blob: b5e28e93149446b59d4db16b58b9c25dc7d31d55 [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),
Mathieu Chartier598302a2015-09-23 14:52:39 -070063 class_loader_(env->NewWeakGlobalRef(class_loader)),
Ian Rogers68d8b422014-07-17 11:09:10 -070064 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) {
Mathieu Chartier598302a2015-09-23 14:52:39 -070073 self->GetJniEnv()->DeleteWeakGlobalRef(class_loader_);
Ian Rogers68d8b422014-07-17 11:09:10 -070074 }
75 }
76
Mathieu Chartier598302a2015-09-23 14:52:39 -070077 jweak GetClassLoader() const {
Ian Rogers68d8b422014-07-17 11:09:10 -070078 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
Mathieu Chartier598302a2015-09-23 14:52:39 -0700134 void* FindSymbol(const std::string& symbol_name, const char* shorty = nullptr) {
135 return NeedsNativeBridge()
136 ? FindSymbolWithNativeBridge(symbol_name.c_str(), shorty)
137 : FindSymbolWithoutNativeBridge(symbol_name.c_str());
138 }
139
140 void* FindSymbolWithoutNativeBridge(const std::string& symbol_name) {
Andreas Gampe8fec90b2015-06-30 11:23:44 -0700141 CHECK(!NeedsNativeBridge());
142
Ian Rogers68d8b422014-07-17 11:09:10 -0700143 return dlsym(handle_, symbol_name.c_str());
144 }
145
146 void* FindSymbolWithNativeBridge(const std::string& symbol_name, const char* shorty) {
147 CHECK(NeedsNativeBridge());
148
149 uint32_t len = 0;
Calin Juravlec8423522014-08-12 20:55:20 +0100150 return android::NativeBridgeGetTrampoline(handle_, symbol_name.c_str(), shorty, len);
Ian Rogers68d8b422014-07-17 11:09:10 -0700151 }
152
153 private:
154 enum JNI_OnLoadState {
155 kPending,
156 kFailed,
157 kOkay,
158 };
159
160 // Path to library "/system/lib/libjni.so".
161 const std::string path_;
162
163 // The void* returned by dlopen(3).
164 void* const handle_;
165
166 // True if a native bridge is required.
167 bool needs_native_bridge_;
168
Mathieu Chartier598302a2015-09-23 14:52:39 -0700169 // The ClassLoader this library is associated with, a weak global JNI reference that is
Ian Rogers68d8b422014-07-17 11:09:10 -0700170 // created/deleted with the scope of the library.
Mathieu Chartier598302a2015-09-23 14:52:39 -0700171 const jweak class_loader_;
Ian Rogers68d8b422014-07-17 11:09:10 -0700172
173 // Guards remaining items.
174 Mutex jni_on_load_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
175 // Wait for JNI_OnLoad in other thread.
176 ConditionVariable jni_on_load_cond_ GUARDED_BY(jni_on_load_lock_);
177 // Recursive invocation guard.
178 uint32_t jni_on_load_thread_id_ GUARDED_BY(jni_on_load_lock_);
179 // Result of earlier JNI_OnLoad call.
180 JNI_OnLoadState jni_on_load_result_ GUARDED_BY(jni_on_load_lock_);
181};
182
183// This exists mainly to keep implementation details out of the header file.
184class Libraries {
185 public:
186 Libraries() {
187 }
188
189 ~Libraries() {
190 STLDeleteValues(&libraries_);
191 }
192
Mathieu Chartier598302a2015-09-23 14:52:39 -0700193 // NO_THREAD_SAFETY_ANALYSIS since this may be called from Dumpable. Dumpable can't be annotated
194 // properly due to the template. The caller should be holding the jni_libraries_lock_.
195 void Dump(std::ostream& os) const NO_THREAD_SAFETY_ANALYSIS {
196 Locks::jni_libraries_lock_->AssertHeld(Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -0700197 bool first = true;
198 for (const auto& library : libraries_) {
199 if (!first) {
200 os << ' ';
201 }
202 first = false;
203 os << library.first;
204 }
205 }
206
Mathieu Chartier598302a2015-09-23 14:52:39 -0700207 size_t size() const REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700208 return libraries_.size();
209 }
210
Mathieu Chartier598302a2015-09-23 14:52:39 -0700211 SharedLibrary* Get(const std::string& path) REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700212 auto it = libraries_.find(path);
213 return (it == libraries_.end()) ? nullptr : it->second;
214 }
215
Mathieu Chartier598302a2015-09-23 14:52:39 -0700216 void Put(const std::string& path, SharedLibrary* library)
217 REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700218 libraries_.Put(path, library);
219 }
220
221 // See section 11.3 "Linking Native Methods" of the JNI spec.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700222 void* FindNativeMethod(ArtMethod* m, std::string& detail)
Mathieu Chartier90443472015-07-16 20:32:27 -0700223 REQUIRES(Locks::jni_libraries_lock_)
224 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700225 std::string jni_short_name(JniShortName(m));
226 std::string jni_long_name(JniLongName(m));
227 const mirror::ClassLoader* declaring_class_loader = m->GetDeclaringClass()->GetClassLoader();
228 ScopedObjectAccessUnchecked soa(Thread::Current());
229 for (const auto& lib : libraries_) {
Mathieu Chartier598302a2015-09-23 14:52:39 -0700230 SharedLibrary* const library = lib.second;
Ian Rogers68d8b422014-07-17 11:09:10 -0700231 if (soa.Decode<mirror::ClassLoader*>(library->GetClassLoader()) != declaring_class_loader) {
232 // We only search libraries loaded by the appropriate ClassLoader.
233 continue;
234 }
235 // Try the short name then the long name...
Mathieu Chartier598302a2015-09-23 14:52:39 -0700236 const char* shorty = library->NeedsNativeBridge()
237 ? m->GetShorty()
238 : nullptr;
239 void* fn = library->FindSymbol(jni_short_name, shorty);
240 if (fn == nullptr) {
241 fn = library->FindSymbol(jni_long_name, shorty);
Ian Rogers68d8b422014-07-17 11:09:10 -0700242 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700243 if (fn != nullptr) {
244 VLOG(jni) << "[Found native code for " << PrettyMethod(m)
245 << " in \"" << library->GetPath() << "\"]";
246 return fn;
247 }
248 }
249 detail += "No implementation found for ";
250 detail += PrettyMethod(m);
251 detail += " (tried " + jni_short_name + " and " + jni_long_name + ")";
252 LOG(ERROR) << detail;
253 return nullptr;
254 }
255
Mathieu Chartier598302a2015-09-23 14:52:39 -0700256 // Unload native libraries with cleared class loaders.
257 void UnloadNativeLibraries()
258 REQUIRES(!Locks::jni_libraries_lock_)
259 SHARED_REQUIRES(Locks::mutator_lock_) {
260 ScopedObjectAccessUnchecked soa(Thread::Current());
261 typedef void (*JNI_OnUnloadFn)(JavaVM*, void*);
262 std::vector<JNI_OnUnloadFn> unload_functions;
263 {
264 MutexLock mu(soa.Self(), *Locks::jni_libraries_lock_);
265 for (auto it = libraries_.begin(); it != libraries_.end(); ) {
266 SharedLibrary* const library = it->second;
267 // If class loader is null then it was unloaded, call JNI_OnUnload.
Mathieu Chartiercffb7472015-09-28 10:33:00 -0700268 const jweak class_loader = library->GetClassLoader();
269 // If class_loader is a null jobject then it is the boot class loader. We should not unload
270 // the native libraries of the boot class loader.
271 if (class_loader != nullptr &&
272 soa.Decode<mirror::ClassLoader*>(class_loader) == nullptr) {
Mathieu Chartier598302a2015-09-23 14:52:39 -0700273 void* const sym = library->FindSymbol("JNI_OnUnload", nullptr);
274 if (sym == nullptr) {
275 VLOG(jni) << "[No JNI_OnUnload found in \"" << library->GetPath() << "\"]";
276 } else {
277 VLOG(jni) << "[JNI_OnUnload found for \"" << library->GetPath() << "\"]";
278 JNI_OnUnloadFn jni_on_unload = reinterpret_cast<JNI_OnUnloadFn>(sym);
279 unload_functions.push_back(jni_on_unload);
280 }
281 delete library;
282 it = libraries_.erase(it);
283 } else {
284 ++it;
285 }
286 }
287 }
288 // Do this without holding the jni libraries lock to prevent possible deadlocks.
289 for (JNI_OnUnloadFn fn : unload_functions) {
290 VLOG(jni) << "Calling JNI_OnUnload";
291 (*fn)(soa.Vm(), nullptr);
292 }
293 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700294
Mathieu Chartier598302a2015-09-23 14:52:39 -0700295 private:
296 AllocationTrackingSafeMap<std::string, SharedLibrary*, kAllocatorTagJNILibraries> libraries_
297 GUARDED_BY(Locks::jni_libraries_lock_);
298};
Ian Rogers68d8b422014-07-17 11:09:10 -0700299
300class JII {
301 public:
302 static jint DestroyJavaVM(JavaVM* vm) {
303 if (vm == nullptr) {
304 return JNI_ERR;
305 }
306 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
307 delete raw_vm->GetRuntime();
308 return JNI_OK;
309 }
310
311 static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
312 return AttachCurrentThreadInternal(vm, p_env, thr_args, false);
313 }
314
315 static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
316 return AttachCurrentThreadInternal(vm, p_env, thr_args, true);
317 }
318
319 static jint DetachCurrentThread(JavaVM* vm) {
320 if (vm == nullptr || Thread::Current() == nullptr) {
321 return JNI_ERR;
322 }
323 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
324 Runtime* runtime = raw_vm->GetRuntime();
325 runtime->DetachCurrentThread();
326 return JNI_OK;
327 }
328
329 static jint GetEnv(JavaVM* vm, void** env, jint version) {
330 // GetEnv always returns a JNIEnv* for the most current supported JNI version,
331 // and unlike other calls that take a JNI version doesn't care if you supply
332 // JNI_VERSION_1_1, which we don't otherwise support.
333 if (IsBadJniVersion(version) && version != JNI_VERSION_1_1) {
334 LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version;
335 return JNI_EVERSION;
336 }
337 if (vm == nullptr || env == nullptr) {
338 return JNI_ERR;
339 }
340 Thread* thread = Thread::Current();
341 if (thread == nullptr) {
342 *env = nullptr;
343 return JNI_EDETACHED;
344 }
345 *env = thread->GetJniEnv();
346 return JNI_OK;
347 }
348
349 private:
350 static jint AttachCurrentThreadInternal(JavaVM* vm, JNIEnv** p_env, void* raw_args, bool as_daemon) {
351 if (vm == nullptr || p_env == nullptr) {
352 return JNI_ERR;
353 }
354
355 // Return immediately if we're already attached.
356 Thread* self = Thread::Current();
357 if (self != nullptr) {
358 *p_env = self->GetJniEnv();
359 return JNI_OK;
360 }
361
362 Runtime* runtime = reinterpret_cast<JavaVMExt*>(vm)->GetRuntime();
363
364 // No threads allowed in zygote mode.
365 if (runtime->IsZygote()) {
366 LOG(ERROR) << "Attempt to attach a thread in the zygote";
367 return JNI_ERR;
368 }
369
370 JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(raw_args);
371 const char* thread_name = nullptr;
372 jobject thread_group = nullptr;
373 if (args != nullptr) {
374 if (IsBadJniVersion(args->version)) {
375 LOG(ERROR) << "Bad JNI version passed to "
376 << (as_daemon ? "AttachCurrentThreadAsDaemon" : "AttachCurrentThread") << ": "
377 << args->version;
378 return JNI_EVERSION;
379 }
380 thread_name = args->name;
381 thread_group = args->group;
382 }
383
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800384 if (!runtime->AttachCurrentThread(thread_name, as_daemon, thread_group,
385 !runtime->IsAotCompiler())) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700386 *p_env = nullptr;
387 return JNI_ERR;
388 } else {
389 *p_env = Thread::Current()->GetJniEnv();
390 return JNI_OK;
391 }
392 }
393};
394
395const JNIInvokeInterface gJniInvokeInterface = {
396 nullptr, // reserved0
397 nullptr, // reserved1
398 nullptr, // reserved2
399 JII::DestroyJavaVM,
400 JII::AttachCurrentThread,
401 JII::DetachCurrentThread,
402 JII::GetEnv,
403 JII::AttachCurrentThreadAsDaemon
404};
405
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800406JavaVMExt::JavaVMExt(Runtime* runtime, const RuntimeArgumentMap& runtime_options)
Ian Rogers68d8b422014-07-17 11:09:10 -0700407 : runtime_(runtime),
408 check_jni_abort_hook_(nullptr),
409 check_jni_abort_hook_data_(nullptr),
410 check_jni_(false), // Initialized properly in the constructor body below.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800411 force_copy_(runtime_options.Exists(RuntimeArgumentMap::JniOptsForceCopy)),
412 tracing_enabled_(runtime_options.Exists(RuntimeArgumentMap::JniTrace)
413 || VLOG_IS_ON(third_party_jni)),
414 trace_(runtime_options.GetOrDefault(RuntimeArgumentMap::JniTrace)),
Ian Rogers68d8b422014-07-17 11:09:10 -0700415 globals_lock_("JNI global reference table lock"),
416 globals_(gGlobalsInitial, gGlobalsMax, kGlobal),
417 libraries_(new Libraries),
418 unchecked_functions_(&gJniInvokeInterface),
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700419 weak_globals_lock_("JNI weak global reference table lock", kJniWeakGlobalsLock),
Ian Rogers68d8b422014-07-17 11:09:10 -0700420 weak_globals_(kWeakGlobalsInitial, kWeakGlobalsMax, kWeakGlobal),
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700421 allow_accessing_weak_globals_(true),
Ian Rogers68d8b422014-07-17 11:09:10 -0700422 weak_globals_add_condition_("weak globals add condition", weak_globals_lock_) {
423 functions = unchecked_functions_;
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800424 SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni));
Ian Rogers68d8b422014-07-17 11:09:10 -0700425}
426
427JavaVMExt::~JavaVMExt() {
428}
429
430void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) {
431 Thread* self = Thread::Current();
432 ScopedObjectAccess soa(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700433 ArtMethod* current_method = self->GetCurrentMethod(nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700434
435 std::ostringstream os;
436 os << "JNI DETECTED ERROR IN APPLICATION: " << msg;
437
438 if (jni_function_name != nullptr) {
439 os << "\n in call to " << jni_function_name;
440 }
441 // TODO: is this useful given that we're about to dump the calling thread's stack?
442 if (current_method != nullptr) {
443 os << "\n from " << PrettyMethod(current_method);
444 }
445 os << "\n";
446 self->Dump(os);
447
448 if (check_jni_abort_hook_ != nullptr) {
449 check_jni_abort_hook_(check_jni_abort_hook_data_, os.str());
450 } else {
451 // Ensure that we get a native stack trace for this thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700452 ScopedThreadSuspension sts(self, kNative);
Ian Rogers68d8b422014-07-17 11:09:10 -0700453 LOG(FATAL) << os.str();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700454 UNREACHABLE();
Ian Rogers68d8b422014-07-17 11:09:10 -0700455 }
456}
457
458void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) {
459 std::string msg;
460 StringAppendV(&msg, fmt, ap);
461 JniAbort(jni_function_name, msg.c_str());
462}
463
464void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) {
465 va_list args;
466 va_start(args, fmt);
467 JniAbortV(jni_function_name, fmt, args);
468 va_end(args);
469}
470
Mathieu Chartiere401d142015-04-22 13:56:20 -0700471bool JavaVMExt::ShouldTrace(ArtMethod* method) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700472 // Fast where no tracing is enabled.
473 if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) {
474 return false;
475 }
476 // Perform checks based on class name.
477 StringPiece class_name(method->GetDeclaringClassDescriptor());
478 if (!trace_.empty() && class_name.find(trace_) != std::string::npos) {
479 return true;
480 }
481 if (!VLOG_IS_ON(third_party_jni)) {
482 return false;
483 }
484 // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
485 // like part of Android.
486 static const char* gBuiltInPrefixes[] = {
487 "Landroid/",
488 "Lcom/android/",
489 "Lcom/google/android/",
490 "Ldalvik/",
491 "Ljava/",
492 "Ljavax/",
493 "Llibcore/",
494 "Lorg/apache/harmony/",
495 };
496 for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) {
497 if (class_name.starts_with(gBuiltInPrefixes[i])) {
498 return false;
499 }
500 }
501 return true;
502}
503
504jobject JavaVMExt::AddGlobalRef(Thread* self, mirror::Object* obj) {
505 // Check for null after decoding the object to handle cleared weak globals.
506 if (obj == nullptr) {
507 return nullptr;
508 }
509 WriterMutexLock mu(self, globals_lock_);
510 IndirectRef ref = globals_.Add(IRT_FIRST_SEGMENT, obj);
511 return reinterpret_cast<jobject>(ref);
512}
513
514jweak JavaVMExt::AddWeakGlobalRef(Thread* self, mirror::Object* obj) {
515 if (obj == nullptr) {
516 return nullptr;
517 }
518 MutexLock mu(self, weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700519 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700520 weak_globals_add_condition_.WaitHoldingLocks(self);
521 }
522 IndirectRef ref = weak_globals_.Add(IRT_FIRST_SEGMENT, obj);
523 return reinterpret_cast<jweak>(ref);
524}
525
526void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
527 if (obj == nullptr) {
528 return;
529 }
530 WriterMutexLock mu(self, globals_lock_);
531 if (!globals_.Remove(IRT_FIRST_SEGMENT, obj)) {
532 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
533 << "failed to find entry";
534 }
535}
536
537void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
538 if (obj == nullptr) {
539 return;
540 }
541 MutexLock mu(self, weak_globals_lock_);
542 if (!weak_globals_.Remove(IRT_FIRST_SEGMENT, obj)) {
543 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
544 << "failed to find entry";
545 }
546}
547
548static void ThreadEnableCheckJni(Thread* thread, void* arg) {
549 bool* check_jni = reinterpret_cast<bool*>(arg);
550 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
551}
552
553bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
554 bool old_check_jni = check_jni_;
555 check_jni_ = enabled;
556 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
557 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
558 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
559 return old_check_jni;
560}
561
562void JavaVMExt::DumpForSigQuit(std::ostream& os) {
563 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
564 if (force_copy_) {
565 os << " (with forcecopy)";
566 }
567 Thread* self = Thread::Current();
568 {
Ian Rogers68d8b422014-07-17 11:09:10 -0700569 ReaderMutexLock mu(self, globals_lock_);
570 os << "; globals=" << globals_.Capacity();
571 }
572 {
573 MutexLock mu(self, weak_globals_lock_);
574 if (weak_globals_.Capacity() > 0) {
575 os << " (plus " << weak_globals_.Capacity() << " weak)";
576 }
577 }
578 os << '\n';
579
580 {
581 MutexLock mu(self, *Locks::jni_libraries_lock_);
582 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
583 }
584}
585
586void JavaVMExt::DisallowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700587 CHECK(!kUseReadBarrier);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700588 Thread* const self = Thread::Current();
589 MutexLock mu(self, weak_globals_lock_);
590 // DisallowNewWeakGlobals is only called by CMS during the pause. It is required to have the
591 // mutator lock exclusively held so that we don't have any threads in the middle of
592 // DecodeWeakGlobal.
593 Locks::mutator_lock_->AssertExclusiveHeld(self);
594 allow_accessing_weak_globals_.StoreSequentiallyConsistent(false);
Ian Rogers68d8b422014-07-17 11:09:10 -0700595}
596
597void JavaVMExt::AllowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700598 CHECK(!kUseReadBarrier);
Ian Rogers68d8b422014-07-17 11:09:10 -0700599 Thread* self = Thread::Current();
600 MutexLock mu(self, weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700601 allow_accessing_weak_globals_.StoreSequentiallyConsistent(true);
Ian Rogers68d8b422014-07-17 11:09:10 -0700602 weak_globals_add_condition_.Broadcast(self);
603}
604
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700605void JavaVMExt::BroadcastForNewWeakGlobals() {
606 CHECK(kUseReadBarrier);
607 Thread* self = Thread::Current();
608 MutexLock mu(self, weak_globals_lock_);
609 weak_globals_add_condition_.Broadcast(self);
610}
611
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700612mirror::Object* JavaVMExt::DecodeGlobal(IndirectRef ref) {
613 return globals_.SynchronizedGet(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700614}
615
Jeff Hao83c81952015-05-27 19:29:29 -0700616void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, mirror::Object* result) {
617 WriterMutexLock mu(self, globals_lock_);
618 globals_.Update(ref, result);
619}
620
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700621inline bool JavaVMExt::MayAccessWeakGlobals(Thread* self) const {
622 return MayAccessWeakGlobalsUnlocked(self);
623}
624
625inline bool JavaVMExt::MayAccessWeakGlobalsUnlocked(Thread* self) const {
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700626 DCHECK(self != nullptr);
627 return kUseReadBarrier ?
628 self->GetWeakRefAccessEnabled() :
629 allow_accessing_weak_globals_.LoadSequentiallyConsistent();
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700630}
631
Ian Rogers68d8b422014-07-17 11:09:10 -0700632mirror::Object* JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700633 // It is safe to access GetWeakRefAccessEnabled without the lock since CC uses checkpoints to call
634 // SetWeakRefAccessEnabled, and the other collectors only modify allow_accessing_weak_globals_
635 // when the mutators are paused.
636 // This only applies in the case where MayAccessWeakGlobals goes from false to true. In the other
637 // case, it may be racy, this is benign since DecodeWeakGlobalLocked does the correct behavior
638 // if MayAccessWeakGlobals is false.
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -0700639 DCHECK_EQ(GetIndirectRefKind(ref), kWeakGlobal);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700640 if (LIKELY(MayAccessWeakGlobalsUnlocked(self))) {
641 return weak_globals_.SynchronizedGet(ref);
642 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700643 MutexLock mu(self, weak_globals_lock_);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700644 return DecodeWeakGlobalLocked(self, ref);
645}
646
647mirror::Object* JavaVMExt::DecodeWeakGlobalLocked(Thread* self, IndirectRef ref) {
648 if (kDebugLocking) {
649 weak_globals_lock_.AssertHeld(self);
650 }
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700651 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700652 weak_globals_add_condition_.WaitHoldingLocks(self);
653 }
654 return weak_globals_.Get(ref);
655}
656
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700657mirror::Object* JavaVMExt::DecodeWeakGlobalDuringShutdown(Thread* self, IndirectRef ref) {
658 DCHECK_EQ(GetIndirectRefKind(ref), kWeakGlobal);
659 DCHECK(Runtime::Current()->IsShuttingDown(self));
660 if (self != nullptr) {
661 return DecodeWeakGlobal(self, ref);
662 }
663 // self can be null during a runtime shutdown. ~Runtime()->~ClassLinker()->DecodeWeakGlobal().
664 if (!kUseReadBarrier) {
665 DCHECK(allow_accessing_weak_globals_.LoadSequentiallyConsistent());
666 }
667 return weak_globals_.SynchronizedGet(ref);
668}
669
Jeff Hao83c81952015-05-27 19:29:29 -0700670void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, mirror::Object* result) {
671 MutexLock mu(self, weak_globals_lock_);
672 weak_globals_.Update(ref, result);
673}
674
Ian Rogers68d8b422014-07-17 11:09:10 -0700675void JavaVMExt::DumpReferenceTables(std::ostream& os) {
676 Thread* self = Thread::Current();
677 {
678 ReaderMutexLock mu(self, globals_lock_);
679 globals_.Dump(os);
680 }
681 {
682 MutexLock mu(self, weak_globals_lock_);
683 weak_globals_.Dump(os);
684 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700685}
686
Mathieu Chartier598302a2015-09-23 14:52:39 -0700687void JavaVMExt::UnloadNativeLibraries() {
688 libraries_.get()->UnloadNativeLibraries();
689}
690
Ian Rogers68d8b422014-07-17 11:09:10 -0700691bool JavaVMExt::LoadNativeLibrary(JNIEnv* env, const std::string& path, jobject class_loader,
692 std::string* error_msg) {
693 error_msg->clear();
694
695 // See if we've already loaded this library. If we have, and the class loader
696 // matches, return successfully without doing anything.
697 // TODO: for better results we should canonicalize the pathname (or even compare
698 // inodes). This implementation is fine if everybody is using System.loadLibrary.
699 SharedLibrary* library;
700 Thread* self = Thread::Current();
701 {
702 // TODO: move the locking (and more of this logic) into Libraries.
703 MutexLock mu(self, *Locks::jni_libraries_lock_);
704 library = libraries_->Get(path);
705 }
706 if (library != nullptr) {
707 if (env->IsSameObject(library->GetClassLoader(), class_loader) == JNI_FALSE) {
708 // The library will be associated with class_loader. The JNI
709 // spec says we can't load the same library into more than one
710 // class loader.
711 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
712 "ClassLoader %p; can't open in ClassLoader %p",
713 path.c_str(), library->GetClassLoader(), class_loader);
714 LOG(WARNING) << error_msg;
715 return false;
716 }
717 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
718 << " ClassLoader " << class_loader << "]";
719 if (!library->CheckOnLoadResult()) {
720 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
721 "to load \"%s\"", path.c_str());
722 return false;
723 }
724 return true;
725 }
726
727 // Open the shared library. Because we're using a full path, the system
728 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
729 // resolve this library's dependencies though.)
730
731 // Failures here are expected when java.library.path has several entries
732 // and we have to hunt for the lib.
733
734 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
735 // class unloading. Libraries will only be unloaded when the reference count (incremented by
736 // dlopen) becomes zero from dlclose.
737
738 Locks::mutator_lock_->AssertNotHeld(self);
739 const char* path_str = path.empty() ? nullptr : path.c_str();
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700740 void* handle = dlopen(path_str, RTLD_NOW);
Ian Rogers68d8b422014-07-17 11:09:10 -0700741 bool needs_native_bridge = false;
742 if (handle == nullptr) {
Calin Juravlec8423522014-08-12 20:55:20 +0100743 if (android::NativeBridgeIsSupported(path_str)) {
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700744 handle = android::NativeBridgeLoadLibrary(path_str, RTLD_NOW);
Ian Rogers68d8b422014-07-17 11:09:10 -0700745 needs_native_bridge = true;
746 }
747 }
748
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700749 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]";
Ian Rogers68d8b422014-07-17 11:09:10 -0700750
751 if (handle == nullptr) {
752 *error_msg = dlerror();
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700753 VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700754 return false;
755 }
756
757 if (env->ExceptionCheck() == JNI_TRUE) {
758 LOG(ERROR) << "Unexpected exception:";
759 env->ExceptionDescribe();
760 env->ExceptionClear();
761 }
762 // Create a new entry.
763 // TODO: move the locking (and more of this logic) into Libraries.
764 bool created_library = false;
765 {
766 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
767 std::unique_ptr<SharedLibrary> new_library(
768 new SharedLibrary(env, self, path, handle, class_loader));
769 MutexLock mu(self, *Locks::jni_libraries_lock_);
770 library = libraries_->Get(path);
771 if (library == nullptr) { // We won race to get libraries_lock.
772 library = new_library.release();
773 libraries_->Put(path, library);
774 created_library = true;
775 }
776 }
777 if (!created_library) {
778 LOG(INFO) << "WOW: we lost a race to add shared library: "
779 << "\"" << path << "\" ClassLoader=" << class_loader;
780 return library->CheckOnLoadResult();
781 }
782 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
783
784 bool was_successful = false;
785 void* sym;
786 if (needs_native_bridge) {
787 library->SetNeedsNativeBridge();
Ian Rogers68d8b422014-07-17 11:09:10 -0700788 }
Mathieu Chartier598302a2015-09-23 14:52:39 -0700789 sym = library->FindSymbol("JNI_OnLoad", nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700790 if (sym == nullptr) {
791 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
792 was_successful = true;
793 } else {
794 // Call JNI_OnLoad. We have to override the current class
795 // loader, which will always be "null" since the stuff at the
796 // top of the stack is around Runtime.loadLibrary(). (See
797 // the comments in the JNI FindClass function.)
798 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
799 self->SetClassLoaderOverride(class_loader);
800
801 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
802 typedef int (*JNI_OnLoadFn)(JavaVM*, void*);
803 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
804 int version = (*jni_on_load)(this, nullptr);
805
Mathieu Chartierd0004802014-10-15 16:59:47 -0700806 if (runtime_->GetTargetSdkVersion() != 0 && runtime_->GetTargetSdkVersion() <= 21) {
807 fault_manager.EnsureArtActionInFrontOfSignalChain();
808 }
809
Ian Rogers68d8b422014-07-17 11:09:10 -0700810 self->SetClassLoaderOverride(old_class_loader.get());
811
812 if (version == JNI_ERR) {
813 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
814 } else if (IsBadJniVersion(version)) {
815 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
816 path.c_str(), version);
817 // It's unwise to call dlclose() here, but we can mark it
818 // as bad and ensure that future load attempts will fail.
819 // We don't know how far JNI_OnLoad got, so there could
820 // be some partially-initialized stuff accessible through
821 // newly-registered native method calls. We could try to
822 // unregister them, but that doesn't seem worthwhile.
823 } else {
824 was_successful = true;
825 }
826 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
827 << " from JNI_OnLoad in \"" << path << "\"]";
828 }
829
830 library->SetResult(was_successful);
831 return was_successful;
832}
833
Mathieu Chartiere401d142015-04-22 13:56:20 -0700834void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700835 CHECK(m->IsNative());
836 mirror::Class* c = m->GetDeclaringClass();
837 // If this is a static method, it could be called before the class has been initialized.
838 CHECK(c->IsInitializing()) << c->GetStatus() << " " << PrettyMethod(m);
839 std::string detail;
840 void* native_method;
841 Thread* self = Thread::Current();
842 {
843 MutexLock mu(self, *Locks::jni_libraries_lock_);
844 native_method = libraries_->FindNativeMethod(m, detail);
845 }
846 // Throwing can cause libraries_lock to be reacquired.
847 if (native_method == nullptr) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000848 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
Ian Rogers68d8b422014-07-17 11:09:10 -0700849 }
850 return native_method;
851}
852
Mathieu Chartier97509952015-07-13 14:35:43 -0700853void JavaVMExt::SweepJniWeakGlobals(IsMarkedVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700854 MutexLock mu(Thread::Current(), weak_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700855 Runtime* const runtime = Runtime::Current();
856 for (auto* entry : weak_globals_) {
857 // Need to skip null here to distinguish between null entries and cleared weak ref entries.
858 if (!entry->IsNull()) {
859 // Since this is called by the GC, we don't need a read barrier.
860 mirror::Object* obj = entry->Read<kWithoutReadBarrier>();
Mathieu Chartier97509952015-07-13 14:35:43 -0700861 mirror::Object* new_obj = visitor->IsMarked(obj);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700862 if (new_obj == nullptr) {
863 new_obj = runtime->GetClearedJniWeakGlobal();
864 }
865 *entry = GcRoot<mirror::Object>(new_obj);
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -0700866 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700867 }
868}
869
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800870void JavaVMExt::TrimGlobals() {
871 WriterMutexLock mu(Thread::Current(), globals_lock_);
872 globals_.Trim();
873}
874
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700875void JavaVMExt::VisitRoots(RootVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700876 Thread* self = Thread::Current();
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800877 ReaderMutexLock mu(self, globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700878 globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal));
Ian Rogers68d8b422014-07-17 11:09:10 -0700879 // The weak_globals table is visited by the GC itself (because it mutates the table).
880}
881
882// JNI Invocation interface.
883
884extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
Richard Uhler054a0782015-04-07 10:56:50 -0700885 ATRACE_BEGIN(__FUNCTION__);
Ian Rogers68d8b422014-07-17 11:09:10 -0700886 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
887 if (IsBadJniVersion(args->version)) {
888 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
Richard Uhler054a0782015-04-07 10:56:50 -0700889 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700890 return JNI_EVERSION;
891 }
892 RuntimeOptions options;
893 for (int i = 0; i < args->nOptions; ++i) {
894 JavaVMOption* option = &args->options[i];
895 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
896 }
897 bool ignore_unrecognized = args->ignoreUnrecognized;
898 if (!Runtime::Create(options, ignore_unrecognized)) {
Richard Uhler054a0782015-04-07 10:56:50 -0700899 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700900 return JNI_ERR;
901 }
902 Runtime* runtime = Runtime::Current();
903 bool started = runtime->Start();
904 if (!started) {
905 delete Thread::Current()->GetJniEnv();
906 delete runtime->GetJavaVM();
907 LOG(WARNING) << "CreateJavaVM failed";
Richard Uhler054a0782015-04-07 10:56:50 -0700908 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700909 return JNI_ERR;
910 }
911 *p_env = Thread::Current()->GetJniEnv();
912 *p_vm = runtime->GetJavaVM();
Richard Uhler054a0782015-04-07 10:56:50 -0700913 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700914 return JNI_OK;
915}
916
Ian Rogersf4d4da12014-11-11 16:10:33 -0800917extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700918 Runtime* runtime = Runtime::Current();
Ian Rogersf4d4da12014-11-11 16:10:33 -0800919 if (runtime == nullptr || buf_len == 0) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700920 *vm_count = 0;
921 } else {
922 *vm_count = 1;
Ian Rogersf4d4da12014-11-11 16:10:33 -0800923 vms_buf[0] = runtime->GetJavaVM();
Ian Rogers68d8b422014-07-17 11:09:10 -0700924 }
925 return JNI_OK;
926}
927
928// Historically unsupported.
929extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
930 return JNI_ERR;
931}
932
933} // namespace art