blob: 8e76aeb7cd1bd91754e397dfd5543a0e60e3aa41 [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,
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080057 bool needs_native_bridge, jobject class_loader, void* class_loader_allocator)
Ian Rogers68d8b422014-07-17 11:09:10 -070058 : path_(path),
59 handle_(handle),
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080060 needs_native_bridge_(needs_native_bridge),
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
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080076 android::CloseNativeLibrary(handle_, needs_native_bridge_);
Ian Rogers68d8b422014-07-17 11:09:10 -070077 }
78
Mathieu Chartier598302a2015-09-23 14:52:39 -070079 jweak GetClassLoader() const {
Ian Rogers68d8b422014-07-17 11:09:10 -070080 return class_loader_;
81 }
82
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080083 const void* GetClassLoaderAllocator() const {
84 return class_loader_allocator_;
85 }
86
Ian Rogers68d8b422014-07-17 11:09:10 -070087 const std::string& GetPath() const {
88 return path_;
89 }
90
91 /*
92 * Check the result of an earlier call to JNI_OnLoad on this library.
93 * If the call has not yet finished in another thread, wait for it.
94 */
95 bool CheckOnLoadResult()
Mathieu Chartier90443472015-07-16 20:32:27 -070096 REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -070097 Thread* self = Thread::Current();
98 bool okay;
99 {
100 MutexLock mu(self, jni_on_load_lock_);
101
102 if (jni_on_load_thread_id_ == self->GetThreadId()) {
103 // Check this so we don't end up waiting for ourselves. We need to return "true" so the
104 // caller can continue.
105 LOG(INFO) << *self << " recursive attempt to load library " << "\"" << path_ << "\"";
106 okay = true;
107 } else {
108 while (jni_on_load_result_ == kPending) {
109 VLOG(jni) << "[" << *self << " waiting for \"" << path_ << "\" " << "JNI_OnLoad...]";
110 jni_on_load_cond_.Wait(self);
111 }
112
113 okay = (jni_on_load_result_ == kOkay);
114 VLOG(jni) << "[Earlier JNI_OnLoad for \"" << path_ << "\" "
115 << (okay ? "succeeded" : "failed") << "]";
116 }
117 }
118 return okay;
119 }
120
Mathieu Chartier90443472015-07-16 20:32:27 -0700121 void SetResult(bool result) REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700122 Thread* self = Thread::Current();
123 MutexLock mu(self, jni_on_load_lock_);
124
125 jni_on_load_result_ = result ? kOkay : kFailed;
126 jni_on_load_thread_id_ = 0;
127
128 // Broadcast a wakeup to anybody sleeping on the condition variable.
129 jni_on_load_cond_.Broadcast(self);
130 }
131
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800132 void SetNeedsNativeBridge(bool needs) {
133 needs_native_bridge_ = needs;
Ian Rogers68d8b422014-07-17 11:09:10 -0700134 }
135
136 bool NeedsNativeBridge() const {
137 return needs_native_bridge_;
138 }
139
Mathieu Chartier598302a2015-09-23 14:52:39 -0700140 void* FindSymbol(const std::string& symbol_name, const char* shorty = nullptr) {
141 return NeedsNativeBridge()
142 ? FindSymbolWithNativeBridge(symbol_name.c_str(), shorty)
143 : FindSymbolWithoutNativeBridge(symbol_name.c_str());
144 }
145
146 void* FindSymbolWithoutNativeBridge(const std::string& symbol_name) {
Andreas Gampe8fec90b2015-06-30 11:23:44 -0700147 CHECK(!NeedsNativeBridge());
148
Ian Rogers68d8b422014-07-17 11:09:10 -0700149 return dlsym(handle_, symbol_name.c_str());
150 }
151
152 void* FindSymbolWithNativeBridge(const std::string& symbol_name, const char* shorty) {
153 CHECK(NeedsNativeBridge());
154
155 uint32_t len = 0;
Calin Juravlec8423522014-08-12 20:55:20 +0100156 return android::NativeBridgeGetTrampoline(handle_, symbol_name.c_str(), shorty, len);
Ian Rogers68d8b422014-07-17 11:09:10 -0700157 }
158
159 private:
160 enum JNI_OnLoadState {
161 kPending,
162 kFailed,
163 kOkay,
164 };
165
166 // Path to library "/system/lib/libjni.so".
167 const std::string path_;
168
169 // The void* returned by dlopen(3).
170 void* const handle_;
171
172 // True if a native bridge is required.
173 bool needs_native_bridge_;
174
Mathieu Chartier598302a2015-09-23 14:52:39 -0700175 // The ClassLoader this library is associated with, a weak global JNI reference that is
Ian Rogers68d8b422014-07-17 11:09:10 -0700176 // created/deleted with the scope of the library.
Mathieu Chartier598302a2015-09-23 14:52:39 -0700177 const jweak class_loader_;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800178 // Used to do equality check on class loaders so we can avoid decoding the weak root and read
179 // barriers that mess with class unloading.
180 const void* class_loader_allocator_;
Ian Rogers68d8b422014-07-17 11:09:10 -0700181
182 // Guards remaining items.
183 Mutex jni_on_load_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
184 // Wait for JNI_OnLoad in other thread.
185 ConditionVariable jni_on_load_cond_ GUARDED_BY(jni_on_load_lock_);
186 // Recursive invocation guard.
187 uint32_t jni_on_load_thread_id_ GUARDED_BY(jni_on_load_lock_);
188 // Result of earlier JNI_OnLoad call.
189 JNI_OnLoadState jni_on_load_result_ GUARDED_BY(jni_on_load_lock_);
190};
191
192// This exists mainly to keep implementation details out of the header file.
193class Libraries {
194 public:
195 Libraries() {
196 }
197
198 ~Libraries() {
199 STLDeleteValues(&libraries_);
200 }
201
Mathieu Chartier598302a2015-09-23 14:52:39 -0700202 // NO_THREAD_SAFETY_ANALYSIS since this may be called from Dumpable. Dumpable can't be annotated
203 // properly due to the template. The caller should be holding the jni_libraries_lock_.
204 void Dump(std::ostream& os) const NO_THREAD_SAFETY_ANALYSIS {
205 Locks::jni_libraries_lock_->AssertHeld(Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -0700206 bool first = true;
207 for (const auto& library : libraries_) {
208 if (!first) {
209 os << ' ';
210 }
211 first = false;
212 os << library.first;
213 }
214 }
215
Mathieu Chartier598302a2015-09-23 14:52:39 -0700216 size_t size() const REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700217 return libraries_.size();
218 }
219
Mathieu Chartier598302a2015-09-23 14:52:39 -0700220 SharedLibrary* Get(const std::string& path) REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700221 auto it = libraries_.find(path);
222 return (it == libraries_.end()) ? nullptr : it->second;
223 }
224
Mathieu Chartier598302a2015-09-23 14:52:39 -0700225 void Put(const std::string& path, SharedLibrary* library)
226 REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700227 libraries_.Put(path, library);
228 }
229
230 // See section 11.3 "Linking Native Methods" of the JNI spec.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700231 void* FindNativeMethod(ArtMethod* m, std::string& detail)
Mathieu Chartier90443472015-07-16 20:32:27 -0700232 REQUIRES(Locks::jni_libraries_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700233 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700234 std::string jni_short_name(m->JniShortName());
235 std::string jni_long_name(m->JniLongName());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800236 mirror::ClassLoader* const declaring_class_loader = m->GetDeclaringClass()->GetClassLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700237 ScopedObjectAccessUnchecked soa(Thread::Current());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800238 void* const declaring_class_loader_allocator =
239 Runtime::Current()->GetClassLinker()->GetAllocatorForClassLoader(declaring_class_loader);
240 CHECK(declaring_class_loader_allocator != nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700241 for (const auto& lib : libraries_) {
Mathieu Chartier598302a2015-09-23 14:52:39 -0700242 SharedLibrary* const library = lib.second;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800243 // Use the allocator address for class loader equality to avoid unnecessary weak root decode.
244 if (library->GetClassLoaderAllocator() != declaring_class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700245 // We only search libraries loaded by the appropriate ClassLoader.
246 continue;
247 }
248 // Try the short name then the long name...
Mathieu Chartier598302a2015-09-23 14:52:39 -0700249 const char* shorty = library->NeedsNativeBridge()
250 ? m->GetShorty()
251 : nullptr;
252 void* fn = library->FindSymbol(jni_short_name, shorty);
253 if (fn == nullptr) {
254 fn = library->FindSymbol(jni_long_name, shorty);
Ian Rogers68d8b422014-07-17 11:09:10 -0700255 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700256 if (fn != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700257 VLOG(jni) << "[Found native code for " << m->PrettyMethod()
Ian Rogers68d8b422014-07-17 11:09:10 -0700258 << " in \"" << library->GetPath() << "\"]";
259 return fn;
260 }
261 }
262 detail += "No implementation found for ";
David Sehr709b0702016-10-13 09:12:37 -0700263 detail += m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700264 detail += " (tried " + jni_short_name + " and " + jni_long_name + ")";
265 LOG(ERROR) << detail;
266 return nullptr;
267 }
268
Mathieu Chartier598302a2015-09-23 14:52:39 -0700269 // Unload native libraries with cleared class loaders.
270 void UnloadNativeLibraries()
271 REQUIRES(!Locks::jni_libraries_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700272 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier598302a2015-09-23 14:52:39 -0700273 ScopedObjectAccessUnchecked soa(Thread::Current());
Alex Lightbc5669e2016-06-13 17:22:13 +0000274 std::vector<SharedLibrary*> unload_libraries;
Mathieu Chartier598302a2015-09-23 14:52:39 -0700275 {
276 MutexLock mu(soa.Self(), *Locks::jni_libraries_lock_);
277 for (auto it = libraries_.begin(); it != libraries_.end(); ) {
278 SharedLibrary* const library = it->second;
279 // If class loader is null then it was unloaded, call JNI_OnUnload.
Mathieu Chartiercffb7472015-09-28 10:33:00 -0700280 const jweak class_loader = library->GetClassLoader();
281 // If class_loader is a null jobject then it is the boot class loader. We should not unload
282 // the native libraries of the boot class loader.
283 if (class_loader != nullptr &&
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800284 soa.Self()->IsJWeakCleared(class_loader)) {
Alex Lightbc5669e2016-06-13 17:22:13 +0000285 unload_libraries.push_back(library);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700286 it = libraries_.erase(it);
287 } else {
288 ++it;
289 }
290 }
291 }
292 // Do this without holding the jni libraries lock to prevent possible deadlocks.
Alex Lightbc5669e2016-06-13 17:22:13 +0000293 typedef void (*JNI_OnUnloadFn)(JavaVM*, void*);
294 for (auto library : unload_libraries) {
295 void* const sym = library->FindSymbol("JNI_OnUnload", nullptr);
296 if (sym == nullptr) {
297 VLOG(jni) << "[No JNI_OnUnload found in \"" << library->GetPath() << "\"]";
298 } else {
299 VLOG(jni) << "[JNI_OnUnload found for \"" << library->GetPath() << "\"]: Calling...";
300 JNI_OnUnloadFn jni_on_unload = reinterpret_cast<JNI_OnUnloadFn>(sym);
301 jni_on_unload(soa.Vm(), nullptr);
302 }
303 delete library;
Mathieu Chartier598302a2015-09-23 14:52:39 -0700304 }
305 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700306
Mathieu Chartier598302a2015-09-23 14:52:39 -0700307 private:
308 AllocationTrackingSafeMap<std::string, SharedLibrary*, kAllocatorTagJNILibraries> libraries_
309 GUARDED_BY(Locks::jni_libraries_lock_);
310};
Ian Rogers68d8b422014-07-17 11:09:10 -0700311
312class JII {
313 public:
314 static jint DestroyJavaVM(JavaVM* vm) {
315 if (vm == nullptr) {
316 return JNI_ERR;
317 }
318 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
319 delete raw_vm->GetRuntime();
Dimitry Ivanov39d68ef2016-04-29 16:02:38 -0700320 android::ResetNativeLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700321 return JNI_OK;
322 }
323
324 static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
325 return AttachCurrentThreadInternal(vm, p_env, thr_args, false);
326 }
327
328 static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
329 return AttachCurrentThreadInternal(vm, p_env, thr_args, true);
330 }
331
332 static jint DetachCurrentThread(JavaVM* vm) {
333 if (vm == nullptr || Thread::Current() == nullptr) {
334 return JNI_ERR;
335 }
336 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
337 Runtime* runtime = raw_vm->GetRuntime();
338 runtime->DetachCurrentThread();
339 return JNI_OK;
340 }
341
342 static jint GetEnv(JavaVM* vm, void** env, jint version) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700343 if (vm == nullptr || env == nullptr) {
344 return JNI_ERR;
345 }
346 Thread* thread = Thread::Current();
347 if (thread == nullptr) {
348 *env = nullptr;
349 return JNI_EDETACHED;
350 }
Alex Light185d1342016-08-11 10:48:03 -0700351 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
352 return raw_vm->HandleGetEnv(env, version);
Ian Rogers68d8b422014-07-17 11:09:10 -0700353 }
354
355 private:
356 static jint AttachCurrentThreadInternal(JavaVM* vm, JNIEnv** p_env, void* raw_args, bool as_daemon) {
357 if (vm == nullptr || p_env == nullptr) {
358 return JNI_ERR;
359 }
360
361 // Return immediately if we're already attached.
362 Thread* self = Thread::Current();
363 if (self != nullptr) {
364 *p_env = self->GetJniEnv();
365 return JNI_OK;
366 }
367
368 Runtime* runtime = reinterpret_cast<JavaVMExt*>(vm)->GetRuntime();
369
370 // No threads allowed in zygote mode.
371 if (runtime->IsZygote()) {
372 LOG(ERROR) << "Attempt to attach a thread in the zygote";
373 return JNI_ERR;
374 }
375
376 JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(raw_args);
377 const char* thread_name = nullptr;
378 jobject thread_group = nullptr;
379 if (args != nullptr) {
Alex Light185d1342016-08-11 10:48:03 -0700380 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700381 LOG(ERROR) << "Bad JNI version passed to "
382 << (as_daemon ? "AttachCurrentThreadAsDaemon" : "AttachCurrentThread") << ": "
383 << args->version;
384 return JNI_EVERSION;
385 }
386 thread_name = args->name;
387 thread_group = args->group;
388 }
389
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800390 if (!runtime->AttachCurrentThread(thread_name, as_daemon, thread_group,
391 !runtime->IsAotCompiler())) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700392 *p_env = nullptr;
393 return JNI_ERR;
394 } else {
395 *p_env = Thread::Current()->GetJniEnv();
396 return JNI_OK;
397 }
398 }
399};
400
401const JNIInvokeInterface gJniInvokeInterface = {
402 nullptr, // reserved0
403 nullptr, // reserved1
404 nullptr, // reserved2
405 JII::DestroyJavaVM,
406 JII::AttachCurrentThread,
407 JII::DetachCurrentThread,
408 JII::GetEnv,
409 JII::AttachCurrentThreadAsDaemon
410};
411
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100412JavaVMExt::JavaVMExt(Runtime* runtime,
413 const RuntimeArgumentMap& runtime_options,
414 std::string* error_msg)
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 Gampe9d7ef622016-10-24 19:35:19 -0700423 globals_(kGlobalsMax, kGlobal, IndirectReferenceTable::ResizableCapacity::kNo, error_msg),
Ian Rogers68d8b422014-07-17 11:09:10 -0700424 libraries_(new Libraries),
425 unchecked_functions_(&gJniInvokeInterface),
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700426 weak_globals_(kWeakGlobalsMax,
427 kWeakGlobal,
428 IndirectReferenceTable::ResizableCapacity::kNo,
429 error_msg),
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700430 allow_accessing_weak_globals_(true),
Andreas Gampe05a364c2016-10-14 13:27:12 -0700431 weak_globals_add_condition_("weak globals add condition",
432 (CHECK(Locks::jni_weak_globals_lock_ != nullptr),
433 *Locks::jni_weak_globals_lock_)),
Alex Light185d1342016-08-11 10:48:03 -0700434 env_hooks_() {
Ian Rogers68d8b422014-07-17 11:09:10 -0700435 functions = unchecked_functions_;
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800436 SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni));
Ian Rogers68d8b422014-07-17 11:09:10 -0700437}
438
439JavaVMExt::~JavaVMExt() {
440}
441
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100442// Checking "globals" and "weak_globals" usually requires locks, but we
443// don't need the locks to check for validity when constructing the
444// object. Use NO_THREAD_SAFETY_ANALYSIS for this.
445std::unique_ptr<JavaVMExt> JavaVMExt::Create(Runtime* runtime,
446 const RuntimeArgumentMap& runtime_options,
447 std::string* error_msg) NO_THREAD_SAFETY_ANALYSIS {
448 std::unique_ptr<JavaVMExt> java_vm(new JavaVMExt(runtime, runtime_options, error_msg));
449 if (java_vm && java_vm->globals_.IsValid() && java_vm->weak_globals_.IsValid()) {
450 return java_vm;
451 }
452 return nullptr;
453}
454
Alex Light185d1342016-08-11 10:48:03 -0700455jint JavaVMExt::HandleGetEnv(/*out*/void** env, jint version) {
456 for (GetEnvHook hook : env_hooks_) {
457 jint res = hook(this, env, version);
458 if (res == JNI_OK) {
459 return JNI_OK;
460 } else if (res != JNI_EVERSION) {
461 LOG(ERROR) << "Error returned from a plugin GetEnv handler! " << res;
462 return res;
463 }
464 }
465 LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version;
466 return JNI_EVERSION;
467}
468
469// Add a hook to handle getting environments from the GetEnv call.
470void JavaVMExt::AddEnvironmentHook(GetEnvHook hook) {
471 CHECK(hook != nullptr) << "environment hooks shouldn't be null!";
472 env_hooks_.push_back(hook);
473}
474
Ian Rogers68d8b422014-07-17 11:09:10 -0700475void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) {
476 Thread* self = Thread::Current();
477 ScopedObjectAccess soa(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700478 ArtMethod* current_method = self->GetCurrentMethod(nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700479
480 std::ostringstream os;
481 os << "JNI DETECTED ERROR IN APPLICATION: " << msg;
482
483 if (jni_function_name != nullptr) {
484 os << "\n in call to " << jni_function_name;
485 }
486 // TODO: is this useful given that we're about to dump the calling thread's stack?
487 if (current_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700488 os << "\n from " << current_method->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700489 }
490 os << "\n";
491 self->Dump(os);
492
493 if (check_jni_abort_hook_ != nullptr) {
494 check_jni_abort_hook_(check_jni_abort_hook_data_, os.str());
495 } else {
496 // Ensure that we get a native stack trace for this thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700497 ScopedThreadSuspension sts(self, kNative);
Ian Rogers68d8b422014-07-17 11:09:10 -0700498 LOG(FATAL) << os.str();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700499 UNREACHABLE();
Ian Rogers68d8b422014-07-17 11:09:10 -0700500 }
501}
502
503void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) {
504 std::string msg;
505 StringAppendV(&msg, fmt, ap);
506 JniAbort(jni_function_name, msg.c_str());
507}
508
509void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) {
510 va_list args;
511 va_start(args, fmt);
512 JniAbortV(jni_function_name, fmt, args);
513 va_end(args);
514}
515
Mathieu Chartiere401d142015-04-22 13:56:20 -0700516bool JavaVMExt::ShouldTrace(ArtMethod* method) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700517 // Fast where no tracing is enabled.
518 if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) {
519 return false;
520 }
521 // Perform checks based on class name.
522 StringPiece class_name(method->GetDeclaringClassDescriptor());
523 if (!trace_.empty() && class_name.find(trace_) != std::string::npos) {
524 return true;
525 }
526 if (!VLOG_IS_ON(third_party_jni)) {
527 return false;
528 }
529 // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
530 // like part of Android.
531 static const char* gBuiltInPrefixes[] = {
532 "Landroid/",
533 "Lcom/android/",
534 "Lcom/google/android/",
535 "Ldalvik/",
536 "Ljava/",
537 "Ljavax/",
538 "Llibcore/",
539 "Lorg/apache/harmony/",
540 };
541 for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) {
542 if (class_name.starts_with(gBuiltInPrefixes[i])) {
543 return false;
544 }
545 }
546 return true;
547}
548
Mathieu Chartier0795f232016-09-27 18:43:30 -0700549jobject JavaVMExt::AddGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700550 // Check for null after decoding the object to handle cleared weak globals.
551 if (obj == nullptr) {
552 return nullptr;
553 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700554 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700555 IndirectRef ref = globals_.Add(kIRTFirstSegment, obj);
Ian Rogers68d8b422014-07-17 11:09:10 -0700556 return reinterpret_cast<jobject>(ref);
557}
558
Mathieu Chartier0795f232016-09-27 18:43:30 -0700559jweak JavaVMExt::AddWeakGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700560 if (obj == nullptr) {
561 return nullptr;
562 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700563 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700564 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700565 weak_globals_add_condition_.WaitHoldingLocks(self);
566 }
Andreas Gampee03662b2016-10-13 17:12:56 -0700567 IndirectRef ref = weak_globals_.Add(kIRTFirstSegment, obj);
Ian Rogers68d8b422014-07-17 11:09:10 -0700568 return reinterpret_cast<jweak>(ref);
569}
570
571void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
572 if (obj == nullptr) {
573 return;
574 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700575 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700576 if (!globals_.Remove(kIRTFirstSegment, obj)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700577 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
578 << "failed to find entry";
579 }
580}
581
582void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
583 if (obj == nullptr) {
584 return;
585 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700586 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700587 if (!weak_globals_.Remove(kIRTFirstSegment, obj)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700588 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
589 << "failed to find entry";
590 }
591}
592
593static void ThreadEnableCheckJni(Thread* thread, void* arg) {
594 bool* check_jni = reinterpret_cast<bool*>(arg);
595 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
596}
597
598bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
599 bool old_check_jni = check_jni_;
600 check_jni_ = enabled;
601 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
602 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
603 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
604 return old_check_jni;
605}
606
607void JavaVMExt::DumpForSigQuit(std::ostream& os) {
608 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
609 if (force_copy_) {
610 os << " (with forcecopy)";
611 }
612 Thread* self = Thread::Current();
613 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700614 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700615 os << "; globals=" << globals_.Capacity();
616 }
617 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700618 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700619 if (weak_globals_.Capacity() > 0) {
620 os << " (plus " << weak_globals_.Capacity() << " weak)";
621 }
622 }
623 os << '\n';
624
625 {
626 MutexLock mu(self, *Locks::jni_libraries_lock_);
627 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
628 }
629}
630
631void JavaVMExt::DisallowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700632 CHECK(!kUseReadBarrier);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700633 Thread* const self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700634 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700635 // DisallowNewWeakGlobals is only called by CMS during the pause. It is required to have the
636 // mutator lock exclusively held so that we don't have any threads in the middle of
637 // DecodeWeakGlobal.
638 Locks::mutator_lock_->AssertExclusiveHeld(self);
639 allow_accessing_weak_globals_.StoreSequentiallyConsistent(false);
Ian Rogers68d8b422014-07-17 11:09:10 -0700640}
641
642void JavaVMExt::AllowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700643 CHECK(!kUseReadBarrier);
Ian Rogers68d8b422014-07-17 11:09:10 -0700644 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700645 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700646 allow_accessing_weak_globals_.StoreSequentiallyConsistent(true);
Ian Rogers68d8b422014-07-17 11:09:10 -0700647 weak_globals_add_condition_.Broadcast(self);
648}
649
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700650void JavaVMExt::BroadcastForNewWeakGlobals() {
651 CHECK(kUseReadBarrier);
652 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700653 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700654 weak_globals_add_condition_.Broadcast(self);
655}
656
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700657ObjPtr<mirror::Object> JavaVMExt::DecodeGlobal(IndirectRef ref) {
658 return globals_.SynchronizedGet(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700659}
660
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700661void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700662 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700663 globals_.Update(ref, result);
664}
665
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700666inline bool JavaVMExt::MayAccessWeakGlobals(Thread* self) const {
667 return MayAccessWeakGlobalsUnlocked(self);
668}
669
670inline bool JavaVMExt::MayAccessWeakGlobalsUnlocked(Thread* self) const {
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700671 DCHECK(self != nullptr);
672 return kUseReadBarrier ?
673 self->GetWeakRefAccessEnabled() :
674 allow_accessing_weak_globals_.LoadSequentiallyConsistent();
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700675}
676
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700677ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700678 // It is safe to access GetWeakRefAccessEnabled without the lock since CC uses checkpoints to call
679 // SetWeakRefAccessEnabled, and the other collectors only modify allow_accessing_weak_globals_
680 // when the mutators are paused.
681 // This only applies in the case where MayAccessWeakGlobals goes from false to true. In the other
682 // case, it may be racy, this is benign since DecodeWeakGlobalLocked does the correct behavior
683 // if MayAccessWeakGlobals is false.
Andreas Gampedc061d02016-10-24 13:19:37 -0700684 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700685 if (LIKELY(MayAccessWeakGlobalsUnlocked(self))) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700686 return weak_globals_.SynchronizedGet(ref);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700687 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700688 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700689 return DecodeWeakGlobalLocked(self, ref);
690}
691
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700692ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalLocked(Thread* self, IndirectRef ref) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700693 if (kDebugLocking) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700694 Locks::jni_weak_globals_lock_->AssertHeld(self);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700695 }
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700696 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700697 weak_globals_add_condition_.WaitHoldingLocks(self);
698 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700699 return weak_globals_.Get(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700700}
701
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700702ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalDuringShutdown(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700703 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700704 DCHECK(Runtime::Current()->IsShuttingDown(self));
705 if (self != nullptr) {
706 return DecodeWeakGlobal(self, ref);
707 }
708 // self can be null during a runtime shutdown. ~Runtime()->~ClassLinker()->DecodeWeakGlobal().
709 if (!kUseReadBarrier) {
710 DCHECK(allow_accessing_weak_globals_.LoadSequentiallyConsistent());
711 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700712 return weak_globals_.SynchronizedGet(ref);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700713}
714
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800715bool JavaVMExt::IsWeakGlobalCleared(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700716 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Andreas Gampe05a364c2016-10-14 13:27:12 -0700717 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800718 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
719 weak_globals_add_condition_.WaitHoldingLocks(self);
720 }
721 // When just checking a weak ref has been cleared, avoid triggering the read barrier in decode
722 // (DecodeWeakGlobal) so that we won't accidentally mark the object alive. Since the cleared
723 // sentinel is a non-moving object, we can compare the ref to it without the read barrier and
724 // decide if it's cleared.
725 return Runtime::Current()->IsClearedJniWeakGlobal(weak_globals_.Get<kWithoutReadBarrier>(ref));
726}
727
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700728void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700729 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700730 weak_globals_.Update(ref, result);
731}
732
Ian Rogers68d8b422014-07-17 11:09:10 -0700733void JavaVMExt::DumpReferenceTables(std::ostream& os) {
734 Thread* self = Thread::Current();
735 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700736 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700737 globals_.Dump(os);
738 }
739 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700740 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700741 weak_globals_.Dump(os);
742 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700743}
744
Mathieu Chartier598302a2015-09-23 14:52:39 -0700745void JavaVMExt::UnloadNativeLibraries() {
746 libraries_.get()->UnloadNativeLibraries();
747}
748
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800749bool JavaVMExt::LoadNativeLibrary(JNIEnv* env,
750 const std::string& path,
751 jobject class_loader,
752 jstring library_path,
753 std::string* error_msg) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700754 error_msg->clear();
755
756 // See if we've already loaded this library. If we have, and the class loader
757 // matches, return successfully without doing anything.
758 // TODO: for better results we should canonicalize the pathname (or even compare
759 // inodes). This implementation is fine if everybody is using System.loadLibrary.
760 SharedLibrary* library;
761 Thread* self = Thread::Current();
762 {
763 // TODO: move the locking (and more of this logic) into Libraries.
764 MutexLock mu(self, *Locks::jni_libraries_lock_);
765 library = libraries_->Get(path);
766 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800767 void* class_loader_allocator = nullptr;
768 {
769 ScopedObjectAccess soa(env);
770 // As the incoming class loader is reachable/alive during the call of this function,
771 // it's okay to decode it without worrying about unexpectedly marking it alive.
Mathieu Chartier0795f232016-09-27 18:43:30 -0700772 ObjPtr<mirror::ClassLoader> loader = soa.Decode<mirror::ClassLoader>(class_loader);
Andreas Gampe2d48e532016-06-17 12:46:14 -0700773
774 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700775 if (class_linker->IsBootClassLoader(soa, loader.Ptr())) {
Andreas Gampe2d48e532016-06-17 12:46:14 -0700776 loader = nullptr;
777 class_loader = nullptr;
778 }
779
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700780 class_loader_allocator = class_linker->GetAllocatorForClassLoader(loader.Ptr());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800781 CHECK(class_loader_allocator != nullptr);
782 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700783 if (library != nullptr) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800784 // Use the allocator pointers for class loader equality to avoid unnecessary weak root decode.
785 if (library->GetClassLoaderAllocator() != class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700786 // The library will be associated with class_loader. The JNI
787 // spec says we can't load the same library into more than one
788 // class loader.
789 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
790 "ClassLoader %p; can't open in ClassLoader %p",
791 path.c_str(), library->GetClassLoader(), class_loader);
792 LOG(WARNING) << error_msg;
793 return false;
794 }
795 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
796 << " ClassLoader " << class_loader << "]";
797 if (!library->CheckOnLoadResult()) {
798 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
799 "to load \"%s\"", path.c_str());
800 return false;
801 }
802 return true;
803 }
804
805 // Open the shared library. Because we're using a full path, the system
806 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
807 // resolve this library's dependencies though.)
808
809 // Failures here are expected when java.library.path has several entries
810 // and we have to hunt for the lib.
811
812 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
813 // class unloading. Libraries will only be unloaded when the reference count (incremented by
814 // dlopen) becomes zero from dlclose.
815
816 Locks::mutator_lock_->AssertNotHeld(self);
817 const char* path_str = path.empty() ? nullptr : path.c_str();
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800818 bool needs_native_bridge = false;
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800819 void* handle = android::OpenNativeLibrary(env,
820 runtime_->GetTargetSdkVersion(),
821 path_str,
822 class_loader,
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800823 library_path,
824 &needs_native_bridge,
825 error_msg);
Ian Rogers68d8b422014-07-17 11:09:10 -0700826
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700827 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]";
Ian Rogers68d8b422014-07-17 11:09:10 -0700828
829 if (handle == nullptr) {
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700830 VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700831 return false;
832 }
833
834 if (env->ExceptionCheck() == JNI_TRUE) {
835 LOG(ERROR) << "Unexpected exception:";
836 env->ExceptionDescribe();
837 env->ExceptionClear();
838 }
839 // Create a new entry.
840 // TODO: move the locking (and more of this logic) into Libraries.
841 bool created_library = false;
842 {
843 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
844 std::unique_ptr<SharedLibrary> new_library(
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800845 new SharedLibrary(env,
846 self,
847 path,
848 handle,
849 needs_native_bridge,
850 class_loader,
851 class_loader_allocator));
852
Ian Rogers68d8b422014-07-17 11:09:10 -0700853 MutexLock mu(self, *Locks::jni_libraries_lock_);
854 library = libraries_->Get(path);
855 if (library == nullptr) { // We won race to get libraries_lock.
856 library = new_library.release();
857 libraries_->Put(path, library);
858 created_library = true;
859 }
860 }
861 if (!created_library) {
862 LOG(INFO) << "WOW: we lost a race to add shared library: "
863 << "\"" << path << "\" ClassLoader=" << class_loader;
864 return library->CheckOnLoadResult();
865 }
866 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
867
868 bool was_successful = false;
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800869 void* sym = library->FindSymbol("JNI_OnLoad", nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700870 if (sym == nullptr) {
871 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
872 was_successful = true;
873 } else {
874 // Call JNI_OnLoad. We have to override the current class
875 // loader, which will always be "null" since the stuff at the
876 // top of the stack is around Runtime.loadLibrary(). (See
877 // the comments in the JNI FindClass function.)
878 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
879 self->SetClassLoaderOverride(class_loader);
880
881 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
882 typedef int (*JNI_OnLoadFn)(JavaVM*, void*);
883 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
884 int version = (*jni_on_load)(this, nullptr);
885
Mathieu Chartierd0004802014-10-15 16:59:47 -0700886 if (runtime_->GetTargetSdkVersion() != 0 && runtime_->GetTargetSdkVersion() <= 21) {
887 fault_manager.EnsureArtActionInFrontOfSignalChain();
888 }
889
Ian Rogers68d8b422014-07-17 11:09:10 -0700890 self->SetClassLoaderOverride(old_class_loader.get());
891
892 if (version == JNI_ERR) {
893 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
Alex Light185d1342016-08-11 10:48:03 -0700894 } else if (JavaVMExt::IsBadJniVersion(version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700895 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
896 path.c_str(), version);
897 // It's unwise to call dlclose() here, but we can mark it
898 // as bad and ensure that future load attempts will fail.
899 // We don't know how far JNI_OnLoad got, so there could
900 // be some partially-initialized stuff accessible through
901 // newly-registered native method calls. We could try to
902 // unregister them, but that doesn't seem worthwhile.
903 } else {
904 was_successful = true;
905 }
906 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
907 << " from JNI_OnLoad in \"" << path << "\"]";
908 }
909
910 library->SetResult(was_successful);
911 return was_successful;
912}
913
Mathieu Chartiere401d142015-04-22 13:56:20 -0700914void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700915 CHECK(m->IsNative());
916 mirror::Class* c = m->GetDeclaringClass();
917 // If this is a static method, it could be called before the class has been initialized.
David Sehr709b0702016-10-13 09:12:37 -0700918 CHECK(c->IsInitializing()) << c->GetStatus() << " " << m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700919 std::string detail;
920 void* native_method;
921 Thread* self = Thread::Current();
922 {
923 MutexLock mu(self, *Locks::jni_libraries_lock_);
924 native_method = libraries_->FindNativeMethod(m, detail);
925 }
926 // Throwing can cause libraries_lock to be reacquired.
927 if (native_method == nullptr) {
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000928 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
Ian Rogers68d8b422014-07-17 11:09:10 -0700929 }
930 return native_method;
931}
932
Mathieu Chartier97509952015-07-13 14:35:43 -0700933void JavaVMExt::SweepJniWeakGlobals(IsMarkedVisitor* visitor) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700934 MutexLock mu(Thread::Current(), *Locks::jni_weak_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700935 Runtime* const runtime = Runtime::Current();
936 for (auto* entry : weak_globals_) {
937 // Need to skip null here to distinguish between null entries and cleared weak ref entries.
938 if (!entry->IsNull()) {
939 // Since this is called by the GC, we don't need a read barrier.
940 mirror::Object* obj = entry->Read<kWithoutReadBarrier>();
Mathieu Chartier97509952015-07-13 14:35:43 -0700941 mirror::Object* new_obj = visitor->IsMarked(obj);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700942 if (new_obj == nullptr) {
943 new_obj = runtime->GetClearedJniWeakGlobal();
944 }
945 *entry = GcRoot<mirror::Object>(new_obj);
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -0700946 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700947 }
948}
949
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800950void JavaVMExt::TrimGlobals() {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700951 WriterMutexLock mu(Thread::Current(), *Locks::jni_globals_lock_);
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800952 globals_.Trim();
953}
954
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700955void JavaVMExt::VisitRoots(RootVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700956 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700957 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700958 globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal));
Ian Rogers68d8b422014-07-17 11:09:10 -0700959 // The weak_globals table is visited by the GC itself (because it mutates the table).
960}
961
962// JNI Invocation interface.
963
964extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -0800965 ScopedTrace trace(__FUNCTION__);
Ian Rogers68d8b422014-07-17 11:09:10 -0700966 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
Alex Light185d1342016-08-11 10:48:03 -0700967 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700968 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
969 return JNI_EVERSION;
970 }
971 RuntimeOptions options;
972 for (int i = 0; i < args->nOptions; ++i) {
973 JavaVMOption* option = &args->options[i];
974 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
975 }
976 bool ignore_unrecognized = args->ignoreUnrecognized;
977 if (!Runtime::Create(options, ignore_unrecognized)) {
978 return JNI_ERR;
979 }
Dimitry Ivanovc544f342016-05-09 16:26:13 -0700980
981 // Initialize native loader. This step makes sure we have
982 // everything set up before we start using JNI.
983 android::InitializeNativeLoader();
984
Ian Rogers68d8b422014-07-17 11:09:10 -0700985 Runtime* runtime = Runtime::Current();
986 bool started = runtime->Start();
987 if (!started) {
988 delete Thread::Current()->GetJniEnv();
989 delete runtime->GetJavaVM();
990 LOG(WARNING) << "CreateJavaVM failed";
991 return JNI_ERR;
992 }
Dimitry Ivanov041169f2016-04-21 16:01:24 -0700993
Ian Rogers68d8b422014-07-17 11:09:10 -0700994 *p_env = Thread::Current()->GetJniEnv();
995 *p_vm = runtime->GetJavaVM();
996 return JNI_OK;
997}
998
Ian Rogersf4d4da12014-11-11 16:10:33 -0800999extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001000 Runtime* runtime = Runtime::Current();
Ian Rogersf4d4da12014-11-11 16:10:33 -08001001 if (runtime == nullptr || buf_len == 0) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001002 *vm_count = 0;
1003 } else {
1004 *vm_count = 1;
Ian Rogersf4d4da12014-11-11 16:10:33 -08001005 vms_buf[0] = runtime->GetJavaVM();
Ian Rogers68d8b422014-07-17 11:09:10 -07001006 }
1007 return JNI_OK;
1008}
1009
1010// Historically unsupported.
1011extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
1012 return JNI_ERR;
1013}
1014
1015} // namespace art