blob: 15f51220e442ba52496e1db70a3c89e8c119f575 [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
Dmitriy Ivanovf5a30992015-11-11 14:18:55 -080020
Richard Uhler054a0782015-04-07 10:56:50 -070021#include <cutils/trace.h>
Ian Rogers68d8b422014-07-17 11:09:10 -070022#include <dlfcn.h>
23
Mathieu Chartiere401d142015-04-22 13:56:20 -070024#include "art_method.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070025#include "base/dumpable.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070026#include "base/mutex.h"
27#include "base/stl_util.h"
28#include "check_jni.h"
Elliott Hughes956af0f2014-12-11 14:34:28 -080029#include "dex_file-inl.h"
Mathieu Chartierd0004802014-10-15 16:59:47 -070030#include "fault_handler.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070031#include "indirect_reference_table-inl.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070032#include "mirror/class-inl.h"
33#include "mirror/class_loader.h"
Calin Juravlec8423522014-08-12 20:55:20 +010034#include "nativebridge/native_bridge.h"
Dmitriy Ivanovf5a30992015-11-11 14:18:55 -080035#include "nativeloader/native_loader.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070036#include "java_vm_ext.h"
37#include "parsed_options.h"
Ian Rogersc0542af2014-09-03 16:16:56 -070038#include "runtime-inl.h"
Igor Murashkinaaebaa02015-01-26 10:55:53 -080039#include "runtime_options.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070040#include "ScopedLocalRef.h"
41#include "scoped_thread_state_change.h"
42#include "thread-inl.h"
43#include "thread_list.h"
44
45namespace art {
46
Ian Rogers68d8b422014-07-17 11:09:10 -070047static size_t gGlobalsInitial = 512; // Arbitrary.
48static size_t gGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
49
50static const size_t kWeakGlobalsInitial = 16; // Arbitrary.
51static const size_t kWeakGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
52
53static bool IsBadJniVersion(int version) {
54 // We don't support JNI_VERSION_1_1. These are the only other valid versions.
55 return version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 && version != JNI_VERSION_1_6;
56}
57
58class SharedLibrary {
59 public:
60 SharedLibrary(JNIEnv* env, Thread* self, const std::string& path, void* handle,
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080061 jobject class_loader, void* class_loader_allocator)
Ian Rogers68d8b422014-07-17 11:09:10 -070062 : path_(path),
63 handle_(handle),
64 needs_native_bridge_(false),
Mathieu Chartier598302a2015-09-23 14:52:39 -070065 class_loader_(env->NewWeakGlobalRef(class_loader)),
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080066 class_loader_allocator_(class_loader_allocator),
Ian Rogers68d8b422014-07-17 11:09:10 -070067 jni_on_load_lock_("JNI_OnLoad lock"),
68 jni_on_load_cond_("JNI_OnLoad condition variable", jni_on_load_lock_),
69 jni_on_load_thread_id_(self->GetThreadId()),
70 jni_on_load_result_(kPending) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080071 CHECK(class_loader_allocator_ != nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -070072 }
73
74 ~SharedLibrary() {
75 Thread* self = Thread::Current();
76 if (self != nullptr) {
Mathieu Chartier598302a2015-09-23 14:52:39 -070077 self->GetJniEnv()->DeleteWeakGlobalRef(class_loader_);
Ian Rogers68d8b422014-07-17 11:09:10 -070078 }
79 }
80
Mathieu Chartier598302a2015-09-23 14:52:39 -070081 jweak GetClassLoader() const {
Ian Rogers68d8b422014-07-17 11:09:10 -070082 return class_loader_;
83 }
84
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080085 const void* GetClassLoaderAllocator() const {
86 return class_loader_allocator_;
87 }
88
Ian Rogers68d8b422014-07-17 11:09:10 -070089 const std::string& GetPath() const {
90 return path_;
91 }
92
93 /*
94 * Check the result of an earlier call to JNI_OnLoad on this library.
95 * If the call has not yet finished in another thread, wait for it.
96 */
97 bool CheckOnLoadResult()
Mathieu Chartier90443472015-07-16 20:32:27 -070098 REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -070099 Thread* self = Thread::Current();
100 bool okay;
101 {
102 MutexLock mu(self, jni_on_load_lock_);
103
104 if (jni_on_load_thread_id_ == self->GetThreadId()) {
105 // Check this so we don't end up waiting for ourselves. We need to return "true" so the
106 // caller can continue.
107 LOG(INFO) << *self << " recursive attempt to load library " << "\"" << path_ << "\"";
108 okay = true;
109 } else {
110 while (jni_on_load_result_ == kPending) {
111 VLOG(jni) << "[" << *self << " waiting for \"" << path_ << "\" " << "JNI_OnLoad...]";
112 jni_on_load_cond_.Wait(self);
113 }
114
115 okay = (jni_on_load_result_ == kOkay);
116 VLOG(jni) << "[Earlier JNI_OnLoad for \"" << path_ << "\" "
117 << (okay ? "succeeded" : "failed") << "]";
118 }
119 }
120 return okay;
121 }
122
Mathieu Chartier90443472015-07-16 20:32:27 -0700123 void SetResult(bool result) REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700124 Thread* self = Thread::Current();
125 MutexLock mu(self, jni_on_load_lock_);
126
127 jni_on_load_result_ = result ? kOkay : kFailed;
128 jni_on_load_thread_id_ = 0;
129
130 // Broadcast a wakeup to anybody sleeping on the condition variable.
131 jni_on_load_cond_.Broadcast(self);
132 }
133
134 void SetNeedsNativeBridge() {
135 needs_native_bridge_ = true;
136 }
137
138 bool NeedsNativeBridge() const {
139 return needs_native_bridge_;
140 }
141
Mathieu Chartier598302a2015-09-23 14:52:39 -0700142 void* FindSymbol(const std::string& symbol_name, const char* shorty = nullptr) {
143 return NeedsNativeBridge()
144 ? FindSymbolWithNativeBridge(symbol_name.c_str(), shorty)
145 : FindSymbolWithoutNativeBridge(symbol_name.c_str());
146 }
147
148 void* FindSymbolWithoutNativeBridge(const std::string& symbol_name) {
Andreas Gampe8fec90b2015-06-30 11:23:44 -0700149 CHECK(!NeedsNativeBridge());
150
Ian Rogers68d8b422014-07-17 11:09:10 -0700151 return dlsym(handle_, symbol_name.c_str());
152 }
153
154 void* FindSymbolWithNativeBridge(const std::string& symbol_name, const char* shorty) {
155 CHECK(NeedsNativeBridge());
156
157 uint32_t len = 0;
Calin Juravlec8423522014-08-12 20:55:20 +0100158 return android::NativeBridgeGetTrampoline(handle_, symbol_name.c_str(), shorty, len);
Ian Rogers68d8b422014-07-17 11:09:10 -0700159 }
160
161 private:
162 enum JNI_OnLoadState {
163 kPending,
164 kFailed,
165 kOkay,
166 };
167
168 // Path to library "/system/lib/libjni.so".
169 const std::string path_;
170
171 // The void* returned by dlopen(3).
172 void* const handle_;
173
174 // True if a native bridge is required.
175 bool needs_native_bridge_;
176
Mathieu Chartier598302a2015-09-23 14:52:39 -0700177 // The ClassLoader this library is associated with, a weak global JNI reference that is
Ian Rogers68d8b422014-07-17 11:09:10 -0700178 // created/deleted with the scope of the library.
Mathieu Chartier598302a2015-09-23 14:52:39 -0700179 const jweak class_loader_;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800180 // Used to do equality check on class loaders so we can avoid decoding the weak root and read
181 // barriers that mess with class unloading.
182 const void* class_loader_allocator_;
Ian Rogers68d8b422014-07-17 11:09:10 -0700183
184 // Guards remaining items.
185 Mutex jni_on_load_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
186 // Wait for JNI_OnLoad in other thread.
187 ConditionVariable jni_on_load_cond_ GUARDED_BY(jni_on_load_lock_);
188 // Recursive invocation guard.
189 uint32_t jni_on_load_thread_id_ GUARDED_BY(jni_on_load_lock_);
190 // Result of earlier JNI_OnLoad call.
191 JNI_OnLoadState jni_on_load_result_ GUARDED_BY(jni_on_load_lock_);
192};
193
194// This exists mainly to keep implementation details out of the header file.
195class Libraries {
196 public:
197 Libraries() {
198 }
199
200 ~Libraries() {
201 STLDeleteValues(&libraries_);
202 }
203
Mathieu Chartier598302a2015-09-23 14:52:39 -0700204 // NO_THREAD_SAFETY_ANALYSIS since this may be called from Dumpable. Dumpable can't be annotated
205 // properly due to the template. The caller should be holding the jni_libraries_lock_.
206 void Dump(std::ostream& os) const NO_THREAD_SAFETY_ANALYSIS {
207 Locks::jni_libraries_lock_->AssertHeld(Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -0700208 bool first = true;
209 for (const auto& library : libraries_) {
210 if (!first) {
211 os << ' ';
212 }
213 first = false;
214 os << library.first;
215 }
216 }
217
Mathieu Chartier598302a2015-09-23 14:52:39 -0700218 size_t size() const REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700219 return libraries_.size();
220 }
221
Mathieu Chartier598302a2015-09-23 14:52:39 -0700222 SharedLibrary* Get(const std::string& path) REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700223 auto it = libraries_.find(path);
224 return (it == libraries_.end()) ? nullptr : it->second;
225 }
226
Mathieu Chartier598302a2015-09-23 14:52:39 -0700227 void Put(const std::string& path, SharedLibrary* library)
228 REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700229 libraries_.Put(path, library);
230 }
231
232 // See section 11.3 "Linking Native Methods" of the JNI spec.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700233 void* FindNativeMethod(ArtMethod* m, std::string& detail)
Mathieu Chartier90443472015-07-16 20:32:27 -0700234 REQUIRES(Locks::jni_libraries_lock_)
235 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700236 std::string jni_short_name(JniShortName(m));
237 std::string jni_long_name(JniLongName(m));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800238 mirror::ClassLoader* const declaring_class_loader = m->GetDeclaringClass()->GetClassLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700239 ScopedObjectAccessUnchecked soa(Thread::Current());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800240 void* const declaring_class_loader_allocator =
241 Runtime::Current()->GetClassLinker()->GetAllocatorForClassLoader(declaring_class_loader);
242 CHECK(declaring_class_loader_allocator != nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700243 for (const auto& lib : libraries_) {
Mathieu Chartier598302a2015-09-23 14:52:39 -0700244 SharedLibrary* const library = lib.second;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800245 // Use the allocator address for class loader equality to avoid unnecessary weak root decode.
246 if (library->GetClassLoaderAllocator() != declaring_class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700247 // We only search libraries loaded by the appropriate ClassLoader.
248 continue;
249 }
250 // Try the short name then the long name...
Mathieu Chartier598302a2015-09-23 14:52:39 -0700251 const char* shorty = library->NeedsNativeBridge()
252 ? m->GetShorty()
253 : nullptr;
254 void* fn = library->FindSymbol(jni_short_name, shorty);
255 if (fn == nullptr) {
256 fn = library->FindSymbol(jni_long_name, shorty);
Ian Rogers68d8b422014-07-17 11:09:10 -0700257 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700258 if (fn != nullptr) {
259 VLOG(jni) << "[Found native code for " << PrettyMethod(m)
260 << " in \"" << library->GetPath() << "\"]";
261 return fn;
262 }
263 }
264 detail += "No implementation found for ";
265 detail += PrettyMethod(m);
266 detail += " (tried " + jni_short_name + " and " + jni_long_name + ")";
267 LOG(ERROR) << detail;
268 return nullptr;
269 }
270
Mathieu Chartier598302a2015-09-23 14:52:39 -0700271 // Unload native libraries with cleared class loaders.
272 void UnloadNativeLibraries()
273 REQUIRES(!Locks::jni_libraries_lock_)
274 SHARED_REQUIRES(Locks::mutator_lock_) {
275 ScopedObjectAccessUnchecked soa(Thread::Current());
276 typedef void (*JNI_OnUnloadFn)(JavaVM*, void*);
277 std::vector<JNI_OnUnloadFn> unload_functions;
278 {
279 MutexLock mu(soa.Self(), *Locks::jni_libraries_lock_);
280 for (auto it = libraries_.begin(); it != libraries_.end(); ) {
281 SharedLibrary* const library = it->second;
282 // If class loader is null then it was unloaded, call JNI_OnUnload.
Mathieu Chartiercffb7472015-09-28 10:33:00 -0700283 const jweak class_loader = library->GetClassLoader();
284 // If class_loader is a null jobject then it is the boot class loader. We should not unload
285 // the native libraries of the boot class loader.
286 if (class_loader != nullptr &&
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800287 soa.Self()->IsJWeakCleared(class_loader)) {
Mathieu Chartier598302a2015-09-23 14:52:39 -0700288 void* const sym = library->FindSymbol("JNI_OnUnload", nullptr);
289 if (sym == nullptr) {
290 VLOG(jni) << "[No JNI_OnUnload found in \"" << library->GetPath() << "\"]";
291 } else {
292 VLOG(jni) << "[JNI_OnUnload found for \"" << library->GetPath() << "\"]";
293 JNI_OnUnloadFn jni_on_unload = reinterpret_cast<JNI_OnUnloadFn>(sym);
294 unload_functions.push_back(jni_on_unload);
295 }
296 delete library;
297 it = libraries_.erase(it);
298 } else {
299 ++it;
300 }
301 }
302 }
303 // Do this without holding the jni libraries lock to prevent possible deadlocks.
304 for (JNI_OnUnloadFn fn : unload_functions) {
305 VLOG(jni) << "Calling JNI_OnUnload";
306 (*fn)(soa.Vm(), nullptr);
307 }
308 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700309
Mathieu Chartier598302a2015-09-23 14:52:39 -0700310 private:
311 AllocationTrackingSafeMap<std::string, SharedLibrary*, kAllocatorTagJNILibraries> libraries_
312 GUARDED_BY(Locks::jni_libraries_lock_);
313};
Ian Rogers68d8b422014-07-17 11:09:10 -0700314
315class JII {
316 public:
317 static jint DestroyJavaVM(JavaVM* vm) {
318 if (vm == nullptr) {
319 return JNI_ERR;
320 }
321 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
322 delete raw_vm->GetRuntime();
323 return JNI_OK;
324 }
325
326 static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
327 return AttachCurrentThreadInternal(vm, p_env, thr_args, false);
328 }
329
330 static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
331 return AttachCurrentThreadInternal(vm, p_env, thr_args, true);
332 }
333
334 static jint DetachCurrentThread(JavaVM* vm) {
335 if (vm == nullptr || Thread::Current() == nullptr) {
336 return JNI_ERR;
337 }
338 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
339 Runtime* runtime = raw_vm->GetRuntime();
340 runtime->DetachCurrentThread();
341 return JNI_OK;
342 }
343
344 static jint GetEnv(JavaVM* vm, void** env, jint version) {
345 // GetEnv always returns a JNIEnv* for the most current supported JNI version,
346 // and unlike other calls that take a JNI version doesn't care if you supply
347 // JNI_VERSION_1_1, which we don't otherwise support.
348 if (IsBadJniVersion(version) && version != JNI_VERSION_1_1) {
349 LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version;
350 return JNI_EVERSION;
351 }
352 if (vm == nullptr || env == nullptr) {
353 return JNI_ERR;
354 }
355 Thread* thread = Thread::Current();
356 if (thread == nullptr) {
357 *env = nullptr;
358 return JNI_EDETACHED;
359 }
360 *env = thread->GetJniEnv();
361 return JNI_OK;
362 }
363
364 private:
365 static jint AttachCurrentThreadInternal(JavaVM* vm, JNIEnv** p_env, void* raw_args, bool as_daemon) {
366 if (vm == nullptr || p_env == nullptr) {
367 return JNI_ERR;
368 }
369
370 // Return immediately if we're already attached.
371 Thread* self = Thread::Current();
372 if (self != nullptr) {
373 *p_env = self->GetJniEnv();
374 return JNI_OK;
375 }
376
377 Runtime* runtime = reinterpret_cast<JavaVMExt*>(vm)->GetRuntime();
378
379 // No threads allowed in zygote mode.
380 if (runtime->IsZygote()) {
381 LOG(ERROR) << "Attempt to attach a thread in the zygote";
382 return JNI_ERR;
383 }
384
385 JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(raw_args);
386 const char* thread_name = nullptr;
387 jobject thread_group = nullptr;
388 if (args != nullptr) {
389 if (IsBadJniVersion(args->version)) {
390 LOG(ERROR) << "Bad JNI version passed to "
391 << (as_daemon ? "AttachCurrentThreadAsDaemon" : "AttachCurrentThread") << ": "
392 << args->version;
393 return JNI_EVERSION;
394 }
395 thread_name = args->name;
396 thread_group = args->group;
397 }
398
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800399 if (!runtime->AttachCurrentThread(thread_name, as_daemon, thread_group,
400 !runtime->IsAotCompiler())) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700401 *p_env = nullptr;
402 return JNI_ERR;
403 } else {
404 *p_env = Thread::Current()->GetJniEnv();
405 return JNI_OK;
406 }
407 }
408};
409
410const JNIInvokeInterface gJniInvokeInterface = {
411 nullptr, // reserved0
412 nullptr, // reserved1
413 nullptr, // reserved2
414 JII::DestroyJavaVM,
415 JII::AttachCurrentThread,
416 JII::DetachCurrentThread,
417 JII::GetEnv,
418 JII::AttachCurrentThreadAsDaemon
419};
420
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800421JavaVMExt::JavaVMExt(Runtime* runtime, const RuntimeArgumentMap& runtime_options)
Ian Rogers68d8b422014-07-17 11:09:10 -0700422 : runtime_(runtime),
423 check_jni_abort_hook_(nullptr),
424 check_jni_abort_hook_data_(nullptr),
425 check_jni_(false), // Initialized properly in the constructor body below.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800426 force_copy_(runtime_options.Exists(RuntimeArgumentMap::JniOptsForceCopy)),
427 tracing_enabled_(runtime_options.Exists(RuntimeArgumentMap::JniTrace)
428 || VLOG_IS_ON(third_party_jni)),
429 trace_(runtime_options.GetOrDefault(RuntimeArgumentMap::JniTrace)),
Ian Rogers68d8b422014-07-17 11:09:10 -0700430 globals_lock_("JNI global reference table lock"),
431 globals_(gGlobalsInitial, gGlobalsMax, kGlobal),
432 libraries_(new Libraries),
433 unchecked_functions_(&gJniInvokeInterface),
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700434 weak_globals_lock_("JNI weak global reference table lock", kJniWeakGlobalsLock),
Ian Rogers68d8b422014-07-17 11:09:10 -0700435 weak_globals_(kWeakGlobalsInitial, kWeakGlobalsMax, kWeakGlobal),
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700436 allow_accessing_weak_globals_(true),
Ian Rogers68d8b422014-07-17 11:09:10 -0700437 weak_globals_add_condition_("weak globals add condition", weak_globals_lock_) {
438 functions = unchecked_functions_;
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800439 SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni));
Ian Rogers68d8b422014-07-17 11:09:10 -0700440}
441
442JavaVMExt::~JavaVMExt() {
443}
444
445void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) {
446 Thread* self = Thread::Current();
447 ScopedObjectAccess soa(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700448 ArtMethod* current_method = self->GetCurrentMethod(nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700449
450 std::ostringstream os;
451 os << "JNI DETECTED ERROR IN APPLICATION: " << msg;
452
453 if (jni_function_name != nullptr) {
454 os << "\n in call to " << jni_function_name;
455 }
456 // TODO: is this useful given that we're about to dump the calling thread's stack?
457 if (current_method != nullptr) {
458 os << "\n from " << PrettyMethod(current_method);
459 }
460 os << "\n";
461 self->Dump(os);
462
463 if (check_jni_abort_hook_ != nullptr) {
464 check_jni_abort_hook_(check_jni_abort_hook_data_, os.str());
465 } else {
466 // Ensure that we get a native stack trace for this thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700467 ScopedThreadSuspension sts(self, kNative);
Ian Rogers68d8b422014-07-17 11:09:10 -0700468 LOG(FATAL) << os.str();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700469 UNREACHABLE();
Ian Rogers68d8b422014-07-17 11:09:10 -0700470 }
471}
472
473void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) {
474 std::string msg;
475 StringAppendV(&msg, fmt, ap);
476 JniAbort(jni_function_name, msg.c_str());
477}
478
479void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) {
480 va_list args;
481 va_start(args, fmt);
482 JniAbortV(jni_function_name, fmt, args);
483 va_end(args);
484}
485
Mathieu Chartiere401d142015-04-22 13:56:20 -0700486bool JavaVMExt::ShouldTrace(ArtMethod* method) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700487 // Fast where no tracing is enabled.
488 if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) {
489 return false;
490 }
491 // Perform checks based on class name.
492 StringPiece class_name(method->GetDeclaringClassDescriptor());
493 if (!trace_.empty() && class_name.find(trace_) != std::string::npos) {
494 return true;
495 }
496 if (!VLOG_IS_ON(third_party_jni)) {
497 return false;
498 }
499 // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
500 // like part of Android.
501 static const char* gBuiltInPrefixes[] = {
502 "Landroid/",
503 "Lcom/android/",
504 "Lcom/google/android/",
505 "Ldalvik/",
506 "Ljava/",
507 "Ljavax/",
508 "Llibcore/",
509 "Lorg/apache/harmony/",
510 };
511 for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) {
512 if (class_name.starts_with(gBuiltInPrefixes[i])) {
513 return false;
514 }
515 }
516 return true;
517}
518
519jobject JavaVMExt::AddGlobalRef(Thread* self, mirror::Object* obj) {
520 // Check for null after decoding the object to handle cleared weak globals.
521 if (obj == nullptr) {
522 return nullptr;
523 }
524 WriterMutexLock mu(self, globals_lock_);
525 IndirectRef ref = globals_.Add(IRT_FIRST_SEGMENT, obj);
526 return reinterpret_cast<jobject>(ref);
527}
528
529jweak JavaVMExt::AddWeakGlobalRef(Thread* self, mirror::Object* obj) {
530 if (obj == nullptr) {
531 return nullptr;
532 }
533 MutexLock mu(self, weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700534 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700535 weak_globals_add_condition_.WaitHoldingLocks(self);
536 }
537 IndirectRef ref = weak_globals_.Add(IRT_FIRST_SEGMENT, obj);
538 return reinterpret_cast<jweak>(ref);
539}
540
541void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
542 if (obj == nullptr) {
543 return;
544 }
545 WriterMutexLock mu(self, globals_lock_);
546 if (!globals_.Remove(IRT_FIRST_SEGMENT, obj)) {
547 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
548 << "failed to find entry";
549 }
550}
551
552void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
553 if (obj == nullptr) {
554 return;
555 }
556 MutexLock mu(self, weak_globals_lock_);
557 if (!weak_globals_.Remove(IRT_FIRST_SEGMENT, obj)) {
558 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
559 << "failed to find entry";
560 }
561}
562
563static void ThreadEnableCheckJni(Thread* thread, void* arg) {
564 bool* check_jni = reinterpret_cast<bool*>(arg);
565 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
566}
567
568bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
569 bool old_check_jni = check_jni_;
570 check_jni_ = enabled;
571 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
572 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
573 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
574 return old_check_jni;
575}
576
577void JavaVMExt::DumpForSigQuit(std::ostream& os) {
578 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
579 if (force_copy_) {
580 os << " (with forcecopy)";
581 }
582 Thread* self = Thread::Current();
583 {
Ian Rogers68d8b422014-07-17 11:09:10 -0700584 ReaderMutexLock mu(self, globals_lock_);
585 os << "; globals=" << globals_.Capacity();
586 }
587 {
588 MutexLock mu(self, weak_globals_lock_);
589 if (weak_globals_.Capacity() > 0) {
590 os << " (plus " << weak_globals_.Capacity() << " weak)";
591 }
592 }
593 os << '\n';
594
595 {
596 MutexLock mu(self, *Locks::jni_libraries_lock_);
597 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
598 }
599}
600
601void JavaVMExt::DisallowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700602 CHECK(!kUseReadBarrier);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700603 Thread* const self = Thread::Current();
604 MutexLock mu(self, weak_globals_lock_);
605 // DisallowNewWeakGlobals is only called by CMS during the pause. It is required to have the
606 // mutator lock exclusively held so that we don't have any threads in the middle of
607 // DecodeWeakGlobal.
608 Locks::mutator_lock_->AssertExclusiveHeld(self);
609 allow_accessing_weak_globals_.StoreSequentiallyConsistent(false);
Ian Rogers68d8b422014-07-17 11:09:10 -0700610}
611
612void JavaVMExt::AllowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700613 CHECK(!kUseReadBarrier);
Ian Rogers68d8b422014-07-17 11:09:10 -0700614 Thread* self = Thread::Current();
615 MutexLock mu(self, weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700616 allow_accessing_weak_globals_.StoreSequentiallyConsistent(true);
Ian Rogers68d8b422014-07-17 11:09:10 -0700617 weak_globals_add_condition_.Broadcast(self);
618}
619
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700620void JavaVMExt::BroadcastForNewWeakGlobals() {
621 CHECK(kUseReadBarrier);
622 Thread* self = Thread::Current();
623 MutexLock mu(self, weak_globals_lock_);
624 weak_globals_add_condition_.Broadcast(self);
625}
626
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700627mirror::Object* JavaVMExt::DecodeGlobal(IndirectRef ref) {
628 return globals_.SynchronizedGet(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700629}
630
Jeff Hao83c81952015-05-27 19:29:29 -0700631void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, mirror::Object* result) {
632 WriterMutexLock mu(self, globals_lock_);
633 globals_.Update(ref, result);
634}
635
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700636inline bool JavaVMExt::MayAccessWeakGlobals(Thread* self) const {
637 return MayAccessWeakGlobalsUnlocked(self);
638}
639
640inline bool JavaVMExt::MayAccessWeakGlobalsUnlocked(Thread* self) const {
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700641 DCHECK(self != nullptr);
642 return kUseReadBarrier ?
643 self->GetWeakRefAccessEnabled() :
644 allow_accessing_weak_globals_.LoadSequentiallyConsistent();
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700645}
646
Ian Rogers68d8b422014-07-17 11:09:10 -0700647mirror::Object* JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700648 // It is safe to access GetWeakRefAccessEnabled without the lock since CC uses checkpoints to call
649 // SetWeakRefAccessEnabled, and the other collectors only modify allow_accessing_weak_globals_
650 // when the mutators are paused.
651 // This only applies in the case where MayAccessWeakGlobals goes from false to true. In the other
652 // case, it may be racy, this is benign since DecodeWeakGlobalLocked does the correct behavior
653 // if MayAccessWeakGlobals is false.
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -0700654 DCHECK_EQ(GetIndirectRefKind(ref), kWeakGlobal);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700655 if (LIKELY(MayAccessWeakGlobalsUnlocked(self))) {
656 return weak_globals_.SynchronizedGet(ref);
657 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700658 MutexLock mu(self, weak_globals_lock_);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700659 return DecodeWeakGlobalLocked(self, ref);
660}
661
662mirror::Object* JavaVMExt::DecodeWeakGlobalLocked(Thread* self, IndirectRef ref) {
663 if (kDebugLocking) {
664 weak_globals_lock_.AssertHeld(self);
665 }
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700666 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700667 weak_globals_add_condition_.WaitHoldingLocks(self);
668 }
669 return weak_globals_.Get(ref);
670}
671
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700672mirror::Object* JavaVMExt::DecodeWeakGlobalDuringShutdown(Thread* self, IndirectRef ref) {
673 DCHECK_EQ(GetIndirectRefKind(ref), kWeakGlobal);
674 DCHECK(Runtime::Current()->IsShuttingDown(self));
675 if (self != nullptr) {
676 return DecodeWeakGlobal(self, ref);
677 }
678 // self can be null during a runtime shutdown. ~Runtime()->~ClassLinker()->DecodeWeakGlobal().
679 if (!kUseReadBarrier) {
680 DCHECK(allow_accessing_weak_globals_.LoadSequentiallyConsistent());
681 }
682 return weak_globals_.SynchronizedGet(ref);
683}
684
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800685bool JavaVMExt::IsWeakGlobalCleared(Thread* self, IndirectRef ref) {
686 DCHECK_EQ(GetIndirectRefKind(ref), kWeakGlobal);
687 MutexLock mu(self, weak_globals_lock_);
688 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
689 weak_globals_add_condition_.WaitHoldingLocks(self);
690 }
691 // When just checking a weak ref has been cleared, avoid triggering the read barrier in decode
692 // (DecodeWeakGlobal) so that we won't accidentally mark the object alive. Since the cleared
693 // sentinel is a non-moving object, we can compare the ref to it without the read barrier and
694 // decide if it's cleared.
695 return Runtime::Current()->IsClearedJniWeakGlobal(weak_globals_.Get<kWithoutReadBarrier>(ref));
696}
697
Jeff Hao83c81952015-05-27 19:29:29 -0700698void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, mirror::Object* result) {
699 MutexLock mu(self, weak_globals_lock_);
700 weak_globals_.Update(ref, result);
701}
702
Ian Rogers68d8b422014-07-17 11:09:10 -0700703void JavaVMExt::DumpReferenceTables(std::ostream& os) {
704 Thread* self = Thread::Current();
705 {
706 ReaderMutexLock mu(self, globals_lock_);
707 globals_.Dump(os);
708 }
709 {
710 MutexLock mu(self, weak_globals_lock_);
711 weak_globals_.Dump(os);
712 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700713}
714
Mathieu Chartier598302a2015-09-23 14:52:39 -0700715void JavaVMExt::UnloadNativeLibraries() {
716 libraries_.get()->UnloadNativeLibraries();
717}
718
Ian Rogers68d8b422014-07-17 11:09:10 -0700719bool JavaVMExt::LoadNativeLibrary(JNIEnv* env, const std::string& path, jobject class_loader,
Dmitriy Ivanovf5a30992015-11-11 14:18:55 -0800720 jstring library_path, jstring permitted_path,
Ian Rogers68d8b422014-07-17 11:09:10 -0700721 std::string* error_msg) {
722 error_msg->clear();
723
724 // See if we've already loaded this library. If we have, and the class loader
725 // matches, return successfully without doing anything.
726 // TODO: for better results we should canonicalize the pathname (or even compare
727 // inodes). This implementation is fine if everybody is using System.loadLibrary.
728 SharedLibrary* library;
729 Thread* self = Thread::Current();
730 {
731 // TODO: move the locking (and more of this logic) into Libraries.
732 MutexLock mu(self, *Locks::jni_libraries_lock_);
733 library = libraries_->Get(path);
734 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800735 void* class_loader_allocator = nullptr;
736 {
737 ScopedObjectAccess soa(env);
738 // As the incoming class loader is reachable/alive during the call of this function,
739 // it's okay to decode it without worrying about unexpectedly marking it alive.
740 mirror::ClassLoader* loader = soa.Decode<mirror::ClassLoader*>(class_loader);
741 class_loader_allocator =
Mathieu Chartier1ed1a132015-12-01 01:20:00 +0000742 Runtime::Current()->GetClassLinker()->GetAllocatorForClassLoader(loader);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800743 CHECK(class_loader_allocator != nullptr);
744 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700745 if (library != nullptr) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800746 // Use the allocator pointers for class loader equality to avoid unnecessary weak root decode.
747 if (library->GetClassLoaderAllocator() != class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700748 // The library will be associated with class_loader. The JNI
749 // spec says we can't load the same library into more than one
750 // class loader.
751 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
752 "ClassLoader %p; can't open in ClassLoader %p",
753 path.c_str(), library->GetClassLoader(), class_loader);
754 LOG(WARNING) << error_msg;
755 return false;
756 }
757 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
758 << " ClassLoader " << class_loader << "]";
759 if (!library->CheckOnLoadResult()) {
760 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
761 "to load \"%s\"", path.c_str());
762 return false;
763 }
764 return true;
765 }
766
767 // Open the shared library. Because we're using a full path, the system
768 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
769 // resolve this library's dependencies though.)
770
771 // Failures here are expected when java.library.path has several entries
772 // and we have to hunt for the lib.
773
774 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
775 // class unloading. Libraries will only be unloaded when the reference count (incremented by
776 // dlopen) becomes zero from dlclose.
777
778 Locks::mutator_lock_->AssertNotHeld(self);
779 const char* path_str = path.empty() ? nullptr : path.c_str();
Dmitriy Ivanovf5a30992015-11-11 14:18:55 -0800780 void* handle = android::OpenNativeLibrary(env, runtime_->GetTargetSdkVersion(),
781 path_str, class_loader, library_path, permitted_path);
Ian Rogers68d8b422014-07-17 11:09:10 -0700782 bool needs_native_bridge = false;
783 if (handle == nullptr) {
Calin Juravlec8423522014-08-12 20:55:20 +0100784 if (android::NativeBridgeIsSupported(path_str)) {
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700785 handle = android::NativeBridgeLoadLibrary(path_str, RTLD_NOW);
Ian Rogers68d8b422014-07-17 11:09:10 -0700786 needs_native_bridge = true;
787 }
788 }
789
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700790 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]";
Ian Rogers68d8b422014-07-17 11:09:10 -0700791
792 if (handle == nullptr) {
793 *error_msg = dlerror();
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700794 VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700795 return false;
796 }
797
798 if (env->ExceptionCheck() == JNI_TRUE) {
799 LOG(ERROR) << "Unexpected exception:";
800 env->ExceptionDescribe();
801 env->ExceptionClear();
802 }
803 // Create a new entry.
804 // TODO: move the locking (and more of this logic) into Libraries.
805 bool created_library = false;
806 {
807 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
808 std::unique_ptr<SharedLibrary> new_library(
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800809 new SharedLibrary(env, self, path, handle, class_loader, class_loader_allocator));
Ian Rogers68d8b422014-07-17 11:09:10 -0700810 MutexLock mu(self, *Locks::jni_libraries_lock_);
811 library = libraries_->Get(path);
812 if (library == nullptr) { // We won race to get libraries_lock.
813 library = new_library.release();
814 libraries_->Put(path, library);
815 created_library = true;
816 }
817 }
818 if (!created_library) {
819 LOG(INFO) << "WOW: we lost a race to add shared library: "
820 << "\"" << path << "\" ClassLoader=" << class_loader;
821 return library->CheckOnLoadResult();
822 }
823 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
824
825 bool was_successful = false;
826 void* sym;
827 if (needs_native_bridge) {
828 library->SetNeedsNativeBridge();
Ian Rogers68d8b422014-07-17 11:09:10 -0700829 }
Mathieu Chartier598302a2015-09-23 14:52:39 -0700830 sym = library->FindSymbol("JNI_OnLoad", nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700831 if (sym == nullptr) {
832 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
833 was_successful = true;
834 } else {
835 // Call JNI_OnLoad. We have to override the current class
836 // loader, which will always be "null" since the stuff at the
837 // top of the stack is around Runtime.loadLibrary(). (See
838 // the comments in the JNI FindClass function.)
839 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
840 self->SetClassLoaderOverride(class_loader);
841
842 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
843 typedef int (*JNI_OnLoadFn)(JavaVM*, void*);
844 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
845 int version = (*jni_on_load)(this, nullptr);
846
Mathieu Chartierd0004802014-10-15 16:59:47 -0700847 if (runtime_->GetTargetSdkVersion() != 0 && runtime_->GetTargetSdkVersion() <= 21) {
848 fault_manager.EnsureArtActionInFrontOfSignalChain();
849 }
850
Ian Rogers68d8b422014-07-17 11:09:10 -0700851 self->SetClassLoaderOverride(old_class_loader.get());
852
853 if (version == JNI_ERR) {
854 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
855 } else if (IsBadJniVersion(version)) {
856 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
857 path.c_str(), version);
858 // It's unwise to call dlclose() here, but we can mark it
859 // as bad and ensure that future load attempts will fail.
860 // We don't know how far JNI_OnLoad got, so there could
861 // be some partially-initialized stuff accessible through
862 // newly-registered native method calls. We could try to
863 // unregister them, but that doesn't seem worthwhile.
864 } else {
865 was_successful = true;
866 }
867 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
868 << " from JNI_OnLoad in \"" << path << "\"]";
869 }
870
871 library->SetResult(was_successful);
872 return was_successful;
873}
874
Mathieu Chartiere401d142015-04-22 13:56:20 -0700875void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700876 CHECK(m->IsNative());
877 mirror::Class* c = m->GetDeclaringClass();
878 // If this is a static method, it could be called before the class has been initialized.
879 CHECK(c->IsInitializing()) << c->GetStatus() << " " << PrettyMethod(m);
880 std::string detail;
881 void* native_method;
882 Thread* self = Thread::Current();
883 {
884 MutexLock mu(self, *Locks::jni_libraries_lock_);
885 native_method = libraries_->FindNativeMethod(m, detail);
886 }
887 // Throwing can cause libraries_lock to be reacquired.
888 if (native_method == nullptr) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000889 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
Ian Rogers68d8b422014-07-17 11:09:10 -0700890 }
891 return native_method;
892}
893
Mathieu Chartier97509952015-07-13 14:35:43 -0700894void JavaVMExt::SweepJniWeakGlobals(IsMarkedVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700895 MutexLock mu(Thread::Current(), weak_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700896 Runtime* const runtime = Runtime::Current();
897 for (auto* entry : weak_globals_) {
898 // Need to skip null here to distinguish between null entries and cleared weak ref entries.
899 if (!entry->IsNull()) {
900 // Since this is called by the GC, we don't need a read barrier.
901 mirror::Object* obj = entry->Read<kWithoutReadBarrier>();
Mathieu Chartier97509952015-07-13 14:35:43 -0700902 mirror::Object* new_obj = visitor->IsMarked(obj);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700903 if (new_obj == nullptr) {
904 new_obj = runtime->GetClearedJniWeakGlobal();
905 }
906 *entry = GcRoot<mirror::Object>(new_obj);
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -0700907 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700908 }
909}
910
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800911void JavaVMExt::TrimGlobals() {
912 WriterMutexLock mu(Thread::Current(), globals_lock_);
913 globals_.Trim();
914}
915
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700916void JavaVMExt::VisitRoots(RootVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700917 Thread* self = Thread::Current();
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800918 ReaderMutexLock mu(self, globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700919 globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal));
Ian Rogers68d8b422014-07-17 11:09:10 -0700920 // The weak_globals table is visited by the GC itself (because it mutates the table).
921}
922
923// JNI Invocation interface.
924
925extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
Richard Uhler054a0782015-04-07 10:56:50 -0700926 ATRACE_BEGIN(__FUNCTION__);
Ian Rogers68d8b422014-07-17 11:09:10 -0700927 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
928 if (IsBadJniVersion(args->version)) {
929 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
Richard Uhler054a0782015-04-07 10:56:50 -0700930 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700931 return JNI_EVERSION;
932 }
933 RuntimeOptions options;
934 for (int i = 0; i < args->nOptions; ++i) {
935 JavaVMOption* option = &args->options[i];
936 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
937 }
938 bool ignore_unrecognized = args->ignoreUnrecognized;
939 if (!Runtime::Create(options, ignore_unrecognized)) {
Richard Uhler054a0782015-04-07 10:56:50 -0700940 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700941 return JNI_ERR;
942 }
943 Runtime* runtime = Runtime::Current();
944 bool started = runtime->Start();
945 if (!started) {
946 delete Thread::Current()->GetJniEnv();
947 delete runtime->GetJavaVM();
948 LOG(WARNING) << "CreateJavaVM failed";
Richard Uhler054a0782015-04-07 10:56:50 -0700949 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700950 return JNI_ERR;
951 }
952 *p_env = Thread::Current()->GetJniEnv();
953 *p_vm = runtime->GetJavaVM();
Richard Uhler054a0782015-04-07 10:56:50 -0700954 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700955 return JNI_OK;
956}
957
Ian Rogersf4d4da12014-11-11 16:10:33 -0800958extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700959 Runtime* runtime = Runtime::Current();
Ian Rogersf4d4da12014-11-11 16:10:33 -0800960 if (runtime == nullptr || buf_len == 0) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700961 *vm_count = 0;
962 } else {
963 *vm_count = 1;
Ian Rogersf4d4da12014-11-11 16:10:33 -0800964 vms_buf[0] = runtime->GetJavaVM();
Ian Rogers68d8b422014-07-17 11:09:10 -0700965 }
966 return JNI_OK;
967}
968
969// Historically unsupported.
970extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
971 return JNI_ERR;
972}
973
974} // namespace art