Ian Rogers | 68d8b42 | 2014-07-17 11:09:10 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2011 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #include "jni_internal.h" |
| 18 | |
| 19 | #include <dlfcn.h> |
| 20 | |
Ian Rogers | c7dd295 | 2014-10-21 23:31:19 -0700 | [diff] [blame] | 21 | #include "base/dumpable.h" |
Ian Rogers | 68d8b42 | 2014-07-17 11:09:10 -0700 | [diff] [blame] | 22 | #include "base/mutex.h" |
| 23 | #include "base/stl_util.h" |
| 24 | #include "check_jni.h" |
Elliott Hughes | 956af0f | 2014-12-11 14:34:28 -0800 | [diff] [blame] | 25 | #include "dex_file-inl.h" |
Mathieu Chartier | d000480 | 2014-10-15 16:59:47 -0700 | [diff] [blame] | 26 | #include "fault_handler.h" |
Ian Rogers | 68d8b42 | 2014-07-17 11:09:10 -0700 | [diff] [blame] | 27 | #include "indirect_reference_table-inl.h" |
| 28 | #include "mirror/art_method.h" |
| 29 | #include "mirror/class-inl.h" |
| 30 | #include "mirror/class_loader.h" |
Calin Juravle | c842352 | 2014-08-12 20:55:20 +0100 | [diff] [blame] | 31 | #include "nativebridge/native_bridge.h" |
Ian Rogers | 68d8b42 | 2014-07-17 11:09:10 -0700 | [diff] [blame] | 32 | #include "java_vm_ext.h" |
| 33 | #include "parsed_options.h" |
Ian Rogers | c0542af | 2014-09-03 16:16:56 -0700 | [diff] [blame] | 34 | #include "runtime-inl.h" |
Igor Murashkin | aaebaa0 | 2015-01-26 10:55:53 -0800 | [diff] [blame] | 35 | #include "runtime_options.h" |
Ian Rogers | 68d8b42 | 2014-07-17 11:09:10 -0700 | [diff] [blame] | 36 | #include "ScopedLocalRef.h" |
| 37 | #include "scoped_thread_state_change.h" |
| 38 | #include "thread-inl.h" |
| 39 | #include "thread_list.h" |
| 40 | |
| 41 | namespace art { |
| 42 | |
Ian Rogers | 68d8b42 | 2014-07-17 11:09:10 -0700 | [diff] [blame] | 43 | static size_t gGlobalsInitial = 512; // Arbitrary. |
| 44 | static size_t gGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.) |
| 45 | |
| 46 | static const size_t kWeakGlobalsInitial = 16; // Arbitrary. |
| 47 | static const size_t kWeakGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.) |
| 48 | |
| 49 | static bool IsBadJniVersion(int version) { |
| 50 | // We don't support JNI_VERSION_1_1. These are the only other valid versions. |
| 51 | return version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 && version != JNI_VERSION_1_6; |
| 52 | } |
| 53 | |
| 54 | class SharedLibrary { |
| 55 | public: |
| 56 | SharedLibrary(JNIEnv* env, Thread* self, const std::string& path, void* handle, |
| 57 | jobject class_loader) |
| 58 | : path_(path), |
| 59 | handle_(handle), |
| 60 | needs_native_bridge_(false), |
| 61 | class_loader_(env->NewGlobalRef(class_loader)), |
| 62 | jni_on_load_lock_("JNI_OnLoad lock"), |
| 63 | jni_on_load_cond_("JNI_OnLoad condition variable", jni_on_load_lock_), |
| 64 | jni_on_load_thread_id_(self->GetThreadId()), |
| 65 | jni_on_load_result_(kPending) { |
| 66 | } |
| 67 | |
| 68 | ~SharedLibrary() { |
| 69 | Thread* self = Thread::Current(); |
| 70 | if (self != nullptr) { |
| 71 | self->GetJniEnv()->DeleteGlobalRef(class_loader_); |
| 72 | } |
| 73 | } |
| 74 | |
| 75 | jobject GetClassLoader() const { |
| 76 | return class_loader_; |
| 77 | } |
| 78 | |
| 79 | const std::string& GetPath() const { |
| 80 | return path_; |
| 81 | } |
| 82 | |
| 83 | /* |
| 84 | * Check the result of an earlier call to JNI_OnLoad on this library. |
| 85 | * If the call has not yet finished in another thread, wait for it. |
| 86 | */ |
| 87 | bool CheckOnLoadResult() |
| 88 | LOCKS_EXCLUDED(jni_on_load_lock_) { |
| 89 | Thread* self = Thread::Current(); |
| 90 | bool okay; |
| 91 | { |
| 92 | MutexLock mu(self, jni_on_load_lock_); |
| 93 | |
| 94 | if (jni_on_load_thread_id_ == self->GetThreadId()) { |
| 95 | // Check this so we don't end up waiting for ourselves. We need to return "true" so the |
| 96 | // caller can continue. |
| 97 | LOG(INFO) << *self << " recursive attempt to load library " << "\"" << path_ << "\""; |
| 98 | okay = true; |
| 99 | } else { |
| 100 | while (jni_on_load_result_ == kPending) { |
| 101 | VLOG(jni) << "[" << *self << " waiting for \"" << path_ << "\" " << "JNI_OnLoad...]"; |
| 102 | jni_on_load_cond_.Wait(self); |
| 103 | } |
| 104 | |
| 105 | okay = (jni_on_load_result_ == kOkay); |
| 106 | VLOG(jni) << "[Earlier JNI_OnLoad for \"" << path_ << "\" " |
| 107 | << (okay ? "succeeded" : "failed") << "]"; |
| 108 | } |
| 109 | } |
| 110 | return okay; |
| 111 | } |
| 112 | |
| 113 | void SetResult(bool result) LOCKS_EXCLUDED(jni_on_load_lock_) { |
| 114 | Thread* self = Thread::Current(); |
| 115 | MutexLock mu(self, jni_on_load_lock_); |
| 116 | |
| 117 | jni_on_load_result_ = result ? kOkay : kFailed; |
| 118 | jni_on_load_thread_id_ = 0; |
| 119 | |
| 120 | // Broadcast a wakeup to anybody sleeping on the condition variable. |
| 121 | jni_on_load_cond_.Broadcast(self); |
| 122 | } |
| 123 | |
| 124 | void SetNeedsNativeBridge() { |
| 125 | needs_native_bridge_ = true; |
| 126 | } |
| 127 | |
| 128 | bool NeedsNativeBridge() const { |
| 129 | return needs_native_bridge_; |
| 130 | } |
| 131 | |
| 132 | void* FindSymbol(const std::string& symbol_name) { |
| 133 | return dlsym(handle_, symbol_name.c_str()); |
| 134 | } |
| 135 | |
| 136 | void* FindSymbolWithNativeBridge(const std::string& symbol_name, const char* shorty) { |
| 137 | CHECK(NeedsNativeBridge()); |
| 138 | |
| 139 | uint32_t len = 0; |
Calin Juravle | c842352 | 2014-08-12 20:55:20 +0100 | [diff] [blame] | 140 | return android::NativeBridgeGetTrampoline(handle_, symbol_name.c_str(), shorty, len); |
Ian Rogers | 68d8b42 | 2014-07-17 11:09:10 -0700 | [diff] [blame] | 141 | } |
| 142 | |
| 143 | private: |
| 144 | enum JNI_OnLoadState { |
| 145 | kPending, |
| 146 | kFailed, |
| 147 | kOkay, |
| 148 | }; |
| 149 | |
| 150 | // Path to library "/system/lib/libjni.so". |
| 151 | const std::string path_; |
| 152 | |
| 153 | // The void* returned by dlopen(3). |
| 154 | void* const handle_; |
| 155 | |
| 156 | // True if a native bridge is required. |
| 157 | bool needs_native_bridge_; |
| 158 | |
| 159 | // The ClassLoader this library is associated with, a global JNI reference that is |
| 160 | // created/deleted with the scope of the library. |
| 161 | const jobject class_loader_; |
| 162 | |
| 163 | // Guards remaining items. |
| 164 | Mutex jni_on_load_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER; |
| 165 | // Wait for JNI_OnLoad in other thread. |
| 166 | ConditionVariable jni_on_load_cond_ GUARDED_BY(jni_on_load_lock_); |
| 167 | // Recursive invocation guard. |
| 168 | uint32_t jni_on_load_thread_id_ GUARDED_BY(jni_on_load_lock_); |
| 169 | // Result of earlier JNI_OnLoad call. |
| 170 | JNI_OnLoadState jni_on_load_result_ GUARDED_BY(jni_on_load_lock_); |
| 171 | }; |
| 172 | |
| 173 | // This exists mainly to keep implementation details out of the header file. |
| 174 | class Libraries { |
| 175 | public: |
| 176 | Libraries() { |
| 177 | } |
| 178 | |
| 179 | ~Libraries() { |
| 180 | STLDeleteValues(&libraries_); |
| 181 | } |
| 182 | |
| 183 | void Dump(std::ostream& os) const { |
| 184 | bool first = true; |
| 185 | for (const auto& library : libraries_) { |
| 186 | if (!first) { |
| 187 | os << ' '; |
| 188 | } |
| 189 | first = false; |
| 190 | os << library.first; |
| 191 | } |
| 192 | } |
| 193 | |
| 194 | size_t size() const { |
| 195 | return libraries_.size(); |
| 196 | } |
| 197 | |
| 198 | SharedLibrary* Get(const std::string& path) { |
| 199 | auto it = libraries_.find(path); |
| 200 | return (it == libraries_.end()) ? nullptr : it->second; |
| 201 | } |
| 202 | |
| 203 | void Put(const std::string& path, SharedLibrary* library) { |
| 204 | libraries_.Put(path, library); |
| 205 | } |
| 206 | |
| 207 | // See section 11.3 "Linking Native Methods" of the JNI spec. |
| 208 | void* FindNativeMethod(mirror::ArtMethod* m, std::string& detail) |
| 209 | EXCLUSIVE_LOCKS_REQUIRED(Locks::jni_libraries_lock_) |
| 210 | SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { |
| 211 | std::string jni_short_name(JniShortName(m)); |
| 212 | std::string jni_long_name(JniLongName(m)); |
| 213 | const mirror::ClassLoader* declaring_class_loader = m->GetDeclaringClass()->GetClassLoader(); |
| 214 | ScopedObjectAccessUnchecked soa(Thread::Current()); |
| 215 | for (const auto& lib : libraries_) { |
| 216 | SharedLibrary* library = lib.second; |
| 217 | if (soa.Decode<mirror::ClassLoader*>(library->GetClassLoader()) != declaring_class_loader) { |
| 218 | // We only search libraries loaded by the appropriate ClassLoader. |
| 219 | continue; |
| 220 | } |
| 221 | // Try the short name then the long name... |
| 222 | void* fn; |
| 223 | if (library->NeedsNativeBridge()) { |
| 224 | const char* shorty = m->GetShorty(); |
| 225 | fn = library->FindSymbolWithNativeBridge(jni_short_name, shorty); |
| 226 | if (fn == nullptr) { |
| 227 | fn = library->FindSymbolWithNativeBridge(jni_long_name, shorty); |
| 228 | } |
| 229 | } else { |
| 230 | fn = library->FindSymbol(jni_short_name); |
| 231 | if (fn == nullptr) { |
| 232 | fn = library->FindSymbol(jni_long_name); |
| 233 | } |
| 234 | } |
| 235 | if (fn == nullptr) { |
| 236 | fn = library->FindSymbol(jni_long_name); |
| 237 | } |
| 238 | if (fn != nullptr) { |
| 239 | VLOG(jni) << "[Found native code for " << PrettyMethod(m) |
| 240 | << " in \"" << library->GetPath() << "\"]"; |
| 241 | return fn; |
| 242 | } |
| 243 | } |
| 244 | detail += "No implementation found for "; |
| 245 | detail += PrettyMethod(m); |
| 246 | detail += " (tried " + jni_short_name + " and " + jni_long_name + ")"; |
| 247 | LOG(ERROR) << detail; |
| 248 | return nullptr; |
| 249 | } |
| 250 | |
| 251 | private: |
Andreas Gampe | 0a7993e | 2014-12-05 11:16:26 -0800 | [diff] [blame] | 252 | AllocationTrackingSafeMap<std::string, SharedLibrary*, kAllocatorTagJNILibraries> libraries_; |
Ian Rogers | 68d8b42 | 2014-07-17 11:09:10 -0700 | [diff] [blame] | 253 | }; |
| 254 | |
| 255 | |
| 256 | class JII { |
| 257 | public: |
| 258 | static jint DestroyJavaVM(JavaVM* vm) { |
| 259 | if (vm == nullptr) { |
| 260 | return JNI_ERR; |
| 261 | } |
| 262 | JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm); |
| 263 | delete raw_vm->GetRuntime(); |
| 264 | return JNI_OK; |
| 265 | } |
| 266 | |
| 267 | static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) { |
| 268 | return AttachCurrentThreadInternal(vm, p_env, thr_args, false); |
| 269 | } |
| 270 | |
| 271 | static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) { |
| 272 | return AttachCurrentThreadInternal(vm, p_env, thr_args, true); |
| 273 | } |
| 274 | |
| 275 | static jint DetachCurrentThread(JavaVM* vm) { |
| 276 | if (vm == nullptr || Thread::Current() == nullptr) { |
| 277 | return JNI_ERR; |
| 278 | } |
| 279 | JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm); |
| 280 | Runtime* runtime = raw_vm->GetRuntime(); |
| 281 | runtime->DetachCurrentThread(); |
| 282 | return JNI_OK; |
| 283 | } |
| 284 | |
| 285 | static jint GetEnv(JavaVM* vm, void** env, jint version) { |
| 286 | // GetEnv always returns a JNIEnv* for the most current supported JNI version, |
| 287 | // and unlike other calls that take a JNI version doesn't care if you supply |
| 288 | // JNI_VERSION_1_1, which we don't otherwise support. |
| 289 | if (IsBadJniVersion(version) && version != JNI_VERSION_1_1) { |
| 290 | LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version; |
| 291 | return JNI_EVERSION; |
| 292 | } |
| 293 | if (vm == nullptr || env == nullptr) { |
| 294 | return JNI_ERR; |
| 295 | } |
| 296 | Thread* thread = Thread::Current(); |
| 297 | if (thread == nullptr) { |
| 298 | *env = nullptr; |
| 299 | return JNI_EDETACHED; |
| 300 | } |
| 301 | *env = thread->GetJniEnv(); |
| 302 | return JNI_OK; |
| 303 | } |
| 304 | |
| 305 | private: |
| 306 | static jint AttachCurrentThreadInternal(JavaVM* vm, JNIEnv** p_env, void* raw_args, bool as_daemon) { |
| 307 | if (vm == nullptr || p_env == nullptr) { |
| 308 | return JNI_ERR; |
| 309 | } |
| 310 | |
| 311 | // Return immediately if we're already attached. |
| 312 | Thread* self = Thread::Current(); |
| 313 | if (self != nullptr) { |
| 314 | *p_env = self->GetJniEnv(); |
| 315 | return JNI_OK; |
| 316 | } |
| 317 | |
| 318 | Runtime* runtime = reinterpret_cast<JavaVMExt*>(vm)->GetRuntime(); |
| 319 | |
| 320 | // No threads allowed in zygote mode. |
| 321 | if (runtime->IsZygote()) { |
| 322 | LOG(ERROR) << "Attempt to attach a thread in the zygote"; |
| 323 | return JNI_ERR; |
| 324 | } |
| 325 | |
| 326 | JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(raw_args); |
| 327 | const char* thread_name = nullptr; |
| 328 | jobject thread_group = nullptr; |
| 329 | if (args != nullptr) { |
| 330 | if (IsBadJniVersion(args->version)) { |
| 331 | LOG(ERROR) << "Bad JNI version passed to " |
| 332 | << (as_daemon ? "AttachCurrentThreadAsDaemon" : "AttachCurrentThread") << ": " |
| 333 | << args->version; |
| 334 | return JNI_EVERSION; |
| 335 | } |
| 336 | thread_name = args->name; |
| 337 | thread_group = args->group; |
| 338 | } |
| 339 | |
Nicolas Geoffray | a5ca888 | 2015-02-24 08:10:57 +0000 | [diff] [blame] | 340 | if (!runtime->AttachCurrentThread(thread_name, as_daemon, thread_group, !runtime->IsCompiler())) { |
Ian Rogers | 68d8b42 | 2014-07-17 11:09:10 -0700 | [diff] [blame] | 341 | *p_env = nullptr; |
| 342 | return JNI_ERR; |
| 343 | } else { |
| 344 | *p_env = Thread::Current()->GetJniEnv(); |
| 345 | return JNI_OK; |
| 346 | } |
| 347 | } |
| 348 | }; |
| 349 | |
| 350 | const JNIInvokeInterface gJniInvokeInterface = { |
| 351 | nullptr, // reserved0 |
| 352 | nullptr, // reserved1 |
| 353 | nullptr, // reserved2 |
| 354 | JII::DestroyJavaVM, |
| 355 | JII::AttachCurrentThread, |
| 356 | JII::DetachCurrentThread, |
| 357 | JII::GetEnv, |
| 358 | JII::AttachCurrentThreadAsDaemon |
| 359 | }; |
| 360 | |
Igor Murashkin | aaebaa0 | 2015-01-26 10:55:53 -0800 | [diff] [blame] | 361 | JavaVMExt::JavaVMExt(Runtime* runtime, const RuntimeArgumentMap& runtime_options) |
Ian Rogers | 68d8b42 | 2014-07-17 11:09:10 -0700 | [diff] [blame] | 362 | : runtime_(runtime), |
| 363 | check_jni_abort_hook_(nullptr), |
| 364 | check_jni_abort_hook_data_(nullptr), |
| 365 | check_jni_(false), // Initialized properly in the constructor body below. |
Igor Murashkin | aaebaa0 | 2015-01-26 10:55:53 -0800 | [diff] [blame] | 366 | force_copy_(runtime_options.Exists(RuntimeArgumentMap::JniOptsForceCopy)), |
| 367 | tracing_enabled_(runtime_options.Exists(RuntimeArgumentMap::JniTrace) |
| 368 | || VLOG_IS_ON(third_party_jni)), |
| 369 | trace_(runtime_options.GetOrDefault(RuntimeArgumentMap::JniTrace)), |
Ian Rogers | 68d8b42 | 2014-07-17 11:09:10 -0700 | [diff] [blame] | 370 | globals_lock_("JNI global reference table lock"), |
| 371 | globals_(gGlobalsInitial, gGlobalsMax, kGlobal), |
| 372 | libraries_(new Libraries), |
| 373 | unchecked_functions_(&gJniInvokeInterface), |
| 374 | weak_globals_lock_("JNI weak global reference table lock"), |
| 375 | weak_globals_(kWeakGlobalsInitial, kWeakGlobalsMax, kWeakGlobal), |
| 376 | allow_new_weak_globals_(true), |
| 377 | weak_globals_add_condition_("weak globals add condition", weak_globals_lock_) { |
| 378 | functions = unchecked_functions_; |
Igor Murashkin | aaebaa0 | 2015-01-26 10:55:53 -0800 | [diff] [blame] | 379 | SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni)); |
Ian Rogers | 68d8b42 | 2014-07-17 11:09:10 -0700 | [diff] [blame] | 380 | } |
| 381 | |
| 382 | JavaVMExt::~JavaVMExt() { |
| 383 | } |
| 384 | |
| 385 | void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) { |
| 386 | Thread* self = Thread::Current(); |
| 387 | ScopedObjectAccess soa(self); |
| 388 | mirror::ArtMethod* current_method = self->GetCurrentMethod(nullptr); |
| 389 | |
| 390 | std::ostringstream os; |
| 391 | os << "JNI DETECTED ERROR IN APPLICATION: " << msg; |
| 392 | |
| 393 | if (jni_function_name != nullptr) { |
| 394 | os << "\n in call to " << jni_function_name; |
| 395 | } |
| 396 | // TODO: is this useful given that we're about to dump the calling thread's stack? |
| 397 | if (current_method != nullptr) { |
| 398 | os << "\n from " << PrettyMethod(current_method); |
| 399 | } |
| 400 | os << "\n"; |
| 401 | self->Dump(os); |
| 402 | |
| 403 | if (check_jni_abort_hook_ != nullptr) { |
| 404 | check_jni_abort_hook_(check_jni_abort_hook_data_, os.str()); |
| 405 | } else { |
| 406 | // Ensure that we get a native stack trace for this thread. |
| 407 | self->TransitionFromRunnableToSuspended(kNative); |
| 408 | LOG(FATAL) << os.str(); |
| 409 | self->TransitionFromSuspendedToRunnable(); // Unreachable, keep annotalysis happy. |
| 410 | } |
| 411 | } |
| 412 | |
| 413 | void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) { |
| 414 | std::string msg; |
| 415 | StringAppendV(&msg, fmt, ap); |
| 416 | JniAbort(jni_function_name, msg.c_str()); |
| 417 | } |
| 418 | |
| 419 | void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) { |
| 420 | va_list args; |
| 421 | va_start(args, fmt); |
| 422 | JniAbortV(jni_function_name, fmt, args); |
| 423 | va_end(args); |
| 424 | } |
| 425 | |
| 426 | bool JavaVMExt::ShouldTrace(mirror::ArtMethod* method) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { |
| 427 | // Fast where no tracing is enabled. |
| 428 | if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) { |
| 429 | return false; |
| 430 | } |
| 431 | // Perform checks based on class name. |
| 432 | StringPiece class_name(method->GetDeclaringClassDescriptor()); |
| 433 | if (!trace_.empty() && class_name.find(trace_) != std::string::npos) { |
| 434 | return true; |
| 435 | } |
| 436 | if (!VLOG_IS_ON(third_party_jni)) { |
| 437 | return false; |
| 438 | } |
| 439 | // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look |
| 440 | // like part of Android. |
| 441 | static const char* gBuiltInPrefixes[] = { |
| 442 | "Landroid/", |
| 443 | "Lcom/android/", |
| 444 | "Lcom/google/android/", |
| 445 | "Ldalvik/", |
| 446 | "Ljava/", |
| 447 | "Ljavax/", |
| 448 | "Llibcore/", |
| 449 | "Lorg/apache/harmony/", |
| 450 | }; |
| 451 | for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) { |
| 452 | if (class_name.starts_with(gBuiltInPrefixes[i])) { |
| 453 | return false; |
| 454 | } |
| 455 | } |
| 456 | return true; |
| 457 | } |
| 458 | |
| 459 | jobject JavaVMExt::AddGlobalRef(Thread* self, mirror::Object* obj) { |
| 460 | // Check for null after decoding the object to handle cleared weak globals. |
| 461 | if (obj == nullptr) { |
| 462 | return nullptr; |
| 463 | } |
| 464 | WriterMutexLock mu(self, globals_lock_); |
| 465 | IndirectRef ref = globals_.Add(IRT_FIRST_SEGMENT, obj); |
| 466 | return reinterpret_cast<jobject>(ref); |
| 467 | } |
| 468 | |
| 469 | jweak JavaVMExt::AddWeakGlobalRef(Thread* self, mirror::Object* obj) { |
| 470 | if (obj == nullptr) { |
| 471 | return nullptr; |
| 472 | } |
| 473 | MutexLock mu(self, weak_globals_lock_); |
| 474 | while (UNLIKELY(!allow_new_weak_globals_)) { |
| 475 | weak_globals_add_condition_.WaitHoldingLocks(self); |
| 476 | } |
| 477 | IndirectRef ref = weak_globals_.Add(IRT_FIRST_SEGMENT, obj); |
| 478 | return reinterpret_cast<jweak>(ref); |
| 479 | } |
| 480 | |
| 481 | void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) { |
| 482 | if (obj == nullptr) { |
| 483 | return; |
| 484 | } |
| 485 | WriterMutexLock mu(self, globals_lock_); |
| 486 | if (!globals_.Remove(IRT_FIRST_SEGMENT, obj)) { |
| 487 | LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") " |
| 488 | << "failed to find entry"; |
| 489 | } |
| 490 | } |
| 491 | |
| 492 | void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) { |
| 493 | if (obj == nullptr) { |
| 494 | return; |
| 495 | } |
| 496 | MutexLock mu(self, weak_globals_lock_); |
| 497 | if (!weak_globals_.Remove(IRT_FIRST_SEGMENT, obj)) { |
| 498 | LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") " |
| 499 | << "failed to find entry"; |
| 500 | } |
| 501 | } |
| 502 | |
| 503 | static void ThreadEnableCheckJni(Thread* thread, void* arg) { |
| 504 | bool* check_jni = reinterpret_cast<bool*>(arg); |
| 505 | thread->GetJniEnv()->SetCheckJniEnabled(*check_jni); |
| 506 | } |
| 507 | |
| 508 | bool JavaVMExt::SetCheckJniEnabled(bool enabled) { |
| 509 | bool old_check_jni = check_jni_; |
| 510 | check_jni_ = enabled; |
| 511 | functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_; |
| 512 | MutexLock mu(Thread::Current(), *Locks::thread_list_lock_); |
| 513 | runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_); |
| 514 | return old_check_jni; |
| 515 | } |
| 516 | |
| 517 | void JavaVMExt::DumpForSigQuit(std::ostream& os) { |
| 518 | os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off"); |
| 519 | if (force_copy_) { |
| 520 | os << " (with forcecopy)"; |
| 521 | } |
| 522 | Thread* self = Thread::Current(); |
| 523 | { |
Ian Rogers | 68d8b42 | 2014-07-17 11:09:10 -0700 | [diff] [blame] | 524 | ReaderMutexLock mu(self, globals_lock_); |
| 525 | os << "; globals=" << globals_.Capacity(); |
| 526 | } |
| 527 | { |
| 528 | MutexLock mu(self, weak_globals_lock_); |
| 529 | if (weak_globals_.Capacity() > 0) { |
| 530 | os << " (plus " << weak_globals_.Capacity() << " weak)"; |
| 531 | } |
| 532 | } |
| 533 | os << '\n'; |
| 534 | |
| 535 | { |
| 536 | MutexLock mu(self, *Locks::jni_libraries_lock_); |
| 537 | os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n"; |
| 538 | } |
| 539 | } |
| 540 | |
| 541 | void JavaVMExt::DisallowNewWeakGlobals() { |
| 542 | MutexLock mu(Thread::Current(), weak_globals_lock_); |
| 543 | allow_new_weak_globals_ = false; |
| 544 | } |
| 545 | |
| 546 | void JavaVMExt::AllowNewWeakGlobals() { |
| 547 | Thread* self = Thread::Current(); |
| 548 | MutexLock mu(self, weak_globals_lock_); |
| 549 | allow_new_weak_globals_ = true; |
| 550 | weak_globals_add_condition_.Broadcast(self); |
| 551 | } |
| 552 | |
Hiroshi Yamauchi | 2cd334a | 2015-01-09 14:03:35 -0800 | [diff] [blame] | 553 | void JavaVMExt::EnsureNewWeakGlobalsDisallowed() { |
| 554 | // Lock and unlock once to ensure that no threads are still in the |
| 555 | // middle of adding new weak globals. |
| 556 | MutexLock mu(Thread::Current(), weak_globals_lock_); |
| 557 | CHECK(!allow_new_weak_globals_); |
| 558 | } |
| 559 | |
Ian Rogers | 68d8b42 | 2014-07-17 11:09:10 -0700 | [diff] [blame] | 560 | mirror::Object* JavaVMExt::DecodeGlobal(Thread* self, IndirectRef ref) { |
| 561 | return globals_.SynchronizedGet(self, &globals_lock_, ref); |
| 562 | } |
| 563 | |
| 564 | mirror::Object* JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) { |
| 565 | MutexLock mu(self, weak_globals_lock_); |
| 566 | while (UNLIKELY(!allow_new_weak_globals_)) { |
| 567 | weak_globals_add_condition_.WaitHoldingLocks(self); |
| 568 | } |
| 569 | return weak_globals_.Get(ref); |
| 570 | } |
| 571 | |
Ian Rogers | 68d8b42 | 2014-07-17 11:09:10 -0700 | [diff] [blame] | 572 | void JavaVMExt::DumpReferenceTables(std::ostream& os) { |
| 573 | Thread* self = Thread::Current(); |
| 574 | { |
| 575 | ReaderMutexLock mu(self, globals_lock_); |
| 576 | globals_.Dump(os); |
| 577 | } |
| 578 | { |
| 579 | MutexLock mu(self, weak_globals_lock_); |
| 580 | weak_globals_.Dump(os); |
| 581 | } |
Ian Rogers | 68d8b42 | 2014-07-17 11:09:10 -0700 | [diff] [blame] | 582 | } |
| 583 | |
| 584 | bool JavaVMExt::LoadNativeLibrary(JNIEnv* env, const std::string& path, jobject class_loader, |
| 585 | std::string* error_msg) { |
| 586 | error_msg->clear(); |
| 587 | |
| 588 | // See if we've already loaded this library. If we have, and the class loader |
| 589 | // matches, return successfully without doing anything. |
| 590 | // TODO: for better results we should canonicalize the pathname (or even compare |
| 591 | // inodes). This implementation is fine if everybody is using System.loadLibrary. |
| 592 | SharedLibrary* library; |
| 593 | Thread* self = Thread::Current(); |
| 594 | { |
| 595 | // TODO: move the locking (and more of this logic) into Libraries. |
| 596 | MutexLock mu(self, *Locks::jni_libraries_lock_); |
| 597 | library = libraries_->Get(path); |
| 598 | } |
| 599 | if (library != nullptr) { |
| 600 | if (env->IsSameObject(library->GetClassLoader(), class_loader) == JNI_FALSE) { |
| 601 | // The library will be associated with class_loader. The JNI |
| 602 | // spec says we can't load the same library into more than one |
| 603 | // class loader. |
| 604 | StringAppendF(error_msg, "Shared library \"%s\" already opened by " |
| 605 | "ClassLoader %p; can't open in ClassLoader %p", |
| 606 | path.c_str(), library->GetClassLoader(), class_loader); |
| 607 | LOG(WARNING) << error_msg; |
| 608 | return false; |
| 609 | } |
| 610 | VLOG(jni) << "[Shared library \"" << path << "\" already loaded in " |
| 611 | << " ClassLoader " << class_loader << "]"; |
| 612 | if (!library->CheckOnLoadResult()) { |
| 613 | StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt " |
| 614 | "to load \"%s\"", path.c_str()); |
| 615 | return false; |
| 616 | } |
| 617 | return true; |
| 618 | } |
| 619 | |
| 620 | // Open the shared library. Because we're using a full path, the system |
| 621 | // doesn't have to search through LD_LIBRARY_PATH. (It may do so to |
| 622 | // resolve this library's dependencies though.) |
| 623 | |
| 624 | // Failures here are expected when java.library.path has several entries |
| 625 | // and we have to hunt for the lib. |
| 626 | |
| 627 | // Below we dlopen but there is no paired dlclose, this would be necessary if we supported |
| 628 | // class unloading. Libraries will only be unloaded when the reference count (incremented by |
| 629 | // dlopen) becomes zero from dlclose. |
| 630 | |
| 631 | Locks::mutator_lock_->AssertNotHeld(self); |
| 632 | const char* path_str = path.empty() ? nullptr : path.c_str(); |
| 633 | void* handle = dlopen(path_str, RTLD_LAZY); |
| 634 | bool needs_native_bridge = false; |
| 635 | if (handle == nullptr) { |
Calin Juravle | c842352 | 2014-08-12 20:55:20 +0100 | [diff] [blame] | 636 | if (android::NativeBridgeIsSupported(path_str)) { |
| 637 | handle = android::NativeBridgeLoadLibrary(path_str, RTLD_LAZY); |
Ian Rogers | 68d8b42 | 2014-07-17 11:09:10 -0700 | [diff] [blame] | 638 | needs_native_bridge = true; |
| 639 | } |
| 640 | } |
| 641 | |
| 642 | VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_LAZY) returned " << handle << "]"; |
| 643 | |
| 644 | if (handle == nullptr) { |
| 645 | *error_msg = dlerror(); |
| 646 | LOG(ERROR) << "dlopen(\"" << path << "\", RTLD_LAZY) failed: " << *error_msg; |
| 647 | return false; |
| 648 | } |
| 649 | |
| 650 | if (env->ExceptionCheck() == JNI_TRUE) { |
| 651 | LOG(ERROR) << "Unexpected exception:"; |
| 652 | env->ExceptionDescribe(); |
| 653 | env->ExceptionClear(); |
| 654 | } |
| 655 | // Create a new entry. |
| 656 | // TODO: move the locking (and more of this logic) into Libraries. |
| 657 | bool created_library = false; |
| 658 | { |
| 659 | // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering. |
| 660 | std::unique_ptr<SharedLibrary> new_library( |
| 661 | new SharedLibrary(env, self, path, handle, class_loader)); |
| 662 | MutexLock mu(self, *Locks::jni_libraries_lock_); |
| 663 | library = libraries_->Get(path); |
| 664 | if (library == nullptr) { // We won race to get libraries_lock. |
| 665 | library = new_library.release(); |
| 666 | libraries_->Put(path, library); |
| 667 | created_library = true; |
| 668 | } |
| 669 | } |
| 670 | if (!created_library) { |
| 671 | LOG(INFO) << "WOW: we lost a race to add shared library: " |
| 672 | << "\"" << path << "\" ClassLoader=" << class_loader; |
| 673 | return library->CheckOnLoadResult(); |
| 674 | } |
| 675 | VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]"; |
| 676 | |
| 677 | bool was_successful = false; |
| 678 | void* sym; |
| 679 | if (needs_native_bridge) { |
| 680 | library->SetNeedsNativeBridge(); |
| 681 | sym = library->FindSymbolWithNativeBridge("JNI_OnLoad", nullptr); |
| 682 | } else { |
| 683 | sym = dlsym(handle, "JNI_OnLoad"); |
| 684 | } |
| 685 | if (sym == nullptr) { |
| 686 | VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]"; |
| 687 | was_successful = true; |
| 688 | } else { |
| 689 | // Call JNI_OnLoad. We have to override the current class |
| 690 | // loader, which will always be "null" since the stuff at the |
| 691 | // top of the stack is around Runtime.loadLibrary(). (See |
| 692 | // the comments in the JNI FindClass function.) |
| 693 | ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride())); |
| 694 | self->SetClassLoaderOverride(class_loader); |
| 695 | |
| 696 | VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]"; |
| 697 | typedef int (*JNI_OnLoadFn)(JavaVM*, void*); |
| 698 | JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym); |
| 699 | int version = (*jni_on_load)(this, nullptr); |
| 700 | |
Mathieu Chartier | d000480 | 2014-10-15 16:59:47 -0700 | [diff] [blame] | 701 | if (runtime_->GetTargetSdkVersion() != 0 && runtime_->GetTargetSdkVersion() <= 21) { |
| 702 | fault_manager.EnsureArtActionInFrontOfSignalChain(); |
| 703 | } |
| 704 | |
Ian Rogers | 68d8b42 | 2014-07-17 11:09:10 -0700 | [diff] [blame] | 705 | self->SetClassLoaderOverride(old_class_loader.get()); |
| 706 | |
| 707 | if (version == JNI_ERR) { |
| 708 | StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str()); |
| 709 | } else if (IsBadJniVersion(version)) { |
| 710 | StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d", |
| 711 | path.c_str(), version); |
| 712 | // It's unwise to call dlclose() here, but we can mark it |
| 713 | // as bad and ensure that future load attempts will fail. |
| 714 | // We don't know how far JNI_OnLoad got, so there could |
| 715 | // be some partially-initialized stuff accessible through |
| 716 | // newly-registered native method calls. We could try to |
| 717 | // unregister them, but that doesn't seem worthwhile. |
| 718 | } else { |
| 719 | was_successful = true; |
| 720 | } |
| 721 | VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure") |
| 722 | << " from JNI_OnLoad in \"" << path << "\"]"; |
| 723 | } |
| 724 | |
| 725 | library->SetResult(was_successful); |
| 726 | return was_successful; |
| 727 | } |
| 728 | |
| 729 | void* JavaVMExt::FindCodeForNativeMethod(mirror::ArtMethod* m) { |
| 730 | CHECK(m->IsNative()); |
| 731 | mirror::Class* c = m->GetDeclaringClass(); |
| 732 | // If this is a static method, it could be called before the class has been initialized. |
| 733 | CHECK(c->IsInitializing()) << c->GetStatus() << " " << PrettyMethod(m); |
| 734 | std::string detail; |
| 735 | void* native_method; |
| 736 | Thread* self = Thread::Current(); |
| 737 | { |
| 738 | MutexLock mu(self, *Locks::jni_libraries_lock_); |
| 739 | native_method = libraries_->FindNativeMethod(m, detail); |
| 740 | } |
| 741 | // Throwing can cause libraries_lock to be reacquired. |
| 742 | if (native_method == nullptr) { |
| 743 | ThrowLocation throw_location = self->GetCurrentLocationForThrow(); |
| 744 | self->ThrowNewException(throw_location, "Ljava/lang/UnsatisfiedLinkError;", detail.c_str()); |
| 745 | } |
| 746 | return native_method; |
| 747 | } |
| 748 | |
| 749 | void JavaVMExt::SweepJniWeakGlobals(IsMarkedCallback* callback, void* arg) { |
| 750 | MutexLock mu(Thread::Current(), weak_globals_lock_); |
| 751 | for (mirror::Object** entry : weak_globals_) { |
| 752 | // Since this is called by the GC, we don't need a read barrier. |
| 753 | mirror::Object* obj = *entry; |
Hiroshi Yamauchi | 8a74117 | 2014-09-08 13:22:56 -0700 | [diff] [blame] | 754 | if (obj == nullptr) { |
| 755 | // Need to skip null here to distinguish between null entries |
| 756 | // and cleared weak ref entries. |
| 757 | continue; |
| 758 | } |
Ian Rogers | 68d8b42 | 2014-07-17 11:09:10 -0700 | [diff] [blame] | 759 | mirror::Object* new_obj = callback(obj, arg); |
| 760 | if (new_obj == nullptr) { |
Ian Rogers | c0542af | 2014-09-03 16:16:56 -0700 | [diff] [blame] | 761 | new_obj = Runtime::Current()->GetClearedJniWeakGlobal(); |
Ian Rogers | 68d8b42 | 2014-07-17 11:09:10 -0700 | [diff] [blame] | 762 | } |
| 763 | *entry = new_obj; |
| 764 | } |
| 765 | } |
| 766 | |
Mathieu Chartier | 91c2f0c | 2014-11-26 11:21:15 -0800 | [diff] [blame] | 767 | void JavaVMExt::TrimGlobals() { |
| 768 | WriterMutexLock mu(Thread::Current(), globals_lock_); |
| 769 | globals_.Trim(); |
| 770 | } |
| 771 | |
Ian Rogers | 68d8b42 | 2014-07-17 11:09:10 -0700 | [diff] [blame] | 772 | void JavaVMExt::VisitRoots(RootCallback* callback, void* arg) { |
| 773 | Thread* self = Thread::Current(); |
Mathieu Chartier | e34fa1d | 2015-01-14 14:55:47 -0800 | [diff] [blame] | 774 | ReaderMutexLock mu(self, globals_lock_); |
| 775 | globals_.VisitRoots(callback, arg, RootInfo(kRootJNIGlobal)); |
Ian Rogers | 68d8b42 | 2014-07-17 11:09:10 -0700 | [diff] [blame] | 776 | // The weak_globals table is visited by the GC itself (because it mutates the table). |
| 777 | } |
| 778 | |
| 779 | // JNI Invocation interface. |
| 780 | |
| 781 | extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) { |
| 782 | const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args); |
| 783 | if (IsBadJniVersion(args->version)) { |
| 784 | LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version; |
| 785 | return JNI_EVERSION; |
| 786 | } |
| 787 | RuntimeOptions options; |
| 788 | for (int i = 0; i < args->nOptions; ++i) { |
| 789 | JavaVMOption* option = &args->options[i]; |
| 790 | options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo)); |
| 791 | } |
| 792 | bool ignore_unrecognized = args->ignoreUnrecognized; |
| 793 | if (!Runtime::Create(options, ignore_unrecognized)) { |
| 794 | return JNI_ERR; |
| 795 | } |
| 796 | Runtime* runtime = Runtime::Current(); |
| 797 | bool started = runtime->Start(); |
| 798 | if (!started) { |
| 799 | delete Thread::Current()->GetJniEnv(); |
| 800 | delete runtime->GetJavaVM(); |
| 801 | LOG(WARNING) << "CreateJavaVM failed"; |
| 802 | return JNI_ERR; |
| 803 | } |
| 804 | *p_env = Thread::Current()->GetJniEnv(); |
| 805 | *p_vm = runtime->GetJavaVM(); |
| 806 | return JNI_OK; |
| 807 | } |
| 808 | |
Ian Rogers | f4d4da1 | 2014-11-11 16:10:33 -0800 | [diff] [blame] | 809 | extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) { |
Ian Rogers | 68d8b42 | 2014-07-17 11:09:10 -0700 | [diff] [blame] | 810 | Runtime* runtime = Runtime::Current(); |
Ian Rogers | f4d4da1 | 2014-11-11 16:10:33 -0800 | [diff] [blame] | 811 | if (runtime == nullptr || buf_len == 0) { |
Ian Rogers | 68d8b42 | 2014-07-17 11:09:10 -0700 | [diff] [blame] | 812 | *vm_count = 0; |
| 813 | } else { |
| 814 | *vm_count = 1; |
Ian Rogers | f4d4da1 | 2014-11-11 16:10:33 -0800 | [diff] [blame] | 815 | vms_buf[0] = runtime->GetJavaVM(); |
Ian Rogers | 68d8b42 | 2014-07-17 11:09:10 -0700 | [diff] [blame] | 816 | } |
| 817 | return JNI_OK; |
| 818 | } |
| 819 | |
| 820 | // Historically unsupported. |
| 821 | extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) { |
| 822 | return JNI_ERR; |
| 823 | } |
| 824 | |
| 825 | } // namespace art |