OLD | NEW |
| (Empty) |
1 /* | |
2 * Copyright 2015 The WebRTC project authors. All Rights Reserved. | |
3 * | |
4 * Use of this source code is governed by a BSD-style license | |
5 * that can be found in the LICENSE file in the root of the source | |
6 * tree. An additional intellectual property rights grant can be found | |
7 * in the file PATENTS. All contributing project authors may | |
8 * be found in the AUTHORS file in the root of the source tree. | |
9 */ | |
10 #include "webrtc/api/java/jni/jni_helpers.h" | |
11 | |
12 #include "webrtc/api/java/jni/classreferenceholder.h" | |
13 | |
14 #include <asm/unistd.h> | |
15 #include <sys/prctl.h> | |
16 #include <sys/syscall.h> | |
17 #include <unistd.h> | |
18 | |
19 namespace webrtc_jni { | |
20 | |
21 static JavaVM* g_jvm = nullptr; | |
22 | |
23 static pthread_once_t g_jni_ptr_once = PTHREAD_ONCE_INIT; | |
24 | |
25 // Key for per-thread JNIEnv* data. Non-NULL in threads attached to |g_jvm| by | |
26 // AttachCurrentThreadIfNeeded(), NULL in unattached threads and threads that | |
27 // were attached by the JVM because of a Java->native call. | |
28 static pthread_key_t g_jni_ptr; | |
29 | |
30 JavaVM *GetJVM() { | |
31 RTC_CHECK(g_jvm) << "JNI_OnLoad failed to run?"; | |
32 return g_jvm; | |
33 } | |
34 | |
35 // Return a |JNIEnv*| usable on this thread or NULL if this thread is detached. | |
36 JNIEnv* GetEnv() { | |
37 void* env = nullptr; | |
38 jint status = g_jvm->GetEnv(&env, JNI_VERSION_1_6); | |
39 RTC_CHECK(((env != nullptr) && (status == JNI_OK)) || | |
40 ((env == nullptr) && (status == JNI_EDETACHED))) | |
41 << "Unexpected GetEnv return: " << status << ":" << env; | |
42 return reinterpret_cast<JNIEnv*>(env); | |
43 } | |
44 | |
45 static void ThreadDestructor(void* prev_jni_ptr) { | |
46 // This function only runs on threads where |g_jni_ptr| is non-NULL, meaning | |
47 // we were responsible for originally attaching the thread, so are responsible | |
48 // for detaching it now. However, because some JVM implementations (notably | |
49 // Oracle's http://goo.gl/eHApYT) also use the pthread_key_create mechanism, | |
50 // the JVMs accounting info for this thread may already be wiped out by the | |
51 // time this is called. Thus it may appear we are already detached even though | |
52 // it was our responsibility to detach! Oh well. | |
53 if (!GetEnv()) | |
54 return; | |
55 | |
56 RTC_CHECK(GetEnv() == prev_jni_ptr) | |
57 << "Detaching from another thread: " << prev_jni_ptr << ":" << GetEnv(); | |
58 jint status = g_jvm->DetachCurrentThread(); | |
59 RTC_CHECK(status == JNI_OK) << "Failed to detach thread: " << status; | |
60 RTC_CHECK(!GetEnv()) << "Detaching was a successful no-op???"; | |
61 } | |
62 | |
63 static void CreateJNIPtrKey() { | |
64 RTC_CHECK(!pthread_key_create(&g_jni_ptr, &ThreadDestructor)) | |
65 << "pthread_key_create"; | |
66 } | |
67 | |
68 jint InitGlobalJniVariables(JavaVM *jvm) { | |
69 RTC_CHECK(!g_jvm) << "InitGlobalJniVariables!"; | |
70 g_jvm = jvm; | |
71 RTC_CHECK(g_jvm) << "InitGlobalJniVariables handed NULL?"; | |
72 | |
73 RTC_CHECK(!pthread_once(&g_jni_ptr_once, &CreateJNIPtrKey)) << "pthread_once"; | |
74 | |
75 JNIEnv* jni = nullptr; | |
76 if (jvm->GetEnv(reinterpret_cast<void**>(&jni), JNI_VERSION_1_6) != JNI_OK) | |
77 return -1; | |
78 | |
79 return JNI_VERSION_1_6; | |
80 } | |
81 | |
82 // Return thread ID as a string. | |
83 static std::string GetThreadId() { | |
84 char buf[21]; // Big enough to hold a kuint64max plus terminating NULL. | |
85 RTC_CHECK_LT(snprintf(buf, sizeof(buf), "%ld", | |
86 static_cast<long>(syscall(__NR_gettid))), | |
87 sizeof(buf)) | |
88 << "Thread id is bigger than uint64??"; | |
89 return std::string(buf); | |
90 } | |
91 | |
92 // Return the current thread's name. | |
93 static std::string GetThreadName() { | |
94 char name[17] = {0}; | |
95 if (prctl(PR_GET_NAME, name) != 0) | |
96 return std::string("<noname>"); | |
97 return std::string(name); | |
98 } | |
99 | |
100 // Return a |JNIEnv*| usable on this thread. Attaches to |g_jvm| if necessary. | |
101 JNIEnv* AttachCurrentThreadIfNeeded() { | |
102 JNIEnv* jni = GetEnv(); | |
103 if (jni) | |
104 return jni; | |
105 RTC_CHECK(!pthread_getspecific(g_jni_ptr)) | |
106 << "TLS has a JNIEnv* but not attached?"; | |
107 | |
108 std::string name(GetThreadName() + " - " + GetThreadId()); | |
109 JavaVMAttachArgs args; | |
110 args.version = JNI_VERSION_1_6; | |
111 args.name = &name[0]; | |
112 args.group = nullptr; | |
113 // Deal with difference in signatures between Oracle's jni.h and Android's. | |
114 #ifdef _JAVASOFT_JNI_H_ // Oracle's jni.h violates the JNI spec! | |
115 void* env = nullptr; | |
116 #else | |
117 JNIEnv* env = nullptr; | |
118 #endif | |
119 RTC_CHECK(!g_jvm->AttachCurrentThread(&env, &args)) | |
120 << "Failed to attach thread"; | |
121 RTC_CHECK(env) << "AttachCurrentThread handed back NULL!"; | |
122 jni = reinterpret_cast<JNIEnv*>(env); | |
123 RTC_CHECK(!pthread_setspecific(g_jni_ptr, jni)) << "pthread_setspecific"; | |
124 return jni; | |
125 } | |
126 | |
127 // Return a |jlong| that will correctly convert back to |ptr|. This is needed | |
128 // because the alternative (of silently passing a 32-bit pointer to a vararg | |
129 // function expecting a 64-bit param) picks up garbage in the high 32 bits. | |
130 jlong jlongFromPointer(void* ptr) { | |
131 static_assert(sizeof(intptr_t) <= sizeof(jlong), | |
132 "Time to rethink the use of jlongs"); | |
133 // Going through intptr_t to be obvious about the definedness of the | |
134 // conversion from pointer to integral type. intptr_t to jlong is a standard | |
135 // widening by the static_assert above. | |
136 jlong ret = reinterpret_cast<intptr_t>(ptr); | |
137 RTC_DCHECK(reinterpret_cast<void*>(ret) == ptr); | |
138 return ret; | |
139 } | |
140 | |
141 // JNIEnv-helper methods that RTC_CHECK success: no Java exception thrown and | |
142 // found object/class/method/field is non-null. | |
143 jmethodID GetMethodID( | |
144 JNIEnv* jni, jclass c, const std::string& name, const char* signature) { | |
145 jmethodID m = jni->GetMethodID(c, name.c_str(), signature); | |
146 CHECK_EXCEPTION(jni) << "error during GetMethodID: " << name << ", " | |
147 << signature; | |
148 RTC_CHECK(m) << name << ", " << signature; | |
149 return m; | |
150 } | |
151 | |
152 jmethodID GetStaticMethodID( | |
153 JNIEnv* jni, jclass c, const char* name, const char* signature) { | |
154 jmethodID m = jni->GetStaticMethodID(c, name, signature); | |
155 CHECK_EXCEPTION(jni) << "error during GetStaticMethodID: " << name << ", " | |
156 << signature; | |
157 RTC_CHECK(m) << name << ", " << signature; | |
158 return m; | |
159 } | |
160 | |
161 jfieldID GetFieldID( | |
162 JNIEnv* jni, jclass c, const char* name, const char* signature) { | |
163 jfieldID f = jni->GetFieldID(c, name, signature); | |
164 CHECK_EXCEPTION(jni) << "error during GetFieldID"; | |
165 RTC_CHECK(f) << name << ", " << signature; | |
166 return f; | |
167 } | |
168 | |
169 jclass GetObjectClass(JNIEnv* jni, jobject object) { | |
170 jclass c = jni->GetObjectClass(object); | |
171 CHECK_EXCEPTION(jni) << "error during GetObjectClass"; | |
172 RTC_CHECK(c) << "GetObjectClass returned NULL"; | |
173 return c; | |
174 } | |
175 | |
176 jobject GetObjectField(JNIEnv* jni, jobject object, jfieldID id) { | |
177 jobject o = jni->GetObjectField(object, id); | |
178 CHECK_EXCEPTION(jni) << "error during GetObjectField"; | |
179 RTC_CHECK(!IsNull(jni, o)) << "GetObjectField returned NULL"; | |
180 return o; | |
181 } | |
182 | |
183 jobject GetNullableObjectField(JNIEnv* jni, jobject object, jfieldID id) { | |
184 jobject o = jni->GetObjectField(object, id); | |
185 CHECK_EXCEPTION(jni) << "error during GetObjectField"; | |
186 return o; | |
187 } | |
188 | |
189 jstring GetStringField(JNIEnv* jni, jobject object, jfieldID id) { | |
190 return static_cast<jstring>(GetObjectField(jni, object, id)); | |
191 } | |
192 | |
193 jlong GetLongField(JNIEnv* jni, jobject object, jfieldID id) { | |
194 jlong l = jni->GetLongField(object, id); | |
195 CHECK_EXCEPTION(jni) << "error during GetLongField"; | |
196 return l; | |
197 } | |
198 | |
199 jint GetIntField(JNIEnv* jni, jobject object, jfieldID id) { | |
200 jint i = jni->GetIntField(object, id); | |
201 CHECK_EXCEPTION(jni) << "error during GetIntField"; | |
202 return i; | |
203 } | |
204 | |
205 bool GetBooleanField(JNIEnv* jni, jobject object, jfieldID id) { | |
206 jboolean b = jni->GetBooleanField(object, id); | |
207 CHECK_EXCEPTION(jni) << "error during GetBooleanField"; | |
208 return b; | |
209 } | |
210 | |
211 bool IsNull(JNIEnv* jni, jobject obj) { | |
212 return jni->IsSameObject(obj, nullptr); | |
213 } | |
214 | |
215 // Given a UTF-8 encoded |native| string return a new (UTF-16) jstring. | |
216 jstring JavaStringFromStdString(JNIEnv* jni, const std::string& native) { | |
217 jstring jstr = jni->NewStringUTF(native.c_str()); | |
218 CHECK_EXCEPTION(jni) << "error during NewStringUTF"; | |
219 return jstr; | |
220 } | |
221 | |
222 // Given a (UTF-16) jstring return a new UTF-8 native string. | |
223 std::string JavaToStdString(JNIEnv* jni, const jstring& j_string) { | |
224 const char* chars = jni->GetStringUTFChars(j_string, nullptr); | |
225 CHECK_EXCEPTION(jni) << "Error during GetStringUTFChars"; | |
226 std::string str(chars, jni->GetStringUTFLength(j_string)); | |
227 CHECK_EXCEPTION(jni) << "Error during GetStringUTFLength"; | |
228 jni->ReleaseStringUTFChars(j_string, chars); | |
229 CHECK_EXCEPTION(jni) << "Error during ReleaseStringUTFChars"; | |
230 return str; | |
231 } | |
232 | |
233 // Return the (singleton) Java Enum object corresponding to |index|; | |
234 jobject JavaEnumFromIndex(JNIEnv* jni, jclass state_class, | |
235 const std::string& state_class_name, int index) { | |
236 jmethodID state_values_id = GetStaticMethodID( | |
237 jni, state_class, "values", ("()[L" + state_class_name + ";").c_str()); | |
238 jobjectArray state_values = static_cast<jobjectArray>( | |
239 jni->CallStaticObjectMethod(state_class, state_values_id)); | |
240 CHECK_EXCEPTION(jni) << "error during CallStaticObjectMethod"; | |
241 jobject ret = jni->GetObjectArrayElement(state_values, index); | |
242 CHECK_EXCEPTION(jni) << "error during GetObjectArrayElement"; | |
243 return ret; | |
244 } | |
245 | |
246 std::string GetJavaEnumName(JNIEnv* jni, | |
247 const std::string& className, | |
248 jobject j_enum) { | |
249 jclass enumClass = FindClass(jni, className.c_str()); | |
250 jmethodID nameMethod = | |
251 GetMethodID(jni, enumClass, "name", "()Ljava/lang/String;"); | |
252 jstring name = | |
253 reinterpret_cast<jstring>(jni->CallObjectMethod(j_enum, nameMethod)); | |
254 CHECK_EXCEPTION(jni) << "error during CallObjectMethod for " << className | |
255 << ".name"; | |
256 return JavaToStdString(jni, name); | |
257 } | |
258 | |
259 jobject NewGlobalRef(JNIEnv* jni, jobject o) { | |
260 jobject ret = jni->NewGlobalRef(o); | |
261 CHECK_EXCEPTION(jni) << "error during NewGlobalRef"; | |
262 RTC_CHECK(ret); | |
263 return ret; | |
264 } | |
265 | |
266 void DeleteGlobalRef(JNIEnv* jni, jobject o) { | |
267 jni->DeleteGlobalRef(o); | |
268 CHECK_EXCEPTION(jni) << "error during DeleteGlobalRef"; | |
269 } | |
270 | |
271 // Scope Java local references to the lifetime of this object. Use in all C++ | |
272 // callbacks (i.e. entry points that don't originate in a Java callstack | |
273 // through a "native" method call). | |
274 ScopedLocalRefFrame::ScopedLocalRefFrame(JNIEnv* jni) : jni_(jni) { | |
275 RTC_CHECK(!jni_->PushLocalFrame(0)) << "Failed to PushLocalFrame"; | |
276 } | |
277 ScopedLocalRefFrame::~ScopedLocalRefFrame() { | |
278 jni_->PopLocalFrame(nullptr); | |
279 } | |
280 | |
281 // Creates an iterator representing the end of any collection. | |
282 Iterable::Iterator::Iterator() : iterator_(nullptr) {} | |
283 | |
284 // Creates an iterator pointing to the beginning of the specified collection. | |
285 Iterable::Iterator::Iterator(JNIEnv* jni, jobject iterable) : jni_(jni) { | |
286 jclass j_class = GetObjectClass(jni, iterable); | |
287 jmethodID iterator_id = | |
288 GetMethodID(jni, j_class, "iterator", "()Ljava/util/Iterator;"); | |
289 iterator_ = jni->CallObjectMethod(iterable, iterator_id); | |
290 CHECK_EXCEPTION(jni) << "error during CallObjectMethod"; | |
291 RTC_CHECK(iterator_ != nullptr); | |
292 | |
293 jclass iterator_class = GetObjectClass(jni, iterator_); | |
294 has_next_id_ = GetMethodID(jni, iterator_class, "hasNext", "()Z"); | |
295 next_id_ = GetMethodID(jni, iterator_class, "next", "()Ljava/lang/Object;"); | |
296 | |
297 // Start at the first element in the collection. | |
298 ++(*this); | |
299 } | |
300 | |
301 // Move constructor - necessary to be able to return iterator types from | |
302 // functions. | |
303 Iterable::Iterator::Iterator(Iterator&& other) | |
304 : jni_(std::move(other.jni_)), | |
305 iterator_(std::move(other.iterator_)), | |
306 value_(std::move(other.value_)), | |
307 has_next_id_(std::move(other.has_next_id_)), | |
308 next_id_(std::move(other.next_id_)), | |
309 thread_checker_(std::move(other.thread_checker_)){}; | |
310 | |
311 // Advances the iterator one step. | |
312 Iterable::Iterator& Iterable::Iterator::operator++() { | |
313 RTC_CHECK(thread_checker_.CalledOnValidThread()); | |
314 if (AtEnd()) { | |
315 // Can't move past the end. | |
316 return *this; | |
317 } | |
318 bool has_next = jni_->CallBooleanMethod(iterator_, has_next_id_); | |
319 CHECK_EXCEPTION(jni_) << "error during CallBooleanMethod"; | |
320 if (!has_next) { | |
321 iterator_ = nullptr; | |
322 value_ = nullptr; | |
323 return *this; | |
324 } | |
325 | |
326 value_ = jni_->CallObjectMethod(iterator_, next_id_); | |
327 CHECK_EXCEPTION(jni_) << "error during CallObjectMethod"; | |
328 return *this; | |
329 } | |
330 | |
331 // Provides a way to compare the iterator with itself and with the end iterator. | |
332 // Note: all other comparison results are undefined, just like for C++ input | |
333 // iterators. | |
334 bool Iterable::Iterator::operator==(const Iterable::Iterator& other) { | |
335 // Two different active iterators should never be compared. | |
336 RTC_DCHECK(this == &other || AtEnd() || other.AtEnd()); | |
337 return AtEnd() == other.AtEnd(); | |
338 } | |
339 | |
340 jobject Iterable::Iterator::operator*() { | |
341 RTC_CHECK(!AtEnd()); | |
342 return value_; | |
343 } | |
344 | |
345 bool Iterable::Iterator::AtEnd() const { | |
346 RTC_CHECK(thread_checker_.CalledOnValidThread()); | |
347 return jni_ == nullptr || IsNull(jni_, iterator_); | |
348 } | |
349 | |
350 } // namespace webrtc_jni | |
OLD | NEW |