blob: 58da7f285a337690fabd72ca9ad33e145b737dc1 [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,
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 }
77 }
78
Mathieu Chartier598302a2015-09-23 14:52:39 -070079 jweak GetClassLoader() const {
Ian Rogers68d8b422014-07-17 11:09:10 -070080 return class_loader_;
81 }
82
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080083 const void* GetClassLoaderAllocator() const {
84 return class_loader_allocator_;
85 }
86
Ian Rogers68d8b422014-07-17 11:09:10 -070087 const std::string& GetPath() const {
88 return path_;
89 }
90
91 /*
92 * Check the result of an earlier call to JNI_OnLoad on this library.
93 * If the call has not yet finished in another thread, wait for it.
94 */
95 bool CheckOnLoadResult()
Mathieu Chartier90443472015-07-16 20:32:27 -070096 REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -070097 Thread* self = Thread::Current();
98 bool okay;
99 {
100 MutexLock mu(self, jni_on_load_lock_);
101
102 if (jni_on_load_thread_id_ == self->GetThreadId()) {
103 // Check this so we don't end up waiting for ourselves. We need to return "true" so the
104 // caller can continue.
105 LOG(INFO) << *self << " recursive attempt to load library " << "\"" << path_ << "\"";
106 okay = true;
107 } else {
108 while (jni_on_load_result_ == kPending) {
109 VLOG(jni) << "[" << *self << " waiting for \"" << path_ << "\" " << "JNI_OnLoad...]";
110 jni_on_load_cond_.Wait(self);
111 }
112
113 okay = (jni_on_load_result_ == kOkay);
114 VLOG(jni) << "[Earlier JNI_OnLoad for \"" << path_ << "\" "
115 << (okay ? "succeeded" : "failed") << "]";
116 }
117 }
118 return okay;
119 }
120
Mathieu Chartier90443472015-07-16 20:32:27 -0700121 void SetResult(bool result) REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700122 Thread* self = Thread::Current();
123 MutexLock mu(self, jni_on_load_lock_);
124
125 jni_on_load_result_ = result ? kOkay : kFailed;
126 jni_on_load_thread_id_ = 0;
127
128 // Broadcast a wakeup to anybody sleeping on the condition variable.
129 jni_on_load_cond_.Broadcast(self);
130 }
131
132 void SetNeedsNativeBridge() {
133 needs_native_bridge_ = true;
134 }
135
136 bool NeedsNativeBridge() const {
137 return needs_native_bridge_;
138 }
139
Mathieu Chartier598302a2015-09-23 14:52:39 -0700140 void* FindSymbol(const std::string& symbol_name, const char* shorty = nullptr) {
141 return NeedsNativeBridge()
142 ? FindSymbolWithNativeBridge(symbol_name.c_str(), shorty)
143 : FindSymbolWithoutNativeBridge(symbol_name.c_str());
144 }
145
146 void* FindSymbolWithoutNativeBridge(const std::string& symbol_name) {
Andreas Gampe8fec90b2015-06-30 11:23:44 -0700147 CHECK(!NeedsNativeBridge());
148
Ian Rogers68d8b422014-07-17 11:09:10 -0700149 return dlsym(handle_, symbol_name.c_str());
150 }
151
152 void* FindSymbolWithNativeBridge(const std::string& symbol_name, const char* shorty) {
153 CHECK(NeedsNativeBridge());
154
155 uint32_t len = 0;
Calin Juravlec8423522014-08-12 20:55:20 +0100156 return android::NativeBridgeGetTrampoline(handle_, symbol_name.c_str(), shorty, len);
Ian Rogers68d8b422014-07-17 11:09:10 -0700157 }
158
159 private:
160 enum JNI_OnLoadState {
161 kPending,
162 kFailed,
163 kOkay,
164 };
165
166 // Path to library "/system/lib/libjni.so".
167 const std::string path_;
168
169 // The void* returned by dlopen(3).
170 void* const handle_;
171
172 // True if a native bridge is required.
173 bool needs_native_bridge_;
174
Mathieu Chartier598302a2015-09-23 14:52:39 -0700175 // The ClassLoader this library is associated with, a weak global JNI reference that is
Ian Rogers68d8b422014-07-17 11:09:10 -0700176 // created/deleted with the scope of the library.
Mathieu Chartier598302a2015-09-23 14:52:39 -0700177 const jweak class_loader_;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800178 // Used to do equality check on class loaders so we can avoid decoding the weak root and read
179 // barriers that mess with class unloading.
180 const void* class_loader_allocator_;
Ian Rogers68d8b422014-07-17 11:09:10 -0700181
182 // Guards remaining items.
183 Mutex jni_on_load_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
184 // Wait for JNI_OnLoad in other thread.
185 ConditionVariable jni_on_load_cond_ GUARDED_BY(jni_on_load_lock_);
186 // Recursive invocation guard.
187 uint32_t jni_on_load_thread_id_ GUARDED_BY(jni_on_load_lock_);
188 // Result of earlier JNI_OnLoad call.
189 JNI_OnLoadState jni_on_load_result_ GUARDED_BY(jni_on_load_lock_);
190};
191
192// This exists mainly to keep implementation details out of the header file.
193class Libraries {
194 public:
195 Libraries() {
196 }
197
198 ~Libraries() {
199 STLDeleteValues(&libraries_);
200 }
201
Mathieu Chartier598302a2015-09-23 14:52:39 -0700202 // NO_THREAD_SAFETY_ANALYSIS since this may be called from Dumpable. Dumpable can't be annotated
203 // properly due to the template. The caller should be holding the jni_libraries_lock_.
204 void Dump(std::ostream& os) const NO_THREAD_SAFETY_ANALYSIS {
205 Locks::jni_libraries_lock_->AssertHeld(Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -0700206 bool first = true;
207 for (const auto& library : libraries_) {
208 if (!first) {
209 os << ' ';
210 }
211 first = false;
212 os << library.first;
213 }
214 }
215
Mathieu Chartier598302a2015-09-23 14:52:39 -0700216 size_t size() const REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700217 return libraries_.size();
218 }
219
Mathieu Chartier598302a2015-09-23 14:52:39 -0700220 SharedLibrary* Get(const std::string& path) REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700221 auto it = libraries_.find(path);
222 return (it == libraries_.end()) ? nullptr : it->second;
223 }
224
Mathieu Chartier598302a2015-09-23 14:52:39 -0700225 void Put(const std::string& path, SharedLibrary* library)
226 REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700227 libraries_.Put(path, library);
228 }
229
230 // See section 11.3 "Linking Native Methods" of the JNI spec.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700231 void* FindNativeMethod(ArtMethod* m, std::string& detail)
Mathieu Chartier90443472015-07-16 20:32:27 -0700232 REQUIRES(Locks::jni_libraries_lock_)
233 SHARED_REQUIRES(Locks::mutator_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700234 std::string jni_short_name(JniShortName(m));
235 std::string jni_long_name(JniLongName(m));
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800236 mirror::ClassLoader* const declaring_class_loader = m->GetDeclaringClass()->GetClassLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700237 ScopedObjectAccessUnchecked soa(Thread::Current());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800238 void* const declaring_class_loader_allocator =
239 Runtime::Current()->GetClassLinker()->GetAllocatorForClassLoader(declaring_class_loader);
240 CHECK(declaring_class_loader_allocator != nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700241 for (const auto& lib : libraries_) {
Mathieu Chartier598302a2015-09-23 14:52:39 -0700242 SharedLibrary* const library = lib.second;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800243 // Use the allocator address for class loader equality to avoid unnecessary weak root decode.
244 if (library->GetClassLoaderAllocator() != declaring_class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700245 // We only search libraries loaded by the appropriate ClassLoader.
246 continue;
247 }
248 // Try the short name then the long name...
Mathieu Chartier598302a2015-09-23 14:52:39 -0700249 const char* shorty = library->NeedsNativeBridge()
250 ? m->GetShorty()
251 : nullptr;
252 void* fn = library->FindSymbol(jni_short_name, shorty);
253 if (fn == nullptr) {
254 fn = library->FindSymbol(jni_long_name, shorty);
Ian Rogers68d8b422014-07-17 11:09:10 -0700255 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700256 if (fn != nullptr) {
257 VLOG(jni) << "[Found native code for " << PrettyMethod(m)
258 << " in \"" << library->GetPath() << "\"]";
259 return fn;
260 }
261 }
262 detail += "No implementation found for ";
263 detail += PrettyMethod(m);
264 detail += " (tried " + jni_short_name + " and " + jni_long_name + ")";
265 LOG(ERROR) << detail;
266 return nullptr;
267 }
268
Mathieu Chartier598302a2015-09-23 14:52:39 -0700269 // Unload native libraries with cleared class loaders.
270 void UnloadNativeLibraries()
271 REQUIRES(!Locks::jni_libraries_lock_)
272 SHARED_REQUIRES(Locks::mutator_lock_) {
273 ScopedObjectAccessUnchecked soa(Thread::Current());
274 typedef void (*JNI_OnUnloadFn)(JavaVM*, void*);
275 std::vector<JNI_OnUnloadFn> unload_functions;
276 {
277 MutexLock mu(soa.Self(), *Locks::jni_libraries_lock_);
278 for (auto it = libraries_.begin(); it != libraries_.end(); ) {
279 SharedLibrary* const library = it->second;
280 // If class loader is null then it was unloaded, call JNI_OnUnload.
Mathieu Chartiercffb7472015-09-28 10:33:00 -0700281 const jweak class_loader = library->GetClassLoader();
282 // If class_loader is a null jobject then it is the boot class loader. We should not unload
283 // the native libraries of the boot class loader.
284 if (class_loader != nullptr &&
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800285 soa.Self()->IsJWeakCleared(class_loader)) {
Mathieu Chartier598302a2015-09-23 14:52:39 -0700286 void* const sym = library->FindSymbol("JNI_OnUnload", nullptr);
287 if (sym == nullptr) {
288 VLOG(jni) << "[No JNI_OnUnload found in \"" << library->GetPath() << "\"]";
289 } else {
290 VLOG(jni) << "[JNI_OnUnload found for \"" << library->GetPath() << "\"]";
291 JNI_OnUnloadFn jni_on_unload = reinterpret_cast<JNI_OnUnloadFn>(sym);
292 unload_functions.push_back(jni_on_unload);
293 }
294 delete library;
295 it = libraries_.erase(it);
296 } else {
297 ++it;
298 }
299 }
300 }
301 // Do this without holding the jni libraries lock to prevent possible deadlocks.
302 for (JNI_OnUnloadFn fn : unload_functions) {
303 VLOG(jni) << "Calling JNI_OnUnload";
304 (*fn)(soa.Vm(), nullptr);
305 }
306 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700307
Mathieu Chartier598302a2015-09-23 14:52:39 -0700308 private:
309 AllocationTrackingSafeMap<std::string, SharedLibrary*, kAllocatorTagJNILibraries> libraries_
310 GUARDED_BY(Locks::jni_libraries_lock_);
311};
Ian Rogers68d8b422014-07-17 11:09:10 -0700312
313class JII {
314 public:
315 static jint DestroyJavaVM(JavaVM* vm) {
316 if (vm == nullptr) {
317 return JNI_ERR;
318 }
319 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
320 delete raw_vm->GetRuntime();
321 return JNI_OK;
322 }
323
324 static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
325 return AttachCurrentThreadInternal(vm, p_env, thr_args, false);
326 }
327
328 static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
329 return AttachCurrentThreadInternal(vm, p_env, thr_args, true);
330 }
331
332 static jint DetachCurrentThread(JavaVM* vm) {
333 if (vm == nullptr || Thread::Current() == nullptr) {
334 return JNI_ERR;
335 }
336 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
337 Runtime* runtime = raw_vm->GetRuntime();
338 runtime->DetachCurrentThread();
339 return JNI_OK;
340 }
341
342 static jint GetEnv(JavaVM* vm, void** env, jint version) {
343 // GetEnv always returns a JNIEnv* for the most current supported JNI version,
344 // and unlike other calls that take a JNI version doesn't care if you supply
345 // JNI_VERSION_1_1, which we don't otherwise support.
346 if (IsBadJniVersion(version) && version != JNI_VERSION_1_1) {
347 LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version;
348 return JNI_EVERSION;
349 }
350 if (vm == nullptr || env == nullptr) {
351 return JNI_ERR;
352 }
353 Thread* thread = Thread::Current();
354 if (thread == nullptr) {
355 *env = nullptr;
356 return JNI_EDETACHED;
357 }
358 *env = thread->GetJniEnv();
359 return JNI_OK;
360 }
361
362 private:
363 static jint AttachCurrentThreadInternal(JavaVM* vm, JNIEnv** p_env, void* raw_args, bool as_daemon) {
364 if (vm == nullptr || p_env == nullptr) {
365 return JNI_ERR;
366 }
367
368 // Return immediately if we're already attached.
369 Thread* self = Thread::Current();
370 if (self != nullptr) {
371 *p_env = self->GetJniEnv();
372 return JNI_OK;
373 }
374
375 Runtime* runtime = reinterpret_cast<JavaVMExt*>(vm)->GetRuntime();
376
377 // No threads allowed in zygote mode.
378 if (runtime->IsZygote()) {
379 LOG(ERROR) << "Attempt to attach a thread in the zygote";
380 return JNI_ERR;
381 }
382
383 JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(raw_args);
384 const char* thread_name = nullptr;
385 jobject thread_group = nullptr;
386 if (args != nullptr) {
387 if (IsBadJniVersion(args->version)) {
388 LOG(ERROR) << "Bad JNI version passed to "
389 << (as_daemon ? "AttachCurrentThreadAsDaemon" : "AttachCurrentThread") << ": "
390 << args->version;
391 return JNI_EVERSION;
392 }
393 thread_name = args->name;
394 thread_group = args->group;
395 }
396
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800397 if (!runtime->AttachCurrentThread(thread_name, as_daemon, thread_group,
398 !runtime->IsAotCompiler())) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700399 *p_env = nullptr;
400 return JNI_ERR;
401 } else {
402 *p_env = Thread::Current()->GetJniEnv();
403 return JNI_OK;
404 }
405 }
406};
407
408const JNIInvokeInterface gJniInvokeInterface = {
409 nullptr, // reserved0
410 nullptr, // reserved1
411 nullptr, // reserved2
412 JII::DestroyJavaVM,
413 JII::AttachCurrentThread,
414 JII::DetachCurrentThread,
415 JII::GetEnv,
416 JII::AttachCurrentThreadAsDaemon
417};
418
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800419JavaVMExt::JavaVMExt(Runtime* runtime, const RuntimeArgumentMap& runtime_options)
Ian Rogers68d8b422014-07-17 11:09:10 -0700420 : runtime_(runtime),
421 check_jni_abort_hook_(nullptr),
422 check_jni_abort_hook_data_(nullptr),
423 check_jni_(false), // Initialized properly in the constructor body below.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800424 force_copy_(runtime_options.Exists(RuntimeArgumentMap::JniOptsForceCopy)),
425 tracing_enabled_(runtime_options.Exists(RuntimeArgumentMap::JniTrace)
426 || VLOG_IS_ON(third_party_jni)),
427 trace_(runtime_options.GetOrDefault(RuntimeArgumentMap::JniTrace)),
Ian Rogers68d8b422014-07-17 11:09:10 -0700428 globals_lock_("JNI global reference table lock"),
429 globals_(gGlobalsInitial, gGlobalsMax, kGlobal),
430 libraries_(new Libraries),
431 unchecked_functions_(&gJniInvokeInterface),
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700432 weak_globals_lock_("JNI weak global reference table lock", kJniWeakGlobalsLock),
Ian Rogers68d8b422014-07-17 11:09:10 -0700433 weak_globals_(kWeakGlobalsInitial, kWeakGlobalsMax, kWeakGlobal),
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700434 allow_accessing_weak_globals_(true),
Ian Rogers68d8b422014-07-17 11:09:10 -0700435 weak_globals_add_condition_("weak globals add condition", weak_globals_lock_) {
436 functions = unchecked_functions_;
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800437 SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni));
Ian Rogers68d8b422014-07-17 11:09:10 -0700438}
439
440JavaVMExt::~JavaVMExt() {
441}
442
443void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) {
444 Thread* self = Thread::Current();
445 ScopedObjectAccess soa(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700446 ArtMethod* current_method = self->GetCurrentMethod(nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700447
448 std::ostringstream os;
449 os << "JNI DETECTED ERROR IN APPLICATION: " << msg;
450
451 if (jni_function_name != nullptr) {
452 os << "\n in call to " << jni_function_name;
453 }
454 // TODO: is this useful given that we're about to dump the calling thread's stack?
455 if (current_method != nullptr) {
456 os << "\n from " << PrettyMethod(current_method);
457 }
458 os << "\n";
459 self->Dump(os);
460
461 if (check_jni_abort_hook_ != nullptr) {
462 check_jni_abort_hook_(check_jni_abort_hook_data_, os.str());
463 } else {
464 // Ensure that we get a native stack trace for this thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700465 ScopedThreadSuspension sts(self, kNative);
Ian Rogers68d8b422014-07-17 11:09:10 -0700466 LOG(FATAL) << os.str();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700467 UNREACHABLE();
Ian Rogers68d8b422014-07-17 11:09:10 -0700468 }
469}
470
471void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) {
472 std::string msg;
473 StringAppendV(&msg, fmt, ap);
474 JniAbort(jni_function_name, msg.c_str());
475}
476
477void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) {
478 va_list args;
479 va_start(args, fmt);
480 JniAbortV(jni_function_name, fmt, args);
481 va_end(args);
482}
483
Mathieu Chartiere401d142015-04-22 13:56:20 -0700484bool JavaVMExt::ShouldTrace(ArtMethod* method) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700485 // Fast where no tracing is enabled.
486 if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) {
487 return false;
488 }
489 // Perform checks based on class name.
490 StringPiece class_name(method->GetDeclaringClassDescriptor());
491 if (!trace_.empty() && class_name.find(trace_) != std::string::npos) {
492 return true;
493 }
494 if (!VLOG_IS_ON(third_party_jni)) {
495 return false;
496 }
497 // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
498 // like part of Android.
499 static const char* gBuiltInPrefixes[] = {
500 "Landroid/",
501 "Lcom/android/",
502 "Lcom/google/android/",
503 "Ldalvik/",
504 "Ljava/",
505 "Ljavax/",
506 "Llibcore/",
507 "Lorg/apache/harmony/",
508 };
509 for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) {
510 if (class_name.starts_with(gBuiltInPrefixes[i])) {
511 return false;
512 }
513 }
514 return true;
515}
516
517jobject JavaVMExt::AddGlobalRef(Thread* self, mirror::Object* obj) {
518 // Check for null after decoding the object to handle cleared weak globals.
519 if (obj == nullptr) {
520 return nullptr;
521 }
522 WriterMutexLock mu(self, globals_lock_);
523 IndirectRef ref = globals_.Add(IRT_FIRST_SEGMENT, obj);
524 return reinterpret_cast<jobject>(ref);
525}
526
527jweak JavaVMExt::AddWeakGlobalRef(Thread* self, mirror::Object* obj) {
528 if (obj == nullptr) {
529 return nullptr;
530 }
531 MutexLock mu(self, weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700532 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700533 weak_globals_add_condition_.WaitHoldingLocks(self);
534 }
535 IndirectRef ref = weak_globals_.Add(IRT_FIRST_SEGMENT, obj);
536 return reinterpret_cast<jweak>(ref);
537}
538
539void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
540 if (obj == nullptr) {
541 return;
542 }
543 WriterMutexLock mu(self, globals_lock_);
544 if (!globals_.Remove(IRT_FIRST_SEGMENT, obj)) {
545 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
546 << "failed to find entry";
547 }
548}
549
550void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
551 if (obj == nullptr) {
552 return;
553 }
554 MutexLock mu(self, weak_globals_lock_);
555 if (!weak_globals_.Remove(IRT_FIRST_SEGMENT, obj)) {
556 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
557 << "failed to find entry";
558 }
559}
560
561static void ThreadEnableCheckJni(Thread* thread, void* arg) {
562 bool* check_jni = reinterpret_cast<bool*>(arg);
563 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
564}
565
566bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
567 bool old_check_jni = check_jni_;
568 check_jni_ = enabled;
569 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
570 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
571 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
572 return old_check_jni;
573}
574
575void JavaVMExt::DumpForSigQuit(std::ostream& os) {
576 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
577 if (force_copy_) {
578 os << " (with forcecopy)";
579 }
580 Thread* self = Thread::Current();
581 {
Ian Rogers68d8b422014-07-17 11:09:10 -0700582 ReaderMutexLock mu(self, globals_lock_);
583 os << "; globals=" << globals_.Capacity();
584 }
585 {
586 MutexLock mu(self, weak_globals_lock_);
587 if (weak_globals_.Capacity() > 0) {
588 os << " (plus " << weak_globals_.Capacity() << " weak)";
589 }
590 }
591 os << '\n';
592
593 {
594 MutexLock mu(self, *Locks::jni_libraries_lock_);
595 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
596 }
597}
598
599void JavaVMExt::DisallowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700600 CHECK(!kUseReadBarrier);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700601 Thread* const self = Thread::Current();
602 MutexLock mu(self, weak_globals_lock_);
603 // DisallowNewWeakGlobals is only called by CMS during the pause. It is required to have the
604 // mutator lock exclusively held so that we don't have any threads in the middle of
605 // DecodeWeakGlobal.
606 Locks::mutator_lock_->AssertExclusiveHeld(self);
607 allow_accessing_weak_globals_.StoreSequentiallyConsistent(false);
Ian Rogers68d8b422014-07-17 11:09:10 -0700608}
609
610void JavaVMExt::AllowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700611 CHECK(!kUseReadBarrier);
Ian Rogers68d8b422014-07-17 11:09:10 -0700612 Thread* self = Thread::Current();
613 MutexLock mu(self, weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700614 allow_accessing_weak_globals_.StoreSequentiallyConsistent(true);
Ian Rogers68d8b422014-07-17 11:09:10 -0700615 weak_globals_add_condition_.Broadcast(self);
616}
617
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700618void JavaVMExt::BroadcastForNewWeakGlobals() {
619 CHECK(kUseReadBarrier);
620 Thread* self = Thread::Current();
621 MutexLock mu(self, weak_globals_lock_);
622 weak_globals_add_condition_.Broadcast(self);
623}
624
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700625mirror::Object* JavaVMExt::DecodeGlobal(IndirectRef ref) {
626 return globals_.SynchronizedGet(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700627}
628
Jeff Hao83c81952015-05-27 19:29:29 -0700629void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, mirror::Object* result) {
630 WriterMutexLock mu(self, globals_lock_);
631 globals_.Update(ref, result);
632}
633
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700634inline bool JavaVMExt::MayAccessWeakGlobals(Thread* self) const {
635 return MayAccessWeakGlobalsUnlocked(self);
636}
637
638inline bool JavaVMExt::MayAccessWeakGlobalsUnlocked(Thread* self) const {
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700639 DCHECK(self != nullptr);
640 return kUseReadBarrier ?
641 self->GetWeakRefAccessEnabled() :
642 allow_accessing_weak_globals_.LoadSequentiallyConsistent();
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700643}
644
Ian Rogers68d8b422014-07-17 11:09:10 -0700645mirror::Object* JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700646 // It is safe to access GetWeakRefAccessEnabled without the lock since CC uses checkpoints to call
647 // SetWeakRefAccessEnabled, and the other collectors only modify allow_accessing_weak_globals_
648 // when the mutators are paused.
649 // This only applies in the case where MayAccessWeakGlobals goes from false to true. In the other
650 // case, it may be racy, this is benign since DecodeWeakGlobalLocked does the correct behavior
651 // if MayAccessWeakGlobals is false.
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -0700652 DCHECK_EQ(GetIndirectRefKind(ref), kWeakGlobal);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700653 if (LIKELY(MayAccessWeakGlobalsUnlocked(self))) {
654 return weak_globals_.SynchronizedGet(ref);
655 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700656 MutexLock mu(self, weak_globals_lock_);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700657 return DecodeWeakGlobalLocked(self, ref);
658}
659
660mirror::Object* JavaVMExt::DecodeWeakGlobalLocked(Thread* self, IndirectRef ref) {
661 if (kDebugLocking) {
662 weak_globals_lock_.AssertHeld(self);
663 }
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700664 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700665 weak_globals_add_condition_.WaitHoldingLocks(self);
666 }
667 return weak_globals_.Get(ref);
668}
669
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700670mirror::Object* JavaVMExt::DecodeWeakGlobalDuringShutdown(Thread* self, IndirectRef ref) {
671 DCHECK_EQ(GetIndirectRefKind(ref), kWeakGlobal);
672 DCHECK(Runtime::Current()->IsShuttingDown(self));
673 if (self != nullptr) {
674 return DecodeWeakGlobal(self, ref);
675 }
676 // self can be null during a runtime shutdown. ~Runtime()->~ClassLinker()->DecodeWeakGlobal().
677 if (!kUseReadBarrier) {
678 DCHECK(allow_accessing_weak_globals_.LoadSequentiallyConsistent());
679 }
680 return weak_globals_.SynchronizedGet(ref);
681}
682
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800683bool JavaVMExt::IsWeakGlobalCleared(Thread* self, IndirectRef ref) {
684 DCHECK_EQ(GetIndirectRefKind(ref), kWeakGlobal);
685 MutexLock mu(self, weak_globals_lock_);
686 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
687 weak_globals_add_condition_.WaitHoldingLocks(self);
688 }
689 // When just checking a weak ref has been cleared, avoid triggering the read barrier in decode
690 // (DecodeWeakGlobal) so that we won't accidentally mark the object alive. Since the cleared
691 // sentinel is a non-moving object, we can compare the ref to it without the read barrier and
692 // decide if it's cleared.
693 return Runtime::Current()->IsClearedJniWeakGlobal(weak_globals_.Get<kWithoutReadBarrier>(ref));
694}
695
Jeff Hao83c81952015-05-27 19:29:29 -0700696void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, mirror::Object* result) {
697 MutexLock mu(self, weak_globals_lock_);
698 weak_globals_.Update(ref, result);
699}
700
Ian Rogers68d8b422014-07-17 11:09:10 -0700701void JavaVMExt::DumpReferenceTables(std::ostream& os) {
702 Thread* self = Thread::Current();
703 {
704 ReaderMutexLock mu(self, globals_lock_);
705 globals_.Dump(os);
706 }
707 {
708 MutexLock mu(self, weak_globals_lock_);
709 weak_globals_.Dump(os);
710 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700711}
712
Mathieu Chartier598302a2015-09-23 14:52:39 -0700713void JavaVMExt::UnloadNativeLibraries() {
714 libraries_.get()->UnloadNativeLibraries();
715}
716
Ian Rogers68d8b422014-07-17 11:09:10 -0700717bool JavaVMExt::LoadNativeLibrary(JNIEnv* env, const std::string& path, jobject class_loader,
718 std::string* error_msg) {
719 error_msg->clear();
720
721 // See if we've already loaded this library. If we have, and the class loader
722 // matches, return successfully without doing anything.
723 // TODO: for better results we should canonicalize the pathname (or even compare
724 // inodes). This implementation is fine if everybody is using System.loadLibrary.
725 SharedLibrary* library;
726 Thread* self = Thread::Current();
727 {
728 // TODO: move the locking (and more of this logic) into Libraries.
729 MutexLock mu(self, *Locks::jni_libraries_lock_);
730 library = libraries_->Get(path);
731 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800732 void* class_loader_allocator = nullptr;
733 {
734 ScopedObjectAccess soa(env);
735 // As the incoming class loader is reachable/alive during the call of this function,
736 // it's okay to decode it without worrying about unexpectedly marking it alive.
737 mirror::ClassLoader* loader = soa.Decode<mirror::ClassLoader*>(class_loader);
738 class_loader_allocator =
Mathieu Chartier2d902b92015-11-24 16:22:54 -0800739 Runtime::Current()->GetClassLinker()->GetOrCreateAllocatorForClassLoader(loader);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800740 CHECK(class_loader_allocator != nullptr);
741 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700742 if (library != nullptr) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800743 // Use the allocator pointers for class loader equality to avoid unnecessary weak root decode.
744 if (library->GetClassLoaderAllocator() != class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700745 // The library will be associated with class_loader. The JNI
746 // spec says we can't load the same library into more than one
747 // class loader.
748 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
749 "ClassLoader %p; can't open in ClassLoader %p",
750 path.c_str(), library->GetClassLoader(), class_loader);
751 LOG(WARNING) << error_msg;
752 return false;
753 }
754 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
755 << " ClassLoader " << class_loader << "]";
756 if (!library->CheckOnLoadResult()) {
757 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
758 "to load \"%s\"", path.c_str());
759 return false;
760 }
761 return true;
762 }
763
764 // Open the shared library. Because we're using a full path, the system
765 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
766 // resolve this library's dependencies though.)
767
768 // Failures here are expected when java.library.path has several entries
769 // and we have to hunt for the lib.
770
771 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
772 // class unloading. Libraries will only be unloaded when the reference count (incremented by
773 // dlopen) becomes zero from dlclose.
774
775 Locks::mutator_lock_->AssertNotHeld(self);
776 const char* path_str = path.empty() ? nullptr : path.c_str();
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700777 void* handle = dlopen(path_str, RTLD_NOW);
Ian Rogers68d8b422014-07-17 11:09:10 -0700778 bool needs_native_bridge = false;
779 if (handle == nullptr) {
Calin Juravlec8423522014-08-12 20:55:20 +0100780 if (android::NativeBridgeIsSupported(path_str)) {
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700781 handle = android::NativeBridgeLoadLibrary(path_str, RTLD_NOW);
Ian Rogers68d8b422014-07-17 11:09:10 -0700782 needs_native_bridge = true;
783 }
784 }
785
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700786 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]";
Ian Rogers68d8b422014-07-17 11:09:10 -0700787
788 if (handle == nullptr) {
789 *error_msg = dlerror();
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700790 VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700791 return false;
792 }
793
794 if (env->ExceptionCheck() == JNI_TRUE) {
795 LOG(ERROR) << "Unexpected exception:";
796 env->ExceptionDescribe();
797 env->ExceptionClear();
798 }
799 // Create a new entry.
800 // TODO: move the locking (and more of this logic) into Libraries.
801 bool created_library = false;
802 {
803 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
804 std::unique_ptr<SharedLibrary> new_library(
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800805 new SharedLibrary(env, self, path, handle, class_loader, class_loader_allocator));
Ian Rogers68d8b422014-07-17 11:09:10 -0700806 MutexLock mu(self, *Locks::jni_libraries_lock_);
807 library = libraries_->Get(path);
808 if (library == nullptr) { // We won race to get libraries_lock.
809 library = new_library.release();
810 libraries_->Put(path, library);
811 created_library = true;
812 }
813 }
814 if (!created_library) {
815 LOG(INFO) << "WOW: we lost a race to add shared library: "
816 << "\"" << path << "\" ClassLoader=" << class_loader;
817 return library->CheckOnLoadResult();
818 }
819 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
820
821 bool was_successful = false;
822 void* sym;
823 if (needs_native_bridge) {
824 library->SetNeedsNativeBridge();
Ian Rogers68d8b422014-07-17 11:09:10 -0700825 }
Mathieu Chartier598302a2015-09-23 14:52:39 -0700826 sym = library->FindSymbol("JNI_OnLoad", nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700827 if (sym == nullptr) {
828 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
829 was_successful = true;
830 } else {
831 // Call JNI_OnLoad. We have to override the current class
832 // loader, which will always be "null" since the stuff at the
833 // top of the stack is around Runtime.loadLibrary(). (See
834 // the comments in the JNI FindClass function.)
835 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
836 self->SetClassLoaderOverride(class_loader);
837
838 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
839 typedef int (*JNI_OnLoadFn)(JavaVM*, void*);
840 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
841 int version = (*jni_on_load)(this, nullptr);
842
Mathieu Chartierd0004802014-10-15 16:59:47 -0700843 if (runtime_->GetTargetSdkVersion() != 0 && runtime_->GetTargetSdkVersion() <= 21) {
844 fault_manager.EnsureArtActionInFrontOfSignalChain();
845 }
846
Ian Rogers68d8b422014-07-17 11:09:10 -0700847 self->SetClassLoaderOverride(old_class_loader.get());
848
849 if (version == JNI_ERR) {
850 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
851 } else if (IsBadJniVersion(version)) {
852 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
853 path.c_str(), version);
854 // It's unwise to call dlclose() here, but we can mark it
855 // as bad and ensure that future load attempts will fail.
856 // We don't know how far JNI_OnLoad got, so there could
857 // be some partially-initialized stuff accessible through
858 // newly-registered native method calls. We could try to
859 // unregister them, but that doesn't seem worthwhile.
860 } else {
861 was_successful = true;
862 }
863 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
864 << " from JNI_OnLoad in \"" << path << "\"]";
865 }
866
867 library->SetResult(was_successful);
868 return was_successful;
869}
870
Mathieu Chartiere401d142015-04-22 13:56:20 -0700871void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700872 CHECK(m->IsNative());
873 mirror::Class* c = m->GetDeclaringClass();
874 // If this is a static method, it could be called before the class has been initialized.
875 CHECK(c->IsInitializing()) << c->GetStatus() << " " << PrettyMethod(m);
876 std::string detail;
877 void* native_method;
878 Thread* self = Thread::Current();
879 {
880 MutexLock mu(self, *Locks::jni_libraries_lock_);
881 native_method = libraries_->FindNativeMethod(m, detail);
882 }
883 // Throwing can cause libraries_lock to be reacquired.
884 if (native_method == nullptr) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000885 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
Ian Rogers68d8b422014-07-17 11:09:10 -0700886 }
887 return native_method;
888}
889
Mathieu Chartier97509952015-07-13 14:35:43 -0700890void JavaVMExt::SweepJniWeakGlobals(IsMarkedVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700891 MutexLock mu(Thread::Current(), weak_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700892 Runtime* const runtime = Runtime::Current();
893 for (auto* entry : weak_globals_) {
894 // Need to skip null here to distinguish between null entries and cleared weak ref entries.
895 if (!entry->IsNull()) {
896 // Since this is called by the GC, we don't need a read barrier.
897 mirror::Object* obj = entry->Read<kWithoutReadBarrier>();
Mathieu Chartier97509952015-07-13 14:35:43 -0700898 mirror::Object* new_obj = visitor->IsMarked(obj);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700899 if (new_obj == nullptr) {
900 new_obj = runtime->GetClearedJniWeakGlobal();
901 }
902 *entry = GcRoot<mirror::Object>(new_obj);
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -0700903 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700904 }
905}
906
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800907void JavaVMExt::TrimGlobals() {
908 WriterMutexLock mu(Thread::Current(), globals_lock_);
909 globals_.Trim();
910}
911
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700912void JavaVMExt::VisitRoots(RootVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700913 Thread* self = Thread::Current();
Mathieu Chartiere34fa1d2015-01-14 14:55:47 -0800914 ReaderMutexLock mu(self, globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700915 globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal));
Ian Rogers68d8b422014-07-17 11:09:10 -0700916 // The weak_globals table is visited by the GC itself (because it mutates the table).
917}
918
919// JNI Invocation interface.
920
921extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
Richard Uhler054a0782015-04-07 10:56:50 -0700922 ATRACE_BEGIN(__FUNCTION__);
Ian Rogers68d8b422014-07-17 11:09:10 -0700923 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
924 if (IsBadJniVersion(args->version)) {
925 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
Richard Uhler054a0782015-04-07 10:56:50 -0700926 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700927 return JNI_EVERSION;
928 }
929 RuntimeOptions options;
930 for (int i = 0; i < args->nOptions; ++i) {
931 JavaVMOption* option = &args->options[i];
932 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
933 }
934 bool ignore_unrecognized = args->ignoreUnrecognized;
935 if (!Runtime::Create(options, ignore_unrecognized)) {
Richard Uhler054a0782015-04-07 10:56:50 -0700936 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700937 return JNI_ERR;
938 }
939 Runtime* runtime = Runtime::Current();
940 bool started = runtime->Start();
941 if (!started) {
942 delete Thread::Current()->GetJniEnv();
943 delete runtime->GetJavaVM();
944 LOG(WARNING) << "CreateJavaVM failed";
Richard Uhler054a0782015-04-07 10:56:50 -0700945 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700946 return JNI_ERR;
947 }
948 *p_env = Thread::Current()->GetJniEnv();
949 *p_vm = runtime->GetJavaVM();
Richard Uhler054a0782015-04-07 10:56:50 -0700950 ATRACE_END();
Ian Rogers68d8b422014-07-17 11:09:10 -0700951 return JNI_OK;
952}
953
Ian Rogersf4d4da12014-11-11 16:10:33 -0800954extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700955 Runtime* runtime = Runtime::Current();
Ian Rogersf4d4da12014-11-11 16:10:33 -0800956 if (runtime == nullptr || buf_len == 0) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700957 *vm_count = 0;
958 } else {
959 *vm_count = 1;
Ian Rogersf4d4da12014-11-11 16:10:33 -0800960 vms_buf[0] = runtime->GetJavaVM();
Ian Rogers68d8b422014-07-17 11:09:10 -0700961 }
962 return JNI_OK;
963}
964
965// Historically unsupported.
966extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
967 return JNI_ERR;
968}
969
970} // namespace art