diff options
76 files changed, 2038 insertions, 281 deletions
diff --git a/build/Android.common_build.mk b/build/Android.common_build.mk index 4c82506516..f5a95fa0cf 100644 --- a/build/Android.common_build.mk +++ b/build/Android.common_build.mk @@ -46,6 +46,9 @@ ifeq ($(ART_BUILD_HOST_DEBUG),false) $(info Disabling ART_BUILD_HOST_DEBUG) endif +# Enable the read barrier by default. +ART_USE_READ_BARRIER ?= true + ART_CPP_EXTENSION := .cc ifndef LIBART_IMG_HOST_BASE_ADDRESS diff --git a/build/Android.gtest.mk b/build/Android.gtest.mk index 5bdfbc74eb..d8b780ac35 100644 --- a/build/Android.gtest.mk +++ b/build/Android.gtest.mk @@ -107,6 +107,7 @@ ART_GTEST_proxy_test_DEX_DEPS := Interfaces ART_GTEST_reflection_test_DEX_DEPS := Main NonStaticLeafMethods StaticLeafMethods ART_GTEST_profile_assistant_test_DEX_DEPS := ProfileTestMultiDex ART_GTEST_profile_compilation_info_test_DEX_DEPS := ProfileTestMultiDex +ART_GTEST_runtime_callbacks_test_DEX_DEPS := XandY ART_GTEST_stub_test_DEX_DEPS := AllFields ART_GTEST_transaction_test_DEX_DEPS := Transaction ART_GTEST_type_lookup_table_test_DEX_DEPS := Lookup @@ -120,14 +121,14 @@ ART_GTEST_elf_writer_test_TARGET_DEPS := $(TARGET_CORE_IMAGE_optimizing_no-pic_6 ART_GTEST_dex2oat_environment_tests_HOST_DEPS := \ $(HOST_CORE_IMAGE_optimizing_pic_64) \ $(HOST_CORE_IMAGE_optimizing_pic_32) \ - $(HOST_CORE_IMAGE_optimizing_no-pic_64) \ - $(HOST_CORE_IMAGE_optimizing_no-pic_32) \ + $(HOST_CORE_IMAGE_interpreter_pic_64) \ + $(HOST_CORE_IMAGE_interpreter_pic_32) \ $(HOST_OUT_EXECUTABLES)/patchoatd ART_GTEST_dex2oat_environment_tests_TARGET_DEPS := \ $(TARGET_CORE_IMAGE_optimizing_pic_64) \ $(TARGET_CORE_IMAGE_optimizing_pic_32) \ - $(TARGET_CORE_IMAGE_optimizing_no-pic_64) \ - $(TARGET_CORE_IMAGE_optimizing_no-pic_32) \ + $(TARGET_CORE_IMAGE_interpreter_pic_64) \ + $(TARGET_CORE_IMAGE_interpreter_pic_32) \ $(TARGET_OUT_EXECUTABLES)/patchoatd ART_GTEST_oat_file_assistant_test_HOST_DEPS := \ diff --git a/build/art.go b/build/art.go index e6e0544e4d..84269c3f23 100644 --- a/build/art.go +++ b/build/art.go @@ -58,7 +58,7 @@ func globalFlags(ctx android.BaseContext) ([]string, []string) { asflags = append(asflags, "-DART_HEAP_POISONING=1") } - if envTrue(ctx, "ART_USE_READ_BARRIER") || ctx.AConfig().ArtUseReadBarrier() { + if !envFalse(ctx, "ART_USE_READ_BARRIER") || ctx.AConfig().ArtUseReadBarrier() { // Used to change the read barrier type. Valid values are BAKER, BROOKS, TABLELOOKUP. // The default is BAKER. barrierType := envDefault(ctx, "ART_READ_BARRIER_TYPE", "BAKER") diff --git a/compiler/common_compiler_test.h b/compiler/common_compiler_test.h index f4838c1119..0d45a50053 100644 --- a/compiler/common_compiler_test.h +++ b/compiler/common_compiler_test.h @@ -23,7 +23,7 @@ #include "common_runtime_test.h" #include "compiler.h" -#include "jit/offline_profiling_info.h" +#include "jit/profile_compilation_info.h" #include "oat_file.h" namespace art { diff --git a/compiler/driver/compiler_driver.h b/compiler/driver/compiler_driver.h index 6bfdd4da9c..503fe3adfc 100644 --- a/compiler/driver/compiler_driver.h +++ b/compiler/driver/compiler_driver.h @@ -33,7 +33,7 @@ #include "dex_file.h" #include "dex_file_types.h" #include "driver/compiled_method_storage.h" -#include "jit/offline_profiling_info.h" +#include "jit/profile_compilation_info.h" #include "invoke_type.h" #include "method_reference.h" #include "mirror/class.h" // For mirror::Class::Status. diff --git a/compiler/driver/compiler_driver_test.cc b/compiler/driver/compiler_driver_test.cc index 12684c09c0..1e4ca16844 100644 --- a/compiler/driver/compiler_driver_test.cc +++ b/compiler/driver/compiler_driver_test.cc @@ -32,7 +32,7 @@ #include "mirror/object_array-inl.h" #include "mirror/object-inl.h" #include "handle_scope-inl.h" -#include "jit/offline_profiling_info.h" +#include "jit/profile_compilation_info.h" #include "scoped_thread_state_change-inl.h" namespace art { diff --git a/compiler/verifier_deps_test.cc b/compiler/verifier_deps_test.cc index 4f06a91448..5fc9972d09 100644 --- a/compiler/verifier_deps_test.cc +++ b/compiler/verifier_deps_test.cc @@ -1414,7 +1414,14 @@ TEST_F(VerifierDepsTest, VerifyDeps) { ASSERT_FALSE(decoded_deps.ValidateDependencies(new_class_loader, soa.Self())); } - { + // The two tests below make sure that fiddling with the method kind + // (static, virtual, interface) is detected by `ValidateDependencies`. + + // An interface method lookup can succeed with a virtual method lookup on the same class. + // That's OK, as we only want to make sure there is a method being defined with the right + // flags. Therefore, polluting the interface methods with virtual methods does not have + // to fail verification. + if (resolution_kind != kVirtualMethodResolution) { VerifierDeps decoded_deps(dex_files_, ArrayRef<const uint8_t>(buffer)); VerifierDeps::DexFileDeps* deps = decoded_deps.GetDexFileDeps(*primary_dex_file_); bool found = false; @@ -1433,7 +1440,8 @@ TEST_F(VerifierDepsTest, VerifyDeps) { ASSERT_FALSE(decoded_deps.ValidateDependencies(new_class_loader, soa.Self())); } - { + // See comment above that applies the same way. + if (resolution_kind != kInterfaceMethodResolution) { VerifierDeps decoded_deps(dex_files_, ArrayRef<const uint8_t>(buffer)); VerifierDeps::DexFileDeps* deps = decoded_deps.GetDexFileDeps(*primary_dex_file_); bool found = false; diff --git a/dex2oat/dex2oat.cc b/dex2oat/dex2oat.cc index 3fbdb89a74..e8a92c1914 100644 --- a/dex2oat/dex2oat.cc +++ b/dex2oat/dex2oat.cc @@ -64,7 +64,7 @@ #include "gc/space/space-inl.h" #include "image_writer.h" #include "interpreter/unstarted_runtime.h" -#include "jit/offline_profiling_info.h" +#include "jit/profile_compilation_info.h" #include "leb128.h" #include "linker/buffered_output_stream.h" #include "linker/file_output_stream.h" diff --git a/dex2oat/dex2oat_test.cc b/dex2oat/dex2oat_test.cc index cdb3b9fe2a..e86e560b1a 100644 --- a/dex2oat/dex2oat_test.cc +++ b/dex2oat/dex2oat_test.cc @@ -30,7 +30,7 @@ #include "base/macros.h" #include "dex_file-inl.h" #include "dex2oat_environment_test.h" -#include "jit/offline_profiling_info.h" +#include "jit/profile_compilation_info.h" #include "oat.h" #include "oat_file.h" #include "utils.h" diff --git a/dexlayout/dex_visualize.cc b/dexlayout/dex_visualize.cc index 02274b25a3..75d47e4013 100644 --- a/dexlayout/dex_visualize.cc +++ b/dexlayout/dex_visualize.cc @@ -31,7 +31,7 @@ #include "dex_ir.h" #include "dexlayout.h" -#include "jit/offline_profiling_info.h" +#include "jit/profile_compilation_info.h" namespace art { diff --git a/dexlayout/dexlayout.cc b/dexlayout/dexlayout.cc index cac60900bc..1add6bfede 100644 --- a/dexlayout/dexlayout.cc +++ b/dexlayout/dexlayout.cc @@ -37,7 +37,7 @@ #include "dex_instruction-inl.h" #include "dex_visualize.h" #include "dex_writer.h" -#include "jit/offline_profiling_info.h" +#include "jit/profile_compilation_info.h" #include "mem_map.h" #include "os.h" #include "utils.h" diff --git a/dexlayout/dexlayout_main.cc b/dexlayout/dexlayout_main.cc index 5f8a118bde..ad599aed93 100644 --- a/dexlayout/dexlayout_main.cc +++ b/dexlayout/dexlayout_main.cc @@ -30,7 +30,7 @@ #include <fcntl.h> #include "base/logging.h" -#include "jit/offline_profiling_info.h" +#include "jit/profile_compilation_info.h" #include "runtime.h" #include "mem_map.h" diff --git a/profman/profile_assistant.h b/profman/profile_assistant.h index d3c75b817a..be703abda8 100644 --- a/profman/profile_assistant.h +++ b/profman/profile_assistant.h @@ -21,7 +21,7 @@ #include <vector> #include "base/scoped_flock.h" -#include "jit/offline_profiling_info.h" +#include "jit/profile_compilation_info.h" namespace art { diff --git a/profman/profile_assistant_test.cc b/profman/profile_assistant_test.cc index 776c31a662..2f40fef42e 100644 --- a/profman/profile_assistant_test.cc +++ b/profman/profile_assistant_test.cc @@ -19,7 +19,7 @@ #include "base/unix_file/fd_file.h" #include "common_runtime_test.h" #include "profile_assistant.h" -#include "jit/offline_profiling_info.h" +#include "jit/profile_compilation_info.h" #include "utils.h" namespace art { diff --git a/profman/profman.cc b/profman/profman.cc index e5384078f1..ffebb6a2ea 100644 --- a/profman/profman.cc +++ b/profman/profman.cc @@ -34,7 +34,7 @@ #include "base/time_utils.h" #include "base/unix_file/fd_file.h" #include "dex_file.h" -#include "jit/offline_profiling_info.h" +#include "jit/profile_compilation_info.h" #include "runtime.h" #include "utils.h" #include "zip_archive.h" diff --git a/runtime/Android.bp b/runtime/Android.bp index 86019bf71c..81f174e43b 100644 --- a/runtime/Android.bp +++ b/runtime/Android.bp @@ -112,7 +112,7 @@ cc_defaults { "jit/debugger_interface.cc", "jit/jit.cc", "jit/jit_code_cache.cc", - "jit/offline_profiling_info.cc", + "jit/profile_compilation_info.cc", "jit/profiling_info.cc", "jit/profile_saver.cc", "jni_internal.cc", @@ -184,6 +184,7 @@ cc_defaults { "reference_table.cc", "reflection.cc", "runtime.cc", + "runtime_callbacks.cc", "runtime_options.cc", "signal_catcher.cc", "stack.cc", @@ -563,6 +564,7 @@ art_cc_test { "parsed_options_test.cc", "prebuilt_tools_test.cc", "reference_table_test.cc", + "runtime_callbacks_test.cc", "thread_pool_test.cc", "transaction_test.cc", "type_lookup_table_test.cc", diff --git a/runtime/class_linker.cc b/runtime/class_linker.cc index 49cffed559..14918df4d5 100644 --- a/runtime/class_linker.cc +++ b/runtime/class_linker.cc @@ -65,7 +65,7 @@ #include "interpreter/interpreter.h" #include "jit/jit.h" #include "jit/jit_code_cache.h" -#include "jit/offline_profiling_info.h" +#include "jit/profile_compilation_info.h" #include "jni_internal.h" #include "leb128.h" #include "linear_alloc.h" @@ -96,6 +96,7 @@ #include "object_lock.h" #include "os.h" #include "runtime.h" +#include "runtime_callbacks.h" #include "ScopedLocalRef.h" #include "scoped_thread_state_change-inl.h" #include "thread-inl.h" @@ -2678,6 +2679,11 @@ mirror::Class* ClassLinker::DefineClass(Thread* self, return nullptr; } CHECK(klass->IsLoaded()); + + // At this point the class is loaded. Publish a ClassLoad even. + // Note: this may be a temporary class. It is a listener's responsibility to handle this. + Runtime::Current()->GetRuntimeCallbacks()->ClassLoad(klass); + // Link the class (if necessary) CHECK(!klass->IsResolved()); // TODO: Use fast jobjects? @@ -2718,7 +2724,7 @@ mirror::Class* ClassLinker::DefineClass(Thread* self, * The class has been prepared and resolved but possibly not yet verified * at this point. */ - Dbg::PostClassPrepare(h_new_class.Get()); + Runtime::Current()->GetRuntimeCallbacks()->ClassPrepare(klass, h_new_class); // Notify native debugger of the new class and its layout. jit::Jit::NewTypeLoadedIfUsingJit(h_new_class.Get()); diff --git a/runtime/class_linker.h b/runtime/class_linker.h index 9b98671cb4..8da979b36f 100644 --- a/runtime/class_linker.h +++ b/runtime/class_linker.h @@ -34,6 +34,7 @@ #include "dex_file.h" #include "dex_file_types.h" #include "gc_root.h" +#include "handle.h" #include "jni.h" #include "mirror/class.h" #include "object_callbacks.h" @@ -1194,6 +1195,21 @@ class ClassLinker { DISALLOW_COPY_AND_ASSIGN(ClassLinker); }; +class ClassLoadCallback { + public: + virtual ~ClassLoadCallback() {} + + // A class has been loaded. + // Note: the class may be temporary, in which case a following ClassPrepare event will be a + // different object. It is the listener's responsibility to handle this. + virtual void ClassLoad(Handle<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) = 0; + + // A class has been prepared, i.e., resolved. As the ClassLoad event might have been for a + // temporary class, provide both the former and the current class. + virtual void ClassPrepare(Handle<mirror::Class> temp_klass, + Handle<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) = 0; +}; + } // namespace art #endif // ART_RUNTIME_CLASS_LINKER_H_ diff --git a/runtime/common_runtime_test.cc b/runtime/common_runtime_test.cc index 743fcc87eb..fc82264b6a 100644 --- a/runtime/common_runtime_test.cc +++ b/runtime/common_runtime_test.cc @@ -133,7 +133,9 @@ void ScratchFile::Unlink() { static bool unstarted_initialized_ = false; -CommonRuntimeTestImpl::CommonRuntimeTestImpl() {} +CommonRuntimeTestImpl::CommonRuntimeTestImpl() + : class_linker_(nullptr), java_lang_dex_file_(nullptr) { +} CommonRuntimeTestImpl::~CommonRuntimeTestImpl() { // Ensure the dex files are cleaned up before the runtime. @@ -425,7 +427,9 @@ void CommonRuntimeTestImpl::TearDown() { TearDownAndroidData(android_data_, true); dalvik_cache_.clear(); - Runtime::Current()->GetHeap()->VerifyHeap(); // Check for heap corruption after the test + if (runtime_ != nullptr) { + runtime_->GetHeap()->VerifyHeap(); // Check for heap corruption after the test + } } static std::string GetDexFileName(const std::string& jar_prefix, bool host) { diff --git a/runtime/debugger.cc b/runtime/debugger.cc index 006476bafc..22a31635a6 100644 --- a/runtime/debugger.cc +++ b/runtime/debugger.cc @@ -320,6 +320,9 @@ size_t Dbg::field_write_event_ref_count_ = 0; size_t Dbg::exception_catch_event_ref_count_ = 0; uint32_t Dbg::instrumentation_events_ = 0; +Dbg::DbgThreadLifecycleCallback Dbg::thread_lifecycle_callback_; +Dbg::DbgClassLoadCallback Dbg::class_load_callback_; + // Breakpoints. static std::vector<Breakpoint> gBreakpoints GUARDED_BY(Locks::breakpoint_lock_); @@ -5135,4 +5138,20 @@ void Dbg::VisitRoots(RootVisitor* visitor) { } } +void Dbg::DbgThreadLifecycleCallback::ThreadStart(Thread* self) { + Dbg::PostThreadStart(self); +} + +void Dbg::DbgThreadLifecycleCallback::ThreadDeath(Thread* self) { + Dbg::PostThreadDeath(self); +} + +void Dbg::DbgClassLoadCallback::ClassLoad(Handle<mirror::Class> klass ATTRIBUTE_UNUSED) { + // Ignore ClassLoad; +} +void Dbg::DbgClassLoadCallback::ClassPrepare(Handle<mirror::Class> temp_klass ATTRIBUTE_UNUSED, + Handle<mirror::Class> klass) { + Dbg::PostClassPrepare(klass.Get()); +} + } // namespace art diff --git a/runtime/debugger.h b/runtime/debugger.h index 3b4a5e16b0..a7fd1605df 100644 --- a/runtime/debugger.h +++ b/runtime/debugger.h @@ -28,6 +28,8 @@ #include <vector> #include "gc_root.h" +#include "class_linker.h" +#include "handle.h" #include "jdwp/jdwp.h" #include "jni.h" #include "jvalue.h" @@ -502,12 +504,6 @@ class Dbg { REQUIRES_SHARED(Locks::mutator_lock_); static void PostException(mirror::Throwable* exception) REQUIRES_SHARED(Locks::mutator_lock_); - static void PostThreadStart(Thread* t) - REQUIRES_SHARED(Locks::mutator_lock_); - static void PostThreadDeath(Thread* t) - REQUIRES_SHARED(Locks::mutator_lock_); - static void PostClassPrepare(mirror::Class* c) - REQUIRES_SHARED(Locks::mutator_lock_); static void UpdateDebugger(Thread* thread, mirror::Object* this_object, ArtMethod* method, uint32_t new_dex_pc, @@ -707,6 +703,13 @@ class Dbg { return instrumentation_events_; } + static ThreadLifecycleCallback* GetThreadLifecycleCallback() { + return &thread_lifecycle_callback_; + } + static ClassLoadCallback* GetClassLoadCallback() { + return &class_load_callback_; + } + private: static void ExecuteMethodWithoutPendingException(ScopedObjectAccess& soa, DebugInvokeReq* pReq) REQUIRES_SHARED(Locks::mutator_lock_); @@ -725,9 +728,17 @@ class Dbg { REQUIRES(!Locks::thread_list_lock_) REQUIRES_SHARED(Locks::mutator_lock_); static void DdmBroadcast(bool connect) REQUIRES_SHARED(Locks::mutator_lock_); + + static void PostThreadStart(Thread* t) + REQUIRES_SHARED(Locks::mutator_lock_); + static void PostThreadDeath(Thread* t) + REQUIRES_SHARED(Locks::mutator_lock_); static void PostThreadStartOrStop(Thread*, uint32_t) REQUIRES_SHARED(Locks::mutator_lock_); + static void PostClassPrepare(mirror::Class* c) + REQUIRES_SHARED(Locks::mutator_lock_); + static void PostLocationEvent(ArtMethod* method, int pcOffset, mirror::Object* thisPtr, int eventFlags, const JValue* return_value) @@ -789,6 +800,22 @@ class Dbg { static size_t exception_catch_event_ref_count_ GUARDED_BY(Locks::deoptimization_lock_); static uint32_t instrumentation_events_ GUARDED_BY(Locks::mutator_lock_); + class DbgThreadLifecycleCallback : public ThreadLifecycleCallback { + public: + void ThreadStart(Thread* self) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_); + void ThreadDeath(Thread* self) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_); + }; + + class DbgClassLoadCallback : public ClassLoadCallback { + public: + void ClassLoad(Handle<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_); + void ClassPrepare(Handle<mirror::Class> temp_klass, + Handle<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_); + }; + + static DbgThreadLifecycleCallback thread_lifecycle_callback_; + static DbgClassLoadCallback class_load_callback_; + DISALLOW_COPY_AND_ASSIGN(Dbg); }; diff --git a/runtime/dex2oat_environment_test.h b/runtime/dex2oat_environment_test.h index b0c4597d73..7ae9f03c83 100644 --- a/runtime/dex2oat_environment_test.h +++ b/runtime/dex2oat_environment_test.h @@ -160,7 +160,7 @@ class Dex2oatEnvironmentTest : public CommonRuntimeTest { // image at GetImageLocation(). This is used for testing mismatched // image checksums in the oat_file_assistant_tests. std::string GetImageLocation2() const { - return GetImageDirectory() + "/core-npic.art"; + return GetImageDirectory() + "/core-interpreter.art"; } std::string GetDexSrc1() const { diff --git a/runtime/gc/space/large_object_space.cc b/runtime/gc/space/large_object_space.cc index e71a397039..4c6b5bfadd 100644 --- a/runtime/gc/space/large_object_space.cc +++ b/runtime/gc/space/large_object_space.cc @@ -141,16 +141,6 @@ mirror::Object* LargeObjectMapSpace::Alloc(Thread* self, size_t num_bytes, return nullptr; } mirror::Object* const obj = reinterpret_cast<mirror::Object*>(mem_map->Begin()); - if (kIsDebugBuild) { - ReaderMutexLock mu2(Thread::Current(), *Locks::heap_bitmap_lock_); - auto* heap = Runtime::Current()->GetHeap(); - auto* live_bitmap = heap->GetLiveBitmap(); - auto* space_bitmap = live_bitmap->GetContinuousSpaceBitmap(obj); - CHECK(space_bitmap == nullptr) << obj << " overlaps with bitmap " << *space_bitmap; - auto* obj_end = reinterpret_cast<mirror::Object*>(mem_map->End()); - space_bitmap = live_bitmap->GetContinuousSpaceBitmap(obj_end - 1); - CHECK(space_bitmap == nullptr) << obj_end << " overlaps with bitmap " << *space_bitmap; - } MutexLock mu(self, lock_); large_objects_.Put(obj, LargeObject {mem_map, false /* not zygote */}); const size_t allocation_size = mem_map->BaseSize(); diff --git a/runtime/interpreter/interpreter_common.cc b/runtime/interpreter/interpreter_common.cc index 76777d938b..28bcb97105 100644 --- a/runtime/interpreter/interpreter_common.cc +++ b/runtime/interpreter/interpreter_common.cc @@ -596,7 +596,7 @@ bool DoInvokePolymorphic(Thread* self, // Get the register arguments for the invoke. inst->GetVarArgs(args, inst_data); // Drop the first register which is the method handle performing the invoke. - memcpy(args, args + 1, sizeof(args[0]) * (Instruction::kMaxVarArgRegs - 1)); + memmove(args, args + 1, sizeof(args[0]) * (Instruction::kMaxVarArgRegs - 1)); args[Instruction::kMaxVarArgRegs - 1] = 0; return DoInvokePolymorphic<is_range, do_access_check>(self, invoke_method, diff --git a/runtime/jit/jit.cc b/runtime/jit/jit.cc index b7125a8a43..2bb8819cb3 100644 --- a/runtime/jit/jit.cc +++ b/runtime/jit/jit.cc @@ -26,7 +26,7 @@ #include "jit_code_cache.h" #include "oat_file_manager.h" #include "oat_quick_method_header.h" -#include "offline_profiling_info.h" +#include "profile_compilation_info.h" #include "profile_saver.h" #include "runtime.h" #include "runtime_options.h" diff --git a/runtime/jit/jit.h b/runtime/jit/jit.h index 05c390590b..4112142a4f 100644 --- a/runtime/jit/jit.h +++ b/runtime/jit/jit.h @@ -25,7 +25,7 @@ #include "jit/profile_saver_options.h" #include "obj_ptr.h" #include "object_callbacks.h" -#include "offline_profiling_info.h" +#include "profile_compilation_info.h" #include "thread_pool.h" namespace art { diff --git a/runtime/jit/offline_profiling_info.cc b/runtime/jit/profile_compilation_info.cc index 6f2a8c673f..1405c40096 100644 --- a/runtime/jit/offline_profiling_info.cc +++ b/runtime/jit/profile_compilation_info.cc @@ -14,7 +14,7 @@ * limitations under the License. */ -#include "offline_profiling_info.h" +#include "profile_compilation_info.h" #include "errno.h" #include <limits.h> diff --git a/runtime/jit/offline_profiling_info.h b/runtime/jit/profile_compilation_info.h index 53d0eea932..f8061bcfd8 100644 --- a/runtime/jit/offline_profiling_info.h +++ b/runtime/jit/profile_compilation_info.h @@ -14,8 +14,8 @@ * limitations under the License. */ -#ifndef ART_RUNTIME_JIT_OFFLINE_PROFILING_INFO_H_ -#define ART_RUNTIME_JIT_OFFLINE_PROFILING_INFO_H_ +#ifndef ART_RUNTIME_JIT_PROFILE_COMPILATION_INFO_H_ +#define ART_RUNTIME_JIT_PROFILE_COMPILATION_INFO_H_ #include <set> #include <vector> @@ -29,7 +29,6 @@ namespace art { -// TODO: rename file. /** * Profile information in a format suitable to be queried by the compiler and * performing profile guided compilation. @@ -187,4 +186,4 @@ class ProfileCompilationInfo { } // namespace art -#endif // ART_RUNTIME_JIT_OFFLINE_PROFILING_INFO_H_ +#endif // ART_RUNTIME_JIT_PROFILE_COMPILATION_INFO_H_ diff --git a/runtime/jit/profile_compilation_info_test.cc b/runtime/jit/profile_compilation_info_test.cc index 1dd1e36e74..835a5f3495 100644 --- a/runtime/jit/profile_compilation_info_test.cc +++ b/runtime/jit/profile_compilation_info_test.cc @@ -25,7 +25,7 @@ #include "mirror/class-inl.h" #include "mirror/class_loader.h" #include "handle_scope-inl.h" -#include "jit/offline_profiling_info.h" +#include "jit/profile_compilation_info.h" #include "scoped_thread_state_change-inl.h" namespace art { diff --git a/runtime/jit/profile_saver.h b/runtime/jit/profile_saver.h index 59e2c94790..9c5e41fd13 100644 --- a/runtime/jit/profile_saver.h +++ b/runtime/jit/profile_saver.h @@ -19,7 +19,7 @@ #include "base/mutex.h" #include "jit_code_cache.h" -#include "offline_profiling_info.h" +#include "profile_compilation_info.h" #include "profile_saver_options.h" #include "safe_map.h" diff --git a/runtime/oat.h b/runtime/oat.h index 3b3ab5aa09..953b445e4e 100644 --- a/runtime/oat.h +++ b/runtime/oat.h @@ -32,7 +32,7 @@ class InstructionSetFeatures; class PACKED(4) OatHeader { public: static constexpr uint8_t kOatMagic[] = { 'o', 'a', 't', '\n' }; - static constexpr uint8_t kOatVersion[] = { '1', '0', '1', '\0' }; // Array entrypoints change + static constexpr uint8_t kOatVersion[] = { '1', '0', '2', '\0' }; // Enabling CC static constexpr const char* kImageLocationKey = "image-location"; static constexpr const char* kDex2OatCmdLineKey = "dex2oat-cmdline"; diff --git a/runtime/oat_file_assistant_test.cc b/runtime/oat_file_assistant_test.cc index afa804c08c..84eacde8b7 100644 --- a/runtime/oat_file_assistant_test.cc +++ b/runtime/oat_file_assistant_test.cc @@ -152,15 +152,17 @@ class OatFileAssistantTest : public Dex2oatEnvironmentTest { } } - if (CompilerFilter::IsBytecodeCompilationEnabled(filter)) { - if (relocate) { - EXPECT_EQ(reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin()), - oat_header.GetImageFileLocationOatDataBegin()); - EXPECT_EQ(image_header->GetPatchDelta(), oat_header.GetImagePatchDelta()); - } else { - EXPECT_NE(reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin()), - oat_header.GetImageFileLocationOatDataBegin()); - EXPECT_NE(image_header->GetPatchDelta(), oat_header.GetImagePatchDelta()); + if (!with_alternate_image) { + if (CompilerFilter::IsBytecodeCompilationEnabled(filter)) { + if (relocate) { + EXPECT_EQ(reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin()), + oat_header.GetImageFileLocationOatDataBegin()); + EXPECT_EQ(image_header->GetPatchDelta(), oat_header.GetImagePatchDelta()); + } else { + EXPECT_NE(reinterpret_cast<uintptr_t>(image_header->GetOatDataBegin()), + oat_header.GetImageFileLocationOatDataBegin()); + EXPECT_NE(image_header->GetPatchDelta(), oat_header.GetImagePatchDelta()); + } } } } diff --git a/runtime/openjdkjvmti/OpenjdkJvmTi.cc b/runtime/openjdkjvmti/OpenjdkJvmTi.cc index 90467db8f6..e9b7cf5b10 100644 --- a/runtime/openjdkjvmti/OpenjdkJvmTi.cc +++ b/runtime/openjdkjvmti/OpenjdkJvmTi.cc @@ -194,7 +194,7 @@ class JvmtiFunctions { jvmtiStartFunction proc, const void* arg, jint priority) { - return ERR(NOT_IMPLEMENTED); + return ThreadUtil::RunAgentThread(env, thread, proc, arg, priority); } static jvmtiError SetThreadLocalStorage(jvmtiEnv* env, jthread thread, const void* data) { @@ -631,7 +631,17 @@ class JvmtiFunctions { } static jvmtiError RetransformClasses(jvmtiEnv* env, jint class_count, const jclass* classes) { - return ERR(NOT_IMPLEMENTED); + std::string error_msg; + jvmtiError res = Transformer::RetransformClasses(ArtJvmTiEnv::AsArtJvmTiEnv(env), + art::Runtime::Current(), + art::Thread::Current(), + class_count, + classes, + &error_msg); + if (res != OK) { + LOG(WARNING) << "FAILURE TO RETRANFORM " << error_msg; + } + return res; } static jvmtiError RedefineClasses(jvmtiEnv* env, @@ -1255,78 +1265,6 @@ class JvmtiFunctions { *format_ptr = jvmtiJlocationFormat::JVMTI_JLOCATION_JVMBCI; return ERR(NONE); } - - // TODO Remove this once events are working. - static jvmtiError RetransformClassWithHook(jvmtiEnv* env, - jclass klass, - jvmtiEventClassFileLoadHook hook) { - std::vector<jclass> classes; - classes.push_back(klass); - return RetransformClassesWithHook(reinterpret_cast<ArtJvmTiEnv*>(env), classes, hook); - } - - // TODO This will be called by the event handler for the art::ti Event Load Event - static jvmtiError RetransformClassesWithHook(ArtJvmTiEnv* env, - const std::vector<jclass>& classes, - jvmtiEventClassFileLoadHook hook) { - if (!IsValidEnv(env)) { - return ERR(INVALID_ENVIRONMENT); - } - jvmtiError res = OK; - std::string error; - for (jclass klass : classes) { - JNIEnv* jni_env = nullptr; - jobject loader = nullptr; - std::string name; - jobject protection_domain = nullptr; - jint data_len = 0; - unsigned char* dex_data = nullptr; - jvmtiError ret = OK; - std::string location; - if ((ret = GetTransformationData(env, - klass, - /*out*/&location, - /*out*/&jni_env, - /*out*/&loader, - /*out*/&name, - /*out*/&protection_domain, - /*out*/&data_len, - /*out*/&dex_data)) != OK) { - // TODO Do something more here? Maybe give log statements? - return ret; - } - jint new_data_len = 0; - unsigned char* new_dex_data = nullptr; - hook(env, - jni_env, - klass, - loader, - name.c_str(), - protection_domain, - data_len, - dex_data, - /*out*/&new_data_len, - /*out*/&new_dex_data); - // Check if anything actually changed. - if ((new_data_len != 0 || new_dex_data != nullptr) && new_dex_data != dex_data) { - jvmtiClassDefinition def = { klass, new_data_len, new_dex_data }; - res = Redefiner::RedefineClasses(env, - art::Runtime::Current(), - art::Thread::Current(), - 1, - &def, - &error); - env->Deallocate(new_dex_data); - } - // Deallocate the old dex data. - env->Deallocate(dex_data); - if (res != OK) { - LOG(ERROR) << "FAILURE TO REDEFINE " << error; - return res; - } - } - return OK; - } }; static bool IsJvmtiVersion(jint version) { @@ -1369,10 +1307,7 @@ extern "C" bool ArtPlugin_Initialize() { // The actual struct holding all of the entrypoints into the jvmti interface. const jvmtiInterface_1 gJvmtiInterface = { - // SPECIAL FUNCTION: RetransformClassWithHook Is normally reserved1 - // TODO Remove once we have events working. - reinterpret_cast<void*>(JvmtiFunctions::RetransformClassWithHook), - // nullptr, // reserved1 + nullptr, // reserved1 JvmtiFunctions::SetEventNotificationMode, nullptr, // reserved3 JvmtiFunctions::GetAllThreads, diff --git a/runtime/openjdkjvmti/art_jvmti.h b/runtime/openjdkjvmti/art_jvmti.h index 5eadc5a8e0..1c84d4d0ce 100644 --- a/runtime/openjdkjvmti/art_jvmti.h +++ b/runtime/openjdkjvmti/art_jvmti.h @@ -47,6 +47,7 @@ namespace openjdkjvmti { extern const jvmtiInterface_1 gJvmtiInterface; +extern EventHandler gEventHandler; // A structure that is a jvmtiEnv with additional information for the runtime. struct ArtJvmTiEnv : public jvmtiEnv { @@ -124,6 +125,29 @@ static inline jvmtiError CopyString(jvmtiEnv* env, const char* src, unsigned cha return ret; } +struct ArtClassDefinition { + jclass klass; + jobject loader; + std::string name; + jobject protection_domain; + jint dex_len; + JvmtiUniquePtr dex_data; + bool modified; + + ArtClassDefinition() = default; + ArtClassDefinition(ArtClassDefinition&& o) = default; + + void SetNewDexData(ArtJvmTiEnv* env, jint new_dex_len, unsigned char* new_dex_data) { + if (new_dex_data == nullptr) { + return; + } else if (new_dex_data != dex_data.get() || new_dex_len != dex_len) { + modified = true; + dex_len = new_dex_len; + dex_data = MakeJvmtiUniquePtr(env, new_dex_data); + } + } +}; + const jvmtiCapabilities kPotentialCapabilities = { .can_tag_objects = 1, .can_generate_field_modification_events = 0, @@ -134,7 +158,7 @@ const jvmtiCapabilities kPotentialCapabilities = { .can_get_current_contended_monitor = 0, .can_get_monitor_info = 0, .can_pop_frame = 0, - .can_redefine_classes = 0, + .can_redefine_classes = 1, .can_signal_thread = 0, .can_get_source_file_name = 0, .can_get_line_numbers = 0, @@ -162,7 +186,7 @@ const jvmtiCapabilities kPotentialCapabilities = { .can_get_owned_monitor_stack_depth_info = 0, .can_get_constant_pool = 0, .can_set_native_method_prefix = 0, - .can_retransform_classes = 0, + .can_retransform_classes = 1, .can_retransform_any_class = 0, .can_generate_resource_exhaustion_heap_events = 0, .can_generate_resource_exhaustion_threads_events = 0, diff --git a/runtime/openjdkjvmti/events-inl.h b/runtime/openjdkjvmti/events-inl.h index 1e07bc6b7b..21ec731ba5 100644 --- a/runtime/openjdkjvmti/events-inl.h +++ b/runtime/openjdkjvmti/events-inl.h @@ -115,9 +115,95 @@ ALWAYS_INLINE static inline FnType* GetCallback(ArtJvmTiEnv* env, ArtJvmtiEvent } template <typename ...Args> +inline void EventHandler::DispatchClassFileLoadHookEvent(art::Thread*, + ArtJvmtiEvent event, + Args... args ATTRIBUTE_UNUSED) const { + CHECK(event == ArtJvmtiEvent::kClassFileLoadHookRetransformable || + event == ArtJvmtiEvent::kClassFileLoadHookNonRetransformable); + LOG(FATAL) << "Incorrect arguments to ClassFileLoadHook!"; +} + +// TODO Locking of some type! +template <> +inline void EventHandler::DispatchClassFileLoadHookEvent(art::Thread* thread, + ArtJvmtiEvent event, + JNIEnv* jnienv, + jclass class_being_redefined, + jobject loader, + const char* name, + jobject protection_domain, + jint class_data_len, + const unsigned char* class_data, + jint* new_class_data_len, + unsigned char** new_class_data) const { + CHECK(event == ArtJvmtiEvent::kClassFileLoadHookRetransformable || + event == ArtJvmtiEvent::kClassFileLoadHookNonRetransformable); + using FnType = void(jvmtiEnv* /* jvmti_env */, + JNIEnv* /* jnienv */, + jclass /* class_being_redefined */, + jobject /* loader */, + const char* /* name */, + jobject /* protection_domain */, + jint /* class_data_len */, + const unsigned char* /* class_data */, + jint* /* new_class_data_len */, + unsigned char** /* new_class_data */); + jint current_len = class_data_len; + unsigned char* current_class_data = const_cast<unsigned char*>(class_data); + ArtJvmTiEnv* last_env = nullptr; + for (ArtJvmTiEnv* env : envs) { + if (ShouldDispatch(event, env, thread)) { + jint new_len; + unsigned char* new_data; + FnType* callback = GetCallback<FnType>(env, event); + callback(env, + jnienv, + class_being_redefined, + loader, + name, + protection_domain, + current_len, + current_class_data, + &new_len, + &new_data); + if (new_data != nullptr && new_data != current_class_data) { + // Destroy the data the last transformer made. We skip this if the previous state was the + // initial one since we don't know here which jvmtiEnv allocated it. + // NB Currently this doesn't matter since all allocations just go to malloc but in the + // future we might have jvmtiEnv's keep track of their allocations for leak-checking. + if (last_env != nullptr) { + last_env->Deallocate(current_class_data); + } + last_env = env; + current_class_data = new_data; + current_len = new_len; + } + } + } + if (last_env != nullptr) { + *new_class_data_len = current_len; + *new_class_data = current_class_data; + } +} + +template <typename ...Args> inline void EventHandler::DispatchEvent(art::Thread* thread, ArtJvmtiEvent event, Args... args) const { + switch (event) { + case ArtJvmtiEvent::kClassFileLoadHookRetransformable: + case ArtJvmtiEvent::kClassFileLoadHookNonRetransformable: + return DispatchClassFileLoadHookEvent(thread, event, args...); + default: + return GenericDispatchEvent(thread, event, args...); + } +} + +// TODO Locking of some type! +template <typename ...Args> +inline void EventHandler::GenericDispatchEvent(art::Thread* thread, + ArtJvmtiEvent event, + Args... args) const { using FnType = void(jvmtiEnv*, Args...); for (ArtJvmTiEnv* env : envs) { if (ShouldDispatch(event, env, thread)) { diff --git a/runtime/openjdkjvmti/events.h b/runtime/openjdkjvmti/events.h index 7990141562..08a87659c7 100644 --- a/runtime/openjdkjvmti/events.h +++ b/runtime/openjdkjvmti/events.h @@ -178,6 +178,15 @@ class EventHandler { ALWAYS_INLINE inline void RecalculateGlobalEventMask(ArtJvmtiEvent event); + template <typename ...Args> + ALWAYS_INLINE inline void GenericDispatchEvent(art::Thread* thread, + ArtJvmtiEvent event, + Args... args) const; + template <typename ...Args> + ALWAYS_INLINE inline void DispatchClassFileLoadHookEvent(art::Thread* thread, + ArtJvmtiEvent event, + Args... args) const; + void HandleEventType(ArtJvmtiEvent event, bool enable); // List of all JvmTiEnv objects that have been created, in their creation order. diff --git a/runtime/openjdkjvmti/ti_redefine.cc b/runtime/openjdkjvmti/ti_redefine.cc index 6af51c4c6c..2db8a40ad4 100644 --- a/runtime/openjdkjvmti/ti_redefine.cc +++ b/runtime/openjdkjvmti/ti_redefine.cc @@ -242,14 +242,12 @@ Redefiner::ClassRedefinition::~ClassRedefinition() { } } -// TODO This should handle doing multiple classes at once so we need to do less cleanup when things -// go wrong. jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env, art::Runtime* runtime, art::Thread* self, jint class_count, const jvmtiClassDefinition* definitions, - std::string* error_msg) { + /*out*/std::string* error_msg) { if (env == nullptr) { *error_msg = "env was null!"; return ERR(INVALID_ENVIRONMENT); @@ -263,46 +261,95 @@ jvmtiError Redefiner::RedefineClasses(ArtJvmTiEnv* env, *error_msg = "null definitions!"; return ERR(NULL_POINTER); } + std::vector<ArtClassDefinition> def_vector; + def_vector.reserve(class_count); + for (jint i = 0; i < class_count; i++) { + // We make a copy of the class_bytes to pass into the retransformation. + // This makes cleanup easier (since we unambiguously own the bytes) and also is useful since we + // will need to keep the original bytes around unaltered for subsequent RetransformClasses calls + // to get the passed in bytes. + // TODO Implement saving the original bytes. + unsigned char* class_bytes_copy = nullptr; + jvmtiError res = env->Allocate(definitions[i].class_byte_count, &class_bytes_copy); + if (res != OK) { + return res; + } + memcpy(class_bytes_copy, definitions[i].class_bytes, definitions[i].class_byte_count); + + ArtClassDefinition def; + def.dex_len = definitions[i].class_byte_count; + def.dex_data = MakeJvmtiUniquePtr(env, class_bytes_copy); + // We are definitely modified. + def.modified = true; + res = Transformer::FillInTransformationData(env, definitions[i].klass, &def); + if (res != OK) { + return res; + } + def_vector.push_back(std::move(def)); + } + // Call all the transformation events. + jvmtiError res = Transformer::RetransformClassesDirect(env, + self, + &def_vector); + if (res != OK) { + // Something went wrong with transformation! + return res; + } + return RedefineClassesDirect(env, runtime, self, def_vector, error_msg); +} + +jvmtiError Redefiner::RedefineClassesDirect(ArtJvmTiEnv* env, + art::Runtime* runtime, + art::Thread* self, + const std::vector<ArtClassDefinition>& definitions, + std::string* error_msg) { + DCHECK(env != nullptr); + if (definitions.size() == 0) { + // We don't actually need to do anything. Just return OK. + return OK; + } // Stop JIT for the duration of this redefine since the JIT might concurrently compile a method we // are going to redefine. art::jit::ScopedJitSuspend suspend_jit; // Get shared mutator lock so we can lock all the classes. art::ScopedObjectAccess soa(self); std::vector<Redefiner::ClassRedefinition> redefinitions; - redefinitions.reserve(class_count); + redefinitions.reserve(definitions.size()); Redefiner r(runtime, self, error_msg); - for (jint i = 0; i < class_count; i++) { - jvmtiError res = r.AddRedefinition(env, definitions[i]); - if (res != OK) { - return res; + for (const ArtClassDefinition& def : definitions) { + // Only try to transform classes that have been modified. + if (def.modified) { + jvmtiError res = r.AddRedefinition(env, def); + if (res != OK) { + return res; + } } } return r.Run(); } -jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const jvmtiClassDefinition& def) { +jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) { std::string original_dex_location; jvmtiError ret = OK; if ((ret = GetClassLocation(env, def.klass, &original_dex_location))) { *error_msg_ = "Unable to get original dex file location!"; return ret; } - std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location, - def.class_byte_count, - def.class_bytes, - error_msg_)); - std::ostringstream os; char* generic_ptr_unused = nullptr; char* signature_ptr = nullptr; - if (env->GetClassSignature(def.klass, &signature_ptr, &generic_ptr_unused) != OK) { - *error_msg_ = "A jclass passed in does not seem to be valid"; - return ERR(INVALID_CLASS); + if ((ret = env->GetClassSignature(def.klass, &signature_ptr, &generic_ptr_unused)) != OK) { + *error_msg_ = "Unable to get class signature!"; + return ret; } - // These will make sure we deallocate the signature. - JvmtiUniquePtr sig_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr)); JvmtiUniquePtr generic_unique_ptr(MakeJvmtiUniquePtr(env, generic_ptr_unused)); + JvmtiUniquePtr signature_unique_ptr(MakeJvmtiUniquePtr(env, signature_ptr)); + std::unique_ptr<art::MemMap> map(MoveDataToMemMap(original_dex_location, + def.dex_len, + def.dex_data.get(), + error_msg_)); + std::ostringstream os; if (map.get() == nullptr) { - os << "Failed to create anonymous mmap for modified dex file of class " << signature_ptr + os << "Failed to create anonymous mmap for modified dex file of class " << def.name << "in dex file " << original_dex_location << " because: " << *error_msg_; *error_msg_ = os.str(); return ERR(OUT_OF_MEMORY); @@ -319,7 +366,7 @@ jvmtiError Redefiner::AddRedefinition(ArtJvmTiEnv* env, const jvmtiClassDefiniti /*verify_checksum*/true, error_msg_)); if (dex_file.get() == nullptr) { - os << "Unable to load modified dex file for " << signature_ptr << ": " << *error_msg_; + os << "Unable to load modified dex file for " << def.name << ": " << *error_msg_; *error_msg_ = os.str(); return ERR(INVALID_CLASS_FORMAT); } @@ -989,17 +1036,16 @@ void Redefiner::ClassRedefinition::UpdateFields(art::ObjPtr<art::mirror::Class> // Performs updates to class that will allow us to verify it. void Redefiner::ClassRedefinition::UpdateClass(art::ObjPtr<art::mirror::Class> mclass, art::ObjPtr<art::mirror::DexCache> new_dex_cache) { - const art::DexFile::ClassDef* class_def = art::OatFile::OatDexFile::FindClassDef( - *dex_file_, class_sig_.c_str(), art::ComputeModifiedUtf8Hash(class_sig_.c_str())); - DCHECK(class_def != nullptr); - UpdateMethods(mclass, new_dex_cache, *class_def); + DCHECK_EQ(dex_file_->NumClassDefs(), 1u); + const art::DexFile::ClassDef& class_def = dex_file_->GetClassDef(0); + UpdateMethods(mclass, new_dex_cache, class_def); UpdateFields(mclass); // Update the class fields. // Need to update class last since the ArtMethod gets its DexFile from the class (which is needed // to call GetReturnTypeDescriptor and GetParameterTypeList above). mclass->SetDexCache(new_dex_cache.Ptr()); - mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(*class_def)); + mclass->SetDexClassDefIndex(dex_file_->GetIndexForClassDef(class_def)); mclass->SetDexTypeIndex(dex_file_->GetIndexForTypeId(*dex_file_->FindTypeId(class_sig_.c_str()))); } diff --git a/runtime/openjdkjvmti/ti_redefine.h b/runtime/openjdkjvmti/ti_redefine.h index 8626bc54d5..f8d51ad124 100644 --- a/runtime/openjdkjvmti/ti_redefine.h +++ b/runtime/openjdkjvmti/ti_redefine.h @@ -72,13 +72,25 @@ class Redefiner { public: // Redefine the given classes with the given dex data. Note this function does not take ownership // of the dex_data pointers. It is not used after this call however and may be freed if desired. + // The caller is responsible for freeing it. The runtime makes its own copy of the data. This + // function does not call the transformation events. + // TODO Check modified flag of the definitions. + static jvmtiError RedefineClassesDirect(ArtJvmTiEnv* env, + art::Runtime* runtime, + art::Thread* self, + const std::vector<ArtClassDefinition>& definitions, + /*out*/std::string* error_msg); + + // Redefine the given classes with the given dex data. Note this function does not take ownership + // of the dex_data pointers. It is not used after this call however and may be freed if desired. // The caller is responsible for freeing it. The runtime makes its own copy of the data. + // TODO This function should call the transformation events. static jvmtiError RedefineClasses(ArtJvmTiEnv* env, art::Runtime* runtime, art::Thread* self, jint class_count, const jvmtiClassDefinition* definitions, - std::string* error_msg); + /*out*/std::string* error_msg); static jvmtiError IsModifiableClass(jvmtiEnv* env, jclass klass, jboolean* is_redefinable); @@ -209,7 +221,7 @@ class Redefiner { redefinitions_(), error_msg_(error_msg) { } - jvmtiError AddRedefinition(ArtJvmTiEnv* env, const jvmtiClassDefinition& def) + jvmtiError AddRedefinition(ArtJvmTiEnv* env, const ArtClassDefinition& def) REQUIRES_SHARED(art::Locks::mutator_lock_); static jvmtiError GetClassRedefinitionError(art::Handle<art::mirror::Class> klass, diff --git a/runtime/openjdkjvmti/ti_thread.cc b/runtime/openjdkjvmti/ti_thread.cc index 2bcdd8cda1..970cc24f12 100644 --- a/runtime/openjdkjvmti/ti_thread.cc +++ b/runtime/openjdkjvmti/ti_thread.cc @@ -443,4 +443,80 @@ jvmtiError ThreadUtil::GetThreadLocalStorage(jvmtiEnv* env ATTRIBUTE_UNUSED, return ERR(NONE); } +struct AgentData { + const void* arg; + jvmtiStartFunction proc; + jthread thread; + JavaVM* java_vm; + jvmtiEnv* jvmti_env; + jint priority; +}; + +static void* AgentCallback(void* arg) { + std::unique_ptr<AgentData> data(reinterpret_cast<AgentData*>(arg)); + CHECK(data->thread != nullptr); + + // We already have a peer. So call our special Attach function. + art::Thread* self = art::Thread::Attach("JVMTI Agent thread", true, data->thread); + CHECK(self != nullptr); + // The name in Attach() is only for logging. Set the thread name. This is important so + // that the thread is no longer seen as starting up. + { + art::ScopedObjectAccess soa(self); + self->SetThreadName("JVMTI Agent thread"); + } + + // Release the peer. + JNIEnv* env = self->GetJniEnv(); + env->DeleteGlobalRef(data->thread); + data->thread = nullptr; + + // Run the agent code. + data->proc(data->jvmti_env, env, const_cast<void*>(data->arg)); + + // Detach the thread. + int detach_result = data->java_vm->DetachCurrentThread(); + CHECK_EQ(detach_result, 0); + + return nullptr; +} + +jvmtiError ThreadUtil::RunAgentThread(jvmtiEnv* jvmti_env, + jthread thread, + jvmtiStartFunction proc, + const void* arg, + jint priority) { + if (priority < JVMTI_THREAD_MIN_PRIORITY || priority > JVMTI_THREAD_MAX_PRIORITY) { + return ERR(INVALID_PRIORITY); + } + JNIEnv* env = art::Thread::Current()->GetJniEnv(); + if (thread == nullptr || !env->IsInstanceOf(thread, art::WellKnownClasses::java_lang_Thread)) { + return ERR(INVALID_THREAD); + } + if (proc == nullptr) { + return ERR(NULL_POINTER); + } + + std::unique_ptr<AgentData> data(new AgentData); + data->arg = arg; + data->proc = proc; + // We need a global ref for Java objects, as local refs will be invalid. + data->thread = env->NewGlobalRef(thread); + data->java_vm = art::Runtime::Current()->GetJavaVM(); + data->jvmti_env = jvmti_env; + data->priority = priority; + + pthread_t pthread; + int pthread_create_result = pthread_create(&pthread, + nullptr, + &AgentCallback, + reinterpret_cast<void*>(data.get())); + if (pthread_create_result != 0) { + return ERR(INTERNAL); + } + data.release(); + + return ERR(NONE); +} + } // namespace openjdkjvmti diff --git a/runtime/openjdkjvmti/ti_thread.h b/runtime/openjdkjvmti/ti_thread.h index 290e9d49b2..5aaec583da 100644 --- a/runtime/openjdkjvmti/ti_thread.h +++ b/runtime/openjdkjvmti/ti_thread.h @@ -49,6 +49,12 @@ class ThreadUtil { static jvmtiError SetThreadLocalStorage(jvmtiEnv* env, jthread thread, const void* data); static jvmtiError GetThreadLocalStorage(jvmtiEnv* env, jthread thread, void** data_ptr); + + static jvmtiError RunAgentThread(jvmtiEnv* env, + jthread thread, + jvmtiStartFunction proc, + const void* arg, + jint priority); }; } // namespace openjdkjvmti diff --git a/runtime/openjdkjvmti/transform.cc b/runtime/openjdkjvmti/transform.cc index f5451254c0..2809cb6926 100644 --- a/runtime/openjdkjvmti/transform.cc +++ b/runtime/openjdkjvmti/transform.cc @@ -38,6 +38,7 @@ #include "class_linker.h" #include "dex_file.h" #include "dex_file_types.h" +#include "events-inl.h" #include "gc_root-inl.h" #include "globals.h" #include "jni_env_ext-inl.h" @@ -52,12 +53,76 @@ #include "scoped_thread_state_change-inl.h" #include "stack.h" #include "thread_list.h" +#include "ti_redefine.h" #include "transform.h" #include "utf.h" #include "utils/dex_cache_arrays_layout-inl.h" namespace openjdkjvmti { +jvmtiError Transformer::RetransformClassesDirect( + ArtJvmTiEnv* env, + art::Thread* self, + /*in-out*/std::vector<ArtClassDefinition>* definitions) { + for (ArtClassDefinition& def : *definitions) { + jint new_len = -1; + unsigned char* new_data = nullptr; + // Static casts are so that we get the right template initialization for the special event + // handling code required by the ClassFileLoadHooks. + gEventHandler.DispatchEvent(self, + ArtJvmtiEvent::kClassFileLoadHookRetransformable, + GetJniEnv(env), + static_cast<jclass>(def.klass), + static_cast<jobject>(def.loader), + static_cast<const char*>(def.name.c_str()), + static_cast<jobject>(def.protection_domain), + static_cast<jint>(def.dex_len), + static_cast<const unsigned char*>(def.dex_data.get()), + static_cast<jint*>(&new_len), + static_cast<unsigned char**>(&new_data)); + def.SetNewDexData(env, new_len, new_data); + } + return OK; +} + +jvmtiError Transformer::RetransformClasses(ArtJvmTiEnv* env, + art::Runtime* runtime, + art::Thread* self, + jint class_count, + const jclass* classes, + /*out*/std::string* error_msg) { + if (env == nullptr) { + *error_msg = "env was null!"; + return ERR(INVALID_ENVIRONMENT); + } else if (class_count < 0) { + *error_msg = "class_count was less then 0"; + return ERR(ILLEGAL_ARGUMENT); + } else if (class_count == 0) { + // We don't actually need to do anything. Just return OK. + return OK; + } else if (classes == nullptr) { + *error_msg = "null classes!"; + return ERR(NULL_POINTER); + } + // A holder that will Deallocate all the class bytes buffers on destruction. + std::vector<ArtClassDefinition> definitions; + jvmtiError res = OK; + for (jint i = 0; i < class_count; i++) { + ArtClassDefinition def; + res = FillInTransformationData(env, classes[i], &def); + if (res != OK) { + return res; + } + definitions.push_back(std::move(def)); + } + res = RetransformClassesDirect(env, self, &definitions); + if (res != OK) { + return res; + } + return Redefiner::RedefineClassesDirect(env, runtime, self, definitions, error_msg); +} + +// TODO Move this somewhere else, ti_class? jvmtiError GetClassLocation(ArtJvmTiEnv* env, jclass klass, /*out*/std::string* location) { JNIEnv* jni_env = nullptr; jint ret = env->art_vm->GetEnv(reinterpret_cast<void**>(&jni_env), JNI_VERSION_1_1); @@ -73,42 +138,61 @@ jvmtiError GetClassLocation(ArtJvmTiEnv* env, jclass klass, /*out*/std::string* return OK; } +// TODO Implement this for real once transformed dex data is actually saved. +jvmtiError Transformer::GetDexDataForRetransformation(ArtJvmTiEnv* env, + art::Handle<art::mirror::Class> klass, + /*out*/jint* dex_data_len, + /*out*/unsigned char** dex_data) { + // TODO De-quicken the dex file before passing it to the agents. + LOG(WARNING) << "Dex file is not de-quickened yet! Quickened dex instructions might be present"; + LOG(WARNING) << "Caching of initial dex data is not yet performed! Dex data might have been " + << "transformed by agent already"; + const art::DexFile& dex = klass->GetDexFile(); + *dex_data_len = static_cast<jint>(dex.Size()); + unsigned char* new_dex_data = nullptr; + jvmtiError alloc_error = env->Allocate(*dex_data_len, &new_dex_data); + if (alloc_error != OK) { + return alloc_error; + } + // Copy the data into a temporary buffer. + memcpy(reinterpret_cast<void*>(new_dex_data), + reinterpret_cast<const void*>(dex.Begin()), + *dex_data_len); + *dex_data = new_dex_data; + return OK; +} + // TODO Move this function somewhere more appropriate. // Gets the data surrounding the given class. -jvmtiError GetTransformationData(ArtJvmTiEnv* env, - jclass klass, - /*out*/std::string* location, - /*out*/JNIEnv** jni_env_ptr, - /*out*/jobject* loader, - /*out*/std::string* name, - /*out*/jobject* protection_domain, - /*out*/jint* data_len, - /*out*/unsigned char** dex_data) { - jint ret = env->art_vm->GetEnv(reinterpret_cast<void**>(jni_env_ptr), JNI_VERSION_1_1); - if (ret != JNI_OK) { +// TODO Make this less magical. +jvmtiError Transformer::FillInTransformationData(ArtJvmTiEnv* env, + jclass klass, + ArtClassDefinition* def) { + JNIEnv* jni_env = GetJniEnv(env); + if (jni_env == nullptr) { // TODO Different error might be better? return ERR(INTERNAL); } - JNIEnv* jni_env = *jni_env_ptr; art::ScopedObjectAccess soa(jni_env); art::StackHandleScope<3> hs(art::Thread::Current()); art::Handle<art::mirror::Class> hs_klass(hs.NewHandle(soa.Decode<art::mirror::Class>(klass))); - *loader = soa.AddLocalReference<jobject>(hs_klass->GetClassLoader()); - *name = art::mirror::Class::ComputeName(hs_klass)->ToModifiedUtf8(); + if (hs_klass.IsNull()) { + return ERR(INVALID_CLASS); + } + def->klass = klass; + def->loader = soa.AddLocalReference<jobject>(hs_klass->GetClassLoader()); + def->name = art::mirror::Class::ComputeName(hs_klass)->ToModifiedUtf8(); // TODO is this always null? - *protection_domain = nullptr; - const art::DexFile& dex = hs_klass->GetDexFile(); - *location = dex.GetLocation(); - *data_len = static_cast<jint>(dex.Size()); - // TODO We should maybe change env->Allocate to allow us to mprotect this memory and stop writes. - jvmtiError alloc_error = env->Allocate(*data_len, dex_data); - if (alloc_error != OK) { - return alloc_error; + def->protection_domain = nullptr; + if (def->dex_data.get() == nullptr) { + unsigned char* new_data; + jvmtiError res = GetDexDataForRetransformation(env, hs_klass, &def->dex_len, &new_data); + if (res == OK) { + def->dex_data = MakeJvmtiUniquePtr(env, new_data); + } else { + return res; + } } - // Copy the data into a temporary buffer. - memcpy(reinterpret_cast<void*>(*dex_data), - reinterpret_cast<const void*>(dex.Begin()), - *data_len); return OK; } diff --git a/runtime/openjdkjvmti/transform.h b/runtime/openjdkjvmti/transform.h index 0ad5099daf..0ff2bd1d40 100644 --- a/runtime/openjdkjvmti/transform.h +++ b/runtime/openjdkjvmti/transform.h @@ -43,16 +43,30 @@ namespace openjdkjvmti { jvmtiError GetClassLocation(ArtJvmTiEnv* env, jclass klass, /*out*/std::string* location); -// Gets the data surrounding the given class. -jvmtiError GetTransformationData(ArtJvmTiEnv* env, - jclass klass, - /*out*/std::string* location, - /*out*/JNIEnv** jni_env_ptr, - /*out*/jobject* loader, - /*out*/std::string* name, - /*out*/jobject* protection_domain, - /*out*/jint* data_len, - /*out*/unsigned char** dex_data); +class Transformer { + public: + static jvmtiError RetransformClassesDirect( + ArtJvmTiEnv* env, art::Thread* self, /*in-out*/std::vector<ArtClassDefinition>* definitions); + + static jvmtiError RetransformClasses(ArtJvmTiEnv* env, + art::Runtime* runtime, + art::Thread* self, + jint class_count, + const jclass* classes, + /*out*/std::string* error_msg); + + // Gets the data surrounding the given class. + static jvmtiError FillInTransformationData(ArtJvmTiEnv* env, + jclass klass, + ArtClassDefinition* def); + + private: + static jvmtiError GetDexDataForRetransformation(ArtJvmTiEnv* env, + art::Handle<art::mirror::Class> klass, + /*out*/jint* dex_data_length, + /*out*/unsigned char** dex_data) + REQUIRES_SHARED(art::Locks::mutator_lock_); +}; } // namespace openjdkjvmti diff --git a/runtime/reflection.cc b/runtime/reflection.cc index 75176f938e..a2b4cb37a9 100644 --- a/runtime/reflection.cc +++ b/runtime/reflection.cc @@ -216,43 +216,54 @@ class ArgArray { } bool BuildArgArrayFromObjectArray(ObjPtr<mirror::Object> receiver, - ObjPtr<mirror::ObjectArray<mirror::Object>> args, - ArtMethod* m) + ObjPtr<mirror::ObjectArray<mirror::Object>> raw_args, + ArtMethod* m, + Thread* self) REQUIRES_SHARED(Locks::mutator_lock_) { const DexFile::TypeList* classes = m->GetParameterTypeList(); // Set receiver if non-null (method is not static) if (receiver != nullptr) { Append(receiver); } + StackHandleScope<2> hs(self); + MutableHandle<mirror::Object> arg(hs.NewHandle<mirror::Object>(nullptr)); + Handle<mirror::ObjectArray<mirror::Object>> args( + hs.NewHandle<mirror::ObjectArray<mirror::Object>>(raw_args)); for (size_t i = 1, args_offset = 0; i < shorty_len_; ++i, ++args_offset) { - ObjPtr<mirror::Object> arg(args->Get(args_offset)); - if (((shorty_[i] == 'L') && (arg != nullptr)) || ((arg == nullptr && shorty_[i] != 'L'))) { - // Note: The method's parameter's type must have been previously resolved. + arg.Assign(args->Get(args_offset)); + if (((shorty_[i] == 'L') && (arg.Get() != nullptr)) || + ((arg.Get() == nullptr && shorty_[i] != 'L'))) { + // TODO: The method's parameter's type must have been previously resolved, yet + // we've seen cases where it's not b/34440020. ObjPtr<mirror::Class> dst_class( m->GetClassFromTypeIndex(classes->GetTypeItem(args_offset).type_idx_, - false /* resolve */)); - DCHECK(dst_class != nullptr) << m->PrettyMethod() << " arg #" << i; - if (UNLIKELY(arg == nullptr || !arg->InstanceOf(dst_class))) { + true /* resolve */)); + if (dst_class.Ptr() == nullptr) { + CHECK(self->IsExceptionPending()); + return false; + } + if (UNLIKELY(arg.Get() == nullptr || !arg->InstanceOf(dst_class))) { ThrowIllegalArgumentException( StringPrintf("method %s argument %zd has type %s, got %s", m->PrettyMethod(false).c_str(), args_offset + 1, // Humans don't count from 0. mirror::Class::PrettyDescriptor(dst_class).c_str(), - mirror::Object::PrettyTypeOf(arg).c_str()).c_str()); + mirror::Object::PrettyTypeOf(arg.Get()).c_str()).c_str()); return false; } } #define DO_FIRST_ARG(match_descriptor, get_fn, append) { \ - if (LIKELY(arg != nullptr && arg->GetClass()->DescriptorEquals(match_descriptor))) { \ + if (LIKELY(arg.Get() != nullptr && \ + arg->GetClass()->DescriptorEquals(match_descriptor))) { \ ArtField* primitive_field = arg->GetClass()->GetInstanceField(0); \ - append(primitive_field-> get_fn(arg)); + append(primitive_field-> get_fn(arg.Get())); #define DO_ARG(match_descriptor, get_fn, append) \ - } else if (LIKELY(arg != nullptr && \ + } else if (LIKELY(arg.Get() != nullptr && \ arg->GetClass<>()->DescriptorEquals(match_descriptor))) { \ ArtField* primitive_field = arg->GetClass()->GetInstanceField(0); \ - append(primitive_field-> get_fn(arg)); + append(primitive_field-> get_fn(arg.Get())); #define DO_FAIL(expected) \ } else { \ @@ -266,14 +277,14 @@ class ArgArray { ArtMethod::PrettyMethod(m, false).c_str(), \ args_offset + 1, \ expected, \ - mirror::Object::PrettyTypeOf(arg).c_str()).c_str()); \ + mirror::Object::PrettyTypeOf(arg.Get()).c_str()).c_str()); \ } \ return false; \ } } switch (shorty_[i]) { case 'L': - Append(arg); + Append(arg.Get()); break; case 'Z': DO_FIRST_ARG("Ljava/lang/Boolean;", GetBoolean, Append) @@ -646,7 +657,7 @@ jobject InvokeMethod(const ScopedObjectAccessAlreadyRunnable& soa, jobject javaM uint32_t shorty_len = 0; const char* shorty = np_method->GetShorty(&shorty_len); ArgArray arg_array(shorty, shorty_len); - if (!arg_array.BuildArgArrayFromObjectArray(receiver, objects, np_method)) { + if (!arg_array.BuildArgArrayFromObjectArray(receiver, objects, np_method, soa.Self())) { CHECK(soa.Self()->IsExceptionPending()); return nullptr; } diff --git a/runtime/runtime.cc b/runtime/runtime.cc index 55e1852c0c..8b355c8c19 100644 --- a/runtime/runtime.cc +++ b/runtime/runtime.cc @@ -137,6 +137,7 @@ #include "jit/profile_saver.h" #include "quick/quick_method_frame_info.h" #include "reflection.h" +#include "runtime_callbacks.h" #include "runtime_options.h" #include "ScopedLocalRef.h" #include "scoped_thread_state_change-inl.h" @@ -253,10 +254,12 @@ Runtime::Runtime() pruned_dalvik_cache_(false), // Initially assume we perceive jank in case the process state is never updated. process_state_(kProcessStateJankPerceptible), - zygote_no_threads_(false) { + zygote_no_threads_(false), + cha_(nullptr) { CheckAsmSupportOffsetsAndSizes(); std::fill(callee_save_methods_, callee_save_methods_ + arraysize(callee_save_methods_), 0u); interpreter::CheckInterpreterAsmConstants(); + callbacks_.reset(new RuntimeCallbacks()); } Runtime::~Runtime() { @@ -301,6 +304,13 @@ Runtime::~Runtime() { Trace::Shutdown(); + // Report death. Clients me require a working thread, still, so do it before GC completes and + // all non-daemon threads are done. + { + ScopedObjectAccess soa(self); + callbacks_->NextRuntimePhase(RuntimePhaseCallback::RuntimePhase::kDeath); + } + if (attach_shutdown_thread) { DetachCurrentThread(); self = nullptr; @@ -703,6 +713,13 @@ bool Runtime::Start() { Thread::FinishStartup(); + // Send the start phase event. We have to wait till here as this is when the main thread peer + // has just been generated, important root clinits have been run and JNI is completely functional. + { + ScopedObjectAccess soa(self); + callbacks_->NextRuntimePhase(RuntimePhaseCallback::RuntimePhase::kStart); + } + system_class_loader_ = CreateSystemClassLoader(this); if (!is_zygote_) { @@ -739,6 +756,12 @@ bool Runtime::Start() { 0); } + // Send the initialized phase event. + { + ScopedObjectAccess soa(self); + callbacks_->NextRuntimePhase(RuntimePhaseCallback::RuntimePhase::kInit); + } + return true; } @@ -1100,6 +1123,8 @@ bool Runtime::Init(RuntimeArgumentMap&& runtime_options_in) { if (runtime_options.Exists(Opt::JdwpOptions)) { Dbg::ConfigureJdwp(runtime_options.GetOrDefault(Opt::JdwpOptions)); } + callbacks_->AddThreadLifecycleCallback(Dbg::GetThreadLifecycleCallback()); + callbacks_->AddClassLoadCallback(Dbg::GetClassLoadCallback()); jit_options_.reset(jit::JitOptions::CreateFromRuntimeArguments(runtime_options)); if (IsAotCompiler()) { @@ -1547,6 +1572,12 @@ void Runtime::DumpForSigQuit(std::ostream& os) { thread_list_->DumpForSigQuit(os); BaseMutex::DumpAll(os); + + // Inform anyone else who is interested in SigQuit. + { + ScopedObjectAccess soa(Thread::Current()); + callbacks_->SigQuit(); + } } void Runtime::DumpLockHolders(std::ostream& os) { @@ -2253,4 +2284,8 @@ void Runtime::Aborter(const char* abort_message) { Runtime::Abort(abort_message); } +RuntimeCallbacks* Runtime::GetRuntimeCallbacks() { + return callbacks_.get(); +} + } // namespace art diff --git a/runtime/runtime.h b/runtime/runtime.h index cf23d0510d..f7d6810ff5 100644 --- a/runtime/runtime.h +++ b/runtime/runtime.h @@ -28,6 +28,7 @@ #include "arch/instruction_set.h" #include "base/macros.h" +#include "base/mutex.h" #include "dex_file_types.h" #include "experimental_flags.h" #include "gc_root.h" @@ -89,6 +90,7 @@ class NullPointerHandler; class OatFileManager; class Plugin; struct RuntimeArgumentMap; +class RuntimeCallbacks; class SignalCatcher; class StackOverflowHandler; class SuspensionHandler; @@ -659,6 +661,8 @@ class Runtime { void AttachAgent(const std::string& agent_arg); + RuntimeCallbacks* GetRuntimeCallbacks(); + private: static void InitPlatformSignalHandlers(); @@ -916,6 +920,8 @@ class Runtime { ClassHierarchyAnalysis* cha_; + std::unique_ptr<RuntimeCallbacks> callbacks_; + DISALLOW_COPY_AND_ASSIGN(Runtime); }; std::ostream& operator<<(std::ostream& os, const Runtime::CalleeSaveType& rhs); diff --git a/runtime/runtime_callbacks.cc b/runtime/runtime_callbacks.cc new file mode 100644 index 0000000000..7b15a4f1b5 --- /dev/null +++ b/runtime/runtime_callbacks.cc @@ -0,0 +1,104 @@ +/* + * Copyright (C) 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "runtime_callbacks.h" + +#include <algorithm> + +#include "base/macros.h" +#include "class_linker.h" +#include "thread.h" + +namespace art { + +void RuntimeCallbacks::AddThreadLifecycleCallback(ThreadLifecycleCallback* cb) { + thread_callbacks_.push_back(cb); +} + +template <typename T> +ALWAYS_INLINE +static inline void Remove(T* cb, std::vector<T*>* data) { + auto it = std::find(data->begin(), data->end(), cb); + if (it != data->end()) { + data->erase(it); + } +} + +void RuntimeCallbacks::RemoveThreadLifecycleCallback(ThreadLifecycleCallback* cb) { + Remove(cb, &thread_callbacks_); +} + +void RuntimeCallbacks::ThreadStart(Thread* self) { + for (ThreadLifecycleCallback* cb : thread_callbacks_) { + cb->ThreadStart(self); + } +} + +void RuntimeCallbacks::ThreadDeath(Thread* self) { + for (ThreadLifecycleCallback* cb : thread_callbacks_) { + cb->ThreadDeath(self); + } +} + +void RuntimeCallbacks::AddClassLoadCallback(ClassLoadCallback* cb) { + class_callbacks_.push_back(cb); +} + +void RuntimeCallbacks::RemoveClassLoadCallback(ClassLoadCallback* cb) { + Remove(cb, &class_callbacks_); +} + +void RuntimeCallbacks::ClassLoad(Handle<mirror::Class> klass) { + for (ClassLoadCallback* cb : class_callbacks_) { + cb->ClassLoad(klass); + } +} + +void RuntimeCallbacks::ClassPrepare(Handle<mirror::Class> temp_klass, Handle<mirror::Class> klass) { + for (ClassLoadCallback* cb : class_callbacks_) { + cb->ClassPrepare(temp_klass, klass); + } +} + +void RuntimeCallbacks::AddRuntimeSigQuitCallback(RuntimeSigQuitCallback* cb) { + sigquit_callbacks_.push_back(cb); +} + +void RuntimeCallbacks::RemoveRuntimeSigQuitCallback(RuntimeSigQuitCallback* cb) { + Remove(cb, &sigquit_callbacks_); +} + +void RuntimeCallbacks::SigQuit() { + for (RuntimeSigQuitCallback* cb : sigquit_callbacks_) { + cb->SigQuit(); + } +} + +void RuntimeCallbacks::AddRuntimePhaseCallback(RuntimePhaseCallback* cb) { + phase_callbacks_.push_back(cb); +} + +void RuntimeCallbacks::RemoveRuntimePhaseCallback(RuntimePhaseCallback* cb) { + Remove(cb, &phase_callbacks_); +} + +void RuntimeCallbacks::NextRuntimePhase(RuntimePhaseCallback::RuntimePhase phase) { + for (RuntimePhaseCallback* cb : phase_callbacks_) { + cb->NextRuntimePhase(phase); + } +} + +} // namespace art diff --git a/runtime/runtime_callbacks.h b/runtime/runtime_callbacks.h new file mode 100644 index 0000000000..6344c69b1f --- /dev/null +++ b/runtime/runtime_callbacks.h @@ -0,0 +1,114 @@ +/* + * Copyright (C) 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#ifndef ART_RUNTIME_RUNTIME_CALLBACKS_H_ +#define ART_RUNTIME_RUNTIME_CALLBACKS_H_ + +#include <vector> + +#include "base/macros.h" +#include "base/mutex.h" +#include "handle.h" + +namespace art { + +namespace mirror { +class Class; +} // namespace mirror + +class ClassLoadCallback; +class Thread; +class ThreadLifecycleCallback; + +// Note: RuntimeCallbacks uses the mutator lock to synchronize the callback lists. A thread must +// hold the exclusive lock to add or remove a listener. A thread must hold the shared lock +// to dispatch an event. This setup is chosen as some clients may want to suspend the +// dispatching thread or all threads. +// +// To make this safe, the following restrictions apply: +// * Only the owner of a listener may ever add or remove said listener. +// * A listener must never add or remove itself or any other listener while running. +// * It is the responsibility of the owner to not remove the listener while it is running +// (and suspended). +// +// The simplest way to satisfy these restrictions is to never remove a listener, and to do +// any state checking (is the listener enabled) in the listener itself. For an example, see +// Dbg. + +class RuntimeSigQuitCallback { + public: + virtual ~RuntimeSigQuitCallback() {} + + virtual void SigQuit() REQUIRES_SHARED(Locks::mutator_lock_) = 0; +}; + +class RuntimePhaseCallback { + public: + enum RuntimePhase { + kStart, // The runtime is started. + kInit, // The runtime is initialized (and will run user code soon). + kDeath, // The runtime just died. + }; + + virtual ~RuntimePhaseCallback() {} + + virtual void NextRuntimePhase(RuntimePhase phase) REQUIRES_SHARED(Locks::mutator_lock_) = 0; +}; + +class RuntimeCallbacks { + public: + void AddThreadLifecycleCallback(ThreadLifecycleCallback* cb) REQUIRES(Locks::mutator_lock_); + void RemoveThreadLifecycleCallback(ThreadLifecycleCallback* cb) REQUIRES(Locks::mutator_lock_); + + void ThreadStart(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_); + void ThreadDeath(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_); + + void AddClassLoadCallback(ClassLoadCallback* cb) REQUIRES(Locks::mutator_lock_); + void RemoveClassLoadCallback(ClassLoadCallback* cb) REQUIRES(Locks::mutator_lock_); + + void ClassLoad(Handle<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_); + void ClassPrepare(Handle<mirror::Class> temp_klass, Handle<mirror::Class> klass) + REQUIRES_SHARED(Locks::mutator_lock_); + + void AddRuntimeSigQuitCallback(RuntimeSigQuitCallback* cb) + REQUIRES(Locks::mutator_lock_); + void RemoveRuntimeSigQuitCallback(RuntimeSigQuitCallback* cb) + REQUIRES(Locks::mutator_lock_); + + void SigQuit() REQUIRES_SHARED(Locks::mutator_lock_); + + void AddRuntimePhaseCallback(RuntimePhaseCallback* cb) + REQUIRES(Locks::mutator_lock_); + void RemoveRuntimePhaseCallback(RuntimePhaseCallback* cb) + REQUIRES(Locks::mutator_lock_); + + void NextRuntimePhase(RuntimePhaseCallback::RuntimePhase phase) + REQUIRES_SHARED(Locks::mutator_lock_); + + private: + std::vector<ThreadLifecycleCallback*> thread_callbacks_ + GUARDED_BY(Locks::mutator_lock_); + std::vector<ClassLoadCallback*> class_callbacks_ + GUARDED_BY(Locks::mutator_lock_); + std::vector<RuntimeSigQuitCallback*> sigquit_callbacks_ + GUARDED_BY(Locks::mutator_lock_); + std::vector<RuntimePhaseCallback*> phase_callbacks_ + GUARDED_BY(Locks::mutator_lock_); +}; + +} // namespace art + +#endif // ART_RUNTIME_RUNTIME_CALLBACKS_H_ diff --git a/runtime/runtime_callbacks_test.cc b/runtime/runtime_callbacks_test.cc new file mode 100644 index 0000000000..c379b5c267 --- /dev/null +++ b/runtime/runtime_callbacks_test.cc @@ -0,0 +1,401 @@ +/* + * Copyright (C) 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include "runtime_callbacks.h" + +#include "jni.h" +#include <signal.h> +#include <sys/types.h> +#include <unistd.h> + +#include <initializer_list> +#include <memory> +#include <string> + +#include "art_method-inl.h" +#include "base/mutex.h" +#include "class_linker.h" +#include "common_runtime_test.h" +#include "handle.h" +#include "handle_scope-inl.h" +#include "mem_map.h" +#include "mirror/class-inl.h" +#include "mirror/class_loader.h" +#include "obj_ptr.h" +#include "runtime.h" +#include "scoped_thread_state_change-inl.h" +#include "ScopedLocalRef.h" +#include "thread-inl.h" +#include "thread_list.h" +#include "well_known_classes.h" + +namespace art { + +class RuntimeCallbacksTest : public CommonRuntimeTest { + protected: + void SetUp() OVERRIDE { + CommonRuntimeTest::SetUp(); + + Thread* self = Thread::Current(); + ScopedObjectAccess soa(self); + ScopedThreadSuspension sts(self, kWaitingForDebuggerToAttach); + ScopedSuspendAll ssa("RuntimeCallbacksTest SetUp"); + AddListener(); + } + + void TearDown() OVERRIDE { + { + Thread* self = Thread::Current(); + ScopedObjectAccess soa(self); + ScopedThreadSuspension sts(self, kWaitingForDebuggerToAttach); + ScopedSuspendAll ssa("RuntimeCallbacksTest TearDown"); + RemoveListener(); + } + + CommonRuntimeTest::TearDown(); + } + + virtual void AddListener() REQUIRES(Locks::mutator_lock_) = 0; + virtual void RemoveListener() REQUIRES(Locks::mutator_lock_) = 0; + + void MakeExecutable(ObjPtr<mirror::Class> klass) REQUIRES_SHARED(Locks::mutator_lock_) { + CHECK(klass != nullptr); + PointerSize pointer_size = class_linker_->GetImagePointerSize(); + for (auto& m : klass->GetMethods(pointer_size)) { + if (!m.IsAbstract()) { + class_linker_->SetEntryPointsToInterpreter(&m); + } + } + } +}; + +class ThreadLifecycleCallbackRuntimeCallbacksTest : public RuntimeCallbacksTest { + public: + static void* PthreadsCallback(void* arg ATTRIBUTE_UNUSED) { + // Attach. + Runtime* runtime = Runtime::Current(); + CHECK(runtime->AttachCurrentThread("ThreadLifecycle test thread", true, nullptr, false)); + + // Detach. + runtime->DetachCurrentThread(); + + // Die... + return nullptr; + } + + protected: + void AddListener() OVERRIDE REQUIRES(Locks::mutator_lock_) { + Runtime::Current()->GetRuntimeCallbacks()->AddThreadLifecycleCallback(&cb_); + } + void RemoveListener() OVERRIDE REQUIRES(Locks::mutator_lock_) { + Runtime::Current()->GetRuntimeCallbacks()->RemoveThreadLifecycleCallback(&cb_); + } + + enum CallbackState { + kBase, + kStarted, + kDied, + kWrongStart, + kWrongDeath, + }; + + struct Callback : public ThreadLifecycleCallback { + void ThreadStart(Thread* self) OVERRIDE { + if (state == CallbackState::kBase) { + state = CallbackState::kStarted; + stored_self = self; + } else { + state = CallbackState::kWrongStart; + } + } + + void ThreadDeath(Thread* self) OVERRIDE { + if (state == CallbackState::kStarted && self == stored_self) { + state = CallbackState::kDied; + } else { + state = CallbackState::kWrongDeath; + } + } + + Thread* stored_self; + CallbackState state = CallbackState::kBase; + }; + + Callback cb_; +}; + +TEST_F(ThreadLifecycleCallbackRuntimeCallbacksTest, ThreadLifecycleCallbackJava) { + Thread* self = Thread::Current(); + + self->TransitionFromSuspendedToRunnable(); + bool started = runtime_->Start(); + ASSERT_TRUE(started); + + cb_.state = CallbackState::kBase; // Ignore main thread attach. + + { + ScopedObjectAccess soa(self); + MakeExecutable(soa.Decode<mirror::Class>(WellKnownClasses::java_lang_Thread)); + } + + JNIEnv* env = self->GetJniEnv(); + + ScopedLocalRef<jobject> thread_name(env, + env->NewStringUTF("ThreadLifecycleCallback test thread")); + ASSERT_TRUE(thread_name.get() != nullptr); + + ScopedLocalRef<jobject> thread(env, env->AllocObject(WellKnownClasses::java_lang_Thread)); + ASSERT_TRUE(thread.get() != nullptr); + + env->CallNonvirtualVoidMethod(thread.get(), + WellKnownClasses::java_lang_Thread, + WellKnownClasses::java_lang_Thread_init, + runtime_->GetMainThreadGroup(), + thread_name.get(), + kMinThreadPriority, + JNI_FALSE); + ASSERT_FALSE(env->ExceptionCheck()); + + jmethodID start_id = env->GetMethodID(WellKnownClasses::java_lang_Thread, "start", "()V"); + ASSERT_TRUE(start_id != nullptr); + + env->CallVoidMethod(thread.get(), start_id); + ASSERT_FALSE(env->ExceptionCheck()); + + jmethodID join_id = env->GetMethodID(WellKnownClasses::java_lang_Thread, "join", "()V"); + ASSERT_TRUE(join_id != nullptr); + + env->CallVoidMethod(thread.get(), join_id); + ASSERT_FALSE(env->ExceptionCheck()); + + EXPECT_TRUE(cb_.state == CallbackState::kDied) << static_cast<int>(cb_.state); +} + +TEST_F(ThreadLifecycleCallbackRuntimeCallbacksTest, ThreadLifecycleCallbackAttach) { + std::string error_msg; + std::unique_ptr<MemMap> stack(MemMap::MapAnonymous("ThreadLifecycleCallback Thread", + nullptr, + 128 * kPageSize, // Just some small stack. + PROT_READ | PROT_WRITE, + false, + false, + &error_msg)); + ASSERT_FALSE(stack == nullptr) << error_msg; + + const char* reason = "ThreadLifecycleCallback test thread"; + pthread_attr_t attr; + CHECK_PTHREAD_CALL(pthread_attr_init, (&attr), reason); + CHECK_PTHREAD_CALL(pthread_attr_setstack, (&attr, stack->Begin(), stack->Size()), reason); + pthread_t pthread; + CHECK_PTHREAD_CALL(pthread_create, + (&pthread, + &attr, + &ThreadLifecycleCallbackRuntimeCallbacksTest::PthreadsCallback, + this), + reason); + CHECK_PTHREAD_CALL(pthread_attr_destroy, (&attr), reason); + + CHECK_PTHREAD_CALL(pthread_join, (pthread, nullptr), "ThreadLifecycleCallback test shutdown"); + + // Detach is not a ThreadDeath event, so we expect to be in state Started. + EXPECT_TRUE(cb_.state == CallbackState::kStarted) << static_cast<int>(cb_.state); +} + +class ClassLoadCallbackRuntimeCallbacksTest : public RuntimeCallbacksTest { + protected: + void AddListener() OVERRIDE REQUIRES(Locks::mutator_lock_) { + Runtime::Current()->GetRuntimeCallbacks()->AddClassLoadCallback(&cb_); + } + void RemoveListener() OVERRIDE REQUIRES(Locks::mutator_lock_) { + Runtime::Current()->GetRuntimeCallbacks()->RemoveClassLoadCallback(&cb_); + } + + bool Expect(std::initializer_list<const char*> list) { + if (cb_.data.size() != list.size()) { + PrintError(list); + return false; + } + + if (!std::equal(cb_.data.begin(), cb_.data.end(), list.begin())) { + PrintError(list); + return false; + } + + return true; + } + + void PrintError(std::initializer_list<const char*> list) { + LOG(ERROR) << "Expected:"; + for (const char* expected : list) { + LOG(ERROR) << " " << expected; + } + LOG(ERROR) << "Found:"; + for (const auto& s : cb_.data) { + LOG(ERROR) << " " << s; + } + } + + struct Callback : public ClassLoadCallback { + void ClassLoad(Handle<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) { + std::string tmp; + std::string event = std::string("Load:") + klass->GetDescriptor(&tmp); + data.push_back(event); + } + + void ClassPrepare(Handle<mirror::Class> temp_klass, + Handle<mirror::Class> klass) OVERRIDE REQUIRES_SHARED(Locks::mutator_lock_) { + std::string tmp, tmp2; + std::string event = std::string("Prepare:") + klass->GetDescriptor(&tmp) + + "[" + temp_klass->GetDescriptor(&tmp2) + "]"; + data.push_back(event); + } + + std::vector<std::string> data; + }; + + Callback cb_; +}; + +TEST_F(ClassLoadCallbackRuntimeCallbacksTest, ClassLoadCallback) { + ScopedObjectAccess soa(Thread::Current()); + jobject jclass_loader = LoadDex("XandY"); + VariableSizedHandleScope hs(soa.Self()); + Handle<mirror::ClassLoader> class_loader(hs.NewHandle( + soa.Decode<mirror::ClassLoader>(jclass_loader))); + + const char* descriptor_y = "LY;"; + Handle<mirror::Class> h_Y( + hs.NewHandle(class_linker_->FindClass(soa.Self(), descriptor_y, class_loader))); + ASSERT_TRUE(h_Y.Get() != nullptr); + + bool expect1 = Expect({ "Load:LX;", "Prepare:LX;[LX;]", "Load:LY;", "Prepare:LY;[LY;]" }); + EXPECT_TRUE(expect1); + + cb_.data.clear(); + + ASSERT_TRUE(class_linker_->EnsureInitialized(Thread::Current(), h_Y, true, true)); + + bool expect2 = Expect({ "Load:LY$Z;", "Prepare:LY$Z;[LY$Z;]" }); + EXPECT_TRUE(expect2); +} + +class RuntimeSigQuitCallbackRuntimeCallbacksTest : public RuntimeCallbacksTest { + protected: + void AddListener() OVERRIDE REQUIRES(Locks::mutator_lock_) { + Runtime::Current()->GetRuntimeCallbacks()->AddRuntimeSigQuitCallback(&cb_); + } + void RemoveListener() OVERRIDE REQUIRES(Locks::mutator_lock_) { + Runtime::Current()->GetRuntimeCallbacks()->RemoveRuntimeSigQuitCallback(&cb_); + } + + struct Callback : public RuntimeSigQuitCallback { + void SigQuit() OVERRIDE { + ++sigquit_count; + } + + size_t sigquit_count = 0; + }; + + Callback cb_; +}; + +TEST_F(RuntimeSigQuitCallbackRuntimeCallbacksTest, SigQuit) { + // The runtime needs to be started for the signal handler. + Thread* self = Thread::Current(); + + self->TransitionFromSuspendedToRunnable(); + bool started = runtime_->Start(); + ASSERT_TRUE(started); + + EXPECT_EQ(0u, cb_.sigquit_count); + + kill(getpid(), SIGQUIT); + + // Try a few times. + for (size_t i = 0; i != 30; ++i) { + if (cb_.sigquit_count == 0) { + sleep(1); + } else { + break; + } + } + EXPECT_EQ(1u, cb_.sigquit_count); +} + +class RuntimePhaseCallbackRuntimeCallbacksTest : public RuntimeCallbacksTest { + protected: + void AddListener() OVERRIDE REQUIRES(Locks::mutator_lock_) { + Runtime::Current()->GetRuntimeCallbacks()->AddRuntimePhaseCallback(&cb_); + } + void RemoveListener() OVERRIDE REQUIRES(Locks::mutator_lock_) { + Runtime::Current()->GetRuntimeCallbacks()->RemoveRuntimePhaseCallback(&cb_); + } + + void TearDown() OVERRIDE { + // Bypass RuntimeCallbacksTest::TearDown, as the runtime is already gone. + CommonRuntimeTest::TearDown(); + } + + struct Callback : public RuntimePhaseCallback { + void NextRuntimePhase(RuntimePhaseCallback::RuntimePhase p) OVERRIDE { + if (p == RuntimePhaseCallback::RuntimePhase::kStart) { + if (init_seen > 0) { + LOG(FATAL) << "Init seen before start."; + } + ++start_seen; + } else if (p == RuntimePhaseCallback::RuntimePhase::kInit) { + ++init_seen; + } else if (p == RuntimePhaseCallback::RuntimePhase::kDeath) { + ++death_seen; + } else { + LOG(FATAL) << "Unknown phase " << static_cast<uint32_t>(p); + } + } + + size_t start_seen = 0; + size_t init_seen = 0; + size_t death_seen = 0; + }; + + Callback cb_; +}; + +TEST_F(RuntimePhaseCallbackRuntimeCallbacksTest, Phases) { + ASSERT_EQ(0u, cb_.start_seen); + ASSERT_EQ(0u, cb_.init_seen); + ASSERT_EQ(0u, cb_.death_seen); + + // Start the runtime. + { + Thread* self = Thread::Current(); + self->TransitionFromSuspendedToRunnable(); + bool started = runtime_->Start(); + ASSERT_TRUE(started); + } + + ASSERT_EQ(1u, cb_.start_seen); + ASSERT_EQ(1u, cb_.init_seen); + ASSERT_EQ(0u, cb_.death_seen); + + // Delete the runtime. + runtime_.reset(); + + ASSERT_EQ(1u, cb_.start_seen); + ASSERT_EQ(1u, cb_.init_seen); + ASSERT_EQ(1u, cb_.death_seen); +} + +} // namespace art diff --git a/runtime/thread.cc b/runtime/thread.cc index ebf14c19b1..d93eab10a0 100644 --- a/runtime/thread.cc +++ b/runtime/thread.cc @@ -67,6 +67,7 @@ #include "quick/quick_method_frame_info.h" #include "reflection.h" #include "runtime.h" +#include "runtime_callbacks.h" #include "scoped_thread_state_change-inl.h" #include "ScopedLocalRef.h" #include "ScopedUtfChars.h" @@ -431,7 +432,8 @@ void* Thread::CreateCallback(void* arg) { ArtField* priorityField = jni::DecodeArtField(WellKnownClasses::java_lang_Thread_priority); self->SetNativePriority(priorityField->GetInt(self->tlsPtr_.opeer)); - Dbg::PostThreadStart(self); + + runtime->GetRuntimeCallbacks()->ThreadStart(self); // Invoke the 'run' method of our java.lang.Thread. ObjPtr<mirror::Object> receiver = self->tlsPtr_.opeer; @@ -723,8 +725,8 @@ bool Thread::Init(ThreadList* thread_list, JavaVMExt* java_vm, JNIEnvExt* jni_en return true; } -Thread* Thread::Attach(const char* thread_name, bool as_daemon, jobject thread_group, - bool create_peer) { +template <typename PeerAction> +Thread* Thread::Attach(const char* thread_name, bool as_daemon, PeerAction peer_action) { Runtime* runtime = Runtime::Current(); if (runtime == nullptr) { LOG(ERROR) << "Thread attaching to non-existent runtime: " << thread_name; @@ -753,32 +755,11 @@ Thread* Thread::Attach(const char* thread_name, bool as_daemon, jobject thread_g CHECK_NE(self->GetState(), kRunnable); self->SetState(kNative); - // If we're the main thread, ClassLinker won't be created until after we're attached, - // so that thread needs a two-stage attach. Regular threads don't need this hack. - // In the compiler, all threads need this hack, because no-one's going to be getting - // a native peer! - if (create_peer) { - self->CreatePeer(thread_name, as_daemon, thread_group); - if (self->IsExceptionPending()) { - // We cannot keep the exception around, as we're deleting self. Try to be helpful and log it. - { - ScopedObjectAccess soa(self); - LOG(ERROR) << "Exception creating thread peer:"; - LOG(ERROR) << self->GetException()->Dump(); - self->ClearException(); - } - runtime->GetThreadList()->Unregister(self); - // Unregister deletes self, no need to do this here. - return nullptr; - } - } else { - // These aren't necessary, but they improve diagnostics for unit tests & command-line tools. - if (thread_name != nullptr) { - self->tlsPtr_.name->assign(thread_name); - ::art::SetThreadName(thread_name); - } else if (self->GetJniEnv()->check_jni) { - LOG(WARNING) << *Thread::Current() << " attached without supplying a name"; - } + // Run the action that is acting on the peer. + if (!peer_action(self)) { + runtime->GetThreadList()->Unregister(self); + // Unregister deletes self, no need to do this here. + return nullptr; } if (VLOG_IS_ON(threads)) { @@ -793,12 +774,63 @@ Thread* Thread::Attach(const char* thread_name, bool as_daemon, jobject thread_g { ScopedObjectAccess soa(self); - Dbg::PostThreadStart(self); + runtime->GetRuntimeCallbacks()->ThreadStart(self); } return self; } +Thread* Thread::Attach(const char* thread_name, + bool as_daemon, + jobject thread_group, + bool create_peer) { + auto create_peer_action = [&](Thread* self) { + // If we're the main thread, ClassLinker won't be created until after we're attached, + // so that thread needs a two-stage attach. Regular threads don't need this hack. + // In the compiler, all threads need this hack, because no-one's going to be getting + // a native peer! + if (create_peer) { + self->CreatePeer(thread_name, as_daemon, thread_group); + if (self->IsExceptionPending()) { + // We cannot keep the exception around, as we're deleting self. Try to be helpful and log it. + { + ScopedObjectAccess soa(self); + LOG(ERROR) << "Exception creating thread peer:"; + LOG(ERROR) << self->GetException()->Dump(); + self->ClearException(); + } + return false; + } + } else { + // These aren't necessary, but they improve diagnostics for unit tests & command-line tools. + if (thread_name != nullptr) { + self->tlsPtr_.name->assign(thread_name); + ::art::SetThreadName(thread_name); + } else if (self->GetJniEnv()->check_jni) { + LOG(WARNING) << *Thread::Current() << " attached without supplying a name"; + } + } + return true; + }; + return Attach(thread_name, as_daemon, create_peer_action); +} + +Thread* Thread::Attach(const char* thread_name, bool as_daemon, jobject thread_peer) { + auto set_peer_action = [&](Thread* self) { + // Install the given peer. + { + DCHECK(self == Thread::Current()); + ScopedObjectAccess soa(self); + self->tlsPtr_.opeer = soa.Decode<mirror::Object>(thread_peer).Ptr(); + } + self->GetJniEnv()->SetLongField(thread_peer, + WellKnownClasses::java_lang_Thread_nativePeer, + reinterpret_cast<jlong>(self)); + return true; + }; + return Attach(thread_name, as_daemon, set_peer_action); +} + void Thread::CreatePeer(const char* name, bool as_daemon, jobject thread_group) { Runtime* runtime = Runtime::Current(); CHECK(runtime->IsStarted()); @@ -1929,7 +1961,11 @@ void Thread::Destroy() { jni::DecodeArtField(WellKnownClasses::java_lang_Thread_nativePeer) ->SetLong<false>(tlsPtr_.opeer, 0); } - Dbg::PostThreadDeath(self); + Runtime* runtime = Runtime::Current(); + if (runtime != nullptr) { + runtime->GetRuntimeCallbacks()->ThreadDeath(self); + } + // Thread.join() is implemented as an Object.wait() on the Thread.lock object. Signal anyone // who is waiting. diff --git a/runtime/thread.h b/runtime/thread.h index 2b451bcaee..b609e723e9 100644 --- a/runtime/thread.h +++ b/runtime/thread.h @@ -158,6 +158,8 @@ class Thread { // Used to implement JNI AttachCurrentThread and AttachCurrentThreadAsDaemon calls. static Thread* Attach(const char* thread_name, bool as_daemon, jobject thread_group, bool create_peer); + // Attaches the calling native thread to the runtime, returning the new native peer. + static Thread* Attach(const char* thread_name, bool as_daemon, jobject thread_peer); // Reset internal state of child thread after fork. void InitAfterFork(); @@ -1166,6 +1168,13 @@ class Thread { ~Thread() REQUIRES(!Locks::mutator_lock_, !Locks::thread_suspend_count_lock_); void Destroy(); + // Attaches the calling native thread to the runtime, returning the new native peer. + // Used to implement JNI AttachCurrentThread and AttachCurrentThreadAsDaemon calls. + template <typename PeerAction> + static Thread* Attach(const char* thread_name, + bool as_daemon, + PeerAction p); + void CreatePeer(const char* name, bool as_daemon, jobject thread_group); template<bool kTransactionActive> @@ -1704,6 +1713,14 @@ class ScopedTransitioningToRunnable : public ValueObject { Thread* const self_; }; +class ThreadLifecycleCallback { + public: + virtual ~ThreadLifecycleCallback() {} + + virtual void ThreadStart(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_) = 0; + virtual void ThreadDeath(Thread* self) REQUIRES_SHARED(Locks::mutator_lock_) = 0; +}; + std::ostream& operator<<(std::ostream& os, const Thread& thread); std::ostream& operator<<(std::ostream& os, const StackedShadowFrameType& thread); diff --git a/runtime/verifier/verifier_deps.cc b/runtime/verifier/verifier_deps.cc index 15cc566cc6..113160785c 100644 --- a/runtime/verifier/verifier_deps.cc +++ b/runtime/verifier/verifier_deps.cc @@ -963,20 +963,25 @@ bool VerifierDeps::VerifyFields(Handle<mirror::ClassLoader> class_loader, // Check recorded fields are resolved the same way, have the same recorded class, // and have the same recorded flags. ClassLinker* class_linker = Runtime::Current()->GetClassLinker(); - StackHandleScope<1> hs(self); - Handle<mirror::DexCache> dex_cache( - hs.NewHandle(class_linker->FindDexCache(self, dex_file, /* allow_failure */ false))); for (const auto& entry : fields) { - ArtField* field = class_linker->ResolveFieldJLS( - dex_file, entry.GetDexFieldIndex(), dex_cache, class_loader); - - if (field == nullptr) { - DCHECK(self->IsExceptionPending()); - self->ClearException(); + const DexFile::FieldId& field_id = dex_file.GetFieldId(entry.GetDexFieldIndex()); + StringPiece name(dex_file.StringDataByIdx(field_id.name_idx_)); + StringPiece type(dex_file.StringDataByIdx(dex_file.GetTypeId(field_id.type_idx_).descriptor_idx_)); + // Only use field_id.class_idx_ when the entry is unresolved, which is rare. + // Otherwise, we might end up resolving an application class, which is expensive. + std::string expected_decl_klass = entry.IsResolved() + ? GetStringFromId(dex_file, entry.GetDeclaringClassIndex()) + : dex_file.StringByTypeIdx(field_id.class_idx_); + mirror::Class* cls = FindClassAndClearException( + class_linker, self, expected_decl_klass.c_str(), class_loader); + if (cls == nullptr) { + LOG(INFO) << "VerifierDeps: Could not resolve class " << expected_decl_klass; + return false; } + DCHECK(cls->IsResolved()); + ArtField* field = mirror::Class::FindField(self, cls, name, type); if (entry.IsResolved()) { - std::string expected_decl_klass = GetStringFromId(dex_file, entry.GetDeclaringClassIndex()); std::string temp; if (field == nullptr) { LOG(INFO) << "VerifierDeps: Could not resolve field " @@ -1025,11 +1030,16 @@ bool VerifierDeps::VerifyMethods(Handle<mirror::ClassLoader> class_loader, const char* name = dex_file.GetMethodName(method_id); const Signature signature = dex_file.GetMethodSignature(method_id); - const char* descriptor = dex_file.GetMethodDeclaringClassDescriptor(method_id); - - mirror::Class* cls = FindClassAndClearException(class_linker, self, descriptor, class_loader); + // Only use method_id.class_idx_ when the entry is unresolved, which is rare. + // Otherwise, we might end up resolving an application class, which is expensive. + std::string expected_decl_klass = entry.IsResolved() + ? GetStringFromId(dex_file, entry.GetDeclaringClassIndex()) + : dex_file.StringByTypeIdx(method_id.class_idx_); + + mirror::Class* cls = FindClassAndClearException( + class_linker, self, expected_decl_klass.c_str(), class_loader); if (cls == nullptr) { - LOG(INFO) << "VerifierDeps: Could not resolve class " << descriptor; + LOG(INFO) << "VerifierDeps: Could not resolve class " << expected_decl_klass; return false; } DCHECK(cls->IsResolved()); @@ -1045,7 +1055,6 @@ bool VerifierDeps::VerifyMethods(Handle<mirror::ClassLoader> class_loader, if (entry.IsResolved()) { std::string temp; - std::string expected_decl_klass = GetStringFromId(dex_file, entry.GetDeclaringClassIndex()); if (method == nullptr) { LOG(INFO) << "VerifierDeps: Could not resolve " << kind diff --git a/test/595-profile-saving/profile-saving.cc b/test/595-profile-saving/profile-saving.cc index bf3d812f94..0f8dd57385 100644 --- a/test/595-profile-saving/profile-saving.cc +++ b/test/595-profile-saving/profile-saving.cc @@ -17,7 +17,7 @@ #include "dex_file.h" #include "art_method-inl.h" -#include "jit/offline_profiling_info.h" +#include "jit/profile_compilation_info.h" #include "jit/profile_saver.h" #include "jni.h" #include "method_reference.h" diff --git a/test/921-hello-failure/expected.txt b/test/921-hello-failure/expected.txt index 1c1d4d9b80..9615e6b33d 100644 --- a/test/921-hello-failure/expected.txt +++ b/test/921-hello-failure/expected.txt @@ -21,3 +21,11 @@ hello2 - MultiRedef Transformation error : java.lang.Exception(Failed to redefine classes <LTransform;, LTransform2;> due to JVMTI_ERROR_NAMES_DONT_MATCH) hello - MultiRedef hello2 - MultiRedef +hello - MultiRetrans +hello2 - MultiRetrans +Transformation error : java.lang.Exception(Failed to retransform classes <LTransform2;, LTransform;> due to JVMTI_ERROR_NAMES_DONT_MATCH) +hello - MultiRetrans +hello2 - MultiRetrans +Transformation error : java.lang.Exception(Failed to retransform classes <LTransform;, LTransform2;> due to JVMTI_ERROR_NAMES_DONT_MATCH) +hello - MultiRetrans +hello2 - MultiRetrans diff --git a/test/921-hello-failure/src/Main.java b/test/921-hello-failure/src/Main.java index 1fe259961d..43d6e9ed07 100644 --- a/test/921-hello-failure/src/Main.java +++ b/test/921-hello-failure/src/Main.java @@ -25,6 +25,7 @@ public class Main { MissingInterface.doTest(new Transform2()); ReorderInterface.doTest(new Transform2()); MultiRedef.doTest(new Transform(), new Transform2()); + MultiRetrans.doTest(new Transform(), new Transform2()); } // Transforms the class. This throws an exception if something goes wrong. @@ -47,7 +48,20 @@ public class Main { dex_files.toArray(new byte[0][])); } + public static void addMultiTransformationResults(CommonClassDefinition... defs) throws Exception { + for (CommonClassDefinition d : defs) { + addCommonTransformationResult(d.target.getCanonicalName(), + d.class_file_bytes, + d.dex_file_bytes); + } + } + public static native void doCommonMultiClassRedefinition(Class<?>[] targets, byte[][] classfiles, byte[][] dexfiles) throws Exception; + public static native void doCommonClassRetransformation(Class<?>... target) throws Exception; + public static native void enableCommonRetransformation(boolean enable); + public static native void addCommonTransformationResult(String target_name, + byte[] class_bytes, + byte[] dex_bytes); } diff --git a/test/921-hello-failure/src/MultiRetrans.java b/test/921-hello-failure/src/MultiRetrans.java new file mode 100644 index 0000000000..95aaf074e9 --- /dev/null +++ b/test/921-hello-failure/src/MultiRetrans.java @@ -0,0 +1,108 @@ +/* + * Copyright (C) 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.Base64; + +class MultiRetrans { + + // class NotTransform { + // public void sayHi(String name) { + // throw new Error("Should not be called!"); + // } + // } + private static CommonClassDefinition INVALID_DEFINITION_T1 = new CommonClassDefinition( + Transform.class, + Base64.getDecoder().decode( + "yv66vgAAADQAFQoABgAPBwAQCAARCgACABIHABMHABQBAAY8aW5pdD4BAAMoKVYBAARDb2RlAQAP" + + "TGluZU51bWJlclRhYmxlAQAFc2F5SGkBABUoTGphdmEvbGFuZy9TdHJpbmc7KVYBAApTb3VyY2VG" + + "aWxlAQARTm90VHJhbnNmb3JtLmphdmEMAAcACAEAD2phdmEvbGFuZy9FcnJvcgEAFVNob3VsZCBu" + + "b3QgYmUgY2FsbGVkIQwABwAMAQAMTm90VHJhbnNmb3JtAQAQamF2YS9sYW5nL09iamVjdAAgAAUA" + + "BgAAAAAAAgAAAAcACAABAAkAAAAdAAEAAQAAAAUqtwABsQAAAAEACgAAAAYAAQAAAAEAAQALAAwA" + + "AQAJAAAAIgADAAIAAAAKuwACWRIDtwAEvwAAAAEACgAAAAYAAQAAAAMAAQANAAAAAgAO"), + Base64.getDecoder().decode( + "ZGV4CjAzNQDLV95i5xnv6iUi6uIeDoY5jP5Xe9NP1AiYAgAAcAAAAHhWNBIAAAAAAAAAAAQCAAAL" + + "AAAAcAAAAAUAAACcAAAAAgAAALAAAAAAAAAAAAAAAAQAAADIAAAAAQAAAOgAAACQAQAACAEAAEoB" + + "AABSAQAAYgEAAHUBAACJAQAAnQEAALABAADHAQAAygEAAM4BAADiAQAAAQAAAAIAAAADAAAABAAA" + + "AAcAAAAHAAAABAAAAAAAAAAIAAAABAAAAEQBAAAAAAAAAAAAAAAAAQAKAAAAAQABAAAAAAACAAAA" + + "AAAAAAAAAAAAAAAAAgAAAAAAAAAFAAAAAAAAAPQBAAAAAAAAAQABAAEAAADpAQAABAAAAHAQAwAA" + + "AA4ABAACAAIAAADuAQAACQAAACIAAQAbAQYAAABwIAIAEAAnAAAAAQAAAAMABjxpbml0PgAOTE5v" + + "dFRyYW5zZm9ybTsAEUxqYXZhL2xhbmcvRXJyb3I7ABJMamF2YS9sYW5nL09iamVjdDsAEkxqYXZh" + + "L2xhbmcvU3RyaW5nOwARTm90VHJhbnNmb3JtLmphdmEAFVNob3VsZCBub3QgYmUgY2FsbGVkIQAB" + + "VgACVkwAEmVtaXR0ZXI6IGphY2stNC4yMAAFc2F5SGkAAQAHDgADAQAHDgAAAAEBAICABIgCAQGg" + + "AgAADAAAAAAAAAABAAAAAAAAAAEAAAALAAAAcAAAAAIAAAAFAAAAnAAAAAMAAAACAAAAsAAAAAUA" + + "AAAEAAAAyAAAAAYAAAABAAAA6AAAAAEgAAACAAAACAEAAAEQAAABAAAARAEAAAIgAAALAAAASgEA" + + "AAMgAAACAAAA6QEAAAAgAAABAAAA9AEAAAAQAAABAAAABAIAAA==")); + + // Valid redefinition of Transform2 + // class Transform2 implements Iface1, Iface2 { + // public void sayHi(String name) { + // throw new Error("Should not be called!"); + // } + // } + private static CommonClassDefinition VALID_DEFINITION_T2 = new CommonClassDefinition( + Transform2.class, + Base64.getDecoder().decode( + "yv66vgAAADQAGQoABgARBwASCAATCgACABQHABUHABYHABcHABgBAAY8aW5pdD4BAAMoKVYBAARD" + + "b2RlAQAPTGluZU51bWJlclRhYmxlAQAFc2F5SGkBABUoTGphdmEvbGFuZy9TdHJpbmc7KVYBAApT" + + "b3VyY2VGaWxlAQAPVHJhbnNmb3JtMi5qYXZhDAAJAAoBAA9qYXZhL2xhbmcvRXJyb3IBABVTaG91" + + "bGQgbm90IGJlIGNhbGxlZCEMAAkADgEAClRyYW5zZm9ybTIBABBqYXZhL2xhbmcvT2JqZWN0AQAG" + + "SWZhY2UxAQAGSWZhY2UyACAABQAGAAIABwAIAAAAAgAAAAkACgABAAsAAAAdAAEAAQAAAAUqtwAB" + + "sQAAAAEADAAAAAYAAQAAAAEAAQANAA4AAQALAAAAIgADAAIAAAAKuwACWRIDtwAEvwAAAAEADAAA" + + "AAYAAQAAAAMAAQAPAAAAAgAQ"), + Base64.getDecoder().decode( + "ZGV4CjAzNQDSWls05CPkX+gbTGMVRvx9dc9vozzVbu7AAgAAcAAAAHhWNBIAAAAAAAAAACwCAAAN" + + "AAAAcAAAAAcAAACkAAAAAgAAAMAAAAAAAAAAAAAAAAQAAADYAAAAAQAAAPgAAACoAQAAGAEAAGIB" + + "AABqAQAAdAEAAH4BAACMAQAAnwEAALMBAADHAQAA3gEAAO8BAADyAQAA9gEAAAoCAAABAAAAAgAA" + + "AAMAAAAEAAAABQAAAAYAAAAJAAAACQAAAAYAAAAAAAAACgAAAAYAAABcAQAAAgAAAAAAAAACAAEA" + + "DAAAAAMAAQAAAAAABAAAAAAAAAACAAAAAAAAAAQAAABUAQAACAAAAAAAAAAcAgAAAAAAAAEAAQAB" + + "AAAAEQIAAAQAAABwEAMAAAAOAAQAAgACAAAAFgIAAAkAAAAiAAMAGwEHAAAAcCACABAAJwAAAAIA" + + "AAAAAAEAAQAAAAUABjxpbml0PgAITElmYWNlMTsACExJZmFjZTI7AAxMVHJhbnNmb3JtMjsAEUxq" + + "YXZhL2xhbmcvRXJyb3I7ABJMamF2YS9sYW5nL09iamVjdDsAEkxqYXZhL2xhbmcvU3RyaW5nOwAV" + + "U2hvdWxkIG5vdCBiZSBjYWxsZWQhAA9UcmFuc2Zvcm0yLmphdmEAAVYAAlZMABJlbWl0dGVyOiBq" + + "YWNrLTQuMjAABXNheUhpAAEABw4AAwEABw4AAAABAQCAgASYAgEBsAIAAAwAAAAAAAAAAQAAAAAA" + + "AAABAAAADQAAAHAAAAACAAAABwAAAKQAAAADAAAAAgAAAMAAAAAFAAAABAAAANgAAAAGAAAAAQAA" + + "APgAAAABIAAAAgAAABgBAAABEAAAAgAAAFQBAAACIAAADQAAAGIBAAADIAAAAgAAABECAAAAIAAA" + + "AQAAABwCAAAAEAAAAQAAACwCAAA=")); + + public static void doTest(Transform t1, Transform2 t2) { + t1.sayHi("MultiRetrans"); + t2.sayHi("MultiRetrans"); + try { + Main.addMultiTransformationResults(VALID_DEFINITION_T2, INVALID_DEFINITION_T1); + Main.enableCommonRetransformation(true); + Main.doCommonClassRetransformation(Transform2.class, Transform.class); + } catch (Exception e) { + System.out.println( + "Transformation error : " + e.getClass().getName() + "(" + e.getMessage() + ")"); + } finally { + Main.enableCommonRetransformation(false); + } + t1.sayHi("MultiRetrans"); + t2.sayHi("MultiRetrans"); + try { + Main.addMultiTransformationResults(VALID_DEFINITION_T2, INVALID_DEFINITION_T1); + Main.enableCommonRetransformation(true); + Main.doCommonClassRetransformation(Transform.class, Transform2.class); + } catch (Exception e) { + System.out.println( + "Transformation error : " + e.getClass().getName() + "(" + e.getMessage() + ")"); + } finally { + Main.enableCommonRetransformation(false); + } + t1.sayHi("MultiRetrans"); + t2.sayHi("MultiRetrans"); + } +} diff --git a/test/930-hello-retransform/build b/test/930-hello-retransform/build new file mode 100755 index 0000000000..898e2e54a2 --- /dev/null +++ b/test/930-hello-retransform/build @@ -0,0 +1,17 @@ +#!/bin/bash +# +# Copyright 2016 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +./default-build "$@" --experimental agents diff --git a/test/930-hello-retransform/expected.txt b/test/930-hello-retransform/expected.txt new file mode 100644 index 0000000000..4774b81b49 --- /dev/null +++ b/test/930-hello-retransform/expected.txt @@ -0,0 +1,2 @@ +hello +Goodbye diff --git a/test/930-hello-retransform/info.txt b/test/930-hello-retransform/info.txt new file mode 100644 index 0000000000..875a5f6ec1 --- /dev/null +++ b/test/930-hello-retransform/info.txt @@ -0,0 +1 @@ +Tests basic functions in the jvmti plugin. diff --git a/test/930-hello-retransform/run b/test/930-hello-retransform/run new file mode 100755 index 0000000000..4379349cb2 --- /dev/null +++ b/test/930-hello-retransform/run @@ -0,0 +1,19 @@ +#!/bin/bash +# +# Copyright 2016 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +./default-run "$@" --experimental agents \ + --experimental runtime-plugins \ + --jvmti diff --git a/test/930-hello-retransform/src/Main.java b/test/930-hello-retransform/src/Main.java new file mode 100644 index 0000000000..12194c3235 --- /dev/null +++ b/test/930-hello-retransform/src/Main.java @@ -0,0 +1,70 @@ +/* + * Copyright (C) 2016 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.Base64; +public class Main { + + /** + * base64 encoded class/dex file for + * class Transform { + * public void sayHi() { + * System.out.println("Goodbye"); + * } + * } + */ + private static final byte[] CLASS_BYTES = Base64.getDecoder().decode( + "yv66vgAAADQAHAoABgAOCQAPABAIABEKABIAEwcAFAcAFQEABjxpbml0PgEAAygpVgEABENvZGUB" + + "AA9MaW5lTnVtYmVyVGFibGUBAAVzYXlIaQEAClNvdXJjZUZpbGUBAA5UcmFuc2Zvcm0uamF2YQwA" + + "BwAIBwAWDAAXABgBAAdHb29kYnllBwAZDAAaABsBAAlUcmFuc2Zvcm0BABBqYXZhL2xhbmcvT2Jq" + + "ZWN0AQAQamF2YS9sYW5nL1N5c3RlbQEAA291dAEAFUxqYXZhL2lvL1ByaW50U3RyZWFtOwEAE2ph" + + "dmEvaW8vUHJpbnRTdHJlYW0BAAdwcmludGxuAQAVKExqYXZhL2xhbmcvU3RyaW5nOylWACAABQAG" + + "AAAAAAACAAAABwAIAAEACQAAAB0AAQABAAAABSq3AAGxAAAAAQAKAAAABgABAAAAEQABAAsACAAB" + + "AAkAAAAlAAIAAQAAAAmyAAISA7YABLEAAAABAAoAAAAKAAIAAAATAAgAFAABAAwAAAACAA0="); + private static final byte[] DEX_BYTES = Base64.getDecoder().decode( + "ZGV4CjAzNQCLXSBQ5FiS3f16krSYZFF8xYZtFVp0GRXMAgAAcAAAAHhWNBIAAAAAAAAAACwCAAAO" + + "AAAAcAAAAAYAAACoAAAAAgAAAMAAAAABAAAA2AAAAAQAAADgAAAAAQAAAAABAACsAQAAIAEAAGIB" + + "AABqAQAAcwEAAIABAACXAQAAqwEAAL8BAADTAQAA4wEAAOYBAADqAQAA/gEAAAMCAAAMAgAAAgAA" + + "AAMAAAAEAAAABQAAAAYAAAAIAAAACAAAAAUAAAAAAAAACQAAAAUAAABcAQAABAABAAsAAAAAAAAA" + + "AAAAAAAAAAANAAAAAQABAAwAAAACAAAAAAAAAAAAAAAAAAAAAgAAAAAAAAAHAAAAAAAAAB4CAAAA" + + "AAAAAQABAAEAAAATAgAABAAAAHAQAwAAAA4AAwABAAIAAAAYAgAACQAAAGIAAAAbAQEAAABuIAIA" + + "EAAOAAAAAQAAAAMABjxpbml0PgAHR29vZGJ5ZQALTFRyYW5zZm9ybTsAFUxqYXZhL2lvL1ByaW50" + + "U3RyZWFtOwASTGphdmEvbGFuZy9PYmplY3Q7ABJMamF2YS9sYW5nL1N0cmluZzsAEkxqYXZhL2xh" + + "bmcvU3lzdGVtOwAOVHJhbnNmb3JtLmphdmEAAVYAAlZMABJlbWl0dGVyOiBqYWNrLTMuMzYAA291" + + "dAAHcHJpbnRsbgAFc2F5SGkAEQAHDgATAAcOhQAAAAEBAICABKACAQG4Ag0AAAAAAAAAAQAAAAAA" + + "AAABAAAADgAAAHAAAAACAAAABgAAAKgAAAADAAAAAgAAAMAAAAAEAAAAAQAAANgAAAAFAAAABAAA" + + "AOAAAAAGAAAAAQAAAAABAAABIAAAAgAAACABAAABEAAAAQAAAFwBAAACIAAADgAAAGIBAAADIAAA" + + "AgAAABMCAAAAIAAAAQAAAB4CAAAAEAAAAQAAACwCAAA="); + + public static void main(String[] args) { + System.loadLibrary(args[1]); + doTest(new Transform()); + } + + public static void doTest(Transform t) { + t.sayHi(); + addCommonTransformationResult("Transform", CLASS_BYTES, DEX_BYTES); + enableCommonRetransformation(true); + doCommonClassRetransformation(Transform.class); + t.sayHi(); + } + + // Transforms the class + private static native void doCommonClassRetransformation(Class<?>... target); + private static native void enableCommonRetransformation(boolean enable); + private static native void addCommonTransformationResult(String target_name, + byte[] class_bytes, + byte[] dex_bytes); +} diff --git a/test/930-hello-retransform/src/Transform.java b/test/930-hello-retransform/src/Transform.java new file mode 100644 index 0000000000..8e8af355da --- /dev/null +++ b/test/930-hello-retransform/src/Transform.java @@ -0,0 +1,28 @@ +/* + * Copyright (C) 2016 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +class Transform { + public void sayHi() { + // Use lower 'h' to make sure the string will have a different string id + // than the transformation (the transformation code is the same except + // the actual printed String, which was making the test inacurately passing + // in JIT mode when loading the string from the dex cache, as the string ids + // of the two different strings were the same). + // We know the string ids will be different because lexicographically: + // "Goodbye" < "LTransform;" < "hello". + System.out.println("hello"); + } +} diff --git a/test/931-agent-thread/agent_thread.cc b/test/931-agent-thread/agent_thread.cc new file mode 100644 index 0000000000..6ace4cea68 --- /dev/null +++ b/test/931-agent-thread/agent_thread.cc @@ -0,0 +1,132 @@ +/* + * Copyright (C) 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +#include <inttypes.h> + +#include "barrier.h" +#include "base/logging.h" +#include "base/macros.h" +#include "jni.h" +#include "openjdkjvmti/jvmti.h" +#include "runtime.h" +#include "ScopedLocalRef.h" +#include "thread-inl.h" +#include "well_known_classes.h" + +#include "ti-agent/common_helper.h" +#include "ti-agent/common_load.h" + +namespace art { +namespace Test930AgentThread { + +struct AgentData { + AgentData() : main_thread(nullptr), + jvmti_env(nullptr), + b(2) { + } + + jthread main_thread; + jvmtiEnv* jvmti_env; + Barrier b; + jint priority; +}; + +static void AgentMain(jvmtiEnv* jenv, JNIEnv* env, void* arg) { + AgentData* data = reinterpret_cast<AgentData*>(arg); + + // Check some basics. + // This thread is not the main thread. + jthread this_thread; + jvmtiError this_thread_result = jenv->GetCurrentThread(&this_thread); + CHECK(!JvmtiErrorToException(env, this_thread_result)); + CHECK(!env->IsSameObject(this_thread, data->main_thread)); + + // The thread is a daemon. + jvmtiThreadInfo info; + jvmtiError info_result = jenv->GetThreadInfo(this_thread, &info); + CHECK(!JvmtiErrorToException(env, info_result)); + CHECK(info.is_daemon); + + // The thread has the requested priority. + // TODO: Our thread priorities do not work on the host. + // CHECK_EQ(info.priority, data->priority); + + // Check further parts of the thread: + jint thread_count; + jthread* threads; + jvmtiError threads_result = jenv->GetAllThreads(&thread_count, &threads); + CHECK(!JvmtiErrorToException(env, threads_result)); + bool found = false; + for (jint i = 0; i != thread_count; ++i) { + if (env->IsSameObject(threads[i], this_thread)) { + found = true; + break; + } + } + CHECK(found); + + // Done, let the main thread progress. + data->b.Pass(Thread::Current()); +} + +extern "C" JNIEXPORT void JNICALL Java_Main_testAgentThread( + JNIEnv* env, jclass Main_klass ATTRIBUTE_UNUSED) { + // Create a Thread object. + ScopedLocalRef<jobject> thread_name(env, + env->NewStringUTF("Agent Thread")); + if (thread_name.get() == nullptr) { + return; + } + + ScopedLocalRef<jobject> thread(env, env->AllocObject(WellKnownClasses::java_lang_Thread)); + if (thread.get() == nullptr) { + return; + } + + env->CallNonvirtualVoidMethod(thread.get(), + WellKnownClasses::java_lang_Thread, + WellKnownClasses::java_lang_Thread_init, + Runtime::Current()->GetMainThreadGroup(), + thread_name.get(), + kMinThreadPriority, + JNI_FALSE); + if (env->ExceptionCheck()) { + return; + } + + jthread main_thread; + jvmtiError main_thread_result = jvmti_env->GetCurrentThread(&main_thread); + if (JvmtiErrorToException(env, main_thread_result)) { + return; + } + + AgentData data; + data.main_thread = env->NewGlobalRef(main_thread); + data.jvmti_env = jvmti_env; + data.priority = JVMTI_THREAD_MIN_PRIORITY; + + jvmtiError result = jvmti_env->RunAgentThread(thread.get(), AgentMain, &data, data.priority); + if (JvmtiErrorToException(env, result)) { + return; + } + + data.b.Wait(Thread::Current()); + + env->DeleteGlobalRef(data.main_thread); +} + +} // namespace Test930AgentThread +} // namespace art diff --git a/test/931-agent-thread/build b/test/931-agent-thread/build new file mode 100755 index 0000000000..898e2e54a2 --- /dev/null +++ b/test/931-agent-thread/build @@ -0,0 +1,17 @@ +#!/bin/bash +# +# Copyright 2016 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +./default-build "$@" --experimental agents diff --git a/test/931-agent-thread/expected.txt b/test/931-agent-thread/expected.txt new file mode 100644 index 0000000000..a965a70ed4 --- /dev/null +++ b/test/931-agent-thread/expected.txt @@ -0,0 +1 @@ +Done diff --git a/test/931-agent-thread/info.txt b/test/931-agent-thread/info.txt new file mode 100644 index 0000000000..875a5f6ec1 --- /dev/null +++ b/test/931-agent-thread/info.txt @@ -0,0 +1 @@ +Tests basic functions in the jvmti plugin. diff --git a/test/931-agent-thread/run b/test/931-agent-thread/run new file mode 100755 index 0000000000..0a8d0672f6 --- /dev/null +++ b/test/931-agent-thread/run @@ -0,0 +1,23 @@ +#!/bin/bash +# +# Copyright 2016 The Android Open Source Project +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. + +# This test checks whether dex files can be injected into parent classloaders. App images preload +# classes, which will make the injection moot. Turn off app images to avoid the issue. + +./default-run "$@" --experimental agents \ + --experimental runtime-plugins \ + --jvmti \ + --no-app-image diff --git a/test/931-agent-thread/src/Main.java b/test/931-agent-thread/src/Main.java new file mode 100644 index 0000000000..6471bc8437 --- /dev/null +++ b/test/931-agent-thread/src/Main.java @@ -0,0 +1,29 @@ +/* + * Copyright (C) 2017 The Android Open Source Project + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + +import java.util.Arrays; + +public class Main { + public static void main(String[] args) throws Exception { + System.loadLibrary(args[1]); + + testAgentThread(); + + System.out.println("Done"); + } + + private static native void testAgentThread(); +} diff --git a/test/Android.bp b/test/Android.bp index 965d07aa43..be5bc59e5c 100644 --- a/test/Android.bp +++ b/test/Android.bp @@ -269,6 +269,7 @@ art_cc_defaults { "927-timers/timers.cc", "928-jni-table/jni_table.cc", "929-search/search.cc", + "931-agent-thread/agent_thread.cc", ], shared_libs: [ "libbase", diff --git a/test/Android.run-test.mk b/test/Android.run-test.mk index e604c93c72..c8e2185891 100644 --- a/test/Android.run-test.mk +++ b/test/Android.run-test.mk @@ -309,6 +309,8 @@ TEST_ART_BROKEN_TARGET_TESTS += \ 927-timers \ 928-jni-table \ 929-search \ + 930-hello-retransform \ + 931-agent-thread \ ifneq (,$(filter target,$(TARGET_TYPES))) ART_TEST_KNOWN_BROKEN += $(call all-run-test-names,target,$(RUN_TYPES),$(PREBUILD_TYPES), \ diff --git a/test/XandY/Y.java b/test/XandY/Y.java index ecead6e35f..2a1f03698c 100644 --- a/test/XandY/Y.java +++ b/test/XandY/Y.java @@ -14,4 +14,8 @@ * limitations under the License. */ -class Y extends X {} +class Y extends X { + static Z z = new Z(); + static class Z { + } +} diff --git a/test/etc/run-test-jar b/test/etc/run-test-jar index 5f1071f658..28fa130443 100755 --- a/test/etc/run-test-jar +++ b/test/etc/run-test-jar @@ -44,7 +44,7 @@ STRIP_DEX="n" SECONDARY_DEX="" TIME_OUT="gdb" # "n" (disabled), "timeout" (use timeout), "gdb" (use gdb) # Value in seconds -if [ "$ART_USE_READ_BARRIER" = "true" ]; then +if [ "$ART_USE_READ_BARRIER" != "false" ]; then TIME_OUT_VALUE=2400 # 40 minutes. else TIME_OUT_VALUE=1200 # 20 minutes. diff --git a/test/run-test b/test/run-test index a913e783d3..9b178021ff 100755 --- a/test/run-test +++ b/test/run-test @@ -722,7 +722,7 @@ if [[ "$TEST_NAME" =~ ^[0-9]+-checker- ]]; then # # TODO: Enable Checker when read barrier support is added to more # architectures (b/12687968). - if [ "x$ART_USE_READ_BARRIER" = xtrue ] \ + if [ "x$ART_USE_READ_BARRIER" != xfalse ] \ && (([ "x$host_mode" = "xyes" ] \ && ! arch_supports_read_barrier "$host_arch_name") \ || ([ "x$target_mode" = "xyes" ] \ diff --git a/test/ti-agent/common_helper.cc b/test/ti-agent/common_helper.cc index 2c6d3eda00..8799c9188b 100644 --- a/test/ti-agent/common_helper.cc +++ b/test/ti-agent/common_helper.cc @@ -18,6 +18,7 @@ #include <stdio.h> #include <sstream> +#include <deque> #include "art_method.h" #include "jni.h" @@ -60,17 +61,17 @@ bool JvmtiErrorToException(JNIEnv* env, jvmtiError error) { return true; } -namespace common_redefine { -static void throwRedefinitionError(jvmtiEnv* jvmti, - JNIEnv* env, - jint num_targets, - jclass* target, - jvmtiError res) { +template <bool is_redefine> +static void throwCommonRedefinitionError(jvmtiEnv* jvmti, + JNIEnv* env, + jint num_targets, + jclass* target, + jvmtiError res) { std::stringstream err; char* error = nullptr; jvmti->GetErrorName(res, &error); - err << "Failed to redefine class"; + err << "Failed to " << (is_redefine ? "redefine" : "retransform") << " class"; if (num_targets > 1) { err << "es"; } @@ -92,6 +93,16 @@ static void throwRedefinitionError(jvmtiEnv* jvmti, env->ThrowNew(env->FindClass("java/lang/Exception"), message.c_str()); } +namespace common_redefine { + +static void throwRedefinitionError(jvmtiEnv* jvmti, + JNIEnv* env, + jint num_targets, + jclass* target, + jvmtiError res) { + return throwCommonRedefinitionError<true>(jvmti, env, num_targets, target, res); +} + static void DoMultiClassRedefine(jvmtiEnv* jvmti_env, JNIEnv* env, jint num_redefines, @@ -161,7 +172,7 @@ extern "C" JNIEXPORT void JNICALL Java_Main_doCommonMultiClassRedefinition( dex_files.data()); } -// Don't do anything +// Get all capabilities except those related to retransformation. jint OnLoad(JavaVM* vm, char* options ATTRIBUTE_UNUSED, void* reserved ATTRIBUTE_UNUSED) { @@ -169,10 +180,148 @@ jint OnLoad(JavaVM* vm, printf("Unable to get jvmti env!\n"); return 1; } - SetAllCapabilities(jvmti_env); + jvmtiCapabilities caps; + jvmti_env->GetPotentialCapabilities(&caps); + caps.can_retransform_classes = 0; + caps.can_retransform_any_class = 0; + jvmti_env->AddCapabilities(&caps); return 0; } } // namespace common_redefine +namespace common_retransform { + +struct CommonTransformationResult { + std::vector<unsigned char> class_bytes; + std::vector<unsigned char> dex_bytes; + + CommonTransformationResult(size_t class_size, size_t dex_size) + : class_bytes(class_size), dex_bytes(dex_size) {} + + CommonTransformationResult() = default; + CommonTransformationResult(CommonTransformationResult&&) = default; + CommonTransformationResult(CommonTransformationResult&) = default; +}; + +// Map from class name to transformation result. +std::map<std::string, std::deque<CommonTransformationResult>> gTransformations; + +extern "C" JNIEXPORT void JNICALL Java_Main_addCommonTransformationResult(JNIEnv* env, + jclass, + jstring class_name, + jbyteArray class_array, + jbyteArray dex_array) { + const char* name_chrs = env->GetStringUTFChars(class_name, nullptr); + std::string name_str(name_chrs); + env->ReleaseStringUTFChars(class_name, name_chrs); + CommonTransformationResult trans(env->GetArrayLength(class_array), + env->GetArrayLength(dex_array)); + if (env->ExceptionOccurred()) { + return; + } + env->GetByteArrayRegion(class_array, + 0, + env->GetArrayLength(class_array), + reinterpret_cast<jbyte*>(trans.class_bytes.data())); + if (env->ExceptionOccurred()) { + return; + } + env->GetByteArrayRegion(dex_array, + 0, + env->GetArrayLength(dex_array), + reinterpret_cast<jbyte*>(trans.dex_bytes.data())); + if (env->ExceptionOccurred()) { + return; + } + if (gTransformations.find(name_str) == gTransformations.end()) { + std::deque<CommonTransformationResult> list; + gTransformations[name_str] = std::move(list); + } + gTransformations[name_str].push_back(std::move(trans)); +} + +// The hook we are using. +void JNICALL CommonClassFileLoadHookRetransformable(jvmtiEnv* jvmti_env, + JNIEnv* jni_env ATTRIBUTE_UNUSED, + jclass class_being_redefined ATTRIBUTE_UNUSED, + jobject loader ATTRIBUTE_UNUSED, + const char* name, + jobject protection_domain ATTRIBUTE_UNUSED, + jint class_data_len ATTRIBUTE_UNUSED, + const unsigned char* class_dat ATTRIBUTE_UNUSED, + jint* new_class_data_len, + unsigned char** new_class_data) { + std::string name_str(name); + if (gTransformations.find(name_str) != gTransformations.end()) { + CommonTransformationResult& res = gTransformations[name_str][0]; + const std::vector<unsigned char>& desired_array = IsJVM() ? res.class_bytes : res.dex_bytes; + unsigned char* new_data; + jvmti_env->Allocate(desired_array.size(), &new_data); + memcpy(new_data, desired_array.data(), desired_array.size()); + *new_class_data = new_data; + *new_class_data_len = desired_array.size(); + gTransformations[name_str].pop_front(); + } +} + +extern "C" JNIEXPORT void Java_Main_enableCommonRetransformation(JNIEnv* env, + jclass, + jboolean enable) { + jvmtiError res = jvmti_env->SetEventNotificationMode(enable ? JVMTI_ENABLE : JVMTI_DISABLE, + JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, + nullptr); + if (res != JVMTI_ERROR_NONE) { + JvmtiErrorToException(env, res); + } +} + +static void throwRetransformationError(jvmtiEnv* jvmti, + JNIEnv* env, + jint num_targets, + jclass* targets, + jvmtiError res) { + return throwCommonRedefinitionError<false>(jvmti, env, num_targets, targets, res); +} + +static void DoClassRetransformation(jvmtiEnv* jvmti_env, JNIEnv* env, jobjectArray targets) { + std::vector<jclass> classes; + jint len = env->GetArrayLength(targets); + for (jint i = 0; i < len; i++) { + classes.push_back(static_cast<jclass>(env->GetObjectArrayElement(targets, i))); + } + jvmtiError res = jvmti_env->RetransformClasses(len, classes.data()); + if (res != JVMTI_ERROR_NONE) { + throwRetransformationError(jvmti_env, env, len, classes.data(), res); + } +} + +// TODO Write something useful. +extern "C" JNIEXPORT void JNICALL Java_Main_doCommonClassRetransformation(JNIEnv* env, + jclass, + jobjectArray targets) { + DoClassRetransformation(jvmti_env, env, targets); +} + +// Get all capabilities except those related to retransformation. +jint OnLoad(JavaVM* vm, + char* options ATTRIBUTE_UNUSED, + void* reserved ATTRIBUTE_UNUSED) { + if (vm->GetEnv(reinterpret_cast<void**>(&jvmti_env), JVMTI_VERSION_1_0)) { + printf("Unable to get jvmti env!\n"); + return 1; + } + SetAllCapabilities(jvmti_env); + jvmtiEventCallbacks cb; + memset(&cb, 0, sizeof(cb)); + cb.ClassFileLoadHook = CommonClassFileLoadHookRetransformable; + if (jvmti_env->SetEventCallbacks(&cb, sizeof(cb)) != JVMTI_ERROR_NONE) { + printf("Unable to set class file load hook cb!\n"); + return 1; + } + return 0; +} + +} // namespace common_retransform + } // namespace art diff --git a/test/ti-agent/common_helper.h b/test/ti-agent/common_helper.h index 642ca03274..8599fc4d6c 100644 --- a/test/ti-agent/common_helper.h +++ b/test/ti-agent/common_helper.h @@ -27,6 +27,10 @@ namespace common_redefine { jint OnLoad(JavaVM* vm, char* options, void* reserved); } // namespace common_redefine +namespace common_retransform { +jint OnLoad(JavaVM* vm, char* options, void* reserved); +} // namespace common_retransform + extern bool RuntimeIsJVM; diff --git a/test/ti-agent/common_load.cc b/test/ti-agent/common_load.cc index 521e672330..1b11442092 100644 --- a/test/ti-agent/common_load.cc +++ b/test/ti-agent/common_load.cc @@ -64,8 +64,9 @@ AgentLib agents[] = { { "916-obsolete-jit", common_redefine::OnLoad, nullptr }, { "917-fields-transformation", common_redefine::OnLoad, nullptr }, { "919-obsolete-fields", common_redefine::OnLoad, nullptr }, - { "921-hello-failure", common_redefine::OnLoad, nullptr }, + { "921-hello-failure", common_retransform::OnLoad, nullptr }, { "926-multi-obsolescence", common_redefine::OnLoad, nullptr }, + { "930-hello-retransform", common_retransform::OnLoad, nullptr }, }; static AgentLib* FindAgent(char* name) { diff --git a/test/valgrind-suppressions.txt b/test/valgrind-suppressions.txt index fd3c3318ce..c148ad01e1 100644 --- a/test/valgrind-suppressions.txt +++ b/test/valgrind-suppressions.txt @@ -22,3 +22,27 @@ ... fun:_ZN3art7Runtime17InitNativeMethodsEv } + +# SigQuit runs libbacktrace +{ + BackTraceReading64 + Memcheck:Addr8 + fun:access_mem_unrestricted + fun:_Uelf64_memory_read + fun:_Uelf64_valid_object_memory + fun:map_create_list + fun:unw_map_local_create + fun:_ZN14UnwindMapLocal5BuildEv + fun:_ZN12BacktraceMap6CreateEib +} +{ + BackTraceReading32 + Memcheck:Addr4 + fun:access_mem_unrestricted + fun:_Uelf32_memory_read + fun:_Uelf32_valid_object_memory + fun:map_create_list + fun:unw_map_local_create + fun:_ZN14UnwindMapLocal5BuildEv + fun:_ZN12BacktraceMap6CreateEib +} |