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