mirror of
https://github.com/xiaozhou233/JuiceAgent.git
synced 2026-12-05 21:15:56 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
5cf0d6ebd8 | ||
|
|
fd6fe0abdb | ||
|
|
5170d50517 | ||
|
|
af22f80b23 | ||
|
|
56a1c32f49 | ||
|
|
f38a28e8b3 | ||
|
|
eb7fd31817 | ||
|
|
92ad21003f | ||
|
|
11cf47c4c2 | ||
|
|
3626abb35a | ||
|
|
382bfb7fed | ||
|
|
560215c0ae | ||
|
|
55303b7dc9 | ||
|
|
41049f1852 | ||
|
|
396ec1a96f | ||
|
|
10ec330480 | ||
|
|
0ddcfcd7c8 | ||
|
|
87a91376c5 | ||
|
|
dbae5e5258 | ||
|
|
ff216aabee | ||
|
|
18a923373b | ||
|
|
6fe467bccf | ||
|
|
4bed99f417 | ||
|
|
81905d6c3f | ||
|
|
6822c1dc63 | ||
|
|
27abc2bf6a | ||
|
|
4f433bc6ee | ||
|
|
20747124d1 | ||
|
|
4833b512f5 | ||
|
|
63dd69abc6 | ||
|
|
f38743e863 | ||
|
|
8e1b8b38e4 | ||
|
|
6962c4a477 | ||
|
|
6bf2d31798 | ||
|
|
6afa44f90a | ||
|
|
2ab1c134ed | ||
|
|
51bcfbd549 | ||
|
|
3b180e7199 | ||
|
|
b34377d447 | ||
|
|
f2ce4e6a5a | ||
|
|
757c5f70f0 | ||
|
|
78160a33a9 | ||
|
|
092110672a | ||
|
|
c5acf2aba0 | ||
|
|
316735cfef | ||
|
|
a1b0eb8b84 | ||
|
|
32e9199d4a | ||
|
|
56ebafd48d | ||
|
|
d304ededd5 | ||
|
|
7a4d8cb101 | ||
|
|
3303630a45 | ||
|
|
20fd69d239 | ||
|
|
b8a4b805c7 | ||
|
|
a56caffe09 | ||
|
|
b08656daa6 | ||
|
|
57405e810c | ||
|
|
6e417035b6 | ||
|
|
1d3755952f | ||
|
|
bcc1ecbf0e | ||
|
|
a251b8996e | ||
|
|
1931072b96 | ||
|
|
ce08b19170 | ||
|
|
998f4d139e | ||
|
|
5023ecf90c | ||
|
|
6479966472 | ||
|
|
841c0e5c2f | ||
|
|
01f966c5f2 | ||
|
|
d711838948 | ||
|
|
fe64308942 | ||
|
|
56b6ab7e98 | ||
|
|
5f9fb7f1b4 | ||
|
|
1dcad52e15 | ||
|
|
cadd3679e9 | ||
|
|
97b100bbbb | ||
|
|
8b5ea4cf28 | ||
|
|
b17ce02ae1 | ||
|
|
bb5b215a33 | ||
|
|
8cf2b8330c | ||
|
|
f11687481f | ||
|
|
c5889cb338 | ||
|
|
1f80df0af0 | ||
|
|
2d1492f3e4 | ||
|
|
b8e2ace91c | ||
|
|
4fde6477c6 | ||
|
|
9ecd2e4e03 | ||
|
|
3842585777 | ||
|
|
18726e59f4 | ||
|
|
02c0583b34 | ||
|
|
9ed7df8476 | ||
|
|
f49ac4dff7 | ||
|
|
16a36ef22a | ||
|
|
4305000bf7 | ||
|
|
65824934d1 | ||
|
|
992fbd9f8d | ||
|
|
882c19ad8f | ||
|
|
637640b938 | ||
|
|
490e4ce2ac | ||
|
|
30ecc82ca2 | ||
|
|
bf4ebd0e5b | ||
|
|
ec7d221b08 | ||
|
|
e5b054fcfc | ||
|
|
b3ec5b6eb5 | ||
|
|
d5a49a5ce7 | ||
|
|
90689f306b | ||
|
|
1e2e5afd07 | ||
|
|
d9d44f029f | ||
|
|
cc1c2bff30 | ||
|
|
7352f8d872 | ||
|
|
4be6324cf3 |
No files matched your search
+4
-5
@@ -1,5 +1,4 @@
|
|||||||
.vscode/*
|
build/
|
||||||
build/*
|
.cache/
|
||||||
debug/*
|
*.log
|
||||||
UserDir/*
|
dist/
|
||||||
CMakeCache.txt
|
|
||||||
+3
-2
@@ -10,12 +10,13 @@ set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
|
|||||||
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
|
||||||
|
|
||||||
set(SRC_DIR ${CMAKE_SOURCE_DIR}/src)
|
set(SRC_DIR ${CMAKE_SOURCE_DIR}/src)
|
||||||
link_directories("$ENV{JAVA_HOME}/lib")
|
link_directories("${CMAKE_SOURCE_DIR}/lib")
|
||||||
|
|
||||||
# libraries
|
# libraries
|
||||||
add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection)
|
add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection)
|
||||||
|
|
||||||
# modules
|
# modules
|
||||||
add_subdirectory(${SRC_DIR}/libloader)
|
add_subdirectory(${SRC_DIR}/libloader)
|
||||||
add_subdirectory(${SRC_DIR}/libinjector)
|
add_subdirectory(${SRC_DIR}/injector)
|
||||||
|
add_subdirectory(${SRC_DIR}/libinject)
|
||||||
add_subdirectory(${SRC_DIR}/libagent)
|
add_subdirectory(${SRC_DIR}/libagent)
|
||||||
+3
-4
@@ -2,16 +2,15 @@
|
|||||||
"version": 3,
|
"version": 3,
|
||||||
"configurePresets": [
|
"configurePresets": [
|
||||||
{
|
{
|
||||||
"name": "ninja-release",
|
"name": "release",
|
||||||
"generator": "Ninja",
|
"generator": "Ninja",
|
||||||
"binaryDir": "${sourceDir}/build",
|
"binaryDir": "${sourceDir}/build",
|
||||||
"cacheVariables": {
|
"cacheVariables": {
|
||||||
"CMAKE_BUILD_TYPE": "Release",
|
"CMAKE_BUILD_TYPE": "Release"
|
||||||
"RELEASE_BUILD": "ON"
|
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
{
|
{
|
||||||
"name": "ninja-debug",
|
"name": "debug",
|
||||||
"generator": "Ninja",
|
"generator": "Ninja",
|
||||||
"binaryDir": "${sourceDir}/build",
|
"binaryDir": "${sourceDir}/build",
|
||||||
"cacheVariables": {
|
"cacheVariables": {
|
||||||
|
|||||||
@@ -1,13 +1,25 @@
|
|||||||
# JuiceAgent
|
# JuiceAgent
|
||||||
|
|
||||||
JuiceAgent is an advanced JVMTI-based injection framework designed for runtime JAR loading, bytecode transformation, and runtime JVM instrumentation, even when DisableAttachMechanism is enabled.
|
[English](README.md) | [简体中文](README_ZH.md)
|
||||||
|
|
||||||
|
JuiceAgent is an advanced JVMTI-based injection framework for runtime JAR loading, bytecode transformation, and runtime JVM instrumentation. It injects into a running JVM process even when `DisableAttachMechanism=true`, without requiring `-javaagent` startup arguments or the attach mechanism.
|
||||||
|
|
||||||
**Warning**: This project is still experimental and is not recommended for production use. Use it at your own risk.
|
**Warning**: This project is still experimental and is not recommended for production use. Use it at your own risk.
|
||||||
|
|
||||||
|
> **Tips**: Some antivirus software may flag JuiceAgent as malware. See [Antivirus False Positive Notice](docs/Antivirus-False-Positive.md) for details.
|
||||||
|
|
||||||
|
**Note**: This project is designed for a regular JVM. Custom JVMs may not be able to run it.
|
||||||
|
|
||||||
|
Welcome to join our QQ/Discord group for more information and support:
|
||||||
|
- Discord: [JuiceDev](https://discord.gg/AQTnUyWNNJ)
|
||||||
|
- QQ Group: 1103504356
|
||||||
|
|
||||||
|
|
||||||

|

|
||||||

|

|
||||||

|

|
||||||

|

|
||||||
|

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

|

|
||||||

|

|
||||||
@@ -20,66 +32,81 @@ JuiceAgent is an advanced JVMTI-based injection framework designed for runtime J
|
|||||||

|

|
||||||

|

|
||||||
|
|
||||||
## Introduction
|
|
||||||
JuiceAgent is a JVMTI-native injection framework for loading external JARs and redefining or retransformation of Java classes in a target JVM without requiring -javaagent startup arguments or attach javaagent. It also works when DisableAttachMechanism=true.
|
|
||||||
|
|
||||||
With JuiceAgent, developers can:
|
|
||||||
- Dynamically load external JARs into a running JVM process
|
|
||||||
- Invoke a specified entry class and method after injection
|
|
||||||
- Redefine already loaded classes at runtime
|
|
||||||
- Retransform bytecode for instrumentation or modification
|
|
||||||
- And more...
|
|
||||||
|
|
||||||
**If you have any questions or suggestions, please feel free to open an issue or submit a pull request. =D**
|
|
||||||
|
|
||||||
## Index
|
## Index
|
||||||
|
|
||||||
- [JuiceAgent](#juiceagent)
|
- [JuiceAgent](#juiceagent)
|
||||||
- [Introduction](#introduction)
|
- [Introduction](#introduction)
|
||||||
- [Index](#index)
|
- [How It Works](#how-it-works)
|
||||||
- [Features](#features)
|
- [Features](#features)
|
||||||
|
- [Project Structure](#project-structure)
|
||||||
- [Quick Start](#quick-start)
|
- [Quick Start](#quick-start)
|
||||||
- [1. Download Release](#1-download-release)
|
- [JuiceAgent API](#juiceagent-api)
|
||||||
- [2. Copy your custom JAR/Dependencies to Directory](#2-copy-your-custom-jardependencies-to-directory)
|
- [Examples](#examples)
|
||||||
- [3. Write Config](#3-write-config)
|
|
||||||
- [4. Run the Injector](#4-run-the-injector)
|
|
||||||
- [Method A: Use `injector.exe`](#method-a-use-injectorexe)
|
|
||||||
- [Method B: Use JNI to call `inject`](#method-b-use-jni-to-call-inject)
|
|
||||||
- [5. Done](#5-done)
|
|
||||||
- [How To Build](#how-to-build)
|
- [How To Build](#how-to-build)
|
||||||
- [Requirements](#requirements)
|
|
||||||
- [Build with CMake Presets](#build-with-cmake-presets)
|
|
||||||
- [Manual Build](#manual-build)
|
|
||||||
- [Full Disclaimer](#full-disclaimer)
|
- [Full Disclaimer](#full-disclaimer)
|
||||||
- [Acknowledgements](#acknowledgements)
|
- [Acknowledgements](#acknowledgements)
|
||||||
|
|
||||||
## Features
|
## Introduction
|
||||||
This project is the native implementation of JuiceAgent-API. See [JuiceAgent.java](https://github.com/xiaozhou233/JuiceAgent-API/blob/master/src/main/java/cn/xiaozhou233/juiceagent/api/JuiceAgent.java) for the API definition.
|
|
||||||
|
|
||||||
- Load JARs into the Bootstrap or System ClassLoader
|
JuiceAgent is the native implementation of the [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API). It loads external JARs into a running JVM, invokes a specified entry class/method, and redefines or retransforms already-loaded classes — all without a `-javaagent` startup flag and even when `DisableAttachMechanism=true`.
|
||||||
|
|
||||||
|
With JuiceAgent, developers can:
|
||||||
|
|
||||||
|
- Dynamically load external JARs into a running JVM process
|
||||||
|
- Invoke a specified entry class and method after injection
|
||||||
|
- Redefine already loaded classes at runtime
|
||||||
|
- Retransform bytecode for instrumentation or modification
|
||||||
|
- Query loaded classes and read class bytecode
|
||||||
|
|
||||||
|
**If you have any questions or suggestions, please feel free to open an issue or submit a pull request. =D**
|
||||||
|
|
||||||
|
## How It Works
|
||||||
|
|
||||||
|
1. `injector.exe` (or `libinject.dll` via JNI) reflectively injects `libloader.dll` into the target JVM process.
|
||||||
|
2. `libloader.dll` attaches to the JVM, reads `config.toml`, extracts the embedded `JuiceAgent-API` jar, and adds it to the system class loader search path.
|
||||||
|
3. The loader bootstraps the agent: it loads `libagent.dll` and initializes the JVMTI agent (`JuiceAgent::Agent`).
|
||||||
|
4. The agent registers JVMTI callbacks and starts the configured modules (e.g. `JarLoader`), which loads the target JAR and invokes the entry class/method.
|
||||||
|
|
||||||
|
The `JuiceAgent-API` jar is embedded in the native binaries, so no separate download is required.
|
||||||
|
|
||||||
|
## Features
|
||||||
|
|
||||||
|
- Load external JARs into the Bootstrap or System ClassLoader
|
||||||
|
- Add JARs to an arbitrary class loader
|
||||||
- Define classes dynamically
|
- Define classes dynamically
|
||||||
- Redefine classes by name or class reference
|
- Redefine classes by name or class reference
|
||||||
- Retransform classes by name or class reference
|
- Retransform classes by name or class reference
|
||||||
- Get all loaded classes
|
- Get all loaded classes
|
||||||
- Find classes by name
|
- Find a class by name
|
||||||
- Get class bytecode by name or class reference
|
- Get class bytecode by name or class reference
|
||||||
|
- Automatic JVM attachment that works with `DisableAttachMechanism=true`
|
||||||
|
|
||||||
|
## Project Structure
|
||||||
|
|
||||||
|
- `src/libloader` — `libloader.dll`. Injected into the target JVM. Attaches to the JVM, parses `config.toml`, injects the embedded `JuiceAgent-API`, and bootstraps the agent.
|
||||||
|
- `src/libagent` — `libagent.dll`. The JVMTI agent. Registers callbacks (e.g. `ClassFileLoadHook`) and implements the native side of `JuiceAgent-API`.
|
||||||
|
- `src/injector` — `injector.exe`. Command-line driver that loads `libinject.dll` and injects `libloader.dll` into the target process.
|
||||||
|
- `src/libinject` — `libinject.dll`. Reflective DLL injector. Exposes a native `inject` function and JNI bindings (`cn.xiaozhou233.juiceagent.injector.InjectorNative`).
|
||||||
|
|
||||||
## Quick Start
|
## Quick Start
|
||||||
|
|
||||||
|
**You can also see the [examples](https://github.com/xiaozhou233/JuiceAgent/tree/main/examples) directory for more detailed usage examples.**
|
||||||
|
|
||||||
### 1. Download Release
|
### 1. Download Release
|
||||||
Download `libagent.dll` `libinject.dll` `libloader.dll` and `injector.exe` from the [releases](https://github.com/xiaozhou233/JuiceAgent/releases) page.
|
|
||||||
|
|
||||||
Download `JuiceAgent-API-x.x.x+build.x.jar` from the [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API/releases) page.
|
Download `JuiceAgent_vx.x.x_x64.zip` from the [releases](https://github.com/xiaozhou233/JuiceAgent/releases) page.
|
||||||
|
|
||||||
|
Extract the ZIP file to a directory:
|
||||||
|
|
||||||
Put the downloaded files into the same directory.
|
|
||||||
- YourDir
|
- YourDir
|
||||||
- JuiceAgent-API-x.x.x+build.x.jar
|
|
||||||
- libagent.dll
|
- libagent.dll
|
||||||
- libinject.dll
|
- libinject.dll
|
||||||
- libloader.dll
|
- libloader.dll
|
||||||
- injector.exe
|
- injector.exe
|
||||||
|
|
||||||
### 2. Copy your custom JAR/Dependencies to Directory
|
### 2. Copy your Custom JAR / Dependencies
|
||||||
|
|
||||||
- YourDir
|
- YourDir
|
||||||
- JuiceAgent-API-x.x.x+build.x.jar
|
|
||||||
- libagent.dll
|
- libagent.dll
|
||||||
- libinject.dll
|
- libinject.dll
|
||||||
- libloader.dll
|
- libloader.dll
|
||||||
@@ -93,33 +120,28 @@ Put the downloaded files into the same directory.
|
|||||||
|
|
||||||
```toml
|
```toml
|
||||||
[JuiceAgent]
|
[JuiceAgent]
|
||||||
Version = 1
|
Version = 2
|
||||||
|
# Path to libagent.dll, default is "./libagent.dll" (relative to the runtime directory)
|
||||||
[JuiceAgent.Loader]
|
|
||||||
# Path to JuiceAgent-API-x.x.x+build.x.jar
|
|
||||||
JuiceAgentAPIJarPath = "./JuiceAgent-API-x.x.x+build.x.jar"
|
|
||||||
# Path to libagent.dll, default is "./libagent.dll"
|
|
||||||
JuiceAgentNativeLibraryPath = ""
|
JuiceAgentNativeLibraryPath = ""
|
||||||
|
|
||||||
[JuiceAgent.Modules]
|
[JarLoader]
|
||||||
|
|
||||||
[JuiceAgent.Modules.JarLoader]
|
|
||||||
Enabled = true
|
Enabled = true
|
||||||
# Path to the Injection JAR files to be loaded
|
# Mode: BuiltIn | CustomJar
|
||||||
|
Mode = "BuiltIn"
|
||||||
|
# Directory containing dependency JARs to load first (BuiltIn mode)
|
||||||
InjectionDir = "./injection"
|
InjectionDir = "./injection"
|
||||||
# Path to the JAR file to be loaded
|
# Path to the JAR file to be loaded
|
||||||
JarPath = "./MyCustomJar.jar"
|
JarPath = "./MyCustomJar.jar"
|
||||||
# Entry class to be executed after loading the JAR
|
# Entry class to be executed after loading the JAR
|
||||||
EntryClass = "Example.Main"
|
EntryClass = "Example.Main"
|
||||||
# Entry method to be executed after loading the JAR
|
# Entry method, must be: public static void run()
|
||||||
EntryMethod = "run"
|
EntryMethod = "run"
|
||||||
```
|
```
|
||||||
|
|
||||||
Save the config file as `config.toml`.
|
Save the file as `config.toml` in the same directory (the runtime directory). Relative paths are resolved against the runtime directory. See [Configuration](docs/config.md) for the complete reference.
|
||||||
|
|
||||||
- YourDir
|
- YourDir
|
||||||
- **config.toml**
|
- **config.toml**
|
||||||
- JuiceAgent-API-x.x.x+build.x.jar
|
|
||||||
- libagent.dll
|
- libagent.dll
|
||||||
- libinject.dll
|
- libinject.dll
|
||||||
- libloader.dll
|
- libloader.dll
|
||||||
@@ -132,7 +154,8 @@ Save the config file as `config.toml`.
|
|||||||
### 4. Run the Injector
|
### 4. Run the Injector
|
||||||
|
|
||||||
#### Method A: Use `injector.exe`
|
#### Method A: Use `injector.exe`
|
||||||
Run `injector.exe` from `YourDir`.
|
|
||||||
|
Run `injector.exe` from `YourDir`:
|
||||||
|
|
||||||
```text
|
```text
|
||||||
<jps output>
|
<jps output>
|
||||||
@@ -141,31 +164,61 @@ Input PID:
|
|||||||
|
|
||||||
Enter the PID of the target JVM process and press Enter.
|
Enter the PID of the target JVM process and press Enter.
|
||||||
|
|
||||||
|
You can also pass arguments directly: `injector.exe <pid> <libloader.dll path> [libinject.dll path]`.
|
||||||
|
|
||||||
#### Method B: Use JNI to call `inject`
|
#### Method B: Use JNI to call `inject`
|
||||||
|
|
||||||
See [Documents](https://github.com/xiaozhou233/JuiceAgent/blob/main/docs/Inject.md) for details.
|
See [Inject](docs/Inject.md)
|
||||||
|
|
||||||
### 5. Done
|
### 5. Done
|
||||||
|
|
||||||
The target JVM will load the specified JAR and execute the specified entry class and method.
|
The target JVM will load the specified JAR and execute the specified entry class and method.
|
||||||
|
|
||||||
|
## JuiceAgent API
|
||||||
|
|
||||||
|
The following native functions are exposed to Java through the `cn.xiaozhou233.juiceagent.api.JuiceAgent` class (see the [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API) project for the Java API definition):
|
||||||
|
|
||||||
|
- `init(String runtimeDir)` — initialize the agent from Java
|
||||||
|
- `addToBootstrapClassLoaderSearch(String jarPath)`
|
||||||
|
- `addToSystemClassLoaderSearch(String jarPath)`
|
||||||
|
- `addToClassLoader(String jarPath, ClassLoader targetClassLoader)`
|
||||||
|
- `defineClass(ClassLoader targetClassLoader, byte[] bytes)` — returns `Class<?>`
|
||||||
|
- `redefineClass(Class<?> clazz, byte[] classBytes, int length)`
|
||||||
|
- `redefineClassByName(String className, byte[] classBytes, int length)`
|
||||||
|
- `retransformClass(Class<?> clazz, byte[] bytecodes, int length)`
|
||||||
|
- `retransformClassByName(String className, byte[] bytecodes, int length)`
|
||||||
|
- `getLoadedClasses()` — returns `Class<?>[]`
|
||||||
|
- `getClassByName(String name)` — returns `Class<?>`
|
||||||
|
- `getClassBytes(Class<?> clazz)` — returns `byte[]`
|
||||||
|
- `getClassBytesByName(String name)` — returns `byte[]`
|
||||||
|
|
||||||
|
## Examples
|
||||||
|
|
||||||
|
- `examples/inject-via-java-api` — injects JuiceAgent into a running JVM through the Java API (JNI), without needing `injector.exe`.
|
||||||
|
- `examples/load-via-injector-exe` — loads a JAR into a target JVM via `injector.exe` and runs an entry point.
|
||||||
|
- `examples/retransform-class` — demonstrates class retransformation with a target JVM and a modified copy of the class.
|
||||||
|
|
||||||
## How To Build
|
## How To Build
|
||||||
|
|
||||||
### Requirements
|
### Requirements
|
||||||
|
|
||||||
- Java 8+
|
- Java 8+
|
||||||
- MinGW
|
- MinGW
|
||||||
- CMake 3.15+
|
- CMake 3.15+
|
||||||
- Ninja
|
- Ninja
|
||||||
|
|
||||||
### Build with CMake Presets
|
### Build with CMake Presets
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
git clone https://github.com/xiaozhou233/JuiceAgent.git
|
git clone https://github.com/xiaozhou233/JuiceAgent.git
|
||||||
cd JuiceAgent
|
cd JuiceAgent
|
||||||
|
|
||||||
cmake --preset ninja-release
|
cmake --preset release
|
||||||
cmake --build build
|
cmake --build build
|
||||||
```
|
```
|
||||||
|
|
||||||
### Manual Build
|
### Manual Build
|
||||||
|
|
||||||
```powershell
|
```powershell
|
||||||
git clone https://github.com/xiaozhou233/JuiceAgent.git
|
git clone https://github.com/xiaozhou233/JuiceAgent.git
|
||||||
cd JuiceAgent
|
cd JuiceAgent
|
||||||
@@ -176,13 +229,12 @@ cmake --build build
|
|||||||
|
|
||||||
The generated binaries will be placed in `build/bin`.
|
The generated binaries will be placed in `build/bin`.
|
||||||
|
|
||||||
`JuiceAgent-API.jar` can be built from or downloaded from [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API).
|
|
||||||
|
|
||||||
## Full Disclaimer
|
## Full Disclaimer
|
||||||
|
|
||||||
This project is intended for learning and research in controlled environments only. The author is not responsible for any consequences arising from unauthorized use, modification, cracking, or violation of any applicable agreements or laws. Users are responsible for ensuring that their actions are legal and compliant.
|
This project is intended for learning and research in controlled environments only. The author is not responsible for any consequences arising from unauthorized use, modification, cracking, or violation of any applicable agreements or laws. Users are responsible for ensuring that their actions are legal and compliant.
|
||||||
|
|
||||||
## Acknowledgements
|
## Acknowledgements
|
||||||
- [ReflectiveDLLInjection](https://github.com/stephenfewer/ReflectiveDLLInjection) - DLL injection implementation
|
|
||||||
- [plog](https://github.com/SergiusTheBest/plog) - Portable, simple, and extensible C++ logging library
|
- [ReflectiveDLLInjection](https://github.com/stephenfewer/ReflectiveDLLInjection) — DLL injection implementation
|
||||||
- [toml11](https://github.com/ToruNiina/toml11) - TOML for Modern C++
|
- [spdlog](https://github.com/gabime/spdlog) — Fast C++ logging library
|
||||||
- [eventpp](https://github.com/wqking/eventpp) - C++ library for event dispatchers and callback lists
|
- [toml11](https://github.com/ToruNiina/toml11) — TOML for Modern C++
|
||||||
+241
@@ -0,0 +1,241 @@
|
|||||||
|
# JuiceAgent
|
||||||
|
|
||||||
|
[English](README.md) | [简体中文](README_ZH.md)
|
||||||
|
|
||||||
|
> **注意**:本文档由 AI 自动翻译,可能存在不准确或不通顺之处,请以 [英文版 README](README.md) 为准。如有疑问欢迎提 issue 或 PR 修正。
|
||||||
|
|
||||||
|
JuiceAgent 是一个基于 JVMTI 的高级注入框架,用于运行时 JAR 加载、字节码变换和运行时 JVM 插桩。它可以在 `DisableAttachMechanism=true` 的情况下注入到正在运行的 JVM 进程中,无需 `-javaagent` 启动参数,也无需使用 attach 机制。
|
||||||
|
|
||||||
|
**警告**:本项目仍处于实验阶段,不建议用于生产环境。使用风险自负。
|
||||||
|
|
||||||
|
> **提示**:部分杀毒软件可能将 JuiceAgent 误报为恶意软件。详情见[杀毒软件误报说明](docs/Antivirus-False-Positive.md)。
|
||||||
|
|
||||||
|
**注意**:本项目针对标准 JVM 设计,自定义 JVM 可能无法运行。
|
||||||
|
|
||||||
|
欢迎加入我们的 QQ / Discord 群组获取更多信息和支持:
|
||||||
|
- Discord:[JuiceDev](https://discord.gg/AQTnUyWNNJ)
|
||||||
|
- QQ 群:1103504356
|
||||||
|
|
||||||
|

|
||||||
|

|
||||||
|

|
||||||
|

|
||||||
|

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

|
||||||
|

|
||||||
|

|
||||||
|

|
||||||
|

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

|
||||||
|

|
||||||
|

|
||||||
|

|
||||||
|
|
||||||
|
## 目录
|
||||||
|
|
||||||
|
- [JuiceAgent](#juiceagent)
|
||||||
|
- [简介](#简介)
|
||||||
|
- [工作原理](#工作原理)
|
||||||
|
- [特性](#特性)
|
||||||
|
- [项目结构](#项目结构)
|
||||||
|
- [快速开始](#快速开始)
|
||||||
|
- [JuiceAgent API](#juiceagent-api)
|
||||||
|
- [示例](#示例)
|
||||||
|
- [如何构建](#如何构建)
|
||||||
|
- [完整免责声明](#完整免责声明)
|
||||||
|
- [致谢](#致谢)
|
||||||
|
|
||||||
|
## 简介
|
||||||
|
|
||||||
|
JuiceAgent 是 [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API) 的原生实现。它可以将外部 JAR 加载到正在运行的 JVM 中、调用指定的入口类/方法,并重新定义或重变换已加载的类——全程无需 `-javaagent` 启动参数,即使 `DisableAttachMechanism=true` 也能工作。
|
||||||
|
|
||||||
|
使用 JuiceAgent 可以做到:
|
||||||
|
|
||||||
|
- 将外部 JAR 动态加载到正在运行的 JVM 进程
|
||||||
|
- 注入后调用指定的入口类和入口方法
|
||||||
|
- 在运行时重新定义已加载的类
|
||||||
|
- 重变换字节码以进行插桩或修改
|
||||||
|
- 查询已加载的类并读取类的字节码
|
||||||
|
|
||||||
|
**如果你有任何问题或建议,欢迎提 issue 或提交 pull request。=D**
|
||||||
|
|
||||||
|
## 工作原理
|
||||||
|
|
||||||
|
1. `injector.exe`(或通过 JNI 调用 `libinject.dll`)将 `libloader.dll` 反射注入到目标 JVM 进程。
|
||||||
|
2. `libloader.dll` 附加到 JVM,读取 `config.toml`,解出内嵌的 `JuiceAgent-API` jar 并将其加入系统类加载器的搜索路径。
|
||||||
|
3. 加载器引导 agent:加载 `libagent.dll` 并初始化 JVMTI agent(`JuiceAgent::Agent`)。
|
||||||
|
4. agent 注册 JVMTI 回调并启动配置的模块(例如 `JarLoader`),加载目标 JAR 并调用入口类/方法。
|
||||||
|
|
||||||
|
`JuiceAgent-API` jar 内嵌于原生二进制中,无需单独下载。
|
||||||
|
|
||||||
|
## 特性
|
||||||
|
|
||||||
|
- 将外部 JAR 加载到 Bootstrap 或 System ClassLoader
|
||||||
|
- 将 JAR 添加到任意类加载器
|
||||||
|
- 动态定义类
|
||||||
|
- 按名称或类引用重新定义类
|
||||||
|
- 按名称或类引用重变换类
|
||||||
|
- 获取所有已加载的类
|
||||||
|
- 按名称查找类
|
||||||
|
- 按名称或类引用获取类的字节码
|
||||||
|
- 自动附加 JVM,支持 `DisableAttachMechanism=true`
|
||||||
|
|
||||||
|
## 项目结构
|
||||||
|
|
||||||
|
- `src/libloader` — `libloader.dll`。注入到目标 JVM,附加 JVM、解析 `config.toml`、注入内嵌的 `JuiceAgent-API` 并引导 agent。
|
||||||
|
- `src/libagent` — `libagent.dll`。JVMTI agent。注册回调(例如 `ClassFileLoadHook`)并实现 `JuiceAgent-API` 的原生侧。
|
||||||
|
- `src/injector` — `injector.exe`。命令行驱动,加载 `libinject.dll` 并将 `libloader.dll` 注入到目标进程。
|
||||||
|
- `src/libinject` — `libinject.dll`。反射式 DLL 注入器,导出原生 `inject` 函数并提供 JNI 绑定(`cn.xiaozhou233.juiceagent.injector.InjectorNative`)。
|
||||||
|
|
||||||
|
## 快速开始
|
||||||
|
|
||||||
|
**你也可以查看 [examples](https://github.com/xiaozhou233/JuiceAgent/tree/main/examples) 目录获取更详细的使用示例。**
|
||||||
|
|
||||||
|
### 1. 下载 Release
|
||||||
|
|
||||||
|
从 [releases](https://github.com/xiaozhou233/JuiceAgent/releases) 页面下载 `JuiceAgent_vx.x.x_x64.zip`。
|
||||||
|
|
||||||
|
解压 ZIP 到一个目录:
|
||||||
|
|
||||||
|
- YourDir
|
||||||
|
- libagent.dll
|
||||||
|
- libinject.dll
|
||||||
|
- libloader.dll
|
||||||
|
- injector.exe
|
||||||
|
|
||||||
|
### 2. 拷贝自定义 JAR / 依赖
|
||||||
|
|
||||||
|
- YourDir
|
||||||
|
- libagent.dll
|
||||||
|
- libinject.dll
|
||||||
|
- libloader.dll
|
||||||
|
- injector.exe
|
||||||
|
- **MyCustomJar.jar**
|
||||||
|
- **injection**
|
||||||
|
- **Dependencies1.jar**
|
||||||
|
- **Dependencies2.jar**
|
||||||
|
|
||||||
|
### 3. 编写配置
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[JuiceAgent]
|
||||||
|
Version = 2
|
||||||
|
# libagent.dll 的路径,默认是 "./libagent.dll"(相对于运行时目录)
|
||||||
|
JuiceAgentNativeLibraryPath = ""
|
||||||
|
|
||||||
|
[JarLoader]
|
||||||
|
Enabled = true
|
||||||
|
# Mode:BuiltIn | CustomJar
|
||||||
|
Mode = "BuiltIn"
|
||||||
|
# 需要优先加载的依赖 JAR 所在目录(BuiltIn 模式)
|
||||||
|
InjectionDir = "./injection"
|
||||||
|
# 要加载的 JAR 文件路径
|
||||||
|
JarPath = "./MyCustomJar.jar"
|
||||||
|
# 加载 JAR 后要执行的入口类
|
||||||
|
EntryClass = "Example.Main"
|
||||||
|
# 入口方法,必须是:public static void run()
|
||||||
|
EntryMethod = "run"
|
||||||
|
```
|
||||||
|
|
||||||
|
将文件保存为 `config.toml` 并放在同一目录(运行时目录)中。相对路径以运行时目录为基准解析。完整配置说明见 [Configuration](docs/config.md)。
|
||||||
|
|
||||||
|
- YourDir
|
||||||
|
- **config.toml**
|
||||||
|
- libagent.dll
|
||||||
|
- libinject.dll
|
||||||
|
- libloader.dll
|
||||||
|
- injector.exe
|
||||||
|
- MyCustomJar.jar
|
||||||
|
- injection
|
||||||
|
- Dependencies1.jar
|
||||||
|
- Dependencies2.jar
|
||||||
|
|
||||||
|
### 4. 运行注入器
|
||||||
|
|
||||||
|
#### 方法 A:使用 `injector.exe`
|
||||||
|
|
||||||
|
在 `YourDir` 下运行 `injector.exe`:
|
||||||
|
|
||||||
|
```text
|
||||||
|
<jps output>
|
||||||
|
Input PID:
|
||||||
|
```
|
||||||
|
|
||||||
|
输入目标 JVM 进程的 PID 并按回车。
|
||||||
|
|
||||||
|
也可以直接传参:`injector.exe <pid> <libloader.dll 路径> [libinject.dll 路径]`。
|
||||||
|
|
||||||
|
#### 方法 B:通过 JNI 调用 `inject`
|
||||||
|
|
||||||
|
看 [Inject](docs/Inject.md)
|
||||||
|
|
||||||
|
### 5. 完成
|
||||||
|
|
||||||
|
目标 JVM 将加载指定的 JAR 并执行指定的入口类和入口方法。
|
||||||
|
|
||||||
|
## JuiceAgent API
|
||||||
|
|
||||||
|
以下原生函数通过 `cn.xiaozhou233.juiceagent.api.JuiceAgent` 类暴露给 Java(Java API 定义见 [JuiceAgent-API](https://github.com/xiaozhou233/JuiceAgent-API) 项目):
|
||||||
|
|
||||||
|
- `init(String runtimeDir)` — 从 Java 初始化 agent
|
||||||
|
- `addToBootstrapClassLoaderSearch(String jarPath)`
|
||||||
|
- `addToSystemClassLoaderSearch(String jarPath)`
|
||||||
|
- `addToClassLoader(String jarPath, ClassLoader targetClassLoader)`
|
||||||
|
- `defineClass(ClassLoader targetClassLoader, byte[] bytes)` — 返回 `Class<?>`
|
||||||
|
- `redefineClass(Class<?> clazz, byte[] classBytes, int length)`
|
||||||
|
- `redefineClassByName(String className, byte[] classBytes, int length)`
|
||||||
|
- `retransformClass(Class<?> clazz, byte[] bytecodes, int length)`
|
||||||
|
- `retransformClassByName(String className, byte[] bytecodes, int length)`
|
||||||
|
- `getLoadedClasses()` — 返回 `Class<?>[]`
|
||||||
|
- `getClassByName(String name)` — 返回 `Class<?>`
|
||||||
|
- `getClassBytes(Class<?> clazz)` — 返回 `byte[]`
|
||||||
|
- `getClassBytesByName(String name)` — 返回 `byte[]`
|
||||||
|
|
||||||
|
## 示例
|
||||||
|
|
||||||
|
- `examples/inject-via-java-api` — 通过 Java API(JNI)将 JuiceAgent 注入到正在运行的 JVM,无需 `injector.exe`。
|
||||||
|
- `examples/load-via-injector-exe` — 通过 `injector.exe` 将 JAR 加载到目标 JVM 并运行入口点。
|
||||||
|
- `examples/retransform-class` — 演示使用目标 JVM 和修改后的类副本进行类重变换。
|
||||||
|
|
||||||
|
## 如何构建
|
||||||
|
|
||||||
|
### 环境要求
|
||||||
|
|
||||||
|
- Java 8+
|
||||||
|
- MinGW
|
||||||
|
- CMake 3.15+
|
||||||
|
- Ninja
|
||||||
|
|
||||||
|
### 使用 CMake Presets 构建
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
git clone https://github.com/xiaozhou233/JuiceAgent.git
|
||||||
|
cd JuiceAgent
|
||||||
|
|
||||||
|
cmake --preset release
|
||||||
|
cmake --build build
|
||||||
|
```
|
||||||
|
|
||||||
|
### 手动构建
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
git clone https://github.com/xiaozhou233/JuiceAgent.git
|
||||||
|
cd JuiceAgent
|
||||||
|
|
||||||
|
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
|
||||||
|
cmake --build build
|
||||||
|
```
|
||||||
|
|
||||||
|
生成的二进制文件将放在 `build/bin` 中。
|
||||||
|
|
||||||
|
## 完整免责声明
|
||||||
|
|
||||||
|
本项目仅用于受控环境下的学习与研究。作者不对因未授权使用、修改、破解或违反任何适用协议或法律所造成的后果负责。用户有责任确保其行为合法合规。
|
||||||
|
|
||||||
|
## 致谢
|
||||||
|
|
||||||
|
- [ReflectiveDLLInjection](https://github.com/stephenfewer/ReflectiveDLLInjection) — DLL 注入实现
|
||||||
|
- [spdlog](https://github.com/gabime/spdlog) — 高性能 C++ 日志库
|
||||||
|
- [toml11](https://github.com/ToruNiina/toml11) — 现代 C++ 的 TOML 库
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
# TODO - 开发待办事项
|
|
||||||
这个文档用来记录开发时的待办事项以及以后的开发计划。
|
|
||||||
---
|
|
||||||
|
|
||||||
## 2026-04-16
|
|
||||||
- [ ] ~~把读取toml的库换成支持toml 1.0的库~~
|
|
||||||
- [x] 在 `includes/JuiceAgent` 文件夹下实现 `Config.hpp` 配置系统
|
|
||||||
- [ ] ~~新建测试 读取配置文件 (放弃)~~
|
|
||||||
|
|
||||||
- [ ] 重构 `libloader` 的配置系统
|
|
||||||
|
|
||||||
## 2026-04-17
|
|
||||||
- [x] 重构项目为模块化项目
|
|
||||||
- [x] `libloader` 模块只负责加载`JuiceAgent-API`和`JuiceAgent`, Jar文件由`JuiceAgent`接管
|
|
||||||
- [x] `libloader` 读取配置文件并传参`JuiceAgentNativePath`和`ConfigDir`到 `JuiceAgent` 中,由`JuiceAgent`读取配置文件继续进行操作
|
|
||||||
|
|
||||||
## 2026-04-19
|
|
||||||
- [x] 在 `JuiceAgent/Utils.hpp`做序列化操作
|
|
||||||
- [x] 统一调用 module的Java实现
|
|
||||||
|
|
||||||
## 2026-04-20
|
|
||||||
- [x] 修改文档
|
|
||||||
+3
-1
@@ -1 +1,3 @@
|
|||||||
VERSION = Version 3.3.2 Build 1
|
Major=5
|
||||||
|
Minor=0
|
||||||
|
Patch=0
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
# 杀毒软件误报说明 / Antivirus False Positive Notice
|
||||||
|
|
||||||
|
## 中文
|
||||||
|
|
||||||
|
JuiceAgent 的 `libloader.dll` 在部分杀毒软件中可能被误报为恶意程序。原因如下:
|
||||||
|
|
||||||
|
1. **进程注入技术**:本项目需通过远程线程将 DLL 注入到目标 JVM 进程(`VirtualAllocEx` + `WriteProcessMemory` + `CreateRemoteThread`),这是杀软对"进程注入"行为的常见告警特征。
|
||||||
|
2. **反射加载(Reflective Loading)**:`libloader.dll` 使用反射加载器在内存中手动解析 PE 并加载,不经过常规的 `LoadLibrary` 加载流程,与部分恶意软件(无文件攻击)的技术高度相似。
|
||||||
|
3. **API 哈希**:为规避导入表,代码使用哈希解析 `LoadLibrary`/`GetProcAddress` 等 API,该手法也是杀软重点检测的静态特征。
|
||||||
|
|
||||||
|
以上技术均为实现 JVMTI 运行时注入所必需,项目本身不包含任何恶意行为。由于这些行为与恶意软件特征高度重合,**无法完全消除误报**。请在使用前自行判断风险,或将其加入杀软白名单。
|
||||||
|
|
||||||
|
## English
|
||||||
|
|
||||||
|
`libloader.dll` in JuiceAgent may be flagged as malware by some antivirus software. The reasons are as follows:
|
||||||
|
|
||||||
|
1. **Process Injection**: This project injects a DLL into the target JVM process via a remote thread (`VirtualAllocEx` + `WriteProcessMemory` + `CreateRemoteThread`). Process injection is a common behavior signature that antivirus engines flag.
|
||||||
|
2. **Reflective Loading**: `libloader.dll` uses a reflective loader to manually parse and map a PE image in memory, bypassing the normal `LoadLibrary` loading flow. This closely resembles fileless malware techniques.
|
||||||
|
3. **API Hashing**: The code resolves APIs such as `LoadLibrary`/`GetProcAddress` by hash instead of using an import table, a static feature also heavily targeted by AV engines.
|
||||||
|
|
||||||
|
These techniques are all required to implement JVMTI runtime injection. The project itself contains no malicious behavior. However, because these behaviors closely overlap with malware signatures, **false positives cannot be completely eliminated**. Please assess the risk before use, or add the binaries to your antivirus whitelist.
|
||||||
+4
-22
@@ -11,34 +11,16 @@ Input PID:
|
|||||||
Enter the PID of the target JVM process and press Enter.
|
Enter the PID of the target JVM process and press Enter.
|
||||||
|
|
||||||
## Method B: Use JNI to call `inject`
|
## Method B: Use JNI to call `inject`
|
||||||
Create `cn/xiaozhou233/juiceagent/injector/InjectorNative.java` in your project:
|
Download the JuiceAgent-JavaInjector-x.x-xxxx.jar from [here](https://github.com/xiaozhou233/JuiceAgent-JavaInjector/releases).
|
||||||
|
|
||||||
```java
|
Add JuiceAgent-JavaInjector-x.x-xxxx.jar to your classpath.
|
||||||
package cn.xiaozhou233.juiceagent.injector;
|
|
||||||
|
|
||||||
public class InjectorNative {
|
|
||||||
/*
|
|
||||||
* @param pid target process id
|
|
||||||
* @param path injection DLL path
|
|
||||||
*/
|
|
||||||
public native boolean inject(int pid, String path);
|
|
||||||
|
|
||||||
/*
|
|
||||||
* @param pid target process id
|
|
||||||
* @param path injection DLL path
|
|
||||||
* @param configDir directory containing config.toml
|
|
||||||
*/
|
|
||||||
public native boolean inject(int pid, String path, String configDir);
|
|
||||||
}
|
|
||||||
```
|
|
||||||
|
|
||||||
Example:
|
Example:
|
||||||
|
|
||||||
```java
|
```java
|
||||||
import cn.xiaozhou233.juiceagent.injector.InjectorNative;
|
import cn.xiaozhou233.juiceagent.injector.Injector;
|
||||||
|
|
||||||
System.load("<path-to-libinject>");
|
System.load("<path-to-libinject>");
|
||||||
InjectorNative injectorNative = new InjectorNative();
|
|
||||||
|
|
||||||
injectorNative.inject(<pid>, "<path-to-libloader>", "<path-to-config-directory>");
|
Injector.inject(<pid>, "<path-to-libloader>", "<path-to-config-directory>");
|
||||||
```
|
```
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
# Advanced
|
||||||
|
|
||||||
|
## Load Custom API / Directly Load Jar
|
||||||
|
|
||||||
|
JuiceAgent runs in **BuiltIn** mode by default: `libloader` registers the embedded
|
||||||
|
JuiceAgent-API jar, the agent bootstraps it, and the JarLoader module loads your JAR
|
||||||
|
and invokes its entry method.
|
||||||
|
|
||||||
|
If you don't need JuiceAgent-API — for example you want to provide your own bootstrap
|
||||||
|
and call an arbitrary class/method — set `JarLoader.Mode` to **`CustomJar`**:
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[JuiceAgent]
|
||||||
|
Version = 2
|
||||||
|
|
||||||
|
[JarLoader]
|
||||||
|
Mode = "CustomJar"
|
||||||
|
JarPath = "./my-agent.jar"
|
||||||
|
EntryClass = "com.example.MyBootstrap"
|
||||||
|
EntryMethod = "start"
|
||||||
|
```
|
||||||
|
|
||||||
|
Workflow in `CustomJar` mode:
|
||||||
|
|
||||||
|
1. `libloader` attaches to the target JVM and reads `config.toml`.
|
||||||
|
2. It adds `JarPath` to the system class loader search path. JuiceAgent-API is **not** loaded.
|
||||||
|
3. It invokes `EntryClass.EntryMethod`.
|
||||||
|
|
||||||
|
`EntryMethod` must be a `public static void` method that takes no arguments.
|
||||||
|
|
||||||
|
> `JarLoader.Enabled` and `JarLoader.InjectionDir` only apply to `BuiltIn` mode; they are
|
||||||
|
> ignored in `CustomJar` mode.
|
||||||
|
|
||||||
|
See [Configuration](config.md) for the complete list of keys.
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
# Configuration (`config.toml`)
|
||||||
|
|
||||||
|
JuiceAgent reads a single `config.toml` from the **runtime directory** (the directory
|
||||||
|
passed to the injector / loader; the current working directory is used when none is
|
||||||
|
given). Paths that start with `./` are resolved against the runtime directory;
|
||||||
|
absolute paths are used as-is.
|
||||||
|
|
||||||
|
The current schema version is **2**. `JuiceAgent.Version` must match the version
|
||||||
|
expected by the binaries, otherwise the loader stops with a version mismatch error.
|
||||||
|
|
||||||
|
## Example
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[JuiceAgent]
|
||||||
|
Version = 2
|
||||||
|
JuiceAgentNativeLibraryPath = ""
|
||||||
|
|
||||||
|
[JarLoader]
|
||||||
|
Enabled = true
|
||||||
|
Mode = "BuiltIn"
|
||||||
|
InjectionDir = "./injection"
|
||||||
|
JarPath = "./MyCustomJar.jar"
|
||||||
|
EntryClass = "Example.Main"
|
||||||
|
EntryMethod = "run"
|
||||||
|
```
|
||||||
|
|
||||||
|
## `[JuiceAgent]`
|
||||||
|
|
||||||
|
| Key | Type | Required | Default | Description |
|
||||||
|
| --- | --- | --- | --- | --- |
|
||||||
|
| `Version` | integer | yes | — | Configuration schema version. Must be `2`. |
|
||||||
|
| `JuiceAgentNativeLibraryPath` | string (path) | no | `./libagent.dll` | Path to `libagent.dll`, loaded by the bootstrap after injection. |
|
||||||
|
|
||||||
|
## `[JarLoader]`
|
||||||
|
|
||||||
|
| Key | Type | Required | Default | Description |
|
||||||
|
| --- | --- | --- | --- | --- |
|
||||||
|
| `Mode` | string | yes | — | How the target JAR is registered: `BuiltIn` or `CustomJar`. |
|
||||||
|
| `Enabled` | boolean | no | `false` | Run the JarLoader module after the agent is initialized (`BuiltIn` mode only). When `false`, no JAR is loaded and no entry method is invoked. |
|
||||||
|
| `InjectionDir` | string (path) | no | `./injection` | Directory of dependency JARs loaded before the main JAR (`BuiltIn` mode). |
|
||||||
|
| `JarPath` | string (path) | see below | `./Entry.jar` (`BuiltIn`) | The JAR to load. |
|
||||||
|
| `EntryClass` | string | see below | `Example.Main` (`BuiltIn`) | Entry class to invoke after loading the JAR. |
|
||||||
|
| `EntryMethod` | string | see below | `start` (`BuiltIn`) | Entry method, must be a `public static void` method with no parameters. |
|
||||||
|
|
||||||
|
> In `CustomJar` mode, `JarPath`, `EntryClass` and `EntryMethod` are required (there are
|
||||||
|
> no defaults); `Enabled` and `InjectionDir` are not used.
|
||||||
|
|
||||||
|
## Modes
|
||||||
|
|
||||||
|
### `BuiltIn` (recommended)
|
||||||
|
|
||||||
|
1. `libloader` extracts the embedded **JuiceAgent-API** jar and adds it to the system class loader.
|
||||||
|
2. The agent bootstraps JuiceAgent-API (`JuiceAgentBootstrap.start`).
|
||||||
|
3. If `Enabled = true`, the JarLoader module loads every `*.jar` from `InjectionDir`, then loads `JarPath`, and invokes `EntryClass.EntryMethod`.
|
||||||
|
|
||||||
|
This is the mode used by most users: keep JuiceAgent-API and just supply the JAR and
|
||||||
|
entry point to run.
|
||||||
|
|
||||||
|
### `CustomJar`
|
||||||
|
|
||||||
|
1. `libloader` adds `JarPath` itself to the system class loader. **JuiceAgent-API is not used.**
|
||||||
|
2. It invokes `EntryClass.EntryMethod` directly.
|
||||||
|
|
||||||
|
Use this when you want to bring your own bootstrap and call an arbitrary class/method.
|
||||||
|
See [Advanced](advanced.md#load-custom-api--directly-load-jar) for details.
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
# Temporary build directories
|
||||||
|
**/out/*
|
||||||
|
**/*.class
|
||||||
|
|
||||||
|
# JuiceAgent runtime binaries copied into the example (not committed)
|
||||||
|
**/injector.exe
|
||||||
|
**/libagent.dll
|
||||||
|
**/libinject.dll
|
||||||
|
**/libloader.dll
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
# Examples
|
||||||
|
|
||||||
|
A collection of JuiceAgent examples demonstrating different ways to inject
|
||||||
|
JuiceAgent into a running JVM process.
|
||||||
|
|
||||||
|
## 1. inject-via-java-api
|
||||||
|
|
||||||
|
Inject JuiceAgent into a running JVM using the Java API (JNI), without needing `injector.exe`.
|
||||||
|
|
||||||
|
- [HowToUse.md](./inject-via-java-api/HowToUse.md)
|
||||||
|
- [如何使用.md](./inject-via-java-api/如何使用.md)
|
||||||
|
|
||||||
|
## 2. load-via-injector-exe
|
||||||
|
|
||||||
|
Inject a JAR into a running JVM using `injector.exe`.
|
||||||
|
|
||||||
|
- [HowToUse.md](./load-via-injector-exe/HowToUse.md)
|
||||||
|
- [如何使用.md](./load-via-injector-exe/如何使用.md)
|
||||||
|
|
||||||
|
## 3. retransform-class
|
||||||
|
|
||||||
|
Retransform an already-loaded class at runtime after injection, without restarting the JVM.
|
||||||
|
|
||||||
|
- [HowToUse.md](./retransform-class/HowToUse.md)
|
||||||
|
- [如何使用.md](./retransform-class/如何使用.md)
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
# Examples
|
||||||
|
|
||||||
|
JuiceAgent 示例集合,演示将 JuiceAgent 注入到正在运行的 JVM 进程的不同方式。
|
||||||
|
|
||||||
|
## 1. inject-via-java-api
|
||||||
|
|
||||||
|
使用 Java API(JNI)将 JuiceAgent 注入正在运行的 JVM,无需使用 `injector.exe`。
|
||||||
|
|
||||||
|
- [HowToUse.md](./inject-via-java-api/HowToUse.md)
|
||||||
|
- [如何使用.md](./inject-via-java-api/如何使用.md)
|
||||||
|
|
||||||
|
## 2. load-via-injector-exe
|
||||||
|
|
||||||
|
使用 `injector.exe` 将 JAR 注入正在运行的 JVM。
|
||||||
|
|
||||||
|
- [HowToUse.md](./load-via-injector-exe/HowToUse.md)
|
||||||
|
- [如何使用.md](./load-via-injector-exe/如何使用.md)
|
||||||
|
|
||||||
|
## 3. retransform-class
|
||||||
|
|
||||||
|
注入后在运行时热替换(retransform)已加载的类,无需重启 JVM。
|
||||||
|
|
||||||
|
- [HowToUse.md](./retransform-class/HowToUse.md)
|
||||||
|
- [如何使用.md](./retransform-class/如何使用.md)
|
||||||
@@ -1,18 +0,0 @@
|
|||||||
[JuiceAgent]
|
|
||||||
Version = 1
|
|
||||||
|
|
||||||
[JuiceAgent.Loader]
|
|
||||||
JuiceAgentNativeLibraryPath = ""
|
|
||||||
|
|
||||||
[JuiceAgent.Modules]
|
|
||||||
|
|
||||||
[JuiceAgent.Modules.JarLoader]
|
|
||||||
Enabled = true
|
|
||||||
InjectionDir = ""
|
|
||||||
JarPath = ""
|
|
||||||
EntryClass = ""
|
|
||||||
EntryMethod = ""
|
|
||||||
|
|
||||||
[JuiceAgent.Modules.Dumper]
|
|
||||||
Enabled = false
|
|
||||||
DumpDir = ""
|
|
||||||
@@ -0,0 +1,94 @@
|
|||||||
|
# How to Use — inject-via-java-api (JuiceAgent)
|
||||||
|
|
||||||
|
This example demonstrates injecting JuiceAgent into a running JVM process
|
||||||
|
using the Java API (JNI), without needing `injector.exe`.
|
||||||
|
|
||||||
|
## Prerequisites
|
||||||
|
|
||||||
|
- Java 8+ installed and available in `PATH`
|
||||||
|
- JuiceAgent native DLLs (`libinject.dll`, `libloader.dll`, `libagent.dll`)
|
||||||
|
placed in the same directory as this example
|
||||||
|
- A `config.toml` file configured for your use case
|
||||||
|
|
||||||
|
## Quick Start
|
||||||
|
|
||||||
|
### Step 1: Build
|
||||||
|
|
||||||
|
Run `build.bat` to compile both the injector and the target jars:
|
||||||
|
|
||||||
|
```
|
||||||
|
> build.bat
|
||||||
|
```
|
||||||
|
|
||||||
|
### Step 2: Run the Target JVM
|
||||||
|
|
||||||
|
Open a terminal and start the target JVM:
|
||||||
|
|
||||||
|
```
|
||||||
|
> run.bat
|
||||||
|
```
|
||||||
|
|
||||||
|
The target JVM will start and print its PID periodically. Keep it running.
|
||||||
|
|
||||||
|
### Step 3: Run the Injector
|
||||||
|
|
||||||
|
Open another terminal and run the injector:
|
||||||
|
|
||||||
|
```
|
||||||
|
> run_injector.bat
|
||||||
|
```
|
||||||
|
|
||||||
|
You will be prompted to enter:
|
||||||
|
|
||||||
|
- `PID` : the target JVM process ID (shown in the target terminal)
|
||||||
|
- `DLL` : path to `libinject.dll` (e.g. `.\libinject.dll`)
|
||||||
|
- `config_path` : directory containing `config.toml` (leave empty for current dir)
|
||||||
|
|
||||||
|
### Step 4: Verify
|
||||||
|
|
||||||
|
If the injection is successful, the target JVM will load the JAR specified
|
||||||
|
in `config.toml` and execute its entry method.
|
||||||
|
|
||||||
|
## Files
|
||||||
|
|
||||||
|
| File | Description |
|
||||||
|
| --- | --- |
|
||||||
|
| `build.bat` | Build all jars (injector + target) |
|
||||||
|
| `run.bat` | Start the target JVM |
|
||||||
|
| `run_injector.bat` | Run the JavaInjector to inject into the target JVM |
|
||||||
|
| `config.toml` | JuiceAgent configuration file |
|
||||||
|
| `injector/` | JavaInjector source code and build script |
|
||||||
|
| `target/` | Target JVM source code and build script |
|
||||||
|
|
||||||
|
## Configuration (config.toml)
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[JuiceAgent]
|
||||||
|
Version = 2
|
||||||
|
JuiceAgentNativeLibraryPath = ""
|
||||||
|
|
||||||
|
[JarLoader]
|
||||||
|
Enabled = true
|
||||||
|
Mode = "BuiltIn"
|
||||||
|
InjectionDir = "./injection"
|
||||||
|
JarPath = "./demo.jar"
|
||||||
|
EntryClass = "Example.Main"
|
||||||
|
EntryMethod = "run"
|
||||||
|
```
|
||||||
|
|
||||||
|
- `JarPath`: the JAR to load into the target JVM
|
||||||
|
- `EntryClass`: the fully qualified class name with the entry method
|
||||||
|
- `EntryMethod`: must be a `public static void` method with no parameters
|
||||||
|
- `InjectionDir`: directory containing dependency JARs loaded before the main JAR
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
- `Error: JuiceAgent-JavaInjector-1.0-SNAPSHOT.jar not found`:
|
||||||
|
Run `build.bat` first to compile the injector.
|
||||||
|
|
||||||
|
- `java.lang.UnsatisfiedLinkError`:
|
||||||
|
Ensure `libinject.dll` is in the current directory or provide the full path.
|
||||||
|
|
||||||
|
- Injection has no effect:
|
||||||
|
Verify that `config.toml` is in the directory you specified as `config_path`,
|
||||||
|
and that the paths inside `config.toml` are correct relative to that directory.
|
||||||
@@ -0,0 +1,77 @@
|
|||||||
|
How to Use -- inject-via-java-api (JuiceAgent)
|
||||||
|
|
||||||
|
This example demonstrates injecting JuiceAgent into a running JVM process
|
||||||
|
using the Java API (JNI), without needing injector.exe.
|
||||||
|
|
||||||
|
Prerequisites:
|
||||||
|
- Java 8+ installed and available in PATH
|
||||||
|
- JuiceAgent native DLLs (libinject.dll, libloader.dll, libagent.dll)
|
||||||
|
placed in the same directory as this example
|
||||||
|
- A config.toml file configured for your use case
|
||||||
|
|
||||||
|
Quick Start
|
||||||
|
============
|
||||||
|
|
||||||
|
Step 1: Build
|
||||||
|
Run build.bat to compile both the injector and the target jars:
|
||||||
|
> build.bat
|
||||||
|
|
||||||
|
Step 2: Run the Target JVM
|
||||||
|
Open a terminal and start the target JVM:
|
||||||
|
> run.bat
|
||||||
|
The target JVM will start and print its PID periodically. Keep it running.
|
||||||
|
|
||||||
|
Step 3: Run the Injector
|
||||||
|
Open another terminal and run the injector:
|
||||||
|
> run_injector.bat
|
||||||
|
You will be prompted to enter:
|
||||||
|
- PID : the target JVM process ID (shown in the target terminal)
|
||||||
|
- DLL : path to libinject.dll (e.g. .\libinject.dll)
|
||||||
|
- config_path : directory containing config.toml (leave empty for current dir)
|
||||||
|
|
||||||
|
Step 4: Verify
|
||||||
|
If the injection is successful, the target JVM will load the JAR specified
|
||||||
|
in config.toml and execute its entry method.
|
||||||
|
|
||||||
|
Files
|
||||||
|
======
|
||||||
|
|
||||||
|
build.bat - Build all jars (injector + target)
|
||||||
|
run.bat - Start the target JVM
|
||||||
|
run_injector.bat - Run the JavaInjector to inject into the target JVM
|
||||||
|
config.toml - JuiceAgent configuration file
|
||||||
|
injector/ - JavaInjector source code and build script
|
||||||
|
target/ - Target JVM source code and build script
|
||||||
|
|
||||||
|
Configuration (config.toml)
|
||||||
|
============================
|
||||||
|
|
||||||
|
[JuiceAgent]
|
||||||
|
Version = 2
|
||||||
|
JuiceAgentNativeLibraryPath = ""
|
||||||
|
|
||||||
|
[JarLoader]
|
||||||
|
Enabled = true
|
||||||
|
Mode = "BuiltIn"
|
||||||
|
InjectionDir = "./injection"
|
||||||
|
JarPath = "./demo.jar"
|
||||||
|
EntryClass = "Example.Main"
|
||||||
|
EntryMethod = "run"
|
||||||
|
|
||||||
|
- JarPath: the JAR to load into the target JVM
|
||||||
|
- EntryClass: the fully qualified class name with the entry method
|
||||||
|
- EntryMethod: must be a public static void method with no parameters
|
||||||
|
- InjectionDir: directory containing dependency JARs loaded before the main JAR
|
||||||
|
|
||||||
|
Troubleshooting
|
||||||
|
================
|
||||||
|
|
||||||
|
- "Error: JuiceAgent-JavaInjector-1.0-SNAPSHOT.jar not found":
|
||||||
|
Run build.bat first to compile the injector.
|
||||||
|
|
||||||
|
- "java.lang.UnsatisfiedLinkError":
|
||||||
|
Ensure libinject.dll is in the current directory or provide the full path.
|
||||||
|
|
||||||
|
- Injection has no effect:
|
||||||
|
Verify that config.toml is in the directory you specified as config_path,
|
||||||
|
and that the paths inside config.toml are correct relative to that directory.
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
@echo off
|
||||||
|
echo === Building injector jar ===
|
||||||
|
pushd injector
|
||||||
|
call build.bat
|
||||||
|
popd
|
||||||
|
if errorlevel 1 goto :error
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo === Building target jar ===
|
||||||
|
pushd target
|
||||||
|
call build.bat
|
||||||
|
popd
|
||||||
|
if errorlevel 1 goto :error
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo Build finished: JuiceAgent-JavaInjector-1.0-SNAPSHOT.jar and target.jar are ready.
|
||||||
|
goto :end
|
||||||
|
|
||||||
|
:error
|
||||||
|
echo Build failed.
|
||||||
|
exit /b 1
|
||||||
|
|
||||||
|
:end
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
# See config.md for more information https://github.com/xiaozhou233/JuiceAgent/blob/main/docs/config.md
|
||||||
|
|
||||||
|
[JuiceAgent]
|
||||||
|
Version = 2
|
||||||
|
JuiceAgentNativeLibraryPath = ""
|
||||||
|
|
||||||
|
[JarLoader]
|
||||||
|
# Mode: BuiltIn, CustomJar
|
||||||
|
# BuiltIn: Use the built-in jar loader (recommended, support JuiceAgent-API ( https://github.com/xiaozhou233/JuiceAgent#juiceagent-api ))
|
||||||
|
# CustomJar: Load the Jar directly, without using JuiceAgent-API
|
||||||
|
# For more information, please refer to the documentation: https://github.com/xiaozhou233/JuiceAgent/blob/main/docs/advanced.md#load-custom-api--directly-load-jar
|
||||||
|
Enabled = true
|
||||||
|
Mode = "BuiltIn"
|
||||||
|
|
||||||
|
# InjectionDir only works when Mode is BuiltIn
|
||||||
|
InjectionDir = "./injection"
|
||||||
|
JarPath = "./demo.jar"
|
||||||
|
EntryClass = "Example.Main"
|
||||||
|
EntryMethod = "run"
|
||||||
@@ -0,0 +1,35 @@
|
|||||||
|
import cn.xiaozhou233.juiceagent.injector.Injector;
|
||||||
|
import cn.xiaozhou233.juiceagent.injector.WindowInfo;
|
||||||
|
|
||||||
|
import java.util.Scanner;
|
||||||
|
import java.io.File;
|
||||||
|
|
||||||
|
public class JavaInjector {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
// Load the native library
|
||||||
|
System.load(new File("./libinject.dll").getAbsolutePath());
|
||||||
|
|
||||||
|
// Find windows by title
|
||||||
|
for (WindowInfo window : Injector.findWindowsByTitle("cmd")) {
|
||||||
|
System.out.println(window.toString());
|
||||||
|
}
|
||||||
|
System.out.println("----------------");
|
||||||
|
|
||||||
|
Scanner scanner = new Scanner(System.in);
|
||||||
|
|
||||||
|
// Input
|
||||||
|
System.out.println("PID: ");
|
||||||
|
String pid = scanner.nextLine();
|
||||||
|
System.out.println("Dll: ");
|
||||||
|
String dll = scanner.nextLine();
|
||||||
|
System.out.println("config_path: ");
|
||||||
|
String config_path = scanner.nextLine();
|
||||||
|
|
||||||
|
if (config_path == null || config_path.isEmpty()) {
|
||||||
|
// config_path is empty
|
||||||
|
Injector.inject(Integer.parseInt(pid), dll);
|
||||||
|
} else {
|
||||||
|
Injector.inject(Integer.parseInt(pid), dll, config_path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Binary file not shown.
@@ -0,0 +1,51 @@
|
|||||||
|
@echo off
|
||||||
|
setlocal
|
||||||
|
|
||||||
|
set "OUT=out"
|
||||||
|
set "JAR=JuiceAgent-JavaInjector-1.0-SNAPSHOT.jar"
|
||||||
|
set "TMP=tmp_jar"
|
||||||
|
|
||||||
|
if not exist "%JAR%" (
|
||||||
|
echo Error: %JAR% not found. Please restore the original jar.
|
||||||
|
exit /b 1
|
||||||
|
)
|
||||||
|
|
||||||
|
if exist "%OUT%" rmdir /s /q "%OUT%"
|
||||||
|
if exist "%TMP%" rmdir /s /q "%TMP%"
|
||||||
|
|
||||||
|
mkdir "%OUT%"
|
||||||
|
mkdir "%TMP%"
|
||||||
|
|
||||||
|
javac -encoding UTF-8 --release 8 -cp "%JAR%" -d "%OUT%" JavaInjector.java
|
||||||
|
if errorlevel 1 goto :error
|
||||||
|
|
||||||
|
rem Extract existing jar (contains Injector/WindowInfo classes) into temp dir
|
||||||
|
rem -J-XX:-UsePerfData prevents JVM from creating locked hsperfdata files in CWD
|
||||||
|
pushd "%TMP%"
|
||||||
|
jar -J-XX:-UsePerfData xf "..\%JAR%"
|
||||||
|
popd
|
||||||
|
if errorlevel 1 goto :error
|
||||||
|
|
||||||
|
rem Remove any hsperfdata folder that may have leaked into the jar
|
||||||
|
for /d %%D in ("%TMP%\hsperfdata_*") do rmdir /s /q "%%D"
|
||||||
|
|
||||||
|
rem Merge compiled JavaInjector.class into temp dir
|
||||||
|
copy /y "%OUT%\JavaInjector.class" "%TMP%\JavaInjector.class" >nul
|
||||||
|
if errorlevel 1 goto :error
|
||||||
|
|
||||||
|
rem Repackage with Main-Class
|
||||||
|
jar -J-XX:-UsePerfData --create --file "%JAR%" --main-class JavaInjector -C "%TMP%" .
|
||||||
|
if errorlevel 1 goto :error
|
||||||
|
|
||||||
|
rmdir /s /q "%OUT%"
|
||||||
|
rmdir /s /q "%TMP%"
|
||||||
|
|
||||||
|
echo Build succeeded: %JAR%
|
||||||
|
goto :end
|
||||||
|
|
||||||
|
:error
|
||||||
|
echo Build failed.
|
||||||
|
exit /b 1
|
||||||
|
|
||||||
|
:end
|
||||||
|
endlocal
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
@echo off
|
||||||
|
cd /d "%~dp0"
|
||||||
|
java -jar target.jar
|
||||||
|
pause
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
@echo off
|
||||||
|
cd /d "%~dp0"
|
||||||
|
|
||||||
|
set "INJECTOR_JAR=injector\JuiceAgent-JavaInjector-1.0-SNAPSHOT.jar"
|
||||||
|
|
||||||
|
echo === Java API Injector ===
|
||||||
|
echo.
|
||||||
|
echo Make sure the target JVM is running (run.bat).
|
||||||
|
echo.
|
||||||
|
echo Usage: This script runs the JavaInjector which will prompt for:
|
||||||
|
echo - PID: target JVM process ID
|
||||||
|
echo - DLL: path to libloader.dll
|
||||||
|
echo - config_path: directory containing config.toml (leave empty to use current dir)
|
||||||
|
echo.
|
||||||
|
|
||||||
|
java -cp "%INJECTOR_JAR%" JavaInjector
|
||||||
|
pause
|
||||||
Binary file not shown.
@@ -0,0 +1,28 @@
|
|||||||
|
@echo off
|
||||||
|
setlocal
|
||||||
|
|
||||||
|
set "SRC=target.java"
|
||||||
|
set "OUT=out"
|
||||||
|
set "JAR=..\target.jar"
|
||||||
|
|
||||||
|
if exist "%OUT%" rmdir /s /q "%OUT%"
|
||||||
|
if exist "%JAR%" del /q "%JAR%"
|
||||||
|
|
||||||
|
mkdir "%OUT%"
|
||||||
|
javac -encoding UTF-8 --release 8 -d "%OUT%" "%SRC%"
|
||||||
|
if errorlevel 1 goto :error
|
||||||
|
|
||||||
|
jar --create --file "%JAR%" --main-class target -C "%OUT%" .
|
||||||
|
if errorlevel 1 goto :error
|
||||||
|
|
||||||
|
rmdir /s /q "%OUT%"
|
||||||
|
|
||||||
|
echo Build succeeded: target.jar
|
||||||
|
goto :end
|
||||||
|
|
||||||
|
:error
|
||||||
|
echo Build failed.
|
||||||
|
exit /b 1
|
||||||
|
|
||||||
|
:end
|
||||||
|
endlocal
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import java.lang.management.ManagementFactory;
|
||||||
|
|
||||||
|
public class target {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
System.out.println("[Target] I am the target JVM (PID: " + pid + ")");
|
||||||
|
Thread.sleep(1000);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
# 如何使用 — inject-via-java-api (JuiceAgent)
|
||||||
|
|
||||||
|
本示例演示如何使用 Java API(JNI)将 JuiceAgent 注入到正在运行的 JVM 进程中,
|
||||||
|
无需使用 `injector.exe`。
|
||||||
|
|
||||||
|
## 环境要求
|
||||||
|
|
||||||
|
- Java 8+ 已安装并在 `PATH` 中可用
|
||||||
|
- JuiceAgent 原生 DLL(`libinject.dll`、`libloader.dll`、`libagent.dll`)
|
||||||
|
已放置在本示例所在目录
|
||||||
|
- 已根据实际需求配置好 `config.toml`
|
||||||
|
|
||||||
|
## 快速开始
|
||||||
|
|
||||||
|
### 步骤 1:构建
|
||||||
|
|
||||||
|
运行 `build.bat` 编译 injector 和 target 两个 jar:
|
||||||
|
|
||||||
|
```
|
||||||
|
> build.bat
|
||||||
|
```
|
||||||
|
|
||||||
|
### 步骤 2:启动目标 JVM
|
||||||
|
|
||||||
|
打开一个终端,启动目标 JVM:
|
||||||
|
|
||||||
|
```
|
||||||
|
> run.bat
|
||||||
|
```
|
||||||
|
|
||||||
|
目标 JVM 将启动并周期性打印其 PID。保持该窗口运行。
|
||||||
|
|
||||||
|
### 步骤 3:运行注入器
|
||||||
|
|
||||||
|
打开另一个终端,运行注入器:
|
||||||
|
|
||||||
|
```
|
||||||
|
> run_injector.bat
|
||||||
|
```
|
||||||
|
|
||||||
|
程序会提示你输入以下信息:
|
||||||
|
|
||||||
|
- `PID` — 目标 JVM 进程 ID(在目标 JVM 终端中显示)
|
||||||
|
- `DLL` — `libinject.dll` 的路径(例如 `.\libinject.dll`)
|
||||||
|
- `config_path` — `config.toml` 所在目录(留空则使用当前目录)
|
||||||
|
|
||||||
|
### 步骤 4:验证
|
||||||
|
|
||||||
|
注入成功后,目标 JVM 将加载 `config.toml` 中指定的 JAR 并执行其入口方法。
|
||||||
|
|
||||||
|
## 文件说明
|
||||||
|
|
||||||
|
| 文件 | 说明 |
|
||||||
|
| --- | --- |
|
||||||
|
| `build.bat` | 构建所有 jar(injector + target) |
|
||||||
|
| `run.bat` | 启动目标 JVM |
|
||||||
|
| `run_injector.bat` | 运行 JavaInjector,将 agent 注入目标 JVM |
|
||||||
|
| `config.toml` | JuiceAgent 配置文件 |
|
||||||
|
| `injector/` | JavaInjector 源码及构建脚本 |
|
||||||
|
| `target/` | 目标 JVM 源码及构建脚本 |
|
||||||
|
|
||||||
|
## 配置说明(config.toml)
|
||||||
|
|
||||||
|
```toml
|
||||||
|
[JuiceAgent]
|
||||||
|
Version = 2
|
||||||
|
JuiceAgentNativeLibraryPath = ""
|
||||||
|
|
||||||
|
[JarLoader]
|
||||||
|
Enabled = true
|
||||||
|
Mode = "BuiltIn"
|
||||||
|
InjectionDir = "./injection"
|
||||||
|
JarPath = "./demo.jar"
|
||||||
|
EntryClass = "Example.Main"
|
||||||
|
EntryMethod = "run"
|
||||||
|
```
|
||||||
|
|
||||||
|
- `JarPath`:要加载到目标 JVM 的 JAR 文件
|
||||||
|
- `EntryClass`:包含入口方法的完整类名
|
||||||
|
- `EntryMethod`:必须是 `public static void` 且无参数的方法
|
||||||
|
- `InjectionDir`:依赖 JAR 所在的目录,这些 JAR 会在主 JAR 之前加载
|
||||||
|
|
||||||
|
## 常见问题
|
||||||
|
|
||||||
|
- `Error: JuiceAgent-JavaInjector-1.0-SNAPSHOT.jar not found`:
|
||||||
|
请先运行 `build.bat` 编译 injector。
|
||||||
|
|
||||||
|
- `java.lang.UnsatisfiedLinkError`:
|
||||||
|
请确保 `libinject.dll` 在当前目录下,或提供完整路径。
|
||||||
|
|
||||||
|
- 注入后无效果:
|
||||||
|
请确认 `config.toml` 在你指定的 `config_path` 目录中,且 `config.toml`
|
||||||
|
中的路径相对于该目录是正确的。
|
||||||
@@ -0,0 +1,76 @@
|
|||||||
|
如何使用 -- inject-via-java-api (JuiceAgent)
|
||||||
|
|
||||||
|
本示例演示如何使用 Java API(JNI)将 JuiceAgent 注入到正在运行的 JVM 进程中,
|
||||||
|
无需使用 injector.exe。
|
||||||
|
|
||||||
|
环境要求:
|
||||||
|
- Java 8+ 已安装并在 PATH 中可用
|
||||||
|
- JuiceAgent 原生 DLL(libinject.dll、libloader.dll、libagent.dll)
|
||||||
|
已放置在本示例所在目录
|
||||||
|
- 已根据实际需求配置好 config.toml
|
||||||
|
|
||||||
|
快速开始
|
||||||
|
========
|
||||||
|
|
||||||
|
步骤 1:构建
|
||||||
|
运行 build.bat 编译 injector 和 target 两个 jar:
|
||||||
|
> build.bat
|
||||||
|
|
||||||
|
步骤 2:启动目标 JVM
|
||||||
|
打开一个终端,启动目标 JVM:
|
||||||
|
> run.bat
|
||||||
|
目标 JVM 将启动并周期性打印其 PID。保持该窗口运行。
|
||||||
|
|
||||||
|
步骤 3:运行注入器
|
||||||
|
打开另一个终端,运行注入器:
|
||||||
|
> run_injector.bat
|
||||||
|
程序会提示你输入以下信息:
|
||||||
|
- PID :目标 JVM 进程 ID(在目标 JVM 终端中显示)
|
||||||
|
- DLL :libinject.dll 的路径(例如 .\libinject.dll)
|
||||||
|
- config_path :config.toml 所在目录(留空则使用当前目录)
|
||||||
|
|
||||||
|
步骤 4:验证
|
||||||
|
注入成功后,目标 JVM 将加载 config.toml 中指定的 JAR 并执行其入口方法。
|
||||||
|
|
||||||
|
文件说明
|
||||||
|
========
|
||||||
|
|
||||||
|
build.bat - 构建所有 jar(injector + target)
|
||||||
|
run.bat - 启动目标 JVM
|
||||||
|
run_injector.bat - 运行 JavaInjector,将 agent 注入目标 JVM
|
||||||
|
config.toml - JuiceAgent 配置文件
|
||||||
|
injector/ - JavaInjector 源码及构建脚本
|
||||||
|
target/ - 目标 JVM 源码及构建脚本
|
||||||
|
|
||||||
|
配置说明(config.toml)
|
||||||
|
=======================
|
||||||
|
|
||||||
|
[JuiceAgent]
|
||||||
|
Version = 2
|
||||||
|
JuiceAgentNativeLibraryPath = ""
|
||||||
|
|
||||||
|
[JarLoader]
|
||||||
|
Enabled = true
|
||||||
|
Mode = "BuiltIn"
|
||||||
|
InjectionDir = "./injection"
|
||||||
|
JarPath = "./demo.jar"
|
||||||
|
EntryClass = "Example.Main"
|
||||||
|
EntryMethod = "run"
|
||||||
|
|
||||||
|
- JarPath:要加载到目标 JVM 的 JAR 文件
|
||||||
|
- EntryClass:包含入口方法的完整类名
|
||||||
|
- EntryMethod:必须是 public static void 且无参数的方法
|
||||||
|
- InjectionDir:依赖 JAR 所在的目录,这些 JAR 会在主 JAR 之前加载
|
||||||
|
|
||||||
|
常见问题
|
||||||
|
========
|
||||||
|
|
||||||
|
- "Error: JuiceAgent-JavaInjector-1.0-SNAPSHOT.jar not found":
|
||||||
|
请先运行 build.bat 编译 injector。
|
||||||
|
|
||||||
|
- "java.lang.UnsatisfiedLinkError":
|
||||||
|
请确保 libinject.dll 在当前目录下,或提供完整路径。
|
||||||
|
|
||||||
|
- 注入后无效果:
|
||||||
|
请确认 config.toml 在你指定的 config_path 目录中,且 config.toml
|
||||||
|
中的路径相对于该目录是正确的。
|
||||||
@@ -0,0 +1,80 @@
|
|||||||
|
# HowToUse — load-via-injector-exe
|
||||||
|
|
||||||
|
**Prerequisites:** Java 8+ (`javac`/`jar` for building, `jps` for injection)
|
||||||
|
|
||||||
|
## Directory Files
|
||||||
|
|
||||||
|
| File | Description |
|
||||||
|
| --- | --- |
|
||||||
|
| `injector.exe` `libagent.dll` `libinject.dll` `libloader.dll` | JuiceAgent runtime |
|
||||||
|
| `config.toml` | Injection config |
|
||||||
|
| `demo.jar` | JAR to inject (built by `build.bat`) |
|
||||||
|
| `target.jar` | Target JVM program (built by `build.bat`) |
|
||||||
|
| `injection/` | Injection source |
|
||||||
|
| `target/` | Target source |
|
||||||
|
| `build.bat` | Rebuild `demo.jar` / `target.jar` |
|
||||||
|
| `run.bat` | Run target JVM (`target.jar`) |
|
||||||
|
|
||||||
|
## Usage Steps
|
||||||
|
|
||||||
|
### 1. Build (optional)
|
||||||
|
|
||||||
|
`demo.jar` and `target.jar` are already included by default.
|
||||||
|
If you modified `injection/Main.java` or `target/target.java`, run:
|
||||||
|
|
||||||
|
```
|
||||||
|
build.bat
|
||||||
|
```
|
||||||
|
|
||||||
|
to regenerate `demo.jar` and `target.jar` in this directory.
|
||||||
|
|
||||||
|
### 2. Run the target JVM
|
||||||
|
|
||||||
|
Double-click `run.bat` (or run: `java -jar target.jar`). A black window
|
||||||
|
appears and prints:
|
||||||
|
|
||||||
|
```
|
||||||
|
[Target] I am the target JVM (PID: <PID>)
|
||||||
|
```
|
||||||
|
|
||||||
|
... (once per second)
|
||||||
|
|
||||||
|
### 3. Inject
|
||||||
|
|
||||||
|
Double-click `injector.exe`, type the target PID and press Enter:
|
||||||
|
|
||||||
|
```
|
||||||
|
6644 target.jar
|
||||||
|
10504 jdk.jcmd/sun.tools.jps.Jps
|
||||||
|
Input PID: 6644
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Verify
|
||||||
|
|
||||||
|
Go back to the target window. Injection succeeded if you see:
|
||||||
|
|
||||||
|
```
|
||||||
|
[Demo] Injection succeeded! Hello from JuiceAgent.
|
||||||
|
[Demo] Current thread: Thread-0
|
||||||
|
```
|
||||||
|
|
||||||
|
## Config / config.toml
|
||||||
|
|
||||||
|
| Key | Description |
|
||||||
|
| --- | --- |
|
||||||
|
| `JarPath` | JAR path to inject (default: `./demo.jar`) |
|
||||||
|
| `EntryClass` | Entry class (default: `Example.Main`) |
|
||||||
|
| `EntryMethod` | Entry method, must be `public static void run()` |
|
||||||
|
| `InjectionDir` | Dependency JAR directory (only `*.jar` is loaded) |
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
- `java/javac/jar is not recognized`:
|
||||||
|
Install a JDK and add its `bin` directory to `PATH`.
|
||||||
|
- `injector.exe` reports injection failure:
|
||||||
|
Make sure the target JVM is running and the PID is correct.
|
||||||
|
- No `[Demo]` output appears:
|
||||||
|
The target window prints many log lines which may affect reading.
|
||||||
|
Check the `[JuiceAgent JarLoader]` lines to locate the cause.
|
||||||
|
If it still fails, copy the full log and submit an Issue, or paste
|
||||||
|
it directly to an AI.
|
||||||
@@ -0,0 +1,65 @@
|
|||||||
|
============================================
|
||||||
|
HowToUse
|
||||||
|
============================================
|
||||||
|
|
||||||
|
Prerequisites: Java 8+ (javac/jar for building, jps for injection)
|
||||||
|
|
||||||
|
Directory Files:
|
||||||
|
injector.exe libagent.dll libinject.dll libloader.dll - JuiceAgent runtime
|
||||||
|
config.toml - injection config
|
||||||
|
demo.jar - JAR to inject (built by build.bat)
|
||||||
|
target.jar - target JVM program (built by build.bat)
|
||||||
|
injection/ - injection source
|
||||||
|
target/ - target source
|
||||||
|
build.bat - rebuild demo.jar / target.jar
|
||||||
|
run.bat - run target JVM (target.jar)
|
||||||
|
|
||||||
|
============================================
|
||||||
|
Usage Steps
|
||||||
|
============================================
|
||||||
|
|
||||||
|
1. Build (optional)
|
||||||
|
demo.jar and target.jar are already included by default.
|
||||||
|
If you modified injection/Main.java or target/target.java, run:
|
||||||
|
build.bat
|
||||||
|
to regenerate demo.jar and target.jar in this directory.
|
||||||
|
|
||||||
|
2. Run the target JVM
|
||||||
|
Double-click run.bat (or run: java -jar target.jar). A black window
|
||||||
|
appears and prints:
|
||||||
|
[Target] I am the target JVM (PID: <PID>)
|
||||||
|
...... (once per second)
|
||||||
|
|
||||||
|
3. Inject
|
||||||
|
Double-click injector.exe, type the target PID and press Enter:
|
||||||
|
6644 target.jar
|
||||||
|
10504 jdk.jcmd/sun.tools.jps.Jps
|
||||||
|
Input PID: 6644
|
||||||
|
|
||||||
|
4. Verify
|
||||||
|
Go back to the target window. Injection succeeded if you see:
|
||||||
|
[Demo] Injection succeeded! Hello from JuiceAgent.
|
||||||
|
[Demo] Current thread: Thread-0
|
||||||
|
|
||||||
|
============================================
|
||||||
|
Config / config.toml
|
||||||
|
============================================
|
||||||
|
|
||||||
|
JarPath - JAR path to inject (default: ./demo.jar)
|
||||||
|
EntryClass - Entry class (default: Example.Main)
|
||||||
|
EntryMethod - Entry method, must be public static void run()
|
||||||
|
InjectionDir - Dependency JAR directory (only *.jar is loaded)
|
||||||
|
|
||||||
|
============================================
|
||||||
|
Troubleshooting
|
||||||
|
============================================
|
||||||
|
|
||||||
|
- "java/javac/jar is not recognized":
|
||||||
|
Install a JDK and add its bin directory to PATH.
|
||||||
|
- injector.exe reports injection failure:
|
||||||
|
Make sure the target JVM is running and the PID is correct.
|
||||||
|
- No [Demo] output appears:
|
||||||
|
The target window prints many log lines which may affect reading.
|
||||||
|
Check the [JuiceAgent JarLoader] lines to locate the cause.
|
||||||
|
If it still fails, copy the full log and submit an Issue, or paste
|
||||||
|
it directly to an AI.
|
||||||
@@ -0,0 +1,23 @@
|
|||||||
|
@echo off
|
||||||
|
echo === Building injection jar ===
|
||||||
|
pushd injection
|
||||||
|
call build.bat
|
||||||
|
popd
|
||||||
|
if errorlevel 1 goto :error
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo === Building target jar ===
|
||||||
|
pushd target
|
||||||
|
call build.bat
|
||||||
|
popd
|
||||||
|
if errorlevel 1 goto :error
|
||||||
|
|
||||||
|
echo.
|
||||||
|
echo Build finished: demo.jar and target.jar are in this directory.
|
||||||
|
goto :end
|
||||||
|
|
||||||
|
:error
|
||||||
|
echo Build failed.
|
||||||
|
exit /b 1
|
||||||
|
|
||||||
|
:end
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
# See config.md for more information https://github.com/xiaozhou233/JuiceAgent/blob/main/docs/config.md
|
||||||
|
|
||||||
|
[JuiceAgent]
|
||||||
|
Version = 2
|
||||||
|
JuiceAgentNativeLibraryPath = ""
|
||||||
|
|
||||||
|
[JarLoader]
|
||||||
|
# Mode: BuiltIn, CustomJar
|
||||||
|
# BuiltIn: Use the built-in jar loader (recommended, support JuiceAgent-API ( https://github.com/xiaozhou233/JuiceAgent#juiceagent-api ))
|
||||||
|
# CustomJar: Load the Jar directly, without using JuiceAgent-API
|
||||||
|
# For more information, please refer to the documentation: https://github.com/xiaozhou233/JuiceAgent/blob/main/docs/advanced.md#load-custom-api--directly-load-jar
|
||||||
|
Enabled = true
|
||||||
|
Mode = "BuiltIn"
|
||||||
|
|
||||||
|
# InjectionDir only works when Mode is BuiltIn
|
||||||
|
InjectionDir = "./injection"
|
||||||
|
JarPath = "./demo.jar"
|
||||||
|
EntryClass = "Example.Main"
|
||||||
|
EntryMethod = "run"
|
||||||
Binary file not shown.
@@ -0,0 +1,8 @@
|
|||||||
|
package Example;
|
||||||
|
|
||||||
|
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());
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
@echo off
|
||||||
|
setlocal
|
||||||
|
|
||||||
|
set "SRC=Main.java"
|
||||||
|
set "OUT=out"
|
||||||
|
set "JAR=..\demo.jar"
|
||||||
|
|
||||||
|
if exist "%OUT%" rmdir /s /q "%OUT%"
|
||||||
|
if exist "%JAR%" del /q "%JAR%"
|
||||||
|
|
||||||
|
mkdir "%OUT%"
|
||||||
|
javac -encoding UTF-8 --release 8 -d "%OUT%" "%SRC%"
|
||||||
|
if errorlevel 1 goto :error
|
||||||
|
|
||||||
|
jar --create --file "%JAR%" -C "%OUT%" .
|
||||||
|
if errorlevel 1 goto :error
|
||||||
|
|
||||||
|
rmdir /s /q "%OUT%"
|
||||||
|
|
||||||
|
echo Build succeeded: demo.jar
|
||||||
|
goto :end
|
||||||
|
|
||||||
|
:error
|
||||||
|
echo Build failed.
|
||||||
|
exit /b 1
|
||||||
|
|
||||||
|
:end
|
||||||
|
endlocal
|
||||||
@@ -0,0 +1,4 @@
|
|||||||
|
@echo off
|
||||||
|
cd /d "%~dp0"
|
||||||
|
java -jar target.jar
|
||||||
|
pause
|
||||||
Binary file not shown.
@@ -0,0 +1,28 @@
|
|||||||
|
@echo off
|
||||||
|
setlocal
|
||||||
|
|
||||||
|
set "SRC=target.java"
|
||||||
|
set "OUT=out"
|
||||||
|
set "JAR=..\target.jar"
|
||||||
|
|
||||||
|
if exist "%OUT%" rmdir /s /q "%OUT%"
|
||||||
|
if exist "%JAR%" del /q "%JAR%"
|
||||||
|
|
||||||
|
mkdir "%OUT%"
|
||||||
|
javac -encoding UTF-8 --release 8 -d "%OUT%" "%SRC%"
|
||||||
|
if errorlevel 1 goto :error
|
||||||
|
|
||||||
|
jar --create --file "%JAR%" --main-class target -C "%OUT%" .
|
||||||
|
if errorlevel 1 goto :error
|
||||||
|
|
||||||
|
rmdir /s /q "%OUT%"
|
||||||
|
|
||||||
|
echo Build succeeded: target.jar
|
||||||
|
goto :end
|
||||||
|
|
||||||
|
:error
|
||||||
|
echo Build failed.
|
||||||
|
exit /b 1
|
||||||
|
|
||||||
|
:end
|
||||||
|
endlocal
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
import java.lang.management.ManagementFactory;
|
||||||
|
|
||||||
|
public class target {
|
||||||
|
public static void main(String[] args) {
|
||||||
|
String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
|
||||||
|
try {
|
||||||
|
while (true) {
|
||||||
|
System.out.println("[Target] I am the target JVM (PID: " + pid + ")");
|
||||||
|
Thread.sleep(1000);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,78 @@
|
|||||||
|
# 使用说明 — load-via-injector-exe
|
||||||
|
|
||||||
|
**前提条件:** 已安装 Java 8+(需要 `javac`/`jar` 构建,`jps` 用于注入)
|
||||||
|
|
||||||
|
## 目录文件说明
|
||||||
|
|
||||||
|
| 文件 | 说明 |
|
||||||
|
| --- | --- |
|
||||||
|
| `injector.exe` `libagent.dll` `libinject.dll` `libloader.dll` | JuiceAgent 运行时 |
|
||||||
|
| `config.toml` | 注入配置 |
|
||||||
|
| `demo.jar` | 待注入的 JAR(`build.bat` 生成) |
|
||||||
|
| `target.jar` | 目标 JVM 程序(`build.bat` 生成) |
|
||||||
|
| `injection/` | 注入代码源码 |
|
||||||
|
| `target/` | 目标程序源码 |
|
||||||
|
| `build.bat` | 重新生成 `demo.jar` / `target.jar` |
|
||||||
|
| `run.bat` | 运行目标 JVM(`target.jar`) |
|
||||||
|
|
||||||
|
## 使用步骤
|
||||||
|
|
||||||
|
### 1. 构建(可选)
|
||||||
|
|
||||||
|
默认已包含 `demo.jar` 和 `target.jar`。
|
||||||
|
若修改了 `injection/Main.java` 或 `target/target.java`,请运行:
|
||||||
|
|
||||||
|
```
|
||||||
|
build.bat
|
||||||
|
```
|
||||||
|
|
||||||
|
生成 `demo.jar` 和 `target.jar` 到本目录。
|
||||||
|
|
||||||
|
### 2. 运行目标 JVM
|
||||||
|
|
||||||
|
双击 `run.bat`(或执行 `java -jar target.jar`),出现黑色窗口并输出:
|
||||||
|
|
||||||
|
```
|
||||||
|
[Target] I am the target JVM (PID: <PID>)
|
||||||
|
```
|
||||||
|
|
||||||
|
...(每秒输出一次)
|
||||||
|
|
||||||
|
### 3. 注入
|
||||||
|
|
||||||
|
双击 `injector.exe`,出现黑色窗口,输入目标 PID 并回车:
|
||||||
|
|
||||||
|
```
|
||||||
|
6644 target.jar
|
||||||
|
10504 jdk.jcmd/sun.tools.jps.Jps
|
||||||
|
Input PID: 6644
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 验证
|
||||||
|
|
||||||
|
回到目标窗口,看到以下输出即注入成功:
|
||||||
|
|
||||||
|
```
|
||||||
|
[Demo] Injection succeeded! Hello from JuiceAgent.
|
||||||
|
[Demo] Current thread: Thread-0
|
||||||
|
```
|
||||||
|
|
||||||
|
## 配置说明 / config.toml
|
||||||
|
|
||||||
|
| 配置项 | 说明 |
|
||||||
|
| --- | --- |
|
||||||
|
| `JarPath` | 待注入的 JAR 路径(默认 `./demo.jar`) |
|
||||||
|
| `EntryClass` | 入口类(默认 `Example.Main`) |
|
||||||
|
| `EntryMethod` | 入口方法,需为 `public static void run()` |
|
||||||
|
| `InjectionDir` | 依赖 JAR 目录(仅加载 `*.jar`) |
|
||||||
|
|
||||||
|
## 常见问题
|
||||||
|
|
||||||
|
- `java/javac/jar 不是内部或外部命令`:
|
||||||
|
安装 JDK 并将其 `bin` 目录加入 `PATH`。
|
||||||
|
- `injector.exe` 提示注入失败:
|
||||||
|
确认目标 JVM 正在运行,且输入的 PID 正确。
|
||||||
|
- 没有出现 `[Demo]` 输出:
|
||||||
|
目标窗口会有大量日志,可能影响阅读;请查看其中的
|
||||||
|
`[JuiceAgent JarLoader]` 日志定位原因。
|
||||||
|
如仍无法解决,请复制完整日志提交 Issue,或直接丢给 AI。
|
||||||
@@ -0,0 +1,63 @@
|
|||||||
|
============================================
|
||||||
|
使用说明 / HOW TO USE
|
||||||
|
============================================
|
||||||
|
|
||||||
|
前提条件:已安装 Java 8+(需要 javac/jar 构建,jps 用于注入)
|
||||||
|
|
||||||
|
目录文件说明:
|
||||||
|
injector.exe libagent.dll libinject.dll libloader.dll - JuiceAgent 运行时
|
||||||
|
config.toml - 注入配置
|
||||||
|
demo.jar - 待注入的 JAR(build.bat 生成)
|
||||||
|
target.jar - 目标 JVM 程序(build.bat 生成)
|
||||||
|
injection/ - 注入代码源码
|
||||||
|
target/ - 目标程序源码
|
||||||
|
build.bat - 重新生成 demo.jar / target.jar
|
||||||
|
run.bat - 运行目标 JVM(target.jar)
|
||||||
|
|
||||||
|
============================================
|
||||||
|
使用步骤 / Usage Steps
|
||||||
|
============================================
|
||||||
|
|
||||||
|
1. 构建(可选)
|
||||||
|
默认已包含 demo.jar 和 target.jar。
|
||||||
|
若修改了 injection/Main.java 或 target/target.java,请运行:
|
||||||
|
build.bat
|
||||||
|
生成 demo.jar 和 target.jar 到本目录。
|
||||||
|
|
||||||
|
2. 运行目标 JVM
|
||||||
|
双击 run.bat(或执行 java -jar target.jar),出现黑色窗口并输出:
|
||||||
|
[Target] I am the target JVM (PID: <PID>)
|
||||||
|
......(每秒输出一次)
|
||||||
|
|
||||||
|
3. 注入
|
||||||
|
双击 injector.exe,出现黑色窗口,输入目标 PID 并回车:
|
||||||
|
6644 target.jar
|
||||||
|
10504 jdk.jcmd/sun.tools.jps.Jps
|
||||||
|
Input PID: 6644
|
||||||
|
|
||||||
|
4. 验证
|
||||||
|
回到目标窗口,看到以下输出即注入成功:
|
||||||
|
[Demo] Injection succeeded! Hello from JuiceAgent.
|
||||||
|
[Demo] Current thread: Thread-0
|
||||||
|
|
||||||
|
============================================
|
||||||
|
配置说明 / config.toml
|
||||||
|
============================================
|
||||||
|
|
||||||
|
JarPath - 待注入的 JAR 路径(默认 ./demo.jar)
|
||||||
|
EntryClass - 入口类(默认 Example.Main)
|
||||||
|
EntryMethod - 入口方法,需为 public static void run()
|
||||||
|
InjectionDir - 依赖 JAR 目录(仅加载 *.jar)
|
||||||
|
|
||||||
|
============================================
|
||||||
|
常见问题 / Troubleshooting
|
||||||
|
============================================
|
||||||
|
|
||||||
|
- "java/javac/jar 不是内部或外部命令":
|
||||||
|
安装 JDK 并将其 bin 目录加入 PATH。
|
||||||
|
- injector.exe 提示注入失败:
|
||||||
|
确认目标 JVM 正在运行,且输入的 PID 正确。
|
||||||
|
- 没有出现 [Demo] 输出:
|
||||||
|
目标窗口会有大量日志,可能影响阅读;请查看其中的
|
||||||
|
[JuiceAgent JarLoader] 日志定位原因。
|
||||||
|
如仍无法解决,请复制完整日志提交 Issue,或直接丢给 AI。
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
# Build output directory (intermediate)
|
||||||
|
out/
|
||||||
|
|
||||||
|
# Do not ignore root build artifacts:
|
||||||
|
!new_target.class
|
||||||
|
!playload.jar
|
||||||
|
!target.jar
|
||||||
@@ -0,0 +1,109 @@
|
|||||||
|
# HowToUse — retransform-class
|
||||||
|
|
||||||
|
**Prerequisites:** Java 8+ (`javac`/`jar` for building, `jps` for injection)
|
||||||
|
|
||||||
|
## Directory Files
|
||||||
|
|
||||||
|
| File | Description |
|
||||||
|
| --- | --- |
|
||||||
|
| `injector.exe` `libagent.dll` `libinject.dll` `libloader.dll` | JuiceAgent runtime |
|
||||||
|
| `config.toml` | Injection config |
|
||||||
|
| `build.bat` | Build script |
|
||||||
|
| `run.bat` | Run target JVM |
|
||||||
|
| `playload.jar` | JAR to inject (built by `build.bat`) |
|
||||||
|
| `target.jar` | Target JVM program (built by `build.bat`) |
|
||||||
|
| `new_target.class` | Retransformed bytecode (built by `build.bat`) |
|
||||||
|
| `playload/` | Payload source |
|
||||||
|
| `target/` | Target source |
|
||||||
|
| `new_target/` | Modified copy of target source |
|
||||||
|
|
||||||
|
## What This Example Does
|
||||||
|
|
||||||
|
The target class `target` has a method `say()` that prints:
|
||||||
|
|
||||||
|
```
|
||||||
|
Hello!
|
||||||
|
```
|
||||||
|
|
||||||
|
`new_target/target.java` is a modified copy that also prints:
|
||||||
|
|
||||||
|
```
|
||||||
|
Retransformed!
|
||||||
|
```
|
||||||
|
|
||||||
|
This example injects `playload.jar` into a running JVM. The payload reads
|
||||||
|
`new_target.class` from its own JAR and calls
|
||||||
|
`JuiceAgent.retransformClassByName("target", ...)` to swap the already-loaded
|
||||||
|
`target` class on the fly. After that, `say()` starts printing the new message
|
||||||
|
without restarting the JVM.
|
||||||
|
|
||||||
|
## Usage Steps
|
||||||
|
|
||||||
|
### 1. Build (optional)
|
||||||
|
|
||||||
|
`playload.jar` and `target.jar` are already included by default.
|
||||||
|
If you modified `playload/`, `target/` or `new_target/`, run:
|
||||||
|
|
||||||
|
```
|
||||||
|
build.bat
|
||||||
|
```
|
||||||
|
|
||||||
|
to regenerate `playload.jar`, `target.jar` and `new_target.class`.
|
||||||
|
|
||||||
|
### 2. Run the target JVM
|
||||||
|
|
||||||
|
Double-click `run.bat` (or run: `java -jar target.jar`). A black window
|
||||||
|
appears and prints:
|
||||||
|
|
||||||
|
```
|
||||||
|
[Target] I am the target JVM (PID: <PID>)
|
||||||
|
Hello!
|
||||||
|
```
|
||||||
|
|
||||||
|
... (once per second)
|
||||||
|
|
||||||
|
### 3. Inject
|
||||||
|
|
||||||
|
Double-click `injector.exe`, type the target PID and press Enter:
|
||||||
|
|
||||||
|
```
|
||||||
|
6644 target.jar
|
||||||
|
10504 jdk.jcmd/sun.tools.jps.Jps
|
||||||
|
Input PID: 6644
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. Verify
|
||||||
|
|
||||||
|
Go back to the target window. Injection succeeded if you see:
|
||||||
|
|
||||||
|
```
|
||||||
|
Playload loaded!
|
||||||
|
Playload executed!
|
||||||
|
```
|
||||||
|
|
||||||
|
and the output of `say()` changes from `Hello!` to:
|
||||||
|
|
||||||
|
```
|
||||||
|
Hello!
|
||||||
|
Retransformed!
|
||||||
|
```
|
||||||
|
|
||||||
|
## Config / config.toml
|
||||||
|
|
||||||
|
| Key | Description |
|
||||||
|
| --- | --- |
|
||||||
|
| `JarPath` | JAR path to inject (default: `./playload.jar`) |
|
||||||
|
| `EntryClass` | Entry class (default: `playload`) |
|
||||||
|
| `EntryMethod` | Entry method, must be `public static void entry()` |
|
||||||
|
|
||||||
|
## Troubleshooting
|
||||||
|
|
||||||
|
- `java/javac/jar is not recognized`:
|
||||||
|
Install a JDK and add its `bin` directory to `PATH`.
|
||||||
|
- `injector.exe` reports injection failure:
|
||||||
|
Make sure the target JVM is running and the PID is correct.
|
||||||
|
- No `Playload loaded!` output appears:
|
||||||
|
Check `libagent.log` and `libloader.log` in this directory for the cause.
|
||||||
|
- `say()` output does not change:
|
||||||
|
Make sure `build.bat` was run after editing `new_target/`, and that
|
||||||
|
`new_target.class` inside `playload.jar` is up to date.
|
||||||
@@ -0,0 +1,86 @@
|
|||||||
|
============================================
|
||||||
|
HowToUse
|
||||||
|
============================================
|
||||||
|
|
||||||
|
Prerequisites: Java 8+ (javac/jar for building, jps for injection)
|
||||||
|
|
||||||
|
Directory Files:
|
||||||
|
injector.exe libagent.dll libinject.dll libloader.dll - JuiceAgent runtime
|
||||||
|
config.toml - injection config
|
||||||
|
build.bat - build script
|
||||||
|
run.bat - run target JVM
|
||||||
|
playload.jar - JAR to inject (built by build.bat)
|
||||||
|
target.jar - target JVM program (built by build.bat)
|
||||||
|
new_target.class - retransformed bytecode (built by build.bat)
|
||||||
|
playload/ - payload source
|
||||||
|
target/ - target source
|
||||||
|
new_target/ - modified copy of target source
|
||||||
|
|
||||||
|
============================================
|
||||||
|
What This Example Does
|
||||||
|
============================================
|
||||||
|
|
||||||
|
The target class "target" has a method say() that prints:
|
||||||
|
Hello!
|
||||||
|
|
||||||
|
new_target/target.java is a modified copy that also prints:
|
||||||
|
Retransformed!
|
||||||
|
|
||||||
|
This example injects playload.jar into a running JVM. The payload reads
|
||||||
|
new_target.class from its own JAR and calls
|
||||||
|
JuiceAgent.retransformClassByName("target", ...) to swap the already-loaded
|
||||||
|
"target" class on the fly. After that, say() starts printing the new message
|
||||||
|
without restarting the JVM.
|
||||||
|
|
||||||
|
============================================
|
||||||
|
Usage Steps
|
||||||
|
============================================
|
||||||
|
|
||||||
|
1. Build (optional)
|
||||||
|
playload.jar and target.jar are already included by default.
|
||||||
|
If you modified playload/, target/ or new_target/, run:
|
||||||
|
build.bat
|
||||||
|
to regenerate playload.jar, target.jar and new_target.class.
|
||||||
|
|
||||||
|
2. Run the target JVM
|
||||||
|
Double-click run.bat (or run: java -jar target.jar). A black window
|
||||||
|
appears and prints:
|
||||||
|
[Target] I am the target JVM (PID: <PID>)
|
||||||
|
Hello!
|
||||||
|
...... (once per second)
|
||||||
|
|
||||||
|
3. Inject
|
||||||
|
Double-click injector.exe, type the target PID and press Enter:
|
||||||
|
6644 target.jar
|
||||||
|
10504 jdk.jcmd/sun.tools.jps.Jps
|
||||||
|
Input PID: 6644
|
||||||
|
|
||||||
|
4. Verify
|
||||||
|
Go back to the target window. Injection succeeded if you see:
|
||||||
|
Playload loaded!
|
||||||
|
Playload executed!
|
||||||
|
and the output of say() changes from "Hello!" to:
|
||||||
|
Hello!
|
||||||
|
Retransformed!
|
||||||
|
|
||||||
|
============================================
|
||||||
|
Config / config.toml
|
||||||
|
============================================
|
||||||
|
|
||||||
|
JarPath - JAR path to inject (default: ./playload.jar)
|
||||||
|
EntryClass - Entry class (default: playload)
|
||||||
|
EntryMethod - Entry method, must be public static void entry()
|
||||||
|
|
||||||
|
============================================
|
||||||
|
Troubleshooting
|
||||||
|
============================================
|
||||||
|
|
||||||
|
- "java/javac/jar is not recognized":
|
||||||
|
Install a JDK and add its bin directory to PATH.
|
||||||
|
- injector.exe reports injection failure:
|
||||||
|
Make sure the target JVM is running and the PID is correct.
|
||||||
|
- No "Playload loaded!" output appears:
|
||||||
|
Check libagent.log and libloader.log in this directory for the cause.
|
||||||
|
- say() output does not change:
|
||||||
|
Make sure build.bat was run after editing new_target/, and that
|
||||||
|
new_target.class inside playload.jar is up to date.
|
||||||
@@ -0,0 +1,58 @@
|
|||||||
|
@echo off
|
||||||
|
setlocal
|
||||||
|
|
||||||
|
set "API_JAR=playload\JuiceAgent-API-1.4.1+build.1.jar"
|
||||||
|
set "PAYLOAD_JAR=playload.jar"
|
||||||
|
set "TARGET_JAR=target.jar"
|
||||||
|
|
||||||
|
set "OUT=out"
|
||||||
|
set "OUT_NT=%OUT%\new_target"
|
||||||
|
set "OUT_PL=%OUT%\playload"
|
||||||
|
set "OUT_TG=%OUT%\target"
|
||||||
|
|
||||||
|
set "NEW_TARGET_CLASS=new_target.class"
|
||||||
|
|
||||||
|
if exist "%OUT%" rmdir /s /q "%OUT%"
|
||||||
|
if exist "%PAYLOAD_JAR%" del /q "%PAYLOAD_JAR%"
|
||||||
|
if exist "%TARGET_JAR%" del /q "%TARGET_JAR%"
|
||||||
|
if exist "%NEW_TARGET_CLASS%" del /q "%NEW_TARGET_CLASS%"
|
||||||
|
|
||||||
|
mkdir "%OUT_NT%"
|
||||||
|
mkdir "%OUT_PL%"
|
||||||
|
mkdir "%OUT_TG%"
|
||||||
|
|
||||||
|
echo === Compiling new_target ===
|
||||||
|
javac -encoding UTF-8 --release 8 -d "%OUT_NT%" new_target\target.java
|
||||||
|
if errorlevel 1 goto :error
|
||||||
|
ren "%OUT_NT%\target.class" new_target.class
|
||||||
|
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
|
||||||
|
if errorlevel 1 goto :error
|
||||||
|
|
||||||
|
echo === Compiling target ===
|
||||||
|
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
|
||||||
|
if errorlevel 1 goto :error
|
||||||
|
|
||||||
|
echo === Packaging target jar ===
|
||||||
|
jar --create --file "%TARGET_JAR%" --main-class target -C "%OUT_TG%" .
|
||||||
|
if errorlevel 1 goto :error
|
||||||
|
|
||||||
|
rmdir /s /q "%OUT%"
|
||||||
|
|
||||||
|
echo Build succeeded: %PAYLOAD_JAR%, %TARGET_JAR%, %NEW_TARGET_CLASS%
|
||||||
|
goto :end
|
||||||
|
|
||||||
|
:error
|
||||||
|
echo Build failed.
|
||||||
|
exit /b 1
|
||||||
|
|
||||||
|
:end
|
||||||
|
endlocal
|
||||||
@@ -0,0 +1,19 @@
|
|||||||
|
# See config.md for more information https://github.com/xiaozhou233/JuiceAgent/blob/main/docs/config.md
|
||||||
|
|
||||||
|
[JuiceAgent]
|
||||||
|
Version = 2
|
||||||
|
JuiceAgentNativeLibraryPath = ""
|
||||||
|
|
||||||
|
[JarLoader]
|
||||||
|
# Mode: BuiltIn, CustomJar
|
||||||
|
# BuiltIn: Use the built-in jar loader (recommended, support JuiceAgent-API ( https://github.com/xiaozhou233/JuiceAgent#juiceagent-api ))
|
||||||
|
# CustomJar: Load the Jar directly, without using JuiceAgent-API
|
||||||
|
# For more information, please refer to the documentation: https://github.com/xiaozhou233/JuiceAgent/blob/main/docs/advanced.md#load-custom-api--directly-load-jar
|
||||||
|
Enabled = true
|
||||||
|
Mode = "BuiltIn"
|
||||||
|
|
||||||
|
# InjectionDir only works when Mode is BuiltIn
|
||||||
|
InjectionDir = "./injection"
|
||||||
|
JarPath = "./playload.jar"
|
||||||
|
EntryClass = "playload"
|
||||||
|
EntryMethod = "entry"
|
||||||
Binary file not shown.
@@ -0,0 +1,23 @@
|
|||||||
|
import java.lang.management.ManagementFactory;
|
||||||
|
|
||||||
|
public class target {
|
||||||
|
public static void say() {
|
||||||
|
System.out.println("Hello!");
|
||||||
|
//// RETRANSFORM HERE
|
||||||
|
System.out.println("Retransformed!");
|
||||||
|
//// RETRANSFORM HERE
|
||||||
|
}
|
||||||
|
|
||||||
|
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 + ")");
|
||||||
|
say();
|
||||||
|
Thread.sleep(1000);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
Binary file not shown.
Binary file not shown.
@@ -0,0 +1,25 @@
|
|||||||
|
import cn.xiaozhou233.juiceagent.api.JuiceAgent;
|
||||||
|
|
||||||
|
public class playload {
|
||||||
|
public static void entry() throws java.io.IOException {
|
||||||
|
System.out.println("Playload loaded!");
|
||||||
|
|
||||||
|
java.io.InputStream in = new java.io.FileInputStream("new_target.class");
|
||||||
|
java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
|
||||||
|
byte[] buf = new byte[4096];
|
||||||
|
int len;
|
||||||
|
while ((len = in.read(buf)) != -1) {
|
||||||
|
out.write(buf, 0, len);
|
||||||
|
}
|
||||||
|
byte[] bytes = out.toByteArray();
|
||||||
|
in.close();
|
||||||
|
|
||||||
|
JuiceAgent.retransformClassByName(
|
||||||
|
"target",
|
||||||
|
bytes,
|
||||||
|
bytes.length
|
||||||
|
);
|
||||||
|
|
||||||
|
System.out.println("Playload executed!");
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
@echo off
|
||||||
|
setlocal
|
||||||
|
|
||||||
|
java -jar target.jar
|
||||||
|
if errorlevel 1 goto :error
|
||||||
|
|
||||||
|
goto :end
|
||||||
|
|
||||||
|
:error
|
||||||
|
echo Run failed.
|
||||||
|
exit /b 1
|
||||||
|
|
||||||
|
:end
|
||||||
|
endlocal
|
||||||
Binary file not shown.
@@ -0,0 +1,20 @@
|
|||||||
|
import java.lang.management.ManagementFactory;
|
||||||
|
|
||||||
|
public class target {
|
||||||
|
public static void say() {
|
||||||
|
System.out.println("Hello!");
|
||||||
|
}
|
||||||
|
|
||||||
|
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 + ")");
|
||||||
|
say();
|
||||||
|
Thread.sleep(1000);
|
||||||
|
}
|
||||||
|
} catch (Exception e) {
|
||||||
|
e.printStackTrace();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
# 如何使用 — retransform-class
|
||||||
|
|
||||||
|
**前置条件:** Java 8+(构建需要 `javac`/`jar`,注入需要 `jps`)
|
||||||
|
|
||||||
|
## 目录文件
|
||||||
|
|
||||||
|
| 文件 | 说明 |
|
||||||
|
| --- | --- |
|
||||||
|
| `injector.exe` `libagent.dll` `libinject.dll` `libloader.dll` | JuiceAgent 运行库 |
|
||||||
|
| `config.toml` | 注入配置 |
|
||||||
|
| `build.bat` | 构建脚本 |
|
||||||
|
| `run.bat` | 运行目标 JVM |
|
||||||
|
| `playload.jar` | 注入用的 JAR(由 `build.bat` 生成) |
|
||||||
|
| `target.jar` | 目标 JVM 程序(由 `build.bat` 生成) |
|
||||||
|
| `new_target.class` | 重变换后的字节码(由 `build.bat` 生成) |
|
||||||
|
| `playload/` | payload 源码 |
|
||||||
|
| `target/` | 目标类源码 |
|
||||||
|
| `new_target/` | target 的修改版源码 |
|
||||||
|
|
||||||
|
## 本示例的作用
|
||||||
|
|
||||||
|
目标类 `target` 的 `say()` 方法原本打印:
|
||||||
|
|
||||||
|
```
|
||||||
|
Hello!
|
||||||
|
```
|
||||||
|
|
||||||
|
`new_target/target.java` 是它的修改版,额外打印:
|
||||||
|
|
||||||
|
```
|
||||||
|
Retransformed!
|
||||||
|
```
|
||||||
|
|
||||||
|
本示例把 `playload.jar` 注入到运行中的 JVM。payload 从自己的 JAR 中读取
|
||||||
|
`new_target.class`,调用 `JuiceAgent.retransformClassByName("target", ...)`
|
||||||
|
在运行时动态替换已加载的 `target` 类。之后 `say()` 无需重启 JVM 就会输出新内容。
|
||||||
|
|
||||||
|
## 使用步骤
|
||||||
|
|
||||||
|
### 1. 构建(可选)
|
||||||
|
|
||||||
|
`playload.jar` 和 `target.jar` 默认已包含。
|
||||||
|
如果修改了 `playload/`、`target/` 或 `new_target/`,运行:
|
||||||
|
|
||||||
|
```
|
||||||
|
build.bat
|
||||||
|
```
|
||||||
|
|
||||||
|
重新生成 `playload.jar`、`target.jar` 和 `new_target.class`。
|
||||||
|
|
||||||
|
### 2. 运行目标 JVM
|
||||||
|
|
||||||
|
双击 `run.bat`(或执行 `java -jar target.jar`)。黑窗口出现并每秒打印:
|
||||||
|
|
||||||
|
```
|
||||||
|
[Target] I am the target JVM (PID: <PID>)
|
||||||
|
Hello!
|
||||||
|
```
|
||||||
|
|
||||||
|
### 3. 注入
|
||||||
|
|
||||||
|
双击 `injector.exe`,输入目标 PID 后回车:
|
||||||
|
|
||||||
|
```
|
||||||
|
6644 target.jar
|
||||||
|
10504 jdk.jcmd/sun.tools.jps.Jps
|
||||||
|
Input PID: 6644
|
||||||
|
```
|
||||||
|
|
||||||
|
### 4. 验证
|
||||||
|
|
||||||
|
回到目标窗口,注入成功应看到:
|
||||||
|
|
||||||
|
```
|
||||||
|
Playload loaded!
|
||||||
|
Playload executed!
|
||||||
|
```
|
||||||
|
|
||||||
|
并且 `say()` 的输出从 `Hello!` 变为:
|
||||||
|
|
||||||
|
```
|
||||||
|
Hello!
|
||||||
|
Retransformed!
|
||||||
|
```
|
||||||
|
|
||||||
|
## 配置 / config.toml
|
||||||
|
|
||||||
|
| 配置项 | 说明 |
|
||||||
|
| --- | --- |
|
||||||
|
| `JarPath` | 注入的 JAR 路径(默认 `./playload.jar`) |
|
||||||
|
| `EntryClass` | 入口类(默认 `playload`) |
|
||||||
|
| `EntryMethod` | 入口方法,必须为 `public static void entry()` |
|
||||||
|
|
||||||
|
## 常见问题
|
||||||
|
|
||||||
|
- `java/javac/jar is not recognized`:
|
||||||
|
安装 JDK 并将 `bin` 目录加入 `PATH`。
|
||||||
|
- `injector.exe` 提示注入失败:
|
||||||
|
确认目标 JVM 正在运行且 PID 正确。
|
||||||
|
- 没有出现 `Playload loaded!` 输出:
|
||||||
|
查看本目录下的 `libagent.log` 和 `libloader.log` 定位原因。
|
||||||
|
- `say()` 输出没有变化:
|
||||||
|
确认修改 `new_target/` 后重新运行过 `build.bat`,且 `playload.jar` 内的
|
||||||
|
`new_target.class` 是最新的。
|
||||||
@@ -0,0 +1,82 @@
|
|||||||
|
============================================
|
||||||
|
如何使用
|
||||||
|
============================================
|
||||||
|
|
||||||
|
前置条件: Java 8+ (构建需要 javac/jar, 注入需要 jps)
|
||||||
|
|
||||||
|
目录文件:
|
||||||
|
injector.exe libagent.dll libinject.dll libloader.dll - JuiceAgent 运行库
|
||||||
|
config.toml - 注入配置
|
||||||
|
build.bat - 构建脚本
|
||||||
|
run.bat - 运行目标 JVM
|
||||||
|
playload.jar - 注入用的 JAR (由 build.bat 生成)
|
||||||
|
target.jar - 目标 JVM 程序 (由 build.bat 生成)
|
||||||
|
new_target.class - 重变换后的字节码 (由 build.bat 生成)
|
||||||
|
playload/ - payload 源码
|
||||||
|
target/ - 目标类源码
|
||||||
|
new_target/ - target 的修改版源码
|
||||||
|
|
||||||
|
============================================
|
||||||
|
本示例的作用
|
||||||
|
============================================
|
||||||
|
|
||||||
|
目标类 "target" 的 say() 方法原本打印:
|
||||||
|
Hello!
|
||||||
|
|
||||||
|
new_target/target.java 是它的修改版, 额外打印:
|
||||||
|
Retransformed!
|
||||||
|
|
||||||
|
本示例把 playload.jar 注入到运行中的 JVM。payload 从自己的 JAR 中读取
|
||||||
|
new_target.class, 调用 JuiceAgent.retransformClassByName("target", ...)
|
||||||
|
在运行时动态替换已加载的 "target" 类。之后 say() 无需重启 JVM 就会输出新内容。
|
||||||
|
|
||||||
|
============================================
|
||||||
|
使用步骤
|
||||||
|
============================================
|
||||||
|
|
||||||
|
1. 构建 (可选)
|
||||||
|
playload.jar 和 target.jar 默认已包含。
|
||||||
|
如果修改了 playload/、target/ 或 new_target/, 运行:
|
||||||
|
build.bat
|
||||||
|
重新生成 playload.jar、target.jar 和 new_target.class。
|
||||||
|
|
||||||
|
2. 运行目标 JVM
|
||||||
|
双击 run.bat (或执行: java -jar target.jar)。黑窗口出现并每秒打印:
|
||||||
|
[Target] I am the target JVM (PID: <PID>)
|
||||||
|
Hello!
|
||||||
|
|
||||||
|
3. 注入
|
||||||
|
双击 injector.exe, 输入目标 PID 后回车:
|
||||||
|
6644 target.jar
|
||||||
|
10504 jdk.jcmd/sun.tools.jps.Jps
|
||||||
|
Input PID: 6644
|
||||||
|
|
||||||
|
4. 验证
|
||||||
|
回到目标窗口, 注入成功应看到:
|
||||||
|
Playload loaded!
|
||||||
|
Playload executed!
|
||||||
|
并且 say() 的输出从 "Hello!" 变为:
|
||||||
|
Hello!
|
||||||
|
Retransformed!
|
||||||
|
|
||||||
|
============================================
|
||||||
|
配置 / config.toml
|
||||||
|
============================================
|
||||||
|
|
||||||
|
JarPath - 注入的 JAR 路径 (默认: ./playload.jar)
|
||||||
|
EntryClass - 入口类 (默认: playload)
|
||||||
|
EntryMethod - 入口方法, 必须为 public static void entry()
|
||||||
|
|
||||||
|
============================================
|
||||||
|
常见问题
|
||||||
|
============================================
|
||||||
|
|
||||||
|
- "java/javac/jar is not recognized":
|
||||||
|
安装 JDK 并将 bin 目录加入 PATH。
|
||||||
|
- injector.exe 提示注入失败:
|
||||||
|
确认目标 JVM 正在运行且 PID 正确。
|
||||||
|
- 没有出现 "Playload loaded!" 输出:
|
||||||
|
查看本目录下的 libagent.log 和 libloader.log 定位原因。
|
||||||
|
- say() 输出没有变化:
|
||||||
|
确认修改 new_target/ 后重新运行过 build.bat, 且 playload.jar 内的
|
||||||
|
new_target.class 是最新的。
|
||||||
+202
-129
@@ -1,161 +1,234 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <JuiceAgent/Logger.hpp>
|
|
||||||
#include <JuiceAgent/JuiceAgent.hpp>
|
|
||||||
#include <toml.hpp>
|
|
||||||
#include <filesystem>
|
#include <filesystem>
|
||||||
|
#include <optional>
|
||||||
|
#include <toml++/toml.h>
|
||||||
|
#include <stdexcept>
|
||||||
#include <string>
|
#include <string>
|
||||||
#include <JuiceAgent/Utils.hpp>
|
#include <vector>
|
||||||
|
#include <cstddef>
|
||||||
|
#include <JuiceAgent/Logger.hpp>
|
||||||
|
|
||||||
namespace JuiceAgent::Config {
|
namespace JuiceAgent::Config {
|
||||||
|
|
||||||
class Config {
|
class Config {
|
||||||
private:
|
private:
|
||||||
|
toml::table _config;
|
||||||
|
std::optional<toml::parse_error> _last_error;
|
||||||
|
|
||||||
std::filesystem::path _runtime_dir;
|
std::filesystem::path _runtime_dir;
|
||||||
toml::value _config;
|
std::filesystem::path _config_path;
|
||||||
|
|
||||||
bool _valid = false;
|
bool _valid = false;
|
||||||
|
|
||||||
private:
|
|
||||||
template<typename T>
|
|
||||||
static T _read_value(const toml::value& v) {
|
|
||||||
if constexpr (std::is_same_v<T, std::string>) {
|
|
||||||
return v.as_string();
|
|
||||||
} else if constexpr (std::is_same_v<T, bool>) {
|
|
||||||
return v.as_boolean();
|
|
||||||
} else if constexpr (std::is_integral_v<T> && !std::is_same_v<T, bool>) {
|
|
||||||
return static_cast<T>(v.as_integer());
|
|
||||||
} else if constexpr (std::is_floating_point_v<T>) {
|
|
||||||
return static_cast<T>(v.as_floating());
|
|
||||||
} else {
|
|
||||||
static_assert(sizeof(T) == 0, "Unsupported config type");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public:
|
public:
|
||||||
explicit Config(const std::filesystem::path& runtime_dir = {})
|
explicit Config(const std::filesystem::path& runtime_dir = {}) {
|
||||||
{
|
// Check if the runtime directory is empty
|
||||||
_runtime_dir = runtime_dir.empty()
|
if (runtime_dir.empty()) {
|
||||||
? std::filesystem::current_path()
|
// Use the default runtime directory
|
||||||
: runtime_dir;
|
_runtime_dir = std::filesystem::current_path();
|
||||||
|
|
||||||
const auto result = toml::try_parse(_runtime_dir / "config.toml");
|
|
||||||
|
|
||||||
if (result.is_ok()) {
|
|
||||||
_config = result.unwrap();
|
|
||||||
_valid = true;
|
|
||||||
} else {
|
} else {
|
||||||
PLOGE << "Failed to parse config.toml";
|
_runtime_dir = runtime_dir;
|
||||||
|
}
|
||||||
|
|
||||||
for (const auto& err : result.unwrap_err()) {
|
_config_path = _runtime_dir / "config.toml";
|
||||||
PLOGE << toml::format_error(err);
|
|
||||||
}
|
// Load the config file
|
||||||
|
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());
|
||||||
|
_last_error = e;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
bool is_valid() const noexcept {
|
|
||||||
return _valid;
|
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;
|
||||||
}
|
}
|
||||||
|
|
||||||
const toml::value& get_config() const noexcept {
|
template<typename T>
|
||||||
|
T get(const std::string& path, T defaultValue) const {
|
||||||
|
const auto* node = _config.at_path(path).node();
|
||||||
|
|
||||||
|
if (!node) {
|
||||||
|
// Configuration key is missing; use the default value.
|
||||||
|
spdlog::warn("Configuration key not found: {}, using default value", path);
|
||||||
|
return defaultValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto value = node->value<T>();
|
||||||
|
|
||||||
|
if (!value) {
|
||||||
|
// Configuration type mismatch; use the default value.
|
||||||
|
spdlog::warn("Configuration type mismatch: {}, using default value", path);
|
||||||
|
return defaultValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
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
|
||||||
|
) const {
|
||||||
|
std::string rawValue = get<std::string>(key, defaultValue);
|
||||||
|
|
||||||
|
// Use the default value when the configuration value is empty.
|
||||||
|
if (rawValue.empty()) {
|
||||||
|
rawValue = defaultValue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if (rawValue.empty()) {
|
||||||
|
return {};
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::filesystem::path value(rawValue);
|
||||||
|
|
||||||
|
if (value.is_absolute()) {
|
||||||
|
return value.lexically_normal().string();
|
||||||
|
}
|
||||||
|
|
||||||
|
const std::string normalized = value.generic_string();
|
||||||
|
|
||||||
|
if (normalized == "." || normalized.starts_with("./")) {
|
||||||
|
return (_runtime_dir / value).lexically_normal().string();
|
||||||
|
}
|
||||||
|
|
||||||
|
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;
|
||||||
|
}
|
||||||
|
|
||||||
|
// Getters
|
||||||
|
const toml::table& getConfig() const {
|
||||||
return _config;
|
return _config;
|
||||||
}
|
}
|
||||||
|
|
||||||
const std::filesystem::path& runtime_dir() const noexcept {
|
const std::filesystem::path& getRuntimeDir() const {
|
||||||
return _runtime_dir;
|
return _runtime_dir;
|
||||||
}
|
}
|
||||||
|
|
||||||
template<typename T>
|
const std::filesystem::path& getConfigPath() const {
|
||||||
T get(const std::string& path, const T& default_value, bool is_path = false) const {
|
return _config_path;
|
||||||
if (!_valid) {
|
}
|
||||||
return default_value;
|
|
||||||
}
|
|
||||||
|
|
||||||
try {
|
const std::optional<toml::parse_error>& getLastError() const {
|
||||||
const toml::value* current = &_config;
|
return _last_error;
|
||||||
std::size_t start = 0;
|
}
|
||||||
|
|
||||||
while (start < path.size()) {
|
bool isValid() const {
|
||||||
const std::size_t end = path.find('.', start);
|
return _valid;
|
||||||
const std::string key = path.substr(
|
|
||||||
start,
|
|
||||||
end == std::string::npos ? std::string::npos : end - start
|
|
||||||
);
|
|
||||||
|
|
||||||
current = ¤t->at(key);
|
|
||||||
|
|
||||||
if (end == std::string::npos) {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
start = end + 1;
|
|
||||||
}
|
|
||||||
|
|
||||||
T value = _read_value<T>(*current);
|
|
||||||
|
|
||||||
if constexpr (std::is_same_v<T, std::string>) {
|
|
||||||
if (value.empty()) {
|
|
||||||
return default_value;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Handle relative paths
|
|
||||||
if (is_path) {
|
|
||||||
// Check if starts with "."
|
|
||||||
if (value.starts_with(".")) {
|
|
||||||
// Remove "."
|
|
||||||
value = value.substr(1);
|
|
||||||
// Check if starts with "/"
|
|
||||||
if (value.starts_with("/")) {
|
|
||||||
// Remove "/"
|
|
||||||
value = value.substr(1);
|
|
||||||
}
|
|
||||||
|
|
||||||
// runtime_dir + value
|
|
||||||
value = (_runtime_dir / value).string();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
}
|
|
||||||
|
|
||||||
return value;
|
|
||||||
}
|
|
||||||
catch (const std::exception& e) {
|
|
||||||
PLOGW << "Config get failed: " << path << ", using default value";
|
|
||||||
return default_value;
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
namespace Utils {
|
|
||||||
inline LoaderConfig get_loader_config(const Config& config) {
|
|
||||||
auto cfg = config.get_config().at("JuiceAgent").at("Loader");
|
|
||||||
|
|
||||||
LoaderConfig loader_config = LoaderConfig();
|
|
||||||
loader_config.JuiceAgentNativeLibraryPath = cfg.at("JuiceAgentNativeLibraryPath").as_string();
|
|
||||||
loader_config.RuntimeDir = config.runtime_dir().string();
|
|
||||||
|
|
||||||
return loader_config;
|
|
||||||
}
|
|
||||||
|
|
||||||
inline void print_loader_config(const LoaderConfig& config) {
|
|
||||||
PLOGI << "JuiceAgentNativeLibraryPath: " << config.JuiceAgentNativeLibraryPath;
|
|
||||||
PLOGI << "RuntimeDir: " << config.RuntimeDir;
|
|
||||||
}
|
|
||||||
|
|
||||||
inline std::string serialize_loader_config(const LoaderConfig& config) {
|
|
||||||
// std::string result = "";
|
|
||||||
|
|
||||||
// result += "Version=2;";
|
|
||||||
// result += "JuiceAgentAPIJarPath=" + config.JuiceAgentAPIJarPath + ";";
|
|
||||||
// result += "JuiceAgentNativeLibraryPath=" + config.JuiceAgentNativeLibraryPath + ";";
|
|
||||||
// result += "RuntimeDir=" + config.RuntimeDir + ";";
|
|
||||||
|
|
||||||
JuiceAgent::Utils::Serializer ser;
|
|
||||||
ser.add_kv("Version", 2);
|
|
||||||
ser.add_kv("JuiceAgentNativeLibraryPath", config.JuiceAgentNativeLibraryPath);
|
|
||||||
ser.add_kv("RuntimeDir", config.RuntimeDir);
|
|
||||||
|
|
||||||
return ser.serialize();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
} // namespace JuiceAgent::Config
|
} // namespace JuiceAgent::Config
|
||||||
@@ -1,9 +1,3 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <string>
|
const int CONFIG_VERSION = 2;
|
||||||
|
|
||||||
struct LoaderConfig {
|
|
||||||
std::string JuiceAgentNativeLibraryPath;
|
|
||||||
|
|
||||||
std::string RuntimeDir;
|
|
||||||
};
|
|
||||||
@@ -1,18 +1,59 @@
|
|||||||
// Logger.hpp
|
|
||||||
#pragma once
|
#pragma once
|
||||||
#include <plog/Log.h>
|
|
||||||
#include <plog/Init.h>
|
|
||||||
#include <plog/Formatters/TxtFormatter.h>
|
|
||||||
#include <plog/Appenders/ColorConsoleAppender.h>
|
|
||||||
#include <plog/Appenders/DebugOutputAppender.h>
|
|
||||||
#include <plog/Appenders/RollingFileAppender.h>
|
|
||||||
|
|
||||||
inline void InitLogger()
|
#include <string>
|
||||||
{
|
#include <memory>
|
||||||
static plog::ColorConsoleAppender<plog::TxtFormatter> colorConsoleAppender;
|
#include <vector>
|
||||||
static plog::DebugOutputAppender<plog::TxtFormatter> debugAppender;
|
|
||||||
|
|
||||||
plog::init(plog::debug, &colorConsoleAppender).addAppender(&debugAppender);
|
#include <spdlog/spdlog.h>
|
||||||
|
#include <spdlog/sinks/stdout_color_sinks.h>
|
||||||
|
#include <spdlog/sinks/basic_file_sink.h>
|
||||||
|
|
||||||
|
namespace Logger {
|
||||||
|
|
||||||
|
inline void init(
|
||||||
|
const std::string& file_name = "app.log",
|
||||||
|
spdlog::level::level_enum level = spdlog::level::trace
|
||||||
|
) {
|
||||||
|
static bool initialized = false;
|
||||||
|
|
||||||
|
if (initialized) {
|
||||||
|
spdlog::warn("Logger already initialized, skipping");
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto console_sink =
|
||||||
|
std::make_shared<spdlog::sinks::stdout_color_sink_mt>();
|
||||||
|
|
||||||
|
auto file_sink =
|
||||||
|
std::make_shared<spdlog::sinks::basic_file_sink_mt>(
|
||||||
|
file_name,
|
||||||
|
true
|
||||||
|
);
|
||||||
|
|
||||||
|
std::vector<spdlog::sink_ptr> sinks{
|
||||||
|
console_sink,
|
||||||
|
file_sink
|
||||||
|
};
|
||||||
|
|
||||||
|
auto logger =
|
||||||
|
std::make_shared<spdlog::logger>(
|
||||||
|
"app",
|
||||||
|
sinks.begin(),
|
||||||
|
sinks.end()
|
||||||
|
);
|
||||||
|
|
||||||
|
logger->set_level(level);
|
||||||
|
|
||||||
|
logger->set_pattern(
|
||||||
|
"[%Y-%m-%d %H:%M:%S] [%^%l%$] %v"
|
||||||
|
);
|
||||||
|
|
||||||
|
spdlog::set_default_logger(logger);
|
||||||
|
|
||||||
|
// Flush after every log message
|
||||||
|
spdlog::flush_on(spdlog::level::trace);
|
||||||
|
|
||||||
|
initialized = true;
|
||||||
|
}
|
||||||
|
|
||||||
PLOG_INFO << "Logger initialized: Console + Debug Output";
|
|
||||||
}
|
}
|
||||||
+213
-211
@@ -1,58 +1,87 @@
|
|||||||
#pragma once
|
#pragma once
|
||||||
|
|
||||||
#include <jni.h>
|
#include <jvm/jni.h>
|
||||||
#include <jvmti.h>
|
#include <jvm/jvmti.h>
|
||||||
#include <JuiceAgent/Logger.hpp>
|
#include <JuiceAgent/Logger.hpp>
|
||||||
#include <string>
|
|
||||||
#include <unordered_map>
|
|
||||||
#include <type_traits>
|
|
||||||
#include <cstdlib>
|
|
||||||
#include <fstream>
|
|
||||||
#include <filesystem>
|
|
||||||
#include <chrono>
|
|
||||||
#include <stdexcept>
|
|
||||||
|
|
||||||
// Check for JNI exceptions and clear them
|
#include <cstdlib>
|
||||||
inline bool check_and_clear_exception(JNIEnv* env, const char* context) {
|
#include <filesystem>
|
||||||
if (env->ExceptionCheck()) {
|
#include <fstream>
|
||||||
PLOGE << "JNI Exception occurred at: " << context;
|
#include <string>
|
||||||
|
#include <type_traits>
|
||||||
|
#include <unordered_map>
|
||||||
|
#include <charconv>
|
||||||
|
#include <string_view>
|
||||||
|
#include <system_error>
|
||||||
|
|
||||||
|
namespace JuiceAgent::Utils
|
||||||
|
{
|
||||||
|
// JNIEnv::FindClass expects the internal form of a class name where the
|
||||||
|
// package separator is '/' (e.g. "Example/Main"). Configs and docs use the
|
||||||
|
// Java binary name with '.' (e.g. "Example.Main"), so normalize it here to
|
||||||
|
// keep both forms working.
|
||||||
|
inline std::string to_jni_class_name(const char* name)
|
||||||
|
{
|
||||||
|
std::string result(name ? name : "");
|
||||||
|
|
||||||
|
for (char& c : result) {
|
||||||
|
if (c == '.') {
|
||||||
|
c = '/';
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline bool check_and_clear_exception(JNIEnv* env, const char* context)
|
||||||
|
{
|
||||||
|
if (!env->ExceptionCheck()) {
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
spdlog::error("JNI Exception occurred at: {}", context);
|
||||||
env->ExceptionDescribe();
|
env->ExceptionDescribe();
|
||||||
env->ExceptionClear();
|
env->ExceptionClear();
|
||||||
return true;
|
return true;
|
||||||
}
|
}
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
namespace JuiceAgent::Utils
|
// Call a static Java method with a single string parameter
|
||||||
{
|
inline bool call_static_java_method(JNIEnv* env, const char* clazz, const char* method, const char* params)
|
||||||
inline bool call_java_impl(JNIEnv* env, const char* clazz, const char* method, const char* params) {
|
{
|
||||||
if (!env || !clazz || !method) {
|
if (!env || !clazz || !method) {
|
||||||
PLOGE << "Invalid JNI arguments";
|
spdlog::error("Invalid JNI arguments");
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
constexpr const char* method_signature = "(Ljava/lang/String;)V";
|
constexpr const char* signature = "(Ljava/lang/String;)V";
|
||||||
|
|
||||||
PLOGD << "Calling Java method: " << clazz << "." << method << " " << method_signature;
|
spdlog::debug("Calling Java method: {}.{} {}", clazz, method, signature);
|
||||||
|
|
||||||
jclass cls = env->FindClass(clazz);
|
std::string jni_class = to_jni_class_name(clazz);
|
||||||
|
jclass cls = env->FindClass(jni_class.c_str());
|
||||||
if (!cls) {
|
if (!cls) {
|
||||||
check_and_clear_exception(env, "FindClass failed");
|
check_and_clear_exception(env, "FindClass failed");
|
||||||
PLOGE << "Class not found: " << clazz;
|
spdlog::error("Class not found: {}", clazz);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
|
|
||||||
jmethodID mid = env->GetStaticMethodID(cls, method, method_signature);
|
jmethodID mid = env->GetStaticMethodID(cls, method, signature);
|
||||||
|
jstring j_params = mid
|
||||||
|
? env->NewStringUTF(params ? params : "")
|
||||||
|
: nullptr;
|
||||||
|
|
||||||
if (!mid) {
|
if (!mid) {
|
||||||
check_and_clear_exception(env, "GetStaticMethodID failed");
|
check_and_clear_exception(env, "GetStaticMethodID failed");
|
||||||
PLOGE << "Method not found: " << method;
|
spdlog::error("Method not found: {}", method);
|
||||||
env->DeleteLocalRef(cls);
|
}
|
||||||
return false;
|
else if (!j_params) {
|
||||||
|
spdlog::error("Failed to create jstring");
|
||||||
}
|
}
|
||||||
|
|
||||||
jstring j_params = env->NewStringUTF(params ? params : "");
|
if (!mid || !j_params) {
|
||||||
if (!j_params) {
|
if (j_params) {
|
||||||
PLOGE << "Failed to create jstring";
|
env->DeleteLocalRef(j_params);
|
||||||
|
}
|
||||||
env->DeleteLocalRef(cls);
|
env->DeleteLocalRef(cls);
|
||||||
return false;
|
return false;
|
||||||
}
|
}
|
||||||
@@ -69,226 +98,200 @@ namespace JuiceAgent::Utils
|
|||||||
return success;
|
return success;
|
||||||
}
|
}
|
||||||
|
|
||||||
class Serializer {
|
inline bool call_static_java_method(JNIEnv* env, const char* clazz, const char* method)
|
||||||
private:
|
{
|
||||||
std::string s;
|
if (!env || !clazz || !method) {
|
||||||
|
spdlog::error("Invalid JNI arguments");
|
||||||
private:
|
return false;
|
||||||
static std::string escape(const std::string& input) {
|
|
||||||
std::string out;
|
|
||||||
out.reserve(input.size());
|
|
||||||
|
|
||||||
for (char c : input) {
|
|
||||||
if (c == '=' || c == ';' || c == '\\') {
|
|
||||||
out += '\\';
|
|
||||||
}
|
|
||||||
out += c;
|
|
||||||
}
|
|
||||||
|
|
||||||
return out;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
public:
|
constexpr const char* signature = "()V";
|
||||||
Serializer() = default;
|
|
||||||
|
|
||||||
Serializer& add_kv(const std::string& key, const std::string& value) {
|
spdlog::debug("Calling Java method: {}.{} {}", clazz, method, signature);
|
||||||
s += escape(key);
|
|
||||||
|
std::string jni_class = to_jni_class_name(clazz);
|
||||||
|
jclass cls = env->FindClass(jni_class.c_str());
|
||||||
|
if (!cls) {
|
||||||
|
check_and_clear_exception(env, "FindClass failed");
|
||||||
|
spdlog::error("Class not found: {}", clazz);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
jmethodID mid = env->GetStaticMethodID(cls, method, signature);
|
||||||
|
if (!mid) {
|
||||||
|
check_and_clear_exception(env, "GetStaticMethodID failed");
|
||||||
|
spdlog::error("Method not found: {}", method);
|
||||||
|
env->DeleteLocalRef(cls);
|
||||||
|
return false;
|
||||||
|
}
|
||||||
|
|
||||||
|
env->CallStaticVoidMethod(cls, mid);
|
||||||
|
|
||||||
|
bool success = !env->ExceptionCheck();
|
||||||
|
check_and_clear_exception(env, "CallStaticVoidMethod failed");
|
||||||
|
|
||||||
|
env->DeleteLocalRef(cls);
|
||||||
|
|
||||||
|
return success;
|
||||||
|
}
|
||||||
|
|
||||||
|
class Serializer {
|
||||||
|
public:
|
||||||
|
template<typename T>
|
||||||
|
Serializer& add_kv(std::string_view key, const T& value)
|
||||||
|
{
|
||||||
|
append_escaped(key);
|
||||||
s += '=';
|
s += '=';
|
||||||
s += escape(value);
|
|
||||||
|
using ValueType = std::decay_t<T>;
|
||||||
|
|
||||||
|
if constexpr (std::is_same_v<ValueType, bool>) {
|
||||||
|
s += value ? "true" : "false";
|
||||||
|
}
|
||||||
|
else if constexpr (std::is_integral_v<ValueType>) {
|
||||||
|
append_number(value);
|
||||||
|
}
|
||||||
|
else if constexpr (std::is_floating_point_v<ValueType>) {
|
||||||
|
append_number(value);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
append_escaped(std::string_view(value));
|
||||||
|
}
|
||||||
|
|
||||||
s += ';';
|
s += ';';
|
||||||
return *this;
|
return *this;
|
||||||
}
|
}
|
||||||
|
|
||||||
Serializer& add_kv(const std::string& key, const char* value) {
|
void clear() noexcept
|
||||||
return add_kv(key, std::string(value));
|
{
|
||||||
}
|
|
||||||
|
|
||||||
Serializer& add_kv(const std::string& key, int value) {
|
|
||||||
return add_kv(key, std::to_string(value));
|
|
||||||
}
|
|
||||||
|
|
||||||
Serializer& add_kv(const std::string& key, bool value) {
|
|
||||||
return add_kv(key, value ? "true" : "false");
|
|
||||||
}
|
|
||||||
|
|
||||||
void clear() {
|
|
||||||
s.clear();
|
s.clear();
|
||||||
}
|
}
|
||||||
|
|
||||||
bool empty() const {
|
bool empty() const noexcept
|
||||||
|
{
|
||||||
return s.empty();
|
return s.empty();
|
||||||
}
|
}
|
||||||
|
|
||||||
const std::string& serialize() const {
|
const std::string& serialize() const noexcept
|
||||||
|
{
|
||||||
return s;
|
return s;
|
||||||
}
|
}
|
||||||
};
|
|
||||||
|
|
||||||
|
|
||||||
class Deserializer {
|
|
||||||
private:
|
|
||||||
std::unordered_map<std::string, std::string> data;
|
|
||||||
|
|
||||||
private:
|
private:
|
||||||
static std::string unescape(const std::string& input) {
|
void append_escaped(std::string_view input)
|
||||||
std::string out;
|
{
|
||||||
out.reserve(input.size());
|
|
||||||
|
|
||||||
bool escaped = false;
|
|
||||||
|
|
||||||
for (char c : input) {
|
for (char c : input) {
|
||||||
if (escaped) {
|
if (c == '=' || c == ';' || c == '\\') {
|
||||||
out += c;
|
s += '\\';
|
||||||
escaped = false;
|
|
||||||
continue;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (c == '\\') {
|
s += c;
|
||||||
escaped = true;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
out += c;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
return out;
|
|
||||||
}
|
|
||||||
|
|
||||||
static bool to_bool(const std::string& v, bool def) {
|
|
||||||
if (v == "true" || v == "1") return true;
|
|
||||||
if (v == "false" || v == "0") return false;
|
|
||||||
return def;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
template<typename T>
|
template<typename T>
|
||||||
static T convert(const std::string& v, T def) {
|
void append_number(T value)
|
||||||
if constexpr (std::is_same_v<T, std::string>) {
|
{
|
||||||
return v;
|
char buffer[64];
|
||||||
}
|
|
||||||
else if constexpr (std::is_same_v<T, bool>) {
|
auto [end, ec] = std::to_chars(
|
||||||
return to_bool(v, def);
|
buffer,
|
||||||
}
|
buffer + sizeof(buffer),
|
||||||
else if constexpr (std::is_integral_v<T>) {
|
value
|
||||||
try {
|
);
|
||||||
long long n = std::stoll(v);
|
|
||||||
return static_cast<T>(n);
|
if (ec == std::errc{}) {
|
||||||
} catch (...) {
|
s.append(buffer, end);
|
||||||
return def;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else if constexpr (std::is_floating_point_v<T>) {
|
|
||||||
try {
|
|
||||||
long double n = std::stold(v);
|
|
||||||
return static_cast<T>(n);
|
|
||||||
} catch (...) {
|
|
||||||
return def;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
else {
|
|
||||||
return def;
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
public:
|
std::string s;
|
||||||
Deserializer() = default;
|
|
||||||
|
|
||||||
explicit Deserializer(const std::string& input) {
|
|
||||||
parse(input);
|
|
||||||
}
|
|
||||||
|
|
||||||
void parse(const std::string& input) {
|
|
||||||
data.clear();
|
|
||||||
|
|
||||||
std::string key;
|
|
||||||
std::string value;
|
|
||||||
|
|
||||||
bool reading_key = true;
|
|
||||||
bool escaped = false;
|
|
||||||
|
|
||||||
for (char c : input) {
|
|
||||||
if (escaped) {
|
|
||||||
(reading_key ? key : value) += c;
|
|
||||||
escaped = false;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (c == '\\') {
|
|
||||||
escaped = true;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (reading_key && c == '=') {
|
|
||||||
reading_key = false;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (c == ';') {
|
|
||||||
if (!key.empty()) {
|
|
||||||
data[unescape(key)] = unescape(value);
|
|
||||||
}
|
|
||||||
|
|
||||||
key.clear();
|
|
||||||
value.clear();
|
|
||||||
reading_key = true;
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
(reading_key ? key : value) += c;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!key.empty()) {
|
|
||||||
data[unescape(key)] = unescape(value);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
bool has(const std::string& key) const {
|
|
||||||
return data.find(key) != data.end();
|
|
||||||
}
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
T get(const std::string& key, T def) const {
|
|
||||||
auto it = data.find(key);
|
|
||||||
if (it == data.end()) {
|
|
||||||
return def;
|
|
||||||
}
|
|
||||||
|
|
||||||
return convert<T>(it->second, def);
|
|
||||||
}
|
|
||||||
|
|
||||||
void clear() {
|
|
||||||
data.clear();
|
|
||||||
}
|
|
||||||
|
|
||||||
bool empty() const {
|
|
||||||
return data.empty();
|
|
||||||
}
|
|
||||||
|
|
||||||
std::size_t size() const {
|
|
||||||
return data.size();
|
|
||||||
}
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
inline jobjectArray to_java_string_array(
|
||||||
|
JNIEnv* env,
|
||||||
|
const std::vector<std::string>& values)
|
||||||
|
{
|
||||||
|
|
||||||
|
if (!env) {
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
jclass string_class = env->FindClass("java/lang/String");
|
||||||
|
if (!string_class) {
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
jobjectArray result = env->NewObjectArray(
|
||||||
|
static_cast<jsize>(values.size()),
|
||||||
|
string_class,
|
||||||
|
nullptr
|
||||||
|
);
|
||||||
|
|
||||||
|
if (!result) {
|
||||||
|
env->DeleteLocalRef(string_class);
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
for (jsize i = 0; i < static_cast<jsize>(values.size()); ++i) {
|
||||||
|
jstring value = env->NewStringUTF(values[i].c_str());
|
||||||
|
|
||||||
|
if (!value) {
|
||||||
|
env->DeleteLocalRef(result);
|
||||||
|
env->DeleteLocalRef(string_class);
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
|
||||||
|
env->SetObjectArrayElement(result, i, value);
|
||||||
|
env->DeleteLocalRef(value);
|
||||||
|
|
||||||
|
if (env->ExceptionCheck()) {
|
||||||
|
env->DeleteLocalRef(result);
|
||||||
|
env->DeleteLocalRef(string_class);
|
||||||
|
return nullptr;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
env->DeleteLocalRef(string_class);
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
inline std::string toDelimitedString(const std::vector<std::string>& values,
|
||||||
|
const std::string& delimiter = ",")
|
||||||
|
{
|
||||||
|
std::string result;
|
||||||
|
|
||||||
|
for (const auto& value : values) {
|
||||||
|
if (!result.empty()) {
|
||||||
|
result += delimiter;
|
||||||
|
}
|
||||||
|
result += value;
|
||||||
|
}
|
||||||
|
|
||||||
|
return result;
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
class File {
|
class File {
|
||||||
public:
|
public:
|
||||||
static inline std::string write_to_tempfile(
|
static std::string write_to_tempfile(
|
||||||
const unsigned char* data,
|
const unsigned char* data,
|
||||||
std::size_t size,
|
std::size_t size,
|
||||||
const std::string& name
|
const std::string& name
|
||||||
) {
|
)
|
||||||
#ifdef _WIN32
|
{
|
||||||
|
#ifdef _WIN32
|
||||||
const char* env = std::getenv("TEMP");
|
const char* env = std::getenv("TEMP");
|
||||||
std::filesystem::path dir = env ? env : ".";
|
#else
|
||||||
#else
|
|
||||||
const char* env = std::getenv("TMPDIR");
|
const char* env = std::getenv("TMPDIR");
|
||||||
std::filesystem::path dir = env ? env : "/tmp";
|
#endif
|
||||||
#endif
|
|
||||||
|
|
||||||
auto path = dir / name;
|
std::filesystem::path path = std::filesystem::path(env ? env : ".") / name;
|
||||||
|
|
||||||
std::ofstream out(path, std::ios::binary | std::ios::trunc);
|
std::ofstream out(path, std::ios::binary | std::ios::trunc);
|
||||||
if (!out) {
|
if (!out) {
|
||||||
PLOGE << "Failed to create temp file " << path;
|
spdlog::error("Failed to create temp file {}", path.string());
|
||||||
return "";
|
return {};
|
||||||
}
|
}
|
||||||
|
|
||||||
out.write(reinterpret_cast<const char*>(data), size);
|
out.write(reinterpret_cast<const char*>(data), size);
|
||||||
@@ -296,4 +299,3 @@ namespace JuiceAgent::Utils
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
} // namespace JuiceAgent::Utils
|
} // namespace JuiceAgent::Utils
|
||||||
|
|
||||||
-24
@@ -111,30 +111,6 @@ JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getCl
|
|||||||
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytesByName
|
JNIEXPORT jbyteArray JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_getClassBytesByName
|
||||||
(JNIEnv *, jclass, jstring);
|
(JNIEnv *, jclass, jstring);
|
||||||
|
|
||||||
/*
|
|
||||||
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
|
||||||
* Method: addRemapperWhiteList
|
|
||||||
* Signature: (Ljava/lang/String;)V
|
|
||||||
*/
|
|
||||||
JNIEXPORT void JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_addRemapperWhiteList
|
|
||||||
(JNIEnv *, jclass, jstring);
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
|
||||||
* Method: removeRemapperWhiteList
|
|
||||||
* Signature: (Ljava/lang/String;)V
|
|
||||||
*/
|
|
||||||
JNIEXPORT void JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_removeRemapperWhiteList
|
|
||||||
(JNIEnv *, jclass, jstring);
|
|
||||||
|
|
||||||
/*
|
|
||||||
* Class: cn_xiaozhou233_juiceagent_api_JuiceAgent
|
|
||||||
* Method: clearRemapperWhiteList
|
|
||||||
* Signature: ()V
|
|
||||||
*/
|
|
||||||
JNIEXPORT void JNICALL Java_cn_xiaozhou233_juiceagent_api_JuiceAgent_clearRemapperWhiteList
|
|
||||||
(JNIEnv *, jclass);
|
|
||||||
|
|
||||||
#ifdef __cplusplus
|
#ifdef __cplusplus
|
||||||
}
|
}
|
||||||
#endif
|
#endif
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
/* DO NOT EDIT THIS FILE - it is machine generated */
|
||||||
|
#include <jni.h>
|
||||||
|
/* Header for class cn_xiaozhou233_juiceagent_injector_Injector */
|
||||||
|
|
||||||
|
#ifndef _Included_cn_xiaozhou233_juiceagent_injector_Injector
|
||||||
|
#define _Included_cn_xiaozhou233_juiceagent_injector_Injector
|
||||||
|
#ifdef __cplusplus
|
||||||
|
extern "C" {
|
||||||
|
#endif
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceagent_injector_Injector
|
||||||
|
* Method: inject
|
||||||
|
* Signature: (ILjava/lang/String;)Z
|
||||||
|
*/
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_injector_Injector_inject__ILjava_lang_String_2
|
||||||
|
(JNIEnv *, jclass, jint, jstring);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceagent_injector_Injector
|
||||||
|
* Method: inject
|
||||||
|
* Signature: (ILjava/lang/String;Ljava/lang/String;)Z
|
||||||
|
*/
|
||||||
|
JNIEXPORT jboolean JNICALL Java_cn_xiaozhou233_juiceagent_injector_Injector_inject__ILjava_lang_String_2Ljava_lang_String_2
|
||||||
|
(JNIEnv *, jclass, jint, jstring, jstring);
|
||||||
|
|
||||||
|
/*
|
||||||
|
* Class: cn_xiaozhou233_juiceagent_injector_Injector
|
||||||
|
* Method: findWindowsByTitle
|
||||||
|
* Signature: (Ljava/lang/String;)[Lcn/xiaozhou233/juiceagent/injector/WindowInfo;
|
||||||
|
*/
|
||||||
|
JNIEXPORT jobjectArray JNICALL Java_cn_xiaozhou233_juiceagent_injector_Injector_findWindowsByTitle
|
||||||
|
(JNIEnv *, jclass, jstring);
|
||||||
|
|
||||||
|
#ifdef __cplusplus
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
@@ -30,7 +30,7 @@
|
|||||||
|
|
||||||
#define WIN32_LEAN_AND_MEAN
|
#define WIN32_LEAN_AND_MEAN
|
||||||
|
|
||||||
#include <Winsock2.h>
|
#include <winsock2.h>
|
||||||
|
|
||||||
#include <windows.h>
|
#include <windows.h>
|
||||||
#include <intrin.h>
|
#include <intrin.h>
|
||||||
|
|||||||
@@ -1,47 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <plog/Appenders/IAppender.h>
|
|
||||||
#include <android/log.h>
|
|
||||||
|
|
||||||
namespace plog
|
|
||||||
{
|
|
||||||
template<class Formatter>
|
|
||||||
class PLOG_LINKAGE_HIDDEN AndroidAppender : public IAppender
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
AndroidAppender(const char* tag) : m_tag(tag)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
virtual void write(const Record& record) PLOG_OVERRIDE
|
|
||||||
{
|
|
||||||
std::string str = Formatter::format(record);
|
|
||||||
|
|
||||||
__android_log_print(toPriority(record.getSeverity()), m_tag, "%s", str.c_str());
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
static android_LogPriority toPriority(Severity severity)
|
|
||||||
{
|
|
||||||
switch (severity)
|
|
||||||
{
|
|
||||||
case fatal:
|
|
||||||
return ANDROID_LOG_FATAL;
|
|
||||||
case error:
|
|
||||||
return ANDROID_LOG_ERROR;
|
|
||||||
case warning:
|
|
||||||
return ANDROID_LOG_WARN;
|
|
||||||
case info:
|
|
||||||
return ANDROID_LOG_INFO;
|
|
||||||
case debug:
|
|
||||||
return ANDROID_LOG_DEBUG;
|
|
||||||
case verbose:
|
|
||||||
return ANDROID_LOG_VERBOSE;
|
|
||||||
default:
|
|
||||||
return ANDROID_LOG_UNKNOWN;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
const char* const m_tag;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <plog/Appenders/IAppender.h>
|
|
||||||
#include <Arduino.h>
|
|
||||||
|
|
||||||
namespace plog
|
|
||||||
{
|
|
||||||
template<class Formatter>
|
|
||||||
class PLOG_LINKAGE_HIDDEN ArduinoAppender : public IAppender
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
ArduinoAppender(Stream &stream) : m_stream(stream)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
virtual void write(const Record &record) PLOG_OVERRIDE
|
|
||||||
{
|
|
||||||
m_stream.print(Formatter::format(record).c_str());
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
Stream &m_stream;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,108 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <plog/Appenders/ConsoleAppender.h>
|
|
||||||
#include <plog/WinApi.h>
|
|
||||||
|
|
||||||
namespace plog
|
|
||||||
{
|
|
||||||
template<class Formatter>
|
|
||||||
class PLOG_LINKAGE_HIDDEN ColorConsoleAppender : public ConsoleAppender<Formatter>
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
#ifdef _WIN32
|
|
||||||
# ifdef _MSC_VER
|
|
||||||
# pragma warning(suppress: 26812) // Prefer 'enum class' over 'enum'
|
|
||||||
# endif
|
|
||||||
ColorConsoleAppender(OutputStream outStream = streamStdOut)
|
|
||||||
: ConsoleAppender<Formatter>(outStream)
|
|
||||||
, m_originalAttr()
|
|
||||||
{
|
|
||||||
if (this->m_isatty)
|
|
||||||
{
|
|
||||||
CONSOLE_SCREEN_BUFFER_INFO csbiInfo;
|
|
||||||
GetConsoleScreenBufferInfo(this->m_outputHandle, &csbiInfo);
|
|
||||||
|
|
||||||
m_originalAttr = csbiInfo.wAttributes;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#else
|
|
||||||
ColorConsoleAppender(OutputStream outStream = streamStdOut)
|
|
||||||
: ConsoleAppender<Formatter>(outStream)
|
|
||||||
{}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
virtual void write(const Record& record) PLOG_OVERRIDE
|
|
||||||
{
|
|
||||||
util::nstring str = Formatter::format(record);
|
|
||||||
util::MutexLock lock(this->m_mutex);
|
|
||||||
|
|
||||||
setColor(record.getSeverity());
|
|
||||||
this->writestr(str);
|
|
||||||
resetColor();
|
|
||||||
}
|
|
||||||
|
|
||||||
protected:
|
|
||||||
void setColor(Severity severity)
|
|
||||||
{
|
|
||||||
if (this->m_isatty)
|
|
||||||
{
|
|
||||||
switch (severity)
|
|
||||||
{
|
|
||||||
#ifdef _WIN32
|
|
||||||
case fatal:
|
|
||||||
SetConsoleTextAttribute(this->m_outputHandle, foreground::kRed | foreground::kGreen | foreground::kBlue | foreground::kIntensity | background::kRed); // white on red background
|
|
||||||
break;
|
|
||||||
|
|
||||||
case error:
|
|
||||||
SetConsoleTextAttribute(this->m_outputHandle, static_cast<WORD>(foreground::kRed | foreground::kIntensity | (m_originalAttr & 0xf0))); // red
|
|
||||||
break;
|
|
||||||
|
|
||||||
case warning:
|
|
||||||
SetConsoleTextAttribute(this->m_outputHandle, static_cast<WORD>(foreground::kRed | foreground::kGreen | foreground::kIntensity | (m_originalAttr & 0xf0))); // yellow
|
|
||||||
break;
|
|
||||||
|
|
||||||
case debug:
|
|
||||||
case verbose:
|
|
||||||
SetConsoleTextAttribute(this->m_outputHandle, static_cast<WORD>(foreground::kGreen | foreground::kBlue | foreground::kIntensity | (m_originalAttr & 0xf0))); // cyan
|
|
||||||
break;
|
|
||||||
#else
|
|
||||||
case fatal:
|
|
||||||
this->m_outputStream << "\x1B[97m\x1B[41m"; // white on red background
|
|
||||||
break;
|
|
||||||
|
|
||||||
case error:
|
|
||||||
this->m_outputStream << "\x1B[91m"; // red
|
|
||||||
break;
|
|
||||||
|
|
||||||
case warning:
|
|
||||||
this->m_outputStream << "\x1B[93m"; // yellow
|
|
||||||
break;
|
|
||||||
|
|
||||||
case debug:
|
|
||||||
case verbose:
|
|
||||||
this->m_outputStream << "\x1B[96m"; // cyan
|
|
||||||
break;
|
|
||||||
#endif
|
|
||||||
default:
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void resetColor()
|
|
||||||
{
|
|
||||||
if (this->m_isatty)
|
|
||||||
{
|
|
||||||
#ifdef _WIN32
|
|
||||||
SetConsoleTextAttribute(this->m_outputHandle, m_originalAttr);
|
|
||||||
#else
|
|
||||||
this->m_outputStream << "\x1B[0m\x1B[0K";
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
#ifdef _WIN32
|
|
||||||
WORD m_originalAttr;
|
|
||||||
#endif
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,83 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <plog/Appenders/IAppender.h>
|
|
||||||
#include <plog/Util.h>
|
|
||||||
#include <plog/WinApi.h>
|
|
||||||
#include <iostream>
|
|
||||||
|
|
||||||
namespace plog
|
|
||||||
{
|
|
||||||
enum OutputStream
|
|
||||||
{
|
|
||||||
streamStdOut,
|
|
||||||
streamStdErr
|
|
||||||
};
|
|
||||||
|
|
||||||
template<class Formatter>
|
|
||||||
class PLOG_LINKAGE_HIDDEN ConsoleAppender : public IAppender
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
#ifdef _WIN32
|
|
||||||
# ifdef _MSC_VER
|
|
||||||
# pragma warning(suppress: 26812) // Prefer 'enum class' over 'enum'
|
|
||||||
# endif
|
|
||||||
ConsoleAppender(OutputStream outStream = streamStdOut)
|
|
||||||
: m_isatty(!!_isatty(_fileno(outStream == streamStdOut ? stdout : stderr)))
|
|
||||||
, m_outputStream(outStream == streamStdOut ? std::cout : std::cerr)
|
|
||||||
, m_outputHandle()
|
|
||||||
{
|
|
||||||
if (m_isatty)
|
|
||||||
{
|
|
||||||
m_outputHandle = GetStdHandle(outStream == streamStdOut ? stdHandle::kOutput : stdHandle::kErrorOutput);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#else
|
|
||||||
ConsoleAppender(OutputStream outStream = streamStdOut)
|
|
||||||
: m_isatty(!!isatty(fileno(outStream == streamStdOut ? stdout : stderr)))
|
|
||||||
, m_outputStream(outStream == streamStdOut ? std::cout : std::cerr)
|
|
||||||
{}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
virtual void write(const Record& record) PLOG_OVERRIDE
|
|
||||||
{
|
|
||||||
util::nstring str = Formatter::format(record);
|
|
||||||
util::MutexLock lock(m_mutex);
|
|
||||||
|
|
||||||
writestr(str);
|
|
||||||
}
|
|
||||||
|
|
||||||
protected:
|
|
||||||
void writestr(const util::nstring& str)
|
|
||||||
{
|
|
||||||
#ifdef _WIN32
|
|
||||||
if (m_isatty)
|
|
||||||
{
|
|
||||||
const std::wstring& wstr = util::toWide(str);
|
|
||||||
WriteConsoleW(m_outputHandle, wstr.c_str(), static_cast<DWORD>(wstr.size()), NULL, NULL);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
# if PLOG_CHAR_IS_UTF8
|
|
||||||
m_outputStream << str << std::flush;
|
|
||||||
# else
|
|
||||||
m_outputStream << util::toNarrow(str, codePage::kActive) << std::flush;
|
|
||||||
# endif
|
|
||||||
}
|
|
||||||
#else
|
|
||||||
m_outputStream << str << std::flush;
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
#ifdef __BORLANDC__
|
|
||||||
static int _isatty(int fd) { return ::isatty(fd); }
|
|
||||||
#endif
|
|
||||||
|
|
||||||
protected:
|
|
||||||
util::Mutex m_mutex;
|
|
||||||
const bool m_isatty;
|
|
||||||
std::ostream& m_outputStream;
|
|
||||||
#ifdef _WIN32
|
|
||||||
HANDLE m_outputHandle;
|
|
||||||
#endif
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <plog/Appenders/IAppender.h>
|
|
||||||
#include <plog/WinApi.h>
|
|
||||||
|
|
||||||
namespace plog
|
|
||||||
{
|
|
||||||
template<class Formatter>
|
|
||||||
class PLOG_LINKAGE_HIDDEN DebugOutputAppender : public IAppender
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
virtual void write(const Record& record) PLOG_OVERRIDE
|
|
||||||
{
|
|
||||||
OutputDebugStringW(util::toWide(Formatter::format(record)).c_str());
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,42 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <plog/Appenders/IAppender.h>
|
|
||||||
#include <set>
|
|
||||||
|
|
||||||
namespace plog
|
|
||||||
{
|
|
||||||
class PLOG_LINKAGE_HIDDEN DynamicAppender : public IAppender
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
DynamicAppender& addAppender(IAppender* appender)
|
|
||||||
{
|
|
||||||
assert(appender != this);
|
|
||||||
|
|
||||||
util::MutexLock lock(m_mutex);
|
|
||||||
m_appenders.insert(appender);
|
|
||||||
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
DynamicAppender& removeAppender(IAppender* appender)
|
|
||||||
{
|
|
||||||
util::MutexLock lock(m_mutex);
|
|
||||||
m_appenders.erase(appender);
|
|
||||||
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
virtual void write(const Record& record) PLOG_OVERRIDE
|
|
||||||
{
|
|
||||||
util::MutexLock lock(m_mutex);
|
|
||||||
|
|
||||||
for (std::set<IAppender*>::iterator it = m_appenders.begin(); it != m_appenders.end(); ++it)
|
|
||||||
{
|
|
||||||
(*it)->write(record);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
mutable util::Mutex m_mutex;
|
|
||||||
std::set<IAppender*> m_appenders;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,117 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <plog/Appenders/IAppender.h>
|
|
||||||
#include <plog/WinApi.h>
|
|
||||||
|
|
||||||
namespace plog
|
|
||||||
{
|
|
||||||
template <class Formatter>
|
|
||||||
class PLOG_LINKAGE_HIDDEN EventLogAppender : public IAppender
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
EventLogAppender(const util::nchar* sourceName) : m_eventSource(RegisterEventSourceW(NULL, util::toWide(sourceName).c_str()))
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
~EventLogAppender()
|
|
||||||
{
|
|
||||||
DeregisterEventSource(m_eventSource);
|
|
||||||
}
|
|
||||||
|
|
||||||
virtual void write(const Record& record) PLOG_OVERRIDE
|
|
||||||
{
|
|
||||||
util::nstring str = Formatter::format(record);
|
|
||||||
|
|
||||||
write(record.getSeverity(), util::toWide(str).c_str());
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
void write(Severity severity, const wchar_t* str)
|
|
||||||
{
|
|
||||||
const wchar_t* logMessagePtr[] = { str };
|
|
||||||
|
|
||||||
ReportEventW(m_eventSource, logSeverityToType(severity), static_cast<WORD>(severity), 0, NULL, 1, 0, logMessagePtr, NULL);
|
|
||||||
}
|
|
||||||
|
|
||||||
static WORD logSeverityToType(plog::Severity severity)
|
|
||||||
{
|
|
||||||
switch (severity)
|
|
||||||
{
|
|
||||||
case plog::fatal:
|
|
||||||
case plog::error:
|
|
||||||
return eventLog::kErrorType;
|
|
||||||
|
|
||||||
case plog::warning:
|
|
||||||
return eventLog::kWarningType;
|
|
||||||
|
|
||||||
case plog::info:
|
|
||||||
case plog::debug:
|
|
||||||
case plog::verbose:
|
|
||||||
default:
|
|
||||||
return eventLog::kInformationType;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
HANDLE m_eventSource;
|
|
||||||
};
|
|
||||||
|
|
||||||
class EventLogAppenderRegistry
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
static bool add(const util::nchar* sourceName, const util::nchar* logName = PLOG_NSTR("Application"))
|
|
||||||
{
|
|
||||||
std::wstring logKeyName;
|
|
||||||
std::wstring sourceKeyName;
|
|
||||||
getKeyNames(sourceName, logName, sourceKeyName, logKeyName);
|
|
||||||
|
|
||||||
HKEY sourceKey;
|
|
||||||
if (0 != RegCreateKeyExW(hkey::kLocalMachine, sourceKeyName.c_str(), 0, NULL, 0, regSam::kSetValue, NULL, &sourceKey, NULL))
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
const DWORD kTypesSupported = eventLog::kErrorType | eventLog::kWarningType | eventLog::kInformationType;
|
|
||||||
RegSetValueExW(sourceKey, L"TypesSupported", 0, regType::kDword, reinterpret_cast<const BYTE*>(&kTypesSupported), sizeof(kTypesSupported));
|
|
||||||
|
|
||||||
const wchar_t kEventMessageFile[] = L"%windir%\\Microsoft.NET\\Framework\\v4.0.30319\\EventLogMessages.dll;%windir%\\Microsoft.NET\\Framework\\v2.0.50727\\EventLogMessages.dll";
|
|
||||||
RegSetValueExW(sourceKey, L"EventMessageFile", 0, regType::kExpandSz, reinterpret_cast<const BYTE*>(kEventMessageFile), sizeof(kEventMessageFile) - sizeof(*kEventMessageFile));
|
|
||||||
|
|
||||||
RegCloseKey(sourceKey);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
static bool exists(const util::nchar* sourceName, const util::nchar* logName = PLOG_NSTR("Application"))
|
|
||||||
{
|
|
||||||
std::wstring logKeyName;
|
|
||||||
std::wstring sourceKeyName;
|
|
||||||
getKeyNames(sourceName, logName, sourceKeyName, logKeyName);
|
|
||||||
|
|
||||||
HKEY sourceKey;
|
|
||||||
if (0 != RegOpenKeyExW(hkey::kLocalMachine, sourceKeyName.c_str(), 0, regSam::kQueryValue, &sourceKey))
|
|
||||||
{
|
|
||||||
return false;
|
|
||||||
}
|
|
||||||
|
|
||||||
RegCloseKey(sourceKey);
|
|
||||||
return true;
|
|
||||||
}
|
|
||||||
|
|
||||||
static void remove(const util::nchar* sourceName, const util::nchar* logName = PLOG_NSTR("Application"))
|
|
||||||
{
|
|
||||||
std::wstring logKeyName;
|
|
||||||
std::wstring sourceKeyName;
|
|
||||||
getKeyNames(sourceName, logName, sourceKeyName, logKeyName);
|
|
||||||
|
|
||||||
RegDeleteKeyW(hkey::kLocalMachine, sourceKeyName.c_str());
|
|
||||||
RegDeleteKeyW(hkey::kLocalMachine, logKeyName.c_str());
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
static void getKeyNames(const util::nchar* sourceName, const util::nchar* logName, std::wstring& sourceKeyName, std::wstring& logKeyName)
|
|
||||||
{
|
|
||||||
const std::wstring kPrefix = L"SYSTEM\\CurrentControlSet\\Services\\EventLog\\";
|
|
||||||
logKeyName = kPrefix + util::toWide(logName);
|
|
||||||
sourceKeyName = logKeyName + L"\\" + util::toWide(sourceName);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,16 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <plog/Record.h>
|
|
||||||
#include <plog/Util.h>
|
|
||||||
|
|
||||||
namespace plog
|
|
||||||
{
|
|
||||||
class PLOG_LINKAGE IAppender
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
virtual ~IAppender()
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
virtual void write(const Record& record) = 0;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,148 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <plog/Appenders/IAppender.h>
|
|
||||||
#include <plog/Converters/UTF8Converter.h>
|
|
||||||
#include <plog/Converters/NativeEOLConverter.h>
|
|
||||||
#include <plog/Util.h>
|
|
||||||
#include <algorithm>
|
|
||||||
|
|
||||||
namespace plog
|
|
||||||
{
|
|
||||||
template<class Formatter, class Converter = NativeEOLConverter<UTF8Converter> >
|
|
||||||
class PLOG_LINKAGE_HIDDEN RollingFileAppender : public IAppender
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
RollingFileAppender(const util::nchar* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
|
||||||
: m_fileSize()
|
|
||||||
, m_maxFileSize()
|
|
||||||
, m_maxFiles(maxFiles)
|
|
||||||
, m_firstWrite(true)
|
|
||||||
{
|
|
||||||
setFileName(fileName);
|
|
||||||
setMaxFileSize(maxFileSize);
|
|
||||||
}
|
|
||||||
|
|
||||||
#if defined(_WIN32) && !PLOG_CHAR_IS_UTF8
|
|
||||||
RollingFileAppender(const char* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
|
||||||
: m_fileSize()
|
|
||||||
, m_maxFileSize()
|
|
||||||
, m_maxFiles(maxFiles)
|
|
||||||
, m_firstWrite(true)
|
|
||||||
{
|
|
||||||
setFileName(fileName);
|
|
||||||
setMaxFileSize(maxFileSize);
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
virtual void write(const Record& record) PLOG_OVERRIDE
|
|
||||||
{
|
|
||||||
util::MutexLock lock(m_mutex);
|
|
||||||
|
|
||||||
if (m_firstWrite)
|
|
||||||
{
|
|
||||||
openLogFile();
|
|
||||||
m_firstWrite = false;
|
|
||||||
}
|
|
||||||
else if (m_maxFiles > 0 && m_fileSize > m_maxFileSize && static_cast<size_t>(-1) != m_fileSize)
|
|
||||||
{
|
|
||||||
rollLogFiles();
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t bytesWritten = m_file.write(Converter::convert(Formatter::format(record)));
|
|
||||||
|
|
||||||
if (static_cast<size_t>(-1) != bytesWritten)
|
|
||||||
{
|
|
||||||
m_fileSize += bytesWritten;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void setFileName(const util::nchar* fileName)
|
|
||||||
{
|
|
||||||
util::MutexLock lock(m_mutex);
|
|
||||||
|
|
||||||
util::splitFileName(fileName, m_fileNameNoExt, m_fileExt);
|
|
||||||
|
|
||||||
m_file.close();
|
|
||||||
m_firstWrite = true;
|
|
||||||
}
|
|
||||||
|
|
||||||
#if defined(_WIN32) && !PLOG_CHAR_IS_UTF8
|
|
||||||
void setFileName(const char* fileName)
|
|
||||||
{
|
|
||||||
setFileName(util::toWide(fileName).c_str());
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
void setMaxFiles(int maxFiles)
|
|
||||||
{
|
|
||||||
m_maxFiles = maxFiles;
|
|
||||||
}
|
|
||||||
|
|
||||||
void setMaxFileSize(size_t maxFileSize)
|
|
||||||
{
|
|
||||||
m_maxFileSize = (std::max)(maxFileSize, static_cast<size_t>(1000)); // set a lower limit for the maxFileSize
|
|
||||||
}
|
|
||||||
|
|
||||||
void rollLogFiles()
|
|
||||||
{
|
|
||||||
m_file.close();
|
|
||||||
|
|
||||||
util::nstring lastFileName = buildFileName(m_maxFiles - 1);
|
|
||||||
util::File::unlink(lastFileName);
|
|
||||||
|
|
||||||
for (int fileNumber = m_maxFiles - 2; fileNumber >= 0; --fileNumber)
|
|
||||||
{
|
|
||||||
util::nstring currentFileName = buildFileName(fileNumber);
|
|
||||||
util::nstring nextFileName = buildFileName(fileNumber + 1);
|
|
||||||
|
|
||||||
util::File::rename(currentFileName, nextFileName);
|
|
||||||
}
|
|
||||||
|
|
||||||
openLogFile();
|
|
||||||
m_firstWrite = false;
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
void openLogFile()
|
|
||||||
{
|
|
||||||
m_fileSize = m_file.open(buildFileName());
|
|
||||||
|
|
||||||
if (0 == m_fileSize)
|
|
||||||
{
|
|
||||||
size_t bytesWritten = m_file.write(Converter::header(Formatter::header()));
|
|
||||||
|
|
||||||
if (static_cast<size_t>(-1) != bytesWritten)
|
|
||||||
{
|
|
||||||
m_fileSize += bytesWritten;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
util::nstring buildFileName(int fileNumber = 0)
|
|
||||||
{
|
|
||||||
util::nostringstream ss;
|
|
||||||
ss << m_fileNameNoExt;
|
|
||||||
|
|
||||||
if (fileNumber > 0)
|
|
||||||
{
|
|
||||||
ss << '.' << fileNumber;
|
|
||||||
}
|
|
||||||
|
|
||||||
if (!m_fileExt.empty())
|
|
||||||
{
|
|
||||||
ss << '.' << m_fileExt;
|
|
||||||
}
|
|
||||||
|
|
||||||
return ss.str();
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
util::Mutex m_mutex;
|
|
||||||
util::File m_file;
|
|
||||||
size_t m_fileSize;
|
|
||||||
size_t m_maxFileSize;
|
|
||||||
int m_maxFiles;
|
|
||||||
util::nstring m_fileExt;
|
|
||||||
util::nstring m_fileNameNoExt;
|
|
||||||
bool m_firstWrite;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,44 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <plog/Converters/UTF8Converter.h>
|
|
||||||
#include <plog/Util.h>
|
|
||||||
|
|
||||||
namespace plog
|
|
||||||
{
|
|
||||||
template<class NextConverter = UTF8Converter>
|
|
||||||
class NativeEOLConverter : public NextConverter
|
|
||||||
{
|
|
||||||
#ifdef _WIN32
|
|
||||||
public:
|
|
||||||
static std::string header(const util::nstring& str)
|
|
||||||
{
|
|
||||||
return NextConverter::header(fixLineEndings(str));
|
|
||||||
}
|
|
||||||
|
|
||||||
static std::string convert(const util::nstring& str)
|
|
||||||
{
|
|
||||||
return NextConverter::convert(fixLineEndings(str));
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
static util::nstring fixLineEndings(const util::nstring& str)
|
|
||||||
{
|
|
||||||
util::nstring output;
|
|
||||||
output.reserve(str.length() * 2); // the worst case requires 2x chars
|
|
||||||
|
|
||||||
for (size_t i = 0; i < str.size(); ++i)
|
|
||||||
{
|
|
||||||
util::nchar ch = str[i];
|
|
||||||
|
|
||||||
if (ch == PLOG_NSTR('\n'))
|
|
||||||
{
|
|
||||||
output.push_back(PLOG_NSTR('\r'));
|
|
||||||
}
|
|
||||||
|
|
||||||
output.push_back(ch);
|
|
||||||
}
|
|
||||||
|
|
||||||
return output;
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,28 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <plog/Util.h>
|
|
||||||
|
|
||||||
namespace plog
|
|
||||||
{
|
|
||||||
class UTF8Converter
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
static std::string header(const util::nstring& str)
|
|
||||||
{
|
|
||||||
const char kBOM[] = "\xEF\xBB\xBF";
|
|
||||||
|
|
||||||
return std::string(kBOM) + convert(str);
|
|
||||||
}
|
|
||||||
|
|
||||||
#if PLOG_CHAR_IS_UTF8
|
|
||||||
static const std::string& convert(const util::nstring& str)
|
|
||||||
{
|
|
||||||
return str;
|
|
||||||
}
|
|
||||||
#else
|
|
||||||
static std::string convert(const util::nstring& str)
|
|
||||||
{
|
|
||||||
return util::toNarrow(str, codePage::kUTF8);
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,57 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <plog/Record.h>
|
|
||||||
#include <plog/Util.h>
|
|
||||||
#include <iomanip>
|
|
||||||
|
|
||||||
namespace plog
|
|
||||||
{
|
|
||||||
template<bool useUtcTime>
|
|
||||||
class CsvFormatterImpl
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
static util::nstring header()
|
|
||||||
{
|
|
||||||
return PLOG_NSTR("Date;Time;Severity;TID;This;Function;Message\n");
|
|
||||||
}
|
|
||||||
|
|
||||||
static util::nstring format(const Record& record)
|
|
||||||
{
|
|
||||||
tm t;
|
|
||||||
useUtcTime ? util::gmtime_s(&t, &record.getTime().time) : util::localtime_s(&t, &record.getTime().time);
|
|
||||||
|
|
||||||
util::nostringstream ss;
|
|
||||||
ss << t.tm_year + 1900 << PLOG_NSTR("/") << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_mon + 1 << PLOG_NSTR("/") << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_mday << PLOG_NSTR(";");
|
|
||||||
ss << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_hour << PLOG_NSTR(":") << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_min << PLOG_NSTR(":") << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_sec << PLOG_NSTR(".") << std::setfill(PLOG_NSTR('0')) << std::setw(3) << static_cast<int> (record.getTime().millitm) << PLOG_NSTR(";");
|
|
||||||
ss << severityToString(record.getSeverity()) << PLOG_NSTR(";");
|
|
||||||
ss << record.getTid() << PLOG_NSTR(";");
|
|
||||||
ss << record.getObject() << PLOG_NSTR(";");
|
|
||||||
ss << record.getFunc() << PLOG_NSTR("@") << record.getLine() << PLOG_NSTR(";");
|
|
||||||
|
|
||||||
util::nstring message = record.getMessage();
|
|
||||||
|
|
||||||
if (message.size() > kMaxMessageSize)
|
|
||||||
{
|
|
||||||
message.resize(kMaxMessageSize);
|
|
||||||
message.append(PLOG_NSTR("..."));
|
|
||||||
}
|
|
||||||
|
|
||||||
util::nistringstream split(message);
|
|
||||||
util::nstring token;
|
|
||||||
|
|
||||||
while (!split.eof())
|
|
||||||
{
|
|
||||||
std::getline(split, token, PLOG_NSTR('"'));
|
|
||||||
ss << PLOG_NSTR("\"") << token << PLOG_NSTR("\"");
|
|
||||||
}
|
|
||||||
|
|
||||||
ss << PLOG_NSTR("\n");
|
|
||||||
|
|
||||||
return ss.str();
|
|
||||||
}
|
|
||||||
|
|
||||||
static const size_t kMaxMessageSize = 32000;
|
|
||||||
};
|
|
||||||
|
|
||||||
class CsvFormatter : public CsvFormatterImpl<false> {};
|
|
||||||
class CsvFormatterUtcTime : public CsvFormatterImpl<true> {};
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <plog/Record.h>
|
|
||||||
#include <plog/Util.h>
|
|
||||||
|
|
||||||
namespace plog
|
|
||||||
{
|
|
||||||
class FuncMessageFormatter
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
static util::nstring header()
|
|
||||||
{
|
|
||||||
return util::nstring();
|
|
||||||
}
|
|
||||||
|
|
||||||
static util::nstring format(const Record& record)
|
|
||||||
{
|
|
||||||
util::nostringstream ss;
|
|
||||||
ss << record.getFunc() << PLOG_NSTR("@") << record.getLine() << PLOG_NSTR(": ") << record.getMessage() << PLOG_NSTR("\n");
|
|
||||||
|
|
||||||
return ss.str();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,23 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <plog/Record.h>
|
|
||||||
#include <plog/Util.h>
|
|
||||||
|
|
||||||
namespace plog
|
|
||||||
{
|
|
||||||
class MessageOnlyFormatter
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
static util::nstring header()
|
|
||||||
{
|
|
||||||
return util::nstring();
|
|
||||||
}
|
|
||||||
|
|
||||||
static util::nstring format(const Record& record)
|
|
||||||
{
|
|
||||||
util::nostringstream ss;
|
|
||||||
ss << record.getMessage() << PLOG_NSTR("\n");
|
|
||||||
|
|
||||||
return ss.str();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,36 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <plog/Record.h>
|
|
||||||
#include <plog/Util.h>
|
|
||||||
#include <iomanip>
|
|
||||||
|
|
||||||
namespace plog
|
|
||||||
{
|
|
||||||
template<bool useUtcTime>
|
|
||||||
class TxtFormatterImpl
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
static util::nstring header()
|
|
||||||
{
|
|
||||||
return util::nstring();
|
|
||||||
}
|
|
||||||
|
|
||||||
static util::nstring format(const Record& record)
|
|
||||||
{
|
|
||||||
tm t;
|
|
||||||
useUtcTime ? util::gmtime_s(&t, &record.getTime().time) : util::localtime_s(&t, &record.getTime().time);
|
|
||||||
|
|
||||||
util::nostringstream ss;
|
|
||||||
ss << t.tm_year + 1900 << "-" << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_mon + 1 << PLOG_NSTR("-") << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_mday << PLOG_NSTR(" ");
|
|
||||||
ss << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_hour << PLOG_NSTR(":") << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_min << PLOG_NSTR(":") << std::setfill(PLOG_NSTR('0')) << std::setw(2) << t.tm_sec << PLOG_NSTR(".") << std::setfill(PLOG_NSTR('0')) << std::setw(3) << static_cast<int> (record.getTime().millitm) << PLOG_NSTR(" ");
|
|
||||||
ss << std::setfill(PLOG_NSTR(' ')) << std::setw(5) << std::left << severityToString(record.getSeverity()) << PLOG_NSTR(" ");
|
|
||||||
ss << PLOG_NSTR("[") << record.getTid() << PLOG_NSTR("] ");
|
|
||||||
ss << PLOG_NSTR("[") << record.getFunc() << PLOG_NSTR("@") << record.getLine() << PLOG_NSTR("] ");
|
|
||||||
ss << record.getMessage() << PLOG_NSTR("\n");
|
|
||||||
|
|
||||||
return ss.str();
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
class TxtFormatter : public TxtFormatterImpl<false> {};
|
|
||||||
class TxtFormatterUtcTime : public TxtFormatterImpl<true> {};
|
|
||||||
}
|
|
||||||
@@ -1,40 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <plog/Util.h>
|
|
||||||
#include <cctype>
|
|
||||||
|
|
||||||
namespace plog
|
|
||||||
{
|
|
||||||
class AscDump
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
AscDump(const void* ptr, size_t size)
|
|
||||||
: m_ptr(static_cast<const char*>(ptr))
|
|
||||||
, m_size(size)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
friend util::nostringstream& operator<<(util::nostringstream& stream, const AscDump& ascDump);
|
|
||||||
|
|
||||||
private:
|
|
||||||
const char* m_ptr;
|
|
||||||
size_t m_size;
|
|
||||||
};
|
|
||||||
|
|
||||||
inline util::nostringstream& operator<<(util::nostringstream& stream, const AscDump& ascDump)
|
|
||||||
{
|
|
||||||
for (size_t i = 0; i < ascDump.m_size; ++i)
|
|
||||||
{
|
|
||||||
stream << (std::isprint(ascDump.m_ptr[i]) ? ascDump.m_ptr[i] : '.');
|
|
||||||
}
|
|
||||||
|
|
||||||
return stream;
|
|
||||||
}
|
|
||||||
|
|
||||||
inline AscDump ascdump(const void* ptr, size_t size) { return AscDump(ptr, size); }
|
|
||||||
|
|
||||||
template<class Container>
|
|
||||||
inline AscDump ascdump(const Container& container) { return AscDump(container.data(), container.size() * sizeof(*container.data())); }
|
|
||||||
|
|
||||||
template<class T, size_t N>
|
|
||||||
inline AscDump ascdump(const T (&arr)[N]) { return AscDump(arr, N * sizeof(*arr)); }
|
|
||||||
}
|
|
||||||
@@ -1,79 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <plog/Util.h>
|
|
||||||
#include <iomanip>
|
|
||||||
|
|
||||||
namespace plog
|
|
||||||
{
|
|
||||||
class HexDump
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
HexDump(const void* ptr, size_t size)
|
|
||||||
: m_ptr(static_cast<const unsigned char*>(ptr))
|
|
||||||
, m_size(size)
|
|
||||||
, m_group(8)
|
|
||||||
, m_digitSeparator(" ")
|
|
||||||
, m_groupSeparator(" ")
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
HexDump& group(size_t group)
|
|
||||||
{
|
|
||||||
m_group = group;
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
HexDump& separator(const char* digitSeparator)
|
|
||||||
{
|
|
||||||
m_digitSeparator = digitSeparator;
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
HexDump& separator(const char* digitSeparator, const char* groupSeparator)
|
|
||||||
{
|
|
||||||
m_digitSeparator = digitSeparator;
|
|
||||||
m_groupSeparator = groupSeparator;
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
friend util::nostringstream& operator<<(util::nostringstream& stream, const HexDump&);
|
|
||||||
|
|
||||||
private:
|
|
||||||
const unsigned char* m_ptr;
|
|
||||||
size_t m_size;
|
|
||||||
size_t m_group;
|
|
||||||
const char* m_digitSeparator;
|
|
||||||
const char* m_groupSeparator;
|
|
||||||
};
|
|
||||||
|
|
||||||
inline util::nostringstream& operator<<(util::nostringstream& stream, const HexDump& hexDump)
|
|
||||||
{
|
|
||||||
stream << std::hex << std::setfill(PLOG_NSTR('0'));
|
|
||||||
|
|
||||||
for (size_t i = 0; i < hexDump.m_size;)
|
|
||||||
{
|
|
||||||
stream << std::setw(2) << static_cast<int>(hexDump.m_ptr[i]);
|
|
||||||
|
|
||||||
if (++i < hexDump.m_size)
|
|
||||||
{
|
|
||||||
if (hexDump.m_group > 0 && i % hexDump.m_group == 0)
|
|
||||||
{
|
|
||||||
stream << hexDump.m_groupSeparator;
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
stream << hexDump.m_digitSeparator;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return stream;
|
|
||||||
}
|
|
||||||
|
|
||||||
inline HexDump hexdump(const void* ptr, size_t size) { return HexDump(ptr, size); }
|
|
||||||
|
|
||||||
template<class Container>
|
|
||||||
inline HexDump hexdump(const Container& container) { return HexDump(container.data(), container.size() * sizeof(*container.data())); }
|
|
||||||
|
|
||||||
template<class T, size_t N>
|
|
||||||
inline HexDump hexdump(const T (&arr)[N]) { return HexDump(arr, N * sizeof(*arr)); }
|
|
||||||
}
|
|
||||||
@@ -1,24 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#define PLOG_IMPL_PRINT_VAR_1(a1) #a1 ": " << a1
|
|
||||||
#define PLOG_IMPL_PRINT_VAR_2(a1, a2) PLOG_IMPL_PRINT_VAR_1(a1) PLOG_IMPL_PRINT_VAR_TAIL(a2)
|
|
||||||
#define PLOG_IMPL_PRINT_VAR_3(a1, a2, a3) PLOG_IMPL_PRINT_VAR_2(a1, a2) PLOG_IMPL_PRINT_VAR_TAIL(a3)
|
|
||||||
#define PLOG_IMPL_PRINT_VAR_4(a1, a2, a3, a4) PLOG_IMPL_PRINT_VAR_3(a1, a2, a3) PLOG_IMPL_PRINT_VAR_TAIL(a4)
|
|
||||||
#define PLOG_IMPL_PRINT_VAR_5(a1, a2, a3, a4, a5) PLOG_IMPL_PRINT_VAR_4(a1, a2, a3, a4) PLOG_IMPL_PRINT_VAR_TAIL(a5)
|
|
||||||
#define PLOG_IMPL_PRINT_VAR_6(a1, a2, a3, a4, a5, a6) PLOG_IMPL_PRINT_VAR_5(a1, a2, a3, a4, a5) PLOG_IMPL_PRINT_VAR_TAIL(a6)
|
|
||||||
#define PLOG_IMPL_PRINT_VAR_7(a1, a2, a3, a4, a5, a6, a7) PLOG_IMPL_PRINT_VAR_6(a1, a2, a3, a4, a5, a6) PLOG_IMPL_PRINT_VAR_TAIL(a7)
|
|
||||||
#define PLOG_IMPL_PRINT_VAR_8(a1, a2, a3, a4, a5, a6, a7, a8) PLOG_IMPL_PRINT_VAR_7(a1, a2, a3, a4, a5, a6, a7) PLOG_IMPL_PRINT_VAR_TAIL(a8)
|
|
||||||
#define PLOG_IMPL_PRINT_VAR_9(a1, a2, a3, a4, a5, a6, a7, a8, a9) PLOG_IMPL_PRINT_VAR_8(a1, a2, a3, a4, a5, a6, a7, a8) PLOG_IMPL_PRINT_VAR_TAIL(a9)
|
|
||||||
#define PLOG_IMPL_PRINT_VAR_TAIL(a) << ", " PLOG_IMPL_PRINT_VAR_1(a)
|
|
||||||
|
|
||||||
#define PLOG_IMPL_PRINT_VAR_EXPAND(x) x
|
|
||||||
|
|
||||||
#ifdef __GNUC__
|
|
||||||
#pragma GCC system_header // disable warning: variadic macros are a C99 feature
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#define PLOG_IMPL_PRINT_VAR_GET_MACRO(x1, x2, x3, x4, x5, x6, x7, x8, x9, NAME, ...) NAME
|
|
||||||
|
|
||||||
#define PLOG_PRINT_VAR(...) PLOG_IMPL_PRINT_VAR_EXPAND(PLOG_IMPL_PRINT_VAR_GET_MACRO(__VA_ARGS__,\
|
|
||||||
PLOG_IMPL_PRINT_VAR_9, PLOG_IMPL_PRINT_VAR_8, PLOG_IMPL_PRINT_VAR_7, PLOG_IMPL_PRINT_VAR_6, PLOG_IMPL_PRINT_VAR_5,\
|
|
||||||
PLOG_IMPL_PRINT_VAR_4, PLOG_IMPL_PRINT_VAR_3, PLOG_IMPL_PRINT_VAR_2, PLOG_IMPL_PRINT_VAR_1, UNUSED)(__VA_ARGS__))
|
|
||||||
@@ -1,17 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <plog/Logger.h>
|
|
||||||
|
|
||||||
namespace plog
|
|
||||||
{
|
|
||||||
template<int instanceId>
|
|
||||||
PLOG_LINKAGE_HIDDEN inline Logger<instanceId>& init(Severity maxSeverity = none, IAppender* appender = NULL)
|
|
||||||
{
|
|
||||||
static Logger<instanceId> logger(maxSeverity);
|
|
||||||
return appender ? logger.addAppender(appender) : logger;
|
|
||||||
}
|
|
||||||
|
|
||||||
inline Logger<PLOG_DEFAULT_INSTANCE_ID>& init(Severity maxSeverity = none, IAppender* appender = NULL)
|
|
||||||
{
|
|
||||||
return init<PLOG_DEFAULT_INSTANCE_ID>(maxSeverity, appender);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,22 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <plog/Appenders/ColorConsoleAppender.h>
|
|
||||||
#include <plog/Init.h>
|
|
||||||
|
|
||||||
namespace plog
|
|
||||||
{
|
|
||||||
//////////////////////////////////////////////////////////////////////////
|
|
||||||
// ColorConsoleAppender with any Formatter
|
|
||||||
|
|
||||||
template<class Formatter, int instanceId>
|
|
||||||
PLOG_LINKAGE_HIDDEN inline Logger<instanceId>& init(Severity maxSeverity, OutputStream outputStream)
|
|
||||||
{
|
|
||||||
static ColorConsoleAppender<Formatter> appender(outputStream);
|
|
||||||
return init<instanceId>(maxSeverity, &appender);
|
|
||||||
}
|
|
||||||
|
|
||||||
template<class Formatter>
|
|
||||||
inline Logger<PLOG_DEFAULT_INSTANCE_ID>& init(Severity maxSeverity, OutputStream outputStream)
|
|
||||||
{
|
|
||||||
return init<Formatter, PLOG_DEFAULT_INSTANCE_ID>(maxSeverity, outputStream);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,80 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <plog/Appenders/RollingFileAppender.h>
|
|
||||||
#include <plog/Formatters/TxtFormatter.h>
|
|
||||||
#include <plog/Formatters/CsvFormatter.h>
|
|
||||||
#include <plog/Init.h>
|
|
||||||
#include <cstring>
|
|
||||||
|
|
||||||
namespace plog
|
|
||||||
{
|
|
||||||
//////////////////////////////////////////////////////////////////////////
|
|
||||||
// RollingFileAppender with any Formatter
|
|
||||||
|
|
||||||
template<class Formatter, int instanceId>
|
|
||||||
PLOG_LINKAGE_HIDDEN inline Logger<instanceId>& init(Severity maxSeverity, const util::nchar* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
|
||||||
{
|
|
||||||
static RollingFileAppender<Formatter> rollingFileAppender(fileName, maxFileSize, maxFiles);
|
|
||||||
return init<instanceId>(maxSeverity, &rollingFileAppender);
|
|
||||||
}
|
|
||||||
|
|
||||||
template<class Formatter>
|
|
||||||
inline Logger<PLOG_DEFAULT_INSTANCE_ID>& init(Severity maxSeverity, const util::nchar* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
|
||||||
{
|
|
||||||
return init<Formatter, PLOG_DEFAULT_INSTANCE_ID>(maxSeverity, fileName, maxFileSize, maxFiles);
|
|
||||||
}
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////
|
|
||||||
// RollingFileAppender with TXT/CSV chosen by file extension
|
|
||||||
|
|
||||||
namespace
|
|
||||||
{
|
|
||||||
inline bool isCsv(const util::nchar* fileName)
|
|
||||||
{
|
|
||||||
const util::nchar* dot = util::findExtensionDot(fileName);
|
|
||||||
#if PLOG_CHAR_IS_UTF8
|
|
||||||
return dot && 0 == std::strcmp(dot, ".csv");
|
|
||||||
#else
|
|
||||||
return dot && 0 == std::wcscmp(dot, L".csv");
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
template<int instanceId>
|
|
||||||
inline Logger<instanceId>& init(Severity maxSeverity, const util::nchar* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
|
||||||
{
|
|
||||||
return isCsv(fileName) ? init<CsvFormatter, instanceId>(maxSeverity, fileName, maxFileSize, maxFiles) : init<TxtFormatter, instanceId>(maxSeverity, fileName, maxFileSize, maxFiles);
|
|
||||||
}
|
|
||||||
|
|
||||||
inline Logger<PLOG_DEFAULT_INSTANCE_ID>& init(Severity maxSeverity, const util::nchar* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
|
||||||
{
|
|
||||||
return init<PLOG_DEFAULT_INSTANCE_ID>(maxSeverity, fileName, maxFileSize, maxFiles);
|
|
||||||
}
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////
|
|
||||||
// CHAR variants for Windows
|
|
||||||
|
|
||||||
#if defined(_WIN32) && !PLOG_CHAR_IS_UTF8
|
|
||||||
template<class Formatter, int instanceId>
|
|
||||||
inline Logger<instanceId>& init(Severity maxSeverity, const char* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
|
||||||
{
|
|
||||||
return init<Formatter, instanceId>(maxSeverity, util::toWide(fileName).c_str(), maxFileSize, maxFiles);
|
|
||||||
}
|
|
||||||
|
|
||||||
template<class Formatter>
|
|
||||||
inline Logger<PLOG_DEFAULT_INSTANCE_ID>& init(Severity maxSeverity, const char* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
|
||||||
{
|
|
||||||
return init<Formatter, PLOG_DEFAULT_INSTANCE_ID>(maxSeverity, fileName, maxFileSize, maxFiles);
|
|
||||||
}
|
|
||||||
|
|
||||||
template<int instanceId>
|
|
||||||
inline Logger<instanceId>& init(Severity maxSeverity, const char* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
|
||||||
{
|
|
||||||
return init<instanceId>(maxSeverity, util::toWide(fileName).c_str(), maxFileSize, maxFiles);
|
|
||||||
}
|
|
||||||
|
|
||||||
inline Logger<PLOG_DEFAULT_INSTANCE_ID>& init(Severity maxSeverity, const char* fileName, size_t maxFileSize = 0, int maxFiles = 0)
|
|
||||||
{
|
|
||||||
return init<PLOG_DEFAULT_INSTANCE_ID>(maxSeverity, fileName, maxFileSize, maxFiles);
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
@@ -1,209 +0,0 @@
|
|||||||
//////////////////////////////////////////////////////////////////////////
|
|
||||||
// Plog - portable and simple log for C++
|
|
||||||
// Documentation and sources: https://github.com/SergiusTheBest/plog
|
|
||||||
// License: MIT, https://choosealicense.com/licenses/mit
|
|
||||||
|
|
||||||
#pragma once
|
|
||||||
#include <plog/Logger.h>
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////
|
|
||||||
// Helper macros that get context info
|
|
||||||
|
|
||||||
#if defined(PLOG_ENABLE_GET_THIS) && defined(_MSC_VER) && _MSC_VER >= 1600 && !defined(__INTELLISENSE__) && !defined(__INTEL_COMPILER) && !defined(__llvm__) && !defined(__RESHARPER__) // >= Visual Studio 2010, skip IntelliSense, Intel Compiler, Clang Code Model and ReSharper
|
|
||||||
# define PLOG_GET_THIS() __if_exists(this) { this } __if_not_exists(this) { 0 }
|
|
||||||
#else
|
|
||||||
# define PLOG_GET_THIS() reinterpret_cast<void*>(0)
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifdef _MSC_VER
|
|
||||||
# define PLOG_GET_FUNC() __FUNCTION__
|
|
||||||
#elif defined(__BORLANDC__)
|
|
||||||
# define PLOG_GET_FUNC() __FUNC__
|
|
||||||
#else
|
|
||||||
# define PLOG_GET_FUNC() __PRETTY_FUNCTION__
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifdef PLOG_CAPTURE_FILE
|
|
||||||
# define PLOG_GET_FILE() __FILE__
|
|
||||||
#else
|
|
||||||
# define PLOG_GET_FILE() ""
|
|
||||||
#endif
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////
|
|
||||||
// Log severity level checker
|
|
||||||
|
|
||||||
#ifdef PLOG_DISABLE_LOGGING
|
|
||||||
# ifdef _MSC_VER
|
|
||||||
# define IF_PLOG_(instanceId, severity) __pragma(warning(push)) __pragma(warning(disable:4127)) if (true) {;} else __pragma(warning(pop)) // conditional expression is constant
|
|
||||||
# else
|
|
||||||
# define IF_PLOG_(instanceId, severity) if (true) {;} else
|
|
||||||
# endif
|
|
||||||
#else
|
|
||||||
# define IF_PLOG_(instanceId, severity) if (!plog::get<instanceId>() || !plog::get<instanceId>()->checkSeverity(severity)) {;} else
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#define IF_PLOG(severity) IF_PLOG_(PLOG_DEFAULT_INSTANCE_ID, severity)
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////
|
|
||||||
// Main logging macros
|
|
||||||
|
|
||||||
#ifdef PLOG_MESSAGE_PREFIX
|
|
||||||
# define PLOG_PRINT_MESSAGE_PREFIX() << PLOG_MESSAGE_PREFIX
|
|
||||||
#else
|
|
||||||
# define PLOG_PRINT_MESSAGE_PREFIX()
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#define PLOG_(instanceId, severity) IF_PLOG_(instanceId, severity) (*plog::get<instanceId>()) += \
|
|
||||||
plog::Record(severity, PLOG_GET_FUNC(), __LINE__, PLOG_GET_FILE(), PLOG_GET_THIS(), instanceId).ref() PLOG_PRINT_MESSAGE_PREFIX()
|
|
||||||
#define PLOG(severity) PLOG_(PLOG_DEFAULT_INSTANCE_ID, severity)
|
|
||||||
|
|
||||||
#define PLOG_VERBOSE PLOG(plog::verbose)
|
|
||||||
#define PLOG_DEBUG PLOG(plog::debug)
|
|
||||||
#define PLOG_INFO PLOG(plog::info)
|
|
||||||
#define PLOG_WARNING PLOG(plog::warning)
|
|
||||||
#define PLOG_ERROR PLOG(plog::error)
|
|
||||||
#define PLOG_FATAL PLOG(plog::fatal)
|
|
||||||
#define PLOG_NONE PLOG(plog::none)
|
|
||||||
|
|
||||||
#define PLOG_VERBOSE_(instanceId) PLOG_(instanceId, plog::verbose)
|
|
||||||
#define PLOG_DEBUG_(instanceId) PLOG_(instanceId, plog::debug)
|
|
||||||
#define PLOG_INFO_(instanceId) PLOG_(instanceId, plog::info)
|
|
||||||
#define PLOG_WARNING_(instanceId) PLOG_(instanceId, plog::warning)
|
|
||||||
#define PLOG_ERROR_(instanceId) PLOG_(instanceId, plog::error)
|
|
||||||
#define PLOG_FATAL_(instanceId) PLOG_(instanceId, plog::fatal)
|
|
||||||
#define PLOG_NONE_(instanceId) PLOG_(instanceId, plog::none)
|
|
||||||
|
|
||||||
#define PLOGV PLOG_VERBOSE
|
|
||||||
#define PLOGD PLOG_DEBUG
|
|
||||||
#define PLOGI PLOG_INFO
|
|
||||||
#define PLOGW PLOG_WARNING
|
|
||||||
#define PLOGE PLOG_ERROR
|
|
||||||
#define PLOGF PLOG_FATAL
|
|
||||||
#define PLOGN PLOG_NONE
|
|
||||||
|
|
||||||
#define PLOGV_(instanceId) PLOG_VERBOSE_(instanceId)
|
|
||||||
#define PLOGD_(instanceId) PLOG_DEBUG_(instanceId)
|
|
||||||
#define PLOGI_(instanceId) PLOG_INFO_(instanceId)
|
|
||||||
#define PLOGW_(instanceId) PLOG_WARNING_(instanceId)
|
|
||||||
#define PLOGE_(instanceId) PLOG_ERROR_(instanceId)
|
|
||||||
#define PLOGF_(instanceId) PLOG_FATAL_(instanceId)
|
|
||||||
#define PLOGN_(instanceId) PLOG_NONE_(instanceId)
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////
|
|
||||||
// Conditional logging macros
|
|
||||||
|
|
||||||
#define PLOG_IF_(instanceId, severity, condition) if (!(condition)) {;} else PLOG_(instanceId, severity)
|
|
||||||
#define PLOG_IF(severity, condition) PLOG_IF_(PLOG_DEFAULT_INSTANCE_ID, severity, condition)
|
|
||||||
|
|
||||||
#define PLOG_VERBOSE_IF(condition) PLOG_IF(plog::verbose, condition)
|
|
||||||
#define PLOG_DEBUG_IF(condition) PLOG_IF(plog::debug, condition)
|
|
||||||
#define PLOG_INFO_IF(condition) PLOG_IF(plog::info, condition)
|
|
||||||
#define PLOG_WARNING_IF(condition) PLOG_IF(plog::warning, condition)
|
|
||||||
#define PLOG_ERROR_IF(condition) PLOG_IF(plog::error, condition)
|
|
||||||
#define PLOG_FATAL_IF(condition) PLOG_IF(plog::fatal, condition)
|
|
||||||
#define PLOG_NONE_IF(condition) PLOG_IF(plog::none, condition)
|
|
||||||
|
|
||||||
#define PLOG_VERBOSE_IF_(instanceId, condition) PLOG_IF_(instanceId, plog::verbose, condition)
|
|
||||||
#define PLOG_DEBUG_IF_(instanceId, condition) PLOG_IF_(instanceId, plog::debug, condition)
|
|
||||||
#define PLOG_INFO_IF_(instanceId, condition) PLOG_IF_(instanceId, plog::info, condition)
|
|
||||||
#define PLOG_WARNING_IF_(instanceId, condition) PLOG_IF_(instanceId, plog::warning, condition)
|
|
||||||
#define PLOG_ERROR_IF_(instanceId, condition) PLOG_IF_(instanceId, plog::error, condition)
|
|
||||||
#define PLOG_FATAL_IF_(instanceId, condition) PLOG_IF_(instanceId, plog::fatal, condition)
|
|
||||||
#define PLOG_NONE_IF_(instanceId, condition) PLOG_IF_(instanceId, plog::none, condition)
|
|
||||||
|
|
||||||
#define PLOGV_IF(condition) PLOG_VERBOSE_IF(condition)
|
|
||||||
#define PLOGD_IF(condition) PLOG_DEBUG_IF(condition)
|
|
||||||
#define PLOGI_IF(condition) PLOG_INFO_IF(condition)
|
|
||||||
#define PLOGW_IF(condition) PLOG_WARNING_IF(condition)
|
|
||||||
#define PLOGE_IF(condition) PLOG_ERROR_IF(condition)
|
|
||||||
#define PLOGF_IF(condition) PLOG_FATAL_IF(condition)
|
|
||||||
#define PLOGN_IF(condition) PLOG_NONE_IF(condition)
|
|
||||||
|
|
||||||
#define PLOGV_IF_(instanceId, condition) PLOG_VERBOSE_IF_(instanceId, condition)
|
|
||||||
#define PLOGD_IF_(instanceId, condition) PLOG_DEBUG_IF_(instanceId, condition)
|
|
||||||
#define PLOGI_IF_(instanceId, condition) PLOG_INFO_IF_(instanceId, condition)
|
|
||||||
#define PLOGW_IF_(instanceId, condition) PLOG_WARNING_IF_(instanceId, condition)
|
|
||||||
#define PLOGE_IF_(instanceId, condition) PLOG_ERROR_IF_(instanceId, condition)
|
|
||||||
#define PLOGF_IF_(instanceId, condition) PLOG_FATAL_IF_(instanceId, condition)
|
|
||||||
#define PLOGN_IF_(instanceId, condition) PLOG_NONE_IF_(instanceId, condition)
|
|
||||||
|
|
||||||
// Old macro names for downward compatibility. To bypass including these macro names, add
|
|
||||||
// #define PLOG_OMIT_LOG_DEFINES before #include <plog/Log.h>
|
|
||||||
#ifndef PLOG_OMIT_LOG_DEFINES
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////
|
|
||||||
// Main logging macros - can be changed later to point at macros for a different logging package
|
|
||||||
|
|
||||||
#define LOG_(instanceId, severity) PLOG_(instanceId, severity)
|
|
||||||
#define LOG(severity) PLOG(severity)
|
|
||||||
|
|
||||||
#define LOG_VERBOSE PLOG_VERBOSE
|
|
||||||
#define LOG_DEBUG PLOG_DEBUG
|
|
||||||
#define LOG_INFO PLOG_INFO
|
|
||||||
#define LOG_WARNING PLOG_WARNING
|
|
||||||
#define LOG_ERROR PLOG_ERROR
|
|
||||||
#define LOG_FATAL PLOG_FATAL
|
|
||||||
#define LOG_NONE PLOG_NONE
|
|
||||||
|
|
||||||
#define LOG_VERBOSE_(instanceId) PLOG_VERBOSE_(instanceId)
|
|
||||||
#define LOG_DEBUG_(instanceId) PLOG_DEBUG_(instanceId)
|
|
||||||
#define LOG_INFO_(instanceId) PLOG_INFO_(instanceId)
|
|
||||||
#define LOG_WARNING_(instanceId) PLOG_WARNING_(instanceId)
|
|
||||||
#define LOG_ERROR_(instanceId) PLOG_ERROR_(instanceId)
|
|
||||||
#define LOG_FATAL_(instanceId) PLOG_FATAL_(instanceId)
|
|
||||||
#define LOG_NONE_(instanceId) PLOG_NONE_(instanceId)
|
|
||||||
|
|
||||||
#define LOGV PLOGV
|
|
||||||
#define LOGD PLOGD
|
|
||||||
#define LOGI PLOGI
|
|
||||||
#define LOGW PLOGW
|
|
||||||
#define LOGE PLOGE
|
|
||||||
#define LOGF PLOGF
|
|
||||||
#define LOGN PLOGN
|
|
||||||
|
|
||||||
#define LOGV_(instanceId) PLOGV_(instanceId)
|
|
||||||
#define LOGD_(instanceId) PLOGD_(instanceId)
|
|
||||||
#define LOGI_(instanceId) PLOGI_(instanceId)
|
|
||||||
#define LOGW_(instanceId) PLOGW_(instanceId)
|
|
||||||
#define LOGE_(instanceId) PLOGE_(instanceId)
|
|
||||||
#define LOGF_(instanceId) PLOGF_(instanceId)
|
|
||||||
#define LOGN_(instanceId) PLOGN_(instanceId)
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////
|
|
||||||
// Conditional logging macros
|
|
||||||
|
|
||||||
#define LOG_IF_(instanceId, severity, condition) PLOG_IF_(instanceId, severity, condition)
|
|
||||||
#define LOG_IF(severity, condition) PLOG_IF(severity, condition)
|
|
||||||
|
|
||||||
#define LOG_VERBOSE_IF(condition) PLOG_VERBOSE_IF(condition)
|
|
||||||
#define LOG_DEBUG_IF(condition) PLOG_DEBUG_IF(condition)
|
|
||||||
#define LOG_INFO_IF(condition) PLOG_INFO_IF(condition)
|
|
||||||
#define LOG_WARNING_IF(condition) PLOG_WARNING_IF(condition)
|
|
||||||
#define LOG_ERROR_IF(condition) PLOG_ERROR_IF(condition)
|
|
||||||
#define LOG_FATAL_IF(condition) PLOG_FATAL_IF(condition)
|
|
||||||
#define LOG_NONE_IF(condition) PLOG_NONE_IF(condition)
|
|
||||||
|
|
||||||
#define LOG_VERBOSE_IF_(instanceId, condition) PLOG_VERBOSE_IF_(instanceId, condition)
|
|
||||||
#define LOG_DEBUG_IF_(instanceId, condition) PLOG_DEBUG_IF_(instanceId, condition)
|
|
||||||
#define LOG_INFO_IF_(instanceId, condition) PLOG_INFO_IF_(instanceId, condition)
|
|
||||||
#define LOG_WARNING_IF_(instanceId, condition) PLOG_WARNING_IF_(instanceId, condition)
|
|
||||||
#define LOG_ERROR_IF_(instanceId, condition) PLOG_ERROR_IF_(instanceId, condition)
|
|
||||||
#define LOG_FATAL_IF_(instanceId, condition) PLOG_FATAL_IF_(instanceId, condition)
|
|
||||||
#define LOG_NONE_IF_(instanceId, condition) PLOG_NONE_IF_(instanceId, condition)
|
|
||||||
|
|
||||||
#define LOGV_IF(condition) PLOGV_IF(condition)
|
|
||||||
#define LOGD_IF(condition) PLOGD_IF(condition)
|
|
||||||
#define LOGI_IF(condition) PLOGI_IF(condition)
|
|
||||||
#define LOGW_IF(condition) PLOGW_IF(condition)
|
|
||||||
#define LOGE_IF(condition) PLOGE_IF(condition)
|
|
||||||
#define LOGF_IF(condition) PLOGF_IF(condition)
|
|
||||||
#define LOGN_IF(condition) PLOGN_IF(condition)
|
|
||||||
|
|
||||||
#define LOGV_IF_(instanceId, condition) PLOGV_IF_(instanceId, condition)
|
|
||||||
#define LOGD_IF_(instanceId, condition) PLOGD_IF_(instanceId, condition)
|
|
||||||
#define LOGI_IF_(instanceId, condition) PLOGI_IF_(instanceId, condition)
|
|
||||||
#define LOGW_IF_(instanceId, condition) PLOGW_IF_(instanceId, condition)
|
|
||||||
#define LOGE_IF_(instanceId, condition) PLOGE_IF_(instanceId, condition)
|
|
||||||
#define LOGF_IF_(instanceId, condition) PLOGF_IF_(instanceId, condition)
|
|
||||||
#define LOGN_IF_(instanceId, condition) PLOGN_IF_(instanceId, condition)
|
|
||||||
#endif
|
|
||||||
@@ -1,84 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <plog/Appenders/IAppender.h>
|
|
||||||
#include <plog/Util.h>
|
|
||||||
#include <vector>
|
|
||||||
|
|
||||||
#ifdef PLOG_DEFAULT_INSTANCE // for backward compatibility
|
|
||||||
# define PLOG_DEFAULT_INSTANCE_ID PLOG_DEFAULT_INSTANCE
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef PLOG_DEFAULT_INSTANCE_ID
|
|
||||||
# define PLOG_DEFAULT_INSTANCE_ID 0
|
|
||||||
#endif
|
|
||||||
|
|
||||||
namespace plog
|
|
||||||
{
|
|
||||||
template<int instanceId>
|
|
||||||
class PLOG_LINKAGE Logger : public util::Singleton<Logger<instanceId> >, public IAppender
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
Logger(Severity maxSeverity = none) : m_maxSeverity(maxSeverity)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
Logger& addAppender(IAppender* appender)
|
|
||||||
{
|
|
||||||
assert(appender != this);
|
|
||||||
m_appenders.push_back(appender);
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
Severity getMaxSeverity() const
|
|
||||||
{
|
|
||||||
return m_maxSeverity;
|
|
||||||
}
|
|
||||||
|
|
||||||
void setMaxSeverity(Severity severity)
|
|
||||||
{
|
|
||||||
m_maxSeverity = severity;
|
|
||||||
}
|
|
||||||
|
|
||||||
bool checkSeverity(Severity severity) const
|
|
||||||
{
|
|
||||||
return severity <= m_maxSeverity;
|
|
||||||
}
|
|
||||||
|
|
||||||
virtual void write(const Record& record) PLOG_OVERRIDE
|
|
||||||
{
|
|
||||||
if (checkSeverity(record.getSeverity()))
|
|
||||||
{
|
|
||||||
*this += record;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
void operator+=(const Record& record)
|
|
||||||
{
|
|
||||||
for (std::vector<IAppender*>::iterator it = m_appenders.begin(); it != m_appenders.end(); ++it)
|
|
||||||
{
|
|
||||||
(*it)->write(record);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
Severity m_maxSeverity;
|
|
||||||
#ifdef _MSC_VER
|
|
||||||
# pragma warning(push)
|
|
||||||
# pragma warning(disable:4251) // needs to have dll-interface to be used by clients of class
|
|
||||||
#endif
|
|
||||||
std::vector<IAppender*> m_appenders;
|
|
||||||
#ifdef _MSC_VER
|
|
||||||
# pragma warning(pop)
|
|
||||||
#endif
|
|
||||||
};
|
|
||||||
|
|
||||||
template<int instanceId>
|
|
||||||
inline Logger<instanceId>* get()
|
|
||||||
{
|
|
||||||
return Logger<instanceId>::getInstance();
|
|
||||||
}
|
|
||||||
|
|
||||||
inline Logger<PLOG_DEFAULT_INSTANCE_ID>* get()
|
|
||||||
{
|
|
||||||
return Logger<PLOG_DEFAULT_INSTANCE_ID>::getInstance();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,465 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <cstdarg>
|
|
||||||
#include <plog/Severity.h>
|
|
||||||
#include <plog/Util.h>
|
|
||||||
|
|
||||||
#ifdef __cplusplus_cli
|
|
||||||
#include <vcclr.h> // For PtrToStringChars
|
|
||||||
#endif
|
|
||||||
|
|
||||||
namespace plog
|
|
||||||
{
|
|
||||||
namespace detail
|
|
||||||
{
|
|
||||||
#if !defined(_MSC_VER) || _MSC_VER > 1400 // MSVC 2005 doesn't understand `enableIf`, so drop all `meta`
|
|
||||||
namespace meta
|
|
||||||
{
|
|
||||||
template<class T>
|
|
||||||
inline T& declval()
|
|
||||||
{
|
|
||||||
#ifdef __INTEL_COMPILER
|
|
||||||
# pragma warning(suppress: 327) // NULL reference is not allowed
|
|
||||||
#endif
|
|
||||||
return *reinterpret_cast<T*>(0);
|
|
||||||
}
|
|
||||||
|
|
||||||
template<bool B, class T = void>
|
|
||||||
struct enableIf {};
|
|
||||||
|
|
||||||
template<class T>
|
|
||||||
struct enableIf<true, T> { typedef T type; };
|
|
||||||
|
|
||||||
struct No { char a[1]; };
|
|
||||||
struct Yes { char a[2]; };
|
|
||||||
|
|
||||||
template <class From, class To>
|
|
||||||
struct isConvertible
|
|
||||||
{
|
|
||||||
// `+ sizeof(U*)` is required for GCC 4.5-4.7
|
|
||||||
template<class U>
|
|
||||||
static typename enableIf<!!(sizeof(static_cast<To>(meta::declval<U>())) + sizeof(U*)), Yes>::type test(int);
|
|
||||||
|
|
||||||
template<class U>
|
|
||||||
static No test(...);
|
|
||||||
|
|
||||||
enum { value = sizeof(test<From>(0)) == sizeof(Yes) };
|
|
||||||
};
|
|
||||||
|
|
||||||
template <class T>
|
|
||||||
struct isConvertibleToString : isConvertible<T, std::string> {};
|
|
||||||
|
|
||||||
#if PLOG_ENABLE_WCHAR_INPUT
|
|
||||||
template <class T>
|
|
||||||
struct isConvertibleToWString : isConvertible<T, std::wstring> {};
|
|
||||||
#endif
|
|
||||||
|
|
||||||
template <class T>
|
|
||||||
struct isContainer
|
|
||||||
{
|
|
||||||
template<class U>
|
|
||||||
static typename meta::enableIf<!!(sizeof(
|
|
||||||
#if defined(_MSC_VER) && _MSC_VER < 1700 // MSVC 2010 doesn't understand `typename T::const_iterator`
|
|
||||||
meta::declval<U>().begin()) + sizeof(meta::declval<U>().end()
|
|
||||||
#else
|
|
||||||
typename U::const_iterator
|
|
||||||
#endif
|
|
||||||
)), Yes>::type test(int);
|
|
||||||
|
|
||||||
template<class U>
|
|
||||||
static No test(...);
|
|
||||||
|
|
||||||
enum { value = sizeof(test<T>(0)) == sizeof(Yes) };
|
|
||||||
};
|
|
||||||
|
|
||||||
// Detects `std::filesystem::path` and `boost::filesystem::path`. They look like containers
|
|
||||||
// but we don't want to treat them as containers, so we use this detector to filter them out.
|
|
||||||
template <class T>
|
|
||||||
struct isFilesystemPath
|
|
||||||
{
|
|
||||||
template<class U>
|
|
||||||
static typename meta::enableIf<!!(sizeof(meta::declval<U>().preferred_separator)), Yes>::type test(int);
|
|
||||||
|
|
||||||
template<class U>
|
|
||||||
static No test(...);
|
|
||||||
|
|
||||||
enum { value = sizeof(test<T>(0)) == sizeof(Yes) };
|
|
||||||
};
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////
|
|
||||||
// Stream output operators as free functions
|
|
||||||
|
|
||||||
#if PLOG_ENABLE_WCHAR_INPUT
|
|
||||||
inline void operator<<(util::nostringstream& stream, const wchar_t* data)
|
|
||||||
{
|
|
||||||
data = data ? data : L"(null)";
|
|
||||||
|
|
||||||
# ifdef _WIN32
|
|
||||||
# if PLOG_CHAR_IS_UTF8
|
|
||||||
std::operator<<(stream, util::toNarrow(data, codePage::kUTF8));
|
|
||||||
# else
|
|
||||||
std::operator<<(stream, data);
|
|
||||||
# endif
|
|
||||||
# else
|
|
||||||
std::operator<<(stream, util::toNarrow(data));
|
|
||||||
# endif
|
|
||||||
}
|
|
||||||
|
|
||||||
inline void operator<<(util::nostringstream& stream, wchar_t* data)
|
|
||||||
{
|
|
||||||
plog::detail::operator<<(stream, const_cast<const wchar_t*>(data));
|
|
||||||
}
|
|
||||||
|
|
||||||
inline void operator<<(util::nostringstream& stream, const std::wstring& data)
|
|
||||||
{
|
|
||||||
plog::detail::operator<<(stream, data.c_str());
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
inline void operator<<(util::nostringstream& stream, const char* data)
|
|
||||||
{
|
|
||||||
data = data ? data : "(null)";
|
|
||||||
|
|
||||||
#if defined(_WIN32) && defined(__BORLANDC__)
|
|
||||||
# if PLOG_CHAR_IS_UTF8
|
|
||||||
stream << data;
|
|
||||||
# else
|
|
||||||
stream << util::toWide(data);
|
|
||||||
# endif
|
|
||||||
#elif defined(_WIN32)
|
|
||||||
# if PLOG_CHAR_IS_UTF8
|
|
||||||
std::operator<<(stream, data);
|
|
||||||
# else
|
|
||||||
std::operator<<(stream, util::toWide(data));
|
|
||||||
# endif
|
|
||||||
#else
|
|
||||||
std::operator<<(stream, data);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
inline void operator<<(util::nostringstream& stream, char* data)
|
|
||||||
{
|
|
||||||
plog::detail::operator<<(stream, const_cast<const char*>(data));
|
|
||||||
}
|
|
||||||
|
|
||||||
inline void operator<<(util::nostringstream& stream, const std::string& data)
|
|
||||||
{
|
|
||||||
plog::detail::operator<<(stream, data.c_str());
|
|
||||||
}
|
|
||||||
|
|
||||||
#ifdef __cpp_char8_t
|
|
||||||
inline void operator<<(util::nostringstream& stream, const char8_t* data)
|
|
||||||
{
|
|
||||||
# if PLOG_CHAR_IS_UTF8
|
|
||||||
plog::detail::operator<<(stream, reinterpret_cast<const char*>(data));
|
|
||||||
# else
|
|
||||||
plog::detail::operator<<(stream, util::toWide(reinterpret_cast<const char*>(data), codePage::kUTF8));
|
|
||||||
# endif
|
|
||||||
}
|
|
||||||
#endif //__cpp_char8_t
|
|
||||||
|
|
||||||
// Print `std::pair`
|
|
||||||
template<class T1, class T2>
|
|
||||||
inline void operator<<(util::nostringstream& stream, const std::pair<T1, T2>& data)
|
|
||||||
{
|
|
||||||
stream << data.first;
|
|
||||||
stream << ":";
|
|
||||||
stream << data.second;
|
|
||||||
}
|
|
||||||
|
|
||||||
#if defined(__clang__) || !defined(__GNUC__) || (__GNUC__ * 100 + __GNUC_MINOR__) >= 405 // skip for GCC < 4.5 due to https://gcc.gnu.org/bugzilla/show_bug.cgi?id=38600
|
|
||||||
#if !defined(_MSC_VER) || _MSC_VER > 1400 // MSVC 2005 doesn't understand `enableIf`, so drop all `meta`
|
|
||||||
// Print data that can be casted to `std::string`
|
|
||||||
template<class T>
|
|
||||||
inline typename meta::enableIf<meta::isConvertibleToString<T>::value, void>::type operator<<(util::nostringstream& stream, const T& data)
|
|
||||||
{
|
|
||||||
plog::detail::operator<<(stream, static_cast<std::string>(data));
|
|
||||||
}
|
|
||||||
|
|
||||||
#if PLOG_ENABLE_WCHAR_INPUT
|
|
||||||
// Print data that can be casted to `std::wstring`
|
|
||||||
template<class T>
|
|
||||||
inline typename meta::enableIf<meta::isConvertibleToWString<T>::value, void>::type operator<<(util::nostringstream& stream, const T& data)
|
|
||||||
{
|
|
||||||
plog::detail::operator<<(stream, static_cast<std::wstring>(data));
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
// Print std containers
|
|
||||||
template<class T>
|
|
||||||
inline typename meta::enableIf<meta::isContainer<T>::value &&
|
|
||||||
!meta::isConvertibleToString<T>::value &&
|
|
||||||
#if PLOG_ENABLE_WCHAR_INPUT
|
|
||||||
!meta::isConvertibleToWString<T>::value &&
|
|
||||||
#endif
|
|
||||||
!meta::isFilesystemPath<T>::value, void>::type operator<<(util::nostringstream& stream, const T& data)
|
|
||||||
{
|
|
||||||
stream << "[";
|
|
||||||
|
|
||||||
for (typename T::const_iterator it = data.begin(); it != data.end();)
|
|
||||||
{
|
|
||||||
stream << *it;
|
|
||||||
|
|
||||||
if (++it == data.end())
|
|
||||||
{
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
|
|
||||||
stream << ", ";
|
|
||||||
}
|
|
||||||
|
|
||||||
stream << "]";
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifdef __cplusplus_cli
|
|
||||||
// Print managed C++ `System::String^`
|
|
||||||
inline void operator<<(util::nostringstream& stream, System::String^ data)
|
|
||||||
{
|
|
||||||
cli::pin_ptr<const System::Char> ptr = PtrToStringChars(data);
|
|
||||||
plog::detail::operator<<(stream, static_cast<const wchar_t*>(ptr));
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#if PLOG_ENABLE_WCHAR_INPUT && (!defined(_MSC_VER) || _MSC_VER > 1400) // MSVC 2005 doesn't understand `enableIf`, so drop all `meta`
|
|
||||||
namespace meta
|
|
||||||
{
|
|
||||||
template<bool Value>
|
|
||||||
struct valueType { enum { value = Value }; };
|
|
||||||
|
|
||||||
template<class T, class Stream>
|
|
||||||
inline No operator<<(Stream&, const T&);
|
|
||||||
|
|
||||||
template<class T, class Stream>
|
|
||||||
struct isStreamable : valueType<sizeof(operator<<(meta::declval<Stream>(), meta::declval<const T>())) != sizeof(No)> {};
|
|
||||||
|
|
||||||
template<class Stream>
|
|
||||||
struct isStreamable<std::ios_base& PLOG_CDECL (std::ios_base&), Stream> : valueType<true> {};
|
|
||||||
|
|
||||||
template<class Stream, size_t N>
|
|
||||||
struct isStreamable<wchar_t[N], Stream> : valueType<false> {};
|
|
||||||
|
|
||||||
template<class Stream, size_t N>
|
|
||||||
struct isStreamable<const wchar_t[N], Stream> : valueType<false> {};
|
|
||||||
|
|
||||||
// meta doesn't work well for deleted functions and C++20 has `operator<<(std::ostream&, const wchar_t*) = delete` so explicitly define it
|
|
||||||
template<>
|
|
||||||
struct isStreamable<const wchar_t*, std::ostream> : valueType<false> {};
|
|
||||||
|
|
||||||
# ifdef __cpp_char8_t
|
|
||||||
// meta doesn't work well for deleted functions and C++20 has `operator<<(std::ostream&, const char8_t*) = delete` so explicitly define it
|
|
||||||
template<class Stream, size_t N>
|
|
||||||
struct isStreamable<char8_t[N], Stream> : valueType<false> {};
|
|
||||||
|
|
||||||
template<class Stream>
|
|
||||||
struct isStreamable<const char8_t*, Stream> : valueType<false> {};
|
|
||||||
# endif //__cpp_char8_t
|
|
||||||
}
|
|
||||||
|
|
||||||
# if PLOG_CHAR_IS_UTF8
|
|
||||||
// Print types that can be streamed into `std::owstringstream` but not into `std::ostringstream` when we use UTF-8 on Windows
|
|
||||||
template<class T>
|
|
||||||
inline typename meta::enableIf<meta::isStreamable<T, std::wostream>::value &&
|
|
||||||
!meta::isStreamable<T, std::ostream>::value &&
|
|
||||||
!meta::isConvertibleToWString<T>::value, void>::type operator<<(std::ostringstream& stream, const T& data)
|
|
||||||
{
|
|
||||||
std::wostringstream ss;
|
|
||||||
ss << data;
|
|
||||||
stream << ss.str();
|
|
||||||
}
|
|
||||||
# else
|
|
||||||
// Print types that can be streamed into `std::ostringstream` but not into `std::owstringstream` when we use `wchar_t` on Windows
|
|
||||||
template<class T>
|
|
||||||
inline typename meta::enableIf<meta::isStreamable<T, std::ostream>::value &&
|
|
||||||
!meta::isStreamable<T, std::wostream>::value &&
|
|
||||||
!meta::isConvertibleToString<T>::value, void>::type operator<<(std::wostringstream& stream, const T& data)
|
|
||||||
{
|
|
||||||
std::ostringstream ss;
|
|
||||||
ss << data;
|
|
||||||
stream << ss.str();
|
|
||||||
}
|
|
||||||
# endif
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
class Record
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
Record(Severity severity, const char* func, size_t line, const char* file, const void* object, int instanceId)
|
|
||||||
: m_severity(severity), m_tid(util::gettid()), m_object(object), m_line(line), m_func(func), m_file(file), m_instanceId(instanceId)
|
|
||||||
{
|
|
||||||
util::ftime(&m_time);
|
|
||||||
}
|
|
||||||
|
|
||||||
Record& ref()
|
|
||||||
{
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////
|
|
||||||
// Stream output operators
|
|
||||||
|
|
||||||
Record& operator<<(char data)
|
|
||||||
{
|
|
||||||
char str[] = { data, 0 };
|
|
||||||
return *this << str;
|
|
||||||
}
|
|
||||||
|
|
||||||
#if PLOG_ENABLE_WCHAR_INPUT
|
|
||||||
Record& operator<<(wchar_t data)
|
|
||||||
{
|
|
||||||
wchar_t str[] = { data, 0 };
|
|
||||||
return *this << str;
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
Record& operator<<(util::nostream& (PLOG_CDECL *data)(util::nostream&))
|
|
||||||
{
|
|
||||||
m_message << data;
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
#ifdef QT_VERSION
|
|
||||||
Record& operator<<(const QString& data)
|
|
||||||
{
|
|
||||||
# if PLOG_CHAR_IS_UTF8
|
|
||||||
return *this << data.toStdString();
|
|
||||||
# else
|
|
||||||
return *this << data.toStdWString();
|
|
||||||
# endif
|
|
||||||
}
|
|
||||||
|
|
||||||
# if QT_VERSION < 0x060000
|
|
||||||
Record& operator<<(const QStringRef& data)
|
|
||||||
{
|
|
||||||
return *this << data.toString();
|
|
||||||
}
|
|
||||||
# endif
|
|
||||||
|
|
||||||
# ifdef QSTRINGVIEW_H
|
|
||||||
Record& operator<<(QStringView data)
|
|
||||||
{
|
|
||||||
return *this << data.toString();
|
|
||||||
}
|
|
||||||
# endif
|
|
||||||
#endif
|
|
||||||
|
|
||||||
template<typename T>
|
|
||||||
Record& operator<<(const T& data)
|
|
||||||
{
|
|
||||||
using namespace plog::detail;
|
|
||||||
|
|
||||||
m_message << data;
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
#ifndef __cplusplus_cli
|
|
||||||
Record& printf(const char* format, ...)
|
|
||||||
{
|
|
||||||
using namespace util;
|
|
||||||
|
|
||||||
char* str = NULL;
|
|
||||||
va_list ap;
|
|
||||||
|
|
||||||
va_start(ap, format);
|
|
||||||
int len = vasprintf(&str, format, ap);
|
|
||||||
static_cast<void>(len);
|
|
||||||
va_end(ap);
|
|
||||||
|
|
||||||
*this << str;
|
|
||||||
free(str);
|
|
||||||
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
|
|
||||||
#ifdef _WIN32
|
|
||||||
Record& printf(const wchar_t* format, ...)
|
|
||||||
{
|
|
||||||
using namespace util;
|
|
||||||
|
|
||||||
wchar_t* str = NULL;
|
|
||||||
va_list ap;
|
|
||||||
|
|
||||||
va_start(ap, format);
|
|
||||||
int len = vaswprintf(&str, format, ap);
|
|
||||||
static_cast<void>(len);
|
|
||||||
va_end(ap);
|
|
||||||
|
|
||||||
*this << str;
|
|
||||||
free(str);
|
|
||||||
|
|
||||||
return *this;
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
#endif //__cplusplus_cli
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////
|
|
||||||
// Getters
|
|
||||||
|
|
||||||
virtual const util::Time& getTime() const
|
|
||||||
{
|
|
||||||
return m_time;
|
|
||||||
}
|
|
||||||
|
|
||||||
virtual Severity getSeverity() const
|
|
||||||
{
|
|
||||||
return m_severity;
|
|
||||||
}
|
|
||||||
|
|
||||||
virtual unsigned int getTid() const
|
|
||||||
{
|
|
||||||
return m_tid;
|
|
||||||
}
|
|
||||||
|
|
||||||
virtual const void* getObject() const
|
|
||||||
{
|
|
||||||
return m_object;
|
|
||||||
}
|
|
||||||
|
|
||||||
virtual size_t getLine() const
|
|
||||||
{
|
|
||||||
return m_line;
|
|
||||||
}
|
|
||||||
|
|
||||||
virtual const util::nchar* getMessage() const
|
|
||||||
{
|
|
||||||
m_messageStr = m_message.str();
|
|
||||||
return m_messageStr.c_str();
|
|
||||||
}
|
|
||||||
|
|
||||||
virtual const char* getFunc() const
|
|
||||||
{
|
|
||||||
m_funcStr = util::processFuncName(m_func);
|
|
||||||
return m_funcStr.c_str();
|
|
||||||
}
|
|
||||||
|
|
||||||
virtual const char* getFile() const
|
|
||||||
{
|
|
||||||
return m_file;
|
|
||||||
}
|
|
||||||
|
|
||||||
virtual ~Record() // virtual destructor to satisfy -Wnon-virtual-dtor warning
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
virtual int getInstanceId() const
|
|
||||||
{
|
|
||||||
return m_instanceId;
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
util::Time m_time;
|
|
||||||
const Severity m_severity;
|
|
||||||
const unsigned int m_tid;
|
|
||||||
const void* const m_object;
|
|
||||||
const size_t m_line;
|
|
||||||
util::nostringstream m_message;
|
|
||||||
const char* const m_func;
|
|
||||||
const char* const m_file;
|
|
||||||
const int m_instanceId;
|
|
||||||
mutable std::string m_funcStr;
|
|
||||||
mutable util::nstring m_messageStr;
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,61 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <cctype>
|
|
||||||
|
|
||||||
namespace plog
|
|
||||||
{
|
|
||||||
enum Severity
|
|
||||||
{
|
|
||||||
none = 0,
|
|
||||||
fatal = 1,
|
|
||||||
error = 2,
|
|
||||||
warning = 3,
|
|
||||||
info = 4,
|
|
||||||
debug = 5,
|
|
||||||
verbose = 6
|
|
||||||
};
|
|
||||||
|
|
||||||
#ifdef _MSC_VER
|
|
||||||
# pragma warning(suppress: 26812) // Prefer 'enum class' over 'enum'
|
|
||||||
#endif
|
|
||||||
inline const char* severityToString(Severity severity)
|
|
||||||
{
|
|
||||||
switch (severity)
|
|
||||||
{
|
|
||||||
case fatal:
|
|
||||||
return "FATAL";
|
|
||||||
case error:
|
|
||||||
return "ERROR";
|
|
||||||
case warning:
|
|
||||||
return "WARN";
|
|
||||||
case info:
|
|
||||||
return "INFO";
|
|
||||||
case debug:
|
|
||||||
return "DEBUG";
|
|
||||||
case verbose:
|
|
||||||
return "VERB";
|
|
||||||
default:
|
|
||||||
return "NONE";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
inline Severity severityFromString(const char* str)
|
|
||||||
{
|
|
||||||
switch (std::toupper(str[0]))
|
|
||||||
{
|
|
||||||
case 'F':
|
|
||||||
return fatal;
|
|
||||||
case 'E':
|
|
||||||
return error;
|
|
||||||
case 'W':
|
|
||||||
return warning;
|
|
||||||
case 'I':
|
|
||||||
return info;
|
|
||||||
case 'D':
|
|
||||||
return debug;
|
|
||||||
case 'V':
|
|
||||||
return verbose;
|
|
||||||
default:
|
|
||||||
return none;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,635 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
#include <cassert>
|
|
||||||
#include <cstring>
|
|
||||||
#include <cstdio>
|
|
||||||
#include <cstdlib>
|
|
||||||
#include <sstream>
|
|
||||||
#include <fcntl.h>
|
|
||||||
#include <sys/stat.h>
|
|
||||||
|
|
||||||
#ifndef PLOG_ENABLE_WCHAR_INPUT
|
|
||||||
# ifdef _WIN32
|
|
||||||
# define PLOG_ENABLE_WCHAR_INPUT 1
|
|
||||||
# else
|
|
||||||
# define PLOG_ENABLE_WCHAR_INPUT 0
|
|
||||||
# endif
|
|
||||||
#endif
|
|
||||||
|
|
||||||
//////////////////////////////////////////////////////////////////////////
|
|
||||||
// PLOG_CHAR_IS_UTF8 specifies character encoding of `char` type. On *nix
|
|
||||||
// systems it's set to UTF-8 while on Windows in can be ANSI or UTF-8. It
|
|
||||||
// automatically detects `/utf-8` command line option in MSVC. Also it can
|
|
||||||
// be set manually if required.
|
|
||||||
// This option allows to support http://utf8everywhere.org approach.
|
|
||||||
|
|
||||||
#ifndef PLOG_CHAR_IS_UTF8
|
|
||||||
# if defined(_WIN32) && !defined(_UTF8)
|
|
||||||
# define PLOG_CHAR_IS_UTF8 0
|
|
||||||
# else
|
|
||||||
# define PLOG_CHAR_IS_UTF8 1
|
|
||||||
# endif
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifdef _WIN32
|
|
||||||
# if defined(PLOG_EXPORT)
|
|
||||||
# define PLOG_LINKAGE __declspec(dllexport)
|
|
||||||
# elif defined(PLOG_IMPORT)
|
|
||||||
# define PLOG_LINKAGE __declspec(dllimport)
|
|
||||||
# endif
|
|
||||||
# if defined(PLOG_GLOBAL)
|
|
||||||
# error "PLOG_GLOBAL isn't supported on Windows"
|
|
||||||
# endif
|
|
||||||
#else
|
|
||||||
# if defined(PLOG_GLOBAL)
|
|
||||||
# define PLOG_LINKAGE __attribute__ ((visibility ("default")))
|
|
||||||
# elif defined(PLOG_LOCAL)
|
|
||||||
# define PLOG_LINKAGE __attribute__ ((visibility ("hidden")))
|
|
||||||
# define PLOG_LINKAGE_HIDDEN PLOG_LINKAGE
|
|
||||||
# endif
|
|
||||||
# if defined(PLOG_EXPORT) || defined(PLOG_IMPORT)
|
|
||||||
# error "PLOG_EXPORT/PLOG_IMPORT is supported only on Windows"
|
|
||||||
# endif
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef PLOG_LINKAGE
|
|
||||||
# define PLOG_LINKAGE
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifndef PLOG_LINKAGE_HIDDEN
|
|
||||||
# define PLOG_LINKAGE_HIDDEN
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifdef _WIN32
|
|
||||||
# include <plog/WinApi.h>
|
|
||||||
# include <time.h>
|
|
||||||
# include <sys/timeb.h>
|
|
||||||
# include <io.h>
|
|
||||||
# include <share.h>
|
|
||||||
#else
|
|
||||||
# include <unistd.h>
|
|
||||||
# include <sys/time.h>
|
|
||||||
# if defined(__linux__) || defined(__FreeBSD__)
|
|
||||||
# include <sys/syscall.h>
|
|
||||||
# elif defined(__rtems__)
|
|
||||||
# include <rtems.h>
|
|
||||||
# endif
|
|
||||||
# if defined(_POSIX_THREADS)
|
|
||||||
# include <pthread.h>
|
|
||||||
# endif
|
|
||||||
# if PLOG_ENABLE_WCHAR_INPUT
|
|
||||||
# include <iconv.h>
|
|
||||||
# endif
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifdef __FREERTOS__ // There is no standard way to know if the code is compiled for FreeRTOS. We expect __FREERTOS__ macro to be defined in such case.
|
|
||||||
# include <FreeRTOS.h>
|
|
||||||
# include <semphr.h>
|
|
||||||
# include <task.h>
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#if PLOG_CHAR_IS_UTF8
|
|
||||||
# define PLOG_NSTR(x) x
|
|
||||||
#else
|
|
||||||
# define _PLOG_NSTR(x) L##x
|
|
||||||
# define PLOG_NSTR(x) _PLOG_NSTR(x)
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifdef _WIN32
|
|
||||||
# define PLOG_CDECL __cdecl
|
|
||||||
#else
|
|
||||||
# define PLOG_CDECL
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#if __cplusplus >= 201103L || defined(_MSC_VER) && _MSC_VER >= 1700
|
|
||||||
# define PLOG_OVERRIDE override
|
|
||||||
#else
|
|
||||||
# define PLOG_OVERRIDE
|
|
||||||
#endif
|
|
||||||
|
|
||||||
namespace plog
|
|
||||||
{
|
|
||||||
namespace util
|
|
||||||
{
|
|
||||||
#if PLOG_CHAR_IS_UTF8
|
|
||||||
typedef std::string nstring;
|
|
||||||
typedef std::ostringstream nostringstream;
|
|
||||||
typedef std::istringstream nistringstream;
|
|
||||||
typedef std::ostream nostream;
|
|
||||||
typedef char nchar;
|
|
||||||
#else
|
|
||||||
typedef std::wstring nstring;
|
|
||||||
typedef std::wostringstream nostringstream;
|
|
||||||
typedef std::wistringstream nistringstream;
|
|
||||||
typedef std::wostream nostream;
|
|
||||||
typedef wchar_t nchar;
|
|
||||||
#endif
|
|
||||||
|
|
||||||
inline void localtime_s(struct tm* t, const time_t* time)
|
|
||||||
{
|
|
||||||
#if defined(_WIN32) && defined(__BORLANDC__)
|
|
||||||
::localtime_s(time, t);
|
|
||||||
#elif defined(_WIN32) && defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
|
|
||||||
*t = *::localtime(time);
|
|
||||||
#elif defined(_WIN32)
|
|
||||||
::localtime_s(t, time);
|
|
||||||
#else
|
|
||||||
::localtime_r(time, t);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
inline void gmtime_s(struct tm* t, const time_t* time)
|
|
||||||
{
|
|
||||||
#if defined(_WIN32) && defined(__BORLANDC__)
|
|
||||||
::gmtime_s(time, t);
|
|
||||||
#elif defined(_WIN32) && defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
|
|
||||||
*t = *::gmtime(time);
|
|
||||||
#elif defined(_WIN32)
|
|
||||||
::gmtime_s(t, time);
|
|
||||||
#else
|
|
||||||
::gmtime_r(time, t);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
#ifdef _WIN32
|
|
||||||
typedef timeb Time;
|
|
||||||
|
|
||||||
inline void ftime(Time* t)
|
|
||||||
{
|
|
||||||
::ftime(t);
|
|
||||||
}
|
|
||||||
#else
|
|
||||||
struct Time
|
|
||||||
{
|
|
||||||
time_t time;
|
|
||||||
unsigned short millitm;
|
|
||||||
};
|
|
||||||
|
|
||||||
inline void ftime(Time* t)
|
|
||||||
{
|
|
||||||
timeval tv;
|
|
||||||
::gettimeofday(&tv, NULL);
|
|
||||||
|
|
||||||
t->time = tv.tv_sec;
|
|
||||||
t->millitm = static_cast<unsigned short>(tv.tv_usec / 1000);
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
inline unsigned int gettid()
|
|
||||||
{
|
|
||||||
#if defined(__FREERTOS__) && defined(INCLUDE_xTaskGetCurrentTaskHandle)
|
|
||||||
return static_cast<unsigned int>(reinterpret_cast<uintptr_t>(xTaskGetCurrentTaskHandle()));
|
|
||||||
#elif defined(_WIN32)
|
|
||||||
return GetCurrentThreadId();
|
|
||||||
#elif defined(__linux__)
|
|
||||||
return static_cast<unsigned int>(::syscall(__NR_gettid));
|
|
||||||
#elif defined(__FreeBSD__)
|
|
||||||
long tid;
|
|
||||||
syscall(SYS_thr_self, &tid);
|
|
||||||
return static_cast<unsigned int>(tid);
|
|
||||||
#elif defined(__rtems__)
|
|
||||||
return rtems_task_self();
|
|
||||||
#elif defined(__APPLE__)
|
|
||||||
uint64_t tid64;
|
|
||||||
pthread_threadid_np(NULL, &tid64);
|
|
||||||
return static_cast<unsigned int>(tid64);
|
|
||||||
#else
|
|
||||||
return 0;
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
#ifndef _GNU_SOURCE
|
|
||||||
inline int vasprintf(char** strp, const char* format, va_list ap)
|
|
||||||
{
|
|
||||||
va_list ap_copy;
|
|
||||||
#if defined(_MSC_VER) && _MSC_VER <= 1600
|
|
||||||
ap_copy = ap; // there is no va_copy on Visual Studio 2010
|
|
||||||
#else
|
|
||||||
va_copy(ap_copy, ap);
|
|
||||||
#endif
|
|
||||||
#ifndef __STDC_SECURE_LIB__
|
|
||||||
int charCount = vsnprintf(NULL, 0, format, ap_copy);
|
|
||||||
#else
|
|
||||||
int charCount = _vscprintf(format, ap_copy);
|
|
||||||
#endif
|
|
||||||
va_end(ap_copy);
|
|
||||||
if (charCount < 0)
|
|
||||||
{
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t bufferCharCount = static_cast<size_t>(charCount) + 1;
|
|
||||||
|
|
||||||
char* str = static_cast<char*>(malloc(bufferCharCount));
|
|
||||||
if (!str)
|
|
||||||
{
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
#ifndef __STDC_SECURE_LIB__
|
|
||||||
int retval = vsnprintf(str, bufferCharCount, format, ap);
|
|
||||||
#else
|
|
||||||
int retval = vsnprintf_s(str, bufferCharCount, static_cast<size_t>(-1), format, ap);
|
|
||||||
#endif
|
|
||||||
if (retval < 0)
|
|
||||||
{
|
|
||||||
free(str);
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
*strp = str;
|
|
||||||
return retval;
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifdef _WIN32
|
|
||||||
inline int vaswprintf(wchar_t** strp, const wchar_t* format, va_list ap)
|
|
||||||
{
|
|
||||||
#if defined(__BORLANDC__)
|
|
||||||
int charCount = 0x1000; // there is no _vscwprintf on Borland/Embarcadero
|
|
||||||
#else
|
|
||||||
int charCount = _vscwprintf(format, ap);
|
|
||||||
if (charCount < 0)
|
|
||||||
{
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
size_t bufferCharCount = static_cast<size_t>(charCount) + 1;
|
|
||||||
|
|
||||||
wchar_t* str = static_cast<wchar_t*>(malloc(bufferCharCount * sizeof(wchar_t)));
|
|
||||||
if (!str)
|
|
||||||
{
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
#if defined(__BORLANDC__)
|
|
||||||
int retval = vsnwprintf_s(str, bufferCharCount, format, ap);
|
|
||||||
#elif defined(__MINGW32__) && !defined(__MINGW64_VERSION_MAJOR)
|
|
||||||
int retval = _vsnwprintf(str, bufferCharCount, format, ap);
|
|
||||||
#else
|
|
||||||
int retval = _vsnwprintf_s(str, bufferCharCount, charCount, format, ap);
|
|
||||||
#endif
|
|
||||||
if (retval < 0)
|
|
||||||
{
|
|
||||||
free(str);
|
|
||||||
return -1;
|
|
||||||
}
|
|
||||||
|
|
||||||
*strp = str;
|
|
||||||
return retval;
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
#ifdef _WIN32
|
|
||||||
inline std::wstring toWide(const char* str, UINT cp = codePage::kChar)
|
|
||||||
{
|
|
||||||
size_t len = ::strlen(str);
|
|
||||||
std::wstring wstr(len, 0);
|
|
||||||
|
|
||||||
if (!wstr.empty())
|
|
||||||
{
|
|
||||||
int wlen = MultiByteToWideChar(cp, 0, str, static_cast<int>(len), &wstr[0], static_cast<int>(wstr.size()));
|
|
||||||
wstr.resize(wlen);
|
|
||||||
}
|
|
||||||
|
|
||||||
return wstr;
|
|
||||||
}
|
|
||||||
|
|
||||||
inline std::wstring toWide(const std::string& str, UINT cp = codePage::kChar)
|
|
||||||
{
|
|
||||||
return toWide(str.c_str(), cp);
|
|
||||||
}
|
|
||||||
|
|
||||||
inline const std::wstring& toWide(const std::wstring& str) // do nothing for already wide string
|
|
||||||
{
|
|
||||||
return str;
|
|
||||||
}
|
|
||||||
|
|
||||||
inline std::string toNarrow(const std::wstring& wstr, long page)
|
|
||||||
{
|
|
||||||
int len = WideCharToMultiByte(page, 0, wstr.c_str(), static_cast<int>(wstr.size()), 0, 0, 0, 0);
|
|
||||||
std::string str(len, 0);
|
|
||||||
|
|
||||||
if (!str.empty())
|
|
||||||
{
|
|
||||||
WideCharToMultiByte(page, 0, wstr.c_str(), static_cast<int>(wstr.size()), &str[0], len, 0, 0);
|
|
||||||
}
|
|
||||||
|
|
||||||
return str;
|
|
||||||
}
|
|
||||||
#elif PLOG_ENABLE_WCHAR_INPUT
|
|
||||||
inline std::string toNarrow(const wchar_t* wstr)
|
|
||||||
{
|
|
||||||
size_t wlen = ::wcslen(wstr);
|
|
||||||
std::string str(wlen * sizeof(wchar_t), 0);
|
|
||||||
|
|
||||||
if (!str.empty())
|
|
||||||
{
|
|
||||||
const char* in = reinterpret_cast<const char*>(&wstr[0]);
|
|
||||||
char* out = &str[0];
|
|
||||||
size_t inBytes = wlen * sizeof(wchar_t);
|
|
||||||
size_t outBytes = str.size();
|
|
||||||
|
|
||||||
iconv_t cd = ::iconv_open("UTF-8", "WCHAR_T");
|
|
||||||
::iconv(cd, const_cast<char**>(&in), &inBytes, &out, &outBytes);
|
|
||||||
::iconv_close(cd);
|
|
||||||
|
|
||||||
str.resize(str.size() - outBytes);
|
|
||||||
}
|
|
||||||
|
|
||||||
return str;
|
|
||||||
}
|
|
||||||
#endif
|
|
||||||
|
|
||||||
inline std::string processFuncName(const char* func)
|
|
||||||
{
|
|
||||||
#if (defined(_WIN32) && !defined(__MINGW32__)) || defined(__OBJC__)
|
|
||||||
return std::string(func);
|
|
||||||
#else
|
|
||||||
const char* funcBegin = func;
|
|
||||||
const char* funcEnd = ::strchr(funcBegin, '(');
|
|
||||||
int foundTemplate = 0;
|
|
||||||
|
|
||||||
if (!funcEnd)
|
|
||||||
{
|
|
||||||
return std::string(func);
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const char* i = funcEnd - 1; i >= funcBegin; --i) // search backwards for the first space char
|
|
||||||
{
|
|
||||||
if (*i == '>')
|
|
||||||
{
|
|
||||||
foundTemplate++;
|
|
||||||
}
|
|
||||||
else if (*i == '<')
|
|
||||||
{
|
|
||||||
foundTemplate--;
|
|
||||||
}
|
|
||||||
else if (*i == ' ' && foundTemplate == 0)
|
|
||||||
{
|
|
||||||
funcBegin = i + 1;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
return std::string(funcBegin, funcEnd);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
inline const nchar* findExtensionDot(const nchar* fileName)
|
|
||||||
{
|
|
||||||
#if PLOG_CHAR_IS_UTF8
|
|
||||||
return std::strrchr(fileName, '.');
|
|
||||||
#else
|
|
||||||
return std::wcsrchr(fileName, L'.');
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
inline void splitFileName(const nchar* fileName, nstring& fileNameNoExt, nstring& fileExt)
|
|
||||||
{
|
|
||||||
const nchar* dot = findExtensionDot(fileName);
|
|
||||||
|
|
||||||
if (dot)
|
|
||||||
{
|
|
||||||
fileNameNoExt.assign(fileName, dot);
|
|
||||||
fileExt.assign(dot + 1);
|
|
||||||
}
|
|
||||||
else
|
|
||||||
{
|
|
||||||
fileNameNoExt.assign(fileName);
|
|
||||||
fileExt.clear();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
class PLOG_LINKAGE NonCopyable
|
|
||||||
{
|
|
||||||
protected:
|
|
||||||
NonCopyable()
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
NonCopyable(const NonCopyable&);
|
|
||||||
NonCopyable& operator=(const NonCopyable&);
|
|
||||||
};
|
|
||||||
|
|
||||||
class PLOG_LINKAGE_HIDDEN File : NonCopyable
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
File() : m_file(-1)
|
|
||||||
{
|
|
||||||
}
|
|
||||||
|
|
||||||
~File()
|
|
||||||
{
|
|
||||||
close();
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t open(const nstring& fileName)
|
|
||||||
{
|
|
||||||
#if defined(_WIN32) && (defined(__BORLANDC__) || defined(__MINGW32__))
|
|
||||||
m_file = ::_wsopen(toWide(fileName).c_str(), _O_CREAT | _O_WRONLY | _O_BINARY | _O_NOINHERIT, SH_DENYWR, _S_IREAD | _S_IWRITE);
|
|
||||||
#elif defined(_WIN32)
|
|
||||||
::_wsopen_s(&m_file, toWide(fileName).c_str(), _O_CREAT | _O_WRONLY | _O_BINARY | _O_NOINHERIT, _SH_DENYWR, _S_IREAD | _S_IWRITE);
|
|
||||||
#elif defined(O_CLOEXEC)
|
|
||||||
m_file = ::open(fileName.c_str(), O_CREAT | O_APPEND | O_WRONLY | O_CLOEXEC, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
|
|
||||||
#else
|
|
||||||
m_file = ::open(fileName.c_str(), O_CREAT | O_APPEND | O_WRONLY, S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH);
|
|
||||||
#endif
|
|
||||||
return seek(0, SEEK_END);
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t write(const void* buf, size_t count)
|
|
||||||
{
|
|
||||||
return m_file != -1 ? static_cast<size_t>(
|
|
||||||
#ifdef _WIN32
|
|
||||||
::_write(m_file, buf, static_cast<unsigned int>(count))
|
|
||||||
#else
|
|
||||||
::write(m_file, buf, count)
|
|
||||||
#endif
|
|
||||||
) : static_cast<size_t>(-1);
|
|
||||||
}
|
|
||||||
|
|
||||||
template<class CharType>
|
|
||||||
size_t write(const std::basic_string<CharType>& str)
|
|
||||||
{
|
|
||||||
return write(str.data(), str.size() * sizeof(CharType));
|
|
||||||
}
|
|
||||||
|
|
||||||
size_t seek(size_t offset, int whence)
|
|
||||||
{
|
|
||||||
return m_file != -1 ? static_cast<size_t>(
|
|
||||||
#if defined(_WIN32) && (defined(__BORLANDC__) || defined(__MINGW32__))
|
|
||||||
::_lseek(m_file, static_cast<off_t>(offset), whence)
|
|
||||||
#elif defined(_WIN32)
|
|
||||||
::_lseeki64(m_file, static_cast<off_t>(offset), whence)
|
|
||||||
#else
|
|
||||||
::lseek(m_file, static_cast<off_t>(offset), whence)
|
|
||||||
#endif
|
|
||||||
) : static_cast<size_t>(-1);
|
|
||||||
}
|
|
||||||
|
|
||||||
void close()
|
|
||||||
{
|
|
||||||
if (m_file != -1)
|
|
||||||
{
|
|
||||||
#ifdef _WIN32
|
|
||||||
::_close(m_file);
|
|
||||||
#else
|
|
||||||
::close(m_file);
|
|
||||||
#endif
|
|
||||||
m_file = -1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
static int unlink(const nstring& fileName)
|
|
||||||
{
|
|
||||||
#ifdef _WIN32
|
|
||||||
return ::_wunlink(toWide(fileName).c_str());
|
|
||||||
#else
|
|
||||||
return ::unlink(fileName.c_str());
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
static int rename(const nstring& oldFilename, const nstring& newFilename)
|
|
||||||
{
|
|
||||||
#ifdef _WIN32
|
|
||||||
return MoveFileW(toWide(oldFilename).c_str(), toWide(newFilename).c_str());
|
|
||||||
#else
|
|
||||||
return ::rename(oldFilename.c_str(), newFilename.c_str());
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
int m_file;
|
|
||||||
};
|
|
||||||
|
|
||||||
class PLOG_LINKAGE_HIDDEN Mutex : NonCopyable
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
Mutex()
|
|
||||||
{
|
|
||||||
#ifdef __FREERTOS__
|
|
||||||
m_sync = xSemaphoreCreateBinary();
|
|
||||||
xSemaphoreGive(m_sync);
|
|
||||||
#elif defined(_WIN32)
|
|
||||||
InitializeCriticalSection(&m_sync);
|
|
||||||
#elif defined(__rtems__)
|
|
||||||
rtems_semaphore_create(0, 1,
|
|
||||||
RTEMS_PRIORITY |
|
|
||||||
RTEMS_BINARY_SEMAPHORE |
|
|
||||||
RTEMS_INHERIT_PRIORITY, 1, &m_sync);
|
|
||||||
#elif defined(_POSIX_THREADS)
|
|
||||||
::pthread_mutex_init(&m_sync, 0);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
~Mutex()
|
|
||||||
{
|
|
||||||
#ifdef __FREERTOS__
|
|
||||||
vSemaphoreDelete(m_sync);
|
|
||||||
#elif defined(_WIN32)
|
|
||||||
DeleteCriticalSection(&m_sync);
|
|
||||||
#elif defined(__rtems__)
|
|
||||||
rtems_semaphore_delete(m_sync);
|
|
||||||
#elif defined(_POSIX_THREADS)
|
|
||||||
::pthread_mutex_destroy(&m_sync);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
friend class MutexLock;
|
|
||||||
|
|
||||||
private:
|
|
||||||
void lock()
|
|
||||||
{
|
|
||||||
#ifdef __FREERTOS__
|
|
||||||
xSemaphoreTake(m_sync, portMAX_DELAY);
|
|
||||||
#elif defined(_WIN32)
|
|
||||||
EnterCriticalSection(&m_sync);
|
|
||||||
#elif defined(__rtems__)
|
|
||||||
rtems_semaphore_obtain(m_sync, RTEMS_WAIT, RTEMS_NO_TIMEOUT);
|
|
||||||
#elif defined(_POSIX_THREADS)
|
|
||||||
::pthread_mutex_lock(&m_sync);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
void unlock()
|
|
||||||
{
|
|
||||||
#ifdef __FREERTOS__
|
|
||||||
xSemaphoreGive(m_sync);
|
|
||||||
#elif defined(_WIN32)
|
|
||||||
LeaveCriticalSection(&m_sync);
|
|
||||||
#elif defined(__rtems__)
|
|
||||||
rtems_semaphore_release(m_sync);
|
|
||||||
#elif defined(_POSIX_THREADS)
|
|
||||||
::pthread_mutex_unlock(&m_sync);
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
#ifdef __FREERTOS__
|
|
||||||
SemaphoreHandle_t m_sync;
|
|
||||||
#elif defined(_WIN32)
|
|
||||||
CRITICAL_SECTION m_sync;
|
|
||||||
#elif defined(__rtems__)
|
|
||||||
rtems_id m_sync;
|
|
||||||
#elif defined(_POSIX_THREADS)
|
|
||||||
pthread_mutex_t m_sync;
|
|
||||||
#endif
|
|
||||||
};
|
|
||||||
|
|
||||||
class PLOG_LINKAGE_HIDDEN MutexLock : NonCopyable
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
MutexLock(Mutex& mutex) : m_mutex(mutex)
|
|
||||||
{
|
|
||||||
m_mutex.lock();
|
|
||||||
}
|
|
||||||
|
|
||||||
~MutexLock()
|
|
||||||
{
|
|
||||||
m_mutex.unlock();
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
Mutex& m_mutex;
|
|
||||||
};
|
|
||||||
|
|
||||||
template<class T>
|
|
||||||
#ifdef _WIN32
|
|
||||||
class Singleton : NonCopyable
|
|
||||||
#else
|
|
||||||
class PLOG_LINKAGE Singleton : NonCopyable
|
|
||||||
#endif
|
|
||||||
{
|
|
||||||
public:
|
|
||||||
#if (defined(__clang__) || defined(__GNUC__) && __GNUC__ >= 8) && !defined(__BORLANDC__)
|
|
||||||
// This constructor is called before the `T` object is fully constructed, and
|
|
||||||
// pointers are not dereferenced anyway, so UBSan shouldn't check vptrs.
|
|
||||||
__attribute__((no_sanitize("vptr")))
|
|
||||||
#endif
|
|
||||||
Singleton()
|
|
||||||
{
|
|
||||||
assert(!m_instance);
|
|
||||||
m_instance = static_cast<T*>(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
~Singleton()
|
|
||||||
{
|
|
||||||
assert(m_instance);
|
|
||||||
m_instance = 0;
|
|
||||||
}
|
|
||||||
|
|
||||||
static T* getInstance()
|
|
||||||
{
|
|
||||||
return m_instance;
|
|
||||||
}
|
|
||||||
|
|
||||||
private:
|
|
||||||
static T* m_instance;
|
|
||||||
};
|
|
||||||
|
|
||||||
template<class T>
|
|
||||||
T* Singleton<T>::m_instance = NULL;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -1,175 +0,0 @@
|
|||||||
#pragma once
|
|
||||||
|
|
||||||
#ifdef _WIN32
|
|
||||||
|
|
||||||
// These windows structs must be in a global namespace
|
|
||||||
struct HKEY__;
|
|
||||||
struct _SECURITY_ATTRIBUTES;
|
|
||||||
struct _CONSOLE_SCREEN_BUFFER_INFO;
|
|
||||||
struct _RTL_CRITICAL_SECTION;
|
|
||||||
|
|
||||||
namespace plog
|
|
||||||
{
|
|
||||||
typedef unsigned long DWORD;
|
|
||||||
typedef unsigned short WORD;
|
|
||||||
typedef unsigned char BYTE;
|
|
||||||
typedef unsigned int UINT;
|
|
||||||
typedef int BOOL;
|
|
||||||
typedef long LSTATUS;
|
|
||||||
typedef char* LPSTR;
|
|
||||||
typedef wchar_t* LPWSTR;
|
|
||||||
typedef const char* LPCSTR;
|
|
||||||
typedef const wchar_t* LPCWSTR;
|
|
||||||
typedef void* HANDLE;
|
|
||||||
typedef HKEY__* HKEY;
|
|
||||||
typedef size_t ULONG_PTR;
|
|
||||||
|
|
||||||
struct CRITICAL_SECTION
|
|
||||||
{
|
|
||||||
void* DebugInfo;
|
|
||||||
long LockCount;
|
|
||||||
long RecursionCount;
|
|
||||||
HANDLE OwningThread;
|
|
||||||
HANDLE LockSemaphore;
|
|
||||||
ULONG_PTR SpinCount;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct COORD
|
|
||||||
{
|
|
||||||
short X;
|
|
||||||
short Y;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct SMALL_RECT
|
|
||||||
{
|
|
||||||
short Left;
|
|
||||||
short Top;
|
|
||||||
short Right;
|
|
||||||
short Bottom;
|
|
||||||
};
|
|
||||||
|
|
||||||
struct CONSOLE_SCREEN_BUFFER_INFO
|
|
||||||
{
|
|
||||||
COORD dwSize;
|
|
||||||
COORD dwCursorPosition;
|
|
||||||
WORD wAttributes;
|
|
||||||
SMALL_RECT srWindow;
|
|
||||||
COORD dwMaximumWindowSize;
|
|
||||||
};
|
|
||||||
|
|
||||||
namespace codePage
|
|
||||||
{
|
|
||||||
const UINT kActive = 0;
|
|
||||||
const UINT kUTF8 = 65001;
|
|
||||||
#if PLOG_CHAR_IS_UTF8
|
|
||||||
const UINT kChar = kUTF8;
|
|
||||||
#else
|
|
||||||
const UINT kChar = kActive;
|
|
||||||
#endif
|
|
||||||
}
|
|
||||||
|
|
||||||
namespace eventLog
|
|
||||||
{
|
|
||||||
const WORD kErrorType = 0x0001;
|
|
||||||
const WORD kWarningType = 0x0002;
|
|
||||||
const WORD kInformationType = 0x0004;
|
|
||||||
}
|
|
||||||
|
|
||||||
namespace hkey
|
|
||||||
{
|
|
||||||
const HKEY kLocalMachine = reinterpret_cast<HKEY>(static_cast<ULONG_PTR>(0x80000002));
|
|
||||||
}
|
|
||||||
|
|
||||||
namespace regSam
|
|
||||||
{
|
|
||||||
const DWORD kQueryValue = 0x0001;
|
|
||||||
const DWORD kSetValue = 0x0002;
|
|
||||||
}
|
|
||||||
|
|
||||||
namespace regType
|
|
||||||
{
|
|
||||||
const DWORD kExpandSz = 2;
|
|
||||||
const DWORD kDword = 4;
|
|
||||||
}
|
|
||||||
|
|
||||||
namespace stdHandle
|
|
||||||
{
|
|
||||||
const DWORD kOutput = static_cast<DWORD>(-11);
|
|
||||||
const DWORD kErrorOutput = static_cast<DWORD>(-12);
|
|
||||||
}
|
|
||||||
|
|
||||||
namespace foreground
|
|
||||||
{
|
|
||||||
const WORD kBlue = 0x0001;
|
|
||||||
const WORD kGreen = 0x0002;
|
|
||||||
const WORD kRed = 0x0004;
|
|
||||||
const WORD kIntensity = 0x0008;
|
|
||||||
}
|
|
||||||
|
|
||||||
namespace background
|
|
||||||
{
|
|
||||||
const WORD kBlue = 0x0010;
|
|
||||||
const WORD kGreen = 0x0020;
|
|
||||||
const WORD kRed = 0x0040;
|
|
||||||
const WORD kIntensity = 0x0080;
|
|
||||||
}
|
|
||||||
|
|
||||||
extern "C"
|
|
||||||
{
|
|
||||||
__declspec(dllimport) int __stdcall MultiByteToWideChar(UINT CodePage, DWORD dwFlags, LPCSTR lpMultiByteStr, int cbMultiByte, LPWSTR lpWideCharStr, int cchWideChar);
|
|
||||||
__declspec(dllimport) int __stdcall WideCharToMultiByte(UINT CodePage, DWORD dwFlags, LPCWSTR lpWideCharStr, int cchWideChar, LPSTR lpMultiByteStr, int cbMultiByte, const char* lpDefaultChar, BOOL* lpUsedDefaultChar);
|
|
||||||
|
|
||||||
__declspec(dllimport) DWORD __stdcall GetCurrentThreadId();
|
|
||||||
|
|
||||||
__declspec(dllimport) BOOL __stdcall MoveFileW(LPCWSTR lpExistingFileName, LPCWSTR lpNewFileName);
|
|
||||||
|
|
||||||
__declspec(dllimport) void __stdcall InitializeCriticalSection(_RTL_CRITICAL_SECTION* lpCriticalSection);
|
|
||||||
__declspec(dllimport) void __stdcall EnterCriticalSection(_RTL_CRITICAL_SECTION* lpCriticalSection);
|
|
||||||
__declspec(dllimport) void __stdcall LeaveCriticalSection(_RTL_CRITICAL_SECTION* lpCriticalSection);
|
|
||||||
__declspec(dllimport) void __stdcall DeleteCriticalSection(_RTL_CRITICAL_SECTION* lpCriticalSection);
|
|
||||||
|
|
||||||
__declspec(dllimport) HANDLE __stdcall RegisterEventSourceW(LPCWSTR lpUNCServerName, LPCWSTR lpSourceName);
|
|
||||||
__declspec(dllimport) BOOL __stdcall DeregisterEventSource(HANDLE hEventLog);
|
|
||||||
__declspec(dllimport) BOOL __stdcall ReportEventW(HANDLE hEventLog, WORD wType, WORD wCategory, DWORD dwEventID, void* lpUserSid, WORD wNumStrings, DWORD dwDataSize, LPCWSTR* lpStrings, void* lpRawData);
|
|
||||||
|
|
||||||
__declspec(dllimport) LSTATUS __stdcall RegCreateKeyExW(HKEY hKey, LPCWSTR lpSubKey, DWORD Reserved, LPWSTR lpClass, DWORD dwOptions, DWORD samDesired, _SECURITY_ATTRIBUTES* lpSecurityAttributes, HKEY* phkResult, DWORD* lpdwDisposition);
|
|
||||||
__declspec(dllimport) LSTATUS __stdcall RegSetValueExW(HKEY hKey, LPCWSTR lpValueName, DWORD Reserved, DWORD dwType, const BYTE* lpData, DWORD cbData);
|
|
||||||
__declspec(dllimport) LSTATUS __stdcall RegCloseKey(HKEY hKey);
|
|
||||||
__declspec(dllimport) LSTATUS __stdcall RegOpenKeyExW(HKEY hKey, LPCWSTR lpSubKey, DWORD ulOptions, DWORD samDesired, HKEY* phkResult);
|
|
||||||
__declspec(dllimport) LSTATUS __stdcall RegDeleteKeyW(HKEY hKey, LPCWSTR lpSubKey);
|
|
||||||
|
|
||||||
__declspec(dllimport) HANDLE __stdcall GetStdHandle(DWORD nStdHandle);
|
|
||||||
|
|
||||||
__declspec(dllimport) BOOL __stdcall WriteConsoleW(HANDLE hConsoleOutput, const void* lpBuffer, DWORD nNumberOfCharsToWrite, DWORD* lpNumberOfCharsWritten, void* lpReserved);
|
|
||||||
__declspec(dllimport) BOOL __stdcall GetConsoleScreenBufferInfo(HANDLE hConsoleOutput, _CONSOLE_SCREEN_BUFFER_INFO* lpConsoleScreenBufferInfo);
|
|
||||||
__declspec(dllimport) BOOL __stdcall SetConsoleTextAttribute(HANDLE hConsoleOutput, WORD wAttributes);
|
|
||||||
|
|
||||||
__declspec(dllimport) void __stdcall OutputDebugStringW(LPCWSTR lpOutputString);
|
|
||||||
}
|
|
||||||
|
|
||||||
inline void InitializeCriticalSection(CRITICAL_SECTION* criticalSection)
|
|
||||||
{
|
|
||||||
plog::InitializeCriticalSection(reinterpret_cast<_RTL_CRITICAL_SECTION*>(criticalSection));
|
|
||||||
}
|
|
||||||
|
|
||||||
inline void EnterCriticalSection(CRITICAL_SECTION* criticalSection)
|
|
||||||
{
|
|
||||||
plog::EnterCriticalSection(reinterpret_cast<_RTL_CRITICAL_SECTION*>(criticalSection));
|
|
||||||
}
|
|
||||||
|
|
||||||
inline void LeaveCriticalSection(CRITICAL_SECTION* criticalSection)
|
|
||||||
{
|
|
||||||
plog::LeaveCriticalSection(reinterpret_cast<_RTL_CRITICAL_SECTION*>(criticalSection));
|
|
||||||
}
|
|
||||||
|
|
||||||
inline void DeleteCriticalSection(CRITICAL_SECTION* criticalSection)
|
|
||||||
{
|
|
||||||
plog::DeleteCriticalSection(reinterpret_cast<_RTL_CRITICAL_SECTION*>(criticalSection));
|
|
||||||
}
|
|
||||||
|
|
||||||
inline BOOL GetConsoleScreenBufferInfo(HANDLE consoleOutput, CONSOLE_SCREEN_BUFFER_INFO* consoleScreenBufferInfo)
|
|
||||||
{
|
|
||||||
return plog::GetConsoleScreenBufferInfo(consoleOutput, reinterpret_cast<_CONSOLE_SCREEN_BUFFER_INFO*>(consoleScreenBufferInfo));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
#endif // _WIN32
|
|
||||||
@@ -0,0 +1,99 @@
|
|||||||
|
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||||
|
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
//
|
||||||
|
// Async logging using global thread pool
|
||||||
|
// All loggers created here share same global thread pool.
|
||||||
|
// Each log message is pushed to a queue along with a shared pointer to the
|
||||||
|
// logger.
|
||||||
|
// If a logger deleted while having pending messages in the queue, it's actual
|
||||||
|
// destruction will defer
|
||||||
|
// until all its messages are processed by the thread pool.
|
||||||
|
// This is because each message in the queue holds a shared_ptr to the
|
||||||
|
// originating logger.
|
||||||
|
|
||||||
|
#include <spdlog/async_logger.h>
|
||||||
|
#include <spdlog/details/registry.h>
|
||||||
|
#include <spdlog/details/thread_pool.h>
|
||||||
|
|
||||||
|
#include <functional>
|
||||||
|
#include <memory>
|
||||||
|
#include <mutex>
|
||||||
|
|
||||||
|
namespace spdlog {
|
||||||
|
|
||||||
|
namespace details {
|
||||||
|
static const size_t default_async_q_size = 8192;
|
||||||
|
}
|
||||||
|
|
||||||
|
// async logger factory - creates async loggers backed with thread pool.
|
||||||
|
// if a global thread pool doesn't already exist, create it with default queue
|
||||||
|
// size of 8192 items and single thread.
|
||||||
|
template <async_overflow_policy OverflowPolicy = async_overflow_policy::block>
|
||||||
|
struct async_factory_impl {
|
||||||
|
template <typename Sink, typename... SinkArgs>
|
||||||
|
static std::shared_ptr<async_logger> create(std::string logger_name, SinkArgs &&...args) {
|
||||||
|
auto ®istry_inst = details::registry::instance();
|
||||||
|
|
||||||
|
// create global thread pool if not already exists..
|
||||||
|
|
||||||
|
auto &mutex = registry_inst.tp_mutex();
|
||||||
|
std::lock_guard<std::recursive_mutex> tp_lock(mutex);
|
||||||
|
auto tp = registry_inst.get_tp();
|
||||||
|
if (tp == nullptr) {
|
||||||
|
tp = std::make_shared<details::thread_pool>(details::default_async_q_size, 1U);
|
||||||
|
registry_inst.set_tp(tp);
|
||||||
|
}
|
||||||
|
|
||||||
|
auto sink = std::make_shared<Sink>(std::forward<SinkArgs>(args)...);
|
||||||
|
auto new_logger = std::make_shared<async_logger>(std::move(logger_name), std::move(sink),
|
||||||
|
std::move(tp), OverflowPolicy);
|
||||||
|
registry_inst.initialize_logger(new_logger);
|
||||||
|
return new_logger;
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
using async_factory = async_factory_impl<async_overflow_policy::block>;
|
||||||
|
using async_factory_nonblock = async_factory_impl<async_overflow_policy::overrun_oldest>;
|
||||||
|
|
||||||
|
template <typename Sink, typename... SinkArgs>
|
||||||
|
inline std::shared_ptr<spdlog::logger> create_async(std::string logger_name,
|
||||||
|
SinkArgs &&...sink_args) {
|
||||||
|
return async_factory::create<Sink>(std::move(logger_name),
|
||||||
|
std::forward<SinkArgs>(sink_args)...);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename Sink, typename... SinkArgs>
|
||||||
|
inline std::shared_ptr<spdlog::logger> create_async_nb(std::string logger_name,
|
||||||
|
SinkArgs &&...sink_args) {
|
||||||
|
return async_factory_nonblock::create<Sink>(std::move(logger_name),
|
||||||
|
std::forward<SinkArgs>(sink_args)...);
|
||||||
|
}
|
||||||
|
|
||||||
|
// set global thread pool.
|
||||||
|
inline void init_thread_pool(size_t q_size,
|
||||||
|
size_t thread_count,
|
||||||
|
std::function<void()> on_thread_start,
|
||||||
|
std::function<void()> on_thread_stop) {
|
||||||
|
auto tp = std::make_shared<details::thread_pool>(q_size, thread_count, on_thread_start,
|
||||||
|
on_thread_stop);
|
||||||
|
details::registry::instance().set_tp(std::move(tp));
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void init_thread_pool(size_t q_size,
|
||||||
|
size_t thread_count,
|
||||||
|
std::function<void()> on_thread_start) {
|
||||||
|
init_thread_pool(q_size, thread_count, on_thread_start, [] {});
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void init_thread_pool(size_t q_size, size_t thread_count) {
|
||||||
|
init_thread_pool(q_size, thread_count, [] {}, [] {});
|
||||||
|
}
|
||||||
|
|
||||||
|
// get the global thread pool.
|
||||||
|
inline std::shared_ptr<spdlog::details::thread_pool> thread_pool() {
|
||||||
|
return details::registry::instance().get_tp();
|
||||||
|
}
|
||||||
|
} // namespace spdlog
|
||||||
@@ -0,0 +1,84 @@
|
|||||||
|
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||||
|
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#ifndef SPDLOG_HEADER_ONLY
|
||||||
|
#include <spdlog/async_logger.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include <spdlog/details/thread_pool.h>
|
||||||
|
#include <spdlog/sinks/sink.h>
|
||||||
|
|
||||||
|
#include <memory>
|
||||||
|
#include <string>
|
||||||
|
|
||||||
|
SPDLOG_INLINE spdlog::async_logger::async_logger(std::string logger_name,
|
||||||
|
sinks_init_list sinks_list,
|
||||||
|
std::weak_ptr<details::thread_pool> tp,
|
||||||
|
async_overflow_policy overflow_policy)
|
||||||
|
: async_logger(std::move(logger_name),
|
||||||
|
sinks_list.begin(),
|
||||||
|
sinks_list.end(),
|
||||||
|
std::move(tp),
|
||||||
|
overflow_policy) {}
|
||||||
|
|
||||||
|
SPDLOG_INLINE spdlog::async_logger::async_logger(std::string logger_name,
|
||||||
|
sink_ptr single_sink,
|
||||||
|
std::weak_ptr<details::thread_pool> tp,
|
||||||
|
async_overflow_policy overflow_policy)
|
||||||
|
: async_logger(
|
||||||
|
std::move(logger_name), {std::move(single_sink)}, std::move(tp), overflow_policy) {}
|
||||||
|
|
||||||
|
// send the log message to the thread pool
|
||||||
|
SPDLOG_INLINE void spdlog::async_logger::sink_it_(const details::log_msg &msg){
|
||||||
|
SPDLOG_TRY{if (auto pool_ptr = thread_pool_.lock()){
|
||||||
|
pool_ptr -> post_log(shared_from_this(), msg, overflow_policy_);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
throw_spdlog_ex("async log: thread pool doesn't exist anymore");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
SPDLOG_LOGGER_CATCH(msg.source)
|
||||||
|
}
|
||||||
|
|
||||||
|
// send flush request to the thread pool
|
||||||
|
SPDLOG_INLINE void spdlog::async_logger::flush_(){
|
||||||
|
SPDLOG_TRY{if (auto pool_ptr = thread_pool_.lock()){
|
||||||
|
pool_ptr -> post_flush(shared_from_this(), overflow_policy_);
|
||||||
|
}
|
||||||
|
else {
|
||||||
|
throw_spdlog_ex("async flush: thread pool doesn't exist anymore");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
SPDLOG_LOGGER_CATCH(source_loc())
|
||||||
|
}
|
||||||
|
|
||||||
|
//
|
||||||
|
// backend functions - called from the thread pool to do the actual job
|
||||||
|
//
|
||||||
|
SPDLOG_INLINE void spdlog::async_logger::backend_sink_it_(const details::log_msg &msg) {
|
||||||
|
for (auto &sink : sinks_) {
|
||||||
|
if (sink->should_log(msg.level)) {
|
||||||
|
SPDLOG_TRY { sink->log(msg); }
|
||||||
|
SPDLOG_LOGGER_CATCH(msg.source)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if (should_flush_(msg)) {
|
||||||
|
backend_flush_();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
SPDLOG_INLINE void spdlog::async_logger::backend_flush_() {
|
||||||
|
for (auto &sink : sinks_) {
|
||||||
|
SPDLOG_TRY { sink->flush(); }
|
||||||
|
SPDLOG_LOGGER_CATCH(source_loc())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
SPDLOG_INLINE std::shared_ptr<spdlog::logger> spdlog::async_logger::clone(std::string new_name) {
|
||||||
|
auto cloned = std::make_shared<spdlog::async_logger>(*this);
|
||||||
|
cloned->name_ = std::move(new_name);
|
||||||
|
return cloned;
|
||||||
|
}
|
||||||
@@ -0,0 +1,74 @@
|
|||||||
|
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||||
|
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
// Fast asynchronous logger.
|
||||||
|
// Uses pre allocated queue.
|
||||||
|
// Creates a single back thread to pop messages from the queue and log them.
|
||||||
|
//
|
||||||
|
// Upon each log write the logger:
|
||||||
|
// 1. Checks if its log level is enough to log the message
|
||||||
|
// 2. Push a new copy of the message to a queue (or block the caller until
|
||||||
|
// space is available in the queue)
|
||||||
|
// Upon destruction, logs all remaining messages in the queue before
|
||||||
|
// destructing..
|
||||||
|
|
||||||
|
#include <spdlog/logger.h>
|
||||||
|
|
||||||
|
namespace spdlog {
|
||||||
|
|
||||||
|
// Async overflow policy - block by default.
|
||||||
|
enum class async_overflow_policy {
|
||||||
|
block, // Block until message can be enqueued
|
||||||
|
overrun_oldest, // Discard oldest message in the queue if full when trying to
|
||||||
|
// add new item.
|
||||||
|
discard_new // Discard new message if the queue is full when trying to add new item.
|
||||||
|
};
|
||||||
|
|
||||||
|
namespace details {
|
||||||
|
class thread_pool;
|
||||||
|
}
|
||||||
|
|
||||||
|
class SPDLOG_API async_logger final : public std::enable_shared_from_this<async_logger>,
|
||||||
|
public logger {
|
||||||
|
friend class details::thread_pool;
|
||||||
|
|
||||||
|
public:
|
||||||
|
template <typename It>
|
||||||
|
async_logger(std::string logger_name,
|
||||||
|
It begin,
|
||||||
|
It end,
|
||||||
|
std::weak_ptr<details::thread_pool> tp,
|
||||||
|
async_overflow_policy overflow_policy = async_overflow_policy::block)
|
||||||
|
: logger(std::move(logger_name), begin, end),
|
||||||
|
thread_pool_(std::move(tp)),
|
||||||
|
overflow_policy_(overflow_policy) {}
|
||||||
|
|
||||||
|
async_logger(std::string logger_name,
|
||||||
|
sinks_init_list sinks_list,
|
||||||
|
std::weak_ptr<details::thread_pool> tp,
|
||||||
|
async_overflow_policy overflow_policy = async_overflow_policy::block);
|
||||||
|
|
||||||
|
async_logger(std::string logger_name,
|
||||||
|
sink_ptr single_sink,
|
||||||
|
std::weak_ptr<details::thread_pool> tp,
|
||||||
|
async_overflow_policy overflow_policy = async_overflow_policy::block);
|
||||||
|
|
||||||
|
std::shared_ptr<logger> clone(std::string new_name) override;
|
||||||
|
|
||||||
|
protected:
|
||||||
|
void sink_it_(const details::log_msg &msg) override;
|
||||||
|
void flush_() override;
|
||||||
|
void backend_sink_it_(const details::log_msg &incoming_log_msg);
|
||||||
|
void backend_flush_();
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::weak_ptr<details::thread_pool> thread_pool_;
|
||||||
|
async_overflow_policy overflow_policy_;
|
||||||
|
};
|
||||||
|
} // namespace spdlog
|
||||||
|
|
||||||
|
#ifdef SPDLOG_HEADER_ONLY
|
||||||
|
#include "async_logger-inl.h"
|
||||||
|
#endif
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||||
|
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
#include <spdlog/cfg/helpers.h>
|
||||||
|
#include <spdlog/details/registry.h>
|
||||||
|
|
||||||
|
//
|
||||||
|
// Init log levels using each argv entry that starts with "SPDLOG_LEVEL="
|
||||||
|
//
|
||||||
|
// set all loggers to debug level:
|
||||||
|
// example.exe "SPDLOG_LEVEL=debug"
|
||||||
|
|
||||||
|
// set logger1 to trace level
|
||||||
|
// example.exe "SPDLOG_LEVEL=logger1=trace"
|
||||||
|
|
||||||
|
// turn off all logging except for logger1 and logger2:
|
||||||
|
// example.exe "SPDLOG_LEVEL=off,logger1=debug,logger2=info"
|
||||||
|
|
||||||
|
namespace spdlog {
|
||||||
|
namespace cfg {
|
||||||
|
|
||||||
|
// search for SPDLOG_LEVEL= in the args and use it to init the levels
|
||||||
|
inline void load_argv_levels(int argc, const char **argv) {
|
||||||
|
const std::string spdlog_level_prefix = "SPDLOG_LEVEL=";
|
||||||
|
for (int i = 1; i < argc; i++) {
|
||||||
|
std::string arg = argv[i];
|
||||||
|
if (arg.find(spdlog_level_prefix) == 0) {
|
||||||
|
auto levels_string = arg.substr(spdlog_level_prefix.size());
|
||||||
|
helpers::load_levels(levels_string);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
inline void load_argv_levels(int argc, char **argv) {
|
||||||
|
load_argv_levels(argc, const_cast<const char **>(argv));
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace cfg
|
||||||
|
} // namespace spdlog
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||||
|
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
#include <spdlog/cfg/helpers.h>
|
||||||
|
#include <spdlog/details/os.h>
|
||||||
|
#include <spdlog/details/registry.h>
|
||||||
|
|
||||||
|
//
|
||||||
|
// Init levels and patterns from env variables SPDLOG_LEVEL
|
||||||
|
// Inspired from Rust's "env_logger" crate (https://crates.io/crates/env_logger).
|
||||||
|
// Note - fallback to "info" level on unrecognized levels
|
||||||
|
//
|
||||||
|
// Examples:
|
||||||
|
//
|
||||||
|
// set global level to debug:
|
||||||
|
// export SPDLOG_LEVEL=debug
|
||||||
|
//
|
||||||
|
// turn off all logging except for logger1:
|
||||||
|
// export SPDLOG_LEVEL="*=off,logger1=debug"
|
||||||
|
//
|
||||||
|
|
||||||
|
// turn off all logging except for logger1 and logger2:
|
||||||
|
// export SPDLOG_LEVEL="off,logger1=debug,logger2=info"
|
||||||
|
|
||||||
|
namespace spdlog {
|
||||||
|
namespace cfg {
|
||||||
|
inline void load_env_levels(const char* var = "SPDLOG_LEVEL") {
|
||||||
|
auto env_val = details::os::getenv(var);
|
||||||
|
if (!env_val.empty()) {
|
||||||
|
helpers::load_levels(env_val);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace cfg
|
||||||
|
} // namespace spdlog
|
||||||
@@ -0,0 +1,106 @@
|
|||||||
|
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||||
|
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#ifndef SPDLOG_HEADER_ONLY
|
||||||
|
#include <spdlog/cfg/helpers.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include <spdlog/details/os.h>
|
||||||
|
#include <spdlog/details/registry.h>
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <sstream>
|
||||||
|
#include <string>
|
||||||
|
#include <utility>
|
||||||
|
|
||||||
|
namespace spdlog {
|
||||||
|
namespace cfg {
|
||||||
|
namespace helpers {
|
||||||
|
|
||||||
|
// inplace convert to lowercase
|
||||||
|
inline std::string &to_lower_(std::string &str) {
|
||||||
|
std::transform(str.begin(), str.end(), str.begin(), [](char ch) {
|
||||||
|
return static_cast<char>((ch >= 'A' && ch <= 'Z') ? ch + ('a' - 'A') : ch);
|
||||||
|
});
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
|
||||||
|
// inplace trim spaces
|
||||||
|
inline std::string &trim_(std::string &str) {
|
||||||
|
const char *spaces = " \n\r\t";
|
||||||
|
str.erase(str.find_last_not_of(spaces) + 1);
|
||||||
|
str.erase(0, str.find_first_not_of(spaces));
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
|
||||||
|
// return (name,value) trimmed pair from the given "name = value" string.
|
||||||
|
// return empty string on missing parts
|
||||||
|
// "key=val" => ("key", "val")
|
||||||
|
// " key = val " => ("key", "val")
|
||||||
|
// "key=" => ("key", "")
|
||||||
|
// "val" => ("", "val")
|
||||||
|
|
||||||
|
inline std::pair<std::string, std::string> extract_kv_(char sep, const std::string &str) {
|
||||||
|
auto n = str.find(sep);
|
||||||
|
std::string k, v;
|
||||||
|
if (n == std::string::npos) {
|
||||||
|
v = str;
|
||||||
|
} else {
|
||||||
|
k = str.substr(0, n);
|
||||||
|
v = str.substr(n + 1);
|
||||||
|
}
|
||||||
|
return std::make_pair(trim_(k), trim_(v));
|
||||||
|
}
|
||||||
|
|
||||||
|
// return vector of key/value pairs from a sequence of "K1=V1,K2=V2,.."
|
||||||
|
// "a=AAA,b=BBB,c=CCC,.." => {("a","AAA"),("b","BBB"),("c", "CCC"),...}
|
||||||
|
inline std::unordered_map<std::string, std::string> extract_key_vals_(const std::string &str) {
|
||||||
|
std::string token;
|
||||||
|
std::istringstream token_stream(str);
|
||||||
|
std::unordered_map<std::string, std::string> rv{};
|
||||||
|
while (std::getline(token_stream, token, ',')) {
|
||||||
|
if (token.empty()) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
auto kv = extract_kv_('=', token);
|
||||||
|
rv[kv.first] = kv.second;
|
||||||
|
}
|
||||||
|
return rv;
|
||||||
|
}
|
||||||
|
|
||||||
|
SPDLOG_INLINE void load_levels(const std::string &input) {
|
||||||
|
if (input.empty() || input.size() >= 32768) {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
auto key_vals = extract_key_vals_(input);
|
||||||
|
std::unordered_map<std::string, level::level_enum> levels;
|
||||||
|
level::level_enum global_level = level::info;
|
||||||
|
bool global_level_found = false;
|
||||||
|
|
||||||
|
for (auto &name_level : key_vals) {
|
||||||
|
const auto &logger_name = name_level.first;
|
||||||
|
const auto &level_name = to_lower_(name_level.second);
|
||||||
|
auto level = level::from_str(level_name);
|
||||||
|
// ignore unrecognized level names
|
||||||
|
if (level == level::off && level_name != "off") {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if (logger_name.empty()) // no logger name indicates global level
|
||||||
|
{
|
||||||
|
global_level_found = true;
|
||||||
|
global_level = level;
|
||||||
|
} else {
|
||||||
|
levels[logger_name] = level;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
details::registry::instance().set_levels(std::move(levels),
|
||||||
|
global_level_found ? &global_level : nullptr);
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace helpers
|
||||||
|
} // namespace cfg
|
||||||
|
} // namespace spdlog
|
||||||
@@ -0,0 +1,29 @@
|
|||||||
|
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||||
|
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <spdlog/common.h>
|
||||||
|
#include <unordered_map>
|
||||||
|
|
||||||
|
namespace spdlog {
|
||||||
|
namespace cfg {
|
||||||
|
namespace helpers {
|
||||||
|
//
|
||||||
|
// Init levels from given string
|
||||||
|
//
|
||||||
|
// Examples:
|
||||||
|
//
|
||||||
|
// set global level to debug: "debug"
|
||||||
|
// turn off all logging except for logger1: "off,logger1=debug"
|
||||||
|
// turn off all logging except for logger1 and logger2: "off,logger1=debug,logger2=info"
|
||||||
|
//
|
||||||
|
SPDLOG_API void load_levels(const std::string &txt);
|
||||||
|
} // namespace helpers
|
||||||
|
|
||||||
|
} // namespace cfg
|
||||||
|
} // namespace spdlog
|
||||||
|
|
||||||
|
#ifdef SPDLOG_HEADER_ONLY
|
||||||
|
#include "helpers-inl.h"
|
||||||
|
#endif // SPDLOG_HEADER_ONLY
|
||||||
@@ -0,0 +1,68 @@
|
|||||||
|
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||||
|
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#ifndef SPDLOG_HEADER_ONLY
|
||||||
|
#include <spdlog/common.h>
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#include <algorithm>
|
||||||
|
#include <iterator>
|
||||||
|
|
||||||
|
namespace spdlog {
|
||||||
|
namespace level {
|
||||||
|
|
||||||
|
#if __cplusplus >= 201703L
|
||||||
|
constexpr
|
||||||
|
#endif
|
||||||
|
static string_view_t level_string_views[] SPDLOG_LEVEL_NAMES;
|
||||||
|
|
||||||
|
static const char *short_level_names[] SPDLOG_SHORT_LEVEL_NAMES;
|
||||||
|
|
||||||
|
SPDLOG_INLINE const string_view_t &to_string_view(spdlog::level::level_enum l) SPDLOG_NOEXCEPT {
|
||||||
|
return level_string_views[l];
|
||||||
|
}
|
||||||
|
|
||||||
|
SPDLOG_INLINE const char *to_short_c_str(spdlog::level::level_enum l) SPDLOG_NOEXCEPT {
|
||||||
|
return short_level_names[l];
|
||||||
|
}
|
||||||
|
|
||||||
|
SPDLOG_INLINE spdlog::level::level_enum from_str(const std::string &name) SPDLOG_NOEXCEPT {
|
||||||
|
auto it = std::find(std::begin(level_string_views), std::end(level_string_views), name);
|
||||||
|
if (it != std::end(level_string_views))
|
||||||
|
return static_cast<level::level_enum>(std::distance(std::begin(level_string_views), it));
|
||||||
|
|
||||||
|
// check also for "warn" and "err" before giving up..
|
||||||
|
if (name == "warn") {
|
||||||
|
return level::warn;
|
||||||
|
}
|
||||||
|
if (name == "err") {
|
||||||
|
return level::err;
|
||||||
|
}
|
||||||
|
return level::off;
|
||||||
|
}
|
||||||
|
} // namespace level
|
||||||
|
|
||||||
|
SPDLOG_INLINE spdlog_ex::spdlog_ex(std::string msg)
|
||||||
|
: msg_(std::move(msg)) {}
|
||||||
|
|
||||||
|
SPDLOG_INLINE spdlog_ex::spdlog_ex(const std::string &msg, int last_errno) {
|
||||||
|
#ifdef SPDLOG_USE_STD_FORMAT
|
||||||
|
msg_ = std::system_error(std::error_code(last_errno, std::generic_category()), msg).what();
|
||||||
|
#else
|
||||||
|
memory_buf_t outbuf;
|
||||||
|
fmt::format_system_error(outbuf, last_errno, msg.c_str());
|
||||||
|
msg_ = fmt::to_string(outbuf);
|
||||||
|
#endif
|
||||||
|
}
|
||||||
|
|
||||||
|
SPDLOG_INLINE const char *spdlog_ex::what() const SPDLOG_NOEXCEPT { return msg_.c_str(); }
|
||||||
|
|
||||||
|
SPDLOG_INLINE void throw_spdlog_ex(const std::string &msg, int last_errno) {
|
||||||
|
SPDLOG_THROW(spdlog_ex(msg, last_errno));
|
||||||
|
}
|
||||||
|
|
||||||
|
SPDLOG_INLINE void throw_spdlog_ex(std::string msg) { SPDLOG_THROW(spdlog_ex(std::move(msg))); }
|
||||||
|
|
||||||
|
} // namespace spdlog
|
||||||
@@ -0,0 +1,406 @@
|
|||||||
|
// Copyright(c) 2015-present, Gabi Melman & spdlog contributors.
|
||||||
|
// Distributed under the MIT License (http://opensource.org/licenses/MIT)
|
||||||
|
|
||||||
|
#pragma once
|
||||||
|
|
||||||
|
#include <spdlog/details/null_mutex.h>
|
||||||
|
#include <spdlog/tweakme.h>
|
||||||
|
|
||||||
|
#include <atomic>
|
||||||
|
#include <chrono>
|
||||||
|
#include <cstdio>
|
||||||
|
#include <exception>
|
||||||
|
#include <functional>
|
||||||
|
#include <initializer_list>
|
||||||
|
#include <memory>
|
||||||
|
#include <string>
|
||||||
|
#include <type_traits>
|
||||||
|
|
||||||
|
#ifdef SPDLOG_USE_STD_FORMAT
|
||||||
|
#include <version>
|
||||||
|
#if __cpp_lib_format >= 202207L
|
||||||
|
#include <format>
|
||||||
|
#else
|
||||||
|
#include <string_view>
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef SPDLOG_COMPILED_LIB
|
||||||
|
#undef SPDLOG_HEADER_ONLY
|
||||||
|
#if defined(SPDLOG_SHARED_LIB)
|
||||||
|
#if defined(_WIN32)
|
||||||
|
#ifdef spdlog_EXPORTS
|
||||||
|
#define SPDLOG_API __declspec(dllexport)
|
||||||
|
#else // !spdlog_EXPORTS
|
||||||
|
#define SPDLOG_API __declspec(dllimport)
|
||||||
|
#endif
|
||||||
|
#else // !defined(_WIN32)
|
||||||
|
#define SPDLOG_API __attribute__((visibility("default")))
|
||||||
|
#endif
|
||||||
|
#else // !defined(SPDLOG_SHARED_LIB)
|
||||||
|
#define SPDLOG_API
|
||||||
|
#endif
|
||||||
|
#define SPDLOG_INLINE
|
||||||
|
#else // !defined(SPDLOG_COMPILED_LIB)
|
||||||
|
#define SPDLOG_API
|
||||||
|
#define SPDLOG_HEADER_ONLY
|
||||||
|
#define SPDLOG_INLINE inline
|
||||||
|
#endif // #ifdef SPDLOG_COMPILED_LIB
|
||||||
|
|
||||||
|
#include <spdlog/fmt/fmt.h>
|
||||||
|
|
||||||
|
#if !defined(SPDLOG_USE_STD_FORMAT) && \
|
||||||
|
FMT_VERSION >= 80000 // backward compatibility with fmt versions older than 8
|
||||||
|
#define SPDLOG_FMT_RUNTIME(format_string) fmt::runtime(format_string)
|
||||||
|
#define SPDLOG_FMT_STRING(format_string) FMT_STRING(format_string)
|
||||||
|
#if defined(SPDLOG_WCHAR_FILENAMES) || defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT)
|
||||||
|
#include <spdlog/fmt/xchar.h>
|
||||||
|
#endif
|
||||||
|
#else
|
||||||
|
#define SPDLOG_FMT_RUNTIME(format_string) format_string
|
||||||
|
#define SPDLOG_FMT_STRING(format_string) format_string
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// visual studio up to 2013 does not support noexcept nor constexpr
|
||||||
|
#if defined(_MSC_VER) && (_MSC_VER < 1900)
|
||||||
|
#define SPDLOG_NOEXCEPT _NOEXCEPT
|
||||||
|
#define SPDLOG_CONSTEXPR
|
||||||
|
#else
|
||||||
|
#define SPDLOG_NOEXCEPT noexcept
|
||||||
|
#define SPDLOG_CONSTEXPR constexpr
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// If building with std::format, can just use constexpr, otherwise if building with fmt
|
||||||
|
// SPDLOG_CONSTEXPR_FUNC needs to be set the same as FMT_CONSTEXPR to avoid situations where
|
||||||
|
// a constexpr function in spdlog could end up calling a non-constexpr function in fmt
|
||||||
|
// depending on the compiler
|
||||||
|
// If fmt determines it can't use constexpr, we should inline the function instead
|
||||||
|
#ifdef SPDLOG_USE_STD_FORMAT
|
||||||
|
#define SPDLOG_CONSTEXPR_FUNC constexpr
|
||||||
|
#else // Being built with fmt
|
||||||
|
#if FMT_USE_CONSTEXPR
|
||||||
|
#define SPDLOG_CONSTEXPR_FUNC FMT_CONSTEXPR
|
||||||
|
#else
|
||||||
|
#define SPDLOG_CONSTEXPR_FUNC inline
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(__GNUC__) || defined(__clang__)
|
||||||
|
#define SPDLOG_DEPRECATED __attribute__((deprecated))
|
||||||
|
#elif defined(_MSC_VER)
|
||||||
|
#define SPDLOG_DEPRECATED __declspec(deprecated)
|
||||||
|
#else
|
||||||
|
#define SPDLOG_DEPRECATED
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// disable thread local on msvc 2013
|
||||||
|
#ifndef SPDLOG_NO_TLS
|
||||||
|
#if (defined(_MSC_VER) && (_MSC_VER < 1900)) || defined(__cplusplus_winrt)
|
||||||
|
#define SPDLOG_NO_TLS 1
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifndef SPDLOG_FUNCTION
|
||||||
|
#define SPDLOG_FUNCTION static_cast<const char *>(__FUNCTION__)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef SPDLOG_NO_EXCEPTIONS
|
||||||
|
#define SPDLOG_TRY
|
||||||
|
#define SPDLOG_THROW(ex) \
|
||||||
|
do { \
|
||||||
|
printf("spdlog fatal error: %s\n", ex.what()); \
|
||||||
|
std::abort(); \
|
||||||
|
} while (0)
|
||||||
|
#define SPDLOG_CATCH_STD
|
||||||
|
#else
|
||||||
|
#define SPDLOG_TRY try
|
||||||
|
#define SPDLOG_THROW(ex) throw(ex)
|
||||||
|
#define SPDLOG_CATCH_STD \
|
||||||
|
catch (const std::exception &) { \
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
namespace spdlog {
|
||||||
|
|
||||||
|
class formatter;
|
||||||
|
|
||||||
|
namespace sinks {
|
||||||
|
class sink;
|
||||||
|
}
|
||||||
|
|
||||||
|
#if defined(_WIN32) && defined(SPDLOG_WCHAR_FILENAMES)
|
||||||
|
using filename_t = std::wstring;
|
||||||
|
// allow macro expansion to occur in SPDLOG_FILENAME_T
|
||||||
|
#define SPDLOG_FILENAME_T_INNER(s) L##s
|
||||||
|
#define SPDLOG_FILENAME_T(s) SPDLOG_FILENAME_T_INNER(s)
|
||||||
|
#else
|
||||||
|
using filename_t = std::string;
|
||||||
|
#define SPDLOG_FILENAME_T(s) s
|
||||||
|
#endif
|
||||||
|
|
||||||
|
using log_clock = std::chrono::system_clock;
|
||||||
|
using sink_ptr = std::shared_ptr<sinks::sink>;
|
||||||
|
using sinks_init_list = std::initializer_list<sink_ptr>;
|
||||||
|
using err_handler = std::function<void(const std::string &err_msg)>;
|
||||||
|
#ifdef SPDLOG_USE_STD_FORMAT
|
||||||
|
namespace fmt_lib = std;
|
||||||
|
|
||||||
|
using string_view_t = std::string_view;
|
||||||
|
using memory_buf_t = std::string;
|
||||||
|
|
||||||
|
template <typename... Args>
|
||||||
|
#if __cpp_lib_format >= 202207L
|
||||||
|
using format_string_t = std::format_string<Args...>;
|
||||||
|
#else
|
||||||
|
using format_string_t = std::string_view;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
template <class T, class Char = char>
|
||||||
|
struct is_convertible_to_basic_format_string
|
||||||
|
: std::integral_constant<bool, std::is_convertible<T, std::basic_string_view<Char>>::value> {};
|
||||||
|
|
||||||
|
#if defined(SPDLOG_WCHAR_FILENAMES) || defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT)
|
||||||
|
using wstring_view_t = std::wstring_view;
|
||||||
|
using wmemory_buf_t = std::wstring;
|
||||||
|
|
||||||
|
template <typename... Args>
|
||||||
|
#if __cpp_lib_format >= 202207L
|
||||||
|
using wformat_string_t = std::wformat_string<Args...>;
|
||||||
|
#else
|
||||||
|
using wformat_string_t = std::wstring_view;
|
||||||
|
#endif
|
||||||
|
#endif
|
||||||
|
#define SPDLOG_BUF_TO_STRING(x) x
|
||||||
|
#else // use fmt lib instead of std::format
|
||||||
|
namespace fmt_lib = fmt;
|
||||||
|
|
||||||
|
using string_view_t = fmt::basic_string_view<char>;
|
||||||
|
using memory_buf_t = fmt::basic_memory_buffer<char, 250>;
|
||||||
|
|
||||||
|
template <typename... Args>
|
||||||
|
using format_string_t = fmt::format_string<Args...>;
|
||||||
|
|
||||||
|
template <class T>
|
||||||
|
using remove_cvref_t = typename std::remove_cv<typename std::remove_reference<T>::type>::type;
|
||||||
|
|
||||||
|
template <typename Char>
|
||||||
|
#if FMT_VERSION >= 90101
|
||||||
|
using fmt_runtime_string = fmt::runtime_format_string<Char>;
|
||||||
|
#else
|
||||||
|
using fmt_runtime_string = fmt::basic_runtime<Char>;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// clang doesn't like SFINAE disabled constructor in std::is_convertible<> so have to repeat the
|
||||||
|
// condition from basic_format_string here, in addition, fmt::basic_runtime<Char> is only
|
||||||
|
// convertible to basic_format_string<Char> but not basic_string_view<Char>
|
||||||
|
template <class T, class Char = char>
|
||||||
|
struct is_convertible_to_basic_format_string
|
||||||
|
: std::integral_constant<bool,
|
||||||
|
std::is_convertible<T, fmt::basic_string_view<Char>>::value ||
|
||||||
|
std::is_same<remove_cvref_t<T>, fmt_runtime_string<Char>>::value> {
|
||||||
|
};
|
||||||
|
|
||||||
|
#if defined(SPDLOG_WCHAR_FILENAMES) || defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT)
|
||||||
|
using wstring_view_t = fmt::basic_string_view<wchar_t>;
|
||||||
|
using wmemory_buf_t = fmt::basic_memory_buffer<wchar_t, 250>;
|
||||||
|
|
||||||
|
template <typename... Args>
|
||||||
|
using wformat_string_t = fmt::wformat_string<Args...>;
|
||||||
|
#endif
|
||||||
|
#define SPDLOG_BUF_TO_STRING(x) fmt::to_string(x)
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#ifdef SPDLOG_WCHAR_TO_UTF8_SUPPORT
|
||||||
|
#ifndef _WIN32
|
||||||
|
#error SPDLOG_WCHAR_TO_UTF8_SUPPORT only supported on windows
|
||||||
|
#endif // _WIN32
|
||||||
|
#endif // SPDLOG_WCHAR_TO_UTF8_SUPPORT
|
||||||
|
|
||||||
|
template <class T>
|
||||||
|
struct is_convertible_to_any_format_string
|
||||||
|
: std::integral_constant<bool,
|
||||||
|
is_convertible_to_basic_format_string<T, char>::value ||
|
||||||
|
is_convertible_to_basic_format_string<T, wchar_t>::value> {};
|
||||||
|
|
||||||
|
#if defined(SPDLOG_NO_ATOMIC_LEVELS)
|
||||||
|
using level_t = details::null_atomic_int;
|
||||||
|
#else
|
||||||
|
using level_t = std::atomic<int>;
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#define SPDLOG_LEVEL_TRACE 0
|
||||||
|
#define SPDLOG_LEVEL_DEBUG 1
|
||||||
|
#define SPDLOG_LEVEL_INFO 2
|
||||||
|
#define SPDLOG_LEVEL_WARN 3
|
||||||
|
#define SPDLOG_LEVEL_ERROR 4
|
||||||
|
#define SPDLOG_LEVEL_CRITICAL 5
|
||||||
|
#define SPDLOG_LEVEL_OFF 6
|
||||||
|
|
||||||
|
#if !defined(SPDLOG_ACTIVE_LEVEL)
|
||||||
|
#define SPDLOG_ACTIVE_LEVEL SPDLOG_LEVEL_INFO
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// Log level enum
|
||||||
|
namespace level {
|
||||||
|
enum level_enum : int {
|
||||||
|
trace = SPDLOG_LEVEL_TRACE,
|
||||||
|
debug = SPDLOG_LEVEL_DEBUG,
|
||||||
|
info = SPDLOG_LEVEL_INFO,
|
||||||
|
warn = SPDLOG_LEVEL_WARN,
|
||||||
|
err = SPDLOG_LEVEL_ERROR,
|
||||||
|
critical = SPDLOG_LEVEL_CRITICAL,
|
||||||
|
off = SPDLOG_LEVEL_OFF,
|
||||||
|
n_levels
|
||||||
|
};
|
||||||
|
|
||||||
|
#define SPDLOG_LEVEL_NAME_TRACE spdlog::string_view_t("trace", 5)
|
||||||
|
#define SPDLOG_LEVEL_NAME_DEBUG spdlog::string_view_t("debug", 5)
|
||||||
|
#define SPDLOG_LEVEL_NAME_INFO spdlog::string_view_t("info", 4)
|
||||||
|
#define SPDLOG_LEVEL_NAME_WARNING spdlog::string_view_t("warning", 7)
|
||||||
|
#define SPDLOG_LEVEL_NAME_ERROR spdlog::string_view_t("error", 5)
|
||||||
|
#define SPDLOG_LEVEL_NAME_CRITICAL spdlog::string_view_t("critical", 8)
|
||||||
|
#define SPDLOG_LEVEL_NAME_OFF spdlog::string_view_t("off", 3)
|
||||||
|
|
||||||
|
#if !defined(SPDLOG_LEVEL_NAMES)
|
||||||
|
#define SPDLOG_LEVEL_NAMES \
|
||||||
|
{ \
|
||||||
|
SPDLOG_LEVEL_NAME_TRACE, SPDLOG_LEVEL_NAME_DEBUG, SPDLOG_LEVEL_NAME_INFO, \
|
||||||
|
SPDLOG_LEVEL_NAME_WARNING, SPDLOG_LEVEL_NAME_ERROR, SPDLOG_LEVEL_NAME_CRITICAL, \
|
||||||
|
SPDLOG_LEVEL_NAME_OFF \
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if !defined(SPDLOG_SHORT_LEVEL_NAMES)
|
||||||
|
|
||||||
|
#define SPDLOG_SHORT_LEVEL_NAMES \
|
||||||
|
{ "T", "D", "I", "W", "E", "C", "O" }
|
||||||
|
#endif
|
||||||
|
|
||||||
|
SPDLOG_API const string_view_t &to_string_view(spdlog::level::level_enum l) SPDLOG_NOEXCEPT;
|
||||||
|
SPDLOG_API const char *to_short_c_str(spdlog::level::level_enum l) SPDLOG_NOEXCEPT;
|
||||||
|
SPDLOG_API spdlog::level::level_enum from_str(const std::string &name) SPDLOG_NOEXCEPT;
|
||||||
|
|
||||||
|
} // namespace level
|
||||||
|
|
||||||
|
//
|
||||||
|
// Color mode used by sinks with color support.
|
||||||
|
//
|
||||||
|
enum class color_mode { always, automatic, never };
|
||||||
|
|
||||||
|
//
|
||||||
|
// Pattern time - specific time getting to use for pattern_formatter.
|
||||||
|
// local time by default
|
||||||
|
//
|
||||||
|
enum class pattern_time_type {
|
||||||
|
local, // log localtime
|
||||||
|
utc // log utc
|
||||||
|
};
|
||||||
|
|
||||||
|
//
|
||||||
|
// Log exception
|
||||||
|
//
|
||||||
|
class SPDLOG_API spdlog_ex : public std::exception {
|
||||||
|
public:
|
||||||
|
explicit spdlog_ex(std::string msg);
|
||||||
|
spdlog_ex(const std::string &msg, int last_errno);
|
||||||
|
const char *what() const SPDLOG_NOEXCEPT override;
|
||||||
|
|
||||||
|
private:
|
||||||
|
std::string msg_;
|
||||||
|
};
|
||||||
|
|
||||||
|
[[noreturn]] SPDLOG_API void throw_spdlog_ex(const std::string &msg, int last_errno);
|
||||||
|
[[noreturn]] SPDLOG_API void throw_spdlog_ex(std::string msg);
|
||||||
|
|
||||||
|
struct source_loc {
|
||||||
|
SPDLOG_CONSTEXPR source_loc() = default;
|
||||||
|
SPDLOG_CONSTEXPR source_loc(const char *filename_in, int line_in, const char *funcname_in)
|
||||||
|
: filename{filename_in},
|
||||||
|
line{line_in},
|
||||||
|
funcname{funcname_in} {}
|
||||||
|
|
||||||
|
SPDLOG_CONSTEXPR bool empty() const SPDLOG_NOEXCEPT { return line <= 0; }
|
||||||
|
const char *filename{nullptr};
|
||||||
|
int line{0};
|
||||||
|
const char *funcname{nullptr};
|
||||||
|
};
|
||||||
|
|
||||||
|
struct file_event_handlers {
|
||||||
|
file_event_handlers()
|
||||||
|
: before_open(nullptr),
|
||||||
|
after_open(nullptr),
|
||||||
|
before_close(nullptr),
|
||||||
|
after_close(nullptr) {}
|
||||||
|
|
||||||
|
std::function<void(const filename_t &filename)> before_open;
|
||||||
|
std::function<void(const filename_t &filename, std::FILE *file_stream)> after_open;
|
||||||
|
std::function<void(const filename_t &filename, std::FILE *file_stream)> before_close;
|
||||||
|
std::function<void(const filename_t &filename)> after_close;
|
||||||
|
};
|
||||||
|
|
||||||
|
namespace details {
|
||||||
|
|
||||||
|
// to_string_view
|
||||||
|
|
||||||
|
SPDLOG_CONSTEXPR_FUNC spdlog::string_view_t to_string_view(const memory_buf_t &buf)
|
||||||
|
SPDLOG_NOEXCEPT {
|
||||||
|
return spdlog::string_view_t{buf.data(), buf.size()};
|
||||||
|
}
|
||||||
|
|
||||||
|
SPDLOG_CONSTEXPR_FUNC spdlog::string_view_t to_string_view(spdlog::string_view_t str)
|
||||||
|
SPDLOG_NOEXCEPT {
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
|
||||||
|
#if defined(SPDLOG_WCHAR_FILENAMES) || defined(SPDLOG_WCHAR_TO_UTF8_SUPPORT)
|
||||||
|
SPDLOG_CONSTEXPR_FUNC spdlog::wstring_view_t to_string_view(const wmemory_buf_t &buf)
|
||||||
|
SPDLOG_NOEXCEPT {
|
||||||
|
return spdlog::wstring_view_t{buf.data(), buf.size()};
|
||||||
|
}
|
||||||
|
|
||||||
|
SPDLOG_CONSTEXPR_FUNC spdlog::wstring_view_t to_string_view(spdlog::wstring_view_t str)
|
||||||
|
SPDLOG_NOEXCEPT {
|
||||||
|
return str;
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
#if defined(SPDLOG_USE_STD_FORMAT) && __cpp_lib_format >= 202207L
|
||||||
|
template <typename T, typename... Args>
|
||||||
|
SPDLOG_CONSTEXPR_FUNC std::basic_string_view<T> to_string_view(
|
||||||
|
std::basic_format_string<T, Args...> fmt) SPDLOG_NOEXCEPT {
|
||||||
|
return fmt.get();
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// make_unique support for pre c++14
|
||||||
|
#if __cplusplus >= 201402L // C++14 and beyond
|
||||||
|
using std::enable_if_t;
|
||||||
|
using std::make_unique;
|
||||||
|
#else
|
||||||
|
template <bool B, class T = void>
|
||||||
|
using enable_if_t = typename std::enable_if<B, T>::type;
|
||||||
|
|
||||||
|
template <typename T, typename... Args>
|
||||||
|
std::unique_ptr<T> make_unique(Args &&...args) {
|
||||||
|
static_assert(!std::is_array<T>::value, "arrays not supported");
|
||||||
|
return std::unique_ptr<T>(new T(std::forward<Args>(args)...));
|
||||||
|
}
|
||||||
|
#endif
|
||||||
|
|
||||||
|
// to avoid useless casts (see https://github.com/nlohmann/json/issues/2893#issuecomment-889152324)
|
||||||
|
template <typename T, typename U, enable_if_t<!std::is_same<T, U>::value, int> = 0>
|
||||||
|
constexpr T conditional_static_cast(U value) {
|
||||||
|
return static_cast<T>(value);
|
||||||
|
}
|
||||||
|
|
||||||
|
template <typename T, typename U, enable_if_t<std::is_same<T, U>::value, int> = 0>
|
||||||
|
constexpr T conditional_static_cast(U value) {
|
||||||
|
return value;
|
||||||
|
}
|
||||||
|
|
||||||
|
} // namespace details
|
||||||
|
} // namespace spdlog
|
||||||
|
|
||||||
|
#ifdef SPDLOG_HEADER_ONLY
|
||||||
|
#include "common-inl.h"
|
||||||
|
#endif
|
||||||
Loaded 100 of 328 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user