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