Merge "Revert "CHA for abstract methods.""
diff --git a/build/Android.common_build.mk b/build/Android.common_build.mk
index 4c82506..f5a95fa 100644
--- a/build/Android.common_build.mk
+++ b/build/Android.common_build.mk
@@ -46,6 +46,9 @@
$(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 5bdfbc7..d8b780a 100644
--- a/build/Android.gtest.mk
+++ b/build/Android.gtest.mk
@@ -107,6 +107,7 @@
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_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 e6e0544..84269c3 100644
--- a/build/art.go
+++ b/build/art.go
@@ -58,7 +58,7 @@
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 f4838c1..0d45a50 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 6bfdd4d..503fe3a 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 12684c0..1e4ca16 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 4f06a91..5fc9972 100644
--- a/compiler/verifier_deps_test.cc
+++ b/compiler/verifier_deps_test.cc
@@ -1414,7 +1414,14 @@
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 @@
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 3fbdb89..e8a92c1 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 cdb3b9f..e86e560 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 02274b2..75d47e4 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 cac6090..1add6bf 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 5f8a118..ad599ae 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 d3c75b8..be703ab 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 776c31a..2f40fef 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 e538407..ffebb6a 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 86019bf..81f174e 100644
--- a/runtime/Android.bp
+++ b/runtime/Android.bp
@@ -112,7 +112,7 @@
"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 @@
"reference_table.cc",
"reflection.cc",
"runtime.cc",
+ "runtime_callbacks.cc",
"runtime_options.cc",
"signal_catcher.cc",
"stack.cc",
@@ -563,6 +564,7 @@
"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 49cffed..14918df 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 @@
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 @@
* 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 9b98671..8da979b 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 @@
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 743fcc8..fc82264 100644
--- a/runtime/common_runtime_test.cc
+++ b/runtime/common_runtime_test.cc
@@ -133,7 +133,9 @@
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 @@
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 006476b..22a3163 100644
--- a/runtime/debugger.cc
+++ b/runtime/debugger.cc
@@ -320,6 +320,9 @@
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::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 3b4a5e1..a7fd160 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 @@
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 @@
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 @@
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 @@
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 b0c4597..7ae9f03 100644
--- a/runtime/dex2oat_environment_test.h
+++ b/runtime/dex2oat_environment_test.h
@@ -160,7 +160,7 @@
// 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 e71a397..4c6b5bf 100644
--- a/runtime/gc/space/large_object_space.cc
+++ b/runtime/gc/space/large_object_space.cc
@@ -141,16 +141,6 @@
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 76777d9..28bcb97 100644
--- a/runtime/interpreter/interpreter_common.cc
+++ b/runtime/interpreter/interpreter_common.cc
@@ -596,7 +596,7 @@
// 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 b7125a8..2bb8819 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 05c3905..4112142 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
similarity index 99%
rename from runtime/jit/offline_profiling_info.cc
rename to runtime/jit/profile_compilation_info.cc
index 6f2a8c6..1405c40 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
similarity index 97%
rename from runtime/jit/offline_profiling_info.h
rename to runtime/jit/profile_compilation_info.h
index 53d0eea..f8061bc 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 @@
} // 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 1dd1e36..835a5f3 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 59e2c94..9c5e41f 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 3b3ab5a..953b445 100644
--- a/runtime/oat.h
+++ b/runtime/oat.h
@@ -32,7 +32,7 @@
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 afa804c..84eacde 100644
--- a/runtime/oat_file_assistant_test.cc
+++ b/runtime/oat_file_assistant_test.cc
@@ -152,15 +152,17 @@
}
}
- 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/Android.bp b/runtime/openjdkjvmti/Android.bp
index d5c6520..acdd0d3 100644
--- a/runtime/openjdkjvmti/Android.bp
+++ b/runtime/openjdkjvmti/Android.bp
@@ -27,6 +27,7 @@
"ti_method.cc",
"ti_monitor.cc",
"ti_object.cc",
+ "ti_phase.cc",
"ti_properties.cc",
"ti_search.cc",
"ti_stack.cc",
diff --git a/runtime/openjdkjvmti/OpenjdkJvmTi.cc b/runtime/openjdkjvmti/OpenjdkJvmTi.cc
index 90467db..fcedd4e 100644
--- a/runtime/openjdkjvmti/OpenjdkJvmTi.cc
+++ b/runtime/openjdkjvmti/OpenjdkJvmTi.cc
@@ -55,6 +55,7 @@
#include "ti_method.h"
#include "ti_monitor.h"
#include "ti_object.h"
+#include "ti_phase.h"
#include "ti_properties.h"
#include "ti_redefine.h"
#include "ti_search.h"
@@ -194,15 +195,15 @@
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) {
- return ERR(NOT_IMPLEMENTED);
+ return ThreadUtil::SetThreadLocalStorage(env, thread, data);
}
static jvmtiError GetThreadLocalStorage(jvmtiEnv* env, jthread thread, void** data_ptr) {
- return ERR(NOT_IMPLEMENTED);
+ return ThreadUtil::GetThreadLocalStorage(env, thread, data_ptr);
}
static jvmtiError GetTopThreadGroups(jvmtiEnv* env,
@@ -593,7 +594,7 @@
jclass klass,
jint* minor_version_ptr,
jint* major_version_ptr) {
- return ERR(NOT_IMPLEMENTED);
+ return ClassUtil::GetClassVersionNumbers(env, klass, minor_version_ptr, major_version_ptr);
}
static jvmtiError GetConstantPool(jvmtiEnv* env,
@@ -631,7 +632,17 @@
}
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,
@@ -1089,11 +1100,12 @@
}
static jvmtiError GetPhase(jvmtiEnv* env, jvmtiPhase* phase_ptr) {
- return ERR(NOT_IMPLEMENTED);
+ return PhaseUtil::GetPhase(env, phase_ptr);
}
static jvmtiError DisposeEnvironment(jvmtiEnv* env) {
ENSURE_VALID_ENV(env);
+ gEventHandler.RemoveArtJvmTiEnv(ArtJvmTiEnv::AsArtJvmTiEnv(env));
delete env;
return OK;
}
@@ -1255,78 +1267,6 @@
*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) {
@@ -1362,17 +1302,23 @@
// The plugin initialization function. This adds the jvmti environment.
extern "C" bool ArtPlugin_Initialize() {
art::Runtime* runtime = art::Runtime::Current();
+
+ if (runtime->IsStarted()) {
+ PhaseUtil::SetToLive();
+ } else {
+ PhaseUtil::SetToOnLoad();
+ }
+ PhaseUtil::Register(&gEventHandler);
+
runtime->GetJavaVM()->AddEnvironmentHook(GetEnvHandler);
runtime->AddSystemWeakHolder(&gObjectTagTable);
+
return true;
}
// 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 5eadc5a..1c84d4d 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 @@
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 @@
.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 @@
.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 1e07bc6..21ec731 100644
--- a/runtime/openjdkjvmti/events-inl.h
+++ b/runtime/openjdkjvmti/events-inl.h
@@ -115,9 +115,95 @@
}
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.cc b/runtime/openjdkjvmti/events.cc
index f38aa86..7182055 100644
--- a/runtime/openjdkjvmti/events.cc
+++ b/runtime/openjdkjvmti/events.cc
@@ -144,6 +144,18 @@
envs.push_back(env);
}
+void EventHandler::RemoveArtJvmTiEnv(ArtJvmTiEnv* env) {
+ auto it = std::find(envs.begin(), envs.end(), env);
+ if (it != envs.end()) {
+ envs.erase(it);
+ for (size_t i = static_cast<size_t>(ArtJvmtiEvent::kMinEventTypeVal);
+ i <= static_cast<size_t>(ArtJvmtiEvent::kMaxEventTypeVal);
+ ++i) {
+ RecalculateGlobalEventMask(static_cast<ArtJvmtiEvent>(i));
+ }
+ }
+}
+
static bool IsThreadControllable(ArtJvmtiEvent event) {
switch (event) {
case ArtJvmtiEvent::kVmInit:
diff --git a/runtime/openjdkjvmti/events.h b/runtime/openjdkjvmti/events.h
index 7990141..8e246de 100644
--- a/runtime/openjdkjvmti/events.h
+++ b/runtime/openjdkjvmti/events.h
@@ -141,6 +141,9 @@
// enabled, yet.
void RegisterArtJvmTiEnv(ArtJvmTiEnv* env);
+ // Remove an env.
+ void RemoveArtJvmTiEnv(ArtJvmTiEnv* env);
+
bool IsEventEnabledAnywhere(ArtJvmtiEvent event) const {
if (!EventMask::EventIsInRange(event)) {
return false;
@@ -178,6 +181,15 @@
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_class.cc b/runtime/openjdkjvmti/ti_class.cc
index d1324bc..abcc849 100644
--- a/runtime/openjdkjvmti/ti_class.cc
+++ b/runtime/openjdkjvmti/ti_class.cc
@@ -417,4 +417,35 @@
return ERR(NONE);
}
+jvmtiError ClassUtil::GetClassVersionNumbers(jvmtiEnv* env ATTRIBUTE_UNUSED,
+ jclass jklass,
+ jint* minor_version_ptr,
+ jint* major_version_ptr) {
+ art::ScopedObjectAccess soa(art::Thread::Current());
+ if (jklass == nullptr) {
+ return ERR(INVALID_CLASS);
+ }
+ art::ObjPtr<art::mirror::Object> jklass_obj = soa.Decode<art::mirror::Object>(jklass);
+ if (!jklass_obj->IsClass()) {
+ return ERR(INVALID_CLASS);
+ }
+ art::ObjPtr<art::mirror::Class> klass = jklass_obj->AsClass();
+ if (klass->IsPrimitive() || klass->IsArrayClass()) {
+ return ERR(INVALID_CLASS);
+ }
+
+ if (minor_version_ptr == nullptr || major_version_ptr == nullptr) {
+ return ERR(NULL_POINTER);
+ }
+
+ // Note: proxies will show the dex file version of java.lang.reflect.Proxy, as that is
+ // what their dex cache copies from.
+ uint32_t version = klass->GetDexFile().GetHeader().GetVersion();
+
+ *major_version_ptr = static_cast<jint>(version);
+ *minor_version_ptr = 0;
+
+ return ERR(NONE);
+}
+
} // namespace openjdkjvmti
diff --git a/runtime/openjdkjvmti/ti_class.h b/runtime/openjdkjvmti/ti_class.h
index 7a0fafb..9558894 100644
--- a/runtime/openjdkjvmti/ti_class.h
+++ b/runtime/openjdkjvmti/ti_class.h
@@ -72,6 +72,11 @@
static jvmtiError IsInterface(jvmtiEnv* env, jclass klass, jboolean* is_interface_ptr);
static jvmtiError IsArrayClass(jvmtiEnv* env, jclass klass, jboolean* is_array_class_ptr);
+
+ static jvmtiError GetClassVersionNumbers(jvmtiEnv* env,
+ jclass klass,
+ jint* minor_version_ptr,
+ jint* major_version_ptr);
};
} // namespace openjdkjvmti
diff --git a/runtime/openjdkjvmti/ti_phase.cc b/runtime/openjdkjvmti/ti_phase.cc
new file mode 100644
index 0000000..85d6b72
--- /dev/null
+++ b/runtime/openjdkjvmti/ti_phase.cc
@@ -0,0 +1,129 @@
+/* Copyright (C) 2017 The Android Open Source Project
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This file implements interfaces from the file jvmti.h. This implementation
+ * is licensed under the same terms as the file jvmti.h. The
+ * copyright and license information for the file jvmti.h follows.
+ *
+ * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+#include "ti_phase.h"
+
+#include "art_jvmti.h"
+#include "base/macros.h"
+#include "events-inl.h"
+#include "runtime.h"
+#include "runtime_callbacks.h"
+#include "ScopedLocalRef.h"
+#include "scoped_thread_state_change-inl.h"
+#include "thread-inl.h"
+#include "thread_list.h"
+
+namespace openjdkjvmti {
+
+jvmtiPhase PhaseUtil::current_phase_ = static_cast<jvmtiPhase>(0);
+
+struct PhaseUtil::PhaseCallback : public art::RuntimePhaseCallback {
+ inline static JNIEnv* GetJniEnv() {
+ return reinterpret_cast<JNIEnv*>(art::Thread::Current()->GetJniEnv());
+ }
+
+ inline static jthread GetCurrentJThread() {
+ art::ScopedObjectAccess soa(art::Thread::Current());
+ return soa.AddLocalReference<jthread>(soa.Self()->GetPeer());
+ }
+
+ void NextRuntimePhase(RuntimePhase phase) OVERRIDE {
+ // TODO: Events.
+ switch (phase) {
+ case RuntimePhase::kInitialAgents:
+ PhaseUtil::current_phase_ = JVMTI_PHASE_PRIMORDIAL;
+ break;
+ case RuntimePhase::kStart:
+ event_handler->DispatchEvent(nullptr, ArtJvmtiEvent::kVmStart, GetJniEnv());
+ PhaseUtil::current_phase_ = JVMTI_PHASE_START;
+ break;
+ case RuntimePhase::kInit:
+ {
+ ScopedLocalRef<jthread> thread(GetJniEnv(), GetCurrentJThread());
+ event_handler->DispatchEvent(nullptr,
+ ArtJvmtiEvent::kVmInit,
+ GetJniEnv(),
+ thread.get());
+ PhaseUtil::current_phase_ = JVMTI_PHASE_LIVE;
+ }
+ break;
+ case RuntimePhase::kDeath:
+ event_handler->DispatchEvent(nullptr, ArtJvmtiEvent::kVmDeath, GetJniEnv());
+ PhaseUtil::current_phase_ = JVMTI_PHASE_DEAD;
+ // TODO: Block events now.
+ break;
+ }
+ }
+
+ EventHandler* event_handler = nullptr;
+};
+
+PhaseUtil::PhaseCallback gPhaseCallback;
+
+jvmtiError PhaseUtil::GetPhase(jvmtiEnv* env ATTRIBUTE_UNUSED, jvmtiPhase* phase_ptr) {
+ if (phase_ptr == nullptr) {
+ return ERR(NULL_POINTER);
+ }
+ jvmtiPhase now = PhaseUtil::current_phase_;
+ DCHECK(now == JVMTI_PHASE_ONLOAD ||
+ now == JVMTI_PHASE_PRIMORDIAL ||
+ now == JVMTI_PHASE_START ||
+ now == JVMTI_PHASE_LIVE ||
+ now == JVMTI_PHASE_DEAD);
+ *phase_ptr = now;
+ return ERR(NONE);
+}
+
+void PhaseUtil::SetToOnLoad() {
+ DCHECK_EQ(0u, static_cast<size_t>(PhaseUtil::current_phase_));
+ PhaseUtil::current_phase_ = JVMTI_PHASE_ONLOAD;
+}
+
+void PhaseUtil::SetToPrimordial() {
+ DCHECK_EQ(static_cast<size_t>(JVMTI_PHASE_ONLOAD), static_cast<size_t>(PhaseUtil::current_phase_));
+ PhaseUtil::current_phase_ = JVMTI_PHASE_ONLOAD;
+}
+
+void PhaseUtil::SetToLive() {
+ DCHECK_EQ(static_cast<size_t>(0), static_cast<size_t>(PhaseUtil::current_phase_));
+ PhaseUtil::current_phase_ = JVMTI_PHASE_LIVE;
+}
+
+void PhaseUtil::Register(EventHandler* handler) {
+ gPhaseCallback.event_handler = handler;
+ art::ScopedThreadStateChange stsc(art::Thread::Current(),
+ art::ThreadState::kWaitingForDebuggerToAttach);
+ art::ScopedSuspendAll ssa("Add phase callback");
+ art::Runtime::Current()->GetRuntimeCallbacks()->AddRuntimePhaseCallback(&gPhaseCallback);
+}
+
+
+} // namespace openjdkjvmti
diff --git a/runtime/openjdkjvmti/ti_phase.h b/runtime/openjdkjvmti/ti_phase.h
new file mode 100644
index 0000000..054652a
--- /dev/null
+++ b/runtime/openjdkjvmti/ti_phase.h
@@ -0,0 +1,65 @@
+/* Copyright (C) 2017 The Android Open Source Project
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This file implements interfaces from the file jvmti.h. This implementation
+ * is licensed under the same terms as the file jvmti.h. The
+ * copyright and license information for the file jvmti.h follows.
+ *
+ * Copyright (c) 2003, 2011, Oracle and/or its affiliates. All rights reserved.
+ * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
+ *
+ * This code is free software; you can redistribute it and/or modify it
+ * under the terms of the GNU General Public License version 2 only, as
+ * published by the Free Software Foundation. Oracle designates this
+ * particular file as subject to the "Classpath" exception as provided
+ * by Oracle in the LICENSE file that accompanied this code.
+ *
+ * This code is distributed in the hope that it will be useful, but WITHOUT
+ * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
+ * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
+ * version 2 for more details (a copy is included in the LICENSE file that
+ * accompanied this code).
+ *
+ * You should have received a copy of the GNU General Public License version
+ * 2 along with this work; if not, write to the Free Software Foundation,
+ * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
+ *
+ * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
+ * or visit www.oracle.com if you need additional information or have any
+ * questions.
+ */
+
+#ifndef ART_RUNTIME_OPENJDKJVMTI_TI_PHASE_H_
+#define ART_RUNTIME_OPENJDKJVMTI_TI_PHASE_H_
+
+#include "jni.h"
+#include "jvmti.h"
+
+namespace openjdkjvmti {
+
+class EventHandler;
+
+class PhaseUtil {
+ public:
+ static jvmtiError GetPhase(jvmtiEnv* env, jvmtiPhase* phase_ptr);
+
+ static void Register(EventHandler* event_handler);
+
+ // Move the phase from unitialized to LOAD.
+ static void SetToOnLoad();
+
+ // Move the phase from LOAD to PRIMORDIAL.
+ static void SetToPrimordial();
+
+ // Move the phase from unitialized to LIVE.
+ static void SetToLive();
+
+ struct PhaseCallback;
+
+ private:
+ static jvmtiPhase current_phase_;
+};
+
+} // namespace openjdkjvmti
+
+#endif // ART_RUNTIME_OPENJDKJVMTI_TI_PHASE_H_
diff --git a/runtime/openjdkjvmti/ti_redefine.cc b/runtime/openjdkjvmti/ti_redefine.cc
index 6af51c4..2db8a40 100644
--- a/runtime/openjdkjvmti/ti_redefine.cc
+++ b/runtime/openjdkjvmti/ti_redefine.cc
@@ -242,14 +242,12 @@
}
}
-// 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 @@
*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 @@
/*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 @@
// 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 8626bc5..f8d51ad 100644
--- a/runtime/openjdkjvmti/ti_redefine.h
+++ b/runtime/openjdkjvmti/ti_redefine.h
@@ -72,13 +72,25 @@
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 @@
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 2bcdd8c..970cc24 100644
--- a/runtime/openjdkjvmti/ti_thread.cc
+++ b/runtime/openjdkjvmti/ti_thread.cc
@@ -443,4 +443,80 @@
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 290e9d4..5aaec58 100644
--- a/runtime/openjdkjvmti/ti_thread.h
+++ b/runtime/openjdkjvmti/ti_thread.h
@@ -49,6 +49,12 @@
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 f545125..2809cb6 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 @@
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 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();
- // 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);
+// 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*>(*dex_data),
- reinterpret_cast<const void*>(dex.Begin()),
- *data_len);
+ 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.
+// 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);
+ }
+ 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)));
+ 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?
+ 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;
+ }
+ }
return OK;
}
diff --git a/runtime/openjdkjvmti/transform.h b/runtime/openjdkjvmti/transform.h
index 0ad5099..0ff2bd1 100644
--- a/runtime/openjdkjvmti/transform.h
+++ b/runtime/openjdkjvmti/transform.h
@@ -43,16 +43,30 @@
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 75176f9..a2b4cb3 100644
--- a/runtime/reflection.cc
+++ b/runtime/reflection.cc
@@ -216,43 +216,54 @@
}
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 @@
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 @@
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 55e1852..4936a2f 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 @@
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 @@
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 @@
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 @@
0);
}
+ // Send the initialized phase event.
+ {
+ ScopedObjectAccess soa(self);
+ callbacks_->NextRuntimePhase(RuntimePhaseCallback::RuntimePhase::kInit);
+ }
+
return true;
}
@@ -1100,6 +1123,8 @@
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()) {
@@ -1358,6 +1383,10 @@
LOG(ERROR) << "Unable to load an agent: " << err;
}
}
+ {
+ ScopedObjectAccess soa(self);
+ callbacks_->NextRuntimePhase(RuntimePhaseCallback::RuntimePhase::kInitialAgents);
+ }
VLOG(startup) << "Runtime::Init exiting";
@@ -1370,7 +1399,7 @@
constexpr const char* plugin_name = kIsDebugBuild ? "libopenjdkjvmtid.so" : "libopenjdkjvmti.so";
// Is the plugin already loaded?
- for (Plugin p : *plugins) {
+ for (const Plugin& p : *plugins) {
if (p.GetLibrary() == plugin_name) {
return true;
}
@@ -1547,6 +1576,12 @@
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 +2288,8 @@
Runtime::Abort(abort_message);
}
+RuntimeCallbacks* Runtime::GetRuntimeCallbacks() {
+ return callbacks_.get();
+}
+
} // namespace art
diff --git a/runtime/runtime.h b/runtime/runtime.h
index cf23d05..f7d6810 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 OatFileManager;
class Plugin;
struct RuntimeArgumentMap;
+class RuntimeCallbacks;
class SignalCatcher;
class StackOverflowHandler;
class SuspensionHandler;
@@ -659,6 +661,8 @@
void AttachAgent(const std::string& agent_arg);
+ RuntimeCallbacks* GetRuntimeCallbacks();
+
private:
static void InitPlatformSignalHandlers();
@@ -916,6 +920,8 @@
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 0000000..7b15a4f
--- /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 0000000..e580e78
--- /dev/null
+++ b/runtime/runtime_callbacks.h
@@ -0,0 +1,115 @@
+/*
+ * 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 {
+ kInitialAgents, // Initial agent loading is done.
+ 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 0000000..8974b59
--- /dev/null
+++ b/runtime/runtime_callbacks_test.cc
@@ -0,0 +1,410 @@
+/*
+ * 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::kInitialAgents) {
+ if (start_seen > 0 || init_seen > 0 || death_seen > 0) {
+ LOG(FATAL) << "Unexpected order";
+ }
+ ++initial_agents_seen;
+ } else if (p == RuntimePhaseCallback::RuntimePhase::kStart) {
+ if (init_seen > 0 || death_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 initial_agents_seen = 0;
+ 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_.initial_agents_seen);
+ 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(0u, cb_.initial_agents_seen);
+ 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(0u, cb_.initial_agents_seen);
+ 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 ebf14c1..d93eab1 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 @@
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 @@
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 @@
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 @@
{
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 @@
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 2b451bc..b609e72 100644
--- a/runtime/thread.h
+++ b/runtime/thread.h
@@ -158,6 +158,8 @@
// 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 @@
~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 @@
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 15cc566..1131607 100644
--- a/runtime/verifier/verifier_deps.cc
+++ b/runtime/verifier/verifier_deps.cc
@@ -963,20 +963,25 @@
// 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 @@
const char* name = dex_file.GetMethodName(method_id);
const Signature signature = dex_file.GetMethodSignature(method_id);
- const char* descriptor = dex_file.GetMethodDeclaringClassDescriptor(method_id);
+ // 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, descriptor, class_loader);
+ 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 @@
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 bf3d812..0f8dd57 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/901-hello-ti-agent/basics.cc b/test/901-hello-ti-agent/basics.cc
index 052fb9a..0b17656 100644
--- a/test/901-hello-ti-agent/basics.cc
+++ b/test/901-hello-ti-agent/basics.cc
@@ -28,6 +28,46 @@
namespace art {
namespace Test901HelloTi {
+static void EnableEvent(jvmtiEnv* env, jvmtiEvent evt) {
+ jvmtiError error = env->SetEventNotificationMode(JVMTI_ENABLE, evt, nullptr);
+ if (error != JVMTI_ERROR_NONE) {
+ printf("Failed to enable event");
+ }
+}
+
+static void JNICALL VMStartCallback(jvmtiEnv *jenv ATTRIBUTE_UNUSED,
+ JNIEnv* jni_env ATTRIBUTE_UNUSED) {
+ printf("VMStart\n");
+}
+
+static void JNICALL VMInitCallback(jvmtiEnv *jvmti_env ATTRIBUTE_UNUSED,
+ JNIEnv* jni_env ATTRIBUTE_UNUSED,
+ jthread thread ATTRIBUTE_UNUSED) {
+ printf("VMInit\n");
+}
+
+static void JNICALL VMDeatchCallback(jvmtiEnv *jenv ATTRIBUTE_UNUSED,
+ JNIEnv* jni_env ATTRIBUTE_UNUSED) {
+ printf("VMDeath\n");
+}
+
+
+static void InstallVMEvents(jvmtiEnv* env) {
+ jvmtiEventCallbacks callbacks;
+ memset(&callbacks, 0, sizeof(jvmtiEventCallbacks));
+ callbacks.VMStart = VMStartCallback;
+ callbacks.VMInit = VMInitCallback;
+ callbacks.VMDeath = VMDeatchCallback;
+ jvmtiError ret = env->SetEventCallbacks(&callbacks, sizeof(callbacks));
+ if (ret != JVMTI_ERROR_NONE) {
+ printf("Failed to install callbacks");
+ }
+
+ EnableEvent(env, JVMTI_EVENT_VM_START);
+ EnableEvent(env, JVMTI_EVENT_VM_INIT);
+ EnableEvent(env, JVMTI_EVENT_VM_DEATH);
+}
+
jint OnLoad(JavaVM* vm,
char* options ATTRIBUTE_UNUSED,
void* reserved ATTRIBUTE_UNUSED) {
@@ -72,6 +112,10 @@
printf("Unexpected version number!\n");
return -1;
}
+
+ InstallVMEvents(env);
+ InstallVMEvents(env2);
+
CHECK_CALL_SUCCESS(env->DisposeEnvironment());
CHECK_CALL_SUCCESS(env2->DisposeEnvironment());
#undef CHECK_CALL_SUCCESS
@@ -82,6 +126,19 @@
}
SetAllCapabilities(jvmti_env);
+ jvmtiPhase current_phase;
+ jvmtiError phase_result = jvmti_env->GetPhase(¤t_phase);
+ if (phase_result != JVMTI_ERROR_NONE) {
+ printf("Could not get phase");
+ return 1;
+ }
+ if (current_phase != JVMTI_PHASE_ONLOAD) {
+ printf("Wrong phase");
+ return 1;
+ }
+
+ InstallVMEvents(jvmti_env);
+
return JNI_OK;
}
@@ -92,5 +149,15 @@
JvmtiErrorToException(env, result);
}
+extern "C" JNIEXPORT jboolean JNICALL Java_Main_checkLivePhase(
+ JNIEnv* env, jclass Main_klass ATTRIBUTE_UNUSED) {
+ jvmtiPhase current_phase;
+ jvmtiError phase_result = jvmti_env->GetPhase(¤t_phase);
+ if (JvmtiErrorToException(env, phase_result)) {
+ return JNI_FALSE;
+ }
+ return (current_phase == JVMTI_PHASE_LIVE) ? JNI_TRUE : JNI_FALSE;
+}
+
} // namespace Test901HelloTi
} // namespace art
diff --git a/test/901-hello-ti-agent/expected.txt b/test/901-hello-ti-agent/expected.txt
index 2aee99b..c4b24cb 100644
--- a/test/901-hello-ti-agent/expected.txt
+++ b/test/901-hello-ti-agent/expected.txt
@@ -1,8 +1,12 @@
Loaded Agent for test 901-hello-ti-agent
+VMStart
+VMInit
Hello, world!
+Agent in live phase.
0
1
2
4
8
JVMTI_ERROR_ILLEGAL_ARGUMENT
+VMDeath
diff --git a/test/901-hello-ti-agent/src/Main.java b/test/901-hello-ti-agent/src/Main.java
index 775e5c2..faf2dc2 100644
--- a/test/901-hello-ti-agent/src/Main.java
+++ b/test/901-hello-ti-agent/src/Main.java
@@ -20,6 +20,10 @@
System.out.println("Hello, world!");
+ if (checkLivePhase()) {
+ System.out.println("Agent in live phase.");
+ }
+
set(0); // OTHER
set(1); // GC
set(2); // CLASS
@@ -37,5 +41,6 @@
}
}
+ private static native boolean checkLivePhase();
private static native void setVerboseFlag(int flag, boolean value);
}
diff --git a/test/912-classes/classes.cc b/test/912-classes/classes.cc
index a22d1d7..29eeff6 100644
--- a/test/912-classes/classes.cc
+++ b/test/912-classes/classes.cc
@@ -241,5 +241,23 @@
return ret;
}
+extern "C" JNIEXPORT jintArray JNICALL Java_Main_getClassVersion(
+ JNIEnv* env, jclass Main_klass ATTRIBUTE_UNUSED, jclass klass) {
+ jint major, minor;
+ jvmtiError result = jvmti_env->GetClassVersionNumbers(klass, &minor, &major);
+ if (JvmtiErrorToException(env, result)) {
+ return nullptr;
+ }
+
+ jintArray int_array = env->NewIntArray(2);
+ if (int_array == nullptr) {
+ return nullptr;
+ }
+ jint buf[2] = { major, minor };
+ env->SetIntArrayRegion(int_array, 0, 2, buf);
+
+ return int_array;
+}
+
} // namespace Test912Classes
} // namespace art
diff --git a/test/912-classes/expected.txt b/test/912-classes/expected.txt
index a95a465..f3cb261 100644
--- a/test/912-classes/expected.txt
+++ b/test/912-classes/expected.txt
@@ -59,3 +59,5 @@
boot <- src+src-ex (A,B)
912-classes.jar+ ->
[class A, class B, class java.lang.Object]
+
+[37, 0]
diff --git a/test/912-classes/src/Main.java b/test/912-classes/src/Main.java
index ea3c49c..cbf2392 100644
--- a/test/912-classes/src/Main.java
+++ b/test/912-classes/src/Main.java
@@ -80,6 +80,10 @@
testClassLoader(getProxyClass());
testClassLoaderClasses();
+
+ System.out.println();
+
+ testClassVersion();
}
private static Class<?> proxyClass = null;
@@ -202,6 +206,10 @@
}
}
+ private static void testClassVersion() {
+ System.out.println(Arrays.toString(getClassVersion(Main.class)));
+ }
+
private static void printClassLoaderClasses(ClassLoader cl) {
for (;;) {
if (cl == null || !cl.getClass().getName().startsWith("dalvik.system")) {
@@ -262,6 +270,8 @@
private static native Class<?>[] getClassLoaderClasses(ClassLoader cl);
+ private static native int[] getClassVersion(Class<?> c);
+
private static class TestForNonInit {
public static double dummy = Math.random(); // So it can't be compile-time initialized.
}
diff --git a/test/921-hello-failure/expected.txt b/test/921-hello-failure/expected.txt
index 1c1d4d9..9615e6b 100644
--- a/test/921-hello-failure/expected.txt
+++ b/test/921-hello-failure/expected.txt
@@ -21,3 +21,11 @@
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 1fe2599..43d6e9e 100644
--- a/test/921-hello-failure/src/Main.java
+++ b/test/921-hello-failure/src/Main.java
@@ -25,6 +25,7 @@
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 @@
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 0000000..95aaf07
--- /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/924-threads/expected.txt b/test/924-threads/expected.txt
index 32e3368..3b7fb24 100644
--- a/test/924-threads/expected.txt
+++ b/test/924-threads/expected.txt
@@ -29,3 +29,5 @@
5 = ALIVE|RUNNABLE
2 = TERMINATED
[Thread[FinalizerDaemon,5,system], Thread[FinalizerWatchdogDaemon,5,system], Thread[HeapTaskDaemon,5,system], Thread[ReferenceQueueDaemon,5,system], Thread[Signal Catcher,5,system], Thread[main,5,main]]
+JVMTI_ERROR_THREAD_NOT_ALIVE
+JVMTI_ERROR_THREAD_NOT_ALIVE
diff --git a/test/924-threads/src/Main.java b/test/924-threads/src/Main.java
index 492a7ac..dec49a8 100644
--- a/test/924-threads/src/Main.java
+++ b/test/924-threads/src/Main.java
@@ -56,6 +56,8 @@
doStateTests();
doAllThreadsTests();
+
+ doTLSTests();
}
private static class Holder {
@@ -164,6 +166,68 @@
System.out.println(Arrays.toString(threads));
}
+ private static void doTLSTests() throws Exception {
+ doTLSNonLiveTests();
+ doTLSLiveTests();
+ }
+
+ private static void doTLSNonLiveTests() throws Exception {
+ Thread t = new Thread();
+ try {
+ setTLS(t, 1);
+ System.out.println("Expected failure setting TLS for non-live thread");
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ }
+ t.start();
+ t.join();
+ try {
+ setTLS(t, 1);
+ System.out.println("Expected failure setting TLS for non-live thread");
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ }
+ }
+
+ private static void doTLSLiveTests() throws Exception {
+ setTLS(Thread.currentThread(), 1);
+
+ long l = getTLS(Thread.currentThread());
+ if (l != 1) {
+ throw new RuntimeException("Unexpected TLS value: " + l);
+ };
+
+ final CountDownLatch cdl1 = new CountDownLatch(1);
+ final CountDownLatch cdl2 = new CountDownLatch(1);
+
+ Runnable r = new Runnable() {
+ @Override
+ public void run() {
+ try {
+ cdl1.countDown();
+ cdl2.await();
+ setTLS(Thread.currentThread(), 2);
+ if (getTLS(Thread.currentThread()) != 2) {
+ throw new RuntimeException("Different thread issue");
+ }
+ } catch (Exception e) {
+ throw new RuntimeException(e);
+ }
+ }
+ };
+
+ Thread t = new Thread(r);
+ t.start();
+ cdl1.await();
+ setTLS(Thread.currentThread(), 1);
+ cdl2.countDown();
+
+ t.join();
+ if (getTLS(Thread.currentThread()) != 1) {
+ throw new RuntimeException("Got clobbered");
+ }
+ }
+
private final static Comparator<Thread> THREAD_COMP = new Comparator<Thread>() {
public int compare(Thread o1, Thread o2) {
return o1.getName().compareTo(o2.getName());
@@ -229,4 +293,6 @@
private static native Object[] getThreadInfo(Thread t);
private static native int getThreadState(Thread t);
private static native Thread[] getAllThreads();
+ private static native void setTLS(Thread t, long l);
+ private static native long getTLS(Thread t);
}
diff --git a/test/924-threads/threads.cc b/test/924-threads/threads.cc
index 1487b7c..d35eaa8 100644
--- a/test/924-threads/threads.cc
+++ b/test/924-threads/threads.cc
@@ -120,5 +120,22 @@
return ret;
}
+extern "C" JNIEXPORT jlong JNICALL Java_Main_getTLS(
+ JNIEnv* env, jclass Main_klass ATTRIBUTE_UNUSED, jthread thread) {
+ void* tls;
+ jvmtiError result = jvmti_env->GetThreadLocalStorage(thread, &tls);
+ if (JvmtiErrorToException(env, result)) {
+ return 0;
+ }
+ return static_cast<jlong>(reinterpret_cast<uintptr_t>(tls));
+}
+
+extern "C" JNIEXPORT void JNICALL Java_Main_setTLS(
+ JNIEnv* env, jclass Main_klass ATTRIBUTE_UNUSED, jthread thread, jlong val) {
+ const void* tls = reinterpret_cast<void*>(static_cast<uintptr_t>(val));
+ jvmtiError result = jvmti_env->SetThreadLocalStorage(thread, tls);
+ JvmtiErrorToException(env, result);
+}
+
} // namespace Test924Threads
} // namespace art
diff --git a/test/930-hello-retransform/build b/test/930-hello-retransform/build
new file mode 100755
index 0000000..898e2e5
--- /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 0000000..4774b81
--- /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 0000000..875a5f6
--- /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 0000000..4379349
--- /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 0000000..12194c3
--- /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 0000000..8e8af35
--- /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 0000000..6ace4ce
--- /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 0000000..898e2e5
--- /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 0000000..a965a70
--- /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 0000000..875a5f6
--- /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 0000000..0a8d067
--- /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 0000000..6471bc8
--- /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 965d07a..be5bc59 100644
--- a/test/Android.bp
+++ b/test/Android.bp
@@ -269,6 +269,7 @@
"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 e604c93..c8e2185 100644
--- a/test/Android.run-test.mk
+++ b/test/Android.run-test.mk
@@ -309,6 +309,8 @@
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 ecead6e..2a1f036 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 5f1071f..28fa130 100755
--- a/test/etc/run-test-jar
+++ b/test/etc/run-test-jar
@@ -44,7 +44,7 @@
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 a913e78..9b17802 100755
--- a/test/run-test
+++ b/test/run-test
@@ -722,7 +722,7 @@
#
# 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 2c6d3ed..8799c91 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 @@
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 @@
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,138 @@
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) {
+ if (vm->GetEnv(reinterpret_cast<void**>(&jvmti_env), JVMTI_VERSION_1_0)) {
+ printf("Unable to get jvmti env!\n");
+ return 1;
+ }
+ 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) {
@@ -170,9 +312,16 @@
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_redefine
+} // namespace common_retransform
} // namespace art
diff --git a/test/ti-agent/common_helper.h b/test/ti-agent/common_helper.h
index 642ca03..8599fc4 100644
--- a/test/ti-agent/common_helper.h
+++ b/test/ti-agent/common_helper.h
@@ -27,6 +27,10 @@
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 521e672..1b11442 100644
--- a/test/ti-agent/common_load.cc
+++ b/test/ti-agent/common_load.cc
@@ -64,8 +64,9 @@
{ "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 fd3c331..c148ad0 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
+}