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