From d8bed79f84fd08c4f60ca6664b67186a9a1723bd Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Sun, 1 Mar 2026 12:38:12 +0800 Subject: [PATCH 01/37] [Refactor] Rename --- CMakeLists.txt | 4 ++-- src/libagent/CMakeLists.txt | 2 ++ .../includes/cn_xiaozhou233_juiceloader_JuiceLoader.h | 0 src/{libjuiceloader => libagent}/includes/jni_impl.h | 0 .../includes/juiceloader.h | 0 .../jni/loader_ClassFileLoadHook.cpp | 0 src/{libjuiceloader => libagent}/jni/loader_class.cpp | 0 src/{libjuiceloader => libagent}/jni/loader_define.cpp | 0 src/{libjuiceloader => libagent}/jni/loader_init.cpp | 0 src/{libjuiceloader => libagent}/jni/loader_inject.cpp | 0 .../jni/loader_redefine.cpp | 0 .../jni/loader_retransform.cpp | 0 src/{libjuiceloader => libagent}/jni/loader_thread.cpp | 0 src/{libjuiceloader => libagent}/libjuiceloader.cpp | 0 src/libinjector/injector.c | 2 +- src/{libjuiceloader => libloader}/CMakeLists.txt | 10 ++++------ src/{libagent => libloader}/DllMain.cpp | 0 src/{libagent => libloader}/ReflectiveLoader.c | 0 src/{libagent => libloader}/includes/libagent.h | 0 src/{libagent => libloader}/libagent.cpp | 0 20 files changed, 9 insertions(+), 9 deletions(-) rename src/{libjuiceloader => libagent}/includes/cn_xiaozhou233_juiceloader_JuiceLoader.h (100%) rename src/{libjuiceloader => libagent}/includes/jni_impl.h (100%) rename src/{libjuiceloader => libagent}/includes/juiceloader.h (100%) rename src/{libjuiceloader => libagent}/jni/loader_ClassFileLoadHook.cpp (100%) rename src/{libjuiceloader => libagent}/jni/loader_class.cpp (100%) rename src/{libjuiceloader => libagent}/jni/loader_define.cpp (100%) rename src/{libjuiceloader => libagent}/jni/loader_init.cpp (100%) rename src/{libjuiceloader => libagent}/jni/loader_inject.cpp (100%) rename src/{libjuiceloader => libagent}/jni/loader_redefine.cpp (100%) rename src/{libjuiceloader => libagent}/jni/loader_retransform.cpp (100%) rename src/{libjuiceloader => libagent}/jni/loader_thread.cpp (100%) rename src/{libjuiceloader => libagent}/libjuiceloader.cpp (100%) rename src/{libjuiceloader => libloader}/CMakeLists.txt (53%) rename src/{libagent => libloader}/DllMain.cpp (100%) rename src/{libagent => libloader}/ReflectiveLoader.c (100%) rename src/{libagent => libloader}/includes/libagent.h (100%) rename src/{libagent => libloader}/libagent.cpp (100%) diff --git a/CMakeLists.txt b/CMakeLists.txt index e90de9b..35ebc8d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -16,6 +16,6 @@ link_directories("$ENV{JAVA_HOME}/lib") add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection) # modules -add_subdirectory(${SRC_DIR}/libagent) +add_subdirectory(${SRC_DIR}/libloader) add_subdirectory(${SRC_DIR}/libinjector) -add_subdirectory(${SRC_DIR}/libjuiceloader) \ No newline at end of file +add_subdirectory(${SRC_DIR}/libagent) \ No newline at end of file diff --git a/src/libagent/CMakeLists.txt b/src/libagent/CMakeLists.txt index 5ae9e94..3c6e577 100644 --- a/src/libagent/CMakeLists.txt +++ b/src/libagent/CMakeLists.txt @@ -3,6 +3,8 @@ file( agent_sources ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp ${CMAKE_CURRENT_SOURCE_DIR}/*.c + ${CMAKE_CURRENT_SOURCE_DIR}/jni/*.c + ${CMAKE_CURRENT_SOURCE_DIR}/jni/*.cpp ) add_library(agent SHARED ${agent_sources}) diff --git a/src/libjuiceloader/includes/cn_xiaozhou233_juiceloader_JuiceLoader.h b/src/libagent/includes/cn_xiaozhou233_juiceloader_JuiceLoader.h similarity index 100% rename from src/libjuiceloader/includes/cn_xiaozhou233_juiceloader_JuiceLoader.h rename to src/libagent/includes/cn_xiaozhou233_juiceloader_JuiceLoader.h diff --git a/src/libjuiceloader/includes/jni_impl.h b/src/libagent/includes/jni_impl.h similarity index 100% rename from src/libjuiceloader/includes/jni_impl.h rename to src/libagent/includes/jni_impl.h diff --git a/src/libjuiceloader/includes/juiceloader.h b/src/libagent/includes/juiceloader.h similarity index 100% rename from src/libjuiceloader/includes/juiceloader.h rename to src/libagent/includes/juiceloader.h diff --git a/src/libjuiceloader/jni/loader_ClassFileLoadHook.cpp b/src/libagent/jni/loader_ClassFileLoadHook.cpp similarity index 100% rename from src/libjuiceloader/jni/loader_ClassFileLoadHook.cpp rename to src/libagent/jni/loader_ClassFileLoadHook.cpp diff --git a/src/libjuiceloader/jni/loader_class.cpp b/src/libagent/jni/loader_class.cpp similarity index 100% rename from src/libjuiceloader/jni/loader_class.cpp rename to src/libagent/jni/loader_class.cpp diff --git a/src/libjuiceloader/jni/loader_define.cpp b/src/libagent/jni/loader_define.cpp similarity index 100% rename from src/libjuiceloader/jni/loader_define.cpp rename to src/libagent/jni/loader_define.cpp diff --git a/src/libjuiceloader/jni/loader_init.cpp b/src/libagent/jni/loader_init.cpp similarity index 100% rename from src/libjuiceloader/jni/loader_init.cpp rename to src/libagent/jni/loader_init.cpp diff --git a/src/libjuiceloader/jni/loader_inject.cpp b/src/libagent/jni/loader_inject.cpp similarity index 100% rename from src/libjuiceloader/jni/loader_inject.cpp rename to src/libagent/jni/loader_inject.cpp diff --git a/src/libjuiceloader/jni/loader_redefine.cpp b/src/libagent/jni/loader_redefine.cpp similarity index 100% rename from src/libjuiceloader/jni/loader_redefine.cpp rename to src/libagent/jni/loader_redefine.cpp diff --git a/src/libjuiceloader/jni/loader_retransform.cpp b/src/libagent/jni/loader_retransform.cpp similarity index 100% rename from src/libjuiceloader/jni/loader_retransform.cpp rename to src/libagent/jni/loader_retransform.cpp diff --git a/src/libjuiceloader/jni/loader_thread.cpp b/src/libagent/jni/loader_thread.cpp similarity index 100% rename from src/libjuiceloader/jni/loader_thread.cpp rename to src/libagent/jni/loader_thread.cpp diff --git a/src/libjuiceloader/libjuiceloader.cpp b/src/libagent/libjuiceloader.cpp similarity index 100% rename from src/libjuiceloader/libjuiceloader.cpp rename to src/libagent/libjuiceloader.cpp diff --git a/src/libinjector/injector.c b/src/libinjector/injector.c index a2c0e4e..7c6479c 100644 --- a/src/libinjector/injector.c +++ b/src/libinjector/injector.c @@ -48,7 +48,7 @@ int main(int argc, char **argv) { printf("Warning: GetCurrentDirectory failed, using '.'\n"); strncpy(cwd, ".", MAX_PATH_LEN - 1); } - snprintf(dll_path, MAX_PATH_LEN, "%s\\libagent.dll", cwd); + snprintf(dll_path, MAX_PATH_LEN, "%s\\libloader.dll", cwd); printf("Using DLL path: %s\n", dll_path); } diff --git a/src/libjuiceloader/CMakeLists.txt b/src/libloader/CMakeLists.txt similarity index 53% rename from src/libjuiceloader/CMakeLists.txt rename to src/libloader/CMakeLists.txt index 27719d9..925521a 100644 --- a/src/libjuiceloader/CMakeLists.txt +++ b/src/libloader/CMakeLists.txt @@ -1,22 +1,20 @@ file( GLOB_RECURSE - libjuiceloader_sources + loader_sources ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp ${CMAKE_CURRENT_SOURCE_DIR}/*.c - ${CMAKE_CURRENT_SOURCE_DIR}/jni/*.c - ${CMAKE_CURRENT_SOURCE_DIR}/jni/*.cpp ) -add_library(juiceloader SHARED ${libjuiceloader_sources}) +add_library(loader SHARED ${loader_sources}) -target_include_directories(juiceloader PRIVATE +target_include_directories(loader PRIVATE ${CMAKE_SOURCE_DIR}/includes ${CMAKE_SOURCE_DIR}/includes/jvm ${CMAKE_SOURCE_DIR}/includes/jvm/win32 ${CMAKE_CURRENT_SOURCE_DIR}/includes ) -target_link_libraries(juiceloader PRIVATE +target_link_libraries(loader PRIVATE ReflectiveDLLInjection jvm ) \ No newline at end of file diff --git a/src/libagent/DllMain.cpp b/src/libloader/DllMain.cpp similarity index 100% rename from src/libagent/DllMain.cpp rename to src/libloader/DllMain.cpp diff --git a/src/libagent/ReflectiveLoader.c b/src/libloader/ReflectiveLoader.c similarity index 100% rename from src/libagent/ReflectiveLoader.c rename to src/libloader/ReflectiveLoader.c diff --git a/src/libagent/includes/libagent.h b/src/libloader/includes/libagent.h similarity index 100% rename from src/libagent/includes/libagent.h rename to src/libloader/includes/libagent.h diff --git a/src/libagent/libagent.cpp b/src/libloader/libagent.cpp similarity index 100% rename from src/libagent/libagent.cpp rename to src/libloader/libagent.cpp From 2ce6a8e19244b035379333b8d87b218612575287 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Sun, 1 Mar 2026 12:50:33 +0800 Subject: [PATCH 02/37] [Refactor] Modify the loader structure --- src/libloader/CMakeLists.txt | 21 +++++++++++++------ src/libloader/{ => common}/libagent.cpp | 0 src/libloader/{ => windows}/DllMain.cpp | 0 .../{ => windows}/ReflectiveLoader.c | 0 4 files changed, 15 insertions(+), 6 deletions(-) rename src/libloader/{ => common}/libagent.cpp (100%) rename src/libloader/{ => windows}/DllMain.cpp (100%) rename src/libloader/{ => windows}/ReflectiveLoader.c (100%) diff --git a/src/libloader/CMakeLists.txt b/src/libloader/CMakeLists.txt index 925521a..a7afc1f 100644 --- a/src/libloader/CMakeLists.txt +++ b/src/libloader/CMakeLists.txt @@ -1,10 +1,19 @@ -file( - GLOB_RECURSE - loader_sources - ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp - ${CMAKE_CURRENT_SOURCE_DIR}/*.c +file(GLOB_RECURSE loader_sources + ${CMAKE_CURRENT_SOURCE_DIR}/common/*.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/common/*.c ) +if (WIN32) + message(STATUS "Detected System: Windows") + + file(GLOB_RECURSE windows_sources + ${CMAKE_CURRENT_SOURCE_DIR}/windows/*.cpp + ${CMAKE_CURRENT_SOURCE_DIR}/windows/*.c + ) + + list(APPEND loader_sources ${windows_sources}) +endif() + add_library(loader SHARED ${loader_sources}) target_include_directories(loader PRIVATE @@ -17,4 +26,4 @@ target_include_directories(loader PRIVATE target_link_libraries(loader PRIVATE ReflectiveDLLInjection jvm -) \ No newline at end of file +) \ No newline at end of file diff --git a/src/libloader/libagent.cpp b/src/libloader/common/libagent.cpp similarity index 100% rename from src/libloader/libagent.cpp rename to src/libloader/common/libagent.cpp diff --git a/src/libloader/DllMain.cpp b/src/libloader/windows/DllMain.cpp similarity index 100% rename from src/libloader/DllMain.cpp rename to src/libloader/windows/DllMain.cpp diff --git a/src/libloader/ReflectiveLoader.c b/src/libloader/windows/ReflectiveLoader.c similarity index 100% rename from src/libloader/ReflectiveLoader.c rename to src/libloader/windows/ReflectiveLoader.c From ab9369d8b714dfdf40eb7977baceff723e4ba166 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Sun, 1 Mar 2026 13:02:33 +0800 Subject: [PATCH 03/37] [Refactor] rename and remove useless log --- src/libloader/common/libagent.cpp | 7 +------ src/libloader/includes/{libagent.h => libloader.h} | 0 src/libloader/windows/DllMain.cpp | 3 --- 3 files changed, 1 insertion(+), 9 deletions(-) rename src/libloader/includes/{libagent.h => libloader.h} (100%) diff --git a/src/libloader/common/libagent.cpp b/src/libloader/common/libagent.cpp index b0aac82..5b9070c 100644 --- a/src/libloader/common/libagent.cpp +++ b/src/libloader/common/libagent.cpp @@ -2,7 +2,7 @@ #include #include #include -#include +#include #include #include #include @@ -208,11 +208,9 @@ static int InvokeJuiceLoaderInit(const char* ConfigDir) { extern "C" __declspec(dllexport) bool InitJuiceAgent(const char* runtime_path) { - PLOGI << "--------> InitJuiceAgent Invoke <--------"; PLOGD << "runtime_path: " << runtime_path; // Read Config - PLOGI << "ReadConfig ..."; if (ReadConfig(runtime_path) != 0) { PLOGE << "ReadConfig failed"; return false; @@ -220,7 +218,6 @@ bool InitJuiceAgent(const char* runtime_path) { PLOGI << "[OK] ReadConfig"; // Get JavaEnv - PLOGI << "Get JavaEnv ..."; if (GetJavaEnv() != 0) { PLOGE << "GetJavaEnv failed"; return false; @@ -228,7 +225,6 @@ bool InitJuiceAgent(const char* runtime_path) { PLOGI << "[OK] Get JavaEnv"; // Inject JuiceLoader jar - PLOGI << "Inject JuiceLoader jar ..."; if (JuiceAgent.jvmti->AddToSystemClassLoaderSearch(InjectionInfo.JuiceLoaderJarPath) != JNI_OK) { PLOGE << "AddToSystemClassLoaderSearch failed"; return false; @@ -236,7 +232,6 @@ bool InitJuiceAgent(const char* runtime_path) { PLOGI << "[OK] Inject JuiceLoader jar"; // Invoke JuiceLoader Init - PLOGI << "Invoke JuiceLoader Init ..."; if (InvokeJuiceLoaderInit(runtime_path) != 0) { PLOGE << "Invoke JuiceLoader Init failed"; return false; diff --git a/src/libloader/includes/libagent.h b/src/libloader/includes/libloader.h similarity index 100% rename from src/libloader/includes/libagent.h rename to src/libloader/includes/libloader.h diff --git a/src/libloader/windows/DllMain.cpp b/src/libloader/windows/DllMain.cpp index 7308e97..518f891 100644 --- a/src/libloader/windows/DllMain.cpp +++ b/src/libloader/windows/DllMain.cpp @@ -8,10 +8,8 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) { case DLL_PROCESS_ATTACH: { InitLogger(); PLOGI << "DllMain: DLL_PROCESS_ATTACH"; - PLOGD.printf("lpReserved: %p", lpReserved); const char* runtime_dir = (const char*)lpReserved; - PLOGD << "runtime_dir: " << runtime_dir; InitJuiceAgent(runtime_dir); @@ -29,7 +27,6 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) { case DLL_PROCESS_DETACH: { PLOGI << "DllMain: DLL_PROCESS_DETACH"; - PLOGD.printf("lpReserved: %p", lpReserved); break; } } From ea5ce8258d04c9aaf8da3b020ee4e23770b10247 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Sun, 1 Mar 2026 13:03:32 +0800 Subject: [PATCH 04/37] [Refactor] Rename --- src/libloader/windows/DllMain.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libloader/windows/DllMain.cpp b/src/libloader/windows/DllMain.cpp index 518f891..217082b 100644 --- a/src/libloader/windows/DllMain.cpp +++ b/src/libloader/windows/DllMain.cpp @@ -1,6 +1,6 @@ #include #include -#include +#include BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) { switch( fdwReason ) From cf49ed0a7b3905ac78584cf6a724a94e580667bf Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Sun, 1 Mar 2026 13:07:00 +0800 Subject: [PATCH 05/37] [Refactor] Rename --- src/libloader/common/{libagent.cpp => libloader.cpp} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename src/libloader/common/{libagent.cpp => libloader.cpp} (100%) diff --git a/src/libloader/common/libagent.cpp b/src/libloader/common/libloader.cpp similarity index 100% rename from src/libloader/common/libagent.cpp rename to src/libloader/common/libloader.cpp From 172f354b049fa9a56e01ce8ba11e232ba3946b05 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Sat, 7 Mar 2026 16:41:20 +0800 Subject: [PATCH 06/37] [Refactor] Config --- includes/JuiceAgent/JuiceAgent.h | 7 +- src/libloader/common/config.cpp | 97 +++++++++++++++++++ .../{libloader.cpp => libloader.cpp.temp} | 0 3 files changed, 101 insertions(+), 3 deletions(-) create mode 100644 src/libloader/common/config.cpp rename src/libloader/common/{libloader.cpp => libloader.cpp.temp} (100%) diff --git a/includes/JuiceAgent/JuiceAgent.h b/includes/JuiceAgent/JuiceAgent.h index 18fa729..5d94747 100644 --- a/includes/JuiceAgent/JuiceAgent.h +++ b/includes/JuiceAgent/JuiceAgent.h @@ -4,13 +4,14 @@ #define INJECT_PATH_MAX 260 typedef struct _InjectionInfo { - char BootstrapAPIPath[INJECT_PATH_MAX]; - char JuiceLoaderJarPath[INJECT_PATH_MAX]; + char JuiceAgentAPIJarPath[INJECT_PATH_MAX]; + char JuiceAgentNativePath[INJECT_PATH_MAX]; + char EntryJarPath[INJECT_PATH_MAX]; char EntryClass[INJECT_PATH_MAX]; char EntryMethod[INJECT_PATH_MAX]; + char InjectionDir[INJECT_PATH_MAX]; - char JuiceLoaderLibraryPath[INJECT_PATH_MAX]; } InjectionInfoType; extern InjectionInfoType InjectionInfo; diff --git a/src/libloader/common/config.cpp b/src/libloader/common/config.cpp new file mode 100644 index 0000000..8bc8e61 --- /dev/null +++ b/src/libloader/common/config.cpp @@ -0,0 +1,97 @@ +#include +#include +#include +#include +#include +#include + +class config +{ +private: + const char* runtime_dir; + std::string config_path; + std::ifstream config_file; + toml::Value config_values; + InjectionInfoType injection_info; +public: + config(const char* runtime_dir); + ~config(); + + std::string get_or_default(const char* key, const char* default_value); + InjectionInfoType get_injection_info(); + void printInjectionInfo(); +}; + +config::config(const char* runtime_dir) { + // config file path + std::string config_path = std::string(runtime_dir) + "/config.toml"; + + this->runtime_dir = runtime_dir; + this->config_path = config_path; + + // read config file + this->config_file.open(config_path); + if (!this->config_file) + { + PLOGE << "Failed to open config file: " << config_path; + } + + // Parse config file + toml::ParseResult pr = toml::parse(this->config_file); + if (!pr.valid()) + { + PLOGE << "Failed to parse config file: " << config_path; + return; + } + + this->config_values = pr.value; +} + +std::string config::get_or_default(const char* key, const char* default_value) { + const toml::Value* value = this->config_values.find(key); + + // key exists and is string + if (value && value->is()) { + std::string result = value->as(); + + if (!result.empty()) { + PLOGD << "Found parameter: " << key << " = " << result; + return result; + } + + PLOGD << "Parameter " << key << " is empty, use default: " << default_value; + return std::string(default_value); + } + + // key not found + PLOGD << "Not found parameter: " << key << ", use default: " << default_value; + return std::string(default_value); +} + +InjectionInfoType config::get_injection_info() { + this->injection_info = {}; + + auto copy_from_config = [this](char* dst, size_t dst_size, const char* key, const char* default_value) { + std::string value = this->get_or_default(key, default_value); + strncpy_s(dst, dst_size, value.c_str(), _TRUNCATE); + }; + + copy_from_config(this->injection_info.JuiceAgentAPIJarPath, sizeof(injection_info.JuiceAgentAPIJarPath), "JuiceAgentAPIJarPath", ""); + copy_from_config(this->injection_info.JuiceAgentNativePath, sizeof(injection_info.JuiceAgentNativePath), "JuiceAgentNativePath", ""); + copy_from_config(this->injection_info.EntryJarPath, sizeof(injection_info.EntryJarPath), "EntryJarPath", ""); + copy_from_config(this->injection_info.EntryClass, sizeof(injection_info.EntryClass), "EntryClass", ""); + copy_from_config(this->injection_info.EntryMethod, sizeof(injection_info.EntryMethod), "EntryMethod", ""); + copy_from_config(this->injection_info.InjectionDir, sizeof(injection_info.InjectionDir), "InjectionDir", this->runtime_dir); + + return injection_info; +} + +void config::printInjectionInfo() { + PLOGI << "Injection Info:"; + PLOGI << "JuiceAgentAPIJarPath: " << this->injection_info.JuiceAgentAPIJarPath; + PLOGI << "JuiceAgentNativePath: " << this->injection_info.JuiceAgentNativePath; + PLOGI << "EntryJarPath: " << this->injection_info.EntryJarPath; + PLOGI << "EntryClass: " << this->injection_info.EntryClass; + PLOGI << "EntryMethod: " << this->injection_info.EntryMethod; + PLOGI << "InjectionDir: " << this->injection_info.InjectionDir; +} \ No newline at end of file diff --git a/src/libloader/common/libloader.cpp b/src/libloader/common/libloader.cpp.temp similarity index 100% rename from src/libloader/common/libloader.cpp rename to src/libloader/common/libloader.cpp.temp From 9b24ea0ae42f9497d35d52dd16b0c3ad2196dd36 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Sat, 7 Mar 2026 17:44:27 +0800 Subject: [PATCH 07/37] [Refactor] libloader --- src/libloader/common/libloader.cpp | 7 +++++++ src/libloader/includes/libloader.h | 10 ---------- src/libloader/includes/libloader.hpp | 6 ++++++ src/libloader/windows/DllMain.cpp | 4 ++-- 4 files changed, 15 insertions(+), 12 deletions(-) create mode 100644 src/libloader/common/libloader.cpp delete mode 100644 src/libloader/includes/libloader.h create mode 100644 src/libloader/includes/libloader.hpp diff --git a/src/libloader/common/libloader.cpp b/src/libloader/common/libloader.cpp new file mode 100644 index 0000000..c4dedf1 --- /dev/null +++ b/src/libloader/common/libloader.cpp @@ -0,0 +1,7 @@ +#include +#include + + +void libloader::entrypoint(const char* runtime_dir) { + PLOGI << "libloader entrypoint"; +} diff --git a/src/libloader/includes/libloader.h b/src/libloader/includes/libloader.h deleted file mode 100644 index 590909f..0000000 --- a/src/libloader/includes/libloader.h +++ /dev/null @@ -1,10 +0,0 @@ -#ifndef LIBAGENT_H -#define LIBAGENT_H - -#include - -extern "C" __declspec(dllexport) -bool InitJuiceAgent(const char* runtime_path); - - -#endif // LIBAGENT_H \ No newline at end of file diff --git a/src/libloader/includes/libloader.hpp b/src/libloader/includes/libloader.hpp new file mode 100644 index 0000000..091d41d --- /dev/null +++ b/src/libloader/includes/libloader.hpp @@ -0,0 +1,6 @@ +#pragma once + +namespace libloader +{ + void entrypoint(const char* runtime_dir); +} // namespace libloader diff --git a/src/libloader/windows/DllMain.cpp b/src/libloader/windows/DllMain.cpp index 217082b..5e5c0b9 100644 --- a/src/libloader/windows/DllMain.cpp +++ b/src/libloader/windows/DllMain.cpp @@ -1,6 +1,6 @@ #include #include -#include +#include BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) { switch( fdwReason ) @@ -11,7 +11,7 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) { const char* runtime_dir = (const char*)lpReserved; - InitJuiceAgent(runtime_dir); + libloader::entrypoint(runtime_dir); break; } From a110e675c646f9dc9aa2ab8e50cf52c5fcfc58c0 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Sat, 7 Mar 2026 22:38:36 +0800 Subject: [PATCH 08/37] [Refactor] API --- src/libloader/common/api.cpp | 9 +++++++++ 1 file changed, 9 insertions(+) create mode 100644 src/libloader/common/api.cpp diff --git a/src/libloader/common/api.cpp b/src/libloader/common/api.cpp new file mode 100644 index 0000000..3a97a4f --- /dev/null +++ b/src/libloader/common/api.cpp @@ -0,0 +1,9 @@ +// for debug tools or other stuff + +#include + +extern "C" __declspec(dllexport) +bool InitJuiceAgent(const char* runtime_path) { + libloader::entrypoint(runtime_path); + return true; +} \ No newline at end of file From c9c10686ab1f8d95878a297eda94e0a56dbf42d4 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Sun, 8 Mar 2026 10:05:03 +0800 Subject: [PATCH 09/37] [Refactor] Delete --- src/libloader/common/api.cpp | 9 --- src/libloader/common/config.cpp | 97 ------------------------------ src/libloader/common/libloader.cpp | 7 --- 3 files changed, 113 deletions(-) delete mode 100644 src/libloader/common/api.cpp delete mode 100644 src/libloader/common/config.cpp delete mode 100644 src/libloader/common/libloader.cpp diff --git a/src/libloader/common/api.cpp b/src/libloader/common/api.cpp deleted file mode 100644 index 3a97a4f..0000000 --- a/src/libloader/common/api.cpp +++ /dev/null @@ -1,9 +0,0 @@ -// for debug tools or other stuff - -#include - -extern "C" __declspec(dllexport) -bool InitJuiceAgent(const char* runtime_path) { - libloader::entrypoint(runtime_path); - return true; -} \ No newline at end of file diff --git a/src/libloader/common/config.cpp b/src/libloader/common/config.cpp deleted file mode 100644 index 8bc8e61..0000000 --- a/src/libloader/common/config.cpp +++ /dev/null @@ -1,97 +0,0 @@ -#include -#include -#include -#include -#include -#include - -class config -{ -private: - const char* runtime_dir; - std::string config_path; - std::ifstream config_file; - toml::Value config_values; - InjectionInfoType injection_info; -public: - config(const char* runtime_dir); - ~config(); - - std::string get_or_default(const char* key, const char* default_value); - InjectionInfoType get_injection_info(); - void printInjectionInfo(); -}; - -config::config(const char* runtime_dir) { - // config file path - std::string config_path = std::string(runtime_dir) + "/config.toml"; - - this->runtime_dir = runtime_dir; - this->config_path = config_path; - - // read config file - this->config_file.open(config_path); - if (!this->config_file) - { - PLOGE << "Failed to open config file: " << config_path; - } - - // Parse config file - toml::ParseResult pr = toml::parse(this->config_file); - if (!pr.valid()) - { - PLOGE << "Failed to parse config file: " << config_path; - return; - } - - this->config_values = pr.value; -} - -std::string config::get_or_default(const char* key, const char* default_value) { - const toml::Value* value = this->config_values.find(key); - - // key exists and is string - if (value && value->is()) { - std::string result = value->as(); - - if (!result.empty()) { - PLOGD << "Found parameter: " << key << " = " << result; - return result; - } - - PLOGD << "Parameter " << key << " is empty, use default: " << default_value; - return std::string(default_value); - } - - // key not found - PLOGD << "Not found parameter: " << key << ", use default: " << default_value; - return std::string(default_value); -} - -InjectionInfoType config::get_injection_info() { - this->injection_info = {}; - - auto copy_from_config = [this](char* dst, size_t dst_size, const char* key, const char* default_value) { - std::string value = this->get_or_default(key, default_value); - strncpy_s(dst, dst_size, value.c_str(), _TRUNCATE); - }; - - copy_from_config(this->injection_info.JuiceAgentAPIJarPath, sizeof(injection_info.JuiceAgentAPIJarPath), "JuiceAgentAPIJarPath", ""); - copy_from_config(this->injection_info.JuiceAgentNativePath, sizeof(injection_info.JuiceAgentNativePath), "JuiceAgentNativePath", ""); - copy_from_config(this->injection_info.EntryJarPath, sizeof(injection_info.EntryJarPath), "EntryJarPath", ""); - copy_from_config(this->injection_info.EntryClass, sizeof(injection_info.EntryClass), "EntryClass", ""); - copy_from_config(this->injection_info.EntryMethod, sizeof(injection_info.EntryMethod), "EntryMethod", ""); - copy_from_config(this->injection_info.InjectionDir, sizeof(injection_info.InjectionDir), "InjectionDir", this->runtime_dir); - - return injection_info; -} - -void config::printInjectionInfo() { - PLOGI << "Injection Info:"; - PLOGI << "JuiceAgentAPIJarPath: " << this->injection_info.JuiceAgentAPIJarPath; - PLOGI << "JuiceAgentNativePath: " << this->injection_info.JuiceAgentNativePath; - PLOGI << "EntryJarPath: " << this->injection_info.EntryJarPath; - PLOGI << "EntryClass: " << this->injection_info.EntryClass; - PLOGI << "EntryMethod: " << this->injection_info.EntryMethod; - PLOGI << "InjectionDir: " << this->injection_info.InjectionDir; -} \ No newline at end of file diff --git a/src/libloader/common/libloader.cpp b/src/libloader/common/libloader.cpp deleted file mode 100644 index c4dedf1..0000000 --- a/src/libloader/common/libloader.cpp +++ /dev/null @@ -1,7 +0,0 @@ -#include -#include - - -void libloader::entrypoint(const char* runtime_dir) { - PLOGI << "libloader entrypoint"; -} From 9dab75b5fd5a968381c7448cd923cb3f2e911cf7 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Tue, 24 Mar 2026 13:53:54 +0800 Subject: [PATCH 10/37] [Refactor] Config System --- src/libloader/includes/config.hpp | 86 +++++++++++++++++++++++++++++++ 1 file changed, 86 insertions(+) create mode 100644 src/libloader/includes/config.hpp diff --git a/src/libloader/includes/config.hpp b/src/libloader/includes/config.hpp new file mode 100644 index 0000000..0ac8f1a --- /dev/null +++ b/src/libloader/includes/config.hpp @@ -0,0 +1,86 @@ +#include +#include +#include +#include +#include +#include + +namespace config +{ + class Config { + private: + std::string config_path; + toml::Value config; + + public: + Config(const std::string& config_path) + : config_path(config_path) + { + PLOGD << "[Config] Loading config file: " << config_path; + + std::ifstream file(config_path); + if (!file.is_open()) { + PLOGE << "[Config] Failed to open config file: " << config_path; + throw std::runtime_error("Failed to open config file: " + config_path); + } + + toml::ParseResult pr = toml::parse(file); + + if (!pr.valid()) { + PLOGE << "[Config] Failed to parse config file: " << config_path + << " | Reason: " << pr.errorReason; + + throw std::runtime_error( + "Failed to parse config file: " + config_path + "\n" + pr.errorReason + ); + } + + config = pr.value; + + PLOGI << "[Config] Successfully loaded config file: " << config_path; + } + + template + T get_or_default(const std::string& key, const T& default_value) const + { + const toml::Value* value = config.find(key); + + if (!value) { + PLOGW << "[Config] Key not found: " << key + << " | Using default value"; + return default_value; + } + + if (!value->is()) { + PLOGE << "[Config] Type mismatch for key: " << key + << " | Expected type does not match | Using default value"; + return default_value; + } + + PLOGD << "[Config] Read key: " << key; + + return value->as(); + } + + std::string get_path_or_default(const std::string& key, const std::string& def) const + { + std::string result = get_or_default(key, def); + + std::filesystem::path p(result); + + if (p.is_relative()) { + std::filesystem::path full = + std::filesystem::path(config_path).parent_path() / p; + + PLOGD << "[Config] Resolved relative path: " << result + << " -> " << full.string(); + + return full.string(); + } + + PLOGD << "[Config] Using absolute path: " << result; + + return result; + } + }; +} \ No newline at end of file From 205e608d6069743acf2798fa86a7fb92dc91c19a Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Tue, 24 Mar 2026 19:24:37 +0800 Subject: [PATCH 11/37] Refactor: Config System --- src/libloader/common/libloader.cpp | 15 +++++ src/libloader/includes/config.hpp | 92 ++++++++---------------------- 2 files changed, 40 insertions(+), 67 deletions(-) create mode 100644 src/libloader/common/libloader.cpp diff --git a/src/libloader/common/libloader.cpp b/src/libloader/common/libloader.cpp new file mode 100644 index 0000000..a9062d0 --- /dev/null +++ b/src/libloader/common/libloader.cpp @@ -0,0 +1,15 @@ +#include +#include + +namespace libloader +{ + void entrypoint(const char* runtime_dir) { + config::Config cfg(runtime_dir); + if (!cfg.is_valid()) { + PLOGE << "Invalid config"; + return; + } + + + } +} // namespace libloader diff --git a/src/libloader/includes/config.hpp b/src/libloader/includes/config.hpp index 0ac8f1a..68fdf30 100644 --- a/src/libloader/includes/config.hpp +++ b/src/libloader/includes/config.hpp @@ -1,86 +1,44 @@ -#include -#include -#include -#include +#pragma once + +#include #include -#include +#include +#include namespace config { class Config { private: - std::string config_path; - toml::Value config; + toml::Value config{}; + bool valid = false; public: - Config(const std::string& config_path) - : config_path(config_path) - { - PLOGD << "[Config] Loading config file: " << config_path; + explicit Config(const char* c_runtime_dir) { + std::filesystem::path path = std::filesystem::path(c_runtime_dir) / "config.toml"; - std::ifstream file(config_path); - if (!file.is_open()) { - PLOGE << "[Config] Failed to open config file: " << config_path; - throw std::runtime_error("Failed to open config file: " + config_path); + std::ifstream ifs(path); + if (!ifs.is_open()) { + PLOGE << "Failed to open config file: " << path; + return; } - toml::ParseResult pr = toml::parse(file); + try { + auto pr = toml::parse(ifs); - if (!pr.valid()) { - PLOGE << "[Config] Failed to parse config file: " << config_path - << " | Reason: " << pr.errorReason; + if (!pr.valid()) { + PLOGE << "Invalid TOML file: " << pr.errorReason; + return; + } - throw std::runtime_error( - "Failed to parse config file: " + config_path + "\n" + pr.errorReason - ); + config = pr.value; + valid = true; + } catch (const std::exception& e) { + PLOGE << "TOML parse error: " << e.what(); } - - config = pr.value; - - PLOGI << "[Config] Successfully loaded config file: " << config_path; } - template - T get_or_default(const std::string& key, const T& default_value) const - { - const toml::Value* value = config.find(key); - - if (!value) { - PLOGW << "[Config] Key not found: " << key - << " | Using default value"; - return default_value; - } - - if (!value->is()) { - PLOGE << "[Config] Type mismatch for key: " << key - << " | Expected type does not match | Using default value"; - return default_value; - } - - PLOGD << "[Config] Read key: " << key; - - return value->as(); - } - - std::string get_path_or_default(const std::string& key, const std::string& def) const - { - std::string result = get_or_default(key, def); - - std::filesystem::path p(result); - - if (p.is_relative()) { - std::filesystem::path full = - std::filesystem::path(config_path).parent_path() / p; - - PLOGD << "[Config] Resolved relative path: " << result - << " -> " << full.string(); - - return full.string(); - } - - PLOGD << "[Config] Using absolute path: " << result; - - return result; + bool is_valid() const { + return valid; } }; } \ No newline at end of file From 3ce1bccf02869aaa4f61e6326aded42389d2513c Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Tue, 24 Mar 2026 19:56:51 +0800 Subject: [PATCH 12/37] Impl: Read config and print --- includes/JuiceAgent/JuiceAgent.h | 19 -------- includes/JuiceAgent/JuiceAgent.hpp | 14 ++++++ src/libloader/common/libloader.cpp | 5 +- src/libloader/includes/config.hpp | 76 +++++++++++++++++++++++++++++- 4 files changed, 91 insertions(+), 23 deletions(-) delete mode 100644 includes/JuiceAgent/JuiceAgent.h create mode 100644 includes/JuiceAgent/JuiceAgent.hpp diff --git a/includes/JuiceAgent/JuiceAgent.h b/includes/JuiceAgent/JuiceAgent.h deleted file mode 100644 index 5d94747..0000000 --- a/includes/JuiceAgent/JuiceAgent.h +++ /dev/null @@ -1,19 +0,0 @@ -#ifndef JUICEAGENT_H -#define JUICEAGENT_H - -#define INJECT_PATH_MAX 260 - -typedef struct _InjectionInfo { - char JuiceAgentAPIJarPath[INJECT_PATH_MAX]; - char JuiceAgentNativePath[INJECT_PATH_MAX]; - - char EntryJarPath[INJECT_PATH_MAX]; - char EntryClass[INJECT_PATH_MAX]; - char EntryMethod[INJECT_PATH_MAX]; - - char InjectionDir[INJECT_PATH_MAX]; -} InjectionInfoType; - -extern InjectionInfoType InjectionInfo; - -#endif // JUICEAGENT_H \ No newline at end of file diff --git a/includes/JuiceAgent/JuiceAgent.hpp b/includes/JuiceAgent/JuiceAgent.hpp new file mode 100644 index 0000000..690e685 --- /dev/null +++ b/includes/JuiceAgent/JuiceAgent.hpp @@ -0,0 +1,14 @@ +#pragma once + +#include + +struct InjectionInfo { + std::string JuiceAgentAPIJarPath; + std::string JuiceAgentNativePath; + + std::string EntryJarPath; + std::string EntryClass; + std::string EntryMethod; + + std::string InjectionDir; +}; \ No newline at end of file diff --git a/src/libloader/common/libloader.cpp b/src/libloader/common/libloader.cpp index a9062d0..0346598 100644 --- a/src/libloader/common/libloader.cpp +++ b/src/libloader/common/libloader.cpp @@ -1,3 +1,4 @@ +#include #include #include @@ -7,9 +8,9 @@ namespace libloader config::Config cfg(runtime_dir); if (!cfg.is_valid()) { PLOGE << "Invalid config"; - return; } - + InjectionInfo info = cfg.get_injection_info(); + config::print_injection_info(info); } } // namespace libloader diff --git a/src/libloader/includes/config.hpp b/src/libloader/includes/config.hpp index 68fdf30..82d8e34 100644 --- a/src/libloader/includes/config.hpp +++ b/src/libloader/includes/config.hpp @@ -1,6 +1,7 @@ #pragma once #include +#include #include #include #include @@ -9,13 +10,15 @@ namespace config { class Config { private: + std::string runtime_dir; toml::Value config{}; bool valid = false; public: - explicit Config(const char* c_runtime_dir) { + explicit Config(const char* c_runtime_dir) + : runtime_dir(c_runtime_dir) { std::filesystem::path path = std::filesystem::path(c_runtime_dir) / "config.toml"; - + std::ifstream ifs(path); if (!ifs.is_open()) { PLOGE << "Failed to open config file: " << path; @@ -37,8 +40,77 @@ namespace config } } + template + T get_or_default(const std::string& key, const T& default_value) const { + if (!valid) return default_value; + + const toml::Value* current = &config; + + size_t start = 0; + while (true) { + size_t dot = key.find('.', start); + std::string part = key.substr(start, dot - start); + + if (!current->is()) { + return default_value; + } + + auto it = current->as().find(part); + if (it == current->as().end()) { + return default_value; + } + + current = &it->second; + + if (dot == std::string::npos) break; + start = dot + 1; + } + + try { + return current->as(); + } catch (...) { + return default_value; + } + } + bool is_valid() const { return valid; } + + InjectionInfo get_injection_info() { + InjectionInfo info; + auto get_default_path = [&](const std::string& name) -> std::string { + return (std::filesystem::path(runtime_dir) / name).string(); + }; + + // [JuiceAgent] + // -- APIJarPath = "runtime_dir/JuiceAgent.jar" + info.JuiceAgentAPIJarPath = get_or_default("JuiceAgent.APIJarPath", get_default_path("JuiceAgent.jar")); + // -- JuiceAgentNativePath = "runtime_dir/libagent.dll/.so" + info.JuiceAgentNativePath = get_or_default("JuiceAgent.JuiceAgentNativePath", get_default_path("libagent.dll")); + + // [Entry] + // -- EntryJarPath = "runtime_dir/entry.jar" + info.EntryJarPath = get_or_default("Entry.EntryJarPath", get_default_path("entry.jar")); + // -- EntryClass = "com.example.Entry" + info.EntryClass = get_or_default("Entry.EntryClass", "com.example.Entry"); + // -- EntryMethod = "start" + info.EntryMethod = get_or_default("Entry.EntryMethod", "start"); + + // [Runtime] + // -- InjectionDir = "runtime_dir/injection" + info.InjectionDir = get_or_default("Runtime.InjectionDir", get_default_path("injection")); + + return info; + } }; + + void print_injection_info(const InjectionInfo& info) { + PLOGI << "JuiceAgent Injection Info:"; + PLOGI << " JuiceAgentNativePath: " << info.JuiceAgentNativePath; + PLOGI << " EntryJarPath: " << info.EntryJarPath; + PLOGI << " EntryClass: " << info.EntryClass; + PLOGI << " EntryMethod: " << info.EntryMethod; + PLOGI << " InjectionDir: " << info.InjectionDir; + } } \ No newline at end of file From 3e3f9d1c1458e448f72575777d1073d280e65622 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Mon, 30 Mar 2026 13:28:32 +0800 Subject: [PATCH 13/37] Impl: Attach JavaVM --- src/libloader/common/libloader.cpp | 8 ++ src/libloader/includes/jvm.hpp | 122 +++++++++++++++++++++++++++++ 2 files changed, 130 insertions(+) create mode 100644 src/libloader/includes/jvm.hpp diff --git a/src/libloader/common/libloader.cpp b/src/libloader/common/libloader.cpp index 0346598..d9da3f0 100644 --- a/src/libloader/common/libloader.cpp +++ b/src/libloader/common/libloader.cpp @@ -1,6 +1,7 @@ #include #include #include +#include namespace libloader { @@ -12,5 +13,12 @@ namespace libloader InjectionInfo info = cfg.get_injection_info(); config::print_injection_info(info); + + jvm::Jvm jvm; + + if (!jvm.attach()) { + PLOGE << "Attach failed"; + return; + } } } // namespace libloader diff --git a/src/libloader/includes/jvm.hpp b/src/libloader/includes/jvm.hpp new file mode 100644 index 0000000..bf87ed5 --- /dev/null +++ b/src/libloader/includes/jvm.hpp @@ -0,0 +1,122 @@ +#pragma once + +#include +#include +#include +#include +#include + +namespace jvm +{ + class Jvm { + private: + JavaVM* jvm = nullptr; + jvmtiEnv* jvmti = nullptr; + + thread_local static JNIEnv* env; + + bool attached = false; + int max_try = 30; + + public: + Jvm() = default; + + ~Jvm() = default; + + JavaVM* get_jvm() const { return jvm; } + JNIEnv* get_env() const { return env; } + jvmtiEnv* get_jvmti() const { return jvmti; } + + bool attach() { + // reset state + jvm = nullptr; + jvmti = nullptr; + env = nullptr; + attached = false; + + jint status = JNI_ERR; + + // ======== Get JavaVM ======== + for (int i = 0; i < max_try; i++) { + status = JNI_GetCreatedJavaVMs(&jvm, 1, nullptr); + + if (status == JNI_OK && jvm != nullptr) { + PLOGI << "Got JavaVM"; + break; + } + + PLOGE << "Failed to get JavaVM: " << status; + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + } + + if (!jvm) { + PLOGF << "JavaVM not found!"; + return false; + } + + // ======== Get JNIEnv ======== + for (int i = 0; i < max_try; i++) { + status = jvm->GetEnv((void**)&env, JNI_VERSION_1_6); + + if (status == JNI_OK && env != nullptr) { + PLOGI << "Got JNIEnv (already attached)"; + break; + } + + // try attach + status = jvm->AttachCurrentThread((void**)&env, nullptr); + if (status == JNI_OK && env != nullptr) { + attached = true; + PLOGI << "Attached current thread"; + break; + } + + PLOGE << "Attach failed: " << status; + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + } + + if (!env) { + PLOGF << "Failed to get JNIEnv"; + return false; + } + + // ======== Get JVMTI ======== + for (int i = 0; i < max_try; i++) { + status = jvm->GetEnv((void**)&jvmti, JVMTI_VERSION_1_2); + + if (status == JNI_OK && jvmti != nullptr) { + PLOGI << "Got JVMTI"; + break; + } + + PLOGE << "Failed to get JVMTI: " << status; + std::this_thread::sleep_for(std::chrono::milliseconds(1000)); + } + + if (!jvmti) { + PLOGF << "Failed to get JVMTI"; + return false; + } + + return true; + } + + bool detach() { + if (jvm && attached) { + jint res = jvm->DetachCurrentThread(); + if (res != JNI_OK) { + PLOGE << "DetachCurrentThread failed: " << res; + return false; + } + + PLOGI << "Thread detached"; + attached = false; + env = nullptr; + } + return true; + } + }; + + thread_local JNIEnv* Jvm::env = nullptr; + +} // namespace jvm \ No newline at end of file From e5ac60d476ab27595fbb7881ca5b33b67b2a70e5 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Mon, 30 Mar 2026 13:37:30 +0800 Subject: [PATCH 14/37] BugFix: Wrong config key --- src/libloader/includes/config.hpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/libloader/includes/config.hpp b/src/libloader/includes/config.hpp index 82d8e34..519cefe 100644 --- a/src/libloader/includes/config.hpp +++ b/src/libloader/includes/config.hpp @@ -85,7 +85,7 @@ namespace config // [JuiceAgent] // -- APIJarPath = "runtime_dir/JuiceAgent.jar" - info.JuiceAgentAPIJarPath = get_or_default("JuiceAgent.APIJarPath", get_default_path("JuiceAgent.jar")); + info.JuiceAgentAPIJarPath = get_or_default("JuiceAgent.JuiceAgentAPIJarPath", get_default_path("JuiceAgent.jar")); // -- JuiceAgentNativePath = "runtime_dir/libagent.dll/.so" info.JuiceAgentNativePath = get_or_default("JuiceAgent.JuiceAgentNativePath", get_default_path("libagent.dll")); @@ -107,6 +107,7 @@ namespace config void print_injection_info(const InjectionInfo& info) { PLOGI << "JuiceAgent Injection Info:"; + PLOGI << " JuiceAgentAPIJarPath: " << info.JuiceAgentAPIJarPath; PLOGI << " JuiceAgentNativePath: " << info.JuiceAgentNativePath; PLOGI << " EntryJarPath: " << info.EntryJarPath; PLOGI << " EntryClass: " << info.EntryClass; From c5817a3b065ddd084a508e42b5a6c58925447dae Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Mon, 30 Mar 2026 13:37:51 +0800 Subject: [PATCH 15/37] Impl: Inject JuiceLoaderAPI --- src/libloader/common/libloader.cpp | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/libloader/common/libloader.cpp b/src/libloader/common/libloader.cpp index d9da3f0..0d9d394 100644 --- a/src/libloader/common/libloader.cpp +++ b/src/libloader/common/libloader.cpp @@ -6,6 +6,8 @@ namespace libloader { void entrypoint(const char* runtime_dir) { + + // Load Config config::Config cfg(runtime_dir); if (!cfg.is_valid()) { PLOGE << "Invalid config"; @@ -14,11 +16,19 @@ namespace libloader InjectionInfo info = cfg.get_injection_info(); config::print_injection_info(info); + // Attach to JVM jvm::Jvm jvm; if (!jvm.attach()) { PLOGE << "Attach failed"; return; } + + // Inject JuiceLoaderAPI.jar + jint status = jvm.get_jvmti()->AddToSystemClassLoaderSearch(info.JuiceAgentAPIJarPath.c_str()); + if (status != JNI_OK) { + PLOGE << "AddToSystemClassLoaderSearch failed: " << status; + } + } } // namespace libloader From 15d7f0295a1905cd1686a8c9e3efce0f7460e918 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Mon, 30 Mar 2026 13:49:47 +0800 Subject: [PATCH 16/37] Patch: AI Fix --- src/libloader/common/libloader.cpp | 45 +++++++++++++++++++++--------- 1 file changed, 32 insertions(+), 13 deletions(-) diff --git a/src/libloader/common/libloader.cpp b/src/libloader/common/libloader.cpp index 0d9d394..06240a5 100644 --- a/src/libloader/common/libloader.cpp +++ b/src/libloader/common/libloader.cpp @@ -5,30 +5,49 @@ namespace libloader { - void entrypoint(const char* runtime_dir) { + void entrypoint(const char* runtime_dir) + { + if (runtime_dir == nullptr) { + PLOGE << "runtime_dir is null, fallback may fail"; + } - // Load Config + // Load Config (allow fallback) config::Config cfg(runtime_dir); if (!cfg.is_valid()) { - PLOGE << "Invalid config"; + PLOGW << "Invalid config, using default values"; } InjectionInfo info = cfg.get_injection_info(); config::print_injection_info(info); - // Attach to JVM - jvm::Jvm jvm; - - if (!jvm.attach()) { - PLOGE << "Attach failed"; + // Validate injection path early + if (info.JuiceAgentAPIJarPath.empty()) { + PLOGE << "JuiceAgentAPIJarPath is empty, abort injection"; return; } - // Inject JuiceLoaderAPI.jar - jint status = jvm.get_jvmti()->AddToSystemClassLoaderSearch(info.JuiceAgentAPIJarPath.c_str()); - if (status != JNI_OK) { - PLOGE << "AddToSystemClassLoaderSearch failed: " << status; + // Attach to JVM + jvm::Jvm jvm; + if (!jvm.attach()) { + PLOGE << "Attach to JVM failed"; + return; } + auto* jvmti = jvm.get_jvmti(); + if (jvmti == nullptr) { + PLOGE << "JVMTI is null"; + return; + } + + // Inject JuiceAgentAPI.jar + const char* jar_path = info.JuiceAgentAPIJarPath.c_str(); + jint status = jvmti->AddToSystemClassLoaderSearch(jar_path); + + if (status != JNI_OK) { + PLOGE << "AddToSystemClassLoaderSearch failed: " << status; + return; + } + + PLOGI << "Jar injected successfully: " << jar_path; } -} // namespace libloader +} // namespace libloader \ No newline at end of file From 0a4ec5e97a4e3b5859e4c4780b240fe5e2d2e4db Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Mon, 30 Mar 2026 14:14:40 +0800 Subject: [PATCH 17/37] Impl: Invoke JuiceAgentAPI start --- src/libloader/common/libloader.cpp | 62 ++++++++++++++++++++++++++++ src/libloader/includes/libloader.hpp | 8 ++++ 2 files changed, 70 insertions(+) diff --git a/src/libloader/common/libloader.cpp b/src/libloader/common/libloader.cpp index 06240a5..6991870 100644 --- a/src/libloader/common/libloader.cpp +++ b/src/libloader/common/libloader.cpp @@ -5,6 +5,66 @@ namespace libloader { + // 累了,这几把的代码扔给AI算了 气死了 + bool invoke_juiceagent_init(JNIEnv* env, const InjectionInfo& info) { + std::string bootstrap_class = "cn/xiaozhou233/juiceagent/api/JuiceAgentBootstrap"; + std::string method_name = "start"; + std::string method_desc = "([Ljava/lang/String;)V"; + + // Find Class + jclass bootstrap_class_obj = env->FindClass(bootstrap_class.c_str()); + if (!bootstrap_class_obj) { + if (env->ExceptionCheck()) { + env->ExceptionDescribe(); + env->ExceptionClear(); + } + PLOGE << "Failed to find JuiceAgentBootstrap class: " << bootstrap_class; + return false; + } + + // Find Method + jmethodID method_id = env->GetStaticMethodID(bootstrap_class_obj, method_name.c_str(), method_desc.c_str()); + if (!method_id) { + if (env->ExceptionCheck()) { + env->ExceptionDescribe(); + env->ExceptionClear(); + } + PLOGE << "Failed to find method: " << method_name; + return false; + } + + // Prepare arguments (order matters) + const char* args[] = { + info.EntryJarPath.c_str(), + info.EntryClass.c_str(), + info.EntryMethod.c_str(), + info.InjectionDir.c_str(), + info.JuiceAgentNativePath.c_str() + }; + int argCount = sizeof(args) / sizeof(args[0]); + + jclass stringCls = env->FindClass("java/lang/String"); + jobjectArray jArgs = env->NewObjectArray(argCount, stringCls, nullptr); + for (int i = 0; i < argCount; i++) { + env->SetObjectArrayElement(jArgs, i, env->NewStringUTF(args[i])); + } + + // Invoke the method + env->CallStaticVoidMethod(bootstrap_class_obj, method_id, jArgs); + if (env->ExceptionCheck()) { + env->ExceptionDescribe(); + env->ExceptionClear(); + } + + // Cleanup + env->DeleteLocalRef(jArgs); + env->DeleteLocalRef(stringCls); + + PLOGI << "JuiceAgentBootstrap.start invoked successfully"; + return true; + } + + void entrypoint(const char* runtime_dir) { if (runtime_dir == nullptr) { @@ -49,5 +109,7 @@ namespace libloader } PLOGI << "Jar injected successfully: " << jar_path; + + invoke_juiceagent_init(jvm.get_env(), info); } } // namespace libloader \ No newline at end of file diff --git a/src/libloader/includes/libloader.hpp b/src/libloader/includes/libloader.hpp index 091d41d..7521fe0 100644 --- a/src/libloader/includes/libloader.hpp +++ b/src/libloader/includes/libloader.hpp @@ -1,6 +1,14 @@ #pragma once +#include +#include +#include +#include +#include + namespace libloader { void entrypoint(const char* runtime_dir); + + bool invoke_juiceagent_init(JNIEnv* env, const InjectionInfo& info); } // namespace libloader From 72c0518ebcedb874289d1c4eea0c78bf39f27bcd Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Mon, 30 Mar 2026 14:19:38 +0800 Subject: [PATCH 18/37] BugFix: No default value was retrieved when the configuration value was empty --- src/libloader/includes/config.hpp | 32 ++++++++++++++++--------------- 1 file changed, 17 insertions(+), 15 deletions(-) diff --git a/src/libloader/includes/config.hpp b/src/libloader/includes/config.hpp index 519cefe..ca0796a 100644 --- a/src/libloader/includes/config.hpp +++ b/src/libloader/includes/config.hpp @@ -41,24 +41,20 @@ namespace config } template - T get_or_default(const std::string& key, const T& default_value) const { + T get_or_default(const std::string& key, const T& default_value, bool use_default_if_empty = false) const { if (!valid) return default_value; const toml::Value* current = &config; - size_t start = 0; + while (true) { size_t dot = key.find('.', start); std::string part = key.substr(start, dot - start); - if (!current->is()) { - return default_value; - } + if (!current->is()) return default_value; auto it = current->as().find(part); - if (it == current->as().end()) { - return default_value; - } + if (it == current->as().end()) return default_value; current = &it->second; @@ -67,7 +63,13 @@ namespace config } try { - return current->as(); + if constexpr (std::is_same_v) { + std::string value = current->as(); + if (use_default_if_empty && value.empty()) return default_value; + return value; + } else { + return current->as(); + } } catch (...) { return default_value; } @@ -85,21 +87,21 @@ namespace config // [JuiceAgent] // -- APIJarPath = "runtime_dir/JuiceAgent.jar" - info.JuiceAgentAPIJarPath = get_or_default("JuiceAgent.JuiceAgentAPIJarPath", get_default_path("JuiceAgent.jar")); + info.JuiceAgentAPIJarPath = get_or_default("JuiceAgent.JuiceAgentAPIJarPath", get_default_path("JuiceAgent.jar"), true); // -- JuiceAgentNativePath = "runtime_dir/libagent.dll/.so" - info.JuiceAgentNativePath = get_or_default("JuiceAgent.JuiceAgentNativePath", get_default_path("libagent.dll")); + info.JuiceAgentNativePath = get_or_default("JuiceAgent.JuiceAgentNativePath", get_default_path("libagent.dll"), true); // [Entry] // -- EntryJarPath = "runtime_dir/entry.jar" - info.EntryJarPath = get_or_default("Entry.EntryJarPath", get_default_path("entry.jar")); + info.EntryJarPath = get_or_default("Entry.EntryJarPath", get_default_path("entry.jar"), true); // -- EntryClass = "com.example.Entry" - info.EntryClass = get_or_default("Entry.EntryClass", "com.example.Entry"); + info.EntryClass = get_or_default("Entry.EntryClass", "com.example.Entry", true); // -- EntryMethod = "start" - info.EntryMethod = get_or_default("Entry.EntryMethod", "start"); + info.EntryMethod = get_or_default("Entry.EntryMethod", "start", true); // [Runtime] // -- InjectionDir = "runtime_dir/injection" - info.InjectionDir = get_or_default("Runtime.InjectionDir", get_default_path("injection")); + info.InjectionDir = get_or_default("Runtime.InjectionDir", get_default_path("injection"), true); return info; } From 3362e2071c658af678169bd97a16460cf3c63499 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Mon, 30 Mar 2026 17:38:46 +0800 Subject: [PATCH 19/37] Patch: AI Fix --- src/libloader/common/libloader.cpp | 214 ++++++++++++----------- src/libloader/includes/config.hpp | 271 ++++++++++++++++++----------- 2 files changed, 281 insertions(+), 204 deletions(-) diff --git a/src/libloader/common/libloader.cpp b/src/libloader/common/libloader.cpp index 6991870..1619ef7 100644 --- a/src/libloader/common/libloader.cpp +++ b/src/libloader/common/libloader.cpp @@ -1,115 +1,133 @@ +#pragma once + #include #include #include #include -namespace libloader -{ - // 累了,这几把的代码扔给AI算了 气死了 - bool invoke_juiceagent_init(JNIEnv* env, const InjectionInfo& info) { - std::string bootstrap_class = "cn/xiaozhou233/juiceagent/api/JuiceAgentBootstrap"; - std::string method_name = "start"; - std::string method_desc = "([Ljava/lang/String;)V"; +namespace libloader { - // Find Class - jclass bootstrap_class_obj = env->FindClass(bootstrap_class.c_str()); - if (!bootstrap_class_obj) { - if (env->ExceptionCheck()) { - env->ExceptionDescribe(); - env->ExceptionClear(); - } - PLOGE << "Failed to find JuiceAgentBootstrap class: " << bootstrap_class; - return false; - } - - // Find Method - jmethodID method_id = env->GetStaticMethodID(bootstrap_class_obj, method_name.c_str(), method_desc.c_str()); - if (!method_id) { - if (env->ExceptionCheck()) { - env->ExceptionDescribe(); - env->ExceptionClear(); - } - PLOGE << "Failed to find method: " << method_name; - return false; - } - - // Prepare arguments (order matters) - const char* args[] = { - info.EntryJarPath.c_str(), - info.EntryClass.c_str(), - info.EntryMethod.c_str(), - info.InjectionDir.c_str(), - info.JuiceAgentNativePath.c_str() - }; - int argCount = sizeof(args) / sizeof(args[0]); - - jclass stringCls = env->FindClass("java/lang/String"); - jobjectArray jArgs = env->NewObjectArray(argCount, stringCls, nullptr); - for (int i = 0; i < argCount; i++) { - env->SetObjectArrayElement(jArgs, i, env->NewStringUTF(args[i])); - } - - // Invoke the method - env->CallStaticVoidMethod(bootstrap_class_obj, method_id, jArgs); +namespace { + // Check for JNI exceptions and clear them + bool check_and_clear_exception(JNIEnv* env, const char* context) { if (env->ExceptionCheck()) { + PLOGE << "JNI Exception occurred at: " << context; env->ExceptionDescribe(); env->ExceptionClear(); + return true; } - - // Cleanup - env->DeleteLocalRef(jArgs); - env->DeleteLocalRef(stringCls); - - PLOGI << "JuiceAgentBootstrap.start invoked successfully"; - return true; + return false; } - - void entrypoint(const char* runtime_dir) - { - if (runtime_dir == nullptr) { - PLOGE << "runtime_dir is null, fallback may fail"; + // RAII wrapper for local JNI references + template + class LocalRef { + private: + JNIEnv* env; + T ref; + public: + LocalRef(JNIEnv* env, T ref) : env(env), ref(ref) {} + ~LocalRef() { + if (ref) env->DeleteLocalRef(ref); } + T get() const { return ref; } + operator T() const { return ref; } + }; +} - // Load Config (allow fallback) - config::Config cfg(runtime_dir); - if (!cfg.is_valid()) { - PLOGW << "Invalid config, using default values"; - } +// Invoke JuiceAgentBootstrap.start(String) via JNI +bool invoke_juiceagent_init(JNIEnv* env, const InjectionInfo& info) { + const char* bootstrap_class = "cn/xiaozhou233/juiceagent/api/JuiceAgentBootstrap"; + const char* method_name = "start"; + const char* method_desc = "(Ljava/lang/String;)V"; - InjectionInfo info = cfg.get_injection_info(); - config::print_injection_info(info); - - // Validate injection path early - if (info.JuiceAgentAPIJarPath.empty()) { - PLOGE << "JuiceAgentAPIJarPath is empty, abort injection"; - return; - } - - // Attach to JVM - jvm::Jvm jvm; - if (!jvm.attach()) { - PLOGE << "Attach to JVM failed"; - return; - } - - auto* jvmti = jvm.get_jvmti(); - if (jvmti == nullptr) { - PLOGE << "JVMTI is null"; - return; - } - - // Inject JuiceAgentAPI.jar - const char* jar_path = info.JuiceAgentAPIJarPath.c_str(); - jint status = jvmti->AddToSystemClassLoaderSearch(jar_path); - - if (status != JNI_OK) { - PLOGE << "AddToSystemClassLoaderSearch failed: " << status; - return; - } - - PLOGI << "Jar injected successfully: " << jar_path; - - invoke_juiceagent_init(jvm.get_env(), info); + // Find Java class + LocalRef cls(env, env->FindClass(bootstrap_class)); + if (!cls.get() || check_and_clear_exception(env, "FindClass")) { + PLOGE << "Failed to find class: " << bootstrap_class; + return false; } + + // Find static method + jmethodID method_id = env->GetStaticMethodID(cls, method_name, method_desc); + if (!method_id || check_and_clear_exception(env, "GetStaticMethodID")) { + PLOGE << "Failed to find method: " << method_name; + return false; + } + + // Serialize InjectionInfo to string + std::string args = config::Config::serialize(info); + PLOGD << "Invoke args: " << args; + + // Create Java string + LocalRef jArgs(env, env->NewStringUTF(args.c_str())); + if (!jArgs.get() || check_and_clear_exception(env, "NewStringUTF")) { + PLOGE << "Failed to create jstring"; + return false; + } + + // Call the static method + env->CallStaticVoidMethod(cls, method_id, jArgs); + + // Check for exceptions + if (check_and_clear_exception(env, "CallStaticVoidMethod")) { + return false; + } + + PLOGI << "JuiceAgentBootstrap.start invoked successfully"; + return true; +} + +// Entrypoint function for loader +void entrypoint(const char* runtime_dir) { + if (!runtime_dir) { + PLOGW << "runtime_dir is null, using empty path"; + } + + // Load configuration + config::Config cfg(runtime_dir); + if (!cfg.is_valid()) { + PLOGW << "Invalid config, using default values"; + } + + // Get InjectionInfo + InjectionInfo info = cfg.get_injection_info(); + config::print_injection_info(info); + + // Validate essential paths + if (info.JuiceAgentAPIJarPath.empty()) { + PLOGE << "JuiceAgentAPIJarPath is empty, abort injection"; + return; + } + + // Attach to JVM + jvm::Jvm jvm; + if (!jvm.attach()) { + PLOGE << "Attach to JVM failed"; + return; + } + + JNIEnv* env = jvm.get_env(); + auto* jvmti = jvm.get_jvmti(); + + if (!env || !jvmti) { + PLOGE << "JNIEnv or JVMTI is null"; + return; + } + + // Inject JuiceAgent jar into system class loader + jint status = jvmti->AddToSystemClassLoaderSearch(info.JuiceAgentAPIJarPath.c_str()); + if (status != JNI_OK) { + PLOGE << "AddToSystemClassLoaderSearch failed: " << status; + return; + } + + PLOGI << "Jar injected successfully: " << info.JuiceAgentAPIJarPath; + + // Invoke JuiceAgent initialization + if (!invoke_juiceagent_init(env, info)) { + PLOGE << "invoke_juiceagent_init failed"; + } +} + } // namespace libloader \ No newline at end of file diff --git a/src/libloader/includes/config.hpp b/src/libloader/includes/config.hpp index ca0796a..5856c5f 100644 --- a/src/libloader/includes/config.hpp +++ b/src/libloader/includes/config.hpp @@ -5,115 +5,174 @@ #include #include #include +#include -namespace config -{ - class Config { - private: - std::string runtime_dir; - toml::Value config{}; - bool valid = false; +namespace config { - public: - explicit Config(const char* c_runtime_dir) - : runtime_dir(c_runtime_dir) { - std::filesystem::path path = std::filesystem::path(c_runtime_dir) / "config.toml"; - - std::ifstream ifs(path); - if (!ifs.is_open()) { - PLOGE << "Failed to open config file: " << path; +class Config { +private: + std::string runtime_dir; // Runtime directory + toml::Value config{}; // Parsed TOML configuration + bool valid = false; // Whether the config is successfully loaded + + // Escape special characters ';' = '\' + static std::string escape(const std::string& s) { + std::string out; + out.reserve(s.size()); + for (char c : s) { + if (c == ';' || c == '=' || c == '\\') { + out += '\\'; + } + out += c; + } + return out; + } + + // Append key=value pair to string + static void append_kv(std::string& out, const char* key, const std::string& value, bool& first) { + if (!first) out += ';'; + first = false; + out += key; + out += '='; + out += escape(value); + } + + // Helper function: find value by dot-separated key + const toml::Value* find_value(const std::string& key) const { + if (!valid) return nullptr; + const toml::Value* current = &config; + size_t start = 0; + while (true) { + size_t dot = key.find('.', start); + std::string part = key.substr(start, dot - start); + + if (!current->is()) return nullptr; + + const auto& table = current->as(); + auto it = table.find(part); + if (it == table.end()) return nullptr; + + current = &it->second; + + if (dot == std::string::npos) break; + start = dot + 1; + } + return current; + } + +public: + explicit Config(const char* c_runtime_dir) + : runtime_dir(c_runtime_dir ? c_runtime_dir : "") + { + if (runtime_dir.empty()) { + PLOGW << "runtime_dir is empty"; + return; + } + + std::filesystem::path path = std::filesystem::path(runtime_dir) / "config.toml"; + std::ifstream ifs(path); + if (!ifs.is_open()) { + PLOGE << "Failed to open config file: " << path; + return; + } + + try { + auto pr = toml::parse(ifs); + if (!pr.valid()) { + PLOGE << "Invalid TOML file: " << pr.errorReason; return; } - - try { - auto pr = toml::parse(ifs); - - if (!pr.valid()) { - PLOGE << "Invalid TOML file: " << pr.errorReason; - return; - } - - config = pr.value; - valid = true; - } catch (const std::exception& e) { - PLOGE << "TOML parse error: " << e.what(); - } + config = pr.value; + valid = true; + } catch (const std::exception& e) { + PLOGE << "TOML parse error: " << e.what(); } - - template - T get_or_default(const std::string& key, const T& default_value, bool use_default_if_empty = false) const { - if (!valid) return default_value; - - const toml::Value* current = &config; - size_t start = 0; - - while (true) { - size_t dot = key.find('.', start); - std::string part = key.substr(start, dot - start); - - if (!current->is()) return default_value; - - auto it = current->as().find(part); - if (it == current->as().end()) return default_value; - - current = &it->second; - - if (dot == std::string::npos) break; - start = dot + 1; - } - - try { - if constexpr (std::is_same_v) { - std::string value = current->as(); - if (use_default_if_empty && value.empty()) return default_value; - return value; - } else { - return current->as(); - } - } catch (...) { - return default_value; - } - } - - bool is_valid() const { - return valid; - } - - InjectionInfo get_injection_info() { - InjectionInfo info; - auto get_default_path = [&](const std::string& name) -> std::string { - return (std::filesystem::path(runtime_dir) / name).string(); - }; - - // [JuiceAgent] - // -- APIJarPath = "runtime_dir/JuiceAgent.jar" - info.JuiceAgentAPIJarPath = get_or_default("JuiceAgent.JuiceAgentAPIJarPath", get_default_path("JuiceAgent.jar"), true); - // -- JuiceAgentNativePath = "runtime_dir/libagent.dll/.so" - info.JuiceAgentNativePath = get_or_default("JuiceAgent.JuiceAgentNativePath", get_default_path("libagent.dll"), true); - - // [Entry] - // -- EntryJarPath = "runtime_dir/entry.jar" - info.EntryJarPath = get_or_default("Entry.EntryJarPath", get_default_path("entry.jar"), true); - // -- EntryClass = "com.example.Entry" - info.EntryClass = get_or_default("Entry.EntryClass", "com.example.Entry", true); - // -- EntryMethod = "start" - info.EntryMethod = get_or_default("Entry.EntryMethod", "start", true); - - // [Runtime] - // -- InjectionDir = "runtime_dir/injection" - info.InjectionDir = get_or_default("Runtime.InjectionDir", get_default_path("injection"), true); - - return info; - } - }; - - void print_injection_info(const InjectionInfo& info) { - PLOGI << "JuiceAgent Injection Info:"; - PLOGI << " JuiceAgentAPIJarPath: " << info.JuiceAgentAPIJarPath; - PLOGI << " JuiceAgentNativePath: " << info.JuiceAgentNativePath; - PLOGI << " EntryJarPath: " << info.EntryJarPath; - PLOGI << " EntryClass: " << info.EntryClass; - PLOGI << " EntryMethod: " << info.EntryMethod; - PLOGI << " InjectionDir: " << info.InjectionDir; } -} \ No newline at end of file + + // Get value by key with default + template + T get_or_default(const std::string& key, const T& default_value, bool use_default_if_empty = false) const { + const toml::Value* val = find_value(key); + if (!val) return default_value; + + try { + if constexpr (std::is_same_v) { + std::string s = val->as(); + if (use_default_if_empty && s.empty()) return default_value; + return s; + } else { + return val->as(); + } + } catch (...) { + return default_value; + } + } + + bool is_valid() const { + return valid; + } + + // Get InjectionInfo struct from config + InjectionInfo get_injection_info() const { + InjectionInfo info; + + auto get_default_path = [&](const std::string& name) { + return (std::filesystem::path(runtime_dir) / name).string(); + }; + + info.JuiceAgentAPIJarPath = get_or_default( + "JuiceAgent.JuiceAgentAPIJarPath", get_default_path("JuiceAgent.jar"), true); + + info.JuiceAgentNativePath = get_or_default( + "JuiceAgent.JuiceAgentNativePath", get_default_path("libagent.dll"), true); + + info.EntryJarPath = get_or_default( + "Entry.EntryJarPath", get_default_path("entry.jar"), true); + + info.EntryClass = get_or_default( + "Entry.EntryClass", "com.example.Entry", true); + + info.EntryMethod = get_or_default( + "Entry.EntryMethod", "start", true); + + info.InjectionDir = get_or_default( + "Runtime.InjectionDir", get_default_path("injection"), true); + + return info; + } + + // Serialize InjectionInfo to key=value; format + static std::string serialize(const InjectionInfo& info) { + std::string result; + result.reserve(256); + bool first = true; + + append_kv(result, "version", "1", first); + append_kv(result, "juiceAgentAPIJarPath", info.JuiceAgentAPIJarPath, first); + append_kv(result, "juiceAgentNativePath", info.JuiceAgentNativePath, first); + append_kv(result, "entryJarPath", info.EntryJarPath, first); + append_kv(result, "entryClass", info.EntryClass, first); + append_kv(result, "entryMethod", info.EntryMethod, first); + append_kv(result, "injectionDir", info.InjectionDir, first); + + PLOGD << "Serialized args: " << result; + return result; + } + + std::string serialize() const { + return serialize(get_injection_info()); + } +}; + +// Print InjectionInfo (debug) +inline void print_injection_info(const InjectionInfo& info) { + PLOGI << "JuiceAgent Injection Info:"; + PLOGI << " JuiceAgentAPIJarPath: " << info.JuiceAgentAPIJarPath; + PLOGI << " JuiceAgentNativePath: " << info.JuiceAgentNativePath; + PLOGI << " EntryJarPath: " << info.EntryJarPath; + PLOGI << " EntryClass: " << info.EntryClass; + PLOGI << " EntryMethod: " << info.EntryMethod; + PLOGI << " InjectionDir: " << info.InjectionDir; +} + +} // namespace config \ No newline at end of file From 8421d3817af2d6a7a5cb2a1474122d75bb3925a2 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Mon, 30 Mar 2026 17:40:14 +0800 Subject: [PATCH 20/37] Fix: #pragma once --- src/libloader/common/libloader.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/libloader/common/libloader.cpp b/src/libloader/common/libloader.cpp index 1619ef7..fc5cef4 100644 --- a/src/libloader/common/libloader.cpp +++ b/src/libloader/common/libloader.cpp @@ -1,5 +1,3 @@ -#pragma once - #include #include #include From 6350bfb0ec8fe92474b7469600b338b1493ee443 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Mon, 30 Mar 2026 18:51:19 +0800 Subject: [PATCH 21/37] Refactor: Rename key --- src/libloader/includes/config.hpp | 17 ++++++++++------- 1 file changed, 10 insertions(+), 7 deletions(-) diff --git a/src/libloader/includes/config.hpp b/src/libloader/includes/config.hpp index 5856c5f..152aeb3 100644 --- a/src/libloader/includes/config.hpp +++ b/src/libloader/includes/config.hpp @@ -147,13 +147,16 @@ public: result.reserve(256); bool first = true; - append_kv(result, "version", "1", first); - append_kv(result, "juiceAgentAPIJarPath", info.JuiceAgentAPIJarPath, first); - append_kv(result, "juiceAgentNativePath", info.JuiceAgentNativePath, first); - append_kv(result, "entryJarPath", info.EntryJarPath, first); - append_kv(result, "entryClass", info.EntryClass, first); - append_kv(result, "entryMethod", info.EntryMethod, first); - append_kv(result, "injectionDir", info.InjectionDir, first); + append_kv(result, "Version", "1", first); + + append_kv(result, "EntryJarPath", info.EntryJarPath, first); + append_kv(result, "EntryClass", info.EntryClass, first); + append_kv(result, "EntryMethod", info.EntryMethod, first); + + append_kv(result, "JuiceAgentAPIJarPath", info.JuiceAgentAPIJarPath, first); + append_kv(result, "JuiceAgentNativePath", info.JuiceAgentNativePath, first); + + append_kv(result, "InjectionDir", info.InjectionDir, first); PLOGD << "Serialized args: " << result; return result; From d6d17aac359d636af9141be8b298c61f0c6abdb5 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Mon, 30 Mar 2026 19:03:10 +0800 Subject: [PATCH 22/37] BugFix: null jstring --- src/libloader/common/libloader.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libloader/common/libloader.cpp b/src/libloader/common/libloader.cpp index fc5cef4..b492d07 100644 --- a/src/libloader/common/libloader.cpp +++ b/src/libloader/common/libloader.cpp @@ -58,8 +58,8 @@ bool invoke_juiceagent_init(JNIEnv* env, const InjectionInfo& info) { PLOGD << "Invoke args: " << args; // Create Java string - LocalRef jArgs(env, env->NewStringUTF(args.c_str())); - if (!jArgs.get() || check_and_clear_exception(env, "NewStringUTF")) { + jstring jArgs = env->NewStringUTF(args.c_str()); + if (!jArgs || check_and_clear_exception(env, "NewStringUTF")) { PLOGE << "Failed to create jstring"; return false; } From 1714f7603d738e6b41fcf7eb2fd2a2228cef2369 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Tue, 31 Mar 2026 22:18:52 +0800 Subject: [PATCH 23/37] Refactor: header file --- ...cn_xiaozhou233_juiceagent_api_JuiceAgent.h | 117 +++++++++++++++ .../cn_xiaozhou233_juiceloader_JuiceLoader.h | 141 ------------------ src/libagent/includes/jni_impl.h | 2 +- 3 files changed, 118 insertions(+), 142 deletions(-) create mode 100644 src/libagent/includes/cn_xiaozhou233_juiceagent_api_JuiceAgent.h delete mode 100644 src/libagent/includes/cn_xiaozhou233_juiceloader_JuiceLoader.h 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..c99f2ca --- /dev/null +++ b/src/libagent/includes/cn_xiaozhou233_juiceagent_api_JuiceAgent.h @@ -0,0 +1,117 @@ +/* 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: ()Z + */ +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init + (JNIEnv *, jclass); + +/* + * 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); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/src/libagent/includes/cn_xiaozhou233_juiceloader_JuiceLoader.h b/src/libagent/includes/cn_xiaozhou233_juiceloader_JuiceLoader.h deleted file mode 100644 index cb2d8be..0000000 --- a/src/libagent/includes/cn_xiaozhou233_juiceloader_JuiceLoader.h +++ /dev/null @@ -1,141 +0,0 @@ -/* DO NOT EDIT THIS FILE - it is machine generated */ -#include -/* Header for class cn_xiaozhou233_juiceloader_JuiceLoader */ - -#ifndef _Included_cn_xiaozhou233_juiceloader_JuiceLoader -#define _Included_cn_xiaozhou233_juiceloader_JuiceLoader -#ifdef __cplusplus -extern "C" { -#endif -/* - * Class: cn_xiaozhou233_juiceloader_JuiceLoader - * Method: init - * Signature: ()Z - */ -JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_init - (JNIEnv *, jclass); - -/* - * Class: cn_xiaozhou233_juiceloader_JuiceLoader - * Method: injectJar - * Signature: (Ljava/lang/String;)Z - */ -JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_injectJar - (JNIEnv *, jclass, jstring); - -/* - * Class: cn_xiaozhou233_juiceloader_JuiceLoader - * Method: AddToBootstrapClassLoaderSearch - * Signature: (Ljava/lang/String;)Z - */ -JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_AddToBootstrapClassLoaderSearch - (JNIEnv *, jclass, jstring); - -/* - * Class: cn_xiaozhou233_juiceloader_JuiceLoader - * Method: AddToSystemClassLoaderSearch - * Signature: (Ljava/lang/String;)Z - */ -JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_AddToSystemClassLoaderSearch - (JNIEnv *, jclass, jstring); - -/* - * Class: cn_xiaozhou233_juiceloader_JuiceLoader - * Method: AddToClassLoader - * Signature: (Ljava/lang/String;Ljava/lang/ClassLoader;)Z - */ -JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_AddToClassLoader - (JNIEnv *, jclass, jstring, jobject); - -/* - * Class: cn_xiaozhou233_juiceloader_JuiceLoader - * Method: defineClass - * Signature: (Ljava/lang/ClassLoader;[B)Ljava/lang/Class; - */ -JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_defineClass - (JNIEnv *, jclass, jobject, jbyteArray); - -/* - * Class: cn_xiaozhou233_juiceloader_JuiceLoader - * Method: redefineClass - * Signature: (Ljava/lang/Class;[BI)Z - */ -JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_redefineClass - (JNIEnv *, jclass, jclass, jbyteArray, jint); - -/* - * Class: cn_xiaozhou233_juiceloader_JuiceLoader - * Method: redefineClassByName - * Signature: (Ljava/lang/String;[BI)Z - */ -JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_redefineClassByName - (JNIEnv *, jclass, jstring, jbyteArray, jint); - -/* - * Class: cn_xiaozhou233_juiceloader_JuiceLoader - * Method: getLoadedClasses - * Signature: ()[Ljava/lang/Class; - */ -JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getLoadedClasses - (JNIEnv *, jclass); - -/* - * Class: cn_xiaozhou233_juiceloader_JuiceLoader - * Method: getClassBytes - * Signature: (Ljava/lang/Class;)[B - */ -JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytes - (JNIEnv *, jclass, jclass); - -/* - * Class: cn_xiaozhou233_juiceloader_JuiceLoader - * Method: getClassBytesByName - * Signature: (Ljava/lang/String;)[B - */ -JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytesByName - (JNIEnv *, jclass, jstring); - -/* - * Class: cn_xiaozhou233_juiceloader_JuiceLoader - * Method: retransformClass - * Signature: (Ljava/lang/Class;[BI)Z - */ -JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClass - (JNIEnv *, jclass, jclass, jbyteArray, jint); - -/* - * Class: cn_xiaozhou233_juiceloader_JuiceLoader - * Method: retransformClassByName - * Signature: (Ljava/lang/String;[BI)Z - */ -JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClassByName - (JNIEnv *, jclass, jstring, jbyteArray, jint); - -/* - * Class: cn_xiaozhou233_juiceloader_JuiceLoader - * Method: getClassByName - * Signature: (Ljava/lang/String;)Ljava/lang/Class; - */ -JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassByName - (JNIEnv *, jclass, jstring); - -/* - * Class: cn_xiaozhou233_juiceloader_JuiceLoader - * Method: nativeGetThreadByName - * Signature: (Ljava/lang/String;)Ljava/lang/Thread; - */ -JNIEXPORT jobject JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_nativeGetThreadByName - (JNIEnv *, jclass, jstring); - -/* - * Class: cn_xiaozhou233_juiceloader_JuiceLoader - * Method: nativeInjectJarToThread - * Signature: (Ljava/lang/Thread;Ljava/lang/String;)Ljava/lang/ClassLoader; - */ -JNIEXPORT jobject JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_nativeInjectJarToThread - (JNIEnv *, jclass, jobject, jstring); - -#ifdef __cplusplus -} -#endif -#endif diff --git a/src/libagent/includes/jni_impl.h b/src/libagent/includes/jni_impl.h index 3b9c594..32316b0 100644 --- a/src/libagent/includes/jni_impl.h +++ b/src/libagent/includes/jni_impl.h @@ -5,7 +5,7 @@ #include #include #include -#include +#include // Variables extern const char* g_target_internal_name; From 289b0311bfe5552cbe673e158235aa36851352e7 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Tue, 31 Mar 2026 22:24:14 +0800 Subject: [PATCH 24/37] break: delete agent src --- src/libagent/includes/jni_impl.h | 27 --- src/libagent/includes/juiceloader.h | 29 --- src/libagent/jni/loader_ClassFileLoadHook.cpp | 74 ------- src/libagent/jni/loader_class.cpp | 176 ---------------- src/libagent/jni/loader_define.cpp | 11 - src/libagent/jni/loader_init.cpp | 31 --- src/libagent/jni/loader_inject.cpp | 195 ------------------ src/libagent/jni/loader_redefine.cpp | 57 ----- src/libagent/jni/loader_retransform.cpp | 142 ------------- src/libagent/jni/loader_thread.cpp | 64 ------ src/libagent/libagent.cpp | 0 src/libagent/libjuiceloader.cpp | 67 ------ 12 files changed, 873 deletions(-) delete mode 100644 src/libagent/includes/jni_impl.h delete mode 100644 src/libagent/includes/juiceloader.h delete mode 100644 src/libagent/jni/loader_ClassFileLoadHook.cpp delete mode 100644 src/libagent/jni/loader_class.cpp delete mode 100644 src/libagent/jni/loader_define.cpp delete mode 100644 src/libagent/jni/loader_init.cpp delete mode 100644 src/libagent/jni/loader_inject.cpp delete mode 100644 src/libagent/jni/loader_redefine.cpp delete mode 100644 src/libagent/jni/loader_retransform.cpp delete mode 100644 src/libagent/jni/loader_thread.cpp create mode 100644 src/libagent/libagent.cpp delete mode 100644 src/libagent/libjuiceloader.cpp diff --git a/src/libagent/includes/jni_impl.h b/src/libagent/includes/jni_impl.h deleted file mode 100644 index 32316b0..0000000 --- a/src/libagent/includes/jni_impl.h +++ /dev/null @@ -1,27 +0,0 @@ -#ifndef JNI_IMPL_H -#define JNI_IMPL_H - -#include -#include -#include -#include -#include - -// Variables -extern const char* g_target_internal_name; -extern unsigned char* g_bytecodes; -extern jint g_bytecodes_len; - -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); - -#endif // JNI_IMPL_H \ No newline at end of file diff --git a/src/libagent/includes/juiceloader.h b/src/libagent/includes/juiceloader.h deleted file mode 100644 index f6d0866..0000000 --- a/src/libagent/includes/juiceloader.h +++ /dev/null @@ -1,29 +0,0 @@ -#ifndef JUICELOADER_H -#define JUICELOADER_H - -#include -#include - -typedef struct _JuiceLoaderNative { - jvmtiEnv *jvmti; -} JuiceLoaderNativeType; -extern JuiceLoaderNativeType JuiceLoaderNative; - -typedef struct { - char *name; - unsigned char *bytes; - int len; -} ClassBytesCacheType; - -typedef struct { - ClassBytesCacheType *arr; - int size; - int capacity; -} RetransformClassCacheType; - -extern RetransformClassCacheType RetransformClassCache; - -extern "C" __declspec(dllexport) -int InitJuiceLoader(JNIEnv *env, jvmtiEnv *jvmti); - -#endif \ No newline at end of file diff --git a/src/libagent/jni/loader_ClassFileLoadHook.cpp b/src/libagent/jni/loader_ClassFileLoadHook.cpp deleted file mode 100644 index 2fbd3de..0000000 --- a/src/libagent/jni/loader_ClassFileLoadHook.cpp +++ /dev/null @@ -1,74 +0,0 @@ -#include - -RetransformClassCacheType RetransformClassCache = {NULL, 0, 0}; - -static void throwRuntimeException(JNIEnv *env, const char *msg) { - jclass rte = env->FindClass("java/lang/RuntimeException"); - if (rte != NULL) { - env->ThrowNew(rte, msg); - } -} - -void JNICALL ClassFileLoadHook( - jvmtiEnv* jvmti_env, - JNIEnv*, - jclass, - jobject, - const char* name, - jobject, - jint class_data_len, - const unsigned char* classbytes, - jint* new_class_data_len, - unsigned char** new_classbytes) { - - if (!name) return; - - /* ========================= - * 1. Capture original bytes - * ========================= */ - if (g_target_internal_name && - g_bytecodes == nullptr && - strcmp(name, g_target_internal_name) == 0) { - - g_bytecodes_len = class_data_len; - g_bytecodes = (unsigned char*)malloc(class_data_len); - memcpy(g_bytecodes, classbytes, class_data_len); - - // IMPORTANT: - // Do NOT touch new_classbytes here - // Let JVM continue normally - PLOGD.printf("[Hook:get] Captured class bytes: %s (%d)", name, class_data_len); - return; - } - - /* ========================= - * 2. Apply redefine patch - * ========================= */ - if (RetransformClassCache.size == 0) return; - - for (int i = 0; i < RetransformClassCache.size; i++) { - ClassBytesCacheType* entry = &RetransformClassCache.arr[i]; - if (strcmp(entry->name, name) == 0) { - - unsigned char* newBytes = nullptr; - if (jvmti_env->Allocate(entry->len, &newBytes) != JVMTI_ERROR_NONE) { - PLOGE.printf("[Hook:set] Allocate failed: %s", name); - return; - } - - memcpy(newBytes, entry->bytes, entry->len); - *new_classbytes = newBytes; - *new_class_data_len = entry->len; - - PLOGI.printf("[Hook:set] Redefined class: %s (%d)", name, entry->len); - - free(entry->name); - free(entry->bytes); - for (int j = i; j < RetransformClassCache.size - 1; j++) { - RetransformClassCache.arr[j] = RetransformClassCache.arr[j + 1]; - } - RetransformClassCache.size--; - return; - } - } -} \ No newline at end of file diff --git a/src/libagent/jni/loader_class.cpp b/src/libagent/jni/loader_class.cpp deleted file mode 100644 index f5c0a3c..0000000 --- a/src/libagent/jni/loader_class.cpp +++ /dev/null @@ -1,176 +0,0 @@ -#include -#include -#include -#include - -/* ========================= - * Global bytecode capture - * ========================= */ -const char* g_target_internal_name = nullptr; -unsigned char* g_bytecodes = nullptr; -jint g_bytecodes_len = 0; - -/* ========================= - * Utils - * ========================= */ - -// Convert java name to internal name: a.b.C -> a/b/C -static void to_internal_name(char* s) { - for (; *s; ++s) { - if (*s == '.') *s = '/'; - } -} - -/* ========================= - * JVMTI: enumerate loaded classes - * ========================= */ -static jclass findLoadedClassByInternalName(jvmtiEnv* jvmti, const char* internalName) { - jint count = 0; - jclass* classes = nullptr; - - if (jvmti->GetLoadedClasses(&count, &classes) != JVMTI_ERROR_NONE || count == 0) { - return nullptr; - } - - jclass result = nullptr; - - for (jint i = 0; i < count; i++) { - char* signature = nullptr; - if (jvmti->GetClassSignature(classes[i], &signature, nullptr) == JVMTI_ERROR_NONE && signature) { - // signature format: Lnet/minecraft/xxx; - size_t len = strlen(signature); - if (len > 2 && signature[0] == 'L' && signature[len - 1] == ';') { - if (strncmp(signature + 1, internalName, len - 2) == 0) { - result = classes[i]; - jvmti->Deallocate((unsigned char*)signature); - break; - } - } - jvmti->Deallocate((unsigned char*)signature); - } - } - - if (classes) { - jvmti->Deallocate((unsigned char*)classes); - } - return result; -} - -/* ========================= - * Exposed: get all loaded classes - * ========================= */ -JNIEXPORT jobjectArray JNICALL -Java_cn_xiaozhou233_juiceloader_JuiceLoader_getLoadedClasses -(JNIEnv* env, jclass) { - - if (!JuiceLoaderNative.jvmti) return nullptr; - - jint count = 0; - jclass* classes = nullptr; - if (JuiceLoaderNative.jvmti->GetLoadedClasses(&count, &classes) != JVMTI_ERROR_NONE || count == 0) { - return env->NewObjectArray(0, env->FindClass("java/lang/Class"), nullptr); - } - - jclass classClass = env->FindClass("java/lang/Class"); - jobjectArray result = env->NewObjectArray(count, classClass, nullptr); - - for (jint i = 0; i < count; i++) { - env->SetObjectArrayElement(result, i, classes[i]); - } - - JuiceLoaderNative.jvmti->Deallocate((unsigned char*)classes); - return result; -} - -/* ========================= - * Get bytecode by jclass - * ========================= */ -JNIEXPORT jbyteArray JNICALL -Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytes -(JNIEnv* env, jclass, jclass clazz) { - - if (!JuiceLoaderNative.jvmti || !clazz) return nullptr; - - char* signature = nullptr; - if (JuiceLoaderNative.jvmti->GetClassSignature(clazz, &signature, nullptr) != JVMTI_ERROR_NONE || !signature) { - return nullptr; - } - - // Lxxx; -> xxx - std::string internalName(signature + 1, strlen(signature) - 2); - JuiceLoaderNative.jvmti->Deallocate((unsigned char*)signature); - - g_target_internal_name = internalName.c_str(); - g_bytecodes = nullptr; - g_bytecodes_len = 0; - - jvmtiError err = JuiceLoaderNative.jvmti->RetransformClasses(1, &clazz); - if (err != JVMTI_ERROR_NONE || !g_bytecodes) { - return nullptr; - } - - jbyteArray out = env->NewByteArray(g_bytecodes_len); - env->SetByteArrayRegion(out, 0, g_bytecodes_len, (jbyte*)g_bytecodes); - - free(g_bytecodes); - g_bytecodes = nullptr; - g_target_internal_name = nullptr; - - return out; -} - -/* ========================= - * Get bytecode by class name - * ========================= */ -JNIEXPORT jbyteArray JNICALL -Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytesByName -(JNIEnv* env, jclass loader_class, jstring className) { - - if (!JuiceLoaderNative.jvmti || !className) return nullptr; - - const char* utf = env->GetStringUTFChars(className, nullptr); - if (!utf) return nullptr; - - char internal[512]; - strncpy(internal, utf, sizeof(internal) - 1); - internal[sizeof(internal) - 1] = '\0'; - env->ReleaseStringUTFChars(className, utf); - - to_internal_name(internal); - - jclass clazz = findLoadedClassByInternalName(JuiceLoaderNative.jvmti, internal); - if (!clazz) { - PLOGE.printf("Class not loaded: %s", internal); - return nullptr; - } - - return Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassBytes( - env, loader_class, clazz - ); -} - -/* ========================= - * Get jclass by name (no ClassLoader) - * ========================= */ -JNIEXPORT jclass JNICALL -Java_cn_xiaozhou233_juiceloader_JuiceLoader_getClassByName -(JNIEnv* env, jclass, jstring className) { - - if (!JuiceLoaderNative.jvmti || !className) return nullptr; - - const char* utf = env->GetStringUTFChars(className, nullptr); - if (!utf) return nullptr; - - char internal[512]; - strncpy(internal, utf, sizeof(internal) - 1); - internal[sizeof(internal) - 1] = '\0'; - env->ReleaseStringUTFChars(className, utf); - - to_internal_name(internal); - - jclass clazz = findLoadedClassByInternalName(JuiceLoaderNative.jvmti, internal); - if (!clazz) { - PLOGE.printf("Failed to find loaded class: %s", internal); - } - return clazz; -} \ No newline at end of file diff --git a/src/libagent/jni/loader_define.cpp b/src/libagent/jni/loader_define.cpp deleted file mode 100644 index 939ec54..0000000 --- a/src/libagent/jni/loader_define.cpp +++ /dev/null @@ -1,11 +0,0 @@ -#include - -JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_defineClass - (JNIEnv *env, jclass, jobject cl, jbyteArray bytes) { - PLOGD << "Invoked!"; - jclass clClass = env->FindClass("java/lang/ClassLoader"); - jmethodID defineClass = env->GetMethodID(clClass, "defineClass", "([BII)Ljava/lang/Class;"); - jobject classDefined = env->CallObjectMethod(cl, defineClass, bytes, 0, - env->GetArrayLength(bytes)); - return (jclass)classDefined; -} \ No newline at end of file diff --git a/src/libagent/jni/loader_init.cpp b/src/libagent/jni/loader_init.cpp deleted file mode 100644 index bcd63de..0000000 --- a/src/libagent/jni/loader_init.cpp +++ /dev/null @@ -1,31 +0,0 @@ -#include - -JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_init -(JNIEnv *env, jclass loader_class) { - PLOGI << "Invoked!"; - - // Get JavaVM - JavaVM* jvm = nullptr; - env->GetJavaVM(&jvm); - if (jvm == nullptr) { - PLOGE << "Failed to get JavaVM instance"; - return JNI_FALSE; - } - - // Get JVMTI - jvmtiEnv* jvmti = nullptr; - jvmtiError err = static_cast(jvm->GetEnv(reinterpret_cast(&jvmti), JVMTI_VERSION_1_2)); - if (err != JVMTI_ERROR_NONE || jvmti == nullptr) { - PLOGE << "Failed to get JVMTI environment, error: " << err; - return JNI_FALSE; - } - - int result = InitJuiceLoader(env, jvmti); - if (result != 0) { - PLOGE << "Failed to initialize JuiceLoader, error code: " << result; - return JNI_FALSE; - } - - PLOGI << "JuiceLoader initialized successfully"; - return JNI_TRUE; -} diff --git a/src/libagent/jni/loader_inject.cpp b/src/libagent/jni/loader_inject.cpp deleted file mode 100644 index 516edc2..0000000 --- a/src/libagent/jni/loader_inject.cpp +++ /dev/null @@ -1,195 +0,0 @@ -#include - -// Deprecated -JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_injectJar -(JNIEnv *env, jclass loader_class, jstring jarPath) { - PLOGI << "Invoked!"; - const char *pathStr = env->GetStringUTFChars(jarPath, NULL); - if (!pathStr) { - PLOGE << "Path is NULL!"; - return JNI_FALSE; - } - - if (!JuiceLoaderNative.jvmti) { - PLOGE.printf("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti); - env->ReleaseStringUTFChars(jarPath, pathStr); - return JNI_FALSE; - } - - jvmtiError result = JuiceLoaderNative.jvmti->AddToSystemClassLoaderSearch(pathStr); - if (result != JVMTI_ERROR_NONE) { - PLOGE.printf("Cannot inject jar [result=%d]", result); - env->ReleaseStringUTFChars(jarPath, pathStr); - return JNI_FALSE; - } - - env->ReleaseStringUTFChars(jarPath, pathStr); - PLOGI << "Jar injected: " << pathStr; - return JNI_TRUE; -} - -// Deprecated -JNIEXPORT jobject JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_nativeInjectJarToThread - (JNIEnv* env, jclass, jobject threadObj, jstring jJarPath) -{ - // Convert jstring -> std::string - const char* cJarPath = env->GetStringUTFChars(jJarPath, nullptr); - - // new File(jarPath) - jclass fileClass = env->FindClass("java/io/File"); - jmethodID fileCtor = env->GetMethodID(fileClass, "", "(Ljava/lang/String;)V"); - jstring jPathCopy = env->NewStringUTF(cJarPath); - jobject fileObj = env->NewObject(fileClass, fileCtor, jPathCopy); - - // File.toURI() - jmethodID midToURI = env->GetMethodID(fileClass, "toURI", "()Ljava/net/URI;"); - jobject uriObj = env->CallObjectMethod(fileObj, midToURI); - - // URI.toURL() - jclass uriClass = env->FindClass("java/net/URI"); - jmethodID midToURL = env->GetMethodID(uriClass, "toURL", "()Ljava/net/URL;"); - jobject urlObj = env->CallObjectMethod(uriObj, midToURL); - - // Thread.getContextClassLoader() - jclass threadClass = env->FindClass("java/lang/Thread"); - jmethodID midGetCL = env->GetMethodID( - threadClass, "getContextClassLoader", "()Ljava/lang/ClassLoader;" - ); - jobject originalCL = env->CallObjectMethod(threadObj, midGetCL); - - // URLClassLoader(URL[] urls, ClassLoader parent) - jclass urlClassLoaderClass = env->FindClass("java/net/URLClassLoader"); - jmethodID urlCLCtor = env->GetMethodID( - urlClassLoaderClass, - "", - "([Ljava/net/URL;Ljava/lang/ClassLoader;)V" - ); - - // Create URL[] array with 1 element - jobjectArray urlArray = env->NewObjectArray(1, env->FindClass("java/net/URL"), nullptr); - env->SetObjectArrayElement(urlArray, 0, urlObj); - - // Create new URLClassLoader - jobject newClassLoader = env->NewObject( - urlClassLoaderClass, - urlCLCtor, - urlArray, - originalCL - ); - - // thread.setContextClassLoader(newCL) - jmethodID midSetCL = env->GetMethodID( - threadClass, - "setContextClassLoader", - "(Ljava/lang/ClassLoader;)V" - ); - env->CallVoidMethod(threadObj, midSetCL, newClassLoader); - - env->ReleaseStringUTFChars(jJarPath, cJarPath); - - return newClassLoader; -} - -JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_AddToBootstrapClassLoaderSearch - (JNIEnv *env, jclass, jstring jarPath) { - PLOGD << "Invoked!"; - const char *pathStr = env->GetStringUTFChars(jarPath, NULL); - if (!pathStr) { - PLOGE << "Path is NULL!"; - return JNI_FALSE; - } - - if (!JuiceLoaderNative.jvmti) { - PLOGE.printf("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti); - env->ReleaseStringUTFChars(jarPath, pathStr); - return JNI_FALSE; - } - - jvmtiError result = JuiceLoaderNative.jvmti->AddToBootstrapClassLoaderSearch(pathStr); - if (result != JVMTI_ERROR_NONE) { - PLOGE.printf("Cannot AddToBootstrapClassLoaderSearch [result=%d]", result); - env->ReleaseStringUTFChars(jarPath, pathStr); - return JNI_FALSE; - } - - env->ReleaseStringUTFChars(jarPath, pathStr); - PLOGI << "AddToBootstrapClassLoaderSearch: " << pathStr; - return JNI_TRUE; -} - -JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_AddToSystemClassLoaderSearch - (JNIEnv *env, jclass, jstring jarPath) { - PLOGD << "Invoked!"; - const char *pathStr = env->GetStringUTFChars(jarPath, NULL); - if (!pathStr) { - PLOGE << "Path is NULL!"; - return JNI_FALSE; - } - - if (!JuiceLoaderNative.jvmti) { - PLOGE.printf("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti); - env->ReleaseStringUTFChars(jarPath, pathStr); - return JNI_FALSE; - } - - jvmtiError result = JuiceLoaderNative.jvmti->AddToSystemClassLoaderSearch(pathStr); - if (result != JVMTI_ERROR_NONE) { - PLOGE.printf("Cannot AddToSystemClassLoaderSearch [result=%d]", result); - env->ReleaseStringUTFChars(jarPath, pathStr); - return JNI_FALSE; - } - - env->ReleaseStringUTFChars(jarPath, pathStr); - PLOGI << "AddToSystemClassLoaderSearch: " << pathStr; - return JNI_TRUE; -} - -JNIEXPORT jboolean JNICALL -Java_cn_xiaozhou233_juiceloader_JuiceLoader_AddToClassLoader - (JNIEnv *env, jclass, jstring path, jobject loader) { - - jclass urlClassLoader = env->FindClass("java/net/URLClassLoader"); - - if (env->IsInstanceOf(loader, urlClassLoader)) { - jclass fileClass = env->FindClass("java/io/File"); - jmethodID fileInit = env->GetMethodID( - fileClass, - "", - "(Ljava/lang/String;)V" - ); - - jobject file = env->NewObject(fileClass, fileInit, path); - - jmethodID toURI = env->GetMethodID( - fileClass, - "toURI", - "()Ljava/net/URI;" - ); - jobject uri = env->CallObjectMethod(file, toURI); - - jclass uriClass = env->FindClass("java/net/URI"); - jmethodID toURL = env->GetMethodID( - uriClass, - "toURL", - "()Ljava/net/URL;" - ); - jobject url = env->CallObjectMethod(uri, toURL); - - jmethodID addURL = env->GetMethodID( - urlClassLoader, - "addURL", - "(Ljava/net/URL;)V" - ); - env->CallVoidMethod(loader, addURL, url); - } else { - // jstring -> const char* - const char* nativePath = env->GetStringUTFChars(path, nullptr); - - JuiceLoaderNative.jvmti->AddToSystemClassLoaderSearch(nativePath); - - // Release UTF string - env->ReleaseStringUTFChars(path, nativePath); - } - - return JNI_TRUE; -} diff --git a/src/libagent/jni/loader_redefine.cpp b/src/libagent/jni/loader_redefine.cpp deleted file mode 100644 index 231a18a..0000000 --- a/src/libagent/jni/loader_redefine.cpp +++ /dev/null @@ -1,57 +0,0 @@ -#include -JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_redefineClass -(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray classBytes, jint length) { - PLOGI << "Invoked!"; - if (!JuiceLoaderNative.jvmti) { - PLOGE.printf("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti); - return JNI_FALSE; - } - - jbyte* buf = env->GetByteArrayElements(classBytes, NULL); - if (!buf) { - PLOGE << "Cannot get class bytes"; - return JNI_FALSE; - } - - jvmtiClassDefinition defs[1]; - defs[0].klass = clazz; - defs[0].class_byte_count = length; - defs[0].class_bytes = reinterpret_cast(buf); - - jvmtiError result = JuiceLoaderNative.jvmti->RedefineClasses(1, defs); - env->ReleaseByteArrayElements(classBytes, buf, JNI_ABORT); - - if (result != JVMTI_ERROR_NONE) { - PLOGE.printf("Cannot redefine class [result=%d]", result); - return JNI_FALSE; - } - - PLOGI.printf("Class redefined successfully!"); - return JNI_TRUE; -} - -JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_redefineClassByName -(JNIEnv *env, jclass loader_class, jstring className, jbyteArray classBytes, jint length) { - PLOGI << "redefineClass_className Invoked!"; - if (!JuiceLoaderNative.jvmti) { - PLOGE.printf("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti); - return JNI_FALSE; - } - - const char* cname = env->GetStringUTFChars(className, NULL); - if (!cname) { - PLOGE << "Class name is NULL!"; - return JNI_FALSE; - } - - jclass clazz = env->FindClass(cname); - if (!clazz) { - PLOGE.printf("Class not found! [ClassName=%s]", cname); - env->ReleaseStringUTFChars(className, cname); - return JNI_FALSE; - } - - jboolean ret = Java_cn_xiaozhou233_juiceloader_JuiceLoader_redefineClass(env, loader_class, clazz, classBytes, length); - env->ReleaseStringUTFChars(className, cname); - return ret; -} \ No newline at end of file diff --git a/src/libagent/jni/loader_retransform.cpp b/src/libagent/jni/loader_retransform.cpp deleted file mode 100644 index 933cf2e..0000000 --- a/src/libagent/jni/loader_retransform.cpp +++ /dev/null @@ -1,142 +0,0 @@ -#include -#include - -/* ========================= - * utils - * ========================= */ - -static char* get_class_name(JNIEnv* env, jclass clazz) { - jclass clsClass = env->FindClass("java/lang/Class"); - jmethodID mid = env->GetMethodID(clsClass, "getName", "()Ljava/lang/String;"); - jstring nameStr = (jstring)env->CallObjectMethod(clazz, mid); - - const char* tmp = env->GetStringUTFChars(nameStr, nullptr); - char* result = _strdup(tmp); - env->ReleaseStringUTFChars(nameStr, tmp); - env->DeleteLocalRef(nameStr); - return result; -} - -/* ========================= - * JVMTI global lookup - * ========================= */ - -static jclass findLoadedClassByInternalName( - jvmtiEnv* jvmti, - const char* internalName -) { - jint count = 0; - jclass* classes = nullptr; - - if (jvmti->GetLoadedClasses(&count, &classes) != JVMTI_ERROR_NONE || count == 0) { - return nullptr; - } - - jclass result = nullptr; - - for (jint i = 0; i < count; i++) { - char* sig = nullptr; - if (jvmti->GetClassSignature(classes[i], &sig, nullptr) == JVMTI_ERROR_NONE && sig) { - // Lnet/minecraft/client/Minecraft; - if (sig[0] == 'L') { - size_t len = strlen(sig); - if (len > 2 && - strncmp(sig + 1, internalName, len - 2) == 0 && - internalName[len - 2] == '\0') { - result = classes[i]; - jvmti->Deallocate((unsigned char*)sig); - break; - } - } - jvmti->Deallocate((unsigned char*)sig); - } - } - - jvmti->Deallocate((unsigned char*)classes); - return result; -} - -/* ========================= - * retransform by jclass - * ========================= */ - -JNIEXPORT jboolean JNICALL -Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClass -(JNIEnv* env, jclass, jclass clazz, jbyteArray classBytes, jint) { - - if (!JuiceLoaderNative.jvmti || !clazz || !classBytes) { - return JNI_FALSE; - } - - char* nameDot = get_class_name(env, clazz); - for (char* p = nameDot; *p; ++p) - if (*p == '.') *p = '/'; - - jbyte* bytes = env->GetByteArrayElements(classBytes, nullptr); - jint len = env->GetArrayLength(classBytes); - - if (RetransformClassCache.size >= RetransformClassCache.capacity) { - int newCap = RetransformClassCache.capacity == 0 ? 4 : RetransformClassCache.capacity * 2; - RetransformClassCache.arr = - (ClassBytesCacheType*)realloc(RetransformClassCache.arr, newCap * sizeof(ClassBytesCacheType)); - RetransformClassCache.capacity = newCap; - } - - ClassBytesCacheType* entry = - &RetransformClassCache.arr[RetransformClassCache.size++]; - - entry->name = _strdup(nameDot); - entry->bytes = (unsigned char*)malloc(len); - memcpy(entry->bytes, bytes, len); - entry->len = len; - - env->ReleaseByteArrayElements(classBytes, bytes, JNI_ABORT); - - jclass arr[1] = { clazz }; - jvmtiError err = JuiceLoaderNative.jvmti->RetransformClasses(1, arr); - - free(nameDot); - - if (err != JVMTI_ERROR_NONE) { - PLOGE.printf("RetransformClasses failed: %d", err); - return JNI_FALSE; - } - - PLOGI.printf("[retransformClass] OK: %s (%d)", entry->name, entry->len); - return JNI_TRUE; -} - -/* ========================= - * retransform by name (NO FindClass) - * ========================= */ - -JNIEXPORT jboolean JNICALL -Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClassByName -(JNIEnv* env, jclass loader_class, jstring className, jbyteArray classBytes, jint length) { - - if (!JuiceLoaderNative.jvmti || !className) { - return JNI_FALSE; - } - - const char* utf = env->GetStringUTFChars(className, nullptr); - char internalName[512]; - strncpy(internalName, utf, sizeof(internalName) - 1); - internalName[sizeof(internalName) - 1] = 0; - - for (char* p = internalName; *p; ++p) - if (*p == '.') *p = '/'; - - env->ReleaseStringUTFChars(className, utf); - - jclass target = - findLoadedClassByInternalName(JuiceLoaderNative.jvmti, internalName); - - if (!target) { - PLOGE.printf("Class not loaded: %s", internalName); - return JNI_FALSE; - } - - return Java_cn_xiaozhou233_juiceloader_JuiceLoader_retransformClass( - env, loader_class, target, classBytes, length - ); -} diff --git a/src/libagent/jni/loader_thread.cpp b/src/libagent/jni/loader_thread.cpp deleted file mode 100644 index 37a17ca..0000000 --- a/src/libagent/jni/loader_thread.cpp +++ /dev/null @@ -1,64 +0,0 @@ -#include - -JNIEXPORT jobject JNICALL Java_cn_xiaozhou233_juiceloader_JuiceLoader_nativeGetThreadByName - (JNIEnv* env, jclass, jstring jName) -{ - // Convert jstring to std::string - const char* cName = env->GetStringUTFChars(jName, nullptr); - std::string targetName = cName; - env->ReleaseStringUTFChars(jName, cName); - - // Thread class - jclass threadClass = env->FindClass("java/lang/Thread"); - - // Call Thread.getAllStackTraces(), signature: ()Ljava/util/Map; - jmethodID midGetAll = env->GetStaticMethodID( - threadClass, - "getAllStackTraces", - "()Ljava/util/Map;" - ); - - jobject mapObj = env->CallStaticObjectMethod(threadClass, midGetAll); - - // Map.keySet() -> Set - jclass mapClass = env->FindClass("java/util/Map"); - jmethodID midKeySet = env->GetMethodID( - mapClass, - "keySet", - "()Ljava/util/Set;" - ); - jobject setObj = env->CallObjectMethod(mapObj, midKeySet); - - // Set.iterator() -> Iterator - jclass setClass = env->FindClass("java/util/Set"); - jmethodID midIterator = env->GetMethodID( - setClass, - "iterator", - "()Ljava/util/Iterator;" - ); - jobject iteratorObj = env->CallObjectMethod(setObj, midIterator); - - // Iterator.hasNext() / next() - jclass iteratorClass = env->FindClass("java/util/Iterator"); - jmethodID midHasNext = env->GetMethodID(iteratorClass, "hasNext", "()Z"); - jmethodID midNext = env->GetMethodID(iteratorClass, "next", "()Ljava/lang/Object;"); - - // Thread.getName() - jmethodID midGetName = env->GetMethodID(threadClass, "getName", "()Ljava/lang/String;"); - - while (env->CallBooleanMethod(iteratorObj, midHasNext)) { - jobject threadObj = env->CallObjectMethod(iteratorObj, midNext); - jstring jThreadName = (jstring)env->CallObjectMethod(threadObj, midGetName); - - const char* cThreadName = env->GetStringUTFChars(jThreadName, nullptr); - bool match = (targetName == cThreadName); - env->ReleaseStringUTFChars(jThreadName, cThreadName); - - if (match) { - return threadObj; // Found target - } - } - - return nullptr; // Not found -} - diff --git a/src/libagent/libagent.cpp b/src/libagent/libagent.cpp new file mode 100644 index 0000000..e69de29 diff --git a/src/libagent/libjuiceloader.cpp b/src/libagent/libjuiceloader.cpp deleted file mode 100644 index 985276f..0000000 --- a/src/libagent/libjuiceloader.cpp +++ /dev/null @@ -1,67 +0,0 @@ -// JVM -#include -#include -#include -#include -#include - -JuiceLoaderNativeType JuiceLoaderNative; - -static int ConfigureJVMTI(JNIEnv *env, _jvmtiEnv *jvmti) { - // Retransform Class Cache : to store classes that need to be retransformed - RetransformClassCache.arr = NULL; - RetransformClassCache.size = 0; - RetransformClassCache.capacity = 0; - - // Application ability - jvmtiCapabilities caps; - memset(&caps, 0, sizeof(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) { - PLOGE << "Failed to add capabilities: " << result; - return JNI_ERR; - } - - // Register callbacks - jvmtiEventCallbacks callbacks; - memset(&callbacks, 0, sizeof(callbacks)); - callbacks.ClassFileLoadHook = &ClassFileLoadHook; - jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks)); - - // Enable events - jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, NULL); - - return JNI_OK; -} - -extern "C" __declspec(dllexport) -int InitJuiceLoader(JNIEnv *env, _jvmtiEnv *jvmti) { - InitLogger(); - // Step 1: Check if env/jvmti is null - PLOGD.printf("env: %p, jvmti: %p", env, jvmti); - if (env == nullptr) { - PLOGE.printf("[-] Failed to initialize libjuiceloader: env is null"); - return -1; - } - if (jvmti == nullptr) { - PLOGE.printf("[-] Failed to initialize libjuiceloader: jvmti is null"); - return -1; - } - JuiceLoaderNative.jvmti = jvmti; - - - // Step 2: Configure JVMTI - if (ConfigureJVMTI(env, jvmti) != JNI_OK) { - PLOGE.printf("[-] Failed to initialize libjuiceloader: ConfigureJVMTI failed"); - return -1; - } - - return 0; -} - From bad147d898209dc348fe5654324e7bf19857a53a Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Tue, 31 Mar 2026 22:48:55 +0800 Subject: [PATCH 25/37] modified: src/libagent/CMakeLists.txt --- src/libagent/CMakeLists.txt | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/libagent/CMakeLists.txt b/src/libagent/CMakeLists.txt index 3c6e577..5ae9e94 100644 --- a/src/libagent/CMakeLists.txt +++ b/src/libagent/CMakeLists.txt @@ -3,8 +3,6 @@ file( agent_sources ${CMAKE_CURRENT_SOURCE_DIR}/*.cpp ${CMAKE_CURRENT_SOURCE_DIR}/*.c - ${CMAKE_CURRENT_SOURCE_DIR}/jni/*.c - ${CMAKE_CURRENT_SOURCE_DIR}/jni/*.cpp ) add_library(agent SHARED ${agent_sources}) From 34cb16d3858363cdb985a2047c9f9453f2f7424b Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Wed, 1 Apr 2026 10:19:40 +0800 Subject: [PATCH 26/37] Refactor & Impl: JuiceAgent and init function and AddToClassLoader --- src/libagent/core/init.cpp | 33 +++++++++++++++++++ src/libagent/includes/jni_impl.hpp | 10 ++++++ src/libagent/includes/libagent.hpp | 35 ++++++++++++++++++++ src/libagent/includes/utils.hpp | 15 +++++++++ src/libagent/jni/classloader.cpp | 52 ++++++++++++++++++++++++++++++ src/libagent/libagent.cpp | 50 ++++++++++++++++++++++++++++ 6 files changed, 195 insertions(+) create mode 100644 src/libagent/core/init.cpp create mode 100644 src/libagent/includes/jni_impl.hpp create mode 100644 src/libagent/includes/libagent.hpp create mode 100644 src/libagent/includes/utils.hpp create mode 100644 src/libagent/jni/classloader.cpp diff --git a/src/libagent/core/init.cpp b/src/libagent/core/init.cpp new file mode 100644 index 0000000..f5b52eb --- /dev/null +++ b/src/libagent/core/init.cpp @@ -0,0 +1,33 @@ +#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 loader_class) { + InitLogger(); + + PLOGI << "Initializing JuiceAgent..."; + + JavaVM* jvm = nullptr; + jvmtiEnv* jvmti = nullptr; + + // Get Java VM + env->GetJavaVM(&jvm); + if (jvm == nullptr) { + PLOGE << "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) { + PLOGE << "Failed to get JVMTI environment, error: " << err; + return JNI_FALSE; + } + + // Invoke EntryPoint + JuiceAgent::Agent& agent = JuiceAgent::Agent::instance(); + agent.init(jvm, env, jvmti); + + return JNI_TRUE; +} diff --git a/src/libagent/includes/jni_impl.hpp b/src/libagent/includes/jni_impl.hpp new file mode 100644 index 0000000..c182a6d --- /dev/null +++ b/src/libagent/includes/jni_impl.hpp @@ -0,0 +1,10 @@ +#pragma once + +#include +#include +#include +#include +#include + +// Generated by JuiceAgent-API +#include diff --git a/src/libagent/includes/libagent.hpp b/src/libagent/includes/libagent.hpp new file mode 100644 index 0000000..6cce749 --- /dev/null +++ b/src/libagent/includes/libagent.hpp @@ -0,0 +1,35 @@ +#pragma once + +#include +#include +#include + +namespace JuiceAgent { + class Agent { + private: + JavaVM* jvm; + jvmtiEnv* jvmti; + + 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); + + // getters + JavaVM* get_jvm() const { return jvm; } + jvmtiEnv* get_jvmti() const { return jvmti; } + + // setters + void set_jvm(JavaVM* jvm) { this->jvm = jvm; } + void set_jvmti(jvmtiEnv* jvmti) { this->jvmti = jvmti; } + }; +} \ 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..48d18a3 --- /dev/null +++ b/src/libagent/includes/utils.hpp @@ -0,0 +1,15 @@ +#pragma once + +#include + +inline bool check_env(JuiceAgent::Agent& agent) { + if (agent.get_jvm() == nullptr) { + PLOGE << "Failed to get JavaVM instance"; + return false; + } + if (agent.get_jvmti() == nullptr) { + PLOGE << "Failed to get JVMTI environment"; + return false; + } + return true; +} \ 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..547945f --- /dev/null +++ b/src/libagent/jni/classloader.cpp @@ -0,0 +1,52 @@ +#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) { + PLOGE << "Path is NULL!"; + return JNI_FALSE; + } + + jvmtiError result = agent.get_jvmti()->AddToBootstrapClassLoaderSearch(j_jar_path); + if (result != JVMTI_ERROR_NONE) { + PLOGE.printf("Cannot AddToBootstrapClassLoaderSearch [result=%d]", result); + env->ReleaseStringUTFChars(jar_path, j_jar_path); + return JNI_FALSE; + } + PLOGI << "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) { + PLOGE << "Path is NULL!"; + return JNI_FALSE; + } + + jvmtiError result = agent.get_jvmti()->AddToSystemClassLoaderSearch(j_jar_path); + if (result != JVMTI_ERROR_NONE) { + PLOGE.printf("Cannot AddToSystemClassLoaderSearch [result=%d]", result); + env->ReleaseStringUTFChars(jar_path, j_jar_path); + return JNI_FALSE; + } + PLOGI << "AddToSystemClassLoaderSearch: " << j_jar_path; + + env->ReleaseStringUTFChars(jar_path, j_jar_path); + return JNI_TRUE; + } \ No newline at end of file diff --git a/src/libagent/libagent.cpp b/src/libagent/libagent.cpp index e69de29..bab114c 100644 --- a/src/libagent/libagent.cpp +++ b/src/libagent/libagent.cpp @@ -0,0 +1,50 @@ +#include + +namespace JuiceAgent { + // ===== Singleton ===== + Agent& Agent::instance() { + static Agent instance; + return instance; + } + + bool Agent::init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti) { + PLOGI << "JuiceAgent Native EntryPoint Invoked!"; + + // ======== neccessary environment check ======== + if (jvm == nullptr) { + PLOGE << "Failed to initialize JuiceAgent: jvm is null"; + return false; + } + if (env == nullptr) { + PLOGE << "Failed to initialize JuiceAgent: env is null"; + return false; + } + if (jvmti == nullptr) { + PLOGE << "Failed to initialize JuiceAgent: jvmti is null"; + return false; + } + + set_jvm(jvm); + set_jvmti(jvmti); + + PLOGD << "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) { + PLOGE << "Failed to add capabilities: " << result; + return false; + } + + PLOGI << "Abilities added successfully"; + + return true; + } +} \ No newline at end of file From 4496931bdf4e0d1575aa034856b3d654c0a0ccfe Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Wed, 1 Apr 2026 10:36:39 +0800 Subject: [PATCH 27/37] Impl: addToClassLoader --- src/libagent/jni/classloader.cpp | 122 ++++++++++++++++++++++++++++++- 1 file changed, 121 insertions(+), 1 deletion(-) diff --git a/src/libagent/jni/classloader.cpp b/src/libagent/jni/classloader.cpp index 547945f..6b69a66 100644 --- a/src/libagent/jni/classloader.cpp +++ b/src/libagent/jni/classloader.cpp @@ -49,4 +49,124 @@ JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToSy env->ReleaseStringUTFChars(jar_path, j_jar_path); return JNI_TRUE; - } \ No newline at end of file + } + +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; +} \ No newline at end of file From b0d8b5901feb0da0087543c1aaa578d98bc04708 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Wed, 1 Apr 2026 18:00:42 +0800 Subject: [PATCH 28/37] Impl: define / redefine class --- src/libagent/jni/classloader.cpp | 23 +++++++++++- src/libagent/jni/instrumentation.cpp | 53 ++++++++++++++++++++++++++++ 2 files changed, 75 insertions(+), 1 deletion(-) create mode 100644 src/libagent/jni/instrumentation.cpp diff --git a/src/libagent/jni/classloader.cpp b/src/libagent/jni/classloader.cpp index 6b69a66..d3c269b 100644 --- a/src/libagent/jni/classloader.cpp +++ b/src/libagent/jni/classloader.cpp @@ -169,4 +169,25 @@ FALLBACK: } return JNI_TRUE; -} \ No newline at end of file +} + +// 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; + } \ 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..7e1b7e8 --- /dev/null +++ b/src/libagent/jni/instrumentation.cpp @@ -0,0 +1,53 @@ +#include + +// Redefine class +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClass + (JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray class_bytes, jint class_bytes_len) { + auto& agent = JuiceAgent::Agent::instance(); + if (!check_env(agent)) + return JNI_FALSE; + + jbyte* buf = env->GetByteArrayElements(class_bytes, nullptr); + if (!buf) { + PLOGE << "Cannot get class bytes"; + return JNI_FALSE; + } + + jvmtiClassDefinition defs[1]; + defs[0].klass = clazz; + defs[0].class_byte_count = class_bytes_len; + defs[0].class_bytes = reinterpret_cast(buf); + + jvmtiError result = agent.get_jvmti()->RedefineClasses(1, defs); + env->ReleaseByteArrayElements(class_bytes, buf, JNI_ABORT); + + if (result != JVMTI_ERROR_NONE) { + PLOGE << "Redefine class failed: " << result; + return JNI_FALSE; + } + + PLOGD << "Class redefined successfully!"; + + return JNI_TRUE; + } + +// Redefine class using class_name +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) { + // jstring -> const char* + const char* cname = env->GetStringUTFChars(class_name, nullptr); + if (!cname) { + PLOGE << "Class name is NULL!"; + return JNI_FALSE; + } + + // Find class by name + jclass clazz = env->FindClass(cname); + env->ReleaseStringUTFChars(class_name, cname); + if (!clazz) { + PLOGE << "Cannot find class: " << cname; + return JNI_FALSE; + } + + return Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClass(env, loader_class, clazz, class_bytes, class_bytes_len); +} \ No newline at end of file From faeaf052b9489491f85b4a61e46091e8e73f0cb9 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Wed, 1 Apr 2026 18:14:44 +0800 Subject: [PATCH 29/37] WIP: ClassFileLoadHook --- src/libagent/callback/ClassFileLoadHook.cpp | 16 ++++++++++++++++ src/libagent/includes/jni_impl.hpp | 14 ++++++++++++++ src/libagent/libagent.cpp | 15 +++++++++++++++ 3 files changed, 45 insertions(+) create mode 100644 src/libagent/callback/ClassFileLoadHook.cpp diff --git a/src/libagent/callback/ClassFileLoadHook.cpp b/src/libagent/callback/ClassFileLoadHook.cpp new file mode 100644 index 0000000..02a1841 --- /dev/null +++ b/src/libagent/callback/ClassFileLoadHook.cpp @@ -0,0 +1,16 @@ +#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) { + std::cout << "ClassFileLoadHook: " << name << std::endl; + } \ No newline at end of file diff --git a/src/libagent/includes/jni_impl.hpp b/src/libagent/includes/jni_impl.hpp index c182a6d..440bbec 100644 --- a/src/libagent/includes/jni_impl.hpp +++ b/src/libagent/includes/jni_impl.hpp @@ -8,3 +8,17 @@ // 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); \ No newline at end of file diff --git a/src/libagent/libagent.cpp b/src/libagent/libagent.cpp index bab114c..e363f83 100644 --- a/src/libagent/libagent.cpp +++ b/src/libagent/libagent.cpp @@ -1,4 +1,5 @@ #include +#include namespace JuiceAgent { // ===== Singleton ===== @@ -45,6 +46,20 @@ namespace JuiceAgent { PLOGI << "Abilities added successfully"; + // ======== Register callbacks ======== + jvmtiEventCallbacks callbacks{}; + callbacks.ClassFileLoadHook = &ClassFileLoadHook; + result = jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks)); + if (result != JNI_OK) { + PLOGE << "Failed to set event callbacks: " << result; + } + + // Enable events + result = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, NULL); + if (result != JNI_OK) { + PLOGE << "Failed to enable event notification: " << result; + } + return true; } } \ No newline at end of file From ad69f9d11a8c1e046ff1157e69c6a0b519faaf85 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Thu, 2 Apr 2026 12:37:31 +0800 Subject: [PATCH 30/37] Impl: Data Structures and set/map --- src/libagent/callback/ClassFileLoadHook.cpp | 2 ++ src/libagent/core/global.cpp | 5 ++++ src/libagent/includes/global.hpp | 31 +++++++++++++++++++++ 3 files changed, 38 insertions(+) create mode 100644 src/libagent/core/global.cpp create mode 100644 src/libagent/includes/global.hpp diff --git a/src/libagent/callback/ClassFileLoadHook.cpp b/src/libagent/callback/ClassFileLoadHook.cpp index 02a1841..19013f3 100644 --- a/src/libagent/callback/ClassFileLoadHook.cpp +++ b/src/libagent/callback/ClassFileLoadHook.cpp @@ -12,5 +12,7 @@ void JNICALL ClassFileLoadHook( const unsigned char* classbytes, jint* new_class_data_len, unsigned char** new_classbytes) { + // Delete this log when the hook is stable, or it will cause performance issues std::cout << "ClassFileLoadHook: " << name << std::endl; + } \ 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..9363c15 --- /dev/null +++ b/src/libagent/core/global.cpp @@ -0,0 +1,5 @@ +#include + +std::unordered_set classToCapture; +std::unordered_map classFileDataMap; +std::mutex classDataMutex; diff --git a/src/libagent/includes/global.hpp b/src/libagent/includes/global.hpp new file mode 100644 index 0000000..40107ae --- /dev/null +++ b/src/libagent/includes/global.hpp @@ -0,0 +1,31 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include + +// Data Structures +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; + jclass 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; \ No newline at end of file From 9aa77848d7668c76691b2188aa102f319f0010d6 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Thu, 2 Apr 2026 12:51:23 +0800 Subject: [PATCH 31/37] BugFix and Update: C++ 20 --- CMakeLists.txt | 2 +- src/libagent/callback/ClassFileLoadHook.cpp | 27 +++++++++++++++++++++ src/libagent/includes/global.hpp | 2 +- src/libagent/includes/jni_impl.hpp | 1 + 4 files changed, 30 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 35ebc8d..635799d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,7 @@ cmake_minimum_required(VERSION 3.15) project(JuiceAgent LANGUAGES C CXX) -set(CMAKE_CXX_STANDARD 17) +set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) # output directories diff --git a/src/libagent/callback/ClassFileLoadHook.cpp b/src/libagent/callback/ClassFileLoadHook.cpp index 19013f3..a2ec4d8 100644 --- a/src/libagent/callback/ClassFileLoadHook.cpp +++ b/src/libagent/callback/ClassFileLoadHook.cpp @@ -14,5 +14,32 @@ void JNICALL ClassFileLoadHook( unsigned char** new_classbytes) { // Delete this log when the hook is stable, or it will cause performance issues std::cout << "ClassFileLoadHook: " << name << std::endl; + if (!name) { + PLOGW << "name is null"; + return; + } + /* ========================= + * 1. Capture original bytes + * ========================= */ + std::lock_guard lock(classDataMutex); + if (classToCapture.contains(name)) { + if (!classFileDataMap.contains(name)) { + ClassFileData data; + + data.className = name; + data.bytecode.assign(classbytes, classbytes + class_data_len); + // Experimental: class/classloader/protection_domain references (to be used in future features, e.g. dynamic patching) + data.clazz = class_being_redefined; + data.classloader = loader; + data.protection_domain = protection_domain; + + + classFileDataMap[name] = std::move(data); + + classToCapture.erase(name); + + PLOGI << "Captured class: " << name << " (length: " << class_data_len << ")"; + } + } } \ No newline at end of file diff --git a/src/libagent/includes/global.hpp b/src/libagent/includes/global.hpp index 40107ae..527e97d 100644 --- a/src/libagent/includes/global.hpp +++ b/src/libagent/includes/global.hpp @@ -16,7 +16,7 @@ struct ClassFileData { // ======== Global references to prevent GC ======== // Remember to release these references when they are no longer needed, otherwise it will cause memory leaks jclass clazz; - jclass classloader; + jobject classloader; jobject protection_domain; }; diff --git a/src/libagent/includes/jni_impl.hpp b/src/libagent/includes/jni_impl.hpp index 440bbec..2e73d74 100644 --- a/src/libagent/includes/jni_impl.hpp +++ b/src/libagent/includes/jni_impl.hpp @@ -5,6 +5,7 @@ #include #include #include +#include // Generated by JuiceAgent-API #include From 34dbd82a599fa597d7a71ad0a038ff941f708642 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Thu, 2 Apr 2026 13:19:07 +0800 Subject: [PATCH 32/37] Impl: getClassBytes/getClassBytesByName --- src/libagent/callback/ClassFileLoadHook.cpp | 2 +- src/libagent/includes/global.hpp | 2 +- src/libagent/jni/bytecode.cpp | 109 ++++++++++++++++++++ 3 files changed, 111 insertions(+), 2 deletions(-) create mode 100644 src/libagent/jni/bytecode.cpp diff --git a/src/libagent/callback/ClassFileLoadHook.cpp b/src/libagent/callback/ClassFileLoadHook.cpp index a2ec4d8..cd7f570 100644 --- a/src/libagent/callback/ClassFileLoadHook.cpp +++ b/src/libagent/callback/ClassFileLoadHook.cpp @@ -27,7 +27,7 @@ void JNICALL ClassFileLoadHook( if (!classFileDataMap.contains(name)) { ClassFileData data; - data.className = name; + data.classname = name; data.bytecode.assign(classbytes, classbytes + class_data_len); // Experimental: class/classloader/protection_domain references (to be used in future features, e.g. dynamic patching) data.clazz = class_being_redefined; diff --git a/src/libagent/includes/global.hpp b/src/libagent/includes/global.hpp index 527e97d..8b1b052 100644 --- a/src/libagent/includes/global.hpp +++ b/src/libagent/includes/global.hpp @@ -10,7 +10,7 @@ // Data Structures struct ClassFileData { - std::string className; + std::string classname; std::vector bytecode; // ======== Global references to prevent GC ======== diff --git a/src/libagent/jni/bytecode.cpp b/src/libagent/jni/bytecode.cpp new file mode 100644 index 0000000..a88969e --- /dev/null +++ b/src/libagent/jni/bytecode.cpp @@ -0,0 +1,109 @@ +#include +#include + +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; + } + + // Lxxx; -> xxx + std::string internalName(signature + 1, strlen(signature) - 2); + agent.get_jvmti()->Deallocate((unsigned char*)signature); + + classToCapture.insert(internalName); // Add to capture list + + jvmtiError err = agent.get_jvmti()->RetransformClasses(1, &clazz); + if (err != JVMTI_ERROR_NONE) { + PLOGE << "Retransform class failed: " << err; + return nullptr; + } + + ClassFileData data = classFileDataMap[internalName]; + if (data.classname.empty()) { + PLOGE << "Failed to capture class [classname null]: " << internalName; + } + if (data.bytecode.empty()) { + PLOGE << "Failed to capture bytecode for class [byetcode null]: " << internalName; + return nullptr; + } + + jbyteArray out = env->NewByteArray(data.bytecode.size()); + env->SetByteArrayRegion(out, 0, data.bytecode.size(), (jbyte*)data.bytecode.data()); + + return out; + } + +JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytesByName + (JNIEnv *env, jclass loader_class, jstring name) { + auto& agent = JuiceAgent::Agent::instance(); + if (!check_env(agent) || !name) + return nullptr; + + // ========================= + // 1. jstring -> internal name + // ========================= + const char* utf = env->GetStringUTFChars(name, nullptr); + if (!utf) + return nullptr; + + std::string internalName(utf); + env->ReleaseStringUTFChars(name, utf); + + // a.b.C -> a/b/C + std::replace(internalName.begin(), internalName.end(), '.', '/'); + + // ========================= + // 2. Find loaded class via JVMTI + // ========================= + 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); + + // Lxxx; -> xxx + if (len > 2 && signature[0] == 'L' && signature[len - 1] == ';') { + if (internalName == std::string(signature + 1, len - 2)) { + targetClass = classes[i]; + jvmti->Deallocate((unsigned char*)signature); + break; + } + } + + jvmti->Deallocate((unsigned char*)signature); + } + } + + if (classes) { + jvmti->Deallocate((unsigned char*)classes); + } + + if (!targetClass) { + PLOGE << "Class not loaded: " << internalName; + return nullptr; + } + + // ========================= + // 3. Reuse existing logic + // ========================= + return Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytes( + env, loader_class, targetClass + ); +} \ No newline at end of file From 71965165b9fe8db54ca6ed07cd7aab6f16affb25 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Thu, 2 Apr 2026 13:25:57 +0800 Subject: [PATCH 33/37] Refactor: bytecode.cpp --- src/libagent/jni/bytecode.cpp | 107 ++++++++++++++++++++-------------- 1 file changed, 63 insertions(+), 44 deletions(-) diff --git a/src/libagent/jni/bytecode.cpp b/src/libagent/jni/bytecode.cpp index a88969e..ebdb934 100644 --- a/src/libagent/jni/bytecode.cpp +++ b/src/libagent/jni/bytecode.cpp @@ -1,69 +1,95 @@ #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; + if (!check_env(agent)) return nullptr; char* signature = nullptr; - if (agent.get_jvmti()->GetClassSignature(clazz, &signature, nullptr) != JVMTI_ERROR_NONE || !signature) { + 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); } - // Lxxx; -> xxx - std::string internalName(signature + 1, strlen(signature) - 2); - agent.get_jvmti()->Deallocate((unsigned char*)signature); - - classToCapture.insert(internalName); // Add to capture list - + // ============================ + // 2. Trigger class retransform + // ============================ jvmtiError err = agent.get_jvmti()->RetransformClasses(1, &clazz); if (err != JVMTI_ERROR_NONE) { PLOGE << "Retransform class failed: " << err; return nullptr; } - ClassFileData data = classFileDataMap[internalName]; - if (data.classname.empty()) { - PLOGE << "Failed to capture class [classname null]: " << internalName; + // ============================ + // 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()) { - PLOGE << "Failed to capture bytecode for class [byetcode null]: " << internalName; + PLOGE << "Failed to capture bytecode for class: " << internalName; return nullptr; } - jbyteArray out = env->NewByteArray(data.bytecode.size()); - env->SetByteArrayRegion(out, 0, data.bytecode.size(), (jbyte*)data.bytecode.data()); + 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) || !name) - return nullptr; + if (!check_env(agent)) return nullptr; - // ========================= - // 1. jstring -> internal name - // ========================= + // ============================ + // 1. Convert jstring -> internal name + // ============================ const char* utf = env->GetStringUTFChars(name, nullptr); - if (!utf) - return nullptr; - + if (!utf) return nullptr; std::string internalName(utf); env->ReleaseStringUTFChars(name, utf); - // a.b.C -> a/b/C + // Convert dots to slashes: a.b.C -> a/b/C std::replace(internalName.begin(), internalName.end(), '.', '/'); - // ========================= - // 2. Find loaded class via JVMTI - // ========================= + // ============================ + // 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) { @@ -71,28 +97,23 @@ JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getCl } 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); - - // Lxxx; -> xxx if (len > 2 && signature[0] == 'L' && signature[len - 1] == ';') { - if (internalName == std::string(signature + 1, len - 2)) { + if (internalName == std::string_view(signature + 1, len - 2)) { targetClass = classes[i]; - jvmti->Deallocate((unsigned char*)signature); + jvmti->Deallocate(reinterpret_cast(signature)); break; } } - - jvmti->Deallocate((unsigned char*)signature); + jvmti->Deallocate(reinterpret_cast(signature)); } } if (classes) { - jvmti->Deallocate((unsigned char*)classes); + jvmti->Deallocate(reinterpret_cast(classes)); } if (!targetClass) { @@ -100,10 +121,8 @@ JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getCl return nullptr; } - // ========================= - // 3. Reuse existing logic - // ========================= - return Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytes( - env, loader_class, targetClass - ); + // ============================ + // 3. Reuse getClassBytes logic + // ============================ + return Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytes(env, loader_class, targetClass); } \ No newline at end of file From 8ad8f45545fcab663be54f0f1865303ceecb0a1c Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Thu, 2 Apr 2026 13:42:19 +0800 Subject: [PATCH 34/37] impl: Redefine class --- src/libagent/jni/bytecode.cpp | 73 ++++++++++++++++++++++++++++ src/libagent/jni/instrumentation.cpp | 51 ------------------- 2 files changed, 73 insertions(+), 51 deletions(-) diff --git a/src/libagent/jni/bytecode.cpp b/src/libagent/jni/bytecode.cpp index ebdb934..d4c7461 100644 --- a/src/libagent/jni/bytecode.cpp +++ b/src/libagent/jni/bytecode.cpp @@ -125,4 +125,77 @@ JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getCl // 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) { + PLOGE << "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) { + PLOGE << "Redefine class failed: " << result; + return JNI_FALSE; + } + + PLOGD << "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) { + PLOGE << "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) { + PLOGE << "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 + ); } \ No newline at end of file diff --git a/src/libagent/jni/instrumentation.cpp b/src/libagent/jni/instrumentation.cpp index 7e1b7e8..68c116f 100644 --- a/src/libagent/jni/instrumentation.cpp +++ b/src/libagent/jni/instrumentation.cpp @@ -1,53 +1,2 @@ #include -// Redefine class -JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClass - (JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray class_bytes, jint class_bytes_len) { - auto& agent = JuiceAgent::Agent::instance(); - if (!check_env(agent)) - return JNI_FALSE; - - jbyte* buf = env->GetByteArrayElements(class_bytes, nullptr); - if (!buf) { - PLOGE << "Cannot get class bytes"; - return JNI_FALSE; - } - - jvmtiClassDefinition defs[1]; - defs[0].klass = clazz; - defs[0].class_byte_count = class_bytes_len; - defs[0].class_bytes = reinterpret_cast(buf); - - jvmtiError result = agent.get_jvmti()->RedefineClasses(1, defs); - env->ReleaseByteArrayElements(class_bytes, buf, JNI_ABORT); - - if (result != JVMTI_ERROR_NONE) { - PLOGE << "Redefine class failed: " << result; - return JNI_FALSE; - } - - PLOGD << "Class redefined successfully!"; - - return JNI_TRUE; - } - -// Redefine class using class_name -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) { - // jstring -> const char* - const char* cname = env->GetStringUTFChars(class_name, nullptr); - if (!cname) { - PLOGE << "Class name is NULL!"; - return JNI_FALSE; - } - - // Find class by name - jclass clazz = env->FindClass(cname); - env->ReleaseStringUTFChars(class_name, cname); - if (!clazz) { - PLOGE << "Cannot find class: " << cname; - return JNI_FALSE; - } - - return Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClass(env, loader_class, clazz, class_bytes, class_bytes_len); -} \ No newline at end of file From 5e7972779f8551deb933ffe1f93c794a42ff2788 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Thu, 2 Apr 2026 13:57:26 +0800 Subject: [PATCH 35/37] Impl: getLoadedClasses and getClassByName --- src/libagent/includes/jni_impl.hpp | 1 + src/libagent/jni/classloader.cpp | 84 +++++++++++++++++++++++++++++- 2 files changed, 84 insertions(+), 1 deletion(-) diff --git a/src/libagent/includes/jni_impl.hpp b/src/libagent/includes/jni_impl.hpp index 2e73d74..238aaeb 100644 --- a/src/libagent/includes/jni_impl.hpp +++ b/src/libagent/includes/jni_impl.hpp @@ -6,6 +6,7 @@ #include #include #include +#include // Generated by JuiceAgent-API #include diff --git a/src/libagent/jni/classloader.cpp b/src/libagent/jni/classloader.cpp index d3c269b..94f43f5 100644 --- a/src/libagent/jni/classloader.cpp +++ b/src/libagent/jni/classloader.cpp @@ -190,4 +190,86 @@ JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_defineCla return nullptr; } return (jclass)classDefined; - } \ No newline at end of file + } + +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) { + PLOGE.printf("GetLoadedClasses failed: %d", 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) { + PLOGE << "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) { + PLOGE << "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) { + PLOGE << "Failed to find loaded class: " << internal_name; + } + + return result; +} \ No newline at end of file From f73265ac3ed43c2374e022a3d45a9b3ee50b68e2 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Thu, 2 Apr 2026 14:19:13 +0800 Subject: [PATCH 36/37] Impl: retransform --- src/libagent/callback/ClassFileLoadHook.cpp | 19 +++ src/libagent/core/global.cpp | 3 + src/libagent/includes/global.hpp | 9 +- src/libagent/includes/utils.hpp | 28 +++++ src/libagent/jni/bytecode.cpp | 127 ++++++++++++++++++++ 5 files changed, 185 insertions(+), 1 deletion(-) diff --git a/src/libagent/callback/ClassFileLoadHook.cpp b/src/libagent/callback/ClassFileLoadHook.cpp index cd7f570..19e84f1 100644 --- a/src/libagent/callback/ClassFileLoadHook.cpp +++ b/src/libagent/callback/ClassFileLoadHook.cpp @@ -42,4 +42,23 @@ void JNICALL ClassFileLoadHook( PLOGI << "Captured class: " << name << " (length: " << class_data_len << ")"; } } + + /* ========================= + * 2. Apply patches + * ========================= */ + if (pendingRetransform.contains(name)) { + auto& bytes = pendingRetransform[name]; + + unsigned char* new_buf = nullptr; + jvmti_env->Allocate(bytes.size(), &new_buf); + + memcpy(new_buf, bytes.data(), bytes.size()); + + *new_class_data_len = (jint)bytes.size(); + *new_classbytes = new_buf; + + pendingRetransform.erase(name); + + PLOGI << "Retransformed: " << name << " (new length: " << bytes.size() << ")"; + } } \ No newline at end of file diff --git a/src/libagent/core/global.cpp b/src/libagent/core/global.cpp index 9363c15..6206983 100644 --- a/src/libagent/core/global.cpp +++ b/src/libagent/core/global.cpp @@ -3,3 +3,6 @@ std::unordered_set classToCapture; std::unordered_map classFileDataMap; std::mutex classDataMutex; + +std::unordered_map> pendingRetransform; +std::mutex pendingRetransformMutex; diff --git a/src/libagent/includes/global.hpp b/src/libagent/includes/global.hpp index 8b1b052..20ce117 100644 --- a/src/libagent/includes/global.hpp +++ b/src/libagent/includes/global.hpp @@ -9,6 +9,10 @@ #include // Data Structures +struct ClassRetransformRequest { + std::string classname; + std::vector bytecode; +}; struct ClassFileData { std::string classname; std::vector bytecode; @@ -28,4 +32,7 @@ extern std::unordered_set classToCapture; extern std::unordered_map classFileDataMap; // Mutex protecting access to classToCapture and classFileDataMap (thread-safe for JVMTI callbacks) -extern std::mutex classDataMutex; \ No newline at end of file +extern std::mutex classDataMutex; + +extern std::unordered_map> pendingRetransform; +extern std::mutex pendingRetransformMutex; \ No newline at end of file diff --git a/src/libagent/includes/utils.hpp b/src/libagent/includes/utils.hpp index 48d18a3..e526ae3 100644 --- a/src/libagent/includes/utils.hpp +++ b/src/libagent/includes/utils.hpp @@ -12,4 +12,32 @@ inline bool check_env(JuiceAgent::Agent& agent) { 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 index d4c7461..92f9d25 100644 --- a/src/libagent/jni/bytecode.cpp +++ b/src/libagent/jni/bytecode.cpp @@ -198,4 +198,131 @@ JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefin 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()) { + PLOGE << "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 bytecode & class info for ClassFileLoadHook + // ========================= + { + std::lock_guard lock(classDataMutex); + + ClassFileData data; + data.classname = nameDot; + data.bytecode.assign(bytes, bytes + len); + data.clazz = static_cast(env->NewGlobalRef(clazz)); // prevent GC + data.classloader = nullptr; // optional + data.protection_domain = nullptr; + + classFileDataMap[nameDot] = std::move(data); + } + + 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) { + PLOGE << "[retransformClass] failed: " << err << " for " << nameDot; + return JNI_FALSE; + } + + PLOGI << "[retransformClass] OK: " << nameDot << " (" << len << " bytes)"; + 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) { + PLOGE << "[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 From 34c8ccd4970d3ce0f191b581d17476df46728628 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Thu, 2 Apr 2026 14:20:33 +0800 Subject: [PATCH 37/37] Breaking Update: Version 3.0 Build 1 --- Version.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/Version.txt b/Version.txt index c70846e..0a10ef9 100644 --- a/Version.txt +++ b/Version.txt @@ -1 +1 @@ -VERSION = Version 2.3 Build 1 \ No newline at end of file +VERSION = Version 3.0 Build 1 \ No newline at end of file