OLD | NEW |
| (Empty) |
1 /* | |
2 * libjingle | |
3 * Copyright 2015 Google Inc. | |
4 * | |
5 * Redistribution and use in source and binary forms, with or without | |
6 * modification, are permitted provided that the following conditions are met: | |
7 * | |
8 * 1. Redistributions of source code must retain the above copyright notice, | |
9 * this list of conditions and the following disclaimer. | |
10 * 2. Redistributions in binary form must reproduce the above copyright notice, | |
11 * this list of conditions and the following disclaimer in the documentation | |
12 * and/or other materials provided with the distribution. | |
13 * 3. The name of the author may not be used to endorse or promote products | |
14 * derived from this software without specific prior written permission. | |
15 * | |
16 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED | |
17 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF | |
18 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO | |
19 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, | |
20 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, | |
21 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; | |
22 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, | |
23 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR | |
24 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF | |
25 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. | |
26 * | |
27 */ | |
28 #include "talk/app/webrtc/java/jni/jni_helpers.h" | |
29 | |
30 #include "talk/app/webrtc/java/jni/classreferenceholder.h" | |
31 | |
32 #include <asm/unistd.h> | |
33 #include <sys/prctl.h> | |
34 #include <sys/syscall.h> | |
35 #include <unistd.h> | |
36 | |
37 namespace webrtc_jni { | |
38 | |
39 static JavaVM* g_jvm = nullptr; | |
40 | |
41 static pthread_once_t g_jni_ptr_once = PTHREAD_ONCE_INIT; | |
42 | |
43 // Key for per-thread JNIEnv* data. Non-NULL in threads attached to |g_jvm| by | |
44 // AttachCurrentThreadIfNeeded(), NULL in unattached threads and threads that | |
45 // were attached by the JVM because of a Java->native call. | |
46 static pthread_key_t g_jni_ptr; | |
47 | |
48 JavaVM *GetJVM() { | |
49 RTC_CHECK(g_jvm) << "JNI_OnLoad failed to run?"; | |
50 return g_jvm; | |
51 } | |
52 | |
53 // Return a |JNIEnv*| usable on this thread or NULL if this thread is detached. | |
54 JNIEnv* GetEnv() { | |
55 void* env = NULL; | |
56 jint status = g_jvm->GetEnv(&env, JNI_VERSION_1_6); | |
57 RTC_CHECK(((env != NULL) && (status == JNI_OK)) || | |
58 ((env == NULL) && (status == JNI_EDETACHED))) | |
59 << "Unexpected GetEnv return: " << status << ":" << env; | |
60 return reinterpret_cast<JNIEnv*>(env); | |
61 } | |
62 | |
63 static void ThreadDestructor(void* prev_jni_ptr) { | |
64 // This function only runs on threads where |g_jni_ptr| is non-NULL, meaning | |
65 // we were responsible for originally attaching the thread, so are responsible | |
66 // for detaching it now. However, because some JVM implementations (notably | |
67 // Oracle's http://goo.gl/eHApYT) also use the pthread_key_create mechanism, | |
68 // the JVMs accounting info for this thread may already be wiped out by the | |
69 // time this is called. Thus it may appear we are already detached even though | |
70 // it was our responsibility to detach! Oh well. | |
71 if (!GetEnv()) | |
72 return; | |
73 | |
74 RTC_CHECK(GetEnv() == prev_jni_ptr) | |
75 << "Detaching from another thread: " << prev_jni_ptr << ":" << GetEnv(); | |
76 jint status = g_jvm->DetachCurrentThread(); | |
77 RTC_CHECK(status == JNI_OK) << "Failed to detach thread: " << status; | |
78 RTC_CHECK(!GetEnv()) << "Detaching was a successful no-op???"; | |
79 } | |
80 | |
81 static void CreateJNIPtrKey() { | |
82 RTC_CHECK(!pthread_key_create(&g_jni_ptr, &ThreadDestructor)) | |
83 << "pthread_key_create"; | |
84 } | |
85 | |
86 jint InitGlobalJniVariables(JavaVM *jvm) { | |
87 RTC_CHECK(!g_jvm) << "InitGlobalJniVariables!"; | |
88 g_jvm = jvm; | |
89 RTC_CHECK(g_jvm) << "InitGlobalJniVariables handed NULL?"; | |
90 | |
91 RTC_CHECK(!pthread_once(&g_jni_ptr_once, &CreateJNIPtrKey)) << "pthread_once"; | |
92 | |
93 JNIEnv* jni = nullptr; | |
94 if (jvm->GetEnv(reinterpret_cast<void**>(&jni), JNI_VERSION_1_6) != JNI_OK) | |
95 return -1; | |
96 | |
97 return JNI_VERSION_1_6; | |
98 } | |
99 | |
100 // Return thread ID as a string. | |
101 static std::string GetThreadId() { | |
102 char buf[21]; // Big enough to hold a kuint64max plus terminating NULL. | |
103 RTC_CHECK_LT(snprintf(buf, sizeof(buf), "%ld", | |
104 static_cast<long>(syscall(__NR_gettid))), | |
105 sizeof(buf)) | |
106 << "Thread id is bigger than uint64??"; | |
107 return std::string(buf); | |
108 } | |
109 | |
110 // Return the current thread's name. | |
111 static std::string GetThreadName() { | |
112 char name[17] = {0}; | |
113 if (prctl(PR_GET_NAME, name) != 0) | |
114 return std::string("<noname>"); | |
115 return std::string(name); | |
116 } | |
117 | |
118 // Return a |JNIEnv*| usable on this thread. Attaches to |g_jvm| if necessary. | |
119 JNIEnv* AttachCurrentThreadIfNeeded() { | |
120 JNIEnv* jni = GetEnv(); | |
121 if (jni) | |
122 return jni; | |
123 RTC_CHECK(!pthread_getspecific(g_jni_ptr)) | |
124 << "TLS has a JNIEnv* but not attached?"; | |
125 | |
126 std::string name(GetThreadName() + " - " + GetThreadId()); | |
127 JavaVMAttachArgs args; | |
128 args.version = JNI_VERSION_1_6; | |
129 args.name = &name[0]; | |
130 args.group = NULL; | |
131 // Deal with difference in signatures between Oracle's jni.h and Android's. | |
132 #ifdef _JAVASOFT_JNI_H_ // Oracle's jni.h violates the JNI spec! | |
133 void* env = NULL; | |
134 #else | |
135 JNIEnv* env = NULL; | |
136 #endif | |
137 RTC_CHECK(!g_jvm->AttachCurrentThread(&env, &args)) | |
138 << "Failed to attach thread"; | |
139 RTC_CHECK(env) << "AttachCurrentThread handed back NULL!"; | |
140 jni = reinterpret_cast<JNIEnv*>(env); | |
141 RTC_CHECK(!pthread_setspecific(g_jni_ptr, jni)) << "pthread_setspecific"; | |
142 return jni; | |
143 } | |
144 | |
145 // Return a |jlong| that will correctly convert back to |ptr|. This is needed | |
146 // because the alternative (of silently passing a 32-bit pointer to a vararg | |
147 // function expecting a 64-bit param) picks up garbage in the high 32 bits. | |
148 jlong jlongFromPointer(void* ptr) { | |
149 static_assert(sizeof(intptr_t) <= sizeof(jlong), | |
150 "Time to rethink the use of jlongs"); | |
151 // Going through intptr_t to be obvious about the definedness of the | |
152 // conversion from pointer to integral type. intptr_t to jlong is a standard | |
153 // widening by the static_assert above. | |
154 jlong ret = reinterpret_cast<intptr_t>(ptr); | |
155 RTC_DCHECK(reinterpret_cast<void*>(ret) == ptr); | |
156 return ret; | |
157 } | |
158 | |
159 // JNIEnv-helper methods that RTC_CHECK success: no Java exception thrown and | |
160 // found object/class/method/field is non-null. | |
161 jmethodID GetMethodID( | |
162 JNIEnv* jni, jclass c, const std::string& name, const char* signature) { | |
163 jmethodID m = jni->GetMethodID(c, name.c_str(), signature); | |
164 CHECK_EXCEPTION(jni) << "error during GetMethodID: " << name << ", " | |
165 << signature; | |
166 RTC_CHECK(m) << name << ", " << signature; | |
167 return m; | |
168 } | |
169 | |
170 jmethodID GetStaticMethodID( | |
171 JNIEnv* jni, jclass c, const char* name, const char* signature) { | |
172 jmethodID m = jni->GetStaticMethodID(c, name, signature); | |
173 CHECK_EXCEPTION(jni) << "error during GetStaticMethodID: " << name << ", " | |
174 << signature; | |
175 RTC_CHECK(m) << name << ", " << signature; | |
176 return m; | |
177 } | |
178 | |
179 jfieldID GetFieldID( | |
180 JNIEnv* jni, jclass c, const char* name, const char* signature) { | |
181 jfieldID f = jni->GetFieldID(c, name, signature); | |
182 CHECK_EXCEPTION(jni) << "error during GetFieldID"; | |
183 RTC_CHECK(f) << name << ", " << signature; | |
184 return f; | |
185 } | |
186 | |
187 jclass GetObjectClass(JNIEnv* jni, jobject object) { | |
188 jclass c = jni->GetObjectClass(object); | |
189 CHECK_EXCEPTION(jni) << "error during GetObjectClass"; | |
190 RTC_CHECK(c) << "GetObjectClass returned NULL"; | |
191 return c; | |
192 } | |
193 | |
194 jobject GetObjectField(JNIEnv* jni, jobject object, jfieldID id) { | |
195 jobject o = jni->GetObjectField(object, id); | |
196 CHECK_EXCEPTION(jni) << "error during GetObjectField"; | |
197 RTC_CHECK(o) << "GetObjectField returned NULL"; | |
198 return o; | |
199 } | |
200 | |
201 jstring GetStringField(JNIEnv* jni, jobject object, jfieldID id) { | |
202 return static_cast<jstring>(GetObjectField(jni, object, id)); | |
203 } | |
204 | |
205 jlong GetLongField(JNIEnv* jni, jobject object, jfieldID id) { | |
206 jlong l = jni->GetLongField(object, id); | |
207 CHECK_EXCEPTION(jni) << "error during GetLongField"; | |
208 return l; | |
209 } | |
210 | |
211 jint GetIntField(JNIEnv* jni, jobject object, jfieldID id) { | |
212 jint i = jni->GetIntField(object, id); | |
213 CHECK_EXCEPTION(jni) << "error during GetIntField"; | |
214 return i; | |
215 } | |
216 | |
217 bool GetBooleanField(JNIEnv* jni, jobject object, jfieldID id) { | |
218 jboolean b = jni->GetBooleanField(object, id); | |
219 CHECK_EXCEPTION(jni) << "error during GetBooleanField"; | |
220 return b; | |
221 } | |
222 | |
223 // Java references to "null" can only be distinguished as such in C++ by | |
224 // creating a local reference, so this helper wraps that logic. | |
225 bool IsNull(JNIEnv* jni, jobject obj) { | |
226 ScopedLocalRefFrame local_ref_frame(jni); | |
227 return jni->NewLocalRef(obj) == NULL; | |
228 } | |
229 | |
230 // Given a UTF-8 encoded |native| string return a new (UTF-16) jstring. | |
231 jstring JavaStringFromStdString(JNIEnv* jni, const std::string& native) { | |
232 jstring jstr = jni->NewStringUTF(native.c_str()); | |
233 CHECK_EXCEPTION(jni) << "error during NewStringUTF"; | |
234 return jstr; | |
235 } | |
236 | |
237 // Given a (UTF-16) jstring return a new UTF-8 native string. | |
238 std::string JavaToStdString(JNIEnv* jni, const jstring& j_string) { | |
239 const char* chars = jni->GetStringUTFChars(j_string, NULL); | |
240 CHECK_EXCEPTION(jni) << "Error during GetStringUTFChars"; | |
241 std::string str(chars, jni->GetStringUTFLength(j_string)); | |
242 CHECK_EXCEPTION(jni) << "Error during GetStringUTFLength"; | |
243 jni->ReleaseStringUTFChars(j_string, chars); | |
244 CHECK_EXCEPTION(jni) << "Error during ReleaseStringUTFChars"; | |
245 return str; | |
246 } | |
247 | |
248 // Return the (singleton) Java Enum object corresponding to |index|; | |
249 jobject JavaEnumFromIndex(JNIEnv* jni, jclass state_class, | |
250 const std::string& state_class_name, int index) { | |
251 jmethodID state_values_id = GetStaticMethodID( | |
252 jni, state_class, "values", ("()[L" + state_class_name + ";").c_str()); | |
253 jobjectArray state_values = static_cast<jobjectArray>( | |
254 jni->CallStaticObjectMethod(state_class, state_values_id)); | |
255 CHECK_EXCEPTION(jni) << "error during CallStaticObjectMethod"; | |
256 jobject ret = jni->GetObjectArrayElement(state_values, index); | |
257 CHECK_EXCEPTION(jni) << "error during GetObjectArrayElement"; | |
258 return ret; | |
259 } | |
260 | |
261 std::string GetJavaEnumName(JNIEnv* jni, | |
262 const std::string& className, | |
263 jobject j_enum) { | |
264 jclass enumClass = FindClass(jni, className.c_str()); | |
265 jmethodID nameMethod = | |
266 GetMethodID(jni, enumClass, "name", "()Ljava/lang/String;"); | |
267 jstring name = | |
268 reinterpret_cast<jstring>(jni->CallObjectMethod(j_enum, nameMethod)); | |
269 CHECK_EXCEPTION(jni) << "error during CallObjectMethod for " << className | |
270 << ".name"; | |
271 return JavaToStdString(jni, name); | |
272 } | |
273 | |
274 jobject NewGlobalRef(JNIEnv* jni, jobject o) { | |
275 jobject ret = jni->NewGlobalRef(o); | |
276 CHECK_EXCEPTION(jni) << "error during NewGlobalRef"; | |
277 RTC_CHECK(ret); | |
278 return ret; | |
279 } | |
280 | |
281 void DeleteGlobalRef(JNIEnv* jni, jobject o) { | |
282 jni->DeleteGlobalRef(o); | |
283 CHECK_EXCEPTION(jni) << "error during DeleteGlobalRef"; | |
284 } | |
285 | |
286 // Scope Java local references to the lifetime of this object. Use in all C++ | |
287 // callbacks (i.e. entry points that don't originate in a Java callstack | |
288 // through a "native" method call). | |
289 ScopedLocalRefFrame::ScopedLocalRefFrame(JNIEnv* jni) : jni_(jni) { | |
290 RTC_CHECK(!jni_->PushLocalFrame(0)) << "Failed to PushLocalFrame"; | |
291 } | |
292 ScopedLocalRefFrame::~ScopedLocalRefFrame() { | |
293 jni_->PopLocalFrame(NULL); | |
294 } | |
295 | |
296 } // namespace webrtc_jni | |
OLD | NEW |