mirror of
https://github.com/xiaozhou233/JuiceAgent.git
synced 2026-12-05 13:05:53 +08:00
Compare commits
17
Commits
v5.0.0
...
6eb1925ec3
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6eb1925ec3 | ||
|
|
59e705510e | ||
|
|
c548022068 | ||
|
|
6a43b3437a | ||
|
|
8cd4c54c07 | ||
|
|
3796cca9a1 | ||
|
|
80f926fde6 | ||
|
|
9351556cda | ||
|
|
19b1bfb88a | ||
|
|
3cd28c9bcb | ||
|
|
124c656400 | ||
|
|
e6da1d6fff | ||
|
|
08fe3a8815 | ||
|
|
9aebf29bb5 | ||
|
|
13145f77c9 | ||
|
|
5b0a26d49e | ||
|
|
4c3798735b |
No files matched your search
@@ -0,0 +1,95 @@
|
||||
name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ main ]
|
||||
pull_request:
|
||||
workflow_dispatch:
|
||||
|
||||
jobs:
|
||||
build-and-test:
|
||||
name: Build & integration tests (Windows, MinGW)
|
||||
runs-on: windows-latest
|
||||
|
||||
steps:
|
||||
- name: Checkout
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Set up JDK
|
||||
uses: actions/setup-java@v4
|
||||
with:
|
||||
distribution: temurin
|
||||
java-version: '25'
|
||||
|
||||
- name: Set up MinGW-w64 toolchain
|
||||
uses: msys2/setup-msys2@v2
|
||||
with:
|
||||
msystem: MINGW64
|
||||
update: false
|
||||
install: >-
|
||||
mingw-w64-x86_64-gcc
|
||||
mingw-w64-x86_64-binutils
|
||||
mingw-w64-x86_64-cmake
|
||||
mingw-w64-x86_64-ninja
|
||||
|
||||
- name: Configure
|
||||
shell: msys2 {0}
|
||||
run: |
|
||||
# Link the C/C++ runtime statically, like w64devkit (the toolchain the
|
||||
# project is built with locally). Without this the DLLs depend on
|
||||
# libstdc++-6/libgcc_s_seh-1, which can be shadowed by a different
|
||||
# version elsewhere on the machine and fail to load.
|
||||
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release \
|
||||
-DCMAKE_EXE_LINKER_FLAGS="-static-libgcc -static-libstdc++" \
|
||||
-DCMAKE_SHARED_LINKER_FLAGS="-static-libgcc -static-libstdc++"
|
||||
|
||||
- name: Build
|
||||
shell: msys2 {0}
|
||||
run: |
|
||||
cmake --build build
|
||||
|
||||
echo "compiler: $(command -v g++)"
|
||||
echo "target: $(gcc -dumpmachine)"
|
||||
|
||||
echo "--- imports (non-system DLLs) ---"
|
||||
objdump -p build/bin/libagent.dll build/bin/libloader.dll build/bin/libinject.dll \
|
||||
| grep 'DLL Name:' | sed 's/.*DLL Name:[[:space:]]*//' | sort -u
|
||||
|
||||
# Bundle whatever non-system DLLs are still imported, taken from the
|
||||
# toolchain that built them, so the tests can load libagent.dll
|
||||
# without depending on PATH.
|
||||
GCC_BIN="$(dirname "$(command -v gcc)")"
|
||||
deps="$(objdump -p build/bin/libagent.dll build/bin/libloader.dll build/bin/libinject.dll \
|
||||
| grep 'DLL Name:' | sed 's/.*DLL Name:[[:space:]]*//' | sort -u \
|
||||
| grep -viE '^(kernel32|user32|advapi32|ws2_32|shell32|ole32|gdi32|msvcrt|ucrtbase|ntdll|comdlg32|comctl32|psapi|version|iphlpapi|bcrypt|secur32|crypt32|winmm|imm32|netapi32|userenv|rpcrt4|setupapi|mswsock|dnsapi|normaliz)[.]dll$' \
|
||||
| grep -viE '^api-ms-win-')"
|
||||
for dll in $deps; do
|
||||
if [ -f "$GCC_BIN/$dll" ]; then
|
||||
cp -f "$GCC_BIN/$dll" build/bin/
|
||||
echo "bundled $dll"
|
||||
else
|
||||
echo "MISSING $dll (not found in $GCC_BIN)"
|
||||
fi
|
||||
done
|
||||
|
||||
echo "--- build/bin ---"
|
||||
ls -1 build/bin
|
||||
|
||||
- name: Run integration tests
|
||||
shell: pwsh
|
||||
run: |
|
||||
# Fallback for any remaining runtime DLLs.
|
||||
$env:PATH = "C:\msys64\mingw64\bin;$env:PATH"
|
||||
./tests/run-tests.ps1
|
||||
|
||||
- name: Package release zip
|
||||
shell: msys2 {0}
|
||||
run: cmake -P script/package.cmake
|
||||
|
||||
- name: Upload build artifacts
|
||||
uses: actions/upload-artifact@v4
|
||||
with:
|
||||
name: JuiceAgent-windows-x64
|
||||
path: dist/JuiceAgent_*.zip
|
||||
if-no-files-found: error
|
||||
retention-days: 14
|
||||
@@ -0,0 +1,210 @@
|
||||
# AGENTS.md
|
||||
|
||||
Guidance for AI coding agents (and humans) working in this repository.
|
||||
|
||||
## Project at a glance
|
||||
|
||||
JuiceAgent is a JVMTI-based runtime injection framework for Windows. It injects
|
||||
into a running JVM (even with `DisableAttachMechanism=true`, no `-javaagent`),
|
||||
loads a JAR and calls an entry point, and exposes native APIs to
|
||||
redefine/retransform classes, query loaded classes and read bytecode.
|
||||
|
||||
Four binaries:
|
||||
|
||||
| Target | Output | Role |
|
||||
| --- | --- | --- |
|
||||
| `injector` | `injector.exe` | CLI driver: loads `libinject.dll` and injects `libloader.dll` into a target PID |
|
||||
| `libinject` | `libinject.dll` | Reflective DLL injector (exports `inject`, plus JNI bindings) |
|
||||
| `libloader` | `libloader.dll` | **Reflectively loaded** into the target JVM. Attaches to the JVM, reads `config.toml`, registers the embedded JuiceAgent-API jar, bootstraps the agent |
|
||||
| `libagent` | `libagent.dll` | The JVMTI agent. Registers `ClassFileLoadHook` and implements the native side of the JuiceAgent-API |
|
||||
|
||||
## Toolchain
|
||||
|
||||
- Windows x64, MinGW-w64 GCC (the maintainer uses [w64devkit](https://github.com/skeeto/w64devkit)), Ninja, CMake 3.15+
|
||||
- C++20
|
||||
- JDK 17+ for the Java side. `--enable-native-access=ALL-UNNAMED` is required from
|
||||
JDK 22 on to keep `System.load` warning-free (a future JDK will deny native
|
||||
access without it).
|
||||
|
||||
## Build
|
||||
|
||||
```powershell
|
||||
cmake --preset release # or: --preset debug
|
||||
cmake --build build
|
||||
```
|
||||
|
||||
Binaries land in `build/bin`.
|
||||
|
||||
Alternatively, without presets:
|
||||
|
||||
```powershell
|
||||
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
|
||||
cmake --build build
|
||||
```
|
||||
|
||||
## Test
|
||||
|
||||
Integration tests live in `tests/`. They are plain `main()` programs (not JUnit)
|
||||
that `System.load("resources/libagent.dll")` and call `JuiceAgent.init("")`.
|
||||
Two of them need the `injection` module compiled into `out/production/injection`.
|
||||
|
||||
Build first, then:
|
||||
|
||||
```powershell
|
||||
pwsh tests/run-tests.ps1
|
||||
# or point it at a specific JDK:
|
||||
pwsh tests/run-tests.ps1 -JdkHome "C:\Program Files\Zulu\zulu-25"
|
||||
```
|
||||
|
||||
The runner compiles the modules, refreshes `tests/resources` from `build/bin`
|
||||
(via `tests/copy-bin.bat`), compiles the tests, then runs every test and
|
||||
**asserts on its output**.
|
||||
|
||||
> Running the tests rebuilds the tracked file `tests/injection.jar`. After a local
|
||||
> run, restore it with `git checkout -- tests/injection.jar` before committing.
|
||||
|
||||
## Release
|
||||
|
||||
1. Bump `Version.txt` (`Major` / `Minor` / `Patch`).
|
||||
2. Add `docs/update/vX.Y.Z.md` (bilingual release notes) and an entry in
|
||||
`docs/update/CHANGELOG.md`.
|
||||
3. Commit the docs, then commit `Version X.Y.Z`, then tag `vX.Y.Z`.
|
||||
4. Build the package and attach it to a GitHub Release:
|
||||
|
||||
```powershell
|
||||
cmake -P script/package.cmake # -> dist/JuiceAgent_vX.Y.Z_x64.zip
|
||||
```
|
||||
|
||||
(`script/package.bat` wraps this but ends with `pause`.)
|
||||
|
||||
`tests/`, `build/`, `dist/` and `*.log` are gitignored; `dist/*.zip` is **not**
|
||||
committed.
|
||||
|
||||
## Hard rules (each of these was learned by breaking the build or a target JVM)
|
||||
|
||||
### 1. `libloader` must never throw a C++ exception
|
||||
|
||||
`libloader.dll` is loaded by a **reflective loader (manual mapping)**, so its
|
||||
unwind tables are never registered with the OS. A C++ exception thrown inside it
|
||||
**cannot be unwound or caught** - it crashes the target JVM with
|
||||
`EXCEPTION_ILLEGAL_INSTRUCTION` (a `try/catch` there is useless, not a fix).
|
||||
|
||||
- The `loader` target is compiled with `-fno-exceptions` (and
|
||||
`SPDLOG_NO_EXCEPTIONS`) on purpose: any exception-capable code fails the build.
|
||||
- Report problems with `spdlog` + an early `return`, never with `throw`.
|
||||
- This also means library code that can throw (`toml::parse_file`,
|
||||
`std::filesystem`, allocations) must be used in a non-throwing way. toml++
|
||||
switches to the non-throwing `toml::parse_result` API automatically when
|
||||
exceptions are disabled.
|
||||
|
||||
### 2. Config reads are non-throwing
|
||||
|
||||
`includes/JuiceAgent/Config.hpp` intentionally has **no throwing getters**. Use:
|
||||
|
||||
```cpp
|
||||
if (!cfg.contains("JarLoader.Mode")) { spdlog::error("Missing key: JarLoader.Mode"); return; }
|
||||
const std::string mode = cfg.get<std::string>("JarLoader.Mode", "");
|
||||
```
|
||||
|
||||
For required values, check `contains()` first and then `get(path, default)`.
|
||||
|
||||
### 3. Config schema changes are a coordinated edit
|
||||
|
||||
The current schema is v2 (`CONFIG_VERSION` in `includes/JuiceAgent/JuiceAgent.hpp`).
|
||||
It is validated at load time, so a mismatch makes the loader refuse to start.
|
||||
Changing the schema requires updating, together:
|
||||
|
||||
- `CONFIG_VERSION`
|
||||
- `docs/config.md`
|
||||
- the three `examples/*/config.toml`
|
||||
- the config block in `README.md` **and** `README_ZH.md`
|
||||
|
||||
### 4. Keep the MinGW runtime out of the shipped DLLs
|
||||
|
||||
Do not introduce a dependency on `libstdc++-6.dll` / `libgcc_s_seh-1.dll` /
|
||||
`libwinpthread-1.dll`. A DLL that needs them can pick up an incompatible copy
|
||||
from elsewhere on the machine and fail to load (`UnsatisfiedLinkError: The
|
||||
specified procedure could not be found`). w64devkit links the runtime statically;
|
||||
CI passes `-static-libgcc -static-libstdc++` to match.
|
||||
|
||||
### 5. Tests assert on output, not exit codes
|
||||
|
||||
The test programs print diagnostics and **still exit 0** when a step fails. Match
|
||||
an expected marker (e.g. `Bytes: 399`, `Modified!`, `Injection Invoked!`) -
|
||||
checking `$LASTEXITCODE` alone will silently pass broken builds.
|
||||
|
||||
Notes when adding tests:
|
||||
|
||||
- `GetClassBytesByName` only resolves **already loaded** classes; load the target
|
||||
first (`Class.forName("Target")`).
|
||||
- Tests that print to stderr make Windows PowerShell 5.1 unhappy; the runner sets
|
||||
`$ErrorActionPreference = "Continue"` and relies on explicit checks.
|
||||
|
||||
## Layout
|
||||
|
||||
```
|
||||
src/injector injector.exe
|
||||
src/libinject libinject.dll (reflective injector)
|
||||
src/libloader libloader.dll (runs in the target; exception-free)
|
||||
src/libagent libagent.dll (JVMTI agent)
|
||||
services/ IService implementations, self-registered via JUICEAGENT_REGISTER_SERVICE
|
||||
includes/eventbus.hpp typed EventBus
|
||||
includes/JuiceAgent Config.hpp / Logger.hpp / Utils.hpp / JuiceAgent.hpp (CONFIG_VERSION)
|
||||
includes/toml++ vendored
|
||||
includes/spdlog vendored
|
||||
tests/ integration tests + run-tests.ps1 + copy-bin.bat
|
||||
docs/ config.md, advanced.md, Inject.md, update/ (release notes + changelog)
|
||||
examples/ runnable end-to-end examples (each has config.toml + HowToUse)
|
||||
script/ package.cmake / package.bat
|
||||
```
|
||||
|
||||
## Conventions
|
||||
|
||||
### Services and the event bus
|
||||
|
||||
A service derives from `IService` (`src/libagent/includes/services/base.hpp`) and
|
||||
self-registers at file scope:
|
||||
|
||||
```cpp
|
||||
JUICEAGENT_REGISTER_SERVICE(::JuiceAgent::Services::MyService)
|
||||
```
|
||||
|
||||
Subscribe with the typed bus - there is no `EventId` and no `void*` casting:
|
||||
|
||||
```cpp
|
||||
listen<MyService, EventLoaded>(&MyService::onLoaded); // append
|
||||
listenFront<MyService, EventLoaded>(&MyService::onLoaded); // run before others
|
||||
```
|
||||
|
||||
Publish with `EventBus::getInstance().post(event)`. Call `unlistenAll()` in
|
||||
`onShutdown()`.
|
||||
|
||||
### Commit messages
|
||||
|
||||
`Type: subject`, then `- component: detail` bullets. Types used here:
|
||||
`Feat`, `BugFix`, `Refactor`, `Docs`, `CI`, and `Version X.Y.Z` for the release
|
||||
commit.
|
||||
|
||||
### Docs
|
||||
|
||||
`README.md` and `README_ZH.md` are kept in sync; keep both updated. Prose docs
|
||||
live in `docs/` (English). Release notes and the changelog live in `docs/update/`.
|
||||
|
||||
### Line endings
|
||||
|
||||
Tracked text files are **LF in the index, CRLF in the working tree** (no
|
||||
`.gitattributes`). When creating files, write CRLF to avoid noisy diffs.
|
||||
|
||||
## CI
|
||||
|
||||
`.github/workflows/ci.yml` runs on `windows-latest`: JDK 25 (Temurin) +
|
||||
MinGW-w64 (MSYS2) + Ninja, then `configure -> build -> tests -> package`, and
|
||||
uploads `dist/JuiceAgent_*.zip` as an artifact (14-day retention).
|
||||
|
||||
CI-specific notes:
|
||||
|
||||
- It builds with `-static-libgcc -static-libstdc++` and also copies any remaining
|
||||
non-system imported DLLs next to the binaries (see rule 4).
|
||||
- The workflow prints the DLL import list - useful when a load error appears.
|
||||
- GitHub's unauthenticated REST API is limited to 60 requests/hour, so avoid
|
||||
polling workflow status in a loop; install `gh` or use a token instead.
|
||||
+11
-3
@@ -10,13 +10,21 @@ set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
||||
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||
|
||||
set(SRC_DIR ${CMAKE_SOURCE_DIR}/src)
|
||||
link_directories("${CMAKE_SOURCE_DIR}/lib")
|
||||
|
||||
if(WIN32)
|
||||
link_directories("${CMAKE_SOURCE_DIR}/lib")
|
||||
endif()
|
||||
|
||||
# libraries
|
||||
add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection)
|
||||
if (WIN32)
|
||||
add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection)
|
||||
endif()
|
||||
|
||||
# modules
|
||||
add_subdirectory(${SRC_DIR}/libloader)
|
||||
add_subdirectory(${SRC_DIR}/injector)
|
||||
add_subdirectory(${SRC_DIR}/libinject)
|
||||
if(WIN32)
|
||||
add_subdirectory(${SRC_DIR}/libinject)
|
||||
endif()
|
||||
|
||||
add_subdirectory(${SRC_DIR}/libagent)
|
||||
@@ -0,0 +1,403 @@
|
||||
# Quick Start for Agents
|
||||
|
||||
This guide tells an **agent** how to set up a JuiceAgent injection for a user:
|
||||
ask the right questions, generate the files, run the injection, and verify it.
|
||||
|
||||
Work through the steps in order. The result is a self-contained runtime
|
||||
directory called `app`, plus a short report to the user.
|
||||
|
||||
## Ground rules
|
||||
|
||||
- Only inject into a JVM that the user owns or is authorized to test. If that is
|
||||
unclear, stop and ask before doing anything else.
|
||||
- Do not modify the JuiceAgent native sources. Configuration and payload changes
|
||||
cover almost every request.
|
||||
- Keep every file in one runtime directory: `config.toml`, both JARs and the
|
||||
four binaries. Relative paths only behave predictably when they sit next to
|
||||
each other (see [Step 4](#step-4--write-configtoml)).
|
||||
- Never guess a PID. Confirm it with the user or read it from the process list.
|
||||
|
||||
## Project overview
|
||||
|
||||
JuiceAgent is a JVMTI-based runtime injection framework for Windows. It injects
|
||||
into a running JVM even when `DisableAttachMechanism=true` and without a
|
||||
`-javaagent` flag, loads a JAR and calls an entry point, and exposes native APIs
|
||||
to redefine/retransform classes, query loaded classes and read bytecode.
|
||||
|
||||
## Step 1 — Check the environment (do this yourself, do not ask the user)
|
||||
|
||||
**1.1 JDK.** `javac`, `jar` and `jps` ship with the JDK, so a full JDK is
|
||||
required — a bare JRE is not enough.
|
||||
|
||||
```
|
||||
java -version
|
||||
```
|
||||
|
||||
If the JDK is missing or older than 1.8, ask the user to install JDK 1.8 or
|
||||
higher.
|
||||
|
||||
**1.2 JuiceAgent binaries.** When built from source they are in `build/bin`
|
||||
(release archives put them wherever they were extracted):
|
||||
|
||||
```
|
||||
ls build/bin
|
||||
```
|
||||
|
||||
Expected files:
|
||||
|
||||
```
|
||||
injector.exe libinject.dll libloader.dll libagent.dll
|
||||
```
|
||||
|
||||
If they are missing, ask the user to pick one of:
|
||||
|
||||
- **Method 1 (recommended):** download the latest release from
|
||||
https://github.com/xiaozhou233/JuiceAgent/releases/latest
|
||||
- **Method 2:** build from source — see the "How To Build" section of `README.md`
|
||||
|
||||
**1.3 Create the runtime directory.** Copy the four files into one directory and
|
||||
call it `app` for the rest of this guide. A complete `app` looks like:
|
||||
|
||||
```
|
||||
app/
|
||||
├─ injector.exe libinject.dll libloader.dll libagent.dll
|
||||
├─ config.toml # Step 4
|
||||
├─ payload.jar # Step 3 (Q3)
|
||||
├─ injection/ # Step 3 (Q5), dependency JARs; BuiltIn mode only
|
||||
├─ src/ # payload source, if you generate it
|
||||
└─ build/ # compiler output, one subdirectory per artifact
|
||||
├─ target/ # demo target classes
|
||||
└─ payload/ # payload classes
|
||||
```
|
||||
|
||||
## Step 2 — Gather requirements (ask the user)
|
||||
|
||||
Ask these six questions and translate them into the user's language. Each
|
||||
answer maps to a concrete decision, so do not skip any of them.
|
||||
|
||||
| # | Question | Decides |
|
||||
| --- | --- | --- |
|
||||
| Q1 | Which process do you want to inject into? (PID / process name / start a demo target — recommended) | the target and its working directory |
|
||||
| Q2 | Is the target a standard, unmodified JVM? | whether injection will work at all |
|
||||
| Q3 | What should the injected code do? (verify the link / your own code / modify bytecode) | the payload JAR, entry class and method |
|
||||
| Q4 | Does the payload need JuiceAgent-API? (yes / no / don't know) | `JarLoader.Mode` |
|
||||
| Q5 | Does the payload depend on other libraries? (yes / no) | `JarLoader.InjectionDir` |
|
||||
| Q6 | How should the injection be triggered? (`injector.exe` / JNI JavaInjector) | the commands in Step 5 |
|
||||
|
||||
## Step 3 — Apply the answers
|
||||
|
||||
### Q1 — Target process
|
||||
|
||||
- **PID:** remember it for Step 5.
|
||||
- **Process name:** resolve it to a PID with `jps -l`. Every JVM appears as
|
||||
`java.exe`, so match the main class or JAR path in the `jps -l` output, or use
|
||||
`Get-Process <name>` on Windows.
|
||||
- **Start a demo target (recommended when the user has no target):** write
|
||||
`app/target.java`:
|
||||
|
||||
```java
|
||||
import java.lang.management.ManagementFactory;
|
||||
|
||||
public class target {
|
||||
public static void main(String[] args) {
|
||||
String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
|
||||
try {
|
||||
while (true) {
|
||||
System.out.println("[Target] I am the target JVM (PID: " + pid + ")");
|
||||
Thread.sleep(1000);
|
||||
}
|
||||
} catch (Exception e) {
|
||||
e.printStackTrace();
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Compile and run it, **with `app` as the working directory**:
|
||||
|
||||
```
|
||||
javac -encoding UTF-8 --release 8 -d app/build/target app/target.java
|
||||
```
|
||||
|
||||
```powershell
|
||||
Start-Process -FilePath java -ArgumentList "-cp","build/target","target" -WorkingDirectory "<path-to-app>"
|
||||
```
|
||||
|
||||
The target prints its PID every second; `jps -l` also lists it.
|
||||
|
||||
> Starting the target with `app` as its working directory is not cosmetic. See
|
||||
> [Step 4](#step-4--write-configtoml) for why the working directory decides which
|
||||
> `config.toml` the injected loader finds.
|
||||
|
||||
### Q2 — Standard JVM
|
||||
|
||||
- **Standard JVM / `DisableAttachMechanism=true`:** continue — JuiceAgent is
|
||||
designed for exactly this case.
|
||||
- **Custom or modified JVM:** continue, but warn the user that JuiceAgent is
|
||||
only tested against a regular JVM and may not work.
|
||||
|
||||
### Q3 — Payload
|
||||
|
||||
**Verify the link.** Write `app/src/Main.java`:
|
||||
|
||||
```java
|
||||
public class Main {
|
||||
public static void run() {
|
||||
System.out.println("[Demo] Injection succeeded! Hello from JuiceAgent.");
|
||||
System.out.println("[Demo] Current thread: " + Thread.currentThread().getName());
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Build it into `app/payload.jar`. Each artifact gets its own output directory, so
|
||||
packaging the payload never picks up the demo target's classes:
|
||||
|
||||
```
|
||||
javac -encoding UTF-8 --release 8 -d app/build/payload app/src/Main.java
|
||||
jar --create --file app/payload.jar -C app/build/payload .
|
||||
```
|
||||
|
||||
The class name `Main` and method name `run` are needed in Step 4.
|
||||
|
||||
**Own code.** Ask the user for the payload JAR and record its fully qualified
|
||||
entry class and method. The entry method must be `public`, `static` and take no
|
||||
arguments (the project documents this as `public static void`; the return value
|
||||
is ignored). It is resolved by reflection, so a non-public, non-static or
|
||||
parameterized method is only reported as a failure at invocation time — the JAR
|
||||
itself still loads.
|
||||
|
||||
**Modify bytecode.** Point the user at `examples/retransform-class`. Payloads
|
||||
that redefine or retransform classes use JuiceAgent-API, so Q4 must resolve to
|
||||
`BuiltIn`.
|
||||
|
||||
### Q4 — JuiceAgent-API
|
||||
|
||||
| Answer | `JarLoader.Mode` |
|
||||
| --- | --- |
|
||||
| Yes | `BuiltIn` |
|
||||
| No | `CustomJar` |
|
||||
| I don't know | `BuiltIn` |
|
||||
|
||||
`BuiltIn` (recommended) runs in two stages, and **both stages read
|
||||
`config.toml` from the runtime directory**:
|
||||
|
||||
1. `libloader` extracts the embedded JuiceAgent-API JAR into `%TEMP%`, adds it
|
||||
to the system class loader and calls `JuiceAgentBootstrap.start`, which loads
|
||||
`libagent.dll` (from `JuiceAgentNativeLibraryPath`) and initializes the JVMTI
|
||||
agent.
|
||||
2. The agent's `JarLoaderService` reads the `JarLoader.*` keys again, then the
|
||||
`JarLoader` module adds every `*.jar` in `InjectionDir` to the system class
|
||||
loader, loads `JarPath` and invokes `EntryClass.EntryMethod`.
|
||||
|
||||
`Enabled` and `InjectionDir` are used in `BuiltIn` mode only. Omitting a key
|
||||
silently falls back to a default, which is a common source of confusion:
|
||||
`InjectionDir` defaults to `./injection`, `JarPath` to `./Entry.jar`,
|
||||
`EntryClass` to `Example.Main` and `EntryMethod` to `start`.
|
||||
|
||||
`CustomJar` skips JuiceAgent-API and `libagent.dll` entirely: `libloader` adds
|
||||
`JarPath` itself to the system class loader and invokes the entry method. In this
|
||||
mode `Enabled` and `InjectionDir` are ignored, so any library the payload needs
|
||||
must be bundled inside the payload JAR (or already on the target's classpath).
|
||||
|
||||
### Q5 — Other libraries
|
||||
|
||||
- **Yes:** create `app/injection/` and copy the dependency JARs into it. Every
|
||||
`*.jar` there is loaded before the payload (`BuiltIn` mode only).
|
||||
- **No:** still create the empty directory if the config references it, or drop
|
||||
`InjectionDir` from the config.
|
||||
|
||||
### Q6 — Injection way
|
||||
|
||||
- **`injector.exe`:** nothing to prepare, continue to Step 4.
|
||||
- **JNI JavaInjector:** copy the whole `examples/inject-via-java-api/injector`
|
||||
directory to `app/injector/`, then build it:
|
||||
|
||||
```
|
||||
app\injector\build.bat
|
||||
```
|
||||
|
||||
That directory ships a prebuilt `JuiceAgent-JavaInjector-1.0-SNAPSHOT.jar`;
|
||||
`build.bat` merges the example's `JavaInjector.class` into it and sets the main
|
||||
class, so keep the JAR in place.
|
||||
|
||||
## Step 4 — Write config.toml
|
||||
|
||||
The file must be named exactly `config.toml` and placed in the directory that
|
||||
`libloader` treats as the **runtime directory** (see the table below). Do not
|
||||
rename it and do not scatter it across directories.
|
||||
|
||||
```toml
|
||||
# See docs/config.md for more information:
|
||||
# https://github.com/xiaozhou233/JuiceAgent/blob/main/docs/config.md
|
||||
|
||||
[JuiceAgent]
|
||||
Version = 2
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JarLoader]
|
||||
# BuiltIn: use the built-in jar loader (recommended; supports JuiceAgent-API)
|
||||
# CustomJar: load the JAR directly, without JuiceAgent-API
|
||||
# https://github.com/xiaozhou233/JuiceAgent/blob/main/docs/advanced.md#load-custom-api--directly-load-jar
|
||||
Enabled = true
|
||||
|
||||
# Q4
|
||||
Mode = "BuiltIn"
|
||||
|
||||
# BuiltIn mode only; Q5
|
||||
InjectionDir = "./injection"
|
||||
|
||||
# Q3
|
||||
JarPath = "./payload.jar"
|
||||
EntryClass = "Main"
|
||||
EntryMethod = "run"
|
||||
```
|
||||
|
||||
- `Version` must stay `2`. A mismatch makes the loader refuse to start.
|
||||
- `JuiceAgentNativeLibraryPath = ""` means "`libagent.dll` in the runtime
|
||||
directory". Change it to an absolute path only if `libagent.dll` lives
|
||||
elsewhere.
|
||||
- `Mode = "CustomJar"` requires `JarPath`, `EntryClass` and `EntryMethod`
|
||||
(there are no defaults in that mode); `Enabled` and `InjectionDir` are unused.
|
||||
- Paths starting with `./` are resolved against the runtime directory; absolute
|
||||
paths are used as-is.
|
||||
|
||||
### Which directory is the runtime directory?
|
||||
|
||||
This is where most failed setups go wrong: `libloader` does not take the config
|
||||
directory from the `injector.exe` command line.
|
||||
|
||||
| How you inject | Directory `config.toml` is read from |
|
||||
| --- | --- |
|
||||
| Interactive `injector.exe` (type the PID) | the **injector process's** current directory — so `cd app` first |
|
||||
| `injector.exe <pid> <libloader.dll> [libinject.dll]` | the **target JVM's** current directory (no directory is passed) |
|
||||
| JavaInjector (JNI) | the `config_path` you enter; an empty value falls back to the target JVM's working directory |
|
||||
|
||||
Consequences:
|
||||
|
||||
- With the argument form, `config.toml` **and** every `./` path inside it
|
||||
(`JarPath`, `InjectionDir`, `libagent.dll`) resolve against the target JVM's
|
||||
working directory.
|
||||
- If the user cannot control the target's working directory, use absolute paths
|
||||
in `config.toml` — including `JuiceAgentNativeLibraryPath`.
|
||||
- JNI injection is the most predictable option, because the config directory is
|
||||
passed explicitly.
|
||||
|
||||
## Step 5 — Run the injection
|
||||
|
||||
### 5.1 Use `injector.exe`
|
||||
|
||||
```
|
||||
cd app
|
||||
```
|
||||
|
||||
`cd app` matters: `injector.exe` loads `libinject.dll` **by name from the
|
||||
current directory**, and in interactive mode the current directory is also the
|
||||
runtime directory.
|
||||
|
||||
**Interactive:**
|
||||
|
||||
```
|
||||
.\injector.exe
|
||||
```
|
||||
|
||||
It prints the `jps -l` output, then `Input PID:`. Type the PID of the target JVM
|
||||
and press Enter.
|
||||
|
||||
> The program always ends with `Press any key to exit...` and waits for stdin.
|
||||
> If you drive it from a script, feed it a newline after the PID and do not wait
|
||||
> for the process to exit on its own.
|
||||
|
||||
**With arguments:**
|
||||
|
||||
```
|
||||
.\injector.exe <PID> "<path-to-app>\libloader.dll" "<path-to-app>\libinject.dll"
|
||||
```
|
||||
|
||||
The third argument is the path to **`libinject.dll`**, not a config directory.
|
||||
Omit it to let `injector.exe` load `libinject.dll` from the current directory.
|
||||
Remember that this form reads `config.toml` from the *target's* working
|
||||
directory (Step 4).
|
||||
|
||||
### 5.2 Use JNI JavaInjector
|
||||
|
||||
Run it from `app`, because the example loads `./libinject.dll`:
|
||||
|
||||
```
|
||||
java -cp injector\JuiceAgent-JavaInjector-1.0-SNAPSHOT.jar JavaInjector
|
||||
```
|
||||
|
||||
```
|
||||
PID: 1234
|
||||
Dll: <path-to-app>\libloader.dll
|
||||
config_path: <path-to-app>
|
||||
```
|
||||
|
||||
Enter the target PID, the path to `libloader.dll`, and the directory containing
|
||||
`config.toml`. Leaving `config_path` empty behaves like the argument form above:
|
||||
the runtime directory falls back to the **target JVM's** working directory, so
|
||||
always pass the directory explicitly.
|
||||
|
||||
## Step 6 — Verify
|
||||
|
||||
Verification has two independent sources. Do not confuse them: the
|
||||
`[JuiceAgent JarLoader]` progress lines are printed to the **target's stdout**,
|
||||
while the diagnostic logs are written to **files**.
|
||||
|
||||
**1. Target stdout** — this is the user-visible proof:
|
||||
|
||||
```
|
||||
[JuiceAgent API] RuntimeDir : <the directory actually used>
|
||||
[JuiceAgent JarLoader] Loading entry jar: ...
|
||||
[JuiceAgent JarLoader] Resolving class: Main
|
||||
[JuiceAgent JarLoader] Invoking method: Main.run
|
||||
[JuiceAgent JarLoader] Entry method invoked successfully.
|
||||
[Demo] Injection succeeded! Hello from JuiceAgent.
|
||||
```
|
||||
|
||||
The `[JuiceAgent API]` banner prints the effective runtime directory and the
|
||||
native library path, which is the fastest way to confirm the Step 4 rules.
|
||||
|
||||
**2. Log files** — two files are written **relative to the target JVM's working
|
||||
directory** and truncated on every injection:
|
||||
|
||||
| File | Look for |
|
||||
| --- | --- |
|
||||
| `libloader.log` | `DllMain: DLL_PROCESS_ATTACH, runtime_dir:` and `[PreLoad] Runtime directory:` |
|
||||
| `libagent.log` | `[JuiceAgent] Added JVMTI capabilities`, `[JarLoaderService] Loaded jar:`, and `JNI Exception occurred at:` when the payload itself throws |
|
||||
|
||||
If the target has no console (a service or a detached window), the stdout
|
||||
markers are invisible — verify through the log files instead.
|
||||
|
||||
Report the outcome to the user, including the exact `app` path, the injection
|
||||
command used, and the observed output.
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
| Symptom | Likely cause |
|
||||
| --- | --- |
|
||||
| Injection reports success but nothing happens | `config.toml` is not in the directory `libloader` actually used — see Step 4 |
|
||||
| `RuntimeDir :` in the banner is not `app` | The runtime directory fell back to the target JVM's working directory — see Step 4 |
|
||||
| `[JuiceAgent API] JuiceAgent library not found at: <path>` | `libagent.dll` could not be resolved — set an absolute `JuiceAgentNativeLibraryPath`, or fix the runtime directory |
|
||||
| `Failed to load injector library` / error 2 | `injector.exe` was not started from `app`, and no `libinject.dll` path was passed |
|
||||
| `Failed to open DLL file` | The `libloader.dll` path is wrong |
|
||||
| `libloader.log` / `libagent.log` seem missing | They are written in the target JVM's working directory, not your shell's |
|
||||
| Loader refuses to start | `[JuiceAgent] Version` is not `2` |
|
||||
| `Missing required config key: JarLoader.Mode` | `JarLoader.Mode` was omitted |
|
||||
| Errors about missing `JarPath` / `EntryClass` / `EntryMethod` | `Mode = "CustomJar"` requires all three |
|
||||
| `Failed to load jar: ...\Entry.jar` | `JarPath` was omitted and the default was used |
|
||||
| The JAR loads but the entry call fails | The method is not `public static` with no parameters, or `EntryClass` is not fully qualified |
|
||||
| `JNI Exception occurred at: CallStaticVoidMethod failed` | The payload threw — read the stack trace printed next to it |
|
||||
| The injected process hangs for ~30 s, then `Failed to attach to JVM!` | The target process is not a JVM (the loader retries 30 × 1 s before giving up) |
|
||||
| `jps` does not list the target | The target is 32-bit (JuiceAgent ships x64 only) or runs with different privileges |
|
||||
| Injection fails on an elevated target | Run `injector.exe` elevated too |
|
||||
| Antivirus flags the binaries | Expected false positive — see `docs/Antivirus-False-Positive.md` |
|
||||
| Native-access warning on JDK 22+ | The payload loads a native library; the target JVM needs `--enable-native-access=ALL-UNNAMED` |
|
||||
|
||||
## Done checklist
|
||||
|
||||
- [ ] A JDK 1.8+ with `javac`, `jar` and `jps` is available
|
||||
- [ ] `app/` contains all four JuiceAgent binaries
|
||||
- [ ] The payload JAR exists and its entry method is `public static` and takes no arguments
|
||||
- [ ] `config.toml` is in the directory `libloader` actually uses (Step 4), `Version = 2`, and every key matches the Q3–Q5 answers
|
||||
- [ ] The injection command reported success
|
||||
- [ ] The `[JuiceAgent API]` banner shows the expected `RuntimeDir`, and the payload output appears with no errors in the logs
|
||||
@@ -14,6 +14,13 @@ Welcome to join our QQ/Discord group for more information and support:
|
||||
- Discord: [JuiceDev](https://discord.gg/AQTnUyWNNJ)
|
||||
- QQ Group: 1103504356
|
||||
|
||||
> **New to JuiceAgent?** You do not have to wire up the injection by hand. A
|
||||
> coding agent such as OpenCode can do it for you: open this repository in the
|
||||
> agent and ask it to read [`QuickStartForAgents.md`](QuickStartForAgents.md) and
|
||||
> follow it. That guide covers the whole process — environment check, requirement
|
||||
> gathering, `config.toml`, injection and verification — and is written to be
|
||||
> executed by an agent. Simply tell the agent:
|
||||
> "Read `QuickStartForAgents.md` and follow it to inject my JAR."
|
||||
|
||||

|
||||

|
||||
|
||||
@@ -16,6 +16,9 @@ JuiceAgent 是一个基于 JVMTI 的高级注入框架,用于运行时 JAR 加
|
||||
- Discord:[JuiceDev](https://discord.gg/AQTnUyWNNJ)
|
||||
- QQ 群:1103504356
|
||||
|
||||
> **不知道该怎么用?** 不必手动折腾注入流程:用支持读写文件和执行命令的 AI Agent(例如 OpenCode)即可。在本仓库中打开 Agent,让它先阅读 [`QuickStartForAgents.md`](QuickStartForAgents.md) 并照着执行——该文档覆盖了完整流程(环境检查、需求确认、`config.toml`、注入与验证),并且是专门写给 Agent 执行的。你只需要告诉它:
|
||||
> "请阅读 `QuickStartForAgents.md`,并照着里面的步骤把我的 JAR 注入到目标 JVM。"
|
||||
|
||||

|
||||

|
||||

|
||||
|
||||
+1
-1
@@ -1,3 +1,3 @@
|
||||
Major=5
|
||||
Minor=0
|
||||
Patch=0
|
||||
Patch=1
|
||||
@@ -0,0 +1,143 @@
|
||||
# Changelog / 更新日志
|
||||
|
||||
本文件记录 JuiceAgent 的版本变更。更早的版本请见 [GitHub Releases](https://github.com/xiaozhou233/JuiceAgent/releases)。
|
||||
|
||||
This file records notable changes to JuiceAgent. For older releases, see [GitHub Releases](https://github.com/xiaozhou233/JuiceAgent/releases).
|
||||
|
||||
## 中文
|
||||
|
||||
### [5.0.1] - 2026-10-16
|
||||
|
||||
#### 🐛 修复
|
||||
|
||||
- 修复配置错误导致目标 JVM 崩溃:`libloader.dll` 是反射加载的,其展开表未被登记,C++ 异常在其中既无法 unwind 也无法捕获。现改为配置读取非抛出 + 解析走无异常模式,并以 `-fno-exceptions` 编译 libloader,任何会抛异常的代码在编译期即失败。
|
||||
|
||||
#### ✨ 新功能
|
||||
|
||||
- 事件总线新增 `subscribeFront` / `listenFront`(监听者顺序能力)。
|
||||
|
||||
#### 🔧 内部改动
|
||||
|
||||
- 用约 60 行类型安全事件总线替换 `eventpp`(移除 23 个 in-tree 头文件,约 144 KB)。
|
||||
- 移除无引用的 `MethodEntry` / `MethodExit` 事件定义。
|
||||
|
||||
#### 📝 文档
|
||||
|
||||
- 新增 `docs/config.md` 与 `docs/update/`;重写 `docs/advanced.md`;README 配置示例升级到 v2。
|
||||
|
||||
#### 🔁 CI
|
||||
|
||||
- 新增 GitHub Actions 工作流(构建 + 集成测试 + 打包 + 上传 artifact)与 `tests/run-tests.ps1`。
|
||||
- 构建改为静态链接 C/C++ 运行时。
|
||||
|
||||
### [5.0.0] - 2026-10-15
|
||||
|
||||
#### ⚠️ 破坏性变更
|
||||
|
||||
- 配置 schema 由 v1 升级到 v2(`CONFIG_VERSION = 2`):旧配置会被版本校验拒绝,需按 [v5.0.0 发布说明](v5.0.0.md) 迁移。
|
||||
|
||||
#### ✨ 新功能
|
||||
|
||||
- 新增 `JarLoader.Mode`:`BuiltIn`(内置 JuiceAgent-API)与 `CustomJar`(直接加载自定义 JAR)两种加载模式。
|
||||
- 新增 `JarLoader.Enabled` 开关,可在 `BuiltIn` 模式下关闭 JarLoader 模块。
|
||||
- 新增配置解析与访问的错误日志。
|
||||
|
||||
#### 🐛 修复
|
||||
|
||||
- 自定义 JAR 入口类名规范化(`.` → `/`),修复 `NoClassDefFoundError`。
|
||||
- `tests/copy-bin.bat` 在被占用时会静默失败的问题。
|
||||
- `GetClassBytesByName` 集成测试未先加载目标类的问题。
|
||||
|
||||
#### 🔧 内部改动
|
||||
|
||||
- TOML 解析器由 `toml11` 迁移到 `toml++`。
|
||||
- 移除未使用的 `LoaderConfig` 相关辅助函数。
|
||||
|
||||
#### 📝 文档
|
||||
|
||||
- 新增 `docs/config.md`(v2 配置参考)。
|
||||
- 重写 `docs/advanced.md`;README 与示例文档升级到 v2。
|
||||
|
||||
### [4.1.2] - 2026-10-11
|
||||
|
||||
#### ✨ 新功能
|
||||
|
||||
- 新增基于版本的打包脚本(`script/package.bat` + `script/package.cmake`)。
|
||||
- `Version.txt` 改为 `Major` / `Minor` / `Patch` 结构化格式。
|
||||
|
||||
#### 🐛 修复
|
||||
|
||||
- 修复 `getClassBytesByName` 在部分环境下无法获取类的问题(改用 JVMTI 的 `findLoadedClass`)。
|
||||
|
||||
#### 📝 文档
|
||||
|
||||
- 新增 `docs/Inject.md`;修正文档路径。
|
||||
|
||||
## English
|
||||
|
||||
### [5.0.1] - 2026-10-16
|
||||
|
||||
#### 🐛 Fixes
|
||||
|
||||
- Fix a config error crashing the target JVM: `libloader.dll` is reflectively loaded, so its unwind tables are never registered and a C++ exception cannot be unwound or caught there. Config reads are now non-throwing, parsing runs in non-throwing mode, and libloader is compiled with `-fno-exceptions` so exception-capable code fails the build.
|
||||
|
||||
#### ✨ Features
|
||||
|
||||
- New `subscribeFront` / `listenFront` listener-ordering support on the event bus.
|
||||
|
||||
#### 🔧 Internal
|
||||
|
||||
- Replace `eventpp` with a ~60-line type-safe event bus (removes 23 in-tree headers, ~144 KB).
|
||||
- Remove the unreferenced `MethodEntry` / `MethodExit` event definitions.
|
||||
|
||||
#### 📝 Docs
|
||||
|
||||
- Add `docs/config.md` and `docs/update/`; rewrite `docs/advanced.md`; update the README config examples to v2.
|
||||
|
||||
#### 🔁 CI
|
||||
|
||||
- Add a GitHub Actions workflow (build + integration tests + package + artifact upload) and `tests/run-tests.ps1`.
|
||||
- Link the C/C++ runtime statically.
|
||||
|
||||
### [5.0.0] - 2026-10-15
|
||||
|
||||
#### ⚠️ Breaking Changes
|
||||
|
||||
- Configuration schema upgraded from v1 to v2 (`CONFIG_VERSION = 2`): older configs are rejected by the version check and must be migrated (see the [v5.0.0 release notes](v5.0.0.md)).
|
||||
|
||||
#### ✨ Features
|
||||
|
||||
- New `JarLoader.Mode`: `BuiltIn` (embedded JuiceAgent-API) and `CustomJar` (load your own JAR directly).
|
||||
- New `JarLoader.Enabled` switch to turn the JarLoader module off in `BuiltIn` mode.
|
||||
- Added logging for config parse and access errors.
|
||||
|
||||
#### 🐛 Fixes
|
||||
|
||||
- Normalize custom-jar entry class names (`.` → `/`), fixing `NoClassDefFoundError`.
|
||||
- `tests/copy-bin.bat` no longer fails silently when a target file is locked.
|
||||
- `GetClassBytesByName` integration test now loads the target class first.
|
||||
|
||||
#### 🔧 Internal
|
||||
|
||||
- Migrate the TOML parser from `toml11` to `toml++`.
|
||||
- Remove the unused `LoaderConfig` helpers.
|
||||
|
||||
#### 📝 Docs
|
||||
|
||||
- Add `docs/config.md` (v2 configuration reference).
|
||||
- Rewrite `docs/advanced.md`; update the READMEs and example guides to v2.
|
||||
|
||||
### [4.1.2] - 2026-10-11
|
||||
|
||||
#### ✨ Features
|
||||
|
||||
- Add a version-based packaging script (`script/package.bat` + `script/package.cmake`).
|
||||
- `Version.txt` now uses a structured `Major` / `Minor` / `Patch` format.
|
||||
|
||||
#### 🐛 Fixes
|
||||
|
||||
- Fix `getClassBytesByName` failing in some environments (use JVMTI `findLoadedClass`).
|
||||
|
||||
#### 📝 Docs
|
||||
|
||||
- Add `docs/Inject.md`; fix documentation paths.
|
||||
@@ -0,0 +1,163 @@
|
||||
# JuiceAgent 5.0.0 Release Notes
|
||||
|
||||
## 中文
|
||||
|
||||
### ⚠️ 破坏性变更
|
||||
|
||||
- **配置文件升级到 v2**:`CONFIG_VERSION` 提升为 `2`。加载器启动时会校验 `JuiceAgent.Version`,版本不匹配将直接拒绝加载,因此旧版 v1 配置必须先迁移。
|
||||
|
||||
v1(不再支持):
|
||||
|
||||
```toml
|
||||
[JuiceAgent]
|
||||
Version = 1
|
||||
|
||||
[JuiceAgent.Loader]
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JuiceAgent.Modules]
|
||||
|
||||
[JuiceAgent.Modules.JarLoader]
|
||||
Enabled = true
|
||||
InjectionDir = "./injection"
|
||||
JarPath = "./MyCustomJar.jar"
|
||||
EntryClass = "Example.Main"
|
||||
EntryMethod = "run"
|
||||
```
|
||||
|
||||
v2(当前):
|
||||
|
||||
```toml
|
||||
[JuiceAgent]
|
||||
Version = 2
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JarLoader]
|
||||
Enabled = true
|
||||
Mode = "BuiltIn"
|
||||
InjectionDir = "./injection"
|
||||
JarPath = "./MyCustomJar.jar"
|
||||
EntryClass = "Example.Main"
|
||||
EntryMethod = "run"
|
||||
```
|
||||
|
||||
迁移要点:
|
||||
|
||||
- `Version` 由 `1` 改为 `2`。
|
||||
- `JuiceAgentNativeLibraryPath` 由 `[JuiceAgent.Loader]` 移到 `[JuiceAgent]`。
|
||||
- 原 `[JuiceAgent.Modules.JarLoader]` 展平为顶层 `[JarLoader]`。
|
||||
- 新增必填项 `Mode`(`BuiltIn` 或 `CustomJar`)。
|
||||
- 完整说明见 [docs/config.md](../config.md)。
|
||||
|
||||
### ✨ 新功能
|
||||
|
||||
- 新增两种 JAR 加载模式(`JarLoader.Mode`):
|
||||
- `BuiltIn`(推荐):加载器解出内嵌的 JuiceAgent-API jar 并注入系统类加载器,agent 通过 API 引导,再由 JarLoader 模块加载目标 JAR 并调用入口方法。
|
||||
- `CustomJar`:不再使用 JuiceAgent-API,加载器直接把 `JarPath` 加入系统类加载器并调用 `EntryClass.EntryMethod`,便于接入自定义引导。
|
||||
- 新增 `JarLoader.Enabled` 开关(默认 `false`),可在 `BuiltIn` 模式下关闭 JarLoader 模块。
|
||||
- 新增配置解析与访问的错误日志:配置缺失或类型不匹配时会给出明确提示。
|
||||
|
||||
### 🐛 修复
|
||||
|
||||
- 修复自定义 JAR 入口类查找失败:将类名规范化为 JNI 内部形式(`.` → `/`),`FindClass` 现在能正确解析 `Example.Main` 这类 Java 二进制名(修复 `NoClassDefFoundError`)。
|
||||
- 修复集成测试的二进制拷贝脚本 `tests/copy-bin.bat`:改用原生 `COPY /Y`,在目标文件被占用时明确报错,不再静默失败导致测试使用旧二进制。
|
||||
- 修复 `GetClassBytesByName` 集成测试:先加载目标类再按名获取字节码(该 API 只解析已加载的类)。
|
||||
|
||||
### 🔧 内部改动
|
||||
|
||||
- TOML 解析器由 `toml11` 迁移到 `toml++`。
|
||||
- 移除未使用的 `LoaderConfig` / `get_loader_config` / `print_loader_config`(其中仍引用着 v1 的配置键)。
|
||||
|
||||
### 📝 文档
|
||||
|
||||
- 新增 [docs/config.md](../config.md):完整的 v2 配置参考(含两种模式流程与各键默认值)。
|
||||
- 重写 [docs/advanced.md](../advanced.md):改为描述 `JarLoader.Mode = "CustomJar"`,移除已废弃的 `JUICEAGENT_API_*` 环境变量说明。
|
||||
- README(中/英)的 Quick Start 配置示例升级到 v2 并链接 `docs/config.md`;示例列表补充 `inject-via-java-api`。
|
||||
- 同步更新 `examples/inject-via-java-api` 的说明文档(中/英,md/txt)。
|
||||
|
||||
---
|
||||
|
||||
## English
|
||||
|
||||
### ⚠️ Breaking Changes
|
||||
|
||||
- **Configuration upgraded to v2**: `CONFIG_VERSION` is now `2`. The loader validates `JuiceAgent.Version` at startup and refuses to load on a mismatch, so existing v1 configs must be migrated first.
|
||||
|
||||
v1 (no longer supported):
|
||||
|
||||
```toml
|
||||
[JuiceAgent]
|
||||
Version = 1
|
||||
|
||||
[JuiceAgent.Loader]
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JuiceAgent.Modules]
|
||||
|
||||
[JuiceAgent.Modules.JarLoader]
|
||||
Enabled = true
|
||||
InjectionDir = "./injection"
|
||||
JarPath = "./MyCustomJar.jar"
|
||||
EntryClass = "Example.Main"
|
||||
EntryMethod = "run"
|
||||
```
|
||||
|
||||
v2 (current):
|
||||
|
||||
```toml
|
||||
[JuiceAgent]
|
||||
Version = 2
|
||||
JuiceAgentNativeLibraryPath = ""
|
||||
|
||||
[JarLoader]
|
||||
Enabled = true
|
||||
Mode = "BuiltIn"
|
||||
InjectionDir = "./injection"
|
||||
JarPath = "./MyCustomJar.jar"
|
||||
EntryClass = "Example.Main"
|
||||
EntryMethod = "run"
|
||||
```
|
||||
|
||||
Migration:
|
||||
|
||||
- `Version`: `1` → `2`.
|
||||
- `JuiceAgentNativeLibraryPath` moved from `[JuiceAgent.Loader]` to `[JuiceAgent]`.
|
||||
- `[JuiceAgent.Modules.JarLoader]` flattened to a top-level `[JarLoader]`.
|
||||
- New required key `Mode` (`BuiltIn` or `CustomJar`).
|
||||
- Full reference: [docs/config.md](../config.md).
|
||||
|
||||
### ✨ Features
|
||||
|
||||
- Two JAR loading modes (`JarLoader.Mode`):
|
||||
- `BuiltIn` (recommended): the loader extracts the embedded JuiceAgent-API jar and adds it to the system class loader, the agent bootstraps it, and the JarLoader module loads the target JAR and invokes its entry method.
|
||||
- `CustomJar`: JuiceAgent-API is not used; the loader adds `JarPath` to the system class loader and invokes `EntryClass.EntryMethod`, so you can plug in your own bootstrap.
|
||||
- New `JarLoader.Enabled` switch (default `false`) to turn the JarLoader module off in `BuiltIn` mode.
|
||||
- New logging for config parse and access errors, with clear messages when a key is missing or has the wrong type.
|
||||
|
||||
### 🐛 Fixes
|
||||
|
||||
- Fix entry class lookup for custom jars: class names are normalized to the JNI internal form (`.` → `/`) so `FindClass` resolves Java binary names like `Example.Main` (fixes `NoClassDefFoundError`).
|
||||
- Fix the integration test helper `tests/copy-bin.bat`: it now uses native `COPY /Y` and reports a clear error when a target file is locked, instead of failing silently and testing against stale binaries.
|
||||
- Fix the `GetClassBytesByName` integration test: load the target class before looking it up by name (the API only resolves already-loaded classes).
|
||||
|
||||
### 🔧 Internal
|
||||
|
||||
- Migrate the TOML parser from `toml11` to `toml++`.
|
||||
- Remove the unused `LoaderConfig` / `get_loader_config` / `print_loader_config` (which still referenced a v1 config key).
|
||||
|
||||
### 📝 Docs
|
||||
|
||||
- Add [docs/config.md](../config.md): the complete v2 configuration reference (mode workflows and key defaults).
|
||||
- Rewrite [docs/advanced.md](../advanced.md) around `JarLoader.Mode = "CustomJar"`, dropping the removed `JUICEAGENT_API_*` environment variables.
|
||||
- Update the Quick Start config example in both READMEs to v2 and link `docs/config.md`; add `inject-via-java-api` to the examples list.
|
||||
- Update the `examples/inject-via-java-api` guides (EN/ZH, md/txt).
|
||||
|
||||
---
|
||||
|
||||
如果您在使用过程中遇到问题,可以加入我们的QQ/Discord群组
|
||||
If you encounter any issues during use, you can join our QQ/Discord group
|
||||
|
||||
Discord: [JuiceDev](https://discord.gg/AQTnUyWNNJ)
|
||||
QQ群: 1103504356
|
||||
|
||||
**Full Changelog**: https://github.com/xiaozhou233/JuiceAgent/compare/v4.1.2...v5.0.0
|
||||
@@ -0,0 +1,77 @@
|
||||
# JuiceAgent 5.0.1 Release Notes
|
||||
|
||||
## 中文
|
||||
|
||||
### 🐛 修复
|
||||
|
||||
- **修复配置错误导致目标 JVM 崩溃**:当 `config.toml` 缺少必填项(例如 `JarLoader.Mode`)或语法不合法时,被注入的目标 JVM 会以 `EXCEPTION_ILLEGAL_INSTRUCTION` 崩溃。
|
||||
|
||||
根因是 `libloader.dll` 采用**反射加载(手动映射)**,其展开表(unwind tables)不会被系统登记,因此在其中抛出的 C++ 异常**既无法 unwind 也无法被 catch**——`try/catch` 在这里是无效的。修复方式:
|
||||
|
||||
- 配置读取全部改为**非抛出**:缺 key / 类型不符只记日志并**提前返回**,报错精确到具体 key;
|
||||
- 配置解析在**无异常模式**下进行(`toml::parse_result`),畸形 TOML 也只报错、不崩;
|
||||
- `libloader` 目标以 **`-fno-exceptions`** 编译,以后任何会抛异常的代码都会在**编译期**失败。
|
||||
|
||||
### ✨ 新功能
|
||||
|
||||
- 事件总线新增 `subscribeFront` / `listenFront`:可将监听者插入队首优先执行(为后续 transformer 管线预留的顺序能力)。
|
||||
|
||||
### 🔧 内部改动
|
||||
|
||||
- 用约 60 行的**类型安全**事件总线替换第三方库 `eventpp`:监听者按事件类型注册与调用,不再有 `const void*` 强转;同时移除 in-tree 的 eventpp 头文件(23 个文件,约 144 KB)及其 license。
|
||||
- 移除无引用的 `MethodEntry` / `MethodExit` 事件定义。
|
||||
|
||||
### 📝 文档
|
||||
|
||||
- 新增 [docs/config.md](../config.md)(v2 配置完整参考)与 [docs/update/](../update/)(发布说明 + CHANGELOG)。
|
||||
- 重写 [docs/advanced.md](../advanced.md);README(中/英)配置示例升级到 v2。
|
||||
|
||||
### 🔁 CI
|
||||
|
||||
- 新增 GitHub Actions 工作流 `.github/workflows/ci.yml`:在 `windows-latest` 上用 MinGW-w64 + Ninja 构建、运行集成测试、打包,并把 `JuiceAgent_v*.zip` 作为 artifact 上传(保留 14 天)。
|
||||
- 新增可复用的测试脚本 `tests/run-tests.ps1`:编译 → 刷新 `tests/resources` → 逐条运行并按**输出断言**(测试程序即使失败也返回 0,所以只看退出码不够)。
|
||||
- 构建改为**静态链接** C/C++ 运行时(与本地 w64devkit 一致),避免运行时 DLL 版本不匹配导致 `UnsatisfiedLinkError`。
|
||||
|
||||
---
|
||||
|
||||
## English
|
||||
|
||||
### 🐛 Fixes
|
||||
|
||||
- **Fix a config error crashing the target JVM**: when `config.toml` was missing a required key (e.g. `JarLoader.Mode`) or was malformed, the injected target JVM crashed with `EXCEPTION_ILLEGAL_INSTRUCTION`.
|
||||
|
||||
The root cause is that `libloader.dll` is **reflectively loaded (manually mapped)**, so its unwind tables are never registered with the OS and a C++ exception thrown inside it can be neither unwound nor caught - `try/catch` simply cannot work there. The fix:
|
||||
|
||||
- configuration reads are now **non-throwing**: a missing key or type mismatch is logged and the loader **returns early**, with the error naming the exact key;
|
||||
- config parsing happens in **non-throwing mode** (`toml::parse_result`), so malformed TOML is reported instead of crashing;
|
||||
- the `libloader` target is compiled with **`-fno-exceptions`**, so any exception-capable code added later fails the **build** instead of crashing at runtime.
|
||||
|
||||
### ✨ Features
|
||||
|
||||
- New `subscribeFront` / `listenFront` on the event bus, to register a listener ahead of the existing ones (ordering support for a future transformer pipeline).
|
||||
|
||||
### 🔧 Internal
|
||||
|
||||
- Replace the `eventpp` dependency with a ~60-line, **type-safe** event bus: listeners are registered and invoked by concrete event type, with no `const void*` casting; the in-tree eventpp headers (23 files, ~144 KB) and their license are removed.
|
||||
- Remove the unreferenced `MethodEntry` / `MethodExit` event definitions.
|
||||
|
||||
### 📝 Docs
|
||||
|
||||
- Add [docs/config.md](../config.md) (full v2 configuration reference) and [docs/update/](../update/) (release notes + changelog).
|
||||
- Rewrite [docs/advanced.md](../advanced.md); update the config examples in both READMEs to v2.
|
||||
|
||||
### 🔁 CI
|
||||
|
||||
- Add a GitHub Actions workflow (`.github/workflows/ci.yml`) that builds with MinGW-w64 + Ninja on `windows-latest`, runs the integration tests, packages the release, and uploads `JuiceAgent_v*.zip` as a build artifact (14-day retention).
|
||||
- Add a reusable test runner, `tests/run-tests.ps1`, which compiles the modules, refreshes `tests/resources`, then runs every test and asserts on its **output** (the test programs exit 0 even on failure, so exit codes are not enough).
|
||||
- Link the C/C++ runtime **statically** (matching the local w64devkit build) so the DLLs do not fail to load because of a mismatched runtime DLL on the machine.
|
||||
|
||||
---
|
||||
|
||||
如果您在使用过程中遇到问题,可以加入我们的QQ/Discord群组
|
||||
If you encounter any issues during use, you can join our QQ/Discord group
|
||||
|
||||
Discord: [JuiceDev](https://discord.gg/AQTnUyWNNJ)
|
||||
QQ群: 1103504356
|
||||
|
||||
**Full Changelog**: https://github.com/xiaozhou233/JuiceAgent/compare/v5.0.0...v5.0.1
|
||||
@@ -3,5 +3,5 @@ out/
|
||||
|
||||
# Do not ignore root build artifacts:
|
||||
!new_target.class
|
||||
!playload.jar
|
||||
!payload.jar
|
||||
!target.jar
|
||||
@@ -10,10 +10,10 @@
|
||||
| `config.toml` | Injection config |
|
||||
| `build.bat` | Build script |
|
||||
| `run.bat` | Run target JVM |
|
||||
| `playload.jar` | JAR to inject (built by `build.bat`) |
|
||||
| `payload.jar` | JAR to inject (built by `build.bat`) |
|
||||
| `target.jar` | Target JVM program (built by `build.bat`) |
|
||||
| `new_target.class` | Retransformed bytecode (built by `build.bat`) |
|
||||
| `playload/` | Payload source |
|
||||
| `payload/` | Payload source |
|
||||
| `target/` | Target source |
|
||||
| `new_target/` | Modified copy of target source |
|
||||
|
||||
@@ -31,7 +31,7 @@ Hello!
|
||||
Retransformed!
|
||||
```
|
||||
|
||||
This example injects `playload.jar` into a running JVM. The payload reads
|
||||
This example injects `payload.jar` into a running JVM. The payload reads
|
||||
`new_target.class` from its own JAR and calls
|
||||
`JuiceAgent.retransformClassByName("target", ...)` to swap the already-loaded
|
||||
`target` class on the fly. After that, `say()` starts printing the new message
|
||||
@@ -41,14 +41,14 @@ without restarting the JVM.
|
||||
|
||||
### 1. Build (optional)
|
||||
|
||||
`playload.jar` and `target.jar` are already included by default.
|
||||
If you modified `playload/`, `target/` or `new_target/`, run:
|
||||
`payload.jar` and `target.jar` are already included by default.
|
||||
If you modified `payload/`, `target/` or `new_target/`, run:
|
||||
|
||||
```
|
||||
build.bat
|
||||
```
|
||||
|
||||
to regenerate `playload.jar`, `target.jar` and `new_target.class`.
|
||||
to regenerate `payload.jar`, `target.jar` and `new_target.class`.
|
||||
|
||||
### 2. Run the target JVM
|
||||
|
||||
@@ -77,8 +77,8 @@ Input PID: 6644
|
||||
Go back to the target window. Injection succeeded if you see:
|
||||
|
||||
```
|
||||
Playload loaded!
|
||||
Playload executed!
|
||||
Payload loaded!
|
||||
Payload executed!
|
||||
```
|
||||
|
||||
and the output of `say()` changes from `Hello!` to:
|
||||
@@ -92,8 +92,8 @@ Retransformed!
|
||||
|
||||
| Key | Description |
|
||||
| --- | --- |
|
||||
| `JarPath` | JAR path to inject (default: `./playload.jar`) |
|
||||
| `EntryClass` | Entry class (default: `playload`) |
|
||||
| `JarPath` | JAR path to inject (default: `./payload.jar`) |
|
||||
| `EntryClass` | Entry class (default: `payload`) |
|
||||
| `EntryMethod` | Entry method, must be `public static void entry()` |
|
||||
|
||||
## Troubleshooting
|
||||
@@ -102,8 +102,8 @@ Retransformed!
|
||||
Install a JDK and add its `bin` directory to `PATH`.
|
||||
- `injector.exe` reports injection failure:
|
||||
Make sure the target JVM is running and the PID is correct.
|
||||
- No `Playload loaded!` output appears:
|
||||
- No `Payload loaded!` output appears:
|
||||
Check `libagent.log` and `libloader.log` in this directory for the cause.
|
||||
- `say()` output does not change:
|
||||
Make sure `build.bat` was run after editing `new_target/`, and that
|
||||
`new_target.class` inside `playload.jar` is up to date.
|
||||
`new_target.class` inside `payload.jar` is up to date.
|
||||
@@ -9,10 +9,10 @@ Directory Files:
|
||||
config.toml - injection config
|
||||
build.bat - build script
|
||||
run.bat - run target JVM
|
||||
playload.jar - JAR to inject (built by build.bat)
|
||||
payload.jar - JAR to inject (built by build.bat)
|
||||
target.jar - target JVM program (built by build.bat)
|
||||
new_target.class - retransformed bytecode (built by build.bat)
|
||||
playload/ - payload source
|
||||
payload/ - payload source
|
||||
target/ - target source
|
||||
new_target/ - modified copy of target source
|
||||
|
||||
@@ -26,7 +26,7 @@ The target class "target" has a method say() that prints:
|
||||
new_target/target.java is a modified copy that also prints:
|
||||
Retransformed!
|
||||
|
||||
This example injects playload.jar into a running JVM. The payload reads
|
||||
This example injects payload.jar into a running JVM. The payload reads
|
||||
new_target.class from its own JAR and calls
|
||||
JuiceAgent.retransformClassByName("target", ...) to swap the already-loaded
|
||||
"target" class on the fly. After that, say() starts printing the new message
|
||||
@@ -37,10 +37,10 @@ without restarting the JVM.
|
||||
============================================
|
||||
|
||||
1. Build (optional)
|
||||
playload.jar and target.jar are already included by default.
|
||||
If you modified playload/, target/ or new_target/, run:
|
||||
payload.jar and target.jar are already included by default.
|
||||
If you modified payload/, target/ or new_target/, run:
|
||||
build.bat
|
||||
to regenerate playload.jar, target.jar and new_target.class.
|
||||
to regenerate payload.jar, target.jar and new_target.class.
|
||||
|
||||
2. Run the target JVM
|
||||
Double-click run.bat (or run: java -jar target.jar). A black window
|
||||
@@ -57,8 +57,8 @@ without restarting the JVM.
|
||||
|
||||
4. Verify
|
||||
Go back to the target window. Injection succeeded if you see:
|
||||
Playload loaded!
|
||||
Playload executed!
|
||||
Payload loaded!
|
||||
Payload executed!
|
||||
and the output of say() changes from "Hello!" to:
|
||||
Hello!
|
||||
Retransformed!
|
||||
@@ -67,8 +67,8 @@ without restarting the JVM.
|
||||
Config / config.toml
|
||||
============================================
|
||||
|
||||
JarPath - JAR path to inject (default: ./playload.jar)
|
||||
EntryClass - Entry class (default: playload)
|
||||
JarPath - JAR path to inject (default: ./payload.jar)
|
||||
EntryClass - Entry class (default: payload)
|
||||
EntryMethod - Entry method, must be public static void entry()
|
||||
|
||||
============================================
|
||||
@@ -79,8 +79,8 @@ without restarting the JVM.
|
||||
Install a JDK and add its bin directory to PATH.
|
||||
- injector.exe reports injection failure:
|
||||
Make sure the target JVM is running and the PID is correct.
|
||||
- No "Playload loaded!" output appears:
|
||||
- No "Payload loaded!" output appears:
|
||||
Check libagent.log and libloader.log in this directory for the cause.
|
||||
- say() output does not change:
|
||||
Make sure build.bat was run after editing new_target/, and that
|
||||
new_target.class inside playload.jar is up to date.
|
||||
new_target.class inside payload.jar is up to date.
|
||||
@@ -1,13 +1,13 @@
|
||||
@echo off
|
||||
setlocal
|
||||
|
||||
set "API_JAR=playload\JuiceAgent-API-1.4.1+build.1.jar"
|
||||
set "PAYLOAD_JAR=playload.jar"
|
||||
set "API_JAR=payload\JuiceAgent-API-1.4.1+build.1.jar"
|
||||
set "PAYLOAD_JAR=payload.jar"
|
||||
set "TARGET_JAR=target.jar"
|
||||
|
||||
set "OUT=out"
|
||||
set "OUT_NT=%OUT%\new_target"
|
||||
set "OUT_PL=%OUT%\playload"
|
||||
set "OUT_PL=%OUT%\payload"
|
||||
set "OUT_TG=%OUT%\target"
|
||||
|
||||
set "NEW_TARGET_CLASS=new_target.class"
|
||||
@@ -29,8 +29,8 @@ if errorlevel 1 goto :error
|
||||
copy /y "%OUT_NT%\new_target.class" "%NEW_TARGET_CLASS%"
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
echo === Compiling playload ===
|
||||
javac -encoding UTF-8 --release 8 -cp "%API_JAR%" -d "%OUT_PL%" playload\playload.java
|
||||
echo === Compiling payload ===
|
||||
javac -encoding UTF-8 --release 8 -cp "%API_JAR%" -d "%OUT_PL%" payload\payload.java
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
echo === Compiling target ===
|
||||
@@ -38,7 +38,7 @@ javac -encoding UTF-8 --release 8 -d "%OUT_TG%" target\target.java
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
echo === Packaging payload jar ===
|
||||
jar --create --file "%PAYLOAD_JAR%" -C "%OUT_PL%" playload.class
|
||||
jar --create --file "%PAYLOAD_JAR%" -C "%OUT_PL%" payload.class
|
||||
if errorlevel 1 goto :error
|
||||
|
||||
echo === Packaging target jar ===
|
||||
|
||||
@@ -14,6 +14,6 @@ Mode = "BuiltIn"
|
||||
|
||||
# InjectionDir only works when Mode is BuiltIn
|
||||
InjectionDir = "./injection"
|
||||
JarPath = "./playload.jar"
|
||||
EntryClass = "playload"
|
||||
JarPath = "./payload.jar"
|
||||
EntryClass = "payload"
|
||||
EntryMethod = "entry"
|
||||
Binary file not shown.
File renamed without changes.
+3
-3
@@ -1,8 +1,8 @@
|
||||
import cn.xiaozhou233.juiceagent.api.JuiceAgent;
|
||||
|
||||
public class playload {
|
||||
public class payload {
|
||||
public static void entry() throws java.io.IOException {
|
||||
System.out.println("Playload loaded!");
|
||||
System.out.println("Payload loaded!");
|
||||
|
||||
java.io.InputStream in = new java.io.FileInputStream("new_target.class");
|
||||
java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
|
||||
@@ -20,6 +20,6 @@ public class playload {
|
||||
bytes.length
|
||||
);
|
||||
|
||||
System.out.println("Playload executed!");
|
||||
System.out.println("Payload executed!");
|
||||
}
|
||||
}
|
||||
Binary file not shown.
@@ -10,10 +10,10 @@
|
||||
| `config.toml` | 注入配置 |
|
||||
| `build.bat` | 构建脚本 |
|
||||
| `run.bat` | 运行目标 JVM |
|
||||
| `playload.jar` | 注入用的 JAR(由 `build.bat` 生成) |
|
||||
| `payload.jar` | 注入用的 JAR(由 `build.bat` 生成) |
|
||||
| `target.jar` | 目标 JVM 程序(由 `build.bat` 生成) |
|
||||
| `new_target.class` | 重变换后的字节码(由 `build.bat` 生成) |
|
||||
| `playload/` | payload 源码 |
|
||||
| `payload/` | payload 源码 |
|
||||
| `target/` | 目标类源码 |
|
||||
| `new_target/` | target 的修改版源码 |
|
||||
|
||||
@@ -31,7 +31,7 @@ Hello!
|
||||
Retransformed!
|
||||
```
|
||||
|
||||
本示例把 `playload.jar` 注入到运行中的 JVM。payload 从自己的 JAR 中读取
|
||||
本示例把 `payload.jar` 注入到运行中的 JVM。payload 从自己的 JAR 中读取
|
||||
`new_target.class`,调用 `JuiceAgent.retransformClassByName("target", ...)`
|
||||
在运行时动态替换已加载的 `target` 类。之后 `say()` 无需重启 JVM 就会输出新内容。
|
||||
|
||||
@@ -39,14 +39,14 @@ Retransformed!
|
||||
|
||||
### 1. 构建(可选)
|
||||
|
||||
`playload.jar` 和 `target.jar` 默认已包含。
|
||||
如果修改了 `playload/`、`target/` 或 `new_target/`,运行:
|
||||
`payload.jar` 和 `target.jar` 默认已包含。
|
||||
如果修改了 `payload/`、`target/` 或 `new_target/`,运行:
|
||||
|
||||
```
|
||||
build.bat
|
||||
```
|
||||
|
||||
重新生成 `playload.jar`、`target.jar` 和 `new_target.class`。
|
||||
重新生成 `payload.jar`、`target.jar` 和 `new_target.class`。
|
||||
|
||||
### 2. 运行目标 JVM
|
||||
|
||||
@@ -72,8 +72,8 @@ Input PID: 6644
|
||||
回到目标窗口,注入成功应看到:
|
||||
|
||||
```
|
||||
Playload loaded!
|
||||
Playload executed!
|
||||
Payload loaded!
|
||||
Payload executed!
|
||||
```
|
||||
|
||||
并且 `say()` 的输出从 `Hello!` 变为:
|
||||
@@ -87,8 +87,8 @@ Retransformed!
|
||||
|
||||
| 配置项 | 说明 |
|
||||
| --- | --- |
|
||||
| `JarPath` | 注入的 JAR 路径(默认 `./playload.jar`) |
|
||||
| `EntryClass` | 入口类(默认 `playload`) |
|
||||
| `JarPath` | 注入的 JAR 路径(默认 `./payload.jar`) |
|
||||
| `EntryClass` | 入口类(默认 `payload`) |
|
||||
| `EntryMethod` | 入口方法,必须为 `public static void entry()` |
|
||||
|
||||
## 常见问题
|
||||
@@ -97,8 +97,8 @@ Retransformed!
|
||||
安装 JDK 并将 `bin` 目录加入 `PATH`。
|
||||
- `injector.exe` 提示注入失败:
|
||||
确认目标 JVM 正在运行且 PID 正确。
|
||||
- 没有出现 `Playload loaded!` 输出:
|
||||
- 没有出现 `Payload loaded!` 输出:
|
||||
查看本目录下的 `libagent.log` 和 `libloader.log` 定位原因。
|
||||
- `say()` 输出没有变化:
|
||||
确认修改 `new_target/` 后重新运行过 `build.bat`,且 `playload.jar` 内的
|
||||
确认修改 `new_target/` 后重新运行过 `build.bat`,且 `payload.jar` 内的
|
||||
`new_target.class` 是最新的。
|
||||
@@ -9,10 +9,10 @@
|
||||
config.toml - 注入配置
|
||||
build.bat - 构建脚本
|
||||
run.bat - 运行目标 JVM
|
||||
playload.jar - 注入用的 JAR (由 build.bat 生成)
|
||||
payload.jar - 注入用的 JAR (由 build.bat 生成)
|
||||
target.jar - 目标 JVM 程序 (由 build.bat 生成)
|
||||
new_target.class - 重变换后的字节码 (由 build.bat 生成)
|
||||
playload/ - payload 源码
|
||||
payload/ - payload 源码
|
||||
target/ - 目标类源码
|
||||
new_target/ - target 的修改版源码
|
||||
|
||||
@@ -26,7 +26,7 @@
|
||||
new_target/target.java 是它的修改版, 额外打印:
|
||||
Retransformed!
|
||||
|
||||
本示例把 playload.jar 注入到运行中的 JVM。payload 从自己的 JAR 中读取
|
||||
本示例把 payload.jar 注入到运行中的 JVM。payload 从自己的 JAR 中读取
|
||||
new_target.class, 调用 JuiceAgent.retransformClassByName("target", ...)
|
||||
在运行时动态替换已加载的 "target" 类。之后 say() 无需重启 JVM 就会输出新内容。
|
||||
|
||||
@@ -35,10 +35,10 @@ new_target.class, 调用 JuiceAgent.retransformClassByName("target", ...)
|
||||
============================================
|
||||
|
||||
1. 构建 (可选)
|
||||
playload.jar 和 target.jar 默认已包含。
|
||||
如果修改了 playload/、target/ 或 new_target/, 运行:
|
||||
payload.jar 和 target.jar 默认已包含。
|
||||
如果修改了 payload/、target/ 或 new_target/, 运行:
|
||||
build.bat
|
||||
重新生成 playload.jar、target.jar 和 new_target.class。
|
||||
重新生成 payload.jar、target.jar 和 new_target.class。
|
||||
|
||||
2. 运行目标 JVM
|
||||
双击 run.bat (或执行: java -jar target.jar)。黑窗口出现并每秒打印:
|
||||
@@ -53,8 +53,8 @@ new_target.class, 调用 JuiceAgent.retransformClassByName("target", ...)
|
||||
|
||||
4. 验证
|
||||
回到目标窗口, 注入成功应看到:
|
||||
Playload loaded!
|
||||
Playload executed!
|
||||
Payload loaded!
|
||||
Payload executed!
|
||||
并且 say() 的输出从 "Hello!" 变为:
|
||||
Hello!
|
||||
Retransformed!
|
||||
@@ -63,8 +63,8 @@ new_target.class, 调用 JuiceAgent.retransformClassByName("target", ...)
|
||||
配置 / config.toml
|
||||
============================================
|
||||
|
||||
JarPath - 注入的 JAR 路径 (默认: ./playload.jar)
|
||||
EntryClass - 入口类 (默认: playload)
|
||||
JarPath - 注入的 JAR 路径 (默认: ./payload.jar)
|
||||
EntryClass - 入口类 (默认: payload)
|
||||
EntryMethod - 入口方法, 必须为 public static void entry()
|
||||
|
||||
============================================
|
||||
@@ -75,8 +75,8 @@ new_target.class, 调用 JuiceAgent.retransformClassByName("target", ...)
|
||||
安装 JDK 并将 bin 目录加入 PATH。
|
||||
- injector.exe 提示注入失败:
|
||||
确认目标 JVM 正在运行且 PID 正确。
|
||||
- 没有出现 "Playload loaded!" 输出:
|
||||
- 没有出现 "Payload loaded!" 输出:
|
||||
查看本目录下的 libagent.log 和 libloader.log 定位原因。
|
||||
- say() 输出没有变化:
|
||||
确认修改 new_target/ 后重新运行过 build.bat, 且 playload.jar 内的
|
||||
确认修改 new_target/ 后重新运行过 build.bat, 且 payload.jar 内的
|
||||
new_target.class 是最新的。
|
||||
+23
-115
@@ -3,7 +3,6 @@
|
||||
#include <filesystem>
|
||||
#include <optional>
|
||||
#include <toml++/toml.h>
|
||||
#include <stdexcept>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
#include <cstddef>
|
||||
@@ -33,40 +32,36 @@ public:
|
||||
|
||||
_config_path = _runtime_dir / "config.toml";
|
||||
|
||||
// Load the config file
|
||||
// Load the config file.
|
||||
//
|
||||
// This must never throw: when libloader runs from the reflectively
|
||||
// loaded DLL its unwind tables are not registered, so a C++ exception
|
||||
// raised here could not be caught and would crash the target process.
|
||||
// toml++ switches to non-throwing mode (parse_result) automatically
|
||||
// when exceptions are disabled.
|
||||
#if TOML_EXCEPTIONS
|
||||
try {
|
||||
_config = toml::parse_file(_config_path.string());
|
||||
_valid = true;
|
||||
} catch (const toml::parse_error& e) {
|
||||
spdlog::error("Failed to parse config file: {}", e.what());
|
||||
spdlog::error("Failed to parse config file: {}", e.description());
|
||||
_last_error = e;
|
||||
}
|
||||
#else
|
||||
toml::parse_result result = toml::parse_file(_config_path.string());
|
||||
if (result.succeeded()) {
|
||||
_config = std::move(result).table();
|
||||
_valid = true;
|
||||
} else {
|
||||
spdlog::error("Failed to parse config file: {}", result.error().description());
|
||||
_last_error = result.error();
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
|
||||
template<typename T>
|
||||
T get(const std::string& path) const {
|
||||
const auto* node = _config.at_path(path).node();
|
||||
|
||||
if (!node) {
|
||||
spdlog::error("Configuration key not found: {}", path);
|
||||
throw std::runtime_error(
|
||||
"Configuration key not found: " + path
|
||||
);
|
||||
}
|
||||
|
||||
auto value = node->value<T>();
|
||||
|
||||
if (!value) {
|
||||
spdlog::error("Configuration type mismatch: {}", path);
|
||||
throw std::runtime_error(
|
||||
"Configuration type mismatch: " + path
|
||||
);
|
||||
}
|
||||
|
||||
return *value;
|
||||
}
|
||||
|
||||
// Non-throwing lookup: returns defaultValue when the key is missing or has
|
||||
// the wrong type. There is deliberately no throwing overload - callers that
|
||||
// require a key must check contains() first.
|
||||
template<typename T>
|
||||
T get(const std::string& path, T defaultValue) const {
|
||||
const auto* node = _config.at_path(path).node();
|
||||
@@ -88,16 +83,6 @@ public:
|
||||
return *value;
|
||||
}
|
||||
|
||||
std::string getPath(const std::string& key) const {
|
||||
const std::string value = get<std::string>(key);
|
||||
|
||||
if (value.empty()) {
|
||||
return {};
|
||||
}
|
||||
|
||||
return getPath(key, value);
|
||||
}
|
||||
|
||||
std::string getPath(
|
||||
const std::string& key,
|
||||
const std::string& defaultValue
|
||||
@@ -128,83 +113,6 @@ public:
|
||||
return value.lexically_normal().string();
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
std::vector<T> getArray(const std::string& path) const {
|
||||
const auto* node = _config.at_path(path).node();
|
||||
|
||||
if (!node) {
|
||||
throw std::runtime_error(
|
||||
"Configuration key not found: " + path
|
||||
);
|
||||
}
|
||||
|
||||
const auto* array = node->as_array();
|
||||
|
||||
if (!array) {
|
||||
throw std::runtime_error(
|
||||
"Configuration type mismatch: expected array: " + path
|
||||
);
|
||||
}
|
||||
|
||||
std::vector<T> result;
|
||||
result.reserve(array->size());
|
||||
|
||||
for (std::size_t i = 0; i < array->size(); ++i) {
|
||||
const auto& element = (*array)[i];
|
||||
auto value = element.value<T>();
|
||||
|
||||
if (!value) {
|
||||
throw std::runtime_error(
|
||||
"Configuration array element type mismatch: "
|
||||
+ path + "[" + std::to_string(i) + "]"
|
||||
);
|
||||
}
|
||||
|
||||
result.push_back(*value);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
template<typename T>
|
||||
std::vector<T> getArray(
|
||||
const std::string& path,
|
||||
std::vector<T> defaultValue
|
||||
) const {
|
||||
const auto* node = _config.at_path(path).node();
|
||||
|
||||
if (!node) {
|
||||
return defaultValue;
|
||||
}
|
||||
|
||||
const auto* array = node->as_array();
|
||||
|
||||
if (!array) {
|
||||
throw std::runtime_error(
|
||||
"Configuration type mismatch: expected array: " + path
|
||||
);
|
||||
}
|
||||
|
||||
std::vector<T> result;
|
||||
result.reserve(array->size());
|
||||
|
||||
for (std::size_t i = 0; i < array->size(); ++i) {
|
||||
const auto& element = (*array)[i];
|
||||
auto value = element.value<T>();
|
||||
|
||||
if (!value) {
|
||||
throw std::runtime_error(
|
||||
"Configuration array element type mismatch: "
|
||||
+ path + "[" + std::to_string(i) + "]"
|
||||
);
|
||||
}
|
||||
|
||||
result.push_back(*value);
|
||||
}
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
bool contains(const std::string& path) const {
|
||||
return _config.at_path(path).node() != nullptr;
|
||||
}
|
||||
@@ -231,4 +139,4 @@ public:
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace JuiceAgent::Config
|
||||
} // namespace JuiceAgent::Config
|
||||
@@ -1,498 +0,0 @@
|
||||
// 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
|
||||
@@ -1,328 +0,0 @@
|
||||
// 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
|
||||
|
||||
@@ -1,186 +0,0 @@
|
||||
// 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
|
||||
@@ -1,561 +0,0 @@
|
||||
// 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
|
||||
|
||||
@@ -1,319 +0,0 @@
|
||||
// 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
|
||||
@@ -1,325 +0,0 @@
|
||||
// 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
|
||||
|
||||
@@ -1,482 +0,0 @@
|
||||
// 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
|
||||
|
||||
@@ -1,191 +0,0 @@
|
||||
// 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_
|
||||
@@ -1,174 +0,0 @@
|
||||
#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
|
||||
|
||||
@@ -1,292 +0,0 @@
|
||||
// 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
|
||||
@@ -1,127 +0,0 @@
|
||||
// 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
|
||||
|
||||
@@ -1,75 +0,0 @@
|
||||
// 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
|
||||
|
||||
@@ -1,73 +0,0 @@
|
||||
// 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
|
||||
|
||||
@@ -1,247 +0,0 @@
|
||||
// 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
|
||||
|
||||
@@ -1,161 +0,0 @@
|
||||
// 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
|
||||
|
||||
@@ -1,136 +0,0 @@
|
||||
// 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
|
||||
|
||||
@@ -1,50 +0,0 @@
|
||||
// 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
|
||||
|
||||
@@ -1,222 +0,0 @@
|
||||
// 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
|
||||
|
||||
@@ -1,196 +0,0 @@
|
||||
// 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
|
||||
|
||||
@@ -1,177 +0,0 @@
|
||||
// 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;
|
||||
|
||||
|
||||
*/
|
||||
@@ -1,169 +0,0 @@
|
||||
// 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
|
||||
|
||||
@@ -1,81 +0,0 @@
|
||||
// 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
|
||||
|
||||
@@ -1,330 +0,0 @@
|
||||
// eventpp library
|
||||
// Copyright (C) 2018 Wang Qi (wqking)
|
||||
// Github: https://github.com/wqking/eventpp
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
#ifndef SCOPEDREMOVER_H_695291515513
|
||||
#define SCOPEDREMOVER_H_695291515513
|
||||
|
||||
#include "../eventpolicies.h"
|
||||
|
||||
#include <vector>
|
||||
#include <algorithm>
|
||||
|
||||
namespace eventpp {
|
||||
|
||||
namespace internal_ {
|
||||
|
||||
template <typename Item, typename Handle, typename Mutex>
|
||||
bool removeHandleFromScopedRemoverItemList(std::vector<Item> & itemList, Handle & handle, Mutex & mutex)
|
||||
{
|
||||
if(! handle) {
|
||||
return false;
|
||||
}
|
||||
auto handlePointer = handle.lock();
|
||||
std::unique_lock<Mutex> lock(mutex);
|
||||
auto it = std::find_if(itemList.begin(), itemList.end(), [&handlePointer](Item & item) {
|
||||
return item.handle && item.handle.lock() == handlePointer;
|
||||
});
|
||||
if(it != itemList.end()) {
|
||||
itemList.erase(it);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} //namespace internal_
|
||||
|
||||
template <typename DispatcherType, typename Enabled = void>
|
||||
class ScopedRemover;
|
||||
|
||||
template <typename DispatcherType>
|
||||
class ScopedRemover <
|
||||
DispatcherType,
|
||||
typename std::enable_if<std::is_base_of<TagEventDispatcher, DispatcherType>::value>::type
|
||||
>
|
||||
{
|
||||
private:
|
||||
struct Item
|
||||
{
|
||||
typename DispatcherType::Event event;
|
||||
typename DispatcherType::Handle handle;
|
||||
};
|
||||
|
||||
public:
|
||||
ScopedRemover()
|
||||
: dispatcher(nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
explicit ScopedRemover(DispatcherType & dispatcher)
|
||||
: dispatcher(&dispatcher)
|
||||
{
|
||||
}
|
||||
|
||||
ScopedRemover(ScopedRemover && other) noexcept
|
||||
: dispatcher(std::move(other.dispatcher)), itemList(std::move(other.itemList))
|
||||
{
|
||||
other.reset();
|
||||
}
|
||||
|
||||
ScopedRemover & operator = (ScopedRemover && other) noexcept
|
||||
{
|
||||
dispatcher = std::move(other.dispatcher);
|
||||
itemList = std::move(other.itemList);
|
||||
other.reset();
|
||||
return *this;
|
||||
}
|
||||
|
||||
~ScopedRemover()
|
||||
{
|
||||
reset();
|
||||
}
|
||||
|
||||
void swap(ScopedRemover & other) noexcept {
|
||||
using std::swap;
|
||||
|
||||
swap(dispatcher, other.dispatcher);
|
||||
swap(itemList, other.itemList);
|
||||
}
|
||||
|
||||
void reset()
|
||||
{
|
||||
if(dispatcher != nullptr) {
|
||||
for(const auto & item : itemList) {
|
||||
dispatcher->removeListener(item.event, item.handle);
|
||||
}
|
||||
}
|
||||
|
||||
std::unique_lock<typename DispatcherType::Mutex> lock(itemListMutex);
|
||||
itemList.clear();
|
||||
}
|
||||
|
||||
void setDispatcher(DispatcherType & dispatcher_)
|
||||
{
|
||||
if(this->dispatcher != &dispatcher_) {
|
||||
reset();
|
||||
this->dispatcher = &dispatcher_;
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename DispatcherType::Handle appendListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener
|
||||
)
|
||||
{
|
||||
Item item {
|
||||
event,
|
||||
dispatcher->appendListener(event, listener)
|
||||
};
|
||||
|
||||
{
|
||||
std::unique_lock<typename DispatcherType::Mutex> lock(itemListMutex);
|
||||
itemList.push_back(item);
|
||||
}
|
||||
|
||||
return item.handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename DispatcherType::Handle prependListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener
|
||||
)
|
||||
{
|
||||
Item item {
|
||||
event,
|
||||
dispatcher->prependListener(event, listener)
|
||||
};
|
||||
|
||||
{
|
||||
std::unique_lock<typename DispatcherType::Mutex> lock(itemListMutex);
|
||||
itemList.push_back(item);
|
||||
}
|
||||
|
||||
return item.handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename DispatcherType::Handle insertListener(
|
||||
const typename DispatcherType::Event & event,
|
||||
const Callback & listener,
|
||||
const typename DispatcherType::Handle & before
|
||||
)
|
||||
{
|
||||
Item item {
|
||||
event,
|
||||
dispatcher->insertListener(event, listener, before)
|
||||
};
|
||||
|
||||
{
|
||||
std::unique_lock<typename DispatcherType::Mutex> lock(itemListMutex);
|
||||
itemList.push_back(item);
|
||||
}
|
||||
|
||||
return item.handle;
|
||||
}
|
||||
|
||||
bool removeListener(const typename DispatcherType::Event & event, const typename DispatcherType::Handle handle)
|
||||
{
|
||||
if(internal_::removeHandleFromScopedRemoverItemList(itemList, handle, itemListMutex)) {
|
||||
return dispatcher->removeListener(event, handle);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private:
|
||||
DispatcherType * dispatcher;
|
||||
std::vector<Item> itemList;
|
||||
typename DispatcherType::Mutex itemListMutex;
|
||||
};
|
||||
|
||||
template <typename CallbackListType>
|
||||
class ScopedRemover <
|
||||
CallbackListType,
|
||||
typename std::enable_if<std::is_base_of<TagCallbackList, CallbackListType>::value>::type
|
||||
>
|
||||
{
|
||||
private:
|
||||
struct Item
|
||||
{
|
||||
typename CallbackListType::Handle handle;
|
||||
};
|
||||
|
||||
public:
|
||||
ScopedRemover()
|
||||
: callbackList(nullptr)
|
||||
{
|
||||
}
|
||||
|
||||
explicit ScopedRemover(CallbackListType & callbackList)
|
||||
: callbackList(&callbackList)
|
||||
{
|
||||
}
|
||||
|
||||
ScopedRemover(ScopedRemover && other) noexcept
|
||||
: callbackList(std::move(other.callbackList)), itemList(std::move(other.itemList))
|
||||
{
|
||||
other.reset();
|
||||
}
|
||||
|
||||
ScopedRemover & operator = (ScopedRemover && other) noexcept
|
||||
{
|
||||
callbackList = std::move(other.callbackList);
|
||||
itemList = std::move(other.itemList);
|
||||
other.reset();
|
||||
return *this;
|
||||
}
|
||||
|
||||
~ScopedRemover()
|
||||
{
|
||||
reset();
|
||||
}
|
||||
|
||||
void swap(ScopedRemover & other) noexcept {
|
||||
using std::swap;
|
||||
|
||||
swap(callbackList, other.callbackList);
|
||||
swap(itemList, other.itemList);
|
||||
}
|
||||
|
||||
void reset()
|
||||
{
|
||||
if(callbackList != nullptr) {
|
||||
for(const auto & item : itemList) {
|
||||
callbackList->remove(item.handle);
|
||||
}
|
||||
}
|
||||
|
||||
std::unique_lock<typename CallbackListType::Mutex> lock(itemListMutex);
|
||||
itemList.clear();
|
||||
}
|
||||
|
||||
void setCallbackList(CallbackListType & callbackList_)
|
||||
{
|
||||
if(this->callbackList != &callbackList_) {
|
||||
reset();
|
||||
this->callbackList = &callbackList_;
|
||||
}
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename CallbackListType::Handle append(
|
||||
const Callback & callback
|
||||
)
|
||||
{
|
||||
Item item {
|
||||
callbackList->append(callback)
|
||||
};
|
||||
|
||||
{
|
||||
std::unique_lock<typename CallbackListType::Mutex> lock(itemListMutex);
|
||||
itemList.push_back(item);
|
||||
}
|
||||
|
||||
return item.handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename CallbackListType::Handle prepend(
|
||||
const Callback & callback
|
||||
)
|
||||
{
|
||||
Item item {
|
||||
callbackList->prepend(callback)
|
||||
};
|
||||
|
||||
{
|
||||
std::unique_lock<typename CallbackListType::Mutex> lock(itemListMutex);
|
||||
itemList.push_back(item);
|
||||
}
|
||||
|
||||
return item.handle;
|
||||
}
|
||||
|
||||
template <typename Callback>
|
||||
typename CallbackListType::Handle insert(
|
||||
const Callback & callback,
|
||||
const typename CallbackListType::Handle & before
|
||||
)
|
||||
{
|
||||
Item item {
|
||||
callbackList->insert(callback, before)
|
||||
};
|
||||
|
||||
{
|
||||
std::unique_lock<typename CallbackListType::Mutex> lock(itemListMutex);
|
||||
itemList.push_back(item);
|
||||
}
|
||||
|
||||
return item.handle;
|
||||
}
|
||||
|
||||
bool remove(const typename CallbackListType::Handle handle)
|
||||
{
|
||||
if(internal_::removeHandleFromScopedRemoverItemList(itemList, handle, itemListMutex)) {
|
||||
return callbackList->remove(handle);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private:
|
||||
CallbackListType * callbackList;
|
||||
std::vector<Item> itemList;
|
||||
typename CallbackListType::Mutex itemListMutex;
|
||||
};
|
||||
|
||||
|
||||
} //namespace eventpp
|
||||
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,60 @@
|
||||
/*
|
||||
* Copyright (c) 1999, 2001, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation. Oracle designates this
|
||||
* particular file as subject to the "Classpath" exception as provided
|
||||
* by Oracle in the LICENSE file that accompanied this code.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
#ifndef _JAVASOFT_JAWT_MD_H_
|
||||
#define _JAVASOFT_JAWT_MD_H_
|
||||
|
||||
#include <X11/Xlib.h>
|
||||
#include <X11/Xutil.h>
|
||||
#include "jawt.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/*
|
||||
* X11-specific declarations for AWT native interface.
|
||||
* See notes in jawt.h for an example of use.
|
||||
*/
|
||||
typedef struct jawt_X11DrawingSurfaceInfo {
|
||||
Drawable drawable;
|
||||
Display* display;
|
||||
VisualID visualID;
|
||||
Colormap colormapID;
|
||||
int depth;
|
||||
/*
|
||||
* Since 1.4
|
||||
* Returns a pixel value from a set of RGB values.
|
||||
* This is useful for paletted color (256 color) modes.
|
||||
*/
|
||||
int (JNICALL *GetAWTColor)(JAWT_DrawingSurface* ds,
|
||||
int r, int g, int b);
|
||||
} JAWT_X11DrawingSurfaceInfo;
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* !_JAVASOFT_JAWT_MD_H_ */
|
||||
@@ -0,0 +1,66 @@
|
||||
/*
|
||||
* Copyright (c) 1996, 2020, Oracle and/or its affiliates. All rights reserved.
|
||||
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
|
||||
*
|
||||
* This code is free software; you can redistribute it and/or modify it
|
||||
* under the terms of the GNU General Public License version 2 only, as
|
||||
* published by the Free Software Foundation. Oracle designates this
|
||||
* particular file as subject to the "Classpath" exception as provided
|
||||
* by Oracle in the LICENSE file that accompanied this code.
|
||||
*
|
||||
* This code is distributed in the hope that it will be useful, but WITHOUT
|
||||
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
|
||||
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
|
||||
* version 2 for more details (a copy is included in the LICENSE file that
|
||||
* accompanied this code).
|
||||
*
|
||||
* You should have received a copy of the GNU General Public License version
|
||||
* 2 along with this work; if not, write to the Free Software Foundation,
|
||||
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
|
||||
*
|
||||
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
|
||||
* or visit www.oracle.com if you need additional information or have any
|
||||
* questions.
|
||||
*/
|
||||
|
||||
#ifndef _JAVASOFT_JNI_MD_H_
|
||||
#define _JAVASOFT_JNI_MD_H_
|
||||
|
||||
#ifndef __has_attribute
|
||||
#define __has_attribute(x) 0
|
||||
#endif
|
||||
|
||||
#ifndef JNIEXPORT
|
||||
#if (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4) && (__GNUC_MINOR__ > 2))) || __has_attribute(visibility)
|
||||
#ifdef ARM
|
||||
#define JNIEXPORT __attribute__((externally_visible,visibility("default")))
|
||||
#else
|
||||
#define JNIEXPORT __attribute__((visibility("default")))
|
||||
#endif
|
||||
#else
|
||||
#define JNIEXPORT
|
||||
#endif
|
||||
#endif
|
||||
|
||||
#if (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4) && (__GNUC_MINOR__ > 2))) || __has_attribute(visibility)
|
||||
#ifdef ARM
|
||||
#define JNIIMPORT __attribute__((externally_visible,visibility("default")))
|
||||
#else
|
||||
#define JNIIMPORT __attribute__((visibility("default")))
|
||||
#endif
|
||||
#else
|
||||
#define JNIIMPORT
|
||||
#endif
|
||||
|
||||
#define JNICALL
|
||||
|
||||
typedef int jint;
|
||||
#ifdef _LP64
|
||||
typedef long jlong;
|
||||
#else
|
||||
typedef long long jlong;
|
||||
#endif
|
||||
|
||||
typedef signed char jbyte;
|
||||
|
||||
#endif /* !_JAVASOFT_JNI_MD_H_ */
|
||||
@@ -1,16 +0,0 @@
|
||||
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,2 +1,6 @@
|
||||
# injector
|
||||
add_executable(injector injector.c)
|
||||
if(WIN32)
|
||||
add_executable(injector injector.c)
|
||||
else()
|
||||
add_executable(injector injector_linux.c)
|
||||
endif()
|
||||
@@ -0,0 +1,10 @@
|
||||
#include <stdio.h>
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
// TODO: Implement Linux injector
|
||||
// Due to certain reasons, the Injector for Linux is not open source.
|
||||
// Please wait a moment for the next update.
|
||||
printf("Due to certain reasons, the Injector for Linux is not open source. Please wait a moment for the next update.\n");
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -10,11 +10,17 @@ 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
|
||||
)
|
||||
if(WIN32)
|
||||
target_include_directories(agent PRIVATE
|
||||
${CMAKE_SOURCE_DIR}/includes/jvm/win32
|
||||
)
|
||||
|
||||
target_link_libraries(agent PRIVATE jvm)
|
||||
else()
|
||||
target_include_directories(agent PRIVATE
|
||||
${CMAKE_SOURCE_DIR}/includes/jvm/linux
|
||||
)
|
||||
endif()
|
||||
@@ -5,6 +5,7 @@
|
||||
#include <jni_common.hpp>
|
||||
#include <services.hpp>
|
||||
#include <eventbus.hpp>
|
||||
#include <event/event_type.hpp>
|
||||
|
||||
namespace JuiceAgent {
|
||||
// Singleton
|
||||
@@ -59,7 +60,7 @@ namespace JuiceAgent {
|
||||
// Post preload event (after environment is set so listeners
|
||||
// can access the agent state via Agent::getInstance())
|
||||
EventPreLoad preloadEvent{ jvm, env, jvmti };
|
||||
EventBus::getInstance().post(EventId::PreLoad, &preloadEvent);
|
||||
EventBus::getInstance().post(preloadEvent);
|
||||
|
||||
return true;
|
||||
}
|
||||
@@ -112,7 +113,7 @@ namespace JuiceAgent {
|
||||
|
||||
// Post loaded event
|
||||
EventLoaded loadedEvent{ getJavaVM(), getJNIEnv(), getJVMTI() };
|
||||
EventBus::getInstance().post(EventId::Loaded, &loadedEvent);
|
||||
EventBus::getInstance().post(loadedEvent);
|
||||
|
||||
|
||||
return true;
|
||||
|
||||
@@ -1,5 +1,6 @@
|
||||
#include <jni_common.hpp>
|
||||
#include <eventbus.hpp>
|
||||
#include <event/event_type.hpp>
|
||||
|
||||
void JNICALL ClassFileLoadHook(
|
||||
jvmtiEnv* jvmti_env,
|
||||
@@ -30,5 +31,5 @@ void JNICALL ClassFileLoadHook(
|
||||
new_classbytes
|
||||
};
|
||||
|
||||
EventBus::getInstance().post(EventId::ClassFileLoadHook, &event);
|
||||
EventBus::getInstance().post(event);
|
||||
}
|
||||
@@ -16,24 +16,6 @@ struct EventClassFileLoadHook {
|
||||
unsigned char** new_classbytes;
|
||||
};
|
||||
|
||||
// MethodEntry
|
||||
struct EventMethodEntry {
|
||||
jvmtiEnv* jvmti_env;
|
||||
JNIEnv* jni_env;
|
||||
jthread thread;
|
||||
jmethodID method;
|
||||
};
|
||||
|
||||
// MethodExit
|
||||
struct EventMethodExit {
|
||||
jvmtiEnv* jvmti_env;
|
||||
JNIEnv* jni_env;
|
||||
jthread thread;
|
||||
jmethodID method;
|
||||
jboolean was_popped_by_exception;
|
||||
jvalue return_value;
|
||||
};
|
||||
|
||||
// JuiceAgent PreLoad/PostLoad
|
||||
struct EventPreLoad {
|
||||
JavaVM* jvm;
|
||||
@@ -45,4 +27,4 @@ struct EventLoaded {
|
||||
JavaVM* jvm;
|
||||
JNIEnv* env;
|
||||
jvmtiEnv* jvmti;
|
||||
};
|
||||
};
|
||||
@@ -1,19 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#include <eventpp/eventdispatcher.h>
|
||||
#include <event/event_type.hpp>
|
||||
|
||||
enum class EventId {
|
||||
ClassFileLoadHook,
|
||||
MethodEntry,
|
||||
MethodExit,
|
||||
PreLoad,
|
||||
Loaded
|
||||
};
|
||||
#include <cstddef>
|
||||
#include <functional>
|
||||
#include <mutex>
|
||||
#include <typeinfo>
|
||||
#include <typeindex>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
// A small type-safe event bus.
|
||||
//
|
||||
// Listeners subscribe to a concrete event type and are invoked with that type,
|
||||
// so there is no `void*` casting at the API boundary:
|
||||
//
|
||||
// auto handle = EventBus::getInstance().subscribe<MyEvent>(
|
||||
// [](const MyEvent& e) { ... });
|
||||
// EventBus::getInstance().post(myEvent);
|
||||
//
|
||||
// Listeners are copied before dispatch, so a handler may safely subscribe or
|
||||
// unsubscribe (including itself) without invalidating the iteration.
|
||||
class EventBus {
|
||||
public:
|
||||
using Dispatcher = eventpp::EventDispatcher<EventId, void(const void*)>;
|
||||
using Handle = std::size_t;
|
||||
|
||||
static EventBus& getInstance() {
|
||||
static EventBus instance;
|
||||
@@ -23,25 +32,91 @@ public:
|
||||
EventBus(const EventBus&) = delete;
|
||||
EventBus& operator=(const EventBus&) = delete;
|
||||
|
||||
void post(EventId id, const void* event) {
|
||||
dispatcher.dispatch(id, event);
|
||||
template <typename EventT>
|
||||
void post(const EventT& event) {
|
||||
std::vector<std::function<void(const void*)>> callbacks;
|
||||
|
||||
{
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
auto it = listeners_.find(std::type_index(typeid(EventT)));
|
||||
if (it == listeners_.end()) {
|
||||
return;
|
||||
}
|
||||
callbacks.reserve(it->second.size());
|
||||
for (const auto& listener : it->second) {
|
||||
callbacks.push_back(listener.callback);
|
||||
}
|
||||
}
|
||||
|
||||
for (auto& callback : callbacks) {
|
||||
callback(&event);
|
||||
}
|
||||
}
|
||||
|
||||
template <typename C>
|
||||
auto appendListener(EventId id, const C& callback) {
|
||||
return dispatcher.appendListener(id, callback);
|
||||
template <typename EventT>
|
||||
Handle subscribe(std::function<void(const EventT&)> callback) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
const Handle handle = next_handle_++;
|
||||
listeners_[std::type_index(typeid(EventT))].push_back({
|
||||
handle,
|
||||
[callback](const void* data) {
|
||||
callback(*static_cast<const EventT*>(data));
|
||||
}
|
||||
});
|
||||
return handle;
|
||||
}
|
||||
|
||||
template <typename C>
|
||||
auto prependListener(EventId id, const C& callback) {
|
||||
return dispatcher.prependListener(id, callback);
|
||||
// Like subscribe(), but inserts the listener at the front so it runs
|
||||
// before previously registered listeners for the same event.
|
||||
template <typename EventT>
|
||||
Handle subscribeFront(std::function<void(const EventT&)> callback) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
const Handle handle = next_handle_++;
|
||||
auto& list = listeners_[std::type_index(typeid(EventT))];
|
||||
list.insert(list.begin(), Listener{
|
||||
handle,
|
||||
[callback](const void* data) {
|
||||
callback(*static_cast<const EventT*>(data));
|
||||
}
|
||||
});
|
||||
return handle;
|
||||
}
|
||||
|
||||
bool removeListener(EventId id, Dispatcher::Handle handle) {
|
||||
return dispatcher.removeListener(id, handle);
|
||||
template <typename EventT>
|
||||
bool unsubscribe(Handle handle) {
|
||||
return unsubscribe(std::type_index(typeid(EventT)), handle);
|
||||
}
|
||||
|
||||
// Type-erased overload, for owners that track listeners across event types.
|
||||
bool unsubscribe(std::type_index type, Handle handle) {
|
||||
std::lock_guard<std::mutex> lock(mutex_);
|
||||
|
||||
auto it = listeners_.find(type);
|
||||
if (it == listeners_.end()) {
|
||||
return false;
|
||||
}
|
||||
|
||||
auto& list = it->second;
|
||||
for (auto e = list.begin(); e != list.end(); ++e) {
|
||||
if (e->handle == handle) {
|
||||
list.erase(e);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
private:
|
||||
EventBus() = default;
|
||||
Dispatcher dispatcher;
|
||||
};
|
||||
|
||||
struct Listener {
|
||||
Handle handle;
|
||||
std::function<void(const void*)> callback;
|
||||
};
|
||||
|
||||
std::mutex mutex_;
|
||||
std::unordered_map<std::type_index, std::vector<Listener>> listeners_;
|
||||
Handle next_handle_ = 1;
|
||||
};
|
||||
@@ -1,8 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
#include <vector>
|
||||
#include <utility>
|
||||
#include <functional>
|
||||
#include <type_traits>
|
||||
#include <typeindex>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
#include <JuiceAgent/Logger.hpp>
|
||||
#include <eventbus.hpp>
|
||||
|
||||
@@ -20,36 +23,51 @@ public:
|
||||
virtual void onShutdown() {}
|
||||
|
||||
protected:
|
||||
// Register `handler` to run after previously registered listeners.
|
||||
template <typename ServiceT, typename EventT>
|
||||
void listen(EventId id, void (ServiceT::*handler)(const EventT&)) {
|
||||
void listen(void (ServiceT::*handler)(const EventT&)) {
|
||||
static_assert(std::is_base_of<IService, ServiceT>::value,
|
||||
"ServiceT must derive from IService");
|
||||
auto* self = static_cast<ServiceT*>(this);
|
||||
handles_.push_back({
|
||||
id,
|
||||
EventBus::getInstance().appendListener(
|
||||
id,
|
||||
[self, handler](const void* data) {
|
||||
if (data) {
|
||||
(self->*handler)(*static_cast<const EventT*>(data));
|
||||
}
|
||||
}
|
||||
)
|
||||
});
|
||||
trackListener<EventT>(
|
||||
[self, handler](const EventT& event) { (self->*handler)(event); },
|
||||
false);
|
||||
}
|
||||
|
||||
// Register `handler` to run before previously registered listeners.
|
||||
// Use it when the ordering between listeners matters (e.g. a transformer
|
||||
// pipeline that must run before other consumers).
|
||||
template <typename ServiceT, typename EventT>
|
||||
void listenFront(void (ServiceT::*handler)(const EventT&)) {
|
||||
static_assert(std::is_base_of<IService, ServiceT>::value,
|
||||
"ServiceT must derive from IService");
|
||||
auto* self = static_cast<ServiceT*>(this);
|
||||
trackListener<EventT>(
|
||||
[self, handler](const EventT& event) { (self->*handler)(event); },
|
||||
true);
|
||||
}
|
||||
|
||||
// Remove all listeners registered by this service. Call it in onShutdown()
|
||||
// so no callback outlives the service instance.
|
||||
void unlistenAll() {
|
||||
auto& bus = EventBus::getInstance();
|
||||
for (auto& [id, handle] : handles_) {
|
||||
bus.removeListener(id, handle);
|
||||
for (auto& [type, handle] : handles_) {
|
||||
bus.unsubscribe(type, handle);
|
||||
}
|
||||
handles_.clear();
|
||||
}
|
||||
|
||||
private:
|
||||
std::vector<std::pair<EventId, EventBus::Dispatcher::Handle>> handles_;
|
||||
template <typename EventT>
|
||||
void trackListener(std::function<void(const EventT&)> callback, bool front) {
|
||||
auto& bus = EventBus::getInstance();
|
||||
const EventBus::Handle handle = front
|
||||
? bus.subscribeFront<EventT>(std::move(callback))
|
||||
: bus.subscribe<EventT>(std::move(callback));
|
||||
handles_.push_back({std::type_index(typeid(EventT)), handle});
|
||||
}
|
||||
|
||||
std::vector<std::pair<std::type_index, EventBus::Handle>> handles_;
|
||||
};
|
||||
|
||||
}
|
||||
|
||||
@@ -15,12 +15,10 @@ public:
|
||||
|
||||
bool onInitialize() override {
|
||||
listen<BytecodeService, EventClassFileLoadHook>(
|
||||
EventId::ClassFileLoadHook,
|
||||
&BytecodeService::captureBytecodes
|
||||
);
|
||||
|
||||
listen<BytecodeService, EventClassFileLoadHook>(
|
||||
EventId::ClassFileLoadHook,
|
||||
&BytecodeService::patchBytecodes
|
||||
);
|
||||
|
||||
|
||||
@@ -13,7 +13,6 @@ public:
|
||||
|
||||
bool onInitialize() override {
|
||||
listen<JarLoaderService, EventLoaded>(
|
||||
EventId::Loaded,
|
||||
&JarLoaderService::onLoaded
|
||||
);
|
||||
|
||||
|
||||
@@ -12,18 +12,41 @@ if (WIN32)
|
||||
)
|
||||
|
||||
list(APPEND loader_sources ${windows_sources})
|
||||
else()
|
||||
message(STATUS "Detected System: Linux or Other")
|
||||
|
||||
file(GLOB_RECURSE linux_sources CONFIGURE_DEPENDS
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/linux/*.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/platform/linux/*.c
|
||||
)
|
||||
|
||||
list(APPEND loader_sources ${linux_sources})
|
||||
endif()
|
||||
|
||||
add_library(loader SHARED ${loader_sources})
|
||||
|
||||
# libloader is reflectively loaded (manually mapped), so the OS never registers
|
||||
# its unwind tables: a C++ exception thrown here cannot be caught and would crash
|
||||
# the target process. Disable exceptions so such code fails the build instead.
|
||||
if(CMAKE_CXX_COMPILER_ID MATCHES "GNU|Clang")
|
||||
target_compile_options(loader PRIVATE -fno-exceptions)
|
||||
target_compile_definitions(loader PRIVATE SPDLOG_NO_EXCEPTIONS)
|
||||
endif()
|
||||
|
||||
target_include_directories(loader PRIVATE
|
||||
${CMAKE_SOURCE_DIR}/includes
|
||||
${CMAKE_SOURCE_DIR}/includes/jvm
|
||||
${CMAKE_SOURCE_DIR}/includes/jvm/win32
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/includes
|
||||
)
|
||||
|
||||
target_link_libraries(loader PRIVATE
|
||||
jvm
|
||||
ReflectiveDLLInjection
|
||||
)
|
||||
if(WIN32)
|
||||
target_include_directories(loader PRIVATE
|
||||
${CMAKE_SOURCE_DIR}/includes/jvm/win32
|
||||
)
|
||||
|
||||
target_link_libraries(loader PRIVATE jvm ReflectiveDLLInjection)
|
||||
else()
|
||||
target_include_directories(loader PRIVATE
|
||||
${CMAKE_SOURCE_DIR}/includes/jvm/linux
|
||||
)
|
||||
endif()
|
||||
@@ -3,6 +3,11 @@
|
||||
#include <JuiceAgent/Logger.hpp>
|
||||
|
||||
void JuiceAgent::Loader::entrypoint(const char* path) {
|
||||
// Called from DllMain inside the target JVM process. NOTE: libloader is
|
||||
// reflectively loaded, so a C++ exception thrown here cannot be unwound and
|
||||
// would crash the target process - this code must not throw (see the note
|
||||
// in Loader::preload).
|
||||
|
||||
// Attach to the JVM
|
||||
JuiceAgent::Loader::JvmAttach jvmAttach;
|
||||
|
||||
@@ -26,4 +31,4 @@ void JuiceAgent::Loader::entrypoint(const char* path) {
|
||||
}
|
||||
|
||||
JuiceAgent::Loader::preload(path, env, jvmti);
|
||||
}
|
||||
}
|
||||
@@ -9,6 +9,11 @@
|
||||
|
||||
// Preload section
|
||||
// Check parameters and load the runtime
|
||||
//
|
||||
// NOTE: libloader is reflectively loaded, so its unwind tables are never
|
||||
// registered with the OS - a C++ exception thrown here could not be caught and
|
||||
// would crash the target process. Everything below must stay exception-free and
|
||||
// report problems with spdlog plus an early return.
|
||||
void JuiceAgent::Loader::preload(const char* runtime_dir, JNIEnv* env, jvmtiEnv* jvmti) {
|
||||
std::string runtime_dir_new;
|
||||
|
||||
@@ -33,27 +38,42 @@ void JuiceAgent::Loader::preload(const char* runtime_dir, JNIEnv* env, jvmtiEnv*
|
||||
}
|
||||
|
||||
// Check config version
|
||||
int version = cfg.get<int>("JuiceAgent.Version");
|
||||
if(!cfg.contains("JuiceAgent.Version")) {
|
||||
spdlog::error("[PreLoad] Missing required config key: JuiceAgent.Version");
|
||||
return;
|
||||
}
|
||||
const int version = cfg.get<int>("JuiceAgent.Version", -1);
|
||||
if(version != CONFIG_VERSION) {
|
||||
spdlog::error("[PreLoad] Config version mismatch! Expected: {}, Got: {}, Please update your config!", CONFIG_VERSION, version);
|
||||
return;
|
||||
}
|
||||
|
||||
// JarLoader mode check and load jars
|
||||
std::string jar_loader_mode = cfg.get<std::string>("JarLoader.Mode");
|
||||
if(!cfg.contains("JarLoader.Mode")) {
|
||||
spdlog::error("[PreLoad] Missing required config key: JarLoader.Mode");
|
||||
return;
|
||||
}
|
||||
const std::string jar_loader_mode = cfg.get<std::string>("JarLoader.Mode", "");
|
||||
|
||||
if(jar_loader_mode == "BuiltIn") {
|
||||
spdlog::info("[PreLoad] JarLoader mode: BuiltIn");
|
||||
|
||||
if(!load_builtin(jvmti)) {
|
||||
spdlog::error("[PreLoad] Failed to load built-in jars!");
|
||||
return;
|
||||
}
|
||||
} else if(jar_loader_mode == "CustomJar") {
|
||||
spdlog::info("[PreLoad] JarLoader mode: CustomJar");
|
||||
|
||||
std::string jar_path = cfg.getPath("JarLoader.JarPath");
|
||||
|
||||
const std::string jar_path = cfg.getPath("JarLoader.JarPath", "");
|
||||
if(jar_path.empty()) {
|
||||
spdlog::error("[PreLoad] Missing required config key: JarLoader.JarPath (CustomJar mode)");
|
||||
return;
|
||||
}
|
||||
|
||||
if(!load_custom(jvmti, jar_path.c_str())) {
|
||||
spdlog::error("[PreLoad] Failed to load custom jar: {}", jar_path);
|
||||
return;
|
||||
}
|
||||
} else {
|
||||
spdlog::error("[PreLoad] Invalid JarLoader mode: {}", jar_loader_mode);
|
||||
@@ -64,7 +84,7 @@ void JuiceAgent::Loader::preload(const char* runtime_dir, JNIEnv* env, jvmtiEnv*
|
||||
}
|
||||
|
||||
void JuiceAgent::Loader::initialize(const char* runtime_dir, JNIEnv* env, jvmtiEnv* jvmti, JuiceAgent::Config::Config& cfg) {
|
||||
std::string jar_loader_mode = cfg.get<std::string>("JarLoader.Mode");
|
||||
const std::string jar_loader_mode = cfg.get<std::string>("JarLoader.Mode", "");
|
||||
|
||||
if(jar_loader_mode == "BuiltIn") {
|
||||
const char* bootstrap_class = "cn/xiaozhou233/juiceagent/api/JuiceAgentBootstrap";
|
||||
@@ -72,9 +92,16 @@ void JuiceAgent::Loader::initialize(const char* runtime_dir, JNIEnv* env, jvmtiE
|
||||
|
||||
JuiceAgent::Utils::Serializer ser;
|
||||
ser.add_kv("Version", cfg.get<int>("JuiceAgent.Version", -1));
|
||||
ser.add_kv("JuiceAgentNativeLibraryPath", cfg.getPath("JuiceAgent.JuiceAgentNativeLibraryPath", (cfg.getRuntimeDir()/"libagent.dll").string()));
|
||||
ser.add_kv("RuntimeDir", cfg.getRuntimeDir().string());
|
||||
|
||||
#ifdef _WIN32
|
||||
std::string default_libagent_path = (cfg.getRuntimeDir()/"libagent.dll").string();
|
||||
#else
|
||||
std::string default_libagent_path = (cfg.getRuntimeDir()/"libagent.so").string();
|
||||
#endif
|
||||
|
||||
ser.add_kv("JuiceAgentNativeLibraryPath", cfg.getPath("JuiceAgent.JuiceAgentNativeLibraryPath", default_libagent_path));
|
||||
ser.add_kv("RuntimeDir", cfg.getRuntimeDir().string());
|
||||
|
||||
std::string args = ser.serialize();
|
||||
spdlog::debug("Serialized config: {}", args);
|
||||
|
||||
@@ -86,8 +113,13 @@ void JuiceAgent::Loader::initialize(const char* runtime_dir, JNIEnv* env, jvmtiE
|
||||
} else if(jar_loader_mode == "CustomJar") {
|
||||
spdlog::info("[Initialize] JarLoader mode: CustomJar");
|
||||
|
||||
std::string entry_class = cfg.get<std::string>("JarLoader.EntryClass");
|
||||
std::string entry_method = cfg.get<std::string>("JarLoader.EntryMethod");
|
||||
const std::string entry_class = cfg.get<std::string>("JarLoader.EntryClass", "");
|
||||
const std::string entry_method = cfg.get<std::string>("JarLoader.EntryMethod", "");
|
||||
if(entry_class.empty() || entry_method.empty()) {
|
||||
spdlog::error("[Initialize] Missing required config key: JarLoader.EntryClass / JarLoader.EntryMethod (CustomJar mode)");
|
||||
return;
|
||||
}
|
||||
|
||||
spdlog::debug("[Initialize] Entry class: {}, Entry method: {}", entry_class, entry_method);
|
||||
bool result = JuiceAgent::Utils::call_static_java_method(env, entry_class.c_str(), entry_method.c_str());
|
||||
if (!result) {
|
||||
@@ -100,4 +132,4 @@ void JuiceAgent::Loader::initialize(const char* runtime_dir, JNIEnv* env, jvmtiE
|
||||
}
|
||||
|
||||
spdlog::info("JuiceAgent initialized!");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
#include "JuiceAgent/Logger.hpp"
|
||||
#include "Loader.hpp"
|
||||
|
||||
#include <cstdlib>
|
||||
#include <filesystem>
|
||||
#include <string>
|
||||
#include <system_error>
|
||||
#include <thread>
|
||||
|
||||
namespace fs = std::filesystem;
|
||||
|
||||
static void run_loader() {
|
||||
const char* env = std::getenv("JuiceAgent_ConfigPath");
|
||||
std::string current_path;
|
||||
|
||||
if (env != nullptr && env[0] != '\0') {
|
||||
// Use the environment variable if it exists and is not empty.
|
||||
current_path = env;
|
||||
} else {
|
||||
spdlog::trace("[libloader] JuiceAgent_ConfigPath is not set");
|
||||
|
||||
const char* home = std::getenv("HOME");
|
||||
if (home == nullptr || home[0] == '\0') {
|
||||
spdlog::error("[libloader] HOME environment variable is not set");
|
||||
return;
|
||||
}
|
||||
|
||||
// Fall back to $HOME/.juiceagent.
|
||||
fs::path config_dir = fs::path(home) / ".juiceagent";
|
||||
|
||||
std::error_code ec;
|
||||
fs::create_directories(config_dir, ec);
|
||||
|
||||
if (ec) {
|
||||
spdlog::error(
|
||||
"[libloader] Failed to create config directory: {}",
|
||||
ec.message()
|
||||
);
|
||||
return;
|
||||
}
|
||||
|
||||
current_path = config_dir.string();
|
||||
}
|
||||
|
||||
spdlog::info("[libloader] current path: {}", current_path);
|
||||
|
||||
JuiceAgent::Loader::entrypoint(current_path.c_str());
|
||||
}
|
||||
|
||||
__attribute__((constructor))
|
||||
static void entry() {
|
||||
Logger::init();
|
||||
|
||||
spdlog::info("[libloader] loaded!");
|
||||
|
||||
std::thread([] {
|
||||
run_loader();
|
||||
}).detach();
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
<#
|
||||
.SYNOPSIS
|
||||
Build and run the JuiceAgent integration tests.
|
||||
|
||||
.DESCRIPTION
|
||||
Compiles the test + injection modules, refreshes tests/resources from
|
||||
build/bin, then runs every test and asserts on its output.
|
||||
|
||||
The test programs always exit 0, even when a step fails (e.g. a bad config
|
||||
or a missing class is printed but the process still returns 0), so exit
|
||||
codes alone are not enough - we match an expected marker per test.
|
||||
|
||||
Requires the native binaries in build/bin; run `cmake --build build` first.
|
||||
|
||||
.PARAMETER JdkHome
|
||||
JDK home directory. Defaults to the `java`/`javac`/`jar` on PATH.
|
||||
|
||||
.EXAMPLE
|
||||
pwsh -File tests/run-tests.ps1
|
||||
pwsh -File tests/run-tests.ps1 -JdkHome "C:\Program Files\Zulu\zulu-25"
|
||||
#>
|
||||
[CmdletBinding()]
|
||||
param(
|
||||
[string]$JdkHome = ""
|
||||
)
|
||||
|
||||
# Native commands (java/javac/jar) write to stderr for warnings; with
|
||||
# ErrorActionPreference=Stop that would be treated as a terminating error on
|
||||
# Windows PowerShell 5.1. Failures are detected explicitly via $LASTEXITCODE
|
||||
# and the per-test output assertions instead.
|
||||
$ErrorActionPreference = "Continue"
|
||||
|
||||
$TestsDir = Split-Path -Parent $MyInvocation.MyCommand.Path
|
||||
$RepoRoot = Split-Path -Parent $TestsDir
|
||||
|
||||
function Resolve-FromPath([string]$name) {
|
||||
$cmd = Get-Command $name -ErrorAction SilentlyContinue
|
||||
if ($cmd) { return $cmd.Source }
|
||||
return $null
|
||||
}
|
||||
|
||||
# --- Locate JDK tools ------------------------------------------------------
|
||||
if ($JdkHome) {
|
||||
$java = Join-Path $JdkHome "bin\java.exe"
|
||||
$javac = Join-Path $JdkHome "bin\javac.exe"
|
||||
$jar = Join-Path $JdkHome "bin\jar.exe"
|
||||
} else {
|
||||
$java = Resolve-FromPath "java"
|
||||
$javac = Resolve-FromPath "javac"
|
||||
$jar = Resolve-FromPath "jar"
|
||||
}
|
||||
|
||||
foreach ($tool in @($java, $javac, $jar)) {
|
||||
if (-not $tool -or -not (Test-Path $tool)) {
|
||||
throw "JDK tools not found. Install a JDK (17+) and put it on PATH, or pass -JdkHome <dir>."
|
||||
}
|
||||
}
|
||||
|
||||
# --- JDK version -> native-access flag -------------------------------------
|
||||
# --enable-native-access exists since JDK 22 and is needed to silence the JNI
|
||||
# warnings added in JDK 24.
|
||||
$versionText = (& $java -version 2>&1 | Out-String)
|
||||
if ($versionText -notmatch 'version "(\d+)') {
|
||||
throw "Could not parse the Java version from: $versionText"
|
||||
}
|
||||
$javaMajor = [int]$Matches[1]
|
||||
if ($javaMajor -lt 17) {
|
||||
throw "JDK $javaMajor is too old; the tests need JDK 17+."
|
||||
}
|
||||
|
||||
$nativeAccessArgs = @()
|
||||
if ($javaMajor -ge 22) {
|
||||
$nativeAccessArgs = @("--enable-native-access=ALL-UNNAMED")
|
||||
}
|
||||
|
||||
# --- Locate the JuiceAgent API jar -----------------------------------------
|
||||
$apiJar = Get-ChildItem (Join-Path $TestsDir "lib") -Filter "JuiceAgent-API-*.jar" -ErrorAction SilentlyContinue |
|
||||
Select-Object -First 1
|
||||
if (-not $apiJar) {
|
||||
throw "JuiceAgent API jar not found under tests/lib."
|
||||
}
|
||||
$apiJar = $apiJar.FullName
|
||||
|
||||
# --- Require native binaries ----------------------------------------------
|
||||
$binDir = Join-Path $RepoRoot "build\bin"
|
||||
foreach ($dll in @("libagent.dll", "libloader.dll", "libinject.dll", "injector.exe")) {
|
||||
if (-not (Test-Path (Join-Path $binDir $dll))) {
|
||||
throw "Missing $dll in build\bin. Build the native binaries first: cmake --build build"
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host "=== JuiceAgent integration tests ===" -ForegroundColor Cyan
|
||||
Write-Host ("JDK: {0} (major {1})" -f $java, $javaMajor)
|
||||
Write-Host ("API jar: {0}" -f $apiJar)
|
||||
Write-Host ("Binaries: {0}" -f $binDir)
|
||||
Write-Host ""
|
||||
|
||||
Push-Location $TestsDir
|
||||
try {
|
||||
# --- 1. Compile the injection module (used by redefine/retransform) ----
|
||||
$injectionOut = "out\production\injection"
|
||||
New-Item -ItemType Directory -Force -Path $injectionOut | Out-Null
|
||||
$injectionSources = (Get-ChildItem "injection\src" -Filter *.java).FullName
|
||||
& $javac -d $injectionOut $injectionSources
|
||||
if ($LASTEXITCODE -ne 0) { throw "Compiling the injection module failed." }
|
||||
|
||||
# --- 2. Rebuild injection.jar (used by the AddTo* tests) --------------
|
||||
& $jar cf "injection.jar" -C $injectionOut .
|
||||
if ($LASTEXITCODE -ne 0) { throw "Rebuilding injection.jar failed." }
|
||||
|
||||
# --- 3. Refresh tests/resources from build/bin ------------------------
|
||||
& cmd /c "copy-bin.bat"
|
||||
if ($LASTEXITCODE -ne 0) { throw "copy-bin.bat failed." }
|
||||
|
||||
# --- 4. Compile the tests ---------------------------------------------
|
||||
$testsOut = "out\production\tests"
|
||||
New-Item -ItemType Directory -Force -Path $testsOut | Out-Null
|
||||
$testSources = (Get-ChildItem "src" -Filter *.java).FullName
|
||||
& $javac -cp $apiJar -d $testsOut $testSources
|
||||
if ($LASTEXITCODE -ne 0) { throw "Compiling the tests failed." }
|
||||
|
||||
# --- 5. Run every test and assert on a marker -------------------------
|
||||
$classpath = "$testsOut;$apiJar"
|
||||
$cases = @(
|
||||
@{ Name = "GetClassByName"; Expect = "class java\.lang\.String" },
|
||||
@{ Name = "GetLoadedClasses"; Expect = "class " },
|
||||
@{ Name = "GetClassBytes"; Expect = "Bytes: 399" },
|
||||
@{ Name = "GetClassBytesByName"; Expect = "Bytes: 399" },
|
||||
@{ Name = "DefineClass"; Expect = "Injection Invoked!" },
|
||||
@{ Name = "RedefineClass"; Expect = "Modified!" },
|
||||
@{ Name = "RedefineClassByName"; Expect = "Modified!" },
|
||||
@{ Name = "RetransformClass"; Expect = "Modified!" },
|
||||
@{ Name = "RetransformClassByName"; Expect = "Modified!" },
|
||||
@{ Name = "AddToClassLoader"; Expect = "Injection Invoked!" },
|
||||
@{ Name = "AddToSystemClassLoaderSearch"; Expect = "Injection Invoked!" },
|
||||
@{ Name = "AddToBootstrapClassLoaderSearch"; Expect = "Injection Invoked!" }
|
||||
)
|
||||
|
||||
$failed = @()
|
||||
foreach ($case in $cases) {
|
||||
$output = (& $java @nativeAccessArgs -cp $classpath $case.Name 2>&1 | Out-String)
|
||||
if ($output -match $case.Expect) {
|
||||
Write-Host (" [PASS] {0}" -f $case.Name) -ForegroundColor Green
|
||||
} else {
|
||||
Write-Host (" [FAIL] {0} (expected /{1}/)" -f $case.Name, $case.Expect) -ForegroundColor Red
|
||||
# Show what the test actually printed so failures are diagnosable
|
||||
# (the test programs exit 0 even when a step fails).
|
||||
$lines = @($output -split "`r?`n" | Where-Object { $_.Trim() })
|
||||
foreach ($line in ($lines | Select-Object -First 25)) {
|
||||
Write-Host (" | " + $line.TrimEnd()) -ForegroundColor DarkGray
|
||||
}
|
||||
if ($lines.Count -gt 25) {
|
||||
Write-Host (" | ... ({0} more lines)" -f ($lines.Count - 25)) -ForegroundColor DarkGray
|
||||
}
|
||||
$failed += $case.Name
|
||||
}
|
||||
}
|
||||
|
||||
Write-Host ""
|
||||
if ($failed.Count -gt 0) {
|
||||
Write-Host ("{0}/{1} tests failed: {2}" -f $failed.Count, $cases.Count, ($failed -join ", ")) -ForegroundColor Red
|
||||
exit 1
|
||||
}
|
||||
|
||||
Write-Host ("All {0} tests passed." -f $cases.Count) -ForegroundColor Green
|
||||
exit 0
|
||||
}
|
||||
finally {
|
||||
Pop-Location
|
||||
}
|
||||
Reference in new issue
Block a user