blob: 7f677ab5d321e31bf9a91cf591e06cb59bf04a30 [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
553mirror::Object* JavaVMExt::DecodeGlobal(Thread* self, IndirectRef ref) {
554 return globals_.SynchronizedGet(self, &globals_lock_, ref);
555}
556
557mirror::Object* JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
558 MutexLock mu(self, weak_globals_lock_);
559 while (UNLIKELY(!allow_new_weak_globals_)) {
560 weak_globals_add_condition_.WaitHoldingLocks(self);
561 }
562 return weak_globals_.Get(ref);
563}
564
Ian Rogers68d8b422014-07-17 11:09:10 -0700565void JavaVMExt::DumpReferenceTables(std::ostream& os) {
566 Thread* self = Thread::Current();
567 {
568 ReaderMutexLock mu(self, globals_lock_);
569 globals_.Dump(os);
570 }
571 {
572 MutexLock mu(self, weak_globals_lock_);
573 weak_globals_.Dump(os);
574 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700575}
576
577bool JavaVMExt::LoadNativeLibrary(JNIEnv* env, const std::string& path, jobject class_loader,
578 std::string* error_msg) {
579 error_msg->clear();
580
581 // See if we've already loaded this library. If we have, and the class loader
582 // matches, return successfully without doing anything.
583 // TODO: for better results we should canonicalize the pathname (or even compare
584 // inodes). This implementation is fine if everybody is using System.loadLibrary.
585 SharedLibrary* library;
586 Thread* self = Thread::Current();
587 {
588 // TODO: move the locking (and more of this logic) into Libraries.
589 MutexLock mu(self, *Locks::jni_libraries_lock_);
590 library = libraries_->Get(path);
591 }
592 if (library != nullptr) {
593 if (env->IsSameObject(library->GetClassLoader(), class_loader) == JNI_FALSE) {
594 // The library will be associated with class_loader. The JNI
595 // spec says we can't load the same library into more than one
596 // class loader.
597 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
598 "ClassLoader %p; can't open in ClassLoader %p",
599 path.c_str(), library->GetClassLoader(), class_loader);
600 LOG(WARNING) << error_msg;
601 return false;
602 }
603 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
604 << " ClassLoader " << class_loader << "]";
605 if (!library->CheckOnLoadResult()) {
606 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
607 "to load \"%s\"", path.c_str());
608 return false;
609 }
610 return true;
611 }
612
613 // Open the shared library. Because we're using a full path, the system
614 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
615 // resolve this library's dependencies though.)
616
617 // Failures here are expected when java.library.path has several entries
618 // and we have to hunt for the lib.
619
620 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
621 // class unloading. Libraries will only be unloaded when the reference count (incremented by
622 // dlopen) becomes zero from dlclose.
623
624 Locks::mutator_lock_->AssertNotHeld(self);
625 const char* path_str = path.empty() ? nullptr : path.c_str();
626 void* handle = dlopen(path_str, RTLD_LAZY);
627 bool needs_native_bridge = false;
628 if (handle == nullptr) {
Calin Juravlec8423522014-08-12 20:55:20 +0100629 if (android::NativeBridgeIsSupported(path_str)) {
630 handle = android::NativeBridgeLoadLibrary(path_str, RTLD_LAZY);
Ian Rogers68d8b422014-07-17 11:09:10 -0700631 needs_native_bridge = true;
632 }
633 }
634
635 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_LAZY) returned " << handle << "]";
636
637 if (handle == nullptr) {
638 *error_msg = dlerror();
639 LOG(ERROR) << "dlopen(\"" << path << "\", RTLD_LAZY) failed: " << *error_msg;
640 return false;
641 }
642
643 if (env->ExceptionCheck() == JNI_TRUE) {
644 LOG(ERROR) << "Unexpected exception:";
645 env->ExceptionDescribe();
646 env->ExceptionClear();
647 }
648 // Create a new entry.
649 // TODO: move the locking (and more of this logic) into Libraries.
650 bool created_library = false;
651 {
652 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
653 std::unique_ptr<SharedLibrary> new_library(
654 new SharedLibrary(env, self, path, handle, class_loader));
655 MutexLock mu(self, *Locks::jni_libraries_lock_);
656 library = libraries_->Get(path);
657 if (library == nullptr) { // We won race to get libraries_lock.
658 library = new_library.release();
659 libraries_->Put(path, library);
660 created_library = true;
661 }
662 }
663 if (!created_library) {
664 LOG(INFO) << "WOW: we lost a race to add shared library: "
665 << "\"" << path << "\" ClassLoader=" << class_loader;
666 return library->CheckOnLoadResult();
667 }
668 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
669
670 bool was_successful = false;
671 void* sym;
672 if (needs_native_bridge) {
673 library->SetNeedsNativeBridge();
674 sym = library->FindSymbolWithNativeBridge("JNI_OnLoad", nullptr);
675 } else {
676 sym = dlsym(handle, "JNI_OnLoad");
677 }
678 if (sym == nullptr) {
679 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
680 was_successful = true;
681 } else {
682 // Call JNI_OnLoad. We have to override the current class
683 // loader, which will always be "null" since the stuff at the
684 // top of the stack is around Runtime.loadLibrary(). (See
685 // the comments in the JNI FindClass function.)
686 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
687 self->SetClassLoaderOverride(class_loader);
688
689 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
690 typedef int (*JNI_OnLoadFn)(JavaVM*, void*);
691 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
692 int version = (*jni_on_load)(this, nullptr);
693
Mathieu Chartierd0004802014-10-15 16:59:47 -0700694 if (runtime_->GetTargetSdkVersion() != 0 && runtime_->GetTargetSdkVersion() <= 21) {
695 fault_manager.EnsureArtActionInFrontOfSignalChain();
696 }
697
Ian Rogers68d8b422014-07-17 11:09:10 -0700698 self->SetClassLoaderOverride(old_class_loader.get());
699
700 if (version == JNI_ERR) {
701 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
702 } else if (IsBadJniVersion(version)) {
703 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
704 path.c_str(), version);
705 // It's unwise to call dlclose() here, but we can mark it
706 // as bad and ensure that future load attempts will fail.
707 // We don't know how far JNI_OnLoad got, so there could
708 // be some partially-initialized stuff accessible through
709 // newly-registered native method calls. We could try to
710 // unregister them, but that doesn't seem worthwhile.
711 } else {
712 was_successful = true;
713 }
714 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
715 << " from JNI_OnLoad in \"" << path << "\"]";
716 }
717
718 library->SetResult(was_successful);
719 return was_successful;
720}
721
722void* JavaVMExt::FindCodeForNativeMethod(mirror::ArtMethod* m) {
723 CHECK(m->IsNative());
724 mirror::Class* c = m->GetDeclaringClass();
725 // If this is a static method, it could be called before the class has been initialized.
726 CHECK(c->IsInitializing()) << c->GetStatus() << " " << PrettyMethod(m);
727 std::string detail;
728 void* native_method;
729 Thread* self = Thread::Current();
730 {
731 MutexLock mu(self, *Locks::jni_libraries_lock_);
732 native_method = libraries_->FindNativeMethod(m, detail);
733 }
734 // Throwing can cause libraries_lock to be reacquired.
735 if (native_method == nullptr) {
736 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
737 self->ThrowNewException(throw_location, "Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
738 }
739 return native_method;
740}
741
742void JavaVMExt::SweepJniWeakGlobals(IsMarkedCallback* callback, void* arg) {
743 MutexLock mu(Thread::Current(), weak_globals_lock_);
744 for (mirror::Object** entry : weak_globals_) {
745 // Since this is called by the GC, we don't need a read barrier.
746 mirror::Object* obj = *entry;
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -0700747 if (obj == nullptr) {
748 // Need to skip null here to distinguish between null entries
749 // and cleared weak ref entries.
750 continue;
751 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700752 mirror::Object* new_obj = callback(obj, arg);
753 if (new_obj == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700754 new_obj = Runtime::Current()->GetClearedJniWeakGlobal();
Ian Rogers68d8b422014-07-17 11:09:10 -0700755 }
756 *entry = new_obj;
757 }
758}
759
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800760void JavaVMExt::TrimGlobals() {
761 WriterMutexLock mu(Thread::Current(), globals_lock_);
762 globals_.Trim();
763}
764
Ian Rogers68d8b422014-07-17 11:09:10 -0700765void JavaVMExt::VisitRoots(RootCallback* callback, void* arg) {
766 Thread* self = Thread::Current();
767 {
768 ReaderMutexLock mu(self, globals_lock_);
769 globals_.VisitRoots(callback, arg, 0, kRootJNIGlobal);
770 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700771 // The weak_globals table is visited by the GC itself (because it mutates the table).
772}
773
774// JNI Invocation interface.
775
776extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
777 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
778 if (IsBadJniVersion(args->version)) {
779 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
780 return JNI_EVERSION;
781 }
782 RuntimeOptions options;
783 for (int i = 0; i < args->nOptions; ++i) {
784 JavaVMOption* option = &args->options[i];
785 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
786 }
787 bool ignore_unrecognized = args->ignoreUnrecognized;
788 if (!Runtime::Create(options, ignore_unrecognized)) {
789 return JNI_ERR;
790 }
791 Runtime* runtime = Runtime::Current();
792 bool started = runtime->Start();
793 if (!started) {
794 delete Thread::Current()->GetJniEnv();
795 delete runtime->GetJavaVM();
796 LOG(WARNING) << "CreateJavaVM failed";
797 return JNI_ERR;
798 }
799 *p_env = Thread::Current()->GetJniEnv();
800 *p_vm = runtime->GetJavaVM();
801 return JNI_OK;
802}
803
Ian Rogersf4d4da12014-11-11 16:10:33 -0800804extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700805 Runtime* runtime = Runtime::Current();
Ian Rogersf4d4da12014-11-11 16:10:33 -0800806 if (runtime == nullptr || buf_len == 0) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700807 *vm_count = 0;
808 } else {
809 *vm_count = 1;
Ian Rogersf4d4da12014-11-11 16:10:33 -0800810 vms_buf[0] = runtime->GetJavaVM();
Ian Rogers68d8b422014-07-17 11:09:10 -0700811 }
812 return JNI_OK;
813}
814
815// Historically unsupported.
816extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
817 return JNI_ERR;
818}
819
820} // namespace art