From 4bed99f4178274fd3de091e1de9a0c969ff2268d Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Tue, 18 Aug 2026 16:28:29 +0800 Subject: [PATCH 1/2] Feat: add JuiceRemapper runtime class remapping - add JuiceRemapperService that listens for ClassFileLoadHook and calls the Java static Remap.remap(String, byte[]) via cached JNI declarations, then writes the returned bytes back to the JVMTI callback - add JNI bindings (initNative, add/remove/clear include/exclude) with Remapper singleton init state and cached jclass/jmethodID stored in Remapper (global.hpp) - cache static class/method declarations lazily in initNative to avoid repeated FindClass/GetStaticMethodID - add generated JuiceRemapper JNI header and runtime-remap example config --- examples/runtime-remap/config.toml | 13 ++ ..._xiaozhou233_juiceremapper_JuiceRemapper.h | 69 ++++++++ src/libagent/includes/global.hpp | 27 ++++ src/libagent/includes/jni_common.hpp | 3 + src/libagent/jni/juiceremapper.cpp | 116 ++++++++++++++ .../services/JuiceRemapperService.cpp | 147 ++++++++++++++++++ 6 files changed, 375 insertions(+) create mode 100644 examples/runtime-remap/config.toml create mode 100644 includes/JuiceRemapper/cn_xiaozhou233_juiceremapper_JuiceRemapper.h create mode 100644 src/libagent/jni/juiceremapper.cpp create mode 100644 src/libagent/services/JuiceRemapperService.cpp diff --git a/examples/runtime-remap/config.toml b/examples/runtime-remap/config.toml new file mode 100644 index 0000000..eccb194 --- /dev/null +++ b/examples/runtime-remap/config.toml @@ -0,0 +1,13 @@ +[JuiceAgent] +Version = 1 + +[JuiceAgent.Loader] +# Path to JuiceAgent-API jar, leave empty to use the built-in API +JuiceAgentAPIJarPath = "" +# Path to libagent.dll, default is "./libagent.dll" +JuiceAgentNativeLibraryPath = "" + +[JuiceAgent.Modules] + +[JuiceAgent.Modules.JuiceRemapper] +Enabled = true diff --git a/includes/JuiceRemapper/cn_xiaozhou233_juiceremapper_JuiceRemapper.h b/includes/JuiceRemapper/cn_xiaozhou233_juiceremapper_JuiceRemapper.h new file mode 100644 index 0000000..c35442c --- /dev/null +++ b/includes/JuiceRemapper/cn_xiaozhou233_juiceremapper_JuiceRemapper.h @@ -0,0 +1,69 @@ +/* DO NOT EDIT THIS FILE - it is machine generated */ +#include +/* Header for class cn_xiaozhou233_juiceremapper_JuiceRemapper */ + +#ifndef _Included_cn_xiaozhou233_juiceremapper_JuiceRemapper +#define _Included_cn_xiaozhou233_juiceremapper_JuiceRemapper +#ifdef __cplusplus +extern "C" { +#endif +/* + * Class: cn_xiaozhou233_juiceremapper_JuiceRemapper + * Method: initNative + * Signature: ()Z + */ +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_initNative + (JNIEnv *, jclass); + +/* + * Class: cn_xiaozhou233_juiceremapper_JuiceRemapper + * Method: addInclude + * Signature: (Ljava/lang/String;)Z + */ +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_addInclude + (JNIEnv *, jclass, jstring); + +/* + * Class: cn_xiaozhou233_juiceremapper_JuiceRemapper + * Method: addExclude + * Signature: (Ljava/lang/String;)Z + */ +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_addExclude + (JNIEnv *, jclass, jstring); + +/* + * Class: cn_xiaozhou233_juiceremapper_JuiceRemapper + * Method: removeInclude + * Signature: (Ljava/lang/String;)Z + */ +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_removeInclude + (JNIEnv *, jclass, jstring); + +/* + * Class: cn_xiaozhou233_juiceremapper_JuiceRemapper + * Method: removeExclude + * Signature: (Ljava/lang/String;)Z + */ +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_removeExclude + (JNIEnv *, jclass, jstring); + +/* + * Class: cn_xiaozhou233_juiceremapper_JuiceRemapper + * Method: clearIncludes + * Signature: ()V + */ +JNIEXPORT void JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_clearIncludes + (JNIEnv *, jclass); + +/* + * Class: cn_xiaozhou233_juiceremapper_JuiceRemapper + * Method: clearExcludes + * Signature: ()V + */ +JNIEXPORT void JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_clearExcludes + (JNIEnv *, jclass); + +#ifdef __cplusplus +} +#endif +#endif diff --git a/src/libagent/includes/global.hpp b/src/libagent/includes/global.hpp index 11cdad5..4da7aa5 100644 --- a/src/libagent/includes/global.hpp +++ b/src/libagent/includes/global.hpp @@ -131,5 +131,32 @@ private: std::unordered_map pendingPatches_; }; +class Remapper { +public: + static Remapper& getInstance() { + static Remapper instance; + return instance; + } + + Remapper(const Remapper&) = delete; + Remapper& operator=(const Remapper&) = delete; + + bool isInit() const { return initialized_; } + void setInit(bool init) { initialized_ = init; } + + // Cached JNI static declarations for the Java remap class. + jclass getRemapClass() const { return remapClass_; } + jmethodID getRemapMethodId() const { return remapMethodId_; } + void setRemapClass(jclass clazz) { remapClass_ = clazz; } + void setRemapMethodId(jmethodID methodId) { remapMethodId_ = methodId; } + +private: + Remapper() = default; + + bool initialized_ = false; + jclass remapClass_ = nullptr; // global ref + jmethodID remapMethodId_ = nullptr; // static method id +}; + } } diff --git a/src/libagent/includes/jni_common.hpp b/src/libagent/includes/jni_common.hpp index b35e88f..2375196 100644 --- a/src/libagent/includes/jni_common.hpp +++ b/src/libagent/includes/jni_common.hpp @@ -10,6 +10,9 @@ // Generated by JuiceAgent-API #include +// Generated by JuiceRemapper +#include + // Event callbacks // See https://docs.oracle.com/javase/8/docs/platform/jvmti/jvmti.html#ClassFileLoadHook void JNICALL ClassFileLoadHook( diff --git a/src/libagent/jni/juiceremapper.cpp b/src/libagent/jni/juiceremapper.cpp new file mode 100644 index 0000000..9b9680f --- /dev/null +++ b/src/libagent/jni/juiceremapper.cpp @@ -0,0 +1,116 @@ +#include +#include + +static const char* remap_class = "cn/xiaozhou233/juiceremapper/remapper/Remap"; +static const char* remap_method = "remap"; +static const char* remap_sig = "(Ljava/lang/String;[B)[B"; + +namespace { + +// Resolve and cache the static class/method declarations. +// Returns true on success. On failure, caches are left null so the +// next call retries the lookup. +bool cacheRemapDeclarations(JNIEnv* env) { + auto& remapper = JuiceAgent::Services::Remapper::getInstance(); + + if (remapper.getRemapClass() && remapper.getRemapMethodId()) { + return true; + } + + jclass localClass = env->FindClass(remap_class); + if (!localClass) { + if (env->ExceptionCheck()) env->ExceptionClear(); + spdlog::error("[JuiceRemapper JNI] FindClass failed: {}", remap_class); + return false; + } + + jclass globalClass = static_cast(env->NewGlobalRef(localClass)); + env->DeleteLocalRef(localClass); + if (!globalClass) { + spdlog::error("[JuiceRemapper JNI] NewGlobalRef failed: {}", remap_class); + return false; + } + + jmethodID methodId = env->GetStaticMethodID(globalClass, remap_method, remap_sig); + if (!methodId) { + if (env->ExceptionCheck()) env->ExceptionClear(); + env->DeleteGlobalRef(globalClass); + spdlog::error("[JuiceRemapper JNI] GetStaticMethodID failed: {}.{}", + remap_class, remap_method); + return false; + } + + remapper.setRemapClass(globalClass); + remapper.setRemapMethodId(methodId); + spdlog::debug("[JuiceRemapper JNI] Cached static declarations: {}.{}", + remap_class, remap_method); + return true; +} + +} // namespace + +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_initNative + (JNIEnv *env, jclass) { + // TODO: Init + + auto& remapper = JuiceAgent::Services::Remapper::getInstance(); + if (remapper.isInit()) { + spdlog::warn("JuiceRemapper::initNative: Remapper is already initialized"); + return JNI_FALSE; + } + + if (!cacheRemapDeclarations(env)) { + spdlog::error("JuiceRemapper::initNative: failed to cache static declarations"); + return JNI_FALSE; + } + + remapper.setInit(true); + + spdlog::info("[JuiceRemapper JNI] JuiceRemapper is initialized."); + + return JNI_TRUE; +} + +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_addInclude + (JNIEnv *, jclass, jstring) { + // TODO: implement + spdlog::warn("JuiceRemapper::addInclude"); + + return JNI_TRUE; +} + +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_addExclude + (JNIEnv *, jclass, jstring) { + // TODO: implement + spdlog::warn("JuiceRemapper::addExclude"); + + return JNI_TRUE; +} + +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_removeInclude + (JNIEnv *, jclass, jstring) { + // TODO: implement + spdlog::warn("JuiceRemapper::removeInclude"); + + return JNI_TRUE; +} + +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_removeExclude + (JNIEnv *, jclass, jstring){ + // TODO: implement + spdlog::warn("JuiceRemapper::removeExclude"); + + return JNI_TRUE; +} + +JNIEXPORT void JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_clearIncludes + (JNIEnv *, jclass) { + // TODO: implement + spdlog::warn("JuiceRemapper::clearIncludes"); +} + +JNIEXPORT void JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_clearExcludes + (JNIEnv *, jclass) { + // TODO: implement + spdlog::warn("JuiceRemapper::clearExcludes"); +} \ No newline at end of file diff --git a/src/libagent/services/JuiceRemapperService.cpp b/src/libagent/services/JuiceRemapperService.cpp new file mode 100644 index 0000000..e45bf95 --- /dev/null +++ b/src/libagent/services/JuiceRemapperService.cpp @@ -0,0 +1,147 @@ +#include +#include +#include +#include +#include +#include + +#include +#include + +namespace JuiceAgent { +namespace Services { + +class JuiceRemapperService : public IService { +public: + const char* name() const override { return "JuiceRemapperService"; } + + bool onInitialize() override { + listen( + EventId::Loaded, + &JuiceRemapperService::onLoaded + ); + + listen( + EventId::ClassFileLoadHook, + &JuiceRemapperService::onClassFileLoadHook + ); + + spdlog::debug("[JuiceRemapperService] Initialized"); + return true; + } + + void onShutdown() override { + unlistenAll(); + spdlog::debug("[JuiceRemapperService] Shutdown"); + } + +private: + void onLoaded(const EventLoaded& /*event*/) { + auto& agent = Agent::getInstance(); + auto& cfg = agent.getConfig(); + + const bool enabled = cfg.get( + "JuiceAgent.Modules.JuiceRemapper.Enabled", false); + + if (!enabled) { + spdlog::debug("[JuiceRemapperService] Disabled by config"); + return; + } + + spdlog::debug("[JuiceRemapperService] Enabled"); + } + + void onClassFileLoadHook(const EventClassFileLoadHook& e) { + if (!e.name || !e.jni_env || !e.jvmti_env || + !e.classbytes || e.class_data_len <= 0) { + return; + } + + auto& remapper = JuiceAgent::Services::Remapper::getInstance(); + if (!remapper.isInit()) + return; + + if (std::string_view(e.name).starts_with("cn/xiaozhou233/juiceremapper/")) + return; + + // TODO: Include/Exclude check + + jclass remapClass = remapper.getRemapClass(); + jmethodID remapMethod = remapper.getRemapMethodId(); + if (!remapClass || !remapMethod) { + spdlog::error("[JuiceRemapperService] Remap declarations not cached"); + return; + } + + JNIEnv* env = e.jni_env; + + // className: const char* -> jstring + jstring jClassName = env->NewStringUTF(e.name); + if (!jClassName) { + if (env->ExceptionCheck()) env->ExceptionClear(); + spdlog::error("[JuiceRemapperService] Failed to create className jstring"); + return; + } + + // classBytes: const unsigned char* -> jbyteArray + jbyteArray jClassBytes = env->NewByteArray(e.class_data_len); + if (!jClassBytes) { + if (env->ExceptionCheck()) env->ExceptionClear(); + env->DeleteLocalRef(jClassName); + spdlog::error("[JuiceRemapperService] Failed to create classBytes jbyteArray"); + return; + } + env->SetByteArrayRegion( + jClassBytes, 0, e.class_data_len, + reinterpret_cast(e.classbytes)); + if (env->ExceptionCheck()) { + env->ExceptionClear(); + env->DeleteLocalRef(jClassName); + env->DeleteLocalRef(jClassBytes); + spdlog::error("[JuiceRemapperService] Failed to fill classBytes"); + return; + } + + // Call static byte[] Remap.remap(String, byte[]) + jbyteArray jResult = static_cast( + env->CallStaticObjectMethod(remapClass, remapMethod, jClassName, jClassBytes)); + if (env->ExceptionCheck() || !jResult) { + env->ExceptionClear(); + env->DeleteLocalRef(jClassName); + env->DeleteLocalRef(jClassBytes); + spdlog::warn("[JuiceRemapperService] Remap returned null/exception for: {}", e.name); + return; + } + + const jsize newLen = env->GetArrayLength(jResult); + jbyte* newBytes = env->GetByteArrayElements(jResult, nullptr); + if (!newBytes) { + env->DeleteLocalRef(jClassName); + env->DeleteLocalRef(jClassBytes); + env->DeleteLocalRef(jResult); + return; + } + + // Write remapped bytes back to the JVMTI callback + unsigned char* newBuf = nullptr; + if (e.jvmti_env->Allocate(newLen, &newBuf) == JVMTI_ERROR_NONE) { + std::memcpy(newBuf, newBytes, newLen); + *e.new_class_data_len = newLen; + *e.new_classbytes = newBuf; + spdlog::info("[JuiceRemapperService] Remapped: {} ({} -> {} bytes)", + e.name, e.class_data_len, newLen); + } else { + spdlog::error("[JuiceRemapperService] Failed to allocate buffer for: {}", e.name); + } + + env->ReleaseByteArrayElements(jResult, newBytes, JNI_ABORT); + env->DeleteLocalRef(jClassName); + env->DeleteLocalRef(jClassBytes); + env->DeleteLocalRef(jResult); + } +}; + +} +} + +JUICEAGENT_REGISTER_SERVICE(::JuiceAgent::Services::JuiceRemapperService) From 6fe467bccf199af866f90329424e7f8968f981fd Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Tue, 18 Aug 2026 16:41:55 +0800 Subject: [PATCH 2/2] Feat: add include/exclude filters for JuiceRemapper - add thread-safe include/exclude sets to Remapper; shouldRemap matches exact name, package prefix (trailing '/'), or nested class ('\$' after the prefix), with exclude taking priority - remapping stays OFF by default: an empty include set remaps nothing; it is only enabled once addInclude is called (no config include) - implement addInclude/addExclude/removeInclude/removeExclude/ clearIncludes/clearExcludes JNI bindings - apply shouldRemap filter in JuiceRemapperService::onClassFileLoadHook --- src/libagent/includes/global.hpp | 67 +++++++++++++++++++ src/libagent/jni/juiceremapper.cpp | 56 +++++++++++----- .../services/JuiceRemapperService.cpp | 8 ++- 3 files changed, 113 insertions(+), 18 deletions(-) diff --git a/src/libagent/includes/global.hpp b/src/libagent/includes/global.hpp index 4da7aa5..dce21a6 100644 --- a/src/libagent/includes/global.hpp +++ b/src/libagent/includes/global.hpp @@ -150,12 +150,79 @@ public: void setRemapClass(jclass clazz) { remapClass_ = clazz; } void setRemapMethodId(jmethodID methodId) { remapMethodId_ = methodId; } + // ---- Include/Exclude filters ---- + + void addInclude(std::string name) { + std::lock_guard lock(filterMutex_); + includes_.insert(std::move(name)); + } + + void removeInclude(const std::string& name) { + std::lock_guard lock(filterMutex_); + includes_.erase(name); + } + + void clearIncludes() { + std::lock_guard lock(filterMutex_); + includes_.clear(); + } + + void addExclude(std::string name) { + std::lock_guard lock(filterMutex_); + excludes_.insert(std::move(name)); + } + + void removeExclude(const std::string& name) { + std::lock_guard lock(filterMutex_); + excludes_.erase(name); + } + + void clearExcludes() { + std::lock_guard lock(filterMutex_); + excludes_.clear(); + } + + // A class should be remapped when: + // 1. its name is not excluded, and + // 2. its name matches an include filter. + // Remapping is OFF by default: an empty include set means nothing is + // remapped. To enable remapping for a package, add it as an include + // (e.g. "com/example/" matches the whole package). + // + // Matching rules (applied to both include and exclude): + // - exact internal name match + // - package prefix (ends with '/', e.g. "java/lang/") + // - class prefix + nested classes (e.g. "java/lang/Shutdown" + // also excludes "java/lang/Shutdown$Lock") + bool shouldRemap(const std::string& name) const { + std::lock_guard lock(filterMutex_); + + for (const auto& exc : excludes_) { + if (name == exc) return false; + if (exc.back() == '/' && name.rfind(exc, 0) == 0) return false; + if (name.size() > exc.size() && + name.rfind(exc, 0) == 0 && name[exc.size()] == '$') return false; + } + + for (const auto& inc : includes_) { + if (name == inc) return true; + if (inc.back() == '/' && name.rfind(inc, 0) == 0) return true; + if (name.size() > inc.size() && + name.rfind(inc, 0) == 0 && name[inc.size()] == '$') return true; + } + return false; + } + private: Remapper() = default; bool initialized_ = false; jclass remapClass_ = nullptr; // global ref jmethodID remapMethodId_ = nullptr; // static method id + + mutable std::mutex filterMutex_; + std::unordered_set includes_; + std::unordered_set excludes_; }; } diff --git a/src/libagent/jni/juiceremapper.cpp b/src/libagent/jni/juiceremapper.cpp index 9b9680f..41325d5 100644 --- a/src/libagent/jni/juiceremapper.cpp +++ b/src/libagent/jni/juiceremapper.cpp @@ -72,45 +72,69 @@ JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_initN } JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_addInclude - (JNIEnv *, jclass, jstring) { - // TODO: implement - spdlog::warn("JuiceRemapper::addInclude"); + (JNIEnv *env, jclass, jstring name) { + if (!name) return JNI_FALSE; + const char* utf = env->GetStringUTFChars(name, nullptr); + if (!utf) return JNI_FALSE; + std::string s(utf); + env->ReleaseStringUTFChars(name, utf); + + JuiceAgent::Services::Remapper::getInstance().addInclude(std::move(s)); + spdlog::debug("[JuiceRemapper JNI] addInclude"); return JNI_TRUE; } JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_addExclude - (JNIEnv *, jclass, jstring) { - // TODO: implement - spdlog::warn("JuiceRemapper::addExclude"); + (JNIEnv *env, jclass, jstring name) { + if (!name) return JNI_FALSE; + const char* utf = env->GetStringUTFChars(name, nullptr); + if (!utf) return JNI_FALSE; + std::string s(utf); + env->ReleaseStringUTFChars(name, utf); + + JuiceAgent::Services::Remapper::getInstance().addExclude(std::move(s)); + spdlog::debug("[JuiceRemapper JNI] addExclude"); return JNI_TRUE; } JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_removeInclude - (JNIEnv *, jclass, jstring) { - // TODO: implement - spdlog::warn("JuiceRemapper::removeInclude"); + (JNIEnv *env, jclass, jstring name) { + if (!name) return JNI_FALSE; + const char* utf = env->GetStringUTFChars(name, nullptr); + if (!utf) return JNI_FALSE; + std::string s(utf); + env->ReleaseStringUTFChars(name, utf); + + JuiceAgent::Services::Remapper::getInstance().removeInclude(s); + spdlog::debug("[JuiceRemapper JNI] removeInclude"); return JNI_TRUE; } JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_removeExclude - (JNIEnv *, jclass, jstring){ - // TODO: implement - spdlog::warn("JuiceRemapper::removeExclude"); + (JNIEnv *env, jclass, jstring name){ + if (!name) return JNI_FALSE; + const char* utf = env->GetStringUTFChars(name, nullptr); + if (!utf) return JNI_FALSE; + std::string s(utf); + env->ReleaseStringUTFChars(name, utf); + + JuiceAgent::Services::Remapper::getInstance().removeExclude(s); + spdlog::debug("[JuiceRemapper JNI] removeExclude"); return JNI_TRUE; } JNIEXPORT void JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_clearIncludes (JNIEnv *, jclass) { - // TODO: implement - spdlog::warn("JuiceRemapper::clearIncludes"); + JuiceAgent::Services::Remapper::getInstance().clearIncludes(); + spdlog::debug("[JuiceRemapper JNI] clearIncludes"); } JNIEXPORT void JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_clearExcludes (JNIEnv *, jclass) { - // TODO: implement - spdlog::warn("JuiceRemapper::clearExcludes"); + JuiceAgent::Services::Remapper::getInstance().clearExcludes(); + spdlog::debug("[JuiceRemapper JNI] clearExcludes"); } \ No newline at end of file diff --git a/src/libagent/services/JuiceRemapperService.cpp b/src/libagent/services/JuiceRemapperService.cpp index e45bf95..6d8ac35 100644 --- a/src/libagent/services/JuiceRemapperService.cpp +++ b/src/libagent/services/JuiceRemapperService.cpp @@ -48,7 +48,7 @@ private: return; } - spdlog::debug("[JuiceRemapperService] Enabled"); + spdlog::debug("[JuiceRemapperService] Enabled. Waiting for addInclude to start remapping"); } void onClassFileLoadHook(const EventClassFileLoadHook& e) { @@ -64,7 +64,11 @@ private: if (std::string_view(e.name).starts_with("cn/xiaozhou233/juiceremapper/")) return; - // TODO: Include/Exclude check + // Include/Exclude filter check + if (!remapper.shouldRemap(e.name)) { + spdlog::trace("[JuiceRemapperService] Skipped by filter: {}", e.name); + return; + } jclass remapClass = remapper.getRemapClass(); jmethodID remapMethod = remapper.getRemapMethodId();