From f38743e863bbea174238af34f95b0f724495f915 Mon Sep 17 00:00:00 2001 From: xiaozhou233 Date: Mon, 17 Aug 2026 19:19:26 +0800 Subject: [PATCH] Feat: add JNI bytecode API and BytecodeStore - introduce thread-safe BytecodeStore singleton for pending captures, captured bytecode cache, and pending patches; replaces ad-hoc global mutex/map pairs - implement BytecodeService capture/patch listeners that operate on the store; keep JVMTI Allocate outside of store locks and put failed patches back so they can be retried - add JNI bindings: getClassBytes(ByName), redefineClass(ByName), retransformClass(ByName); use JVMTI GetLoadedClasses for name-based lookup instead of JNI FindClass, validate array length vs declared length in redefineClass --- src/libagent/includes/global.hpp | 135 +++++++++++ src/libagent/includes/jni_common.hpp | 1 + src/libagent/jni/bytecode.cpp | 266 ++++++++++++++++++++++ src/libagent/services/BytecodeService.cpp | 44 +++- 4 files changed, 440 insertions(+), 6 deletions(-) create mode 100644 src/libagent/includes/global.hpp create mode 100644 src/libagent/jni/bytecode.cpp diff --git a/src/libagent/includes/global.hpp b/src/libagent/includes/global.hpp new file mode 100644 index 0000000..11cdad5 --- /dev/null +++ b/src/libagent/includes/global.hpp @@ -0,0 +1,135 @@ +#pragma once + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace JuiceAgent { +namespace Services { + +struct ClassFileData { + std::string classname; + std::vector bytecode; +}; + +struct PendingPatch { + std::vector bytecode; +}; + +class BytecodeStore { +public: + static BytecodeStore& getInstance() { + static BytecodeStore instance; + return instance; + } + + BytecodeStore(const BytecodeStore&) = delete; + BytecodeStore& operator=(const BytecodeStore&) = delete; + + // ---- Capture API (called by JNI or other services) ---- + + // Mark a class (internal name, e.g. "java/lang/String") for capture + // on the next ClassFileLoadHook. + void requestCapture(std::string classname) { + std::lock_guard lock(mutex_); + pendingCaptures_.insert(std::move(classname)); + } + + // Returns the captured bytecode if available, removing it from the cache. + // Returns std::nullopt if not yet captured. + std::optional takeCaptured(const std::string& classname) { + std::lock_guard lock(mutex_); + auto it = captured_.find(classname); + if (it == captured_.end()) { + return std::nullopt; + } + ClassFileData data = std::move(it->second); + captured_.erase(it); + return data; + } + + // Peek without removing. + std::optional peekCaptured(const std::string& classname) const { + std::lock_guard lock(mutex_); + auto it = captured_.find(classname); + if (it == captured_.end()) { + return std::nullopt; + } + return it->second; + } + + // ---- Patch API (called by JNI or other services) ---- + + // Queue a retransform: the next ClassFileLoadHook for this class will + // replace its bytecode with the provided buffer. + void requestPatch(std::string classname, std::vector bytecode) { + std::lock_guard lock(mutex_); + pendingPatches_.insert_or_assign( + std::move(classname), + PendingPatch{std::move(bytecode)} + ); + } + +private: + friend class BytecodeService; + + BytecodeStore() = default; + + // Called by BytecodeService::captureBytecodes under internal lock. + // Stores the raw bytes if this class is pending capture. + // Returns the captured byte length, or 0 if no capture was pending. + std::size_t tryCapture(const char* name, const unsigned char* bytes, jint len) { + std::lock_guard lock(mutex_); + if (!name || !bytes || len <= 0) return 0; + + auto reqIt = pendingCaptures_.find(name); + if (reqIt == pendingCaptures_.end()) return 0; + if (captured_.find(name) != captured_.end()) { + pendingCaptures_.erase(reqIt); + return 0; + } + + ClassFileData data; + data.classname = name; + data.bytecode.assign(bytes, bytes + len); + + std::size_t capturedLen = data.bytecode.size(); + captured_.emplace(name, std::move(data)); + pendingCaptures_.erase(reqIt); + return capturedLen; + } + + // Called by BytecodeService::patchBytecodes under internal lock. + // If a pending patch exists for `name`, moves its bytecode out and + // returns true; otherwise returns false. + bool takePatch(const char* name, std::vector& out) { + std::lock_guard lock(mutex_); + if (!name) return false; + auto it = pendingPatches_.find(name); + if (it == pendingPatches_.end()) return false; + out = std::move(it->second.bytecode); + pendingPatches_.erase(it); + return true; + } + + // Put a failed patch back so it can be retried on the next hook. + void putBackPatch(const char* name, std::vector&& bytes) { + if (!name || bytes.empty()) return; + std::lock_guard lock(mutex_); + pendingPatches_.insert_or_assign( + name, PendingPatch{std::move(bytes)}); + } + + mutable std::mutex mutex_; + std::unordered_set pendingCaptures_; + std::unordered_map captured_; + std::unordered_map pendingPatches_; +}; + +} +} diff --git a/src/libagent/includes/jni_common.hpp b/src/libagent/includes/jni_common.hpp index ac9e197..b35e88f 100644 --- a/src/libagent/includes/jni_common.hpp +++ b/src/libagent/includes/jni_common.hpp @@ -5,6 +5,7 @@ #include #include #include +#include // Generated by JuiceAgent-API #include diff --git a/src/libagent/jni/bytecode.cpp b/src/libagent/jni/bytecode.cpp new file mode 100644 index 0000000..05dc76b --- /dev/null +++ b/src/libagent/jni/bytecode.cpp @@ -0,0 +1,266 @@ +#include +#include +#include +#include +#include +#include + +using JuiceAgent::Services::BytecodeStore; + +namespace { + +// Convert "Lcom/foo/Bar;" -> "com/foo/Bar"; returns empty on malformed input. +std::string signatureToInternal(const char* signature) { + if (!signature) return {}; + size_t len = std::strlen(signature); + if (len < 2 || signature[0] != 'L' || signature[len - 1] != ';') return {}; + return std::string(signature + 1, len - 2); +} + +std::string dottedToInternal(std::string s) { + std::replace(s.begin(), s.end(), '.', '/'); + return s; +} + +// Find a loaded class by internal name ("com/foo/Bar"). Returns a local ref, +// or nullptr if not found. Caller must DeleteLocalRef when done. +jclass findLoadedClass(jvmtiEnv* jvmti, JNIEnv* env, const std::string& internalName) { + jint count = 0; + jclass* classes = nullptr; + if (jvmti->GetLoadedClasses(&count, &classes) != JVMTI_ERROR_NONE || count == 0) { + return nullptr; + } + + jclass target = nullptr; + for (jint i = 0; i < count; ++i) { + char* sig = nullptr; + if (jvmti->GetClassSignature(classes[i], &sig, nullptr) != JVMTI_ERROR_NONE || !sig) { + continue; + } + std::string name = signatureToInternal(sig); + jvmti->Deallocate(reinterpret_cast(sig)); + if (name == internalName) { + target = static_cast(env->NewLocalRef(classes[i])); + break; + } + } + jvmti->Deallocate(reinterpret_cast(classes)); + return target; +} + +} + +// --------------------------------------------------------------------------- +// getClassBytes(Class) -> byte[] +// --------------------------------------------------------------------------- +JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytes + (JNIEnv *env, jclass, jclass clazz) { + + auto& agent = JuiceAgent::Agent::getInstance(); + if (!check_env(agent) || !clazz) return nullptr; + + char* signature = nullptr; + if (agent.getJVMTI()->GetClassSignature(clazz, &signature, nullptr) != JVMTI_ERROR_NONE || !signature) { + return nullptr; + } + std::string internalName = signatureToInternal(signature); + agent.getJVMTI()->Deallocate(reinterpret_cast(signature)); + if (internalName.empty()) return nullptr; + + BytecodeStore::getInstance().requestCapture(internalName); + + jvmtiError err = agent.getJVMTI()->RetransformClasses(1, &clazz); + if (err != JVMTI_ERROR_NONE) { + spdlog::error("[bytecode] RetransformClasses failed for {}: {}", + internalName, static_cast(err)); + return nullptr; + } + + auto captured = BytecodeStore::getInstance().takeCaptured(internalName); + if (!captured || captured->bytecode.empty()) { + spdlog::error("[bytecode] Failed to capture bytecode for class: {}", internalName); + return nullptr; + } + + jbyteArray out = env->NewByteArray(static_cast(captured->bytecode.size())); + if (!out || env->ExceptionCheck()) { + env->ExceptionClear(); + return nullptr; + } + env->SetByteArrayRegion(out, 0, + static_cast(captured->bytecode.size()), + reinterpret_cast(captured->bytecode.data())); + return out; +} + +// --------------------------------------------------------------------------- +// getClassBytesByName(String) -> byte[] +// --------------------------------------------------------------------------- +JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytesByName + (JNIEnv *env, jclass, jstring name) { + + if (!name) return nullptr; + auto& agent = JuiceAgent::Agent::getInstance(); + if (!check_env(agent)) return nullptr; + + const char* utf = env->GetStringUTFChars(name, nullptr); + if (!utf) return nullptr; + std::string internalName = dottedToInternal(utf); + env->ReleaseStringUTFChars(name, utf); + + jclass target = findLoadedClass(agent.getJVMTI(), env, internalName); + if (!target) { + spdlog::error("[bytecode] Class not loaded: {}", internalName); + return nullptr; + } + + jbyteArray result = Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytes(env, nullptr, target); + env->DeleteLocalRef(target); + return result; +} + +// --------------------------------------------------------------------------- +// redefineClass(Class, byte[], int) -> boolean +// --------------------------------------------------------------------------- +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClass + (JNIEnv *env, jclass, jclass clazz, jbyteArray class_bytes, jint class_bytes_len) { + + auto& agent = JuiceAgent::Agent::getInstance(); + if (!check_env(agent) || !clazz || !class_bytes || class_bytes_len <= 0) { + return JNI_FALSE; + } + + // Validate the declared length against the actual array length to prevent + // JVMTI from reading past the buffer. + const jint array_len = env->GetArrayLength(class_bytes); + if (class_bytes_len > array_len) { + spdlog::error("[bytecode] class_bytes_len {} exceeds array length {}", + class_bytes_len, array_len); + return JNI_FALSE; + } + + jbyte* buf = env->GetByteArrayElements(class_bytes, nullptr); + if (!buf) { + spdlog::error("[bytecode] Cannot get class bytes"); + return JNI_FALSE; + } + + jvmtiClassDefinition def{}; + def.klass = clazz; + def.class_byte_count = class_bytes_len; + def.class_bytes = reinterpret_cast(buf); + + jvmtiError result = agent.getJVMTI()->RedefineClasses(1, &def); + env->ReleaseByteArrayElements(class_bytes, buf, JNI_ABORT); + + if (result != JVMTI_ERROR_NONE) { + spdlog::error("[bytecode] RedefineClasses failed: {}", static_cast(result)); + return JNI_FALSE; + } + + spdlog::debug("[bytecode] Class redefined successfully"); + return JNI_TRUE; +} + +// --------------------------------------------------------------------------- +// redefineClassByName(String, byte[], int) -> boolean +// --------------------------------------------------------------------------- +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClassByName + (JNIEnv *env, jclass, jstring class_name, jbyteArray class_bytes, jint class_bytes_len) { + + if (!class_name) return JNI_FALSE; + auto& agent = JuiceAgent::Agent::getInstance(); + if (!check_env(agent)) return JNI_FALSE; + + const char* cname = env->GetStringUTFChars(class_name, nullptr); + if (!cname) return JNI_FALSE; + std::string internalName = dottedToInternal(cname); + env->ReleaseStringUTFChars(class_name, cname); + + // JNI FindClass uses the caller's classloader, which is unreliable from a + // native agent thread. Use JVMTI to search loaded classes instead. + jclass clazz = findLoadedClass(agent.getJVMTI(), env, internalName); + if (!clazz) { + spdlog::error("[bytecode] Cannot find loaded class: {}", internalName); + return JNI_FALSE; + } + + jboolean result = Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClass( + env, nullptr, clazz, class_bytes, class_bytes_len); + env->DeleteLocalRef(clazz); + return result; +} + +// --------------------------------------------------------------------------- +// retransformClass(Class, byte[], int) -> boolean +// +// Queues new bytecode for the next ClassFileLoadHook (which will write it +// back via new_classbytes/new_class_data_len), then triggers RetransformClasses. +// The `length` parameter is kept for JNI signature compatibility but the +// actual length is read from the array. +// --------------------------------------------------------------------------- +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClass + (JNIEnv* env, jclass, jclass clazz, jbyteArray bytecodes, jint /*length*/) { + + auto& agent = JuiceAgent::Agent::getInstance(); + if (!check_env(agent) || !clazz || !bytecodes) return JNI_FALSE; + + char* signature = nullptr; + if (agent.getJVMTI()->GetClassSignature(clazz, &signature, nullptr) != JVMTI_ERROR_NONE || !signature) { + return JNI_FALSE; + } + std::string internalName = signatureToInternal(signature); + agent.getJVMTI()->Deallocate(reinterpret_cast(signature)); + if (internalName.empty()) return JNI_FALSE; + + jint len = env->GetArrayLength(bytecodes); + if (len <= 0) return JNI_FALSE; + + jbyte* bytes = env->GetByteArrayElements(bytecodes, nullptr); + if (!bytes) return JNI_FALSE; + + std::vector newBytes( + reinterpret_cast(bytes), + reinterpret_cast(bytes) + len); + env->ReleaseByteArrayElements(bytecodes, bytes, JNI_ABORT); + + BytecodeStore::getInstance().requestPatch(internalName, std::move(newBytes)); + + jclass classes[1] = { clazz }; + jvmtiError err = agent.getJVMTI()->RetransformClasses(1, classes); + if (err != JVMTI_ERROR_NONE) { + spdlog::error("[bytecode] RetransformClasses failed for {}: {}", + internalName, static_cast(err)); + return JNI_FALSE; + } + + spdlog::info("[bytecode] Retransform queued: {} ({} bytes)", internalName, len); + return JNI_TRUE; +} + +// --------------------------------------------------------------------------- +// retransformClassByName(String, byte[], int) -> boolean +// --------------------------------------------------------------------------- +JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClassByName + (JNIEnv* env, jclass, jstring className, jbyteArray bytecodes, jint length) { + + if (!className) return JNI_FALSE; + auto& agent = JuiceAgent::Agent::getInstance(); + if (!check_env(agent)) return JNI_FALSE; + + const char* utf = env->GetStringUTFChars(className, nullptr); + if (!utf) return JNI_FALSE; + std::string internalName = dottedToInternal(utf); + env->ReleaseStringUTFChars(className, utf); + + jclass target = findLoadedClass(agent.getJVMTI(), env, internalName); + if (!target) { + spdlog::error("[bytecode] Class not loaded: {}", internalName); + return JNI_FALSE; + } + + jboolean result = Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClass( + env, nullptr, target, bytecodes, length); + env->DeleteLocalRef(target); + return result; +} diff --git a/src/libagent/services/BytecodeService.cpp b/src/libagent/services/BytecodeService.cpp index c4981fb..65b2826 100644 --- a/src/libagent/services/BytecodeService.cpp +++ b/src/libagent/services/BytecodeService.cpp @@ -2,6 +2,9 @@ #include #include #include +#include + +#include namespace JuiceAgent { namespace Services { @@ -31,15 +34,44 @@ public: private: void captureBytecodes(const EventClassFileLoadHook& e) { - // TODO: Capture original bytes - spdlog::trace("[BytecodeService] Capture original bytes: {}", - e.name ? e.name : ""); + if (!e.name) return; + + const std::size_t len = BytecodeStore::getInstance() + .tryCapture(e.name, e.classbytes, e.class_data_len); + + if (len > 0) { + spdlog::info("[BytecodeService] Captured class: {} (length: {})", + e.name, len); + } } void patchBytecodes(const EventClassFileLoadHook& e) { - // TODO: Apply patches - spdlog::trace("[BytecodeService] Apply patches: {}", - e.name ? e.name : ""); + if (!e.name || !e.jvmti_env || + !e.new_class_data_len || !e.new_classbytes) { + return; + } + + std::vector bytes; + if (!BytecodeStore::getInstance().takePatch(e.name, bytes) || bytes.empty()) { + return; + } + + const jlong new_len = static_cast(bytes.size()); + unsigned char* new_buf = nullptr; + if (e.jvmti_env->Allocate(new_len, &new_buf) != JVMTI_ERROR_NONE) { + // Put bytes back so a future hook can retry instead of losing the patch. + BytecodeStore::getInstance().putBackPatch(e.name, std::move(bytes)); + spdlog::error("[BytecodeService] Failed to allocate buffer for: {}", e.name); + return; + } + + std::memcpy(new_buf, bytes.data(), bytes.size()); + + *e.new_class_data_len = static_cast(new_len); + *e.new_classbytes = new_buf; + + spdlog::info("[BytecodeService] Patched class: {} (new length: {})", + e.name, new_len); } };