1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #include "base/android/jni_android.h"
9 #include "base/android/build_info.h"
10 #include "base/android/jni_string.h"
11 #include "base/android/jni_utils.h"
12 #include "base/lazy_instance.h"
13 #include "base/logging.h"
16 using base::android::GetClass
;
17 using base::android::MethodID
;
18 using base::android::ScopedJavaLocalRef
;
20 bool g_disable_manual_jni_registration
= false;
23 // Leak the global app context, as it is used from a non-joinable worker thread
24 // that may still be running at shutdown. There is no harm in doing this.
25 base::LazyInstance
<base::android::ScopedJavaGlobalRef
<jobject
> >::Leaky
26 g_application_context
= LAZY_INSTANCE_INITIALIZER
;
27 base::LazyInstance
<base::android::ScopedJavaGlobalRef
<jobject
> >::Leaky
28 g_class_loader
= LAZY_INSTANCE_INITIALIZER
;
29 jmethodID g_class_loader_load_class_method_id
= 0;
31 std::string
GetJavaExceptionInfo(JNIEnv
* env
, jthrowable java_throwable
) {
32 ScopedJavaLocalRef
<jclass
> throwable_clazz
=
33 GetClass(env
, "java/lang/Throwable");
34 jmethodID throwable_printstacktrace
=
35 MethodID::Get
<MethodID::TYPE_INSTANCE
>(
36 env
, throwable_clazz
.obj(), "printStackTrace",
37 "(Ljava/io/PrintStream;)V");
39 // Create an instance of ByteArrayOutputStream.
40 ScopedJavaLocalRef
<jclass
> bytearray_output_stream_clazz
=
41 GetClass(env
, "java/io/ByteArrayOutputStream");
42 jmethodID bytearray_output_stream_constructor
=
43 MethodID::Get
<MethodID::TYPE_INSTANCE
>(
44 env
, bytearray_output_stream_clazz
.obj(), "<init>", "()V");
45 jmethodID bytearray_output_stream_tostring
=
46 MethodID::Get
<MethodID::TYPE_INSTANCE
>(
47 env
, bytearray_output_stream_clazz
.obj(), "toString",
48 "()Ljava/lang/String;");
49 ScopedJavaLocalRef
<jobject
> bytearray_output_stream(env
,
50 env
->NewObject(bytearray_output_stream_clazz
.obj(),
51 bytearray_output_stream_constructor
));
53 // Create an instance of PrintStream.
54 ScopedJavaLocalRef
<jclass
> printstream_clazz
=
55 GetClass(env
, "java/io/PrintStream");
56 jmethodID printstream_constructor
=
57 MethodID::Get
<MethodID::TYPE_INSTANCE
>(
58 env
, printstream_clazz
.obj(), "<init>",
59 "(Ljava/io/OutputStream;)V");
60 ScopedJavaLocalRef
<jobject
> printstream(env
,
61 env
->NewObject(printstream_clazz
.obj(), printstream_constructor
,
62 bytearray_output_stream
.obj()));
64 // Call Throwable.printStackTrace(PrintStream)
65 env
->CallVoidMethod(java_throwable
, throwable_printstacktrace
,
68 // Call ByteArrayOutputStream.toString()
69 ScopedJavaLocalRef
<jstring
> exception_string(
70 env
, static_cast<jstring
>(
71 env
->CallObjectMethod(bytearray_output_stream
.obj(),
72 bytearray_output_stream_tostring
)));
74 return ConvertJavaStringToUTF8(exception_string
);
82 bool IsManualJniRegistrationDisabled() {
83 return g_disable_manual_jni_registration
;
86 void DisableManualJniRegistration() {
87 DCHECK(!g_disable_manual_jni_registration
);
88 g_disable_manual_jni_registration
= true;
91 JNIEnv
* AttachCurrentThread() {
94 jint ret
= g_jvm
->AttachCurrentThread(&env
, NULL
);
95 DCHECK_EQ(JNI_OK
, ret
);
99 JNIEnv
* AttachCurrentThreadWithName(const std::string
& thread_name
) {
101 JavaVMAttachArgs args
;
102 args
.version
= JNI_VERSION_1_2
;
103 args
.name
= thread_name
.c_str();
106 jint ret
= g_jvm
->AttachCurrentThread(&env
, &args
);
107 DCHECK_EQ(JNI_OK
, ret
);
111 void DetachFromVM() {
112 // Ignore the return value, if the thread is not attached, DetachCurrentThread
113 // will fail. But it is ok as the native thread may never be attached.
115 g_jvm
->DetachCurrentThread();
118 void InitVM(JavaVM
* vm
) {
123 bool IsVMInitialized() {
124 return g_jvm
!= NULL
;
127 void InitApplicationContext(JNIEnv
* env
, const JavaRef
<jobject
>& context
) {
128 if (env
->IsSameObject(g_application_context
.Get().obj(), context
.obj())) {
129 // It's safe to set the context more than once if it's the same context.
132 DCHECK(g_application_context
.Get().is_null());
133 g_application_context
.Get().Reset(context
);
136 void InitReplacementClassLoader(JNIEnv
* env
,
137 const JavaRef
<jobject
>& class_loader
) {
138 DCHECK(g_class_loader
.Get().is_null());
139 DCHECK(!class_loader
.is_null());
141 ScopedJavaLocalRef
<jclass
> class_loader_clazz
=
142 GetClass(env
, "java/lang/ClassLoader");
143 CHECK(!ClearException(env
));
144 g_class_loader_load_class_method_id
=
145 env
->GetMethodID(class_loader_clazz
.obj(),
147 "(Ljava/lang/String;)Ljava/lang/Class;");
148 CHECK(!ClearException(env
));
150 DCHECK(env
->IsInstanceOf(class_loader
.obj(), class_loader_clazz
.obj()));
151 g_class_loader
.Get().Reset(class_loader
);
154 const jobject
GetApplicationContext() {
155 DCHECK(!g_application_context
.Get().is_null());
156 return g_application_context
.Get().obj();
159 ScopedJavaLocalRef
<jclass
> GetClass(JNIEnv
* env
, const char* class_name
) {
161 if (!g_class_loader
.Get().is_null()) {
162 clazz
= static_cast<jclass
>(
163 env
->CallObjectMethod(g_class_loader
.Get().obj(),
164 g_class_loader_load_class_method_id
,
165 ConvertUTF8ToJavaString(env
, class_name
).obj()));
167 clazz
= env
->FindClass(class_name
);
169 CHECK(!ClearException(env
) && clazz
) << "Failed to find class " << class_name
;
170 return ScopedJavaLocalRef
<jclass
>(env
, clazz
);
175 const char* class_name
,
176 base::subtle::AtomicWord
* atomic_class_id
) {
177 COMPILE_ASSERT(sizeof(subtle::AtomicWord
) >= sizeof(jclass
),
178 AtomicWord_SmallerThan_jMethodID
);
179 subtle::AtomicWord value
= base::subtle::Acquire_Load(atomic_class_id
);
181 return reinterpret_cast<jclass
>(value
);
182 ScopedJavaGlobalRef
<jclass
> clazz
;
183 clazz
.Reset(GetClass(env
, class_name
));
184 subtle::AtomicWord null_aw
= reinterpret_cast<subtle::AtomicWord
>(NULL
);
185 subtle::AtomicWord cas_result
= base::subtle::Release_CompareAndSwap(
188 reinterpret_cast<subtle::AtomicWord
>(clazz
.obj()));
189 if (cas_result
== null_aw
) {
190 // We intentionally leak the global ref since we now storing it as a raw
191 // pointer in |atomic_class_id|.
192 return clazz
.Release();
194 return reinterpret_cast<jclass
>(cas_result
);
198 template<MethodID::Type type
>
199 jmethodID
MethodID::Get(JNIEnv
* env
,
201 const char* method_name
,
202 const char* jni_signature
) {
203 jmethodID id
= type
== TYPE_STATIC
?
204 env
->GetStaticMethodID(clazz
, method_name
, jni_signature
) :
205 env
->GetMethodID(clazz
, method_name
, jni_signature
);
206 CHECK(base::android::ClearException(env
) || id
) <<
208 (type
== TYPE_STATIC
? "static " : "") <<
209 "method " << method_name
<< " " << jni_signature
;
213 // If |atomic_method_id| set, it'll return immediately. Otherwise, it'll call
214 // into ::Get() above. If there's a race, it's ok since the values are the same
215 // (and the duplicated effort will happen only once).
216 template<MethodID::Type type
>
217 jmethodID
MethodID::LazyGet(JNIEnv
* env
,
219 const char* method_name
,
220 const char* jni_signature
,
221 base::subtle::AtomicWord
* atomic_method_id
) {
222 COMPILE_ASSERT(sizeof(subtle::AtomicWord
) >= sizeof(jmethodID
),
223 AtomicWord_SmallerThan_jMethodID
);
224 subtle::AtomicWord value
= base::subtle::Acquire_Load(atomic_method_id
);
226 return reinterpret_cast<jmethodID
>(value
);
227 jmethodID id
= MethodID::Get
<type
>(env
, clazz
, method_name
, jni_signature
);
228 base::subtle::Release_Store(
229 atomic_method_id
, reinterpret_cast<subtle::AtomicWord
>(id
));
233 // Various template instantiations.
234 template jmethodID
MethodID::Get
<MethodID::TYPE_STATIC
>(
235 JNIEnv
* env
, jclass clazz
, const char* method_name
,
236 const char* jni_signature
);
238 template jmethodID
MethodID::Get
<MethodID::TYPE_INSTANCE
>(
239 JNIEnv
* env
, jclass clazz
, const char* method_name
,
240 const char* jni_signature
);
242 template jmethodID
MethodID::LazyGet
<MethodID::TYPE_STATIC
>(
243 JNIEnv
* env
, jclass clazz
, const char* method_name
,
244 const char* jni_signature
, base::subtle::AtomicWord
* atomic_method_id
);
246 template jmethodID
MethodID::LazyGet
<MethodID::TYPE_INSTANCE
>(
247 JNIEnv
* env
, jclass clazz
, const char* method_name
,
248 const char* jni_signature
, base::subtle::AtomicWord
* atomic_method_id
);
250 bool HasException(JNIEnv
* env
) {
251 return env
->ExceptionCheck() != JNI_FALSE
;
254 bool ClearException(JNIEnv
* env
) {
255 if (!HasException(env
))
257 env
->ExceptionDescribe();
258 env
->ExceptionClear();
262 void CheckException(JNIEnv
* env
) {
263 if (!HasException(env
))
266 // Exception has been found, might as well tell breakpad about it.
267 jthrowable java_throwable
= env
->ExceptionOccurred();
268 if (java_throwable
) {
269 // Clear the pending exception, since a local reference is now held.
270 env
->ExceptionDescribe();
271 env
->ExceptionClear();
273 // Set the exception_string in BuildInfo so that breakpad can read it.
274 // RVO should avoid any extra copies of the exception string.
275 base::android::BuildInfo::GetInstance()->set_java_exception_info(
276 GetJavaExceptionInfo(env
, java_throwable
));
279 // Now, feel good about it and die.
280 CHECK(false) << "Please include Java exception stack in crash report";
283 } // namespace android