Compare commits

...
13 Commits
15 changed files with 386 additions and 2384 deletions

No files matched your search

+108 -66
View File
@@ -1,64 +1,135 @@
# JuiceAgent # JuiceAgent
[English](https://github.com/xiaozhou233/JuiceAgent/blob/main/README.md) | [中文](https://github.com/xiaozhou233/JuiceAgent/blob/main/README_zh.md)
JuiceAgent is a JVMTI-based injection library for loading external JARs and transforming Java bytecode, even when `DisableAttachMechanism` is enabled. JuiceAgent is an advanced JVMTI-based injection framework designed for runtime JAR loading, bytecode transformation, and runtime JVM instrumentation, even when DisableAttachMechanism is enabled.
**Notice:** Currently, only **Windows** is supported. **Linux** support may be added in the future. **Warning**: This project is still experimental and is not recommended for production use. Use it at your own risk.
**Notice:** The current repository version is **Version 3.3 Build 1**. ![License](https://img.shields.io/github/license/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 repo size](https://img.shields.io/github/repo-size/xiaozhou233/JuiceAgent)
**Warning:** This project is still experimental and is not recommended for production use. Use it at your own risk. ![Java](https://img.shields.io/badge/Java-8+-orange)
![C++](https://img.shields.io/badge/C++-20-blue)
![JNI](https://img.shields.io/badge/JNI-Native-green)
![CMake](https://img.shields.io/badge/CMake-Build-red)
![Platform](https://img.shields.io/badge/Platform-Windows-lightgrey)
## Summary ![JVMTI](https://img.shields.io/badge/JVMTI-Agent-success)
JuiceAgent is a JVMTI-native injection framework that injects native code into a target JVM to dynamically load external JARs and perform bytecode redefinition or retransformation without requiring a `javaagent`. It can still work when `DisableAttachMechanism=true`. ![Injection](https://img.shields.io/badge/Runtime-Injection-blueviolet)
![Bytecode](https://img.shields.io/badge/Bytecode-Transform-blue)
![Attach](https://img.shields.io/badge/DisableAttach-Bypass-important)
## Introduction
JuiceAgent is a JVMTI-native injection framework for loading external JARs and redefining or retransformation of Java classes in a target JVM without requiring -javaagent startup arguments or attach javaagent. It also works when DisableAttachMechanism=true.
With JuiceAgent, developers can:
- Dynamically load external JARs into a running JVM process
- Invoke a specified entry class and method after injection
- Redefine already loaded classes at runtime
- Retransform bytecode for instrumentation or modification
- And more...
**If you have any questions or suggestions, please feel free to open an issue or submit a pull request. =D**
## Index
- [JuiceAgent](#juiceagent)
- [Introduction](#introduction)
- [Index](#index)
- [Features](#features)
- [Quick Start](#quick-start)
- [1. Download Release](#1-download-release)
- [2. Copy your custom JAR/Dependencies to Directory](#2-copy-your-custom-jardependencies-to-directory)
- [3. Write Config](#3-write-config)
- [4. Run the Injector](#4-run-the-injector)
- [Method A: Use `injector.exe`](#method-a-use-injectorexe)
- [Method B: Use JNI to call `inject`](#method-b-use-jni-to-call-inject)
- [5. Done](#5-done)
- [How To Build](#how-to-build)
- [Requirements](#requirements)
- [Build with CMake Presets](#build-with-cmake-presets)
- [Manual Build](#manual-build)
- [Full Disclaimer](#full-disclaimer)
- [Acknowledgements](#acknowledgements)
## Features ## Features
This project is the native implementation of JuiceAgent-API. For the API definition, see [JuiceAgent.java](https://github.com/xiaozhou233/JuiceAgent-API/blob/master/src/main/java/cn/xiaozhou233/juiceagent/api/JuiceAgent.java). This project is the native implementation of JuiceAgent-API. See [JuiceAgent.java](https://github.com/xiaozhou233/JuiceAgent-API/blob/master/src/main/java/cn/xiaozhou233/juiceagent/api/JuiceAgent.java) for the API definition.
- `addToBootstrapClassLoaderSearch` - Load JARs into the Bootstrap or System ClassLoader
- `addToSystemClassLoaderSearch` - Define classes dynamically
- `addToClassLoader` - Redefine classes by name or class reference
- `defineClass` - Retransform classes by name or class reference
- `redefineClass(ByName)` - Get all loaded classes
- `retransformClass(ByName)` - Find classes by name
- `getLoadedClasses` - Get class bytecode by name or class reference
- `getClassByName`
- `getClassBytes(ByName)`
## How To Use ## Quick Start
### 1. Download Release
Download `libagent.dll` `libinject.dll` `libloader.dll` and `injector.exe` from the [releases](https://github.com/xiaozhou233/JuiceAgent/releases) page.
### 1. Download Files Download `JuiceAgent-API-x.x.x+build.x.jar` from the [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API/releases) page.
Download the following files from [Releases](https://github.com/xiaozhou233/JuiceAgent/releases) and place them in `YourDir`:
- `libagent.dll` Put the downloaded files into the same directory.
- `libinject.dll` - YourDir
- `libloader.dll` - JuiceAgent-API-x.x.x+build.x.jar
- `injector.exe` - libagent.dll
- libinject.dll
- libloader.dll
- injector.exe
Download `JuiceAgent-API-X.X.X+build.X.jar` from [JuiceAgent-API Releases](https://github.com/xiaozhou233/JuiceAgent-API/releases) and place it in `YourDir`. ### 2. Copy your custom JAR/Dependencies to Directory
- YourDir
- JuiceAgent-API-x.x.x+build.x.jar
- libagent.dll
- libinject.dll
- libloader.dll
- injector.exe
- **MyCustomJar.jar**
- **injection**
- **Dependencies1.jar**
- **Dependencies2.jar**
### 2. Write the Config File ### 3. Write Config
Create a file named `config.toml` in `YourDir`.
```toml ```toml
[JuiceAgent] [JuiceAgent]
Version = 1 Version = 1
[JuiceAgent.Loader] [JuiceAgent.Loader]
JuiceAgentAPIJarPath = "" # Path to JuiceAgent-API-x.x.x+build.x.jar
JuiceAgentAPIJarPath = "./JuiceAgent-API-x.x.x+build.x.jar"
# Path to libagent.dll, default is "./libagent.dll"
JuiceAgentNativeLibraryPath = "" JuiceAgentNativeLibraryPath = ""
[JuiceAgent.Modules] [JuiceAgent.Modules]
[JuiceAgent.Modules.JarLoader] [JuiceAgent.Modules.JarLoader]
Enabled = true Enabled = true
InjectionDir = "" # Path to the Injection JAR files to be loaded
JarPath = "" InjectionDir = "./injection"
EntryClass = "" # Path to the JAR file to be loaded
EntryMethod = "" JarPath = "./MyCustomJar.jar"
# Entry class to be executed after loading the JAR
EntryClass = "Example.Main"
# Entry method to be executed after loading the JAR
EntryMethod = "run"
``` ```
### 3. Run the Injector Save the config file as `config.toml`.
- YourDir
- **config.toml**
- JuiceAgent-API-x.x.x+build.x.jar
- libagent.dll
- libinject.dll
- libloader.dll
- injector.exe
- MyCustomJar.jar
- injection
- Dependencies1.jar
- Dependencies2.jar
### 4. Run the Injector
#### Method A: Use `injector.exe` #### Method A: Use `injector.exe`
Run `injector.exe` from `YourDir`. Run `injector.exe` from `YourDir`.
@@ -71,40 +142,11 @@ Input PID:
Enter the PID of the target JVM process and press Enter. Enter the PID of the target JVM process and press Enter.
#### Method B: Use JNI to call `inject` #### Method B: Use JNI to call `inject`
Create `cn/xiaozhou233/juiceagent/injector/InjectorNative.java` in your project:
```java See [Documents](https://github.com/xiaozhou233/JuiceAgent/blob/main/docs/Inject.md) for details.
package cn.xiaozhou233.juiceagent.injector;
public class InjectorNative { ### 5. Done
/* The target JVM will load the specified JAR and execute the specified entry class and method.
* @param pid target process id
* @param path injection DLL path
*/
public native boolean inject(int pid, String path);
/*
* @param pid target process id
* @param path injection DLL path
* @param configDir directory containing config.toml
*/
public native boolean inject(int pid, String path, String configDir);
}
```
Example:
```java
import cn.xiaozhou233.juiceagent.injector.InjectorNative;
System.load("<path-to-libinject>");
InjectorNative injectorNative = new InjectorNative();
injectorNative.inject(<pid>, "<path-to-libloader>", "<path-to-config-directory>");
```
### 4. Done
If the injection succeeds, the target process will load `Entry.jar` (or the file specified by `EntryJarPath`) and invoke `EntryClass.EntryMethod` (default: `com.example.Entry.start`).
## How To Build ## How To Build
@@ -142,5 +184,5 @@ This project is intended for learning and research in controlled environments on
## Acknowledgements ## Acknowledgements
- [ReflectiveDLLInjection](https://github.com/stephenfewer/ReflectiveDLLInjection) - DLL injection implementation - [ReflectiveDLLInjection](https://github.com/stephenfewer/ReflectiveDLLInjection) - DLL injection implementation
- [plog](https://github.com/SergiusTheBest/plog) - Portable, simple, and extensible C++ logging library - [plog](https://github.com/SergiusTheBest/plog) - Portable, simple, and extensible C++ logging library
- [tinytoml](https://github.com/mayah/tinytoml) - Header-only C++11 TOML parser - [toml11](https://github.com/ToruNiina/toml11) - TOML for Modern C++
- [eventpp](https://github.com/wqking/eventpp) - C++ library for event dispatchers and callback lists - [eventpp](https://github.com/wqking/eventpp) - C++ library for event dispatchers and callback lists
-146
View File
@@ -1,146 +0,0 @@
# JuiceAgent
[English](https://github.com/xiaozhou233/JuiceAgent/blob/main/README.md) | [中文](https://github.com/xiaozhou233/JuiceAgent/blob/main/README_zh.md)
JuiceAgent 是一个基于 JVMTI 的注入库,用于加载外部 JAR 并对 Java 字节码进行转换;即使启用了 `DisableAttachMechanism` 也可以使用。
**注意:** 当前仅支持 **Windows**,未来可能会支持 **Linux**。
**注意:** 当前仓库版本为 **Version 3.3 Build 1**。
**警告:** 本项目仍处于实验阶段,不建议在生产环境中使用。使用风险请自行承担。
## 简介
JuiceAgent 是一个基于 JVMTI 的原生注入框架。它通过向目标 JVM 注入原生代码,动态加载外部 JAR,并执行字节码重定义或重转换,而不需要 `javaagent`。在 `DisableAttachMechanism=true` 的情况下依然可以工作。
## 功能特性
本项目是 JuiceAgent-API 的原生实现。API 定义可参考 [JuiceAgent.java](https://github.com/xiaozhou233/JuiceAgent-API/blob/master/src/main/java/cn/xiaozhou233/juiceagent/api/JuiceAgent.java)。
- `addToBootstrapClassLoaderSearch`
- `addToSystemClassLoaderSearch`
- `addToClassLoader`
- `defineClass`
- `redefineClass(ByName)`
- `retransformClass(ByName)`
- `getLoadedClasses`
- `getClassByName`
- `getClassBytes(ByName)`
## 使用方法
### 1. 下载文件
从 [Releases](https://github.com/xiaozhou233/JuiceAgent/releases) 下载以下文件,并放到 `YourDir` 中:
- `libagent.dll`
- `libinject.dll`
- `libloader.dll`
- `injector.exe`
从 [JuiceAgent-API Releases](https://github.com/xiaozhou233/JuiceAgent-API/releases) 下载 `JuiceAgent-API-X.X.X+build.X.jar`,并放到 `YourDir` 中。
### 2. 编写配置文件
在 `YourDir` 下创建 `config.toml`:
```toml
[JuiceAgent]
Version = 1
[JuiceAgent.Loader]
JuiceAgentAPIJarPath = ""
JuiceAgentNativeLibraryPath = ""
[JuiceAgent.Modules]
[JuiceAgent.Modules.JarLoader]
Enabled = true
InjectionDir = ""
JarPath = ""
EntryClass = ""
EntryMethod = ""
```
### 3. 执行注入
#### 方法 A:使用 `injector.exe`
在 `YourDir` 中运行 `injector.exe`。
```text
<jps 输出>
Input PID:
```
输入目标 JVM 进程的 PID 后按回车。
#### 方法 B:通过 JNI 调用 `inject`
在你的项目中创建 `cn/xiaozhou233/juiceagent/injector/InjectorNative.java`:
```java
package cn.xiaozhou233.juiceagent.injector;
public class InjectorNative {
/*
* @param pid target process id
* @param path injection DLL path
*/
public native boolean inject(int pid, String path);
/*
* @param pid target process id
* @param path injection DLL path
* @param configDir 包含 config.toml 的目录
*/
public native boolean inject(int pid, String path, String configDir);
}
```
调用示例:
```java
import cn.xiaozhou233.juiceagent.injector.InjectorNative;
System.load("<path-to-libinject>");
InjectorNative injectorNative = new InjectorNative();
injectorNative.inject(<pid>, "<path-to-libloader>", "<path-to-config-directory>");
```
### 4. 完成
如果注入成功,目标进程会加载 `Entry.jar`(或 `EntryJarPath` 指定的文件),并调用 `EntryClass.EntryMethod`(默认值为 `com.example.Entry.start`)。
## 构建方法
### 环境要求
- Java 8+
- MinGW
- CMake 3.15+
- Ninja
### 使用 CMake Presets 构建
```powershell
git clone https://github.com/xiaozhou233/JuiceAgent.git
cd JuiceAgent
cmake --preset ninja-release
cmake --build build
```
### 手动构建
```powershell
git clone https://github.com/xiaozhou233/JuiceAgent.git
cd JuiceAgent
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
cmake --build build
```
生成的二进制文件位于 `build/bin`。
`JuiceAgent-API.jar` 可以在 [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API) 项目中构建,或直接从其发布页下载。
## 完整免责声明
本项目仅用于受控环境中的学习与研究。对于任何未经授权的使用、修改、破解,或违反适用协议与法律的行为所产生的后果,作者概不负责。使用者应自行确保其行为合法合规,并承担全部责任。
## 致谢
- [ReflectiveDLLInjection](https://github.com/stephenfewer/ReflectiveDLLInjection) - DLL 注入实现
- [plog](https://github.com/SergiusTheBest/plog) - 轻量、可扩展的 C++ 日志库
- [tinytoml](https://github.com/mayah/tinytoml) - Header-only C++11 TOML 解析库
- [eventpp](https://github.com/wqking/eventpp) - 用于事件分发和回调列表的 C++ 库
+3
View File
@@ -17,3 +17,6 @@
## 2026-04-19 ## 2026-04-19
- [x] 在 `JuiceAgent/Utils.hpp`做序列化操作 - [x] 在 `JuiceAgent/Utils.hpp`做序列化操作
- [x] 统一调用 module的Java实现 - [x] 统一调用 module的Java实现
## 2026-04-20
- [x] 修改文档
+1 -1
View File
@@ -1 +1 @@
VERSION = Version 3.1 Build 3 VERSION = Version 3.3 Build 2
+44
View File
@@ -0,0 +1,44 @@
# Inject Method
## Method A: Use `injector.exe`
Run `injector.exe` from `YourDir`.
```text
<jps output>
Input PID:
```
Enter the PID of the target JVM process and press Enter.
## Method B: Use JNI to call `inject`
Create `cn/xiaozhou233/juiceagent/injector/InjectorNative.java` in your project:
```java
package cn.xiaozhou233.juiceagent.injector;
public class InjectorNative {
/*
* @param pid target process id
* @param path injection DLL path
*/
public native boolean inject(int pid, String path);
/*
* @param pid target process id
* @param path injection DLL path
* @param configDir directory containing config.toml
*/
public native boolean inject(int pid, String path, String configDir);
}
```
Example:
```java
import cn.xiaozhou233.juiceagent.injector.InjectorNative;
System.load("<path-to-libinject>");
InjectorNative injectorNative = new InjectorNative();
injectorNative.inject(<pid>, "<path-to-libloader>", "<path-to-config-directory>");
```
+4 -3
View File
@@ -3,15 +3,16 @@
#include <plog/Log.h> #include <plog/Log.h>
#include <plog/Init.h> #include <plog/Init.h>
#include <plog/Formatters/TxtFormatter.h> #include <plog/Formatters/TxtFormatter.h>
#include <plog/Appenders/ConsoleAppender.h> #include <plog/Appenders/ColorConsoleAppender.h>
#include <plog/Appenders/DebugOutputAppender.h> #include <plog/Appenders/DebugOutputAppender.h>
#include <plog/Appenders/RollingFileAppender.h>
inline void InitLogger() inline void InitLogger()
{ {
static plog::ConsoleAppender<plog::TxtFormatter> consoleAppender; static plog::ColorConsoleAppender<plog::TxtFormatter> colorConsoleAppender;
static plog::DebugOutputAppender<plog::TxtFormatter> debugAppender; static plog::DebugOutputAppender<plog::TxtFormatter> debugAppender;
plog::init(plog::debug, &consoleAppender).addAppender(&debugAppender); plog::init(plog::debug, &colorConsoleAppender).addAppender(&debugAppender);
PLOG_INFO << "Logger initialized: Console + Debug Output"; PLOG_INFO << "Logger initialized: Console + Debug Output";
} }
File diff suppressed because it is too large. Load diff
-23
View File
@@ -1,23 +0,0 @@
Copyright (c) 2014, MAYAH
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright notice, this
list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright notice,
this list of conditions and the following disclaimer in the documentation
and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
@@ -12,7 +12,7 @@ public:
ModuleManager() = default; ModuleManager() = default;
~ModuleManager() = default; ~ModuleManager() = default;
void register_module(std::unique_ptr<IModule> module); void load_all();
bool init_all(); bool init_all();
bool start_all(); bool start_all();
@@ -0,0 +1,56 @@
#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>(); \
} \
); \
}
-25
View File
@@ -1,25 +0,0 @@
#pragma once
#include <modules/IModule.hpp>
namespace JuiceAgent::Core::Modules {
class JarLoaderModule : public IModule {
public:
JarLoaderModule() = default;
~JarLoaderModule() override = default;
std::string name() const override {
return "JarLoader";
}
bool init() override;
bool start() override;
void stop() override;
private:
bool _initialized = false;
bool _running = false;
};
}
+3 -3
View File
@@ -4,7 +4,6 @@
#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 <modules/Modules.hpp>
namespace JuiceAgent { namespace JuiceAgent {
// ===== Singleton ===== // ===== Singleton =====
@@ -42,8 +41,9 @@ namespace JuiceAgent {
set_config(cfg); set_config(cfg);
PLOGD << "env: " << env << ", jvmti: " << jvmti; PLOGD << "env: " << env << ", jvmti: " << jvmti;
// Register Modules // Load and Initialize Modules
module_manager.register_module(std::make_unique<JuiceAgent::Core::Modules::JarLoaderModule>()); module_manager.load_all();
module_manager.init_all();
// Initialize Modules // Initialize Modules
module_manager.init_all(); module_manager.init_all();
+92 -62
View File
@@ -1,87 +1,117 @@
#include <modules/Modules.hpp> #include <modules/ModuleRegistry.hpp>
#include <JuiceAgent/Logger.hpp> #include <JuiceAgent/Logger.hpp>
#include <libagent.hpp> #include <libagent.hpp>
#include <JuiceAgent/Utils.hpp> #include <JuiceAgent/Utils.hpp>
namespace JuiceAgent::Core::Modules { namespace JuiceAgent::Core::Modules {
struct _Config { struct JarLoaderConfig {
bool Enabled = true; bool enabled = true;
std::string InjectionDir; std::string injection_dir;
std::string JarPath; std::string jar_path;
std::string EntryClass; std::string entry_class;
std::string EntryMethod; std::string entry_method;
} Config; };
static JarLoaderConfig config;
static JuiceAgent::Agent& agent = JuiceAgent::Agent::instance(); static JuiceAgent::Agent& agent = JuiceAgent::Agent::instance();
static const char* MODULE_CLASS = "cn/xiaozhou233/juiceagent/api/modules/JarLoader"; static const char* MODULE_CLASS = "cn/xiaozhou233/juiceagent/api/modules/JarLoader";
static const char* MODULE_METHOD = "loadJar"; static const char* MODULE_METHOD = "loadJar";
bool JarLoaderModule::init() { class JarLoaderModule : public IModule {
if (_initialized) return true; public:
std::string name() const override {
PLOGI << "JarLoader init"; return "JarLoader";
JuiceAgent::Config::Config& cfg = agent.get_config();
Config.Enabled = cfg.get<bool>("JuiceAgent.Modules.JarLoader.Enabled", false);
Config.InjectionDir = cfg.get<std::string>("JuiceAgent.Modules.JarLoader.InjectionDir", (agent.get_config().runtime_dir() / "injection").string(), true);
Config.JarPath = cfg.get<std::string>("JuiceAgent.Modules.JarLoader.JarPath", "./Entry.jar", true);
Config.EntryClass = cfg.get<std::string>("JuiceAgent.Modules.JarLoader.EntryClass", "Example.Main", false);
Config.EntryMethod = cfg.get<std::string>("JuiceAgent.Modules.JarLoader.EntryMethod", "start", false);
PLOGD << ">>> JarLoader Config <<<";
PLOGD << "Enabled: " << Config.Enabled;
PLOGD << "InjectionDir: " << Config.InjectionDir;
PLOGD << "JarPath: " << Config.JarPath;
PLOGD << "EntryClass: " << Config.EntryClass;
PLOGD << "EntryMethod: " << Config.EntryMethod;
PLOGD << ">>> JarLoader Config <<<";
_initialized = true;
return true;
}
bool JarLoaderModule::start() {
if (!_initialized) return false;
if (_running) return true;
PLOGI << "JarLoader start";
if (!Config.Enabled) {
PLOGI << "JarLoader is disabled";
return false;
} }
if (Config.InjectionDir.empty() || Config.JarPath.empty() || Config.EntryClass.empty() || Config.EntryMethod.empty()) { bool init() override {
PLOGE << "JarLoader config is invalid"; if (_initialized) {
return false; return true;
}
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 << "JarLoader init";
_initialized = true;
return true;
} }
JuiceAgent::Utils::Serializer ser; bool start() override {
if (!_initialized) {
return false;
}
ser.add_kv("InjectionDir", Config.InjectionDir); if (_running || !config.enabled) {
ser.add_kv("JarPath", Config.JarPath); return true;
ser.add_kv("EntryClass", Config.EntryClass); }
ser.add_kv("EntryMethod", Config.EntryMethod);
std::string serialized = ser.serialize(); 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);
PLOGD << "Serialized config: " << serialized; auto data = ser.serialize();
JNIEnv* env = agent.get_env(); JuiceAgent::Utils::call_java_impl(
JuiceAgent::Utils::call_java_impl(env, MODULE_CLASS, MODULE_METHOD, serialized.c_str()); agent.get_env(),
MODULE_CLASS,
MODULE_METHOD,
data.c_str()
);
PLOGI << "JarLoader is running"; PLOGI << "JarLoader start";
_running = true; _running = true;
return true; return true;
} }
void JarLoaderModule::stop() { void stop() override {
if (!_running) return; if (!_running) {
return;
}
PLOGI << "JarLoader stop"; PLOGI << "JarLoader stop";
_running = false; _running = false;
} }
private:
bool _initialized = false;
bool _running = false;
};
} }
JUICEAGENT_REGISTER_MODULE(
JuiceAgent::Core::Modules::JarLoaderModule,
JarLoader
)
+16 -4
View File
@@ -1,13 +1,21 @@
#include <modules/ModuleManager.hpp> #include <modules/ModuleManager.hpp>
#include <modules/ModuleRegistry.hpp>
#include <JuiceAgent/Logger.hpp> #include <JuiceAgent/Logger.hpp>
namespace JuiceAgent::Core::Modules { namespace JuiceAgent::Core::Modules {
void ModuleManager::register_module(std::unique_ptr<IModule> module) { void ModuleManager::load_all() {
if (!module) return; for (const auto& entry : ModuleRegistry::instance().entries()) {
auto module = entry.factory();
PLOGI << "Register module: " << module->name(); if (!module) {
_modules.push_back(std::move(module)); PLOGE << "Failed to create module: " << entry.name;
continue;
}
PLOGI << "Register module: " << module->name();
_modules.push_back(std::move(module));
}
} }
bool ModuleManager::init_all() { bool ModuleManager::init_all() {
@@ -19,6 +27,7 @@ bool ModuleManager::init_all() {
return false; return false;
} }
} }
return true; return true;
} }
@@ -31,11 +40,13 @@ bool ModuleManager::start_all() {
return false; return false;
} }
} }
return true; return true;
} }
void ModuleManager::stop_all() { void ModuleManager::stop_all() {
for (auto it = _modules.rbegin(); it != _modules.rend(); ++it) { for (auto it = _modules.rbegin(); it != _modules.rend(); ++it) {
PLOGI << "Stop module: " << (*it)->name();
(*it)->stop(); (*it)->stop();
} }
} }
@@ -46,6 +57,7 @@ IModule* ModuleManager::find_module(const std::string& name) {
return module.get(); return module.get();
} }
} }
return nullptr; return nullptr;
} }
+58
View File
@@ -0,0 +1,58 @@
#include <modules/ModuleRegistry.hpp>
#include <JuiceAgent/Logger.hpp>
namespace JuiceAgent::Core::Modules {
class TemplateModule : public IModule {
public:
std::string name() const override {
return "Template";
}
bool init() override {
if (_initialized) {
return true;
}
// load config / prepare resource
_initialized = true;
return true;
}
bool start() override {
if (!_initialized) {
return false;
}
if (_running) {
return true;
}
// start logic
_running = true;
return true;
}
void stop() override {
if (!_running) {
return;
}
// cleanup logic
_running = false;
}
private:
bool _initialized = false;
bool _running = false;
};
}
JUICEAGENT_REGISTER_MODULE(
JuiceAgent::Core::Modules::TemplateModule,
Template
)