blob: 19e03d8f825a5c4e66bd19974973cb1266481c16 [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"
Mathieu Chartierd0004802014-10-15 16:59:47 -070025#include "fault_handler.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070026#include "indirect_reference_table-inl.h"
27#include "mirror/art_method.h"
28#include "mirror/class-inl.h"
29#include "mirror/class_loader.h"
Calin Juravlec8423522014-08-12 20:55:20 +010030#include "nativebridge/native_bridge.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070031#include "java_vm_ext.h"
32#include "parsed_options.h"
Ian Rogersc0542af2014-09-03 16:16:56 -070033#include "runtime-inl.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070034#include "ScopedLocalRef.h"
35#include "scoped_thread_state_change.h"
36#include "thread-inl.h"
37#include "thread_list.h"
38
39namespace art {
40
Ian Rogers68d8b422014-07-17 11:09:10 -070041static 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;
Calin Juravlec8423522014-08-12 20:55:20 +0100138 return android::NativeBridgeGetTrampoline(handle_, symbol_name.c_str(), shorty, len);
Ian Rogers68d8b422014-07-17 11:09:10 -0700139 }
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:
Mathieu Chartierbad02672014-08-25 13:08:22 -0700250 AllocationTrackingSafeMap<std::string, SharedLibrary*, kAllocatorTagJNILibrarires> libraries_;
Ian Rogers68d8b422014-07-17 11:09:10 -0700251};
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_),
Ian Rogers68d8b422014-07-17 11:09:10 -0700367 globals_lock_("JNI global reference table lock"),
368 globals_(gGlobalsInitial, gGlobalsMax, kGlobal),
369 libraries_(new Libraries),
370 unchecked_functions_(&gJniInvokeInterface),
371 weak_globals_lock_("JNI weak global reference table lock"),
372 weak_globals_(kWeakGlobalsInitial, kWeakGlobalsMax, kWeakGlobal),
373 allow_new_weak_globals_(true),
374 weak_globals_add_condition_("weak globals add condition", weak_globals_lock_) {
375 functions = unchecked_functions_;
376 if (options->check_jni_) {
377 SetCheckJniEnabled(true);
378 }
379}
380
381JavaVMExt::~JavaVMExt() {
382}
383
384void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) {
385 Thread* self = Thread::Current();
386 ScopedObjectAccess soa(self);
387 mirror::ArtMethod* current_method = self->GetCurrentMethod(nullptr);
388
389 std::ostringstream os;
390 os << "JNI DETECTED ERROR IN APPLICATION: " << msg;
391
392 if (jni_function_name != nullptr) {
393 os << "\n in call to " << jni_function_name;
394 }
395 // TODO: is this useful given that we're about to dump the calling thread's stack?
396 if (current_method != nullptr) {
397 os << "\n from " << PrettyMethod(current_method);
398 }
399 os << "\n";
400 self->Dump(os);
401
402 if (check_jni_abort_hook_ != nullptr) {
403 check_jni_abort_hook_(check_jni_abort_hook_data_, os.str());
404 } else {
405 // Ensure that we get a native stack trace for this thread.
406 self->TransitionFromRunnableToSuspended(kNative);
407 LOG(FATAL) << os.str();
408 self->TransitionFromSuspendedToRunnable(); // Unreachable, keep annotalysis happy.
409 }
410}
411
412void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) {
413 std::string msg;
414 StringAppendV(&msg, fmt, ap);
415 JniAbort(jni_function_name, msg.c_str());
416}
417
418void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) {
419 va_list args;
420 va_start(args, fmt);
421 JniAbortV(jni_function_name, fmt, args);
422 va_end(args);
423}
424
425bool JavaVMExt::ShouldTrace(mirror::ArtMethod* method) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
426 // Fast where no tracing is enabled.
427 if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) {
428 return false;
429 }
430 // Perform checks based on class name.
431 StringPiece class_name(method->GetDeclaringClassDescriptor());
432 if (!trace_.empty() && class_name.find(trace_) != std::string::npos) {
433 return true;
434 }
435 if (!VLOG_IS_ON(third_party_jni)) {
436 return false;
437 }
438 // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
439 // like part of Android.
440 static const char* gBuiltInPrefixes[] = {
441 "Landroid/",
442 "Lcom/android/",
443 "Lcom/google/android/",
444 "Ldalvik/",
445 "Ljava/",
446 "Ljavax/",
447 "Llibcore/",
448 "Lorg/apache/harmony/",
449 };
450 for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) {
451 if (class_name.starts_with(gBuiltInPrefixes[i])) {
452 return false;
453 }
454 }
455 return true;
456}
457
458jobject JavaVMExt::AddGlobalRef(Thread* self, mirror::Object* obj) {
459 // Check for null after decoding the object to handle cleared weak globals.
460 if (obj == nullptr) {
461 return nullptr;
462 }
463 WriterMutexLock mu(self, globals_lock_);
464 IndirectRef ref = globals_.Add(IRT_FIRST_SEGMENT, obj);
465 return reinterpret_cast<jobject>(ref);
466}
467
468jweak JavaVMExt::AddWeakGlobalRef(Thread* self, mirror::Object* obj) {
469 if (obj == nullptr) {
470 return nullptr;
471 }
472 MutexLock mu(self, weak_globals_lock_);
473 while (UNLIKELY(!allow_new_weak_globals_)) {
474 weak_globals_add_condition_.WaitHoldingLocks(self);
475 }
476 IndirectRef ref = weak_globals_.Add(IRT_FIRST_SEGMENT, obj);
477 return reinterpret_cast<jweak>(ref);
478}
479
480void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
481 if (obj == nullptr) {
482 return;
483 }
484 WriterMutexLock mu(self, globals_lock_);
485 if (!globals_.Remove(IRT_FIRST_SEGMENT, obj)) {
486 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
487 << "failed to find entry";
488 }
489}
490
491void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
492 if (obj == nullptr) {
493 return;
494 }
495 MutexLock mu(self, weak_globals_lock_);
496 if (!weak_globals_.Remove(IRT_FIRST_SEGMENT, obj)) {
497 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
498 << "failed to find entry";
499 }
500}
501
502static void ThreadEnableCheckJni(Thread* thread, void* arg) {
503 bool* check_jni = reinterpret_cast<bool*>(arg);
504 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
505}
506
507bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
508 bool old_check_jni = check_jni_;
509 check_jni_ = enabled;
510 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
511 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
512 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
513 return old_check_jni;
514}
515
516void JavaVMExt::DumpForSigQuit(std::ostream& os) {
517 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
518 if (force_copy_) {
519 os << " (with forcecopy)";
520 }
521 Thread* self = Thread::Current();
522 {
Ian Rogers68d8b422014-07-17 11:09:10 -0700523 ReaderMutexLock mu(self, globals_lock_);
524 os << "; globals=" << globals_.Capacity();
525 }
526 {
527 MutexLock mu(self, weak_globals_lock_);
528 if (weak_globals_.Capacity() > 0) {
529 os << " (plus " << weak_globals_.Capacity() << " weak)";
530 }
531 }
532 os << '\n';
533
534 {
535 MutexLock mu(self, *Locks::jni_libraries_lock_);
536 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
537 }
538}
539
540void JavaVMExt::DisallowNewWeakGlobals() {
541 MutexLock mu(Thread::Current(), weak_globals_lock_);
542 allow_new_weak_globals_ = false;
543}
544
545void JavaVMExt::AllowNewWeakGlobals() {
546 Thread* self = Thread::Current();
547 MutexLock mu(self, weak_globals_lock_);
548 allow_new_weak_globals_ = true;
549 weak_globals_add_condition_.Broadcast(self);
550}
551
552mirror::Object* JavaVMExt::DecodeGlobal(Thread* self, IndirectRef ref) {
553 return globals_.SynchronizedGet(self, &globals_lock_, ref);
554}
555
556mirror::Object* JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
557 MutexLock mu(self, weak_globals_lock_);
558 while (UNLIKELY(!allow_new_weak_globals_)) {
559 weak_globals_add_condition_.WaitHoldingLocks(self);
560 }
561 return weak_globals_.Get(ref);
562}
563
Ian Rogers68d8b422014-07-17 11:09:10 -0700564void JavaVMExt::DumpReferenceTables(std::ostream& os) {
565 Thread* self = Thread::Current();
566 {
567 ReaderMutexLock mu(self, globals_lock_);
568 globals_.Dump(os);
569 }
570 {
571 MutexLock mu(self, weak_globals_lock_);
572 weak_globals_.Dump(os);
573 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700574}
575
576bool JavaVMExt::LoadNativeLibrary(JNIEnv* env, const std::string& path, jobject class_loader,
577 std::string* error_msg) {
578 error_msg->clear();
579
580 // See if we've already loaded this library. If we have, and the class loader
581 // matches, return successfully without doing anything.
582 // TODO: for better results we should canonicalize the pathname (or even compare
583 // inodes). This implementation is fine if everybody is using System.loadLibrary.
584 SharedLibrary* library;
585 Thread* self = Thread::Current();
586 {
587 // TODO: move the locking (and more of this logic) into Libraries.
588 MutexLock mu(self, *Locks::jni_libraries_lock_);
589 library = libraries_->Get(path);
590 }
591 if (library != nullptr) {
592 if (env->IsSameObject(library->GetClassLoader(), class_loader) == JNI_FALSE) {
593 // The library will be associated with class_loader. The JNI
594 // spec says we can't load the same library into more than one
595 // class loader.
596 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
597 "ClassLoader %p; can't open in ClassLoader %p",
598 path.c_str(), library->GetClassLoader(), class_loader);
599 LOG(WARNING) << error_msg;
600 return false;
601 }
602 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
603 << " ClassLoader " << class_loader << "]";
604 if (!library->CheckOnLoadResult()) {
605 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
606 "to load \"%s\"", path.c_str());
607 return false;
608 }
609 return true;
610 }
611
612 // Open the shared library. Because we're using a full path, the system
613 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
614 // resolve this library's dependencies though.)
615
616 // Failures here are expected when java.library.path has several entries
617 // and we have to hunt for the lib.
618
619 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
620 // class unloading. Libraries will only be unloaded when the reference count (incremented by
621 // dlopen) becomes zero from dlclose.
622
623 Locks::mutator_lock_->AssertNotHeld(self);
624 const char* path_str = path.empty() ? nullptr : path.c_str();
625 void* handle = dlopen(path_str, RTLD_LAZY);
626 bool needs_native_bridge = false;
627 if (handle == nullptr) {
Calin Juravlec8423522014-08-12 20:55:20 +0100628 if (android::NativeBridgeIsSupported(path_str)) {
629 handle = android::NativeBridgeLoadLibrary(path_str, RTLD_LAZY);
Ian Rogers68d8b422014-07-17 11:09:10 -0700630 needs_native_bridge = true;
631 }
632 }
633
634 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_LAZY) returned " << handle << "]";
635
636 if (handle == nullptr) {
637 *error_msg = dlerror();
638 LOG(ERROR) << "dlopen(\"" << path << "\", RTLD_LAZY) failed: " << *error_msg;
639 return false;
640 }
641
642 if (env->ExceptionCheck() == JNI_TRUE) {
643 LOG(ERROR) << "Unexpected exception:";
644 env->ExceptionDescribe();
645 env->ExceptionClear();
646 }
647 // Create a new entry.
648 // TODO: move the locking (and more of this logic) into Libraries.
649 bool created_library = false;
650 {
651 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
652 std::unique_ptr<SharedLibrary> new_library(
653 new SharedLibrary(env, self, path, handle, class_loader));
654 MutexLock mu(self, *Locks::jni_libraries_lock_);
655 library = libraries_->Get(path);
656 if (library == nullptr) { // We won race to get libraries_lock.
657 library = new_library.release();
658 libraries_->Put(path, library);
659 created_library = true;
660 }
661 }
662 if (!created_library) {
663 LOG(INFO) << "WOW: we lost a race to add shared library: "
664 << "\"" << path << "\" ClassLoader=" << class_loader;
665 return library->CheckOnLoadResult();
666 }
667 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
668
669 bool was_successful = false;
670 void* sym;
671 if (needs_native_bridge) {
672 library->SetNeedsNativeBridge();
673 sym = library->FindSymbolWithNativeBridge("JNI_OnLoad", nullptr);
674 } else {
675 sym = dlsym(handle, "JNI_OnLoad");
676 }
677 if (sym == nullptr) {
678 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
679 was_successful = true;
680 } else {
681 // Call JNI_OnLoad. We have to override the current class
682 // loader, which will always be "null" since the stuff at the
683 // top of the stack is around Runtime.loadLibrary(). (See
684 // the comments in the JNI FindClass function.)
685 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
686 self->SetClassLoaderOverride(class_loader);
687
688 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
689 typedef int (*JNI_OnLoadFn)(JavaVM*, void*);
690 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
691 int version = (*jni_on_load)(this, nullptr);
692
Mathieu Chartierd0004802014-10-15 16:59:47 -0700693 if (runtime_->GetTargetSdkVersion() != 0 && runtime_->GetTargetSdkVersion() <= 21) {
694 fault_manager.EnsureArtActionInFrontOfSignalChain();
695 }
696
Ian Rogers68d8b422014-07-17 11:09:10 -0700697 self->SetClassLoaderOverride(old_class_loader.get());
698
699 if (version == JNI_ERR) {
700 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
701 } else if (IsBadJniVersion(version)) {
702 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
703 path.c_str(), version);
704 // It's unwise to call dlclose() here, but we can mark it
705 // as bad and ensure that future load attempts will fail.
706 // We don't know how far JNI_OnLoad got, so there could
707 // be some partially-initialized stuff accessible through
708 // newly-registered native method calls. We could try to
709 // unregister them, but that doesn't seem worthwhile.
710 } else {
711 was_successful = true;
712 }
713 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
714 << " from JNI_OnLoad in \"" << path << "\"]";
715 }
716
717 library->SetResult(was_successful);
718 return was_successful;
719}
720
721void* JavaVMExt::FindCodeForNativeMethod(mirror::ArtMethod* m) {
722 CHECK(m->IsNative());
723 mirror::Class* c = m->GetDeclaringClass();
724 // If this is a static method, it could be called before the class has been initialized.
725 CHECK(c->IsInitializing()) << c->GetStatus() << " " << PrettyMethod(m);
726 std::string detail;
727 void* native_method;
728 Thread* self = Thread::Current();
729 {
730 MutexLock mu(self, *Locks::jni_libraries_lock_);
731 native_method = libraries_->FindNativeMethod(m, detail);
732 }
733 // Throwing can cause libraries_lock to be reacquired.
734 if (native_method == nullptr) {
735 ThrowLocation throw_location = self->GetCurrentLocationForThrow();
736 self->ThrowNewException(throw_location, "Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
737 }
738 return native_method;
739}
740
741void JavaVMExt::SweepJniWeakGlobals(IsMarkedCallback* callback, void* arg) {
742 MutexLock mu(Thread::Current(), weak_globals_lock_);
743 for (mirror::Object** entry : weak_globals_) {
744 // Since this is called by the GC, we don't need a read barrier.
745 mirror::Object* obj = *entry;
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -0700746 if (obj == nullptr) {
747 // Need to skip null here to distinguish between null entries
748 // and cleared weak ref entries.
749 continue;
750 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700751 mirror::Object* new_obj = callback(obj, arg);
752 if (new_obj == nullptr) {
Ian Rogersc0542af2014-09-03 16:16:56 -0700753 new_obj = Runtime::Current()->GetClearedJniWeakGlobal();
Ian Rogers68d8b422014-07-17 11:09:10 -0700754 }
755 *entry = new_obj;
756 }
757}
758
759void JavaVMExt::VisitRoots(RootCallback* callback, void* arg) {
760 Thread* self = Thread::Current();
761 {
762 ReaderMutexLock mu(self, globals_lock_);
763 globals_.VisitRoots(callback, arg, 0, kRootJNIGlobal);
764 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700765 // The weak_globals table is visited by the GC itself (because it mutates the table).
766}
767
768// JNI Invocation interface.
769
770extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
771 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
772 if (IsBadJniVersion(args->version)) {
773 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
774 return JNI_EVERSION;
775 }
776 RuntimeOptions options;
777 for (int i = 0; i < args->nOptions; ++i) {
778 JavaVMOption* option = &args->options[i];
779 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
780 }
781 bool ignore_unrecognized = args->ignoreUnrecognized;
782 if (!Runtime::Create(options, ignore_unrecognized)) {
783 return JNI_ERR;
784 }
785 Runtime* runtime = Runtime::Current();
786 bool started = runtime->Start();
787 if (!started) {
788 delete Thread::Current()->GetJniEnv();
789 delete runtime->GetJavaVM();
790 LOG(WARNING) << "CreateJavaVM failed";
791 return JNI_ERR;
792 }
793 *p_env = Thread::Current()->GetJniEnv();
794 *p_vm = runtime->GetJavaVM();
795 return JNI_OK;
796}
797
798extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms, jsize, jsize* vm_count) {
799 Runtime* runtime = Runtime::Current();
800 if (runtime == nullptr) {
801 *vm_count = 0;
802 } else {
803 *vm_count = 1;
804 vms[0] = runtime->GetJavaVM();
805 }
806 return JNI_OK;
807}
808
809// Historically unsupported.
810extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
811 return JNI_ERR;
812}
813
814} // namespace art