blob: 41376335a5f31fa90d9fe6aecb0faae9a2ea1b76 [file] [log] [blame]
Ian Rogers68d8b422014-07-17 11:09:10 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "jni_internal.h"
18
19#include <dlfcn.h>
20
Andreas Gampe46ee31b2016-12-14 10:11:49 -080021#include "android-base/stringprintf.h"
22
Andreas Gampec6ea7d02017-02-01 16:46:28 -080023#include "art_method-inl.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070024#include "base/dumpable.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070025#include "base/mutex-inl.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070026#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080027#include "base/systrace.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070028#include "check_jni.h"
Elliott Hughes956af0f2014-12-11 14:34:28 -080029#include "dex_file-inl.h"
Mathieu Chartierd0004802014-10-15 16:59:47 -070030#include "fault_handler.h"
Andreas Gamped4901292017-05-30 18:41:34 -070031#include "gc_root-inl.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070032#include "indirect_reference_table-inl.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070033#include "mirror/class-inl.h"
34#include "mirror/class_loader.h"
Calin Juravlec8423522014-08-12 20:55:20 +010035#include "nativebridge/native_bridge.h"
Dmitriy Ivanovf5a30992015-11-11 14:18:55 -080036#include "nativeloader/native_loader.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070037#include "java_vm_ext.h"
38#include "parsed_options.h"
Ian Rogersc0542af2014-09-03 16:16:56 -070039#include "runtime-inl.h"
Igor Murashkinaaebaa02015-01-26 10:55:53 -080040#include "runtime_options.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070041#include "ScopedLocalRef.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070042#include "scoped_thread_state_change-inl.h"
Josh Gao85a78cf2017-03-20 16:26:42 -070043#include "sigchain.h"
Alex Light65af20b2017-04-20 09:15:08 -070044#include "ti/agent.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070045#include "thread-inl.h"
46#include "thread_list.h"
47
48namespace art {
49
Andreas Gampe46ee31b2016-12-14 10:11:49 -080050using android::base::StringAppendF;
51using android::base::StringAppendV;
52
Andreas Gampea8e3b862016-10-17 20:12:52 -070053static constexpr size_t kGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
Ian Rogers68d8b422014-07-17 11:09:10 -070054
Andreas Gampea8e3b862016-10-17 20:12:52 -070055static constexpr size_t kWeakGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
Ian Rogers68d8b422014-07-17 11:09:10 -070056
Alex Light185d1342016-08-11 10:48:03 -070057bool JavaVMExt::IsBadJniVersion(int version) {
Ian Rogers68d8b422014-07-17 11:09:10 -070058 // We don't support JNI_VERSION_1_1. These are the only other valid versions.
59 return version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 && version != JNI_VERSION_1_6;
60}
61
62class SharedLibrary {
63 public:
64 SharedLibrary(JNIEnv* env, Thread* self, const std::string& path, void* handle,
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080065 bool needs_native_bridge, jobject class_loader, void* class_loader_allocator)
Ian Rogers68d8b422014-07-17 11:09:10 -070066 : path_(path),
67 handle_(handle),
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080068 needs_native_bridge_(needs_native_bridge),
Mathieu Chartier598302a2015-09-23 14:52:39 -070069 class_loader_(env->NewWeakGlobalRef(class_loader)),
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080070 class_loader_allocator_(class_loader_allocator),
Ian Rogers68d8b422014-07-17 11:09:10 -070071 jni_on_load_lock_("JNI_OnLoad lock"),
72 jni_on_load_cond_("JNI_OnLoad condition variable", jni_on_load_lock_),
73 jni_on_load_thread_id_(self->GetThreadId()),
74 jni_on_load_result_(kPending) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080075 CHECK(class_loader_allocator_ != nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -070076 }
77
78 ~SharedLibrary() {
79 Thread* self = Thread::Current();
80 if (self != nullptr) {
Mathieu Chartier598302a2015-09-23 14:52:39 -070081 self->GetJniEnv()->DeleteWeakGlobalRef(class_loader_);
Ian Rogers68d8b422014-07-17 11:09:10 -070082 }
Alex Lightbc5669e2016-06-13 17:22:13 +000083
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080084 android::CloseNativeLibrary(handle_, needs_native_bridge_);
Ian Rogers68d8b422014-07-17 11:09:10 -070085 }
86
Mathieu Chartier598302a2015-09-23 14:52:39 -070087 jweak GetClassLoader() const {
Ian Rogers68d8b422014-07-17 11:09:10 -070088 return class_loader_;
89 }
90
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080091 const void* GetClassLoaderAllocator() const {
92 return class_loader_allocator_;
93 }
94
Ian Rogers68d8b422014-07-17 11:09:10 -070095 const std::string& GetPath() const {
96 return path_;
97 }
98
99 /*
100 * Check the result of an earlier call to JNI_OnLoad on this library.
101 * If the call has not yet finished in another thread, wait for it.
102 */
103 bool CheckOnLoadResult()
Mathieu Chartier90443472015-07-16 20:32:27 -0700104 REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700105 Thread* self = Thread::Current();
106 bool okay;
107 {
108 MutexLock mu(self, jni_on_load_lock_);
109
110 if (jni_on_load_thread_id_ == self->GetThreadId()) {
111 // Check this so we don't end up waiting for ourselves. We need to return "true" so the
112 // caller can continue.
113 LOG(INFO) << *self << " recursive attempt to load library " << "\"" << path_ << "\"";
114 okay = true;
115 } else {
116 while (jni_on_load_result_ == kPending) {
117 VLOG(jni) << "[" << *self << " waiting for \"" << path_ << "\" " << "JNI_OnLoad...]";
118 jni_on_load_cond_.Wait(self);
119 }
120
121 okay = (jni_on_load_result_ == kOkay);
122 VLOG(jni) << "[Earlier JNI_OnLoad for \"" << path_ << "\" "
123 << (okay ? "succeeded" : "failed") << "]";
124 }
125 }
126 return okay;
127 }
128
Mathieu Chartier90443472015-07-16 20:32:27 -0700129 void SetResult(bool result) REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700130 Thread* self = Thread::Current();
131 MutexLock mu(self, jni_on_load_lock_);
132
133 jni_on_load_result_ = result ? kOkay : kFailed;
134 jni_on_load_thread_id_ = 0;
135
136 // Broadcast a wakeup to anybody sleeping on the condition variable.
137 jni_on_load_cond_.Broadcast(self);
138 }
139
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800140 void SetNeedsNativeBridge(bool needs) {
141 needs_native_bridge_ = needs;
Ian Rogers68d8b422014-07-17 11:09:10 -0700142 }
143
144 bool NeedsNativeBridge() const {
145 return needs_native_bridge_;
146 }
147
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700148 // No mutator lock since dlsym may block for a while if another thread is doing dlopen.
149 void* FindSymbol(const std::string& symbol_name, const char* shorty = nullptr)
150 REQUIRES(!Locks::mutator_lock_) {
Mathieu Chartier598302a2015-09-23 14:52:39 -0700151 return NeedsNativeBridge()
152 ? FindSymbolWithNativeBridge(symbol_name.c_str(), shorty)
153 : FindSymbolWithoutNativeBridge(symbol_name.c_str());
154 }
155
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700156 // No mutator lock since dlsym may block for a while if another thread is doing dlopen.
157 void* FindSymbolWithoutNativeBridge(const std::string& symbol_name)
158 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe8fec90b2015-06-30 11:23:44 -0700159 CHECK(!NeedsNativeBridge());
160
Ian Rogers68d8b422014-07-17 11:09:10 -0700161 return dlsym(handle_, symbol_name.c_str());
162 }
163
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700164 void* FindSymbolWithNativeBridge(const std::string& symbol_name, const char* shorty)
165 REQUIRES(!Locks::mutator_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700166 CHECK(NeedsNativeBridge());
167
168 uint32_t len = 0;
Calin Juravlec8423522014-08-12 20:55:20 +0100169 return android::NativeBridgeGetTrampoline(handle_, symbol_name.c_str(), shorty, len);
Ian Rogers68d8b422014-07-17 11:09:10 -0700170 }
171
172 private:
173 enum JNI_OnLoadState {
174 kPending,
175 kFailed,
176 kOkay,
177 };
178
179 // Path to library "/system/lib/libjni.so".
180 const std::string path_;
181
182 // The void* returned by dlopen(3).
183 void* const handle_;
184
185 // True if a native bridge is required.
186 bool needs_native_bridge_;
187
Mathieu Chartier598302a2015-09-23 14:52:39 -0700188 // The ClassLoader this library is associated with, a weak global JNI reference that is
Ian Rogers68d8b422014-07-17 11:09:10 -0700189 // created/deleted with the scope of the library.
Mathieu Chartier598302a2015-09-23 14:52:39 -0700190 const jweak class_loader_;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800191 // Used to do equality check on class loaders so we can avoid decoding the weak root and read
192 // barriers that mess with class unloading.
193 const void* class_loader_allocator_;
Ian Rogers68d8b422014-07-17 11:09:10 -0700194
195 // Guards remaining items.
196 Mutex jni_on_load_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
197 // Wait for JNI_OnLoad in other thread.
198 ConditionVariable jni_on_load_cond_ GUARDED_BY(jni_on_load_lock_);
199 // Recursive invocation guard.
200 uint32_t jni_on_load_thread_id_ GUARDED_BY(jni_on_load_lock_);
201 // Result of earlier JNI_OnLoad call.
202 JNI_OnLoadState jni_on_load_result_ GUARDED_BY(jni_on_load_lock_);
203};
204
205// This exists mainly to keep implementation details out of the header file.
206class Libraries {
207 public:
208 Libraries() {
209 }
210
211 ~Libraries() {
212 STLDeleteValues(&libraries_);
213 }
214
Mathieu Chartier598302a2015-09-23 14:52:39 -0700215 // NO_THREAD_SAFETY_ANALYSIS since this may be called from Dumpable. Dumpable can't be annotated
216 // properly due to the template. The caller should be holding the jni_libraries_lock_.
217 void Dump(std::ostream& os) const NO_THREAD_SAFETY_ANALYSIS {
218 Locks::jni_libraries_lock_->AssertHeld(Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -0700219 bool first = true;
220 for (const auto& library : libraries_) {
221 if (!first) {
222 os << ' ';
223 }
224 first = false;
225 os << library.first;
226 }
227 }
228
Mathieu Chartier598302a2015-09-23 14:52:39 -0700229 size_t size() const REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700230 return libraries_.size();
231 }
232
Mathieu Chartier598302a2015-09-23 14:52:39 -0700233 SharedLibrary* Get(const std::string& path) REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700234 auto it = libraries_.find(path);
235 return (it == libraries_.end()) ? nullptr : it->second;
236 }
237
Mathieu Chartier598302a2015-09-23 14:52:39 -0700238 void Put(const std::string& path, SharedLibrary* library)
239 REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700240 libraries_.Put(path, library);
241 }
242
243 // See section 11.3 "Linking Native Methods" of the JNI spec.
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700244 void* FindNativeMethod(Thread* self, ArtMethod* m, std::string& detail)
245 REQUIRES(!Locks::jni_libraries_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700246 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700247 std::string jni_short_name(m->JniShortName());
248 std::string jni_long_name(m->JniLongName());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800249 mirror::ClassLoader* const declaring_class_loader = m->GetDeclaringClass()->GetClassLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700250 ScopedObjectAccessUnchecked soa(Thread::Current());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800251 void* const declaring_class_loader_allocator =
252 Runtime::Current()->GetClassLinker()->GetAllocatorForClassLoader(declaring_class_loader);
253 CHECK(declaring_class_loader_allocator != nullptr);
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700254 // TODO: Avoid calling GetShorty here to prevent dirtying dex pages?
255 const char* shorty = m->GetShorty();
256 {
257 // Go to suspended since dlsym may block for a long time if other threads are using dlopen.
258 ScopedThreadSuspension sts(self, kNative);
259 void* native_code = FindNativeMethodInternal(self,
260 declaring_class_loader_allocator,
261 shorty,
262 jni_short_name,
263 jni_long_name);
264 if (native_code != nullptr) {
265 return native_code;
Ian Rogers68d8b422014-07-17 11:09:10 -0700266 }
267 }
268 detail += "No implementation found for ";
David Sehr709b0702016-10-13 09:12:37 -0700269 detail += m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700270 detail += " (tried " + jni_short_name + " and " + jni_long_name + ")";
Ian Rogers68d8b422014-07-17 11:09:10 -0700271 return nullptr;
272 }
273
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700274 void* FindNativeMethodInternal(Thread* self,
275 void* declaring_class_loader_allocator,
276 const char* shorty,
277 const std::string& jni_short_name,
278 const std::string& jni_long_name)
279 REQUIRES(!Locks::jni_libraries_lock_)
280 REQUIRES(!Locks::mutator_lock_) {
281 MutexLock mu(self, *Locks::jni_libraries_lock_);
282 for (const auto& lib : libraries_) {
283 SharedLibrary* const library = lib.second;
284 // Use the allocator address for class loader equality to avoid unnecessary weak root decode.
285 if (library->GetClassLoaderAllocator() != declaring_class_loader_allocator) {
286 // We only search libraries loaded by the appropriate ClassLoader.
287 continue;
288 }
289 // Try the short name then the long name...
290 const char* arg_shorty = library->NeedsNativeBridge() ? shorty : nullptr;
291 void* fn = library->FindSymbol(jni_short_name, arg_shorty);
292 if (fn == nullptr) {
293 fn = library->FindSymbol(jni_long_name, arg_shorty);
294 }
295 if (fn != nullptr) {
296 VLOG(jni) << "[Found native code for " << jni_long_name
297 << " in \"" << library->GetPath() << "\"]";
298 return fn;
299 }
300 }
301 return nullptr;
302 }
303
Mathieu Chartier598302a2015-09-23 14:52:39 -0700304 // Unload native libraries with cleared class loaders.
305 void UnloadNativeLibraries()
306 REQUIRES(!Locks::jni_libraries_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700307 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700308 Thread* const self = Thread::Current();
Alex Lightbc5669e2016-06-13 17:22:13 +0000309 std::vector<SharedLibrary*> unload_libraries;
Mathieu Chartier598302a2015-09-23 14:52:39 -0700310 {
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700311 MutexLock mu(self, *Locks::jni_libraries_lock_);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700312 for (auto it = libraries_.begin(); it != libraries_.end(); ) {
313 SharedLibrary* const library = it->second;
314 // If class loader is null then it was unloaded, call JNI_OnUnload.
Mathieu Chartiercffb7472015-09-28 10:33:00 -0700315 const jweak class_loader = library->GetClassLoader();
316 // If class_loader is a null jobject then it is the boot class loader. We should not unload
317 // the native libraries of the boot class loader.
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700318 if (class_loader != nullptr && self->IsJWeakCleared(class_loader)) {
Alex Lightbc5669e2016-06-13 17:22:13 +0000319 unload_libraries.push_back(library);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700320 it = libraries_.erase(it);
321 } else {
322 ++it;
323 }
324 }
325 }
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700326 ScopedThreadSuspension sts(self, kNative);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700327 // Do this without holding the jni libraries lock to prevent possible deadlocks.
Alex Lightbc5669e2016-06-13 17:22:13 +0000328 typedef void (*JNI_OnUnloadFn)(JavaVM*, void*);
329 for (auto library : unload_libraries) {
330 void* const sym = library->FindSymbol("JNI_OnUnload", nullptr);
331 if (sym == nullptr) {
332 VLOG(jni) << "[No JNI_OnUnload found in \"" << library->GetPath() << "\"]";
333 } else {
334 VLOG(jni) << "[JNI_OnUnload found for \"" << library->GetPath() << "\"]: Calling...";
335 JNI_OnUnloadFn jni_on_unload = reinterpret_cast<JNI_OnUnloadFn>(sym);
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700336 jni_on_unload(self->GetJniEnv()->vm, nullptr);
Alex Lightbc5669e2016-06-13 17:22:13 +0000337 }
338 delete library;
Mathieu Chartier598302a2015-09-23 14:52:39 -0700339 }
340 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700341
Mathieu Chartier598302a2015-09-23 14:52:39 -0700342 private:
343 AllocationTrackingSafeMap<std::string, SharedLibrary*, kAllocatorTagJNILibraries> libraries_
344 GUARDED_BY(Locks::jni_libraries_lock_);
345};
Ian Rogers68d8b422014-07-17 11:09:10 -0700346
347class JII {
348 public:
349 static jint DestroyJavaVM(JavaVM* vm) {
350 if (vm == nullptr) {
351 return JNI_ERR;
352 }
353 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
354 delete raw_vm->GetRuntime();
Dimitry Ivanov39d68ef2016-04-29 16:02:38 -0700355 android::ResetNativeLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700356 return JNI_OK;
357 }
358
359 static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
360 return AttachCurrentThreadInternal(vm, p_env, thr_args, false);
361 }
362
363 static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
364 return AttachCurrentThreadInternal(vm, p_env, thr_args, true);
365 }
366
367 static jint DetachCurrentThread(JavaVM* vm) {
368 if (vm == nullptr || Thread::Current() == nullptr) {
369 return JNI_ERR;
370 }
371 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
372 Runtime* runtime = raw_vm->GetRuntime();
373 runtime->DetachCurrentThread();
374 return JNI_OK;
375 }
376
377 static jint GetEnv(JavaVM* vm, void** env, jint version) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700378 if (vm == nullptr || env == nullptr) {
379 return JNI_ERR;
380 }
381 Thread* thread = Thread::Current();
382 if (thread == nullptr) {
383 *env = nullptr;
384 return JNI_EDETACHED;
385 }
Alex Light185d1342016-08-11 10:48:03 -0700386 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
387 return raw_vm->HandleGetEnv(env, version);
Ian Rogers68d8b422014-07-17 11:09:10 -0700388 }
389
390 private:
391 static jint AttachCurrentThreadInternal(JavaVM* vm, JNIEnv** p_env, void* raw_args, bool as_daemon) {
392 if (vm == nullptr || p_env == nullptr) {
393 return JNI_ERR;
394 }
395
396 // Return immediately if we're already attached.
397 Thread* self = Thread::Current();
398 if (self != nullptr) {
399 *p_env = self->GetJniEnv();
400 return JNI_OK;
401 }
402
403 Runtime* runtime = reinterpret_cast<JavaVMExt*>(vm)->GetRuntime();
404
405 // No threads allowed in zygote mode.
406 if (runtime->IsZygote()) {
407 LOG(ERROR) << "Attempt to attach a thread in the zygote";
408 return JNI_ERR;
409 }
410
411 JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(raw_args);
412 const char* thread_name = nullptr;
413 jobject thread_group = nullptr;
414 if (args != nullptr) {
Alex Light185d1342016-08-11 10:48:03 -0700415 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700416 LOG(ERROR) << "Bad JNI version passed to "
417 << (as_daemon ? "AttachCurrentThreadAsDaemon" : "AttachCurrentThread") << ": "
418 << args->version;
419 return JNI_EVERSION;
420 }
421 thread_name = args->name;
422 thread_group = args->group;
423 }
424
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800425 if (!runtime->AttachCurrentThread(thread_name, as_daemon, thread_group,
426 !runtime->IsAotCompiler())) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700427 *p_env = nullptr;
428 return JNI_ERR;
429 } else {
430 *p_env = Thread::Current()->GetJniEnv();
431 return JNI_OK;
432 }
433 }
434};
435
436const JNIInvokeInterface gJniInvokeInterface = {
437 nullptr, // reserved0
438 nullptr, // reserved1
439 nullptr, // reserved2
440 JII::DestroyJavaVM,
441 JII::AttachCurrentThread,
442 JII::DetachCurrentThread,
443 JII::GetEnv,
444 JII::AttachCurrentThreadAsDaemon
445};
446
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100447JavaVMExt::JavaVMExt(Runtime* runtime,
448 const RuntimeArgumentMap& runtime_options,
449 std::string* error_msg)
Ian Rogers68d8b422014-07-17 11:09:10 -0700450 : runtime_(runtime),
451 check_jni_abort_hook_(nullptr),
452 check_jni_abort_hook_data_(nullptr),
453 check_jni_(false), // Initialized properly in the constructor body below.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800454 force_copy_(runtime_options.Exists(RuntimeArgumentMap::JniOptsForceCopy)),
455 tracing_enabled_(runtime_options.Exists(RuntimeArgumentMap::JniTrace)
456 || VLOG_IS_ON(third_party_jni)),
457 trace_(runtime_options.GetOrDefault(RuntimeArgumentMap::JniTrace)),
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700458 globals_(kGlobalsMax, kGlobal, IndirectReferenceTable::ResizableCapacity::kNo, error_msg),
Ian Rogers68d8b422014-07-17 11:09:10 -0700459 libraries_(new Libraries),
460 unchecked_functions_(&gJniInvokeInterface),
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700461 weak_globals_(kWeakGlobalsMax,
462 kWeakGlobal,
463 IndirectReferenceTable::ResizableCapacity::kNo,
464 error_msg),
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700465 allow_accessing_weak_globals_(true),
Andreas Gampe05a364c2016-10-14 13:27:12 -0700466 weak_globals_add_condition_("weak globals add condition",
467 (CHECK(Locks::jni_weak_globals_lock_ != nullptr),
468 *Locks::jni_weak_globals_lock_)),
Alex Light185d1342016-08-11 10:48:03 -0700469 env_hooks_() {
Ian Rogers68d8b422014-07-17 11:09:10 -0700470 functions = unchecked_functions_;
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800471 SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni));
Ian Rogers68d8b422014-07-17 11:09:10 -0700472}
473
474JavaVMExt::~JavaVMExt() {
475}
476
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100477// Checking "globals" and "weak_globals" usually requires locks, but we
478// don't need the locks to check for validity when constructing the
479// object. Use NO_THREAD_SAFETY_ANALYSIS for this.
480std::unique_ptr<JavaVMExt> JavaVMExt::Create(Runtime* runtime,
481 const RuntimeArgumentMap& runtime_options,
482 std::string* error_msg) NO_THREAD_SAFETY_ANALYSIS {
483 std::unique_ptr<JavaVMExt> java_vm(new JavaVMExt(runtime, runtime_options, error_msg));
484 if (java_vm && java_vm->globals_.IsValid() && java_vm->weak_globals_.IsValid()) {
485 return java_vm;
486 }
487 return nullptr;
488}
489
Alex Light185d1342016-08-11 10:48:03 -0700490jint JavaVMExt::HandleGetEnv(/*out*/void** env, jint version) {
491 for (GetEnvHook hook : env_hooks_) {
492 jint res = hook(this, env, version);
493 if (res == JNI_OK) {
494 return JNI_OK;
495 } else if (res != JNI_EVERSION) {
496 LOG(ERROR) << "Error returned from a plugin GetEnv handler! " << res;
497 return res;
498 }
499 }
500 LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version;
501 return JNI_EVERSION;
502}
503
504// Add a hook to handle getting environments from the GetEnv call.
505void JavaVMExt::AddEnvironmentHook(GetEnvHook hook) {
506 CHECK(hook != nullptr) << "environment hooks shouldn't be null!";
507 env_hooks_.push_back(hook);
508}
509
Ian Rogers68d8b422014-07-17 11:09:10 -0700510void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) {
511 Thread* self = Thread::Current();
512 ScopedObjectAccess soa(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700513 ArtMethod* current_method = self->GetCurrentMethod(nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700514
515 std::ostringstream os;
516 os << "JNI DETECTED ERROR IN APPLICATION: " << msg;
517
518 if (jni_function_name != nullptr) {
519 os << "\n in call to " << jni_function_name;
520 }
521 // TODO: is this useful given that we're about to dump the calling thread's stack?
522 if (current_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700523 os << "\n from " << current_method->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700524 }
525 os << "\n";
526 self->Dump(os);
527
528 if (check_jni_abort_hook_ != nullptr) {
529 check_jni_abort_hook_(check_jni_abort_hook_data_, os.str());
530 } else {
531 // Ensure that we get a native stack trace for this thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700532 ScopedThreadSuspension sts(self, kNative);
Ian Rogers68d8b422014-07-17 11:09:10 -0700533 LOG(FATAL) << os.str();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700534 UNREACHABLE();
Ian Rogers68d8b422014-07-17 11:09:10 -0700535 }
536}
537
538void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) {
539 std::string msg;
540 StringAppendV(&msg, fmt, ap);
541 JniAbort(jni_function_name, msg.c_str());
542}
543
544void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) {
545 va_list args;
546 va_start(args, fmt);
547 JniAbortV(jni_function_name, fmt, args);
548 va_end(args);
549}
550
Mathieu Chartiere401d142015-04-22 13:56:20 -0700551bool JavaVMExt::ShouldTrace(ArtMethod* method) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700552 // Fast where no tracing is enabled.
553 if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) {
554 return false;
555 }
556 // Perform checks based on class name.
557 StringPiece class_name(method->GetDeclaringClassDescriptor());
558 if (!trace_.empty() && class_name.find(trace_) != std::string::npos) {
559 return true;
560 }
561 if (!VLOG_IS_ON(third_party_jni)) {
562 return false;
563 }
564 // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
565 // like part of Android.
566 static const char* gBuiltInPrefixes[] = {
567 "Landroid/",
568 "Lcom/android/",
569 "Lcom/google/android/",
570 "Ldalvik/",
571 "Ljava/",
572 "Ljavax/",
573 "Llibcore/",
574 "Lorg/apache/harmony/",
575 };
576 for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) {
577 if (class_name.starts_with(gBuiltInPrefixes[i])) {
578 return false;
579 }
580 }
581 return true;
582}
583
Mathieu Chartier0795f232016-09-27 18:43:30 -0700584jobject JavaVMExt::AddGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700585 // Check for null after decoding the object to handle cleared weak globals.
586 if (obj == nullptr) {
587 return nullptr;
588 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700589 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700590 IndirectRef ref = globals_.Add(kIRTFirstSegment, obj);
Ian Rogers68d8b422014-07-17 11:09:10 -0700591 return reinterpret_cast<jobject>(ref);
592}
593
Mathieu Chartier0795f232016-09-27 18:43:30 -0700594jweak JavaVMExt::AddWeakGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700595 if (obj == nullptr) {
596 return nullptr;
597 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700598 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchif1c6f872017-01-06 12:23:47 -0800599 // CMS needs this to block for concurrent reference processing because an object allocated during
600 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
601 // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant.
602 while (!kUseReadBarrier && UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700603 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
604 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800605 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700606 weak_globals_add_condition_.WaitHoldingLocks(self);
607 }
Andreas Gampee03662b2016-10-13 17:12:56 -0700608 IndirectRef ref = weak_globals_.Add(kIRTFirstSegment, obj);
Ian Rogers68d8b422014-07-17 11:09:10 -0700609 return reinterpret_cast<jweak>(ref);
610}
611
612void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
613 if (obj == nullptr) {
614 return;
615 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700616 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700617 if (!globals_.Remove(kIRTFirstSegment, obj)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700618 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
619 << "failed to find entry";
620 }
621}
622
623void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
624 if (obj == nullptr) {
625 return;
626 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700627 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700628 if (!weak_globals_.Remove(kIRTFirstSegment, obj)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700629 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
630 << "failed to find entry";
631 }
632}
633
634static void ThreadEnableCheckJni(Thread* thread, void* arg) {
635 bool* check_jni = reinterpret_cast<bool*>(arg);
636 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
637}
638
639bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
640 bool old_check_jni = check_jni_;
641 check_jni_ = enabled;
642 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
643 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
644 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
645 return old_check_jni;
646}
647
648void JavaVMExt::DumpForSigQuit(std::ostream& os) {
649 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
650 if (force_copy_) {
651 os << " (with forcecopy)";
652 }
653 Thread* self = Thread::Current();
654 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700655 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700656 os << "; globals=" << globals_.Capacity();
657 }
658 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700659 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700660 if (weak_globals_.Capacity() > 0) {
661 os << " (plus " << weak_globals_.Capacity() << " weak)";
662 }
663 }
664 os << '\n';
665
666 {
667 MutexLock mu(self, *Locks::jni_libraries_lock_);
668 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
669 }
670}
671
672void JavaVMExt::DisallowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700673 CHECK(!kUseReadBarrier);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700674 Thread* const self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700675 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700676 // DisallowNewWeakGlobals is only called by CMS during the pause. It is required to have the
677 // mutator lock exclusively held so that we don't have any threads in the middle of
678 // DecodeWeakGlobal.
679 Locks::mutator_lock_->AssertExclusiveHeld(self);
680 allow_accessing_weak_globals_.StoreSequentiallyConsistent(false);
Ian Rogers68d8b422014-07-17 11:09:10 -0700681}
682
683void JavaVMExt::AllowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700684 CHECK(!kUseReadBarrier);
Ian Rogers68d8b422014-07-17 11:09:10 -0700685 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700686 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700687 allow_accessing_weak_globals_.StoreSequentiallyConsistent(true);
Ian Rogers68d8b422014-07-17 11:09:10 -0700688 weak_globals_add_condition_.Broadcast(self);
689}
690
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700691void JavaVMExt::BroadcastForNewWeakGlobals() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700692 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700693 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700694 weak_globals_add_condition_.Broadcast(self);
695}
696
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700697ObjPtr<mirror::Object> JavaVMExt::DecodeGlobal(IndirectRef ref) {
698 return globals_.SynchronizedGet(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700699}
700
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700701void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700702 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700703 globals_.Update(ref, result);
704}
705
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700706inline bool JavaVMExt::MayAccessWeakGlobals(Thread* self) const {
707 return MayAccessWeakGlobalsUnlocked(self);
708}
709
710inline bool JavaVMExt::MayAccessWeakGlobalsUnlocked(Thread* self) const {
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700711 DCHECK(self != nullptr);
712 return kUseReadBarrier ?
713 self->GetWeakRefAccessEnabled() :
714 allow_accessing_weak_globals_.LoadSequentiallyConsistent();
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700715}
716
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700717ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700718 // It is safe to access GetWeakRefAccessEnabled without the lock since CC uses checkpoints to call
719 // SetWeakRefAccessEnabled, and the other collectors only modify allow_accessing_weak_globals_
720 // when the mutators are paused.
721 // This only applies in the case where MayAccessWeakGlobals goes from false to true. In the other
722 // case, it may be racy, this is benign since DecodeWeakGlobalLocked does the correct behavior
723 // if MayAccessWeakGlobals is false.
Andreas Gampedc061d02016-10-24 13:19:37 -0700724 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700725 if (LIKELY(MayAccessWeakGlobalsUnlocked(self))) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700726 return weak_globals_.SynchronizedGet(ref);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700727 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700728 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700729 return DecodeWeakGlobalLocked(self, ref);
730}
731
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700732ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalLocked(Thread* self, IndirectRef ref) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700733 if (kDebugLocking) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700734 Locks::jni_weak_globals_lock_->AssertHeld(self);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700735 }
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700736 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700737 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
738 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800739 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700740 weak_globals_add_condition_.WaitHoldingLocks(self);
741 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700742 return weak_globals_.Get(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700743}
744
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700745ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalDuringShutdown(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700746 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700747 DCHECK(Runtime::Current()->IsShuttingDown(self));
748 if (self != nullptr) {
749 return DecodeWeakGlobal(self, ref);
750 }
751 // self can be null during a runtime shutdown. ~Runtime()->~ClassLinker()->DecodeWeakGlobal().
752 if (!kUseReadBarrier) {
753 DCHECK(allow_accessing_weak_globals_.LoadSequentiallyConsistent());
754 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700755 return weak_globals_.SynchronizedGet(ref);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700756}
757
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800758bool JavaVMExt::IsWeakGlobalCleared(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700759 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Andreas Gampe05a364c2016-10-14 13:27:12 -0700760 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800761 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700762 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
763 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800764 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800765 weak_globals_add_condition_.WaitHoldingLocks(self);
766 }
767 // When just checking a weak ref has been cleared, avoid triggering the read barrier in decode
768 // (DecodeWeakGlobal) so that we won't accidentally mark the object alive. Since the cleared
769 // sentinel is a non-moving object, we can compare the ref to it without the read barrier and
770 // decide if it's cleared.
771 return Runtime::Current()->IsClearedJniWeakGlobal(weak_globals_.Get<kWithoutReadBarrier>(ref));
772}
773
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700774void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700775 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700776 weak_globals_.Update(ref, result);
777}
778
Ian Rogers68d8b422014-07-17 11:09:10 -0700779void JavaVMExt::DumpReferenceTables(std::ostream& os) {
780 Thread* self = Thread::Current();
781 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700782 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700783 globals_.Dump(os);
784 }
785 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700786 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700787 weak_globals_.Dump(os);
788 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700789}
790
Mathieu Chartier598302a2015-09-23 14:52:39 -0700791void JavaVMExt::UnloadNativeLibraries() {
792 libraries_.get()->UnloadNativeLibraries();
793}
794
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800795bool JavaVMExt::LoadNativeLibrary(JNIEnv* env,
796 const std::string& path,
797 jobject class_loader,
798 jstring library_path,
799 std::string* error_msg) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700800 error_msg->clear();
801
802 // See if we've already loaded this library. If we have, and the class loader
803 // matches, return successfully without doing anything.
804 // TODO: for better results we should canonicalize the pathname (or even compare
805 // inodes). This implementation is fine if everybody is using System.loadLibrary.
806 SharedLibrary* library;
807 Thread* self = Thread::Current();
808 {
809 // TODO: move the locking (and more of this logic) into Libraries.
810 MutexLock mu(self, *Locks::jni_libraries_lock_);
811 library = libraries_->Get(path);
812 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800813 void* class_loader_allocator = nullptr;
814 {
815 ScopedObjectAccess soa(env);
816 // As the incoming class loader is reachable/alive during the call of this function,
817 // it's okay to decode it without worrying about unexpectedly marking it alive.
Mathieu Chartier0795f232016-09-27 18:43:30 -0700818 ObjPtr<mirror::ClassLoader> loader = soa.Decode<mirror::ClassLoader>(class_loader);
Andreas Gampe2d48e532016-06-17 12:46:14 -0700819
820 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700821 if (class_linker->IsBootClassLoader(soa, loader.Ptr())) {
Andreas Gampe2d48e532016-06-17 12:46:14 -0700822 loader = nullptr;
823 class_loader = nullptr;
824 }
825
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700826 class_loader_allocator = class_linker->GetAllocatorForClassLoader(loader.Ptr());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800827 CHECK(class_loader_allocator != nullptr);
828 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700829 if (library != nullptr) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800830 // Use the allocator pointers for class loader equality to avoid unnecessary weak root decode.
831 if (library->GetClassLoaderAllocator() != class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700832 // The library will be associated with class_loader. The JNI
833 // spec says we can't load the same library into more than one
834 // class loader.
835 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
836 "ClassLoader %p; can't open in ClassLoader %p",
837 path.c_str(), library->GetClassLoader(), class_loader);
838 LOG(WARNING) << error_msg;
839 return false;
840 }
841 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
842 << " ClassLoader " << class_loader << "]";
843 if (!library->CheckOnLoadResult()) {
844 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
845 "to load \"%s\"", path.c_str());
846 return false;
847 }
848 return true;
849 }
850
851 // Open the shared library. Because we're using a full path, the system
852 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
853 // resolve this library's dependencies though.)
854
855 // Failures here are expected when java.library.path has several entries
856 // and we have to hunt for the lib.
857
858 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
859 // class unloading. Libraries will only be unloaded when the reference count (incremented by
860 // dlopen) becomes zero from dlclose.
861
862 Locks::mutator_lock_->AssertNotHeld(self);
863 const char* path_str = path.empty() ? nullptr : path.c_str();
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800864 bool needs_native_bridge = false;
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800865 void* handle = android::OpenNativeLibrary(env,
866 runtime_->GetTargetSdkVersion(),
867 path_str,
868 class_loader,
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800869 library_path,
870 &needs_native_bridge,
871 error_msg);
Ian Rogers68d8b422014-07-17 11:09:10 -0700872
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700873 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]";
Ian Rogers68d8b422014-07-17 11:09:10 -0700874
875 if (handle == nullptr) {
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700876 VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700877 return false;
878 }
879
880 if (env->ExceptionCheck() == JNI_TRUE) {
881 LOG(ERROR) << "Unexpected exception:";
882 env->ExceptionDescribe();
883 env->ExceptionClear();
884 }
885 // Create a new entry.
886 // TODO: move the locking (and more of this logic) into Libraries.
887 bool created_library = false;
888 {
889 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
890 std::unique_ptr<SharedLibrary> new_library(
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800891 new SharedLibrary(env,
892 self,
893 path,
894 handle,
895 needs_native_bridge,
896 class_loader,
897 class_loader_allocator));
898
Ian Rogers68d8b422014-07-17 11:09:10 -0700899 MutexLock mu(self, *Locks::jni_libraries_lock_);
900 library = libraries_->Get(path);
901 if (library == nullptr) { // We won race to get libraries_lock.
902 library = new_library.release();
903 libraries_->Put(path, library);
904 created_library = true;
905 }
906 }
907 if (!created_library) {
908 LOG(INFO) << "WOW: we lost a race to add shared library: "
909 << "\"" << path << "\" ClassLoader=" << class_loader;
910 return library->CheckOnLoadResult();
911 }
912 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
913
914 bool was_successful = false;
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800915 void* sym = library->FindSymbol("JNI_OnLoad", nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700916 if (sym == nullptr) {
917 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
918 was_successful = true;
919 } else {
920 // Call JNI_OnLoad. We have to override the current class
921 // loader, which will always be "null" since the stuff at the
922 // top of the stack is around Runtime.loadLibrary(). (See
923 // the comments in the JNI FindClass function.)
924 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
925 self->SetClassLoaderOverride(class_loader);
926
927 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
928 typedef int (*JNI_OnLoadFn)(JavaVM*, void*);
929 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
930 int version = (*jni_on_load)(this, nullptr);
931
Mathieu Chartierd0004802014-10-15 16:59:47 -0700932 if (runtime_->GetTargetSdkVersion() != 0 && runtime_->GetTargetSdkVersion() <= 21) {
Josh Gao85a78cf2017-03-20 16:26:42 -0700933 // Make sure that sigchain owns SIGSEGV.
934 EnsureFrontOfChain(SIGSEGV);
Mathieu Chartierd0004802014-10-15 16:59:47 -0700935 }
936
Ian Rogers68d8b422014-07-17 11:09:10 -0700937 self->SetClassLoaderOverride(old_class_loader.get());
938
939 if (version == JNI_ERR) {
940 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
Alex Light185d1342016-08-11 10:48:03 -0700941 } else if (JavaVMExt::IsBadJniVersion(version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700942 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
943 path.c_str(), version);
944 // It's unwise to call dlclose() here, but we can mark it
945 // as bad and ensure that future load attempts will fail.
946 // We don't know how far JNI_OnLoad got, so there could
947 // be some partially-initialized stuff accessible through
948 // newly-registered native method calls. We could try to
949 // unregister them, but that doesn't seem worthwhile.
950 } else {
951 was_successful = true;
952 }
953 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
954 << " from JNI_OnLoad in \"" << path << "\"]";
955 }
956
957 library->SetResult(was_successful);
958 return was_successful;
959}
960
Alex Light65af20b2017-04-20 09:15:08 -0700961static void* FindCodeForNativeMethodInAgents(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
962 std::string jni_short_name(m->JniShortName());
963 std::string jni_long_name(m->JniLongName());
964 for (const ti::Agent& agent : Runtime::Current()->GetAgents()) {
965 void* fn = agent.FindSymbol(jni_short_name);
966 if (fn != nullptr) {
967 VLOG(jni) << "Found implementation for " << m->PrettyMethod()
968 << " (symbol: " << jni_short_name << ") in " << agent;
969 return fn;
970 }
971 fn = agent.FindSymbol(jni_long_name);
972 if (fn != nullptr) {
973 VLOG(jni) << "Found implementation for " << m->PrettyMethod()
974 << " (symbol: " << jni_long_name << ") in " << agent;
975 return fn;
976 }
977 }
978 return nullptr;
979}
980
Mathieu Chartiere401d142015-04-22 13:56:20 -0700981void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700982 CHECK(m->IsNative());
983 mirror::Class* c = m->GetDeclaringClass();
984 // If this is a static method, it could be called before the class has been initialized.
David Sehr709b0702016-10-13 09:12:37 -0700985 CHECK(c->IsInitializing()) << c->GetStatus() << " " << m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700986 std::string detail;
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700987 Thread* const self = Thread::Current();
988 void* native_method = libraries_->FindNativeMethod(self, m, detail);
Alex Light65af20b2017-04-20 09:15:08 -0700989 if (native_method == nullptr) {
990 // Lookup JNI native methods from native TI Agent libraries. See runtime/ti/agent.h for more
991 // information. Agent libraries are searched for native methods after all jni libraries.
992 native_method = FindCodeForNativeMethodInAgents(m);
993 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700994 // Throwing can cause libraries_lock to be reacquired.
995 if (native_method == nullptr) {
Alex Light65af20b2017-04-20 09:15:08 -0700996 LOG(ERROR) << detail;
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000997 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
Ian Rogers68d8b422014-07-17 11:09:10 -0700998 }
999 return native_method;
1000}
1001
Mathieu Chartier97509952015-07-13 14:35:43 -07001002void JavaVMExt::SweepJniWeakGlobals(IsMarkedVisitor* visitor) {
Andreas Gampe05a364c2016-10-14 13:27:12 -07001003 MutexLock mu(Thread::Current(), *Locks::jni_weak_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001004 Runtime* const runtime = Runtime::Current();
1005 for (auto* entry : weak_globals_) {
1006 // Need to skip null here to distinguish between null entries and cleared weak ref entries.
1007 if (!entry->IsNull()) {
1008 // Since this is called by the GC, we don't need a read barrier.
1009 mirror::Object* obj = entry->Read<kWithoutReadBarrier>();
Mathieu Chartier97509952015-07-13 14:35:43 -07001010 mirror::Object* new_obj = visitor->IsMarked(obj);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001011 if (new_obj == nullptr) {
1012 new_obj = runtime->GetClearedJniWeakGlobal();
1013 }
1014 *entry = GcRoot<mirror::Object>(new_obj);
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -07001015 }
Ian Rogers68d8b422014-07-17 11:09:10 -07001016 }
1017}
1018
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001019void JavaVMExt::TrimGlobals() {
Andreas Gampe05a364c2016-10-14 13:27:12 -07001020 WriterMutexLock mu(Thread::Current(), *Locks::jni_globals_lock_);
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001021 globals_.Trim();
1022}
1023
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001024void JavaVMExt::VisitRoots(RootVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001025 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -07001026 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001027 globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal));
Ian Rogers68d8b422014-07-17 11:09:10 -07001028 // The weak_globals table is visited by the GC itself (because it mutates the table).
1029}
1030
1031// JNI Invocation interface.
1032
1033extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001034 ScopedTrace trace(__FUNCTION__);
Ian Rogers68d8b422014-07-17 11:09:10 -07001035 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
Alex Light185d1342016-08-11 10:48:03 -07001036 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001037 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
1038 return JNI_EVERSION;
1039 }
1040 RuntimeOptions options;
1041 for (int i = 0; i < args->nOptions; ++i) {
1042 JavaVMOption* option = &args->options[i];
1043 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
1044 }
1045 bool ignore_unrecognized = args->ignoreUnrecognized;
1046 if (!Runtime::Create(options, ignore_unrecognized)) {
1047 return JNI_ERR;
1048 }
Dimitry Ivanovc544f342016-05-09 16:26:13 -07001049
1050 // Initialize native loader. This step makes sure we have
1051 // everything set up before we start using JNI.
1052 android::InitializeNativeLoader();
1053
Ian Rogers68d8b422014-07-17 11:09:10 -07001054 Runtime* runtime = Runtime::Current();
1055 bool started = runtime->Start();
1056 if (!started) {
1057 delete Thread::Current()->GetJniEnv();
1058 delete runtime->GetJavaVM();
1059 LOG(WARNING) << "CreateJavaVM failed";
1060 return JNI_ERR;
1061 }
Dimitry Ivanov041169f2016-04-21 16:01:24 -07001062
Ian Rogers68d8b422014-07-17 11:09:10 -07001063 *p_env = Thread::Current()->GetJniEnv();
1064 *p_vm = runtime->GetJavaVM();
1065 return JNI_OK;
1066}
1067
Ian Rogersf4d4da12014-11-11 16:10:33 -08001068extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001069 Runtime* runtime = Runtime::Current();
Ian Rogersf4d4da12014-11-11 16:10:33 -08001070 if (runtime == nullptr || buf_len == 0) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001071 *vm_count = 0;
1072 } else {
1073 *vm_count = 1;
Ian Rogersf4d4da12014-11-11 16:10:33 -08001074 vms_buf[0] = runtime->GetJavaVM();
Ian Rogers68d8b422014-07-17 11:09:10 -07001075 }
1076 return JNI_OK;
1077}
1078
1079// Historically unsupported.
1080extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
1081 return JNI_ERR;
1082}
1083
1084} // namespace art