blob: 36e3aa3b58bef55a78f002c23c83b1c5d9c3c14a [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) {
Andreas Gampe8fec90b2015-06-30 11:23:44 -0700135 CHECK(!NeedsNativeBridge());
136
Ian Rogers68d8b422014-07-17 11:09:10 -0700137 return dlsym(handle_, symbol_name.c_str());
138 }
139
140 void* FindSymbolWithNativeBridge(const std::string& symbol_name, const char* shorty) {
141 CHECK(NeedsNativeBridge());
142
143 uint32_t len = 0;
Calin Juravlec8423522014-08-12 20:55:20 +0100144 return android::NativeBridgeGetTrampoline(handle_, symbol_name.c_str(), shorty, len);
Ian Rogers68d8b422014-07-17 11:09:10 -0700145 }
146
147 private:
148 enum JNI_OnLoadState {
149 kPending,
150 kFailed,
151 kOkay,
152 };
153
154 // Path to library "/system/lib/libjni.so".
155 const std::string path_;
156
157 // The void* returned by dlopen(3).
158 void* const handle_;
159
160 // True if a native bridge is required.
161 bool needs_native_bridge_;
162
163 // The ClassLoader this library is associated with, a global JNI reference that is
164 // created/deleted with the scope of the library.
165 const jobject class_loader_;
166
167 // Guards remaining items.
168 Mutex jni_on_load_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
169 // Wait for JNI_OnLoad in other thread.
170 ConditionVariable jni_on_load_cond_ GUARDED_BY(jni_on_load_lock_);
171 // Recursive invocation guard.
172 uint32_t jni_on_load_thread_id_ GUARDED_BY(jni_on_load_lock_);
173 // Result of earlier JNI_OnLoad call.
174 JNI_OnLoadState jni_on_load_result_ GUARDED_BY(jni_on_load_lock_);
175};
176
177// This exists mainly to keep implementation details out of the header file.
178class Libraries {
179 public:
180 Libraries() {
181 }
182
183 ~Libraries() {
184 STLDeleteValues(&libraries_);
185 }
186
187 void Dump(std::ostream& os) const {
188 bool first = true;
189 for (const auto& library : libraries_) {
190 if (!first) {
191 os << ' ';
192 }
193 first = false;
194 os << library.first;
195 }
196 }
197
198 size_t size() const {
199 return libraries_.size();
200 }
201
202 SharedLibrary* Get(const std::string& path) {
203 auto it = libraries_.find(path);
204 return (it == libraries_.end()) ? nullptr : it->second;
205 }
206
207 void Put(const std::string& path, SharedLibrary* library) {
208 libraries_.Put(path, library);
209 }
210
211 // See section 11.3 "Linking Native Methods" of the JNI spec.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700212 void* FindNativeMethod(ArtMethod* m, std::string& detail)
Ian Rogers68d8b422014-07-17 11:09:10 -0700213 EXCLUSIVE_LOCKS_REQUIRED(Locks::jni_libraries_lock_)
214 SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) {
215 std::string jni_short_name(JniShortName(m));
216 std::string jni_long_name(JniLongName(m));
217 const mirror::ClassLoader* declaring_class_loader = m->GetDeclaringClass()->GetClassLoader();
218 ScopedObjectAccessUnchecked soa(Thread::Current());
219 for (const auto& lib : libraries_) {
220 SharedLibrary* library = lib.second;
221 if (soa.Decode<mirror::ClassLoader*>(library->GetClassLoader()) != declaring_class_loader) {
222 // We only search libraries loaded by the appropriate ClassLoader.
223 continue;
224 }
225 // Try the short name then the long name...
226 void* fn;
227 if (library->NeedsNativeBridge()) {
228 const char* shorty = m->GetShorty();
229 fn = library->FindSymbolWithNativeBridge(jni_short_name, shorty);
230 if (fn == nullptr) {
231 fn = library->FindSymbolWithNativeBridge(jni_long_name, shorty);
232 }
233 } else {
234 fn = library->FindSymbol(jni_short_name);
235 if (fn == nullptr) {
236 fn = library->FindSymbol(jni_long_name);
237 }
238 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700239 if (fn != nullptr) {
240 VLOG(jni) << "[Found native code for " << PrettyMethod(m)
241 << " in \"" << library->GetPath() << "\"]";
242 return fn;
243 }
244 }
245 detail += "No implementation found for ";
246 detail += PrettyMethod(m);
247 detail += " (tried " + jni_short_name + " and " + jni_long_name + ")";
248 LOG(ERROR) << detail;
249 return nullptr;
250 }
251
252 private:
Andreas Gampe0a7993e2014-12-05 11:16:26 -0800253 AllocationTrackingSafeMap<std::string, SharedLibrary*, kAllocatorTagJNILibraries> libraries_;
Ian Rogers68d8b422014-07-17 11:09:10 -0700254};
255
256
257class JII {
258 public:
259 static jint DestroyJavaVM(JavaVM* vm) {
260 if (vm == nullptr) {
261 return JNI_ERR;
262 }
263 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
264 delete raw_vm->GetRuntime();
265 return JNI_OK;
266 }
267
268 static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
269 return AttachCurrentThreadInternal(vm, p_env, thr_args, false);
270 }
271
272 static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
273 return AttachCurrentThreadInternal(vm, p_env, thr_args, true);
274 }
275
276 static jint DetachCurrentThread(JavaVM* vm) {
277 if (vm == nullptr || Thread::Current() == nullptr) {
278 return JNI_ERR;
279 }
280 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
281 Runtime* runtime = raw_vm->GetRuntime();
282 runtime->DetachCurrentThread();
283 return JNI_OK;
284 }
285
286 static jint GetEnv(JavaVM* vm, void** env, jint version) {
287 // GetEnv always returns a JNIEnv* for the most current supported JNI version,
288 // and unlike other calls that take a JNI version doesn't care if you supply
289 // JNI_VERSION_1_1, which we don't otherwise support.
290 if (IsBadJniVersion(version) && version != JNI_VERSION_1_1) {
291 LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version;
292 return JNI_EVERSION;
293 }
294 if (vm == nullptr || env == nullptr) {
295 return JNI_ERR;
296 }
297 Thread* thread = Thread::Current();
298 if (thread == nullptr) {
299 *env = nullptr;
300 return JNI_EDETACHED;
301 }
302 *env = thread->GetJniEnv();
303 return JNI_OK;
304 }
305
306 private:
307 static jint AttachCurrentThreadInternal(JavaVM* vm, JNIEnv** p_env, void* raw_args, bool as_daemon) {
308 if (vm == nullptr || p_env == nullptr) {
309 return JNI_ERR;
310 }
311
312 // Return immediately if we're already attached.
313 Thread* self = Thread::Current();
314 if (self != nullptr) {
315 *p_env = self->GetJniEnv();
316 return JNI_OK;
317 }
318
319 Runtime* runtime = reinterpret_cast<JavaVMExt*>(vm)->GetRuntime();
320
321 // No threads allowed in zygote mode.
322 if (runtime->IsZygote()) {
323 LOG(ERROR) << "Attempt to attach a thread in the zygote";
324 return JNI_ERR;
325 }
326
327 JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(raw_args);
328 const char* thread_name = nullptr;
329 jobject thread_group = nullptr;
330 if (args != nullptr) {
331 if (IsBadJniVersion(args->version)) {
332 LOG(ERROR) << "Bad JNI version passed to "
333 << (as_daemon ? "AttachCurrentThreadAsDaemon" : "AttachCurrentThread") << ": "
334 << args->version;
335 return JNI_EVERSION;
336 }
337 thread_name = args->name;
338 thread_group = args->group;
339 }
340
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800341 if (!runtime->AttachCurrentThread(thread_name, as_daemon, thread_group,
342 !runtime->IsAotCompiler())) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700343 *p_env = nullptr;
344 return JNI_ERR;
345 } else {
346 *p_env = Thread::Current()->GetJniEnv();
347 return JNI_OK;
348 }
349 }
350};
351
352const JNIInvokeInterface gJniInvokeInterface = {
353 nullptr, // reserved0
354 nullptr, // reserved1
355 nullptr, // reserved2
356 JII::DestroyJavaVM,
357 JII::AttachCurrentThread,
358 JII::DetachCurrentThread,
359 JII::GetEnv,
360 JII::AttachCurrentThreadAsDaemon
361};
362
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800363JavaVMExt::JavaVMExt(Runtime* runtime, const RuntimeArgumentMap& runtime_options)
Ian Rogers68d8b422014-07-17 11:09:10 -0700364 : runtime_(runtime),
365 check_jni_abort_hook_(nullptr),
366 check_jni_abort_hook_data_(nullptr),
367 check_jni_(false), // Initialized properly in the constructor body below.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800368 force_copy_(runtime_options.Exists(RuntimeArgumentMap::JniOptsForceCopy)),
369 tracing_enabled_(runtime_options.Exists(RuntimeArgumentMap::JniTrace)
370 || VLOG_IS_ON(third_party_jni)),
371 trace_(runtime_options.GetOrDefault(RuntimeArgumentMap::JniTrace)),
Ian Rogers68d8b422014-07-17 11:09:10 -0700372 globals_lock_("JNI global reference table lock"),
373 globals_(gGlobalsInitial, gGlobalsMax, kGlobal),
374 libraries_(new Libraries),
375 unchecked_functions_(&gJniInvokeInterface),
376 weak_globals_lock_("JNI weak global reference table lock"),
377 weak_globals_(kWeakGlobalsInitial, kWeakGlobalsMax, kWeakGlobal),
378 allow_new_weak_globals_(true),
379 weak_globals_add_condition_("weak globals add condition", weak_globals_lock_) {
380 functions = unchecked_functions_;
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800381 SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni));
Ian Rogers68d8b422014-07-17 11:09:10 -0700382}
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);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700390 ArtMethod* current_method = self->GetCurrentMethod(nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700391
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
Mathieu Chartiere401d142015-04-22 13:56:20 -0700428bool JavaVMExt::ShouldTrace(ArtMethod* method) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700429 // 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_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700476 while (UNLIKELY((!kUseReadBarrier && !allow_new_weak_globals_) ||
477 (kUseReadBarrier && !self->GetWeakRefAccessEnabled()))) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700478 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
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700563void JavaVMExt::BroadcastForNewWeakGlobals() {
564 CHECK(kUseReadBarrier);
565 Thread* self = Thread::Current();
566 MutexLock mu(self, weak_globals_lock_);
567 weak_globals_add_condition_.Broadcast(self);
568}
569
Ian Rogers68d8b422014-07-17 11:09:10 -0700570mirror::Object* JavaVMExt::DecodeGlobal(Thread* self, IndirectRef ref) {
571 return globals_.SynchronizedGet(self, &globals_lock_, ref);
572}
573
Jeff Hao83c81952015-05-27 19:29:29 -0700574void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, mirror::Object* result) {
575 WriterMutexLock mu(self, globals_lock_);
576 globals_.Update(ref, result);
577}
578
Ian Rogers68d8b422014-07-17 11:09:10 -0700579mirror::Object* JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
580 MutexLock mu(self, weak_globals_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700581 while (UNLIKELY((!kUseReadBarrier && !allow_new_weak_globals_) ||
582 (kUseReadBarrier && !self->GetWeakRefAccessEnabled()))) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700583 weak_globals_add_condition_.WaitHoldingLocks(self);
584 }
585 return weak_globals_.Get(ref);
586}
587
Jeff Hao83c81952015-05-27 19:29:29 -0700588void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, mirror::Object* result) {
589 MutexLock mu(self, weak_globals_lock_);
590 weak_globals_.Update(ref, result);
591}
592
Ian Rogers68d8b422014-07-17 11:09:10 -0700593void JavaVMExt::DumpReferenceTables(std::ostream& os) {
594 Thread* self = Thread::Current();
595 {
596 ReaderMutexLock mu(self, globals_lock_);
597 globals_.Dump(os);
598 }
599 {
600 MutexLock mu(self, weak_globals_lock_);
601 weak_globals_.Dump(os);
602 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700603}
604
605bool JavaVMExt::LoadNativeLibrary(JNIEnv* env, const std::string& path, jobject class_loader,
606 std::string* error_msg) {
607 error_msg->clear();
608
609 // See if we've already loaded this library. If we have, and the class loader
610 // matches, return successfully without doing anything.
611 // TODO: for better results we should canonicalize the pathname (or even compare
612 // inodes). This implementation is fine if everybody is using System.loadLibrary.
613 SharedLibrary* library;
614 Thread* self = Thread::Current();
615 {
616 // TODO: move the locking (and more of this logic) into Libraries.
617 MutexLock mu(self, *Locks::jni_libraries_lock_);
618 library = libraries_->Get(path);
619 }
620 if (library != nullptr) {
621 if (env->IsSameObject(library->GetClassLoader(), class_loader) == JNI_FALSE) {
622 // The library will be associated with class_loader. The JNI
623 // spec says we can't load the same library into more than one
624 // class loader.
625 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
626 "ClassLoader %p; can't open in ClassLoader %p",
627 path.c_str(), library->GetClassLoader(), class_loader);
628 LOG(WARNING) << error_msg;
629 return false;
630 }
631 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
632 << " ClassLoader " << class_loader << "]";
633 if (!library->CheckOnLoadResult()) {
634 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
635 "to load \"%s\"", path.c_str());
636 return false;
637 }
638 return true;
639 }
640
641 // Open the shared library. Because we're using a full path, the system
642 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
643 // resolve this library's dependencies though.)
644
645 // Failures here are expected when java.library.path has several entries
646 // and we have to hunt for the lib.
647
648 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
649 // class unloading. Libraries will only be unloaded when the reference count (incremented by
650 // dlopen) becomes zero from dlclose.
651
652 Locks::mutator_lock_->AssertNotHeld(self);
653 const char* path_str = path.empty() ? nullptr : path.c_str();
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700654 void* handle = dlopen(path_str, RTLD_NOW);
Ian Rogers68d8b422014-07-17 11:09:10 -0700655 bool needs_native_bridge = false;
656 if (handle == nullptr) {
Calin Juravlec8423522014-08-12 20:55:20 +0100657 if (android::NativeBridgeIsSupported(path_str)) {
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700658 handle = android::NativeBridgeLoadLibrary(path_str, RTLD_NOW);
Ian Rogers68d8b422014-07-17 11:09:10 -0700659 needs_native_bridge = true;
660 }
661 }
662
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700663 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]";
Ian Rogers68d8b422014-07-17 11:09:10 -0700664
665 if (handle == nullptr) {
666 *error_msg = dlerror();
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700667 VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700668 return false;
669 }
670
671 if (env->ExceptionCheck() == JNI_TRUE) {
672 LOG(ERROR) << "Unexpected exception:";
673 env->ExceptionDescribe();
674 env->ExceptionClear();
675 }
676 // Create a new entry.
677 // TODO: move the locking (and more of this logic) into Libraries.
678 bool created_library = false;
679 {
680 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
681 std::unique_ptr<SharedLibrary> new_library(
682 new SharedLibrary(env, self, path, handle, class_loader));
683 MutexLock mu(self, *Locks::jni_libraries_lock_);
684 library = libraries_->Get(path);
685 if (library == nullptr) { // We won race to get libraries_lock.
686 library = new_library.release();
687 libraries_->Put(path, library);
688 created_library = true;
689 }
690 }
691 if (!created_library) {
692 LOG(INFO) << "WOW: we lost a race to add shared library: "
693 << "\"" << path << "\" ClassLoader=" << class_loader;
694 return library->CheckOnLoadResult();
695 }
696 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
697
698 bool was_successful = false;
699 void* sym;
700 if (needs_native_bridge) {
701 library->SetNeedsNativeBridge();
702 sym = library->FindSymbolWithNativeBridge("JNI_OnLoad", nullptr);
703 } else {
704 sym = dlsym(handle, "JNI_OnLoad");
705 }
706 if (sym == nullptr) {
707 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
708 was_successful = true;
709 } else {
710 // Call JNI_OnLoad. We have to override the current class
711 // loader, which will always be "null" since the stuff at the
712 // top of the stack is around Runtime.loadLibrary(). (See
713 // the comments in the JNI FindClass function.)
714 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
715 self->SetClassLoaderOverride(class_loader);
716
717 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
718 typedef int (*JNI_OnLoadFn)(JavaVM*, void*);
719 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
720 int version = (*jni_on_load)(this, nullptr);
721
Mathieu Chartierd0004802014-10-15 16:59:47 -0700722 if (runtime_->GetTargetSdkVersion() != 0 && runtime_->GetTargetSdkVersion() <= 21) {
723 fault_manager.EnsureArtActionInFrontOfSignalChain();
724 }
725
Ian Rogers68d8b422014-07-17 11:09:10 -0700726 self->SetClassLoaderOverride(old_class_loader.get());
727
728 if (version == JNI_ERR) {
729 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
730 } else if (IsBadJniVersion(version)) {
731 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
732 path.c_str(), version);
733 // It's unwise to call dlclose() here, but we can mark it
734 // as bad and ensure that future load attempts will fail.
735 // We don't know how far JNI_OnLoad got, so there could
736 // be some partially-initialized stuff accessible through
737 // newly-registered native method calls. We could try to
738 // unregister them, but that doesn't seem worthwhile.
739 } else {
740 was_successful = true;
741 }
742 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
743 << " from JNI_OnLoad in \"" << path << "\"]";
744 }
745
746 library->SetResult(was_successful);
747 return was_successful;
748}
749
Mathieu Chartiere401d142015-04-22 13:56:20 -0700750void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700751 CHECK(m->IsNative());
752 mirror::Class* c = m->GetDeclaringClass();
753 // If this is a static method, it could be called before the class has been initialized.
754 CHECK(c->IsInitializing()) << c->GetStatus() << " " << PrettyMethod(m);
755 std::string detail;
756 void* native_method;
757 Thread* self = Thread::Current();
758 {
759 MutexLock mu(self, *Locks::jni_libraries_lock_);
760 native_method = libraries_->FindNativeMethod(m, detail);
761 }
762 // Throwing can cause libraries_lock to be reacquired.
763 if (native_method == nullptr) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000764 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
Ian Rogers68d8b422014-07-17 11:09:10 -0700765 }
766 return native_method;
767}
768
Mathieu Chartier97509952015-07-13 14:35:43 -0700769void JavaVMExt::SweepJniWeakGlobals(IsMarkedVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700770 MutexLock mu(Thread::Current(), weak_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700771 Runtime* const runtime = Runtime::Current();
772 for (auto* entry : weak_globals_) {
773 // Need to skip null here to distinguish between null entries and cleared weak ref entries.
774 if (!entry->IsNull()) {
775 // Since this is called by the GC, we don't need a read barrier.
776 mirror::Object* obj = entry->Read<kWithoutReadBarrier>();
Mathieu Chartier97509952015-07-13 14:35:43 -0700777 mirror::Object* new_obj = visitor->IsMarked(obj);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700778 if (new_obj == nullptr) {
779 new_obj = runtime->GetClearedJniWeakGlobal();
780 }
781 *entry = GcRoot<mirror::Object>(new_obj);
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -0700782 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700783 }
784}
785
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800786void JavaVMExt::TrimGlobals() {
787 WriterMutexLock mu(Thread::Current(), globals_lock_);
788 globals_.Trim();
789}
790
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700791void JavaVMExt::VisitRoots(RootVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700792 Thread* self = Thread::Current();
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800793 ReaderMutexLock mu(self, globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700794 globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal));
Ian Rogers68d8b422014-07-17 11:09:10 -0700795 // The weak_globals table is visited by the GC itself (because it mutates the table).
796}
797
798// JNI Invocation interface.
799
800extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
Richard Uhler054a0782015-04-07 10:56:50 -0700801 ATRACE_BEGIN(__FUNCTION__);
Ian Rogers68d8b422014-07-17 11:09:10 -0700802 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
803 if (IsBadJniVersion(args->version)) {
804 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
Richard Uhler054a0782015-04-07 10:56:50 -0700805 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700806 return JNI_EVERSION;
807 }
808 RuntimeOptions options;
809 for (int i = 0; i < args->nOptions; ++i) {
810 JavaVMOption* option = &args->options[i];
811 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
812 }
813 bool ignore_unrecognized = args->ignoreUnrecognized;
814 if (!Runtime::Create(options, ignore_unrecognized)) {
Richard Uhler054a0782015-04-07 10:56:50 -0700815 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700816 return JNI_ERR;
817 }
818 Runtime* runtime = Runtime::Current();
819 bool started = runtime->Start();
820 if (!started) {
821 delete Thread::Current()->GetJniEnv();
822 delete runtime->GetJavaVM();
823 LOG(WARNING) << "CreateJavaVM failed";
Richard Uhler054a0782015-04-07 10:56:50 -0700824 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700825 return JNI_ERR;
826 }
827 *p_env = Thread::Current()->GetJniEnv();
828 *p_vm = runtime->GetJavaVM();
Richard Uhler054a0782015-04-07 10:56:50 -0700829 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700830 return JNI_OK;
831}
832
Ian Rogersf4d4da12014-11-11 16:10:33 -0800833extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700834 Runtime* runtime = Runtime::Current();
Ian Rogersf4d4da12014-11-11 16:10:33 -0800835 if (runtime == nullptr || buf_len == 0) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700836 *vm_count = 0;
837 } else {
838 *vm_count = 1;
Ian Rogersf4d4da12014-11-11 16:10:33 -0800839 vms_buf[0] = runtime->GetJavaVM();
Ian Rogers68d8b422014-07-17 11:09:10 -0700840 }
841 return JNI_OK;
842}
843
844// Historically unsupported.
845extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
846 return JNI_ERR;
847}
848
849} // namespace art