blob: ecad5df7519b6108c29de10738a619ed775bb8c0 [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() {
52 CHECK(g_jvm) << "JNI_OnLoad failed to run?";
53 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);
60 CHECK(((env != NULL) && (status == JNI_OK)) ||
61 ((env == NULL) && (status == JNI_EDETACHED)))
62 << "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
77 CHECK(GetEnv() == prev_jni_ptr)
78 << "Detaching from another thread: " << prev_jni_ptr << ":" << GetEnv();
79 jint status = g_jvm->DetachCurrentThread();
80 CHECK(status == JNI_OK) << "Failed to detach thread: " << status;
81 CHECK(!GetEnv()) << "Detaching was a successful no-op???";
82}
83
84static void CreateJNIPtrKey() {
85 CHECK(!pthread_key_create(&g_jni_ptr, &ThreadDestructor))
86 << "pthread_key_create";
87}
88
89jint InitGlobalJniVariables(JavaVM *jvm) {
90 CHECK(!g_jvm) << "InitGlobalJniVariables!";
91 g_jvm = jvm;
92 CHECK(g_jvm) << "InitGlobalJniVariables handed NULL?";
93
94 CHECK(!pthread_once(&g_jni_ptr_once, &CreateJNIPtrKey)) << "pthread_once";
95
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.
phoglund6480d032015-08-28 02:58:41 -0700106 CHECK_LT(snprintf(buf, sizeof(buf), "%ld",
107 static_cast<long>(syscall(__NR_gettid))),
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000108 sizeof(buf))
109 << "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;
126 CHECK(!pthread_getspecific(g_jni_ptr))
127 << "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
140 CHECK(!g_jvm->AttachCurrentThread(&env, &args)) << "Failed to attach thread";
141 CHECK(env) << "AttachCurrentThread handed back NULL!";
142 jni = reinterpret_cast<JNIEnv*>(env);
143 CHECK(!pthread_setspecific(g_jni_ptr, jni)) << "pthread_setspecific";
144 return jni;
145}
146
147// Return a |jlong| that will correctly convert back to |ptr|. This is needed
148// because the alternative (of silently passing a 32-bit pointer to a vararg
149// function expecting a 64-bit param) picks up garbage in the high 32 bits.
150jlong jlongFromPointer(void* ptr) {
151 static_assert(sizeof(intptr_t) <= sizeof(jlong),
152 "Time to rethink the use of jlongs");
153 // Going through intptr_t to be obvious about the definedness of the
154 // conversion from pointer to integral type. intptr_t to jlong is a standard
155 // widening by the static_assert above.
156 jlong ret = reinterpret_cast<intptr_t>(ptr);
157 DCHECK(reinterpret_cast<void*>(ret) == ptr);
158 return ret;
159}
160
161// JNIEnv-helper methods that CHECK success: no Java exception thrown and found
162// object/class/method/field is non-null.
163jmethodID GetMethodID(
164 JNIEnv* jni, jclass c, const std::string& name, const char* signature) {
165 jmethodID m = jni->GetMethodID(c, name.c_str(), signature);
166 CHECK_EXCEPTION(jni) << "error during GetMethodID: " << name << ", "
167 << signature;
168 CHECK(m) << name << ", " << signature;
169 return m;
170}
171
172jmethodID GetStaticMethodID(
173 JNIEnv* jni, jclass c, const char* name, const char* signature) {
174 jmethodID m = jni->GetStaticMethodID(c, name, signature);
175 CHECK_EXCEPTION(jni) << "error during GetStaticMethodID: " << name << ", "
176 << signature;
177 CHECK(m) << name << ", " << signature;
178 return m;
179}
180
181jfieldID GetFieldID(
182 JNIEnv* jni, jclass c, const char* name, const char* signature) {
183 jfieldID f = jni->GetFieldID(c, name, signature);
184 CHECK_EXCEPTION(jni) << "error during GetFieldID";
185 CHECK(f) << name << ", " << signature;
186 return f;
187}
188
189jclass GetObjectClass(JNIEnv* jni, jobject object) {
190 jclass c = jni->GetObjectClass(object);
191 CHECK_EXCEPTION(jni) << "error during GetObjectClass";
192 CHECK(c) << "GetObjectClass returned NULL";
193 return c;
194}
195
196jobject GetObjectField(JNIEnv* jni, jobject object, jfieldID id) {
197 jobject o = jni->GetObjectField(object, id);
198 CHECK_EXCEPTION(jni) << "error during GetObjectField";
199 CHECK(o) << "GetObjectField returned NULL";
200 return o;
201}
202
203jstring GetStringField(JNIEnv* jni, jobject object, jfieldID id) {
204 return static_cast<jstring>(GetObjectField(jni, object, id));
205}
206
207jlong GetLongField(JNIEnv* jni, jobject object, jfieldID id) {
208 jlong l = jni->GetLongField(object, id);
209 CHECK_EXCEPTION(jni) << "error during GetLongField";
210 return l;
211}
212
213jint GetIntField(JNIEnv* jni, jobject object, jfieldID id) {
214 jint i = jni->GetIntField(object, id);
215 CHECK_EXCEPTION(jni) << "error during GetIntField";
216 return i;
217}
218
219bool GetBooleanField(JNIEnv* jni, jobject object, jfieldID id) {
220 jboolean b = jni->GetBooleanField(object, id);
221 CHECK_EXCEPTION(jni) << "error during GetBooleanField";
222 return b;
223}
224
225// Java references to "null" can only be distinguished as such in C++ by
226// creating a local reference, so this helper wraps that logic.
227bool IsNull(JNIEnv* jni, jobject obj) {
228 ScopedLocalRefFrame local_ref_frame(jni);
229 return jni->NewLocalRef(obj) == NULL;
230}
231
232// Given a UTF-8 encoded |native| string return a new (UTF-16) jstring.
233jstring JavaStringFromStdString(JNIEnv* jni, const std::string& native) {
234 UnicodeString ustr(UnicodeString::fromUTF8(native));
235 jstring jstr = jni->NewString(ustr.getBuffer(), ustr.length());
236 CHECK_EXCEPTION(jni) << "error during NewString";
237 return jstr;
238}
239
240// Given a (UTF-16) jstring return a new UTF-8 native string.
241std::string JavaToStdString(JNIEnv* jni, const jstring& j_string) {
242 const jchar* jchars = jni->GetStringChars(j_string, NULL);
243 CHECK_EXCEPTION(jni) << "Error during GetStringChars";
244 UnicodeString ustr(jchars, jni->GetStringLength(j_string));
245 CHECK_EXCEPTION(jni) << "Error during GetStringLength";
246 jni->ReleaseStringChars(j_string, jchars);
247 CHECK_EXCEPTION(jni) << "Error during ReleaseStringChars";
248 std::string ret;
249 return ustr.toUTF8String(ret);
250}
251
252// Return the (singleton) Java Enum object corresponding to |index|;
253jobject JavaEnumFromIndex(JNIEnv* jni, jclass state_class,
254 const std::string& state_class_name, int index) {
255 jmethodID state_values_id = GetStaticMethodID(
256 jni, state_class, "values", ("()[L" + state_class_name + ";").c_str());
257 jobjectArray state_values = static_cast<jobjectArray>(
258 jni->CallStaticObjectMethod(state_class, state_values_id));
259 CHECK_EXCEPTION(jni) << "error during CallStaticObjectMethod";
260 jobject ret = jni->GetObjectArrayElement(state_values, index);
261 CHECK_EXCEPTION(jni) << "error during GetObjectArrayElement";
262 return ret;
263}
264
265jobject NewGlobalRef(JNIEnv* jni, jobject o) {
266 jobject ret = jni->NewGlobalRef(o);
267 CHECK_EXCEPTION(jni) << "error during NewGlobalRef";
268 CHECK(ret);
269 return ret;
270}
271
272void DeleteGlobalRef(JNIEnv* jni, jobject o) {
273 jni->DeleteGlobalRef(o);
274 CHECK_EXCEPTION(jni) << "error during DeleteGlobalRef";
275}
276
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000277// Scope Java local references to the lifetime of this object. Use in all C++
278// callbacks (i.e. entry points that don't originate in a Java callstack
279// through a "native" method call).
280ScopedLocalRefFrame::ScopedLocalRefFrame(JNIEnv* jni) : jni_(jni) {
281 CHECK(!jni_->PushLocalFrame(0)) << "Failed to PushLocalFrame";
282}
283ScopedLocalRefFrame::~ScopedLocalRefFrame() {
284 jni_->PopLocalFrame(NULL);
285}
286
287} // namespace webrtc_jni