blob: 052dcf9a8960b255af8950a89d9434650328d8a4 [file] [log] [blame]
perkj@webrtc.org96e4db92015-02-13 12:46:51 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2015 The WebRTC project authors. All Rights Reserved.
perkj@webrtc.org96e4db92015-02-13 12:46:51 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * 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.
perkj@webrtc.org96e4db92015-02-13 12:46:51 +00009 */
Henrik Kjellander15583c12016-02-10 10:53:12 +010010#include "webrtc/api/java/jni/jni_helpers.h"
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000011
Henrik Kjellander15583c12016-02-10 10:53:12 +010012#include "webrtc/api/java/jni/classreferenceholder.h"
honghaizcec0a082016-01-15 14:49:09 -080013
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000014#include <asm/unistd.h>
15#include <sys/prctl.h>
16#include <sys/syscall.h>
17#include <unistd.h>
18
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000019namespace webrtc_jni {
20
21static JavaVM* g_jvm = nullptr;
22
23static 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.
28static pthread_key_t g_jni_ptr;
29
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000030JavaVM *GetJVM() {
henrikg91d6ede2015-09-17 00:24:34 -070031 RTC_CHECK(g_jvm) << "JNI_OnLoad failed to run?";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000032 return g_jvm;
33}
34
35// Return a |JNIEnv*| usable on this thread or NULL if this thread is detached.
36JNIEnv* GetEnv() {
skvlad303b3c22016-03-24 19:36:46 -070037 void* env = nullptr;
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000038 jint status = g_jvm->GetEnv(&env, JNI_VERSION_1_6);
skvlad303b3c22016-03-24 19:36:46 -070039 RTC_CHECK(((env != nullptr) && (status == JNI_OK)) ||
40 ((env == nullptr) && (status == JNI_EDETACHED)))
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000041 << "Unexpected GetEnv return: " << status << ":" << env;
42 return reinterpret_cast<JNIEnv*>(env);
43}
44
45static 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
henrikg91d6ede2015-09-17 00:24:34 -070056 RTC_CHECK(GetEnv() == prev_jni_ptr)
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000057 << "Detaching from another thread: " << prev_jni_ptr << ":" << GetEnv();
58 jint status = g_jvm->DetachCurrentThread();
henrikg91d6ede2015-09-17 00:24:34 -070059 RTC_CHECK(status == JNI_OK) << "Failed to detach thread: " << status;
60 RTC_CHECK(!GetEnv()) << "Detaching was a successful no-op???";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000061}
62
63static void CreateJNIPtrKey() {
henrikg91d6ede2015-09-17 00:24:34 -070064 RTC_CHECK(!pthread_key_create(&g_jni_ptr, &ThreadDestructor))
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000065 << "pthread_key_create";
66}
67
68jint InitGlobalJniVariables(JavaVM *jvm) {
henrikg91d6ede2015-09-17 00:24:34 -070069 RTC_CHECK(!g_jvm) << "InitGlobalJniVariables!";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000070 g_jvm = jvm;
henrikg91d6ede2015-09-17 00:24:34 -070071 RTC_CHECK(g_jvm) << "InitGlobalJniVariables handed NULL?";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000072
henrikg91d6ede2015-09-17 00:24:34 -070073 RTC_CHECK(!pthread_once(&g_jni_ptr_once, &CreateJNIPtrKey)) << "pthread_once";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000074
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.
83static std::string GetThreadId() {
84 char buf[21]; // Big enough to hold a kuint64max plus terminating NULL.
henrikg91d6ede2015-09-17 00:24:34 -070085 RTC_CHECK_LT(snprintf(buf, sizeof(buf), "%ld",
86 static_cast<long>(syscall(__NR_gettid))),
87 sizeof(buf))
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000088 << "Thread id is bigger than uint64??";
89 return std::string(buf);
90}
91
92// Return the current thread's name.
93static std::string GetThreadName() {
Tommia9952cd2015-06-03 18:59:11 +020094 char name[17] = {0};
95 if (prctl(PR_GET_NAME, name) != 0)
96 return std::string("<noname>");
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000097 return std::string(name);
98}
99
100// Return a |JNIEnv*| usable on this thread. Attaches to |g_jvm| if necessary.
101JNIEnv* AttachCurrentThreadIfNeeded() {
102 JNIEnv* jni = GetEnv();
103 if (jni)
104 return jni;
henrikg91d6ede2015-09-17 00:24:34 -0700105 RTC_CHECK(!pthread_getspecific(g_jni_ptr))
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000106 << "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];
skvlad303b3c22016-03-24 19:36:46 -0700112 args.group = nullptr;
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000113 // 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!
skvlad303b3c22016-03-24 19:36:46 -0700115 void* env = nullptr;
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000116#else
skvlad303b3c22016-03-24 19:36:46 -0700117 JNIEnv* env = nullptr;
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000118#endif
henrikg91d6ede2015-09-17 00:24:34 -0700119 RTC_CHECK(!g_jvm->AttachCurrentThread(&env, &args))
120 << "Failed to attach thread";
121 RTC_CHECK(env) << "AttachCurrentThread handed back NULL!";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000122 jni = reinterpret_cast<JNIEnv*>(env);
henrikg91d6ede2015-09-17 00:24:34 -0700123 RTC_CHECK(!pthread_setspecific(g_jni_ptr, jni)) << "pthread_setspecific";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000124 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.
130jlong 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);
henrikg91d6ede2015-09-17 00:24:34 -0700137 RTC_DCHECK(reinterpret_cast<void*>(ret) == ptr);
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000138 return ret;
139}
140
henrikg91d6ede2015-09-17 00:24:34 -0700141// JNIEnv-helper methods that RTC_CHECK success: no Java exception thrown and
142// found object/class/method/field is non-null.
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000143jmethodID 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;
henrikg91d6ede2015-09-17 00:24:34 -0700148 RTC_CHECK(m) << name << ", " << signature;
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000149 return m;
150}
151
152jmethodID 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;
henrikg91d6ede2015-09-17 00:24:34 -0700157 RTC_CHECK(m) << name << ", " << signature;
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000158 return m;
159}
160
161jfieldID 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";
henrikg91d6ede2015-09-17 00:24:34 -0700165 RTC_CHECK(f) << name << ", " << signature;
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000166 return f;
167}
168
169jclass GetObjectClass(JNIEnv* jni, jobject object) {
170 jclass c = jni->GetObjectClass(object);
171 CHECK_EXCEPTION(jni) << "error during GetObjectClass";
henrikg91d6ede2015-09-17 00:24:34 -0700172 RTC_CHECK(c) << "GetObjectClass returned NULL";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000173 return c;
174}
175
176jobject GetObjectField(JNIEnv* jni, jobject object, jfieldID id) {
177 jobject o = jni->GetObjectField(object, id);
178 CHECK_EXCEPTION(jni) << "error during GetObjectField";
deadbeef60631772016-04-04 10:21:02 -0700179 RTC_CHECK(!IsNull(jni, o)) << "GetObjectField returned NULL";
180 return o;
181}
182
183jobject GetNullableObjectField(JNIEnv* jni, jobject object, jfieldID id) {
184 jobject o = jni->GetObjectField(object, id);
185 CHECK_EXCEPTION(jni) << "error during GetObjectField";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000186 return o;
187}
188
189jstring GetStringField(JNIEnv* jni, jobject object, jfieldID id) {
190 return static_cast<jstring>(GetObjectField(jni, object, id));
191}
192
193jlong 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
199jint 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
205bool 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
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000211bool IsNull(JNIEnv* jni, jobject obj) {
Magnus Jedvertffdd41e2016-03-01 10:10:01 +0100212 return jni->IsSameObject(obj, nullptr);
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000213}
214
215// Given a UTF-8 encoded |native| string return a new (UTF-16) jstring.
216jstring JavaStringFromStdString(JNIEnv* jni, const std::string& native) {
noahric23725e02015-11-06 13:56:06 -0800217 jstring jstr = jni->NewStringUTF(native.c_str());
218 CHECK_EXCEPTION(jni) << "error during NewStringUTF";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000219 return jstr;
220}
221
222// Given a (UTF-16) jstring return a new UTF-8 native string.
223std::string JavaToStdString(JNIEnv* jni, const jstring& j_string) {
skvlad303b3c22016-03-24 19:36:46 -0700224 const char* chars = jni->GetStringUTFChars(j_string, nullptr);
noahric23725e02015-11-06 13:56:06 -0800225 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;
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000231}
232
233// Return the (singleton) Java Enum object corresponding to |index|;
234jobject 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
honghaizcec0a082016-01-15 14:49:09 -0800246std::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
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000259jobject NewGlobalRef(JNIEnv* jni, jobject o) {
260 jobject ret = jni->NewGlobalRef(o);
261 CHECK_EXCEPTION(jni) << "error during NewGlobalRef";
henrikg91d6ede2015-09-17 00:24:34 -0700262 RTC_CHECK(ret);
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000263 return ret;
264}
265
266void DeleteGlobalRef(JNIEnv* jni, jobject o) {
267 jni->DeleteGlobalRef(o);
268 CHECK_EXCEPTION(jni) << "error during DeleteGlobalRef";
269}
270
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000271// 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).
274ScopedLocalRefFrame::ScopedLocalRefFrame(JNIEnv* jni) : jni_(jni) {
henrikg91d6ede2015-09-17 00:24:34 -0700275 RTC_CHECK(!jni_->PushLocalFrame(0)) << "Failed to PushLocalFrame";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000276}
277ScopedLocalRefFrame::~ScopedLocalRefFrame() {
skvlad303b3c22016-03-24 19:36:46 -0700278 jni_->PopLocalFrame(nullptr);
279}
280
281// Creates an iterator representing the end of any collection.
282Iterable::Iterator::Iterator() : iterator_(nullptr) {}
283
284// Creates an iterator pointing to the beginning of the specified collection.
285Iterable::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.
303Iterable::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.
312Iterable::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.
334bool 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
340jobject Iterable::Iterator::operator*() {
341 RTC_CHECK(!AtEnd());
342 return value_;
343}
344
345bool Iterable::Iterator::AtEnd() const {
346 RTC_CHECK(thread_checker_.CalledOnValidThread());
347 return jni_ == nullptr || IsNull(jni_, iterator_);
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000348}
349
350} // namespace webrtc_jni