blob: a61a48a29b00c5d7e6ff20cc16a2bb6c87663085 [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"
David Brazdil2bb2fbd2018-11-13 18:24:26 +000026#include "base/sdk_version.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070027#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080028#include "base/systrace.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070029#include "check_jni.h"
David Sehr9e734c72018-01-04 17:56:19 -080030#include "dex/dex_file-inl.h"
Mathieu Chartierd0004802014-10-15 16:59:47 -070031#include "fault_handler.h"
Andreas Gampe1b35b462017-09-29 18:52:15 -070032#include "gc/allocation_record.h"
33#include "gc/heap.h"
Andreas Gamped4901292017-05-30 18:41:34 -070034#include "gc_root-inl.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070035#include "indirect_reference_table-inl.h"
Andreas Gampe57cf00b2017-06-05 17:15:32 -070036#include "jni_internal.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070037#include "mirror/class-inl.h"
38#include "mirror/class_loader.h"
Calin Juravlec8423522014-08-12 20:55:20 +010039#include "nativebridge/native_bridge.h"
Andreas Gampe373a9b52017-10-18 09:01:57 -070040#include "nativehelper/scoped_local_ref.h"
41#include "nativehelper/scoped_utf_chars.h"
Dmitriy Ivanovf5a30992015-11-11 14:18:55 -080042#include "nativeloader/native_loader.h"
Andreas Gampe57cf00b2017-06-05 17:15:32 -070043#include "object_callbacks.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070044#include "parsed_options.h"
Ian Rogersc0542af2014-09-03 16:16:56 -070045#include "runtime-inl.h"
Igor Murashkinaaebaa02015-01-26 10:55:53 -080046#include "runtime_options.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070047#include "scoped_thread_state_change-inl.h"
Josh Gao85a78cf2017-03-20 16:26:42 -070048#include "sigchain.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070049#include "thread-inl.h"
50#include "thread_list.h"
Steven Morelande431e272017-07-18 16:53:49 -070051#include "ti/agent.h"
Andreas Gampe473191c2017-12-28 16:55:31 -080052#include "well_known_classes.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070053
54namespace art {
55
Andreas Gampe46ee31b2016-12-14 10:11:49 -080056using android::base::StringAppendF;
57using android::base::StringAppendV;
58
Andreas Gampea8e3b862016-10-17 20:12:52 -070059static constexpr size_t kGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
Ian Rogers68d8b422014-07-17 11:09:10 -070060
Andreas Gampea8e3b862016-10-17 20:12:52 -070061static constexpr size_t kWeakGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
Ian Rogers68d8b422014-07-17 11:09:10 -070062
Alex Light185d1342016-08-11 10:48:03 -070063bool JavaVMExt::IsBadJniVersion(int version) {
Ian Rogers68d8b422014-07-17 11:09:10 -070064 // We don't support JNI_VERSION_1_1. These are the only other valid versions.
65 return version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 && version != JNI_VERSION_1_6;
66}
67
68class SharedLibrary {
69 public:
70 SharedLibrary(JNIEnv* env, Thread* self, const std::string& path, void* handle,
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080071 bool needs_native_bridge, jobject class_loader, void* class_loader_allocator)
Ian Rogers68d8b422014-07-17 11:09:10 -070072 : path_(path),
73 handle_(handle),
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080074 needs_native_bridge_(needs_native_bridge),
Mathieu Chartier598302a2015-09-23 14:52:39 -070075 class_loader_(env->NewWeakGlobalRef(class_loader)),
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080076 class_loader_allocator_(class_loader_allocator),
Ian Rogers68d8b422014-07-17 11:09:10 -070077 jni_on_load_lock_("JNI_OnLoad lock"),
78 jni_on_load_cond_("JNI_OnLoad condition variable", jni_on_load_lock_),
79 jni_on_load_thread_id_(self->GetThreadId()),
80 jni_on_load_result_(kPending) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080081 CHECK(class_loader_allocator_ != nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -070082 }
83
84 ~SharedLibrary() {
85 Thread* self = Thread::Current();
86 if (self != nullptr) {
Mathieu Chartier598302a2015-09-23 14:52:39 -070087 self->GetJniEnv()->DeleteWeakGlobalRef(class_loader_);
Ian Rogers68d8b422014-07-17 11:09:10 -070088 }
Alex Lightbc5669e2016-06-13 17:22:13 +000089
dimitry947573e2018-09-12 01:12:56 +020090 std::string error_msg;
91 if (!android::CloseNativeLibrary(handle_, needs_native_bridge_, &error_msg)) {
92 LOG(WARNING) << "Error while unloading native library \"" << path_ << "\": " << error_msg;
93 }
Ian Rogers68d8b422014-07-17 11:09:10 -070094 }
95
Mathieu Chartier598302a2015-09-23 14:52:39 -070096 jweak GetClassLoader() const {
Ian Rogers68d8b422014-07-17 11:09:10 -070097 return class_loader_;
98 }
99
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800100 const void* GetClassLoaderAllocator() const {
101 return class_loader_allocator_;
102 }
103
Ian Rogers68d8b422014-07-17 11:09:10 -0700104 const std::string& GetPath() const {
105 return path_;
106 }
107
108 /*
109 * Check the result of an earlier call to JNI_OnLoad on this library.
110 * If the call has not yet finished in another thread, wait for it.
111 */
112 bool CheckOnLoadResult()
Mathieu Chartier90443472015-07-16 20:32:27 -0700113 REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700114 Thread* self = Thread::Current();
115 bool okay;
116 {
117 MutexLock mu(self, jni_on_load_lock_);
118
119 if (jni_on_load_thread_id_ == self->GetThreadId()) {
120 // Check this so we don't end up waiting for ourselves. We need to return "true" so the
121 // caller can continue.
122 LOG(INFO) << *self << " recursive attempt to load library " << "\"" << path_ << "\"";
123 okay = true;
124 } else {
125 while (jni_on_load_result_ == kPending) {
126 VLOG(jni) << "[" << *self << " waiting for \"" << path_ << "\" " << "JNI_OnLoad...]";
127 jni_on_load_cond_.Wait(self);
128 }
129
130 okay = (jni_on_load_result_ == kOkay);
131 VLOG(jni) << "[Earlier JNI_OnLoad for \"" << path_ << "\" "
132 << (okay ? "succeeded" : "failed") << "]";
133 }
134 }
135 return okay;
136 }
137
Mathieu Chartier90443472015-07-16 20:32:27 -0700138 void SetResult(bool result) REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700139 Thread* self = Thread::Current();
140 MutexLock mu(self, jni_on_load_lock_);
141
142 jni_on_load_result_ = result ? kOkay : kFailed;
143 jni_on_load_thread_id_ = 0;
144
145 // Broadcast a wakeup to anybody sleeping on the condition variable.
146 jni_on_load_cond_.Broadcast(self);
147 }
148
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800149 void SetNeedsNativeBridge(bool needs) {
150 needs_native_bridge_ = needs;
Ian Rogers68d8b422014-07-17 11:09:10 -0700151 }
152
153 bool NeedsNativeBridge() const {
154 return needs_native_bridge_;
155 }
156
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700157 // No mutator lock since dlsym may block for a while if another thread is doing dlopen.
158 void* FindSymbol(const std::string& symbol_name, const char* shorty = nullptr)
159 REQUIRES(!Locks::mutator_lock_) {
Mathieu Chartier598302a2015-09-23 14:52:39 -0700160 return NeedsNativeBridge()
161 ? FindSymbolWithNativeBridge(symbol_name.c_str(), shorty)
162 : FindSymbolWithoutNativeBridge(symbol_name.c_str());
163 }
164
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700165 // No mutator lock since dlsym may block for a while if another thread is doing dlopen.
166 void* FindSymbolWithoutNativeBridge(const std::string& symbol_name)
167 REQUIRES(!Locks::mutator_lock_) {
Andreas Gampe8fec90b2015-06-30 11:23:44 -0700168 CHECK(!NeedsNativeBridge());
169
Ian Rogers68d8b422014-07-17 11:09:10 -0700170 return dlsym(handle_, symbol_name.c_str());
171 }
172
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700173 void* FindSymbolWithNativeBridge(const std::string& symbol_name, const char* shorty)
174 REQUIRES(!Locks::mutator_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700175 CHECK(NeedsNativeBridge());
176
177 uint32_t len = 0;
Calin Juravlec8423522014-08-12 20:55:20 +0100178 return android::NativeBridgeGetTrampoline(handle_, symbol_name.c_str(), shorty, len);
Ian Rogers68d8b422014-07-17 11:09:10 -0700179 }
180
181 private:
182 enum JNI_OnLoadState {
183 kPending,
184 kFailed,
185 kOkay,
186 };
187
188 // Path to library "/system/lib/libjni.so".
189 const std::string path_;
190
191 // The void* returned by dlopen(3).
192 void* const handle_;
193
194 // True if a native bridge is required.
195 bool needs_native_bridge_;
196
Mathieu Chartier598302a2015-09-23 14:52:39 -0700197 // The ClassLoader this library is associated with, a weak global JNI reference that is
Ian Rogers68d8b422014-07-17 11:09:10 -0700198 // created/deleted with the scope of the library.
Mathieu Chartier598302a2015-09-23 14:52:39 -0700199 const jweak class_loader_;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800200 // Used to do equality check on class loaders so we can avoid decoding the weak root and read
201 // barriers that mess with class unloading.
202 const void* class_loader_allocator_;
Ian Rogers68d8b422014-07-17 11:09:10 -0700203
204 // Guards remaining items.
205 Mutex jni_on_load_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
206 // Wait for JNI_OnLoad in other thread.
207 ConditionVariable jni_on_load_cond_ GUARDED_BY(jni_on_load_lock_);
208 // Recursive invocation guard.
209 uint32_t jni_on_load_thread_id_ GUARDED_BY(jni_on_load_lock_);
210 // Result of earlier JNI_OnLoad call.
211 JNI_OnLoadState jni_on_load_result_ GUARDED_BY(jni_on_load_lock_);
212};
213
214// This exists mainly to keep implementation details out of the header file.
215class Libraries {
216 public:
217 Libraries() {
218 }
219
220 ~Libraries() {
221 STLDeleteValues(&libraries_);
222 }
223
Mathieu Chartier598302a2015-09-23 14:52:39 -0700224 // NO_THREAD_SAFETY_ANALYSIS since this may be called from Dumpable. Dumpable can't be annotated
225 // properly due to the template. The caller should be holding the jni_libraries_lock_.
226 void Dump(std::ostream& os) const NO_THREAD_SAFETY_ANALYSIS {
227 Locks::jni_libraries_lock_->AssertHeld(Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -0700228 bool first = true;
229 for (const auto& library : libraries_) {
230 if (!first) {
231 os << ' ';
232 }
233 first = false;
234 os << library.first;
235 }
236 }
237
Mathieu Chartier598302a2015-09-23 14:52:39 -0700238 size_t size() const REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700239 return libraries_.size();
240 }
241
Mathieu Chartier598302a2015-09-23 14:52:39 -0700242 SharedLibrary* Get(const std::string& path) REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700243 auto it = libraries_.find(path);
244 return (it == libraries_.end()) ? nullptr : it->second;
245 }
246
Mathieu Chartier598302a2015-09-23 14:52:39 -0700247 void Put(const std::string& path, SharedLibrary* library)
248 REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700249 libraries_.Put(path, library);
250 }
251
252 // See section 11.3 "Linking Native Methods" of the JNI spec.
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700253 void* FindNativeMethod(Thread* self, ArtMethod* m, std::string& detail)
254 REQUIRES(!Locks::jni_libraries_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700255 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700256 std::string jni_short_name(m->JniShortName());
257 std::string jni_long_name(m->JniLongName());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800258 mirror::ClassLoader* const declaring_class_loader = m->GetDeclaringClass()->GetClassLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700259 ScopedObjectAccessUnchecked soa(Thread::Current());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800260 void* const declaring_class_loader_allocator =
261 Runtime::Current()->GetClassLinker()->GetAllocatorForClassLoader(declaring_class_loader);
262 CHECK(declaring_class_loader_allocator != nullptr);
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700263 // TODO: Avoid calling GetShorty here to prevent dirtying dex pages?
264 const char* shorty = m->GetShorty();
265 {
266 // Go to suspended since dlsym may block for a long time if other threads are using dlopen.
267 ScopedThreadSuspension sts(self, kNative);
268 void* native_code = FindNativeMethodInternal(self,
269 declaring_class_loader_allocator,
270 shorty,
271 jni_short_name,
272 jni_long_name);
273 if (native_code != nullptr) {
274 return native_code;
Ian Rogers68d8b422014-07-17 11:09:10 -0700275 }
276 }
277 detail += "No implementation found for ";
David Sehr709b0702016-10-13 09:12:37 -0700278 detail += m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700279 detail += " (tried " + jni_short_name + " and " + jni_long_name + ")";
Ian Rogers68d8b422014-07-17 11:09:10 -0700280 return nullptr;
281 }
282
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700283 void* FindNativeMethodInternal(Thread* self,
284 void* declaring_class_loader_allocator,
285 const char* shorty,
286 const std::string& jni_short_name,
287 const std::string& jni_long_name)
288 REQUIRES(!Locks::jni_libraries_lock_)
289 REQUIRES(!Locks::mutator_lock_) {
290 MutexLock mu(self, *Locks::jni_libraries_lock_);
291 for (const auto& lib : libraries_) {
292 SharedLibrary* const library = lib.second;
293 // Use the allocator address for class loader equality to avoid unnecessary weak root decode.
294 if (library->GetClassLoaderAllocator() != declaring_class_loader_allocator) {
295 // We only search libraries loaded by the appropriate ClassLoader.
296 continue;
297 }
298 // Try the short name then the long name...
299 const char* arg_shorty = library->NeedsNativeBridge() ? shorty : nullptr;
300 void* fn = library->FindSymbol(jni_short_name, arg_shorty);
301 if (fn == nullptr) {
302 fn = library->FindSymbol(jni_long_name, arg_shorty);
303 }
304 if (fn != nullptr) {
305 VLOG(jni) << "[Found native code for " << jni_long_name
306 << " in \"" << library->GetPath() << "\"]";
307 return fn;
308 }
309 }
310 return nullptr;
311 }
312
Mathieu Chartier598302a2015-09-23 14:52:39 -0700313 // Unload native libraries with cleared class loaders.
314 void UnloadNativeLibraries()
315 REQUIRES(!Locks::jni_libraries_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700316 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700317 Thread* const self = Thread::Current();
Alex Lightbc5669e2016-06-13 17:22:13 +0000318 std::vector<SharedLibrary*> unload_libraries;
Mathieu Chartier598302a2015-09-23 14:52:39 -0700319 {
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700320 MutexLock mu(self, *Locks::jni_libraries_lock_);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700321 for (auto it = libraries_.begin(); it != libraries_.end(); ) {
322 SharedLibrary* const library = it->second;
323 // If class loader is null then it was unloaded, call JNI_OnUnload.
Mathieu Chartiercffb7472015-09-28 10:33:00 -0700324 const jweak class_loader = library->GetClassLoader();
325 // If class_loader is a null jobject then it is the boot class loader. We should not unload
326 // the native libraries of the boot class loader.
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700327 if (class_loader != nullptr && self->IsJWeakCleared(class_loader)) {
Alex Lightbc5669e2016-06-13 17:22:13 +0000328 unload_libraries.push_back(library);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700329 it = libraries_.erase(it);
330 } else {
331 ++it;
332 }
333 }
334 }
Mathieu Chartier46e75d02017-06-02 16:03:39 -0700335 ScopedThreadSuspension sts(self, kNative);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700336 // Do this without holding the jni libraries lock to prevent possible deadlocks.
Andreas Gampec55bb392018-09-21 00:02:02 +0000337 using JNI_OnUnloadFn = void(*)(JavaVM*, void*);
Alex Lightbc5669e2016-06-13 17:22:13 +0000338 for (auto library : unload_libraries) {
339 void* const sym = library->FindSymbol("JNI_OnUnload", nullptr);
340 if (sym == nullptr) {
341 VLOG(jni) << "[No JNI_OnUnload found in \"" << library->GetPath() << "\"]";
342 } else {
343 VLOG(jni) << "[JNI_OnUnload found for \"" << library->GetPath() << "\"]: Calling...";
344 JNI_OnUnloadFn jni_on_unload = reinterpret_cast<JNI_OnUnloadFn>(sym);
Ian Rogers55256cb2017-12-21 17:07:11 -0800345 jni_on_unload(self->GetJniEnv()->GetVm(), nullptr);
Alex Lightbc5669e2016-06-13 17:22:13 +0000346 }
347 delete library;
Mathieu Chartier598302a2015-09-23 14:52:39 -0700348 }
349 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700350
Mathieu Chartier598302a2015-09-23 14:52:39 -0700351 private:
352 AllocationTrackingSafeMap<std::string, SharedLibrary*, kAllocatorTagJNILibraries> libraries_
353 GUARDED_BY(Locks::jni_libraries_lock_);
354};
Ian Rogers68d8b422014-07-17 11:09:10 -0700355
356class JII {
357 public:
358 static jint DestroyJavaVM(JavaVM* vm) {
359 if (vm == nullptr) {
360 return JNI_ERR;
361 }
362 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
363 delete raw_vm->GetRuntime();
Dimitry Ivanov39d68ef2016-04-29 16:02:38 -0700364 android::ResetNativeLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700365 return JNI_OK;
366 }
367
368 static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
369 return AttachCurrentThreadInternal(vm, p_env, thr_args, false);
370 }
371
372 static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
373 return AttachCurrentThreadInternal(vm, p_env, thr_args, true);
374 }
375
376 static jint DetachCurrentThread(JavaVM* vm) {
377 if (vm == nullptr || Thread::Current() == nullptr) {
378 return JNI_ERR;
379 }
380 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
381 Runtime* runtime = raw_vm->GetRuntime();
382 runtime->DetachCurrentThread();
383 return JNI_OK;
384 }
385
386 static jint GetEnv(JavaVM* vm, void** env, jint version) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700387 if (vm == nullptr || env == nullptr) {
388 return JNI_ERR;
389 }
390 Thread* thread = Thread::Current();
391 if (thread == nullptr) {
392 *env = nullptr;
393 return JNI_EDETACHED;
394 }
Alex Light185d1342016-08-11 10:48:03 -0700395 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
396 return raw_vm->HandleGetEnv(env, version);
Ian Rogers68d8b422014-07-17 11:09:10 -0700397 }
398
399 private:
400 static jint AttachCurrentThreadInternal(JavaVM* vm, JNIEnv** p_env, void* raw_args, bool as_daemon) {
401 if (vm == nullptr || p_env == nullptr) {
402 return JNI_ERR;
403 }
404
405 // Return immediately if we're already attached.
406 Thread* self = Thread::Current();
407 if (self != nullptr) {
408 *p_env = self->GetJniEnv();
409 return JNI_OK;
410 }
411
412 Runtime* runtime = reinterpret_cast<JavaVMExt*>(vm)->GetRuntime();
413
414 // No threads allowed in zygote mode.
415 if (runtime->IsZygote()) {
416 LOG(ERROR) << "Attempt to attach a thread in the zygote";
417 return JNI_ERR;
418 }
419
420 JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(raw_args);
421 const char* thread_name = nullptr;
422 jobject thread_group = nullptr;
423 if (args != nullptr) {
Alex Light185d1342016-08-11 10:48:03 -0700424 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700425 LOG(ERROR) << "Bad JNI version passed to "
426 << (as_daemon ? "AttachCurrentThreadAsDaemon" : "AttachCurrentThread") << ": "
427 << args->version;
428 return JNI_EVERSION;
429 }
430 thread_name = args->name;
431 thread_group = args->group;
432 }
433
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800434 if (!runtime->AttachCurrentThread(thread_name, as_daemon, thread_group,
435 !runtime->IsAotCompiler())) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700436 *p_env = nullptr;
437 return JNI_ERR;
438 } else {
439 *p_env = Thread::Current()->GetJniEnv();
440 return JNI_OK;
441 }
442 }
443};
444
445const JNIInvokeInterface gJniInvokeInterface = {
446 nullptr, // reserved0
447 nullptr, // reserved1
448 nullptr, // reserved2
449 JII::DestroyJavaVM,
450 JII::AttachCurrentThread,
451 JII::DetachCurrentThread,
452 JII::GetEnv,
453 JII::AttachCurrentThreadAsDaemon
454};
455
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100456JavaVMExt::JavaVMExt(Runtime* runtime,
457 const RuntimeArgumentMap& runtime_options,
458 std::string* error_msg)
Ian Rogers68d8b422014-07-17 11:09:10 -0700459 : runtime_(runtime),
460 check_jni_abort_hook_(nullptr),
461 check_jni_abort_hook_data_(nullptr),
462 check_jni_(false), // Initialized properly in the constructor body below.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800463 force_copy_(runtime_options.Exists(RuntimeArgumentMap::JniOptsForceCopy)),
464 tracing_enabled_(runtime_options.Exists(RuntimeArgumentMap::JniTrace)
465 || VLOG_IS_ON(third_party_jni)),
466 trace_(runtime_options.GetOrDefault(RuntimeArgumentMap::JniTrace)),
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700467 globals_(kGlobalsMax, kGlobal, IndirectReferenceTable::ResizableCapacity::kNo, error_msg),
Ian Rogers68d8b422014-07-17 11:09:10 -0700468 libraries_(new Libraries),
469 unchecked_functions_(&gJniInvokeInterface),
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700470 weak_globals_(kWeakGlobalsMax,
471 kWeakGlobal,
472 IndirectReferenceTable::ResizableCapacity::kNo,
473 error_msg),
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700474 allow_accessing_weak_globals_(true),
Andreas Gampe05a364c2016-10-14 13:27:12 -0700475 weak_globals_add_condition_("weak globals add condition",
476 (CHECK(Locks::jni_weak_globals_lock_ != nullptr),
477 *Locks::jni_weak_globals_lock_)),
Andreas Gampe1b35b462017-09-29 18:52:15 -0700478 env_hooks_(),
479 enable_allocation_tracking_delta_(
480 runtime_options.GetOrDefault(RuntimeArgumentMap::GlobalRefAllocStackTraceLimit)),
481 allocation_tracking_enabled_(false),
482 old_allocation_tracking_state_(false) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700483 functions = unchecked_functions_;
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800484 SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni));
Ian Rogers68d8b422014-07-17 11:09:10 -0700485}
486
487JavaVMExt::~JavaVMExt() {
488}
489
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100490// Checking "globals" and "weak_globals" usually requires locks, but we
491// don't need the locks to check for validity when constructing the
492// object. Use NO_THREAD_SAFETY_ANALYSIS for this.
493std::unique_ptr<JavaVMExt> JavaVMExt::Create(Runtime* runtime,
494 const RuntimeArgumentMap& runtime_options,
495 std::string* error_msg) NO_THREAD_SAFETY_ANALYSIS {
496 std::unique_ptr<JavaVMExt> java_vm(new JavaVMExt(runtime, runtime_options, error_msg));
497 if (java_vm && java_vm->globals_.IsValid() && java_vm->weak_globals_.IsValid()) {
498 return java_vm;
499 }
500 return nullptr;
501}
502
Alex Light185d1342016-08-11 10:48:03 -0700503jint JavaVMExt::HandleGetEnv(/*out*/void** env, jint version) {
504 for (GetEnvHook hook : env_hooks_) {
505 jint res = hook(this, env, version);
506 if (res == JNI_OK) {
507 return JNI_OK;
508 } else if (res != JNI_EVERSION) {
509 LOG(ERROR) << "Error returned from a plugin GetEnv handler! " << res;
510 return res;
511 }
512 }
513 LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version;
514 return JNI_EVERSION;
515}
516
517// Add a hook to handle getting environments from the GetEnv call.
518void JavaVMExt::AddEnvironmentHook(GetEnvHook hook) {
519 CHECK(hook != nullptr) << "environment hooks shouldn't be null!";
520 env_hooks_.push_back(hook);
521}
522
Ian Rogers68d8b422014-07-17 11:09:10 -0700523void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) {
524 Thread* self = Thread::Current();
525 ScopedObjectAccess soa(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700526 ArtMethod* current_method = self->GetCurrentMethod(nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700527
528 std::ostringstream os;
529 os << "JNI DETECTED ERROR IN APPLICATION: " << msg;
530
531 if (jni_function_name != nullptr) {
532 os << "\n in call to " << jni_function_name;
533 }
534 // TODO: is this useful given that we're about to dump the calling thread's stack?
535 if (current_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700536 os << "\n from " << current_method->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700537 }
538 os << "\n";
539 self->Dump(os);
540
541 if (check_jni_abort_hook_ != nullptr) {
542 check_jni_abort_hook_(check_jni_abort_hook_data_, os.str());
543 } else {
544 // Ensure that we get a native stack trace for this thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700545 ScopedThreadSuspension sts(self, kNative);
Ian Rogers68d8b422014-07-17 11:09:10 -0700546 LOG(FATAL) << os.str();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700547 UNREACHABLE();
Ian Rogers68d8b422014-07-17 11:09:10 -0700548 }
549}
550
551void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) {
552 std::string msg;
553 StringAppendV(&msg, fmt, ap);
554 JniAbort(jni_function_name, msg.c_str());
555}
556
557void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) {
558 va_list args;
559 va_start(args, fmt);
560 JniAbortV(jni_function_name, fmt, args);
561 va_end(args);
562}
563
Mathieu Chartiere401d142015-04-22 13:56:20 -0700564bool JavaVMExt::ShouldTrace(ArtMethod* method) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700565 // Fast where no tracing is enabled.
566 if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) {
567 return false;
568 }
569 // Perform checks based on class name.
570 StringPiece class_name(method->GetDeclaringClassDescriptor());
571 if (!trace_.empty() && class_name.find(trace_) != std::string::npos) {
572 return true;
573 }
574 if (!VLOG_IS_ON(third_party_jni)) {
575 return false;
576 }
577 // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
578 // like part of Android.
579 static const char* gBuiltInPrefixes[] = {
580 "Landroid/",
581 "Lcom/android/",
582 "Lcom/google/android/",
583 "Ldalvik/",
584 "Ljava/",
585 "Ljavax/",
586 "Llibcore/",
587 "Lorg/apache/harmony/",
588 };
589 for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) {
590 if (class_name.starts_with(gBuiltInPrefixes[i])) {
591 return false;
592 }
593 }
594 return true;
595}
596
Andreas Gampe1b35b462017-09-29 18:52:15 -0700597void JavaVMExt::CheckGlobalRefAllocationTracking() {
598 if (LIKELY(enable_allocation_tracking_delta_ == 0)) {
599 return;
600 }
601 size_t simple_free_capacity = globals_.FreeCapacity();
602 if (UNLIKELY(simple_free_capacity <= enable_allocation_tracking_delta_)) {
603 if (!allocation_tracking_enabled_) {
604 LOG(WARNING) << "Global reference storage appears close to exhaustion, program termination "
605 << "may be imminent. Enabling allocation tracking to improve abort diagnostics. "
606 << "This will result in program slow-down.";
607
608 old_allocation_tracking_state_ = runtime_->GetHeap()->IsAllocTrackingEnabled();
609 if (!old_allocation_tracking_state_) {
610 // Need to be guaranteed suspended.
611 ScopedObjectAccess soa(Thread::Current());
612 ScopedThreadSuspension sts(soa.Self(), ThreadState::kNative);
613 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(true);
614 }
615 allocation_tracking_enabled_ = true;
616 }
617 } else {
618 if (UNLIKELY(allocation_tracking_enabled_)) {
619 if (!old_allocation_tracking_state_) {
620 // Need to be guaranteed suspended.
621 ScopedObjectAccess soa(Thread::Current());
622 ScopedThreadSuspension sts(soa.Self(), ThreadState::kNative);
623 gc::AllocRecordObjectMap::SetAllocTrackingEnabled(false);
624 }
Andreas Gampe45485342017-10-11 12:04:35 -0700625 allocation_tracking_enabled_ = false;
Andreas Gampe1b35b462017-09-29 18:52:15 -0700626 }
627 }
628}
629
Mathieu Chartier0795f232016-09-27 18:43:30 -0700630jobject JavaVMExt::AddGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700631 // Check for null after decoding the object to handle cleared weak globals.
632 if (obj == nullptr) {
633 return nullptr;
634 }
Andreas Gampe1b35b462017-09-29 18:52:15 -0700635 IndirectRef ref;
Andreas Gampe25651122017-09-25 14:50:23 -0700636 std::string error_msg;
Andreas Gampe1b35b462017-09-29 18:52:15 -0700637 {
638 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
639 ref = globals_.Add(kIRTFirstSegment, obj, &error_msg);
640 }
Andreas Gampe25651122017-09-25 14:50:23 -0700641 if (UNLIKELY(ref == nullptr)) {
642 LOG(FATAL) << error_msg;
643 UNREACHABLE();
644 }
Andreas Gampe1b35b462017-09-29 18:52:15 -0700645 CheckGlobalRefAllocationTracking();
Ian Rogers68d8b422014-07-17 11:09:10 -0700646 return reinterpret_cast<jobject>(ref);
647}
648
Mathieu Chartier0795f232016-09-27 18:43:30 -0700649jweak JavaVMExt::AddWeakGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700650 if (obj == nullptr) {
651 return nullptr;
652 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700653 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchif1c6f872017-01-06 12:23:47 -0800654 // CMS needs this to block for concurrent reference processing because an object allocated during
655 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
656 // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant.
657 while (!kUseReadBarrier && UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700658 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
659 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800660 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700661 weak_globals_add_condition_.WaitHoldingLocks(self);
662 }
Andreas Gampe25651122017-09-25 14:50:23 -0700663 std::string error_msg;
664 IndirectRef ref = weak_globals_.Add(kIRTFirstSegment, obj, &error_msg);
665 if (UNLIKELY(ref == nullptr)) {
666 LOG(FATAL) << error_msg;
667 UNREACHABLE();
668 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700669 return reinterpret_cast<jweak>(ref);
670}
671
672void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
673 if (obj == nullptr) {
674 return;
675 }
Andreas Gampe1b35b462017-09-29 18:52:15 -0700676 {
677 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
678 if (!globals_.Remove(kIRTFirstSegment, obj)) {
679 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
680 << "failed to find entry";
681 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700682 }
Andreas Gampe1b35b462017-09-29 18:52:15 -0700683 CheckGlobalRefAllocationTracking();
Ian Rogers68d8b422014-07-17 11:09:10 -0700684}
685
686void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
687 if (obj == nullptr) {
688 return;
689 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700690 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700691 if (!weak_globals_.Remove(kIRTFirstSegment, obj)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700692 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
693 << "failed to find entry";
694 }
695}
696
697static void ThreadEnableCheckJni(Thread* thread, void* arg) {
698 bool* check_jni = reinterpret_cast<bool*>(arg);
699 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
700}
701
702bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
703 bool old_check_jni = check_jni_;
704 check_jni_ = enabled;
705 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
706 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
707 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
708 return old_check_jni;
709}
710
711void JavaVMExt::DumpForSigQuit(std::ostream& os) {
712 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
713 if (force_copy_) {
714 os << " (with forcecopy)";
715 }
716 Thread* self = Thread::Current();
717 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700718 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700719 os << "; globals=" << globals_.Capacity();
720 }
721 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700722 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700723 if (weak_globals_.Capacity() > 0) {
724 os << " (plus " << weak_globals_.Capacity() << " weak)";
725 }
726 }
727 os << '\n';
728
729 {
730 MutexLock mu(self, *Locks::jni_libraries_lock_);
731 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
732 }
733}
734
735void JavaVMExt::DisallowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700736 CHECK(!kUseReadBarrier);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700737 Thread* const self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700738 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700739 // DisallowNewWeakGlobals is only called by CMS during the pause. It is required to have the
740 // mutator lock exclusively held so that we don't have any threads in the middle of
741 // DecodeWeakGlobal.
742 Locks::mutator_lock_->AssertExclusiveHeld(self);
Orion Hodson88591fe2018-03-06 13:35:43 +0000743 allow_accessing_weak_globals_.store(false, std::memory_order_seq_cst);
Ian Rogers68d8b422014-07-17 11:09:10 -0700744}
745
746void JavaVMExt::AllowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700747 CHECK(!kUseReadBarrier);
Ian Rogers68d8b422014-07-17 11:09:10 -0700748 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700749 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Orion Hodson88591fe2018-03-06 13:35:43 +0000750 allow_accessing_weak_globals_.store(true, std::memory_order_seq_cst);
Ian Rogers68d8b422014-07-17 11:09:10 -0700751 weak_globals_add_condition_.Broadcast(self);
752}
753
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700754void JavaVMExt::BroadcastForNewWeakGlobals() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700755 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700756 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700757 weak_globals_add_condition_.Broadcast(self);
758}
759
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700760ObjPtr<mirror::Object> JavaVMExt::DecodeGlobal(IndirectRef ref) {
761 return globals_.SynchronizedGet(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700762}
763
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700764void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700765 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700766 globals_.Update(ref, result);
767}
768
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700769inline bool JavaVMExt::MayAccessWeakGlobals(Thread* self) const {
770 return MayAccessWeakGlobalsUnlocked(self);
771}
772
773inline bool JavaVMExt::MayAccessWeakGlobalsUnlocked(Thread* self) const {
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700774 DCHECK(self != nullptr);
775 return kUseReadBarrier ?
776 self->GetWeakRefAccessEnabled() :
Orion Hodson88591fe2018-03-06 13:35:43 +0000777 allow_accessing_weak_globals_.load(std::memory_order_seq_cst);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700778}
779
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700780ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700781 // It is safe to access GetWeakRefAccessEnabled without the lock since CC uses checkpoints to call
782 // SetWeakRefAccessEnabled, and the other collectors only modify allow_accessing_weak_globals_
783 // when the mutators are paused.
784 // This only applies in the case where MayAccessWeakGlobals goes from false to true. In the other
785 // case, it may be racy, this is benign since DecodeWeakGlobalLocked does the correct behavior
786 // if MayAccessWeakGlobals is false.
Andreas Gampedc061d02016-10-24 13:19:37 -0700787 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700788 if (LIKELY(MayAccessWeakGlobalsUnlocked(self))) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700789 return weak_globals_.SynchronizedGet(ref);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700790 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700791 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700792 return DecodeWeakGlobalLocked(self, ref);
793}
794
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700795ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalLocked(Thread* self, IndirectRef ref) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700796 if (kDebugLocking) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700797 Locks::jni_weak_globals_lock_->AssertHeld(self);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700798 }
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700799 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700800 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
801 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800802 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700803 weak_globals_add_condition_.WaitHoldingLocks(self);
804 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700805 return weak_globals_.Get(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700806}
807
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700808ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalDuringShutdown(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700809 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700810 DCHECK(Runtime::Current()->IsShuttingDown(self));
811 if (self != nullptr) {
812 return DecodeWeakGlobal(self, ref);
813 }
814 // self can be null during a runtime shutdown. ~Runtime()->~ClassLinker()->DecodeWeakGlobal().
815 if (!kUseReadBarrier) {
Orion Hodson88591fe2018-03-06 13:35:43 +0000816 DCHECK(allow_accessing_weak_globals_.load(std::memory_order_seq_cst));
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700817 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700818 return weak_globals_.SynchronizedGet(ref);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700819}
820
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800821bool JavaVMExt::IsWeakGlobalCleared(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700822 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Andreas Gampe05a364c2016-10-14 13:27:12 -0700823 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800824 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700825 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
826 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800827 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800828 weak_globals_add_condition_.WaitHoldingLocks(self);
829 }
830 // When just checking a weak ref has been cleared, avoid triggering the read barrier in decode
831 // (DecodeWeakGlobal) so that we won't accidentally mark the object alive. Since the cleared
832 // sentinel is a non-moving object, we can compare the ref to it without the read barrier and
833 // decide if it's cleared.
834 return Runtime::Current()->IsClearedJniWeakGlobal(weak_globals_.Get<kWithoutReadBarrier>(ref));
835}
836
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700837void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700838 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700839 weak_globals_.Update(ref, result);
840}
841
Ian Rogers68d8b422014-07-17 11:09:10 -0700842void JavaVMExt::DumpReferenceTables(std::ostream& os) {
843 Thread* self = Thread::Current();
844 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700845 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700846 globals_.Dump(os);
847 }
848 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700849 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700850 weak_globals_.Dump(os);
851 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700852}
853
Mathieu Chartier598302a2015-09-23 14:52:39 -0700854void JavaVMExt::UnloadNativeLibraries() {
855 libraries_.get()->UnloadNativeLibraries();
856}
857
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800858bool JavaVMExt::LoadNativeLibrary(JNIEnv* env,
859 const std::string& path,
860 jobject class_loader,
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800861 std::string* error_msg) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700862 error_msg->clear();
863
864 // See if we've already loaded this library. If we have, and the class loader
865 // matches, return successfully without doing anything.
866 // TODO: for better results we should canonicalize the pathname (or even compare
867 // inodes). This implementation is fine if everybody is using System.loadLibrary.
868 SharedLibrary* library;
869 Thread* self = Thread::Current();
870 {
871 // TODO: move the locking (and more of this logic) into Libraries.
872 MutexLock mu(self, *Locks::jni_libraries_lock_);
873 library = libraries_->Get(path);
874 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800875 void* class_loader_allocator = nullptr;
876 {
877 ScopedObjectAccess soa(env);
878 // As the incoming class loader is reachable/alive during the call of this function,
879 // it's okay to decode it without worrying about unexpectedly marking it alive.
Mathieu Chartier0795f232016-09-27 18:43:30 -0700880 ObjPtr<mirror::ClassLoader> loader = soa.Decode<mirror::ClassLoader>(class_loader);
Andreas Gampe2d48e532016-06-17 12:46:14 -0700881
882 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700883 if (class_linker->IsBootClassLoader(soa, loader.Ptr())) {
Andreas Gampe2d48e532016-06-17 12:46:14 -0700884 loader = nullptr;
885 class_loader = nullptr;
886 }
887
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700888 class_loader_allocator = class_linker->GetAllocatorForClassLoader(loader.Ptr());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800889 CHECK(class_loader_allocator != nullptr);
890 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700891 if (library != nullptr) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800892 // Use the allocator pointers for class loader equality to avoid unnecessary weak root decode.
893 if (library->GetClassLoaderAllocator() != class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700894 // The library will be associated with class_loader. The JNI
895 // spec says we can't load the same library into more than one
896 // class loader.
Andreas Gampefd03f1e2017-09-19 17:10:10 -0700897 //
898 // This isn't very common. So spend some time to get a readable message.
899 auto call_to_string = [&](jobject obj) -> std::string {
900 if (obj == nullptr) {
901 return "null";
902 }
903 // Handle jweaks. Ignore double local-ref.
904 ScopedLocalRef<jobject> local_ref(env, env->NewLocalRef(obj));
905 if (local_ref != nullptr) {
906 ScopedLocalRef<jclass> local_class(env, env->GetObjectClass(local_ref.get()));
907 jmethodID to_string = env->GetMethodID(local_class.get(),
908 "toString",
909 "()Ljava/lang/String;");
910 DCHECK(to_string != nullptr);
911 ScopedLocalRef<jobject> local_string(env,
912 env->CallObjectMethod(local_ref.get(), to_string));
913 if (local_string != nullptr) {
914 ScopedUtfChars utf(env, reinterpret_cast<jstring>(local_string.get()));
915 if (utf.c_str() != nullptr) {
916 return utf.c_str();
917 }
918 }
Andreas Gampe3362d222018-06-05 16:02:10 -0700919 if (env->ExceptionCheck()) {
920 // We can't do much better logging, really. So leave it with a Describe.
921 env->ExceptionDescribe();
922 env->ExceptionClear();
923 }
Andreas Gampefd03f1e2017-09-19 17:10:10 -0700924 return "(Error calling toString)";
925 }
926 return "null";
927 };
928 std::string old_class_loader = call_to_string(library->GetClassLoader());
929 std::string new_class_loader = call_to_string(class_loader);
Ian Rogers68d8b422014-07-17 11:09:10 -0700930 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
Andreas Gampefd03f1e2017-09-19 17:10:10 -0700931 "ClassLoader %p(%s); can't open in ClassLoader %p(%s)",
932 path.c_str(),
933 library->GetClassLoader(),
934 old_class_loader.c_str(),
935 class_loader,
936 new_class_loader.c_str());
Andreas Gampe335ee582017-09-19 17:09:52 -0700937 LOG(WARNING) << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700938 return false;
939 }
940 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
941 << " ClassLoader " << class_loader << "]";
942 if (!library->CheckOnLoadResult()) {
943 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
944 "to load \"%s\"", path.c_str());
945 return false;
946 }
947 return true;
948 }
949
950 // Open the shared library. Because we're using a full path, the system
951 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
952 // resolve this library's dependencies though.)
953
954 // Failures here are expected when java.library.path has several entries
955 // and we have to hunt for the lib.
956
957 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
958 // class unloading. Libraries will only be unloaded when the reference count (incremented by
959 // dlopen) becomes zero from dlclose.
960
Andreas Gampe473191c2017-12-28 16:55:31 -0800961 // Retrieve the library path from the classloader, if necessary.
962 ScopedLocalRef<jstring> library_path(env, GetLibrarySearchPath(env, class_loader));
963
Ian Rogers68d8b422014-07-17 11:09:10 -0700964 Locks::mutator_lock_->AssertNotHeld(self);
965 const char* path_str = path.empty() ? nullptr : path.c_str();
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800966 bool needs_native_bridge = false;
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800967 void* handle = android::OpenNativeLibrary(env,
968 runtime_->GetTargetSdkVersion(),
969 path_str,
970 class_loader,
Andreas Gampe473191c2017-12-28 16:55:31 -0800971 library_path.get(),
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800972 &needs_native_bridge,
973 error_msg);
Ian Rogers68d8b422014-07-17 11:09:10 -0700974
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700975 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]";
Ian Rogers68d8b422014-07-17 11:09:10 -0700976
977 if (handle == nullptr) {
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700978 VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700979 return false;
980 }
981
982 if (env->ExceptionCheck() == JNI_TRUE) {
983 LOG(ERROR) << "Unexpected exception:";
984 env->ExceptionDescribe();
985 env->ExceptionClear();
986 }
987 // Create a new entry.
988 // TODO: move the locking (and more of this logic) into Libraries.
989 bool created_library = false;
990 {
991 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
992 std::unique_ptr<SharedLibrary> new_library(
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800993 new SharedLibrary(env,
994 self,
995 path,
996 handle,
997 needs_native_bridge,
998 class_loader,
999 class_loader_allocator));
1000
Ian Rogers68d8b422014-07-17 11:09:10 -07001001 MutexLock mu(self, *Locks::jni_libraries_lock_);
1002 library = libraries_->Get(path);
1003 if (library == nullptr) { // We won race to get libraries_lock.
1004 library = new_library.release();
1005 libraries_->Put(path, library);
1006 created_library = true;
1007 }
1008 }
1009 if (!created_library) {
1010 LOG(INFO) << "WOW: we lost a race to add shared library: "
1011 << "\"" << path << "\" ClassLoader=" << class_loader;
1012 return library->CheckOnLoadResult();
1013 }
1014 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
1015
1016 bool was_successful = false;
Zhenhua WANG8447e6d2016-05-30 11:10:29 +08001017 void* sym = library->FindSymbol("JNI_OnLoad", nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -07001018 if (sym == nullptr) {
1019 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
1020 was_successful = true;
1021 } else {
1022 // Call JNI_OnLoad. We have to override the current class
1023 // loader, which will always be "null" since the stuff at the
1024 // top of the stack is around Runtime.loadLibrary(). (See
1025 // the comments in the JNI FindClass function.)
1026 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
1027 self->SetClassLoaderOverride(class_loader);
1028
1029 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
Andreas Gampec55bb392018-09-21 00:02:02 +00001030 using JNI_OnLoadFn = int(*)(JavaVM*, void*);
Ian Rogers68d8b422014-07-17 11:09:10 -07001031 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
1032 int version = (*jni_on_load)(this, nullptr);
1033
David Brazdil2bb2fbd2018-11-13 18:24:26 +00001034 if (IsSdkVersionSetAndAtMost(runtime_->GetTargetSdkVersion(), SdkVersion::kL)) {
Josh Gao85a78cf2017-03-20 16:26:42 -07001035 // Make sure that sigchain owns SIGSEGV.
1036 EnsureFrontOfChain(SIGSEGV);
Mathieu Chartierd0004802014-10-15 16:59:47 -07001037 }
1038
Ian Rogers68d8b422014-07-17 11:09:10 -07001039 self->SetClassLoaderOverride(old_class_loader.get());
1040
1041 if (version == JNI_ERR) {
1042 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
Alex Light185d1342016-08-11 10:48:03 -07001043 } else if (JavaVMExt::IsBadJniVersion(version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001044 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
1045 path.c_str(), version);
1046 // It's unwise to call dlclose() here, but we can mark it
1047 // as bad and ensure that future load attempts will fail.
1048 // We don't know how far JNI_OnLoad got, so there could
1049 // be some partially-initialized stuff accessible through
1050 // newly-registered native method calls. We could try to
1051 // unregister them, but that doesn't seem worthwhile.
1052 } else {
1053 was_successful = true;
1054 }
1055 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
1056 << " from JNI_OnLoad in \"" << path << "\"]";
1057 }
1058
1059 library->SetResult(was_successful);
1060 return was_successful;
1061}
1062
Alex Light65af20b2017-04-20 09:15:08 -07001063static void* FindCodeForNativeMethodInAgents(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
1064 std::string jni_short_name(m->JniShortName());
1065 std::string jni_long_name(m->JniLongName());
Andreas Gampeaadcbc62017-12-28 14:05:42 -08001066 for (const std::unique_ptr<ti::Agent>& agent : Runtime::Current()->GetAgents()) {
1067 void* fn = agent->FindSymbol(jni_short_name);
Alex Light65af20b2017-04-20 09:15:08 -07001068 if (fn != nullptr) {
1069 VLOG(jni) << "Found implementation for " << m->PrettyMethod()
Andreas Gampeaadcbc62017-12-28 14:05:42 -08001070 << " (symbol: " << jni_short_name << ") in " << *agent;
Alex Light65af20b2017-04-20 09:15:08 -07001071 return fn;
1072 }
Andreas Gampeaadcbc62017-12-28 14:05:42 -08001073 fn = agent->FindSymbol(jni_long_name);
Alex Light65af20b2017-04-20 09:15:08 -07001074 if (fn != nullptr) {
1075 VLOG(jni) << "Found implementation for " << m->PrettyMethod()
Andreas Gampeaadcbc62017-12-28 14:05:42 -08001076 << " (symbol: " << jni_long_name << ") in " << *agent;
Alex Light65af20b2017-04-20 09:15:08 -07001077 return fn;
1078 }
1079 }
1080 return nullptr;
1081}
1082
Mathieu Chartiere401d142015-04-22 13:56:20 -07001083void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001084 CHECK(m->IsNative());
Vladimir Markod93e3742018-07-18 10:58:13 +01001085 ObjPtr<mirror::Class> c = m->GetDeclaringClass();
Ian Rogers68d8b422014-07-17 11:09:10 -07001086 // If this is a static method, it could be called before the class has been initialized.
David Sehr709b0702016-10-13 09:12:37 -07001087 CHECK(c->IsInitializing()) << c->GetStatus() << " " << m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -07001088 std::string detail;
Mathieu Chartier46e75d02017-06-02 16:03:39 -07001089 Thread* const self = Thread::Current();
1090 void* native_method = libraries_->FindNativeMethod(self, m, detail);
Alex Light65af20b2017-04-20 09:15:08 -07001091 if (native_method == nullptr) {
1092 // Lookup JNI native methods from native TI Agent libraries. See runtime/ti/agent.h for more
1093 // information. Agent libraries are searched for native methods after all jni libraries.
1094 native_method = FindCodeForNativeMethodInAgents(m);
1095 }
Ian Rogers68d8b422014-07-17 11:09:10 -07001096 // Throwing can cause libraries_lock to be reacquired.
1097 if (native_method == nullptr) {
Alex Light65af20b2017-04-20 09:15:08 -07001098 LOG(ERROR) << detail;
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +00001099 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
Ian Rogers68d8b422014-07-17 11:09:10 -07001100 }
1101 return native_method;
1102}
1103
Mathieu Chartier97509952015-07-13 14:35:43 -07001104void JavaVMExt::SweepJniWeakGlobals(IsMarkedVisitor* visitor) {
Andreas Gampe05a364c2016-10-14 13:27:12 -07001105 MutexLock mu(Thread::Current(), *Locks::jni_weak_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001106 Runtime* const runtime = Runtime::Current();
1107 for (auto* entry : weak_globals_) {
1108 // Need to skip null here to distinguish between null entries and cleared weak ref entries.
1109 if (!entry->IsNull()) {
1110 // Since this is called by the GC, we don't need a read barrier.
1111 mirror::Object* obj = entry->Read<kWithoutReadBarrier>();
Mathieu Chartier97509952015-07-13 14:35:43 -07001112 mirror::Object* new_obj = visitor->IsMarked(obj);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001113 if (new_obj == nullptr) {
1114 new_obj = runtime->GetClearedJniWeakGlobal();
1115 }
1116 *entry = GcRoot<mirror::Object>(new_obj);
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -07001117 }
Ian Rogers68d8b422014-07-17 11:09:10 -07001118 }
1119}
1120
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001121void JavaVMExt::TrimGlobals() {
Andreas Gampe05a364c2016-10-14 13:27:12 -07001122 WriterMutexLock mu(Thread::Current(), *Locks::jni_globals_lock_);
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -08001123 globals_.Trim();
1124}
1125
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001126void JavaVMExt::VisitRoots(RootVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001127 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -07001128 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001129 globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal));
Ian Rogers68d8b422014-07-17 11:09:10 -07001130 // The weak_globals table is visited by the GC itself (because it mutates the table).
1131}
1132
Andreas Gampe473191c2017-12-28 16:55:31 -08001133jstring JavaVMExt::GetLibrarySearchPath(JNIEnv* env, jobject class_loader) {
1134 if (class_loader == nullptr) {
1135 return nullptr;
1136 }
1137 if (!env->IsInstanceOf(class_loader, WellKnownClasses::dalvik_system_BaseDexClassLoader)) {
1138 return nullptr;
1139 }
1140 return reinterpret_cast<jstring>(env->CallObjectMethod(
1141 class_loader,
1142 WellKnownClasses::dalvik_system_BaseDexClassLoader_getLdLibraryPath));
1143}
1144
Ian Rogers68d8b422014-07-17 11:09:10 -07001145// JNI Invocation interface.
1146
1147extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001148 ScopedTrace trace(__FUNCTION__);
Ian Rogers68d8b422014-07-17 11:09:10 -07001149 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
Alex Light185d1342016-08-11 10:48:03 -07001150 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001151 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
1152 return JNI_EVERSION;
1153 }
1154 RuntimeOptions options;
1155 for (int i = 0; i < args->nOptions; ++i) {
1156 JavaVMOption* option = &args->options[i];
1157 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
1158 }
1159 bool ignore_unrecognized = args->ignoreUnrecognized;
1160 if (!Runtime::Create(options, ignore_unrecognized)) {
1161 return JNI_ERR;
1162 }
Dimitry Ivanovc544f342016-05-09 16:26:13 -07001163
1164 // Initialize native loader. This step makes sure we have
1165 // everything set up before we start using JNI.
1166 android::InitializeNativeLoader();
1167
Ian Rogers68d8b422014-07-17 11:09:10 -07001168 Runtime* runtime = Runtime::Current();
1169 bool started = runtime->Start();
1170 if (!started) {
1171 delete Thread::Current()->GetJniEnv();
1172 delete runtime->GetJavaVM();
1173 LOG(WARNING) << "CreateJavaVM failed";
1174 return JNI_ERR;
1175 }
Dimitry Ivanov041169f2016-04-21 16:01:24 -07001176
Ian Rogers68d8b422014-07-17 11:09:10 -07001177 *p_env = Thread::Current()->GetJniEnv();
1178 *p_vm = runtime->GetJavaVM();
1179 return JNI_OK;
1180}
1181
Ian Rogersf4d4da12014-11-11 16:10:33 -08001182extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001183 Runtime* runtime = Runtime::Current();
Ian Rogersf4d4da12014-11-11 16:10:33 -08001184 if (runtime == nullptr || buf_len == 0) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001185 *vm_count = 0;
1186 } else {
1187 *vm_count = 1;
Ian Rogersf4d4da12014-11-11 16:10:33 -08001188 vms_buf[0] = runtime->GetJavaVM();
Ian Rogers68d8b422014-07-17 11:09:10 -07001189 }
1190 return JNI_OK;
1191}
1192
1193// Historically unsupported.
1194extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
1195 return JNI_ERR;
1196}
1197
1198} // namespace art