blob: a2cbd61971ecdcb68d4f5913a92ae4ea56223136 [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.
Henrik Kjellandere6cefb62015-04-27 14:39:04 +0200106 CHECK_LT(snprintf(buf, sizeof(buf), "%ld", syscall(__NR_gettid)),
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000107 sizeof(buf))
108 << "Thread id is bigger than uint64??";
109 return std::string(buf);
110}
111
112// Return the current thread's name.
113static std::string GetThreadName() {
Tommia9952cd2015-06-03 18:59:11 +0200114 char name[17] = {0};
115 if (prctl(PR_GET_NAME, name) != 0)
116 return std::string("<noname>");
perkj@webrtc.org96e4db92015-02-13 12:46:51 +0000117 return std::string(name);
118}
119
120// Return a |JNIEnv*| usable on this thread. Attaches to |g_jvm| if necessary.
121JNIEnv* AttachCurrentThreadIfNeeded() {
122 JNIEnv* jni = GetEnv();
123 if (jni)
124 return jni;
125 CHECK(!pthread_getspecific(g_jni_ptr))
126 << "TLS has a JNIEnv* but not attached?";
127
128 std::string name(GetThreadName() + " - " + GetThreadId());
129 JavaVMAttachArgs args;
130 args.version = JNI_VERSION_1_6;
131 args.name = &name[0];
132 args.group = NULL;
133 // Deal with difference in signatures between Oracle's jni.h and Android's.
134#ifdef _JAVASOFT_JNI_H_ // Oracle's jni.h violates the JNI spec!
135 void* env = NULL;
136#else
137 JNIEnv* env = NULL;
138#endif
139 CHECK(!g_jvm->AttachCurrentThread(&env, &args)) << "Failed to attach thread";
140 CHECK(env) << "AttachCurrentThread handed back NULL!";
141 jni = reinterpret_cast<JNIEnv*>(env);
142 CHECK(!pthread_setspecific(g_jni_ptr, jni)) << "pthread_setspecific";
143 return jni;
144}
145
146// Return a |jlong| that will correctly convert back to |ptr|. This is needed
147// because the alternative (of silently passing a 32-bit pointer to a vararg
148// function expecting a 64-bit param) picks up garbage in the high 32 bits.
149jlong jlongFromPointer(void* ptr) {
150 static_assert(sizeof(intptr_t) <= sizeof(jlong),
151 "Time to rethink the use of jlongs");
152 // Going through intptr_t to be obvious about the definedness of the
153 // conversion from pointer to integral type. intptr_t to jlong is a standard
154 // widening by the static_assert above.
155 jlong ret = reinterpret_cast<intptr_t>(ptr);
156 DCHECK(reinterpret_cast<void*>(ret) == ptr);
157 return ret;
158}
159
160// JNIEnv-helper methods that CHECK success: no Java exception thrown and found
161// object/class/method/field is non-null.
162jmethodID GetMethodID(
163 JNIEnv* jni, jclass c, const std::string& name, const char* signature) {
164 jmethodID m = jni->GetMethodID(c, name.c_str(), signature);
165 CHECK_EXCEPTION(jni) << "error during GetMethodID: " << name << ", "
166 << signature;
167 CHECK(m) << name << ", " << signature;
168 return m;
169}
170
171jmethodID GetStaticMethodID(
172 JNIEnv* jni, jclass c, const char* name, const char* signature) {
173 jmethodID m = jni->GetStaticMethodID(c, name, signature);
174 CHECK_EXCEPTION(jni) << "error during GetStaticMethodID: " << name << ", "
175 << signature;
176 CHECK(m) << name << ", " << signature;
177 return m;
178}
179
180jfieldID GetFieldID(
181 JNIEnv* jni, jclass c, const char* name, const char* signature) {
182 jfieldID f = jni->GetFieldID(c, name, signature);
183 CHECK_EXCEPTION(jni) << "error during GetFieldID";
184 CHECK(f) << name << ", " << signature;
185 return f;
186}
187
188jclass GetObjectClass(JNIEnv* jni, jobject object) {
189 jclass c = jni->GetObjectClass(object);
190 CHECK_EXCEPTION(jni) << "error during GetObjectClass";
191 CHECK(c) << "GetObjectClass returned NULL";
192 return c;
193}
194
195jobject GetObjectField(JNIEnv* jni, jobject object, jfieldID id) {
196 jobject o = jni->GetObjectField(object, id);
197 CHECK_EXCEPTION(jni) << "error during GetObjectField";
198 CHECK(o) << "GetObjectField returned NULL";
199 return o;
200}
201
202jstring GetStringField(JNIEnv* jni, jobject object, jfieldID id) {
203 return static_cast<jstring>(GetObjectField(jni, object, id));
204}
205
206jlong GetLongField(JNIEnv* jni, jobject object, jfieldID id) {
207 jlong l = jni->GetLongField(object, id);
208 CHECK_EXCEPTION(jni) << "error during GetLongField";
209 return l;
210}
211
212jint GetIntField(JNIEnv* jni, jobject object, jfieldID id) {
213 jint i = jni->GetIntField(object, id);
214 CHECK_EXCEPTION(jni) << "error during GetIntField";
215 return i;
216}
217
218bool GetBooleanField(JNIEnv* jni, jobject object, jfieldID id) {
219 jboolean b = jni->GetBooleanField(object, id);
220 CHECK_EXCEPTION(jni) << "error during GetBooleanField";
221 return b;
222}
223
224// Java references to "null" can only be distinguished as such in C++ by
225// creating a local reference, so this helper wraps that logic.
226bool IsNull(JNIEnv* jni, jobject obj) {
227 ScopedLocalRefFrame local_ref_frame(jni);
228 return jni->NewLocalRef(obj) == NULL;
229}
230
231// Given a UTF-8 encoded |native| string return a new (UTF-16) jstring.
232jstring JavaStringFromStdString(JNIEnv* jni, const std::string& native) {
233 UnicodeString ustr(UnicodeString::fromUTF8(native));
234 jstring jstr = jni->NewString(ustr.getBuffer(), ustr.length());
235 CHECK_EXCEPTION(jni) << "error during NewString";
236 return jstr;
237}
238
239// Given a (UTF-16) jstring return a new UTF-8 native string.
240std::string JavaToStdString(JNIEnv* jni, const jstring& j_string) {
241 const jchar* jchars = jni->GetStringChars(j_string, NULL);
242 CHECK_EXCEPTION(jni) << "Error during GetStringChars";
243 UnicodeString ustr(jchars, jni->GetStringLength(j_string));
244 CHECK_EXCEPTION(jni) << "Error during GetStringLength";
245 jni->ReleaseStringChars(j_string, jchars);
246 CHECK_EXCEPTION(jni) << "Error during ReleaseStringChars";
247 std::string ret;
248 return ustr.toUTF8String(ret);
249}
250
251// Return the (singleton) Java Enum object corresponding to |index|;
252jobject JavaEnumFromIndex(JNIEnv* jni, jclass state_class,
253 const std::string& state_class_name, int index) {
254 jmethodID state_values_id = GetStaticMethodID(
255 jni, state_class, "values", ("()[L" + state_class_name + ";").c_str());
256 jobjectArray state_values = static_cast<jobjectArray>(
257 jni->CallStaticObjectMethod(state_class, state_values_id));
258 CHECK_EXCEPTION(jni) << "error during CallStaticObjectMethod";
259 jobject ret = jni->GetObjectArrayElement(state_values, index);
260 CHECK_EXCEPTION(jni) << "error during GetObjectArrayElement";
261 return ret;
262}
263
264jobject NewGlobalRef(JNIEnv* jni, jobject o) {
265 jobject ret = jni->NewGlobalRef(o);
266 CHECK_EXCEPTION(jni) << "error during NewGlobalRef";
267 CHECK(ret);
268 return ret;
269}
270
271void DeleteGlobalRef(JNIEnv* jni, jobject o) {
272 jni->DeleteGlobalRef(o);
273 CHECK_EXCEPTION(jni) << "error during DeleteGlobalRef";
274}
275
276WeakRef::WeakRef(JNIEnv* jni, jweak ref)
277 : jni_(jni), obj_(jni_->NewLocalRef(ref)) {
278 CHECK_EXCEPTION(jni) << "error during NewLocalRef";
279}
280WeakRef::~WeakRef() {
281 if (obj_) {
282 jni_->DeleteLocalRef(obj_);
283 CHECK_EXCEPTION(jni_) << "error during DeleteLocalRef";
284 }
285}
286
287// Scope Java local references to the lifetime of this object. Use in all C++
288// callbacks (i.e. entry points that don't originate in a Java callstack
289// through a "native" method call).
290ScopedLocalRefFrame::ScopedLocalRefFrame(JNIEnv* jni) : jni_(jni) {
291 CHECK(!jni_->PushLocalFrame(0)) << "Failed to PushLocalFrame";
292}
293ScopedLocalRefFrame::~ScopedLocalRefFrame() {
294 jni_->PopLocalFrame(NULL);
295}
296
297} // namespace webrtc_jni