blob: 5a1605323e52724e190f4325edb5129134605149 [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"
Andreas Gampefd03f1e2017-09-19 17:10:10 -070038#include "nativehelper/ScopedUtfChars.h"
Dmitriy Ivanovf5a30992015-11-11 14:18:55 -080039#include "nativeloader/native_loader.h"
Andreas Gampe57cf00b2017-06-05 17:15:32 -070040#include "object_callbacks.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070041#include "parsed_options.h"
Ian Rogersc0542af2014-09-03 16:16:56 -070042#include "runtime-inl.h"
Igor Murashkinaaebaa02015-01-26 10:55:53 -080043#include "runtime_options.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070044#include "scoped_thread_state_change-inl.h"
Josh Gao85a78cf2017-03-20 16:26:42 -070045#include "sigchain.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070046#include "thread-inl.h"
47#include "thread_list.h"
Steven Morelande431e272017-07-18 16:53:49 -070048#include "ti/agent.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070049
50namespace art {
51
Andreas Gampe46ee31b2016-12-14 10:11:49 -080052using android::base::StringAppendF;
53using android::base::StringAppendV;
54
Andreas Gampea8e3b862016-10-17 20:12:52 -070055static constexpr size_t kGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
Ian Rogers68d8b422014-07-17 11:09:10 -070056
Andreas Gampea8e3b862016-10-17 20:12:52 -070057static constexpr size_t kWeakGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
Ian Rogers68d8b422014-07-17 11:09:10 -070058
Alex Light185d1342016-08-11 10:48:03 -070059bool JavaVMExt::IsBadJniVersion(int version) {
Ian Rogers68d8b422014-07-17 11:09:10 -070060 // We don't support JNI_VERSION_1_1. These are the only other valid versions.
61 return version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 && version != JNI_VERSION_1_6;
62}
63
64class SharedLibrary {
65 public:
66 SharedLibrary(JNIEnv* env, Thread* self, const std::string& path, void* handle,
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080067 bool needs_native_bridge, jobject class_loader, void* class_loader_allocator)
Ian Rogers68d8b422014-07-17 11:09:10 -070068 : path_(path),
69 handle_(handle),
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080070 needs_native_bridge_(needs_native_bridge),
Mathieu Chartier598302a2015-09-23 14:52:39 -070071 class_loader_(env->NewWeakGlobalRef(class_loader)),
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080072 class_loader_allocator_(class_loader_allocator),
Ian Rogers68d8b422014-07-17 11:09:10 -070073 jni_on_load_lock_("JNI_OnLoad lock"),
74 jni_on_load_cond_("JNI_OnLoad condition variable", jni_on_load_lock_),
75 jni_on_load_thread_id_(self->GetThreadId()),
76 jni_on_load_result_(kPending) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080077 CHECK(class_loader_allocator_ != nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -070078 }
79
80 ~SharedLibrary() {
81 Thread* self = Thread::Current();
82 if (self != nullptr) {
Mathieu Chartier598302a2015-09-23 14:52:39 -070083 self->GetJniEnv()->DeleteWeakGlobalRef(class_loader_);
Ian Rogers68d8b422014-07-17 11:09:10 -070084 }
Alex Lightbc5669e2016-06-13 17:22:13 +000085
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080086 android::CloseNativeLibrary(handle_, needs_native_bridge_);
Ian Rogers68d8b422014-07-17 11:09:10 -070087 }
88
Mathieu Chartier598302a2015-09-23 14:52:39 -070089 jweak GetClassLoader() const {
Ian Rogers68d8b422014-07-17 11:09:10 -070090 return class_loader_;
91 }
92
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080093 const void* GetClassLoaderAllocator() const {
94 return class_loader_allocator_;
95 }
96
Ian Rogers68d8b422014-07-17 11:09:10 -070097 const std::string& GetPath() const {
98 return path_;
99 }
100
101 /*
102 * Check the result of an earlier call to JNI_OnLoad on this library.
103 * If the call has not yet finished in another thread, wait for it.
104 */
105 bool CheckOnLoadResult()
Mathieu Chartier90443472015-07-16 20:32:27 -0700106 REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700107 Thread* self = Thread::Current();
108 bool okay;
109 {
110 MutexLock mu(self, jni_on_load_lock_);
111
112 if (jni_on_load_thread_id_ == self->GetThreadId()) {
113 // Check this so we don't end up waiting for ourselves. We need to return "true" so the
114 // caller can continue.
115 LOG(INFO) << *self << " recursive attempt to load library " << "\"" << path_ << "\"";
116 okay = true;
117 } else {
118 while (jni_on_load_result_ == kPending) {
119 VLOG(jni) << "[" << *self << " waiting for \"" << path_ << "\" " << "JNI_OnLoad...]";
120 jni_on_load_cond_.Wait(self);
121 }
122
123 okay = (jni_on_load_result_ == kOkay);
124 VLOG(jni) << "[Earlier JNI_OnLoad for \"" << path_ << "\" "
125 << (okay ? "succeeded" : "failed") << "]";
126 }
127 }
128 return okay;
129 }
130
Mathieu Chartier90443472015-07-16 20:32:27 -0700131 void SetResult(bool result) REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700132 Thread* self = Thread::Current();
133 MutexLock mu(self, jni_on_load_lock_);
134
135 jni_on_load_result_ = result ? kOkay : kFailed;
136 jni_on_load_thread_id_ = 0;
137
138 // Broadcast a wakeup to anybody sleeping on the condition variable.
139 jni_on_load_cond_.Broadcast(self);
140 }
141
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800142 void SetNeedsNativeBridge(bool needs) {
143 needs_native_bridge_ = needs;
Ian Rogers68d8b422014-07-17 11:09:10 -0700144 }
145
146 bool NeedsNativeBridge() const {
147 return needs_native_bridge_;
148 }
149
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700150 // No mutator lock since dlsym may block for a while if another thread is doing dlopen.
151 void* FindSymbol(const std::string& symbol_name, const char* shorty = nullptr)
152 REQUIRES(!Locks::mutator_lock_) {
Mathieu Chartier598302a2015-09-23 14:52:39 -0700153 return NeedsNativeBridge()
154 ? FindSymbolWithNativeBridge(symbol_name.c_str(), shorty)
155 : FindSymbolWithoutNativeBridge(symbol_name.c_str());
156 }
157
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700158 // No mutator lock since dlsym may block for a while if another thread is doing dlopen.
159 void* FindSymbolWithoutNativeBridge(const std::string& symbol_name)
160 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe8fec90b2015-06-30 11:23:44 -0700161 CHECK(!NeedsNativeBridge());
162
Ian Rogers68d8b422014-07-17 11:09:10 -0700163 return dlsym(handle_, symbol_name.c_str());
164 }
165
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700166 void* FindSymbolWithNativeBridge(const std::string& symbol_name, const char* shorty)
167 REQUIRES(!Locks::mutator_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700168 CHECK(NeedsNativeBridge());
169
170 uint32_t len = 0;
Calin Juravlec8423522014-08-12 20:55:20 +0100171 return android::NativeBridgeGetTrampoline(handle_, symbol_name.c_str(), shorty, len);
Ian Rogers68d8b422014-07-17 11:09:10 -0700172 }
173
174 private:
175 enum JNI_OnLoadState {
176 kPending,
177 kFailed,
178 kOkay,
179 };
180
181 // Path to library "/system/lib/libjni.so".
182 const std::string path_;
183
184 // The void* returned by dlopen(3).
185 void* const handle_;
186
187 // True if a native bridge is required.
188 bool needs_native_bridge_;
189
Mathieu Chartier598302a2015-09-23 14:52:39 -0700190 // The ClassLoader this library is associated with, a weak global JNI reference that is
Ian Rogers68d8b422014-07-17 11:09:10 -0700191 // created/deleted with the scope of the library.
Mathieu Chartier598302a2015-09-23 14:52:39 -0700192 const jweak class_loader_;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800193 // Used to do equality check on class loaders so we can avoid decoding the weak root and read
194 // barriers that mess with class unloading.
195 const void* class_loader_allocator_;
Ian Rogers68d8b422014-07-17 11:09:10 -0700196
197 // Guards remaining items.
198 Mutex jni_on_load_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
199 // Wait for JNI_OnLoad in other thread.
200 ConditionVariable jni_on_load_cond_ GUARDED_BY(jni_on_load_lock_);
201 // Recursive invocation guard.
202 uint32_t jni_on_load_thread_id_ GUARDED_BY(jni_on_load_lock_);
203 // Result of earlier JNI_OnLoad call.
204 JNI_OnLoadState jni_on_load_result_ GUARDED_BY(jni_on_load_lock_);
205};
206
207// This exists mainly to keep implementation details out of the header file.
208class Libraries {
209 public:
210 Libraries() {
211 }
212
213 ~Libraries() {
214 STLDeleteValues(&libraries_);
215 }
216
Mathieu Chartier598302a2015-09-23 14:52:39 -0700217 // NO_THREAD_SAFETY_ANALYSIS since this may be called from Dumpable. Dumpable can't be annotated
218 // properly due to the template. The caller should be holding the jni_libraries_lock_.
219 void Dump(std::ostream& os) const NO_THREAD_SAFETY_ANALYSIS {
220 Locks::jni_libraries_lock_->AssertHeld(Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -0700221 bool first = true;
222 for (const auto& library : libraries_) {
223 if (!first) {
224 os << ' ';
225 }
226 first = false;
227 os << library.first;
228 }
229 }
230
Mathieu Chartier598302a2015-09-23 14:52:39 -0700231 size_t size() const REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700232 return libraries_.size();
233 }
234
Mathieu Chartier598302a2015-09-23 14:52:39 -0700235 SharedLibrary* Get(const std::string& path) REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700236 auto it = libraries_.find(path);
237 return (it == libraries_.end()) ? nullptr : it->second;
238 }
239
Mathieu Chartier598302a2015-09-23 14:52:39 -0700240 void Put(const std::string& path, SharedLibrary* library)
241 REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700242 libraries_.Put(path, library);
243 }
244
245 // See section 11.3 "Linking Native Methods" of the JNI spec.
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700246 void* FindNativeMethod(Thread* self, ArtMethod* m, std::string& detail)
247 REQUIRES(!Locks::jni_libraries_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700248 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700249 std::string jni_short_name(m->JniShortName());
250 std::string jni_long_name(m->JniLongName());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800251 mirror::ClassLoader* const declaring_class_loader = m->GetDeclaringClass()->GetClassLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700252 ScopedObjectAccessUnchecked soa(Thread::Current());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800253 void* const declaring_class_loader_allocator =
254 Runtime::Current()->GetClassLinker()->GetAllocatorForClassLoader(declaring_class_loader);
255 CHECK(declaring_class_loader_allocator != nullptr);
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700256 // TODO: Avoid calling GetShorty here to prevent dirtying dex pages?
257 const char* shorty = m->GetShorty();
258 {
259 // Go to suspended since dlsym may block for a long time if other threads are using dlopen.
260 ScopedThreadSuspension sts(self, kNative);
261 void* native_code = FindNativeMethodInternal(self,
262 declaring_class_loader_allocator,
263 shorty,
264 jni_short_name,
265 jni_long_name);
266 if (native_code != nullptr) {
267 return native_code;
Ian Rogers68d8b422014-07-17 11:09:10 -0700268 }
269 }
270 detail += "No implementation found for ";
David Sehr709b0702016-10-13 09:12:37 -0700271 detail += m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700272 detail += " (tried " + jni_short_name + " and " + jni_long_name + ")";
Ian Rogers68d8b422014-07-17 11:09:10 -0700273 return nullptr;
274 }
275
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700276 void* FindNativeMethodInternal(Thread* self,
277 void* declaring_class_loader_allocator,
278 const char* shorty,
279 const std::string& jni_short_name,
280 const std::string& jni_long_name)
281 REQUIRES(!Locks::jni_libraries_lock_)
282 REQUIRES(!Locks::mutator_lock_) {
283 MutexLock mu(self, *Locks::jni_libraries_lock_);
284 for (const auto& lib : libraries_) {
285 SharedLibrary* const library = lib.second;
286 // Use the allocator address for class loader equality to avoid unnecessary weak root decode.
287 if (library->GetClassLoaderAllocator() != declaring_class_loader_allocator) {
288 // We only search libraries loaded by the appropriate ClassLoader.
289 continue;
290 }
291 // Try the short name then the long name...
292 const char* arg_shorty = library->NeedsNativeBridge() ? shorty : nullptr;
293 void* fn = library->FindSymbol(jni_short_name, arg_shorty);
294 if (fn == nullptr) {
295 fn = library->FindSymbol(jni_long_name, arg_shorty);
296 }
297 if (fn != nullptr) {
298 VLOG(jni) << "[Found native code for " << jni_long_name
299 << " in \"" << library->GetPath() << "\"]";
300 return fn;
301 }
302 }
303 return nullptr;
304 }
305
Mathieu Chartier598302a2015-09-23 14:52:39 -0700306 // Unload native libraries with cleared class loaders.
307 void UnloadNativeLibraries()
308 REQUIRES(!Locks::jni_libraries_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700309 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700310 Thread* const self = Thread::Current();
Alex Lightbc5669e2016-06-13 17:22:13 +0000311 std::vector<SharedLibrary*> unload_libraries;
Mathieu Chartier598302a2015-09-23 14:52:39 -0700312 {
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700313 MutexLock mu(self, *Locks::jni_libraries_lock_);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700314 for (auto it = libraries_.begin(); it != libraries_.end(); ) {
315 SharedLibrary* const library = it->second;
316 // If class loader is null then it was unloaded, call JNI_OnUnload.
Mathieu Chartiercffb7472015-09-28 10:33:00 -0700317 const jweak class_loader = library->GetClassLoader();
318 // If class_loader is a null jobject then it is the boot class loader. We should not unload
319 // the native libraries of the boot class loader.
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700320 if (class_loader != nullptr && self->IsJWeakCleared(class_loader)) {
Alex Lightbc5669e2016-06-13 17:22:13 +0000321 unload_libraries.push_back(library);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700322 it = libraries_.erase(it);
323 } else {
324 ++it;
325 }
326 }
327 }
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700328 ScopedThreadSuspension sts(self, kNative);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700329 // Do this without holding the jni libraries lock to prevent possible deadlocks.
Alex Lightbc5669e2016-06-13 17:22:13 +0000330 typedef void (*JNI_OnUnloadFn)(JavaVM*, void*);
331 for (auto library : unload_libraries) {
332 void* const sym = library->FindSymbol("JNI_OnUnload", nullptr);
333 if (sym == nullptr) {
334 VLOG(jni) << "[No JNI_OnUnload found in \"" << library->GetPath() << "\"]";
335 } else {
336 VLOG(jni) << "[JNI_OnUnload found for \"" << library->GetPath() << "\"]: Calling...";
337 JNI_OnUnloadFn jni_on_unload = reinterpret_cast<JNI_OnUnloadFn>(sym);
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700338 jni_on_unload(self->GetJniEnv()->vm, nullptr);
Alex Lightbc5669e2016-06-13 17:22:13 +0000339 }
340 delete library;
Mathieu Chartier598302a2015-09-23 14:52:39 -0700341 }
342 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700343
Mathieu Chartier598302a2015-09-23 14:52:39 -0700344 private:
345 AllocationTrackingSafeMap<std::string, SharedLibrary*, kAllocatorTagJNILibraries> libraries_
346 GUARDED_BY(Locks::jni_libraries_lock_);
347};
Ian Rogers68d8b422014-07-17 11:09:10 -0700348
349class JII {
350 public:
351 static jint DestroyJavaVM(JavaVM* vm) {
352 if (vm == nullptr) {
353 return JNI_ERR;
354 }
355 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
356 delete raw_vm->GetRuntime();
Dimitry Ivanov39d68ef2016-04-29 16:02:38 -0700357 android::ResetNativeLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700358 return JNI_OK;
359 }
360
361 static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
362 return AttachCurrentThreadInternal(vm, p_env, thr_args, false);
363 }
364
365 static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
366 return AttachCurrentThreadInternal(vm, p_env, thr_args, true);
367 }
368
369 static jint DetachCurrentThread(JavaVM* vm) {
370 if (vm == nullptr || Thread::Current() == nullptr) {
371 return JNI_ERR;
372 }
373 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
374 Runtime* runtime = raw_vm->GetRuntime();
375 runtime->DetachCurrentThread();
376 return JNI_OK;
377 }
378
379 static jint GetEnv(JavaVM* vm, void** env, jint version) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700380 if (vm == nullptr || env == nullptr) {
381 return JNI_ERR;
382 }
383 Thread* thread = Thread::Current();
384 if (thread == nullptr) {
385 *env = nullptr;
386 return JNI_EDETACHED;
387 }
Alex Light185d1342016-08-11 10:48:03 -0700388 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
389 return raw_vm->HandleGetEnv(env, version);
Ian Rogers68d8b422014-07-17 11:09:10 -0700390 }
391
392 private:
393 static jint AttachCurrentThreadInternal(JavaVM* vm, JNIEnv** p_env, void* raw_args, bool as_daemon) {
394 if (vm == nullptr || p_env == nullptr) {
395 return JNI_ERR;
396 }
397
398 // Return immediately if we're already attached.
399 Thread* self = Thread::Current();
400 if (self != nullptr) {
401 *p_env = self->GetJniEnv();
402 return JNI_OK;
403 }
404
405 Runtime* runtime = reinterpret_cast<JavaVMExt*>(vm)->GetRuntime();
406
407 // No threads allowed in zygote mode.
408 if (runtime->IsZygote()) {
409 LOG(ERROR) << "Attempt to attach a thread in the zygote";
410 return JNI_ERR;
411 }
412
413 JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(raw_args);
414 const char* thread_name = nullptr;
415 jobject thread_group = nullptr;
416 if (args != nullptr) {
Alex Light185d1342016-08-11 10:48:03 -0700417 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700418 LOG(ERROR) << "Bad JNI version passed to "
419 << (as_daemon ? "AttachCurrentThreadAsDaemon" : "AttachCurrentThread") << ": "
420 << args->version;
421 return JNI_EVERSION;
422 }
423 thread_name = args->name;
424 thread_group = args->group;
425 }
426
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800427 if (!runtime->AttachCurrentThread(thread_name, as_daemon, thread_group,
428 !runtime->IsAotCompiler())) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700429 *p_env = nullptr;
430 return JNI_ERR;
431 } else {
432 *p_env = Thread::Current()->GetJniEnv();
433 return JNI_OK;
434 }
435 }
436};
437
438const JNIInvokeInterface gJniInvokeInterface = {
439 nullptr, // reserved0
440 nullptr, // reserved1
441 nullptr, // reserved2
442 JII::DestroyJavaVM,
443 JII::AttachCurrentThread,
444 JII::DetachCurrentThread,
445 JII::GetEnv,
446 JII::AttachCurrentThreadAsDaemon
447};
448
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100449JavaVMExt::JavaVMExt(Runtime* runtime,
450 const RuntimeArgumentMap& runtime_options,
451 std::string* error_msg)
Ian Rogers68d8b422014-07-17 11:09:10 -0700452 : runtime_(runtime),
453 check_jni_abort_hook_(nullptr),
454 check_jni_abort_hook_data_(nullptr),
455 check_jni_(false), // Initialized properly in the constructor body below.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800456 force_copy_(runtime_options.Exists(RuntimeArgumentMap::JniOptsForceCopy)),
457 tracing_enabled_(runtime_options.Exists(RuntimeArgumentMap::JniTrace)
458 || VLOG_IS_ON(third_party_jni)),
459 trace_(runtime_options.GetOrDefault(RuntimeArgumentMap::JniTrace)),
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700460 globals_(kGlobalsMax, kGlobal, IndirectReferenceTable::ResizableCapacity::kNo, error_msg),
Ian Rogers68d8b422014-07-17 11:09:10 -0700461 libraries_(new Libraries),
462 unchecked_functions_(&gJniInvokeInterface),
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700463 weak_globals_(kWeakGlobalsMax,
464 kWeakGlobal,
465 IndirectReferenceTable::ResizableCapacity::kNo,
466 error_msg),
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700467 allow_accessing_weak_globals_(true),
Andreas Gampe05a364c2016-10-14 13:27:12 -0700468 weak_globals_add_condition_("weak globals add condition",
469 (CHECK(Locks::jni_weak_globals_lock_ != nullptr),
470 *Locks::jni_weak_globals_lock_)),
Alex Light185d1342016-08-11 10:48:03 -0700471 env_hooks_() {
Ian Rogers68d8b422014-07-17 11:09:10 -0700472 functions = unchecked_functions_;
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800473 SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni));
Ian Rogers68d8b422014-07-17 11:09:10 -0700474}
475
476JavaVMExt::~JavaVMExt() {
477}
478
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100479// Checking "globals" and "weak_globals" usually requires locks, but we
480// don't need the locks to check for validity when constructing the
481// object. Use NO_THREAD_SAFETY_ANALYSIS for this.
482std::unique_ptr<JavaVMExt> JavaVMExt::Create(Runtime* runtime,
483 const RuntimeArgumentMap& runtime_options,
484 std::string* error_msg) NO_THREAD_SAFETY_ANALYSIS {
485 std::unique_ptr<JavaVMExt> java_vm(new JavaVMExt(runtime, runtime_options, error_msg));
486 if (java_vm && java_vm->globals_.IsValid() && java_vm->weak_globals_.IsValid()) {
487 return java_vm;
488 }
489 return nullptr;
490}
491
Alex Light185d1342016-08-11 10:48:03 -0700492jint JavaVMExt::HandleGetEnv(/*out*/void** env, jint version) {
493 for (GetEnvHook hook : env_hooks_) {
494 jint res = hook(this, env, version);
495 if (res == JNI_OK) {
496 return JNI_OK;
497 } else if (res != JNI_EVERSION) {
498 LOG(ERROR) << "Error returned from a plugin GetEnv handler! " << res;
499 return res;
500 }
501 }
502 LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version;
503 return JNI_EVERSION;
504}
505
506// Add a hook to handle getting environments from the GetEnv call.
507void JavaVMExt::AddEnvironmentHook(GetEnvHook hook) {
508 CHECK(hook != nullptr) << "environment hooks shouldn't be null!";
509 env_hooks_.push_back(hook);
510}
511
Ian Rogers68d8b422014-07-17 11:09:10 -0700512void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) {
513 Thread* self = Thread::Current();
514 ScopedObjectAccess soa(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700515 ArtMethod* current_method = self->GetCurrentMethod(nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700516
517 std::ostringstream os;
518 os << "JNI DETECTED ERROR IN APPLICATION: " << msg;
519
520 if (jni_function_name != nullptr) {
521 os << "\n in call to " << jni_function_name;
522 }
523 // TODO: is this useful given that we're about to dump the calling thread's stack?
524 if (current_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700525 os << "\n from " << current_method->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700526 }
527 os << "\n";
528 self->Dump(os);
529
530 if (check_jni_abort_hook_ != nullptr) {
531 check_jni_abort_hook_(check_jni_abort_hook_data_, os.str());
532 } else {
533 // Ensure that we get a native stack trace for this thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700534 ScopedThreadSuspension sts(self, kNative);
Ian Rogers68d8b422014-07-17 11:09:10 -0700535 LOG(FATAL) << os.str();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700536 UNREACHABLE();
Ian Rogers68d8b422014-07-17 11:09:10 -0700537 }
538}
539
540void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) {
541 std::string msg;
542 StringAppendV(&msg, fmt, ap);
543 JniAbort(jni_function_name, msg.c_str());
544}
545
546void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) {
547 va_list args;
548 va_start(args, fmt);
549 JniAbortV(jni_function_name, fmt, args);
550 va_end(args);
551}
552
Mathieu Chartiere401d142015-04-22 13:56:20 -0700553bool JavaVMExt::ShouldTrace(ArtMethod* method) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700554 // Fast where no tracing is enabled.
555 if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) {
556 return false;
557 }
558 // Perform checks based on class name.
559 StringPiece class_name(method->GetDeclaringClassDescriptor());
560 if (!trace_.empty() && class_name.find(trace_) != std::string::npos) {
561 return true;
562 }
563 if (!VLOG_IS_ON(third_party_jni)) {
564 return false;
565 }
566 // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
567 // like part of Android.
568 static const char* gBuiltInPrefixes[] = {
569 "Landroid/",
570 "Lcom/android/",
571 "Lcom/google/android/",
572 "Ldalvik/",
573 "Ljava/",
574 "Ljavax/",
575 "Llibcore/",
576 "Lorg/apache/harmony/",
577 };
578 for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) {
579 if (class_name.starts_with(gBuiltInPrefixes[i])) {
580 return false;
581 }
582 }
583 return true;
584}
585
Mathieu Chartier0795f232016-09-27 18:43:30 -0700586jobject JavaVMExt::AddGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700587 // Check for null after decoding the object to handle cleared weak globals.
588 if (obj == nullptr) {
589 return nullptr;
590 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700591 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Andreas Gampe25651122017-09-25 14:50:23 -0700592 std::string error_msg;
593 IndirectRef ref = globals_.Add(kIRTFirstSegment, obj, &error_msg);
594 if (UNLIKELY(ref == nullptr)) {
595 LOG(FATAL) << error_msg;
596 UNREACHABLE();
597 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700598 return reinterpret_cast<jobject>(ref);
599}
600
Mathieu Chartier0795f232016-09-27 18:43:30 -0700601jweak JavaVMExt::AddWeakGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700602 if (obj == nullptr) {
603 return nullptr;
604 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700605 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchif1c6f872017-01-06 12:23:47 -0800606 // CMS needs this to block for concurrent reference processing because an object allocated during
607 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
608 // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant.
609 while (!kUseReadBarrier && UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700610 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
611 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800612 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700613 weak_globals_add_condition_.WaitHoldingLocks(self);
614 }
Andreas Gampe25651122017-09-25 14:50:23 -0700615 std::string error_msg;
616 IndirectRef ref = weak_globals_.Add(kIRTFirstSegment, obj, &error_msg);
617 if (UNLIKELY(ref == nullptr)) {
618 LOG(FATAL) << error_msg;
619 UNREACHABLE();
620 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700621 return reinterpret_cast<jweak>(ref);
622}
623
624void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
625 if (obj == nullptr) {
626 return;
627 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700628 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700629 if (!globals_.Remove(kIRTFirstSegment, obj)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700630 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
631 << "failed to find entry";
632 }
633}
634
635void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
636 if (obj == nullptr) {
637 return;
638 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700639 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700640 if (!weak_globals_.Remove(kIRTFirstSegment, obj)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700641 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
642 << "failed to find entry";
643 }
644}
645
646static void ThreadEnableCheckJni(Thread* thread, void* arg) {
647 bool* check_jni = reinterpret_cast<bool*>(arg);
648 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
649}
650
651bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
652 bool old_check_jni = check_jni_;
653 check_jni_ = enabled;
654 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
655 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
656 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
657 return old_check_jni;
658}
659
660void JavaVMExt::DumpForSigQuit(std::ostream& os) {
661 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
662 if (force_copy_) {
663 os << " (with forcecopy)";
664 }
665 Thread* self = Thread::Current();
666 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700667 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700668 os << "; globals=" << globals_.Capacity();
669 }
670 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700671 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700672 if (weak_globals_.Capacity() > 0) {
673 os << " (plus " << weak_globals_.Capacity() << " weak)";
674 }
675 }
676 os << '\n';
677
678 {
679 MutexLock mu(self, *Locks::jni_libraries_lock_);
680 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
681 }
682}
683
684void JavaVMExt::DisallowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700685 CHECK(!kUseReadBarrier);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700686 Thread* const 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 // DisallowNewWeakGlobals is only called by CMS during the pause. It is required to have the
689 // mutator lock exclusively held so that we don't have any threads in the middle of
690 // DecodeWeakGlobal.
691 Locks::mutator_lock_->AssertExclusiveHeld(self);
692 allow_accessing_weak_globals_.StoreSequentiallyConsistent(false);
Ian Rogers68d8b422014-07-17 11:09:10 -0700693}
694
695void JavaVMExt::AllowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700696 CHECK(!kUseReadBarrier);
Ian Rogers68d8b422014-07-17 11:09:10 -0700697 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700698 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700699 allow_accessing_weak_globals_.StoreSequentiallyConsistent(true);
Ian Rogers68d8b422014-07-17 11:09:10 -0700700 weak_globals_add_condition_.Broadcast(self);
701}
702
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700703void JavaVMExt::BroadcastForNewWeakGlobals() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700704 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700705 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700706 weak_globals_add_condition_.Broadcast(self);
707}
708
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700709ObjPtr<mirror::Object> JavaVMExt::DecodeGlobal(IndirectRef ref) {
710 return globals_.SynchronizedGet(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700711}
712
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700713void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700714 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700715 globals_.Update(ref, result);
716}
717
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700718inline bool JavaVMExt::MayAccessWeakGlobals(Thread* self) const {
719 return MayAccessWeakGlobalsUnlocked(self);
720}
721
722inline bool JavaVMExt::MayAccessWeakGlobalsUnlocked(Thread* self) const {
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700723 DCHECK(self != nullptr);
724 return kUseReadBarrier ?
725 self->GetWeakRefAccessEnabled() :
726 allow_accessing_weak_globals_.LoadSequentiallyConsistent();
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700727}
728
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700729ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700730 // It is safe to access GetWeakRefAccessEnabled without the lock since CC uses checkpoints to call
731 // SetWeakRefAccessEnabled, and the other collectors only modify allow_accessing_weak_globals_
732 // when the mutators are paused.
733 // This only applies in the case where MayAccessWeakGlobals goes from false to true. In the other
734 // case, it may be racy, this is benign since DecodeWeakGlobalLocked does the correct behavior
735 // if MayAccessWeakGlobals is false.
Andreas Gampedc061d02016-10-24 13:19:37 -0700736 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700737 if (LIKELY(MayAccessWeakGlobalsUnlocked(self))) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700738 return weak_globals_.SynchronizedGet(ref);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700739 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700740 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700741 return DecodeWeakGlobalLocked(self, ref);
742}
743
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700744ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalLocked(Thread* self, IndirectRef ref) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700745 if (kDebugLocking) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700746 Locks::jni_weak_globals_lock_->AssertHeld(self);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700747 }
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700748 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700749 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
750 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800751 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700752 weak_globals_add_condition_.WaitHoldingLocks(self);
753 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700754 return weak_globals_.Get(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700755}
756
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700757ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalDuringShutdown(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700758 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700759 DCHECK(Runtime::Current()->IsShuttingDown(self));
760 if (self != nullptr) {
761 return DecodeWeakGlobal(self, ref);
762 }
763 // self can be null during a runtime shutdown. ~Runtime()->~ClassLinker()->DecodeWeakGlobal().
764 if (!kUseReadBarrier) {
765 DCHECK(allow_accessing_weak_globals_.LoadSequentiallyConsistent());
766 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700767 return weak_globals_.SynchronizedGet(ref);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700768}
769
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800770bool JavaVMExt::IsWeakGlobalCleared(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700771 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Andreas Gampe05a364c2016-10-14 13:27:12 -0700772 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800773 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700774 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
775 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800776 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800777 weak_globals_add_condition_.WaitHoldingLocks(self);
778 }
779 // When just checking a weak ref has been cleared, avoid triggering the read barrier in decode
780 // (DecodeWeakGlobal) so that we won't accidentally mark the object alive. Since the cleared
781 // sentinel is a non-moving object, we can compare the ref to it without the read barrier and
782 // decide if it's cleared.
783 return Runtime::Current()->IsClearedJniWeakGlobal(weak_globals_.Get<kWithoutReadBarrier>(ref));
784}
785
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700786void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700787 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700788 weak_globals_.Update(ref, result);
789}
790
Ian Rogers68d8b422014-07-17 11:09:10 -0700791void JavaVMExt::DumpReferenceTables(std::ostream& os) {
792 Thread* self = Thread::Current();
793 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700794 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700795 globals_.Dump(os);
796 }
797 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700798 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700799 weak_globals_.Dump(os);
800 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700801}
802
Mathieu Chartier598302a2015-09-23 14:52:39 -0700803void JavaVMExt::UnloadNativeLibraries() {
804 libraries_.get()->UnloadNativeLibraries();
805}
806
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800807bool JavaVMExt::LoadNativeLibrary(JNIEnv* env,
808 const std::string& path,
809 jobject class_loader,
810 jstring library_path,
811 std::string* error_msg) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700812 error_msg->clear();
813
814 // See if we've already loaded this library. If we have, and the class loader
815 // matches, return successfully without doing anything.
816 // TODO: for better results we should canonicalize the pathname (or even compare
817 // inodes). This implementation is fine if everybody is using System.loadLibrary.
818 SharedLibrary* library;
819 Thread* self = Thread::Current();
820 {
821 // TODO: move the locking (and more of this logic) into Libraries.
822 MutexLock mu(self, *Locks::jni_libraries_lock_);
823 library = libraries_->Get(path);
824 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800825 void* class_loader_allocator = nullptr;
826 {
827 ScopedObjectAccess soa(env);
828 // As the incoming class loader is reachable/alive during the call of this function,
829 // it's okay to decode it without worrying about unexpectedly marking it alive.
Mathieu Chartier0795f232016-09-27 18:43:30 -0700830 ObjPtr<mirror::ClassLoader> loader = soa.Decode<mirror::ClassLoader>(class_loader);
Andreas Gampe2d48e532016-06-17 12:46:14 -0700831
832 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700833 if (class_linker->IsBootClassLoader(soa, loader.Ptr())) {
Andreas Gampe2d48e532016-06-17 12:46:14 -0700834 loader = nullptr;
835 class_loader = nullptr;
836 }
837
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700838 class_loader_allocator = class_linker->GetAllocatorForClassLoader(loader.Ptr());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800839 CHECK(class_loader_allocator != nullptr);
840 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700841 if (library != nullptr) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800842 // Use the allocator pointers for class loader equality to avoid unnecessary weak root decode.
843 if (library->GetClassLoaderAllocator() != class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700844 // The library will be associated with class_loader. The JNI
845 // spec says we can't load the same library into more than one
846 // class loader.
Andreas Gampefd03f1e2017-09-19 17:10:10 -0700847 //
848 // This isn't very common. So spend some time to get a readable message.
849 auto call_to_string = [&](jobject obj) -> std::string {
850 if (obj == nullptr) {
851 return "null";
852 }
853 // Handle jweaks. Ignore double local-ref.
854 ScopedLocalRef<jobject> local_ref(env, env->NewLocalRef(obj));
855 if (local_ref != nullptr) {
856 ScopedLocalRef<jclass> local_class(env, env->GetObjectClass(local_ref.get()));
857 jmethodID to_string = env->GetMethodID(local_class.get(),
858 "toString",
859 "()Ljava/lang/String;");
860 DCHECK(to_string != nullptr);
861 ScopedLocalRef<jobject> local_string(env,
862 env->CallObjectMethod(local_ref.get(), to_string));
863 if (local_string != nullptr) {
864 ScopedUtfChars utf(env, reinterpret_cast<jstring>(local_string.get()));
865 if (utf.c_str() != nullptr) {
866 return utf.c_str();
867 }
868 }
869 env->ExceptionClear();
870 return "(Error calling toString)";
871 }
872 return "null";
873 };
874 std::string old_class_loader = call_to_string(library->GetClassLoader());
875 std::string new_class_loader = call_to_string(class_loader);
Ian Rogers68d8b422014-07-17 11:09:10 -0700876 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
Andreas Gampefd03f1e2017-09-19 17:10:10 -0700877 "ClassLoader %p(%s); can't open in ClassLoader %p(%s)",
878 path.c_str(),
879 library->GetClassLoader(),
880 old_class_loader.c_str(),
881 class_loader,
882 new_class_loader.c_str());
Andreas Gampe335ee582017-09-19 17:09:52 -0700883 LOG(WARNING) << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700884 return false;
885 }
886 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
887 << " ClassLoader " << class_loader << "]";
888 if (!library->CheckOnLoadResult()) {
889 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
890 "to load \"%s\"", path.c_str());
891 return false;
892 }
893 return true;
894 }
895
896 // Open the shared library. Because we're using a full path, the system
897 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
898 // resolve this library's dependencies though.)
899
900 // Failures here are expected when java.library.path has several entries
901 // and we have to hunt for the lib.
902
903 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
904 // class unloading. Libraries will only be unloaded when the reference count (incremented by
905 // dlopen) becomes zero from dlclose.
906
907 Locks::mutator_lock_->AssertNotHeld(self);
908 const char* path_str = path.empty() ? nullptr : path.c_str();
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800909 bool needs_native_bridge = false;
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800910 void* handle = android::OpenNativeLibrary(env,
911 runtime_->GetTargetSdkVersion(),
912 path_str,
913 class_loader,
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800914 library_path,
915 &needs_native_bridge,
916 error_msg);
Ian Rogers68d8b422014-07-17 11:09:10 -0700917
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700918 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]";
Ian Rogers68d8b422014-07-17 11:09:10 -0700919
920 if (handle == nullptr) {
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700921 VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700922 return false;
923 }
924
925 if (env->ExceptionCheck() == JNI_TRUE) {
926 LOG(ERROR) << "Unexpected exception:";
927 env->ExceptionDescribe();
928 env->ExceptionClear();
929 }
930 // Create a new entry.
931 // TODO: move the locking (and more of this logic) into Libraries.
932 bool created_library = false;
933 {
934 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
935 std::unique_ptr<SharedLibrary> new_library(
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800936 new SharedLibrary(env,
937 self,
938 path,
939 handle,
940 needs_native_bridge,
941 class_loader,
942 class_loader_allocator));
943
Ian Rogers68d8b422014-07-17 11:09:10 -0700944 MutexLock mu(self, *Locks::jni_libraries_lock_);
945 library = libraries_->Get(path);
946 if (library == nullptr) { // We won race to get libraries_lock.
947 library = new_library.release();
948 libraries_->Put(path, library);
949 created_library = true;
950 }
951 }
952 if (!created_library) {
953 LOG(INFO) << "WOW: we lost a race to add shared library: "
954 << "\"" << path << "\" ClassLoader=" << class_loader;
955 return library->CheckOnLoadResult();
956 }
957 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
958
959 bool was_successful = false;
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800960 void* sym = library->FindSymbol("JNI_OnLoad", nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700961 if (sym == nullptr) {
962 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
963 was_successful = true;
964 } else {
965 // Call JNI_OnLoad. We have to override the current class
966 // loader, which will always be "null" since the stuff at the
967 // top of the stack is around Runtime.loadLibrary(). (See
968 // the comments in the JNI FindClass function.)
969 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
970 self->SetClassLoaderOverride(class_loader);
971
972 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
973 typedef int (*JNI_OnLoadFn)(JavaVM*, void*);
974 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
975 int version = (*jni_on_load)(this, nullptr);
976
Mathieu Chartierd0004802014-10-15 16:59:47 -0700977 if (runtime_->GetTargetSdkVersion() != 0 && runtime_->GetTargetSdkVersion() <= 21) {
Josh Gao85a78cf2017-03-20 16:26:42 -0700978 // Make sure that sigchain owns SIGSEGV.
979 EnsureFrontOfChain(SIGSEGV);
Mathieu Chartierd0004802014-10-15 16:59:47 -0700980 }
981
Ian Rogers68d8b422014-07-17 11:09:10 -0700982 self->SetClassLoaderOverride(old_class_loader.get());
983
984 if (version == JNI_ERR) {
985 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
Alex Light185d1342016-08-11 10:48:03 -0700986 } else if (JavaVMExt::IsBadJniVersion(version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700987 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
988 path.c_str(), version);
989 // It's unwise to call dlclose() here, but we can mark it
990 // as bad and ensure that future load attempts will fail.
991 // We don't know how far JNI_OnLoad got, so there could
992 // be some partially-initialized stuff accessible through
993 // newly-registered native method calls. We could try to
994 // unregister them, but that doesn't seem worthwhile.
995 } else {
996 was_successful = true;
997 }
998 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
999 << " from JNI_OnLoad in \"" << path << "\"]";
1000 }
1001
1002 library->SetResult(was_successful);
1003 return was_successful;
1004}
1005
Alex Light65af20b2017-04-20 09:15:08 -07001006static void* FindCodeForNativeMethodInAgents(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
1007 std::string jni_short_name(m->JniShortName());
1008 std::string jni_long_name(m->JniLongName());
1009 for (const ti::Agent& agent : Runtime::Current()->GetAgents()) {
1010 void* fn = agent.FindSymbol(jni_short_name);
1011 if (fn != nullptr) {
1012 VLOG(jni) << "Found implementation for " << m->PrettyMethod()
1013 << " (symbol: " << jni_short_name << ") in " << agent;
1014 return fn;
1015 }
1016 fn = agent.FindSymbol(jni_long_name);
1017 if (fn != nullptr) {
1018 VLOG(jni) << "Found implementation for " << m->PrettyMethod()
1019 << " (symbol: " << jni_long_name << ") in " << agent;
1020 return fn;
1021 }
1022 }
1023 return nullptr;
1024}
1025
Mathieu Chartiere401d142015-04-22 13:56:20 -07001026void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001027 CHECK(m->IsNative());
1028 mirror::Class* c = m->GetDeclaringClass();
1029 // If this is a static method, it could be called before the class has been initialized.
David Sehr709b0702016-10-13 09:12:37 -07001030 CHECK(c->IsInitializing()) << c->GetStatus() << " " << m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -07001031 std::string detail;
Mathieu Chartier46e75d02017-06-02 16:03:39 -07001032 Thread* const self = Thread::Current();
1033 void* native_method = libraries_->FindNativeMethod(self, m, detail);
Alex Light65af20b2017-04-20 09:15:08 -07001034 if (native_method == nullptr) {
1035 // Lookup JNI native methods from native TI Agent libraries. See runtime/ti/agent.h for more
1036 // information. Agent libraries are searched for native methods after all jni libraries.
1037 native_method = FindCodeForNativeMethodInAgents(m);
1038 }
Ian Rogers68d8b422014-07-17 11:09:10 -07001039 // Throwing can cause libraries_lock to be reacquired.
1040 if (native_method == nullptr) {
Alex Light65af20b2017-04-20 09:15:08 -07001041 LOG(ERROR) << detail;
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001042 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
Ian Rogers68d8b422014-07-17 11:09:10 -07001043 }
1044 return native_method;
1045}
1046
Mathieu Chartier97509952015-07-13 14:35:43 -07001047void JavaVMExt::SweepJniWeakGlobals(IsMarkedVisitor* visitor) {
Andreas Gampe05a364c2016-10-14 13:27:12 -07001048 MutexLock mu(Thread::Current(), *Locks::jni_weak_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001049 Runtime* const runtime = Runtime::Current();
1050 for (auto* entry : weak_globals_) {
1051 // Need to skip null here to distinguish between null entries and cleared weak ref entries.
1052 if (!entry->IsNull()) {
1053 // Since this is called by the GC, we don't need a read barrier.
1054 mirror::Object* obj = entry->Read<kWithoutReadBarrier>();
Mathieu Chartier97509952015-07-13 14:35:43 -07001055 mirror::Object* new_obj = visitor->IsMarked(obj);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001056 if (new_obj == nullptr) {
1057 new_obj = runtime->GetClearedJniWeakGlobal();
1058 }
1059 *entry = GcRoot<mirror::Object>(new_obj);
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -07001060 }
Ian Rogers68d8b422014-07-17 11:09:10 -07001061 }
1062}
1063
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001064void JavaVMExt::TrimGlobals() {
Andreas Gampe05a364c2016-10-14 13:27:12 -07001065 WriterMutexLock mu(Thread::Current(), *Locks::jni_globals_lock_);
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001066 globals_.Trim();
1067}
1068
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001069void JavaVMExt::VisitRoots(RootVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001070 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -07001071 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001072 globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal));
Ian Rogers68d8b422014-07-17 11:09:10 -07001073 // The weak_globals table is visited by the GC itself (because it mutates the table).
1074}
1075
1076// JNI Invocation interface.
1077
1078extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001079 ScopedTrace trace(__FUNCTION__);
Ian Rogers68d8b422014-07-17 11:09:10 -07001080 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
Alex Light185d1342016-08-11 10:48:03 -07001081 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001082 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
1083 return JNI_EVERSION;
1084 }
1085 RuntimeOptions options;
1086 for (int i = 0; i < args->nOptions; ++i) {
1087 JavaVMOption* option = &args->options[i];
1088 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
1089 }
1090 bool ignore_unrecognized = args->ignoreUnrecognized;
1091 if (!Runtime::Create(options, ignore_unrecognized)) {
1092 return JNI_ERR;
1093 }
Dimitry Ivanovc544f342016-05-09 16:26:13 -07001094
1095 // Initialize native loader. This step makes sure we have
1096 // everything set up before we start using JNI.
1097 android::InitializeNativeLoader();
1098
Ian Rogers68d8b422014-07-17 11:09:10 -07001099 Runtime* runtime = Runtime::Current();
1100 bool started = runtime->Start();
1101 if (!started) {
1102 delete Thread::Current()->GetJniEnv();
1103 delete runtime->GetJavaVM();
1104 LOG(WARNING) << "CreateJavaVM failed";
1105 return JNI_ERR;
1106 }
Dimitry Ivanov041169f2016-04-21 16:01:24 -07001107
Ian Rogers68d8b422014-07-17 11:09:10 -07001108 *p_env = Thread::Current()->GetJniEnv();
1109 *p_vm = runtime->GetJavaVM();
1110 return JNI_OK;
1111}
1112
Ian Rogersf4d4da12014-11-11 16:10:33 -08001113extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001114 Runtime* runtime = Runtime::Current();
Ian Rogersf4d4da12014-11-11 16:10:33 -08001115 if (runtime == nullptr || buf_len == 0) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001116 *vm_count = 0;
1117 } else {
1118 *vm_count = 1;
Ian Rogersf4d4da12014-11-11 16:10:33 -08001119 vms_buf[0] = runtime->GetJavaVM();
Ian Rogers68d8b422014-07-17 11:09:10 -07001120 }
1121 return JNI_OK;
1122}
1123
1124// Historically unsupported.
1125extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
1126 return JNI_ERR;
1127}
1128
1129} // namespace art