blob: 755698e37978c65d177e43c23ae286ae454f8fe8 [file] [log] [blame]
perkj@webrtc.org96e4db92015-02-13 12:46:51 +00001
2/*
3 * libjingle
4 * Copyright 2015 Google Inc.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions are met:
8 *
9 * 1. Redistributions of source code must retain the above copyright notice,
10 * this list of conditions and the following disclaimer.
11 * 2. Redistributions in binary form must reproduce the above copyright notice,
12 * this list of conditions and the following disclaimer in the documentation
13 * and/or other materials provided with the distribution.
14 * 3. The name of the author may not be used to endorse or promote products
15 * derived from this software without specific prior written permission.
16 *
17 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED
18 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
19 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
20 * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
22 * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS;
23 * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
24 * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR
25 * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
26 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 *
28 */
29#include "talk/app/webrtc/java/jni/jni_helpers.h"
30
31#include <asm/unistd.h>
32#include <sys/prctl.h>
33#include <sys/syscall.h>
34#include <unistd.h>
35
Henrik Kjellander35259542015-04-23 08:58:21 +020036#include "unicode/unistr.h"
37
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000038namespace webrtc_jni {
39
40static JavaVM* g_jvm = nullptr;
41
42static pthread_once_t g_jni_ptr_once = PTHREAD_ONCE_INIT;
43
44// Key for per-thread JNIEnv* data. Non-NULL in threads attached to |g_jvm| by
45// AttachCurrentThreadIfNeeded(), NULL in unattached threads and threads that
46// were attached by the JVM because of a Java->native call.
47static pthread_key_t g_jni_ptr;
48
49using icu::UnicodeString;
50
51JavaVM *GetJVM() {
henrikg91d6ede2015-09-17 00:24:34 -070052 RTC_CHECK(g_jvm) << "JNI_OnLoad failed to run?";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000053 return g_jvm;
54}
55
56// Return a |JNIEnv*| usable on this thread or NULL if this thread is detached.
57JNIEnv* GetEnv() {
58 void* env = NULL;
59 jint status = g_jvm->GetEnv(&env, JNI_VERSION_1_6);
henrikg91d6ede2015-09-17 00:24:34 -070060 RTC_CHECK(((env != NULL) && (status == JNI_OK)) ||
61 ((env == NULL) && (status == JNI_EDETACHED)))
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000062 << "Unexpected GetEnv return: " << status << ":" << env;
63 return reinterpret_cast<JNIEnv*>(env);
64}
65
66static void ThreadDestructor(void* prev_jni_ptr) {
67 // This function only runs on threads where |g_jni_ptr| is non-NULL, meaning
68 // we were responsible for originally attaching the thread, so are responsible
69 // for detaching it now. However, because some JVM implementations (notably
70 // Oracle's http://goo.gl/eHApYT) also use the pthread_key_create mechanism,
71 // the JVMs accounting info for this thread may already be wiped out by the
72 // time this is called. Thus it may appear we are already detached even though
73 // it was our responsibility to detach! Oh well.
74 if (!GetEnv())
75 return;
76
henrikg91d6ede2015-09-17 00:24:34 -070077 RTC_CHECK(GetEnv() == prev_jni_ptr)
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000078 << "Detaching from another thread: " << prev_jni_ptr << ":" << GetEnv();
79 jint status = g_jvm->DetachCurrentThread();
henrikg91d6ede2015-09-17 00:24:34 -070080 RTC_CHECK(status == JNI_OK) << "Failed to detach thread: " << status;
81 RTC_CHECK(!GetEnv()) << "Detaching was a successful no-op???";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000082}
83
84static void CreateJNIPtrKey() {
henrikg91d6ede2015-09-17 00:24:34 -070085 RTC_CHECK(!pthread_key_create(&g_jni_ptr, &ThreadDestructor))
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000086 << "pthread_key_create";
87}
88
89jint InitGlobalJniVariables(JavaVM *jvm) {
henrikg91d6ede2015-09-17 00:24:34 -070090 RTC_CHECK(!g_jvm) << "InitGlobalJniVariables!";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000091 g_jvm = jvm;
henrikg91d6ede2015-09-17 00:24:34 -070092 RTC_CHECK(g_jvm) << "InitGlobalJniVariables handed NULL?";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000093
henrikg91d6ede2015-09-17 00:24:34 -070094 RTC_CHECK(!pthread_once(&g_jni_ptr_once, &CreateJNIPtrKey)) << "pthread_once";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +000095
96 JNIEnv* jni = nullptr;
97 if (jvm->GetEnv(reinterpret_cast<void**>(&jni), JNI_VERSION_1_6) != JNI_OK)
98 return -1;
99
100 return JNI_VERSION_1_6;
101}
102
103// Return thread ID as a string.
104static std::string GetThreadId() {
105 char buf[21]; // Big enough to hold a kuint64max plus terminating NULL.
henrikg91d6ede2015-09-17 00:24:34 -0700106 RTC_CHECK_LT(snprintf(buf, sizeof(buf), "%ld",
107 static_cast<long>(syscall(__NR_gettid))),
108 sizeof(buf))
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000109 << "Thread id is bigger than uint64??";
110 return std::string(buf);
111}
112
113// Return the current thread's name.
114static std::string GetThreadName() {
Tommia9952cd2015-06-03 18:59:11 +0200115 char name[17] = {0};
116 if (prctl(PR_GET_NAME, name) != 0)
117 return std::string("<noname>");
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000118 return std::string(name);
119}
120
121// Return a |JNIEnv*| usable on this thread. Attaches to |g_jvm| if necessary.
122JNIEnv* AttachCurrentThreadIfNeeded() {
123 JNIEnv* jni = GetEnv();
124 if (jni)
125 return jni;
henrikg91d6ede2015-09-17 00:24:34 -0700126 RTC_CHECK(!pthread_getspecific(g_jni_ptr))
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000127 << "TLS has a JNIEnv* but not attached?";
128
129 std::string name(GetThreadName() + " - " + GetThreadId());
130 JavaVMAttachArgs args;
131 args.version = JNI_VERSION_1_6;
132 args.name = &name[0];
133 args.group = NULL;
134 // Deal with difference in signatures between Oracle's jni.h and Android's.
135#ifdef _JAVASOFT_JNI_H_ // Oracle's jni.h violates the JNI spec!
136 void* env = NULL;
137#else
138 JNIEnv* env = NULL;
139#endif
henrikg91d6ede2015-09-17 00:24:34 -0700140 RTC_CHECK(!g_jvm->AttachCurrentThread(&env, &args))
141 << "Failed to attach thread";
142 RTC_CHECK(env) << "AttachCurrentThread handed back NULL!";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000143 jni = reinterpret_cast<JNIEnv*>(env);
henrikg91d6ede2015-09-17 00:24:34 -0700144 RTC_CHECK(!pthread_setspecific(g_jni_ptr, jni)) << "pthread_setspecific";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000145 return jni;
146}
147
148// Return a |jlong| that will correctly convert back to |ptr|. This is needed
149// because the alternative (of silently passing a 32-bit pointer to a vararg
150// function expecting a 64-bit param) picks up garbage in the high 32 bits.
151jlong jlongFromPointer(void* ptr) {
152 static_assert(sizeof(intptr_t) <= sizeof(jlong),
153 "Time to rethink the use of jlongs");
154 // Going through intptr_t to be obvious about the definedness of the
155 // conversion from pointer to integral type. intptr_t to jlong is a standard
156 // widening by the static_assert above.
157 jlong ret = reinterpret_cast<intptr_t>(ptr);
henrikg91d6ede2015-09-17 00:24:34 -0700158 RTC_DCHECK(reinterpret_cast<void*>(ret) == ptr);
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000159 return ret;
160}
161
henrikg91d6ede2015-09-17 00:24:34 -0700162// JNIEnv-helper methods that RTC_CHECK success: no Java exception thrown and
163// found object/class/method/field is non-null.
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000164jmethodID GetMethodID(
165 JNIEnv* jni, jclass c, const std::string& name, const char* signature) {
166 jmethodID m = jni->GetMethodID(c, name.c_str(), signature);
167 CHECK_EXCEPTION(jni) << "error during GetMethodID: " << name << ", "
168 << signature;
henrikg91d6ede2015-09-17 00:24:34 -0700169 RTC_CHECK(m) << name << ", " << signature;
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000170 return m;
171}
172
173jmethodID GetStaticMethodID(
174 JNIEnv* jni, jclass c, const char* name, const char* signature) {
175 jmethodID m = jni->GetStaticMethodID(c, name, signature);
176 CHECK_EXCEPTION(jni) << "error during GetStaticMethodID: " << name << ", "
177 << signature;
henrikg91d6ede2015-09-17 00:24:34 -0700178 RTC_CHECK(m) << name << ", " << signature;
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000179 return m;
180}
181
182jfieldID GetFieldID(
183 JNIEnv* jni, jclass c, const char* name, const char* signature) {
184 jfieldID f = jni->GetFieldID(c, name, signature);
185 CHECK_EXCEPTION(jni) << "error during GetFieldID";
henrikg91d6ede2015-09-17 00:24:34 -0700186 RTC_CHECK(f) << name << ", " << signature;
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000187 return f;
188}
189
190jclass GetObjectClass(JNIEnv* jni, jobject object) {
191 jclass c = jni->GetObjectClass(object);
192 CHECK_EXCEPTION(jni) << "error during GetObjectClass";
henrikg91d6ede2015-09-17 00:24:34 -0700193 RTC_CHECK(c) << "GetObjectClass returned NULL";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000194 return c;
195}
196
197jobject GetObjectField(JNIEnv* jni, jobject object, jfieldID id) {
198 jobject o = jni->GetObjectField(object, id);
199 CHECK_EXCEPTION(jni) << "error during GetObjectField";
henrikg91d6ede2015-09-17 00:24:34 -0700200 RTC_CHECK(o) << "GetObjectField returned NULL";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000201 return o;
202}
203
204jstring GetStringField(JNIEnv* jni, jobject object, jfieldID id) {
205 return static_cast<jstring>(GetObjectField(jni, object, id));
206}
207
208jlong GetLongField(JNIEnv* jni, jobject object, jfieldID id) {
209 jlong l = jni->GetLongField(object, id);
210 CHECK_EXCEPTION(jni) << "error during GetLongField";
211 return l;
212}
213
214jint GetIntField(JNIEnv* jni, jobject object, jfieldID id) {
215 jint i = jni->GetIntField(object, id);
216 CHECK_EXCEPTION(jni) << "error during GetIntField";
217 return i;
218}
219
220bool GetBooleanField(JNIEnv* jni, jobject object, jfieldID id) {
221 jboolean b = jni->GetBooleanField(object, id);
222 CHECK_EXCEPTION(jni) << "error during GetBooleanField";
223 return b;
224}
225
226// Java references to "null" can only be distinguished as such in C++ by
227// creating a local reference, so this helper wraps that logic.
228bool IsNull(JNIEnv* jni, jobject obj) {
229 ScopedLocalRefFrame local_ref_frame(jni);
230 return jni->NewLocalRef(obj) == NULL;
231}
232
233// Given a UTF-8 encoded |native| string return a new (UTF-16) jstring.
234jstring JavaStringFromStdString(JNIEnv* jni, const std::string& native) {
235 UnicodeString ustr(UnicodeString::fromUTF8(native));
236 jstring jstr = jni->NewString(ustr.getBuffer(), ustr.length());
237 CHECK_EXCEPTION(jni) << "error during NewString";
238 return jstr;
239}
240
241// Given a (UTF-16) jstring return a new UTF-8 native string.
242std::string JavaToStdString(JNIEnv* jni, const jstring& j_string) {
243 const jchar* jchars = jni->GetStringChars(j_string, NULL);
244 CHECK_EXCEPTION(jni) << "Error during GetStringChars";
245 UnicodeString ustr(jchars, jni->GetStringLength(j_string));
246 CHECK_EXCEPTION(jni) << "Error during GetStringLength";
247 jni->ReleaseStringChars(j_string, jchars);
248 CHECK_EXCEPTION(jni) << "Error during ReleaseStringChars";
249 std::string ret;
250 return ustr.toUTF8String(ret);
251}
252
253// Return the (singleton) Java Enum object corresponding to |index|;
254jobject JavaEnumFromIndex(JNIEnv* jni, jclass state_class,
255 const std::string& state_class_name, int index) {
256 jmethodID state_values_id = GetStaticMethodID(
257 jni, state_class, "values", ("()[L" + state_class_name + ";").c_str());
258 jobjectArray state_values = static_cast<jobjectArray>(
259 jni->CallStaticObjectMethod(state_class, state_values_id));
260 CHECK_EXCEPTION(jni) << "error during CallStaticObjectMethod";
261 jobject ret = jni->GetObjectArrayElement(state_values, index);
262 CHECK_EXCEPTION(jni) << "error during GetObjectArrayElement";
263 return ret;
264}
265
266jobject NewGlobalRef(JNIEnv* jni, jobject o) {
267 jobject ret = jni->NewGlobalRef(o);
268 CHECK_EXCEPTION(jni) << "error during NewGlobalRef";
henrikg91d6ede2015-09-17 00:24:34 -0700269 RTC_CHECK(ret);
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000270 return ret;
271}
272
273void DeleteGlobalRef(JNIEnv* jni, jobject o) {
274 jni->DeleteGlobalRef(o);
275 CHECK_EXCEPTION(jni) << "error during DeleteGlobalRef";
276}
277
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000278// Scope Java local references to the lifetime of this object. Use in all C++
279// callbacks (i.e. entry points that don't originate in a Java callstack
280// through a "native" method call).
281ScopedLocalRefFrame::ScopedLocalRefFrame(JNIEnv* jni) : jni_(jni) {
henrikg91d6ede2015-09-17 00:24:34 -0700282 RTC_CHECK(!jni_->PushLocalFrame(0)) << "Failed to PushLocalFrame";
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000283}
284ScopedLocalRefFrame::~ScopedLocalRefFrame() {
285 jni_->PopLocalFrame(NULL);
286}
287
288} // namespace webrtc_jni