mirror of
https://github.com/xiaozhou233/JuiceAgent.git
synced 2026-12-05 21:15:56 +08:00
Compare commits
8
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
e4844abba1 | ||
|
|
d359438e5d | ||
|
|
e8bee3040f | ||
|
|
535ed0f117 | ||
|
|
2f7eb532a7 | ||
|
|
174197badb | ||
|
|
56dead0725 | ||
|
|
fcb6be0b03 |
No files matched your search
@@ -1,135 +1,66 @@
|
|||||||
# JuiceAgent
|
# JuiceAgent
|
||||||
|
[English](https://github.com/xiaozhou233/JuiceAgent/blob/main/README.md) | [中文](https://github.com/xiaozhou233/JuiceAgent/blob/main/README_zh.md)
|
||||||
|
|
||||||
JuiceAgent is an advanced JVMTI-based injection framework designed for runtime JAR loading, bytecode transformation, and runtime JVM instrumentation, even when DisableAttachMechanism is enabled.
|
JuiceAgent is a JVMTI-based injection library for loading external JARs and transforming Java bytecode, even when `DisableAttachMechanism` is enabled.
|
||||||
|
|
||||||
**Warning**: This project is still experimental and is not recommended for production use. Use it at your own risk.
|
**Notice:** Currently, only **Windows** is supported. **Linux** support may be added in the future.
|
||||||
|
|
||||||

|
**Notice:** The current repository version is **Version 3.1 Build 3**.
|
||||||

|
|
||||||

|
|
||||||

|
|
||||||
|
|
||||||

|
**Warning:** This project is still experimental and is not recommended for production use. Use it at your own risk.
|
||||||

|
|
||||||

|
|
||||||

|
|
||||||

|
|
||||||
|
|
||||||

|
## Summary
|
||||||

|
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`.
|
||||||

|
|
||||||

|
|
||||||
|
|
||||||
## 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. See [JuiceAgent.java](https://github.com/xiaozhou233/JuiceAgent-API/blob/master/src/main/java/cn/xiaozhou233/juiceagent/api/JuiceAgent.java) for the API definition.
|
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).
|
||||||
|
|
||||||
- Load JARs into the Bootstrap or System ClassLoader
|
- `addToBootstrapClassLoaderSearch`
|
||||||
- Define classes dynamically
|
- `addToSystemClassLoaderSearch`
|
||||||
- Redefine classes by name or class reference
|
- `addToClassLoader`
|
||||||
- Retransform classes by name or class reference
|
- `defineClass`
|
||||||
- Get all loaded classes
|
- `redefineClass(ByName)`
|
||||||
- Find classes by name
|
- `retransformClass(ByName)`
|
||||||
- Get class bytecode by name or class reference
|
- `getLoadedClasses`
|
||||||
|
- `getClassByName`
|
||||||
|
- `getClassBytes(ByName)`
|
||||||
|
|
||||||
## Quick Start
|
## How To Use
|
||||||
### 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-API-x.x.x+build.x.jar` from the [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API/releases) page.
|
### 1. Download Files
|
||||||
|
Download the following files from [Releases](https://github.com/xiaozhou233/JuiceAgent/releases) and place them in `YourDir`:
|
||||||
|
|
||||||
Put the downloaded files into the same directory.
|
- `libagent.dll`
|
||||||
- YourDir
|
- `libinject.dll`
|
||||||
- JuiceAgent-API-x.x.x+build.x.jar
|
- `libloader.dll`
|
||||||
- libagent.dll
|
- `injector.exe`
|
||||||
- libinject.dll
|
|
||||||
- libloader.dll
|
|
||||||
- injector.exe
|
|
||||||
|
|
||||||
### 2. Copy your custom JAR/Dependencies to Directory
|
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`.
|
||||||
- YourDir
|
|
||||||
- JuiceAgent-API-x.x.x+build.x.jar
|
|
||||||
- libagent.dll
|
|
||||||
- libinject.dll
|
|
||||||
- libloader.dll
|
|
||||||
- injector.exe
|
|
||||||
- **MyCustomJar.jar**
|
|
||||||
- **injection**
|
|
||||||
- **Dependencies1.jar**
|
|
||||||
- **Dependencies2.jar**
|
|
||||||
|
|
||||||
### 3. Write Config
|
### 2. Write the Config File
|
||||||
|
Create a file named `config.toml` in `YourDir`.
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
[JuiceAgent]
|
[JuiceAgent]
|
||||||
Version = 1
|
# Default value: YourDir/JuiceAgent-API.jar
|
||||||
|
JuiceAgentAPIJarPath = ""
|
||||||
|
# Default value: YourDir/libagent.dll
|
||||||
|
JuiceAgentNativePath = ""
|
||||||
|
|
||||||
[JuiceAgent.Loader]
|
[Entry]
|
||||||
# Path to JuiceAgent-API-x.x.x+build.x.jar
|
# Default value: YourDir/Entry.jar
|
||||||
JuiceAgentAPIJarPath = "./JuiceAgent-API-x.x.x+build.x.jar"
|
EntryJarPath = ""
|
||||||
# Path to libagent.dll, default is "./libagent.dll"
|
# Default value: com.example.Entry
|
||||||
JuiceAgentNativeLibraryPath = ""
|
EntryClass = ""
|
||||||
|
# Default value: start
|
||||||
|
EntryMethod = "start"
|
||||||
|
|
||||||
[JuiceAgent.Modules]
|
[Runtime]
|
||||||
|
# Default value: YourDir/injection
|
||||||
[JuiceAgent.Modules.JarLoader]
|
InjectionDir = ""
|
||||||
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"
|
|
||||||
```
|
```
|
||||||
|
|
||||||
Save the config file as `config.toml`.
|
### 3. Run the Injector
|
||||||
|
|
||||||
- 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`.
|
||||||
@@ -142,11 +73,40 @@ 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:
|
||||||
|
|
||||||
See [Documents](https://github.com/xiaozhou233/JuiceAgent/blob/main/docs/Inject.md) for details.
|
```java
|
||||||
|
package cn.xiaozhou233.juiceagent.injector;
|
||||||
|
|
||||||
### 5. Done
|
public class InjectorNative {
|
||||||
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
|
||||||
|
|
||||||
@@ -184,5 +144,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
|
||||||
- [toml11](https://github.com/ToruNiina/toml11) - TOML for Modern C++
|
- [tinytoml](https://github.com/mayah/tinytoml) - Header-only C++11 TOML parser
|
||||||
- [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
@@ -0,0 +1,148 @@
|
|||||||
|
# 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++ 库
|
||||||
@@ -7,16 +7,11 @@
|
|||||||
- [x] 在 `includes/JuiceAgent` 文件夹下实现 `Config.hpp` 配置系统
|
- [x] 在 `includes/JuiceAgent` 文件夹下实现 `Config.hpp` 配置系统
|
||||||
- [ ] ~~新建测试 读取配置文件 (放弃)~~
|
- [ ] ~~新建测试 读取配置文件 (放弃)~~
|
||||||
|
|
||||||
- [ ] 重构 `libloader` 的配置系统
|
- [x] 重构 `libloader` 的配置系统
|
||||||
|
|
||||||
## 2026-04-17
|
## 2026-04-17
|
||||||
- [x] 重构项目为模块化项目
|
- [ ] 重构项目为模块化项目
|
||||||
- [x] `libloader` 模块只负责加载`JuiceAgent-API`和`JuiceAgent`, Jar文件由`JuiceAgent`接管
|
- [x] `libloader` 模块只负责加载`JuiceAgent-API`和`JuiceAgent`, Jar文件由`JuiceAgent`接管
|
||||||
- [x] `libloader` 读取配置文件并传参`JuiceAgentNativePath`和`ConfigDir`到 `JuiceAgent` 中,由`JuiceAgent`读取配置文件继续进行操作
|
- [x] `libloader` 读取配置文件并传参`JuiceAgentNativePath`和`ConfigDir`到 `JuiceAgent` 中,由`JuiceAgent`读取配置文件继续进行操作
|
||||||
|
- [x] 替换toml库
|
||||||
## 2026-04-19
|
- [x] 重构 `libloader` 的配置系统
|
||||||
- [x] 在 `JuiceAgent/Utils.hpp`做序列化操作
|
|
||||||
- [x] 统一调用 module的Java实现
|
|
||||||
|
|
||||||
## 2026-04-20
|
|
||||||
- [x] 修改文档
|
|
||||||
+1
-1
@@ -1 +1 @@
|
|||||||
VERSION = Version 3.3 Build 2
|
VERSION = Version 3.2 Build 1 PreRelease
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
# 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>");
|
|
||||||
```
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
[JuiceAgent]
|
|
||||||
Version = 1
|
|
||||||
|
|
||||||
[JuiceAgent.Loader]
|
|
||||||
JuiceAgentAPIJarPath = ""
|
|
||||||
JuiceAgentNativeLibraryPath = ""
|
|
||||||
|
|
||||||
[JuiceAgent.Modules]
|
|
||||||
|
|
||||||
[JuiceAgent.Modules.JarLoader]
|
|
||||||
Enabled = true
|
|
||||||
InjectionDir = ""
|
|
||||||
JarPath = ""
|
|
||||||
EntryClass = ""
|
|
||||||
EntryMethod = ""
|
|
||||||
|
|
||||||
+151
-131
@@ -1,164 +1,184 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <JuiceAgent/Logger.hpp>
|
|
||||||
#include <JuiceAgent/JuiceAgent.hpp>
|
|
||||||
#include <toml.hpp>
|
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
|
#include <sstream>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <JuiceAgent/Utils.hpp>
|
#include <vector>
|
||||||
|
|
||||||
|
#include <JuiceAgent/Logger.hpp>
|
||||||
|
#include <toml.hpp>
|
||||||
|
|
||||||
namespace JuiceAgent::Config {
|
namespace JuiceAgent::Config {
|
||||||
|
|
||||||
class Config {
|
class Config {
|
||||||
private:
|
|
||||||
std::filesystem::path _runtime_dir;
|
|
||||||
toml::value _config;
|
|
||||||
bool _valid = false;
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
template<typename T>
|
std::filesystem::path config_dir_;
|
||||||
static T _read_value(const toml::value& v) {
|
toml::value data_;
|
||||||
if constexpr (std::is_same_v<T, std::string>) {
|
bool valid_ = false;
|
||||||
return v.as_string();
|
|
||||||
} else if constexpr (std::is_same_v<T, bool>) {
|
private:
|
||||||
return v.as_boolean();
|
// Split "A.B.C" -> {"A", "B", "C"}
|
||||||
} else if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool>) {
|
static std::vector<std::string> split_path(const std::string& path) {
|
||||||
return static_cast<T>(v.as_integer());
|
std::vector<std::string> result;
|
||||||
} else if constexpr (std::is_floating_point_v<T>) {
|
std::stringstream stream(path);
|
||||||
return static_cast<T>(v.as_floating());
|
std::string token;
|
||||||
} else {
|
|
||||||
static_assert(sizeof(T) == 0, "Unsupported config type");
|
while (std::getline(stream, token, '.')) {
|
||||||
|
if (!token.empty()) {
|
||||||
|
result.push_back(token);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Find node by dot path
|
||||||
|
const toml::value* find(const std::string& path) const {
|
||||||
|
const toml::value* current = &data_;
|
||||||
|
|
||||||
|
for (const auto& key : split_path(path)) {
|
||||||
|
if (!current->is_table()) {
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!current->contains(key)) {
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
current = ¤t->at(key);
|
||||||
|
}
|
||||||
|
|
||||||
|
return current;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Load and parse config file
|
||||||
|
void load() {
|
||||||
|
if (!std::filesystem::exists(config_dir_)) {
|
||||||
|
PLOGE << "Config directory not found: " << config_dir_;
|
||||||
|
config_dir_ = std::filesystem::current_path();
|
||||||
|
PLOGW << "Using runtime directory: " << std::filesystem::current_path();
|
||||||
|
}
|
||||||
|
|
||||||
|
const auto path = config_dir_ / "config.toml";
|
||||||
|
|
||||||
|
if (!std::filesystem::exists(path)) {
|
||||||
|
PLOGE << "Config file not found: " << path;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
data_ = toml::parse(path);
|
||||||
|
valid_ = true;
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
PLOGE << "Failed to parse config: " << e.what();
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public:
|
public:
|
||||||
explicit Config(const std::filesystem::path& runtime_dir = {})
|
explicit Config(std::filesystem::path dir)
|
||||||
{
|
: config_dir_(std::move(dir)) {
|
||||||
_runtime_dir = runtime_dir.empty()
|
load();
|
||||||
? std::filesystem::current_path()
|
|
||||||
: runtime_dir;
|
|
||||||
|
|
||||||
const auto result = toml::try_parse(_runtime_dir / "config.toml");
|
|
||||||
|
|
||||||
if (result.is_ok()) {
|
|
||||||
_config = result.unwrap();
|
|
||||||
_valid = true;
|
|
||||||
} else {
|
|
||||||
PLOGE << "Failed to parse config.toml";
|
|
||||||
|
|
||||||
for (const auto& err : result.unwrap_err()) {
|
|
||||||
PLOGE << toml::format_error(err);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
bool is_valid() const noexcept {
|
public:
|
||||||
return _valid;
|
bool is_valid() const {
|
||||||
|
return valid_;
|
||||||
}
|
}
|
||||||
|
|
||||||
const toml::value& get_config() const noexcept {
|
bool contains(const std::string& path) const {
|
||||||
return _config;
|
return find(path) != nullptr;
|
||||||
}
|
|
||||||
|
|
||||||
const std::filesystem::path& runtime_dir() const noexcept {
|
|
||||||
return _runtime_dir;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
template<typename T>
|
template<typename T>
|
||||||
T get(const std::string& path, const T& default_value, bool is_path = false) const {
|
T get(const std::string& path) const {
|
||||||
if (!_valid) {
|
const auto* node = find(path);
|
||||||
|
|
||||||
|
if (!node) {
|
||||||
|
throw std::runtime_error("Config key not found: " + path);
|
||||||
|
}
|
||||||
|
|
||||||
|
return toml::get<T>(*node);
|
||||||
|
}
|
||||||
|
|
||||||
|
template<typename T>
|
||||||
|
T get_or(const std::string& path, const T& default_value) const {
|
||||||
|
const auto* node = find(path);
|
||||||
|
|
||||||
|
if (!node) {
|
||||||
return default_value;
|
return default_value;
|
||||||
}
|
}
|
||||||
|
|
||||||
try {
|
try {
|
||||||
const toml::value* current = &_config;
|
auto result = toml::get<T>(*node);
|
||||||
std::size_t start = 0;
|
if (result.empty())
|
||||||
|
return default_value;
|
||||||
while (start < path.size()) {
|
return result;
|
||||||
const std::size_t end = path.find('.', start);
|
} catch (...) {
|
||||||
const std::string key = path.substr(
|
|
||||||
start,
|
|
||||||
end == std::string::npos ? std::string::npos : end - start
|
|
||||||
);
|
|
||||||
|
|
||||||
current = ¤t->at(key);
|
|
||||||
|
|
||||||
if (end == std::string::npos) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
start = end + 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
std::string get_path_or_default(const std::string& path, const std::string& default_value) const {
|
||||||
|
std::string result = get_or<std::string>(path, default_value);
|
||||||
|
if(result.starts_with(".")) {
|
||||||
|
result.erase(0, 1);
|
||||||
|
|
||||||
|
// Check if string starts with '/'
|
||||||
|
// MUST REMOVE '/', or it will cause path error (root directory)
|
||||||
|
if (result.starts_with('/')) {
|
||||||
|
result.erase(0, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
result = (config_dir_ / result).string();
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
InjectionInfo get_injection_info() const {
|
||||||
|
InjectionInfo info;
|
||||||
|
|
||||||
|
auto get_default_path = [&](const std::string& name) {
|
||||||
|
return (std::filesystem::path(config_dir_) / name).string();
|
||||||
|
};
|
||||||
|
|
||||||
|
info.JuiceAgentAPIJarPath = get_path_or_default("Loader.JuiceAgentAPIJarPath", get_default_path("JuiceAgentAPI.jar"));
|
||||||
|
info.JuiceAgentNativeLibraryPath = get_path_or_default("Loader.JuiceAgentNativeLibraryPath", get_default_path("libagent.dll"));
|
||||||
|
info.ConfigDir = config_dir_.string();
|
||||||
|
|
||||||
|
return info;
|
||||||
|
}
|
||||||
|
|
||||||
|
static std::string serialize(InjectionInfo info) {
|
||||||
|
|
||||||
|
auto escape = [](const std::string& value) -> std::string {
|
||||||
|
std::string result;
|
||||||
|
result.reserve(value.size());
|
||||||
|
|
||||||
|
for (char ch : value) {
|
||||||
|
if (ch == ';' || ch == '=' || ch == '\\') {
|
||||||
|
result += '\\';
|
||||||
|
}
|
||||||
|
result += ch;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
};
|
||||||
|
|
||||||
|
return
|
||||||
|
"JuiceAgentAPIJarPath=" + escape(info.JuiceAgentAPIJarPath) + ";" +
|
||||||
|
"JuiceAgentNativeLibraryPath=" + escape(info.JuiceAgentNativeLibraryPath) + ";" +
|
||||||
|
"ConfigDir=" + escape(info.ConfigDir);
|
||||||
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
namespace Utils {
|
void print_injection_info(const InjectionInfo& info) {
|
||||||
inline LoaderConfig get_loader_config(const Config& config) {
|
|
||||||
auto cfg = config.get_config().at("JuiceAgent").at("Loader");
|
PLOGI << "JuiceAgentAPIJarPath: " << info.JuiceAgentAPIJarPath;
|
||||||
|
PLOGI << "JuiceAgentNativeLibraryPath: " << info.JuiceAgentNativeLibraryPath;
|
||||||
LoaderConfig loader_config = LoaderConfig();
|
PLOGI << "ConfigDir: " << info.ConfigDir;
|
||||||
loader_config.JuiceAgentAPIJarPath = cfg.at("JuiceAgentAPIJarPath").as_string();
|
|
||||||
loader_config.JuiceAgentNativeLibraryPath = cfg.at("JuiceAgentNativeLibraryPath").as_string();
|
|
||||||
loader_config.RuntimeDir = config.runtime_dir().string();
|
|
||||||
|
|
||||||
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 JuiceAgent::Config
|
} // namespace JuiceAgent::Config
|
||||||
@@ -2,9 +2,9 @@
|
|||||||
|
|
||||||
#include <string>
|
#include <string>
|
||||||
|
|
||||||
struct LoaderConfig {
|
struct InjectionInfo {
|
||||||
std::string JuiceAgentAPIJarPath;
|
std::string JuiceAgentAPIJarPath;
|
||||||
std::string JuiceAgentNativeLibraryPath;
|
std::string JuiceAgentNativeLibraryPath;
|
||||||
|
|
||||||
std::string RuntimeDir;
|
std::string ConfigDir;
|
||||||
};
|
};
|
||||||
@@ -3,16 +3,15 @@
|
|||||||
#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/ColorConsoleAppender.h>
|
#include <plog/Appenders/ConsoleAppender.h>
|
||||||
#include <plog/Appenders/DebugOutputAppender.h>
|
#include <plog/Appenders/DebugOutputAppender.h>
|
||||||
#include <plog/Appenders/RollingFileAppender.h>
|
|
||||||
|
|
||||||
inline void InitLogger()
|
inline void InitLogger()
|
||||||
{
|
{
|
||||||
static plog::ColorConsoleAppender<plog::TxtFormatter> colorConsoleAppender;
|
static plog::ConsoleAppender<plog::TxtFormatter> consoleAppender;
|
||||||
static plog::DebugOutputAppender<plog::TxtFormatter> debugAppender;
|
static plog::DebugOutputAppender<plog::TxtFormatter> debugAppender;
|
||||||
|
|
||||||
plog::init(plog::debug, &colorConsoleAppender).addAppender(&debugAppender);
|
plog::init(plog::debug, &consoleAppender).addAppender(&debugAppender);
|
||||||
|
|
||||||
PLOG_INFO << "Logger initialized: Console + Debug Output";
|
PLOG_INFO << "Logger initialized: Console + Debug Output";
|
||||||
}
|
}
|
||||||
@@ -1,267 +0,0 @@
|
|||||||
#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
|
|
||||||
|
|
||||||
@@ -3,22 +3,11 @@
|
|||||||
|
|
||||||
// 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 , jstring j_runtime_dir) {
|
(JNIEnv *env, jclass loader_class) {
|
||||||
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;
|
||||||
|
|
||||||
@@ -38,7 +27,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, runtime_dir);
|
agent.init(jvm, env, jvmti);
|
||||||
|
|
||||||
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: (Ljava/lang/String;)Z
|
* Signature: ()Z
|
||||||
*/
|
*/
|
||||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init
|
||||||
(JNIEnv *, jclass, jstring);
|
(JNIEnv *, jclass);
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||||
|
|||||||
@@ -4,18 +4,13 @@
|
|||||||
#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;
|
||||||
@@ -29,19 +24,15 @@ namespace JuiceAgent {
|
|||||||
Agent& operator=(const Agent&) = delete;
|
Agent& operator=(const Agent&) = delete;
|
||||||
|
|
||||||
// EntryPoint
|
// EntryPoint
|
||||||
bool init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti, std::string& runtime_dir);
|
bool init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti);
|
||||||
|
|
||||||
// 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; }
|
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
@@ -1,17 +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;
|
|
||||||
};
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -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>(); \
|
|
||||||
} \
|
|
||||||
); \
|
|
||||||
}
|
|
||||||
|
|
||||||
+66
-89
@@ -3,7 +3,6 @@
|
|||||||
#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 =====
|
||||||
@@ -12,96 +11,74 @@ namespace JuiceAgent {
|
|||||||
return instance;
|
return instance;
|
||||||
}
|
}
|
||||||
|
|
||||||
bool Agent::init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti, std::string& runtime_dir) {
|
bool Agent::init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti) {
|
||||||
try {
|
PLOGI << "JuiceAgent Native EntryPoint Invoked!";
|
||||||
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;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -1,117 +0,0 @@
|
|||||||
#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
|
|
||||||
)
|
|
||||||
@@ -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();
|
|
||||||
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;
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
@@ -1,58 +0,0 @@
|
|||||||
#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,13 +1,40 @@
|
|||||||
#include <JuiceAgent/Logger.hpp>
|
#include <JuiceAgent/Logger.hpp>
|
||||||
#include <Loader.hpp>
|
#include <libloader.hpp>
|
||||||
#include <JuiceAgent/Config.hpp>
|
#include <JuiceAgent/Config.hpp>
|
||||||
#include <JvmManager.hpp>
|
#include <jvm.hpp>
|
||||||
#include <JuiceAgent/Utils.hpp>
|
|
||||||
|
|
||||||
namespace JuiceAgent::Loader {
|
namespace libloader {
|
||||||
|
|
||||||
|
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 LoaderConfig& config) {
|
bool invoke_juiceagent_init(JNIEnv* env, const InjectionInfo& info) {
|
||||||
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";
|
||||||
@@ -27,7 +54,7 @@ bool invoke_juiceagent_init(JNIEnv* env, const LoaderConfig& config) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Serialize InjectionInfo to string
|
// Serialize InjectionInfo to string
|
||||||
std::string args = JuiceAgent::Config::Utils::serialize_loader_config(config);
|
std::string args = JuiceAgent::Config::Config::serialize(info);
|
||||||
PLOGD << "Invoke args: " << args;
|
PLOGD << "Invoke args: " << args;
|
||||||
|
|
||||||
// Create Java string
|
// Create Java string
|
||||||
@@ -59,24 +86,21 @@ 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;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
PLOGI << cfg.get_path_or_default("Loader.JuiceAgentAPIJarPath", "NONE");
|
||||||
// Get InjectionInfo
|
// Get InjectionInfo
|
||||||
LoaderConfig config = JuiceAgent::Config::Utils::get_loader_config(cfg);
|
InjectionInfo info = cfg.get_injection_info();
|
||||||
JuiceAgent::Config::Utils::print_loader_config(config);
|
JuiceAgent::Config::print_injection_info(info);
|
||||||
|
|
||||||
// Validate essential paths
|
// Validate essential paths
|
||||||
if (config.JuiceAgentAPIJarPath.empty()) {
|
if (info.JuiceAgentAPIJarPath.empty()) {
|
||||||
PLOGE << "JuiceAgentAPIJarPath is empty, abort injection";
|
PLOGE << "JuiceAgentAPIJarPath is empty, abort injection";
|
||||||
return;
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
// Attach to JVM
|
// Attach to JVM
|
||||||
JuiceAgent::Loader::JvmManager::Jvm jvm;
|
jvm::Jvm jvm;
|
||||||
if (!jvm.attach()) {
|
if (!jvm.attach()) {
|
||||||
PLOGE << "Attach to JVM failed";
|
PLOGE << "Attach to JVM failed";
|
||||||
return;
|
return;
|
||||||
@@ -91,18 +115,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(config.JuiceAgentAPIJarPath.c_str());
|
jint status = jvmti->AddToSystemClassLoaderSearch(info.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: " << config.JuiceAgentAPIJarPath;
|
PLOGI << "Jar injected successfully: " << info.JuiceAgentAPIJarPath;
|
||||||
|
|
||||||
// Invoke JuiceAgent initialization
|
// Invoke JuiceAgent initialization
|
||||||
if (!invoke_juiceagent_init(env, config)) {
|
if (!invoke_juiceagent_init(env, info)) {
|
||||||
PLOGE << "invoke_juiceagent_init failed";
|
PLOGE << "invoke_juiceagent_init failed";
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
} // namespace JuiceAgent::Loader
|
} // namespace libloader
|
||||||
@@ -0,0 +1,246 @@
|
|||||||
|
#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;
|
||||||
|
}
|
||||||
@@ -1,31 +0,0 @@
|
|||||||
#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; }
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,195 @@
|
|||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <JuiceAgent/Logger.hpp>
|
||||||
|
#include <JuiceAgent/JuiceAgent.hpp>
|
||||||
|
#include <tinytoml/toml.h>
|
||||||
|
#include <filesystem>
|
||||||
|
#include <fstream>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
namespace JuiceAgent::Config {
|
||||||
|
|
||||||
|
class Config {
|
||||||
|
private:
|
||||||
|
std::string runtime_dir; // Runtime directory
|
||||||
|
toml::Value config{}; // Parsed TOML configuration
|
||||||
|
bool valid = false; // Whether the config is successfully loaded
|
||||||
|
|
||||||
|
// Escape special characters ';' = '\'
|
||||||
|
static std::string escape(const std::string& s) {
|
||||||
|
std::string out;
|
||||||
|
out.reserve(s.size());
|
||||||
|
for (char c : s) {
|
||||||
|
if (c == ';' || c == '=' || c == '\\') {
|
||||||
|
out += '\\';
|
||||||
|
}
|
||||||
|
out += c;
|
||||||
|
}
|
||||||
|
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:
|
||||||
|
explicit Config(const char* c_runtime_dir)
|
||||||
|
: runtime_dir(c_runtime_dir ? c_runtime_dir : "")
|
||||||
|
{
|
||||||
|
if (runtime_dir.empty()) {
|
||||||
|
PLOGW << "runtime_dir is empty";
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::filesystem::path path = std::filesystem::path(runtime_dir) / "config.toml";
|
||||||
|
std::ifstream ifs(path);
|
||||||
|
if (!ifs.is_open()) {
|
||||||
|
PLOGE << "Failed to open config file: " << path;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
try {
|
||||||
|
auto pr = toml::parse(ifs);
|
||||||
|
if (!pr.valid()) {
|
||||||
|
PLOGE << "Invalid TOML file: " << pr.errorReason;
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
config = pr.value;
|
||||||
|
valid = true;
|
||||||
|
} catch (const std::exception& e) {
|
||||||
|
PLOGE << "TOML parse error: " << e.what();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// Get value by key with default
|
||||||
|
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 {
|
||||||
|
const toml::Value* val = find_value(key);
|
||||||
|
if (!val) return default_value;
|
||||||
|
|
||||||
|
try {
|
||||||
|
if constexpr (std::is_same_v<T, std::string>) {
|
||||||
|
std::string s = val->as<std::string>();
|
||||||
|
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 '/'
|
||||||
|
// MUST REMOVE '/', or it will cause path error (root directory)
|
||||||
|
if (s.starts_with('/')) {
|
||||||
|
s.erase(0, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
// runtime_dir + s
|
||||||
|
s = (std::filesystem::path(runtime_dir) / s).string();
|
||||||
|
}
|
||||||
|
return s;
|
||||||
|
} else {
|
||||||
|
return val->as<T>();
|
||||||
|
}
|
||||||
|
} catch (...) {
|
||||||
|
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)
|
||||||
|
inline void print_injection_info(const InjectionInfo& info) {
|
||||||
|
PLOGI << "JuiceAgent Injection Info:";
|
||||||
|
PLOGI << " JuiceAgentAPIJarPath: " << info.JuiceAgentAPIJarPath;
|
||||||
|
PLOGI << " JuiceAgentNativePath: " << info.JuiceAgentNativePath;
|
||||||
|
PLOGI << " EntryJarPath: " << info.EntryJarPath;
|
||||||
|
PLOGI << " EntryClass: " << info.EntryClass;
|
||||||
|
PLOGI << " EntryMethod: " << info.EntryMethod;
|
||||||
|
PLOGI << " InjectionDir: " << info.InjectionDir;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace config
|
||||||
@@ -6,7 +6,7 @@
|
|||||||
#include <thread>
|
#include <thread>
|
||||||
#include <chrono>
|
#include <chrono>
|
||||||
|
|
||||||
namespace JuiceAgent::Loader::JvmManager
|
namespace jvm
|
||||||
{
|
{
|
||||||
class Jvm {
|
class Jvm {
|
||||||
private:
|
private:
|
||||||
@@ -119,4 +119,4 @@ namespace JuiceAgent::Loader::JvmManager
|
|||||||
|
|
||||||
thread_local JNIEnv* Jvm::env = nullptr;
|
thread_local JNIEnv* Jvm::env = nullptr;
|
||||||
|
|
||||||
} // namespace JuiceAgent::Loader::JvmManager
|
} // namespace jvm
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
#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
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
#include <windows.h>
|
#include <windows.h>
|
||||||
#include <JuiceAgent/Logger.hpp>
|
#include <JuiceAgent/Logger.hpp>
|
||||||
#include <Loader.hpp>
|
#include <libloader.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;
|
||||||
|
|
||||||
JuiceAgent::Loader::entrypoint(runtime_dir);
|
libloader::entrypoint(runtime_dir);
|
||||||
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in new issue
Block a user