Compare commits

...
Author SHA1 Message Date
xiaozhou233 4c940c848b Version 3.3 Build 2 2026-04-23 22:06:11 +08:00
xiaozhou233 6564a0e020 feat: Update logger to use ColorConsoleAppender for improved output 2026-04-22 21:37:23 +08:00
xiaozhou233 c6dd965a9a feat: Delete tinytoml licenses 2026-04-22 21:17:42 +08:00
xiaozhou233 d87972242a feat: Add Template Module 2026-04-22 13:22:14 +08:00
xiaozhou233 50eb73d4e8 feat: Refactor module management and introduce ModuleRegistry for dynamic module loading 2026-04-22 13:19:39 +08:00
xiaozhou233 08ec414094 [Revert] Restore project state to 79ae4b6 2026-04-22 13:08:39 +08:00
xiaozhou233 601c999023 feat: Add Example module implementation and registration 2026-04-21 18:47:42 +08:00
xiaozhou233 e1577d4fae feat: Implement module registration and loading functionality 2026-04-21 18:34:32 +08:00
xiaozhou233 79ae4b62a3 Fix: Docs 2026-04-21 15:05:37 +08:00
xiaozhou233 f90582d24f modified: README.md 2026-04-21 14:56:52 +08:00
xiaozhou233 bc2440eeab Docs: Readme 2026-04-21 14:55:24 +08:00
xiaozhou233 92837c9597 Docs: Readme 2026-04-21 14:44:35 +08:00
xiaozhou233 b348757416 Version 3.3 Build 1 2026-04-20 16:48:54 +08:00
xiaozhou233 f5912f8040 [Doc] Update Version & Example Config 2026-04-20 16:48:29 +08:00
xiaozhou233 95f5604bfe Merge pull request #9 from xiaozhou233/refactor
Enhance configuration handling and implement module system
2026-04-20 14:06:38 +08:00
xiaozhou233 1ae65dd516 [Doc] TODO 2026-04-20 14:05:14 +08:00
xiaozhou233 50773f5456 Feat: Call Java Implementation 2026-04-20 14:04:53 +08:00
xiaozhou233 ccb332cb42 [Feat] Serializer 2026-04-20 13:18:58 +08:00
xiaozhou233 9a2dd217f1 [Refactor] Update configuration handling in JarLoader and enhance Config class 2026-04-19 22:26:51 +08:00
xiaozhou233 3fe9f5a573 Feat: Modules System 2026-04-19 19:03:48 +08:00
xiaozhou233 6858a35754 Feat: Simple module system 2026-04-19 18:57:32 +08:00
xiaozhou233 e7ce54188b [Refactor] Enhance Config class with type-safe get method and value reading 2026-04-19 18:44:59 +08:00
xiaozhou233 9f366645c9 Feat: libagent can now read the config 2026-04-19 18:36:26 +08:00
xiaozhou233 6a7e5a1d38 [Refactor] Config and Loader
[Add] toml11 library
[Refactor] Config
[Refactor] Data Struct
[Refactor] Loader
2026-04-19 16:41:39 +08:00
xiaozhou233 17bc993296 Example: empty example config 2026-04-19 15:44:06 +08:00
xiaozhou233 c348529e65 Style: Rename 2026-04-18 19:53:59 +08:00
xiaozhou233 cc52a25db4 Style: Rename 2026-04-18 19:28:47 +08:00
xiaozhou233 8b0bf8f211 Style: move LocalRef to header / move check_and_clear_exception to header 2026-04-18 19:24:49 +08:00
30 changed files with 19276 additions and 2844 deletions

No files matched your search

