blob: 598e88472cc3eb209b20ec233478a564b114f22d [file] [log] [blame]
[email protected]9fc44162012-01-23 22:56:411// Copyright (c) 2012 The Chromium Authors. All rights reserved.
[email protected]61c86c62011-08-02 16:11:162// 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
avib30f2402015-12-24 03:43:287#include <stddef.h>
erikchen011ad3f2018-01-26 17:54:558#include <sys/prctl.h>
avib30f2402015-12-24 03:43:289
[email protected]96e7ade2011-12-05 14:42:0810#include <map>
11
Joshua Peraza7814da22018-07-10 21:37:5012#include "base/android/java_exception_reporter.h"
[email protected]1b46a532012-05-23 05:59:4913#include "base/android/jni_string.h"
Scott Violet44165792018-02-22 02:08:0814#include "base/debug/debugging_buildflags.h"
[email protected]96e7ade2011-12-05 14:42:0815#include "base/lazy_instance.h"
[email protected]61c86c62011-08-02 16:11:1616#include "base/logging.h"
dskibaa8c951e2016-10-25 23:39:1117#include "base/threading/thread_local.h"
[email protected]61c86c62011-08-02 16:11:1618
19namespace {
[email protected]1b46a532012-05-23 05:59:4920using base::android::GetClass;
[email protected]c410a2cb2012-10-16 18:35:1021using base::android::MethodID;
[email protected]1b46a532012-05-23 05:59:4922using base::android::ScopedJavaLocalRef;
[email protected]fe0f1ab2012-02-09 21:02:2723
[email protected]995a3ff2012-09-17 06:15:1024JavaVM* g_jvm = NULL;
scottmg5e65e3a2017-03-08 08:48:4625base::LazyInstance<base::android::ScopedJavaGlobalRef<jobject>>::Leaky
[email protected]d30dd6e2014-08-21 16:37:3226 g_class_loader = LAZY_INSTANCE_INITIALIZER;
27jmethodID g_class_loader_load_class_method_id = 0;
[email protected]96e7ade2011-12-05 14:42:0828
erikchenf7c8a0d2017-04-06 21:15:2729#if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
dskibaa8c951e2016-10-25 23:39:1130base::LazyInstance<base::ThreadLocalPointer<void>>::Leaky
31 g_stack_frame_pointer = LAZY_INSTANCE_INITIALIZER;
32#endif
33
Xianzhu Wangab2f3662018-02-09 22:02:2634bool g_fatal_exception_occurred = false;
35
[email protected]1b46a532012-05-23 05:59:4936} // namespace
[email protected]61c86c62011-08-02 16:11:1637
38namespace base {
39namespace android {
40
41JNIEnv* AttachCurrentThread() {
[email protected]7a3b0e42012-10-09 19:43:1042 DCHECK(g_jvm);
erikchen011ad3f2018-01-26 17:54:5543 JNIEnv* env = nullptr;
44 jint ret = g_jvm->GetEnv(reinterpret_cast<void**>(&env), JNI_VERSION_1_2);
45 if (ret == JNI_EDETACHED || !env) {
46 JavaVMAttachArgs args;
47 args.version = JNI_VERSION_1_2;
48 args.group = nullptr;
49
50 // 16 is the maximum size for thread names on Android.
51 char thread_name[16];
52 int err = prctl(PR_GET_NAME, thread_name);
53 if (err < 0) {
54 DPLOG(ERROR) << "prctl(PR_GET_NAME)";
55 args.name = nullptr;
56 } else {
57 args.name = thread_name;
58 }
59
60 ret = g_jvm->AttachCurrentThread(&env, &args);
61 DCHECK_EQ(JNI_OK, ret);
62 }
[email protected]61c86c62011-08-02 16:11:1663 return env;
64}
65
[email protected]f3225bdb2014-06-20 00:38:1966JNIEnv* AttachCurrentThreadWithName(const std::string& thread_name) {
67 DCHECK(g_jvm);
68 JavaVMAttachArgs args;
69 args.version = JNI_VERSION_1_2;
70 args.name = thread_name.c_str();
71 args.group = NULL;
72 JNIEnv* env = NULL;
73 jint ret = g_jvm->AttachCurrentThread(&env, &args);
74 DCHECK_EQ(JNI_OK, ret);
75 return env;
76}
77
[email protected]61c86c62011-08-02 16:11:1678void DetachFromVM() {
79 // Ignore the return value, if the thread is not attached, DetachCurrentThread
80 // will fail. But it is ok as the native thread may never be attached.
[email protected]691b2002014-01-07 19:51:3781 if (g_jvm)
[email protected]61c86c62011-08-02 16:11:1682 g_jvm->DetachCurrentThread();
83}
84
85void InitVM(JavaVM* vm) {
michaelbai25ec25c2015-10-22 19:40:2286 DCHECK(!g_jvm || g_jvm == vm);
[email protected]61c86c62011-08-02 16:11:1687 g_jvm = vm;
88}
89
[email protected]2e944632013-08-21 17:59:4290bool IsVMInitialized() {
91 return g_jvm != NULL;
92}
93
[email protected]d30dd6e2014-08-21 16:37:3294void InitReplacementClassLoader(JNIEnv* env,
95 const JavaRef<jobject>& class_loader) {
96 DCHECK(g_class_loader.Get().is_null());
97 DCHECK(!class_loader.is_null());
98
99 ScopedJavaLocalRef<jclass> class_loader_clazz =
100 GetClass(env, "java/lang/ClassLoader");
101 CHECK(!ClearException(env));
102 g_class_loader_load_class_method_id =
103 env->GetMethodID(class_loader_clazz.obj(),
104 "loadClass",
105 "(Ljava/lang/String;)Ljava/lang/Class;");
106 CHECK(!ClearException(env));
107
108 DCHECK(env->IsInstanceOf(class_loader.obj(), class_loader_clazz.obj()));
109 g_class_loader.Get().Reset(class_loader);
110}
111
[email protected]fe0f1ab2012-02-09 21:02:27112ScopedJavaLocalRef<jclass> GetClass(JNIEnv* env, const char* class_name) {
[email protected]d30dd6e2014-08-21 16:37:32113 jclass clazz;
114 if (!g_class_loader.Get().is_null()) {
tornec16354c2015-03-16 22:53:33115 // ClassLoader.loadClass expects a classname with components separated by
116 // dots instead of the slashes that JNIEnv::FindClass expects. The JNI
117 // generator generates names with slashes, so we have to replace them here.
118 // TODO(torne): move to an approach where we always use ClassLoader except
119 // for the special case of base::android::GetClassLoader(), and change the
120 // JNI generator to generate dot-separated names. http://crbug.com/461773
121 size_t bufsize = strlen(class_name) + 1;
122 char dotted_name[bufsize];
123 memmove(dotted_name, class_name, bufsize);
124 for (size_t i = 0; i < bufsize; ++i) {
125 if (dotted_name[i] == '/') {
126 dotted_name[i] = '.';
127 }
128 }
129
[email protected]d30dd6e2014-08-21 16:37:32130 clazz = static_cast<jclass>(
131 env->CallObjectMethod(g_class_loader.Get().obj(),
132 g_class_loader_load_class_method_id,
tornec16354c2015-03-16 22:53:33133 ConvertUTF8ToJavaString(env, dotted_name).obj()));
[email protected]d30dd6e2014-08-21 16:37:32134 } else {
135 clazz = env->FindClass(class_name);
136 }
yfriedmane524fe72016-05-05 19:51:38137 if (ClearException(env) || !clazz) {
138 LOG(FATAL) << "Failed to find class " << class_name;
139 }
[email protected]c7c2b462013-04-10 02:44:55140 return ScopedJavaLocalRef<jclass>(env, clazz);
[email protected]fe0f1ab2012-02-09 21:02:27141}
142
[email protected]d30dd6e2014-08-21 16:37:32143jclass LazyGetClass(
144 JNIEnv* env,
145 const char* class_name,
Oleh Prypin54f759312018-08-02 14:33:32146 std::atomic<jclass>* atomic_class_id) {
147 const jclass value = std::atomic_load(atomic_class_id);
[email protected]d30dd6e2014-08-21 16:37:32148 if (value)
Oleh Prypin54f759312018-08-02 14:33:32149 return value;
[email protected]d30dd6e2014-08-21 16:37:32150 ScopedJavaGlobalRef<jclass> clazz;
151 clazz.Reset(GetClass(env, class_name));
Oleh Prypin54f759312018-08-02 14:33:32152 jclass cas_result = nullptr;
153 if (std::atomic_compare_exchange_strong(atomic_class_id, &cas_result,
154 clazz.obj())) {
[email protected]d30dd6e2014-08-21 16:37:32155 // We intentionally leak the global ref since we now storing it as a raw
156 // pointer in |atomic_class_id|.
157 return clazz.Release();
158 } else {
Oleh Prypin54f759312018-08-02 14:33:32159 return cas_result;
[email protected]d30dd6e2014-08-21 16:37:32160 }
161}
162
[email protected]c410a2cb2012-10-16 18:35:10163template<MethodID::Type type>
164jmethodID MethodID::Get(JNIEnv* env,
165 jclass clazz,
166 const char* method_name,
167 const char* jni_signature) {
Oleh Prypin54f759312018-08-02 14:33:32168 auto get_method_ptr = type == MethodID::TYPE_STATIC ?
169 &JNIEnv::GetStaticMethodID :
170 &JNIEnv::GetMethodID;
171 jmethodID id = (env->*get_method_ptr)(clazz, method_name, jni_signature);
yfriedmane524fe72016-05-05 19:51:38172 if (base::android::ClearException(env) || !id) {
173 LOG(FATAL) << "Failed to find " <<
174 (type == TYPE_STATIC ? "static " : "") <<
175 "method " << method_name << " " << jni_signature;
176 }
[email protected]c410a2cb2012-10-16 18:35:10177 return id;
[email protected]fae37d62012-03-08 12:39:13178}
179
[email protected]c410a2cb2012-10-16 18:35:10180// If |atomic_method_id| set, it'll return immediately. Otherwise, it'll call
181// into ::Get() above. If there's a race, it's ok since the values are the same
182// (and the duplicated effort will happen only once).
183template<MethodID::Type type>
184jmethodID MethodID::LazyGet(JNIEnv* env,
[email protected]3764dddb2012-10-02 21:13:55185 jclass clazz,
186 const char* method_name,
[email protected]c410a2cb2012-10-16 18:35:10187 const char* jni_signature,
Oleh Prypin54f759312018-08-02 14:33:32188 std::atomic<jmethodID>* atomic_method_id) {
189 const jmethodID value = std::atomic_load(atomic_method_id);
[email protected]c410a2cb2012-10-16 18:35:10190 if (value)
Oleh Prypin54f759312018-08-02 14:33:32191 return value;
[email protected]c410a2cb2012-10-16 18:35:10192 jmethodID id = MethodID::Get<type>(env, clazz, method_name, jni_signature);
Oleh Prypin54f759312018-08-02 14:33:32193 std::atomic_store(atomic_method_id, id);
[email protected]c410a2cb2012-10-16 18:35:10194 return id;
[email protected]fe0f1ab2012-02-09 21:02:27195}
196
[email protected]c410a2cb2012-10-16 18:35:10197// Various template instantiations.
198template jmethodID MethodID::Get<MethodID::TYPE_STATIC>(
199 JNIEnv* env, jclass clazz, const char* method_name,
200 const char* jni_signature);
[email protected]fae37d62012-03-08 12:39:13201
[email protected]c410a2cb2012-10-16 18:35:10202template jmethodID MethodID::Get<MethodID::TYPE_INSTANCE>(
203 JNIEnv* env, jclass clazz, const char* method_name,
204 const char* jni_signature);
[email protected]3764dddb2012-10-02 21:13:55205
[email protected]c410a2cb2012-10-16 18:35:10206template jmethodID MethodID::LazyGet<MethodID::TYPE_STATIC>(
207 JNIEnv* env, jclass clazz, const char* method_name,
Oleh Prypin54f759312018-08-02 14:33:32208 const char* jni_signature, std::atomic<jmethodID>* atomic_method_id);
[email protected]fe0f1ab2012-02-09 21:02:27209
[email protected]c410a2cb2012-10-16 18:35:10210template jmethodID MethodID::LazyGet<MethodID::TYPE_INSTANCE>(
211 JNIEnv* env, jclass clazz, const char* method_name,
Oleh Prypin54f759312018-08-02 14:33:32212 const char* jni_signature, std::atomic<jmethodID>* atomic_method_id);
[email protected]fe0f1ab2012-02-09 21:02:27213
[email protected]fe0f1ab2012-02-09 21:02:27214bool HasException(JNIEnv* env) {
215 return env->ExceptionCheck() != JNI_FALSE;
[email protected]61c86c62011-08-02 16:11:16216}
217
[email protected]fe0f1ab2012-02-09 21:02:27218bool ClearException(JNIEnv* env) {
219 if (!HasException(env))
[email protected]61c86c62011-08-02 16:11:16220 return false;
[email protected]1b46a532012-05-23 05:59:49221 env->ExceptionDescribe();
[email protected]61c86c62011-08-02 16:11:16222 env->ExceptionClear();
223 return true;
224}
225
[email protected]fe0f1ab2012-02-09 21:02:27226void CheckException(JNIEnv* env) {
[email protected]909193c2014-06-28 01:58:04227 if (!HasException(env))
228 return;
[email protected]1b46a532012-05-23 05:59:49229
[email protected]1b46a532012-05-23 05:59:49230 jthrowable java_throwable = env->ExceptionOccurred();
[email protected]909193c2014-06-28 01:58:04231 if (java_throwable) {
232 // Clear the pending exception, since a local reference is now held.
233 env->ExceptionDescribe();
234 env->ExceptionClear();
235
Xianzhu Wangab2f3662018-02-09 22:02:26236 if (g_fatal_exception_occurred) {
237 // Another exception (probably OOM) occurred during GetJavaExceptionInfo.
Joshua Peraza7814da22018-07-10 21:37:50238 base::android::SetJavaException(
Xianzhu Wangab2f3662018-02-09 22:02:26239 "Java OOM'ed in exception handling, check logcat");
240 } else {
241 g_fatal_exception_occurred = true;
Xianzhu Wangab2f3662018-02-09 22:02:26242 // RVO should avoid any extra copies of the exception string.
Joshua Peraza7814da22018-07-10 21:37:50243 base::android::SetJavaException(
244 GetJavaExceptionInfo(env, java_throwable).c_str());
Xianzhu Wangab2f3662018-02-09 22:02:26245 }
[email protected]fe0f1ab2012-02-09 21:02:27246 }
[email protected]1b46a532012-05-23 05:59:49247
[email protected]1b46a532012-05-23 05:59:49248 // Now, feel good about it and die.
yfriedmane524fe72016-05-05 19:51:38249 LOG(FATAL) << "Please include Java exception stack in crash report";
[email protected]fe0f1ab2012-02-09 21:02:27250}
251
cjhopman060e0072015-05-06 21:37:48252std::string GetJavaExceptionInfo(JNIEnv* env, jthrowable java_throwable) {
253 ScopedJavaLocalRef<jclass> throwable_clazz =
254 GetClass(env, "java/lang/Throwable");
255 jmethodID throwable_printstacktrace =
256 MethodID::Get<MethodID::TYPE_INSTANCE>(
257 env, throwable_clazz.obj(), "printStackTrace",
258 "(Ljava/io/PrintStream;)V");
259
260 // Create an instance of ByteArrayOutputStream.
261 ScopedJavaLocalRef<jclass> bytearray_output_stream_clazz =
262 GetClass(env, "java/io/ByteArrayOutputStream");
263 jmethodID bytearray_output_stream_constructor =
264 MethodID::Get<MethodID::TYPE_INSTANCE>(
265 env, bytearray_output_stream_clazz.obj(), "<init>", "()V");
266 jmethodID bytearray_output_stream_tostring =
267 MethodID::Get<MethodID::TYPE_INSTANCE>(
268 env, bytearray_output_stream_clazz.obj(), "toString",
269 "()Ljava/lang/String;");
270 ScopedJavaLocalRef<jobject> bytearray_output_stream(env,
271 env->NewObject(bytearray_output_stream_clazz.obj(),
272 bytearray_output_stream_constructor));
Xianzhu Wangab2f3662018-02-09 22:02:26273 CheckException(env);
cjhopman060e0072015-05-06 21:37:48274
275 // Create an instance of PrintStream.
276 ScopedJavaLocalRef<jclass> printstream_clazz =
277 GetClass(env, "java/io/PrintStream");
278 jmethodID printstream_constructor =
279 MethodID::Get<MethodID::TYPE_INSTANCE>(
280 env, printstream_clazz.obj(), "<init>",
281 "(Ljava/io/OutputStream;)V");
282 ScopedJavaLocalRef<jobject> printstream(env,
283 env->NewObject(printstream_clazz.obj(), printstream_constructor,
284 bytearray_output_stream.obj()));
Xianzhu Wangab2f3662018-02-09 22:02:26285 CheckException(env);
cjhopman060e0072015-05-06 21:37:48286
287 // Call Throwable.printStackTrace(PrintStream)
288 env->CallVoidMethod(java_throwable, throwable_printstacktrace,
289 printstream.obj());
Xianzhu Wangab2f3662018-02-09 22:02:26290 CheckException(env);
cjhopman060e0072015-05-06 21:37:48291
292 // Call ByteArrayOutputStream.toString()
293 ScopedJavaLocalRef<jstring> exception_string(
294 env, static_cast<jstring>(
295 env->CallObjectMethod(bytearray_output_stream.obj(),
296 bytearray_output_stream_tostring)));
Xianzhu Wangab2f3662018-02-09 22:02:26297 CheckException(env);
cjhopman060e0072015-05-06 21:37:48298
299 return ConvertJavaStringToUTF8(exception_string);
300}
301
erikchenf7c8a0d2017-04-06 21:15:27302#if BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
dskibaa8c951e2016-10-25 23:39:11303
304JNIStackFrameSaver::JNIStackFrameSaver(void* current_fp) {
305 previous_fp_ = g_stack_frame_pointer.Pointer()->Get();
306 g_stack_frame_pointer.Pointer()->Set(current_fp);
307}
308
309JNIStackFrameSaver::~JNIStackFrameSaver() {
310 g_stack_frame_pointer.Pointer()->Set(previous_fp_);
311}
312
313void* JNIStackFrameSaver::SavedFrame() {
314 return g_stack_frame_pointer.Pointer()->Get();
315}
316
erikchenf7c8a0d2017-04-06 21:15:27317#endif // BUILDFLAG(CAN_UNWIND_WITH_FRAME_POINTERS)
cjhopman060e0072015-05-06 21:37:48318
[email protected]61c86c62011-08-02 16:11:16319} // namespace android
320} // namespace base