From 1d3755952f8b7b58f703da6da7779bfe9603c1a7 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Sat, 15 Aug 2026 13:13:55 +0800 Subject: [PATCH] Feat: migrate libagent from JuiceAgent and port to spdlog --- src/libagent/CMakeLists.txt | 23 +- src/libagent/JuiceAgent.cpp | 96 ++++++ src/libagent/callback/ClassFileLoadHook.cpp | 38 +++ src/libagent/callback/MethodEntry.cpp | 15 + src/libagent/callback/MethodExit.cpp | 19 ++ src/libagent/core/global.cpp | 8 + src/libagent/entry/agent_onload.cpp | 119 +++++++ src/libagent/entry/jni.cpp | 44 +++ src/libagent/includes/JuiceAgent.hpp | 45 +++ ...cn_xiaozhou233_juiceagent_api_JuiceAgent.h | 141 ++++++++ src/libagent/includes/event/event_type.hpp | 48 +++ src/libagent/includes/event/eventbus.hpp | 218 ++++++++++++ src/libagent/includes/global.hpp | 38 +++ src/libagent/includes/jni_impl.hpp | 40 +++ src/libagent/includes/services.hpp | 37 ++ src/libagent/includes/utils.hpp | 43 +++ src/libagent/jni/bytecode.cpp | 320 ++++++++++++++++++ src/libagent/jni/classloader.cpp | 275 +++++++++++++++ src/libagent/jni/instrumentation.cpp | 2 + src/libagent/services/BytecodeService.cpp | 64 ++++ src/libagent/services/JarLoaderService.cpp | 68 ++++ src/libagent/services/ServicesManager.cpp | 38 +++ 22 files changed, 1727 insertions(+), 12 deletions(-) create mode 100644 src/libagent/JuiceAgent.cpp create mode 100644 src/libagent/callback/ClassFileLoadHook.cpp create mode 100644 src/libagent/callback/MethodEntry.cpp create mode 100644 src/libagent/callback/MethodExit.cpp create mode 100644 src/libagent/core/global.cpp create mode 100644 src/libagent/entry/agent_onload.cpp create mode 100644 src/libagent/entry/jni.cpp create mode 100644 src/libagent/includes/JuiceAgent.hpp create mode 100644 src/libagent/includes/cn_xiaozhou233_juiceagent_api_JuiceAgent.h create mode 100644 src/libagent/includes/event/event_type.hpp create mode 100644 src/libagent/includes/event/eventbus.hpp create mode 100644 src/libagent/includes/global.hpp create mode 100644 src/libagent/includes/jni_impl.hpp create mode 100644 src/libagent/includes/services.hpp create mode 100644 src/libagent/includes/utils.hpp create mode 100644 src/libagent/jni/bytecode.cpp create mode 100644 src/libagent/jni/classloader.cpp create mode 100644 src/libagent/jni/instrumentation.cpp create mode 100644 src/libagent/services/BytecodeService.cpp create mode 100644 src/libagent/services/JarLoaderService.cpp create mode 100644 src/libagent/services/ServicesManager.cpp diff --git a/src/libagent/CMakeLists.txt b/src/libagent/CMakeLists.txt index 2fe78bb..5ae9e94 100644 --- a/src/libagent/CMakeLists.txt +++ b/src/libagent/CMakeLists.txt @@ -5,17 +5,16 @@ file( ${CMAKE_CURRENT_SOURCE_DIR}/*.c ) -if (agent_sources) - add_library(agent SHARED ${agent_sources}) +add_library(agent SHARED ${agent_sources}) - target_include_directories(agent PRIVATE - ${CMAKE_SOURCE_DIR}/includes - ${CMAKE_SOURCE_DIR}/includes/jvm - ${CMAKE_SOURCE_DIR}/includes/jvm/win32 - ${CMAKE_CURRENT_SOURCE_DIR}/includes - ) +target_include_directories(agent PRIVATE + ${CMAKE_SOURCE_DIR}/includes + ${CMAKE_SOURCE_DIR}/includes/jvm + ${CMAKE_SOURCE_DIR}/includes/jvm/win32 + ${CMAKE_CURRENT_SOURCE_DIR}/includes +) - target_link_libraries(agent PRIVATE - jvm - ) -endif() +target_link_libraries(agent PRIVATE + ReflectiveDLLInjection + jvm +) \ No newline at end of file diff --git a/src/libagent/JuiceAgent.cpp b/src/libagent/JuiceAgent.cpp new file mode 100644 index 0000000..f2bf2d3 --- /dev/null +++ b/src/libagent/JuiceAgent.cpp @@ -0,0 +1,96 @@ +#include +#include +#include +#include +#include +#include + +namespace JuiceAgent { + // ===== Singleton ===== + Agent& Agent::instance() { + static Agent instance; + return instance; + } + + bool Agent::init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti, std::string& runtime_dir) { + try { + spdlog::info("JuiceAgent Native EntryPoint Invoked!"); + + // ======== neccessary environment check ======== + if (jvm == nullptr) { + spdlog::error("Failed to initialize JuiceAgent: jvm is null"); + return false; + } + if (env == nullptr) { + spdlog::error("Failed to initialize JuiceAgent: env is null"); + return false; + } + if (jvmti == nullptr) { + spdlog::error("Failed to initialize JuiceAgent: jvmti is null"); + return false; + } + JuiceAgent::Config::Config cfg (runtime_dir); + if (!cfg.is_valid()) { + spdlog::error("Failed to initialize JuiceAgent: config is invalid"); + return false; + } + + set_jvm(jvm); + set_jvmti(jvmti); + set_env(env); + set_config(cfg); + spdlog::debug("env: {}, jvmti: {}", fmt::ptr(env), fmt::ptr(jvmti)); + + // Register events for services + JuiceAgent::services::Manager::register_events(); + + // PreLoad Event + eventbus.post(EventPreLoad{ + .jvm = jvm, + .env = env, + .jvmti = jvmti + }); + + // ======== Application ability ======== + jvmtiCapabilities caps{}; + caps.can_get_bytecodes = 1; + caps.can_redefine_classes = 1; + caps.can_redefine_any_class = 1; + caps.can_retransform_classes = 1; + caps.can_retransform_any_class = 1; + caps.can_generate_all_class_hook_events = 1; + jint result = jvmti->AddCapabilities(&caps); + if (result != JNI_OK) { + spdlog::error("Failed to add capabilities: {}", result); + return false; + } + + spdlog::info("Abilities added successfully"); + + // ======== Register callbacks ======== + jvmtiEventCallbacks callbacks{}; + callbacks.ClassFileLoadHook = &ClassFileLoadHook; + result = jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks)); + if (result != JNI_OK) { + spdlog::error("Failed to set event callbacks: {}", result); + } + + // Enable events + result = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, NULL); + if (result != JNI_OK) { + spdlog::error("Failed to enable event notification: {}", result); + } + + // Loaded Event + eventbus.post(EventLoaded{ + .jvm = jvm, + .env = env, + .jvmti = jvmti + }); + return true; + } catch (const std::exception& e) { + spdlog::error("Exception: {}", e.what()); + return false; + } + } +} \ No newline at end of file diff --git a/src/libagent/callback/ClassFileLoadHook.cpp b/src/libagent/callback/ClassFileLoadHook.cpp new file mode 100644 index 0000000..714ce5b --- /dev/null +++ b/src/libagent/callback/ClassFileLoadHook.cpp @@ -0,0 +1,38 @@ +#include +#include + +void JNICALL ClassFileLoadHook( + jvmtiEnv* jvmti_env, + JNIEnv* jni_env, + jclass class_being_redefined, + jobject loader, + const char* name, + jobject protection_domain, + jint class_data_len, + const unsigned char* classbytes, + jint* new_class_data_len, + unsigned char** new_classbytes) { + if (!name) { + spdlog::warn("name is null"); + return; + } + + auto& agent = JuiceAgent::Agent::instance(); + + EventClassFileLoadHook event{ + .jvmti_env = jvmti_env, + .jni_env = jni_env, + .class_being_redefined = class_being_redefined, + .loader = loader, + .name = name, + .protection_domain = protection_domain, + .class_data_len = class_data_len, + .classbytes = classbytes, + .new_class_data_len = new_class_data_len, + .new_classbytes = new_classbytes + }; + + agent.get_eventbus().post(event); + + agent.get_eventbus().post_mutable(event); + } \ No newline at end of file diff --git a/src/libagent/callback/MethodEntry.cpp b/src/libagent/callback/MethodEntry.cpp new file mode 100644 index 0000000..a9eb29d --- /dev/null +++ b/src/libagent/callback/MethodEntry.cpp @@ -0,0 +1,15 @@ +#include +#include + +void JNICALL MethodEntry(jvmtiEnv *jvmti_env, + JNIEnv* jni_env, + jthread thread, + jmethodID method) { + auto& agent = JuiceAgent::Agent::instance(); + agent.get_eventbus().post(EventMethodEntry{ + .jvmti_env = jvmti_env, + .jni_env = jni_env, + .thread = thread, + .method = method + }); + } diff --git a/src/libagent/callback/MethodExit.cpp b/src/libagent/callback/MethodExit.cpp new file mode 100644 index 0000000..9223692 --- /dev/null +++ b/src/libagent/callback/MethodExit.cpp @@ -0,0 +1,19 @@ +#include +#include + +void JNICALL MethodExit(jvmtiEnv *jvmti_env, + JNIEnv* jni_env, + jthread thread, + jmethodID method, + jboolean was_popped_by_exception, + jvalue return_value) { + auto& agent = JuiceAgent::Agent::instance(); + agent.get_eventbus().post(EventMethodExit{ + .jvmti_env = jvmti_env, + .jni_env = jni_env, + .thread = thread, + .method = method, + .was_popped_by_exception = was_popped_by_exception, + .return_value = return_value + }); + } \ No newline at end of file diff --git a/src/libagent/core/global.cpp b/src/libagent/core/global.cpp new file mode 100644 index 0000000..6206983 --- /dev/null +++ b/src/libagent/core/global.cpp @@ -0,0 +1,8 @@ +#include + +std::unordered_set classToCapture; +std::unordered_map classFileDataMap; +std::mutex classDataMutex; + +std::unordered_map> pendingRetransform; +std::mutex pendingRetransformMutex; diff --git a/src/libagent/entry/agent_onload.cpp b/src/libagent/entry/agent_onload.cpp new file mode 100644 index 0000000..efb7fc7 --- /dev/null +++ b/src/libagent/entry/agent_onload.cpp @@ -0,0 +1,119 @@ +#include +#include +#include +#include +#include +#include + +// Global state +static JavaVM* g_vm = nullptr; +static jvmtiEnv* g_jvmti = nullptr; + +// Forward declaration +void JNICALL OnVMInit(jvmtiEnv* jvmti, JNIEnv* env, jthread thread); + +// Utility: check JVMTI error +static bool CheckJvmti(jvmtiError err, const char* action) { + if (err != JVMTI_ERROR_NONE) { + spdlog::error("{} failed, code={}", action, static_cast(err)); + return false; + } + return true; +} + +// VMInit callback +void JNICALL OnVMInit(jvmtiEnv* jvmti, JNIEnv* env, jthread thread) { + spdlog::info("JVMTI VMInit triggered"); + + std::string runtime_dir = std::filesystem::current_path().string(); + + if (runtime_dir.empty()) { + spdlog::error("runtime_dir is empty"); + return; + } + + spdlog::info("Runtime directory: {}", runtime_dir); + + // Inject JuiceAgent-API + // Save bytes to file + std::string hash = + JuiceAgent::Resource::juiceagent_api_bytes_sha256; + + std::string file_name = + hash.substr(0, 8) + "_" + + JuiceAgent::Resource::juiceagent_api_bytes_name; + + std::string juiceagent_api_path = + JuiceAgent::Utils::File::write_to_tempfile( + JuiceAgent::Resource::juiceagent_api_bytes, + JuiceAgent::Resource::juiceagent_api_bytes_len, + file_name + ); + + spdlog::debug("Saved JuiceAgent-API to: {}", juiceagent_api_path); + spdlog::debug("JuiceAgent-API size: {}", JuiceAgent::Resource::juiceagent_api_bytes_len); + spdlog::debug("JuiceAgent-API SHA256: {}", JuiceAgent::Resource::juiceagent_api_bytes_sha256); + + // Inject JuiceAgent jar into system class loader + jint status = jvmti->AddToSystemClassLoaderSearch(juiceagent_api_path.c_str()); + if (status != JNI_OK) { + spdlog::error("AddToSystemClassLoaderSearch failed: {}", status); + return; + } + + spdlog::info("Jar injected successfully: {}", juiceagent_api_path); + + JuiceAgent::Agent& agent = JuiceAgent::Agent::instance(); + agent.init(g_vm, env, g_jvmti, runtime_dir); + + spdlog::info("JuiceAgent initialized successfully"); +} + +// Agent entry +JNIEXPORT jint JNICALL +Agent_OnLoad(JavaVM* vm, char* options, void* reserved) { + Logger::init("libagent.log"); + + spdlog::info("Agent_OnLoad"); + + g_vm = vm; + + // Get JVMTI first + jint result = vm->GetEnv(reinterpret_cast(&g_jvmti), JVMTI_VERSION_1_2); + if (result != JNI_OK || g_jvmti == nullptr) { + spdlog::error("Failed to get JVMTI, code={}", result); + return JNI_ERR; + } + + // Optional capabilities + jvmtiCapabilities caps{}; + CheckJvmti(g_jvmti->AddCapabilities(&caps), "AddCapabilities"); + + // Register callbacks + jvmtiEventCallbacks callbacks{}; + callbacks.VMInit = &OnVMInit; + + if (!CheckJvmti( + g_jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks)), + "SetEventCallbacks")) { + return JNI_ERR; + } + + if (!CheckJvmti( + g_jvmti->SetEventNotificationMode( + JVMTI_ENABLE, + JVMTI_EVENT_VM_INIT, + nullptr), + "Enable VM_INIT")) { + return JNI_ERR; + } + + spdlog::info("Agent loaded, waiting for VMInit..."); + return JNI_OK; +} + +// Optional unload +JNIEXPORT void JNICALL +Agent_OnUnload(JavaVM* vm) { + spdlog::info("Agent_OnUnload"); +} \ No newline at end of file diff --git a/src/libagent/entry/jni.cpp b/src/libagent/entry/jni.cpp new file mode 100644 index 0000000..e6cfed9 --- /dev/null +++ b/src/libagent/entry/jni.cpp @@ -0,0 +1,44 @@ +#include +#include + +// This function is called by Java to initialize the agent. +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init + (JNIEnv *env, jclass , jstring j_runtime_dir) { + Logger::init("libagent.log"); + + spdlog::info("Initializing JuiceAgent..."); + + // Get runtime directory + const char* c_runtime_dir = env->GetStringUTFChars(j_runtime_dir, nullptr); + std::string runtime_dir(c_runtime_dir); + env->ReleaseStringUTFChars(j_runtime_dir, c_runtime_dir); + + if (runtime_dir.empty()) { + spdlog::error("Failed to get runtime directory from argument, runtime_dir is empty"); + return JNI_FALSE; + } + spdlog::info("JuiceAgent got runtime directory: {}", runtime_dir); + + JavaVM* jvm = nullptr; + jvmtiEnv* jvmti = nullptr; + + // Get Java VM + env->GetJavaVM(&jvm); + if (jvm == nullptr) { + spdlog::error("Failed to get JavaVM instance"); + return JNI_FALSE; + } + + // Get JVMTI + jvmtiError err = static_cast(jvm->GetEnv(reinterpret_cast(&jvmti), JVMTI_VERSION_1_2)); + if (err != JVMTI_ERROR_NONE || jvmti == nullptr) { + spdlog::error("Failed to get JVMTI environment, error: {}", static_cast(err)); + return JNI_FALSE; + } + + // Invoke EntryPoint + JuiceAgent::Agent& agent = JuiceAgent::Agent::instance(); + agent.init(jvm, env, jvmti, runtime_dir); + + return JNI_TRUE; +} diff --git a/src/libagent/includes/JuiceAgent.hpp b/src/libagent/includes/JuiceAgent.hpp new file mode 100644 index 0000000..6b94c17 --- /dev/null +++ b/src/libagent/includes/JuiceAgent.hpp @@ -0,0 +1,45 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace JuiceAgent { + class Agent { + private: + JavaVM* jvm; + jvmtiEnv* jvmti; + JNIEnv* env; + EventBus eventbus; + JuiceAgent::Config::Config config; + + private: + Agent() = default; + ~Agent() = default; + + public: + // ===== Singleton ===== + static Agent& instance(); + + Agent(const Agent&) = delete; + Agent& operator=(const Agent&) = delete; + + // EntryPoint + bool init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti, std::string& runtime_dir); + + // getters + JavaVM* get_jvm() const { return jvm; } + jvmtiEnv* get_jvmti() const { return jvmti; } + JNIEnv* get_env() const { return env; } + EventBus& get_eventbus() { return eventbus; } + JuiceAgent::Config::Config& get_config() { return config; } + + // setters + void set_jvm(JavaVM* jvm) { this->jvm = jvm; } + void set_jvmti(jvmtiEnv* jvmti) { this->jvmti = jvmti; } + void set_env(JNIEnv* env) { this->env = env; } + void set_config(JuiceAgent::Config::Config& config) { this->config = config; } + }; +} \ No newline at end of file diff --git a/src/libagent/includes/cn_xiaozhou233_juiceagent_api_JuiceAgent.h b/src/libagent/includes/cn_xiaozhou233_juiceagent_api_JuiceAgent.h new file mode 100644 index 0000000..463578c --- /dev/null +++ b/src/libagent/includes/cn_xiaozhou233_juiceagent_api_JuiceAgent.h @@ -0,0 +1,141 @@ +/* DO NOT EDIT THIS FILE - it is machine generated */ +#include +/* Header for class cn_xiaozhou233_juiceagent_api_JuiceAgent */ + +#ifndef _Included_cn_xiaozhou233_juiceagent_api_JuiceAgent +#define _Included_cn_xiaozhou233_juiceagent_api_JuiceAgent +#ifdef __cplusplus +extern "C" { +#endif +/* + * Class: cn_xiaozhou233_juiceagent_api_JuiceAgent + * Method: init + * Signature: (Ljava/lang/String;)Z + */ +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init + (JNIEnv *, jclass, jstring); + +/* + * Class: cn_xiaozhou233_juiceagent_api_JuiceAgent + * Method: addToBootstrapClassLoaderSearch + * Signature: (Ljava/lang/String;)Z + */ +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToBootstrapClassLoaderSearch + (JNIEnv *, jclass, jstring); + +/* + * Class: cn_xiaozhou233_juiceagent_api_JuiceAgent + * Method: addToSystemClassLoaderSearch + * Signature: (Ljava/lang/String;)Z + */ +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToSystemClassLoaderSearch + (JNIEnv *, jclass, jstring); + +/* + * Class: cn_xiaozhou233_juiceagent_api_JuiceAgent + * Method: addToClassLoader + * Signature: (Ljava/lang/String;Ljava/lang/ClassLoader;)Z + */ +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToClassLoader + (JNIEnv *, jclass, jstring, jobject); + +/* + * Class: cn_xiaozhou233_juiceagent_api_JuiceAgent + * Method: defineClass + * Signature: (Ljava/lang/ClassLoader;[B)Ljava/lang/Class; + */ +JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_defineClass + (JNIEnv *, jclass, jobject, jbyteArray); + +/* + * Class: cn_xiaozhou233_juiceagent_api_JuiceAgent + * Method: redefineClass + * Signature: (Ljava/lang/Class;[BI)Z + */ +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClass + (JNIEnv *, jclass, jclass, jbyteArray, jint); + +/* + * Class: cn_xiaozhou233_juiceagent_api_JuiceAgent + * Method: redefineClassByName + * Signature: (Ljava/lang/String;[BI)Z + */ +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClassByName + (JNIEnv *, jclass, jstring, jbyteArray, jint); + +/* + * Class: cn_xiaozhou233_juiceagent_api_JuiceAgent + * Method: retransformClass + * Signature: (Ljava/lang/Class;[BI)Z + */ +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClass + (JNIEnv *, jclass, jclass, jbyteArray, jint); + +/* + * Class: cn_xiaozhou233_juiceagent_api_JuiceAgent + * Method: retransformClassByName + * Signature: (Ljava/lang/String;[BI)Z + */ +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClassByName + (JNIEnv *, jclass, jstring, jbyteArray, jint); + +/* + * Class: cn_xiaozhou233_juiceagent_api_JuiceAgent + * Method: getLoadedClasses + * Signature: ()[Ljava/lang/Class; + */ +JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getLoadedClasses + (JNIEnv *, jclass); + +/* + * Class: cn_xiaozhou233_juiceagent_api_JuiceAgent + * Method: getClassByName + * Signature: (Ljava/lang/String;)Ljava/lang/Class; + */ +JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassByName + (JNIEnv *, jclass, jstring); + +/* + * Class: cn_xiaozhou233_juiceagent_api_JuiceAgent + * Method: getClassBytes + * Signature: (Ljava/lang/Class;)[B + */ +JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytes + (JNIEnv *, jclass, jclass); + +/* + * Class: cn_xiaozhou233_juiceagent_api_JuiceAgent + * Method: getClassBytesByName + * Signature: (Ljava/lang/String;)[B + */ +JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytesByName + (JNIEnv *, jclass, jstring); + +/* + * Class: cn_xiaozhou233_juiceagent_api_JuiceAgent + * Method: addRemapperWhiteList + * Signature: (Ljava/lang/String;)V + */ +JNIEXPORT void JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addRemapperWhiteList + (JNIEnv *, jclass, jstring); + +/* + * Class: cn_xiaozhou233_juiceagent_api_JuiceAgent + * Method: removeRemapperWhiteList + * Signature: (Ljava/lang/String;)V + */ +JNIEXPORT void JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_removeRemapperWhiteList + (JNIEnv *, jclass, jstring); + +/* + * Class: cn_xiaozhou233_juiceagent_api_JuiceAgent + * Method: clearRemapperWhiteList + * Signature: ()V + */ +JNIEXPORT void JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_clearRemapperWhiteList + (JNIEnv *, jclass); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/src/libagent/includes/event/event_type.hpp b/src/libagent/includes/event/event_type.hpp new file mode 100644 index 0000000..f7a20d6 --- /dev/null +++ b/src/libagent/includes/event/event_type.hpp @@ -0,0 +1,48 @@ +#pragma once + +#include + +// ClassFileLoadHook +struct EventClassFileLoadHook { + jvmtiEnv* jvmti_env; + JNIEnv* jni_env; + jclass class_being_redefined; + jobject loader; + const char* name; + jobject protection_domain; + jint class_data_len; + const unsigned char* classbytes; + jint* new_class_data_len; + unsigned char** new_classbytes; +}; + +// MethodEntry +struct EventMethodEntry { + jvmtiEnv* jvmti_env; + JNIEnv* jni_env; + jthread thread; + jmethodID method; +}; + +// MethodExit +struct EventMethodExit { + jvmtiEnv* jvmti_env; + JNIEnv* jni_env; + jthread thread; + jmethodID method; + jboolean was_popped_by_exception; + jvalue return_value; +}; + +// JuiceAgent PreLoad/PostLoad +struct EventPreLoad { + JavaVM* jvm; + JNIEnv* env; + jvmtiEnv* jvmti; +}; + +struct EventLoaded { + JavaVM* jvm; + JNIEnv* env; + jvmtiEnv* jvmti; +}; \ No newline at end of file diff --git a/src/libagent/includes/event/eventbus.hpp b/src/libagent/includes/event/eventbus.hpp new file mode 100644 index 0000000..eb8e4b7 --- /dev/null +++ b/src/libagent/includes/event/eventbus.hpp @@ -0,0 +1,218 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +class EventBus { +public: + using Token = std::uint64_t; + + // === Readonly === + template + using Listener = std::function; + + // === Mutable === + template + using MutableListener = std::function; + + // ========================= + // Subscribe (Readonly) + // ========================= + template + Token subscribe(Listener listener, int priority = 0) { + std::lock_guard lock(mutex_); + + auto& vec = getListeners(); + + Token token = nextToken_++; + + vec.push_back({ + token, + priority, + std::move(listener) + }); + + sort(vec); + return token; + } + + // ========================= + // Subscribe (Mutable) + // ========================= + template + Token subscribe_mutable(MutableListener listener, int priority = 0) { + std::lock_guard lock(mutex_); + + auto& vec = getMutableListeners(); + + Token token = nextToken_++; + + vec.push_back({ + token, + priority, + std::move(listener) + }); + + sort(vec); + return token; + } + + // ========================= + // Unsubscribe + // ========================= + template + bool unsubscribe(Token token) { + std::lock_guard lock(mutex_); + + bool removed = false; + + // readonly + if (auto it = listeners_.find(std::type_index(typeid(Event))); it != listeners_.end()) { + auto& vec = *std::static_pointer_cast>>(it->second); + removed |= erase(vec, token); + } + + // mutable + if (auto it = mutable_listeners_.find(std::type_index(typeid(Event))); it != mutable_listeners_.end()) { + auto& vec = *std::static_pointer_cast>>(it->second); + removed |= erase(vec, token); + } + + return removed; + } + + // ========================= + // Post (Readonly) + // ========================= + template + void post(const Event& event) { + std::vector> copy; + + { + std::lock_guard lock(mutex_); + + auto it = listeners_.find(std::type_index(typeid(Event))); + if (it == listeners_.end()) return; + + copy = *std::static_pointer_cast>>(it->second); + } + + for (auto& node : copy) { + node.callback(event); + } + } + + // ========================= + // Post (Mutable) + // ========================= + template + void post_mutable(Event& event) { + std::vector> copy; + + { + std::lock_guard lock(mutex_); + + auto it = mutable_listeners_.find(std::type_index(typeid(Event))); + if (it == mutable_listeners_.end()) return; + + copy = *std::static_pointer_cast>>(it->second); + } + + for (auto& node : copy) { + node.callback(event); + } + } + + // ========================= + // Clear + // ========================= + template + void clear() { + std::lock_guard lock(mutex_); + listeners_.erase(std::type_index(typeid(Event))); + mutable_listeners_.erase(std::type_index(typeid(Event))); + } + + void clearAll() { + std::lock_guard lock(mutex_); + listeners_.clear(); + mutable_listeners_.clear(); + } + +private: + template + struct Node { + Token token; + int priority; + Listener callback; + }; + + template + struct MutableNode { + Token token; + int priority; + MutableListener callback; + }; + + std::mutex mutex_; + std::atomic nextToken_{1}; + + std::unordered_map> listeners_; + std::unordered_map> mutable_listeners_; + + // === helpers === + + template + static void sort(std::vector& vec) { + std::sort(vec.begin(), vec.end(), + [](const auto& a, const auto& b) { + return a.priority > b.priority; + }); + } + + template + static bool erase(std::vector& vec, Token token) { + auto oldSize = vec.size(); + + vec.erase( + std::remove_if(vec.begin(), vec.end(), + [token](const T& node) { + return node.token == token; + }), + vec.end() + ); + + return vec.size() != oldSize; + } + + template + std::vector>& getListeners() { + return getContainer>(listeners_); + } + + template + std::vector>& getMutableListeners() { + return getContainer>(mutable_listeners_); + } + + template + std::vector& getContainer(std::unordered_map>& map) { + auto type = std::type_index(typeid(Event)); + auto it = map.find(type); + + if (it == map.end()) { + auto ptr = std::make_shared>(); + map[type] = ptr; + return *ptr; + } + + return *std::static_pointer_cast>(it->second); + } +}; \ No newline at end of file diff --git a/src/libagent/includes/global.hpp b/src/libagent/includes/global.hpp new file mode 100644 index 0000000..2507b36 --- /dev/null +++ b/src/libagent/includes/global.hpp @@ -0,0 +1,38 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +// Data Structures +struct ClassRetransformRequest { + std::string classname; + std::vector bytecode; +}; +struct ClassFileData { + std::string classname; + std::vector bytecode; + + // ======== Global references to prevent GC ======== + // Remember to release these references when they are no longer needed, otherwise it will cause memory leaks + jclass clazz; + jobject classloader; + jobject protection_domain; + +}; + +// Set of target class internal names to capture (e.g. java/lang/String) +extern std::unordered_set classToCapture; + +// Cache of captured class bytecode, keyed by internal class name +extern std::unordered_map classFileDataMap; + +// Mutex protecting access to classToCapture and classFileDataMap (thread-safe for JVMTI callbacks) +extern std::mutex classDataMutex; + +extern std::unordered_map> pendingRetransform; +extern std::mutex pendingRetransformMutex; diff --git a/src/libagent/includes/jni_impl.hpp b/src/libagent/includes/jni_impl.hpp new file mode 100644 index 0000000..ff012ab --- /dev/null +++ b/src/libagent/includes/jni_impl.hpp @@ -0,0 +1,40 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +// Generated by JuiceAgent-API +#include + +// Event callbacks +// See https://docs.oracle.com/javase/8/docs/platform/jvmti/jvmti.html#ClassFileLoadHook +void JNICALL ClassFileLoadHook( + jvmtiEnv* jvmti_env, + JNIEnv* jni_env, + jclass class_being_redefined, + jobject loader, + const char* name, + jobject protection_domain, + jint class_data_len, + const unsigned char* classbytes, + jint* new_class_data_len, + unsigned char** new_classbytes); + +// See https://docs.oracle.com/javase/8/docs/platform/jvmti/jvmti.html#MethodEntry +void JNICALL MethodEntry(jvmtiEnv *jvmti_env, + JNIEnv* jni_env, + jthread thread, + jmethodID method); + +// See https://docs.oracle.com/javase/8/docs/platform/jvmti/jvmti.html#MethodExit +void JNICALL MethodExit(jvmtiEnv *jvmti_env, + JNIEnv* jni_env, + jthread thread, + jmethodID method, + jboolean was_popped_by_exception, + jvalue return_value); \ No newline at end of file diff --git a/src/libagent/includes/services.hpp b/src/libagent/includes/services.hpp new file mode 100644 index 0000000..ed9feaf --- /dev/null +++ b/src/libagent/includes/services.hpp @@ -0,0 +1,37 @@ +#pragma once + +#include +#include +#include + +namespace JuiceAgent::services +{ + static JuiceAgent::Agent& agent = JuiceAgent::Agent::instance(); + + namespace Manager { + void register_events(); + void init(const EventPreLoad&); + void start(const EventLoaded&); + void stop(); + } + + namespace JarLoader + { + struct JarLoaderConfig { + bool enabled = false; + std::string injection_dir; + std::string jar_path; + std::string entry_class; + std::string entry_method; + }; + + void init(); + void start(); + } // namespace JarLoader + + namespace Bytecode + { + void init(); + void start(); + } +} // namespace JuiceAgent::services \ No newline at end of file diff --git a/src/libagent/includes/utils.hpp b/src/libagent/includes/utils.hpp new file mode 100644 index 0000000..c07d70a --- /dev/null +++ b/src/libagent/includes/utils.hpp @@ -0,0 +1,43 @@ +#pragma once + +#include + +inline bool check_env(JuiceAgent::Agent& agent) { + if (agent.get_jvm() == nullptr) { + spdlog::error("Failed to get JavaVM instance"); + return false; + } + if (agent.get_jvmti() == nullptr) { + spdlog::error("Failed to get JVMTI environment"); + return false; + } + return true; +} + +inline std::string get_class_name(JNIEnv* env, jclass clazz) { + if (!env || !clazz) return ""; + + jclass clsClass = env->FindClass("java/lang/Class"); + if (!clsClass) return ""; + + jmethodID mid = env->GetMethodID(clsClass, "getName", "()Ljava/lang/String;"); + if (!mid) { + env->DeleteLocalRef(clsClass); + return ""; + } + + jstring nameStr = static_cast(env->CallObjectMethod(clazz, mid)); + std::string result; + + if (nameStr) { + const char* tmp = env->GetStringUTFChars(nameStr, nullptr); + if (tmp) { + result = tmp; // copy to std::string + env->ReleaseStringUTFChars(nameStr, tmp); + } + env->DeleteLocalRef(nameStr); + } + + env->DeleteLocalRef(clsClass); + return result; +} \ No newline at end of file diff --git a/src/libagent/jni/bytecode.cpp b/src/libagent/jni/bytecode.cpp new file mode 100644 index 0000000..7ac8f16 --- /dev/null +++ b/src/libagent/jni/bytecode.cpp @@ -0,0 +1,320 @@ +#include +#include +#include +#include + +// ============================ +// Get class bytecode (already captured) +// ============================ +JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytes + (JNIEnv *env, jclass, jclass clazz) { + + auto& agent = JuiceAgent::Agent::instance(); + if (!check_env(agent)) return nullptr; + + char* signature = nullptr; + if (agent.get_jvmti()->GetClassSignature(clazz, &signature, nullptr) != JVMTI_ERROR_NONE || !signature) + return nullptr; + + // Convert Lxxx; -> xxx + std::string internalName(signature + 1, strlen(signature) - 2); + agent.get_jvmti()->Deallocate(reinterpret_cast(signature)); + + // ============================ + // 1. Mark class for capture + // ============================ + { + std::lock_guard lock(classDataMutex); + classToCapture.insert(internalName); + } + + // ============================ + // 2. Trigger class retransform + // ============================ + jvmtiError err = agent.get_jvmti()->RetransformClasses(1, &clazz); + if (err != JVMTI_ERROR_NONE) { + spdlog::error("Retransform class failed: {}", static_cast(err)); + return nullptr; + } + + // ============================ + // 3. Retrieve bytecode from cache + // ============================ + ClassFileData data; + { + std::lock_guard lock(classDataMutex); + auto it = classFileDataMap.find(internalName); + if (it != classFileDataMap.end()) { + data = it->second; + } + } + + if (data.bytecode.empty()) { + spdlog::error("Failed to capture bytecode for class: {}", internalName); + return nullptr; + } + + jbyteArray out = env->NewByteArray(static_cast(data.bytecode.size())); + if (!out || env->ExceptionCheck()) { + env->ExceptionClear(); + return nullptr; + } + + env->SetByteArrayRegion(out, 0, static_cast(data.bytecode.size()), reinterpret_cast(data.bytecode.data())); + return out; +} + +// ============================ +// Get class bytecode by class name +// ============================ +JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytesByName + (JNIEnv *env, jclass loader_class, jstring name) { + + if (!name) return nullptr; + auto& agent = JuiceAgent::Agent::instance(); + if (!check_env(agent)) return nullptr; + + // ============================ + // 1. Convert jstring -> internal name + // ============================ + const char* utf = env->GetStringUTFChars(name, nullptr); + if (!utf) return nullptr; + std::string internalName(utf); + env->ReleaseStringUTFChars(name, utf); + + // Convert dots to slashes: a.b.C -> a/b/C + std::replace(internalName.begin(), internalName.end(), '.', '/'); + + // ============================ + // 2. Iterate loaded classes + // ============================ + jint count = 0; + jclass* classes = nullptr; + jvmtiEnv* jvmti = agent.get_jvmti(); + + if (jvmti->GetLoadedClasses(&count, &classes) != JVMTI_ERROR_NONE || count == 0) { + return nullptr; + } + + jclass targetClass = nullptr; + for (jint i = 0; i < count; i++) { + char* signature = nullptr; + if (jvmti->GetClassSignature(classes[i], &signature, nullptr) == JVMTI_ERROR_NONE && signature) { + size_t len = strlen(signature); + if (len > 2 && signature[0] == 'L' && signature[len - 1] == ';') { + if (internalName == std::string_view(signature + 1, len - 2)) { + targetClass = classes[i]; + jvmti->Deallocate(reinterpret_cast(signature)); + break; + } + } + jvmti->Deallocate(reinterpret_cast(signature)); + } + } + + if (classes) { + jvmti->Deallocate(reinterpret_cast(classes)); + } + + if (!targetClass) { + spdlog::error("Class not loaded: {}", internalName); + return nullptr; + } + + // ============================ + // 3. Reuse getClassBytes logic + // ============================ + return Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytes(env, loader_class, targetClass); +} + +// ============================ +// Redefine class using jclass +// ============================ +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClass + (JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray class_bytes, jint class_bytes_len) { + + // Get singleton agent instance + auto& agent = JuiceAgent::Agent::instance(); + if (!check_env(agent)) + return JNI_FALSE; + + // Get byte array elements + jbyte* buf = env->GetByteArrayElements(class_bytes, nullptr); + if (!buf) { + spdlog::error("Cannot get class bytes"); + return JNI_FALSE; + } + + // Prepare JVMTI class definition + jvmtiClassDefinition defs[1]; + defs[0].klass = clazz; + defs[0].class_byte_count = class_bytes_len; + defs[0].class_bytes = reinterpret_cast(buf); + + // Redefine class via JVMTI + jvmtiError result = agent.get_jvmti()->RedefineClasses(1, defs); + + // Release byte array (no need to copy back) + env->ReleaseByteArrayElements(class_bytes, buf, JNI_ABORT); + + if (result != JVMTI_ERROR_NONE) { + spdlog::error("Redefine class failed: {}", static_cast(result)); + return JNI_FALSE; + } + + spdlog::debug("Class redefined successfully!"); + return JNI_TRUE; +} + +// ============================================ +// Redefine class using its fully qualified name +// Supports automatic '.' -> '/' conversion +// ============================================ +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClassByName + (JNIEnv *env, jclass loader_class, jstring class_name, jbyteArray class_bytes, jint class_bytes_len) { + + // Convert jstring to C string + const char* cname = env->GetStringUTFChars(class_name, nullptr); + if (!cname) { + spdlog::error("Class name is NULL!"); + return JNI_FALSE; + } + + // Copy and replace '.' with '/' for JVM internal class name + std::string internal_name(cname); + std::replace(internal_name.begin(), internal_name.end(), '.', '/'); + + // Release the original Java string + env->ReleaseStringUTFChars(class_name, cname); + + // Find class by internal name + jclass clazz = env->FindClass(internal_name.c_str()); + if (!clazz) { + spdlog::error("Cannot find class: {}", internal_name); + return JNI_FALSE; + } + + // Call redefineClass with the found class + return Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClass( + env, loader_class, clazz, class_bytes, class_bytes_len + ); +} + +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClass + (JNIEnv* env, jclass, jclass clazz, jbyteArray bytecodes, jint length) { + auto& agent = JuiceAgent::Agent::instance(); + + // ========================= + // 1. Check environment & parameters + // ========================= + if (!check_env(agent) || !clazz || !bytecodes) { + return JNI_FALSE; + } + + // ========================= + // 2. Get class internal name + // ========================= + std::string nameDot = get_class_name(env, clazz); + if (nameDot.empty()) { + spdlog::error("Failed to get class name for retransform"); + return JNI_FALSE; + } + + // Convert '.' to '/' for internal name + for (auto& c : nameDot) if (c == '.') c = '/'; + + // ========================= + // 3. Extract bytecode from jbyteArray + // ========================= + jbyte* bytes = env->GetByteArrayElements(bytecodes, nullptr); + jint len = env->GetArrayLength(bytecodes); + if (!bytes || len <= 0) { + return JNI_FALSE; + } + + // ========================= + // 4. Cache new bytecode for ClassFileLoadHook + // ========================= + { + std::lock_guard lock(pendingRetransformMutex); + pendingRetransform[nameDot].assign(bytes, bytes + len); + } + + env->ReleaseByteArrayElements(bytecodes, bytes, JNI_ABORT); + + // ========================= + // 5. Trigger JVMTI retransform + // ========================= + jclass classes[1] = { clazz }; + jvmtiError err = agent.get_jvmti()->RetransformClasses(1, classes); + + if (err != JVMTI_ERROR_NONE) { + spdlog::error("[retransformClass] failed: {} for {}", static_cast(err), nameDot); + return JNI_FALSE; + } + + spdlog::info("[retransformClass] OK: {} ({} bytes)", nameDot, len); + return JNI_TRUE; +} + +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClassByName + (JNIEnv* env, jclass, jstring className, jbyteArray bytecodes, jint length) { + + auto& agent = JuiceAgent::Agent::instance(); + + if (!check_env(agent) || !className || !bytecodes) { + return JNI_FALSE; + } + + // ========================= + // 1. Get UTF string from jstring + // ========================= + const char* utf = env->GetStringUTFChars(className, nullptr); + if (!utf) return JNI_FALSE; + + std::string internalName(utf); + env->ReleaseStringUTFChars(className, utf); + + // Convert '.' to '/' for internal name + for (auto& c : internalName) if (c == '.') c = '/'; + + // ========================= + // 2. Find loaded class by internal name (inline) + // ========================= + jclass target = nullptr; + { + jint classCount = 0; + jclass* loadedClasses = nullptr; + + if (agent.get_jvmti()->GetLoadedClasses(&classCount, &loadedClasses) == JVMTI_ERROR_NONE && classCount > 0) { + for (jint i = 0; i < classCount; ++i) { + char* sig = nullptr; + if (agent.get_jvmti()->GetClassSignature(loadedClasses[i], &sig, nullptr) == JVMTI_ERROR_NONE && sig) { + // sig: "Lnet/minecraft/client/Minecraft;" + if (sig[0] == 'L') { + size_t len = strlen(sig); + if (len > 2 && internalName == std::string(sig + 1, len - 2)) { + target = loadedClasses[i]; + agent.get_jvmti()->Deallocate(reinterpret_cast(sig)); + break; + } + } + agent.get_jvmti()->Deallocate(reinterpret_cast(sig)); + } + } + agent.get_jvmti()->Deallocate(reinterpret_cast(loadedClasses)); + } + } + + if (!target) { + spdlog::error("[retransformClassByName] class not loaded: {}", internalName); + return JNI_FALSE; + } + + // ========================= + // 3. Delegate to retransformClass + // ========================= + return Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClass( + env, nullptr, target, bytecodes, length + ); +} \ No newline at end of file diff --git a/src/libagent/jni/classloader.cpp b/src/libagent/jni/classloader.cpp new file mode 100644 index 0000000..3b7e393 --- /dev/null +++ b/src/libagent/jni/classloader.cpp @@ -0,0 +1,275 @@ +#include + +// Add jar to bootstrap classloader search path +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToBootstrapClassLoaderSearch + (JNIEnv *env, jclass, jstring jar_path) { + auto& agent = JuiceAgent::Agent::instance(); + + if (!check_env(agent)) + return JNI_FALSE; + + const char* j_jar_path = env->GetStringUTFChars(jar_path, nullptr); + if (!j_jar_path) { + spdlog::error("Path is NULL!"); + return JNI_FALSE; + } + + jvmtiError result = agent.get_jvmti()->AddToBootstrapClassLoaderSearch(j_jar_path); + if (result != JVMTI_ERROR_NONE) { + spdlog::error("Cannot AddToBootstrapClassLoaderSearch [result={}]", static_cast(result)); + env->ReleaseStringUTFChars(jar_path, j_jar_path); + return JNI_FALSE; + } + spdlog::info("AddToBootstrapClassLoaderSearch: {}", j_jar_path); + + env->ReleaseStringUTFChars(jar_path, j_jar_path); + return JNI_TRUE; + } + +// Add jar to system classloader search path +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToSystemClassLoaderSearch + (JNIEnv *env, jclass, jstring jar_path) { + auto& agent = JuiceAgent::Agent::instance(); + if (!check_env(agent)) + return JNI_FALSE; + + const char* j_jar_path = env->GetStringUTFChars(jar_path, nullptr); + if (!j_jar_path) { + spdlog::error("Path is NULL!"); + return JNI_FALSE; + } + + jvmtiError result = agent.get_jvmti()->AddToSystemClassLoaderSearch(j_jar_path); + if (result != JVMTI_ERROR_NONE) { + spdlog::error("Cannot AddToSystemClassLoaderSearch [result={}]", static_cast(result)); + env->ReleaseStringUTFChars(jar_path, j_jar_path); + return JNI_FALSE; + } + spdlog::info("AddToSystemClassLoaderSearch: {}", j_jar_path); + + env->ReleaseStringUTFChars(jar_path, j_jar_path); + return JNI_TRUE; + } + +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToClassLoader + (JNIEnv *env, jclass, jstring jar_path, jobject target_classloader) { + + auto& agent = JuiceAgent::Agent::instance(); + + if (!check_env(agent)) + return JNI_FALSE; + + if (!jar_path || !target_classloader) + return JNI_FALSE; + + // --- Try URLClassLoader path --- + jclass urlClassLoader = env->FindClass("java/net/URLClassLoader"); + if (env->ExceptionCheck() || !urlClassLoader) { + env->ExceptionClear(); + goto FALLBACK; + } + + if (env->IsInstanceOf(target_classloader, urlClassLoader)) { + + jclass fileClass = env->FindClass("java/io/File"); + if (env->ExceptionCheck() || !fileClass) { + env->ExceptionClear(); + goto FALLBACK; + } + + jmethodID fileInit = env->GetMethodID(fileClass, "", "(Ljava/lang/String;)V"); + if (env->ExceptionCheck() || !fileInit) { + env->ExceptionClear(); + goto FALLBACK; + } + + jobject file = env->NewObject(fileClass, fileInit, jar_path); + if (env->ExceptionCheck() || !file) { + env->ExceptionClear(); + goto FALLBACK; + } + + jmethodID toURI = env->GetMethodID(fileClass, "toURI", "()Ljava/net/URI;"); + if (env->ExceptionCheck() || !toURI) { + env->ExceptionClear(); + env->DeleteLocalRef(file); + goto FALLBACK; + } + + jobject uri = env->CallObjectMethod(file, toURI); + if (env->ExceptionCheck() || !uri) { + env->ExceptionClear(); + env->DeleteLocalRef(file); + goto FALLBACK; + } + + jclass uriClass = env->FindClass("java/net/URI"); + if (env->ExceptionCheck() || !uriClass) { + env->ExceptionClear(); + env->DeleteLocalRef(file); + env->DeleteLocalRef(uri); + goto FALLBACK; + } + + jmethodID toURL = env->GetMethodID(uriClass, "toURL", "()Ljava/net/URL;"); + if (env->ExceptionCheck() || !toURL) { + env->ExceptionClear(); + env->DeleteLocalRef(file); + env->DeleteLocalRef(uri); + goto FALLBACK; + } + + jobject url = env->CallObjectMethod(uri, toURL); + if (env->ExceptionCheck() || !url) { + env->ExceptionClear(); + env->DeleteLocalRef(file); + env->DeleteLocalRef(uri); + goto FALLBACK; + } + + jmethodID addURL = env->GetMethodID(urlClassLoader, "addURL", "(Ljava/net/URL;)V"); + if (env->ExceptionCheck() || !addURL) { + env->ExceptionClear(); + env->DeleteLocalRef(file); + env->DeleteLocalRef(uri); + env->DeleteLocalRef(url); + goto FALLBACK; + } + + env->CallVoidMethod(target_classloader, addURL, url); + if (env->ExceptionCheck()) { + env->ExceptionClear(); + env->DeleteLocalRef(file); + env->DeleteLocalRef(uri); + env->DeleteLocalRef(url); + goto FALLBACK; + } + + // cleanup + env->DeleteLocalRef(file); + env->DeleteLocalRef(uri); + env->DeleteLocalRef(url); + + return JNI_TRUE; + } + +FALLBACK: + + // --- JVMTI fallback --- + const char* j_jar_path = env->GetStringUTFChars(jar_path, nullptr); + if (!j_jar_path) + return JNI_FALSE; + + jvmtiError err = agent.get_jvmti()->AddToSystemClassLoaderSearch(j_jar_path); + + env->ReleaseStringUTFChars(jar_path, j_jar_path); + + if (err != JVMTI_ERROR_NONE) { + return JNI_FALSE; + } + + return JNI_TRUE; +} + +// TODO: Safety and Compatibility: Define Class +// Define class using target classloader +JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_defineClass + (JNIEnv *env, jclass, jobject target_classloader, jbyteArray bytes) { + auto& agent = JuiceAgent::Agent::instance(); + + if (!check_env(agent)) + return nullptr; + + jclass clClass = env->FindClass("java/lang/ClassLoader"); + jmethodID defineClass = env->GetMethodID(clClass, "defineClass", "([BII)Ljava/lang/Class;"); + jobject classDefined = env->CallObjectMethod(target_classloader, defineClass, bytes, 0, + env->GetArrayLength(bytes)); + if (env->ExceptionCheck()) { + env->ExceptionDescribe(); + env->ExceptionClear(); + return nullptr; + } + return (jclass)classDefined; + } + +JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getLoadedClasses + (JNIEnv *env, jclass) { + auto& agent = JuiceAgent::Agent::instance(); + + if (!check_env(agent)) + return nullptr; + + jint count = 0; + jclass* classes = nullptr; + jvmtiError err = agent.get_jvmti()->GetLoadedClasses(&count, &classes); + if (err != JVMTI_ERROR_NONE) { + spdlog::error("GetLoadedClasses failed: {}", static_cast(err)); + return nullptr; + } + + jclass classClass = env->FindClass("java/lang/Class"); + jobjectArray classesArray = env->NewObjectArray(count, classClass, nullptr); + + for (int i = 0; i < count; i++) { + env->SetObjectArrayElement(classesArray, i, classes[i]); + } + + agent.get_jvmti()->Deallocate((unsigned char*)classes); + return classesArray; + } + +JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassByName +(JNIEnv *env, jclass, jstring name) { + auto& agent = JuiceAgent::Agent::instance(); + + if (!check_env(agent)) + return nullptr; + + const char* utf = env->GetStringUTFChars(name, nullptr); + if (!utf) { + spdlog::error("Class name is NULL!"); + return nullptr; + } + + // Convert Java name to internal name: a.b.C -> a/b/C + std::string internal_name(utf); + std::replace(internal_name.begin(), internal_name.end(), '.', '/'); + env->ReleaseStringUTFChars(name, utf); + + // Get all loaded classes + jint count = 0; + jclass* classes = nullptr; + if (agent.get_jvmti()->GetLoadedClasses(&count, &classes) != JVMTI_ERROR_NONE || count == 0) { + spdlog::error("GetLoadedClasses failed or no classes loaded"); + return nullptr; + } + + jclass result = nullptr; + + for (jint i = 0; i < count; i++) { + char* signature = nullptr; + if (agent.get_jvmti()->GetClassSignature(classes[i], &signature, nullptr) != JVMTI_ERROR_NONE || !signature) + continue; + + size_t sig_len = strlen(signature); + if (sig_len > 2 && signature[0] == 'L' && signature[sig_len - 1] == ';' && + internal_name.size() == sig_len - 2 && + strncmp(signature + 1, internal_name.c_str(), sig_len - 2) == 0) { + result = classes[i]; + agent.get_jvmti()->Deallocate((unsigned char*)signature); + break; + } + + agent.get_jvmti()->Deallocate((unsigned char*)signature); + } + + if (classes) { + agent.get_jvmti()->Deallocate((unsigned char*)classes); + } + + if (!result) { + spdlog::error("Failed to find loaded class: {}", internal_name); + } + + return result; +} \ No newline at end of file diff --git a/src/libagent/jni/instrumentation.cpp b/src/libagent/jni/instrumentation.cpp new file mode 100644 index 0000000..68c116f --- /dev/null +++ b/src/libagent/jni/instrumentation.cpp @@ -0,0 +1,2 @@ +#include + diff --git a/src/libagent/services/BytecodeService.cpp b/src/libagent/services/BytecodeService.cpp new file mode 100644 index 0000000..3aa3091 --- /dev/null +++ b/src/libagent/services/BytecodeService.cpp @@ -0,0 +1,64 @@ +#include +#include + +namespace JuiceAgent::services::Bytecode { + void capture_bytecodes(const EventClassFileLoadHook& e) { + std::lock_guard lock(classDataMutex); + + if (!classToCapture.contains(e.name) || classFileDataMap.contains(e.name)) { + return; + } + + ClassFileData data; + data.classname = e.name; + data.bytecode.assign(e.classbytes, e.classbytes + e.class_data_len); + + if (e.jni_env) { + if (e.class_being_redefined) data.clazz = static_cast(e.jni_env->NewGlobalRef(e.class_being_redefined)); + if (e.loader) data.classloader = e.jni_env->NewGlobalRef(e.loader); + if (e.protection_domain) data.protection_domain = e.jni_env->NewGlobalRef(e.protection_domain); + } + + classFileDataMap[e.name] = std::move(data); + classToCapture.erase(e.name); + + spdlog::info("Captured class: {} (length: {})", e.name, e.class_data_len); + } + + void patch_bytecodes(const EventClassFileLoadHook& e) { + std::lock_guard lock(pendingRetransformMutex); + + auto it = pendingRetransform.find(e.name); + if (it == pendingRetransform.end()) { + return; + } + + auto& bytes = it->second; + const jint new_len = static_cast(bytes.size()); + + unsigned char* new_buf = nullptr; + if (e.jvmti_env->Allocate(bytes.size(), &new_buf) != JVMTI_ERROR_NONE) { + spdlog::error("Failed to allocate buffer for retransform: {}", e.name); + return; + } + + memcpy(new_buf, bytes.data(), bytes.size()); + + *e.new_class_data_len = new_len; + *e.new_classbytes = new_buf; + + pendingRetransform.erase(it); + + spdlog::info("Retransformed: {} (new length: {})", e.name, new_len); + } + + void init() { + agent.get_eventbus().subscribe(capture_bytecodes); + agent.get_eventbus().subscribe(patch_bytecodes); + } + + void start() { + + } + +} \ No newline at end of file diff --git a/src/libagent/services/JarLoaderService.cpp b/src/libagent/services/JarLoaderService.cpp new file mode 100644 index 0000000..e741517 --- /dev/null +++ b/src/libagent/services/JarLoaderService.cpp @@ -0,0 +1,68 @@ +#include + +namespace JuiceAgent::services::JarLoader { + static JarLoaderConfig config; + + static const char* MODULE_CLASS = "cn/xiaozhou233/juiceagent/api/modules/JarLoader"; + static const char* MODULE_METHOD = "loadJar"; + + void init() { + auto& cfg = agent.get_config(); + + config.enabled = cfg.get( + "JuiceAgent.Modules.JarLoader.Enabled", + false + ); + + config.injection_dir = cfg.get( + "JuiceAgent.Modules.JarLoader.InjectionDir", + (cfg.runtime_dir() / "injection").string(), + true + ); + + config.jar_path = cfg.get( + "JuiceAgent.Modules.JarLoader.JarPath", + "./Entry.jar", + true + ); + + config.entry_class = cfg.get( + "JuiceAgent.Modules.JarLoader.EntryClass", + "Example.Main", + false + ); + + config.entry_method = cfg.get( + "JuiceAgent.Modules.JarLoader.EntryMethod", + "start", + false + ); + + spdlog::info("JarLoaderService initialized"); + } + + void start() { + if (!config.enabled) { + return; + } + + JuiceAgent::Utils::Serializer ser; + + ser.add_kv("InjectionDir", config.injection_dir); + ser.add_kv("JarPath", config.jar_path); + ser.add_kv("EntryClass", config.entry_class); + ser.add_kv("EntryMethod", config.entry_method); + + auto data = ser.serialize(); + + JuiceAgent::Utils::call_java_impl( + agent.get_env(), + MODULE_CLASS, + MODULE_METHOD, + data.c_str() + ); + + spdlog::info("JarLoader start"); + return; + } +} \ No newline at end of file diff --git a/src/libagent/services/ServicesManager.cpp b/src/libagent/services/ServicesManager.cpp new file mode 100644 index 0000000..9c0725a --- /dev/null +++ b/src/libagent/services/ServicesManager.cpp @@ -0,0 +1,38 @@ +#include +#include + +namespace JuiceAgent::services::Manager { + void register_events() { + // PreLoad + agent.get_eventbus().subscribe(init); + + // Loaded + agent.get_eventbus().subscribe(start); + + // TODO: Stopped + + spdlog::info("Services Manager registered events"); + } + + void init(const EventPreLoad& event) { + spdlog::info("Initializing services"); + // JarLoader + JuiceAgent::services::JarLoader::init(); + + // Bytecode + JuiceAgent::services::Bytecode::init(); + } + + void start(const EventLoaded& event) { + spdlog::info("Starting services"); + // JarLoader + JuiceAgent::services::JarLoader::start(); + + // Bytecode + JuiceAgent::services::Bytecode::start(); + } + + void stop() { + + } +} \ No newline at end of file