• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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     delete raw_vm->GetRuntime();
389     android::ResetNativeLoader();
390     return JNI_OK;
391   }
392 
AttachCurrentThread(JavaVM * vm,JNIEnv ** p_env,void * thr_args)393   static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
394     return AttachCurrentThreadInternal(vm, p_env, thr_args, false);
395   }
396 
AttachCurrentThreadAsDaemon(JavaVM * vm,JNIEnv ** p_env,void * thr_args)397   static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
398     return AttachCurrentThreadInternal(vm, p_env, thr_args, true);
399   }
400 
DetachCurrentThread(JavaVM * vm)401   static jint DetachCurrentThread(JavaVM* vm) {
402     if (vm == nullptr || Thread::Current() == nullptr) {
403       return JNI_ERR;
404     }
405     JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
406     Runtime* runtime = raw_vm->GetRuntime();
407     runtime->DetachCurrentThread();
408     return JNI_OK;
409   }
410 
GetEnv(JavaVM * vm,void ** env,jint version)411   static jint GetEnv(JavaVM* vm, void** env, jint version) {
412     if (vm == nullptr || env == nullptr) {
413       return JNI_ERR;
414     }
415     Thread* thread = Thread::Current();
416     if (thread == nullptr) {
417       *env = nullptr;
418       return JNI_EDETACHED;
419     }
420     JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
421     return raw_vm->HandleGetEnv(env, version);
422   }
423 
424  private:
AttachCurrentThreadInternal(JavaVM * vm,JNIEnv ** p_env,void * raw_args,bool as_daemon)425   static jint AttachCurrentThreadInternal(JavaVM* vm, JNIEnv** p_env, void* raw_args, bool as_daemon) {
426     if (vm == nullptr || p_env == nullptr) {
427       return JNI_ERR;
428     }
429 
430     // Return immediately if we're already attached.
431     Thread* self = Thread::Current();
432     if (self != nullptr) {
433       *p_env = self->GetJniEnv();
434       return JNI_OK;
435     }
436 
437     Runtime* runtime = reinterpret_cast<JavaVMExt*>(vm)->GetRuntime();
438 
439     // No threads allowed in zygote mode.
440     if (runtime->IsZygote()) {
441       LOG(ERROR) << "Attempt to attach a thread in the zygote";
442       return JNI_ERR;
443     }
444 
445     JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(raw_args);
446     const char* thread_name = nullptr;
447     jobject thread_group = nullptr;
448     if (args != nullptr) {
449       if (JavaVMExt::IsBadJniVersion(args->version)) {
450         LOG(ERROR) << "Bad JNI version passed to "
451                    << (as_daemon ? "AttachCurrentThreadAsDaemon" : "AttachCurrentThread") << ": "
452                    << args->version;
453         return JNI_EVERSION;
454       }
455       thread_name = args->name;
456       thread_group = args->group;
457     }
458 
459     if (!runtime->AttachCurrentThread(thread_name, as_daemon, thread_group,
460                                       !runtime->IsAotCompiler())) {
461       *p_env = nullptr;
462       return JNI_ERR;
463     } else {
464       *p_env = Thread::Current()->GetJniEnv();
465       return JNI_OK;
466     }
467   }
468 };
469 
470 const JNIInvokeInterface gJniInvokeInterface = {
471   nullptr,  // reserved0
472   nullptr,  // reserved1
473   nullptr,  // reserved2
474   JII::DestroyJavaVM,
475   JII::AttachCurrentThread,
476   JII::DetachCurrentThread,
477   JII::GetEnv,
478   JII::AttachCurrentThreadAsDaemon
479 };
480 
JavaVMExt(Runtime * runtime,const RuntimeArgumentMap & runtime_options,std::string * error_msg)481 JavaVMExt::JavaVMExt(Runtime* runtime,
482                      const RuntimeArgumentMap& runtime_options,
483                      std::string* error_msg)
484     : runtime_(runtime),
485       check_jni_abort_hook_(nullptr),
486       check_jni_abort_hook_data_(nullptr),
487       check_jni_(false),  // Initialized properly in the constructor body below.
488       force_copy_(runtime_options.Exists(RuntimeArgumentMap::JniOptsForceCopy)),
489       tracing_enabled_(runtime_options.Exists(RuntimeArgumentMap::JniTrace)
490                        || VLOG_IS_ON(third_party_jni)),
491       trace_(runtime_options.GetOrDefault(RuntimeArgumentMap::JniTrace)),
492       globals_(kGlobalsMax, kGlobal, IndirectReferenceTable::ResizableCapacity::kNo, error_msg),
493       libraries_(new Libraries),
494       unchecked_functions_(&gJniInvokeInterface),
495       weak_globals_(kWeakGlobalsMax,
496                     kWeakGlobal,
497                     IndirectReferenceTable::ResizableCapacity::kNo,
498                     error_msg),
499       allow_accessing_weak_globals_(true),
500       weak_globals_add_condition_("weak globals add condition",
501                                   (CHECK(Locks::jni_weak_globals_lock_ != nullptr),
502                                    *Locks::jni_weak_globals_lock_)),
503       env_hooks_(),
504       enable_allocation_tracking_delta_(
505           runtime_options.GetOrDefault(RuntimeArgumentMap::GlobalRefAllocStackTraceLimit)),
506       allocation_tracking_enabled_(false),
507       old_allocation_tracking_state_(false) {
508   functions = unchecked_functions_;
509   SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni));
510 }
511 
~JavaVMExt()512 JavaVMExt::~JavaVMExt() {
513   UnloadBootNativeLibraries();
514 }
515 
516 // Checking "globals" and "weak_globals" usually requires locks, but we
517 // don't need the locks to check for validity when constructing the
518 // object. Use NO_THREAD_SAFETY_ANALYSIS for this.
Create(Runtime * runtime,const RuntimeArgumentMap & runtime_options,std::string * error_msg)519 std::unique_ptr<JavaVMExt> JavaVMExt::Create(Runtime* runtime,
520                                              const RuntimeArgumentMap& runtime_options,
521                                              std::string* error_msg) NO_THREAD_SAFETY_ANALYSIS {
522   std::unique_ptr<JavaVMExt> java_vm(new JavaVMExt(runtime, runtime_options, error_msg));
523   if (java_vm && java_vm->globals_.IsValid() && java_vm->weak_globals_.IsValid()) {
524     return java_vm;
525   }
526   return nullptr;
527 }
528 
HandleGetEnv(void ** env,jint version)529 jint JavaVMExt::HandleGetEnv(/*out*/void** env, jint version) {
530   for (GetEnvHook hook : env_hooks_) {
531     jint res = hook(this, env, version);
532     if (res == JNI_OK) {
533       return JNI_OK;
534     } else if (res != JNI_EVERSION) {
535       LOG(ERROR) << "Error returned from a plugin GetEnv handler! " << res;
536       return res;
537     }
538   }
539   LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version;
540   return JNI_EVERSION;
541 }
542 
543 // Add a hook to handle getting environments from the GetEnv call.
AddEnvironmentHook(GetEnvHook hook)544 void JavaVMExt::AddEnvironmentHook(GetEnvHook hook) {
545   CHECK(hook != nullptr) << "environment hooks shouldn't be null!";
546   env_hooks_.push_back(hook);
547 }
548 
JniAbort(const char * jni_function_name,const char * msg)549 void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) {
550   Thread* self = Thread::Current();
551   ScopedObjectAccess soa(self);
552   ArtMethod* current_method = self->GetCurrentMethod(nullptr);
553 
554   std::ostringstream os;
555   os << "JNI DETECTED ERROR IN APPLICATION: " << msg;
556 
557   if (jni_function_name != nullptr) {
558     os << "\n    in call to " << jni_function_name;
559   }
560   // TODO: is this useful given that we're about to dump the calling thread's stack?
561   if (current_method != nullptr) {
562     os << "\n    from " << current_method->PrettyMethod();
563   }
564 
565   if (check_jni_abort_hook_ != nullptr) {
566     check_jni_abort_hook_(check_jni_abort_hook_data_, os.str());
567   } else {
568     // Ensure that we get a native stack trace for this thread.
569     ScopedThreadSuspension sts(self, kNative);
570     LOG(FATAL) << os.str();
571     UNREACHABLE();
572   }
573 }
574 
JniAbortV(const char * jni_function_name,const char * fmt,va_list ap)575 void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) {
576   std::string msg;
577   StringAppendV(&msg, fmt, ap);
578   JniAbort(jni_function_name, msg.c_str());
579 }
580 
JniAbortF(const char * jni_function_name,const char * fmt,...)581 void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) {
582   va_list args;
583   va_start(args, fmt);
584   JniAbortV(jni_function_name, fmt, args);
585   va_end(args);
586 }
587 
ShouldTrace(ArtMethod * method)588 bool JavaVMExt::ShouldTrace(ArtMethod* method) {
589   // Fast where no tracing is enabled.
590   if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) {
591     return false;
592   }
593   // Perform checks based on class name.
594   std::string_view class_name(method->GetDeclaringClassDescriptor());
595   if (!trace_.empty() && class_name.find(trace_) != std::string_view::npos) {
596     return true;
597   }
598   if (!VLOG_IS_ON(third_party_jni)) {
599     return false;
600   }
601   // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
602   // like part of Android.
603   static const char* const gBuiltInPrefixes[] = {
604       "Landroid/",
605       "Lcom/android/",
606       "Lcom/google/android/",
607       "Ldalvik/",
608       "Ljava/",
609       "Ljavax/",
610       "Llibcore/",
611       "Lorg/apache/harmony/",
612   };
613   for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) {
614     if (StartsWith(class_name, gBuiltInPrefixes[i])) {
615       return false;
616     }
617   }
618   return true;
619 }
620 
CheckGlobalRefAllocationTracking()621 void JavaVMExt::CheckGlobalRefAllocationTracking() {
622   if (LIKELY(enable_allocation_tracking_delta_ == 0)) {
623     return;
624   }
625   size_t simple_free_capacity = globals_.FreeCapacity();
626   if (UNLIKELY(simple_free_capacity <= enable_allocation_tracking_delta_)) {
627     if (!allocation_tracking_enabled_) {
628       LOG(WARNING) << "Global reference storage appears close to exhaustion, program termination "
629                    << "may be imminent. Enabling allocation tracking to improve abort diagnostics. "
630                    << "This will result in program slow-down.";
631 
632       old_allocation_tracking_state_ = runtime_->GetHeap()->IsAllocTrackingEnabled();
633       if (!old_allocation_tracking_state_) {
634         // Need to be guaranteed suspended.
635         ScopedObjectAccess soa(Thread::Current());
636         ScopedThreadSuspension sts(soa.Self(), ThreadState::kNative);
637         gc::AllocRecordObjectMap::SetAllocTrackingEnabled(true);
638       }
639       allocation_tracking_enabled_ = true;
640     }
641   } else {
642     if (UNLIKELY(allocation_tracking_enabled_)) {
643       if (!old_allocation_tracking_state_) {
644         // Need to be guaranteed suspended.
645         ScopedObjectAccess soa(Thread::Current());
646         ScopedThreadSuspension sts(soa.Self(), ThreadState::kNative);
647         gc::AllocRecordObjectMap::SetAllocTrackingEnabled(false);
648       }
649       allocation_tracking_enabled_ = false;
650     }
651   }
652 }
653 
AddGlobalRef(Thread * self,ObjPtr<mirror::Object> obj)654 jobject JavaVMExt::AddGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
655   // Check for null after decoding the object to handle cleared weak globals.
656   if (obj == nullptr) {
657     return nullptr;
658   }
659   IndirectRef ref;
660   std::string error_msg;
661   {
662     WriterMutexLock mu(self, *Locks::jni_globals_lock_);
663     ref = globals_.Add(kIRTFirstSegment, obj, &error_msg);
664   }
665   if (UNLIKELY(ref == nullptr)) {
666     LOG(FATAL) << error_msg;
667     UNREACHABLE();
668   }
669   CheckGlobalRefAllocationTracking();
670   return reinterpret_cast<jobject>(ref);
671 }
672 
AddWeakGlobalRef(Thread * self,ObjPtr<mirror::Object> obj)673 jweak JavaVMExt::AddWeakGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
674   if (obj == nullptr) {
675     return nullptr;
676   }
677   MutexLock mu(self, *Locks::jni_weak_globals_lock_);
678   // CMS needs this to block for concurrent reference processing because an object allocated during
679   // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
680   // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant.
681   while (!kUseReadBarrier && UNLIKELY(!MayAccessWeakGlobals(self))) {
682     // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
683     // presence of threads blocking for weak ref access.
684     self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
685     weak_globals_add_condition_.WaitHoldingLocks(self);
686   }
687   std::string error_msg;
688   IndirectRef ref = weak_globals_.Add(kIRTFirstSegment, obj, &error_msg);
689   if (UNLIKELY(ref == nullptr)) {
690     LOG(FATAL) << error_msg;
691     UNREACHABLE();
692   }
693   return reinterpret_cast<jweak>(ref);
694 }
695 
DeleteGlobalRef(Thread * self,jobject obj)696 void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
697   if (obj == nullptr) {
698     return;
699   }
700   {
701     WriterMutexLock mu(self, *Locks::jni_globals_lock_);
702     if (!globals_.Remove(kIRTFirstSegment, obj)) {
703       LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
704                    << "failed to find entry";
705     }
706   }
707   CheckGlobalRefAllocationTracking();
708 }
709 
DeleteWeakGlobalRef(Thread * self,jweak obj)710 void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
711   if (obj == nullptr) {
712     return;
713   }
714   MutexLock mu(self, *Locks::jni_weak_globals_lock_);
715   if (!weak_globals_.Remove(kIRTFirstSegment, obj)) {
716     LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
717                  << "failed to find entry";
718   }
719 }
720 
ThreadEnableCheckJni(Thread * thread,void * arg)721 static void ThreadEnableCheckJni(Thread* thread, void* arg) {
722   bool* check_jni = reinterpret_cast<bool*>(arg);
723   thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
724 }
725 
SetCheckJniEnabled(bool enabled)726 bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
727   bool old_check_jni = check_jni_;
728   check_jni_ = enabled;
729   functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
730   MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
731   runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
732   return old_check_jni;
733 }
734 
DumpForSigQuit(std::ostream & os)735 void JavaVMExt::DumpForSigQuit(std::ostream& os) {
736   os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
737   if (force_copy_) {
738     os << " (with forcecopy)";
739   }
740   Thread* self = Thread::Current();
741   {
742     ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
743     os << "; globals=" << globals_.Capacity();
744   }
745   {
746     MutexLock mu(self, *Locks::jni_weak_globals_lock_);
747     if (weak_globals_.Capacity() > 0) {
748       os << " (plus " << weak_globals_.Capacity() << " weak)";
749     }
750   }
751   os << '\n';
752 
753   {
754     MutexLock mu(self, *Locks::jni_libraries_lock_);
755     os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
756   }
757 }
758 
DisallowNewWeakGlobals()759 void JavaVMExt::DisallowNewWeakGlobals() {
760   CHECK(!kUseReadBarrier);
761   Thread* const self = Thread::Current();
762   MutexLock mu(self, *Locks::jni_weak_globals_lock_);
763   // DisallowNewWeakGlobals is only called by CMS during the pause. It is required to have the
764   // mutator lock exclusively held so that we don't have any threads in the middle of
765   // DecodeWeakGlobal.
766   Locks::mutator_lock_->AssertExclusiveHeld(self);
767   allow_accessing_weak_globals_.store(false, std::memory_order_seq_cst);
768 }
769 
AllowNewWeakGlobals()770 void JavaVMExt::AllowNewWeakGlobals() {
771   CHECK(!kUseReadBarrier);
772   Thread* self = Thread::Current();
773   MutexLock mu(self, *Locks::jni_weak_globals_lock_);
774   allow_accessing_weak_globals_.store(true, std::memory_order_seq_cst);
775   weak_globals_add_condition_.Broadcast(self);
776 }
777 
BroadcastForNewWeakGlobals()778 void JavaVMExt::BroadcastForNewWeakGlobals() {
779   Thread* self = Thread::Current();
780   MutexLock mu(self, *Locks::jni_weak_globals_lock_);
781   weak_globals_add_condition_.Broadcast(self);
782 }
783 
DecodeGlobal(IndirectRef ref)784 ObjPtr<mirror::Object> JavaVMExt::DecodeGlobal(IndirectRef ref) {
785   return globals_.SynchronizedGet(ref);
786 }
787 
UpdateGlobal(Thread * self,IndirectRef ref,ObjPtr<mirror::Object> result)788 void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
789   WriterMutexLock mu(self, *Locks::jni_globals_lock_);
790   globals_.Update(ref, result);
791 }
792 
MayAccessWeakGlobals(Thread * self) const793 inline bool JavaVMExt::MayAccessWeakGlobals(Thread* self) const {
794   return MayAccessWeakGlobalsUnlocked(self);
795 }
796 
MayAccessWeakGlobalsUnlocked(Thread * self) const797 inline bool JavaVMExt::MayAccessWeakGlobalsUnlocked(Thread* self) const {
798   DCHECK(self != nullptr);
799   return kUseReadBarrier ?
800       self->GetWeakRefAccessEnabled() :
801       allow_accessing_weak_globals_.load(std::memory_order_seq_cst);
802 }
803 
DecodeWeakGlobal(Thread * self,IndirectRef ref)804 ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
805   // It is safe to access GetWeakRefAccessEnabled without the lock since CC uses checkpoints to call
806   // SetWeakRefAccessEnabled, and the other collectors only modify allow_accessing_weak_globals_
807   // when the mutators are paused.
808   // This only applies in the case where MayAccessWeakGlobals goes from false to true. In the other
809   // case, it may be racy, this is benign since DecodeWeakGlobalLocked does the correct behavior
810   // if MayAccessWeakGlobals is false.
811   DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
812   if (LIKELY(MayAccessWeakGlobalsUnlocked(self))) {
813     return weak_globals_.SynchronizedGet(ref);
814   }
815   MutexLock mu(self, *Locks::jni_weak_globals_lock_);
816   return DecodeWeakGlobalLocked(self, ref);
817 }
818 
DecodeWeakGlobalLocked(Thread * self,IndirectRef ref)819 ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalLocked(Thread* self, IndirectRef ref) {
820   if (kDebugLocking) {
821     Locks::jni_weak_globals_lock_->AssertHeld(self);
822   }
823   while (UNLIKELY(!MayAccessWeakGlobals(self))) {
824     // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
825     // presence of threads blocking for weak ref access.
826     self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
827     weak_globals_add_condition_.WaitHoldingLocks(self);
828   }
829   return weak_globals_.Get(ref);
830 }
831 
DecodeWeakGlobalDuringShutdown(Thread * self,IndirectRef ref)832 ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalDuringShutdown(Thread* self, IndirectRef ref) {
833   DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
834   DCHECK(Runtime::Current()->IsShuttingDown(self));
835   if (self != nullptr) {
836     return DecodeWeakGlobal(self, ref);
837   }
838   // self can be null during a runtime shutdown. ~Runtime()->~ClassLinker()->DecodeWeakGlobal().
839   if (!kUseReadBarrier) {
840     DCHECK(allow_accessing_weak_globals_.load(std::memory_order_seq_cst));
841   }
842   return weak_globals_.SynchronizedGet(ref);
843 }
844 
IsWeakGlobalCleared(Thread * self,IndirectRef ref)845 bool JavaVMExt::IsWeakGlobalCleared(Thread* self, IndirectRef ref) {
846   DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
847   MutexLock mu(self, *Locks::jni_weak_globals_lock_);
848   while (UNLIKELY(!MayAccessWeakGlobals(self))) {
849     // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
850     // presence of threads blocking for weak ref access.
851     self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
852     weak_globals_add_condition_.WaitHoldingLocks(self);
853   }
854   // When just checking a weak ref has been cleared, avoid triggering the read barrier in decode
855   // (DecodeWeakGlobal) so that we won't accidentally mark the object alive. Since the cleared
856   // sentinel is a non-moving object, we can compare the ref to it without the read barrier and
857   // decide if it's cleared.
858   return Runtime::Current()->IsClearedJniWeakGlobal(weak_globals_.Get<kWithoutReadBarrier>(ref));
859 }
860 
UpdateWeakGlobal(Thread * self,IndirectRef ref,ObjPtr<mirror::Object> result)861 void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
862   MutexLock mu(self, *Locks::jni_weak_globals_lock_);
863   weak_globals_.Update(ref, result);
864 }
865 
DumpReferenceTables(std::ostream & os)866 void JavaVMExt::DumpReferenceTables(std::ostream& os) {
867   Thread* self = Thread::Current();
868   {
869     ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
870     globals_.Dump(os);
871   }
872   {
873     MutexLock mu(self, *Locks::jni_weak_globals_lock_);
874     weak_globals_.Dump(os);
875   }
876 }
877 
UnloadNativeLibraries()878 void JavaVMExt::UnloadNativeLibraries() {
879   libraries_.get()->UnloadNativeLibraries();
880 }
881 
UnloadBootNativeLibraries()882 void JavaVMExt::UnloadBootNativeLibraries() {
883   libraries_.get()->UnloadBootNativeLibraries(this);
884 }
885 
LoadNativeLibrary(JNIEnv * env,const std::string & path,jobject class_loader,jclass caller_class,std::string * error_msg)886 bool JavaVMExt::LoadNativeLibrary(JNIEnv* env,
887                                   const std::string& path,
888                                   jobject class_loader,
889                                   jclass caller_class,
890                                   std::string* error_msg) {
891   error_msg->clear();
892 
893   // See if we've already loaded this library.  If we have, and the class loader
894   // matches, return successfully without doing anything.
895   // TODO: for better results we should canonicalize the pathname (or even compare
896   // inodes). This implementation is fine if everybody is using System.loadLibrary.
897   SharedLibrary* library;
898   Thread* self = Thread::Current();
899   {
900     // TODO: move the locking (and more of this logic) into Libraries.
901     MutexLock mu(self, *Locks::jni_libraries_lock_);
902     library = libraries_->Get(path);
903   }
904   void* class_loader_allocator = nullptr;
905   std::string caller_location;
906   {
907     ScopedObjectAccess soa(env);
908     // As the incoming class loader is reachable/alive during the call of this function,
909     // it's okay to decode it without worrying about unexpectedly marking it alive.
910     ObjPtr<mirror::ClassLoader> loader = soa.Decode<mirror::ClassLoader>(class_loader);
911 
912     ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
913     if (class_linker->IsBootClassLoader(soa, loader.Ptr())) {
914       loader = nullptr;
915       class_loader = nullptr;
916       if (caller_class != nullptr) {
917         ObjPtr<mirror::Class> caller = soa.Decode<mirror::Class>(caller_class);
918         ObjPtr<mirror::DexCache> dex_cache = caller->GetDexCache();
919         if (dex_cache != nullptr) {
920           caller_location = dex_cache->GetLocation()->ToModifiedUtf8();
921         }
922       }
923     }
924 
925     class_loader_allocator = class_linker->GetAllocatorForClassLoader(loader.Ptr());
926     CHECK(class_loader_allocator != nullptr);
927   }
928   if (library != nullptr) {
929     // Use the allocator pointers for class loader equality to avoid unnecessary weak root decode.
930     if (library->GetClassLoaderAllocator() != class_loader_allocator) {
931       // The library will be associated with class_loader. The JNI
932       // spec says we can't load the same library into more than one
933       // class loader.
934       //
935       // This isn't very common. So spend some time to get a readable message.
936       auto call_to_string = [&](jobject obj) -> std::string {
937         if (obj == nullptr) {
938           return "null";
939         }
940         // Handle jweaks. Ignore double local-ref.
941         ScopedLocalRef<jobject> local_ref(env, env->NewLocalRef(obj));
942         if (local_ref != nullptr) {
943           ScopedLocalRef<jclass> local_class(env, env->GetObjectClass(local_ref.get()));
944           jmethodID to_string = env->GetMethodID(local_class.get(),
945                                                  "toString",
946                                                  "()Ljava/lang/String;");
947           DCHECK(to_string != nullptr);
948           ScopedLocalRef<jobject> local_string(env,
949                                                env->CallObjectMethod(local_ref.get(), to_string));
950           if (local_string != nullptr) {
951             ScopedUtfChars utf(env, reinterpret_cast<jstring>(local_string.get()));
952             if (utf.c_str() != nullptr) {
953               return utf.c_str();
954             }
955           }
956           if (env->ExceptionCheck()) {
957             // We can't do much better logging, really. So leave it with a Describe.
958             env->ExceptionDescribe();
959             env->ExceptionClear();
960           }
961           return "(Error calling toString)";
962         }
963         return "null";
964       };
965       std::string old_class_loader = call_to_string(library->GetClassLoader());
966       std::string new_class_loader = call_to_string(class_loader);
967       StringAppendF(error_msg, "Shared library \"%s\" already opened by "
968           "ClassLoader %p(%s); can't open in ClassLoader %p(%s)",
969           path.c_str(),
970           library->GetClassLoader(),
971           old_class_loader.c_str(),
972           class_loader,
973           new_class_loader.c_str());
974       LOG(WARNING) << *error_msg;
975       return false;
976     }
977     VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
978               << " ClassLoader " << class_loader << "]";
979     if (!library->CheckOnLoadResult()) {
980       StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
981           "to load \"%s\"", path.c_str());
982       return false;
983     }
984     return true;
985   }
986 
987   // Open the shared library.  Because we're using a full path, the system
988   // doesn't have to search through LD_LIBRARY_PATH.  (It may do so to
989   // resolve this library's dependencies though.)
990 
991   // Failures here are expected when java.library.path has several entries
992   // and we have to hunt for the lib.
993 
994   // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
995   // class unloading. Libraries will only be unloaded when the reference count (incremented by
996   // dlopen) becomes zero from dlclose.
997 
998   // Retrieve the library path from the classloader, if necessary.
999   ScopedLocalRef<jstring> library_path(env, GetLibrarySearchPath(env, class_loader));
1000 
1001   Locks::mutator_lock_->AssertNotHeld(self);
1002   const char* path_str = path.empty() ? nullptr : path.c_str();
1003   bool needs_native_bridge = false;
1004   char* nativeloader_error_msg = nullptr;
1005   void* handle = android::OpenNativeLibrary(
1006       env,
1007       runtime_->GetTargetSdkVersion(),
1008       path_str,
1009       class_loader,
1010       (caller_location.empty() ? nullptr : caller_location.c_str()),
1011       library_path.get(),
1012       &needs_native_bridge,
1013       &nativeloader_error_msg);
1014   VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]";
1015 
1016   if (handle == nullptr) {
1017     *error_msg = nativeloader_error_msg;
1018     android::NativeLoaderFreeErrorMessage(nativeloader_error_msg);
1019     VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg;
1020     return false;
1021   }
1022 
1023   if (env->ExceptionCheck() == JNI_TRUE) {
1024     LOG(ERROR) << "Unexpected exception:";
1025     env->ExceptionDescribe();
1026     env->ExceptionClear();
1027   }
1028   // Create a new entry.
1029   // TODO: move the locking (and more of this logic) into Libraries.
1030   bool created_library = false;
1031   {
1032     // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
1033     std::unique_ptr<SharedLibrary> new_library(
1034         new SharedLibrary(env,
1035                           self,
1036                           path,
1037                           handle,
1038                           needs_native_bridge,
1039                           class_loader,
1040                           class_loader_allocator));
1041 
1042     MutexLock mu(self, *Locks::jni_libraries_lock_);
1043     library = libraries_->Get(path);
1044     if (library == nullptr) {  // We won race to get libraries_lock.
1045       library = new_library.release();
1046       libraries_->Put(path, library);
1047       created_library = true;
1048     }
1049   }
1050   if (!created_library) {
1051     LOG(INFO) << "WOW: we lost a race to add shared library: "
1052         << "\"" << path << "\" ClassLoader=" << class_loader;
1053     return library->CheckOnLoadResult();
1054   }
1055   VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
1056 
1057   bool was_successful = false;
1058   void* sym = library->FindSymbol("JNI_OnLoad", nullptr);
1059   if (sym == nullptr) {
1060     VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
1061     was_successful = true;
1062   } else {
1063     // Call JNI_OnLoad.  We have to override the current class
1064     // loader, which will always be "null" since the stuff at the
1065     // top of the stack is around Runtime.loadLibrary().  (See
1066     // the comments in the JNI FindClass function.)
1067     ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
1068     self->SetClassLoaderOverride(class_loader);
1069 
1070     VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
1071     using JNI_OnLoadFn = int(*)(JavaVM*, void*);
1072     JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
1073     int version = (*jni_on_load)(this, nullptr);
1074 
1075     if (IsSdkVersionSetAndAtMost(runtime_->GetTargetSdkVersion(), SdkVersion::kL)) {
1076       // Make sure that sigchain owns SIGSEGV.
1077       EnsureFrontOfChain(SIGSEGV);
1078     }
1079 
1080     self->SetClassLoaderOverride(old_class_loader.get());
1081 
1082     if (version == JNI_ERR) {
1083       StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
1084     } else if (JavaVMExt::IsBadJniVersion(version)) {
1085       StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
1086                     path.c_str(), version);
1087       // It's unwise to call dlclose() here, but we can mark it
1088       // as bad and ensure that future load attempts will fail.
1089       // We don't know how far JNI_OnLoad got, so there could
1090       // be some partially-initialized stuff accessible through
1091       // newly-registered native method calls.  We could try to
1092       // unregister them, but that doesn't seem worthwhile.
1093     } else {
1094       was_successful = true;
1095     }
1096     VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
1097               << " from JNI_OnLoad in \"" << path << "\"]";
1098   }
1099 
1100   library->SetResult(was_successful);
1101   return was_successful;
1102 }
1103 
FindCodeForNativeMethodInAgents(ArtMethod * m)1104 static void* FindCodeForNativeMethodInAgents(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
1105   std::string jni_short_name(m->JniShortName());
1106   std::string jni_long_name(m->JniLongName());
1107   for (const std::unique_ptr<ti::Agent>& agent : Runtime::Current()->GetAgents()) {
1108     void* fn = agent->FindSymbol(jni_short_name);
1109     if (fn != nullptr) {
1110       VLOG(jni) << "Found implementation for " << m->PrettyMethod()
1111                 << " (symbol: " << jni_short_name << ") in " << *agent;
1112       return fn;
1113     }
1114     fn = agent->FindSymbol(jni_long_name);
1115     if (fn != nullptr) {
1116       VLOG(jni) << "Found implementation for " << m->PrettyMethod()
1117                 << " (symbol: " << jni_long_name << ") in " << *agent;
1118       return fn;
1119     }
1120   }
1121   return nullptr;
1122 }
1123 
FindCodeForNativeMethod(ArtMethod * m)1124 void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) {
1125   CHECK(m->IsNative());
1126   ObjPtr<mirror::Class> c = m->GetDeclaringClass();
1127   // If this is a static method, it could be called before the class has been initialized.
1128   CHECK(c->IsInitializing()) << c->GetStatus() << " " << m->PrettyMethod();
1129   std::string detail;
1130   Thread* const self = Thread::Current();
1131   void* native_method = libraries_->FindNativeMethod(self, m, detail);
1132   if (native_method == nullptr) {
1133     // Lookup JNI native methods from native TI Agent libraries. See runtime/ti/agent.h for more
1134     // information. Agent libraries are searched for native methods after all jni libraries.
1135     native_method = FindCodeForNativeMethodInAgents(m);
1136   }
1137   // Throwing can cause libraries_lock to be reacquired.
1138   if (native_method == nullptr) {
1139     LOG(ERROR) << detail;
1140     self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
1141   }
1142   return native_method;
1143 }
1144 
SweepJniWeakGlobals(IsMarkedVisitor * visitor)1145 void JavaVMExt::SweepJniWeakGlobals(IsMarkedVisitor* visitor) {
1146   MutexLock mu(Thread::Current(), *Locks::jni_weak_globals_lock_);
1147   Runtime* const runtime = Runtime::Current();
1148   for (auto* entry : weak_globals_) {
1149     // Need to skip null here to distinguish between null entries and cleared weak ref entries.
1150     if (!entry->IsNull()) {
1151       // Since this is called by the GC, we don't need a read barrier.
1152       mirror::Object* obj = entry->Read<kWithoutReadBarrier>();
1153       mirror::Object* new_obj = visitor->IsMarked(obj);
1154       if (new_obj == nullptr) {
1155         new_obj = runtime->GetClearedJniWeakGlobal();
1156       }
1157       *entry = GcRoot<mirror::Object>(new_obj);
1158     }
1159   }
1160 }
1161 
TrimGlobals()1162 void JavaVMExt::TrimGlobals() {
1163   WriterMutexLock mu(Thread::Current(), *Locks::jni_globals_lock_);
1164   globals_.Trim();
1165 }
1166 
VisitRoots(RootVisitor * visitor)1167 void JavaVMExt::VisitRoots(RootVisitor* visitor) {
1168   Thread* self = Thread::Current();
1169   ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
1170   globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal));
1171   // The weak_globals table is visited by the GC itself (because it mutates the table).
1172 }
1173 
GetLibrarySearchPath(JNIEnv * env,jobject class_loader)1174 jstring JavaVMExt::GetLibrarySearchPath(JNIEnv* env, jobject class_loader) {
1175   if (class_loader == nullptr) {
1176     return nullptr;
1177   }
1178   if (!env->IsInstanceOf(class_loader, WellKnownClasses::dalvik_system_BaseDexClassLoader)) {
1179     return nullptr;
1180   }
1181   return reinterpret_cast<jstring>(env->CallObjectMethod(
1182       class_loader,
1183       WellKnownClasses::dalvik_system_BaseDexClassLoader_getLdLibraryPath));
1184 }
1185 
1186 // JNI Invocation interface.
1187 
JNI_CreateJavaVM(JavaVM ** p_vm,JNIEnv ** p_env,void * vm_args)1188 extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
1189   ScopedTrace trace(__FUNCTION__);
1190   const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
1191   if (JavaVMExt::IsBadJniVersion(args->version)) {
1192     LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
1193     return JNI_EVERSION;
1194   }
1195   RuntimeOptions options;
1196   for (int i = 0; i < args->nOptions; ++i) {
1197     JavaVMOption* option = &args->options[i];
1198     options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
1199   }
1200   bool ignore_unrecognized = args->ignoreUnrecognized;
1201   if (!Runtime::Create(options, ignore_unrecognized)) {
1202     return JNI_ERR;
1203   }
1204 
1205   // Initialize native loader. This step makes sure we have
1206   // everything set up before we start using JNI.
1207   android::InitializeNativeLoader();
1208 
1209   Runtime* runtime = Runtime::Current();
1210   bool started = runtime->Start();
1211   if (!started) {
1212     delete Thread::Current()->GetJniEnv();
1213     delete runtime->GetJavaVM();
1214     LOG(WARNING) << "CreateJavaVM failed";
1215     return JNI_ERR;
1216   }
1217 
1218   *p_env = Thread::Current()->GetJniEnv();
1219   *p_vm = runtime->GetJavaVM();
1220   return JNI_OK;
1221 }
1222 
JNI_GetCreatedJavaVMs(JavaVM ** vms_buf,jsize buf_len,jsize * vm_count)1223 extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
1224   Runtime* runtime = Runtime::Current();
1225   if (runtime == nullptr || buf_len == 0) {
1226     *vm_count = 0;
1227   } else {
1228     *vm_count = 1;
1229     vms_buf[0] = runtime->GetJavaVM();
1230   }
1231   return JNI_OK;
1232 }
1233 
1234 // Historically unsupported.
JNI_GetDefaultJavaVMInitArgs(void *)1235 extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
1236   return JNI_ERR;
1237 }
1238 
1239 }  // namespace art
1240