blob: 753684917c36fa5e830e6b14f92dc9d437ead98b [file] [log] [blame]
Ian Rogers68d8b422014-07-17 11:09:10 -07001/*
2 * Copyright (C) 2011 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17#include "jni_internal.h"
18
19#include <dlfcn.h>
20
Andreas Gampe46ee31b2016-12-14 10:11:49 -080021#include "android-base/stringprintf.h"
22
Andreas Gampec6ea7d02017-02-01 16:46:28 -080023#include "art_method-inl.h"
Ian Rogersc7dd2952014-10-21 23:31:19 -070024#include "base/dumpable.h"
Andreas Gampeb486a982017-06-01 13:45:54 -070025#include "base/mutex-inl.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070026#include "base/stl_util.h"
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -080027#include "base/systrace.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070028#include "check_jni.h"
Elliott Hughes956af0f2014-12-11 14:34:28 -080029#include "dex_file-inl.h"
Mathieu Chartierd0004802014-10-15 16:59:47 -070030#include "fault_handler.h"
Andreas Gamped4901292017-05-30 18:41:34 -070031#include "gc_root-inl.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070032#include "indirect_reference_table-inl.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070033#include "mirror/class-inl.h"
34#include "mirror/class_loader.h"
Calin Juravlec8423522014-08-12 20:55:20 +010035#include "nativebridge/native_bridge.h"
Dmitriy Ivanovf5a30992015-11-11 14:18:55 -080036#include "nativeloader/native_loader.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070037#include "java_vm_ext.h"
38#include "parsed_options.h"
Ian Rogersc0542af2014-09-03 16:16:56 -070039#include "runtime-inl.h"
Igor Murashkinaaebaa02015-01-26 10:55:53 -080040#include "runtime_options.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070041#include "ScopedLocalRef.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070042#include "scoped_thread_state_change-inl.h"
Josh Gao85a78cf2017-03-20 16:26:42 -070043#include "sigchain.h"
Alex Light65af20b2017-04-20 09:15:08 -070044#include "ti/agent.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070045#include "thread-inl.h"
46#include "thread_list.h"
47
48namespace art {
49
Andreas Gampe46ee31b2016-12-14 10:11:49 -080050using android::base::StringAppendF;
51using android::base::StringAppendV;
52
Andreas Gampea8e3b862016-10-17 20:12:52 -070053static constexpr size_t kGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
Ian Rogers68d8b422014-07-17 11:09:10 -070054
Andreas Gampea8e3b862016-10-17 20:12:52 -070055static constexpr size_t kWeakGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
Ian Rogers68d8b422014-07-17 11:09:10 -070056
Alex Light185d1342016-08-11 10:48:03 -070057bool JavaVMExt::IsBadJniVersion(int version) {
Ian Rogers68d8b422014-07-17 11:09:10 -070058 // We don't support JNI_VERSION_1_1. These are the only other valid versions.
59 return version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 && version != JNI_VERSION_1_6;
60}
61
62class SharedLibrary {
63 public:
64 SharedLibrary(JNIEnv* env, Thread* self, const std::string& path, void* handle,
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080065 bool needs_native_bridge, jobject class_loader, void* class_loader_allocator)
Ian Rogers68d8b422014-07-17 11:09:10 -070066 : path_(path),
67 handle_(handle),
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080068 needs_native_bridge_(needs_native_bridge),
Mathieu Chartier598302a2015-09-23 14:52:39 -070069 class_loader_(env->NewWeakGlobalRef(class_loader)),
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080070 class_loader_allocator_(class_loader_allocator),
Ian Rogers68d8b422014-07-17 11:09:10 -070071 jni_on_load_lock_("JNI_OnLoad lock"),
72 jni_on_load_cond_("JNI_OnLoad condition variable", jni_on_load_lock_),
73 jni_on_load_thread_id_(self->GetThreadId()),
74 jni_on_load_result_(kPending) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080075 CHECK(class_loader_allocator_ != nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -070076 }
77
78 ~SharedLibrary() {
79 Thread* self = Thread::Current();
80 if (self != nullptr) {
Mathieu Chartier598302a2015-09-23 14:52:39 -070081 self->GetJniEnv()->DeleteWeakGlobalRef(class_loader_);
Ian Rogers68d8b422014-07-17 11:09:10 -070082 }
Alex Lightbc5669e2016-06-13 17:22:13 +000083
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080084 android::CloseNativeLibrary(handle_, needs_native_bridge_);
Ian Rogers68d8b422014-07-17 11:09:10 -070085 }
86
Mathieu Chartier598302a2015-09-23 14:52:39 -070087 jweak GetClassLoader() const {
Ian Rogers68d8b422014-07-17 11:09:10 -070088 return class_loader_;
89 }
90
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080091 const void* GetClassLoaderAllocator() const {
92 return class_loader_allocator_;
93 }
94
Ian Rogers68d8b422014-07-17 11:09:10 -070095 const std::string& GetPath() const {
96 return path_;
97 }
98
99 /*
100 * Check the result of an earlier call to JNI_OnLoad on this library.
101 * If the call has not yet finished in another thread, wait for it.
102 */
103 bool CheckOnLoadResult()
Mathieu Chartier90443472015-07-16 20:32:27 -0700104 REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700105 Thread* self = Thread::Current();
106 bool okay;
107 {
108 MutexLock mu(self, jni_on_load_lock_);
109
110 if (jni_on_load_thread_id_ == self->GetThreadId()) {
111 // Check this so we don't end up waiting for ourselves. We need to return "true" so the
112 // caller can continue.
113 LOG(INFO) << *self << " recursive attempt to load library " << "\"" << path_ << "\"";
114 okay = true;
115 } else {
116 while (jni_on_load_result_ == kPending) {
117 VLOG(jni) << "[" << *self << " waiting for \"" << path_ << "\" " << "JNI_OnLoad...]";
118 jni_on_load_cond_.Wait(self);
119 }
120
121 okay = (jni_on_load_result_ == kOkay);
122 VLOG(jni) << "[Earlier JNI_OnLoad for \"" << path_ << "\" "
123 << (okay ? "succeeded" : "failed") << "]";
124 }
125 }
126 return okay;
127 }
128
Mathieu Chartier90443472015-07-16 20:32:27 -0700129 void SetResult(bool result) REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700130 Thread* self = Thread::Current();
131 MutexLock mu(self, jni_on_load_lock_);
132
133 jni_on_load_result_ = result ? kOkay : kFailed;
134 jni_on_load_thread_id_ = 0;
135
136 // Broadcast a wakeup to anybody sleeping on the condition variable.
137 jni_on_load_cond_.Broadcast(self);
138 }
139
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800140 void SetNeedsNativeBridge(bool needs) {
141 needs_native_bridge_ = needs;
Ian Rogers68d8b422014-07-17 11:09:10 -0700142 }
143
144 bool NeedsNativeBridge() const {
145 return needs_native_bridge_;
146 }
147
Mathieu Chartier598302a2015-09-23 14:52:39 -0700148 void* FindSymbol(const std::string& symbol_name, const char* shorty = nullptr) {
149 return NeedsNativeBridge()
150 ? FindSymbolWithNativeBridge(symbol_name.c_str(), shorty)
151 : FindSymbolWithoutNativeBridge(symbol_name.c_str());
152 }
153
154 void* FindSymbolWithoutNativeBridge(const std::string& symbol_name) {
Andreas Gampe8fec90b2015-06-30 11:23:44 -0700155 CHECK(!NeedsNativeBridge());
156
Ian Rogers68d8b422014-07-17 11:09:10 -0700157 return dlsym(handle_, symbol_name.c_str());
158 }
159
160 void* FindSymbolWithNativeBridge(const std::string& symbol_name, const char* shorty) {
161 CHECK(NeedsNativeBridge());
162
163 uint32_t len = 0;
Calin Juravlec8423522014-08-12 20:55:20 +0100164 return android::NativeBridgeGetTrampoline(handle_, symbol_name.c_str(), shorty, len);
Ian Rogers68d8b422014-07-17 11:09:10 -0700165 }
166
167 private:
168 enum JNI_OnLoadState {
169 kPending,
170 kFailed,
171 kOkay,
172 };
173
174 // Path to library "/system/lib/libjni.so".
175 const std::string path_;
176
177 // The void* returned by dlopen(3).
178 void* const handle_;
179
180 // True if a native bridge is required.
181 bool needs_native_bridge_;
182
Mathieu Chartier598302a2015-09-23 14:52:39 -0700183 // The ClassLoader this library is associated with, a weak global JNI reference that is
Ian Rogers68d8b422014-07-17 11:09:10 -0700184 // created/deleted with the scope of the library.
Mathieu Chartier598302a2015-09-23 14:52:39 -0700185 const jweak class_loader_;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800186 // Used to do equality check on class loaders so we can avoid decoding the weak root and read
187 // barriers that mess with class unloading.
188 const void* class_loader_allocator_;
Ian Rogers68d8b422014-07-17 11:09:10 -0700189
190 // Guards remaining items.
191 Mutex jni_on_load_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
192 // Wait for JNI_OnLoad in other thread.
193 ConditionVariable jni_on_load_cond_ GUARDED_BY(jni_on_load_lock_);
194 // Recursive invocation guard.
195 uint32_t jni_on_load_thread_id_ GUARDED_BY(jni_on_load_lock_);
196 // Result of earlier JNI_OnLoad call.
197 JNI_OnLoadState jni_on_load_result_ GUARDED_BY(jni_on_load_lock_);
198};
199
200// This exists mainly to keep implementation details out of the header file.
201class Libraries {
202 public:
203 Libraries() {
204 }
205
206 ~Libraries() {
207 STLDeleteValues(&libraries_);
208 }
209
Mathieu Chartier598302a2015-09-23 14:52:39 -0700210 // NO_THREAD_SAFETY_ANALYSIS since this may be called from Dumpable. Dumpable can't be annotated
211 // properly due to the template. The caller should be holding the jni_libraries_lock_.
212 void Dump(std::ostream& os) const NO_THREAD_SAFETY_ANALYSIS {
213 Locks::jni_libraries_lock_->AssertHeld(Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -0700214 bool first = true;
215 for (const auto& library : libraries_) {
216 if (!first) {
217 os << ' ';
218 }
219 first = false;
220 os << library.first;
221 }
222 }
223
Mathieu Chartier598302a2015-09-23 14:52:39 -0700224 size_t size() const REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700225 return libraries_.size();
226 }
227
Mathieu Chartier598302a2015-09-23 14:52:39 -0700228 SharedLibrary* Get(const std::string& path) REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700229 auto it = libraries_.find(path);
230 return (it == libraries_.end()) ? nullptr : it->second;
231 }
232
Mathieu Chartier598302a2015-09-23 14:52:39 -0700233 void Put(const std::string& path, SharedLibrary* library)
234 REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700235 libraries_.Put(path, library);
236 }
237
238 // See section 11.3 "Linking Native Methods" of the JNI spec.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700239 void* FindNativeMethod(ArtMethod* m, std::string& detail)
Mathieu Chartier90443472015-07-16 20:32:27 -0700240 REQUIRES(Locks::jni_libraries_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700241 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700242 std::string jni_short_name(m->JniShortName());
243 std::string jni_long_name(m->JniLongName());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800244 mirror::ClassLoader* const declaring_class_loader = m->GetDeclaringClass()->GetClassLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700245 ScopedObjectAccessUnchecked soa(Thread::Current());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800246 void* const declaring_class_loader_allocator =
247 Runtime::Current()->GetClassLinker()->GetAllocatorForClassLoader(declaring_class_loader);
248 CHECK(declaring_class_loader_allocator != nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700249 for (const auto& lib : libraries_) {
Mathieu Chartier598302a2015-09-23 14:52:39 -0700250 SharedLibrary* const library = lib.second;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800251 // Use the allocator address for class loader equality to avoid unnecessary weak root decode.
252 if (library->GetClassLoaderAllocator() != declaring_class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700253 // We only search libraries loaded by the appropriate ClassLoader.
254 continue;
255 }
256 // Try the short name then the long name...
Mathieu Chartier598302a2015-09-23 14:52:39 -0700257 const char* shorty = library->NeedsNativeBridge()
258 ? m->GetShorty()
259 : nullptr;
260 void* fn = library->FindSymbol(jni_short_name, shorty);
261 if (fn == nullptr) {
262 fn = library->FindSymbol(jni_long_name, shorty);
Ian Rogers68d8b422014-07-17 11:09:10 -0700263 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700264 if (fn != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700265 VLOG(jni) << "[Found native code for " << m->PrettyMethod()
Ian Rogers68d8b422014-07-17 11:09:10 -0700266 << " in \"" << library->GetPath() << "\"]";
267 return fn;
268 }
269 }
270 detail += "No implementation found for ";
David Sehr709b0702016-10-13 09:12:37 -0700271 detail += m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700272 detail += " (tried " + jni_short_name + " and " + jni_long_name + ")";
Ian Rogers68d8b422014-07-17 11:09:10 -0700273 return nullptr;
274 }
275
Mathieu Chartier598302a2015-09-23 14:52:39 -0700276 // Unload native libraries with cleared class loaders.
277 void UnloadNativeLibraries()
278 REQUIRES(!Locks::jni_libraries_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700279 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier598302a2015-09-23 14:52:39 -0700280 ScopedObjectAccessUnchecked soa(Thread::Current());
Alex Lightbc5669e2016-06-13 17:22:13 +0000281 std::vector<SharedLibrary*> unload_libraries;
Mathieu Chartier598302a2015-09-23 14:52:39 -0700282 {
283 MutexLock mu(soa.Self(), *Locks::jni_libraries_lock_);
284 for (auto it = libraries_.begin(); it != libraries_.end(); ) {
285 SharedLibrary* const library = it->second;
286 // If class loader is null then it was unloaded, call JNI_OnUnload.
Mathieu Chartiercffb7472015-09-28 10:33:00 -0700287 const jweak class_loader = library->GetClassLoader();
288 // If class_loader is a null jobject then it is the boot class loader. We should not unload
289 // the native libraries of the boot class loader.
290 if (class_loader != nullptr &&
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800291 soa.Self()->IsJWeakCleared(class_loader)) {
Alex Lightbc5669e2016-06-13 17:22:13 +0000292 unload_libraries.push_back(library);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700293 it = libraries_.erase(it);
294 } else {
295 ++it;
296 }
297 }
298 }
299 // Do this without holding the jni libraries lock to prevent possible deadlocks.
Alex Lightbc5669e2016-06-13 17:22:13 +0000300 typedef void (*JNI_OnUnloadFn)(JavaVM*, void*);
301 for (auto library : unload_libraries) {
302 void* const sym = library->FindSymbol("JNI_OnUnload", nullptr);
303 if (sym == nullptr) {
304 VLOG(jni) << "[No JNI_OnUnload found in \"" << library->GetPath() << "\"]";
305 } else {
306 VLOG(jni) << "[JNI_OnUnload found for \"" << library->GetPath() << "\"]: Calling...";
307 JNI_OnUnloadFn jni_on_unload = reinterpret_cast<JNI_OnUnloadFn>(sym);
308 jni_on_unload(soa.Vm(), nullptr);
309 }
310 delete library;
Mathieu Chartier598302a2015-09-23 14:52:39 -0700311 }
312 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700313
Mathieu Chartier598302a2015-09-23 14:52:39 -0700314 private:
315 AllocationTrackingSafeMap<std::string, SharedLibrary*, kAllocatorTagJNILibraries> libraries_
316 GUARDED_BY(Locks::jni_libraries_lock_);
317};
Ian Rogers68d8b422014-07-17 11:09:10 -0700318
319class JII {
320 public:
321 static jint DestroyJavaVM(JavaVM* vm) {
322 if (vm == nullptr) {
323 return JNI_ERR;
324 }
325 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
326 delete raw_vm->GetRuntime();
Dimitry Ivanov39d68ef2016-04-29 16:02:38 -0700327 android::ResetNativeLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700328 return JNI_OK;
329 }
330
331 static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
332 return AttachCurrentThreadInternal(vm, p_env, thr_args, false);
333 }
334
335 static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
336 return AttachCurrentThreadInternal(vm, p_env, thr_args, true);
337 }
338
339 static jint DetachCurrentThread(JavaVM* vm) {
340 if (vm == nullptr || Thread::Current() == nullptr) {
341 return JNI_ERR;
342 }
343 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
344 Runtime* runtime = raw_vm->GetRuntime();
345 runtime->DetachCurrentThread();
346 return JNI_OK;
347 }
348
349 static jint GetEnv(JavaVM* vm, void** env, jint version) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700350 if (vm == nullptr || env == nullptr) {
351 return JNI_ERR;
352 }
353 Thread* thread = Thread::Current();
354 if (thread == nullptr) {
355 *env = nullptr;
356 return JNI_EDETACHED;
357 }
Alex Light185d1342016-08-11 10:48:03 -0700358 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
359 return raw_vm->HandleGetEnv(env, version);
Ian Rogers68d8b422014-07-17 11:09:10 -0700360 }
361
362 private:
363 static jint AttachCurrentThreadInternal(JavaVM* vm, JNIEnv** p_env, void* raw_args, bool as_daemon) {
364 if (vm == nullptr || p_env == nullptr) {
365 return JNI_ERR;
366 }
367
368 // Return immediately if we're already attached.
369 Thread* self = Thread::Current();
370 if (self != nullptr) {
371 *p_env = self->GetJniEnv();
372 return JNI_OK;
373 }
374
375 Runtime* runtime = reinterpret_cast<JavaVMExt*>(vm)->GetRuntime();
376
377 // No threads allowed in zygote mode.
378 if (runtime->IsZygote()) {
379 LOG(ERROR) << "Attempt to attach a thread in the zygote";
380 return JNI_ERR;
381 }
382
383 JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(raw_args);
384 const char* thread_name = nullptr;
385 jobject thread_group = nullptr;
386 if (args != nullptr) {
Alex Light185d1342016-08-11 10:48:03 -0700387 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700388 LOG(ERROR) << "Bad JNI version passed to "
389 << (as_daemon ? "AttachCurrentThreadAsDaemon" : "AttachCurrentThread") << ": "
390 << args->version;
391 return JNI_EVERSION;
392 }
393 thread_name = args->name;
394 thread_group = args->group;
395 }
396
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800397 if (!runtime->AttachCurrentThread(thread_name, as_daemon, thread_group,
398 !runtime->IsAotCompiler())) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700399 *p_env = nullptr;
400 return JNI_ERR;
401 } else {
402 *p_env = Thread::Current()->GetJniEnv();
403 return JNI_OK;
404 }
405 }
406};
407
408const JNIInvokeInterface gJniInvokeInterface = {
409 nullptr, // reserved0
410 nullptr, // reserved1
411 nullptr, // reserved2
412 JII::DestroyJavaVM,
413 JII::AttachCurrentThread,
414 JII::DetachCurrentThread,
415 JII::GetEnv,
416 JII::AttachCurrentThreadAsDaemon
417};
418
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100419JavaVMExt::JavaVMExt(Runtime* runtime,
420 const RuntimeArgumentMap& runtime_options,
421 std::string* error_msg)
Ian Rogers68d8b422014-07-17 11:09:10 -0700422 : runtime_(runtime),
423 check_jni_abort_hook_(nullptr),
424 check_jni_abort_hook_data_(nullptr),
425 check_jni_(false), // Initialized properly in the constructor body below.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800426 force_copy_(runtime_options.Exists(RuntimeArgumentMap::JniOptsForceCopy)),
427 tracing_enabled_(runtime_options.Exists(RuntimeArgumentMap::JniTrace)
428 || VLOG_IS_ON(third_party_jni)),
429 trace_(runtime_options.GetOrDefault(RuntimeArgumentMap::JniTrace)),
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700430 globals_(kGlobalsMax, kGlobal, IndirectReferenceTable::ResizableCapacity::kNo, error_msg),
Ian Rogers68d8b422014-07-17 11:09:10 -0700431 libraries_(new Libraries),
432 unchecked_functions_(&gJniInvokeInterface),
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700433 weak_globals_(kWeakGlobalsMax,
434 kWeakGlobal,
435 IndirectReferenceTable::ResizableCapacity::kNo,
436 error_msg),
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700437 allow_accessing_weak_globals_(true),
Andreas Gampe05a364c2016-10-14 13:27:12 -0700438 weak_globals_add_condition_("weak globals add condition",
439 (CHECK(Locks::jni_weak_globals_lock_ != nullptr),
440 *Locks::jni_weak_globals_lock_)),
Alex Light185d1342016-08-11 10:48:03 -0700441 env_hooks_() {
Ian Rogers68d8b422014-07-17 11:09:10 -0700442 functions = unchecked_functions_;
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800443 SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni));
Ian Rogers68d8b422014-07-17 11:09:10 -0700444}
445
446JavaVMExt::~JavaVMExt() {
447}
448
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100449// Checking "globals" and "weak_globals" usually requires locks, but we
450// don't need the locks to check for validity when constructing the
451// object. Use NO_THREAD_SAFETY_ANALYSIS for this.
452std::unique_ptr<JavaVMExt> JavaVMExt::Create(Runtime* runtime,
453 const RuntimeArgumentMap& runtime_options,
454 std::string* error_msg) NO_THREAD_SAFETY_ANALYSIS {
455 std::unique_ptr<JavaVMExt> java_vm(new JavaVMExt(runtime, runtime_options, error_msg));
456 if (java_vm && java_vm->globals_.IsValid() && java_vm->weak_globals_.IsValid()) {
457 return java_vm;
458 }
459 return nullptr;
460}
461
Alex Light185d1342016-08-11 10:48:03 -0700462jint JavaVMExt::HandleGetEnv(/*out*/void** env, jint version) {
463 for (GetEnvHook hook : env_hooks_) {
464 jint res = hook(this, env, version);
465 if (res == JNI_OK) {
466 return JNI_OK;
467 } else if (res != JNI_EVERSION) {
468 LOG(ERROR) << "Error returned from a plugin GetEnv handler! " << res;
469 return res;
470 }
471 }
472 LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version;
473 return JNI_EVERSION;
474}
475
476// Add a hook to handle getting environments from the GetEnv call.
477void JavaVMExt::AddEnvironmentHook(GetEnvHook hook) {
478 CHECK(hook != nullptr) << "environment hooks shouldn't be null!";
479 env_hooks_.push_back(hook);
480}
481
Ian Rogers68d8b422014-07-17 11:09:10 -0700482void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) {
483 Thread* self = Thread::Current();
484 ScopedObjectAccess soa(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700485 ArtMethod* current_method = self->GetCurrentMethod(nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700486
487 std::ostringstream os;
488 os << "JNI DETECTED ERROR IN APPLICATION: " << msg;
489
490 if (jni_function_name != nullptr) {
491 os << "\n in call to " << jni_function_name;
492 }
493 // TODO: is this useful given that we're about to dump the calling thread's stack?
494 if (current_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700495 os << "\n from " << current_method->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700496 }
497 os << "\n";
498 self->Dump(os);
499
500 if (check_jni_abort_hook_ != nullptr) {
501 check_jni_abort_hook_(check_jni_abort_hook_data_, os.str());
502 } else {
503 // Ensure that we get a native stack trace for this thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700504 ScopedThreadSuspension sts(self, kNative);
Ian Rogers68d8b422014-07-17 11:09:10 -0700505 LOG(FATAL) << os.str();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700506 UNREACHABLE();
Ian Rogers68d8b422014-07-17 11:09:10 -0700507 }
508}
509
510void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) {
511 std::string msg;
512 StringAppendV(&msg, fmt, ap);
513 JniAbort(jni_function_name, msg.c_str());
514}
515
516void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) {
517 va_list args;
518 va_start(args, fmt);
519 JniAbortV(jni_function_name, fmt, args);
520 va_end(args);
521}
522
Mathieu Chartiere401d142015-04-22 13:56:20 -0700523bool JavaVMExt::ShouldTrace(ArtMethod* method) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700524 // Fast where no tracing is enabled.
525 if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) {
526 return false;
527 }
528 // Perform checks based on class name.
529 StringPiece class_name(method->GetDeclaringClassDescriptor());
530 if (!trace_.empty() && class_name.find(trace_) != std::string::npos) {
531 return true;
532 }
533 if (!VLOG_IS_ON(third_party_jni)) {
534 return false;
535 }
536 // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
537 // like part of Android.
538 static const char* gBuiltInPrefixes[] = {
539 "Landroid/",
540 "Lcom/android/",
541 "Lcom/google/android/",
542 "Ldalvik/",
543 "Ljava/",
544 "Ljavax/",
545 "Llibcore/",
546 "Lorg/apache/harmony/",
547 };
548 for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) {
549 if (class_name.starts_with(gBuiltInPrefixes[i])) {
550 return false;
551 }
552 }
553 return true;
554}
555
Mathieu Chartier0795f232016-09-27 18:43:30 -0700556jobject JavaVMExt::AddGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700557 // Check for null after decoding the object to handle cleared weak globals.
558 if (obj == nullptr) {
559 return nullptr;
560 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700561 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700562 IndirectRef ref = globals_.Add(kIRTFirstSegment, obj);
Ian Rogers68d8b422014-07-17 11:09:10 -0700563 return reinterpret_cast<jobject>(ref);
564}
565
Mathieu Chartier0795f232016-09-27 18:43:30 -0700566jweak JavaVMExt::AddWeakGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700567 if (obj == nullptr) {
568 return nullptr;
569 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700570 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchif1c6f872017-01-06 12:23:47 -0800571 // CMS needs this to block for concurrent reference processing because an object allocated during
572 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
573 // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant.
574 while (!kUseReadBarrier && UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700575 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
576 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800577 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700578 weak_globals_add_condition_.WaitHoldingLocks(self);
579 }
Andreas Gampee03662b2016-10-13 17:12:56 -0700580 IndirectRef ref = weak_globals_.Add(kIRTFirstSegment, obj);
Ian Rogers68d8b422014-07-17 11:09:10 -0700581 return reinterpret_cast<jweak>(ref);
582}
583
584void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
585 if (obj == nullptr) {
586 return;
587 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700588 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700589 if (!globals_.Remove(kIRTFirstSegment, obj)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700590 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
591 << "failed to find entry";
592 }
593}
594
595void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
596 if (obj == nullptr) {
597 return;
598 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700599 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700600 if (!weak_globals_.Remove(kIRTFirstSegment, obj)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700601 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
602 << "failed to find entry";
603 }
604}
605
606static void ThreadEnableCheckJni(Thread* thread, void* arg) {
607 bool* check_jni = reinterpret_cast<bool*>(arg);
608 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
609}
610
611bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
612 bool old_check_jni = check_jni_;
613 check_jni_ = enabled;
614 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
615 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
616 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
617 return old_check_jni;
618}
619
620void JavaVMExt::DumpForSigQuit(std::ostream& os) {
621 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
622 if (force_copy_) {
623 os << " (with forcecopy)";
624 }
625 Thread* self = Thread::Current();
626 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700627 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700628 os << "; globals=" << globals_.Capacity();
629 }
630 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700631 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700632 if (weak_globals_.Capacity() > 0) {
633 os << " (plus " << weak_globals_.Capacity() << " weak)";
634 }
635 }
636 os << '\n';
637
638 {
639 MutexLock mu(self, *Locks::jni_libraries_lock_);
640 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
641 }
642}
643
644void JavaVMExt::DisallowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700645 CHECK(!kUseReadBarrier);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700646 Thread* const self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700647 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700648 // DisallowNewWeakGlobals is only called by CMS during the pause. It is required to have the
649 // mutator lock exclusively held so that we don't have any threads in the middle of
650 // DecodeWeakGlobal.
651 Locks::mutator_lock_->AssertExclusiveHeld(self);
652 allow_accessing_weak_globals_.StoreSequentiallyConsistent(false);
Ian Rogers68d8b422014-07-17 11:09:10 -0700653}
654
655void JavaVMExt::AllowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700656 CHECK(!kUseReadBarrier);
Ian Rogers68d8b422014-07-17 11:09:10 -0700657 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700658 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700659 allow_accessing_weak_globals_.StoreSequentiallyConsistent(true);
Ian Rogers68d8b422014-07-17 11:09:10 -0700660 weak_globals_add_condition_.Broadcast(self);
661}
662
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700663void JavaVMExt::BroadcastForNewWeakGlobals() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700664 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700665 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700666 weak_globals_add_condition_.Broadcast(self);
667}
668
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700669ObjPtr<mirror::Object> JavaVMExt::DecodeGlobal(IndirectRef ref) {
670 return globals_.SynchronizedGet(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700671}
672
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700673void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700674 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700675 globals_.Update(ref, result);
676}
677
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700678inline bool JavaVMExt::MayAccessWeakGlobals(Thread* self) const {
679 return MayAccessWeakGlobalsUnlocked(self);
680}
681
682inline bool JavaVMExt::MayAccessWeakGlobalsUnlocked(Thread* self) const {
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700683 DCHECK(self != nullptr);
684 return kUseReadBarrier ?
685 self->GetWeakRefAccessEnabled() :
686 allow_accessing_weak_globals_.LoadSequentiallyConsistent();
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700687}
688
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700689ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700690 // It is safe to access GetWeakRefAccessEnabled without the lock since CC uses checkpoints to call
691 // SetWeakRefAccessEnabled, and the other collectors only modify allow_accessing_weak_globals_
692 // when the mutators are paused.
693 // This only applies in the case where MayAccessWeakGlobals goes from false to true. In the other
694 // case, it may be racy, this is benign since DecodeWeakGlobalLocked does the correct behavior
695 // if MayAccessWeakGlobals is false.
Andreas Gampedc061d02016-10-24 13:19:37 -0700696 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700697 if (LIKELY(MayAccessWeakGlobalsUnlocked(self))) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700698 return weak_globals_.SynchronizedGet(ref);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700699 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700700 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700701 return DecodeWeakGlobalLocked(self, ref);
702}
703
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700704ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalLocked(Thread* self, IndirectRef ref) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700705 if (kDebugLocking) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700706 Locks::jni_weak_globals_lock_->AssertHeld(self);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700707 }
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700708 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700709 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
710 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800711 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700712 weak_globals_add_condition_.WaitHoldingLocks(self);
713 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700714 return weak_globals_.Get(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700715}
716
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700717ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalDuringShutdown(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700718 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700719 DCHECK(Runtime::Current()->IsShuttingDown(self));
720 if (self != nullptr) {
721 return DecodeWeakGlobal(self, ref);
722 }
723 // self can be null during a runtime shutdown. ~Runtime()->~ClassLinker()->DecodeWeakGlobal().
724 if (!kUseReadBarrier) {
725 DCHECK(allow_accessing_weak_globals_.LoadSequentiallyConsistent());
726 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700727 return weak_globals_.SynchronizedGet(ref);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700728}
729
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800730bool JavaVMExt::IsWeakGlobalCleared(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700731 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Andreas Gampe05a364c2016-10-14 13:27:12 -0700732 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800733 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700734 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
735 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800736 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800737 weak_globals_add_condition_.WaitHoldingLocks(self);
738 }
739 // When just checking a weak ref has been cleared, avoid triggering the read barrier in decode
740 // (DecodeWeakGlobal) so that we won't accidentally mark the object alive. Since the cleared
741 // sentinel is a non-moving object, we can compare the ref to it without the read barrier and
742 // decide if it's cleared.
743 return Runtime::Current()->IsClearedJniWeakGlobal(weak_globals_.Get<kWithoutReadBarrier>(ref));
744}
745
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700746void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700747 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700748 weak_globals_.Update(ref, result);
749}
750
Ian Rogers68d8b422014-07-17 11:09:10 -0700751void JavaVMExt::DumpReferenceTables(std::ostream& os) {
752 Thread* self = Thread::Current();
753 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700754 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700755 globals_.Dump(os);
756 }
757 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700758 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700759 weak_globals_.Dump(os);
760 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700761}
762
Mathieu Chartier598302a2015-09-23 14:52:39 -0700763void JavaVMExt::UnloadNativeLibraries() {
764 libraries_.get()->UnloadNativeLibraries();
765}
766
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800767bool JavaVMExt::LoadNativeLibrary(JNIEnv* env,
768 const std::string& path,
769 jobject class_loader,
770 jstring library_path,
771 std::string* error_msg) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700772 error_msg->clear();
773
774 // See if we've already loaded this library. If we have, and the class loader
775 // matches, return successfully without doing anything.
776 // TODO: for better results we should canonicalize the pathname (or even compare
777 // inodes). This implementation is fine if everybody is using System.loadLibrary.
778 SharedLibrary* library;
779 Thread* self = Thread::Current();
780 {
781 // TODO: move the locking (and more of this logic) into Libraries.
782 MutexLock mu(self, *Locks::jni_libraries_lock_);
783 library = libraries_->Get(path);
784 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800785 void* class_loader_allocator = nullptr;
786 {
787 ScopedObjectAccess soa(env);
788 // As the incoming class loader is reachable/alive during the call of this function,
789 // it's okay to decode it without worrying about unexpectedly marking it alive.
Mathieu Chartier0795f232016-09-27 18:43:30 -0700790 ObjPtr<mirror::ClassLoader> loader = soa.Decode<mirror::ClassLoader>(class_loader);
Andreas Gampe2d48e532016-06-17 12:46:14 -0700791
792 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700793 if (class_linker->IsBootClassLoader(soa, loader.Ptr())) {
Andreas Gampe2d48e532016-06-17 12:46:14 -0700794 loader = nullptr;
795 class_loader = nullptr;
796 }
797
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700798 class_loader_allocator = class_linker->GetAllocatorForClassLoader(loader.Ptr());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800799 CHECK(class_loader_allocator != nullptr);
800 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700801 if (library != nullptr) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800802 // Use the allocator pointers for class loader equality to avoid unnecessary weak root decode.
803 if (library->GetClassLoaderAllocator() != class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700804 // The library will be associated with class_loader. The JNI
805 // spec says we can't load the same library into more than one
806 // class loader.
807 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
808 "ClassLoader %p; can't open in ClassLoader %p",
809 path.c_str(), library->GetClassLoader(), class_loader);
810 LOG(WARNING) << error_msg;
811 return false;
812 }
813 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
814 << " ClassLoader " << class_loader << "]";
815 if (!library->CheckOnLoadResult()) {
816 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
817 "to load \"%s\"", path.c_str());
818 return false;
819 }
820 return true;
821 }
822
823 // Open the shared library. Because we're using a full path, the system
824 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
825 // resolve this library's dependencies though.)
826
827 // Failures here are expected when java.library.path has several entries
828 // and we have to hunt for the lib.
829
830 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
831 // class unloading. Libraries will only be unloaded when the reference count (incremented by
832 // dlopen) becomes zero from dlclose.
833
834 Locks::mutator_lock_->AssertNotHeld(self);
835 const char* path_str = path.empty() ? nullptr : path.c_str();
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800836 bool needs_native_bridge = false;
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800837 void* handle = android::OpenNativeLibrary(env,
838 runtime_->GetTargetSdkVersion(),
839 path_str,
840 class_loader,
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800841 library_path,
842 &needs_native_bridge,
843 error_msg);
Ian Rogers68d8b422014-07-17 11:09:10 -0700844
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700845 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]";
Ian Rogers68d8b422014-07-17 11:09:10 -0700846
847 if (handle == nullptr) {
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700848 VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700849 return false;
850 }
851
852 if (env->ExceptionCheck() == JNI_TRUE) {
853 LOG(ERROR) << "Unexpected exception:";
854 env->ExceptionDescribe();
855 env->ExceptionClear();
856 }
857 // Create a new entry.
858 // TODO: move the locking (and more of this logic) into Libraries.
859 bool created_library = false;
860 {
861 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
862 std::unique_ptr<SharedLibrary> new_library(
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800863 new SharedLibrary(env,
864 self,
865 path,
866 handle,
867 needs_native_bridge,
868 class_loader,
869 class_loader_allocator));
870
Ian Rogers68d8b422014-07-17 11:09:10 -0700871 MutexLock mu(self, *Locks::jni_libraries_lock_);
872 library = libraries_->Get(path);
873 if (library == nullptr) { // We won race to get libraries_lock.
874 library = new_library.release();
875 libraries_->Put(path, library);
876 created_library = true;
877 }
878 }
879 if (!created_library) {
880 LOG(INFO) << "WOW: we lost a race to add shared library: "
881 << "\"" << path << "\" ClassLoader=" << class_loader;
882 return library->CheckOnLoadResult();
883 }
884 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
885
886 bool was_successful = false;
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800887 void* sym = library->FindSymbol("JNI_OnLoad", nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700888 if (sym == nullptr) {
889 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
890 was_successful = true;
891 } else {
892 // Call JNI_OnLoad. We have to override the current class
893 // loader, which will always be "null" since the stuff at the
894 // top of the stack is around Runtime.loadLibrary(). (See
895 // the comments in the JNI FindClass function.)
896 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
897 self->SetClassLoaderOverride(class_loader);
898
899 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
900 typedef int (*JNI_OnLoadFn)(JavaVM*, void*);
901 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
902 int version = (*jni_on_load)(this, nullptr);
903
Mathieu Chartierd0004802014-10-15 16:59:47 -0700904 if (runtime_->GetTargetSdkVersion() != 0 && runtime_->GetTargetSdkVersion() <= 21) {
Josh Gao85a78cf2017-03-20 16:26:42 -0700905 // Make sure that sigchain owns SIGSEGV.
906 EnsureFrontOfChain(SIGSEGV);
Mathieu Chartierd0004802014-10-15 16:59:47 -0700907 }
908
Ian Rogers68d8b422014-07-17 11:09:10 -0700909 self->SetClassLoaderOverride(old_class_loader.get());
910
911 if (version == JNI_ERR) {
912 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
Alex Light185d1342016-08-11 10:48:03 -0700913 } else if (JavaVMExt::IsBadJniVersion(version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700914 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
915 path.c_str(), version);
916 // It's unwise to call dlclose() here, but we can mark it
917 // as bad and ensure that future load attempts will fail.
918 // We don't know how far JNI_OnLoad got, so there could
919 // be some partially-initialized stuff accessible through
920 // newly-registered native method calls. We could try to
921 // unregister them, but that doesn't seem worthwhile.
922 } else {
923 was_successful = true;
924 }
925 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
926 << " from JNI_OnLoad in \"" << path << "\"]";
927 }
928
929 library->SetResult(was_successful);
930 return was_successful;
931}
932
Alex Light65af20b2017-04-20 09:15:08 -0700933static void* FindCodeForNativeMethodInAgents(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
934 std::string jni_short_name(m->JniShortName());
935 std::string jni_long_name(m->JniLongName());
936 for (const ti::Agent& agent : Runtime::Current()->GetAgents()) {
937 void* fn = agent.FindSymbol(jni_short_name);
938 if (fn != nullptr) {
939 VLOG(jni) << "Found implementation for " << m->PrettyMethod()
940 << " (symbol: " << jni_short_name << ") in " << agent;
941 return fn;
942 }
943 fn = agent.FindSymbol(jni_long_name);
944 if (fn != nullptr) {
945 VLOG(jni) << "Found implementation for " << m->PrettyMethod()
946 << " (symbol: " << jni_long_name << ") in " << agent;
947 return fn;
948 }
949 }
950 return nullptr;
951}
952
Mathieu Chartiere401d142015-04-22 13:56:20 -0700953void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700954 CHECK(m->IsNative());
955 mirror::Class* c = m->GetDeclaringClass();
956 // If this is a static method, it could be called before the class has been initialized.
David Sehr709b0702016-10-13 09:12:37 -0700957 CHECK(c->IsInitializing()) << c->GetStatus() << " " << m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700958 std::string detail;
959 void* native_method;
960 Thread* self = Thread::Current();
961 {
962 MutexLock mu(self, *Locks::jni_libraries_lock_);
963 native_method = libraries_->FindNativeMethod(m, detail);
964 }
Alex Light65af20b2017-04-20 09:15:08 -0700965 if (native_method == nullptr) {
966 // Lookup JNI native methods from native TI Agent libraries. See runtime/ti/agent.h for more
967 // information. Agent libraries are searched for native methods after all jni libraries.
968 native_method = FindCodeForNativeMethodInAgents(m);
969 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700970 // Throwing can cause libraries_lock to be reacquired.
971 if (native_method == nullptr) {
Alex Light65af20b2017-04-20 09:15:08 -0700972 LOG(ERROR) << detail;
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000973 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
Ian Rogers68d8b422014-07-17 11:09:10 -0700974 }
975 return native_method;
976}
977
Mathieu Chartier97509952015-07-13 14:35:43 -0700978void JavaVMExt::SweepJniWeakGlobals(IsMarkedVisitor* visitor) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700979 MutexLock mu(Thread::Current(), *Locks::jni_weak_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700980 Runtime* const runtime = Runtime::Current();
981 for (auto* entry : weak_globals_) {
982 // Need to skip null here to distinguish between null entries and cleared weak ref entries.
983 if (!entry->IsNull()) {
984 // Since this is called by the GC, we don't need a read barrier.
985 mirror::Object* obj = entry->Read<kWithoutReadBarrier>();
Mathieu Chartier97509952015-07-13 14:35:43 -0700986 mirror::Object* new_obj = visitor->IsMarked(obj);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700987 if (new_obj == nullptr) {
988 new_obj = runtime->GetClearedJniWeakGlobal();
989 }
990 *entry = GcRoot<mirror::Object>(new_obj);
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -0700991 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700992 }
993}
994
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800995void JavaVMExt::TrimGlobals() {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700996 WriterMutexLock mu(Thread::Current(), *Locks::jni_globals_lock_);
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800997 globals_.Trim();
998}
999
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001000void JavaVMExt::VisitRoots(RootVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001001 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -07001002 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001003 globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal));
Ian Rogers68d8b422014-07-17 11:09:10 -07001004 // The weak_globals table is visited by the GC itself (because it mutates the table).
1005}
1006
1007// JNI Invocation interface.
1008
1009extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001010 ScopedTrace trace(__FUNCTION__);
Ian Rogers68d8b422014-07-17 11:09:10 -07001011 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
Alex Light185d1342016-08-11 10:48:03 -07001012 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001013 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
1014 return JNI_EVERSION;
1015 }
1016 RuntimeOptions options;
1017 for (int i = 0; i < args->nOptions; ++i) {
1018 JavaVMOption* option = &args->options[i];
1019 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
1020 }
1021 bool ignore_unrecognized = args->ignoreUnrecognized;
1022 if (!Runtime::Create(options, ignore_unrecognized)) {
1023 return JNI_ERR;
1024 }
Dimitry Ivanovc544f342016-05-09 16:26:13 -07001025
1026 // Initialize native loader. This step makes sure we have
1027 // everything set up before we start using JNI.
1028 android::InitializeNativeLoader();
1029
Ian Rogers68d8b422014-07-17 11:09:10 -07001030 Runtime* runtime = Runtime::Current();
1031 bool started = runtime->Start();
1032 if (!started) {
1033 delete Thread::Current()->GetJniEnv();
1034 delete runtime->GetJavaVM();
1035 LOG(WARNING) << "CreateJavaVM failed";
1036 return JNI_ERR;
1037 }
Dimitry Ivanov041169f2016-04-21 16:01:24 -07001038
Ian Rogers68d8b422014-07-17 11:09:10 -07001039 *p_env = Thread::Current()->GetJniEnv();
1040 *p_vm = runtime->GetJavaVM();
1041 return JNI_OK;
1042}
1043
Ian Rogersf4d4da12014-11-11 16:10:33 -08001044extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001045 Runtime* runtime = Runtime::Current();
Ian Rogersf4d4da12014-11-11 16:10:33 -08001046 if (runtime == nullptr || buf_len == 0) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001047 *vm_count = 0;
1048 } else {
1049 *vm_count = 1;
Ian Rogersf4d4da12014-11-11 16:10:33 -08001050 vms_buf[0] = runtime->GetJavaVM();
Ian Rogers68d8b422014-07-17 11:09:10 -07001051 }
1052 return JNI_OK;
1053}
1054
1055// Historically unsupported.
1056extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
1057 return JNI_ERR;
1058}
1059
1060} // namespace art