blob: df96d2801e6c7af70bf272aad8bc02bd37e537cf [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
Andreas Gampe57cf00b2017-06-05 17:15:32 -070017#include "java_vm_ext.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070018
19#include <dlfcn.h>
Vladimir Marko72101082019-02-05 16:16:30 +000020#include <string_view>
Ian Rogers68d8b422014-07-17 11:09:10 -070021
Andreas Gampe46ee31b2016-12-14 10:11:49 -080022#include "android-base/stringprintf.h"
23
Andreas Gampec6ea7d02017-02-01 16:46:28 -080024#include "art_method-inl.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070025#include "base/dumpable.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070026#include "base/mutex-inl.h"
David Brazdil2bb2fbd2018-11-13 18:24:26 +000027#include "base/sdk_version.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070028#include "base/stl_util.h"
Vladimir Marko72101082019-02-05 16:16:30 +000029#include "base/string_view_cpp20.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080030#include "base/systrace.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070031#include "check_jni.h"
David Sehr9e734c72018-01-04 17:56:19 -080032#include "dex/dex_file-inl.h"
Mathieu Chartierd0004802014-10-15 16:59:47 -070033#include "fault_handler.h"
Andreas Gampe1b35b462017-09-29 18:52:15 -070034#include "gc/allocation_record.h"
35#include "gc/heap.h"
Andreas Gamped4901292017-05-30 18:41:34 -070036#include "gc_root-inl.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070037#include "indirect_reference_table-inl.h"
Andreas Gampe57cf00b2017-06-05 17:15:32 -070038#include "jni_internal.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070039#include "mirror/class-inl.h"
40#include "mirror/class_loader.h"
Calin Juravlec8423522014-08-12 20:55:20 +010041#include "nativebridge/native_bridge.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070042#include "nativehelper/scoped_local_ref.h"
43#include "nativehelper/scoped_utf_chars.h"
Dmitriy Ivanovf5a30992015-11-11 14:18:55 -080044#include "nativeloader/native_loader.h"
Andreas Gampe57cf00b2017-06-05 17:15:32 -070045#include "object_callbacks.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070046#include "parsed_options.h"
Ian Rogersc0542af2014-09-03 16:16:56 -070047#include "runtime-inl.h"
Igor Murashkinaaebaa02015-01-26 10:55:53 -080048#include "runtime_options.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070049#include "scoped_thread_state_change-inl.h"
Josh Gao85a78cf2017-03-20 16:26:42 -070050#include "sigchain.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070051#include "thread-inl.h"
52#include "thread_list.h"
Steven Morelande431e272017-07-18 16:53:49 -070053#include "ti/agent.h"
Andreas Gampe473191c2017-12-28 16:55:31 -080054#include "well_known_classes.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070055
56namespace art {
57
Andreas Gampe46ee31b2016-12-14 10:11:49 -080058using android::base::StringAppendF;
59using android::base::StringAppendV;
60
Andreas Gampea8e3b862016-10-17 20:12:52 -070061static constexpr size_t kGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
Ian Rogers68d8b422014-07-17 11:09:10 -070062
Andreas Gampea8e3b862016-10-17 20:12:52 -070063static constexpr size_t kWeakGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
Ian Rogers68d8b422014-07-17 11:09:10 -070064
Alex Light185d1342016-08-11 10:48:03 -070065bool JavaVMExt::IsBadJniVersion(int version) {
Ian Rogers68d8b422014-07-17 11:09:10 -070066 // We don't support JNI_VERSION_1_1. These are the only other valid versions.
67 return version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 && version != JNI_VERSION_1_6;
68}
69
70class SharedLibrary {
71 public:
72 SharedLibrary(JNIEnv* env, Thread* self, const std::string& path, void* handle,
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080073 bool needs_native_bridge, jobject class_loader, void* class_loader_allocator)
Ian Rogers68d8b422014-07-17 11:09:10 -070074 : path_(path),
75 handle_(handle),
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080076 needs_native_bridge_(needs_native_bridge),
Mathieu Chartier598302a2015-09-23 14:52:39 -070077 class_loader_(env->NewWeakGlobalRef(class_loader)),
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080078 class_loader_allocator_(class_loader_allocator),
Ian Rogers68d8b422014-07-17 11:09:10 -070079 jni_on_load_lock_("JNI_OnLoad lock"),
80 jni_on_load_cond_("JNI_OnLoad condition variable", jni_on_load_lock_),
81 jni_on_load_thread_id_(self->GetThreadId()),
82 jni_on_load_result_(kPending) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080083 CHECK(class_loader_allocator_ != nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -070084 }
85
86 ~SharedLibrary() {
87 Thread* self = Thread::Current();
88 if (self != nullptr) {
Mathieu Chartier598302a2015-09-23 14:52:39 -070089 self->GetJniEnv()->DeleteWeakGlobalRef(class_loader_);
Ian Rogers68d8b422014-07-17 11:09:10 -070090 }
Alex Lightbc5669e2016-06-13 17:22:13 +000091
Nicolas Geoffrayd9b30692019-01-12 14:59:05 +000092 char* error_msg = nullptr;
dimitry947573e2018-09-12 01:12:56 +020093 if (!android::CloseNativeLibrary(handle_, needs_native_bridge_, &error_msg)) {
94 LOG(WARNING) << "Error while unloading native library \"" << path_ << "\": " << error_msg;
Nicolas Geoffrayd9b30692019-01-12 14:59:05 +000095 android::NativeLoaderFreeErrorMessage(error_msg);
dimitry947573e2018-09-12 01:12:56 +020096 }
Ian Rogers68d8b422014-07-17 11:09:10 -070097 }
98
Mathieu Chartier598302a2015-09-23 14:52:39 -070099 jweak GetClassLoader() const {
Ian Rogers68d8b422014-07-17 11:09:10 -0700100 return class_loader_;
101 }
102
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800103 const void* GetClassLoaderAllocator() const {
104 return class_loader_allocator_;
105 }
106
Ian Rogers68d8b422014-07-17 11:09:10 -0700107 const std::string& GetPath() const {
108 return path_;
109 }
110
111 /*
112 * Check the result of an earlier call to JNI_OnLoad on this library.
113 * If the call has not yet finished in another thread, wait for it.
114 */
115 bool CheckOnLoadResult()
Mathieu Chartier90443472015-07-16 20:32:27 -0700116 REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700117 Thread* self = Thread::Current();
118 bool okay;
119 {
120 MutexLock mu(self, jni_on_load_lock_);
121
122 if (jni_on_load_thread_id_ == self->GetThreadId()) {
123 // Check this so we don't end up waiting for ourselves. We need to return "true" so the
124 // caller can continue.
125 LOG(INFO) << *self << " recursive attempt to load library " << "\"" << path_ << "\"";
126 okay = true;
127 } else {
128 while (jni_on_load_result_ == kPending) {
129 VLOG(jni) << "[" << *self << " waiting for \"" << path_ << "\" " << "JNI_OnLoad...]";
130 jni_on_load_cond_.Wait(self);
131 }
132
133 okay = (jni_on_load_result_ == kOkay);
134 VLOG(jni) << "[Earlier JNI_OnLoad for \"" << path_ << "\" "
135 << (okay ? "succeeded" : "failed") << "]";
136 }
137 }
138 return okay;
139 }
140
Mathieu Chartier90443472015-07-16 20:32:27 -0700141 void SetResult(bool result) REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700142 Thread* self = Thread::Current();
143 MutexLock mu(self, jni_on_load_lock_);
144
145 jni_on_load_result_ = result ? kOkay : kFailed;
146 jni_on_load_thread_id_ = 0;
147
148 // Broadcast a wakeup to anybody sleeping on the condition variable.
149 jni_on_load_cond_.Broadcast(self);
150 }
151
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800152 void SetNeedsNativeBridge(bool needs) {
153 needs_native_bridge_ = needs;
Ian Rogers68d8b422014-07-17 11:09:10 -0700154 }
155
156 bool NeedsNativeBridge() const {
157 return needs_native_bridge_;
158 }
159
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700160 // No mutator lock since dlsym may block for a while if another thread is doing dlopen.
161 void* FindSymbol(const std::string& symbol_name, const char* shorty = nullptr)
162 REQUIRES(!Locks::mutator_lock_) {
Mathieu Chartier598302a2015-09-23 14:52:39 -0700163 return NeedsNativeBridge()
164 ? FindSymbolWithNativeBridge(symbol_name.c_str(), shorty)
165 : FindSymbolWithoutNativeBridge(symbol_name.c_str());
166 }
167
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700168 // No mutator lock since dlsym may block for a while if another thread is doing dlopen.
169 void* FindSymbolWithoutNativeBridge(const std::string& symbol_name)
170 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe8fec90b2015-06-30 11:23:44 -0700171 CHECK(!NeedsNativeBridge());
172
Ian Rogers68d8b422014-07-17 11:09:10 -0700173 return dlsym(handle_, symbol_name.c_str());
174 }
175
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700176 void* FindSymbolWithNativeBridge(const std::string& symbol_name, const char* shorty)
177 REQUIRES(!Locks::mutator_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700178 CHECK(NeedsNativeBridge());
179
180 uint32_t len = 0;
Calin Juravlec8423522014-08-12 20:55:20 +0100181 return android::NativeBridgeGetTrampoline(handle_, symbol_name.c_str(), shorty, len);
Ian Rogers68d8b422014-07-17 11:09:10 -0700182 }
183
184 private:
185 enum JNI_OnLoadState {
186 kPending,
187 kFailed,
188 kOkay,
189 };
190
191 // Path to library "/system/lib/libjni.so".
192 const std::string path_;
193
194 // The void* returned by dlopen(3).
195 void* const handle_;
196
197 // True if a native bridge is required.
198 bool needs_native_bridge_;
199
Mathieu Chartier598302a2015-09-23 14:52:39 -0700200 // The ClassLoader this library is associated with, a weak global JNI reference that is
Ian Rogers68d8b422014-07-17 11:09:10 -0700201 // created/deleted with the scope of the library.
Mathieu Chartier598302a2015-09-23 14:52:39 -0700202 const jweak class_loader_;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800203 // Used to do equality check on class loaders so we can avoid decoding the weak root and read
204 // barriers that mess with class unloading.
205 const void* class_loader_allocator_;
Ian Rogers68d8b422014-07-17 11:09:10 -0700206
207 // Guards remaining items.
208 Mutex jni_on_load_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
209 // Wait for JNI_OnLoad in other thread.
210 ConditionVariable jni_on_load_cond_ GUARDED_BY(jni_on_load_lock_);
211 // Recursive invocation guard.
212 uint32_t jni_on_load_thread_id_ GUARDED_BY(jni_on_load_lock_);
213 // Result of earlier JNI_OnLoad call.
214 JNI_OnLoadState jni_on_load_result_ GUARDED_BY(jni_on_load_lock_);
215};
216
217// This exists mainly to keep implementation details out of the header file.
218class Libraries {
219 public:
220 Libraries() {
221 }
222
223 ~Libraries() {
224 STLDeleteValues(&libraries_);
225 }
226
Mathieu Chartier598302a2015-09-23 14:52:39 -0700227 // NO_THREAD_SAFETY_ANALYSIS since this may be called from Dumpable. Dumpable can't be annotated
228 // properly due to the template. The caller should be holding the jni_libraries_lock_.
229 void Dump(std::ostream& os) const NO_THREAD_SAFETY_ANALYSIS {
230 Locks::jni_libraries_lock_->AssertHeld(Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -0700231 bool first = true;
232 for (const auto& library : libraries_) {
233 if (!first) {
234 os << ' ';
235 }
236 first = false;
237 os << library.first;
238 }
239 }
240
Mathieu Chartier598302a2015-09-23 14:52:39 -0700241 size_t size() const REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700242 return libraries_.size();
243 }
244
Mathieu Chartier598302a2015-09-23 14:52:39 -0700245 SharedLibrary* Get(const std::string& path) REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700246 auto it = libraries_.find(path);
247 return (it == libraries_.end()) ? nullptr : it->second;
248 }
249
Mathieu Chartier598302a2015-09-23 14:52:39 -0700250 void Put(const std::string& path, SharedLibrary* library)
251 REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700252 libraries_.Put(path, library);
253 }
254
255 // See section 11.3 "Linking Native Methods" of the JNI spec.
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700256 void* FindNativeMethod(Thread* self, ArtMethod* m, std::string& detail)
257 REQUIRES(!Locks::jni_libraries_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700258 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700259 std::string jni_short_name(m->JniShortName());
260 std::string jni_long_name(m->JniLongName());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800261 mirror::ClassLoader* const declaring_class_loader = m->GetDeclaringClass()->GetClassLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700262 ScopedObjectAccessUnchecked soa(Thread::Current());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800263 void* const declaring_class_loader_allocator =
264 Runtime::Current()->GetClassLinker()->GetAllocatorForClassLoader(declaring_class_loader);
265 CHECK(declaring_class_loader_allocator != nullptr);
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700266 // TODO: Avoid calling GetShorty here to prevent dirtying dex pages?
267 const char* shorty = m->GetShorty();
268 {
269 // Go to suspended since dlsym may block for a long time if other threads are using dlopen.
270 ScopedThreadSuspension sts(self, kNative);
271 void* native_code = FindNativeMethodInternal(self,
272 declaring_class_loader_allocator,
273 shorty,
274 jni_short_name,
275 jni_long_name);
276 if (native_code != nullptr) {
277 return native_code;
Ian Rogers68d8b422014-07-17 11:09:10 -0700278 }
279 }
280 detail += "No implementation found for ";
David Sehr709b0702016-10-13 09:12:37 -0700281 detail += m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700282 detail += " (tried " + jni_short_name + " and " + jni_long_name + ")";
Ian Rogers68d8b422014-07-17 11:09:10 -0700283 return nullptr;
284 }
285
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700286 void* FindNativeMethodInternal(Thread* self,
287 void* declaring_class_loader_allocator,
288 const char* shorty,
289 const std::string& jni_short_name,
290 const std::string& jni_long_name)
291 REQUIRES(!Locks::jni_libraries_lock_)
292 REQUIRES(!Locks::mutator_lock_) {
293 MutexLock mu(self, *Locks::jni_libraries_lock_);
294 for (const auto& lib : libraries_) {
295 SharedLibrary* const library = lib.second;
296 // Use the allocator address for class loader equality to avoid unnecessary weak root decode.
297 if (library->GetClassLoaderAllocator() != declaring_class_loader_allocator) {
298 // We only search libraries loaded by the appropriate ClassLoader.
299 continue;
300 }
301 // Try the short name then the long name...
302 const char* arg_shorty = library->NeedsNativeBridge() ? shorty : nullptr;
303 void* fn = library->FindSymbol(jni_short_name, arg_shorty);
304 if (fn == nullptr) {
305 fn = library->FindSymbol(jni_long_name, arg_shorty);
306 }
307 if (fn != nullptr) {
308 VLOG(jni) << "[Found native code for " << jni_long_name
309 << " in \"" << library->GetPath() << "\"]";
310 return fn;
311 }
312 }
313 return nullptr;
314 }
315
Mathieu Chartier598302a2015-09-23 14:52:39 -0700316 // Unload native libraries with cleared class loaders.
317 void UnloadNativeLibraries()
318 REQUIRES(!Locks::jni_libraries_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700319 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700320 Thread* const self = Thread::Current();
Alex Lightbc5669e2016-06-13 17:22:13 +0000321 std::vector<SharedLibrary*> unload_libraries;
Mathieu Chartier598302a2015-09-23 14:52:39 -0700322 {
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700323 MutexLock mu(self, *Locks::jni_libraries_lock_);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700324 for (auto it = libraries_.begin(); it != libraries_.end(); ) {
325 SharedLibrary* const library = it->second;
326 // If class loader is null then it was unloaded, call JNI_OnUnload.
Mathieu Chartiercffb7472015-09-28 10:33:00 -0700327 const jweak class_loader = library->GetClassLoader();
328 // If class_loader is a null jobject then it is the boot class loader. We should not unload
329 // the native libraries of the boot class loader.
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700330 if (class_loader != nullptr && self->IsJWeakCleared(class_loader)) {
Alex Lightbc5669e2016-06-13 17:22:13 +0000331 unload_libraries.push_back(library);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700332 it = libraries_.erase(it);
333 } else {
334 ++it;
335 }
336 }
337 }
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700338 ScopedThreadSuspension sts(self, kNative);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700339 // Do this without holding the jni libraries lock to prevent possible deadlocks.
Andreas Gampec55bb392018-09-21 00:02:02 +0000340 using JNI_OnUnloadFn = void(*)(JavaVM*, void*);
Alex Lightbc5669e2016-06-13 17:22:13 +0000341 for (auto library : unload_libraries) {
342 void* const sym = library->FindSymbol("JNI_OnUnload", nullptr);
343 if (sym == nullptr) {
344 VLOG(jni) << "[No JNI_OnUnload found in \"" << library->GetPath() << "\"]";
345 } else {
346 VLOG(jni) << "[JNI_OnUnload found for \"" << library->GetPath() << "\"]: Calling...";
347 JNI_OnUnloadFn jni_on_unload = reinterpret_cast<JNI_OnUnloadFn>(sym);
Ian Rogers55256cb2017-12-21 17:07:11 -0800348 jni_on_unload(self->GetJniEnv()->GetVm(), nullptr);
Alex Lightbc5669e2016-06-13 17:22:13 +0000349 }
350 delete library;
Mathieu Chartier598302a2015-09-23 14:52:39 -0700351 }
352 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700353
Mathieu Chartier598302a2015-09-23 14:52:39 -0700354 private:
355 AllocationTrackingSafeMap<std::string, SharedLibrary*, kAllocatorTagJNILibraries> libraries_
356 GUARDED_BY(Locks::jni_libraries_lock_);
357};
Ian Rogers68d8b422014-07-17 11:09:10 -0700358
359class JII {
360 public:
361 static jint DestroyJavaVM(JavaVM* vm) {
362 if (vm == nullptr) {
363 return JNI_ERR;
364 }
365 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
366 delete raw_vm->GetRuntime();
Dimitry Ivanov39d68ef2016-04-29 16:02:38 -0700367 android::ResetNativeLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700368 return JNI_OK;
369 }
370
371 static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
372 return AttachCurrentThreadInternal(vm, p_env, thr_args, false);
373 }
374
375 static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
376 return AttachCurrentThreadInternal(vm, p_env, thr_args, true);
377 }
378
379 static jint DetachCurrentThread(JavaVM* vm) {
380 if (vm == nullptr || Thread::Current() == nullptr) {
381 return JNI_ERR;
382 }
383 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
384 Runtime* runtime = raw_vm->GetRuntime();
385 runtime->DetachCurrentThread();
386 return JNI_OK;
387 }
388
389 static jint GetEnv(JavaVM* vm, void** env, jint version) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700390 if (vm == nullptr || env == nullptr) {
391 return JNI_ERR;
392 }
393 Thread* thread = Thread::Current();
394 if (thread == nullptr) {
395 *env = nullptr;
396 return JNI_EDETACHED;
397 }
Alex Light185d1342016-08-11 10:48:03 -0700398 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
399 return raw_vm->HandleGetEnv(env, version);
Ian Rogers68d8b422014-07-17 11:09:10 -0700400 }
401
402 private:
403 static jint AttachCurrentThreadInternal(JavaVM* vm, JNIEnv** p_env, void* raw_args, bool as_daemon) {
404 if (vm == nullptr || p_env == nullptr) {
405 return JNI_ERR;
406 }
407
408 // Return immediately if we're already attached.
409 Thread* self = Thread::Current();
410 if (self != nullptr) {
411 *p_env = self->GetJniEnv();
412 return JNI_OK;
413 }
414
415 Runtime* runtime = reinterpret_cast<JavaVMExt*>(vm)->GetRuntime();
416
417 // No threads allowed in zygote mode.
418 if (runtime->IsZygote()) {
419 LOG(ERROR) << "Attempt to attach a thread in the zygote";
420 return JNI_ERR;
421 }
422
423 JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(raw_args);
424 const char* thread_name = nullptr;
425 jobject thread_group = nullptr;
426 if (args != nullptr) {
Alex Light185d1342016-08-11 10:48:03 -0700427 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700428 LOG(ERROR) << "Bad JNI version passed to "
429 << (as_daemon ? "AttachCurrentThreadAsDaemon" : "AttachCurrentThread") << ": "
430 << args->version;
431 return JNI_EVERSION;
432 }
433 thread_name = args->name;
434 thread_group = args->group;
435 }
436
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800437 if (!runtime->AttachCurrentThread(thread_name, as_daemon, thread_group,
438 !runtime->IsAotCompiler())) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700439 *p_env = nullptr;
440 return JNI_ERR;
441 } else {
442 *p_env = Thread::Current()->GetJniEnv();
443 return JNI_OK;
444 }
445 }
446};
447
448const JNIInvokeInterface gJniInvokeInterface = {
449 nullptr, // reserved0
450 nullptr, // reserved1
451 nullptr, // reserved2
452 JII::DestroyJavaVM,
453 JII::AttachCurrentThread,
454 JII::DetachCurrentThread,
455 JII::GetEnv,
456 JII::AttachCurrentThreadAsDaemon
457};
458
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100459JavaVMExt::JavaVMExt(Runtime* runtime,
460 const RuntimeArgumentMap& runtime_options,
461 std::string* error_msg)
Ian Rogers68d8b422014-07-17 11:09:10 -0700462 : runtime_(runtime),
463 check_jni_abort_hook_(nullptr),
464 check_jni_abort_hook_data_(nullptr),
465 check_jni_(false), // Initialized properly in the constructor body below.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800466 force_copy_(runtime_options.Exists(RuntimeArgumentMap::JniOptsForceCopy)),
467 tracing_enabled_(runtime_options.Exists(RuntimeArgumentMap::JniTrace)
468 || VLOG_IS_ON(third_party_jni)),
469 trace_(runtime_options.GetOrDefault(RuntimeArgumentMap::JniTrace)),
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700470 globals_(kGlobalsMax, kGlobal, IndirectReferenceTable::ResizableCapacity::kNo, error_msg),
Ian Rogers68d8b422014-07-17 11:09:10 -0700471 libraries_(new Libraries),
472 unchecked_functions_(&gJniInvokeInterface),
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700473 weak_globals_(kWeakGlobalsMax,
474 kWeakGlobal,
475 IndirectReferenceTable::ResizableCapacity::kNo,
476 error_msg),
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700477 allow_accessing_weak_globals_(true),
Andreas Gampe05a364c2016-10-14 13:27:12 -0700478 weak_globals_add_condition_("weak globals add condition",
479 (CHECK(Locks::jni_weak_globals_lock_ != nullptr),
480 *Locks::jni_weak_globals_lock_)),
Andreas Gampe1b35b462017-09-29 18:52:15 -0700481 env_hooks_(),
482 enable_allocation_tracking_delta_(
483 runtime_options.GetOrDefault(RuntimeArgumentMap::GlobalRefAllocStackTraceLimit)),
484 allocation_tracking_enabled_(false),
485 old_allocation_tracking_state_(false) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700486 functions = unchecked_functions_;
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800487 SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni));
Ian Rogers68d8b422014-07-17 11:09:10 -0700488}
489
490JavaVMExt::~JavaVMExt() {
491}
492
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100493// Checking "globals" and "weak_globals" usually requires locks, but we
494// don't need the locks to check for validity when constructing the
495// object. Use NO_THREAD_SAFETY_ANALYSIS for this.
496std::unique_ptr<JavaVMExt> JavaVMExt::Create(Runtime* runtime,
497 const RuntimeArgumentMap& runtime_options,
498 std::string* error_msg) NO_THREAD_SAFETY_ANALYSIS {
499 std::unique_ptr<JavaVMExt> java_vm(new JavaVMExt(runtime, runtime_options, error_msg));
500 if (java_vm && java_vm->globals_.IsValid() && java_vm->weak_globals_.IsValid()) {
501 return java_vm;
502 }
503 return nullptr;
504}
505
Alex Light185d1342016-08-11 10:48:03 -0700506jint JavaVMExt::HandleGetEnv(/*out*/void** env, jint version) {
507 for (GetEnvHook hook : env_hooks_) {
508 jint res = hook(this, env, version);
509 if (res == JNI_OK) {
510 return JNI_OK;
511 } else if (res != JNI_EVERSION) {
512 LOG(ERROR) << "Error returned from a plugin GetEnv handler! " << res;
513 return res;
514 }
515 }
516 LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version;
517 return JNI_EVERSION;
518}
519
520// Add a hook to handle getting environments from the GetEnv call.
521void JavaVMExt::AddEnvironmentHook(GetEnvHook hook) {
522 CHECK(hook != nullptr) << "environment hooks shouldn't be null!";
523 env_hooks_.push_back(hook);
524}
525
Ian Rogers68d8b422014-07-17 11:09:10 -0700526void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) {
527 Thread* self = Thread::Current();
528 ScopedObjectAccess soa(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700529 ArtMethod* current_method = self->GetCurrentMethod(nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700530
531 std::ostringstream os;
532 os << "JNI DETECTED ERROR IN APPLICATION: " << msg;
533
534 if (jni_function_name != nullptr) {
535 os << "\n in call to " << jni_function_name;
536 }
537 // TODO: is this useful given that we're about to dump the calling thread's stack?
538 if (current_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700539 os << "\n from " << current_method->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700540 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700541
542 if (check_jni_abort_hook_ != nullptr) {
543 check_jni_abort_hook_(check_jni_abort_hook_data_, os.str());
544 } else {
545 // Ensure that we get a native stack trace for this thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700546 ScopedThreadSuspension sts(self, kNative);
Ian Rogers68d8b422014-07-17 11:09:10 -0700547 LOG(FATAL) << os.str();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700548 UNREACHABLE();
Ian Rogers68d8b422014-07-17 11:09:10 -0700549 }
550}
551
552void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) {
553 std::string msg;
554 StringAppendV(&msg, fmt, ap);
555 JniAbort(jni_function_name, msg.c_str());
556}
557
558void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) {
559 va_list args;
560 va_start(args, fmt);
561 JniAbortV(jni_function_name, fmt, args);
562 va_end(args);
563}
564
Mathieu Chartiere401d142015-04-22 13:56:20 -0700565bool JavaVMExt::ShouldTrace(ArtMethod* method) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700566 // Fast where no tracing is enabled.
567 if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) {
568 return false;
569 }
570 // Perform checks based on class name.
Vladimir Marko72101082019-02-05 16:16:30 +0000571 std::string_view class_name(method->GetDeclaringClassDescriptor());
572 if (!trace_.empty() && class_name.find(trace_) != std::string_view::npos) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700573 return true;
574 }
575 if (!VLOG_IS_ON(third_party_jni)) {
576 return false;
577 }
578 // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
579 // like part of Android.
Vladimir Marko72101082019-02-05 16:16:30 +0000580 static const char* const gBuiltInPrefixes[] = {
Ian Rogers68d8b422014-07-17 11:09:10 -0700581 "Landroid/",
582 "Lcom/android/",
583 "Lcom/google/android/",
584 "Ldalvik/",
585 "Ljava/",
586 "Ljavax/",
587 "Llibcore/",
588 "Lorg/apache/harmony/",
589 };
590 for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) {
Vladimir Marko72101082019-02-05 16:16:30 +0000591 if (StartsWith(class_name, gBuiltInPrefixes[i])) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700592 return false;
593 }
594 }
595 return true;
596}
597
Andreas Gampe1b35b462017-09-29 18:52:15 -0700598void JavaVMExt::CheckGlobalRefAllocationTracking() {
599 if (LIKELY(enable_allocation_tracking_delta_ == 0)) {
600 return;
601 }
602 size_t simple_free_capacity = globals_.FreeCapacity();
603 if (UNLIKELY(simple_free_capacity <= enable_allocation_tracking_delta_)) {
604 if (!allocation_tracking_enabled_) {
605 LOG(WARNING) << "Global reference storage appears close to exhaustion, program termination "
606 << "may be imminent. Enabling allocation tracking to improve abort diagnostics. "
607 << "This will result in program slow-down.";
608
609 old_allocation_tracking_state_ = runtime_->GetHeap()->IsAllocTrackingEnabled();
610 if (!old_allocation_tracking_state_) {
611 // Need to be guaranteed suspended.
612 ScopedObjectAccess soa(Thread::Current());
613 ScopedThreadSuspension sts(soa.Self(), ThreadState::kNative);
614 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(true);
615 }
616 allocation_tracking_enabled_ = true;
617 }
618 } else {
619 if (UNLIKELY(allocation_tracking_enabled_)) {
620 if (!old_allocation_tracking_state_) {
621 // Need to be guaranteed suspended.
622 ScopedObjectAccess soa(Thread::Current());
623 ScopedThreadSuspension sts(soa.Self(), ThreadState::kNative);
624 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(false);
625 }
Andreas Gampe45485342017-10-11 12:04:35 -0700626 allocation_tracking_enabled_ = false;
Andreas Gampe1b35b462017-09-29 18:52:15 -0700627 }
628 }
629}
630
Mathieu Chartier0795f232016-09-27 18:43:30 -0700631jobject JavaVMExt::AddGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700632 // Check for null after decoding the object to handle cleared weak globals.
633 if (obj == nullptr) {
634 return nullptr;
635 }
Andreas Gampe1b35b462017-09-29 18:52:15 -0700636 IndirectRef ref;
Andreas Gampe25651122017-09-25 14:50:23 -0700637 std::string error_msg;
Andreas Gampe1b35b462017-09-29 18:52:15 -0700638 {
639 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
640 ref = globals_.Add(kIRTFirstSegment, obj, &error_msg);
641 }
Andreas Gampe25651122017-09-25 14:50:23 -0700642 if (UNLIKELY(ref == nullptr)) {
643 LOG(FATAL) << error_msg;
644 UNREACHABLE();
645 }
Andreas Gampe1b35b462017-09-29 18:52:15 -0700646 CheckGlobalRefAllocationTracking();
Ian Rogers68d8b422014-07-17 11:09:10 -0700647 return reinterpret_cast<jobject>(ref);
648}
649
Mathieu Chartier0795f232016-09-27 18:43:30 -0700650jweak JavaVMExt::AddWeakGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700651 if (obj == nullptr) {
652 return nullptr;
653 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700654 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchif1c6f872017-01-06 12:23:47 -0800655 // CMS needs this to block for concurrent reference processing because an object allocated during
656 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
657 // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant.
658 while (!kUseReadBarrier && UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700659 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
660 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800661 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700662 weak_globals_add_condition_.WaitHoldingLocks(self);
663 }
Andreas Gampe25651122017-09-25 14:50:23 -0700664 std::string error_msg;
665 IndirectRef ref = weak_globals_.Add(kIRTFirstSegment, obj, &error_msg);
666 if (UNLIKELY(ref == nullptr)) {
667 LOG(FATAL) << error_msg;
668 UNREACHABLE();
669 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700670 return reinterpret_cast<jweak>(ref);
671}
672
673void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
674 if (obj == nullptr) {
675 return;
676 }
Andreas Gampe1b35b462017-09-29 18:52:15 -0700677 {
678 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
679 if (!globals_.Remove(kIRTFirstSegment, obj)) {
680 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
681 << "failed to find entry";
682 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700683 }
Andreas Gampe1b35b462017-09-29 18:52:15 -0700684 CheckGlobalRefAllocationTracking();
Ian Rogers68d8b422014-07-17 11:09:10 -0700685}
686
687void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
688 if (obj == nullptr) {
689 return;
690 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700691 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700692 if (!weak_globals_.Remove(kIRTFirstSegment, obj)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700693 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
694 << "failed to find entry";
695 }
696}
697
698static void ThreadEnableCheckJni(Thread* thread, void* arg) {
699 bool* check_jni = reinterpret_cast<bool*>(arg);
700 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
701}
702
703bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
704 bool old_check_jni = check_jni_;
705 check_jni_ = enabled;
706 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
707 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
708 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
709 return old_check_jni;
710}
711
712void JavaVMExt::DumpForSigQuit(std::ostream& os) {
713 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
714 if (force_copy_) {
715 os << " (with forcecopy)";
716 }
717 Thread* self = Thread::Current();
718 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700719 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700720 os << "; globals=" << globals_.Capacity();
721 }
722 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700723 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700724 if (weak_globals_.Capacity() > 0) {
725 os << " (plus " << weak_globals_.Capacity() << " weak)";
726 }
727 }
728 os << '\n';
729
730 {
731 MutexLock mu(self, *Locks::jni_libraries_lock_);
732 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
733 }
734}
735
736void JavaVMExt::DisallowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700737 CHECK(!kUseReadBarrier);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700738 Thread* const self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700739 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700740 // DisallowNewWeakGlobals is only called by CMS during the pause. It is required to have the
741 // mutator lock exclusively held so that we don't have any threads in the middle of
742 // DecodeWeakGlobal.
743 Locks::mutator_lock_->AssertExclusiveHeld(self);
Orion Hodson88591fe2018-03-06 13:35:43 +0000744 allow_accessing_weak_globals_.store(false, std::memory_order_seq_cst);
Ian Rogers68d8b422014-07-17 11:09:10 -0700745}
746
747void JavaVMExt::AllowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700748 CHECK(!kUseReadBarrier);
Ian Rogers68d8b422014-07-17 11:09:10 -0700749 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700750 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Orion Hodson88591fe2018-03-06 13:35:43 +0000751 allow_accessing_weak_globals_.store(true, std::memory_order_seq_cst);
Ian Rogers68d8b422014-07-17 11:09:10 -0700752 weak_globals_add_condition_.Broadcast(self);
753}
754
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700755void JavaVMExt::BroadcastForNewWeakGlobals() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700756 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700757 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700758 weak_globals_add_condition_.Broadcast(self);
759}
760
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700761ObjPtr<mirror::Object> JavaVMExt::DecodeGlobal(IndirectRef ref) {
762 return globals_.SynchronizedGet(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700763}
764
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700765void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700766 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700767 globals_.Update(ref, result);
768}
769
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700770inline bool JavaVMExt::MayAccessWeakGlobals(Thread* self) const {
771 return MayAccessWeakGlobalsUnlocked(self);
772}
773
774inline bool JavaVMExt::MayAccessWeakGlobalsUnlocked(Thread* self) const {
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700775 DCHECK(self != nullptr);
776 return kUseReadBarrier ?
777 self->GetWeakRefAccessEnabled() :
Orion Hodson88591fe2018-03-06 13:35:43 +0000778 allow_accessing_weak_globals_.load(std::memory_order_seq_cst);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700779}
780
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700781ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700782 // It is safe to access GetWeakRefAccessEnabled without the lock since CC uses checkpoints to call
783 // SetWeakRefAccessEnabled, and the other collectors only modify allow_accessing_weak_globals_
784 // when the mutators are paused.
785 // This only applies in the case where MayAccessWeakGlobals goes from false to true. In the other
786 // case, it may be racy, this is benign since DecodeWeakGlobalLocked does the correct behavior
787 // if MayAccessWeakGlobals is false.
Andreas Gampedc061d02016-10-24 13:19:37 -0700788 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700789 if (LIKELY(MayAccessWeakGlobalsUnlocked(self))) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700790 return weak_globals_.SynchronizedGet(ref);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700791 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700792 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700793 return DecodeWeakGlobalLocked(self, ref);
794}
795
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700796ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalLocked(Thread* self, IndirectRef ref) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700797 if (kDebugLocking) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700798 Locks::jni_weak_globals_lock_->AssertHeld(self);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700799 }
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700800 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700801 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
802 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800803 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700804 weak_globals_add_condition_.WaitHoldingLocks(self);
805 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700806 return weak_globals_.Get(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700807}
808
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700809ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalDuringShutdown(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700810 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700811 DCHECK(Runtime::Current()->IsShuttingDown(self));
812 if (self != nullptr) {
813 return DecodeWeakGlobal(self, ref);
814 }
815 // self can be null during a runtime shutdown. ~Runtime()->~ClassLinker()->DecodeWeakGlobal().
816 if (!kUseReadBarrier) {
Orion Hodson88591fe2018-03-06 13:35:43 +0000817 DCHECK(allow_accessing_weak_globals_.load(std::memory_order_seq_cst));
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700818 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700819 return weak_globals_.SynchronizedGet(ref);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700820}
821
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800822bool JavaVMExt::IsWeakGlobalCleared(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700823 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Andreas Gampe05a364c2016-10-14 13:27:12 -0700824 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800825 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700826 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
827 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800828 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800829 weak_globals_add_condition_.WaitHoldingLocks(self);
830 }
831 // When just checking a weak ref has been cleared, avoid triggering the read barrier in decode
832 // (DecodeWeakGlobal) so that we won't accidentally mark the object alive. Since the cleared
833 // sentinel is a non-moving object, we can compare the ref to it without the read barrier and
834 // decide if it's cleared.
835 return Runtime::Current()->IsClearedJniWeakGlobal(weak_globals_.Get<kWithoutReadBarrier>(ref));
836}
837
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700838void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700839 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700840 weak_globals_.Update(ref, result);
841}
842
Ian Rogers68d8b422014-07-17 11:09:10 -0700843void JavaVMExt::DumpReferenceTables(std::ostream& os) {
844 Thread* self = Thread::Current();
845 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700846 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700847 globals_.Dump(os);
848 }
849 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700850 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700851 weak_globals_.Dump(os);
852 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700853}
854
Mathieu Chartier598302a2015-09-23 14:52:39 -0700855void JavaVMExt::UnloadNativeLibraries() {
856 libraries_.get()->UnloadNativeLibraries();
857}
858
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800859bool JavaVMExt::LoadNativeLibrary(JNIEnv* env,
860 const std::string& path,
861 jobject class_loader,
Nicolas Geoffray96259f12019-01-18 10:04:51 +0000862 jclass caller_class,
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800863 std::string* error_msg) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700864 error_msg->clear();
865
866 // See if we've already loaded this library. If we have, and the class loader
867 // matches, return successfully without doing anything.
868 // TODO: for better results we should canonicalize the pathname (or even compare
869 // inodes). This implementation is fine if everybody is using System.loadLibrary.
870 SharedLibrary* library;
871 Thread* self = Thread::Current();
872 {
873 // TODO: move the locking (and more of this logic) into Libraries.
874 MutexLock mu(self, *Locks::jni_libraries_lock_);
875 library = libraries_->Get(path);
876 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800877 void* class_loader_allocator = nullptr;
Nicolas Geoffray96259f12019-01-18 10:04:51 +0000878 std::string caller_location;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800879 {
880 ScopedObjectAccess soa(env);
881 // As the incoming class loader is reachable/alive during the call of this function,
882 // it's okay to decode it without worrying about unexpectedly marking it alive.
Mathieu Chartier0795f232016-09-27 18:43:30 -0700883 ObjPtr<mirror::ClassLoader> loader = soa.Decode<mirror::ClassLoader>(class_loader);
Andreas Gampe2d48e532016-06-17 12:46:14 -0700884
885 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700886 if (class_linker->IsBootClassLoader(soa, loader.Ptr())) {
Andreas Gampe2d48e532016-06-17 12:46:14 -0700887 loader = nullptr;
888 class_loader = nullptr;
Nicolas Geoffray96259f12019-01-18 10:04:51 +0000889 if (caller_class != nullptr) {
890 ObjPtr<mirror::Class> caller = soa.Decode<mirror::Class>(caller_class);
891 ObjPtr<mirror::DexCache> dex_cache = caller->GetDexCache();
892 if (dex_cache != nullptr) {
893 caller_location = dex_cache->GetLocation()->ToModifiedUtf8();
894 }
895 }
Andreas Gampe2d48e532016-06-17 12:46:14 -0700896 }
897
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700898 class_loader_allocator = class_linker->GetAllocatorForClassLoader(loader.Ptr());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800899 CHECK(class_loader_allocator != nullptr);
900 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700901 if (library != nullptr) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800902 // Use the allocator pointers for class loader equality to avoid unnecessary weak root decode.
903 if (library->GetClassLoaderAllocator() != class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700904 // The library will be associated with class_loader. The JNI
905 // spec says we can't load the same library into more than one
906 // class loader.
Andreas Gampefd03f1e2017-09-19 17:10:10 -0700907 //
908 // This isn't very common. So spend some time to get a readable message.
909 auto call_to_string = [&](jobject obj) -> std::string {
910 if (obj == nullptr) {
911 return "null";
912 }
913 // Handle jweaks. Ignore double local-ref.
914 ScopedLocalRef<jobject> local_ref(env, env->NewLocalRef(obj));
915 if (local_ref != nullptr) {
916 ScopedLocalRef<jclass> local_class(env, env->GetObjectClass(local_ref.get()));
917 jmethodID to_string = env->GetMethodID(local_class.get(),
918 "toString",
919 "()Ljava/lang/String;");
920 DCHECK(to_string != nullptr);
921 ScopedLocalRef<jobject> local_string(env,
922 env->CallObjectMethod(local_ref.get(), to_string));
923 if (local_string != nullptr) {
924 ScopedUtfChars utf(env, reinterpret_cast<jstring>(local_string.get()));
925 if (utf.c_str() != nullptr) {
926 return utf.c_str();
927 }
928 }
Andreas Gampe3362d222018-06-05 16:02:10 -0700929 if (env->ExceptionCheck()) {
930 // We can't do much better logging, really. So leave it with a Describe.
931 env->ExceptionDescribe();
932 env->ExceptionClear();
933 }
Andreas Gampefd03f1e2017-09-19 17:10:10 -0700934 return "(Error calling toString)";
935 }
936 return "null";
937 };
938 std::string old_class_loader = call_to_string(library->GetClassLoader());
939 std::string new_class_loader = call_to_string(class_loader);
Ian Rogers68d8b422014-07-17 11:09:10 -0700940 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
Andreas Gampefd03f1e2017-09-19 17:10:10 -0700941 "ClassLoader %p(%s); can't open in ClassLoader %p(%s)",
942 path.c_str(),
943 library->GetClassLoader(),
944 old_class_loader.c_str(),
945 class_loader,
946 new_class_loader.c_str());
Andreas Gampe335ee582017-09-19 17:09:52 -0700947 LOG(WARNING) << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700948 return false;
949 }
950 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
951 << " ClassLoader " << class_loader << "]";
952 if (!library->CheckOnLoadResult()) {
953 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
954 "to load \"%s\"", path.c_str());
955 return false;
956 }
957 return true;
958 }
959
960 // Open the shared library. Because we're using a full path, the system
961 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
962 // resolve this library's dependencies though.)
963
964 // Failures here are expected when java.library.path has several entries
965 // and we have to hunt for the lib.
966
967 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
968 // class unloading. Libraries will only be unloaded when the reference count (incremented by
969 // dlopen) becomes zero from dlclose.
970
Andreas Gampe473191c2017-12-28 16:55:31 -0800971 // Retrieve the library path from the classloader, if necessary.
972 ScopedLocalRef<jstring> library_path(env, GetLibrarySearchPath(env, class_loader));
973
Ian Rogers68d8b422014-07-17 11:09:10 -0700974 Locks::mutator_lock_->AssertNotHeld(self);
975 const char* path_str = path.empty() ? nullptr : path.c_str();
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800976 bool needs_native_bridge = false;
Nicolas Geoffrayc3ba7ee2019-01-16 21:46:48 +0000977 char* nativeloader_error_msg = nullptr;
Nicolas Geoffray96259f12019-01-18 10:04:51 +0000978 void* handle = android::OpenNativeLibrary(
979 env,
980 runtime_->GetTargetSdkVersion(),
981 path_str,
982 class_loader,
983 (caller_location.empty() ? nullptr : caller_location.c_str()),
984 library_path.get(),
985 &needs_native_bridge,
986 &nativeloader_error_msg);
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700987 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]";
Ian Rogers68d8b422014-07-17 11:09:10 -0700988
989 if (handle == nullptr) {
Nicolas Geoffrayd9b30692019-01-12 14:59:05 +0000990 *error_msg = nativeloader_error_msg;
Nicolas Geoffrayc3ba7ee2019-01-16 21:46:48 +0000991 android::NativeLoaderFreeErrorMessage(nativeloader_error_msg);
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700992 VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700993 return false;
994 }
995
996 if (env->ExceptionCheck() == JNI_TRUE) {
997 LOG(ERROR) << "Unexpected exception:";
998 env->ExceptionDescribe();
999 env->ExceptionClear();
1000 }
1001 // Create a new entry.
1002 // TODO: move the locking (and more of this logic) into Libraries.
1003 bool created_library = false;
1004 {
1005 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
1006 std::unique_ptr<SharedLibrary> new_library(
Zhenhua WANG8447e6d2016-05-30 11:10:29 +08001007 new SharedLibrary(env,
1008 self,
1009 path,
1010 handle,
1011 needs_native_bridge,
1012 class_loader,
1013 class_loader_allocator));
1014
Ian Rogers68d8b422014-07-17 11:09:10 -07001015 MutexLock mu(self, *Locks::jni_libraries_lock_);
1016 library = libraries_->Get(path);
1017 if (library == nullptr) { // We won race to get libraries_lock.
1018 library = new_library.release();
1019 libraries_->Put(path, library);
1020 created_library = true;
1021 }
1022 }
1023 if (!created_library) {
1024 LOG(INFO) << "WOW: we lost a race to add shared library: "
1025 << "\"" << path << "\" ClassLoader=" << class_loader;
1026 return library->CheckOnLoadResult();
1027 }
1028 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
1029
1030 bool was_successful = false;
Zhenhua WANG8447e6d2016-05-30 11:10:29 +08001031 void* sym = library->FindSymbol("JNI_OnLoad", nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -07001032 if (sym == nullptr) {
1033 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
1034 was_successful = true;
1035 } else {
1036 // Call JNI_OnLoad. We have to override the current class
1037 // loader, which will always be "null" since the stuff at the
1038 // top of the stack is around Runtime.loadLibrary(). (See
1039 // the comments in the JNI FindClass function.)
1040 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
1041 self->SetClassLoaderOverride(class_loader);
1042
1043 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
Andreas Gampec55bb392018-09-21 00:02:02 +00001044 using JNI_OnLoadFn = int(*)(JavaVM*, void*);
Ian Rogers68d8b422014-07-17 11:09:10 -07001045 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
1046 int version = (*jni_on_load)(this, nullptr);
1047
David Brazdil2bb2fbd2018-11-13 18:24:26 +00001048 if (IsSdkVersionSetAndAtMost(runtime_->GetTargetSdkVersion(), SdkVersion::kL)) {
Josh Gao85a78cf2017-03-20 16:26:42 -07001049 // Make sure that sigchain owns SIGSEGV.
1050 EnsureFrontOfChain(SIGSEGV);
Mathieu Chartierd0004802014-10-15 16:59:47 -07001051 }
1052
Ian Rogers68d8b422014-07-17 11:09:10 -07001053 self->SetClassLoaderOverride(old_class_loader.get());
1054
1055 if (version == JNI_ERR) {
1056 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
Alex Light185d1342016-08-11 10:48:03 -07001057 } else if (JavaVMExt::IsBadJniVersion(version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001058 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
1059 path.c_str(), version);
1060 // It's unwise to call dlclose() here, but we can mark it
1061 // as bad and ensure that future load attempts will fail.
1062 // We don't know how far JNI_OnLoad got, so there could
1063 // be some partially-initialized stuff accessible through
1064 // newly-registered native method calls. We could try to
1065 // unregister them, but that doesn't seem worthwhile.
1066 } else {
1067 was_successful = true;
1068 }
1069 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
1070 << " from JNI_OnLoad in \"" << path << "\"]";
1071 }
1072
1073 library->SetResult(was_successful);
1074 return was_successful;
1075}
1076
Alex Light65af20b2017-04-20 09:15:08 -07001077static void* FindCodeForNativeMethodInAgents(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
1078 std::string jni_short_name(m->JniShortName());
1079 std::string jni_long_name(m->JniLongName());
Andreas Gampeaadcbc62017-12-28 14:05:42 -08001080 for (const std::unique_ptr<ti::Agent>& agent : Runtime::Current()->GetAgents()) {
1081 void* fn = agent->FindSymbol(jni_short_name);
Alex Light65af20b2017-04-20 09:15:08 -07001082 if (fn != nullptr) {
1083 VLOG(jni) << "Found implementation for " << m->PrettyMethod()
Andreas Gampeaadcbc62017-12-28 14:05:42 -08001084 << " (symbol: " << jni_short_name << ") in " << *agent;
Alex Light65af20b2017-04-20 09:15:08 -07001085 return fn;
1086 }
Andreas Gampeaadcbc62017-12-28 14:05:42 -08001087 fn = agent->FindSymbol(jni_long_name);
Alex Light65af20b2017-04-20 09:15:08 -07001088 if (fn != nullptr) {
1089 VLOG(jni) << "Found implementation for " << m->PrettyMethod()
Andreas Gampeaadcbc62017-12-28 14:05:42 -08001090 << " (symbol: " << jni_long_name << ") in " << *agent;
Alex Light65af20b2017-04-20 09:15:08 -07001091 return fn;
1092 }
1093 }
1094 return nullptr;
1095}
1096
Mathieu Chartiere401d142015-04-22 13:56:20 -07001097void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001098 CHECK(m->IsNative());
Vladimir Markod93e3742018-07-18 10:58:13 +01001099 ObjPtr<mirror::Class> c = m->GetDeclaringClass();
Ian Rogers68d8b422014-07-17 11:09:10 -07001100 // If this is a static method, it could be called before the class has been initialized.
David Sehr709b0702016-10-13 09:12:37 -07001101 CHECK(c->IsInitializing()) << c->GetStatus() << " " << m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -07001102 std::string detail;
Mathieu Chartier46e75d02017-06-02 16:03:39 -07001103 Thread* const self = Thread::Current();
1104 void* native_method = libraries_->FindNativeMethod(self, m, detail);
Alex Light65af20b2017-04-20 09:15:08 -07001105 if (native_method == nullptr) {
1106 // Lookup JNI native methods from native TI Agent libraries. See runtime/ti/agent.h for more
1107 // information. Agent libraries are searched for native methods after all jni libraries.
1108 native_method = FindCodeForNativeMethodInAgents(m);
1109 }
Ian Rogers68d8b422014-07-17 11:09:10 -07001110 // Throwing can cause libraries_lock to be reacquired.
1111 if (native_method == nullptr) {
Alex Light65af20b2017-04-20 09:15:08 -07001112 LOG(ERROR) << detail;
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001113 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
Ian Rogers68d8b422014-07-17 11:09:10 -07001114 }
1115 return native_method;
1116}
1117
Mathieu Chartier97509952015-07-13 14:35:43 -07001118void JavaVMExt::SweepJniWeakGlobals(IsMarkedVisitor* visitor) {
Andreas Gampe05a364c2016-10-14 13:27:12 -07001119 MutexLock mu(Thread::Current(), *Locks::jni_weak_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001120 Runtime* const runtime = Runtime::Current();
1121 for (auto* entry : weak_globals_) {
1122 // Need to skip null here to distinguish between null entries and cleared weak ref entries.
1123 if (!entry->IsNull()) {
1124 // Since this is called by the GC, we don't need a read barrier.
1125 mirror::Object* obj = entry->Read<kWithoutReadBarrier>();
Mathieu Chartier97509952015-07-13 14:35:43 -07001126 mirror::Object* new_obj = visitor->IsMarked(obj);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001127 if (new_obj == nullptr) {
1128 new_obj = runtime->GetClearedJniWeakGlobal();
1129 }
1130 *entry = GcRoot<mirror::Object>(new_obj);
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -07001131 }
Ian Rogers68d8b422014-07-17 11:09:10 -07001132 }
1133}
1134
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001135void JavaVMExt::TrimGlobals() {
Andreas Gampe05a364c2016-10-14 13:27:12 -07001136 WriterMutexLock mu(Thread::Current(), *Locks::jni_globals_lock_);
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001137 globals_.Trim();
1138}
1139
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001140void JavaVMExt::VisitRoots(RootVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001141 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -07001142 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001143 globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal));
Ian Rogers68d8b422014-07-17 11:09:10 -07001144 // The weak_globals table is visited by the GC itself (because it mutates the table).
1145}
1146
Andreas Gampe473191c2017-12-28 16:55:31 -08001147jstring JavaVMExt::GetLibrarySearchPath(JNIEnv* env, jobject class_loader) {
1148 if (class_loader == nullptr) {
1149 return nullptr;
1150 }
1151 if (!env->IsInstanceOf(class_loader, WellKnownClasses::dalvik_system_BaseDexClassLoader)) {
1152 return nullptr;
1153 }
1154 return reinterpret_cast<jstring>(env->CallObjectMethod(
1155 class_loader,
1156 WellKnownClasses::dalvik_system_BaseDexClassLoader_getLdLibraryPath));
1157}
1158
Ian Rogers68d8b422014-07-17 11:09:10 -07001159// JNI Invocation interface.
1160
1161extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001162 ScopedTrace trace(__FUNCTION__);
Ian Rogers68d8b422014-07-17 11:09:10 -07001163 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
Alex Light185d1342016-08-11 10:48:03 -07001164 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001165 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
1166 return JNI_EVERSION;
1167 }
1168 RuntimeOptions options;
1169 for (int i = 0; i < args->nOptions; ++i) {
1170 JavaVMOption* option = &args->options[i];
1171 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
1172 }
1173 bool ignore_unrecognized = args->ignoreUnrecognized;
1174 if (!Runtime::Create(options, ignore_unrecognized)) {
1175 return JNI_ERR;
1176 }
Dimitry Ivanovc544f342016-05-09 16:26:13 -07001177
1178 // Initialize native loader. This step makes sure we have
1179 // everything set up before we start using JNI.
1180 android::InitializeNativeLoader();
1181
Ian Rogers68d8b422014-07-17 11:09:10 -07001182 Runtime* runtime = Runtime::Current();
1183 bool started = runtime->Start();
1184 if (!started) {
1185 delete Thread::Current()->GetJniEnv();
1186 delete runtime->GetJavaVM();
1187 LOG(WARNING) << "CreateJavaVM failed";
1188 return JNI_ERR;
1189 }
Dimitry Ivanov041169f2016-04-21 16:01:24 -07001190
Ian Rogers68d8b422014-07-17 11:09:10 -07001191 *p_env = Thread::Current()->GetJniEnv();
1192 *p_vm = runtime->GetJavaVM();
1193 return JNI_OK;
1194}
1195
Ian Rogersf4d4da12014-11-11 16:10:33 -08001196extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001197 Runtime* runtime = Runtime::Current();
Ian Rogersf4d4da12014-11-11 16:10:33 -08001198 if (runtime == nullptr || buf_len == 0) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001199 *vm_count = 0;
1200 } else {
1201 *vm_count = 1;
Ian Rogersf4d4da12014-11-11 16:10:33 -08001202 vms_buf[0] = runtime->GetJavaVM();
Ian Rogers68d8b422014-07-17 11:09:10 -07001203 }
1204 return JNI_OK;
1205}
1206
1207// Historically unsupported.
1208extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
1209 return JNI_ERR;
1210}
1211
1212} // namespace art