jni_android.cc revision c2e0dbddbe15c98d52c4786dac06cb8952a8ae6d
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. 4 5#include "base/android/jni_android.h" 6 7#include <map> 8 9#include "base/android/build_info.h" 10#include "base/android/jni_string.h" 11#include "base/lazy_instance.h" 12#include "base/logging.h" 13#include "base/threading/platform_thread.h" 14 15namespace { 16using base::android::GetClass; 17using base::android::MethodID; 18using base::android::ScopedJavaLocalRef; 19 20struct MethodIdentifier { 21 const char* class_name; 22 const char* method; 23 const char* jni_signature; 24 25 bool operator<(const MethodIdentifier& other) const { 26 int r = strcmp(class_name, other.class_name); 27 if (r < 0) { 28 return true; 29 } else if (r > 0) { 30 return false; 31 } 32 33 r = strcmp(method, other.method); 34 if (r < 0) { 35 return true; 36 } else if (r > 0) { 37 return false; 38 } 39 40 return strcmp(jni_signature, other.jni_signature) < 0; 41 } 42}; 43 44typedef std::map<MethodIdentifier, jmethodID> MethodIDMap; 45 46const base::subtle::AtomicWord kUnlocked = 0; 47const base::subtle::AtomicWord kLocked = 1; 48base::subtle::AtomicWord g_method_id_map_lock = kUnlocked; 49JavaVM* g_jvm = NULL; 50// Leak the global app context, as it is used from a non-joinable worker thread 51// that may still be running at shutdown. There is no harm in doing this. 52base::LazyInstance<base::android::ScopedJavaGlobalRef<jobject> >::Leaky 53 g_application_context = LAZY_INSTANCE_INITIALIZER; 54base::LazyInstance<MethodIDMap> g_method_id_map = LAZY_INSTANCE_INITIALIZER; 55 56std::string GetJavaExceptionInfo(JNIEnv* env, jthrowable java_throwable) { 57 ScopedJavaLocalRef<jclass> throwable_clazz = 58 GetClass(env, "java/lang/Throwable"); 59 jmethodID throwable_printstacktrace = 60 MethodID::Get<MethodID::TYPE_INSTANCE>( 61 env, throwable_clazz.obj(), "printStackTrace", 62 "(Ljava/io/PrintStream;)V"); 63 64 // Create an instance of ByteArrayOutputStream. 65 ScopedJavaLocalRef<jclass> bytearray_output_stream_clazz = 66 GetClass(env, "java/io/ByteArrayOutputStream"); 67 jmethodID bytearray_output_stream_constructor = 68 MethodID::Get<MethodID::TYPE_INSTANCE>( 69 env, bytearray_output_stream_clazz.obj(), "<init>", "()V"); 70 jmethodID bytearray_output_stream_tostring = 71 MethodID::Get<MethodID::TYPE_INSTANCE>( 72 env, bytearray_output_stream_clazz.obj(), "toString", 73 "()Ljava/lang/String;"); 74 ScopedJavaLocalRef<jobject> bytearray_output_stream(env, 75 env->NewObject(bytearray_output_stream_clazz.obj(), 76 bytearray_output_stream_constructor)); 77 78 // Create an instance of PrintStream. 79 ScopedJavaLocalRef<jclass> printstream_clazz = 80 GetClass(env, "java/io/PrintStream"); 81 jmethodID printstream_constructor = 82 MethodID::Get<MethodID::TYPE_INSTANCE>( 83 env, printstream_clazz.obj(), "<init>", 84 "(Ljava/io/OutputStream;)V"); 85 ScopedJavaLocalRef<jobject> printstream(env, 86 env->NewObject(printstream_clazz.obj(), printstream_constructor, 87 bytearray_output_stream.obj())); 88 89 // Call Throwable.printStackTrace(PrintStream) 90 env->CallVoidMethod(java_throwable, throwable_printstacktrace, 91 printstream.obj()); 92 93 // Call ByteArrayOutputStream.toString() 94 ScopedJavaLocalRef<jstring> exception_string( 95 env, static_cast<jstring>( 96 env->CallObjectMethod(bytearray_output_stream.obj(), 97 bytearray_output_stream_tostring))); 98 99 return ConvertJavaStringToUTF8(exception_string); 100} 101 102} // namespace 103 104namespace base { 105namespace android { 106 107JNIEnv* AttachCurrentThread() { 108 DCHECK(g_jvm); 109 JNIEnv* env = NULL; 110 jint ret = g_jvm->AttachCurrentThread(&env, NULL); 111 DCHECK_EQ(JNI_OK, ret); 112 return env; 113} 114 115void DetachFromVM() { 116 // Ignore the return value, if the thread is not attached, DetachCurrentThread 117 // will fail. But it is ok as the native thread may never be attached. 118 if (g_jvm) 119 g_jvm->DetachCurrentThread(); 120} 121 122void InitVM(JavaVM* vm) { 123 DCHECK(!g_jvm); 124 g_jvm = vm; 125} 126 127void InitApplicationContext(const JavaRef<jobject>& context) { 128 DCHECK(g_application_context.Get().is_null()); 129 g_application_context.Get().Reset(context); 130} 131 132const jobject GetApplicationContext() { 133 DCHECK(!g_application_context.Get().is_null()); 134 return g_application_context.Get().obj(); 135} 136 137ScopedJavaLocalRef<jclass> GetClass(JNIEnv* env, const char* class_name) { 138 jclass clazz = env->FindClass(class_name); 139 CHECK(!ClearException(env) && clazz) << "Failed to find class " << class_name; 140 return ScopedJavaLocalRef<jclass>(env, clazz); 141} 142 143bool HasClass(JNIEnv* env, const char* class_name) { 144 ScopedJavaLocalRef<jclass> clazz(env, env->FindClass(class_name)); 145 if (!clazz.obj()) { 146 ClearException(env); 147 return false; 148 } 149 bool error = ClearException(env); 150 DCHECK(!error); 151 return true; 152} 153 154template<MethodID::Type type> 155jmethodID MethodID::Get(JNIEnv* env, 156 jclass clazz, 157 const char* method_name, 158 const char* jni_signature) { 159 jmethodID id = type == TYPE_STATIC ? 160 env->GetStaticMethodID(clazz, method_name, jni_signature) : 161 env->GetMethodID(clazz, method_name, jni_signature); 162 CHECK(base::android::ClearException(env) || id) << 163 "Failed to find " << 164 (type == TYPE_STATIC ? "static " : "") << 165 "method " << method_name << " " << jni_signature; 166 return id; 167} 168 169// If |atomic_method_id| set, it'll return immediately. Otherwise, it'll call 170// into ::Get() above. If there's a race, it's ok since the values are the same 171// (and the duplicated effort will happen only once). 172template<MethodID::Type type> 173jmethodID MethodID::LazyGet(JNIEnv* env, 174 jclass clazz, 175 const char* method_name, 176 const char* jni_signature, 177 base::subtle::AtomicWord* atomic_method_id) { 178 COMPILE_ASSERT(sizeof(subtle::AtomicWord) >= sizeof(jmethodID), 179 AtomicWord_SmallerThan_jMethodID); 180 subtle::AtomicWord value = base::subtle::Acquire_Load(atomic_method_id); 181 if (value) 182 return reinterpret_cast<jmethodID>(value); 183 jmethodID id = MethodID::Get<type>(env, clazz, method_name, jni_signature); 184 base::subtle::Release_Store( 185 atomic_method_id, reinterpret_cast<subtle::AtomicWord>(id)); 186 return id; 187} 188 189// Various template instantiations. 190template jmethodID MethodID::Get<MethodID::TYPE_STATIC>( 191 JNIEnv* env, jclass clazz, const char* method_name, 192 const char* jni_signature); 193 194template jmethodID MethodID::Get<MethodID::TYPE_INSTANCE>( 195 JNIEnv* env, jclass clazz, const char* method_name, 196 const char* jni_signature); 197 198template jmethodID MethodID::LazyGet<MethodID::TYPE_STATIC>( 199 JNIEnv* env, jclass clazz, const char* method_name, 200 const char* jni_signature, base::subtle::AtomicWord* atomic_method_id); 201 202template jmethodID MethodID::LazyGet<MethodID::TYPE_INSTANCE>( 203 JNIEnv* env, jclass clazz, const char* method_name, 204 const char* jni_signature, base::subtle::AtomicWord* atomic_method_id); 205 206jfieldID GetFieldID(JNIEnv* env, 207 const JavaRef<jclass>& clazz, 208 const char* field_name, 209 const char* jni_signature) { 210 jfieldID field_id = env->GetFieldID(clazz.obj(), field_name, jni_signature); 211 CHECK(!ClearException(env) && field_id) << "Failed to find field " << 212 field_name << " " << jni_signature; 213 return field_id; 214} 215 216bool HasField(JNIEnv* env, 217 const JavaRef<jclass>& clazz, 218 const char* field_name, 219 const char* jni_signature) { 220 jfieldID field_id = env->GetFieldID(clazz.obj(), field_name, jni_signature); 221 if (!field_id) { 222 ClearException(env); 223 return false; 224 } 225 bool error = ClearException(env); 226 DCHECK(!error); 227 return true; 228} 229 230jfieldID GetStaticFieldID(JNIEnv* env, 231 const JavaRef<jclass>& clazz, 232 const char* field_name, 233 const char* jni_signature) { 234 jfieldID field_id = 235 env->GetStaticFieldID(clazz.obj(), field_name, jni_signature); 236 CHECK(!ClearException(env) && field_id) << "Failed to find static field " << 237 field_name << " " << jni_signature; 238 return field_id; 239} 240 241jmethodID GetMethodIDFromClassName(JNIEnv* env, 242 const char* class_name, 243 const char* method, 244 const char* jni_signature) { 245 MethodIdentifier key; 246 key.class_name = class_name; 247 key.method = method; 248 key.jni_signature = jni_signature; 249 250 MethodIDMap* map = g_method_id_map.Pointer(); 251 bool found = false; 252 253 while (base::subtle::Acquire_CompareAndSwap(&g_method_id_map_lock, 254 kUnlocked, 255 kLocked) != kUnlocked) { 256 base::PlatformThread::YieldCurrentThread(); 257 } 258 MethodIDMap::const_iterator iter = map->find(key); 259 if (iter != map->end()) { 260 found = true; 261 } 262 base::subtle::Release_Store(&g_method_id_map_lock, kUnlocked); 263 264 // Addition to the map does not invalidate this iterator. 265 if (found) { 266 return iter->second; 267 } 268 269 ScopedJavaLocalRef<jclass> clazz(env, env->FindClass(class_name)); 270 jmethodID id = MethodID::Get<MethodID::TYPE_INSTANCE>( 271 env, clazz.obj(), method, jni_signature); 272 273 while (base::subtle::Acquire_CompareAndSwap(&g_method_id_map_lock, 274 kUnlocked, 275 kLocked) != kUnlocked) { 276 base::PlatformThread::YieldCurrentThread(); 277 } 278 // Another thread may have populated the map already. 279 std::pair<MethodIDMap::const_iterator, bool> result = 280 map->insert(std::make_pair(key, id)); 281 DCHECK_EQ(id, result.first->second); 282 base::subtle::Release_Store(&g_method_id_map_lock, kUnlocked); 283 284 return id; 285} 286 287bool HasException(JNIEnv* env) { 288 return env->ExceptionCheck() != JNI_FALSE; 289} 290 291bool ClearException(JNIEnv* env) { 292 if (!HasException(env)) 293 return false; 294 env->ExceptionDescribe(); 295 env->ExceptionClear(); 296 return true; 297} 298 299void CheckException(JNIEnv* env) { 300 if (!HasException(env)) return; 301 302 // Exception has been found, might as well tell breakpad about it. 303 jthrowable java_throwable = env->ExceptionOccurred(); 304 if (!java_throwable) { 305 // Do nothing but return false. 306 CHECK(false); 307 } 308 309 // Clear the pending exception, since a local reference is now held. 310 env->ExceptionDescribe(); 311 env->ExceptionClear(); 312 313 // Set the exception_string in BuildInfo so that breakpad can read it. 314 // RVO should avoid any extra copies of the exception string. 315 base::android::BuildInfo::GetInstance()->set_java_exception_info( 316 GetJavaExceptionInfo(env, java_throwable)); 317 318 // Now, feel good about it and die. 319 CHECK(false); 320} 321 322} // namespace android 323} // namespace base 324