blob: e5b3d4de42da6bfc4a8178cacc390063e06dc610 [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"
Vladimir Marko58412b12019-04-01 13:26:34 +010041#include "mirror/dex_cache-inl.h"
Calin Juravlec8423522014-08-12 20:55:20 +010042#include "nativebridge/native_bridge.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070043#include "nativehelper/scoped_local_ref.h"
44#include "nativehelper/scoped_utf_chars.h"
Dmitriy Ivanovf5a30992015-11-11 14:18:55 -080045#include "nativeloader/native_loader.h"
Andreas Gampe57cf00b2017-06-05 17:15:32 -070046#include "object_callbacks.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070047#include "parsed_options.h"
Ian Rogersc0542af2014-09-03 16:16:56 -070048#include "runtime-inl.h"
Igor Murashkinaaebaa02015-01-26 10:55:53 -080049#include "runtime_options.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070050#include "scoped_thread_state_change-inl.h"
Josh Gao85a78cf2017-03-20 16:26:42 -070051#include "sigchain.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070052#include "thread-inl.h"
53#include "thread_list.h"
Steven Morelande431e272017-07-18 16:53:49 -070054#include "ti/agent.h"
Andreas Gampe473191c2017-12-28 16:55:31 -080055#include "well_known_classes.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070056
57namespace art {
58
Andreas Gampe46ee31b2016-12-14 10:11:49 -080059using android::base::StringAppendF;
60using android::base::StringAppendV;
61
Andreas Gampea8e3b862016-10-17 20:12:52 -070062static constexpr size_t kGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
Ian Rogers68d8b422014-07-17 11:09:10 -070063
Andreas Gampea8e3b862016-10-17 20:12:52 -070064static constexpr size_t kWeakGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
Ian Rogers68d8b422014-07-17 11:09:10 -070065
Alex Light185d1342016-08-11 10:48:03 -070066bool JavaVMExt::IsBadJniVersion(int version) {
Ian Rogers68d8b422014-07-17 11:09:10 -070067 // We don't support JNI_VERSION_1_1. These are the only other valid versions.
68 return version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 && version != JNI_VERSION_1_6;
69}
70
71class SharedLibrary {
72 public:
73 SharedLibrary(JNIEnv* env, Thread* self, const std::string& path, void* handle,
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080074 bool needs_native_bridge, jobject class_loader, void* class_loader_allocator)
Ian Rogers68d8b422014-07-17 11:09:10 -070075 : path_(path),
76 handle_(handle),
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080077 needs_native_bridge_(needs_native_bridge),
Mathieu Chartier598302a2015-09-23 14:52:39 -070078 class_loader_(env->NewWeakGlobalRef(class_loader)),
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080079 class_loader_allocator_(class_loader_allocator),
Ian Rogers68d8b422014-07-17 11:09:10 -070080 jni_on_load_lock_("JNI_OnLoad lock"),
81 jni_on_load_cond_("JNI_OnLoad condition variable", jni_on_load_lock_),
82 jni_on_load_thread_id_(self->GetThreadId()),
83 jni_on_load_result_(kPending) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080084 CHECK(class_loader_allocator_ != nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -070085 }
86
87 ~SharedLibrary() {
88 Thread* self = Thread::Current();
89 if (self != nullptr) {
Mathieu Chartier598302a2015-09-23 14:52:39 -070090 self->GetJniEnv()->DeleteWeakGlobalRef(class_loader_);
Ian Rogers68d8b422014-07-17 11:09:10 -070091 }
Alex Lightbc5669e2016-06-13 17:22:13 +000092
Nicolas Geoffrayd9b30692019-01-12 14:59:05 +000093 char* error_msg = nullptr;
dimitry947573e2018-09-12 01:12:56 +020094 if (!android::CloseNativeLibrary(handle_, needs_native_bridge_, &error_msg)) {
95 LOG(WARNING) << "Error while unloading native library \"" << path_ << "\": " << error_msg;
Nicolas Geoffrayd9b30692019-01-12 14:59:05 +000096 android::NativeLoaderFreeErrorMessage(error_msg);
dimitry947573e2018-09-12 01:12:56 +020097 }
Ian Rogers68d8b422014-07-17 11:09:10 -070098 }
99
Mathieu Chartier598302a2015-09-23 14:52:39 -0700100 jweak GetClassLoader() const {
Ian Rogers68d8b422014-07-17 11:09:10 -0700101 return class_loader_;
102 }
103
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800104 const void* GetClassLoaderAllocator() const {
105 return class_loader_allocator_;
106 }
107
Ian Rogers68d8b422014-07-17 11:09:10 -0700108 const std::string& GetPath() const {
109 return path_;
110 }
111
112 /*
113 * Check the result of an earlier call to JNI_OnLoad on this library.
114 * If the call has not yet finished in another thread, wait for it.
115 */
116 bool CheckOnLoadResult()
Mathieu Chartier90443472015-07-16 20:32:27 -0700117 REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700118 Thread* self = Thread::Current();
119 bool okay;
120 {
121 MutexLock mu(self, jni_on_load_lock_);
122
123 if (jni_on_load_thread_id_ == self->GetThreadId()) {
124 // Check this so we don't end up waiting for ourselves. We need to return "true" so the
125 // caller can continue.
126 LOG(INFO) << *self << " recursive attempt to load library " << "\"" << path_ << "\"";
127 okay = true;
128 } else {
129 while (jni_on_load_result_ == kPending) {
130 VLOG(jni) << "[" << *self << " waiting for \"" << path_ << "\" " << "JNI_OnLoad...]";
131 jni_on_load_cond_.Wait(self);
132 }
133
134 okay = (jni_on_load_result_ == kOkay);
135 VLOG(jni) << "[Earlier JNI_OnLoad for \"" << path_ << "\" "
136 << (okay ? "succeeded" : "failed") << "]";
137 }
138 }
139 return okay;
140 }
141
Mathieu Chartier90443472015-07-16 20:32:27 -0700142 void SetResult(bool result) REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700143 Thread* self = Thread::Current();
144 MutexLock mu(self, jni_on_load_lock_);
145
146 jni_on_load_result_ = result ? kOkay : kFailed;
147 jni_on_load_thread_id_ = 0;
148
149 // Broadcast a wakeup to anybody sleeping on the condition variable.
150 jni_on_load_cond_.Broadcast(self);
151 }
152
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800153 void SetNeedsNativeBridge(bool needs) {
154 needs_native_bridge_ = needs;
Ian Rogers68d8b422014-07-17 11:09:10 -0700155 }
156
157 bool NeedsNativeBridge() const {
158 return needs_native_bridge_;
159 }
160
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700161 // No mutator lock since dlsym may block for a while if another thread is doing dlopen.
162 void* FindSymbol(const std::string& symbol_name, const char* shorty = nullptr)
163 REQUIRES(!Locks::mutator_lock_) {
Mathieu Chartier598302a2015-09-23 14:52:39 -0700164 return NeedsNativeBridge()
Greg Kaiser338403c2019-03-26 08:22:13 -0700165 ? FindSymbolWithNativeBridge(symbol_name, shorty)
166 : FindSymbolWithoutNativeBridge(symbol_name);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700167 }
168
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700169 // No mutator lock since dlsym may block for a while if another thread is doing dlopen.
170 void* FindSymbolWithoutNativeBridge(const std::string& symbol_name)
171 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe8fec90b2015-06-30 11:23:44 -0700172 CHECK(!NeedsNativeBridge());
173
Ian Rogers68d8b422014-07-17 11:09:10 -0700174 return dlsym(handle_, symbol_name.c_str());
175 }
176
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700177 void* FindSymbolWithNativeBridge(const std::string& symbol_name, const char* shorty)
178 REQUIRES(!Locks::mutator_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700179 CHECK(NeedsNativeBridge());
180
181 uint32_t len = 0;
Calin Juravlec8423522014-08-12 20:55:20 +0100182 return android::NativeBridgeGetTrampoline(handle_, symbol_name.c_str(), shorty, len);
Ian Rogers68d8b422014-07-17 11:09:10 -0700183 }
184
185 private:
186 enum JNI_OnLoadState {
187 kPending,
188 kFailed,
189 kOkay,
190 };
191
192 // Path to library "/system/lib/libjni.so".
193 const std::string path_;
194
195 // The void* returned by dlopen(3).
196 void* const handle_;
197
198 // True if a native bridge is required.
199 bool needs_native_bridge_;
200
Mathieu Chartier598302a2015-09-23 14:52:39 -0700201 // The ClassLoader this library is associated with, a weak global JNI reference that is
Ian Rogers68d8b422014-07-17 11:09:10 -0700202 // created/deleted with the scope of the library.
Mathieu Chartier598302a2015-09-23 14:52:39 -0700203 const jweak class_loader_;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800204 // Used to do equality check on class loaders so we can avoid decoding the weak root and read
205 // barriers that mess with class unloading.
206 const void* class_loader_allocator_;
Ian Rogers68d8b422014-07-17 11:09:10 -0700207
208 // Guards remaining items.
209 Mutex jni_on_load_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
210 // Wait for JNI_OnLoad in other thread.
211 ConditionVariable jni_on_load_cond_ GUARDED_BY(jni_on_load_lock_);
212 // Recursive invocation guard.
213 uint32_t jni_on_load_thread_id_ GUARDED_BY(jni_on_load_lock_);
214 // Result of earlier JNI_OnLoad call.
215 JNI_OnLoadState jni_on_load_result_ GUARDED_BY(jni_on_load_lock_);
216};
217
218// This exists mainly to keep implementation details out of the header file.
219class Libraries {
220 public:
221 Libraries() {
222 }
223
224 ~Libraries() {
225 STLDeleteValues(&libraries_);
226 }
227
Nicolas Geoffrayc8b7d442019-03-25 09:40:22 +0000228 // NO_THREAD_SAFETY_ANALYSIS as this is during runtime shutdown, and we have
229 // no thread to lock this with.
230 void UnloadBootNativeLibraries(JavaVM* vm) const NO_THREAD_SAFETY_ANALYSIS {
231 CHECK(Thread::Current() == nullptr);
Nicolas Geoffray21b65682019-03-12 00:49:45 +0000232 std::vector<SharedLibrary*> unload_libraries;
Nicolas Geoffrayc8b7d442019-03-25 09:40:22 +0000233 for (auto it = libraries_.begin(); it != libraries_.end(); ++it) {
234 SharedLibrary* const library = it->second;
235 if (library->GetClassLoader() == nullptr) {
236 unload_libraries.push_back(library);
Nicolas Geoffray21b65682019-03-12 00:49:45 +0000237 }
238 }
239 UnloadLibraries(vm, unload_libraries);
240 }
241
Mathieu Chartier598302a2015-09-23 14:52:39 -0700242 // NO_THREAD_SAFETY_ANALYSIS since this may be called from Dumpable. Dumpable can't be annotated
243 // properly due to the template. The caller should be holding the jni_libraries_lock_.
244 void Dump(std::ostream& os) const NO_THREAD_SAFETY_ANALYSIS {
245 Locks::jni_libraries_lock_->AssertHeld(Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -0700246 bool first = true;
247 for (const auto& library : libraries_) {
248 if (!first) {
249 os << ' ';
250 }
251 first = false;
252 os << library.first;
253 }
254 }
255
Mathieu Chartier598302a2015-09-23 14:52:39 -0700256 size_t size() const REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700257 return libraries_.size();
258 }
259
Mathieu Chartier598302a2015-09-23 14:52:39 -0700260 SharedLibrary* Get(const std::string& path) REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700261 auto it = libraries_.find(path);
262 return (it == libraries_.end()) ? nullptr : it->second;
263 }
264
Mathieu Chartier598302a2015-09-23 14:52:39 -0700265 void Put(const std::string& path, SharedLibrary* library)
266 REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700267 libraries_.Put(path, library);
268 }
269
270 // See section 11.3 "Linking Native Methods" of the JNI spec.
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700271 void* FindNativeMethod(Thread* self, ArtMethod* m, std::string& detail)
272 REQUIRES(!Locks::jni_libraries_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700273 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700274 std::string jni_short_name(m->JniShortName());
275 std::string jni_long_name(m->JniLongName());
Vladimir Marko0984e482019-03-27 16:41:41 +0000276 const ObjPtr<mirror::ClassLoader> declaring_class_loader =
Vladimir Markoc524e9e2019-03-26 10:54:50 +0000277 m->GetDeclaringClass()->GetClassLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700278 ScopedObjectAccessUnchecked soa(Thread::Current());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800279 void* const declaring_class_loader_allocator =
280 Runtime::Current()->GetClassLinker()->GetAllocatorForClassLoader(declaring_class_loader);
281 CHECK(declaring_class_loader_allocator != nullptr);
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700282 // TODO: Avoid calling GetShorty here to prevent dirtying dex pages?
283 const char* shorty = m->GetShorty();
284 {
285 // Go to suspended since dlsym may block for a long time if other threads are using dlopen.
286 ScopedThreadSuspension sts(self, kNative);
287 void* native_code = FindNativeMethodInternal(self,
288 declaring_class_loader_allocator,
289 shorty,
290 jni_short_name,
291 jni_long_name);
292 if (native_code != nullptr) {
293 return native_code;
Ian Rogers68d8b422014-07-17 11:09:10 -0700294 }
295 }
296 detail += "No implementation found for ";
David Sehr709b0702016-10-13 09:12:37 -0700297 detail += m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700298 detail += " (tried " + jni_short_name + " and " + jni_long_name + ")";
Ian Rogers68d8b422014-07-17 11:09:10 -0700299 return nullptr;
300 }
301
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700302 void* FindNativeMethodInternal(Thread* self,
303 void* declaring_class_loader_allocator,
304 const char* shorty,
305 const std::string& jni_short_name,
306 const std::string& jni_long_name)
307 REQUIRES(!Locks::jni_libraries_lock_)
308 REQUIRES(!Locks::mutator_lock_) {
309 MutexLock mu(self, *Locks::jni_libraries_lock_);
310 for (const auto& lib : libraries_) {
311 SharedLibrary* const library = lib.second;
312 // Use the allocator address for class loader equality to avoid unnecessary weak root decode.
313 if (library->GetClassLoaderAllocator() != declaring_class_loader_allocator) {
314 // We only search libraries loaded by the appropriate ClassLoader.
315 continue;
316 }
317 // Try the short name then the long name...
318 const char* arg_shorty = library->NeedsNativeBridge() ? shorty : nullptr;
319 void* fn = library->FindSymbol(jni_short_name, arg_shorty);
320 if (fn == nullptr) {
321 fn = library->FindSymbol(jni_long_name, arg_shorty);
322 }
323 if (fn != nullptr) {
324 VLOG(jni) << "[Found native code for " << jni_long_name
325 << " in \"" << library->GetPath() << "\"]";
326 return fn;
327 }
328 }
329 return nullptr;
330 }
331
Mathieu Chartier598302a2015-09-23 14:52:39 -0700332 // Unload native libraries with cleared class loaders.
333 void UnloadNativeLibraries()
334 REQUIRES(!Locks::jni_libraries_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700335 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700336 Thread* const self = Thread::Current();
Alex Lightbc5669e2016-06-13 17:22:13 +0000337 std::vector<SharedLibrary*> unload_libraries;
Mathieu Chartier598302a2015-09-23 14:52:39 -0700338 {
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700339 MutexLock mu(self, *Locks::jni_libraries_lock_);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700340 for (auto it = libraries_.begin(); it != libraries_.end(); ) {
341 SharedLibrary* const library = it->second;
342 // If class loader is null then it was unloaded, call JNI_OnUnload.
Mathieu Chartiercffb7472015-09-28 10:33:00 -0700343 const jweak class_loader = library->GetClassLoader();
344 // If class_loader is a null jobject then it is the boot class loader. We should not unload
345 // the native libraries of the boot class loader.
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700346 if (class_loader != nullptr && self->IsJWeakCleared(class_loader)) {
Alex Lightbc5669e2016-06-13 17:22:13 +0000347 unload_libraries.push_back(library);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700348 it = libraries_.erase(it);
349 } else {
350 ++it;
351 }
352 }
353 }
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700354 ScopedThreadSuspension sts(self, kNative);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700355 // Do this without holding the jni libraries lock to prevent possible deadlocks.
Nicolas Geoffray21b65682019-03-12 00:49:45 +0000356 UnloadLibraries(self->GetJniEnv()->GetVm(), unload_libraries);
Alex Lightbc5669e2016-06-13 17:22:13 +0000357 for (auto library : unload_libraries) {
Nicolas Geoffray21b65682019-03-12 00:49:45 +0000358 delete library;
359 }
360 }
361
362 static void UnloadLibraries(JavaVM* vm, const std::vector<SharedLibrary*>& libraries) {
363 using JNI_OnUnloadFn = void(*)(JavaVM*, void*);
364 for (SharedLibrary* library : libraries) {
Alex Lightbc5669e2016-06-13 17:22:13 +0000365 void* const sym = library->FindSymbol("JNI_OnUnload", nullptr);
366 if (sym == nullptr) {
367 VLOG(jni) << "[No JNI_OnUnload found in \"" << library->GetPath() << "\"]";
368 } else {
369 VLOG(jni) << "[JNI_OnUnload found for \"" << library->GetPath() << "\"]: Calling...";
370 JNI_OnUnloadFn jni_on_unload = reinterpret_cast<JNI_OnUnloadFn>(sym);
Nicolas Geoffray21b65682019-03-12 00:49:45 +0000371 jni_on_unload(vm, nullptr);
Alex Lightbc5669e2016-06-13 17:22:13 +0000372 }
Mathieu Chartier598302a2015-09-23 14:52:39 -0700373 }
374 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700375
Mathieu Chartier598302a2015-09-23 14:52:39 -0700376 private:
377 AllocationTrackingSafeMap<std::string, SharedLibrary*, kAllocatorTagJNILibraries> libraries_
378 GUARDED_BY(Locks::jni_libraries_lock_);
379};
Ian Rogers68d8b422014-07-17 11:09:10 -0700380
381class JII {
382 public:
383 static jint DestroyJavaVM(JavaVM* vm) {
384 if (vm == nullptr) {
385 return JNI_ERR;
386 }
387 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
Hans Boehmdc77ca32020-01-31 16:29:35 -0800388
389 // Wait for all non-dameon threads to terminate before we start destroying
390 // bits of the runtime. Thread list deletion will repeat this in case more
391 // threads are created by daemons in the meantime.
392 raw_vm->GetRuntime()->GetThreadList()
393 ->WaitForOtherNonDaemonThreadsToExit(/*check_no_birth=*/ false);
394
Ian Rogers68d8b422014-07-17 11:09:10 -0700395 delete raw_vm->GetRuntime();
Dimitry Ivanov39d68ef2016-04-29 16:02:38 -0700396 android::ResetNativeLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700397 return JNI_OK;
398 }
399
400 static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
401 return AttachCurrentThreadInternal(vm, p_env, thr_args, false);
402 }
403
404 static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
405 return AttachCurrentThreadInternal(vm, p_env, thr_args, true);
406 }
407
408 static jint DetachCurrentThread(JavaVM* vm) {
409 if (vm == nullptr || Thread::Current() == nullptr) {
410 return JNI_ERR;
411 }
412 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
413 Runtime* runtime = raw_vm->GetRuntime();
414 runtime->DetachCurrentThread();
415 return JNI_OK;
416 }
417
418 static jint GetEnv(JavaVM* vm, void** env, jint version) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700419 if (vm == nullptr || env == nullptr) {
420 return JNI_ERR;
421 }
422 Thread* thread = Thread::Current();
423 if (thread == nullptr) {
424 *env = nullptr;
425 return JNI_EDETACHED;
426 }
Alex Light185d1342016-08-11 10:48:03 -0700427 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
428 return raw_vm->HandleGetEnv(env, version);
Ian Rogers68d8b422014-07-17 11:09:10 -0700429 }
430
431 private:
432 static jint AttachCurrentThreadInternal(JavaVM* vm, JNIEnv** p_env, void* raw_args, bool as_daemon) {
433 if (vm == nullptr || p_env == nullptr) {
434 return JNI_ERR;
435 }
436
437 // Return immediately if we're already attached.
438 Thread* self = Thread::Current();
439 if (self != nullptr) {
440 *p_env = self->GetJniEnv();
441 return JNI_OK;
442 }
443
444 Runtime* runtime = reinterpret_cast<JavaVMExt*>(vm)->GetRuntime();
445
446 // No threads allowed in zygote mode.
447 if (runtime->IsZygote()) {
448 LOG(ERROR) << "Attempt to attach a thread in the zygote";
449 return JNI_ERR;
450 }
451
452 JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(raw_args);
453 const char* thread_name = nullptr;
454 jobject thread_group = nullptr;
455 if (args != nullptr) {
Alex Light185d1342016-08-11 10:48:03 -0700456 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700457 LOG(ERROR) << "Bad JNI version passed to "
458 << (as_daemon ? "AttachCurrentThreadAsDaemon" : "AttachCurrentThread") << ": "
459 << args->version;
460 return JNI_EVERSION;
461 }
462 thread_name = args->name;
463 thread_group = args->group;
464 }
465
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800466 if (!runtime->AttachCurrentThread(thread_name, as_daemon, thread_group,
467 !runtime->IsAotCompiler())) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700468 *p_env = nullptr;
469 return JNI_ERR;
470 } else {
471 *p_env = Thread::Current()->GetJniEnv();
472 return JNI_OK;
473 }
474 }
475};
476
477const JNIInvokeInterface gJniInvokeInterface = {
478 nullptr, // reserved0
479 nullptr, // reserved1
480 nullptr, // reserved2
481 JII::DestroyJavaVM,
482 JII::AttachCurrentThread,
483 JII::DetachCurrentThread,
484 JII::GetEnv,
485 JII::AttachCurrentThreadAsDaemon
486};
487
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100488JavaVMExt::JavaVMExt(Runtime* runtime,
489 const RuntimeArgumentMap& runtime_options,
490 std::string* error_msg)
Ian Rogers68d8b422014-07-17 11:09:10 -0700491 : runtime_(runtime),
492 check_jni_abort_hook_(nullptr),
493 check_jni_abort_hook_data_(nullptr),
494 check_jni_(false), // Initialized properly in the constructor body below.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800495 force_copy_(runtime_options.Exists(RuntimeArgumentMap::JniOptsForceCopy)),
496 tracing_enabled_(runtime_options.Exists(RuntimeArgumentMap::JniTrace)
497 || VLOG_IS_ON(third_party_jni)),
498 trace_(runtime_options.GetOrDefault(RuntimeArgumentMap::JniTrace)),
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700499 globals_(kGlobalsMax, kGlobal, IndirectReferenceTable::ResizableCapacity::kNo, error_msg),
Ian Rogers68d8b422014-07-17 11:09:10 -0700500 libraries_(new Libraries),
501 unchecked_functions_(&gJniInvokeInterface),
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700502 weak_globals_(kWeakGlobalsMax,
503 kWeakGlobal,
504 IndirectReferenceTable::ResizableCapacity::kNo,
505 error_msg),
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700506 allow_accessing_weak_globals_(true),
Andreas Gampe05a364c2016-10-14 13:27:12 -0700507 weak_globals_add_condition_("weak globals add condition",
508 (CHECK(Locks::jni_weak_globals_lock_ != nullptr),
509 *Locks::jni_weak_globals_lock_)),
Andreas Gampe1b35b462017-09-29 18:52:15 -0700510 env_hooks_(),
511 enable_allocation_tracking_delta_(
512 runtime_options.GetOrDefault(RuntimeArgumentMap::GlobalRefAllocStackTraceLimit)),
513 allocation_tracking_enabled_(false),
514 old_allocation_tracking_state_(false) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700515 functions = unchecked_functions_;
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800516 SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni));
Ian Rogers68d8b422014-07-17 11:09:10 -0700517}
518
519JavaVMExt::~JavaVMExt() {
Nicolas Geoffrayc8b7d442019-03-25 09:40:22 +0000520 UnloadBootNativeLibraries();
Ian Rogers68d8b422014-07-17 11:09:10 -0700521}
522
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100523// Checking "globals" and "weak_globals" usually requires locks, but we
524// don't need the locks to check for validity when constructing the
525// object. Use NO_THREAD_SAFETY_ANALYSIS for this.
526std::unique_ptr<JavaVMExt> JavaVMExt::Create(Runtime* runtime,
527 const RuntimeArgumentMap& runtime_options,
528 std::string* error_msg) NO_THREAD_SAFETY_ANALYSIS {
529 std::unique_ptr<JavaVMExt> java_vm(new JavaVMExt(runtime, runtime_options, error_msg));
530 if (java_vm && java_vm->globals_.IsValid() && java_vm->weak_globals_.IsValid()) {
531 return java_vm;
532 }
533 return nullptr;
534}
535
Alex Light185d1342016-08-11 10:48:03 -0700536jint JavaVMExt::HandleGetEnv(/*out*/void** env, jint version) {
537 for (GetEnvHook hook : env_hooks_) {
538 jint res = hook(this, env, version);
539 if (res == JNI_OK) {
540 return JNI_OK;
541 } else if (res != JNI_EVERSION) {
542 LOG(ERROR) << "Error returned from a plugin GetEnv handler! " << res;
543 return res;
544 }
545 }
546 LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version;
547 return JNI_EVERSION;
548}
549
550// Add a hook to handle getting environments from the GetEnv call.
551void JavaVMExt::AddEnvironmentHook(GetEnvHook hook) {
552 CHECK(hook != nullptr) << "environment hooks shouldn't be null!";
553 env_hooks_.push_back(hook);
554}
555
Ian Rogers68d8b422014-07-17 11:09:10 -0700556void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) {
557 Thread* self = Thread::Current();
558 ScopedObjectAccess soa(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700559 ArtMethod* current_method = self->GetCurrentMethod(nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700560
561 std::ostringstream os;
562 os << "JNI DETECTED ERROR IN APPLICATION: " << msg;
563
564 if (jni_function_name != nullptr) {
565 os << "\n in call to " << jni_function_name;
566 }
567 // TODO: is this useful given that we're about to dump the calling thread's stack?
568 if (current_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700569 os << "\n from " << current_method->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700570 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700571
572 if (check_jni_abort_hook_ != nullptr) {
573 check_jni_abort_hook_(check_jni_abort_hook_data_, os.str());
574 } else {
575 // Ensure that we get a native stack trace for this thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700576 ScopedThreadSuspension sts(self, kNative);
Ian Rogers68d8b422014-07-17 11:09:10 -0700577 LOG(FATAL) << os.str();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700578 UNREACHABLE();
Ian Rogers68d8b422014-07-17 11:09:10 -0700579 }
580}
581
582void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) {
583 std::string msg;
584 StringAppendV(&msg, fmt, ap);
585 JniAbort(jni_function_name, msg.c_str());
586}
587
588void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) {
589 va_list args;
590 va_start(args, fmt);
591 JniAbortV(jni_function_name, fmt, args);
592 va_end(args);
593}
594
Mathieu Chartiere401d142015-04-22 13:56:20 -0700595bool JavaVMExt::ShouldTrace(ArtMethod* method) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700596 // Fast where no tracing is enabled.
597 if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) {
598 return false;
599 }
600 // Perform checks based on class name.
Vladimir Marko72101082019-02-05 16:16:30 +0000601 std::string_view class_name(method->GetDeclaringClassDescriptor());
602 if (!trace_.empty() && class_name.find(trace_) != std::string_view::npos) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700603 return true;
604 }
605 if (!VLOG_IS_ON(third_party_jni)) {
606 return false;
607 }
608 // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
609 // like part of Android.
Vladimir Marko72101082019-02-05 16:16:30 +0000610 static const char* const gBuiltInPrefixes[] = {
Ian Rogers68d8b422014-07-17 11:09:10 -0700611 "Landroid/",
612 "Lcom/android/",
613 "Lcom/google/android/",
614 "Ldalvik/",
615 "Ljava/",
616 "Ljavax/",
617 "Llibcore/",
618 "Lorg/apache/harmony/",
619 };
620 for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) {
Vladimir Marko72101082019-02-05 16:16:30 +0000621 if (StartsWith(class_name, gBuiltInPrefixes[i])) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700622 return false;
623 }
624 }
625 return true;
626}
627
Andreas Gampe1b35b462017-09-29 18:52:15 -0700628void JavaVMExt::CheckGlobalRefAllocationTracking() {
629 if (LIKELY(enable_allocation_tracking_delta_ == 0)) {
630 return;
631 }
632 size_t simple_free_capacity = globals_.FreeCapacity();
633 if (UNLIKELY(simple_free_capacity <= enable_allocation_tracking_delta_)) {
634 if (!allocation_tracking_enabled_) {
635 LOG(WARNING) << "Global reference storage appears close to exhaustion, program termination "
636 << "may be imminent. Enabling allocation tracking to improve abort diagnostics. "
637 << "This will result in program slow-down.";
638
639 old_allocation_tracking_state_ = runtime_->GetHeap()->IsAllocTrackingEnabled();
640 if (!old_allocation_tracking_state_) {
641 // Need to be guaranteed suspended.
642 ScopedObjectAccess soa(Thread::Current());
643 ScopedThreadSuspension sts(soa.Self(), ThreadState::kNative);
644 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(true);
645 }
646 allocation_tracking_enabled_ = true;
647 }
648 } else {
649 if (UNLIKELY(allocation_tracking_enabled_)) {
650 if (!old_allocation_tracking_state_) {
651 // Need to be guaranteed suspended.
652 ScopedObjectAccess soa(Thread::Current());
653 ScopedThreadSuspension sts(soa.Self(), ThreadState::kNative);
654 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(false);
655 }
Andreas Gampe45485342017-10-11 12:04:35 -0700656 allocation_tracking_enabled_ = false;
Andreas Gampe1b35b462017-09-29 18:52:15 -0700657 }
658 }
659}
660
Mathieu Chartier0795f232016-09-27 18:43:30 -0700661jobject JavaVMExt::AddGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700662 // Check for null after decoding the object to handle cleared weak globals.
663 if (obj == nullptr) {
664 return nullptr;
665 }
Andreas Gampe1b35b462017-09-29 18:52:15 -0700666 IndirectRef ref;
Andreas Gampe25651122017-09-25 14:50:23 -0700667 std::string error_msg;
Andreas Gampe1b35b462017-09-29 18:52:15 -0700668 {
669 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
670 ref = globals_.Add(kIRTFirstSegment, obj, &error_msg);
671 }
Andreas Gampe25651122017-09-25 14:50:23 -0700672 if (UNLIKELY(ref == nullptr)) {
673 LOG(FATAL) << error_msg;
674 UNREACHABLE();
675 }
Andreas Gampe1b35b462017-09-29 18:52:15 -0700676 CheckGlobalRefAllocationTracking();
Ian Rogers68d8b422014-07-17 11:09:10 -0700677 return reinterpret_cast<jobject>(ref);
678}
679
Mathieu Chartier0795f232016-09-27 18:43:30 -0700680jweak JavaVMExt::AddWeakGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700681 if (obj == nullptr) {
682 return nullptr;
683 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700684 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchif1c6f872017-01-06 12:23:47 -0800685 // CMS needs this to block for concurrent reference processing because an object allocated during
686 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
687 // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant.
688 while (!kUseReadBarrier && UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700689 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
690 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800691 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700692 weak_globals_add_condition_.WaitHoldingLocks(self);
693 }
Andreas Gampe25651122017-09-25 14:50:23 -0700694 std::string error_msg;
695 IndirectRef ref = weak_globals_.Add(kIRTFirstSegment, obj, &error_msg);
696 if (UNLIKELY(ref == nullptr)) {
697 LOG(FATAL) << error_msg;
698 UNREACHABLE();
699 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700700 return reinterpret_cast<jweak>(ref);
701}
702
703void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
704 if (obj == nullptr) {
705 return;
706 }
Andreas Gampe1b35b462017-09-29 18:52:15 -0700707 {
708 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
709 if (!globals_.Remove(kIRTFirstSegment, obj)) {
710 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
711 << "failed to find entry";
712 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700713 }
Andreas Gampe1b35b462017-09-29 18:52:15 -0700714 CheckGlobalRefAllocationTracking();
Ian Rogers68d8b422014-07-17 11:09:10 -0700715}
716
717void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
718 if (obj == nullptr) {
719 return;
720 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700721 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700722 if (!weak_globals_.Remove(kIRTFirstSegment, obj)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700723 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
724 << "failed to find entry";
725 }
726}
727
728static void ThreadEnableCheckJni(Thread* thread, void* arg) {
729 bool* check_jni = reinterpret_cast<bool*>(arg);
730 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
731}
732
733bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
734 bool old_check_jni = check_jni_;
735 check_jni_ = enabled;
736 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
737 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
738 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
739 return old_check_jni;
740}
741
742void JavaVMExt::DumpForSigQuit(std::ostream& os) {
743 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
744 if (force_copy_) {
745 os << " (with forcecopy)";
746 }
747 Thread* self = Thread::Current();
748 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700749 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700750 os << "; globals=" << globals_.Capacity();
751 }
752 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700753 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700754 if (weak_globals_.Capacity() > 0) {
755 os << " (plus " << weak_globals_.Capacity() << " weak)";
756 }
757 }
758 os << '\n';
759
760 {
761 MutexLock mu(self, *Locks::jni_libraries_lock_);
762 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
763 }
764}
765
766void JavaVMExt::DisallowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700767 CHECK(!kUseReadBarrier);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700768 Thread* const self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700769 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700770 // DisallowNewWeakGlobals is only called by CMS during the pause. It is required to have the
771 // mutator lock exclusively held so that we don't have any threads in the middle of
772 // DecodeWeakGlobal.
773 Locks::mutator_lock_->AssertExclusiveHeld(self);
Orion Hodson88591fe2018-03-06 13:35:43 +0000774 allow_accessing_weak_globals_.store(false, std::memory_order_seq_cst);
Ian Rogers68d8b422014-07-17 11:09:10 -0700775}
776
777void JavaVMExt::AllowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700778 CHECK(!kUseReadBarrier);
Ian Rogers68d8b422014-07-17 11:09:10 -0700779 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700780 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Orion Hodson88591fe2018-03-06 13:35:43 +0000781 allow_accessing_weak_globals_.store(true, std::memory_order_seq_cst);
Ian Rogers68d8b422014-07-17 11:09:10 -0700782 weak_globals_add_condition_.Broadcast(self);
783}
784
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700785void JavaVMExt::BroadcastForNewWeakGlobals() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700786 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700787 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700788 weak_globals_add_condition_.Broadcast(self);
789}
790
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700791ObjPtr<mirror::Object> JavaVMExt::DecodeGlobal(IndirectRef ref) {
792 return globals_.SynchronizedGet(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700793}
794
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700795void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700796 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700797 globals_.Update(ref, result);
798}
799
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700800inline bool JavaVMExt::MayAccessWeakGlobals(Thread* self) const {
801 return MayAccessWeakGlobalsUnlocked(self);
802}
803
804inline bool JavaVMExt::MayAccessWeakGlobalsUnlocked(Thread* self) const {
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700805 DCHECK(self != nullptr);
806 return kUseReadBarrier ?
807 self->GetWeakRefAccessEnabled() :
Orion Hodson88591fe2018-03-06 13:35:43 +0000808 allow_accessing_weak_globals_.load(std::memory_order_seq_cst);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700809}
810
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700811ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700812 // It is safe to access GetWeakRefAccessEnabled without the lock since CC uses checkpoints to call
813 // SetWeakRefAccessEnabled, and the other collectors only modify allow_accessing_weak_globals_
814 // when the mutators are paused.
815 // This only applies in the case where MayAccessWeakGlobals goes from false to true. In the other
816 // case, it may be racy, this is benign since DecodeWeakGlobalLocked does the correct behavior
817 // if MayAccessWeakGlobals is false.
Andreas Gampedc061d02016-10-24 13:19:37 -0700818 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700819 if (LIKELY(MayAccessWeakGlobalsUnlocked(self))) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700820 return weak_globals_.SynchronizedGet(ref);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700821 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700822 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700823 return DecodeWeakGlobalLocked(self, ref);
824}
825
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700826ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalLocked(Thread* self, IndirectRef ref) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700827 if (kDebugLocking) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700828 Locks::jni_weak_globals_lock_->AssertHeld(self);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700829 }
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700830 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700831 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
832 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800833 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700834 weak_globals_add_condition_.WaitHoldingLocks(self);
835 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700836 return weak_globals_.Get(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700837}
838
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700839ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalDuringShutdown(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700840 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700841 DCHECK(Runtime::Current()->IsShuttingDown(self));
842 if (self != nullptr) {
843 return DecodeWeakGlobal(self, ref);
844 }
845 // self can be null during a runtime shutdown. ~Runtime()->~ClassLinker()->DecodeWeakGlobal().
846 if (!kUseReadBarrier) {
Orion Hodson88591fe2018-03-06 13:35:43 +0000847 DCHECK(allow_accessing_weak_globals_.load(std::memory_order_seq_cst));
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700848 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700849 return weak_globals_.SynchronizedGet(ref);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700850}
851
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800852bool JavaVMExt::IsWeakGlobalCleared(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700853 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Andreas Gampe05a364c2016-10-14 13:27:12 -0700854 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800855 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700856 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
857 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800858 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800859 weak_globals_add_condition_.WaitHoldingLocks(self);
860 }
861 // When just checking a weak ref has been cleared, avoid triggering the read barrier in decode
862 // (DecodeWeakGlobal) so that we won't accidentally mark the object alive. Since the cleared
863 // sentinel is a non-moving object, we can compare the ref to it without the read barrier and
864 // decide if it's cleared.
865 return Runtime::Current()->IsClearedJniWeakGlobal(weak_globals_.Get<kWithoutReadBarrier>(ref));
866}
867
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700868void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700869 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700870 weak_globals_.Update(ref, result);
871}
872
Ian Rogers68d8b422014-07-17 11:09:10 -0700873void JavaVMExt::DumpReferenceTables(std::ostream& os) {
874 Thread* self = Thread::Current();
875 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700876 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700877 globals_.Dump(os);
878 }
879 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700880 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700881 weak_globals_.Dump(os);
882 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700883}
884
Mathieu Chartier598302a2015-09-23 14:52:39 -0700885void JavaVMExt::UnloadNativeLibraries() {
886 libraries_.get()->UnloadNativeLibraries();
887}
888
Nicolas Geoffray21b65682019-03-12 00:49:45 +0000889void JavaVMExt::UnloadBootNativeLibraries() {
890 libraries_.get()->UnloadBootNativeLibraries(this);
891}
892
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800893bool JavaVMExt::LoadNativeLibrary(JNIEnv* env,
894 const std::string& path,
895 jobject class_loader,
Nicolas Geoffray96259f12019-01-18 10:04:51 +0000896 jclass caller_class,
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800897 std::string* error_msg) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700898 error_msg->clear();
899
900 // See if we've already loaded this library. If we have, and the class loader
901 // matches, return successfully without doing anything.
902 // TODO: for better results we should canonicalize the pathname (or even compare
903 // inodes). This implementation is fine if everybody is using System.loadLibrary.
904 SharedLibrary* library;
905 Thread* self = Thread::Current();
906 {
907 // TODO: move the locking (and more of this logic) into Libraries.
908 MutexLock mu(self, *Locks::jni_libraries_lock_);
909 library = libraries_->Get(path);
910 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800911 void* class_loader_allocator = nullptr;
Nicolas Geoffray96259f12019-01-18 10:04:51 +0000912 std::string caller_location;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800913 {
914 ScopedObjectAccess soa(env);
915 // As the incoming class loader is reachable/alive during the call of this function,
916 // it's okay to decode it without worrying about unexpectedly marking it alive.
Mathieu Chartier0795f232016-09-27 18:43:30 -0700917 ObjPtr<mirror::ClassLoader> loader = soa.Decode<mirror::ClassLoader>(class_loader);
Andreas Gampe2d48e532016-06-17 12:46:14 -0700918
919 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700920 if (class_linker->IsBootClassLoader(soa, loader.Ptr())) {
Andreas Gampe2d48e532016-06-17 12:46:14 -0700921 loader = nullptr;
922 class_loader = nullptr;
Nicolas Geoffray96259f12019-01-18 10:04:51 +0000923 if (caller_class != nullptr) {
924 ObjPtr<mirror::Class> caller = soa.Decode<mirror::Class>(caller_class);
925 ObjPtr<mirror::DexCache> dex_cache = caller->GetDexCache();
926 if (dex_cache != nullptr) {
927 caller_location = dex_cache->GetLocation()->ToModifiedUtf8();
928 }
929 }
Andreas Gampe2d48e532016-06-17 12:46:14 -0700930 }
931
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700932 class_loader_allocator = class_linker->GetAllocatorForClassLoader(loader.Ptr());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800933 CHECK(class_loader_allocator != nullptr);
934 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700935 if (library != nullptr) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800936 // Use the allocator pointers for class loader equality to avoid unnecessary weak root decode.
937 if (library->GetClassLoaderAllocator() != class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700938 // The library will be associated with class_loader. The JNI
939 // spec says we can't load the same library into more than one
940 // class loader.
Andreas Gampefd03f1e2017-09-19 17:10:10 -0700941 //
942 // This isn't very common. So spend some time to get a readable message.
943 auto call_to_string = [&](jobject obj) -> std::string {
944 if (obj == nullptr) {
945 return "null";
946 }
947 // Handle jweaks. Ignore double local-ref.
948 ScopedLocalRef<jobject> local_ref(env, env->NewLocalRef(obj));
949 if (local_ref != nullptr) {
950 ScopedLocalRef<jclass> local_class(env, env->GetObjectClass(local_ref.get()));
951 jmethodID to_string = env->GetMethodID(local_class.get(),
952 "toString",
953 "()Ljava/lang/String;");
954 DCHECK(to_string != nullptr);
955 ScopedLocalRef<jobject> local_string(env,
956 env->CallObjectMethod(local_ref.get(), to_string));
957 if (local_string != nullptr) {
958 ScopedUtfChars utf(env, reinterpret_cast<jstring>(local_string.get()));
959 if (utf.c_str() != nullptr) {
960 return utf.c_str();
961 }
962 }
Andreas Gampe3362d222018-06-05 16:02:10 -0700963 if (env->ExceptionCheck()) {
964 // We can't do much better logging, really. So leave it with a Describe.
965 env->ExceptionDescribe();
966 env->ExceptionClear();
967 }
Andreas Gampefd03f1e2017-09-19 17:10:10 -0700968 return "(Error calling toString)";
969 }
970 return "null";
971 };
972 std::string old_class_loader = call_to_string(library->GetClassLoader());
973 std::string new_class_loader = call_to_string(class_loader);
Ian Rogers68d8b422014-07-17 11:09:10 -0700974 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
Andreas Gampefd03f1e2017-09-19 17:10:10 -0700975 "ClassLoader %p(%s); can't open in ClassLoader %p(%s)",
976 path.c_str(),
977 library->GetClassLoader(),
978 old_class_loader.c_str(),
979 class_loader,
980 new_class_loader.c_str());
Andreas Gampe335ee582017-09-19 17:09:52 -0700981 LOG(WARNING) << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700982 return false;
983 }
984 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
985 << " ClassLoader " << class_loader << "]";
986 if (!library->CheckOnLoadResult()) {
987 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
988 "to load \"%s\"", path.c_str());
989 return false;
990 }
991 return true;
992 }
993
994 // Open the shared library. Because we're using a full path, the system
995 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
996 // resolve this library's dependencies though.)
997
998 // Failures here are expected when java.library.path has several entries
999 // and we have to hunt for the lib.
1000
1001 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
1002 // class unloading. Libraries will only be unloaded when the reference count (incremented by
1003 // dlopen) becomes zero from dlclose.
1004
Andreas Gampe473191c2017-12-28 16:55:31 -08001005 // Retrieve the library path from the classloader, if necessary.
1006 ScopedLocalRef<jstring> library_path(env, GetLibrarySearchPath(env, class_loader));
1007
Ian Rogers68d8b422014-07-17 11:09:10 -07001008 Locks::mutator_lock_->AssertNotHeld(self);
1009 const char* path_str = path.empty() ? nullptr : path.c_str();
Zhenhua WANG8447e6d2016-05-30 11:10:29 +08001010 bool needs_native_bridge = false;
Nicolas Geoffrayc3ba7ee2019-01-16 21:46:48 +00001011 char* nativeloader_error_msg = nullptr;
Nicolas Geoffray96259f12019-01-18 10:04:51 +00001012 void* handle = android::OpenNativeLibrary(
1013 env,
1014 runtime_->GetTargetSdkVersion(),
1015 path_str,
1016 class_loader,
1017 (caller_location.empty() ? nullptr : caller_location.c_str()),
1018 library_path.get(),
1019 &needs_native_bridge,
1020 &nativeloader_error_msg);
Dmitriy Ivanov53056722015-03-23 13:38:20 -07001021 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]";
Ian Rogers68d8b422014-07-17 11:09:10 -07001022
1023 if (handle == nullptr) {
Nicolas Geoffrayd9b30692019-01-12 14:59:05 +00001024 *error_msg = nativeloader_error_msg;
Nicolas Geoffrayc3ba7ee2019-01-16 21:46:48 +00001025 android::NativeLoaderFreeErrorMessage(nativeloader_error_msg);
Dmitriy Ivanov53056722015-03-23 13:38:20 -07001026 VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -07001027 return false;
1028 }
1029
1030 if (env->ExceptionCheck() == JNI_TRUE) {
1031 LOG(ERROR) << "Unexpected exception:";
1032 env->ExceptionDescribe();
1033 env->ExceptionClear();
1034 }
1035 // Create a new entry.
1036 // TODO: move the locking (and more of this logic) into Libraries.
1037 bool created_library = false;
1038 {
1039 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
1040 std::unique_ptr<SharedLibrary> new_library(
Zhenhua WANG8447e6d2016-05-30 11:10:29 +08001041 new SharedLibrary(env,
1042 self,
1043 path,
1044 handle,
1045 needs_native_bridge,
1046 class_loader,
1047 class_loader_allocator));
1048
Ian Rogers68d8b422014-07-17 11:09:10 -07001049 MutexLock mu(self, *Locks::jni_libraries_lock_);
1050 library = libraries_->Get(path);
1051 if (library == nullptr) { // We won race to get libraries_lock.
1052 library = new_library.release();
1053 libraries_->Put(path, library);
1054 created_library = true;
1055 }
1056 }
1057 if (!created_library) {
1058 LOG(INFO) << "WOW: we lost a race to add shared library: "
1059 << "\"" << path << "\" ClassLoader=" << class_loader;
1060 return library->CheckOnLoadResult();
1061 }
1062 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
1063
1064 bool was_successful = false;
Zhenhua WANG8447e6d2016-05-30 11:10:29 +08001065 void* sym = library->FindSymbol("JNI_OnLoad", nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -07001066 if (sym == nullptr) {
1067 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
1068 was_successful = true;
1069 } else {
1070 // Call JNI_OnLoad. We have to override the current class
1071 // loader, which will always be "null" since the stuff at the
1072 // top of the stack is around Runtime.loadLibrary(). (See
1073 // the comments in the JNI FindClass function.)
1074 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
1075 self->SetClassLoaderOverride(class_loader);
1076
1077 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
Andreas Gampec55bb392018-09-21 00:02:02 +00001078 using JNI_OnLoadFn = int(*)(JavaVM*, void*);
Ian Rogers68d8b422014-07-17 11:09:10 -07001079 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
1080 int version = (*jni_on_load)(this, nullptr);
1081
David Brazdil2bb2fbd2018-11-13 18:24:26 +00001082 if (IsSdkVersionSetAndAtMost(runtime_->GetTargetSdkVersion(), SdkVersion::kL)) {
Josh Gao85a78cf2017-03-20 16:26:42 -07001083 // Make sure that sigchain owns SIGSEGV.
1084 EnsureFrontOfChain(SIGSEGV);
Mathieu Chartierd0004802014-10-15 16:59:47 -07001085 }
1086
Ian Rogers68d8b422014-07-17 11:09:10 -07001087 self->SetClassLoaderOverride(old_class_loader.get());
1088
1089 if (version == JNI_ERR) {
1090 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
Alex Light185d1342016-08-11 10:48:03 -07001091 } else if (JavaVMExt::IsBadJniVersion(version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001092 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
1093 path.c_str(), version);
1094 // It's unwise to call dlclose() here, but we can mark it
1095 // as bad and ensure that future load attempts will fail.
1096 // We don't know how far JNI_OnLoad got, so there could
1097 // be some partially-initialized stuff accessible through
1098 // newly-registered native method calls. We could try to
1099 // unregister them, but that doesn't seem worthwhile.
1100 } else {
1101 was_successful = true;
1102 }
1103 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
1104 << " from JNI_OnLoad in \"" << path << "\"]";
1105 }
1106
1107 library->SetResult(was_successful);
1108 return was_successful;
1109}
1110
Alex Light65af20b2017-04-20 09:15:08 -07001111static void* FindCodeForNativeMethodInAgents(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
1112 std::string jni_short_name(m->JniShortName());
1113 std::string jni_long_name(m->JniLongName());
Andreas Gampeaadcbc62017-12-28 14:05:42 -08001114 for (const std::unique_ptr<ti::Agent>& agent : Runtime::Current()->GetAgents()) {
1115 void* fn = agent->FindSymbol(jni_short_name);
Alex Light65af20b2017-04-20 09:15:08 -07001116 if (fn != nullptr) {
1117 VLOG(jni) << "Found implementation for " << m->PrettyMethod()
Andreas Gampeaadcbc62017-12-28 14:05:42 -08001118 << " (symbol: " << jni_short_name << ") in " << *agent;
Alex Light65af20b2017-04-20 09:15:08 -07001119 return fn;
1120 }
Andreas Gampeaadcbc62017-12-28 14:05:42 -08001121 fn = agent->FindSymbol(jni_long_name);
Alex Light65af20b2017-04-20 09:15:08 -07001122 if (fn != nullptr) {
1123 VLOG(jni) << "Found implementation for " << m->PrettyMethod()
Andreas Gampeaadcbc62017-12-28 14:05:42 -08001124 << " (symbol: " << jni_long_name << ") in " << *agent;
Alex Light65af20b2017-04-20 09:15:08 -07001125 return fn;
1126 }
1127 }
1128 return nullptr;
1129}
1130
Mathieu Chartiere401d142015-04-22 13:56:20 -07001131void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001132 CHECK(m->IsNative());
Vladimir Markod93e3742018-07-18 10:58:13 +01001133 ObjPtr<mirror::Class> c = m->GetDeclaringClass();
Ian Rogers68d8b422014-07-17 11:09:10 -07001134 // If this is a static method, it could be called before the class has been initialized.
David Sehr709b0702016-10-13 09:12:37 -07001135 CHECK(c->IsInitializing()) << c->GetStatus() << " " << m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -07001136 std::string detail;
Mathieu Chartier46e75d02017-06-02 16:03:39 -07001137 Thread* const self = Thread::Current();
1138 void* native_method = libraries_->FindNativeMethod(self, m, detail);
Alex Light65af20b2017-04-20 09:15:08 -07001139 if (native_method == nullptr) {
1140 // Lookup JNI native methods from native TI Agent libraries. See runtime/ti/agent.h for more
1141 // information. Agent libraries are searched for native methods after all jni libraries.
1142 native_method = FindCodeForNativeMethodInAgents(m);
1143 }
Ian Rogers68d8b422014-07-17 11:09:10 -07001144 // Throwing can cause libraries_lock to be reacquired.
1145 if (native_method == nullptr) {
Alex Light65af20b2017-04-20 09:15:08 -07001146 LOG(ERROR) << detail;
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001147 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
Ian Rogers68d8b422014-07-17 11:09:10 -07001148 }
1149 return native_method;
1150}
1151
Mathieu Chartier97509952015-07-13 14:35:43 -07001152void JavaVMExt::SweepJniWeakGlobals(IsMarkedVisitor* visitor) {
Andreas Gampe05a364c2016-10-14 13:27:12 -07001153 MutexLock mu(Thread::Current(), *Locks::jni_weak_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001154 Runtime* const runtime = Runtime::Current();
1155 for (auto* entry : weak_globals_) {
1156 // Need to skip null here to distinguish between null entries and cleared weak ref entries.
1157 if (!entry->IsNull()) {
1158 // Since this is called by the GC, we don't need a read barrier.
1159 mirror::Object* obj = entry->Read<kWithoutReadBarrier>();
Mathieu Chartier97509952015-07-13 14:35:43 -07001160 mirror::Object* new_obj = visitor->IsMarked(obj);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001161 if (new_obj == nullptr) {
1162 new_obj = runtime->GetClearedJniWeakGlobal();
1163 }
1164 *entry = GcRoot<mirror::Object>(new_obj);
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -07001165 }
Ian Rogers68d8b422014-07-17 11:09:10 -07001166 }
1167}
1168
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001169void JavaVMExt::TrimGlobals() {
Andreas Gampe05a364c2016-10-14 13:27:12 -07001170 WriterMutexLock mu(Thread::Current(), *Locks::jni_globals_lock_);
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001171 globals_.Trim();
1172}
1173
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001174void JavaVMExt::VisitRoots(RootVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001175 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -07001176 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001177 globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal));
Ian Rogers68d8b422014-07-17 11:09:10 -07001178 // The weak_globals table is visited by the GC itself (because it mutates the table).
1179}
1180
Andreas Gampe473191c2017-12-28 16:55:31 -08001181jstring JavaVMExt::GetLibrarySearchPath(JNIEnv* env, jobject class_loader) {
1182 if (class_loader == nullptr) {
1183 return nullptr;
1184 }
1185 if (!env->IsInstanceOf(class_loader, WellKnownClasses::dalvik_system_BaseDexClassLoader)) {
1186 return nullptr;
1187 }
1188 return reinterpret_cast<jstring>(env->CallObjectMethod(
1189 class_loader,
1190 WellKnownClasses::dalvik_system_BaseDexClassLoader_getLdLibraryPath));
1191}
1192
Ian Rogers68d8b422014-07-17 11:09:10 -07001193// JNI Invocation interface.
1194
1195extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001196 ScopedTrace trace(__FUNCTION__);
Ian Rogers68d8b422014-07-17 11:09:10 -07001197 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
Alex Light185d1342016-08-11 10:48:03 -07001198 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001199 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
1200 return JNI_EVERSION;
1201 }
1202 RuntimeOptions options;
1203 for (int i = 0; i < args->nOptions; ++i) {
1204 JavaVMOption* option = &args->options[i];
1205 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
1206 }
1207 bool ignore_unrecognized = args->ignoreUnrecognized;
1208 if (!Runtime::Create(options, ignore_unrecognized)) {
1209 return JNI_ERR;
1210 }
Dimitry Ivanovc544f342016-05-09 16:26:13 -07001211
1212 // Initialize native loader. This step makes sure we have
1213 // everything set up before we start using JNI.
1214 android::InitializeNativeLoader();
1215
Ian Rogers68d8b422014-07-17 11:09:10 -07001216 Runtime* runtime = Runtime::Current();
1217 bool started = runtime->Start();
1218 if (!started) {
1219 delete Thread::Current()->GetJniEnv();
1220 delete runtime->GetJavaVM();
1221 LOG(WARNING) << "CreateJavaVM failed";
1222 return JNI_ERR;
1223 }
Dimitry Ivanov041169f2016-04-21 16:01:24 -07001224
Ian Rogers68d8b422014-07-17 11:09:10 -07001225 *p_env = Thread::Current()->GetJniEnv();
1226 *p_vm = runtime->GetJavaVM();
1227 return JNI_OK;
1228}
1229
Ian Rogersf4d4da12014-11-11 16:10:33 -08001230extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001231 Runtime* runtime = Runtime::Current();
Ian Rogersf4d4da12014-11-11 16:10:33 -08001232 if (runtime == nullptr || buf_len == 0) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001233 *vm_count = 0;
1234 } else {
1235 *vm_count = 1;
Ian Rogersf4d4da12014-11-11 16:10:33 -08001236 vms_buf[0] = runtime->GetJavaVM();
Ian Rogers68d8b422014-07-17 11:09:10 -07001237 }
1238 return JNI_OK;
1239}
1240
1241// Historically unsupported.
1242extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
1243 return JNI_ERR;
1244}
1245
1246} // namespace art