blob: 6d3118e4aa5b750d90f46df77519c0d08232f206 [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"
Ian Rogers68d8b422014-07-17 11:09:10 -070025#include "base/mutex.h"
26#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"
Ian Rogers68d8b422014-07-17 11:09:10 -070031#include "indirect_reference_table-inl.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070032#include "mirror/class-inl.h"
33#include "mirror/class_loader.h"
Calin Juravlec8423522014-08-12 20:55:20 +010034#include "nativebridge/native_bridge.h"
Dmitriy Ivanovf5a30992015-11-11 14:18:55 -080035#include "nativeloader/native_loader.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070036#include "java_vm_ext.h"
37#include "parsed_options.h"
Ian Rogersc0542af2014-09-03 16:16:56 -070038#include "runtime-inl.h"
Igor Murashkinaaebaa02015-01-26 10:55:53 -080039#include "runtime_options.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070040#include "ScopedLocalRef.h"
Mathieu Chartier0795f232016-09-27 18:43:30 -070041#include "scoped_thread_state_change-inl.h"
Josh Gao85a78cf2017-03-20 16:26:42 -070042#include "sigchain.h"
Alex Light65af20b2017-04-20 09:15:08 -070043#include "ti/agent.h"
Ian Rogers68d8b422014-07-17 11:09:10 -070044#include "thread-inl.h"
45#include "thread_list.h"
46
47namespace art {
48
Andreas Gampe46ee31b2016-12-14 10:11:49 -080049using android::base::StringAppendF;
50using android::base::StringAppendV;
51
Andreas Gampea8e3b862016-10-17 20:12:52 -070052static constexpr size_t kGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
Ian Rogers68d8b422014-07-17 11:09:10 -070053
Andreas Gampea8e3b862016-10-17 20:12:52 -070054static constexpr size_t kWeakGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.)
Ian Rogers68d8b422014-07-17 11:09:10 -070055
Alex Light185d1342016-08-11 10:48:03 -070056bool JavaVMExt::IsBadJniVersion(int version) {
Ian Rogers68d8b422014-07-17 11:09:10 -070057 // We don't support JNI_VERSION_1_1. These are the only other valid versions.
58 return version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 && version != JNI_VERSION_1_6;
59}
60
61class SharedLibrary {
62 public:
63 SharedLibrary(JNIEnv* env, Thread* self, const std::string& path, void* handle,
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080064 bool needs_native_bridge, jobject class_loader, void* class_loader_allocator)
Ian Rogers68d8b422014-07-17 11:09:10 -070065 : path_(path),
66 handle_(handle),
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080067 needs_native_bridge_(needs_native_bridge),
Mathieu Chartier598302a2015-09-23 14:52:39 -070068 class_loader_(env->NewWeakGlobalRef(class_loader)),
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080069 class_loader_allocator_(class_loader_allocator),
Ian Rogers68d8b422014-07-17 11:09:10 -070070 jni_on_load_lock_("JNI_OnLoad lock"),
71 jni_on_load_cond_("JNI_OnLoad condition variable", jni_on_load_lock_),
72 jni_on_load_thread_id_(self->GetThreadId()),
73 jni_on_load_result_(kPending) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080074 CHECK(class_loader_allocator_ != nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -070075 }
76
77 ~SharedLibrary() {
78 Thread* self = Thread::Current();
79 if (self != nullptr) {
Mathieu Chartier598302a2015-09-23 14:52:39 -070080 self->GetJniEnv()->DeleteWeakGlobalRef(class_loader_);
Ian Rogers68d8b422014-07-17 11:09:10 -070081 }
Alex Lightbc5669e2016-06-13 17:22:13 +000082
Zhenhua WANG8447e6d2016-05-30 11:10:29 +080083 android::CloseNativeLibrary(handle_, needs_native_bridge_);
Ian Rogers68d8b422014-07-17 11:09:10 -070084 }
85
Mathieu Chartier598302a2015-09-23 14:52:39 -070086 jweak GetClassLoader() const {
Ian Rogers68d8b422014-07-17 11:09:10 -070087 return class_loader_;
88 }
89
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -080090 const void* GetClassLoaderAllocator() const {
91 return class_loader_allocator_;
92 }
93
Ian Rogers68d8b422014-07-17 11:09:10 -070094 const std::string& GetPath() const {
95 return path_;
96 }
97
98 /*
99 * Check the result of an earlier call to JNI_OnLoad on this library.
100 * If the call has not yet finished in another thread, wait for it.
101 */
102 bool CheckOnLoadResult()
Mathieu Chartier90443472015-07-16 20:32:27 -0700103 REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700104 Thread* self = Thread::Current();
105 bool okay;
106 {
107 MutexLock mu(self, jni_on_load_lock_);
108
109 if (jni_on_load_thread_id_ == self->GetThreadId()) {
110 // Check this so we don't end up waiting for ourselves. We need to return "true" so the
111 // caller can continue.
112 LOG(INFO) << *self << " recursive attempt to load library " << "\"" << path_ << "\"";
113 okay = true;
114 } else {
115 while (jni_on_load_result_ == kPending) {
116 VLOG(jni) << "[" << *self << " waiting for \"" << path_ << "\" " << "JNI_OnLoad...]";
117 jni_on_load_cond_.Wait(self);
118 }
119
120 okay = (jni_on_load_result_ == kOkay);
121 VLOG(jni) << "[Earlier JNI_OnLoad for \"" << path_ << "\" "
122 << (okay ? "succeeded" : "failed") << "]";
123 }
124 }
125 return okay;
126 }
127
Mathieu Chartier90443472015-07-16 20:32:27 -0700128 void SetResult(bool result) REQUIRES(!jni_on_load_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700129 Thread* self = Thread::Current();
130 MutexLock mu(self, jni_on_load_lock_);
131
132 jni_on_load_result_ = result ? kOkay : kFailed;
133 jni_on_load_thread_id_ = 0;
134
135 // Broadcast a wakeup to anybody sleeping on the condition variable.
136 jni_on_load_cond_.Broadcast(self);
137 }
138
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800139 void SetNeedsNativeBridge(bool needs) {
140 needs_native_bridge_ = needs;
Ian Rogers68d8b422014-07-17 11:09:10 -0700141 }
142
143 bool NeedsNativeBridge() const {
144 return needs_native_bridge_;
145 }
146
Mathieu Chartier598302a2015-09-23 14:52:39 -0700147 void* FindSymbol(const std::string& symbol_name, const char* shorty = nullptr) {
148 return NeedsNativeBridge()
149 ? FindSymbolWithNativeBridge(symbol_name.c_str(), shorty)
150 : FindSymbolWithoutNativeBridge(symbol_name.c_str());
151 }
152
153 void* FindSymbolWithoutNativeBridge(const std::string& symbol_name) {
Andreas Gampe8fec90b2015-06-30 11:23:44 -0700154 CHECK(!NeedsNativeBridge());
155
Ian Rogers68d8b422014-07-17 11:09:10 -0700156 return dlsym(handle_, symbol_name.c_str());
157 }
158
159 void* FindSymbolWithNativeBridge(const std::string& symbol_name, const char* shorty) {
160 CHECK(NeedsNativeBridge());
161
162 uint32_t len = 0;
Calin Juravlec8423522014-08-12 20:55:20 +0100163 return android::NativeBridgeGetTrampoline(handle_, symbol_name.c_str(), shorty, len);
Ian Rogers68d8b422014-07-17 11:09:10 -0700164 }
165
166 private:
167 enum JNI_OnLoadState {
168 kPending,
169 kFailed,
170 kOkay,
171 };
172
173 // Path to library "/system/lib/libjni.so".
174 const std::string path_;
175
176 // The void* returned by dlopen(3).
177 void* const handle_;
178
179 // True if a native bridge is required.
180 bool needs_native_bridge_;
181
Mathieu Chartier598302a2015-09-23 14:52:39 -0700182 // The ClassLoader this library is associated with, a weak global JNI reference that is
Ian Rogers68d8b422014-07-17 11:09:10 -0700183 // created/deleted with the scope of the library.
Mathieu Chartier598302a2015-09-23 14:52:39 -0700184 const jweak class_loader_;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800185 // Used to do equality check on class loaders so we can avoid decoding the weak root and read
186 // barriers that mess with class unloading.
187 const void* class_loader_allocator_;
Ian Rogers68d8b422014-07-17 11:09:10 -0700188
189 // Guards remaining items.
190 Mutex jni_on_load_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER;
191 // Wait for JNI_OnLoad in other thread.
192 ConditionVariable jni_on_load_cond_ GUARDED_BY(jni_on_load_lock_);
193 // Recursive invocation guard.
194 uint32_t jni_on_load_thread_id_ GUARDED_BY(jni_on_load_lock_);
195 // Result of earlier JNI_OnLoad call.
196 JNI_OnLoadState jni_on_load_result_ GUARDED_BY(jni_on_load_lock_);
197};
198
199// This exists mainly to keep implementation details out of the header file.
200class Libraries {
201 public:
202 Libraries() {
203 }
204
205 ~Libraries() {
206 STLDeleteValues(&libraries_);
207 }
208
Mathieu Chartier598302a2015-09-23 14:52:39 -0700209 // NO_THREAD_SAFETY_ANALYSIS since this may be called from Dumpable. Dumpable can't be annotated
210 // properly due to the template. The caller should be holding the jni_libraries_lock_.
211 void Dump(std::ostream& os) const NO_THREAD_SAFETY_ANALYSIS {
212 Locks::jni_libraries_lock_->AssertHeld(Thread::Current());
Ian Rogers68d8b422014-07-17 11:09:10 -0700213 bool first = true;
214 for (const auto& library : libraries_) {
215 if (!first) {
216 os << ' ';
217 }
218 first = false;
219 os << library.first;
220 }
221 }
222
Mathieu Chartier598302a2015-09-23 14:52:39 -0700223 size_t size() const REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700224 return libraries_.size();
225 }
226
Mathieu Chartier598302a2015-09-23 14:52:39 -0700227 SharedLibrary* Get(const std::string& path) REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700228 auto it = libraries_.find(path);
229 return (it == libraries_.end()) ? nullptr : it->second;
230 }
231
Mathieu Chartier598302a2015-09-23 14:52:39 -0700232 void Put(const std::string& path, SharedLibrary* library)
233 REQUIRES(Locks::jni_libraries_lock_) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700234 libraries_.Put(path, library);
235 }
236
237 // See section 11.3 "Linking Native Methods" of the JNI spec.
Mathieu Chartiere401d142015-04-22 13:56:20 -0700238 void* FindNativeMethod(ArtMethod* m, std::string& detail)
Mathieu Chartier90443472015-07-16 20:32:27 -0700239 REQUIRES(Locks::jni_libraries_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700240 REQUIRES_SHARED(Locks::mutator_lock_) {
David Sehr709b0702016-10-13 09:12:37 -0700241 std::string jni_short_name(m->JniShortName());
242 std::string jni_long_name(m->JniLongName());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800243 mirror::ClassLoader* const declaring_class_loader = m->GetDeclaringClass()->GetClassLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700244 ScopedObjectAccessUnchecked soa(Thread::Current());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800245 void* const declaring_class_loader_allocator =
246 Runtime::Current()->GetClassLinker()->GetAllocatorForClassLoader(declaring_class_loader);
247 CHECK(declaring_class_loader_allocator != nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700248 for (const auto& lib : libraries_) {
Mathieu Chartier598302a2015-09-23 14:52:39 -0700249 SharedLibrary* const library = lib.second;
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800250 // Use the allocator address for class loader equality to avoid unnecessary weak root decode.
251 if (library->GetClassLoaderAllocator() != declaring_class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700252 // We only search libraries loaded by the appropriate ClassLoader.
253 continue;
254 }
255 // Try the short name then the long name...
Mathieu Chartier598302a2015-09-23 14:52:39 -0700256 const char* shorty = library->NeedsNativeBridge()
257 ? m->GetShorty()
258 : nullptr;
259 void* fn = library->FindSymbol(jni_short_name, shorty);
260 if (fn == nullptr) {
261 fn = library->FindSymbol(jni_long_name, shorty);
Ian Rogers68d8b422014-07-17 11:09:10 -0700262 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700263 if (fn != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700264 VLOG(jni) << "[Found native code for " << m->PrettyMethod()
Ian Rogers68d8b422014-07-17 11:09:10 -0700265 << " in \"" << library->GetPath() << "\"]";
266 return fn;
267 }
268 }
269 detail += "No implementation found for ";
David Sehr709b0702016-10-13 09:12:37 -0700270 detail += m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700271 detail += " (tried " + jni_short_name + " and " + jni_long_name + ")";
Ian Rogers68d8b422014-07-17 11:09:10 -0700272 return nullptr;
273 }
274
Mathieu Chartier598302a2015-09-23 14:52:39 -0700275 // Unload native libraries with cleared class loaders.
276 void UnloadNativeLibraries()
277 REQUIRES(!Locks::jni_libraries_lock_)
Andreas Gampebdf7f1c2016-08-30 16:38:47 -0700278 REQUIRES_SHARED(Locks::mutator_lock_) {
Mathieu Chartier598302a2015-09-23 14:52:39 -0700279 ScopedObjectAccessUnchecked soa(Thread::Current());
Alex Lightbc5669e2016-06-13 17:22:13 +0000280 std::vector<SharedLibrary*> unload_libraries;
Mathieu Chartier598302a2015-09-23 14:52:39 -0700281 {
282 MutexLock mu(soa.Self(), *Locks::jni_libraries_lock_);
283 for (auto it = libraries_.begin(); it != libraries_.end(); ) {
284 SharedLibrary* const library = it->second;
285 // If class loader is null then it was unloaded, call JNI_OnUnload.
Mathieu Chartiercffb7472015-09-28 10:33:00 -0700286 const jweak class_loader = library->GetClassLoader();
287 // If class_loader is a null jobject then it is the boot class loader. We should not unload
288 // the native libraries of the boot class loader.
289 if (class_loader != nullptr &&
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800290 soa.Self()->IsJWeakCleared(class_loader)) {
Alex Lightbc5669e2016-06-13 17:22:13 +0000291 unload_libraries.push_back(library);
Mathieu Chartier598302a2015-09-23 14:52:39 -0700292 it = libraries_.erase(it);
293 } else {
294 ++it;
295 }
296 }
297 }
298 // Do this without holding the jni libraries lock to prevent possible deadlocks.
Alex Lightbc5669e2016-06-13 17:22:13 +0000299 typedef void (*JNI_OnUnloadFn)(JavaVM*, void*);
300 for (auto library : unload_libraries) {
301 void* const sym = library->FindSymbol("JNI_OnUnload", nullptr);
302 if (sym == nullptr) {
303 VLOG(jni) << "[No JNI_OnUnload found in \"" << library->GetPath() << "\"]";
304 } else {
305 VLOG(jni) << "[JNI_OnUnload found for \"" << library->GetPath() << "\"]: Calling...";
306 JNI_OnUnloadFn jni_on_unload = reinterpret_cast<JNI_OnUnloadFn>(sym);
307 jni_on_unload(soa.Vm(), nullptr);
308 }
309 delete library;
Mathieu Chartier598302a2015-09-23 14:52:39 -0700310 }
311 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700312
Mathieu Chartier598302a2015-09-23 14:52:39 -0700313 private:
314 AllocationTrackingSafeMap<std::string, SharedLibrary*, kAllocatorTagJNILibraries> libraries_
315 GUARDED_BY(Locks::jni_libraries_lock_);
316};
Ian Rogers68d8b422014-07-17 11:09:10 -0700317
318class JII {
319 public:
320 static jint DestroyJavaVM(JavaVM* vm) {
321 if (vm == nullptr) {
322 return JNI_ERR;
323 }
324 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
325 delete raw_vm->GetRuntime();
Dimitry Ivanov39d68ef2016-04-29 16:02:38 -0700326 android::ResetNativeLoader();
Ian Rogers68d8b422014-07-17 11:09:10 -0700327 return JNI_OK;
328 }
329
330 static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
331 return AttachCurrentThreadInternal(vm, p_env, thr_args, false);
332 }
333
334 static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) {
335 return AttachCurrentThreadInternal(vm, p_env, thr_args, true);
336 }
337
338 static jint DetachCurrentThread(JavaVM* vm) {
339 if (vm == nullptr || Thread::Current() == nullptr) {
340 return JNI_ERR;
341 }
342 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
343 Runtime* runtime = raw_vm->GetRuntime();
344 runtime->DetachCurrentThread();
345 return JNI_OK;
346 }
347
348 static jint GetEnv(JavaVM* vm, void** env, jint version) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700349 if (vm == nullptr || env == nullptr) {
350 return JNI_ERR;
351 }
352 Thread* thread = Thread::Current();
353 if (thread == nullptr) {
354 *env = nullptr;
355 return JNI_EDETACHED;
356 }
Alex Light185d1342016-08-11 10:48:03 -0700357 JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm);
358 return raw_vm->HandleGetEnv(env, version);
Ian Rogers68d8b422014-07-17 11:09:10 -0700359 }
360
361 private:
362 static jint AttachCurrentThreadInternal(JavaVM* vm, JNIEnv** p_env, void* raw_args, bool as_daemon) {
363 if (vm == nullptr || p_env == nullptr) {
364 return JNI_ERR;
365 }
366
367 // Return immediately if we're already attached.
368 Thread* self = Thread::Current();
369 if (self != nullptr) {
370 *p_env = self->GetJniEnv();
371 return JNI_OK;
372 }
373
374 Runtime* runtime = reinterpret_cast<JavaVMExt*>(vm)->GetRuntime();
375
376 // No threads allowed in zygote mode.
377 if (runtime->IsZygote()) {
378 LOG(ERROR) << "Attempt to attach a thread in the zygote";
379 return JNI_ERR;
380 }
381
382 JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(raw_args);
383 const char* thread_name = nullptr;
384 jobject thread_group = nullptr;
385 if (args != nullptr) {
Alex Light185d1342016-08-11 10:48:03 -0700386 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700387 LOG(ERROR) << "Bad JNI version passed to "
388 << (as_daemon ? "AttachCurrentThreadAsDaemon" : "AttachCurrentThread") << ": "
389 << args->version;
390 return JNI_EVERSION;
391 }
392 thread_name = args->name;
393 thread_group = args->group;
394 }
395
Mathieu Chartiere5f13e52015-02-24 09:37:21 -0800396 if (!runtime->AttachCurrentThread(thread_name, as_daemon, thread_group,
397 !runtime->IsAotCompiler())) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700398 *p_env = nullptr;
399 return JNI_ERR;
400 } else {
401 *p_env = Thread::Current()->GetJniEnv();
402 return JNI_OK;
403 }
404 }
405};
406
407const JNIInvokeInterface gJniInvokeInterface = {
408 nullptr, // reserved0
409 nullptr, // reserved1
410 nullptr, // reserved2
411 JII::DestroyJavaVM,
412 JII::AttachCurrentThread,
413 JII::DetachCurrentThread,
414 JII::GetEnv,
415 JII::AttachCurrentThreadAsDaemon
416};
417
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100418JavaVMExt::JavaVMExt(Runtime* runtime,
419 const RuntimeArgumentMap& runtime_options,
420 std::string* error_msg)
Ian Rogers68d8b422014-07-17 11:09:10 -0700421 : runtime_(runtime),
422 check_jni_abort_hook_(nullptr),
423 check_jni_abort_hook_data_(nullptr),
424 check_jni_(false), // Initialized properly in the constructor body below.
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800425 force_copy_(runtime_options.Exists(RuntimeArgumentMap::JniOptsForceCopy)),
426 tracing_enabled_(runtime_options.Exists(RuntimeArgumentMap::JniTrace)
427 || VLOG_IS_ON(third_party_jni)),
428 trace_(runtime_options.GetOrDefault(RuntimeArgumentMap::JniTrace)),
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700429 globals_(kGlobalsMax, kGlobal, IndirectReferenceTable::ResizableCapacity::kNo, error_msg),
Ian Rogers68d8b422014-07-17 11:09:10 -0700430 libraries_(new Libraries),
431 unchecked_functions_(&gJniInvokeInterface),
Andreas Gampe9d7ef622016-10-24 19:35:19 -0700432 weak_globals_(kWeakGlobalsMax,
433 kWeakGlobal,
434 IndirectReferenceTable::ResizableCapacity::kNo,
435 error_msg),
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700436 allow_accessing_weak_globals_(true),
Andreas Gampe05a364c2016-10-14 13:27:12 -0700437 weak_globals_add_condition_("weak globals add condition",
438 (CHECK(Locks::jni_weak_globals_lock_ != nullptr),
439 *Locks::jni_weak_globals_lock_)),
Alex Light185d1342016-08-11 10:48:03 -0700440 env_hooks_() {
Ian Rogers68d8b422014-07-17 11:09:10 -0700441 functions = unchecked_functions_;
Igor Murashkinaaebaa02015-01-26 10:55:53 -0800442 SetCheckJniEnabled(runtime_options.Exists(RuntimeArgumentMap::CheckJni));
Ian Rogers68d8b422014-07-17 11:09:10 -0700443}
444
445JavaVMExt::~JavaVMExt() {
446}
447
Richard Uhlerda0a69e2016-10-11 15:06:38 +0100448// Checking "globals" and "weak_globals" usually requires locks, but we
449// don't need the locks to check for validity when constructing the
450// object. Use NO_THREAD_SAFETY_ANALYSIS for this.
451std::unique_ptr<JavaVMExt> JavaVMExt::Create(Runtime* runtime,
452 const RuntimeArgumentMap& runtime_options,
453 std::string* error_msg) NO_THREAD_SAFETY_ANALYSIS {
454 std::unique_ptr<JavaVMExt> java_vm(new JavaVMExt(runtime, runtime_options, error_msg));
455 if (java_vm && java_vm->globals_.IsValid() && java_vm->weak_globals_.IsValid()) {
456 return java_vm;
457 }
458 return nullptr;
459}
460
Alex Light185d1342016-08-11 10:48:03 -0700461jint JavaVMExt::HandleGetEnv(/*out*/void** env, jint version) {
462 for (GetEnvHook hook : env_hooks_) {
463 jint res = hook(this, env, version);
464 if (res == JNI_OK) {
465 return JNI_OK;
466 } else if (res != JNI_EVERSION) {
467 LOG(ERROR) << "Error returned from a plugin GetEnv handler! " << res;
468 return res;
469 }
470 }
471 LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version;
472 return JNI_EVERSION;
473}
474
475// Add a hook to handle getting environments from the GetEnv call.
476void JavaVMExt::AddEnvironmentHook(GetEnvHook hook) {
477 CHECK(hook != nullptr) << "environment hooks shouldn't be null!";
478 env_hooks_.push_back(hook);
479}
480
Ian Rogers68d8b422014-07-17 11:09:10 -0700481void JavaVMExt::JniAbort(const char* jni_function_name, const char* msg) {
482 Thread* self = Thread::Current();
483 ScopedObjectAccess soa(self);
Mathieu Chartiere401d142015-04-22 13:56:20 -0700484 ArtMethod* current_method = self->GetCurrentMethod(nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700485
486 std::ostringstream os;
487 os << "JNI DETECTED ERROR IN APPLICATION: " << msg;
488
489 if (jni_function_name != nullptr) {
490 os << "\n in call to " << jni_function_name;
491 }
492 // TODO: is this useful given that we're about to dump the calling thread's stack?
493 if (current_method != nullptr) {
David Sehr709b0702016-10-13 09:12:37 -0700494 os << "\n from " << current_method->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700495 }
496 os << "\n";
497 self->Dump(os);
498
499 if (check_jni_abort_hook_ != nullptr) {
500 check_jni_abort_hook_(check_jni_abort_hook_data_, os.str());
501 } else {
502 // Ensure that we get a native stack trace for this thread.
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700503 ScopedThreadSuspension sts(self, kNative);
Ian Rogers68d8b422014-07-17 11:09:10 -0700504 LOG(FATAL) << os.str();
Mathieu Chartierf1d666e2015-09-03 16:13:34 -0700505 UNREACHABLE();
Ian Rogers68d8b422014-07-17 11:09:10 -0700506 }
507}
508
509void JavaVMExt::JniAbortV(const char* jni_function_name, const char* fmt, va_list ap) {
510 std::string msg;
511 StringAppendV(&msg, fmt, ap);
512 JniAbort(jni_function_name, msg.c_str());
513}
514
515void JavaVMExt::JniAbortF(const char* jni_function_name, const char* fmt, ...) {
516 va_list args;
517 va_start(args, fmt);
518 JniAbortV(jni_function_name, fmt, args);
519 va_end(args);
520}
521
Mathieu Chartiere401d142015-04-22 13:56:20 -0700522bool JavaVMExt::ShouldTrace(ArtMethod* method) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700523 // Fast where no tracing is enabled.
524 if (trace_.empty() && !VLOG_IS_ON(third_party_jni)) {
525 return false;
526 }
527 // Perform checks based on class name.
528 StringPiece class_name(method->GetDeclaringClassDescriptor());
529 if (!trace_.empty() && class_name.find(trace_) != std::string::npos) {
530 return true;
531 }
532 if (!VLOG_IS_ON(third_party_jni)) {
533 return false;
534 }
535 // Return true if we're trying to log all third-party JNI activity and 'method' doesn't look
536 // like part of Android.
537 static const char* gBuiltInPrefixes[] = {
538 "Landroid/",
539 "Lcom/android/",
540 "Lcom/google/android/",
541 "Ldalvik/",
542 "Ljava/",
543 "Ljavax/",
544 "Llibcore/",
545 "Lorg/apache/harmony/",
546 };
547 for (size_t i = 0; i < arraysize(gBuiltInPrefixes); ++i) {
548 if (class_name.starts_with(gBuiltInPrefixes[i])) {
549 return false;
550 }
551 }
552 return true;
553}
554
Mathieu Chartier0795f232016-09-27 18:43:30 -0700555jobject JavaVMExt::AddGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700556 // Check for null after decoding the object to handle cleared weak globals.
557 if (obj == nullptr) {
558 return nullptr;
559 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700560 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700561 IndirectRef ref = globals_.Add(kIRTFirstSegment, obj);
Ian Rogers68d8b422014-07-17 11:09:10 -0700562 return reinterpret_cast<jobject>(ref);
563}
564
Mathieu Chartier0795f232016-09-27 18:43:30 -0700565jweak JavaVMExt::AddWeakGlobalRef(Thread* self, ObjPtr<mirror::Object> obj) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700566 if (obj == nullptr) {
567 return nullptr;
568 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700569 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchif1c6f872017-01-06 12:23:47 -0800570 // CMS needs this to block for concurrent reference processing because an object allocated during
571 // the GC won't be marked and concurrent reference processing would incorrectly clear the JNI weak
572 // ref. But CC (kUseReadBarrier == true) doesn't because of the to-space invariant.
573 while (!kUseReadBarrier && UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700574 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
575 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800576 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700577 weak_globals_add_condition_.WaitHoldingLocks(self);
578 }
Andreas Gampee03662b2016-10-13 17:12:56 -0700579 IndirectRef ref = weak_globals_.Add(kIRTFirstSegment, obj);
Ian Rogers68d8b422014-07-17 11:09:10 -0700580 return reinterpret_cast<jweak>(ref);
581}
582
583void JavaVMExt::DeleteGlobalRef(Thread* self, jobject obj) {
584 if (obj == nullptr) {
585 return;
586 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700587 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700588 if (!globals_.Remove(kIRTFirstSegment, obj)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700589 LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") "
590 << "failed to find entry";
591 }
592}
593
594void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) {
595 if (obj == nullptr) {
596 return;
597 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700598 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Andreas Gampee03662b2016-10-13 17:12:56 -0700599 if (!weak_globals_.Remove(kIRTFirstSegment, obj)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700600 LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") "
601 << "failed to find entry";
602 }
603}
604
605static void ThreadEnableCheckJni(Thread* thread, void* arg) {
606 bool* check_jni = reinterpret_cast<bool*>(arg);
607 thread->GetJniEnv()->SetCheckJniEnabled(*check_jni);
608}
609
610bool JavaVMExt::SetCheckJniEnabled(bool enabled) {
611 bool old_check_jni = check_jni_;
612 check_jni_ = enabled;
613 functions = enabled ? GetCheckJniInvokeInterface() : unchecked_functions_;
614 MutexLock mu(Thread::Current(), *Locks::thread_list_lock_);
615 runtime_->GetThreadList()->ForEach(ThreadEnableCheckJni, &check_jni_);
616 return old_check_jni;
617}
618
619void JavaVMExt::DumpForSigQuit(std::ostream& os) {
620 os << "JNI: CheckJNI is " << (check_jni_ ? "on" : "off");
621 if (force_copy_) {
622 os << " (with forcecopy)";
623 }
624 Thread* self = Thread::Current();
625 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700626 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700627 os << "; globals=" << globals_.Capacity();
628 }
629 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700630 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700631 if (weak_globals_.Capacity() > 0) {
632 os << " (plus " << weak_globals_.Capacity() << " weak)";
633 }
634 }
635 os << '\n';
636
637 {
638 MutexLock mu(self, *Locks::jni_libraries_lock_);
639 os << "Libraries: " << Dumpable<Libraries>(*libraries_) << " (" << libraries_->size() << ")\n";
640 }
641}
642
643void JavaVMExt::DisallowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700644 CHECK(!kUseReadBarrier);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700645 Thread* const self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700646 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700647 // DisallowNewWeakGlobals is only called by CMS during the pause. It is required to have the
648 // mutator lock exclusively held so that we don't have any threads in the middle of
649 // DecodeWeakGlobal.
650 Locks::mutator_lock_->AssertExclusiveHeld(self);
651 allow_accessing_weak_globals_.StoreSequentiallyConsistent(false);
Ian Rogers68d8b422014-07-17 11:09:10 -0700652}
653
654void JavaVMExt::AllowNewWeakGlobals() {
Hiroshi Yamauchifdbd13c2015-09-02 16:16:58 -0700655 CHECK(!kUseReadBarrier);
Ian Rogers68d8b422014-07-17 11:09:10 -0700656 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700657 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700658 allow_accessing_weak_globals_.StoreSequentiallyConsistent(true);
Ian Rogers68d8b422014-07-17 11:09:10 -0700659 weak_globals_add_condition_.Broadcast(self);
660}
661
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700662void JavaVMExt::BroadcastForNewWeakGlobals() {
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700663 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -0700664 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi0b713572015-06-16 18:29:23 -0700665 weak_globals_add_condition_.Broadcast(self);
666}
667
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700668ObjPtr<mirror::Object> JavaVMExt::DecodeGlobal(IndirectRef ref) {
669 return globals_.SynchronizedGet(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700670}
671
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700672void JavaVMExt::UpdateGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700673 WriterMutexLock mu(self, *Locks::jni_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700674 globals_.Update(ref, result);
675}
676
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700677inline bool JavaVMExt::MayAccessWeakGlobals(Thread* self) const {
678 return MayAccessWeakGlobalsUnlocked(self);
679}
680
681inline bool JavaVMExt::MayAccessWeakGlobalsUnlocked(Thread* self) const {
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700682 DCHECK(self != nullptr);
683 return kUseReadBarrier ?
684 self->GetWeakRefAccessEnabled() :
685 allow_accessing_weak_globals_.LoadSequentiallyConsistent();
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700686}
687
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700688ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) {
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700689 // It is safe to access GetWeakRefAccessEnabled without the lock since CC uses checkpoints to call
690 // SetWeakRefAccessEnabled, and the other collectors only modify allow_accessing_weak_globals_
691 // when the mutators are paused.
692 // This only applies in the case where MayAccessWeakGlobals goes from false to true. In the other
693 // case, it may be racy, this is benign since DecodeWeakGlobalLocked does the correct behavior
694 // if MayAccessWeakGlobals is false.
Andreas Gampedc061d02016-10-24 13:19:37 -0700695 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700696 if (LIKELY(MayAccessWeakGlobalsUnlocked(self))) {
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700697 return weak_globals_.SynchronizedGet(ref);
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700698 }
Andreas Gampe05a364c2016-10-14 13:27:12 -0700699 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700700 return DecodeWeakGlobalLocked(self, ref);
701}
702
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700703ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalLocked(Thread* self, IndirectRef ref) {
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700704 if (kDebugLocking) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700705 Locks::jni_weak_globals_lock_->AssertHeld(self);
Mathieu Chartier673ed3d2015-08-28 14:56:43 -0700706 }
Mathieu Chartier30b5e272015-09-01 11:14:34 -0700707 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700708 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
709 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800710 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700711 weak_globals_add_condition_.WaitHoldingLocks(self);
712 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700713 return weak_globals_.Get(ref);
Ian Rogers68d8b422014-07-17 11:09:10 -0700714}
715
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700716ObjPtr<mirror::Object> JavaVMExt::DecodeWeakGlobalDuringShutdown(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700717 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700718 DCHECK(Runtime::Current()->IsShuttingDown(self));
719 if (self != nullptr) {
720 return DecodeWeakGlobal(self, ref);
721 }
722 // self can be null during a runtime shutdown. ~Runtime()->~ClassLinker()->DecodeWeakGlobal().
723 if (!kUseReadBarrier) {
724 DCHECK(allow_accessing_weak_globals_.LoadSequentiallyConsistent());
725 }
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700726 return weak_globals_.SynchronizedGet(ref);
Hiroshi Yamauchi498b1602015-09-16 21:11:44 -0700727}
728
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800729bool JavaVMExt::IsWeakGlobalCleared(Thread* self, IndirectRef ref) {
Andreas Gampedc061d02016-10-24 13:19:37 -0700730 DCHECK_EQ(IndirectReferenceTable::GetIndirectRefKind(ref), kWeakGlobal);
Andreas Gampe05a364c2016-10-14 13:27:12 -0700731 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800732 while (UNLIKELY(!MayAccessWeakGlobals(self))) {
Hiroshi Yamauchi30493242016-11-03 13:06:52 -0700733 // Check and run the empty checkpoint before blocking so the empty checkpoint will work in the
734 // presence of threads blocking for weak ref access.
Hiroshi Yamauchia2224042017-02-08 16:35:45 -0800735 self->CheckEmptyCheckpointFromWeakRefAccess(Locks::jni_weak_globals_lock_);
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800736 weak_globals_add_condition_.WaitHoldingLocks(self);
737 }
738 // When just checking a weak ref has been cleared, avoid triggering the read barrier in decode
739 // (DecodeWeakGlobal) so that we won't accidentally mark the object alive. Since the cleared
740 // sentinel is a non-moving object, we can compare the ref to it without the read barrier and
741 // decide if it's cleared.
742 return Runtime::Current()->IsClearedJniWeakGlobal(weak_globals_.Get<kWithoutReadBarrier>(ref));
743}
744
Mathieu Chartierc4f39252016-10-05 18:32:08 -0700745void JavaVMExt::UpdateWeakGlobal(Thread* self, IndirectRef ref, ObjPtr<mirror::Object> result) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700746 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Jeff Hao83c81952015-05-27 19:29:29 -0700747 weak_globals_.Update(ref, result);
748}
749
Ian Rogers68d8b422014-07-17 11:09:10 -0700750void JavaVMExt::DumpReferenceTables(std::ostream& os) {
751 Thread* self = Thread::Current();
752 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700753 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700754 globals_.Dump(os);
755 }
756 {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700757 MutexLock mu(self, *Locks::jni_weak_globals_lock_);
Ian Rogers68d8b422014-07-17 11:09:10 -0700758 weak_globals_.Dump(os);
759 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700760}
761
Mathieu Chartier598302a2015-09-23 14:52:39 -0700762void JavaVMExt::UnloadNativeLibraries() {
763 libraries_.get()->UnloadNativeLibraries();
764}
765
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800766bool JavaVMExt::LoadNativeLibrary(JNIEnv* env,
767 const std::string& path,
768 jobject class_loader,
769 jstring library_path,
770 std::string* error_msg) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700771 error_msg->clear();
772
773 // See if we've already loaded this library. If we have, and the class loader
774 // matches, return successfully without doing anything.
775 // TODO: for better results we should canonicalize the pathname (or even compare
776 // inodes). This implementation is fine if everybody is using System.loadLibrary.
777 SharedLibrary* library;
778 Thread* self = Thread::Current();
779 {
780 // TODO: move the locking (and more of this logic) into Libraries.
781 MutexLock mu(self, *Locks::jni_libraries_lock_);
782 library = libraries_->Get(path);
783 }
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800784 void* class_loader_allocator = nullptr;
785 {
786 ScopedObjectAccess soa(env);
787 // As the incoming class loader is reachable/alive during the call of this function,
788 // it's okay to decode it without worrying about unexpectedly marking it alive.
Mathieu Chartier0795f232016-09-27 18:43:30 -0700789 ObjPtr<mirror::ClassLoader> loader = soa.Decode<mirror::ClassLoader>(class_loader);
Andreas Gampe2d48e532016-06-17 12:46:14 -0700790
791 ClassLinker* class_linker = Runtime::Current()->GetClassLinker();
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700792 if (class_linker->IsBootClassLoader(soa, loader.Ptr())) {
Andreas Gampe2d48e532016-06-17 12:46:14 -0700793 loader = nullptr;
794 class_loader = nullptr;
795 }
796
Mathieu Chartier1cc62e42016-10-03 18:01:28 -0700797 class_loader_allocator = class_linker->GetAllocatorForClassLoader(loader.Ptr());
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800798 CHECK(class_loader_allocator != nullptr);
799 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700800 if (library != nullptr) {
Hiroshi Yamauchi04302db2015-11-11 23:45:34 -0800801 // Use the allocator pointers for class loader equality to avoid unnecessary weak root decode.
802 if (library->GetClassLoaderAllocator() != class_loader_allocator) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700803 // The library will be associated with class_loader. The JNI
804 // spec says we can't load the same library into more than one
805 // class loader.
806 StringAppendF(error_msg, "Shared library \"%s\" already opened by "
807 "ClassLoader %p; can't open in ClassLoader %p",
808 path.c_str(), library->GetClassLoader(), class_loader);
809 LOG(WARNING) << error_msg;
810 return false;
811 }
812 VLOG(jni) << "[Shared library \"" << path << "\" already loaded in "
813 << " ClassLoader " << class_loader << "]";
814 if (!library->CheckOnLoadResult()) {
815 StringAppendF(error_msg, "JNI_OnLoad failed on a previous attempt "
816 "to load \"%s\"", path.c_str());
817 return false;
818 }
819 return true;
820 }
821
822 // Open the shared library. Because we're using a full path, the system
823 // doesn't have to search through LD_LIBRARY_PATH. (It may do so to
824 // resolve this library's dependencies though.)
825
826 // Failures here are expected when java.library.path has several entries
827 // and we have to hunt for the lib.
828
829 // Below we dlopen but there is no paired dlclose, this would be necessary if we supported
830 // class unloading. Libraries will only be unloaded when the reference count (incremented by
831 // dlopen) becomes zero from dlclose.
832
833 Locks::mutator_lock_->AssertNotHeld(self);
834 const char* path_str = path.empty() ? nullptr : path.c_str();
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800835 bool needs_native_bridge = false;
Dimitry Ivanov942dc2982016-02-24 13:33:33 -0800836 void* handle = android::OpenNativeLibrary(env,
837 runtime_->GetTargetSdkVersion(),
838 path_str,
839 class_loader,
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800840 library_path,
841 &needs_native_bridge,
842 error_msg);
Ian Rogers68d8b422014-07-17 11:09:10 -0700843
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700844 VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_NOW) returned " << handle << "]";
Ian Rogers68d8b422014-07-17 11:09:10 -0700845
846 if (handle == nullptr) {
Dmitriy Ivanov53056722015-03-23 13:38:20 -0700847 VLOG(jni) << "dlopen(\"" << path << "\", RTLD_NOW) failed: " << *error_msg;
Ian Rogers68d8b422014-07-17 11:09:10 -0700848 return false;
849 }
850
851 if (env->ExceptionCheck() == JNI_TRUE) {
852 LOG(ERROR) << "Unexpected exception:";
853 env->ExceptionDescribe();
854 env->ExceptionClear();
855 }
856 // Create a new entry.
857 // TODO: move the locking (and more of this logic) into Libraries.
858 bool created_library = false;
859 {
860 // Create SharedLibrary ahead of taking the libraries lock to maintain lock ordering.
861 std::unique_ptr<SharedLibrary> new_library(
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800862 new SharedLibrary(env,
863 self,
864 path,
865 handle,
866 needs_native_bridge,
867 class_loader,
868 class_loader_allocator));
869
Ian Rogers68d8b422014-07-17 11:09:10 -0700870 MutexLock mu(self, *Locks::jni_libraries_lock_);
871 library = libraries_->Get(path);
872 if (library == nullptr) { // We won race to get libraries_lock.
873 library = new_library.release();
874 libraries_->Put(path, library);
875 created_library = true;
876 }
877 }
878 if (!created_library) {
879 LOG(INFO) << "WOW: we lost a race to add shared library: "
880 << "\"" << path << "\" ClassLoader=" << class_loader;
881 return library->CheckOnLoadResult();
882 }
883 VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader << "]";
884
885 bool was_successful = false;
Zhenhua WANG8447e6d2016-05-30 11:10:29 +0800886 void* sym = library->FindSymbol("JNI_OnLoad", nullptr);
Ian Rogers68d8b422014-07-17 11:09:10 -0700887 if (sym == nullptr) {
888 VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]";
889 was_successful = true;
890 } else {
891 // Call JNI_OnLoad. We have to override the current class
892 // loader, which will always be "null" since the stuff at the
893 // top of the stack is around Runtime.loadLibrary(). (See
894 // the comments in the JNI FindClass function.)
895 ScopedLocalRef<jobject> old_class_loader(env, env->NewLocalRef(self->GetClassLoaderOverride()));
896 self->SetClassLoaderOverride(class_loader);
897
898 VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]";
899 typedef int (*JNI_OnLoadFn)(JavaVM*, void*);
900 JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym);
901 int version = (*jni_on_load)(this, nullptr);
902
Mathieu Chartierd0004802014-10-15 16:59:47 -0700903 if (runtime_->GetTargetSdkVersion() != 0 && runtime_->GetTargetSdkVersion() <= 21) {
Josh Gao85a78cf2017-03-20 16:26:42 -0700904 // Make sure that sigchain owns SIGSEGV.
905 EnsureFrontOfChain(SIGSEGV);
Mathieu Chartierd0004802014-10-15 16:59:47 -0700906 }
907
Ian Rogers68d8b422014-07-17 11:09:10 -0700908 self->SetClassLoaderOverride(old_class_loader.get());
909
910 if (version == JNI_ERR) {
911 StringAppendF(error_msg, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str());
Alex Light185d1342016-08-11 10:48:03 -0700912 } else if (JavaVMExt::IsBadJniVersion(version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700913 StringAppendF(error_msg, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d",
914 path.c_str(), version);
915 // It's unwise to call dlclose() here, but we can mark it
916 // as bad and ensure that future load attempts will fail.
917 // We don't know how far JNI_OnLoad got, so there could
918 // be some partially-initialized stuff accessible through
919 // newly-registered native method calls. We could try to
920 // unregister them, but that doesn't seem worthwhile.
921 } else {
922 was_successful = true;
923 }
924 VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure")
925 << " from JNI_OnLoad in \"" << path << "\"]";
926 }
927
928 library->SetResult(was_successful);
929 return was_successful;
930}
931
Alex Light65af20b2017-04-20 09:15:08 -0700932static void* FindCodeForNativeMethodInAgents(ArtMethod* m) REQUIRES_SHARED(Locks::mutator_lock_) {
933 std::string jni_short_name(m->JniShortName());
934 std::string jni_long_name(m->JniLongName());
935 for (const ti::Agent& agent : Runtime::Current()->GetAgents()) {
936 void* fn = agent.FindSymbol(jni_short_name);
937 if (fn != nullptr) {
938 VLOG(jni) << "Found implementation for " << m->PrettyMethod()
939 << " (symbol: " << jni_short_name << ") in " << agent;
940 return fn;
941 }
942 fn = agent.FindSymbol(jni_long_name);
943 if (fn != nullptr) {
944 VLOG(jni) << "Found implementation for " << m->PrettyMethod()
945 << " (symbol: " << jni_long_name << ") in " << agent;
946 return fn;
947 }
948 }
949 return nullptr;
950}
951
Mathieu Chartiere401d142015-04-22 13:56:20 -0700952void* JavaVMExt::FindCodeForNativeMethod(ArtMethod* m) {
Ian Rogers68d8b422014-07-17 11:09:10 -0700953 CHECK(m->IsNative());
954 mirror::Class* c = m->GetDeclaringClass();
955 // If this is a static method, it could be called before the class has been initialized.
David Sehr709b0702016-10-13 09:12:37 -0700956 CHECK(c->IsInitializing()) << c->GetStatus() << " " << m->PrettyMethod();
Ian Rogers68d8b422014-07-17 11:09:10 -0700957 std::string detail;
958 void* native_method;
959 Thread* self = Thread::Current();
960 {
961 MutexLock mu(self, *Locks::jni_libraries_lock_);
962 native_method = libraries_->FindNativeMethod(m, detail);
963 }
Alex Light65af20b2017-04-20 09:15:08 -0700964 if (native_method == nullptr) {
965 // Lookup JNI native methods from native TI Agent libraries. See runtime/ti/agent.h for more
966 // information. Agent libraries are searched for native methods after all jni libraries.
967 native_method = FindCodeForNativeMethodInAgents(m);
968 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700969 // Throwing can cause libraries_lock to be reacquired.
970 if (native_method == nullptr) {
Alex Light65af20b2017-04-20 09:15:08 -0700971 LOG(ERROR) << detail;
Nicolas Geoffray0aa50ce2015-03-10 11:03:29 +0000972 self->ThrowNewException("Ljava/lang/UnsatisfiedLinkError;", detail.c_str());
Ian Rogers68d8b422014-07-17 11:09:10 -0700973 }
974 return native_method;
975}
976
Mathieu Chartier97509952015-07-13 14:35:43 -0700977void JavaVMExt::SweepJniWeakGlobals(IsMarkedVisitor* visitor) {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700978 MutexLock mu(Thread::Current(), *Locks::jni_weak_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700979 Runtime* const runtime = Runtime::Current();
980 for (auto* entry : weak_globals_) {
981 // Need to skip null here to distinguish between null entries and cleared weak ref entries.
982 if (!entry->IsNull()) {
983 // Since this is called by the GC, we don't need a read barrier.
984 mirror::Object* obj = entry->Read<kWithoutReadBarrier>();
Mathieu Chartier97509952015-07-13 14:35:43 -0700985 mirror::Object* new_obj = visitor->IsMarked(obj);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700986 if (new_obj == nullptr) {
987 new_obj = runtime->GetClearedJniWeakGlobal();
988 }
989 *entry = GcRoot<mirror::Object>(new_obj);
Hiroshi Yamauchi8a741172014-09-08 13:22:56 -0700990 }
Ian Rogers68d8b422014-07-17 11:09:10 -0700991 }
992}
993
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800994void JavaVMExt::TrimGlobals() {
Andreas Gampe05a364c2016-10-14 13:27:12 -0700995 WriterMutexLock mu(Thread::Current(), *Locks::jni_globals_lock_);
Mathieu Chartier91c2f0c2014-11-26 11:21:15 -0800996 globals_.Trim();
997}
998
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -0700999void JavaVMExt::VisitRoots(RootVisitor* visitor) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001000 Thread* self = Thread::Current();
Andreas Gampe05a364c2016-10-14 13:27:12 -07001001 ReaderMutexLock mu(self, *Locks::jni_globals_lock_);
Mathieu Chartierbb87e0f2015-04-03 11:21:55 -07001002 globals_.VisitRoots(visitor, RootInfo(kRootJNIGlobal));
Ian Rogers68d8b422014-07-17 11:09:10 -07001003 // The weak_globals table is visited by the GC itself (because it mutates the table).
1004}
1005
1006// JNI Invocation interface.
1007
1008extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) {
Mathieu Chartier32ce2ad2016-03-04 14:58:03 -08001009 ScopedTrace trace(__FUNCTION__);
Ian Rogers68d8b422014-07-17 11:09:10 -07001010 const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args);
Alex Light185d1342016-08-11 10:48:03 -07001011 if (JavaVMExt::IsBadJniVersion(args->version)) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001012 LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version;
1013 return JNI_EVERSION;
1014 }
1015 RuntimeOptions options;
1016 for (int i = 0; i < args->nOptions; ++i) {
1017 JavaVMOption* option = &args->options[i];
1018 options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo));
1019 }
1020 bool ignore_unrecognized = args->ignoreUnrecognized;
1021 if (!Runtime::Create(options, ignore_unrecognized)) {
1022 return JNI_ERR;
1023 }
Dimitry Ivanovc544f342016-05-09 16:26:13 -07001024
1025 // Initialize native loader. This step makes sure we have
1026 // everything set up before we start using JNI.
1027 android::InitializeNativeLoader();
1028
Ian Rogers68d8b422014-07-17 11:09:10 -07001029 Runtime* runtime = Runtime::Current();
1030 bool started = runtime->Start();
1031 if (!started) {
1032 delete Thread::Current()->GetJniEnv();
1033 delete runtime->GetJavaVM();
1034 LOG(WARNING) << "CreateJavaVM failed";
1035 return JNI_ERR;
1036 }
Dimitry Ivanov041169f2016-04-21 16:01:24 -07001037
Ian Rogers68d8b422014-07-17 11:09:10 -07001038 *p_env = Thread::Current()->GetJniEnv();
1039 *p_vm = runtime->GetJavaVM();
1040 return JNI_OK;
1041}
1042
Ian Rogersf4d4da12014-11-11 16:10:33 -08001043extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms_buf, jsize buf_len, jsize* vm_count) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001044 Runtime* runtime = Runtime::Current();
Ian Rogersf4d4da12014-11-11 16:10:33 -08001045 if (runtime == nullptr || buf_len == 0) {
Ian Rogers68d8b422014-07-17 11:09:10 -07001046 *vm_count = 0;
1047 } else {
1048 *vm_count = 1;
Ian Rogersf4d4da12014-11-11 16:10:33 -08001049 vms_buf[0] = runtime->GetJavaVM();
Ian Rogers68d8b422014-07-17 11:09:10 -07001050 }
1051 return JNI_OK;
1052}
1053
1054// Historically unsupported.
1055extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) {
1056 return JNI_ERR;
1057}
1058
1059} // namespace art