Compare commits

..
30 Commits
Author SHA1 Message Date
xiaozhou233 f5912f8040 [Doc] Update Version & Example Config 2026-04-20 16:48:29 +08:00
xiaozhou233 95f5604bfe Merge pull request #9 from xiaozhou233/refactor
Enhance configuration handling and implement module system
2026-04-20 14:06:38 +08:00
xiaozhou233 1ae65dd516 [Doc] TODO 2026-04-20 14:05:14 +08:00
xiaozhou233 50773f5456 Feat: Call Java Implementation 2026-04-20 14:04:53 +08:00
xiaozhou233 ccb332cb42 [Feat] Serializer 2026-04-20 13:18:58 +08:00
xiaozhou233 9a2dd217f1 [Refactor] Update configuration handling in JarLoader and enhance Config class 2026-04-19 22:26:51 +08:00
xiaozhou233 3fe9f5a573 Feat: Modules System 2026-04-19 19:03:48 +08:00
xiaozhou233 6858a35754 Feat: Simple module system 2026-04-19 18:57:32 +08:00
xiaozhou233 e7ce54188b [Refactor] Enhance Config class with type-safe get method and value reading 2026-04-19 18:44:59 +08:00
xiaozhou233 9f366645c9 Feat: libagent can now read the config 2026-04-19 18:36:26 +08:00
xiaozhou233 6a7e5a1d38 [Refactor] Config and Loader
[Add] toml11 library
[Refactor] Config
[Refactor] Data Struct
[Refactor] Loader
2026-04-19 16:41:39 +08:00
xiaozhou233 17bc993296 Example: empty example config 2026-04-19 15:44:06 +08:00
xiaozhou233 c348529e65 Style: Rename 2026-04-18 19:53:59 +08:00
xiaozhou233 cc52a25db4 Style: Rename 2026-04-18 19:28:47 +08:00
xiaozhou233 8b0bf8f211 Style: move LocalRef to header / move check_and_clear_exception to header 2026-04-18 19:24:49 +08:00
xiaozhou233 455986b08c Docs: todo 2026-04-17 14:24:48 +08:00
xiaozhou233 5b2c3c77ef Docs: Todo 2026-04-16 21:32:31 +08:00
xiaozhou233 11aaac0f0b Style: Config 2026-04-16 21:29:13 +08:00
xiaozhou233 6d3e29db03 Docs: todo 2026-04-16 19:16:07 +08:00
xiaozhou233 655039745a Fix: Doc 2026-04-16 15:35:41 +08:00
xiaozhou233 09f44f1aff Update Doc 2026-04-16 14:58:12 +08:00
xiaozhou233 5ac0bac555 Doc & Update to Version 3.0 Build 2 2026-04-16 13:26:36 +08:00
xiaozhou233 c7d9336b70 Refactor: preload event 2026-04-05 14:26:33 +08:00
xiaozhou233 c11891e718 Style: rename 2026-04-05 13:48:59 +08:00
xiaozhou233 de56fca73d Doc: README Acknowledgements 2026-04-05 11:28:20 +08:00
xiaozhou233 c20ec1e839 Merge pull request #7 - Feat/separation: 添加事件系统、分离Capture/Patch bytecodes
Feat/separation: 添加事件系统、分离Capture/Patch bytecodes
2026-04-04 21:59:10 +08:00
xiaozhou233 f8be8cb795 Feat: Event of preload & loaded 2026-04-04 21:51:12 +08:00
xiaozhou233 eb3a76769d Refactor: move eventbus.hpp/event_type to includes/event 2026-04-04 21:44:03 +08:00
xiaozhou233 49d2499f73 Feat: EventBus 2026-04-04 21:42:15 +08:00
xiaozhou233 a64bbb8bb8 Update: Add eventpp library 2026-04-04 21:02:04 +08:00
55 changed files with 24802 additions and 790 deletions

No files matched your search

