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