blob: cd150142a13d0772b3040d0bde7509a5f8976a23 [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() {
37 void* env = NULL;
38 jint status = g_jvm->GetEnv(&env, JNI_VERSION_1_6);
henrikg91d6ede2015-09-17 00:24:34 -070039 RTC_CHECK(((env != NULL) && (status == JNI_OK)) ||
40 ((env == NULL) && (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];
112 args.group = NULL;
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 = NULL;
116#else
117 JNIEnv* env = NULL;
118#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
205// Java references to "null" can only be distinguished as such in C++ by
206// creating a local reference, so this helper wraps that logic.
207bool IsNull(JNIEnv* jni, jobject obj) {
208 ScopedLocalRefFrame local_ref_frame(jni);
209 return jni->NewLocalRef(obj) == NULL;
210}
211
212// Given a UTF-8 encoded |native| string return a new (UTF-16) jstring.
213jstring JavaStringFromStdString(JNIEnv* jni, const std::string& native) {
noahric23725e02015-11-06 13:56:06 -0800214 jstring jstr = jni->NewStringUTF(native.c_str());
215 CHECK_EXCEPTION(jni) << "error during NewStringUTF";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000216 return jstr;
217}
218
219// Given a (UTF-16) jstring return a new UTF-8 native string.
220std::string JavaToStdString(JNIEnv* jni, const jstring& j_string) {
noahric23725e02015-11-06 13:56:06 -0800221 const char* chars = jni->GetStringUTFChars(j_string, NULL);
222 CHECK_EXCEPTION(jni) << "Error during GetStringUTFChars";
223 std::string str(chars, jni->GetStringUTFLength(j_string));
224 CHECK_EXCEPTION(jni) << "Error during GetStringUTFLength";
225 jni->ReleaseStringUTFChars(j_string, chars);
226 CHECK_EXCEPTION(jni) << "Error during ReleaseStringUTFChars";
227 return str;
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000228}
229
230// Return the (singleton) Java Enum object corresponding to |index|;
231jobject JavaEnumFromIndex(JNIEnv* jni, jclass state_class,
232 const std::string& state_class_name, int index) {
233 jmethodID state_values_id = GetStaticMethodID(
234 jni, state_class, "values", ("()[L" + state_class_name + ";").c_str());
235 jobjectArray state_values = static_cast<jobjectArray>(
236 jni->CallStaticObjectMethod(state_class, state_values_id));
237 CHECK_EXCEPTION(jni) << "error during CallStaticObjectMethod";
238 jobject ret = jni->GetObjectArrayElement(state_values, index);
239 CHECK_EXCEPTION(jni) << "error during GetObjectArrayElement";
240 return ret;
241}
242
honghaizcec0a082016-01-15 14:49:09 -0800243std::string GetJavaEnumName(JNIEnv* jni,
244 const std::string& className,
245 jobject j_enum) {
246 jclass enumClass = FindClass(jni, className.c_str());
247 jmethodID nameMethod =
248 GetMethodID(jni, enumClass, "name", "()Ljava/lang/String;");
249 jstring name =
250 reinterpret_cast<jstring>(jni->CallObjectMethod(j_enum, nameMethod));
251 CHECK_EXCEPTION(jni) << "error during CallObjectMethod for " << className
252 << ".name";
253 return JavaToStdString(jni, name);
254}
255
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000256jobject NewGlobalRef(JNIEnv* jni, jobject o) {
257 jobject ret = jni->NewGlobalRef(o);
258 CHECK_EXCEPTION(jni) << "error during NewGlobalRef";
henrikg91d6ede2015-09-17 00:24:34 -0700259 RTC_CHECK(ret);
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000260 return ret;
261}
262
263void DeleteGlobalRef(JNIEnv* jni, jobject o) {
264 jni->DeleteGlobalRef(o);
265 CHECK_EXCEPTION(jni) << "error during DeleteGlobalRef";
266}
267
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000268// Scope Java local references to the lifetime of this object. Use in all C++
269// callbacks (i.e. entry points that don't originate in a Java callstack
270// through a "native" method call).
271ScopedLocalRefFrame::ScopedLocalRefFrame(JNIEnv* jni) : jni_(jni) {
henrikg91d6ede2015-09-17 00:24:34 -0700272 RTC_CHECK(!jni_->PushLocalFrame(0)) << "Failed to PushLocalFrame";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000273}
274ScopedLocalRefFrame::~ScopedLocalRefFrame() {
275 jni_->PopLocalFrame(NULL);
276}
277
278} // namespace webrtc_jni