blob: f80c43d80cca92e9d8ace0b67e1deb80982b2625 [file] [log] [blame]
Ian Rogers68d8b422014-07-17 11:09:10 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "jni_internal.h"
18
19#include <dlfcn.h>
20
Andreas Gampe46ee31b2016-12-14 10:11:49 -080021#include "android-base/stringprintf.h"
22
Mathieu Chartiere401d142015-04-22 13:56:20 -070023#include "art_method.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070024#include "base/dumpable.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070025#include "base/mutex.h"
26#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080027#include "base/systrace.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070028#include "check_jni.h"
Elliott Hughes956af0f2014-12-11 14:34:28 -080029#include "dex_file-inl.h"
Mathieu Chartierd0004802014-10-15 16:59:47 -070030#include "fault_handler.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070031#include "indirect_reference_table-inl.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070032#include "mirror/class-inl.h"
33#include "mirror/class_loader.h"
Calin Juravlec8423522014-08-12 20:55:20 +010034#include "nativebridge/native_bridge.h"
Dmitriy Ivanovf5a30992015-11-11 14:18:55 -080035#include "nativeloader/native_loader.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070036#include "java_vm_ext.h"
37#include "parsed_options.h"
Ian Rogersc0542af2014-09-03 16:16:56 -070038#include "runtime-inl.h"
Igor Murashkinaaebaa02015-01-26 10:55:53 -080039#include "runtime_options.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070040#include "ScopedLocalRef.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070041#include "scoped_thread_state_change-inl.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070042#include "thread-inl.h"
43#include "thread_list.h"
44
45namespace art {
46
Andreas Gampe46ee31b2016-12-14 10:11:49 -080047using android::base::StringAppendF;
48using android::base::StringAppendV;
49
Andreas Gampea8e3b862016-10-17 20:12:52 -070050static constexpr size_t kGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
Ian Rogers68d8b422014-07-17 11:09:10 -070051
Andreas Gampea8e3b862016-10-17 20:12:52 -070052static constexpr size_t kWeakGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
Ian Rogers68d8b422014-07-17 11:09:10 -070053
Alex Light185d1342016-08-11 10:48:03 -070054bool JavaVMExt::IsBadJniVersion(int version) {
Ian Rogers68d8b422014-07-17 11:09:10 -070055 // We don't support JNI_VERSION_1_1. These are the only other valid versions.
56 return version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 && version != JNI_VERSION_1_6;
57}
58
59class SharedLibrary {
60 public:
61 SharedLibrary(JNIEnv* env, Thread* self, const std::string& path, void* handle,
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080062 bool needs_native_bridge, jobject class_loader, void* class_loader_allocator)
Ian Rogers68d8b422014-07-17 11:09:10 -070063 : path_(path),
64 handle_(handle),
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080065 needs_native_bridge_(needs_native_bridge),
Mathieu Chartier598302a2015-09-23 14:52:39 -070066 class_loader_(env->NewWeakGlobalRef(class_loader)),
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080067 class_loader_allocator_(class_loader_allocator),
Ian Rogers68d8b422014-07-17 11:09:10 -070068 jni_on_load_lock_("JNI_OnLoad lock"),
69 jni_on_load_cond_("JNI_OnLoad condition variable", jni_on_load_lock_),
70 jni_on_load_thread_id_(self->GetThreadId()),
71 jni_on_load_result_(kPending) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080072 CHECK(class_loader_allocator_ != nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -070073 }
74
75 ~SharedLibrary() {
76 Thread* self = Thread::Current();
77 if (self != nullptr) {
Mathieu Chartier598302a2015-09-23 14:52:39 -070078 self->GetJniEnv()->DeleteWeakGlobalRef(class_loader_);
Ian Rogers68d8b422014-07-17 11:09:10 -070079 }
Alex Lightbc5669e2016-06-13 17:22:13 +000080
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080081 android::CloseNativeLibrary(handle_, needs_native_bridge_);
Ian Rogers68d8b422014-07-17 11:09:10 -070082 }
83
Mathieu Chartier598302a2015-09-23 14:52:39 -070084 jweak GetClassLoader() const {
Ian Rogers68d8b422014-07-17 11:09:10 -070085 return class_loader_;
86 }
87
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080088 const void* GetClassLoaderAllocator() const {
89 return class_loader_allocator_;
90 }
91
Ian Rogers68d8b422014-07-17 11:09:10 -070092 const std::string& GetPath() const {
93 return path_;
94 }
95
96 /*
97 * Check the result of an earlier call to JNI_OnLoad on this library.
98 * If the call has not yet finished in another thread, wait for it.
99 */
100 bool CheckOnLoadResult()
Mathieu Chartier90443472015-07-16 20:32:27 -0700101 REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700102 Thread* self = Thread::Current();
103 bool okay;
104 {
105 MutexLock mu(self, jni_on_load_lock_);
106
107 if (jni_on_load_thread_id_ == self->GetThreadId()) {
108 // Check this so we don't end up waiting for ourselves. We need to return "true" so the
109 // caller can continue.
110 LOG(INFO) << *self << " recursive attempt to load library " << "\"" << path_ << "\"";
111 okay = true;
112 } else {
113 while (jni_on_load_result_ == kPending) {
114 VLOG(jni) << "[" << *self << " waiting for \"" << path_ << "\" " << "JNI_OnLoad...]";
115 jni_on_load_cond_.Wait(self);
116 }
117
118 okay = (jni_on_load_result_ == kOkay);
119 VLOG(jni) << "[Earlier JNI_OnLoad for \"" << path_ << "\" "
120 << (okay ? "succeeded" : "failed") << "]";
121 }
122 }
123 return okay;
124 }
125
Mathieu Chartier90443472015-07-16 20:32:27 -0700126 void SetResult(bool result) REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700127 Thread* self = Thread::Current();
128 MutexLock mu(self, jni_on_load_lock_);
129
130 jni_on_load_result_ = result ? kOkay : kFailed;
131 jni_on_load_thread_id_ = 0;
132
133 // Broadcast a wakeup to anybody sleeping on the condition variable.
134 jni_on_load_cond_.Broadcast(self);
135 }
136
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800137 void SetNeedsNativeBridge(bool needs) {
138 needs_native_bridge_ = needs;
Ian Rogers68d8b422014-07-17 11:09:10 -0700139 }
140
141 bool NeedsNativeBridge() const {
142 return needs_native_bridge_;
143 }
144
Mathieu Chartier598302a2015-09-23 14:52:39 -0700145 void* FindSymbol(const std::string& symbol_name, const char* shorty = nullptr) {
146 return NeedsNativeBridge()
147 ? FindSymbolWithNativeBridge(symbol_name.c_str(), shorty)
148 : FindSymbolWithoutNativeBridge(symbol_name.c_str());
149 }
150
151 void* FindSymbolWithoutNativeBridge(const std::string& symbol_name) {
Andreas Gampe8fec90b2015-06-30 11:23:44 -0700152 CHECK(!NeedsNativeBridge());
153
Ian Rogers68d8b422014-07-17 11:09:10 -0700154 return dlsym(handle_, symbol_name.c_str());
155 }
156
157 void* FindSymbolWithNativeBridge(const std::string& symbol_name, const char* shorty) {
158 CHECK(NeedsNativeBridge());
159
160 uint32_t len = 0;
Calin Juravlec8423522014-08-12 20:55:20 +0100161 return android::NativeBridgeGetTrampoline(handle_, symbol_name.c_str(), shorty, len);
Ian Rogers68d8b422014-07-17 11:09:10 -0700162 }
163
164 private:
165 enum JNI_OnLoadState {
166 kPending,
167 kFailed,
168 kOkay,
169 };
170
171 // Path to library "/system/lib/libjni.so".
172 const std::string path_;
173
174 // The void* returned by dlopen(3).
175 void* const handle_;
176
177 // True if a native bridge is required.
178 bool needs_native_bridge_;
179
Mathieu Chartier598302a2015-09-23 14:52:39 -0700180 // The ClassLoader this library is associated with, a weak global JNI reference that is
Ian Rogers68d8b422014-07-17 11:09:10 -0700181 // created/deleted with the scope of the library.
Mathieu Chartier598302a2015-09-23 14:52:39 -0700182 const jweak class_loader_;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800183 // Used to do equality check on class loaders so we can avoid decoding the weak root and read
184 // barriers that mess with class unloading.
185 const void* class_loader_allocator_;
Ian Rogers68d8b422014-07-17 11:09:10 -0700186
187 // Guards remaining items.
188 Mutex jni_on_load_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
189 // Wait for JNI_OnLoad in other thread.
190 ConditionVariable jni_on_load_cond_ GUARDED_BY(jni_on_load_lock_);
191 // Recursive invocation guard.
192 uint32_t jni_on_load_thread_id_ GUARDED_BY(jni_on_load_lock_);
193 // Result of earlier JNI_OnLoad call.
194 JNI_OnLoadState jni_on_load_result_ GUARDED_BY(jni_on_load_lock_);
195};
196
197// This exists mainly to keep implementation details out of the header file.
198class Libraries {
199 public:
200 Libraries() {
201 }
202
203 ~Libraries() {
204 STLDeleteValues(&libraries_);
205 }
206
Mathieu Chartier598302a2015-09-23 14:52:39 -0700207 // NO_THREAD_SAFETY_ANALYSIS since this may be called from Dumpable. Dumpable can't be annotated
208 // properly due to the template. The caller should be holding the jni_libraries_lock_.
209 void Dump(std::ostream& os) const NO_THREAD_SAFETY_ANALYSIS {
210 Locks::jni_libraries_lock_->AssertHeld(Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -0700211 bool first = true;
212 for (const auto& library : libraries_) {
213 if (!first) {
214 os << ' ';
215 }
216 first = false;
217 os << library.first;
218 }
219 }
220
Mathieu Chartier598302a2015-09-23 14:52:39 -0700221 size_t size() const REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700222 return libraries_.size();
223 }
224
Mathieu Chartier598302a2015-09-23 14:52:39 -0700225 SharedLibrary* Get(const std::string& path) REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700226 auto it = libraries_.find(path);
227 return (it == libraries_.end()) ? nullptr : it->second;
228 }
229
Mathieu Chartier598302a2015-09-23 14:52:39 -0700230 void Put(const std::string& path, SharedLibrary* library)
231 REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700232 libraries_.Put(path, library);
233 }
234
235 // See section 11.3 "Linking Native Methods" of the JNI spec.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700236 void* FindNativeMethod(ArtMethod* m, std::string& detail)
Mathieu Chartier90443472015-07-16 20:32:27 -0700237 REQUIRES(Locks::jni_libraries_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700238 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700239 std::string jni_short_name(m->JniShortName());
240 std::string jni_long_name(m->JniLongName());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800241 mirror::ClassLoader* const declaring_class_loader = m->GetDeclaringClass()->GetClassLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700242 ScopedObjectAccessUnchecked soa(Thread::Current());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800243 void* const declaring_class_loader_allocator =
244 Runtime::Current()->GetClassLinker()->GetAllocatorForClassLoader(declaring_class_loader);
245 CHECK(declaring_class_loader_allocator != nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700246 for (const auto& lib : libraries_) {
Mathieu Chartier598302a2015-09-23 14:52:39 -0700247 SharedLibrary* const library = lib.second;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800248 // Use the allocator address for class loader equality to avoid unnecessary weak root decode.
249 if (library->GetClassLoaderAllocator() != declaring_class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700250 // We only search libraries loaded by the appropriate ClassLoader.
251 continue;
252 }
253 // Try the short name then the long name...
Mathieu Chartier598302a2015-09-23 14:52:39 -0700254 const char* shorty = library->NeedsNativeBridge()
255 ? m->GetShorty()
256 : nullptr;
257 void* fn = library->FindSymbol(jni_short_name, shorty);
258 if (fn == nullptr) {
259 fn = library->FindSymbol(jni_long_name, shorty);
Ian Rogers68d8b422014-07-17 11:09:10 -0700260 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700261 if (fn != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700262 VLOG(jni) << "[Found native code for " << m->PrettyMethod()
Ian Rogers68d8b422014-07-17 11:09:10 -0700263 << " in \"" << library->GetPath() << "\"]";
264 return fn;
265 }
266 }
267 detail += "No implementation found for ";
David Sehr709b0702016-10-13 09:12:37 -0700268 detail += m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700269 detail += " (tried " + jni_short_name + " and " + jni_long_name + ")";
270 LOG(ERROR) << detail;
271 return nullptr;
272 }
273
Mathieu Chartier598302a2015-09-23 14:52:39 -0700274 // Unload native libraries with cleared class loaders.
275 void UnloadNativeLibraries()
276 REQUIRES(!Locks::jni_libraries_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700277 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier598302a2015-09-23 14:52:39 -0700278 ScopedObjectAccessUnchecked soa(Thread::Current());
Alex Lightbc5669e2016-06-13 17:22:13 +0000279 std::vector<SharedLibrary*> unload_libraries;
Mathieu Chartier598302a2015-09-23 14:52:39 -0700280 {
281 MutexLock mu(soa.Self(), *Locks::jni_libraries_lock_);
282 for (auto it = libraries_.begin(); it != libraries_.end(); ) {
283 SharedLibrary* const library = it->second;
284 // If class loader is null then it was unloaded, call JNI_OnUnload.
Mathieu Chartiercffb7472015-09-28 10:33:00 -0700285 const jweak class_loader = library->GetClassLoader();
286 // If class_loader is a null jobject then it is the boot class loader. We should not unload
287 // the native libraries of the boot class loader.
288 if (class_loader != nullptr &&
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800289 soa.Self()->IsJWeakCleared(class_loader)) {
Alex Lightbc5669e2016-06-13 17:22:13 +0000290 unload_libraries.push_back(library);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700291 it = libraries_.erase(it);
292 } else {
293 ++it;
294 }
295 }
296 }
297 // Do this without holding the jni libraries lock to prevent possible deadlocks.
Alex Lightbc5669e2016-06-13 17:22:13 +0000298 typedef void (*JNI_OnUnloadFn)(JavaVM*, void*);
299 for (auto library : unload_libraries) {
300 void* const sym = library->FindSymbol("JNI_OnUnload", nullptr);
301 if (sym == nullptr) {
302 VLOG(jni) << "[No JNI_OnUnload found in \"" << library->GetPath() << "\"]";
303 } else {
304 VLOG(jni) << "[JNI_OnUnload found for \"" << library->GetPath() << "\"]: Calling...";
305 JNI_OnUnloadFn jni_on_unload = reinterpret_cast<JNI_OnUnloadFn>(sym);
306 jni_on_unload(soa.Vm(), nullptr);
307 }
308 delete library;
Mathieu Chartier598302a2015-09-23 14:52:39 -0700309 }
310 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700311
Mathieu Chartier598302a2015-09-23 14:52:39 -0700312 private:
313 AllocationTrackingSafeMap<std::string, SharedLibrary*, kAllocatorTagJNILibraries> libraries_
314 GUARDED_BY(Locks::jni_libraries_lock_);
315};
Ian Rogers68d8b422014-07-17 11:09:10 -0700316
317class JII {
318 public:
319 static jint DestroyJavaVM(JavaVM* vm) {
320 if (vm == nullptr) {
321 return JNI_ERR;
322 }
323 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
324 delete raw_vm->GetRuntime();
Dimitry Ivanov39d68ef2016-04-29 16:02:38 -0700325 android::ResetNativeLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700326 return JNI_OK;
327 }
328
329 static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
330 return AttachCurrentThreadInternal(vm, p_env, thr_args, false);
331 }
332
333 static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
334 return AttachCurrentThreadInternal(vm, p_env, thr_args, true);
335 }
336
337 static jint DetachCurrentThread(JavaVM* vm) {
338 if (vm == nullptr || Thread::Current() == nullptr) {
339 return JNI_ERR;
340 }
341 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
342 Runtime* runtime = raw_vm->GetRuntime();
343 runtime->DetachCurrentThread();
344 return JNI_OK;
345 }
346
347 static jint GetEnv(JavaVM* vm, void** env, jint version) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700348 if (vm == nullptr || env == nullptr) {
349 return JNI_ERR;
350 }
351 Thread* thread = Thread::Current();
352 if (thread == nullptr) {
353 *env = nullptr;
354 return JNI_EDETACHED;
355 }
Alex Light185d1342016-08-11 10:48:03 -0700356 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
357 return raw_vm->HandleGetEnv(env, version);
Ian Rogers68d8b422014-07-17 11:09:10 -0700358 }
359
360 private:
361 static jint AttachCurrentThreadInternal(JavaVM* vm, JNIEnv** p_env, void* raw_args, bool as_daemon) {
362 if (vm == nullptr || p_env == nullptr) {
363 return JNI_ERR;
364 }
365
366 // Return immediately if we're already attached.
367 Thread* self = Thread::Current();
368 if (self != nullptr) {
369 *p_env = self->GetJniEnv();
370 return JNI_OK;
371 }
372
373 Runtime* runtime = reinterpret_cast<JavaVMExt*>(vm)->GetRuntime();
374
375 // No threads allowed in zygote mode.
376 if (runtime->IsZygote()) {
377 LOG(ERROR) << "Attempt to attach a thread in the zygote";
378 return JNI_ERR;
379 }
380
381 JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(raw_args);
382 const char* thread_name = nullptr;
383 jobject thread_group = nullptr;
384 if (args != nullptr) {
Alex Light185d1342016-08-11 10:48:03 -0700385 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700386 LOG(ERROR) << "Bad JNI version passed to "
387 << (as_daemon ? "AttachCurrentThreadAsDaemon" : "AttachCurrentThread") << ": "
388 << args->version;
389 return JNI_EVERSION;
390 }
391 thread_name = args->name;
392 thread_group = args->group;
393 }
394
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800395 if (!runtime->AttachCurrentThread(thread_name, as_daemon, thread_group,
396 !runtime->IsAotCompiler())) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700397 *p_env = nullptr;
398 return JNI_ERR;
399 } else {
400 *p_env = Thread::Current()->GetJniEnv();
401 return JNI_OK;
402 }
403 }
404};
405
406const JNIInvokeInterface gJniInvokeInterface = {
407 nullptr, // reserved0
408 nullptr, // reserved1
409 nullptr, // reserved2
410 JII::DestroyJavaVM,
411 JII::AttachCurrentThread,
412 JII::DetachCurrentThread,
413 JII::GetEnv,
414 JII::AttachCurrentThreadAsDaemon
415};
416
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100417JavaVMExt::JavaVMExt(Runtime* runtime,
418 const RuntimeArgumentMap& runtime_options,
419 std::string* error_msg)
Ian Rogers68d8b422014-07-17 11:09:10 -0700420 : runtime_(runtime),
421 check_jni_abort_hook_(nullptr),
422 check_jni_abort_hook_data_(nullptr),
423 check_jni_(false), // Initialized properly in the constructor body below.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800424 force_copy_(runtime_options.Exists(RuntimeArgumentMap::JniOptsForceCopy)),
425 tracing_enabled_(runtime_options.Exists(RuntimeArgumentMap::JniTrace)
426 || VLOG_IS_ON(third_party_jni)),
427 trace_(runtime_options.GetOrDefault(RuntimeArgumentMap::JniTrace)),
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700428 globals_(kGlobalsMax, kGlobal, IndirectReferenceTable::ResizableCapacity::kNo, error_msg),
Ian Rogers68d8b422014-07-17 11:09:10 -0700429 libraries_(new Libraries),
430 unchecked_functions_(&gJniInvokeInterface),
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700431 weak_globals_(kWeakGlobalsMax,
432 kWeakGlobal,
433 IndirectReferenceTable::ResizableCapacity::kNo,
434 error_msg),
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700435 allow_accessing_weak_globals_(true),
Andreas Gampe05a364c2016-10-14 13:27:12 -0700436 weak_globals_add_condition_("weak globals add condition",
437 (CHECK(Locks::jni_weak_globals_lock_ != nullptr),
438 *Locks::jni_weak_globals_lock_)),
Alex Light185d1342016-08-11 10:48:03 -0700439 env_hooks_() {
Ian Rogers68d8b422014-07-17 11:09:10 -0700440 functions = unchecked_functions_;
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800441 SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni));
Ian Rogers68d8b422014-07-17 11:09:10 -0700442}
443
444JavaVMExt::~JavaVMExt() {
445}
446
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100447// Checking "globals" and "weak_globals" usually requires locks, but we
448// don't need the locks to check for validity when constructing the
449// object. Use NO_THREAD_SAFETY_ANALYSIS for this.
450std::unique_ptr<JavaVMExt> JavaVMExt::Create(Runtime* runtime,
451 const RuntimeArgumentMap& runtime_options,
452 std::string* error_msg) NO_THREAD_SAFETY_ANALYSIS {
453 std::unique_ptr<JavaVMExt> java_vm(new JavaVMExt(runtime, runtime_options, error_msg));
454 if (java_vm && java_vm->globals_.IsValid() && java_vm->weak_globals_.IsValid()) {
455 return java_vm;
456 }
457 return nullptr;
458}
459
Alex Light185d1342016-08-11 10:48:03 -0700460jint JavaVMExt::HandleGetEnv(/*out*/void** env, jint version) {
461 for (GetEnvHook hook : env_hooks_) {
462 jint res = hook(this, env, version);
463 if (res == JNI_OK) {
464 return JNI_OK;
465 } else if (res != JNI_EVERSION) {
466 LOG(ERROR) << "Error returned from a plugin GetEnv handler! " << res;
467 return res;
468 }
469 }
470 LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version;
471 return JNI_EVERSION;
472}
473
474// Add a hook to handle getting environments from the GetEnv call.
475void JavaVMExt::AddEnvironmentHook(GetEnvHook hook) {
476 CHECK(hook != nullptr) << "environment hooks shouldn't be null!";
477 env_hooks_.push_back(hook);
478}
479
Ian Rogers68d8b422014-07-17 11:09:10 -0700480void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) {
481 Thread* self = Thread::Current();
482 ScopedObjectAccess soa(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700483 ArtMethod* current_method = self->GetCurrentMethod(nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700484
485 std::ostringstream os;
486 os << "JNI DETECTED ERROR IN APPLICATION: " << msg;
487
488 if (jni_function_name != nullptr) {
489 os << "\n in call to " << jni_function_name;
490 }
491 // TODO: is this useful given that we're about to dump the calling thread's stack?
492 if (current_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700493 os << "\n from " << current_method->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700494 }
495 os << "\n";
496 self->Dump(os);
497
498 if (check_jni_abort_hook_ != nullptr) {
499 check_jni_abort_hook_(check_jni_abort_hook_data_, os.str());
500 } else {
501 // Ensure that we get a native stack trace for this thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700502 ScopedThreadSuspension sts(self, kNative);
Ian Rogers68d8b422014-07-17 11:09:10 -0700503 LOG(FATAL) << os.str();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700504 UNREACHABLE();
Ian Rogers68d8b422014-07-17 11:09:10 -0700505 }
506}
507
508void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) {
509 std::string msg;
510 StringAppendV(&msg, fmt, ap);
511 JniAbort(jni_function_name, msg.c_str());
512}
513
514void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) {
515 va_list args;
516 va_start(args, fmt);
517 JniAbortV(jni_function_name, fmt, args);
518 va_end(args);
519}
520
Mathieu Chartiere401d142015-04-22 13:56:20 -0700521bool JavaVMExt::ShouldTrace(ArtMethod* method) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700522 // Fast where no tracing is enabled.
523 if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) {
524 return false;
525 }
526 // Perform checks based on class name.
527 StringPiece class_name(method->GetDeclaringClassDescriptor());
528 if (!trace_.empty() && class_name.find(trace_) != std::string::npos) {
529 return true;
530 }
531 if (!VLOG_IS_ON(third_party_jni)) {
532 return false;
533 }
534 // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
535 // like part of Android.
536 static const char* gBuiltInPrefixes[] = {
537 "Landroid/",
538 "Lcom/android/",
539 "Lcom/google/android/",
540 "Ldalvik/",
541 "Ljava/",
542 "Ljavax/",
543 "Llibcore/",
544 "Lorg/apache/harmony/",
545 };
546 for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) {
547 if (class_name.starts_with(gBuiltInPrefixes[i])) {
548 return false;
549 }
550 }
551 return true;
552}
553
Mathieu Chartier0795f232016-09-27 18:43:30 -0700554jobject JavaVMExt::AddGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700555 // Check for null after decoding the object to handle cleared weak globals.
556 if (obj == nullptr) {
557 return nullptr;
558 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700559 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700560 IndirectRef ref = globals_.Add(kIRTFirstSegment, obj);
Ian Rogers68d8b422014-07-17 11:09:10 -0700561 return reinterpret_cast<jobject>(ref);
562}
563
Mathieu Chartier0795f232016-09-27 18:43:30 -0700564jweak JavaVMExt::AddWeakGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700565 if (obj == nullptr) {
566 return nullptr;
567 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700568 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700569 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700570 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
571 // presence of threads blocking for weak ref access.
572 self->CheckEmptyCheckpoint();
Ian Rogers68d8b422014-07-17 11:09:10 -0700573 weak_globals_add_condition_.WaitHoldingLocks(self);
574 }
Andreas Gampee03662b2016-10-13 17:12:56 -0700575 IndirectRef ref = weak_globals_.Add(kIRTFirstSegment, obj);
Ian Rogers68d8b422014-07-17 11:09:10 -0700576 return reinterpret_cast<jweak>(ref);
577}
578
579void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
580 if (obj == nullptr) {
581 return;
582 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700583 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700584 if (!globals_.Remove(kIRTFirstSegment, obj)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700585 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
586 << "failed to find entry";
587 }
588}
589
590void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
591 if (obj == nullptr) {
592 return;
593 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700594 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700595 if (!weak_globals_.Remove(kIRTFirstSegment, obj)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700596 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
597 << "failed to find entry";
598 }
599}
600
601static void ThreadEnableCheckJni(Thread* thread, void* arg) {
602 bool* check_jni = reinterpret_cast<bool*>(arg);
603 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
604}
605
606bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
607 bool old_check_jni = check_jni_;
608 check_jni_ = enabled;
609 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
610 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
611 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
612 return old_check_jni;
613}
614
615void JavaVMExt::DumpForSigQuit(std::ostream& os) {
616 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
617 if (force_copy_) {
618 os << " (with forcecopy)";
619 }
620 Thread* self = Thread::Current();
621 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700622 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700623 os << "; globals=" << globals_.Capacity();
624 }
625 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700626 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700627 if (weak_globals_.Capacity() > 0) {
628 os << " (plus " << weak_globals_.Capacity() << " weak)";
629 }
630 }
631 os << '\n';
632
633 {
634 MutexLock mu(self, *Locks::jni_libraries_lock_);
635 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
636 }
637}
638
639void JavaVMExt::DisallowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700640 CHECK(!kUseReadBarrier);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700641 Thread* const self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700642 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700643 // DisallowNewWeakGlobals is only called by CMS during the pause. It is required to have the
644 // mutator lock exclusively held so that we don't have any threads in the middle of
645 // DecodeWeakGlobal.
646 Locks::mutator_lock_->AssertExclusiveHeld(self);
647 allow_accessing_weak_globals_.StoreSequentiallyConsistent(false);
Ian Rogers68d8b422014-07-17 11:09:10 -0700648}
649
650void JavaVMExt::AllowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700651 CHECK(!kUseReadBarrier);
Ian Rogers68d8b422014-07-17 11:09:10 -0700652 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700653 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700654 allow_accessing_weak_globals_.StoreSequentiallyConsistent(true);
Ian Rogers68d8b422014-07-17 11:09:10 -0700655 weak_globals_add_condition_.Broadcast(self);
656}
657
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700658void JavaVMExt::BroadcastForNewWeakGlobals() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700659 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700660 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700661 weak_globals_add_condition_.Broadcast(self);
662}
663
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700664ObjPtr<mirror::Object> JavaVMExt::DecodeGlobal(IndirectRef ref) {
665 return globals_.SynchronizedGet(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700666}
667
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700668void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700669 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700670 globals_.Update(ref, result);
671}
672
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700673inline bool JavaVMExt::MayAccessWeakGlobals(Thread* self) const {
674 return MayAccessWeakGlobalsUnlocked(self);
675}
676
677inline bool JavaVMExt::MayAccessWeakGlobalsUnlocked(Thread* self) const {
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700678 DCHECK(self != nullptr);
679 return kUseReadBarrier ?
680 self->GetWeakRefAccessEnabled() :
681 allow_accessing_weak_globals_.LoadSequentiallyConsistent();
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700682}
683
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700684ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700685 // It is safe to access GetWeakRefAccessEnabled without the lock since CC uses checkpoints to call
686 // SetWeakRefAccessEnabled, and the other collectors only modify allow_accessing_weak_globals_
687 // when the mutators are paused.
688 // This only applies in the case where MayAccessWeakGlobals goes from false to true. In the other
689 // case, it may be racy, this is benign since DecodeWeakGlobalLocked does the correct behavior
690 // if MayAccessWeakGlobals is false.
Andreas Gampedc061d02016-10-24 13:19:37 -0700691 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700692 if (LIKELY(MayAccessWeakGlobalsUnlocked(self))) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700693 return weak_globals_.SynchronizedGet(ref);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700694 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700695 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700696 return DecodeWeakGlobalLocked(self, ref);
697}
698
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700699ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalLocked(Thread* self, IndirectRef ref) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700700 if (kDebugLocking) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700701 Locks::jni_weak_globals_lock_->AssertHeld(self);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700702 }
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700703 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700704 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
705 // presence of threads blocking for weak ref access.
706 self->CheckEmptyCheckpoint();
Ian Rogers68d8b422014-07-17 11:09:10 -0700707 weak_globals_add_condition_.WaitHoldingLocks(self);
708 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700709 return weak_globals_.Get(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700710}
711
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700712ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalDuringShutdown(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700713 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700714 DCHECK(Runtime::Current()->IsShuttingDown(self));
715 if (self != nullptr) {
716 return DecodeWeakGlobal(self, ref);
717 }
718 // self can be null during a runtime shutdown. ~Runtime()->~ClassLinker()->DecodeWeakGlobal().
719 if (!kUseReadBarrier) {
720 DCHECK(allow_accessing_weak_globals_.LoadSequentiallyConsistent());
721 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700722 return weak_globals_.SynchronizedGet(ref);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700723}
724
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800725bool JavaVMExt::IsWeakGlobalCleared(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700726 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Andreas Gampe05a364c2016-10-14 13:27:12 -0700727 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800728 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700729 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
730 // presence of threads blocking for weak ref access.
731 self->CheckEmptyCheckpoint();
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800732 weak_globals_add_condition_.WaitHoldingLocks(self);
733 }
734 // When just checking a weak ref has been cleared, avoid triggering the read barrier in decode
735 // (DecodeWeakGlobal) so that we won't accidentally mark the object alive. Since the cleared
736 // sentinel is a non-moving object, we can compare the ref to it without the read barrier and
737 // decide if it's cleared.
738 return Runtime::Current()->IsClearedJniWeakGlobal(weak_globals_.Get<kWithoutReadBarrier>(ref));
739}
740
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700741void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700742 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700743 weak_globals_.Update(ref, result);
744}
745
Ian Rogers68d8b422014-07-17 11:09:10 -0700746void JavaVMExt::DumpReferenceTables(std::ostream& os) {
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 globals_.Dump(os);
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 weak_globals_.Dump(os);
755 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700756}
757
Mathieu Chartier598302a2015-09-23 14:52:39 -0700758void JavaVMExt::UnloadNativeLibraries() {
759 libraries_.get()->UnloadNativeLibraries();
760}
761
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800762bool JavaVMExt::LoadNativeLibrary(JNIEnv* env,
763 const std::string& path,
764 jobject class_loader,
765 jstring library_path,
766 std::string* error_msg) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700767 error_msg->clear();
768
769 // See if we've already loaded this library. If we have, and the class loader
770 // matches, return successfully without doing anything.
771 // TODO: for better results we should canonicalize the pathname (or even compare
772 // inodes). This implementation is fine if everybody is using System.loadLibrary.
773 SharedLibrary* library;
774 Thread* self = Thread::Current();
775 {
776 // TODO: move the locking (and more of this logic) into Libraries.
777 MutexLock mu(self, *Locks::jni_libraries_lock_);
778 library = libraries_->Get(path);
779 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800780 void* class_loader_allocator = nullptr;
781 {
782 ScopedObjectAccess soa(env);
783 // As the incoming class loader is reachable/alive during the call of this function,
784 // it's okay to decode it without worrying about unexpectedly marking it alive.
Mathieu Chartier0795f232016-09-27 18:43:30 -0700785 ObjPtr<mirror::ClassLoader> loader = soa.Decode<mirror::ClassLoader>(class_loader);
Andreas Gampe2d48e532016-06-17 12:46:14 -0700786
787 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700788 if (class_linker->IsBootClassLoader(soa, loader.Ptr())) {
Andreas Gampe2d48e532016-06-17 12:46:14 -0700789 loader = nullptr;
790 class_loader = nullptr;
791 }
792
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700793 class_loader_allocator = class_linker->GetAllocatorForClassLoader(loader.Ptr());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800794 CHECK(class_loader_allocator != nullptr);
795 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700796 if (library != nullptr) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800797 // Use the allocator pointers for class loader equality to avoid unnecessary weak root decode.
798 if (library->GetClassLoaderAllocator() != class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700799 // The library will be associated with class_loader. The JNI
800 // spec says we can't load the same library into more than one
801 // class loader.
802 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
803 "ClassLoader %p; can't open in ClassLoader %p",
804 path.c_str(), library->GetClassLoader(), class_loader);
805 LOG(WARNING) << error_msg;
806 return false;
807 }
808 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
809 << " ClassLoader " << class_loader << "]";
810 if (!library->CheckOnLoadResult()) {
811 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
812 "to load \"%s\"", path.c_str());
813 return false;
814 }
815 return true;
816 }
817
818 // Open the shared library. Because we're using a full path, the system
819 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
820 // resolve this library's dependencies though.)
821
822 // Failures here are expected when java.library.path has several entries
823 // and we have to hunt for the lib.
824
825 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
826 // class unloading. Libraries will only be unloaded when the reference count (incremented by
827 // dlopen) becomes zero from dlclose.
828
829 Locks::mutator_lock_->AssertNotHeld(self);
830 const char* path_str = path.empty() ? nullptr : path.c_str();
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800831 bool needs_native_bridge = false;
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800832 void* handle = android::OpenNativeLibrary(env,
833 runtime_->GetTargetSdkVersion(),
834 path_str,
835 class_loader,
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800836 library_path,
837 &needs_native_bridge,
838 error_msg);
Ian Rogers68d8b422014-07-17 11:09:10 -0700839
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700840 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]";
Ian Rogers68d8b422014-07-17 11:09:10 -0700841
842 if (handle == nullptr) {
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700843 VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700844 return false;
845 }
846
847 if (env->ExceptionCheck() == JNI_TRUE) {
848 LOG(ERROR) << "Unexpected exception:";
849 env->ExceptionDescribe();
850 env->ExceptionClear();
851 }
852 // Create a new entry.
853 // TODO: move the locking (and more of this logic) into Libraries.
854 bool created_library = false;
855 {
856 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
857 std::unique_ptr<SharedLibrary> new_library(
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800858 new SharedLibrary(env,
859 self,
860 path,
861 handle,
862 needs_native_bridge,
863 class_loader,
864 class_loader_allocator));
865
Ian Rogers68d8b422014-07-17 11:09:10 -0700866 MutexLock mu(self, *Locks::jni_libraries_lock_);
867 library = libraries_->Get(path);
868 if (library == nullptr) { // We won race to get libraries_lock.
869 library = new_library.release();
870 libraries_->Put(path, library);
871 created_library = true;
872 }
873 }
874 if (!created_library) {
875 LOG(INFO) << "WOW: we lost a race to add shared library: "
876 << "\"" << path << "\" ClassLoader=" << class_loader;
877 return library->CheckOnLoadResult();
878 }
879 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
880
881 bool was_successful = false;
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800882 void* sym = library->FindSymbol("JNI_OnLoad", nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700883 if (sym == nullptr) {
884 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
885 was_successful = true;
886 } else {
887 // Call JNI_OnLoad. We have to override the current class
888 // loader, which will always be "null" since the stuff at the
889 // top of the stack is around Runtime.loadLibrary(). (See
890 // the comments in the JNI FindClass function.)
891 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
892 self->SetClassLoaderOverride(class_loader);
893
894 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
895 typedef int (*JNI_OnLoadFn)(JavaVM*, void*);
896 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
897 int version = (*jni_on_load)(this, nullptr);
898
Mathieu Chartierd0004802014-10-15 16:59:47 -0700899 if (runtime_->GetTargetSdkVersion() != 0 && runtime_->GetTargetSdkVersion() <= 21) {
900 fault_manager.EnsureArtActionInFrontOfSignalChain();
901 }
902
Ian Rogers68d8b422014-07-17 11:09:10 -0700903 self->SetClassLoaderOverride(old_class_loader.get());
904
905 if (version == JNI_ERR) {
906 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
Alex Light185d1342016-08-11 10:48:03 -0700907 } else if (JavaVMExt::IsBadJniVersion(version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700908 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
909 path.c_str(), version);
910 // It's unwise to call dlclose() here, but we can mark it
911 // as bad and ensure that future load attempts will fail.
912 // We don't know how far JNI_OnLoad got, so there could
913 // be some partially-initialized stuff accessible through
914 // newly-registered native method calls. We could try to
915 // unregister them, but that doesn't seem worthwhile.
916 } else {
917 was_successful = true;
918 }
919 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
920 << " from JNI_OnLoad in \"" << path << "\"]";
921 }
922
923 library->SetResult(was_successful);
924 return was_successful;
925}
926
Mathieu Chartiere401d142015-04-22 13:56:20 -0700927void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700928 CHECK(m->IsNative());
929 mirror::Class* c = m->GetDeclaringClass();
930 // If this is a static method, it could be called before the class has been initialized.
David Sehr709b0702016-10-13 09:12:37 -0700931 CHECK(c->IsInitializing()) << c->GetStatus() << " " << m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700932 std::string detail;
933 void* native_method;
934 Thread* self = Thread::Current();
935 {
936 MutexLock mu(self, *Locks::jni_libraries_lock_);
937 native_method = libraries_->FindNativeMethod(m, detail);
938 }
939 // Throwing can cause libraries_lock to be reacquired.
940 if (native_method == nullptr) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000941 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
Ian Rogers68d8b422014-07-17 11:09:10 -0700942 }
943 return native_method;
944}
945
Mathieu Chartier97509952015-07-13 14:35:43 -0700946void JavaVMExt::SweepJniWeakGlobals(IsMarkedVisitor* visitor) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700947 MutexLock mu(Thread::Current(), *Locks::jni_weak_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700948 Runtime* const runtime = Runtime::Current();
949 for (auto* entry : weak_globals_) {
950 // Need to skip null here to distinguish between null entries and cleared weak ref entries.
951 if (!entry->IsNull()) {
952 // Since this is called by the GC, we don't need a read barrier.
953 mirror::Object* obj = entry->Read<kWithoutReadBarrier>();
Mathieu Chartier97509952015-07-13 14:35:43 -0700954 mirror::Object* new_obj = visitor->IsMarked(obj);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700955 if (new_obj == nullptr) {
956 new_obj = runtime->GetClearedJniWeakGlobal();
957 }
958 *entry = GcRoot<mirror::Object>(new_obj);
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -0700959 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700960 }
961}
962
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800963void JavaVMExt::TrimGlobals() {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700964 WriterMutexLock mu(Thread::Current(), *Locks::jni_globals_lock_);
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800965 globals_.Trim();
966}
967
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700968void JavaVMExt::VisitRoots(RootVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700969 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700970 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700971 globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal));
Ian Rogers68d8b422014-07-17 11:09:10 -0700972 // The weak_globals table is visited by the GC itself (because it mutates the table).
973}
974
975// JNI Invocation interface.
976
977extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800978 ScopedTrace trace(__FUNCTION__);
Ian Rogers68d8b422014-07-17 11:09:10 -0700979 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
Alex Light185d1342016-08-11 10:48:03 -0700980 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700981 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
982 return JNI_EVERSION;
983 }
984 RuntimeOptions options;
985 for (int i = 0; i < args->nOptions; ++i) {
986 JavaVMOption* option = &args->options[i];
987 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
988 }
989 bool ignore_unrecognized = args->ignoreUnrecognized;
990 if (!Runtime::Create(options, ignore_unrecognized)) {
991 return JNI_ERR;
992 }
Dimitry Ivanovc544f342016-05-09 16:26:13 -0700993
994 // Initialize native loader. This step makes sure we have
995 // everything set up before we start using JNI.
996 android::InitializeNativeLoader();
997
Ian Rogers68d8b422014-07-17 11:09:10 -0700998 Runtime* runtime = Runtime::Current();
999 bool started = runtime->Start();
1000 if (!started) {
1001 delete Thread::Current()->GetJniEnv();
1002 delete runtime->GetJavaVM();
1003 LOG(WARNING) << "CreateJavaVM failed";
1004 return JNI_ERR;
1005 }
Dimitry Ivanov041169f2016-04-21 16:01:24 -07001006
Ian Rogers68d8b422014-07-17 11:09:10 -07001007 *p_env = Thread::Current()->GetJniEnv();
1008 *p_vm = runtime->GetJavaVM();
1009 return JNI_OK;
1010}
1011
Ian Rogersf4d4da12014-11-11 16:10:33 -08001012extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001013 Runtime* runtime = Runtime::Current();
Ian Rogersf4d4da12014-11-11 16:10:33 -08001014 if (runtime == nullptr || buf_len == 0) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001015 *vm_count = 0;
1016 } else {
1017 *vm_count = 1;
Ian Rogersf4d4da12014-11-11 16:10:33 -08001018 vms_buf[0] = runtime->GetJavaVM();
Ian Rogers68d8b422014-07-17 11:09:10 -07001019 }
1020 return JNI_OK;
1021}
1022
1023// Historically unsupported.
1024extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
1025 return JNI_ERR;
1026}
1027
1028} // namespace art