blob: a341cdb89ff20594c38273641a790a1d5a8f5b6a [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_);
Hiroshi Yamauchif1c6f872017-01-06 12:23:47 -0800569 // CMS needs this to block for concurrent reference processing because an object allocated during
570 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
571 // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant.
572 while (!kUseReadBarrier && UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700573 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
574 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800575 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700576 weak_globals_add_condition_.WaitHoldingLocks(self);
577 }
Andreas Gampee03662b2016-10-13 17:12:56 -0700578 IndirectRef ref = weak_globals_.Add(kIRTFirstSegment, obj);
Ian Rogers68d8b422014-07-17 11:09:10 -0700579 return reinterpret_cast<jweak>(ref);
580}
581
582void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
583 if (obj == nullptr) {
584 return;
585 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700586 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700587 if (!globals_.Remove(kIRTFirstSegment, obj)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700588 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
589 << "failed to find entry";
590 }
591}
592
593void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
594 if (obj == nullptr) {
595 return;
596 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700597 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700598 if (!weak_globals_.Remove(kIRTFirstSegment, obj)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700599 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
600 << "failed to find entry";
601 }
602}
603
604static void ThreadEnableCheckJni(Thread* thread, void* arg) {
605 bool* check_jni = reinterpret_cast<bool*>(arg);
606 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
607}
608
609bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
610 bool old_check_jni = check_jni_;
611 check_jni_ = enabled;
612 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
613 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
614 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
615 return old_check_jni;
616}
617
618void JavaVMExt::DumpForSigQuit(std::ostream& os) {
619 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
620 if (force_copy_) {
621 os << " (with forcecopy)";
622 }
623 Thread* self = Thread::Current();
624 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700625 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700626 os << "; globals=" << globals_.Capacity();
627 }
628 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700629 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700630 if (weak_globals_.Capacity() > 0) {
631 os << " (plus " << weak_globals_.Capacity() << " weak)";
632 }
633 }
634 os << '\n';
635
636 {
637 MutexLock mu(self, *Locks::jni_libraries_lock_);
638 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
639 }
640}
641
642void JavaVMExt::DisallowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700643 CHECK(!kUseReadBarrier);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700644 Thread* const self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700645 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700646 // DisallowNewWeakGlobals is only called by CMS during the pause. It is required to have the
647 // mutator lock exclusively held so that we don't have any threads in the middle of
648 // DecodeWeakGlobal.
649 Locks::mutator_lock_->AssertExclusiveHeld(self);
650 allow_accessing_weak_globals_.StoreSequentiallyConsistent(false);
Ian Rogers68d8b422014-07-17 11:09:10 -0700651}
652
653void JavaVMExt::AllowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700654 CHECK(!kUseReadBarrier);
Ian Rogers68d8b422014-07-17 11:09:10 -0700655 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700656 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700657 allow_accessing_weak_globals_.StoreSequentiallyConsistent(true);
Ian Rogers68d8b422014-07-17 11:09:10 -0700658 weak_globals_add_condition_.Broadcast(self);
659}
660
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700661void JavaVMExt::BroadcastForNewWeakGlobals() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700662 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700663 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700664 weak_globals_add_condition_.Broadcast(self);
665}
666
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700667ObjPtr<mirror::Object> JavaVMExt::DecodeGlobal(IndirectRef ref) {
668 return globals_.SynchronizedGet(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700669}
670
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700671void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700672 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700673 globals_.Update(ref, result);
674}
675
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700676inline bool JavaVMExt::MayAccessWeakGlobals(Thread* self) const {
677 return MayAccessWeakGlobalsUnlocked(self);
678}
679
680inline bool JavaVMExt::MayAccessWeakGlobalsUnlocked(Thread* self) const {
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700681 DCHECK(self != nullptr);
682 return kUseReadBarrier ?
683 self->GetWeakRefAccessEnabled() :
684 allow_accessing_weak_globals_.LoadSequentiallyConsistent();
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700685}
686
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700687ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700688 // It is safe to access GetWeakRefAccessEnabled without the lock since CC uses checkpoints to call
689 // SetWeakRefAccessEnabled, and the other collectors only modify allow_accessing_weak_globals_
690 // when the mutators are paused.
691 // This only applies in the case where MayAccessWeakGlobals goes from false to true. In the other
692 // case, it may be racy, this is benign since DecodeWeakGlobalLocked does the correct behavior
693 // if MayAccessWeakGlobals is false.
Andreas Gampedc061d02016-10-24 13:19:37 -0700694 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700695 if (LIKELY(MayAccessWeakGlobalsUnlocked(self))) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700696 return weak_globals_.SynchronizedGet(ref);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700697 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700698 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700699 return DecodeWeakGlobalLocked(self, ref);
700}
701
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700702ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalLocked(Thread* self, IndirectRef ref) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700703 if (kDebugLocking) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700704 Locks::jni_weak_globals_lock_->AssertHeld(self);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700705 }
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700706 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700707 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
708 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800709 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700710 weak_globals_add_condition_.WaitHoldingLocks(self);
711 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700712 return weak_globals_.Get(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700713}
714
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700715ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalDuringShutdown(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700716 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700717 DCHECK(Runtime::Current()->IsShuttingDown(self));
718 if (self != nullptr) {
719 return DecodeWeakGlobal(self, ref);
720 }
721 // self can be null during a runtime shutdown. ~Runtime()->~ClassLinker()->DecodeWeakGlobal().
722 if (!kUseReadBarrier) {
723 DCHECK(allow_accessing_weak_globals_.LoadSequentiallyConsistent());
724 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700725 return weak_globals_.SynchronizedGet(ref);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700726}
727
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800728bool JavaVMExt::IsWeakGlobalCleared(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700729 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Andreas Gampe05a364c2016-10-14 13:27:12 -0700730 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800731 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700732 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
733 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800734 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800735 weak_globals_add_condition_.WaitHoldingLocks(self);
736 }
737 // When just checking a weak ref has been cleared, avoid triggering the read barrier in decode
738 // (DecodeWeakGlobal) so that we won't accidentally mark the object alive. Since the cleared
739 // sentinel is a non-moving object, we can compare the ref to it without the read barrier and
740 // decide if it's cleared.
741 return Runtime::Current()->IsClearedJniWeakGlobal(weak_globals_.Get<kWithoutReadBarrier>(ref));
742}
743
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700744void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700745 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700746 weak_globals_.Update(ref, result);
747}
748
Ian Rogers68d8b422014-07-17 11:09:10 -0700749void JavaVMExt::DumpReferenceTables(std::ostream& os) {
750 Thread* self = Thread::Current();
751 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700752 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700753 globals_.Dump(os);
754 }
755 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700756 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700757 weak_globals_.Dump(os);
758 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700759}
760
Mathieu Chartier598302a2015-09-23 14:52:39 -0700761void JavaVMExt::UnloadNativeLibraries() {
762 libraries_.get()->UnloadNativeLibraries();
763}
764
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800765bool JavaVMExt::LoadNativeLibrary(JNIEnv* env,
766 const std::string& path,
767 jobject class_loader,
768 jstring library_path,
769 std::string* error_msg) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700770 error_msg->clear();
771
772 // See if we've already loaded this library. If we have, and the class loader
773 // matches, return successfully without doing anything.
774 // TODO: for better results we should canonicalize the pathname (or even compare
775 // inodes). This implementation is fine if everybody is using System.loadLibrary.
776 SharedLibrary* library;
777 Thread* self = Thread::Current();
778 {
779 // TODO: move the locking (and more of this logic) into Libraries.
780 MutexLock mu(self, *Locks::jni_libraries_lock_);
781 library = libraries_->Get(path);
782 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800783 void* class_loader_allocator = nullptr;
784 {
785 ScopedObjectAccess soa(env);
786 // As the incoming class loader is reachable/alive during the call of this function,
787 // it's okay to decode it without worrying about unexpectedly marking it alive.
Mathieu Chartier0795f232016-09-27 18:43:30 -0700788 ObjPtr<mirror::ClassLoader> loader = soa.Decode<mirror::ClassLoader>(class_loader);
Andreas Gampe2d48e532016-06-17 12:46:14 -0700789
790 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700791 if (class_linker->IsBootClassLoader(soa, loader.Ptr())) {
Andreas Gampe2d48e532016-06-17 12:46:14 -0700792 loader = nullptr;
793 class_loader = nullptr;
794 }
795
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700796 class_loader_allocator = class_linker->GetAllocatorForClassLoader(loader.Ptr());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800797 CHECK(class_loader_allocator != nullptr);
798 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700799 if (library != nullptr) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800800 // Use the allocator pointers for class loader equality to avoid unnecessary weak root decode.
801 if (library->GetClassLoaderAllocator() != class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700802 // The library will be associated with class_loader. The JNI
803 // spec says we can't load the same library into more than one
804 // class loader.
805 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
806 "ClassLoader %p; can't open in ClassLoader %p",
807 path.c_str(), library->GetClassLoader(), class_loader);
808 LOG(WARNING) << error_msg;
809 return false;
810 }
811 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
812 << " ClassLoader " << class_loader << "]";
813 if (!library->CheckOnLoadResult()) {
814 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
815 "to load \"%s\"", path.c_str());
816 return false;
817 }
818 return true;
819 }
820
821 // Open the shared library. Because we're using a full path, the system
822 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
823 // resolve this library's dependencies though.)
824
825 // Failures here are expected when java.library.path has several entries
826 // and we have to hunt for the lib.
827
828 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
829 // class unloading. Libraries will only be unloaded when the reference count (incremented by
830 // dlopen) becomes zero from dlclose.
831
832 Locks::mutator_lock_->AssertNotHeld(self);
833 const char* path_str = path.empty() ? nullptr : path.c_str();
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800834 bool needs_native_bridge = false;
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800835 void* handle = android::OpenNativeLibrary(env,
836 runtime_->GetTargetSdkVersion(),
837 path_str,
838 class_loader,
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800839 library_path,
840 &needs_native_bridge,
841 error_msg);
Ian Rogers68d8b422014-07-17 11:09:10 -0700842
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700843 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]";
Ian Rogers68d8b422014-07-17 11:09:10 -0700844
845 if (handle == nullptr) {
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700846 VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700847 return false;
848 }
849
850 if (env->ExceptionCheck() == JNI_TRUE) {
851 LOG(ERROR) << "Unexpected exception:";
852 env->ExceptionDescribe();
853 env->ExceptionClear();
854 }
855 // Create a new entry.
856 // TODO: move the locking (and more of this logic) into Libraries.
857 bool created_library = false;
858 {
859 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
860 std::unique_ptr<SharedLibrary> new_library(
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800861 new SharedLibrary(env,
862 self,
863 path,
864 handle,
865 needs_native_bridge,
866 class_loader,
867 class_loader_allocator));
868
Ian Rogers68d8b422014-07-17 11:09:10 -0700869 MutexLock mu(self, *Locks::jni_libraries_lock_);
870 library = libraries_->Get(path);
871 if (library == nullptr) { // We won race to get libraries_lock.
872 library = new_library.release();
873 libraries_->Put(path, library);
874 created_library = true;
875 }
876 }
877 if (!created_library) {
878 LOG(INFO) << "WOW: we lost a race to add shared library: "
879 << "\"" << path << "\" ClassLoader=" << class_loader;
880 return library->CheckOnLoadResult();
881 }
882 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
883
884 bool was_successful = false;
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800885 void* sym = library->FindSymbol("JNI_OnLoad", nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700886 if (sym == nullptr) {
887 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
888 was_successful = true;
889 } else {
890 // Call JNI_OnLoad. We have to override the current class
891 // loader, which will always be "null" since the stuff at the
892 // top of the stack is around Runtime.loadLibrary(). (See
893 // the comments in the JNI FindClass function.)
894 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
895 self->SetClassLoaderOverride(class_loader);
896
897 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
898 typedef int (*JNI_OnLoadFn)(JavaVM*, void*);
899 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
900 int version = (*jni_on_load)(this, nullptr);
901
Mathieu Chartierd0004802014-10-15 16:59:47 -0700902 if (runtime_->GetTargetSdkVersion() != 0 && runtime_->GetTargetSdkVersion() <= 21) {
903 fault_manager.EnsureArtActionInFrontOfSignalChain();
904 }
905
Ian Rogers68d8b422014-07-17 11:09:10 -0700906 self->SetClassLoaderOverride(old_class_loader.get());
907
908 if (version == JNI_ERR) {
909 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
Alex Light185d1342016-08-11 10:48:03 -0700910 } else if (JavaVMExt::IsBadJniVersion(version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700911 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
912 path.c_str(), version);
913 // It's unwise to call dlclose() here, but we can mark it
914 // as bad and ensure that future load attempts will fail.
915 // We don't know how far JNI_OnLoad got, so there could
916 // be some partially-initialized stuff accessible through
917 // newly-registered native method calls. We could try to
918 // unregister them, but that doesn't seem worthwhile.
919 } else {
920 was_successful = true;
921 }
922 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
923 << " from JNI_OnLoad in \"" << path << "\"]";
924 }
925
926 library->SetResult(was_successful);
927 return was_successful;
928}
929
Mathieu Chartiere401d142015-04-22 13:56:20 -0700930void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700931 CHECK(m->IsNative());
932 mirror::Class* c = m->GetDeclaringClass();
933 // If this is a static method, it could be called before the class has been initialized.
David Sehr709b0702016-10-13 09:12:37 -0700934 CHECK(c->IsInitializing()) << c->GetStatus() << " " << m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700935 std::string detail;
936 void* native_method;
937 Thread* self = Thread::Current();
938 {
939 MutexLock mu(self, *Locks::jni_libraries_lock_);
940 native_method = libraries_->FindNativeMethod(m, detail);
941 }
942 // Throwing can cause libraries_lock to be reacquired.
943 if (native_method == nullptr) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000944 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
Ian Rogers68d8b422014-07-17 11:09:10 -0700945 }
946 return native_method;
947}
948
Mathieu Chartier97509952015-07-13 14:35:43 -0700949void JavaVMExt::SweepJniWeakGlobals(IsMarkedVisitor* visitor) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700950 MutexLock mu(Thread::Current(), *Locks::jni_weak_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700951 Runtime* const runtime = Runtime::Current();
952 for (auto* entry : weak_globals_) {
953 // Need to skip null here to distinguish between null entries and cleared weak ref entries.
954 if (!entry->IsNull()) {
955 // Since this is called by the GC, we don't need a read barrier.
956 mirror::Object* obj = entry->Read<kWithoutReadBarrier>();
Mathieu Chartier97509952015-07-13 14:35:43 -0700957 mirror::Object* new_obj = visitor->IsMarked(obj);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700958 if (new_obj == nullptr) {
959 new_obj = runtime->GetClearedJniWeakGlobal();
960 }
961 *entry = GcRoot<mirror::Object>(new_obj);
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -0700962 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700963 }
964}
965
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800966void JavaVMExt::TrimGlobals() {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700967 WriterMutexLock mu(Thread::Current(), *Locks::jni_globals_lock_);
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800968 globals_.Trim();
969}
970
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700971void JavaVMExt::VisitRoots(RootVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700972 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700973 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700974 globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal));
Ian Rogers68d8b422014-07-17 11:09:10 -0700975 // The weak_globals table is visited by the GC itself (because it mutates the table).
976}
977
978// JNI Invocation interface.
979
980extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800981 ScopedTrace trace(__FUNCTION__);
Ian Rogers68d8b422014-07-17 11:09:10 -0700982 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
Alex Light185d1342016-08-11 10:48:03 -0700983 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700984 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
985 return JNI_EVERSION;
986 }
987 RuntimeOptions options;
988 for (int i = 0; i < args->nOptions; ++i) {
989 JavaVMOption* option = &args->options[i];
990 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
991 }
992 bool ignore_unrecognized = args->ignoreUnrecognized;
993 if (!Runtime::Create(options, ignore_unrecognized)) {
994 return JNI_ERR;
995 }
Dimitry Ivanovc544f342016-05-09 16:26:13 -0700996
997 // Initialize native loader. This step makes sure we have
998 // everything set up before we start using JNI.
999 android::InitializeNativeLoader();
1000
Ian Rogers68d8b422014-07-17 11:09:10 -07001001 Runtime* runtime = Runtime::Current();
1002 bool started = runtime->Start();
1003 if (!started) {
1004 delete Thread::Current()->GetJniEnv();
1005 delete runtime->GetJavaVM();
1006 LOG(WARNING) << "CreateJavaVM failed";
1007 return JNI_ERR;
1008 }
Dimitry Ivanov041169f2016-04-21 16:01:24 -07001009
Ian Rogers68d8b422014-07-17 11:09:10 -07001010 *p_env = Thread::Current()->GetJniEnv();
1011 *p_vm = runtime->GetJavaVM();
1012 return JNI_OK;
1013}
1014
Ian Rogersf4d4da12014-11-11 16:10:33 -08001015extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001016 Runtime* runtime = Runtime::Current();
Ian Rogersf4d4da12014-11-11 16:10:33 -08001017 if (runtime == nullptr || buf_len == 0) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001018 *vm_count = 0;
1019 } else {
1020 *vm_count = 1;
Ian Rogersf4d4da12014-11-11 16:10:33 -08001021 vms_buf[0] = runtime->GetJavaVM();
Ian Rogers68d8b422014-07-17 11:09:10 -07001022 }
1023 return JNI_OK;
1024}
1025
1026// Historically unsupported.
1027extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
1028 return JNI_ERR;
1029}
1030
1031} // namespace art