+115 -75
View File
@@ -1,66 +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.1 Build 3**. ![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]
# Default value: YourDir/JuiceAgent-API.jar Version = 1
JuiceAgentAPIJarPath = ""
# Default value: YourDir/libagent.dll
JuiceAgentNativePath = ""
[Entry] [JuiceAgent.Loader]
# Default value: YourDir/Entry.jar # Path to JuiceAgent-API-x.x.x+build.x.jar
EntryJarPath = "" JuiceAgentAPIJarPath = "./JuiceAgent-API-x.x.x+build.x.jar"
# Default value: com.example.Entry # Path to libagent.dll, default is "./libagent.dll"
EntryClass = "" JuiceAgentNativeLibraryPath = ""
# Default value: start
EntryMethod = "start"
[Runtime] [JuiceAgent.Modules]
# Default value: YourDir/injection
InjectionDir = "" [JuiceAgent.Modules.JarLoader]
Enabled = true
# Path to the Injection JAR files to be loaded
InjectionDir = "./injection"
# Path to the JAR file to be loaded
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`.
@@ -73,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
@@ -144,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
-148
View File
@@ -1,148 +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.1 Build 3**。
**警告:** 本项目仍处于实验阶段,不建议在生产环境中使用。使用风险请自行承担。
## 简介
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]
# 默认值: YourDir/JuiceAgent-API.jar
JuiceAgentAPIJarPath = ""
# 默认值: YourDir/libagent.dll
JuiceAgentNativePath = ""
[Entry]
# 默认值: YourDir/Entry.jar
EntryJarPath = ""
# 默认值: com.example.Entry
EntryClass = ""
# 默认值: start
EntryMethod = "start"
[Runtime]
# 默认值: YourDir/injection
InjectionDir = ""
```
### 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++ 库
+10 -3
View File
@@ -10,6 +10,13 @@
- [ ] 重构 `libloader` 的配置系统 - [ ] 重构 `libloader` 的配置系统
## 2026-04-17 ## 2026-04-17
- [ ] 重构项目为模块化项目 - [x] 重构项目为模块化项目
- [ ] `libloader` 模块只负责加载`JuiceAgent-API`和`JuiceAgent`, Jar文件由`JuiceAgent`接管 - [x] `libloader` 模块只负责加载`JuiceAgent-API`和`JuiceAgent`, Jar文件由`JuiceAgent`接管
- [ ] `libloader` 读取配置文件并传参`JuiceAgentNativePath`和`ConfigDir`到 `JuiceAgent` 中,由`JuiceAgent`读取配置文件继续进行操作 - [x] `libloader` 读取配置文件并传参`JuiceAgentNativePath`和`ConfigDir`到 `JuiceAgent` 中,由`JuiceAgent`读取配置文件继续进行操作
## 2026-04-19
- [x] 在 `JuiceAgent/Utils.hpp`做序列化操作
- [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>");
```
+16
View File
@@ -0,0 +1,16 @@
[JuiceAgent]
Version = 1
[JuiceAgent.Loader]
JuiceAgentAPIJarPath = ""
JuiceAgentNativeLibraryPath = ""
[JuiceAgent.Modules]
[JuiceAgent.Modules.JarLoader]
Enabled = true
InjectionDir = ""
JarPath = ""
EntryClass = ""
EntryMethod = ""
+127 -158
View File
@@ -2,194 +2,163 @@
#include <JuiceAgent/Logger.hpp> #include <JuiceAgent/Logger.hpp>
#include <JuiceAgent/JuiceAgent.hpp> #include <JuiceAgent/JuiceAgent.hpp>
#include <tinytoml/toml.h> #include <toml.hpp>
#include <filesystem> #include <filesystem>
#include <fstream>
#include <string> #include <string>
#include <JuiceAgent/Utils.hpp>
namespace JuiceAgent::Config { namespace JuiceAgent::Config {
class Config { class Config {
private: private:
std::string runtime_dir; // Runtime directory std::filesystem::path _runtime_dir;
toml::Value config{}; // Parsed TOML configuration toml::value _config;
bool valid = false; // Whether the config is successfully loaded bool _valid = false;
// Escape special characters ';' = '\' private:
static std::string escape(const std::string& s) { template<typename T>
std::string out; static T _read_value(const toml::value& v) {
out.reserve(s.size()); if constexpr (std::is_same_v<T, std::string>) {
for (char c : s) { return v.as_string();
if (c == ';' || c == '=' || c == '\\') { } else if constexpr (std::is_same_v<T, bool>) {
out += '\\'; return v.as_boolean();
} } else if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool>) {
out += c; return static_cast<T>(v.as_integer());
} else if constexpr (std::is_floating_point_v<T>) {
return static_cast<T>(v.as_floating());
} else {
static_assert(sizeof(T) == 0, "Unsupported config type");
} }
return out;
}
// Append key=value pair to string
static void append_kv(std::string& out, const char* key, const std::string& value, bool& first) {
if (!first) out += ';';
first = false;
out += key;
out += '=';
out += escape(value);
}
// Helper function: find value by dot-separated key
const toml::Value* find_value(const std::string& key) const {
if (!valid) return nullptr;
const toml::Value* current = &config;
size_t start = 0;
while (true) {
size_t dot = key.find('.', start);
std::string part = key.substr(start, dot - start);
if (!current->is<toml::Table>()) return nullptr;
const auto& table = current->as<toml::Table>();
auto it = table.find(part);
if (it == table.end()) return nullptr;
current = &it->second;
if (dot == std::string::npos) break;
start = dot + 1;
}
return current;
} }
public: public:
explicit Config(const char* c_runtime_dir) explicit Config(const std::filesystem::path& runtime_dir = {})
: runtime_dir(c_runtime_dir ? c_runtime_dir : "")
{ {
if (runtime_dir.empty()) { _runtime_dir = runtime_dir.empty()
PLOGW << "runtime_dir is empty"; ? std::filesystem::current_path()
return; : runtime_dir;
}
std::filesystem::path path = std::filesystem::path(runtime_dir) / "config.toml"; const auto result = toml::try_parse(_runtime_dir / "config.toml");
std::ifstream ifs(path);
if (!ifs.is_open()) {
PLOGE << "Failed to open config file: " << path;
return;
}
try { if (result.is_ok()) {
auto pr = toml::parse(ifs); _config = result.unwrap();
if (!pr.valid()) { _valid = true;
PLOGE << "Invalid TOML file: " << pr.errorReason; } else {
return; PLOGE << "Failed to parse config.toml";
for (const auto& err : result.unwrap_err()) {
PLOGE << toml::format_error(err);
} }
config = pr.value;
valid = true;
} catch (const std::exception& e) {
PLOGE << "TOML parse error: " << e.what();
} }
} }
// Get value by key with default bool is_valid() const noexcept {
return _valid;
}
const toml::value& get_config() const noexcept {
return _config;
}
const std::filesystem::path& runtime_dir() const noexcept {
return _runtime_dir;
}
template<typename T> template<typename T>
T get_or_default(const std::string& key, const T& default_value, bool use_default_if_empty = false, bool is_path = false) const { T get(const std::string& path, const T& default_value, bool is_path = false) const {
const toml::Value* val = find_value(key); if (!_valid) {
if (!val) return default_value; return default_value;
}
try { try {
if constexpr (std::is_same_v<T, std::string>) { const toml::value* current = &_config;
std::string s = val->as<std::string>(); std::size_t start = 0;
if (use_default_if_empty && s.empty()) return default_value;
// Check if string starts with '.'
if (is_path && s.starts_with('.')) {
// remove '.'
s.erase(0, 1);
// Check if string starts with '/' while (start < path.size()) {
// MUST REMOVE '/', or it will cause path error (root directory) const std::size_t end = path.find('.', start);
if (s.starts_with('/')) { const std::string key = path.substr(
s.erase(0, 1); start,
} end == std::string::npos ? std::string::npos : end - start
);
// runtime_dir + s current = &current->at(key);
s = (std::filesystem::path(runtime_dir) / s).string();
if (end == std::string::npos) {
break;
} }
return s;
} else { start = end + 1;
return val->as<T>();
} }
} catch (...) {
T value = _read_value<T>(*current);
if constexpr (std::is_same_v<T, std::string>) {
if (value.empty()) {
return default_value;
}
// Handle relative paths
if (is_path) {
// Check if starts with "."
if (value.starts_with(".")) {
// Remove "."
value = value.substr(1);
// Check if starts with "/"
if (value.starts_with("/")) {
// Remove "/"
value = value.substr(1);
}
// runtime_dir + value
value = (_runtime_dir / value).string();
}
}
}
return value;
}
catch (const std::exception& e) {
PLOGW << "Config get failed: " << path << ", using default value";
return default_value; return default_value;
} }
} }
bool is_valid() const {
return valid;
}
// Get InjectionInfo struct from config
InjectionInfo get_injection_info() const {
InjectionInfo info;
auto get_default_path = [&](const std::string& name) {
return (std::filesystem::path(runtime_dir) / name).string();
};
info.JuiceAgentAPIJarPath = get_or_default<std::string>(
"JuiceAgent.JuiceAgentAPIJarPath", get_default_path("JuiceAgent-API.jar"), true, true);
info.JuiceAgentNativePath = get_or_default<std::string>(
"JuiceAgent.JuiceAgentNativePath", get_default_path("libagent.dll"), true, true);
info.EntryJarPath = get_or_default<std::string>(
"Entry.EntryJarPath", get_default_path("Entry.jar"), true, true);
info.EntryClass = get_or_default<std::string>(
"Entry.EntryClass", "com.example.Entry", true, false);
info.EntryMethod = get_or_default<std::string>(
"Entry.EntryMethod", "start", true, false);
info.InjectionDir = get_or_default<std::string>(
"Runtime.InjectionDir", get_default_path("injection"), true, true);
return info;
}
// Serialize InjectionInfo to key=value; format
static std::string serialize(const InjectionInfo& info) {
std::string result;
result.reserve(256);
bool first = true;
append_kv(result, "Version", "1", first);
append_kv(result, "EntryJarPath", info.EntryJarPath, first);
append_kv(result, "EntryClass", info.EntryClass, first);
append_kv(result, "EntryMethod", info.EntryMethod, first);
append_kv(result, "JuiceAgentAPIJarPath", info.JuiceAgentAPIJarPath, first);
append_kv(result, "JuiceAgentNativePath", info.JuiceAgentNativePath, first);
append_kv(result, "InjectionDir", info.InjectionDir, first);
PLOGD << "Serialized args: " << result;
return result;
}
std::string serialize() const {
return serialize(get_injection_info());
}
}; };
// Print InjectionInfo (debug) namespace Utils {
inline void print_injection_info(const InjectionInfo& info) { inline LoaderConfig get_loader_config(const Config& config) {
PLOGI << "JuiceAgent Injection Info:"; auto cfg = config.get_config().at("JuiceAgent").at("Loader");
PLOGI << " JuiceAgentAPIJarPath: " << info.JuiceAgentAPIJarPath;
PLOGI << " JuiceAgentNativePath: " << info.JuiceAgentNativePath; LoaderConfig loader_config = LoaderConfig();
PLOGI << " EntryJarPath: " << info.EntryJarPath; loader_config.JuiceAgentAPIJarPath = cfg.at("JuiceAgentAPIJarPath").as_string();
PLOGI << " EntryClass: " << info.EntryClass; loader_config.JuiceAgentNativeLibraryPath = cfg.at("JuiceAgentNativeLibraryPath").as_string();
PLOGI << " EntryMethod: " << info.EntryMethod; loader_config.RuntimeDir = config.runtime_dir().string();
PLOGI << " InjectionDir: " << info.InjectionDir;
return loader_config;
}
inline void print_loader_config(const LoaderConfig& config) {
PLOGI << "JuiceAgentAPIJarPath: " << config.JuiceAgentAPIJarPath;
PLOGI << "JuiceAgentNativeLibraryPath: " << config.JuiceAgentNativeLibraryPath;
PLOGI << "RuntimeDir: " << config.RuntimeDir;
}
inline std::string serialize_loader_config(const LoaderConfig& config) {
// std::string result = "";
// result += "Version=2;";
// result += "JuiceAgentAPIJarPath=" + config.JuiceAgentAPIJarPath + ";";
// result += "JuiceAgentNativeLibraryPath=" + config.JuiceAgentNativeLibraryPath + ";";
// result += "RuntimeDir=" + config.RuntimeDir + ";";
JuiceAgent::Utils::Serializer ser;
ser.add_kv("Version", 2);
ser.add_kv("JuiceAgentAPIJarPath", config.JuiceAgentAPIJarPath);
ser.add_kv("JuiceAgentNativeLibraryPath", config.JuiceAgentNativeLibraryPath);
ser.add_kv("RuntimeDir", config.RuntimeDir);
return ser.serialize();
}
} }
} // namespace config } // namespace JuiceAgent::Config
+3 -7
View File
@@ -2,13 +2,9 @@
#include <string> #include <string>
struct InjectionInfo { struct LoaderConfig {
std::string JuiceAgentAPIJarPath; std::string JuiceAgentAPIJarPath;
std::string JuiceAgentNativePath; std::string JuiceAgentNativeLibraryPath;
std::string EntryJarPath; std::string RuntimeDir;
std::string EntryClass;
std::string EntryMethod;
std::string InjectionDir;
}; };
+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";
} }
+267
View File
@@ -0,0 +1,267 @@
#pragma once
#include <jni.h>
#include <jvmti.h>
#include <JuiceAgent/Logger.hpp>
#include <string>
#include <unordered_map>
#include <type_traits>
#include <cstdlib>
// Check for JNI exceptions and clear them
inline bool check_and_clear_exception(JNIEnv* env, const char* context) {
if (env->ExceptionCheck()) {
PLOGE << "JNI Exception occurred at: " << context;
env->ExceptionDescribe();
env->ExceptionClear();
return true;
}
return false;
}
namespace JuiceAgent::Utils
{
inline bool call_java_impl(JNIEnv* env, const char* clazz, const char* method, const char* params) {
if (!env || !clazz || !method) {
PLOGE << "Invalid JNI arguments";
return false;
}
constexpr const char* method_signature = "(Ljava/lang/String;)V";
PLOGD << "Calling Java method: " << clazz << "." << method << " " << method_signature;
jclass cls = env->FindClass(clazz);
if (!cls) {
check_and_clear_exception(env, "FindClass failed");
PLOGE << "Class not found: " << clazz;
return false;
}
jmethodID mid = env->GetStaticMethodID(cls, method, method_signature);
if (!mid) {
check_and_clear_exception(env, "GetStaticMethodID failed");
PLOGE << "Method not found: " << method;
env->DeleteLocalRef(cls);
return false;
}
jstring j_params = env->NewStringUTF(params ? params : "");
if (!j_params) {
PLOGE << "Failed to create jstring";
env->DeleteLocalRef(cls);
return false;
}
env->CallStaticVoidMethod(cls, mid, j_params);
bool success = !env->ExceptionCheck();
check_and_clear_exception(env, "CallStaticVoidMethod failed");
env->DeleteLocalRef(j_params);
env->DeleteLocalRef(cls);
return success;
}
class Serializer {
private:
std::string s;
private:
static std::string escape(const std::string& input) {
std::string out;
out.reserve(input.size());
for (char c : input) {
if (c == '=' || c == ';' || c == '\\') {
out += '\\';
}
out += c;
}
return out;
}
public:
Serializer() = default;
Serializer& add_kv(const std::string& key, const std::string& value) {
s += escape(key);
s += '=';
s += escape(value);
s += ';';
return *this;
}
Serializer& add_kv(const std::string& key, const char* value) {
return add_kv(key, std::string(value));
}
Serializer& add_kv(const std::string& key, int value) {
return add_kv(key, std::to_string(value));
}
Serializer& add_kv(const std::string& key, bool value) {
return add_kv(key, value ? "true" : "false");
}
void clear() {
s.clear();
}
bool empty() const {
return s.empty();
}
const std::string& serialize() const {
return s;
}
};
class Deserializer {
private:
std::unordered_map<std::string, std::string> data;
private:
static std::string unescape(const std::string& input) {
std::string out;
out.reserve(input.size());
bool escaped = false;
for (char c : input) {
if (escaped) {
out += c;
escaped = false;
continue;
}
if (c == '\\') {
escaped = true;
continue;
}
out += c;
}
return out;
}
static bool to_bool(const std::string& v, bool def) {
if (v == "true" || v == "1") return true;
if (v == "false" || v == "0") return false;
return def;
}
template<typename T>
static T convert(const std::string& v, T def) {
if constexpr (std::is_same_v<T, std::string>) {
return v;
}
else if constexpr (std::is_same_v<T, bool>) {
return to_bool(v, def);
}
else if constexpr (std::is_integral_v<T>) {
try {
long long n = std::stoll(v);
return static_cast<T>(n);
} catch (...) {
return def;
}
}
else if constexpr (std::is_floating_point_v<T>) {
try {
long double n = std::stold(v);
return static_cast<T>(n);
} catch (...) {
return def;
}
}
else {
return def;
}
}
public:
Deserializer() = default;
explicit Deserializer(const std::string& input) {
parse(input);
}
void parse(const std::string& input) {
data.clear();
std::string key;
std::string value;
bool reading_key = true;
bool escaped = false;
for (char c : input) {
if (escaped) {
(reading_key ? key : value) += c;
escaped = false;
continue;
}
if (c == '\\') {
escaped = true;
continue;
}
if (reading_key && c == '=') {
reading_key = false;
continue;
}
if (c == ';') {
if (!key.empty()) {
data[unescape(key)] = unescape(value);
}
key.clear();
value.clear();
reading_key = true;
continue;
}
(reading_key ? key : value) += c;
}
if (!key.empty()) {
data[unescape(key)] = unescape(value);
}
}
bool has(const std::string& key) const {
return data.find(key) != data.end();
}
template<typename T>
T get(const std::string& key, T def) const {
auto it = data.find(key);
if (it == data.end()) {
return def;
}
return convert<T>(it->second, def);
}
void clear() {
data.clear();
}
bool empty() const {
return data.empty();
}
std::size_t size() const {
return data.size();
}
};
} // namespace JuiceAgent::Utils
File diff suppressed because it is too large. Load diff
+18162
View File
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.
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2017 Toru Niina
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+13 -2
View File
@@ -3,11 +3,22 @@
// 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
(JNIEnv *env, jclass loader_class) { (JNIEnv *env, jclass , jstring j_runtime_dir) {
InitLogger(); InitLogger();
PLOGI << "Initializing JuiceAgent..."; 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; JavaVM* jvm = nullptr;
jvmtiEnv* jvmti = nullptr; jvmtiEnv* jvmti = nullptr;
@@ -27,7 +38,7 @@ JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init
// Invoke EntryPoint // Invoke EntryPoint
JuiceAgent::Agent& agent = JuiceAgent::Agent::instance(); JuiceAgent::Agent& agent = JuiceAgent::Agent::instance();
agent.init(jvm, env, jvmti); agent.init(jvm, env, jvmti, runtime_dir);
return JNI_TRUE; return JNI_TRUE;
} }
@@ -10,10 +10,10 @@ extern "C" {
/* /*
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent * Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
* Method: init * Method: init
* Signature: ()Z * Signature: (Ljava/lang/String;)Z
*/ */
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init
(JNIEnv *, jclass); (JNIEnv *, jclass, jstring);
/* /*
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent * Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
+10 -1
View File
@@ -4,13 +4,18 @@
#include <jni.h> #include <jni.h>
#include <jvmti.h> #include <jvmti.h>
#include <event/eventbus.hpp> #include <event/eventbus.hpp>
#include <JuiceAgent/Config.hpp>
#include <modules/ModuleManager.hpp>
namespace JuiceAgent { namespace JuiceAgent {
class Agent { class Agent {
private: private:
JavaVM* jvm; JavaVM* jvm;
jvmtiEnv* jvmti; jvmtiEnv* jvmti;
JNIEnv* env;
EventBus eventbus; EventBus eventbus;
JuiceAgent::Config::Config config;
JuiceAgent::Core::Modules::ModuleManager module_manager;
private: private:
Agent() = default; Agent() = default;
@@ -24,15 +29,19 @@ namespace JuiceAgent {
Agent& operator=(const Agent&) = delete; Agent& operator=(const Agent&) = delete;
// EntryPoint // EntryPoint
bool init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti); bool init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti, std::string& runtime_dir);
// getters // getters
JavaVM* get_jvm() const { return jvm; } JavaVM* get_jvm() const { return jvm; }
jvmtiEnv* get_jvmti() const { return jvmti; } jvmtiEnv* get_jvmti() const { return jvmti; }
JNIEnv* get_env() const { return env; }
EventBus& get_eventbus() { return eventbus; } EventBus& get_eventbus() { return eventbus; }
JuiceAgent::Config::Config& get_config() { return config; }
// setters // setters
void set_jvm(JavaVM* jvm) { this->jvm = jvm; } void set_jvm(JavaVM* jvm) { this->jvm = jvm; }
void set_jvmti(jvmtiEnv* jvmti) { this->jvmti = jvmti; } 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; }
}; };
} }
+17
View File
@@ -0,0 +1,17 @@
#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;
};
}
@@ -0,0 +1,27 @@
#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;
};
}
@@ -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>(); \
} \
); \
}
+89 -66
View File
@@ -3,6 +3,7 @@
#include <bytecodes_opt.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>
namespace JuiceAgent { namespace JuiceAgent {
// ===== Singleton ===== // ===== Singleton =====
@@ -11,74 +12,96 @@ namespace JuiceAgent {
return instance; return instance;
} }
bool Agent::init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti) { bool Agent::init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti, std::string& runtime_dir) {
PLOGI << "JuiceAgent Native EntryPoint Invoked!"; try {
PLOGI << "JuiceAgent Native EntryPoint Invoked!";
// ======== neccessary environment check ======== // ======== neccessary environment check ========
if (jvm == nullptr) { if (jvm == nullptr) {
PLOGE << "Failed to initialize JuiceAgent: jvm is null"; 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;
// Load and Initialize Modules
module_manager.load_all();
module_manager.init_all();
// Initialize Modules
module_manager.init_all();
// 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;
}
// register bytecodes_opt
JuiceAgent::Bytecodes::register_bytecodes();
// Start Modules
module_manager.start_all();
// Loaded Event
eventbus.post(EventLoaded{
.jvm = jvm,
.env = env,
.jvmti = jvmti
});
return true;
} catch (const std::exception& e) {
PLOGE << "Exception: " << e.what();
return false; 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;
}
set_jvm(jvm);
set_jvmti(jvmti);
PLOGD << "env: " << env << ", jvmti: " << jvmti;
// 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;
}
// register bytecodes_opt
JuiceAgent::Bytecodes::register_bytecodes();
// Loaded Event
eventbus.post(EventLoaded{
.jvm = jvm,
.env = env,
.jvmti = jvmti
});
return true;
} }
} }
+117
View File
@@ -0,0 +1,117 @@
#include <modules/ModuleRegistry.hpp>
#include <JuiceAgent/Logger.hpp>
#include <libagent.hpp>
#include <JuiceAgent/Utils.hpp>
namespace JuiceAgent::Core::Modules {
struct JarLoaderConfig {
bool enabled = true;
std::string injection_dir;
std::string jar_path;
std::string entry_class;
std::string entry_method;
};
static JarLoaderConfig config;
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 IModule {
public:
std::string name() const override {
return "JarLoader";
}
bool init() override {
if (_initialized) {
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;
}
bool start() override {
if (!_initialized) {
return false;
}
if (_running || !config.enabled) {
return true;
}
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";
_running = true;
return true;
}
void stop() override {
if (!_running) {
return;
}
PLOGI << "JarLoader stop";
_running = false;
}
private:
bool _initialized = false;
bool _running = false;
};
}
JUICEAGENT_REGISTER_MODULE(
JuiceAgent::Core::Modules::JarLoaderModule,
JarLoader
)
+64
View File
@@ -0,0 +1,64 @@
#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();
return false;
}
}
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();
return false;
}
}
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;
}
}
+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
)
@@ -1,40 +1,13 @@
#include <JuiceAgent/Logger.hpp> #include <JuiceAgent/Logger.hpp>
#include <libloader.hpp> #include <Loader.hpp>
#include <JuiceAgent/Config.hpp> #include <JuiceAgent/Config.hpp>
#include <jvm.hpp> #include <JvmManager.hpp>
#include <JuiceAgent/Utils.hpp>
namespace libloader { namespace JuiceAgent::Loader {
namespace {
// Check for JNI exceptions and clear them
bool check_and_clear_exception(JNIEnv* env, const char* context) {
if (env->ExceptionCheck()) {
PLOGE << "JNI Exception occurred at: " << context;
env->ExceptionDescribe();
env->ExceptionClear();
return true;
}
return false;
}
// RAII wrapper for local JNI references
template<typename T>
class LocalRef {
private:
JNIEnv* env;
T ref;
public:
LocalRef(JNIEnv* env, T ref) : env(env), ref(ref) {}
~LocalRef() {
if (ref) env->DeleteLocalRef(ref);
}
T get() const { return ref; }
operator T() const { return ref; }
};
}
// Invoke JuiceAgentBootstrap.start(String) via JNI // Invoke JuiceAgentBootstrap.start(String) via JNI
bool invoke_juiceagent_init(JNIEnv* env, const InjectionInfo& info) { bool invoke_juiceagent_init(JNIEnv* env, const LoaderConfig& config) {
const char* bootstrap_class = "cn/xiaozhou233/juiceagent/api/JuiceAgentBootstrap"; const char* bootstrap_class = "cn/xiaozhou233/juiceagent/api/JuiceAgentBootstrap";
const char* method_name = "start"; const char* method_name = "start";
const char* method_desc = "(Ljava/lang/String;)V"; const char* method_desc = "(Ljava/lang/String;)V";
@@ -54,7 +27,7 @@ bool invoke_juiceagent_init(JNIEnv* env, const InjectionInfo& info) {
} }
// Serialize InjectionInfo to string // Serialize InjectionInfo to string
std::string args = JuiceAgent::Config::Config::serialize(info); std::string args = JuiceAgent::Config::Utils::serialize_loader_config(config);
PLOGD << "Invoke args: " << args; PLOGD << "Invoke args: " << args;
// Create Java string // Create Java string
@@ -86,20 +59,24 @@ void entrypoint(const char* runtime_dir) {
JuiceAgent::Config::Config cfg(runtime_dir); JuiceAgent::Config::Config cfg(runtime_dir);
if (!cfg.is_valid()) { if (!cfg.is_valid()) {
PLOGW << "Invalid config, using default values"; PLOGW << "Invalid config, using default values";
// TODO: Use default values
// Before impl TODO, must return, or crash will happen
return;
} }
// Get InjectionInfo // Get InjectionInfo
InjectionInfo info = cfg.get_injection_info(); LoaderConfig config = JuiceAgent::Config::Utils::get_loader_config(cfg);
JuiceAgent::Config::print_injection_info(info); JuiceAgent::Config::Utils::print_loader_config(config);
// Validate essential paths // Validate essential paths
if (info.JuiceAgentAPIJarPath.empty()) { if (config.JuiceAgentAPIJarPath.empty()) {
PLOGE << "JuiceAgentAPIJarPath is empty, abort injection"; PLOGE << "JuiceAgentAPIJarPath is empty, abort injection";
return; return;
} }
// Attach to JVM // Attach to JVM
jvm::Jvm jvm; JuiceAgent::Loader::JvmManager::Jvm jvm;
if (!jvm.attach()) { if (!jvm.attach()) {
PLOGE << "Attach to JVM failed"; PLOGE << "Attach to JVM failed";
return; return;
@@ -114,18 +91,18 @@ void entrypoint(const char* runtime_dir) {
} }
// Inject JuiceAgent jar into system class loader // Inject JuiceAgent jar into system class loader
jint status = jvmti->AddToSystemClassLoaderSearch(info.JuiceAgentAPIJarPath.c_str()); jint status = jvmti->AddToSystemClassLoaderSearch(config.JuiceAgentAPIJarPath.c_str());
if (status != JNI_OK) { if (status != JNI_OK) {
PLOGE << "AddToSystemClassLoaderSearch failed: " << status; PLOGE << "AddToSystemClassLoaderSearch failed: " << status;
return; return;
} }
PLOGI << "Jar injected successfully: " << info.JuiceAgentAPIJarPath; PLOGI << "Jar injected successfully: " << config.JuiceAgentAPIJarPath;
// Invoke JuiceAgent initialization // Invoke JuiceAgent initialization
if (!invoke_juiceagent_init(env, info)) { if (!invoke_juiceagent_init(env, config)) {
PLOGE << "invoke_juiceagent_init failed"; PLOGE << "invoke_juiceagent_init failed";
} }
} }
} // namespace libloader } // namespace JuiceAgent::Loader
-246
View File
@@ -1,246 +0,0 @@
#include <jvm/jni.h>
#include <jvm/jvmti.h>
#include <stdio.h>
#include <JuiceAgent/Logger.hpp>
#include <libloader.h>
#include <thread>
#include <tinytoml/toml.h>
#include <JuiceAgent/JuiceAgent.h>
struct _JuiceAgent {
bool isAttached;
JavaVM *jvm;
jvmtiEnv *jvmti;
JNIEnv *env;
} JuiceAgent = {false, NULL, NULL, NULL};
InjectionInfoType InjectionInfo;
static int ReadConfig(const char* ConfigDir)
{
// ConfigDir/config.toml
std::string path = std::string(ConfigDir) + "\\config.toml";
std::ifstream ifs(path);
if (!ifs) return -1;
// Parse toml
toml::ParseResult pr = toml::parse(ifs);
if (!pr.valid()) return -2;
const toml::Value& tbl = pr.value;
// Helper function: get string from toml
auto get_str = [&](const char* key, const char* def, char* out) {
const toml::Value* v = tbl.find(key);
if (v && v->is<std::string>()) {
std::string s = v->as<std::string>();
if (!s.empty()) {
strncpy(out, s.c_str(), INJECT_PATH_MAX - 1);
PLOGD << "Found parameter: " << key << " = " << s.c_str();
} else {
strncpy(out, def, INJECT_PATH_MAX - 1);
PLOGD << "Parameter " << key << " is empty, use default: " << def;
}
} else {
strncpy(out, def, INJECT_PATH_MAX - 1);
PLOGD << "Not found parameter: " << key << ", use default: " << def;
}
out[INJECT_PATH_MAX - 1] = '\0';
};
// Default values
std::string defaultJuiceLoader = std::string(ConfigDir) + "\\JuiceLoader.jar";
std::string defaultJuiceLoaderLibrary = std::string(ConfigDir) + "\\libjuiceloader.dll";
std::string defaultEntryJar = std::string(ConfigDir) + "\\Entry.jar";
std::string defaultInjectionDir = std::string(ConfigDir) + "\\injection";
get_str("JuiceLoaderJarPath", defaultJuiceLoader.c_str(), InjectionInfo.JuiceLoaderJarPath);
get_str("JuiceLoaderLibraryPath", defaultJuiceLoaderLibrary.c_str(), InjectionInfo.JuiceLoaderLibraryPath);
get_str("InjectionDir", defaultInjectionDir.c_str(), InjectionInfo.InjectionDir);
get_str("EntryJarPath", defaultEntryJar.c_str(), InjectionInfo.EntryJarPath);
get_str("EntryClass", "cn.xiaozhou233.test.Entry", InjectionInfo.EntryClass);
get_str("EntryMethod", "start", InjectionInfo.EntryMethod);
PLOGD << "JuiceLoaderJarPath: " << InjectionInfo.JuiceLoaderJarPath;
PLOGD << "JuiceLoaderLibraryPath: " << InjectionInfo.JuiceLoaderLibraryPath;
PLOGD << "InjectionDir: " << InjectionInfo.InjectionDir;
PLOGD << "EntryJarPath: " << InjectionInfo.EntryJarPath;
PLOGD << "EntryClass: " << InjectionInfo.EntryClass;
PLOGD << "EntryMethod: " << InjectionInfo.EntryMethod;
return 0;
}
static int GetJavaEnv() {
jint res = JNI_ERR;
JavaVM *jvm = NULL;
jvmtiEnv *jvmti = NULL;
JNIEnv *env = NULL;
int max_try = 30;
// Get the JVM
max_try = 30;
do {
res = JNI_GetCreatedJavaVMs(&jvm, 1, NULL);
if (res != JNI_OK || jvm == NULL) {
PLOGE.printf("JNI_GetCreatedJavaVMs failed: %d", res);
PLOGD << "JVM NULL: " << (jvm == NULL);
}
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
max_try--;
if (jvm != NULL) {
break;
} else {
PLOGI.printf("Waiting for JVM... (%d)", max_try);
}
} while (jvm == NULL && max_try > 0);
if (jvm == NULL) {
PLOGE << "GetJavaEnv failed";
return res;
}
JuiceAgent.jvm = jvm;
PLOGI << "Got the JVM";
// Get the JNIEnv
max_try = 30;
do {
res = jvm->GetEnv((void**)&env, JNI_VERSION_1_8);
if (res != JNI_OK || env == NULL) {
PLOGI << "GetEnv failed, trying to attach.";
PLOGD << "env NULL: " << (env == NULL);
res = jvm->AttachCurrentThread((void**)&env, NULL);
if (res != JNI_OK || env == NULL) {
PLOGE.printf("AttachCurrentThread failed: %d", res);
PLOGD << "env NULL: " << (env == NULL);
return res;
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
max_try--;
if (env != NULL) {
break;
} else {
PLOGI.printf("Waiting for JNI... (%d)", max_try);
}
} while (env == NULL && max_try > 0);
if (env == NULL) {
PLOGE << "Get JNI failed";
return res;
}
JuiceAgent.env = env;
PLOGI << "Got the JNIEnv";
// Get the JVMTI
res = jvm->GetEnv((void**)&jvmti, JVMTI_VERSION_1_2);
if (res != JNI_OK || jvmti == NULL) {
PLOGE.printf("GetEnv failed: %d", res);
PLOGD << "jvmti NULL: " << (jvmti == NULL);
return res;
}
JuiceAgent.jvmti = jvmti;
PLOGI << "Got the JVMTI";
return 0;
}
static int InvokeJuiceLoaderInit(const char* ConfigDir) {
// Variables
int result = JNI_ERR;
JNIEnv *env = JuiceAgent.env;
jvmtiEnv *jvmti = JuiceAgent.jvmti;
const char *bootstrap_class = "cn/xiaozhou233/juiceloader/JuiceLoaderBootstrap";
const char *method_name = "init";
const char *method_signature = "([Ljava/lang/String;)V";
PLOGI << "Invoke JuiceLoader Init";
PLOGI << "================ JuiceLoader Init =================";
// Find class
jclass cls = env->FindClass(bootstrap_class);
if (cls == NULL) {
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
env->ExceptionClear();
}
PLOGE << "FindClass failed";
return 1;
}
// Find method
jmethodID mid = env->GetStaticMethodID(cls, method_name, method_signature);
if (mid == NULL) {
PLOGE << "GetStaticMethodID failed";
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
env->ExceptionClear();
}
return 1;
}
// arguments array
const char* args[] = {
InjectionInfo.EntryJarPath,
InjectionInfo.EntryClass,
InjectionInfo.EntryMethod,
InjectionInfo.InjectionDir,
InjectionInfo.JuiceLoaderLibraryPath
};
int argCount = sizeof(args)/sizeof(args[0]);
jclass stringCls = env->FindClass("java/lang/String");
jobjectArray jArgs = env->NewObjectArray(argCount, stringCls, nullptr);
for (int i = 0; i < argCount; i++) {
env->SetObjectArrayElement(jArgs, i, env->NewStringUTF(args[i]));
}
// Invoke method
env->CallStaticVoidMethod(cls, mid, jArgs);
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
env->ExceptionClear();
}
PLOGI << "================ JuiceLoader Init =================";
PLOGI << "Invoke JuiceLoader Init done";
return 0;
}
extern "C" __declspec(dllexport)
bool InitJuiceAgent(const char* runtime_path) {
PLOGD << "runtime_path: " << runtime_path;
// Read Config
if (ReadConfig(runtime_path) != 0) {
PLOGE << "ReadConfig failed";
return false;
}
PLOGI << "[OK] ReadConfig";
// Get JavaEnv
if (GetJavaEnv() != 0) {
PLOGE << "GetJavaEnv failed";
return false;
}
PLOGI << "[OK] Get JavaEnv";
// Inject JuiceLoader jar
if (JuiceAgent.jvmti->AddToSystemClassLoaderSearch(InjectionInfo.JuiceLoaderJarPath) != JNI_OK) {
PLOGE << "AddToSystemClassLoaderSearch failed";
return false;
}
PLOGI << "[OK] Inject JuiceLoader jar";
// Invoke JuiceLoader Init
if (InvokeJuiceLoaderInit(runtime_path) != 0) {
PLOGE << "Invoke JuiceLoader Init failed";
return false;
}
PLOGI << "[OK] Invoke JuiceLoader Init";
// Load JuiceLoaderLibrary
PLOGI << "--------> InitJuiceAgent Succeed <--------";
return true;
}
@@ -6,7 +6,7 @@
#include <thread> #include <thread>
#include <chrono> #include <chrono>
namespace jvm namespace JuiceAgent::Loader::JvmManager
{ {
class Jvm { class Jvm {
private: private:
@@ -119,4 +119,4 @@ namespace jvm
thread_local JNIEnv* Jvm::env = nullptr; thread_local JNIEnv* Jvm::env = nullptr;
} // namespace jvm } // namespace JuiceAgent::Loader::JvmManager
+31
View File
@@ -0,0 +1,31 @@
#pragma once
#include <JuiceAgent/JuiceAgent.hpp>
#include <string>
#include <JuiceAgent/Logger.hpp>
#include <jvm/jni.h>
#include <jvm/jvmti.h>
namespace JuiceAgent::Loader
{
void entrypoint(const char* runtime_dir);
bool invoke_juiceagent_init(JNIEnv* env, const LoaderConfig& info);
} // namespace JuiceAgent::Loader
namespace {
// RAII wrapper for local JNI references
template<typename T>
class LocalRef {
private:
JNIEnv* env;
T ref;
public:
LocalRef(JNIEnv* env, T ref) : env(env), ref(ref) {}
~LocalRef() {
if (ref) env->DeleteLocalRef(ref);
}
T get() const { return ref; }
operator T() const { return ref; }
};
}
-14
View File
@@ -1,14 +0,0 @@
#pragma once
#include <JuiceAgent/JuiceAgent.hpp>
#include <string>
#include <JuiceAgent/Logger.hpp>
#include <jvm/jni.h>
#include <jvm/jvmti.h>
namespace libloader
{
void entrypoint(const char* runtime_dir);
bool invoke_juiceagent_init(JNIEnv* env, const InjectionInfo& info);
} // namespace libloader
+2 -2
View File
@@ -1,6 +1,6 @@
#include <windows.h> #include <windows.h>
#include <JuiceAgent/Logger.hpp> #include <JuiceAgent/Logger.hpp>
#include <libloader.hpp> #include <Loader.hpp>
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) { BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) {
switch( fdwReason ) switch( fdwReason )
@@ -11,7 +11,7 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) {
const char* runtime_dir = (const char*)lpReserved; const char* runtime_dir = (const char*)lpReserved;
libloader::entrypoint(runtime_dir); JuiceAgent::Loader::entrypoint(runtime_dir);
break; break;
} }