DELETE: all code

This commit is contained in:
xiaozhou233 committed 2026-08-15 10:23:15 +08:00
1 parent 56b6ab7e98
commit fe64308942
134 files changed
-41980

No files matched your search

-20
View File
@@ -1,20 +0,0 @@
file(
GLOB_RECURSE
agent_sources
${CMAKE_CURRENT_SOURCE_DIR}/*.cpp
${CMAKE_CURRENT_SOURCE_DIR}/*.c
)
add_library(agent SHARED ${agent_sources})
target_include_directories(agent PRIVATE
${CMAKE_SOURCE_DIR}/includes
${CMAKE_SOURCE_DIR}/includes/jvm
${CMAKE_SOURCE_DIR}/includes/jvm/win32
${CMAKE_CURRENT_SOURCE_DIR}/includes
)
target_link_libraries(agent PRIVATE
ReflectiveDLLInjection
jvm
)
-96
View File
@@ -1,96 +0,0 @@
#include <JuiceAgent.hpp>
#include <jni_impl.hpp>
#include <event/event_type.hpp>
#include <event/eventbus.hpp>
#include <JuiceAgent/Config.hpp>
#include <services.hpp>
namespace JuiceAgent {
// ===== Singleton =====
Agent& Agent::instance() {
static Agent instance;
return instance;
}
bool Agent::init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti, std::string& runtime_dir) {
try {
PLOGI << "JuiceAgent Native EntryPoint Invoked!";
// ======== neccessary environment check ========
if (jvm == nullptr) {
PLOGE << "Failed to initialize JuiceAgent: jvm is null";
return false;
}
if (env == nullptr) {
PLOGE << "Failed to initialize JuiceAgent: env is null";
return false;
}
if (jvmti == nullptr) {
PLOGE << "Failed to initialize JuiceAgent: jvmti is null";
return false;
}
JuiceAgent::Config::Config cfg (runtime_dir);
if (!cfg.is_valid()) {
PLOGE << "Failed to initialize JuiceAgent: config is invalid";
return false;
}
set_jvm(jvm);
set_jvmti(jvmti);
set_env(env);
set_config(cfg);
PLOGD << "env: " << env << ", jvmti: " << 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) {
PLOGE << "Failed to add capabilities: " << result;
return false;
}
PLOGI << "Abilities added successfully";
// ======== Register callbacks ========
jvmtiEventCallbacks callbacks{};
callbacks.ClassFileLoadHook = &ClassFileLoadHook;
result = jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks));
if (result != JNI_OK) {
PLOGE << "Failed to set event callbacks: " << result;
}
// Enable events
result = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, NULL);
if (result != JNI_OK) {
PLOGE << "Failed to enable event notification: " << result;
}
// Loaded Event
eventbus.post(EventLoaded{
.jvm = jvm,
.env = env,
.jvmti = jvmti
});
return true;
} catch (const std::exception& e) {
PLOGE << "Exception: " << e.what();
return false;
}
}
}
@@ -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) {
PLOGW << "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
});
}
-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) {
PLOGE << action << " failed, code=" << err;
return false;
}
return true;
}
// VMInit callback
void JNICALL OnVMInit(jvmtiEnv* jvmti, JNIEnv* env, jthread thread) {
PLOGI << "JVMTI VMInit triggered";
std::string runtime_dir = std::filesystem::current_path().string();
if (runtime_dir.empty()) {
PLOGE << "runtime_dir is empty";
return;
}
PLOGI << "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
);
PLOGD << "Saved JuiceAgent-API to: " << juiceagent_api_path;
PLOGD << "JuiceAgent-API size: " << JuiceAgent::Resource::juiceagent_api_bytes_len;
PLOGD << "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) {
PLOGE << "AddToSystemClassLoaderSearch failed: " << status;
return;
}
PLOGI << "Jar injected successfully: " << juiceagent_api_path;
JuiceAgent::Agent& agent = JuiceAgent::Agent::instance();
agent.init(g_vm, env, g_jvmti, runtime_dir);
PLOGI << "JuiceAgent initialized successfully";
}
// Agent entry
JNIEXPORT jint JNICALL
Agent_OnLoad(JavaVM* vm, char* options, void* reserved) {
InitLogger();
PLOGI << "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) {
PLOGE << "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;
}
PLOGI << "Agent loaded, waiting for VMInit...";
return JNI_OK;
}
// Optional unload
JNIEXPORT void JNICALL
Agent_OnUnload(JavaVM* vm) {
PLOGI << "Agent_OnUnload";
}
-44
View File
@@ -1,44 +0,0 @@
#include <jni_impl.hpp>
#include <JuiceAgent.hpp>
// This function is called by Java to initialize the agent.
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init
(JNIEnv *env, jclass , jstring j_runtime_dir) {
InitLogger();
PLOGI << "Initializing JuiceAgent...";
// Get runtime directory
const char* c_runtime_dir = env->GetStringUTFChars(j_runtime_dir, nullptr);
std::string runtime_dir(c_runtime_dir);
env->ReleaseStringUTFChars(j_runtime_dir, c_runtime_dir);
if (runtime_dir.empty()) {
PLOGE << "Failed to get runtime directory from argument, runtime_dir is empty";
return JNI_FALSE;
}
PLOGI << "JuiceAgent got runtime directory: " << runtime_dir;
JavaVM* jvm = nullptr;
jvmtiEnv* jvmti = nullptr;
// Get Java VM
env->GetJavaVM(&jvm);
if (jvm == nullptr) {
PLOGE << "Failed to get JavaVM instance";
return JNI_FALSE;
}
// Get JVMTI
jvmtiError err = static_cast<jvmtiError>(jvm->GetEnv(reinterpret_cast<void**>(&jvmti), JVMTI_VERSION_1_2));
if (err != JVMTI_ERROR_NONE || jvmti == nullptr) {
PLOGE << "Failed to get JVMTI environment, error: " << err;
return JNI_FALSE;
}
// Invoke EntryPoint
JuiceAgent::Agent& agent = JuiceAgent::Agent::instance();
agent.init(jvm, env, jvmti, runtime_dir);
return JNI_TRUE;
}
-45
View File
@@ -1,45 +0,0 @@
#pragma once
#include <JuiceAgent/Logger.hpp>
#include <jni.h>
#include <jvmti.h>
#include <event/eventbus.hpp>
#include <JuiceAgent/Config.hpp>
namespace JuiceAgent {
class Agent {
private:
JavaVM* jvm;
jvmtiEnv* jvmti;
JNIEnv* env;
EventBus eventbus;
JuiceAgent::Config::Config config;
private:
Agent() = default;
~Agent() = default;
public:
// ===== Singleton =====
static Agent& instance();
Agent(const Agent&) = delete;
Agent& operator=(const Agent&) = delete;
// EntryPoint
bool init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti, std::string& runtime_dir);
// 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; }
// 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; }
};
}
@@ -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
@@ -1,48 +0,0 @@
#pragma once
#include <jni_impl.hpp>
// ClassFileLoadHook
struct EventClassFileLoadHook {
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;
};
// MethodEntry
struct EventMethodEntry {
jvmtiEnv* jvmti_env;
JNIEnv* jni_env;
jthread thread;
jmethodID method;
};
// MethodExit
struct EventMethodExit {
jvmtiEnv* jvmti_env;
JNIEnv* jni_env;
jthread thread;
jmethodID method;
jboolean was_popped_by_exception;
jvalue return_value;
};
// JuiceAgent PreLoad/PostLoad
struct EventPreLoad {
JavaVM* jvm;
JNIEnv* env;
jvmtiEnv* jvmti;
};
struct EventLoaded {
JavaVM* jvm;
JNIEnv* env;
jvmtiEnv* jvmti;
};
-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;
-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);
-37
View File
@@ -1,37 +0,0 @@
#pragma once
#include <string>
#include <JuiceAgent.hpp>
#include <event/event_type.hpp>
namespace JuiceAgent::services
{
static JuiceAgent::Agent& agent = JuiceAgent::Agent::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) {
PLOGE << "Failed to get JavaVM instance";
return false;
}
if (agent.get_jvmti() == nullptr) {
PLOGE << "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;
}
-328
View File
@@ -1,328 +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) {
PLOGE << "Retransform class failed: " << 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()) {
PLOGE << "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) {
PLOGE << "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) {
PLOGE << "Cannot get class bytes";
return JNI_FALSE;
}
// Prepare JVMTI class definition
jvmtiClassDefinition defs[1];
defs[0].klass = clazz;
defs[0].class_byte_count = class_bytes_len;
defs[0].class_bytes = reinterpret_cast<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) {
PLOGE << "Redefine class failed: " << result;
return JNI_FALSE;
}
PLOGD << "Class redefined successfully!";
return JNI_TRUE;
}
// ============================================
// Redefine class using its fully qualified name
// Supports automatic '.' -> '/' conversion
// ============================================
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClassByName
(JNIEnv *env, jclass loader_class, jstring class_name, jbyteArray class_bytes, jint class_bytes_len) {
// Convert jstring to C string
const char* cname = env->GetStringUTFChars(class_name, nullptr);
if (!cname) {
PLOGE << "Class name is NULL!";
return JNI_FALSE;
}
// Copy and replace '.' with '/' for JVM internal class name
std::string internal_name(cname);
std::replace(internal_name.begin(), internal_name.end(), '.', '/');
// Release the original Java string
env->ReleaseStringUTFChars(class_name, cname);
// Find class by internal name
jclass clazz = env->FindClass(internal_name.c_str());
if (!clazz) {
PLOGE << "Cannot find class: " << internal_name;
return JNI_FALSE;
}
// Call redefineClass with the found class
return Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClass(
env, loader_class, clazz, class_bytes, class_bytes_len
);
}
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClass
(JNIEnv* env, jclass, jclass clazz, jbyteArray bytecodes, jint length) {
auto& agent = JuiceAgent::Agent::instance();
// =========================
// 1. Check environment & parameters
// =========================
if (!check_env(agent) || !clazz || !bytecodes) {
return JNI_FALSE;
}
// =========================
// 2. Get class internal name
// =========================
std::string nameDot = get_class_name(env, clazz);
if (nameDot.empty()) {
PLOGE << "Failed to get class name for retransform";
return JNI_FALSE;
}
// Convert '.' to '/' for internal name
for (auto& c : nameDot) if (c == '.') c = '/';
// =========================
// 3. Extract bytecode from jbyteArray
// =========================
jbyte* bytes = env->GetByteArrayElements(bytecodes, nullptr);
jint len = env->GetArrayLength(bytecodes);
if (!bytes || len <= 0) {
return JNI_FALSE;
}
// =========================
// 4. Cache bytecode & class info for ClassFileLoadHook
// =========================
{
std::lock_guard<std::mutex> lock(classDataMutex);
ClassFileData data;
data.classname = nameDot;
data.bytecode.assign(bytes, bytes + len);
data.clazz = static_cast<jclass>(env->NewGlobalRef(clazz)); // prevent GC
data.classloader = nullptr; // optional
data.protection_domain = nullptr;
classFileDataMap[nameDot] = std::move(data);
}
env->ReleaseByteArrayElements(bytecodes, bytes, JNI_ABORT);
// =========================
// 5. Trigger JVMTI retransform
// =========================
jclass classes[1] = { clazz };
jvmtiError err = agent.get_jvmti()->RetransformClasses(1, classes);
if (err != JVMTI_ERROR_NONE) {
PLOGE << "[retransformClass] failed: " << err << " for " << nameDot;
return JNI_FALSE;
}
PLOGI << "[retransformClass] OK: " << nameDot << " (" << len << " bytes)";
return JNI_TRUE;
}
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClassByName
(JNIEnv* env, jclass, jstring className, jbyteArray bytecodes, jint length) {
auto& agent = JuiceAgent::Agent::instance();
if (!check_env(agent) || !className || !bytecodes) {
return JNI_FALSE;
}
// =========================
// 1. Get UTF string from jstring
// =========================
const char* utf = env->GetStringUTFChars(className, nullptr);
if (!utf) return JNI_FALSE;
std::string internalName(utf);
env->ReleaseStringUTFChars(className, utf);
// Convert '.' to '/' for internal name
for (auto& c : internalName) if (c == '.') c = '/';
// =========================
// 2. Find loaded class by internal name (inline)
// =========================
jclass target = nullptr;
{
jint classCount = 0;
jclass* loadedClasses = nullptr;
if (agent.get_jvmti()->GetLoadedClasses(&classCount, &loadedClasses) == JVMTI_ERROR_NONE && classCount > 0) {
for (jint i = 0; i < classCount; ++i) {
char* sig = nullptr;
if (agent.get_jvmti()->GetClassSignature(loadedClasses[i], &sig, nullptr) == JVMTI_ERROR_NONE && sig) {
// sig: "Lnet/minecraft/client/Minecraft;"
if (sig[0] == 'L') {
size_t len = strlen(sig);
if (len > 2 && internalName == std::string(sig + 1, len - 2)) {
target = loadedClasses[i];
agent.get_jvmti()->Deallocate(reinterpret_cast<unsigned char*>(sig));
break;
}
}
agent.get_jvmti()->Deallocate(reinterpret_cast<unsigned char*>(sig));
}
}
agent.get_jvmti()->Deallocate(reinterpret_cast<unsigned char*>(loadedClasses));
}
}
if (!target) {
PLOGE << "[retransformClassByName] class not loaded: " << internalName;
return JNI_FALSE;
}
// =========================
// 3. Delegate to retransformClass
// =========================
return Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClass(
env, nullptr, target, bytecodes, length
);
}
-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) {
PLOGE << "Path is NULL!";
return JNI_FALSE;
}
jvmtiError result = agent.get_jvmti()->AddToBootstrapClassLoaderSearch(j_jar_path);
if (result != JVMTI_ERROR_NONE) {
PLOGE.printf("Cannot AddToBootstrapClassLoaderSearch [result=%d]", result);
env->ReleaseStringUTFChars(jar_path, j_jar_path);
return JNI_FALSE;
}
PLOGI << "AddToBootstrapClassLoaderSearch: " << j_jar_path;
env->ReleaseStringUTFChars(jar_path, j_jar_path);
return JNI_TRUE;
}
// Add jar to system classloader search path
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToSystemClassLoaderSearch
(JNIEnv *env, jclass, jstring jar_path) {
auto& agent = JuiceAgent::Agent::instance();
if (!check_env(agent))
return JNI_FALSE;
const char* j_jar_path = env->GetStringUTFChars(jar_path, nullptr);
if (!j_jar_path) {
PLOGE << "Path is NULL!";
return JNI_FALSE;
}
jvmtiError result = agent.get_jvmti()->AddToSystemClassLoaderSearch(j_jar_path);
if (result != JVMTI_ERROR_NONE) {
PLOGE.printf("Cannot AddToSystemClassLoaderSearch [result=%d]", result);
env->ReleaseStringUTFChars(jar_path, j_jar_path);
return JNI_FALSE;
}
PLOGI << "AddToSystemClassLoaderSearch: " << j_jar_path;
env->ReleaseStringUTFChars(jar_path, j_jar_path);
return JNI_TRUE;
}
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) {
PLOGE.printf("GetLoadedClasses failed: %d", err);
return nullptr;
}
jclass classClass = env->FindClass("java/lang/Class");
jobjectArray classesArray = env->NewObjectArray(count, classClass, nullptr);
for (int i = 0; i < count; i++) {
env->SetObjectArrayElement(classesArray, i, classes[i]);
}
agent.get_jvmti()->Deallocate((unsigned char*)classes);
return classesArray;
}
JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassByName
(JNIEnv *env, jclass, jstring name) {
auto& agent = JuiceAgent::Agent::instance();
if (!check_env(agent))
return nullptr;
const char* utf = env->GetStringUTFChars(name, nullptr);
if (!utf) {
PLOGE << "Class name is NULL!";
return nullptr;
}
// Convert Java name to internal name: a.b.C -> a/b/C
std::string internal_name(utf);
std::replace(internal_name.begin(), internal_name.end(), '.', '/');
env->ReleaseStringUTFChars(name, utf);
// Get all loaded classes
jint count = 0;
jclass* classes = nullptr;
if (agent.get_jvmti()->GetLoadedClasses(&count, &classes) != JVMTI_ERROR_NONE || count == 0) {
PLOGE << "GetLoadedClasses failed or no classes loaded";
return nullptr;
}
jclass result = nullptr;
for (jint i = 0; i < count; i++) {
char* signature = nullptr;
if (agent.get_jvmti()->GetClassSignature(classes[i], &signature, nullptr) != JVMTI_ERROR_NONE || !signature)
continue;
size_t sig_len = strlen(signature);
if (sig_len > 2 && signature[0] == 'L' && signature[sig_len - 1] == ';' &&
internal_name.size() == sig_len - 2 &&
strncmp(signature + 1, internal_name.c_str(), sig_len - 2) == 0) {
result = classes[i];
agent.get_jvmti()->Deallocate((unsigned char*)signature);
break;
}
agent.get_jvmti()->Deallocate((unsigned char*)signature);
}
if (classes) {
agent.get_jvmti()->Deallocate((unsigned char*)classes);
}
if (!result) {
PLOGE << "Failed to find loaded class: " << internal_name;
}
return result;
}
-2
View File
@@ -1,2 +0,0 @@
#include <jni_impl.hpp>
-61
View File
@@ -1,61 +0,0 @@
#include <services.hpp>
#include <jni_impl.hpp>
namespace JuiceAgent::services::Bytecode {
void capture_bytecodes(const EventClassFileLoadHook& e) {
/* =========================
* 1. Capture original bytes
* ========================= */
std::lock_guard<std::mutex> lock(classDataMutex);
if (classToCapture.contains(e.name)) {
if (!classFileDataMap.contains(e.name)) {
ClassFileData data;
data.classname = e.name;
data.bytecode.assign(e.classbytes, e.classbytes + e.class_data_len);
// Experimental: class/classloader/protection_domain references (to be used in future features, e.g. dynamic patching)
data.clazz = e.class_being_redefined;
data.classloader = e.loader;
data.protection_domain = e.protection_domain;
classFileDataMap[e.name] = std::move(data);
classToCapture.erase(e.name);
PLOGI << "Captured class: " << e.name << " (length: " << e.class_data_len << ")";
}
}
}
void patch_bytecodes(const EventClassFileLoadHook& e) {
/* =========================
* 2. Apply patches
* ========================= */
if (pendingRetransform.contains(e.name)) {
auto& bytes = pendingRetransform[e.name];
unsigned char* new_buf = nullptr;
e.jvmti_env->Allocate(bytes.size(), &new_buf);
memcpy(new_buf, bytes.data(), bytes.size());
*e.new_class_data_len = (jint)bytes.size();
*e.new_classbytes = new_buf;
pendingRetransform.erase(e.name);
PLOGI << "Retransformed: " << e.name << " (new length: " << bytes.size() << ")";
}
}
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
);
PLOGI << "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()
);
PLOGI << "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
PLOGI << "Services Manager registered events";
}
void init(const EventPreLoad& event) {
PLOGI << "Initializing services";
// JarLoader
JuiceAgent::services::JarLoader::init();
// Bytecode
JuiceAgent::services::Bytecode::init();
}
void start(const EventLoaded& event) {
PLOGI << "Starting services";
// JarLoader
JuiceAgent::services::JarLoader::start();
// Bytecode
JuiceAgent::services::Bytecode::start();
}
void stop() {
}
}