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 "java_vm_ext.h" 18 19 #include <dlfcn.h> 20 21 #include "android-base/stringprintf.h" 22 23 #include "art_method-inl.h" 24 #include "base/dumpable.h" 25 #include "base/mutex-inl.h" 26 #include "base/stl_util.h" 27 #include "base/systrace.h" 28 #include "check_jni.h" 29 #include "dex_file-inl.h" 30 #include "fault_handler.h" 31 #include "gc_root-inl.h" 32 #include "indirect_reference_table-inl.h" 33 #include "jni_internal.h" 34 #include "mirror/class-inl.h" 35 #include "mirror/class_loader.h" 36 #include "nativebridge/native_bridge.h" 37 #include "nativehelper/ScopedLocalRef.h" 38 #include "nativeloader/native_loader.h" 39 #include "object_callbacks.h" 40 #include "parsed_options.h" 41 #include "runtime-inl.h" 42 #include "runtime_options.h" 43 #include "scoped_thread_state_change-inl.h" 44 #include "sigchain.h" 45 #include "thread-inl.h" 46 #include "thread_list.h" 47 #include "ti/agent.h" 48 49 namespace art { 50 51 using android::base::StringAppendF; 52 using android::base::StringAppendV; 53 54 static constexpr size_t kGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.) 55 56 static constexpr size_t kWeakGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.) 57 58 bool JavaVMExt::IsBadJniVersion(int version) { 59 // We don't support JNI_VERSION_1_1. These are the only other valid versions. 60 return version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 && version != JNI_VERSION_1_6; 61 } 62 63 class SharedLibrary { 64 public: 65 SharedLibrary(JNIEnv* env, Thread* self, const std::string& path, void* handle, 66 bool needs_native_bridge, jobject class_loader, void* class_loader_allocator) 67 : path_(path), 68 handle_(handle), 69 needs_native_bridge_(needs_native_bridge), 70 class_loader_(env->NewWeakGlobalRef(class_loader)), 71 class_loader_allocator_(class_loader_allocator), 72 jni_on_load_lock_("JNI_OnLoad lock"), 73 jni_on_load_cond_("JNI_OnLoad condition variable", jni_on_load_lock_), 74 jni_on_load_thread_id_(self->GetThreadId()), 75 jni_on_load_result_(kPending) { 76 CHECK(class_loader_allocator_ != nullptr); 77 } 78 79 ~SharedLibrary() { 80 Thread* self = Thread::Current(); 81 if (self != nullptr) { 82 self->GetJniEnv()->DeleteWeakGlobalRef(class_loader_); 83 } 84 85 android::CloseNativeLibrary(handle_, needs_native_bridge_); 86 } 87 88 jweak GetClassLoader() const { 89 return class_loader_; 90 } 91 92 const void* GetClassLoaderAllocator() const { 93 return class_loader_allocator_; 94 } 95 96 const std::string& GetPath() const { 97 return path_; 98 } 99 100 /* 101 * Check the result of an earlier call to JNI_OnLoad on this library. 102 * If the call has not yet finished in another thread, wait for it. 103 */ 104 bool CheckOnLoadResult() 105 REQUIRES(!jni_on_load_lock_) { 106 Thread* self = Thread::Current(); 107 bool okay; 108 { 109 MutexLock mu(self, jni_on_load_lock_); 110 111 if (jni_on_load_thread_id_ == self->GetThreadId()) { 112 // Check this so we don't end up waiting for ourselves. We need to return "true" so the 113 // caller can continue. 114 LOG(INFO) << *self << " recursive attempt to load library " << "\"" << path_ << "\""; 115 okay = true; 116 } else { 117 while (jni_on_load_result_ == kPending) { 118 VLOG(jni) << "[" << *self << " waiting for \"" << path_ << "\" " << "JNI_OnLoad...]"; 119 jni_on_load_cond_.Wait(self); 120 } 121 122 okay = (jni_on_load_result_ == kOkay); 123 VLOG(jni) << "[Earlier JNI_OnLoad for \"" << path_ << "\" " 124 << (okay ? "succeeded" : "failed") << "]"; 125 } 126 } 127 return okay; 128 } 129 130 void SetResult(bool result) REQUIRES(!jni_on_load_lock_) { 131 Thread* self = Thread::Current(); 132 MutexLock mu(self, jni_on_load_lock_); 133 134 jni_on_load_result_ = result ? kOkay : kFailed; 135 jni_on_load_thread_id_ = 0; 136 137 // Broadcast a wakeup to anybody sleeping on the condition variable. 138 jni_on_load_cond_.Broadcast(self); 139 } 140 141 void SetNeedsNativeBridge(bool needs) { 142 needs_native_bridge_ = needs; 143 } 144 145 bool NeedsNativeBridge() const { 146 return needs_native_bridge_; 147 } 148 149 // No mutator lock since dlsym may block for a while if another thread is doing dlopen. 150 void* FindSymbol(const std::string& symbol_name, const char* shorty = nullptr) 151 REQUIRES(!Locks::mutator_lock_) { 152 return NeedsNativeBridge() 153 ? FindSymbolWithNativeBridge(symbol_name.c_str(), shorty) 154 : FindSymbolWithoutNativeBridge(symbol_name.c_str()); 155 } 156 157 // No mutator lock since dlsym may block for a while if another thread is doing dlopen. 158 void* FindSymbolWithoutNativeBridge(const std::string& symbol_name) 159 REQUIRES(!Locks::mutator_lock_) { 160 CHECK(!NeedsNativeBridge()); 161 162 return dlsym(handle_, symbol_name.c_str()); 163 } 164 165 void* FindSymbolWithNativeBridge(const std::string& symbol_name, const char* shorty) 166 REQUIRES(!Locks::mutator_lock_) { 167 CHECK(NeedsNativeBridge()); 168 169 uint32_t len = 0; 170 return android::NativeBridgeGetTrampoline(handle_, symbol_name.c_str(), shorty, len); 171 } 172 173 private: 174 enum JNI_OnLoadState { 175 kPending, 176 kFailed, 177 kOkay, 178 }; 179 180 // Path to library "/system/lib/libjni.so". 181 const std::string path_; 182 183 // The void* returned by dlopen(3). 184 void* const handle_; 185 186 // True if a native bridge is required. 187 bool needs_native_bridge_; 188 189 // The ClassLoader this library is associated with, a weak global JNI reference that is 190 // created/deleted with the scope of the library. 191 const jweak class_loader_; 192 // Used to do equality check on class loaders so we can avoid decoding the weak root and read 193 // barriers that mess with class unloading. 194 const void* class_loader_allocator_; 195 196 // Guards remaining items. 197 Mutex jni_on_load_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER; 198 // Wait for JNI_OnLoad in other thread. 199 ConditionVariable jni_on_load_cond_ GUARDED_BY(jni_on_load_lock_); 200 // Recursive invocation guard. 201 uint32_t jni_on_load_thread_id_ GUARDED_BY(jni_on_load_lock_); 202 // Result of earlier JNI_OnLoad call. 203 JNI_OnLoadState jni_on_load_result_ GUARDED_BY(jni_on_load_lock_); 204 }; 205 206 // This exists mainly to keep implementation details out of the header file. 207 class Libraries { 208 public: 209 Libraries() { 210 } 211 212 ~Libraries() { 213 STLDeleteValues(&libraries_); 214 } 215 216 // NO_THREAD_SAFETY_ANALYSIS since this may be called from Dumpable. Dumpable can't be annotated 217 // properly due to the template. The caller should be holding the jni_libraries_lock_. 218 void Dump(std::ostream& os) const NO_THREAD_SAFETY_ANALYSIS { 219 Locks::jni_libraries_lock_->AssertHeld(Thread::Current()); 220 bool first = true; 221 for (const auto& library : libraries_) { 222 if (!first) { 223 os << ' '; 224 } 225 first = false; 226 os << library.first; 227 } 228 } 229 230 size_t size() const REQUIRES(Locks::jni_libraries_lock_) { 231 return libraries_.size(); 232 } 233 234 SharedLibrary* Get(const std::string& path) REQUIRES(Locks::jni_libraries_lock_) { 235 auto it = libraries_.find(path); 236 return (it == libraries_.end()) ? nullptr : it->second; 237 } 238 239 void Put(const std::string& path, SharedLibrary* library) 240 REQUIRES(Locks::jni_libraries_lock_) { 241 libraries_.Put(path, library); 242 } 243 244 // See section 11.3 "Linking Native Methods" of the JNI spec. 245 void* FindNativeMethod(Thread* self, ArtMethod* m, std::string& detail) 246 REQUIRES(!Locks::jni_libraries_lock_) 247 REQUIRES_SHARED(Locks::mutator_lock_) { 248 std::string jni_short_name(m->JniShortName()); 249 std::string jni_long_name(m->JniLongName()); 250 mirror::ClassLoader* const declaring_class_loader = m->GetDeclaringClass()->GetClassLoader(); 251 ScopedObjectAccessUnchecked soa(Thread::Current()); 252 void* const declaring_class_loader_allocator = 253 Runtime::Current()->GetClassLinker()->GetAllocatorForClassLoader(declaring_class_loader); 254 CHECK(declaring_class_loader_allocator != nullptr); 255 // TODO: Avoid calling GetShorty here to prevent dirtying dex pages? 256 const char* shorty = m->GetShorty(); 257 { 258 // Go to suspended since dlsym may block for a long time if other threads are using dlopen. 259 ScopedThreadSuspension sts(self, kNative); 260 void* native_code = FindNativeMethodInternal(self, 261 declaring_class_loader_allocator, 262 shorty, 263 jni_short_name, 264 jni_long_name); 265 if (native_code != nullptr) { 266 return native_code; 267 } 268 } 269 detail += "No implementation found for "; 270 detail += m->PrettyMethod(); 271 detail += " (tried " + jni_short_name + " and " + jni_long_name + ")"; 272 return nullptr; 273 } 274 275 void* FindNativeMethodInternal(Thread* self, 276 void* declaring_class_loader_allocator, 277 const char* shorty, 278 const std::string& jni_short_name, 279 const std::string& jni_long_name) 280 REQUIRES(!Locks::jni_libraries_lock_) 281 REQUIRES(!Locks::mutator_lock_) { 282 MutexLock mu(self, *Locks::jni_libraries_lock_); 283 for (const auto& lib : libraries_) { 284 SharedLibrary* const library = lib.second; 285 // Use the allocator address for class loader equality to avoid unnecessary weak root decode. 286 if (library->GetClassLoaderAllocator() != declaring_class_loader_allocator) { 287 // We only search libraries loaded by the appropriate ClassLoader. 288 continue; 289 } 290 // Try the short name then the long name... 291 const char* arg_shorty = library->NeedsNativeBridge() ? shorty : nullptr; 292 void* fn = library->FindSymbol(jni_short_name, arg_shorty); 293 if (fn == nullptr) { 294 fn = library->FindSymbol(jni_long_name, arg_shorty); 295 } 296 if (fn != nullptr) { 297 VLOG(jni) << "[Found native code for " << jni_long_name 298 << " in \"" << library->GetPath() << "\"]"; 299 return fn; 300 } 301 } 302 return nullptr; 303 } 304 305 // Unload native libraries with cleared class loaders. 306 void UnloadNativeLibraries() 307 REQUIRES(!Locks::jni_libraries_lock_) 308 REQUIRES_SHARED(Locks::mutator_lock_) { 309 Thread* const self = Thread::Current(); 310 std::vector<SharedLibrary*> unload_libraries; 311 { 312 MutexLock mu(self, *Locks::jni_libraries_lock_); 313 for (auto it = libraries_.begin(); it != libraries_.end(); ) { 314 SharedLibrary* const library = it->second; 315 // If class loader is null then it was unloaded, call JNI_OnUnload. 316 const jweak class_loader = library->GetClassLoader(); 317 // If class_loader is a null jobject then it is the boot class loader. We should not unload 318 // the native libraries of the boot class loader. 319 if (class_loader != nullptr && self->IsJWeakCleared(class_loader)) { 320 unload_libraries.push_back(library); 321 it = libraries_.erase(it); 322 } else { 323 ++it; 324 } 325 } 326 } 327 ScopedThreadSuspension sts(self, kNative); 328 // Do this without holding the jni libraries lock to prevent possible deadlocks. 329 typedef void (*JNI_OnUnloadFn)(JavaVM*, void*); 330 for (auto library : unload_libraries) { 331 void* const sym = library->FindSymbol("JNI_OnUnload", nullptr); 332 if (sym == nullptr) { 333 VLOG(jni) << "[No JNI_OnUnload found in \"" << library->GetPath() << "\"]"; 334 } else { 335 VLOG(jni) << "[JNI_OnUnload found for \"" << library->GetPath() << "\"]: Calling..."; 336 JNI_OnUnloadFn jni_on_unload = reinterpret_cast<JNI_OnUnloadFn>(sym); 337 jni_on_unload(self->GetJniEnv()->vm, nullptr); 338 } 339 delete library; 340 } 341 } 342 343 private: 344 AllocationTrackingSafeMap<std::string, SharedLibrary*, kAllocatorTagJNILibraries> libraries_ 345 GUARDED_BY(Locks::jni_libraries_lock_); 346 }; 347 348 class JII { 349 public: 350 static jint DestroyJavaVM(JavaVM* vm) { 351 if (vm == nullptr) { 352 return JNI_ERR; 353 } 354 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm); 355 delete raw_vm->GetRuntime(); 356 android::ResetNativeLoader(); 357 return JNI_OK; 358 } 359 360 static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) { 361 return AttachCurrentThreadInternal(vm, p_env, thr_args, false); 362 } 363 364 static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) { 365 return AttachCurrentThreadInternal(vm, p_env, thr_args, true); 366 } 367 368 static jint DetachCurrentThread(JavaVM* vm) { 369 if (vm == nullptr || Thread::Current() == nullptr) { 370 return JNI_ERR; 371 } 372 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm); 373 Runtime* runtime = raw_vm->GetRuntime(); 374 runtime->DetachCurrentThread(); 375 return JNI_OK; 376 } 377 378 static jint GetEnv(JavaVM* vm, void** env, jint version) { 379 if (vm == nullptr || env == nullptr) { 380 return JNI_ERR; 381 } 382 Thread* thread = Thread::Current(); 383 if (thread == nullptr) { 384 *env = nullptr; 385 return JNI_EDETACHED; 386 } 387 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm); 388 return raw_vm->HandleGetEnv(env, version); 389 } 390 391 private: 392 static jint AttachCurrentThreadInternal(JavaVM* vm, JNIEnv** p_env, void* raw_args, bool as_daemon) { 393 if (vm == nullptr || p_env == nullptr) { 394 return JNI_ERR; 395 } 396 397 // Return immediately if we're already attached. 398 Thread* self = Thread::Current(); 399 if (self != nullptr) { 400 *p_env = self->GetJniEnv(); 401 return JNI_OK; 402 } 403 404 Runtime* runtime = reinterpret_cast<JavaVMExt*>(vm)->GetRuntime(); 405 406 // No threads allowed in zygote mode. 407 if (runtime->IsZygote()) { 408 LOG(ERROR) << "Attempt to attach a thread in the zygote"; 409 return JNI_ERR; 410 } 411 412 JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(raw_args); 413 const char* thread_name = nullptr; 414 jobject thread_group = nullptr; 415 if (args != nullptr) { 416 if (JavaVMExt::IsBadJniVersion(args->version)) { 417 LOG(ERROR) << "Bad JNI version passed to " 418 << (as_daemon ? "AttachCurrentThreadAsDaemon" : "AttachCurrentThread") << ": " 419 << args->version; 420 return JNI_EVERSION; 421 } 422 thread_name = args->name; 423 thread_group = args->group; 424 } 425 426 if (!runtime->AttachCurrentThread(thread_name, as_daemon, thread_group, 427 !runtime->IsAotCompiler())) { 428 *p_env = nullptr; 429 return JNI_ERR; 430 } else { 431 *p_env = Thread::Current()->GetJniEnv(); 432 return JNI_OK; 433 } 434 } 435 }; 436 437 const JNIInvokeInterface gJniInvokeInterface = { 438 nullptr, // reserved0 439 nullptr, // reserved1 440 nullptr, // reserved2 441 JII::DestroyJavaVM, 442 JII::AttachCurrentThread, 443 JII::DetachCurrentThread, 444 JII::GetEnv, 445 JII::AttachCurrentThreadAsDaemon 446 }; 447 448 JavaVMExt::JavaVMExt(Runtime* runtime, 449 const RuntimeArgumentMap& runtime_options, 450 std::string* error_msg) 451 : runtime_(runtime), 452 check_jni_abort_hook_(nullptr), 453 check_jni_abort_hook_data_(nullptr), 454 check_jni_(false), // Initialized properly in the constructor body below. 455 force_copy_(runtime_options.Exists(RuntimeArgumentMap::JniOptsForceCopy)), 456 tracing_enabled_(runtime_options.Exists(RuntimeArgumentMap::JniTrace) 457 || VLOG_IS_ON(third_party_jni)), 458 trace_(runtime_options.GetOrDefault(RuntimeArgumentMap::JniTrace)), 459 globals_(kGlobalsMax, kGlobal, IndirectReferenceTable::ResizableCapacity::kNo, error_msg), 460 libraries_(new Libraries), 461 unchecked_functions_(&gJniInvokeInterface), 462 weak_globals_(kWeakGlobalsMax, 463 kWeakGlobal, 464 IndirectReferenceTable::ResizableCapacity::kNo, 465 error_msg), 466 allow_accessing_weak_globals_(true), 467 weak_globals_add_condition_("weak globals add condition", 468 (CHECK(Locks::jni_weak_globals_lock_ != nullptr), 469 *Locks::jni_weak_globals_lock_)), 470 env_hooks_() { 471 functions = unchecked_functions_; 472 SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni)); 473 } 474 475 JavaVMExt::~JavaVMExt() { 476 } 477 478 // Checking "globals" and "weak_globals" usually requires locks, but we 479 // don't need the locks to check for validity when constructing the 480 // object. Use NO_THREAD_SAFETY_ANALYSIS for this. 481 std::unique_ptr<JavaVMExt> JavaVMExt::Create(Runtime* runtime, 482 const RuntimeArgumentMap& runtime_options, 483 std::string* error_msg) NO_THREAD_SAFETY_ANALYSIS { 484 std::unique_ptr<JavaVMExt> java_vm(new JavaVMExt(runtime, runtime_options, error_msg)); 485 if (java_vm && java_vm->globals_.IsValid() && java_vm->weak_globals_.IsValid()) { 486 return java_vm; 487 } 488 return nullptr; 489 } 490 491 jint JavaVMExt::HandleGetEnv(/*out*/void** env, jint version) { 492 for (GetEnvHook hook : env_hooks_) { 493 jint res = hook(this, env, version); 494 if (res == JNI_OK) { 495 return JNI_OK; 496 } else if (res != JNI_EVERSION) { 497 LOG(ERROR) << "Error returned from a plugin GetEnv handler! " << res; 498 return res; 499 } 500 } 501 LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version; 502 return JNI_EVERSION; 503 } 504 505 // Add a hook to handle getting environments from the GetEnv call. 506 void JavaVMExt::AddEnvironmentHook(GetEnvHook hook) { 507 CHECK(hook != nullptr) << "environment hooks shouldn't be null!"; 508 env_hooks_.push_back(hook); 509 } 510 511 void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) { 512 Thread* self = Thread::Current(); 513 ScopedObjectAccess soa(self); 514 ArtMethod* current_method = self->GetCurrentMethod(nullptr); 515 516 std::ostringstream os; 517 os << "JNI DETECTED ERROR IN APPLICATION: " << msg; 518 519 if (jni_function_name != nullptr) { 520 os << "\n in call to " << jni_function_name; 521 } 522 // TODO: is this useful given that we're about to dump the calling thread's stack? 523 if (current_method != nullptr) { 524 os << "\n from " << current_method->PrettyMethod(); 525 } 526 os << "\n"; 527 self->Dump(os); 528 529 if (check_jni_abort_hook_ != nullptr) { 530 check_jni_abort_hook_(check_jni_abort_hook_data_, os.str()); 531 } else { 532 // Ensure that we get a native stack trace for this thread. 533 ScopedThreadSuspension sts(self, kNative); 534 LOG(FATAL) << os.str(); 535 UNREACHABLE(); 536 } 537 } 538 539 void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) { 540 std::string msg; 541 StringAppendV(&msg, fmt, ap); 542 JniAbort(jni_function_name, msg.c_str()); 543 } 544 545 void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) { 546 va_list args; 547 va_start(args, fmt); 548 JniAbortV(jni_function_name, fmt, args); 549 va_end(args); 550 } 551 552 bool JavaVMExt::ShouldTrace(ArtMethod* method) { 553 // Fast where no tracing is enabled. 554 if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) { 555 return false; 556 } 557 // Perform checks based on class name. 558 StringPiece class_name(method->GetDeclaringClassDescriptor()); 559 if (!trace_.empty() && class_name.find(trace_) != std::string::npos) { 560 return true; 561 } 562 if (!VLOG_IS_ON(third_party_jni)) { 563 return false; 564 } 565 // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look 566 // like part of Android. 567 static const char* gBuiltInPrefixes[] = { 568 "Landroid/", 569 "Lcom/android/", 570 "Lcom/google/android/", 571 "Ldalvik/", 572 "Ljava/", 573 "Ljavax/", 574 "Llibcore/", 575 "Lorg/apache/harmony/", 576 }; 577 for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) { 578 if (class_name.starts_with(gBuiltInPrefixes[i])) { 579 return false; 580 } 581 } 582 return true; 583 } 584 585 jobject JavaVMExt::AddGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) { 586 // Check for null after decoding the object to handle cleared weak globals. 587 if (obj == nullptr) { 588 return nullptr; 589 } 590 WriterMutexLock mu(self, *Locks::jni_globals_lock_); 591 IndirectRef ref = globals_.Add(kIRTFirstSegment, obj); 592 return reinterpret_cast<jobject>(ref); 593 } 594 595 jweak JavaVMExt::AddWeakGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) { 596 if (obj == nullptr) { 597 return nullptr; 598 } 599 MutexLock mu(self, *Locks::jni_weak_globals_lock_); 600 // CMS needs this to block for concurrent reference processing because an object allocated during 601 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak 602 // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant. 603 while (!kUseReadBarrier && UNLIKELY(!MayAccessWeakGlobals(self))) { 604 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the 605 // presence of threads blocking for weak ref access. 606 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_); 607 weak_globals_add_condition_.WaitHoldingLocks(self); 608 } 609 IndirectRef ref = weak_globals_.Add(kIRTFirstSegment, obj); 610 return reinterpret_cast<jweak>(ref); 611 } 612 613 void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) { 614 if (obj == nullptr) { 615 return; 616 } 617 WriterMutexLock mu(self, *Locks::jni_globals_lock_); 618 if (!globals_.Remove(kIRTFirstSegment, obj)) { 619 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") " 620 << "failed to find entry"; 621 } 622 } 623 624 void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) { 625 if (obj == nullptr) { 626 return; 627 } 628 MutexLock mu(self, *Locks::jni_weak_globals_lock_); 629 if (!weak_globals_.Remove(kIRTFirstSegment, obj)) { 630 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") " 631 << "failed to find entry"; 632 } 633 } 634 635 static void ThreadEnableCheckJni(Thread* thread, void* arg) { 636 bool* check_jni = reinterpret_cast<bool*>(arg); 637 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni); 638 } 639 640 bool JavaVMExt::SetCheckJniEnabled(bool enabled) { 641 bool old_check_jni = check_jni_; 642 check_jni_ = enabled; 643 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_; 644 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_); 645 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_); 646 return old_check_jni; 647 } 648 649 void JavaVMExt::DumpForSigQuit(std::ostream& os) { 650 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off"); 651 if (force_copy_) { 652 os << " (with forcecopy)"; 653 } 654 Thread* self = Thread::Current(); 655 { 656 ReaderMutexLock mu(self, *Locks::jni_globals_lock_); 657 os << "; globals=" << globals_.Capacity(); 658 } 659 { 660 MutexLock mu(self, *Locks::jni_weak_globals_lock_); 661 if (weak_globals_.Capacity() > 0) { 662 os << " (plus " << weak_globals_.Capacity() << " weak)"; 663 } 664 } 665 os << '\n'; 666 667 { 668 MutexLock mu(self, *Locks::jni_libraries_lock_); 669 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n"; 670 } 671 } 672 673 void JavaVMExt::DisallowNewWeakGlobals() { 674 CHECK(!kUseReadBarrier); 675 Thread* const self = Thread::Current(); 676 MutexLock mu(self, *Locks::jni_weak_globals_lock_); 677 // DisallowNewWeakGlobals is only called by CMS during the pause. It is required to have the 678 // mutator lock exclusively held so that we don't have any threads in the middle of 679 // DecodeWeakGlobal. 680 Locks::mutator_lock_->AssertExclusiveHeld(self); 681 allow_accessing_weak_globals_.StoreSequentiallyConsistent(false); 682 } 683 684 void JavaVMExt::AllowNewWeakGlobals() { 685 CHECK(!kUseReadBarrier); 686 Thread* self = Thread::Current(); 687 MutexLock mu(self, *Locks::jni_weak_globals_lock_); 688 allow_accessing_weak_globals_.StoreSequentiallyConsistent(true); 689 weak_globals_add_condition_.Broadcast(self); 690 } 691 692 void JavaVMExt::BroadcastForNewWeakGlobals() { 693 Thread* self = Thread::Current(); 694 MutexLock mu(self, *Locks::jni_weak_globals_lock_); 695 weak_globals_add_condition_.Broadcast(self); 696 } 697 698 ObjPtr<mirror::Object> JavaVMExt::DecodeGlobal(IndirectRef ref) { 699 return globals_.SynchronizedGet(ref); 700 } 701 702 void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) { 703 WriterMutexLock mu(self, *Locks::jni_globals_lock_); 704 globals_.Update(ref, result); 705 } 706 707 inline bool JavaVMExt::MayAccessWeakGlobals(Thread* self) const { 708 return MayAccessWeakGlobalsUnlocked(self); 709 } 710 711 inline bool JavaVMExt::MayAccessWeakGlobalsUnlocked(Thread* self) const { 712 DCHECK(self != nullptr); 713 return kUseReadBarrier ? 714 self->GetWeakRefAccessEnabled() : 715 allow_accessing_weak_globals_.LoadSequentiallyConsistent(); 716 } 717 718 ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) { 719 // It is safe to access GetWeakRefAccessEnabled without the lock since CC uses checkpoints to call 720 // SetWeakRefAccessEnabled, and the other collectors only modify allow_accessing_weak_globals_ 721 // when the mutators are paused. 722 // This only applies in the case where MayAccessWeakGlobals goes from false to true. In the other 723 // case, it may be racy, this is benign since DecodeWeakGlobalLocked does the correct behavior 724 // if MayAccessWeakGlobals is false. 725 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal); 726 if (LIKELY(MayAccessWeakGlobalsUnlocked(self))) { 727 return weak_globals_.SynchronizedGet(ref); 728 } 729 MutexLock mu(self, *Locks::jni_weak_globals_lock_); 730 return DecodeWeakGlobalLocked(self, ref); 731 } 732 733 ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalLocked(Thread* self, IndirectRef ref) { 734 if (kDebugLocking) { 735 Locks::jni_weak_globals_lock_->AssertHeld(self); 736 } 737 while (UNLIKELY(!MayAccessWeakGlobals(self))) { 738 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the 739 // presence of threads blocking for weak ref access. 740 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_); 741 weak_globals_add_condition_.WaitHoldingLocks(self); 742 } 743 return weak_globals_.Get(ref); 744 } 745 746 ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalDuringShutdown(Thread* self, IndirectRef ref) { 747 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal); 748 DCHECK(Runtime::Current()->IsShuttingDown(self)); 749 if (self != nullptr) { 750 return DecodeWeakGlobal(self, ref); 751 } 752 // self can be null during a runtime shutdown. ~Runtime()->~ClassLinker()->DecodeWeakGlobal(). 753 if (!kUseReadBarrier) { 754 DCHECK(allow_accessing_weak_globals_.LoadSequentiallyConsistent()); 755 } 756 return weak_globals_.SynchronizedGet(ref); 757 } 758 759 bool JavaVMExt::IsWeakGlobalCleared(Thread* self, IndirectRef ref) { 760 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal); 761 MutexLock mu(self, *Locks::jni_weak_globals_lock_); 762 while (UNLIKELY(!MayAccessWeakGlobals(self))) { 763 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the 764 // presence of threads blocking for weak ref access. 765 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_); 766 weak_globals_add_condition_.WaitHoldingLocks(self); 767 } 768 // When just checking a weak ref has been cleared, avoid triggering the read barrier in decode 769 // (DecodeWeakGlobal) so that we won't accidentally mark the object alive. Since the cleared 770 // sentinel is a non-moving object, we can compare the ref to it without the read barrier and 771 // decide if it's cleared. 772 return Runtime::Current()->IsClearedJniWeakGlobal(weak_globals_.Get<kWithoutReadBarrier>(ref)); 773 } 774 775 void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) { 776 MutexLock mu(self, *Locks::jni_weak_globals_lock_); 777 weak_globals_.Update(ref, result); 778 } 779 780 void JavaVMExt::DumpReferenceTables(std::ostream& os) { 781 Thread* self = Thread::Current(); 782 { 783 ReaderMutexLock mu(self, *Locks::jni_globals_lock_); 784 globals_.Dump(os); 785 } 786 { 787 MutexLock mu(self, *Locks::jni_weak_globals_lock_); 788 weak_globals_.Dump(os); 789 } 790 } 791 792 void JavaVMExt::UnloadNativeLibraries() { 793 libraries_.get()->UnloadNativeLibraries(); 794 } 795 796 bool JavaVMExt::LoadNativeLibrary(JNIEnv* env, 797 const std::string& path, 798 jobject class_loader, 799 jstring library_path, 800 std::string* error_msg) { 801 error_msg->clear(); 802 803 // See if we've already loaded this library. If we have, and the class loader 804 // matches, return successfully without doing anything. 805 // TODO: for better results we should canonicalize the pathname (or even compare 806 // inodes). This implementation is fine if everybody is using System.loadLibrary. 807 SharedLibrary* library; 808 Thread* self = Thread::Current(); 809 { 810 // TODO: move the locking (and more of this logic) into Libraries. 811 MutexLock mu(self, *Locks::jni_libraries_lock_); 812 library = libraries_->Get(path); 813 } 814 void* class_loader_allocator = nullptr; 815 { 816 ScopedObjectAccess soa(env); 817 // As the incoming class loader is reachable/alive during the call of this function, 818 // it's okay to decode it without worrying about unexpectedly marking it alive. 819 ObjPtr<mirror::ClassLoader> loader = soa.Decode<mirror::ClassLoader>(class_loader); 820 821 ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); 822 if (class_linker->IsBootClassLoader(soa, loader.Ptr())) { 823 loader = nullptr; 824 class_loader = nullptr; 825 } 826 827 class_loader_allocator = class_linker->GetAllocatorForClassLoader(loader.Ptr()); 828 CHECK(class_loader_allocator != nullptr); 829 } 830 if (library != nullptr) { 831 // Use the allocator pointers for class loader equality to avoid unnecessary weak root decode. 832 if (library->GetClassLoaderAllocator() != class_loader_allocator) { 833 // The library will be associated with class_loader. The JNI 834 // spec says we can't load the same library into more than one 835 // class loader. 836 StringAppendF(error_msg, "Shared library \"%s\" already opened by " 837 "ClassLoader %p; can't open in ClassLoader %p", 838 path.c_str(), library->GetClassLoader(), class_loader); 839 LOG(WARNING) << error_msg; 840 return false; 841 } 842 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in " 843 << " ClassLoader " << class_loader << "]"; 844 if (!library->CheckOnLoadResult()) { 845 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt " 846 "to load \"%s\"", path.c_str()); 847 return false; 848 } 849 return true; 850 } 851 852 // Open the shared library. Because we're using a full path, the system 853 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to 854 // resolve this library's dependencies though.) 855 856 // Failures here are expected when java.library.path has several entries 857 // and we have to hunt for the lib. 858 859 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported 860 // class unloading. Libraries will only be unloaded when the reference count (incremented by 861 // dlopen) becomes zero from dlclose. 862 863 Locks::mutator_lock_->AssertNotHeld(self); 864 const char* path_str = path.empty() ? nullptr : path.c_str(); 865 bool needs_native_bridge = false; 866 void* handle = android::OpenNativeLibrary(env, 867 runtime_->GetTargetSdkVersion(), 868 path_str, 869 class_loader, 870 library_path, 871 &needs_native_bridge, 872 error_msg); 873 874 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]"; 875 876 if (handle == nullptr) { 877 VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg; 878 return false; 879 } 880 881 if (env->ExceptionCheck() == JNI_TRUE) { 882 LOG(ERROR) << "Unexpected exception:"; 883 env->ExceptionDescribe(); 884 env->ExceptionClear(); 885 } 886 // Create a new entry. 887 // TODO: move the locking (and more of this logic) into Libraries. 888 bool created_library = false; 889 { 890 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering. 891 std::unique_ptr<SharedLibrary> new_library( 892 new SharedLibrary(env, 893 self, 894 path, 895 handle, 896 needs_native_bridge, 897 class_loader, 898 class_loader_allocator)); 899 900 MutexLock mu(self, *Locks::jni_libraries_lock_); 901 library = libraries_->Get(path); 902 if (library == nullptr) { // We won race to get libraries_lock. 903 library = new_library.release(); 904 libraries_->Put(path, library); 905 created_library = true; 906 } 907 } 908 if (!created_library) { 909 LOG(INFO) << "WOW: we lost a race to add shared library: " 910 << "\"" << path << "\" ClassLoader=" << class_loader; 911 return library->CheckOnLoadResult(); 912 } 913 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]"; 914 915 bool was_successful = false; 916 void* sym = library->FindSymbol("JNI_OnLoad", nullptr); 917 if (sym == nullptr) { 918 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]"; 919 was_successful = true; 920 } else { 921 // Call JNI_OnLoad. We have to override the current class 922 // loader, which will always be "null" since the stuff at the 923 // top of the stack is around Runtime.loadLibrary(). (See 924 // the comments in the JNI FindClass function.) 925 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride())); 926 self->SetClassLoaderOverride(class_loader); 927 928 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]"; 929 typedef int (*JNI_OnLoadFn)(JavaVM*, void*); 930 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym); 931 int version = (*jni_on_load)(this, nullptr); 932 933 if (runtime_->GetTargetSdkVersion() != 0 && runtime_->GetTargetSdkVersion() <= 21) { 934 // Make sure that sigchain owns SIGSEGV. 935 EnsureFrontOfChain(SIGSEGV); 936 } 937 938 self->SetClassLoaderOverride(old_class_loader.get()); 939 940 if (version == JNI_ERR) { 941 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str()); 942 } else if (JavaVMExt::IsBadJniVersion(version)) { 943 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d", 944 path.c_str(), version); 945 // It's unwise to call dlclose() here, but we can mark it 946 // as bad and ensure that future load attempts will fail. 947 // We don't know how far JNI_OnLoad got, so there could 948 // be some partially-initialized stuff accessible through 949 // newly-registered native method calls. We could try to 950 // unregister them, but that doesn't seem worthwhile. 951 } else { 952 was_successful = true; 953 } 954 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure") 955 << " from JNI_OnLoad in \"" << path << "\"]"; 956 } 957 958 library->SetResult(was_successful); 959 return was_successful; 960 } 961 962 static void* FindCodeForNativeMethodInAgents(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) { 963 std::string jni_short_name(m->JniShortName()); 964 std::string jni_long_name(m->JniLongName()); 965 for (const ti::Agent& agent : Runtime::Current()->GetAgents()) { 966 void* fn = agent.FindSymbol(jni_short_name); 967 if (fn != nullptr) { 968 VLOG(jni) << "Found implementation for " << m->PrettyMethod() 969 << " (symbol: " << jni_short_name << ") in " << agent; 970 return fn; 971 } 972 fn = agent.FindSymbol(jni_long_name); 973 if (fn != nullptr) { 974 VLOG(jni) << "Found implementation for " << m->PrettyMethod() 975 << " (symbol: " << jni_long_name << ") in " << agent; 976 return fn; 977 } 978 } 979 return nullptr; 980 } 981 982 void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) { 983 CHECK(m->IsNative()); 984 mirror::Class* c = m->GetDeclaringClass(); 985 // If this is a static method, it could be called before the class has been initialized. 986 CHECK(c->IsInitializing()) << c->GetStatus() << " " << m->PrettyMethod(); 987 std::string detail; 988 Thread* const self = Thread::Current(); 989 void* native_method = libraries_->FindNativeMethod(self, m, detail); 990 if (native_method == nullptr) { 991 // Lookup JNI native methods from native TI Agent libraries. See runtime/ti/agent.h for more 992 // information. Agent libraries are searched for native methods after all jni libraries. 993 native_method = FindCodeForNativeMethodInAgents(m); 994 } 995 // Throwing can cause libraries_lock to be reacquired. 996 if (native_method == nullptr) { 997 LOG(ERROR) << detail; 998 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str()); 999 } 1000 return native_method; 1001 } 1002 1003 void JavaVMExt::SweepJniWeakGlobals(IsMarkedVisitor* visitor) { 1004 MutexLock mu(Thread::Current(), *Locks::jni_weak_globals_lock_); 1005 Runtime* const runtime = Runtime::Current(); 1006 for (auto* entry : weak_globals_) { 1007 // Need to skip null here to distinguish between null entries and cleared weak ref entries. 1008 if (!entry->IsNull()) { 1009 // Since this is called by the GC, we don't need a read barrier. 1010 mirror::Object* obj = entry->Read<kWithoutReadBarrier>(); 1011 mirror::Object* new_obj = visitor->IsMarked(obj); 1012 if (new_obj == nullptr) { 1013 new_obj = runtime->GetClearedJniWeakGlobal(); 1014 } 1015 *entry = GcRoot<mirror::Object>(new_obj); 1016 } 1017 } 1018 } 1019 1020 void JavaVMExt::TrimGlobals() { 1021 WriterMutexLock mu(Thread::Current(), *Locks::jni_globals_lock_); 1022 globals_.Trim(); 1023 } 1024 1025 void JavaVMExt::VisitRoots(RootVisitor* visitor) { 1026 Thread* self = Thread::Current(); 1027 ReaderMutexLock mu(self, *Locks::jni_globals_lock_); 1028 globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal)); 1029 // The weak_globals table is visited by the GC itself (because it mutates the table). 1030 } 1031 1032 // JNI Invocation interface. 1033 1034 extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) { 1035 ScopedTrace trace(__FUNCTION__); 1036 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args); 1037 if (JavaVMExt::IsBadJniVersion(args->version)) { 1038 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version; 1039 return JNI_EVERSION; 1040 } 1041 RuntimeOptions options; 1042 for (int i = 0; i < args->nOptions; ++i) { 1043 JavaVMOption* option = &args->options[i]; 1044 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo)); 1045 } 1046 bool ignore_unrecognized = args->ignoreUnrecognized; 1047 if (!Runtime::Create(options, ignore_unrecognized)) { 1048 return JNI_ERR; 1049 } 1050 1051 // Initialize native loader. This step makes sure we have 1052 // everything set up before we start using JNI. 1053 android::InitializeNativeLoader(); 1054 1055 Runtime* runtime = Runtime::Current(); 1056 bool started = runtime->Start(); 1057 if (!started) { 1058 delete Thread::Current()->GetJniEnv(); 1059 delete runtime->GetJavaVM(); 1060 LOG(WARNING) << "CreateJavaVM failed"; 1061 return JNI_ERR; 1062 } 1063 1064 *p_env = Thread::Current()->GetJniEnv(); 1065 *p_vm = runtime->GetJavaVM(); 1066 return JNI_OK; 1067 } 1068 1069 extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) { 1070 Runtime* runtime = Runtime::Current(); 1071 if (runtime == nullptr || buf_len == 0) { 1072 *vm_count = 0; 1073 } else { 1074 *vm_count = 1; 1075 vms_buf[0] = runtime->GetJavaVM(); 1076 } 1077 return JNI_OK; 1078 } 1079 1080 // Historically unsupported. 1081 extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) { 1082 return JNI_ERR; 1083 } 1084 1085 } // namespace art 1086