blob: eb9c32d7ad4d3250b53b66b8246f04ea7d5e124c [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
Richard Uhler054a0782015-04-07 10:56:50 -070019#define ATRACE_TAG ATRACE_TAG_DALVIK
20#include <cutils/trace.h>
Ian Rogers68d8b422014-07-17 11:09:10 -070021#include <dlfcn.h>
22
Mathieu Chartiere401d142015-04-22 13:56:20 -070023#include "art_method.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070024#include "base/dumpable.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070025#include "base/mutex.h"
26#include "base/stl_util.h"
27#include "check_jni.h"
Elliott Hughes956af0f2014-12-11 14:34:28 -080028#include "dex_file-inl.h"
Mathieu Chartierd0004802014-10-15 16:59:47 -070029#include "fault_handler.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070030#include "indirect_reference_table-inl.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070031#include "mirror/class-inl.h"
32#include "mirror/class_loader.h"
Calin Juravlec8423522014-08-12 20:55:20 +010033#include "nativebridge/native_bridge.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070034#include "java_vm_ext.h"
35#include "parsed_options.h"
Ian Rogersc0542af2014-09-03 16:16:56 -070036#include "runtime-inl.h"
Igor Murashkinaaebaa02015-01-26 10:55:53 -080037#include "runtime_options.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070038#include "ScopedLocalRef.h"
39#include "scoped_thread_state_change.h"
40#include "thread-inl.h"
41#include "thread_list.h"
42
43namespace art {
44
Ian Rogers68d8b422014-07-17 11:09:10 -070045static size_t gGlobalsInitial = 512; // Arbitrary.
46static size_t gGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
47
48static const size_t kWeakGlobalsInitial = 16; // Arbitrary.
49static const size_t kWeakGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
50
51static bool IsBadJniVersion(int version) {
52 // We don't support JNI_VERSION_1_1. These are the only other valid versions.
53 return version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 && version != JNI_VERSION_1_6;
54}
55
56class SharedLibrary {
57 public:
58 SharedLibrary(JNIEnv* env, Thread* self, const std::string& path, void* handle,
59 jobject class_loader)
60 : path_(path),
61 handle_(handle),
62 needs_native_bridge_(false),
63 class_loader_(env->NewGlobalRef(class_loader)),
64 jni_on_load_lock_("JNI_OnLoad lock"),
65 jni_on_load_cond_("JNI_OnLoad condition variable", jni_on_load_lock_),
66 jni_on_load_thread_id_(self->GetThreadId()),
67 jni_on_load_result_(kPending) {
68 }
69
70 ~SharedLibrary() {
71 Thread* self = Thread::Current();
72 if (self != nullptr) {
73 self->GetJniEnv()->DeleteGlobalRef(class_loader_);
74 }
75 }
76
77 jobject GetClassLoader() const {
78 return class_loader_;
79 }
80
81 const std::string& GetPath() const {
82 return path_;
83 }
84
85 /*
86 * Check the result of an earlier call to JNI_OnLoad on this library.
87 * If the call has not yet finished in another thread, wait for it.
88 */
89 bool CheckOnLoadResult()
90 LOCKS_EXCLUDED(jni_on_load_lock_) {
91 Thread* self = Thread::Current();
92 bool okay;
93 {
94 MutexLock mu(self, jni_on_load_lock_);
95
96 if (jni_on_load_thread_id_ == self->GetThreadId()) {
97 // Check this so we don't end up waiting for ourselves. We need to return "true" so the
98 // caller can continue.
99 LOG(INFO) << *self << " recursive attempt to load library " << "\"" << path_ << "\"";
100 okay = true;
101 } else {
102 while (jni_on_load_result_ == kPending) {
103 VLOG(jni) << "[" << *self << " waiting for \"" << path_ << "\" " << "JNI_OnLoad...]";
104 jni_on_load_cond_.Wait(self);
105 }
106
107 okay = (jni_on_load_result_ == kOkay);
108 VLOG(jni) << "[Earlier JNI_OnLoad for \"" << path_ << "\" "
109 << (okay ? "succeeded" : "failed") << "]";
110 }
111 }
112 return okay;
113 }
114
115 void SetResult(bool result) LOCKS_EXCLUDED(jni_on_load_lock_) {
116 Thread* self = Thread::Current();
117 MutexLock mu(self, jni_on_load_lock_);
118
119 jni_on_load_result_ = result ? kOkay : kFailed;
120 jni_on_load_thread_id_ = 0;
121
122 // Broadcast a wakeup to anybody sleeping on the condition variable.
123 jni_on_load_cond_.Broadcast(self);
124 }
125
126 void SetNeedsNativeBridge() {
127 needs_native_bridge_ = true;
128 }
129
130 bool NeedsNativeBridge() const {
131 return needs_native_bridge_;
132 }
133
134 void* FindSymbol(const std::string& symbol_name) {
135 return dlsym(handle_, symbol_name.c_str());
136 }
137
138 void* FindSymbolWithNativeBridge(const std::string& symbol_name, const char* shorty) {
139 CHECK(NeedsNativeBridge());
140
141 uint32_t len = 0;
Calin Juravlec8423522014-08-12 20:55:20 +0100142 return android::NativeBridgeGetTrampoline(handle_, symbol_name.c_str(), shorty, len);
Ian Rogers68d8b422014-07-17 11:09:10 -0700143 }
144
145 private:
146 enum JNI_OnLoadState {
147 kPending,
148 kFailed,
149 kOkay,
150 };
151
152 // Path to library "/system/lib/libjni.so".
153 const std::string path_;
154
155 // The void* returned by dlopen(3).
156 void* const handle_;
157
158 // True if a native bridge is required.
159 bool needs_native_bridge_;
160
161 // The ClassLoader this library is associated with, a global JNI reference that is
162 // created/deleted with the scope of the library.
163 const jobject class_loader_;
164
165 // Guards remaining items.
166 Mutex jni_on_load_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
167 // Wait for JNI_OnLoad in other thread.
168 ConditionVariable jni_on_load_cond_ GUARDED_BY(jni_on_load_lock_);
169 // Recursive invocation guard.
170 uint32_t jni_on_load_thread_id_ GUARDED_BY(jni_on_load_lock_);
171 // Result of earlier JNI_OnLoad call.
172 JNI_OnLoadState jni_on_load_result_ GUARDED_BY(jni_on_load_lock_);
173};
174
175// This exists mainly to keep implementation details out of the header file.
176class Libraries {
177 public:
178 Libraries() {
179 }
180
181 ~Libraries() {
182 STLDeleteValues(&libraries_);
183 }
184
185 void Dump(std::ostream& os) const {
186 bool first = true;
187 for (const auto& library : libraries_) {
188 if (!first) {
189 os << ' ';
190 }
191 first = false;
192 os << library.first;
193 }
194 }
195
196 size_t size() const {
197 return libraries_.size();
198 }
199
200 SharedLibrary* Get(const std::string& path) {
201 auto it = libraries_.find(path);
202 return (it == libraries_.end()) ? nullptr : it->second;
203 }
204
205 void Put(const std::string& path, SharedLibrary* library) {
206 libraries_.Put(path, library);
207 }
208
209 // See section 11.3 "Linking Native Methods" of the JNI spec.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700210 void* FindNativeMethod(ArtMethod* m, std::string& detail)
Ian Rogers68d8b422014-07-17 11:09:10 -0700211 EXCLUSIVE_LOCKS_REQUIRED(Locks::jni_libraries_lock_)
212 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
213 std::string jni_short_name(JniShortName(m));
214 std::string jni_long_name(JniLongName(m));
215 const mirror::ClassLoader* declaring_class_loader = m->GetDeclaringClass()->GetClassLoader();
216 ScopedObjectAccessUnchecked soa(Thread::Current());
217 for (const auto& lib : libraries_) {
218 SharedLibrary* library = lib.second;
219 if (soa.Decode<mirror::ClassLoader*>(library->GetClassLoader()) != declaring_class_loader) {
220 // We only search libraries loaded by the appropriate ClassLoader.
221 continue;
222 }
223 // Try the short name then the long name...
224 void* fn;
225 if (library->NeedsNativeBridge()) {
226 const char* shorty = m->GetShorty();
227 fn = library->FindSymbolWithNativeBridge(jni_short_name, shorty);
228 if (fn == nullptr) {
229 fn = library->FindSymbolWithNativeBridge(jni_long_name, shorty);
230 }
231 } else {
232 fn = library->FindSymbol(jni_short_name);
233 if (fn == nullptr) {
234 fn = library->FindSymbol(jni_long_name);
235 }
236 }
237 if (fn == nullptr) {
238 fn = library->FindSymbol(jni_long_name);
239 }
240 if (fn != nullptr) {
241 VLOG(jni) << "[Found native code for " << PrettyMethod(m)
242 << " in \"" << library->GetPath() << "\"]";
243 return fn;
244 }
245 }
246 detail += "No implementation found for ";
247 detail += PrettyMethod(m);
248 detail += " (tried " + jni_short_name + " and " + jni_long_name + ")";
249 LOG(ERROR) << detail;
250 return nullptr;
251 }
252
253 private:
Andreas Gampe0a7993e2014-12-05 11:16:26 -0800254 AllocationTrackingSafeMap<std::string, SharedLibrary*, kAllocatorTagJNILibraries> libraries_;
Ian Rogers68d8b422014-07-17 11:09:10 -0700255};
256
257
258class JII {
259 public:
260 static jint DestroyJavaVM(JavaVM* vm) {
261 if (vm == nullptr) {
262 return JNI_ERR;
263 }
264 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
265 delete raw_vm->GetRuntime();
266 return JNI_OK;
267 }
268
269 static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
270 return AttachCurrentThreadInternal(vm, p_env, thr_args, false);
271 }
272
273 static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
274 return AttachCurrentThreadInternal(vm, p_env, thr_args, true);
275 }
276
277 static jint DetachCurrentThread(JavaVM* vm) {
278 if (vm == nullptr || Thread::Current() == nullptr) {
279 return JNI_ERR;
280 }
281 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
282 Runtime* runtime = raw_vm->GetRuntime();
283 runtime->DetachCurrentThread();
284 return JNI_OK;
285 }
286
287 static jint GetEnv(JavaVM* vm, void** env, jint version) {
288 // GetEnv always returns a JNIEnv* for the most current supported JNI version,
289 // and unlike other calls that take a JNI version doesn't care if you supply
290 // JNI_VERSION_1_1, which we don't otherwise support.
291 if (IsBadJniVersion(version) && version != JNI_VERSION_1_1) {
292 LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version;
293 return JNI_EVERSION;
294 }
295 if (vm == nullptr || env == nullptr) {
296 return JNI_ERR;
297 }
298 Thread* thread = Thread::Current();
299 if (thread == nullptr) {
300 *env = nullptr;
301 return JNI_EDETACHED;
302 }
303 *env = thread->GetJniEnv();
304 return JNI_OK;
305 }
306
307 private:
308 static jint AttachCurrentThreadInternal(JavaVM* vm, JNIEnv** p_env, void* raw_args, bool as_daemon) {
309 if (vm == nullptr || p_env == nullptr) {
310 return JNI_ERR;
311 }
312
313 // Return immediately if we're already attached.
314 Thread* self = Thread::Current();
315 if (self != nullptr) {
316 *p_env = self->GetJniEnv();
317 return JNI_OK;
318 }
319
320 Runtime* runtime = reinterpret_cast<JavaVMExt*>(vm)->GetRuntime();
321
322 // No threads allowed in zygote mode.
323 if (runtime->IsZygote()) {
324 LOG(ERROR) << "Attempt to attach a thread in the zygote";
325 return JNI_ERR;
326 }
327
328 JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(raw_args);
329 const char* thread_name = nullptr;
330 jobject thread_group = nullptr;
331 if (args != nullptr) {
332 if (IsBadJniVersion(args->version)) {
333 LOG(ERROR) << "Bad JNI version passed to "
334 << (as_daemon ? "AttachCurrentThreadAsDaemon" : "AttachCurrentThread") << ": "
335 << args->version;
336 return JNI_EVERSION;
337 }
338 thread_name = args->name;
339 thread_group = args->group;
340 }
341
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800342 if (!runtime->AttachCurrentThread(thread_name, as_daemon, thread_group,
343 !runtime->IsAotCompiler())) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700344 *p_env = nullptr;
345 return JNI_ERR;
346 } else {
347 *p_env = Thread::Current()->GetJniEnv();
348 return JNI_OK;
349 }
350 }
351};
352
353const JNIInvokeInterface gJniInvokeInterface = {
354 nullptr, // reserved0
355 nullptr, // reserved1
356 nullptr, // reserved2
357 JII::DestroyJavaVM,
358 JII::AttachCurrentThread,
359 JII::DetachCurrentThread,
360 JII::GetEnv,
361 JII::AttachCurrentThreadAsDaemon
362};
363
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800364JavaVMExt::JavaVMExt(Runtime* runtime, const RuntimeArgumentMap& runtime_options)
Ian Rogers68d8b422014-07-17 11:09:10 -0700365 : runtime_(runtime),
366 check_jni_abort_hook_(nullptr),
367 check_jni_abort_hook_data_(nullptr),
368 check_jni_(false), // Initialized properly in the constructor body below.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800369 force_copy_(runtime_options.Exists(RuntimeArgumentMap::JniOptsForceCopy)),
370 tracing_enabled_(runtime_options.Exists(RuntimeArgumentMap::JniTrace)
371 || VLOG_IS_ON(third_party_jni)),
372 trace_(runtime_options.GetOrDefault(RuntimeArgumentMap::JniTrace)),
Ian Rogers68d8b422014-07-17 11:09:10 -0700373 globals_lock_("JNI global reference table lock"),
374 globals_(gGlobalsInitial, gGlobalsMax, kGlobal),
375 libraries_(new Libraries),
376 unchecked_functions_(&gJniInvokeInterface),
377 weak_globals_lock_("JNI weak global reference table lock"),
378 weak_globals_(kWeakGlobalsInitial, kWeakGlobalsMax, kWeakGlobal),
379 allow_new_weak_globals_(true),
380 weak_globals_add_condition_("weak globals add condition", weak_globals_lock_) {
381 functions = unchecked_functions_;
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800382 SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni));
Ian Rogers68d8b422014-07-17 11:09:10 -0700383}
384
385JavaVMExt::~JavaVMExt() {
386}
387
388void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) {
389 Thread* self = Thread::Current();
390 ScopedObjectAccess soa(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700391 ArtMethod* current_method = self->GetCurrentMethod(nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700392
393 std::ostringstream os;
394 os << "JNI DETECTED ERROR IN APPLICATION: " << msg;
395
396 if (jni_function_name != nullptr) {
397 os << "\n in call to " << jni_function_name;
398 }
399 // TODO: is this useful given that we're about to dump the calling thread's stack?
400 if (current_method != nullptr) {
401 os << "\n from " << PrettyMethod(current_method);
402 }
403 os << "\n";
404 self->Dump(os);
405
406 if (check_jni_abort_hook_ != nullptr) {
407 check_jni_abort_hook_(check_jni_abort_hook_data_, os.str());
408 } else {
409 // Ensure that we get a native stack trace for this thread.
410 self->TransitionFromRunnableToSuspended(kNative);
411 LOG(FATAL) << os.str();
412 self->TransitionFromSuspendedToRunnable(); // Unreachable, keep annotalysis happy.
413 }
414}
415
416void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) {
417 std::string msg;
418 StringAppendV(&msg, fmt, ap);
419 JniAbort(jni_function_name, msg.c_str());
420}
421
422void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) {
423 va_list args;
424 va_start(args, fmt);
425 JniAbortV(jni_function_name, fmt, args);
426 va_end(args);
427}
428
Mathieu Chartiere401d142015-04-22 13:56:20 -0700429bool JavaVMExt::ShouldTrace(ArtMethod* method) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700430 // Fast where no tracing is enabled.
431 if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) {
432 return false;
433 }
434 // Perform checks based on class name.
435 StringPiece class_name(method->GetDeclaringClassDescriptor());
436 if (!trace_.empty() && class_name.find(trace_) != std::string::npos) {
437 return true;
438 }
439 if (!VLOG_IS_ON(third_party_jni)) {
440 return false;
441 }
442 // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
443 // like part of Android.
444 static const char* gBuiltInPrefixes[] = {
445 "Landroid/",
446 "Lcom/android/",
447 "Lcom/google/android/",
448 "Ldalvik/",
449 "Ljava/",
450 "Ljavax/",
451 "Llibcore/",
452 "Lorg/apache/harmony/",
453 };
454 for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) {
455 if (class_name.starts_with(gBuiltInPrefixes[i])) {
456 return false;
457 }
458 }
459 return true;
460}
461
462jobject JavaVMExt::AddGlobalRef(Thread* self, mirror::Object* obj) {
463 // Check for null after decoding the object to handle cleared weak globals.
464 if (obj == nullptr) {
465 return nullptr;
466 }
467 WriterMutexLock mu(self, globals_lock_);
468 IndirectRef ref = globals_.Add(IRT_FIRST_SEGMENT, obj);
469 return reinterpret_cast<jobject>(ref);
470}
471
472jweak JavaVMExt::AddWeakGlobalRef(Thread* self, mirror::Object* obj) {
473 if (obj == nullptr) {
474 return nullptr;
475 }
476 MutexLock mu(self, weak_globals_lock_);
477 while (UNLIKELY(!allow_new_weak_globals_)) {
478 weak_globals_add_condition_.WaitHoldingLocks(self);
479 }
480 IndirectRef ref = weak_globals_.Add(IRT_FIRST_SEGMENT, obj);
481 return reinterpret_cast<jweak>(ref);
482}
483
484void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
485 if (obj == nullptr) {
486 return;
487 }
488 WriterMutexLock mu(self, globals_lock_);
489 if (!globals_.Remove(IRT_FIRST_SEGMENT, obj)) {
490 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
491 << "failed to find entry";
492 }
493}
494
495void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
496 if (obj == nullptr) {
497 return;
498 }
499 MutexLock mu(self, weak_globals_lock_);
500 if (!weak_globals_.Remove(IRT_FIRST_SEGMENT, obj)) {
501 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
502 << "failed to find entry";
503 }
504}
505
506static void ThreadEnableCheckJni(Thread* thread, void* arg) {
507 bool* check_jni = reinterpret_cast<bool*>(arg);
508 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
509}
510
511bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
512 bool old_check_jni = check_jni_;
513 check_jni_ = enabled;
514 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
515 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
516 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
517 return old_check_jni;
518}
519
520void JavaVMExt::DumpForSigQuit(std::ostream& os) {
521 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
522 if (force_copy_) {
523 os << " (with forcecopy)";
524 }
525 Thread* self = Thread::Current();
526 {
Ian Rogers68d8b422014-07-17 11:09:10 -0700527 ReaderMutexLock mu(self, globals_lock_);
528 os << "; globals=" << globals_.Capacity();
529 }
530 {
531 MutexLock mu(self, weak_globals_lock_);
532 if (weak_globals_.Capacity() > 0) {
533 os << " (plus " << weak_globals_.Capacity() << " weak)";
534 }
535 }
536 os << '\n';
537
538 {
539 MutexLock mu(self, *Locks::jni_libraries_lock_);
540 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
541 }
542}
543
544void JavaVMExt::DisallowNewWeakGlobals() {
545 MutexLock mu(Thread::Current(), weak_globals_lock_);
546 allow_new_weak_globals_ = false;
547}
548
549void JavaVMExt::AllowNewWeakGlobals() {
550 Thread* self = Thread::Current();
551 MutexLock mu(self, weak_globals_lock_);
552 allow_new_weak_globals_ = true;
553 weak_globals_add_condition_.Broadcast(self);
554}
555
Hiroshi Yamauchi2cd334a2015-01-09 14:03:35 -0800556void JavaVMExt::EnsureNewWeakGlobalsDisallowed() {
557 // Lock and unlock once to ensure that no threads are still in the
558 // middle of adding new weak globals.
559 MutexLock mu(Thread::Current(), weak_globals_lock_);
560 CHECK(!allow_new_weak_globals_);
561}
562
Ian Rogers68d8b422014-07-17 11:09:10 -0700563mirror::Object* JavaVMExt::DecodeGlobal(Thread* self, IndirectRef ref) {
564 return globals_.SynchronizedGet(self, &globals_lock_, ref);
565}
566
Jeff Hao83c81952015-05-27 19:29:29 -0700567void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, mirror::Object* result) {
568 WriterMutexLock mu(self, globals_lock_);
569 globals_.Update(ref, result);
570}
571
Ian Rogers68d8b422014-07-17 11:09:10 -0700572mirror::Object* JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
573 MutexLock mu(self, weak_globals_lock_);
574 while (UNLIKELY(!allow_new_weak_globals_)) {
575 weak_globals_add_condition_.WaitHoldingLocks(self);
576 }
577 return weak_globals_.Get(ref);
578}
579
Jeff Hao83c81952015-05-27 19:29:29 -0700580void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, mirror::Object* result) {
581 MutexLock mu(self, weak_globals_lock_);
582 weak_globals_.Update(ref, result);
583}
584
Ian Rogers68d8b422014-07-17 11:09:10 -0700585void JavaVMExt::DumpReferenceTables(std::ostream& os) {
586 Thread* self = Thread::Current();
587 {
588 ReaderMutexLock mu(self, globals_lock_);
589 globals_.Dump(os);
590 }
591 {
592 MutexLock mu(self, weak_globals_lock_);
593 weak_globals_.Dump(os);
594 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700595}
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();
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700646 void* handle = dlopen(path_str, RTLD_NOW);
Ian Rogers68d8b422014-07-17 11:09:10 -0700647 bool needs_native_bridge = false;
648 if (handle == nullptr) {
Calin Juravlec8423522014-08-12 20:55:20 +0100649 if (android::NativeBridgeIsSupported(path_str)) {
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700650 handle = android::NativeBridgeLoadLibrary(path_str, RTLD_NOW);
Ian Rogers68d8b422014-07-17 11:09:10 -0700651 needs_native_bridge = true;
652 }
653 }
654
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700655 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]";
Ian Rogers68d8b422014-07-17 11:09:10 -0700656
657 if (handle == nullptr) {
658 *error_msg = dlerror();
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700659 VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700660 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
Mathieu Chartierd0004802014-10-15 16:59:47 -0700714 if (runtime_->GetTargetSdkVersion() != 0 && runtime_->GetTargetSdkVersion() <= 21) {
715 fault_manager.EnsureArtActionInFrontOfSignalChain();
716 }
717
Ian Rogers68d8b422014-07-17 11:09:10 -0700718 self->SetClassLoaderOverride(old_class_loader.get());
719
720 if (version == JNI_ERR) {
721 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
722 } else if (IsBadJniVersion(version)) {
723 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
724 path.c_str(), version);
725 // It's unwise to call dlclose() here, but we can mark it
726 // as bad and ensure that future load attempts will fail.
727 // We don't know how far JNI_OnLoad got, so there could
728 // be some partially-initialized stuff accessible through
729 // newly-registered native method calls. We could try to
730 // unregister them, but that doesn't seem worthwhile.
731 } else {
732 was_successful = true;
733 }
734 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
735 << " from JNI_OnLoad in \"" << path << "\"]";
736 }
737
738 library->SetResult(was_successful);
739 return was_successful;
740}
741
Mathieu Chartiere401d142015-04-22 13:56:20 -0700742void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700743 CHECK(m->IsNative());
744 mirror::Class* c = m->GetDeclaringClass();
745 // If this is a static method, it could be called before the class has been initialized.
746 CHECK(c->IsInitializing()) << c->GetStatus() << " " << PrettyMethod(m);
747 std::string detail;
748 void* native_method;
749 Thread* self = Thread::Current();
750 {
751 MutexLock mu(self, *Locks::jni_libraries_lock_);
752 native_method = libraries_->FindNativeMethod(m, detail);
753 }
754 // Throwing can cause libraries_lock to be reacquired.
755 if (native_method == nullptr) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000756 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
Ian Rogers68d8b422014-07-17 11:09:10 -0700757 }
758 return native_method;
759}
760
761void JavaVMExt::SweepJniWeakGlobals(IsMarkedCallback* callback, void* arg) {
762 MutexLock mu(Thread::Current(), weak_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700763 Runtime* const runtime = Runtime::Current();
764 for (auto* entry : weak_globals_) {
765 // Need to skip null here to distinguish between null entries and cleared weak ref entries.
766 if (!entry->IsNull()) {
767 // Since this is called by the GC, we don't need a read barrier.
768 mirror::Object* obj = entry->Read<kWithoutReadBarrier>();
769 mirror::Object* new_obj = callback(obj, arg);
770 if (new_obj == nullptr) {
771 new_obj = runtime->GetClearedJniWeakGlobal();
772 }
773 *entry = GcRoot<mirror::Object>(new_obj);
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -0700774 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700775 }
776}
777
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800778void JavaVMExt::TrimGlobals() {
779 WriterMutexLock mu(Thread::Current(), globals_lock_);
780 globals_.Trim();
781}
782
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700783void JavaVMExt::VisitRoots(RootVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700784 Thread* self = Thread::Current();
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800785 ReaderMutexLock mu(self, globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700786 globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal));
Ian Rogers68d8b422014-07-17 11:09:10 -0700787 // The weak_globals table is visited by the GC itself (because it mutates the table).
788}
789
790// JNI Invocation interface.
791
792extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
Richard Uhler054a0782015-04-07 10:56:50 -0700793 ATRACE_BEGIN(__FUNCTION__);
Ian Rogers68d8b422014-07-17 11:09:10 -0700794 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
795 if (IsBadJniVersion(args->version)) {
796 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
Richard Uhler054a0782015-04-07 10:56:50 -0700797 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700798 return JNI_EVERSION;
799 }
800 RuntimeOptions options;
801 for (int i = 0; i < args->nOptions; ++i) {
802 JavaVMOption* option = &args->options[i];
803 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
804 }
805 bool ignore_unrecognized = args->ignoreUnrecognized;
806 if (!Runtime::Create(options, ignore_unrecognized)) {
Richard Uhler054a0782015-04-07 10:56:50 -0700807 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700808 return JNI_ERR;
809 }
810 Runtime* runtime = Runtime::Current();
811 bool started = runtime->Start();
812 if (!started) {
813 delete Thread::Current()->GetJniEnv();
814 delete runtime->GetJavaVM();
815 LOG(WARNING) << "CreateJavaVM failed";
Richard Uhler054a0782015-04-07 10:56:50 -0700816 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700817 return JNI_ERR;
818 }
819 *p_env = Thread::Current()->GetJniEnv();
820 *p_vm = runtime->GetJavaVM();
Richard Uhler054a0782015-04-07 10:56:50 -0700821 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700822 return JNI_OK;
823}
824
Ian Rogersf4d4da12014-11-11 16:10:33 -0800825extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700826 Runtime* runtime = Runtime::Current();
Ian Rogersf4d4da12014-11-11 16:10:33 -0800827 if (runtime == nullptr || buf_len == 0) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700828 *vm_count = 0;
829 } else {
830 *vm_count = 1;
Ian Rogersf4d4da12014-11-11 16:10:33 -0800831 vms_buf[0] = runtime->GetJavaVM();
Ian Rogers68d8b422014-07-17 11:09:10 -0700832 }
833 return JNI_OK;
834}
835
836// Historically unsupported.
837extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
838 return JNI_ERR;
839}
840
841} // namespace art