1 /* 2 * Copyright (c) 2013 The WebRTC project authors. All Rights Reserved. 3 * 4 * Use of this source code is governed by a BSD-style license 5 * that can be found in the LICENSE file in the root of the source 6 * tree. An additional intellectual property rights grant can be found 7 * in the file PATENTS. All contributing project authors may 8 * be found in the AUTHORS file in the root of the source tree. 9 */ 10 11 #ifndef MODULES_UTILITY_INCLUDE_HELPERS_ANDROID_H_ 12 #define MODULES_UTILITY_INCLUDE_HELPERS_ANDROID_H_ 13 14 #include <jni.h> 15 16 #include <string> 17 18 #include "rtc_base/system/arch.h" 19 20 // Abort the process if |jni| has a Java exception pending. 21 // TODO(henrika): merge with CHECK_JNI_EXCEPTION() in jni_helpers.h. 22 #define CHECK_EXCEPTION(jni) \ 23 RTC_CHECK(!jni->ExceptionCheck()) \ 24 << (jni->ExceptionDescribe(), jni->ExceptionClear(), "") 25 26 #if defined(WEBRTC_ARCH_X86) 27 // Dalvik JIT generated code doesn't guarantee 16-byte stack alignment on 28 // x86 - use force_align_arg_pointer to realign the stack at the JNI 29 // boundary. bugs.webrtc.org/9050 30 #define JNI_FUNCTION_ALIGN __attribute__((force_align_arg_pointer)) 31 #else 32 #define JNI_FUNCTION_ALIGN 33 #endif 34 35 namespace webrtc { 36 37 // Return a |JNIEnv*| usable on this thread or NULL if this thread is detached. 38 JNIEnv* GetEnv(JavaVM* jvm); 39 40 // Return a |jlong| that will correctly convert back to |ptr|. This is needed 41 // because the alternative (of silently passing a 32-bit pointer to a vararg 42 // function expecting a 64-bit param) picks up garbage in the high 32 bits. 43 jlong PointerTojlong(void* ptr); 44 45 // JNIEnv-helper methods that wraps the API which uses the JNI interface 46 // pointer (JNIEnv*). It allows us to RTC_CHECK success and that no Java 47 // exception is thrown while calling the method. 48 jmethodID GetMethodID(JNIEnv* jni, 49 jclass c, 50 const char* name, 51 const char* signature); 52 53 jmethodID GetStaticMethodID(JNIEnv* jni, 54 jclass c, 55 const char* name, 56 const char* signature); 57 58 jclass FindClass(JNIEnv* jni, const char* name); 59 60 jobject NewGlobalRef(JNIEnv* jni, jobject o); 61 62 void DeleteGlobalRef(JNIEnv* jni, jobject o); 63 64 // Attach thread to JVM if necessary and detach at scope end if originally 65 // attached. 66 class AttachThreadScoped { 67 public: 68 explicit AttachThreadScoped(JavaVM* jvm); 69 ~AttachThreadScoped(); 70 JNIEnv* env(); 71 72 private: 73 bool attached_; 74 JavaVM* jvm_; 75 JNIEnv* env_; 76 }; 77 78 } // namespace webrtc 79 80 #endif // MODULES_UTILITY_INCLUDE_HELPERS_ANDROID_H_ 81