+92 -75
View File
@@ -1,129 +1,146 @@
# JuiceAgent # JuiceAgent
[English](https://github.com/xiaozhou233/JuiceAgent/blob/main/README.md) | [中文](https://github.com/xiaozhou233/JuiceAgent/blob/main/README_zh.md) [English](https://github.com/xiaozhou233/JuiceAgent/blob/main/README.md) | [中文](https://github.com/xiaozhou233/JuiceAgent/blob/main/README_zh.md)
JuiceAgent is a JVMTI-based injection library for loading external JARs and transforming Java bytecode, even when `DisableAttachMechanism` is enabled.
JuiceAgent — a JVMTI-based injection library for loading external JARs and transforming Java bytecode, even when DisableAttachMechanism is enabled. **Notice:** Currently, only **Windows** is supported. **Linux** support may be added in the future.
**NOTICE:** Currently only supports **Windows**, and plans to support **Linux** in the future. **Notice:** The current repository version is **Version 3.3 Build 1**.
**NOTICE:** **Version 2.3 Build 1** is the current **stable release and is no longer being updated.** Version 3.0 and later have been rewritten and may contain unknown issues. **Warning:** This project is still experimental and is not recommended for production use. Use it at your own risk.
**WARNING:** This project is still in the experimental stage and is not recommended for production use.
**Use this at your own risk.**
## Summary ## Summary
JuiceAgent is a JVMTI-native injection framework that injects native code into a target JVM to dynamically load external JARs and perform bytecode redefinition/transformations without requiring a javaagent (works when DisableAttachMechanism=true). JuiceAgent is a JVMTI-native injection framework that injects native code into a target JVM to dynamically load external JARs and perform bytecode redefinition or retransformation without requiring a `javaagent`. It can still work when `DisableAttachMechanism=true`.
## Features ## Features
This project is an implementation of the JuiceAgent-API. For more details, please see [This](https://github.com/xiaozhou233/JuiceAgent-API/blob/master/src/main/java/cn/xiaozhou233/juiceagent/api/JuiceAgent.java) This project is the native implementation of JuiceAgent-API. For the API definition, see [JuiceAgent.java](https://github.com/xiaozhou233/JuiceAgent-API/blob/master/src/main/java/cn/xiaozhou233/juiceagent/api/JuiceAgent.java).
- addToBootstrapClassLoaderSearch - `addToBootstrapClassLoaderSearch`
- addToSystemClassLoaderSearch - `addToSystemClassLoaderSearch`
- addToClassLoader - `addToClassLoader`
- defineClass - `defineClass`
- redefineClass(ByName) - `redefineClass(ByName)`
- retransformClass(ByName) - `retransformClass(ByName)`
- getLoadedClasses - `getLoadedClasses`
- getClassByName - `getClassByName`
- getClassBytes(ByName) - `getClassBytes(ByName)`
## How To Use (**For Version 3.0 Build 2**) ## How To Use
### 1. ⬇️ Download Files ### 1. Download Files
- Download `libagent.dll` `libinject.dll` `libloader.dll` `injector.exe` from [Release](https://github.com/xiaozhou233/JuiceAgent/releases) and put them in `YourDir` Download the following files from [Releases](https://github.com/xiaozhou233/JuiceAgent/releases) and place them in `YourDir`:
- Download JARs `JuiceAgent-API-X.X.X+build.X.jar` from [JuiceAgent-API Release] (https://github.com/xiaozhou233/JuiceAgent-API/releases) and put them in `YourDir`
### 2. ✍️ Write Config File - `libagent.dll`
Create a config file named `config.toml` in `YourDir` - `libinject.dll`
- `libloader.dll`
- `injector.exe`
Download `JuiceAgent-API-X.X.X+build.X.jar` from [JuiceAgent-API Releases](https://github.com/xiaozhou233/JuiceAgent-API/releases) and place it in `YourDir`.
### 2. Write the Config File
Create a file named `config.toml` in `YourDir`.
```toml ```toml
[JuiceAgent] [JuiceAgent]
# Default value: YourDir/JuiceAgent-API.jar Version = 1
[JuiceAgent.Loader]
JuiceAgentAPIJarPath = "" JuiceAgentAPIJarPath = ""
# Default value: YourDir/libagent.dll JuiceAgentNativeLibraryPath = ""
JuiceAgentNativePath = ""
[Entry] [JuiceAgent.Modules]
# Default value: YourDir/Entry.jar
EntryJarPath = ""
# Default value: com.example.Entry
EntryClass = ""
# Default value: start
EntryMethod = "start"
[Runtime] [JuiceAgent.Modules.JarLoader]
# Default value: YourDir/injection Enabled = true
InjectionDir = "" InjectionDir = ""
JarPath = ""
EntryClass = ""
EntryMethod = ""
``` ```
### 3. 💉 Run Injector ### 3. Run the Injector
#### **Method A** : Use `injector.exe`
Run `injector.exe` #### Method A: Use `injector.exe`
``` Run `injector.exe` from `YourDir`.
114514 loop
```text
<jps output>
Input PID: Input PID:
``` ```
Input PID of target process and press Enter Enter the PID of the target JVM process and press Enter.
#### Method B: Use JNI to call `inject`
Create `cn/xiaozhou233/juiceagent/injector/InjectorNative.java` in your project:
#### **Method B** : Use JNI to call `inject` function
Create a file named cn/xiaozhou233/juiceagent/injector.java in your project
```java ```java
package cn.xiaozhou233.juiceagent.injector; package cn.xiaozhou233.juiceagent.injector;
public class InjectorNative { public class InjectorNative {
/* /*
* @param pid target process id * @param pid target process id
*/ * @param path injection DLL path
public native boolean inject(int pid, String path); */
public native boolean inject(int pid, String path);
/* /*
* @param pid target process id * @param pid target process id
* @param path injection dll path * @param path injection DLL path
* @param configPath config file path * @param configDir directory containing config.toml
*/ */
public native boolean inject(int pid, String path, String configPath); public native boolean inject(int pid, String path, String configDir);
} }
``` ```
Then write it down somewhere
Example:
```java ```java
// Your class
import cn.xiaozhou233.juiceagent.injector.InjectorNative; import cn.xiaozhou233.juiceagent.injector.InjectorNative;
System.load("<path-to-libinject>"); System.load("<path-to-libinject>");
InjectorNative injectorNative = new InjectorNative(); InjectorNative injectorNative = new InjectorNative();
injectorNative.inject(<pid>, "<path-to-libloader>", "<path-to-toml-config-dir>"); injectorNative.inject(<pid>, "<path-to-libloader>", "<path-to-config-directory>");
``` ```
### 4. ✅ Done!
if injection is successful, target process will load `Entry.jar` (or `EntryClass` in config file) and run `EntryMethod` method(or `start` method in config file)
## Hot To Build ### 4. Done
### Environment If the injection succeeds, the target process will load `Entry.jar` (or the file specified by `EntryJarPath`) and invoke `EntryClass.EntryMethod` (default: `com.example.Entry.start`).
## How To Build
### Requirements
- Java 8+ - Java 8+
- MinGW - MinGW
- CMake - CMake 3.15+
- Ninja - Ninja
```
### Build with CMake Presets
```powershell
git clone https://github.com/xiaozhou233/JuiceAgent.git git clone https://github.com/xiaozhou233/JuiceAgent.git
cd JuiceAgent cd JuiceAgent
mkdir -p build cmake --preset ninja-release
cmake --build build -- cmake --build build
``` ```
Dlls will be generated in `build/bin` directory ### Manual Build
```powershell
git clone https://github.com/xiaozhou233/JuiceAgent.git
cd JuiceAgent
Jars can be build or download in project [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API) cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
cmake --build build
```
## Full Disclaimer/ 完整免责声明 The generated binaries will be placed in `build/bin`.
Disclaimer: This project is intended for learning and research in controlled environments only. The author is not responsible for any consequences arising from unauthorized use, modification, cracking, or violation of any applicable agreements or laws. Users are responsible for ensuring their actions are legal and compliant.
免责声明: 本项目仅建议在受控环境中用于学习与研究。任何利用本项目实施破解、篡改、未经授权获取源码或其他违反目标协议或法律的行为所导致的一切后果,作者概不负责。使用者应自行确保其行为合法合规,并对相应后果承担全部责任。 `JuiceAgent-API.jar` can be built from or downloaded from [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API).
## Full Disclaimer
This project is intended for learning and research in controlled environments only. The author is not responsible for any consequences arising from unauthorized use, modification, cracking, or violation of any applicable agreements or laws. Users are responsible for ensuring that their actions are legal and compliant.
## Acknowledgements ## Acknowledgements
- [ReflectiveDLLInjection](https://github.com/stephenfewer/ReflectiveDLLInjection) - DLL injection implementation
- [ReflectiveDLLInjection](https://github.com/stephenfewer/ReflectiveDLLInjection) - DLL Inject - [plog](https://github.com/SergiusTheBest/plog) - Portable, simple, and extensible C++ logging library
- [plog](https://github.com/SergiusTheBest/plog) - portable, simple and extensible C++ logging library - [tinytoml](https://github.com/mayah/tinytoml) - Header-only C++11 TOML parser
- [tinytoml](https://github.com/mayah/tinytoml) - A header only C++11 library for parsing TOML. - [eventpp](https://github.com/wqking/eventpp) - C++ library for event dispatchers and callback lists
+76 -107
View File
@@ -1,117 +1,94 @@
# JuiceAgent # JuiceAgent
[English](https://github.com/xiaozhou233/JuiceAgent/blob/main/README.md) | [中文](https://github.com/xiaozhou233/JuiceAgent/blob/main/README_zh.md) [English](https://github.com/xiaozhou233/JuiceAgent/blob/main/README.md) | [中文](https://github.com/xiaozhou233/JuiceAgent/blob/main/README_zh.md)
JuiceAgent —— 一个基于 JVMTI 的注入库,用于加载外部 JAR 并对 Java 字节码进行热替换,即使在 DisableAttachMechanism 启用的情况下也可使用。 JuiceAgent 是一个基于 JVMTI 的注入库,用于加载外部 JAR 并对 Java 字节码进行转换;即使启用了 `DisableAttachMechanism` 也可以使用。
**注意:** 当前仅支持 **Windows**,未来计划支持 **Linux**。 **注意:** 当前仅支持 **Windows**,未来可能会支持 **Linux**。
**注意:** **Version 2.3 Build 1** 是当前的 **稳定版本且已停止更新**。3.0 及之后版本已重构,可能存在未知问题。 **注意:** 当前仓库版本为 **Version 3.3 Build 1**。
**警告:** 本项目仍处于实验阶段,不建议用于生产环境。 **警告:** 本项目仍处于实验阶段,不建议在生产环境中使用。使用风险请自行承担。
**使用风险自负。**
---
## 简介 ## 简介
JuiceAgent 是一个基于 JVMTI 的原生注入框架,通过向目标 JVM 注入代码,实现动态加载外部 JAR 以及字节码热替换,无需使用 javaagent(在 DisableAttachMechanism=true 时仍可工作)。 JuiceAgent 是一个基于 JVMTI 的原生注入框架。它通过向目标 JVM 注入原生代码,动态加载外部 JAR,并执行字节码重定义或重转换,而不需要 `javaagent`。在 `DisableAttachMechanism=true` 的情况下依然可以工作。
---
## 功能特性 ## 功能特性
本项目是 JuiceAgent-API 的原生实现。API 定义可参考 [JuiceAgent.java](https://github.com/xiaozhou233/JuiceAgent-API/blob/master/src/main/java/cn/xiaozhou233/juiceagent/api/JuiceAgent.java)。
本项目是 JuiceAgent-API 的Native实现,详细内容请参考: - `addToBootstrapClassLoaderSearch`
https://github.com/xiaozhou233/JuiceAgent-API/blob/master/src/main/java/cn/xiaozhou233/juiceagent/api/JuiceAgent.java - `addToSystemClassLoaderSearch`
- `addToClassLoader`
- `defineClass`
- `redefineClass(ByName)`
- `retransformClass(ByName)`
- `getLoadedClasses`
- `getClassByName`
- `getClassBytes(ByName)`
- addToBootstrapClassLoaderSearch ## 使用方法
- addToSystemClassLoaderSearch
- addToClassLoader
- defineClass
- redefineClass(ByName)
- retransformClass(ByName)
- getLoadedClasses
- getClassByName
- getClassBytes(ByName)
--- ### 1. 下载文件
从 [Releases](https://github.com/xiaozhou233/JuiceAgent/releases) 下载以下文件,并放到 `YourDir` 中:
## 使用方法(适用于 Version 3.0 Build 2) - `libagent.dll`
- `libinject.dll`
- `libloader.dll`
- `injector.exe`
### 1. ⬇️ 下载文件 从 [JuiceAgent-API Releases](https://github.com/xiaozhou233/JuiceAgent-API/releases) 下载 `JuiceAgent-API-X.X.X+build.X.jar`,并放到 `YourDir` 中。
- 从 Release 下载: ### 2. 编写配置文件
- libagent.dll 在 `YourDir` 下创建 `config.toml`:
- libinject.dll
- libloader.dll
- injector.exe
并放入 `YourDir`
- 从 JuiceAgent-API Release 下载:
- JuiceAgent-API-X.X.X+build.X.jar
并放入 `YourDir`
---
### 2. ✍️ 编写配置文件
在 `YourDir` 下创建 `config.toml`
```toml ```toml
[JuiceAgent] [JuiceAgent]
# 默认值: YourDir/JuiceAgent-API.jar Version = 1
[JuiceAgent.Loader]
JuiceAgentAPIJarPath = "" JuiceAgentAPIJarPath = ""
# 默认值: YourDir/libagent.dll JuiceAgentNativeLibraryPath = ""
JuiceAgentNativePath = ""
[Entry] [JuiceAgent.Modules]
# 默认值: YourDir/Entry.jar
EntryJarPath = ""
# 默认值: com.example.Entry
EntryClass = ""
# 默认值: start
EntryMethod = "start"
[Runtime] [JuiceAgent.Modules.JarLoader]
# 默认值: YourDir/injection Enabled = true
InjectionDir = "" InjectionDir = ""
JarPath = ""
EntryClass = ""
EntryMethod = ""
``` ```
--- ### 3. 执行注入
### 3. 💉 执行注入 #### 方法 A:使用 `injector.exe`
在 `YourDir` 中运行 `injector.exe`。
#### 方法 A:使用 injector.exe ```text
<jps 输出>
运行`inject.exe`:
```
114514 loop
Input PID: Input PID:
``` ```
输入目标进程 PID 后回车 输入目标 JVM 进程的 PID 后按回车。
--- #### 方法 B:通过 JNI 调用 `inject`
在你的项目中创建 `cn/xiaozhou233/juiceagent/injector/InjectorNative.java`:
#### 方法 B:使用 JNI 调用 inject
创建文件:
`cn/xiaozhou233/juiceagent/injector/InjectorNative.java`
```java ```java
package cn.xiaozhou233.juiceagent.injector; package cn.xiaozhou233.juiceagent.injector;
public class InjectorNative { public class InjectorNative {
/* /*
* @param pid target process id * @param pid target process id
*/ * @param path injection DLL path
public native boolean inject(int pid, String path); */
public native boolean inject(int pid, String path);
/* /*
* @param pid target process id * @param pid target process id
* @param path injection dll path * @param path injection DLL path
* @param configPath config file path * @param configDir 包含 config.toml 的目录
*/ */
public native boolean inject(int pid, String path, String configPath); public native boolean inject(int pid, String path, String configDir);
} }
``` ```
@@ -123,55 +100,47 @@ import cn.xiaozhou233.juiceagent.injector.InjectorNative;
System.load("<path-to-libinject>"); System.load("<path-to-libinject>");
InjectorNative injectorNative = new InjectorNative(); InjectorNative injectorNative = new InjectorNative();
injectorNative.inject(<pid>, "<path-to-libloader>", "<path-to-toml-config-dir>"); injectorNative.inject(<pid>, "<path-to-libloader>", "<path-to-config-directory>");
``` ```
--- ### 4. 完成
如果注入成功,目标进程会加载 `Entry.jar`(或 `EntryJarPath` 指定的文件),并调用 `EntryClass.EntryMethod`(默认值为 `com.example.Entry.start`)。
### 4. ✅ 完成 ## 构建方法
注入成功后,目标进程将加载:
- Entry.jar(或配置中的 EntryClass)
- 并执行 EntryMethod(默认 start)
---
## 如何构建
### 环境要求 ### 环境要求
- Java 8+ - Java 8+
- MinGW - MinGW
- CMake - CMake 3.15+
- Ninja - Ninja
```bash ### 使用 CMake Presets 构建
```powershell
git clone https://github.com/xiaozhou233/JuiceAgent.git git clone https://github.com/xiaozhou233/JuiceAgent.git
cd JuiceAgent cd JuiceAgent
mkdir -p build cmake --preset ninja-release
cmake --build build -- cmake --build build
``` ```
生成的 DLL 位于: ### 手动构建
```powershell
git clone https://github.com/xiaozhou233/JuiceAgent.git
cd JuiceAgent
``` cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
build/bin cmake --build build
``` ```
JAR 可在 JuiceAgent-API 项目中构建或下载。 生成的二进制文件位于 `build/bin`。
--- `JuiceAgent-API.jar` 可以在 [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API) 项目中构建,或直接从其发布页下载。
## 完整免责声明 ## 完整免责声明
本项目仅用于受控环境中的学习与研究。对于任何未经授权的使用、修改、破解,或违反适用协议与法律的行为所产生的后果,作者概不负责。使用者应自行确保其行为合法合规,并承担全部责任。
免责声明:本项目仅建议在受控环境中用于学习与研究。作者不对任何因滥用、破解、修改或违反协议/法律行为所产生的后果负责。使用者需自行确保合法合规,并承担全部责任。
---
## 致谢 ## 致谢
- [ReflectiveDLLInjection](https://github.com/stephenfewer/ReflectiveDLLInjection) - DLL 注入实现
- ReflectiveDLLInjection — DLL 注入实现 - [plog](https://github.com/SergiusTheBest/plog) - 轻量、可扩展的 C++ 日志库
- plog — 轻量级 C++ 日志库 - [tinytoml](https://github.com/mayah/tinytoml) - Header-only C++11 TOML 解析库
- tinytoml — C++11 TOML 解析库 - [eventpp](https://github.com/wqking/eventpp) - 用于事件分发和回调列表的 C++ 库
+19
View File
@@ -0,0 +1,19 @@
# TODO - 开发待办事项
这个文档用来记录开发时的待办事项以及以后的开发计划。
---
## 2026-04-16
- [ ] ~~把读取toml的库换成支持toml 1.0的库~~
- [x] 在 `includes/JuiceAgent` 文件夹下实现 `Config.hpp` 配置系统
- [ ] ~~新建测试 读取配置文件 (放弃)~~
- [ ] 重构 `libloader` 的配置系统
## 2026-04-17
- [x] 重构项目为模块化项目
- [x] `libloader` 模块只负责加载`JuiceAgent-API`和`JuiceAgent`, Jar文件由`JuiceAgent`接管
- [x] `libloader` 读取配置文件并传参`JuiceAgentNativePath`和`ConfigDir`到 `JuiceAgent` 中,由`JuiceAgent`读取配置文件继续进行操作
## 2026-04-19
- [x] 在 `JuiceAgent/Utils.hpp`做序列化操作
- [x] 统一调用 module的Java实现
+1 -1
View File
@@ -1 +1 @@
VERSION = Version 3.0 Build 2 VERSION = Version 3.1 Build 3
+16
View File
@@ -0,0 +1,16 @@
[JuiceAgent]
Version = 1
[JuiceAgent.Loader]
JuiceAgentAPIJarPath = ""
JuiceAgentNativeLibraryPath = ""
[JuiceAgent.Modules]
[JuiceAgent.Modules.JarLoader]
Enabled = true
InjectionDir = ""
JarPath = ""
EntryClass = ""
EntryMethod = ""
+164
View File
@@ -0,0 +1,164 @@
#pragma once
#include <JuiceAgent/Logger.hpp>
#include <JuiceAgent/JuiceAgent.hpp>
#include <toml.hpp>
#include <filesystem>
#include <string>
#include <JuiceAgent/Utils.hpp>
namespace JuiceAgent::Config {
class Config {
private:
std::filesystem::path _runtime_dir;
toml::value _config;
bool _valid = false;
private:
template<typename T>
static T _read_value(const toml::value& v) {
if constexpr (std::is_same_v<T, std::string>) {
return v.as_string();
} else if constexpr (std::is_same_v<T, bool>) {
return v.as_boolean();
} else if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool>) {
return static_cast<T>(v.as_integer());
} else if constexpr (std::is_floating_point_v<T>) {
return static_cast<T>(v.as_floating());
} else {
static_assert(sizeof(T) == 0, "Unsupported config type");
}
}
public:
explicit Config(const std::filesystem::path& runtime_dir = {})
{
_runtime_dir = runtime_dir.empty()
? std::filesystem::current_path()
: runtime_dir;
const auto result = toml::try_parse(_runtime_dir / "config.toml");
if (result.is_ok()) {
_config = result.unwrap();
_valid = true;
} else {
PLOGE << "Failed to parse config.toml";
for (const auto& err : result.unwrap_err()) {
PLOGE << toml::format_error(err);
}
}
}
bool is_valid() const noexcept {
return _valid;
}
const toml::value& get_config() const noexcept {
return _config;
}
const std::filesystem::path& runtime_dir() const noexcept {
return _runtime_dir;
}
template<typename T>
T get(const std::string& path, const T& default_value, bool is_path = false) const {
if (!_valid) {
return default_value;
}
try {
const toml::value* current = &_config;
std::size_t start = 0;
while (start < path.size()) {
const std::size_t end = path.find('.', start);
const std::string key = path.substr(
start,
end == std::string::npos ? std::string::npos : end - start
);
current = &current->at(key);
if (end == std::string::npos) {
break;
}
start = end + 1;
}
T value = _read_value<T>(*current);
if constexpr (std::is_same_v<T, std::string>) {
if (value.empty()) {
return default_value;
}
// Handle relative paths
if (is_path) {
// Check if starts with "."
if (value.starts_with(".")) {
// Remove "."
value = value.substr(1);
// Check if starts with "/"
if (value.starts_with("/")) {
// Remove "/"
value = value.substr(1);
}
// runtime_dir + value
value = (_runtime_dir / value).string();
}
}
}
return value;
}
catch (const std::exception& e) {
PLOGW << "Config get failed: " << path << ", using default value";
return default_value;
}
}
};
namespace Utils {
inline LoaderConfig get_loader_config(const Config& config) {
auto cfg = config.get_config().at("JuiceAgent").at("Loader");
LoaderConfig loader_config = LoaderConfig();
loader_config.JuiceAgentAPIJarPath = cfg.at("JuiceAgentAPIJarPath").as_string();
loader_config.JuiceAgentNativeLibraryPath = cfg.at("JuiceAgentNativeLibraryPath").as_string();
loader_config.RuntimeDir = config.runtime_dir().string();
return loader_config;
}
inline void print_loader_config(const LoaderConfig& config) {
PLOGI << "JuiceAgentAPIJarPath: " << config.JuiceAgentAPIJarPath;
PLOGI << "JuiceAgentNativeLibraryPath: " << config.JuiceAgentNativeLibraryPath;
PLOGI << "RuntimeDir: " << config.RuntimeDir;
}
inline std::string serialize_loader_config(const LoaderConfig& config) {
// std::string result = "";
// result += "Version=2;";
// result += "JuiceAgentAPIJarPath=" + config.JuiceAgentAPIJarPath + ";";
// result += "JuiceAgentNativeLibraryPath=" + config.JuiceAgentNativeLibraryPath + ";";
// result += "RuntimeDir=" + config.RuntimeDir + ";";
JuiceAgent::Utils::Serializer ser;
ser.add_kv("Version", 2);
ser.add_kv("JuiceAgentAPIJarPath", config.JuiceAgentAPIJarPath);
ser.add_kv("JuiceAgentNativeLibraryPath", config.JuiceAgentNativeLibraryPath);
ser.add_kv("RuntimeDir", config.RuntimeDir);
return ser.serialize();
}
}
} // namespace JuiceAgent::Config
+3 -7
View File
@@ -2,13 +2,9 @@
#include <string> #include <string>
struct InjectionInfo { struct LoaderConfig {
std::string JuiceAgentAPIJarPath; std::string JuiceAgentAPIJarPath;
std::string JuiceAgentNativePath; std::string JuiceAgentNativeLibraryPath;
std::string EntryJarPath; std::string RuntimeDir;
std::string EntryClass;
std::string EntryMethod;
std::string InjectionDir;
}; };
+267
View File
@@ -0,0 +1,267 @@
#pragma once
#include <jni.h>
#include <jvmti.h>
#include <JuiceAgent/Logger.hpp>
#include <string>
#include <unordered_map>
#include <type_traits>
#include <cstdlib>
// Check for JNI exceptions and clear them
inline bool check_and_clear_exception(JNIEnv* env, const char* context) {
if (env->ExceptionCheck()) {
PLOGE << "JNI Exception occurred at: " << context;
env->ExceptionDescribe();
env->ExceptionClear();
return true;
}
return false;
}
namespace JuiceAgent::Utils
{
inline bool call_java_impl(JNIEnv* env, const char* clazz, const char* method, const char* params) {
if (!env || !clazz || !method) {
PLOGE << "Invalid JNI arguments";
return false;
}
constexpr const char* method_signature = "(Ljava/lang/String;)V";
PLOGD << "Calling Java method: " << clazz << "." << method << " " << method_signature;
jclass cls = env->FindClass(clazz);
if (!cls) {
check_and_clear_exception(env, "FindClass failed");
PLOGE << "Class not found: " << clazz;
return false;
}
jmethodID mid = env->GetStaticMethodID(cls, method, method_signature);
if (!mid) {
check_and_clear_exception(env, "GetStaticMethodID failed");
PLOGE << "Method not found: " << method;
env->DeleteLocalRef(cls);
return false;
}
jstring j_params = env->NewStringUTF(params ? params : "");
if (!j_params) {
PLOGE << "Failed to create jstring";
env->DeleteLocalRef(cls);
return false;
}
env->CallStaticVoidMethod(cls, mid, j_params);
bool success = !env->ExceptionCheck();
check_and_clear_exception(env, "CallStaticVoidMethod failed");
env->DeleteLocalRef(j_params);
env->DeleteLocalRef(cls);
return success;
}
class Serializer {
private:
std::string s;
private:
static std::string escape(const std::string& input) {
std::string out;
out.reserve(input.size());
for (char c : input) {
if (c == '=' || c == ';' || c == '\\') {
out += '\\';
}
out += c;
}
return out;
}
public:
Serializer() = default;
Serializer& add_kv(const std::string& key, const std::string& value) {
s += escape(key);
s += '=';
s += escape(value);
s += ';';
return *this;
}
Serializer& add_kv(const std::string& key, const char* value) {
return add_kv(key, std::string(value));
}
Serializer& add_kv(const std::string& key, int value) {
return add_kv(key, std::to_string(value));
}
Serializer& add_kv(const std::string& key, bool value) {
return add_kv(key, value ? "true" : "false");
}
void clear() {
s.clear();
}
bool empty() const {
return s.empty();
}
const std::string& serialize() const {
return s;
}
};
class Deserializer {
private:
std::unordered_map<std::string, std::string> data;
private:
static std::string unescape(const std::string& input) {
std::string out;
out.reserve(input.size());
bool escaped = false;
for (char c : input) {
if (escaped) {
out += c;
escaped = false;
continue;
}
if (c == '\\') {
escaped = true;
continue;
}
out += c;
}
return out;
}
static bool to_bool(const std::string& v, bool def) {
if (v == "true" || v == "1") return true;
if (v == "false" || v == "0") return false;
return def;
}
template<typename T>
static T convert(const std::string& v, T def) {
if constexpr (std::is_same_v<T, std::string>) {
return v;
}
else if constexpr (std::is_same_v<T, bool>) {
return to_bool(v, def);
}
else if constexpr (std::is_integral_v<T>) {
try {
long long n = std::stoll(v);
return static_cast<T>(n);
} catch (...) {
return def;
}
}
else if constexpr (std::is_floating_point_v<T>) {
try {
long double n = std::stold(v);
return static_cast<T>(n);
} catch (...) {
return def;
}
}
else {
return def;
}
}
public:
Deserializer() = default;
explicit Deserializer(const std::string& input) {
parse(input);
}
void parse(const std::string& input) {
data.clear();
std::string key;
std::string value;
bool reading_key = true;
bool escaped = false;
for (char c : input) {
if (escaped) {
(reading_key ? key : value) += c;
escaped = false;
continue;
}
if (c == '\\') {
escaped = true;
continue;
}
if (reading_key && c == '=') {
reading_key = false;
continue;
}
if (c == ';') {
if (!key.empty()) {
data[unescape(key)] = unescape(value);
}
key.clear();
value.clear();
reading_key = true;
continue;
}
(reading_key ? key : value) += c;
}
if (!key.empty()) {
data[unescape(key)] = unescape(value);
}
}
bool has(const std::string& key) const {
return data.find(key) != data.end();
}
template<typename T>
T get(const std::string& key, T def) const {
auto it = data.find(key);
if (it == data.end()) {
return def;
}
return convert<T>(it->second, def);
}
void clear() {
data.clear();
}
bool empty() const {
return data.empty();
}
std::size_t size() const {
return data.size();
}
};
} // namespace JuiceAgent::Utils
+498
View File
@@ -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
+328
View File
@@ -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
+186
View File
@@ -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
+561
View File
@@ -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
+319
View File
@@ -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
+325
View File
@@ -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
+482
View File
@@ -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
+191
View File
@@ -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_
+174
View File
@@ -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
+127
View File
@@ -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
+75
View File
@@ -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
+247
View File
@@ -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
+161
View File
@@ -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
+196
View File
@@ -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
+177
View File
@@ -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;
*/
+169
View File
@@ -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
+330
View File
@@ -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
+18162
View File
File diff suppressed because it is too large. Load diff
+16
View File
@@ -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.
+21
View File
@@ -0,0 +1,21 @@
The MIT License (MIT)
Copyright (c) 2017 Toru Niina
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
+14 -43
View File
@@ -1,5 +1,5 @@
#include <jni_impl.hpp> #include <jni_impl.hpp>
#include <iostream> #include <event/event_type.hpp>
void JNICALL ClassFileLoadHook( void JNICALL ClassFileLoadHook(
jvmtiEnv* jvmti_env, jvmtiEnv* jvmti_env,
@@ -17,46 +17,17 @@ void JNICALL ClassFileLoadHook(
return; return;
} }
/* ========================= auto& agent = JuiceAgent::Agent::instance();
* 1. Capture original bytes agent.get_eventbus().post(EventClassFileLoadHook{
* ========================= */ .jvmti_env = jvmti_env,
std::lock_guard<std::mutex> lock(classDataMutex); .jni_env = jni_env,
if (classToCapture.contains(name)) { .class_being_redefined = class_being_redefined,
if (!classFileDataMap.contains(name)) { .loader = loader,
ClassFileData data; .name = name,
.protection_domain = protection_domain,
data.classname = name; .class_data_len = class_data_len,
data.bytecode.assign(classbytes, classbytes + class_data_len); .classbytes = classbytes,
// Experimental: class/classloader/protection_domain references (to be used in future features, e.g. dynamic patching) .new_class_data_len = new_class_data_len,
data.clazz = class_being_redefined; .new_classbytes = new_classbytes
data.classloader = loader; });
data.protection_domain = protection_domain;
classFileDataMap[name] = std::move(data);
classToCapture.erase(name);
PLOGI << "Captured class: " << name << " (length: " << class_data_len << ")";
}
}
/* =========================
* 2. Apply patches
* ========================= */
if (pendingRetransform.contains(name)) {
auto& bytes = pendingRetransform[name];
unsigned char* new_buf = nullptr;
jvmti_env->Allocate(bytes.size(), &new_buf);
memcpy(new_buf, bytes.data(), bytes.size());
*new_class_data_len = (jint)bytes.size();
*new_classbytes = new_buf;
pendingRetransform.erase(name);
PLOGI << "Retransformed: " << name << " (new length: " << bytes.size() << ")";
}
} }
+59
View File
@@ -0,0 +1,59 @@
#include <bytecodes_opt.hpp>
#include <jni_impl.hpp>
#include <event/event_type.hpp>
namespace JuiceAgent::Bytecodes {
void register_bytecodes() {
auto& agent = JuiceAgent::Agent::instance();
agent.get_eventbus().subscribe<EventClassFileLoadHook>(capture_bytecodes);
agent.get_eventbus().subscribe<EventClassFileLoadHook>(patch_bytecodes);
}
void capture_bytecodes(const EventClassFileLoadHook& e) {
/* =========================
* 1. Capture original bytes
* ========================= */
std::lock_guard<std::mutex> lock(classDataMutex);
if (classToCapture.contains(e.name)) {
if (!classFileDataMap.contains(e.name)) {
ClassFileData data;
data.classname = e.name;
data.bytecode.assign(e.classbytes, e.classbytes + e.class_data_len);
// Experimental: class/classloader/protection_domain references (to be used in future features, e.g. dynamic patching)
data.clazz = e.class_being_redefined;
data.classloader = e.loader;
data.protection_domain = e.protection_domain;
classFileDataMap[e.name] = std::move(data);
classToCapture.erase(e.name);
PLOGI << "Captured class: " << e.name << " (length: " << e.class_data_len << ")";
}
}
}
void patch_bytecodes(const EventClassFileLoadHook& e) {
/* =========================
* 2. Apply patches
* ========================= */
if (pendingRetransform.contains(e.name)) {
auto& bytes = pendingRetransform[e.name];
unsigned char* new_buf = nullptr;
e.jvmti_env->Allocate(bytes.size(), &new_buf);
memcpy(new_buf, bytes.data(), bytes.size());
*e.new_class_data_len = (jint)bytes.size();
*e.new_classbytes = new_buf;
pendingRetransform.erase(e.name);
PLOGI << "Retransformed: " << e.name << " (new length: " << bytes.size() << ")";
}
}
}
@@ -3,11 +3,22 @@
// This function is called by Java to initialize the agent. // This function is called by Java to initialize the agent.
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init
(JNIEnv *env, jclass loader_class) { (JNIEnv *env, jclass , jstring j_runtime_dir) {
InitLogger(); InitLogger();
PLOGI << "Initializing JuiceAgent..."; PLOGI << "Initializing JuiceAgent...";
// Get runtime directory
const char* c_runtime_dir = env->GetStringUTFChars(j_runtime_dir, nullptr);
std::string runtime_dir(c_runtime_dir);
env->ReleaseStringUTFChars(j_runtime_dir, c_runtime_dir);
if (runtime_dir.empty()) {
PLOGE << "Failed to get runtime directory from argument, runtime_dir is empty";
return JNI_FALSE;
}
PLOGI << "JuiceAgent got runtime directory: " << runtime_dir;
JavaVM* jvm = nullptr; JavaVM* jvm = nullptr;
jvmtiEnv* jvmti = nullptr; jvmtiEnv* jvmti = nullptr;
@@ -27,7 +38,7 @@ JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init
// Invoke EntryPoint // Invoke EntryPoint
JuiceAgent::Agent& agent = JuiceAgent::Agent::instance(); JuiceAgent::Agent& agent = JuiceAgent::Agent::instance();
agent.init(jvm, env, jvmti); agent.init(jvm, env, jvmti, runtime_dir);
return JNI_TRUE; return JNI_TRUE;
} }
+10
View File
@@ -0,0 +1,10 @@
#pragma once
#include "event/event_type.hpp"
namespace JuiceAgent::Bytecodes {
void register_bytecodes();
void capture_bytecodes(const EventClassFileLoadHook& e);
void patch_bytecodes(const EventClassFileLoadHook& e);
}
@@ -10,10 +10,10 @@ extern "C" {
/* /*
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent * Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
* Method: init * Method: init
* Signature: ()Z * Signature: (Ljava/lang/String;)Z
*/ */
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init
(JNIEnv *, jclass); (JNIEnv *, jclass, jstring);
/* /*
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent * Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
@@ -0,0 +1,30 @@
#pragma once
#include <jni_impl.hpp>
// ClassFileLoadHook
struct EventClassFileLoadHook {
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;
};
// JuiceAgent PreLoad/PostLoad
struct EventPreLoad {
JavaVM* jvm;
JNIEnv* env;
jvmtiEnv* jvmti;
};
struct EventLoaded {
JavaVM* jvm;
JNIEnv* env;
jvmtiEnv* jvmti;
};
+69
View File
@@ -0,0 +1,69 @@
#pragma once
#include <eventpp/eventdispatcher.h>
#include <unordered_map>
#include <functional>
#include <memory>
#include <mutex>
#include <typeindex>
class EventBus {
public:
template<typename Event>
using Listener = std::function<void(const Event&)>;
template<typename Event>
void subscribe(Listener<Event> listener, int priority = 0) {
std::lock_guard<std::mutex> lock(mutex_);
auto& dispatcher = getDispatcher<Event>();
dispatcher.appendListener(priority, std::move(listener));
}
template<typename Event>
void clear() {
std::lock_guard<std::mutex> lock(mutex_);
dispatchers_.erase(std::type_index(typeid(Event)));
}
template<typename Event>
void post(const Event& event) {
std::shared_ptr<void> dispatcherPtr;
{
std::lock_guard<std::mutex> lock(mutex_);
auto it = dispatchers_.find(std::type_index(typeid(Event)));
if(it == dispatchers_.end()) return;
dispatcherPtr = it->second;
}
auto dispatcher = std::static_pointer_cast<
eventpp::EventDispatcher<int, void(const Event&)>
>(dispatcherPtr);
dispatcher->dispatch(0, event);
}
private:
std::mutex mutex_;
std::unordered_map<std::type_index, std::shared_ptr<void>> dispatchers_;
template<typename Event>
eventpp::EventDispatcher<int, void(const Event&)>& getDispatcher() {
auto typeIdx = std::type_index(typeid(Event));
auto it = dispatchers_.find(typeIdx);
if(it == dispatchers_.end()) {
auto dispatcher = std::make_shared<
eventpp::EventDispatcher<int, void(const Event&)>
>();
dispatchers_[typeIdx] = dispatcher;
return *dispatcher;
}
return *std::static_pointer_cast<
eventpp::EventDispatcher<int, void(const Event&)>
>(it->second);
}
};
+13 -1
View File
@@ -3,12 +3,19 @@
#include <JuiceAgent/Logger.hpp> #include <JuiceAgent/Logger.hpp>
#include <jni.h> #include <jni.h>
#include <jvmti.h> #include <jvmti.h>
#include <event/eventbus.hpp>
#include <JuiceAgent/Config.hpp>
#include <modules/ModuleManager.hpp>
namespace JuiceAgent { namespace JuiceAgent {
class Agent { class Agent {
private: private:
JavaVM* jvm; JavaVM* jvm;
jvmtiEnv* jvmti; jvmtiEnv* jvmti;
JNIEnv* env;
EventBus eventbus;
JuiceAgent::Config::Config config;
JuiceAgent::Core::Modules::ModuleManager module_manager;
private: private:
Agent() = default; Agent() = default;
@@ -22,14 +29,19 @@ namespace JuiceAgent {
Agent& operator=(const Agent&) = delete; Agent& operator=(const Agent&) = delete;
// EntryPoint // EntryPoint
bool init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti); bool init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti, std::string& runtime_dir);
// getters // getters
JavaVM* get_jvm() const { return jvm; } JavaVM* get_jvm() const { return jvm; }
jvmtiEnv* get_jvmti() const { return jvmti; } jvmtiEnv* get_jvmti() const { return jvmti; }
JNIEnv* get_env() const { return env; }
EventBus& get_eventbus() { return eventbus; }
JuiceAgent::Config::Config& get_config() { return config; }
// setters // setters
void set_jvm(JavaVM* jvm) { this->jvm = jvm; } void set_jvm(JavaVM* jvm) { this->jvm = jvm; }
void set_jvmti(jvmtiEnv* jvmti) { this->jvmti = jvmti; } void set_jvmti(jvmtiEnv* jvmti) { this->jvmti = jvmti; }
void set_env(JNIEnv* env) { this->env = env; }
void set_config(JuiceAgent::Config::Config& config) { this->config = config; }
}; };
} }
+17
View File
@@ -0,0 +1,17 @@
#pragma once
#include <string>
namespace JuiceAgent::Core::Modules {
class IModule {
public:
virtual ~IModule() = default;
virtual std::string name() const = 0;
virtual bool init() = 0;
virtual bool start() = 0;
virtual void stop() = 0;
};
}
@@ -0,0 +1,27 @@
#pragma once
#include <memory>
#include <vector>
#include <string>
#include <modules/IModule.hpp>
namespace JuiceAgent::Core::Modules {
class ModuleManager {
public:
ModuleManager() = default;
~ModuleManager() = default;
void register_module(std::unique_ptr<IModule> module);
bool init_all();
bool start_all();
void stop_all();
IModule* find_module(const std::string& name);
private:
std::vector<std::unique_ptr<IModule>> _modules;
};
}
+25
View File
@@ -0,0 +1,25 @@
#pragma once
#include <modules/IModule.hpp>
namespace JuiceAgent::Core::Modules {
class JarLoaderModule : public IModule {
public:
JarLoaderModule() = default;
~JarLoaderModule() override = default;
std::string name() const override {
return "JarLoader";
}
bool init() override;
bool start() override;
void stop() override;
private:
bool _initialized = false;
bool _running = false;
};
}
+92 -50
View File
@@ -1,5 +1,10 @@
#include <libagent.hpp> #include <libagent.hpp>
#include <jni_impl.hpp> #include <jni_impl.hpp>
#include <bytecodes_opt.hpp>
#include <event/event_type.hpp>
#include <event/eventbus.hpp>
#include <JuiceAgent/Config.hpp>
#include <modules/Modules.hpp>
namespace JuiceAgent { namespace JuiceAgent {
// ===== Singleton ===== // ===== Singleton =====
@@ -8,58 +13,95 @@ namespace JuiceAgent {
return instance; return instance;
} }
bool Agent::init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti) { bool Agent::init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti, std::string& runtime_dir) {
PLOGI << "JuiceAgent Native EntryPoint Invoked!"; try {
PLOGI << "JuiceAgent Native EntryPoint Invoked!";
// ======== neccessary environment check ======== // ======== neccessary environment check ========
if (jvm == nullptr) { if (jvm == nullptr) {
PLOGE << "Failed to initialize JuiceAgent: jvm is null"; PLOGE << "Failed to initialize JuiceAgent: jvm is null";
return false;
}
if (env == nullptr) {
PLOGE << "Failed to initialize JuiceAgent: env is null";
return false;
}
if (jvmti == nullptr) {
PLOGE << "Failed to initialize JuiceAgent: jvmti is null";
return false;
}
JuiceAgent::Config::Config cfg (runtime_dir);
if (!cfg.is_valid()) {
PLOGE << "Failed to initialize JuiceAgent: config is invalid";
return false;
}
set_jvm(jvm);
set_jvmti(jvmti);
set_env(env);
set_config(cfg);
PLOGD << "env: " << env << ", jvmti: " << jvmti;
// Register Modules
module_manager.register_module(std::make_unique<JuiceAgent::Core::Modules::JarLoaderModule>());
// Initialize Modules
module_manager.init_all();
// PreLoad Event
eventbus.post(EventPreLoad{
.jvm = jvm,
.env = env,
.jvmti = jvmti
});
// ======== Application ability ========
jvmtiCapabilities caps{};
caps.can_get_bytecodes = 1;
caps.can_redefine_classes = 1;
caps.can_redefine_any_class = 1;
caps.can_retransform_classes = 1;
caps.can_retransform_any_class = 1;
caps.can_generate_all_class_hook_events = 1;
jint result = jvmti->AddCapabilities(&caps);
if (result != JNI_OK) {
PLOGE << "Failed to add capabilities: " << result;
return false;
}
PLOGI << "Abilities added successfully";
// ======== Register callbacks ========
jvmtiEventCallbacks callbacks{};
callbacks.ClassFileLoadHook = &ClassFileLoadHook;
result = jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks));
if (result != JNI_OK) {
PLOGE << "Failed to set event callbacks: " << result;
}
// Enable events
result = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, NULL);
if (result != JNI_OK) {
PLOGE << "Failed to enable event notification: " << result;
}
// register bytecodes_opt
JuiceAgent::Bytecodes::register_bytecodes();
// Start Modules
module_manager.start_all();
// Loaded Event
eventbus.post(EventLoaded{
.jvm = jvm,
.env = env,
.jvmti = jvmti
});
return true;
} catch (const std::exception& e) {
PLOGE << "Exception: " << e.what();
return false; return false;
} }
if (env == nullptr) {
PLOGE << "Failed to initialize JuiceAgent: env is null";
return false;
}
if (jvmti == nullptr) {
PLOGE << "Failed to initialize JuiceAgent: jvmti is null";
return false;
}
set_jvm(jvm);
set_jvmti(jvmti);
PLOGD << "env: " << env << ", jvmti: " << jvmti;
// ======== Application ability ========
jvmtiCapabilities caps{};
caps.can_get_bytecodes = 1;
caps.can_redefine_classes = 1;
caps.can_redefine_any_class = 1;
caps.can_retransform_classes = 1;
caps.can_retransform_any_class = 1;
caps.can_generate_all_class_hook_events = 1;
jint result = jvmti->AddCapabilities(&caps);
if (result != JNI_OK) {
PLOGE << "Failed to add capabilities: " << result;
return false;
}
PLOGI << "Abilities added successfully";
// ======== Register callbacks ========
jvmtiEventCallbacks callbacks{};
callbacks.ClassFileLoadHook = &ClassFileLoadHook;
result = jvmti->SetEventCallbacks(&callbacks, sizeof(callbacks));
if (result != JNI_OK) {
PLOGE << "Failed to set event callbacks: " << result;
}
// Enable events
result = jvmti->SetEventNotificationMode(JVMTI_ENABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, NULL);
if (result != JNI_OK) {
PLOGE << "Failed to enable event notification: " << result;
}
return true;
} }
} }
+87
View File
@@ -0,0 +1,87 @@
#include <modules/Modules.hpp>
#include <JuiceAgent/Logger.hpp>
#include <libagent.hpp>
#include <JuiceAgent/Utils.hpp>
namespace JuiceAgent::Core::Modules {
struct _Config {
bool Enabled = true;
std::string InjectionDir;
std::string JarPath;
std::string EntryClass;
std::string EntryMethod;
} Config;
static JuiceAgent::Agent& agent = JuiceAgent::Agent::instance();
static const char* MODULE_CLASS = "cn/xiaozhou233/juiceagent/api/modules/JarLoader";
static const char* MODULE_METHOD = "loadJar";
bool JarLoaderModule::init() {
if (_initialized) return true;
PLOGI << "JarLoader init";
JuiceAgent::Config::Config& cfg = agent.get_config();
Config.Enabled = cfg.get<bool>("JuiceAgent.Modules.JarLoader.Enabled", false);
Config.InjectionDir = cfg.get<std::string>("JuiceAgent.Modules.JarLoader.InjectionDir", (agent.get_config().runtime_dir() / "injection").string(), true);
Config.JarPath = cfg.get<std::string>("JuiceAgent.Modules.JarLoader.JarPath", "./Entry.jar", true);
Config.EntryClass = cfg.get<std::string>("JuiceAgent.Modules.JarLoader.EntryClass", "Example.Main", false);
Config.EntryMethod = cfg.get<std::string>("JuiceAgent.Modules.JarLoader.EntryMethod", "start", false);
PLOGD << ">>> JarLoader Config <<<";
PLOGD << "Enabled: " << Config.Enabled;
PLOGD << "InjectionDir: " << Config.InjectionDir;
PLOGD << "JarPath: " << Config.JarPath;
PLOGD << "EntryClass: " << Config.EntryClass;
PLOGD << "EntryMethod: " << Config.EntryMethod;
PLOGD << ">>> JarLoader Config <<<";
_initialized = true;
return true;
}
bool JarLoaderModule::start() {
if (!_initialized) return false;
if (_running) return true;
PLOGI << "JarLoader start";
if (!Config.Enabled) {
PLOGI << "JarLoader is disabled";
return false;
}
if (Config.InjectionDir.empty() || Config.JarPath.empty() || Config.EntryClass.empty() || Config.EntryMethod.empty()) {
PLOGE << "JarLoader config is invalid";
return false;
}
JuiceAgent::Utils::Serializer ser;
ser.add_kv("InjectionDir", Config.InjectionDir);
ser.add_kv("JarPath", Config.JarPath);
ser.add_kv("EntryClass", Config.EntryClass);
ser.add_kv("EntryMethod", Config.EntryMethod);
std::string serialized = ser.serialize();
PLOGD << "Serialized config: " << serialized;
JNIEnv* env = agent.get_env();
JuiceAgent::Utils::call_java_impl(env, MODULE_CLASS, MODULE_METHOD, serialized.c_str());
PLOGI << "JarLoader is running";
_running = true;
return true;
}
void JarLoaderModule::stop() {
if (!_running) return;
PLOGI << "JarLoader stop";
_running = false;
}
}
+52
View File
@@ -0,0 +1,52 @@
#include <modules/ModuleManager.hpp>
#include <JuiceAgent/Logger.hpp>
namespace JuiceAgent::Core::Modules {
void ModuleManager::register_module(std::unique_ptr<IModule> module) {
if (!module) return;
PLOGI << "Register module: " << module->name();
_modules.push_back(std::move(module));
}
bool ModuleManager::init_all() {
for (auto& module : _modules) {
PLOGI << "Init module: " << module->name();
if (!module->init()) {
PLOGE << "Failed to init module: " << module->name();
return false;
}
}
return true;
}
bool ModuleManager::start_all() {
for (auto& module : _modules) {
PLOGI << "Start module: " << module->name();
if (!module->start()) {
PLOGE << "Failed to start module: " << module->name();
return false;
}
}
return true;
}
void ModuleManager::stop_all() {
for (auto it = _modules.rbegin(); it != _modules.rend(); ++it) {
(*it)->stop();
}
}
IModule* ModuleManager::find_module(const std::string& name) {
for (auto& module : _modules) {
if (module->name() == name) {
return module.get();
}
}
return nullptr;
}
}
@@ -1,40 +1,13 @@
#include <JuiceAgent/Logger.hpp> #include <JuiceAgent/Logger.hpp>
#include <libloader.hpp> #include <Loader.hpp>
#include <config.hpp> #include <JuiceAgent/Config.hpp>
#include <jvm.hpp> #include <JvmManager.hpp>
#include <JuiceAgent/Utils.hpp>
namespace libloader { namespace JuiceAgent::Loader {
namespace {
// Check for JNI exceptions and clear them
bool check_and_clear_exception(JNIEnv* env, const char* context) {
if (env->ExceptionCheck()) {
PLOGE << "JNI Exception occurred at: " << context;
env->ExceptionDescribe();
env->ExceptionClear();
return true;
}
return false;
}
// RAII wrapper for local JNI references
template<typename T>
class LocalRef {
private:
JNIEnv* env;
T ref;
public:
LocalRef(JNIEnv* env, T ref) : env(env), ref(ref) {}
~LocalRef() {
if (ref) env->DeleteLocalRef(ref);
}
T get() const { return ref; }
operator T() const { return ref; }
};
}
// Invoke JuiceAgentBootstrap.start(String) via JNI // Invoke JuiceAgentBootstrap.start(String) via JNI
bool invoke_juiceagent_init(JNIEnv* env, const InjectionInfo& info) { bool invoke_juiceagent_init(JNIEnv* env, const LoaderConfig& config) {
const char* bootstrap_class = "cn/xiaozhou233/juiceagent/api/JuiceAgentBootstrap"; const char* bootstrap_class = "cn/xiaozhou233/juiceagent/api/JuiceAgentBootstrap";
const char* method_name = "start"; const char* method_name = "start";
const char* method_desc = "(Ljava/lang/String;)V"; const char* method_desc = "(Ljava/lang/String;)V";
@@ -54,7 +27,7 @@ bool invoke_juiceagent_init(JNIEnv* env, const InjectionInfo& info) {
} }
// Serialize InjectionInfo to string // Serialize InjectionInfo to string
std::string args = config::Config::serialize(info); std::string args = JuiceAgent::Config::Utils::serialize_loader_config(config);
PLOGD << "Invoke args: " << args; PLOGD << "Invoke args: " << args;
// Create Java string // Create Java string
@@ -83,23 +56,27 @@ void entrypoint(const char* runtime_dir) {
} }
// Load configuration // Load configuration
config::Config cfg(runtime_dir); JuiceAgent::Config::Config cfg(runtime_dir);
if (!cfg.is_valid()) { if (!cfg.is_valid()) {
PLOGW << "Invalid config, using default values"; PLOGW << "Invalid config, using default values";
// TODO: Use default values
// Before impl TODO, must return, or crash will happen
return;
} }
// Get InjectionInfo // Get InjectionInfo
InjectionInfo info = cfg.get_injection_info(); LoaderConfig config = JuiceAgent::Config::Utils::get_loader_config(cfg);
config::print_injection_info(info); JuiceAgent::Config::Utils::print_loader_config(config);
// Validate essential paths // Validate essential paths
if (info.JuiceAgentAPIJarPath.empty()) { if (config.JuiceAgentAPIJarPath.empty()) {
PLOGE << "JuiceAgentAPIJarPath is empty, abort injection"; PLOGE << "JuiceAgentAPIJarPath is empty, abort injection";
return; return;
} }
// Attach to JVM // Attach to JVM
jvm::Jvm jvm; JuiceAgent::Loader::JvmManager::Jvm jvm;
if (!jvm.attach()) { if (!jvm.attach()) {
PLOGE << "Attach to JVM failed"; PLOGE << "Attach to JVM failed";
return; return;
@@ -114,18 +91,18 @@ void entrypoint(const char* runtime_dir) {
} }
// Inject JuiceAgent jar into system class loader // Inject JuiceAgent jar into system class loader
jint status = jvmti->AddToSystemClassLoaderSearch(info.JuiceAgentAPIJarPath.c_str()); jint status = jvmti->AddToSystemClassLoaderSearch(config.JuiceAgentAPIJarPath.c_str());
if (status != JNI_OK) { if (status != JNI_OK) {
PLOGE << "AddToSystemClassLoaderSearch failed: " << status; PLOGE << "AddToSystemClassLoaderSearch failed: " << status;
return; return;
} }
PLOGI << "Jar injected successfully: " << info.JuiceAgentAPIJarPath; PLOGI << "Jar injected successfully: " << config.JuiceAgentAPIJarPath;
// Invoke JuiceAgent initialization // Invoke JuiceAgent initialization
if (!invoke_juiceagent_init(env, info)) { if (!invoke_juiceagent_init(env, config)) {
PLOGE << "invoke_juiceagent_init failed"; PLOGE << "invoke_juiceagent_init failed";
} }
} }
} // namespace libloader } // namespace JuiceAgent::Loader
-246
View File
@@ -1,246 +0,0 @@
#include <jvm/jni.h>
#include <jvm/jvmti.h>
#include <stdio.h>
#include <JuiceAgent/Logger.hpp>
#include <libloader.h>
#include <thread>
#include <tinytoml/toml.h>
#include <JuiceAgent/JuiceAgent.h>
struct _JuiceAgent {
bool isAttached;
JavaVM *jvm;
jvmtiEnv *jvmti;
JNIEnv *env;
} JuiceAgent = {false, NULL, NULL, NULL};
InjectionInfoType InjectionInfo;
static int ReadConfig(const char* ConfigDir)
{
// ConfigDir/config.toml
std::string path = std::string(ConfigDir) + "\\config.toml";
std::ifstream ifs(path);
if (!ifs) return -1;
// Parse toml
toml::ParseResult pr = toml::parse(ifs);
if (!pr.valid()) return -2;
const toml::Value& tbl = pr.value;
// Helper function: get string from toml
auto get_str = [&](const char* key, const char* def, char* out) {
const toml::Value* v = tbl.find(key);
if (v && v->is<std::string>()) {
std::string s = v->as<std::string>();
if (!s.empty()) {
strncpy(out, s.c_str(), INJECT_PATH_MAX - 1);
PLOGD << "Found parameter: " << key << " = " << s.c_str();
} else {
strncpy(out, def, INJECT_PATH_MAX - 1);
PLOGD << "Parameter " << key << " is empty, use default: " << def;
}
} else {
strncpy(out, def, INJECT_PATH_MAX - 1);
PLOGD << "Not found parameter: " << key << ", use default: " << def;
}
out[INJECT_PATH_MAX - 1] = '\0';
};
// Default values
std::string defaultJuiceLoader = std::string(ConfigDir) + "\\JuiceLoader.jar";
std::string defaultJuiceLoaderLibrary = std::string(ConfigDir) + "\\libjuiceloader.dll";
std::string defaultEntryJar = std::string(ConfigDir) + "\\Entry.jar";
std::string defaultInjectionDir = std::string(ConfigDir) + "\\injection";
get_str("JuiceLoaderJarPath", defaultJuiceLoader.c_str(), InjectionInfo.JuiceLoaderJarPath);
get_str("JuiceLoaderLibraryPath", defaultJuiceLoaderLibrary.c_str(), InjectionInfo.JuiceLoaderLibraryPath);
get_str("InjectionDir", defaultInjectionDir.c_str(), InjectionInfo.InjectionDir);
get_str("EntryJarPath", defaultEntryJar.c_str(), InjectionInfo.EntryJarPath);
get_str("EntryClass", "cn.xiaozhou233.test.Entry", InjectionInfo.EntryClass);
get_str("EntryMethod", "start", InjectionInfo.EntryMethod);
PLOGD << "JuiceLoaderJarPath: " << InjectionInfo.JuiceLoaderJarPath;
PLOGD << "JuiceLoaderLibraryPath: " << InjectionInfo.JuiceLoaderLibraryPath;
PLOGD << "InjectionDir: " << InjectionInfo.InjectionDir;
PLOGD << "EntryJarPath: " << InjectionInfo.EntryJarPath;
PLOGD << "EntryClass: " << InjectionInfo.EntryClass;
PLOGD << "EntryMethod: " << InjectionInfo.EntryMethod;
return 0;
}
static int GetJavaEnv() {
jint res = JNI_ERR;
JavaVM *jvm = NULL;
jvmtiEnv *jvmti = NULL;
JNIEnv *env = NULL;
int max_try = 30;
// Get the JVM
max_try = 30;
do {
res = JNI_GetCreatedJavaVMs(&jvm, 1, NULL);
if (res != JNI_OK || jvm == NULL) {
PLOGE.printf("JNI_GetCreatedJavaVMs failed: %d", res);
PLOGD << "JVM NULL: " << (jvm == NULL);
}
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
max_try--;
if (jvm != NULL) {
break;
} else {
PLOGI.printf("Waiting for JVM... (%d)", max_try);
}
} while (jvm == NULL && max_try > 0);
if (jvm == NULL) {
PLOGE << "GetJavaEnv failed";
return res;
}
JuiceAgent.jvm = jvm;
PLOGI << "Got the JVM";
// Get the JNIEnv
max_try = 30;
do {
res = jvm->GetEnv((void**)&env, JNI_VERSION_1_8);
if (res != JNI_OK || env == NULL) {
PLOGI << "GetEnv failed, trying to attach.";
PLOGD << "env NULL: " << (env == NULL);
res = jvm->AttachCurrentThread((void**)&env, NULL);
if (res != JNI_OK || env == NULL) {
PLOGE.printf("AttachCurrentThread failed: %d", res);
PLOGD << "env NULL: " << (env == NULL);
return res;
}
}
std::this_thread::sleep_for(std::chrono::milliseconds(1000));
max_try--;
if (env != NULL) {
break;
} else {
PLOGI.printf("Waiting for JNI... (%d)", max_try);
}
} while (env == NULL && max_try > 0);
if (env == NULL) {
PLOGE << "Get JNI failed";
return res;
}
JuiceAgent.env = env;
PLOGI << "Got the JNIEnv";
// Get the JVMTI
res = jvm->GetEnv((void**)&jvmti, JVMTI_VERSION_1_2);
if (res != JNI_OK || jvmti == NULL) {
PLOGE.printf("GetEnv failed: %d", res);
PLOGD << "jvmti NULL: " << (jvmti == NULL);
return res;
}
JuiceAgent.jvmti = jvmti;
PLOGI << "Got the JVMTI";
return 0;
}
static int InvokeJuiceLoaderInit(const char* ConfigDir) {
// Variables
int result = JNI_ERR;
JNIEnv *env = JuiceAgent.env;
jvmtiEnv *jvmti = JuiceAgent.jvmti;
const char *bootstrap_class = "cn/xiaozhou233/juiceloader/JuiceLoaderBootstrap";
const char *method_name = "init";
const char *method_signature = "([Ljava/lang/String;)V";
PLOGI << "Invoke JuiceLoader Init";
PLOGI << "================ JuiceLoader Init =================";
// Find class
jclass cls = env->FindClass(bootstrap_class);
if (cls == NULL) {
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
env->ExceptionClear();
}
PLOGE << "FindClass failed";
return 1;
}
// Find method
jmethodID mid = env->GetStaticMethodID(cls, method_name, method_signature);
if (mid == NULL) {
PLOGE << "GetStaticMethodID failed";
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
env->ExceptionClear();
}
return 1;
}
// arguments array
const char* args[] = {
InjectionInfo.EntryJarPath,
InjectionInfo.EntryClass,
InjectionInfo.EntryMethod,
InjectionInfo.InjectionDir,
InjectionInfo.JuiceLoaderLibraryPath
};
int argCount = sizeof(args)/sizeof(args[0]);
jclass stringCls = env->FindClass("java/lang/String");
jobjectArray jArgs = env->NewObjectArray(argCount, stringCls, nullptr);
for (int i = 0; i < argCount; i++) {
env->SetObjectArrayElement(jArgs, i, env->NewStringUTF(args[i]));
}
// Invoke method
env->CallStaticVoidMethod(cls, mid, jArgs);
if (env->ExceptionCheck()) {
env->ExceptionDescribe();
env->ExceptionClear();
}
PLOGI << "================ JuiceLoader Init =================";
PLOGI << "Invoke JuiceLoader Init done";
return 0;
}
extern "C" __declspec(dllexport)
bool InitJuiceAgent(const char* runtime_path) {
PLOGD << "runtime_path: " << runtime_path;
// Read Config
if (ReadConfig(runtime_path) != 0) {
PLOGE << "ReadConfig failed";
return false;
}
PLOGI << "[OK] ReadConfig";
// Get JavaEnv
if (GetJavaEnv() != 0) {
PLOGE << "GetJavaEnv failed";
return false;
}
PLOGI << "[OK] Get JavaEnv";
// Inject JuiceLoader jar
if (JuiceAgent.jvmti->AddToSystemClassLoaderSearch(InjectionInfo.JuiceLoaderJarPath) != JNI_OK) {
PLOGE << "AddToSystemClassLoaderSearch failed";
return false;
}
PLOGI << "[OK] Inject JuiceLoader jar";
// Invoke JuiceLoader Init
if (InvokeJuiceLoaderInit(runtime_path) != 0) {
PLOGE << "Invoke JuiceLoader Init failed";
return false;
}
PLOGI << "[OK] Invoke JuiceLoader Init";
// Load JuiceLoaderLibrary
PLOGI << "--------> InitJuiceAgent Succeed <--------";
return true;
}
@@ -6,7 +6,7 @@
#include <thread> #include <thread>
#include <chrono> #include <chrono>
namespace jvm namespace JuiceAgent::Loader::JvmManager
{ {
class Jvm { class Jvm {
private: private:
@@ -119,4 +119,4 @@ namespace jvm
thread_local JNIEnv* Jvm::env = nullptr; thread_local JNIEnv* Jvm::env = nullptr;
} // namespace jvm } // namespace JuiceAgent::Loader::JvmManager
+31
View File
@@ -0,0 +1,31 @@
#pragma once
#include <JuiceAgent/JuiceAgent.hpp>
#include <string>
#include <JuiceAgent/Logger.hpp>
#include <jvm/jni.h>
#include <jvm/jvmti.h>
namespace JuiceAgent::Loader
{
void entrypoint(const char* runtime_dir);
bool invoke_juiceagent_init(JNIEnv* env, const LoaderConfig& info);
} // namespace JuiceAgent::Loader
namespace {
// RAII wrapper for local JNI references
template<typename T>
class LocalRef {
private:
JNIEnv* env;
T ref;
public:
LocalRef(JNIEnv* env, T ref) : env(env), ref(ref) {}
~LocalRef() {
if (ref) env->DeleteLocalRef(ref);
}
T get() const { return ref; }
operator T() const { return ref; }
};
}
-195
View File
@@ -1,195 +0,0 @@
#pragma once
#include <JuiceAgent/Logger.hpp>
#include <JuiceAgent/JuiceAgent.hpp>
#include <tinytoml/toml.h>
#include <filesystem>
#include <fstream>
#include <string>
namespace config {
class Config {
private:
std::string runtime_dir; // Runtime directory
toml::Value config{}; // Parsed TOML configuration
bool valid = false; // Whether the config is successfully loaded
// Escape special characters ';' = '\'
static std::string escape(const std::string& s) {
std::string out;
out.reserve(s.size());
for (char c : s) {
if (c == ';' || c == '=' || c == '\\') {
out += '\\';
}
out += c;
}
return out;
}
// Append key=value pair to string
static void append_kv(std::string& out, const char* key, const std::string& value, bool& first) {
if (!first) out += ';';
first = false;
out += key;
out += '=';
out += escape(value);
}
// Helper function: find value by dot-separated key
const toml::Value* find_value(const std::string& key) const {
if (!valid) return nullptr;
const toml::Value* current = &config;
size_t start = 0;
while (true) {
size_t dot = key.find('.', start);
std::string part = key.substr(start, dot - start);
if (!current->is<toml::Table>()) return nullptr;
const auto& table = current->as<toml::Table>();
auto it = table.find(part);
if (it == table.end()) return nullptr;
current = &it->second;
if (dot == std::string::npos) break;
start = dot + 1;
}
return current;
}
public:
explicit Config(const char* c_runtime_dir)
: runtime_dir(c_runtime_dir ? c_runtime_dir : "")
{
if (runtime_dir.empty()) {
PLOGW << "runtime_dir is empty";
return;
}
std::filesystem::path path = std::filesystem::path(runtime_dir) / "config.toml";
std::ifstream ifs(path);
if (!ifs.is_open()) {
PLOGE << "Failed to open config file: " << path;
return;
}
try {
auto pr = toml::parse(ifs);
if (!pr.valid()) {
PLOGE << "Invalid TOML file: " << pr.errorReason;
return;
}
config = pr.value;
valid = true;
} catch (const std::exception& e) {
PLOGE << "TOML parse error: " << e.what();
}
}
// Get value by key with default
template<typename T>
T get_or_default(const std::string& key, const T& default_value, bool use_default_if_empty = false, bool is_path = false) const {
const toml::Value* val = find_value(key);
if (!val) return default_value;
try {
if constexpr (std::is_same_v<T, std::string>) {
std::string s = val->as<std::string>();
if (use_default_if_empty && s.empty()) return default_value;
// Check if string starts with '.'
if (is_path && s.starts_with('.')) {
// remove '.'
s.erase(0, 1);
// Check if string starts with '/'
// MUST REMOVE '/', or it will cause path error (root directory)
if (s.starts_with('/')) {
s.erase(0, 1);
}
// runtime_dir + s
s = (std::filesystem::path(runtime_dir) / s).string();
}
return s;
} else {
return val->as<T>();
}
} catch (...) {
return default_value;
}
}
bool is_valid() const {
return valid;
}
// Get InjectionInfo struct from config
InjectionInfo get_injection_info() const {
InjectionInfo info;
auto get_default_path = [&](const std::string& name) {
return (std::filesystem::path(runtime_dir) / name).string();
};
info.JuiceAgentAPIJarPath = get_or_default<std::string>(
"JuiceAgent.JuiceAgentAPIJarPath", get_default_path("JuiceAgent-API.jar"), true, true);
info.JuiceAgentNativePath = get_or_default<std::string>(
"JuiceAgent.JuiceAgentNativePath", get_default_path("libagent.dll"), true, true);
info.EntryJarPath = get_or_default<std::string>(
"Entry.EntryJarPath", get_default_path("Entry.jar"), true, true);
info.EntryClass = get_or_default<std::string>(
"Entry.EntryClass", "com.example.Entry", true, false);
info.EntryMethod = get_or_default<std::string>(
"Entry.EntryMethod", "start", true, false);
info.InjectionDir = get_or_default<std::string>(
"Runtime.InjectionDir", get_default_path("injection"), true, true);
return info;
}
// Serialize InjectionInfo to key=value; format
static std::string serialize(const InjectionInfo& info) {
std::string result;
result.reserve(256);
bool first = true;
append_kv(result, "Version", "1", first);
append_kv(result, "EntryJarPath", info.EntryJarPath, first);
append_kv(result, "EntryClass", info.EntryClass, first);
append_kv(result, "EntryMethod", info.EntryMethod, first);
append_kv(result, "JuiceAgentAPIJarPath", info.JuiceAgentAPIJarPath, first);
append_kv(result, "JuiceAgentNativePath", info.JuiceAgentNativePath, first);
append_kv(result, "InjectionDir", info.InjectionDir, first);
PLOGD << "Serialized args: " << result;
return result;
}
std::string serialize() const {
return serialize(get_injection_info());
}
};
// Print InjectionInfo (debug)
inline void print_injection_info(const InjectionInfo& info) {
PLOGI << "JuiceAgent Injection Info:";
PLOGI << " JuiceAgentAPIJarPath: " << info.JuiceAgentAPIJarPath;
PLOGI << " JuiceAgentNativePath: " << info.JuiceAgentNativePath;
PLOGI << " EntryJarPath: " << info.EntryJarPath;
PLOGI << " EntryClass: " << info.EntryClass;
PLOGI << " EntryMethod: " << info.EntryMethod;
PLOGI << " InjectionDir: " << info.InjectionDir;
}
} // namespace config
-14
View File
@@ -1,14 +0,0 @@
#pragma once
#include <JuiceAgent/JuiceAgent.hpp>
#include <string>
#include <JuiceAgent/Logger.hpp>
#include <jvm/jni.h>
#include <jvm/jvmti.h>
namespace libloader
{
void entrypoint(const char* runtime_dir);
bool invoke_juiceagent_init(JNIEnv* env, const InjectionInfo& info);
} // namespace libloader
+2 -2
View File
@@ -1,6 +1,6 @@
#include <windows.h> #include <windows.h>
#include <JuiceAgent/Logger.hpp> #include <JuiceAgent/Logger.hpp>
#include <libloader.hpp> #include <Loader.hpp>
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) { BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) {
switch( fdwReason ) switch( fdwReason )
@@ -11,7 +11,7 @@ BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD fdwReason, LPVOID lpReserved ) {
const char* runtime_dir = (const char*)lpReserved; const char* runtime_dir = (const char*)lpReserved;
libloader::entrypoint(runtime_dir); JuiceAgent::Loader::entrypoint(runtime_dir);
break; break;
} }