blob: 7285b9a96550e15463d9299dcec8b1d366fca8af [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
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800414JavaVMExt::JavaVMExt(Runtime* runtime, const RuntimeArgumentMap& runtime_options)
Ian Rogers68d8b422014-07-17 11:09:10 -0700415 : runtime_(runtime),
416 check_jni_abort_hook_(nullptr),
417 check_jni_abort_hook_data_(nullptr),
418 check_jni_(false), // Initialized properly in the constructor body below.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800419 force_copy_(runtime_options.Exists(RuntimeArgumentMap::JniOptsForceCopy)),
420 tracing_enabled_(runtime_options.Exists(RuntimeArgumentMap::JniTrace)
421 || VLOG_IS_ON(third_party_jni)),
422 trace_(runtime_options.GetOrDefault(RuntimeArgumentMap::JniTrace)),
Andreas Gampea8e3b862016-10-17 20:12:52 -0700423 globals_(kGlobalsMax, kGlobal),
Ian Rogers68d8b422014-07-17 11:09:10 -0700424 libraries_(new Libraries),
425 unchecked_functions_(&gJniInvokeInterface),
Andreas Gampea8e3b862016-10-17 20:12:52 -0700426 weak_globals_(kWeakGlobalsMax, kWeakGlobal),
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700427 allow_accessing_weak_globals_(true),
Andreas Gampe05a364c2016-10-14 13:27:12 -0700428 weak_globals_add_condition_("weak globals add condition",
429 (CHECK(Locks::jni_weak_globals_lock_ != nullptr),
430 *Locks::jni_weak_globals_lock_)),
Alex Light185d1342016-08-11 10:48:03 -0700431 env_hooks_() {
Ian Rogers68d8b422014-07-17 11:09:10 -0700432 functions = unchecked_functions_;
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800433 SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni));
Ian Rogers68d8b422014-07-17 11:09:10 -0700434}
435
436JavaVMExt::~JavaVMExt() {
437}
438
Alex Light185d1342016-08-11 10:48:03 -0700439jint JavaVMExt::HandleGetEnv(/*out*/void** env, jint version) {
440 for (GetEnvHook hook : env_hooks_) {
441 jint res = hook(this, env, version);
442 if (res == JNI_OK) {
443 return JNI_OK;
444 } else if (res != JNI_EVERSION) {
445 LOG(ERROR) << "Error returned from a plugin GetEnv handler! " << res;
446 return res;
447 }
448 }
449 LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version;
450 return JNI_EVERSION;
451}
452
453// Add a hook to handle getting environments from the GetEnv call.
454void JavaVMExt::AddEnvironmentHook(GetEnvHook hook) {
455 CHECK(hook != nullptr) << "environment hooks shouldn't be null!";
456 env_hooks_.push_back(hook);
457}
458
Ian Rogers68d8b422014-07-17 11:09:10 -0700459void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) {
460 Thread* self = Thread::Current();
461 ScopedObjectAccess soa(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700462 ArtMethod* current_method = self->GetCurrentMethod(nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700463
464 std::ostringstream os;
465 os << "JNI DETECTED ERROR IN APPLICATION: " << msg;
466
467 if (jni_function_name != nullptr) {
468 os << "\n in call to " << jni_function_name;
469 }
470 // TODO: is this useful given that we're about to dump the calling thread's stack?
471 if (current_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700472 os << "\n from " << current_method->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700473 }
474 os << "\n";
475 self->Dump(os);
476
477 if (check_jni_abort_hook_ != nullptr) {
478 check_jni_abort_hook_(check_jni_abort_hook_data_, os.str());
479 } else {
480 // Ensure that we get a native stack trace for this thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700481 ScopedThreadSuspension sts(self, kNative);
Ian Rogers68d8b422014-07-17 11:09:10 -0700482 LOG(FATAL) << os.str();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700483 UNREACHABLE();
Ian Rogers68d8b422014-07-17 11:09:10 -0700484 }
485}
486
487void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) {
488 std::string msg;
489 StringAppendV(&msg, fmt, ap);
490 JniAbort(jni_function_name, msg.c_str());
491}
492
493void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) {
494 va_list args;
495 va_start(args, fmt);
496 JniAbortV(jni_function_name, fmt, args);
497 va_end(args);
498}
499
Mathieu Chartiere401d142015-04-22 13:56:20 -0700500bool JavaVMExt::ShouldTrace(ArtMethod* method) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700501 // Fast where no tracing is enabled.
502 if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) {
503 return false;
504 }
505 // Perform checks based on class name.
506 StringPiece class_name(method->GetDeclaringClassDescriptor());
507 if (!trace_.empty() && class_name.find(trace_) != std::string::npos) {
508 return true;
509 }
510 if (!VLOG_IS_ON(third_party_jni)) {
511 return false;
512 }
513 // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
514 // like part of Android.
515 static const char* gBuiltInPrefixes[] = {
516 "Landroid/",
517 "Lcom/android/",
518 "Lcom/google/android/",
519 "Ldalvik/",
520 "Ljava/",
521 "Ljavax/",
522 "Llibcore/",
523 "Lorg/apache/harmony/",
524 };
525 for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) {
526 if (class_name.starts_with(gBuiltInPrefixes[i])) {
527 return false;
528 }
529 }
530 return true;
531}
532
Mathieu Chartier0795f232016-09-27 18:43:30 -0700533jobject JavaVMExt::AddGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700534 // Check for null after decoding the object to handle cleared weak globals.
535 if (obj == nullptr) {
536 return nullptr;
537 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700538 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -0700539 IndirectRef ref = globals_.Add(IRT_FIRST_SEGMENT, obj);
Ian Rogers68d8b422014-07-17 11:09:10 -0700540 return reinterpret_cast<jobject>(ref);
541}
542
Mathieu Chartier0795f232016-09-27 18:43:30 -0700543jweak JavaVMExt::AddWeakGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700544 if (obj == nullptr) {
545 return nullptr;
546 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700547 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700548 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700549 weak_globals_add_condition_.WaitHoldingLocks(self);
550 }
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -0700551 IndirectRef ref = weak_globals_.Add(IRT_FIRST_SEGMENT, obj);
Ian Rogers68d8b422014-07-17 11:09:10 -0700552 return reinterpret_cast<jweak>(ref);
553}
554
555void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
556 if (obj == nullptr) {
557 return;
558 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700559 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700560 if (!globals_.Remove(IRT_FIRST_SEGMENT, obj)) {
561 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
562 << "failed to find entry";
563 }
564}
565
566void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
567 if (obj == nullptr) {
568 return;
569 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700570 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700571 if (!weak_globals_.Remove(IRT_FIRST_SEGMENT, obj)) {
572 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
573 << "failed to find entry";
574 }
575}
576
577static void ThreadEnableCheckJni(Thread* thread, void* arg) {
578 bool* check_jni = reinterpret_cast<bool*>(arg);
579 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
580}
581
582bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
583 bool old_check_jni = check_jni_;
584 check_jni_ = enabled;
585 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
586 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
587 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
588 return old_check_jni;
589}
590
591void JavaVMExt::DumpForSigQuit(std::ostream& os) {
592 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
593 if (force_copy_) {
594 os << " (with forcecopy)";
595 }
596 Thread* self = Thread::Current();
597 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700598 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700599 os << "; globals=" << globals_.Capacity();
600 }
601 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700602 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700603 if (weak_globals_.Capacity() > 0) {
604 os << " (plus " << weak_globals_.Capacity() << " weak)";
605 }
606 }
607 os << '\n';
608
609 {
610 MutexLock mu(self, *Locks::jni_libraries_lock_);
611 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
612 }
613}
614
615void JavaVMExt::DisallowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700616 CHECK(!kUseReadBarrier);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700617 Thread* const self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700618 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700619 // DisallowNewWeakGlobals is only called by CMS during the pause. It is required to have the
620 // mutator lock exclusively held so that we don't have any threads in the middle of
621 // DecodeWeakGlobal.
622 Locks::mutator_lock_->AssertExclusiveHeld(self);
623 allow_accessing_weak_globals_.StoreSequentiallyConsistent(false);
Ian Rogers68d8b422014-07-17 11:09:10 -0700624}
625
626void JavaVMExt::AllowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700627 CHECK(!kUseReadBarrier);
Ian Rogers68d8b422014-07-17 11:09:10 -0700628 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700629 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700630 allow_accessing_weak_globals_.StoreSequentiallyConsistent(true);
Ian Rogers68d8b422014-07-17 11:09:10 -0700631 weak_globals_add_condition_.Broadcast(self);
632}
633
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700634void JavaVMExt::BroadcastForNewWeakGlobals() {
635 CHECK(kUseReadBarrier);
636 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700637 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700638 weak_globals_add_condition_.Broadcast(self);
639}
640
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700641ObjPtr<mirror::Object> JavaVMExt::DecodeGlobal(IndirectRef ref) {
642 return globals_.SynchronizedGet(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700643}
644
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700645void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700646 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700647 globals_.Update(ref, result);
648}
649
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700650inline bool JavaVMExt::MayAccessWeakGlobals(Thread* self) const {
651 return MayAccessWeakGlobalsUnlocked(self);
652}
653
654inline bool JavaVMExt::MayAccessWeakGlobalsUnlocked(Thread* self) const {
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700655 DCHECK(self != nullptr);
656 return kUseReadBarrier ?
657 self->GetWeakRefAccessEnabled() :
658 allow_accessing_weak_globals_.LoadSequentiallyConsistent();
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700659}
660
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700661ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700662 // It is safe to access GetWeakRefAccessEnabled without the lock since CC uses checkpoints to call
663 // SetWeakRefAccessEnabled, and the other collectors only modify allow_accessing_weak_globals_
664 // when the mutators are paused.
665 // This only applies in the case where MayAccessWeakGlobals goes from false to true. In the other
666 // case, it may be racy, this is benign since DecodeWeakGlobalLocked does the correct behavior
667 // if MayAccessWeakGlobals is false.
Mathieu Chartier9b1c71e2015-09-02 18:51:54 -0700668 DCHECK_EQ(GetIndirectRefKind(ref), kWeakGlobal);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700669 if (LIKELY(MayAccessWeakGlobalsUnlocked(self))) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700670 return weak_globals_.SynchronizedGet(ref);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700671 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700672 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700673 return DecodeWeakGlobalLocked(self, ref);
674}
675
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700676ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalLocked(Thread* self, IndirectRef ref) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700677 if (kDebugLocking) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700678 Locks::jni_weak_globals_lock_->AssertHeld(self);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700679 }
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700680 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700681 weak_globals_add_condition_.WaitHoldingLocks(self);
682 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700683 return weak_globals_.Get(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700684}
685
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700686ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalDuringShutdown(Thread* self, IndirectRef ref) {
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700687 DCHECK_EQ(GetIndirectRefKind(ref), kWeakGlobal);
688 DCHECK(Runtime::Current()->IsShuttingDown(self));
689 if (self != nullptr) {
690 return DecodeWeakGlobal(self, ref);
691 }
692 // self can be null during a runtime shutdown. ~Runtime()->~ClassLinker()->DecodeWeakGlobal().
693 if (!kUseReadBarrier) {
694 DCHECK(allow_accessing_weak_globals_.LoadSequentiallyConsistent());
695 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700696 return weak_globals_.SynchronizedGet(ref);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700697}
698
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800699bool JavaVMExt::IsWeakGlobalCleared(Thread* self, IndirectRef ref) {
700 DCHECK_EQ(GetIndirectRefKind(ref), kWeakGlobal);
Andreas Gampe05a364c2016-10-14 13:27:12 -0700701 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800702 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
703 weak_globals_add_condition_.WaitHoldingLocks(self);
704 }
705 // When just checking a weak ref has been cleared, avoid triggering the read barrier in decode
706 // (DecodeWeakGlobal) so that we won't accidentally mark the object alive. Since the cleared
707 // sentinel is a non-moving object, we can compare the ref to it without the read barrier and
708 // decide if it's cleared.
709 return Runtime::Current()->IsClearedJniWeakGlobal(weak_globals_.Get<kWithoutReadBarrier>(ref));
710}
711
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700712void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700713 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700714 weak_globals_.Update(ref, result);
715}
716
Ian Rogers68d8b422014-07-17 11:09:10 -0700717void JavaVMExt::DumpReferenceTables(std::ostream& os) {
718 Thread* self = Thread::Current();
719 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700720 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700721 globals_.Dump(os);
722 }
723 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700724 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700725 weak_globals_.Dump(os);
726 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700727}
728
Mathieu Chartier598302a2015-09-23 14:52:39 -0700729void JavaVMExt::UnloadNativeLibraries() {
730 libraries_.get()->UnloadNativeLibraries();
731}
732
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800733bool JavaVMExt::LoadNativeLibrary(JNIEnv* env,
734 const std::string& path,
735 jobject class_loader,
736 jstring library_path,
737 std::string* error_msg) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700738 error_msg->clear();
739
740 // See if we've already loaded this library. If we have, and the class loader
741 // matches, return successfully without doing anything.
742 // TODO: for better results we should canonicalize the pathname (or even compare
743 // inodes). This implementation is fine if everybody is using System.loadLibrary.
744 SharedLibrary* library;
745 Thread* self = Thread::Current();
746 {
747 // TODO: move the locking (and more of this logic) into Libraries.
748 MutexLock mu(self, *Locks::jni_libraries_lock_);
749 library = libraries_->Get(path);
750 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800751 void* class_loader_allocator = nullptr;
752 {
753 ScopedObjectAccess soa(env);
754 // As the incoming class loader is reachable/alive during the call of this function,
755 // it's okay to decode it without worrying about unexpectedly marking it alive.
Mathieu Chartier0795f232016-09-27 18:43:30 -0700756 ObjPtr<mirror::ClassLoader> loader = soa.Decode<mirror::ClassLoader>(class_loader);
Andreas Gampe2d48e532016-06-17 12:46:14 -0700757
758 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700759 if (class_linker->IsBootClassLoader(soa, loader.Ptr())) {
Andreas Gampe2d48e532016-06-17 12:46:14 -0700760 loader = nullptr;
761 class_loader = nullptr;
762 }
763
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700764 class_loader_allocator = class_linker->GetAllocatorForClassLoader(loader.Ptr());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800765 CHECK(class_loader_allocator != nullptr);
766 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700767 if (library != nullptr) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800768 // Use the allocator pointers for class loader equality to avoid unnecessary weak root decode.
769 if (library->GetClassLoaderAllocator() != class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700770 // The library will be associated with class_loader. The JNI
771 // spec says we can't load the same library into more than one
772 // class loader.
773 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
774 "ClassLoader %p; can't open in ClassLoader %p",
775 path.c_str(), library->GetClassLoader(), class_loader);
776 LOG(WARNING) << error_msg;
777 return false;
778 }
779 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
780 << " ClassLoader " << class_loader << "]";
781 if (!library->CheckOnLoadResult()) {
782 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
783 "to load \"%s\"", path.c_str());
784 return false;
785 }
786 return true;
787 }
788
789 // Open the shared library. Because we're using a full path, the system
790 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
791 // resolve this library's dependencies though.)
792
793 // Failures here are expected when java.library.path has several entries
794 // and we have to hunt for the lib.
795
796 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
797 // class unloading. Libraries will only be unloaded when the reference count (incremented by
798 // dlopen) becomes zero from dlclose.
799
800 Locks::mutator_lock_->AssertNotHeld(self);
801 const char* path_str = path.empty() ? nullptr : path.c_str();
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800802 void* handle = android::OpenNativeLibrary(env,
803 runtime_->GetTargetSdkVersion(),
804 path_str,
805 class_loader,
806 library_path);
807
Ian Rogers68d8b422014-07-17 11:09:10 -0700808 bool needs_native_bridge = false;
809 if (handle == nullptr) {
Calin Juravlec8423522014-08-12 20:55:20 +0100810 if (android::NativeBridgeIsSupported(path_str)) {
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700811 handle = android::NativeBridgeLoadLibrary(path_str, RTLD_NOW);
Ian Rogers68d8b422014-07-17 11:09:10 -0700812 needs_native_bridge = true;
813 }
814 }
815
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700816 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]";
Ian Rogers68d8b422014-07-17 11:09:10 -0700817
818 if (handle == nullptr) {
819 *error_msg = dlerror();
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700820 VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700821 return false;
822 }
823
824 if (env->ExceptionCheck() == JNI_TRUE) {
825 LOG(ERROR) << "Unexpected exception:";
826 env->ExceptionDescribe();
827 env->ExceptionClear();
828 }
829 // Create a new entry.
830 // TODO: move the locking (and more of this logic) into Libraries.
831 bool created_library = false;
832 {
833 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
834 std::unique_ptr<SharedLibrary> new_library(
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800835 new SharedLibrary(env, self, path, handle, class_loader, class_loader_allocator));
Ian Rogers68d8b422014-07-17 11:09:10 -0700836 MutexLock mu(self, *Locks::jni_libraries_lock_);
837 library = libraries_->Get(path);
838 if (library == nullptr) { // We won race to get libraries_lock.
839 library = new_library.release();
840 libraries_->Put(path, library);
841 created_library = true;
842 }
843 }
844 if (!created_library) {
845 LOG(INFO) << "WOW: we lost a race to add shared library: "
846 << "\"" << path << "\" ClassLoader=" << class_loader;
847 return library->CheckOnLoadResult();
848 }
849 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
850
851 bool was_successful = false;
852 void* sym;
853 if (needs_native_bridge) {
854 library->SetNeedsNativeBridge();
Ian Rogers68d8b422014-07-17 11:09:10 -0700855 }
Mathieu Chartier598302a2015-09-23 14:52:39 -0700856 sym = library->FindSymbol("JNI_OnLoad", nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700857 if (sym == nullptr) {
858 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
859 was_successful = true;
860 } else {
861 // Call JNI_OnLoad. We have to override the current class
862 // loader, which will always be "null" since the stuff at the
863 // top of the stack is around Runtime.loadLibrary(). (See
864 // the comments in the JNI FindClass function.)
865 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
866 self->SetClassLoaderOverride(class_loader);
867
868 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
869 typedef int (*JNI_OnLoadFn)(JavaVM*, void*);
870 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
871 int version = (*jni_on_load)(this, nullptr);
872
Mathieu Chartierd0004802014-10-15 16:59:47 -0700873 if (runtime_->GetTargetSdkVersion() != 0 && runtime_->GetTargetSdkVersion() <= 21) {
874 fault_manager.EnsureArtActionInFrontOfSignalChain();
875 }
876
Ian Rogers68d8b422014-07-17 11:09:10 -0700877 self->SetClassLoaderOverride(old_class_loader.get());
878
879 if (version == JNI_ERR) {
880 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
Alex Light185d1342016-08-11 10:48:03 -0700881 } else if (JavaVMExt::IsBadJniVersion(version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700882 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
883 path.c_str(), version);
884 // It's unwise to call dlclose() here, but we can mark it
885 // as bad and ensure that future load attempts will fail.
886 // We don't know how far JNI_OnLoad got, so there could
887 // be some partially-initialized stuff accessible through
888 // newly-registered native method calls. We could try to
889 // unregister them, but that doesn't seem worthwhile.
890 } else {
891 was_successful = true;
892 }
893 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
894 << " from JNI_OnLoad in \"" << path << "\"]";
895 }
896
897 library->SetResult(was_successful);
898 return was_successful;
899}
900
Mathieu Chartiere401d142015-04-22 13:56:20 -0700901void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700902 CHECK(m->IsNative());
903 mirror::Class* c = m->GetDeclaringClass();
904 // If this is a static method, it could be called before the class has been initialized.
David Sehr709b0702016-10-13 09:12:37 -0700905 CHECK(c->IsInitializing()) << c->GetStatus() << " " << m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700906 std::string detail;
907 void* native_method;
908 Thread* self = Thread::Current();
909 {
910 MutexLock mu(self, *Locks::jni_libraries_lock_);
911 native_method = libraries_->FindNativeMethod(m, detail);
912 }
913 // Throwing can cause libraries_lock to be reacquired.
914 if (native_method == nullptr) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000915 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
Ian Rogers68d8b422014-07-17 11:09:10 -0700916 }
917 return native_method;
918}
919
Mathieu Chartier97509952015-07-13 14:35:43 -0700920void JavaVMExt::SweepJniWeakGlobals(IsMarkedVisitor* visitor) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700921 MutexLock mu(Thread::Current(), *Locks::jni_weak_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700922 Runtime* const runtime = Runtime::Current();
923 for (auto* entry : weak_globals_) {
924 // Need to skip null here to distinguish between null entries and cleared weak ref entries.
925 if (!entry->IsNull()) {
926 // Since this is called by the GC, we don't need a read barrier.
927 mirror::Object* obj = entry->Read<kWithoutReadBarrier>();
Mathieu Chartier97509952015-07-13 14:35:43 -0700928 mirror::Object* new_obj = visitor->IsMarked(obj);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700929 if (new_obj == nullptr) {
930 new_obj = runtime->GetClearedJniWeakGlobal();
931 }
932 *entry = GcRoot<mirror::Object>(new_obj);
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -0700933 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700934 }
935}
936
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800937void JavaVMExt::TrimGlobals() {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700938 WriterMutexLock mu(Thread::Current(), *Locks::jni_globals_lock_);
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800939 globals_.Trim();
940}
941
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700942void JavaVMExt::VisitRoots(RootVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700943 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700944 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700945 globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal));
Ian Rogers68d8b422014-07-17 11:09:10 -0700946 // The weak_globals table is visited by the GC itself (because it mutates the table).
947}
948
949// JNI Invocation interface.
950
951extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800952 ScopedTrace trace(__FUNCTION__);
Ian Rogers68d8b422014-07-17 11:09:10 -0700953 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
Alex Light185d1342016-08-11 10:48:03 -0700954 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700955 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
956 return JNI_EVERSION;
957 }
958 RuntimeOptions options;
959 for (int i = 0; i < args->nOptions; ++i) {
960 JavaVMOption* option = &args->options[i];
961 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
962 }
963 bool ignore_unrecognized = args->ignoreUnrecognized;
964 if (!Runtime::Create(options, ignore_unrecognized)) {
965 return JNI_ERR;
966 }
Dimitry Ivanovc544f342016-05-09 16:26:13 -0700967
968 // Initialize native loader. This step makes sure we have
969 // everything set up before we start using JNI.
970 android::InitializeNativeLoader();
971
Ian Rogers68d8b422014-07-17 11:09:10 -0700972 Runtime* runtime = Runtime::Current();
973 bool started = runtime->Start();
974 if (!started) {
975 delete Thread::Current()->GetJniEnv();
976 delete runtime->GetJavaVM();
977 LOG(WARNING) << "CreateJavaVM failed";
978 return JNI_ERR;
979 }
Dimitry Ivanov041169f2016-04-21 16:01:24 -0700980
Ian Rogers68d8b422014-07-17 11:09:10 -0700981 *p_env = Thread::Current()->GetJniEnv();
982 *p_vm = runtime->GetJavaVM();
983 return JNI_OK;
984}
985
Ian Rogersf4d4da12014-11-11 16:10:33 -0800986extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700987 Runtime* runtime = Runtime::Current();
Ian Rogersf4d4da12014-11-11 16:10:33 -0800988 if (runtime == nullptr || buf_len == 0) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700989 *vm_count = 0;
990 } else {
991 *vm_count = 1;
Ian Rogersf4d4da12014-11-11 16:10:33 -0800992 vms_buf[0] = runtime->GetJavaVM();
Ian Rogers68d8b422014-07-17 11:09:10 -0700993 }
994 return JNI_OK;
995}
996
997// Historically unsupported.
998extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
999 return JNI_ERR;
1000}
1001
1002} // namespace art