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