mirror of
https://github.com/xiaozhou233/JuiceAgent.git
synced 2026-12-05 13:05:53 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c20ec1e839 | ||
|
|
f8be8cb795 | ||
|
|
eb3a76769d | ||
|
|
49d2499f73 | ||
|
|
a64bbb8bb8 | ||
|
|
011fafb5b0 | ||
|
|
748b118fb1 | ||
|
|
b78839a8d4 | ||
|
|
8894a819f2 | ||
|
|
e25f0c304a | ||
|
|
bbea7b72c3 | ||
|
|
896a856c57 | ||
|
|
c80851adb7 | ||
|
|
49ac4a51a1 | ||
|
|
0d9e5fe836 | ||
|
|
34c8ccd497 | ||
|
|
f73265ac3e | ||
|
|
5e7972779f | ||
|
|
8ad8f45545 | ||
|
|
71965165b9 | ||
|
|
34dbd82a59 | ||
|
|
9aa77848d7 | ||
|
|
ad69f9d11a | ||
|
|
faeaf052b9 | ||
|
|
b0d8b5901f | ||
|
|
4496931bdf | ||
|
|
34cb16d385 | ||
|
|
bad147d898 | ||
|
|
289b0311bf | ||
|
|
1714f7603d | ||
|
|
d6d17aac35 | ||
|
|
6350bfb0ec | ||
|
|
8421d3817a | ||
|
|
3362e2071c | ||
|
|
72c0518ebc | ||
|
|
0a4ec5e97a | ||
|
|
15d7f0295a | ||
|
|
c5817a3b06 | ||
|
|
e5ac60d476 | ||
|
|
3e3f9d1c14 | ||
|
|
3ce1bccf02 | ||
|
|
205e608d60 | ||
|
|
9dab75b5fd | ||
|
|
c9c10686ab | ||
|
|
a110e675c6 | ||
|
|
9b24ea0ae4 | ||
|
|
172f354b04 | ||
|
|
cf49ed0a7b | ||
|
|
ea5ce8258d | ||
|
|
ab9369d8b7 | ||
|
|
2ce6a8e192 | ||
|
|
d8bed79f84 | ||
|
|
6ab3c279aa | ||
|
|
a8c2496292 | ||
|
|
94d881fe63 | ||
|
|
d98e3e818e | ||
|
|
58f76009e4 | ||
|
|
64ca48dfc8 | ||
|
|
4ef94b5ac2 | ||
|
|
339b68c8af | ||
|
|
623445aa5e | ||
|
|
cacdb6a1cd | ||
|
|
f5a6564fd0 | ||
|
|
338f4eb50c | ||
|
|
9b5f29eee4 | ||
|
|
797cf8aed9 | ||
|
|
63c9e55355 | ||
|
|
7f9e381bc3 | ||
|
|
e2a3119af6 | ||
|
|
681a86cb36 | ||
|
|
353fe3e5a5 | ||
|
|
ffaa234bbf | ||
|
|
76055183d2 | ||
|
|
80713ace68 | ||
|
|
01caa4c8cb | ||
|
|
07a71eab12 | ||
|
|
ad827fabff | ||
|
|
ebc557c2f2 | ||
|
|
c4bbbabe07 | ||
|
|
4c184cbb95 | ||
|
|
ffd42c5e30 | ||
|
|
6628b5bfd5 | ||
|
|
56cd994715 | ||
|
|
e3481d007c | ||
|
|
386dc14a01 | ||
|
|
c8c255b233 | ||
|
|
094e7bc0d4 | ||
|
|
acf2cd2c1d | ||
|
|
bd2e9ca730 | ||
|
|
7039e0f914 | ||
|
|
25153d2062 | ||
|
|
eefee5d04d | ||
|
|
df6bc29360 | ||
|
|
9f2782a126 | ||
|
|
21df0346db | ||
|
|
73910150b2 | ||
|
|
8e8f08c986 | ||
|
|
01b437cd9f | ||
|
|
1ea23faab9 | ||
|
|
8966125ad9 | ||
|
|
de971d6481 | ||
|
|
ee97c10702 | ||
|
|
87a1701f22 | ||
|
|
e265e39be9 | ||
|
|
34323a68fe | ||
|
|
39fad40655 | ||
|
|
bf5a6b0804 | ||
|
|
30d379521a | ||
|
|
fe495657d4 | ||
|
|
40707231c0 | ||
|
|
3dc83d83db | ||
|
|
9bb9faacdf | ||
|
|
7cdd3e4b11 |
No files matched your search
@@ -1,7 +0,0 @@
|
||||
[Injection]
|
||||
BootstrapAPIPath = "D:/Development/JuiceLoader/build/libs/bootstrap-api.jar"
|
||||
JuiceLoaderJarPath = "D:/Development/JuiceLoader/build/libs/JuiceLoader.jar"
|
||||
JuiceLoaderLibPath = ""
|
||||
EntryJarPath = "D:/Development/JuiceLoader/build/libs/Entry.jar"
|
||||
EntryClass = "cn.xiaozhou233.juiceloader.entry.Entry"
|
||||
EntryMethod = "start"
|
||||
+7
-24
@@ -1,38 +1,21 @@
|
||||
cmake_minimum_required(VERSION 3.15)
|
||||
project(JuiceAgent LANGUAGES C CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 17)
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
# version
|
||||
set(PROJECT_VERSION_MAJOR 1)
|
||||
set(PROJECT_VERSION_MINOR 3)
|
||||
set(PROJECT_BUILD_NUMBER 35)
|
||||
set(PROJECT_VERSION_STRING "v${PROJECT_VERSION_MAJOR}.${PROJECT_VERSION_MINOR}-b${PROJECT_BUILD_NUMBER}")
|
||||
message(STATUS " ======== Build version: ${PROJECT_VERSION_STRING} ======== ")
|
||||
|
||||
add_compile_definitions(
|
||||
PROJECT_VERSION_MAJOR=${PROJECT_VERSION_MAJOR}
|
||||
PROJECT_VERSION_MINOR=${PROJECT_VERSION_MINOR}
|
||||
PROJECT_BUILD_NUMBER=${PROJECT_BUILD_NUMBER}
|
||||
PROJECT_VERSION_STRING=\"${PROJECT_VERSION_STRING}\")
|
||||
|
||||
# output directories
|
||||
set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
||||
set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
||||
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||
|
||||
# includes
|
||||
set(INCLUDES ${CMAKE_CURRENT_SOURCE_DIR}/includes)
|
||||
set(SRC_DIR ${CMAKE_SOURCE_DIR}/src)
|
||||
link_directories("$ENV{JAVA_HOME}/lib")
|
||||
|
||||
# libraries
|
||||
add_subdirectory(${INCLUDES}/ReflectiveDLLInjection)
|
||||
add_subdirectory(${INCLUDES}/log.c)
|
||||
add_subdirectory(${INCLUDES}/tomlc17)
|
||||
add_subdirectory(src/utils)
|
||||
|
||||
include(cmake/JuiceModule.cmake)
|
||||
add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection)
|
||||
|
||||
# modules
|
||||
add_juice_module(agent)
|
||||
add_juice_module(injector)
|
||||
add_subdirectory(${SRC_DIR}/libloader)
|
||||
add_subdirectory(${SRC_DIR}/libinjector)
|
||||
add_subdirectory(${SRC_DIR}/libagent)
|
||||
@@ -1,95 +1,103 @@
|
||||
|
||||
# JuiceAgent
|
||||
[English]() | [中文]()
|
||||
[English](https://github.com/xiaozhou233/JuiceAgent/blob/main/README.md) | [中文](https://github.com/xiaozhou233/JuiceAgent/blob/main/README_zh.md)
|
||||
|
||||
|
||||
JuiceAgent — a JVMTI-based injection library for loading external JARs and transforming Java bytecode, even when DisableAttachMechanism is enabled.
|
||||
|
||||
**NOTICE:** Currently only supports **Windows**, and plans to support **Linux** in the future.
|
||||
|
||||
**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 in the experimental stage and is not recommended for production use.
|
||||
**Disclaimer: This project is for learning and research in controlled environments only. The author is not responsible for any illegal or unauthorized use. Users must ensure their actions are legal. (See Full Disclaimer below)**
|
||||
***免责声明: 本项目仅供受控环境下的学习和研究使用。作者不对任何非法或未授权的使用承担责任。使用者应确保自己的行为合法。(在下方查看完整免责声明)***
|
||||
**Use this at your own risk.**
|
||||
|
||||
## Summary
|
||||
JuiceAgent is a JVMTI-native injection framework that injects native code into a target JVM to dynamically load external JARs and perform bytecode redefinition/transformations without requiring a javaagent (works when DisableAttachMechanism=true).
|
||||
## Features
|
||||
### Injector (src/injector)
|
||||
Reflective injector, can be invoke in java (java/InjectorNative.java)
|
||||
- Inject Dlls. (with no params)
|
||||
- Inject JuiceAgent library. (with params)
|
||||
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)
|
||||
|
||||
### JuiceAgent (src/agent)
|
||||
Minimize loading, inject to target jvm.
|
||||
- Get JVM / JNI / JVMTI
|
||||
- Inject bootstrap-api.jar
|
||||
- Inject JuiceLoader.jar
|
||||
- Invoke Java Function JuiceLoader init
|
||||
- addToBootstrapClassLoaderSearch
|
||||
- addToSystemClassLoaderSearch
|
||||
- addToClassLoader
|
||||
- defineClass
|
||||
- redefineClass(ByName)
|
||||
- retransformClass(ByName)
|
||||
- getLoadedClasses
|
||||
- getClassByName
|
||||
- getClassBytes(ByName)
|
||||
|
||||
### JuiceLoader Native (src/juiceloader)
|
||||
Native library for [JuiceLoader](https://github.com/xiaozhou233/JuiceLoader) , Inject Jars/ Redefine class Low-level implementation.
|
||||
- Get JVM / JNI / JVMTI
|
||||
- Inject Custom Jars
|
||||
- Redefine class
|
||||
- Get Loaded Classes
|
||||
- JNI Function (Can be invoke in java)
|
||||
## How To Use
|
||||
***TODO: Update How to Use***
|
||||
***Notice: Tutorial for Version 1.0***
|
||||
## How To Use (**For Version 3.0 Build 2**)
|
||||
|
||||
### 1. Download Files
|
||||
- Download `libagent`, `libinjector`, and `libjuiceloader` from the Release to the same directory.
|
||||
- Download JARs `bootstrap-api.jar`, `JuiceLoader.jar`, and `Entry.jar` (or your own JAR) to the same directory.
|
||||
### 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 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
|
||||
Create a config file named `AgentConfig.toml` in the same directory. Example:
|
||||
### 2. ✍️ Write Config File
|
||||
Create a config file named `config.toml` in `YourDir`
|
||||
|
||||
```toml
|
||||
[Injection]
|
||||
BootstrapAPIPath = "<YourDir>/bootstrap-api.jar"
|
||||
JuiceLoaderJarPath = "<YourDir>/JuiceLoader.jar"
|
||||
# Leave empty to use the DLL directory (Normal Inject) or the directory passed as parameter (Reflective Inject)
|
||||
JuiceLoaderLibPath = ""
|
||||
EntryJarPath = "<YourDir>/Entry.jar"
|
||||
EntryClass = "entry.class"
|
||||
EntryMethod = "entryMethod"
|
||||
[JuiceAgent]
|
||||
# Default value: YourDir/JuiceAgent-API.jar
|
||||
JuiceAgentAPIJarPath = ""
|
||||
# Default value: YourDir/libagent.dll
|
||||
JuiceAgentNativePath = ""
|
||||
|
||||
[Entry]
|
||||
# Default value: YourDir/Entry.jar
|
||||
EntryJarPath = ""
|
||||
# Default value: com.example.Entry
|
||||
EntryClass = ""
|
||||
# Default value: start
|
||||
EntryMethod = "start"
|
||||
|
||||
[Runtime]
|
||||
# Default value: YourDir/injection
|
||||
InjectionDir = ""
|
||||
```
|
||||
| Method| Usage|
|
||||
| - | -|
|
||||
| **Reflective Inject** | Uses `libinjector`. Pass the config directory as a parameter. </br> Example: config file at `<YourDir>/AgentConfig.toml`, pass `<YourDir>` as parameter. If a key is empty (e.g., `BootstrapAPIPath = ""`), it defaults to `<DirA>/default-name` (e.g., `<DirA>/bootstrap-api.jar`). |
|
||||
| **Normal Inject** | Uses `LoadLibraryA + CreateRemoteThread`. Keep `AgentConfig.toml` and all DLLs/JARs in the same directory.
|
||||
|
||||
### 3. Invoke Inject Function
|
||||
C/C++ Use libinjector and invoke inject(int pid, char* path, InjectParameters *params)
|
||||
### 3. 💉 Run Injector
|
||||
#### **Method A** : Use `injector.exe`
|
||||
Run `injector.exe`
|
||||
```
|
||||
114514 loop
|
||||
Input PID:
|
||||
```
|
||||
|
||||
Java Use `Injecor.jar`: `java -jar Injecor.jar` or
|
||||
```
|
||||
package cn.xiaozhou233.juiceagent.injector;
|
||||
Input PID of target process and press Enter
|
||||
|
||||
#### **Method B** : Use JNI to call `inject` function
|
||||
Create a file named cn/xiaozhou233/juiceagent/injector.java in your project
|
||||
```java
|
||||
package cn.xiaozhou233.juiceagent.injector;
|
||||
|
||||
public class InjectorNative {
|
||||
/*
|
||||
* @param pid target process id
|
||||
*/
|
||||
public native boolean inject(int pid, String path);
|
||||
/*
|
||||
* @param pid target process id
|
||||
*/
|
||||
public native boolean inject(int pid, String path);
|
||||
|
||||
/*
|
||||
* @param pid target process id
|
||||
* @param path injection dll path
|
||||
* @param configPath config file path
|
||||
*/
|
||||
public native boolean inject(int pid, String path, String configPath);
|
||||
/*
|
||||
* @param pid target process id
|
||||
* @param path injection dll path
|
||||
* @param configPath config file path
|
||||
*/
|
||||
public native boolean inject(int pid, String path, String configPath);
|
||||
}
|
||||
```
|
||||
```
|
||||
Then write it down somewhere
|
||||
```java
|
||||
// Your class
|
||||
import cn.xiaozhou233.juiceagent.injector.InjectorNative;
|
||||
|
||||
System.load("<path-to-libinjector>");
|
||||
System.load("<path-to-libinject>");
|
||||
InjectorNative injectorNative = new InjectorNative();
|
||||
|
||||
injectorNative.inject(<pid>, "<path-to-libagent>", "<path-to-toml-config-dir>");
|
||||
injectorNative.inject(<pid>, "<path-to-libloader>", "<path-to-toml-config-dir>");
|
||||
```
|
||||
### 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)
|
||||
|
||||
### 4. Done!
|
||||
If the injection is successful, EntryClass .EntryMethod() of <EntryJarPath> will be executed.
|
||||
## Hot To Build
|
||||
### Environment
|
||||
- Java 8+
|
||||
@@ -103,9 +111,10 @@ cd JuiceAgent
|
||||
mkdir -p build
|
||||
cmake --build build --
|
||||
```
|
||||
dlls: build/bin/
|
||||
|
||||
jars: see [JuiceLoader](https://github.com/xiaozhou233/JuiceLoader)
|
||||
Dlls will be generated in `build/bin` directory
|
||||
|
||||
Jars can be build or download in project [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API)
|
||||
|
||||
## Full Disclaimer/ 完整免责声明
|
||||
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.
|
||||
@@ -115,6 +124,6 @@ Disclaimer: This project is intended for learning and research in controlled env
|
||||
## Acknowledgements
|
||||
|
||||
- [ReflectiveDLLInjection](https://github.com/stephenfewer/ReflectiveDLLInjection) - DLL Inject
|
||||
- [log.c](https://github.com/rxi/log.c) - A simple logger system
|
||||
- [tomlc17](https://github.com/cktan/tomlc17) - TOML parser in C17
|
||||
- [plog](https://github.com/SergiusTheBest/plog) - portable, simple and extensible C++ logging library
|
||||
- [tinytoml](https://github.com/mayah/tinytoml) - A header only C++11 library for parsing TOML.
|
||||
|
||||
+177
@@ -0,0 +1,177 @@
|
||||
# JuiceAgent
|
||||
[English](https://github.com/xiaozhou233/JuiceAgent/blob/main/README.md) | [中文](https://github.com/xiaozhou233/JuiceAgent/blob/main/README_zh.md)
|
||||
|
||||
JuiceAgent —— 一个基于 JVMTI 的注入库,用于加载外部 JAR 并对 Java 字节码进行热替换,即使在 DisableAttachMechanism 启用的情况下也可使用。
|
||||
|
||||
**注意:** 当前仅支持 **Windows**,未来计划支持 **Linux**。
|
||||
|
||||
**注意:** **Version 2.3 Build 1** 是当前的 **稳定版本且已停止更新**。3.0 及之后版本已重构,可能存在未知问题。
|
||||
|
||||
**警告:** 本项目仍处于实验阶段,不建议用于生产环境。
|
||||
**使用风险自负。**
|
||||
|
||||
---
|
||||
|
||||
## 简介
|
||||
JuiceAgent 是一个基于 JVMTI 的原生注入框架,通过向目标 JVM 注入代码,实现动态加载外部 JAR 以及字节码热替换,无需使用 javaagent(在 DisableAttachMechanism=true 时仍可工作)。
|
||||
|
||||
---
|
||||
|
||||
## 功能特性
|
||||
|
||||
本项目是 JuiceAgent-API 的Native实现,详细内容请参考:
|
||||
https://github.com/xiaozhou233/JuiceAgent-API/blob/master/src/main/java/cn/xiaozhou233/juiceagent/api/JuiceAgent.java
|
||||
|
||||
- addToBootstrapClassLoaderSearch
|
||||
- addToSystemClassLoaderSearch
|
||||
- addToClassLoader
|
||||
- defineClass
|
||||
- redefineClass(ByName)
|
||||
- retransformClass(ByName)
|
||||
- getLoadedClasses
|
||||
- getClassByName
|
||||
- getClassBytes(ByName)
|
||||
|
||||
---
|
||||
|
||||
## 使用方法(适用于 Version 3.0 Build 2)
|
||||
|
||||
### 1. ⬇️ 下载文件
|
||||
|
||||
- 从 Release 下载:
|
||||
- libagent.dll
|
||||
- libinject.dll
|
||||
- libloader.dll
|
||||
- injector.exe
|
||||
并放入 `YourDir`
|
||||
|
||||
- 从 JuiceAgent-API Release 下载:
|
||||
- JuiceAgent-API-X.X.X+build.X.jar
|
||||
并放入 `YourDir`
|
||||
|
||||
---
|
||||
|
||||
### 2. ✍️ 编写配置文件
|
||||
|
||||
在 `YourDir` 下创建 `config.toml`
|
||||
|
||||
```toml
|
||||
[JuiceAgent]
|
||||
# 默认值: YourDir/JuiceAgent-API.jar
|
||||
JuiceAgentAPIJarPath = ""
|
||||
# 默认值: YourDir/libagent.dll
|
||||
JuiceAgentNativePath = ""
|
||||
|
||||
[Entry]
|
||||
# 默认值: YourDir/Entry.jar
|
||||
EntryJarPath = ""
|
||||
# 默认值: com.example.Entry
|
||||
EntryClass = ""
|
||||
# 默认值: start
|
||||
EntryMethod = "start"
|
||||
|
||||
[Runtime]
|
||||
# 默认值: YourDir/injection
|
||||
InjectionDir = ""
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 3. 💉 执行注入
|
||||
|
||||
#### 方法 A:使用 injector.exe
|
||||
|
||||
运行`inject.exe`:
|
||||
|
||||
```
|
||||
114514 loop
|
||||
Input PID:
|
||||
```
|
||||
|
||||
输入目标进程 PID 后回车
|
||||
|
||||
---
|
||||
|
||||
#### 方法 B:使用 JNI 调用 inject
|
||||
|
||||
创建文件:
|
||||
`cn/xiaozhou233/juiceagent/injector/InjectorNative.java`
|
||||
|
||||
```java
|
||||
package cn.xiaozhou233.juiceagent.injector;
|
||||
|
||||
public class InjectorNative {
|
||||
/*
|
||||
* @param pid target process id
|
||||
*/
|
||||
public native boolean inject(int pid, String path);
|
||||
|
||||
/*
|
||||
* @param pid target process id
|
||||
* @param path injection dll path
|
||||
* @param configPath config file path
|
||||
*/
|
||||
public native boolean inject(int pid, String path, String configPath);
|
||||
}
|
||||
```
|
||||
|
||||
调用示例:
|
||||
|
||||
```java
|
||||
import cn.xiaozhou233.juiceagent.injector.InjectorNative;
|
||||
|
||||
System.load("<path-to-libinject>");
|
||||
InjectorNative injectorNative = new InjectorNative();
|
||||
|
||||
injectorNative.inject(<pid>, "<path-to-libloader>", "<path-to-toml-config-dir>");
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### 4. ✅ 完成
|
||||
|
||||
注入成功后,目标进程将加载:
|
||||
|
||||
- Entry.jar(或配置中的 EntryClass)
|
||||
- 并执行 EntryMethod(默认 start)
|
||||
|
||||
---
|
||||
|
||||
## 如何构建
|
||||
|
||||
### 环境要求
|
||||
|
||||
- Java 8+
|
||||
- MinGW
|
||||
- CMake
|
||||
- Ninja
|
||||
|
||||
```bash
|
||||
git clone https://github.com/xiaozhou233/JuiceAgent.git
|
||||
cd JuiceAgent
|
||||
|
||||
mkdir -p build
|
||||
cmake --build build --
|
||||
```
|
||||
|
||||
生成的 DLL 位于:
|
||||
|
||||
```
|
||||
build/bin
|
||||
```
|
||||
|
||||
JAR 可在 JuiceAgent-API 项目中构建或下载。
|
||||
|
||||
---
|
||||
|
||||
## 完整免责声明
|
||||
|
||||
免责声明:本项目仅建议在受控环境中用于学习与研究。作者不对任何因滥用、破解、修改或违反协议/法律行为所产生的后果负责。使用者需自行确保合法合规,并承担全部责任。
|
||||
|
||||
---
|
||||
|
||||
## 致谢
|
||||
|
||||
- ReflectiveDLLInjection — DLL 注入实现
|
||||
- plog — 轻量级 C++ 日志库
|
||||
- tinytoml — C++11 TOML 解析库
|
||||
@@ -0,0 +1 @@
|
||||
VERSION = Version 3.0 Build 2
|
||||
@@ -1,38 +0,0 @@
|
||||
# JuiceModule.cmake
|
||||
# Function to add a JuiceAgent module (agent, injector, juiceloader)
|
||||
|
||||
function(add_juice_module NAME)
|
||||
link_directories("$ENV{JAVA_HOME}/lib")
|
||||
|
||||
# Collect all source files in module src and utils
|
||||
file(GLOB MODULE_SOURCES
|
||||
"${CMAKE_SOURCE_DIR}/src/${NAME}/*.c"
|
||||
"${CMAKE_SOURCE_DIR}/src/${NAME}/utils/*.c"
|
||||
)
|
||||
|
||||
# Create shared library
|
||||
add_library(${NAME} SHARED ${MODULE_SOURCES})
|
||||
|
||||
# Include directories
|
||||
target_include_directories(${NAME} PRIVATE
|
||||
${CMAKE_SOURCE_DIR}/includes
|
||||
${CMAKE_SOURCE_DIR}/includes/jvm
|
||||
${CMAKE_SOURCE_DIR}/includes/jvm/win32
|
||||
${CMAKE_SOURCE_DIR}/includes/JuiceAgent
|
||||
${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection
|
||||
${CMAKE_SOURCE_DIR}/includes/log.c
|
||||
"${CMAKE_SOURCE_DIR}/src/${NAME}/utils"
|
||||
"${CMAKE_SOURCE_DIR}/src/${NAME}/include"
|
||||
"${CMAKE_SOURCE_DIR}/src/utils"
|
||||
)
|
||||
|
||||
# Link common libraries
|
||||
target_link_libraries(${NAME} PRIVATE
|
||||
ReflectiveDLLInjection
|
||||
log.c
|
||||
jvm
|
||||
utils
|
||||
)
|
||||
|
||||
add_subdirectory("${CMAKE_SOURCE_DIR}/src/${NAME}")
|
||||
endfunction()
|
||||
@@ -1,12 +0,0 @@
|
||||
#ifndef INJECTPARAMETERS_H
|
||||
#define INJECTPARAMETERS_H
|
||||
|
||||
#include <windows.h>
|
||||
|
||||
#define INJECT_PATH_MAX 4096
|
||||
|
||||
typedef struct InjectParameters{
|
||||
char ConfigDir[INJECT_PATH_MAX];
|
||||
} InjectParameters;
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,14 @@
|
||||
#pragma once
|
||||
|
||||
#include <string>
|
||||
|
||||
struct InjectionInfo {
|
||||
std::string JuiceAgentAPIJarPath;
|
||||
std::string JuiceAgentNativePath;
|
||||
|
||||
std::string EntryJarPath;
|
||||
std::string EntryClass;
|
||||
std::string EntryMethod;
|
||||
|
||||
std::string InjectionDir;
|
||||
};
|
||||
@@ -0,0 +1,17 @@
|
||||
// Logger.hpp
|
||||
#pragma once
|
||||
#include <plog/Log.h>
|
||||
#include <plog/Init.h>
|
||||
#include <plog/Formatters/TxtFormatter.h>
|
||||
#include <plog/Appenders/ConsoleAppender.h>
|
||||
#include <plog/Appenders/DebugOutputAppender.h>
|
||||
|
||||
inline void InitLogger()
|
||||
{
|
||||
static plog::ConsoleAppender<plog::TxtFormatter> consoleAppender;
|
||||
static plog::DebugOutputAppender<plog::TxtFormatter> debugAppender;
|
||||
|
||||
plog::init(plog::debug, &consoleAppender).addAppender(&debugAppender);
|
||||
|
||||
PLOG_INFO << "Logger initialized: Console + Debug Output";
|
||||
}
|
||||
@@ -0,0 +1,498 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef CALLBACKLIST_H_588722158669
|
||||
#define CALLBACKLIST_H_588722158669
|
||||
|
||||
#include "eventpolicies.h"
|
||||
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <cassert>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <
|
||||
typename Prototype,
|
||||
typename PoliciesType
|
||||
>
|
||||
class CallbackListBase;
|
||||
|
||||
template <
|
||||
typename PoliciesType,
|
||||
typename ReturnType, typename ...Args
|
||||
>
|
||||
class CallbackListBase<
|
||||
ReturnType (Args...),
|
||||
PoliciesType
|
||||
>
|
||||
{
|
||||
private:
|
||||
using Policies = PoliciesType;
|
||||
|
||||
using Threading = typename SelectThreading<Policies, HasTypeThreading<Policies>::value>::Type;
|
||||
|
||||
using Callback_ = typename SelectCallback<
|
||||
Policies,
|
||||
HasTypeCallback<Policies>::value,
|
||||
std::function<ReturnType (Args...)>
|
||||
>::Type;
|
||||
|
||||
using CanContinueInvoking = typename SelectCanContinueInvoking<
|
||||
Policies, HasFunctionCanContinueInvoking<Policies, Args...>::value
|
||||
>::Type;
|
||||
|
||||
struct Node;
|
||||
using NodePtr = std::shared_ptr<Node>;
|
||||
|
||||
struct Node
|
||||
{
|
||||
using Counter = unsigned int;
|
||||
|
||||
Node(const Callback_ & callback, const Counter counter)
|
||||
: callback(callback), counter(counter)
|
||||
{
|
||||
}
|
||||
|
||||
NodePtr previous;
|
||||
NodePtr next;
|
||||
Callback_ callback;
|
||||
Counter counter;
|
||||
};
|
||||
|
||||
class Handle_ : public std::weak_ptr<Node>
|
||||
{
|
||||
private:
|
||||
using super = std::weak_ptr<Node>;
|
||||
|
||||
public:
|
||||
using super::super;
|
||||
|
||||
operator bool () const noexcept {
|
||||
return ! this->expired();
|
||||
}
|
||||
};
|
||||
|
||||
using Counter = typename Node::Counter;
|
||||
enum : Counter {
|
||||
removedCounter = 0
|
||||
};
|
||||
|
||||
public:
|
||||
using Callback = Callback_;
|
||||
using Handle = Handle_;
|
||||
using Mutex = typename Threading::Mutex;
|
||||
|
||||
public:
|
||||
CallbackListBase() noexcept
|
||||
:
|
||||
head(),
|
||||
tail(),
|
||||
mutex(),
|
||||
currentCounter(0)
|
||||
{
|
||||
}
|
||||
|
||||
CallbackListBase(const CallbackListBase & other)
|
||||
: CallbackListBase()
|
||||
{
|
||||
cloneFrom(other.head);
|
||||
}
|
||||
|
||||
CallbackListBase(CallbackListBase && other) noexcept
|
||||
: CallbackListBase()
|
||||
{
|
||||
swap(other);
|
||||
}
|
||||
|
||||
// If we use pass by value idiom and omit the 'this' check,
|
||||
// when assigning to self there is a deep copy which is inefficient.
|
||||
CallbackListBase & operator = (const CallbackListBase & other) {
|
||||
if(this != &other) {
|
||||
CallbackListBase copied(other);
|
||||
swap(copied);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
CallbackListBase & operator = (CallbackListBase && other) noexcept {
|
||||
if(this != &other) {
|
||||
doFreeAllNodes();
|
||||
|
||||
head = std::move(other.head);
|
||||
tail = std::move(other.tail);
|
||||
currentCounter = other.currentCounter.load();
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
~CallbackListBase() {
|
||||
// Don't lock mutex here since it may throw exception
|
||||
|
||||
doFreeAllNodes();
|
||||
}
|
||||
|
||||
void swap(CallbackListBase & other) noexcept {
|
||||
using std::swap;
|
||||
|
||||
swap(head, other.head);
|
||||
swap(tail, other.tail);
|
||||
|
||||
const auto value = currentCounter.load();
|
||||
currentCounter.exchange(other.currentCounter.load());
|
||||
other.currentCounter.exchange(value);
|
||||
}
|
||||
|
||||
bool empty() const {
|
||||
// Don't lock the mutex for performance reason.
|
||||
// !head still works even when the underlying raw pointer is garbled (for other thread is writting to head)
|
||||
// And empty() doesn't guarantee the list is still empty after the function returned.
|
||||
//std::lock_guard<Mutex> lockGuard(mutex);
|
||||
|
||||
return ! head;
|
||||
}
|
||||
|
||||
operator bool() const {
|
||||
return ! empty();
|
||||
}
|
||||
|
||||
Handle append(const Callback & callback)
|
||||
{
|
||||
NodePtr node(doAllocateNode(callback));
|
||||
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
|
||||
if(head) {
|
||||
node->previous = tail;
|
||||
tail->next = node;
|
||||
tail = node;
|
||||
}
|
||||
else {
|
||||
head = node;
|
||||
tail = node;
|
||||
}
|
||||
|
||||
return Handle(node);
|
||||
}
|
||||
|
||||
Handle prepend(const Callback & callback)
|
||||
{
|
||||
NodePtr node(doAllocateNode(callback));
|
||||
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
|
||||
if(head) {
|
||||
node->next = head;
|
||||
head->previous = node;
|
||||
head = node;
|
||||
}
|
||||
else {
|
||||
head = node;
|
||||
tail = node;
|
||||
}
|
||||
|
||||
return Handle(node);
|
||||
}
|
||||
|
||||
Handle insert(const Callback & callback, const Handle & before)
|
||||
{
|
||||
// Disable this assertion because it's too slow in debug mode.
|
||||
//assert(before.expired() || ownsHandle(before));
|
||||
|
||||
NodePtr beforeNode = before.lock();
|
||||
if(beforeNode) {
|
||||
NodePtr node(doAllocateNode(callback));
|
||||
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
|
||||
doInsert(node, beforeNode);
|
||||
|
||||
return Handle(node);
|
||||
}
|
||||
|
||||
return append(callback);
|
||||
}
|
||||
|
||||
bool remove(const Handle & handle)
|
||||
{
|
||||
// Disable this assertion because it's too slow in debug mode.
|
||||
//assert(handle.expired() || ownsHandle(handle));
|
||||
|
||||
// It looks like the lock can be put inside the `if` below,
|
||||
// but that doesn't work in multi-threading and cause related unit tests fail.
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
|
||||
auto node = handle.lock();
|
||||
if(node) {
|
||||
doFreeNode(node);
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool ownsHandle(const Handle & handle) const
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
|
||||
auto node = handle.lock();
|
||||
if(node) {
|
||||
while(node->previous) {
|
||||
node = node->previous;
|
||||
}
|
||||
return node == head;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename Func>
|
||||
void forEach(Func && func) const
|
||||
{
|
||||
doForEachIf([&func, this](NodePtr & node) -> bool {
|
||||
doForEachInvoke<void>(func, node);
|
||||
return true;
|
||||
});
|
||||
}
|
||||
|
||||
template <typename Func>
|
||||
bool forEachIf(Func && func) const
|
||||
{
|
||||
return doForEachIf([&func, this](NodePtr & node) -> bool {
|
||||
return doForEachInvoke<bool>(func, node);
|
||||
});
|
||||
}
|
||||
|
||||
#if !defined(__GNUC__) || __GNUC__ >= 5
|
||||
void operator() (Args ...args) const
|
||||
{
|
||||
forEachIf([&args...](Callback & callback) -> bool {
|
||||
// We can't use std::forward here, because if we use std::forward,
|
||||
// for arg that is passed by value, and the callback prototype accepts it by value,
|
||||
// std::forward will move it and may cause the original value invalid.
|
||||
// That happens on any value-to-value passing, no matter the callback moves it or not.
|
||||
|
||||
callback(args...);
|
||||
return CanContinueInvoking::canContinueInvoking(args...);
|
||||
});
|
||||
}
|
||||
#else
|
||||
// This is a patch version for GCC 4. It inlines the unrolled doForEachIf.
|
||||
// GCC 4.8.3 doesn't supporting parameter pack catpure in lambda, see,
|
||||
// https://github.com/wqking/eventpp/issues/19
|
||||
// This is a compromised patch for GCC 4, it may be not maintained or updated unless there are bugs.
|
||||
// We don't use the patch as main code because the patch generates longer code, and duplicated with doForEachIf.
|
||||
void operator() (Args ...args) const
|
||||
{
|
||||
NodePtr node;
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
node = head;
|
||||
}
|
||||
|
||||
const Counter counter = currentCounter.load(std::memory_order_acquire);
|
||||
|
||||
while(node) {
|
||||
if(node->counter != removedCounter && counter >= node->counter) {
|
||||
node->callback(args...);
|
||||
if(! CanContinueInvoking::canContinueInvoking(args...)) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
node = node->next;
|
||||
}
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
private:
|
||||
template <typename F>
|
||||
bool doForEachIf(F && f) const
|
||||
{
|
||||
NodePtr node;
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
node = head;
|
||||
}
|
||||
|
||||
const Counter counter = currentCounter.load(std::memory_order_acquire);
|
||||
|
||||
while(node) {
|
||||
if(node->counter != removedCounter && counter >= node->counter) {
|
||||
if(! f(node)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
node = node->next;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename RT, typename Func>
|
||||
auto doForEachInvoke(Func && func, NodePtr & node) const
|
||||
-> typename std::enable_if<CanInvoke<Func, Handle, Callback &>::value, RT>::type
|
||||
{
|
||||
return func(Handle(node), node->callback);
|
||||
}
|
||||
|
||||
template <typename RT, typename Func>
|
||||
auto doForEachInvoke(Func && func, NodePtr & node) const
|
||||
-> typename std::enable_if<CanInvoke<Func, Callback &>::value, RT>::type
|
||||
{
|
||||
return func(node->callback);
|
||||
}
|
||||
|
||||
void doInsert(NodePtr & node, NodePtr & beforeNode)
|
||||
{
|
||||
node->previous = beforeNode->previous;
|
||||
node->next = beforeNode;
|
||||
if(beforeNode->previous) {
|
||||
beforeNode->previous->next = node;
|
||||
}
|
||||
beforeNode->previous = node;
|
||||
|
||||
if(beforeNode == head) {
|
||||
head = node;
|
||||
}
|
||||
}
|
||||
|
||||
NodePtr doAllocateNode(const Callback & callback)
|
||||
{
|
||||
return std::make_shared<Node>(callback, getNextCounter());
|
||||
}
|
||||
|
||||
void doFreeNode(NodePtr & node)
|
||||
{
|
||||
if(node->next) {
|
||||
node->next->previous = node->previous;
|
||||
}
|
||||
if(node->previous) {
|
||||
node->previous->next = node->next;
|
||||
}
|
||||
|
||||
// Mark it as deleted, this must be before the assignment of head and tail below,
|
||||
// because node can be a reference to head or tail, and after the assignment, node
|
||||
// can be null pointer.
|
||||
node->counter = removedCounter;
|
||||
|
||||
if(head == node) {
|
||||
head = node->next;
|
||||
}
|
||||
if(tail == node) {
|
||||
tail = node->previous;
|
||||
}
|
||||
|
||||
// don't modify node->previous or node->next
|
||||
// because node may be still used in a loop.
|
||||
}
|
||||
|
||||
void doFreeAllNodes() {
|
||||
NodePtr node = head;
|
||||
head.reset();
|
||||
while(node) {
|
||||
NodePtr next = node->next;
|
||||
node->previous.reset();
|
||||
node->next.reset();
|
||||
node = next;
|
||||
}
|
||||
node.reset();
|
||||
}
|
||||
|
||||
Counter getNextCounter()
|
||||
{
|
||||
Counter result = ++currentCounter;;
|
||||
if(result == 0) { // overflow, let's reset all nodes' counters.
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(mutex);
|
||||
NodePtr node = head;
|
||||
while(node) {
|
||||
node->counter = 1;
|
||||
node = node->next;
|
||||
}
|
||||
}
|
||||
result = ++currentCounter;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
void cloneFrom(const NodePtr & fromHead) {
|
||||
NodePtr fromNode(fromHead);
|
||||
NodePtr node;
|
||||
const Counter counter = getNextCounter();
|
||||
while(fromNode) {
|
||||
const NodePtr nextNode(std::make_shared<Node>(fromNode->callback, counter));
|
||||
|
||||
nextNode->previous = node;
|
||||
|
||||
if(node) {
|
||||
node->next = nextNode;
|
||||
}
|
||||
else {
|
||||
node = nextNode;
|
||||
head = node;
|
||||
}
|
||||
|
||||
node = nextNode;
|
||||
fromNode = fromNode->next;
|
||||
}
|
||||
|
||||
tail = node;
|
||||
}
|
||||
|
||||
private:
|
||||
NodePtr head;
|
||||
NodePtr tail;
|
||||
mutable Mutex mutex;
|
||||
typename Threading::template Atomic<Counter> currentCounter;
|
||||
|
||||
};
|
||||
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
|
||||
template <
|
||||
typename Prototype_,
|
||||
typename Policies_ = DefaultPolicies
|
||||
>
|
||||
class CallbackList : public internal_::CallbackListBase<Prototype_, Policies_>, public TagCallbackList
|
||||
{
|
||||
private:
|
||||
using super = internal_::CallbackListBase<Prototype_, Policies_>;
|
||||
|
||||
public:
|
||||
using super::super;
|
||||
|
||||
friend void swap(CallbackList & first, CallbackList & second) noexcept {
|
||||
first.swap(second);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,328 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef EVENTDISPATCHER_H_319010983013
|
||||
#define EVENTDISPATCHER_H_319010983013
|
||||
|
||||
#include "callbacklist.h"
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <
|
||||
typename EventType_,
|
||||
typename Prototype_,
|
||||
typename Policies_,
|
||||
typename MixinRoot_
|
||||
>
|
||||
class EventDispatcherBase;
|
||||
|
||||
template <
|
||||
typename EventType_,
|
||||
typename Policies_,
|
||||
typename MixinRoot_,
|
||||
typename ReturnType, typename ...Args
|
||||
>
|
||||
class EventDispatcherBase <
|
||||
EventType_,
|
||||
ReturnType (Args...),
|
||||
Policies_,
|
||||
MixinRoot_
|
||||
>
|
||||
{
|
||||
protected:
|
||||
using ThisType = EventDispatcherBase<
|
||||
EventType_,
|
||||
ReturnType (Args...),
|
||||
Policies_,
|
||||
MixinRoot_
|
||||
>;
|
||||
using MixinRoot = typename std::conditional<
|
||||
std::is_same<MixinRoot_, void>::value,
|
||||
ThisType,
|
||||
MixinRoot_
|
||||
>::type;
|
||||
using Policies = Policies_;
|
||||
|
||||
using Threading = typename SelectThreading<Policies_, HasTypeThreading<Policies_>::value>::Type;
|
||||
|
||||
using ArgumentPassingMode = typename SelectArgumentPassingMode<
|
||||
Policies_,
|
||||
HasTypeArgumentPassingMode<Policies_>::value,
|
||||
ArgumentPassingAutoDetect
|
||||
>::Type;
|
||||
|
||||
using Callback_ = typename SelectCallback<
|
||||
Policies_,
|
||||
HasTypeCallback<Policies_>::value,
|
||||
std::function<ReturnType (Args...)>
|
||||
>::Type;
|
||||
using CallbackList_ = CallbackList<ReturnType (Args...), Policies_>;
|
||||
|
||||
using Prototype = ReturnType (Args...);
|
||||
|
||||
using Map = typename SelectMap<
|
||||
EventType_,
|
||||
CallbackList_,
|
||||
Policies_,
|
||||
HasTemplateMap<Policies_>::value
|
||||
>::Type;
|
||||
|
||||
using Mixins = typename internal_::SelectMixins<
|
||||
Policies_,
|
||||
internal_::HasTypeMixins<Policies_>::value
|
||||
>::Type;
|
||||
|
||||
public:
|
||||
using Handle = typename CallbackList_::Handle;
|
||||
using Callback = Callback_;
|
||||
using Event = EventType_;
|
||||
using Mutex = typename Threading::Mutex;
|
||||
|
||||
public:
|
||||
EventDispatcherBase()
|
||||
:
|
||||
eventCallbackListMap(),
|
||||
listenerMutex()
|
||||
{
|
||||
}
|
||||
|
||||
EventDispatcherBase(const EventDispatcherBase & other)
|
||||
:
|
||||
eventCallbackListMap(other.eventCallbackListMap),
|
||||
listenerMutex()
|
||||
{
|
||||
}
|
||||
|
||||
EventDispatcherBase(EventDispatcherBase && other) noexcept
|
||||
:
|
||||
eventCallbackListMap(std::move(other.eventCallbackListMap)),
|
||||
listenerMutex()
|
||||
{
|
||||
}
|
||||
|
||||
EventDispatcherBase & operator = (const EventDispatcherBase & other)
|
||||
{
|
||||
eventCallbackListMap = other.eventCallbackListMap;
|
||||
return *this;
|
||||
}
|
||||
|
||||
EventDispatcherBase & operator = (EventDispatcherBase && other) noexcept
|
||||
{
|
||||
eventCallbackListMap = std::move(other.eventCallbackListMap);
|
||||
return *this;
|
||||
}
|
||||
|
||||
void swap(EventDispatcherBase & other) noexcept {
|
||||
using std::swap;
|
||||
|
||||
swap(eventCallbackListMap, other.eventCallbackListMap);
|
||||
}
|
||||
|
||||
Handle appendListener(const Event & event, const Callback & callback)
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(listenerMutex);
|
||||
|
||||
return eventCallbackListMap[event].append(callback);
|
||||
}
|
||||
|
||||
Handle prependListener(const Event & event, const Callback & callback)
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(listenerMutex);
|
||||
|
||||
return eventCallbackListMap[event].prepend(callback);
|
||||
}
|
||||
|
||||
Handle insertListener(const Event & event, const Callback & callback, const Handle & before)
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(listenerMutex);
|
||||
|
||||
return eventCallbackListMap[event].insert(callback, before);
|
||||
}
|
||||
|
||||
bool removeListener(const Event & event, const Handle handle)
|
||||
{
|
||||
CallbackList_ * callableList = doFindCallableList(event);
|
||||
if(callableList) {
|
||||
return callableList->remove(handle);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool hasAnyListener(const Event & event) const
|
||||
{
|
||||
const CallbackList_ * callableList = doFindCallableList(event);
|
||||
if(callableList) {
|
||||
return ! callableList->empty();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool ownsHandle(const Event & event, const Handle & handle) const
|
||||
{
|
||||
const CallbackList_ * callableList = doFindCallableList(event);
|
||||
if(callableList) {
|
||||
return callableList->ownsHandle(handle);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename Func>
|
||||
void forEach(const Event & event, Func && func) const
|
||||
{
|
||||
const CallbackList_ * callableList = doFindCallableList(event);
|
||||
if(callableList) {
|
||||
callableList->forEach(std::forward<Func>(func));
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Func>
|
||||
bool forEachIf(const Event & event, Func && func) const
|
||||
{
|
||||
const CallbackList_ * callableList = doFindCallableList(event);
|
||||
if (callableList) {
|
||||
return callableList->forEachIf(std::forward<Func>(func));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
void dispatch(Args ...args) const
|
||||
{
|
||||
static_assert(ArgumentPassingMode::canIncludeEventType, "Dispatching arguments count doesn't match required (Event type should be included).");
|
||||
|
||||
using GetEvent = typename SelectGetEvent<Policies_, EventType_, HasFunctionGetEvent<Policies_, Args...>::value>::Type;
|
||||
|
||||
// can't std::forward<Args>(args) in GetEvent::getEvent because the pass by value arguments will be moved to getEvent
|
||||
// then the other std::forward<Args>(args) to directDispatch will get empty values.
|
||||
directDispatch(
|
||||
GetEvent::getEvent(args...),
|
||||
std::forward<Args>(args)...
|
||||
);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void dispatch(T && first, Args ...args) const
|
||||
{
|
||||
static_assert(ArgumentPassingMode::canExcludeEventType, "Dispatching arguments count doesn't match required (Event type should NOT be included).");
|
||||
|
||||
using GetEvent = typename SelectGetEvent<Policies_, EventType_, HasFunctionGetEvent<Policies_, T &&, Args...>::value>::Type;
|
||||
|
||||
directDispatch(
|
||||
GetEvent::getEvent(std::forward<T>(first), args...),
|
||||
std::forward<Args>(args)...
|
||||
);
|
||||
}
|
||||
|
||||
// Bypass any getEvent policy. The first argument is the event type.
|
||||
// Most used for internal purpose.
|
||||
void directDispatch(const Event & e, Args ...args) const
|
||||
{
|
||||
if(! internal_::ForEachMixins<MixinRoot, Mixins, DoMixinBeforeDispatch>::forEach(
|
||||
this, typename std::add_lvalue_reference<Args>::type(args)...)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const CallbackList_ * callableList = doFindCallableList(e);
|
||||
if(callableList) {
|
||||
(*callableList)(std::forward<Args>(args)...);
|
||||
}
|
||||
}
|
||||
|
||||
protected:
|
||||
const CallbackList_ * doFindCallableList(const Event & e) const
|
||||
{
|
||||
return doFindCallableListHelper(this, e);
|
||||
}
|
||||
|
||||
CallbackList_ * doFindCallableList(const Event & e)
|
||||
{
|
||||
return doFindCallableListHelper(this, e);
|
||||
}
|
||||
|
||||
private:
|
||||
// template helper to avoid code duplication in doFindCallableList
|
||||
template <typename T>
|
||||
static auto doFindCallableListHelper(T * self, const Event & e)
|
||||
-> typename std::conditional<std::is_const<T>::value, const CallbackList_ *, CallbackList_ *>::type
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(self->listenerMutex);
|
||||
|
||||
auto it = self->eventCallbackListMap.find(e);
|
||||
if(it != self->eventCallbackListMap.end()) {
|
||||
return &it->second;
|
||||
}
|
||||
else {
|
||||
return nullptr;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
// Mixin related
|
||||
struct DoMixinBeforeDispatch
|
||||
{
|
||||
template <typename T, typename Self, typename ...A>
|
||||
static auto forEach(const Self * self, A && ...args)
|
||||
-> typename std::enable_if<HasFunctionMixinBeforeDispatch<T, A...>::value, bool>::type {
|
||||
return static_cast<const T *>(self)->mixinBeforeDispatch(std::forward<A>(args)...);
|
||||
}
|
||||
|
||||
template <typename T, typename Self, typename ...A>
|
||||
static auto forEach(const Self * /*self*/, A && ... /*args*/)
|
||||
-> typename std::enable_if<! HasFunctionMixinBeforeDispatch<T, A...>::value, bool>::type {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
private:
|
||||
Map eventCallbackListMap;
|
||||
mutable Mutex listenerMutex;
|
||||
};
|
||||
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
template <
|
||||
typename Event_,
|
||||
typename Prototype_,
|
||||
typename Policies_ = DefaultPolicies
|
||||
>
|
||||
class EventDispatcher : public internal_::InheritMixins<
|
||||
internal_::EventDispatcherBase<Event_, Prototype_, Policies_, void>,
|
||||
typename internal_::SelectMixins<Policies_, internal_::HasTypeMixins<Policies_>::value >::Type
|
||||
>::Type, public TagEventDispatcher
|
||||
{
|
||||
private:
|
||||
using super = typename internal_::InheritMixins<
|
||||
internal_::EventDispatcherBase<Event_, Prototype_, Policies_, void>,
|
||||
typename internal_::SelectMixins<Policies_, internal_::HasTypeMixins<Policies_>::value >::Type
|
||||
>::Type;
|
||||
|
||||
public:
|
||||
using super::super;
|
||||
|
||||
friend void swap(EventDispatcher & first, EventDispatcher & second) noexcept {
|
||||
first.swap(second);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,186 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef EVENTOPTIONS_H_730367862613
|
||||
#define EVENTOPTIONS_H_730367862613
|
||||
|
||||
#include "internal/typeutil_i.h"
|
||||
|
||||
#include <atomic>
|
||||
#include <condition_variable>
|
||||
#include <map>
|
||||
#include <unordered_map>
|
||||
#include <list>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
struct TagHomo {};
|
||||
struct TagCallbackList : public TagHomo {};
|
||||
struct TagEventDispatcher : public TagHomo {};
|
||||
struct TagEventQueue : public TagHomo {};
|
||||
|
||||
struct TagHeter {};
|
||||
struct TagHeterCallbackList : public TagHeter {};
|
||||
struct TagHeterEventDispatcher : public TagHeter {};
|
||||
struct TagHeterEventQueue : public TagHeter {};
|
||||
|
||||
struct SpinLock
|
||||
{
|
||||
public:
|
||||
void lock() {
|
||||
while(locked.test_and_set(std::memory_order_acquire)) {
|
||||
}
|
||||
}
|
||||
|
||||
void unlock() {
|
||||
locked.clear(std::memory_order_release);
|
||||
}
|
||||
|
||||
private:
|
||||
std::atomic_flag locked = ATOMIC_FLAG_INIT;
|
||||
};
|
||||
|
||||
template <
|
||||
typename Mutex_,
|
||||
template <typename > class Atomic_ = std::atomic,
|
||||
typename ConditionVariable_ = std::condition_variable
|
||||
>
|
||||
struct GeneralThreading
|
||||
{
|
||||
using Mutex = Mutex_;
|
||||
|
||||
template <typename T>
|
||||
using Atomic = Atomic_<T>;
|
||||
|
||||
using ConditionVariable = ConditionVariable_;
|
||||
};
|
||||
|
||||
struct MultipleThreading
|
||||
{
|
||||
using Mutex = std::mutex;
|
||||
|
||||
template <typename T>
|
||||
using Atomic = std::atomic<T>;
|
||||
|
||||
using ConditionVariable = std::condition_variable;
|
||||
};
|
||||
|
||||
struct SingleThreading
|
||||
{
|
||||
struct Mutex
|
||||
{
|
||||
void lock() {}
|
||||
void unlock() {}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct Atomic
|
||||
{
|
||||
Atomic() noexcept = default;
|
||||
constexpr Atomic(T desired) noexcept
|
||||
: value(desired)
|
||||
{
|
||||
}
|
||||
|
||||
void store(T desired, std::memory_order /*order*/ = std::memory_order_seq_cst) noexcept
|
||||
{
|
||||
value = desired;
|
||||
}
|
||||
|
||||
T load(std::memory_order /*order*/ = std::memory_order_seq_cst) const noexcept
|
||||
{
|
||||
return value;
|
||||
}
|
||||
|
||||
T exchange(T desired, std::memory_order /*order*/ = std::memory_order_seq_cst) noexcept
|
||||
{
|
||||
const T previous = value;
|
||||
value = desired;
|
||||
return previous;
|
||||
}
|
||||
|
||||
T operator ++ () noexcept
|
||||
{
|
||||
return ++value;
|
||||
}
|
||||
|
||||
T operator -- () noexcept
|
||||
{
|
||||
return --value;
|
||||
}
|
||||
|
||||
T value;
|
||||
};
|
||||
|
||||
struct ConditionVariable
|
||||
{
|
||||
void notify_one() noexcept
|
||||
{
|
||||
}
|
||||
|
||||
template <class Predicate>
|
||||
void wait(std::unique_lock<std::mutex> & /*lock*/, Predicate /*pred*/)
|
||||
{
|
||||
}
|
||||
|
||||
template <class Rep, class Period, class Predicate>
|
||||
bool wait_for(std::unique_lock<std::mutex> & /*lock*/,
|
||||
const std::chrono::duration<Rep, Period> & /*rel_time*/,
|
||||
Predicate /*pred*/
|
||||
)
|
||||
{
|
||||
return true;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
struct ArgumentPassingAutoDetect
|
||||
{
|
||||
enum {
|
||||
canIncludeEventType = true,
|
||||
canExcludeEventType = true
|
||||
};
|
||||
};
|
||||
|
||||
struct ArgumentPassingIncludeEvent
|
||||
{
|
||||
enum {
|
||||
canIncludeEventType = true,
|
||||
canExcludeEventType = false
|
||||
};
|
||||
};
|
||||
|
||||
struct ArgumentPassingExcludeEvent
|
||||
{
|
||||
enum {
|
||||
canIncludeEventType = false,
|
||||
canExcludeEventType = true
|
||||
};
|
||||
};
|
||||
|
||||
struct DefaultPolicies
|
||||
{
|
||||
};
|
||||
|
||||
template <template <typename> class ...Mixins>
|
||||
struct MixinList
|
||||
{
|
||||
};
|
||||
|
||||
#include "internal/eventpolicies_i.h"
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,561 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef EVENTQUEUE_H_705786053037
|
||||
#define EVENTQUEUE_H_705786053037
|
||||
|
||||
#include "eventdispatcher.h"
|
||||
#include "internal/eventqueue_i.h"
|
||||
|
||||
#include <tuple>
|
||||
#include <chrono>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <
|
||||
typename EventType_,
|
||||
typename Prototype_,
|
||||
typename Policies_
|
||||
>
|
||||
class EventQueueBase;
|
||||
|
||||
template <
|
||||
typename EventType_,
|
||||
typename Policies_,
|
||||
typename ReturnType, typename ...Args
|
||||
>
|
||||
class EventQueueBase <
|
||||
EventType_,
|
||||
ReturnType (Args...),
|
||||
Policies_
|
||||
> : public EventDispatcherBase<
|
||||
EventType_,
|
||||
ReturnType (Args...),
|
||||
Policies_,
|
||||
EventQueueBase <
|
||||
EventType_,
|
||||
ReturnType (Args...),
|
||||
Policies_
|
||||
>
|
||||
>
|
||||
{
|
||||
private:
|
||||
using super = EventDispatcherBase<
|
||||
EventType_,
|
||||
ReturnType (Args...),
|
||||
Policies_,
|
||||
EventQueueBase <
|
||||
EventType_,
|
||||
ReturnType (Args...),
|
||||
Policies_
|
||||
>
|
||||
>;
|
||||
|
||||
using Policies = typename super::Policies;
|
||||
using Threading = typename super::Threading;
|
||||
using ConditionVariable = typename Threading::ConditionVariable;
|
||||
|
||||
using QueuedEventArgumentsType = std::tuple<typename std::decay<Args>::type...>;
|
||||
|
||||
struct QueuedEvent_
|
||||
{
|
||||
typename std::decay<typename super::Event>::type event;
|
||||
QueuedEventArgumentsType arguments;
|
||||
|
||||
typename super::Event getEvent() const {
|
||||
return event;
|
||||
}
|
||||
|
||||
template <std::size_t N>
|
||||
auto getArgument() const
|
||||
-> typename std::tuple_element<N, std::tuple<Args...> >::type {
|
||||
return std::get<N>(arguments);
|
||||
}
|
||||
};
|
||||
|
||||
using BufferedItemList = typename SelectQueueList<
|
||||
BufferedItem<QueuedEvent_>,
|
||||
Policies_,
|
||||
HasTemplateQueueList<Policies_>::value
|
||||
>::Type;
|
||||
|
||||
public:
|
||||
using QueuedEvent = QueuedEvent_;
|
||||
using Event = typename super::Event;
|
||||
using Handle = typename super::Handle;
|
||||
using Callback = typename super::Callback;
|
||||
using Mutex = typename super::Mutex;
|
||||
|
||||
struct DisableQueueNotify
|
||||
{
|
||||
DisableQueueNotify(EventQueueBase * queue)
|
||||
: queue(queue)
|
||||
{
|
||||
++queue->queueNotifyCounter;
|
||||
}
|
||||
|
||||
~DisableQueueNotify()
|
||||
{
|
||||
--queue->queueNotifyCounter;
|
||||
|
||||
if(queue->doCanNotifyQueueAvailable() && ! queue->emptyQueue()) {
|
||||
queue->queueListConditionVariable.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
EventQueueBase * queue;
|
||||
};
|
||||
|
||||
public:
|
||||
EventQueueBase()
|
||||
:
|
||||
super(),
|
||||
queueListConditionVariable(),
|
||||
queueEmptyCounter(0),
|
||||
queueNotifyCounter(0),
|
||||
queueListMutex(),
|
||||
queueList(),
|
||||
freeListMutex(),
|
||||
freeList()
|
||||
{
|
||||
}
|
||||
|
||||
EventQueueBase(const EventQueueBase & other)
|
||||
: super(other)
|
||||
{
|
||||
}
|
||||
|
||||
EventQueueBase(EventQueueBase && other) noexcept
|
||||
: super(std::move(other))
|
||||
{
|
||||
}
|
||||
|
||||
EventQueueBase & operator = (const EventQueueBase & other)
|
||||
{
|
||||
super::operator = (other);
|
||||
return *this;
|
||||
}
|
||||
|
||||
EventQueueBase & operator = (EventQueueBase && other) noexcept
|
||||
{
|
||||
super::operator = (std::move(other));
|
||||
return *this;
|
||||
}
|
||||
|
||||
template <typename ...A>
|
||||
auto enqueue(A && ...args) -> typename std::enable_if<sizeof...(A) == sizeof...(Args), void>::type
|
||||
{
|
||||
static_assert(super::ArgumentPassingMode::canIncludeEventType, "Enqueuing arguments count doesn't match required (Event type should be included).");
|
||||
|
||||
using GetEvent = typename SelectGetEvent<Policies_, EventType_, HasFunctionGetEvent<Policies_, A...>::value>::Type;
|
||||
|
||||
doEnqueue(QueuedEvent{
|
||||
GetEvent::getEvent(args...),
|
||||
QueuedEventArgumentsType(std::forward<A>(args)...)
|
||||
});
|
||||
|
||||
if(doCanProcess()) {
|
||||
queueListConditionVariable.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T, typename ...A>
|
||||
auto enqueue(T && first, A && ...args) -> typename std::enable_if<sizeof...(A) == sizeof...(Args), void>::type
|
||||
{
|
||||
static_assert(super::ArgumentPassingMode::canExcludeEventType, "Enqueuing arguments count doesn't match required (Event type should NOT be included).");
|
||||
|
||||
using GetEvent = typename SelectGetEvent<Policies_, EventType_, HasFunctionGetEvent<Policies_, T &&, A...>::value>::Type;
|
||||
|
||||
doEnqueue(QueuedEvent{
|
||||
GetEvent::getEvent(std::forward<T>(first), args...),
|
||||
QueuedEventArgumentsType(std::forward<A>(args)...)
|
||||
});
|
||||
|
||||
if(doCanProcess()) {
|
||||
queueListConditionVariable.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
bool emptyQueue() const
|
||||
{
|
||||
return queueList.empty() && (queueEmptyCounter.load(std::memory_order_acquire) == 0);
|
||||
}
|
||||
|
||||
void clearEvents()
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
std::swap(queueList, tempList);
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
for(auto & item : tempList) {
|
||||
item.clear();
|
||||
}
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), tempList);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool process()
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
|
||||
// Use a counter to tell the queue list is not empty during processing
|
||||
// even though queueList is swapped to empty.
|
||||
CounterGuard<decltype(queueEmptyCounter)> counterGuard(queueEmptyCounter);
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
std::swap(queueList, tempList);
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
for(auto & item : tempList) {
|
||||
doDispatchQueuedEvent(
|
||||
item.get(),
|
||||
typename MakeIndexSequence<sizeof...(Args)>::Type()
|
||||
);
|
||||
item.clear();
|
||||
}
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), tempList);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool processOne()
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
|
||||
// Use a counter to tell the queue list is not empty during processing
|
||||
// even though queueList is swapped to empty.
|
||||
CounterGuard<decltype(queueEmptyCounter)> counterGuard(queueEmptyCounter);
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
if(! queueList.empty()) {
|
||||
tempList.splice(tempList.end(), queueList, queueList.begin());
|
||||
}
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
auto & item = tempList.front();
|
||||
doDispatchQueuedEvent(
|
||||
item.get(),
|
||||
typename MakeIndexSequence<sizeof...(Args)>::Type()
|
||||
);
|
||||
item.clear();
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), tempList);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename Predictor>
|
||||
bool processIf(Predictor && predictor)
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
BufferedItemList idleList;
|
||||
|
||||
// Use a counter to tell the queue list is not empty during processing
|
||||
// even though queueList is swapped to empty.
|
||||
CounterGuard<decltype(queueEmptyCounter)> counterGuard(queueEmptyCounter);
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
std::swap(queueList, tempList);
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
for(auto it = tempList.begin(); it != tempList.end(); ) {
|
||||
if(doInvokeFuncWithQueuedEvent(
|
||||
predictor,
|
||||
it->get(),
|
||||
typename MakeIndexSequence<sizeof...(Args)>::Type())
|
||||
) {
|
||||
doDispatchQueuedEvent(
|
||||
it->get(),
|
||||
typename MakeIndexSequence<sizeof...(Args)>::Type()
|
||||
);
|
||||
it->clear();
|
||||
|
||||
auto tempIt = it;
|
||||
++it;
|
||||
idleList.splice(idleList.end(), tempList, tempIt);
|
||||
}
|
||||
else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
|
||||
if (! tempList.empty()) {
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
queueList.splice(queueList.begin(), tempList);
|
||||
}
|
||||
|
||||
if(! idleList.empty()) {
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), idleList);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename Predictor>
|
||||
bool processUntil(Predictor && predictor)
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
BufferedItemList idleList;
|
||||
|
||||
// Use a counter to tell the queue list is not empty during processing
|
||||
// even though queueList is swapped to empty.
|
||||
CounterGuard<decltype(queueEmptyCounter)> counterGuard(queueEmptyCounter);
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
std::swap(queueList, tempList);
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
for(auto it = tempList.begin(); it != tempList.end(); ) {
|
||||
if(doInvokeFuncWithQueuedEvent(
|
||||
predictor,
|
||||
it->get(),
|
||||
typename MakeIndexSequence<sizeof...(Args)>::Type())
|
||||
) {
|
||||
break;
|
||||
}
|
||||
else {
|
||||
doDispatchQueuedEvent(
|
||||
it->get(),
|
||||
typename MakeIndexSequence<sizeof...(Args)>::Type()
|
||||
);
|
||||
it->clear();
|
||||
|
||||
auto tempIt = it;
|
||||
++it;
|
||||
idleList.splice(idleList.end(), tempList, tempIt);
|
||||
}
|
||||
}
|
||||
|
||||
if (! tempList.empty()) {
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
queueList.splice(queueList.begin(), tempList);
|
||||
}
|
||||
|
||||
if(! idleList.empty()) {
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), idleList);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
void wait() const
|
||||
{
|
||||
std::unique_lock<Mutex> queueListLock(queueListMutex);
|
||||
queueListConditionVariable.wait(queueListLock, [this]() -> bool {
|
||||
return doCanProcess();
|
||||
});
|
||||
}
|
||||
|
||||
template <class Rep, class Period>
|
||||
bool waitFor(const std::chrono::duration<Rep, Period> & duration) const
|
||||
{
|
||||
std::unique_lock<Mutex> queueListLock(queueListMutex);
|
||||
return queueListConditionVariable.wait_for(queueListLock, duration, [this]() -> bool {
|
||||
return doCanProcess();
|
||||
});
|
||||
}
|
||||
|
||||
using super::dispatch;
|
||||
|
||||
template <typename U>
|
||||
auto dispatch(const U & queuedEvent)
|
||||
-> typename std::enable_if<std::is_same<U, QueuedEvent>::value, void>::type
|
||||
{
|
||||
doDispatchQueuedEvent(
|
||||
queuedEvent,
|
||||
typename MakeIndexSequence<sizeof...(Args)>::Type()
|
||||
);
|
||||
}
|
||||
|
||||
bool peekEvent(QueuedEvent * queuedEvent)
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
|
||||
if(! queueList.empty()) {
|
||||
*queuedEvent = queueList.front().get();
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool takeEvent(QueuedEvent * queuedEvent)
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
|
||||
if(! queueList.empty()) {
|
||||
tempList.splice(tempList.end(), queueList, queueList.begin());
|
||||
}
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
*queuedEvent = std::move(tempList.front().get());
|
||||
tempList.front().clear();
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), tempList);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
protected:
|
||||
bool doCanProcess() const
|
||||
{
|
||||
return ! emptyQueue() && doCanNotifyQueueAvailable();
|
||||
}
|
||||
|
||||
bool doCanNotifyQueueAvailable() const
|
||||
{
|
||||
return queueNotifyCounter.load(std::memory_order_acquire) == 0;
|
||||
}
|
||||
|
||||
template <typename T, size_t ...Indexes>
|
||||
void doDispatchQueuedEvent(T && item, IndexSequence<Indexes...>)
|
||||
{
|
||||
this->directDispatch(item.event, std::get<Indexes>(item.arguments)...);
|
||||
}
|
||||
|
||||
template <typename F, typename T, size_t ...Indexes>
|
||||
bool doInvokeFuncWithQueuedEvent(F && func, T && item, IndexSequence<Indexes...>) const
|
||||
{
|
||||
return doInvokeFuncWithQueuedEventHelper(std::forward<F>(func), std::get<Indexes>(item.arguments)...);
|
||||
}
|
||||
|
||||
template <typename F>
|
||||
auto doInvokeFuncWithQueuedEventHelper(F && func, Args ...args) const
|
||||
-> typename std::enable_if<! CanInvoke<F>::value, bool>::type
|
||||
{
|
||||
return func(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename F>
|
||||
auto doInvokeFuncWithQueuedEventHelper(F && func, Args .../*args*/) const
|
||||
-> typename std::enable_if<CanInvoke<F>::value, bool>::type
|
||||
{
|
||||
return func();
|
||||
}
|
||||
|
||||
void doEnqueue(QueuedEvent && item)
|
||||
{
|
||||
BufferedItemList tempList;
|
||||
if(! freeList.empty()) {
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
if(! freeList.empty()) {
|
||||
tempList.splice(tempList.end(), freeList, freeList.begin());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(tempList.empty()) {
|
||||
tempList.emplace_back();
|
||||
}
|
||||
|
||||
auto it = tempList.begin();
|
||||
it->set(std::move(item));
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
queueList.splice(queueList.end(), tempList, it);
|
||||
}
|
||||
|
||||
private:
|
||||
mutable ConditionVariable queueListConditionVariable;
|
||||
typename Threading::template Atomic<int> queueEmptyCounter;
|
||||
typename Threading::template Atomic<int> queueNotifyCounter;
|
||||
mutable Mutex queueListMutex;
|
||||
BufferedItemList queueList;
|
||||
Mutex freeListMutex;
|
||||
BufferedItemList freeList;
|
||||
};
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
template <
|
||||
typename Event_,
|
||||
typename Prototype_,
|
||||
typename Policies_ = DefaultPolicies
|
||||
>
|
||||
class EventQueue : public internal_::InheritMixins<
|
||||
internal_::EventQueueBase<Event_, Prototype_, Policies_>,
|
||||
typename internal_::SelectMixins<Policies_, internal_::HasTypeMixins<Policies_>::value >::Type
|
||||
>::Type, public TagEventDispatcher, public TagEventQueue
|
||||
{
|
||||
private:
|
||||
using super = typename internal_::InheritMixins<
|
||||
internal_::EventQueueBase<Event_, Prototype_, Policies_>,
|
||||
typename internal_::SelectMixins<Policies_, internal_::HasTypeMixins<Policies_>::value >::Type
|
||||
>::Type;
|
||||
|
||||
public:
|
||||
using super::super;
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,319 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef HETERCALLBACKLIST_H_966730936077
|
||||
#define HETERCALLBACKLIST_H_966730936077
|
||||
|
||||
#include "internal/hetercallbacklist_i.h"
|
||||
#include "callbacklist.h"
|
||||
|
||||
#include <array>
|
||||
#include <mutex>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <
|
||||
typename PrototypeList_,
|
||||
typename Policies_
|
||||
>
|
||||
class HeterCallbackListBase
|
||||
{
|
||||
protected:
|
||||
struct HeterHandle_
|
||||
{
|
||||
int index;
|
||||
std::weak_ptr<void> homoHandle;
|
||||
|
||||
operator bool () const noexcept {
|
||||
return (bool)homoHandle;
|
||||
}
|
||||
};
|
||||
|
||||
struct UnderlyingPoliciesType_
|
||||
{
|
||||
};
|
||||
|
||||
class HomoCallbackListTypeBase
|
||||
{
|
||||
public:
|
||||
virtual ~HomoCallbackListTypeBase() {}
|
||||
|
||||
virtual bool empty() = 0;
|
||||
virtual bool doRemove(const HeterHandle_ & handle) = 0;
|
||||
virtual std::shared_ptr<HomoCallbackListTypeBase> doClone() = 0;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class HomoCallbackListType : public CallbackList<T, UnderlyingPoliciesType_>, public HomoCallbackListTypeBase
|
||||
{
|
||||
private:
|
||||
using super = CallbackList<T, UnderlyingPoliciesType_>;
|
||||
|
||||
public:
|
||||
virtual bool empty() override {
|
||||
return super::empty();
|
||||
}
|
||||
|
||||
virtual bool doRemove(const HeterHandle_ & handle) override {
|
||||
auto sp = handle.homoHandle.lock();
|
||||
if(! sp) {
|
||||
return false;
|
||||
}
|
||||
return this->remove(typename super::Handle(std::static_pointer_cast<typename super::Handle::element_type>(sp)));
|
||||
}
|
||||
|
||||
virtual std::shared_ptr<HomoCallbackListTypeBase> doClone() override {
|
||||
return std::make_shared<HomoCallbackListType<T> >(*this);
|
||||
}
|
||||
};
|
||||
|
||||
using Policies = Policies_;
|
||||
using Threading = typename SelectThreading<Policies, HasTypeThreading<Policies>::value>::Type;
|
||||
|
||||
using PrototypeList = PrototypeList_;
|
||||
|
||||
public:
|
||||
using Handle = HeterHandle_;
|
||||
using Mutex = typename Threading::Mutex;
|
||||
|
||||
public:
|
||||
HeterCallbackListBase()
|
||||
:
|
||||
callbackListList(),
|
||||
callbackListListMutex()
|
||||
{
|
||||
}
|
||||
|
||||
HeterCallbackListBase(const HeterCallbackListBase & other)
|
||||
:
|
||||
callbackListList(),
|
||||
callbackListListMutex()
|
||||
{
|
||||
for(size_t i = 0; i < callbackListList.size(); ++i) {
|
||||
if(other.callbackListList[i]) {
|
||||
callbackListList[i] = other.callbackListList[i]->doClone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
HeterCallbackListBase(HeterCallbackListBase && other) noexcept
|
||||
:
|
||||
callbackListList(std::move(other.callbackListList)),
|
||||
callbackListListMutex()
|
||||
{
|
||||
}
|
||||
|
||||
// If we use pass by value idiom and omit the 'this' check,
|
||||
// when assigning to self there is a deep copy which is inefficient.
|
||||
HeterCallbackListBase & operator = (const HeterCallbackListBase & other) noexcept
|
||||
{
|
||||
if(this != &other) {
|
||||
HeterCallbackListBase copied(other);
|
||||
swap(copied);
|
||||
}
|
||||
return *this;
|
||||
}
|
||||
|
||||
HeterCallbackListBase & operator = (HeterCallbackListBase && other) noexcept
|
||||
{
|
||||
if(this != &other) {
|
||||
for(size_t i = 0; i < callbackListList.size(); ++i) {
|
||||
callbackListList[i] = std::move(other.callbackListList[i]);
|
||||
}
|
||||
}
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
void swap(HeterCallbackListBase & other) noexcept {
|
||||
using std::swap;
|
||||
|
||||
swap(callbackListList, other.callbackListList);
|
||||
}
|
||||
|
||||
bool empty() const {
|
||||
for(const auto & callbackList : callbackListList) {
|
||||
if(callbackList && ! callbackList->empty()) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
operator bool() const {
|
||||
return ! empty();
|
||||
}
|
||||
|
||||
template <typename C>
|
||||
Handle append(const C & callback)
|
||||
{
|
||||
using PrototypeInfo = FindPrototypeByCallable<PrototypeList_, C>;
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
|
||||
auto callbackList= doGetCallbackList<PrototypeInfo>();
|
||||
return Handle {
|
||||
PrototypeInfo::index,
|
||||
callbackList->append(callback)
|
||||
};
|
||||
}
|
||||
|
||||
template <typename C>
|
||||
Handle prepend(const C & callback)
|
||||
{
|
||||
using PrototypeInfo = FindPrototypeByCallable<PrototypeList_, C>;
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
|
||||
auto callbackList= doGetCallbackList<PrototypeInfo>();
|
||||
return Handle {
|
||||
PrototypeInfo::index,
|
||||
callbackList->prepend(callback)
|
||||
};
|
||||
}
|
||||
|
||||
template <typename C>
|
||||
Handle insert(const C & callback, const Handle & before)
|
||||
{
|
||||
using PrototypeInfo = FindPrototypeByCallable<PrototypeList_, C>;
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
|
||||
auto callbackList= doGetCallbackList<PrototypeInfo>();
|
||||
|
||||
if(before.index != PrototypeInfo::index) {
|
||||
return Handle {
|
||||
PrototypeInfo::index,
|
||||
callbackList->append(callback)
|
||||
};
|
||||
}
|
||||
|
||||
using UnderlyingHandle = typename decltype(callbackList)::element_type::Handle;
|
||||
|
||||
return Handle {
|
||||
PrototypeInfo::index,
|
||||
callbackList->insert(
|
||||
callback,
|
||||
UnderlyingHandle(std::static_pointer_cast<typename UnderlyingHandle::element_type>(before.homoHandle.lock()))
|
||||
)
|
||||
};
|
||||
}
|
||||
|
||||
bool remove(const Handle & handle)
|
||||
{
|
||||
auto callbackList = callbackListList[handle.index];
|
||||
if(callbackList) {
|
||||
return callbackList->doRemove(handle);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename Prototype, typename Func>
|
||||
void forEach(Func && func) const
|
||||
{
|
||||
using PrototypeInfo = FindPrototypeByCallable<PrototypeList, Prototype>;
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
|
||||
auto callbackList= doGetCallbackList<PrototypeInfo>();
|
||||
using CL = typename decltype(callbackList)::element_type;
|
||||
callbackList->forEach([this, &func](const typename CL::Handle & handle, const typename CL::Callback & callback) {
|
||||
doForEachInvoke<void, PrototypeInfo::index>(func, handle, callback);
|
||||
});
|
||||
}
|
||||
|
||||
template <typename Prototype, typename Func>
|
||||
bool forEachIf(Func && func) const
|
||||
{
|
||||
using PrototypeInfo = FindPrototypeByCallable<PrototypeList, Prototype>;
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
|
||||
auto callbackList= doGetCallbackList<PrototypeInfo>();
|
||||
using CL = typename decltype(callbackList)::element_type;
|
||||
return callbackList->forEachIf([this, &func](const typename CL::Handle & handle, const typename CL::Callback & callback) {
|
||||
return doForEachInvoke<bool, PrototypeInfo::index>(func, handle, callback);
|
||||
});
|
||||
}
|
||||
|
||||
template <typename ...Args>
|
||||
void operator() (Args && ...args) const
|
||||
{
|
||||
using PrototypeInfo = FindPrototypeByArgs<PrototypeList, Args...>;
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
|
||||
auto callbackList= doGetCallbackList<PrototypeInfo>();
|
||||
(*callbackList)(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
private:
|
||||
template <typename RT, int PrototypeIndex, typename Func, typename H, typename CL>
|
||||
auto doForEachInvoke(Func && func, const H & handle, CL && callback) const
|
||||
-> typename std::enable_if<CanInvoke<Func, Handle, CL>::value, RT>::type
|
||||
{
|
||||
return func(Handle { PrototypeIndex, handle }, callback);
|
||||
}
|
||||
|
||||
template <typename RT, int PrototypeIndex, typename Func, typename H, typename CL>
|
||||
auto doForEachInvoke(Func && func, const H & /*handle*/, CL && callback) const
|
||||
-> typename std::enable_if<CanInvoke<Func, CL>::value, RT>::type
|
||||
{
|
||||
return func(callback);
|
||||
}
|
||||
|
||||
template <typename PrototypeInfo>
|
||||
auto doGetCallbackList() const
|
||||
-> std::shared_ptr<HomoCallbackListType<typename PrototypeInfo::Prototype> >
|
||||
{
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
|
||||
if(! callbackListList[PrototypeInfo::index]) {
|
||||
std::lock_guard<Mutex> lockGuard(callbackListListMutex);
|
||||
|
||||
if(! callbackListList[PrototypeInfo::index]) {
|
||||
callbackListList[PrototypeInfo::index] = std::make_shared<HomoCallbackListType<typename PrototypeInfo::Prototype> >();
|
||||
}
|
||||
}
|
||||
|
||||
return std::static_pointer_cast<HomoCallbackListType<typename PrototypeInfo::Prototype> >(callbackListList[PrototypeInfo::index]);
|
||||
}
|
||||
|
||||
private:
|
||||
// the postfix 'ListList' is not good, but it's better to use consistent naming convention.
|
||||
mutable std::array<std::shared_ptr<HomoCallbackListTypeBase>, HeterTupleSize<PrototypeList_>::value> callbackListList;
|
||||
mutable Mutex callbackListListMutex;
|
||||
};
|
||||
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
template <
|
||||
typename PrototypeList_,
|
||||
typename Policies_ = DefaultPolicies
|
||||
>
|
||||
class HeterCallbackList : public internal_::HeterCallbackListBase<PrototypeList_, Policies_>, public TagCallbackList, public TagHeterCallbackList
|
||||
{
|
||||
private:
|
||||
using super = internal_::HeterCallbackListBase<PrototypeList_, Policies_>;
|
||||
|
||||
public:
|
||||
using super::super;
|
||||
|
||||
friend void swap(HeterCallbackList & first, HeterCallbackList & second) noexcept {
|
||||
first.swap(second);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,325 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef HETEREVENTDISPATCHER_H_127766658555
|
||||
#define HETEREVENTDISPATCHER_H_127766658555
|
||||
|
||||
#include "mixins/mixinheterfilter.h"
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <
|
||||
typename EventType_,
|
||||
typename PrototypeList_,
|
||||
typename Policies_,
|
||||
typename MixinRoot_
|
||||
>
|
||||
class HeterEventDispatcherBase
|
||||
{
|
||||
protected:
|
||||
using ThisType = HeterEventDispatcherBase<
|
||||
EventType_,
|
||||
PrototypeList_,
|
||||
Policies_,
|
||||
MixinRoot_
|
||||
>;
|
||||
using MixinRoot = typename std::conditional<
|
||||
std::is_same<MixinRoot_, void>::value,
|
||||
ThisType,
|
||||
MixinRoot_
|
||||
>::type;
|
||||
using Policies = Policies_;
|
||||
|
||||
using Threading = typename SelectThreading<Policies, HasTypeThreading<Policies_>::value>::Type;
|
||||
|
||||
using ArgumentPassingMode = typename SelectArgumentPassingMode<
|
||||
Policies_,
|
||||
HasTypeArgumentPassingMode<Policies_>::value,
|
||||
ArgumentPassingExcludeEvent
|
||||
>::Type;
|
||||
|
||||
static_assert(! std::is_same<ArgumentPassingMode, ArgumentPassingAutoDetect>::value,
|
||||
"ArgumentPassingMode can't be ArgumentPassingAutoDetect in heterogeneous dispatcher.");
|
||||
|
||||
using CallbackList_ = HeterCallbackList<PrototypeList_, Policies_>;
|
||||
|
||||
using Map = typename SelectMap<
|
||||
EventType_,
|
||||
CallbackList_,
|
||||
Policies_,
|
||||
HasTemplateMap<Policies_>::value
|
||||
>::Type;
|
||||
|
||||
using Mixins = typename internal_::SelectMixins<
|
||||
Policies_,
|
||||
internal_::HasTypeMixins<Policies_>::value
|
||||
>::Type;
|
||||
|
||||
public:
|
||||
using PrototypeList = PrototypeList_;
|
||||
using Handle = typename CallbackList_::Handle;
|
||||
using Event = EventType_;
|
||||
using Mutex = typename Threading::Mutex;
|
||||
|
||||
public:
|
||||
HeterEventDispatcherBase()
|
||||
:
|
||||
eventCallbackListMap(),
|
||||
listenerMutex()
|
||||
{
|
||||
}
|
||||
|
||||
HeterEventDispatcherBase(const HeterEventDispatcherBase & other)
|
||||
:
|
||||
eventCallbackListMap(other.eventCallbackListMap),
|
||||
listenerMutex()
|
||||
{
|
||||
}
|
||||
|
||||
HeterEventDispatcherBase(HeterEventDispatcherBase && other) noexcept
|
||||
:
|
||||
eventCallbackListMap(std::move(other.eventCallbackListMap)),
|
||||
listenerMutex()
|
||||
{
|
||||
}
|
||||
|
||||
HeterEventDispatcherBase & operator = (const HeterEventDispatcherBase & other)
|
||||
{
|
||||
eventCallbackListMap = other.eventCallbackListMap;
|
||||
return *this;
|
||||
}
|
||||
|
||||
HeterEventDispatcherBase & operator = (HeterEventDispatcherBase && other) noexcept
|
||||
{
|
||||
eventCallbackListMap = std::move(other.eventCallbackListMap);
|
||||
return *this;
|
||||
}
|
||||
|
||||
void swap(HeterEventDispatcherBase & other) noexcept {
|
||||
using std::swap;
|
||||
|
||||
swap(eventCallbackListMap, other.eventCallbackListMap);
|
||||
}
|
||||
|
||||
template <typename C>
|
||||
Handle appendListener(const Event & event, const C & callback)
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(listenerMutex);
|
||||
|
||||
return eventCallbackListMap[event].append(callback);
|
||||
}
|
||||
|
||||
template <typename C>
|
||||
Handle prependListener(const Event & event, const C & callback)
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(listenerMutex);
|
||||
|
||||
return eventCallbackListMap[event].prepend(callback);
|
||||
}
|
||||
|
||||
template <typename C>
|
||||
Handle insertListener(const Event & event, const C & callback, const Handle & before)
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(listenerMutex);
|
||||
|
||||
return eventCallbackListMap[event].insert(callback, before);
|
||||
}
|
||||
|
||||
bool removeListener(const Event & event, const Handle handle)
|
||||
{
|
||||
CallbackList_ * callableList = doFindCallableList(event);
|
||||
if(callableList) {
|
||||
return callableList->remove(handle);
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool hasAnyListener(const Event & event) const
|
||||
{
|
||||
const CallbackList_ * callableList = doFindCallableList(event);
|
||||
if(callableList) {
|
||||
return ! callableList->empty();
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename Prototype, typename Func>
|
||||
void forEach(const Event & event, Func && func) const
|
||||
{
|
||||
const CallbackList_ * callableList = doFindCallableList(event);
|
||||
if(callableList) {
|
||||
callableList->template forEach<Prototype>(std::forward<Func>(func));
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Prototype, typename Func>
|
||||
bool forEachIf(const Event & event, Func && func) const
|
||||
{
|
||||
const CallbackList_ * callableList = doFindCallableList(event);
|
||||
if (callableList) {
|
||||
return callableList->template forEachIf<Prototype>(std::forward<Func>(func));
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
template <typename T, typename ...Args>
|
||||
void dispatch(T && first, Args && ...args) const
|
||||
{
|
||||
doDispatch<ArgumentPassingMode>(std::forward<T>(first), std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
// Bypass any getEvent policy. The first argument is the event type.
|
||||
// Most used for internal purpose.
|
||||
template <typename ...Args>
|
||||
void directDispatch(const Event & e, Args && ...args) const
|
||||
{
|
||||
if(! internal_::ForEachMixins<MixinRoot, Mixins, DoMixinBeforeDispatch>::forEach(
|
||||
this, typename std::add_lvalue_reference<Args>::type(args)...)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const CallbackList_ * callableList = doFindCallableList(e);
|
||||
if(callableList) {
|
||||
(*callableList)(std::forward<Args>(args)...);
|
||||
}
|
||||
}
|
||||
|
||||
protected:
|
||||
template <typename ArgumentMode, typename T, typename ...Args>
|
||||
auto doDispatch(T && first, Args && ...args) const
|
||||
-> typename std::enable_if<std::is_same<ArgumentMode, ArgumentPassingIncludeEvent>::value>::type
|
||||
{
|
||||
if(! internal_::ForEachMixins<MixinRoot, Mixins, DoMixinBeforeDispatch>::forEach(
|
||||
this,
|
||||
typename std::add_lvalue_reference<T>::type(first),
|
||||
typename std::add_lvalue_reference<Args>::type(args)...)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
using GetEvent = typename SelectGetEvent<Policies_, EventType_, HasFunctionGetEvent<Policies_, T &&, Args...>::value>::Type;
|
||||
const auto e = GetEvent::getEvent(std::forward<T>(first), args...);
|
||||
const CallbackList_ * callableList = doFindCallableList(e);
|
||||
if(callableList) {
|
||||
(*callableList)(std::forward<T>(first), std::forward<Args>(args)...);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename ArgumentMode, typename T, typename ...Args>
|
||||
auto doDispatch(T && first, Args && ...args) const
|
||||
-> typename std::enable_if<std::is_same<ArgumentMode, ArgumentPassingExcludeEvent>::value>::type
|
||||
{
|
||||
if(! internal_::ForEachMixins<MixinRoot, Mixins, DoMixinBeforeDispatch>::forEach(
|
||||
this,
|
||||
typename std::add_lvalue_reference<Args>::type(args)...)
|
||||
) {
|
||||
return;
|
||||
}
|
||||
|
||||
using GetEvent = typename SelectGetEvent<Policies_, EventType_, HasFunctionGetEvent<Policies_, T &&, Args...>::value>::Type;
|
||||
const auto e = GetEvent::getEvent(std::forward<T>(first), args...);
|
||||
const CallbackList_ * callableList = doFindCallableList(e);
|
||||
if(callableList) {
|
||||
(*callableList)(std::forward<Args>(args)...);
|
||||
}
|
||||
}
|
||||
|
||||
const CallbackList_ * doFindCallableList(const Event & e) const
|
||||
{
|
||||
return doFindCallableListHelper(this, e);
|
||||
}
|
||||
|
||||
CallbackList_ * doFindCallableList(const Event & e)
|
||||
{
|
||||
return doFindCallableListHelper(this, e);
|
||||
}
|
||||
|
||||
private:
|
||||
// template helper to avoid code duplication in doFindCallableList
|
||||
template <typename T>
|
||||
static auto doFindCallableListHelper(T * self, const Event & e)
|
||||
-> typename std::conditional<std::is_const<T>::value, const CallbackList_ *, CallbackList_ *>::type
|
||||
{
|
||||
std::lock_guard<Mutex> lockGuard(self->listenerMutex);
|
||||
|
||||
auto it = self->eventCallbackListMap.find(e);
|
||||
if(it != self->eventCallbackListMap.end()) {
|
||||
return &it->second;
|
||||
}
|
||||
else {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
return 0;
|
||||
}
|
||||
|
||||
private:
|
||||
// Mixin related
|
||||
struct DoMixinBeforeDispatch
|
||||
{
|
||||
template <typename T, typename Self, typename ...A>
|
||||
static auto forEach(const Self * self, A && ...args)
|
||||
-> typename std::enable_if<HasFunctionMixinBeforeDispatch<T, A...>::value, bool>::type {
|
||||
return static_cast<const T *>(self)->mixinBeforeDispatch(std::forward<A>(args)...);
|
||||
}
|
||||
|
||||
template <typename T, typename Self, typename ...A>
|
||||
static auto forEach(const Self * self, A && ...args)
|
||||
-> typename std::enable_if<! HasFunctionMixinBeforeDispatch<T, A...>::value, bool>::type {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
private:
|
||||
Map eventCallbackListMap;
|
||||
mutable Mutex listenerMutex;
|
||||
};
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
|
||||
template <
|
||||
typename Event_,
|
||||
typename PrototypeList_,
|
||||
typename Policies_ = DefaultPolicies
|
||||
>
|
||||
class HeterEventDispatcher : public internal_::InheritMixins<
|
||||
internal_::HeterEventDispatcherBase<Event_, PrototypeList_, Policies_, void>,
|
||||
typename internal_::SelectMixins<Policies_, internal_::HasTypeMixins<Policies_>::value >::Type
|
||||
>::Type, public TagEventDispatcher, public TagHeterEventDispatcher
|
||||
{
|
||||
private:
|
||||
using super = typename internal_::InheritMixins<
|
||||
internal_::HeterEventDispatcherBase<Event_, PrototypeList_, Policies_, void>,
|
||||
typename internal_::SelectMixins<Policies_, internal_::HasTypeMixins<Policies_>::value >::Type
|
||||
>::Type;
|
||||
|
||||
public:
|
||||
using super::super;
|
||||
|
||||
friend void swap(HeterEventDispatcher & first, HeterEventDispatcher & second) noexcept {
|
||||
first.swap(second);
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,482 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef HETEREVENTQUEUE_H_210892536510
|
||||
#define HETEREVENTQUEUE_H_210892536510
|
||||
|
||||
#include "hetereventdispatcher.h"
|
||||
|
||||
// temp, should move the internal code in eventqueue to separated file
|
||||
#include "eventqueue.h"
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <
|
||||
typename EventType_,
|
||||
typename PrototypeList_,
|
||||
typename Policies_
|
||||
>
|
||||
class HeterEventQueueBase : public HeterEventDispatcherBase<
|
||||
EventType_,
|
||||
PrototypeList_,
|
||||
Policies_,
|
||||
HeterEventQueueBase <
|
||||
EventType_,
|
||||
PrototypeList_,
|
||||
Policies_
|
||||
>
|
||||
>
|
||||
{
|
||||
private:
|
||||
using super = HeterEventDispatcherBase<
|
||||
EventType_,
|
||||
PrototypeList_,
|
||||
Policies_,
|
||||
HeterEventQueueBase <
|
||||
EventType_,
|
||||
PrototypeList_,
|
||||
Policies_
|
||||
>
|
||||
>;
|
||||
|
||||
using Policies = typename super::Policies;
|
||||
using Threading = typename super::Threading;
|
||||
using ConditionVariable = typename Threading::ConditionVariable;
|
||||
|
||||
struct QueuedItemBase;
|
||||
using ItemDispatcher = void (*)(const HeterEventQueueBase *, const QueuedItemBase &);
|
||||
|
||||
struct QueuedItemBase
|
||||
{
|
||||
QueuedItemBase(const int callableIndex, const EventType_ & event, const ItemDispatcher dispatcher)
|
||||
: callableIndex(callableIndex), event(event), dispatcher(dispatcher)
|
||||
{
|
||||
}
|
||||
|
||||
int callableIndex;
|
||||
EventType_ event;
|
||||
ItemDispatcher dispatcher;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct QueuedItem : public QueuedItemBase
|
||||
{
|
||||
QueuedItem(const int callableIndex, const EventType_ & event, const ItemDispatcher dispatcher, T && arguments)
|
||||
: QueuedItemBase(callableIndex, event, dispatcher), arguments(std::move(arguments))
|
||||
{
|
||||
}
|
||||
|
||||
T arguments;
|
||||
};
|
||||
|
||||
template <typename ...Args>
|
||||
using QueuedItemSizer = QueuedItem<std::tuple<typename std::remove_cv<typename std::remove_reference<Args>::type>::type...> >;
|
||||
|
||||
using BufferedQueuedItem = BufferedUnion<GetCallablePrototypeMaxSize<PrototypeList_, QueuedItemSizer>::value>;
|
||||
|
||||
using BufferedItemList = std::list<BufferedQueuedItem>;
|
||||
|
||||
using PrototypeList = typename super::PrototypeList;
|
||||
|
||||
using ArgumentPassingMode = typename super::ArgumentPassingMode;
|
||||
|
||||
public:
|
||||
using Event = typename super::Event;
|
||||
using Handle = typename super::Handle;
|
||||
using Mutex = typename super::Mutex;
|
||||
|
||||
public:
|
||||
HeterEventQueueBase()
|
||||
:
|
||||
super(),
|
||||
queueListConditionVariable(),
|
||||
queueEmptyCounter(0),
|
||||
queueNotifyCounter(0),
|
||||
queueListMutex(),
|
||||
queueList(),
|
||||
freeListMutex(),
|
||||
freeList()
|
||||
{
|
||||
}
|
||||
|
||||
HeterEventQueueBase(const HeterEventQueueBase & other)
|
||||
: super(other)
|
||||
{
|
||||
}
|
||||
|
||||
HeterEventQueueBase(HeterEventQueueBase && other) noexcept
|
||||
: super(std::move(other))
|
||||
{
|
||||
}
|
||||
|
||||
HeterEventQueueBase & operator = (const HeterEventQueueBase & other)
|
||||
{
|
||||
super::operator = (other);
|
||||
return *this;
|
||||
}
|
||||
|
||||
HeterEventQueueBase & operator = (HeterEventQueueBase && other) noexcept
|
||||
{
|
||||
super::operator = (std::move(other));
|
||||
return *this;
|
||||
}
|
||||
|
||||
template <typename T, typename ...Args>
|
||||
void enqueue(T && first, Args && ...args)
|
||||
{
|
||||
doEnqueue<ArgumentPassingMode>(std::forward<T>(first), std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
bool emptyQueue() const
|
||||
{
|
||||
return queueList.empty() && (queueEmptyCounter.load(std::memory_order_acquire) == 0);
|
||||
}
|
||||
|
||||
void clearEvents()
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
std::swap(queueList, tempList);
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
for(auto & item : tempList) {
|
||||
item.clear();
|
||||
}
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), tempList);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
bool process()
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
|
||||
// Use a counter to tell the queue list is not empty during processing
|
||||
// even though queueList is swapped to empty.
|
||||
CounterGuard<decltype(queueEmptyCounter)> counterGuard(queueEmptyCounter);
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
std::swap(queueList, tempList);
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
for(auto & item : tempList) {
|
||||
doDispatchQueuedEvent(item.template get<QueuedItemBase>());
|
||||
item.clear();
|
||||
}
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), tempList);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
bool processOne()
|
||||
{
|
||||
if(! queueList.empty()) {
|
||||
BufferedItemList tempList;
|
||||
|
||||
// Use a counter to tell the queue list is not empty during processing
|
||||
// even though queueList is swapped to empty.
|
||||
CounterGuard<decltype(queueEmptyCounter)> counterGuard(queueEmptyCounter);
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
if(! queueList.empty()) {
|
||||
tempList.splice(tempList.end(), queueList, queueList.begin());
|
||||
}
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
auto & item = tempList.front();
|
||||
doDispatchQueuedEvent(item.template get<QueuedItemBase>());
|
||||
item.clear();
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), tempList);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename F>
|
||||
bool processIf(F && func)
|
||||
{
|
||||
if(queueList.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
using PrototypeInfo = FindPrototypeByCallable<PrototypeList, F>;
|
||||
return doProcessIf<PrototypeInfo>(std::forward<F>(func));
|
||||
}
|
||||
|
||||
void wait() const
|
||||
{
|
||||
std::unique_lock<Mutex> queueListLock(queueListMutex);
|
||||
queueListConditionVariable.wait(queueListLock, [this]() -> bool {
|
||||
return doCanProcess();
|
||||
});
|
||||
}
|
||||
|
||||
template <class Rep, class Period>
|
||||
bool waitFor(const std::chrono::duration<Rep, Period> & duration) const
|
||||
{
|
||||
std::unique_lock<Mutex> queueListLock(queueListMutex);
|
||||
return queueListConditionVariable.wait_for(queueListLock, duration, [this]() -> bool {
|
||||
return doCanProcess();
|
||||
});
|
||||
}
|
||||
|
||||
using super::dispatch;
|
||||
|
||||
private:
|
||||
bool doCanProcess() const
|
||||
{
|
||||
return ! emptyQueue() && doCanNotifyQueueAvailable();
|
||||
}
|
||||
|
||||
bool doCanNotifyQueueAvailable() const
|
||||
{
|
||||
return queueNotifyCounter.load(std::memory_order_acquire) == 0;
|
||||
}
|
||||
|
||||
void doDispatchQueuedEvent(const QueuedItemBase & item)
|
||||
{
|
||||
item.dispatcher(this, item);
|
||||
}
|
||||
|
||||
template <typename PrototypeInfo>
|
||||
static void doDispatchItem(const HeterEventQueueBase * self, const QueuedItemBase & baseItem)
|
||||
{
|
||||
const auto & item = static_cast<const QueuedItem<typename PrototypeInfo::ArgsTuple> &>(baseItem);
|
||||
self->doDispatchQueuedItem<PrototypeInfo>(
|
||||
item,
|
||||
typename MakeIndexSequence<std::tuple_size<typename PrototypeInfo::ArgsTuple>::value>::Type()
|
||||
);
|
||||
}
|
||||
|
||||
template <typename PrototypeInfo, typename T, size_t ...Indexes>
|
||||
void doDispatchQueuedItem(T && item, IndexSequence<Indexes...>) const
|
||||
{
|
||||
this->directDispatch(item.event, std::get<Indexes>(item.arguments)...);
|
||||
}
|
||||
|
||||
template <typename PrototypeInfo, typename F>
|
||||
auto doProcessIf(F && func)
|
||||
-> typename std::enable_if<(PrototypeInfo::index >= 0), bool>::type
|
||||
{
|
||||
BufferedItemList tempList;
|
||||
BufferedItemList idleList;
|
||||
|
||||
// Use a counter to tell the queue list is not empty during processing
|
||||
// even though queueList is swapped to empty.
|
||||
CounterGuard<decltype(queueEmptyCounter)> counterGuard(queueEmptyCounter);
|
||||
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
std::swap(queueList, tempList);
|
||||
}
|
||||
|
||||
if(! tempList.empty()) {
|
||||
for(auto it = tempList.begin(); it != tempList.end(); ) {
|
||||
using ArgsTuple = typename PrototypeInfo::ArgsTuple;
|
||||
auto item = it->template get<QueuedItem<ArgsTuple> >();
|
||||
|
||||
if(item.callableIndex != PrototypeInfo::index) {
|
||||
++it;
|
||||
continue;
|
||||
}
|
||||
if(doInvokeFuncWithQueuedEvent(
|
||||
func,
|
||||
item,
|
||||
typename MakeIndexSequence<std::tuple_size<ArgsTuple>::value>::Type())
|
||||
) {
|
||||
doDispatchQueuedEvent(item);
|
||||
it->clear();
|
||||
|
||||
auto tempIt = it;
|
||||
++it;
|
||||
idleList.splice(idleList.end(), tempList, tempIt);
|
||||
}
|
||||
else {
|
||||
++it;
|
||||
}
|
||||
}
|
||||
|
||||
if (! tempList.empty()) {
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
queueList.splice(queueList.begin(), tempList);
|
||||
}
|
||||
|
||||
if(! idleList.empty()) {
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
freeList.splice(freeList.end(), idleList);
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
using NextPrototypeInfo = FindPrototypeByCallableFromIndex<PrototypeInfo::index + 1, PrototypeList, F>;
|
||||
if(doProcessIf<NextPrototypeInfo>(std::forward<F>(func))) {
|
||||
return true;
|
||||
}
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename PrototypeInfo, typename F>
|
||||
auto doProcessIf(F && /*func*/)
|
||||
-> typename std::enable_if<(PrototypeInfo::index < 0), bool>::type
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename F, typename T, size_t ...Indexes>
|
||||
bool doInvokeFuncWithQueuedEvent(F && func, T && item, IndexSequence<Indexes...>) const
|
||||
{
|
||||
return doInvokeFuncWithQueuedEventHelper(std::forward<F>(func), std::get<Indexes>(item.arguments)...);
|
||||
}
|
||||
|
||||
template <typename F, typename ...Args>
|
||||
bool doInvokeFuncWithQueuedEventHelper(F && func, Args && ...args) const
|
||||
{
|
||||
return func(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename ArgumentMode, typename T, typename ...Args>
|
||||
auto doEnqueue(T && first, Args && ...args)
|
||||
-> typename std::enable_if<std::is_same<ArgumentMode, ArgumentPassingIncludeEvent>::value>::type
|
||||
{
|
||||
using GetEvent = typename SelectGetEvent<Policies_, EventType_, HasFunctionGetEvent<Policies_, T &&, Args...>::value>::Type;
|
||||
using PrototypeInfo = FindPrototypeByArgs<PrototypeList_, T, Args...>;
|
||||
using QueuedItemType = QueuedItem<typename PrototypeInfo::ArgsTuple>;
|
||||
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
static_assert(std::tuple_size<typename PrototypeInfo::ArgsTuple>::value == 1 + sizeof...(Args), "Arguments count mismatch.");
|
||||
|
||||
doEnqueueItem(QueuedItemType(
|
||||
PrototypeInfo::index,
|
||||
GetEvent::getEvent(std::forward<T>(first), args...),
|
||||
&HeterEventQueueBase::doDispatchItem<PrototypeInfo>,
|
||||
typename PrototypeInfo::ArgsTuple(std::forward<T>(first), std::forward<Args>(args)...)
|
||||
));
|
||||
|
||||
if(doCanProcess()) {
|
||||
queueListConditionVariable.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
template <typename ArgumentMode, typename T, typename ...Args>
|
||||
auto doEnqueue(T && first, Args && ...args)
|
||||
-> typename std::enable_if<std::is_same<ArgumentMode, ArgumentPassingExcludeEvent>::value>::type
|
||||
{
|
||||
using GetEvent = typename SelectGetEvent<Policies_, EventType_, HasFunctionGetEvent<Policies_, T &&, Args...>::value>::Type;
|
||||
using PrototypeInfo = FindPrototypeByArgs<PrototypeList_, Args...>;
|
||||
using QueuedItemType = QueuedItem<typename PrototypeInfo::ArgsTuple>;
|
||||
|
||||
static_assert(PrototypeInfo::index >= 0, "Can't find invoker for the given argument types.");
|
||||
static_assert(std::tuple_size<typename PrototypeInfo::ArgsTuple>::value == sizeof...(Args), "Arguments count mismatch.");
|
||||
|
||||
doEnqueueItem(QueuedItemType(
|
||||
PrototypeInfo::index,
|
||||
GetEvent::getEvent(std::forward<T>(first), args...),
|
||||
&HeterEventQueueBase::doDispatchItem<PrototypeInfo>,
|
||||
typename PrototypeInfo::ArgsTuple(std::forward<Args>(args)...)
|
||||
));
|
||||
|
||||
if(doCanProcess()) {
|
||||
queueListConditionVariable.notify_one();
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void doEnqueueItem(T && item)
|
||||
{
|
||||
BufferedItemList tempList;
|
||||
if(! freeList.empty()) {
|
||||
{
|
||||
std::lock_guard<Mutex> queueListLock(freeListMutex);
|
||||
if(! freeList.empty()) {
|
||||
tempList.splice(tempList.end(), freeList, freeList.begin());
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if(tempList.empty()) {
|
||||
tempList.emplace_back();
|
||||
}
|
||||
|
||||
auto it = tempList.begin();
|
||||
it->set(std::move(item));
|
||||
|
||||
std::lock_guard<Mutex> queueListLock(queueListMutex);
|
||||
queueList.splice(queueList.end(), tempList, it);
|
||||
}
|
||||
|
||||
private:
|
||||
mutable ConditionVariable queueListConditionVariable;
|
||||
typename Threading::template Atomic<int> queueEmptyCounter;
|
||||
typename Threading::template Atomic<int> queueNotifyCounter;
|
||||
mutable Mutex queueListMutex;
|
||||
BufferedItemList queueList;
|
||||
Mutex freeListMutex;
|
||||
BufferedItemList freeList;
|
||||
};
|
||||
|
||||
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
template <
|
||||
typename Event_,
|
||||
typename PrototypeList_,
|
||||
typename Policies_ = DefaultPolicies
|
||||
>
|
||||
class HeterEventQueue : public internal_::InheritMixins<
|
||||
internal_::HeterEventQueueBase<Event_, PrototypeList_, Policies_>,
|
||||
typename internal_::SelectMixins<Policies_, internal_::HasTypeMixins<Policies_>::value >::Type
|
||||
>::Type, public TagEventDispatcher, public TagEventQueue, public TagHeterEventDispatcher, public TagHeterEventQueue
|
||||
{
|
||||
private:
|
||||
using super = typename internal_::InheritMixins<
|
||||
internal_::HeterEventQueueBase<Event_, PrototypeList_, Policies_>,
|
||||
typename internal_::SelectMixins<Policies_, internal_::HasTypeMixins<Policies_>::value >::Type
|
||||
>::Type;
|
||||
|
||||
public:
|
||||
using super::super;
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
// Don't include this header, include eventpolicies.h instead
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <typename T>
|
||||
struct HasTypeArgumentPassingMode
|
||||
{
|
||||
template <typename C> static std::true_type test(typename C::ArgumentPassingMode *) ;
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
template <typename T, bool, typename Default> struct SelectArgumentPassingMode { using Type = typename T::ArgumentPassingMode; };
|
||||
template <typename T, typename Default> struct SelectArgumentPassingMode <T, false, Default> { using Type = Default; };
|
||||
|
||||
template <typename T>
|
||||
struct HasTypeThreading
|
||||
{
|
||||
template <typename C> static std::true_type test(typename C::Threading *) ;
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
template <typename T, bool> struct SelectThreading { using Type = typename T::Threading; };
|
||||
template <typename T> struct SelectThreading <T, false> { using Type = MultipleThreading; };
|
||||
|
||||
template <typename T>
|
||||
struct HasTypeCallback
|
||||
{
|
||||
template <typename C> static std::true_type test(typename C::Callback *) ;
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
template <typename T, bool, typename D> struct SelectCallback { using Type = typename T::Callback; };
|
||||
template <typename T, typename D> struct SelectCallback<T, false, D> { using Type = D; };
|
||||
|
||||
template <typename T, typename ...Args>
|
||||
struct HasFunctionGetEvent
|
||||
{
|
||||
template <typename C> static std::true_type test(decltype(C::getEvent(std::declval<Args>()...)) *);
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
template <typename E>
|
||||
struct DefaultGetEvent
|
||||
{
|
||||
template <typename U, typename ...Args>
|
||||
static E getEvent(U && e, Args && ...) {
|
||||
return e;
|
||||
}
|
||||
};
|
||||
template <typename T, typename Key, bool> struct SelectGetEvent { using Type = T; };
|
||||
template <typename T, typename Key> struct SelectGetEvent<T, Key, false> { using Type = DefaultGetEvent<Key>; };
|
||||
|
||||
template <typename T, typename ...Args>
|
||||
struct HasFunctionCanContinueInvoking
|
||||
{
|
||||
template <typename C> static std::true_type test(decltype(C::canContinueInvoking(std::declval<Args>()...)) *) ;
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
struct DefaultCanContinueInvoking
|
||||
{
|
||||
template <typename ...Args>
|
||||
static bool canContinueInvoking(Args && ...) {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
template <typename T, bool> struct SelectCanContinueInvoking { using Type = T; };
|
||||
template <typename T> struct SelectCanContinueInvoking<T, false> { using Type = DefaultCanContinueInvoking; };
|
||||
|
||||
template <typename T>
|
||||
struct HasTemplateMap
|
||||
{
|
||||
template <typename C> static std::true_type test(typename C::template Map<int, int> *) ;
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
template <typename T>
|
||||
class HasHash
|
||||
{
|
||||
template <typename C> static std::true_type test(decltype(std::hash<C>()(std::declval<C>())) *) ;
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
public:
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
template <typename Key, typename Value, typename T, bool>
|
||||
struct SelectMap
|
||||
{
|
||||
using Type = typename T::template Map<Key, Value>;
|
||||
};
|
||||
template <typename Key, typename Value, typename T>
|
||||
struct SelectMap<Key, Value, T, false> {
|
||||
using Type = typename std::conditional<
|
||||
HasHash<Key>::value,
|
||||
std::unordered_map<Key, Value>,
|
||||
std::map<Key, Value>
|
||||
>::type;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct HasTemplateQueueList
|
||||
{
|
||||
template <typename C> static std::true_type test(typename C::template QueueList<int> *);
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
template <typename Value, typename T, bool>
|
||||
struct SelectQueueList
|
||||
{
|
||||
using Type = typename T::template QueueList<Value>;
|
||||
};
|
||||
template <typename Value, typename T>
|
||||
struct SelectQueueList<Value, T, false> {
|
||||
using Type = std::list<Value>;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct HasTypeMixins
|
||||
{
|
||||
template <typename C> static std::true_type test(typename C::Mixins *) ;
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
template <typename T, bool> struct SelectMixins { using Type = typename T::Mixins; };
|
||||
template <typename T> struct SelectMixins <T, false> { using Type = MixinList<>; };
|
||||
|
||||
|
||||
template <typename Root, typename TList>
|
||||
struct InheritMixins;
|
||||
|
||||
template <typename Root, template <typename> class T, template <typename> class ...Args>
|
||||
struct InheritMixins <Root, MixinList<T, Args...> >
|
||||
{
|
||||
using Type = T <typename InheritMixins<Root, MixinList<Args...> >::Type>;
|
||||
};
|
||||
|
||||
template <typename Root>
|
||||
struct InheritMixins <Root, MixinList<> >
|
||||
{
|
||||
using Type = Root;
|
||||
};
|
||||
|
||||
template <typename Root, typename TList, typename Func>
|
||||
struct ForEachMixins;
|
||||
|
||||
template <typename Func, typename Root, template <typename> class T, template <typename> class ...Args>
|
||||
struct ForEachMixins <Root, MixinList<T, Args...>, Func>
|
||||
{
|
||||
using Type = typename InheritMixins<Root, MixinList<T, Args...> >::Type;
|
||||
|
||||
template <typename ...A>
|
||||
static bool forEach(A && ...args) {
|
||||
if(Func::template forEach<Type>(args...)) {
|
||||
return ForEachMixins<Root, MixinList<Args...>, Func>::forEach(std::forward<A>(args)...);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename Root, typename Func>
|
||||
struct ForEachMixins <Root, MixinList<>, Func>
|
||||
{
|
||||
using Type = Root;
|
||||
|
||||
template <typename ...A>
|
||||
static bool forEach(A && .../*args*/) {
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T, typename ...Args>
|
||||
struct HasFunctionMixinBeforeDispatch
|
||||
{
|
||||
template <typename C> static std::true_type test(
|
||||
decltype(std::declval<C>().mixinBeforeDispatch(std::declval<Args>()...)) *
|
||||
);
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
|
||||
|
||||
} //namespace internal_
|
||||
@@ -0,0 +1,174 @@
|
||||
#ifndef EVENTQUEUE_I_H
|
||||
#define EVENTQUEUE_I_H
|
||||
|
||||
#include <array>
|
||||
#include <cassert>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <size_t ...Indexes>
|
||||
struct IndexSequence
|
||||
{
|
||||
};
|
||||
|
||||
template <size_t N, size_t ...Indexes>
|
||||
struct MakeIndexSequence : MakeIndexSequence <N - 1, N - 1, Indexes...>
|
||||
{
|
||||
};
|
||||
|
||||
template <std::size_t ...Indexes>
|
||||
struct MakeIndexSequence<0, Indexes...>
|
||||
{
|
||||
using Type = IndexSequence<Indexes...>;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct CounterGuard
|
||||
{
|
||||
explicit CounterGuard(T & v) : value(v) {
|
||||
++value;
|
||||
}
|
||||
|
||||
~CounterGuard() {
|
||||
--value;
|
||||
}
|
||||
|
||||
T & value;
|
||||
};
|
||||
|
||||
using DtorFunc = void (*)(void *);
|
||||
|
||||
template <typename T>
|
||||
void commonDtor(void * instance)
|
||||
{
|
||||
reinterpret_cast<T *>(instance)->~T();
|
||||
}
|
||||
|
||||
// used by EventQueue
|
||||
template <typename T>
|
||||
class BufferedItem
|
||||
{
|
||||
public:
|
||||
using ValueType = T;
|
||||
|
||||
public:
|
||||
explicit BufferedItem() : buffer(), dtor(nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
~BufferedItem()
|
||||
{
|
||||
if(dtor != nullptr) {
|
||||
clear();
|
||||
}
|
||||
}
|
||||
|
||||
BufferedItem(BufferedItem &&) = delete;
|
||||
BufferedItem(const BufferedItem &) = delete;
|
||||
BufferedItem & operator = (const BufferedItem &) = delete;
|
||||
|
||||
void set(T && item) {
|
||||
assert(dtor == nullptr);
|
||||
|
||||
new (buffer.data()) T(std::forward<T>(item));
|
||||
dtor = &commonDtor<T>;
|
||||
}
|
||||
|
||||
T & get() {
|
||||
assert(dtor != nullptr);
|
||||
|
||||
return *reinterpret_cast<T *>(buffer.data());
|
||||
}
|
||||
|
||||
const T & get() const {
|
||||
assert(dtor != nullptr);
|
||||
|
||||
return *reinterpret_cast<const T *>(buffer.data());
|
||||
}
|
||||
|
||||
void clear() {
|
||||
assert(dtor != nullptr);
|
||||
|
||||
dtor(buffer.data());
|
||||
dtor = nullptr;
|
||||
}
|
||||
|
||||
bool empty() const {
|
||||
return dtor == nullptr;
|
||||
}
|
||||
|
||||
private:
|
||||
std::array<char, sizeof(T)> buffer;
|
||||
DtorFunc dtor;
|
||||
};
|
||||
|
||||
|
||||
// used by HeterEventQueue
|
||||
template <size_t Size>
|
||||
class BufferedUnion
|
||||
{
|
||||
public:
|
||||
explicit BufferedUnion() : buffer(), dtor(nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
~BufferedUnion()
|
||||
{
|
||||
if(dtor != nullptr) {
|
||||
clear();
|
||||
}
|
||||
}
|
||||
|
||||
BufferedUnion(BufferedUnion &&) = delete;
|
||||
BufferedUnion(const BufferedUnion &) = delete;
|
||||
BufferedUnion & operator = (const BufferedUnion &) = delete;
|
||||
|
||||
template <typename U>
|
||||
void set(U && item) {
|
||||
static_assert(sizeof(U) <= Size, "Item is too large to fit in BufferedUnion");
|
||||
assert(dtor == nullptr);
|
||||
|
||||
new (buffer.data()) U(std::forward<U>(item));
|
||||
dtor = &commonDtor<U>;
|
||||
}
|
||||
|
||||
template <typename U>
|
||||
U & get() {
|
||||
assert(dtor != nullptr);
|
||||
|
||||
return *reinterpret_cast<U *>(buffer.data());
|
||||
}
|
||||
|
||||
template <typename U>
|
||||
const U & get() const {
|
||||
assert(dtor != nullptr);
|
||||
|
||||
return *reinterpret_cast<const U *>(buffer.data());
|
||||
}
|
||||
|
||||
void clear() {
|
||||
assert(dtor != nullptr);
|
||||
|
||||
dtor(buffer.data());
|
||||
dtor = nullptr;
|
||||
}
|
||||
|
||||
bool empty() const {
|
||||
return dtor == nullptr;
|
||||
}
|
||||
|
||||
private:
|
||||
std::array<char, Size> buffer;
|
||||
DtorFunc dtor;
|
||||
};
|
||||
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,292 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef HETERCALLBACKLIST_I_H
|
||||
#define HETERCALLBACKLIST_I_H
|
||||
|
||||
#include "typeutil_i.h"
|
||||
|
||||
#include <tuple>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
/*
|
||||
// We can't use std::tuple as HeterTuple because std::tuple is instantialized
|
||||
// somewhere in the Map in HeterEventDispatcherBase, that causes compile error
|
||||
// for that function type can't be declared.
|
||||
template <typename ...Types>
|
||||
using HeterTuple = std::tuple<Types...>;
|
||||
|
||||
template <typename T>
|
||||
struct HeterTupleSize;
|
||||
|
||||
template <typename ...Types>
|
||||
struct HeterTupleSize <HeterTuple <Types...> >
|
||||
{
|
||||
enum { value = std::tuple_size<HeterTuple <Types...> >::value };
|
||||
};
|
||||
*/
|
||||
|
||||
template <typename ...Types>
|
||||
struct HeterTuple
|
||||
{
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct HeterTupleSize;
|
||||
|
||||
template <typename ...Types>
|
||||
struct HeterTupleSize <HeterTuple <Types...> >
|
||||
{
|
||||
enum { value = sizeof...(Types) };
|
||||
};
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <typename T>
|
||||
struct FindPrototypeDefaultArgTransformer
|
||||
{
|
||||
using type = T;
|
||||
};
|
||||
|
||||
template <
|
||||
int N,
|
||||
typename PrototypeList_,
|
||||
typename Callable,
|
||||
template <typename> class ArgTransformer = FindPrototypeDefaultArgTransformer,
|
||||
int M = HeterTupleSize<PrototypeList_>::value,
|
||||
typename Enabled = void
|
||||
>
|
||||
struct FindPrototypeByCallableFromIndex;
|
||||
|
||||
template <
|
||||
int N,
|
||||
typename RT,
|
||||
typename ...Args,
|
||||
typename ...Others,
|
||||
typename Callable,
|
||||
template <typename> class ArgTransformer,
|
||||
int M
|
||||
>
|
||||
struct FindPrototypeByCallableFromIndex <
|
||||
N,
|
||||
HeterTuple<RT (Args...), Others...>,
|
||||
Callable,
|
||||
ArgTransformer,
|
||||
M,
|
||||
typename std::enable_if<(N < M)>::type
|
||||
>
|
||||
{
|
||||
enum { canInvoke = CanInvoke<Callable, typename ArgTransformer<Args>::type...>::value };
|
||||
|
||||
using Prototype = typename std::conditional<
|
||||
canInvoke,
|
||||
RT (Args...),
|
||||
typename FindPrototypeByCallableFromIndex<N + 1, HeterTuple<Others...>, Callable, ArgTransformer, M>::Prototype
|
||||
>::type;
|
||||
|
||||
using ArgsTuple = typename std::conditional<
|
||||
canInvoke,
|
||||
std::tuple<typename std::remove_cv<typename std::remove_reference<Args>::type>::type...>,
|
||||
typename FindPrototypeByCallableFromIndex<N + 1, HeterTuple<Others...>, Callable, ArgTransformer, M>::ArgsTuple
|
||||
>::type;
|
||||
|
||||
enum {
|
||||
index = canInvoke
|
||||
? N
|
||||
: FindPrototypeByCallableFromIndex<N + 1, HeterTuple<Others...>, Callable, ArgTransformer, M>::index
|
||||
};
|
||||
};
|
||||
|
||||
template <
|
||||
int N,
|
||||
typename PrototypeList_,
|
||||
typename Callable,
|
||||
template <typename> class ArgTransformer,
|
||||
int M
|
||||
>
|
||||
struct FindPrototypeByCallableFromIndex <
|
||||
N,
|
||||
PrototypeList_,
|
||||
Callable,
|
||||
ArgTransformer,
|
||||
M,
|
||||
typename std::enable_if<(N >= M)>::type
|
||||
>
|
||||
{
|
||||
using Prototype = void;
|
||||
|
||||
using ArgsTuple = std::tuple<>;
|
||||
|
||||
enum {
|
||||
index = -1
|
||||
};
|
||||
};
|
||||
|
||||
template <typename PrototypeList_, typename Callable, template <typename> class ArgTransformer = FindPrototypeDefaultArgTransformer>
|
||||
struct FindPrototypeByCallable : public FindPrototypeByCallableFromIndex <0, PrototypeList_, Callable, ArgTransformer>
|
||||
{
|
||||
};
|
||||
|
||||
template <int N, typename PrototypeList_, typename ...InArgs>
|
||||
struct FindPrototypeByArgsFromIndex;
|
||||
|
||||
template <int N, typename RT, typename ...Args, typename ...Others, typename ...InArgs>
|
||||
struct FindPrototypeByArgsFromIndex <N, HeterTuple<RT (Args...), Others...>, InArgs...>
|
||||
{
|
||||
enum { canInvoke = CanInvoke<RT (Args...), InArgs...>::value };
|
||||
|
||||
using Prototype = typename std::conditional<
|
||||
canInvoke,
|
||||
RT (Args...),
|
||||
typename FindPrototypeByArgsFromIndex<N + 1, HeterTuple<Others...>, InArgs...>::Prototype
|
||||
>::type;
|
||||
|
||||
using ArgsTuple = typename std::conditional<
|
||||
canInvoke,
|
||||
std::tuple<typename std::remove_cv<typename std::remove_reference<Args>::type>::type...>,
|
||||
typename FindPrototypeByArgsFromIndex<N + 1, HeterTuple<Others...>, InArgs...>::ArgsTuple
|
||||
>::type;
|
||||
|
||||
enum {
|
||||
index = canInvoke
|
||||
? N
|
||||
: FindPrototypeByArgsFromIndex<N + 1, HeterTuple<Others...>, InArgs...>::index
|
||||
};
|
||||
};
|
||||
|
||||
template <int N, typename ...InArgs>
|
||||
struct FindPrototypeByArgsFromIndex <N, HeterTuple<>, InArgs...>
|
||||
{
|
||||
using Prototype = void;
|
||||
|
||||
using ArgsTuple = std::tuple<>;
|
||||
|
||||
enum { index = -1 };
|
||||
};
|
||||
|
||||
template <typename PrototypeList_, typename ...InArgs>
|
||||
struct FindPrototypeByArgs : public FindPrototypeByArgsFromIndex <0, PrototypeList_, InArgs...>
|
||||
{
|
||||
};
|
||||
|
||||
template <int I, int N, typename PrototypeList_>
|
||||
struct FindPrototypeByIndexHelper;
|
||||
|
||||
template <int I, int N, typename RT, typename ...Args, typename ...Others>
|
||||
struct FindPrototypeByIndexHelper <I, N, HeterTuple<RT (Args...), Others...> >
|
||||
{
|
||||
using NextType = FindPrototypeByIndexHelper<I + 1, N, HeterTuple<Others...> >;
|
||||
using Prototype = typename NextType::Prototype;
|
||||
|
||||
using ArgsTuple = typename NextType::ArgsTuple;
|
||||
|
||||
enum { index = NextType::index };
|
||||
};
|
||||
|
||||
template <int N, typename RT, typename ...Args, typename ...Others>
|
||||
struct FindPrototypeByIndexHelper <N, N, HeterTuple<RT (Args...), Others...> >
|
||||
{
|
||||
using Prototype = RT (Args...);
|
||||
|
||||
using ArgsTuple = HeterTuple<typename std::remove_cv<typename std::remove_reference<Args>::type>::type...>;
|
||||
|
||||
enum { index = N };
|
||||
};
|
||||
|
||||
template <int I, int N>
|
||||
struct FindPrototypeByIndexHelper <I, N, HeterTuple<>>
|
||||
{
|
||||
using Prototype = void;
|
||||
|
||||
using ArgsTuple = HeterTuple<>;
|
||||
|
||||
enum { index = -1 };
|
||||
};
|
||||
|
||||
template <typename PrototypeList_, int N>
|
||||
struct FindPrototypeByIndex : public FindPrototypeByIndexHelper <0, N, PrototypeList_>
|
||||
{
|
||||
};
|
||||
|
||||
template <typename PrototypeList_, template <typename ...> class Record>
|
||||
struct GetCallablePrototypeMaxSize;
|
||||
|
||||
template <typename RT, typename ...Args, typename ...Others, template <typename ...> class Record>
|
||||
struct GetCallablePrototypeMaxSize <HeterTuple<RT (Args...), Others...>, Record>
|
||||
{
|
||||
enum {
|
||||
my = sizeof(Record<Args...>),
|
||||
other = GetCallablePrototypeMaxSize<HeterTuple<Others...>, Record>::value
|
||||
};
|
||||
enum { value = (my > other ? (int)my : (int)other) };
|
||||
};
|
||||
|
||||
template <template <typename ...> class Record>
|
||||
struct GetCallablePrototypeMaxSize <HeterTuple<>, Record>
|
||||
{
|
||||
enum { value = 1 }; // set minimum size to 1 instead of 0
|
||||
};
|
||||
|
||||
template <typename List, typename Item>
|
||||
struct PrependHeterTuple;
|
||||
|
||||
template <typename Item, typename ...Types>
|
||||
struct PrependHeterTuple <HeterTuple<Types...>, Item>
|
||||
{
|
||||
using Type = HeterTuple<Item, Types...>;
|
||||
};
|
||||
|
||||
template <typename List, typename Replacement>
|
||||
struct ReplaceReturnTypeList;
|
||||
|
||||
template <typename Replacement, typename RT, typename ...Args, typename ...Others>
|
||||
struct ReplaceReturnTypeList <HeterTuple<RT (Args...), Others...>, Replacement>
|
||||
{
|
||||
using Type = typename PrependHeterTuple<
|
||||
typename ReplaceReturnTypeList<HeterTuple<Others...>, Replacement>::Type,
|
||||
Replacement (Args...)
|
||||
>::Type;
|
||||
};
|
||||
|
||||
template <typename Replacement>
|
||||
struct ReplaceReturnTypeList <HeterTuple<>, Replacement>
|
||||
{
|
||||
using Type = HeterTuple<>;
|
||||
};
|
||||
|
||||
template <typename F, template <typename> class T>
|
||||
struct TransformArgumentsList;
|
||||
|
||||
template <template <typename> class T, typename RT, typename ...Args, typename ...Others>
|
||||
struct TransformArgumentsList <HeterTuple<RT (Args...), Others...>, T>
|
||||
{
|
||||
using Type = typename PrependHeterTuple<
|
||||
typename TransformArgumentsList<HeterTuple<Others...>, T>::Type,
|
||||
RT (typename T<Args>::type...)
|
||||
>::Type;
|
||||
};
|
||||
|
||||
template <template <typename> class T>
|
||||
struct TransformArgumentsList <HeterTuple<>, T>
|
||||
{
|
||||
using Type = HeterTuple<>;
|
||||
};
|
||||
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,127 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef TYPEUTIL_I_H
|
||||
#define TYPEUTIL_I_H
|
||||
|
||||
#include <utility>
|
||||
#include <tuple>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <typename F, template <typename> class T>
|
||||
struct TransformArguments;
|
||||
|
||||
template <template <typename> class T, typename RT, typename ...Args>
|
||||
struct TransformArguments <RT (Args...), T>
|
||||
{
|
||||
using Type = RT (typename T<Args>::type...);
|
||||
};
|
||||
|
||||
template <typename F, typename Replacement>
|
||||
struct ReplaceReturnType;
|
||||
|
||||
template <typename Replacement, typename RT, typename ...Args>
|
||||
struct ReplaceReturnType <RT (Args...), Replacement>
|
||||
{
|
||||
using Type = Replacement (Args...);
|
||||
};
|
||||
|
||||
template <int N, int M>
|
||||
struct IntToConstantHelper
|
||||
{
|
||||
template <typename C, typename ...Args>
|
||||
static auto find(const int index, C && c, Args && ...args)
|
||||
-> decltype(std::declval<C>().template operator()<0>(std::declval<Args>()...))
|
||||
{
|
||||
if(N == index) {
|
||||
return c.template operator()<N>(std::forward<Args>(args)...);
|
||||
}
|
||||
else {
|
||||
return IntToConstantHelper<N + 1, M>::find(index, std::forward<C>(c), std::forward<Args>(args)...);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
template <int M>
|
||||
struct IntToConstantHelper <M, M>
|
||||
{
|
||||
template <typename C, typename ...Args>
|
||||
static auto find(const int /*index*/, C && c, Args && ...args)
|
||||
-> decltype(std::declval<C>().template operator()<0>(std::declval<Args>()...))
|
||||
{
|
||||
return decltype(c.template operator()<0>(std::forward<Args>(args)...))();
|
||||
}
|
||||
};
|
||||
|
||||
template <int M, typename C, typename ...Args>
|
||||
auto intToConstant(const int index, C && c, Args && ...args)
|
||||
-> decltype(std::declval<C>().template operator()<0>(std::declval<Args>()...))
|
||||
{
|
||||
return IntToConstantHelper<0, M>::find(index, std::forward<C>(c), std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename F, typename ...Args>
|
||||
struct CanInvoke
|
||||
{
|
||||
template <typename U, typename ...X>
|
||||
static auto invoke(int) -> decltype(std::declval<U>()(std::declval<X>()...), std::true_type());
|
||||
|
||||
template <typename U, typename ...X>
|
||||
static auto invoke(...) -> std::false_type;
|
||||
|
||||
enum {
|
||||
value = !! decltype(invoke<F, Args...>(0))()
|
||||
};
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct ShiftTuple;
|
||||
|
||||
template <typename A, typename ...Args>
|
||||
struct ShiftTuple <std::tuple<A, Args...> >
|
||||
{
|
||||
using Type = std::tuple<Args...>;
|
||||
};
|
||||
|
||||
template <>
|
||||
struct ShiftTuple <std::tuple<> >
|
||||
{
|
||||
using Type = std::tuple<>;
|
||||
};
|
||||
|
||||
// for compile time debug
|
||||
template<typename T>
|
||||
void printTypeInCompileTime(T * = 0)
|
||||
{
|
||||
static_assert(std::is_same<T, int>::value && ! std::is_same<T, int>::value, "The error shows the type name.");
|
||||
}
|
||||
template<int N>
|
||||
void printIntInCompileTime()
|
||||
{
|
||||
int n = 0;
|
||||
switch(n) {
|
||||
case N:
|
||||
case N:
|
||||
break;
|
||||
};
|
||||
}
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef MIXINFILTER_H_713231680355
|
||||
#define MIXINFILTER_H_713231680355
|
||||
|
||||
#include "../callbacklist.h"
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
template <typename Base>
|
||||
class MixinFilter : public Base
|
||||
{
|
||||
private:
|
||||
using super = Base;
|
||||
|
||||
using BoolReferencePrototype = typename internal_::ReplaceReturnType<
|
||||
typename internal_::TransformArguments<
|
||||
typename super::Prototype,
|
||||
std::add_lvalue_reference
|
||||
>::Type,
|
||||
bool
|
||||
>::Type;
|
||||
|
||||
using Filter = std::function<BoolReferencePrototype>;
|
||||
using FilterList = CallbackList<BoolReferencePrototype>;
|
||||
|
||||
public:
|
||||
using FilterHandle = typename FilterList::Handle;
|
||||
|
||||
public:
|
||||
FilterHandle appendFilter(const Filter & filter)
|
||||
{
|
||||
return filterList.append(filter);
|
||||
}
|
||||
|
||||
bool removeFilter(const FilterHandle & filterHandle)
|
||||
{
|
||||
return filterList.remove(filterHandle);
|
||||
}
|
||||
|
||||
template <typename ...Args>
|
||||
bool mixinBeforeDispatch(Args && ...args) const {
|
||||
if(! filterList.empty()) {
|
||||
if(! filterList.forEachIf([&args...](typename FilterList::Callback & callback) {
|
||||
return callback(args...);
|
||||
})
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
FilterList filterList;
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,73 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef MIXINHETERFILTER_H_990158796753
|
||||
#define MIXINHETERFILTER_H_990158796753
|
||||
|
||||
#include "../hetercallbacklist.h"
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
template <typename Base>
|
||||
class MixinHeterFilter : public Base
|
||||
{
|
||||
private:
|
||||
using super = Base;
|
||||
|
||||
using BoolReferencePrototypeList = typename internal_::ReplaceReturnTypeList<
|
||||
typename internal_::TransformArgumentsList<
|
||||
typename super::PrototypeList,
|
||||
std::add_lvalue_reference
|
||||
>::Type,
|
||||
bool
|
||||
>::Type;
|
||||
|
||||
using FilterList = HeterCallbackList<BoolReferencePrototypeList>;
|
||||
|
||||
public:
|
||||
using FilterHandle = typename FilterList::Handle;
|
||||
|
||||
public:
|
||||
template <typename Callback>
|
||||
FilterHandle appendFilter(const Callback & filter)
|
||||
{
|
||||
return filterList.append(filter);
|
||||
}
|
||||
|
||||
bool removeFilter(const FilterHandle & filterHandle)
|
||||
{
|
||||
return filterList.remove(filterHandle);
|
||||
}
|
||||
|
||||
template <typename ...Args>
|
||||
bool mixinBeforeDispatch(Args && ...args) const {
|
||||
if(! filterList.template forEachIf<void (Args...)>([&args...](const typename std::function<bool (Args...)> & callback) -> bool {
|
||||
return callback(std::forward<Args>(args)...);
|
||||
})
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
private:
|
||||
FilterList filterList;
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,247 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef ANYDATA_H_320827729782
|
||||
#define ANYDATA_H_320827729782
|
||||
|
||||
#include <array>
|
||||
#include <type_traits>
|
||||
#include <cstdint>
|
||||
#include <cassert>
|
||||
#include <memory>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace anydata_internal_ {
|
||||
|
||||
template <typename T>
|
||||
void funcDeleteObject(void * object)
|
||||
{
|
||||
delete static_cast<T *>(object);
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void funcFreeObject(void * object)
|
||||
{
|
||||
static_cast<T *>(object)->~T();
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
auto doFuncMoveConstruct(void * object, void * buffer)
|
||||
-> typename std::enable_if<std::is_move_constructible<T>::value>::type
|
||||
{
|
||||
new (buffer) T(std::move(*(T *)object));
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
auto doFuncMoveConstruct(void * object, void * buffer)
|
||||
-> typename std::enable_if<! std::is_move_constructible<T>::value>::type
|
||||
{
|
||||
static_assert(std::is_move_constructible<T>::value, "AnyData: object must be either copy or move constructible");
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
void funcMoveConstruct(void * object, void * buffer)
|
||||
{
|
||||
doFuncMoveConstruct<T>(object, buffer);
|
||||
}
|
||||
|
||||
struct AnyDataFunctions
|
||||
{
|
||||
void (*free)(void *);
|
||||
void (*moveConstruct)(void *, void *);
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
const AnyDataFunctions * doGetAnyDataFunctions()
|
||||
{
|
||||
static const AnyDataFunctions functions {
|
||||
&funcFreeObject<T>,
|
||||
&funcMoveConstruct<T>
|
||||
};
|
||||
return &functions;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
struct RemoveCvRef
|
||||
{
|
||||
using Type = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
const AnyDataFunctions * getAnyDataFunctions()
|
||||
{
|
||||
using U = typename RemoveCvRef<T>::Type;
|
||||
return doGetAnyDataFunctions<U>();
|
||||
}
|
||||
|
||||
template <typename ...Ts>
|
||||
struct MaxSizeOf;
|
||||
|
||||
template <typename T, typename ...Ts>
|
||||
struct MaxSizeOf <T, Ts...>
|
||||
{
|
||||
static constexpr std::size_t otherSize = MaxSizeOf<Ts...>::value;
|
||||
static constexpr std::size_t tSize = sizeof(T);
|
||||
|
||||
static constexpr std::size_t value = tSize > otherSize ? tSize : otherSize;
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct MaxSizeOf <T>
|
||||
{
|
||||
static constexpr std::size_t value = sizeof(T);
|
||||
};
|
||||
|
||||
class LargeData
|
||||
{
|
||||
public:
|
||||
template <typename T>
|
||||
explicit LargeData(T && object) : data(), deleter() {
|
||||
using U = typename RemoveCvRef<T>::Type;
|
||||
deleter = &funcDeleteObject<U>;
|
||||
data = new U(std::forward<T>(object));
|
||||
}
|
||||
|
||||
~LargeData() {
|
||||
if(data != nullptr) {
|
||||
assert(deleter != nullptr);
|
||||
deleter(data);
|
||||
}
|
||||
}
|
||||
|
||||
LargeData(LargeData && other) : data(), deleter() {
|
||||
std::swap(data, other.data);
|
||||
std::swap(deleter, other.deleter);
|
||||
}
|
||||
|
||||
LargeData(const LargeData & other) = delete;
|
||||
LargeData & operator = (const LargeData & other) = delete;
|
||||
LargeData & operator = (LargeData && other) = delete;
|
||||
|
||||
const void * getAddress() const {
|
||||
return data;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
bool isType() const {
|
||||
using U = typename RemoveCvRef<T>::Type;
|
||||
return deleter == &funcDeleteObject<U>;
|
||||
}
|
||||
|
||||
private:
|
||||
void * data;
|
||||
void (*deleter)(void *);
|
||||
};
|
||||
|
||||
} //namespace anydata_internal_
|
||||
|
||||
template <std::size_t maxSize_>
|
||||
class AnyData
|
||||
{
|
||||
private:
|
||||
using LargeData = anydata_internal_::LargeData;
|
||||
static constexpr std::size_t maxSize = maxSize_ < sizeof(LargeData) ? sizeof(LargeData) : maxSize_;
|
||||
|
||||
static_assert(maxSize > 0, "AnyData: maxSize must be greater than 0");
|
||||
|
||||
public:
|
||||
~AnyData() {
|
||||
if(functions != nullptr) {
|
||||
functions->free(buffer.data());
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
AnyData(T && object,
|
||||
typename std::enable_if<(sizeof(typename anydata_internal_::RemoveCvRef<T>::Type) <= maxSize)>::type * = 0)
|
||||
: functions(anydata_internal_::getAnyDataFunctions<T>()), buffer() {
|
||||
using U = typename std::remove_reference<T>::type;
|
||||
new (buffer.data()) U(std::forward<T>(object));
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
AnyData(T && object,
|
||||
typename std::enable_if<(sizeof(typename anydata_internal_::RemoveCvRef<T>::Type) > maxSize)>::type * = 0)
|
||||
: functions(anydata_internal_::getAnyDataFunctions<LargeData>()), buffer() {
|
||||
new (buffer.data()) LargeData(std::forward<T>(object));
|
||||
}
|
||||
|
||||
AnyData(AnyData && other) : functions(other.functions), buffer() {
|
||||
if(functions != nullptr) {
|
||||
functions->moveConstruct(other.buffer.data(), buffer.data());
|
||||
}
|
||||
}
|
||||
|
||||
AnyData(const AnyData & other) = delete;
|
||||
AnyData(AnyData & other) = delete;
|
||||
AnyData & operator = (const AnyData & other) = delete;
|
||||
AnyData & operator = (AnyData && other) = delete;
|
||||
|
||||
template <typename T>
|
||||
const T & get() const {
|
||||
return *(T *)getAddress();
|
||||
}
|
||||
|
||||
const void * getAddress() const {
|
||||
assert(functions != nullptr);
|
||||
|
||||
if(! isLargerData()) {
|
||||
return buffer.data();
|
||||
}
|
||||
else {
|
||||
return ((const LargeData *)buffer.data())->getAddress();
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
bool isType() const {
|
||||
if(! isLargerData()) {
|
||||
return anydata_internal_::getAnyDataFunctions<T>() == functions;
|
||||
}
|
||||
else {
|
||||
return ((const LargeData *)buffer.data())->isType<T>();
|
||||
}
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
operator T & () const {
|
||||
return *(T *)getAddress();
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
operator T * () const {
|
||||
return (T *)getAddress();
|
||||
}
|
||||
|
||||
private:
|
||||
bool isLargerData() const {
|
||||
return functions == anydata_internal_::getAnyDataFunctions<LargeData>();
|
||||
}
|
||||
|
||||
private:
|
||||
const anydata_internal_::AnyDataFunctions * functions;
|
||||
std::array<std::uint8_t, maxSize> buffer;
|
||||
};
|
||||
|
||||
template <typename ...Ts>
|
||||
constexpr std::size_t maxSizeOf()
|
||||
{
|
||||
return anydata_internal_::MaxSizeOf<Ts...>::value;
|
||||
}
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,161 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef ANYID_H_320827729782
|
||||
#define ANYID_H_320827729782
|
||||
|
||||
#include <functional>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace anyid_internal_ {
|
||||
|
||||
template <typename T, typename Enabled = void>
|
||||
struct MakeHash;
|
||||
|
||||
template <typename T>
|
||||
struct MakeHash <T, typename std::enable_if<std::is_convertible<T, std::size_t>::value>::type>
|
||||
{
|
||||
std::size_t operator() (T value) const {
|
||||
return static_cast<std::size_t>(value);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct MakeHash <T, typename std::enable_if<! std::is_convertible<T, std::size_t>::value>::type>
|
||||
{
|
||||
std::size_t operator() (const T & value) const {
|
||||
return std::hash<T>()(value);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
class HasLess
|
||||
{
|
||||
template <typename C> static std::true_type test(decltype(std::declval<C>() < std::declval<C>()) *);
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
public:
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
auto compareLessThan(const T & a, const T & b)
|
||||
-> typename std::enable_if<HasLess<T>::value, bool>::type
|
||||
{
|
||||
return a < b;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
auto compareLessThan(const T &, const T &)
|
||||
-> typename std::enable_if<! HasLess<T>::value, bool>::type
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
class HasEqual
|
||||
{
|
||||
template <typename C> static std::true_type test(decltype(std::declval<C>() == std::declval<C>()) *);
|
||||
template <typename C> static std::false_type test(...);
|
||||
|
||||
public:
|
||||
enum { value = !! decltype(test<T>(0))() };
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
auto compareEqual(const T & a, const T & b)
|
||||
-> typename std::enable_if<HasEqual<T>::value, bool>::type
|
||||
{
|
||||
return a == b;
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
auto compareEqual(const T &, const T &)
|
||||
-> typename std::enable_if<! HasEqual<T>::value, bool>::type
|
||||
{
|
||||
return true;
|
||||
}
|
||||
|
||||
|
||||
} //namespace anyid_internal_
|
||||
|
||||
struct EmptyAnyStorage
|
||||
{
|
||||
EmptyAnyStorage() {}
|
||||
|
||||
template <typename T>
|
||||
EmptyAnyStorage(const T &) {}
|
||||
};
|
||||
|
||||
template <template <typename> class Digester = std::hash, typename Storage = EmptyAnyStorage>
|
||||
class AnyId
|
||||
{
|
||||
public:
|
||||
using DigestType = decltype(std::declval<Digester<int>>()(0));
|
||||
|
||||
public:
|
||||
AnyId() : digest(), value() {
|
||||
}
|
||||
|
||||
template <typename T>
|
||||
AnyId(const T & value)
|
||||
: digest(Digester<T>()(value)), value(value)
|
||||
{
|
||||
}
|
||||
|
||||
DigestType getDigest() const {
|
||||
return digest;
|
||||
}
|
||||
|
||||
const Storage & getValue() const {
|
||||
return value;
|
||||
}
|
||||
|
||||
private:
|
||||
DigestType digest;
|
||||
Storage value;
|
||||
};
|
||||
|
||||
template <template <typename> class Digester, typename Storage>
|
||||
bool operator == (const AnyId<Digester, Storage> & a, const AnyId<Digester, Storage> & b)
|
||||
{
|
||||
return a.getDigest() == b.getDigest() && anyid_internal_::compareEqual(a.getValue(), b.getValue());
|
||||
}
|
||||
|
||||
template <template <typename> class Digester, typename Storage>
|
||||
bool operator < (const AnyId<Digester, Storage> & a, const AnyId<Digester, Storage> & b)
|
||||
{
|
||||
return (a.getDigest() < b.getDigest())
|
||||
|| (anyid_internal_::compareLessThan(a.getValue(), b.getValue()) && a.getDigest() == b.getDigest())
|
||||
;
|
||||
}
|
||||
|
||||
using AnyHashableId = AnyId<>;
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
namespace std
|
||||
{
|
||||
template <template <typename> class Digester, typename Storage>
|
||||
struct hash<eventpp::AnyId<Digester, Storage> >
|
||||
{
|
||||
std::size_t operator()(const eventpp::AnyId<Digester, Storage> & value) const noexcept
|
||||
{
|
||||
return eventpp::anyid_internal_::MakeHash<typename eventpp::AnyId<Digester, Storage>::DigestType>()(value.getDigest());
|
||||
}
|
||||
};
|
||||
} //namespace std
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef ARGUMENTADAPTER_H_566280692673
|
||||
#define ARGUMENTADAPTER_H_566280692673
|
||||
|
||||
#include <memory>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace adapter_internal_ {
|
||||
|
||||
template <typename T>
|
||||
struct StaticCast
|
||||
{
|
||||
template <typename U>
|
||||
static T cast(U && value)
|
||||
{
|
||||
return static_cast<T>(value);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct StaticCast<std::shared_ptr<T> >
|
||||
{
|
||||
template <typename U>
|
||||
static std::shared_ptr<T> cast(U && value)
|
||||
{
|
||||
return std::static_pointer_cast<T>(value);
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct IsSharedPtr
|
||||
{
|
||||
enum { value = false };
|
||||
};
|
||||
|
||||
template <typename T>
|
||||
struct IsSharedPtr<std::shared_ptr<T> >
|
||||
{
|
||||
enum { value = true };
|
||||
};
|
||||
|
||||
template <typename ...Args>
|
||||
struct IsAnySharedPtr
|
||||
{
|
||||
enum { value = false };
|
||||
};
|
||||
|
||||
template <typename First, typename ...Others>
|
||||
struct IsAnySharedPtr <First, Others...>
|
||||
{
|
||||
enum { value = IsSharedPtr<First>::value
|
||||
|| IsAnySharedPtr<Others...>::value };
|
||||
};
|
||||
|
||||
} //namespace adapter_internal_
|
||||
|
||||
template <typename Func, typename Prototype, typename IsSharedPtr = void>
|
||||
struct ArgumentAdapter;
|
||||
|
||||
template <typename Func, typename R, typename ...Args>
|
||||
struct ArgumentAdapter <
|
||||
Func,
|
||||
R(Args...),
|
||||
typename std::enable_if<! adapter_internal_::IsAnySharedPtr<Args...>::value>::type
|
||||
>
|
||||
{
|
||||
explicit ArgumentAdapter(Func f)
|
||||
: func(std::move(f))
|
||||
{
|
||||
}
|
||||
|
||||
template <typename ...A>
|
||||
void operator() (A &&...args) {
|
||||
func(std::forward<Args>(static_cast<Args>(args))...);
|
||||
}
|
||||
|
||||
Func func;
|
||||
};
|
||||
|
||||
template <typename Func, typename R, typename ...Args>
|
||||
struct ArgumentAdapter <
|
||||
Func,
|
||||
R(Args...),
|
||||
typename std::enable_if<adapter_internal_::IsAnySharedPtr<Args...>::value>::type
|
||||
>
|
||||
{
|
||||
explicit ArgumentAdapter(Func f)
|
||||
: func(std::move(f))
|
||||
{
|
||||
}
|
||||
|
||||
template <typename ...A>
|
||||
void operator() (A &&...args) {
|
||||
func(std::forward<Args>(adapter_internal_::StaticCast<Args>::cast(args))...);
|
||||
}
|
||||
|
||||
Func func;
|
||||
};
|
||||
|
||||
template <template <typename> class Func, typename R, typename ...Args>
|
||||
ArgumentAdapter<Func<R(Args...)>, R(Args...)> argumentAdapter(Func<R(Args...)> func)
|
||||
{
|
||||
return ArgumentAdapter<Func<R(Args...)>, R(Args...)>(std::move(func));
|
||||
}
|
||||
|
||||
template <typename Prototype, typename Func>
|
||||
ArgumentAdapter<Func, Prototype> argumentAdapter(Func func)
|
||||
{
|
||||
return ArgumentAdapter<Func, Prototype>(std::move(func));
|
||||
}
|
||||
|
||||
template <typename R, typename ...Args>
|
||||
ArgumentAdapter<R(*)(Args...), R(Args...)> argumentAdapter(R(*func)(Args...))
|
||||
{
|
||||
return ArgumentAdapter<R(*)(Args...), R(Args...)>(std::move(func));
|
||||
}
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,50 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef CONDITIONALFUNCTOR_H_828958739581
|
||||
#define CONDITIONALFUNCTOR_H_828958739581
|
||||
|
||||
#include <utility>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
template <typename Func, typename Condition>
|
||||
struct ConditionalFunctor
|
||||
{
|
||||
ConditionalFunctor(Func f, Condition condition)
|
||||
: func(std::move(f)), condition(std::move(condition))
|
||||
{
|
||||
}
|
||||
|
||||
template <typename ...A>
|
||||
void operator() (A &&...args) {
|
||||
if(condition(args...)) {
|
||||
func(std::forward<A>(args)...);
|
||||
}
|
||||
}
|
||||
|
||||
Func func;
|
||||
Condition condition;
|
||||
};
|
||||
|
||||
template <typename Func, typename Condition>
|
||||
ConditionalFunctor<Func, Condition> conditionalFunctor(Func func, Condition condition)
|
||||
{
|
||||
return ConditionalFunctor<Func, Condition>(std::move(func), std::move(condition));
|
||||
}
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,222 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef CONDITIONALREMOVER_H_882115092280
|
||||
#define CONDITIONALREMOVER_H_882115092280
|
||||
|
||||
#include "../eventpolicies.h"
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
template <typename DispatcherType, typename Enabled = void>
|
||||
class ConditionalRemover;
|
||||
|
||||
template <typename DispatcherType>
|
||||
class ConditionalRemover <
|
||||
DispatcherType,
|
||||
typename std::enable_if<std::is_base_of<TagEventDispatcher, DispatcherType>::value>::type
|
||||
>
|
||||
{
|
||||
private:
|
||||
template <typename Callback, typename Condition>
|
||||
struct ItemByCondition
|
||||
{
|
||||
struct Data
|
||||
{
|
||||
Condition shouldRemove;
|
||||
DispatcherType & dispatcher;
|
||||
typename DispatcherType::Event event;
|
||||
Callback listener;
|
||||
typename DispatcherType::Handle handle;
|
||||
};
|
||||
|
||||
template <typename ...Args>
|
||||
auto operator() (Args && ...args) const
|
||||
-> typename std::enable_if<internal_::CanInvoke<Condition, Args...>::value>::type {
|
||||
if(data->shouldRemove(args...)) {
|
||||
data->dispatcher.removeListener(data->event, data->handle);
|
||||
}
|
||||
data->listener(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename ...Args>
|
||||
auto operator() (Args && ...args) const
|
||||
-> typename std::enable_if<! internal_::CanInvoke<Condition, Args...>::value>::type {
|
||||
if(data->shouldRemove()) {
|
||||
data->dispatcher.removeListener(data->event, data->handle);
|
||||
}
|
||||
data->listener(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
std::shared_ptr<Data> data;
|
||||
};
|
||||
|
||||
public:
|
||||
explicit ConditionalRemover(DispatcherType & dispatcher)
|
||||
: dispatcher(dispatcher)
|
||||
{
|
||||
}
|
||||
|
||||
template <typename Callback, typename Condition>
|
||||
typename DispatcherType::Handle appendListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener,
|
||||
const Condition & condition
|
||||
)
|
||||
{
|
||||
using Wrapper = ItemByCondition<Callback, Condition>;
|
||||
auto data = std::make_shared<typename Wrapper::Data>(typename Wrapper::Data {
|
||||
condition, dispatcher, event, listener, typename DispatcherType::Handle()
|
||||
});
|
||||
data->handle = dispatcher.appendListener(event, Wrapper{data});
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
template <typename Callback, typename Condition>
|
||||
typename DispatcherType::Handle prependListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener,
|
||||
const Condition & condition
|
||||
)
|
||||
{
|
||||
using Wrapper = ItemByCondition<Callback, Condition>;
|
||||
auto data = std::make_shared<typename Wrapper::Data>(typename Wrapper::Data {
|
||||
condition, dispatcher, event, listener, typename DispatcherType::Handle()
|
||||
});
|
||||
data->handle = dispatcher.prependListener(event, Wrapper{data});
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
template <typename Callback, typename Condition>
|
||||
typename DispatcherType::Handle insertListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener,
|
||||
const typename DispatcherType::Handle & before,
|
||||
const Condition & condition
|
||||
)
|
||||
{
|
||||
using Wrapper = ItemByCondition<Callback, Condition>;
|
||||
auto data = std::make_shared<typename Wrapper::Data>(typename Wrapper::Data {
|
||||
condition, dispatcher, event, listener, typename DispatcherType::Handle()
|
||||
});
|
||||
data->handle = dispatcher.insertListener(event, Wrapper{data}, before);
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
private:
|
||||
DispatcherType & dispatcher;
|
||||
};
|
||||
|
||||
template <typename CallbackListType>
|
||||
class ConditionalRemover <
|
||||
CallbackListType,
|
||||
typename std::enable_if<std::is_base_of<TagCallbackList, CallbackListType>::value>::type
|
||||
>
|
||||
{
|
||||
private:
|
||||
template <typename Callback, typename Condition>
|
||||
struct ItemByCondition
|
||||
{
|
||||
struct Data
|
||||
{
|
||||
Condition shouldRemove;
|
||||
CallbackListType & callbackList;
|
||||
Callback listener;
|
||||
typename CallbackListType::Handle handle;
|
||||
};
|
||||
|
||||
template <typename ...Args>
|
||||
auto operator() (Args && ...args) const
|
||||
-> typename std::enable_if<internal_::CanInvoke<Condition, Args...>::value>::type const {
|
||||
if(data->shouldRemove(args...)) {
|
||||
data->callbackList.remove(data->handle);
|
||||
}
|
||||
data->listener(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
template <typename ...Args>
|
||||
auto operator() (Args && ...args) const
|
||||
-> typename std::enable_if<! internal_::CanInvoke<Condition, Args...>::value>::type {
|
||||
if(data->shouldRemove()) {
|
||||
data->callbackList.remove(data->handle);
|
||||
}
|
||||
data->listener(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
std::shared_ptr<Data> data;
|
||||
};
|
||||
|
||||
public:
|
||||
explicit ConditionalRemover(CallbackListType & callbackList)
|
||||
: callbackList(callbackList)
|
||||
{
|
||||
}
|
||||
|
||||
template <typename Callback, typename Condition>
|
||||
typename CallbackListType::Handle append(
|
||||
const Callback & listener,
|
||||
const Condition & condition
|
||||
)
|
||||
{
|
||||
using Wrapper = ItemByCondition<Callback, Condition>;
|
||||
auto data = std::make_shared<typename Wrapper::Data>(typename Wrapper::Data {
|
||||
condition, callbackList, listener, typename CallbackListType::Handle()
|
||||
});
|
||||
data->handle = callbackList.append(Wrapper{data});
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
template <typename Callback, typename Condition>
|
||||
typename CallbackListType::Handle prepend(
|
||||
const Callback & listener,
|
||||
const Condition & condition
|
||||
)
|
||||
{
|
||||
using Wrapper = ItemByCondition<Callback, Condition>;
|
||||
auto data = std::make_shared<typename Wrapper::Data>(typename Wrapper::Data {
|
||||
condition, callbackList, listener, typename CallbackListType::Handle()
|
||||
});
|
||||
data->handle = callbackList.prepend(Wrapper{data});
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
template <typename Callback, typename Condition>
|
||||
typename CallbackListType::Handle insert(
|
||||
const Callback & listener,
|
||||
const typename CallbackListType::Handle & before,
|
||||
const Condition & condition
|
||||
)
|
||||
{
|
||||
using Wrapper = ItemByCondition<Callback, Condition>;
|
||||
auto data = std::make_shared<typename Wrapper::Data>(typename Wrapper::Data {
|
||||
condition, callbackList, listener, typename CallbackListType::Handle()
|
||||
});
|
||||
data->handle = callbackList.insert(Wrapper{data}, before);
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
private:
|
||||
CallbackListType & callbackList;
|
||||
};
|
||||
|
||||
template <typename DispatcherType>
|
||||
ConditionalRemover<DispatcherType> conditionalRemover(DispatcherType & dispatcher)
|
||||
{
|
||||
return ConditionalRemover<DispatcherType>(dispatcher);
|
||||
}
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,196 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef COUNTERREMOVER_H_211532679833
|
||||
#define COUNTERREMOVER_H_211532679833
|
||||
|
||||
#include "../eventpolicies.h"
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
template <typename DispatcherType, typename Enabled = void>
|
||||
class CounterRemover;
|
||||
|
||||
template <typename DispatcherType>
|
||||
class CounterRemover <
|
||||
DispatcherType,
|
||||
typename std::enable_if<std::is_base_of<TagEventDispatcher, DispatcherType>::value>::type
|
||||
>
|
||||
{
|
||||
private:
|
||||
template <typename Callback>
|
||||
struct Wrapper
|
||||
{
|
||||
struct Data
|
||||
{
|
||||
int triggerCount;
|
||||
DispatcherType & dispatcher;
|
||||
typename DispatcherType::Event event;
|
||||
Callback listener;
|
||||
typename DispatcherType::Handle handle;
|
||||
};
|
||||
|
||||
template <typename ...Args>
|
||||
void operator() (Args && ...args) const {
|
||||
if(--data->triggerCount <= 0) {
|
||||
data->dispatcher.removeListener(data->event, data->handle);
|
||||
}
|
||||
data->listener(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
std::shared_ptr<Data> data;
|
||||
};
|
||||
|
||||
public:
|
||||
explicit CounterRemover(DispatcherType & dispatcher)
|
||||
: dispatcher(dispatcher)
|
||||
{
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename DispatcherType::Handle appendListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener,
|
||||
const int triggerCount = 1
|
||||
)
|
||||
{
|
||||
auto data = std::make_shared<typename Wrapper<Callback>::Data>(typename Wrapper<Callback>::Data {
|
||||
triggerCount, dispatcher, event, listener, typename DispatcherType::Handle()
|
||||
});
|
||||
data->handle = dispatcher.appendListener(event, Wrapper<Callback>{data});
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename DispatcherType::Handle prependListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener,
|
||||
const int triggerCount = 1
|
||||
)
|
||||
{
|
||||
auto data = std::make_shared<typename Wrapper<Callback>::Data>(typename Wrapper<Callback>::Data {
|
||||
triggerCount, dispatcher, event, listener, typename DispatcherType::Handle()
|
||||
});
|
||||
data->handle = dispatcher.prependListener(event, Wrapper<Callback>{data});
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename DispatcherType::Handle insertListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener,
|
||||
const typename DispatcherType::Handle & before,
|
||||
const int triggerCount = 1
|
||||
)
|
||||
{
|
||||
auto data = std::make_shared<typename Wrapper<Callback>::Data>(typename Wrapper<Callback>::Data {
|
||||
triggerCount, dispatcher, event, listener, typename DispatcherType::Handle()
|
||||
});
|
||||
data->handle = dispatcher.insertListener(event, Wrapper<Callback>{data}, before);
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
private:
|
||||
DispatcherType & dispatcher;
|
||||
};
|
||||
|
||||
template <typename CallbackListType>
|
||||
class CounterRemover <
|
||||
CallbackListType,
|
||||
typename std::enable_if<std::is_base_of<TagCallbackList, CallbackListType>::value>::type
|
||||
>
|
||||
{
|
||||
private:
|
||||
template <typename Callback>
|
||||
struct Wrapper
|
||||
{
|
||||
struct Data
|
||||
{
|
||||
int triggerCount;
|
||||
CallbackListType & callbackList;
|
||||
Callback listener;
|
||||
typename CallbackListType::Handle handle;
|
||||
};
|
||||
|
||||
template <typename ...Args>
|
||||
void operator() (Args && ...args) const {
|
||||
if(--data->triggerCount <= 0) {
|
||||
data->callbackList.remove(data->handle);
|
||||
}
|
||||
data->listener(std::forward<Args>(args)...);
|
||||
}
|
||||
|
||||
std::shared_ptr<Data> data;
|
||||
};
|
||||
|
||||
public:
|
||||
explicit CounterRemover(CallbackListType & callbackList)
|
||||
: callbackList(callbackList)
|
||||
{
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename CallbackListType::Handle append(
|
||||
const Callback & listener,
|
||||
const int triggerCount = 1
|
||||
)
|
||||
{
|
||||
auto data = std::make_shared<typename Wrapper<Callback>::Data>(typename Wrapper<Callback>::Data {
|
||||
triggerCount, callbackList, listener, typename CallbackListType::Handle()
|
||||
});
|
||||
data->handle = callbackList.append(Wrapper<Callback>{data});
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename CallbackListType::Handle prepend(
|
||||
const Callback & listener,
|
||||
const int triggerCount = 1
|
||||
)
|
||||
{
|
||||
auto data = std::make_shared<typename Wrapper<Callback>::Data>(typename Wrapper<Callback>::Data {
|
||||
triggerCount, callbackList, listener, typename CallbackListType::Handle()
|
||||
});
|
||||
data->handle = callbackList.prepend(Wrapper<Callback>{data});
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename CallbackListType::Handle insert(
|
||||
const Callback & listener,
|
||||
const typename CallbackListType::Handle & before,
|
||||
const int triggerCount = 1
|
||||
)
|
||||
{
|
||||
auto data = std::make_shared<typename Wrapper<Callback>::Data>(typename Wrapper<Callback>::Data {
|
||||
triggerCount, callbackList, listener, typename CallbackListType::Handle()
|
||||
});
|
||||
data->handle = callbackList.insert(Wrapper<Callback>{data}, before);
|
||||
return data->handle;
|
||||
}
|
||||
|
||||
private:
|
||||
CallbackListType & callbackList;
|
||||
};
|
||||
|
||||
template <typename DispatcherType>
|
||||
CounterRemover<DispatcherType> counterRemover(DispatcherType & dispatcher)
|
||||
{
|
||||
return CounterRemover<DispatcherType>(dispatcher);
|
||||
}
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,177 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef EVENTMAKER_H_378278023815
|
||||
#define EVENTMAKER_H_378278023815
|
||||
|
||||
// auto generated macros begin
|
||||
|
||||
#define I_EVENTPP_ARG_COUNT(p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14, p15, ...) p15
|
||||
#define EVENTPP_ARG_COUNT(...) EVENTPP_EXPAND(I_EVENTPP_ARG_COUNT(__VA_ARGS__, 15, 14, 13, 12, 11, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0))
|
||||
|
||||
#define I_EVENTPP_ITERATE_ARGS_0(EXEC, DELI)
|
||||
#define I_EVENTPP_ITERATE_ARGS_1(EXEC, DELI, p0) I_EVENTPP_ITERATE_ARGS_0(EXEC, DELI ) EXEC(p0)
|
||||
#define I_EVENTPP_ITERATE_ARGS_2(EXEC, DELI, p0, p1) I_EVENTPP_ITERATE_ARGS_1(EXEC, DELI, p0) DELI() EXEC(p1)
|
||||
#define I_EVENTPP_ITERATE_ARGS_3(EXEC, DELI, p0, p1, p2) I_EVENTPP_ITERATE_ARGS_2(EXEC, DELI, p0, p1) DELI() EXEC(p2)
|
||||
#define I_EVENTPP_ITERATE_ARGS_4(EXEC, DELI, p0, p1, p2, p3) I_EVENTPP_ITERATE_ARGS_3(EXEC, DELI, p0, p1, p2) DELI() EXEC(p3)
|
||||
#define I_EVENTPP_ITERATE_ARGS_5(EXEC, DELI, p0, p1, p2, p3, p4) I_EVENTPP_ITERATE_ARGS_4(EXEC, DELI, p0, p1, p2, p3) DELI() EXEC(p4)
|
||||
#define I_EVENTPP_ITERATE_ARGS_6(EXEC, DELI, p0, p1, p2, p3, p4, p5) I_EVENTPP_ITERATE_ARGS_5(EXEC, DELI, p0, p1, p2, p3, p4) DELI() EXEC(p5)
|
||||
#define I_EVENTPP_ITERATE_ARGS_7(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6) I_EVENTPP_ITERATE_ARGS_6(EXEC, DELI, p0, p1, p2, p3, p4, p5) DELI() EXEC(p6)
|
||||
#define I_EVENTPP_ITERATE_ARGS_8(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7) I_EVENTPP_ITERATE_ARGS_7(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6) DELI() EXEC(p7)
|
||||
#define I_EVENTPP_ITERATE_ARGS_9(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8) I_EVENTPP_ITERATE_ARGS_8(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7) DELI() EXEC(p8)
|
||||
#define I_EVENTPP_ITERATE_ARGS_10(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9) I_EVENTPP_ITERATE_ARGS_9(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8) DELI() EXEC(p9)
|
||||
#define I_EVENTPP_ITERATE_ARGS_11(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10) I_EVENTPP_ITERATE_ARGS_10(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9) DELI() EXEC(p10)
|
||||
#define I_EVENTPP_ITERATE_ARGS_12(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11) I_EVENTPP_ITERATE_ARGS_11(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10) DELI() EXEC(p11)
|
||||
#define I_EVENTPP_ITERATE_ARGS_13(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12) I_EVENTPP_ITERATE_ARGS_12(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11) DELI() EXEC(p12)
|
||||
#define I_EVENTPP_ITERATE_ARGS_14(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13) I_EVENTPP_ITERATE_ARGS_13(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12) DELI() EXEC(p13)
|
||||
#define I_EVENTPP_ITERATE_ARGS_15(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13, p14) I_EVENTPP_ITERATE_ARGS_14(EXEC, DELI, p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, p10, p11, p12, p13) DELI() EXEC(p14)
|
||||
#define I_EVENTPP_ITERATE_ARGS_N(EXEC, DELI, N, ...) EVENTPP_EXPAND(EVENTPP_CONCAT(I_EVENTPP_ITERATE_ARGS_, N) (EXEC, DELI, __VA_ARGS__))
|
||||
#define EVENTPP_ITERATE_ARGS(EXEC, DELI, ...) I_EVENTPP_ITERATE_ARGS_N(EXEC, DELI, EVENTPP_ARG_COUNT(__VA_ARGS__), __VA_ARGS__)
|
||||
|
||||
// auto generated macros end
|
||||
|
||||
#define I_EVENTPP_STRINGIFY(x) #x
|
||||
#define EVENTPP_STRINGIFY(x) I_EVENTPP_STRINGIFY(x)
|
||||
|
||||
#define I_EVENTPP_CONCAT(a, b) a ## b
|
||||
#define EVENTPP_CONCAT(a, b) I_EVENTPP_CONCAT(a, b)
|
||||
|
||||
// EVENTPP_EXPAND is used to expand __VA_ARGS__ correctly in VC++
|
||||
#define EVENTPP_EXPAND(...) __VA_ARGS__
|
||||
#define EVENTPP_BRACKETS_EXPAND(...) EVENTPP_EXPAND(EVENTPP_EXPAND __VA_ARGS__)
|
||||
|
||||
#define EVENTPP_EMPTY()
|
||||
#define EVENTPP_COMMA() ,
|
||||
#define EVENTPP_SEMICOLON() ;
|
||||
|
||||
#define I_EVENTPP_GET0_2(p0, ...) p0
|
||||
#define I_EVENTPP_GET0(...) EVENTPP_EXPAND(I_EVENTPP_GET0_2(__VA_ARGS__, ))
|
||||
#define EVENTPP_GET0(p0) EVENTPP_EXPAND(I_EVENTPP_GET0 p0)
|
||||
|
||||
#define I_EVENTPP_GET1_2(p0, p1, ...) p1
|
||||
#define I_EVENTPP_GET1(...) EVENTPP_EXPAND(I_EVENTPP_GET1_2(__VA_ARGS__, ))
|
||||
#define EVENTPP_GET1(p0) EVENTPP_EXPAND(I_EVENTPP_GET1 p0)
|
||||
|
||||
#define I_EVENTPP_GET2_2(p0, p1, p2, ...) p2
|
||||
#define I_EVENTPP_GET2(...) EVENTPP_EXPAND(I_EVENTPP_GET2_2(__VA_ARGS__, ))
|
||||
#define EVENTPP_GET2(p0) EVENTPP_EXPAND(I_EVENTPP_GET2 p0)
|
||||
|
||||
#define EVENTPP_MAKE_FIELD_NAME(p0) EVENTPP_CONCAT(v, EVENTPP_GET1(p0))
|
||||
#define EVENTPP_EXEC_MAKE_FIELD(p0) EVENTPP_GET0(p0) EVENTPP_MAKE_FIELD_NAME(p0)
|
||||
#define EVENTPP_EXEC_MAKE_GETTER(p0) const EVENTPP_GET0(p0) & EVENTPP_GET1(p0) () const { return EVENTPP_MAKE_FIELD_NAME(p0); }
|
||||
|
||||
#define I_EVENTPP_EXEC_MAKE_SETTER_0(p0)
|
||||
#define I_EVENTPP_EXEC_MAKE_SETTER_1(p0)
|
||||
#define I_EVENTPP_EXEC_MAKE_SETTER_2(p0)
|
||||
#define I_EVENTPP_EXEC_MAKE_SETTER_3(p0) void EVENTPP_GET2(p0) (const EVENTPP_GET0(p0) & value) { EVENTPP_MAKE_FIELD_NAME(p0) = value; }
|
||||
#define I_EVENTPP_EXEC_MAKE_SETTER_4(p0) I_EVENTPP_MAKE_SETTER_HELPER_3(p0)
|
||||
#define I_EVENTPP_EXEC_MAKE_SETTER_5(p0) I_EVENTPP_MAKE_SETTER_HELPER_3(p0)
|
||||
#define I_EVENTPP_EXEC_MAKE_SETTER_6(p0) I_EVENTPP_MAKE_SETTER_HELPER_3(p0)
|
||||
#define I_EVENTPP_EXEC_MAKE_SETTER_N(N, p0) EVENTPP_EXPAND(EVENTPP_CONCAT(I_EVENTPP_EXEC_MAKE_SETTER_, N) (p0))
|
||||
#define EVENTPP_EXEC_MAKE_SETTER(p0) EVENTPP_EXPAND(I_EVENTPP_EXEC_MAKE_SETTER_N(EVENTPP_ARG_COUNT EVENTPP_EXPAND(p0), p0))
|
||||
|
||||
#define EVENTPP_EXEC_MAKE_INITIALIZE(p0) EVENTPP_MAKE_FIELD_NAME(p0)(EVENTPP_MAKE_FIELD_NAME(p0))
|
||||
#define EVENTPP_EXEC_MAKE_DEFAULT_INITIALIZE(p0) EVENTPP_MAKE_FIELD_NAME(p0)()
|
||||
#define EVENTPP_EXEC_MAKE_CTOR_FIELD(p0) const EVENTPP_GET0(p0) & EVENTPP_MAKE_FIELD_NAME(p0)
|
||||
|
||||
#define I_EVENTPP_CHECK(x, n, ...) n
|
||||
#define EVENTPP_CHECK(...) EVENTPP_EXPAND(I_EVENTPP_CHECK(__VA_ARGS__, 0, ))
|
||||
|
||||
#define I_EVENTPP_IS_ENCLOSED_BY_BRACKETS(...) x, 1
|
||||
#define EVENTPP_IS_ENCLOSED_BY_BRACKETS(x) EVENTPP_CHECK(I_EVENTPP_IS_ENCLOSED_BY_BRACKETS x)
|
||||
|
||||
#define I_EVENTPP_IF_1(t, f) t
|
||||
#define I_EVENTPP_IF_0(t, f) f
|
||||
#define EVENTPP_IF(b, t, f) EVENTPP_CONCAT(I_EVENTPP_IF_, b)(t, f)
|
||||
|
||||
#define EVENTPP_ADD_BACKETS(x) EVENTPP_IF(EVENTPP_IS_ENCLOSED_BY_BRACKETS(x), x, (x))
|
||||
#define EVENTPP_REMOVE_BACKETS(x) EVENTPP_BRACKETS_EXPAND(EVENTPP_IF(EVENTPP_IS_ENCLOSED_BY_BRACKETS(x), (EVENTPP_EXPAND x), (x)))
|
||||
|
||||
#define I_EVENTPP_MAKE_EVENT(className, baseClassName, baseClassArgs, ...) \
|
||||
class className : public EVENTPP_REMOVE_BACKETS(baseClassName) { \
|
||||
public: \
|
||||
className() \
|
||||
: EVENTPP_REMOVE_BACKETS(baseClassName) EVENTPP_ADD_BACKETS(baseClassArgs), \
|
||||
EVENTPP_ITERATE_ARGS(EVENTPP_EXEC_MAKE_DEFAULT_INITIALIZE, EVENTPP_COMMA, __VA_ARGS__) {} \
|
||||
className(EVENTPP_ITERATE_ARGS(EVENTPP_EXEC_MAKE_CTOR_FIELD, EVENTPP_COMMA, __VA_ARGS__)) \
|
||||
: EVENTPP_REMOVE_BACKETS(baseClassName) EVENTPP_ADD_BACKETS(baseClassArgs), \
|
||||
EVENTPP_ITERATE_ARGS(EVENTPP_EXEC_MAKE_INITIALIZE, EVENTPP_COMMA, __VA_ARGS__) {} \
|
||||
EVENTPP_ITERATE_ARGS(EVENTPP_EXEC_MAKE_GETTER, EVENTPP_EMPTY, __VA_ARGS__) \
|
||||
EVENTPP_ITERATE_ARGS(EVENTPP_EXEC_MAKE_SETTER, EVENTPP_EMPTY, __VA_ARGS__) \
|
||||
private: \
|
||||
EVENTPP_ITERATE_ARGS(EVENTPP_EXEC_MAKE_FIELD, EVENTPP_SEMICOLON, __VA_ARGS__); \
|
||||
}
|
||||
|
||||
#define EVENTPP_MAKE_EVENT(className, baseClassName, baseClassArgs, ...) EVENTPP_EXPAND(I_EVENTPP_MAKE_EVENT(className, baseClassName, baseClassArgs, __VA_ARGS__))
|
||||
|
||||
#define EVENTPP_MAKE_EMPTY_EVENT(className, baseClassName, baseClassArgs) \
|
||||
class className : public EVENTPP_REMOVE_BACKETS(baseClassName) { \
|
||||
public: \
|
||||
className() \
|
||||
: EVENTPP_REMOVE_BACKETS(baseClassName) EVENTPP_ADD_BACKETS(baseClassArgs) {} \
|
||||
}
|
||||
|
||||
|
||||
#endif
|
||||
|
||||
|
||||
/*
|
||||
Perl script to generate some of the macros
|
||||
|
||||
use strict;
|
||||
use warnings;
|
||||
|
||||
my $paramCount = 15;
|
||||
|
||||
sub outputParams
|
||||
{
|
||||
my ($count) = @_;
|
||||
|
||||
for(my $i = 0; $i < $count; ++$i) {
|
||||
print ', ' if($i > 0);
|
||||
print 'p', $i;
|
||||
}
|
||||
}
|
||||
|
||||
sub doMain
|
||||
{
|
||||
print '#define I_EVENTPP_ARG_COUNT(';
|
||||
&outputParams($paramCount + 1);
|
||||
print ', ...) p', $paramCount, "\n";
|
||||
print '#define EVENTPP_ARG_COUNT(...) EVENTPP_EXPAND(I_EVENTPP_ARG_COUNT(__VA_ARGS__';
|
||||
for(my $i = $paramCount; $i >= 0; --$i) {
|
||||
print ', ', $i;
|
||||
}
|
||||
print "))\n";
|
||||
print "\n";
|
||||
|
||||
print "#define I_EVENTPP_ITERATE_ARGS_0(EXEC, DELI)\n";
|
||||
for(my $i = 1; $i <= $paramCount; ++$i) {
|
||||
print '#define I_EVENTPP_ITERATE_ARGS_', $i, '(EXEC, DELI, ';
|
||||
&outputParams($i);
|
||||
print ') I_EVENTPP_ITERATE_ARGS_', ($i - 1), '(EXEC, DELI';
|
||||
print ($i > 1 ? ', ' : ' ');
|
||||
&outputParams($i - 1);
|
||||
print ')', ($i > 1 ? ' DELI()' : ''), ' EXEC(p', ($i - 1), ')';
|
||||
print "\n";
|
||||
}
|
||||
print "#define I_EVENTPP_ITERATE_ARGS_N(EXEC, DELI, N, ...) EVENTPP_EXPAND(EVENTPP_CONCAT(I_EVENTPP_ITERATE_ARGS_, N) (EXEC, DELI, __VA_ARGS__))\n";
|
||||
print "#define EVENTPP_ITERATE_ARGS(EXEC, DELI, ...) I_EVENTPP_ITERATE_ARGS_N(EXEC, DELI, EVENTPP_ARG_COUNT(__VA_ARGS__), __VA_ARGS__)\n";
|
||||
print "\n";
|
||||
|
||||
}
|
||||
|
||||
&doMain;
|
||||
|
||||
|
||||
*/
|
||||
@@ -0,0 +1,169 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef EVENTUTIL_H_802615012766
|
||||
#define EVENTUTIL_H_802615012766
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
template <typename DispatcherType>
|
||||
bool removeListener(
|
||||
DispatcherType & dispatcher,
|
||||
const typename DispatcherType::Event & event,
|
||||
const typename DispatcherType::Callback & listener
|
||||
)
|
||||
{
|
||||
bool found = false;
|
||||
dispatcher.forEachIf(
|
||||
event,
|
||||
[&found, &dispatcher, &event, &listener](
|
||||
const typename DispatcherType::Handle & handle,
|
||||
const typename DispatcherType::Callback & item
|
||||
) -> bool {
|
||||
if(item == listener) {
|
||||
found = true;
|
||||
dispatcher.removeListener(event, handle);
|
||||
return false;
|
||||
}
|
||||
else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
template <typename CallbackListType>
|
||||
bool removeListener(
|
||||
CallbackListType & callbackList,
|
||||
const typename CallbackListType::Callback & callback
|
||||
)
|
||||
{
|
||||
bool found = false;
|
||||
callbackList.forEachIf(
|
||||
[&found, &callbackList, &callback](
|
||||
const typename CallbackListType::Handle & handle,
|
||||
const typename CallbackListType::Callback & item
|
||||
) -> bool {
|
||||
if(item == callback) {
|
||||
found = true;
|
||||
callbackList.remove(handle);
|
||||
return false;
|
||||
}
|
||||
else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
template <typename DispatcherType>
|
||||
bool hasListener(
|
||||
DispatcherType & dispatcher,
|
||||
const typename DispatcherType::Event & event,
|
||||
const typename DispatcherType::Callback & listener
|
||||
)
|
||||
{
|
||||
bool found = false;
|
||||
dispatcher.forEachIf(
|
||||
event,
|
||||
[&found, &listener](
|
||||
const typename DispatcherType::Handle & /*handle*/,
|
||||
const typename DispatcherType::Callback & item
|
||||
) -> bool {
|
||||
if(item == listener) {
|
||||
found = true;
|
||||
return false;
|
||||
}
|
||||
else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
template <typename DispatcherType>
|
||||
bool hasAnyListener(
|
||||
DispatcherType & dispatcher,
|
||||
const typename DispatcherType::Event & event
|
||||
)
|
||||
{
|
||||
bool found = false;
|
||||
dispatcher.forEachIf(
|
||||
event,
|
||||
[&found](
|
||||
const typename DispatcherType::Handle & /*handle*/,
|
||||
const typename DispatcherType::Callback & /*item*/
|
||||
) -> bool {
|
||||
found = true;
|
||||
return false;
|
||||
}
|
||||
);
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
template <typename CallbackListType>
|
||||
bool hasListener(
|
||||
CallbackListType & callbackList,
|
||||
const typename CallbackListType::Callback & callback
|
||||
)
|
||||
{
|
||||
bool found = false;
|
||||
callbackList.forEachIf(
|
||||
[&found, &callback](
|
||||
const typename CallbackListType::Handle & /*handle*/,
|
||||
const typename CallbackListType::Callback & item
|
||||
) -> bool {
|
||||
if(item == callback) {
|
||||
found = true;
|
||||
return false;
|
||||
}
|
||||
else {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
template <typename CallbackListType>
|
||||
bool hasAnyListener(
|
||||
CallbackListType & callbackList
|
||||
)
|
||||
{
|
||||
bool found = false;
|
||||
callbackList.forEachIf(
|
||||
[&found](
|
||||
const typename CallbackListType::Handle & /*handle*/,
|
||||
const typename CallbackListType::Callback & /*item*/
|
||||
) -> bool {
|
||||
found = true;
|
||||
return false;
|
||||
}
|
||||
);
|
||||
|
||||
return found;
|
||||
}
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,81 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef ORDEREDQUEUELIST_H_862875671799
|
||||
#define ORDEREDQUEUELIST_H_862875671799
|
||||
|
||||
#include "../eventpolicies.h"
|
||||
|
||||
#include <list>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
struct OrderedQueueListCompare
|
||||
{
|
||||
template <typename T>
|
||||
bool operator() (const T & a, const T & b) const {
|
||||
return a.event < b.event;
|
||||
}
|
||||
};
|
||||
|
||||
template <typename T, typename Compare = OrderedQueueListCompare>
|
||||
class OrderedQueueList : private std::list<T>
|
||||
{
|
||||
private:
|
||||
using super = std::list<T>;
|
||||
|
||||
public:
|
||||
using iterator = typename super::iterator;
|
||||
using const_iterator = typename super::const_iterator;
|
||||
using super::empty;
|
||||
using super::begin;
|
||||
using super::end;
|
||||
using super::front;
|
||||
using super::swap;
|
||||
using super::emplace_back;
|
||||
|
||||
void splice(const_iterator pos, OrderedQueueList & other) {
|
||||
super::splice(pos, other);
|
||||
doSort();
|
||||
}
|
||||
|
||||
void splice(const_iterator pos, OrderedQueueList & other, const_iterator it) {
|
||||
super::splice(pos, other, it);
|
||||
doSort();
|
||||
}
|
||||
|
||||
private:
|
||||
void doSort() {
|
||||
auto compare = Compare();
|
||||
this->sort([compare](const T & a, const T & b) {
|
||||
// a and b may be empty if they are recycled to free list.
|
||||
if(a.empty()) {
|
||||
if(b.empty()) {
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
else if(b.empty()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return compare(a.get(), b.get());
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,330 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef SCOPEDREMOVER_H_695291515513
|
||||
#define SCOPEDREMOVER_H_695291515513
|
||||
|
||||
#include "../eventpolicies.h"
|
||||
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <typename Item, typename Handle, typename Mutex>
|
||||
bool removeHandleFromScopedRemoverItemList(std::vector<Item> & itemList, Handle & handle, Mutex & mutex)
|
||||
{
|
||||
if(! handle) {
|
||||
return false;
|
||||
}
|
||||
auto handlePointer = handle.lock();
|
||||
std::unique_lock<Mutex> lock(mutex);
|
||||
auto it = std::find_if(itemList.begin(), itemList.end(), [&handlePointer](Item & item) {
|
||||
return item.handle && item.handle.lock() == handlePointer;
|
||||
});
|
||||
if(it != itemList.end()) {
|
||||
itemList.erase(it);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
template <typename DispatcherType, typename Enabled = void>
|
||||
class ScopedRemover;
|
||||
|
||||
template <typename DispatcherType>
|
||||
class ScopedRemover <
|
||||
DispatcherType,
|
||||
typename std::enable_if<std::is_base_of<TagEventDispatcher, DispatcherType>::value>::type
|
||||
>
|
||||
{
|
||||
private:
|
||||
struct Item
|
||||
{
|
||||
typename DispatcherType::Event event;
|
||||
typename DispatcherType::Handle handle;
|
||||
};
|
||||
|
||||
public:
|
||||
ScopedRemover()
|
||||
: dispatcher(nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
explicit ScopedRemover(DispatcherType & dispatcher)
|
||||
: dispatcher(&dispatcher)
|
||||
{
|
||||
}
|
||||
|
||||
ScopedRemover(ScopedRemover && other) noexcept
|
||||
: dispatcher(std::move(other.dispatcher)), itemList(std::move(other.itemList))
|
||||
{
|
||||
other.reset();
|
||||
}
|
||||
|
||||
ScopedRemover & operator = (ScopedRemover && other) noexcept
|
||||
{
|
||||
dispatcher = std::move(other.dispatcher);
|
||||
itemList = std::move(other.itemList);
|
||||
other.reset();
|
||||
return *this;
|
||||
}
|
||||
|
||||
~ScopedRemover()
|
||||
{
|
||||
reset();
|
||||
}
|
||||
|
||||
void swap(ScopedRemover & other) noexcept {
|
||||
using std::swap;
|
||||
|
||||
swap(dispatcher, other.dispatcher);
|
||||
swap(itemList, other.itemList);
|
||||
}
|
||||
|
||||
void reset()
|
||||
{
|
||||
if(dispatcher != nullptr) {
|
||||
for(const auto & item : itemList) {
|
||||
dispatcher->removeListener(item.event, item.handle);
|
||||
}
|
||||
}
|
||||
|
||||
std::unique_lock<typename DispatcherType::Mutex> lock(itemListMutex);
|
||||
itemList.clear();
|
||||
}
|
||||
|
||||
void setDispatcher(DispatcherType & dispatcher_)
|
||||
{
|
||||
if(this->dispatcher != &dispatcher_) {
|
||||
reset();
|
||||
this->dispatcher = &dispatcher_;
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename DispatcherType::Handle appendListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener
|
||||
)
|
||||
{
|
||||
Item item {
|
||||
event,
|
||||
dispatcher->appendListener(event, listener)
|
||||
};
|
||||
|
||||
{
|
||||
std::unique_lock<typename DispatcherType::Mutex> lock(itemListMutex);
|
||||
itemList.push_back(item);
|
||||
}
|
||||
|
||||
return item.handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename DispatcherType::Handle prependListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener
|
||||
)
|
||||
{
|
||||
Item item {
|
||||
event,
|
||||
dispatcher->prependListener(event, listener)
|
||||
};
|
||||
|
||||
{
|
||||
std::unique_lock<typename DispatcherType::Mutex> lock(itemListMutex);
|
||||
itemList.push_back(item);
|
||||
}
|
||||
|
||||
return item.handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename DispatcherType::Handle insertListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener,
|
||||
const typename DispatcherType::Handle & before
|
||||
)
|
||||
{
|
||||
Item item {
|
||||
event,
|
||||
dispatcher->insertListener(event, listener, before)
|
||||
};
|
||||
|
||||
{
|
||||
std::unique_lock<typename DispatcherType::Mutex> lock(itemListMutex);
|
||||
itemList.push_back(item);
|
||||
}
|
||||
|
||||
return item.handle;
|
||||
}
|
||||
|
||||
bool removeListener(const typename DispatcherType::Event & event, const typename DispatcherType::Handle handle)
|
||||
{
|
||||
if(internal_::removeHandleFromScopedRemoverItemList(itemList, handle, itemListMutex)) {
|
||||
return dispatcher->removeListener(event, handle);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private:
|
||||
DispatcherType * dispatcher;
|
||||
std::vector<Item> itemList;
|
||||
typename DispatcherType::Mutex itemListMutex;
|
||||
};
|
||||
|
||||
template <typename CallbackListType>
|
||||
class ScopedRemover <
|
||||
CallbackListType,
|
||||
typename std::enable_if<std::is_base_of<TagCallbackList, CallbackListType>::value>::type
|
||||
>
|
||||
{
|
||||
private:
|
||||
struct Item
|
||||
{
|
||||
typename CallbackListType::Handle handle;
|
||||
};
|
||||
|
||||
public:
|
||||
ScopedRemover()
|
||||
: callbackList(nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
explicit ScopedRemover(CallbackListType & callbackList)
|
||||
: callbackList(&callbackList)
|
||||
{
|
||||
}
|
||||
|
||||
ScopedRemover(ScopedRemover && other) noexcept
|
||||
: callbackList(std::move(other.callbackList)), itemList(std::move(other.itemList))
|
||||
{
|
||||
other.reset();
|
||||
}
|
||||
|
||||
ScopedRemover & operator = (ScopedRemover && other) noexcept
|
||||
{
|
||||
callbackList = std::move(other.callbackList);
|
||||
itemList = std::move(other.itemList);
|
||||
other.reset();
|
||||
return *this;
|
||||
}
|
||||
|
||||
~ScopedRemover()
|
||||
{
|
||||
reset();
|
||||
}
|
||||
|
||||
void swap(ScopedRemover & other) noexcept {
|
||||
using std::swap;
|
||||
|
||||
swap(callbackList, other.callbackList);
|
||||
swap(itemList, other.itemList);
|
||||
}
|
||||
|
||||
void reset()
|
||||
{
|
||||
if(callbackList != nullptr) {
|
||||
for(const auto & item : itemList) {
|
||||
callbackList->remove(item.handle);
|
||||
}
|
||||
}
|
||||
|
||||
std::unique_lock<typename CallbackListType::Mutex> lock(itemListMutex);
|
||||
itemList.clear();
|
||||
}
|
||||
|
||||
void setCallbackList(CallbackListType & callbackList_)
|
||||
{
|
||||
if(this->callbackList != &callbackList_) {
|
||||
reset();
|
||||
this->callbackList = &callbackList_;
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename CallbackListType::Handle append(
|
||||
const Callback & callback
|
||||
)
|
||||
{
|
||||
Item item {
|
||||
callbackList->append(callback)
|
||||
};
|
||||
|
||||
{
|
||||
std::unique_lock<typename CallbackListType::Mutex> lock(itemListMutex);
|
||||
itemList.push_back(item);
|
||||
}
|
||||
|
||||
return item.handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename CallbackListType::Handle prepend(
|
||||
const Callback & callback
|
||||
)
|
||||
{
|
||||
Item item {
|
||||
callbackList->prepend(callback)
|
||||
};
|
||||
|
||||
{
|
||||
std::unique_lock<typename CallbackListType::Mutex> lock(itemListMutex);
|
||||
itemList.push_back(item);
|
||||
}
|
||||
|
||||
return item.handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename CallbackListType::Handle insert(
|
||||
const Callback & callback,
|
||||
const typename CallbackListType::Handle & before
|
||||
)
|
||||
{
|
||||
Item item {
|
||||
callbackList->insert(callback, before)
|
||||
};
|
||||
|
||||
{
|
||||
std::unique_lock<typename CallbackListType::Mutex> lock(itemListMutex);
|
||||
itemList.push_back(item);
|
||||
}
|
||||
|
||||
return item.handle;
|
||||
}
|
||||
|
||||
bool remove(const typename CallbackListType::Handle handle)
|
||||
{
|
||||
if(internal_::removeHandleFromScopedRemoverItemList(itemList, handle, itemListMutex)) {
|
||||
return callbackList->remove(handle);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private:
|
||||
CallbackListType * callbackList;
|
||||
std::vector<Item> itemList;
|
||||
typename CallbackListType::Mutex itemListMutex;
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
|
||||
@@ -1,9 +0,0 @@
|
||||
add_library(log.c STATIC
|
||||
log.c
|
||||
)
|
||||
|
||||
target_include_directories(log.c PUBLIC
|
||||
${CMAKE_CURRENT_SOURCE_DIR}
|
||||
)
|
||||
|
||||
target_compile_definitions(log.c PRIVATE LOG_USE_COLOR)
|
||||
@@ -1,241 +0,0 @@
|
||||
/*
|
||||
* Copyright (c) 2020 rxi
|
||||
*
|
||||
* 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.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Modified by xiaozhou233 (2025), based on work by rxi (MIT License).
|
||||
* - Add log setting
|
||||
* - log time switch
|
||||
* - log level switch
|
||||
* - log filename switch
|
||||
* - log line number switch
|
||||
* - log name prefix
|
||||
*/
|
||||
|
||||
#include "log.h"
|
||||
|
||||
#define MAX_CALLBACKS 32
|
||||
|
||||
typedef struct {
|
||||
log_LogFn fn;
|
||||
void *udata;
|
||||
int level;
|
||||
} Callback;
|
||||
|
||||
static struct {
|
||||
void *udata;
|
||||
log_LockFn lock;
|
||||
int level;
|
||||
bool quiet;
|
||||
Callback callbacks[MAX_CALLBACKS];
|
||||
|
||||
bool is_log_time;
|
||||
bool is_log_level;
|
||||
bool is_log_filename;
|
||||
bool is_log_line;
|
||||
|
||||
const char *logname;
|
||||
} L = {
|
||||
.is_log_time = true,
|
||||
.is_log_level = true,
|
||||
.is_log_filename = false,
|
||||
.is_log_line = false,
|
||||
.logname = NULL
|
||||
};
|
||||
|
||||
|
||||
static const char *level_strings[] = {
|
||||
"TRACE", "DEBUG", "INFO", "WARN", "ERROR", "FATAL"
|
||||
};
|
||||
|
||||
#ifdef LOG_USE_COLOR
|
||||
static const char *level_colors[] = {
|
||||
"\x1b[94m", "\x1b[36m", "\x1b[32m", "\x1b[33m", "\x1b[31m", "\x1b[35m"
|
||||
};
|
||||
#endif
|
||||
|
||||
|
||||
static void stdout_callback(log_Event *ev) {
|
||||
char buf[64] = {0};
|
||||
|
||||
if (L.is_log_time) {
|
||||
strftime(buf, sizeof(buf), "%H:%M:%S", ev->time);
|
||||
}
|
||||
|
||||
#ifdef LOG_USE_COLOR
|
||||
fprintf(ev->udata, "%s", LOG_USE_COLOR ? level_colors[ev->level] : "");
|
||||
|
||||
if (L.is_log_time)
|
||||
fprintf(ev->udata, "%s ", buf);
|
||||
|
||||
if (L.is_log_level)
|
||||
fprintf(ev->udata, "%-5s ", level_strings[ev->level]);
|
||||
|
||||
fprintf(ev->udata, "\x1b[0m");
|
||||
|
||||
if (L.is_log_filename)
|
||||
fprintf(ev->udata, "\x1b[90m%s", ev->file);
|
||||
|
||||
if (L.is_log_line)
|
||||
fprintf(ev->udata, ":%d", ev->line);
|
||||
|
||||
if (L.is_log_filename || L.is_log_line)
|
||||
fprintf(ev->udata, ":\x1b[0m ");
|
||||
#else
|
||||
if (L.is_log_time)
|
||||
fprintf(ev->udata, "%s ", buf);
|
||||
|
||||
if (L.is_log_level)
|
||||
fprintf(ev->udata, "%-5s ", level_strings[ev->level]);
|
||||
|
||||
if (L.is_log_filename)
|
||||
fprintf(ev->udata, "%s", ev->file);
|
||||
|
||||
if (L.is_log_line)
|
||||
fprintf(ev->udata, ":%d", ev->line);
|
||||
|
||||
if (L.is_log_filename || L.is_log_line)
|
||||
fprintf(ev->udata, ": ");
|
||||
#endif
|
||||
|
||||
if (L.logname) fprintf(ev->udata, "[%s] ", L.logname);
|
||||
|
||||
vfprintf(ev->udata, ev->fmt, ev->ap);
|
||||
fprintf(ev->udata, "\n");
|
||||
fflush(ev->udata);
|
||||
}
|
||||
|
||||
|
||||
static void file_callback(log_Event *ev) {
|
||||
char buf[64];
|
||||
buf[strftime(buf, sizeof(buf), "%Y-%m-%d %H:%M:%S", ev->time)] = '\0';
|
||||
fprintf(ev->udata, "%s %-5s ", buf, level_strings[ev->level]);
|
||||
fprintf(ev->udata, "%s:%d: ", ev->file, ev->line);
|
||||
if (L.logname) fprintf(ev->udata, "[%s] ", L.logname);
|
||||
vfprintf(ev->udata, ev->fmt, ev->ap);
|
||||
fprintf(ev->udata, "\n");
|
||||
fflush(ev->udata);
|
||||
}
|
||||
|
||||
|
||||
static void lock(void) {
|
||||
if (L.lock) { L.lock(true, L.udata); }
|
||||
}
|
||||
|
||||
|
||||
static void unlock(void) {
|
||||
if (L.lock) { L.lock(false, L.udata); }
|
||||
}
|
||||
|
||||
|
||||
const char* log_level_string(int level) {
|
||||
return level_strings[level];
|
||||
}
|
||||
|
||||
|
||||
void log_set_lock(log_LockFn fn, void *udata) {
|
||||
L.lock = fn;
|
||||
L.udata = udata;
|
||||
}
|
||||
|
||||
|
||||
void log_set_level(int level) {
|
||||
L.level = level;
|
||||
}
|
||||
|
||||
|
||||
void log_set_quiet(bool enable) {
|
||||
L.quiet = enable;
|
||||
}
|
||||
|
||||
|
||||
int log_add_callback(log_LogFn fn, void *udata, int level) {
|
||||
for (int i = 0; i < MAX_CALLBACKS; i++) {
|
||||
if (!L.callbacks[i].fn) {
|
||||
L.callbacks[i] = (Callback) { fn, udata, level };
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
|
||||
int log_add_fp(FILE *fp, int level) {
|
||||
return log_add_callback(file_callback, fp, level);
|
||||
}
|
||||
|
||||
|
||||
static void init_event(log_Event *ev, void *udata) {
|
||||
if (!ev->time) {
|
||||
time_t t = time(NULL);
|
||||
ev->time = localtime(&t);
|
||||
}
|
||||
ev->udata = udata;
|
||||
}
|
||||
|
||||
|
||||
void log_log(int level, const char *file, int line, const char *fmt, ...) {
|
||||
|
||||
log_Event ev = {
|
||||
.fmt = fmt,
|
||||
.file = file,
|
||||
.line = line,
|
||||
.level = level,
|
||||
};
|
||||
|
||||
lock();
|
||||
|
||||
if (!L.quiet && level >= L.level) {
|
||||
init_event(&ev, stderr);
|
||||
va_start(ev.ap, fmt);
|
||||
stdout_callback(&ev);
|
||||
va_end(ev.ap);
|
||||
}
|
||||
|
||||
for (int i = 0; i < MAX_CALLBACKS && L.callbacks[i].fn; i++) {
|
||||
Callback *cb = &L.callbacks[i];
|
||||
if (level >= cb->level) {
|
||||
init_event(&ev, cb->udata);
|
||||
va_start(ev.ap, fmt);
|
||||
cb->fn(&ev);
|
||||
va_end(ev.ap);
|
||||
}
|
||||
}
|
||||
|
||||
unlock();
|
||||
}
|
||||
|
||||
|
||||
void log_is_log_time(bool enable) {
|
||||
L.is_log_time = enable;
|
||||
}
|
||||
void log_is_log_level(bool enable) {
|
||||
L.is_log_level = enable;
|
||||
}
|
||||
void log_is_log_filename(bool enable) {
|
||||
L.is_log_filename = enable;
|
||||
}
|
||||
void log_is_log_line(bool enable) {
|
||||
L.is_log_line = enable;
|
||||
}
|
||||
void log_set_name(const char *name) {
|
||||
L.logname = name;
|
||||
}
|
||||
@@ -1,61 +0,0 @@
|
||||
/**
|
||||
* Copyright (c) 2020 rxi
|
||||
*
|
||||
* This library is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the MIT license. See `log.c` for details.
|
||||
*/
|
||||
|
||||
/*
|
||||
* Modified by xiaozhou233 (2025), based on work by rxi (MIT License).
|
||||
* See `log.c` for details.
|
||||
*/
|
||||
|
||||
#ifndef LOG_H
|
||||
#define LOG_H
|
||||
|
||||
#include <stdio.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdbool.h>
|
||||
#include <time.h>
|
||||
|
||||
#define LOG_VERSION "0.1.0"
|
||||
|
||||
typedef struct {
|
||||
va_list ap;
|
||||
const char *fmt;
|
||||
const char *file;
|
||||
struct tm *time;
|
||||
void *udata;
|
||||
int line;
|
||||
int level;
|
||||
} log_Event;
|
||||
|
||||
typedef void (*log_LogFn)(log_Event *ev);
|
||||
typedef void (*log_LockFn)(bool lock, void *udata);
|
||||
|
||||
enum { LOG_TRACE, LOG_DEBUG, LOG_INFO, LOG_WARN, LOG_ERROR, LOG_FATAL };
|
||||
|
||||
#define log_trace(...) log_log(LOG_TRACE, __FILE__, __LINE__, __VA_ARGS__)
|
||||
#define log_debug(...) log_log(LOG_DEBUG, __FILE__, __LINE__, __VA_ARGS__)
|
||||
#define log_info(...) log_log(LOG_INFO, __FILE__, __LINE__, __VA_ARGS__)
|
||||
#define log_warn(...) log_log(LOG_WARN, __FILE__, __LINE__, __VA_ARGS__)
|
||||
#define log_error(...) log_log(LOG_ERROR, __FILE__, __LINE__, __VA_ARGS__)
|
||||
#define log_fatal(...) log_log(LOG_FATAL, __FILE__, __LINE__, __VA_ARGS__)
|
||||
|
||||
const char* log_level_string(int level);
|
||||
void log_set_lock(log_LockFn fn, void *udata);
|
||||
void log_set_level(int level);
|
||||
void log_set_quiet(bool enable);
|
||||
int log_add_callback(log_LogFn fn, void *udata, int level);
|
||||
int log_add_fp(FILE *fp, int level);
|
||||
|
||||
// Add custom log formatting function
|
||||
void log_is_log_time(bool enable);
|
||||
void log_is_log_level(bool enable);
|
||||
void log_is_log_filename(bool enable);
|
||||
void log_is_log_line(bool enable);
|
||||
void log_set_name(const char *name);
|
||||
|
||||
void log_log(int level, const char *file, int line, const char *fmt, ...);
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,47 @@
|
||||
#pragma once
|
||||
#include <plog/Appenders/IAppender.h>
|
||||
#include <android/log.h>
|
||||
|
||||
namespace plog
|
||||
{
|
||||
template<class Formatter>
|
||||
class PLOG_LINKAGE_HIDDEN AndroidAppender : public IAppender
|
||||
{
|
||||
public:
|
||||
AndroidAppender(const char* tag) : m_tag(tag)
|
||||
{
|
||||
}
|
||||
|
||||
virtual void write(const Record& record) PLOG_OVERRIDE
|
||||
{
|
||||
std::string str = Formatter::format(record);
|
||||
|
||||
__android_log_print(toPriority(record.getSeverity()), m_tag, "%s", str.c_str());
|
||||
}
|
||||
|
||||
private:
|
||||
static android_LogPriority toPriority(Severity severity)
|
||||
{
|
||||
switch (severity)
|
||||
{
|
||||
case fatal:
|
||||
return ANDROID_LOG_FATAL;
|
||||
case error:
|
||||
return ANDROID_LOG_ERROR;
|
||||
case warning:
|
||||
return ANDROID_LOG_WARN;
|
||||
case info:
|
||||
return ANDROID_LOG_INFO;
|
||||
case debug:
|
||||
return ANDROID_LOG_DEBUG;
|
||||
case verbose:
|
||||
return ANDROID_LOG_VERBOSE;
|
||||
default:
|
||||
return ANDROID_LOG_UNKNOWN;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
const char* const m_tag;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
#include <plog/Appenders/IAppender.h>
|
||||
#include <Arduino.h>
|
||||
|
||||
namespace plog
|
||||
{
|
||||
template<class Formatter>
|
||||
class PLOG_LINKAGE_HIDDEN ArduinoAppender : public IAppender
|
||||
{
|
||||
public:
|
||||
ArduinoAppender(Stream &stream) : m_stream(stream)
|
||||
{
|
||||
}
|
||||
|
||||
virtual void write(const Record &record) PLOG_OVERRIDE
|
||||
{
|
||||
m_stream.print(Formatter::format(record).c_str());
|
||||
}
|
||||
|
||||
private:
|
||||
Stream &m_stream;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,108 @@
|
||||
#pragma once
|
||||
#include <plog/Appenders/ConsoleAppender.h>
|
||||
#include <plog/WinApi.h>
|
||||
|
||||
namespace plog
|
||||
{
|
||||
template<class Formatter>
|
||||
class PLOG_LINKAGE_HIDDEN ColorConsoleAppender : public ConsoleAppender<Formatter>
|
||||
{
|
||||
public:
|
||||
#ifdef _WIN32
|
||||
# ifdef _MSC_VER
|
||||
# pragma warning(suppress: 26812) // Prefer 'enum class' over 'enum'
|
||||
# endif
|
||||
ColorConsoleAppender(OutputStream outStream = streamStdOut)
|
||||
: ConsoleAppender<Formatter>(outStream)
|
||||
, m_originalAttr()
|
||||
{
|
||||
if (this->m_isatty)
|
||||
{
|
||||
CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
|
||||
GetConsoleScreenBufferInfo(this->m_outputHandle, &csbiInfo);
|
||||
|
||||
m_originalAttr = csbiInfo.wAttributes;
|
||||
}
|
||||
}
|
||||
#else
|
||||
ColorConsoleAppender(OutputStream outStream = streamStdOut)
|
||||
: ConsoleAppender<Formatter>(outStream)
|
||||
{}
|
||||
#endif
|
||||
|
||||
virtual void write(const Record& record) PLOG_OVERRIDE
|
||||
{
|
||||
util::nstring str = Formatter::format(record);
|
||||
util::MutexLock lock(this->m_mutex);
|
||||
|
||||
setColor(record.getSeverity());
|
||||
this->writestr(str);
|
||||
resetColor();
|
||||
}
|
||||
|
||||
protected:
|
||||
void setColor(Severity severity)
|
||||
{
|
||||
if (this->m_isatty)
|
||||
{
|
||||
switch (severity)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
case fatal:
|
||||
SetConsoleTextAttribute(this->m_outputHandle, foreground::kRed | foreground::kGreen | foreground::kBlue | foreground::kIntensity | background::kRed); // white on red background
|
||||
break;
|
||||
|
||||
case error:
|
||||
SetConsoleTextAttribute(this->m_outputHandle, static_cast<WORD>(foreground::kRed | foreground::kIntensity | (m_originalAttr & 0xf0))); // red
|
||||
break;
|
||||
|
||||
case warning:
|
||||
SetConsoleTextAttribute(this->m_outputHandle, static_cast<WORD>(foreground::kRed | foreground::kGreen | foreground::kIntensity | (m_originalAttr & 0xf0))); // yellow
|
||||
break;
|
||||
|
||||
case debug:
|
||||
case verbose:
|
||||
SetConsoleTextAttribute(this->m_outputHandle, static_cast<WORD>(foreground::kGreen | foreground::kBlue | foreground::kIntensity | (m_originalAttr & 0xf0))); // cyan
|
||||
break;
|
||||
#else
|
||||
case fatal:
|
||||
this->m_outputStream << "\x1B[97m\x1B[41m"; // white on red background
|
||||
break;
|
||||
|
||||
case error:
|
||||
this->m_outputStream << "\x1B[91m"; // red
|
||||
break;
|
||||
|
||||
case warning:
|
||||
this->m_outputStream << "\x1B[93m"; // yellow
|
||||
break;
|
||||
|
||||
case debug:
|
||||
case verbose:
|
||||
this->m_outputStream << "\x1B[96m"; // cyan
|
||||
break;
|
||||
#endif
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
void resetColor()
|
||||
{
|
||||
if (this->m_isatty)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
SetConsoleTextAttribute(this->m_outputHandle, m_originalAttr);
|
||||
#else
|
||||
this->m_outputStream << "\x1B[0m\x1B[0K";
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
#ifdef _WIN32
|
||||
WORD m_originalAttr;
|
||||
#endif
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,83 @@
|
||||
#pragma once
|
||||
#include <plog/Appenders/IAppender.h>
|
||||
#include <plog/Util.h>
|
||||
#include <plog/WinApi.h>
|
||||
#include <iostream>
|
||||
|
||||
namespace plog
|
||||
{
|
||||
enum OutputStream
|
||||
{
|
||||
streamStdOut,
|
||||
streamStdErr
|
||||
};
|
||||
|
||||
template<class Formatter>
|
||||
class PLOG_LINKAGE_HIDDEN ConsoleAppender : public IAppender
|
||||
{
|
||||
public:
|
||||
#ifdef _WIN32
|
||||
# ifdef _MSC_VER
|
||||
# pragma warning(suppress: 26812) // Prefer 'enum class' over 'enum'
|
||||
# endif
|
||||
ConsoleAppender(OutputStream outStream = streamStdOut)
|
||||
: m_isatty(!!_isatty(_fileno(outStream == streamStdOut ? stdout : stderr)))
|
||||
, m_outputStream(outStream == streamStdOut ? std::cout : std::cerr)
|
||||
, m_outputHandle()
|
||||
{
|
||||
if (m_isatty)
|
||||
{
|
||||
m_outputHandle = GetStdHandle(outStream == streamStdOut ? stdHandle::kOutput : stdHandle::kErrorOutput);
|
||||
}
|
||||
}
|
||||
#else
|
||||
ConsoleAppender(OutputStream outStream = streamStdOut)
|
||||
: m_isatty(!!isatty(fileno(outStream == streamStdOut ? stdout : stderr)))
|
||||
, m_outputStream(outStream == streamStdOut ? std::cout : std::cerr)
|
||||
{}
|
||||
#endif
|
||||
|
||||
virtual void write(const Record& record) PLOG_OVERRIDE
|
||||
{
|
||||
util::nstring str = Formatter::format(record);
|
||||
util::MutexLock lock(m_mutex);
|
||||
|
||||
writestr(str);
|
||||
}
|
||||
|
||||
protected:
|
||||
void writestr(const util::nstring& str)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
if (m_isatty)
|
||||
{
|
||||
const std::wstring& wstr = util::toWide(str);
|
||||
WriteConsoleW(m_outputHandle, wstr.c_str(), static_cast<DWORD>(wstr.size()), NULL, NULL);
|
||||
}
|
||||
else
|
||||
{
|
||||
# if PLOG_CHAR_IS_UTF8
|
||||
m_outputStream << str << std::flush;
|
||||
# else
|
||||
m_outputStream << util::toNarrow(str, codePage::kActive) << std::flush;
|
||||
# endif
|
||||
}
|
||||
#else
|
||||
m_outputStream << str << std::flush;
|
||||
#endif
|
||||
}
|
||||
|
||||
private:
|
||||
#ifdef __BORLANDC__
|
||||
static int _isatty(int fd) { return ::isatty(fd); }
|
||||
#endif
|
||||
|
||||
protected:
|
||||
util::Mutex m_mutex;
|
||||
const bool m_isatty;
|
||||
std::ostream& m_outputStream;
|
||||
#ifdef _WIN32
|
||||
HANDLE m_outputHandle;
|
||||
#endif
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
#pragma once
|
||||
#include <plog/Appenders/IAppender.h>
|
||||
#include <plog/WinApi.h>
|
||||
|
||||
namespace plog
|
||||
{
|
||||
template<class Formatter>
|
||||
class PLOG_LINKAGE_HIDDEN DebugOutputAppender : public IAppender
|
||||
{
|
||||
public:
|
||||
virtual void write(const Record& record) PLOG_OVERRIDE
|
||||
{
|
||||
OutputDebugStringW(util::toWide(Formatter::format(record)).c_str());
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
#pragma once
|
||||
#include <plog/Appenders/IAppender.h>
|
||||
#include <set>
|
||||
|
||||
namespace plog
|
||||
{
|
||||
class PLOG_LINKAGE_HIDDEN DynamicAppender : public IAppender
|
||||
{
|
||||
public:
|
||||
DynamicAppender& addAppender(IAppender* appender)
|
||||
{
|
||||
assert(appender != this);
|
||||
|
||||
util::MutexLock lock(m_mutex);
|
||||
m_appenders.insert(appender);
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
DynamicAppender& removeAppender(IAppender* appender)
|
||||
{
|
||||
util::MutexLock lock(m_mutex);
|
||||
m_appenders.erase(appender);
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
virtual void write(const Record& record) PLOG_OVERRIDE
|
||||
{
|
||||
util::MutexLock lock(m_mutex);
|
||||
|
||||
for (std::set<IAppender*>::iterator it = m_appenders.begin(); it != m_appenders.end(); ++it)
|
||||
{
|
||||
(*it)->write(record);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
mutable util::Mutex m_mutex;
|
||||
std::set<IAppender*> m_appenders;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
#pragma once
|
||||
#include <plog/Appenders/IAppender.h>
|
||||
#include <plog/WinApi.h>
|
||||
|
||||
namespace plog
|
||||
{
|
||||
template <class Formatter>
|
||||
class PLOG_LINKAGE_HIDDEN EventLogAppender : public IAppender
|
||||
{
|
||||
public:
|
||||
EventLogAppender(const util::nchar* sourceName) : m_eventSource(RegisterEventSourceW(NULL, util::toWide(sourceName).c_str()))
|
||||
{
|
||||
}
|
||||
|
||||
~EventLogAppender()
|
||||
{
|
||||
DeregisterEventSource(m_eventSource);
|
||||
}
|
||||
|
||||
virtual void write(const Record& record) PLOG_OVERRIDE
|
||||
{
|
||||
util::nstring str = Formatter::format(record);
|
||||
|
||||
write(record.getSeverity(), util::toWide(str).c_str());
|
||||
}
|
||||
|
||||
private:
|
||||
void write(Severity severity, const wchar_t* str)
|
||||
{
|
||||
const wchar_t* logMessagePtr[] = { str };
|
||||
|
||||
ReportEventW(m_eventSource, logSeverityToType(severity), static_cast<WORD>(severity), 0, NULL, 1, 0, logMessagePtr, NULL);
|
||||
}
|
||||
|
||||
static WORD logSeverityToType(plog::Severity severity)
|
||||
{
|
||||
switch (severity)
|
||||
{
|
||||
case plog::fatal:
|
||||
case plog::error:
|
||||
return eventLog::kErrorType;
|
||||
|
||||
case plog::warning:
|
||||
return eventLog::kWarningType;
|
||||
|
||||
case plog::info:
|
||||
case plog::debug:
|
||||
case plog::verbose:
|
||||
default:
|
||||
return eventLog::kInformationType;
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
HANDLE m_eventSource;
|
||||
};
|
||||
|
||||
class EventLogAppenderRegistry
|
||||
{
|
||||
public:
|
||||
static bool add(const util::nchar* sourceName, const util::nchar* logName = PLOG_NSTR("Application"))
|
||||
{
|
||||
std::wstring logKeyName;
|
||||
std::wstring sourceKeyName;
|
||||
getKeyNames(sourceName, logName, sourceKeyName, logKeyName);
|
||||
|
||||
HKEY sourceKey;
|
||||
if (0 != RegCreateKeyExW(hkey::kLocalMachine, sourceKeyName.c_str(), 0, NULL, 0, regSam::kSetValue, NULL, &sourceKey, NULL))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
const DWORD kTypesSupported = eventLog::kErrorType | eventLog::kWarningType | eventLog::kInformationType;
|
||||
RegSetValueExW(sourceKey, L"TypesSupported", 0, regType::kDword, reinterpret_cast<const BYTE*>(&kTypesSupported), sizeof(kTypesSupported));
|
||||
|
||||
const wchar_t kEventMessageFile[] = L"%windir%\\Microsoft.NET\\Framework\\v4.0.30319\\EventLogMessages.dll;%windir%\\Microsoft.NET\\Framework\\v2.0.50727\\EventLogMessages.dll";
|
||||
RegSetValueExW(sourceKey, L"EventMessageFile", 0, regType::kExpandSz, reinterpret_cast<const BYTE*>(kEventMessageFile), sizeof(kEventMessageFile) - sizeof(*kEventMessageFile));
|
||||
|
||||
RegCloseKey(sourceKey);
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool exists(const util::nchar* sourceName, const util::nchar* logName = PLOG_NSTR("Application"))
|
||||
{
|
||||
std::wstring logKeyName;
|
||||
std::wstring sourceKeyName;
|
||||
getKeyNames(sourceName, logName, sourceKeyName, logKeyName);
|
||||
|
||||
HKEY sourceKey;
|
||||
if (0 != RegOpenKeyExW(hkey::kLocalMachine, sourceKeyName.c_str(), 0, regSam::kQueryValue, &sourceKey))
|
||||
{
|
||||
return false;
|
||||
}
|
||||
|
||||
RegCloseKey(sourceKey);
|
||||
return true;
|
||||
}
|
||||
|
||||
static void remove(const util::nchar* sourceName, const util::nchar* logName = PLOG_NSTR("Application"))
|
||||
{
|
||||
std::wstring logKeyName;
|
||||
std::wstring sourceKeyName;
|
||||
getKeyNames(sourceName, logName, sourceKeyName, logKeyName);
|
||||
|
||||
RegDeleteKeyW(hkey::kLocalMachine, sourceKeyName.c_str());
|
||||
RegDeleteKeyW(hkey::kLocalMachine, logKeyName.c_str());
|
||||
}
|
||||
|
||||
private:
|
||||
static void getKeyNames(const util::nchar* sourceName, const util::nchar* logName, std::wstring& sourceKeyName, std::wstring& logKeyName)
|
||||
{
|
||||
const std::wstring kPrefix = L"SYSTEM\\CurrentControlSet\\Services\\EventLog\\";
|
||||
logKeyName = kPrefix + util::toWide(logName);
|
||||
sourceKeyName = logKeyName + L"\\" + util::toWide(sourceName);
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,16 @@
|
||||
#pragma once
|
||||
#include <plog/Record.h>
|
||||
#include <plog/Util.h>
|
||||
|
||||
namespace plog
|
||||
{
|
||||
class PLOG_LINKAGE IAppender
|
||||
{
|
||||
public:
|
||||
virtual ~IAppender()
|
||||
{
|
||||
}
|
||||
|
||||
virtual void write(const Record& record) = 0;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,148 @@
|
||||
#pragma once
|
||||
#include <plog/Appenders/IAppender.h>
|
||||
#include <plog/Converters/UTF8Converter.h>
|
||||
#include <plog/Converters/NativeEOLConverter.h>
|
||||
#include <plog/Util.h>
|
||||
#include <algorithm>
|
||||
|
||||
namespace plog
|
||||
{
|
||||
template<class Formatter, class Converter = NativeEOLConverter<UTF8Converter> >
|
||||
class PLOG_LINKAGE_HIDDEN RollingFileAppender : public IAppender
|
||||
{
|
||||
public:
|
||||
RollingFileAppender(const util::nchar* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
||||
: m_fileSize()
|
||||
, m_maxFileSize()
|
||||
, m_maxFiles(maxFiles)
|
||||
, m_firstWrite(true)
|
||||
{
|
||||
setFileName(fileName);
|
||||
setMaxFileSize(maxFileSize);
|
||||
}
|
||||
|
||||
#if defined(_WIN32) && !PLOG_CHAR_IS_UTF8
|
||||
RollingFileAppender(const char* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
||||
: m_fileSize()
|
||||
, m_maxFileSize()
|
||||
, m_maxFiles(maxFiles)
|
||||
, m_firstWrite(true)
|
||||
{
|
||||
setFileName(fileName);
|
||||
setMaxFileSize(maxFileSize);
|
||||
}
|
||||
#endif
|
||||
|
||||
virtual void write(const Record& record) PLOG_OVERRIDE
|
||||
{
|
||||
util::MutexLock lock(m_mutex);
|
||||
|
||||
if (m_firstWrite)
|
||||
{
|
||||
openLogFile();
|
||||
m_firstWrite = false;
|
||||
}
|
||||
else if (m_maxFiles > 0 && m_fileSize > m_maxFileSize && static_cast<size_t>(-1) != m_fileSize)
|
||||
{
|
||||
rollLogFiles();
|
||||
}
|
||||
|
||||
size_t bytesWritten = m_file.write(Converter::convert(Formatter::format(record)));
|
||||
|
||||
if (static_cast<size_t>(-1) != bytesWritten)
|
||||
{
|
||||
m_fileSize += bytesWritten;
|
||||
}
|
||||
}
|
||||
|
||||
void setFileName(const util::nchar* fileName)
|
||||
{
|
||||
util::MutexLock lock(m_mutex);
|
||||
|
||||
util::splitFileName(fileName, m_fileNameNoExt, m_fileExt);
|
||||
|
||||
m_file.close();
|
||||
m_firstWrite = true;
|
||||
}
|
||||
|
||||
#if defined(_WIN32) && !PLOG_CHAR_IS_UTF8
|
||||
void setFileName(const char* fileName)
|
||||
{
|
||||
setFileName(util::toWide(fileName).c_str());
|
||||
}
|
||||
#endif
|
||||
|
||||
void setMaxFiles(int maxFiles)
|
||||
{
|
||||
m_maxFiles = maxFiles;
|
||||
}
|
||||
|
||||
void setMaxFileSize(size_t maxFileSize)
|
||||
{
|
||||
m_maxFileSize = (std::max)(maxFileSize, static_cast<size_t>(1000)); // set a lower limit for the maxFileSize
|
||||
}
|
||||
|
||||
void rollLogFiles()
|
||||
{
|
||||
m_file.close();
|
||||
|
||||
util::nstring lastFileName = buildFileName(m_maxFiles - 1);
|
||||
util::File::unlink(lastFileName);
|
||||
|
||||
for (int fileNumber = m_maxFiles - 2; fileNumber >= 0; --fileNumber)
|
||||
{
|
||||
util::nstring currentFileName = buildFileName(fileNumber);
|
||||
util::nstring nextFileName = buildFileName(fileNumber + 1);
|
||||
|
||||
util::File::rename(currentFileName, nextFileName);
|
||||
}
|
||||
|
||||
openLogFile();
|
||||
m_firstWrite = false;
|
||||
}
|
||||
|
||||
private:
|
||||
void openLogFile()
|
||||
{
|
||||
m_fileSize = m_file.open(buildFileName());
|
||||
|
||||
if (0 == m_fileSize)
|
||||
{
|
||||
size_t bytesWritten = m_file.write(Converter::header(Formatter::header()));
|
||||
|
||||
if (static_cast<size_t>(-1) != bytesWritten)
|
||||
{
|
||||
m_fileSize += bytesWritten;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
util::nstring buildFileName(int fileNumber = 0)
|
||||
{
|
||||
util::nostringstream ss;
|
||||
ss << m_fileNameNoExt;
|
||||
|
||||
if (fileNumber > 0)
|
||||
{
|
||||
ss << '.' << fileNumber;
|
||||
}
|
||||
|
||||
if (!m_fileExt.empty())
|
||||
{
|
||||
ss << '.' << m_fileExt;
|
||||
}
|
||||
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
private:
|
||||
util::Mutex m_mutex;
|
||||
util::File m_file;
|
||||
size_t m_fileSize;
|
||||
size_t m_maxFileSize;
|
||||
int m_maxFiles;
|
||||
util::nstring m_fileExt;
|
||||
util::nstring m_fileNameNoExt;
|
||||
bool m_firstWrite;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
#pragma once
|
||||
#include <plog/Converters/UTF8Converter.h>
|
||||
#include <plog/Util.h>
|
||||
|
||||
namespace plog
|
||||
{
|
||||
template<class NextConverter = UTF8Converter>
|
||||
class NativeEOLConverter : public NextConverter
|
||||
{
|
||||
#ifdef _WIN32
|
||||
public:
|
||||
static std::string header(const util::nstring& str)
|
||||
{
|
||||
return NextConverter::header(fixLineEndings(str));
|
||||
}
|
||||
|
||||
static std::string convert(const util::nstring& str)
|
||||
{
|
||||
return NextConverter::convert(fixLineEndings(str));
|
||||
}
|
||||
|
||||
private:
|
||||
static util::nstring fixLineEndings(const util::nstring& str)
|
||||
{
|
||||
util::nstring output;
|
||||
output.reserve(str.length() * 2); // the worst case requires 2x chars
|
||||
|
||||
for (size_t i = 0; i < str.size(); ++i)
|
||||
{
|
||||
util::nchar ch = str[i];
|
||||
|
||||
if (ch == PLOG_NSTR('\n'))
|
||||
{
|
||||
output.push_back(PLOG_NSTR('\r'));
|
||||
}
|
||||
|
||||
output.push_back(ch);
|
||||
}
|
||||
|
||||
return output;
|
||||
}
|
||||
#endif
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
#include <plog/Util.h>
|
||||
|
||||
namespace plog
|
||||
{
|
||||
class UTF8Converter
|
||||
{
|
||||
public:
|
||||
static std::string header(const util::nstring& str)
|
||||
{
|
||||
const char kBOM[] = "\xEF\xBB\xBF";
|
||||
|
||||
return std::string(kBOM) + convert(str);
|
||||
}
|
||||
|
||||
#if PLOG_CHAR_IS_UTF8
|
||||
static const std::string& convert(const util::nstring& str)
|
||||
{
|
||||
return str;
|
||||
}
|
||||
#else
|
||||
static std::string convert(const util::nstring& str)
|
||||
{
|
||||
return util::toNarrow(str, codePage::kUTF8);
|
||||
}
|
||||
#endif
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
#pragma once
|
||||
#include <plog/Record.h>
|
||||
#include <plog/Util.h>
|
||||
#include <iomanip>
|
||||
|
||||
namespace plog
|
||||
{
|
||||
template<bool useUtcTime>
|
||||
class CsvFormatterImpl
|
||||
{
|
||||
public:
|
||||
static util::nstring header()
|
||||
{
|
||||
return PLOG_NSTR("Date;Time;Severity;TID;This;Function;Message\n");
|
||||
}
|
||||
|
||||
static util::nstring format(const Record& record)
|
||||
{
|
||||
tm t;
|
||||
useUtcTime ? util::gmtime_s(&t, &record.getTime().time) : util::localtime_s(&t, &record.getTime().time);
|
||||
|
||||
util::nostringstream ss;
|
||||
ss << t.tm_year + 1900 << PLOG_NSTR("/") << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_mon + 1 << PLOG_NSTR("/") << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_mday << PLOG_NSTR(";");
|
||||
ss << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_hour << PLOG_NSTR(":") << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_min << PLOG_NSTR(":") << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_sec << PLOG_NSTR(".") << std::setfill(PLOG_NSTR('0')) << std::setw(3) << static_cast<int> (record.getTime().millitm) << PLOG_NSTR(";");
|
||||
ss << severityToString(record.getSeverity()) << PLOG_NSTR(";");
|
||||
ss << record.getTid() << PLOG_NSTR(";");
|
||||
ss << record.getObject() << PLOG_NSTR(";");
|
||||
ss << record.getFunc() << PLOG_NSTR("@") << record.getLine() << PLOG_NSTR(";");
|
||||
|
||||
util::nstring message = record.getMessage();
|
||||
|
||||
if (message.size() > kMaxMessageSize)
|
||||
{
|
||||
message.resize(kMaxMessageSize);
|
||||
message.append(PLOG_NSTR("..."));
|
||||
}
|
||||
|
||||
util::nistringstream split(message);
|
||||
util::nstring token;
|
||||
|
||||
while (!split.eof())
|
||||
{
|
||||
std::getline(split, token, PLOG_NSTR('"'));
|
||||
ss << PLOG_NSTR("\"") << token << PLOG_NSTR("\"");
|
||||
}
|
||||
|
||||
ss << PLOG_NSTR("\n");
|
||||
|
||||
return ss.str();
|
||||
}
|
||||
|
||||
static const size_t kMaxMessageSize = 32000;
|
||||
};
|
||||
|
||||
class CsvFormatter : public CsvFormatterImpl<false> {};
|
||||
class CsvFormatterUtcTime : public CsvFormatterImpl<true> {};
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
#include <plog/Record.h>
|
||||
#include <plog/Util.h>
|
||||
|
||||
namespace plog
|
||||
{
|
||||
class FuncMessageFormatter
|
||||
{
|
||||
public:
|
||||
static util::nstring header()
|
||||
{
|
||||
return util::nstring();
|
||||
}
|
||||
|
||||
static util::nstring format(const Record& record)
|
||||
{
|
||||
util::nostringstream ss;
|
||||
ss << record.getFunc() << PLOG_NSTR("@") << record.getLine() << PLOG_NSTR(": ") << record.getMessage() << PLOG_NSTR("\n");
|
||||
|
||||
return ss.str();
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
#pragma once
|
||||
#include <plog/Record.h>
|
||||
#include <plog/Util.h>
|
||||
|
||||
namespace plog
|
||||
{
|
||||
class MessageOnlyFormatter
|
||||
{
|
||||
public:
|
||||
static util::nstring header()
|
||||
{
|
||||
return util::nstring();
|
||||
}
|
||||
|
||||
static util::nstring format(const Record& record)
|
||||
{
|
||||
util::nostringstream ss;
|
||||
ss << record.getMessage() << PLOG_NSTR("\n");
|
||||
|
||||
return ss.str();
|
||||
}
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,36 @@
|
||||
#pragma once
|
||||
#include <plog/Record.h>
|
||||
#include <plog/Util.h>
|
||||
#include <iomanip>
|
||||
|
||||
namespace plog
|
||||
{
|
||||
template<bool useUtcTime>
|
||||
class TxtFormatterImpl
|
||||
{
|
||||
public:
|
||||
static util::nstring header()
|
||||
{
|
||||
return util::nstring();
|
||||
}
|
||||
|
||||
static util::nstring format(const Record& record)
|
||||
{
|
||||
tm t;
|
||||
useUtcTime ? util::gmtime_s(&t, &record.getTime().time) : util::localtime_s(&t, &record.getTime().time);
|
||||
|
||||
util::nostringstream ss;
|
||||
ss << t.tm_year + 1900 << "-" << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_mon + 1 << PLOG_NSTR("-") << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_mday << PLOG_NSTR(" ");
|
||||
ss << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_hour << PLOG_NSTR(":") << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_min << PLOG_NSTR(":") << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_sec << PLOG_NSTR(".") << std::setfill(PLOG_NSTR('0')) << std::setw(3) << static_cast<int> (record.getTime().millitm) << PLOG_NSTR(" ");
|
||||
ss << std::setfill(PLOG_NSTR(' ')) << std::setw(5) << std::left << severityToString(record.getSeverity()) << PLOG_NSTR(" ");
|
||||
ss << PLOG_NSTR("[") << record.getTid() << PLOG_NSTR("] ");
|
||||
ss << PLOG_NSTR("[") << record.getFunc() << PLOG_NSTR("@") << record.getLine() << PLOG_NSTR("] ");
|
||||
ss << record.getMessage() << PLOG_NSTR("\n");
|
||||
|
||||
return ss.str();
|
||||
}
|
||||
};
|
||||
|
||||
class TxtFormatter : public TxtFormatterImpl<false> {};
|
||||
class TxtFormatterUtcTime : public TxtFormatterImpl<true> {};
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
#pragma once
|
||||
#include <plog/Util.h>
|
||||
#include <cctype>
|
||||
|
||||
namespace plog
|
||||
{
|
||||
class AscDump
|
||||
{
|
||||
public:
|
||||
AscDump(const void* ptr, size_t size)
|
||||
: m_ptr(static_cast<const char*>(ptr))
|
||||
, m_size(size)
|
||||
{
|
||||
}
|
||||
|
||||
friend util::nostringstream& operator<<(util::nostringstream& stream, const AscDump& ascDump);
|
||||
|
||||
private:
|
||||
const char* m_ptr;
|
||||
size_t m_size;
|
||||
};
|
||||
|
||||
inline util::nostringstream& operator<<(util::nostringstream& stream, const AscDump& ascDump)
|
||||
{
|
||||
for (size_t i = 0; i < ascDump.m_size; ++i)
|
||||
{
|
||||
stream << (std::isprint(ascDump.m_ptr[i]) ? ascDump.m_ptr[i] : '.');
|
||||
}
|
||||
|
||||
return stream;
|
||||
}
|
||||
|
||||
inline AscDump ascdump(const void* ptr, size_t size) { return AscDump(ptr, size); }
|
||||
|
||||
template<class Container>
|
||||
inline AscDump ascdump(const Container& container) { return AscDump(container.data(), container.size() * sizeof(*container.data())); }
|
||||
|
||||
template<class T, size_t N>
|
||||
inline AscDump ascdump(const T (&arr)[N]) { return AscDump(arr, N * sizeof(*arr)); }
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
#pragma once
|
||||
#include <plog/Util.h>
|
||||
#include <iomanip>
|
||||
|
||||
namespace plog
|
||||
{
|
||||
class HexDump
|
||||
{
|
||||
public:
|
||||
HexDump(const void* ptr, size_t size)
|
||||
: m_ptr(static_cast<const unsigned char*>(ptr))
|
||||
, m_size(size)
|
||||
, m_group(8)
|
||||
, m_digitSeparator(" ")
|
||||
, m_groupSeparator(" ")
|
||||
{
|
||||
}
|
||||
|
||||
HexDump& group(size_t group)
|
||||
{
|
||||
m_group = group;
|
||||
return *this;
|
||||
}
|
||||
|
||||
HexDump& separator(const char* digitSeparator)
|
||||
{
|
||||
m_digitSeparator = digitSeparator;
|
||||
return *this;
|
||||
}
|
||||
|
||||
HexDump& separator(const char* digitSeparator, const char* groupSeparator)
|
||||
{
|
||||
m_digitSeparator = digitSeparator;
|
||||
m_groupSeparator = groupSeparator;
|
||||
return *this;
|
||||
}
|
||||
|
||||
friend util::nostringstream& operator<<(util::nostringstream& stream, const HexDump&);
|
||||
|
||||
private:
|
||||
const unsigned char* m_ptr;
|
||||
size_t m_size;
|
||||
size_t m_group;
|
||||
const char* m_digitSeparator;
|
||||
const char* m_groupSeparator;
|
||||
};
|
||||
|
||||
inline util::nostringstream& operator<<(util::nostringstream& stream, const HexDump& hexDump)
|
||||
{
|
||||
stream << std::hex << std::setfill(PLOG_NSTR('0'));
|
||||
|
||||
for (size_t i = 0; i < hexDump.m_size;)
|
||||
{
|
||||
stream << std::setw(2) << static_cast<int>(hexDump.m_ptr[i]);
|
||||
|
||||
if (++i < hexDump.m_size)
|
||||
{
|
||||
if (hexDump.m_group > 0 && i % hexDump.m_group == 0)
|
||||
{
|
||||
stream << hexDump.m_groupSeparator;
|
||||
}
|
||||
else
|
||||
{
|
||||
stream << hexDump.m_digitSeparator;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return stream;
|
||||
}
|
||||
|
||||
inline HexDump hexdump(const void* ptr, size_t size) { return HexDump(ptr, size); }
|
||||
|
||||
template<class Container>
|
||||
inline HexDump hexdump(const Container& container) { return HexDump(container.data(), container.size() * sizeof(*container.data())); }
|
||||
|
||||
template<class T, size_t N>
|
||||
inline HexDump hexdump(const T (&arr)[N]) { return HexDump(arr, N * sizeof(*arr)); }
|
||||
}
|
||||
@@ -0,0 +1,24 @@
|
||||
#pragma once
|
||||
|
||||
#define PLOG_IMPL_PRINT_VAR_1(a1) #a1 ": " << a1
|
||||
#define PLOG_IMPL_PRINT_VAR_2(a1, a2) PLOG_IMPL_PRINT_VAR_1(a1) PLOG_IMPL_PRINT_VAR_TAIL(a2)
|
||||
#define PLOG_IMPL_PRINT_VAR_3(a1, a2, a3) PLOG_IMPL_PRINT_VAR_2(a1, a2) PLOG_IMPL_PRINT_VAR_TAIL(a3)
|
||||
#define PLOG_IMPL_PRINT_VAR_4(a1, a2, a3, a4) PLOG_IMPL_PRINT_VAR_3(a1, a2, a3) PLOG_IMPL_PRINT_VAR_TAIL(a4)
|
||||
#define PLOG_IMPL_PRINT_VAR_5(a1, a2, a3, a4, a5) PLOG_IMPL_PRINT_VAR_4(a1, a2, a3, a4) PLOG_IMPL_PRINT_VAR_TAIL(a5)
|
||||
#define PLOG_IMPL_PRINT_VAR_6(a1, a2, a3, a4, a5, a6) PLOG_IMPL_PRINT_VAR_5(a1, a2, a3, a4, a5) PLOG_IMPL_PRINT_VAR_TAIL(a6)
|
||||
#define PLOG_IMPL_PRINT_VAR_7(a1, a2, a3, a4, a5, a6, a7) PLOG_IMPL_PRINT_VAR_6(a1, a2, a3, a4, a5, a6) PLOG_IMPL_PRINT_VAR_TAIL(a7)
|
||||
#define PLOG_IMPL_PRINT_VAR_8(a1, a2, a3, a4, a5, a6, a7, a8) PLOG_IMPL_PRINT_VAR_7(a1, a2, a3, a4, a5, a6, a7) PLOG_IMPL_PRINT_VAR_TAIL(a8)
|
||||
#define PLOG_IMPL_PRINT_VAR_9(a1, a2, a3, a4, a5, a6, a7, a8, a9) PLOG_IMPL_PRINT_VAR_8(a1, a2, a3, a4, a5, a6, a7, a8) PLOG_IMPL_PRINT_VAR_TAIL(a9)
|
||||
#define PLOG_IMPL_PRINT_VAR_TAIL(a) << ", " PLOG_IMPL_PRINT_VAR_1(a)
|
||||
|
||||
#define PLOG_IMPL_PRINT_VAR_EXPAND(x) x
|
||||
|
||||
#ifdef __GNUC__
|
||||
#pragma GCC system_header // disable warning: variadic macros are a C99 feature
|
||||
#endif
|
||||
|
||||
#define PLOG_IMPL_PRINT_VAR_GET_MACRO(x1, x2, x3, x4, x5, x6, x7, x8, x9, NAME, ...) NAME
|
||||
|
||||
#define PLOG_PRINT_VAR(...) PLOG_IMPL_PRINT_VAR_EXPAND(PLOG_IMPL_PRINT_VAR_GET_MACRO(__VA_ARGS__,\
|
||||
PLOG_IMPL_PRINT_VAR_9, PLOG_IMPL_PRINT_VAR_8, PLOG_IMPL_PRINT_VAR_7, PLOG_IMPL_PRINT_VAR_6, PLOG_IMPL_PRINT_VAR_5,\
|
||||
PLOG_IMPL_PRINT_VAR_4, PLOG_IMPL_PRINT_VAR_3, PLOG_IMPL_PRINT_VAR_2, PLOG_IMPL_PRINT_VAR_1, UNUSED)(__VA_ARGS__))
|
||||
@@ -0,0 +1,17 @@
|
||||
#pragma once
|
||||
#include <plog/Logger.h>
|
||||
|
||||
namespace plog
|
||||
{
|
||||
template<int instanceId>
|
||||
PLOG_LINKAGE_HIDDEN inline Logger<instanceId>& init(Severity maxSeverity = none, IAppender* appender = NULL)
|
||||
{
|
||||
static Logger<instanceId> logger(maxSeverity);
|
||||
return appender ? logger.addAppender(appender) : logger;
|
||||
}
|
||||
|
||||
inline Logger<PLOG_DEFAULT_INSTANCE_ID>& init(Severity maxSeverity = none, IAppender* appender = NULL)
|
||||
{
|
||||
return init<PLOG_DEFAULT_INSTANCE_ID>(maxSeverity, appender);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
#pragma once
|
||||
#include <plog/Appenders/ColorConsoleAppender.h>
|
||||
#include <plog/Init.h>
|
||||
|
||||
namespace plog
|
||||
{
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// ColorConsoleAppender with any Formatter
|
||||
|
||||
template<class Formatter, int instanceId>
|
||||
PLOG_LINKAGE_HIDDEN inline Logger<instanceId>& init(Severity maxSeverity, OutputStream outputStream)
|
||||
{
|
||||
static ColorConsoleAppender<Formatter> appender(outputStream);
|
||||
return init<instanceId>(maxSeverity, &appender);
|
||||
}
|
||||
|
||||
template<class Formatter>
|
||||
inline Logger<PLOG_DEFAULT_INSTANCE_ID>& init(Severity maxSeverity, OutputStream outputStream)
|
||||
{
|
||||
return init<Formatter, PLOG_DEFAULT_INSTANCE_ID>(maxSeverity, outputStream);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
#pragma once
|
||||
#include <plog/Appenders/RollingFileAppender.h>
|
||||
#include <plog/Formatters/TxtFormatter.h>
|
||||
#include <plog/Formatters/CsvFormatter.h>
|
||||
#include <plog/Init.h>
|
||||
#include <cstring>
|
||||
|
||||
namespace plog
|
||||
{
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// RollingFileAppender with any Formatter
|
||||
|
||||
template<class Formatter, int instanceId>
|
||||
PLOG_LINKAGE_HIDDEN inline Logger<instanceId>& init(Severity maxSeverity, const util::nchar* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
||||
{
|
||||
static RollingFileAppender<Formatter> rollingFileAppender(fileName, maxFileSize, maxFiles);
|
||||
return init<instanceId>(maxSeverity, &rollingFileAppender);
|
||||
}
|
||||
|
||||
template<class Formatter>
|
||||
inline Logger<PLOG_DEFAULT_INSTANCE_ID>& init(Severity maxSeverity, const util::nchar* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
||||
{
|
||||
return init<Formatter, PLOG_DEFAULT_INSTANCE_ID>(maxSeverity, fileName, maxFileSize, maxFiles);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// RollingFileAppender with TXT/CSV chosen by file extension
|
||||
|
||||
namespace
|
||||
{
|
||||
inline bool isCsv(const util::nchar* fileName)
|
||||
{
|
||||
const util::nchar* dot = util::findExtensionDot(fileName);
|
||||
#if PLOG_CHAR_IS_UTF8
|
||||
return dot && 0 == std::strcmp(dot, ".csv");
|
||||
#else
|
||||
return dot && 0 == std::wcscmp(dot, L".csv");
|
||||
#endif
|
||||
}
|
||||
}
|
||||
|
||||
template<int instanceId>
|
||||
inline Logger<instanceId>& init(Severity maxSeverity, const util::nchar* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
||||
{
|
||||
return isCsv(fileName) ? init<CsvFormatter, instanceId>(maxSeverity, fileName, maxFileSize, maxFiles) : init<TxtFormatter, instanceId>(maxSeverity, fileName, maxFileSize, maxFiles);
|
||||
}
|
||||
|
||||
inline Logger<PLOG_DEFAULT_INSTANCE_ID>& init(Severity maxSeverity, const util::nchar* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
||||
{
|
||||
return init<PLOG_DEFAULT_INSTANCE_ID>(maxSeverity, fileName, maxFileSize, maxFiles);
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// CHAR variants for Windows
|
||||
|
||||
#if defined(_WIN32) && !PLOG_CHAR_IS_UTF8
|
||||
template<class Formatter, int instanceId>
|
||||
inline Logger<instanceId>& init(Severity maxSeverity, const char* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
||||
{
|
||||
return init<Formatter, instanceId>(maxSeverity, util::toWide(fileName).c_str(), maxFileSize, maxFiles);
|
||||
}
|
||||
|
||||
template<class Formatter>
|
||||
inline Logger<PLOG_DEFAULT_INSTANCE_ID>& init(Severity maxSeverity, const char* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
||||
{
|
||||
return init<Formatter, PLOG_DEFAULT_INSTANCE_ID>(maxSeverity, fileName, maxFileSize, maxFiles);
|
||||
}
|
||||
|
||||
template<int instanceId>
|
||||
inline Logger<instanceId>& init(Severity maxSeverity, const char* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
||||
{
|
||||
return init<instanceId>(maxSeverity, util::toWide(fileName).c_str(), maxFileSize, maxFiles);
|
||||
}
|
||||
|
||||
inline Logger<PLOG_DEFAULT_INSTANCE_ID>& init(Severity maxSeverity, const char* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
||||
{
|
||||
return init<PLOG_DEFAULT_INSTANCE_ID>(maxSeverity, fileName, maxFileSize, maxFiles);
|
||||
}
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,209 @@
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// Plog - portable and simple log for C++
|
||||
// Documentation and sources: https://github.com/SergiusTheBest/plog
|
||||
// License: MIT, https://choosealicense.com/licenses/mit
|
||||
|
||||
#pragma once
|
||||
#include <plog/Logger.h>
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// Helper macros that get context info
|
||||
|
||||
#if defined(PLOG_ENABLE_GET_THIS) && defined(_MSC_VER) && _MSC_VER >= 1600 && !defined(__INTELLISENSE__) && !defined(__INTEL_COMPILER) && !defined(__llvm__) && !defined(__RESHARPER__) // >= Visual Studio 2010, skip IntelliSense, Intel Compiler, Clang Code Model and ReSharper
|
||||
# define PLOG_GET_THIS() __if_exists(this) { this } __if_not_exists(this) { 0 }
|
||||
#else
|
||||
# define PLOG_GET_THIS() reinterpret_cast<void*>(0)
|
||||
#endif
|
||||
|
||||
#ifdef _MSC_VER
|
||||
# define PLOG_GET_FUNC() __FUNCTION__
|
||||
#elif defined(__BORLANDC__)
|
||||
# define PLOG_GET_FUNC() __FUNC__
|
||||
#else
|
||||
# define PLOG_GET_FUNC() __PRETTY_FUNCTION__
|
||||
#endif
|
||||
|
||||
#ifdef PLOG_CAPTURE_FILE
|
||||
# define PLOG_GET_FILE() __FILE__
|
||||
#else
|
||||
# define PLOG_GET_FILE() ""
|
||||
#endif
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// Log severity level checker
|
||||
|
||||
#ifdef PLOG_DISABLE_LOGGING
|
||||
# ifdef _MSC_VER
|
||||
# define IF_PLOG_(instanceId, severity) __pragma(warning(push)) __pragma(warning(disable:4127)) if (true) {;} else __pragma(warning(pop)) // conditional expression is constant
|
||||
# else
|
||||
# define IF_PLOG_(instanceId, severity) if (true) {;} else
|
||||
# endif
|
||||
#else
|
||||
# define IF_PLOG_(instanceId, severity) if (!plog::get<instanceId>() || !plog::get<instanceId>()->checkSeverity(severity)) {;} else
|
||||
#endif
|
||||
|
||||
#define IF_PLOG(severity) IF_PLOG_(PLOG_DEFAULT_INSTANCE_ID, severity)
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// Main logging macros
|
||||
|
||||
#ifdef PLOG_MESSAGE_PREFIX
|
||||
# define PLOG_PRINT_MESSAGE_PREFIX() << PLOG_MESSAGE_PREFIX
|
||||
#else
|
||||
# define PLOG_PRINT_MESSAGE_PREFIX()
|
||||
#endif
|
||||
|
||||
#define PLOG_(instanceId, severity) IF_PLOG_(instanceId, severity) (*plog::get<instanceId>()) += \
|
||||
plog::Record(severity, PLOG_GET_FUNC(), __LINE__, PLOG_GET_FILE(), PLOG_GET_THIS(), instanceId).ref() PLOG_PRINT_MESSAGE_PREFIX()
|
||||
#define PLOG(severity) PLOG_(PLOG_DEFAULT_INSTANCE_ID, severity)
|
||||
|
||||
#define PLOG_VERBOSE PLOG(plog::verbose)
|
||||
#define PLOG_DEBUG PLOG(plog::debug)
|
||||
#define PLOG_INFO PLOG(plog::info)
|
||||
#define PLOG_WARNING PLOG(plog::warning)
|
||||
#define PLOG_ERROR PLOG(plog::error)
|
||||
#define PLOG_FATAL PLOG(plog::fatal)
|
||||
#define PLOG_NONE PLOG(plog::none)
|
||||
|
||||
#define PLOG_VERBOSE_(instanceId) PLOG_(instanceId, plog::verbose)
|
||||
#define PLOG_DEBUG_(instanceId) PLOG_(instanceId, plog::debug)
|
||||
#define PLOG_INFO_(instanceId) PLOG_(instanceId, plog::info)
|
||||
#define PLOG_WARNING_(instanceId) PLOG_(instanceId, plog::warning)
|
||||
#define PLOG_ERROR_(instanceId) PLOG_(instanceId, plog::error)
|
||||
#define PLOG_FATAL_(instanceId) PLOG_(instanceId, plog::fatal)
|
||||
#define PLOG_NONE_(instanceId) PLOG_(instanceId, plog::none)
|
||||
|
||||
#define PLOGV PLOG_VERBOSE
|
||||
#define PLOGD PLOG_DEBUG
|
||||
#define PLOGI PLOG_INFO
|
||||
#define PLOGW PLOG_WARNING
|
||||
#define PLOGE PLOG_ERROR
|
||||
#define PLOGF PLOG_FATAL
|
||||
#define PLOGN PLOG_NONE
|
||||
|
||||
#define PLOGV_(instanceId) PLOG_VERBOSE_(instanceId)
|
||||
#define PLOGD_(instanceId) PLOG_DEBUG_(instanceId)
|
||||
#define PLOGI_(instanceId) PLOG_INFO_(instanceId)
|
||||
#define PLOGW_(instanceId) PLOG_WARNING_(instanceId)
|
||||
#define PLOGE_(instanceId) PLOG_ERROR_(instanceId)
|
||||
#define PLOGF_(instanceId) PLOG_FATAL_(instanceId)
|
||||
#define PLOGN_(instanceId) PLOG_NONE_(instanceId)
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// Conditional logging macros
|
||||
|
||||
#define PLOG_IF_(instanceId, severity, condition) if (!(condition)) {;} else PLOG_(instanceId, severity)
|
||||
#define PLOG_IF(severity, condition) PLOG_IF_(PLOG_DEFAULT_INSTANCE_ID, severity, condition)
|
||||
|
||||
#define PLOG_VERBOSE_IF(condition) PLOG_IF(plog::verbose, condition)
|
||||
#define PLOG_DEBUG_IF(condition) PLOG_IF(plog::debug, condition)
|
||||
#define PLOG_INFO_IF(condition) PLOG_IF(plog::info, condition)
|
||||
#define PLOG_WARNING_IF(condition) PLOG_IF(plog::warning, condition)
|
||||
#define PLOG_ERROR_IF(condition) PLOG_IF(plog::error, condition)
|
||||
#define PLOG_FATAL_IF(condition) PLOG_IF(plog::fatal, condition)
|
||||
#define PLOG_NONE_IF(condition) PLOG_IF(plog::none, condition)
|
||||
|
||||
#define PLOG_VERBOSE_IF_(instanceId, condition) PLOG_IF_(instanceId, plog::verbose, condition)
|
||||
#define PLOG_DEBUG_IF_(instanceId, condition) PLOG_IF_(instanceId, plog::debug, condition)
|
||||
#define PLOG_INFO_IF_(instanceId, condition) PLOG_IF_(instanceId, plog::info, condition)
|
||||
#define PLOG_WARNING_IF_(instanceId, condition) PLOG_IF_(instanceId, plog::warning, condition)
|
||||
#define PLOG_ERROR_IF_(instanceId, condition) PLOG_IF_(instanceId, plog::error, condition)
|
||||
#define PLOG_FATAL_IF_(instanceId, condition) PLOG_IF_(instanceId, plog::fatal, condition)
|
||||
#define PLOG_NONE_IF_(instanceId, condition) PLOG_IF_(instanceId, plog::none, condition)
|
||||
|
||||
#define PLOGV_IF(condition) PLOG_VERBOSE_IF(condition)
|
||||
#define PLOGD_IF(condition) PLOG_DEBUG_IF(condition)
|
||||
#define PLOGI_IF(condition) PLOG_INFO_IF(condition)
|
||||
#define PLOGW_IF(condition) PLOG_WARNING_IF(condition)
|
||||
#define PLOGE_IF(condition) PLOG_ERROR_IF(condition)
|
||||
#define PLOGF_IF(condition) PLOG_FATAL_IF(condition)
|
||||
#define PLOGN_IF(condition) PLOG_NONE_IF(condition)
|
||||
|
||||
#define PLOGV_IF_(instanceId, condition) PLOG_VERBOSE_IF_(instanceId, condition)
|
||||
#define PLOGD_IF_(instanceId, condition) PLOG_DEBUG_IF_(instanceId, condition)
|
||||
#define PLOGI_IF_(instanceId, condition) PLOG_INFO_IF_(instanceId, condition)
|
||||
#define PLOGW_IF_(instanceId, condition) PLOG_WARNING_IF_(instanceId, condition)
|
||||
#define PLOGE_IF_(instanceId, condition) PLOG_ERROR_IF_(instanceId, condition)
|
||||
#define PLOGF_IF_(instanceId, condition) PLOG_FATAL_IF_(instanceId, condition)
|
||||
#define PLOGN_IF_(instanceId, condition) PLOG_NONE_IF_(instanceId, condition)
|
||||
|
||||
// Old macro names for downward compatibility. To bypass including these macro names, add
|
||||
// #define PLOG_OMIT_LOG_DEFINES before #include <plog/Log.h>
|
||||
#ifndef PLOG_OMIT_LOG_DEFINES
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// Main logging macros - can be changed later to point at macros for a different logging package
|
||||
|
||||
#define LOG_(instanceId, severity) PLOG_(instanceId, severity)
|
||||
#define LOG(severity) PLOG(severity)
|
||||
|
||||
#define LOG_VERBOSE PLOG_VERBOSE
|
||||
#define LOG_DEBUG PLOG_DEBUG
|
||||
#define LOG_INFO PLOG_INFO
|
||||
#define LOG_WARNING PLOG_WARNING
|
||||
#define LOG_ERROR PLOG_ERROR
|
||||
#define LOG_FATAL PLOG_FATAL
|
||||
#define LOG_NONE PLOG_NONE
|
||||
|
||||
#define LOG_VERBOSE_(instanceId) PLOG_VERBOSE_(instanceId)
|
||||
#define LOG_DEBUG_(instanceId) PLOG_DEBUG_(instanceId)
|
||||
#define LOG_INFO_(instanceId) PLOG_INFO_(instanceId)
|
||||
#define LOG_WARNING_(instanceId) PLOG_WARNING_(instanceId)
|
||||
#define LOG_ERROR_(instanceId) PLOG_ERROR_(instanceId)
|
||||
#define LOG_FATAL_(instanceId) PLOG_FATAL_(instanceId)
|
||||
#define LOG_NONE_(instanceId) PLOG_NONE_(instanceId)
|
||||
|
||||
#define LOGV PLOGV
|
||||
#define LOGD PLOGD
|
||||
#define LOGI PLOGI
|
||||
#define LOGW PLOGW
|
||||
#define LOGE PLOGE
|
||||
#define LOGF PLOGF
|
||||
#define LOGN PLOGN
|
||||
|
||||
#define LOGV_(instanceId) PLOGV_(instanceId)
|
||||
#define LOGD_(instanceId) PLOGD_(instanceId)
|
||||
#define LOGI_(instanceId) PLOGI_(instanceId)
|
||||
#define LOGW_(instanceId) PLOGW_(instanceId)
|
||||
#define LOGE_(instanceId) PLOGE_(instanceId)
|
||||
#define LOGF_(instanceId) PLOGF_(instanceId)
|
||||
#define LOGN_(instanceId) PLOGN_(instanceId)
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// Conditional logging macros
|
||||
|
||||
#define LOG_IF_(instanceId, severity, condition) PLOG_IF_(instanceId, severity, condition)
|
||||
#define LOG_IF(severity, condition) PLOG_IF(severity, condition)
|
||||
|
||||
#define LOG_VERBOSE_IF(condition) PLOG_VERBOSE_IF(condition)
|
||||
#define LOG_DEBUG_IF(condition) PLOG_DEBUG_IF(condition)
|
||||
#define LOG_INFO_IF(condition) PLOG_INFO_IF(condition)
|
||||
#define LOG_WARNING_IF(condition) PLOG_WARNING_IF(condition)
|
||||
#define LOG_ERROR_IF(condition) PLOG_ERROR_IF(condition)
|
||||
#define LOG_FATAL_IF(condition) PLOG_FATAL_IF(condition)
|
||||
#define LOG_NONE_IF(condition) PLOG_NONE_IF(condition)
|
||||
|
||||
#define LOG_VERBOSE_IF_(instanceId, condition) PLOG_VERBOSE_IF_(instanceId, condition)
|
||||
#define LOG_DEBUG_IF_(instanceId, condition) PLOG_DEBUG_IF_(instanceId, condition)
|
||||
#define LOG_INFO_IF_(instanceId, condition) PLOG_INFO_IF_(instanceId, condition)
|
||||
#define LOG_WARNING_IF_(instanceId, condition) PLOG_WARNING_IF_(instanceId, condition)
|
||||
#define LOG_ERROR_IF_(instanceId, condition) PLOG_ERROR_IF_(instanceId, condition)
|
||||
#define LOG_FATAL_IF_(instanceId, condition) PLOG_FATAL_IF_(instanceId, condition)
|
||||
#define LOG_NONE_IF_(instanceId, condition) PLOG_NONE_IF_(instanceId, condition)
|
||||
|
||||
#define LOGV_IF(condition) PLOGV_IF(condition)
|
||||
#define LOGD_IF(condition) PLOGD_IF(condition)
|
||||
#define LOGI_IF(condition) PLOGI_IF(condition)
|
||||
#define LOGW_IF(condition) PLOGW_IF(condition)
|
||||
#define LOGE_IF(condition) PLOGE_IF(condition)
|
||||
#define LOGF_IF(condition) PLOGF_IF(condition)
|
||||
#define LOGN_IF(condition) PLOGN_IF(condition)
|
||||
|
||||
#define LOGV_IF_(instanceId, condition) PLOGV_IF_(instanceId, condition)
|
||||
#define LOGD_IF_(instanceId, condition) PLOGD_IF_(instanceId, condition)
|
||||
#define LOGI_IF_(instanceId, condition) PLOGI_IF_(instanceId, condition)
|
||||
#define LOGW_IF_(instanceId, condition) PLOGW_IF_(instanceId, condition)
|
||||
#define LOGE_IF_(instanceId, condition) PLOGE_IF_(instanceId, condition)
|
||||
#define LOGF_IF_(instanceId, condition) PLOGF_IF_(instanceId, condition)
|
||||
#define LOGN_IF_(instanceId, condition) PLOGN_IF_(instanceId, condition)
|
||||
#endif
|
||||
@@ -0,0 +1,84 @@
|
||||
#pragma once
|
||||
#include <plog/Appenders/IAppender.h>
|
||||
#include <plog/Util.h>
|
||||
#include <vector>
|
||||
|
||||
#ifdef PLOG_DEFAULT_INSTANCE // for backward compatibility
|
||||
# define PLOG_DEFAULT_INSTANCE_ID PLOG_DEFAULT_INSTANCE
|
||||
#endif
|
||||
|
||||
#ifndef PLOG_DEFAULT_INSTANCE_ID
|
||||
# define PLOG_DEFAULT_INSTANCE_ID 0
|
||||
#endif
|
||||
|
||||
namespace plog
|
||||
{
|
||||
template<int instanceId>
|
||||
class PLOG_LINKAGE Logger : public util::Singleton<Logger<instanceId> >, public IAppender
|
||||
{
|
||||
public:
|
||||
Logger(Severity maxSeverity = none) : m_maxSeverity(maxSeverity)
|
||||
{
|
||||
}
|
||||
|
||||
Logger& addAppender(IAppender* appender)
|
||||
{
|
||||
assert(appender != this);
|
||||
m_appenders.push_back(appender);
|
||||
return *this;
|
||||
}
|
||||
|
||||
Severity getMaxSeverity() const
|
||||
{
|
||||
return m_maxSeverity;
|
||||
}
|
||||
|
||||
void setMaxSeverity(Severity severity)
|
||||
{
|
||||
m_maxSeverity = severity;
|
||||
}
|
||||
|
||||
bool checkSeverity(Severity severity) const
|
||||
{
|
||||
return severity <= m_maxSeverity;
|
||||
}
|
||||
|
||||
virtual void write(const Record& record) PLOG_OVERRIDE
|
||||
{
|
||||
if (checkSeverity(record.getSeverity()))
|
||||
{
|
||||
*this += record;
|
||||
}
|
||||
}
|
||||
|
||||
void operator+=(const Record& record)
|
||||
{
|
||||
for (std::vector<IAppender*>::iterator it = m_appenders.begin(); it != m_appenders.end(); ++it)
|
||||
{
|
||||
(*it)->write(record);
|
||||
}
|
||||
}
|
||||
|
||||
private:
|
||||
Severity m_maxSeverity;
|
||||
#ifdef _MSC_VER
|
||||
# pragma warning(push)
|
||||
# pragma warning(disable:4251) // needs to have dll-interface to be used by clients of class
|
||||
#endif
|
||||
std::vector<IAppender*> m_appenders;
|
||||
#ifdef _MSC_VER
|
||||
# pragma warning(pop)
|
||||
#endif
|
||||
};
|
||||
|
||||
template<int instanceId>
|
||||
inline Logger<instanceId>* get()
|
||||
{
|
||||
return Logger<instanceId>::getInstance();
|
||||
}
|
||||
|
||||
inline Logger<PLOG_DEFAULT_INSTANCE_ID>* get()
|
||||
{
|
||||
return Logger<PLOG_DEFAULT_INSTANCE_ID>::getInstance();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,465 @@
|
||||
#pragma once
|
||||
#include <cstdarg>
|
||||
#include <plog/Severity.h>
|
||||
#include <plog/Util.h>
|
||||
|
||||
#ifdef __cplusplus_cli
|
||||
#include <vcclr.h> // For PtrToStringChars
|
||||
#endif
|
||||
|
||||
namespace plog
|
||||
{
|
||||
namespace detail
|
||||
{
|
||||
#if !defined(_MSC_VER) || _MSC_VER > 1400 // MSVC 2005 doesn't understand `enableIf`, so drop all `meta`
|
||||
namespace meta
|
||||
{
|
||||
template<class T>
|
||||
inline T& declval()
|
||||
{
|
||||
#ifdef __INTEL_COMPILER
|
||||
# pragma warning(suppress: 327) // NULL reference is not allowed
|
||||
#endif
|
||||
return *reinterpret_cast<T*>(0);
|
||||
}
|
||||
|
||||
template<bool B, class T = void>
|
||||
struct enableIf {};
|
||||
|
||||
template<class T>
|
||||
struct enableIf<true, T> { typedef T type; };
|
||||
|
||||
struct No { char a[1]; };
|
||||
struct Yes { char a[2]; };
|
||||
|
||||
template <class From, class To>
|
||||
struct isConvertible
|
||||
{
|
||||
// `+ sizeof(U*)` is required for GCC 4.5-4.7
|
||||
template<class U>
|
||||
static typename enableIf<!!(sizeof(static_cast<To>(meta::declval<U>())) + sizeof(U*)), Yes>::type test(int);
|
||||
|
||||
template<class U>
|
||||
static No test(...);
|
||||
|
||||
enum { value = sizeof(test<From>(0)) == sizeof(Yes) };
|
||||
};
|
||||
|
||||
template <class T>
|
||||
struct isConvertibleToString : isConvertible<T, std::string> {};
|
||||
|
||||
#if PLOG_ENABLE_WCHAR_INPUT
|
||||
template <class T>
|
||||
struct isConvertibleToWString : isConvertible<T, std::wstring> {};
|
||||
#endif
|
||||
|
||||
template <class T>
|
||||
struct isContainer
|
||||
{
|
||||
template<class U>
|
||||
static typename meta::enableIf<!!(sizeof(
|
||||
#if defined(_MSC_VER) && _MSC_VER < 1700 // MSVC 2010 doesn't understand `typename T::const_iterator`
|
||||
meta::declval<U>().begin()) + sizeof(meta::declval<U>().end()
|
||||
#else
|
||||
typename U::const_iterator
|
||||
#endif
|
||||
)), Yes>::type test(int);
|
||||
|
||||
template<class U>
|
||||
static No test(...);
|
||||
|
||||
enum { value = sizeof(test<T>(0)) == sizeof(Yes) };
|
||||
};
|
||||
|
||||
// Detects `std::filesystem::path` and `boost::filesystem::path`. They look like containers
|
||||
// but we don't want to treat them as containers, so we use this detector to filter them out.
|
||||
template <class T>
|
||||
struct isFilesystemPath
|
||||
{
|
||||
template<class U>
|
||||
static typename meta::enableIf<!!(sizeof(meta::declval<U>().preferred_separator)), Yes>::type test(int);
|
||||
|
||||
template<class U>
|
||||
static No test(...);
|
||||
|
||||
enum { value = sizeof(test<T>(0)) == sizeof(Yes) };
|
||||
};
|
||||
}
|
||||
#endif
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// Stream output operators as free functions
|
||||
|
||||
#if PLOG_ENABLE_WCHAR_INPUT
|
||||
inline void operator<<(util::nostringstream& stream, const wchar_t* data)
|
||||
{
|
||||
data = data ? data : L"(null)";
|
||||
|
||||
# ifdef _WIN32
|
||||
# if PLOG_CHAR_IS_UTF8
|
||||
std::operator<<(stream, util::toNarrow(data, codePage::kUTF8));
|
||||
# else
|
||||
std::operator<<(stream, data);
|
||||
# endif
|
||||
# else
|
||||
std::operator<<(stream, util::toNarrow(data));
|
||||
# endif
|
||||
}
|
||||
|
||||
inline void operator<<(util::nostringstream& stream, wchar_t* data)
|
||||
{
|
||||
plog::detail::operator<<(stream, const_cast<const wchar_t*>(data));
|
||||
}
|
||||
|
||||
inline void operator<<(util::nostringstream& stream, const std::wstring& data)
|
||||
{
|
||||
plog::detail::operator<<(stream, data.c_str());
|
||||
}
|
||||
#endif
|
||||
|
||||
inline void operator<<(util::nostringstream& stream, const char* data)
|
||||
{
|
||||
data = data ? data : "(null)";
|
||||
|
||||
#if defined(_WIN32) && defined(__BORLANDC__)
|
||||
# if PLOG_CHAR_IS_UTF8
|
||||
stream << data;
|
||||
# else
|
||||
stream << util::toWide(data);
|
||||
# endif
|
||||
#elif defined(_WIN32)
|
||||
# if PLOG_CHAR_IS_UTF8
|
||||
std::operator<<(stream, data);
|
||||
# else
|
||||
std::operator<<(stream, util::toWide(data));
|
||||
# endif
|
||||
#else
|
||||
std::operator<<(stream, data);
|
||||
#endif
|
||||
}
|
||||
|
||||
inline void operator<<(util::nostringstream& stream, char* data)
|
||||
{
|
||||
plog::detail::operator<<(stream, const_cast<const char*>(data));
|
||||
}
|
||||
|
||||
inline void operator<<(util::nostringstream& stream, const std::string& data)
|
||||
{
|
||||
plog::detail::operator<<(stream, data.c_str());
|
||||
}
|
||||
|
||||
#ifdef __cpp_char8_t
|
||||
inline void operator<<(util::nostringstream& stream, const char8_t* data)
|
||||
{
|
||||
# if PLOG_CHAR_IS_UTF8
|
||||
plog::detail::operator<<(stream, reinterpret_cast<const char*>(data));
|
||||
# else
|
||||
plog::detail::operator<<(stream, util::toWide(reinterpret_cast<const char*>(data), codePage::kUTF8));
|
||||
# endif
|
||||
}
|
||||
#endif //__cpp_char8_t
|
||||
|
||||
// Print `std::pair`
|
||||
template<class T1, class T2>
|
||||
inline void operator<<(util::nostringstream& stream, const std::pair<T1, T2>& data)
|
||||
{
|
||||
stream << data.first;
|
||||
stream << ":";
|
||||
stream << data.second;
|
||||
}
|
||||
|
||||
#if defined(__clang__) || !defined(__GNUC__) || (__GNUC__ * 100 + __GNUC_MINOR__) >= 405 // skip for GCC < 4.5 due to https://gcc.gnu.org/bugzilla/show_bug.cgi?id=38600
|
||||
#if !defined(_MSC_VER) || _MSC_VER > 1400 // MSVC 2005 doesn't understand `enableIf`, so drop all `meta`
|
||||
// Print data that can be casted to `std::string`
|
||||
template<class T>
|
||||
inline typename meta::enableIf<meta::isConvertibleToString<T>::value, void>::type operator<<(util::nostringstream& stream, const T& data)
|
||||
{
|
||||
plog::detail::operator<<(stream, static_cast<std::string>(data));
|
||||
}
|
||||
|
||||
#if PLOG_ENABLE_WCHAR_INPUT
|
||||
// Print data that can be casted to `std::wstring`
|
||||
template<class T>
|
||||
inline typename meta::enableIf<meta::isConvertibleToWString<T>::value, void>::type operator<<(util::nostringstream& stream, const T& data)
|
||||
{
|
||||
plog::detail::operator<<(stream, static_cast<std::wstring>(data));
|
||||
}
|
||||
#endif
|
||||
|
||||
// Print std containers
|
||||
template<class T>
|
||||
inline typename meta::enableIf<meta::isContainer<T>::value &&
|
||||
!meta::isConvertibleToString<T>::value &&
|
||||
#if PLOG_ENABLE_WCHAR_INPUT
|
||||
!meta::isConvertibleToWString<T>::value &&
|
||||
#endif
|
||||
!meta::isFilesystemPath<T>::value, void>::type operator<<(util::nostringstream& stream, const T& data)
|
||||
{
|
||||
stream << "[";
|
||||
|
||||
for (typename T::const_iterator it = data.begin(); it != data.end();)
|
||||
{
|
||||
stream << *it;
|
||||
|
||||
if (++it == data.end())
|
||||
{
|
||||
break;
|
||||
}
|
||||
|
||||
stream << ", ";
|
||||
}
|
||||
|
||||
stream << "]";
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#ifdef __cplusplus_cli
|
||||
// Print managed C++ `System::String^`
|
||||
inline void operator<<(util::nostringstream& stream, System::String^ data)
|
||||
{
|
||||
cli::pin_ptr<const System::Char> ptr = PtrToStringChars(data);
|
||||
plog::detail::operator<<(stream, static_cast<const wchar_t*>(ptr));
|
||||
}
|
||||
#endif
|
||||
|
||||
#if PLOG_ENABLE_WCHAR_INPUT && (!defined(_MSC_VER) || _MSC_VER > 1400) // MSVC 2005 doesn't understand `enableIf`, so drop all `meta`
|
||||
namespace meta
|
||||
{
|
||||
template<bool Value>
|
||||
struct valueType { enum { value = Value }; };
|
||||
|
||||
template<class T, class Stream>
|
||||
inline No operator<<(Stream&, const T&);
|
||||
|
||||
template<class T, class Stream>
|
||||
struct isStreamable : valueType<sizeof(operator<<(meta::declval<Stream>(), meta::declval<const T>())) != sizeof(No)> {};
|
||||
|
||||
template<class Stream>
|
||||
struct isStreamable<std::ios_base& PLOG_CDECL (std::ios_base&), Stream> : valueType<true> {};
|
||||
|
||||
template<class Stream, size_t N>
|
||||
struct isStreamable<wchar_t[N], Stream> : valueType<false> {};
|
||||
|
||||
template<class Stream, size_t N>
|
||||
struct isStreamable<const wchar_t[N], Stream> : valueType<false> {};
|
||||
|
||||
// meta doesn't work well for deleted functions and C++20 has `operator<<(std::ostream&, const wchar_t*) = delete` so explicitly define it
|
||||
template<>
|
||||
struct isStreamable<const wchar_t*, std::ostream> : valueType<false> {};
|
||||
|
||||
# ifdef __cpp_char8_t
|
||||
// meta doesn't work well for deleted functions and C++20 has `operator<<(std::ostream&, const char8_t*) = delete` so explicitly define it
|
||||
template<class Stream, size_t N>
|
||||
struct isStreamable<char8_t[N], Stream> : valueType<false> {};
|
||||
|
||||
template<class Stream>
|
||||
struct isStreamable<const char8_t*, Stream> : valueType<false> {};
|
||||
# endif //__cpp_char8_t
|
||||
}
|
||||
|
||||
# if PLOG_CHAR_IS_UTF8
|
||||
// Print types that can be streamed into `std::owstringstream` but not into `std::ostringstream` when we use UTF-8 on Windows
|
||||
template<class T>
|
||||
inline typename meta::enableIf<meta::isStreamable<T, std::wostream>::value &&
|
||||
!meta::isStreamable<T, std::ostream>::value &&
|
||||
!meta::isConvertibleToWString<T>::value, void>::type operator<<(std::ostringstream& stream, const T& data)
|
||||
{
|
||||
std::wostringstream ss;
|
||||
ss << data;
|
||||
stream << ss.str();
|
||||
}
|
||||
# else
|
||||
// Print types that can be streamed into `std::ostringstream` but not into `std::owstringstream` when we use `wchar_t` on Windows
|
||||
template<class T>
|
||||
inline typename meta::enableIf<meta::isStreamable<T, std::ostream>::value &&
|
||||
!meta::isStreamable<T, std::wostream>::value &&
|
||||
!meta::isConvertibleToString<T>::value, void>::type operator<<(std::wostringstream& stream, const T& data)
|
||||
{
|
||||
std::ostringstream ss;
|
||||
ss << data;
|
||||
stream << ss.str();
|
||||
}
|
||||
# endif
|
||||
#endif
|
||||
}
|
||||
|
||||
class Record
|
||||
{
|
||||
public:
|
||||
Record(Severity severity, const char* func, size_t line, const char* file, const void* object, int instanceId)
|
||||
: m_severity(severity), m_tid(util::gettid()), m_object(object), m_line(line), m_func(func), m_file(file), m_instanceId(instanceId)
|
||||
{
|
||||
util::ftime(&m_time);
|
||||
}
|
||||
|
||||
Record& ref()
|
||||
{
|
||||
return *this;
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// Stream output operators
|
||||
|
||||
Record& operator<<(char data)
|
||||
{
|
||||
char str[] = { data, 0 };
|
||||
return *this << str;
|
||||
}
|
||||
|
||||
#if PLOG_ENABLE_WCHAR_INPUT
|
||||
Record& operator<<(wchar_t data)
|
||||
{
|
||||
wchar_t str[] = { data, 0 };
|
||||
return *this << str;
|
||||
}
|
||||
#endif
|
||||
|
||||
Record& operator<<(util::nostream& (PLOG_CDECL *data)(util::nostream&))
|
||||
{
|
||||
m_message << data;
|
||||
return *this;
|
||||
}
|
||||
|
||||
#ifdef QT_VERSION
|
||||
Record& operator<<(const QString& data)
|
||||
{
|
||||
# if PLOG_CHAR_IS_UTF8
|
||||
return *this << data.toStdString();
|
||||
# else
|
||||
return *this << data.toStdWString();
|
||||
# endif
|
||||
}
|
||||
|
||||
# if QT_VERSION < 0x060000
|
||||
Record& operator<<(const QStringRef& data)
|
||||
{
|
||||
return *this << data.toString();
|
||||
}
|
||||
# endif
|
||||
|
||||
# ifdef QSTRINGVIEW_H
|
||||
Record& operator<<(QStringView data)
|
||||
{
|
||||
return *this << data.toString();
|
||||
}
|
||||
# endif
|
||||
#endif
|
||||
|
||||
template<typename T>
|
||||
Record& operator<<(const T& data)
|
||||
{
|
||||
using namespace plog::detail;
|
||||
|
||||
m_message << data;
|
||||
return *this;
|
||||
}
|
||||
|
||||
#ifndef __cplusplus_cli
|
||||
Record& printf(const char* format, ...)
|
||||
{
|
||||
using namespace util;
|
||||
|
||||
char* str = NULL;
|
||||
va_list ap;
|
||||
|
||||
va_start(ap, format);
|
||||
int len = vasprintf(&str, format, ap);
|
||||
static_cast<void>(len);
|
||||
va_end(ap);
|
||||
|
||||
*this << str;
|
||||
free(str);
|
||||
|
||||
return *this;
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
Record& printf(const wchar_t* format, ...)
|
||||
{
|
||||
using namespace util;
|
||||
|
||||
wchar_t* str = NULL;
|
||||
va_list ap;
|
||||
|
||||
va_start(ap, format);
|
||||
int len = vaswprintf(&str, format, ap);
|
||||
static_cast<void>(len);
|
||||
va_end(ap);
|
||||
|
||||
*this << str;
|
||||
free(str);
|
||||
|
||||
return *this;
|
||||
}
|
||||
#endif
|
||||
#endif //__cplusplus_cli
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// Getters
|
||||
|
||||
virtual const util::Time& getTime() const
|
||||
{
|
||||
return m_time;
|
||||
}
|
||||
|
||||
virtual Severity getSeverity() const
|
||||
{
|
||||
return m_severity;
|
||||
}
|
||||
|
||||
virtual unsigned int getTid() const
|
||||
{
|
||||
return m_tid;
|
||||
}
|
||||
|
||||
virtual const void* getObject() const
|
||||
{
|
||||
return m_object;
|
||||
}
|
||||
|
||||
virtual size_t getLine() const
|
||||
{
|
||||
return m_line;
|
||||
}
|
||||
|
||||
virtual const util::nchar* getMessage() const
|
||||
{
|
||||
m_messageStr = m_message.str();
|
||||
return m_messageStr.c_str();
|
||||
}
|
||||
|
||||
virtual const char* getFunc() const
|
||||
{
|
||||
m_funcStr = util::processFuncName(m_func);
|
||||
return m_funcStr.c_str();
|
||||
}
|
||||
|
||||
virtual const char* getFile() const
|
||||
{
|
||||
return m_file;
|
||||
}
|
||||
|
||||
virtual ~Record() // virtual destructor to satisfy -Wnon-virtual-dtor warning
|
||||
{
|
||||
}
|
||||
|
||||
virtual int getInstanceId() const
|
||||
{
|
||||
return m_instanceId;
|
||||
}
|
||||
|
||||
private:
|
||||
util::Time m_time;
|
||||
const Severity m_severity;
|
||||
const unsigned int m_tid;
|
||||
const void* const m_object;
|
||||
const size_t m_line;
|
||||
util::nostringstream m_message;
|
||||
const char* const m_func;
|
||||
const char* const m_file;
|
||||
const int m_instanceId;
|
||||
mutable std::string m_funcStr;
|
||||
mutable util::nstring m_messageStr;
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,61 @@
|
||||
#pragma once
|
||||
#include <cctype>
|
||||
|
||||
namespace plog
|
||||
{
|
||||
enum Severity
|
||||
{
|
||||
none = 0,
|
||||
fatal = 1,
|
||||
error = 2,
|
||||
warning = 3,
|
||||
info = 4,
|
||||
debug = 5,
|
||||
verbose = 6
|
||||
};
|
||||
|
||||
#ifdef _MSC_VER
|
||||
# pragma warning(suppress: 26812) // Prefer 'enum class' over 'enum'
|
||||
#endif
|
||||
inline const char* severityToString(Severity severity)
|
||||
{
|
||||
switch (severity)
|
||||
{
|
||||
case fatal:
|
||||
return "FATAL";
|
||||
case error:
|
||||
return "ERROR";
|
||||
case warning:
|
||||
return "WARN";
|
||||
case info:
|
||||
return "INFO";
|
||||
case debug:
|
||||
return "DEBUG";
|
||||
case verbose:
|
||||
return "VERB";
|
||||
default:
|
||||
return "NONE";
|
||||
}
|
||||
}
|
||||
|
||||
inline Severity severityFromString(const char* str)
|
||||
{
|
||||
switch (std::toupper(str[0]))
|
||||
{
|
||||
case 'F':
|
||||
return fatal;
|
||||
case 'E':
|
||||
return error;
|
||||
case 'W':
|
||||
return warning;
|
||||
case 'I':
|
||||
return info;
|
||||
case 'D':
|
||||
return debug;
|
||||
case 'V':
|
||||
return verbose;
|
||||
default:
|
||||
return none;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,635 @@
|
||||
#pragma once
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <sstream>
|
||||
#include <fcntl.h>
|
||||
#include <sys/stat.h>
|
||||
|
||||
#ifndef PLOG_ENABLE_WCHAR_INPUT
|
||||
# ifdef _WIN32
|
||||
# define PLOG_ENABLE_WCHAR_INPUT 1
|
||||
# else
|
||||
# define PLOG_ENABLE_WCHAR_INPUT 0
|
||||
# endif
|
||||
#endif
|
||||
|
||||
//////////////////////////////////////////////////////////////////////////
|
||||
// PLOG_CHAR_IS_UTF8 specifies character encoding of `char` type. On *nix
|
||||
// systems it's set to UTF-8 while on Windows in can be ANSI or UTF-8. It
|
||||
// automatically detects `/utf-8` command line option in MSVC. Also it can
|
||||
// be set manually if required.
|
||||
// This option allows to support http://utf8everywhere.org approach.
|
||||
|
||||
#ifndef PLOG_CHAR_IS_UTF8
|
||||
# if defined(_WIN32) && !defined(_UTF8)
|
||||
# define PLOG_CHAR_IS_UTF8 0
|
||||
# else
|
||||
# define PLOG_CHAR_IS_UTF8 1
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#ifdef _WIN32
|
||||
# if defined(PLOG_EXPORT)
|
||||
# define PLOG_LINKAGE __declspec(dllexport)
|
||||
# elif defined(PLOG_IMPORT)
|
||||
# define PLOG_LINKAGE __declspec(dllimport)
|
||||
# endif
|
||||
# if defined(PLOG_GLOBAL)
|
||||
# error "PLOG_GLOBAL isn't supported on Windows"
|
||||
# endif
|
||||
#else
|
||||
# if defined(PLOG_GLOBAL)
|
||||
# define PLOG_LINKAGE __attribute__ ((visibility ("default")))
|
||||
# elif defined(PLOG_LOCAL)
|
||||
# define PLOG_LINKAGE __attribute__ ((visibility ("hidden")))
|
||||
# define PLOG_LINKAGE_HIDDEN PLOG_LINKAGE
|
||||
# endif
|
||||
# if defined(PLOG_EXPORT) || defined(PLOG_IMPORT)
|
||||
# error "PLOG_EXPORT/PLOG_IMPORT is supported only on Windows"
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#ifndef PLOG_LINKAGE
|
||||
# define PLOG_LINKAGE
|
||||
#endif
|
||||
|
||||
#ifndef PLOG_LINKAGE_HIDDEN
|
||||
# define PLOG_LINKAGE_HIDDEN
|
||||
#endif
|
||||
|
||||
#ifdef _WIN32
|
||||
# include <plog/WinApi.h>
|
||||
# include <time.h>
|
||||
# include <sys/timeb.h>
|
||||
# include <io.h>
|
||||
# include <share.h>
|
||||
#else
|
||||
# include <unistd.h>
|
||||
# include <sys/time.h>
|
||||
# if defined(__linux__) || defined(__FreeBSD__)
|
||||
# include <sys/syscall.h>
|
||||
# elif defined(__rtems__)
|
||||
# include <rtems.h>
|
||||
# endif
|
||||
# if defined(_POSIX_THREADS)
|
||||
# include <pthread.h>
|
||||
# endif
|
||||
# if PLOG_ENABLE_WCHAR_INPUT
|
||||
# include <iconv.h>
|
||||
# endif
|
||||
#endif
|
||||
|
||||
#ifdef __FREERTOS__ // There is no standard way to know if the code is compiled for FreeRTOS. We expect __FREERTOS__ macro to be defined in such case.
|
||||
# include <FreeRTOS.h>
|
||||
# include <semphr.h>
|
||||
# include <task.h>
|
||||
#endif
|
||||
|
||||
#if PLOG_CHAR_IS_UTF8
|
||||
# define PLOG_NSTR(x) x
|
||||
#else
|
||||
# define _PLOG_NSTR(x) L##x
|
||||
# define PLOG_NSTR(x) _PLOG_NSTR(x)
|
||||
#endif
|
||||
|
||||
#ifdef _WIN32
|
||||
# define PLOG_CDECL __cdecl
|
||||
#else
|
||||
# define PLOG_CDECL
|
||||
#endif
|
||||
|
||||
#if __cplusplus >= 201103L || defined(_MSC_VER) && _MSC_VER >= 1700
|
||||
# define PLOG_OVERRIDE override
|
||||
#else
|
||||
# define PLOG_OVERRIDE
|
||||
#endif
|
||||
|
||||
namespace plog
|
||||
{
|
||||
namespace util
|
||||
{
|
||||
#if PLOG_CHAR_IS_UTF8
|
||||
typedef std::string nstring;
|
||||
typedef std::ostringstream nostringstream;
|
||||
typedef std::istringstream nistringstream;
|
||||
typedef std::ostream nostream;
|
||||
typedef char nchar;
|
||||
#else
|
||||
typedef std::wstring nstring;
|
||||
typedef std::wostringstream nostringstream;
|
||||
typedef std::wistringstream nistringstream;
|
||||
typedef std::wostream nostream;
|
||||
typedef wchar_t nchar;
|
||||
#endif
|
||||
|
||||
inline void localtime_s(struct tm* t, const time_t* time)
|
||||
{
|
||||
#if defined(_WIN32) && defined(__BORLANDC__)
|
||||
::localtime_s(time, t);
|
||||
#elif defined(_WIN32) && defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
|
||||
*t = *::localtime(time);
|
||||
#elif defined(_WIN32)
|
||||
::localtime_s(t, time);
|
||||
#else
|
||||
::localtime_r(time, t);
|
||||
#endif
|
||||
}
|
||||
|
||||
inline void gmtime_s(struct tm* t, const time_t* time)
|
||||
{
|
||||
#if defined(_WIN32) && defined(__BORLANDC__)
|
||||
::gmtime_s(time, t);
|
||||
#elif defined(_WIN32) && defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
|
||||
*t = *::gmtime(time);
|
||||
#elif defined(_WIN32)
|
||||
::gmtime_s(t, time);
|
||||
#else
|
||||
::gmtime_r(time, t);
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifdef _WIN32
|
||||
typedef timeb Time;
|
||||
|
||||
inline void ftime(Time* t)
|
||||
{
|
||||
::ftime(t);
|
||||
}
|
||||
#else
|
||||
struct Time
|
||||
{
|
||||
time_t time;
|
||||
unsigned short millitm;
|
||||
};
|
||||
|
||||
inline void ftime(Time* t)
|
||||
{
|
||||
timeval tv;
|
||||
::gettimeofday(&tv, NULL);
|
||||
|
||||
t->time = tv.tv_sec;
|
||||
t->millitm = static_cast<unsigned short>(tv.tv_usec / 1000);
|
||||
}
|
||||
#endif
|
||||
|
||||
inline unsigned int gettid()
|
||||
{
|
||||
#if defined(__FREERTOS__) && defined(INCLUDE_xTaskGetCurrentTaskHandle)
|
||||
return static_cast<unsigned int>(reinterpret_cast<uintptr_t>(xTaskGetCurrentTaskHandle()));
|
||||
#elif defined(_WIN32)
|
||||
return GetCurrentThreadId();
|
||||
#elif defined(__linux__)
|
||||
return static_cast<unsigned int>(::syscall(__NR_gettid));
|
||||
#elif defined(__FreeBSD__)
|
||||
long tid;
|
||||
syscall(SYS_thr_self, &tid);
|
||||
return static_cast<unsigned int>(tid);
|
||||
#elif defined(__rtems__)
|
||||
return rtems_task_self();
|
||||
#elif defined(__APPLE__)
|
||||
uint64_t tid64;
|
||||
pthread_threadid_np(NULL, &tid64);
|
||||
return static_cast<unsigned int>(tid64);
|
||||
#else
|
||||
return 0;
|
||||
#endif
|
||||
}
|
||||
|
||||
#ifndef _GNU_SOURCE
|
||||
inline int vasprintf(char** strp, const char* format, va_list ap)
|
||||
{
|
||||
va_list ap_copy;
|
||||
#if defined(_MSC_VER) && _MSC_VER <= 1600
|
||||
ap_copy = ap; // there is no va_copy on Visual Studio 2010
|
||||
#else
|
||||
va_copy(ap_copy, ap);
|
||||
#endif
|
||||
#ifndef __STDC_SECURE_LIB__
|
||||
int charCount = vsnprintf(NULL, 0, format, ap_copy);
|
||||
#else
|
||||
int charCount = _vscprintf(format, ap_copy);
|
||||
#endif
|
||||
va_end(ap_copy);
|
||||
if (charCount < 0)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
size_t bufferCharCount = static_cast<size_t>(charCount) + 1;
|
||||
|
||||
char* str = static_cast<char*>(malloc(bufferCharCount));
|
||||
if (!str)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
#ifndef __STDC_SECURE_LIB__
|
||||
int retval = vsnprintf(str, bufferCharCount, format, ap);
|
||||
#else
|
||||
int retval = vsnprintf_s(str, bufferCharCount, static_cast<size_t>(-1), format, ap);
|
||||
#endif
|
||||
if (retval < 0)
|
||||
{
|
||||
free(str);
|
||||
return -1;
|
||||
}
|
||||
|
||||
*strp = str;
|
||||
return retval;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef _WIN32
|
||||
inline int vaswprintf(wchar_t** strp, const wchar_t* format, va_list ap)
|
||||
{
|
||||
#if defined(__BORLANDC__)
|
||||
int charCount = 0x1000; // there is no _vscwprintf on Borland/Embarcadero
|
||||
#else
|
||||
int charCount = _vscwprintf(format, ap);
|
||||
if (charCount < 0)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
#endif
|
||||
|
||||
size_t bufferCharCount = static_cast<size_t>(charCount) + 1;
|
||||
|
||||
wchar_t* str = static_cast<wchar_t*>(malloc(bufferCharCount * sizeof(wchar_t)));
|
||||
if (!str)
|
||||
{
|
||||
return -1;
|
||||
}
|
||||
|
||||
#if defined(__BORLANDC__)
|
||||
int retval = vsnwprintf_s(str, bufferCharCount, format, ap);
|
||||
#elif defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
|
||||
int retval = _vsnwprintf(str, bufferCharCount, format, ap);
|
||||
#else
|
||||
int retval = _vsnwprintf_s(str, bufferCharCount, charCount, format, ap);
|
||||
#endif
|
||||
if (retval < 0)
|
||||
{
|
||||
free(str);
|
||||
return -1;
|
||||
}
|
||||
|
||||
*strp = str;
|
||||
return retval;
|
||||
}
|
||||
#endif
|
||||
|
||||
#ifdef _WIN32
|
||||
inline std::wstring toWide(const char* str, UINT cp = codePage::kChar)
|
||||
{
|
||||
size_t len = ::strlen(str);
|
||||
std::wstring wstr(len, 0);
|
||||
|
||||
if (!wstr.empty())
|
||||
{
|
||||
int wlen = MultiByteToWideChar(cp, 0, str, static_cast<int>(len), &wstr[0], static_cast<int>(wstr.size()));
|
||||
wstr.resize(wlen);
|
||||
}
|
||||
|
||||
return wstr;
|
||||
}
|
||||
|
||||
inline std::wstring toWide(const std::string& str, UINT cp = codePage::kChar)
|
||||
{
|
||||
return toWide(str.c_str(), cp);
|
||||
}
|
||||
|
||||
inline const std::wstring& toWide(const std::wstring& str) // do nothing for already wide string
|
||||
{
|
||||
return str;
|
||||
}
|
||||
|
||||
inline std::string toNarrow(const std::wstring& wstr, long page)
|
||||
{
|
||||
int len = WideCharToMultiByte(page, 0, wstr.c_str(), static_cast<int>(wstr.size()), 0, 0, 0, 0);
|
||||
std::string str(len, 0);
|
||||
|
||||
if (!str.empty())
|
||||
{
|
||||
WideCharToMultiByte(page, 0, wstr.c_str(), static_cast<int>(wstr.size()), &str[0], len, 0, 0);
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
||||
#elif PLOG_ENABLE_WCHAR_INPUT
|
||||
inline std::string toNarrow(const wchar_t* wstr)
|
||||
{
|
||||
size_t wlen = ::wcslen(wstr);
|
||||
std::string str(wlen * sizeof(wchar_t), 0);
|
||||
|
||||
if (!str.empty())
|
||||
{
|
||||
const char* in = reinterpret_cast<const char*>(&wstr[0]);
|
||||
char* out = &str[0];
|
||||
size_t inBytes = wlen * sizeof(wchar_t);
|
||||
size_t outBytes = str.size();
|
||||
|
||||
iconv_t cd = ::iconv_open("UTF-8", "WCHAR_T");
|
||||
::iconv(cd, const_cast<char**>(&in), &inBytes, &out, &outBytes);
|
||||
::iconv_close(cd);
|
||||
|
||||
str.resize(str.size() - outBytes);
|
||||
}
|
||||
|
||||
return str;
|
||||
}
|
||||
#endif
|
||||
|
||||
inline std::string processFuncName(const char* func)
|
||||
{
|
||||
#if (defined(_WIN32) && !defined(__MINGW32__)) || defined(__OBJC__)
|
||||
return std::string(func);
|
||||
#else
|
||||
const char* funcBegin = func;
|
||||
const char* funcEnd = ::strchr(funcBegin, '(');
|
||||
int foundTemplate = 0;
|
||||
|
||||
if (!funcEnd)
|
||||
{
|
||||
return std::string(func);
|
||||
}
|
||||
|
||||
for (const char* i = funcEnd - 1; i >= funcBegin; --i) // search backwards for the first space char
|
||||
{
|
||||
if (*i == '>')
|
||||
{
|
||||
foundTemplate++;
|
||||
}
|
||||
else if (*i == '<')
|
||||
{
|
||||
foundTemplate--;
|
||||
}
|
||||
else if (*i == ' ' && foundTemplate == 0)
|
||||
{
|
||||
funcBegin = i + 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
return std::string(funcBegin, funcEnd);
|
||||
#endif
|
||||
}
|
||||
|
||||
inline const nchar* findExtensionDot(const nchar* fileName)
|
||||
{
|
||||
#if PLOG_CHAR_IS_UTF8
|
||||
return std::strrchr(fileName, '.');
|
||||
#else
|
||||
return std::wcsrchr(fileName, L'.');
|
||||
#endif
|
||||
}
|
||||
|
||||
inline void splitFileName(const nchar* fileName, nstring& fileNameNoExt, nstring& fileExt)
|
||||
{
|
||||
const nchar* dot = findExtensionDot(fileName);
|
||||
|
||||
if (dot)
|
||||
{
|
||||
fileNameNoExt.assign(fileName, dot);
|
||||
fileExt.assign(dot + 1);
|
||||
}
|
||||
else
|
||||
{
|
||||
fileNameNoExt.assign(fileName);
|
||||
fileExt.clear();
|
||||
}
|
||||
}
|
||||
|
||||
class PLOG_LINKAGE NonCopyable
|
||||
{
|
||||
protected:
|
||||
NonCopyable()
|
||||
{
|
||||
}
|
||||
|
||||
private:
|
||||
NonCopyable(const NonCopyable&);
|
||||
NonCopyable& operator=(const NonCopyable&);
|
||||
};
|
||||
|
||||
class PLOG_LINKAGE_HIDDEN File : NonCopyable
|
||||
{
|
||||
public:
|
||||
File() : m_file(-1)
|
||||
{
|
||||
}
|
||||
|
||||
~File()
|
||||
{
|
||||
close();
|
||||
}
|
||||
|
||||
size_t open(const nstring& fileName)
|
||||
{
|
||||
#if defined(_WIN32) && (defined(__BORLANDC__) || defined(__MINGW32__))
|
||||
m_file = ::_wsopen(toWide(fileName).c_str(), _O_CREAT | _O_WRONLY | _O_BINARY | _O_NOINHERIT, SH_DENYWR, _S_IREAD | _S_IWRITE);
|
||||
#elif defined(_WIN32)
|
||||
::_wsopen_s(&m_file, toWide(fileName).c_str(), _O_CREAT | _O_WRONLY | _O_BINARY | _O_NOINHERIT, _SH_DENYWR, _S_IREAD | _S_IWRITE);
|
||||
#elif defined(O_CLOEXEC)
|
||||
m_file = ::open(fileName.c_str(), O_CREAT | O_APPEND | O_WRONLY | O_CLOEXEC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
|
||||
#else
|
||||
m_file = ::open(fileName.c_str(), O_CREAT | O_APPEND | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
|
||||
#endif
|
||||
return seek(0, SEEK_END);
|
||||
}
|
||||
|
||||
size_t write(const void* buf, size_t count)
|
||||
{
|
||||
return m_file != -1 ? static_cast<size_t>(
|
||||
#ifdef _WIN32
|
||||
::_write(m_file, buf, static_cast<unsigned int>(count))
|
||||
#else
|
||||
::write(m_file, buf, count)
|
||||
#endif
|
||||
) : static_cast<size_t>(-1);
|
||||
}
|
||||
|
||||
template<class CharType>
|
||||
size_t write(const std::basic_string<CharType>& str)
|
||||
{
|
||||
return write(str.data(), str.size() * sizeof(CharType));
|
||||
}
|
||||
|
||||
size_t seek(size_t offset, int whence)
|
||||
{
|
||||
return m_file != -1 ? static_cast<size_t>(
|
||||
#if defined(_WIN32) && (defined(__BORLANDC__) || defined(__MINGW32__))
|
||||
::_lseek(m_file, static_cast<off_t>(offset), whence)
|
||||
#elif defined(_WIN32)
|
||||
::_lseeki64(m_file, static_cast<off_t>(offset), whence)
|
||||
#else
|
||||
::lseek(m_file, static_cast<off_t>(offset), whence)
|
||||
#endif
|
||||
) : static_cast<size_t>(-1);
|
||||
}
|
||||
|
||||
void close()
|
||||
{
|
||||
if (m_file != -1)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
::_close(m_file);
|
||||
#else
|
||||
::close(m_file);
|
||||
#endif
|
||||
m_file = -1;
|
||||
}
|
||||
}
|
||||
|
||||
static int unlink(const nstring& fileName)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
return ::_wunlink(toWide(fileName).c_str());
|
||||
#else
|
||||
return ::unlink(fileName.c_str());
|
||||
#endif
|
||||
}
|
||||
|
||||
static int rename(const nstring& oldFilename, const nstring& newFilename)
|
||||
{
|
||||
#ifdef _WIN32
|
||||
return MoveFileW(toWide(oldFilename).c_str(), toWide(newFilename).c_str());
|
||||
#else
|
||||
return ::rename(oldFilename.c_str(), newFilename.c_str());
|
||||
#endif
|
||||
}
|
||||
|
||||
private:
|
||||
int m_file;
|
||||
};
|
||||
|
||||
class PLOG_LINKAGE_HIDDEN Mutex : NonCopyable
|
||||
{
|
||||
public:
|
||||
Mutex()
|
||||
{
|
||||
#ifdef __FREERTOS__
|
||||
m_sync = xSemaphoreCreateBinary();
|
||||
xSemaphoreGive(m_sync);
|
||||
#elif defined(_WIN32)
|
||||
InitializeCriticalSection(&m_sync);
|
||||
#elif defined(__rtems__)
|
||||
rtems_semaphore_create(0, 1,
|
||||
RTEMS_PRIORITY |
|
||||
RTEMS_BINARY_SEMAPHORE |
|
||||
RTEMS_INHERIT_PRIORITY, 1, &m_sync);
|
||||
#elif defined(_POSIX_THREADS)
|
||||
::pthread_mutex_init(&m_sync, 0);
|
||||
#endif
|
||||
}
|
||||
|
||||
~Mutex()
|
||||
{
|
||||
#ifdef __FREERTOS__
|
||||
vSemaphoreDelete(m_sync);
|
||||
#elif defined(_WIN32)
|
||||
DeleteCriticalSection(&m_sync);
|
||||
#elif defined(__rtems__)
|
||||
rtems_semaphore_delete(m_sync);
|
||||
#elif defined(_POSIX_THREADS)
|
||||
::pthread_mutex_destroy(&m_sync);
|
||||
#endif
|
||||
}
|
||||
|
||||
friend class MutexLock;
|
||||
|
||||
private:
|
||||
void lock()
|
||||
{
|
||||
#ifdef __FREERTOS__
|
||||
xSemaphoreTake(m_sync, portMAX_DELAY);
|
||||
#elif defined(_WIN32)
|
||||
EnterCriticalSection(&m_sync);
|
||||
#elif defined(__rtems__)
|
||||
rtems_semaphore_obtain(m_sync, RTEMS_WAIT, RTEMS_NO_TIMEOUT);
|
||||
#elif defined(_POSIX_THREADS)
|
||||
::pthread_mutex_lock(&m_sync);
|
||||
#endif
|
||||
}
|
||||
|
||||
void unlock()
|
||||
{
|
||||
#ifdef __FREERTOS__
|
||||
xSemaphoreGive(m_sync);
|
||||
#elif defined(_WIN32)
|
||||
LeaveCriticalSection(&m_sync);
|
||||
#elif defined(__rtems__)
|
||||
rtems_semaphore_release(m_sync);
|
||||
#elif defined(_POSIX_THREADS)
|
||||
::pthread_mutex_unlock(&m_sync);
|
||||
#endif
|
||||
}
|
||||
|
||||
private:
|
||||
#ifdef __FREERTOS__
|
||||
SemaphoreHandle_t m_sync;
|
||||
#elif defined(_WIN32)
|
||||
CRITICAL_SECTION m_sync;
|
||||
#elif defined(__rtems__)
|
||||
rtems_id m_sync;
|
||||
#elif defined(_POSIX_THREADS)
|
||||
pthread_mutex_t m_sync;
|
||||
#endif
|
||||
};
|
||||
|
||||
class PLOG_LINKAGE_HIDDEN MutexLock : NonCopyable
|
||||
{
|
||||
public:
|
||||
MutexLock(Mutex& mutex) : m_mutex(mutex)
|
||||
{
|
||||
m_mutex.lock();
|
||||
}
|
||||
|
||||
~MutexLock()
|
||||
{
|
||||
m_mutex.unlock();
|
||||
}
|
||||
|
||||
private:
|
||||
Mutex& m_mutex;
|
||||
};
|
||||
|
||||
template<class T>
|
||||
#ifdef _WIN32
|
||||
class Singleton : NonCopyable
|
||||
#else
|
||||
class PLOG_LINKAGE Singleton : NonCopyable
|
||||
#endif
|
||||
{
|
||||
public:
|
||||
#if (defined(__clang__) || defined(__GNUC__) && __GNUC__ >= 8) && !defined(__BORLANDC__)
|
||||
// This constructor is called before the `T` object is fully constructed, and
|
||||
// pointers are not dereferenced anyway, so UBSan shouldn't check vptrs.
|
||||
__attribute__((no_sanitize("vptr")))
|
||||
#endif
|
||||
Singleton()
|
||||
{
|
||||
assert(!m_instance);
|
||||
m_instance = static_cast<T*>(this);
|
||||
}
|
||||
|
||||
~Singleton()
|
||||
{
|
||||
assert(m_instance);
|
||||
m_instance = 0;
|
||||
}
|
||||
|
||||
static T* getInstance()
|
||||
{
|
||||
return m_instance;
|
||||
}
|
||||
|
||||
private:
|
||||
static T* m_instance;
|
||||
};
|
||||
|
||||
template<class T>
|
||||
T* Singleton<T>::m_instance = NULL;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,175 @@
|
||||
#pragma once
|
||||
|
||||
#ifdef _WIN32
|
||||
|
||||
// These windows structs must be in a global namespace
|
||||
struct HKEY__;
|
||||
struct _SECURITY_ATTRIBUTES;
|
||||
struct _CONSOLE_SCREEN_BUFFER_INFO;
|
||||
struct _RTL_CRITICAL_SECTION;
|
||||
|
||||
namespace plog
|
||||
{
|
||||
typedef unsigned long DWORD;
|
||||
typedef unsigned short WORD;
|
||||
typedef unsigned char BYTE;
|
||||
typedef unsigned int UINT;
|
||||
typedef int BOOL;
|
||||
typedef long LSTATUS;
|
||||
typedef char* LPSTR;
|
||||
typedef wchar_t* LPWSTR;
|
||||
typedef const char* LPCSTR;
|
||||
typedef const wchar_t* LPCWSTR;
|
||||
typedef void* HANDLE;
|
||||
typedef HKEY__* HKEY;
|
||||
typedef size_t ULONG_PTR;
|
||||
|
||||
struct CRITICAL_SECTION
|
||||
{
|
||||
void* DebugInfo;
|
||||
long LockCount;
|
||||
long RecursionCount;
|
||||
HANDLE OwningThread;
|
||||
HANDLE LockSemaphore;
|
||||
ULONG_PTR SpinCount;
|
||||
};
|
||||
|
||||
struct COORD
|
||||
{
|
||||
short X;
|
||||
short Y;
|
||||
};
|
||||
|
||||
struct SMALL_RECT
|
||||
{
|
||||
short Left;
|
||||
short Top;
|
||||
short Right;
|
||||
short Bottom;
|
||||
};
|
||||
|
||||
struct CONSOLE_SCREEN_BUFFER_INFO
|
||||
{
|
||||
COORD dwSize;
|
||||
COORD dwCursorPosition;
|
||||
WORD wAttributes;
|
||||
SMALL_RECT srWindow;
|
||||
COORD dwMaximumWindowSize;
|
||||
};
|
||||
|
||||
namespace codePage
|
||||
{
|
||||
const UINT kActive = 0;
|
||||
const UINT kUTF8 = 65001;
|
||||
#if PLOG_CHAR_IS_UTF8
|
||||
const UINT kChar = kUTF8;
|
||||
#else
|
||||
const UINT kChar = kActive;
|
||||
#endif
|
||||
}
|
||||
|
||||
namespace eventLog
|
||||
{
|
||||
const WORD kErrorType = 0x0001;
|
||||
const WORD kWarningType = 0x0002;
|
||||
const WORD kInformationType = 0x0004;
|
||||
}
|
||||
|
||||
namespace hkey
|
||||
{
|
||||
const HKEY kLocalMachine = reinterpret_cast<HKEY>(static_cast<ULONG_PTR>(0x80000002));
|
||||
}
|
||||
|
||||
namespace regSam
|
||||
{
|
||||
const DWORD kQueryValue = 0x0001;
|
||||
const DWORD kSetValue = 0x0002;
|
||||
}
|
||||
|
||||
namespace regType
|
||||
{
|
||||
const DWORD kExpandSz = 2;
|
||||
const DWORD kDword = 4;
|
||||
}
|
||||
|
||||
namespace stdHandle
|
||||
{
|
||||
const DWORD kOutput = static_cast<DWORD>(-11);
|
||||
const DWORD kErrorOutput = static_cast<DWORD>(-12);
|
||||
}
|
||||
|
||||
namespace foreground
|
||||
{
|
||||
const WORD kBlue = 0x0001;
|
||||
const WORD kGreen = 0x0002;
|
||||
const WORD kRed = 0x0004;
|
||||
const WORD kIntensity = 0x0008;
|
||||
}
|
||||
|
||||
namespace background
|
||||
{
|
||||
const WORD kBlue = 0x0010;
|
||||
const WORD kGreen = 0x0020;
|
||||
const WORD kRed = 0x0040;
|
||||
const WORD kIntensity = 0x0080;
|
||||
}
|
||||
|
||||
extern "C"
|
||||
{
|
||||
__declspec(dllimport) int __stdcall MultiByteToWideChar(UINT CodePage, DWORD dwFlags, LPCSTR lpMultiByteStr, int cbMultiByte, LPWSTR lpWideCharStr, int cchWideChar);
|
||||
__declspec(dllimport) int __stdcall WideCharToMultiByte(UINT CodePage, DWORD dwFlags, LPCWSTR lpWideCharStr, int cchWideChar, LPSTR lpMultiByteStr, int cbMultiByte, const char* lpDefaultChar, BOOL* lpUsedDefaultChar);
|
||||
|
||||
__declspec(dllimport) DWORD __stdcall GetCurrentThreadId();
|
||||
|
||||
__declspec(dllimport) BOOL __stdcall MoveFileW(LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName);
|
||||
|
||||
__declspec(dllimport) void __stdcall InitializeCriticalSection(_RTL_CRITICAL_SECTION* lpCriticalSection);
|
||||
__declspec(dllimport) void __stdcall EnterCriticalSection(_RTL_CRITICAL_SECTION* lpCriticalSection);
|
||||
__declspec(dllimport) void __stdcall LeaveCriticalSection(_RTL_CRITICAL_SECTION* lpCriticalSection);
|
||||
__declspec(dllimport) void __stdcall DeleteCriticalSection(_RTL_CRITICAL_SECTION* lpCriticalSection);
|
||||
|
||||
__declspec(dllimport) HANDLE __stdcall RegisterEventSourceW(LPCWSTR lpUNCServerName, LPCWSTR lpSourceName);
|
||||
__declspec(dllimport) BOOL __stdcall DeregisterEventSource(HANDLE hEventLog);
|
||||
__declspec(dllimport) BOOL __stdcall ReportEventW(HANDLE hEventLog, WORD wType, WORD wCategory, DWORD dwEventID, void* lpUserSid, WORD wNumStrings, DWORD dwDataSize, LPCWSTR* lpStrings, void* lpRawData);
|
||||
|
||||
__declspec(dllimport) LSTATUS __stdcall RegCreateKeyExW(HKEY hKey, LPCWSTR lpSubKey, DWORD Reserved, LPWSTR lpClass, DWORD dwOptions, DWORD samDesired, _SECURITY_ATTRIBUTES* lpSecurityAttributes, HKEY* phkResult, DWORD* lpdwDisposition);
|
||||
__declspec(dllimport) LSTATUS __stdcall RegSetValueExW(HKEY hKey, LPCWSTR lpValueName, DWORD Reserved, DWORD dwType, const BYTE* lpData, DWORD cbData);
|
||||
__declspec(dllimport) LSTATUS __stdcall RegCloseKey(HKEY hKey);
|
||||
__declspec(dllimport) LSTATUS __stdcall RegOpenKeyExW(HKEY hKey, LPCWSTR lpSubKey, DWORD ulOptions, DWORD samDesired, HKEY* phkResult);
|
||||
__declspec(dllimport) LSTATUS __stdcall RegDeleteKeyW(HKEY hKey, LPCWSTR lpSubKey);
|
||||
|
||||
__declspec(dllimport) HANDLE __stdcall GetStdHandle(DWORD nStdHandle);
|
||||
|
||||
__declspec(dllimport) BOOL __stdcall WriteConsoleW(HANDLE hConsoleOutput, const void* lpBuffer, DWORD nNumberOfCharsToWrite, DWORD* lpNumberOfCharsWritten, void* lpReserved);
|
||||
__declspec(dllimport) BOOL __stdcall GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, _CONSOLE_SCREEN_BUFFER_INFO* lpConsoleScreenBufferInfo);
|
||||
__declspec(dllimport) BOOL __stdcall SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttributes);
|
||||
|
||||
__declspec(dllimport) void __stdcall OutputDebugStringW(LPCWSTR lpOutputString);
|
||||
}
|
||||
|
||||
inline void InitializeCriticalSection(CRITICAL_SECTION* criticalSection)
|
||||
{
|
||||
plog::InitializeCriticalSection(reinterpret_cast<_RTL_CRITICAL_SECTION*>(criticalSection));
|
||||
}
|
||||
|
||||
inline void EnterCriticalSection(CRITICAL_SECTION* criticalSection)
|
||||
{
|
||||
plog::EnterCriticalSection(reinterpret_cast<_RTL_CRITICAL_SECTION*>(criticalSection));
|
||||
}
|
||||
|
||||
inline void LeaveCriticalSection(CRITICAL_SECTION* criticalSection)
|
||||
{
|
||||
plog::LeaveCriticalSection(reinterpret_cast<_RTL_CRITICAL_SECTION*>(criticalSection));
|
||||
}
|
||||
|
||||
inline void DeleteCriticalSection(CRITICAL_SECTION* criticalSection)
|
||||
{
|
||||
plog::DeleteCriticalSection(reinterpret_cast<_RTL_CRITICAL_SECTION*>(criticalSection));
|
||||
}
|
||||
|
||||
inline BOOL GetConsoleScreenBufferInfo(HANDLE consoleOutput, CONSOLE_SCREEN_BUFFER_INFO* consoleScreenBufferInfo)
|
||||
{
|
||||
return plog::GetConsoleScreenBufferInfo(consoleOutput, reinterpret_cast<_CONSOLE_SCREEN_BUFFER_INFO*>(consoleScreenBufferInfo));
|
||||
}
|
||||
}
|
||||
#endif // _WIN32
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,4 +0,0 @@
|
||||
/scanvalue
|
||||
/scankey
|
||||
/parser
|
||||
/*.so.*
|
||||
@@ -1,10 +0,0 @@
|
||||
# includes/tomlc17/CMakeLists.txt
|
||||
|
||||
add_library(tomlc17 STATIC tomlc17.c)
|
||||
set_target_properties(tomlc17 PROPERTIES
|
||||
OUTPUT_NAME "tomlc17"
|
||||
)
|
||||
|
||||
target_include_directories(tomlc17 PUBLIC
|
||||
${CMAKE_CURRENT_SOURCE_DIR}
|
||||
)
|
||||
@@ -1,41 +0,0 @@
|
||||
HFILES = tomlc17.h
|
||||
CFILES = tomlc17.c
|
||||
OBJ = $(CFILES:.c=.o)
|
||||
|
||||
CFLAGS = -std=c17 -fpic -Wmissing-declarations -Wall -Wextra -MMD
|
||||
LIB_VERSION = 1.0
|
||||
LIB = libtomlc17.a
|
||||
LIB_SHARED = libtomlc17.so.$(LIB_VERSION)
|
||||
EXEC =
|
||||
|
||||
ifdef DEBUG
|
||||
CFLAGS += -O0 -g
|
||||
else
|
||||
CFLAGS += -O3 -DNDEBUG
|
||||
endif
|
||||
|
||||
all: $(EXEC) $(LIB) $(LIB_SHARED)
|
||||
|
||||
*.o: $(HFILES)
|
||||
|
||||
libtomlc17.a: tomlc17.o
|
||||
ar -rcs $@ $^
|
||||
|
||||
$(LIB_SHARED): tomlc17.o
|
||||
$(CC) -shared -o $@ $^
|
||||
|
||||
-include $(OBJ:%.o=%.d) $(EXEC:%=%.d)
|
||||
|
||||
test: all
|
||||
|
||||
clean:
|
||||
rm -f *.o *.d *.a *.so.* $(EXEC)
|
||||
|
||||
distclean: clean
|
||||
|
||||
format:
|
||||
clang-format -i *.[ch] *.hpp
|
||||
|
||||
|
||||
.PHONY: all clean distclean format
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,190 +0,0 @@
|
||||
/* Copyright (c) 2024-2025, CK Tan.
|
||||
* https://github.com/cktan/tomlc17/blob/main/LICENSE
|
||||
*/
|
||||
#ifndef TOMLC17_H
|
||||
#define TOMLC17_H
|
||||
|
||||
/*
|
||||
* USAGE:
|
||||
*
|
||||
* 1. Call toml_parse(), toml_parse_file(), or toml_parse_file_ex()
|
||||
* 2. Check result.ok
|
||||
* 3. Use toml_get() or toml_seek() to query and traverse the
|
||||
* result.toptab
|
||||
* 4. Call toml_free() to release resources.
|
||||
*
|
||||
*/
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
|
||||
#ifdef __cplusplus
|
||||
#define TOML_EXTERN extern "C"
|
||||
#else
|
||||
#define TOML_EXTERN extern
|
||||
#endif
|
||||
|
||||
enum toml_type_t {
|
||||
TOML_UNKNOWN = 0,
|
||||
TOML_STRING,
|
||||
TOML_INT64,
|
||||
TOML_FP64,
|
||||
TOML_BOOLEAN,
|
||||
TOML_DATE,
|
||||
TOML_TIME,
|
||||
TOML_DATETIME,
|
||||
TOML_DATETIMETZ,
|
||||
TOML_ARRAY,
|
||||
TOML_TABLE,
|
||||
};
|
||||
typedef enum toml_type_t toml_type_t;
|
||||
|
||||
/* This is a Node in a Tree that represents a toml document rooted
|
||||
* at toml_result_t::toptab.
|
||||
*/
|
||||
typedef struct toml_datum_t toml_datum_t;
|
||||
struct toml_datum_t {
|
||||
toml_type_t type;
|
||||
uint32_t flag; // internal
|
||||
union {
|
||||
const char *s; // same as str.ptr; use if there are no NUL in string.
|
||||
struct {
|
||||
const char *ptr; // NUL terminated string
|
||||
int len; // length excluding the terminating NUL.
|
||||
} str;
|
||||
int64_t int64; // integer
|
||||
double fp64; // float
|
||||
bool boolean;
|
||||
struct { // date, time
|
||||
int16_t year, month, day;
|
||||
int16_t hour, minute, second;
|
||||
int32_t usec;
|
||||
int16_t tz; // in minutes
|
||||
} ts;
|
||||
struct { // array
|
||||
int32_t size; // count elem
|
||||
toml_datum_t *elem; // elem[]
|
||||
} arr;
|
||||
struct { // table
|
||||
int32_t size; // count key
|
||||
const char **key; // key[]
|
||||
int *len; // len[]
|
||||
toml_datum_t *value; // value[]
|
||||
} tab;
|
||||
} u;
|
||||
};
|
||||
|
||||
/* Result returned by toml_parse() */
|
||||
typedef struct toml_result_t toml_result_t;
|
||||
struct toml_result_t {
|
||||
bool ok; // success flag
|
||||
toml_datum_t toptab; // valid if ok
|
||||
char errmsg[200]; // valid if not ok
|
||||
void *__internal; // do not use
|
||||
};
|
||||
|
||||
/**
|
||||
* Parse a toml document. Returns a toml_result which must be freed
|
||||
* using toml_free() eventually.
|
||||
*
|
||||
* IMPORTANT: src[] must be a NUL terminated string! The len parameter
|
||||
* does not include the NUL terminator.
|
||||
*/
|
||||
TOML_EXTERN toml_result_t toml_parse(const char *src, int len);
|
||||
|
||||
/**
|
||||
* Parse a toml file. Returns a toml_result which must be freed
|
||||
* using toml_free() eventually.
|
||||
*
|
||||
* IMPORTANT: you are still responsible to fclose(fp).
|
||||
*/
|
||||
TOML_EXTERN toml_result_t toml_parse_file(FILE *fp);
|
||||
|
||||
/**
|
||||
* Parse a toml file. Returns a toml_result which must be freed
|
||||
* using toml_free() eventually.
|
||||
*/
|
||||
TOML_EXTERN toml_result_t toml_parse_file_ex(const char *fname);
|
||||
|
||||
/**
|
||||
* Release the result.
|
||||
*/
|
||||
TOML_EXTERN void toml_free(toml_result_t result);
|
||||
|
||||
/**
|
||||
* Find a key in a toml_table. Return the value of the key if found,
|
||||
* or a TOML_UNKNOWN otherwise.
|
||||
*/
|
||||
TOML_EXTERN toml_datum_t toml_get(toml_datum_t table, const char *key);
|
||||
|
||||
/**
|
||||
* Locate a value starting from a toml_table. Return the value of the key if
|
||||
* found, or a TOML_UNKNOWN otherwise.
|
||||
*
|
||||
* Note: the multipart-key is separated by DOT, and must not have any escape
|
||||
* chars.
|
||||
*/
|
||||
TOML_EXTERN toml_datum_t toml_seek(toml_datum_t table,
|
||||
const char *multipart_key);
|
||||
|
||||
/**
|
||||
* OBSOLETE: use toml_get() instead.
|
||||
* Find a key in a toml_table. Return the value of the key if found,
|
||||
* or a TOML_UNKNOWN otherwise. (
|
||||
*/
|
||||
static inline toml_datum_t toml_table_find(toml_datum_t table,
|
||||
const char *key) {
|
||||
return toml_get(table, key);
|
||||
}
|
||||
|
||||
/**
|
||||
* Override values in r1 using r2. Return a new result. All results
|
||||
* (i.e., r1, r2 and the returned result) must be freed using toml_free()
|
||||
* after use.
|
||||
*
|
||||
* LOGIC:
|
||||
* ret = copy of r1
|
||||
* for each item x in r2:
|
||||
* if x is not in ret:
|
||||
* override
|
||||
* elif x in ret is NOT of the same type:
|
||||
* override
|
||||
* elif x is an array of tables:
|
||||
* append r2.x to ret.x
|
||||
* elif x is a table:
|
||||
* merge r2.x to ret.x
|
||||
* else:
|
||||
* override
|
||||
*/
|
||||
TOML_EXTERN toml_result_t toml_merge(const toml_result_t *r1,
|
||||
const toml_result_t *r2);
|
||||
|
||||
/**
|
||||
* Check if two results are the same. Dictinary and array orders are
|
||||
* sensitive.
|
||||
*/
|
||||
TOML_EXTERN bool toml_equiv(const toml_result_t *r1, const toml_result_t *r2);
|
||||
|
||||
/* Options that override tomlc17 defaults globally */
|
||||
typedef struct toml_option_t toml_option_t;
|
||||
struct toml_option_t {
|
||||
bool check_utf8; // Check all chars are valid utf8; default: false.
|
||||
void *(*mem_realloc)(void *ptr, size_t size); // default: realloc()
|
||||
void (*mem_free)(void *ptr); // default: free()
|
||||
};
|
||||
|
||||
/**
|
||||
* Get the default options. IF NECESSARY, use this to initialize
|
||||
* toml_option_t and override values before calling
|
||||
* toml_set_option().
|
||||
*/
|
||||
TOML_EXTERN toml_option_t toml_default_option(void);
|
||||
|
||||
/**
|
||||
* Set toml options globally. Do this ONLY IF you are not satisfied with the
|
||||
* defaults.
|
||||
*/
|
||||
TOML_EXTERN void toml_set_option(toml_option_t opt);
|
||||
|
||||
#endif // TOMLC17_H
|
||||
@@ -1,231 +0,0 @@
|
||||
#pragma once
|
||||
#if !defined(__cplusplus) || __cplusplus < 202002L
|
||||
#error "This code requires C++20 or later"
|
||||
#endif
|
||||
|
||||
#include "tomlc17.h"
|
||||
#include <chrono>
|
||||
#include <cstdint>
|
||||
#include <optional>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
namespace toml {
|
||||
|
||||
|
||||
class Datum : public toml_datum_t {
|
||||
public:
|
||||
using datetime = std::chrono::sys_time<std::chrono::microseconds>;
|
||||
using time = std::chrono::hh_mm_ss<std::chrono::microseconds>;
|
||||
using date = std::chrono::year_month_day;
|
||||
|
||||
Datum(toml_datum_t dat = toml_datum_t{}) : toml_datum_t(dat) {}
|
||||
bool is_table() const { return type == TOML_TABLE; }
|
||||
bool is_array() const { return type == TOML_ARRAY; }
|
||||
|
||||
// Retrieve a string.
|
||||
std::optional<std::string_view> as_str() const {
|
||||
if (type != TOML_STRING)
|
||||
return std::nullopt;
|
||||
else
|
||||
return std::string_view{u.str.ptr, (size_t)u.str.len};
|
||||
}
|
||||
|
||||
// Retrieve an int.
|
||||
std::optional<std::int64_t> as_int() const {
|
||||
if (type != TOML_INT64)
|
||||
return std::nullopt;
|
||||
else
|
||||
return u.int64;
|
||||
}
|
||||
|
||||
// Retrieve a float.
|
||||
std::optional<double> as_real() const {
|
||||
if (type != TOML_FP64)
|
||||
return std::nullopt;
|
||||
else
|
||||
return u.fp64;
|
||||
}
|
||||
|
||||
// Retrieve a boolean.
|
||||
std::optional<bool> as_bool() const {
|
||||
if (type != TOML_BOOLEAN)
|
||||
return std::nullopt;
|
||||
else
|
||||
return !!u.boolean;
|
||||
}
|
||||
|
||||
// Retrieve a date.
|
||||
std::optional<date> as_date() const {
|
||||
using namespace std::chrono;
|
||||
if (type != TOML_DATE)
|
||||
return std::nullopt;
|
||||
else
|
||||
return date{year(u.ts.year), month(u.ts.month), day(u.ts.day)};
|
||||
}
|
||||
|
||||
// Retrieve a time.
|
||||
std::optional<time> as_time() const {
|
||||
using namespace std::chrono;
|
||||
if (type != TOML_TIME)
|
||||
return std::nullopt;
|
||||
else
|
||||
return time{hours(u.ts.hour) + minutes(u.ts.minute) +
|
||||
seconds(u.ts.second) + microseconds(u.ts.usec)};
|
||||
}
|
||||
|
||||
// Retrieve a datetime.
|
||||
std::optional<datetime> as_datetime() const {
|
||||
using namespace std::chrono;
|
||||
if (type != TOML_DATETIME) {
|
||||
return std::nullopt;
|
||||
}
|
||||
year_month_day ymd{year{u.ts.year}, month{(unsigned)u.ts.month},
|
||||
day{(unsigned)u.ts.day}};
|
||||
auto tod = hours{u.ts.hour} + minutes{u.ts.minute} + seconds{u.ts.second} +
|
||||
microseconds{u.ts.usec};
|
||||
return datetime{sys_days{ymd} + tod};
|
||||
}
|
||||
|
||||
// Retrieve a datetime and minute offset from UTC.
|
||||
std::optional<std::pair<datetime, int>> as_datetimetz() const {
|
||||
using namespace std::chrono;
|
||||
|
||||
if (type != TOML_DATETIMETZ) {
|
||||
return std::nullopt;
|
||||
}
|
||||
year_month_day ymd{year{u.ts.year}, month{(unsigned)u.ts.month},
|
||||
day{(unsigned)u.ts.day}};
|
||||
auto tod = hours{u.ts.hour} + minutes{u.ts.minute} + seconds{u.ts.second} +
|
||||
microseconds{u.ts.usec};
|
||||
return std::pair{datetime{sys_days{ymd} + tod}, u.ts.tz};
|
||||
}
|
||||
|
||||
// Retrieve an array of Datum from this datum.
|
||||
std::optional<std::vector<Datum>> as_vector() const {
|
||||
if (type != TOML_ARRAY) {
|
||||
return std::nullopt;
|
||||
}
|
||||
std::vector<Datum> ret;
|
||||
ret.assign(u.arr.elem, u.arr.elem + u.arr.size);
|
||||
return ret;
|
||||
}
|
||||
|
||||
// Retrieve an array of strings from this datum.
|
||||
std::optional<std::vector<std::string_view>> as_strvec() const {
|
||||
try {
|
||||
auto vec = as_vector().value();
|
||||
std::vector<std::string_view> ret;
|
||||
ret.resize(vec.size());
|
||||
for (size_t i = 0; i < vec.size(); i++) {
|
||||
ret[i] = vec[i].as_str().value();
|
||||
}
|
||||
return ret;
|
||||
} catch (const std::bad_optional_access &ex) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
|
||||
// Retrieve an array of ints from this datum
|
||||
std::optional<std::vector<int64_t>> as_intvec() const {
|
||||
try {
|
||||
auto vec = as_vector().value();
|
||||
std::vector<int64_t> ret;
|
||||
ret.resize(vec.size());
|
||||
for (size_t i = 0; i < vec.size(); i++) {
|
||||
ret[i] = *vec[i].as_int();
|
||||
}
|
||||
return ret;
|
||||
} catch (const std::bad_optional_access &ex) {
|
||||
return std::nullopt;
|
||||
}
|
||||
}
|
||||
|
||||
// For tables. Retrieve the value of a composite key from this datum
|
||||
// (which is a table).
|
||||
std::optional<Datum> get(std::initializer_list<std::string_view> keys) const {
|
||||
Datum tab = *this;
|
||||
Datum value;
|
||||
for (auto key : keys) {
|
||||
value = {};
|
||||
if (tab.type != TOML_TABLE) {
|
||||
return std::nullopt;
|
||||
}
|
||||
for (int i = 0; i < tab.u.tab.size; i++) {
|
||||
if (key ==
|
||||
std::string_view{tab.u.tab.key[i], (size_t)tab.u.tab.len[i]}) {
|
||||
value = tab.u.tab.value[i];
|
||||
break;
|
||||
}
|
||||
}
|
||||
tab = value;
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
// Retrieve the value of a key
|
||||
std::optional<Datum> get(std::string_view key) const { return get({key}); }
|
||||
|
||||
// Retrieve the value of a multi-part key
|
||||
std::optional<Datum> seek(const char *multipart_key) const {
|
||||
auto ret = toml_seek(*this, multipart_key);
|
||||
if (!ret.type) {
|
||||
return std::nullopt;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
}; // class Datum
|
||||
|
||||
class Result : private toml_result_t {
|
||||
public:
|
||||
Result(const toml_result_t& result) : toml_result_t(result) {}
|
||||
~Result() noexcept { toml_free(*this); }
|
||||
|
||||
// Disallow copying
|
||||
Result(const Result&) = delete;
|
||||
Result& operator=(const Result&) = delete;
|
||||
|
||||
// Allow moving
|
||||
Result(Result&& other) noexcept : toml_result_t() {
|
||||
swap(*this, other);
|
||||
}
|
||||
Result& operator=(Result&& other) noexcept {
|
||||
swap(*this, other);
|
||||
return *this;
|
||||
}
|
||||
|
||||
// Access methods
|
||||
bool ok() const { return toml_result_t::ok; }
|
||||
Datum toptab() const { return toml_result_t::toptab; }
|
||||
const char* errmsg() const { return toml_result_t::errmsg; }
|
||||
|
||||
// Shortcuts
|
||||
std::optional<Datum> get(std::initializer_list<std::string_view> keys) const {
|
||||
return toptab().get(keys);
|
||||
}
|
||||
std::optional<Datum> seek(const char *multipart_key) const {
|
||||
return toptab().seek(multipart_key);
|
||||
}
|
||||
|
||||
private:
|
||||
friend void swap(Result& a, Result& b) noexcept {
|
||||
std::swap(static_cast<toml_result_t&>(a), static_cast<toml_result_t&>(b));
|
||||
}
|
||||
};
|
||||
|
||||
static inline Result parse_file(FILE* fp) {
|
||||
return Result{toml_parse_file(fp)};
|
||||
}
|
||||
|
||||
static inline Result parse_file_ex(const char* fname) {
|
||||
return Result{toml_parse_file_ex(fname)};
|
||||
}
|
||||
|
||||
static inline Result parse(const std::string& s) {
|
||||
return Result{toml_parse(s.data(), s.size())};
|
||||
}
|
||||
|
||||
|
||||
|
||||
}; // namespace toml
|
||||
@@ -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.
|
||||
|
||||
@@ -1,19 +0,0 @@
|
||||
Copyright (c) 2020 rxi
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
this software and associated documentation files (the "Software"), to deal in
|
||||
the Software without restriction, including without limitation the rights to
|
||||
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
|
||||
of the Software, and to permit persons to whom the Software is furnished to do
|
||||
so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
@@ -1,7 +1,6 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2024-2025, CK Tan
|
||||
https://github.com/cktan/tomlc17
|
||||
Copyright (c) 2022 Sergey Podobry
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
@@ -19,4 +18,4 @@ 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.
|
||||
SOFTWARE.
|
||||
@@ -0,0 +1,23 @@
|
||||
Copyright (c) 2014, MAYAH
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without
|
||||
modification, are permitted provided that the following conditions are met:
|
||||
|
||||
* Redistributions of source code must retain the above copyright notice, this
|
||||
list of conditions and the following disclaimer.
|
||||
|
||||
* Redistributions in binary form must reproduce the above copyright notice,
|
||||
this list of conditions and the following disclaimer in the documentation
|
||||
and/or other materials provided with the distribution.
|
||||
|
||||
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
@@ -1,5 +0,0 @@
|
||||
# src/agent/CMakeLists.txt
|
||||
|
||||
target_include_directories(agent PRIVATE ${CMAKE_SOURCE_DIR}/includes/tomlc17)
|
||||
|
||||
target_link_libraries(agent PRIVATE shlwapi tomlc17)
|
||||
@@ -1,21 +0,0 @@
|
||||
#ifndef DATAUTILS_H
|
||||
#define DATAUTILS_H
|
||||
|
||||
#include <string.h>
|
||||
#include "InjectParameters.h"
|
||||
#include "tomlc17.h"
|
||||
#include "log.h"
|
||||
|
||||
typedef struct _InjectionInfo {
|
||||
char BootstrapAPIPath[INJECT_PATH_MAX];
|
||||
char JuiceLoaderJarPath[INJECT_PATH_MAX];
|
||||
char EntryJarPath[INJECT_PATH_MAX];
|
||||
char EntryClass[INJECT_PATH_MAX];
|
||||
char EntryMethod[INJECT_PATH_MAX];
|
||||
} InjectionInfoType;
|
||||
extern InjectionInfoType InjectionInfo;
|
||||
|
||||
void safe_copy(char *dest, const char *src, size_t dest_size);
|
||||
bool ReadInjectionInfo(toml_result_t result, InjectParameters* params);
|
||||
|
||||
#endif // DATAUTILS_H
|
||||
@@ -1,9 +0,0 @@
|
||||
#ifndef JAVAUTILS_H
|
||||
#define JAVAUTILS_H
|
||||
|
||||
#include <jni.h>
|
||||
#include <jvmti.h>
|
||||
|
||||
char* get_class_name(JNIEnv* env, jclass clazz);
|
||||
|
||||
#endif //JAVAUTILS_H
|
||||
@@ -1,29 +0,0 @@
|
||||
#ifndef JUICELOADER_H
|
||||
#define JUICELOADER_H
|
||||
|
||||
#include <jni.h>
|
||||
#include <jvmti.h>
|
||||
|
||||
typedef struct _JuiceLoaderNative {
|
||||
jvmtiEnv *jvmti;
|
||||
} JuiceLoaderNativeType;
|
||||
extern JuiceLoaderNativeType JuiceLoaderNative;
|
||||
|
||||
jint init_juiceloader(JNIEnv *env, jvmtiEnv *jvmti);
|
||||
|
||||
// JNI Functions
|
||||
// public native static boolean init();
|
||||
JNIEXPORT jboolean JNICALL loader_init(JNIEnv *env, jclass loader_class);
|
||||
// public native static boolean injectJar(String jarPath);
|
||||
JNIEXPORT jboolean JNICALL loader_injectJar(JNIEnv *env, jclass loader_class, jstring jarPath);
|
||||
// public native static boolean redefineClass(Class<?> clazz, byte[] classBytes, int length);
|
||||
JNIEXPORT jboolean JNICALL loader_redefineClass_clazz(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray classBytes, jint length);
|
||||
// public native static boolean redefineClass(String className, byte[] classBytes, int length);
|
||||
JNIEXPORT jboolean JNICALL loader_redefineClass_className(JNIEnv *env, jclass loader_class, jstring className, jbyteArray classBytes, jint length);
|
||||
// public native static Class<?>[] getLoadedClasses();
|
||||
JNIEXPORT jobjectArray JNICALL loader_getLoadedClasses(JNIEnv *env, jclass loader_class);
|
||||
// public static native byte[] getClassBytes(Class<?> clazz);
|
||||
JNIEXPORT jbyteArray JNICALL loader_getClassBytes(JNIEnv *env, jclass loader_class, jclass clazz);
|
||||
// public static native byte[] getClassBytesByName(String className);
|
||||
JNIEXPORT jbyteArray JNICALL loader_getClassBytesByName(JNIEnv *env, jclass loader_class, jstring className);
|
||||
#endif
|
||||
@@ -1,345 +0,0 @@
|
||||
/*
|
||||
Author: xiaozhou233 (xiaozhou233@vip.qq.com)
|
||||
File: juiceloader.c
|
||||
Desc: JuiceLoader Native, Provide jni function for JuiceLoader
|
||||
*/
|
||||
|
||||
#include <windows.h>
|
||||
#include "log.h"
|
||||
#include "juiceloader.h"
|
||||
#include "javautils.h"
|
||||
|
||||
JuiceLoaderNativeType JuiceLoaderNative;
|
||||
|
||||
static const char* g_bytecodes_classname = NULL;
|
||||
static unsigned char* g_bytecodes = NULL;
|
||||
static jint g_bytecodes_len = 0;
|
||||
|
||||
static void initLogger() {
|
||||
log_set_level(LOG_TRACE);
|
||||
log_is_log_time(false);
|
||||
log_set_name("juiceloader");
|
||||
log_info("Logger initialized.");
|
||||
}
|
||||
|
||||
void JNICALL ClassFileLoadHook(
|
||||
jvmtiEnv* jvmti_env,
|
||||
JNIEnv* jni_env,
|
||||
jclass class_being_redefined,
|
||||
jobject loader,
|
||||
const char* name,
|
||||
jobject protection_domain,
|
||||
jint class_data_len,
|
||||
const unsigned char* classbytes,
|
||||
jint* new_class_data_len,
|
||||
unsigned char** new_classbytes) {
|
||||
|
||||
//log_trace("CallBack: ClassFileLoadHook [%s]", name);
|
||||
|
||||
if (g_bytecodes_classname != NULL && g_bytecodes == NULL) {
|
||||
if (strcmp(name, g_bytecodes_classname) == 0) {
|
||||
g_bytecodes_len = class_data_len;
|
||||
g_bytecodes = (unsigned char*)malloc(class_data_len);
|
||||
memcpy(g_bytecodes, classbytes, class_data_len);
|
||||
|
||||
*new_classbytes = NULL;
|
||||
*new_class_data_len = 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
jint init_juiceloader(JNIEnv *env, jvmtiEnv *jvmti) {
|
||||
log_info("[*] libjuiceloader Version %d.%d Build %d", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR, PROJECT_BUILD_NUMBER);
|
||||
|
||||
initLogger();
|
||||
if (env == NULL) {
|
||||
log_error("env is NULL! env=%p", env);
|
||||
return JNI_ERR;
|
||||
}
|
||||
if (jvmti == NULL) {
|
||||
log_error("jvmti is NULL! jvmti=%p", jvmti);
|
||||
return JNI_ERR;
|
||||
}
|
||||
JuiceLoaderNative.jvmti = jvmti;
|
||||
log_debug("[JuiceLoader] JuiceLoaderNative addr = %p", &JuiceLoaderNative);
|
||||
log_debug("[JuiceLoader] JVMTI ptr = %p", JuiceLoaderNative.jvmti);
|
||||
|
||||
|
||||
// Dynamic register jni functions
|
||||
jclass clazz = (*env)->FindClass(env, "cn/xiaozhou233/juiceloader/JuiceLoaderNative");
|
||||
if (clazz == NULL) {
|
||||
log_error("Cannot find JuiceLoaderNative class!");
|
||||
return JNI_ERR;
|
||||
}
|
||||
JNINativeMethod methods[] = {
|
||||
// JuiceLoaderNative.init()
|
||||
{"init", "()Z", (void *)&loader_init},
|
||||
// JuiceLoaderNative.injectJar(String(jarPath));
|
||||
{"injectJar", "(Ljava/lang/String;)Z", (void *)&loader_injectJar},
|
||||
// JuiceLoaderNative.redefineClass(Class<?> clazz, byte[] classBytes, int length);
|
||||
{"redefineClass", "(Ljava/lang/Class;[BI)Z", (void *)&loader_redefineClass_clazz},
|
||||
// JuiceLoaderNative.redefineClassByName(String className, byte[] classBytes, int length);
|
||||
{"redefineClassByName", "(Ljava/lang/String;[BI)Z", (void *)&loader_redefineClass_className},
|
||||
// JuiceLoaderNative.getLoadedClasses();
|
||||
{"getLoadedClasses", "()[Ljava/lang/Class;", (void *)&loader_getLoadedClasses},
|
||||
// public static native byte[] getClassBytes(Class<?> clazz);
|
||||
// public static native byte[] getClassBytesByName(String className);
|
||||
{"getClassBytes", "(Ljava/lang/Class;)[B", (void *)&loader_getClassBytes},
|
||||
{ "getClassBytesByName", "(Ljava/lang/String;)[B", (void *)&loader_getClassBytesByName}
|
||||
};
|
||||
jint result = (*env)->RegisterNatives(env, clazz, methods, sizeof(methods) / sizeof(methods[0]));
|
||||
if (result != JNI_OK) {
|
||||
log_error("Cannot register JNI methods for JuiceLoaderNative class! [result=%d]", result);
|
||||
return JNI_ERR;
|
||||
}
|
||||
|
||||
// Application ability
|
||||
jvmtiCapabilities caps;
|
||||
memset(&caps, 0, sizeof(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;
|
||||
result = (*JuiceLoaderNative.jvmti)->AddCapabilities(JuiceLoaderNative.jvmti, &caps);
|
||||
if (result != JNI_OK) {
|
||||
log_error("Cannot add JVMTI capabilities! [result=%d]", result);
|
||||
return JNI_ERR;
|
||||
}
|
||||
|
||||
// Register callbacks
|
||||
jvmtiEventCallbacks callbacks;
|
||||
memset(&callbacks, 0, sizeof(callbacks));
|
||||
callbacks.ClassFileLoadHook = &ClassFileLoadHook;
|
||||
(*jvmti)->SetEventCallbacks(jvmti, &callbacks, sizeof(callbacks));
|
||||
|
||||
// Enable events
|
||||
(*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, JVMTI_EVENT_CLASS_FILE_LOAD_HOOK, NULL);
|
||||
|
||||
return JNI_OK;
|
||||
}
|
||||
|
||||
/// ============ JNI Function ============ ///
|
||||
|
||||
// JuiceLoaderNative.init()
|
||||
JNIEXPORT jboolean JNICALL loader_init(JNIEnv *env, jclass loader_class) {
|
||||
// Deprcated
|
||||
log_warn("JuiceLoaderNative.init() is deprecated, init will be done automatically.");
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
// JuiceLoaderNative.injectJar(String)
|
||||
JNIEXPORT jboolean JNICALL loader_injectJar(JNIEnv *env, jclass loader_class, jstring jarPath) {
|
||||
log_info("injectJar Invoked!");
|
||||
jboolean return_value = JNI_FALSE;
|
||||
|
||||
const char *pathStr = (*env)->GetStringUTFChars(env, jarPath, NULL);
|
||||
if (pathStr == NULL) {
|
||||
log_error("jar path is NULL!");
|
||||
return_value = JNI_FALSE;
|
||||
goto cleanup;
|
||||
}
|
||||
log_info("Injecting jar: %s", pathStr);
|
||||
|
||||
if (JuiceLoaderNative.jvmti == NULL) {
|
||||
log_error("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
||||
return_value = JNI_FALSE;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
jvmtiError result = (*JuiceLoaderNative.jvmti)->AddToSystemClassLoaderSearch(JuiceLoaderNative.jvmti, pathStr);
|
||||
if (result != JNI_OK) {
|
||||
log_error("Cannot inject jar [result=%d]", result);
|
||||
return_value = JNI_FALSE;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
return_value = JNI_TRUE;
|
||||
|
||||
cleanup:
|
||||
if (pathStr != NULL)
|
||||
(*env)->ReleaseStringUTFChars(env, jarPath, pathStr);
|
||||
return return_value;
|
||||
}
|
||||
|
||||
// JuiceLoaderNative.redefineClass(Class, byte[], int)
|
||||
JNIEXPORT jboolean JNICALL loader_redefineClass_clazz(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray classBytes, jint length) {
|
||||
log_info("redefineClass_clazz Invoked!");
|
||||
jboolean return_value = JNI_FALSE;
|
||||
jbyte* buf = NULL;
|
||||
|
||||
if (JuiceLoaderNative.jvmti == NULL) {
|
||||
log_error("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
||||
return_value = JNI_FALSE;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
log_info("Creating class definition...");
|
||||
log_trace("class: %p", clazz);
|
||||
log_trace("Class bytes length: %d", length);
|
||||
buf = (*env)->GetByteArrayElements(env, classBytes, NULL);
|
||||
if (buf == NULL) {
|
||||
log_error("Cannot get class bytes");
|
||||
return_value = JNI_FALSE;
|
||||
goto cleanup;
|
||||
}
|
||||
jvmtiClassDefinition defs[1];
|
||||
defs[0].klass = clazz;
|
||||
defs[0].class_byte_count = length;
|
||||
defs[0].class_bytes = (const unsigned char*) buf;
|
||||
|
||||
jvmtiError result = (*JuiceLoaderNative.jvmti)->RedefineClasses(JuiceLoaderNative.jvmti, 1, defs);
|
||||
if (result != JVMTI_ERROR_NONE) {
|
||||
log_error("Cannot redefine class [result=%d]", result);
|
||||
return_value = JNI_FALSE;
|
||||
goto cleanup;
|
||||
}
|
||||
return_value = JNI_TRUE;
|
||||
log_info("Class redefined successfully!");
|
||||
|
||||
cleanup:
|
||||
if (buf != NULL) {
|
||||
(*env)->ReleaseByteArrayElements(env, classBytes, buf, JNI_ABORT);
|
||||
}
|
||||
return return_value;
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL loader_redefineClass_className(JNIEnv *env, jclass loader_class, jstring className, jbyteArray classBytes, jint length) {
|
||||
log_info("redefineClass_className Invoked!");
|
||||
jboolean return_value = JNI_FALSE;
|
||||
|
||||
if (JuiceLoaderNative.jvmti == NULL) {
|
||||
log_error("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
||||
return_value = JNI_FALSE;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
const char* cname = (*env)->GetStringUTFChars(env, className, NULL);
|
||||
log_info("Finding class %s", cname);
|
||||
if (cname == NULL) {
|
||||
log_error("Class name is NULL!");
|
||||
return_value = JNI_FALSE;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
jclass clazz = (*env)->FindClass(env, cname);
|
||||
if (clazz == NULL) {
|
||||
log_error("Class not found! [ClassName=%s, clazz=%p]", cname, clazz);
|
||||
return_value = JNI_FALSE;
|
||||
goto cleanup;
|
||||
}
|
||||
|
||||
return_value = loader_redefineClass_clazz(env, loader_class, clazz, classBytes, length);
|
||||
|
||||
cleanup:
|
||||
if (cname != NULL) {
|
||||
(*env)->ReleaseStringUTFChars(env, className, cname);
|
||||
}
|
||||
|
||||
return return_value;
|
||||
}
|
||||
|
||||
JNIEXPORT jobjectArray JNICALL loader_getLoadedClasses(JNIEnv *env, jclass loader_class) {
|
||||
log_info("loader_getLoadedClasses invoked!");
|
||||
|
||||
if (JuiceLoaderNative.jvmti == NULL) {
|
||||
log_error("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// Debug
|
||||
jvmtiPhase phase; (*JuiceLoaderNative.jvmti)->GetPhase(JuiceLoaderNative.jvmti, &phase);
|
||||
log_debug("JVMTI Phase=%d [getLoadedClasses]", phase);
|
||||
|
||||
jint count = 0;
|
||||
jclass* classes = NULL;
|
||||
|
||||
jvmtiError result = (*JuiceLoaderNative.jvmti)->GetLoadedClasses(JuiceLoaderNative.jvmti, &count, &classes);
|
||||
if (result != JVMTI_ERROR_NONE || count == 0) {
|
||||
(*JuiceLoaderNative.jvmti)->Deallocate(JuiceLoaderNative.jvmti, (unsigned char*)classes);
|
||||
return (*env)->NewObjectArray(env, 0, (*env)->FindClass(env, "java/lang/Class"), NULL);
|
||||
}
|
||||
|
||||
jclass classClass = (*env)->FindClass(env, "java/lang/Class");
|
||||
jobjectArray classArray = (*env)->NewObjectArray(env, count, classClass, NULL);
|
||||
|
||||
for (int i = 0; i < count; i++) {
|
||||
(*env)->SetObjectArrayElement(env, classArray, i, classes[i]);
|
||||
}
|
||||
|
||||
if (classes != NULL) {
|
||||
(*JuiceLoaderNative.jvmti)->Deallocate(JuiceLoaderNative.jvmti, (unsigned char*)classes);
|
||||
}
|
||||
return classArray;
|
||||
}
|
||||
|
||||
JNIEXPORT jbyteArray JNICALL loader_getClassBytes(JNIEnv *env, jclass loader_class, jclass clazz) {
|
||||
log_info("getClassBytes Invoked!");
|
||||
|
||||
if (JuiceLoaderNative.jvmti == NULL) {
|
||||
log_error("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
char* className = get_class_name(env, clazz);
|
||||
if (className == NULL) {
|
||||
log_error("Failed to get class name!");
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// JVM 内部使用路径名(. 替换为 /)
|
||||
for (char* p = className; *p; p++) {
|
||||
if (*p == '.') *p = '/';
|
||||
}
|
||||
|
||||
g_bytecodes = NULL;
|
||||
g_bytecodes_classname = className;
|
||||
g_bytecodes_len = 0;
|
||||
|
||||
jclass classes[1] = { clazz };
|
||||
jvmtiError err = (*JuiceLoaderNative.jvmti)->RetransformClasses(JuiceLoaderNative.jvmti, 1, classes);
|
||||
if (err != JVMTI_ERROR_NONE) {
|
||||
log_error("RetransformClasses failed: %d", err);
|
||||
free((void*)className);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
if (g_bytecodes != NULL) {
|
||||
jbyteArray result = (*env)->NewByteArray(env, g_bytecodes_len);
|
||||
(*env)->SetByteArrayRegion(env, result, 0, g_bytecodes_len, (jbyte*)g_bytecodes);
|
||||
|
||||
free((void*)g_bytecodes);
|
||||
free((void*)className);
|
||||
g_bytecodes = NULL;
|
||||
g_bytecodes_classname = NULL;
|
||||
g_bytecodes_len = 0;
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
log_warn("No bytecode captured for class: %s", className);
|
||||
free((void*)className);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
JNIEXPORT jbyteArray JNICALL loader_getClassBytesByName(JNIEnv *env, jclass loader_class, jstring className) {
|
||||
log_info("getClassBytesByName Invoked!");
|
||||
|
||||
if (JuiceLoaderNative.jvmti == NULL) {
|
||||
log_error("JuiceLoaderNative.jvmti is NULL! [jvmti=%p]", JuiceLoaderNative.jvmti);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
const char* cname = (*env)->GetStringUTFChars(env, className, NULL);
|
||||
jclass clazz = (*env)->FindClass(env, cname);
|
||||
(*env)->ReleaseStringUTFChars(env, className, cname);
|
||||
|
||||
if (clazz == NULL) {
|
||||
log_error("Failed to find class %s", cname);
|
||||
return NULL;
|
||||
}
|
||||
|
||||
return loader_getClassBytes(env, loader_class, clazz);
|
||||
}
|
||||
@@ -1,377 +0,0 @@
|
||||
/*
|
||||
Author: xiaozhou233 (xiaozhou233@vip.qq.com)
|
||||
File: libagent.c
|
||||
Desc: Entry point for the agent
|
||||
*/
|
||||
|
||||
#include "ReflectiveLoader.h"
|
||||
#include "windows.h"
|
||||
#include "unistd.h"
|
||||
#include "stdio.h"
|
||||
#include "jni.h"
|
||||
#include "jvmti.h"
|
||||
#include "InjectParameters.h"
|
||||
#include "log.h"
|
||||
#include "GlobalUtils.h"
|
||||
#include "shlwapi.h"
|
||||
#include "tomlc17.h"
|
||||
#include "datautils.h"
|
||||
#include "juiceloader.h"
|
||||
|
||||
#define WIN_X64
|
||||
extern HINSTANCE hAppInstance;
|
||||
|
||||
InjectionInfoType InjectionInfo;
|
||||
|
||||
static void initLogger() {
|
||||
log_set_level(LOG_TRACE);
|
||||
log_is_log_time(false);
|
||||
log_set_name("libagent");
|
||||
log_info("Logger initialized.");
|
||||
}
|
||||
|
||||
DWORD WINAPI ThreadProc(LPVOID lpParam) {
|
||||
log_trace("New thread started.");
|
||||
|
||||
memset(&InjectionInfo, 0, sizeof(InjectionInfo));
|
||||
|
||||
/// ======== Check Environment ======== ///
|
||||
InjectParameters *param = (InjectParameters*)lpParam;
|
||||
if (!param) {
|
||||
log_error("ThreadProc got NULL param");
|
||||
return 1;
|
||||
}
|
||||
if (!param->ConfigDir || param->ConfigDir[0] == '\0') {
|
||||
log_error("ThreadProc got NULL or empty ConfigPath");
|
||||
return 1;
|
||||
}
|
||||
|
||||
char ConfigPath[INJECT_PATH_MAX];
|
||||
snprintf(ConfigPath, sizeof(ConfigPath), "%s\\AgentConfig.toml", param->ConfigDir);
|
||||
toml_result_t toml_result = toml_parse_file_ex(ConfigPath);
|
||||
if (!toml_result.ok) {
|
||||
log_error("ThreadProc failed to parse config file: %s", toml_result.errmsg);
|
||||
return 1;
|
||||
}
|
||||
if (!ReadInjectionInfo(toml_result, param)) {
|
||||
log_error("Failed to read injection info");
|
||||
return 1;
|
||||
}
|
||||
toml_free(toml_result);
|
||||
|
||||
log_trace("Checking bootstrap-api.jar");
|
||||
if (GetFileAttributesA(InjectionInfo.BootstrapAPIPath) == INVALID_FILE_ATTRIBUTES) {
|
||||
log_error("bootstrap-api.jar not found: %s", InjectionInfo.BootstrapAPIPath);
|
||||
// MessageBoxA(NULL, "bootstrap-api.jar not found", "Error", MB_OK);
|
||||
return 1;
|
||||
}
|
||||
|
||||
// Check JuiceLoader.jar
|
||||
|
||||
log_trace("Checking JuiceLoader.jar");
|
||||
if (GetFileAttributesA(InjectionInfo.JuiceLoaderJarPath) == INVALID_FILE_ATTRIBUTES) {
|
||||
log_error("JuiceLoader.jar not found: %s", InjectionInfo.JuiceLoaderJarPath);
|
||||
// MessageBoxA(NULL, "JuiceLoader.jar not found", "Error", MB_OK);
|
||||
return 1;
|
||||
}
|
||||
/// ======== Check Environment ======== ///
|
||||
|
||||
// Init vars
|
||||
jint result = JNI_ERR;
|
||||
JavaVM *jvm = NULL;
|
||||
JNIEnv *env = NULL;
|
||||
jvmtiEnv *jvmti = NULL;
|
||||
|
||||
result = GetCreatedJVM(&jvm);
|
||||
if (result != JNI_OK) {
|
||||
log_error("Failed to get JVM (%d)", result);
|
||||
MessageBoxA(NULL, "Failed to get JVM", "Error", MB_OK);
|
||||
return 1;
|
||||
}
|
||||
log_info("Got JVM");
|
||||
|
||||
|
||||
result = GetJNIEnv(jvm, &env);
|
||||
if (result != JNI_OK) {
|
||||
log_error("Failed to get JNIEnv (%d)", result);
|
||||
// MessageBoxA(NULL, "Failed to get JNIEnv", "Error", MB_OK);
|
||||
return 1;
|
||||
}
|
||||
log_info("Got JNIEnv");
|
||||
|
||||
// Debug: JVM version
|
||||
jint version = (*env)->GetVersion(env);
|
||||
log_trace("JVM version: 0x%x", version);
|
||||
|
||||
// Init and enable jvmti
|
||||
result = GetJVMTI(jvm, &jvmti);
|
||||
if (result != JNI_OK) {
|
||||
log_error("Failed to get JVMTI (%d)", result);
|
||||
// MessageBoxA(NULL, "Failed to get JVMTI", "Error", MB_OK);
|
||||
return 1;
|
||||
}
|
||||
log_info("Enabled jvmti");
|
||||
|
||||
// Inject jars
|
||||
log_info("injecting bootstrap-api jar...");
|
||||
(*jvmti)->AddToSystemClassLoaderSearch(jvmti, InjectionInfo.BootstrapAPIPath);
|
||||
log_info("injected bootstrap-api jar");
|
||||
|
||||
log_info("injecting loader jar...");
|
||||
(*jvmti)->AddToSystemClassLoaderSearch(jvmti, InjectionInfo.JuiceLoaderJarPath);
|
||||
log_info("injected loader jar");
|
||||
|
||||
// init juiceloader
|
||||
log_info("init juice loader...");
|
||||
init_juiceloader(env, jvmti);
|
||||
|
||||
initLogger();
|
||||
log_info("juice loader init done");
|
||||
|
||||
log_info("invoking loader init()...");
|
||||
log_info("============ Loader Info ============\n");
|
||||
jclass cls = (*env)->FindClass(env, "cn/xiaozhou233/juiceloader/JuiceLoader");
|
||||
if (cls == NULL) {
|
||||
log_error("FindClass JuiceLoader failed");
|
||||
return 1;
|
||||
}
|
||||
jmethodID mid = (*env)->GetStaticMethodID(env, cls, "init", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)V");
|
||||
if (mid == NULL) {
|
||||
log_error("GetStaticMethodID init failed");
|
||||
if ((*env)->ExceptionCheck(env)) {
|
||||
(*env)->ExceptionDescribe(env);
|
||||
(*env)->ExceptionClear(env);
|
||||
}
|
||||
|
||||
return 1;
|
||||
}
|
||||
(*env)->CallStaticVoidMethod(env, cls, mid,
|
||||
(*env)->NewStringUTF(env, InjectionInfo.EntryJarPath),
|
||||
(*env)->NewStringUTF(env, InjectionInfo.EntryClass),
|
||||
(*env)->NewStringUTF(env, InjectionInfo.EntryMethod));
|
||||
log_info("============ Loader Info =============\n");
|
||||
log_info("invoked. ");
|
||||
log_info("done. cleaning up...");
|
||||
|
||||
// :(
|
||||
// (*jvm)->DetachCurrentThread(jvm);
|
||||
|
||||
free(param);
|
||||
log_info("exit.");
|
||||
return 0;
|
||||
}
|
||||
|
||||
/// =========================================================== ///
|
||||
/// Function: DllMain
|
||||
/// Description: DLL Injection Entry Point
|
||||
/// Inject Method: A) ReflectiveDLLInjection B) LoadLibraryA+CreateRemoteThread
|
||||
/// =========================================================== ///
|
||||
BOOL WINAPI DllMain(HINSTANCE hinstDLL, DWORD dwReason, LPVOID lpReserved){
|
||||
BOOL bReturnValue = TRUE;
|
||||
switch (dwReason){
|
||||
case DLL_QUERY_HMODULE:
|
||||
if (lpReserved != NULL)
|
||||
*(HMODULE *)lpReserved = hAppInstance;
|
||||
break;
|
||||
|
||||
case DLL_PROCESS_ATTACH:
|
||||
hAppInstance = hinstDLL;
|
||||
|
||||
// Initialize log
|
||||
initLogger();
|
||||
log_info("DLL_PROCESS_ATTACH");
|
||||
log_info("[*] JuiceAgent Version %d.%d Build %d", PROJECT_VERSION_MAJOR, PROJECT_VERSION_MINOR, PROJECT_BUILD_NUMBER);
|
||||
|
||||
DisableThreadLibraryCalls(hinstDLL);
|
||||
|
||||
// JVM Options Inject Method Detection
|
||||
// TODO: Remove Duplicated Code: GetCreatedJVM/GetEnv and var jvm/env (Duplicated at: ThreadProc)
|
||||
JavaVM *jvm = NULL;
|
||||
JNIEnv *env = NULL;
|
||||
jint result = GetCreatedJVM(&jvm);
|
||||
// Check if JVM is created
|
||||
if (result != JNI_OK || jvm == NULL) {
|
||||
log_error("Failed to get JVM (%d) [JVM: %p]", result, jvm);
|
||||
MessageBoxA(NULL, "Failed to get JVM [GetCreatedJVM Faliled or JVM is NULL]\nCheck console for more info.", "Error", MB_OK);
|
||||
return 1;
|
||||
}
|
||||
log_info("DllMain GetCreatedJVM OK. Checking if JVM is inited...");
|
||||
// Check if JVM is inited
|
||||
// JNI_EDETACHED: jvm not initialized, means Agent loaded before JVM inited (jvm options: -agentpath)
|
||||
// Will exit DllMain and jvm will invoke Agent_OnLoad
|
||||
if (GetJNIEnv(jvm, &env) == JNI_EDETACHED) {
|
||||
log_warn("Inject Method JVM Options Detected! Exiting...");
|
||||
log_trace("DllMain(DLL_PROCESS_ATTACH) Exiting...");
|
||||
log_info("Agent Will be injected by the Inject Methood JVM Options.\n");
|
||||
break;
|
||||
}
|
||||
|
||||
// Allocate memory for local param
|
||||
InjectParameters *localParm = (InjectParameters*)malloc(sizeof(InjectParameters));
|
||||
if (localParm == NULL) {
|
||||
log_error("malloc failed for InjectParameters");
|
||||
break;
|
||||
}
|
||||
memset(localParm, 0, sizeof(InjectParameters));
|
||||
|
||||
// Check if lpReserved is not NULL
|
||||
if (lpReserved != NULL) {
|
||||
// Copy remote param to local param
|
||||
InjectParameters *remoteParm = (InjectParameters*)lpReserved;
|
||||
|
||||
safe_copy(localParm->ConfigDir, remoteParm->ConfigDir, sizeof(localParm->ConfigDir));
|
||||
} else {
|
||||
log_info("RemoteParm is NULL!");
|
||||
|
||||
char DllDir[INJECT_PATH_MAX] = {0};
|
||||
|
||||
if (GetModuleFileNameA(hinstDLL, DllDir, INJECT_PATH_MAX) == 0) {
|
||||
// Failed to get module file name
|
||||
DWORD err = GetLastError();
|
||||
if (err == ERROR_MOD_NOT_FOUND) {
|
||||
// Reflective detected, lpReserved must be set.
|
||||
log_fatal("Reflective load detected! Please set ConfigDir manually! Exit.");
|
||||
} else {
|
||||
log_error("Normal Inject: GetModuleFileNameA failed! Error: %lu", err);
|
||||
}
|
||||
break;
|
||||
} else {
|
||||
// Normal Inject(e.g. CreateRemoteThread+LoadLibraryA), lpReserved can be NULL.
|
||||
PathRemoveFileSpecA(DllDir);
|
||||
log_info("GetModuleFileNameA: %s", DllDir);
|
||||
safe_copy(localParm->ConfigDir, DllDir, INJECT_PATH_MAX);
|
||||
}
|
||||
}
|
||||
|
||||
log_info("ConfigDir: %s", localParm->ConfigDir);
|
||||
|
||||
HANDLE hThread = CreateThread(NULL, 0, ThreadProc, localParm, 0, NULL);
|
||||
if (hThread) {
|
||||
CloseHandle(hThread);
|
||||
} else {
|
||||
log_error("CreateThread failed %lu", GetLastError());
|
||||
free(localParm);
|
||||
}
|
||||
|
||||
break;
|
||||
case DLL_PROCESS_DETACH:
|
||||
log_info("DLL_PROCESS_DETACH");
|
||||
break;
|
||||
case DLL_THREAD_ATTACH:
|
||||
case DLL_THREAD_DETACH:
|
||||
break;
|
||||
}
|
||||
return bReturnValue;
|
||||
}
|
||||
|
||||
/// =========================================================== ///
|
||||
/// Inject Method: JVM Options -agentpath
|
||||
|
||||
/// =========================================================== ///
|
||||
/// Function: vm_init
|
||||
/// Description: Called when the JVM is fully initialized. This is a callback function.
|
||||
/// =========================================================== ///
|
||||
static char *agent_options = NULL;
|
||||
static void JNICALL vm_init(jvmtiEnv *jvmti, JNIEnv *env, jthread thread) {
|
||||
log_info("vminit: VM fully initialized!");
|
||||
log_info("Use options: %s", agent_options);
|
||||
|
||||
log_info("JNIEnv: %p", env);
|
||||
log_info("jvmtiEnv: %p", jvmti);
|
||||
|
||||
log_info("Version: %d", (*env)->GetVersion(env));
|
||||
|
||||
// TODO: Remove Duplicated Code
|
||||
|
||||
// Check if agent_options is null
|
||||
if (agent_options == NULL) {
|
||||
// Use DLL path as default
|
||||
log_info("agent_options is null, use DLL path as default");
|
||||
char DllDir[INJECT_PATH_MAX] = {0};
|
||||
|
||||
if (GetModuleFileNameA(hAppInstance, DllDir, INJECT_PATH_MAX) == 0) {
|
||||
// Failed to get module file name
|
||||
DWORD err = GetLastError();
|
||||
if (err == ERROR_MOD_NOT_FOUND) {
|
||||
// Reflective detected, lpReserved must be set.
|
||||
log_fatal("Reflective load detected! Please set ConfigDir manually! Exit.");
|
||||
} else {
|
||||
log_error("Normal Inject: GetModuleFileNameA failed! Error: %lu", err);
|
||||
}
|
||||
return;
|
||||
} else {
|
||||
// Normal Inject(e.g. CreateRemoteThread+LoadLibraryA), lpReserved can be NULL.
|
||||
PathRemoveFileSpecA(DllDir);
|
||||
log_info("GetModuleFileNameA: %s", DllDir);
|
||||
agent_options = DllDir;
|
||||
}
|
||||
}
|
||||
log_trace("agent_options: %s", agent_options);
|
||||
|
||||
// Allocate memory for InjectParameters
|
||||
InjectParameters *localParm = (InjectParameters*)malloc(sizeof(InjectParameters));
|
||||
if (localParm == NULL) {
|
||||
log_error("malloc failed for InjectParameters");
|
||||
return;
|
||||
}
|
||||
memset(localParm, 0, sizeof(InjectParameters));
|
||||
|
||||
// safe copy
|
||||
safe_copy(localParm->ConfigDir, agent_options, INJECT_PATH_MAX);
|
||||
|
||||
// Start new thread
|
||||
HANDLE hThread = CreateThread(NULL, 0, ThreadProc, localParm, 0, NULL);
|
||||
if (hThread) {
|
||||
CloseHandle(hThread);
|
||||
} else {
|
||||
log_error("CreateThread failed %lu", GetLastError());
|
||||
free(localParm);
|
||||
}
|
||||
}
|
||||
|
||||
/// =========================================================== ///
|
||||
/// Function: Agent_OnLoad
|
||||
/// Description: Java Agent OnLoad
|
||||
/// Inject Method: JVM Options A) -agentpath:<path-to-agent>.dll=<param-config-dir>
|
||||
/// Example: java -agentpath:./libagent.dll=./config -jar myapp.jar
|
||||
/// =========================================================== ///
|
||||
|
||||
// Notice: This function is called by the JVM when the agent is loaded.
|
||||
// Warning: JVM not initialized yet when this function is called.
|
||||
JNIEXPORT jint JNICALL Agent_OnLoad(JavaVM *vm, char *options, void *reserved) {
|
||||
initLogger();
|
||||
log_info("Agent_OnLoad");
|
||||
log_info("Agent_OnLoad: options: %s", options);
|
||||
|
||||
// save options
|
||||
if (options != NULL) {
|
||||
agent_options = strdup(options);
|
||||
}
|
||||
|
||||
jvmtiEnv *jvmti;
|
||||
(*vm)->GetEnv(vm, (void **)&jvmti, JVMTI_VERSION_1_2);
|
||||
|
||||
// callbacks
|
||||
jvmtiEventCallbacks callbacks = {0};
|
||||
callbacks.VMInit = &vm_init;
|
||||
(*jvmti)->SetEventCallbacks(jvmti, &callbacks, sizeof(callbacks));
|
||||
|
||||
// enable events
|
||||
(*jvmti)->SetEventNotificationMode(jvmti, JVMTI_ENABLE, JVMTI_EVENT_VM_INIT, NULL);
|
||||
|
||||
log_info("Agent_OnLoad: Done, waiting for JVM Init event.");
|
||||
return JNI_OK;
|
||||
}
|
||||
|
||||
/// Inject Method: JVM Options -agentpath
|
||||
/// =========================================================== ///
|
||||
|
||||
// Notice: This function is useless but required by the JVM (in Windows).
|
||||
JNIEXPORT jint JNICALL Agent_OnAttach (JavaVM* vm, char *options, void *reserved) {
|
||||
log_info("Agent_OnAttach");
|
||||
#ifdef WIN_X64
|
||||
log_warn("Agent_OnAttach: Windows will invoke DllMain, Exiting Agent_OnAttach.");
|
||||
log_info("Agent_OnAttach will exit in Windows, Loading will be done in DllMain.\n");
|
||||
#endif
|
||||
return JNI_OK;
|
||||
}
|
||||
@@ -1,89 +0,0 @@
|
||||
/*
|
||||
Author: xiaozhou233 (xiaozhou233@vip.qq.com)
|
||||
File: datautils.c
|
||||
Desc: data utils
|
||||
*/
|
||||
|
||||
|
||||
#include "datautils.h"
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include "tomlc17.h"
|
||||
|
||||
void safe_copy(char *dest, const char *src, size_t dest_size) {
|
||||
if (!dest || dest_size == 0) return;
|
||||
strncpy(dest, src, dest_size - 1);
|
||||
dest[dest_size - 1] = '\0';
|
||||
}
|
||||
|
||||
bool ReadInjectionInfo(toml_result_t result, InjectParameters* params) {
|
||||
toml_datum_t InjectionTree = toml_seek(result.toptab, "Injection");
|
||||
|
||||
// ======= BootstrapAPIPath =======
|
||||
toml_datum_t BootstrapAPIPath = toml_seek(InjectionTree, "BootstrapAPIPath");
|
||||
char BootstrapAPIPathStr[INJECT_PATH_MAX];
|
||||
if (BootstrapAPIPath.type != TOML_STRING) {
|
||||
log_error("BootstrapAPIPath is not a string.");
|
||||
return false;
|
||||
}
|
||||
if (BootstrapAPIPath.u.s == NULL || strlen(BootstrapAPIPath.u.s) == 0) {
|
||||
sprintf(BootstrapAPIPathStr, "%s\\bootstrap-api.jar", params->ConfigDir);
|
||||
} else {
|
||||
sprintf(BootstrapAPIPathStr, "%s", BootstrapAPIPath.u.s);
|
||||
}
|
||||
safe_copy(InjectionInfo.BootstrapAPIPath, BootstrapAPIPathStr, INJECT_PATH_MAX);
|
||||
// ======= BootstrapAPIPath =======
|
||||
|
||||
// ======= JuiceLoaderJarPath =======
|
||||
toml_datum_t JuiceLoaderJarPath = toml_seek(InjectionTree, "JuiceLoaderJarPath");
|
||||
char JuiceLoaderJarPathStr[INJECT_PATH_MAX];
|
||||
if (JuiceLoaderJarPath.type != TOML_STRING) {
|
||||
log_error("JuiceLoaderJarPath is not a string.");
|
||||
return false;
|
||||
}
|
||||
if (JuiceLoaderJarPath.u.s == NULL || strlen(JuiceLoaderJarPath.u.s) == 0) {
|
||||
sprintf(JuiceLoaderJarPathStr, "%s\\JuiceLoader.jar", params->ConfigDir);
|
||||
} else {
|
||||
sprintf(JuiceLoaderJarPathStr, "%s", JuiceLoaderJarPath.u.s);
|
||||
}
|
||||
safe_copy(InjectionInfo.JuiceLoaderJarPath, JuiceLoaderJarPathStr, INJECT_PATH_MAX);
|
||||
// ======= JuiceLoaderJarPath =======
|
||||
|
||||
// ======= Entry =======
|
||||
toml_datum_t EntryJarPath = toml_seek(InjectionTree, "EntryJarPath");
|
||||
char EntryJarPathStr[INJECT_PATH_MAX];
|
||||
if (EntryJarPath.type != TOML_STRING) {
|
||||
log_error("EntryJarPath is not a string.");
|
||||
return false;
|
||||
}
|
||||
if (EntryJarPath.u.s == NULL || strlen(EntryJarPath.u.s) == 0) {
|
||||
sprintf(EntryJarPathStr, "%s\\entry.jar", params->ConfigDir);
|
||||
} else {
|
||||
sprintf(EntryJarPathStr, "%s", EntryJarPath.u.s);
|
||||
}
|
||||
safe_copy(InjectionInfo.EntryJarPath, EntryJarPathStr, INJECT_PATH_MAX);
|
||||
|
||||
toml_datum_t EntryClass = toml_seek(InjectionTree, "EntryClass");
|
||||
if (EntryClass.type != TOML_STRING) {
|
||||
log_error("EntryClass is not a string.");
|
||||
return false;
|
||||
}
|
||||
if (EntryClass.u.s == NULL || strlen(EntryClass.u.s) == 0) {
|
||||
safe_copy(InjectionInfo.EntryClass, "cn.xiaozhou233.juiceloader.entry.Entry", INJECT_PATH_MAX);
|
||||
} else {
|
||||
safe_copy(InjectionInfo.EntryClass, EntryClass.u.s, INJECT_PATH_MAX);
|
||||
}
|
||||
|
||||
toml_datum_t EntryMethod = toml_seek(InjectionTree, "EntryMethod");
|
||||
if (EntryMethod.type != TOML_STRING) {
|
||||
log_error("EntryMethod is not a string.");
|
||||
return false;
|
||||
}
|
||||
if (EntryMethod.u.s == NULL || strlen(EntryMethod.u.s) == 0) {
|
||||
safe_copy(InjectionInfo.EntryMethod, "start", INJECT_PATH_MAX);
|
||||
} else {
|
||||
safe_copy(InjectionInfo.EntryMethod, EntryMethod.u.s, INJECT_PATH_MAX);
|
||||
}
|
||||
// ======= Entry =======
|
||||
return true;
|
||||
}
|
||||
@@ -1,16 +0,0 @@
|
||||
#include "javautils.h"
|
||||
#include <jni.h>
|
||||
#include <jvmti.h>
|
||||
#include <string.h>
|
||||
|
||||
char* get_class_name(JNIEnv* env, jclass clazz) {
|
||||
jclass clsClass = (*env)->FindClass(env, "java/lang/Class");
|
||||
jmethodID mid_getName = (*env)->GetMethodID(env, clsClass, "getName", "()Ljava/lang/String;");
|
||||
jstring nameStr = (jstring)(*env)->CallObjectMethod(env, clazz, mid_getName);
|
||||
|
||||
const char* temp = (*env)->GetStringUTFChars(env, nameStr, NULL);
|
||||
char* result = strdup(temp);
|
||||
(*env)->ReleaseStringUTFChars(env, nameStr, temp);
|
||||
(*env)->DeleteLocalRef(env, nameStr);
|
||||
return result;
|
||||
}
|
||||
@@ -1 +0,0 @@
|
||||
# src/injector/CMakeLists.txt
|
||||
@@ -1,37 +0,0 @@
|
||||
/* DO NOT EDIT THIS FILE - it is machine generated */
|
||||
#include <jni.h>
|
||||
/* Header for class cn_xiaozhou233_juiceagent_injector_InjectorNative */
|
||||
|
||||
#ifndef _Included_cn_xiaozhou233_juiceagent_injector_InjectorNative
|
||||
#define _Included_cn_xiaozhou233_juiceagent_injector_InjectorNative
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceagent_injector_InjectorNative
|
||||
* Method: inject
|
||||
* Signature: (ILjava/lang/String;)Z
|
||||
*/
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorNative_inject__ILjava_lang_String_2
|
||||
(JNIEnv *, jobject, jint, jstring);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceagent_injector_InjectorNative
|
||||
* Method: inject
|
||||
* Signature: (ILjava/lang/String;Ljava/lang/String;)Z
|
||||
*/
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorNative_inject__ILjava_lang_String_2Ljava_lang_String_2
|
||||
(JNIEnv *, jobject, jint, jstring, jstring);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceagent_injector_InjectorNative
|
||||
* Method: findWindowsByTitle
|
||||
* Signature: (Ljava/lang/String;)[Lcn/xiaozhou233/juiceagent/injector/InjectorNative/WindowInfo;
|
||||
*/
|
||||
JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceagent_injector_InjectorNative_findWindowsByTitle
|
||||
(JNIEnv *, jclass, jstring);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
@@ -1,10 +0,0 @@
|
||||
#ifndef INJECTOR_UTILS_H
|
||||
#define INJECTOR_UTILS_H
|
||||
|
||||
#include "windows.h"
|
||||
|
||||
WORD get_pe_machine(LPVOID, DWORD);
|
||||
BOOL has_reflective_loader_export(LPVOID, DWORD);
|
||||
const char* machine_to_str(WORD);
|
||||
|
||||
#endif
|
||||
@@ -1,104 +0,0 @@
|
||||
#include "InjectorUtils.h"
|
||||
|
||||
/* Helpers: parse PE header to get Machine and check for ReflectiveLoader export */
|
||||
|
||||
/* return IMAGE_FILE_MACHINE_* value or 0 on error */
|
||||
WORD get_pe_machine(LPVOID buffer, DWORD length) {
|
||||
if (!buffer || length < sizeof(IMAGE_DOS_HEADER)) return 0;
|
||||
PIMAGE_DOS_HEADER dos = (PIMAGE_DOS_HEADER)buffer;
|
||||
if (dos->e_magic != IMAGE_DOS_SIGNATURE) return 0;
|
||||
if ((DWORD)dos->e_lfanew + sizeof(IMAGE_NT_HEADERS) > length) return 0;
|
||||
PIMAGE_NT_HEADERS nt = (PIMAGE_NT_HEADERS)((BYTE*)buffer + dos->e_lfanew);
|
||||
if (nt->Signature != IMAGE_NT_SIGNATURE) return 0;
|
||||
return nt->FileHeader.Machine;
|
||||
}
|
||||
|
||||
/* return TRUE if export table contains "ReflectiveLoader" */
|
||||
BOOL has_reflective_loader_export(LPVOID buffer, DWORD length) {
|
||||
if (!buffer || length < sizeof(IMAGE_DOS_HEADER)) return FALSE;
|
||||
PIMAGE_DOS_HEADER dos = (PIMAGE_DOS_HEADER)buffer;
|
||||
if (dos->e_magic != IMAGE_DOS_SIGNATURE) return FALSE;
|
||||
PIMAGE_NT_HEADERS nt = (PIMAGE_NT_HEADERS)((BYTE*)buffer + dos->e_lfanew);
|
||||
if (nt->Signature != IMAGE_NT_SIGNATURE) return FALSE;
|
||||
|
||||
DWORD exportRVA = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].VirtualAddress;
|
||||
DWORD exportSize = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_EXPORT].Size;
|
||||
if (!exportRVA || exportSize == 0) return FALSE;
|
||||
|
||||
// Need to convert RVA -> raw offset: iterate sections
|
||||
PIMAGE_SECTION_HEADER section = IMAGE_FIRST_SECTION(nt);
|
||||
WORD numberOfSections = nt->FileHeader.NumberOfSections;
|
||||
DWORD exportOffset = 0;
|
||||
for (WORD i = 0; i < numberOfSections; ++i) {
|
||||
DWORD va = section[i].VirtualAddress;
|
||||
DWORD vs = section[i].Misc.VirtualSize;
|
||||
DWORD ptr = section[i].PointerToRawData;
|
||||
DWORD size = section[i].SizeOfRawData;
|
||||
if (exportRVA >= va && exportRVA < va + vs) {
|
||||
exportOffset = ptr + (exportRVA - va);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!exportOffset) return FALSE;
|
||||
if ((DWORD)exportOffset + sizeof(IMAGE_EXPORT_DIRECTORY) > length) return FALSE;
|
||||
|
||||
PIMAGE_EXPORT_DIRECTORY exp = (PIMAGE_EXPORT_DIRECTORY)((BYTE*)buffer + exportOffset);
|
||||
if (exp->NumberOfNames == 0) return FALSE;
|
||||
|
||||
// locate arrays
|
||||
DWORD addrOfNamesRVA = exp->AddressOfNames;
|
||||
DWORD addrOfNameOrdinalsRVA = exp->AddressOfNameOrdinals;
|
||||
if (!addrOfNamesRVA || !addrOfNameOrdinalsRVA) return FALSE;
|
||||
|
||||
// find raw offsets for these arrays
|
||||
DWORD namesOffset = 0;
|
||||
DWORD ordinalsOffset = 0;
|
||||
for (WORD i = 0; i < numberOfSections; ++i) {
|
||||
DWORD va = section[i].VirtualAddress;
|
||||
DWORD vs = section[i].Misc.VirtualSize;
|
||||
DWORD ptr = section[i].PointerToRawData;
|
||||
if (addrOfNamesRVA >= va && addrOfNamesRVA < va + vs) {
|
||||
namesOffset = ptr + (addrOfNamesRVA - va);
|
||||
}
|
||||
if (addrOfNameOrdinalsRVA >= va && addrOfNameOrdinalsRVA < va + vs) {
|
||||
ordinalsOffset = ptr + (addrOfNameOrdinalsRVA - va);
|
||||
}
|
||||
}
|
||||
if (!namesOffset || !ordinalsOffset) return FALSE;
|
||||
if ((DWORD)namesOffset + exp->NumberOfNames * sizeof(DWORD) > length) return FALSE;
|
||||
if ((DWORD)ordinalsOffset + exp->NumberOfNames * sizeof(WORD) > length) return FALSE;
|
||||
|
||||
// iterate names
|
||||
for (DWORD i = 0; i < exp->NumberOfNames; ++i) {
|
||||
DWORD nameRVA = *(DWORD*)((BYTE*)buffer + namesOffset + i * sizeof(DWORD));
|
||||
// convert nameRVA to raw offset
|
||||
DWORD nameOffset = 0;
|
||||
for (WORD s = 0; s < numberOfSections; ++s) {
|
||||
DWORD va = section[s].VirtualAddress;
|
||||
DWORD vs = section[s].Misc.VirtualSize;
|
||||
DWORD ptr = section[s].PointerToRawData;
|
||||
if (nameRVA >= va && nameRVA < va + vs) {
|
||||
nameOffset = ptr + (nameRVA - va);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (!nameOffset) continue;
|
||||
if ((DWORD)nameOffset >= length) continue;
|
||||
char *name = (char*)((BYTE*)buffer + nameOffset);
|
||||
// safe compare - ensure string is within buffer
|
||||
size_t maxlen = length - nameOffset;
|
||||
if (strncasecmp(name, "ReflectiveLoader", maxlen) == 0) return TRUE;
|
||||
}
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
/* Pretty-print machine */
|
||||
const char* machine_to_str(WORD machine) {
|
||||
switch(machine) {
|
||||
case IMAGE_FILE_MACHINE_I386: return "x86 (IMAGE_FILE_MACHINE_I386)";
|
||||
case IMAGE_FILE_MACHINE_AMD64: return "x64 (IMAGE_FILE_MACHINE_AMD64)";
|
||||
case IMAGE_FILE_MACHINE_ARM: return "ARM";
|
||||
case IMAGE_FILE_MACHINE_ARM64: return "ARM64";
|
||||
default: return "Unknown";
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
file(
|
||||
GLOB_RECURSE
|
||||
agent_sources
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/*.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/*.c
|
||||
)
|
||||
|
||||
add_library(agent SHARED ${agent_sources})
|
||||
|
||||
target_include_directories(agent PRIVATE
|
||||
${CMAKE_SOURCE_DIR}/includes
|
||||
${CMAKE_SOURCE_DIR}/includes/jvm
|
||||
${CMAKE_SOURCE_DIR}/includes/jvm/win32
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/includes
|
||||
)
|
||||
|
||||
target_link_libraries(agent PRIVATE
|
||||
ReflectiveDLLInjection
|
||||
jvm
|
||||
)
|
||||
@@ -0,0 +1,33 @@
|
||||
#include <jni_impl.hpp>
|
||||
#include <event/event_type.hpp>
|
||||
|
||||
void JNICALL ClassFileLoadHook(
|
||||
jvmtiEnv* jvmti_env,
|
||||
JNIEnv* jni_env,
|
||||
jclass class_being_redefined,
|
||||
jobject loader,
|
||||
const char* name,
|
||||
jobject protection_domain,
|
||||
jint class_data_len,
|
||||
const unsigned char* classbytes,
|
||||
jint* new_class_data_len,
|
||||
unsigned char** new_classbytes) {
|
||||
if (!name) {
|
||||
PLOGW << "name is null";
|
||||
return;
|
||||
}
|
||||
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
agent.get_eventbus().post(EventClassFileLoadHook{
|
||||
.jvmti_env = jvmti_env,
|
||||
.jni_env = jni_env,
|
||||
.class_being_redefined = class_being_redefined,
|
||||
.loader = loader,
|
||||
.name = name,
|
||||
.protection_domain = protection_domain,
|
||||
.class_data_len = class_data_len,
|
||||
.classbytes = classbytes,
|
||||
.new_class_data_len = new_class_data_len,
|
||||
.new_classbytes = new_classbytes
|
||||
});
|
||||
}
|
||||
@@ -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() << ")";
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
#include <global.hpp>
|
||||
|
||||
std::unordered_set<std::string> classToCapture;
|
||||
std::unordered_map<std::string, ClassFileData> classFileDataMap;
|
||||
std::mutex classDataMutex;
|
||||
|
||||
std::unordered_map<std::string, std::vector<unsigned char>> pendingRetransform;
|
||||
std::mutex pendingRetransformMutex;
|
||||
@@ -0,0 +1,33 @@
|
||||
#include <jni_impl.hpp>
|
||||
#include <libagent.hpp>
|
||||
|
||||
// This function is called by Java to initialize the agent.
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init
|
||||
(JNIEnv *env, jclass loader_class) {
|
||||
InitLogger();
|
||||
|
||||
PLOGI << "Initializing JuiceAgent...";
|
||||
|
||||
JavaVM* jvm = nullptr;
|
||||
jvmtiEnv* jvmti = nullptr;
|
||||
|
||||
// Get Java VM
|
||||
env->GetJavaVM(&jvm);
|
||||
if (jvm == nullptr) {
|
||||
PLOGE << "Failed to get JavaVM instance";
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
// Get JVMTI
|
||||
jvmtiError err = static_cast<jvmtiError>(jvm->GetEnv(reinterpret_cast<void**>(&jvmti), JVMTI_VERSION_1_2));
|
||||
if (err != JVMTI_ERROR_NONE || jvmti == nullptr) {
|
||||
PLOGE << "Failed to get JVMTI environment, error: " << err;
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
// Invoke EntryPoint
|
||||
JuiceAgent::Agent& agent = JuiceAgent::Agent::instance();
|
||||
agent.init(jvm, env, jvmti);
|
||||
|
||||
return JNI_TRUE;
|
||||
}
|
||||
@@ -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);
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
/* DO NOT EDIT THIS FILE - it is machine generated */
|
||||
#include <jni.h>
|
||||
/* Header for class cn_xiaozhou233_juiceagent_api_JuiceAgent */
|
||||
|
||||
#ifndef _Included_cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||
#define _Included_cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||
* Method: init
|
||||
* Signature: ()Z
|
||||
*/
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_init
|
||||
(JNIEnv *, jclass);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||
* Method: addToBootstrapClassLoaderSearch
|
||||
* Signature: (Ljava/lang/String;)Z
|
||||
*/
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToBootstrapClassLoaderSearch
|
||||
(JNIEnv *, jclass, jstring);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||
* Method: addToSystemClassLoaderSearch
|
||||
* Signature: (Ljava/lang/String;)Z
|
||||
*/
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToSystemClassLoaderSearch
|
||||
(JNIEnv *, jclass, jstring);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||
* Method: addToClassLoader
|
||||
* Signature: (Ljava/lang/String;Ljava/lang/ClassLoader;)Z
|
||||
*/
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToClassLoader
|
||||
(JNIEnv *, jclass, jstring, jobject);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||
* Method: defineClass
|
||||
* Signature: (Ljava/lang/ClassLoader;[B)Ljava/lang/Class;
|
||||
*/
|
||||
JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_defineClass
|
||||
(JNIEnv *, jclass, jobject, jbyteArray);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||
* Method: redefineClass
|
||||
* Signature: (Ljava/lang/Class;[BI)Z
|
||||
*/
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClass
|
||||
(JNIEnv *, jclass, jclass, jbyteArray, jint);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||
* Method: redefineClassByName
|
||||
* Signature: (Ljava/lang/String;[BI)Z
|
||||
*/
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClassByName
|
||||
(JNIEnv *, jclass, jstring, jbyteArray, jint);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||
* Method: retransformClass
|
||||
* Signature: (Ljava/lang/Class;[BI)Z
|
||||
*/
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClass
|
||||
(JNIEnv *, jclass, jclass, jbyteArray, jint);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||
* Method: retransformClassByName
|
||||
* Signature: (Ljava/lang/String;[BI)Z
|
||||
*/
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClassByName
|
||||
(JNIEnv *, jclass, jstring, jbyteArray, jint);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||
* Method: getLoadedClasses
|
||||
* Signature: ()[Ljava/lang/Class;
|
||||
*/
|
||||
JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getLoadedClasses
|
||||
(JNIEnv *, jclass);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||
* Method: getClassByName
|
||||
* Signature: (Ljava/lang/String;)Ljava/lang/Class;
|
||||
*/
|
||||
JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassByName
|
||||
(JNIEnv *, jclass, jstring);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||
* Method: getClassBytes
|
||||
* Signature: (Ljava/lang/Class;)[B
|
||||
*/
|
||||
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytes
|
||||
(JNIEnv *, jclass, jclass);
|
||||
|
||||
/*
|
||||
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
||||
* Method: getClassBytesByName
|
||||
* Signature: (Ljava/lang/String;)[B
|
||||
*/
|
||||
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytesByName
|
||||
(JNIEnv *, jclass, jstring);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
@@ -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;
|
||||
};
|
||||
@@ -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);
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,38 @@
|
||||
#pragma once
|
||||
|
||||
#include <jni.h>
|
||||
#include <jvmti.h>
|
||||
#include <vector>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <unordered_set>
|
||||
#include <mutex>
|
||||
|
||||
// Data Structures
|
||||
struct ClassRetransformRequest {
|
||||
std::string classname;
|
||||
std::vector<unsigned char> bytecode;
|
||||
};
|
||||
struct ClassFileData {
|
||||
std::string classname;
|
||||
std::vector<unsigned char> bytecode;
|
||||
|
||||
// ======== Global references to prevent GC ========
|
||||
// Remember to release these references when they are no longer needed, otherwise it will cause memory leaks
|
||||
jclass clazz;
|
||||
jobject classloader;
|
||||
jobject protection_domain;
|
||||
|
||||
};
|
||||
|
||||
// Set of target class internal names to capture (e.g. java/lang/String)
|
||||
extern std::unordered_set<std::string> classToCapture;
|
||||
|
||||
// Cache of captured class bytecode, keyed by internal class name
|
||||
extern std::unordered_map<std::string, ClassFileData> classFileDataMap;
|
||||
|
||||
// Mutex protecting access to classToCapture and classFileDataMap (thread-safe for JVMTI callbacks)
|
||||
extern std::mutex classDataMutex;
|
||||
|
||||
extern std::unordered_map<std::string, std::vector<unsigned char>> pendingRetransform;
|
||||
extern std::mutex pendingRetransformMutex;
|
||||
@@ -0,0 +1,26 @@
|
||||
#pragma once
|
||||
|
||||
#include <jni.h>
|
||||
#include <jvmti.h>
|
||||
#include <JuiceAgent/Logger.hpp>
|
||||
#include <libagent.hpp>
|
||||
#include <utils.hpp>
|
||||
#include <global.hpp>
|
||||
#include <algorithm>
|
||||
|
||||
// Generated by JuiceAgent-API
|
||||
#include <cn_xiaozhou233_juiceagent_api_JuiceAgent.h>
|
||||
|
||||
// Event callbacks
|
||||
// See https://docs.oracle.com/javase/8/docs/platform/jvmti/jvmti.html#ClassFileLoadHook
|
||||
void JNICALL ClassFileLoadHook(
|
||||
jvmtiEnv* jvmti_env,
|
||||
JNIEnv* jni_env,
|
||||
jclass class_being_redefined,
|
||||
jobject loader,
|
||||
const char* name,
|
||||
jobject protection_domain,
|
||||
jint class_data_len,
|
||||
const unsigned char* classbytes,
|
||||
jint* new_class_data_len,
|
||||
unsigned char** new_classbytes);
|
||||
@@ -0,0 +1,38 @@
|
||||
#pragma once
|
||||
|
||||
#include <JuiceAgent/Logger.hpp>
|
||||
#include <jni.h>
|
||||
#include <jvmti.h>
|
||||
#include <event/eventbus.hpp>
|
||||
|
||||
namespace JuiceAgent {
|
||||
class Agent {
|
||||
private:
|
||||
JavaVM* jvm;
|
||||
jvmtiEnv* jvmti;
|
||||
EventBus eventbus;
|
||||
|
||||
private:
|
||||
Agent() = default;
|
||||
~Agent() = default;
|
||||
|
||||
public:
|
||||
// ===== Singleton =====
|
||||
static Agent& instance();
|
||||
|
||||
Agent(const Agent&) = delete;
|
||||
Agent& operator=(const Agent&) = delete;
|
||||
|
||||
// EntryPoint
|
||||
bool init(JavaVM* jvm, JNIEnv* env, jvmtiEnv* jvmti);
|
||||
|
||||
// getters
|
||||
JavaVM* get_jvm() const { return jvm; }
|
||||
jvmtiEnv* get_jvmti() const { return jvmti; }
|
||||
EventBus& get_eventbus() { return eventbus; }
|
||||
|
||||
// setters
|
||||
void set_jvm(JavaVM* jvm) { this->jvm = jvm; }
|
||||
void set_jvmti(jvmtiEnv* jvmti) { this->jvmti = jvmti; }
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
#pragma once
|
||||
|
||||
#include <libagent.hpp>
|
||||
|
||||
inline bool check_env(JuiceAgent::Agent& agent) {
|
||||
if (agent.get_jvm() == nullptr) {
|
||||
PLOGE << "Failed to get JavaVM instance";
|
||||
return false;
|
||||
}
|
||||
if (agent.get_jvmti() == nullptr) {
|
||||
PLOGE << "Failed to get JVMTI environment";
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
inline std::string get_class_name(JNIEnv* env, jclass clazz) {
|
||||
if (!env || !clazz) return "";
|
||||
|
||||
jclass clsClass = env->FindClass("java/lang/Class");
|
||||
if (!clsClass) return "";
|
||||
|
||||
jmethodID mid = env->GetMethodID(clsClass, "getName", "()Ljava/lang/String;");
|
||||
if (!mid) {
|
||||
env->DeleteLocalRef(clsClass);
|
||||
return "";
|
||||
}
|
||||
|
||||
jstring nameStr = static_cast<jstring>(env->CallObjectMethod(clazz, mid));
|
||||
std::string result;
|
||||
|
||||
if (nameStr) {
|
||||
const char* tmp = env->GetStringUTFChars(nameStr, nullptr);
|
||||
if (tmp) {
|
||||
result = tmp; // copy to std::string
|
||||
env->ReleaseStringUTFChars(nameStr, tmp);
|
||||
}
|
||||
env->DeleteLocalRef(nameStr);
|
||||
}
|
||||
|
||||
env->DeleteLocalRef(clsClass);
|
||||
return result;
|
||||
}
|
||||
@@ -0,0 +1,328 @@
|
||||
#include <jni_impl.hpp>
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
#include <cstring>
|
||||
|
||||
// ============================
|
||||
// Get class bytecode (already captured)
|
||||
// ============================
|
||||
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytes
|
||||
(JNIEnv *env, jclass, jclass clazz) {
|
||||
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
if (!check_env(agent)) return nullptr;
|
||||
|
||||
char* signature = nullptr;
|
||||
if (agent.get_jvmti()->GetClassSignature(clazz, &signature, nullptr) != JVMTI_ERROR_NONE || !signature)
|
||||
return nullptr;
|
||||
|
||||
// Convert Lxxx; -> xxx
|
||||
std::string internalName(signature + 1, strlen(signature) - 2);
|
||||
agent.get_jvmti()->Deallocate(reinterpret_cast<unsigned char*>(signature));
|
||||
|
||||
// ============================
|
||||
// 1. Mark class for capture
|
||||
// ============================
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(classDataMutex);
|
||||
classToCapture.insert(internalName);
|
||||
}
|
||||
|
||||
// ============================
|
||||
// 2. Trigger class retransform
|
||||
// ============================
|
||||
jvmtiError err = agent.get_jvmti()->RetransformClasses(1, &clazz);
|
||||
if (err != JVMTI_ERROR_NONE) {
|
||||
PLOGE << "Retransform class failed: " << err;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// ============================
|
||||
// 3. Retrieve bytecode from cache
|
||||
// ============================
|
||||
ClassFileData data;
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(classDataMutex);
|
||||
auto it = classFileDataMap.find(internalName);
|
||||
if (it != classFileDataMap.end()) {
|
||||
data = it->second;
|
||||
}
|
||||
}
|
||||
|
||||
if (data.bytecode.empty()) {
|
||||
PLOGE << "Failed to capture bytecode for class: " << internalName;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
jbyteArray out = env->NewByteArray(static_cast<jsize>(data.bytecode.size()));
|
||||
if (!out || env->ExceptionCheck()) {
|
||||
env->ExceptionClear();
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
env->SetByteArrayRegion(out, 0, static_cast<jsize>(data.bytecode.size()), reinterpret_cast<const jbyte*>(data.bytecode.data()));
|
||||
return out;
|
||||
}
|
||||
|
||||
// ============================
|
||||
// Get class bytecode by class name
|
||||
// ============================
|
||||
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytesByName
|
||||
(JNIEnv *env, jclass loader_class, jstring name) {
|
||||
|
||||
if (!name) return nullptr;
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
if (!check_env(agent)) return nullptr;
|
||||
|
||||
// ============================
|
||||
// 1. Convert jstring -> internal name
|
||||
// ============================
|
||||
const char* utf = env->GetStringUTFChars(name, nullptr);
|
||||
if (!utf) return nullptr;
|
||||
std::string internalName(utf);
|
||||
env->ReleaseStringUTFChars(name, utf);
|
||||
|
||||
// Convert dots to slashes: a.b.C -> a/b/C
|
||||
std::replace(internalName.begin(), internalName.end(), '.', '/');
|
||||
|
||||
// ============================
|
||||
// 2. Iterate loaded classes
|
||||
// ============================
|
||||
jint count = 0;
|
||||
jclass* classes = nullptr;
|
||||
jvmtiEnv* jvmti = agent.get_jvmti();
|
||||
|
||||
if (jvmti->GetLoadedClasses(&count, &classes) != JVMTI_ERROR_NONE || count == 0) {
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
jclass targetClass = nullptr;
|
||||
for (jint i = 0; i < count; i++) {
|
||||
char* signature = nullptr;
|
||||
if (jvmti->GetClassSignature(classes[i], &signature, nullptr) == JVMTI_ERROR_NONE && signature) {
|
||||
size_t len = strlen(signature);
|
||||
if (len > 2 && signature[0] == 'L' && signature[len - 1] == ';') {
|
||||
if (internalName == std::string_view(signature + 1, len - 2)) {
|
||||
targetClass = classes[i];
|
||||
jvmti->Deallocate(reinterpret_cast<unsigned char*>(signature));
|
||||
break;
|
||||
}
|
||||
}
|
||||
jvmti->Deallocate(reinterpret_cast<unsigned char*>(signature));
|
||||
}
|
||||
}
|
||||
|
||||
if (classes) {
|
||||
jvmti->Deallocate(reinterpret_cast<unsigned char*>(classes));
|
||||
}
|
||||
|
||||
if (!targetClass) {
|
||||
PLOGE << "Class not loaded: " << internalName;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// ============================
|
||||
// 3. Reuse getClassBytes logic
|
||||
// ============================
|
||||
return Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytes(env, loader_class, targetClass);
|
||||
}
|
||||
|
||||
// ============================
|
||||
// Redefine class using jclass
|
||||
// ============================
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClass
|
||||
(JNIEnv *env, jclass loader_class, jclass clazz, jbyteArray class_bytes, jint class_bytes_len) {
|
||||
|
||||
// Get singleton agent instance
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
if (!check_env(agent))
|
||||
return JNI_FALSE;
|
||||
|
||||
// Get byte array elements
|
||||
jbyte* buf = env->GetByteArrayElements(class_bytes, nullptr);
|
||||
if (!buf) {
|
||||
PLOGE << "Cannot get class bytes";
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
// Prepare JVMTI class definition
|
||||
jvmtiClassDefinition defs[1];
|
||||
defs[0].klass = clazz;
|
||||
defs[0].class_byte_count = class_bytes_len;
|
||||
defs[0].class_bytes = reinterpret_cast<const unsigned char*>(buf);
|
||||
|
||||
// Redefine class via JVMTI
|
||||
jvmtiError result = agent.get_jvmti()->RedefineClasses(1, defs);
|
||||
|
||||
// Release byte array (no need to copy back)
|
||||
env->ReleaseByteArrayElements(class_bytes, buf, JNI_ABORT);
|
||||
|
||||
if (result != JVMTI_ERROR_NONE) {
|
||||
PLOGE << "Redefine class failed: " << result;
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
PLOGD << "Class redefined successfully!";
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
// ============================================
|
||||
// Redefine class using its fully qualified name
|
||||
// Supports automatic '.' -> '/' conversion
|
||||
// ============================================
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClassByName
|
||||
(JNIEnv *env, jclass loader_class, jstring class_name, jbyteArray class_bytes, jint class_bytes_len) {
|
||||
|
||||
// Convert jstring to C string
|
||||
const char* cname = env->GetStringUTFChars(class_name, nullptr);
|
||||
if (!cname) {
|
||||
PLOGE << "Class name is NULL!";
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
// Copy and replace '.' with '/' for JVM internal class name
|
||||
std::string internal_name(cname);
|
||||
std::replace(internal_name.begin(), internal_name.end(), '.', '/');
|
||||
|
||||
// Release the original Java string
|
||||
env->ReleaseStringUTFChars(class_name, cname);
|
||||
|
||||
// Find class by internal name
|
||||
jclass clazz = env->FindClass(internal_name.c_str());
|
||||
if (!clazz) {
|
||||
PLOGE << "Cannot find class: " << internal_name;
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
// Call redefineClass with the found class
|
||||
return Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_redefineClass(
|
||||
env, loader_class, clazz, class_bytes, class_bytes_len
|
||||
);
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClass
|
||||
(JNIEnv* env, jclass, jclass clazz, jbyteArray bytecodes, jint length) {
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
|
||||
// =========================
|
||||
// 1. Check environment & parameters
|
||||
// =========================
|
||||
if (!check_env(agent) || !clazz || !bytecodes) {
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
// =========================
|
||||
// 2. Get class internal name
|
||||
// =========================
|
||||
std::string nameDot = get_class_name(env, clazz);
|
||||
if (nameDot.empty()) {
|
||||
PLOGE << "Failed to get class name for retransform";
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
// Convert '.' to '/' for internal name
|
||||
for (auto& c : nameDot) if (c == '.') c = '/';
|
||||
|
||||
// =========================
|
||||
// 3. Extract bytecode from jbyteArray
|
||||
// =========================
|
||||
jbyte* bytes = env->GetByteArrayElements(bytecodes, nullptr);
|
||||
jint len = env->GetArrayLength(bytecodes);
|
||||
if (!bytes || len <= 0) {
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
// =========================
|
||||
// 4. Cache bytecode & class info for ClassFileLoadHook
|
||||
// =========================
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(classDataMutex);
|
||||
|
||||
ClassFileData data;
|
||||
data.classname = nameDot;
|
||||
data.bytecode.assign(bytes, bytes + len);
|
||||
data.clazz = static_cast<jclass>(env->NewGlobalRef(clazz)); // prevent GC
|
||||
data.classloader = nullptr; // optional
|
||||
data.protection_domain = nullptr;
|
||||
|
||||
classFileDataMap[nameDot] = std::move(data);
|
||||
}
|
||||
|
||||
env->ReleaseByteArrayElements(bytecodes, bytes, JNI_ABORT);
|
||||
|
||||
// =========================
|
||||
// 5. Trigger JVMTI retransform
|
||||
// =========================
|
||||
jclass classes[1] = { clazz };
|
||||
jvmtiError err = agent.get_jvmti()->RetransformClasses(1, classes);
|
||||
|
||||
if (err != JVMTI_ERROR_NONE) {
|
||||
PLOGE << "[retransformClass] failed: " << err << " for " << nameDot;
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
PLOGI << "[retransformClass] OK: " << nameDot << " (" << len << " bytes)";
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClassByName
|
||||
(JNIEnv* env, jclass, jstring className, jbyteArray bytecodes, jint length) {
|
||||
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
|
||||
if (!check_env(agent) || !className || !bytecodes) {
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
// =========================
|
||||
// 1. Get UTF string from jstring
|
||||
// =========================
|
||||
const char* utf = env->GetStringUTFChars(className, nullptr);
|
||||
if (!utf) return JNI_FALSE;
|
||||
|
||||
std::string internalName(utf);
|
||||
env->ReleaseStringUTFChars(className, utf);
|
||||
|
||||
// Convert '.' to '/' for internal name
|
||||
for (auto& c : internalName) if (c == '.') c = '/';
|
||||
|
||||
// =========================
|
||||
// 2. Find loaded class by internal name (inline)
|
||||
// =========================
|
||||
jclass target = nullptr;
|
||||
{
|
||||
jint classCount = 0;
|
||||
jclass* loadedClasses = nullptr;
|
||||
|
||||
if (agent.get_jvmti()->GetLoadedClasses(&classCount, &loadedClasses) == JVMTI_ERROR_NONE && classCount > 0) {
|
||||
for (jint i = 0; i < classCount; ++i) {
|
||||
char* sig = nullptr;
|
||||
if (agent.get_jvmti()->GetClassSignature(loadedClasses[i], &sig, nullptr) == JVMTI_ERROR_NONE && sig) {
|
||||
// sig: "Lnet/minecraft/client/Minecraft;"
|
||||
if (sig[0] == 'L') {
|
||||
size_t len = strlen(sig);
|
||||
if (len > 2 && internalName == std::string(sig + 1, len - 2)) {
|
||||
target = loadedClasses[i];
|
||||
agent.get_jvmti()->Deallocate(reinterpret_cast<unsigned char*>(sig));
|
||||
break;
|
||||
}
|
||||
}
|
||||
agent.get_jvmti()->Deallocate(reinterpret_cast<unsigned char*>(sig));
|
||||
}
|
||||
}
|
||||
agent.get_jvmti()->Deallocate(reinterpret_cast<unsigned char*>(loadedClasses));
|
||||
}
|
||||
}
|
||||
|
||||
if (!target) {
|
||||
PLOGE << "[retransformClassByName] class not loaded: " << internalName;
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
// =========================
|
||||
// 3. Delegate to retransformClass
|
||||
// =========================
|
||||
return Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_retransformClass(
|
||||
env, nullptr, target, bytecodes, length
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,275 @@
|
||||
#include <jni_impl.hpp>
|
||||
|
||||
// Add jar to bootstrap classloader search path
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToBootstrapClassLoaderSearch
|
||||
(JNIEnv *env, jclass, jstring jar_path) {
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
|
||||
if (!check_env(agent))
|
||||
return JNI_FALSE;
|
||||
|
||||
const char* j_jar_path = env->GetStringUTFChars(jar_path, nullptr);
|
||||
if (!j_jar_path) {
|
||||
PLOGE << "Path is NULL!";
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
jvmtiError result = agent.get_jvmti()->AddToBootstrapClassLoaderSearch(j_jar_path);
|
||||
if (result != JVMTI_ERROR_NONE) {
|
||||
PLOGE.printf("Cannot AddToBootstrapClassLoaderSearch [result=%d]", result);
|
||||
env->ReleaseStringUTFChars(jar_path, j_jar_path);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
PLOGI << "AddToBootstrapClassLoaderSearch: " << j_jar_path;
|
||||
|
||||
env->ReleaseStringUTFChars(jar_path, j_jar_path);
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
// Add jar to system classloader search path
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToSystemClassLoaderSearch
|
||||
(JNIEnv *env, jclass, jstring jar_path) {
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
if (!check_env(agent))
|
||||
return JNI_FALSE;
|
||||
|
||||
const char* j_jar_path = env->GetStringUTFChars(jar_path, nullptr);
|
||||
if (!j_jar_path) {
|
||||
PLOGE << "Path is NULL!";
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
jvmtiError result = agent.get_jvmti()->AddToSystemClassLoaderSearch(j_jar_path);
|
||||
if (result != JVMTI_ERROR_NONE) {
|
||||
PLOGE.printf("Cannot AddToSystemClassLoaderSearch [result=%d]", result);
|
||||
env->ReleaseStringUTFChars(jar_path, j_jar_path);
|
||||
return JNI_FALSE;
|
||||
}
|
||||
PLOGI << "AddToSystemClassLoaderSearch: " << j_jar_path;
|
||||
|
||||
env->ReleaseStringUTFChars(jar_path, j_jar_path);
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addToClassLoader
|
||||
(JNIEnv *env, jclass, jstring jar_path, jobject target_classloader) {
|
||||
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
|
||||
if (!check_env(agent))
|
||||
return JNI_FALSE;
|
||||
|
||||
if (!jar_path || !target_classloader)
|
||||
return JNI_FALSE;
|
||||
|
||||
// --- Try URLClassLoader path ---
|
||||
jclass urlClassLoader = env->FindClass("java/net/URLClassLoader");
|
||||
if (env->ExceptionCheck() || !urlClassLoader) {
|
||||
env->ExceptionClear();
|
||||
goto FALLBACK;
|
||||
}
|
||||
|
||||
if (env->IsInstanceOf(target_classloader, urlClassLoader)) {
|
||||
|
||||
jclass fileClass = env->FindClass("java/io/File");
|
||||
if (env->ExceptionCheck() || !fileClass) {
|
||||
env->ExceptionClear();
|
||||
goto FALLBACK;
|
||||
}
|
||||
|
||||
jmethodID fileInit = env->GetMethodID(fileClass, "<init>", "(Ljava/lang/String;)V");
|
||||
if (env->ExceptionCheck() || !fileInit) {
|
||||
env->ExceptionClear();
|
||||
goto FALLBACK;
|
||||
}
|
||||
|
||||
jobject file = env->NewObject(fileClass, fileInit, jar_path);
|
||||
if (env->ExceptionCheck() || !file) {
|
||||
env->ExceptionClear();
|
||||
goto FALLBACK;
|
||||
}
|
||||
|
||||
jmethodID toURI = env->GetMethodID(fileClass, "toURI", "()Ljava/net/URI;");
|
||||
if (env->ExceptionCheck() || !toURI) {
|
||||
env->ExceptionClear();
|
||||
env->DeleteLocalRef(file);
|
||||
goto FALLBACK;
|
||||
}
|
||||
|
||||
jobject uri = env->CallObjectMethod(file, toURI);
|
||||
if (env->ExceptionCheck() || !uri) {
|
||||
env->ExceptionClear();
|
||||
env->DeleteLocalRef(file);
|
||||
goto FALLBACK;
|
||||
}
|
||||
|
||||
jclass uriClass = env->FindClass("java/net/URI");
|
||||
if (env->ExceptionCheck() || !uriClass) {
|
||||
env->ExceptionClear();
|
||||
env->DeleteLocalRef(file);
|
||||
env->DeleteLocalRef(uri);
|
||||
goto FALLBACK;
|
||||
}
|
||||
|
||||
jmethodID toURL = env->GetMethodID(uriClass, "toURL", "()Ljava/net/URL;");
|
||||
if (env->ExceptionCheck() || !toURL) {
|
||||
env->ExceptionClear();
|
||||
env->DeleteLocalRef(file);
|
||||
env->DeleteLocalRef(uri);
|
||||
goto FALLBACK;
|
||||
}
|
||||
|
||||
jobject url = env->CallObjectMethod(uri, toURL);
|
||||
if (env->ExceptionCheck() || !url) {
|
||||
env->ExceptionClear();
|
||||
env->DeleteLocalRef(file);
|
||||
env->DeleteLocalRef(uri);
|
||||
goto FALLBACK;
|
||||
}
|
||||
|
||||
jmethodID addURL = env->GetMethodID(urlClassLoader, "addURL", "(Ljava/net/URL;)V");
|
||||
if (env->ExceptionCheck() || !addURL) {
|
||||
env->ExceptionClear();
|
||||
env->DeleteLocalRef(file);
|
||||
env->DeleteLocalRef(uri);
|
||||
env->DeleteLocalRef(url);
|
||||
goto FALLBACK;
|
||||
}
|
||||
|
||||
env->CallVoidMethod(target_classloader, addURL, url);
|
||||
if (env->ExceptionCheck()) {
|
||||
env->ExceptionClear();
|
||||
env->DeleteLocalRef(file);
|
||||
env->DeleteLocalRef(uri);
|
||||
env->DeleteLocalRef(url);
|
||||
goto FALLBACK;
|
||||
}
|
||||
|
||||
// cleanup
|
||||
env->DeleteLocalRef(file);
|
||||
env->DeleteLocalRef(uri);
|
||||
env->DeleteLocalRef(url);
|
||||
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
FALLBACK:
|
||||
|
||||
// --- JVMTI fallback ---
|
||||
const char* j_jar_path = env->GetStringUTFChars(jar_path, nullptr);
|
||||
if (!j_jar_path)
|
||||
return JNI_FALSE;
|
||||
|
||||
jvmtiError err = agent.get_jvmti()->AddToSystemClassLoaderSearch(j_jar_path);
|
||||
|
||||
env->ReleaseStringUTFChars(jar_path, j_jar_path);
|
||||
|
||||
if (err != JVMTI_ERROR_NONE) {
|
||||
return JNI_FALSE;
|
||||
}
|
||||
|
||||
return JNI_TRUE;
|
||||
}
|
||||
|
||||
// TODO: Safety and Compatibility: Define Class
|
||||
// Define class using target classloader
|
||||
JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_defineClass
|
||||
(JNIEnv *env, jclass, jobject target_classloader, jbyteArray bytes) {
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
|
||||
if (!check_env(agent))
|
||||
return nullptr;
|
||||
|
||||
jclass clClass = env->FindClass("java/lang/ClassLoader");
|
||||
jmethodID defineClass = env->GetMethodID(clClass, "defineClass", "([BII)Ljava/lang/Class;");
|
||||
jobject classDefined = env->CallObjectMethod(target_classloader, defineClass, bytes, 0,
|
||||
env->GetArrayLength(bytes));
|
||||
if (env->ExceptionCheck()) {
|
||||
env->ExceptionDescribe();
|
||||
env->ExceptionClear();
|
||||
return nullptr;
|
||||
}
|
||||
return (jclass)classDefined;
|
||||
}
|
||||
|
||||
JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getLoadedClasses
|
||||
(JNIEnv *env, jclass) {
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
|
||||
if (!check_env(agent))
|
||||
return nullptr;
|
||||
|
||||
jint count = 0;
|
||||
jclass* classes = nullptr;
|
||||
jvmtiError err = agent.get_jvmti()->GetLoadedClasses(&count, &classes);
|
||||
if (err != JVMTI_ERROR_NONE) {
|
||||
PLOGE.printf("GetLoadedClasses failed: %d", err);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
jclass classClass = env->FindClass("java/lang/Class");
|
||||
jobjectArray classesArray = env->NewObjectArray(count, classClass, nullptr);
|
||||
|
||||
for (int i = 0; i < count; i++) {
|
||||
env->SetObjectArrayElement(classesArray, i, classes[i]);
|
||||
}
|
||||
|
||||
agent.get_jvmti()->Deallocate((unsigned char*)classes);
|
||||
return classesArray;
|
||||
}
|
||||
|
||||
JNIEXPORT jclass JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassByName
|
||||
(JNIEnv *env, jclass, jstring name) {
|
||||
auto& agent = JuiceAgent::Agent::instance();
|
||||
|
||||
if (!check_env(agent))
|
||||
return nullptr;
|
||||
|
||||
const char* utf = env->GetStringUTFChars(name, nullptr);
|
||||
if (!utf) {
|
||||
PLOGE << "Class name is NULL!";
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Convert Java name to internal name: a.b.C -> a/b/C
|
||||
std::string internal_name(utf);
|
||||
std::replace(internal_name.begin(), internal_name.end(), '.', '/');
|
||||
env->ReleaseStringUTFChars(name, utf);
|
||||
|
||||
// Get all loaded classes
|
||||
jint count = 0;
|
||||
jclass* classes = nullptr;
|
||||
if (agent.get_jvmti()->GetLoadedClasses(&count, &classes) != JVMTI_ERROR_NONE || count == 0) {
|
||||
PLOGE << "GetLoadedClasses failed or no classes loaded";
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
jclass result = nullptr;
|
||||
|
||||
for (jint i = 0; i < count; i++) {
|
||||
char* signature = nullptr;
|
||||
if (agent.get_jvmti()->GetClassSignature(classes[i], &signature, nullptr) != JVMTI_ERROR_NONE || !signature)
|
||||
continue;
|
||||
|
||||
size_t sig_len = strlen(signature);
|
||||
if (sig_len > 2 && signature[0] == 'L' && signature[sig_len - 1] == ';' &&
|
||||
internal_name.size() == sig_len - 2 &&
|
||||
strncmp(signature + 1, internal_name.c_str(), sig_len - 2) == 0) {
|
||||
result = classes[i];
|
||||
agent.get_jvmti()->Deallocate((unsigned char*)signature);
|
||||
break;
|
||||
}
|
||||
|
||||
agent.get_jvmti()->Deallocate((unsigned char*)signature);
|
||||
}
|
||||
|
||||
if (classes) {
|
||||
agent.get_jvmti()->Deallocate((unsigned char*)classes);
|
||||
}
|
||||
|
||||
if (!result) {
|
||||
PLOGE << "Failed to find loaded class: " << internal_name;
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
Loaded 100 of 116 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user