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 // ClassLoader.loadClass expects a classname with components separated by
163 // dots instead of the slashes that JNIEnv::FindClass expects. The JNI
164 // generator generates names with slashes, so we have to replace them here.
165 // TODO(torne): move to an approach where we always use ClassLoader except
166 // for the special case of base::android::GetClassLoader(), and change the
167 // JNI generator to generate dot-separated names. http://crbug.com/461773
168 size_t bufsize
= strlen(class_name
) + 1;
169 char dotted_name
[bufsize
];
170 memmove(dotted_name
, class_name
, bufsize
);
171 for (size_t i
= 0; i
< bufsize
; ++i
) {
172 if (dotted_name
[i
] == '/') {
173 dotted_name
[i
] = '.';
177 clazz
= static_cast<jclass
>(
178 env
->CallObjectMethod(g_class_loader
.Get().obj(),
179 g_class_loader_load_class_method_id
,
180 ConvertUTF8ToJavaString(env
, dotted_name
).obj()));
182 clazz
= env
->FindClass(class_name
);
184 CHECK(!ClearException(env
) && clazz
) << "Failed to find class " << class_name
;
185 return ScopedJavaLocalRef
<jclass
>(env
, clazz
);
190 const char* class_name
,
191 base::subtle::AtomicWord
* atomic_class_id
) {
192 COMPILE_ASSERT(sizeof(subtle::AtomicWord
) >= sizeof(jclass
),
193 AtomicWord_SmallerThan_jMethodID
);
194 subtle::AtomicWord value
= base::subtle::Acquire_Load(atomic_class_id
);
196 return reinterpret_cast<jclass
>(value
);
197 ScopedJavaGlobalRef
<jclass
> clazz
;
198 clazz
.Reset(GetClass(env
, class_name
));
199 subtle::AtomicWord null_aw
= reinterpret_cast<subtle::AtomicWord
>(NULL
);
200 subtle::AtomicWord cas_result
= base::subtle::Release_CompareAndSwap(
203 reinterpret_cast<subtle::AtomicWord
>(clazz
.obj()));
204 if (cas_result
== null_aw
) {
205 // We intentionally leak the global ref since we now storing it as a raw
206 // pointer in |atomic_class_id|.
207 return clazz
.Release();
209 return reinterpret_cast<jclass
>(cas_result
);
213 template<MethodID::Type type
>
214 jmethodID
MethodID::Get(JNIEnv
* env
,
216 const char* method_name
,
217 const char* jni_signature
) {
218 jmethodID id
= type
== TYPE_STATIC
?
219 env
->GetStaticMethodID(clazz
, method_name
, jni_signature
) :
220 env
->GetMethodID(clazz
, method_name
, jni_signature
);
221 CHECK(base::android::ClearException(env
) || id
) <<
223 (type
== TYPE_STATIC
? "static " : "") <<
224 "method " << method_name
<< " " << jni_signature
;
228 // If |atomic_method_id| set, it'll return immediately. Otherwise, it'll call
229 // into ::Get() above. If there's a race, it's ok since the values are the same
230 // (and the duplicated effort will happen only once).
231 template<MethodID::Type type
>
232 jmethodID
MethodID::LazyGet(JNIEnv
* env
,
234 const char* method_name
,
235 const char* jni_signature
,
236 base::subtle::AtomicWord
* atomic_method_id
) {
237 COMPILE_ASSERT(sizeof(subtle::AtomicWord
) >= sizeof(jmethodID
),
238 AtomicWord_SmallerThan_jMethodID
);
239 subtle::AtomicWord value
= base::subtle::Acquire_Load(atomic_method_id
);
241 return reinterpret_cast<jmethodID
>(value
);
242 jmethodID id
= MethodID::Get
<type
>(env
, clazz
, method_name
, jni_signature
);
243 base::subtle::Release_Store(
244 atomic_method_id
, reinterpret_cast<subtle::AtomicWord
>(id
));
248 // Various template instantiations.
249 template jmethodID
MethodID::Get
<MethodID::TYPE_STATIC
>(
250 JNIEnv
* env
, jclass clazz
, const char* method_name
,
251 const char* jni_signature
);
253 template jmethodID
MethodID::Get
<MethodID::TYPE_INSTANCE
>(
254 JNIEnv
* env
, jclass clazz
, const char* method_name
,
255 const char* jni_signature
);
257 template jmethodID
MethodID::LazyGet
<MethodID::TYPE_STATIC
>(
258 JNIEnv
* env
, jclass clazz
, const char* method_name
,
259 const char* jni_signature
, base::subtle::AtomicWord
* atomic_method_id
);
261 template jmethodID
MethodID::LazyGet
<MethodID::TYPE_INSTANCE
>(
262 JNIEnv
* env
, jclass clazz
, const char* method_name
,
263 const char* jni_signature
, base::subtle::AtomicWord
* atomic_method_id
);
265 bool HasException(JNIEnv
* env
) {
266 return env
->ExceptionCheck() != JNI_FALSE
;
269 bool ClearException(JNIEnv
* env
) {
270 if (!HasException(env
))
272 env
->ExceptionDescribe();
273 env
->ExceptionClear();
277 void CheckException(JNIEnv
* env
) {
278 if (!HasException(env
))
281 // Exception has been found, might as well tell breakpad about it.
282 jthrowable java_throwable
= env
->ExceptionOccurred();
283 if (java_throwable
) {
284 // Clear the pending exception, since a local reference is now held.
285 env
->ExceptionDescribe();
286 env
->ExceptionClear();
288 // Set the exception_string in BuildInfo so that breakpad can read it.
289 // RVO should avoid any extra copies of the exception string.
290 base::android::BuildInfo::GetInstance()->set_java_exception_info(
291 GetJavaExceptionInfo(env
, java_throwable
));
294 // Now, feel good about it and die.
295 CHECK(false) << "Please include Java exception stack in crash report";
298 } // namespace android