blob: 9eab3fde13220d94251013eded906eb3ef22b74c [file] [log] [blame]
Ian Rogers68d8b422014-07-17 11:09:10 -07001/*
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 "base/mutex.h"
22#include "base/stl_util.h"
23#include "check_jni.h"
24#include "indirect_reference_table-inl.h"
25#include "mirror/art_method.h"
26#include "mirror/class-inl.h"
27#include "mirror/class_loader.h"
28#include "native_bridge.h"
29#include "java_vm_ext.h"
30#include "parsed_options.h"
31#include "ScopedLocalRef.h"
32#include "scoped_thread_state_change.h"
33#include "thread-inl.h"
34#include "thread_list.h"
35
36namespace art {
37
38static const size_t kPinTableInitial = 16; // Arbitrary.
39static const size_t kPinTableMax = 1024; // Arbitrary sanity check.
40
41static size_t gGlobalsInitial = 512; // Arbitrary.
42static size_t gGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
43
44static const size_t kWeakGlobalsInitial = 16; // Arbitrary.
45static const size_t kWeakGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
46
47static bool IsBadJniVersion(int version) {
48 // We don't support JNI_VERSION_1_1. These are the only other valid versions.
49 return version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 && version != JNI_VERSION_1_6;
50}
51
52class SharedLibrary {
53 public:
54 SharedLibrary(JNIEnv* env, Thread* self, const std::string& path, void* handle,
55 jobject class_loader)
56 : path_(path),
57 handle_(handle),
58 needs_native_bridge_(false),
59 class_loader_(env->NewGlobalRef(class_loader)),
60 jni_on_load_lock_("JNI_OnLoad lock"),
61 jni_on_load_cond_("JNI_OnLoad condition variable", jni_on_load_lock_),
62 jni_on_load_thread_id_(self->GetThreadId()),
63 jni_on_load_result_(kPending) {
64 }
65
66 ~SharedLibrary() {
67 Thread* self = Thread::Current();
68 if (self != nullptr) {
69 self->GetJniEnv()->DeleteGlobalRef(class_loader_);
70 }
71 }
72
73 jobject GetClassLoader() const {
74 return class_loader_;
75 }
76
77 const std::string& GetPath() const {
78 return path_;
79 }
80
81 /*
82 * Check the result of an earlier call to JNI_OnLoad on this library.
83 * If the call has not yet finished in another thread, wait for it.
84 */
85 bool CheckOnLoadResult()
86 LOCKS_EXCLUDED(jni_on_load_lock_) {
87 Thread* self = Thread::Current();
88 bool okay;
89 {
90 MutexLock mu(self, jni_on_load_lock_);
91
92 if (jni_on_load_thread_id_ == self->GetThreadId()) {
93 // Check this so we don't end up waiting for ourselves. We need to return "true" so the
94 // caller can continue.
95 LOG(INFO) << *self << " recursive attempt to load library " << "\"" << path_ << "\"";
96 okay = true;
97 } else {
98 while (jni_on_load_result_ == kPending) {
99 VLOG(jni) << "[" << *self << " waiting for \"" << path_ << "\" " << "JNI_OnLoad...]";
100 jni_on_load_cond_.Wait(self);
101 }
102
103 okay = (jni_on_load_result_ == kOkay);
104 VLOG(jni) << "[Earlier JNI_OnLoad for \"" << path_ << "\" "
105 << (okay ? "succeeded" : "failed") << "]";
106 }
107 }
108 return okay;
109 }
110
111 void SetResult(bool result) LOCKS_EXCLUDED(jni_on_load_lock_) {
112 Thread* self = Thread::Current();
113 MutexLock mu(self, jni_on_load_lock_);
114
115 jni_on_load_result_ = result ? kOkay : kFailed;
116 jni_on_load_thread_id_ = 0;
117
118 // Broadcast a wakeup to anybody sleeping on the condition variable.
119 jni_on_load_cond_.Broadcast(self);
120 }
121
122 void SetNeedsNativeBridge() {
123 needs_native_bridge_ = true;
124 }
125
126 bool NeedsNativeBridge() const {
127 return needs_native_bridge_;
128 }
129
130 void* FindSymbol(const std::string& symbol_name) {
131 return dlsym(handle_, symbol_name.c_str());
132 }
133
134 void* FindSymbolWithNativeBridge(const std::string& symbol_name, const char* shorty) {
135 CHECK(NeedsNativeBridge());
136
137 uint32_t len = 0;
138 return NativeBridgeGetTrampoline(handle_, symbol_name.c_str(), shorty, len);
139 }
140
141 private:
142 enum JNI_OnLoadState {
143 kPending,
144 kFailed,
145 kOkay,
146 };
147
148 // Path to library "/system/lib/libjni.so".
149 const std::string path_;
150
151 // The void* returned by dlopen(3).
152 void* const handle_;
153
154 // True if a native bridge is required.
155 bool needs_native_bridge_;
156
157 // The ClassLoader this library is associated with, a global JNI reference that is
158 // created/deleted with the scope of the library.
159 const jobject class_loader_;
160
161 // Guards remaining items.
162 Mutex jni_on_load_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
163 // Wait for JNI_OnLoad in other thread.
164 ConditionVariable jni_on_load_cond_ GUARDED_BY(jni_on_load_lock_);
165 // Recursive invocation guard.
166 uint32_t jni_on_load_thread_id_ GUARDED_BY(jni_on_load_lock_);
167 // Result of earlier JNI_OnLoad call.
168 JNI_OnLoadState jni_on_load_result_ GUARDED_BY(jni_on_load_lock_);
169};
170
171// This exists mainly to keep implementation details out of the header file.
172class Libraries {
173 public:
174 Libraries() {
175 }
176
177 ~Libraries() {
178 STLDeleteValues(&libraries_);
179 }
180
181 void Dump(std::ostream& os) const {
182 bool first = true;
183 for (const auto& library : libraries_) {
184 if (!first) {
185 os << ' ';
186 }
187 first = false;
188 os << library.first;
189 }
190 }
191
192 size_t size() const {
193 return libraries_.size();
194 }
195
196 SharedLibrary* Get(const std::string& path) {
197 auto it = libraries_.find(path);
198 return (it == libraries_.end()) ? nullptr : it->second;
199 }
200
201 void Put(const std::string& path, SharedLibrary* library) {
202 libraries_.Put(path, library);
203 }
204
205 // See section 11.3 "Linking Native Methods" of the JNI spec.
206 void* FindNativeMethod(mirror::ArtMethod* m, std::string& detail)
207 EXCLUSIVE_LOCKS_REQUIRED(Locks::jni_libraries_lock_)
208 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
209 std::string jni_short_name(JniShortName(m));
210 std::string jni_long_name(JniLongName(m));
211 const mirror::ClassLoader* declaring_class_loader = m->GetDeclaringClass()->GetClassLoader();
212 ScopedObjectAccessUnchecked soa(Thread::Current());
213 for (const auto& lib : libraries_) {
214 SharedLibrary* library = lib.second;
215 if (soa.Decode<mirror::ClassLoader*>(library->GetClassLoader()) != declaring_class_loader) {
216 // We only search libraries loaded by the appropriate ClassLoader.
217 continue;
218 }
219 // Try the short name then the long name...
220 void* fn;
221 if (library->NeedsNativeBridge()) {
222 const char* shorty = m->GetShorty();
223 fn = library->FindSymbolWithNativeBridge(jni_short_name, shorty);
224 if (fn == nullptr) {
225 fn = library->FindSymbolWithNativeBridge(jni_long_name, shorty);
226 }
227 } else {
228 fn = library->FindSymbol(jni_short_name);
229 if (fn == nullptr) {
230 fn = library->FindSymbol(jni_long_name);
231 }
232 }
233 if (fn == nullptr) {
234 fn = library->FindSymbol(jni_long_name);
235 }
236 if (fn != nullptr) {
237 VLOG(jni) << "[Found native code for " << PrettyMethod(m)
238 << " in \"" << library->GetPath() << "\"]";
239 return fn;
240 }
241 }
242 detail += "No implementation found for ";
243 detail += PrettyMethod(m);
244 detail += " (tried " + jni_short_name + " and " + jni_long_name + ")";
245 LOG(ERROR) << detail;
246 return nullptr;
247 }
248
249 private:
250 SafeMap<std::string, SharedLibrary*> libraries_;
251};
252
253
254class JII {
255 public:
256 static jint DestroyJavaVM(JavaVM* vm) {
257 if (vm == nullptr) {
258 return JNI_ERR;
259 }
260 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
261 delete raw_vm->GetRuntime();
262 return JNI_OK;
263 }
264
265 static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
266 return AttachCurrentThreadInternal(vm, p_env, thr_args, false);
267 }
268
269 static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
270 return AttachCurrentThreadInternal(vm, p_env, thr_args, true);
271 }
272
273 static jint DetachCurrentThread(JavaVM* vm) {
274 if (vm == nullptr || Thread::Current() == nullptr) {
275 return JNI_ERR;
276 }
277 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
278 Runtime* runtime = raw_vm->GetRuntime();
279 runtime->DetachCurrentThread();
280 return JNI_OK;
281 }
282
283 static jint GetEnv(JavaVM* vm, void** env, jint version) {
284 // GetEnv always returns a JNIEnv* for the most current supported JNI version,
285 // and unlike other calls that take a JNI version doesn't care if you supply
286 // JNI_VERSION_1_1, which we don't otherwise support.
287 if (IsBadJniVersion(version) && version != JNI_VERSION_1_1) {
288 LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version;
289 return JNI_EVERSION;
290 }
291 if (vm == nullptr || env == nullptr) {
292 return JNI_ERR;
293 }
294 Thread* thread = Thread::Current();
295 if (thread == nullptr) {
296 *env = nullptr;
297 return JNI_EDETACHED;
298 }
299 *env = thread->GetJniEnv();
300 return JNI_OK;
301 }
302
303 private:
304 static jint AttachCurrentThreadInternal(JavaVM* vm, JNIEnv** p_env, void* raw_args, bool as_daemon) {
305 if (vm == nullptr || p_env == nullptr) {
306 return JNI_ERR;
307 }
308
309 // Return immediately if we're already attached.
310 Thread* self = Thread::Current();
311 if (self != nullptr) {
312 *p_env = self->GetJniEnv();
313 return JNI_OK;
314 }
315
316 Runtime* runtime = reinterpret_cast<JavaVMExt*>(vm)->GetRuntime();
317
318 // No threads allowed in zygote mode.
319 if (runtime->IsZygote()) {
320 LOG(ERROR) << "Attempt to attach a thread in the zygote";
321 return JNI_ERR;
322 }
323
324 JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(raw_args);
325 const char* thread_name = nullptr;
326 jobject thread_group = nullptr;
327 if (args != nullptr) {
328 if (IsBadJniVersion(args->version)) {
329 LOG(ERROR) << "Bad JNI version passed to "
330 << (as_daemon ? "AttachCurrentThreadAsDaemon" : "AttachCurrentThread") << ": "
331 << args->version;
332 return JNI_EVERSION;
333 }
334 thread_name = args->name;
335 thread_group = args->group;
336 }
337
338 if (!runtime->AttachCurrentThread(thread_name, as_daemon, thread_group, !runtime->IsCompiler())) {
339 *p_env = nullptr;
340 return JNI_ERR;
341 } else {
342 *p_env = Thread::Current()->GetJniEnv();
343 return JNI_OK;
344 }
345 }
346};
347
348const JNIInvokeInterface gJniInvokeInterface = {
349 nullptr, // reserved0
350 nullptr, // reserved1
351 nullptr, // reserved2
352 JII::DestroyJavaVM,
353 JII::AttachCurrentThread,
354 JII::DetachCurrentThread,
355 JII::GetEnv,
356 JII::AttachCurrentThreadAsDaemon
357};
358
359JavaVMExt::JavaVMExt(Runtime* runtime, ParsedOptions* options)
360 : runtime_(runtime),
361 check_jni_abort_hook_(nullptr),
362 check_jni_abort_hook_data_(nullptr),
363 check_jni_(false), // Initialized properly in the constructor body below.
364 force_copy_(options->force_copy_),
365 tracing_enabled_(!options->jni_trace_.empty() || VLOG_IS_ON(third_party_jni)),
366 trace_(options->jni_trace_),
367 pins_lock_("JNI pin table lock", kPinTableLock),
368 pin_table_("pin table", kPinTableInitial, kPinTableMax),
369 globals_lock_("JNI global reference table lock"),
370 globals_(gGlobalsInitial, gGlobalsMax, kGlobal),
371 libraries_(new Libraries),
372 unchecked_functions_(&gJniInvokeInterface),
373 weak_globals_lock_("JNI weak global reference table lock"),
374 weak_globals_(kWeakGlobalsInitial, kWeakGlobalsMax, kWeakGlobal),
375 allow_new_weak_globals_(true),
376 weak_globals_add_condition_("weak globals add condition", weak_globals_lock_) {
377 functions = unchecked_functions_;
378 if (options->check_jni_) {
379 SetCheckJniEnabled(true);
380 }
381}
382
383JavaVMExt::~JavaVMExt() {
384}
385
386void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) {
387 Thread* self = Thread::Current();
388 ScopedObjectAccess soa(self);
389 mirror::ArtMethod* current_method = self->GetCurrentMethod(nullptr);
390
391 std::ostringstream os;
392 os << "JNI DETECTED ERROR IN APPLICATION: " << msg;
393
394 if (jni_function_name != nullptr) {
395 os << "\n in call to " << jni_function_name;
396 }
397 // TODO: is this useful given that we're about to dump the calling thread's stack?
398 if (current_method != nullptr) {
399 os << "\n from " << PrettyMethod(current_method);
400 }
401 os << "\n";
402 self->Dump(os);
403
404 if (check_jni_abort_hook_ != nullptr) {
405 check_jni_abort_hook_(check_jni_abort_hook_data_, os.str());
406 } else {
407 // Ensure that we get a native stack trace for this thread.
408 self->TransitionFromRunnableToSuspended(kNative);
409 LOG(FATAL) << os.str();
410 self->TransitionFromSuspendedToRunnable(); // Unreachable, keep annotalysis happy.
411 }
412}
413
414void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) {
415 std::string msg;
416 StringAppendV(&msg, fmt, ap);
417 JniAbort(jni_function_name, msg.c_str());
418}
419
420void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) {
421 va_list args;
422 va_start(args, fmt);
423 JniAbortV(jni_function_name, fmt, args);
424 va_end(args);
425}
426
427bool JavaVMExt::ShouldTrace(mirror::ArtMethod* method) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
428 // Fast where no tracing is enabled.
429 if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) {
430 return false;
431 }
432 // Perform checks based on class name.
433 StringPiece class_name(method->GetDeclaringClassDescriptor());
434 if (!trace_.empty() && class_name.find(trace_) != std::string::npos) {
435 return true;
436 }
437 if (!VLOG_IS_ON(third_party_jni)) {
438 return false;
439 }
440 // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
441 // like part of Android.
442 static const char* gBuiltInPrefixes[] = {
443 "Landroid/",
444 "Lcom/android/",
445 "Lcom/google/android/",
446 "Ldalvik/",
447 "Ljava/",
448 "Ljavax/",
449 "Llibcore/",
450 "Lorg/apache/harmony/",
451 };
452 for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) {
453 if (class_name.starts_with(gBuiltInPrefixes[i])) {
454 return false;
455 }
456 }
457 return true;
458}
459
460jobject JavaVMExt::AddGlobalRef(Thread* self, mirror::Object* obj) {
461 // Check for null after decoding the object to handle cleared weak globals.
462 if (obj == nullptr) {
463 return nullptr;
464 }
465 WriterMutexLock mu(self, globals_lock_);
466 IndirectRef ref = globals_.Add(IRT_FIRST_SEGMENT, obj);
467 return reinterpret_cast<jobject>(ref);
468}
469
470jweak JavaVMExt::AddWeakGlobalRef(Thread* self, mirror::Object* obj) {
471 if (obj == nullptr) {
472 return nullptr;
473 }
474 MutexLock mu(self, weak_globals_lock_);
475 while (UNLIKELY(!allow_new_weak_globals_)) {
476 weak_globals_add_condition_.WaitHoldingLocks(self);
477 }
478 IndirectRef ref = weak_globals_.Add(IRT_FIRST_SEGMENT, obj);
479 return reinterpret_cast<jweak>(ref);
480}
481
482void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
483 if (obj == nullptr) {
484 return;
485 }
486 WriterMutexLock mu(self, globals_lock_);
487 if (!globals_.Remove(IRT_FIRST_SEGMENT, obj)) {
488 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
489 << "failed to find entry";
490 }
491}
492
493void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
494 if (obj == nullptr) {
495 return;
496 }
497 MutexLock mu(self, weak_globals_lock_);
498 if (!weak_globals_.Remove(IRT_FIRST_SEGMENT, obj)) {
499 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
500 << "failed to find entry";
501 }
502}
503
504static void ThreadEnableCheckJni(Thread* thread, void* arg) {
505 bool* check_jni = reinterpret_cast<bool*>(arg);
506 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
507}
508
509bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
510 bool old_check_jni = check_jni_;
511 check_jni_ = enabled;
512 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
513 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
514 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
515 return old_check_jni;
516}
517
518void JavaVMExt::DumpForSigQuit(std::ostream& os) {
519 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
520 if (force_copy_) {
521 os << " (with forcecopy)";
522 }
523 Thread* self = Thread::Current();
524 {
525 MutexLock mu(self, pins_lock_);
526 os << "; pins=" << pin_table_.Size();
527 }
528 {
529 ReaderMutexLock mu(self, globals_lock_);
530 os << "; globals=" << globals_.Capacity();
531 }
532 {
533 MutexLock mu(self, weak_globals_lock_);
534 if (weak_globals_.Capacity() > 0) {
535 os << " (plus " << weak_globals_.Capacity() << " weak)";
536 }
537 }
538 os << '\n';
539
540 {
541 MutexLock mu(self, *Locks::jni_libraries_lock_);
542 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
543 }
544}
545
546void JavaVMExt::DisallowNewWeakGlobals() {
547 MutexLock mu(Thread::Current(), weak_globals_lock_);
548 allow_new_weak_globals_ = false;
549}
550
551void JavaVMExt::AllowNewWeakGlobals() {
552 Thread* self = Thread::Current();
553 MutexLock mu(self, weak_globals_lock_);
554 allow_new_weak_globals_ = true;
555 weak_globals_add_condition_.Broadcast(self);
556}
557
558mirror::Object* JavaVMExt::DecodeGlobal(Thread* self, IndirectRef ref) {
559 return globals_.SynchronizedGet(self, &globals_lock_, ref);
560}
561
562mirror::Object* JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
563 MutexLock mu(self, weak_globals_lock_);
564 while (UNLIKELY(!allow_new_weak_globals_)) {
565 weak_globals_add_condition_.WaitHoldingLocks(self);
566 }
567 return weak_globals_.Get(ref);
568}
569
570void JavaVMExt::PinPrimitiveArray(Thread* self, mirror::Array* array) {
571 MutexLock mu(self, pins_lock_);
572 pin_table_.Add(array);
573}
574
575void JavaVMExt::UnpinPrimitiveArray(Thread* self, mirror::Array* array) {
576 MutexLock mu(self, pins_lock_);
577 pin_table_.Remove(array);
578}
579
580void JavaVMExt::DumpReferenceTables(std::ostream& os) {
581 Thread* self = Thread::Current();
582 {
583 ReaderMutexLock mu(self, globals_lock_);
584 globals_.Dump(os);
585 }
586 {
587 MutexLock mu(self, weak_globals_lock_);
588 weak_globals_.Dump(os);
589 }
590 {
591 MutexLock mu(self, pins_lock_);
592 pin_table_.Dump(os);
593 }
594}
595
596bool JavaVMExt::LoadNativeLibrary(JNIEnv* env, const std::string& path, jobject class_loader,
597 std::string* error_msg) {
598 error_msg->clear();
599
600 // See if we've already loaded this library. If we have, and the class loader
601 // matches, return successfully without doing anything.
602 // TODO: for better results we should canonicalize the pathname (or even compare
603 // inodes). This implementation is fine if everybody is using System.loadLibrary.
604 SharedLibrary* library;
605 Thread* self = Thread::Current();
606 {
607 // TODO: move the locking (and more of this logic) into Libraries.
608 MutexLock mu(self, *Locks::jni_libraries_lock_);
609 library = libraries_->Get(path);
610 }
611 if (library != nullptr) {
612 if (env->IsSameObject(library->GetClassLoader(), class_loader) == JNI_FALSE) {
613 // The library will be associated with class_loader. The JNI
614 // spec says we can't load the same library into more than one
615 // class loader.
616 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
617 "ClassLoader %p; can't open in ClassLoader %p",
618 path.c_str(), library->GetClassLoader(), class_loader);
619 LOG(WARNING) << error_msg;
620 return false;
621 }
622 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
623 << " ClassLoader " << class_loader << "]";
624 if (!library->CheckOnLoadResult()) {
625 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
626 "to load \"%s\"", path.c_str());
627 return false;
628 }
629 return true;
630 }
631
632 // Open the shared library. Because we're using a full path, the system
633 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
634 // resolve this library's dependencies though.)
635
636 // Failures here are expected when java.library.path has several entries
637 // and we have to hunt for the lib.
638
639 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
640 // class unloading. Libraries will only be unloaded when the reference count (incremented by
641 // dlopen) becomes zero from dlclose.
642
643 Locks::mutator_lock_->AssertNotHeld(self);
644 const char* path_str = path.empty() ? nullptr : path.c_str();
645 void* handle = dlopen(path_str, RTLD_LAZY);
646 bool needs_native_bridge = false;
647 if (handle == nullptr) {
648 if (NativeBridgeIsSupported(path_str)) {
649 handle = NativeBridgeLoadLibrary(path_str, RTLD_LAZY);
650 needs_native_bridge = true;
651 }
652 }
653
654 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_LAZY) returned " << handle << "]";
655
656 if (handle == nullptr) {
657 *error_msg = dlerror();
658 LOG(ERROR) << "dlopen(\"" << path << "\", RTLD_LAZY) failed: " << *error_msg;
659 return false;
660 }
661
662 if (env->ExceptionCheck() == JNI_TRUE) {
663 LOG(ERROR) << "Unexpected exception:";
664 env->ExceptionDescribe();
665 env->ExceptionClear();
666 }
667 // Create a new entry.
668 // TODO: move the locking (and more of this logic) into Libraries.
669 bool created_library = false;
670 {
671 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
672 std::unique_ptr<SharedLibrary> new_library(
673 new SharedLibrary(env, self, path, handle, class_loader));
674 MutexLock mu(self, *Locks::jni_libraries_lock_);
675 library = libraries_->Get(path);
676 if (library == nullptr) { // We won race to get libraries_lock.
677 library = new_library.release();
678 libraries_->Put(path, library);
679 created_library = true;
680 }
681 }
682 if (!created_library) {
683 LOG(INFO) << "WOW: we lost a race to add shared library: "
684 << "\"" << path << "\" ClassLoader=" << class_loader;
685 return library->CheckOnLoadResult();
686 }
687 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
688
689 bool was_successful = false;
690 void* sym;
691 if (needs_native_bridge) {
692 library->SetNeedsNativeBridge();
693 sym = library->FindSymbolWithNativeBridge("JNI_OnLoad", nullptr);
694 } else {
695 sym = dlsym(handle, "JNI_OnLoad");
696 }
697 if (sym == nullptr) {
698 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
699 was_successful = true;
700 } else {
701 // Call JNI_OnLoad. We have to override the current class
702 // loader, which will always be "null" since the stuff at the
703 // top of the stack is around Runtime.loadLibrary(). (See
704 // the comments in the JNI FindClass function.)
705 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
706 self->SetClassLoaderOverride(class_loader);
707
708 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
709 typedef int (*JNI_OnLoadFn)(JavaVM*, void*);
710 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
711 int version = (*jni_on_load)(this, nullptr);
712
713 self->SetClassLoaderOverride(old_class_loader.get());
714
715 if (version == JNI_ERR) {
716 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
717 } else if (IsBadJniVersion(version)) {
718 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
719 path.c_str(), version);
720 // It's unwise to call dlclose() here, but we can mark it
721 // as bad and ensure that future load attempts will fail.
722 // We don't know how far JNI_OnLoad got, so there could
723 // be some partially-initialized stuff accessible through
724 // newly-registered native method calls. We could try to
725 // unregister them, but that doesn't seem worthwhile.
726 } else {
727 was_successful = true;
728 }
729 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
730 << " from JNI_OnLoad in \"" << path << "\"]";
731 }
732
733 library->SetResult(was_successful);
734 return was_successful;
735}
736
737void* JavaVMExt::FindCodeForNativeMethod(mirror::ArtMethod* m) {
738 CHECK(m->IsNative());
739 mirror::Class* c = m->GetDeclaringClass();
740 // If this is a static method, it could be called before the class has been initialized.
741 CHECK(c->IsInitializing()) << c->GetStatus() << " " << PrettyMethod(m);
742 std::string detail;
743 void* native_method;
744 Thread* self = Thread::Current();
745 {
746 MutexLock mu(self, *Locks::jni_libraries_lock_);
747 native_method = libraries_->FindNativeMethod(m, detail);
748 }
749 // Throwing can cause libraries_lock to be reacquired.
750 if (native_method == nullptr) {
751 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
752 self->ThrowNewException(throw_location, "Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
753 }
754 return native_method;
755}
756
757void JavaVMExt::SweepJniWeakGlobals(IsMarkedCallback* callback, void* arg) {
758 MutexLock mu(Thread::Current(), weak_globals_lock_);
759 for (mirror::Object** entry : weak_globals_) {
760 // Since this is called by the GC, we don't need a read barrier.
761 mirror::Object* obj = *entry;
762 mirror::Object* new_obj = callback(obj, arg);
763 if (new_obj == nullptr) {
764 new_obj = kClearedJniWeakGlobal;
765 }
766 *entry = new_obj;
767 }
768}
769
770void JavaVMExt::VisitRoots(RootCallback* callback, void* arg) {
771 Thread* self = Thread::Current();
772 {
773 ReaderMutexLock mu(self, globals_lock_);
774 globals_.VisitRoots(callback, arg, 0, kRootJNIGlobal);
775 }
776 {
777 MutexLock mu(self, pins_lock_);
778 pin_table_.VisitRoots(callback, arg, 0, kRootVMInternal);
779 }
780 // The weak_globals table is visited by the GC itself (because it mutates the table).
781}
782
783// JNI Invocation interface.
784
785extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
786 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
787 if (IsBadJniVersion(args->version)) {
788 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
789 return JNI_EVERSION;
790 }
791 RuntimeOptions options;
792 for (int i = 0; i < args->nOptions; ++i) {
793 JavaVMOption* option = &args->options[i];
794 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
795 }
796 bool ignore_unrecognized = args->ignoreUnrecognized;
797 if (!Runtime::Create(options, ignore_unrecognized)) {
798 return JNI_ERR;
799 }
800 Runtime* runtime = Runtime::Current();
801 bool started = runtime->Start();
802 if (!started) {
803 delete Thread::Current()->GetJniEnv();
804 delete runtime->GetJavaVM();
805 LOG(WARNING) << "CreateJavaVM failed";
806 return JNI_ERR;
807 }
808 *p_env = Thread::Current()->GetJniEnv();
809 *p_vm = runtime->GetJavaVM();
810 return JNI_OK;
811}
812
813extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms, jsize, jsize* vm_count) {
814 Runtime* runtime = Runtime::Current();
815 if (runtime == nullptr) {
816 *vm_count = 0;
817 } else {
818 *vm_count = 1;
819 vms[0] = runtime->GetJavaVM();
820 }
821 return JNI_OK;
822}
823
824// Historically unsupported.
825extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
826 return JNI_ERR;
827}
828
829} // namespace art