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