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