Compare commits

..
17 Commits
Author SHA1 Message Date
xiaozhou233 16a36ef22a Update: Version 3.4.0 Build 1 2026-05-07 20:41:04 +08:00
xiaozhou233 4305000bf7 Feat: entrypoint_with_env 2026-05-07 15:54:02 +08:00
xiaozhou233 65824934d1 Refactor: Rename libagent -> JuiceAgent 2026-05-07 15:38:03 +08:00
xiaozhou233 992fbd9f8d Refactor: Remove Remapper 2026-05-07 15:36:19 +08:00
xiaozhou233 882c19ad8f Refactor: Move bytecodes_opt -> BytecodeService 2026-05-07 15:34:59 +08:00
xiaozhou233 637640b938 Refactor: Remove unused module files and streamline service management 2026-05-07 15:25:40 +08:00
xiaozhou233 490e4ce2ac Merge branch 'feat/Remapper' 2026-05-07 00:39:26 +08:00
xiaozhou233 30ecc82ca2 Feat: Update Remapper configuration to include JuiceRemapperJarPath 2026-05-06 14:15:11 +08:00
xiaozhou233 bf4ebd0e5b Docs: Update README with new features and installation instructions 2026-05-06 13:33:20 +08:00
xiaozhou233 ec7d221b08 Docs: Add Note 2026-05-06 13:27:51 +08:00
xiaozhou233 e5b054fcfc Docs: README.mc 2026-05-06 13:22:37 +08:00
xiaozhou233 b3ec5b6eb5 Feat: Remapper balcklist/whitelist 2026-05-05 16:17:08 +08:00
xiaozhou233 d5a49a5ce7 Merge branch 'feat/Remapper2' into feat/Remapper
Merge feat/Remapper2
2026-05-05 16:07:41 +08:00
xiaozhou233 90689f306b Feat: remapper blacklist/whitelist 2026-05-05 16:02:46 +08:00
xiaozhou233 1e2e5afd07 Feat: Add Remapper 2026-05-05 13:39:08 +08:00
xiaozhou233 d9d44f029f Fix: TemplateModule 2026-05-05 13:11:38 +08:00
xiaozhou233 cc1c2bff30 BugFix: The path for JuiceAgentNativeLibraryPath could not be resolved 2026-05-04 20:46:15 +08:00
28 changed files with 304 additions and 563 deletions

No files matched your search

