2 * Copyright (C) 2011 The Android Open Source Project
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 #include "jni_internal.h"
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"
45 static size_t gGlobalsInitial = 512; // Arbitrary.
46 static size_t gGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
48 static const size_t kWeakGlobalsInitial = 16; // Arbitrary.
49 static const size_t kWeakGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
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;
58 SharedLibrary(JNIEnv* env, Thread* self, const std::string& path, void* handle,
59 jobject class_loader, void* class_loader_allocator)
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);
73 Thread* self = Thread::Current();
74 if (self != nullptr) {
75 self->GetJniEnv()->DeleteWeakGlobalRef(class_loader_);
79 jweak GetClassLoader() const {
83 const void* GetClassLoaderAllocator() const {
84 return class_loader_allocator_;
87 const std::string& GetPath() const {
92 * Check the result of an earlier call to JNI_OnLoad on this library.
93 * If the call has not yet finished in another thread, wait for it.
95 bool CheckOnLoadResult()
96 REQUIRES(!jni_on_load_lock_) {
97 Thread* self = Thread::Current();
100 MutexLock mu(self, jni_on_load_lock_);
102 if (jni_on_load_thread_id_ == self->GetThreadId()) {
103 // Check this so we don't end up waiting for ourselves. We need to return "true" so the
104 // caller can continue.
105 LOG(INFO) << *self << " recursive attempt to load library " << "\"" << path_ << "\"";
108 while (jni_on_load_result_ == kPending) {
109 VLOG(jni) << "[" << *self << " waiting for \"" << path_ << "\" " << "JNI_OnLoad...]";
110 jni_on_load_cond_.Wait(self);
113 okay = (jni_on_load_result_ == kOkay);
114 VLOG(jni) << "[Earlier JNI_OnLoad for \"" << path_ << "\" "
115 << (okay ? "succeeded" : "failed") << "]";
121 void SetResult(bool result) REQUIRES(!jni_on_load_lock_) {
122 Thread* self = Thread::Current();
123 MutexLock mu(self, jni_on_load_lock_);
125 jni_on_load_result_ = result ? kOkay : kFailed;
126 jni_on_load_thread_id_ = 0;
128 // Broadcast a wakeup to anybody sleeping on the condition variable.
129 jni_on_load_cond_.Broadcast(self);
132 void SetNeedsNativeBridge() {
133 needs_native_bridge_ = true;
136 bool NeedsNativeBridge() const {
137 return needs_native_bridge_;
140 void* FindSymbol(const std::string& symbol_name, const char* shorty = nullptr) {
141 return NeedsNativeBridge()
142 ? FindSymbolWithNativeBridge(symbol_name.c_str(), shorty)
143 : FindSymbolWithoutNativeBridge(symbol_name.c_str());
146 void* FindSymbolWithoutNativeBridge(const std::string& symbol_name) {
147 CHECK(!NeedsNativeBridge());
149 return dlsym(handle_, symbol_name.c_str());
152 void* FindSymbolWithNativeBridge(const std::string& symbol_name, const char* shorty) {
153 CHECK(NeedsNativeBridge());
156 return android::NativeBridgeGetTrampoline(handle_, symbol_name.c_str(), shorty, len);
160 enum JNI_OnLoadState {
166 // Path to library "/system/lib/libjni.so".
167 const std::string path_;
169 // The void* returned by dlopen(3).
172 // True if a native bridge is required.
173 bool needs_native_bridge_;
175 // The ClassLoader this library is associated with, a weak global JNI reference that is
176 // created/deleted with the scope of the library.
177 const jweak class_loader_;
178 // Used to do equality check on class loaders so we can avoid decoding the weak root and read
179 // barriers that mess with class unloading.
180 const void* class_loader_allocator_;
182 // Guards remaining items.
183 Mutex jni_on_load_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
184 // Wait for JNI_OnLoad in other thread.
185 ConditionVariable jni_on_load_cond_ GUARDED_BY(jni_on_load_lock_);
186 // Recursive invocation guard.
187 uint32_t jni_on_load_thread_id_ GUARDED_BY(jni_on_load_lock_);
188 // Result of earlier JNI_OnLoad call.
189 JNI_OnLoadState jni_on_load_result_ GUARDED_BY(jni_on_load_lock_);
192 // This exists mainly to keep implementation details out of the header file.
199 STLDeleteValues(&libraries_);
202 // NO_THREAD_SAFETY_ANALYSIS since this may be called from Dumpable. Dumpable can't be annotated
203 // properly due to the template. The caller should be holding the jni_libraries_lock_.
204 void Dump(std::ostream& os) const NO_THREAD_SAFETY_ANALYSIS {
205 Locks::jni_libraries_lock_->AssertHeld(Thread::Current());
207 for (const auto& library : libraries_) {
216 size_t size() const REQUIRES(Locks::jni_libraries_lock_) {
217 return libraries_.size();
220 SharedLibrary* Get(const std::string& path) REQUIRES(Locks::jni_libraries_lock_) {
221 auto it = libraries_.find(path);
222 return (it == libraries_.end()) ? nullptr : it->second;
225 void Put(const std::string& path, SharedLibrary* library)
226 REQUIRES(Locks::jni_libraries_lock_) {
227 libraries_.Put(path, library);
230 // See section 11.3 "Linking Native Methods" of the JNI spec.
231 void* FindNativeMethod(ArtMethod* m, std::string& detail)
232 REQUIRES(Locks::jni_libraries_lock_)
233 SHARED_REQUIRES(Locks::mutator_lock_) {
234 std::string jni_short_name(JniShortName(m));
235 std::string jni_long_name(JniLongName(m));
236 mirror::ClassLoader* const declaring_class_loader = m->GetDeclaringClass()->GetClassLoader();
237 ScopedObjectAccessUnchecked soa(Thread::Current());
238 void* const declaring_class_loader_allocator =
239 Runtime::Current()->GetClassLinker()->GetAllocatorForClassLoader(declaring_class_loader);
240 CHECK(declaring_class_loader_allocator != nullptr);
241 for (const auto& lib : libraries_) {
242 SharedLibrary* const library = lib.second;
243 // Use the allocator address for class loader equality to avoid unnecessary weak root decode.
244 if (library->GetClassLoaderAllocator() != declaring_class_loader_allocator) {
245 // We only search libraries loaded by the appropriate ClassLoader.
248 // Try the short name then the long name...
249 const char* shorty = library->NeedsNativeBridge()
252 void* fn = library->FindSymbol(jni_short_name, shorty);
254 fn = library->FindSymbol(jni_long_name, shorty);
257 VLOG(jni) << "[Found native code for " << PrettyMethod(m)
258 << " in \"" << library->GetPath() << "\"]";
262 detail += "No implementation found for ";
263 detail += PrettyMethod(m);
264 detail += " (tried " + jni_short_name + " and " + jni_long_name + ")";
265 LOG(ERROR) << detail;
269 // Unload native libraries with cleared class loaders.
270 void UnloadNativeLibraries()
271 REQUIRES(!Locks::jni_libraries_lock_)
272 SHARED_REQUIRES(Locks::mutator_lock_) {
273 ScopedObjectAccessUnchecked soa(Thread::Current());
274 typedef void (*JNI_OnUnloadFn)(JavaVM*, void*);
275 std::vector<JNI_OnUnloadFn> unload_functions;
277 MutexLock mu(soa.Self(), *Locks::jni_libraries_lock_);
278 for (auto it = libraries_.begin(); it != libraries_.end(); ) {
279 SharedLibrary* const library = it->second;
280 // If class loader is null then it was unloaded, call JNI_OnUnload.
281 const jweak class_loader = library->GetClassLoader();
282 // If class_loader is a null jobject then it is the boot class loader. We should not unload
283 // the native libraries of the boot class loader.
284 if (class_loader != nullptr &&
285 soa.Self()->IsJWeakCleared(class_loader)) {
286 void* const sym = library->FindSymbol("JNI_OnUnload", nullptr);
287 if (sym == nullptr) {
288 VLOG(jni) << "[No JNI_OnUnload found in \"" << library->GetPath() << "\"]";
290 VLOG(jni) << "[JNI_OnUnload found for \"" << library->GetPath() << "\"]";
291 JNI_OnUnloadFn jni_on_unload = reinterpret_cast<JNI_OnUnloadFn>(sym);
292 unload_functions.push_back(jni_on_unload);
295 it = libraries_.erase(it);
301 // Do this without holding the jni libraries lock to prevent possible deadlocks.
302 for (JNI_OnUnloadFn fn : unload_functions) {
303 VLOG(jni) << "Calling JNI_OnUnload";
304 (*fn)(soa.Vm(), nullptr);
309 AllocationTrackingSafeMap<std::string, SharedLibrary*, kAllocatorTagJNILibraries> libraries_
310 GUARDED_BY(Locks::jni_libraries_lock_);
315 static jint DestroyJavaVM(JavaVM* vm) {
319 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
320 delete raw_vm->GetRuntime();
324 static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
325 return AttachCurrentThreadInternal(vm, p_env, thr_args, false);
328 static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
329 return AttachCurrentThreadInternal(vm, p_env, thr_args, true);
332 static jint DetachCurrentThread(JavaVM* vm) {
333 if (vm == nullptr || Thread::Current() == nullptr) {
336 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
337 Runtime* runtime = raw_vm->GetRuntime();
338 runtime->DetachCurrentThread();
342 static jint GetEnv(JavaVM* vm, void** env, jint version) {
343 // GetEnv always returns a JNIEnv* for the most current supported JNI version,
344 // and unlike other calls that take a JNI version doesn't care if you supply
345 // JNI_VERSION_1_1, which we don't otherwise support.
346 if (IsBadJniVersion(version) && version != JNI_VERSION_1_1) {
347 LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version;
350 if (vm == nullptr || env == nullptr) {
353 Thread* thread = Thread::Current();
354 if (thread == nullptr) {
356 return JNI_EDETACHED;
358 *env = thread->GetJniEnv();
363 static jint AttachCurrentThreadInternal(JavaVM* vm, JNIEnv** p_env, void* raw_args, bool as_daemon) {
364 if (vm == nullptr || p_env == nullptr) {
368 // Return immediately if we're already attached.
369 Thread* self = Thread::Current();
370 if (self != nullptr) {
371 *p_env = self->GetJniEnv();
375 Runtime* runtime = reinterpret_cast<JavaVMExt*>(vm)->GetRuntime();
377 // No threads allowed in zygote mode.
378 if (runtime->IsZygote()) {
379 LOG(ERROR) << "Attempt to attach a thread in the zygote";
383 JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(raw_args);
384 const char* thread_name = nullptr;
385 jobject thread_group = nullptr;
386 if (args != nullptr) {
387 if (IsBadJniVersion(args->version)) {
388 LOG(ERROR) << "Bad JNI version passed to "
389 << (as_daemon ? "AttachCurrentThreadAsDaemon" : "AttachCurrentThread") << ": "
393 thread_name = args->name;
394 thread_group = args->group;
397 if (!runtime->AttachCurrentThread(thread_name, as_daemon, thread_group,
398 !runtime->IsAotCompiler())) {
402 *p_env = Thread::Current()->GetJniEnv();
408 const JNIInvokeInterface gJniInvokeInterface = {
409 nullptr, // reserved0
410 nullptr, // reserved1
411 nullptr, // reserved2
413 JII::AttachCurrentThread,
414 JII::DetachCurrentThread,
416 JII::AttachCurrentThreadAsDaemon
419 JavaVMExt::JavaVMExt(Runtime* runtime, const RuntimeArgumentMap& runtime_options)
421 check_jni_abort_hook_(nullptr),
422 check_jni_abort_hook_data_(nullptr),
423 check_jni_(false), // Initialized properly in the constructor body below.
424 force_copy_(runtime_options.Exists(RuntimeArgumentMap::JniOptsForceCopy)),
425 tracing_enabled_(runtime_options.Exists(RuntimeArgumentMap::JniTrace)
426 || VLOG_IS_ON(third_party_jni)),
427 trace_(runtime_options.GetOrDefault(RuntimeArgumentMap::JniTrace)),
428 globals_lock_("JNI global reference table lock"),
429 globals_(gGlobalsInitial, gGlobalsMax, kGlobal),
430 libraries_(new Libraries),
431 unchecked_functions_(&gJniInvokeInterface),
432 weak_globals_lock_("JNI weak global reference table lock", kJniWeakGlobalsLock),
433 weak_globals_(kWeakGlobalsInitial, kWeakGlobalsMax, kWeakGlobal),
434 allow_accessing_weak_globals_(true),
435 weak_globals_add_condition_("weak globals add condition", weak_globals_lock_) {
436 functions = unchecked_functions_;
437 SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni));
440 JavaVMExt::~JavaVMExt() {
443 void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) {
444 Thread* self = Thread::Current();
445 ScopedObjectAccess soa(self);
446 ArtMethod* current_method = self->GetCurrentMethod(nullptr);
448 std::ostringstream os;
449 os << "JNI DETECTED ERROR IN APPLICATION: " << msg;
451 if (jni_function_name != nullptr) {
452 os << "\n in call to " << jni_function_name;
454 // TODO: is this useful given that we're about to dump the calling thread's stack?
455 if (current_method != nullptr) {
456 os << "\n from " << PrettyMethod(current_method);
461 if (check_jni_abort_hook_ != nullptr) {
462 check_jni_abort_hook_(check_jni_abort_hook_data_, os.str());
464 // Ensure that we get a native stack trace for this thread.
465 ScopedThreadSuspension sts(self, kNative);
466 LOG(FATAL) << os.str();
471 void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) {
473 StringAppendV(&msg, fmt, ap);
474 JniAbort(jni_function_name, msg.c_str());
477 void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) {
480 JniAbortV(jni_function_name, fmt, args);
484 bool JavaVMExt::ShouldTrace(ArtMethod* method) {
485 // Fast where no tracing is enabled.
486 if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) {
489 // Perform checks based on class name.
490 StringPiece class_name(method->GetDeclaringClassDescriptor());
491 if (!trace_.empty() && class_name.find(trace_) != std::string::npos) {
494 if (!VLOG_IS_ON(third_party_jni)) {
497 // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
498 // like part of Android.
499 static const char* gBuiltInPrefixes[] = {
502 "Lcom/google/android/",
507 "Lorg/apache/harmony/",
509 for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) {
510 if (class_name.starts_with(gBuiltInPrefixes[i])) {
517 jobject JavaVMExt::AddGlobalRef(Thread* self, mirror::Object* obj) {
518 // Check for null after decoding the object to handle cleared weak globals.
519 if (obj == nullptr) {
522 WriterMutexLock mu(self, globals_lock_);
523 IndirectRef ref = globals_.Add(IRT_FIRST_SEGMENT, obj);
524 return reinterpret_cast<jobject>(ref);
527 jweak JavaVMExt::AddWeakGlobalRef(Thread* self, mirror::Object* obj) {
528 if (obj == nullptr) {
531 MutexLock mu(self, weak_globals_lock_);
532 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
533 weak_globals_add_condition_.WaitHoldingLocks(self);
535 IndirectRef ref = weak_globals_.Add(IRT_FIRST_SEGMENT, obj);
536 return reinterpret_cast<jweak>(ref);
539 void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
540 if (obj == nullptr) {
543 WriterMutexLock mu(self, globals_lock_);
544 if (!globals_.Remove(IRT_FIRST_SEGMENT, obj)) {
545 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
546 << "failed to find entry";
550 void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
551 if (obj == nullptr) {
554 MutexLock mu(self, weak_globals_lock_);
555 if (!weak_globals_.Remove(IRT_FIRST_SEGMENT, obj)) {
556 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
557 << "failed to find entry";
561 static void ThreadEnableCheckJni(Thread* thread, void* arg) {
562 bool* check_jni = reinterpret_cast<bool*>(arg);
563 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
566 bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
567 bool old_check_jni = check_jni_;
568 check_jni_ = enabled;
569 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
570 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
571 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
572 return old_check_jni;
575 void JavaVMExt::DumpForSigQuit(std::ostream& os) {
576 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
578 os << " (with forcecopy)";
580 Thread* self = Thread::Current();
582 ReaderMutexLock mu(self, globals_lock_);
583 os << "; globals=" << globals_.Capacity();
586 MutexLock mu(self, weak_globals_lock_);
587 if (weak_globals_.Capacity() > 0) {
588 os << " (plus " << weak_globals_.Capacity() << " weak)";
594 MutexLock mu(self, *Locks::jni_libraries_lock_);
595 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
599 void JavaVMExt::DisallowNewWeakGlobals() {
600 CHECK(!kUseReadBarrier);
601 Thread* const self = Thread::Current();
602 MutexLock mu(self, weak_globals_lock_);
603 // DisallowNewWeakGlobals is only called by CMS during the pause. It is required to have the
604 // mutator lock exclusively held so that we don't have any threads in the middle of
606 Locks::mutator_lock_->AssertExclusiveHeld(self);
607 allow_accessing_weak_globals_.StoreSequentiallyConsistent(false);
610 void JavaVMExt::AllowNewWeakGlobals() {
611 CHECK(!kUseReadBarrier);
612 Thread* self = Thread::Current();
613 MutexLock mu(self, weak_globals_lock_);
614 allow_accessing_weak_globals_.StoreSequentiallyConsistent(true);
615 weak_globals_add_condition_.Broadcast(self);
618 void JavaVMExt::BroadcastForNewWeakGlobals() {
619 CHECK(kUseReadBarrier);
620 Thread* self = Thread::Current();
621 MutexLock mu(self, weak_globals_lock_);
622 weak_globals_add_condition_.Broadcast(self);
625 mirror::Object* JavaVMExt::DecodeGlobal(IndirectRef ref) {
626 return globals_.SynchronizedGet(ref);
629 void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, mirror::Object* result) {
630 WriterMutexLock mu(self, globals_lock_);
631 globals_.Update(ref, result);
634 inline bool JavaVMExt::MayAccessWeakGlobals(Thread* self) const {
635 return MayAccessWeakGlobalsUnlocked(self);
638 inline bool JavaVMExt::MayAccessWeakGlobalsUnlocked(Thread* self) const {
639 DCHECK(self != nullptr);
640 return kUseReadBarrier ?
641 self->GetWeakRefAccessEnabled() :
642 allow_accessing_weak_globals_.LoadSequentiallyConsistent();
645 mirror::Object* JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
646 // It is safe to access GetWeakRefAccessEnabled without the lock since CC uses checkpoints to call
647 // SetWeakRefAccessEnabled, and the other collectors only modify allow_accessing_weak_globals_
648 // when the mutators are paused.
649 // This only applies in the case where MayAccessWeakGlobals goes from false to true. In the other
650 // case, it may be racy, this is benign since DecodeWeakGlobalLocked does the correct behavior
651 // if MayAccessWeakGlobals is false.
652 DCHECK_EQ(GetIndirectRefKind(ref), kWeakGlobal);
653 if (LIKELY(MayAccessWeakGlobalsUnlocked(self))) {
654 return weak_globals_.SynchronizedGet(ref);
656 MutexLock mu(self, weak_globals_lock_);
657 return DecodeWeakGlobalLocked(self, ref);
660 mirror::Object* JavaVMExt::DecodeWeakGlobalLocked(Thread* self, IndirectRef ref) {
662 weak_globals_lock_.AssertHeld(self);
664 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
665 weak_globals_add_condition_.WaitHoldingLocks(self);
667 return weak_globals_.Get(ref);
670 mirror::Object* JavaVMExt::DecodeWeakGlobalDuringShutdown(Thread* self, IndirectRef ref) {
671 DCHECK_EQ(GetIndirectRefKind(ref), kWeakGlobal);
672 DCHECK(Runtime::Current()->IsShuttingDown(self));
673 if (self != nullptr) {
674 return DecodeWeakGlobal(self, ref);
676 // self can be null during a runtime shutdown. ~Runtime()->~ClassLinker()->DecodeWeakGlobal().
677 if (!kUseReadBarrier) {
678 DCHECK(allow_accessing_weak_globals_.LoadSequentiallyConsistent());
680 return weak_globals_.SynchronizedGet(ref);
683 bool JavaVMExt::IsWeakGlobalCleared(Thread* self, IndirectRef ref) {
684 DCHECK_EQ(GetIndirectRefKind(ref), kWeakGlobal);
685 MutexLock mu(self, weak_globals_lock_);
686 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
687 weak_globals_add_condition_.WaitHoldingLocks(self);
689 // When just checking a weak ref has been cleared, avoid triggering the read barrier in decode
690 // (DecodeWeakGlobal) so that we won't accidentally mark the object alive. Since the cleared
691 // sentinel is a non-moving object, we can compare the ref to it without the read barrier and
692 // decide if it's cleared.
693 return Runtime::Current()->IsClearedJniWeakGlobal(weak_globals_.Get<kWithoutReadBarrier>(ref));
696 void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, mirror::Object* result) {
697 MutexLock mu(self, weak_globals_lock_);
698 weak_globals_.Update(ref, result);
701 void JavaVMExt::DumpReferenceTables(std::ostream& os) {
702 Thread* self = Thread::Current();
704 ReaderMutexLock mu(self, globals_lock_);
708 MutexLock mu(self, weak_globals_lock_);
709 weak_globals_.Dump(os);
713 void JavaVMExt::UnloadNativeLibraries() {
714 libraries_.get()->UnloadNativeLibraries();
717 bool JavaVMExt::LoadNativeLibrary(JNIEnv* env,
718 const std::string& path,
719 jobject class_loader,
720 jstring library_path,
721 std::string* error_msg) {
724 // See if we've already loaded this library. If we have, and the class loader
725 // matches, return successfully without doing anything.
726 // TODO: for better results we should canonicalize the pathname (or even compare
727 // inodes). This implementation is fine if everybody is using System.loadLibrary.
728 SharedLibrary* library;
729 Thread* self = Thread::Current();
731 // TODO: move the locking (and more of this logic) into Libraries.
732 MutexLock mu(self, *Locks::jni_libraries_lock_);
733 library = libraries_->Get(path);
735 void* class_loader_allocator = nullptr;
737 ScopedObjectAccess soa(env);
738 // As the incoming class loader is reachable/alive during the call of this function,
739 // it's okay to decode it without worrying about unexpectedly marking it alive.
740 mirror::ClassLoader* loader = soa.Decode<mirror::ClassLoader*>(class_loader);
741 class_loader_allocator =
742 Runtime::Current()->GetClassLinker()->GetAllocatorForClassLoader(loader);
743 CHECK(class_loader_allocator != nullptr);
745 if (library != nullptr) {
746 // Use the allocator pointers for class loader equality to avoid unnecessary weak root decode.
747 if (library->GetClassLoaderAllocator() != class_loader_allocator) {
748 // The library will be associated with class_loader. The JNI
749 // spec says we can't load the same library into more than one
751 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
752 "ClassLoader %p; can't open in ClassLoader %p",
753 path.c_str(), library->GetClassLoader(), class_loader);
754 LOG(WARNING) << error_msg;
757 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
758 << " ClassLoader " << class_loader << "]";
759 if (!library->CheckOnLoadResult()) {
760 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
761 "to load \"%s\"", path.c_str());
767 // Open the shared library. Because we're using a full path, the system
768 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
769 // resolve this library's dependencies though.)
771 // Failures here are expected when java.library.path has several entries
772 // and we have to hunt for the lib.
774 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
775 // class unloading. Libraries will only be unloaded when the reference count (incremented by
776 // dlopen) becomes zero from dlclose.
778 Locks::mutator_lock_->AssertNotHeld(self);
779 const char* path_str = path.empty() ? nullptr : path.c_str();
780 void* handle = android::OpenNativeLibrary(env,
781 runtime_->GetTargetSdkVersion(),
786 bool needs_native_bridge = false;
787 if (handle == nullptr) {
788 if (android::NativeBridgeIsSupported(path_str)) {
789 handle = android::NativeBridgeLoadLibrary(path_str, RTLD_NOW);
790 needs_native_bridge = true;
794 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]";
796 if (handle == nullptr) {
797 *error_msg = dlerror();
798 VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg;
802 if (env->ExceptionCheck() == JNI_TRUE) {
803 LOG(ERROR) << "Unexpected exception:";
804 env->ExceptionDescribe();
805 env->ExceptionClear();
807 // Create a new entry.
808 // TODO: move the locking (and more of this logic) into Libraries.
809 bool created_library = false;
811 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
812 std::unique_ptr<SharedLibrary> new_library(
813 new SharedLibrary(env, self, path, handle, class_loader, class_loader_allocator));
814 MutexLock mu(self, *Locks::jni_libraries_lock_);
815 library = libraries_->Get(path);
816 if (library == nullptr) { // We won race to get libraries_lock.
817 library = new_library.release();
818 libraries_->Put(path, library);
819 created_library = true;
822 if (!created_library) {
823 LOG(INFO) << "WOW: we lost a race to add shared library: "
824 << "\"" << path << "\" ClassLoader=" << class_loader;
825 return library->CheckOnLoadResult();
827 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
829 bool was_successful = false;
831 if (needs_native_bridge) {
832 library->SetNeedsNativeBridge();
834 sym = library->FindSymbol("JNI_OnLoad", nullptr);
835 if (sym == nullptr) {
836 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
837 was_successful = true;
839 // Call JNI_OnLoad. We have to override the current class
840 // loader, which will always be "null" since the stuff at the
841 // top of the stack is around Runtime.loadLibrary(). (See
842 // the comments in the JNI FindClass function.)
843 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
844 self->SetClassLoaderOverride(class_loader);
846 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
847 typedef int (*JNI_OnLoadFn)(JavaVM*, void*);
848 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
849 int version = (*jni_on_load)(this, nullptr);
851 if (runtime_->GetTargetSdkVersion() != 0 && runtime_->GetTargetSdkVersion() <= 21) {
852 fault_manager.EnsureArtActionInFrontOfSignalChain();
855 self->SetClassLoaderOverride(old_class_loader.get());
857 if (version == JNI_ERR) {
858 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
859 } else if (IsBadJniVersion(version)) {
860 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
861 path.c_str(), version);
862 // It's unwise to call dlclose() here, but we can mark it
863 // as bad and ensure that future load attempts will fail.
864 // We don't know how far JNI_OnLoad got, so there could
865 // be some partially-initialized stuff accessible through
866 // newly-registered native method calls. We could try to
867 // unregister them, but that doesn't seem worthwhile.
869 was_successful = true;
871 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
872 << " from JNI_OnLoad in \"" << path << "\"]";
875 library->SetResult(was_successful);
876 return was_successful;
879 void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) {
880 CHECK(m->IsNative());
881 mirror::Class* c = m->GetDeclaringClass();
882 // If this is a static method, it could be called before the class has been initialized.
883 CHECK(c->IsInitializing()) << c->GetStatus() << " " << PrettyMethod(m);
886 Thread* self = Thread::Current();
888 MutexLock mu(self, *Locks::jni_libraries_lock_);
889 native_method = libraries_->FindNativeMethod(m, detail);
891 // Throwing can cause libraries_lock to be reacquired.
892 if (native_method == nullptr) {
893 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
895 return native_method;
898 void JavaVMExt::SweepJniWeakGlobals(IsMarkedVisitor* visitor) {
899 MutexLock mu(Thread::Current(), weak_globals_lock_);
900 Runtime* const runtime = Runtime::Current();
901 for (auto* entry : weak_globals_) {
902 // Need to skip null here to distinguish between null entries and cleared weak ref entries.
903 if (!entry->IsNull()) {
904 // Since this is called by the GC, we don't need a read barrier.
905 mirror::Object* obj = entry->Read<kWithoutReadBarrier>();
906 mirror::Object* new_obj = visitor->IsMarked(obj);
907 if (new_obj == nullptr) {
908 new_obj = runtime->GetClearedJniWeakGlobal();
910 *entry = GcRoot<mirror::Object>(new_obj);
915 void JavaVMExt::TrimGlobals() {
916 WriterMutexLock mu(Thread::Current(), globals_lock_);
920 void JavaVMExt::VisitRoots(RootVisitor* visitor) {
921 Thread* self = Thread::Current();
922 ReaderMutexLock mu(self, globals_lock_);
923 globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal));
924 // The weak_globals table is visited by the GC itself (because it mutates the table).
927 // JNI Invocation interface.
929 extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
930 ScopedTrace trace(__FUNCTION__);
931 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
932 if (IsBadJniVersion(args->version)) {
933 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
936 RuntimeOptions options;
937 for (int i = 0; i < args->nOptions; ++i) {
938 JavaVMOption* option = &args->options[i];
939 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
941 bool ignore_unrecognized = args->ignoreUnrecognized;
942 if (!Runtime::Create(options, ignore_unrecognized)) {
945 Runtime* runtime = Runtime::Current();
946 bool started = runtime->Start();
948 delete Thread::Current()->GetJniEnv();
949 delete runtime->GetJavaVM();
950 LOG(WARNING) << "CreateJavaVM failed";
953 *p_env = Thread::Current()->GetJniEnv();
954 *p_vm = runtime->GetJavaVM();
958 extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
959 Runtime* runtime = Runtime::Current();
960 if (runtime == nullptr || buf_len == 0) {
964 vms_buf[0] = runtime->GetJavaVM();
969 // Historically unsupported.
970 extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {