blob: 104fb66ed88dbecf0a4d56b5444b723bcbc586d0 [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 Gampe1b35b462017-09-29 18:52:15 -070031#include "gc/allocation_record.h"
32#include "gc/heap.h"
Andreas Gamped4901292017-05-30 18:41:34 -070033#include "gc_root-inl.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070034#include "indirect_reference_table-inl.h"
Andreas Gampe57cf00b2017-06-05 17:15:32 -070035#include "jni_internal.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070036#include "mirror/class-inl.h"
37#include "mirror/class_loader.h"
Calin Juravlec8423522014-08-12 20:55:20 +010038#include "nativebridge/native_bridge.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070039#include "nativehelper/scoped_local_ref.h"
40#include "nativehelper/scoped_utf_chars.h"
Dmitriy Ivanovf5a30992015-11-11 14:18:55 -080041#include "nativeloader/native_loader.h"
Andreas Gampe57cf00b2017-06-05 17:15:32 -070042#include "object_callbacks.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070043#include "parsed_options.h"
Ian Rogersc0542af2014-09-03 16:16:56 -070044#include "runtime-inl.h"
Igor Murashkinaaebaa02015-01-26 10:55:53 -080045#include "runtime_options.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070046#include "scoped_thread_state_change-inl.h"
Josh Gao85a78cf2017-03-20 16:26:42 -070047#include "sigchain.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070048#include "thread-inl.h"
49#include "thread_list.h"
Steven Morelande431e272017-07-18 16:53:49 -070050#include "ti/agent.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070051
52namespace art {
53
Andreas Gampe46ee31b2016-12-14 10:11:49 -080054using android::base::StringAppendF;
55using android::base::StringAppendV;
56
Andreas Gampea8e3b862016-10-17 20:12:52 -070057static constexpr size_t kGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
Ian Rogers68d8b422014-07-17 11:09:10 -070058
Andreas Gampea8e3b862016-10-17 20:12:52 -070059static constexpr size_t kWeakGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
Ian Rogers68d8b422014-07-17 11:09:10 -070060
Alex Light185d1342016-08-11 10:48:03 -070061bool JavaVMExt::IsBadJniVersion(int version) {
Ian Rogers68d8b422014-07-17 11:09:10 -070062 // We don't support JNI_VERSION_1_1. These are the only other valid versions.
63 return version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 && version != JNI_VERSION_1_6;
64}
65
66class SharedLibrary {
67 public:
68 SharedLibrary(JNIEnv* env, Thread* self, const std::string& path, void* handle,
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080069 bool needs_native_bridge, jobject class_loader, void* class_loader_allocator)
Ian Rogers68d8b422014-07-17 11:09:10 -070070 : path_(path),
71 handle_(handle),
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080072 needs_native_bridge_(needs_native_bridge),
Mathieu Chartier598302a2015-09-23 14:52:39 -070073 class_loader_(env->NewWeakGlobalRef(class_loader)),
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080074 class_loader_allocator_(class_loader_allocator),
Ian Rogers68d8b422014-07-17 11:09:10 -070075 jni_on_load_lock_("JNI_OnLoad lock"),
76 jni_on_load_cond_("JNI_OnLoad condition variable", jni_on_load_lock_),
77 jni_on_load_thread_id_(self->GetThreadId()),
78 jni_on_load_result_(kPending) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080079 CHECK(class_loader_allocator_ != nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -070080 }
81
82 ~SharedLibrary() {
83 Thread* self = Thread::Current();
84 if (self != nullptr) {
Mathieu Chartier598302a2015-09-23 14:52:39 -070085 self->GetJniEnv()->DeleteWeakGlobalRef(class_loader_);
Ian Rogers68d8b422014-07-17 11:09:10 -070086 }
Alex Lightbc5669e2016-06-13 17:22:13 +000087
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080088 android::CloseNativeLibrary(handle_, needs_native_bridge_);
Ian Rogers68d8b422014-07-17 11:09:10 -070089 }
90
Mathieu Chartier598302a2015-09-23 14:52:39 -070091 jweak GetClassLoader() const {
Ian Rogers68d8b422014-07-17 11:09:10 -070092 return class_loader_;
93 }
94
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080095 const void* GetClassLoaderAllocator() const {
96 return class_loader_allocator_;
97 }
98
Ian Rogers68d8b422014-07-17 11:09:10 -070099 const std::string& GetPath() const {
100 return path_;
101 }
102
103 /*
104 * Check the result of an earlier call to JNI_OnLoad on this library.
105 * If the call has not yet finished in another thread, wait for it.
106 */
107 bool CheckOnLoadResult()
Mathieu Chartier90443472015-07-16 20:32:27 -0700108 REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700109 Thread* self = Thread::Current();
110 bool okay;
111 {
112 MutexLock mu(self, jni_on_load_lock_);
113
114 if (jni_on_load_thread_id_ == self->GetThreadId()) {
115 // Check this so we don't end up waiting for ourselves. We need to return "true" so the
116 // caller can continue.
117 LOG(INFO) << *self << " recursive attempt to load library " << "\"" << path_ << "\"";
118 okay = true;
119 } else {
120 while (jni_on_load_result_ == kPending) {
121 VLOG(jni) << "[" << *self << " waiting for \"" << path_ << "\" " << "JNI_OnLoad...]";
122 jni_on_load_cond_.Wait(self);
123 }
124
125 okay = (jni_on_load_result_ == kOkay);
126 VLOG(jni) << "[Earlier JNI_OnLoad for \"" << path_ << "\" "
127 << (okay ? "succeeded" : "failed") << "]";
128 }
129 }
130 return okay;
131 }
132
Mathieu Chartier90443472015-07-16 20:32:27 -0700133 void SetResult(bool result) REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700134 Thread* self = Thread::Current();
135 MutexLock mu(self, jni_on_load_lock_);
136
137 jni_on_load_result_ = result ? kOkay : kFailed;
138 jni_on_load_thread_id_ = 0;
139
140 // Broadcast a wakeup to anybody sleeping on the condition variable.
141 jni_on_load_cond_.Broadcast(self);
142 }
143
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800144 void SetNeedsNativeBridge(bool needs) {
145 needs_native_bridge_ = needs;
Ian Rogers68d8b422014-07-17 11:09:10 -0700146 }
147
148 bool NeedsNativeBridge() const {
149 return needs_native_bridge_;
150 }
151
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700152 // No mutator lock since dlsym may block for a while if another thread is doing dlopen.
153 void* FindSymbol(const std::string& symbol_name, const char* shorty = nullptr)
154 REQUIRES(!Locks::mutator_lock_) {
Mathieu Chartier598302a2015-09-23 14:52:39 -0700155 return NeedsNativeBridge()
156 ? FindSymbolWithNativeBridge(symbol_name.c_str(), shorty)
157 : FindSymbolWithoutNativeBridge(symbol_name.c_str());
158 }
159
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700160 // No mutator lock since dlsym may block for a while if another thread is doing dlopen.
161 void* FindSymbolWithoutNativeBridge(const std::string& symbol_name)
162 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe8fec90b2015-06-30 11:23:44 -0700163 CHECK(!NeedsNativeBridge());
164
Ian Rogers68d8b422014-07-17 11:09:10 -0700165 return dlsym(handle_, symbol_name.c_str());
166 }
167
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700168 void* FindSymbolWithNativeBridge(const std::string& symbol_name, const char* shorty)
169 REQUIRES(!Locks::mutator_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700170 CHECK(NeedsNativeBridge());
171
172 uint32_t len = 0;
Calin Juravlec8423522014-08-12 20:55:20 +0100173 return android::NativeBridgeGetTrampoline(handle_, symbol_name.c_str(), shorty, len);
Ian Rogers68d8b422014-07-17 11:09:10 -0700174 }
175
176 private:
177 enum JNI_OnLoadState {
178 kPending,
179 kFailed,
180 kOkay,
181 };
182
183 // Path to library "/system/lib/libjni.so".
184 const std::string path_;
185
186 // The void* returned by dlopen(3).
187 void* const handle_;
188
189 // True if a native bridge is required.
190 bool needs_native_bridge_;
191
Mathieu Chartier598302a2015-09-23 14:52:39 -0700192 // The ClassLoader this library is associated with, a weak global JNI reference that is
Ian Rogers68d8b422014-07-17 11:09:10 -0700193 // created/deleted with the scope of the library.
Mathieu Chartier598302a2015-09-23 14:52:39 -0700194 const jweak class_loader_;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800195 // Used to do equality check on class loaders so we can avoid decoding the weak root and read
196 // barriers that mess with class unloading.
197 const void* class_loader_allocator_;
Ian Rogers68d8b422014-07-17 11:09:10 -0700198
199 // Guards remaining items.
200 Mutex jni_on_load_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
201 // Wait for JNI_OnLoad in other thread.
202 ConditionVariable jni_on_load_cond_ GUARDED_BY(jni_on_load_lock_);
203 // Recursive invocation guard.
204 uint32_t jni_on_load_thread_id_ GUARDED_BY(jni_on_load_lock_);
205 // Result of earlier JNI_OnLoad call.
206 JNI_OnLoadState jni_on_load_result_ GUARDED_BY(jni_on_load_lock_);
207};
208
209// This exists mainly to keep implementation details out of the header file.
210class Libraries {
211 public:
212 Libraries() {
213 }
214
215 ~Libraries() {
216 STLDeleteValues(&libraries_);
217 }
218
Mathieu Chartier598302a2015-09-23 14:52:39 -0700219 // NO_THREAD_SAFETY_ANALYSIS since this may be called from Dumpable. Dumpable can't be annotated
220 // properly due to the template. The caller should be holding the jni_libraries_lock_.
221 void Dump(std::ostream& os) const NO_THREAD_SAFETY_ANALYSIS {
222 Locks::jni_libraries_lock_->AssertHeld(Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -0700223 bool first = true;
224 for (const auto& library : libraries_) {
225 if (!first) {
226 os << ' ';
227 }
228 first = false;
229 os << library.first;
230 }
231 }
232
Mathieu Chartier598302a2015-09-23 14:52:39 -0700233 size_t size() const REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700234 return libraries_.size();
235 }
236
Mathieu Chartier598302a2015-09-23 14:52:39 -0700237 SharedLibrary* Get(const std::string& path) REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700238 auto it = libraries_.find(path);
239 return (it == libraries_.end()) ? nullptr : it->second;
240 }
241
Mathieu Chartier598302a2015-09-23 14:52:39 -0700242 void Put(const std::string& path, SharedLibrary* library)
243 REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700244 libraries_.Put(path, library);
245 }
246
247 // See section 11.3 "Linking Native Methods" of the JNI spec.
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700248 void* FindNativeMethod(Thread* self, ArtMethod* m, std::string& detail)
249 REQUIRES(!Locks::jni_libraries_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700250 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700251 std::string jni_short_name(m->JniShortName());
252 std::string jni_long_name(m->JniLongName());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800253 mirror::ClassLoader* const declaring_class_loader = m->GetDeclaringClass()->GetClassLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700254 ScopedObjectAccessUnchecked soa(Thread::Current());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800255 void* const declaring_class_loader_allocator =
256 Runtime::Current()->GetClassLinker()->GetAllocatorForClassLoader(declaring_class_loader);
257 CHECK(declaring_class_loader_allocator != nullptr);
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700258 // TODO: Avoid calling GetShorty here to prevent dirtying dex pages?
259 const char* shorty = m->GetShorty();
260 {
261 // Go to suspended since dlsym may block for a long time if other threads are using dlopen.
262 ScopedThreadSuspension sts(self, kNative);
263 void* native_code = FindNativeMethodInternal(self,
264 declaring_class_loader_allocator,
265 shorty,
266 jni_short_name,
267 jni_long_name);
268 if (native_code != nullptr) {
269 return native_code;
Ian Rogers68d8b422014-07-17 11:09:10 -0700270 }
271 }
272 detail += "No implementation found for ";
David Sehr709b0702016-10-13 09:12:37 -0700273 detail += m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700274 detail += " (tried " + jni_short_name + " and " + jni_long_name + ")";
Ian Rogers68d8b422014-07-17 11:09:10 -0700275 return nullptr;
276 }
277
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700278 void* FindNativeMethodInternal(Thread* self,
279 void* declaring_class_loader_allocator,
280 const char* shorty,
281 const std::string& jni_short_name,
282 const std::string& jni_long_name)
283 REQUIRES(!Locks::jni_libraries_lock_)
284 REQUIRES(!Locks::mutator_lock_) {
285 MutexLock mu(self, *Locks::jni_libraries_lock_);
286 for (const auto& lib : libraries_) {
287 SharedLibrary* const library = lib.second;
288 // Use the allocator address for class loader equality to avoid unnecessary weak root decode.
289 if (library->GetClassLoaderAllocator() != declaring_class_loader_allocator) {
290 // We only search libraries loaded by the appropriate ClassLoader.
291 continue;
292 }
293 // Try the short name then the long name...
294 const char* arg_shorty = library->NeedsNativeBridge() ? shorty : nullptr;
295 void* fn = library->FindSymbol(jni_short_name, arg_shorty);
296 if (fn == nullptr) {
297 fn = library->FindSymbol(jni_long_name, arg_shorty);
298 }
299 if (fn != nullptr) {
300 VLOG(jni) << "[Found native code for " << jni_long_name
301 << " in \"" << library->GetPath() << "\"]";
302 return fn;
303 }
304 }
305 return nullptr;
306 }
307
Mathieu Chartier598302a2015-09-23 14:52:39 -0700308 // Unload native libraries with cleared class loaders.
309 void UnloadNativeLibraries()
310 REQUIRES(!Locks::jni_libraries_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700311 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700312 Thread* const self = Thread::Current();
Alex Lightbc5669e2016-06-13 17:22:13 +0000313 std::vector<SharedLibrary*> unload_libraries;
Mathieu Chartier598302a2015-09-23 14:52:39 -0700314 {
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700315 MutexLock mu(self, *Locks::jni_libraries_lock_);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700316 for (auto it = libraries_.begin(); it != libraries_.end(); ) {
317 SharedLibrary* const library = it->second;
318 // If class loader is null then it was unloaded, call JNI_OnUnload.
Mathieu Chartiercffb7472015-09-28 10:33:00 -0700319 const jweak class_loader = library->GetClassLoader();
320 // If class_loader is a null jobject then it is the boot class loader. We should not unload
321 // the native libraries of the boot class loader.
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700322 if (class_loader != nullptr && self->IsJWeakCleared(class_loader)) {
Alex Lightbc5669e2016-06-13 17:22:13 +0000323 unload_libraries.push_back(library);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700324 it = libraries_.erase(it);
325 } else {
326 ++it;
327 }
328 }
329 }
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700330 ScopedThreadSuspension sts(self, kNative);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700331 // Do this without holding the jni libraries lock to prevent possible deadlocks.
Alex Lightbc5669e2016-06-13 17:22:13 +0000332 typedef void (*JNI_OnUnloadFn)(JavaVM*, void*);
333 for (auto library : unload_libraries) {
334 void* const sym = library->FindSymbol("JNI_OnUnload", nullptr);
335 if (sym == nullptr) {
336 VLOG(jni) << "[No JNI_OnUnload found in \"" << library->GetPath() << "\"]";
337 } else {
338 VLOG(jni) << "[JNI_OnUnload found for \"" << library->GetPath() << "\"]: Calling...";
339 JNI_OnUnloadFn jni_on_unload = reinterpret_cast<JNI_OnUnloadFn>(sym);
Ian Rogers55256cb2017-12-21 17:07:11 -0800340 jni_on_unload(self->GetJniEnv()->GetVm(), nullptr);
Alex Lightbc5669e2016-06-13 17:22:13 +0000341 }
342 delete library;
Mathieu Chartier598302a2015-09-23 14:52:39 -0700343 }
344 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700345
Mathieu Chartier598302a2015-09-23 14:52:39 -0700346 private:
347 AllocationTrackingSafeMap<std::string, SharedLibrary*, kAllocatorTagJNILibraries> libraries_
348 GUARDED_BY(Locks::jni_libraries_lock_);
349};
Ian Rogers68d8b422014-07-17 11:09:10 -0700350
351class JII {
352 public:
353 static jint DestroyJavaVM(JavaVM* vm) {
354 if (vm == nullptr) {
355 return JNI_ERR;
356 }
357 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
358 delete raw_vm->GetRuntime();
Dimitry Ivanov39d68ef2016-04-29 16:02:38 -0700359 android::ResetNativeLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700360 return JNI_OK;
361 }
362
363 static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
364 return AttachCurrentThreadInternal(vm, p_env, thr_args, false);
365 }
366
367 static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
368 return AttachCurrentThreadInternal(vm, p_env, thr_args, true);
369 }
370
371 static jint DetachCurrentThread(JavaVM* vm) {
372 if (vm == nullptr || Thread::Current() == nullptr) {
373 return JNI_ERR;
374 }
375 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
376 Runtime* runtime = raw_vm->GetRuntime();
377 runtime->DetachCurrentThread();
378 return JNI_OK;
379 }
380
381 static jint GetEnv(JavaVM* vm, void** env, jint version) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700382 if (vm == nullptr || env == nullptr) {
383 return JNI_ERR;
384 }
385 Thread* thread = Thread::Current();
386 if (thread == nullptr) {
387 *env = nullptr;
388 return JNI_EDETACHED;
389 }
Alex Light185d1342016-08-11 10:48:03 -0700390 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
391 return raw_vm->HandleGetEnv(env, version);
Ian Rogers68d8b422014-07-17 11:09:10 -0700392 }
393
394 private:
395 static jint AttachCurrentThreadInternal(JavaVM* vm, JNIEnv** p_env, void* raw_args, bool as_daemon) {
396 if (vm == nullptr || p_env == nullptr) {
397 return JNI_ERR;
398 }
399
400 // Return immediately if we're already attached.
401 Thread* self = Thread::Current();
402 if (self != nullptr) {
403 *p_env = self->GetJniEnv();
404 return JNI_OK;
405 }
406
407 Runtime* runtime = reinterpret_cast<JavaVMExt*>(vm)->GetRuntime();
408
409 // No threads allowed in zygote mode.
410 if (runtime->IsZygote()) {
411 LOG(ERROR) << "Attempt to attach a thread in the zygote";
412 return JNI_ERR;
413 }
414
415 JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(raw_args);
416 const char* thread_name = nullptr;
417 jobject thread_group = nullptr;
418 if (args != nullptr) {
Alex Light185d1342016-08-11 10:48:03 -0700419 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700420 LOG(ERROR) << "Bad JNI version passed to "
421 << (as_daemon ? "AttachCurrentThreadAsDaemon" : "AttachCurrentThread") << ": "
422 << args->version;
423 return JNI_EVERSION;
424 }
425 thread_name = args->name;
426 thread_group = args->group;
427 }
428
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800429 if (!runtime->AttachCurrentThread(thread_name, as_daemon, thread_group,
430 !runtime->IsAotCompiler())) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700431 *p_env = nullptr;
432 return JNI_ERR;
433 } else {
434 *p_env = Thread::Current()->GetJniEnv();
435 return JNI_OK;
436 }
437 }
438};
439
440const JNIInvokeInterface gJniInvokeInterface = {
441 nullptr, // reserved0
442 nullptr, // reserved1
443 nullptr, // reserved2
444 JII::DestroyJavaVM,
445 JII::AttachCurrentThread,
446 JII::DetachCurrentThread,
447 JII::GetEnv,
448 JII::AttachCurrentThreadAsDaemon
449};
450
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100451JavaVMExt::JavaVMExt(Runtime* runtime,
452 const RuntimeArgumentMap& runtime_options,
453 std::string* error_msg)
Ian Rogers68d8b422014-07-17 11:09:10 -0700454 : runtime_(runtime),
455 check_jni_abort_hook_(nullptr),
456 check_jni_abort_hook_data_(nullptr),
457 check_jni_(false), // Initialized properly in the constructor body below.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800458 force_copy_(runtime_options.Exists(RuntimeArgumentMap::JniOptsForceCopy)),
459 tracing_enabled_(runtime_options.Exists(RuntimeArgumentMap::JniTrace)
460 || VLOG_IS_ON(third_party_jni)),
461 trace_(runtime_options.GetOrDefault(RuntimeArgumentMap::JniTrace)),
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700462 globals_(kGlobalsMax, kGlobal, IndirectReferenceTable::ResizableCapacity::kNo, error_msg),
Ian Rogers68d8b422014-07-17 11:09:10 -0700463 libraries_(new Libraries),
464 unchecked_functions_(&gJniInvokeInterface),
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700465 weak_globals_(kWeakGlobalsMax,
466 kWeakGlobal,
467 IndirectReferenceTable::ResizableCapacity::kNo,
468 error_msg),
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700469 allow_accessing_weak_globals_(true),
Andreas Gampe05a364c2016-10-14 13:27:12 -0700470 weak_globals_add_condition_("weak globals add condition",
471 (CHECK(Locks::jni_weak_globals_lock_ != nullptr),
472 *Locks::jni_weak_globals_lock_)),
Andreas Gampe1b35b462017-09-29 18:52:15 -0700473 env_hooks_(),
474 enable_allocation_tracking_delta_(
475 runtime_options.GetOrDefault(RuntimeArgumentMap::GlobalRefAllocStackTraceLimit)),
476 allocation_tracking_enabled_(false),
477 old_allocation_tracking_state_(false) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700478 functions = unchecked_functions_;
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800479 SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni));
Ian Rogers68d8b422014-07-17 11:09:10 -0700480}
481
482JavaVMExt::~JavaVMExt() {
483}
484
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100485// Checking "globals" and "weak_globals" usually requires locks, but we
486// don't need the locks to check for validity when constructing the
487// object. Use NO_THREAD_SAFETY_ANALYSIS for this.
488std::unique_ptr<JavaVMExt> JavaVMExt::Create(Runtime* runtime,
489 const RuntimeArgumentMap& runtime_options,
490 std::string* error_msg) NO_THREAD_SAFETY_ANALYSIS {
491 std::unique_ptr<JavaVMExt> java_vm(new JavaVMExt(runtime, runtime_options, error_msg));
492 if (java_vm && java_vm->globals_.IsValid() && java_vm->weak_globals_.IsValid()) {
493 return java_vm;
494 }
495 return nullptr;
496}
497
Alex Light185d1342016-08-11 10:48:03 -0700498jint JavaVMExt::HandleGetEnv(/*out*/void** env, jint version) {
499 for (GetEnvHook hook : env_hooks_) {
500 jint res = hook(this, env, version);
501 if (res == JNI_OK) {
502 return JNI_OK;
503 } else if (res != JNI_EVERSION) {
504 LOG(ERROR) << "Error returned from a plugin GetEnv handler! " << res;
505 return res;
506 }
507 }
508 LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version;
509 return JNI_EVERSION;
510}
511
512// Add a hook to handle getting environments from the GetEnv call.
513void JavaVMExt::AddEnvironmentHook(GetEnvHook hook) {
514 CHECK(hook != nullptr) << "environment hooks shouldn't be null!";
515 env_hooks_.push_back(hook);
516}
517
Ian Rogers68d8b422014-07-17 11:09:10 -0700518void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) {
519 Thread* self = Thread::Current();
520 ScopedObjectAccess soa(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700521 ArtMethod* current_method = self->GetCurrentMethod(nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700522
523 std::ostringstream os;
524 os << "JNI DETECTED ERROR IN APPLICATION: " << msg;
525
526 if (jni_function_name != nullptr) {
527 os << "\n in call to " << jni_function_name;
528 }
529 // TODO: is this useful given that we're about to dump the calling thread's stack?
530 if (current_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700531 os << "\n from " << current_method->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700532 }
533 os << "\n";
534 self->Dump(os);
535
536 if (check_jni_abort_hook_ != nullptr) {
537 check_jni_abort_hook_(check_jni_abort_hook_data_, os.str());
538 } else {
539 // Ensure that we get a native stack trace for this thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700540 ScopedThreadSuspension sts(self, kNative);
Ian Rogers68d8b422014-07-17 11:09:10 -0700541 LOG(FATAL) << os.str();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700542 UNREACHABLE();
Ian Rogers68d8b422014-07-17 11:09:10 -0700543 }
544}
545
546void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) {
547 std::string msg;
548 StringAppendV(&msg, fmt, ap);
549 JniAbort(jni_function_name, msg.c_str());
550}
551
552void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) {
553 va_list args;
554 va_start(args, fmt);
555 JniAbortV(jni_function_name, fmt, args);
556 va_end(args);
557}
558
Mathieu Chartiere401d142015-04-22 13:56:20 -0700559bool JavaVMExt::ShouldTrace(ArtMethod* method) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700560 // Fast where no tracing is enabled.
561 if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) {
562 return false;
563 }
564 // Perform checks based on class name.
565 StringPiece class_name(method->GetDeclaringClassDescriptor());
566 if (!trace_.empty() && class_name.find(trace_) != std::string::npos) {
567 return true;
568 }
569 if (!VLOG_IS_ON(third_party_jni)) {
570 return false;
571 }
572 // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
573 // like part of Android.
574 static const char* gBuiltInPrefixes[] = {
575 "Landroid/",
576 "Lcom/android/",
577 "Lcom/google/android/",
578 "Ldalvik/",
579 "Ljava/",
580 "Ljavax/",
581 "Llibcore/",
582 "Lorg/apache/harmony/",
583 };
584 for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) {
585 if (class_name.starts_with(gBuiltInPrefixes[i])) {
586 return false;
587 }
588 }
589 return true;
590}
591
Andreas Gampe1b35b462017-09-29 18:52:15 -0700592void JavaVMExt::CheckGlobalRefAllocationTracking() {
593 if (LIKELY(enable_allocation_tracking_delta_ == 0)) {
594 return;
595 }
596 size_t simple_free_capacity = globals_.FreeCapacity();
597 if (UNLIKELY(simple_free_capacity <= enable_allocation_tracking_delta_)) {
598 if (!allocation_tracking_enabled_) {
599 LOG(WARNING) << "Global reference storage appears close to exhaustion, program termination "
600 << "may be imminent. Enabling allocation tracking to improve abort diagnostics. "
601 << "This will result in program slow-down.";
602
603 old_allocation_tracking_state_ = runtime_->GetHeap()->IsAllocTrackingEnabled();
604 if (!old_allocation_tracking_state_) {
605 // Need to be guaranteed suspended.
606 ScopedObjectAccess soa(Thread::Current());
607 ScopedThreadSuspension sts(soa.Self(), ThreadState::kNative);
608 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(true);
609 }
610 allocation_tracking_enabled_ = true;
611 }
612 } else {
613 if (UNLIKELY(allocation_tracking_enabled_)) {
614 if (!old_allocation_tracking_state_) {
615 // Need to be guaranteed suspended.
616 ScopedObjectAccess soa(Thread::Current());
617 ScopedThreadSuspension sts(soa.Self(), ThreadState::kNative);
618 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(false);
619 }
Andreas Gampe45485342017-10-11 12:04:35 -0700620 allocation_tracking_enabled_ = false;
Andreas Gampe1b35b462017-09-29 18:52:15 -0700621 }
622 }
623}
624
Mathieu Chartier0795f232016-09-27 18:43:30 -0700625jobject JavaVMExt::AddGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700626 // Check for null after decoding the object to handle cleared weak globals.
627 if (obj == nullptr) {
628 return nullptr;
629 }
Andreas Gampe1b35b462017-09-29 18:52:15 -0700630 IndirectRef ref;
Andreas Gampe25651122017-09-25 14:50:23 -0700631 std::string error_msg;
Andreas Gampe1b35b462017-09-29 18:52:15 -0700632 {
633 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
634 ref = globals_.Add(kIRTFirstSegment, obj, &error_msg);
635 }
Andreas Gampe25651122017-09-25 14:50:23 -0700636 if (UNLIKELY(ref == nullptr)) {
637 LOG(FATAL) << error_msg;
638 UNREACHABLE();
639 }
Andreas Gampe1b35b462017-09-29 18:52:15 -0700640 CheckGlobalRefAllocationTracking();
Ian Rogers68d8b422014-07-17 11:09:10 -0700641 return reinterpret_cast<jobject>(ref);
642}
643
Mathieu Chartier0795f232016-09-27 18:43:30 -0700644jweak JavaVMExt::AddWeakGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700645 if (obj == nullptr) {
646 return nullptr;
647 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700648 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchif1c6f872017-01-06 12:23:47 -0800649 // CMS needs this to block for concurrent reference processing because an object allocated during
650 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
651 // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant.
652 while (!kUseReadBarrier && UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700653 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
654 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800655 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700656 weak_globals_add_condition_.WaitHoldingLocks(self);
657 }
Andreas Gampe25651122017-09-25 14:50:23 -0700658 std::string error_msg;
659 IndirectRef ref = weak_globals_.Add(kIRTFirstSegment, obj, &error_msg);
660 if (UNLIKELY(ref == nullptr)) {
661 LOG(FATAL) << error_msg;
662 UNREACHABLE();
663 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700664 return reinterpret_cast<jweak>(ref);
665}
666
667void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
668 if (obj == nullptr) {
669 return;
670 }
Andreas Gampe1b35b462017-09-29 18:52:15 -0700671 {
672 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
673 if (!globals_.Remove(kIRTFirstSegment, obj)) {
674 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
675 << "failed to find entry";
676 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700677 }
Andreas Gampe1b35b462017-09-29 18:52:15 -0700678 CheckGlobalRefAllocationTracking();
Ian Rogers68d8b422014-07-17 11:09:10 -0700679}
680
681void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
682 if (obj == nullptr) {
683 return;
684 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700685 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700686 if (!weak_globals_.Remove(kIRTFirstSegment, obj)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700687 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
688 << "failed to find entry";
689 }
690}
691
692static void ThreadEnableCheckJni(Thread* thread, void* arg) {
693 bool* check_jni = reinterpret_cast<bool*>(arg);
694 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
695}
696
697bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
698 bool old_check_jni = check_jni_;
699 check_jni_ = enabled;
700 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
701 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
702 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
703 return old_check_jni;
704}
705
706void JavaVMExt::DumpForSigQuit(std::ostream& os) {
707 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
708 if (force_copy_) {
709 os << " (with forcecopy)";
710 }
711 Thread* self = Thread::Current();
712 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700713 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700714 os << "; globals=" << globals_.Capacity();
715 }
716 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700717 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700718 if (weak_globals_.Capacity() > 0) {
719 os << " (plus " << weak_globals_.Capacity() << " weak)";
720 }
721 }
722 os << '\n';
723
724 {
725 MutexLock mu(self, *Locks::jni_libraries_lock_);
726 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
727 }
728}
729
730void JavaVMExt::DisallowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700731 CHECK(!kUseReadBarrier);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700732 Thread* const self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700733 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700734 // DisallowNewWeakGlobals is only called by CMS during the pause. It is required to have the
735 // mutator lock exclusively held so that we don't have any threads in the middle of
736 // DecodeWeakGlobal.
737 Locks::mutator_lock_->AssertExclusiveHeld(self);
738 allow_accessing_weak_globals_.StoreSequentiallyConsistent(false);
Ian Rogers68d8b422014-07-17 11:09:10 -0700739}
740
741void JavaVMExt::AllowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700742 CHECK(!kUseReadBarrier);
Ian Rogers68d8b422014-07-17 11:09:10 -0700743 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700744 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700745 allow_accessing_weak_globals_.StoreSequentiallyConsistent(true);
Ian Rogers68d8b422014-07-17 11:09:10 -0700746 weak_globals_add_condition_.Broadcast(self);
747}
748
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700749void JavaVMExt::BroadcastForNewWeakGlobals() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700750 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700751 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700752 weak_globals_add_condition_.Broadcast(self);
753}
754
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700755ObjPtr<mirror::Object> JavaVMExt::DecodeGlobal(IndirectRef ref) {
756 return globals_.SynchronizedGet(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700757}
758
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700759void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700760 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700761 globals_.Update(ref, result);
762}
763
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700764inline bool JavaVMExt::MayAccessWeakGlobals(Thread* self) const {
765 return MayAccessWeakGlobalsUnlocked(self);
766}
767
768inline bool JavaVMExt::MayAccessWeakGlobalsUnlocked(Thread* self) const {
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700769 DCHECK(self != nullptr);
770 return kUseReadBarrier ?
771 self->GetWeakRefAccessEnabled() :
772 allow_accessing_weak_globals_.LoadSequentiallyConsistent();
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700773}
774
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700775ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700776 // It is safe to access GetWeakRefAccessEnabled without the lock since CC uses checkpoints to call
777 // SetWeakRefAccessEnabled, and the other collectors only modify allow_accessing_weak_globals_
778 // when the mutators are paused.
779 // This only applies in the case where MayAccessWeakGlobals goes from false to true. In the other
780 // case, it may be racy, this is benign since DecodeWeakGlobalLocked does the correct behavior
781 // if MayAccessWeakGlobals is false.
Andreas Gampedc061d02016-10-24 13:19:37 -0700782 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700783 if (LIKELY(MayAccessWeakGlobalsUnlocked(self))) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700784 return weak_globals_.SynchronizedGet(ref);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700785 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700786 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700787 return DecodeWeakGlobalLocked(self, ref);
788}
789
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700790ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalLocked(Thread* self, IndirectRef ref) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700791 if (kDebugLocking) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700792 Locks::jni_weak_globals_lock_->AssertHeld(self);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700793 }
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700794 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700795 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
796 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800797 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700798 weak_globals_add_condition_.WaitHoldingLocks(self);
799 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700800 return weak_globals_.Get(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700801}
802
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700803ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalDuringShutdown(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700804 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700805 DCHECK(Runtime::Current()->IsShuttingDown(self));
806 if (self != nullptr) {
807 return DecodeWeakGlobal(self, ref);
808 }
809 // self can be null during a runtime shutdown. ~Runtime()->~ClassLinker()->DecodeWeakGlobal().
810 if (!kUseReadBarrier) {
811 DCHECK(allow_accessing_weak_globals_.LoadSequentiallyConsistent());
812 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700813 return weak_globals_.SynchronizedGet(ref);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700814}
815
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800816bool JavaVMExt::IsWeakGlobalCleared(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700817 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Andreas Gampe05a364c2016-10-14 13:27:12 -0700818 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800819 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700820 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
821 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800822 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800823 weak_globals_add_condition_.WaitHoldingLocks(self);
824 }
825 // When just checking a weak ref has been cleared, avoid triggering the read barrier in decode
826 // (DecodeWeakGlobal) so that we won't accidentally mark the object alive. Since the cleared
827 // sentinel is a non-moving object, we can compare the ref to it without the read barrier and
828 // decide if it's cleared.
829 return Runtime::Current()->IsClearedJniWeakGlobal(weak_globals_.Get<kWithoutReadBarrier>(ref));
830}
831
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700832void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700833 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700834 weak_globals_.Update(ref, result);
835}
836
Ian Rogers68d8b422014-07-17 11:09:10 -0700837void JavaVMExt::DumpReferenceTables(std::ostream& os) {
838 Thread* self = Thread::Current();
839 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700840 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700841 globals_.Dump(os);
842 }
843 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700844 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700845 weak_globals_.Dump(os);
846 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700847}
848
Mathieu Chartier598302a2015-09-23 14:52:39 -0700849void JavaVMExt::UnloadNativeLibraries() {
850 libraries_.get()->UnloadNativeLibraries();
851}
852
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800853bool JavaVMExt::LoadNativeLibrary(JNIEnv* env,
854 const std::string& path,
855 jobject class_loader,
856 jstring library_path,
857 std::string* error_msg) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700858 error_msg->clear();
859
860 // See if we've already loaded this library. If we have, and the class loader
861 // matches, return successfully without doing anything.
862 // TODO: for better results we should canonicalize the pathname (or even compare
863 // inodes). This implementation is fine if everybody is using System.loadLibrary.
864 SharedLibrary* library;
865 Thread* self = Thread::Current();
866 {
867 // TODO: move the locking (and more of this logic) into Libraries.
868 MutexLock mu(self, *Locks::jni_libraries_lock_);
869 library = libraries_->Get(path);
870 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800871 void* class_loader_allocator = nullptr;
872 {
873 ScopedObjectAccess soa(env);
874 // As the incoming class loader is reachable/alive during the call of this function,
875 // it's okay to decode it without worrying about unexpectedly marking it alive.
Mathieu Chartier0795f232016-09-27 18:43:30 -0700876 ObjPtr<mirror::ClassLoader> loader = soa.Decode<mirror::ClassLoader>(class_loader);
Andreas Gampe2d48e532016-06-17 12:46:14 -0700877
878 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700879 if (class_linker->IsBootClassLoader(soa, loader.Ptr())) {
Andreas Gampe2d48e532016-06-17 12:46:14 -0700880 loader = nullptr;
881 class_loader = nullptr;
882 }
883
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700884 class_loader_allocator = class_linker->GetAllocatorForClassLoader(loader.Ptr());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800885 CHECK(class_loader_allocator != nullptr);
886 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700887 if (library != nullptr) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800888 // Use the allocator pointers for class loader equality to avoid unnecessary weak root decode.
889 if (library->GetClassLoaderAllocator() != class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700890 // The library will be associated with class_loader. The JNI
891 // spec says we can't load the same library into more than one
892 // class loader.
Andreas Gampefd03f1e2017-09-19 17:10:10 -0700893 //
894 // This isn't very common. So spend some time to get a readable message.
895 auto call_to_string = [&](jobject obj) -> std::string {
896 if (obj == nullptr) {
897 return "null";
898 }
899 // Handle jweaks. Ignore double local-ref.
900 ScopedLocalRef<jobject> local_ref(env, env->NewLocalRef(obj));
901 if (local_ref != nullptr) {
902 ScopedLocalRef<jclass> local_class(env, env->GetObjectClass(local_ref.get()));
903 jmethodID to_string = env->GetMethodID(local_class.get(),
904 "toString",
905 "()Ljava/lang/String;");
906 DCHECK(to_string != nullptr);
907 ScopedLocalRef<jobject> local_string(env,
908 env->CallObjectMethod(local_ref.get(), to_string));
909 if (local_string != nullptr) {
910 ScopedUtfChars utf(env, reinterpret_cast<jstring>(local_string.get()));
911 if (utf.c_str() != nullptr) {
912 return utf.c_str();
913 }
914 }
915 env->ExceptionClear();
916 return "(Error calling toString)";
917 }
918 return "null";
919 };
920 std::string old_class_loader = call_to_string(library->GetClassLoader());
921 std::string new_class_loader = call_to_string(class_loader);
Ian Rogers68d8b422014-07-17 11:09:10 -0700922 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
Andreas Gampefd03f1e2017-09-19 17:10:10 -0700923 "ClassLoader %p(%s); can't open in ClassLoader %p(%s)",
924 path.c_str(),
925 library->GetClassLoader(),
926 old_class_loader.c_str(),
927 class_loader,
928 new_class_loader.c_str());
Andreas Gampe335ee582017-09-19 17:09:52 -0700929 LOG(WARNING) << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700930 return false;
931 }
932 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
933 << " ClassLoader " << class_loader << "]";
934 if (!library->CheckOnLoadResult()) {
935 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
936 "to load \"%s\"", path.c_str());
937 return false;
938 }
939 return true;
940 }
941
942 // Open the shared library. Because we're using a full path, the system
943 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
944 // resolve this library's dependencies though.)
945
946 // Failures here are expected when java.library.path has several entries
947 // and we have to hunt for the lib.
948
949 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
950 // class unloading. Libraries will only be unloaded when the reference count (incremented by
951 // dlopen) becomes zero from dlclose.
952
953 Locks::mutator_lock_->AssertNotHeld(self);
954 const char* path_str = path.empty() ? nullptr : path.c_str();
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800955 bool needs_native_bridge = false;
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800956 void* handle = android::OpenNativeLibrary(env,
957 runtime_->GetTargetSdkVersion(),
958 path_str,
959 class_loader,
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800960 library_path,
961 &needs_native_bridge,
962 error_msg);
Ian Rogers68d8b422014-07-17 11:09:10 -0700963
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700964 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]";
Ian Rogers68d8b422014-07-17 11:09:10 -0700965
966 if (handle == nullptr) {
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700967 VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700968 return false;
969 }
970
971 if (env->ExceptionCheck() == JNI_TRUE) {
972 LOG(ERROR) << "Unexpected exception:";
973 env->ExceptionDescribe();
974 env->ExceptionClear();
975 }
976 // Create a new entry.
977 // TODO: move the locking (and more of this logic) into Libraries.
978 bool created_library = false;
979 {
980 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
981 std::unique_ptr<SharedLibrary> new_library(
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800982 new SharedLibrary(env,
983 self,
984 path,
985 handle,
986 needs_native_bridge,
987 class_loader,
988 class_loader_allocator));
989
Ian Rogers68d8b422014-07-17 11:09:10 -0700990 MutexLock mu(self, *Locks::jni_libraries_lock_);
991 library = libraries_->Get(path);
992 if (library == nullptr) { // We won race to get libraries_lock.
993 library = new_library.release();
994 libraries_->Put(path, library);
995 created_library = true;
996 }
997 }
998 if (!created_library) {
999 LOG(INFO) << "WOW: we lost a race to add shared library: "
1000 << "\"" << path << "\" ClassLoader=" << class_loader;
1001 return library->CheckOnLoadResult();
1002 }
1003 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
1004
1005 bool was_successful = false;
Zhenhua WANG8447e6d2016-05-30 11:10:29 +08001006 void* sym = library->FindSymbol("JNI_OnLoad", nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -07001007 if (sym == nullptr) {
1008 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
1009 was_successful = true;
1010 } else {
1011 // Call JNI_OnLoad. We have to override the current class
1012 // loader, which will always be "null" since the stuff at the
1013 // top of the stack is around Runtime.loadLibrary(). (See
1014 // the comments in the JNI FindClass function.)
1015 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
1016 self->SetClassLoaderOverride(class_loader);
1017
1018 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
1019 typedef int (*JNI_OnLoadFn)(JavaVM*, void*);
1020 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
1021 int version = (*jni_on_load)(this, nullptr);
1022
Mathieu Chartierd0004802014-10-15 16:59:47 -07001023 if (runtime_->GetTargetSdkVersion() != 0 && runtime_->GetTargetSdkVersion() <= 21) {
Josh Gao85a78cf2017-03-20 16:26:42 -07001024 // Make sure that sigchain owns SIGSEGV.
1025 EnsureFrontOfChain(SIGSEGV);
Mathieu Chartierd0004802014-10-15 16:59:47 -07001026 }
1027
Ian Rogers68d8b422014-07-17 11:09:10 -07001028 self->SetClassLoaderOverride(old_class_loader.get());
1029
1030 if (version == JNI_ERR) {
1031 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
Alex Light185d1342016-08-11 10:48:03 -07001032 } else if (JavaVMExt::IsBadJniVersion(version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001033 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
1034 path.c_str(), version);
1035 // It's unwise to call dlclose() here, but we can mark it
1036 // as bad and ensure that future load attempts will fail.
1037 // We don't know how far JNI_OnLoad got, so there could
1038 // be some partially-initialized stuff accessible through
1039 // newly-registered native method calls. We could try to
1040 // unregister them, but that doesn't seem worthwhile.
1041 } else {
1042 was_successful = true;
1043 }
1044 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
1045 << " from JNI_OnLoad in \"" << path << "\"]";
1046 }
1047
1048 library->SetResult(was_successful);
1049 return was_successful;
1050}
1051
Alex Light65af20b2017-04-20 09:15:08 -07001052static void* FindCodeForNativeMethodInAgents(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
1053 std::string jni_short_name(m->JniShortName());
1054 std::string jni_long_name(m->JniLongName());
1055 for (const ti::Agent& agent : Runtime::Current()->GetAgents()) {
1056 void* fn = agent.FindSymbol(jni_short_name);
1057 if (fn != nullptr) {
1058 VLOG(jni) << "Found implementation for " << m->PrettyMethod()
1059 << " (symbol: " << jni_short_name << ") in " << agent;
1060 return fn;
1061 }
1062 fn = agent.FindSymbol(jni_long_name);
1063 if (fn != nullptr) {
1064 VLOG(jni) << "Found implementation for " << m->PrettyMethod()
1065 << " (symbol: " << jni_long_name << ") in " << agent;
1066 return fn;
1067 }
1068 }
1069 return nullptr;
1070}
1071
Mathieu Chartiere401d142015-04-22 13:56:20 -07001072void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001073 CHECK(m->IsNative());
1074 mirror::Class* c = m->GetDeclaringClass();
1075 // If this is a static method, it could be called before the class has been initialized.
David Sehr709b0702016-10-13 09:12:37 -07001076 CHECK(c->IsInitializing()) << c->GetStatus() << " " << m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -07001077 std::string detail;
Mathieu Chartier46e75d02017-06-02 16:03:39 -07001078 Thread* const self = Thread::Current();
1079 void* native_method = libraries_->FindNativeMethod(self, m, detail);
Alex Light65af20b2017-04-20 09:15:08 -07001080 if (native_method == nullptr) {
1081 // Lookup JNI native methods from native TI Agent libraries. See runtime/ti/agent.h for more
1082 // information. Agent libraries are searched for native methods after all jni libraries.
1083 native_method = FindCodeForNativeMethodInAgents(m);
1084 }
Ian Rogers68d8b422014-07-17 11:09:10 -07001085 // Throwing can cause libraries_lock to be reacquired.
1086 if (native_method == nullptr) {
Alex Light65af20b2017-04-20 09:15:08 -07001087 LOG(ERROR) << detail;
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001088 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
Ian Rogers68d8b422014-07-17 11:09:10 -07001089 }
1090 return native_method;
1091}
1092
Mathieu Chartier97509952015-07-13 14:35:43 -07001093void JavaVMExt::SweepJniWeakGlobals(IsMarkedVisitor* visitor) {
Andreas Gampe05a364c2016-10-14 13:27:12 -07001094 MutexLock mu(Thread::Current(), *Locks::jni_weak_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001095 Runtime* const runtime = Runtime::Current();
1096 for (auto* entry : weak_globals_) {
1097 // Need to skip null here to distinguish between null entries and cleared weak ref entries.
1098 if (!entry->IsNull()) {
1099 // Since this is called by the GC, we don't need a read barrier.
1100 mirror::Object* obj = entry->Read<kWithoutReadBarrier>();
Mathieu Chartier97509952015-07-13 14:35:43 -07001101 mirror::Object* new_obj = visitor->IsMarked(obj);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001102 if (new_obj == nullptr) {
1103 new_obj = runtime->GetClearedJniWeakGlobal();
1104 }
1105 *entry = GcRoot<mirror::Object>(new_obj);
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -07001106 }
Ian Rogers68d8b422014-07-17 11:09:10 -07001107 }
1108}
1109
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001110void JavaVMExt::TrimGlobals() {
Andreas Gampe05a364c2016-10-14 13:27:12 -07001111 WriterMutexLock mu(Thread::Current(), *Locks::jni_globals_lock_);
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001112 globals_.Trim();
1113}
1114
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001115void JavaVMExt::VisitRoots(RootVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001116 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -07001117 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001118 globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal));
Ian Rogers68d8b422014-07-17 11:09:10 -07001119 // The weak_globals table is visited by the GC itself (because it mutates the table).
1120}
1121
1122// JNI Invocation interface.
1123
1124extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001125 ScopedTrace trace(__FUNCTION__);
Ian Rogers68d8b422014-07-17 11:09:10 -07001126 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
Alex Light185d1342016-08-11 10:48:03 -07001127 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001128 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
1129 return JNI_EVERSION;
1130 }
1131 RuntimeOptions options;
1132 for (int i = 0; i < args->nOptions; ++i) {
1133 JavaVMOption* option = &args->options[i];
1134 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
1135 }
1136 bool ignore_unrecognized = args->ignoreUnrecognized;
1137 if (!Runtime::Create(options, ignore_unrecognized)) {
1138 return JNI_ERR;
1139 }
Dimitry Ivanovc544f342016-05-09 16:26:13 -07001140
1141 // Initialize native loader. This step makes sure we have
1142 // everything set up before we start using JNI.
1143 android::InitializeNativeLoader();
1144
Ian Rogers68d8b422014-07-17 11:09:10 -07001145 Runtime* runtime = Runtime::Current();
1146 bool started = runtime->Start();
1147 if (!started) {
1148 delete Thread::Current()->GetJniEnv();
1149 delete runtime->GetJavaVM();
1150 LOG(WARNING) << "CreateJavaVM failed";
1151 return JNI_ERR;
1152 }
Dimitry Ivanov041169f2016-04-21 16:01:24 -07001153
Ian Rogers68d8b422014-07-17 11:09:10 -07001154 *p_env = Thread::Current()->GetJniEnv();
1155 *p_vm = runtime->GetJavaVM();
1156 return JNI_OK;
1157}
1158
Ian Rogersf4d4da12014-11-11 16:10:33 -08001159extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001160 Runtime* runtime = Runtime::Current();
Ian Rogersf4d4da12014-11-11 16:10:33 -08001161 if (runtime == nullptr || buf_len == 0) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001162 *vm_count = 0;
1163 } else {
1164 *vm_count = 1;
Ian Rogersf4d4da12014-11-11 16:10:33 -08001165 vms_buf[0] = runtime->GetJavaVM();
Ian Rogers68d8b422014-07-17 11:09:10 -07001166 }
1167 return JNI_OK;
1168}
1169
1170// Historically unsupported.
1171extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
1172 return JNI_ERR;
1173}
1174
1175} // namespace art