+7 -7
View File
@@ -4,10 +4,13 @@ JuiceAgent is an advanced JVMTI-based injection framework designed for runtime J
**Warning**: This project is still experimental and is not recommended for production use. Use it at your own risk. **Warning**: This project is still experimental and is not recommended for production use. Use it at your own risk.
**Note**: This project is designed for a regular JVM. Custom JVMs may not be able to run it.
![License](https://img.shields.io/github/license/xiaozhou233/JuiceAgent) ![License](https://img.shields.io/github/license/xiaozhou233/JuiceAgent)
![Release](https://img.shields.io/github/v/release/xiaozhou233/JuiceAgent) ![Release](https://img.shields.io/github/v/release/xiaozhou233/JuiceAgent)
![GitHub last commit](https://img.shields.io/github/last-commit/xiaozhou233/JuiceAgent) ![GitHub last commit](https://img.shields.io/github/last-commit/xiaozhou233/JuiceAgent)
![GitHub repo size](https://img.shields.io/github/repo-size/xiaozhou233/JuiceAgent) ![GitHub repo size](https://img.shields.io/github/repo-size/xiaozhou233/JuiceAgent)
![Downloads](https://img.shields.io/github/downloads/xiaozhou233/JuiceAgent/total)
![Java](https://img.shields.io/badge/Java-8+-orange) ![Java](https://img.shields.io/badge/Java-8+-orange)
![C++](https://img.shields.io/badge/C++-20-blue) ![C++](https://img.shields.io/badge/C++-20-blue)
@@ -28,6 +31,7 @@ With JuiceAgent, developers can:
- Invoke a specified entry class and method after injection - Invoke a specified entry class and method after injection
- Redefine already loaded classes at runtime - Redefine already loaded classes at runtime
- Retransform bytecode for instrumentation or modification - Retransform bytecode for instrumentation or modification
- Dump classes to disk by -agentpath:libagent.dll flags
- And more... - And more...
**If you have any questions or suggestions, please feel free to open an issue or submit a pull request. =D** **If you have any questions or suggestions, please feel free to open an issue or submit a pull request. =D**
@@ -65,13 +69,10 @@ This project is the native implementation of JuiceAgent-API. See [JuiceAgent.jav
## Quick Start ## Quick Start
### 1. Download Release ### 1. Download Release
Download `libagent.dll` `libinject.dll` `libloader.dll` and `injector.exe` from the [releases](https://github.com/xiaozhou233/JuiceAgent/releases) page. Download `JuiceAgent_vx.x.x_x64.zip` from the [releases](https://github.com/xiaozhou233/JuiceAgent/releases) page.
Download `JuiceAgent-API-x.x.x+build.x.jar` from the [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API/releases) page. Extract the ZIP file to a directory.
Put the downloaded files into the same directory.
- YourDir - YourDir
- JuiceAgent-API-x.x.x+build.x.jar
- libagent.dll - libagent.dll
- libinject.dll - libinject.dll
- libloader.dll - libloader.dll
@@ -79,7 +80,6 @@ Put the downloaded files into the same directory.
### 2. Copy your custom JAR/Dependencies to Directory ### 2. Copy your custom JAR/Dependencies to Directory
- YourDir - YourDir
- JuiceAgent-API-x.x.x+build.x.jar
- libagent.dll - libagent.dll
- libinject.dll - libinject.dll
- libloader.dll - libloader.dll
@@ -112,6 +112,7 @@ JarPath = "./MyCustomJar.jar"
# Entry class to be executed after loading the JAR # Entry class to be executed after loading the JAR
EntryClass = "Example.Main" EntryClass = "Example.Main"
# Entry method to be executed after loading the JAR # Entry method to be executed after loading the JAR
# Method: public static void run()
EntryMethod = "run" EntryMethod = "run"
``` ```
@@ -119,7 +120,6 @@ Save the config file as `config.toml`.
- YourDir - YourDir
- **config.toml** - **config.toml**
- JuiceAgent-API-x.x.x+build.x.jar
- libagent.dll - libagent.dll
- libinject.dll - libinject.dll
- libloader.dll - libloader.dll
+1 -1
View File
@@ -1 +1 @@
VERSION = Version 3.3.2 Build 2 VERSION = Version 3.4.0 Build 1
+4
View File
@@ -16,3 +16,7 @@ EntryMethod = ""
[JuiceAgent.Modules.Dumper] [JuiceAgent.Modules.Dumper]
Enabled = false Enabled = false
DumpDir = "" DumpDir = ""
[JuiceAgent.Modules.Remapper]
Enabled = false
JuiceRemapperJarPath = ""
+3 -2
View File
@@ -127,10 +127,11 @@ public:
namespace Utils { namespace Utils {
inline LoaderConfig get_loader_config(const Config& config) { inline LoaderConfig get_loader_config(const Config& config) {
auto cfg = config.get_config().at("JuiceAgent").at("Loader");
LoaderConfig loader_config = LoaderConfig(); LoaderConfig loader_config = LoaderConfig();
loader_config.JuiceAgentNativeLibraryPath = cfg.at("JuiceAgentNativeLibraryPath").as_string(); loader_config.JuiceAgentNativeLibraryPath = config.get<std::string>("JuiceAgent.Loader.JuiceAgentNativeLibraryPath",
(config.runtime_dir()/"libagent.dll").string(),
true);
loader_config.RuntimeDir = config.runtime_dir().string(); loader_config.RuntimeDir = config.runtime_dir().string();
return loader_config; return loader_config;
@@ -1,9 +1,9 @@
#include <libagent.hpp> #include <JuiceAgent.hpp>
#include <jni_impl.hpp> #include <jni_impl.hpp>
#include <bytecodes_opt.hpp>
#include <event/event_type.hpp> #include <event/event_type.hpp>
#include <event/eventbus.hpp> #include <event/eventbus.hpp>
#include <JuiceAgent/Config.hpp> #include <JuiceAgent/Config.hpp>
#include <services.hpp>
namespace JuiceAgent { namespace JuiceAgent {
// ===== Singleton ===== // ===== Singleton =====
@@ -41,12 +41,8 @@ namespace JuiceAgent {
set_config(cfg); set_config(cfg);
PLOGD << "env: " << env << ", jvmti: " << jvmti; PLOGD << "env: " << env << ", jvmti: " << jvmti;
// Load and Initialize Modules // Register events for services
module_manager.load_all(); JuiceAgent::services::Manager::register_events();
module_manager.init_all();
// Initialize Modules
module_manager.init_all();
// PreLoad Event // PreLoad Event
eventbus.post(EventPreLoad{ eventbus.post(EventPreLoad{
@@ -85,13 +81,6 @@ namespace JuiceAgent {
PLOGE << "Failed to enable event notification: " << result; PLOGE << "Failed to enable event notification: " << result;
} }
// register bytecodes_opt
JuiceAgent::Bytecodes::register_bytecodes();
// Start Modules
module_manager.start_all();
// Loaded Event // Loaded Event
eventbus.post(EventLoaded{ eventbus.post(EventLoaded{
.jvm = jvm, .jvm = jvm,
+7 -2
View File
@@ -18,7 +18,8 @@ void JNICALL ClassFileLoadHook(
} }
auto& agent = JuiceAgent::Agent::instance(); auto& agent = JuiceAgent::Agent::instance();
agent.get_eventbus().post(EventClassFileLoadHook{
EventClassFileLoadHook event{
.jvmti_env = jvmti_env, .jvmti_env = jvmti_env,
.jni_env = jni_env, .jni_env = jni_env,
.class_being_redefined = class_being_redefined, .class_being_redefined = class_being_redefined,
@@ -29,5 +30,9 @@ void JNICALL ClassFileLoadHook(
.classbytes = classbytes, .classbytes = classbytes,
.new_class_data_len = new_class_data_len, .new_class_data_len = new_class_data_len,
.new_classbytes = new_classbytes .new_classbytes = new_classbytes
}); };
agent.get_eventbus().post(event);
agent.get_eventbus().post_mutable(event);
} }
-2
View File
@@ -6,5 +6,3 @@ std::mutex classDataMutex;
std::unordered_map<std::string, std::vector<unsigned char>> pendingRetransform; std::unordered_map<std::string, std::vector<unsigned char>> pendingRetransform;
std::mutex pendingRetransformMutex; std::mutex pendingRetransformMutex;
std::unordered_set<std::string> remapperWhiteList;
+1 -1
View File
@@ -1,5 +1,5 @@
#include <jni_impl.hpp> #include <jni_impl.hpp>
#include <libagent.hpp> #include <JuiceAgent.hpp>
// This function is called by Java to initialize the agent. // This function is called by Java to initialize the agent.
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init
@@ -5,7 +5,6 @@
#include <jvmti.h> #include <jvmti.h>
#include <event/eventbus.hpp> #include <event/eventbus.hpp>
#include <JuiceAgent/Config.hpp> #include <JuiceAgent/Config.hpp>
#include <modules/ModuleManager.hpp>
namespace JuiceAgent { namespace JuiceAgent {
class Agent { class Agent {
@@ -15,7 +14,6 @@ namespace JuiceAgent {
JNIEnv* env; JNIEnv* env;
EventBus eventbus; EventBus eventbus;
JuiceAgent::Config::Config config; JuiceAgent::Config::Config config;
JuiceAgent::Core::Modules::ModuleManager module_manager;
private: private:
Agent() = default; Agent() = default;
-10
View File
@@ -1,10 +0,0 @@
#pragma once
#include "event/event_type.hpp"
namespace JuiceAgent::Bytecodes {
void register_bytecodes();
void capture_bytecodes(const EventClassFileLoadHook& e);
void patch_bytecodes(const EventClassFileLoadHook& e);
}
+1 -1
View File
@@ -3,7 +3,7 @@
#include <jni_impl.hpp> #include <jni_impl.hpp>
// ClassFileLoadHook // ClassFileLoadHook
struct EventClassFileLoadHook { struct EventClassFileLoadHook {
jvmtiEnv* jvmti_env; jvmtiEnv* jvmti_env;
JNIEnv* jni_env; JNIEnv* jni_env;
jclass class_being_redefined; jclass class_being_redefined;
+127 -37
View File
@@ -14,9 +14,17 @@ class EventBus {
public: public:
using Token = std::uint64_t; using Token = std::uint64_t;
// === Readonly ===
template<typename Event> template<typename Event>
using Listener = std::function<void(const Event&)>; using Listener = std::function<void(const Event&)>;
// === Mutable ===
template<typename Event>
using MutableListener = std::function<void(Event&)>;
// =========================
// Subscribe (Readonly)
// =========================
template<typename Event> template<typename Event>
Token subscribe(Listener<Event> listener, int priority = 0) { Token subscribe(Listener<Event> listener, int priority = 0) {
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
@@ -31,40 +39,58 @@ public:
std::move(listener) std::move(listener)
}); });
std::sort(vec.begin(), vec.end(), sort(vec);
[](const auto& a, const auto& b) {
return a.priority > b.priority;
});
return token; 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> template<typename Event>
bool unsubscribe(Token token) { bool unsubscribe(Token token) {
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
auto type = std::type_index(typeid(Event)); bool removed = false;
auto it = listeners_.find(type);
if (it == listeners_.end()) { // readonly
return false; 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);
} }
auto& vec = // mutable
*std::static_pointer_cast<std::vector<Node<Event>>>(it->second); 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);
}
auto oldSize = vec.size(); return removed;
vec.erase(
std::remove_if(vec.begin(), vec.end(),
[token](const Node<Event>& node) {
return node.token == token;
}),
vec.end()
);
return vec.size() != oldSize;
} }
// =========================
// Post (Readonly)
// =========================
template<typename Event> template<typename Event>
void post(const Event& event) { void post(const Event& event) {
std::vector<Node<Event>> copy; std::vector<Node<Event>> copy;
@@ -72,15 +98,10 @@ public:
{ {
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
auto type = std::type_index(typeid(Event)); auto it = listeners_.find(std::type_index(typeid(Event)));
auto it = listeners_.find(type); if (it == listeners_.end()) return;
if (it == listeners_.end()) { copy = *std::static_pointer_cast<std::vector<Node<Event>>>(it->second);
return;
}
copy =
*std::static_pointer_cast<std::vector<Node<Event>>>(it->second);
} }
for (auto& node : copy) { for (auto& node : copy) {
@@ -88,15 +109,41 @@ public:
} }
} }
// =========================
// 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> template<typename Event>
void clear() { void clear() {
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
listeners_.erase(std::type_index(typeid(Event))); listeners_.erase(std::type_index(typeid(Event)));
mutable_listeners_.erase(std::type_index(typeid(Event)));
} }
void clearAll() { void clearAll() {
std::lock_guard<std::mutex> lock(mutex_); std::lock_guard<std::mutex> lock(mutex_);
listeners_.clear(); listeners_.clear();
mutable_listeners_.clear();
} }
private: private:
@@ -107,22 +154,65 @@ private:
Listener<Event> callback; Listener<Event> callback;
}; };
template<typename Event>
struct MutableNode {
Token token;
int priority;
MutableListener<Event> callback;
};
std::mutex mutex_; std::mutex mutex_;
std::atomic<Token> nextToken_ {1}; 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>> 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> template<typename Event>
std::vector<Node<Event>>& getListeners() { std::vector<Node<Event>>& getListeners() {
auto type = std::type_index(typeid(Event)); return getContainer<Event, Node<Event>>(listeners_);
auto it = listeners_.find(type); }
if (it == listeners_.end()) { template<typename Event>
auto ptr = std::make_shared<std::vector<Node<Event>>>(); std::vector<MutableNode<Event>>& getMutableListeners() {
listeners_[type] = ptr; 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 *ptr;
} }
return *std::static_pointer_cast<std::vector<Node<Event>>>(it->second); return *std::static_pointer_cast<std::vector<NodeType>>(it->second);
} }
}; };
-3
View File
@@ -36,6 +36,3 @@ extern std::mutex classDataMutex;
extern std::unordered_map<std::string, std::vector<unsigned char>> pendingRetransform; extern std::unordered_map<std::string, std::vector<unsigned char>> pendingRetransform;
extern std::mutex pendingRetransformMutex; extern std::mutex pendingRetransformMutex;
// Remapper WhiteList
extern std::unordered_set<std::string> remapperWhiteList;
+1 -1
View File
@@ -3,7 +3,7 @@
#include <jni.h> #include <jni.h>
#include <jvmti.h> #include <jvmti.h>
#include <JuiceAgent/Logger.hpp> #include <JuiceAgent/Logger.hpp>
#include <libagent.hpp> #include <JuiceAgent.hpp>
#include <utils.hpp> #include <utils.hpp>
#include <global.hpp> #include <global.hpp>
#include <algorithm> #include <algorithm>
-20
View File
@@ -1,20 +0,0 @@
#pragma once
#include <string>
namespace JuiceAgent::Core::Modules {
class IModule {
public:
virtual ~IModule() = default;
virtual std::string name() const = 0;
virtual bool init() = 0;
virtual bool start() = 0;
virtual void stop() = 0;
virtual bool initialized() const = 0;
virtual bool running() const = 0;
};
}
@@ -1,74 +0,0 @@
#pragma once
#include <modules/IModule.hpp>
namespace JuiceAgent::Core::Modules {
class ModuleBase : public IModule {
public:
virtual ~ModuleBase() = default;
bool init() override {
if (_initialized) {
return true;
}
if (!on_init()) {
return false;
}
_initialized = true;
return true;
}
bool start() override {
if (!_initialized) {
return false;
}
if (_running) {
return true;
}
if (!on_start()) {
return false;
}
_running = true;
return true;
}
void stop() override {
if (!_running) {
return;
}
on_stop();
_running = false;
}
bool initialized() const override {
return _initialized;
}
bool running() const override {
return _running;
}
protected:
virtual bool on_init() {
return true;
}
virtual bool on_start() {
return true;
}
virtual void on_stop() {
}
private:
bool _initialized = false;
bool _running = false;
};
}
@@ -1,27 +0,0 @@
#pragma once
#include <memory>
#include <vector>
#include <string>
#include <modules/IModule.hpp>
namespace JuiceAgent::Core::Modules {
class ModuleManager {
public:
ModuleManager() = default;
~ModuleManager() = default;
void load_all();
bool init_all();
bool start_all();
void stop_all();
IModule* find_module(const std::string& name);
private:
std::vector<std::unique_ptr<IModule>> _modules;
};
}
@@ -1,56 +0,0 @@
#pragma once
#include <vector>
#include <memory>
#include <functional>
#include <string>
#include <modules/IModule.hpp>
namespace JuiceAgent::Core::Modules {
class ModuleRegistry {
public:
using Factory = std::function<std::unique_ptr<IModule>()>;
struct Entry {
std::string name;
Factory factory;
};
static ModuleRegistry& instance() {
static ModuleRegistry inst;
return inst;
}
bool add(const std::string& name, Factory factory) {
for (const auto& item : _entries) {
if (item.name == name) {
return false;
}
}
_entries.push_back({name, std::move(factory)});
return true;
}
const std::vector<Entry>& entries() const {
return _entries;
}
private:
std::vector<Entry> _entries;
};
}
#define JUICEAGENT_REGISTER_MODULE(TYPE, NAME) \
namespace { \
const bool registered_##NAME = \
JuiceAgent::Core::Modules::ModuleRegistry::instance().add( \
#NAME, \
[]() -> std::unique_ptr<JuiceAgent::Core::Modules::IModule> { \
return std::make_unique<TYPE>(); \
} \
); \
}
+37
View File
@@ -0,0 +1,37 @@
#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
+1 -1
View File
@@ -1,6 +1,6 @@
#pragma once #pragma once
#include <libagent.hpp> #include <JuiceAgent.hpp>
inline bool check_env(JuiceAgent::Agent& agent) { inline bool check_env(JuiceAgent::Agent& agent) {
if (agent.get_jvm() == nullptr) { if (agent.get_jvm() == nullptr) {
-133
View File
@@ -1,133 +0,0 @@
#include <modules/ModuleRegistry.hpp>
#include <modules/ModuleBase.hpp>
#include <JuiceAgent/Logger.hpp>
#include <libagent.hpp>
#include <event/eventbus.hpp>
#include <event/event_type.hpp>
#include <filesystem>
#include <fstream>
#include <mutex>
#include <string_view>
namespace JuiceAgent::Core::Modules {
namespace fs = std::filesystem;
struct DumperConfig {
bool enabled = false;
std::string DumpDir;
};
static DumperConfig config;
static JuiceAgent::Agent& agent = JuiceAgent::Agent::instance();
class Dumper : public ModuleBase {
using super = ModuleBase;
public:
std::string name() const override {
return "Dumper";
}
protected:
bool on_init() override {
auto& cfg = agent.get_config();
config.enabled = cfg.get<bool>(
"JuiceAgent.Modules.Dumper.Enabled",
false
);
config.DumpDir = cfg.get<std::string>(
"JuiceAgent.Modules.Dumper.DumpDir",
"./dump",
true
);
return true;
}
bool on_start() override {
if (!config.enabled) {
return true;
}
auto& bus = agent.get_eventbus();
_classFileToken = bus.subscribe<EventClassFileLoadHook>(
[this](const auto& e) {
on_class_file_load_hook(e);
}
);
return true;
}
void on_stop() override {
if (!config.enabled) {
return;
}
auto& bus = agent.get_eventbus();
if (_classFileToken != 0) {
bus.unsubscribe<EventClassFileLoadHook>(_classFileToken);
_classFileToken = 0;
}
}
private:
void on_class_file_load_hook(const EventClassFileLoadHook& event) {
if (!event.classbytes || event.class_data_len <= 0) {
return;
}
std::string_view name = event.name ? event.name : "";
if (name.empty()) {
return;
}
try {
fs::path output = build_class_path(name);
{
std::lock_guard<std::mutex> lock(_mutex);
fs::create_directories(output.parent_path());
}
std::ofstream file(output, std::ios::binary);
if (!file.is_open()) {
PLOGW << "Dumper: Failed to open file: " << output.string();
return;
}
file.write(
reinterpret_cast<const char*>(event.classbytes),
static_cast<std::streamsize>(event.class_data_len)
);
} catch (const std::exception& e) {
PLOGE << "Dumper: " << e.what();
}
}
fs::path build_class_path(std::string_view class_name) {
fs::path path(config.DumpDir);
path /= fs::path(class_name);
path += ".class";
return path;
}
private:
EventBus::Token _classFileToken = 0;
std::mutex _mutex;
};
}
JUICEAGENT_REGISTER_MODULE(
JuiceAgent::Core::Modules::Dumper,
Dumper
)
-64
View File
@@ -1,64 +0,0 @@
#include <modules/ModuleManager.hpp>
#include <modules/ModuleRegistry.hpp>
#include <JuiceAgent/Logger.hpp>
namespace JuiceAgent::Core::Modules {
void ModuleManager::load_all() {
for (const auto& entry : ModuleRegistry::instance().entries()) {
auto module = entry.factory();
if (!module) {
PLOGE << "Failed to create module: " << entry.name;
continue;
}
PLOGI << "Register module: " << module->name();
_modules.push_back(std::move(module));
}
}
bool ModuleManager::init_all() {
for (auto& module : _modules) {
PLOGI << "Init module: " << module->name();
if (!module->init()) {
PLOGE << "Failed to init module: " << module->name();
continue;
}
}
return true;
}
bool ModuleManager::start_all() {
for (auto& module : _modules) {
PLOGI << "Start module: " << module->name();
if (!module->start()) {
PLOGE << "Failed to start module: " << module->name();
continue;
}
}
return true;
}
void ModuleManager::stop_all() {
for (auto it = _modules.rbegin(); it != _modules.rend(); ++it) {
PLOGI << "Stop module: " << (*it)->name();
(*it)->stop();
}
}
IModule* ModuleManager::find_module(const std::string& name) {
for (auto& module : _modules) {
if (module->name() == name) {
return module.get();
}
}
return nullptr;
}
}
-28
View File
@@ -1,28 +0,0 @@
#include <modules/ModuleBase.hpp>
#include <JuiceAgent/Logger.hpp>
namespace JuiceAgent::Core::Modules {
class TemplateModule : public ModuleBase {
public:
std::string name() const override {
return "Template";
}
protected:
bool on_init() override {
// load config / prepare resource
return true;
}
bool on_start() override {
// start module
return true;
}
void on_stop() override {
// stop module
}
};
}
@@ -1,16 +1,8 @@
#include <bytecodes_opt.hpp> #include <services.hpp>
#include <jni_impl.hpp> #include <jni_impl.hpp>
#include <event/event_type.hpp>
namespace JuiceAgent::Bytecodes { namespace JuiceAgent::services::Bytecode {
void register_bytecodes() { void capture_bytecodes(const EventClassFileLoadHook& e) {
auto& agent = JuiceAgent::Agent::instance();
agent.get_eventbus().subscribe<EventClassFileLoadHook>(capture_bytecodes);
agent.get_eventbus().subscribe<EventClassFileLoadHook>(patch_bytecodes);
}
void capture_bytecodes(const EventClassFileLoadHook& e) {
/* ========================= /* =========================
* 1. Capture original bytes * 1. Capture original bytes
* ========================= */ * ========================= */
@@ -56,4 +48,14 @@ namespace JuiceAgent::Bytecodes {
PLOGI << "Retransformed: " << e.name << " (new length: " << bytes.size() << ")"; 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,37 +1,12 @@
#include <modules/ModuleRegistry.hpp> #include <services.hpp>
#include <modules/ModuleBase.hpp>
#include <JuiceAgent/Logger.hpp>
#include <libagent.hpp>
#include <JuiceAgent/Utils.hpp>
namespace JuiceAgent::Core::Modules { namespace JuiceAgent::services::JarLoader {
static JarLoaderConfig config;
struct JarLoaderConfig { static const char* MODULE_CLASS = "cn/xiaozhou233/juiceagent/api/modules/JarLoader";
bool enabled = true; static const char* MODULE_METHOD = "loadJar";
std::string injection_dir;
std::string jar_path;
std::string entry_class;
std::string entry_method;
};
static JarLoaderConfig config; void init() {
static JuiceAgent::Agent& agent = JuiceAgent::Agent::instance();
static const char* MODULE_CLASS =
"cn/xiaozhou233/juiceagent/api/modules/JarLoader";
static const char* MODULE_METHOD = "loadJar";
class JarLoaderModule : public ModuleBase {
using super = ModuleBase;
public:
std::string name() const override {
return "JarLoader";
}
protected:
bool on_init() override {
auto& cfg = agent.get_config(); auto& cfg = agent.get_config();
config.enabled = cfg.get<bool>( config.enabled = cfg.get<bool>(
@@ -63,13 +38,12 @@ protected:
false false
); );
PLOGI << "JarLoader init"; PLOGI << "JarLoaderService initialized";
return true;
} }
bool on_start() override { void start() {
if (!config.enabled) { if (!config.enabled) {
return true; return;
} }
JuiceAgent::Utils::Serializer ser; JuiceAgent::Utils::Serializer ser;
@@ -89,17 +63,6 @@ protected:
); );
PLOGI << "JarLoader start"; PLOGI << "JarLoader start";
return true; return;
} }
void on_stop() override {
PLOGI << "JarLoader stop";
}
};
} }
JUICEAGENT_REGISTER_MODULE(
JuiceAgent::Core::Modules::JarLoaderModule,
JarLoader
)
+38
View File
@@ -0,0 +1,38 @@
#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() {
}
}
+48 -18
View File
@@ -50,9 +50,8 @@ bool invoke_juiceagent_init(JNIEnv* env, const LoaderConfig& config) {
return true; return true;
} }
// Entrypoint function for loader static void init(const char* runtime_dir, JNIEnv * env, jvmtiEnv* jvmti) {
void entrypoint(const char* runtime_dir) { if (!runtime_dir) {
if (!runtime_dir) {
PLOGW << "runtime_dir is null, using empty path"; PLOGW << "runtime_dir is null, using empty path";
} }
@@ -89,21 +88,6 @@ void entrypoint(const char* runtime_dir) {
PLOGD << "JuiceAgent-API size: " << JuiceAgent::Resource::juiceagent_api_bytes_len; PLOGD << "JuiceAgent-API size: " << JuiceAgent::Resource::juiceagent_api_bytes_len;
PLOGD << "JuiceAgent-API SHA256: " << JuiceAgent::Resource::juiceagent_api_bytes_sha256; PLOGD << "JuiceAgent-API SHA256: " << JuiceAgent::Resource::juiceagent_api_bytes_sha256;
// Attach to JVM
JuiceAgent::Loader::JvmManager::Jvm jvm;
if (!jvm.attach()) {
PLOGE << "Attach to JVM failed";
return;
}
JNIEnv* env = jvm.get_env();
auto* jvmti = jvm.get_jvmti();
if (!env || !jvmti) {
PLOGE << "JNIEnv or JVMTI is null";
return;
}
// Inject JuiceAgent jar into system class loader // Inject JuiceAgent jar into system class loader
jint status = jvmti->AddToSystemClassLoaderSearch(juiceagent_api_path.c_str()); jint status = jvmti->AddToSystemClassLoaderSearch(juiceagent_api_path.c_str());
if (status != JNI_OK) { if (status != JNI_OK) {
@@ -119,4 +103,50 @@ void entrypoint(const char* runtime_dir) {
} }
} }
// Entrypoint function for loader
void entrypoint(const char* runtime_dir) {
// Attach to JVM
JuiceAgent::Loader::JvmManager::Jvm jvm;
if (!jvm.attach()) {
PLOGE << "Attach to JVM failed";
return;
}
JNIEnv* env = jvm.get_env();
auto* jvmti = jvm.get_jvmti();
if (!env || !jvmti) {
PLOGE << "JNIEnv or JVMTI is null";
return;
}
// Init JuiceAgent
init(runtime_dir, env, jvmti);
}
void entrypoint_with_env(const char* runtime_dir, JNIEnv* env) {
JavaVM* jvm = nullptr;
jvmtiEnv* jvmti = nullptr;
env->GetJavaVM(&jvm);
if (!jvm) {
PLOGE << "Failed to get JavaVM";
return;
}
jint result = jvm->GetEnv(
reinterpret_cast<void**>(&jvmti),
JVMTI_VERSION_1_2
);
if (result != JNI_OK || !jvmti) {
PLOGE << "Failed to get JVMTI environment";
return;
}
PLOGI << "Successfully acquired JVMTI";
init(runtime_dir, env, jvmti);
}
} // namespace JuiceAgent::Loader } // namespace JuiceAgent::Loader
+1
View File
@@ -9,6 +9,7 @@
namespace JuiceAgent::Loader namespace JuiceAgent::Loader
{ {
void entrypoint(const char* runtime_dir); void entrypoint(const char* runtime_dir);
void entrypoint_with_env(const char* runtime_dir, JNIEnv* env);
bool invoke_juiceagent_init(JNIEnv* env, const LoaderConfig& info); bool invoke_juiceagent_init(JNIEnv* env, const LoaderConfig& info);
} // namespace JuiceAgent::Loader } // namespace JuiceAgent::Loader