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