Refactor: rebuild libagent with simplified lifecycle

- Replace eventbus/services with Agent preload/init lifecycle
- Move JNI header to shared includes; add jni_common.hpp umbrella header
- Reduce ClassFileLoadHook to a stub for later implementation
- Add eventpp dependency
- Document custom API JAR workflow (WIP)
This commit is contained in:
xiaozhou233 committed 2026-08-16 21:14:44 +08:00
1 parent 3b180e7199
commit 51bcfbd549
47 files changed
+5583 -1462

No files matched your search

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