blob: eebcc689c911db24cb9737c0ad081cb0ff2bb3fa [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
19#include <dlfcn.h>
20
Mathieu Chartiere401d142015-04-22 13:56:20 -070021#include "art_method.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070022#include "base/dumpable.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070023#include "base/mutex.h"
24#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080025#include "base/systrace.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070026#include "check_jni.h"
Elliott Hughes956af0f2014-12-11 14:34:28 -080027#include "dex_file-inl.h"
Mathieu Chartierd0004802014-10-15 16:59:47 -070028#include "fault_handler.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070029#include "indirect_reference_table-inl.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070030#include "mirror/class-inl.h"
31#include "mirror/class_loader.h"
Calin Juravlec8423522014-08-12 20:55:20 +010032#include "nativebridge/native_bridge.h"
Dmitriy Ivanovf5a30992015-11-11 14:18:55 -080033#include "nativeloader/native_loader.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,
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080059 jobject class_loader, void* class_loader_allocator)
Ian Rogers68d8b422014-07-17 11:09:10 -070060 : path_(path),
61 handle_(handle),
62 needs_native_bridge_(false),
Mathieu Chartier598302a2015-09-23 14:52:39 -070063 class_loader_(env->NewWeakGlobalRef(class_loader)),
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080064 class_loader_allocator_(class_loader_allocator),
Ian Rogers68d8b422014-07-17 11:09:10 -070065 jni_on_load_lock_("JNI_OnLoad lock"),
66 jni_on_load_cond_("JNI_OnLoad condition variable", jni_on_load_lock_),
67 jni_on_load_thread_id_(self->GetThreadId()),
68 jni_on_load_result_(kPending) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080069 CHECK(class_loader_allocator_ != nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -070070 }
71
72 ~SharedLibrary() {
73 Thread* self = Thread::Current();
74 if (self != nullptr) {
Mathieu Chartier598302a2015-09-23 14:52:39 -070075 self->GetJniEnv()->DeleteWeakGlobalRef(class_loader_);
Ian Rogers68d8b422014-07-17 11:09:10 -070076 }
Dimitry Ivanov2eb3ba92016-05-03 15:05:41 -070077
78 if (!needs_native_bridge_) {
79 android::CloseNativeLibrary(handle_);
80 }
Ian Rogers68d8b422014-07-17 11:09:10 -070081 }
82
Mathieu Chartier598302a2015-09-23 14:52:39 -070083 jweak GetClassLoader() const {
Ian Rogers68d8b422014-07-17 11:09:10 -070084 return class_loader_;
85 }
86
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080087 const void* GetClassLoaderAllocator() const {
88 return class_loader_allocator_;
89 }
90
Ian Rogers68d8b422014-07-17 11:09:10 -070091 const std::string& GetPath() const {
92 return path_;
93 }
94
95 /*
96 * Check the result of an earlier call to JNI_OnLoad on this library.
97 * If the call has not yet finished in another thread, wait for it.
98 */
99 bool CheckOnLoadResult()
Mathieu Chartier90443472015-07-16 20:32:27 -0700100 REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700101 Thread* self = Thread::Current();
102 bool okay;
103 {
104 MutexLock mu(self, jni_on_load_lock_);
105
106 if (jni_on_load_thread_id_ == self->GetThreadId()) {
107 // Check this so we don't end up waiting for ourselves. We need to return "true" so the
108 // caller can continue.
109 LOG(INFO) << *self << " recursive attempt to load library " << "\"" << path_ << "\"";
110 okay = true;
111 } else {
112 while (jni_on_load_result_ == kPending) {
113 VLOG(jni) << "[" << *self << " waiting for \"" << path_ << "\" " << "JNI_OnLoad...]";
114 jni_on_load_cond_.Wait(self);
115 }
116
117 okay = (jni_on_load_result_ == kOkay);
118 VLOG(jni) << "[Earlier JNI_OnLoad for \"" << path_ << "\" "
119 << (okay ? "succeeded" : "failed") << "]";
120 }
121 }
122 return okay;
123 }
124
Mathieu Chartier90443472015-07-16 20:32:27 -0700125 void SetResult(bool result) REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700126 Thread* self = Thread::Current();
127 MutexLock mu(self, jni_on_load_lock_);
128
129 jni_on_load_result_ = result ? kOkay : kFailed;
130 jni_on_load_thread_id_ = 0;
131
132 // Broadcast a wakeup to anybody sleeping on the condition variable.
133 jni_on_load_cond_.Broadcast(self);
134 }
135
136 void SetNeedsNativeBridge() {
137 needs_native_bridge_ = true;
138 }
139
140 bool NeedsNativeBridge() const {
141 return needs_native_bridge_;
142 }
143
Mathieu Chartier598302a2015-09-23 14:52:39 -0700144 void* FindSymbol(const std::string& symbol_name, const char* shorty = nullptr) {
145 return NeedsNativeBridge()
146 ? FindSymbolWithNativeBridge(symbol_name.c_str(), shorty)
147 : FindSymbolWithoutNativeBridge(symbol_name.c_str());
148 }
149
150 void* FindSymbolWithoutNativeBridge(const std::string& symbol_name) {
Andreas Gampe8fec90b2015-06-30 11:23:44 -0700151 CHECK(!NeedsNativeBridge());
152
Ian Rogers68d8b422014-07-17 11:09:10 -0700153 return dlsym(handle_, symbol_name.c_str());
154 }
155
156 void* FindSymbolWithNativeBridge(const std::string& symbol_name, const char* shorty) {
157 CHECK(NeedsNativeBridge());
158
159 uint32_t len = 0;
Calin Juravlec8423522014-08-12 20:55:20 +0100160 return android::NativeBridgeGetTrampoline(handle_, symbol_name.c_str(), shorty, len);
Ian Rogers68d8b422014-07-17 11:09:10 -0700161 }
162
163 private:
164 enum JNI_OnLoadState {
165 kPending,
166 kFailed,
167 kOkay,
168 };
169
170 // Path to library "/system/lib/libjni.so".
171 const std::string path_;
172
173 // The void* returned by dlopen(3).
174 void* const handle_;
175
176 // True if a native bridge is required.
177 bool needs_native_bridge_;
178
Mathieu Chartier598302a2015-09-23 14:52:39 -0700179 // The ClassLoader this library is associated with, a weak global JNI reference that is
Ian Rogers68d8b422014-07-17 11:09:10 -0700180 // created/deleted with the scope of the library.
Mathieu Chartier598302a2015-09-23 14:52:39 -0700181 const jweak class_loader_;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800182 // Used to do equality check on class loaders so we can avoid decoding the weak root and read
183 // barriers that mess with class unloading.
184 const void* class_loader_allocator_;
Ian Rogers68d8b422014-07-17 11:09:10 -0700185
186 // Guards remaining items.
187 Mutex jni_on_load_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
188 // Wait for JNI_OnLoad in other thread.
189 ConditionVariable jni_on_load_cond_ GUARDED_BY(jni_on_load_lock_);
190 // Recursive invocation guard.
191 uint32_t jni_on_load_thread_id_ GUARDED_BY(jni_on_load_lock_);
192 // Result of earlier JNI_OnLoad call.
193 JNI_OnLoadState jni_on_load_result_ GUARDED_BY(jni_on_load_lock_);
194};
195
196// This exists mainly to keep implementation details out of the header file.
197class Libraries {
198 public:
199 Libraries() {
200 }
201
202 ~Libraries() {
203 STLDeleteValues(&libraries_);
204 }
205
Mathieu Chartier598302a2015-09-23 14:52:39 -0700206 // NO_THREAD_SAFETY_ANALYSIS since this may be called from Dumpable. Dumpable can't be annotated
207 // properly due to the template. The caller should be holding the jni_libraries_lock_.
208 void Dump(std::ostream& os) const NO_THREAD_SAFETY_ANALYSIS {
209 Locks::jni_libraries_lock_->AssertHeld(Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -0700210 bool first = true;
211 for (const auto& library : libraries_) {
212 if (!first) {
213 os << ' ';
214 }
215 first = false;
216 os << library.first;
217 }
218 }
219
Mathieu Chartier598302a2015-09-23 14:52:39 -0700220 size_t size() const REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700221 return libraries_.size();
222 }
223
Mathieu Chartier598302a2015-09-23 14:52:39 -0700224 SharedLibrary* Get(const std::string& path) REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700225 auto it = libraries_.find(path);
226 return (it == libraries_.end()) ? nullptr : it->second;
227 }
228
Mathieu Chartier598302a2015-09-23 14:52:39 -0700229 void Put(const std::string& path, SharedLibrary* library)
230 REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700231 libraries_.Put(path, library);
232 }
233
234 // See section 11.3 "Linking Native Methods" of the JNI spec.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700235 void* FindNativeMethod(ArtMethod* m, std::string& detail)
Mathieu Chartier90443472015-07-16 20:32:27 -0700236 REQUIRES(Locks::jni_libraries_lock_)
237 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700238 std::string jni_short_name(JniShortName(m));
239 std::string jni_long_name(JniLongName(m));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800240 mirror::ClassLoader* const declaring_class_loader = m->GetDeclaringClass()->GetClassLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700241 ScopedObjectAccessUnchecked soa(Thread::Current());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800242 void* const declaring_class_loader_allocator =
243 Runtime::Current()->GetClassLinker()->GetAllocatorForClassLoader(declaring_class_loader);
244 CHECK(declaring_class_loader_allocator != nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700245 for (const auto& lib : libraries_) {
Mathieu Chartier598302a2015-09-23 14:52:39 -0700246 SharedLibrary* const library = lib.second;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800247 // Use the allocator address for class loader equality to avoid unnecessary weak root decode.
248 if (library->GetClassLoaderAllocator() != declaring_class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700249 // We only search libraries loaded by the appropriate ClassLoader.
250 continue;
251 }
252 // Try the short name then the long name...
Mathieu Chartier598302a2015-09-23 14:52:39 -0700253 const char* shorty = library->NeedsNativeBridge()
254 ? m->GetShorty()
255 : nullptr;
256 void* fn = library->FindSymbol(jni_short_name, shorty);
257 if (fn == nullptr) {
258 fn = library->FindSymbol(jni_long_name, shorty);
Ian Rogers68d8b422014-07-17 11:09:10 -0700259 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700260 if (fn != nullptr) {
261 VLOG(jni) << "[Found native code for " << PrettyMethod(m)
262 << " in \"" << library->GetPath() << "\"]";
263 return fn;
264 }
265 }
266 detail += "No implementation found for ";
267 detail += PrettyMethod(m);
268 detail += " (tried " + jni_short_name + " and " + jni_long_name + ")";
269 LOG(ERROR) << detail;
270 return nullptr;
271 }
272
Mathieu Chartier598302a2015-09-23 14:52:39 -0700273 // Unload native libraries with cleared class loaders.
274 void UnloadNativeLibraries()
275 REQUIRES(!Locks::jni_libraries_lock_)
276 SHARED_REQUIRES(Locks::mutator_lock_) {
277 ScopedObjectAccessUnchecked soa(Thread::Current());
Dimitry Ivanov2eb3ba92016-05-03 15:05:41 -0700278 std::vector<SharedLibrary*> unload_libraries;
Mathieu Chartier598302a2015-09-23 14:52:39 -0700279 {
280 MutexLock mu(soa.Self(), *Locks::jni_libraries_lock_);
281 for (auto it = libraries_.begin(); it != libraries_.end(); ) {
282 SharedLibrary* const library = it->second;
283 // If class loader is null then it was unloaded, call JNI_OnUnload.
Mathieu Chartiercffb7472015-09-28 10:33:00 -0700284 const jweak class_loader = library->GetClassLoader();
285 // If class_loader is a null jobject then it is the boot class loader. We should not unload
286 // the native libraries of the boot class loader.
287 if (class_loader != nullptr &&
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800288 soa.Self()->IsJWeakCleared(class_loader)) {
Dimitry Ivanov2eb3ba92016-05-03 15:05:41 -0700289 unload_libraries.push_back(library);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700290 it = libraries_.erase(it);
291 } else {
292 ++it;
293 }
294 }
295 }
296 // Do this without holding the jni libraries lock to prevent possible deadlocks.
Dimitry Ivanov2eb3ba92016-05-03 15:05:41 -0700297 typedef void (*JNI_OnUnloadFn)(JavaVM*, void*);
298 for (auto library : unload_libraries) {
299 void* const sym = library->FindSymbol("JNI_OnUnload", nullptr);
300 if (sym == nullptr) {
301 VLOG(jni) << "[No JNI_OnUnload found in \"" << library->GetPath() << "\"]";
302 } else {
303 VLOG(jni) << "[JNI_OnUnload found for \"" << library->GetPath() << "\"]: Calling...";
304 JNI_OnUnloadFn jni_on_unload = reinterpret_cast<JNI_OnUnloadFn>(sym);
305 jni_on_unload(soa.Vm(), nullptr);
306 }
307 delete library;
Mathieu Chartier598302a2015-09-23 14:52:39 -0700308 }
309 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700310
Mathieu Chartier598302a2015-09-23 14:52:39 -0700311 private:
312 AllocationTrackingSafeMap<std::string, SharedLibrary*, kAllocatorTagJNILibraries> libraries_
313 GUARDED_BY(Locks::jni_libraries_lock_);
314};
Ian Rogers68d8b422014-07-17 11:09:10 -0700315
316class JII {
317 public:
318 static jint DestroyJavaVM(JavaVM* vm) {
319 if (vm == nullptr) {
320 return JNI_ERR;
321 }
322 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
323 delete raw_vm->GetRuntime();
324 return JNI_OK;
325 }
326
327 static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
328 return AttachCurrentThreadInternal(vm, p_env, thr_args, false);
329 }
330
331 static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
332 return AttachCurrentThreadInternal(vm, p_env, thr_args, true);
333 }
334
335 static jint DetachCurrentThread(JavaVM* vm) {
336 if (vm == nullptr || Thread::Current() == nullptr) {
337 return JNI_ERR;
338 }
339 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
340 Runtime* runtime = raw_vm->GetRuntime();
341 runtime->DetachCurrentThread();
342 return JNI_OK;
343 }
344
345 static jint GetEnv(JavaVM* vm, void** env, jint version) {
346 // GetEnv always returns a JNIEnv* for the most current supported JNI version,
347 // and unlike other calls that take a JNI version doesn't care if you supply
348 // JNI_VERSION_1_1, which we don't otherwise support.
349 if (IsBadJniVersion(version) && version != JNI_VERSION_1_1) {
350 LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version;
351 return JNI_EVERSION;
352 }
353 if (vm == nullptr || env == nullptr) {
354 return JNI_ERR;
355 }
356 Thread* thread = Thread::Current();
357 if (thread == nullptr) {
358 *env = nullptr;
359 return JNI_EDETACHED;
360 }
361 *env = thread->GetJniEnv();
362 return JNI_OK;
363 }
364
365 private:
366 static jint AttachCurrentThreadInternal(JavaVM* vm, JNIEnv** p_env, void* raw_args, bool as_daemon) {
367 if (vm == nullptr || p_env == nullptr) {
368 return JNI_ERR;
369 }
370
371 // Return immediately if we're already attached.
372 Thread* self = Thread::Current();
373 if (self != nullptr) {
374 *p_env = self->GetJniEnv();
375 return JNI_OK;
376 }
377
378 Runtime* runtime = reinterpret_cast<JavaVMExt*>(vm)->GetRuntime();
379
380 // No threads allowed in zygote mode.
381 if (runtime->IsZygote()) {
382 LOG(ERROR) << "Attempt to attach a thread in the zygote";
383 return JNI_ERR;
384 }
385
386 JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(raw_args);
387 const char* thread_name = nullptr;
388 jobject thread_group = nullptr;
389 if (args != nullptr) {
390 if (IsBadJniVersion(args->version)) {
391 LOG(ERROR) << "Bad JNI version passed to "
392 << (as_daemon ? "AttachCurrentThreadAsDaemon" : "AttachCurrentThread") << ": "
393 << args->version;
394 return JNI_EVERSION;
395 }
396 thread_name = args->name;
397 thread_group = args->group;
398 }
399
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800400 if (!runtime->AttachCurrentThread(thread_name, as_daemon, thread_group,
401 !runtime->IsAotCompiler())) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700402 *p_env = nullptr;
403 return JNI_ERR;
404 } else {
405 *p_env = Thread::Current()->GetJniEnv();
406 return JNI_OK;
407 }
408 }
409};
410
411const JNIInvokeInterface gJniInvokeInterface = {
412 nullptr, // reserved0
413 nullptr, // reserved1
414 nullptr, // reserved2
415 JII::DestroyJavaVM,
416 JII::AttachCurrentThread,
417 JII::DetachCurrentThread,
418 JII::GetEnv,
419 JII::AttachCurrentThreadAsDaemon
420};
421
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800422JavaVMExt::JavaVMExt(Runtime* runtime, const RuntimeArgumentMap& runtime_options)
Ian Rogers68d8b422014-07-17 11:09:10 -0700423 : runtime_(runtime),
424 check_jni_abort_hook_(nullptr),
425 check_jni_abort_hook_data_(nullptr),
426 check_jni_(false), // Initialized properly in the constructor body below.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800427 force_copy_(runtime_options.Exists(RuntimeArgumentMap::JniOptsForceCopy)),
428 tracing_enabled_(runtime_options.Exists(RuntimeArgumentMap::JniTrace)
429 || VLOG_IS_ON(third_party_jni)),
430 trace_(runtime_options.GetOrDefault(RuntimeArgumentMap::JniTrace)),
Ian Rogers68d8b422014-07-17 11:09:10 -0700431 globals_lock_("JNI global reference table lock"),
432 globals_(gGlobalsInitial, gGlobalsMax, kGlobal),
433 libraries_(new Libraries),
434 unchecked_functions_(&gJniInvokeInterface),
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700435 weak_globals_lock_("JNI weak global reference table lock", kJniWeakGlobalsLock),
Ian Rogers68d8b422014-07-17 11:09:10 -0700436 weak_globals_(kWeakGlobalsInitial, kWeakGlobalsMax, kWeakGlobal),
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700437 allow_accessing_weak_globals_(true),
Ian Rogers68d8b422014-07-17 11:09:10 -0700438 weak_globals_add_condition_("weak globals add condition", weak_globals_lock_) {
439 functions = unchecked_functions_;
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800440 SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni));
Ian Rogers68d8b422014-07-17 11:09:10 -0700441}
442
443JavaVMExt::~JavaVMExt() {
444}
445
446void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) {
447 Thread* self = Thread::Current();
448 ScopedObjectAccess soa(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700449 ArtMethod* current_method = self->GetCurrentMethod(nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700450
451 std::ostringstream os;
452 os << "JNI DETECTED ERROR IN APPLICATION: " << msg;
453
454 if (jni_function_name != nullptr) {
455 os << "\n in call to " << jni_function_name;
456 }
457 // TODO: is this useful given that we're about to dump the calling thread's stack?
458 if (current_method != nullptr) {
459 os << "\n from " << PrettyMethod(current_method);
460 }
461 os << "\n";
462 self->Dump(os);
463
464 if (check_jni_abort_hook_ != nullptr) {
465 check_jni_abort_hook_(check_jni_abort_hook_data_, os.str());
466 } else {
467 // Ensure that we get a native stack trace for this thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700468 ScopedThreadSuspension sts(self, kNative);
Ian Rogers68d8b422014-07-17 11:09:10 -0700469 LOG(FATAL) << os.str();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700470 UNREACHABLE();
Ian Rogers68d8b422014-07-17 11:09:10 -0700471 }
472}
473
474void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) {
475 std::string msg;
476 StringAppendV(&msg, fmt, ap);
477 JniAbort(jni_function_name, msg.c_str());
478}
479
480void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) {
481 va_list args;
482 va_start(args, fmt);
483 JniAbortV(jni_function_name, fmt, args);
484 va_end(args);
485}
486
Mathieu Chartiere401d142015-04-22 13:56:20 -0700487bool JavaVMExt::ShouldTrace(ArtMethod* method) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700488 // Fast where no tracing is enabled.
489 if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) {
490 return false;
491 }
492 // Perform checks based on class name.
493 StringPiece class_name(method->GetDeclaringClassDescriptor());
494 if (!trace_.empty() && class_name.find(trace_) != std::string::npos) {
495 return true;
496 }
497 if (!VLOG_IS_ON(third_party_jni)) {
498 return false;
499 }
500 // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
501 // like part of Android.
502 static const char* gBuiltInPrefixes[] = {
503 "Landroid/",
504 "Lcom/android/",
505 "Lcom/google/android/",
506 "Ldalvik/",
507 "Ljava/",
508 "Ljavax/",
509 "Llibcore/",
510 "Lorg/apache/harmony/",
511 };
512 for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) {
513 if (class_name.starts_with(gBuiltInPrefixes[i])) {
514 return false;
515 }
516 }
517 return true;
518}
519
520jobject JavaVMExt::AddGlobalRef(Thread* self, mirror::Object* obj) {
521 // Check for null after decoding the object to handle cleared weak globals.
522 if (obj == nullptr) {
523 return nullptr;
524 }
525 WriterMutexLock mu(self, globals_lock_);
526 IndirectRef ref = globals_.Add(IRT_FIRST_SEGMENT, obj);
527 return reinterpret_cast<jobject>(ref);
528}
529
530jweak JavaVMExt::AddWeakGlobalRef(Thread* self, mirror::Object* obj) {
531 if (obj == nullptr) {
532 return nullptr;
533 }
534 MutexLock mu(self, weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700535 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700536 weak_globals_add_condition_.WaitHoldingLocks(self);
537 }
538 IndirectRef ref = weak_globals_.Add(IRT_FIRST_SEGMENT, obj);
539 return reinterpret_cast<jweak>(ref);
540}
541
542void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
543 if (obj == nullptr) {
544 return;
545 }
546 WriterMutexLock mu(self, globals_lock_);
547 if (!globals_.Remove(IRT_FIRST_SEGMENT, obj)) {
548 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
549 << "failed to find entry";
550 }
551}
552
553void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
554 if (obj == nullptr) {
555 return;
556 }
557 MutexLock mu(self, weak_globals_lock_);
558 if (!weak_globals_.Remove(IRT_FIRST_SEGMENT, obj)) {
559 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
560 << "failed to find entry";
561 }
562}
563
564static void ThreadEnableCheckJni(Thread* thread, void* arg) {
565 bool* check_jni = reinterpret_cast<bool*>(arg);
566 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
567}
568
569bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
570 bool old_check_jni = check_jni_;
571 check_jni_ = enabled;
572 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
573 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
574 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
575 return old_check_jni;
576}
577
578void JavaVMExt::DumpForSigQuit(std::ostream& os) {
579 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
580 if (force_copy_) {
581 os << " (with forcecopy)";
582 }
583 Thread* self = Thread::Current();
584 {
Ian Rogers68d8b422014-07-17 11:09:10 -0700585 ReaderMutexLock mu(self, globals_lock_);
586 os << "; globals=" << globals_.Capacity();
587 }
588 {
589 MutexLock mu(self, weak_globals_lock_);
590 if (weak_globals_.Capacity() > 0) {
591 os << " (plus " << weak_globals_.Capacity() << " weak)";
592 }
593 }
594 os << '\n';
595
596 {
597 MutexLock mu(self, *Locks::jni_libraries_lock_);
598 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
599 }
600}
601
602void JavaVMExt::DisallowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700603 CHECK(!kUseReadBarrier);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700604 Thread* const self = Thread::Current();
605 MutexLock mu(self, weak_globals_lock_);
606 // DisallowNewWeakGlobals is only called by CMS during the pause. It is required to have the
607 // mutator lock exclusively held so that we don't have any threads in the middle of
608 // DecodeWeakGlobal.
609 Locks::mutator_lock_->AssertExclusiveHeld(self);
610 allow_accessing_weak_globals_.StoreSequentiallyConsistent(false);
Ian Rogers68d8b422014-07-17 11:09:10 -0700611}
612
613void JavaVMExt::AllowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700614 CHECK(!kUseReadBarrier);
Ian Rogers68d8b422014-07-17 11:09:10 -0700615 Thread* self = Thread::Current();
616 MutexLock mu(self, weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700617 allow_accessing_weak_globals_.StoreSequentiallyConsistent(true);
Ian Rogers68d8b422014-07-17 11:09:10 -0700618 weak_globals_add_condition_.Broadcast(self);
619}
620
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700621void JavaVMExt::BroadcastForNewWeakGlobals() {
622 CHECK(kUseReadBarrier);
623 Thread* self = Thread::Current();
624 MutexLock mu(self, weak_globals_lock_);
625 weak_globals_add_condition_.Broadcast(self);
626}
627
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700628mirror::Object* JavaVMExt::DecodeGlobal(IndirectRef ref) {
629 return globals_.SynchronizedGet(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700630}
631
Jeff Hao83c81952015-05-27 19:29:29 -0700632void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, mirror::Object* result) {
633 WriterMutexLock mu(self, globals_lock_);
634 globals_.Update(ref, result);
635}
636
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700637inline bool JavaVMExt::MayAccessWeakGlobals(Thread* self) const {
638 return MayAccessWeakGlobalsUnlocked(self);
639}
640
641inline bool JavaVMExt::MayAccessWeakGlobalsUnlocked(Thread* self) const {
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700642 DCHECK(self != nullptr);
643 return kUseReadBarrier ?
644 self->GetWeakRefAccessEnabled() :
645 allow_accessing_weak_globals_.LoadSequentiallyConsistent();
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700646}
647
Ian Rogers68d8b422014-07-17 11:09:10 -0700648mirror::Object* JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700649 // It is safe to access GetWeakRefAccessEnabled without the lock since CC uses checkpoints to call
650 // SetWeakRefAccessEnabled, and the other collectors only modify allow_accessing_weak_globals_
651 // when the mutators are paused.
652 // This only applies in the case where MayAccessWeakGlobals goes from false to true. In the other
653 // case, it may be racy, this is benign since DecodeWeakGlobalLocked does the correct behavior
654 // if MayAccessWeakGlobals is false.
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -0700655 DCHECK_EQ(GetIndirectRefKind(ref), kWeakGlobal);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700656 if (LIKELY(MayAccessWeakGlobalsUnlocked(self))) {
657 return weak_globals_.SynchronizedGet(ref);
658 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700659 MutexLock mu(self, weak_globals_lock_);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700660 return DecodeWeakGlobalLocked(self, ref);
661}
662
663mirror::Object* JavaVMExt::DecodeWeakGlobalLocked(Thread* self, IndirectRef ref) {
664 if (kDebugLocking) {
665 weak_globals_lock_.AssertHeld(self);
666 }
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700667 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700668 weak_globals_add_condition_.WaitHoldingLocks(self);
669 }
670 return weak_globals_.Get(ref);
671}
672
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700673mirror::Object* JavaVMExt::DecodeWeakGlobalDuringShutdown(Thread* self, IndirectRef ref) {
674 DCHECK_EQ(GetIndirectRefKind(ref), kWeakGlobal);
675 DCHECK(Runtime::Current()->IsShuttingDown(self));
676 if (self != nullptr) {
677 return DecodeWeakGlobal(self, ref);
678 }
679 // self can be null during a runtime shutdown. ~Runtime()->~ClassLinker()->DecodeWeakGlobal().
680 if (!kUseReadBarrier) {
681 DCHECK(allow_accessing_weak_globals_.LoadSequentiallyConsistent());
682 }
683 return weak_globals_.SynchronizedGet(ref);
684}
685
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800686bool JavaVMExt::IsWeakGlobalCleared(Thread* self, IndirectRef ref) {
687 DCHECK_EQ(GetIndirectRefKind(ref), kWeakGlobal);
688 MutexLock mu(self, weak_globals_lock_);
689 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
690 weak_globals_add_condition_.WaitHoldingLocks(self);
691 }
692 // When just checking a weak ref has been cleared, avoid triggering the read barrier in decode
693 // (DecodeWeakGlobal) so that we won't accidentally mark the object alive. Since the cleared
694 // sentinel is a non-moving object, we can compare the ref to it without the read barrier and
695 // decide if it's cleared.
696 return Runtime::Current()->IsClearedJniWeakGlobal(weak_globals_.Get<kWithoutReadBarrier>(ref));
697}
698
Jeff Hao83c81952015-05-27 19:29:29 -0700699void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, mirror::Object* result) {
700 MutexLock mu(self, weak_globals_lock_);
701 weak_globals_.Update(ref, result);
702}
703
Ian Rogers68d8b422014-07-17 11:09:10 -0700704void JavaVMExt::DumpReferenceTables(std::ostream& os) {
705 Thread* self = Thread::Current();
706 {
707 ReaderMutexLock mu(self, globals_lock_);
708 globals_.Dump(os);
709 }
710 {
711 MutexLock mu(self, weak_globals_lock_);
712 weak_globals_.Dump(os);
713 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700714}
715
Mathieu Chartier598302a2015-09-23 14:52:39 -0700716void JavaVMExt::UnloadNativeLibraries() {
717 libraries_.get()->UnloadNativeLibraries();
718}
719
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800720bool JavaVMExt::LoadNativeLibrary(JNIEnv* env,
721 const std::string& path,
722 jobject class_loader,
723 jstring library_path,
724 std::string* error_msg) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700725 error_msg->clear();
726
727 // See if we've already loaded this library. If we have, and the class loader
728 // matches, return successfully without doing anything.
729 // TODO: for better results we should canonicalize the pathname (or even compare
730 // inodes). This implementation is fine if everybody is using System.loadLibrary.
731 SharedLibrary* library;
732 Thread* self = Thread::Current();
733 {
734 // TODO: move the locking (and more of this logic) into Libraries.
735 MutexLock mu(self, *Locks::jni_libraries_lock_);
736 library = libraries_->Get(path);
737 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800738 void* class_loader_allocator = nullptr;
739 {
740 ScopedObjectAccess soa(env);
741 // As the incoming class loader is reachable/alive during the call of this function,
742 // it's okay to decode it without worrying about unexpectedly marking it alive.
743 mirror::ClassLoader* loader = soa.Decode<mirror::ClassLoader*>(class_loader);
744 class_loader_allocator =
Mathieu Chartier1ed1a132015-12-01 01:20:00 +0000745 Runtime::Current()->GetClassLinker()->GetAllocatorForClassLoader(loader);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800746 CHECK(class_loader_allocator != nullptr);
747 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700748 if (library != nullptr) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800749 // Use the allocator pointers for class loader equality to avoid unnecessary weak root decode.
750 if (library->GetClassLoaderAllocator() != class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700751 // The library will be associated with class_loader. The JNI
752 // spec says we can't load the same library into more than one
753 // class loader.
754 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
755 "ClassLoader %p; can't open in ClassLoader %p",
756 path.c_str(), library->GetClassLoader(), class_loader);
757 LOG(WARNING) << error_msg;
758 return false;
759 }
760 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
761 << " ClassLoader " << class_loader << "]";
762 if (!library->CheckOnLoadResult()) {
763 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
764 "to load \"%s\"", path.c_str());
765 return false;
766 }
767 return true;
768 }
769
770 // Open the shared library. Because we're using a full path, the system
771 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
772 // resolve this library's dependencies though.)
773
774 // Failures here are expected when java.library.path has several entries
775 // and we have to hunt for the lib.
776
777 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
778 // class unloading. Libraries will only be unloaded when the reference count (incremented by
779 // dlopen) becomes zero from dlclose.
780
781 Locks::mutator_lock_->AssertNotHeld(self);
782 const char* path_str = path.empty() ? nullptr : path.c_str();
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800783 void* handle = android::OpenNativeLibrary(env,
784 runtime_->GetTargetSdkVersion(),
785 path_str,
786 class_loader,
787 library_path);
788
Ian Rogers68d8b422014-07-17 11:09:10 -0700789 bool needs_native_bridge = false;
790 if (handle == nullptr) {
Calin Juravlec8423522014-08-12 20:55:20 +0100791 if (android::NativeBridgeIsSupported(path_str)) {
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700792 handle = android::NativeBridgeLoadLibrary(path_str, RTLD_NOW);
Ian Rogers68d8b422014-07-17 11:09:10 -0700793 needs_native_bridge = true;
794 }
795 }
796
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700797 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]";
Ian Rogers68d8b422014-07-17 11:09:10 -0700798
799 if (handle == nullptr) {
800 *error_msg = dlerror();
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700801 VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700802 return false;
803 }
804
805 if (env->ExceptionCheck() == JNI_TRUE) {
806 LOG(ERROR) << "Unexpected exception:";
807 env->ExceptionDescribe();
808 env->ExceptionClear();
809 }
810 // Create a new entry.
811 // TODO: move the locking (and more of this logic) into Libraries.
812 bool created_library = false;
813 {
814 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
815 std::unique_ptr<SharedLibrary> new_library(
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800816 new SharedLibrary(env, self, path, handle, class_loader, class_loader_allocator));
Ian Rogers68d8b422014-07-17 11:09:10 -0700817 MutexLock mu(self, *Locks::jni_libraries_lock_);
818 library = libraries_->Get(path);
819 if (library == nullptr) { // We won race to get libraries_lock.
820 library = new_library.release();
821 libraries_->Put(path, library);
822 created_library = true;
823 }
824 }
825 if (!created_library) {
826 LOG(INFO) << "WOW: we lost a race to add shared library: "
827 << "\"" << path << "\" ClassLoader=" << class_loader;
828 return library->CheckOnLoadResult();
829 }
830 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
831
832 bool was_successful = false;
833 void* sym;
834 if (needs_native_bridge) {
835 library->SetNeedsNativeBridge();
Ian Rogers68d8b422014-07-17 11:09:10 -0700836 }
Mathieu Chartier598302a2015-09-23 14:52:39 -0700837 sym = library->FindSymbol("JNI_OnLoad", nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700838 if (sym == nullptr) {
839 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
840 was_successful = true;
841 } else {
842 // Call JNI_OnLoad. We have to override the current class
843 // loader, which will always be "null" since the stuff at the
844 // top of the stack is around Runtime.loadLibrary(). (See
845 // the comments in the JNI FindClass function.)
846 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
847 self->SetClassLoaderOverride(class_loader);
848
849 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
850 typedef int (*JNI_OnLoadFn)(JavaVM*, void*);
851 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
852 int version = (*jni_on_load)(this, nullptr);
853
Mathieu Chartierd0004802014-10-15 16:59:47 -0700854 if (runtime_->GetTargetSdkVersion() != 0 && runtime_->GetTargetSdkVersion() <= 21) {
855 fault_manager.EnsureArtActionInFrontOfSignalChain();
856 }
857
Ian Rogers68d8b422014-07-17 11:09:10 -0700858 self->SetClassLoaderOverride(old_class_loader.get());
859
860 if (version == JNI_ERR) {
861 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
862 } else if (IsBadJniVersion(version)) {
863 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
864 path.c_str(), version);
865 // It's unwise to call dlclose() here, but we can mark it
866 // as bad and ensure that future load attempts will fail.
867 // We don't know how far JNI_OnLoad got, so there could
868 // be some partially-initialized stuff accessible through
869 // newly-registered native method calls. We could try to
870 // unregister them, but that doesn't seem worthwhile.
871 } else {
872 was_successful = true;
873 }
874 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
875 << " from JNI_OnLoad in \"" << path << "\"]";
876 }
877
878 library->SetResult(was_successful);
879 return was_successful;
880}
881
Mathieu Chartiere401d142015-04-22 13:56:20 -0700882void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700883 CHECK(m->IsNative());
884 mirror::Class* c = m->GetDeclaringClass();
885 // If this is a static method, it could be called before the class has been initialized.
886 CHECK(c->IsInitializing()) << c->GetStatus() << " " << PrettyMethod(m);
887 std::string detail;
888 void* native_method;
889 Thread* self = Thread::Current();
890 {
891 MutexLock mu(self, *Locks::jni_libraries_lock_);
892 native_method = libraries_->FindNativeMethod(m, detail);
893 }
894 // Throwing can cause libraries_lock to be reacquired.
895 if (native_method == nullptr) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000896 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
Ian Rogers68d8b422014-07-17 11:09:10 -0700897 }
898 return native_method;
899}
900
Mathieu Chartier97509952015-07-13 14:35:43 -0700901void JavaVMExt::SweepJniWeakGlobals(IsMarkedVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700902 MutexLock mu(Thread::Current(), weak_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700903 Runtime* const runtime = Runtime::Current();
904 for (auto* entry : weak_globals_) {
905 // Need to skip null here to distinguish between null entries and cleared weak ref entries.
906 if (!entry->IsNull()) {
907 // Since this is called by the GC, we don't need a read barrier.
908 mirror::Object* obj = entry->Read<kWithoutReadBarrier>();
Mathieu Chartier97509952015-07-13 14:35:43 -0700909 mirror::Object* new_obj = visitor->IsMarked(obj);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700910 if (new_obj == nullptr) {
911 new_obj = runtime->GetClearedJniWeakGlobal();
912 }
913 *entry = GcRoot<mirror::Object>(new_obj);
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -0700914 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700915 }
916}
917
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800918void JavaVMExt::TrimGlobals() {
919 WriterMutexLock mu(Thread::Current(), globals_lock_);
920 globals_.Trim();
921}
922
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700923void JavaVMExt::VisitRoots(RootVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700924 Thread* self = Thread::Current();
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800925 ReaderMutexLock mu(self, globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700926 globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal));
Ian Rogers68d8b422014-07-17 11:09:10 -0700927 // The weak_globals table is visited by the GC itself (because it mutates the table).
928}
929
930// JNI Invocation interface.
931
932extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800933 ScopedTrace trace(__FUNCTION__);
Ian Rogers68d8b422014-07-17 11:09:10 -0700934 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
935 if (IsBadJniVersion(args->version)) {
936 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
937 return JNI_EVERSION;
938 }
939 RuntimeOptions options;
940 for (int i = 0; i < args->nOptions; ++i) {
941 JavaVMOption* option = &args->options[i];
942 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
943 }
944 bool ignore_unrecognized = args->ignoreUnrecognized;
945 if (!Runtime::Create(options, ignore_unrecognized)) {
946 return JNI_ERR;
947 }
948 Runtime* runtime = Runtime::Current();
949 bool started = runtime->Start();
950 if (!started) {
951 delete Thread::Current()->GetJniEnv();
952 delete runtime->GetJavaVM();
953 LOG(WARNING) << "CreateJavaVM failed";
954 return JNI_ERR;
955 }
Dimitry Ivanov041169f2016-04-21 16:01:24 -0700956
957 // Initialize native loader. This step makes sure we have
958 // everything set up before we start using JNI.
959 android::InitializeNativeLoader();
960
Ian Rogers68d8b422014-07-17 11:09:10 -0700961 *p_env = Thread::Current()->GetJniEnv();
962 *p_vm = runtime->GetJavaVM();
963 return JNI_OK;
964}
965
Ian Rogersf4d4da12014-11-11 16:10:33 -0800966extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700967 Runtime* runtime = Runtime::Current();
Ian Rogersf4d4da12014-11-11 16:10:33 -0800968 if (runtime == nullptr || buf_len == 0) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700969 *vm_count = 0;
970 } else {
971 *vm_count = 1;
Ian Rogersf4d4da12014-11-11 16:10:33 -0800972 vms_buf[0] = runtime->GetJavaVM();
Ian Rogers68d8b422014-07-17 11:09:10 -0700973 }
974 return JNI_OK;
975}
976
977// Historically unsupported.
978extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
979 return JNI_ERR;
980}
981
982} // namespace art