diff options
Diffstat (limited to 'runtime/jni_internal.cc')
| -rw-r--r-- | runtime/jni_internal.cc | 1263 |
1 files changed, 281 insertions, 982 deletions
diff --git a/runtime/jni_internal.cc b/runtime/jni_internal.cc index 938bf2c20e..0a01f78fcb 100644 --- a/runtime/jni_internal.cc +++ b/runtime/jni_internal.cc @@ -23,6 +23,8 @@ #include <utility> #include <vector> +#include "art_field-inl.h" +#include "art_method-inl.h" #include "atomic.h" #include "base/allocator.h" #include "base/logging.h" @@ -35,16 +37,16 @@ #include "gc/accounting/card_table-inl.h" #include "indirect_reference_table-inl.h" #include "interpreter/interpreter.h" -#include "jni.h" -#include "mirror/art_field-inl.h" -#include "mirror/art_method-inl.h" +#include "jni_env_ext.h" +#include "java_vm_ext.h" #include "mirror/class-inl.h" #include "mirror/class_loader.h" +#include "mirror/field-inl.h" +#include "mirror/method.h" #include "mirror/object-inl.h" #include "mirror/object_array-inl.h" #include "mirror/string-inl.h" #include "mirror/throwable.h" -#include "nativebridge/native_bridge.h" #include "parsed_options.h" #include "reflection.h" #include "runtime.h" @@ -57,27 +59,9 @@ namespace art { -static const size_t kMonitorsInitial = 32; // Arbitrary. -static const size_t kMonitorsMax = 4096; // Arbitrary sanity check. - -static const size_t kLocalsInitial = 64; // Arbitrary. -static const size_t kLocalsMax = 512; // Arbitrary sanity check. - -static size_t gGlobalsInitial = 512; // Arbitrary. -static size_t gGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.) - -static const size_t kWeakGlobalsInitial = 16; // Arbitrary. -static const size_t kWeakGlobalsMax = 51200; // Arbitrary sanity check. (Must fit in 16 bits.) - -static jweak AddWeakGlobalReference(ScopedObjectAccess& soa, mirror::Object* obj) - SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { - return soa.Vm()->AddWeakGlobalReference(soa.Self(), obj); -} - -static bool IsBadJniVersion(int version) { - // We don't support JNI_VERSION_1_1. These are the only other valid versions. - return version != JNI_VERSION_1_2 && version != JNI_VERSION_1_4 && version != JNI_VERSION_1_6; -} +// Consider turning this on when there is errors which could be related to JNI array copies such as +// things not rendering correctly. E.g. b/16858794 +static constexpr bool kWarnJniAbort = false; // Section 12.3.2 of the JNI spec describes JNI class descriptors. They're // separated with slashes but aren't wrapped with "L;" like regular descriptors @@ -106,9 +90,8 @@ static std::string NormalizeJniClassDescriptor(const char* name) { static void ThrowNoSuchMethodError(ScopedObjectAccess& soa, mirror::Class* c, const char* name, const char* sig, const char* kind) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { - ThrowLocation throw_location = soa.Self()->GetCurrentLocationForThrow(); std::string temp; - soa.Self()->ThrowNewExceptionF(throw_location, "Ljava/lang/NoSuchMethodError;", + soa.Self()->ThrowNewExceptionF("Ljava/lang/NoSuchMethodError;", "no %s method \"%s.%s%s\"", kind, c->GetDescriptor(&temp), name, sig); } @@ -119,8 +102,7 @@ static void ReportInvalidJNINativeMethod(const ScopedObjectAccess& soa, mirror:: LOG(return_errors ? ERROR : FATAL) << "Failed to register native method in " << PrettyDescriptor(c) << " in " << c->GetDexCache()->GetLocation()->ToModifiedUtf8() << ": " << kind << " is null at index " << idx; - ThrowLocation throw_location = soa.Self()->GetCurrentLocationForThrow(); - soa.Self()->ThrowNewExceptionF(throw_location, "Ljava/lang/NoSuchMethodError;", + soa.Self()->ThrowNewExceptionF("Ljava/lang/NoSuchMethodError;", "%s is null at index %d", kind, idx); } @@ -131,7 +113,7 @@ static mirror::Class* EnsureInitialized(Thread* self, mirror::Class* klass) } StackHandleScope<1> hs(self); Handle<mirror::Class> h_klass(hs.NewHandle(klass)); - if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(h_klass, true, true)) { + if (!Runtime::Current()->GetClassLinker()->EnsureInitialized(self, h_klass, true, true)) { return nullptr; } return h_klass.Get(); @@ -144,17 +126,18 @@ static jmethodID FindMethodID(ScopedObjectAccess& soa, jclass jni_class, if (c == nullptr) { return nullptr; } - mirror::ArtMethod* method = nullptr; + ArtMethod* method = nullptr; + auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize(); if (is_static) { - method = c->FindDirectMethod(name, sig); + method = c->FindDirectMethod(name, sig, pointer_size); } else if (c->IsInterface()) { - method = c->FindInterfaceMethod(name, sig); + method = c->FindInterfaceMethod(name, sig, pointer_size); } else { - method = c->FindVirtualMethod(name, sig); + method = c->FindVirtualMethod(name, sig, pointer_size); if (method == nullptr) { // No virtual method matching the signature. Search declared // private methods and constructors. - method = c->FindDeclaredDirectMethod(name, sig); + method = c->FindDeclaredDirectMethod(name, sig, pointer_size); } } if (method == nullptr || method->IsStatic() != is_static) { @@ -166,10 +149,10 @@ static jmethodID FindMethodID(ScopedObjectAccess& soa, jclass jni_class, static mirror::ClassLoader* GetClassLoader(const ScopedObjectAccess& soa) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { - mirror::ArtMethod* method = soa.Self()->GetCurrentMethod(nullptr); + ArtMethod* method = soa.Self()->GetCurrentMethod(nullptr); // If we are running Runtime.nativeLoad, use the overriding ClassLoader it set. if (method == soa.DecodeMethod(WellKnownClasses::java_lang_Runtime_nativeLoad)) { - return soa.Self()->GetClassLoaderOverride(); + return soa.Decode<mirror::ClassLoader*>(soa.Self()->GetClassLoaderOverride()); } // If we have a method, use its ClassLoader for context. if (method != nullptr) { @@ -182,10 +165,12 @@ static mirror::ClassLoader* GetClassLoader(const ScopedObjectAccess& soa) return class_loader; } // See if the override ClassLoader is set for gtests. - class_loader = soa.Self()->GetClassLoaderOverride(); + class_loader = soa.Decode<mirror::ClassLoader*>(soa.Self()->GetClassLoaderOverride()); if (class_loader != nullptr) { - // If so, CommonCompilerTest should have set UseCompileTimeClassPath. - CHECK(Runtime::Current()->UseCompileTimeClassPath()); + // If so, CommonCompilerTest should have marked the runtime as a compiler not compiling an + // image. + CHECK(Runtime::Current()->IsAotCompiler()); + CHECK(!Runtime::Current()->IsCompilingBootImage()); return class_loader; } // Use the BOOTCLASSPATH. @@ -201,7 +186,7 @@ static jfieldID FindFieldID(const ScopedObjectAccess& soa, jclass jni_class, con if (c.Get() == nullptr) { return nullptr; } - mirror::ArtField* field = nullptr; + ArtField* field = nullptr; mirror::Class* field_type; ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); if (sig[1] != '\0') { @@ -213,16 +198,15 @@ static jfieldID FindFieldID(const ScopedObjectAccess& soa, jclass jni_class, con if (field_type == nullptr) { // Failed to find type from the signature of the field. DCHECK(soa.Self()->IsExceptionPending()); - ThrowLocation throw_location; - StackHandleScope<1> hs(soa.Self()); - Handle<mirror::Throwable> cause(hs.NewHandle(soa.Self()->GetException(&throw_location))); + StackHandleScope<1> hs2(soa.Self()); + Handle<mirror::Throwable> cause(hs2.NewHandle(soa.Self()->GetException())); soa.Self()->ClearException(); std::string temp; - soa.Self()->ThrowNewExceptionF(throw_location, "Ljava/lang/NoSuchFieldError;", + soa.Self()->ThrowNewExceptionF("Ljava/lang/NoSuchFieldError;", "no type \"%s\" found and so no field \"%s\" " "could be found in class \"%s\" or its superclasses", sig, name, c->GetDescriptor(&temp)); - soa.Self()->GetException(nullptr)->SetCause(cause.Get()); + soa.Self()->GetException()->SetCause(cause.Get()); return nullptr; } std::string temp; @@ -233,8 +217,7 @@ static jfieldID FindFieldID(const ScopedObjectAccess& soa, jclass jni_class, con field = c->FindInstanceField(name, field_type->GetDescriptor(&temp)); } if (field == nullptr) { - ThrowLocation throw_location = soa.Self()->GetCurrentLocationForThrow(); - soa.Self()->ThrowNewExceptionF(throw_location, "Ljava/lang/NoSuchFieldError;", + soa.Self()->ThrowNewExceptionF("Ljava/lang/NoSuchFieldError;", "no \"%s\" field \"%s\" in class \"%s\" or its superclasses", sig, name, c->GetDescriptor(&temp)); return nullptr; @@ -246,8 +229,7 @@ static void ThrowAIOOBE(ScopedObjectAccess& soa, mirror::Array* array, jsize sta jsize length, const char* identifier) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { std::string type(PrettyTypeOf(array)); - ThrowLocation throw_location = soa.Self()->GetCurrentLocationForThrow(); - soa.Self()->ThrowNewExceptionF(throw_location, "Ljava/lang/ArrayIndexOutOfBoundsException;", + soa.Self()->ThrowNewExceptionF("Ljava/lang/ArrayIndexOutOfBoundsException;", "%s offset=%d length=%d %s.length=%d", type.c_str(), start, length, identifier, array->GetLength()); } @@ -255,8 +237,7 @@ static void ThrowAIOOBE(ScopedObjectAccess& soa, mirror::Array* array, jsize sta static void ThrowSIOOBE(ScopedObjectAccess& soa, jsize start, jsize length, jsize array_length) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { - ThrowLocation throw_location = soa.Self()->GetCurrentLocationForThrow(); - soa.Self()->ThrowNewExceptionF(throw_location, "Ljava/lang/StringIndexOutOfBoundsException;", + soa.Self()->ThrowNewExceptionF("Ljava/lang/StringIndexOutOfBoundsException;", "offset=%d length=%d string.length()=%d", start, length, array_length); } @@ -299,258 +280,14 @@ int ThrowNewException(JNIEnv* env, jclass exception_class, const char* msg, jobj return JNI_ERR; } ScopedObjectAccess soa(env); - ThrowLocation throw_location = soa.Self()->GetCurrentLocationForThrow(); - soa.Self()->SetException(throw_location, soa.Decode<mirror::Throwable*>(exception.get())); + soa.Self()->SetException(soa.Decode<mirror::Throwable*>(exception.get())); return JNI_OK; } -static jint JII_AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* raw_args, bool as_daemon) { - if (vm == nullptr || p_env == nullptr) { - return JNI_ERR; - } - - // Return immediately if we're already attached. - Thread* self = Thread::Current(); - if (self != nullptr) { - *p_env = self->GetJniEnv(); - return JNI_OK; - } - - Runtime* runtime = reinterpret_cast<JavaVMExt*>(vm)->runtime; - - // No threads allowed in zygote mode. - if (runtime->IsZygote()) { - LOG(ERROR) << "Attempt to attach a thread in the zygote"; - return JNI_ERR; - } - - JavaVMAttachArgs* args = static_cast<JavaVMAttachArgs*>(raw_args); - const char* thread_name = nullptr; - jobject thread_group = nullptr; - if (args != nullptr) { - if (IsBadJniVersion(args->version)) { - LOG(ERROR) << "Bad JNI version passed to " - << (as_daemon ? "AttachCurrentThreadAsDaemon" : "AttachCurrentThread") << ": " - << args->version; - return JNI_EVERSION; - } - thread_name = args->name; - thread_group = args->group; - } - - if (!runtime->AttachCurrentThread(thread_name, as_daemon, thread_group, !runtime->IsCompiler())) { - *p_env = nullptr; - return JNI_ERR; - } else { - *p_env = Thread::Current()->GetJniEnv(); - return JNI_OK; - } +static JavaVMExt* JavaVmExtFromEnv(JNIEnv* env) { + return reinterpret_cast<JNIEnvExt*>(env)->vm; } -class SharedLibrary { - public: - SharedLibrary(const std::string& path, void* handle, mirror::Object* class_loader) - : path_(path), - handle_(handle), - needs_native_bridge_(false), - class_loader_(GcRoot<mirror::Object>(class_loader)), - jni_on_load_lock_("JNI_OnLoad lock"), - jni_on_load_cond_("JNI_OnLoad condition variable", jni_on_load_lock_), - jni_on_load_thread_id_(Thread::Current()->GetThreadId()), - jni_on_load_result_(kPending) { - } - - mirror::Object* GetClassLoader() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { - return class_loader_.Read(); - } - - std::string GetPath() { - return path_; - } - - /* - * Check the result of an earlier call to JNI_OnLoad on this library. - * If the call has not yet finished in another thread, wait for it. - */ - bool CheckOnLoadResult() - LOCKS_EXCLUDED(jni_on_load_lock_) - SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { - Thread* self = Thread::Current(); - self->TransitionFromRunnableToSuspended(kWaitingForJniOnLoad); - bool okay; - { - MutexLock mu(self, jni_on_load_lock_); - - if (jni_on_load_thread_id_ == self->GetThreadId()) { - // Check this so we don't end up waiting for ourselves. We need to return "true" so the - // caller can continue. - LOG(INFO) << *self << " recursive attempt to load library " << "\"" << path_ << "\""; - okay = true; - } else { - while (jni_on_load_result_ == kPending) { - VLOG(jni) << "[" << *self << " waiting for \"" << path_ << "\" " << "JNI_OnLoad...]"; - jni_on_load_cond_.Wait(self); - } - - okay = (jni_on_load_result_ == kOkay); - VLOG(jni) << "[Earlier JNI_OnLoad for \"" << path_ << "\" " - << (okay ? "succeeded" : "failed") << "]"; - } - } - self->TransitionFromSuspendedToRunnable(); - return okay; - } - - void SetResult(bool result) LOCKS_EXCLUDED(jni_on_load_lock_) { - Thread* self = Thread::Current(); - MutexLock mu(self, jni_on_load_lock_); - - jni_on_load_result_ = result ? kOkay : kFailed; - jni_on_load_thread_id_ = 0; - - // Broadcast a wakeup to anybody sleeping on the condition variable. - jni_on_load_cond_.Broadcast(self); - } - - void SetNeedsNativeBridge() { - needs_native_bridge_ = true; - } - - bool NeedsNativeBridge() const { - return needs_native_bridge_; - } - - void* FindSymbol(const std::string& symbol_name) { - return dlsym(handle_, symbol_name.c_str()); - } - - void* FindSymbolWithNativeBridge(const std::string& symbol_name, mirror::ArtMethod* m) - SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { - CHECK(NeedsNativeBridge()); - - uint32_t len = 0; - const char* shorty = nullptr; - if (m != nullptr) { - shorty = m->GetShorty(&len); - } - return android::NativeBridgeGetTrampoline(handle_, symbol_name.c_str(), shorty, len); - } - - void VisitRoots(RootCallback* visitor, void* arg) { - class_loader_.VisitRootIfNonNull(visitor, arg, RootInfo(kRootVMInternal)); - } - - private: - enum JNI_OnLoadState { - kPending, - kFailed, - kOkay, - }; - - // Path to library "/system/lib/libjni.so". - std::string path_; - - // The void* returned by dlopen(3). - void* handle_; - - // True if a native bridge is required. - bool needs_native_bridge_; - - // The ClassLoader this library is associated with. - GcRoot<mirror::Object> class_loader_; - - // Guards remaining items. - Mutex jni_on_load_lock_ DEFAULT_MUTEX_ACQUIRED_AFTER; - // Wait for JNI_OnLoad in other thread. - ConditionVariable jni_on_load_cond_ GUARDED_BY(jni_on_load_lock_); - // Recursive invocation guard. - uint32_t jni_on_load_thread_id_ GUARDED_BY(jni_on_load_lock_); - // Result of earlier JNI_OnLoad call. - JNI_OnLoadState jni_on_load_result_ GUARDED_BY(jni_on_load_lock_); -}; - -// This exists mainly to keep implementation details out of the header file. -class Libraries { - public: - Libraries() { - } - - ~Libraries() { - STLDeleteValues(&libraries_); - } - - void Dump(std::ostream& os) const { - bool first = true; - for (const auto& library : libraries_) { - if (!first) { - os << ' '; - } - first = false; - os << library.first; - } - } - - size_t size() const { - return libraries_.size(); - } - - SharedLibrary* Get(const std::string& path) { - auto it = libraries_.find(path); - return (it == libraries_.end()) ? nullptr : it->second; - } - - void Put(const std::string& path, SharedLibrary* library) { - libraries_.Put(path, library); - } - - // See section 11.3 "Linking Native Methods" of the JNI spec. - void* FindNativeMethod(mirror::ArtMethod* m, std::string& detail) - SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { - std::string jni_short_name(JniShortName(m)); - std::string jni_long_name(JniLongName(m)); - const mirror::ClassLoader* declaring_class_loader = m->GetDeclaringClass()->GetClassLoader(); - for (const auto& lib : libraries_) { - SharedLibrary* library = lib.second; - if (library->GetClassLoader() != declaring_class_loader) { - // We only search libraries loaded by the appropriate ClassLoader. - continue; - } - // Try the short name then the long name... - void* fn = nullptr; - if (UNLIKELY(library->NeedsNativeBridge())) { - fn = library->FindSymbolWithNativeBridge(jni_short_name, m); - if (fn == nullptr) { - fn = library->FindSymbolWithNativeBridge(jni_long_name, m); - } - } else { - fn = library->FindSymbol(jni_short_name); - if (fn == nullptr) { - fn = library->FindSymbol(jni_long_name); - } - } - if (fn != nullptr) { - VLOG(jni) << "[Found native code for " << PrettyMethod(m) - << " in \"" << library->GetPath() << "\"]"; - return fn; - } - } - detail += "No implementation found for "; - detail += PrettyMethod(m); - detail += " (tried " + jni_short_name + " and " + jni_long_name + ")"; - LOG(ERROR) << detail; - return nullptr; - } - - void VisitRoots(RootCallback* callback, void* arg) { - for (auto& lib_pair : libraries_) { - lib_pair.second->VisitRoots(callback, arg); - } - } - - private: - AllocationTrackingSafeMap<std::string, SharedLibrary*, kAllocatorTagJNILibrarires> libraries_; -}; - #define CHECK_NON_NULL_ARGUMENT(value) \ CHECK_NON_NULL_ARGUMENT_FN_NAME(__FUNCTION__, value, nullptr) @@ -565,16 +302,33 @@ class Libraries { #define CHECK_NON_NULL_ARGUMENT_FN_NAME(name, value, return_val) \ if (UNLIKELY(value == nullptr)) { \ - JniAbortF(name, #value " == null"); \ + JavaVmExtFromEnv(env)->JniAbortF(name, #value " == null"); \ return return_val; \ } #define CHECK_NON_NULL_MEMCPY_ARGUMENT(length, value) \ if (UNLIKELY(length != 0 && value == nullptr)) { \ - JniAbortF(__FUNCTION__, #value " == null"); \ + JavaVmExtFromEnv(env)->JniAbortF(__FUNCTION__, #value " == null"); \ return; \ } +template <bool kNative> +static ArtMethod* FindMethod(mirror::Class* c, const StringPiece& name, const StringPiece& sig) + SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { + auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize(); + for (auto& method : c->GetDirectMethods(pointer_size)) { + if (kNative == method.IsNative() && name == method.GetName() && method.GetSignature() == sig) { + return &method; + } + } + for (auto& method : c->GetVirtualMethods(pointer_size)) { + if (kNative == method.IsNative() && name == method.GetName() && method.GetSignature() == sig) { + return &method; + } + } + return nullptr; +} + class JNI { public: static jint GetVersion(JNIEnv*) { @@ -606,47 +360,39 @@ class JNI { static jmethodID FromReflectedMethod(JNIEnv* env, jobject jlr_method) { CHECK_NON_NULL_ARGUMENT(jlr_method); ScopedObjectAccess soa(env); - return soa.EncodeMethod(mirror::ArtMethod::FromReflectedMethod(soa, jlr_method)); + return soa.EncodeMethod(ArtMethod::FromReflectedMethod(soa, jlr_method)); } static jfieldID FromReflectedField(JNIEnv* env, jobject jlr_field) { CHECK_NON_NULL_ARGUMENT(jlr_field); ScopedObjectAccess soa(env); - return soa.EncodeField(mirror::ArtField::FromReflectedField(soa, jlr_field)); + mirror::Object* obj_field = soa.Decode<mirror::Object*>(jlr_field); + if (obj_field->GetClass() != mirror::Field::StaticClass()) { + // Not even a java.lang.reflect.Field, return null. TODO, is this check necessary? + return nullptr; + } + auto* field = static_cast<mirror::Field*>(obj_field); + return soa.EncodeField(field->GetArtField()); } static jobject ToReflectedMethod(JNIEnv* env, jclass, jmethodID mid, jboolean) { CHECK_NON_NULL_ARGUMENT(mid); ScopedObjectAccess soa(env); - mirror::ArtMethod* m = soa.DecodeMethod(mid); - CHECK(!kMovingMethods); - ScopedLocalRef<jobject> art_method(env, soa.AddLocalReference<jobject>(m)); - jobject reflect_method; + ArtMethod* m = soa.DecodeMethod(mid); + mirror::AbstractMethod* method; if (m->IsConstructor()) { - reflect_method = env->AllocObject(WellKnownClasses::java_lang_reflect_Constructor); + method = mirror::Constructor::CreateFromArtMethod(soa.Self(), m); } else { - reflect_method = env->AllocObject(WellKnownClasses::java_lang_reflect_Method); - } - if (env->ExceptionCheck()) { - return nullptr; + method = mirror::Method::CreateFromArtMethod(soa.Self(), m); } - SetObjectField(env, reflect_method, - WellKnownClasses::java_lang_reflect_AbstractMethod_artMethod, art_method.get()); - return reflect_method; + return soa.AddLocalReference<jobject>(method); } static jobject ToReflectedField(JNIEnv* env, jclass, jfieldID fid, jboolean) { CHECK_NON_NULL_ARGUMENT(fid); ScopedObjectAccess soa(env); - mirror::ArtField* f = soa.DecodeField(fid); - ScopedLocalRef<jobject> art_field(env, soa.AddLocalReference<jobject>(f)); - jobject reflect_field = env->AllocObject(WellKnownClasses::java_lang_reflect_Field); - if (env->ExceptionCheck()) { - return nullptr; - } - SetObjectField(env, reflect_field, - WellKnownClasses::java_lang_reflect_Field_artField, art_field.get()); - return reflect_field; + ArtField* f = soa.DecodeField(fid); + return soa.AddLocalReference<jobject>(mirror::Field::CreateFromArtField(soa.Self(), f, true)); } static jclass GetObjectClass(JNIEnv* env, jobject java_object) { @@ -693,8 +439,7 @@ class JNI { if (exception == nullptr) { return JNI_ERR; } - ThrowLocation throw_location = soa.Self()->GetCurrentLocationForThrow(); - soa.Self()->SetException(throw_location, exception); + soa.Self()->SetException(exception); return JNI_OK; } @@ -716,27 +461,14 @@ class JNI { ScopedObjectAccess soa(env); // If we have no exception to describe, pass through. - if (!soa.Self()->GetException(nullptr)) { + if (!soa.Self()->GetException()) { return; } - StackHandleScope<3> hs(soa.Self()); - // TODO: Use nullptr instead of null handles? - auto old_throw_this_object(hs.NewHandle<mirror::Object>(nullptr)); - auto old_throw_method(hs.NewHandle<mirror::ArtMethod>(nullptr)); - auto old_exception(hs.NewHandle<mirror::Throwable>(nullptr)); - uint32_t old_throw_dex_pc; - bool old_is_exception_reported; - { - ThrowLocation old_throw_location; - mirror::Throwable* old_exception_obj = soa.Self()->GetException(&old_throw_location); - old_throw_this_object.Assign(old_throw_location.GetThis()); - old_throw_method.Assign(old_throw_location.GetMethod()); - old_exception.Assign(old_exception_obj); - old_throw_dex_pc = old_throw_location.GetDexPc(); - old_is_exception_reported = soa.Self()->IsExceptionReportedToInstrumentation(); - soa.Self()->ClearException(); - } + StackHandleScope<1> hs(soa.Self()); + Handle<mirror::Throwable> old_exception( + hs.NewHandle<mirror::Throwable>(soa.Self()->GetException())); + soa.Self()->ClearException(); ScopedLocalRef<jthrowable> exception(env, soa.AddLocalReference<jthrowable>(old_exception.Get())); ScopedLocalRef<jclass> exception_class(env, env->GetObjectClass(exception.get())); @@ -747,21 +479,17 @@ class JNI { } else { env->CallVoidMethod(exception.get(), mid); if (soa.Self()->IsExceptionPending()) { - LOG(WARNING) << "JNI WARNING: " << PrettyTypeOf(soa.Self()->GetException(nullptr)) + LOG(WARNING) << "JNI WARNING: " << PrettyTypeOf(soa.Self()->GetException()) << " thrown while calling printStackTrace"; soa.Self()->ClearException(); } } - ThrowLocation gc_safe_throw_location(old_throw_this_object.Get(), old_throw_method.Get(), - old_throw_dex_pc); - - soa.Self()->SetException(gc_safe_throw_location, old_exception.Get()); - soa.Self()->SetExceptionReportedToInstrumentation(old_is_exception_reported); + soa.Self()->SetException(old_exception.Get()); } static jthrowable ExceptionOccurred(JNIEnv* env) { ScopedObjectAccess soa(env); - mirror::Object* exception = soa.Self()->GetException(nullptr); + mirror::Object* exception = soa.Self()->GetException(); return soa.AddLocalReference<jthrowable>(exception); } @@ -772,10 +500,10 @@ class JNI { static jint PushLocalFrame(JNIEnv* env, jint capacity) { // TODO: SOA may not be necessary but I do it to please lock annotations. ScopedObjectAccess soa(env); - if (EnsureLocalCapacity(soa, capacity, "PushLocalFrame") != JNI_OK) { + if (EnsureLocalCapacityInternal(soa, capacity, "PushLocalFrame") != JNI_OK) { return JNI_ERR; } - static_cast<JNIEnvExt*>(env)->PushFrame(capacity); + down_cast<JNIEnvExt*>(env)->PushFrame(capacity); return JNI_OK; } @@ -789,48 +517,31 @@ class JNI { static jint EnsureLocalCapacity(JNIEnv* env, jint desired_capacity) { // TODO: SOA may not be necessary but I do it to please lock annotations. ScopedObjectAccess soa(env); - return EnsureLocalCapacity(soa, desired_capacity, "EnsureLocalCapacity"); + return EnsureLocalCapacityInternal(soa, desired_capacity, "EnsureLocalCapacity"); } static jobject NewGlobalRef(JNIEnv* env, jobject obj) { ScopedObjectAccess soa(env); mirror::Object* decoded_obj = soa.Decode<mirror::Object*>(obj); - // Check for null after decoding the object to handle cleared weak globals. - if (decoded_obj == nullptr) { - return nullptr; - } - JavaVMExt* vm = soa.Vm(); - IndirectReferenceTable& globals = vm->globals; - WriterMutexLock mu(soa.Self(), vm->globals_lock); - IndirectRef ref = globals.Add(IRT_FIRST_SEGMENT, decoded_obj); - return reinterpret_cast<jobject>(ref); + return soa.Vm()->AddGlobalRef(soa.Self(), decoded_obj); } static void DeleteGlobalRef(JNIEnv* env, jobject obj) { - if (obj == nullptr) { - return; - } - JavaVMExt* vm = reinterpret_cast<JNIEnvExt*>(env)->vm; - IndirectReferenceTable& globals = vm->globals; - Thread* self = reinterpret_cast<JNIEnvExt*>(env)->self; - WriterMutexLock mu(self, vm->globals_lock); - - if (!globals.Remove(IRT_FIRST_SEGMENT, obj)) { - LOG(WARNING) << "JNI WARNING: DeleteGlobalRef(" << obj << ") " - << "failed to find entry"; - } + JavaVMExt* vm = down_cast<JNIEnvExt*>(env)->vm; + Thread* self = down_cast<JNIEnvExt*>(env)->self; + vm->DeleteGlobalRef(self, obj); } static jweak NewWeakGlobalRef(JNIEnv* env, jobject obj) { ScopedObjectAccess soa(env); - return AddWeakGlobalReference(soa, soa.Decode<mirror::Object*>(obj)); + mirror::Object* decoded_obj = soa.Decode<mirror::Object*>(obj); + return soa.Vm()->AddWeakGlobalRef(soa.Self(), decoded_obj); } static void DeleteWeakGlobalRef(JNIEnv* env, jweak obj) { - if (obj != nullptr) { - ScopedObjectAccess soa(env); - soa.Vm()->DeleteWeakGlobalRef(soa.Self(), obj); - } + JavaVMExt* vm = down_cast<JNIEnvExt*>(env)->vm; + Thread* self = down_cast<JNIEnvExt*>(env)->self; + vm->DeleteWeakGlobalRef(self, obj); } static jobject NewLocalRef(JNIEnv* env, jobject obj) { @@ -847,11 +558,12 @@ class JNI { if (obj == nullptr) { return; } + // SOA is only necessary to have exclusion between GC root marking and removing. + // We don't want to have the GC attempt to mark a null root if we just removed + // it. b/22119403 ScopedObjectAccess soa(env); - IndirectReferenceTable& locals = reinterpret_cast<JNIEnvExt*>(env)->locals; - - uint32_t cookie = reinterpret_cast<JNIEnvExt*>(env)->local_ref_cookie; - if (!locals.Remove(cookie, obj)) { + auto* ext_env = down_cast<JNIEnvExt*>(env); + if (!ext_env->locals.Remove(ext_env->local_ref_cookie, obj)) { // Attempting to delete a local reference that is not in the // topmost local reference frame is a no-op. DeleteLocalRef returns // void and doesn't throw any exceptions, but we should probably @@ -879,6 +591,12 @@ class JNI { if (c == nullptr) { return nullptr; } + if (c->IsStringClass()) { + gc::AllocatorType allocator_type = Runtime::Current()->GetHeap()->GetCurrentAllocator(); + mirror::SetStringCountVisitor visitor(0); + return soa.AddLocalReference<jobject>(mirror::String::Alloc<true>(soa.Self(), 0, + allocator_type, visitor)); + } return soa.AddLocalReference<jobject>(c->AllocObject(soa.Self())); } @@ -900,6 +618,11 @@ class JNI { if (c == nullptr) { return nullptr; } + if (c->IsStringClass()) { + // Replace calls to String.<init> with equivalent StringFactory call. + jmethodID sf_mid = WellKnownClasses::StringInitToStringFactoryMethodID(mid); + return CallStaticObjectMethodV(env, WellKnownClasses::java_lang_StringFactory, sf_mid, args); + } mirror::Object* result = c->AllocObject(soa.Self()); if (result == nullptr) { return nullptr; @@ -920,6 +643,11 @@ class JNI { if (c == nullptr) { return nullptr; } + if (c->IsStringClass()) { + // Replace calls to String.<init> with equivalent StringFactory call. + jmethodID sf_mid = WellKnownClasses::StringInitToStringFactoryMethodID(mid); + return CallStaticObjectMethodA(env, WellKnownClasses::java_lang_StringFactory, sf_mid, args); + } mirror::Object* result = c->AllocObject(soa.Self()); if (result == nullptr) { return nullptr; @@ -972,8 +700,7 @@ class JNI { CHECK_NON_NULL_ARGUMENT(obj); CHECK_NON_NULL_ARGUMENT(mid); ScopedObjectAccess soa(env); - JValue result(InvokeVirtualOrInterfaceWithJValues(soa, soa.Decode<mirror::Object*>(obj), mid, - args)); + JValue result(InvokeVirtualOrInterfaceWithJValues(soa, obj, mid, args)); return soa.AddLocalReference<jobject>(result.GetL()); } @@ -999,8 +726,7 @@ class JNI { CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj); CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid); ScopedObjectAccess soa(env); - return InvokeVirtualOrInterfaceWithJValues(soa, soa.Decode<mirror::Object*>(obj), mid, - args).GetZ(); + return InvokeVirtualOrInterfaceWithJValues(soa, obj, mid, args).GetZ(); } static jbyte CallByteMethod(JNIEnv* env, jobject obj, jmethodID mid, ...) { @@ -1025,8 +751,7 @@ class JNI { CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj); CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid); ScopedObjectAccess soa(env); - return InvokeVirtualOrInterfaceWithJValues(soa, soa.Decode<mirror::Object*>(obj), mid, - args).GetB(); + return InvokeVirtualOrInterfaceWithJValues(soa, obj, mid, args).GetB(); } static jchar CallCharMethod(JNIEnv* env, jobject obj, jmethodID mid, ...) { @@ -1051,8 +776,7 @@ class JNI { CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj); CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid); ScopedObjectAccess soa(env); - return InvokeVirtualOrInterfaceWithJValues(soa, soa.Decode<mirror::Object*>(obj), mid, - args).GetC(); + return InvokeVirtualOrInterfaceWithJValues(soa, obj, mid, args).GetC(); } static jdouble CallDoubleMethod(JNIEnv* env, jobject obj, jmethodID mid, ...) { @@ -1077,8 +801,7 @@ class JNI { CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj); CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid); ScopedObjectAccess soa(env); - return InvokeVirtualOrInterfaceWithJValues(soa, soa.Decode<mirror::Object*>(obj), mid, - args).GetD(); + return InvokeVirtualOrInterfaceWithJValues(soa, obj, mid, args).GetD(); } static jfloat CallFloatMethod(JNIEnv* env, jobject obj, jmethodID mid, ...) { @@ -1103,8 +826,7 @@ class JNI { CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj); CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid); ScopedObjectAccess soa(env); - return InvokeVirtualOrInterfaceWithJValues(soa, soa.Decode<mirror::Object*>(obj), mid, - args).GetF(); + return InvokeVirtualOrInterfaceWithJValues(soa, obj, mid, args).GetF(); } static jint CallIntMethod(JNIEnv* env, jobject obj, jmethodID mid, ...) { @@ -1129,8 +851,7 @@ class JNI { CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj); CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid); ScopedObjectAccess soa(env); - return InvokeVirtualOrInterfaceWithJValues(soa, soa.Decode<mirror::Object*>(obj), mid, - args).GetI(); + return InvokeVirtualOrInterfaceWithJValues(soa, obj, mid, args).GetI(); } static jlong CallLongMethod(JNIEnv* env, jobject obj, jmethodID mid, ...) { @@ -1155,8 +876,7 @@ class JNI { CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj); CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid); ScopedObjectAccess soa(env); - return InvokeVirtualOrInterfaceWithJValues(soa, soa.Decode<mirror::Object*>(obj), mid, - args).GetJ(); + return InvokeVirtualOrInterfaceWithJValues(soa, obj, mid, args).GetJ(); } static jshort CallShortMethod(JNIEnv* env, jobject obj, jmethodID mid, ...) { @@ -1181,8 +901,7 @@ class JNI { CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj); CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid); ScopedObjectAccess soa(env); - return InvokeVirtualOrInterfaceWithJValues(soa, soa.Decode<mirror::Object*>(obj), mid, - args).GetS(); + return InvokeVirtualOrInterfaceWithJValues(soa, obj, mid, args).GetS(); } static void CallVoidMethod(JNIEnv* env, jobject obj, jmethodID mid, ...) { @@ -1206,7 +925,7 @@ class JNI { CHECK_NON_NULL_ARGUMENT_RETURN_VOID(obj); CHECK_NON_NULL_ARGUMENT_RETURN_VOID(mid); ScopedObjectAccess soa(env); - InvokeVirtualOrInterfaceWithJValues(soa, soa.Decode<mirror::Object*>(obj), mid, args); + InvokeVirtualOrInterfaceWithJValues(soa, obj, mid, args); } static jobject CallNonvirtualObjectMethod(JNIEnv* env, jobject obj, jclass, jmethodID mid, ...) { @@ -1235,7 +954,7 @@ class JNI { CHECK_NON_NULL_ARGUMENT(obj); CHECK_NON_NULL_ARGUMENT(mid); ScopedObjectAccess soa(env); - JValue result(InvokeWithJValues(soa, soa.Decode<mirror::Object*>(obj), mid, args)); + JValue result(InvokeWithJValues(soa, obj, mid, args)); return soa.AddLocalReference<jobject>(result.GetL()); } @@ -1264,7 +983,7 @@ class JNI { CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj); CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid); ScopedObjectAccess soa(env); - return InvokeWithJValues(soa, soa.Decode<mirror::Object*>(obj), mid, args).GetZ(); + return InvokeWithJValues(soa, obj, mid, args).GetZ(); } static jbyte CallNonvirtualByteMethod(JNIEnv* env, jobject obj, jclass, jmethodID mid, ...) { @@ -1291,7 +1010,7 @@ class JNI { CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj); CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid); ScopedObjectAccess soa(env); - return InvokeWithJValues(soa, soa.Decode<mirror::Object*>(obj), mid, args).GetB(); + return InvokeWithJValues(soa, obj, mid, args).GetB(); } static jchar CallNonvirtualCharMethod(JNIEnv* env, jobject obj, jclass, jmethodID mid, ...) { @@ -1318,7 +1037,7 @@ class JNI { CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj); CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid); ScopedObjectAccess soa(env); - return InvokeWithJValues(soa, soa.Decode<mirror::Object*>(obj), mid, args).GetC(); + return InvokeWithJValues(soa, obj, mid, args).GetC(); } static jshort CallNonvirtualShortMethod(JNIEnv* env, jobject obj, jclass, jmethodID mid, ...) { @@ -1345,7 +1064,7 @@ class JNI { CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj); CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid); ScopedObjectAccess soa(env); - return InvokeWithJValues(soa, soa.Decode<mirror::Object*>(obj), mid, args).GetS(); + return InvokeWithJValues(soa, obj, mid, args).GetS(); } static jint CallNonvirtualIntMethod(JNIEnv* env, jobject obj, jclass, jmethodID mid, ...) { @@ -1372,7 +1091,7 @@ class JNI { CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj); CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid); ScopedObjectAccess soa(env); - return InvokeWithJValues(soa, soa.Decode<mirror::Object*>(obj), mid, args).GetI(); + return InvokeWithJValues(soa, obj, mid, args).GetI(); } static jlong CallNonvirtualLongMethod(JNIEnv* env, jobject obj, jclass, jmethodID mid, ...) { @@ -1399,7 +1118,7 @@ class JNI { CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj); CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid); ScopedObjectAccess soa(env); - return InvokeWithJValues(soa, soa.Decode<mirror::Object*>(obj), mid, args).GetJ(); + return InvokeWithJValues(soa, obj, mid, args).GetJ(); } static jfloat CallNonvirtualFloatMethod(JNIEnv* env, jobject obj, jclass, jmethodID mid, ...) { @@ -1426,7 +1145,7 @@ class JNI { CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj); CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid); ScopedObjectAccess soa(env); - return InvokeWithJValues(soa, soa.Decode<mirror::Object*>(obj), mid, args).GetF(); + return InvokeWithJValues(soa, obj, mid, args).GetF(); } static jdouble CallNonvirtualDoubleMethod(JNIEnv* env, jobject obj, jclass, jmethodID mid, ...) { @@ -1453,7 +1172,7 @@ class JNI { CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(obj); CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(mid); ScopedObjectAccess soa(env); - return InvokeWithJValues(soa, soa.Decode<mirror::Object*>(obj), mid, args).GetD(); + return InvokeWithJValues(soa, obj, mid, args).GetD(); } static void CallNonvirtualVoidMethod(JNIEnv* env, jobject obj, jclass, jmethodID mid, ...) { @@ -1479,7 +1198,7 @@ class JNI { CHECK_NON_NULL_ARGUMENT_RETURN_VOID(obj); CHECK_NON_NULL_ARGUMENT_RETURN_VOID(mid); ScopedObjectAccess soa(env); - InvokeWithJValues(soa, soa.Decode<mirror::Object*>(obj), mid, args); + InvokeWithJValues(soa, obj, mid, args); } static jfieldID GetFieldID(JNIEnv* env, jclass java_class, const char* name, const char* sig) { @@ -1504,14 +1223,14 @@ class JNI { CHECK_NON_NULL_ARGUMENT(fid); ScopedObjectAccess soa(env); mirror::Object* o = soa.Decode<mirror::Object*>(obj); - mirror::ArtField* f = soa.DecodeField(fid); + ArtField* f = soa.DecodeField(fid); return soa.AddLocalReference<jobject>(f->GetObject(o)); } static jobject GetStaticObjectField(JNIEnv* env, jclass, jfieldID fid) { CHECK_NON_NULL_ARGUMENT(fid); ScopedObjectAccess soa(env); - mirror::ArtField* f = soa.DecodeField(fid); + ArtField* f = soa.DecodeField(fid); return soa.AddLocalReference<jobject>(f->GetObject(f->GetDeclaringClass())); } @@ -1521,7 +1240,7 @@ class JNI { ScopedObjectAccess soa(env); mirror::Object* o = soa.Decode<mirror::Object*>(java_object); mirror::Object* v = soa.Decode<mirror::Object*>(java_value); - mirror::ArtField* f = soa.DecodeField(fid); + ArtField* f = soa.DecodeField(fid); f->SetObject<false>(o, v); } @@ -1529,7 +1248,7 @@ class JNI { CHECK_NON_NULL_ARGUMENT_RETURN_VOID(fid); ScopedObjectAccess soa(env); mirror::Object* v = soa.Decode<mirror::Object*>(java_value); - mirror::ArtField* f = soa.DecodeField(fid); + ArtField* f = soa.DecodeField(fid); f->SetObject<false>(f->GetDeclaringClass(), v); } @@ -1538,13 +1257,13 @@ class JNI { CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(fid); \ ScopedObjectAccess soa(env); \ mirror::Object* o = soa.Decode<mirror::Object*>(instance); \ - mirror::ArtField* f = soa.DecodeField(fid); \ + ArtField* f = soa.DecodeField(fid); \ return f->Get ##fn (o) #define GET_STATIC_PRIMITIVE_FIELD(fn) \ CHECK_NON_NULL_ARGUMENT_RETURN_ZERO(fid); \ ScopedObjectAccess soa(env); \ - mirror::ArtField* f = soa.DecodeField(fid); \ + ArtField* f = soa.DecodeField(fid); \ return f->Get ##fn (f->GetDeclaringClass()) #define SET_PRIMITIVE_FIELD(fn, instance, value) \ @@ -1552,13 +1271,13 @@ class JNI { CHECK_NON_NULL_ARGUMENT_RETURN_VOID(fid); \ ScopedObjectAccess soa(env); \ mirror::Object* o = soa.Decode<mirror::Object*>(instance); \ - mirror::ArtField* f = soa.DecodeField(fid); \ + ArtField* f = soa.DecodeField(fid); \ f->Set ##fn <false>(o, value) #define SET_STATIC_PRIMITIVE_FIELD(fn, value) \ CHECK_NON_NULL_ARGUMENT_RETURN_VOID(fid); \ ScopedObjectAccess soa(env); \ - mirror::ArtField* f = soa.DecodeField(fid); \ + ArtField* f = soa.DecodeField(fid); \ f->Set ##fn <false>(f->GetDeclaringClass(), value) static jboolean GetBooleanField(JNIEnv* env, jobject obj, jfieldID fid) { @@ -1913,11 +1632,11 @@ class JNI { static jstring NewString(JNIEnv* env, const jchar* chars, jsize char_count) { if (UNLIKELY(char_count < 0)) { - JniAbortF("NewString", "char_count < 0: %d", char_count); + JavaVmExtFromEnv(env)->JniAbortF("NewString", "char_count < 0: %d", char_count); return nullptr; } if (UNLIKELY(chars == nullptr && char_count > 0)) { - JniAbortF("NewString", "chars == null && char_count > 0"); + JavaVmExtFromEnv(env)->JniAbortF("NewString", "chars == null && char_count > 0"); return nullptr; } ScopedObjectAccess soa(env); @@ -1955,7 +1674,7 @@ class JNI { ThrowSIOOBE(soa, start, length, s->GetLength()); } else { CHECK_NON_NULL_MEMCPY_ARGUMENT(length, buf); - const jchar* chars = s->GetCharArray()->GetData() + s->GetOffset(); + const jchar* chars = s->GetValue(); memcpy(buf, chars + start, length * sizeof(jchar)); } } @@ -1969,7 +1688,7 @@ class JNI { ThrowSIOOBE(soa, start, length, s->GetLength()); } else { CHECK_NON_NULL_MEMCPY_ARGUMENT(length, buf); - const jchar* chars = s->GetCharArray()->GetData() + s->GetOffset(); + const jchar* chars = s->GetValue(); ConvertUtf16ToModifiedUtf8(buf, chars + start, length); } } @@ -1978,33 +1697,26 @@ class JNI { CHECK_NON_NULL_ARGUMENT(java_string); ScopedObjectAccess soa(env); mirror::String* s = soa.Decode<mirror::String*>(java_string); - mirror::CharArray* chars = s->GetCharArray(); gc::Heap* heap = Runtime::Current()->GetHeap(); - if (heap->IsMovableObject(chars)) { + if (heap->IsMovableObject(s)) { + jchar* chars = new jchar[s->GetLength()]; + memcpy(chars, s->GetValue(), sizeof(jchar) * s->GetLength()); if (is_copy != nullptr) { *is_copy = JNI_TRUE; } - int32_t char_count = s->GetLength(); - int32_t offset = s->GetOffset(); - jchar* bytes = new jchar[char_count]; - for (int32_t i = 0; i < char_count; i++) { - bytes[i] = chars->Get(i + offset); - } - return bytes; - } else { - if (is_copy != nullptr) { - *is_copy = JNI_FALSE; - } - return static_cast<jchar*>(chars->GetData() + s->GetOffset()); + return chars; + } + if (is_copy != nullptr) { + *is_copy = JNI_FALSE; } + return static_cast<jchar*>(s->GetValue()); } static void ReleaseStringChars(JNIEnv* env, jstring java_string, const jchar* chars) { CHECK_NON_NULL_ARGUMENT_RETURN_VOID(java_string); ScopedObjectAccess soa(env); mirror::String* s = soa.Decode<mirror::String*>(java_string); - mirror::CharArray* s_chars = s->GetCharArray(); - if (chars != (s_chars->GetData() + s->GetOffset())) { + if (chars != s->GetValue()) { delete[] chars; } } @@ -2013,27 +1725,25 @@ class JNI { CHECK_NON_NULL_ARGUMENT(java_string); ScopedObjectAccess soa(env); mirror::String* s = soa.Decode<mirror::String*>(java_string); - mirror::CharArray* chars = s->GetCharArray(); - int32_t offset = s->GetOffset(); gc::Heap* heap = Runtime::Current()->GetHeap(); - if (heap->IsMovableObject(chars)) { + if (heap->IsMovableObject(s)) { StackHandleScope<1> hs(soa.Self()); - HandleWrapper<mirror::CharArray> h(hs.NewHandleWrapper(&chars)); + HandleWrapper<mirror::String> h(hs.NewHandleWrapper(&s)); heap->IncrementDisableMovingGC(soa.Self()); } if (is_copy != nullptr) { *is_copy = JNI_FALSE; } - return static_cast<jchar*>(chars->GetData() + offset); + return static_cast<jchar*>(s->GetValue()); } static void ReleaseStringCritical(JNIEnv* env, jstring java_string, const jchar* chars) { + UNUSED(chars); CHECK_NON_NULL_ARGUMENT_RETURN_VOID(java_string); ScopedObjectAccess soa(env); gc::Heap* heap = Runtime::Current()->GetHeap(); mirror::String* s = soa.Decode<mirror::String*>(java_string); - mirror::CharArray* s_chars = s->GetCharArray(); - if (heap->IsMovableObject(s_chars)) { + if (heap->IsMovableObject(s)) { heap->DecrementDisableMovingGC(soa.Self()); } } @@ -2050,13 +1760,13 @@ class JNI { size_t byte_count = s->GetUtfLength(); char* bytes = new char[byte_count + 1]; CHECK(bytes != nullptr); // bionic aborts anyway. - const uint16_t* chars = s->GetCharArray()->GetData() + s->GetOffset(); + const uint16_t* chars = s->GetValue(); ConvertUtf16ToModifiedUtf8(bytes, chars, s->GetLength()); bytes[byte_count] = '\0'; return bytes; } - static void ReleaseStringUTFChars(JNIEnv* env, jstring, const char* chars) { + static void ReleaseStringUTFChars(JNIEnv*, jstring, const char* chars) { delete[] chars; } @@ -2065,7 +1775,8 @@ class JNI { ScopedObjectAccess soa(env); mirror::Object* obj = soa.Decode<mirror::Object*>(java_array); if (UNLIKELY(!obj->IsArrayInstance())) { - JniAbortF("GetArrayLength", "not an array: %s", PrettyTypeOf(obj).c_str()); + soa.Vm()->JniAbortF("GetArrayLength", "not an array: %s", PrettyTypeOf(obj).c_str()); + return 0; } mirror::Array* array = obj->AsArray(); return array->GetLength(); @@ -2120,7 +1831,7 @@ class JNI { static jobjectArray NewObjectArray(JNIEnv* env, jsize length, jclass element_jclass, jobject initial_element) { if (UNLIKELY(length < 0)) { - JniAbortF("NewObjectArray", "negative array length: %d", length); + JavaVmExtFromEnv(env)->JniAbortF("NewObjectArray", "negative array length: %d", length); return nullptr; } CHECK_NON_NULL_ARGUMENT(element_jclass); @@ -2131,8 +1842,8 @@ class JNI { { mirror::Class* element_class = soa.Decode<mirror::Class*>(element_jclass); if (UNLIKELY(element_class->IsPrimitive())) { - JniAbortF("NewObjectArray", "not an object type: %s", - PrettyDescriptor(element_class).c_str()); + soa.Vm()->JniAbortF("NewObjectArray", "not an object type: %s", + PrettyDescriptor(element_class).c_str()); return nullptr; } ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); @@ -2150,10 +1861,11 @@ class JNI { if (initial_object != nullptr) { mirror::Class* element_class = result->GetClass()->GetComponentType(); if (UNLIKELY(!element_class->IsAssignableFrom(initial_object->GetClass()))) { - JniAbortF("NewObjectArray", "cannot assign object of type '%s' to array with element " - "type of '%s'", PrettyDescriptor(initial_object->GetClass()).c_str(), - PrettyDescriptor(element_class).c_str()); - + soa.Vm()->JniAbortF("NewObjectArray", "cannot assign object of type '%s' to array with " + "element type of '%s'", + PrettyDescriptor(initial_object->GetClass()).c_str(), + PrettyDescriptor(element_class).c_str()); + return nullptr; } else { for (jsize i = 0; i < length; ++i) { result->SetWithoutChecks<false>(i, initial_object); @@ -2173,8 +1885,8 @@ class JNI { ScopedObjectAccess soa(env); mirror::Array* array = soa.Decode<mirror::Array*>(java_array); if (UNLIKELY(!array->GetClass()->IsPrimitiveArray())) { - JniAbortF("GetPrimitiveArrayCritical", "expected primitive array, given %s", - PrettyDescriptor(array->GetClass()).c_str()); + soa.Vm()->JniAbortF("GetPrimitiveArrayCritical", "expected primitive array, given %s", + PrettyDescriptor(array->GetClass()).c_str()); return nullptr; } gc::Heap* heap = Runtime::Current()->GetHeap(); @@ -2195,8 +1907,8 @@ class JNI { ScopedObjectAccess soa(env); mirror::Array* array = soa.Decode<mirror::Array*>(java_array); if (UNLIKELY(!array->GetClass()->IsPrimitiveArray())) { - JniAbortF("ReleasePrimitiveArrayCritical", "expected primitive array, given %s", - PrettyDescriptor(array->GetClass()).c_str()); + soa.Vm()->JniAbortF("ReleasePrimitiveArrayCritical", "expected primitive array, given %s", + PrettyDescriptor(array->GetClass()).c_str()); return; } const size_t component_size = array->GetClass()->GetComponentSize(); @@ -2368,8 +2080,9 @@ class JNI { static jint RegisterNativeMethods(JNIEnv* env, jclass java_class, const JNINativeMethod* methods, jint method_count, bool return_errors) { if (UNLIKELY(method_count < 0)) { - JniAbortF("RegisterNatives", "negative method count: %d", method_count); - return JNI_ERR; // Not reached. + JavaVmExtFromEnv(env)->JniAbortF("RegisterNatives", "negative method count: %d", + method_count); + return JNI_ERR; // Not reached except in unit tests. } CHECK_NON_NULL_ARGUMENT_FN_NAME("RegisterNatives", java_class, JNI_ERR); ScopedObjectAccess soa(env); @@ -2395,20 +2108,74 @@ class JNI { return JNI_ERR; } bool is_fast = false; + // Notes about fast JNI calls: + // + // On a normal JNI call, the calling thread usually transitions + // from the kRunnable state to the kNative state. But if the + // called native function needs to access any Java object, it + // will have to transition back to the kRunnable state. + // + // There is a cost to this double transition. For a JNI call + // that should be quick, this cost may dominate the call cost. + // + // On a fast JNI call, the calling thread avoids this double + // transition by not transitioning from kRunnable to kNative and + // stays in the kRunnable state. + // + // There are risks to using a fast JNI call because it can delay + // a response to a thread suspension request which is typically + // used for a GC root scanning, etc. If a fast JNI call takes a + // long time, it could cause longer thread suspension latency + // and GC pauses. + // + // Thus, fast JNI should be used with care. It should be used + // for a JNI call that takes a short amount of time (eg. no + // long-running loop) and does not block (eg. no locks, I/O, + // etc.) + // + // A '!' prefix in the signature in the JNINativeMethod + // indicates that it's a fast JNI call and the runtime omits the + // thread state transition from kRunnable to kNative at the + // entry. if (*sig == '!') { is_fast = true; ++sig; } - mirror::ArtMethod* m = c->FindDirectMethod(name, sig); - if (m == nullptr) { - m = c->FindVirtualMethod(name, sig); + // Note: the right order is to try to find the method locally + // first, either as a direct or a virtual method. Then move to + // the parent. + ArtMethod* m = nullptr; + bool warn_on_going_to_parent = down_cast<JNIEnvExt*>(env)->vm->IsCheckJniEnabled(); + for (mirror::Class* current_class = c; + current_class != nullptr; + current_class = current_class->GetSuperClass()) { + // Search first only comparing methods which are native. + m = FindMethod<true>(current_class, name, sig); + if (m != nullptr) { + break; + } + + // Search again comparing to all methods, to find non-native methods that match. + m = FindMethod<false>(current_class, name, sig); + if (m != nullptr) { + break; + } + + if (warn_on_going_to_parent) { + LOG(WARNING) << "CheckJNI: method to register \"" << name << "\" not in the given class. " + << "This is slow, consider changing your RegisterNatives calls."; + warn_on_going_to_parent = false; + } } + if (m == nullptr) { - c->DumpClass(LOG(ERROR), mirror::Class::kDumpClassFullDetail); - LOG(return_errors ? ERROR : FATAL) << "Failed to register native method " + LOG(return_errors ? ERROR : INTERNAL_FATAL) << "Failed to register native method " << PrettyDescriptor(c) << "." << name << sig << " in " << c->GetDexCache()->GetLocation()->ToModifiedUtf8(); + // Safe to pass in LOG(FATAL) since the log object aborts in destructor and only goes + // out of scope after the DumpClass is done executing. + c->DumpClass(LOG(return_errors ? ERROR : FATAL), mirror::Class::kDumpClassFullDetail); ThrowNoSuchMethodError(soa, c, name, sig, "static or non-static"); return JNI_ERR; } else if (!m->IsNative()) { @@ -2421,7 +2188,7 @@ class JNI { VLOG(jni) << "[Registering JNI native method " << PrettyMethod(m) << "]"; - m->RegisterNative(soa.Self(), fnPtr, is_fast); + m->RegisterNative(fnPtr, is_fast); } return JNI_OK; } @@ -2434,17 +2201,16 @@ class JNI { VLOG(jni) << "[Unregistering JNI native methods for " << PrettyClass(c) << "]"; size_t unregistered_count = 0; - for (size_t i = 0; i < c->NumDirectMethods(); ++i) { - mirror::ArtMethod* m = c->GetDirectMethod(i); - if (m->IsNative()) { - m->UnregisterNative(soa.Self()); + auto pointer_size = Runtime::Current()->GetClassLinker()->GetImagePointerSize(); + for (auto& m : c->GetDirectMethods(pointer_size)) { + if (m.IsNative()) { + m.UnregisterNative(); unregistered_count++; } } - for (size_t i = 0; i < c->NumVirtualMethods(); ++i) { - mirror::ArtMethod* m = c->GetVirtualMethod(i); - if (m->IsNative()) { - m->UnregisterNative(soa.Self()); + for (auto& m : c->GetVirtualMethods(pointer_size)) { + if (m.IsNative()) { + m.UnregisterNative(); unregistered_count++; } } @@ -2493,17 +2259,21 @@ class JNI { static jobject NewDirectByteBuffer(JNIEnv* env, void* address, jlong capacity) { if (capacity < 0) { - JniAbortF("NewDirectByteBuffer", "negative buffer capacity: %" PRId64, capacity); + JavaVmExtFromEnv(env)->JniAbortF("NewDirectByteBuffer", "negative buffer capacity: %" PRId64, + capacity); return nullptr; } if (address == nullptr && capacity != 0) { - JniAbortF("NewDirectByteBuffer", "non-zero capacity for nullptr pointer: %" PRId64, capacity); + JavaVmExtFromEnv(env)->JniAbortF("NewDirectByteBuffer", + "non-zero capacity for nullptr pointer: %" PRId64, capacity); return nullptr; } // At the moment, the capacity of DirectByteBuffer is limited to a signed int. if (capacity > INT_MAX) { - JniAbortF("NewDirectByteBuffer", "buffer capacity greater than maximum jint: %" PRId64, capacity); + JavaVmExtFromEnv(env)->JniAbortF("NewDirectByteBuffer", + "buffer capacity greater than maximum jint: %" PRId64, + capacity); return nullptr; } jlong address_arg = reinterpret_cast<jlong>(address); @@ -2525,7 +2295,7 @@ class JNI { java_buffer, WellKnownClasses::java_nio_DirectByteBuffer_capacity)); } - static jobjectRefType GetObjectRefType(JNIEnv* env, jobject java_object) { + static jobjectRefType GetObjectRefType(JNIEnv* env ATTRIBUTE_UNUSED, jobject java_object) { if (java_object == nullptr) { return JNIInvalidRefType; } @@ -2534,33 +2304,24 @@ class JNI { IndirectRef ref = reinterpret_cast<IndirectRef>(java_object); IndirectRefKind kind = GetIndirectRefKind(ref); switch (kind) { - case kLocal: { - ScopedObjectAccess soa(env); - // The local refs don't need a read barrier. - if (static_cast<JNIEnvExt*>(env)->locals.Get<kWithoutReadBarrier>(ref) != - kInvalidIndirectRefObject) { - return JNILocalRefType; - } - return JNIInvalidRefType; - } + case kLocal: + return JNILocalRefType; case kGlobal: return JNIGlobalRefType; case kWeakGlobal: return JNIWeakGlobalRefType; case kHandleScopeOrInvalid: - // Is it in a stack IRT? - if (static_cast<JNIEnvExt*>(env)->self->HandleScopeContains(java_object)) { - return JNILocalRefType; - } - return JNIInvalidRefType; + // Assume value is in a handle scope. + return JNILocalRefType; } LOG(FATAL) << "IndirectRefKind[" << kind << "]"; - return JNIInvalidRefType; + UNREACHABLE(); } private: - static jint EnsureLocalCapacity(ScopedObjectAccess& soa, jint desired_capacity, - const char* caller) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { + static jint EnsureLocalCapacityInternal(ScopedObjectAccess& soa, jint desired_capacity, + const char* caller) + SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { // TODO: we should try to expand the table if necessary. if (desired_capacity < 0 || desired_capacity > static_cast<jint>(kLocalsMax)) { LOG(ERROR) << "Invalid capacity given to " << caller << ": " << desired_capacity; @@ -2577,11 +2338,11 @@ class JNI { template<typename JniT, typename ArtT> static JniT NewPrimitiveArray(JNIEnv* env, jsize length) { + ScopedObjectAccess soa(env); if (UNLIKELY(length < 0)) { - JniAbortF("NewPrimitiveArray", "negative array length: %d", length); + soa.Vm()->JniAbortF("NewPrimitiveArray", "negative array length: %d", length); return nullptr; } - ScopedObjectAccess soa(env); ArtT* result = ArtT::Alloc(soa.Self(), length); return soa.AddLocalReference<JniT>(result); } @@ -2592,9 +2353,11 @@ class JNI { SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { ArtArrayT* array = soa.Decode<ArtArrayT*>(java_array); if (UNLIKELY(ArtArrayT::GetArrayClass() != array->GetClass())) { - JniAbortF(fn_name, "attempt to %s %s primitive array elements with an object of type %s", - operation, PrettyDescriptor(ArtArrayT::GetArrayClass()->GetComponentType()).c_str(), - PrettyDescriptor(array->GetClass()).c_str()); + soa.Vm()->JniAbortF(fn_name, + "attempt to %s %s primitive array elements with an object of type %s", + operation, + PrettyDescriptor(ArtArrayT::GetArrayClass()->GetComponentType()).c_str(), + PrettyDescriptor(array->GetClass()).c_str()); return nullptr; } DCHECK_EQ(sizeof(ElementT), array->GetClass()->GetComponentSize()); @@ -2656,14 +2419,18 @@ class JNI { // heap address. TODO: This might be slow to check, may be worth keeping track of which // copies we make? if (heap->IsNonDiscontinuousSpaceHeapAddress(reinterpret_cast<mirror::Object*>(elements))) { - JniAbortF("ReleaseArrayElements", "invalid element pointer %p, array elements are %p", - reinterpret_cast<void*>(elements), array_data); + soa.Vm()->JniAbortF("ReleaseArrayElements", + "invalid element pointer %p, array elements are %p", + reinterpret_cast<void*>(elements), array_data); return; } - } - // Don't need to copy if we had a direct pointer. - if (mode != JNI_ABORT && is_copy) { - memcpy(array_data, elements, bytes); + if (mode != JNI_ABORT) { + memcpy(array_data, elements, bytes); + } else if (kWarnJniAbort && memcmp(array_data, elements, bytes) != 0) { + // Warn if we have JNI_ABORT and the arrays don't match since this is usually an error. + LOG(WARNING) << "Possible incorrect JNI_ABORT in Release*ArrayElements"; + soa.Self()->DumpJavaStack(LOG(WARNING)); + } } if (mode != JNI_COMMIT) { if (is_copy) { @@ -2952,476 +2719,8 @@ const JNINativeInterface gJniNativeInterface = { JNI::GetObjectRefType, }; -JNIEnvExt::JNIEnvExt(Thread* self, JavaVMExt* vm) - : self(self), - vm(vm), - local_ref_cookie(IRT_FIRST_SEGMENT), - locals(kLocalsInitial, kLocalsMax, kLocal), - check_jni(false), - critical(0), - monitors("monitors", kMonitorsInitial, kMonitorsMax) { - functions = unchecked_functions = &gJniNativeInterface; - if (vm->check_jni) { - SetCheckJniEnabled(true); - } -} - -JNIEnvExt::~JNIEnvExt() { -} - -jobject JNIEnvExt::NewLocalRef(mirror::Object* obj) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { - if (obj == nullptr) { - return nullptr; - } - return reinterpret_cast<jobject>(locals.Add(local_ref_cookie, obj)); -} - -void JNIEnvExt::DeleteLocalRef(jobject obj) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { - if (obj != nullptr) { - locals.Remove(local_ref_cookie, reinterpret_cast<IndirectRef>(obj)); - } -} -void JNIEnvExt::SetCheckJniEnabled(bool enabled) { - check_jni = enabled; - functions = enabled ? GetCheckJniNativeInterface() : &gJniNativeInterface; -} - -void JNIEnvExt::DumpReferenceTables(std::ostream& os) { - locals.Dump(os); - monitors.Dump(os); -} - -void JNIEnvExt::PushFrame(int capacity) SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { - UNUSED(capacity); // cpplint gets confused with (int) and thinks its a cast. - // TODO: take 'capacity' into account. - stacked_local_ref_cookies.push_back(local_ref_cookie); - local_ref_cookie = locals.GetSegmentState(); -} - -void JNIEnvExt::PopFrame() SHARED_LOCKS_REQUIRED(Locks::mutator_lock_) { - locals.SetSegmentState(local_ref_cookie); - local_ref_cookie = stacked_local_ref_cookies.back(); - stacked_local_ref_cookies.pop_back(); -} - -Offset JNIEnvExt::SegmentStateOffset() { - return Offset(OFFSETOF_MEMBER(JNIEnvExt, locals) + - IndirectReferenceTable::SegmentStateOffset().Int32Value()); -} - -// JNI Invocation interface. - -extern "C" jint JNI_CreateJavaVM(JavaVM** p_vm, JNIEnv** p_env, void* vm_args) { - const JavaVMInitArgs* args = static_cast<JavaVMInitArgs*>(vm_args); - if (IsBadJniVersion(args->version)) { - LOG(ERROR) << "Bad JNI version passed to CreateJavaVM: " << args->version; - return JNI_EVERSION; - } - RuntimeOptions options; - for (int i = 0; i < args->nOptions; ++i) { - JavaVMOption* option = &args->options[i]; - options.push_back(std::make_pair(std::string(option->optionString), option->extraInfo)); - } - bool ignore_unrecognized = args->ignoreUnrecognized; - if (!Runtime::Create(options, ignore_unrecognized)) { - return JNI_ERR; - } - Runtime* runtime = Runtime::Current(); - bool started = runtime->Start(); - if (!started) { - delete Thread::Current()->GetJniEnv(); - delete runtime->GetJavaVM(); - LOG(WARNING) << "CreateJavaVM failed"; - return JNI_ERR; - } - *p_env = Thread::Current()->GetJniEnv(); - *p_vm = runtime->GetJavaVM(); - return JNI_OK; -} - -extern "C" jint JNI_GetCreatedJavaVMs(JavaVM** vms, jsize, jsize* vm_count) { - Runtime* runtime = Runtime::Current(); - if (runtime == nullptr) { - *vm_count = 0; - } else { - *vm_count = 1; - vms[0] = runtime->GetJavaVM(); - } - return JNI_OK; -} - -// Historically unsupported. -extern "C" jint JNI_GetDefaultJavaVMInitArgs(void* /*vm_args*/) { - return JNI_ERR; -} - -class JII { - public: - static jint DestroyJavaVM(JavaVM* vm) { - if (vm == nullptr) { - return JNI_ERR; - } - JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm); - delete raw_vm->runtime; - return JNI_OK; - } - - static jint AttachCurrentThread(JavaVM* vm, JNIEnv** p_env, void* thr_args) { - return JII_AttachCurrentThread(vm, p_env, thr_args, false); - } - - static jint AttachCurrentThreadAsDaemon(JavaVM* vm, JNIEnv** p_env, void* thr_args) { - return JII_AttachCurrentThread(vm, p_env, thr_args, true); - } - - static jint DetachCurrentThread(JavaVM* vm) { - if (vm == nullptr || Thread::Current() == nullptr) { - return JNI_ERR; - } - JavaVMExt* raw_vm = reinterpret_cast<JavaVMExt*>(vm); - Runtime* runtime = raw_vm->runtime; - runtime->DetachCurrentThread(); - return JNI_OK; - } - - static jint GetEnv(JavaVM* vm, void** env, jint version) { - // GetEnv always returns a JNIEnv* for the most current supported JNI version, - // and unlike other calls that take a JNI version doesn't care if you supply - // JNI_VERSION_1_1, which we don't otherwise support. - if (IsBadJniVersion(version) && version != JNI_VERSION_1_1) { - LOG(ERROR) << "Bad JNI version passed to GetEnv: " << version; - return JNI_EVERSION; - } - if (vm == nullptr || env == nullptr) { - return JNI_ERR; - } - Thread* thread = Thread::Current(); - if (thread == nullptr) { - *env = nullptr; - return JNI_EDETACHED; - } - *env = thread->GetJniEnv(); - return JNI_OK; - } -}; - -const JNIInvokeInterface gJniInvokeInterface = { - nullptr, // reserved0 - nullptr, // reserved1 - nullptr, // reserved2 - JII::DestroyJavaVM, - JII::AttachCurrentThread, - JII::DetachCurrentThread, - JII::GetEnv, - JII::AttachCurrentThreadAsDaemon -}; - -JavaVMExt::JavaVMExt(Runtime* runtime, ParsedOptions* options) - : runtime(runtime), - check_jni_abort_hook(nullptr), - check_jni_abort_hook_data(nullptr), - check_jni(false), - force_copy(false), // TODO: add a way to enable this - trace(options->jni_trace_), - globals_lock("JNI global reference table lock"), - globals(gGlobalsInitial, gGlobalsMax, kGlobal), - libraries_lock("JNI shared libraries map lock", kLoadLibraryLock), - libraries(new Libraries), - weak_globals_lock_("JNI weak global reference table lock"), - weak_globals_(kWeakGlobalsInitial, kWeakGlobalsMax, kWeakGlobal), - allow_new_weak_globals_(true), - weak_globals_add_condition_("weak globals add condition", weak_globals_lock_) { - functions = unchecked_functions = &gJniInvokeInterface; - if (options->check_jni_) { - SetCheckJniEnabled(true); - } -} - -JavaVMExt::~JavaVMExt() { - delete libraries; -} - -jweak JavaVMExt::AddWeakGlobalReference(Thread* self, mirror::Object* obj) { - if (obj == nullptr) { - return nullptr; - } - MutexLock mu(self, weak_globals_lock_); - while (UNLIKELY(!allow_new_weak_globals_)) { - weak_globals_add_condition_.WaitHoldingLocks(self); - } - IndirectRef ref = weak_globals_.Add(IRT_FIRST_SEGMENT, obj); - return reinterpret_cast<jweak>(ref); -} - -void JavaVMExt::DeleteWeakGlobalRef(Thread* self, jweak obj) { - MutexLock mu(self, weak_globals_lock_); - if (!weak_globals_.Remove(IRT_FIRST_SEGMENT, obj)) { - LOG(WARNING) << "JNI WARNING: DeleteWeakGlobalRef(" << obj << ") " - << "failed to find entry"; - } -} - -void JavaVMExt::SetCheckJniEnabled(bool enabled) { - check_jni = enabled; - functions = enabled ? GetCheckJniInvokeInterface() : &gJniInvokeInterface; -} - -void JavaVMExt::DumpForSigQuit(std::ostream& os) { - os << "JNI: CheckJNI is " << (check_jni ? "on" : "off"); - if (force_copy) { - os << " (with forcecopy)"; - } - Thread* self = Thread::Current(); - { - ReaderMutexLock mu(self, globals_lock); - os << "; globals=" << globals.Capacity(); - } - { - MutexLock mu(self, weak_globals_lock_); - if (weak_globals_.Capacity() > 0) { - os << " (plus " << weak_globals_.Capacity() << " weak)"; - } - } - os << '\n'; - - { - MutexLock mu(self, libraries_lock); - os << "Libraries: " << Dumpable<Libraries>(*libraries) << " (" << libraries->size() << ")\n"; - } -} - -void JavaVMExt::DisallowNewWeakGlobals() { - MutexLock mu(Thread::Current(), weak_globals_lock_); - allow_new_weak_globals_ = false; -} - -void JavaVMExt::AllowNewWeakGlobals() { - Thread* self = Thread::Current(); - MutexLock mu(self, weak_globals_lock_); - allow_new_weak_globals_ = true; - weak_globals_add_condition_.Broadcast(self); -} - -mirror::Object* JavaVMExt::DecodeWeakGlobal(Thread* self, IndirectRef ref) { - MutexLock mu(self, weak_globals_lock_); - while (UNLIKELY(!allow_new_weak_globals_)) { - weak_globals_add_condition_.WaitHoldingLocks(self); - } - return weak_globals_.Get(ref); -} - -void JavaVMExt::DumpReferenceTables(std::ostream& os) { - Thread* self = Thread::Current(); - { - ReaderMutexLock mu(self, globals_lock); - globals.Dump(os); - } - { - MutexLock mu(self, weak_globals_lock_); - weak_globals_.Dump(os); - } -} - -bool JavaVMExt::LoadNativeLibrary(const std::string& path, - Handle<mirror::ClassLoader> class_loader, - std::string* detail) { - detail->clear(); - - // See if we've already loaded this library. If we have, and the class loader - // matches, return successfully without doing anything. - // TODO: for better results we should canonicalize the pathname (or even compare - // inodes). This implementation is fine if everybody is using System.loadLibrary. - SharedLibrary* library; - Thread* self = Thread::Current(); - { - // TODO: move the locking (and more of this logic) into Libraries. - MutexLock mu(self, libraries_lock); - library = libraries->Get(path); - } - if (library != nullptr) { - if (library->GetClassLoader() != class_loader.Get()) { - // The library will be associated with class_loader. The JNI - // spec says we can't load the same library into more than one - // class loader. - StringAppendF(detail, "Shared library \"%s\" already opened by " - "ClassLoader %p; can't open in ClassLoader %p", - path.c_str(), library->GetClassLoader(), class_loader.Get()); - LOG(WARNING) << detail; - return false; - } - VLOG(jni) << "[Shared library \"" << path << "\" already loaded in " - << "ClassLoader " << class_loader.Get() << "]"; - if (!library->CheckOnLoadResult()) { - StringAppendF(detail, "JNI_OnLoad failed on a previous attempt " - "to load \"%s\"", path.c_str()); - return false; - } - return true; - } - - // Open the shared library. Because we're using a full path, the system - // doesn't have to search through LD_LIBRARY_PATH. (It may do so to - // resolve this library's dependencies though.) - - // Failures here are expected when java.library.path has several entries - // and we have to hunt for the lib. - - // Below we dlopen but there is no paired dlclose, this would be necessary if we supported - // class unloading. Libraries will only be unloaded when the reference count (incremented by - // dlopen) becomes zero from dlclose. - - // This can execute slowly for a large library on a busy system, so we - // want to switch from kRunnable while it executes. This allows the GC to ignore us. - self->TransitionFromRunnableToSuspended(kWaitingForJniOnLoad); - const char* path_str = path.empty() ? nullptr : path.c_str(); - void* handle = dlopen(path_str, RTLD_LAZY); - bool needs_native_bridge = false; - if (handle == nullptr) { - if (android::NativeBridgeIsSupported(path_str)) { - handle = android::NativeBridgeLoadLibrary(path_str, RTLD_LAZY); - needs_native_bridge = true; - } - } - self->TransitionFromSuspendedToRunnable(); - - VLOG(jni) << "[Call to dlopen(\"" << path << "\", RTLD_LAZY) returned " << handle << "]"; - - if (handle == nullptr) { - *detail = dlerror(); - LOG(ERROR) << "dlopen(\"" << path << "\", RTLD_LAZY) failed: " << *detail; - return false; - } - - // Create a new entry. - // TODO: move the locking (and more of this logic) into Libraries. - bool created_library = false; - { - MutexLock mu(self, libraries_lock); - library = libraries->Get(path); - if (library == nullptr) { // We won race to get libraries_lock - library = new SharedLibrary(path, handle, class_loader.Get()); - libraries->Put(path, library); - created_library = true; - } - } - if (!created_library) { - LOG(INFO) << "WOW: we lost a race to add shared library: " - << "\"" << path << "\" ClassLoader=" << class_loader.Get(); - return library->CheckOnLoadResult(); - } - - VLOG(jni) << "[Added shared library \"" << path << "\" for ClassLoader " << class_loader.Get() - << "]"; - - bool was_successful = false; - void* sym = nullptr; - if (UNLIKELY(needs_native_bridge)) { - library->SetNeedsNativeBridge(); - sym = library->FindSymbolWithNativeBridge("JNI_OnLoad", nullptr); - } else { - sym = dlsym(handle, "JNI_OnLoad"); - } - - if (sym == nullptr) { - VLOG(jni) << "[No JNI_OnLoad found in \"" << path << "\"]"; - was_successful = true; - } else { - // Call JNI_OnLoad. We have to override the current class - // loader, which will always be "null" since the stuff at the - // top of the stack is around Runtime.loadLibrary(). (See - // the comments in the JNI FindClass function.) - typedef int (*JNI_OnLoadFn)(JavaVM*, void*); - JNI_OnLoadFn jni_on_load = reinterpret_cast<JNI_OnLoadFn>(sym); - StackHandleScope<1> hs(self); - Handle<mirror::ClassLoader> old_class_loader(hs.NewHandle(self->GetClassLoaderOverride())); - self->SetClassLoaderOverride(class_loader.Get()); - - int version = 0; - { - ScopedThreadStateChange tsc(self, kNative); - VLOG(jni) << "[Calling JNI_OnLoad in \"" << path << "\"]"; - version = (*jni_on_load)(this, nullptr); - } - - if (runtime->GetTargetSdkVersion() != 0 && runtime->GetTargetSdkVersion() <= 21) { - fault_manager.EnsureArtActionInFrontOfSignalChain(); - } - self->SetClassLoaderOverride(old_class_loader.Get()); - - if (version == JNI_ERR) { - StringAppendF(detail, "JNI_ERR returned from JNI_OnLoad in \"%s\"", path.c_str()); - } else if (IsBadJniVersion(version)) { - StringAppendF(detail, "Bad JNI version returned from JNI_OnLoad in \"%s\": %d", - path.c_str(), version); - // It's unwise to call dlclose() here, but we can mark it - // as bad and ensure that future load attempts will fail. - // We don't know how far JNI_OnLoad got, so there could - // be some partially-initialized stuff accessible through - // newly-registered native method calls. We could try to - // unregister them, but that doesn't seem worthwhile. - } else { - was_successful = true; - } - VLOG(jni) << "[Returned " << (was_successful ? "successfully" : "failure") - << " from JNI_OnLoad in \"" << path << "\"]"; - } - - library->SetResult(was_successful); - return was_successful; -} - -void* JavaVMExt::FindCodeForNativeMethod(mirror::ArtMethod* m) { - CHECK(m->IsNative()); - mirror::Class* c = m->GetDeclaringClass(); - // If this is a static method, it could be called before the class has been initialized. - if (m->IsStatic()) { - c = EnsureInitialized(Thread::Current(), c); - if (c == nullptr) { - return nullptr; - } - } else { - CHECK(c->IsInitializing()) << c->GetStatus() << " " << PrettyMethod(m); - } - std::string detail; - void* native_method; - Thread* self = Thread::Current(); - { - MutexLock mu(self, libraries_lock); - native_method = libraries->FindNativeMethod(m, detail); - } - // Throwing can cause libraries_lock to be reacquired. - if (native_method == nullptr) { - ThrowLocation throw_location = self->GetCurrentLocationForThrow(); - self->ThrowNewException(throw_location, "Ljava/lang/UnsatisfiedLinkError;", detail.c_str()); - } - return native_method; -} - -void JavaVMExt::SweepJniWeakGlobals(IsMarkedCallback* callback, void* arg) { - MutexLock mu(Thread::Current(), weak_globals_lock_); - for (mirror::Object** entry : weak_globals_) { - // Since this is called by the GC, we don't need a read barrier. - mirror::Object* obj = *entry; - mirror::Object* new_obj = callback(obj, arg); - if (new_obj == nullptr) { - new_obj = kClearedJniWeakGlobal; - } - *entry = new_obj; - } -} - -void JavaVMExt::VisitRoots(RootCallback* callback, void* arg) { - Thread* self = Thread::Current(); - { - ReaderMutexLock mu(self, globals_lock); - globals.VisitRoots(callback, arg, RootInfo(kRootJNIGlobal)); - } - { - MutexLock mu(self, libraries_lock); - // Libraries contains shared libraries which hold a pointer to a class loader. - libraries->VisitRoots(callback, arg); - } - // The weak_globals table is visited by the GC itself (because it mutates the table). +const JNINativeInterface* GetJniNativeInterface() { + return &gJniNativeInterface; } void RegisterNativeMethods(JNIEnv* env, const char* jni_class_name, const JNINativeMethod* methods, @@ -3450,7 +2749,7 @@ std::ostream& operator<<(std::ostream& os, const jobjectRefType& rhs) { os << "JNIWeakGlobalRefType"; return os; default: - LOG(FATAL) << "jobjectRefType[" << static_cast<int>(rhs) << "]"; - return os; + LOG(::art::FATAL) << "jobjectRefType[" << static_cast<int>(rhs) << "]"; + UNREACHABLE(); } } |