blob: 1e8326b751ec0bbd950249f14742c441fb4c2ae5 [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()
Mathieu Chartier90443472015-07-16 20:32:27 -070090 REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -070091 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
Mathieu Chartier90443472015-07-16 20:32:27 -0700115 void SetResult(bool result) REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700116 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)
Mathieu Chartier90443472015-07-16 20:32:27 -0700213 REQUIRES(Locks::jni_libraries_lock_)
214 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700215 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),
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700376 weak_globals_lock_("JNI weak global reference table lock", kJniWeakGlobalsLock),
Ian Rogers68d8b422014-07-17 11:09:10 -0700377 weak_globals_(kWeakGlobalsInitial, kWeakGlobalsMax, kWeakGlobal),
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700378 allow_accessing_weak_globals_(true),
Ian Rogers68d8b422014-07-17 11:09:10 -0700379 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.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700409 ScopedThreadSuspension sts(self, kNative);
Ian Rogers68d8b422014-07-17 11:09:10 -0700410 LOG(FATAL) << os.str();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700411 UNREACHABLE();
Ian Rogers68d8b422014-07-17 11:09:10 -0700412 }
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_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700476 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700477 weak_globals_add_condition_.WaitHoldingLocks(self);
478 }
479 IndirectRef ref = weak_globals_.Add(IRT_FIRST_SEGMENT, obj);
480 return reinterpret_cast<jweak>(ref);
481}
482
483void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
484 if (obj == nullptr) {
485 return;
486 }
487 WriterMutexLock mu(self, globals_lock_);
488 if (!globals_.Remove(IRT_FIRST_SEGMENT, obj)) {
489 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
490 << "failed to find entry";
491 }
492}
493
494void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
495 if (obj == nullptr) {
496 return;
497 }
498 MutexLock mu(self, weak_globals_lock_);
499 if (!weak_globals_.Remove(IRT_FIRST_SEGMENT, obj)) {
500 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
501 << "failed to find entry";
502 }
503}
504
505static void ThreadEnableCheckJni(Thread* thread, void* arg) {
506 bool* check_jni = reinterpret_cast<bool*>(arg);
507 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
508}
509
510bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
511 bool old_check_jni = check_jni_;
512 check_jni_ = enabled;
513 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
514 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
515 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
516 return old_check_jni;
517}
518
519void JavaVMExt::DumpForSigQuit(std::ostream& os) {
520 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
521 if (force_copy_) {
522 os << " (with forcecopy)";
523 }
524 Thread* self = Thread::Current();
525 {
Ian Rogers68d8b422014-07-17 11:09:10 -0700526 ReaderMutexLock mu(self, globals_lock_);
527 os << "; globals=" << globals_.Capacity();
528 }
529 {
530 MutexLock mu(self, weak_globals_lock_);
531 if (weak_globals_.Capacity() > 0) {
532 os << " (plus " << weak_globals_.Capacity() << " weak)";
533 }
534 }
535 os << '\n';
536
537 {
538 MutexLock mu(self, *Locks::jni_libraries_lock_);
539 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
540 }
541}
542
543void JavaVMExt::DisallowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700544 CHECK(!kUseReadBarrier);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700545 Thread* const self = Thread::Current();
546 MutexLock mu(self, weak_globals_lock_);
547 // DisallowNewWeakGlobals is only called by CMS during the pause. It is required to have the
548 // mutator lock exclusively held so that we don't have any threads in the middle of
549 // DecodeWeakGlobal.
550 Locks::mutator_lock_->AssertExclusiveHeld(self);
551 allow_accessing_weak_globals_.StoreSequentiallyConsistent(false);
Ian Rogers68d8b422014-07-17 11:09:10 -0700552}
553
554void JavaVMExt::AllowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700555 CHECK(!kUseReadBarrier);
Ian Rogers68d8b422014-07-17 11:09:10 -0700556 Thread* self = Thread::Current();
557 MutexLock mu(self, weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700558 allow_accessing_weak_globals_.StoreSequentiallyConsistent(true);
Ian Rogers68d8b422014-07-17 11:09:10 -0700559 weak_globals_add_condition_.Broadcast(self);
560}
561
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700562void JavaVMExt::BroadcastForNewWeakGlobals() {
563 CHECK(kUseReadBarrier);
564 Thread* self = Thread::Current();
565 MutexLock mu(self, weak_globals_lock_);
566 weak_globals_add_condition_.Broadcast(self);
567}
568
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700569mirror::Object* JavaVMExt::DecodeGlobal(IndirectRef ref) {
570 return globals_.SynchronizedGet(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700571}
572
Jeff Hao83c81952015-05-27 19:29:29 -0700573void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, mirror::Object* result) {
574 WriterMutexLock mu(self, globals_lock_);
575 globals_.Update(ref, result);
576}
577
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700578inline bool JavaVMExt::MayAccessWeakGlobals(Thread* self) const {
579 return MayAccessWeakGlobalsUnlocked(self);
580}
581
582inline bool JavaVMExt::MayAccessWeakGlobalsUnlocked(Thread* self) const {
583 return kUseReadBarrier ? self->GetWeakRefAccessEnabled() :
584 allow_accessing_weak_globals_.LoadSequentiallyConsistent();
585}
586
Ian Rogers68d8b422014-07-17 11:09:10 -0700587mirror::Object* JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700588 // It is safe to access GetWeakRefAccessEnabled without the lock since CC uses checkpoints to call
589 // SetWeakRefAccessEnabled, and the other collectors only modify allow_accessing_weak_globals_
590 // when the mutators are paused.
591 // This only applies in the case where MayAccessWeakGlobals goes from false to true. In the other
592 // case, it may be racy, this is benign since DecodeWeakGlobalLocked does the correct behavior
593 // if MayAccessWeakGlobals is false.
594 if (LIKELY(MayAccessWeakGlobalsUnlocked(self))) {
595 return weak_globals_.SynchronizedGet(ref);
596 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700597 MutexLock mu(self, weak_globals_lock_);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700598 return DecodeWeakGlobalLocked(self, ref);
599}
600
601mirror::Object* JavaVMExt::DecodeWeakGlobalLocked(Thread* self, IndirectRef ref) {
602 if (kDebugLocking) {
603 weak_globals_lock_.AssertHeld(self);
604 }
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700605 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700606 weak_globals_add_condition_.WaitHoldingLocks(self);
607 }
608 return weak_globals_.Get(ref);
609}
610
Jeff Hao83c81952015-05-27 19:29:29 -0700611void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, mirror::Object* result) {
612 MutexLock mu(self, weak_globals_lock_);
613 weak_globals_.Update(ref, result);
614}
615
Ian Rogers68d8b422014-07-17 11:09:10 -0700616void JavaVMExt::DumpReferenceTables(std::ostream& os) {
617 Thread* self = Thread::Current();
618 {
619 ReaderMutexLock mu(self, globals_lock_);
620 globals_.Dump(os);
621 }
622 {
623 MutexLock mu(self, weak_globals_lock_);
624 weak_globals_.Dump(os);
625 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700626}
627
628bool JavaVMExt::LoadNativeLibrary(JNIEnv* env, const std::string& path, jobject class_loader,
629 std::string* error_msg) {
630 error_msg->clear();
631
632 // See if we've already loaded this library. If we have, and the class loader
633 // matches, return successfully without doing anything.
634 // TODO: for better results we should canonicalize the pathname (or even compare
635 // inodes). This implementation is fine if everybody is using System.loadLibrary.
636 SharedLibrary* library;
637 Thread* self = Thread::Current();
638 {
639 // TODO: move the locking (and more of this logic) into Libraries.
640 MutexLock mu(self, *Locks::jni_libraries_lock_);
641 library = libraries_->Get(path);
642 }
643 if (library != nullptr) {
644 if (env->IsSameObject(library->GetClassLoader(), class_loader) == JNI_FALSE) {
645 // The library will be associated with class_loader. The JNI
646 // spec says we can't load the same library into more than one
647 // class loader.
648 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
649 "ClassLoader %p; can't open in ClassLoader %p",
650 path.c_str(), library->GetClassLoader(), class_loader);
651 LOG(WARNING) << error_msg;
652 return false;
653 }
654 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
655 << " ClassLoader " << class_loader << "]";
656 if (!library->CheckOnLoadResult()) {
657 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
658 "to load \"%s\"", path.c_str());
659 return false;
660 }
661 return true;
662 }
663
664 // Open the shared library. Because we're using a full path, the system
665 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
666 // resolve this library's dependencies though.)
667
668 // Failures here are expected when java.library.path has several entries
669 // and we have to hunt for the lib.
670
671 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
672 // class unloading. Libraries will only be unloaded when the reference count (incremented by
673 // dlopen) becomes zero from dlclose.
674
675 Locks::mutator_lock_->AssertNotHeld(self);
676 const char* path_str = path.empty() ? nullptr : path.c_str();
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700677 void* handle = dlopen(path_str, RTLD_NOW);
Ian Rogers68d8b422014-07-17 11:09:10 -0700678 bool needs_native_bridge = false;
679 if (handle == nullptr) {
Calin Juravlec8423522014-08-12 20:55:20 +0100680 if (android::NativeBridgeIsSupported(path_str)) {
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700681 handle = android::NativeBridgeLoadLibrary(path_str, RTLD_NOW);
Ian Rogers68d8b422014-07-17 11:09:10 -0700682 needs_native_bridge = true;
683 }
684 }
685
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700686 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]";
Ian Rogers68d8b422014-07-17 11:09:10 -0700687
688 if (handle == nullptr) {
689 *error_msg = dlerror();
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700690 VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700691 return false;
692 }
693
694 if (env->ExceptionCheck() == JNI_TRUE) {
695 LOG(ERROR) << "Unexpected exception:";
696 env->ExceptionDescribe();
697 env->ExceptionClear();
698 }
699 // Create a new entry.
700 // TODO: move the locking (and more of this logic) into Libraries.
701 bool created_library = false;
702 {
703 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
704 std::unique_ptr<SharedLibrary> new_library(
705 new SharedLibrary(env, self, path, handle, class_loader));
706 MutexLock mu(self, *Locks::jni_libraries_lock_);
707 library = libraries_->Get(path);
708 if (library == nullptr) { // We won race to get libraries_lock.
709 library = new_library.release();
710 libraries_->Put(path, library);
711 created_library = true;
712 }
713 }
714 if (!created_library) {
715 LOG(INFO) << "WOW: we lost a race to add shared library: "
716 << "\"" << path << "\" ClassLoader=" << class_loader;
717 return library->CheckOnLoadResult();
718 }
719 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
720
721 bool was_successful = false;
722 void* sym;
723 if (needs_native_bridge) {
724 library->SetNeedsNativeBridge();
725 sym = library->FindSymbolWithNativeBridge("JNI_OnLoad", nullptr);
726 } else {
727 sym = dlsym(handle, "JNI_OnLoad");
728 }
729 if (sym == nullptr) {
730 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
731 was_successful = true;
732 } else {
733 // Call JNI_OnLoad. We have to override the current class
734 // loader, which will always be "null" since the stuff at the
735 // top of the stack is around Runtime.loadLibrary(). (See
736 // the comments in the JNI FindClass function.)
737 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
738 self->SetClassLoaderOverride(class_loader);
739
740 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
741 typedef int (*JNI_OnLoadFn)(JavaVM*, void*);
742 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
743 int version = (*jni_on_load)(this, nullptr);
744
Mathieu Chartierd0004802014-10-15 16:59:47 -0700745 if (runtime_->GetTargetSdkVersion() != 0 && runtime_->GetTargetSdkVersion() <= 21) {
746 fault_manager.EnsureArtActionInFrontOfSignalChain();
747 }
748
Ian Rogers68d8b422014-07-17 11:09:10 -0700749 self->SetClassLoaderOverride(old_class_loader.get());
750
751 if (version == JNI_ERR) {
752 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
753 } else if (IsBadJniVersion(version)) {
754 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
755 path.c_str(), version);
756 // It's unwise to call dlclose() here, but we can mark it
757 // as bad and ensure that future load attempts will fail.
758 // We don't know how far JNI_OnLoad got, so there could
759 // be some partially-initialized stuff accessible through
760 // newly-registered native method calls. We could try to
761 // unregister them, but that doesn't seem worthwhile.
762 } else {
763 was_successful = true;
764 }
765 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
766 << " from JNI_OnLoad in \"" << path << "\"]";
767 }
768
769 library->SetResult(was_successful);
770 return was_successful;
771}
772
Mathieu Chartiere401d142015-04-22 13:56:20 -0700773void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700774 CHECK(m->IsNative());
775 mirror::Class* c = m->GetDeclaringClass();
776 // If this is a static method, it could be called before the class has been initialized.
777 CHECK(c->IsInitializing()) << c->GetStatus() << " " << PrettyMethod(m);
778 std::string detail;
779 void* native_method;
780 Thread* self = Thread::Current();
781 {
782 MutexLock mu(self, *Locks::jni_libraries_lock_);
783 native_method = libraries_->FindNativeMethod(m, detail);
784 }
785 // Throwing can cause libraries_lock to be reacquired.
786 if (native_method == nullptr) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000787 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
Ian Rogers68d8b422014-07-17 11:09:10 -0700788 }
789 return native_method;
790}
791
Mathieu Chartier97509952015-07-13 14:35:43 -0700792void JavaVMExt::SweepJniWeakGlobals(IsMarkedVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700793 MutexLock mu(Thread::Current(), weak_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700794 Runtime* const runtime = Runtime::Current();
795 for (auto* entry : weak_globals_) {
796 // Need to skip null here to distinguish between null entries and cleared weak ref entries.
797 if (!entry->IsNull()) {
798 // Since this is called by the GC, we don't need a read barrier.
799 mirror::Object* obj = entry->Read<kWithoutReadBarrier>();
Mathieu Chartier97509952015-07-13 14:35:43 -0700800 mirror::Object* new_obj = visitor->IsMarked(obj);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700801 if (new_obj == nullptr) {
802 new_obj = runtime->GetClearedJniWeakGlobal();
803 }
804 *entry = GcRoot<mirror::Object>(new_obj);
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -0700805 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700806 }
807}
808
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800809void JavaVMExt::TrimGlobals() {
810 WriterMutexLock mu(Thread::Current(), globals_lock_);
811 globals_.Trim();
812}
813
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700814void JavaVMExt::VisitRoots(RootVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700815 Thread* self = Thread::Current();
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800816 ReaderMutexLock mu(self, globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700817 globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal));
Ian Rogers68d8b422014-07-17 11:09:10 -0700818 // The weak_globals table is visited by the GC itself (because it mutates the table).
819}
820
821// JNI Invocation interface.
822
823extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
Richard Uhler054a0782015-04-07 10:56:50 -0700824 ATRACE_BEGIN(__FUNCTION__);
Ian Rogers68d8b422014-07-17 11:09:10 -0700825 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
826 if (IsBadJniVersion(args->version)) {
827 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
Richard Uhler054a0782015-04-07 10:56:50 -0700828 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700829 return JNI_EVERSION;
830 }
831 RuntimeOptions options;
832 for (int i = 0; i < args->nOptions; ++i) {
833 JavaVMOption* option = &args->options[i];
834 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
835 }
836 bool ignore_unrecognized = args->ignoreUnrecognized;
837 if (!Runtime::Create(options, ignore_unrecognized)) {
Richard Uhler054a0782015-04-07 10:56:50 -0700838 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700839 return JNI_ERR;
840 }
841 Runtime* runtime = Runtime::Current();
842 bool started = runtime->Start();
843 if (!started) {
844 delete Thread::Current()->GetJniEnv();
845 delete runtime->GetJavaVM();
846 LOG(WARNING) << "CreateJavaVM failed";
Richard Uhler054a0782015-04-07 10:56:50 -0700847 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700848 return JNI_ERR;
849 }
850 *p_env = Thread::Current()->GetJniEnv();
851 *p_vm = runtime->GetJavaVM();
Richard Uhler054a0782015-04-07 10:56:50 -0700852 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700853 return JNI_OK;
854}
855
Ian Rogersf4d4da12014-11-11 16:10:33 -0800856extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700857 Runtime* runtime = Runtime::Current();
Ian Rogersf4d4da12014-11-11 16:10:33 -0800858 if (runtime == nullptr || buf_len == 0) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700859 *vm_count = 0;
860 } else {
861 *vm_count = 1;
Ian Rogersf4d4da12014-11-11 16:10:33 -0800862 vms_buf[0] = runtime->GetJavaVM();
Ian Rogers68d8b422014-07-17 11:09:10 -0700863 }
864 return JNI_OK;
865}
866
867// Historically unsupported.
868extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
869 return JNI_ERR;
870}
871
872} // namespace art