mirror of
https://github.com/xiaozhou233/JuiceAgent.git
synced 2026-12-05 13:05:53 +08:00
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
This commit is contained in:
1 parent
8e1b8b38e4
commit
f38743e863
4 files changed
+440
-6
No files matched your search
@@ -0,0 +1,135 @@
|
||||
#pragma once
|
||||
|
||||
#include <jni.h>
|
||||
#include <jvmti.h>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <vector>
|
||||
|
||||
namespace JuiceAgent {
|
||||
namespace Services {
|
||||
|
||||
struct ClassFileData {
|
||||
std::string classname;
|
||||
std::vector<unsigned char> bytecode;
|
||||
};
|
||||
|
||||
struct PendingPatch {
|
||||
std::vector<unsigned char> 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<std::mutex> 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<ClassFileData> takeCaptured(const std::string& classname) {
|
||||
std::lock_guard<std::mutex> 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<ClassFileData> peekCaptured(const std::string& classname) const {
|
||||
std::lock_guard<std::mutex> 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<unsigned char> bytecode) {
|
||||
std::lock_guard<std::mutex> 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<std::mutex> 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<unsigned char>& out) {
|
||||
std::lock_guard<std::mutex> 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<unsigned char>&& bytes) {
|
||||
if (!name || bytes.empty()) return;
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
pendingPatches_.insert_or_assign(
|
||||
name, PendingPatch{std::move(bytes)});
|
||||
}
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
std::unordered_set<std::string> pendingCaptures_;
|
||||
std::unordered_map<std::string, ClassFileData> captured_;
|
||||
std::unordered_map<std::string, PendingPatch> pendingPatches_;
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <JuiceAgent/Logger.hpp>
|
||||
#include <JuiceAgent.hpp>
|
||||
#include <utils.hpp>
|
||||
#include <global.hpp>
|
||||
|
||||
// Generated by JuiceAgent-API
|
||||
#include <JuiceAgent/cn_xiaozhou233_juiceagent_api_JuiceAgent.h>
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
#include <jni_common.hpp>
|
||||
#include <global.hpp>
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <cstring>
|
||||
|
||||
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<unsigned char*>(sig));
|
||||
if (name == internalName) {
|
||||
target = static_cast<jclass>(env->NewLocalRef(classes[i]));
|
||||
break;
|
||||
}
|
||||
}
|
||||
jvmti->Deallocate(reinterpret_cast<unsigned char*>(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<unsigned char*>(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<int>(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<jsize>(captured->bytecode.size()));
|
||||
if (!out || env->ExceptionCheck()) {
|
||||
env->ExceptionClear();
|
||||
return nullptr;
|
||||
}
|
||||
env->SetByteArrayRegion(out, 0,
|
||||
static_cast<jsize>(captured->bytecode.size()),
|
||||
reinterpret_cast<const jbyte*>(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<const unsigned char*>(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<int>(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<unsigned char*>(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<unsigned char> newBytes(
|
||||
reinterpret_cast<const unsigned char*>(bytes),
|
||||
reinterpret_cast<const unsigned char*>(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<int>(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;
|
||||
}
|
||||
@@ -2,6 +2,9 @@
|
||||
#include <services/service_manager.hpp>
|
||||
#include <event/event_type.hpp>
|
||||
#include <JuiceAgent/Logger.hpp>
|
||||
#include <global.hpp>
|
||||
|
||||
#include <cstring>
|
||||
|
||||
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 : "<null>");
|
||||
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 : "<null>");
|
||||
if (!e.name || !e.jvmti_env ||
|
||||
!e.new_class_data_len || !e.new_classbytes) {
|
||||
return;
|
||||
}
|
||||
|
||||
std::vector<unsigned char> bytes;
|
||||
if (!BytecodeStore::getInstance().takePatch(e.name, bytes) || bytes.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const jlong new_len = static_cast<jlong>(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<jint>(new_len);
|
||||
*e.new_classbytes = new_buf;
|
||||
|
||||
spdlog::info("[BytecodeService] Patched class: {} (new length: {})",
|
||||
e.name, new_len);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
Reference in new issue
Block a user