blob: f42abc703e6ce613e47837a9107eff7eee78dd09 [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";
henrikg91d6ede2015-09-17 00:24:34 -0700179 RTC_CHECK(o) << "GetObjectField returned NULL";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000180 return o;
181}
182
183jstring GetStringField(JNIEnv* jni, jobject object, jfieldID id) {
184 return static_cast<jstring>(GetObjectField(jni, object, id));
185}
186
187jlong GetLongField(JNIEnv* jni, jobject object, jfieldID id) {
188 jlong l = jni->GetLongField(object, id);
189 CHECK_EXCEPTION(jni) << "error during GetLongField";
190 return l;
191}
192
193jint GetIntField(JNIEnv* jni, jobject object, jfieldID id) {
194 jint i = jni->GetIntField(object, id);
195 CHECK_EXCEPTION(jni) << "error during GetIntField";
196 return i;
197}
198
199bool GetBooleanField(JNIEnv* jni, jobject object, jfieldID id) {
200 jboolean b = jni->GetBooleanField(object, id);
201 CHECK_EXCEPTION(jni) << "error during GetBooleanField";
202 return b;
203}
204
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000205bool IsNull(JNIEnv* jni, jobject obj) {
Magnus Jedvertffdd41e2016-03-01 10:10:01 +0100206 return jni->IsSameObject(obj, nullptr);
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000207}
208
209// Given a UTF-8 encoded |native| string return a new (UTF-16) jstring.
210jstring JavaStringFromStdString(JNIEnv* jni, const std::string& native) {
noahric23725e02015-11-06 13:56:06 -0800211 jstring jstr = jni->NewStringUTF(native.c_str());
212 CHECK_EXCEPTION(jni) << "error during NewStringUTF";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000213 return jstr;
214}
215
216// Given a (UTF-16) jstring return a new UTF-8 native string.
217std::string JavaToStdString(JNIEnv* jni, const jstring& j_string) {
skvlad303b3c22016-03-24 19:36:46 -0700218 const char* chars = jni->GetStringUTFChars(j_string, nullptr);
noahric23725e02015-11-06 13:56:06 -0800219 CHECK_EXCEPTION(jni) << "Error during GetStringUTFChars";
220 std::string str(chars, jni->GetStringUTFLength(j_string));
221 CHECK_EXCEPTION(jni) << "Error during GetStringUTFLength";
222 jni->ReleaseStringUTFChars(j_string, chars);
223 CHECK_EXCEPTION(jni) << "Error during ReleaseStringUTFChars";
224 return str;
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000225}
226
227// Return the (singleton) Java Enum object corresponding to |index|;
228jobject JavaEnumFromIndex(JNIEnv* jni, jclass state_class,
229 const std::string& state_class_name, int index) {
230 jmethodID state_values_id = GetStaticMethodID(
231 jni, state_class, "values", ("()[L" + state_class_name + ";").c_str());
232 jobjectArray state_values = static_cast<jobjectArray>(
233 jni->CallStaticObjectMethod(state_class, state_values_id));
234 CHECK_EXCEPTION(jni) << "error during CallStaticObjectMethod";
235 jobject ret = jni->GetObjectArrayElement(state_values, index);
236 CHECK_EXCEPTION(jni) << "error during GetObjectArrayElement";
237 return ret;
238}
239
honghaizcec0a082016-01-15 14:49:09 -0800240std::string GetJavaEnumName(JNIEnv* jni,
241 const std::string& className,
242 jobject j_enum) {
243 jclass enumClass = FindClass(jni, className.c_str());
244 jmethodID nameMethod =
245 GetMethodID(jni, enumClass, "name", "()Ljava/lang/String;");
246 jstring name =
247 reinterpret_cast<jstring>(jni->CallObjectMethod(j_enum, nameMethod));
248 CHECK_EXCEPTION(jni) << "error during CallObjectMethod for " << className
249 << ".name";
250 return JavaToStdString(jni, name);
251}
252
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000253jobject NewGlobalRef(JNIEnv* jni, jobject o) {
254 jobject ret = jni->NewGlobalRef(o);
255 CHECK_EXCEPTION(jni) << "error during NewGlobalRef";
henrikg91d6ede2015-09-17 00:24:34 -0700256 RTC_CHECK(ret);
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000257 return ret;
258}
259
260void DeleteGlobalRef(JNIEnv* jni, jobject o) {
261 jni->DeleteGlobalRef(o);
262 CHECK_EXCEPTION(jni) << "error during DeleteGlobalRef";
263}
264
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000265// Scope Java local references to the lifetime of this object. Use in all C++
266// callbacks (i.e. entry points that don't originate in a Java callstack
267// through a "native" method call).
268ScopedLocalRefFrame::ScopedLocalRefFrame(JNIEnv* jni) : jni_(jni) {
henrikg91d6ede2015-09-17 00:24:34 -0700269 RTC_CHECK(!jni_->PushLocalFrame(0)) << "Failed to PushLocalFrame";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000270}
271ScopedLocalRefFrame::~ScopedLocalRefFrame() {
skvlad303b3c22016-03-24 19:36:46 -0700272 jni_->PopLocalFrame(nullptr);
273}
274
275// Creates an iterator representing the end of any collection.
276Iterable::Iterator::Iterator() : iterator_(nullptr) {}
277
278// Creates an iterator pointing to the beginning of the specified collection.
279Iterable::Iterator::Iterator(JNIEnv* jni, jobject iterable) : jni_(jni) {
280 jclass j_class = GetObjectClass(jni, iterable);
281 jmethodID iterator_id =
282 GetMethodID(jni, j_class, "iterator", "()Ljava/util/Iterator;");
283 iterator_ = jni->CallObjectMethod(iterable, iterator_id);
284 CHECK_EXCEPTION(jni) << "error during CallObjectMethod";
285 RTC_CHECK(iterator_ != nullptr);
286
287 jclass iterator_class = GetObjectClass(jni, iterator_);
288 has_next_id_ = GetMethodID(jni, iterator_class, "hasNext", "()Z");
289 next_id_ = GetMethodID(jni, iterator_class, "next", "()Ljava/lang/Object;");
290
291 // Start at the first element in the collection.
292 ++(*this);
293}
294
295// Move constructor - necessary to be able to return iterator types from
296// functions.
297Iterable::Iterator::Iterator(Iterator&& other)
298 : jni_(std::move(other.jni_)),
299 iterator_(std::move(other.iterator_)),
300 value_(std::move(other.value_)),
301 has_next_id_(std::move(other.has_next_id_)),
302 next_id_(std::move(other.next_id_)),
303 thread_checker_(std::move(other.thread_checker_)){};
304
305// Advances the iterator one step.
306Iterable::Iterator& Iterable::Iterator::operator++() {
307 RTC_CHECK(thread_checker_.CalledOnValidThread());
308 if (AtEnd()) {
309 // Can't move past the end.
310 return *this;
311 }
312 bool has_next = jni_->CallBooleanMethod(iterator_, has_next_id_);
313 CHECK_EXCEPTION(jni_) << "error during CallBooleanMethod";
314 if (!has_next) {
315 iterator_ = nullptr;
316 value_ = nullptr;
317 return *this;
318 }
319
320 value_ = jni_->CallObjectMethod(iterator_, next_id_);
321 CHECK_EXCEPTION(jni_) << "error during CallObjectMethod";
322 return *this;
323}
324
325// Provides a way to compare the iterator with itself and with the end iterator.
326// Note: all other comparison results are undefined, just like for C++ input
327// iterators.
328bool Iterable::Iterator::operator==(const Iterable::Iterator& other) {
329 // Two different active iterators should never be compared.
330 RTC_DCHECK(this == &other || AtEnd() || other.AtEnd());
331 return AtEnd() == other.AtEnd();
332}
333
334jobject Iterable::Iterator::operator*() {
335 RTC_CHECK(!AtEnd());
336 return value_;
337}
338
339bool Iterable::Iterator::AtEnd() const {
340 RTC_CHECK(thread_checker_.CalledOnValidThread());
341 return jni_ == nullptr || IsNull(jni_, iterator_);
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000342}
343
344} // namespace webrtc_jni