1 /*
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 
30 #include <asm/unistd.h>
31 #include <sys/prctl.h>
32 #include <sys/syscall.h>
33 #include <unistd.h>
34 
35 namespace webrtc_jni {
36 
37 static JavaVM* g_jvm = nullptr;
38 
39 static pthread_once_t g_jni_ptr_once = PTHREAD_ONCE_INIT;
40 
41 // Key for per-thread JNIEnv* data.  Non-NULL in threads attached to |g_jvm| by
42 // AttachCurrentThreadIfNeeded(), NULL in unattached threads and threads that
43 // were attached by the JVM because of a Java->native call.
44 static pthread_key_t g_jni_ptr;
45 
GetJVM()46 JavaVM *GetJVM() {
47   RTC_CHECK(g_jvm) << "JNI_OnLoad failed to run?";
48   return g_jvm;
49 }
50 
51 // Return a |JNIEnv*| usable on this thread or NULL if this thread is detached.
GetEnv()52 JNIEnv* GetEnv() {
53   void* env = NULL;
54   jint status = g_jvm->GetEnv(&env, JNI_VERSION_1_6);
55   RTC_CHECK(((env != NULL) && (status == JNI_OK)) ||
56             ((env == NULL) && (status == JNI_EDETACHED)))
57       << "Unexpected GetEnv return: " << status << ":" << env;
58   return reinterpret_cast<JNIEnv*>(env);
59 }
60 
ThreadDestructor(void * prev_jni_ptr)61 static void ThreadDestructor(void* prev_jni_ptr) {
62   // This function only runs on threads where |g_jni_ptr| is non-NULL, meaning
63   // we were responsible for originally attaching the thread, so are responsible
64   // for detaching it now.  However, because some JVM implementations (notably
65   // Oracle's http://goo.gl/eHApYT) also use the pthread_key_create mechanism,
66   // the JVMs accounting info for this thread may already be wiped out by the
67   // time this is called. Thus it may appear we are already detached even though
68   // it was our responsibility to detach!  Oh well.
69   if (!GetEnv())
70     return;
71 
72   RTC_CHECK(GetEnv() == prev_jni_ptr)
73       << "Detaching from another thread: " << prev_jni_ptr << ":" << GetEnv();
74   jint status = g_jvm->DetachCurrentThread();
75   RTC_CHECK(status == JNI_OK) << "Failed to detach thread: " << status;
76   RTC_CHECK(!GetEnv()) << "Detaching was a successful no-op???";
77 }
78 
CreateJNIPtrKey()79 static void CreateJNIPtrKey() {
80   RTC_CHECK(!pthread_key_create(&g_jni_ptr, &ThreadDestructor))
81       << "pthread_key_create";
82 }
83 
InitGlobalJniVariables(JavaVM * jvm)84 jint InitGlobalJniVariables(JavaVM *jvm) {
85   RTC_CHECK(!g_jvm) << "InitGlobalJniVariables!";
86   g_jvm = jvm;
87   RTC_CHECK(g_jvm) << "InitGlobalJniVariables handed NULL?";
88 
89   RTC_CHECK(!pthread_once(&g_jni_ptr_once, &CreateJNIPtrKey)) << "pthread_once";
90 
91   JNIEnv* jni = nullptr;
92   if (jvm->GetEnv(reinterpret_cast<void**>(&jni), JNI_VERSION_1_6) != JNI_OK)
93     return -1;
94 
95   return JNI_VERSION_1_6;
96 }
97 
98 // Return thread ID as a string.
GetThreadId()99 static std::string GetThreadId() {
100   char buf[21];  // Big enough to hold a kuint64max plus terminating NULL.
101   RTC_CHECK_LT(snprintf(buf, sizeof(buf), "%ld",
102                         static_cast<long>(syscall(__NR_gettid))),
103                sizeof(buf))
104       << "Thread id is bigger than uint64??";
105   return std::string(buf);
106 }
107 
108 // Return the current thread's name.
GetThreadName()109 static std::string GetThreadName() {
110   char name[17] = {0};
111   if (prctl(PR_GET_NAME, name) != 0)
112     return std::string("<noname>");
113   return std::string(name);
114 }
115 
116 // Return a |JNIEnv*| usable on this thread.  Attaches to |g_jvm| if necessary.
AttachCurrentThreadIfNeeded()117 JNIEnv* AttachCurrentThreadIfNeeded() {
118   JNIEnv* jni = GetEnv();
119   if (jni)
120     return jni;
121   RTC_CHECK(!pthread_getspecific(g_jni_ptr))
122       << "TLS has a JNIEnv* but not attached?";
123 
124   std::string name(GetThreadName() + " - " + GetThreadId());
125   JavaVMAttachArgs args;
126   args.version = JNI_VERSION_1_6;
127   args.name = &name[0];
128   args.group = NULL;
129   // Deal with difference in signatures between Oracle's jni.h and Android's.
130 #ifdef _JAVASOFT_JNI_H_  // Oracle's jni.h violates the JNI spec!
131   void* env = NULL;
132 #else
133   JNIEnv* env = NULL;
134 #endif
135   RTC_CHECK(!g_jvm->AttachCurrentThread(&env, &args))
136       << "Failed to attach thread";
137   RTC_CHECK(env) << "AttachCurrentThread handed back NULL!";
138   jni = reinterpret_cast<JNIEnv*>(env);
139   RTC_CHECK(!pthread_setspecific(g_jni_ptr, jni)) << "pthread_setspecific";
140   return jni;
141 }
142 
143 // Return a |jlong| that will correctly convert back to |ptr|.  This is needed
144 // because the alternative (of silently passing a 32-bit pointer to a vararg
145 // function expecting a 64-bit param) picks up garbage in the high 32 bits.
jlongFromPointer(void * ptr)146 jlong jlongFromPointer(void* ptr) {
147   static_assert(sizeof(intptr_t) <= sizeof(jlong),
148                 "Time to rethink the use of jlongs");
149   // Going through intptr_t to be obvious about the definedness of the
150   // conversion from pointer to integral type.  intptr_t to jlong is a standard
151   // widening by the static_assert above.
152   jlong ret = reinterpret_cast<intptr_t>(ptr);
153   RTC_DCHECK(reinterpret_cast<void*>(ret) == ptr);
154   return ret;
155 }
156 
157 // JNIEnv-helper methods that RTC_CHECK success: no Java exception thrown and
158 // found object/class/method/field is non-null.
GetMethodID(JNIEnv * jni,jclass c,const std::string & name,const char * signature)159 jmethodID GetMethodID(
160     JNIEnv* jni, jclass c, const std::string& name, const char* signature) {
161   jmethodID m = jni->GetMethodID(c, name.c_str(), signature);
162   CHECK_EXCEPTION(jni) << "error during GetMethodID: " << name << ", "
163                        << signature;
164   RTC_CHECK(m) << name << ", " << signature;
165   return m;
166 }
167 
GetStaticMethodID(JNIEnv * jni,jclass c,const char * name,const char * signature)168 jmethodID GetStaticMethodID(
169     JNIEnv* jni, jclass c, const char* name, const char* signature) {
170   jmethodID m = jni->GetStaticMethodID(c, name, signature);
171   CHECK_EXCEPTION(jni) << "error during GetStaticMethodID: " << name << ", "
172                        << signature;
173   RTC_CHECK(m) << name << ", " << signature;
174   return m;
175 }
176 
GetFieldID(JNIEnv * jni,jclass c,const char * name,const char * signature)177 jfieldID GetFieldID(
178     JNIEnv* jni, jclass c, const char* name, const char* signature) {
179   jfieldID f = jni->GetFieldID(c, name, signature);
180   CHECK_EXCEPTION(jni) << "error during GetFieldID";
181   RTC_CHECK(f) << name << ", " << signature;
182   return f;
183 }
184 
GetObjectClass(JNIEnv * jni,jobject object)185 jclass GetObjectClass(JNIEnv* jni, jobject object) {
186   jclass c = jni->GetObjectClass(object);
187   CHECK_EXCEPTION(jni) << "error during GetObjectClass";
188   RTC_CHECK(c) << "GetObjectClass returned NULL";
189   return c;
190 }
191 
GetObjectField(JNIEnv * jni,jobject object,jfieldID id)192 jobject GetObjectField(JNIEnv* jni, jobject object, jfieldID id) {
193   jobject o = jni->GetObjectField(object, id);
194   CHECK_EXCEPTION(jni) << "error during GetObjectField";
195   RTC_CHECK(o) << "GetObjectField returned NULL";
196   return o;
197 }
198 
GetStringField(JNIEnv * jni,jobject object,jfieldID id)199 jstring GetStringField(JNIEnv* jni, jobject object, jfieldID id) {
200   return static_cast<jstring>(GetObjectField(jni, object, id));
201 }
202 
GetLongField(JNIEnv * jni,jobject object,jfieldID id)203 jlong GetLongField(JNIEnv* jni, jobject object, jfieldID id) {
204   jlong l = jni->GetLongField(object, id);
205   CHECK_EXCEPTION(jni) << "error during GetLongField";
206   return l;
207 }
208 
GetIntField(JNIEnv * jni,jobject object,jfieldID id)209 jint GetIntField(JNIEnv* jni, jobject object, jfieldID id) {
210   jint i = jni->GetIntField(object, id);
211   CHECK_EXCEPTION(jni) << "error during GetIntField";
212   return i;
213 }
214 
GetBooleanField(JNIEnv * jni,jobject object,jfieldID id)215 bool GetBooleanField(JNIEnv* jni, jobject object, jfieldID id) {
216   jboolean b = jni->GetBooleanField(object, id);
217   CHECK_EXCEPTION(jni) << "error during GetBooleanField";
218   return b;
219 }
220 
221 // Java references to "null" can only be distinguished as such in C++ by
222 // creating a local reference, so this helper wraps that logic.
IsNull(JNIEnv * jni,jobject obj)223 bool IsNull(JNIEnv* jni, jobject obj) {
224   ScopedLocalRefFrame local_ref_frame(jni);
225   return jni->NewLocalRef(obj) == NULL;
226 }
227 
228 // Given a UTF-8 encoded |native| string return a new (UTF-16) jstring.
JavaStringFromStdString(JNIEnv * jni,const std::string & native)229 jstring JavaStringFromStdString(JNIEnv* jni, const std::string& native) {
230   jstring jstr = jni->NewStringUTF(native.c_str());
231   CHECK_EXCEPTION(jni) << "error during NewStringUTF";
232   return jstr;
233 }
234 
235 // Given a (UTF-16) jstring return a new UTF-8 native string.
JavaToStdString(JNIEnv * jni,const jstring & j_string)236 std::string JavaToStdString(JNIEnv* jni, const jstring& j_string) {
237   const char* chars = jni->GetStringUTFChars(j_string, NULL);
238   CHECK_EXCEPTION(jni) << "Error during GetStringUTFChars";
239   std::string str(chars, jni->GetStringUTFLength(j_string));
240   CHECK_EXCEPTION(jni) << "Error during GetStringUTFLength";
241   jni->ReleaseStringUTFChars(j_string, chars);
242   CHECK_EXCEPTION(jni) << "Error during ReleaseStringUTFChars";
243   return str;
244 }
245 
246 // Return the (singleton) Java Enum object corresponding to |index|;
JavaEnumFromIndex(JNIEnv * jni,jclass state_class,const std::string & state_class_name,int index)247 jobject JavaEnumFromIndex(JNIEnv* jni, jclass state_class,
248                           const std::string& state_class_name, int index) {
249   jmethodID state_values_id = GetStaticMethodID(
250       jni, state_class, "values", ("()[L" + state_class_name  + ";").c_str());
251   jobjectArray state_values = static_cast<jobjectArray>(
252       jni->CallStaticObjectMethod(state_class, state_values_id));
253   CHECK_EXCEPTION(jni) << "error during CallStaticObjectMethod";
254   jobject ret = jni->GetObjectArrayElement(state_values, index);
255   CHECK_EXCEPTION(jni) << "error during GetObjectArrayElement";
256   return ret;
257 }
258 
NewGlobalRef(JNIEnv * jni,jobject o)259 jobject NewGlobalRef(JNIEnv* jni, jobject o) {
260   jobject ret = jni->NewGlobalRef(o);
261   CHECK_EXCEPTION(jni) << "error during NewGlobalRef";
262   RTC_CHECK(ret);
263   return ret;
264 }
265 
DeleteGlobalRef(JNIEnv * jni,jobject o)266 void DeleteGlobalRef(JNIEnv* jni, jobject o) {
267   jni->DeleteGlobalRef(o);
268   CHECK_EXCEPTION(jni) << "error during DeleteGlobalRef";
269 }
270 
271 // Scope Java local references to the lifetime of this object.  Use in all C++
272 // callbacks (i.e. entry points that don't originate in a Java callstack
273 // through a "native" method call).
ScopedLocalRefFrame(JNIEnv * jni)274 ScopedLocalRefFrame::ScopedLocalRefFrame(JNIEnv* jni) : jni_(jni) {
275   RTC_CHECK(!jni_->PushLocalFrame(0)) << "Failed to PushLocalFrame";
276 }
~ScopedLocalRefFrame()277 ScopedLocalRefFrame::~ScopedLocalRefFrame() {
278   jni_->PopLocalFrame(NULL);
279 }
280 
281 }  // namespace webrtc_jni
282