blob: a1ed4708860283c02b1cbd56b62c8482cb08370a [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
Mathieu Chartiere401d142015-04-22 13:56:20 -070021#include "art_method.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070022#include "base/dumpable.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070023#include "base/mutex.h"
24#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080025#include "base/systrace.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070026#include "check_jni.h"
Elliott Hughes956af0f2014-12-11 14:34:28 -080027#include "dex_file-inl.h"
Mathieu Chartierd0004802014-10-15 16:59:47 -070028#include "fault_handler.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070029#include "indirect_reference_table-inl.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070030#include "mirror/class-inl.h"
31#include "mirror/class_loader.h"
Calin Juravlec8423522014-08-12 20:55:20 +010032#include "nativebridge/native_bridge.h"
Dmitriy Ivanovf5a30992015-11-11 14:18:55 -080033#include "nativeloader/native_loader.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070034#include "java_vm_ext.h"
35#include "parsed_options.h"
Ian Rogersc0542af2014-09-03 16:16:56 -070036#include "runtime-inl.h"
Igor Murashkinaaebaa02015-01-26 10:55:53 -080037#include "runtime_options.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070038#include "ScopedLocalRef.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070039#include "scoped_thread_state_change-inl.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070040#include "thread-inl.h"
41#include "thread_list.h"
42
43namespace art {
44
Andreas Gampea8e3b862016-10-17 20:12:52 -070045static constexpr size_t kGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
Ian Rogers68d8b422014-07-17 11:09:10 -070046
Andreas Gampea8e3b862016-10-17 20:12:52 -070047static constexpr size_t kWeakGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
Ian Rogers68d8b422014-07-17 11:09:10 -070048
Alex Light185d1342016-08-11 10:48:03 -070049bool JavaVMExt::IsBadJniVersion(int version) {
Ian Rogers68d8b422014-07-17 11:09:10 -070050 // We don't support JNI_VERSION_1_1. These are the only other valid versions.
51 return version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 && version != JNI_VERSION_1_6;
52}
53
54class SharedLibrary {
55 public:
56 SharedLibrary(JNIEnv* env, Thread* self, const std::string& path, void* handle,
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080057 jobject class_loader, void* class_loader_allocator)
Ian Rogers68d8b422014-07-17 11:09:10 -070058 : path_(path),
59 handle_(handle),
60 needs_native_bridge_(false),
Mathieu Chartier598302a2015-09-23 14:52:39 -070061 class_loader_(env->NewWeakGlobalRef(class_loader)),
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080062 class_loader_allocator_(class_loader_allocator),
Ian Rogers68d8b422014-07-17 11:09:10 -070063 jni_on_load_lock_("JNI_OnLoad lock"),
64 jni_on_load_cond_("JNI_OnLoad condition variable", jni_on_load_lock_),
65 jni_on_load_thread_id_(self->GetThreadId()),
66 jni_on_load_result_(kPending) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080067 CHECK(class_loader_allocator_ != nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -070068 }
69
70 ~SharedLibrary() {
71 Thread* self = Thread::Current();
72 if (self != nullptr) {
Mathieu Chartier598302a2015-09-23 14:52:39 -070073 self->GetJniEnv()->DeleteWeakGlobalRef(class_loader_);
Ian Rogers68d8b422014-07-17 11:09:10 -070074 }
Alex Lightbc5669e2016-06-13 17:22:13 +000075
76 if (!needs_native_bridge_) {
77 android::CloseNativeLibrary(handle_);
78 }
Ian Rogers68d8b422014-07-17 11:09:10 -070079 }
80
Mathieu Chartier598302a2015-09-23 14:52:39 -070081 jweak GetClassLoader() const {
Ian Rogers68d8b422014-07-17 11:09:10 -070082 return class_loader_;
83 }
84
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080085 const void* GetClassLoaderAllocator() const {
86 return class_loader_allocator_;
87 }
88
Ian Rogers68d8b422014-07-17 11:09:10 -070089 const std::string& GetPath() const {
90 return path_;
91 }
92
93 /*
94 * Check the result of an earlier call to JNI_OnLoad on this library.
95 * If the call has not yet finished in another thread, wait for it.
96 */
97 bool CheckOnLoadResult()
Mathieu Chartier90443472015-07-16 20:32:27 -070098 REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -070099 Thread* self = Thread::Current();
100 bool okay;
101 {
102 MutexLock mu(self, jni_on_load_lock_);
103
104 if (jni_on_load_thread_id_ == self->GetThreadId()) {
105 // Check this so we don't end up waiting for ourselves. We need to return "true" so the
106 // caller can continue.
107 LOG(INFO) << *self << " recursive attempt to load library " << "\"" << path_ << "\"";
108 okay = true;
109 } else {
110 while (jni_on_load_result_ == kPending) {
111 VLOG(jni) << "[" << *self << " waiting for \"" << path_ << "\" " << "JNI_OnLoad...]";
112 jni_on_load_cond_.Wait(self);
113 }
114
115 okay = (jni_on_load_result_ == kOkay);
116 VLOG(jni) << "[Earlier JNI_OnLoad for \"" << path_ << "\" "
117 << (okay ? "succeeded" : "failed") << "]";
118 }
119 }
120 return okay;
121 }
122
Mathieu Chartier90443472015-07-16 20:32:27 -0700123 void SetResult(bool result) REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700124 Thread* self = Thread::Current();
125 MutexLock mu(self, jni_on_load_lock_);
126
127 jni_on_load_result_ = result ? kOkay : kFailed;
128 jni_on_load_thread_id_ = 0;
129
130 // Broadcast a wakeup to anybody sleeping on the condition variable.
131 jni_on_load_cond_.Broadcast(self);
132 }
133
134 void SetNeedsNativeBridge() {
135 needs_native_bridge_ = true;
136 }
137
138 bool NeedsNativeBridge() const {
139 return needs_native_bridge_;
140 }
141
Mathieu Chartier598302a2015-09-23 14:52:39 -0700142 void* FindSymbol(const std::string& symbol_name, const char* shorty = nullptr) {
143 return NeedsNativeBridge()
144 ? FindSymbolWithNativeBridge(symbol_name.c_str(), shorty)
145 : FindSymbolWithoutNativeBridge(symbol_name.c_str());
146 }
147
148 void* FindSymbolWithoutNativeBridge(const std::string& symbol_name) {
Andreas Gampe8fec90b2015-06-30 11:23:44 -0700149 CHECK(!NeedsNativeBridge());
150
Ian Rogers68d8b422014-07-17 11:09:10 -0700151 return dlsym(handle_, symbol_name.c_str());
152 }
153
154 void* FindSymbolWithNativeBridge(const std::string& symbol_name, const char* shorty) {
155 CHECK(NeedsNativeBridge());
156
157 uint32_t len = 0;
Calin Juravlec8423522014-08-12 20:55:20 +0100158 return android::NativeBridgeGetTrampoline(handle_, symbol_name.c_str(), shorty, len);
Ian Rogers68d8b422014-07-17 11:09:10 -0700159 }
160
161 private:
162 enum JNI_OnLoadState {
163 kPending,
164 kFailed,
165 kOkay,
166 };
167
168 // Path to library "/system/lib/libjni.so".
169 const std::string path_;
170
171 // The void* returned by dlopen(3).
172 void* const handle_;
173
174 // True if a native bridge is required.
175 bool needs_native_bridge_;
176
Mathieu Chartier598302a2015-09-23 14:52:39 -0700177 // The ClassLoader this library is associated with, a weak global JNI reference that is
Ian Rogers68d8b422014-07-17 11:09:10 -0700178 // created/deleted with the scope of the library.
Mathieu Chartier598302a2015-09-23 14:52:39 -0700179 const jweak class_loader_;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800180 // Used to do equality check on class loaders so we can avoid decoding the weak root and read
181 // barriers that mess with class unloading.
182 const void* class_loader_allocator_;
Ian Rogers68d8b422014-07-17 11:09:10 -0700183
184 // Guards remaining items.
185 Mutex jni_on_load_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
186 // Wait for JNI_OnLoad in other thread.
187 ConditionVariable jni_on_load_cond_ GUARDED_BY(jni_on_load_lock_);
188 // Recursive invocation guard.
189 uint32_t jni_on_load_thread_id_ GUARDED_BY(jni_on_load_lock_);
190 // Result of earlier JNI_OnLoad call.
191 JNI_OnLoadState jni_on_load_result_ GUARDED_BY(jni_on_load_lock_);
192};
193
194// This exists mainly to keep implementation details out of the header file.
195class Libraries {
196 public:
197 Libraries() {
198 }
199
200 ~Libraries() {
201 STLDeleteValues(&libraries_);
202 }
203
Mathieu Chartier598302a2015-09-23 14:52:39 -0700204 // NO_THREAD_SAFETY_ANALYSIS since this may be called from Dumpable. Dumpable can't be annotated
205 // properly due to the template. The caller should be holding the jni_libraries_lock_.
206 void Dump(std::ostream& os) const NO_THREAD_SAFETY_ANALYSIS {
207 Locks::jni_libraries_lock_->AssertHeld(Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -0700208 bool first = true;
209 for (const auto& library : libraries_) {
210 if (!first) {
211 os << ' ';
212 }
213 first = false;
214 os << library.first;
215 }
216 }
217
Mathieu Chartier598302a2015-09-23 14:52:39 -0700218 size_t size() const REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700219 return libraries_.size();
220 }
221
Mathieu Chartier598302a2015-09-23 14:52:39 -0700222 SharedLibrary* Get(const std::string& path) REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700223 auto it = libraries_.find(path);
224 return (it == libraries_.end()) ? nullptr : it->second;
225 }
226
Mathieu Chartier598302a2015-09-23 14:52:39 -0700227 void Put(const std::string& path, SharedLibrary* library)
228 REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700229 libraries_.Put(path, library);
230 }
231
232 // See section 11.3 "Linking Native Methods" of the JNI spec.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700233 void* FindNativeMethod(ArtMethod* m, std::string& detail)
Mathieu Chartier90443472015-07-16 20:32:27 -0700234 REQUIRES(Locks::jni_libraries_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700235 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700236 std::string jni_short_name(m->JniShortName());
237 std::string jni_long_name(m->JniLongName());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800238 mirror::ClassLoader* const declaring_class_loader = m->GetDeclaringClass()->GetClassLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700239 ScopedObjectAccessUnchecked soa(Thread::Current());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800240 void* const declaring_class_loader_allocator =
241 Runtime::Current()->GetClassLinker()->GetAllocatorForClassLoader(declaring_class_loader);
242 CHECK(declaring_class_loader_allocator != nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700243 for (const auto& lib : libraries_) {
Mathieu Chartier598302a2015-09-23 14:52:39 -0700244 SharedLibrary* const library = lib.second;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800245 // Use the allocator address for class loader equality to avoid unnecessary weak root decode.
246 if (library->GetClassLoaderAllocator() != declaring_class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700247 // We only search libraries loaded by the appropriate ClassLoader.
248 continue;
249 }
250 // Try the short name then the long name...
Mathieu Chartier598302a2015-09-23 14:52:39 -0700251 const char* shorty = library->NeedsNativeBridge()
252 ? m->GetShorty()
253 : nullptr;
254 void* fn = library->FindSymbol(jni_short_name, shorty);
255 if (fn == nullptr) {
256 fn = library->FindSymbol(jni_long_name, shorty);
Ian Rogers68d8b422014-07-17 11:09:10 -0700257 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700258 if (fn != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700259 VLOG(jni) << "[Found native code for " << m->PrettyMethod()
Ian Rogers68d8b422014-07-17 11:09:10 -0700260 << " in \"" << library->GetPath() << "\"]";
261 return fn;
262 }
263 }
264 detail += "No implementation found for ";
David Sehr709b0702016-10-13 09:12:37 -0700265 detail += m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700266 detail += " (tried " + jni_short_name + " and " + jni_long_name + ")";
267 LOG(ERROR) << detail;
268 return nullptr;
269 }
270
Mathieu Chartier598302a2015-09-23 14:52:39 -0700271 // Unload native libraries with cleared class loaders.
272 void UnloadNativeLibraries()
273 REQUIRES(!Locks::jni_libraries_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700274 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier598302a2015-09-23 14:52:39 -0700275 ScopedObjectAccessUnchecked soa(Thread::Current());
Alex Lightbc5669e2016-06-13 17:22:13 +0000276 std::vector<SharedLibrary*> unload_libraries;
Mathieu Chartier598302a2015-09-23 14:52:39 -0700277 {
278 MutexLock mu(soa.Self(), *Locks::jni_libraries_lock_);
279 for (auto it = libraries_.begin(); it != libraries_.end(); ) {
280 SharedLibrary* const library = it->second;
281 // If class loader is null then it was unloaded, call JNI_OnUnload.
Mathieu Chartiercffb7472015-09-28 10:33:00 -0700282 const jweak class_loader = library->GetClassLoader();
283 // If class_loader is a null jobject then it is the boot class loader. We should not unload
284 // the native libraries of the boot class loader.
285 if (class_loader != nullptr &&
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800286 soa.Self()->IsJWeakCleared(class_loader)) {
Alex Lightbc5669e2016-06-13 17:22:13 +0000287 unload_libraries.push_back(library);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700288 it = libraries_.erase(it);
289 } else {
290 ++it;
291 }
292 }
293 }
294 // Do this without holding the jni libraries lock to prevent possible deadlocks.
Alex Lightbc5669e2016-06-13 17:22:13 +0000295 typedef void (*JNI_OnUnloadFn)(JavaVM*, void*);
296 for (auto library : unload_libraries) {
297 void* const sym = library->FindSymbol("JNI_OnUnload", nullptr);
298 if (sym == nullptr) {
299 VLOG(jni) << "[No JNI_OnUnload found in \"" << library->GetPath() << "\"]";
300 } else {
301 VLOG(jni) << "[JNI_OnUnload found for \"" << library->GetPath() << "\"]: Calling...";
302 JNI_OnUnloadFn jni_on_unload = reinterpret_cast<JNI_OnUnloadFn>(sym);
303 jni_on_unload(soa.Vm(), nullptr);
304 }
305 delete library;
Mathieu Chartier598302a2015-09-23 14:52:39 -0700306 }
307 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700308
Mathieu Chartier598302a2015-09-23 14:52:39 -0700309 private:
310 AllocationTrackingSafeMap<std::string, SharedLibrary*, kAllocatorTagJNILibraries> libraries_
311 GUARDED_BY(Locks::jni_libraries_lock_);
312};
Ian Rogers68d8b422014-07-17 11:09:10 -0700313
314class JII {
315 public:
316 static jint DestroyJavaVM(JavaVM* vm) {
317 if (vm == nullptr) {
318 return JNI_ERR;
319 }
320 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
321 delete raw_vm->GetRuntime();
Dimitry Ivanov39d68ef2016-04-29 16:02:38 -0700322 android::ResetNativeLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700323 return JNI_OK;
324 }
325
326 static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
327 return AttachCurrentThreadInternal(vm, p_env, thr_args, false);
328 }
329
330 static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
331 return AttachCurrentThreadInternal(vm, p_env, thr_args, true);
332 }
333
334 static jint DetachCurrentThread(JavaVM* vm) {
335 if (vm == nullptr || Thread::Current() == nullptr) {
336 return JNI_ERR;
337 }
338 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
339 Runtime* runtime = raw_vm->GetRuntime();
340 runtime->DetachCurrentThread();
341 return JNI_OK;
342 }
343
344 static jint GetEnv(JavaVM* vm, void** env, jint version) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700345 if (vm == nullptr || env == nullptr) {
346 return JNI_ERR;
347 }
348 Thread* thread = Thread::Current();
349 if (thread == nullptr) {
350 *env = nullptr;
351 return JNI_EDETACHED;
352 }
Alex Light185d1342016-08-11 10:48:03 -0700353 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
354 return raw_vm->HandleGetEnv(env, version);
Ian Rogers68d8b422014-07-17 11:09:10 -0700355 }
356
357 private:
358 static jint AttachCurrentThreadInternal(JavaVM* vm, JNIEnv** p_env, void* raw_args, bool as_daemon) {
359 if (vm == nullptr || p_env == nullptr) {
360 return JNI_ERR;
361 }
362
363 // Return immediately if we're already attached.
364 Thread* self = Thread::Current();
365 if (self != nullptr) {
366 *p_env = self->GetJniEnv();
367 return JNI_OK;
368 }
369
370 Runtime* runtime = reinterpret_cast<JavaVMExt*>(vm)->GetRuntime();
371
372 // No threads allowed in zygote mode.
373 if (runtime->IsZygote()) {
374 LOG(ERROR) << "Attempt to attach a thread in the zygote";
375 return JNI_ERR;
376 }
377
378 JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(raw_args);
379 const char* thread_name = nullptr;
380 jobject thread_group = nullptr;
381 if (args != nullptr) {
Alex Light185d1342016-08-11 10:48:03 -0700382 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700383 LOG(ERROR) << "Bad JNI version passed to "
384 << (as_daemon ? "AttachCurrentThreadAsDaemon" : "AttachCurrentThread") << ": "
385 << args->version;
386 return JNI_EVERSION;
387 }
388 thread_name = args->name;
389 thread_group = args->group;
390 }
391
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800392 if (!runtime->AttachCurrentThread(thread_name, as_daemon, thread_group,
393 !runtime->IsAotCompiler())) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700394 *p_env = nullptr;
395 return JNI_ERR;
396 } else {
397 *p_env = Thread::Current()->GetJniEnv();
398 return JNI_OK;
399 }
400 }
401};
402
403const JNIInvokeInterface gJniInvokeInterface = {
404 nullptr, // reserved0
405 nullptr, // reserved1
406 nullptr, // reserved2
407 JII::DestroyJavaVM,
408 JII::AttachCurrentThread,
409 JII::DetachCurrentThread,
410 JII::GetEnv,
411 JII::AttachCurrentThreadAsDaemon
412};
413
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100414JavaVMExt::JavaVMExt(Runtime* runtime,
415 const RuntimeArgumentMap& runtime_options,
416 std::string* error_msg)
Ian Rogers68d8b422014-07-17 11:09:10 -0700417 : runtime_(runtime),
418 check_jni_abort_hook_(nullptr),
419 check_jni_abort_hook_data_(nullptr),
420 check_jni_(false), // Initialized properly in the constructor body below.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800421 force_copy_(runtime_options.Exists(RuntimeArgumentMap::JniOptsForceCopy)),
422 tracing_enabled_(runtime_options.Exists(RuntimeArgumentMap::JniTrace)
423 || VLOG_IS_ON(third_party_jni)),
424 trace_(runtime_options.GetOrDefault(RuntimeArgumentMap::JniTrace)),
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700425 globals_(kGlobalsMax, kGlobal, IndirectReferenceTable::ResizableCapacity::kNo, error_msg),
Ian Rogers68d8b422014-07-17 11:09:10 -0700426 libraries_(new Libraries),
427 unchecked_functions_(&gJniInvokeInterface),
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700428 weak_globals_(kWeakGlobalsMax,
429 kWeakGlobal,
430 IndirectReferenceTable::ResizableCapacity::kNo,
431 error_msg),
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700432 allow_accessing_weak_globals_(true),
Andreas Gampe05a364c2016-10-14 13:27:12 -0700433 weak_globals_add_condition_("weak globals add condition",
434 (CHECK(Locks::jni_weak_globals_lock_ != nullptr),
435 *Locks::jni_weak_globals_lock_)),
Alex Light185d1342016-08-11 10:48:03 -0700436 env_hooks_() {
Ian Rogers68d8b422014-07-17 11:09:10 -0700437 functions = unchecked_functions_;
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800438 SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni));
Ian Rogers68d8b422014-07-17 11:09:10 -0700439}
440
441JavaVMExt::~JavaVMExt() {
442}
443
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100444// Checking "globals" and "weak_globals" usually requires locks, but we
445// don't need the locks to check for validity when constructing the
446// object. Use NO_THREAD_SAFETY_ANALYSIS for this.
447std::unique_ptr<JavaVMExt> JavaVMExt::Create(Runtime* runtime,
448 const RuntimeArgumentMap& runtime_options,
449 std::string* error_msg) NO_THREAD_SAFETY_ANALYSIS {
450 std::unique_ptr<JavaVMExt> java_vm(new JavaVMExt(runtime, runtime_options, error_msg));
451 if (java_vm && java_vm->globals_.IsValid() && java_vm->weak_globals_.IsValid()) {
452 return java_vm;
453 }
454 return nullptr;
455}
456
Alex Light185d1342016-08-11 10:48:03 -0700457jint JavaVMExt::HandleGetEnv(/*out*/void** env, jint version) {
458 for (GetEnvHook hook : env_hooks_) {
459 jint res = hook(this, env, version);
460 if (res == JNI_OK) {
461 return JNI_OK;
462 } else if (res != JNI_EVERSION) {
463 LOG(ERROR) << "Error returned from a plugin GetEnv handler! " << res;
464 return res;
465 }
466 }
467 LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version;
468 return JNI_EVERSION;
469}
470
471// Add a hook to handle getting environments from the GetEnv call.
472void JavaVMExt::AddEnvironmentHook(GetEnvHook hook) {
473 CHECK(hook != nullptr) << "environment hooks shouldn't be null!";
474 env_hooks_.push_back(hook);
475}
476
Ian Rogers68d8b422014-07-17 11:09:10 -0700477void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) {
478 Thread* self = Thread::Current();
479 ScopedObjectAccess soa(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700480 ArtMethod* current_method = self->GetCurrentMethod(nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700481
482 std::ostringstream os;
483 os << "JNI DETECTED ERROR IN APPLICATION: " << msg;
484
485 if (jni_function_name != nullptr) {
486 os << "\n in call to " << jni_function_name;
487 }
488 // TODO: is this useful given that we're about to dump the calling thread's stack?
489 if (current_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700490 os << "\n from " << current_method->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700491 }
492 os << "\n";
493 self->Dump(os);
494
495 if (check_jni_abort_hook_ != nullptr) {
496 check_jni_abort_hook_(check_jni_abort_hook_data_, os.str());
497 } else {
498 // Ensure that we get a native stack trace for this thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700499 ScopedThreadSuspension sts(self, kNative);
Ian Rogers68d8b422014-07-17 11:09:10 -0700500 LOG(FATAL) << os.str();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700501 UNREACHABLE();
Ian Rogers68d8b422014-07-17 11:09:10 -0700502 }
503}
504
505void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) {
506 std::string msg;
507 StringAppendV(&msg, fmt, ap);
508 JniAbort(jni_function_name, msg.c_str());
509}
510
511void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) {
512 va_list args;
513 va_start(args, fmt);
514 JniAbortV(jni_function_name, fmt, args);
515 va_end(args);
516}
517
Mathieu Chartiere401d142015-04-22 13:56:20 -0700518bool JavaVMExt::ShouldTrace(ArtMethod* method) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700519 // Fast where no tracing is enabled.
520 if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) {
521 return false;
522 }
523 // Perform checks based on class name.
524 StringPiece class_name(method->GetDeclaringClassDescriptor());
525 if (!trace_.empty() && class_name.find(trace_) != std::string::npos) {
526 return true;
527 }
528 if (!VLOG_IS_ON(third_party_jni)) {
529 return false;
530 }
531 // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
532 // like part of Android.
533 static const char* gBuiltInPrefixes[] = {
534 "Landroid/",
535 "Lcom/android/",
536 "Lcom/google/android/",
537 "Ldalvik/",
538 "Ljava/",
539 "Ljavax/",
540 "Llibcore/",
541 "Lorg/apache/harmony/",
542 };
543 for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) {
544 if (class_name.starts_with(gBuiltInPrefixes[i])) {
545 return false;
546 }
547 }
548 return true;
549}
550
Mathieu Chartier0795f232016-09-27 18:43:30 -0700551jobject JavaVMExt::AddGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700552 // Check for null after decoding the object to handle cleared weak globals.
553 if (obj == nullptr) {
554 return nullptr;
555 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700556 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700557 IndirectRef ref = globals_.Add(kIRTFirstSegment, obj);
Ian Rogers68d8b422014-07-17 11:09:10 -0700558 return reinterpret_cast<jobject>(ref);
559}
560
Mathieu Chartier0795f232016-09-27 18:43:30 -0700561jweak JavaVMExt::AddWeakGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700562 if (obj == nullptr) {
563 return nullptr;
564 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700565 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700566 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700567 weak_globals_add_condition_.WaitHoldingLocks(self);
568 }
Andreas Gampee03662b2016-10-13 17:12:56 -0700569 IndirectRef ref = weak_globals_.Add(kIRTFirstSegment, obj);
Ian Rogers68d8b422014-07-17 11:09:10 -0700570 return reinterpret_cast<jweak>(ref);
571}
572
573void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
574 if (obj == nullptr) {
575 return;
576 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700577 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700578 if (!globals_.Remove(kIRTFirstSegment, obj)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700579 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
580 << "failed to find entry";
581 }
582}
583
584void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
585 if (obj == nullptr) {
586 return;
587 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700588 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700589 if (!weak_globals_.Remove(kIRTFirstSegment, obj)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700590 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
591 << "failed to find entry";
592 }
593}
594
595static void ThreadEnableCheckJni(Thread* thread, void* arg) {
596 bool* check_jni = reinterpret_cast<bool*>(arg);
597 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
598}
599
600bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
601 bool old_check_jni = check_jni_;
602 check_jni_ = enabled;
603 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
604 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
605 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
606 return old_check_jni;
607}
608
609void JavaVMExt::DumpForSigQuit(std::ostream& os) {
610 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
611 if (force_copy_) {
612 os << " (with forcecopy)";
613 }
614 Thread* self = Thread::Current();
615 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700616 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700617 os << "; globals=" << globals_.Capacity();
618 }
619 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700620 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700621 if (weak_globals_.Capacity() > 0) {
622 os << " (plus " << weak_globals_.Capacity() << " weak)";
623 }
624 }
625 os << '\n';
626
627 {
628 MutexLock mu(self, *Locks::jni_libraries_lock_);
629 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
630 }
631}
632
633void JavaVMExt::DisallowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700634 CHECK(!kUseReadBarrier);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700635 Thread* const self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700636 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700637 // DisallowNewWeakGlobals is only called by CMS during the pause. It is required to have the
638 // mutator lock exclusively held so that we don't have any threads in the middle of
639 // DecodeWeakGlobal.
640 Locks::mutator_lock_->AssertExclusiveHeld(self);
641 allow_accessing_weak_globals_.StoreSequentiallyConsistent(false);
Ian Rogers68d8b422014-07-17 11:09:10 -0700642}
643
644void JavaVMExt::AllowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700645 CHECK(!kUseReadBarrier);
Ian Rogers68d8b422014-07-17 11:09:10 -0700646 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700647 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700648 allow_accessing_weak_globals_.StoreSequentiallyConsistent(true);
Ian Rogers68d8b422014-07-17 11:09:10 -0700649 weak_globals_add_condition_.Broadcast(self);
650}
651
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700652void JavaVMExt::BroadcastForNewWeakGlobals() {
653 CHECK(kUseReadBarrier);
654 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700655 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700656 weak_globals_add_condition_.Broadcast(self);
657}
658
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700659ObjPtr<mirror::Object> JavaVMExt::DecodeGlobal(IndirectRef ref) {
660 return globals_.SynchronizedGet(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700661}
662
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700663void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700664 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700665 globals_.Update(ref, result);
666}
667
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700668inline bool JavaVMExt::MayAccessWeakGlobals(Thread* self) const {
669 return MayAccessWeakGlobalsUnlocked(self);
670}
671
672inline bool JavaVMExt::MayAccessWeakGlobalsUnlocked(Thread* self) const {
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700673 DCHECK(self != nullptr);
674 return kUseReadBarrier ?
675 self->GetWeakRefAccessEnabled() :
676 allow_accessing_weak_globals_.LoadSequentiallyConsistent();
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700677}
678
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700679ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700680 // It is safe to access GetWeakRefAccessEnabled without the lock since CC uses checkpoints to call
681 // SetWeakRefAccessEnabled, and the other collectors only modify allow_accessing_weak_globals_
682 // when the mutators are paused.
683 // This only applies in the case where MayAccessWeakGlobals goes from false to true. In the other
684 // case, it may be racy, this is benign since DecodeWeakGlobalLocked does the correct behavior
685 // if MayAccessWeakGlobals is false.
Andreas Gampedc061d02016-10-24 13:19:37 -0700686 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700687 if (LIKELY(MayAccessWeakGlobalsUnlocked(self))) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700688 return weak_globals_.SynchronizedGet(ref);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700689 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700690 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700691 return DecodeWeakGlobalLocked(self, ref);
692}
693
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700694ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalLocked(Thread* self, IndirectRef ref) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700695 if (kDebugLocking) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700696 Locks::jni_weak_globals_lock_->AssertHeld(self);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700697 }
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700698 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700699 weak_globals_add_condition_.WaitHoldingLocks(self);
700 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700701 return weak_globals_.Get(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700702}
703
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700704ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalDuringShutdown(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700705 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700706 DCHECK(Runtime::Current()->IsShuttingDown(self));
707 if (self != nullptr) {
708 return DecodeWeakGlobal(self, ref);
709 }
710 // self can be null during a runtime shutdown. ~Runtime()->~ClassLinker()->DecodeWeakGlobal().
711 if (!kUseReadBarrier) {
712 DCHECK(allow_accessing_weak_globals_.LoadSequentiallyConsistent());
713 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700714 return weak_globals_.SynchronizedGet(ref);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700715}
716
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800717bool JavaVMExt::IsWeakGlobalCleared(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700718 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Andreas Gampe05a364c2016-10-14 13:27:12 -0700719 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800720 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
721 weak_globals_add_condition_.WaitHoldingLocks(self);
722 }
723 // When just checking a weak ref has been cleared, avoid triggering the read barrier in decode
724 // (DecodeWeakGlobal) so that we won't accidentally mark the object alive. Since the cleared
725 // sentinel is a non-moving object, we can compare the ref to it without the read barrier and
726 // decide if it's cleared.
727 return Runtime::Current()->IsClearedJniWeakGlobal(weak_globals_.Get<kWithoutReadBarrier>(ref));
728}
729
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700730void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700731 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700732 weak_globals_.Update(ref, result);
733}
734
Ian Rogers68d8b422014-07-17 11:09:10 -0700735void JavaVMExt::DumpReferenceTables(std::ostream& os) {
736 Thread* self = Thread::Current();
737 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700738 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700739 globals_.Dump(os);
740 }
741 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700742 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700743 weak_globals_.Dump(os);
744 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700745}
746
Mathieu Chartier598302a2015-09-23 14:52:39 -0700747void JavaVMExt::UnloadNativeLibraries() {
748 libraries_.get()->UnloadNativeLibraries();
749}
750
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800751bool JavaVMExt::LoadNativeLibrary(JNIEnv* env,
752 const std::string& path,
753 jobject class_loader,
754 jstring library_path,
755 std::string* error_msg) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700756 error_msg->clear();
757
758 // See if we've already loaded this library. If we have, and the class loader
759 // matches, return successfully without doing anything.
760 // TODO: for better results we should canonicalize the pathname (or even compare
761 // inodes). This implementation is fine if everybody is using System.loadLibrary.
762 SharedLibrary* library;
763 Thread* self = Thread::Current();
764 {
765 // TODO: move the locking (and more of this logic) into Libraries.
766 MutexLock mu(self, *Locks::jni_libraries_lock_);
767 library = libraries_->Get(path);
768 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800769 void* class_loader_allocator = nullptr;
770 {
771 ScopedObjectAccess soa(env);
772 // As the incoming class loader is reachable/alive during the call of this function,
773 // it's okay to decode it without worrying about unexpectedly marking it alive.
Mathieu Chartier0795f232016-09-27 18:43:30 -0700774 ObjPtr<mirror::ClassLoader> loader = soa.Decode<mirror::ClassLoader>(class_loader);
Andreas Gampe2d48e532016-06-17 12:46:14 -0700775
776 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700777 if (class_linker->IsBootClassLoader(soa, loader.Ptr())) {
Andreas Gampe2d48e532016-06-17 12:46:14 -0700778 loader = nullptr;
779 class_loader = nullptr;
780 }
781
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700782 class_loader_allocator = class_linker->GetAllocatorForClassLoader(loader.Ptr());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800783 CHECK(class_loader_allocator != nullptr);
784 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700785 if (library != nullptr) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800786 // Use the allocator pointers for class loader equality to avoid unnecessary weak root decode.
787 if (library->GetClassLoaderAllocator() != class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700788 // The library will be associated with class_loader. The JNI
789 // spec says we can't load the same library into more than one
790 // class loader.
791 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
792 "ClassLoader %p; can't open in ClassLoader %p",
793 path.c_str(), library->GetClassLoader(), class_loader);
794 LOG(WARNING) << error_msg;
795 return false;
796 }
797 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
798 << " ClassLoader " << class_loader << "]";
799 if (!library->CheckOnLoadResult()) {
800 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
801 "to load \"%s\"", path.c_str());
802 return false;
803 }
804 return true;
805 }
806
807 // Open the shared library. Because we're using a full path, the system
808 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
809 // resolve this library's dependencies though.)
810
811 // Failures here are expected when java.library.path has several entries
812 // and we have to hunt for the lib.
813
814 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
815 // class unloading. Libraries will only be unloaded when the reference count (incremented by
816 // dlopen) becomes zero from dlclose.
817
818 Locks::mutator_lock_->AssertNotHeld(self);
819 const char* path_str = path.empty() ? nullptr : path.c_str();
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800820 void* handle = android::OpenNativeLibrary(env,
821 runtime_->GetTargetSdkVersion(),
822 path_str,
823 class_loader,
824 library_path);
825
Ian Rogers68d8b422014-07-17 11:09:10 -0700826 bool needs_native_bridge = false;
827 if (handle == nullptr) {
Calin Juravlec8423522014-08-12 20:55:20 +0100828 if (android::NativeBridgeIsSupported(path_str)) {
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700829 handle = android::NativeBridgeLoadLibrary(path_str, RTLD_NOW);
Ian Rogers68d8b422014-07-17 11:09:10 -0700830 needs_native_bridge = true;
831 }
832 }
833
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700834 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]";
Ian Rogers68d8b422014-07-17 11:09:10 -0700835
836 if (handle == nullptr) {
837 *error_msg = dlerror();
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700838 VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700839 return false;
840 }
841
842 if (env->ExceptionCheck() == JNI_TRUE) {
843 LOG(ERROR) << "Unexpected exception:";
844 env->ExceptionDescribe();
845 env->ExceptionClear();
846 }
847 // Create a new entry.
848 // TODO: move the locking (and more of this logic) into Libraries.
849 bool created_library = false;
850 {
851 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
852 std::unique_ptr<SharedLibrary> new_library(
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800853 new SharedLibrary(env, self, path, handle, class_loader, class_loader_allocator));
Ian Rogers68d8b422014-07-17 11:09:10 -0700854 MutexLock mu(self, *Locks::jni_libraries_lock_);
855 library = libraries_->Get(path);
856 if (library == nullptr) { // We won race to get libraries_lock.
857 library = new_library.release();
858 libraries_->Put(path, library);
859 created_library = true;
860 }
861 }
862 if (!created_library) {
863 LOG(INFO) << "WOW: we lost a race to add shared library: "
864 << "\"" << path << "\" ClassLoader=" << class_loader;
865 return library->CheckOnLoadResult();
866 }
867 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
868
869 bool was_successful = false;
870 void* sym;
871 if (needs_native_bridge) {
872 library->SetNeedsNativeBridge();
Ian Rogers68d8b422014-07-17 11:09:10 -0700873 }
Mathieu Chartier598302a2015-09-23 14:52:39 -0700874 sym = library->FindSymbol("JNI_OnLoad", nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700875 if (sym == nullptr) {
876 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
877 was_successful = true;
878 } else {
879 // Call JNI_OnLoad. We have to override the current class
880 // loader, which will always be "null" since the stuff at the
881 // top of the stack is around Runtime.loadLibrary(). (See
882 // the comments in the JNI FindClass function.)
883 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
884 self->SetClassLoaderOverride(class_loader);
885
886 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
887 typedef int (*JNI_OnLoadFn)(JavaVM*, void*);
888 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
889 int version = (*jni_on_load)(this, nullptr);
890
Mathieu Chartierd0004802014-10-15 16:59:47 -0700891 if (runtime_->GetTargetSdkVersion() != 0 && runtime_->GetTargetSdkVersion() <= 21) {
892 fault_manager.EnsureArtActionInFrontOfSignalChain();
893 }
894
Ian Rogers68d8b422014-07-17 11:09:10 -0700895 self->SetClassLoaderOverride(old_class_loader.get());
896
897 if (version == JNI_ERR) {
898 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
Alex Light185d1342016-08-11 10:48:03 -0700899 } else if (JavaVMExt::IsBadJniVersion(version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700900 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
901 path.c_str(), version);
902 // It's unwise to call dlclose() here, but we can mark it
903 // as bad and ensure that future load attempts will fail.
904 // We don't know how far JNI_OnLoad got, so there could
905 // be some partially-initialized stuff accessible through
906 // newly-registered native method calls. We could try to
907 // unregister them, but that doesn't seem worthwhile.
908 } else {
909 was_successful = true;
910 }
911 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
912 << " from JNI_OnLoad in \"" << path << "\"]";
913 }
914
915 library->SetResult(was_successful);
916 return was_successful;
917}
918
Mathieu Chartiere401d142015-04-22 13:56:20 -0700919void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700920 CHECK(m->IsNative());
921 mirror::Class* c = m->GetDeclaringClass();
922 // If this is a static method, it could be called before the class has been initialized.
David Sehr709b0702016-10-13 09:12:37 -0700923 CHECK(c->IsInitializing()) << c->GetStatus() << " " << m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700924 std::string detail;
925 void* native_method;
926 Thread* self = Thread::Current();
927 {
928 MutexLock mu(self, *Locks::jni_libraries_lock_);
929 native_method = libraries_->FindNativeMethod(m, detail);
930 }
931 // Throwing can cause libraries_lock to be reacquired.
932 if (native_method == nullptr) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000933 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
Ian Rogers68d8b422014-07-17 11:09:10 -0700934 }
935 return native_method;
936}
937
Mathieu Chartier97509952015-07-13 14:35:43 -0700938void JavaVMExt::SweepJniWeakGlobals(IsMarkedVisitor* visitor) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700939 MutexLock mu(Thread::Current(), *Locks::jni_weak_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700940 Runtime* const runtime = Runtime::Current();
941 for (auto* entry : weak_globals_) {
942 // Need to skip null here to distinguish between null entries and cleared weak ref entries.
943 if (!entry->IsNull()) {
944 // Since this is called by the GC, we don't need a read barrier.
945 mirror::Object* obj = entry->Read<kWithoutReadBarrier>();
Mathieu Chartier97509952015-07-13 14:35:43 -0700946 mirror::Object* new_obj = visitor->IsMarked(obj);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700947 if (new_obj == nullptr) {
948 new_obj = runtime->GetClearedJniWeakGlobal();
949 }
950 *entry = GcRoot<mirror::Object>(new_obj);
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -0700951 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700952 }
953}
954
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800955void JavaVMExt::TrimGlobals() {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700956 WriterMutexLock mu(Thread::Current(), *Locks::jni_globals_lock_);
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800957 globals_.Trim();
958}
959
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700960void JavaVMExt::VisitRoots(RootVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700961 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700962 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700963 globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal));
Ian Rogers68d8b422014-07-17 11:09:10 -0700964 // The weak_globals table is visited by the GC itself (because it mutates the table).
965}
966
967// JNI Invocation interface.
968
969extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800970 ScopedTrace trace(__FUNCTION__);
Ian Rogers68d8b422014-07-17 11:09:10 -0700971 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
Alex Light185d1342016-08-11 10:48:03 -0700972 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700973 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
974 return JNI_EVERSION;
975 }
976 RuntimeOptions options;
977 for (int i = 0; i < args->nOptions; ++i) {
978 JavaVMOption* option = &args->options[i];
979 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
980 }
981 bool ignore_unrecognized = args->ignoreUnrecognized;
982 if (!Runtime::Create(options, ignore_unrecognized)) {
983 return JNI_ERR;
984 }
Dimitry Ivanovc544f342016-05-09 16:26:13 -0700985
986 // Initialize native loader. This step makes sure we have
987 // everything set up before we start using JNI.
988 android::InitializeNativeLoader();
989
Ian Rogers68d8b422014-07-17 11:09:10 -0700990 Runtime* runtime = Runtime::Current();
991 bool started = runtime->Start();
992 if (!started) {
993 delete Thread::Current()->GetJniEnv();
994 delete runtime->GetJavaVM();
995 LOG(WARNING) << "CreateJavaVM failed";
996 return JNI_ERR;
997 }
Dimitry Ivanov041169f2016-04-21 16:01:24 -0700998
Ian Rogers68d8b422014-07-17 11:09:10 -0700999 *p_env = Thread::Current()->GetJniEnv();
1000 *p_vm = runtime->GetJavaVM();
1001 return JNI_OK;
1002}
1003
Ian Rogersf4d4da12014-11-11 16:10:33 -08001004extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001005 Runtime* runtime = Runtime::Current();
Ian Rogersf4d4da12014-11-11 16:10:33 -08001006 if (runtime == nullptr || buf_len == 0) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001007 *vm_count = 0;
1008 } else {
1009 *vm_count = 1;
Ian Rogersf4d4da12014-11-11 16:10:33 -08001010 vms_buf[0] = runtime->GetJavaVM();
Ian Rogers68d8b422014-07-17 11:09:10 -07001011 }
1012 return JNI_OK;
1013}
1014
1015// Historically unsupported.
1016extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
1017 return JNI_ERR;
1018}
1019
1020} // namespace art