blob: 267f9fdc992b0c05ffb38649a156ebcc1e515937 [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
Andreas Gampe57cf00b2017-06-05 17:15:32 -070017#include "java_vm_ext.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070018
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"
Andreas Gampe57cf00b2017-06-05 17:15:32 -070033#include "jni_internal.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070034#include "mirror/class-inl.h"
35#include "mirror/class_loader.h"
Calin Juravlec8423522014-08-12 20:55:20 +010036#include "nativebridge/native_bridge.h"
Steven Morelande431e272017-07-18 16:53:49 -070037#include "nativehelper/ScopedLocalRef.h"
Dmitriy Ivanovf5a30992015-11-11 14:18:55 -080038#include "nativeloader/native_loader.h"
Andreas Gampe57cf00b2017-06-05 17:15:32 -070039#include "object_callbacks.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070040#include "parsed_options.h"
Ian Rogersc0542af2014-09-03 16:16:56 -070041#include "runtime-inl.h"
Igor Murashkinaaebaa02015-01-26 10:55:53 -080042#include "runtime_options.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070043#include "scoped_thread_state_change-inl.h"
Josh Gao85a78cf2017-03-20 16:26:42 -070044#include "sigchain.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070045#include "thread-inl.h"
46#include "thread_list.h"
Steven Morelande431e272017-07-18 16:53:49 -070047#include "ti/agent.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070048
49namespace art {
50
Andreas Gampe46ee31b2016-12-14 10:11:49 -080051using android::base::StringAppendF;
52using android::base::StringAppendV;
53
Andreas Gampea8e3b862016-10-17 20:12:52 -070054static constexpr size_t kGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
Ian Rogers68d8b422014-07-17 11:09:10 -070055
Andreas Gampea8e3b862016-10-17 20:12:52 -070056static constexpr size_t kWeakGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
Ian Rogers68d8b422014-07-17 11:09:10 -070057
Alex Light185d1342016-08-11 10:48:03 -070058bool JavaVMExt::IsBadJniVersion(int version) {
Ian Rogers68d8b422014-07-17 11:09:10 -070059 // We don't support JNI_VERSION_1_1. These are the only other valid versions.
60 return version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 && version != JNI_VERSION_1_6;
61}
62
63class SharedLibrary {
64 public:
65 SharedLibrary(JNIEnv* env, Thread* self, const std::string& path, void* handle,
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080066 bool needs_native_bridge, jobject class_loader, void* class_loader_allocator)
Ian Rogers68d8b422014-07-17 11:09:10 -070067 : path_(path),
68 handle_(handle),
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080069 needs_native_bridge_(needs_native_bridge),
Mathieu Chartier598302a2015-09-23 14:52:39 -070070 class_loader_(env->NewWeakGlobalRef(class_loader)),
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080071 class_loader_allocator_(class_loader_allocator),
Ian Rogers68d8b422014-07-17 11:09:10 -070072 jni_on_load_lock_("JNI_OnLoad lock"),
73 jni_on_load_cond_("JNI_OnLoad condition variable", jni_on_load_lock_),
74 jni_on_load_thread_id_(self->GetThreadId()),
75 jni_on_load_result_(kPending) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080076 CHECK(class_loader_allocator_ != nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -070077 }
78
79 ~SharedLibrary() {
80 Thread* self = Thread::Current();
81 if (self != nullptr) {
Mathieu Chartier598302a2015-09-23 14:52:39 -070082 self->GetJniEnv()->DeleteWeakGlobalRef(class_loader_);
Ian Rogers68d8b422014-07-17 11:09:10 -070083 }
Alex Lightbc5669e2016-06-13 17:22:13 +000084
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080085 android::CloseNativeLibrary(handle_, needs_native_bridge_);
Ian Rogers68d8b422014-07-17 11:09:10 -070086 }
87
Mathieu Chartier598302a2015-09-23 14:52:39 -070088 jweak GetClassLoader() const {
Ian Rogers68d8b422014-07-17 11:09:10 -070089 return class_loader_;
90 }
91
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080092 const void* GetClassLoaderAllocator() const {
93 return class_loader_allocator_;
94 }
95
Ian Rogers68d8b422014-07-17 11:09:10 -070096 const std::string& GetPath() const {
97 return path_;
98 }
99
100 /*
101 * Check the result of an earlier call to JNI_OnLoad on this library.
102 * If the call has not yet finished in another thread, wait for it.
103 */
104 bool CheckOnLoadResult()
Mathieu Chartier90443472015-07-16 20:32:27 -0700105 REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700106 Thread* self = Thread::Current();
107 bool okay;
108 {
109 MutexLock mu(self, jni_on_load_lock_);
110
111 if (jni_on_load_thread_id_ == self->GetThreadId()) {
112 // Check this so we don't end up waiting for ourselves. We need to return "true" so the
113 // caller can continue.
114 LOG(INFO) << *self << " recursive attempt to load library " << "\"" << path_ << "\"";
115 okay = true;
116 } else {
117 while (jni_on_load_result_ == kPending) {
118 VLOG(jni) << "[" << *self << " waiting for \"" << path_ << "\" " << "JNI_OnLoad...]";
119 jni_on_load_cond_.Wait(self);
120 }
121
122 okay = (jni_on_load_result_ == kOkay);
123 VLOG(jni) << "[Earlier JNI_OnLoad for \"" << path_ << "\" "
124 << (okay ? "succeeded" : "failed") << "]";
125 }
126 }
127 return okay;
128 }
129
Mathieu Chartier90443472015-07-16 20:32:27 -0700130 void SetResult(bool result) REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700131 Thread* self = Thread::Current();
132 MutexLock mu(self, jni_on_load_lock_);
133
134 jni_on_load_result_ = result ? kOkay : kFailed;
135 jni_on_load_thread_id_ = 0;
136
137 // Broadcast a wakeup to anybody sleeping on the condition variable.
138 jni_on_load_cond_.Broadcast(self);
139 }
140
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800141 void SetNeedsNativeBridge(bool needs) {
142 needs_native_bridge_ = needs;
Ian Rogers68d8b422014-07-17 11:09:10 -0700143 }
144
145 bool NeedsNativeBridge() const {
146 return needs_native_bridge_;
147 }
148
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700149 // No mutator lock since dlsym may block for a while if another thread is doing dlopen.
150 void* FindSymbol(const std::string& symbol_name, const char* shorty = nullptr)
151 REQUIRES(!Locks::mutator_lock_) {
Mathieu Chartier598302a2015-09-23 14:52:39 -0700152 return NeedsNativeBridge()
153 ? FindSymbolWithNativeBridge(symbol_name.c_str(), shorty)
154 : FindSymbolWithoutNativeBridge(symbol_name.c_str());
155 }
156
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700157 // No mutator lock since dlsym may block for a while if another thread is doing dlopen.
158 void* FindSymbolWithoutNativeBridge(const std::string& symbol_name)
159 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe8fec90b2015-06-30 11:23:44 -0700160 CHECK(!NeedsNativeBridge());
161
Ian Rogers68d8b422014-07-17 11:09:10 -0700162 return dlsym(handle_, symbol_name.c_str());
163 }
164
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700165 void* FindSymbolWithNativeBridge(const std::string& symbol_name, const char* shorty)
166 REQUIRES(!Locks::mutator_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700167 CHECK(NeedsNativeBridge());
168
169 uint32_t len = 0;
Calin Juravlec8423522014-08-12 20:55:20 +0100170 return android::NativeBridgeGetTrampoline(handle_, symbol_name.c_str(), shorty, len);
Ian Rogers68d8b422014-07-17 11:09:10 -0700171 }
172
173 private:
174 enum JNI_OnLoadState {
175 kPending,
176 kFailed,
177 kOkay,
178 };
179
180 // Path to library "/system/lib/libjni.so".
181 const std::string path_;
182
183 // The void* returned by dlopen(3).
184 void* const handle_;
185
186 // True if a native bridge is required.
187 bool needs_native_bridge_;
188
Mathieu Chartier598302a2015-09-23 14:52:39 -0700189 // The ClassLoader this library is associated with, a weak global JNI reference that is
Ian Rogers68d8b422014-07-17 11:09:10 -0700190 // created/deleted with the scope of the library.
Mathieu Chartier598302a2015-09-23 14:52:39 -0700191 const jweak class_loader_;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800192 // Used to do equality check on class loaders so we can avoid decoding the weak root and read
193 // barriers that mess with class unloading.
194 const void* class_loader_allocator_;
Ian Rogers68d8b422014-07-17 11:09:10 -0700195
196 // Guards remaining items.
197 Mutex jni_on_load_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
198 // Wait for JNI_OnLoad in other thread.
199 ConditionVariable jni_on_load_cond_ GUARDED_BY(jni_on_load_lock_);
200 // Recursive invocation guard.
201 uint32_t jni_on_load_thread_id_ GUARDED_BY(jni_on_load_lock_);
202 // Result of earlier JNI_OnLoad call.
203 JNI_OnLoadState jni_on_load_result_ GUARDED_BY(jni_on_load_lock_);
204};
205
206// This exists mainly to keep implementation details out of the header file.
207class Libraries {
208 public:
209 Libraries() {
210 }
211
212 ~Libraries() {
213 STLDeleteValues(&libraries_);
214 }
215
Mathieu Chartier598302a2015-09-23 14:52:39 -0700216 // NO_THREAD_SAFETY_ANALYSIS since this may be called from Dumpable. Dumpable can't be annotated
217 // properly due to the template. The caller should be holding the jni_libraries_lock_.
218 void Dump(std::ostream& os) const NO_THREAD_SAFETY_ANALYSIS {
219 Locks::jni_libraries_lock_->AssertHeld(Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -0700220 bool first = true;
221 for (const auto& library : libraries_) {
222 if (!first) {
223 os << ' ';
224 }
225 first = false;
226 os << library.first;
227 }
228 }
229
Mathieu Chartier598302a2015-09-23 14:52:39 -0700230 size_t size() const REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700231 return libraries_.size();
232 }
233
Mathieu Chartier598302a2015-09-23 14:52:39 -0700234 SharedLibrary* Get(const std::string& path) REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700235 auto it = libraries_.find(path);
236 return (it == libraries_.end()) ? nullptr : it->second;
237 }
238
Mathieu Chartier598302a2015-09-23 14:52:39 -0700239 void Put(const std::string& path, SharedLibrary* library)
240 REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700241 libraries_.Put(path, library);
242 }
243
244 // See section 11.3 "Linking Native Methods" of the JNI spec.
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700245 void* FindNativeMethod(Thread* self, ArtMethod* m, std::string& detail)
246 REQUIRES(!Locks::jni_libraries_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700247 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700248 std::string jni_short_name(m->JniShortName());
249 std::string jni_long_name(m->JniLongName());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800250 mirror::ClassLoader* const declaring_class_loader = m->GetDeclaringClass()->GetClassLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700251 ScopedObjectAccessUnchecked soa(Thread::Current());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800252 void* const declaring_class_loader_allocator =
253 Runtime::Current()->GetClassLinker()->GetAllocatorForClassLoader(declaring_class_loader);
254 CHECK(declaring_class_loader_allocator != nullptr);
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700255 // TODO: Avoid calling GetShorty here to prevent dirtying dex pages?
256 const char* shorty = m->GetShorty();
257 {
258 // Go to suspended since dlsym may block for a long time if other threads are using dlopen.
259 ScopedThreadSuspension sts(self, kNative);
260 void* native_code = FindNativeMethodInternal(self,
261 declaring_class_loader_allocator,
262 shorty,
263 jni_short_name,
264 jni_long_name);
265 if (native_code != nullptr) {
266 return native_code;
Ian Rogers68d8b422014-07-17 11:09:10 -0700267 }
268 }
269 detail += "No implementation found for ";
David Sehr709b0702016-10-13 09:12:37 -0700270 detail += m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700271 detail += " (tried " + jni_short_name + " and " + jni_long_name + ")";
Ian Rogers68d8b422014-07-17 11:09:10 -0700272 return nullptr;
273 }
274
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700275 void* FindNativeMethodInternal(Thread* self,
276 void* declaring_class_loader_allocator,
277 const char* shorty,
278 const std::string& jni_short_name,
279 const std::string& jni_long_name)
280 REQUIRES(!Locks::jni_libraries_lock_)
281 REQUIRES(!Locks::mutator_lock_) {
282 MutexLock mu(self, *Locks::jni_libraries_lock_);
283 for (const auto& lib : libraries_) {
284 SharedLibrary* const library = lib.second;
285 // Use the allocator address for class loader equality to avoid unnecessary weak root decode.
286 if (library->GetClassLoaderAllocator() != declaring_class_loader_allocator) {
287 // We only search libraries loaded by the appropriate ClassLoader.
288 continue;
289 }
290 // Try the short name then the long name...
291 const char* arg_shorty = library->NeedsNativeBridge() ? shorty : nullptr;
292 void* fn = library->FindSymbol(jni_short_name, arg_shorty);
293 if (fn == nullptr) {
294 fn = library->FindSymbol(jni_long_name, arg_shorty);
295 }
296 if (fn != nullptr) {
297 VLOG(jni) << "[Found native code for " << jni_long_name
298 << " in \"" << library->GetPath() << "\"]";
299 return fn;
300 }
301 }
302 return nullptr;
303 }
304
Mathieu Chartier598302a2015-09-23 14:52:39 -0700305 // Unload native libraries with cleared class loaders.
306 void UnloadNativeLibraries()
307 REQUIRES(!Locks::jni_libraries_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700308 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700309 Thread* const self = Thread::Current();
Alex Lightbc5669e2016-06-13 17:22:13 +0000310 std::vector<SharedLibrary*> unload_libraries;
Mathieu Chartier598302a2015-09-23 14:52:39 -0700311 {
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700312 MutexLock mu(self, *Locks::jni_libraries_lock_);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700313 for (auto it = libraries_.begin(); it != libraries_.end(); ) {
314 SharedLibrary* const library = it->second;
315 // If class loader is null then it was unloaded, call JNI_OnUnload.
Mathieu Chartiercffb7472015-09-28 10:33:00 -0700316 const jweak class_loader = library->GetClassLoader();
317 // If class_loader is a null jobject then it is the boot class loader. We should not unload
318 // the native libraries of the boot class loader.
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700319 if (class_loader != nullptr && self->IsJWeakCleared(class_loader)) {
Alex Lightbc5669e2016-06-13 17:22:13 +0000320 unload_libraries.push_back(library);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700321 it = libraries_.erase(it);
322 } else {
323 ++it;
324 }
325 }
326 }
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700327 ScopedThreadSuspension sts(self, kNative);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700328 // Do this without holding the jni libraries lock to prevent possible deadlocks.
Alex Lightbc5669e2016-06-13 17:22:13 +0000329 typedef void (*JNI_OnUnloadFn)(JavaVM*, void*);
330 for (auto library : unload_libraries) {
331 void* const sym = library->FindSymbol("JNI_OnUnload", nullptr);
332 if (sym == nullptr) {
333 VLOG(jni) << "[No JNI_OnUnload found in \"" << library->GetPath() << "\"]";
334 } else {
335 VLOG(jni) << "[JNI_OnUnload found for \"" << library->GetPath() << "\"]: Calling...";
336 JNI_OnUnloadFn jni_on_unload = reinterpret_cast<JNI_OnUnloadFn>(sym);
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700337 jni_on_unload(self->GetJniEnv()->vm, nullptr);
Alex Lightbc5669e2016-06-13 17:22:13 +0000338 }
339 delete library;
Mathieu Chartier598302a2015-09-23 14:52:39 -0700340 }
341 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700342
Mathieu Chartier598302a2015-09-23 14:52:39 -0700343 private:
344 AllocationTrackingSafeMap<std::string, SharedLibrary*, kAllocatorTagJNILibraries> libraries_
345 GUARDED_BY(Locks::jni_libraries_lock_);
346};
Ian Rogers68d8b422014-07-17 11:09:10 -0700347
348class JII {
349 public:
350 static jint DestroyJavaVM(JavaVM* vm) {
351 if (vm == nullptr) {
352 return JNI_ERR;
353 }
354 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
355 delete raw_vm->GetRuntime();
Dimitry Ivanov39d68ef2016-04-29 16:02:38 -0700356 android::ResetNativeLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700357 return JNI_OK;
358 }
359
360 static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
361 return AttachCurrentThreadInternal(vm, p_env, thr_args, false);
362 }
363
364 static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
365 return AttachCurrentThreadInternal(vm, p_env, thr_args, true);
366 }
367
368 static jint DetachCurrentThread(JavaVM* vm) {
369 if (vm == nullptr || Thread::Current() == nullptr) {
370 return JNI_ERR;
371 }
372 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
373 Runtime* runtime = raw_vm->GetRuntime();
374 runtime->DetachCurrentThread();
375 return JNI_OK;
376 }
377
378 static jint GetEnv(JavaVM* vm, void** env, jint version) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700379 if (vm == nullptr || env == nullptr) {
380 return JNI_ERR;
381 }
382 Thread* thread = Thread::Current();
383 if (thread == nullptr) {
384 *env = nullptr;
385 return JNI_EDETACHED;
386 }
Alex Light185d1342016-08-11 10:48:03 -0700387 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
388 return raw_vm->HandleGetEnv(env, version);
Ian Rogers68d8b422014-07-17 11:09:10 -0700389 }
390
391 private:
392 static jint AttachCurrentThreadInternal(JavaVM* vm, JNIEnv** p_env, void* raw_args, bool as_daemon) {
393 if (vm == nullptr || p_env == nullptr) {
394 return JNI_ERR;
395 }
396
397 // Return immediately if we're already attached.
398 Thread* self = Thread::Current();
399 if (self != nullptr) {
400 *p_env = self->GetJniEnv();
401 return JNI_OK;
402 }
403
404 Runtime* runtime = reinterpret_cast<JavaVMExt*>(vm)->GetRuntime();
405
406 // No threads allowed in zygote mode.
407 if (runtime->IsZygote()) {
408 LOG(ERROR) << "Attempt to attach a thread in the zygote";
409 return JNI_ERR;
410 }
411
412 JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(raw_args);
413 const char* thread_name = nullptr;
414 jobject thread_group = nullptr;
415 if (args != nullptr) {
Alex Light185d1342016-08-11 10:48:03 -0700416 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700417 LOG(ERROR) << "Bad JNI version passed to "
418 << (as_daemon ? "AttachCurrentThreadAsDaemon" : "AttachCurrentThread") << ": "
419 << args->version;
420 return JNI_EVERSION;
421 }
422 thread_name = args->name;
423 thread_group = args->group;
424 }
425
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800426 if (!runtime->AttachCurrentThread(thread_name, as_daemon, thread_group,
427 !runtime->IsAotCompiler())) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700428 *p_env = nullptr;
429 return JNI_ERR;
430 } else {
431 *p_env = Thread::Current()->GetJniEnv();
432 return JNI_OK;
433 }
434 }
435};
436
437const JNIInvokeInterface gJniInvokeInterface = {
438 nullptr, // reserved0
439 nullptr, // reserved1
440 nullptr, // reserved2
441 JII::DestroyJavaVM,
442 JII::AttachCurrentThread,
443 JII::DetachCurrentThread,
444 JII::GetEnv,
445 JII::AttachCurrentThreadAsDaemon
446};
447
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100448JavaVMExt::JavaVMExt(Runtime* runtime,
449 const RuntimeArgumentMap& runtime_options,
450 std::string* error_msg)
Ian Rogers68d8b422014-07-17 11:09:10 -0700451 : runtime_(runtime),
452 check_jni_abort_hook_(nullptr),
453 check_jni_abort_hook_data_(nullptr),
454 check_jni_(false), // Initialized properly in the constructor body below.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800455 force_copy_(runtime_options.Exists(RuntimeArgumentMap::JniOptsForceCopy)),
456 tracing_enabled_(runtime_options.Exists(RuntimeArgumentMap::JniTrace)
457 || VLOG_IS_ON(third_party_jni)),
458 trace_(runtime_options.GetOrDefault(RuntimeArgumentMap::JniTrace)),
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700459 globals_(kGlobalsMax, kGlobal, IndirectReferenceTable::ResizableCapacity::kNo, error_msg),
Ian Rogers68d8b422014-07-17 11:09:10 -0700460 libraries_(new Libraries),
461 unchecked_functions_(&gJniInvokeInterface),
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700462 weak_globals_(kWeakGlobalsMax,
463 kWeakGlobal,
464 IndirectReferenceTable::ResizableCapacity::kNo,
465 error_msg),
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700466 allow_accessing_weak_globals_(true),
Andreas Gampe05a364c2016-10-14 13:27:12 -0700467 weak_globals_add_condition_("weak globals add condition",
468 (CHECK(Locks::jni_weak_globals_lock_ != nullptr),
469 *Locks::jni_weak_globals_lock_)),
Alex Light185d1342016-08-11 10:48:03 -0700470 env_hooks_() {
Ian Rogers68d8b422014-07-17 11:09:10 -0700471 functions = unchecked_functions_;
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800472 SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni));
Ian Rogers68d8b422014-07-17 11:09:10 -0700473}
474
475JavaVMExt::~JavaVMExt() {
476}
477
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100478// Checking "globals" and "weak_globals" usually requires locks, but we
479// don't need the locks to check for validity when constructing the
480// object. Use NO_THREAD_SAFETY_ANALYSIS for this.
481std::unique_ptr<JavaVMExt> JavaVMExt::Create(Runtime* runtime,
482 const RuntimeArgumentMap& runtime_options,
483 std::string* error_msg) NO_THREAD_SAFETY_ANALYSIS {
484 std::unique_ptr<JavaVMExt> java_vm(new JavaVMExt(runtime, runtime_options, error_msg));
485 if (java_vm && java_vm->globals_.IsValid() && java_vm->weak_globals_.IsValid()) {
486 return java_vm;
487 }
488 return nullptr;
489}
490
Alex Light185d1342016-08-11 10:48:03 -0700491jint JavaVMExt::HandleGetEnv(/*out*/void** env, jint version) {
492 for (GetEnvHook hook : env_hooks_) {
493 jint res = hook(this, env, version);
494 if (res == JNI_OK) {
495 return JNI_OK;
496 } else if (res != JNI_EVERSION) {
497 LOG(ERROR) << "Error returned from a plugin GetEnv handler! " << res;
498 return res;
499 }
500 }
501 LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version;
502 return JNI_EVERSION;
503}
504
505// Add a hook to handle getting environments from the GetEnv call.
506void JavaVMExt::AddEnvironmentHook(GetEnvHook hook) {
507 CHECK(hook != nullptr) << "environment hooks shouldn't be null!";
508 env_hooks_.push_back(hook);
509}
510
Ian Rogers68d8b422014-07-17 11:09:10 -0700511void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) {
512 Thread* self = Thread::Current();
513 ScopedObjectAccess soa(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700514 ArtMethod* current_method = self->GetCurrentMethod(nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700515
516 std::ostringstream os;
517 os << "JNI DETECTED ERROR IN APPLICATION: " << msg;
518
519 if (jni_function_name != nullptr) {
520 os << "\n in call to " << jni_function_name;
521 }
522 // TODO: is this useful given that we're about to dump the calling thread's stack?
523 if (current_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700524 os << "\n from " << current_method->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700525 }
526 os << "\n";
527 self->Dump(os);
528
529 if (check_jni_abort_hook_ != nullptr) {
530 check_jni_abort_hook_(check_jni_abort_hook_data_, os.str());
531 } else {
532 // Ensure that we get a native stack trace for this thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700533 ScopedThreadSuspension sts(self, kNative);
Ian Rogers68d8b422014-07-17 11:09:10 -0700534 LOG(FATAL) << os.str();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700535 UNREACHABLE();
Ian Rogers68d8b422014-07-17 11:09:10 -0700536 }
537}
538
539void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) {
540 std::string msg;
541 StringAppendV(&msg, fmt, ap);
542 JniAbort(jni_function_name, msg.c_str());
543}
544
545void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) {
546 va_list args;
547 va_start(args, fmt);
548 JniAbortV(jni_function_name, fmt, args);
549 va_end(args);
550}
551
Mathieu Chartiere401d142015-04-22 13:56:20 -0700552bool JavaVMExt::ShouldTrace(ArtMethod* method) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700553 // Fast where no tracing is enabled.
554 if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) {
555 return false;
556 }
557 // Perform checks based on class name.
558 StringPiece class_name(method->GetDeclaringClassDescriptor());
559 if (!trace_.empty() && class_name.find(trace_) != std::string::npos) {
560 return true;
561 }
562 if (!VLOG_IS_ON(third_party_jni)) {
563 return false;
564 }
565 // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
566 // like part of Android.
567 static const char* gBuiltInPrefixes[] = {
568 "Landroid/",
569 "Lcom/android/",
570 "Lcom/google/android/",
571 "Ldalvik/",
572 "Ljava/",
573 "Ljavax/",
574 "Llibcore/",
575 "Lorg/apache/harmony/",
576 };
577 for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) {
578 if (class_name.starts_with(gBuiltInPrefixes[i])) {
579 return false;
580 }
581 }
582 return true;
583}
584
Mathieu Chartier0795f232016-09-27 18:43:30 -0700585jobject JavaVMExt::AddGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700586 // Check for null after decoding the object to handle cleared weak globals.
587 if (obj == nullptr) {
588 return nullptr;
589 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700590 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700591 IndirectRef ref = globals_.Add(kIRTFirstSegment, obj);
Ian Rogers68d8b422014-07-17 11:09:10 -0700592 return reinterpret_cast<jobject>(ref);
593}
594
Mathieu Chartier0795f232016-09-27 18:43:30 -0700595jweak JavaVMExt::AddWeakGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700596 if (obj == nullptr) {
597 return nullptr;
598 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700599 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchif1c6f872017-01-06 12:23:47 -0800600 // CMS needs this to block for concurrent reference processing because an object allocated during
601 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
602 // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant.
603 while (!kUseReadBarrier && UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700604 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
605 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800606 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700607 weak_globals_add_condition_.WaitHoldingLocks(self);
608 }
Andreas Gampee03662b2016-10-13 17:12:56 -0700609 IndirectRef ref = weak_globals_.Add(kIRTFirstSegment, obj);
Ian Rogers68d8b422014-07-17 11:09:10 -0700610 return reinterpret_cast<jweak>(ref);
611}
612
613void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
614 if (obj == nullptr) {
615 return;
616 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700617 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700618 if (!globals_.Remove(kIRTFirstSegment, obj)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700619 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
620 << "failed to find entry";
621 }
622}
623
624void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
625 if (obj == nullptr) {
626 return;
627 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700628 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700629 if (!weak_globals_.Remove(kIRTFirstSegment, obj)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700630 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
631 << "failed to find entry";
632 }
633}
634
635static void ThreadEnableCheckJni(Thread* thread, void* arg) {
636 bool* check_jni = reinterpret_cast<bool*>(arg);
637 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
638}
639
640bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
641 bool old_check_jni = check_jni_;
642 check_jni_ = enabled;
643 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
644 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
645 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
646 return old_check_jni;
647}
648
649void JavaVMExt::DumpForSigQuit(std::ostream& os) {
650 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
651 if (force_copy_) {
652 os << " (with forcecopy)";
653 }
654 Thread* self = Thread::Current();
655 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700656 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700657 os << "; globals=" << globals_.Capacity();
658 }
659 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700660 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700661 if (weak_globals_.Capacity() > 0) {
662 os << " (plus " << weak_globals_.Capacity() << " weak)";
663 }
664 }
665 os << '\n';
666
667 {
668 MutexLock mu(self, *Locks::jni_libraries_lock_);
669 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
670 }
671}
672
673void JavaVMExt::DisallowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700674 CHECK(!kUseReadBarrier);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700675 Thread* const self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700676 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700677 // DisallowNewWeakGlobals is only called by CMS during the pause. It is required to have the
678 // mutator lock exclusively held so that we don't have any threads in the middle of
679 // DecodeWeakGlobal.
680 Locks::mutator_lock_->AssertExclusiveHeld(self);
681 allow_accessing_weak_globals_.StoreSequentiallyConsistent(false);
Ian Rogers68d8b422014-07-17 11:09:10 -0700682}
683
684void JavaVMExt::AllowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700685 CHECK(!kUseReadBarrier);
Ian Rogers68d8b422014-07-17 11:09:10 -0700686 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700687 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700688 allow_accessing_weak_globals_.StoreSequentiallyConsistent(true);
Ian Rogers68d8b422014-07-17 11:09:10 -0700689 weak_globals_add_condition_.Broadcast(self);
690}
691
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700692void JavaVMExt::BroadcastForNewWeakGlobals() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700693 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700694 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700695 weak_globals_add_condition_.Broadcast(self);
696}
697
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700698ObjPtr<mirror::Object> JavaVMExt::DecodeGlobal(IndirectRef ref) {
699 return globals_.SynchronizedGet(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700700}
701
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700702void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700703 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700704 globals_.Update(ref, result);
705}
706
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700707inline bool JavaVMExt::MayAccessWeakGlobals(Thread* self) const {
708 return MayAccessWeakGlobalsUnlocked(self);
709}
710
711inline bool JavaVMExt::MayAccessWeakGlobalsUnlocked(Thread* self) const {
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700712 DCHECK(self != nullptr);
713 return kUseReadBarrier ?
714 self->GetWeakRefAccessEnabled() :
715 allow_accessing_weak_globals_.LoadSequentiallyConsistent();
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700716}
717
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700718ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700719 // It is safe to access GetWeakRefAccessEnabled without the lock since CC uses checkpoints to call
720 // SetWeakRefAccessEnabled, and the other collectors only modify allow_accessing_weak_globals_
721 // when the mutators are paused.
722 // This only applies in the case where MayAccessWeakGlobals goes from false to true. In the other
723 // case, it may be racy, this is benign since DecodeWeakGlobalLocked does the correct behavior
724 // if MayAccessWeakGlobals is false.
Andreas Gampedc061d02016-10-24 13:19:37 -0700725 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700726 if (LIKELY(MayAccessWeakGlobalsUnlocked(self))) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700727 return weak_globals_.SynchronizedGet(ref);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700728 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700729 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700730 return DecodeWeakGlobalLocked(self, ref);
731}
732
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700733ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalLocked(Thread* self, IndirectRef ref) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700734 if (kDebugLocking) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700735 Locks::jni_weak_globals_lock_->AssertHeld(self);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700736 }
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700737 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700738 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
739 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800740 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700741 weak_globals_add_condition_.WaitHoldingLocks(self);
742 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700743 return weak_globals_.Get(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700744}
745
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700746ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalDuringShutdown(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700747 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700748 DCHECK(Runtime::Current()->IsShuttingDown(self));
749 if (self != nullptr) {
750 return DecodeWeakGlobal(self, ref);
751 }
752 // self can be null during a runtime shutdown. ~Runtime()->~ClassLinker()->DecodeWeakGlobal().
753 if (!kUseReadBarrier) {
754 DCHECK(allow_accessing_weak_globals_.LoadSequentiallyConsistent());
755 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700756 return weak_globals_.SynchronizedGet(ref);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700757}
758
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800759bool JavaVMExt::IsWeakGlobalCleared(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700760 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Andreas Gampe05a364c2016-10-14 13:27:12 -0700761 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800762 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700763 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
764 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800765 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800766 weak_globals_add_condition_.WaitHoldingLocks(self);
767 }
768 // When just checking a weak ref has been cleared, avoid triggering the read barrier in decode
769 // (DecodeWeakGlobal) so that we won't accidentally mark the object alive. Since the cleared
770 // sentinel is a non-moving object, we can compare the ref to it without the read barrier and
771 // decide if it's cleared.
772 return Runtime::Current()->IsClearedJniWeakGlobal(weak_globals_.Get<kWithoutReadBarrier>(ref));
773}
774
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700775void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700776 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700777 weak_globals_.Update(ref, result);
778}
779
Ian Rogers68d8b422014-07-17 11:09:10 -0700780void JavaVMExt::DumpReferenceTables(std::ostream& os) {
781 Thread* self = Thread::Current();
782 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700783 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700784 globals_.Dump(os);
785 }
786 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700787 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700788 weak_globals_.Dump(os);
789 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700790}
791
Mathieu Chartier598302a2015-09-23 14:52:39 -0700792void JavaVMExt::UnloadNativeLibraries() {
793 libraries_.get()->UnloadNativeLibraries();
794}
795
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800796bool JavaVMExt::LoadNativeLibrary(JNIEnv* env,
797 const std::string& path,
798 jobject class_loader,
799 jstring library_path,
800 std::string* error_msg) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700801 error_msg->clear();
802
803 // See if we've already loaded this library. If we have, and the class loader
804 // matches, return successfully without doing anything.
805 // TODO: for better results we should canonicalize the pathname (or even compare
806 // inodes). This implementation is fine if everybody is using System.loadLibrary.
807 SharedLibrary* library;
808 Thread* self = Thread::Current();
809 {
810 // TODO: move the locking (and more of this logic) into Libraries.
811 MutexLock mu(self, *Locks::jni_libraries_lock_);
812 library = libraries_->Get(path);
813 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800814 void* class_loader_allocator = nullptr;
815 {
816 ScopedObjectAccess soa(env);
817 // As the incoming class loader is reachable/alive during the call of this function,
818 // it's okay to decode it without worrying about unexpectedly marking it alive.
Mathieu Chartier0795f232016-09-27 18:43:30 -0700819 ObjPtr<mirror::ClassLoader> loader = soa.Decode<mirror::ClassLoader>(class_loader);
Andreas Gampe2d48e532016-06-17 12:46:14 -0700820
821 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700822 if (class_linker->IsBootClassLoader(soa, loader.Ptr())) {
Andreas Gampe2d48e532016-06-17 12:46:14 -0700823 loader = nullptr;
824 class_loader = nullptr;
825 }
826
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700827 class_loader_allocator = class_linker->GetAllocatorForClassLoader(loader.Ptr());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800828 CHECK(class_loader_allocator != nullptr);
829 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700830 if (library != nullptr) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800831 // Use the allocator pointers for class loader equality to avoid unnecessary weak root decode.
832 if (library->GetClassLoaderAllocator() != class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700833 // The library will be associated with class_loader. The JNI
834 // spec says we can't load the same library into more than one
835 // class loader.
836 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
837 "ClassLoader %p; can't open in ClassLoader %p",
838 path.c_str(), library->GetClassLoader(), class_loader);
839 LOG(WARNING) << error_msg;
840 return false;
841 }
842 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
843 << " ClassLoader " << class_loader << "]";
844 if (!library->CheckOnLoadResult()) {
845 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
846 "to load \"%s\"", path.c_str());
847 return false;
848 }
849 return true;
850 }
851
852 // Open the shared library. Because we're using a full path, the system
853 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
854 // resolve this library's dependencies though.)
855
856 // Failures here are expected when java.library.path has several entries
857 // and we have to hunt for the lib.
858
859 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
860 // class unloading. Libraries will only be unloaded when the reference count (incremented by
861 // dlopen) becomes zero from dlclose.
862
863 Locks::mutator_lock_->AssertNotHeld(self);
864 const char* path_str = path.empty() ? nullptr : path.c_str();
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800865 bool needs_native_bridge = false;
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800866 void* handle = android::OpenNativeLibrary(env,
867 runtime_->GetTargetSdkVersion(),
868 path_str,
869 class_loader,
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800870 library_path,
871 &needs_native_bridge,
872 error_msg);
Ian Rogers68d8b422014-07-17 11:09:10 -0700873
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700874 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]";
Ian Rogers68d8b422014-07-17 11:09:10 -0700875
876 if (handle == nullptr) {
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700877 VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700878 return false;
879 }
880
881 if (env->ExceptionCheck() == JNI_TRUE) {
882 LOG(ERROR) << "Unexpected exception:";
883 env->ExceptionDescribe();
884 env->ExceptionClear();
885 }
886 // Create a new entry.
887 // TODO: move the locking (and more of this logic) into Libraries.
888 bool created_library = false;
889 {
890 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
891 std::unique_ptr<SharedLibrary> new_library(
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800892 new SharedLibrary(env,
893 self,
894 path,
895 handle,
896 needs_native_bridge,
897 class_loader,
898 class_loader_allocator));
899
Ian Rogers68d8b422014-07-17 11:09:10 -0700900 MutexLock mu(self, *Locks::jni_libraries_lock_);
901 library = libraries_->Get(path);
902 if (library == nullptr) { // We won race to get libraries_lock.
903 library = new_library.release();
904 libraries_->Put(path, library);
905 created_library = true;
906 }
907 }
908 if (!created_library) {
909 LOG(INFO) << "WOW: we lost a race to add shared library: "
910 << "\"" << path << "\" ClassLoader=" << class_loader;
911 return library->CheckOnLoadResult();
912 }
913 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
914
915 bool was_successful = false;
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800916 void* sym = library->FindSymbol("JNI_OnLoad", nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700917 if (sym == nullptr) {
918 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
919 was_successful = true;
920 } else {
921 // Call JNI_OnLoad. We have to override the current class
922 // loader, which will always be "null" since the stuff at the
923 // top of the stack is around Runtime.loadLibrary(). (See
924 // the comments in the JNI FindClass function.)
925 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
926 self->SetClassLoaderOverride(class_loader);
927
928 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
929 typedef int (*JNI_OnLoadFn)(JavaVM*, void*);
930 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
931 int version = (*jni_on_load)(this, nullptr);
932
Mathieu Chartierd0004802014-10-15 16:59:47 -0700933 if (runtime_->GetTargetSdkVersion() != 0 && runtime_->GetTargetSdkVersion() <= 21) {
Josh Gao85a78cf2017-03-20 16:26:42 -0700934 // Make sure that sigchain owns SIGSEGV.
935 EnsureFrontOfChain(SIGSEGV);
Mathieu Chartierd0004802014-10-15 16:59:47 -0700936 }
937
Ian Rogers68d8b422014-07-17 11:09:10 -0700938 self->SetClassLoaderOverride(old_class_loader.get());
939
940 if (version == JNI_ERR) {
941 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
Alex Light185d1342016-08-11 10:48:03 -0700942 } else if (JavaVMExt::IsBadJniVersion(version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700943 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
944 path.c_str(), version);
945 // It's unwise to call dlclose() here, but we can mark it
946 // as bad and ensure that future load attempts will fail.
947 // We don't know how far JNI_OnLoad got, so there could
948 // be some partially-initialized stuff accessible through
949 // newly-registered native method calls. We could try to
950 // unregister them, but that doesn't seem worthwhile.
951 } else {
952 was_successful = true;
953 }
954 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
955 << " from JNI_OnLoad in \"" << path << "\"]";
956 }
957
958 library->SetResult(was_successful);
959 return was_successful;
960}
961
Alex Light65af20b2017-04-20 09:15:08 -0700962static void* FindCodeForNativeMethodInAgents(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
963 std::string jni_short_name(m->JniShortName());
964 std::string jni_long_name(m->JniLongName());
965 for (const ti::Agent& agent : Runtime::Current()->GetAgents()) {
966 void* fn = agent.FindSymbol(jni_short_name);
967 if (fn != nullptr) {
968 VLOG(jni) << "Found implementation for " << m->PrettyMethod()
969 << " (symbol: " << jni_short_name << ") in " << agent;
970 return fn;
971 }
972 fn = agent.FindSymbol(jni_long_name);
973 if (fn != nullptr) {
974 VLOG(jni) << "Found implementation for " << m->PrettyMethod()
975 << " (symbol: " << jni_long_name << ") in " << agent;
976 return fn;
977 }
978 }
979 return nullptr;
980}
981
Mathieu Chartiere401d142015-04-22 13:56:20 -0700982void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700983 CHECK(m->IsNative());
984 mirror::Class* c = m->GetDeclaringClass();
985 // If this is a static method, it could be called before the class has been initialized.
David Sehr709b0702016-10-13 09:12:37 -0700986 CHECK(c->IsInitializing()) << c->GetStatus() << " " << m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700987 std::string detail;
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700988 Thread* const self = Thread::Current();
989 void* native_method = libraries_->FindNativeMethod(self, m, detail);
Alex Light65af20b2017-04-20 09:15:08 -0700990 if (native_method == nullptr) {
991 // Lookup JNI native methods from native TI Agent libraries. See runtime/ti/agent.h for more
992 // information. Agent libraries are searched for native methods after all jni libraries.
993 native_method = FindCodeForNativeMethodInAgents(m);
994 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700995 // Throwing can cause libraries_lock to be reacquired.
996 if (native_method == nullptr) {
Alex Light65af20b2017-04-20 09:15:08 -0700997 LOG(ERROR) << detail;
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000998 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
Ian Rogers68d8b422014-07-17 11:09:10 -0700999 }
1000 return native_method;
1001}
1002
Mathieu Chartier97509952015-07-13 14:35:43 -07001003void JavaVMExt::SweepJniWeakGlobals(IsMarkedVisitor* visitor) {
Andreas Gampe05a364c2016-10-14 13:27:12 -07001004 MutexLock mu(Thread::Current(), *Locks::jni_weak_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001005 Runtime* const runtime = Runtime::Current();
1006 for (auto* entry : weak_globals_) {
1007 // Need to skip null here to distinguish between null entries and cleared weak ref entries.
1008 if (!entry->IsNull()) {
1009 // Since this is called by the GC, we don't need a read barrier.
1010 mirror::Object* obj = entry->Read<kWithoutReadBarrier>();
Mathieu Chartier97509952015-07-13 14:35:43 -07001011 mirror::Object* new_obj = visitor->IsMarked(obj);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001012 if (new_obj == nullptr) {
1013 new_obj = runtime->GetClearedJniWeakGlobal();
1014 }
1015 *entry = GcRoot<mirror::Object>(new_obj);
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -07001016 }
Ian Rogers68d8b422014-07-17 11:09:10 -07001017 }
1018}
1019
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001020void JavaVMExt::TrimGlobals() {
Andreas Gampe05a364c2016-10-14 13:27:12 -07001021 WriterMutexLock mu(Thread::Current(), *Locks::jni_globals_lock_);
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001022 globals_.Trim();
1023}
1024
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001025void JavaVMExt::VisitRoots(RootVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001026 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -07001027 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001028 globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal));
Ian Rogers68d8b422014-07-17 11:09:10 -07001029 // The weak_globals table is visited by the GC itself (because it mutates the table).
1030}
1031
1032// JNI Invocation interface.
1033
1034extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001035 ScopedTrace trace(__FUNCTION__);
Ian Rogers68d8b422014-07-17 11:09:10 -07001036 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
Alex Light185d1342016-08-11 10:48:03 -07001037 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001038 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
1039 return JNI_EVERSION;
1040 }
1041 RuntimeOptions options;
1042 for (int i = 0; i < args->nOptions; ++i) {
1043 JavaVMOption* option = &args->options[i];
1044 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
1045 }
1046 bool ignore_unrecognized = args->ignoreUnrecognized;
1047 if (!Runtime::Create(options, ignore_unrecognized)) {
1048 return JNI_ERR;
1049 }
Dimitry Ivanovc544f342016-05-09 16:26:13 -07001050
1051 // Initialize native loader. This step makes sure we have
1052 // everything set up before we start using JNI.
1053 android::InitializeNativeLoader();
1054
Ian Rogers68d8b422014-07-17 11:09:10 -07001055 Runtime* runtime = Runtime::Current();
1056 bool started = runtime->Start();
1057 if (!started) {
1058 delete Thread::Current()->GetJniEnv();
1059 delete runtime->GetJavaVM();
1060 LOG(WARNING) << "CreateJavaVM failed";
1061 return JNI_ERR;
1062 }
Dimitry Ivanov041169f2016-04-21 16:01:24 -07001063
Ian Rogers68d8b422014-07-17 11:09:10 -07001064 *p_env = Thread::Current()->GetJniEnv();
1065 *p_vm = runtime->GetJavaVM();
1066 return JNI_OK;
1067}
1068
Ian Rogersf4d4da12014-11-11 16:10:33 -08001069extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001070 Runtime* runtime = Runtime::Current();
Ian Rogersf4d4da12014-11-11 16:10:33 -08001071 if (runtime == nullptr || buf_len == 0) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001072 *vm_count = 0;
1073 } else {
1074 *vm_count = 1;
Ian Rogersf4d4da12014-11-11 16:10:33 -08001075 vms_buf[0] = runtime->GetJavaVM();
Ian Rogers68d8b422014-07-17 11:09:10 -07001076 }
1077 return JNI_OK;
1078}
1079
1080// Historically unsupported.
1081extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
1082 return JNI_ERR;
1083}
1084
1085} // namespace art