1 // Copyright 2012 The Chromium Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "base/android/jni_android.h"
6
7 #include <stddef.h>
8 #include <sys/prctl.h>
9
10 #include "base/android/java_exception_reporter.h"
11 #include "base/android/jni_string.h"
12 #include "base/android/jni_utils.h"
13 #include "base/android_runtime_jni_headers/Throwable_jni.h"
14 #include "base/base_jni/JniAndroid_jni.h"
15 #include "base/debug/debugging_buildflags.h"
16 #include "base/feature_list.h"
17 #include "base/logging.h"
18 #include "build/build_config.h"
19 #include "third_party/abseil-cpp/absl/base/attributes.h"
20
21 namespace base {
22 namespace android {
23 namespace {
24
25 // If disabled, we LOG(FATAL) immediately in native code when faced with an
26 // uncaught Java exception (historical behavior). If enabled, we give the Java
27 // uncaught exception handler a chance to handle the exception first, so that
28 // the crash is (hopefully) seen as a Java crash, not a native crash.
29 // TODO(https://crbug.com/1426888): remove this switch once we are confident the
30 // new behavior is fine.
31 BASE_FEATURE(kHandleExceptionsInJava,
32 "HandleJniExceptionsInJava",
33 base::FEATURE_ENABLED_BY_DEFAULT);
34
35 JavaVM* g_jvm = nullptr;
36 jobject g_class_loader = nullptr;
37 jclass g_out_of_memory_error_class = nullptr;
38 jmethodID g_class_loader_load_class_method_id = nullptr;
39
GetClassInternal(JNIEnv * env,const char * class_name,jobject class_loader)40 ScopedJavaLocalRef<jclass> GetClassInternal(JNIEnv* env,
41 const char* class_name,
42 jobject class_loader) {
43 jclass clazz;
44 if (class_loader != nullptr) {
45 // ClassLoader.loadClass expects a classname with components separated by
46 // dots instead of the slashes that JNIEnv::FindClass expects. The JNI
47 // generator generates names with slashes, so we have to replace them here.
48 // TODO(torne): move to an approach where we always use ClassLoader except
49 // for the special case of base::android::GetClassLoader(), and change the
50 // JNI generator to generate dot-separated names. http://crbug.com/461773
51 size_t bufsize = strlen(class_name) + 1;
52 char dotted_name[bufsize];
53 memmove(dotted_name, class_name, bufsize);
54 for (size_t i = 0; i < bufsize; ++i) {
55 if (dotted_name[i] == '/') {
56 dotted_name[i] = '.';
57 }
58 }
59
60 clazz = static_cast<jclass>(
61 env->CallObjectMethod(class_loader, g_class_loader_load_class_method_id,
62 ConvertUTF8ToJavaString(env, dotted_name).obj()));
63 } else {
64 clazz = env->FindClass(class_name);
65 }
66 if (ClearException(env) || !clazz) {
67 LOG(FATAL) << "Failed to find class " << class_name;
68 }
69 return ScopedJavaLocalRef<jclass>(env, clazz);
70 }
71
72 } // namespace
73
AttachCurrentThread()74 JNIEnv* AttachCurrentThread() {
75 DCHECK(g_jvm);
76 JNIEnv* env = nullptr;
77 jint ret = g_jvm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_2);
78 if (ret == JNI_EDETACHED || !env) {
79 JavaVMAttachArgs args;
80 args.version = JNI_VERSION_1_2;
81 args.group = nullptr;
82
83 // 16 is the maximum size for thread names on Android.
84 char thread_name[16];
85 int err = prctl(PR_GET_NAME, thread_name);
86 if (err < 0) {
87 DPLOG(ERROR) << "prctl(PR_GET_NAME)";
88 args.name = nullptr;
89 } else {
90 args.name = thread_name;
91 }
92
93 #if BUILDFLAG(IS_ANDROID)
94 ret = g_jvm->AttachCurrentThread(&env, &args);
95 #else
96 ret = g_jvm->AttachCurrentThread(reinterpret_cast<void**>(&env), &args);
97 #endif
98 CHECK_EQ(JNI_OK, ret);
99 }
100 return env;
101 }
102
AttachCurrentThreadWithName(const std::string & thread_name)103 JNIEnv* AttachCurrentThreadWithName(const std::string& thread_name) {
104 DCHECK(g_jvm);
105 JavaVMAttachArgs args;
106 args.version = JNI_VERSION_1_2;
107 args.name = const_cast<char*>(thread_name.c_str());
108 args.group = nullptr;
109 JNIEnv* env = nullptr;
110 #if BUILDFLAG(IS_ANDROID)
111 jint ret = g_jvm->AttachCurrentThread(&env, &args);
112 #else
113 jint ret = g_jvm->AttachCurrentThread(reinterpret_cast<void**>(&env), &args);
114 #endif
115 CHECK_EQ(JNI_OK, ret);
116 return env;
117 }
118
DetachFromVM()119 void DetachFromVM() {
120 // Ignore the return value, if the thread is not attached, DetachCurrentThread
121 // will fail. But it is ok as the native thread may never be attached.
122 if (g_jvm)
123 g_jvm->DetachCurrentThread();
124 }
125
InitVM(JavaVM * vm)126 void InitVM(JavaVM* vm) {
127 DCHECK(!g_jvm || g_jvm == vm);
128 g_jvm = vm;
129 JNIEnv* env = base::android::AttachCurrentThread();
130 g_out_of_memory_error_class = static_cast<jclass>(
131 env->NewGlobalRef(env->FindClass("java/lang/OutOfMemoryError")));
132 DCHECK(g_out_of_memory_error_class);
133 }
134
IsVMInitialized()135 bool IsVMInitialized() {
136 return g_jvm != nullptr;
137 }
138
GetVM()139 JavaVM* GetVM() {
140 return g_jvm;
141 }
142
DisableJvmForTesting()143 void DisableJvmForTesting() {
144 g_jvm = nullptr;
145 }
146
InitGlobalClassLoader(JNIEnv * env)147 void InitGlobalClassLoader(JNIEnv* env) {
148 DCHECK(g_class_loader == nullptr);
149
150 ScopedJavaLocalRef<jclass> class_loader_clazz =
151 GetClass(env, "java/lang/ClassLoader");
152 CHECK(!ClearException(env));
153 g_class_loader_load_class_method_id =
154 env->GetMethodID(class_loader_clazz.obj(),
155 "loadClass",
156 "(Ljava/lang/String;)Ljava/lang/Class;");
157 CHECK(!ClearException(env));
158
159 // GetClassLoader() caches the reference, so we do not need to wrap it in a
160 // smart pointer as well.
161 g_class_loader = GetClassLoader(env);
162 }
163
GetClass(JNIEnv * env,const char * class_name,const char * split_name)164 ScopedJavaLocalRef<jclass> GetClass(JNIEnv* env,
165 const char* class_name,
166 const char* split_name) {
167 return GetClassInternal(env, class_name,
168 GetSplitClassLoader(env, split_name));
169 }
170
GetClass(JNIEnv * env,const char * class_name)171 ScopedJavaLocalRef<jclass> GetClass(JNIEnv* env, const char* class_name) {
172 return GetClassInternal(env, class_name, g_class_loader);
173 }
174
175 // This is duplicated with LazyGetClass below because these are performance
176 // sensitive.
LazyGetClass(JNIEnv * env,const char * class_name,const char * split_name,std::atomic<jclass> * atomic_class_id)177 jclass LazyGetClass(JNIEnv* env,
178 const char* class_name,
179 const char* split_name,
180 std::atomic<jclass>* atomic_class_id) {
181 const jclass value = atomic_class_id->load(std::memory_order_acquire);
182 if (value)
183 return value;
184 ScopedJavaGlobalRef<jclass> clazz;
185 clazz.Reset(GetClass(env, class_name, split_name));
186 jclass cas_result = nullptr;
187 if (atomic_class_id->compare_exchange_strong(cas_result, clazz.obj(),
188 std::memory_order_acq_rel)) {
189 // We intentionally leak the global ref since we now storing it as a raw
190 // pointer in |atomic_class_id|.
191 return clazz.Release();
192 } else {
193 return cas_result;
194 }
195 }
196
197 // This is duplicated with LazyGetClass above because these are performance
198 // sensitive.
LazyGetClass(JNIEnv * env,const char * class_name,std::atomic<jclass> * atomic_class_id)199 jclass LazyGetClass(JNIEnv* env,
200 const char* class_name,
201 std::atomic<jclass>* atomic_class_id) {
202 const jclass value = atomic_class_id->load(std::memory_order_acquire);
203 if (value)
204 return value;
205 ScopedJavaGlobalRef<jclass> clazz;
206 clazz.Reset(GetClass(env, class_name));
207 jclass cas_result = nullptr;
208 if (atomic_class_id->compare_exchange_strong(cas_result, clazz.obj(),
209 std::memory_order_acq_rel)) {
210 // We intentionally leak the global ref since we now storing it as a raw
211 // pointer in |atomic_class_id|.
212 return clazz.Release();
213 } else {
214 return cas_result;
215 }
216 }
217
218 template<MethodID::Type type>
Get(JNIEnv * env,jclass clazz,const char * method_name,const char * jni_signature)219 jmethodID MethodID::Get(JNIEnv* env,
220 jclass clazz,
221 const char* method_name,
222 const char* jni_signature) {
223 auto get_method_ptr = type == MethodID::TYPE_STATIC ?
224 &JNIEnv::GetStaticMethodID :
225 &JNIEnv::GetMethodID;
226 jmethodID id = (env->*get_method_ptr)(clazz, method_name, jni_signature);
227 if (base::android::ClearException(env) || !id) {
228 LOG(FATAL) << "Failed to find " <<
229 (type == TYPE_STATIC ? "static " : "") <<
230 "method " << method_name << " " << jni_signature;
231 }
232 return id;
233 }
234
235 // If |atomic_method_id| set, it'll return immediately. Otherwise, it'll call
236 // into ::Get() above. If there's a race, it's ok since the values are the same
237 // (and the duplicated effort will happen only once).
238 template <MethodID::Type type>
LazyGet(JNIEnv * env,jclass clazz,const char * method_name,const char * jni_signature,std::atomic<jmethodID> * atomic_method_id)239 jmethodID MethodID::LazyGet(JNIEnv* env,
240 jclass clazz,
241 const char* method_name,
242 const char* jni_signature,
243 std::atomic<jmethodID>* atomic_method_id) {
244 const jmethodID value = atomic_method_id->load(std::memory_order_acquire);
245 if (value)
246 return value;
247 jmethodID id = MethodID::Get<type>(env, clazz, method_name, jni_signature);
248 atomic_method_id->store(id, std::memory_order_release);
249 return id;
250 }
251
252 // Various template instantiations.
253 template jmethodID MethodID::Get<MethodID::TYPE_STATIC>(
254 JNIEnv* env, jclass clazz, const char* method_name,
255 const char* jni_signature);
256
257 template jmethodID MethodID::Get<MethodID::TYPE_INSTANCE>(
258 JNIEnv* env, jclass clazz, const char* method_name,
259 const char* jni_signature);
260
261 template jmethodID MethodID::LazyGet<MethodID::TYPE_STATIC>(
262 JNIEnv* env, jclass clazz, const char* method_name,
263 const char* jni_signature, std::atomic<jmethodID>* atomic_method_id);
264
265 template jmethodID MethodID::LazyGet<MethodID::TYPE_INSTANCE>(
266 JNIEnv* env, jclass clazz, const char* method_name,
267 const char* jni_signature, std::atomic<jmethodID>* atomic_method_id);
268
HasException(JNIEnv * env)269 bool HasException(JNIEnv* env) {
270 return env->ExceptionCheck() != JNI_FALSE;
271 }
272
ClearException(JNIEnv * env)273 bool ClearException(JNIEnv* env) {
274 if (!HasException(env))
275 return false;
276 env->ExceptionDescribe();
277 env->ExceptionClear();
278 return true;
279 }
280
CheckException(JNIEnv * env)281 void CheckException(JNIEnv* env) {
282 if (!HasException(env))
283 return;
284
285 static thread_local bool g_reentering = false;
286 if (g_reentering) {
287 // We were handling an uncaught Java exception already, but one of the Java
288 // methods we called below threw another exception. (This is unlikely to
289 // happen as we are careful to never throw from these methods, but we can't
290 // rule it out entirely as the JVM itself may throw - think
291 // OutOfMemoryError, for example.)
292 env->ExceptionDescribe();
293 jthrowable raw_throwable = env->ExceptionOccurred();
294 env->ExceptionClear();
295 jclass clazz = env->GetObjectClass(raw_throwable);
296 bool is_oom_error = env->IsSameObject(clazz, g_out_of_memory_error_class);
297 env->Throw(raw_throwable); // Ensure we don't re-enter Java.
298
299 if (is_oom_error) {
300 constexpr char kMessage[] =
301 "While handling an uncaught Java exception, an OutOfMemoryError "
302 "occurred.";
303 base::android::SetJavaException(kMessage);
304 // Use different LOG(FATAL) statements to ensure unique stack traces.
305 LOG(FATAL) << kMessage;
306 } else {
307 constexpr char kMessage[] =
308 "While handling an uncaught Java exception, another exception "
309 "occurred.";
310 base::android::SetJavaException(kMessage);
311 LOG(FATAL) << kMessage;
312 }
313 }
314 g_reentering = true;
315
316 // Log a message to ensure there is something in the log even if the rest of
317 // this function goes horribly wrong, and also to provide a convenient marker
318 // in the log for where Java exception crash information starts.
319 LOG(ERROR) << "Crashing due to uncaught Java exception";
320
321 const bool handle_exception_in_java =
322 base::FeatureList::IsEnabled(kHandleExceptionsInJava);
323
324 if (!handle_exception_in_java) {
325 env->ExceptionDescribe();
326 }
327
328 // We cannot use `ScopedJavaLocalRef` directly because that ends up calling
329 // env->GetObjectRefType() when DCHECK is on, and that call is not allowed
330 // with a pending exception according to the JNI spec.
331 jthrowable raw_throwable = env->ExceptionOccurred();
332 // Now that we saved the reference to the throwable, clear the exception.
333 //
334 // We need to do this as early as possible to remove the risk that code below
335 // might accidentally call back into Java, which is not allowed when `env`
336 // has an exception set, per the JNI spec. (For example, LOG(FATAL) doesn't
337 // work with a JNI exception set, because it calls
338 // GetJavaStackTraceIfPresent()).
339 env->ExceptionClear();
340 // The reference returned by `ExceptionOccurred()` is a local reference.
341 // `ExceptionClear()` merely removes the exception information from `env`;
342 // it doesn't delete the reference, which is why this call is valid.
343 auto throwable = ScopedJavaLocalRef<jthrowable>::Adopt(env, raw_throwable);
344
345 if (!handle_exception_in_java) {
346 base::android::SetJavaException(
347 GetJavaExceptionInfo(env, throwable).c_str());
348 LOG(FATAL)
349 << "Uncaught Java exception in native code. Please include the Java "
350 "exception stack from the Android log in your crash report.";
351 }
352
353 // We don't need to call SetJavaException() in this branch because we
354 // expect handleException() to eventually call JavaExceptionReporter through
355 // the global uncaught exception handler.
356
357 const std::string native_stack_trace = base::debug::StackTrace().ToString();
358 LOG(ERROR) << "Native stack trace:" << std::endl << native_stack_trace;
359
360 ScopedJavaLocalRef<jthrowable> secondary_exception =
361 Java_JniAndroid_handleException(
362 env, throwable, ConvertUTF8ToJavaString(env, native_stack_trace));
363
364 // Ideally handleException() should have terminated the process and we should
365 // not get here. This can happen in the case of OutOfMemoryError or if the
366 // app that embedded WebView installed an exception handler that does not
367 // terminate, or itself threw an exception. We cannot be confident that
368 // JavaExceptionReporter ran, so set the java exception explicitly.
369 base::android::SetJavaException(
370 GetJavaExceptionInfo(
371 env, secondary_exception ? secondary_exception : throwable)
372 .c_str());
373 LOG(FATAL)
374 << "Uncaught Java exception in native code, and the Java uncaught "
375 "exception handler did not terminate the process. Please include the "
376 "Java exception stack from the Android log in your crash report.";
377 }
378
GetJavaExceptionInfo(JNIEnv * env,const JavaRef<jthrowable> & throwable)379 std::string GetJavaExceptionInfo(JNIEnv* env,
380 const JavaRef<jthrowable>& throwable) {
381 ScopedJavaLocalRef<jstring> sanitized_exception_string =
382 Java_JniAndroid_sanitizedStacktraceForUnhandledException(env, throwable);
383 // Returns null when PiiElider results in an OutOfMemoryError.
384 return sanitized_exception_string
385 ? ConvertJavaStringToUTF8(sanitized_exception_string)
386 : "Unable to obtain Java stack trace due to OutOfMemoryError";
387 }
388
GetJavaStackTraceIfPresent()389 std::string GetJavaStackTraceIfPresent() {
390 JNIEnv* env = nullptr;
391 if (g_jvm) {
392 g_jvm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_2);
393 }
394 if (!env) {
395 // JNI has not been initialized on this thread.
396 return {};
397 }
398
399 if (HasException(env)) {
400 // This can happen if CheckException() is being re-entered, decided to
401 // LOG(FATAL) immediately, and LOG(FATAL) itself is calling us. In that case
402 // it is imperative that we don't try to call Java again.
403 return "Unable to retrieve Java caller stack trace as the exception "
404 "handler is being re-entered";
405 }
406
407 ScopedJavaLocalRef<jthrowable> throwable =
408 JNI_Throwable::Java_Throwable_Constructor(env);
409 std::string ret = GetJavaExceptionInfo(env, throwable);
410 // Strip the exception message and leave only the "at" lines. Example:
411 // java.lang.Throwable:
412 // {tab}at Clazz.method(Clazz.java:111)
413 // {tab}at ...
414 size_t newline_idx = ret.find('\n');
415 if (newline_idx == std::string::npos) {
416 // There are no java frames.
417 return {};
418 }
419 return ret.substr(newline_idx + 1);
420 }
421
422 } // namespace android
423 } // namespace base
424