blob: ab70d02349629bd8962d2f2ce2fe5d10d23345a7 [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.
268 if (soa.Decode<mirror::ClassLoader*>(library->GetClassLoader()) == nullptr) {
269 void* const sym = library->FindSymbol("JNI_OnUnload", nullptr);
270 if (sym == nullptr) {
271 VLOG(jni) << "[No JNI_OnUnload found in \"" << library->GetPath() << "\"]";
272 } else {
273 VLOG(jni) << "[JNI_OnUnload found for \"" << library->GetPath() << "\"]";
274 JNI_OnUnloadFn jni_on_unload = reinterpret_cast<JNI_OnUnloadFn>(sym);
275 unload_functions.push_back(jni_on_unload);
276 }
277 delete library;
278 it = libraries_.erase(it);
279 } else {
280 ++it;
281 }
282 }
283 }
284 // Do this without holding the jni libraries lock to prevent possible deadlocks.
285 for (JNI_OnUnloadFn fn : unload_functions) {
286 VLOG(jni) << "Calling JNI_OnUnload";
287 (*fn)(soa.Vm(), nullptr);
288 }
289 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700290
Mathieu Chartier598302a2015-09-23 14:52:39 -0700291 private:
292 AllocationTrackingSafeMap<std::string, SharedLibrary*, kAllocatorTagJNILibraries> libraries_
293 GUARDED_BY(Locks::jni_libraries_lock_);
294};
Ian Rogers68d8b422014-07-17 11:09:10 -0700295
296class JII {
297 public:
298 static jint DestroyJavaVM(JavaVM* vm) {
299 if (vm == nullptr) {
300 return JNI_ERR;
301 }
302 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
303 delete raw_vm->GetRuntime();
304 return JNI_OK;
305 }
306
307 static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
308 return AttachCurrentThreadInternal(vm, p_env, thr_args, false);
309 }
310
311 static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
312 return AttachCurrentThreadInternal(vm, p_env, thr_args, true);
313 }
314
315 static jint DetachCurrentThread(JavaVM* vm) {
316 if (vm == nullptr || Thread::Current() == nullptr) {
317 return JNI_ERR;
318 }
319 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
320 Runtime* runtime = raw_vm->GetRuntime();
321 runtime->DetachCurrentThread();
322 return JNI_OK;
323 }
324
325 static jint GetEnv(JavaVM* vm, void** env, jint version) {
326 // GetEnv always returns a JNIEnv* for the most current supported JNI version,
327 // and unlike other calls that take a JNI version doesn't care if you supply
328 // JNI_VERSION_1_1, which we don't otherwise support.
329 if (IsBadJniVersion(version) && version != JNI_VERSION_1_1) {
330 LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version;
331 return JNI_EVERSION;
332 }
333 if (vm == nullptr || env == nullptr) {
334 return JNI_ERR;
335 }
336 Thread* thread = Thread::Current();
337 if (thread == nullptr) {
338 *env = nullptr;
339 return JNI_EDETACHED;
340 }
341 *env = thread->GetJniEnv();
342 return JNI_OK;
343 }
344
345 private:
346 static jint AttachCurrentThreadInternal(JavaVM* vm, JNIEnv** p_env, void* raw_args, bool as_daemon) {
347 if (vm == nullptr || p_env == nullptr) {
348 return JNI_ERR;
349 }
350
351 // Return immediately if we're already attached.
352 Thread* self = Thread::Current();
353 if (self != nullptr) {
354 *p_env = self->GetJniEnv();
355 return JNI_OK;
356 }
357
358 Runtime* runtime = reinterpret_cast<JavaVMExt*>(vm)->GetRuntime();
359
360 // No threads allowed in zygote mode.
361 if (runtime->IsZygote()) {
362 LOG(ERROR) << "Attempt to attach a thread in the zygote";
363 return JNI_ERR;
364 }
365
366 JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(raw_args);
367 const char* thread_name = nullptr;
368 jobject thread_group = nullptr;
369 if (args != nullptr) {
370 if (IsBadJniVersion(args->version)) {
371 LOG(ERROR) << "Bad JNI version passed to "
372 << (as_daemon ? "AttachCurrentThreadAsDaemon" : "AttachCurrentThread") << ": "
373 << args->version;
374 return JNI_EVERSION;
375 }
376 thread_name = args->name;
377 thread_group = args->group;
378 }
379
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800380 if (!runtime->AttachCurrentThread(thread_name, as_daemon, thread_group,
381 !runtime->IsAotCompiler())) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700382 *p_env = nullptr;
383 return JNI_ERR;
384 } else {
385 *p_env = Thread::Current()->GetJniEnv();
386 return JNI_OK;
387 }
388 }
389};
390
391const JNIInvokeInterface gJniInvokeInterface = {
392 nullptr, // reserved0
393 nullptr, // reserved1
394 nullptr, // reserved2
395 JII::DestroyJavaVM,
396 JII::AttachCurrentThread,
397 JII::DetachCurrentThread,
398 JII::GetEnv,
399 JII::AttachCurrentThreadAsDaemon
400};
401
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800402JavaVMExt::JavaVMExt(Runtime* runtime, const RuntimeArgumentMap& runtime_options)
Ian Rogers68d8b422014-07-17 11:09:10 -0700403 : runtime_(runtime),
404 check_jni_abort_hook_(nullptr),
405 check_jni_abort_hook_data_(nullptr),
406 check_jni_(false), // Initialized properly in the constructor body below.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800407 force_copy_(runtime_options.Exists(RuntimeArgumentMap::JniOptsForceCopy)),
408 tracing_enabled_(runtime_options.Exists(RuntimeArgumentMap::JniTrace)
409 || VLOG_IS_ON(third_party_jni)),
410 trace_(runtime_options.GetOrDefault(RuntimeArgumentMap::JniTrace)),
Ian Rogers68d8b422014-07-17 11:09:10 -0700411 globals_lock_("JNI global reference table lock"),
412 globals_(gGlobalsInitial, gGlobalsMax, kGlobal),
413 libraries_(new Libraries),
414 unchecked_functions_(&gJniInvokeInterface),
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700415 weak_globals_lock_("JNI weak global reference table lock", kJniWeakGlobalsLock),
Ian Rogers68d8b422014-07-17 11:09:10 -0700416 weak_globals_(kWeakGlobalsInitial, kWeakGlobalsMax, kWeakGlobal),
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700417 allow_accessing_weak_globals_(true),
Ian Rogers68d8b422014-07-17 11:09:10 -0700418 weak_globals_add_condition_("weak globals add condition", weak_globals_lock_) {
419 functions = unchecked_functions_;
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800420 SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni));
Ian Rogers68d8b422014-07-17 11:09:10 -0700421}
422
423JavaVMExt::~JavaVMExt() {
424}
425
426void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) {
427 Thread* self = Thread::Current();
428 ScopedObjectAccess soa(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700429 ArtMethod* current_method = self->GetCurrentMethod(nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700430
431 std::ostringstream os;
432 os << "JNI DETECTED ERROR IN APPLICATION: " << msg;
433
434 if (jni_function_name != nullptr) {
435 os << "\n in call to " << jni_function_name;
436 }
437 // TODO: is this useful given that we're about to dump the calling thread's stack?
438 if (current_method != nullptr) {
439 os << "\n from " << PrettyMethod(current_method);
440 }
441 os << "\n";
442 self->Dump(os);
443
444 if (check_jni_abort_hook_ != nullptr) {
445 check_jni_abort_hook_(check_jni_abort_hook_data_, os.str());
446 } else {
447 // Ensure that we get a native stack trace for this thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700448 ScopedThreadSuspension sts(self, kNative);
Ian Rogers68d8b422014-07-17 11:09:10 -0700449 LOG(FATAL) << os.str();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700450 UNREACHABLE();
Ian Rogers68d8b422014-07-17 11:09:10 -0700451 }
452}
453
454void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) {
455 std::string msg;
456 StringAppendV(&msg, fmt, ap);
457 JniAbort(jni_function_name, msg.c_str());
458}
459
460void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) {
461 va_list args;
462 va_start(args, fmt);
463 JniAbortV(jni_function_name, fmt, args);
464 va_end(args);
465}
466
Mathieu Chartiere401d142015-04-22 13:56:20 -0700467bool JavaVMExt::ShouldTrace(ArtMethod* method) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700468 // Fast where no tracing is enabled.
469 if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) {
470 return false;
471 }
472 // Perform checks based on class name.
473 StringPiece class_name(method->GetDeclaringClassDescriptor());
474 if (!trace_.empty() && class_name.find(trace_) != std::string::npos) {
475 return true;
476 }
477 if (!VLOG_IS_ON(third_party_jni)) {
478 return false;
479 }
480 // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
481 // like part of Android.
482 static const char* gBuiltInPrefixes[] = {
483 "Landroid/",
484 "Lcom/android/",
485 "Lcom/google/android/",
486 "Ldalvik/",
487 "Ljava/",
488 "Ljavax/",
489 "Llibcore/",
490 "Lorg/apache/harmony/",
491 };
492 for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) {
493 if (class_name.starts_with(gBuiltInPrefixes[i])) {
494 return false;
495 }
496 }
497 return true;
498}
499
500jobject JavaVMExt::AddGlobalRef(Thread* self, mirror::Object* obj) {
501 // Check for null after decoding the object to handle cleared weak globals.
502 if (obj == nullptr) {
503 return nullptr;
504 }
505 WriterMutexLock mu(self, globals_lock_);
506 IndirectRef ref = globals_.Add(IRT_FIRST_SEGMENT, obj);
507 return reinterpret_cast<jobject>(ref);
508}
509
510jweak JavaVMExt::AddWeakGlobalRef(Thread* self, mirror::Object* obj) {
511 if (obj == nullptr) {
512 return nullptr;
513 }
514 MutexLock mu(self, weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700515 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700516 weak_globals_add_condition_.WaitHoldingLocks(self);
517 }
518 IndirectRef ref = weak_globals_.Add(IRT_FIRST_SEGMENT, obj);
519 return reinterpret_cast<jweak>(ref);
520}
521
522void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
523 if (obj == nullptr) {
524 return;
525 }
526 WriterMutexLock mu(self, globals_lock_);
527 if (!globals_.Remove(IRT_FIRST_SEGMENT, obj)) {
528 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
529 << "failed to find entry";
530 }
531}
532
533void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
534 if (obj == nullptr) {
535 return;
536 }
537 MutexLock mu(self, weak_globals_lock_);
538 if (!weak_globals_.Remove(IRT_FIRST_SEGMENT, obj)) {
539 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
540 << "failed to find entry";
541 }
542}
543
544static void ThreadEnableCheckJni(Thread* thread, void* arg) {
545 bool* check_jni = reinterpret_cast<bool*>(arg);
546 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
547}
548
549bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
550 bool old_check_jni = check_jni_;
551 check_jni_ = enabled;
552 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
553 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
554 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
555 return old_check_jni;
556}
557
558void JavaVMExt::DumpForSigQuit(std::ostream& os) {
559 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
560 if (force_copy_) {
561 os << " (with forcecopy)";
562 }
563 Thread* self = Thread::Current();
564 {
Ian Rogers68d8b422014-07-17 11:09:10 -0700565 ReaderMutexLock mu(self, globals_lock_);
566 os << "; globals=" << globals_.Capacity();
567 }
568 {
569 MutexLock mu(self, weak_globals_lock_);
570 if (weak_globals_.Capacity() > 0) {
571 os << " (plus " << weak_globals_.Capacity() << " weak)";
572 }
573 }
574 os << '\n';
575
576 {
577 MutexLock mu(self, *Locks::jni_libraries_lock_);
578 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
579 }
580}
581
582void JavaVMExt::DisallowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700583 CHECK(!kUseReadBarrier);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700584 Thread* const self = Thread::Current();
585 MutexLock mu(self, weak_globals_lock_);
586 // DisallowNewWeakGlobals is only called by CMS during the pause. It is required to have the
587 // mutator lock exclusively held so that we don't have any threads in the middle of
588 // DecodeWeakGlobal.
589 Locks::mutator_lock_->AssertExclusiveHeld(self);
590 allow_accessing_weak_globals_.StoreSequentiallyConsistent(false);
Ian Rogers68d8b422014-07-17 11:09:10 -0700591}
592
593void JavaVMExt::AllowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700594 CHECK(!kUseReadBarrier);
Ian Rogers68d8b422014-07-17 11:09:10 -0700595 Thread* self = Thread::Current();
596 MutexLock mu(self, weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700597 allow_accessing_weak_globals_.StoreSequentiallyConsistent(true);
Ian Rogers68d8b422014-07-17 11:09:10 -0700598 weak_globals_add_condition_.Broadcast(self);
599}
600
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700601void JavaVMExt::BroadcastForNewWeakGlobals() {
602 CHECK(kUseReadBarrier);
603 Thread* self = Thread::Current();
604 MutexLock mu(self, weak_globals_lock_);
605 weak_globals_add_condition_.Broadcast(self);
606}
607
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700608mirror::Object* JavaVMExt::DecodeGlobal(IndirectRef ref) {
609 return globals_.SynchronizedGet(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700610}
611
Jeff Hao83c81952015-05-27 19:29:29 -0700612void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, mirror::Object* result) {
613 WriterMutexLock mu(self, globals_lock_);
614 globals_.Update(ref, result);
615}
616
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700617inline bool JavaVMExt::MayAccessWeakGlobals(Thread* self) const {
618 return MayAccessWeakGlobalsUnlocked(self);
619}
620
621inline bool JavaVMExt::MayAccessWeakGlobalsUnlocked(Thread* self) const {
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700622 DCHECK(self != nullptr);
623 return kUseReadBarrier ?
624 self->GetWeakRefAccessEnabled() :
625 allow_accessing_weak_globals_.LoadSequentiallyConsistent();
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700626}
627
Ian Rogers68d8b422014-07-17 11:09:10 -0700628mirror::Object* JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700629 // It is safe to access GetWeakRefAccessEnabled without the lock since CC uses checkpoints to call
630 // SetWeakRefAccessEnabled, and the other collectors only modify allow_accessing_weak_globals_
631 // when the mutators are paused.
632 // This only applies in the case where MayAccessWeakGlobals goes from false to true. In the other
633 // case, it may be racy, this is benign since DecodeWeakGlobalLocked does the correct behavior
634 // if MayAccessWeakGlobals is false.
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -0700635 DCHECK_EQ(GetIndirectRefKind(ref), kWeakGlobal);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700636 if (LIKELY(MayAccessWeakGlobalsUnlocked(self))) {
637 return weak_globals_.SynchronizedGet(ref);
638 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700639 MutexLock mu(self, weak_globals_lock_);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700640 return DecodeWeakGlobalLocked(self, ref);
641}
642
643mirror::Object* JavaVMExt::DecodeWeakGlobalLocked(Thread* self, IndirectRef ref) {
644 if (kDebugLocking) {
645 weak_globals_lock_.AssertHeld(self);
646 }
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700647 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700648 weak_globals_add_condition_.WaitHoldingLocks(self);
649 }
650 return weak_globals_.Get(ref);
651}
652
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700653mirror::Object* JavaVMExt::DecodeWeakGlobalDuringShutdown(Thread* self, IndirectRef ref) {
654 DCHECK_EQ(GetIndirectRefKind(ref), kWeakGlobal);
655 DCHECK(Runtime::Current()->IsShuttingDown(self));
656 if (self != nullptr) {
657 return DecodeWeakGlobal(self, ref);
658 }
659 // self can be null during a runtime shutdown. ~Runtime()->~ClassLinker()->DecodeWeakGlobal().
660 if (!kUseReadBarrier) {
661 DCHECK(allow_accessing_weak_globals_.LoadSequentiallyConsistent());
662 }
663 return weak_globals_.SynchronizedGet(ref);
664}
665
Jeff Hao83c81952015-05-27 19:29:29 -0700666void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, mirror::Object* result) {
667 MutexLock mu(self, weak_globals_lock_);
668 weak_globals_.Update(ref, result);
669}
670
Ian Rogers68d8b422014-07-17 11:09:10 -0700671void JavaVMExt::DumpReferenceTables(std::ostream& os) {
672 Thread* self = Thread::Current();
673 {
674 ReaderMutexLock mu(self, globals_lock_);
675 globals_.Dump(os);
676 }
677 {
678 MutexLock mu(self, weak_globals_lock_);
679 weak_globals_.Dump(os);
680 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700681}
682
Mathieu Chartier598302a2015-09-23 14:52:39 -0700683void JavaVMExt::UnloadNativeLibraries() {
684 libraries_.get()->UnloadNativeLibraries();
685}
686
Ian Rogers68d8b422014-07-17 11:09:10 -0700687bool JavaVMExt::LoadNativeLibrary(JNIEnv* env, const std::string& path, jobject class_loader,
688 std::string* error_msg) {
689 error_msg->clear();
690
691 // See if we've already loaded this library. If we have, and the class loader
692 // matches, return successfully without doing anything.
693 // TODO: for better results we should canonicalize the pathname (or even compare
694 // inodes). This implementation is fine if everybody is using System.loadLibrary.
695 SharedLibrary* library;
696 Thread* self = Thread::Current();
697 {
698 // TODO: move the locking (and more of this logic) into Libraries.
699 MutexLock mu(self, *Locks::jni_libraries_lock_);
700 library = libraries_->Get(path);
701 }
702 if (library != nullptr) {
703 if (env->IsSameObject(library->GetClassLoader(), class_loader) == JNI_FALSE) {
704 // The library will be associated with class_loader. The JNI
705 // spec says we can't load the same library into more than one
706 // class loader.
707 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
708 "ClassLoader %p; can't open in ClassLoader %p",
709 path.c_str(), library->GetClassLoader(), class_loader);
710 LOG(WARNING) << error_msg;
711 return false;
712 }
713 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
714 << " ClassLoader " << class_loader << "]";
715 if (!library->CheckOnLoadResult()) {
716 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
717 "to load \"%s\"", path.c_str());
718 return false;
719 }
720 return true;
721 }
722
723 // Open the shared library. Because we're using a full path, the system
724 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
725 // resolve this library's dependencies though.)
726
727 // Failures here are expected when java.library.path has several entries
728 // and we have to hunt for the lib.
729
730 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
731 // class unloading. Libraries will only be unloaded when the reference count (incremented by
732 // dlopen) becomes zero from dlclose.
733
734 Locks::mutator_lock_->AssertNotHeld(self);
735 const char* path_str = path.empty() ? nullptr : path.c_str();
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700736 void* handle = dlopen(path_str, RTLD_NOW);
Ian Rogers68d8b422014-07-17 11:09:10 -0700737 bool needs_native_bridge = false;
738 if (handle == nullptr) {
Calin Juravlec8423522014-08-12 20:55:20 +0100739 if (android::NativeBridgeIsSupported(path_str)) {
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700740 handle = android::NativeBridgeLoadLibrary(path_str, RTLD_NOW);
Ian Rogers68d8b422014-07-17 11:09:10 -0700741 needs_native_bridge = true;
742 }
743 }
744
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700745 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]";
Ian Rogers68d8b422014-07-17 11:09:10 -0700746
747 if (handle == nullptr) {
748 *error_msg = dlerror();
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700749 VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700750 return false;
751 }
752
753 if (env->ExceptionCheck() == JNI_TRUE) {
754 LOG(ERROR) << "Unexpected exception:";
755 env->ExceptionDescribe();
756 env->ExceptionClear();
757 }
758 // Create a new entry.
759 // TODO: move the locking (and more of this logic) into Libraries.
760 bool created_library = false;
761 {
762 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
763 std::unique_ptr<SharedLibrary> new_library(
764 new SharedLibrary(env, self, path, handle, class_loader));
765 MutexLock mu(self, *Locks::jni_libraries_lock_);
766 library = libraries_->Get(path);
767 if (library == nullptr) { // We won race to get libraries_lock.
768 library = new_library.release();
769 libraries_->Put(path, library);
770 created_library = true;
771 }
772 }
773 if (!created_library) {
774 LOG(INFO) << "WOW: we lost a race to add shared library: "
775 << "\"" << path << "\" ClassLoader=" << class_loader;
776 return library->CheckOnLoadResult();
777 }
778 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
779
780 bool was_successful = false;
781 void* sym;
782 if (needs_native_bridge) {
783 library->SetNeedsNativeBridge();
Ian Rogers68d8b422014-07-17 11:09:10 -0700784 }
Mathieu Chartier598302a2015-09-23 14:52:39 -0700785 sym = library->FindSymbol("JNI_OnLoad", nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700786 if (sym == nullptr) {
787 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
788 was_successful = true;
789 } else {
790 // Call JNI_OnLoad. We have to override the current class
791 // loader, which will always be "null" since the stuff at the
792 // top of the stack is around Runtime.loadLibrary(). (See
793 // the comments in the JNI FindClass function.)
794 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
795 self->SetClassLoaderOverride(class_loader);
796
797 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
798 typedef int (*JNI_OnLoadFn)(JavaVM*, void*);
799 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
800 int version = (*jni_on_load)(this, nullptr);
801
Mathieu Chartierd0004802014-10-15 16:59:47 -0700802 if (runtime_->GetTargetSdkVersion() != 0 && runtime_->GetTargetSdkVersion() <= 21) {
803 fault_manager.EnsureArtActionInFrontOfSignalChain();
804 }
805
Ian Rogers68d8b422014-07-17 11:09:10 -0700806 self->SetClassLoaderOverride(old_class_loader.get());
807
808 if (version == JNI_ERR) {
809 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
810 } else if (IsBadJniVersion(version)) {
811 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
812 path.c_str(), version);
813 // It's unwise to call dlclose() here, but we can mark it
814 // as bad and ensure that future load attempts will fail.
815 // We don't know how far JNI_OnLoad got, so there could
816 // be some partially-initialized stuff accessible through
817 // newly-registered native method calls. We could try to
818 // unregister them, but that doesn't seem worthwhile.
819 } else {
820 was_successful = true;
821 }
822 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
823 << " from JNI_OnLoad in \"" << path << "\"]";
824 }
825
826 library->SetResult(was_successful);
827 return was_successful;
828}
829
Mathieu Chartiere401d142015-04-22 13:56:20 -0700830void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700831 CHECK(m->IsNative());
832 mirror::Class* c = m->GetDeclaringClass();
833 // If this is a static method, it could be called before the class has been initialized.
834 CHECK(c->IsInitializing()) << c->GetStatus() << " " << PrettyMethod(m);
835 std::string detail;
836 void* native_method;
837 Thread* self = Thread::Current();
838 {
839 MutexLock mu(self, *Locks::jni_libraries_lock_);
840 native_method = libraries_->FindNativeMethod(m, detail);
841 }
842 // Throwing can cause libraries_lock to be reacquired.
843 if (native_method == nullptr) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000844 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
Ian Rogers68d8b422014-07-17 11:09:10 -0700845 }
846 return native_method;
847}
848
Mathieu Chartier97509952015-07-13 14:35:43 -0700849void JavaVMExt::SweepJniWeakGlobals(IsMarkedVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700850 MutexLock mu(Thread::Current(), weak_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700851 Runtime* const runtime = Runtime::Current();
852 for (auto* entry : weak_globals_) {
853 // Need to skip null here to distinguish between null entries and cleared weak ref entries.
854 if (!entry->IsNull()) {
855 // Since this is called by the GC, we don't need a read barrier.
856 mirror::Object* obj = entry->Read<kWithoutReadBarrier>();
Mathieu Chartier97509952015-07-13 14:35:43 -0700857 mirror::Object* new_obj = visitor->IsMarked(obj);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700858 if (new_obj == nullptr) {
859 new_obj = runtime->GetClearedJniWeakGlobal();
860 }
861 *entry = GcRoot<mirror::Object>(new_obj);
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -0700862 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700863 }
864}
865
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800866void JavaVMExt::TrimGlobals() {
867 WriterMutexLock mu(Thread::Current(), globals_lock_);
868 globals_.Trim();
869}
870
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700871void JavaVMExt::VisitRoots(RootVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700872 Thread* self = Thread::Current();
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800873 ReaderMutexLock mu(self, globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700874 globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal));
Ian Rogers68d8b422014-07-17 11:09:10 -0700875 // The weak_globals table is visited by the GC itself (because it mutates the table).
876}
877
878// JNI Invocation interface.
879
880extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
Richard Uhler054a0782015-04-07 10:56:50 -0700881 ATRACE_BEGIN(__FUNCTION__);
Ian Rogers68d8b422014-07-17 11:09:10 -0700882 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
883 if (IsBadJniVersion(args->version)) {
884 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
Richard Uhler054a0782015-04-07 10:56:50 -0700885 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700886 return JNI_EVERSION;
887 }
888 RuntimeOptions options;
889 for (int i = 0; i < args->nOptions; ++i) {
890 JavaVMOption* option = &args->options[i];
891 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
892 }
893 bool ignore_unrecognized = args->ignoreUnrecognized;
894 if (!Runtime::Create(options, ignore_unrecognized)) {
Richard Uhler054a0782015-04-07 10:56:50 -0700895 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700896 return JNI_ERR;
897 }
898 Runtime* runtime = Runtime::Current();
899 bool started = runtime->Start();
900 if (!started) {
901 delete Thread::Current()->GetJniEnv();
902 delete runtime->GetJavaVM();
903 LOG(WARNING) << "CreateJavaVM failed";
Richard Uhler054a0782015-04-07 10:56:50 -0700904 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700905 return JNI_ERR;
906 }
907 *p_env = Thread::Current()->GetJniEnv();
908 *p_vm = runtime->GetJavaVM();
Richard Uhler054a0782015-04-07 10:56:50 -0700909 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700910 return JNI_OK;
911}
912
Ian Rogersf4d4da12014-11-11 16:10:33 -0800913extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700914 Runtime* runtime = Runtime::Current();
Ian Rogersf4d4da12014-11-11 16:10:33 -0800915 if (runtime == nullptr || buf_len == 0) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700916 *vm_count = 0;
917 } else {
918 *vm_count = 1;
Ian Rogersf4d4da12014-11-11 16:10:33 -0800919 vms_buf[0] = runtime->GetJavaVM();
Ian Rogers68d8b422014-07-17 11:09:10 -0700920 }
921 return JNI_OK;
922}
923
924// Historically unsupported.
925extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
926 return JNI_ERR;
927}
928
929} // namespace art