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