blob: f1f9de8ef8baa676ce44313ea577d8c514031070 [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)),
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100425 globals_(kGlobalsMax, kGlobal, error_msg),
Ian Rogers68d8b422014-07-17 11:09:10 -0700426 libraries_(new Libraries),
427 unchecked_functions_(&gJniInvokeInterface),
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100428 weak_globals_(kWeakGlobalsMax, kWeakGlobal, error_msg),
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700429 allow_accessing_weak_globals_(true),
Andreas Gampe05a364c2016-10-14 13:27:12 -0700430 weak_globals_add_condition_("weak globals add condition",
431 (CHECK(Locks::jni_weak_globals_lock_ != nullptr),
432 *Locks::jni_weak_globals_lock_)),
Alex Light185d1342016-08-11 10:48:03 -0700433 env_hooks_() {
Ian Rogers68d8b422014-07-17 11:09:10 -0700434 functions = unchecked_functions_;
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800435 SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni));
Ian Rogers68d8b422014-07-17 11:09:10 -0700436}
437
438JavaVMExt::~JavaVMExt() {
439}
440
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100441// Checking "globals" and "weak_globals" usually requires locks, but we
442// don't need the locks to check for validity when constructing the
443// object. Use NO_THREAD_SAFETY_ANALYSIS for this.
444std::unique_ptr<JavaVMExt> JavaVMExt::Create(Runtime* runtime,
445 const RuntimeArgumentMap& runtime_options,
446 std::string* error_msg) NO_THREAD_SAFETY_ANALYSIS {
447 std::unique_ptr<JavaVMExt> java_vm(new JavaVMExt(runtime, runtime_options, error_msg));
448 if (java_vm && java_vm->globals_.IsValid() && java_vm->weak_globals_.IsValid()) {
449 return java_vm;
450 }
451 return nullptr;
452}
453
Alex Light185d1342016-08-11 10:48:03 -0700454jint JavaVMExt::HandleGetEnv(/*out*/void** env, jint version) {
455 for (GetEnvHook hook : env_hooks_) {
456 jint res = hook(this, env, version);
457 if (res == JNI_OK) {
458 return JNI_OK;
459 } else if (res != JNI_EVERSION) {
460 LOG(ERROR) << "Error returned from a plugin GetEnv handler! " << res;
461 return res;
462 }
463 }
464 LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version;
465 return JNI_EVERSION;
466}
467
468// Add a hook to handle getting environments from the GetEnv call.
469void JavaVMExt::AddEnvironmentHook(GetEnvHook hook) {
470 CHECK(hook != nullptr) << "environment hooks shouldn't be null!";
471 env_hooks_.push_back(hook);
472}
473
Ian Rogers68d8b422014-07-17 11:09:10 -0700474void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) {
475 Thread* self = Thread::Current();
476 ScopedObjectAccess soa(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700477 ArtMethod* current_method = self->GetCurrentMethod(nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700478
479 std::ostringstream os;
480 os << "JNI DETECTED ERROR IN APPLICATION: " << msg;
481
482 if (jni_function_name != nullptr) {
483 os << "\n in call to " << jni_function_name;
484 }
485 // TODO: is this useful given that we're about to dump the calling thread's stack?
486 if (current_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700487 os << "\n from " << current_method->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700488 }
489 os << "\n";
490 self->Dump(os);
491
492 if (check_jni_abort_hook_ != nullptr) {
493 check_jni_abort_hook_(check_jni_abort_hook_data_, os.str());
494 } else {
495 // Ensure that we get a native stack trace for this thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700496 ScopedThreadSuspension sts(self, kNative);
Ian Rogers68d8b422014-07-17 11:09:10 -0700497 LOG(FATAL) << os.str();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700498 UNREACHABLE();
Ian Rogers68d8b422014-07-17 11:09:10 -0700499 }
500}
501
502void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) {
503 std::string msg;
504 StringAppendV(&msg, fmt, ap);
505 JniAbort(jni_function_name, msg.c_str());
506}
507
508void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) {
509 va_list args;
510 va_start(args, fmt);
511 JniAbortV(jni_function_name, fmt, args);
512 va_end(args);
513}
514
Mathieu Chartiere401d142015-04-22 13:56:20 -0700515bool JavaVMExt::ShouldTrace(ArtMethod* method) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700516 // Fast where no tracing is enabled.
517 if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) {
518 return false;
519 }
520 // Perform checks based on class name.
521 StringPiece class_name(method->GetDeclaringClassDescriptor());
522 if (!trace_.empty() && class_name.find(trace_) != std::string::npos) {
523 return true;
524 }
525 if (!VLOG_IS_ON(third_party_jni)) {
526 return false;
527 }
528 // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
529 // like part of Android.
530 static const char* gBuiltInPrefixes[] = {
531 "Landroid/",
532 "Lcom/android/",
533 "Lcom/google/android/",
534 "Ldalvik/",
535 "Ljava/",
536 "Ljavax/",
537 "Llibcore/",
538 "Lorg/apache/harmony/",
539 };
540 for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) {
541 if (class_name.starts_with(gBuiltInPrefixes[i])) {
542 return false;
543 }
544 }
545 return true;
546}
547
Mathieu Chartier0795f232016-09-27 18:43:30 -0700548jobject JavaVMExt::AddGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700549 // Check for null after decoding the object to handle cleared weak globals.
550 if (obj == nullptr) {
551 return nullptr;
552 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700553 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -0700554 IndirectRef ref = globals_.Add(IRT_FIRST_SEGMENT, obj);
Ian Rogers68d8b422014-07-17 11:09:10 -0700555 return reinterpret_cast<jobject>(ref);
556}
557
Mathieu Chartier0795f232016-09-27 18:43:30 -0700558jweak JavaVMExt::AddWeakGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700559 if (obj == nullptr) {
560 return nullptr;
561 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700562 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700563 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700564 weak_globals_add_condition_.WaitHoldingLocks(self);
565 }
Mathieu Chartierf8ac97f2016-10-05 15:56:52 -0700566 IndirectRef ref = weak_globals_.Add(IRT_FIRST_SEGMENT, obj);
Ian Rogers68d8b422014-07-17 11:09:10 -0700567 return reinterpret_cast<jweak>(ref);
568}
569
570void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
571 if (obj == nullptr) {
572 return;
573 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700574 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700575 if (!globals_.Remove(IRT_FIRST_SEGMENT, obj)) {
576 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
577 << "failed to find entry";
578 }
579}
580
581void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
582 if (obj == nullptr) {
583 return;
584 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700585 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700586 if (!weak_globals_.Remove(IRT_FIRST_SEGMENT, obj)) {
587 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
588 << "failed to find entry";
589 }
590}
591
592static void ThreadEnableCheckJni(Thread* thread, void* arg) {
593 bool* check_jni = reinterpret_cast<bool*>(arg);
594 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
595}
596
597bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
598 bool old_check_jni = check_jni_;
599 check_jni_ = enabled;
600 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
601 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
602 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
603 return old_check_jni;
604}
605
606void JavaVMExt::DumpForSigQuit(std::ostream& os) {
607 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
608 if (force_copy_) {
609 os << " (with forcecopy)";
610 }
611 Thread* self = Thread::Current();
612 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700613 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700614 os << "; globals=" << globals_.Capacity();
615 }
616 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700617 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700618 if (weak_globals_.Capacity() > 0) {
619 os << " (plus " << weak_globals_.Capacity() << " weak)";
620 }
621 }
622 os << '\n';
623
624 {
625 MutexLock mu(self, *Locks::jni_libraries_lock_);
626 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
627 }
628}
629
630void JavaVMExt::DisallowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700631 CHECK(!kUseReadBarrier);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700632 Thread* const self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700633 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700634 // DisallowNewWeakGlobals is only called by CMS during the pause. It is required to have the
635 // mutator lock exclusively held so that we don't have any threads in the middle of
636 // DecodeWeakGlobal.
637 Locks::mutator_lock_->AssertExclusiveHeld(self);
638 allow_accessing_weak_globals_.StoreSequentiallyConsistent(false);
Ian Rogers68d8b422014-07-17 11:09:10 -0700639}
640
641void JavaVMExt::AllowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700642 CHECK(!kUseReadBarrier);
Ian Rogers68d8b422014-07-17 11:09:10 -0700643 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700644 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700645 allow_accessing_weak_globals_.StoreSequentiallyConsistent(true);
Ian Rogers68d8b422014-07-17 11:09:10 -0700646 weak_globals_add_condition_.Broadcast(self);
647}
648
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700649void JavaVMExt::BroadcastForNewWeakGlobals() {
650 CHECK(kUseReadBarrier);
651 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700652 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700653 weak_globals_add_condition_.Broadcast(self);
654}
655
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700656ObjPtr<mirror::Object> JavaVMExt::DecodeGlobal(IndirectRef ref) {
657 return globals_.SynchronizedGet(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700658}
659
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700660void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700661 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700662 globals_.Update(ref, result);
663}
664
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700665inline bool JavaVMExt::MayAccessWeakGlobals(Thread* self) const {
666 return MayAccessWeakGlobalsUnlocked(self);
667}
668
669inline bool JavaVMExt::MayAccessWeakGlobalsUnlocked(Thread* self) const {
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700670 DCHECK(self != nullptr);
671 return kUseReadBarrier ?
672 self->GetWeakRefAccessEnabled() :
673 allow_accessing_weak_globals_.LoadSequentiallyConsistent();
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700674}
675
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700676ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700677 // It is safe to access GetWeakRefAccessEnabled without the lock since CC uses checkpoints to call
678 // SetWeakRefAccessEnabled, and the other collectors only modify allow_accessing_weak_globals_
679 // when the mutators are paused.
680 // This only applies in the case where MayAccessWeakGlobals goes from false to true. In the other
681 // case, it may be racy, this is benign since DecodeWeakGlobalLocked does the correct behavior
682 // if MayAccessWeakGlobals is false.
Andreas Gampedc061d02016-10-24 13:19:37 -0700683 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700684 if (LIKELY(MayAccessWeakGlobalsUnlocked(self))) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700685 return weak_globals_.SynchronizedGet(ref);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700686 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700687 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700688 return DecodeWeakGlobalLocked(self, ref);
689}
690
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700691ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalLocked(Thread* self, IndirectRef ref) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700692 if (kDebugLocking) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700693 Locks::jni_weak_globals_lock_->AssertHeld(self);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700694 }
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700695 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700696 weak_globals_add_condition_.WaitHoldingLocks(self);
697 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700698 return weak_globals_.Get(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700699}
700
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700701ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalDuringShutdown(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700702 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700703 DCHECK(Runtime::Current()->IsShuttingDown(self));
704 if (self != nullptr) {
705 return DecodeWeakGlobal(self, ref);
706 }
707 // self can be null during a runtime shutdown. ~Runtime()->~ClassLinker()->DecodeWeakGlobal().
708 if (!kUseReadBarrier) {
709 DCHECK(allow_accessing_weak_globals_.LoadSequentiallyConsistent());
710 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700711 return weak_globals_.SynchronizedGet(ref);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700712}
713
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800714bool JavaVMExt::IsWeakGlobalCleared(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700715 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Andreas Gampe05a364c2016-10-14 13:27:12 -0700716 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800717 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
718 weak_globals_add_condition_.WaitHoldingLocks(self);
719 }
720 // When just checking a weak ref has been cleared, avoid triggering the read barrier in decode
721 // (DecodeWeakGlobal) so that we won't accidentally mark the object alive. Since the cleared
722 // sentinel is a non-moving object, we can compare the ref to it without the read barrier and
723 // decide if it's cleared.
724 return Runtime::Current()->IsClearedJniWeakGlobal(weak_globals_.Get<kWithoutReadBarrier>(ref));
725}
726
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700727void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700728 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700729 weak_globals_.Update(ref, result);
730}
731
Ian Rogers68d8b422014-07-17 11:09:10 -0700732void JavaVMExt::DumpReferenceTables(std::ostream& os) {
733 Thread* self = Thread::Current();
734 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700735 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700736 globals_.Dump(os);
737 }
738 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700739 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700740 weak_globals_.Dump(os);
741 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700742}
743
Mathieu Chartier598302a2015-09-23 14:52:39 -0700744void JavaVMExt::UnloadNativeLibraries() {
745 libraries_.get()->UnloadNativeLibraries();
746}
747
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800748bool JavaVMExt::LoadNativeLibrary(JNIEnv* env,
749 const std::string& path,
750 jobject class_loader,
751 jstring library_path,
752 std::string* error_msg) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700753 error_msg->clear();
754
755 // See if we've already loaded this library. If we have, and the class loader
756 // matches, return successfully without doing anything.
757 // TODO: for better results we should canonicalize the pathname (or even compare
758 // inodes). This implementation is fine if everybody is using System.loadLibrary.
759 SharedLibrary* library;
760 Thread* self = Thread::Current();
761 {
762 // TODO: move the locking (and more of this logic) into Libraries.
763 MutexLock mu(self, *Locks::jni_libraries_lock_);
764 library = libraries_->Get(path);
765 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800766 void* class_loader_allocator = nullptr;
767 {
768 ScopedObjectAccess soa(env);
769 // As the incoming class loader is reachable/alive during the call of this function,
770 // it's okay to decode it without worrying about unexpectedly marking it alive.
Mathieu Chartier0795f232016-09-27 18:43:30 -0700771 ObjPtr<mirror::ClassLoader> loader = soa.Decode<mirror::ClassLoader>(class_loader);
Andreas Gampe2d48e532016-06-17 12:46:14 -0700772
773 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700774 if (class_linker->IsBootClassLoader(soa, loader.Ptr())) {
Andreas Gampe2d48e532016-06-17 12:46:14 -0700775 loader = nullptr;
776 class_loader = nullptr;
777 }
778
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700779 class_loader_allocator = class_linker->GetAllocatorForClassLoader(loader.Ptr());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800780 CHECK(class_loader_allocator != nullptr);
781 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700782 if (library != nullptr) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800783 // Use the allocator pointers for class loader equality to avoid unnecessary weak root decode.
784 if (library->GetClassLoaderAllocator() != class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700785 // The library will be associated with class_loader. The JNI
786 // spec says we can't load the same library into more than one
787 // class loader.
788 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
789 "ClassLoader %p; can't open in ClassLoader %p",
790 path.c_str(), library->GetClassLoader(), class_loader);
791 LOG(WARNING) << error_msg;
792 return false;
793 }
794 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
795 << " ClassLoader " << class_loader << "]";
796 if (!library->CheckOnLoadResult()) {
797 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
798 "to load \"%s\"", path.c_str());
799 return false;
800 }
801 return true;
802 }
803
804 // Open the shared library. Because we're using a full path, the system
805 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
806 // resolve this library's dependencies though.)
807
808 // Failures here are expected when java.library.path has several entries
809 // and we have to hunt for the lib.
810
811 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
812 // class unloading. Libraries will only be unloaded when the reference count (incremented by
813 // dlopen) becomes zero from dlclose.
814
815 Locks::mutator_lock_->AssertNotHeld(self);
816 const char* path_str = path.empty() ? nullptr : path.c_str();
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800817 void* handle = android::OpenNativeLibrary(env,
818 runtime_->GetTargetSdkVersion(),
819 path_str,
820 class_loader,
821 library_path);
822
Ian Rogers68d8b422014-07-17 11:09:10 -0700823 bool needs_native_bridge = false;
824 if (handle == nullptr) {
Calin Juravlec8423522014-08-12 20:55:20 +0100825 if (android::NativeBridgeIsSupported(path_str)) {
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700826 handle = android::NativeBridgeLoadLibrary(path_str, RTLD_NOW);
Ian Rogers68d8b422014-07-17 11:09:10 -0700827 needs_native_bridge = true;
828 }
829 }
830
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700831 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]";
Ian Rogers68d8b422014-07-17 11:09:10 -0700832
833 if (handle == nullptr) {
834 *error_msg = dlerror();
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700835 VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700836 return false;
837 }
838
839 if (env->ExceptionCheck() == JNI_TRUE) {
840 LOG(ERROR) << "Unexpected exception:";
841 env->ExceptionDescribe();
842 env->ExceptionClear();
843 }
844 // Create a new entry.
845 // TODO: move the locking (and more of this logic) into Libraries.
846 bool created_library = false;
847 {
848 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
849 std::unique_ptr<SharedLibrary> new_library(
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800850 new SharedLibrary(env, self, path, handle, class_loader, class_loader_allocator));
Ian Rogers68d8b422014-07-17 11:09:10 -0700851 MutexLock mu(self, *Locks::jni_libraries_lock_);
852 library = libraries_->Get(path);
853 if (library == nullptr) { // We won race to get libraries_lock.
854 library = new_library.release();
855 libraries_->Put(path, library);
856 created_library = true;
857 }
858 }
859 if (!created_library) {
860 LOG(INFO) << "WOW: we lost a race to add shared library: "
861 << "\"" << path << "\" ClassLoader=" << class_loader;
862 return library->CheckOnLoadResult();
863 }
864 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
865
866 bool was_successful = false;
867 void* sym;
868 if (needs_native_bridge) {
869 library->SetNeedsNativeBridge();
Ian Rogers68d8b422014-07-17 11:09:10 -0700870 }
Mathieu Chartier598302a2015-09-23 14:52:39 -0700871 sym = library->FindSymbol("JNI_OnLoad", nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700872 if (sym == nullptr) {
873 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
874 was_successful = true;
875 } else {
876 // Call JNI_OnLoad. We have to override the current class
877 // loader, which will always be "null" since the stuff at the
878 // top of the stack is around Runtime.loadLibrary(). (See
879 // the comments in the JNI FindClass function.)
880 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
881 self->SetClassLoaderOverride(class_loader);
882
883 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
884 typedef int (*JNI_OnLoadFn)(JavaVM*, void*);
885 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
886 int version = (*jni_on_load)(this, nullptr);
887
Mathieu Chartierd0004802014-10-15 16:59:47 -0700888 if (runtime_->GetTargetSdkVersion() != 0 && runtime_->GetTargetSdkVersion() <= 21) {
889 fault_manager.EnsureArtActionInFrontOfSignalChain();
890 }
891
Ian Rogers68d8b422014-07-17 11:09:10 -0700892 self->SetClassLoaderOverride(old_class_loader.get());
893
894 if (version == JNI_ERR) {
895 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
Alex Light185d1342016-08-11 10:48:03 -0700896 } else if (JavaVMExt::IsBadJniVersion(version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700897 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
898 path.c_str(), version);
899 // It's unwise to call dlclose() here, but we can mark it
900 // as bad and ensure that future load attempts will fail.
901 // We don't know how far JNI_OnLoad got, so there could
902 // be some partially-initialized stuff accessible through
903 // newly-registered native method calls. We could try to
904 // unregister them, but that doesn't seem worthwhile.
905 } else {
906 was_successful = true;
907 }
908 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
909 << " from JNI_OnLoad in \"" << path << "\"]";
910 }
911
912 library->SetResult(was_successful);
913 return was_successful;
914}
915
Mathieu Chartiere401d142015-04-22 13:56:20 -0700916void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700917 CHECK(m->IsNative());
918 mirror::Class* c = m->GetDeclaringClass();
919 // If this is a static method, it could be called before the class has been initialized.
David Sehr709b0702016-10-13 09:12:37 -0700920 CHECK(c->IsInitializing()) << c->GetStatus() << " " << m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700921 std::string detail;
922 void* native_method;
923 Thread* self = Thread::Current();
924 {
925 MutexLock mu(self, *Locks::jni_libraries_lock_);
926 native_method = libraries_->FindNativeMethod(m, detail);
927 }
928 // Throwing can cause libraries_lock to be reacquired.
929 if (native_method == nullptr) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000930 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
Ian Rogers68d8b422014-07-17 11:09:10 -0700931 }
932 return native_method;
933}
934
Mathieu Chartier97509952015-07-13 14:35:43 -0700935void JavaVMExt::SweepJniWeakGlobals(IsMarkedVisitor* visitor) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700936 MutexLock mu(Thread::Current(), *Locks::jni_weak_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700937 Runtime* const runtime = Runtime::Current();
938 for (auto* entry : weak_globals_) {
939 // Need to skip null here to distinguish between null entries and cleared weak ref entries.
940 if (!entry->IsNull()) {
941 // Since this is called by the GC, we don't need a read barrier.
942 mirror::Object* obj = entry->Read<kWithoutReadBarrier>();
Mathieu Chartier97509952015-07-13 14:35:43 -0700943 mirror::Object* new_obj = visitor->IsMarked(obj);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700944 if (new_obj == nullptr) {
945 new_obj = runtime->GetClearedJniWeakGlobal();
946 }
947 *entry = GcRoot<mirror::Object>(new_obj);
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -0700948 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700949 }
950}
951
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800952void JavaVMExt::TrimGlobals() {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700953 WriterMutexLock mu(Thread::Current(), *Locks::jni_globals_lock_);
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800954 globals_.Trim();
955}
956
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700957void JavaVMExt::VisitRoots(RootVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700958 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700959 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700960 globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal));
Ian Rogers68d8b422014-07-17 11:09:10 -0700961 // The weak_globals table is visited by the GC itself (because it mutates the table).
962}
963
964// JNI Invocation interface.
965
966extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800967 ScopedTrace trace(__FUNCTION__);
Ian Rogers68d8b422014-07-17 11:09:10 -0700968 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
Alex Light185d1342016-08-11 10:48:03 -0700969 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700970 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
971 return JNI_EVERSION;
972 }
973 RuntimeOptions options;
974 for (int i = 0; i < args->nOptions; ++i) {
975 JavaVMOption* option = &args->options[i];
976 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
977 }
978 bool ignore_unrecognized = args->ignoreUnrecognized;
979 if (!Runtime::Create(options, ignore_unrecognized)) {
980 return JNI_ERR;
981 }
Dimitry Ivanovc544f342016-05-09 16:26:13 -0700982
983 // Initialize native loader. This step makes sure we have
984 // everything set up before we start using JNI.
985 android::InitializeNativeLoader();
986
Ian Rogers68d8b422014-07-17 11:09:10 -0700987 Runtime* runtime = Runtime::Current();
988 bool started = runtime->Start();
989 if (!started) {
990 delete Thread::Current()->GetJniEnv();
991 delete runtime->GetJavaVM();
992 LOG(WARNING) << "CreateJavaVM failed";
993 return JNI_ERR;
994 }
Dimitry Ivanov041169f2016-04-21 16:01:24 -0700995
Ian Rogers68d8b422014-07-17 11:09:10 -0700996 *p_env = Thread::Current()->GetJniEnv();
997 *p_vm = runtime->GetJavaVM();
998 return JNI_OK;
999}
1000
Ian Rogersf4d4da12014-11-11 16:10:33 -08001001extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001002 Runtime* runtime = Runtime::Current();
Ian Rogersf4d4da12014-11-11 16:10:33 -08001003 if (runtime == nullptr || buf_len == 0) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001004 *vm_count = 0;
1005 } else {
1006 *vm_count = 1;
Ian Rogersf4d4da12014-11-11 16:10:33 -08001007 vms_buf[0] = runtime->GetJavaVM();
Ian Rogers68d8b422014-07-17 11:09:10 -07001008 }
1009 return JNI_OK;
1010}
1011
1012// Historically unsupported.
1013extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
1014 return JNI_ERR;
1015}
1016
1017} // namespace art