mirror of
https://github.com/xiaozhou233/JuiceAgent.git
synced 2026-12-05 13:05:53 +08:00
Compare commits
32
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6fe467bccf | ||
|
|
4bed99f417 | ||
|
|
81905d6c3f | ||
|
|
6822c1dc63 | ||
|
|
27abc2bf6a | ||
|
|
4f433bc6ee | ||
|
|
20747124d1 | ||
|
|
4833b512f5 | ||
|
|
63dd69abc6 | ||
|
|
f38743e863 | ||
|
|
8e1b8b38e4 | ||
|
|
6962c4a477 | ||
|
|
6bf2d31798 | ||
|
|
6afa44f90a | ||
|
|
2ab1c134ed | ||
|
|
51bcfbd549 | ||
|
|
3b180e7199 | ||
|
|
b34377d447 | ||
|
|
f2ce4e6a5a | ||
|
|
757c5f70f0 | ||
|
|
78160a33a9 | ||
|
|
092110672a | ||
|
|
c5acf2aba0 | ||
|
|
316735cfef | ||
|
|
a1b0eb8b84 | ||
|
|
32e9199d4a | ||
|
|
56ebafd48d | ||
|
|
d304ededd5 | ||
|
|
7a4d8cb101 | ||
|
|
3303630a45 | ||
|
|
20fd69d239 | ||
|
|
b8a4b805c7 |
No files matched your search
@@ -0,0 +1,22 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2025 xiaozhou233
|
||||
All rights reserved.
|
||||
|
||||
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.
|
||||
@@ -1,11 +1,20 @@
|
||||
# JuiceAgent
|
||||
|
||||
[English](README.md) | [简体中文](README_ZH.md)
|
||||
|
||||
JuiceAgent is an advanced JVMTI-based injection framework for runtime JAR loading, bytecode transformation, and runtime JVM instrumentation. It injects into a running JVM process even when `DisableAttachMechanism=true`, without requiring `-javaagent` startup arguments or the attach mechanism.
|
||||
|
||||
**Warning**: This project is still experimental and is not recommended for production use. Use it at your own risk.
|
||||
|
||||
> **Tips**: Some antivirus software may flag JuiceAgent as malware. See [Antivirus False Positive Notice](docs/Antivirus-False-Positive.md) for details.
|
||||
|
||||
**Note**: This project is designed for a regular JVM. Custom JVMs may not be able to run it.
|
||||
|
||||
Welcome to join our QQ/Discord group for more information and support:
|
||||
- Discord: [JuiceDev](https://discord.gg/AQTnUyWNNJ)
|
||||
- QQ Group: 1103504356
|
||||
|
||||
|
||||

|
||||

|
||||

|
||||
@@ -76,10 +85,13 @@ The `JuiceAgent-API` jar is embedded in the native binaries, so no separate down
|
||||
|
||||
- `src/libloader` — `libloader.dll`. Injected into the target JVM. Attaches to the JVM, parses `config.toml`, injects the embedded `JuiceAgent-API`, and bootstraps the agent.
|
||||
- `src/libagent` — `libagent.dll`. The JVMTI agent. Registers callbacks (e.g. `ClassFileLoadHook`) and implements the native side of `JuiceAgent-API`.
|
||||
- `src/libinjector` — `injector.exe` + `libinject.dll`. Reflective DLL injector that loads `libloader.dll` into the target process. Can be driven from the command line or through JNI.
|
||||
- `src/injector` — `injector.exe`. Command-line driver that loads `libinject.dll` and injects `libloader.dll` into the target process.
|
||||
- `src/libinject` — `libinject.dll`. Reflective DLL injector. Exposes a native `inject` function and JNI bindings (`cn.xiaozhou233.juiceagent.injector.InjectorNative`).
|
||||
|
||||
## Quick Start
|
||||
|
||||
**You can also see the [examples](https://github.com/xiaozhou233/JuiceAgent/tree/main/examples) directory for more detailed usage examples.**
|
||||
|
||||
### 1. Download Release
|
||||
|
||||
Download `JuiceAgent_vx.x.x_x64.zip` from the [releases](https://github.com/xiaozhou233/JuiceAgent/releases) page.
|
||||
@@ -158,7 +170,25 @@ You can also pass arguments directly: `injector.exe <pid> <libloader.dll path> [
|
||||
|
||||
#### Method B: Use JNI to call `inject`
|
||||
|
||||
See [docs/Inject.md](docs/Inject.md) for details.
|
||||
Create `cn/xiaozhou233/juiceagent/injector/InjectorNative.java` in your project:
|
||||
|
||||
```java
|
||||
package cn.xiaozhou233.juiceagent.injector;
|
||||
|
||||
public class InjectorNative {
|
||||
public native boolean inject(int pid, String path);
|
||||
public native boolean inject(int pid, String path, String configDir);
|
||||
}
|
||||
```
|
||||
|
||||
Example:
|
||||
|
||||
```java
|
||||
System.load("<path-to-libinject.dll>");
|
||||
InjectorNative injectorNative = new InjectorNative();
|
||||
|
||||
injectorNative.inject(<pid>, "<path-to-libloader.dll>", "<path-to-config-directory>");
|
||||
```
|
||||
|
||||
### 5. Done
|
||||
|
||||
@@ -185,7 +215,7 @@ The following native functions are exposed to Java through the `cn.xiaozhou233.j
|
||||
## Examples
|
||||
|
||||
- `examples/load-via-injector-exe` — loads a JAR into a target JVM via `injector.exe` and runs an entry point.
|
||||
- `examples/retansform-class` — demonstrates class retransformation with a target JVM and a modified copy of the class.
|
||||
- `examples/retransform-class` — demonstrates class retransformation with a target JVM and a modified copy of the class.
|
||||
|
||||
## How To Build
|
||||
|
||||
@@ -202,7 +232,7 @@ The following native functions are exposed to Java through the `cn.xiaozhou233.j
|
||||
git clone https://github.com/xiaozhou233/JuiceAgent.git
|
||||
cd JuiceAgent
|
||||
|
||||
cmake --preset ninja-release
|
||||
cmake --preset release
|
||||
cmake --build build
|
||||
```
|
||||
|
||||
@@ -225,6 +255,5 @@ This project is intended for learning and research in controlled environments on
|
||||
## Acknowledgements
|
||||
|
||||
- [ReflectiveDLLInjection](https://github.com/stephenfewer/ReflectiveDLLInjection) — DLL injection implementation
|
||||
- [plog](https://github.com/SergiusTheBest/plog) — Portable, simple, and extensible C++ logging library
|
||||
- [spdlog](https://github.com/gabime/spdlog) — Fast C++ logging library
|
||||
- [toml11](https://github.com/ToruNiina/toml11) — TOML for Modern C++
|
||||
- [eventpp](https://github.com/wqking/eventpp) — C++ library for event dispatchers and callback lists
|
||||
+260
@@ -0,0 +1,260 @@
|
||||
# JuiceAgent
|
||||
|
||||
[English](README.md) | [简体中文](README_ZH.md)
|
||||
|
||||
> **注意**:本文档由 AI 自动翻译,可能存在不准确或不通顺之处,请以 [英文版 README](README.md) 为准。如有疑问欢迎提 issue 或 PR 修正。
|
||||
|
||||
JuiceAgent 是一个基于 JVMTI 的高级注入框架,用于运行时 JAR 加载、字节码变换和运行时 JVM 插桩。它可以在 `DisableAttachMechanism=true` 的情况下注入到正在运行的 JVM 进程中,无需 `-javaagent` 启动参数,也无需使用 attach 机制。
|
||||
|
||||
**警告**:本项目仍处于实验阶段,不建议用于生产环境。使用风险自负。
|
||||
|
||||
> **提示**:部分杀毒软件可能将 JuiceAgent 误报为恶意软件。详情见[杀毒软件误报说明](docs/Antivirus-False-Positive.md)。
|
||||
|
||||
**注意**:本项目针对标准 JVM 设计,自定义 JVM 可能无法运行。
|
||||
|
||||
欢迎加入我们的 QQ / Discord 群组获取更多信息和支持:
|
||||
- Discord:[JuiceDev](https://discord.gg/AQTnUyWNNJ)
|
||||
- QQ 群:1103504356
|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||

|
||||

|
||||

|
||||

|
||||

|
||||
|
||||

|
||||

|
||||

|
||||

|
||||
|
||||
## 目录
|
||||
|
||||
- [JuiceAgent](#juiceagent)
|
||||
- [简介](#简介)
|
||||
- [工作原理](#工作原理)
|
||||
- [特性](#特性)
|
||||
- [项目结构](#项目结构)
|
||||
- [快速开始](#快速开始)
|
||||
- [JuiceAgent API](#juiceagent-api)
|
||||
- [示例](#示例)
|
||||
- [如何构建](#如何构建)
|
||||
- [完整免责声明](#完整免责声明)
|
||||
- [致谢](#致谢)
|
||||
|
||||
## 简介
|
||||
|
||||
JuiceAgent 是 [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API) 的原生实现。它可以将外部 JAR 加载到正在运行的 JVM 中、调用指定的入口类/方法,并重新定义或重变换已加载的类——全程无需 `-javaagent` 启动参数,即使 `DisableAttachMechanism=true` 也能工作。
|
||||
|
||||
使用 JuiceAgent 可以做到:
|
||||
|
||||
- 将外部 JAR 动态加载到正在运行的 JVM 进程
|
||||
- 注入后调用指定的入口类和入口方法
|
||||
- 在运行时重新定义已加载的类
|
||||
- 重变换字节码以进行插桩或修改
|
||||
- 查询已加载的类并读取类的字节码
|
||||
|
||||
**如果你有任何问题或建议,欢迎提 issue 或提交 pull request。=D**
|
||||
|
||||
## 工作原理
|
||||
|
||||
1. `injector.exe`(或通过 JNI 调用 `libinject.dll`)将 `libloader.dll` 反射注入到目标 JVM 进程。
|
||||
2. `libloader.dll` 附加到 JVM,读取 `config.toml`,解出内嵌的 `JuiceAgent-API` jar 并将其加入系统类加载器的搜索路径。
|
||||
3. 加载器引导 agent:加载 `libagent.dll` 并初始化 JVMTI agent(`JuiceAgent::Agent`)。
|
||||
4. agent 注册 JVMTI 回调并启动配置的模块(例如 `JarLoader`),加载目标 JAR 并调用入口类/方法。
|
||||
|
||||
`JuiceAgent-API` jar 内嵌于原生二进制中,无需单独下载。
|
||||
|
||||
## 特性
|
||||
|
||||
- 将外部 JAR 加载到 Bootstrap 或 System ClassLoader
|
||||
- 将 JAR 添加到任意类加载器
|
||||
- 动态定义类
|
||||
- 按名称或类引用重新定义类
|
||||
- 按名称或类引用重变换类
|
||||
- 获取所有已加载的类
|
||||
- 按名称查找类
|
||||
- 按名称或类引用获取类的字节码
|
||||
- 自动附加 JVM,支持 `DisableAttachMechanism=true`
|
||||
|
||||
## 项目结构
|
||||
|
||||
- `src/libloader` — `libloader.dll`。注入到目标 JVM,附加 JVM、解析 `config.toml`、注入内嵌的 `JuiceAgent-API` 并引导 agent。
|
||||
- `src/libagent` — `libagent.dll`。JVMTI agent。注册回调(例如 `ClassFileLoadHook`)并实现 `JuiceAgent-API` 的原生侧。
|
||||
- `src/injector` — `injector.exe`。命令行驱动,加载 `libinject.dll` 并将 `libloader.dll` 注入到目标进程。
|
||||
- `src/libinject` — `libinject.dll`。反射式 DLL 注入器,导出原生 `inject` 函数并提供 JNI 绑定(`cn.xiaozhou233.juiceagent.injector.InjectorNative`)。
|
||||
|
||||
## 快速开始
|
||||
|
||||
**你也可以查看 [examples](https://github.com/xiaozhou233/JuiceAgent/tree/main/examples) 目录获取更详细的使用示例。**
|
||||
|
||||
### 1. 下载 Release
|
||||
|
||||
从 [releases](https://github.com/xiaozhou233/JuiceAgent/releases) 页面下载 `JuiceAgent_vx.x.x_x64.zip`。
|
||||
|
||||
解压 ZIP 到一个目录:
|
||||
|
||||
- YourDir
|
||||
- libagent.dll
|
||||
- libinject.dll
|
||||
- libloader.dll
|
||||
- injector.exe
|
||||
|
||||
### 2. 拷贝自定义 JAR / 依赖
|
||||
|
||||
- YourDir
|
||||
- libagent.dll
|
||||
- libinject.dll
|
||||
- libloader.dll
|
||||
- injector.exe
|
||||
- **MyCustomJar.jar**
|
||||
- **injection**
|
||||
- **Dependencies1.jar**
|
||||
- **Dependencies2.jar**
|
||||
|
||||
### 3. 编写配置
|
||||
|
||||
```toml
|
||||
[JuiceAgent]
|
||||
Version = 1
|
||||
|
||||
[JuiceAgent.Loader]
|
||||
# libagent.dll 的路径,默认是 "./libagent.dll"
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JuiceAgent.Modules]
|
||||
|
||||
[JuiceAgent.Modules.JarLoader]
|
||||
Enabled = true
|
||||
# 需要优先加载的依赖 JAR 所在目录
|
||||
InjectionDir = "./injection"
|
||||
# 要加载的 JAR 文件路径
|
||||
JarPath = "./MyCustomJar.jar"
|
||||
# 加载 JAR 后要执行的入口类
|
||||
EntryClass = "Example.Main"
|
||||
# 入口方法,必须是:public static void run()
|
||||
EntryMethod = "run"
|
||||
```
|
||||
|
||||
将文件保存为 `config.toml` 并放在同一目录(运行时目录)中。相对路径以运行时目录为基准解析。
|
||||
|
||||
- YourDir
|
||||
- **config.toml**
|
||||
- libagent.dll
|
||||
- libinject.dll
|
||||
- libloader.dll
|
||||
- injector.exe
|
||||
- MyCustomJar.jar
|
||||
- injection
|
||||
- Dependencies1.jar
|
||||
- Dependencies2.jar
|
||||
|
||||
### 4. 运行注入器
|
||||
|
||||
#### 方法 A:使用 `injector.exe`
|
||||
|
||||
在 `YourDir` 下运行 `injector.exe`:
|
||||
|
||||
```text
|
||||
<jps output>
|
||||
Input PID:
|
||||
```
|
||||
|
||||
输入目标 JVM 进程的 PID 并按回车。
|
||||
|
||||
也可以直接传参:`injector.exe <pid> <libloader.dll 路径> [libinject.dll 路径]`。
|
||||
|
||||
#### 方法 B:通过 JNI 调用 `inject`
|
||||
|
||||
在你的项目中创建 `cn/xiaozhou233/juiceagent/injector/InjectorNative.java`:
|
||||
|
||||
```java
|
||||
package cn.xiaozhou233.juiceagent.injector;
|
||||
|
||||
public class InjectorNative {
|
||||
public native boolean inject(int pid, String path);
|
||||
public native boolean inject(int pid, String path, String configDir);
|
||||
}
|
||||
```
|
||||
|
||||
示例:
|
||||
|
||||
```java
|
||||
System.load("<libinject.dll 的路径>");
|
||||
InjectorNative injectorNative = new InjectorNative();
|
||||
|
||||
injectorNative.inject(<pid>, "<libloader.dll 的路径>", "<配置文件所在目录>");
|
||||
```
|
||||
|
||||
### 5. 完成
|
||||
|
||||
目标 JVM 将加载指定的 JAR 并执行指定的入口类和入口方法。
|
||||
|
||||
## JuiceAgent API
|
||||
|
||||
以下原生函数通过 `cn.xiaozhou233.juiceagent.api.JuiceAgent` 类暴露给 Java(Java API 定义见 [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API) 项目):
|
||||
|
||||
- `init(String runtimeDir)` — 从 Java 初始化 agent
|
||||
- `addToBootstrapClassLoaderSearch(String jarPath)`
|
||||
- `addToSystemClassLoaderSearch(String jarPath)`
|
||||
- `addToClassLoader(String jarPath, ClassLoader targetClassLoader)`
|
||||
- `defineClass(ClassLoader targetClassLoader, byte[] bytes)` — 返回 `Class<?>`
|
||||
- `redefineClass(Class<?> clazz, byte[] classBytes, int length)`
|
||||
- `redefineClassByName(String className, byte[] classBytes, int length)`
|
||||
- `retransformClass(Class<?> clazz, byte[] bytecodes, int length)`
|
||||
- `retransformClassByName(String className, byte[] bytecodes, int length)`
|
||||
- `getLoadedClasses()` — 返回 `Class<?>[]`
|
||||
- `getClassByName(String name)` — 返回 `Class<?>`
|
||||
- `getClassBytes(Class<?> clazz)` — 返回 `byte[]`
|
||||
- `getClassBytesByName(String name)` — 返回 `byte[]`
|
||||
|
||||
## 示例
|
||||
|
||||
- `examples/load-via-injector-exe` — 通过 `injector.exe` 将 JAR 加载到目标 JVM 并运行入口点。
|
||||
- `examples/retransform-class` — 演示使用目标 JVM 和修改后的类副本进行类重变换。
|
||||
|
||||
## 如何构建
|
||||
|
||||
### 环境要求
|
||||
|
||||
- Java 8+
|
||||
- MinGW
|
||||
- CMake 3.15+
|
||||
- Ninja
|
||||
|
||||
### 使用 CMake Presets 构建
|
||||
|
||||
```powershell
|
||||
git clone https://github.com/xiaozhou233/JuiceAgent.git
|
||||
cd JuiceAgent
|
||||
|
||||
cmake --preset 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` 中。
|
||||
|
||||
## 完整免责声明
|
||||
|
||||
本项目仅用于受控环境下的学习与研究。作者不对因未授权使用、修改、破解或违反任何适用协议或法律所造成的后果负责。用户有责任确保其行为合法合规。
|
||||
|
||||
## 致谢
|
||||
|
||||
- [ReflectiveDLLInjection](https://github.com/stephenfewer/ReflectiveDLLInjection) — DLL 注入实现
|
||||
- [spdlog](https://github.com/gabime/spdlog) — 高性能 C++ 日志库
|
||||
- [toml11](https://github.com/ToruNiina/toml11) — 现代 C++ 的 TOML 库
|
||||
+1
-1
@@ -1 +1 @@
|
||||
Version = VERSION = Version 4.0.0 Build 1
|
||||
Version 4.1.0
|
||||
@@ -0,0 +1,21 @@
|
||||
# 杀毒软件误报说明 / Antivirus False Positive Notice
|
||||
|
||||
## 中文
|
||||
|
||||
JuiceAgent 的 `libloader.dll` 在部分杀毒软件中可能被误报为恶意程序。原因如下:
|
||||
|
||||
1. **进程注入技术**:本项目需通过远程线程将 DLL 注入到目标 JVM 进程(`VirtualAllocEx` + `WriteProcessMemory` + `CreateRemoteThread`),这是杀软对"进程注入"行为的常见告警特征。
|
||||
2. **反射加载(Reflective Loading)**:`libloader.dll` 使用反射加载器在内存中手动解析 PE 并加载,不经过常规的 `LoadLibrary` 加载流程,与部分恶意软件(无文件攻击)的技术高度相似。
|
||||
3. **API 哈希**:为规避导入表,代码使用哈希解析 `LoadLibrary`/`GetProcAddress` 等 API,该手法也是杀软重点检测的静态特征。
|
||||
|
||||
以上技术均为实现 JVMTI 运行时注入所必需,项目本身不包含任何恶意行为。由于这些行为与恶意软件特征高度重合,**无法完全消除误报**。请在使用前自行判断风险,或将其加入杀软白名单。
|
||||
|
||||
## English
|
||||
|
||||
`libloader.dll` in JuiceAgent may be flagged as malware by some antivirus software. The reasons are as follows:
|
||||
|
||||
1. **Process Injection**: This project injects a DLL into the target JVM process via a remote thread (`VirtualAllocEx` + `WriteProcessMemory` + `CreateRemoteThread`). Process injection is a common behavior signature that antivirus engines flag.
|
||||
2. **Reflective Loading**: `libloader.dll` uses a reflective loader to manually parse and map a PE image in memory, bypassing the normal `LoadLibrary` loading flow. This closely resembles fileless malware techniques.
|
||||
3. **API Hashing**: The code resolves APIs such as `LoadLibrary`/`GetProcAddress` by hash instead of using an import table, a static feature also heavily targeted by AV engines.
|
||||
|
||||
These techniques are all required to implement JVMTI runtime injection. The project itself contains no malicious behavior. However, because these behaviors closely overlap with malware signatures, **false positives cannot be completely eliminated**. Please assess the risk before use, or add the binaries to your antivirus whitelist.
|
||||
@@ -0,0 +1,24 @@
|
||||
# Advanced
|
||||
|
||||
## Load Custom API / Directly Load Jar
|
||||
WARN: This feature didn't implement yet.
|
||||
|
||||
### Describe
|
||||
JuiceAgent loads custom JARs through the following workflow:
|
||||
|
||||
1. Inject `libloader` into the target process.
|
||||
2. Load **JuiceAgent-API** and execute its initialization entry point.
|
||||
3. Invoke the `JarLoader` from **JuiceAgent-API** to load the specified JAR into the JVM.
|
||||
|
||||
The second step is fully customizable. You can replace **JuiceAgent-API** with your own JAR and call any class method you specify.
|
||||
|
||||
### Configuration
|
||||
|
||||
Set the following environment variables before launching `libloader`:
|
||||
|
||||
```bat
|
||||
set JUICEAGENT_API_ENABLED=true
|
||||
set JUICEAGENT_API_JAR=<path-to-your-jar>
|
||||
set JUICEAGENT_API_CLASS=<target-class-name>
|
||||
set JUICEAGENT_API_METHOD=<target-method-name>
|
||||
```
|
||||
@@ -0,0 +1,25 @@
|
||||
# Examples
|
||||
|
||||
A collection of JuiceAgent examples demonstrating different ways to inject
|
||||
JuiceAgent into a running JVM process.
|
||||
|
||||
## 1. inject-via-java-api
|
||||
|
||||
Inject JuiceAgent into a running JVM using the Java API (JNI), without needing `injector.exe`.
|
||||
|
||||
- [HowToUse.md](./inject-via-java-api/HowToUse.md)
|
||||
- [如何使用.md](./inject-via-java-api/如何使用.md)
|
||||
|
||||
## 2. load-via-injector-exe
|
||||
|
||||
Inject a JAR into a running JVM using `injector.exe`.
|
||||
|
||||
- [HowToUse.md](./load-via-injector-exe/HowToUse.md)
|
||||
- [如何使用.md](./load-via-injector-exe/如何使用.md)
|
||||
|
||||
## 3. retransform-class
|
||||
|
||||
Retransform an already-loaded class at runtime after injection, without restarting the JVM.
|
||||
|
||||
- [HowToUse.md](./retransform-class/HowToUse.md)
|
||||
- [如何使用.md](./retransform-class/如何使用.md)
|
||||
@@ -0,0 +1,24 @@
|
||||
# Examples
|
||||
|
||||
JuiceAgent 示例集合,演示将 JuiceAgent 注入到正在运行的 JVM 进程的不同方式。
|
||||
|
||||
## 1. inject-via-java-api
|
||||
|
||||
使用 Java API(JNI)将 JuiceAgent 注入正在运行的 JVM,无需使用 `injector.exe`。
|
||||
|
||||
- [HowToUse.md](./inject-via-java-api/HowToUse.md)
|
||||
- [如何使用.md](./inject-via-java-api/如何使用.md)
|
||||
|
||||
## 2. load-via-injector-exe
|
||||
|
||||
使用 `injector.exe` 将 JAR 注入正在运行的 JVM。
|
||||
|
||||
- [HowToUse.md](./load-via-injector-exe/HowToUse.md)
|
||||
- [如何使用.md](./load-via-injector-exe/如何使用.md)
|
||||
|
||||
## 3. retransform-class
|
||||
|
||||
注入后在运行时热替换(retransform)已加载的类,无需重启 JVM。
|
||||
|
||||
- [HowToUse.md](./retransform-class/HowToUse.md)
|
||||
- [如何使用.md](./retransform-class/如何使用.md)
|
||||
@@ -0,0 +1,97 @@
|
||||
# How to Use — inject-via-java-api (JuiceAgent)
|
||||
|
||||
This example demonstrates injecting JuiceAgent into a running JVM process
|
||||
using the Java API (JNI), without needing `injector.exe`.
|
||||
|
||||
## Prerequisites
|
||||
|
||||
- Java 8+ installed and available in `PATH`
|
||||
- JuiceAgent native DLLs (`libinject.dll`, `libloader.dll`, `libagent.dll`)
|
||||
placed in the same directory as this example
|
||||
- A `config.toml` file configured for your use case
|
||||
|
||||
## Quick Start
|
||||
|
||||
### Step 1: Build
|
||||
|
||||
Run `build.bat` to compile both the injector and the target jars:
|
||||
|
||||
```
|
||||
> build.bat
|
||||
```
|
||||
|
||||
### Step 2: Run the Target JVM
|
||||
|
||||
Open a terminal and start the target JVM:
|
||||
|
||||
```
|
||||
> run.bat
|
||||
```
|
||||
|
||||
The target JVM will start and print its PID periodically. Keep it running.
|
||||
|
||||
### Step 3: Run the Injector
|
||||
|
||||
Open another terminal and run the injector:
|
||||
|
||||
```
|
||||
> run_injector.bat
|
||||
```
|
||||
|
||||
You will be prompted to enter:
|
||||
|
||||
- `PID` : the target JVM process ID (shown in the target terminal)
|
||||
- `DLL` : path to `libinject.dll` (e.g. `.\libinject.dll`)
|
||||
- `config_path` : directory containing `config.toml` (leave empty for current dir)
|
||||
|
||||
### Step 4: Verify
|
||||
|
||||
If the injection is successful, the target JVM will load the JAR specified
|
||||
in `config.toml` and execute its entry method.
|
||||
|
||||
## Files
|
||||
|
||||
| File | Description |
|
||||
| --- | --- |
|
||||
| `build.bat` | Build all jars (injector + target) |
|
||||
| `run.bat` | Start the target JVM |
|
||||
| `run_injector.bat` | Run the JavaInjector to inject into the target JVM |
|
||||
| `config.toml` | JuiceAgent configuration file |
|
||||
| `injector/` | JavaInjector source code and build script |
|
||||
| `target/` | Target JVM source code and build script |
|
||||
|
||||
## Configuration (config.toml)
|
||||
|
||||
```toml
|
||||
[JuiceAgent]
|
||||
Version = 1
|
||||
|
||||
[JuiceAgent.Loader]
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JuiceAgent.Modules]
|
||||
|
||||
[JuiceAgent.Modules.JarLoader]
|
||||
Enabled = true
|
||||
InjectionDir = "./injection"
|
||||
JarPath = "./demo.jar"
|
||||
EntryClass = "Example.Main"
|
||||
EntryMethod = "run"
|
||||
```
|
||||
|
||||
- `JarPath`: the JAR to load into the target JVM
|
||||
- `EntryClass`: the fully qualified class name with the entry method
|
||||
- `EntryMethod`: must be a `public static void` method with no parameters
|
||||
- `InjectionDir`: directory containing dependency JARs loaded before the main JAR
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- `Error: JuiceAgent-JavaInjector-1.0-SNAPSHOT.jar not found`:
|
||||
Run `build.bat` first to compile the injector.
|
||||
|
||||
- `java.lang.UnsatisfiedLinkError`:
|
||||
Ensure `libinject.dll` is in the current directory or provide the full path.
|
||||
|
||||
- Injection has no effect:
|
||||
Verify that `config.toml` is in the directory you specified as `config_path`,
|
||||
and that the paths inside `config.toml` are correct relative to that directory.
|
||||
@@ -0,0 +1,80 @@
|
||||
How to Use -- inject-via-java-api (JuiceAgent)
|
||||
|
||||
This example demonstrates injecting JuiceAgent into a running JVM process
|
||||
using the Java API (JNI), without needing injector.exe.
|
||||
|
||||
Prerequisites:
|
||||
- Java 8+ installed and available in PATH
|
||||
- JuiceAgent native DLLs (libinject.dll, libloader.dll, libagent.dll)
|
||||
placed in the same directory as this example
|
||||
- A config.toml file configured for your use case
|
||||
|
||||
Quick Start
|
||||
============
|
||||
|
||||
Step 1: Build
|
||||
Run build.bat to compile both the injector and the target jars:
|
||||
> build.bat
|
||||
|
||||
Step 2: Run the Target JVM
|
||||
Open a terminal and start the target JVM:
|
||||
> run.bat
|
||||
The target JVM will start and print its PID periodically. Keep it running.
|
||||
|
||||
Step 3: Run the Injector
|
||||
Open another terminal and run the injector:
|
||||
> run_injector.bat
|
||||
You will be prompted to enter:
|
||||
- PID : the target JVM process ID (shown in the target terminal)
|
||||
- DLL : path to libinject.dll (e.g. .\libinject.dll)
|
||||
- config_path : directory containing config.toml (leave empty for current dir)
|
||||
|
||||
Step 4: Verify
|
||||
If the injection is successful, the target JVM will load the JAR specified
|
||||
in config.toml and execute its entry method.
|
||||
|
||||
Files
|
||||
======
|
||||
|
||||
build.bat - Build all jars (injector + target)
|
||||
run.bat - Start the target JVM
|
||||
run_injector.bat - Run the JavaInjector to inject into the target JVM
|
||||
config.toml - JuiceAgent configuration file
|
||||
injector/ - JavaInjector source code and build script
|
||||
target/ - Target JVM source code and build script
|
||||
|
||||
Configuration (config.toml)
|
||||
============================
|
||||
|
||||
[JuiceAgent]
|
||||
Version = 1
|
||||
|
||||
[JuiceAgent.Loader]
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JuiceAgent.Modules]
|
||||
|
||||
[JuiceAgent.Modules.JarLoader]
|
||||
Enabled = true
|
||||
InjectionDir = "./injection"
|
||||
JarPath = "./demo.jar"
|
||||
EntryClass = "Example.Main"
|
||||
EntryMethod = "run"
|
||||
|
||||
- JarPath: the JAR to load into the target JVM
|
||||
- EntryClass: the fully qualified class name with the entry method
|
||||
- EntryMethod: must be a public static void method with no parameters
|
||||
- InjectionDir: directory containing dependency JARs loaded before the main JAR
|
||||
|
||||
Troubleshooting
|
||||
================
|
||||
|
||||
- "Error: JuiceAgent-JavaInjector-1.0-SNAPSHOT.jar not found":
|
||||
Run build.bat first to compile the injector.
|
||||
|
||||
- "java.lang.UnsatisfiedLinkError":
|
||||
Ensure libinject.dll is in the current directory or provide the full path.
|
||||
|
||||
- Injection has no effect:
|
||||
Verify that config.toml is in the directory you specified as config_path,
|
||||
and that the paths inside config.toml are correct relative to that directory.
|
||||
@@ -0,0 +1,23 @@
|
||||
@echo off
|
||||
echo === Building injector jar ===
|
||||
pushd injector
|
||||
call build.bat
|
||||
popd
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
echo.
|
||||
echo === Building target jar ===
|
||||
pushd target
|
||||
call build.bat
|
||||
popd
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
echo.
|
||||
echo Build finished: JuiceAgent-JavaInjector-1.0-SNAPSHOT.jar and target.jar are ready.
|
||||
goto :end
|
||||
|
||||
:error
|
||||
echo Build failed.
|
||||
exit /b 1
|
||||
|
||||
:end
|
||||
@@ -0,0 +1,14 @@
|
||||
[JuiceAgent]
|
||||
Version = 1
|
||||
|
||||
[JuiceAgent.Loader]
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JuiceAgent.Modules]
|
||||
|
||||
[JuiceAgent.Modules.JarLoader]
|
||||
Enabled = true
|
||||
InjectionDir = "./injection"
|
||||
JarPath = "./demo.jar"
|
||||
EntryClass = "Example.Main"
|
||||
EntryMethod = "run"
|
||||
@@ -0,0 +1,35 @@
|
||||
import cn.xiaozhou233.juiceagent.injector.Injector;
|
||||
import cn.xiaozhou233.juiceagent.injector.WindowInfo;
|
||||
|
||||
import java.util.Scanner;
|
||||
import java.io.File;
|
||||
|
||||
public class JavaInjector {
|
||||
public static void main(String[] args) {
|
||||
// Load the native library
|
||||
System.load(new File("./libinject.dll").getAbsolutePath());
|
||||
|
||||
// Find windows by title
|
||||
for (WindowInfo window : Injector.findWindowsByTitle("cmd")) {
|
||||
System.out.println(window.toString());
|
||||
}
|
||||
System.out.println("----------------");
|
||||
|
||||
Scanner scanner = new Scanner(System.in);
|
||||
|
||||
// Input
|
||||
System.out.println("PID: ");
|
||||
String pid = scanner.nextLine();
|
||||
System.out.println("Dll: ");
|
||||
String dll = scanner.nextLine();
|
||||
System.out.println("config_path: ");
|
||||
String config_path = scanner.nextLine();
|
||||
|
||||
if (config_path == null || config_path.isEmpty()) {
|
||||
// config_path is empty
|
||||
Injector.inject(Integer.parseInt(pid), dll);
|
||||
} else {
|
||||
Injector.inject(Integer.parseInt(pid), dll, config_path);
|
||||
}
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -0,0 +1,51 @@
|
||||
@echo off
|
||||
setlocal
|
||||
|
||||
set "OUT=out"
|
||||
set "JAR=JuiceAgent-JavaInjector-1.0-SNAPSHOT.jar"
|
||||
set "TMP=tmp_jar"
|
||||
|
||||
if not exist "%JAR%" (
|
||||
echo Error: %JAR% not found. Please restore the original jar.
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
if exist "%OUT%" rmdir /s /q "%OUT%"
|
||||
if exist "%TMP%" rmdir /s /q "%TMP%"
|
||||
|
||||
mkdir "%OUT%"
|
||||
mkdir "%TMP%"
|
||||
|
||||
javac -encoding UTF-8 --release 8 -cp "%JAR%" -d "%OUT%" JavaInjector.java
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
rem Extract existing jar (contains Injector/WindowInfo classes) into temp dir
|
||||
rem -J-XX:-UsePerfData prevents JVM from creating locked hsperfdata files in CWD
|
||||
pushd "%TMP%"
|
||||
jar -J-XX:-UsePerfData xf "..\%JAR%"
|
||||
popd
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
rem Remove any hsperfdata folder that may have leaked into the jar
|
||||
for /d %%D in ("%TMP%\hsperfdata_*") do rmdir /s /q "%%D"
|
||||
|
||||
rem Merge compiled JavaInjector.class into temp dir
|
||||
copy /y "%OUT%\JavaInjector.class" "%TMP%\JavaInjector.class" >nul
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
rem Repackage with Main-Class
|
||||
jar -J-XX:-UsePerfData --create --file "%JAR%" --main-class JavaInjector -C "%TMP%" .
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
rmdir /s /q "%OUT%"
|
||||
rmdir /s /q "%TMP%"
|
||||
|
||||
echo Build succeeded: %JAR%
|
||||
goto :end
|
||||
|
||||
:error
|
||||
echo Build failed.
|
||||
exit /b 1
|
||||
|
||||
:end
|
||||
endlocal
|
||||
@@ -0,0 +1,4 @@
|
||||
@echo off
|
||||
cd /d "%~dp0"
|
||||
java -jar target.jar
|
||||
pause
|
||||
@@ -0,0 +1,17 @@
|
||||
@echo off
|
||||
cd /d "%~dp0"
|
||||
|
||||
set "INJECTOR_JAR=injector\JuiceAgent-JavaInjector-1.0-SNAPSHOT.jar"
|
||||
|
||||
echo === Java API Injector ===
|
||||
echo.
|
||||
echo Make sure the target JVM is running (run.bat).
|
||||
echo.
|
||||
echo Usage: This script runs the JavaInjector which will prompt for:
|
||||
echo - PID: target JVM process ID
|
||||
echo - DLL: path to libloader.dll
|
||||
echo - config_path: directory containing config.toml (leave empty to use current dir)
|
||||
echo.
|
||||
|
||||
java -cp "%INJECTOR_JAR%" JavaInjector
|
||||
pause
|
||||
Binary file not shown.
@@ -0,0 +1,28 @@
|
||||
@echo off
|
||||
setlocal
|
||||
|
||||
set "SRC=target.java"
|
||||
set "OUT=out"
|
||||
set "JAR=..\target.jar"
|
||||
|
||||
if exist "%OUT%" rmdir /s /q "%OUT%"
|
||||
if exist "%JAR%" del /q "%JAR%"
|
||||
|
||||
mkdir "%OUT%"
|
||||
javac -encoding UTF-8 --release 8 -d "%OUT%" "%SRC%"
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
jar --create --file "%JAR%" --main-class target -C "%OUT%" .
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
rmdir /s /q "%OUT%"
|
||||
|
||||
echo Build succeeded: target.jar
|
||||
goto :end
|
||||
|
||||
:error
|
||||
echo Build failed.
|
||||
exit /b 1
|
||||
|
||||
:end
|
||||
endlocal
|
||||
@@ -0,0 +1,15 @@
|
||||
import java.lang.management.ManagementFactory;
|
||||
|
||||
public class target {
|
||||
public static void main(String[] args) {
|
||||
String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
|
||||
try {
|
||||
while (true) {
|
||||
System.out.println("[Target] I am the target JVM (PID: " + pid + ")");
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,96 @@
|
||||
# 如何使用 — inject-via-java-api (JuiceAgent)
|
||||
|
||||
本示例演示如何使用 Java API(JNI)将 JuiceAgent 注入到正在运行的 JVM 进程中,
|
||||
无需使用 `injector.exe`。
|
||||
|
||||
## 环境要求
|
||||
|
||||
- Java 8+ 已安装并在 `PATH` 中可用
|
||||
- JuiceAgent 原生 DLL(`libinject.dll`、`libloader.dll`、`libagent.dll`)
|
||||
已放置在本示例所在目录
|
||||
- 已根据实际需求配置好 `config.toml`
|
||||
|
||||
## 快速开始
|
||||
|
||||
### 步骤 1:构建
|
||||
|
||||
运行 `build.bat` 编译 injector 和 target 两个 jar:
|
||||
|
||||
```
|
||||
> build.bat
|
||||
```
|
||||
|
||||
### 步骤 2:启动目标 JVM
|
||||
|
||||
打开一个终端,启动目标 JVM:
|
||||
|
||||
```
|
||||
> run.bat
|
||||
```
|
||||
|
||||
目标 JVM 将启动并周期性打印其 PID。保持该窗口运行。
|
||||
|
||||
### 步骤 3:运行注入器
|
||||
|
||||
打开另一个终端,运行注入器:
|
||||
|
||||
```
|
||||
> run_injector.bat
|
||||
```
|
||||
|
||||
程序会提示你输入以下信息:
|
||||
|
||||
- `PID` — 目标 JVM 进程 ID(在目标 JVM 终端中显示)
|
||||
- `DLL` — `libinject.dll` 的路径(例如 `.\libinject.dll`)
|
||||
- `config_path` — `config.toml` 所在目录(留空则使用当前目录)
|
||||
|
||||
### 步骤 4:验证
|
||||
|
||||
注入成功后,目标 JVM 将加载 `config.toml` 中指定的 JAR 并执行其入口方法。
|
||||
|
||||
## 文件说明
|
||||
|
||||
| 文件 | 说明 |
|
||||
| --- | --- |
|
||||
| `build.bat` | 构建所有 jar(injector + target) |
|
||||
| `run.bat` | 启动目标 JVM |
|
||||
| `run_injector.bat` | 运行 JavaInjector,将 agent 注入目标 JVM |
|
||||
| `config.toml` | JuiceAgent 配置文件 |
|
||||
| `injector/` | JavaInjector 源码及构建脚本 |
|
||||
| `target/` | 目标 JVM 源码及构建脚本 |
|
||||
|
||||
## 配置说明(config.toml)
|
||||
|
||||
```toml
|
||||
[JuiceAgent]
|
||||
Version = 1
|
||||
|
||||
[JuiceAgent.Loader]
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JuiceAgent.Modules]
|
||||
|
||||
[JuiceAgent.Modules.JarLoader]
|
||||
Enabled = true
|
||||
InjectionDir = "./injection"
|
||||
JarPath = "./demo.jar"
|
||||
EntryClass = "Example.Main"
|
||||
EntryMethod = "run"
|
||||
```
|
||||
|
||||
- `JarPath`:要加载到目标 JVM 的 JAR 文件
|
||||
- `EntryClass`:包含入口方法的完整类名
|
||||
- `EntryMethod`:必须是 `public static void` 且无参数的方法
|
||||
- `InjectionDir`:依赖 JAR 所在的目录,这些 JAR 会在主 JAR 之前加载
|
||||
|
||||
## 常见问题
|
||||
|
||||
- `Error: JuiceAgent-JavaInjector-1.0-SNAPSHOT.jar not found`:
|
||||
请先运行 `build.bat` 编译 injector。
|
||||
|
||||
- `java.lang.UnsatisfiedLinkError`:
|
||||
请确保 `libinject.dll` 在当前目录下,或提供完整路径。
|
||||
|
||||
- 注入后无效果:
|
||||
请确认 `config.toml` 在你指定的 `config_path` 目录中,且 `config.toml`
|
||||
中的路径相对于该目录是正确的。
|
||||
@@ -0,0 +1,79 @@
|
||||
如何使用 -- inject-via-java-api (JuiceAgent)
|
||||
|
||||
本示例演示如何使用 Java API(JNI)将 JuiceAgent 注入到正在运行的 JVM 进程中,
|
||||
无需使用 injector.exe。
|
||||
|
||||
环境要求:
|
||||
- Java 8+ 已安装并在 PATH 中可用
|
||||
- JuiceAgent 原生 DLL(libinject.dll、libloader.dll、libagent.dll)
|
||||
已放置在本示例所在目录
|
||||
- 已根据实际需求配置好 config.toml
|
||||
|
||||
快速开始
|
||||
========
|
||||
|
||||
步骤 1:构建
|
||||
运行 build.bat 编译 injector 和 target 两个 jar:
|
||||
> build.bat
|
||||
|
||||
步骤 2:启动目标 JVM
|
||||
打开一个终端,启动目标 JVM:
|
||||
> run.bat
|
||||
目标 JVM 将启动并周期性打印其 PID。保持该窗口运行。
|
||||
|
||||
步骤 3:运行注入器
|
||||
打开另一个终端,运行注入器:
|
||||
> run_injector.bat
|
||||
程序会提示你输入以下信息:
|
||||
- PID :目标 JVM 进程 ID(在目标 JVM 终端中显示)
|
||||
- DLL :libinject.dll 的路径(例如 .\libinject.dll)
|
||||
- config_path :config.toml 所在目录(留空则使用当前目录)
|
||||
|
||||
步骤 4:验证
|
||||
注入成功后,目标 JVM 将加载 config.toml 中指定的 JAR 并执行其入口方法。
|
||||
|
||||
文件说明
|
||||
========
|
||||
|
||||
build.bat - 构建所有 jar(injector + target)
|
||||
run.bat - 启动目标 JVM
|
||||
run_injector.bat - 运行 JavaInjector,将 agent 注入目标 JVM
|
||||
config.toml - JuiceAgent 配置文件
|
||||
injector/ - JavaInjector 源码及构建脚本
|
||||
target/ - 目标 JVM 源码及构建脚本
|
||||
|
||||
配置说明(config.toml)
|
||||
=======================
|
||||
|
||||
[JuiceAgent]
|
||||
Version = 1
|
||||
|
||||
[JuiceAgent.Loader]
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JuiceAgent.Modules]
|
||||
|
||||
[JuiceAgent.Modules.JarLoader]
|
||||
Enabled = true
|
||||
InjectionDir = "./injection"
|
||||
JarPath = "./demo.jar"
|
||||
EntryClass = "Example.Main"
|
||||
EntryMethod = "run"
|
||||
|
||||
- JarPath:要加载到目标 JVM 的 JAR 文件
|
||||
- EntryClass:包含入口方法的完整类名
|
||||
- EntryMethod:必须是 public static void 且无参数的方法
|
||||
- InjectionDir:依赖 JAR 所在的目录,这些 JAR 会在主 JAR 之前加载
|
||||
|
||||
常见问题
|
||||
========
|
||||
|
||||
- "Error: JuiceAgent-JavaInjector-1.0-SNAPSHOT.jar not found":
|
||||
请先运行 build.bat 编译 injector。
|
||||
|
||||
- "java.lang.UnsatisfiedLinkError":
|
||||
请确保 libinject.dll 在当前目录下,或提供完整路径。
|
||||
|
||||
- 注入后无效果:
|
||||
请确认 config.toml 在你指定的 config_path 目录中,且 config.toml
|
||||
中的路径相对于该目录是正确的。
|
||||
@@ -0,0 +1,80 @@
|
||||
# HowToUse — load-via-injector-exe
|
||||
|
||||
**Prerequisites:** Java 8+ (`javac`/`jar` for building, `jps` for injection)
|
||||
|
||||
## Directory Files
|
||||
|
||||
| File | Description |
|
||||
| --- | --- |
|
||||
| `injector.exe` `libagent.dll` `libinject.dll` `libloader.dll` | JuiceAgent runtime |
|
||||
| `config.toml` | Injection config |
|
||||
| `demo.jar` | JAR to inject (built by `build.bat`) |
|
||||
| `target.jar` | Target JVM program (built by `build.bat`) |
|
||||
| `injection/` | Injection source |
|
||||
| `target/` | Target source |
|
||||
| `build.bat` | Rebuild `demo.jar` / `target.jar` |
|
||||
| `run.bat` | Run target JVM (`target.jar`) |
|
||||
|
||||
## Usage Steps
|
||||
|
||||
### 1. Build (optional)
|
||||
|
||||
`demo.jar` and `target.jar` are already included by default.
|
||||
If you modified `injection/Main.java` or `target/target.java`, run:
|
||||
|
||||
```
|
||||
build.bat
|
||||
```
|
||||
|
||||
to regenerate `demo.jar` and `target.jar` in this directory.
|
||||
|
||||
### 2. Run the target JVM
|
||||
|
||||
Double-click `run.bat` (or run: `java -jar target.jar`). A black window
|
||||
appears and prints:
|
||||
|
||||
```
|
||||
[Target] I am the target JVM (PID: <PID>)
|
||||
```
|
||||
|
||||
... (once per second)
|
||||
|
||||
### 3. Inject
|
||||
|
||||
Double-click `injector.exe`, type the target PID and press Enter:
|
||||
|
||||
```
|
||||
6644 target.jar
|
||||
10504 jdk.jcmd/sun.tools.jps.Jps
|
||||
Input PID: 6644
|
||||
```
|
||||
|
||||
### 4. Verify
|
||||
|
||||
Go back to the target window. Injection succeeded if you see:
|
||||
|
||||
```
|
||||
[Demo] Injection succeeded! Hello from JuiceAgent.
|
||||
[Demo] Current thread: Thread-0
|
||||
```
|
||||
|
||||
## Config / config.toml
|
||||
|
||||
| Key | Description |
|
||||
| --- | --- |
|
||||
| `JarPath` | JAR path to inject (default: `./demo.jar`) |
|
||||
| `EntryClass` | Entry class (default: `Example.Main`) |
|
||||
| `EntryMethod` | Entry method, must be `public static void run()` |
|
||||
| `InjectionDir` | Dependency JAR directory (only `*.jar` is loaded) |
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- `java/javac/jar is not recognized`:
|
||||
Install a JDK and add its `bin` directory to `PATH`.
|
||||
- `injector.exe` reports injection failure:
|
||||
Make sure the target JVM is running and the PID is correct.
|
||||
- No `[Demo]` output appears:
|
||||
The target window prints many log lines which may affect reading.
|
||||
Check the `[JuiceAgent JarLoader]` lines to locate the cause.
|
||||
If it still fails, copy the full log and submit an Issue, or paste
|
||||
it directly to an AI.
|
||||
@@ -0,0 +1,78 @@
|
||||
# 使用说明 — load-via-injector-exe
|
||||
|
||||
**前提条件:** 已安装 Java 8+(需要 `javac`/`jar` 构建,`jps` 用于注入)
|
||||
|
||||
## 目录文件说明
|
||||
|
||||
| 文件 | 说明 |
|
||||
| --- | --- |
|
||||
| `injector.exe` `libagent.dll` `libinject.dll` `libloader.dll` | JuiceAgent 运行时 |
|
||||
| `config.toml` | 注入配置 |
|
||||
| `demo.jar` | 待注入的 JAR(`build.bat` 生成) |
|
||||
| `target.jar` | 目标 JVM 程序(`build.bat` 生成) |
|
||||
| `injection/` | 注入代码源码 |
|
||||
| `target/` | 目标程序源码 |
|
||||
| `build.bat` | 重新生成 `demo.jar` / `target.jar` |
|
||||
| `run.bat` | 运行目标 JVM(`target.jar`) |
|
||||
|
||||
## 使用步骤
|
||||
|
||||
### 1. 构建(可选)
|
||||
|
||||
默认已包含 `demo.jar` 和 `target.jar`。
|
||||
若修改了 `injection/Main.java` 或 `target/target.java`,请运行:
|
||||
|
||||
```
|
||||
build.bat
|
||||
```
|
||||
|
||||
生成 `demo.jar` 和 `target.jar` 到本目录。
|
||||
|
||||
### 2. 运行目标 JVM
|
||||
|
||||
双击 `run.bat`(或执行 `java -jar target.jar`),出现黑色窗口并输出:
|
||||
|
||||
```
|
||||
[Target] I am the target JVM (PID: <PID>)
|
||||
```
|
||||
|
||||
...(每秒输出一次)
|
||||
|
||||
### 3. 注入
|
||||
|
||||
双击 `injector.exe`,出现黑色窗口,输入目标 PID 并回车:
|
||||
|
||||
```
|
||||
6644 target.jar
|
||||
10504 jdk.jcmd/sun.tools.jps.Jps
|
||||
Input PID: 6644
|
||||
```
|
||||
|
||||
### 4. 验证
|
||||
|
||||
回到目标窗口,看到以下输出即注入成功:
|
||||
|
||||
```
|
||||
[Demo] Injection succeeded! Hello from JuiceAgent.
|
||||
[Demo] Current thread: Thread-0
|
||||
```
|
||||
|
||||
## 配置说明 / config.toml
|
||||
|
||||
| 配置项 | 说明 |
|
||||
| --- | --- |
|
||||
| `JarPath` | 待注入的 JAR 路径(默认 `./demo.jar`) |
|
||||
| `EntryClass` | 入口类(默认 `Example.Main`) |
|
||||
| `EntryMethod` | 入口方法,需为 `public static void run()` |
|
||||
| `InjectionDir` | 依赖 JAR 目录(仅加载 `*.jar`) |
|
||||
|
||||
## 常见问题
|
||||
|
||||
- `java/javac/jar 不是内部或外部命令`:
|
||||
安装 JDK 并将其 `bin` 目录加入 `PATH`。
|
||||
- `injector.exe` 提示注入失败:
|
||||
确认目标 JVM 正在运行,且输入的 PID 正确。
|
||||
- 没有出现 `[Demo]` 输出:
|
||||
目标窗口会有大量日志,可能影响阅读;请查看其中的
|
||||
`[JuiceAgent JarLoader]` 日志定位原因。
|
||||
如仍无法解决,请复制完整日志提交 Issue,或直接丢给 AI。
|
||||
@@ -0,0 +1,109 @@
|
||||
# HowToUse — retransform-class
|
||||
|
||||
**Prerequisites:** Java 8+ (`javac`/`jar` for building, `jps` for injection)
|
||||
|
||||
## Directory Files
|
||||
|
||||
| File | Description |
|
||||
| --- | --- |
|
||||
| `injector.exe` `libagent.dll` `libinject.dll` `libloader.dll` | JuiceAgent runtime |
|
||||
| `config.toml` | Injection config |
|
||||
| `build.bat` | Build script |
|
||||
| `run.bat` | Run target JVM |
|
||||
| `playload.jar` | JAR to inject (built by `build.bat`) |
|
||||
| `target.jar` | Target JVM program (built by `build.bat`) |
|
||||
| `new_target.class` | Retransformed bytecode (built by `build.bat`) |
|
||||
| `playload/` | Payload source |
|
||||
| `target/` | Target source |
|
||||
| `new_target/` | Modified copy of target source |
|
||||
|
||||
## What This Example Does
|
||||
|
||||
The target class `target` has a method `say()` that prints:
|
||||
|
||||
```
|
||||
Hello!
|
||||
```
|
||||
|
||||
`new_target/target.java` is a modified copy that also prints:
|
||||
|
||||
```
|
||||
Retransformed!
|
||||
```
|
||||
|
||||
This example injects `playload.jar` into a running JVM. The payload reads
|
||||
`new_target.class` from its own JAR and calls
|
||||
`JuiceAgent.retransformClassByName("target", ...)` to swap the already-loaded
|
||||
`target` class on the fly. After that, `say()` starts printing the new message
|
||||
without restarting the JVM.
|
||||
|
||||
## Usage Steps
|
||||
|
||||
### 1. Build (optional)
|
||||
|
||||
`playload.jar` and `target.jar` are already included by default.
|
||||
If you modified `playload/`, `target/` or `new_target/`, run:
|
||||
|
||||
```
|
||||
build.bat
|
||||
```
|
||||
|
||||
to regenerate `playload.jar`, `target.jar` and `new_target.class`.
|
||||
|
||||
### 2. Run the target JVM
|
||||
|
||||
Double-click `run.bat` (or run: `java -jar target.jar`). A black window
|
||||
appears and prints:
|
||||
|
||||
```
|
||||
[Target] I am the target JVM (PID: <PID>)
|
||||
Hello!
|
||||
```
|
||||
|
||||
... (once per second)
|
||||
|
||||
### 3. Inject
|
||||
|
||||
Double-click `injector.exe`, type the target PID and press Enter:
|
||||
|
||||
```
|
||||
6644 target.jar
|
||||
10504 jdk.jcmd/sun.tools.jps.Jps
|
||||
Input PID: 6644
|
||||
```
|
||||
|
||||
### 4. Verify
|
||||
|
||||
Go back to the target window. Injection succeeded if you see:
|
||||
|
||||
```
|
||||
Playload loaded!
|
||||
Playload executed!
|
||||
```
|
||||
|
||||
and the output of `say()` changes from `Hello!` to:
|
||||
|
||||
```
|
||||
Hello!
|
||||
Retransformed!
|
||||
```
|
||||
|
||||
## Config / config.toml
|
||||
|
||||
| Key | Description |
|
||||
| --- | --- |
|
||||
| `JarPath` | JAR path to inject (default: `./playload.jar`) |
|
||||
| `EntryClass` | Entry class (default: `playload`) |
|
||||
| `EntryMethod` | Entry method, must be `public static void entry()` |
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
- `java/javac/jar is not recognized`:
|
||||
Install a JDK and add its `bin` directory to `PATH`.
|
||||
- `injector.exe` reports injection failure:
|
||||
Make sure the target JVM is running and the PID is correct.
|
||||
- No `Playload loaded!` output appears:
|
||||
Check `libagent.log` and `libloader.log` in this directory for the cause.
|
||||
- `say()` output does not change:
|
||||
Make sure `build.bat` was run after editing `new_target/`, and that
|
||||
`new_target.class` inside `playload.jar` is up to date.
|
||||
@@ -0,0 +1,104 @@
|
||||
# 如何使用 — retransform-class
|
||||
|
||||
**前置条件:** Java 8+(构建需要 `javac`/`jar`,注入需要 `jps`)
|
||||
|
||||
## 目录文件
|
||||
|
||||
| 文件 | 说明 |
|
||||
| --- | --- |
|
||||
| `injector.exe` `libagent.dll` `libinject.dll` `libloader.dll` | JuiceAgent 运行库 |
|
||||
| `config.toml` | 注入配置 |
|
||||
| `build.bat` | 构建脚本 |
|
||||
| `run.bat` | 运行目标 JVM |
|
||||
| `playload.jar` | 注入用的 JAR(由 `build.bat` 生成) |
|
||||
| `target.jar` | 目标 JVM 程序(由 `build.bat` 生成) |
|
||||
| `new_target.class` | 重变换后的字节码(由 `build.bat` 生成) |
|
||||
| `playload/` | payload 源码 |
|
||||
| `target/` | 目标类源码 |
|
||||
| `new_target/` | target 的修改版源码 |
|
||||
|
||||
## 本示例的作用
|
||||
|
||||
目标类 `target` 的 `say()` 方法原本打印:
|
||||
|
||||
```
|
||||
Hello!
|
||||
```
|
||||
|
||||
`new_target/target.java` 是它的修改版,额外打印:
|
||||
|
||||
```
|
||||
Retransformed!
|
||||
```
|
||||
|
||||
本示例把 `playload.jar` 注入到运行中的 JVM。payload 从自己的 JAR 中读取
|
||||
`new_target.class`,调用 `JuiceAgent.retransformClassByName("target", ...)`
|
||||
在运行时动态替换已加载的 `target` 类。之后 `say()` 无需重启 JVM 就会输出新内容。
|
||||
|
||||
## 使用步骤
|
||||
|
||||
### 1. 构建(可选)
|
||||
|
||||
`playload.jar` 和 `target.jar` 默认已包含。
|
||||
如果修改了 `playload/`、`target/` 或 `new_target/`,运行:
|
||||
|
||||
```
|
||||
build.bat
|
||||
```
|
||||
|
||||
重新生成 `playload.jar`、`target.jar` 和 `new_target.class`。
|
||||
|
||||
### 2. 运行目标 JVM
|
||||
|
||||
双击 `run.bat`(或执行 `java -jar target.jar`)。黑窗口出现并每秒打印:
|
||||
|
||||
```
|
||||
[Target] I am the target JVM (PID: <PID>)
|
||||
Hello!
|
||||
```
|
||||
|
||||
### 3. 注入
|
||||
|
||||
双击 `injector.exe`,输入目标 PID 后回车:
|
||||
|
||||
```
|
||||
6644 target.jar
|
||||
10504 jdk.jcmd/sun.tools.jps.Jps
|
||||
Input PID: 6644
|
||||
```
|
||||
|
||||
### 4. 验证
|
||||
|
||||
回到目标窗口,注入成功应看到:
|
||||
|
||||
```
|
||||
Playload loaded!
|
||||
Playload executed!
|
||||
```
|
||||
|
||||
并且 `say()` 的输出从 `Hello!` 变为:
|
||||
|
||||
```
|
||||
Hello!
|
||||
Retransformed!
|
||||
```
|
||||
|
||||
## 配置 / config.toml
|
||||
|
||||
| 配置项 | 说明 |
|
||||
| --- | --- |
|
||||
| `JarPath` | 注入的 JAR 路径(默认 `./playload.jar`) |
|
||||
| `EntryClass` | 入口类(默认 `playload`) |
|
||||
| `EntryMethod` | 入口方法,必须为 `public static void entry()` |
|
||||
|
||||
## 常见问题
|
||||
|
||||
- `java/javac/jar is not recognized`:
|
||||
安装 JDK 并将 `bin` 目录加入 `PATH`。
|
||||
- `injector.exe` 提示注入失败:
|
||||
确认目标 JVM 正在运行且 PID 正确。
|
||||
- 没有出现 `Playload loaded!` 输出:
|
||||
查看本目录下的 `libagent.log` 和 `libloader.log` 定位原因。
|
||||
- `say()` 输出没有变化:
|
||||
确认修改 `new_target/` 后重新运行过 `build.bat`,且 `playload.jar` 内的
|
||||
`new_target.class` 是最新的。
|
||||
@@ -0,0 +1,13 @@
|
||||
[JuiceAgent]
|
||||
Version = 1
|
||||
|
||||
[JuiceAgent.Loader]
|
||||
# Path to JuiceAgent-API jar, leave empty to use the built-in API
|
||||
JuiceAgentAPIJarPath = ""
|
||||
# Path to libagent.dll, default is "./libagent.dll"
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JuiceAgent.Modules]
|
||||
|
||||
[JuiceAgent.Modules.JuiceRemapper]
|
||||
Enabled = true
|
||||
@@ -4,7 +4,7 @@
|
||||
#include <string>
|
||||
#include <type_traits>
|
||||
|
||||
#include <JuiceAgent/JuiceAgent.hpp>
|
||||
#include <JuiceAgent/ConfigStruct.hpp>
|
||||
#include <JuiceAgent/Logger.hpp>
|
||||
#include <JuiceAgent/Utils.hpp>
|
||||
#include <toml.hpp>
|
||||
@@ -142,12 +142,12 @@ namespace Utils {
|
||||
spdlog::info("RuntimeDir: {}", config.RuntimeDir);
|
||||
}
|
||||
|
||||
inline std::string serialize_loader_config(const LoaderConfig& config)
|
||||
inline std::string serialize_loader_config(const Config& config, const LoaderConfig& loader_config)
|
||||
{
|
||||
JuiceAgent::Utils::Serializer ser;
|
||||
ser.add_kv("Version", 2);
|
||||
ser.add_kv("JuiceAgentNativeLibraryPath", config.JuiceAgentNativeLibraryPath);
|
||||
ser.add_kv("RuntimeDir", config.RuntimeDir);
|
||||
ser.add_kv("Version", config.get<int>("JuiceAgent.Version", 1));
|
||||
ser.add_kv("JuiceAgentNativeLibraryPath", loader_config.JuiceAgentNativeLibraryPath);
|
||||
ser.add_kv("RuntimeDir", loader_config.RuntimeDir);
|
||||
|
||||
return ser.serialize();
|
||||
}
|
||||
|
||||
@@ -2,11 +2,8 @@
|
||||
|
||||
#include <string>
|
||||
|
||||
namespace JuiceAgent {
|
||||
|
||||
struct LoaderConfig {
|
||||
std::string JuiceAgentNativeLibraryPath;
|
||||
std::string RuntimeDir;
|
||||
};
|
||||
|
||||
} // namespace JuiceAgent
|
||||
std::string RuntimeDir;
|
||||
};
|
||||
File renamed without changes.
@@ -0,0 +1,37 @@
|
||||
/* DO NOT EDIT THIS FILE - it is machine generated */
|
||||
#include <jni.h>
|
||||
/* Header for class cn_xiaozhou233_juiceagent_injector_Injector */
|
||||
|
||||
#ifndef _Included_cn_xiaozhou233_juiceagent_injector_Injector
|
||||
#define _Included_cn_xiaozhou233_juiceagent_injector_Injector
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceagent_injector_Injector
|
||||
* Method: inject
|
||||
* Signature: (ILjava/lang/String;)Z
|
||||
*/
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_injector_Injector_inject__ILjava_lang_String_2
|
||||
(JNIEnv *, jclass, jint, jstring);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceagent_injector_Injector
|
||||
* Method: inject
|
||||
* Signature: (ILjava/lang/String;Ljava/lang/String;)Z
|
||||
*/
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_injector_Injector_inject__ILjava_lang_String_2Ljava_lang_String_2
|
||||
(JNIEnv *, jclass, jint, jstring, jstring);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceagent_injector_Injector
|
||||
* Method: findWindowsByTitle
|
||||
* Signature: (Ljava/lang/String;)[Lcn/xiaozhou233/juiceagent/injector/WindowInfo;
|
||||
*/
|
||||
JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceagent_injector_Injector_findWindowsByTitle
|
||||
(JNIEnv *, jclass, jstring);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
@@ -0,0 +1,69 @@
|
||||
/* DO NOT EDIT THIS FILE - it is machine generated */
|
||||
#include <jni.h>
|
||||
/* Header for class cn_xiaozhou233_juiceremapper_JuiceRemapper */
|
||||
|
||||
#ifndef _Included_cn_xiaozhou233_juiceremapper_JuiceRemapper
|
||||
#define _Included_cn_xiaozhou233_juiceremapper_JuiceRemapper
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceremapper_JuiceRemapper
|
||||
* Method: initNative
|
||||
* Signature: ()Z
|
||||
*/
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_initNative
|
||||
(JNIEnv *, jclass);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceremapper_JuiceRemapper
|
||||
* Method: addInclude
|
||||
* Signature: (Ljava/lang/String;)Z
|
||||
*/
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_addInclude
|
||||
(JNIEnv *, jclass, jstring);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceremapper_JuiceRemapper
|
||||
* Method: addExclude
|
||||
* Signature: (Ljava/lang/String;)Z
|
||||
*/
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_addExclude
|
||||
(JNIEnv *, jclass, jstring);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceremapper_JuiceRemapper
|
||||
* Method: removeInclude
|
||||
* Signature: (Ljava/lang/String;)Z
|
||||
*/
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_removeInclude
|
||||
(JNIEnv *, jclass, jstring);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceremapper_JuiceRemapper
|
||||
* Method: removeExclude
|
||||
* Signature: (Ljava/lang/String;)Z
|
||||
*/
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_removeExclude
|
||||
(JNIEnv *, jclass, jstring);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceremapper_JuiceRemapper
|
||||
* Method: clearIncludes
|
||||
* Signature: ()V
|
||||
*/
|
||||
JNIEXPORT void JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_clearIncludes
|
||||
(JNIEnv *, jclass);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceremapper_JuiceRemapper
|
||||
* Method: clearExcludes
|
||||
* Signature: ()V
|
||||
*/
|
||||
JNIEXPORT void JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_clearExcludes
|
||||
(JNIEnv *, jclass);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
@@ -0,0 +1,498 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef CALLBACKLIST_H_588722158669
|
||||
#define CALLBACKLIST_H_588722158669
|
||||
|
||||
#include "eventpolicies.h"
|
||||
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <cassert>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <
|
||||
typename Prototype,
|
||||
typename PoliciesType
|
||||
>
|
||||
class CallbackListBase;
|
||||
|
||||
template <
|
||||
typename PoliciesType,
|
||||
typename ReturnType, typename ...Args
|
||||
>
|
||||
class CallbackListBase<
|
||||
ReturnType (Args...),
|
||||
PoliciesType
|
||||
>
|
||||
{
|
||||
private:
|
||||
using Policies = PoliciesType;
|
||||
|
||||
using Threading = typename SelectThreading<Policies, HasTypeThreading<Policies>::value>::Type;
|
||||
|
||||
using Callback_ = typename SelectCallback<
|
||||
Policies,
|
||||
HasTypeCallback<Policies>::value,
|
||||
std::function<ReturnType (Args...)>
|
||||
>::Type;
|
||||
|
||||
using CanContinueInvoking = typename SelectCanContinueInvoking<
|
||||
Policies, HasFunctionCanContinueInvoking<Policies, Args...>::value
|
||||
>::Type;
|
||||
|
||||
struct Node;
|
||||
using NodePtr = std::shared_ptr<Node>;
|
||||
|
||||
struct Node
|
||||
{
|
||||
using Counter = unsigned int;
|
||||
|
||||
Node(const Callback_ & callback, const Counter counter)
|
||||
: callback(callback), counter(counter)
|
||||
{
|
||||
}
|
||||
|
||||
NodePtr previous;
|
||||
NodePtr next;
|
||||
Callback_ callback;
|
||||
Counter counter;
|
||||
};
|
||||
|
||||
class Handle_ : public std::weak_ptr<Node>
|
||||
{
|
||||
private:
|
||||
using super = std::weak_ptr<Node>;
|
||||
|
||||
public:
|
||||
using super::super;
|
||||
|
||||
operator bool () const noexcept {
|
||||
return ! this->expired();
|
||||
}
|
||||
};
|
||||
|
||||
using Counter = typename Node::Counter;
|
||||
enum : Counter {
|
||||
removedCounter = 0
|
||||
};
|
||||
|
||||
public:
|
||||
using Callback = Callback_;
|
||||
using Handle = Handle_;
|
||||
using Mutex = typename Threading::Mutex;
|
||||
|
||||
public:
|
||||
CallbackListBase() noexcept
|
||||
:
|
||||
head(),
|
||||
tail(),
|
||||
mutex(),
|
||||
currentCounter(0)
|
||||
{
|
||||
}
|
||||
|
||||
CallbackListBase(const CallbackListBase & other)
|
||||
: CallbackListBase()
|
||||
{
|
||||
cloneFrom(other.head);
|
||||
}
|
||||
|
||||
CallbackListBase(CallbackListBase && other) noexcept
|
||||
: CallbackListBase()
|
||||
{
|
||||
swap(other);
|
||||
}
|
||||
|
||||
// If we use pass by value idiom and omit the 'this' check,
|
||||
// when assigning to self there is a deep copy which is inefficient.
|
||||
CallbackListBase & operator = (const CallbackListBase & other) {
|
||||
if(this != &other) {
|
||||
CallbackListBase copied(other);
|
||||
swap(copied);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
CallbackListBase & operator = (CallbackListBase && other) noexcept {
|
||||
if(this != &other) {
|
||||
doFreeAllNodes();
|
||||
|
||||
head = std::move(other.head);
|
||||
tail = std::move(other.tail);
|
||||
currentCounter = other.currentCounter.load();
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
~CallbackListBase() {
|
||||
// Don't lock mutex here since it may throw exception
|
||||
|
||||
doFreeAllNodes();
|
||||
}
|
||||
|
||||
void swap(CallbackListBase & other) noexcept {
|
||||
using std::swap;
|
||||
|
||||
swap(head, other.head);
|
||||
swap(tail, other.tail);
|
||||
|
||||
const auto value = currentCounter.load();
|
||||
currentCounter.exchange(other.currentCounter.load());
|
||||
other.currentCounter.exchange(value);
|
||||
}
|
||||
|
||||
bool empty() const {
|
||||
// Don't lock the mutex for performance reason.
|
||||
// !head still works even when the underlying raw pointer is garbled (for other thread is writting to head)
|
||||
// And empty() doesn't guarantee the list is still empty after the function returned.
|
||||
//std::lock_guard<Mutex> lockGuard(mutex);
|
||||
|
||||
return ! head;
|
||||
}
|
||||
|
||||
operator bool() const {
|
||||
return ! empty();
|
||||
}
|
||||
|
||||
Handle append(const Callback & callback)
|
||||
{
|
||||
NodePtr node(doAllocateNode(callback));
|
||||
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
|
||||
if(head) {
|
||||
node->previous = tail;
|
||||
tail->next = node;
|
||||
tail = node;
|
||||
}
|
||||
else {
|
||||
head = node;
|
||||
tail = node;
|
||||
}
|
||||
|
||||
return Handle(node);
|
||||
}
|
||||
|
||||
Handle prepend(const Callback & callback)
|
||||
{
|
||||
NodePtr node(doAllocateNode(callback));
|
||||
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
|
||||
if(head) {
|
||||
node->next = head;
|
||||
head->previous = node;
|
||||
head = node;
|
||||
}
|
||||
else {
|
||||
head = node;
|
||||
tail = node;
|
||||
}
|
||||
|
||||
return Handle(node);
|
||||
}
|
||||
|
||||
Handle insert(const Callback & callback, const Handle & before)
|
||||
{
|
||||
// Disable this assertion because it's too slow in debug mode.
|
||||
//assert(before.expired() || ownsHandle(before));
|
||||
|
||||
NodePtr beforeNode = before.lock();
|
||||
if(beforeNode) {
|
||||
NodePtr node(doAllocateNode(callback));
|
||||
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
|
||||
doInsert(node, beforeNode);
|
||||
|
||||
return Handle(node);
|
||||
}
|
||||
|
||||
return append(callback);
|
||||
}
|
||||
|
||||
bool remove(const Handle & handle)
|
||||
{
|
||||
// Disable this assertion because it's too slow in debug mode.
|
||||
//assert(handle.expired() || ownsHandle(handle));
|
||||
|
||||
// It looks like the lock can be put inside the `if` below,
|
||||
// but that doesn't work in multi-threading and cause related unit tests fail.
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
|
||||
auto node = handle.lock();
|
||||
if(node) {
|
||||
doFreeNode(node);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool ownsHandle(const Handle & handle) const
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
|
||||
auto node = handle.lock();
|
||||
if(node) {
|
||||
while(node->previous) {
|
||||
node = node->previous;
|
||||
}
|
||||
return node == head;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename Func>
|
||||
void forEach(Func && func) const
|
||||
{
|
||||
doForEachIf([&func, this](NodePtr & node) -> bool {
|
||||
doForEachInvoke<void>(func, node);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
template <typename Func>
|
||||
bool forEachIf(Func && func) const
|
||||
{
|
||||
return doForEachIf([&func, this](NodePtr & node) -> bool {
|
||||
return doForEachInvoke<bool>(func, node);
|
||||
});
|
||||
}
|
||||
|
||||
#if !defined(__GNUC__) || __GNUC__ >= 5
|
||||
void operator() (Args ...args) const
|
||||
{
|
||||
forEachIf([&args...](Callback & callback) -> bool {
|
||||
// We can't use std::forward here, because if we use std::forward,
|
||||
// for arg that is passed by value, and the callback prototype accepts it by value,
|
||||
// std::forward will move it and may cause the original value invalid.
|
||||
// That happens on any value-to-value passing, no matter the callback moves it or not.
|
||||
|
||||
callback(args...);
|
||||
return CanContinueInvoking::canContinueInvoking(args...);
|
||||
});
|
||||
}
|
||||
#else
|
||||
// This is a patch version for GCC 4. It inlines the unrolled doForEachIf.
|
||||
// GCC 4.8.3 doesn't supporting parameter pack catpure in lambda, see,
|
||||
// https://github.com/wqking/eventpp/issues/19
|
||||
// This is a compromised patch for GCC 4, it may be not maintained or updated unless there are bugs.
|
||||
// We don't use the patch as main code because the patch generates longer code, and duplicated with doForEachIf.
|
||||
void operator() (Args ...args) const
|
||||
{
|
||||
NodePtr node;
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
node = head;
|
||||
}
|
||||
|
||||
const Counter counter = currentCounter.load(std::memory_order_acquire);
|
||||
|
||||
while(node) {
|
||||
if(node->counter != removedCounter && counter >= node->counter) {
|
||||
node->callback(args...);
|
||||
if(! CanContinueInvoking::canContinueInvoking(args...)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
node = node->next;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
private:
|
||||
template <typename F>
|
||||
bool doForEachIf(F && f) const
|
||||
{
|
||||
NodePtr node;
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
node = head;
|
||||
}
|
||||
|
||||
const Counter counter = currentCounter.load(std::memory_order_acquire);
|
||||
|
||||
while(node) {
|
||||
if(node->counter != removedCounter && counter >= node->counter) {
|
||||
if(! f(node)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
node = node->next;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename RT, typename Func>
|
||||
auto doForEachInvoke(Func && func, NodePtr & node) const
|
||||
-> typename std::enable_if<CanInvoke<Func, Handle, Callback &>::value, RT>::type
|
||||
{
|
||||
return func(Handle(node), node->callback);
|
||||
}
|
||||
|
||||
template <typename RT, typename Func>
|
||||
auto doForEachInvoke(Func && func, NodePtr & node) const
|
||||
-> typename std::enable_if<CanInvoke<Func, Callback &>::value, RT>::type
|
||||
{
|
||||
return func(node->callback);
|
||||
}
|
||||
|
||||
void doInsert(NodePtr & node, NodePtr & beforeNode)
|
||||
{
|
||||
node->previous = beforeNode->previous;
|
||||
node->next = beforeNode;
|
||||
if(beforeNode->previous) {
|
||||
beforeNode->previous->next = node;
|
||||
}
|
||||
beforeNode->previous = node;
|
||||
|
||||
if(beforeNode == head) {
|
||||
head = node;
|
||||
}
|
||||
}
|
||||
|
||||
NodePtr doAllocateNode(const Callback & callback)
|
||||
{
|
||||
return std::make_shared<Node>(callback, getNextCounter());
|
||||
}
|
||||
|
||||
void doFreeNode(NodePtr & node)
|
||||
{
|
||||
if(node->next) {
|
||||
node->next->previous = node->previous;
|
||||
}
|
||||
if(node->previous) {
|
||||
node->previous->next = node->next;
|
||||
}
|
||||
|
||||
// Mark it as deleted, this must be before the assignment of head and tail below,
|
||||
// because node can be a reference to head or tail, and after the assignment, node
|
||||
// can be null pointer.
|
||||
node->counter = removedCounter;
|
||||
|
||||
if(head == node) {
|
||||
head = node->next;
|
||||
}
|
||||
if(tail == node) {
|
||||
tail = node->previous;
|
||||
}
|
||||
|
||||
// don't modify node->previous or node->next
|
||||
// because node may be still used in a loop.
|
||||
}
|
||||
|
||||
void doFreeAllNodes() {
|
||||
NodePtr node = head;
|
||||
head.reset();
|
||||
while(node) {
|
||||
NodePtr next = node->next;
|
||||
node->previous.reset();
|
||||
node->next.reset();
|
||||
node = next;
|
||||
}
|
||||
node.reset();
|
||||
}
|
||||
|
||||
Counter getNextCounter()
|
||||
{
|
||||
Counter result = ++currentCounter;;
|
||||
if(result == 0) { // overflow, let's reset all nodes' counters.
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
NodePtr node = head;
|
||||
while(node) {
|
||||
node->counter = 1;
|
||||
node = node->next;
|
||||
}
|
||||
}
|
||||
result = ++currentCounter;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
void cloneFrom(const NodePtr & fromHead) {
|
||||
NodePtr fromNode(fromHead);
|
||||
NodePtr node;
|
||||
const Counter counter = getNextCounter();
|
||||
while(fromNode) {
|
||||
const NodePtr nextNode(std::make_shared<Node>(fromNode->callback, counter));
|
||||
|
||||
nextNode->previous = node;
|
||||
|
||||
if(node) {
|
||||
node->next = nextNode;
|
||||
}
|
||||
else {
|
||||
node = nextNode;
|
||||
head = node;
|
||||
}
|
||||
|
||||
node = nextNode;
|
||||
fromNode = fromNode->next;
|
||||
}
|
||||
|
||||
tail = node;
|
||||
}
|
||||
|
||||
private:
|
||||
NodePtr head;
|
||||
NodePtr tail;
|
||||
mutable Mutex mutex;
|
||||
typename Threading::template Atomic<Counter> currentCounter;
|
||||
|
||||
};
|
||||
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
|
||||
template <
|
||||
typename Prototype_,
|
||||
typename Policies_ = DefaultPolicies
|
||||
>
|
||||
class CallbackList : public internal_::CallbackListBase<Prototype_, Policies_>, public TagCallbackList
|
||||
{
|
||||
private:
|
||||
using super = internal_::CallbackListBase<Prototype_, Policies_>;
|
||||
|
||||
public:
|
||||
using super::super;
|
||||
|
||||
friend void swap(CallbackList & first, CallbackList & second) noexcept {
|
||||
first.swap(second);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,328 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef EVENTDISPATCHER_H_319010983013
|
||||
#define EVENTDISPATCHER_H_319010983013
|
||||
|
||||
#include "callbacklist.h"
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <
|
||||
typename EventType_,
|
||||
typename Prototype_,
|
||||
typename Policies_,
|
||||
typename MixinRoot_
|
||||
>
|
||||
class EventDispatcherBase;
|
||||
|
||||
template <
|
||||
typename EventType_,
|
||||
typename Policies_,
|
||||
typename MixinRoot_,
|
||||
typename ReturnType, typename ...Args
|
||||
>
|
||||
class EventDispatcherBase <
|
||||
EventType_,
|
||||
ReturnType (Args...),
|
||||
Policies_,
|
||||
MixinRoot_
|
||||
>
|
||||
{
|
||||
protected:
|
||||
using ThisType = EventDispatcherBase<
|
||||
EventType_,
|
||||
ReturnType (Args...),
|
||||
Policies_,
|
||||
MixinRoot_
|
||||
>;
|
||||
using MixinRoot = typename std::conditional<
|
||||
std::is_same<MixinRoot_, void>::value,
|
||||
ThisType,
|
||||
MixinRoot_
|
||||
>::type;
|
||||
using Policies = Policies_;
|
||||
|
||||
using Threading = typename SelectThreading<Policies_, HasTypeThreading<Policies_>::value>::Type;
|
||||
|
||||
using ArgumentPassingMode = typename SelectArgumentPassingMode<
|
||||
Policies_,
|
||||
HasTypeArgumentPassingMode<Policies_>::value,
|
||||
ArgumentPassingAutoDetect
|
||||
>::Type;
|
||||
|
||||
using Callback_ = typename SelectCallback<
|
||||
Policies_,
|
||||
HasTypeCallback<Policies_>::value,
|
||||
std::function<ReturnType (Args...)>
|
||||
>::Type;
|
||||
using CallbackList_ = CallbackList<ReturnType (Args...), Policies_>;
|
||||
|
||||
using Prototype = ReturnType (Args...);
|
||||
|
||||
using Map = typename SelectMap<
|
||||
EventType_,
|
||||
CallbackList_,
|
||||
Policies_,
|
||||
HasTemplateMap<Policies_>::value
|
||||
>::Type;
|
||||
|
||||
using Mixins = typename internal_::SelectMixins<
|
||||
Policies_,
|
||||
internal_::HasTypeMixins<Policies_>::value
|
||||
>::Type;
|
||||
|
||||
public:
|
||||
using Handle = typename CallbackList_::Handle;
|
||||
using Callback = Callback_;
|
||||
using Event = EventType_;
|
||||
using Mutex = typename Threading::Mutex;
|
||||
|
||||
public:
|
||||
EventDispatcherBase()
|
||||
:
|
||||
eventCallbackListMap(),
|
||||
listenerMutex()
|
||||
{
|
||||
}
|
||||
|
||||
EventDispatcherBase(const EventDispatcherBase & other)
|
||||
:
|
||||
eventCallbackListMap(other.eventCallbackListMap),
|
||||
listenerMutex()
|
||||
{
|
||||
}
|
||||
|
||||
EventDispatcherBase(EventDispatcherBase && other) noexcept
|
||||
:
|
||||
eventCallbackListMap(std::move(other.eventCallbackListMap)),
|
||||
listenerMutex()
|
||||
{
|
||||
}
|
||||
|
||||
EventDispatcherBase & operator = (const EventDispatcherBase & other)
|
||||
{
|
||||
eventCallbackListMap = other.eventCallbackListMap;
|
||||
return *this;
|
||||
}
|
||||
|
||||
EventDispatcherBase & operator = (EventDispatcherBase && other) noexcept
|
||||
{
|
||||
eventCallbackListMap = std::move(other.eventCallbackListMap);
|
||||
return *this;
|
||||
}
|
||||
|
||||
void swap(EventDispatcherBase & other) noexcept {
|
||||
using std::swap;
|
||||
|
||||
swap(eventCallbackListMap, other.eventCallbackListMap);
|
||||
}
|
||||
|
||||
Handle appendListener(const Event & event, const Callback & callback)
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(listenerMutex);
|
||||
|
||||
return eventCallbackListMap[event].append(callback);
|
||||
}
|
||||
|
||||
Handle prependListener(const Event & event, const Callback & callback)
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(listenerMutex);
|
||||
|
||||
return eventCallbackListMap[event].prepend(callback);
|
||||
}
|
||||
|
||||
Handle insertListener(const Event & event, const Callback & callback, const Handle & before)
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(listenerMutex);
|
||||
|
||||
return eventCallbackListMap[event].insert(callback, before);
|
||||
}
|
||||
|
||||
bool removeListener(const Event & event, const Handle handle)
|
||||
{
|
||||
CallbackList_ * callableList = doFindCallableList(event);
|
||||
if(callableList) {
|
||||
return callableList->remove(handle);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool hasAnyListener(const Event & event) const
|
||||
{
|
||||
const CallbackList_ * callableList = doFindCallableList(event);
|
||||
if(callableList) {
|
||||
return ! callableList->empty();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool ownsHandle(const Event & event, const Handle & handle) const
|
||||
{
|
||||
const CallbackList_ * callableList = doFindCallableList(event);
|
||||
if(callableList) {
|
||||
return callableList->ownsHandle(handle);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename Func>
|
||||
void forEach(const Event & event, Func && func) const
|
||||
{
|
||||
const CallbackList_ * callableList = doFindCallableList(event);
|
||||
if(callableList) {
|
||||
callableList->forEach(std::forward<Func>(func));
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Func>
|
||||
bool forEachIf(const Event & event, Func && func) const
|
||||
{
|
||||
const CallbackList_ * callableList = doFindCallableList(event);
|
||||
if (callableList) {
|
||||
return callableList->forEachIf(std::forward<Func>(func));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void dispatch(Args ...args) const
|
||||
{
|
||||
static_assert(ArgumentPassingMode::canIncludeEventType, "Dispatching arguments count doesn't match required (Event type should be included).");
|
||||
|
||||
using GetEvent = typename SelectGetEvent<Policies_, EventType_, HasFunctionGetEvent<Policies_, Args...>::value>::Type;
|
||||
|
||||
// can't std::forward<Args>(args) in GetEvent::getEvent because the pass by value arguments will be moved to getEvent
|
||||
// then the other std::forward<Args>(args) to directDispatch will get empty values.
|
||||
directDispatch(
|
||||
GetEvent::getEvent(args...),
|
||||
std::forward<Args>(args)...
|
||||
);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void dispatch(T && first, Args ...args) const
|
||||
{
|
||||
static_assert(ArgumentPassingMode::canExcludeEventType, "Dispatching arguments count doesn't match required (Event type should NOT be included).");
|
||||
|
||||
using GetEvent = typename SelectGetEvent<Policies_, EventType_, HasFunctionGetEvent<Policies_, T &&, Args...>::value>::Type;
|
||||
|
||||
directDispatch(
|
||||
GetEvent::getEvent(std::forward<T>(first), args...),
|
||||
std::forward<Args>(args)...
|
||||
);
|
||||
}
|
||||
|
||||
// Bypass any getEvent policy. The first argument is the event type.
|
||||
// Most used for internal purpose.
|
||||
void directDispatch(const Event & e, Args ...args) const
|
||||
{
|
||||
if(! internal_::ForEachMixins<MixinRoot, Mixins, DoMixinBeforeDispatch>::forEach(
|
||||
this, typename std::add_lvalue_reference<Args>::type(args)...)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const CallbackList_ * callableList = doFindCallableList(e);
|
||||
if(callableList) {
|
||||
(*callableList)(std::forward<Args>(args)...);
|
||||
}
|
||||
}
|
||||
|
||||
protected:
|
||||
const CallbackList_ * doFindCallableList(const Event & e) const
|
||||
{
|
||||
return doFindCallableListHelper(this, e);
|
||||
}
|
||||
|
||||
CallbackList_ * doFindCallableList(const Event & e)
|
||||
{
|
||||
return doFindCallableListHelper(this, e);
|
||||
}
|
||||
|
||||
private:
|
||||
// template helper to avoid code duplication in doFindCallableList
|
||||
template <typename T>
|
||||
static auto doFindCallableListHelper(T * self, const Event & e)
|
||||
-> typename std::conditional<std::is_const<T>::value, const CallbackList_ *, CallbackList_ *>::type
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(self->listenerMutex);
|
||||
|
||||
auto it = self->eventCallbackListMap.find(e);
|
||||
if(it != self->eventCallbackListMap.end()) {
|
||||
return &it->second;
|
||||
}
|
||||
else {
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
// Mixin related
|
||||
struct DoMixinBeforeDispatch
|
||||
{
|
||||
template <typename T, typename Self, typename ...A>
|
||||
static auto forEach(const Self * self, A && ...args)
|
||||
-> typename std::enable_if<HasFunctionMixinBeforeDispatch<T, A...>::value, bool>::type {
|
||||
return static_cast<const T *>(self)->mixinBeforeDispatch(std::forward<A>(args)...);
|
||||
}
|
||||
|
||||
template <typename T, typename Self, typename ...A>
|
||||
static auto forEach(const Self * /*self*/, A && ... /*args*/)
|
||||
-> typename std::enable_if<! HasFunctionMixinBeforeDispatch<T, A...>::value, bool>::type {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
private:
|
||||
Map eventCallbackListMap;
|
||||
mutable Mutex listenerMutex;
|
||||
};
|
||||
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
template <
|
||||
typename Event_,
|
||||
typename Prototype_,
|
||||
typename Policies_ = DefaultPolicies
|
||||
>
|
||||
class EventDispatcher : public internal_::InheritMixins<
|
||||
internal_::EventDispatcherBase<Event_, Prototype_, Policies_, void>,
|
||||
typename internal_::SelectMixins<Policies_, internal_::HasTypeMixins<Policies_>::value >::Type
|
||||
>::Type, public TagEventDispatcher
|
||||
{
|
||||
private:
|
||||
using super = typename internal_::InheritMixins<
|
||||
internal_::EventDispatcherBase<Event_, Prototype_, Policies_, void>,
|
||||
typename internal_::SelectMixins<Policies_, internal_::HasTypeMixins<Policies_>::value >::Type
|
||||
>::Type;
|
||||
|
||||
public:
|
||||
using super::super;
|
||||
|
||||
friend void swap(EventDispatcher & first, EventDispatcher & second) noexcept {
|
||||
first.swap(second);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef EVENTOPTIONS_H_730367862613
|
||||
#define EVENTOPTIONS_H_730367862613
|
||||
|
||||
#include "internal/typeutil_i.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <map>
|
||||
#include <unordered_map>
|
||||
#include <list>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
struct TagHomo {};
|
||||
struct TagCallbackList : public TagHomo {};
|
||||
struct TagEventDispatcher : public TagHomo {};
|
||||
struct TagEventQueue : public TagHomo {};
|
||||
|
||||
struct TagHeter {};
|
||||
struct TagHeterCallbackList : public TagHeter {};
|
||||
struct TagHeterEventDispatcher : public TagHeter {};
|
||||
struct TagHeterEventQueue : public TagHeter {};
|
||||
|
||||
struct SpinLock
|
||||
{
|
||||
public:
|
||||
void lock() {
|
||||
while(locked.test_and_set(std::memory_order_acquire)) {
|
||||
}
|
||||
}
|
||||
|
||||
void unlock() {
|
||||
locked.clear(std::memory_order_release);
|
||||
}
|
||||
|
||||
private:
|
||||
std::atomic_flag locked = ATOMIC_FLAG_INIT;
|
||||
};
|
||||
|
||||
template <
|
||||
typename Mutex_,
|
||||
template <typename > class Atomic_ = std::atomic,
|
||||
typename ConditionVariable_ = std::condition_variable
|
||||
>
|
||||
struct GeneralThreading
|
||||
{
|
||||
using Mutex = Mutex_;
|
||||
|
||||
template <typename T>
|
||||
using Atomic = Atomic_<T>;
|
||||
|
||||
using ConditionVariable = ConditionVariable_;
|
||||
};
|
||||
|
||||
struct MultipleThreading
|
||||
{
|
||||
using Mutex = std::mutex;
|
||||
|
||||
template <typename T>
|
||||
using Atomic = std::atomic<T>;
|
||||
|
||||
using ConditionVariable = std::condition_variable;
|
||||
};
|
||||
|
||||
struct SingleThreading
|
||||
{
|
||||
struct Mutex
|
||||
{
|
||||
void lock() {}
|
||||
void unlock() {}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct Atomic
|
||||
{
|
||||
Atomic() noexcept = default;
|
||||
constexpr Atomic(T desired) noexcept
|
||||
: value(desired)
|
||||
{
|
||||
}
|
||||
|
||||
void store(T desired, std::memory_order /*order*/ = std::memory_order_seq_cst) noexcept
|
||||
{
|
||||
value = desired;
|
||||
}
|
||||
|
||||
T load(std::memory_order /*order*/ = std::memory_order_seq_cst) const noexcept
|
||||
{
|
||||
return value;
|
||||
}
|
||||
|
||||
T exchange(T desired, std::memory_order /*order*/ = std::memory_order_seq_cst) noexcept
|
||||
{
|
||||
const T previous = value;
|
||||
value = desired;
|
||||
return previous;
|
||||
}
|
||||
|
||||
T operator ++ () noexcept
|
||||
{
|
||||
return ++value;
|
||||
}
|
||||
|
||||
T operator -- () noexcept
|
||||
{
|
||||
return --value;
|
||||
}
|
||||
|
||||
T value;
|
||||
};
|
||||
|
||||
struct ConditionVariable
|
||||
{
|
||||
void notify_one() noexcept
|
||||
{
|
||||
}
|
||||
|
||||
template <class Predicate>
|
||||
void wait(std::unique_lock<std::mutex> & /*lock*/, Predicate /*pred*/)
|
||||
{
|
||||
}
|
||||
|
||||
template <class Rep, class Period, class Predicate>
|
||||
bool wait_for(std::unique_lock<std::mutex> & /*lock*/,
|
||||
const std::chrono::duration<Rep, Period> & /*rel_time*/,
|
||||
Predicate /*pred*/
|
||||
)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
struct ArgumentPassingAutoDetect
|
||||
{
|
||||
enum {
|
||||
canIncludeEventType = true,
|
||||
canExcludeEventType = true
|
||||
};
|
||||
};
|
||||
|
||||
struct ArgumentPassingIncludeEvent
|
||||
{
|
||||
enum {
|
||||
canIncludeEventType = true,
|
||||
canExcludeEventType = false
|
||||
};
|
||||
};
|
||||
|
||||
struct ArgumentPassingExcludeEvent
|
||||
{
|
||||
enum {
|
||||
canIncludeEventType = false,
|
||||
canExcludeEventType = true
|
||||
};
|
||||
};
|
||||
|
||||
struct DefaultPolicies
|
||||
{
|
||||
};
|
||||
|
||||
template <template <typename> class ...Mixins>
|
||||
struct MixinList
|
||||
{
|
||||
};
|
||||
|
||||
#include "internal/eventpolicies_i.h"
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,561 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef EVENTQUEUE_H_705786053037
|
||||
#define EVENTQUEUE_H_705786053037
|
||||
|
||||
#include "eventdispatcher.h"
|
||||
#include "internal/eventqueue_i.h"
|
||||
|
||||
#include <tuple>
|
||||
#include <chrono>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <
|
||||
typename EventType_,
|
||||
typename Prototype_,
|
||||
typename Policies_
|
||||
>
|
||||
class EventQueueBase;
|
||||
|
||||
template <
|
||||
typename EventType_,
|
||||
typename Policies_,
|
||||
typename ReturnType, typename ...Args
|
||||
>
|
||||
class EventQueueBase <
|
||||
EventType_,
|
||||
ReturnType (Args...),
|
||||
Policies_
|
||||
> : public EventDispatcherBase<
|
||||
EventType_,
|
||||
ReturnType (Args...),
|
||||
Policies_,
|
||||
EventQueueBase <
|
||||
EventType_,
|
||||
ReturnType (Args...),
|
||||
Policies_
|
||||
>
|
||||
>
|
||||
{
|
||||
private:
|
||||
using super = EventDispatcherBase<
|
||||
EventType_,
|
||||
ReturnType (Args...),
|
||||
Policies_,
|
||||
EventQueueBase <
|
||||
EventType_,
|
||||
ReturnType (Args...),
|
||||
Policies_
|
||||
>
|
||||
>;
|
||||
|
||||
using Policies = typename super::Policies;
|
||||
using Threading = typename super::Threading;
|
||||
using ConditionVariable = typename Threading::ConditionVariable;
|
||||
|
||||
using QueuedEventArgumentsType = std::tuple<typename std::decay<Args>::type...>;
|
||||
|
||||
struct QueuedEvent_
|
||||
{
|
||||
typename std::decay<typename super::Event>::type event;
|
||||
QueuedEventArgumentsType arguments;
|
||||
|
||||
typename super::Event getEvent() const {
|
||||
return event;
|
||||
}
|
||||
|
||||
template <std::size_t N>
|
||||
auto getArgument() const
|
||||
-> typename std::tuple_element<N, std::tuple<Args...> >::type {
|
||||
return std::get<N>(arguments);
|
||||
}
|
||||
};
|
||||
|
||||
using BufferedItemList = typename SelectQueueList<
|
||||
BufferedItem<QueuedEvent_>,
|
||||
Policies_,
|
||||
HasTemplateQueueList<Policies_>::value
|
||||
>::Type;
|
||||
|
||||
public:
|
||||
using QueuedEvent = QueuedEvent_;
|
||||
using Event = typename super::Event;
|
||||
using Handle = typename super::Handle;
|
||||
using Callback = typename super::Callback;
|
||||
using Mutex = typename super::Mutex;
|
||||
|
||||
struct DisableQueueNotify
|
||||
{
|
||||
DisableQueueNotify(EventQueueBase * queue)
|
||||
: queue(queue)
|
||||
{
|
||||
++queue->queueNotifyCounter;
|
||||
}
|
||||
|
||||
~DisableQueueNotify()
|
||||
{
|
||||
--queue->queueNotifyCounter;
|
||||
|
||||
if(queue->doCanNotifyQueueAvailable() && ! queue->emptyQueue()) {
|
||||
queue->queueListConditionVariable.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
EventQueueBase * queue;
|
||||
};
|
||||
|
||||
public:
|
||||
EventQueueBase()
|
||||
:
|
||||
super(),
|
||||
queueListConditionVariable(),
|
||||
queueEmptyCounter(0),
|
||||
queueNotifyCounter(0),
|
||||
queueListMutex(),
|
||||
queueList(),
|
||||
freeListMutex(),
|
||||
freeList()
|
||||
{
|
||||
}
|
||||
|
||||
EventQueueBase(const EventQueueBase & other)
|
||||
: super(other)
|
||||
{
|
||||
}
|
||||
|
||||
EventQueueBase(EventQueueBase && other) noexcept
|
||||
: super(std::move(other))
|
||||
{
|
||||
}
|
||||
|
||||
EventQueueBase & operator = (const EventQueueBase & other)
|
||||
{
|
||||
super::operator = (other);
|
||||
return *this;
|
||||
}
|
||||
|
||||
EventQueueBase & operator = (EventQueueBase && other) noexcept
|
||||
{
|
||||
super::operator = (std::move(other));
|
||||
return *this;
|
||||
}
|
||||
|
||||
template <typename ...A>
|
||||
auto enqueue(A && ...args) -> typename std::enable_if<sizeof...(A) == sizeof...(Args), void>::type
|
||||
{
|
||||
static_assert(super::ArgumentPassingMode::canIncludeEventType, "Enqueuing arguments count doesn't match required (Event type should be included).");
|
||||
|
||||
using GetEvent = typename SelectGetEvent<Policies_, EventType_, HasFunctionGetEvent<Policies_, A...>::value>::Type;
|
||||
|
||||
doEnqueue(QueuedEvent{
|
||||
GetEvent::getEvent(args...),
|
||||
QueuedEventArgumentsType(std::forward<A>(args)...)
|
||||
});
|
||||
|
||||
if(doCanProcess()) {
|
||||
queueListConditionVariable.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T, typename ...A>
|
||||
auto enqueue(T && first, A && ...args) -> typename std::enable_if<sizeof...(A) == sizeof...(Args), void>::type
|
||||
{
|
||||
static_assert(super::ArgumentPassingMode::canExcludeEventType, "Enqueuing arguments count doesn't match required (Event type should NOT be included).");
|
||||
|
||||
using GetEvent = typename SelectGetEvent<Policies_, EventType_, HasFunctionGetEvent<Policies_, T &&, A...>::value>::Type;
|
||||
|
||||
doEnqueue(QueuedEvent{
|
||||
GetEvent::getEvent(std::forward<T>(first), args...),
|
||||
QueuedEventArgumentsType(std::forward<A>(args)...)
|
||||
});
|
||||
|
||||
if(doCanProcess()) {
|
||||
queueListConditionVariable.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
bool emptyQueue() const
|
||||
{
|
||||
return queueList.empty() && (queueEmptyCounter.load(std::memory_order_acquire) == 0);
|
||||
}
|
||||
|
||||
void clearEvents()
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
std::swap(queueList, tempList);
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
for(auto & item : tempList) {
|
||||
item.clear();
|
||||
}
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), tempList);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool process()
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
|
||||
// Use a counter to tell the queue list is not empty during processing
|
||||
// even though queueList is swapped to empty.
|
||||
CounterGuard<decltype(queueEmptyCounter)> counterGuard(queueEmptyCounter);
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
std::swap(queueList, tempList);
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
for(auto & item : tempList) {
|
||||
doDispatchQueuedEvent(
|
||||
item.get(),
|
||||
typename MakeIndexSequence<sizeof...(Args)>::Type()
|
||||
);
|
||||
item.clear();
|
||||
}
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), tempList);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool processOne()
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
|
||||
// Use a counter to tell the queue list is not empty during processing
|
||||
// even though queueList is swapped to empty.
|
||||
CounterGuard<decltype(queueEmptyCounter)> counterGuard(queueEmptyCounter);
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
if(! queueList.empty()) {
|
||||
tempList.splice(tempList.end(), queueList, queueList.begin());
|
||||
}
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
auto & item = tempList.front();
|
||||
doDispatchQueuedEvent(
|
||||
item.get(),
|
||||
typename MakeIndexSequence<sizeof...(Args)>::Type()
|
||||
);
|
||||
item.clear();
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), tempList);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename Predictor>
|
||||
bool processIf(Predictor && predictor)
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
BufferedItemList idleList;
|
||||
|
||||
// Use a counter to tell the queue list is not empty during processing
|
||||
// even though queueList is swapped to empty.
|
||||
CounterGuard<decltype(queueEmptyCounter)> counterGuard(queueEmptyCounter);
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
std::swap(queueList, tempList);
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
for(auto it = tempList.begin(); it != tempList.end(); ) {
|
||||
if(doInvokeFuncWithQueuedEvent(
|
||||
predictor,
|
||||
it->get(),
|
||||
typename MakeIndexSequence<sizeof...(Args)>::Type())
|
||||
) {
|
||||
doDispatchQueuedEvent(
|
||||
it->get(),
|
||||
typename MakeIndexSequence<sizeof...(Args)>::Type()
|
||||
);
|
||||
it->clear();
|
||||
|
||||
auto tempIt = it;
|
||||
++it;
|
||||
idleList.splice(idleList.end(), tempList, tempIt);
|
||||
}
|
||||
else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
|
||||
if (! tempList.empty()) {
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
queueList.splice(queueList.begin(), tempList);
|
||||
}
|
||||
|
||||
if(! idleList.empty()) {
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), idleList);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename Predictor>
|
||||
bool processUntil(Predictor && predictor)
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
BufferedItemList idleList;
|
||||
|
||||
// Use a counter to tell the queue list is not empty during processing
|
||||
// even though queueList is swapped to empty.
|
||||
CounterGuard<decltype(queueEmptyCounter)> counterGuard(queueEmptyCounter);
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
std::swap(queueList, tempList);
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
for(auto it = tempList.begin(); it != tempList.end(); ) {
|
||||
if(doInvokeFuncWithQueuedEvent(
|
||||
predictor,
|
||||
it->get(),
|
||||
typename MakeIndexSequence<sizeof...(Args)>::Type())
|
||||
) {
|
||||
break;
|
||||
}
|
||||
else {
|
||||
doDispatchQueuedEvent(
|
||||
it->get(),
|
||||
typename MakeIndexSequence<sizeof...(Args)>::Type()
|
||||
);
|
||||
it->clear();
|
||||
|
||||
auto tempIt = it;
|
||||
++it;
|
||||
idleList.splice(idleList.end(), tempList, tempIt);
|
||||
}
|
||||
}
|
||||
|
||||
if (! tempList.empty()) {
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
queueList.splice(queueList.begin(), tempList);
|
||||
}
|
||||
|
||||
if(! idleList.empty()) {
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), idleList);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void wait() const
|
||||
{
|
||||
std::unique_lock<Mutex> queueListLock(queueListMutex);
|
||||
queueListConditionVariable.wait(queueListLock, [this]() -> bool {
|
||||
return doCanProcess();
|
||||
});
|
||||
}
|
||||
|
||||
template <class Rep, class Period>
|
||||
bool waitFor(const std::chrono::duration<Rep, Period> & duration) const
|
||||
{
|
||||
std::unique_lock<Mutex> queueListLock(queueListMutex);
|
||||
return queueListConditionVariable.wait_for(queueListLock, duration, [this]() -> bool {
|
||||
return doCanProcess();
|
||||
});
|
||||
}
|
||||
|
||||
using super::dispatch;
|
||||
|
||||
template <typename U>
|
||||
auto dispatch(const U & queuedEvent)
|
||||
-> typename std::enable_if<std::is_same<U, QueuedEvent>::value, void>::type
|
||||
{
|
||||
doDispatchQueuedEvent(
|
||||
queuedEvent,
|
||||
typename MakeIndexSequence<sizeof...(Args)>::Type()
|
||||
);
|
||||
}
|
||||
|
||||
bool peekEvent(QueuedEvent * queuedEvent)
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
|
||||
if(! queueList.empty()) {
|
||||
*queuedEvent = queueList.front().get();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool takeEvent(QueuedEvent * queuedEvent)
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
|
||||
if(! queueList.empty()) {
|
||||
tempList.splice(tempList.end(), queueList, queueList.begin());
|
||||
}
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
*queuedEvent = std::move(tempList.front().get());
|
||||
tempList.front().clear();
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), tempList);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
protected:
|
||||
bool doCanProcess() const
|
||||
{
|
||||
return ! emptyQueue() && doCanNotifyQueueAvailable();
|
||||
}
|
||||
|
||||
bool doCanNotifyQueueAvailable() const
|
||||
{
|
||||
return queueNotifyCounter.load(std::memory_order_acquire) == 0;
|
||||
}
|
||||
|
||||
template <typename T, size_t ...Indexes>
|
||||
void doDispatchQueuedEvent(T && item, IndexSequence<Indexes...>)
|
||||
{
|
||||
this->directDispatch(item.event, std::get<Indexes>(item.arguments)...);
|
||||
}
|
||||
|
||||
template <typename F, typename T, size_t ...Indexes>
|
||||
bool doInvokeFuncWithQueuedEvent(F && func, T && item, IndexSequence<Indexes...>) const
|
||||
{
|
||||
return doInvokeFuncWithQueuedEventHelper(std::forward<F>(func), std::get<Indexes>(item.arguments)...);
|
||||
}
|
||||
|
||||
template <typename F>
|
||||
auto doInvokeFuncWithQueuedEventHelper(F && func, Args ...args) const
|
||||
-> typename std::enable_if<! CanInvoke<F>::value, bool>::type
|
||||
{
|
||||
return func(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename F>
|
||||
auto doInvokeFuncWithQueuedEventHelper(F && func, Args .../*args*/) const
|
||||
-> typename std::enable_if<CanInvoke<F>::value, bool>::type
|
||||
{
|
||||
return func();
|
||||
}
|
||||
|
||||
void doEnqueue(QueuedEvent && item)
|
||||
{
|
||||
BufferedItemList tempList;
|
||||
if(! freeList.empty()) {
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
if(! freeList.empty()) {
|
||||
tempList.splice(tempList.end(), freeList, freeList.begin());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(tempList.empty()) {
|
||||
tempList.emplace_back();
|
||||
}
|
||||
|
||||
auto it = tempList.begin();
|
||||
it->set(std::move(item));
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
queueList.splice(queueList.end(), tempList, it);
|
||||
}
|
||||
|
||||
private:
|
||||
mutable ConditionVariable queueListConditionVariable;
|
||||
typename Threading::template Atomic<int> queueEmptyCounter;
|
||||
typename Threading::template Atomic<int> queueNotifyCounter;
|
||||
mutable Mutex queueListMutex;
|
||||
BufferedItemList queueList;
|
||||
Mutex freeListMutex;
|
||||
BufferedItemList freeList;
|
||||
};
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
template <
|
||||
typename Event_,
|
||||
typename Prototype_,
|
||||
typename Policies_ = DefaultPolicies
|
||||
>
|
||||
class EventQueue : public internal_::InheritMixins<
|
||||
internal_::EventQueueBase<Event_, Prototype_, Policies_>,
|
||||
typename internal_::SelectMixins<Policies_, internal_::HasTypeMixins<Policies_>::value >::Type
|
||||
>::Type, public TagEventDispatcher, public TagEventQueue
|
||||
{
|
||||
private:
|
||||
using super = typename internal_::InheritMixins<
|
||||
internal_::EventQueueBase<Event_, Prototype_, Policies_>,
|
||||
typename internal_::SelectMixins<Policies_, internal_::HasTypeMixins<Policies_>::value >::Type
|
||||
>::Type;
|
||||
|
||||
public:
|
||||
using super::super;
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef HETERCALLBACKLIST_H_966730936077
|
||||
#define HETERCALLBACKLIST_H_966730936077
|
||||
|
||||
#include "internal/hetercallbacklist_i.h"
|
||||
#include "callbacklist.h"
|
||||
|
||||
#include <array>
|
||||
#include <mutex>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <
|
||||
typename PrototypeList_,
|
||||
typename Policies_
|
||||
>
|
||||
class HeterCallbackListBase
|
||||
{
|
||||
protected:
|
||||
struct HeterHandle_
|
||||
{
|
||||
int index;
|
||||
std::weak_ptr<void> homoHandle;
|
||||
|
||||
operator bool () const noexcept {
|
||||
return (bool)homoHandle;
|
||||
}
|
||||
};
|
||||
|
||||
struct UnderlyingPoliciesType_
|
||||
{
|
||||
};
|
||||
|
||||
class HomoCallbackListTypeBase
|
||||
{
|
||||
public:
|
||||
virtual ~HomoCallbackListTypeBase() {}
|
||||
|
||||
virtual bool empty() = 0;
|
||||
virtual bool doRemove(const HeterHandle_ & handle) = 0;
|
||||
virtual std::shared_ptr<HomoCallbackListTypeBase> doClone() = 0;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class HomoCallbackListType : public CallbackList<T, UnderlyingPoliciesType_>, public HomoCallbackListTypeBase
|
||||
{
|
||||
private:
|
||||
using super = CallbackList<T, UnderlyingPoliciesType_>;
|
||||
|
||||
public:
|
||||
virtual bool empty() override {
|
||||
return super::empty();
|
||||
}
|
||||
|
||||
virtual bool doRemove(const HeterHandle_ & handle) override {
|
||||
auto sp = handle.homoHandle.lock();
|
||||
if(! sp) {
|
||||
return false;
|
||||
}
|
||||
return this->remove(typename super::Handle(std::static_pointer_cast<typename super::Handle::element_type>(sp)));
|
||||
}
|
||||
|
||||
virtual std::shared_ptr<HomoCallbackListTypeBase> doClone() override {
|
||||
return std::make_shared<HomoCallbackListType<T> >(*this);
|
||||
}
|
||||
};
|
||||
|
||||
using Policies = Policies_;
|
||||
using Threading = typename SelectThreading<Policies, HasTypeThreading<Policies>::value>::Type;
|
||||
|
||||
using PrototypeList = PrototypeList_;
|
||||
|
||||
public:
|
||||
using Handle = HeterHandle_;
|
||||
using Mutex = typename Threading::Mutex;
|
||||
|
||||
public:
|
||||
HeterCallbackListBase()
|
||||
:
|
||||
callbackListList(),
|
||||
callbackListListMutex()
|
||||
{
|
||||
}
|
||||
|
||||
HeterCallbackListBase(const HeterCallbackListBase & other)
|
||||
:
|
||||
callbackListList(),
|
||||
callbackListListMutex()
|
||||
{
|
||||
for(size_t i = 0; i < callbackListList.size(); ++i) {
|
||||
if(other.callbackListList[i]) {
|
||||
callbackListList[i] = other.callbackListList[i]->doClone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
HeterCallbackListBase(HeterCallbackListBase && other) noexcept
|
||||
:
|
||||
callbackListList(std::move(other.callbackListList)),
|
||||
callbackListListMutex()
|
||||
{
|
||||
}
|
||||
|
||||
// If we use pass by value idiom and omit the 'this' check,
|
||||
// when assigning to self there is a deep copy which is inefficient.
|
||||
HeterCallbackListBase & operator = (const HeterCallbackListBase & other) noexcept
|
||||
{
|
||||
if(this != &other) {
|
||||
HeterCallbackListBase copied(other);
|
||||
swap(copied);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
HeterCallbackListBase & operator = (HeterCallbackListBase && other) noexcept
|
||||
{
|
||||
if(this != &other) {
|
||||
for(size_t i = 0; i < callbackListList.size(); ++i) {
|
||||
callbackListList[i] = std::move(other.callbackListList[i]);
|
||||
}
|
||||
}
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
void swap(HeterCallbackListBase & other) noexcept {
|
||||
using std::swap;
|
||||
|
||||
swap(callbackListList, other.callbackListList);
|
||||
}
|
||||
|
||||
bool empty() const {
|
||||
for(const auto & callbackList : callbackListList) {
|
||||
if(callbackList && ! callbackList->empty()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
operator bool() const {
|
||||
return ! empty();
|
||||
}
|
||||
|
||||
template <typename C>
|
||||
Handle append(const C & callback)
|
||||
{
|
||||
using PrototypeInfo = FindPrototypeByCallable<PrototypeList_, C>;
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
|
||||
auto callbackList= doGetCallbackList<PrototypeInfo>();
|
||||
return Handle {
|
||||
PrototypeInfo::index,
|
||||
callbackList->append(callback)
|
||||
};
|
||||
}
|
||||
|
||||
template <typename C>
|
||||
Handle prepend(const C & callback)
|
||||
{
|
||||
using PrototypeInfo = FindPrototypeByCallable<PrototypeList_, C>;
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
|
||||
auto callbackList= doGetCallbackList<PrototypeInfo>();
|
||||
return Handle {
|
||||
PrototypeInfo::index,
|
||||
callbackList->prepend(callback)
|
||||
};
|
||||
}
|
||||
|
||||
template <typename C>
|
||||
Handle insert(const C & callback, const Handle & before)
|
||||
{
|
||||
using PrototypeInfo = FindPrototypeByCallable<PrototypeList_, C>;
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
|
||||
auto callbackList= doGetCallbackList<PrototypeInfo>();
|
||||
|
||||
if(before.index != PrototypeInfo::index) {
|
||||
return Handle {
|
||||
PrototypeInfo::index,
|
||||
callbackList->append(callback)
|
||||
};
|
||||
}
|
||||
|
||||
using UnderlyingHandle = typename decltype(callbackList)::element_type::Handle;
|
||||
|
||||
return Handle {
|
||||
PrototypeInfo::index,
|
||||
callbackList->insert(
|
||||
callback,
|
||||
UnderlyingHandle(std::static_pointer_cast<typename UnderlyingHandle::element_type>(before.homoHandle.lock()))
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
bool remove(const Handle & handle)
|
||||
{
|
||||
auto callbackList = callbackListList[handle.index];
|
||||
if(callbackList) {
|
||||
return callbackList->doRemove(handle);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename Prototype, typename Func>
|
||||
void forEach(Func && func) const
|
||||
{
|
||||
using PrototypeInfo = FindPrototypeByCallable<PrototypeList, Prototype>;
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
|
||||
auto callbackList= doGetCallbackList<PrototypeInfo>();
|
||||
using CL = typename decltype(callbackList)::element_type;
|
||||
callbackList->forEach([this, &func](const typename CL::Handle & handle, const typename CL::Callback & callback) {
|
||||
doForEachInvoke<void, PrototypeInfo::index>(func, handle, callback);
|
||||
});
|
||||
}
|
||||
|
||||
template <typename Prototype, typename Func>
|
||||
bool forEachIf(Func && func) const
|
||||
{
|
||||
using PrototypeInfo = FindPrototypeByCallable<PrototypeList, Prototype>;
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
|
||||
auto callbackList= doGetCallbackList<PrototypeInfo>();
|
||||
using CL = typename decltype(callbackList)::element_type;
|
||||
return callbackList->forEachIf([this, &func](const typename CL::Handle & handle, const typename CL::Callback & callback) {
|
||||
return doForEachInvoke<bool, PrototypeInfo::index>(func, handle, callback);
|
||||
});
|
||||
}
|
||||
|
||||
template <typename ...Args>
|
||||
void operator() (Args && ...args) const
|
||||
{
|
||||
using PrototypeInfo = FindPrototypeByArgs<PrototypeList, Args...>;
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
|
||||
auto callbackList= doGetCallbackList<PrototypeInfo>();
|
||||
(*callbackList)(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename RT, int PrototypeIndex, typename Func, typename H, typename CL>
|
||||
auto doForEachInvoke(Func && func, const H & handle, CL && callback) const
|
||||
-> typename std::enable_if<CanInvoke<Func, Handle, CL>::value, RT>::type
|
||||
{
|
||||
return func(Handle { PrototypeIndex, handle }, callback);
|
||||
}
|
||||
|
||||
template <typename RT, int PrototypeIndex, typename Func, typename H, typename CL>
|
||||
auto doForEachInvoke(Func && func, const H & /*handle*/, CL && callback) const
|
||||
-> typename std::enable_if<CanInvoke<Func, CL>::value, RT>::type
|
||||
{
|
||||
return func(callback);
|
||||
}
|
||||
|
||||
template <typename PrototypeInfo>
|
||||
auto doGetCallbackList() const
|
||||
-> std::shared_ptr<HomoCallbackListType<typename PrototypeInfo::Prototype> >
|
||||
{
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
|
||||
if(! callbackListList[PrototypeInfo::index]) {
|
||||
std::lock_guard<Mutex> lockGuard(callbackListListMutex);
|
||||
|
||||
if(! callbackListList[PrototypeInfo::index]) {
|
||||
callbackListList[PrototypeInfo::index] = std::make_shared<HomoCallbackListType<typename PrototypeInfo::Prototype> >();
|
||||
}
|
||||
}
|
||||
|
||||
return std::static_pointer_cast<HomoCallbackListType<typename PrototypeInfo::Prototype> >(callbackListList[PrototypeInfo::index]);
|
||||
}
|
||||
|
||||
private:
|
||||
// the postfix 'ListList' is not good, but it's better to use consistent naming convention.
|
||||
mutable std::array<std::shared_ptr<HomoCallbackListTypeBase>, HeterTupleSize<PrototypeList_>::value> callbackListList;
|
||||
mutable Mutex callbackListListMutex;
|
||||
};
|
||||
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
template <
|
||||
typename PrototypeList_,
|
||||
typename Policies_ = DefaultPolicies
|
||||
>
|
||||
class HeterCallbackList : public internal_::HeterCallbackListBase<PrototypeList_, Policies_>, public TagCallbackList, public TagHeterCallbackList
|
||||
{
|
||||
private:
|
||||
using super = internal_::HeterCallbackListBase<PrototypeList_, Policies_>;
|
||||
|
||||
public:
|
||||
using super::super;
|
||||
|
||||
friend void swap(HeterCallbackList & first, HeterCallbackList & second) noexcept {
|
||||
first.swap(second);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,325 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef HETEREVENTDISPATCHER_H_127766658555
|
||||
#define HETEREVENTDISPATCHER_H_127766658555
|
||||
|
||||
#include "mixins/mixinheterfilter.h"
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <
|
||||
typename EventType_,
|
||||
typename PrototypeList_,
|
||||
typename Policies_,
|
||||
typename MixinRoot_
|
||||
>
|
||||
class HeterEventDispatcherBase
|
||||
{
|
||||
protected:
|
||||
using ThisType = HeterEventDispatcherBase<
|
||||
EventType_,
|
||||
PrototypeList_,
|
||||
Policies_,
|
||||
MixinRoot_
|
||||
>;
|
||||
using MixinRoot = typename std::conditional<
|
||||
std::is_same<MixinRoot_, void>::value,
|
||||
ThisType,
|
||||
MixinRoot_
|
||||
>::type;
|
||||
using Policies = Policies_;
|
||||
|
||||
using Threading = typename SelectThreading<Policies, HasTypeThreading<Policies_>::value>::Type;
|
||||
|
||||
using ArgumentPassingMode = typename SelectArgumentPassingMode<
|
||||
Policies_,
|
||||
HasTypeArgumentPassingMode<Policies_>::value,
|
||||
ArgumentPassingExcludeEvent
|
||||
>::Type;
|
||||
|
||||
static_assert(! std::is_same<ArgumentPassingMode, ArgumentPassingAutoDetect>::value,
|
||||
"ArgumentPassingMode can't be ArgumentPassingAutoDetect in heterogeneous dispatcher.");
|
||||
|
||||
using CallbackList_ = HeterCallbackList<PrototypeList_, Policies_>;
|
||||
|
||||
using Map = typename SelectMap<
|
||||
EventType_,
|
||||
CallbackList_,
|
||||
Policies_,
|
||||
HasTemplateMap<Policies_>::value
|
||||
>::Type;
|
||||
|
||||
using Mixins = typename internal_::SelectMixins<
|
||||
Policies_,
|
||||
internal_::HasTypeMixins<Policies_>::value
|
||||
>::Type;
|
||||
|
||||
public:
|
||||
using PrototypeList = PrototypeList_;
|
||||
using Handle = typename CallbackList_::Handle;
|
||||
using Event = EventType_;
|
||||
using Mutex = typename Threading::Mutex;
|
||||
|
||||
public:
|
||||
HeterEventDispatcherBase()
|
||||
:
|
||||
eventCallbackListMap(),
|
||||
listenerMutex()
|
||||
{
|
||||
}
|
||||
|
||||
HeterEventDispatcherBase(const HeterEventDispatcherBase & other)
|
||||
:
|
||||
eventCallbackListMap(other.eventCallbackListMap),
|
||||
listenerMutex()
|
||||
{
|
||||
}
|
||||
|
||||
HeterEventDispatcherBase(HeterEventDispatcherBase && other) noexcept
|
||||
:
|
||||
eventCallbackListMap(std::move(other.eventCallbackListMap)),
|
||||
listenerMutex()
|
||||
{
|
||||
}
|
||||
|
||||
HeterEventDispatcherBase & operator = (const HeterEventDispatcherBase & other)
|
||||
{
|
||||
eventCallbackListMap = other.eventCallbackListMap;
|
||||
return *this;
|
||||
}
|
||||
|
||||
HeterEventDispatcherBase & operator = (HeterEventDispatcherBase && other) noexcept
|
||||
{
|
||||
eventCallbackListMap = std::move(other.eventCallbackListMap);
|
||||
return *this;
|
||||
}
|
||||
|
||||
void swap(HeterEventDispatcherBase & other) noexcept {
|
||||
using std::swap;
|
||||
|
||||
swap(eventCallbackListMap, other.eventCallbackListMap);
|
||||
}
|
||||
|
||||
template <typename C>
|
||||
Handle appendListener(const Event & event, const C & callback)
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(listenerMutex);
|
||||
|
||||
return eventCallbackListMap[event].append(callback);
|
||||
}
|
||||
|
||||
template <typename C>
|
||||
Handle prependListener(const Event & event, const C & callback)
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(listenerMutex);
|
||||
|
||||
return eventCallbackListMap[event].prepend(callback);
|
||||
}
|
||||
|
||||
template <typename C>
|
||||
Handle insertListener(const Event & event, const C & callback, const Handle & before)
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(listenerMutex);
|
||||
|
||||
return eventCallbackListMap[event].insert(callback, before);
|
||||
}
|
||||
|
||||
bool removeListener(const Event & event, const Handle handle)
|
||||
{
|
||||
CallbackList_ * callableList = doFindCallableList(event);
|
||||
if(callableList) {
|
||||
return callableList->remove(handle);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool hasAnyListener(const Event & event) const
|
||||
{
|
||||
const CallbackList_ * callableList = doFindCallableList(event);
|
||||
if(callableList) {
|
||||
return ! callableList->empty();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename Prototype, typename Func>
|
||||
void forEach(const Event & event, Func && func) const
|
||||
{
|
||||
const CallbackList_ * callableList = doFindCallableList(event);
|
||||
if(callableList) {
|
||||
callableList->template forEach<Prototype>(std::forward<Func>(func));
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Prototype, typename Func>
|
||||
bool forEachIf(const Event & event, Func && func) const
|
||||
{
|
||||
const CallbackList_ * callableList = doFindCallableList(event);
|
||||
if (callableList) {
|
||||
return callableList->template forEachIf<Prototype>(std::forward<Func>(func));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename T, typename ...Args>
|
||||
void dispatch(T && first, Args && ...args) const
|
||||
{
|
||||
doDispatch<ArgumentPassingMode>(std::forward<T>(first), std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
// Bypass any getEvent policy. The first argument is the event type.
|
||||
// Most used for internal purpose.
|
||||
template <typename ...Args>
|
||||
void directDispatch(const Event & e, Args && ...args) const
|
||||
{
|
||||
if(! internal_::ForEachMixins<MixinRoot, Mixins, DoMixinBeforeDispatch>::forEach(
|
||||
this, typename std::add_lvalue_reference<Args>::type(args)...)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const CallbackList_ * callableList = doFindCallableList(e);
|
||||
if(callableList) {
|
||||
(*callableList)(std::forward<Args>(args)...);
|
||||
}
|
||||
}
|
||||
|
||||
protected:
|
||||
template <typename ArgumentMode, typename T, typename ...Args>
|
||||
auto doDispatch(T && first, Args && ...args) const
|
||||
-> typename std::enable_if<std::is_same<ArgumentMode, ArgumentPassingIncludeEvent>::value>::type
|
||||
{
|
||||
if(! internal_::ForEachMixins<MixinRoot, Mixins, DoMixinBeforeDispatch>::forEach(
|
||||
this,
|
||||
typename std::add_lvalue_reference<T>::type(first),
|
||||
typename std::add_lvalue_reference<Args>::type(args)...)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
using GetEvent = typename SelectGetEvent<Policies_, EventType_, HasFunctionGetEvent<Policies_, T &&, Args...>::value>::Type;
|
||||
const auto e = GetEvent::getEvent(std::forward<T>(first), args...);
|
||||
const CallbackList_ * callableList = doFindCallableList(e);
|
||||
if(callableList) {
|
||||
(*callableList)(std::forward<T>(first), std::forward<Args>(args)...);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename ArgumentMode, typename T, typename ...Args>
|
||||
auto doDispatch(T && first, Args && ...args) const
|
||||
-> typename std::enable_if<std::is_same<ArgumentMode, ArgumentPassingExcludeEvent>::value>::type
|
||||
{
|
||||
if(! internal_::ForEachMixins<MixinRoot, Mixins, DoMixinBeforeDispatch>::forEach(
|
||||
this,
|
||||
typename std::add_lvalue_reference<Args>::type(args)...)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
using GetEvent = typename SelectGetEvent<Policies_, EventType_, HasFunctionGetEvent<Policies_, T &&, Args...>::value>::Type;
|
||||
const auto e = GetEvent::getEvent(std::forward<T>(first), args...);
|
||||
const CallbackList_ * callableList = doFindCallableList(e);
|
||||
if(callableList) {
|
||||
(*callableList)(std::forward<Args>(args)...);
|
||||
}
|
||||
}
|
||||
|
||||
const CallbackList_ * doFindCallableList(const Event & e) const
|
||||
{
|
||||
return doFindCallableListHelper(this, e);
|
||||
}
|
||||
|
||||
CallbackList_ * doFindCallableList(const Event & e)
|
||||
{
|
||||
return doFindCallableListHelper(this, e);
|
||||
}
|
||||
|
||||
private:
|
||||
// template helper to avoid code duplication in doFindCallableList
|
||||
template <typename T>
|
||||
static auto doFindCallableListHelper(T * self, const Event & e)
|
||||
-> typename std::conditional<std::is_const<T>::value, const CallbackList_ *, CallbackList_ *>::type
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(self->listenerMutex);
|
||||
|
||||
auto it = self->eventCallbackListMap.find(e);
|
||||
if(it != self->eventCallbackListMap.end()) {
|
||||
return &it->second;
|
||||
}
|
||||
else {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private:
|
||||
// Mixin related
|
||||
struct DoMixinBeforeDispatch
|
||||
{
|
||||
template <typename T, typename Self, typename ...A>
|
||||
static auto forEach(const Self * self, A && ...args)
|
||||
-> typename std::enable_if<HasFunctionMixinBeforeDispatch<T, A...>::value, bool>::type {
|
||||
return static_cast<const T *>(self)->mixinBeforeDispatch(std::forward<A>(args)...);
|
||||
}
|
||||
|
||||
template <typename T, typename Self, typename ...A>
|
||||
static auto forEach(const Self * self, A && ...args)
|
||||
-> typename std::enable_if<! HasFunctionMixinBeforeDispatch<T, A...>::value, bool>::type {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
private:
|
||||
Map eventCallbackListMap;
|
||||
mutable Mutex listenerMutex;
|
||||
};
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
|
||||
template <
|
||||
typename Event_,
|
||||
typename PrototypeList_,
|
||||
typename Policies_ = DefaultPolicies
|
||||
>
|
||||
class HeterEventDispatcher : public internal_::InheritMixins<
|
||||
internal_::HeterEventDispatcherBase<Event_, PrototypeList_, Policies_, void>,
|
||||
typename internal_::SelectMixins<Policies_, internal_::HasTypeMixins<Policies_>::value >::Type
|
||||
>::Type, public TagEventDispatcher, public TagHeterEventDispatcher
|
||||
{
|
||||
private:
|
||||
using super = typename internal_::InheritMixins<
|
||||
internal_::HeterEventDispatcherBase<Event_, PrototypeList_, Policies_, void>,
|
||||
typename internal_::SelectMixins<Policies_, internal_::HasTypeMixins<Policies_>::value >::Type
|
||||
>::Type;
|
||||
|
||||
public:
|
||||
using super::super;
|
||||
|
||||
friend void swap(HeterEventDispatcher & first, HeterEventDispatcher & second) noexcept {
|
||||
first.swap(second);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,482 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef HETEREVENTQUEUE_H_210892536510
|
||||
#define HETEREVENTQUEUE_H_210892536510
|
||||
|
||||
#include "hetereventdispatcher.h"
|
||||
|
||||
// temp, should move the internal code in eventqueue to separated file
|
||||
#include "eventqueue.h"
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <
|
||||
typename EventType_,
|
||||
typename PrototypeList_,
|
||||
typename Policies_
|
||||
>
|
||||
class HeterEventQueueBase : public HeterEventDispatcherBase<
|
||||
EventType_,
|
||||
PrototypeList_,
|
||||
Policies_,
|
||||
HeterEventQueueBase <
|
||||
EventType_,
|
||||
PrototypeList_,
|
||||
Policies_
|
||||
>
|
||||
>
|
||||
{
|
||||
private:
|
||||
using super = HeterEventDispatcherBase<
|
||||
EventType_,
|
||||
PrototypeList_,
|
||||
Policies_,
|
||||
HeterEventQueueBase <
|
||||
EventType_,
|
||||
PrototypeList_,
|
||||
Policies_
|
||||
>
|
||||
>;
|
||||
|
||||
using Policies = typename super::Policies;
|
||||
using Threading = typename super::Threading;
|
||||
using ConditionVariable = typename Threading::ConditionVariable;
|
||||
|
||||
struct QueuedItemBase;
|
||||
using ItemDispatcher = void (*)(const HeterEventQueueBase *, const QueuedItemBase &);
|
||||
|
||||
struct QueuedItemBase
|
||||
{
|
||||
QueuedItemBase(const int callableIndex, const EventType_ & event, const ItemDispatcher dispatcher)
|
||||
: callableIndex(callableIndex), event(event), dispatcher(dispatcher)
|
||||
{
|
||||
}
|
||||
|
||||
int callableIndex;
|
||||
EventType_ event;
|
||||
ItemDispatcher dispatcher;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct QueuedItem : public QueuedItemBase
|
||||
{
|
||||
QueuedItem(const int callableIndex, const EventType_ & event, const ItemDispatcher dispatcher, T && arguments)
|
||||
: QueuedItemBase(callableIndex, event, dispatcher), arguments(std::move(arguments))
|
||||
{
|
||||
}
|
||||
|
||||
T arguments;
|
||||
};
|
||||
|
||||
template <typename ...Args>
|
||||
using QueuedItemSizer = QueuedItem<std::tuple<typename std::remove_cv<typename std::remove_reference<Args>::type>::type...> >;
|
||||
|
||||
using BufferedQueuedItem = BufferedUnion<GetCallablePrototypeMaxSize<PrototypeList_, QueuedItemSizer>::value>;
|
||||
|
||||
using BufferedItemList = std::list<BufferedQueuedItem>;
|
||||
|
||||
using PrototypeList = typename super::PrototypeList;
|
||||
|
||||
using ArgumentPassingMode = typename super::ArgumentPassingMode;
|
||||
|
||||
public:
|
||||
using Event = typename super::Event;
|
||||
using Handle = typename super::Handle;
|
||||
using Mutex = typename super::Mutex;
|
||||
|
||||
public:
|
||||
HeterEventQueueBase()
|
||||
:
|
||||
super(),
|
||||
queueListConditionVariable(),
|
||||
queueEmptyCounter(0),
|
||||
queueNotifyCounter(0),
|
||||
queueListMutex(),
|
||||
queueList(),
|
||||
freeListMutex(),
|
||||
freeList()
|
||||
{
|
||||
}
|
||||
|
||||
HeterEventQueueBase(const HeterEventQueueBase & other)
|
||||
: super(other)
|
||||
{
|
||||
}
|
||||
|
||||
HeterEventQueueBase(HeterEventQueueBase && other) noexcept
|
||||
: super(std::move(other))
|
||||
{
|
||||
}
|
||||
|
||||
HeterEventQueueBase & operator = (const HeterEventQueueBase & other)
|
||||
{
|
||||
super::operator = (other);
|
||||
return *this;
|
||||
}
|
||||
|
||||
HeterEventQueueBase & operator = (HeterEventQueueBase && other) noexcept
|
||||
{
|
||||
super::operator = (std::move(other));
|
||||
return *this;
|
||||
}
|
||||
|
||||
template <typename T, typename ...Args>
|
||||
void enqueue(T && first, Args && ...args)
|
||||
{
|
||||
doEnqueue<ArgumentPassingMode>(std::forward<T>(first), std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
bool emptyQueue() const
|
||||
{
|
||||
return queueList.empty() && (queueEmptyCounter.load(std::memory_order_acquire) == 0);
|
||||
}
|
||||
|
||||
void clearEvents()
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
std::swap(queueList, tempList);
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
for(auto & item : tempList) {
|
||||
item.clear();
|
||||
}
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), tempList);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool process()
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
|
||||
// Use a counter to tell the queue list is not empty during processing
|
||||
// even though queueList is swapped to empty.
|
||||
CounterGuard<decltype(queueEmptyCounter)> counterGuard(queueEmptyCounter);
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
std::swap(queueList, tempList);
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
for(auto & item : tempList) {
|
||||
doDispatchQueuedEvent(item.template get<QueuedItemBase>());
|
||||
item.clear();
|
||||
}
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), tempList);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool processOne()
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
|
||||
// Use a counter to tell the queue list is not empty during processing
|
||||
// even though queueList is swapped to empty.
|
||||
CounterGuard<decltype(queueEmptyCounter)> counterGuard(queueEmptyCounter);
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
if(! queueList.empty()) {
|
||||
tempList.splice(tempList.end(), queueList, queueList.begin());
|
||||
}
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
auto & item = tempList.front();
|
||||
doDispatchQueuedEvent(item.template get<QueuedItemBase>());
|
||||
item.clear();
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), tempList);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename F>
|
||||
bool processIf(F && func)
|
||||
{
|
||||
if(queueList.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
using PrototypeInfo = FindPrototypeByCallable<PrototypeList, F>;
|
||||
return doProcessIf<PrototypeInfo>(std::forward<F>(func));
|
||||
}
|
||||
|
||||
void wait() const
|
||||
{
|
||||
std::unique_lock<Mutex> queueListLock(queueListMutex);
|
||||
queueListConditionVariable.wait(queueListLock, [this]() -> bool {
|
||||
return doCanProcess();
|
||||
});
|
||||
}
|
||||
|
||||
template <class Rep, class Period>
|
||||
bool waitFor(const std::chrono::duration<Rep, Period> & duration) const
|
||||
{
|
||||
std::unique_lock<Mutex> queueListLock(queueListMutex);
|
||||
return queueListConditionVariable.wait_for(queueListLock, duration, [this]() -> bool {
|
||||
return doCanProcess();
|
||||
});
|
||||
}
|
||||
|
||||
using super::dispatch;
|
||||
|
||||
private:
|
||||
bool doCanProcess() const
|
||||
{
|
||||
return ! emptyQueue() && doCanNotifyQueueAvailable();
|
||||
}
|
||||
|
||||
bool doCanNotifyQueueAvailable() const
|
||||
{
|
||||
return queueNotifyCounter.load(std::memory_order_acquire) == 0;
|
||||
}
|
||||
|
||||
void doDispatchQueuedEvent(const QueuedItemBase & item)
|
||||
{
|
||||
item.dispatcher(this, item);
|
||||
}
|
||||
|
||||
template <typename PrototypeInfo>
|
||||
static void doDispatchItem(const HeterEventQueueBase * self, const QueuedItemBase & baseItem)
|
||||
{
|
||||
const auto & item = static_cast<const QueuedItem<typename PrototypeInfo::ArgsTuple> &>(baseItem);
|
||||
self->doDispatchQueuedItem<PrototypeInfo>(
|
||||
item,
|
||||
typename MakeIndexSequence<std::tuple_size<typename PrototypeInfo::ArgsTuple>::value>::Type()
|
||||
);
|
||||
}
|
||||
|
||||
template <typename PrototypeInfo, typename T, size_t ...Indexes>
|
||||
void doDispatchQueuedItem(T && item, IndexSequence<Indexes...>) const
|
||||
{
|
||||
this->directDispatch(item.event, std::get<Indexes>(item.arguments)...);
|
||||
}
|
||||
|
||||
template <typename PrototypeInfo, typename F>
|
||||
auto doProcessIf(F && func)
|
||||
-> typename std::enable_if<(PrototypeInfo::index >= 0), bool>::type
|
||||
{
|
||||
BufferedItemList tempList;
|
||||
BufferedItemList idleList;
|
||||
|
||||
// Use a counter to tell the queue list is not empty during processing
|
||||
// even though queueList is swapped to empty.
|
||||
CounterGuard<decltype(queueEmptyCounter)> counterGuard(queueEmptyCounter);
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
std::swap(queueList, tempList);
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
for(auto it = tempList.begin(); it != tempList.end(); ) {
|
||||
using ArgsTuple = typename PrototypeInfo::ArgsTuple;
|
||||
auto item = it->template get<QueuedItem<ArgsTuple> >();
|
||||
|
||||
if(item.callableIndex != PrototypeInfo::index) {
|
||||
++it;
|
||||
continue;
|
||||
}
|
||||
if(doInvokeFuncWithQueuedEvent(
|
||||
func,
|
||||
item,
|
||||
typename MakeIndexSequence<std::tuple_size<ArgsTuple>::value>::Type())
|
||||
) {
|
||||
doDispatchQueuedEvent(item);
|
||||
it->clear();
|
||||
|
||||
auto tempIt = it;
|
||||
++it;
|
||||
idleList.splice(idleList.end(), tempList, tempIt);
|
||||
}
|
||||
else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
|
||||
if (! tempList.empty()) {
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
queueList.splice(queueList.begin(), tempList);
|
||||
}
|
||||
|
||||
if(! idleList.empty()) {
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), idleList);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
using NextPrototypeInfo = FindPrototypeByCallableFromIndex<PrototypeInfo::index + 1, PrototypeList, F>;
|
||||
if(doProcessIf<NextPrototypeInfo>(std::forward<F>(func))) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename PrototypeInfo, typename F>
|
||||
auto doProcessIf(F && /*func*/)
|
||||
-> typename std::enable_if<(PrototypeInfo::index < 0), bool>::type
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename F, typename T, size_t ...Indexes>
|
||||
bool doInvokeFuncWithQueuedEvent(F && func, T && item, IndexSequence<Indexes...>) const
|
||||
{
|
||||
return doInvokeFuncWithQueuedEventHelper(std::forward<F>(func), std::get<Indexes>(item.arguments)...);
|
||||
}
|
||||
|
||||
template <typename F, typename ...Args>
|
||||
bool doInvokeFuncWithQueuedEventHelper(F && func, Args && ...args) const
|
||||
{
|
||||
return func(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename ArgumentMode, typename T, typename ...Args>
|
||||
auto doEnqueue(T && first, Args && ...args)
|
||||
-> typename std::enable_if<std::is_same<ArgumentMode, ArgumentPassingIncludeEvent>::value>::type
|
||||
{
|
||||
using GetEvent = typename SelectGetEvent<Policies_, EventType_, HasFunctionGetEvent<Policies_, T &&, Args...>::value>::Type;
|
||||
using PrototypeInfo = FindPrototypeByArgs<PrototypeList_, T, Args...>;
|
||||
using QueuedItemType = QueuedItem<typename PrototypeInfo::ArgsTuple>;
|
||||
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
static_assert(std::tuple_size<typename PrototypeInfo::ArgsTuple>::value == 1 + sizeof...(Args), "Arguments count mismatch.");
|
||||
|
||||
doEnqueueItem(QueuedItemType(
|
||||
PrototypeInfo::index,
|
||||
GetEvent::getEvent(std::forward<T>(first), args...),
|
||||
&HeterEventQueueBase::doDispatchItem<PrototypeInfo>,
|
||||
typename PrototypeInfo::ArgsTuple(std::forward<T>(first), std::forward<Args>(args)...)
|
||||
));
|
||||
|
||||
if(doCanProcess()) {
|
||||
queueListConditionVariable.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
template <typename ArgumentMode, typename T, typename ...Args>
|
||||
auto doEnqueue(T && first, Args && ...args)
|
||||
-> typename std::enable_if<std::is_same<ArgumentMode, ArgumentPassingExcludeEvent>::value>::type
|
||||
{
|
||||
using GetEvent = typename SelectGetEvent<Policies_, EventType_, HasFunctionGetEvent<Policies_, T &&, Args...>::value>::Type;
|
||||
using PrototypeInfo = FindPrototypeByArgs<PrototypeList_, Args...>;
|
||||
using QueuedItemType = QueuedItem<typename PrototypeInfo::ArgsTuple>;
|
||||
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
static_assert(std::tuple_size<typename PrototypeInfo::ArgsTuple>::value == sizeof...(Args), "Arguments count mismatch.");
|
||||
|
||||
doEnqueueItem(QueuedItemType(
|
||||
PrototypeInfo::index,
|
||||
GetEvent::getEvent(std::forward<T>(first), args...),
|
||||
&HeterEventQueueBase::doDispatchItem<PrototypeInfo>,
|
||||
typename PrototypeInfo::ArgsTuple(std::forward<Args>(args)...)
|
||||
));
|
||||
|
||||
if(doCanProcess()) {
|
||||
queueListConditionVariable.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void doEnqueueItem(T && item)
|
||||
{
|
||||
BufferedItemList tempList;
|
||||
if(! freeList.empty()) {
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
if(! freeList.empty()) {
|
||||
tempList.splice(tempList.end(), freeList, freeList.begin());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(tempList.empty()) {
|
||||
tempList.emplace_back();
|
||||
}
|
||||
|
||||
auto it = tempList.begin();
|
||||
it->set(std::move(item));
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
queueList.splice(queueList.end(), tempList, it);
|
||||
}
|
||||
|
||||
private:
|
||||
mutable ConditionVariable queueListConditionVariable;
|
||||
typename Threading::template Atomic<int> queueEmptyCounter;
|
||||
typename Threading::template Atomic<int> queueNotifyCounter;
|
||||
mutable Mutex queueListMutex;
|
||||
BufferedItemList queueList;
|
||||
Mutex freeListMutex;
|
||||
BufferedItemList freeList;
|
||||
};
|
||||
|
||||
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
template <
|
||||
typename Event_,
|
||||
typename PrototypeList_,
|
||||
typename Policies_ = DefaultPolicies
|
||||
>
|
||||
class HeterEventQueue : public internal_::InheritMixins<
|
||||
internal_::HeterEventQueueBase<Event_, PrototypeList_, Policies_>,
|
||||
typename internal_::SelectMixins<Policies_, internal_::HasTypeMixins<Policies_>::value >::Type
|
||||
>::Type, public TagEventDispatcher, public TagEventQueue, public TagHeterEventDispatcher, public TagHeterEventQueue
|
||||
{
|
||||
private:
|
||||
using super = typename internal_::InheritMixins<
|
||||
internal_::HeterEventQueueBase<Event_, PrototypeList_, Policies_>,
|
||||
typename internal_::SelectMixins<Policies_, internal_::HasTypeMixins<Policies_>::value >::Type
|
||||
>::Type;
|
||||
|
||||
public:
|
||||
using super::super;
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
// Don't include this header, include eventpolicies.h instead
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <typename T>
|
||||
struct HasTypeArgumentPassingMode
|
||||
{
|
||||
template <typename C> static std::true_type test(typename C::ArgumentPassingMode *) ;
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
template <typename T, bool, typename Default> struct SelectArgumentPassingMode { using Type = typename T::ArgumentPassingMode; };
|
||||
template <typename T, typename Default> struct SelectArgumentPassingMode <T, false, Default> { using Type = Default; };
|
||||
|
||||
template <typename T>
|
||||
struct HasTypeThreading
|
||||
{
|
||||
template <typename C> static std::true_type test(typename C::Threading *) ;
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
template <typename T, bool> struct SelectThreading { using Type = typename T::Threading; };
|
||||
template <typename T> struct SelectThreading <T, false> { using Type = MultipleThreading; };
|
||||
|
||||
template <typename T>
|
||||
struct HasTypeCallback
|
||||
{
|
||||
template <typename C> static std::true_type test(typename C::Callback *) ;
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
template <typename T, bool, typename D> struct SelectCallback { using Type = typename T::Callback; };
|
||||
template <typename T, typename D> struct SelectCallback<T, false, D> { using Type = D; };
|
||||
|
||||
template <typename T, typename ...Args>
|
||||
struct HasFunctionGetEvent
|
||||
{
|
||||
template <typename C> static std::true_type test(decltype(C::getEvent(std::declval<Args>()...)) *);
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
template <typename E>
|
||||
struct DefaultGetEvent
|
||||
{
|
||||
template <typename U, typename ...Args>
|
||||
static E getEvent(U && e, Args && ...) {
|
||||
return e;
|
||||
}
|
||||
};
|
||||
template <typename T, typename Key, bool> struct SelectGetEvent { using Type = T; };
|
||||
template <typename T, typename Key> struct SelectGetEvent<T, Key, false> { using Type = DefaultGetEvent<Key>; };
|
||||
|
||||
template <typename T, typename ...Args>
|
||||
struct HasFunctionCanContinueInvoking
|
||||
{
|
||||
template <typename C> static std::true_type test(decltype(C::canContinueInvoking(std::declval<Args>()...)) *) ;
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
struct DefaultCanContinueInvoking
|
||||
{
|
||||
template <typename ...Args>
|
||||
static bool canContinueInvoking(Args && ...) {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
template <typename T, bool> struct SelectCanContinueInvoking { using Type = T; };
|
||||
template <typename T> struct SelectCanContinueInvoking<T, false> { using Type = DefaultCanContinueInvoking; };
|
||||
|
||||
template <typename T>
|
||||
struct HasTemplateMap
|
||||
{
|
||||
template <typename C> static std::true_type test(typename C::template Map<int, int> *) ;
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
template <typename T>
|
||||
class HasHash
|
||||
{
|
||||
template <typename C> static std::true_type test(decltype(std::hash<C>()(std::declval<C>())) *) ;
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
public:
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
template <typename Key, typename Value, typename T, bool>
|
||||
struct SelectMap
|
||||
{
|
||||
using Type = typename T::template Map<Key, Value>;
|
||||
};
|
||||
template <typename Key, typename Value, typename T>
|
||||
struct SelectMap<Key, Value, T, false> {
|
||||
using Type = typename std::conditional<
|
||||
HasHash<Key>::value,
|
||||
std::unordered_map<Key, Value>,
|
||||
std::map<Key, Value>
|
||||
>::type;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct HasTemplateQueueList
|
||||
{
|
||||
template <typename C> static std::true_type test(typename C::template QueueList<int> *);
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
template <typename Value, typename T, bool>
|
||||
struct SelectQueueList
|
||||
{
|
||||
using Type = typename T::template QueueList<Value>;
|
||||
};
|
||||
template <typename Value, typename T>
|
||||
struct SelectQueueList<Value, T, false> {
|
||||
using Type = std::list<Value>;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct HasTypeMixins
|
||||
{
|
||||
template <typename C> static std::true_type test(typename C::Mixins *) ;
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
template <typename T, bool> struct SelectMixins { using Type = typename T::Mixins; };
|
||||
template <typename T> struct SelectMixins <T, false> { using Type = MixinList<>; };
|
||||
|
||||
|
||||
template <typename Root, typename TList>
|
||||
struct InheritMixins;
|
||||
|
||||
template <typename Root, template <typename> class T, template <typename> class ...Args>
|
||||
struct InheritMixins <Root, MixinList<T, Args...> >
|
||||
{
|
||||
using Type = T <typename InheritMixins<Root, MixinList<Args...> >::Type>;
|
||||
};
|
||||
|
||||
template <typename Root>
|
||||
struct InheritMixins <Root, MixinList<> >
|
||||
{
|
||||
using Type = Root;
|
||||
};
|
||||
|
||||
template <typename Root, typename TList, typename Func>
|
||||
struct ForEachMixins;
|
||||
|
||||
template <typename Func, typename Root, template <typename> class T, template <typename> class ...Args>
|
||||
struct ForEachMixins <Root, MixinList<T, Args...>, Func>
|
||||
{
|
||||
using Type = typename InheritMixins<Root, MixinList<T, Args...> >::Type;
|
||||
|
||||
template <typename ...A>
|
||||
static bool forEach(A && ...args) {
|
||||
if(Func::template forEach<Type>(args...)) {
|
||||
return ForEachMixins<Root, MixinList<Args...>, Func>::forEach(std::forward<A>(args)...);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Root, typename Func>
|
||||
struct ForEachMixins <Root, MixinList<>, Func>
|
||||
{
|
||||
using Type = Root;
|
||||
|
||||
template <typename ...A>
|
||||
static bool forEach(A && .../*args*/) {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T, typename ...Args>
|
||||
struct HasFunctionMixinBeforeDispatch
|
||||
{
|
||||
template <typename C> static std::true_type test(
|
||||
decltype(std::declval<C>().mixinBeforeDispatch(std::declval<Args>()...)) *
|
||||
);
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
|
||||
|
||||
} //namespace internal_
|
||||
@@ -0,0 +1,174 @@
|
||||
#ifndef EVENTQUEUE_I_H
|
||||
#define EVENTQUEUE_I_H
|
||||
|
||||
#include <array>
|
||||
#include <cassert>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <size_t ...Indexes>
|
||||
struct IndexSequence
|
||||
{
|
||||
};
|
||||
|
||||
template <size_t N, size_t ...Indexes>
|
||||
struct MakeIndexSequence : MakeIndexSequence <N - 1, N - 1, Indexes...>
|
||||
{
|
||||
};
|
||||
|
||||
template <std::size_t ...Indexes>
|
||||
struct MakeIndexSequence<0, Indexes...>
|
||||
{
|
||||
using Type = IndexSequence<Indexes...>;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct CounterGuard
|
||||
{
|
||||
explicit CounterGuard(T & v) : value(v) {
|
||||
++value;
|
||||
}
|
||||
|
||||
~CounterGuard() {
|
||||
--value;
|
||||
}
|
||||
|
||||
T & value;
|
||||
};
|
||||
|
||||
using DtorFunc = void (*)(void *);
|
||||
|
||||
template <typename T>
|
||||
void commonDtor(void * instance)
|
||||
{
|
||||
reinterpret_cast<T *>(instance)->~T();
|
||||
}
|
||||
|
||||
// used by EventQueue
|
||||
template <typename T>
|
||||
class BufferedItem
|
||||
{
|
||||
public:
|
||||
using ValueType = T;
|
||||
|
||||
public:
|
||||
explicit BufferedItem() : buffer(), dtor(nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
~BufferedItem()
|
||||
{
|
||||
if(dtor != nullptr) {
|
||||
clear();
|
||||
}
|
||||
}
|
||||
|
||||
BufferedItem(BufferedItem &&) = delete;
|
||||
BufferedItem(const BufferedItem &) = delete;
|
||||
BufferedItem & operator = (const BufferedItem &) = delete;
|
||||
|
||||
void set(T && item) {
|
||||
assert(dtor == nullptr);
|
||||
|
||||
new (buffer.data()) T(std::forward<T>(item));
|
||||
dtor = &commonDtor<T>;
|
||||
}
|
||||
|
||||
T & get() {
|
||||
assert(dtor != nullptr);
|
||||
|
||||
return *reinterpret_cast<T *>(buffer.data());
|
||||
}
|
||||
|
||||
const T & get() const {
|
||||
assert(dtor != nullptr);
|
||||
|
||||
return *reinterpret_cast<const T *>(buffer.data());
|
||||
}
|
||||
|
||||
void clear() {
|
||||
assert(dtor != nullptr);
|
||||
|
||||
dtor(buffer.data());
|
||||
dtor = nullptr;
|
||||
}
|
||||
|
||||
bool empty() const {
|
||||
return dtor == nullptr;
|
||||
}
|
||||
|
||||
private:
|
||||
std::array<char, sizeof(T)> buffer;
|
||||
DtorFunc dtor;
|
||||
};
|
||||
|
||||
|
||||
// used by HeterEventQueue
|
||||
template <size_t Size>
|
||||
class BufferedUnion
|
||||
{
|
||||
public:
|
||||
explicit BufferedUnion() : buffer(), dtor(nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
~BufferedUnion()
|
||||
{
|
||||
if(dtor != nullptr) {
|
||||
clear();
|
||||
}
|
||||
}
|
||||
|
||||
BufferedUnion(BufferedUnion &&) = delete;
|
||||
BufferedUnion(const BufferedUnion &) = delete;
|
||||
BufferedUnion & operator = (const BufferedUnion &) = delete;
|
||||
|
||||
template <typename U>
|
||||
void set(U && item) {
|
||||
static_assert(sizeof(U) <= Size, "Item is too large to fit in BufferedUnion");
|
||||
assert(dtor == nullptr);
|
||||
|
||||
new (buffer.data()) U(std::forward<U>(item));
|
||||
dtor = &commonDtor<U>;
|
||||
}
|
||||
|
||||
template <typename U>
|
||||
U & get() {
|
||||
assert(dtor != nullptr);
|
||||
|
||||
return *reinterpret_cast<U *>(buffer.data());
|
||||
}
|
||||
|
||||
template <typename U>
|
||||
const U & get() const {
|
||||
assert(dtor != nullptr);
|
||||
|
||||
return *reinterpret_cast<const U *>(buffer.data());
|
||||
}
|
||||
|
||||
void clear() {
|
||||
assert(dtor != nullptr);
|
||||
|
||||
dtor(buffer.data());
|
||||
dtor = nullptr;
|
||||
}
|
||||
|
||||
bool empty() const {
|
||||
return dtor == nullptr;
|
||||
}
|
||||
|
||||
private:
|
||||
std::array<char, Size> buffer;
|
||||
DtorFunc dtor;
|
||||
};
|
||||
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef HETERCALLBACKLIST_I_H
|
||||
#define HETERCALLBACKLIST_I_H
|
||||
|
||||
#include "typeutil_i.h"
|
||||
|
||||
#include <tuple>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
/*
|
||||
// We can't use std::tuple as HeterTuple because std::tuple is instantialized
|
||||
// somewhere in the Map in HeterEventDispatcherBase, that causes compile error
|
||||
// for that function type can't be declared.
|
||||
template <typename ...Types>
|
||||
using HeterTuple = std::tuple<Types...>;
|
||||
|
||||
template <typename T>
|
||||
struct HeterTupleSize;
|
||||
|
||||
template <typename ...Types>
|
||||
struct HeterTupleSize <HeterTuple <Types...> >
|
||||
{
|
||||
enum { value = std::tuple_size<HeterTuple <Types...> >::value };
|
||||
};
|
||||
*/
|
||||
|
||||
template <typename ...Types>
|
||||
struct HeterTuple
|
||||
{
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct HeterTupleSize;
|
||||
|
||||
template <typename ...Types>
|
||||
struct HeterTupleSize <HeterTuple <Types...> >
|
||||
{
|
||||
enum { value = sizeof...(Types) };
|
||||
};
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <typename T>
|
||||
struct FindPrototypeDefaultArgTransformer
|
||||
{
|
||||
using type = T;
|
||||
};
|
||||
|
||||
template <
|
||||
int N,
|
||||
typename PrototypeList_,
|
||||
typename Callable,
|
||||
template <typename> class ArgTransformer = FindPrototypeDefaultArgTransformer,
|
||||
int M = HeterTupleSize<PrototypeList_>::value,
|
||||
typename Enabled = void
|
||||
>
|
||||
struct FindPrototypeByCallableFromIndex;
|
||||
|
||||
template <
|
||||
int N,
|
||||
typename RT,
|
||||
typename ...Args,
|
||||
typename ...Others,
|
||||
typename Callable,
|
||||
template <typename> class ArgTransformer,
|
||||
int M
|
||||
>
|
||||
struct FindPrototypeByCallableFromIndex <
|
||||
N,
|
||||
HeterTuple<RT (Args...), Others...>,
|
||||
Callable,
|
||||
ArgTransformer,
|
||||
M,
|
||||
typename std::enable_if<(N < M)>::type
|
||||
>
|
||||
{
|
||||
enum { canInvoke = CanInvoke<Callable, typename ArgTransformer<Args>::type...>::value };
|
||||
|
||||
using Prototype = typename std::conditional<
|
||||
canInvoke,
|
||||
RT (Args...),
|
||||
typename FindPrototypeByCallableFromIndex<N + 1, HeterTuple<Others...>, Callable, ArgTransformer, M>::Prototype
|
||||
>::type;
|
||||
|
||||
using ArgsTuple = typename std::conditional<
|
||||
canInvoke,
|
||||
std::tuple<typename std::remove_cv<typename std::remove_reference<Args>::type>::type...>,
|
||||
typename FindPrototypeByCallableFromIndex<N + 1, HeterTuple<Others...>, Callable, ArgTransformer, M>::ArgsTuple
|
||||
>::type;
|
||||
|
||||
enum {
|
||||
index = canInvoke
|
||||
? N
|
||||
: FindPrototypeByCallableFromIndex<N + 1, HeterTuple<Others...>, Callable, ArgTransformer, M>::index
|
||||
};
|
||||
};
|
||||
|
||||
template <
|
||||
int N,
|
||||
typename PrototypeList_,
|
||||
typename Callable,
|
||||
template <typename> class ArgTransformer,
|
||||
int M
|
||||
>
|
||||
struct FindPrototypeByCallableFromIndex <
|
||||
N,
|
||||
PrototypeList_,
|
||||
Callable,
|
||||
ArgTransformer,
|
||||
M,
|
||||
typename std::enable_if<(N >= M)>::type
|
||||
>
|
||||
{
|
||||
using Prototype = void;
|
||||
|
||||
using ArgsTuple = std::tuple<>;
|
||||
|
||||
enum {
|
||||
index = -1
|
||||
};
|
||||
};
|
||||
|
||||
template <typename PrototypeList_, typename Callable, template <typename> class ArgTransformer = FindPrototypeDefaultArgTransformer>
|
||||
struct FindPrototypeByCallable : public FindPrototypeByCallableFromIndex <0, PrototypeList_, Callable, ArgTransformer>
|
||||
{
|
||||
};
|
||||
|
||||
template <int N, typename PrototypeList_, typename ...InArgs>
|
||||
struct FindPrototypeByArgsFromIndex;
|
||||
|
||||
template <int N, typename RT, typename ...Args, typename ...Others, typename ...InArgs>
|
||||
struct FindPrototypeByArgsFromIndex <N, HeterTuple<RT (Args...), Others...>, InArgs...>
|
||||
{
|
||||
enum { canInvoke = CanInvoke<RT (Args...), InArgs...>::value };
|
||||
|
||||
using Prototype = typename std::conditional<
|
||||
canInvoke,
|
||||
RT (Args...),
|
||||
typename FindPrototypeByArgsFromIndex<N + 1, HeterTuple<Others...>, InArgs...>::Prototype
|
||||
>::type;
|
||||
|
||||
using ArgsTuple = typename std::conditional<
|
||||
canInvoke,
|
||||
std::tuple<typename std::remove_cv<typename std::remove_reference<Args>::type>::type...>,
|
||||
typename FindPrototypeByArgsFromIndex<N + 1, HeterTuple<Others...>, InArgs...>::ArgsTuple
|
||||
>::type;
|
||||
|
||||
enum {
|
||||
index = canInvoke
|
||||
? N
|
||||
: FindPrototypeByArgsFromIndex<N + 1, HeterTuple<Others...>, InArgs...>::index
|
||||
};
|
||||
};
|
||||
|
||||
template <int N, typename ...InArgs>
|
||||
struct FindPrototypeByArgsFromIndex <N, HeterTuple<>, InArgs...>
|
||||
{
|
||||
using Prototype = void;
|
||||
|
||||
using ArgsTuple = std::tuple<>;
|
||||
|
||||
enum { index = -1 };
|
||||
};
|
||||
|
||||
template <typename PrototypeList_, typename ...InArgs>
|
||||
struct FindPrototypeByArgs : public FindPrototypeByArgsFromIndex <0, PrototypeList_, InArgs...>
|
||||
{
|
||||
};
|
||||
|
||||
template <int I, int N, typename PrototypeList_>
|
||||
struct FindPrototypeByIndexHelper;
|
||||
|
||||
template <int I, int N, typename RT, typename ...Args, typename ...Others>
|
||||
struct FindPrototypeByIndexHelper <I, N, HeterTuple<RT (Args...), Others...> >
|
||||
{
|
||||
using NextType = FindPrototypeByIndexHelper<I + 1, N, HeterTuple<Others...> >;
|
||||
using Prototype = typename NextType::Prototype;
|
||||
|
||||
using ArgsTuple = typename NextType::ArgsTuple;
|
||||
|
||||
enum { index = NextType::index };
|
||||
};
|
||||
|
||||
template <int N, typename RT, typename ...Args, typename ...Others>
|
||||
struct FindPrototypeByIndexHelper <N, N, HeterTuple<RT (Args...), Others...> >
|
||||
{
|
||||
using Prototype = RT (Args...);
|
||||
|
||||
using ArgsTuple = HeterTuple<typename std::remove_cv<typename std::remove_reference<Args>::type>::type...>;
|
||||
|
||||
enum { index = N };
|
||||
};
|
||||
|
||||
template <int I, int N>
|
||||
struct FindPrototypeByIndexHelper <I, N, HeterTuple<>>
|
||||
{
|
||||
using Prototype = void;
|
||||
|
||||
using ArgsTuple = HeterTuple<>;
|
||||
|
||||
enum { index = -1 };
|
||||
};
|
||||
|
||||
template <typename PrototypeList_, int N>
|
||||
struct FindPrototypeByIndex : public FindPrototypeByIndexHelper <0, N, PrototypeList_>
|
||||
{
|
||||
};
|
||||
|
||||
template <typename PrototypeList_, template <typename ...> class Record>
|
||||
struct GetCallablePrototypeMaxSize;
|
||||
|
||||
template <typename RT, typename ...Args, typename ...Others, template <typename ...> class Record>
|
||||
struct GetCallablePrototypeMaxSize <HeterTuple<RT (Args...), Others...>, Record>
|
||||
{
|
||||
enum {
|
||||
my = sizeof(Record<Args...>),
|
||||
other = GetCallablePrototypeMaxSize<HeterTuple<Others...>, Record>::value
|
||||
};
|
||||
enum { value = (my > other ? (int)my : (int)other) };
|
||||
};
|
||||
|
||||
template <template <typename ...> class Record>
|
||||
struct GetCallablePrototypeMaxSize <HeterTuple<>, Record>
|
||||
{
|
||||
enum { value = 1 }; // set minimum size to 1 instead of 0
|
||||
};
|
||||
|
||||
template <typename List, typename Item>
|
||||
struct PrependHeterTuple;
|
||||
|
||||
template <typename Item, typename ...Types>
|
||||
struct PrependHeterTuple <HeterTuple<Types...>, Item>
|
||||
{
|
||||
using Type = HeterTuple<Item, Types...>;
|
||||
};
|
||||
|
||||
template <typename List, typename Replacement>
|
||||
struct ReplaceReturnTypeList;
|
||||
|
||||
template <typename Replacement, typename RT, typename ...Args, typename ...Others>
|
||||
struct ReplaceReturnTypeList <HeterTuple<RT (Args...), Others...>, Replacement>
|
||||
{
|
||||
using Type = typename PrependHeterTuple<
|
||||
typename ReplaceReturnTypeList<HeterTuple<Others...>, Replacement>::Type,
|
||||
Replacement (Args...)
|
||||
>::Type;
|
||||
};
|
||||
|
||||
template <typename Replacement>
|
||||
struct ReplaceReturnTypeList <HeterTuple<>, Replacement>
|
||||
{
|
||||
using Type = HeterTuple<>;
|
||||
};
|
||||
|
||||
template <typename F, template <typename> class T>
|
||||
struct TransformArgumentsList;
|
||||
|
||||
template <template <typename> class T, typename RT, typename ...Args, typename ...Others>
|
||||
struct TransformArgumentsList <HeterTuple<RT (Args...), Others...>, T>
|
||||
{
|
||||
using Type = typename PrependHeterTuple<
|
||||
typename TransformArgumentsList<HeterTuple<Others...>, T>::Type,
|
||||
RT (typename T<Args>::type...)
|
||||
>::Type;
|
||||
};
|
||||
|
||||
template <template <typename> class T>
|
||||
struct TransformArgumentsList <HeterTuple<>, T>
|
||||
{
|
||||
using Type = HeterTuple<>;
|
||||
};
|
||||
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,127 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef TYPEUTIL_I_H
|
||||
#define TYPEUTIL_I_H
|
||||
|
||||
#include <utility>
|
||||
#include <tuple>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <typename F, template <typename> class T>
|
||||
struct TransformArguments;
|
||||
|
||||
template <template <typename> class T, typename RT, typename ...Args>
|
||||
struct TransformArguments <RT (Args...), T>
|
||||
{
|
||||
using Type = RT (typename T<Args>::type...);
|
||||
};
|
||||
|
||||
template <typename F, typename Replacement>
|
||||
struct ReplaceReturnType;
|
||||
|
||||
template <typename Replacement, typename RT, typename ...Args>
|
||||
struct ReplaceReturnType <RT (Args...), Replacement>
|
||||
{
|
||||
using Type = Replacement (Args...);
|
||||
};
|
||||
|
||||
template <int N, int M>
|
||||
struct IntToConstantHelper
|
||||
{
|
||||
template <typename C, typename ...Args>
|
||||
static auto find(const int index, C && c, Args && ...args)
|
||||
-> decltype(std::declval<C>().template operator()<0>(std::declval<Args>()...))
|
||||
{
|
||||
if(N == index) {
|
||||
return c.template operator()<N>(std::forward<Args>(args)...);
|
||||
}
|
||||
else {
|
||||
return IntToConstantHelper<N + 1, M>::find(index, std::forward<C>(c), std::forward<Args>(args)...);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
template <int M>
|
||||
struct IntToConstantHelper <M, M>
|
||||
{
|
||||
template <typename C, typename ...Args>
|
||||
static auto find(const int /*index*/, C && c, Args && ...args)
|
||||
-> decltype(std::declval<C>().template operator()<0>(std::declval<Args>()...))
|
||||
{
|
||||
return decltype(c.template operator()<0>(std::forward<Args>(args)...))();
|
||||
}
|
||||
};
|
||||
|
||||
template <int M, typename C, typename ...Args>
|
||||
auto intToConstant(const int index, C && c, Args && ...args)
|
||||
-> decltype(std::declval<C>().template operator()<0>(std::declval<Args>()...))
|
||||
{
|
||||
return IntToConstantHelper<0, M>::find(index, std::forward<C>(c), std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename F, typename ...Args>
|
||||
struct CanInvoke
|
||||
{
|
||||
template <typename U, typename ...X>
|
||||
static auto invoke(int) -> decltype(std::declval<U>()(std::declval<X>()...), std::true_type());
|
||||
|
||||
template <typename U, typename ...X>
|
||||
static auto invoke(...) -> std::false_type;
|
||||
|
||||
enum {
|
||||
value = !! decltype(invoke<F, Args...>(0))()
|
||||
};
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct ShiftTuple;
|
||||
|
||||
template <typename A, typename ...Args>
|
||||
struct ShiftTuple <std::tuple<A, Args...> >
|
||||
{
|
||||
using Type = std::tuple<Args...>;
|
||||
};
|
||||
|
||||
template <>
|
||||
struct ShiftTuple <std::tuple<> >
|
||||
{
|
||||
using Type = std::tuple<>;
|
||||
};
|
||||
|
||||
// for compile time debug
|
||||
template<typename T>
|
||||
void printTypeInCompileTime(T * = 0)
|
||||
{
|
||||
static_assert(std::is_same<T, int>::value && ! std::is_same<T, int>::value, "The error shows the type name.");
|
||||
}
|
||||
template<int N>
|
||||
void printIntInCompileTime()
|
||||
{
|
||||
int n = 0;
|
||||
switch(n) {
|
||||
case N:
|
||||
case N:
|
||||
break;
|
||||
};
|
||||
}
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef MIXINFILTER_H_713231680355
|
||||
#define MIXINFILTER_H_713231680355
|
||||
|
||||
#include "../callbacklist.h"
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
template <typename Base>
|
||||
class MixinFilter : public Base
|
||||
{
|
||||
private:
|
||||
using super = Base;
|
||||
|
||||
using BoolReferencePrototype = typename internal_::ReplaceReturnType<
|
||||
typename internal_::TransformArguments<
|
||||
typename super::Prototype,
|
||||
std::add_lvalue_reference
|
||||
>::Type,
|
||||
bool
|
||||
>::Type;
|
||||
|
||||
using Filter = std::function<BoolReferencePrototype>;
|
||||
using FilterList = CallbackList<BoolReferencePrototype>;
|
||||
|
||||
public:
|
||||
using FilterHandle = typename FilterList::Handle;
|
||||
|
||||
public:
|
||||
FilterHandle appendFilter(const Filter & filter)
|
||||
{
|
||||
return filterList.append(filter);
|
||||
}
|
||||
|
||||
bool removeFilter(const FilterHandle & filterHandle)
|
||||
{
|
||||
return filterList.remove(filterHandle);
|
||||
}
|
||||
|
||||
template <typename ...Args>
|
||||
bool mixinBeforeDispatch(Args && ...args) const {
|
||||
if(! filterList.empty()) {
|
||||
if(! filterList.forEachIf([&args...](typename FilterList::Callback & callback) {
|
||||
return callback(args...);
|
||||
})
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
FilterList filterList;
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef MIXINHETERFILTER_H_990158796753
|
||||
#define MIXINHETERFILTER_H_990158796753
|
||||
|
||||
#include "../hetercallbacklist.h"
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
template <typename Base>
|
||||
class MixinHeterFilter : public Base
|
||||
{
|
||||
private:
|
||||
using super = Base;
|
||||
|
||||
using BoolReferencePrototypeList = typename internal_::ReplaceReturnTypeList<
|
||||
typename internal_::TransformArgumentsList<
|
||||
typename super::PrototypeList,
|
||||
std::add_lvalue_reference
|
||||
>::Type,
|
||||
bool
|
||||
>::Type;
|
||||
|
||||
using FilterList = HeterCallbackList<BoolReferencePrototypeList>;
|
||||
|
||||
public:
|
||||
using FilterHandle = typename FilterList::Handle;
|
||||
|
||||
public:
|
||||
template <typename Callback>
|
||||
FilterHandle appendFilter(const Callback & filter)
|
||||
{
|
||||
return filterList.append(filter);
|
||||
}
|
||||
|
||||
bool removeFilter(const FilterHandle & filterHandle)
|
||||
{
|
||||
return filterList.remove(filterHandle);
|
||||
}
|
||||
|
||||
template <typename ...Args>
|
||||
bool mixinBeforeDispatch(Args && ...args) const {
|
||||
if(! filterList.template forEachIf<void (Args...)>([&args...](const typename std::function<bool (Args...)> & callback) -> bool {
|
||||
return callback(std::forward<Args>(args)...);
|
||||
})
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
FilterList filterList;
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef ANYDATA_H_320827729782
|
||||
#define ANYDATA_H_320827729782
|
||||
|
||||
#include <array>
|
||||
#include <type_traits>
|
||||
#include <cstdint>
|
||||
#include <cassert>
|
||||
#include <memory>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace anydata_internal_ {
|
||||
|
||||
template <typename T>
|
||||
void funcDeleteObject(void * object)
|
||||
{
|
||||
delete static_cast<T *>(object);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void funcFreeObject(void * object)
|
||||
{
|
||||
static_cast<T *>(object)->~T();
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
auto doFuncMoveConstruct(void * object, void * buffer)
|
||||
-> typename std::enable_if<std::is_move_constructible<T>::value>::type
|
||||
{
|
||||
new (buffer) T(std::move(*(T *)object));
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
auto doFuncMoveConstruct(void * object, void * buffer)
|
||||
-> typename std::enable_if<! std::is_move_constructible<T>::value>::type
|
||||
{
|
||||
static_assert(std::is_move_constructible<T>::value, "AnyData: object must be either copy or move constructible");
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void funcMoveConstruct(void * object, void * buffer)
|
||||
{
|
||||
doFuncMoveConstruct<T>(object, buffer);
|
||||
}
|
||||
|
||||
struct AnyDataFunctions
|
||||
{
|
||||
void (*free)(void *);
|
||||
void (*moveConstruct)(void *, void *);
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
const AnyDataFunctions * doGetAnyDataFunctions()
|
||||
{
|
||||
static const AnyDataFunctions functions {
|
||||
&funcFreeObject<T>,
|
||||
&funcMoveConstruct<T>
|
||||
};
|
||||
return &functions;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
struct RemoveCvRef
|
||||
{
|
||||
using Type = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
const AnyDataFunctions * getAnyDataFunctions()
|
||||
{
|
||||
using U = typename RemoveCvRef<T>::Type;
|
||||
return doGetAnyDataFunctions<U>();
|
||||
}
|
||||
|
||||
template <typename ...Ts>
|
||||
struct MaxSizeOf;
|
||||
|
||||
template <typename T, typename ...Ts>
|
||||
struct MaxSizeOf <T, Ts...>
|
||||
{
|
||||
static constexpr std::size_t otherSize = MaxSizeOf<Ts...>::value;
|
||||
static constexpr std::size_t tSize = sizeof(T);
|
||||
|
||||
static constexpr std::size_t value = tSize > otherSize ? tSize : otherSize;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct MaxSizeOf <T>
|
||||
{
|
||||
static constexpr std::size_t value = sizeof(T);
|
||||
};
|
||||
|
||||
class LargeData
|
||||
{
|
||||
public:
|
||||
template <typename T>
|
||||
explicit LargeData(T && object) : data(), deleter() {
|
||||
using U = typename RemoveCvRef<T>::Type;
|
||||
deleter = &funcDeleteObject<U>;
|
||||
data = new U(std::forward<T>(object));
|
||||
}
|
||||
|
||||
~LargeData() {
|
||||
if(data != nullptr) {
|
||||
assert(deleter != nullptr);
|
||||
deleter(data);
|
||||
}
|
||||
}
|
||||
|
||||
LargeData(LargeData && other) : data(), deleter() {
|
||||
std::swap(data, other.data);
|
||||
std::swap(deleter, other.deleter);
|
||||
}
|
||||
|
||||
LargeData(const LargeData & other) = delete;
|
||||
LargeData & operator = (const LargeData & other) = delete;
|
||||
LargeData & operator = (LargeData && other) = delete;
|
||||
|
||||
const void * getAddress() const {
|
||||
return data;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
bool isType() const {
|
||||
using U = typename RemoveCvRef<T>::Type;
|
||||
return deleter == &funcDeleteObject<U>;
|
||||
}
|
||||
|
||||
private:
|
||||
void * data;
|
||||
void (*deleter)(void *);
|
||||
};
|
||||
|
||||
} //namespace anydata_internal_
|
||||
|
||||
template <std::size_t maxSize_>
|
||||
class AnyData
|
||||
{
|
||||
private:
|
||||
using LargeData = anydata_internal_::LargeData;
|
||||
static constexpr std::size_t maxSize = maxSize_ < sizeof(LargeData) ? sizeof(LargeData) : maxSize_;
|
||||
|
||||
static_assert(maxSize > 0, "AnyData: maxSize must be greater than 0");
|
||||
|
||||
public:
|
||||
~AnyData() {
|
||||
if(functions != nullptr) {
|
||||
functions->free(buffer.data());
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
AnyData(T && object,
|
||||
typename std::enable_if<(sizeof(typename anydata_internal_::RemoveCvRef<T>::Type) <= maxSize)>::type * = 0)
|
||||
: functions(anydata_internal_::getAnyDataFunctions<T>()), buffer() {
|
||||
using U = typename std::remove_reference<T>::type;
|
||||
new (buffer.data()) U(std::forward<T>(object));
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
AnyData(T && object,
|
||||
typename std::enable_if<(sizeof(typename anydata_internal_::RemoveCvRef<T>::Type) > maxSize)>::type * = 0)
|
||||
: functions(anydata_internal_::getAnyDataFunctions<LargeData>()), buffer() {
|
||||
new (buffer.data()) LargeData(std::forward<T>(object));
|
||||
}
|
||||
|
||||
AnyData(AnyData && other) : functions(other.functions), buffer() {
|
||||
if(functions != nullptr) {
|
||||
functions->moveConstruct(other.buffer.data(), buffer.data());
|
||||
}
|
||||
}
|
||||
|
||||
AnyData(const AnyData & other) = delete;
|
||||
AnyData(AnyData & other) = delete;
|
||||
AnyData & operator = (const AnyData & other) = delete;
|
||||
AnyData & operator = (AnyData && other) = delete;
|
||||
|
||||
template <typename T>
|
||||
const T & get() const {
|
||||
return *(T *)getAddress();
|
||||
}
|
||||
|
||||
const void * getAddress() const {
|
||||
assert(functions != nullptr);
|
||||
|
||||
if(! isLargerData()) {
|
||||
return buffer.data();
|
||||
}
|
||||
else {
|
||||
return ((const LargeData *)buffer.data())->getAddress();
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
bool isType() const {
|
||||
if(! isLargerData()) {
|
||||
return anydata_internal_::getAnyDataFunctions<T>() == functions;
|
||||
}
|
||||
else {
|
||||
return ((const LargeData *)buffer.data())->isType<T>();
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
operator T & () const {
|
||||
return *(T *)getAddress();
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
operator T * () const {
|
||||
return (T *)getAddress();
|
||||
}
|
||||
|
||||
private:
|
||||
bool isLargerData() const {
|
||||
return functions == anydata_internal_::getAnyDataFunctions<LargeData>();
|
||||
}
|
||||
|
||||
private:
|
||||
const anydata_internal_::AnyDataFunctions * functions;
|
||||
std::array<std::uint8_t, maxSize> buffer;
|
||||
};
|
||||
|
||||
template <typename ...Ts>
|
||||
constexpr std::size_t maxSizeOf()
|
||||
{
|
||||
return anydata_internal_::MaxSizeOf<Ts...>::value;
|
||||
}
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef ANYID_H_320827729782
|
||||
#define ANYID_H_320827729782
|
||||
|
||||
#include <functional>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace anyid_internal_ {
|
||||
|
||||
template <typename T, typename Enabled = void>
|
||||
struct MakeHash;
|
||||
|
||||
template <typename T>
|
||||
struct MakeHash <T, typename std::enable_if<std::is_convertible<T, std::size_t>::value>::type>
|
||||
{
|
||||
std::size_t operator() (T value) const {
|
||||
return static_cast<std::size_t>(value);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct MakeHash <T, typename std::enable_if<! std::is_convertible<T, std::size_t>::value>::type>
|
||||
{
|
||||
std::size_t operator() (const T & value) const {
|
||||
return std::hash<T>()(value);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class HasLess
|
||||
{
|
||||
template <typename C> static std::true_type test(decltype(std::declval<C>() < std::declval<C>()) *);
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
public:
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
auto compareLessThan(const T & a, const T & b)
|
||||
-> typename std::enable_if<HasLess<T>::value, bool>::type
|
||||
{
|
||||
return a < b;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
auto compareLessThan(const T &, const T &)
|
||||
-> typename std::enable_if<! HasLess<T>::value, bool>::type
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
class HasEqual
|
||||
{
|
||||
template <typename C> static std::true_type test(decltype(std::declval<C>() == std::declval<C>()) *);
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
public:
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
auto compareEqual(const T & a, const T & b)
|
||||
-> typename std::enable_if<HasEqual<T>::value, bool>::type
|
||||
{
|
||||
return a == b;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
auto compareEqual(const T &, const T &)
|
||||
-> typename std::enable_if<! HasEqual<T>::value, bool>::type
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
} //namespace anyid_internal_
|
||||
|
||||
struct EmptyAnyStorage
|
||||
{
|
||||
EmptyAnyStorage() {}
|
||||
|
||||
template <typename T>
|
||||
EmptyAnyStorage(const T &) {}
|
||||
};
|
||||
|
||||
template <template <typename> class Digester = std::hash, typename Storage = EmptyAnyStorage>
|
||||
class AnyId
|
||||
{
|
||||
public:
|
||||
using DigestType = decltype(std::declval<Digester<int>>()(0));
|
||||
|
||||
public:
|
||||
AnyId() : digest(), value() {
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
AnyId(const T & value)
|
||||
: digest(Digester<T>()(value)), value(value)
|
||||
{
|
||||
}
|
||||
|
||||
DigestType getDigest() const {
|
||||
return digest;
|
||||
}
|
||||
|
||||
const Storage & getValue() const {
|
||||
return value;
|
||||
}
|
||||
|
||||
private:
|
||||
DigestType digest;
|
||||
Storage value;
|
||||
};
|
||||
|
||||
template <template <typename> class Digester, typename Storage>
|
||||
bool operator == (const AnyId<Digester, Storage> & a, const AnyId<Digester, Storage> & b)
|
||||
{
|
||||
return a.getDigest() == b.getDigest() && anyid_internal_::compareEqual(a.getValue(), b.getValue());
|
||||
}
|
||||
|
||||
template <template <typename> class Digester, typename Storage>
|
||||
bool operator < (const AnyId<Digester, Storage> & a, const AnyId<Digester, Storage> & b)
|
||||
{
|
||||
return (a.getDigest() < b.getDigest())
|
||||
|| (anyid_internal_::compareLessThan(a.getValue(), b.getValue()) && a.getDigest() == b.getDigest())
|
||||
;
|
||||
}
|
||||
|
||||
using AnyHashableId = AnyId<>;
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
namespace std
|
||||
{
|
||||
template <template <typename> class Digester, typename Storage>
|
||||
struct hash<eventpp::AnyId<Digester, Storage> >
|
||||
{
|
||||
std::size_t operator()(const eventpp::AnyId<Digester, Storage> & value) const noexcept
|
||||
{
|
||||
return eventpp::anyid_internal_::MakeHash<typename eventpp::AnyId<Digester, Storage>::DigestType>()(value.getDigest());
|
||||
}
|
||||
};
|
||||
} //namespace std
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef ARGUMENTADAPTER_H_566280692673
|
||||
#define ARGUMENTADAPTER_H_566280692673
|
||||
|
||||
#include <memory>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace adapter_internal_ {
|
||||
|
||||
template <typename T>
|
||||
struct StaticCast
|
||||
{
|
||||
template <typename U>
|
||||
static T cast(U && value)
|
||||
{
|
||||
return static_cast<T>(value);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct StaticCast<std::shared_ptr<T> >
|
||||
{
|
||||
template <typename U>
|
||||
static std::shared_ptr<T> cast(U && value)
|
||||
{
|
||||
return std::static_pointer_cast<T>(value);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct IsSharedPtr
|
||||
{
|
||||
enum { value = false };
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct IsSharedPtr<std::shared_ptr<T> >
|
||||
{
|
||||
enum { value = true };
|
||||
};
|
||||
|
||||
template <typename ...Args>
|
||||
struct IsAnySharedPtr
|
||||
{
|
||||
enum { value = false };
|
||||
};
|
||||
|
||||
template <typename First, typename ...Others>
|
||||
struct IsAnySharedPtr <First, Others...>
|
||||
{
|
||||
enum { value = IsSharedPtr<First>::value
|
||||
|| IsAnySharedPtr<Others...>::value };
|
||||
};
|
||||
|
||||
} //namespace adapter_internal_
|
||||
|
||||
template <typename Func, typename Prototype, typename IsSharedPtr = void>
|
||||
struct ArgumentAdapter;
|
||||
|
||||
template <typename Func, typename R, typename ...Args>
|
||||
struct ArgumentAdapter <
|
||||
Func,
|
||||
R(Args...),
|
||||
typename std::enable_if<! adapter_internal_::IsAnySharedPtr<Args...>::value>::type
|
||||
>
|
||||
{
|
||||
explicit ArgumentAdapter(Func f)
|
||||
: func(std::move(f))
|
||||
{
|
||||
}
|
||||
|
||||
template <typename ...A>
|
||||
void operator() (A &&...args) {
|
||||
func(std::forward<Args>(static_cast<Args>(args))...);
|
||||
}
|
||||
|
||||
Func func;
|
||||
};
|
||||
|
||||
template <typename Func, typename R, typename ...Args>
|
||||
struct ArgumentAdapter <
|
||||
Func,
|
||||
R(Args...),
|
||||
typename std::enable_if<adapter_internal_::IsAnySharedPtr<Args...>::value>::type
|
||||
>
|
||||
{
|
||||
explicit ArgumentAdapter(Func f)
|
||||
: func(std::move(f))
|
||||
{
|
||||
}
|
||||
|
||||
template <typename ...A>
|
||||
void operator() (A &&...args) {
|
||||
func(std::forward<Args>(adapter_internal_::StaticCast<Args>::cast(args))...);
|
||||
}
|
||||
|
||||
Func func;
|
||||
};
|
||||
|
||||
template <template <typename> class Func, typename R, typename ...Args>
|
||||
ArgumentAdapter<Func<R(Args...)>, R(Args...)> argumentAdapter(Func<R(Args...)> func)
|
||||
{
|
||||
return ArgumentAdapter<Func<R(Args...)>, R(Args...)>(std::move(func));
|
||||
}
|
||||
|
||||
template <typename Prototype, typename Func>
|
||||
ArgumentAdapter<Func, Prototype> argumentAdapter(Func func)
|
||||
{
|
||||
return ArgumentAdapter<Func, Prototype>(std::move(func));
|
||||
}
|
||||
|
||||
template <typename R, typename ...Args>
|
||||
ArgumentAdapter<R(*)(Args...), R(Args...)> argumentAdapter(R(*func)(Args...))
|
||||
{
|
||||
return ArgumentAdapter<R(*)(Args...), R(Args...)>(std::move(func));
|
||||
}
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef CONDITIONALFUNCTOR_H_828958739581
|
||||
#define CONDITIONALFUNCTOR_H_828958739581
|
||||
|
||||
#include <utility>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
template <typename Func, typename Condition>
|
||||
struct ConditionalFunctor
|
||||
{
|
||||
ConditionalFunctor(Func f, Condition condition)
|
||||
: func(std::move(f)), condition(std::move(condition))
|
||||
{
|
||||
}
|
||||
|
||||
template <typename ...A>
|
||||
void operator() (A &&...args) {
|
||||
if(condition(args...)) {
|
||||
func(std::forward<A>(args)...);
|
||||
}
|
||||
}
|
||||
|
||||
Func func;
|
||||
Condition condition;
|
||||
};
|
||||
|
||||
template <typename Func, typename Condition>
|
||||
ConditionalFunctor<Func, Condition> conditionalFunctor(Func func, Condition condition)
|
||||
{
|
||||
return ConditionalFunctor<Func, Condition>(std::move(func), std::move(condition));
|
||||
}
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef CONDITIONALREMOVER_H_882115092280
|
||||
#define CONDITIONALREMOVER_H_882115092280
|
||||
|
||||
#include "../eventpolicies.h"
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
template <typename DispatcherType, typename Enabled = void>
|
||||
class ConditionalRemover;
|
||||
|
||||
template <typename DispatcherType>
|
||||
class ConditionalRemover <
|
||||
DispatcherType,
|
||||
typename std::enable_if<std::is_base_of<TagEventDispatcher, DispatcherType>::value>::type
|
||||
>
|
||||
{
|
||||
private:
|
||||
template <typename Callback, typename Condition>
|
||||
struct ItemByCondition
|
||||
{
|
||||
struct Data
|
||||
{
|
||||
Condition shouldRemove;
|
||||
DispatcherType & dispatcher;
|
||||
typename DispatcherType::Event event;
|
||||
Callback listener;
|
||||
typename DispatcherType::Handle handle;
|
||||
};
|
||||
|
||||
template <typename ...Args>
|
||||
auto operator() (Args && ...args) const
|
||||
-> typename std::enable_if<internal_::CanInvoke<Condition, Args...>::value>::type {
|
||||
if(data->shouldRemove(args...)) {
|
||||
data->dispatcher.removeListener(data->event, data->handle);
|
||||
}
|
||||
data->listener(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename ...Args>
|
||||
auto operator() (Args && ...args) const
|
||||
-> typename std::enable_if<! internal_::CanInvoke<Condition, Args...>::value>::type {
|
||||
if(data->shouldRemove()) {
|
||||
data->dispatcher.removeListener(data->event, data->handle);
|
||||
}
|
||||
data->listener(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
std::shared_ptr<Data> data;
|
||||
};
|
||||
|
||||
public:
|
||||
explicit ConditionalRemover(DispatcherType & dispatcher)
|
||||
: dispatcher(dispatcher)
|
||||
{
|
||||
}
|
||||
|
||||
template <typename Callback, typename Condition>
|
||||
typename DispatcherType::Handle appendListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener,
|
||||
const Condition & condition
|
||||
)
|
||||
{
|
||||
using Wrapper = ItemByCondition<Callback, Condition>;
|
||||
auto data = std::make_shared<typename Wrapper::Data>(typename Wrapper::Data {
|
||||
condition, dispatcher, event, listener, typename DispatcherType::Handle()
|
||||
});
|
||||
data->handle = dispatcher.appendListener(event, Wrapper{data});
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
template <typename Callback, typename Condition>
|
||||
typename DispatcherType::Handle prependListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener,
|
||||
const Condition & condition
|
||||
)
|
||||
{
|
||||
using Wrapper = ItemByCondition<Callback, Condition>;
|
||||
auto data = std::make_shared<typename Wrapper::Data>(typename Wrapper::Data {
|
||||
condition, dispatcher, event, listener, typename DispatcherType::Handle()
|
||||
});
|
||||
data->handle = dispatcher.prependListener(event, Wrapper{data});
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
template <typename Callback, typename Condition>
|
||||
typename DispatcherType::Handle insertListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener,
|
||||
const typename DispatcherType::Handle & before,
|
||||
const Condition & condition
|
||||
)
|
||||
{
|
||||
using Wrapper = ItemByCondition<Callback, Condition>;
|
||||
auto data = std::make_shared<typename Wrapper::Data>(typename Wrapper::Data {
|
||||
condition, dispatcher, event, listener, typename DispatcherType::Handle()
|
||||
});
|
||||
data->handle = dispatcher.insertListener(event, Wrapper{data}, before);
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
private:
|
||||
DispatcherType & dispatcher;
|
||||
};
|
||||
|
||||
template <typename CallbackListType>
|
||||
class ConditionalRemover <
|
||||
CallbackListType,
|
||||
typename std::enable_if<std::is_base_of<TagCallbackList, CallbackListType>::value>::type
|
||||
>
|
||||
{
|
||||
private:
|
||||
template <typename Callback, typename Condition>
|
||||
struct ItemByCondition
|
||||
{
|
||||
struct Data
|
||||
{
|
||||
Condition shouldRemove;
|
||||
CallbackListType & callbackList;
|
||||
Callback listener;
|
||||
typename CallbackListType::Handle handle;
|
||||
};
|
||||
|
||||
template <typename ...Args>
|
||||
auto operator() (Args && ...args) const
|
||||
-> typename std::enable_if<internal_::CanInvoke<Condition, Args...>::value>::type const {
|
||||
if(data->shouldRemove(args...)) {
|
||||
data->callbackList.remove(data->handle);
|
||||
}
|
||||
data->listener(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename ...Args>
|
||||
auto operator() (Args && ...args) const
|
||||
-> typename std::enable_if<! internal_::CanInvoke<Condition, Args...>::value>::type {
|
||||
if(data->shouldRemove()) {
|
||||
data->callbackList.remove(data->handle);
|
||||
}
|
||||
data->listener(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
std::shared_ptr<Data> data;
|
||||
};
|
||||
|
||||
public:
|
||||
explicit ConditionalRemover(CallbackListType & callbackList)
|
||||
: callbackList(callbackList)
|
||||
{
|
||||
}
|
||||
|
||||
template <typename Callback, typename Condition>
|
||||
typename CallbackListType::Handle append(
|
||||
const Callback & listener,
|
||||
const Condition & condition
|
||||
)
|
||||
{
|
||||
using Wrapper = ItemByCondition<Callback, Condition>;
|
||||
auto data = std::make_shared<typename Wrapper::Data>(typename Wrapper::Data {
|
||||
condition, callbackList, listener, typename CallbackListType::Handle()
|
||||
});
|
||||
data->handle = callbackList.append(Wrapper{data});
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
template <typename Callback, typename Condition>
|
||||
typename CallbackListType::Handle prepend(
|
||||
const Callback & listener,
|
||||
const Condition & condition
|
||||
)
|
||||
{
|
||||
using Wrapper = ItemByCondition<Callback, Condition>;
|
||||
auto data = std::make_shared<typename Wrapper::Data>(typename Wrapper::Data {
|
||||
condition, callbackList, listener, typename CallbackListType::Handle()
|
||||
});
|
||||
data->handle = callbackList.prepend(Wrapper{data});
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
template <typename Callback, typename Condition>
|
||||
typename CallbackListType::Handle insert(
|
||||
const Callback & listener,
|
||||
const typename CallbackListType::Handle & before,
|
||||
const Condition & condition
|
||||
)
|
||||
{
|
||||
using Wrapper = ItemByCondition<Callback, Condition>;
|
||||
auto data = std::make_shared<typename Wrapper::Data>(typename Wrapper::Data {
|
||||
condition, callbackList, listener, typename CallbackListType::Handle()
|
||||
});
|
||||
data->handle = callbackList.insert(Wrapper{data}, before);
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
private:
|
||||
CallbackListType & callbackList;
|
||||
};
|
||||
|
||||
template <typename DispatcherType>
|
||||
ConditionalRemover<DispatcherType> conditionalRemover(DispatcherType & dispatcher)
|
||||
{
|
||||
return ConditionalRemover<DispatcherType>(dispatcher);
|
||||
}
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef COUNTERREMOVER_H_211532679833
|
||||
#define COUNTERREMOVER_H_211532679833
|
||||
|
||||
#include "../eventpolicies.h"
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
template <typename DispatcherType, typename Enabled = void>
|
||||
class CounterRemover;
|
||||
|
||||
template <typename DispatcherType>
|
||||
class CounterRemover <
|
||||
DispatcherType,
|
||||
typename std::enable_if<std::is_base_of<TagEventDispatcher, DispatcherType>::value>::type
|
||||
>
|
||||
{
|
||||
private:
|
||||
template <typename Callback>
|
||||
struct Wrapper
|
||||
{
|
||||
struct Data
|
||||
{
|
||||
int triggerCount;
|
||||
DispatcherType & dispatcher;
|
||||
typename DispatcherType::Event event;
|
||||
Callback listener;
|
||||
typename DispatcherType::Handle handle;
|
||||
};
|
||||
|
||||
template <typename ...Args>
|
||||
void operator() (Args && ...args) const {
|
||||
if(--data->triggerCount <= 0) {
|
||||
data->dispatcher.removeListener(data->event, data->handle);
|
||||
}
|
||||
data->listener(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
std::shared_ptr<Data> data;
|
||||
};
|
||||
|
||||
public:
|
||||
explicit CounterRemover(DispatcherType & dispatcher)
|
||||
: dispatcher(dispatcher)
|
||||
{
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename DispatcherType::Handle appendListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener,
|
||||
const int triggerCount = 1
|
||||
)
|
||||
{
|
||||
auto data = std::make_shared<typename Wrapper<Callback>::Data>(typename Wrapper<Callback>::Data {
|
||||
triggerCount, dispatcher, event, listener, typename DispatcherType::Handle()
|
||||
});
|
||||
data->handle = dispatcher.appendListener(event, Wrapper<Callback>{data});
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename DispatcherType::Handle prependListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener,
|
||||
const int triggerCount = 1
|
||||
)
|
||||
{
|
||||
auto data = std::make_shared<typename Wrapper<Callback>::Data>(typename Wrapper<Callback>::Data {
|
||||
triggerCount, dispatcher, event, listener, typename DispatcherType::Handle()
|
||||
});
|
||||
data->handle = dispatcher.prependListener(event, Wrapper<Callback>{data});
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename DispatcherType::Handle insertListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener,
|
||||
const typename DispatcherType::Handle & before,
|
||||
const int triggerCount = 1
|
||||
)
|
||||
{
|
||||
auto data = std::make_shared<typename Wrapper<Callback>::Data>(typename Wrapper<Callback>::Data {
|
||||
triggerCount, dispatcher, event, listener, typename DispatcherType::Handle()
|
||||
});
|
||||
data->handle = dispatcher.insertListener(event, Wrapper<Callback>{data}, before);
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
private:
|
||||
DispatcherType & dispatcher;
|
||||
};
|
||||
|
||||
template <typename CallbackListType>
|
||||
class CounterRemover <
|
||||
CallbackListType,
|
||||
typename std::enable_if<std::is_base_of<TagCallbackList, CallbackListType>::value>::type
|
||||
>
|
||||
{
|
||||
private:
|
||||
template <typename Callback>
|
||||
struct Wrapper
|
||||
{
|
||||
struct Data
|
||||
{
|
||||
int triggerCount;
|
||||
CallbackListType & callbackList;
|
||||
Callback listener;
|
||||
typename CallbackListType::Handle handle;
|
||||
};
|
||||
|
||||
template <typename ...Args>
|
||||
void operator() (Args && ...args) const {
|
||||
if(--data->triggerCount <= 0) {
|
||||
data->callbackList.remove(data->handle);
|
||||
}
|
||||
data->listener(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
std::shared_ptr<Data> data;
|
||||
};
|
||||
|
||||
public:
|
||||
explicit CounterRemover(CallbackListType & callbackList)
|
||||
: callbackList(callbackList)
|
||||
{
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename CallbackListType::Handle append(
|
||||
const Callback & listener,
|
||||
const int triggerCount = 1
|
||||
)
|
||||
{
|
||||
auto data = std::make_shared<typename Wrapper<Callback>::Data>(typename Wrapper<Callback>::Data {
|
||||
triggerCount, callbackList, listener, typename CallbackListType::Handle()
|
||||
});
|
||||
data->handle = callbackList.append(Wrapper<Callback>{data});
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename CallbackListType::Handle prepend(
|
||||
const Callback & listener,
|
||||
const int triggerCount = 1
|
||||
)
|
||||
{
|
||||
auto data = std::make_shared<typename Wrapper<Callback>::Data>(typename Wrapper<Callback>::Data {
|
||||
triggerCount, callbackList, listener, typename CallbackListType::Handle()
|
||||
});
|
||||
data->handle = callbackList.prepend(Wrapper<Callback>{data});
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename CallbackListType::Handle insert(
|
||||
const Callback & listener,
|
||||
const typename CallbackListType::Handle & before,
|
||||
const int triggerCount = 1
|
||||
)
|
||||
{
|
||||
auto data = std::make_shared<typename Wrapper<Callback>::Data>(typename Wrapper<Callback>::Data {
|
||||
triggerCount, callbackList, listener, typename CallbackListType::Handle()
|
||||
});
|
||||
data->handle = callbackList.insert(Wrapper<Callback>{data}, before);
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
private:
|
||||
CallbackListType & callbackList;
|
||||
};
|
||||
|
||||
template <typename DispatcherType>
|
||||
CounterRemover<DispatcherType> counterRemover(DispatcherType & dispatcher)
|
||||
{
|
||||
return CounterRemover<DispatcherType>(dispatcher);
|
||||
}
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef EVENTMAKER_H_378278023815
|
||||
#define EVENTMAKER_H_378278023815
|
||||
|
||||
// auto generated macros begin
|
||||
|
||||
#define I_EVENTPP_ARG_COUNT(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, ...) p15
|
||||
#define EVENTPP_ARG_COUNT(...) EVENTPP_EXPAND(I_EVENTPP_ARG_COUNT(__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0))
|
||||
|
||||
#define I_EVENTPP_ITERATE_ARGS_0(EXEC, DELI)
|
||||
#define I_EVENTPP_ITERATE_ARGS_1(EXEC, DELI, p0) I_EVENTPP_ITERATE_ARGS_0(EXEC, DELI ) EXEC(p0)
|
||||
#define I_EVENTPP_ITERATE_ARGS_2(EXEC, DELI, p0, p1) I_EVENTPP_ITERATE_ARGS_1(EXEC, DELI, p0) DELI() EXEC(p1)
|
||||
#define I_EVENTPP_ITERATE_ARGS_3(EXEC, DELI, p0, p1, p2) I_EVENTPP_ITERATE_ARGS_2(EXEC, DELI, p0, p1) DELI() EXEC(p2)
|
||||
#define I_EVENTPP_ITERATE_ARGS_4(EXEC, DELI, p0, p1, p2, p3) I_EVENTPP_ITERATE_ARGS_3(EXEC, DELI, p0, p1, p2) DELI() EXEC(p3)
|
||||
#define I_EVENTPP_ITERATE_ARGS_5(EXEC, DELI, p0, p1, p2, p3, p4) I_EVENTPP_ITERATE_ARGS_4(EXEC, DELI, p0, p1, p2, p3) DELI() EXEC(p4)
|
||||
#define I_EVENTPP_ITERATE_ARGS_6(EXEC, DELI, p0, p1, p2, p3, p4, p5) I_EVENTPP_ITERATE_ARGS_5(EXEC, DELI, p0, p1, p2, p3, p4) DELI() EXEC(p5)
|
||||
#define I_EVENTPP_ITERATE_ARGS_7(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6) I_EVENTPP_ITERATE_ARGS_6(EXEC, DELI, p0, p1, p2, p3, p4, p5) DELI() EXEC(p6)
|
||||
#define I_EVENTPP_ITERATE_ARGS_8(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7) I_EVENTPP_ITERATE_ARGS_7(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6) DELI() EXEC(p7)
|
||||
#define I_EVENTPP_ITERATE_ARGS_9(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8) I_EVENTPP_ITERATE_ARGS_8(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7) DELI() EXEC(p8)
|
||||
#define I_EVENTPP_ITERATE_ARGS_10(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9) I_EVENTPP_ITERATE_ARGS_9(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8) DELI() EXEC(p9)
|
||||
#define I_EVENTPP_ITERATE_ARGS_11(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10) I_EVENTPP_ITERATE_ARGS_10(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9) DELI() EXEC(p10)
|
||||
#define I_EVENTPP_ITERATE_ARGS_12(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11) I_EVENTPP_ITERATE_ARGS_11(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10) DELI() EXEC(p11)
|
||||
#define I_EVENTPP_ITERATE_ARGS_13(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12) I_EVENTPP_ITERATE_ARGS_12(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11) DELI() EXEC(p12)
|
||||
#define I_EVENTPP_ITERATE_ARGS_14(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13) I_EVENTPP_ITERATE_ARGS_13(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12) DELI() EXEC(p13)
|
||||
#define I_EVENTPP_ITERATE_ARGS_15(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14) I_EVENTPP_ITERATE_ARGS_14(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13) DELI() EXEC(p14)
|
||||
#define I_EVENTPP_ITERATE_ARGS_N(EXEC, DELI, N, ...) EVENTPP_EXPAND(EVENTPP_CONCAT(I_EVENTPP_ITERATE_ARGS_, N) (EXEC, DELI, __VA_ARGS__))
|
||||
#define EVENTPP_ITERATE_ARGS(EXEC, DELI, ...) I_EVENTPP_ITERATE_ARGS_N(EXEC, DELI, EVENTPP_ARG_COUNT(__VA_ARGS__), __VA_ARGS__)
|
||||
|
||||
// auto generated macros end
|
||||
|
||||
#define I_EVENTPP_STRINGIFY(x) #x
|
||||
#define EVENTPP_STRINGIFY(x) I_EVENTPP_STRINGIFY(x)
|
||||
|
||||
#define I_EVENTPP_CONCAT(a, b) a ## b
|
||||
#define EVENTPP_CONCAT(a, b) I_EVENTPP_CONCAT(a, b)
|
||||
|
||||
// EVENTPP_EXPAND is used to expand __VA_ARGS__ correctly in VC++
|
||||
#define EVENTPP_EXPAND(...) __VA_ARGS__
|
||||
#define EVENTPP_BRACKETS_EXPAND(...) EVENTPP_EXPAND(EVENTPP_EXPAND __VA_ARGS__)
|
||||
|
||||
#define EVENTPP_EMPTY()
|
||||
#define EVENTPP_COMMA() ,
|
||||
#define EVENTPP_SEMICOLON() ;
|
||||
|
||||
#define I_EVENTPP_GET0_2(p0, ...) p0
|
||||
#define I_EVENTPP_GET0(...) EVENTPP_EXPAND(I_EVENTPP_GET0_2(__VA_ARGS__, ))
|
||||
#define EVENTPP_GET0(p0) EVENTPP_EXPAND(I_EVENTPP_GET0 p0)
|
||||
|
||||
#define I_EVENTPP_GET1_2(p0, p1, ...) p1
|
||||
#define I_EVENTPP_GET1(...) EVENTPP_EXPAND(I_EVENTPP_GET1_2(__VA_ARGS__, ))
|
||||
#define EVENTPP_GET1(p0) EVENTPP_EXPAND(I_EVENTPP_GET1 p0)
|
||||
|
||||
#define I_EVENTPP_GET2_2(p0, p1, p2, ...) p2
|
||||
#define I_EVENTPP_GET2(...) EVENTPP_EXPAND(I_EVENTPP_GET2_2(__VA_ARGS__, ))
|
||||
#define EVENTPP_GET2(p0) EVENTPP_EXPAND(I_EVENTPP_GET2 p0)
|
||||
|
||||
#define EVENTPP_MAKE_FIELD_NAME(p0) EVENTPP_CONCAT(v, EVENTPP_GET1(p0))
|
||||
#define EVENTPP_EXEC_MAKE_FIELD(p0) EVENTPP_GET0(p0) EVENTPP_MAKE_FIELD_NAME(p0)
|
||||
#define EVENTPP_EXEC_MAKE_GETTER(p0) const EVENTPP_GET0(p0) & EVENTPP_GET1(p0) () const { return EVENTPP_MAKE_FIELD_NAME(p0); }
|
||||
|
||||
#define I_EVENTPP_EXEC_MAKE_SETTER_0(p0)
|
||||
#define I_EVENTPP_EXEC_MAKE_SETTER_1(p0)
|
||||
#define I_EVENTPP_EXEC_MAKE_SETTER_2(p0)
|
||||
#define I_EVENTPP_EXEC_MAKE_SETTER_3(p0) void EVENTPP_GET2(p0) (const EVENTPP_GET0(p0) & value) { EVENTPP_MAKE_FIELD_NAME(p0) = value; }
|
||||
#define I_EVENTPP_EXEC_MAKE_SETTER_4(p0) I_EVENTPP_MAKE_SETTER_HELPER_3(p0)
|
||||
#define I_EVENTPP_EXEC_MAKE_SETTER_5(p0) I_EVENTPP_MAKE_SETTER_HELPER_3(p0)
|
||||
#define I_EVENTPP_EXEC_MAKE_SETTER_6(p0) I_EVENTPP_MAKE_SETTER_HELPER_3(p0)
|
||||
#define I_EVENTPP_EXEC_MAKE_SETTER_N(N, p0) EVENTPP_EXPAND(EVENTPP_CONCAT(I_EVENTPP_EXEC_MAKE_SETTER_, N) (p0))
|
||||
#define EVENTPP_EXEC_MAKE_SETTER(p0) EVENTPP_EXPAND(I_EVENTPP_EXEC_MAKE_SETTER_N(EVENTPP_ARG_COUNT EVENTPP_EXPAND(p0), p0))
|
||||
|
||||
#define EVENTPP_EXEC_MAKE_INITIALIZE(p0) EVENTPP_MAKE_FIELD_NAME(p0)(EVENTPP_MAKE_FIELD_NAME(p0))
|
||||
#define EVENTPP_EXEC_MAKE_DEFAULT_INITIALIZE(p0) EVENTPP_MAKE_FIELD_NAME(p0)()
|
||||
#define EVENTPP_EXEC_MAKE_CTOR_FIELD(p0) const EVENTPP_GET0(p0) & EVENTPP_MAKE_FIELD_NAME(p0)
|
||||
|
||||
#define I_EVENTPP_CHECK(x, n, ...) n
|
||||
#define EVENTPP_CHECK(...) EVENTPP_EXPAND(I_EVENTPP_CHECK(__VA_ARGS__, 0, ))
|
||||
|
||||
#define I_EVENTPP_IS_ENCLOSED_BY_BRACKETS(...) x, 1
|
||||
#define EVENTPP_IS_ENCLOSED_BY_BRACKETS(x) EVENTPP_CHECK(I_EVENTPP_IS_ENCLOSED_BY_BRACKETS x)
|
||||
|
||||
#define I_EVENTPP_IF_1(t, f) t
|
||||
#define I_EVENTPP_IF_0(t, f) f
|
||||
#define EVENTPP_IF(b, t, f) EVENTPP_CONCAT(I_EVENTPP_IF_, b)(t, f)
|
||||
|
||||
#define EVENTPP_ADD_BACKETS(x) EVENTPP_IF(EVENTPP_IS_ENCLOSED_BY_BRACKETS(x), x, (x))
|
||||
#define EVENTPP_REMOVE_BACKETS(x) EVENTPP_BRACKETS_EXPAND(EVENTPP_IF(EVENTPP_IS_ENCLOSED_BY_BRACKETS(x), (EVENTPP_EXPAND x), (x)))
|
||||
|
||||
#define I_EVENTPP_MAKE_EVENT(className, baseClassName, baseClassArgs, ...) \
|
||||
class className : public EVENTPP_REMOVE_BACKETS(baseClassName) { \
|
||||
public: \
|
||||
className() \
|
||||
: EVENTPP_REMOVE_BACKETS(baseClassName) EVENTPP_ADD_BACKETS(baseClassArgs), \
|
||||
EVENTPP_ITERATE_ARGS(EVENTPP_EXEC_MAKE_DEFAULT_INITIALIZE, EVENTPP_COMMA, __VA_ARGS__) {} \
|
||||
className(EVENTPP_ITERATE_ARGS(EVENTPP_EXEC_MAKE_CTOR_FIELD, EVENTPP_COMMA, __VA_ARGS__)) \
|
||||
: EVENTPP_REMOVE_BACKETS(baseClassName) EVENTPP_ADD_BACKETS(baseClassArgs), \
|
||||
EVENTPP_ITERATE_ARGS(EVENTPP_EXEC_MAKE_INITIALIZE, EVENTPP_COMMA, __VA_ARGS__) {} \
|
||||
EVENTPP_ITERATE_ARGS(EVENTPP_EXEC_MAKE_GETTER, EVENTPP_EMPTY, __VA_ARGS__) \
|
||||
EVENTPP_ITERATE_ARGS(EVENTPP_EXEC_MAKE_SETTER, EVENTPP_EMPTY, __VA_ARGS__) \
|
||||
private: \
|
||||
EVENTPP_ITERATE_ARGS(EVENTPP_EXEC_MAKE_FIELD, EVENTPP_SEMICOLON, __VA_ARGS__); \
|
||||
}
|
||||
|
||||
#define EVENTPP_MAKE_EVENT(className, baseClassName, baseClassArgs, ...) EVENTPP_EXPAND(I_EVENTPP_MAKE_EVENT(className, baseClassName, baseClassArgs, __VA_ARGS__))
|
||||
|
||||
#define EVENTPP_MAKE_EMPTY_EVENT(className, baseClassName, baseClassArgs) \
|
||||
class className : public EVENTPP_REMOVE_BACKETS(baseClassName) { \
|
||||
public: \
|
||||
className() \
|
||||
: EVENTPP_REMOVE_BACKETS(baseClassName) EVENTPP_ADD_BACKETS(baseClassArgs) {} \
|
||||
}
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
/*
|
||||
Perl script to generate some of the macros
|
||||
|
||||
use strict;
|
||||
use warnings;
|
||||
|
||||
my $paramCount = 15;
|
||||
|
||||
sub outputParams
|
||||
{
|
||||
my ($count) = @_;
|
||||
|
||||
for(my $i = 0; $i < $count; ++$i) {
|
||||
print ', ' if($i > 0);
|
||||
print 'p', $i;
|
||||
}
|
||||
}
|
||||
|
||||
sub doMain
|
||||
{
|
||||
print '#define I_EVENTPP_ARG_COUNT(';
|
||||
&outputParams($paramCount + 1);
|
||||
print ', ...) p', $paramCount, "\n";
|
||||
print '#define EVENTPP_ARG_COUNT(...) EVENTPP_EXPAND(I_EVENTPP_ARG_COUNT(__VA_ARGS__';
|
||||
for(my $i = $paramCount; $i >= 0; --$i) {
|
||||
print ', ', $i;
|
||||
}
|
||||
print "))\n";
|
||||
print "\n";
|
||||
|
||||
print "#define I_EVENTPP_ITERATE_ARGS_0(EXEC, DELI)\n";
|
||||
for(my $i = 1; $i <= $paramCount; ++$i) {
|
||||
print '#define I_EVENTPP_ITERATE_ARGS_', $i, '(EXEC, DELI, ';
|
||||
&outputParams($i);
|
||||
print ') I_EVENTPP_ITERATE_ARGS_', ($i - 1), '(EXEC, DELI';
|
||||
print ($i > 1 ? ', ' : ' ');
|
||||
&outputParams($i - 1);
|
||||
print ')', ($i > 1 ? ' DELI()' : ''), ' EXEC(p', ($i - 1), ')';
|
||||
print "\n";
|
||||
}
|
||||
print "#define I_EVENTPP_ITERATE_ARGS_N(EXEC, DELI, N, ...) EVENTPP_EXPAND(EVENTPP_CONCAT(I_EVENTPP_ITERATE_ARGS_, N) (EXEC, DELI, __VA_ARGS__))\n";
|
||||
print "#define EVENTPP_ITERATE_ARGS(EXEC, DELI, ...) I_EVENTPP_ITERATE_ARGS_N(EXEC, DELI, EVENTPP_ARG_COUNT(__VA_ARGS__), __VA_ARGS__)\n";
|
||||
print "\n";
|
||||
|
||||
}
|
||||
|
||||
&doMain;
|
||||
|
||||
|
||||
*/
|
||||
@@ -0,0 +1,169 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef EVENTUTIL_H_802615012766
|
||||
#define EVENTUTIL_H_802615012766
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
template <typename DispatcherType>
|
||||
bool removeListener(
|
||||
DispatcherType & dispatcher,
|
||||
const typename DispatcherType::Event & event,
|
||||
const typename DispatcherType::Callback & listener
|
||||
)
|
||||
{
|
||||
bool found = false;
|
||||
dispatcher.forEachIf(
|
||||
event,
|
||||
[&found, &dispatcher, &event, &listener](
|
||||
const typename DispatcherType::Handle & handle,
|
||||
const typename DispatcherType::Callback & item
|
||||
) -> bool {
|
||||
if(item == listener) {
|
||||
found = true;
|
||||
dispatcher.removeListener(event, handle);
|
||||
return false;
|
||||
}
|
||||
else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
template <typename CallbackListType>
|
||||
bool removeListener(
|
||||
CallbackListType & callbackList,
|
||||
const typename CallbackListType::Callback & callback
|
||||
)
|
||||
{
|
||||
bool found = false;
|
||||
callbackList.forEachIf(
|
||||
[&found, &callbackList, &callback](
|
||||
const typename CallbackListType::Handle & handle,
|
||||
const typename CallbackListType::Callback & item
|
||||
) -> bool {
|
||||
if(item == callback) {
|
||||
found = true;
|
||||
callbackList.remove(handle);
|
||||
return false;
|
||||
}
|
||||
else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
template <typename DispatcherType>
|
||||
bool hasListener(
|
||||
DispatcherType & dispatcher,
|
||||
const typename DispatcherType::Event & event,
|
||||
const typename DispatcherType::Callback & listener
|
||||
)
|
||||
{
|
||||
bool found = false;
|
||||
dispatcher.forEachIf(
|
||||
event,
|
||||
[&found, &listener](
|
||||
const typename DispatcherType::Handle & /*handle*/,
|
||||
const typename DispatcherType::Callback & item
|
||||
) -> bool {
|
||||
if(item == listener) {
|
||||
found = true;
|
||||
return false;
|
||||
}
|
||||
else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
template <typename DispatcherType>
|
||||
bool hasAnyListener(
|
||||
DispatcherType & dispatcher,
|
||||
const typename DispatcherType::Event & event
|
||||
)
|
||||
{
|
||||
bool found = false;
|
||||
dispatcher.forEachIf(
|
||||
event,
|
||||
[&found](
|
||||
const typename DispatcherType::Handle & /*handle*/,
|
||||
const typename DispatcherType::Callback & /*item*/
|
||||
) -> bool {
|
||||
found = true;
|
||||
return false;
|
||||
}
|
||||
);
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
template <typename CallbackListType>
|
||||
bool hasListener(
|
||||
CallbackListType & callbackList,
|
||||
const typename CallbackListType::Callback & callback
|
||||
)
|
||||
{
|
||||
bool found = false;
|
||||
callbackList.forEachIf(
|
||||
[&found, &callback](
|
||||
const typename CallbackListType::Handle & /*handle*/,
|
||||
const typename CallbackListType::Callback & item
|
||||
) -> bool {
|
||||
if(item == callback) {
|
||||
found = true;
|
||||
return false;
|
||||
}
|
||||
else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
template <typename CallbackListType>
|
||||
bool hasAnyListener(
|
||||
CallbackListType & callbackList
|
||||
)
|
||||
{
|
||||
bool found = false;
|
||||
callbackList.forEachIf(
|
||||
[&found](
|
||||
const typename CallbackListType::Handle & /*handle*/,
|
||||
const typename CallbackListType::Callback & /*item*/
|
||||
) -> bool {
|
||||
found = true;
|
||||
return false;
|
||||
}
|
||||
);
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef ORDEREDQUEUELIST_H_862875671799
|
||||
#define ORDEREDQUEUELIST_H_862875671799
|
||||
|
||||
#include "../eventpolicies.h"
|
||||
|
||||
#include <list>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
struct OrderedQueueListCompare
|
||||
{
|
||||
template <typename T>
|
||||
bool operator() (const T & a, const T & b) const {
|
||||
return a.event < b.event;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T, typename Compare = OrderedQueueListCompare>
|
||||
class OrderedQueueList : private std::list<T>
|
||||
{
|
||||
private:
|
||||
using super = std::list<T>;
|
||||
|
||||
public:
|
||||
using iterator = typename super::iterator;
|
||||
using const_iterator = typename super::const_iterator;
|
||||
using super::empty;
|
||||
using super::begin;
|
||||
using super::end;
|
||||
using super::front;
|
||||
using super::swap;
|
||||
using super::emplace_back;
|
||||
|
||||
void splice(const_iterator pos, OrderedQueueList & other) {
|
||||
super::splice(pos, other);
|
||||
doSort();
|
||||
}
|
||||
|
||||
void splice(const_iterator pos, OrderedQueueList & other, const_iterator it) {
|
||||
super::splice(pos, other, it);
|
||||
doSort();
|
||||
}
|
||||
|
||||
private:
|
||||
void doSort() {
|
||||
auto compare = Compare();
|
||||
this->sort([compare](const T & a, const T & b) {
|
||||
// a and b may be empty if they are recycled to free list.
|
||||
if(a.empty()) {
|
||||
if(b.empty()) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
else if(b.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return compare(a.get(), b.get());
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef SCOPEDREMOVER_H_695291515513
|
||||
#define SCOPEDREMOVER_H_695291515513
|
||||
|
||||
#include "../eventpolicies.h"
|
||||
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <typename Item, typename Handle, typename Mutex>
|
||||
bool removeHandleFromScopedRemoverItemList(std::vector<Item> & itemList, Handle & handle, Mutex & mutex)
|
||||
{
|
||||
if(! handle) {
|
||||
return false;
|
||||
}
|
||||
auto handlePointer = handle.lock();
|
||||
std::unique_lock<Mutex> lock(mutex);
|
||||
auto it = std::find_if(itemList.begin(), itemList.end(), [&handlePointer](Item & item) {
|
||||
return item.handle && item.handle.lock() == handlePointer;
|
||||
});
|
||||
if(it != itemList.end()) {
|
||||
itemList.erase(it);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
template <typename DispatcherType, typename Enabled = void>
|
||||
class ScopedRemover;
|
||||
|
||||
template <typename DispatcherType>
|
||||
class ScopedRemover <
|
||||
DispatcherType,
|
||||
typename std::enable_if<std::is_base_of<TagEventDispatcher, DispatcherType>::value>::type
|
||||
>
|
||||
{
|
||||
private:
|
||||
struct Item
|
||||
{
|
||||
typename DispatcherType::Event event;
|
||||
typename DispatcherType::Handle handle;
|
||||
};
|
||||
|
||||
public:
|
||||
ScopedRemover()
|
||||
: dispatcher(nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
explicit ScopedRemover(DispatcherType & dispatcher)
|
||||
: dispatcher(&dispatcher)
|
||||
{
|
||||
}
|
||||
|
||||
ScopedRemover(ScopedRemover && other) noexcept
|
||||
: dispatcher(std::move(other.dispatcher)), itemList(std::move(other.itemList))
|
||||
{
|
||||
other.reset();
|
||||
}
|
||||
|
||||
ScopedRemover & operator = (ScopedRemover && other) noexcept
|
||||
{
|
||||
dispatcher = std::move(other.dispatcher);
|
||||
itemList = std::move(other.itemList);
|
||||
other.reset();
|
||||
return *this;
|
||||
}
|
||||
|
||||
~ScopedRemover()
|
||||
{
|
||||
reset();
|
||||
}
|
||||
|
||||
void swap(ScopedRemover & other) noexcept {
|
||||
using std::swap;
|
||||
|
||||
swap(dispatcher, other.dispatcher);
|
||||
swap(itemList, other.itemList);
|
||||
}
|
||||
|
||||
void reset()
|
||||
{
|
||||
if(dispatcher != nullptr) {
|
||||
for(const auto & item : itemList) {
|
||||
dispatcher->removeListener(item.event, item.handle);
|
||||
}
|
||||
}
|
||||
|
||||
std::unique_lock<typename DispatcherType::Mutex> lock(itemListMutex);
|
||||
itemList.clear();
|
||||
}
|
||||
|
||||
void setDispatcher(DispatcherType & dispatcher_)
|
||||
{
|
||||
if(this->dispatcher != &dispatcher_) {
|
||||
reset();
|
||||
this->dispatcher = &dispatcher_;
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename DispatcherType::Handle appendListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener
|
||||
)
|
||||
{
|
||||
Item item {
|
||||
event,
|
||||
dispatcher->appendListener(event, listener)
|
||||
};
|
||||
|
||||
{
|
||||
std::unique_lock<typename DispatcherType::Mutex> lock(itemListMutex);
|
||||
itemList.push_back(item);
|
||||
}
|
||||
|
||||
return item.handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename DispatcherType::Handle prependListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener
|
||||
)
|
||||
{
|
||||
Item item {
|
||||
event,
|
||||
dispatcher->prependListener(event, listener)
|
||||
};
|
||||
|
||||
{
|
||||
std::unique_lock<typename DispatcherType::Mutex> lock(itemListMutex);
|
||||
itemList.push_back(item);
|
||||
}
|
||||
|
||||
return item.handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename DispatcherType::Handle insertListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener,
|
||||
const typename DispatcherType::Handle & before
|
||||
)
|
||||
{
|
||||
Item item {
|
||||
event,
|
||||
dispatcher->insertListener(event, listener, before)
|
||||
};
|
||||
|
||||
{
|
||||
std::unique_lock<typename DispatcherType::Mutex> lock(itemListMutex);
|
||||
itemList.push_back(item);
|
||||
}
|
||||
|
||||
return item.handle;
|
||||
}
|
||||
|
||||
bool removeListener(const typename DispatcherType::Event & event, const typename DispatcherType::Handle handle)
|
||||
{
|
||||
if(internal_::removeHandleFromScopedRemoverItemList(itemList, handle, itemListMutex)) {
|
||||
return dispatcher->removeListener(event, handle);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private:
|
||||
DispatcherType * dispatcher;
|
||||
std::vector<Item> itemList;
|
||||
typename DispatcherType::Mutex itemListMutex;
|
||||
};
|
||||
|
||||
template <typename CallbackListType>
|
||||
class ScopedRemover <
|
||||
CallbackListType,
|
||||
typename std::enable_if<std::is_base_of<TagCallbackList, CallbackListType>::value>::type
|
||||
>
|
||||
{
|
||||
private:
|
||||
struct Item
|
||||
{
|
||||
typename CallbackListType::Handle handle;
|
||||
};
|
||||
|
||||
public:
|
||||
ScopedRemover()
|
||||
: callbackList(nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
explicit ScopedRemover(CallbackListType & callbackList)
|
||||
: callbackList(&callbackList)
|
||||
{
|
||||
}
|
||||
|
||||
ScopedRemover(ScopedRemover && other) noexcept
|
||||
: callbackList(std::move(other.callbackList)), itemList(std::move(other.itemList))
|
||||
{
|
||||
other.reset();
|
||||
}
|
||||
|
||||
ScopedRemover & operator = (ScopedRemover && other) noexcept
|
||||
{
|
||||
callbackList = std::move(other.callbackList);
|
||||
itemList = std::move(other.itemList);
|
||||
other.reset();
|
||||
return *this;
|
||||
}
|
||||
|
||||
~ScopedRemover()
|
||||
{
|
||||
reset();
|
||||
}
|
||||
|
||||
void swap(ScopedRemover & other) noexcept {
|
||||
using std::swap;
|
||||
|
||||
swap(callbackList, other.callbackList);
|
||||
swap(itemList, other.itemList);
|
||||
}
|
||||
|
||||
void reset()
|
||||
{
|
||||
if(callbackList != nullptr) {
|
||||
for(const auto & item : itemList) {
|
||||
callbackList->remove(item.handle);
|
||||
}
|
||||
}
|
||||
|
||||
std::unique_lock<typename CallbackListType::Mutex> lock(itemListMutex);
|
||||
itemList.clear();
|
||||
}
|
||||
|
||||
void setCallbackList(CallbackListType & callbackList_)
|
||||
{
|
||||
if(this->callbackList != &callbackList_) {
|
||||
reset();
|
||||
this->callbackList = &callbackList_;
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename CallbackListType::Handle append(
|
||||
const Callback & callback
|
||||
)
|
||||
{
|
||||
Item item {
|
||||
callbackList->append(callback)
|
||||
};
|
||||
|
||||
{
|
||||
std::unique_lock<typename CallbackListType::Mutex> lock(itemListMutex);
|
||||
itemList.push_back(item);
|
||||
}
|
||||
|
||||
return item.handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename CallbackListType::Handle prepend(
|
||||
const Callback & callback
|
||||
)
|
||||
{
|
||||
Item item {
|
||||
callbackList->prepend(callback)
|
||||
};
|
||||
|
||||
{
|
||||
std::unique_lock<typename CallbackListType::Mutex> lock(itemListMutex);
|
||||
itemList.push_back(item);
|
||||
}
|
||||
|
||||
return item.handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename CallbackListType::Handle insert(
|
||||
const Callback & callback,
|
||||
const typename CallbackListType::Handle & before
|
||||
)
|
||||
{
|
||||
Item item {
|
||||
callbackList->insert(callback, before)
|
||||
};
|
||||
|
||||
{
|
||||
std::unique_lock<typename CallbackListType::Mutex> lock(itemListMutex);
|
||||
itemList.push_back(item);
|
||||
}
|
||||
|
||||
return item.handle;
|
||||
}
|
||||
|
||||
bool remove(const typename CallbackListType::Handle handle)
|
||||
{
|
||||
if(internal_::removeHandleFromScopedRemoverItemList(itemList, handle, itemListMutex)) {
|
||||
return callbackList->remove(handle);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private:
|
||||
CallbackListType * callbackList;
|
||||
std::vector<Item> itemList;
|
||||
typename CallbackListType::Mutex itemListMutex;
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,16 @@
|
||||
eventpp library
|
||||
|
||||
Copyright (C) 2018 Wang Qi (wqking)
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
+101
-82
@@ -1,96 +1,115 @@
|
||||
#include <string>
|
||||
#include <JuiceAgent/Logger.hpp>
|
||||
#include <JuiceAgent.hpp>
|
||||
#include <jni_impl.hpp>
|
||||
#include <event/event_type.hpp>
|
||||
#include <event/eventbus.hpp>
|
||||
#include <JuiceAgent/Config.hpp>
|
||||
#include <jni_common.hpp>
|
||||
#include <services.hpp>
|
||||
#include <eventbus.hpp>
|
||||
|
||||
namespace JuiceAgent {
|
||||
// ===== Singleton =====
|
||||
Agent& Agent::instance() {
|
||||
// Singleton
|
||||
Agent& Agent::getInstance() {
|
||||
static Agent instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
bool Agent::init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti, std::string& runtime_dir) {
|
||||
try {
|
||||
spdlog::info("JuiceAgent Native EntryPoint Invoked!");
|
||||
|
||||
// ======== neccessary environment check ========
|
||||
if (jvm == nullptr) {
|
||||
spdlog::error("Failed to initialize JuiceAgent: jvm is null");
|
||||
return false;
|
||||
}
|
||||
if (env == nullptr) {
|
||||
spdlog::error("Failed to initialize JuiceAgent: env is null");
|
||||
return false;
|
||||
}
|
||||
if (jvmti == nullptr) {
|
||||
spdlog::error("Failed to initialize JuiceAgent: jvmti is null");
|
||||
return false;
|
||||
}
|
||||
JuiceAgent::Config::Config cfg (runtime_dir);
|
||||
if (!cfg.is_valid()) {
|
||||
spdlog::error("Failed to initialize JuiceAgent: config is invalid");
|
||||
return false;
|
||||
}
|
||||
bool Agent::preload(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti, std::string& runtime_dir) {
|
||||
// Check if the agent is already loaded
|
||||
if(Agent::getInstance().isLoaded()) {
|
||||
spdlog::warn("[JuiceAgent] Agent already loaded! Loading again will cause problems!");
|
||||
}
|
||||
|
||||
set_jvm(jvm);
|
||||
set_jvmti(jvmti);
|
||||
set_env(env);
|
||||
set_config(cfg);
|
||||
spdlog::debug("env: {}, jvmti: {}", fmt::ptr(env), fmt::ptr(jvmti));
|
||||
|
||||
// Register events for services
|
||||
JuiceAgent::services::Manager::register_events();
|
||||
|
||||
// PreLoad Event
|
||||
eventbus.post(EventPreLoad{
|
||||
.jvm = jvm,
|
||||
.env = env,
|
||||
.jvmti = jvmti
|
||||
});
|
||||
|
||||
// ======== Application ability ========
|
||||
jvmtiCapabilities caps{};
|
||||
caps.can_get_bytecodes = 1;
|
||||
caps.can_redefine_classes = 1;
|
||||
caps.can_redefine_any_class = 1;
|
||||
caps.can_retransform_classes = 1;
|
||||
caps.can_retransform_any_class = 1;
|
||||
caps.can_generate_all_class_hook_events = 1;
|
||||
jint result = jvmti->AddCapabilities(&caps);
|
||||
if (result != JNI_OK) {
|
||||
spdlog::error("Failed to add capabilities: {}", result);
|
||||
return false;
|
||||
}
|
||||
|
||||
spdlog::info("Abilities added successfully");
|
||||
|
||||
// ======== Register callbacks ========
|
||||
jvmtiEventCallbacks callbacks{};
|
||||
callbacks.ClassFileLoadHook = &ClassFileLoadHook;
|
||||
result = jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks));
|
||||
if (result != JNI_OK) {
|
||||
spdlog::error("Failed to set event callbacks: {}", result);
|
||||
}
|
||||
|
||||
// Enable events
|
||||
result = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, NULL);
|
||||
if (result != JNI_OK) {
|
||||
spdlog::error("Failed to enable event notification: {}", result);
|
||||
}
|
||||
|
||||
// Loaded Event
|
||||
eventbus.post(EventLoaded{
|
||||
.jvm = jvm,
|
||||
.env = env,
|
||||
.jvmti = jvmti
|
||||
});
|
||||
return true;
|
||||
} catch (const std::exception& e) {
|
||||
spdlog::error("Exception: {}", e.what());
|
||||
// Environment check
|
||||
if(!jvm || jvm==nullptr) {
|
||||
spdlog::error("[JuiceAgent] No JVM found!");
|
||||
return false;
|
||||
}
|
||||
if(!env || env==nullptr) {
|
||||
spdlog::error("[JuiceAgent] Could not get JNIEnv!");
|
||||
return false;
|
||||
}
|
||||
if(!jvmti || jvmti==nullptr) {
|
||||
spdlog::error("[JuiceAgent] Could not get JVMTI!");
|
||||
return false;
|
||||
}
|
||||
if(runtime_dir.empty()) {
|
||||
spdlog::warn("[JuiceAgent] No runtime directory specified!");
|
||||
spdlog::warn("[JuiceAgent] No config provided, Modules will not be loaded!");
|
||||
} else {
|
||||
JuiceAgent::Config::Config cfg(runtime_dir);
|
||||
setConfig(cfg);
|
||||
if(!getConfig().is_valid()) {
|
||||
spdlog::warn("[JuiceAgent] Config is not valid!");
|
||||
spdlog::warn("[JuiceAgent] No config provided, Modules will not be loaded!");
|
||||
}
|
||||
}
|
||||
|
||||
// Set Environment
|
||||
setJavaVM(jvm);
|
||||
setJNIEnv(env);
|
||||
setJVMTI(jvmti);
|
||||
// Debug
|
||||
spdlog::debug("[JuiceAgent] JavaVM: {:p}, JNIEnv: {:p}, JVMTI: {:p}",
|
||||
(void*)jvm,
|
||||
(void*)env,
|
||||
(void*)jvmti);
|
||||
|
||||
setLoaded(true);
|
||||
|
||||
// Post preload event (after environment is set so listeners
|
||||
// can access the agent state via Agent::getInstance())
|
||||
EventPreLoad preloadEvent{ jvm, env, jvmti };
|
||||
EventBus::getInstance().post(EventId::PreLoad, &preloadEvent);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
bool Agent::init() {
|
||||
if(!isLoaded()) {
|
||||
spdlog::error("[JuiceAgent] Agent not loaded! Please call preload() first!");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Add Abilities
|
||||
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 = getJVMTI()->AddCapabilities(&caps);
|
||||
if(result != JVMTI_ERROR_NONE) {
|
||||
spdlog::error("[JuiceAgent] Could not add JVMTI capabilities: {}", result);
|
||||
return false;
|
||||
}
|
||||
spdlog::info("[JuiceAgent] Added JVMTI capabilities");
|
||||
|
||||
// Register callbacks
|
||||
jvmtiEventCallbacks callbacks{};
|
||||
callbacks.ClassFileLoadHook = &ClassFileLoadHook;
|
||||
result = getJVMTI()->SetEventCallbacks(&callbacks, sizeof(callbacks));
|
||||
if(result != JVMTI_ERROR_NONE) {
|
||||
spdlog::error("[JuiceAgent] Could not set JVMTI event callbacks: {}", result);
|
||||
}
|
||||
|
||||
// Enable events
|
||||
result = getJVMTI()->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, nullptr);
|
||||
if(result != JVMTI_ERROR_NONE) {
|
||||
spdlog::error("[JuiceAgent] Could not enable JVMTI event notifications: {}", result);
|
||||
}
|
||||
|
||||
// Initialize services
|
||||
if(!JuiceAgent::Services::initializeAll()) {
|
||||
spdlog::error("[JuiceAgent] Failed to initialize services");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Post loaded event
|
||||
EventLoaded loadedEvent{ getJavaVM(), getJNIEnv(), getJVMTI() };
|
||||
EventBus::getInstance().post(EventId::Loaded, &loadedEvent);
|
||||
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -1,38 +0,0 @@
|
||||
#include <jni_impl.hpp>
|
||||
#include <event/event_type.hpp>
|
||||
|
||||
void JNICALL ClassFileLoadHook(
|
||||
jvmtiEnv* jvmti_env,
|
||||
JNIEnv* jni_env,
|
||||
jclass class_being_redefined,
|
||||
jobject loader,
|
||||
const char* name,
|
||||
jobject protection_domain,
|
||||
jint class_data_len,
|
||||
const unsigned char* classbytes,
|
||||
jint* new_class_data_len,
|
||||
unsigned char** new_classbytes) {
|
||||
if (!name) {
|
||||
spdlog::warn("name is null");
|
||||
return;
|
||||
}
|
||||
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
|
||||
EventClassFileLoadHook event{
|
||||
.jvmti_env = jvmti_env,
|
||||
.jni_env = jni_env,
|
||||
.class_being_redefined = class_being_redefined,
|
||||
.loader = loader,
|
||||
.name = name,
|
||||
.protection_domain = protection_domain,
|
||||
.class_data_len = class_data_len,
|
||||
.classbytes = classbytes,
|
||||
.new_class_data_len = new_class_data_len,
|
||||
.new_classbytes = new_classbytes
|
||||
};
|
||||
|
||||
agent.get_eventbus().post(event);
|
||||
|
||||
agent.get_eventbus().post_mutable(event);
|
||||
}
|
||||
@@ -1,15 +0,0 @@
|
||||
#include <jni_impl.hpp>
|
||||
#include <event/event_type.hpp>
|
||||
|
||||
void JNICALL MethodEntry(jvmtiEnv *jvmti_env,
|
||||
JNIEnv* jni_env,
|
||||
jthread thread,
|
||||
jmethodID method) {
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
agent.get_eventbus().post(EventMethodEntry{
|
||||
.jvmti_env = jvmti_env,
|
||||
.jni_env = jni_env,
|
||||
.thread = thread,
|
||||
.method = method
|
||||
});
|
||||
}
|
||||
@@ -1,19 +0,0 @@
|
||||
#include <jni_impl.hpp>
|
||||
#include <event/event_type.hpp>
|
||||
|
||||
void JNICALL MethodExit(jvmtiEnv *jvmti_env,
|
||||
JNIEnv* jni_env,
|
||||
jthread thread,
|
||||
jmethodID method,
|
||||
jboolean was_popped_by_exception,
|
||||
jvalue return_value) {
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
agent.get_eventbus().post(EventMethodExit{
|
||||
.jvmti_env = jvmti_env,
|
||||
.jni_env = jni_env,
|
||||
.thread = thread,
|
||||
.method = method,
|
||||
.was_popped_by_exception = was_popped_by_exception,
|
||||
.return_value = return_value
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,34 @@
|
||||
#include <jni_common.hpp>
|
||||
#include <eventbus.hpp>
|
||||
|
||||
void JNICALL ClassFileLoadHook(
|
||||
jvmtiEnv* jvmti_env,
|
||||
JNIEnv* jni_env,
|
||||
jclass class_being_redefined,
|
||||
jobject loader,
|
||||
const char* name,
|
||||
jobject protection_domain,
|
||||
jint class_data_len,
|
||||
const unsigned char* classbytes,
|
||||
jint* new_class_data_len,
|
||||
unsigned char** new_classbytes) {
|
||||
if (!name) {
|
||||
spdlog::warn("[ClassFileLoadHook] name is null");
|
||||
return;
|
||||
}
|
||||
|
||||
EventClassFileLoadHook event{
|
||||
jvmti_env,
|
||||
jni_env,
|
||||
class_being_redefined,
|
||||
loader,
|
||||
name,
|
||||
protection_domain,
|
||||
class_data_len,
|
||||
classbytes,
|
||||
new_class_data_len,
|
||||
new_classbytes
|
||||
};
|
||||
|
||||
EventBus::getInstance().post(EventId::ClassFileLoadHook, &event);
|
||||
}
|
||||
@@ -1,8 +0,0 @@
|
||||
#include <global.hpp>
|
||||
|
||||
std::unordered_set<std::string> classToCapture;
|
||||
std::unordered_map<std::string, ClassFileData> classFileDataMap;
|
||||
std::mutex classDataMutex;
|
||||
|
||||
std::unordered_map<std::string, std::vector<unsigned char>> pendingRetransform;
|
||||
std::mutex pendingRetransformMutex;
|
||||
@@ -1,119 +0,0 @@
|
||||
#include <jni.h>
|
||||
#include <jvmti.h>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <jni_impl.hpp>
|
||||
#include <JuiceAgent/JuiceAgent-API-1.4.1+build.1.hpp>
|
||||
|
||||
// Global state
|
||||
static JavaVM* g_vm = nullptr;
|
||||
static jvmtiEnv* g_jvmti = nullptr;
|
||||
|
||||
// Forward declaration
|
||||
void JNICALL OnVMInit(jvmtiEnv* jvmti, JNIEnv* env, jthread thread);
|
||||
|
||||
// Utility: check JVMTI error
|
||||
static bool CheckJvmti(jvmtiError err, const char* action) {
|
||||
if (err != JVMTI_ERROR_NONE) {
|
||||
spdlog::error("{} failed, code={}", action, static_cast<int>(err));
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// VMInit callback
|
||||
void JNICALL OnVMInit(jvmtiEnv* jvmti, JNIEnv* env, jthread thread) {
|
||||
spdlog::info("JVMTI VMInit triggered");
|
||||
|
||||
std::string runtime_dir = std::filesystem::current_path().string();
|
||||
|
||||
if (runtime_dir.empty()) {
|
||||
spdlog::error("runtime_dir is empty");
|
||||
return;
|
||||
}
|
||||
|
||||
spdlog::info("Runtime directory: {}", runtime_dir);
|
||||
|
||||
// Inject JuiceAgent-API
|
||||
// Save bytes to file
|
||||
std::string hash =
|
||||
JuiceAgent::Resource::juiceagent_api_bytes_sha256;
|
||||
|
||||
std::string file_name =
|
||||
hash.substr(0, 8) + "_" +
|
||||
JuiceAgent::Resource::juiceagent_api_bytes_name;
|
||||
|
||||
std::string juiceagent_api_path =
|
||||
JuiceAgent::Utils::File::write_to_tempfile(
|
||||
JuiceAgent::Resource::juiceagent_api_bytes,
|
||||
JuiceAgent::Resource::juiceagent_api_bytes_len,
|
||||
file_name
|
||||
);
|
||||
|
||||
spdlog::debug("Saved JuiceAgent-API to: {}", juiceagent_api_path);
|
||||
spdlog::debug("JuiceAgent-API size: {}", JuiceAgent::Resource::juiceagent_api_bytes_len);
|
||||
spdlog::debug("JuiceAgent-API SHA256: {}", JuiceAgent::Resource::juiceagent_api_bytes_sha256);
|
||||
|
||||
// Inject JuiceAgent jar into system class loader
|
||||
jint status = jvmti->AddToSystemClassLoaderSearch(juiceagent_api_path.c_str());
|
||||
if (status != JNI_OK) {
|
||||
spdlog::error("AddToSystemClassLoaderSearch failed: {}", status);
|
||||
return;
|
||||
}
|
||||
|
||||
spdlog::info("Jar injected successfully: {}", juiceagent_api_path);
|
||||
|
||||
JuiceAgent::Agent& agent = JuiceAgent::Agent::instance();
|
||||
agent.init(g_vm, env, g_jvmti, runtime_dir);
|
||||
|
||||
spdlog::info("JuiceAgent initialized successfully");
|
||||
}
|
||||
|
||||
// Agent entry
|
||||
JNIEXPORT jint JNICALL
|
||||
Agent_OnLoad(JavaVM* vm, char* options, void* reserved) {
|
||||
Logger::init("libagent.log");
|
||||
|
||||
spdlog::info("Agent_OnLoad");
|
||||
|
||||
g_vm = vm;
|
||||
|
||||
// Get JVMTI first
|
||||
jint result = vm->GetEnv(reinterpret_cast<void**>(&g_jvmti), JVMTI_VERSION_1_2);
|
||||
if (result != JNI_OK || g_jvmti == nullptr) {
|
||||
spdlog::error("Failed to get JVMTI, code={}", result);
|
||||
return JNI_ERR;
|
||||
}
|
||||
|
||||
// Optional capabilities
|
||||
jvmtiCapabilities caps{};
|
||||
CheckJvmti(g_jvmti->AddCapabilities(&caps), "AddCapabilities");
|
||||
|
||||
// Register callbacks
|
||||
jvmtiEventCallbacks callbacks{};
|
||||
callbacks.VMInit = &OnVMInit;
|
||||
|
||||
if (!CheckJvmti(
|
||||
g_jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks)),
|
||||
"SetEventCallbacks")) {
|
||||
return JNI_ERR;
|
||||
}
|
||||
|
||||
if (!CheckJvmti(
|
||||
g_jvmti->SetEventNotificationMode(
|
||||
JVMTI_ENABLE,
|
||||
JVMTI_EVENT_VM_INIT,
|
||||
nullptr),
|
||||
"Enable VM_INIT")) {
|
||||
return JNI_ERR;
|
||||
}
|
||||
|
||||
spdlog::info("Agent loaded, waiting for VMInit...");
|
||||
return JNI_OK;
|
||||
}
|
||||
|
||||
// Optional unload
|
||||
JNIEXPORT void JNICALL
|
||||
Agent_OnUnload(JavaVM* vm) {
|
||||
spdlog::info("Agent_OnUnload");
|
||||
}
|
||||
+24
-11
@@ -1,21 +1,27 @@
|
||||
#include <jni_impl.hpp>
|
||||
#include <JuiceAgent.hpp>
|
||||
#include <jni_common.hpp>
|
||||
|
||||
// This function is called by Java to initialize the agent.
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init
|
||||
(JNIEnv *env, jclass , jstring j_runtime_dir) {
|
||||
|
||||
Logger::init("libagent.log");
|
||||
|
||||
spdlog::info("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);
|
||||
std::string runtime_dir;
|
||||
|
||||
if (j_runtime_dir != nullptr) {
|
||||
const char* c_runtime_dir = env->GetStringUTFChars(j_runtime_dir, nullptr);
|
||||
|
||||
if (c_runtime_dir != nullptr) {
|
||||
runtime_dir = c_runtime_dir;
|
||||
env->ReleaseStringUTFChars(j_runtime_dir, c_runtime_dir);
|
||||
}
|
||||
}
|
||||
|
||||
if (runtime_dir.empty()) {
|
||||
spdlog::error("Failed to get runtime directory from argument, runtime_dir is empty");
|
||||
return JNI_FALSE;
|
||||
spdlog::warn("Runtime directory is empty");
|
||||
}
|
||||
spdlog::info("JuiceAgent got runtime directory: {}", runtime_dir);
|
||||
|
||||
@@ -37,8 +43,15 @@ JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init
|
||||
}
|
||||
|
||||
// Invoke EntryPoint
|
||||
JuiceAgent::Agent& agent = JuiceAgent::Agent::instance();
|
||||
agent.init(jvm, env, jvmti, runtime_dir);
|
||||
JuiceAgent::Agent& agent = JuiceAgent::Agent::getInstance();
|
||||
if (!agent.preload(jvm, env, jvmti, runtime_dir)) {
|
||||
spdlog::error("Failed to preload JuiceAgent");
|
||||
return JNI_FALSE;
|
||||
}
|
||||
if (!agent.init()) {
|
||||
spdlog::error("Failed to init JuiceAgent");
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
return JNI_TRUE;
|
||||
}
|
||||
return JNI_TRUE;
|
||||
}
|
||||
@@ -1,45 +1,41 @@
|
||||
#pragma once
|
||||
|
||||
#include <JuiceAgent/Logger.hpp>
|
||||
#include <jni.h>
|
||||
#include <jvmti.h>
|
||||
#include <event/eventbus.hpp>
|
||||
#include <jvm/jni.h>
|
||||
#include <jvm/jvmti.h>
|
||||
#include <JuiceAgent/Config.hpp>
|
||||
|
||||
namespace JuiceAgent {
|
||||
class Agent {
|
||||
class Agent{
|
||||
private:
|
||||
JavaVM* jvm;
|
||||
jvmtiEnv* jvmti;
|
||||
// Unsafe: JNIEnv
|
||||
JNIEnv* env;
|
||||
EventBus eventbus;
|
||||
JuiceAgent::Config::Config config;
|
||||
|
||||
private:
|
||||
Agent() = default;
|
||||
~Agent() = default;
|
||||
|
||||
bool loaded = false;
|
||||
public:
|
||||
// ===== Singleton =====
|
||||
static Agent& instance();
|
||||
// Singleton
|
||||
static Agent& getInstance();
|
||||
|
||||
Agent(const Agent&) = delete;
|
||||
Agent& operator=(const Agent&) = delete;
|
||||
|
||||
// EntryPoint
|
||||
bool init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti, std::string& runtime_dir);
|
||||
|
||||
// preload
|
||||
bool preload(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti, std::string& runtime_dir);
|
||||
// init
|
||||
bool init();
|
||||
|
||||
// getters
|
||||
JavaVM* get_jvm() const { return jvm; }
|
||||
jvmtiEnv* get_jvmti() const { return jvmti; }
|
||||
JNIEnv* get_env() const { return env; }
|
||||
EventBus& get_eventbus() { return eventbus; }
|
||||
JuiceAgent::Config::Config& get_config() { return config; }
|
||||
JavaVM* getJavaVM() const { return jvm; }
|
||||
jvmtiEnv* getJVMTI() const { return jvmti; }
|
||||
JNIEnv* getJNIEnv() const { return env; }
|
||||
bool isLoaded() const { return loaded; }
|
||||
JuiceAgent::Config::Config& getConfig() { return config; }
|
||||
|
||||
// setters
|
||||
void set_jvm(JavaVM* jvm) { this->jvm = jvm; }
|
||||
void set_jvmti(jvmtiEnv* jvmti) { this->jvmti = jvmti; }
|
||||
void set_env(JNIEnv* env) { this->env = env; }
|
||||
void set_config(JuiceAgent::Config::Config& config) { this->config = config; }
|
||||
void setJavaVM(JavaVM* jvm) { this->jvm = jvm; }
|
||||
void setJVMTI(jvmtiEnv* jvmti) { this->jvmti = jvmti; }
|
||||
void setJNIEnv(JNIEnv* env) { this->env = env; }
|
||||
void setLoaded(bool loaded) { this->loaded = loaded; }
|
||||
void setConfig(JuiceAgent::Config::Config& config) { this->config = config; }
|
||||
};
|
||||
}
|
||||
@@ -1,6 +1,6 @@
|
||||
#pragma once
|
||||
|
||||
#include <jni_impl.hpp>
|
||||
#include <jni_common.hpp>
|
||||
|
||||
// ClassFileLoadHook
|
||||
struct EventClassFileLoadHook {
|
||||
|
||||
@@ -1,218 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <unordered_map>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <typeindex>
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cstdint>
|
||||
|
||||
class EventBus {
|
||||
public:
|
||||
using Token = std::uint64_t;
|
||||
|
||||
// === Readonly ===
|
||||
template<typename Event>
|
||||
using Listener = std::function<void(const Event&)>;
|
||||
|
||||
// === Mutable ===
|
||||
template<typename Event>
|
||||
using MutableListener = std::function<void(Event&)>;
|
||||
|
||||
// =========================
|
||||
// Subscribe (Readonly)
|
||||
// =========================
|
||||
template<typename Event>
|
||||
Token subscribe(Listener<Event> listener, int priority = 0) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
auto& vec = getListeners<Event>();
|
||||
|
||||
Token token = nextToken_++;
|
||||
|
||||
vec.push_back({
|
||||
token,
|
||||
priority,
|
||||
std::move(listener)
|
||||
});
|
||||
|
||||
sort(vec);
|
||||
return token;
|
||||
}
|
||||
|
||||
// =========================
|
||||
// Subscribe (Mutable)
|
||||
// =========================
|
||||
template<typename Event>
|
||||
Token subscribe_mutable(MutableListener<Event> listener, int priority = 0) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
auto& vec = getMutableListeners<Event>();
|
||||
|
||||
Token token = nextToken_++;
|
||||
|
||||
vec.push_back({
|
||||
token,
|
||||
priority,
|
||||
std::move(listener)
|
||||
});
|
||||
|
||||
sort(vec);
|
||||
return token;
|
||||
}
|
||||
|
||||
// =========================
|
||||
// Unsubscribe
|
||||
// =========================
|
||||
template<typename Event>
|
||||
bool unsubscribe(Token token) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
bool removed = false;
|
||||
|
||||
// readonly
|
||||
if (auto it = listeners_.find(std::type_index(typeid(Event))); it != listeners_.end()) {
|
||||
auto& vec = *std::static_pointer_cast<std::vector<Node<Event>>>(it->second);
|
||||
removed |= erase(vec, token);
|
||||
}
|
||||
|
||||
// mutable
|
||||
if (auto it = mutable_listeners_.find(std::type_index(typeid(Event))); it != mutable_listeners_.end()) {
|
||||
auto& vec = *std::static_pointer_cast<std::vector<MutableNode<Event>>>(it->second);
|
||||
removed |= erase(vec, token);
|
||||
}
|
||||
|
||||
return removed;
|
||||
}
|
||||
|
||||
// =========================
|
||||
// Post (Readonly)
|
||||
// =========================
|
||||
template<typename Event>
|
||||
void post(const Event& event) {
|
||||
std::vector<Node<Event>> copy;
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
auto it = listeners_.find(std::type_index(typeid(Event)));
|
||||
if (it == listeners_.end()) return;
|
||||
|
||||
copy = *std::static_pointer_cast<std::vector<Node<Event>>>(it->second);
|
||||
}
|
||||
|
||||
for (auto& node : copy) {
|
||||
node.callback(event);
|
||||
}
|
||||
}
|
||||
|
||||
// =========================
|
||||
// Post (Mutable)
|
||||
// =========================
|
||||
template<typename Event>
|
||||
void post_mutable(Event& event) {
|
||||
std::vector<MutableNode<Event>> copy;
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
auto it = mutable_listeners_.find(std::type_index(typeid(Event)));
|
||||
if (it == mutable_listeners_.end()) return;
|
||||
|
||||
copy = *std::static_pointer_cast<std::vector<MutableNode<Event>>>(it->second);
|
||||
}
|
||||
|
||||
for (auto& node : copy) {
|
||||
node.callback(event);
|
||||
}
|
||||
}
|
||||
|
||||
// =========================
|
||||
// Clear
|
||||
// =========================
|
||||
template<typename Event>
|
||||
void clear() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
listeners_.erase(std::type_index(typeid(Event)));
|
||||
mutable_listeners_.erase(std::type_index(typeid(Event)));
|
||||
}
|
||||
|
||||
void clearAll() {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
listeners_.clear();
|
||||
mutable_listeners_.clear();
|
||||
}
|
||||
|
||||
private:
|
||||
template<typename Event>
|
||||
struct Node {
|
||||
Token token;
|
||||
int priority;
|
||||
Listener<Event> callback;
|
||||
};
|
||||
|
||||
template<typename Event>
|
||||
struct MutableNode {
|
||||
Token token;
|
||||
int priority;
|
||||
MutableListener<Event> callback;
|
||||
};
|
||||
|
||||
std::mutex mutex_;
|
||||
std::atomic<Token> nextToken_{1};
|
||||
|
||||
std::unordered_map<std::type_index, std::shared_ptr<void>> listeners_;
|
||||
std::unordered_map<std::type_index, std::shared_ptr<void>> mutable_listeners_;
|
||||
|
||||
// === helpers ===
|
||||
|
||||
template<typename T>
|
||||
static void sort(std::vector<T>& vec) {
|
||||
std::sort(vec.begin(), vec.end(),
|
||||
[](const auto& a, const auto& b) {
|
||||
return a.priority > b.priority;
|
||||
});
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
static bool erase(std::vector<T>& vec, Token token) {
|
||||
auto oldSize = vec.size();
|
||||
|
||||
vec.erase(
|
||||
std::remove_if(vec.begin(), vec.end(),
|
||||
[token](const T& node) {
|
||||
return node.token == token;
|
||||
}),
|
||||
vec.end()
|
||||
);
|
||||
|
||||
return vec.size() != oldSize;
|
||||
}
|
||||
|
||||
template<typename Event>
|
||||
std::vector<Node<Event>>& getListeners() {
|
||||
return getContainer<Event, Node<Event>>(listeners_);
|
||||
}
|
||||
|
||||
template<typename Event>
|
||||
std::vector<MutableNode<Event>>& getMutableListeners() {
|
||||
return getContainer<Event, MutableNode<Event>>(mutable_listeners_);
|
||||
}
|
||||
|
||||
template<typename Event, typename NodeType>
|
||||
std::vector<NodeType>& getContainer(std::unordered_map<std::type_index, std::shared_ptr<void>>& map) {
|
||||
auto type = std::type_index(typeid(Event));
|
||||
auto it = map.find(type);
|
||||
|
||||
if (it == map.end()) {
|
||||
auto ptr = std::make_shared<std::vector<NodeType>>();
|
||||
map[type] = ptr;
|
||||
return *ptr;
|
||||
}
|
||||
|
||||
return *std::static_pointer_cast<std::vector<NodeType>>(it->second);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,47 @@
|
||||
#pragma once
|
||||
|
||||
#include <eventpp/eventdispatcher.h>
|
||||
#include <event/event_type.hpp>
|
||||
|
||||
enum class EventId {
|
||||
ClassFileLoadHook,
|
||||
MethodEntry,
|
||||
MethodExit,
|
||||
PreLoad,
|
||||
Loaded
|
||||
};
|
||||
|
||||
class EventBus {
|
||||
public:
|
||||
using Dispatcher = eventpp::EventDispatcher<EventId, void(const void*)>;
|
||||
|
||||
static EventBus& getInstance() {
|
||||
static EventBus instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
EventBus(const EventBus&) = delete;
|
||||
EventBus& operator=(const EventBus&) = delete;
|
||||
|
||||
void post(EventId id, const void* event) {
|
||||
dispatcher.dispatch(id, event);
|
||||
}
|
||||
|
||||
template <typename C>
|
||||
auto appendListener(EventId id, const C& callback) {
|
||||
return dispatcher.appendListener(id, callback);
|
||||
}
|
||||
|
||||
template <typename C>
|
||||
auto prependListener(EventId id, const C& callback) {
|
||||
return dispatcher.prependListener(id, callback);
|
||||
}
|
||||
|
||||
bool removeListener(EventId id, Dispatcher::Handle handle) {
|
||||
return dispatcher.removeListener(id, handle);
|
||||
}
|
||||
|
||||
private:
|
||||
EventBus() = default;
|
||||
Dispatcher dispatcher;
|
||||
};
|
||||
@@ -2,37 +2,228 @@
|
||||
|
||||
#include <jni.h>
|
||||
#include <jvmti.h>
|
||||
#include <vector>
|
||||
#include <mutex>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
namespace JuiceAgent {
|
||||
namespace Services {
|
||||
|
||||
// Data Structures
|
||||
struct ClassRetransformRequest {
|
||||
std::string classname;
|
||||
std::vector<unsigned char> bytecode;
|
||||
};
|
||||
struct ClassFileData {
|
||||
std::string classname;
|
||||
std::vector<unsigned char> bytecode;
|
||||
|
||||
// ======== Global references to prevent GC ========
|
||||
// Remember to release these references when they are no longer needed, otherwise it will cause memory leaks
|
||||
jclass clazz;
|
||||
jobject classloader;
|
||||
jobject protection_domain;
|
||||
|
||||
std::string classname;
|
||||
std::vector<unsigned char> bytecode;
|
||||
};
|
||||
|
||||
// Set of target class internal names to capture (e.g. java/lang/String)
|
||||
extern std::unordered_set<std::string> classToCapture;
|
||||
struct PendingPatch {
|
||||
std::vector<unsigned char> bytecode;
|
||||
};
|
||||
|
||||
// Cache of captured class bytecode, keyed by internal class name
|
||||
extern std::unordered_map<std::string, ClassFileData> classFileDataMap;
|
||||
class BytecodeStore {
|
||||
public:
|
||||
static BytecodeStore& getInstance() {
|
||||
static BytecodeStore instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
// Mutex protecting access to classToCapture and classFileDataMap (thread-safe for JVMTI callbacks)
|
||||
extern std::mutex classDataMutex;
|
||||
BytecodeStore(const BytecodeStore&) = delete;
|
||||
BytecodeStore& operator=(const BytecodeStore&) = delete;
|
||||
|
||||
extern std::unordered_map<std::string, std::vector<unsigned char>> pendingRetransform;
|
||||
extern std::mutex pendingRetransformMutex;
|
||||
// ---- Capture API (called by JNI or other services) ----
|
||||
|
||||
// Mark a class (internal name, e.g. "java/lang/String") for capture
|
||||
// on the next ClassFileLoadHook.
|
||||
void requestCapture(std::string classname) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
pendingCaptures_.insert(std::move(classname));
|
||||
}
|
||||
|
||||
// Returns the captured bytecode if available, removing it from the cache.
|
||||
// Returns std::nullopt if not yet captured.
|
||||
std::optional<ClassFileData> takeCaptured(const std::string& classname) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
auto it = captured_.find(classname);
|
||||
if (it == captured_.end()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
ClassFileData data = std::move(it->second);
|
||||
captured_.erase(it);
|
||||
return data;
|
||||
}
|
||||
|
||||
// Peek without removing.
|
||||
std::optional<ClassFileData> peekCaptured(const std::string& classname) const {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
auto it = captured_.find(classname);
|
||||
if (it == captured_.end()) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return it->second;
|
||||
}
|
||||
|
||||
// ---- Patch API (called by JNI or other services) ----
|
||||
|
||||
// Queue a retransform: the next ClassFileLoadHook for this class will
|
||||
// replace its bytecode with the provided buffer.
|
||||
void requestPatch(std::string classname, std::vector<unsigned char> bytecode) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
pendingPatches_.insert_or_assign(
|
||||
std::move(classname),
|
||||
PendingPatch{std::move(bytecode)}
|
||||
);
|
||||
}
|
||||
|
||||
private:
|
||||
friend class BytecodeService;
|
||||
|
||||
BytecodeStore() = default;
|
||||
|
||||
// Called by BytecodeService::captureBytecodes under internal lock.
|
||||
// Stores the raw bytes if this class is pending capture.
|
||||
// Returns the captured byte length, or 0 if no capture was pending.
|
||||
std::size_t tryCapture(const char* name, const unsigned char* bytes, jint len) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (!name || !bytes || len <= 0) return 0;
|
||||
|
||||
auto reqIt = pendingCaptures_.find(name);
|
||||
if (reqIt == pendingCaptures_.end()) return 0;
|
||||
if (captured_.find(name) != captured_.end()) {
|
||||
pendingCaptures_.erase(reqIt);
|
||||
return 0;
|
||||
}
|
||||
|
||||
ClassFileData data;
|
||||
data.classname = name;
|
||||
data.bytecode.assign(bytes, bytes + len);
|
||||
|
||||
std::size_t capturedLen = data.bytecode.size();
|
||||
captured_.emplace(name, std::move(data));
|
||||
pendingCaptures_.erase(reqIt);
|
||||
return capturedLen;
|
||||
}
|
||||
|
||||
// Called by BytecodeService::patchBytecodes under internal lock.
|
||||
// If a pending patch exists for `name`, moves its bytecode out and
|
||||
// returns true; otherwise returns false.
|
||||
bool takePatch(const char* name, std::vector<unsigned char>& out) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
if (!name) return false;
|
||||
auto it = pendingPatches_.find(name);
|
||||
if (it == pendingPatches_.end()) return false;
|
||||
out = std::move(it->second.bytecode);
|
||||
pendingPatches_.erase(it);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Put a failed patch back so it can be retried on the next hook.
|
||||
void putBackPatch(const char* name, std::vector<unsigned char>&& bytes) {
|
||||
if (!name || bytes.empty()) return;
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
pendingPatches_.insert_or_assign(
|
||||
name, PendingPatch{std::move(bytes)});
|
||||
}
|
||||
|
||||
mutable std::mutex mutex_;
|
||||
std::unordered_set<std::string> pendingCaptures_;
|
||||
std::unordered_map<std::string, ClassFileData> captured_;
|
||||
std::unordered_map<std::string, PendingPatch> pendingPatches_;
|
||||
};
|
||||
|
||||
class Remapper {
|
||||
public:
|
||||
static Remapper& getInstance() {
|
||||
static Remapper instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
Remapper(const Remapper&) = delete;
|
||||
Remapper& operator=(const Remapper&) = delete;
|
||||
|
||||
bool isInit() const { return initialized_; }
|
||||
void setInit(bool init) { initialized_ = init; }
|
||||
|
||||
// Cached JNI static declarations for the Java remap class.
|
||||
jclass getRemapClass() const { return remapClass_; }
|
||||
jmethodID getRemapMethodId() const { return remapMethodId_; }
|
||||
void setRemapClass(jclass clazz) { remapClass_ = clazz; }
|
||||
void setRemapMethodId(jmethodID methodId) { remapMethodId_ = methodId; }
|
||||
|
||||
// ---- Include/Exclude filters ----
|
||||
|
||||
void addInclude(std::string name) {
|
||||
std::lock_guard<std::mutex> lock(filterMutex_);
|
||||
includes_.insert(std::move(name));
|
||||
}
|
||||
|
||||
void removeInclude(const std::string& name) {
|
||||
std::lock_guard<std::mutex> lock(filterMutex_);
|
||||
includes_.erase(name);
|
||||
}
|
||||
|
||||
void clearIncludes() {
|
||||
std::lock_guard<std::mutex> lock(filterMutex_);
|
||||
includes_.clear();
|
||||
}
|
||||
|
||||
void addExclude(std::string name) {
|
||||
std::lock_guard<std::mutex> lock(filterMutex_);
|
||||
excludes_.insert(std::move(name));
|
||||
}
|
||||
|
||||
void removeExclude(const std::string& name) {
|
||||
std::lock_guard<std::mutex> lock(filterMutex_);
|
||||
excludes_.erase(name);
|
||||
}
|
||||
|
||||
void clearExcludes() {
|
||||
std::lock_guard<std::mutex> lock(filterMutex_);
|
||||
excludes_.clear();
|
||||
}
|
||||
|
||||
// A class should be remapped when:
|
||||
// 1. its name is not excluded, and
|
||||
// 2. its name matches an include filter.
|
||||
// Remapping is OFF by default: an empty include set means nothing is
|
||||
// remapped. To enable remapping for a package, add it as an include
|
||||
// (e.g. "com/example/" matches the whole package).
|
||||
//
|
||||
// Matching rules (applied to both include and exclude):
|
||||
// - exact internal name match
|
||||
// - package prefix (ends with '/', e.g. "java/lang/")
|
||||
// - class prefix + nested classes (e.g. "java/lang/Shutdown"
|
||||
// also excludes "java/lang/Shutdown$Lock")
|
||||
bool shouldRemap(const std::string& name) const {
|
||||
std::lock_guard<std::mutex> lock(filterMutex_);
|
||||
|
||||
for (const auto& exc : excludes_) {
|
||||
if (name == exc) return false;
|
||||
if (exc.back() == '/' && name.rfind(exc, 0) == 0) return false;
|
||||
if (name.size() > exc.size() &&
|
||||
name.rfind(exc, 0) == 0 && name[exc.size()] == '$') return false;
|
||||
}
|
||||
|
||||
for (const auto& inc : includes_) {
|
||||
if (name == inc) return true;
|
||||
if (inc.back() == '/' && name.rfind(inc, 0) == 0) return true;
|
||||
if (name.size() > inc.size() &&
|
||||
name.rfind(inc, 0) == 0 && name[inc.size()] == '$') return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private:
|
||||
Remapper() = default;
|
||||
|
||||
bool initialized_ = false;
|
||||
jclass remapClass_ = nullptr; // global ref
|
||||
jmethodID remapMethodId_ = nullptr; // static method id
|
||||
|
||||
mutable std::mutex filterMutex_;
|
||||
std::unordered_set<std::string> includes_;
|
||||
std::unordered_set<std::string> excludes_;
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#include <jni.h>
|
||||
#include <jvmti.h>
|
||||
#include <JuiceAgent/Logger.hpp>
|
||||
#include <JuiceAgent.hpp>
|
||||
#include <utils.hpp>
|
||||
#include <global.hpp>
|
||||
|
||||
// Generated by JuiceAgent-API
|
||||
#include <JuiceAgent/cn_xiaozhou233_juiceagent_api_JuiceAgent.h>
|
||||
|
||||
// Generated by JuiceRemapper
|
||||
#include <JuiceRemapper/cn_xiaozhou233_juiceremapper_JuiceRemapper.h>
|
||||
|
||||
// Event callbacks
|
||||
// See https://docs.oracle.com/javase/8/docs/platform/jvmti/jvmti.html#ClassFileLoadHook
|
||||
void JNICALL ClassFileLoadHook(
|
||||
jvmtiEnv* jvmti_env,
|
||||
JNIEnv* jni_env,
|
||||
jclass class_being_redefined,
|
||||
jobject loader,
|
||||
const char* name,
|
||||
jobject protection_domain,
|
||||
jint class_data_len,
|
||||
const unsigned char* classbytes,
|
||||
jint* new_class_data_len,
|
||||
unsigned char** new_classbytes);
|
||||
@@ -1,40 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <jni.h>
|
||||
#include <jvmti.h>
|
||||
#include <JuiceAgent/Logger.hpp>
|
||||
#include <JuiceAgent.hpp>
|
||||
#include <utils.hpp>
|
||||
#include <global.hpp>
|
||||
#include <algorithm>
|
||||
|
||||
// Generated by JuiceAgent-API
|
||||
#include <cn_xiaozhou233_juiceagent_api_JuiceAgent.h>
|
||||
|
||||
// Event callbacks
|
||||
// See https://docs.oracle.com/javase/8/docs/platform/jvmti/jvmti.html#ClassFileLoadHook
|
||||
void JNICALL ClassFileLoadHook(
|
||||
jvmtiEnv* jvmti_env,
|
||||
JNIEnv* jni_env,
|
||||
jclass class_being_redefined,
|
||||
jobject loader,
|
||||
const char* name,
|
||||
jobject protection_domain,
|
||||
jint class_data_len,
|
||||
const unsigned char* classbytes,
|
||||
jint* new_class_data_len,
|
||||
unsigned char** new_classbytes);
|
||||
|
||||
// See https://docs.oracle.com/javase/8/docs/platform/jvmti/jvmti.html#MethodEntry
|
||||
void JNICALL MethodEntry(jvmtiEnv *jvmti_env,
|
||||
JNIEnv* jni_env,
|
||||
jthread thread,
|
||||
jmethodID method);
|
||||
|
||||
// See https://docs.oracle.com/javase/8/docs/platform/jvmti/jvmti.html#MethodExit
|
||||
void JNICALL MethodExit(jvmtiEnv *jvmti_env,
|
||||
JNIEnv* jni_env,
|
||||
jthread thread,
|
||||
jmethodID method,
|
||||
jboolean was_popped_by_exception,
|
||||
jvalue return_value);
|
||||
@@ -1,37 +1,16 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
#include <JuiceAgent.hpp>
|
||||
#include <event/event_type.hpp>
|
||||
#include <services/base.hpp>
|
||||
#include <services/service_manager.hpp>
|
||||
|
||||
namespace JuiceAgent::services
|
||||
{
|
||||
static JuiceAgent::Agent& agent = JuiceAgent::Agent::instance();
|
||||
namespace JuiceAgent {
|
||||
namespace Services {
|
||||
|
||||
namespace Manager {
|
||||
void register_events();
|
||||
void init(const EventPreLoad&);
|
||||
void start(const EventLoaded&);
|
||||
void stop();
|
||||
}
|
||||
inline bool initializeAll() {
|
||||
auto& manager = ServiceManager::getInstance();
|
||||
ServiceRegistry::getInstance().instantiateAll(manager);
|
||||
return manager.initializeAll();
|
||||
}
|
||||
|
||||
namespace JarLoader
|
||||
{
|
||||
struct JarLoaderConfig {
|
||||
bool enabled = false;
|
||||
std::string injection_dir;
|
||||
std::string jar_path;
|
||||
std::string entry_class;
|
||||
std::string entry_method;
|
||||
};
|
||||
|
||||
void init();
|
||||
void start();
|
||||
} // namespace JarLoader
|
||||
|
||||
namespace Bytecode
|
||||
{
|
||||
void init();
|
||||
void start();
|
||||
}
|
||||
} // namespace JuiceAgent::services
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,56 @@
|
||||
#pragma once
|
||||
|
||||
#include <vector>
|
||||
#include <utility>
|
||||
#include <type_traits>
|
||||
#include <JuiceAgent/Logger.hpp>
|
||||
#include <eventbus.hpp>
|
||||
|
||||
namespace JuiceAgent {
|
||||
namespace Services {
|
||||
|
||||
class IService {
|
||||
public:
|
||||
virtual ~IService() = default;
|
||||
|
||||
virtual const char* name() const = 0;
|
||||
|
||||
virtual bool onInitialize() { return true; }
|
||||
|
||||
virtual void onShutdown() {}
|
||||
|
||||
protected:
|
||||
template <typename ServiceT, typename EventT>
|
||||
void listen(EventId id, void (ServiceT::*handler)(const EventT&)) {
|
||||
static_assert(std::is_base_of<IService, ServiceT>::value,
|
||||
"ServiceT must derive from IService");
|
||||
auto* self = static_cast<ServiceT*>(this);
|
||||
handles_.push_back({
|
||||
id,
|
||||
EventBus::getInstance().appendListener(
|
||||
id,
|
||||
[self, handler](const void* data) {
|
||||
if (data) {
|
||||
(self->*handler)(*static_cast<const EventT*>(data));
|
||||
}
|
||||
}
|
||||
)
|
||||
});
|
||||
}
|
||||
|
||||
// Remove all listeners registered by this service. Call it in onShutdown()
|
||||
// so no callback outlives the service instance.
|
||||
void unlistenAll() {
|
||||
auto& bus = EventBus::getInstance();
|
||||
for (auto& [id, handle] : handles_) {
|
||||
bus.removeListener(id, handle);
|
||||
}
|
||||
handles_.clear();
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<std::pair<EventId, EventBus::Dispatcher::Handle>> handles_;
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,131 @@
|
||||
#pragma once
|
||||
|
||||
#include <services/base.hpp>
|
||||
|
||||
#include <algorithm>
|
||||
#include <functional>
|
||||
#include <memory>
|
||||
#include <mutex>
|
||||
#include <vector>
|
||||
|
||||
namespace JuiceAgent {
|
||||
namespace Services {
|
||||
|
||||
class ServiceManager {
|
||||
public:
|
||||
static ServiceManager& getInstance() {
|
||||
static ServiceManager instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
ServiceManager(const ServiceManager&) = delete;
|
||||
ServiceManager& operator=(const ServiceManager&) = delete;
|
||||
|
||||
template <typename ServiceT, typename... Args>
|
||||
ServiceT* registerService(Args&&... args) {
|
||||
auto service = std::make_unique<ServiceT>(std::forward<Args>(args)...);
|
||||
ServiceT* raw = service.get();
|
||||
spdlog::debug("[ServiceManager] Registering service: {}", raw->name());
|
||||
services_.push_back(std::move(service));
|
||||
return raw;
|
||||
}
|
||||
|
||||
IService* createService(std::unique_ptr<IService> service) {
|
||||
IService* raw = service.get();
|
||||
spdlog::debug("[ServiceManager] Registering service: {}", raw->name());
|
||||
services_.push_back(std::move(service));
|
||||
return raw;
|
||||
}
|
||||
|
||||
template <typename ServiceT>
|
||||
ServiceT* getService() const {
|
||||
const std::type_info& target = typeid(ServiceT);
|
||||
for (const auto& s : services_) {
|
||||
if (typeid(*s) == target) {
|
||||
return static_cast<ServiceT*>(s.get());
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
bool initializeAll() {
|
||||
for (auto& s : services_) {
|
||||
spdlog::info("[ServiceManager] Initializing service: {}", s->name());
|
||||
if (!s->onInitialize()) {
|
||||
spdlog::error("[ServiceManager] Service '{}' failed to initialize", s->name());
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void shutdownAll() {
|
||||
for (auto it = services_.rbegin(); it != services_.rend(); ++it) {
|
||||
spdlog::info("[ServiceManager] Shutting down service: {}", (*it)->name());
|
||||
(*it)->onShutdown();
|
||||
}
|
||||
services_.clear();
|
||||
}
|
||||
|
||||
private:
|
||||
ServiceManager() = default;
|
||||
~ServiceManager() {
|
||||
shutdownAll();
|
||||
}
|
||||
|
||||
std::vector<std::unique_ptr<IService>> services_;
|
||||
};
|
||||
|
||||
// Static self-registration: each service's .cpp uses JUICEAGENT_REGISTER_SERVICE.
|
||||
class ServiceRegistry {
|
||||
public:
|
||||
using Factory = std::function<std::unique_ptr<IService>()>;
|
||||
|
||||
static ServiceRegistry& getInstance() {
|
||||
static ServiceRegistry instance;
|
||||
return instance;
|
||||
}
|
||||
|
||||
void addFactory(Factory factory) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
factories_.push_back(std::move(factory));
|
||||
}
|
||||
|
||||
void instantiateAll(ServiceManager& manager) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
for (auto& f : factories_) {
|
||||
manager.createService(f());
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
ServiceRegistry() = default;
|
||||
std::mutex mutex_;
|
||||
std::vector<Factory> factories_;
|
||||
};
|
||||
|
||||
template <typename ServiceT>
|
||||
class ServiceRegistrar {
|
||||
public:
|
||||
ServiceRegistrar() {
|
||||
ServiceRegistry::getInstance().addFactory(
|
||||
[]() -> std::unique_ptr<IService> {
|
||||
return std::make_unique<ServiceT>();
|
||||
}
|
||||
);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
#define JUICEAGENT_SERVICE_CONCAT_IMPL(a, b) a##b
|
||||
#define JUICEAGENT_SERVICE_CONCAT(a, b) JUICEAGENT_SERVICE_CONCAT_IMPL(a, b)
|
||||
|
||||
// Put at file scope in the service's .cpp:
|
||||
// JUICEAGENT_REGISTER_SERVICE(juiceagent::services::MyService)
|
||||
#define JUICEAGENT_REGISTER_SERVICE(ServiceT) \
|
||||
namespace { \
|
||||
const ::JuiceAgent::Services::ServiceRegistrar<ServiceT> \
|
||||
JUICEAGENT_SERVICE_CONCAT(_juiceagent_service_registrar_, __LINE__); \
|
||||
}
|
||||
@@ -3,11 +3,11 @@
|
||||
#include <JuiceAgent.hpp>
|
||||
|
||||
inline bool check_env(JuiceAgent::Agent& agent) {
|
||||
if (agent.get_jvm() == nullptr) {
|
||||
if (agent.getJavaVM() == nullptr) {
|
||||
spdlog::error("Failed to get JavaVM instance");
|
||||
return false;
|
||||
}
|
||||
if (agent.get_jvmti() == nullptr) {
|
||||
if (agent.getJVMTI() == nullptr) {
|
||||
spdlog::error("Failed to get JVMTI environment");
|
||||
return false;
|
||||
}
|
||||
|
||||
+185
-238
@@ -1,320 +1,267 @@
|
||||
#include <jni_impl.hpp>
|
||||
#include <jni_common.hpp>
|
||||
#include <global.hpp>
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <cstring>
|
||||
|
||||
// ============================
|
||||
// Get class bytecode (already captured)
|
||||
// ============================
|
||||
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytes
|
||||
(JNIEnv *env, jclass, jclass clazz) {
|
||||
using JuiceAgent::Services::BytecodeStore;
|
||||
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
if (!check_env(agent)) return nullptr;
|
||||
namespace {
|
||||
|
||||
char* signature = nullptr;
|
||||
if (agent.get_jvmti()->GetClassSignature(clazz, &signature, nullptr) != JVMTI_ERROR_NONE || !signature)
|
||||
return nullptr;
|
||||
|
||||
// Convert Lxxx; -> xxx
|
||||
std::string internalName(signature + 1, strlen(signature) - 2);
|
||||
agent.get_jvmti()->Deallocate(reinterpret_cast<unsigned char*>(signature));
|
||||
|
||||
// ============================
|
||||
// 1. Mark class for capture
|
||||
// ============================
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(classDataMutex);
|
||||
classToCapture.insert(internalName);
|
||||
}
|
||||
|
||||
// ============================
|
||||
// 2. Trigger class retransform
|
||||
// ============================
|
||||
jvmtiError err = agent.get_jvmti()->RetransformClasses(1, &clazz);
|
||||
if (err != JVMTI_ERROR_NONE) {
|
||||
spdlog::error("Retransform class failed: {}", static_cast<int>(err));
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// ============================
|
||||
// 3. Retrieve bytecode from cache
|
||||
// ============================
|
||||
ClassFileData data;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(classDataMutex);
|
||||
auto it = classFileDataMap.find(internalName);
|
||||
if (it != classFileDataMap.end()) {
|
||||
data = it->second;
|
||||
}
|
||||
}
|
||||
|
||||
if (data.bytecode.empty()) {
|
||||
spdlog::error("Failed to capture bytecode for class: {}", internalName);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
jbyteArray out = env->NewByteArray(static_cast<jsize>(data.bytecode.size()));
|
||||
if (!out || env->ExceptionCheck()) {
|
||||
env->ExceptionClear();
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
env->SetByteArrayRegion(out, 0, static_cast<jsize>(data.bytecode.size()), reinterpret_cast<const jbyte*>(data.bytecode.data()));
|
||||
return out;
|
||||
// Convert "Lcom/foo/Bar;" -> "com/foo/Bar"; returns empty on malformed input.
|
||||
std::string signatureToInternal(const char* signature) {
|
||||
if (!signature) return {};
|
||||
size_t len = std::strlen(signature);
|
||||
if (len < 2 || signature[0] != 'L' || signature[len - 1] != ';') return {};
|
||||
return std::string(signature + 1, len - 2);
|
||||
}
|
||||
|
||||
// ============================
|
||||
// Get class bytecode by class name
|
||||
// ============================
|
||||
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytesByName
|
||||
(JNIEnv *env, jclass loader_class, jstring name) {
|
||||
std::string dottedToInternal(std::string s) {
|
||||
std::replace(s.begin(), s.end(), '.', '/');
|
||||
return s;
|
||||
}
|
||||
|
||||
if (!name) return nullptr;
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
if (!check_env(agent)) return nullptr;
|
||||
|
||||
// ============================
|
||||
// 1. Convert jstring -> internal name
|
||||
// ============================
|
||||
const char* utf = env->GetStringUTFChars(name, nullptr);
|
||||
if (!utf) return nullptr;
|
||||
std::string internalName(utf);
|
||||
env->ReleaseStringUTFChars(name, utf);
|
||||
|
||||
// Convert dots to slashes: a.b.C -> a/b/C
|
||||
std::replace(internalName.begin(), internalName.end(), '.', '/');
|
||||
|
||||
// ============================
|
||||
// 2. Iterate loaded classes
|
||||
// ============================
|
||||
// Find a loaded class by internal name ("com/foo/Bar"). Returns a local ref,
|
||||
// or nullptr if not found. Caller must DeleteLocalRef when done.
|
||||
jclass findLoadedClass(jvmtiEnv* jvmti, JNIEnv* env, const std::string& internalName) {
|
||||
jint count = 0;
|
||||
jclass* classes = nullptr;
|
||||
jvmtiEnv* jvmti = agent.get_jvmti();
|
||||
|
||||
if (jvmti->GetLoadedClasses(&count, &classes) != JVMTI_ERROR_NONE || count == 0) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
jclass targetClass = nullptr;
|
||||
for (jint i = 0; i < count; i++) {
|
||||
char* signature = nullptr;
|
||||
if (jvmti->GetClassSignature(classes[i], &signature, nullptr) == JVMTI_ERROR_NONE && signature) {
|
||||
size_t len = strlen(signature);
|
||||
if (len > 2 && signature[0] == 'L' && signature[len - 1] == ';') {
|
||||
if (internalName == std::string_view(signature + 1, len - 2)) {
|
||||
targetClass = classes[i];
|
||||
jvmti->Deallocate(reinterpret_cast<unsigned char*>(signature));
|
||||
break;
|
||||
}
|
||||
}
|
||||
jvmti->Deallocate(reinterpret_cast<unsigned char*>(signature));
|
||||
jclass target = nullptr;
|
||||
for (jint i = 0; i < count; ++i) {
|
||||
char* sig = nullptr;
|
||||
if (jvmti->GetClassSignature(classes[i], &sig, nullptr) != JVMTI_ERROR_NONE || !sig) {
|
||||
continue;
|
||||
}
|
||||
std::string name = signatureToInternal(sig);
|
||||
jvmti->Deallocate(reinterpret_cast<unsigned char*>(sig));
|
||||
if (name == internalName) {
|
||||
target = static_cast<jclass>(env->NewLocalRef(classes[i]));
|
||||
break;
|
||||
}
|
||||
}
|
||||
jvmti->Deallocate(reinterpret_cast<unsigned char*>(classes));
|
||||
return target;
|
||||
}
|
||||
|
||||
if (classes) {
|
||||
jvmti->Deallocate(reinterpret_cast<unsigned char*>(classes));
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// getClassBytes(Class) -> byte[]
|
||||
// ---------------------------------------------------------------------------
|
||||
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytes
|
||||
(JNIEnv *env, jclass, jclass clazz) {
|
||||
|
||||
auto& agent = JuiceAgent::Agent::getInstance();
|
||||
if (!check_env(agent) || !clazz) return nullptr;
|
||||
|
||||
char* signature = nullptr;
|
||||
if (agent.getJVMTI()->GetClassSignature(clazz, &signature, nullptr) != JVMTI_ERROR_NONE || !signature) {
|
||||
return nullptr;
|
||||
}
|
||||
std::string internalName = signatureToInternal(signature);
|
||||
agent.getJVMTI()->Deallocate(reinterpret_cast<unsigned char*>(signature));
|
||||
if (internalName.empty()) return nullptr;
|
||||
|
||||
if (!targetClass) {
|
||||
spdlog::error("Class not loaded: {}", internalName);
|
||||
BytecodeStore::getInstance().requestCapture(internalName);
|
||||
|
||||
jvmtiError err = agent.getJVMTI()->RetransformClasses(1, &clazz);
|
||||
if (err != JVMTI_ERROR_NONE) {
|
||||
spdlog::error("[bytecode] RetransformClasses failed for {}: {}",
|
||||
internalName, static_cast<int>(err));
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// ============================
|
||||
// 3. Reuse getClassBytes logic
|
||||
// ============================
|
||||
return Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytes(env, loader_class, targetClass);
|
||||
auto captured = BytecodeStore::getInstance().takeCaptured(internalName);
|
||||
if (!captured || captured->bytecode.empty()) {
|
||||
spdlog::error("[bytecode] Failed to capture bytecode for class: {}", internalName);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
jbyteArray out = env->NewByteArray(static_cast<jsize>(captured->bytecode.size()));
|
||||
if (!out || env->ExceptionCheck()) {
|
||||
env->ExceptionClear();
|
||||
return nullptr;
|
||||
}
|
||||
env->SetByteArrayRegion(out, 0,
|
||||
static_cast<jsize>(captured->bytecode.size()),
|
||||
reinterpret_cast<const jbyte*>(captured->bytecode.data()));
|
||||
return out;
|
||||
}
|
||||
|
||||
// ============================
|
||||
// Redefine class using jclass
|
||||
// ============================
|
||||
// ---------------------------------------------------------------------------
|
||||
// getClassBytesByName(String) -> byte[]
|
||||
// ---------------------------------------------------------------------------
|
||||
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytesByName
|
||||
(JNIEnv *env, jclass, jstring name) {
|
||||
|
||||
if (!name) return nullptr;
|
||||
auto& agent = JuiceAgent::Agent::getInstance();
|
||||
if (!check_env(agent)) return nullptr;
|
||||
|
||||
const char* utf = env->GetStringUTFChars(name, nullptr);
|
||||
if (!utf) return nullptr;
|
||||
std::string internalName = dottedToInternal(utf);
|
||||
env->ReleaseStringUTFChars(name, utf);
|
||||
|
||||
jclass clazz = env->FindClass(internalName.c_str());
|
||||
if (!clazz) {
|
||||
if (env->ExceptionCheck()) env->ExceptionClear();
|
||||
spdlog::error("[bytecode] Class not found: {}", internalName);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
jbyteArray result = Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytes(env, nullptr, clazz);
|
||||
env->DeleteLocalRef(clazz);
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// redefineClass(Class, byte[], int) -> boolean
|
||||
// ---------------------------------------------------------------------------
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClass
|
||||
(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray class_bytes, jint class_bytes_len) {
|
||||
(JNIEnv *env, jclass, jclass clazz, jbyteArray class_bytes, jint class_bytes_len) {
|
||||
|
||||
// Get singleton agent instance
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
if (!check_env(agent))
|
||||
return JNI_FALSE;
|
||||
|
||||
// Get byte array elements
|
||||
jbyte* buf = env->GetByteArrayElements(class_bytes, nullptr);
|
||||
if (!buf) {
|
||||
spdlog::error("Cannot get class bytes");
|
||||
auto& agent = JuiceAgent::Agent::getInstance();
|
||||
if (!check_env(agent) || !clazz || !class_bytes || class_bytes_len <= 0) {
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
// Prepare JVMTI class definition
|
||||
jvmtiClassDefinition defs[1];
|
||||
defs[0].klass = clazz;
|
||||
defs[0].class_byte_count = class_bytes_len;
|
||||
defs[0].class_bytes = reinterpret_cast<const unsigned char*>(buf);
|
||||
// Validate the declared length against the actual array length to prevent
|
||||
// JVMTI from reading past the buffer.
|
||||
const jint array_len = env->GetArrayLength(class_bytes);
|
||||
if (class_bytes_len > array_len) {
|
||||
spdlog::error("[bytecode] class_bytes_len {} exceeds array length {}",
|
||||
class_bytes_len, array_len);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
// Redefine class via JVMTI
|
||||
jvmtiError result = agent.get_jvmti()->RedefineClasses(1, defs);
|
||||
jbyte* buf = env->GetByteArrayElements(class_bytes, nullptr);
|
||||
if (!buf) {
|
||||
spdlog::error("[bytecode] Cannot get class bytes");
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
// Release byte array (no need to copy back)
|
||||
jvmtiClassDefinition def{};
|
||||
def.klass = clazz;
|
||||
def.class_byte_count = class_bytes_len;
|
||||
def.class_bytes = reinterpret_cast<const unsigned char*>(buf);
|
||||
|
||||
jvmtiError result = agent.getJVMTI()->RedefineClasses(1, &def);
|
||||
env->ReleaseByteArrayElements(class_bytes, buf, JNI_ABORT);
|
||||
|
||||
if (result != JVMTI_ERROR_NONE) {
|
||||
spdlog::error("Redefine class failed: {}", static_cast<int>(result));
|
||||
spdlog::error("[bytecode] RedefineClasses failed: {}", static_cast<int>(result));
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
spdlog::debug("Class redefined successfully!");
|
||||
spdlog::debug("[bytecode] Class redefined successfully");
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Redefine class using its fully qualified name
|
||||
// Supports automatic '.' -> '/' conversion
|
||||
// ============================================
|
||||
// ---------------------------------------------------------------------------
|
||||
// redefineClassByName(String, byte[], int) -> boolean
|
||||
// ---------------------------------------------------------------------------
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClassByName
|
||||
(JNIEnv *env, jclass loader_class, jstring class_name, jbyteArray class_bytes, jint class_bytes_len) {
|
||||
(JNIEnv *env, jclass, jstring class_name, jbyteArray class_bytes, jint class_bytes_len) {
|
||||
|
||||
if (!class_name) return JNI_FALSE;
|
||||
auto& agent = JuiceAgent::Agent::getInstance();
|
||||
if (!check_env(agent)) return JNI_FALSE;
|
||||
|
||||
// Convert jstring to C string
|
||||
const char* cname = env->GetStringUTFChars(class_name, nullptr);
|
||||
if (!cname) {
|
||||
spdlog::error("Class name is NULL!");
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
// Copy and replace '.' with '/' for JVM internal class name
|
||||
std::string internal_name(cname);
|
||||
std::replace(internal_name.begin(), internal_name.end(), '.', '/');
|
||||
|
||||
// Release the original Java string
|
||||
if (!cname) return JNI_FALSE;
|
||||
std::string internalName = dottedToInternal(cname);
|
||||
env->ReleaseStringUTFChars(class_name, cname);
|
||||
|
||||
// Find class by internal name
|
||||
jclass clazz = env->FindClass(internal_name.c_str());
|
||||
// JNI FindClass uses the caller's classloader, which is unreliable from a
|
||||
// native agent thread. Use JVMTI to search loaded classes instead.
|
||||
jclass clazz = findLoadedClass(agent.getJVMTI(), env, internalName);
|
||||
if (!clazz) {
|
||||
spdlog::error("Cannot find class: {}", internal_name);
|
||||
spdlog::error("[bytecode] Cannot find loaded class: {}", internalName);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
// Call redefineClass with the found class
|
||||
return Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClass(
|
||||
env, loader_class, clazz, class_bytes, class_bytes_len
|
||||
);
|
||||
jboolean result = Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClass(
|
||||
env, nullptr, clazz, class_bytes, class_bytes_len);
|
||||
env->DeleteLocalRef(clazz);
|
||||
return result;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// retransformClass(Class, byte[], int) -> boolean
|
||||
//
|
||||
// Queues new bytecode for the next ClassFileLoadHook (which will write it
|
||||
// back via new_classbytes/new_class_data_len), then triggers RetransformClasses.
|
||||
// The `length` parameter is kept for JNI signature compatibility but the
|
||||
// actual length is read from the array.
|
||||
// ---------------------------------------------------------------------------
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClass
|
||||
(JNIEnv* env, jclass, jclass clazz, jbyteArray bytecodes, jint length) {
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
(JNIEnv* env, jclass, jclass clazz, jbyteArray bytecodes, jint /*length*/) {
|
||||
|
||||
// =========================
|
||||
// 1. Check environment & parameters
|
||||
// =========================
|
||||
if (!check_env(agent) || !clazz || !bytecodes) {
|
||||
auto& agent = JuiceAgent::Agent::getInstance();
|
||||
if (!check_env(agent) || !clazz || !bytecodes) return JNI_FALSE;
|
||||
|
||||
char* signature = nullptr;
|
||||
if (agent.getJVMTI()->GetClassSignature(clazz, &signature, nullptr) != JVMTI_ERROR_NONE || !signature) {
|
||||
return JNI_FALSE;
|
||||
}
|
||||
std::string internalName = signatureToInternal(signature);
|
||||
agent.getJVMTI()->Deallocate(reinterpret_cast<unsigned char*>(signature));
|
||||
if (internalName.empty()) return JNI_FALSE;
|
||||
|
||||
// =========================
|
||||
// 2. Get class internal name
|
||||
// =========================
|
||||
std::string nameDot = get_class_name(env, clazz);
|
||||
if (nameDot.empty()) {
|
||||
spdlog::error("Failed to get class name for retransform");
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
// Convert '.' to '/' for internal name
|
||||
for (auto& c : nameDot) if (c == '.') c = '/';
|
||||
|
||||
// =========================
|
||||
// 3. Extract bytecode from jbyteArray
|
||||
// =========================
|
||||
jbyte* bytes = env->GetByteArrayElements(bytecodes, nullptr);
|
||||
jint len = env->GetArrayLength(bytecodes);
|
||||
if (!bytes || len <= 0) {
|
||||
return JNI_FALSE;
|
||||
}
|
||||
if (len <= 0) return JNI_FALSE;
|
||||
|
||||
// =========================
|
||||
// 4. Cache new bytecode for ClassFileLoadHook
|
||||
// =========================
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(pendingRetransformMutex);
|
||||
pendingRetransform[nameDot].assign(bytes, bytes + len);
|
||||
}
|
||||
jbyte* bytes = env->GetByteArrayElements(bytecodes, nullptr);
|
||||
if (!bytes) return JNI_FALSE;
|
||||
|
||||
std::vector<unsigned char> newBytes(
|
||||
reinterpret_cast<const unsigned char*>(bytes),
|
||||
reinterpret_cast<const unsigned char*>(bytes) + len);
|
||||
env->ReleaseByteArrayElements(bytecodes, bytes, JNI_ABORT);
|
||||
|
||||
// =========================
|
||||
// 5. Trigger JVMTI retransform
|
||||
// =========================
|
||||
jclass classes[1] = { clazz };
|
||||
jvmtiError err = agent.get_jvmti()->RetransformClasses(1, classes);
|
||||
BytecodeStore::getInstance().requestPatch(internalName, std::move(newBytes));
|
||||
|
||||
jclass classes[1] = { clazz };
|
||||
jvmtiError err = agent.getJVMTI()->RetransformClasses(1, classes);
|
||||
if (err != JVMTI_ERROR_NONE) {
|
||||
spdlog::error("[retransformClass] failed: {} for {}", static_cast<int>(err), nameDot);
|
||||
spdlog::error("[bytecode] RetransformClasses failed for {}: {}",
|
||||
internalName, static_cast<int>(err));
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
spdlog::info("[retransformClass] OK: {} ({} bytes)", nameDot, len);
|
||||
spdlog::info("[bytecode] Retransform queued: {} ({} bytes)", internalName, len);
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// retransformClassByName(String, byte[], int) -> boolean
|
||||
// ---------------------------------------------------------------------------
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClassByName
|
||||
(JNIEnv* env, jclass, jstring className, jbyteArray bytecodes, jint length) {
|
||||
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
if (!className) return JNI_FALSE;
|
||||
auto& agent = JuiceAgent::Agent::getInstance();
|
||||
if (!check_env(agent)) return JNI_FALSE;
|
||||
|
||||
if (!check_env(agent) || !className || !bytecodes) {
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
// =========================
|
||||
// 1. Get UTF string from jstring
|
||||
// =========================
|
||||
const char* utf = env->GetStringUTFChars(className, nullptr);
|
||||
if (!utf) return JNI_FALSE;
|
||||
|
||||
std::string internalName(utf);
|
||||
std::string internalName = dottedToInternal(utf);
|
||||
env->ReleaseStringUTFChars(className, utf);
|
||||
|
||||
// Convert '.' to '/' for internal name
|
||||
for (auto& c : internalName) if (c == '.') c = '/';
|
||||
|
||||
// =========================
|
||||
// 2. Find loaded class by internal name (inline)
|
||||
// =========================
|
||||
jclass target = nullptr;
|
||||
{
|
||||
jint classCount = 0;
|
||||
jclass* loadedClasses = nullptr;
|
||||
|
||||
if (agent.get_jvmti()->GetLoadedClasses(&classCount, &loadedClasses) == JVMTI_ERROR_NONE && classCount > 0) {
|
||||
for (jint i = 0; i < classCount; ++i) {
|
||||
char* sig = nullptr;
|
||||
if (agent.get_jvmti()->GetClassSignature(loadedClasses[i], &sig, nullptr) == JVMTI_ERROR_NONE && sig) {
|
||||
// sig: "Lnet/minecraft/client/Minecraft;"
|
||||
if (sig[0] == 'L') {
|
||||
size_t len = strlen(sig);
|
||||
if (len > 2 && internalName == std::string(sig + 1, len - 2)) {
|
||||
target = loadedClasses[i];
|
||||
agent.get_jvmti()->Deallocate(reinterpret_cast<unsigned char*>(sig));
|
||||
break;
|
||||
}
|
||||
}
|
||||
agent.get_jvmti()->Deallocate(reinterpret_cast<unsigned char*>(sig));
|
||||
}
|
||||
}
|
||||
agent.get_jvmti()->Deallocate(reinterpret_cast<unsigned char*>(loadedClasses));
|
||||
}
|
||||
}
|
||||
|
||||
jclass target = findLoadedClass(agent.getJVMTI(), env, internalName);
|
||||
if (!target) {
|
||||
spdlog::error("[retransformClassByName] class not loaded: {}", internalName);
|
||||
spdlog::error("[bytecode] Class not loaded: {}", internalName);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
// =========================
|
||||
// 3. Delegate to retransformClass
|
||||
// =========================
|
||||
return Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClass(
|
||||
env, nullptr, target, bytecodes, length
|
||||
);
|
||||
}
|
||||
jboolean result = Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClass(
|
||||
env, nullptr, target, bytecodes, length);
|
||||
env->DeleteLocalRef(target);
|
||||
return result;
|
||||
}
|
||||
@@ -1,9 +1,9 @@
|
||||
#include <jni_impl.hpp>
|
||||
#include <jni_common.hpp>
|
||||
|
||||
// Add jar to bootstrap classloader search path
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToBootstrapClassLoaderSearch
|
||||
(JNIEnv *env, jclass, jstring jar_path) {
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
auto& agent = JuiceAgent::Agent::getInstance();
|
||||
|
||||
if (!check_env(agent))
|
||||
return JNI_FALSE;
|
||||
@@ -14,7 +14,7 @@ JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToBo
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
jvmtiError result = agent.get_jvmti()->AddToBootstrapClassLoaderSearch(j_jar_path);
|
||||
jvmtiError result = agent.getJVMTI()->AddToBootstrapClassLoaderSearch(j_jar_path);
|
||||
if (result != JVMTI_ERROR_NONE) {
|
||||
spdlog::error("Cannot AddToBootstrapClassLoaderSearch [result={}]", static_cast<int>(result));
|
||||
env->ReleaseStringUTFChars(jar_path, j_jar_path);
|
||||
@@ -24,12 +24,12 @@ JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToBo
|
||||
|
||||
env->ReleaseStringUTFChars(jar_path, j_jar_path);
|
||||
return JNI_TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
// Add jar to system classloader search path
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToSystemClassLoaderSearch
|
||||
(JNIEnv *env, jclass, jstring jar_path) {
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
auto& agent = JuiceAgent::Agent::getInstance();
|
||||
if (!check_env(agent))
|
||||
return JNI_FALSE;
|
||||
|
||||
@@ -39,7 +39,7 @@ JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToSy
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
jvmtiError result = agent.get_jvmti()->AddToSystemClassLoaderSearch(j_jar_path);
|
||||
jvmtiError result = agent.getJVMTI()->AddToSystemClassLoaderSearch(j_jar_path);
|
||||
if (result != JVMTI_ERROR_NONE) {
|
||||
spdlog::error("Cannot AddToSystemClassLoaderSearch [result={}]", static_cast<int>(result));
|
||||
env->ReleaseStringUTFChars(jar_path, j_jar_path);
|
||||
@@ -49,12 +49,12 @@ JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToSy
|
||||
|
||||
env->ReleaseStringUTFChars(jar_path, j_jar_path);
|
||||
return JNI_TRUE;
|
||||
}
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToClassLoader
|
||||
(JNIEnv *env, jclass, jstring jar_path, jobject target_classloader) {
|
||||
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
auto& agent = JuiceAgent::Agent::getInstance();
|
||||
|
||||
if (!check_env(agent))
|
||||
return JNI_FALSE;
|
||||
@@ -160,7 +160,7 @@ FALLBACK:
|
||||
if (!j_jar_path)
|
||||
return JNI_FALSE;
|
||||
|
||||
jvmtiError err = agent.get_jvmti()->AddToSystemClassLoaderSearch(j_jar_path);
|
||||
jvmtiError err = agent.getJVMTI()->AddToSystemClassLoaderSearch(j_jar_path);
|
||||
|
||||
env->ReleaseStringUTFChars(jar_path, j_jar_path);
|
||||
|
||||
@@ -175,7 +175,7 @@ FALLBACK:
|
||||
// Define class using target classloader
|
||||
JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_defineClass
|
||||
(JNIEnv *env, jclass, jobject target_classloader, jbyteArray bytes) {
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
auto& agent = JuiceAgent::Agent::getInstance();
|
||||
|
||||
if (!check_env(agent))
|
||||
return nullptr;
|
||||
@@ -190,18 +190,18 @@ JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_defineCla
|
||||
return nullptr;
|
||||
}
|
||||
return (jclass)classDefined;
|
||||
}
|
||||
}
|
||||
|
||||
JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getLoadedClasses
|
||||
(JNIEnv *env, jclass) {
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
auto& agent = JuiceAgent::Agent::getInstance();
|
||||
|
||||
if (!check_env(agent))
|
||||
return nullptr;
|
||||
|
||||
jint count = 0;
|
||||
jclass* classes = nullptr;
|
||||
jvmtiError err = agent.get_jvmti()->GetLoadedClasses(&count, &classes);
|
||||
jvmtiError err = agent.getJVMTI()->GetLoadedClasses(&count, &classes);
|
||||
if (err != JVMTI_ERROR_NONE) {
|
||||
spdlog::error("GetLoadedClasses failed: {}", static_cast<int>(err));
|
||||
return nullptr;
|
||||
@@ -214,13 +214,13 @@ JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_get
|
||||
env->SetObjectArrayElement(classesArray, i, classes[i]);
|
||||
}
|
||||
|
||||
agent.get_jvmti()->Deallocate((unsigned char*)classes);
|
||||
agent.getJVMTI()->Deallocate((unsigned char*)classes);
|
||||
return classesArray;
|
||||
}
|
||||
}
|
||||
|
||||
JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassByName
|
||||
(JNIEnv *env, jclass, jstring name) {
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
auto& agent = JuiceAgent::Agent::getInstance();
|
||||
|
||||
if (!check_env(agent))
|
||||
return nullptr;
|
||||
@@ -239,7 +239,7 @@ JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassB
|
||||
// Get all loaded classes
|
||||
jint count = 0;
|
||||
jclass* classes = nullptr;
|
||||
if (agent.get_jvmti()->GetLoadedClasses(&count, &classes) != JVMTI_ERROR_NONE || count == 0) {
|
||||
if (agent.getJVMTI()->GetLoadedClasses(&count, &classes) != JVMTI_ERROR_NONE || count == 0) {
|
||||
spdlog::error("GetLoadedClasses failed or no classes loaded");
|
||||
return nullptr;
|
||||
}
|
||||
@@ -248,7 +248,7 @@ JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassB
|
||||
|
||||
for (jint i = 0; i < count; i++) {
|
||||
char* signature = nullptr;
|
||||
if (agent.get_jvmti()->GetClassSignature(classes[i], &signature, nullptr) != JVMTI_ERROR_NONE || !signature)
|
||||
if (agent.getJVMTI()->GetClassSignature(classes[i], &signature, nullptr) != JVMTI_ERROR_NONE || !signature)
|
||||
continue;
|
||||
|
||||
size_t sig_len = strlen(signature);
|
||||
@@ -256,15 +256,15 @@ JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassB
|
||||
internal_name.size() == sig_len - 2 &&
|
||||
strncmp(signature + 1, internal_name.c_str(), sig_len - 2) == 0) {
|
||||
result = classes[i];
|
||||
agent.get_jvmti()->Deallocate((unsigned char*)signature);
|
||||
agent.getJVMTI()->Deallocate((unsigned char*)signature);
|
||||
break;
|
||||
}
|
||||
|
||||
agent.get_jvmti()->Deallocate((unsigned char*)signature);
|
||||
agent.getJVMTI()->Deallocate((unsigned char*)signature);
|
||||
}
|
||||
|
||||
if (classes) {
|
||||
agent.get_jvmti()->Deallocate((unsigned char*)classes);
|
||||
agent.getJVMTI()->Deallocate((unsigned char*)classes);
|
||||
}
|
||||
|
||||
if (!result) {
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
#include <jni_impl.hpp>
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
#include <jni_common.hpp>
|
||||
#include <global.hpp>
|
||||
|
||||
static const char* remap_class = "cn/xiaozhou233/juiceremapper/remapper/Remap";
|
||||
static const char* remap_method = "remap";
|
||||
static const char* remap_sig = "(Ljava/lang/String;[B)[B";
|
||||
|
||||
namespace {
|
||||
|
||||
// Resolve and cache the static class/method declarations.
|
||||
// Returns true on success. On failure, caches are left null so the
|
||||
// next call retries the lookup.
|
||||
bool cacheRemapDeclarations(JNIEnv* env) {
|
||||
auto& remapper = JuiceAgent::Services::Remapper::getInstance();
|
||||
|
||||
if (remapper.getRemapClass() && remapper.getRemapMethodId()) {
|
||||
return true;
|
||||
}
|
||||
|
||||
jclass localClass = env->FindClass(remap_class);
|
||||
if (!localClass) {
|
||||
if (env->ExceptionCheck()) env->ExceptionClear();
|
||||
spdlog::error("[JuiceRemapper JNI] FindClass failed: {}", remap_class);
|
||||
return false;
|
||||
}
|
||||
|
||||
jclass globalClass = static_cast<jclass>(env->NewGlobalRef(localClass));
|
||||
env->DeleteLocalRef(localClass);
|
||||
if (!globalClass) {
|
||||
spdlog::error("[JuiceRemapper JNI] NewGlobalRef failed: {}", remap_class);
|
||||
return false;
|
||||
}
|
||||
|
||||
jmethodID methodId = env->GetStaticMethodID(globalClass, remap_method, remap_sig);
|
||||
if (!methodId) {
|
||||
if (env->ExceptionCheck()) env->ExceptionClear();
|
||||
env->DeleteGlobalRef(globalClass);
|
||||
spdlog::error("[JuiceRemapper JNI] GetStaticMethodID failed: {}.{}",
|
||||
remap_class, remap_method);
|
||||
return false;
|
||||
}
|
||||
|
||||
remapper.setRemapClass(globalClass);
|
||||
remapper.setRemapMethodId(methodId);
|
||||
spdlog::debug("[JuiceRemapper JNI] Cached static declarations: {}.{}",
|
||||
remap_class, remap_method);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_initNative
|
||||
(JNIEnv *env, jclass) {
|
||||
// TODO: Init
|
||||
|
||||
auto& remapper = JuiceAgent::Services::Remapper::getInstance();
|
||||
if (remapper.isInit()) {
|
||||
spdlog::warn("JuiceRemapper::initNative: Remapper is already initialized");
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
if (!cacheRemapDeclarations(env)) {
|
||||
spdlog::error("JuiceRemapper::initNative: failed to cache static declarations");
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
remapper.setInit(true);
|
||||
|
||||
spdlog::info("[JuiceRemapper JNI] JuiceRemapper is initialized.");
|
||||
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_addInclude
|
||||
(JNIEnv *env, jclass, jstring name) {
|
||||
if (!name) return JNI_FALSE;
|
||||
|
||||
const char* utf = env->GetStringUTFChars(name, nullptr);
|
||||
if (!utf) return JNI_FALSE;
|
||||
std::string s(utf);
|
||||
env->ReleaseStringUTFChars(name, utf);
|
||||
|
||||
JuiceAgent::Services::Remapper::getInstance().addInclude(std::move(s));
|
||||
spdlog::debug("[JuiceRemapper JNI] addInclude");
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_addExclude
|
||||
(JNIEnv *env, jclass, jstring name) {
|
||||
if (!name) return JNI_FALSE;
|
||||
|
||||
const char* utf = env->GetStringUTFChars(name, nullptr);
|
||||
if (!utf) return JNI_FALSE;
|
||||
std::string s(utf);
|
||||
env->ReleaseStringUTFChars(name, utf);
|
||||
|
||||
JuiceAgent::Services::Remapper::getInstance().addExclude(std::move(s));
|
||||
spdlog::debug("[JuiceRemapper JNI] addExclude");
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_removeInclude
|
||||
(JNIEnv *env, jclass, jstring name) {
|
||||
if (!name) return JNI_FALSE;
|
||||
|
||||
const char* utf = env->GetStringUTFChars(name, nullptr);
|
||||
if (!utf) return JNI_FALSE;
|
||||
std::string s(utf);
|
||||
env->ReleaseStringUTFChars(name, utf);
|
||||
|
||||
JuiceAgent::Services::Remapper::getInstance().removeInclude(s);
|
||||
spdlog::debug("[JuiceRemapper JNI] removeInclude");
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_removeExclude
|
||||
(JNIEnv *env, jclass, jstring name){
|
||||
if (!name) return JNI_FALSE;
|
||||
|
||||
const char* utf = env->GetStringUTFChars(name, nullptr);
|
||||
if (!utf) return JNI_FALSE;
|
||||
std::string s(utf);
|
||||
env->ReleaseStringUTFChars(name, utf);
|
||||
|
||||
JuiceAgent::Services::Remapper::getInstance().removeExclude(s);
|
||||
spdlog::debug("[JuiceRemapper JNI] removeExclude");
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_clearIncludes
|
||||
(JNIEnv *, jclass) {
|
||||
JuiceAgent::Services::Remapper::getInstance().clearIncludes();
|
||||
spdlog::debug("[JuiceRemapper JNI] clearIncludes");
|
||||
}
|
||||
|
||||
JNIEXPORT void JNICALL Java_cn_xiaozhou233_juiceremapper_JuiceRemapper_clearExcludes
|
||||
(JNIEnv *, jclass) {
|
||||
JuiceAgent::Services::Remapper::getInstance().clearExcludes();
|
||||
spdlog::debug("[JuiceRemapper JNI] clearExcludes");
|
||||
}
|
||||
@@ -1,64 +1,82 @@
|
||||
#include <services.hpp>
|
||||
#include <jni_impl.hpp>
|
||||
#include <services/base.hpp>
|
||||
#include <services/service_manager.hpp>
|
||||
#include <event/event_type.hpp>
|
||||
#include <JuiceAgent/Logger.hpp>
|
||||
#include <global.hpp>
|
||||
|
||||
namespace JuiceAgent::services::Bytecode {
|
||||
void capture_bytecodes(const EventClassFileLoadHook& e) {
|
||||
std::lock_guard<std::mutex> lock(classDataMutex);
|
||||
#include <cstring>
|
||||
|
||||
if (!classToCapture.contains(e.name) || classFileDataMap.contains(e.name)) {
|
||||
return;
|
||||
}
|
||||
namespace JuiceAgent {
|
||||
namespace Services {
|
||||
|
||||
ClassFileData data;
|
||||
data.classname = e.name;
|
||||
data.bytecode.assign(e.classbytes, e.classbytes + e.class_data_len);
|
||||
class BytecodeService : public IService {
|
||||
public:
|
||||
const char* name() const override { return "BytecodeService"; }
|
||||
|
||||
if (e.jni_env) {
|
||||
if (e.class_being_redefined) data.clazz = static_cast<jclass>(e.jni_env->NewGlobalRef(e.class_being_redefined));
|
||||
if (e.loader) data.classloader = e.jni_env->NewGlobalRef(e.loader);
|
||||
if (e.protection_domain) data.protection_domain = e.jni_env->NewGlobalRef(e.protection_domain);
|
||||
}
|
||||
bool onInitialize() override {
|
||||
listen<BytecodeService, EventClassFileLoadHook>(
|
||||
EventId::ClassFileLoadHook,
|
||||
&BytecodeService::captureBytecodes
|
||||
);
|
||||
|
||||
classFileDataMap[e.name] = std::move(data);
|
||||
classToCapture.erase(e.name);
|
||||
listen<BytecodeService, EventClassFileLoadHook>(
|
||||
EventId::ClassFileLoadHook,
|
||||
&BytecodeService::patchBytecodes
|
||||
);
|
||||
|
||||
spdlog::info("Captured class: {} (length: {})", e.name, e.class_data_len);
|
||||
spdlog::info("[BytecodeService] Initialized");
|
||||
return true;
|
||||
}
|
||||
|
||||
void patch_bytecodes(const EventClassFileLoadHook& e) {
|
||||
std::lock_guard<std::mutex> lock(pendingRetransformMutex);
|
||||
void onShutdown() override {
|
||||
unlistenAll();
|
||||
spdlog::info("[BytecodeService] Shutdown");
|
||||
}
|
||||
|
||||
auto it = pendingRetransform.find(e.name);
|
||||
if (it == pendingRetransform.end()) {
|
||||
private:
|
||||
void captureBytecodes(const EventClassFileLoadHook& e) {
|
||||
if (!e.name) return;
|
||||
|
||||
const std::size_t len = BytecodeStore::getInstance()
|
||||
.tryCapture(e.name, e.classbytes, e.class_data_len);
|
||||
|
||||
if (len > 0) {
|
||||
spdlog::info("[BytecodeService] Captured class: {} (length: {})",
|
||||
e.name, len);
|
||||
}
|
||||
}
|
||||
|
||||
void patchBytecodes(const EventClassFileLoadHook& e) {
|
||||
if (!e.name || !e.jvmti_env ||
|
||||
!e.new_class_data_len || !e.new_classbytes) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto& bytes = it->second;
|
||||
const jint new_len = static_cast<jint>(bytes.size());
|
||||
std::vector<unsigned char> bytes;
|
||||
if (!BytecodeStore::getInstance().takePatch(e.name, bytes) || bytes.empty()) {
|
||||
return;
|
||||
}
|
||||
|
||||
const jlong new_len = static_cast<jlong>(bytes.size());
|
||||
unsigned char* new_buf = nullptr;
|
||||
if (e.jvmti_env->Allocate(bytes.size(), &new_buf) != JVMTI_ERROR_NONE) {
|
||||
spdlog::error("Failed to allocate buffer for retransform: {}", e.name);
|
||||
if (e.jvmti_env->Allocate(new_len, &new_buf) != JVMTI_ERROR_NONE) {
|
||||
// Put bytes back so a future hook can retry instead of losing the patch.
|
||||
BytecodeStore::getInstance().putBackPatch(e.name, std::move(bytes));
|
||||
spdlog::error("[BytecodeService] Failed to allocate buffer for: {}", e.name);
|
||||
return;
|
||||
}
|
||||
|
||||
memcpy(new_buf, bytes.data(), bytes.size());
|
||||
std::memcpy(new_buf, bytes.data(), bytes.size());
|
||||
|
||||
*e.new_class_data_len = new_len;
|
||||
*e.new_class_data_len = static_cast<jint>(new_len);
|
||||
*e.new_classbytes = new_buf;
|
||||
|
||||
pendingRetransform.erase(it);
|
||||
|
||||
spdlog::info("Retransformed: {} (new length: {})", e.name, new_len);
|
||||
spdlog::info("[BytecodeService] Patched class: {} (new length: {})",
|
||||
e.name, new_len);
|
||||
}
|
||||
};
|
||||
|
||||
void init() {
|
||||
agent.get_eventbus().subscribe<EventClassFileLoadHook>(capture_bytecodes);
|
||||
agent.get_eventbus().subscribe<EventClassFileLoadHook>(patch_bytecodes);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void start() {
|
||||
|
||||
}
|
||||
|
||||
}
|
||||
JUICEAGENT_REGISTER_SERVICE(::JuiceAgent::Services::BytecodeService)
|
||||
@@ -1,68 +1,96 @@
|
||||
#include <services.hpp>
|
||||
#include <services/base.hpp>
|
||||
#include <services/service_manager.hpp>
|
||||
#include <event/event_type.hpp>
|
||||
#include <JuiceAgent/Logger.hpp>
|
||||
#include <JuiceAgent/Utils.hpp>
|
||||
|
||||
namespace JuiceAgent::services::JarLoader {
|
||||
static JarLoaderConfig config;
|
||||
namespace JuiceAgent {
|
||||
namespace Services {
|
||||
|
||||
static const char* MODULE_CLASS = "cn/xiaozhou233/juiceagent/api/modules/JarLoader";
|
||||
static const char* MODULE_METHOD = "loadJar";
|
||||
class JarLoaderService : public IService {
|
||||
public:
|
||||
const char* name() const override { return "JarLoaderService"; }
|
||||
|
||||
void init() {
|
||||
auto& cfg = agent.get_config();
|
||||
|
||||
config.enabled = cfg.get<bool>(
|
||||
"JuiceAgent.Modules.JarLoader.Enabled",
|
||||
false
|
||||
bool onInitialize() override {
|
||||
listen<JarLoaderService, EventLoaded>(
|
||||
EventId::Loaded,
|
||||
&JarLoaderService::onLoaded
|
||||
);
|
||||
|
||||
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
|
||||
);
|
||||
|
||||
spdlog::info("JarLoaderService initialized");
|
||||
spdlog::info("[JarLoaderService] Initialized");
|
||||
return true;
|
||||
}
|
||||
|
||||
void start() {
|
||||
if (!config.enabled) {
|
||||
void onShutdown() override {
|
||||
unlistenAll();
|
||||
spdlog::info("[JarLoaderService] Shutdown");
|
||||
}
|
||||
|
||||
private:
|
||||
static constexpr const char* MODULE_CLASS =
|
||||
"cn/xiaozhou233/juiceagent/api/modules/JarLoader";
|
||||
static constexpr const char* MODULE_METHOD = "loadJar";
|
||||
|
||||
void onLoaded(const EventLoaded& /*event*/) {
|
||||
auto& agent = Agent::getInstance();
|
||||
auto& cfg = agent.getConfig();
|
||||
|
||||
const bool enabled = cfg.get<bool>(
|
||||
"JuiceAgent.Modules.JarLoader.Enabled", false);
|
||||
|
||||
if (!enabled) {
|
||||
spdlog::info("[JarLoaderService] Disabled by config");
|
||||
return;
|
||||
}
|
||||
|
||||
const std::string injection_dir = cfg.get<std::string>(
|
||||
"JuiceAgent.Modules.JarLoader.InjectionDir",
|
||||
(cfg.runtime_dir() / "injection").string(),
|
||||
true);
|
||||
|
||||
const std::string jar_path = cfg.get<std::string>(
|
||||
"JuiceAgent.Modules.JarLoader.JarPath",
|
||||
(cfg.runtime_dir() / "Entry.jar").string(),
|
||||
true);
|
||||
|
||||
const std::string entry_class = cfg.get<std::string>(
|
||||
"JuiceAgent.Modules.JarLoader.EntryClass",
|
||||
"Example.Main",
|
||||
false);
|
||||
|
||||
const std::string entry_method = cfg.get<std::string>(
|
||||
"JuiceAgent.Modules.JarLoader.EntryMethod",
|
||||
"start",
|
||||
false);
|
||||
|
||||
JuiceAgent::Utils::Serializer ser;
|
||||
ser.add_kv("InjectionDir", injection_dir);
|
||||
ser.add_kv("JarPath", jar_path);
|
||||
ser.add_kv("EntryClass", entry_class);
|
||||
ser.add_kv("EntryMethod", entry_method);
|
||||
|
||||
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);
|
||||
const std::string data = ser.serialize();
|
||||
spdlog::debug("[JarLoaderService] Serialized config: {}", data);
|
||||
|
||||
auto data = ser.serialize();
|
||||
JNIEnv* env = agent.getJNIEnv();
|
||||
if (!env) {
|
||||
spdlog::error("[JarLoaderService] JNIEnv is null, cannot load jar");
|
||||
return;
|
||||
}
|
||||
|
||||
JuiceAgent::Utils::call_java_impl(
|
||||
agent.get_env(),
|
||||
MODULE_CLASS,
|
||||
MODULE_METHOD,
|
||||
data.c_str()
|
||||
);
|
||||
bool result = JuiceAgent::Utils::call_java_impl(
|
||||
env, MODULE_CLASS, MODULE_METHOD, data.c_str());
|
||||
|
||||
spdlog::info("JarLoader start");
|
||||
return;
|
||||
if (!result) {
|
||||
spdlog::error("[JarLoaderService] Failed to load jar: {}", jar_path);
|
||||
return;
|
||||
}
|
||||
|
||||
spdlog::info("[JarLoaderService] Loaded jar: {}", jar_path);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
JUICEAGENT_REGISTER_SERVICE(::JuiceAgent::Services::JarLoaderService)
|
||||
@@ -0,0 +1,151 @@
|
||||
#include <services/base.hpp>
|
||||
#include <services/service_manager.hpp>
|
||||
#include <event/event_type.hpp>
|
||||
#include <JuiceAgent/Logger.hpp>
|
||||
#include <JuiceAgent/Utils.hpp>
|
||||
#include <global.hpp>
|
||||
|
||||
#include <string_view>
|
||||
#include <cstring>
|
||||
|
||||
namespace JuiceAgent {
|
||||
namespace Services {
|
||||
|
||||
class JuiceRemapperService : public IService {
|
||||
public:
|
||||
const char* name() const override { return "JuiceRemapperService"; }
|
||||
|
||||
bool onInitialize() override {
|
||||
listen<JuiceRemapperService, EventLoaded>(
|
||||
EventId::Loaded,
|
||||
&JuiceRemapperService::onLoaded
|
||||
);
|
||||
|
||||
listen<JuiceRemapperService, EventClassFileLoadHook>(
|
||||
EventId::ClassFileLoadHook,
|
||||
&JuiceRemapperService::onClassFileLoadHook
|
||||
);
|
||||
|
||||
spdlog::debug("[JuiceRemapperService] Initialized");
|
||||
return true;
|
||||
}
|
||||
|
||||
void onShutdown() override {
|
||||
unlistenAll();
|
||||
spdlog::debug("[JuiceRemapperService] Shutdown");
|
||||
}
|
||||
|
||||
private:
|
||||
void onLoaded(const EventLoaded& /*event*/) {
|
||||
auto& agent = Agent::getInstance();
|
||||
auto& cfg = agent.getConfig();
|
||||
|
||||
const bool enabled = cfg.get<bool>(
|
||||
"JuiceAgent.Modules.JuiceRemapper.Enabled", false);
|
||||
|
||||
if (!enabled) {
|
||||
spdlog::debug("[JuiceRemapperService] Disabled by config");
|
||||
return;
|
||||
}
|
||||
|
||||
spdlog::debug("[JuiceRemapperService] Enabled. Waiting for addInclude to start remapping");
|
||||
}
|
||||
|
||||
void onClassFileLoadHook(const EventClassFileLoadHook& e) {
|
||||
if (!e.name || !e.jni_env || !e.jvmti_env ||
|
||||
!e.classbytes || e.class_data_len <= 0) {
|
||||
return;
|
||||
}
|
||||
|
||||
auto& remapper = JuiceAgent::Services::Remapper::getInstance();
|
||||
if (!remapper.isInit())
|
||||
return;
|
||||
|
||||
if (std::string_view(e.name).starts_with("cn/xiaozhou233/juiceremapper/"))
|
||||
return;
|
||||
|
||||
// Include/Exclude filter check
|
||||
if (!remapper.shouldRemap(e.name)) {
|
||||
spdlog::trace("[JuiceRemapperService] Skipped by filter: {}", e.name);
|
||||
return;
|
||||
}
|
||||
|
||||
jclass remapClass = remapper.getRemapClass();
|
||||
jmethodID remapMethod = remapper.getRemapMethodId();
|
||||
if (!remapClass || !remapMethod) {
|
||||
spdlog::error("[JuiceRemapperService] Remap declarations not cached");
|
||||
return;
|
||||
}
|
||||
|
||||
JNIEnv* env = e.jni_env;
|
||||
|
||||
// className: const char* -> jstring
|
||||
jstring jClassName = env->NewStringUTF(e.name);
|
||||
if (!jClassName) {
|
||||
if (env->ExceptionCheck()) env->ExceptionClear();
|
||||
spdlog::error("[JuiceRemapperService] Failed to create className jstring");
|
||||
return;
|
||||
}
|
||||
|
||||
// classBytes: const unsigned char* -> jbyteArray
|
||||
jbyteArray jClassBytes = env->NewByteArray(e.class_data_len);
|
||||
if (!jClassBytes) {
|
||||
if (env->ExceptionCheck()) env->ExceptionClear();
|
||||
env->DeleteLocalRef(jClassName);
|
||||
spdlog::error("[JuiceRemapperService] Failed to create classBytes jbyteArray");
|
||||
return;
|
||||
}
|
||||
env->SetByteArrayRegion(
|
||||
jClassBytes, 0, e.class_data_len,
|
||||
reinterpret_cast<const jbyte*>(e.classbytes));
|
||||
if (env->ExceptionCheck()) {
|
||||
env->ExceptionClear();
|
||||
env->DeleteLocalRef(jClassName);
|
||||
env->DeleteLocalRef(jClassBytes);
|
||||
spdlog::error("[JuiceRemapperService] Failed to fill classBytes");
|
||||
return;
|
||||
}
|
||||
|
||||
// Call static byte[] Remap.remap(String, byte[])
|
||||
jbyteArray jResult = static_cast<jbyteArray>(
|
||||
env->CallStaticObjectMethod(remapClass, remapMethod, jClassName, jClassBytes));
|
||||
if (env->ExceptionCheck() || !jResult) {
|
||||
env->ExceptionClear();
|
||||
env->DeleteLocalRef(jClassName);
|
||||
env->DeleteLocalRef(jClassBytes);
|
||||
spdlog::warn("[JuiceRemapperService] Remap returned null/exception for: {}", e.name);
|
||||
return;
|
||||
}
|
||||
|
||||
const jsize newLen = env->GetArrayLength(jResult);
|
||||
jbyte* newBytes = env->GetByteArrayElements(jResult, nullptr);
|
||||
if (!newBytes) {
|
||||
env->DeleteLocalRef(jClassName);
|
||||
env->DeleteLocalRef(jClassBytes);
|
||||
env->DeleteLocalRef(jResult);
|
||||
return;
|
||||
}
|
||||
|
||||
// Write remapped bytes back to the JVMTI callback
|
||||
unsigned char* newBuf = nullptr;
|
||||
if (e.jvmti_env->Allocate(newLen, &newBuf) == JVMTI_ERROR_NONE) {
|
||||
std::memcpy(newBuf, newBytes, newLen);
|
||||
*e.new_class_data_len = newLen;
|
||||
*e.new_classbytes = newBuf;
|
||||
spdlog::info("[JuiceRemapperService] Remapped: {} ({} -> {} bytes)",
|
||||
e.name, e.class_data_len, newLen);
|
||||
} else {
|
||||
spdlog::error("[JuiceRemapperService] Failed to allocate buffer for: {}", e.name);
|
||||
}
|
||||
|
||||
env->ReleaseByteArrayElements(jResult, newBytes, JNI_ABORT);
|
||||
env->DeleteLocalRef(jClassName);
|
||||
env->DeleteLocalRef(jClassBytes);
|
||||
env->DeleteLocalRef(jResult);
|
||||
}
|
||||
};
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
JUICEAGENT_REGISTER_SERVICE(::JuiceAgent::Services::JuiceRemapperService)
|
||||
@@ -1,38 +0,0 @@
|
||||
#include <services.hpp>
|
||||
#include <event/event_type.hpp>
|
||||
|
||||
namespace JuiceAgent::services::Manager {
|
||||
void register_events() {
|
||||
// PreLoad
|
||||
agent.get_eventbus().subscribe<EventPreLoad>(init);
|
||||
|
||||
// Loaded
|
||||
agent.get_eventbus().subscribe<EventLoaded>(start);
|
||||
|
||||
// TODO: Stopped
|
||||
|
||||
spdlog::info("Services Manager registered events");
|
||||
}
|
||||
|
||||
void init(const EventPreLoad& event) {
|
||||
spdlog::info("Initializing services");
|
||||
// JarLoader
|
||||
JuiceAgent::services::JarLoader::init();
|
||||
|
||||
// Bytecode
|
||||
JuiceAgent::services::Bytecode::init();
|
||||
}
|
||||
|
||||
void start(const EventLoaded& event) {
|
||||
spdlog::info("Starting services");
|
||||
// JarLoader
|
||||
JuiceAgent::services::JarLoader::start();
|
||||
|
||||
// Bytecode
|
||||
JuiceAgent::services::Bytecode::start();
|
||||
}
|
||||
|
||||
void stop() {
|
||||
|
||||
}
|
||||
}
|
||||
@@ -5,6 +5,8 @@
|
||||
#include <jni.h>
|
||||
#include <ReflectiveDLLInjection/LoadLibraryR.h>
|
||||
|
||||
#include <JuiceAgent/cn_xiaozhou233_juiceagent_injector_Injector.h>
|
||||
|
||||
#define BREAK_WITH_ERROR(e) { printf("[-] %s. Error=%lu\n", e, GetLastError()); break; }
|
||||
|
||||
__declspec(dllexport)
|
||||
@@ -120,6 +122,8 @@ static jboolean jni_inject(JNIEnv* env, jint pid, jstring path, const char* conf
|
||||
strncpy(params, config_dir, MAX_PATH - 1);
|
||||
params[MAX_PATH - 1] = '\0';
|
||||
inject_params = params;
|
||||
} else {
|
||||
inject_params = params;
|
||||
}
|
||||
|
||||
int ret = inject(pid, dll_path, inject_params);
|
||||
@@ -131,9 +135,8 @@ static jboolean jni_inject(JNIEnv* env, jint pid, jstring path, const char* conf
|
||||
/*
|
||||
* JNI Function: inject(int pid, String path)
|
||||
*/
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorNative_inject__ILjava_lang_String_2
|
||||
(JNIEnv *env, jobject obj, jint pid, jstring path) {
|
||||
(void)obj;
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_injector_Injector_inject__ILjava_lang_String_2
|
||||
(JNIEnv *env, jclass, jint pid, jstring path) {
|
||||
return jni_inject(env, pid, path, NULL);
|
||||
}
|
||||
|
||||
@@ -141,9 +144,8 @@ JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorNativ
|
||||
* JNI Function: inject(int pid, String path, String configDir)
|
||||
* configDir: path of config file (toml)
|
||||
*/
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorNative_inject__ILjava_lang_String_2Ljava_lang_String_2
|
||||
(JNIEnv *env, jobject obj, jint pid, jstring path, jstring configDir) {
|
||||
(void)obj;
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_injector_Injector_inject__ILjava_lang_String_2Ljava_lang_String_2
|
||||
(JNIEnv *env, jclass, jint pid, jstring path, jstring configDir) {
|
||||
const char* config_dir = (*env)->GetStringUTFChars(env, configDir, NULL);
|
||||
jboolean result = jni_inject(env, pid, path, config_dir);
|
||||
(*env)->ReleaseStringUTFChars(env, configDir, config_dir);
|
||||
@@ -182,7 +184,7 @@ BOOL CALLBACK EnumWindowsProc(HWND hwnd, LPARAM lParam) {
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorNative_findWindowsByTitle
|
||||
JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceagent_injector_Injector_findWindowsByTitle
|
||||
(JNIEnv *env, jclass clazz, jstring keyword) {
|
||||
(void)clazz;
|
||||
const jchar *input = (*env)->GetStringChars(env, keyword, NULL);
|
||||
@@ -193,7 +195,7 @@ JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorN
|
||||
g_count = 0;
|
||||
EnumWindows(EnumWindowsProc, 0);
|
||||
|
||||
jclass infoClass = (*env)->FindClass(env, "cn/xiaozhou233/juiceagent/injector/InjectorNative$WindowInfo");
|
||||
jclass infoClass = (*env)->FindClass(env, "cn/xiaozhou233/juiceagent/injector/WindowInfo");
|
||||
if (!infoClass) return NULL;
|
||||
|
||||
jmethodID ctor = (*env)->GetMethodID(env, infoClass, "<init>", "(Ljava/lang/String;I)V");
|
||||
|
||||
@@ -1,14 +1,14 @@
|
||||
file(GLOB_RECURSE loader_sources
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/common/*.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/common/*.c
|
||||
file(GLOB_RECURSE loader_sources CONFIGURE_DEPENDS
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/core/*.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/core/*.c
|
||||
)
|
||||
|
||||
if (WIN32)
|
||||
message(STATUS "Detected System: Windows")
|
||||
|
||||
file(GLOB_RECURSE windows_sources
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/plantform/windows/*.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/plantform/windows/*.c
|
||||
file(GLOB_RECURSE windows_sources CONFIGURE_DEPENDS
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/windows/*.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/windows/*.c
|
||||
)
|
||||
|
||||
list(APPEND loader_sources ${windows_sources})
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
#include <Loader.hpp>
|
||||
#include <JvmAttach.hpp>
|
||||
#include <JuiceAgent/Logger.hpp>
|
||||
|
||||
void JuiceAgent::Loader::entrypoint(const char* path) {
|
||||
// Attach to the JVM
|
||||
JuiceAgent::Loader::JvmAttach jvmAttach;
|
||||
|
||||
if(!jvmAttach.attach()) {
|
||||
spdlog::error("Failed to attach to JVM!");
|
||||
return;
|
||||
}
|
||||
|
||||
// Get JNIEnv
|
||||
JNIEnv* env = jvmAttach.get_env();
|
||||
if(!env) {
|
||||
spdlog::error("Failed to get JNIEnv!");
|
||||
return;
|
||||
}
|
||||
|
||||
// Get JVMTI environment
|
||||
jvmtiEnv* jvmti = jvmAttach.get_jvmti();
|
||||
if(!jvmti) {
|
||||
spdlog::error("Failed to get JVMTI environment!");
|
||||
return;
|
||||
}
|
||||
|
||||
JuiceAgent::Loader::preload(path, env, jvmti);
|
||||
}
|
||||
@@ -1,49 +1,32 @@
|
||||
#include <jvm/jni.h>
|
||||
#include <Loader.hpp>
|
||||
#include <JvmAttach.hpp>
|
||||
#include <filesystem>
|
||||
#include <JuiceAgent/Logger.hpp>
|
||||
#include <JuiceAgent/Config.hpp>
|
||||
#include <JuiceAgent/Utils.hpp>
|
||||
#include <JuiceAgent/JuiceAgent.hpp>
|
||||
#include <JuiceAgent/Config.hpp>
|
||||
#include <JuiceAgent/ConfigStruct.hpp>
|
||||
#include <JuiceAgent/JuiceAgent-API-1.4.1+build.1.hpp>
|
||||
|
||||
namespace JuiceAgent::Loader {
|
||||
// Preload section
|
||||
// Check parameters and load the runtime
|
||||
void JuiceAgent::Loader::preload(const char* runtime_dir, JNIEnv* env, jvmtiEnv* jvmti) {
|
||||
std::string runtime_dir_new;
|
||||
|
||||
static bool invoke_juiceagent_init(JNIEnv* env, const LoaderConfig& config) {
|
||||
const char* bootstrap_class = "cn/xiaozhou233/juiceagent/api/JuiceAgentBootstrap";
|
||||
const char* method_name = "start";
|
||||
// Check parameters
|
||||
if(!runtime_dir) {
|
||||
spdlog::warn("[PreLoad] Runtime directory is not specified!");
|
||||
|
||||
std::string args = JuiceAgent::Config::Utils::serialize_loader_config(config);
|
||||
spdlog::debug("Invoke args: {}", args);
|
||||
runtime_dir_new = std::filesystem::current_path().string();
|
||||
|
||||
if (!JuiceAgent::Utils::call_java_impl(env, bootstrap_class, method_name, args.c_str())) {
|
||||
spdlog::error("Failed to init JuiceAgent!");
|
||||
return false;
|
||||
spdlog::warn( "[PreLoad] Using default runtime directory: {}", runtime_dir_new);
|
||||
} else {
|
||||
runtime_dir_new = runtime_dir;
|
||||
}
|
||||
|
||||
spdlog::info("JuiceAgentBootstrap.start invoked successfully");
|
||||
return true;
|
||||
}
|
||||
spdlog::info("[PreLoad] Runtime directory: {}", runtime_dir_new);
|
||||
|
||||
static void init(const char* runtime_dir, JNIEnv* env, jvmtiEnv* jvmti) {
|
||||
if (!runtime_dir) {
|
||||
spdlog::warn("Runtime directory is not set!");
|
||||
}
|
||||
|
||||
// Load configuration
|
||||
JuiceAgent::Config::Config cfg(runtime_dir ? runtime_dir : "");
|
||||
if (!cfg.is_valid()) {
|
||||
spdlog::error("Failed to load configuration!");
|
||||
|
||||
// TODO: Use default values
|
||||
// Before impl TODO, must return, or crash will happen
|
||||
return;
|
||||
}
|
||||
|
||||
// Print configuration
|
||||
LoaderConfig config = JuiceAgent::Config::Utils::get_loader_config(cfg);
|
||||
JuiceAgent::Config::Utils::print_loader_config(config);
|
||||
|
||||
// Save bytes to file
|
||||
// TODO: Advanced options
|
||||
// Extract JuiceAgent API to temp file
|
||||
std::string hash =
|
||||
JuiceAgent::Resource::juiceagent_api_bytes_sha256;
|
||||
|
||||
@@ -58,11 +41,12 @@ static void init(const char* runtime_dir, JNIEnv* env, jvmtiEnv* jvmti) {
|
||||
file_name
|
||||
);
|
||||
|
||||
// Debug
|
||||
spdlog::debug("JuiceAgent API path: {}", juiceagent_api_path);
|
||||
spdlog::debug("JuiceAgent API size: {}", JuiceAgent::Resource::juiceagent_api_bytes_len);
|
||||
spdlog::debug("JuiceAgent API sha256: {}", JuiceAgent::Resource::juiceagent_api_bytes_sha256);
|
||||
|
||||
// Load JuiceAgent API to system classloader
|
||||
// Load JuiceAgent API
|
||||
jvmtiError status = jvmti->AddToSystemClassLoaderSearch(juiceagent_api_path.c_str());
|
||||
if (status != JVMTI_ERROR_NONE) {
|
||||
spdlog::error("Failed to add JuiceAgent API to system classloader! code: {}", static_cast<int>(status));
|
||||
@@ -71,31 +55,34 @@ static void init(const char* runtime_dir, JNIEnv* env, jvmtiEnv* jvmti) {
|
||||
|
||||
spdlog::info("JuiceAgent API loaded to system classloader!");
|
||||
|
||||
// Init JuiceAgent
|
||||
if (!invoke_juiceagent_init(env, config)) {
|
||||
spdlog::error("Failed to init JuiceAgent!");
|
||||
}
|
||||
// Init JuiceAgent via JuiceAgent API
|
||||
JuiceAgent::Loader::initialize(runtime_dir_new.c_str(), env, jvmti);
|
||||
}
|
||||
|
||||
void JuiceAgent::Loader::initialize(const char* runtime_dir, JNIEnv* env, jvmtiEnv* jvmti) {
|
||||
const char* bootstrap_class = "cn/xiaozhou233/juiceagent/api/JuiceAgentBootstrap";
|
||||
const char* method_name = "start";
|
||||
|
||||
void entrypoint(const char* runtime_dir) {
|
||||
// Attach to the JVM
|
||||
Jvm jvm;
|
||||
if (!jvm.attach()) {
|
||||
spdlog::error("Failed to attach to JVM!");
|
||||
// Read JuiceAgent config
|
||||
JuiceAgent::Config::Config cfg(runtime_dir ? runtime_dir : "");
|
||||
if (!cfg.is_valid()) {
|
||||
spdlog::error("JuiceAgent configuration is invalid!");
|
||||
return;
|
||||
}
|
||||
|
||||
// Get jvm and jni env
|
||||
JNIEnv* env = jvm.get_env();
|
||||
auto* jvmti = jvm.get_jvmti();
|
||||
if (!env || !jvmti) {
|
||||
spdlog::error("Failed to get jni env or jvmti env!");
|
||||
// TODO: Refactor config
|
||||
LoaderConfig config = JuiceAgent::Config::Utils::get_loader_config(cfg);
|
||||
JuiceAgent::Config::Utils::print_loader_config(config);
|
||||
|
||||
// Serialize InjectionInfo to string
|
||||
std::string args = JuiceAgent::Config::Utils::serialize_loader_config(cfg, config);
|
||||
spdlog::debug("Serialized config: {}", args);
|
||||
|
||||
bool result = JuiceAgent::Utils::call_java_impl(env, bootstrap_class, method_name, args.c_str());
|
||||
if (!result) {
|
||||
spdlog::error("Failed to initialize JuiceAgent!");
|
||||
return;
|
||||
}
|
||||
|
||||
// Init JuiceAgent
|
||||
init(runtime_dir, env, jvmti);
|
||||
}
|
||||
|
||||
}
|
||||
spdlog::info("JuiceAgent initialized!");
|
||||
}
|
||||
@@ -1,7 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <thread>
|
||||
#include <chrono>
|
||||
#include <thread>
|
||||
|
||||
#include <JuiceAgent/Logger.hpp>
|
||||
#include <jvm/jni.h>
|
||||
@@ -9,29 +9,50 @@
|
||||
|
||||
namespace JuiceAgent::Loader {
|
||||
|
||||
class Jvm {
|
||||
// RAII wrapper: attaches to the running JVM (with retry) and detaches on destruction.
|
||||
class JvmAttach {
|
||||
public:
|
||||
explicit Jvm(int max_try = 30, int retry_delay_ms = 1000)
|
||||
explicit JvmAttach(int max_try = 30, int retry_delay_ms = 1000)
|
||||
: max_try_(max_try), retry_delay_ms_(retry_delay_ms) {}
|
||||
|
||||
~JvmAttach() { detach(); }
|
||||
|
||||
JvmAttach(const JvmAttach&) = delete;
|
||||
JvmAttach& operator=(const JvmAttach&) = delete;
|
||||
|
||||
JavaVM* get_jvm() const { return jvm_; }
|
||||
JNIEnv* get_env() const { return env_; }
|
||||
jvmtiEnv* get_jvmti() const { return jvmti_; }
|
||||
|
||||
bool attach() {
|
||||
reset();
|
||||
jvm_ = nullptr;
|
||||
env_ = nullptr;
|
||||
jvmti_ = nullptr;
|
||||
attached_ = false;
|
||||
|
||||
return acquire_jvm() && acquire_env() && acquire_jvmti();
|
||||
return retry("JavaVM", [this] {
|
||||
return JNI_GetCreatedJavaVMs(&jvm_, 1, nullptr) == JNI_OK && jvm_;
|
||||
}) && retry("JNIEnv", [this] {
|
||||
if (jvm_->GetEnv(reinterpret_cast<void**>(&env_), JNI_VERSION_1_8) == JNI_OK && env_)
|
||||
return true;
|
||||
env_ = nullptr;
|
||||
if (jvm_->AttachCurrentThread(reinterpret_cast<void**>(&env_), nullptr) == JNI_OK && env_) {
|
||||
attached_ = true;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}) && retry("JVMTI", [this] {
|
||||
return jvm_->GetEnv(reinterpret_cast<void**>(&jvmti_), JVMTI_VERSION_1_2) == JNI_OK && jvmti_;
|
||||
});
|
||||
}
|
||||
|
||||
bool detach() {
|
||||
bool detach() noexcept {
|
||||
if (jvm_ && attached_) {
|
||||
jint res = jvm_->DetachCurrentThread();
|
||||
if (res != JNI_OK) {
|
||||
spdlog::debug("DetachCurrentThread failed: {}", res);
|
||||
return false;
|
||||
}
|
||||
|
||||
spdlog::debug("Thread detached");
|
||||
attached_ = false;
|
||||
env_ = nullptr;
|
||||
@@ -40,69 +61,23 @@ public:
|
||||
}
|
||||
|
||||
private:
|
||||
static inline thread_local JNIEnv* env_ = nullptr;
|
||||
|
||||
JavaVM* jvm_ = nullptr;
|
||||
jvmtiEnv* jvmti_ = nullptr;
|
||||
|
||||
bool attached_ = false;
|
||||
int max_try_;
|
||||
int retry_delay_ms_;
|
||||
|
||||
void reset() {
|
||||
jvm_ = nullptr;
|
||||
jvmti_ = nullptr;
|
||||
env_ = nullptr;
|
||||
attached_ = false;
|
||||
}
|
||||
|
||||
void retry(const char* what, int attempt) {
|
||||
spdlog::debug("Failed to get {}, attempt {}/{}", what, attempt, max_try_);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(retry_delay_ms_));
|
||||
}
|
||||
|
||||
template<typename Fn>
|
||||
bool acquire(const char* what, Fn&& attempt) {
|
||||
bool retry(const char* what, Fn&& attempt) {
|
||||
for (int i = 1; i <= max_try_; i++) {
|
||||
if (attempt()) {
|
||||
if (attempt())
|
||||
return true;
|
||||
}
|
||||
retry(what, i);
|
||||
spdlog::debug("Failed to get {}, attempt {}/{}", what, i, max_try_);
|
||||
std::this_thread::sleep_for(std::chrono::milliseconds(retry_delay_ms_));
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool acquire_jvm() {
|
||||
return acquire("JavaVM", [this] {
|
||||
jvm_ = nullptr;
|
||||
return JNI_GetCreatedJavaVMs(&jvm_, 1, nullptr) == JNI_OK && jvm_ != nullptr;
|
||||
});
|
||||
}
|
||||
|
||||
bool acquire_env() {
|
||||
return acquire("JNIEnv", [this] {
|
||||
env_ = nullptr;
|
||||
if (jvm_->GetEnv(reinterpret_cast<void**>(&env_), JNI_VERSION_1_6) == JNI_OK && env_ != nullptr) {
|
||||
return true;
|
||||
}
|
||||
|
||||
env_ = nullptr;
|
||||
if (jvm_->AttachCurrentThread(reinterpret_cast<void**>(&env_), nullptr) == JNI_OK && env_ != nullptr) {
|
||||
attached_ = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
env_ = nullptr;
|
||||
return false;
|
||||
});
|
||||
}
|
||||
|
||||
bool acquire_jvmti() {
|
||||
return acquire("JVMTI", [this] {
|
||||
jvmti_ = nullptr;
|
||||
return jvm_->GetEnv(reinterpret_cast<void**>(&jvmti_), JVMTI_VERSION_1_2) == JNI_OK && jvmti_ != nullptr;
|
||||
});
|
||||
}
|
||||
JavaVM* jvm_ = nullptr;
|
||||
JNIEnv* env_ = nullptr;
|
||||
jvmtiEnv* jvmti_ = nullptr;
|
||||
bool attached_ = false;
|
||||
int max_try_;
|
||||
int retry_delay_ms_;
|
||||
};
|
||||
|
||||
} // namespace JuiceAgent::Loader
|
||||
@@ -1,9 +1,10 @@
|
||||
#pragma once
|
||||
|
||||
#include <jvm/jni.h>
|
||||
#include <jvm/jvmti.h>
|
||||
|
||||
namespace JuiceAgent::Loader {
|
||||
|
||||
// Attach to the JVM and initialize JuiceAgent.
|
||||
// runtime_dir: directory containing config.toml, or nullptr to use defaults.
|
||||
void entrypoint(const char* runtime_dir);
|
||||
|
||||
void entrypoint(const char* runtime_dir);
|
||||
void preload(const char* runtime_dir, JNIEnv* env, jvmtiEnv* jvmti);
|
||||
void initialize(const char* runtime_dir, JNIEnv* env, jvmtiEnv* jvmti);
|
||||
} // namespace JuiceAgent::Loader
|
||||
+2
-3
@@ -3,15 +3,14 @@
|
||||
#include "JuiceAgent/Logger.hpp"
|
||||
#include "Loader.hpp"
|
||||
|
||||
|
||||
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved) {
|
||||
switch (fdwReason) {
|
||||
case DLL_PROCESS_ATTACH: {
|
||||
DisableThreadLibraryCalls(hinstDLL);
|
||||
Logger::init("libloader.log");
|
||||
|
||||
// lpReserved carries the runtime directory from the reflective loader
|
||||
const char* runtime_dir = (const char*)lpReserved;
|
||||
spdlog::info("DllMain: DLL_PROCESS_ATTACH, runtime_dir: {}", runtime_dir);
|
||||
spdlog::info("DllMain: DLL_PROCESS_ATTACH, runtime_dir: {}", runtime_dir ? runtime_dir : "NULL");
|
||||
|
||||
JuiceAgent::Loader::entrypoint(runtime_dir);
|
||||
break;
|
||||
File renamed without changes.
+35
-2
@@ -1,3 +1,36 @@
|
||||
*.class
|
||||
### IntelliJ IDEA ###
|
||||
.idea/
|
||||
out/
|
||||
!**/src/main/**/out/
|
||||
!**/src/test/**/out/
|
||||
|
||||
### Eclipse ###
|
||||
.apt_generated
|
||||
.classpath
|
||||
.factorypath
|
||||
.project
|
||||
.settings
|
||||
.springBeans
|
||||
.sts4-cache
|
||||
bin/
|
||||
!**/src/main/**/bin/
|
||||
!**/src/test/**/bin/
|
||||
|
||||
### NetBeans ###
|
||||
/nbproject/private/
|
||||
/nbbuild/
|
||||
/dist/
|
||||
/nbdist/
|
||||
/.nb-gradle/
|
||||
|
||||
### VS Code ###
|
||||
.vscode/
|
||||
|
||||
### Mac OS ###
|
||||
.DS_Store
|
||||
|
||||
*.log
|
||||
build/
|
||||
|
||||
### JuiceAgent ###
|
||||
resources/
|
||||
tmp/
|
||||
@@ -0,0 +1,4 @@
|
||||
@ECHO OFF
|
||||
|
||||
cp ../build/bin/*.dll ./resources
|
||||
cp ../build/bin/*.exe ./resources
|
||||
Binary file not shown.
@@ -0,0 +1,11 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="JAVA_MODULE" version="4">
|
||||
<component name="NewModuleRootManager" inherit-compiler-output="true">
|
||||
<exclude-output />
|
||||
<content url="file://$MODULE_DIR$">
|
||||
<sourceFolder url="file://$MODULE_DIR$/src" isTestSource="false" />
|
||||
</content>
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
@@ -0,0 +1,5 @@
|
||||
public class Injection {
|
||||
public static void test() {
|
||||
System.out.println("Injection Invoked!");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,6 @@
|
||||
public class Target {
|
||||
public static void targetTest() {
|
||||
System.out.println("Target test!");
|
||||
System.out.println("Modified!");
|
||||
}
|
||||
}
|
||||
@@ -1,14 +0,0 @@
|
||||
@echo off
|
||||
setlocal
|
||||
cd /d "%~dp0"
|
||||
|
||||
if not exist build mkdir build
|
||||
|
||||
javac -d build loop.java
|
||||
if errorlevel 1 (
|
||||
echo [ERROR] Build failed.
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
echo [OK] Build succeeded: build\loop.class
|
||||
endlocal
|
||||
@@ -1,12 +0,0 @@
|
||||
public class loop {
|
||||
public static void main(String[] args) {
|
||||
while (true) {
|
||||
try {
|
||||
System.out.println("Hello, World!");
|
||||
Thread.sleep(1000);
|
||||
} catch (InterruptedException e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
@echo off
|
||||
setlocal
|
||||
cd /d "%~dp0"
|
||||
|
||||
if not exist build\loop.class (
|
||||
echo [ERROR] Build output not found. Run build.bat first.
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
java -cp build loop
|
||||
if errorlevel 1 (
|
||||
echo [ERROR] Run failed.
|
||||
exit /b 1
|
||||
)
|
||||
|
||||
endlocal
|
||||
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user