blob: 25b340ff79a9902ba2ad7e7a0eeb72db497cbee6 [file] [log] [blame]
perkj@webrtc.org96e4db92015-02-13 12:46:51 +00001/*
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
honghaizcec0a082016-01-15 14:49:09 -080030#include "talk/app/webrtc/java/jni/classreferenceholder.h"
31
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000032#include <asm/unistd.h>
33#include <sys/prctl.h>
34#include <sys/syscall.h>
35#include <unistd.h>
36
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000037namespace webrtc_jni {
38
39static JavaVM* g_jvm = nullptr;
40
41static 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.
46static pthread_key_t g_jni_ptr;
47
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000048JavaVM *GetJVM() {
henrikg91d6ede2015-09-17 00:24:34 -070049 RTC_CHECK(g_jvm) << "JNI_OnLoad failed to run?";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000050 return g_jvm;
51}
52
53// Return a |JNIEnv*| usable on this thread or NULL if this thread is detached.
54JNIEnv* GetEnv() {
55 void* env = NULL;
56 jint status = g_jvm->GetEnv(&env, JNI_VERSION_1_6);
henrikg91d6ede2015-09-17 00:24:34 -070057 RTC_CHECK(((env != NULL) && (status == JNI_OK)) ||
58 ((env == NULL) && (status == JNI_EDETACHED)))
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000059 << "Unexpected GetEnv return: " << status << ":" << env;
60 return reinterpret_cast<JNIEnv*>(env);
61}
62
63static 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
henrikg91d6ede2015-09-17 00:24:34 -070074 RTC_CHECK(GetEnv() == prev_jni_ptr)
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000075 << "Detaching from another thread: " << prev_jni_ptr << ":" << GetEnv();
76 jint status = g_jvm->DetachCurrentThread();
henrikg91d6ede2015-09-17 00:24:34 -070077 RTC_CHECK(status == JNI_OK) << "Failed to detach thread: " << status;
78 RTC_CHECK(!GetEnv()) << "Detaching was a successful no-op???";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000079}
80
81static void CreateJNIPtrKey() {
henrikg91d6ede2015-09-17 00:24:34 -070082 RTC_CHECK(!pthread_key_create(&g_jni_ptr, &ThreadDestructor))
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000083 << "pthread_key_create";
84}
85
86jint InitGlobalJniVariables(JavaVM *jvm) {
henrikg91d6ede2015-09-17 00:24:34 -070087 RTC_CHECK(!g_jvm) << "InitGlobalJniVariables!";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000088 g_jvm = jvm;
henrikg91d6ede2015-09-17 00:24:34 -070089 RTC_CHECK(g_jvm) << "InitGlobalJniVariables handed NULL?";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000090
henrikg91d6ede2015-09-17 00:24:34 -070091 RTC_CHECK(!pthread_once(&g_jni_ptr_once, &CreateJNIPtrKey)) << "pthread_once";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000092
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.
101static std::string GetThreadId() {
102 char buf[21]; // Big enough to hold a kuint64max plus terminating NULL.
henrikg91d6ede2015-09-17 00:24:34 -0700103 RTC_CHECK_LT(snprintf(buf, sizeof(buf), "%ld",
104 static_cast<long>(syscall(__NR_gettid))),
105 sizeof(buf))
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000106 << "Thread id is bigger than uint64??";
107 return std::string(buf);
108}
109
110// Return the current thread's name.
111static std::string GetThreadName() {
Tommia9952cd2015-06-03 18:59:11 +0200112 char name[17] = {0};
113 if (prctl(PR_GET_NAME, name) != 0)
114 return std::string("<noname>");
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000115 return std::string(name);
116}
117
118// Return a |JNIEnv*| usable on this thread. Attaches to |g_jvm| if necessary.
119JNIEnv* AttachCurrentThreadIfNeeded() {
120 JNIEnv* jni = GetEnv();
121 if (jni)
122 return jni;
henrikg91d6ede2015-09-17 00:24:34 -0700123 RTC_CHECK(!pthread_getspecific(g_jni_ptr))
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000124 << "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
henrikg91d6ede2015-09-17 00:24:34 -0700137 RTC_CHECK(!g_jvm->AttachCurrentThread(&env, &args))
138 << "Failed to attach thread";
139 RTC_CHECK(env) << "AttachCurrentThread handed back NULL!";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000140 jni = reinterpret_cast<JNIEnv*>(env);
henrikg91d6ede2015-09-17 00:24:34 -0700141 RTC_CHECK(!pthread_setspecific(g_jni_ptr, jni)) << "pthread_setspecific";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000142 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.
148jlong 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);
henrikg91d6ede2015-09-17 00:24:34 -0700155 RTC_DCHECK(reinterpret_cast<void*>(ret) == ptr);
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000156 return ret;
157}
158
henrikg91d6ede2015-09-17 00:24:34 -0700159// JNIEnv-helper methods that RTC_CHECK success: no Java exception thrown and
160// found object/class/method/field is non-null.
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000161jmethodID 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;
henrikg91d6ede2015-09-17 00:24:34 -0700166 RTC_CHECK(m) << name << ", " << signature;
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000167 return m;
168}
169
170jmethodID 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;
henrikg91d6ede2015-09-17 00:24:34 -0700175 RTC_CHECK(m) << name << ", " << signature;
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000176 return m;
177}
178
179jfieldID 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";
henrikg91d6ede2015-09-17 00:24:34 -0700183 RTC_CHECK(f) << name << ", " << signature;
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000184 return f;
185}
186
187jclass GetObjectClass(JNIEnv* jni, jobject object) {
188 jclass c = jni->GetObjectClass(object);
189 CHECK_EXCEPTION(jni) << "error during GetObjectClass";
henrikg91d6ede2015-09-17 00:24:34 -0700190 RTC_CHECK(c) << "GetObjectClass returned NULL";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000191 return c;
192}
193
194jobject GetObjectField(JNIEnv* jni, jobject object, jfieldID id) {
195 jobject o = jni->GetObjectField(object, id);
196 CHECK_EXCEPTION(jni) << "error during GetObjectField";
henrikg91d6ede2015-09-17 00:24:34 -0700197 RTC_CHECK(o) << "GetObjectField returned NULL";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000198 return o;
199}
200
201jstring GetStringField(JNIEnv* jni, jobject object, jfieldID id) {
202 return static_cast<jstring>(GetObjectField(jni, object, id));
203}
204
205jlong 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
211jint 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
217bool 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.
225bool 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.
231jstring JavaStringFromStdString(JNIEnv* jni, const std::string& native) {
noahric23725e02015-11-06 13:56:06 -0800232 jstring jstr = jni->NewStringUTF(native.c_str());
233 CHECK_EXCEPTION(jni) << "error during NewStringUTF";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000234 return jstr;
235}
236
237// Given a (UTF-16) jstring return a new UTF-8 native string.
238std::string JavaToStdString(JNIEnv* jni, const jstring& j_string) {
noahric23725e02015-11-06 13:56:06 -0800239 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;
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000246}
247
248// Return the (singleton) Java Enum object corresponding to |index|;
249jobject 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
honghaizcec0a082016-01-15 14:49:09 -0800261std::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
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000274jobject NewGlobalRef(JNIEnv* jni, jobject o) {
275 jobject ret = jni->NewGlobalRef(o);
276 CHECK_EXCEPTION(jni) << "error during NewGlobalRef";
henrikg91d6ede2015-09-17 00:24:34 -0700277 RTC_CHECK(ret);
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000278 return ret;
279}
280
281void DeleteGlobalRef(JNIEnv* jni, jobject o) {
282 jni->DeleteGlobalRef(o);
283 CHECK_EXCEPTION(jni) << "error during DeleteGlobalRef";
284}
285
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000286// 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).
289ScopedLocalRefFrame::ScopedLocalRefFrame(JNIEnv* jni) : jni_(jni) {
henrikg91d6ede2015-09-17 00:24:34 -0700290 RTC_CHECK(!jni_->PushLocalFrame(0)) << "Failed to PushLocalFrame";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000291}
292ScopedLocalRefFrame::~ScopedLocalRefFrame() {
293 jni_->PopLocalFrame(NULL);
294}
295
296} // namespace webrtc_jni