Compare commits

..
6 Commits
Author SHA1 Message Date
xiaozhou233 6eb1925ec3 Feat: add Linux libloader entry point
- libloader: add platform/linux/Entry.cpp that starts the loader from a constructor
- libloader: read the config path from JuiceAgent_ConfigPath, falling back to $HOME/.juiceagent
- libloader: default JuiceAgentNativeLibraryPath to libagent.so on non-Windows
- injector: print a notice that the Linux injector is not open source yet
2026-10-18 22:32:14 +08:00
xiaozhou233 59e705510e BugFix: restore ReflectiveDLLInjection link for libloader
- cmake: link ReflectiveDLLInjection into loader on Windows again; the platform split dropped it when jvm moved into the WIN32 branch
2026-10-18 19:18:04 +08:00
xiaozhou233 c548022068 Feat: add Linux build support scaffolding
- cmake: guard Windows-only link dir and projects (ReflectiveDLLInjection, libinject)
- agent/loader: select win32 or linux JVM headers by platform, link jvm only on Windows
- loader: glob platform/linux sources for non-Windows builds
- injector: add a Linux entry point stub selected on non-Windows
- jvm: vendor Linux jni_md.h and jawt_md.h
2026-10-18 19:12:31 +08:00
xiaozhou233 6a43b3437a BugFix: fix playload typo in retransform-class example [skip ci]
- examples: rename playload to payload (directory, class, jar, config, docs)

- payload.jar: rebuild with payload.class
2026-10-17 13:21:42 +08:00
xiaozhou233 8cd4c54c07 Docs: add QuickStartForAgents.md [skip ci]
- docs: add the agent-facing quick start (environment check, requirements, config.toml, injection, verification)
- readme: point new users at the agent guide and show how to prompt an agent
- readme-zh: mirror the same note in Chinese
2026-10-16 20:44:24 +08:00
xiaozhou233 3796cca9a1 Docs: add AGENTS.md [skip ci]
- document the build/test/release flow for agents working in this repo

- record the hard-won rules: libloader must stay exception-free (reflective loading breaks unwind), config reads are non-throwing, no MinGW runtime DLL deps, and tests must be asserted on output
2026-10-16 13:14:09 +08:00
24 changed files with 933 additions and 75 deletions

No files matched your search

+210
View File
@@ -0,0 +1,210 @@
# AGENTS.md
Guidance for AI coding agents (and humans) working in this repository.
## Project at a glance
JuiceAgent is a JVMTI-based runtime injection framework for Windows. It injects
into a running JVM (even with `DisableAttachMechanism=true`, no `-javaagent`),
loads a JAR and calls an entry point, and exposes native APIs to
redefine/retransform classes, query loaded classes and read bytecode.
Four binaries:
| Target | Output | Role |
| --- | --- | --- |
| `injector` | `injector.exe` | CLI driver: loads `libinject.dll` and injects `libloader.dll` into a target PID |
| `libinject` | `libinject.dll` | Reflective DLL injector (exports `inject`, plus JNI bindings) |
| `libloader` | `libloader.dll` | **Reflectively loaded** into the target JVM. Attaches to the JVM, reads `config.toml`, registers the embedded JuiceAgent-API jar, bootstraps the agent |
| `libagent` | `libagent.dll` | The JVMTI agent. Registers `ClassFileLoadHook` and implements the native side of the JuiceAgent-API |
## Toolchain
- Windows x64, MinGW-w64 GCC (the maintainer uses [w64devkit](https://github.com/skeeto/w64devkit)), Ninja, CMake 3.15+
- C++20
- JDK 17+ for the Java side. `--enable-native-access=ALL-UNNAMED` is required from
JDK 22 on to keep `System.load` warning-free (a future JDK will deny native
access without it).
## Build
```powershell
cmake --preset release # or: --preset debug
cmake --build build
```
Binaries land in `build/bin`.
Alternatively, without presets:
```powershell
cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release
cmake --build build
```
## Test
Integration tests live in `tests/`. They are plain `main()` programs (not JUnit)
that `System.load("resources/libagent.dll")` and call `JuiceAgent.init("")`.
Two of them need the `injection` module compiled into `out/production/injection`.
Build first, then:
```powershell
pwsh tests/run-tests.ps1
# or point it at a specific JDK:
pwsh tests/run-tests.ps1 -JdkHome "C:\Program Files\Zulu\zulu-25"
```
The runner compiles the modules, refreshes `tests/resources` from `build/bin`
(via `tests/copy-bin.bat`), compiles the tests, then runs every test and
**asserts on its output**.
> Running the tests rebuilds the tracked file `tests/injection.jar`. After a local
> run, restore it with `git checkout -- tests/injection.jar` before committing.
## Release
1. Bump `Version.txt` (`Major` / `Minor` / `Patch`).
2. Add `docs/update/vX.Y.Z.md` (bilingual release notes) and an entry in
`docs/update/CHANGELOG.md`.
3. Commit the docs, then commit `Version X.Y.Z`, then tag `vX.Y.Z`.
4. Build the package and attach it to a GitHub Release:
```powershell
cmake -P script/package.cmake # -> dist/JuiceAgent_vX.Y.Z_x64.zip
```
(`script/package.bat` wraps this but ends with `pause`.)
`tests/`, `build/`, `dist/` and `*.log` are gitignored; `dist/*.zip` is **not**
committed.
## Hard rules (each of these was learned by breaking the build or a target JVM)
### 1. `libloader` must never throw a C++ exception
`libloader.dll` is loaded by a **reflective loader (manual mapping)**, so its
unwind tables are never registered with the OS. A C++ exception thrown inside it
**cannot be unwound or caught** - it crashes the target JVM with
`EXCEPTION_ILLEGAL_INSTRUCTION` (a `try/catch` there is useless, not a fix).
- The `loader` target is compiled with `-fno-exceptions` (and
`SPDLOG_NO_EXCEPTIONS`) on purpose: any exception-capable code fails the build.
- Report problems with `spdlog` + an early `return`, never with `throw`.
- This also means library code that can throw (`toml::parse_file`,
`std::filesystem`, allocations) must be used in a non-throwing way. toml++
switches to the non-throwing `toml::parse_result` API automatically when
exceptions are disabled.
### 2. Config reads are non-throwing
`includes/JuiceAgent/Config.hpp` intentionally has **no throwing getters**. Use:
```cpp
if (!cfg.contains("JarLoader.Mode")) { spdlog::error("Missing key: JarLoader.Mode"); return; }
const std::string mode = cfg.get<std::string>("JarLoader.Mode", "");
```
For required values, check `contains()` first and then `get(path, default)`.
### 3. Config schema changes are a coordinated edit
The current schema is v2 (`CONFIG_VERSION` in `includes/JuiceAgent/JuiceAgent.hpp`).
It is validated at load time, so a mismatch makes the loader refuse to start.
Changing the schema requires updating, together:
- `CONFIG_VERSION`
- `docs/config.md`
- the three `examples/*/config.toml`
- the config block in `README.md` **and** `README_ZH.md`
### 4. Keep the MinGW runtime out of the shipped DLLs
Do not introduce a dependency on `libstdc++-6.dll` / `libgcc_s_seh-1.dll` /
`libwinpthread-1.dll`. A DLL that needs them can pick up an incompatible copy
from elsewhere on the machine and fail to load (`UnsatisfiedLinkError: The
specified procedure could not be found`). w64devkit links the runtime statically;
CI passes `-static-libgcc -static-libstdc++` to match.
### 5. Tests assert on output, not exit codes
The test programs print diagnostics and **still exit 0** when a step fails. Match
an expected marker (e.g. `Bytes: 399`, `Modified!`, `Injection Invoked!`) -
checking `$LASTEXITCODE` alone will silently pass broken builds.
Notes when adding tests:
- `GetClassBytesByName` only resolves **already loaded** classes; load the target
first (`Class.forName("Target")`).
- Tests that print to stderr make Windows PowerShell 5.1 unhappy; the runner sets
`$ErrorActionPreference = "Continue"` and relies on explicit checks.
## Layout
```
src/injector injector.exe
src/libinject libinject.dll (reflective injector)
src/libloader libloader.dll (runs in the target; exception-free)
src/libagent libagent.dll (JVMTI agent)
services/ IService implementations, self-registered via JUICEAGENT_REGISTER_SERVICE
includes/eventbus.hpp typed EventBus
includes/JuiceAgent Config.hpp / Logger.hpp / Utils.hpp / JuiceAgent.hpp (CONFIG_VERSION)
includes/toml++ vendored
includes/spdlog vendored
tests/ integration tests + run-tests.ps1 + copy-bin.bat
docs/ config.md, advanced.md, Inject.md, update/ (release notes + changelog)
examples/ runnable end-to-end examples (each has config.toml + HowToUse)
script/ package.cmake / package.bat
```
## Conventions
### Services and the event bus
A service derives from `IService` (`src/libagent/includes/services/base.hpp`) and
self-registers at file scope:
```cpp
JUICEAGENT_REGISTER_SERVICE(::JuiceAgent::Services::MyService)
```
Subscribe with the typed bus - there is no `EventId` and no `void*` casting:
```cpp
listen<MyService, EventLoaded>(&MyService::onLoaded); // append
listenFront<MyService, EventLoaded>(&MyService::onLoaded); // run before others
```
Publish with `EventBus::getInstance().post(event)`. Call `unlistenAll()` in
`onShutdown()`.
### Commit messages
`Type: subject`, then `- component: detail` bullets. Types used here:
`Feat`, `BugFix`, `Refactor`, `Docs`, `CI`, and `Version X.Y.Z` for the release
commit.
### Docs
`README.md` and `README_ZH.md` are kept in sync; keep both updated. Prose docs
live in `docs/` (English). Release notes and the changelog live in `docs/update/`.
### Line endings
Tracked text files are **LF in the index, CRLF in the working tree** (no
`.gitattributes`). When creating files, write CRLF to avoid noisy diffs.
## CI
`.github/workflows/ci.yml` runs on `windows-latest`: JDK 25 (Temurin) +
MinGW-w64 (MSYS2) + Ninja, then `configure -> build -> tests -> package`, and
uploads `dist/JuiceAgent_*.zip` as an artifact (14-day retention).
CI-specific notes:
- It builds with `-static-libgcc -static-libstdc++` and also copies any remaining
non-system imported DLLs next to the binaries (see rule 4).
- The workflow prints the DLL import list - useful when a load error appears.
- GitHub's unauthenticated REST API is limited to 60 requests/hour, so avoid
polling workflow status in a loop; install `gh` or use a token instead.
+11 -3
View File
@@ -10,13 +10,21 @@ set(CMAKE_LIBRARY_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)
set(CMAKE_ARCHIVE_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/lib)
set(SRC_DIR ${CMAKE_SOURCE_DIR}/src)
link_directories("${CMAKE_SOURCE_DIR}/lib")
if(WIN32)
link_directories("${CMAKE_SOURCE_DIR}/lib")
endif()
# libraries
add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection)
if (WIN32)
add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection)
endif()
# modules
add_subdirectory(${SRC_DIR}/libloader)
add_subdirectory(${SRC_DIR}/injector)
add_subdirectory(${SRC_DIR}/libinject)
if(WIN32)
add_subdirectory(${SRC_DIR}/libinject)
endif()
add_subdirectory(${SRC_DIR}/libagent)
+403
View File
@@ -0,0 +1,403 @@
# Quick Start for Agents
This guide tells an **agent** how to set up a JuiceAgent injection for a user:
ask the right questions, generate the files, run the injection, and verify it.
Work through the steps in order. The result is a self-contained runtime
directory called `app`, plus a short report to the user.
## Ground rules
- Only inject into a JVM that the user owns or is authorized to test. If that is
unclear, stop and ask before doing anything else.
- Do not modify the JuiceAgent native sources. Configuration and payload changes
cover almost every request.
- Keep every file in one runtime directory: `config.toml`, both JARs and the
four binaries. Relative paths only behave predictably when they sit next to
each other (see [Step 4](#step-4--write-configtoml)).
- Never guess a PID. Confirm it with the user or read it from the process list.
## Project overview
JuiceAgent is a JVMTI-based runtime injection framework for Windows. It injects
into a running JVM even when `DisableAttachMechanism=true` and without a
`-javaagent` flag, loads a JAR and calls an entry point, and exposes native APIs
to redefine/retransform classes, query loaded classes and read bytecode.
## Step 1 — Check the environment (do this yourself, do not ask the user)
**1.1 JDK.** `javac`, `jar` and `jps` ship with the JDK, so a full JDK is
required — a bare JRE is not enough.
```
java -version
```
If the JDK is missing or older than 1.8, ask the user to install JDK 1.8 or
higher.
**1.2 JuiceAgent binaries.** When built from source they are in `build/bin`
(release archives put them wherever they were extracted):
```
ls build/bin
```
Expected files:
```
injector.exe libinject.dll libloader.dll libagent.dll
```
If they are missing, ask the user to pick one of:
- **Method 1 (recommended):** download the latest release from
https://github.com/xiaozhou233/JuiceAgent/releases/latest
- **Method 2:** build from source — see the "How To Build" section of `README.md`
**1.3 Create the runtime directory.** Copy the four files into one directory and
call it `app` for the rest of this guide. A complete `app` looks like:
```
app/
├─ injector.exe libinject.dll libloader.dll libagent.dll
├─ config.toml # Step 4
├─ payload.jar # Step 3 (Q3)
├─ injection/ # Step 3 (Q5), dependency JARs; BuiltIn mode only
├─ src/ # payload source, if you generate it
└─ build/ # compiler output, one subdirectory per artifact
├─ target/ # demo target classes
└─ payload/ # payload classes
```
## Step 2 — Gather requirements (ask the user)
Ask these six questions and translate them into the user's language. Each
answer maps to a concrete decision, so do not skip any of them.
| # | Question | Decides |
| --- | --- | --- |
| Q1 | Which process do you want to inject into? (PID / process name / start a demo target — recommended) | the target and its working directory |
| Q2 | Is the target a standard, unmodified JVM? | whether injection will work at all |
| Q3 | What should the injected code do? (verify the link / your own code / modify bytecode) | the payload JAR, entry class and method |
| Q4 | Does the payload need JuiceAgent-API? (yes / no / don't know) | `JarLoader.Mode` |
| Q5 | Does the payload depend on other libraries? (yes / no) | `JarLoader.InjectionDir` |
| Q6 | How should the injection be triggered? (`injector.exe` / JNI JavaInjector) | the commands in Step 5 |
## Step 3 — Apply the answers
### Q1 — Target process
- **PID:** remember it for Step 5.
- **Process name:** resolve it to a PID with `jps -l`. Every JVM appears as
`java.exe`, so match the main class or JAR path in the `jps -l` output, or use
`Get-Process <name>` on Windows.
- **Start a demo target (recommended when the user has no target):** write
`app/target.java`:
```java
import java.lang.management.ManagementFactory;
public class target {
public static void main(String[] args) {
String pid = ManagementFactory.getRuntimeMXBean().getName().split("@")[0];
try {
while (true) {
System.out.println("[Target] I am the target JVM (PID: " + pid + ")");
Thread.sleep(1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
Compile and run it, **with `app` as the working directory**:
```
javac -encoding UTF-8 --release 8 -d app/build/target app/target.java
```
```powershell
Start-Process -FilePath java -ArgumentList "-cp","build/target","target" -WorkingDirectory "<path-to-app>"
```
The target prints its PID every second; `jps -l` also lists it.
> Starting the target with `app` as its working directory is not cosmetic. See
> [Step 4](#step-4--write-configtoml) for why the working directory decides which
> `config.toml` the injected loader finds.
### Q2 — Standard JVM
- **Standard JVM / `DisableAttachMechanism=true`:** continue — JuiceAgent is
designed for exactly this case.
- **Custom or modified JVM:** continue, but warn the user that JuiceAgent is
only tested against a regular JVM and may not work.
### Q3 — Payload
**Verify the link.** Write `app/src/Main.java`:
```java
public class Main {
public static void run() {
System.out.println("[Demo] Injection succeeded! Hello from JuiceAgent.");
System.out.println("[Demo] Current thread: " + Thread.currentThread().getName());
}
}
```
Build it into `app/payload.jar`. Each artifact gets its own output directory, so
packaging the payload never picks up the demo target's classes:
```
javac -encoding UTF-8 --release 8 -d app/build/payload app/src/Main.java
jar --create --file app/payload.jar -C app/build/payload .
```
The class name `Main` and method name `run` are needed in Step 4.
**Own code.** Ask the user for the payload JAR and record its fully qualified
entry class and method. The entry method must be `public`, `static` and take no
arguments (the project documents this as `public static void`; the return value
is ignored). It is resolved by reflection, so a non-public, non-static or
parameterized method is only reported as a failure at invocation time — the JAR
itself still loads.
**Modify bytecode.** Point the user at `examples/retransform-class`. Payloads
that redefine or retransform classes use JuiceAgent-API, so Q4 must resolve to
`BuiltIn`.
### Q4 — JuiceAgent-API
| Answer | `JarLoader.Mode` |
| --- | --- |
| Yes | `BuiltIn` |
| No | `CustomJar` |
| I don't know | `BuiltIn` |
`BuiltIn` (recommended) runs in two stages, and **both stages read
`config.toml` from the runtime directory**:
1. `libloader` extracts the embedded JuiceAgent-API JAR into `%TEMP%`, adds it
to the system class loader and calls `JuiceAgentBootstrap.start`, which loads
`libagent.dll` (from `JuiceAgentNativeLibraryPath`) and initializes the JVMTI
agent.
2. The agent's `JarLoaderService` reads the `JarLoader.*` keys again, then the
`JarLoader` module adds every `*.jar` in `InjectionDir` to the system class
loader, loads `JarPath` and invokes `EntryClass.EntryMethod`.
`Enabled` and `InjectionDir` are used in `BuiltIn` mode only. Omitting a key
silently falls back to a default, which is a common source of confusion:
`InjectionDir` defaults to `./injection`, `JarPath` to `./Entry.jar`,
`EntryClass` to `Example.Main` and `EntryMethod` to `start`.
`CustomJar` skips JuiceAgent-API and `libagent.dll` entirely: `libloader` adds
`JarPath` itself to the system class loader and invokes the entry method. In this
mode `Enabled` and `InjectionDir` are ignored, so any library the payload needs
must be bundled inside the payload JAR (or already on the target's classpath).
### Q5 — Other libraries
- **Yes:** create `app/injection/` and copy the dependency JARs into it. Every
`*.jar` there is loaded before the payload (`BuiltIn` mode only).
- **No:** still create the empty directory if the config references it, or drop
`InjectionDir` from the config.
### Q6 — Injection way
- **`injector.exe`:** nothing to prepare, continue to Step 4.
- **JNI JavaInjector:** copy the whole `examples/inject-via-java-api/injector`
directory to `app/injector/`, then build it:
```
app\injector\build.bat
```
That directory ships a prebuilt `JuiceAgent-JavaInjector-1.0-SNAPSHOT.jar`;
`build.bat` merges the example's `JavaInjector.class` into it and sets the main
class, so keep the JAR in place.
## Step 4 — Write config.toml
The file must be named exactly `config.toml` and placed in the directory that
`libloader` treats as the **runtime directory** (see the table below). Do not
rename it and do not scatter it across directories.
```toml
# See docs/config.md for more information:
# https://github.com/xiaozhou233/JuiceAgent/blob/main/docs/config.md
[JuiceAgent]
Version = 2
JuiceAgentNativeLibraryPath = ""
[JarLoader]
# BuiltIn: use the built-in jar loader (recommended; supports JuiceAgent-API)
# CustomJar: load the JAR directly, without JuiceAgent-API
# https://github.com/xiaozhou233/JuiceAgent/blob/main/docs/advanced.md#load-custom-api--directly-load-jar
Enabled = true
# Q4
Mode = "BuiltIn"
# BuiltIn mode only; Q5
InjectionDir = "./injection"
# Q3
JarPath = "./payload.jar"
EntryClass = "Main"
EntryMethod = "run"
```
- `Version` must stay `2`. A mismatch makes the loader refuse to start.
- `JuiceAgentNativeLibraryPath = ""` means "`libagent.dll` in the runtime
directory". Change it to an absolute path only if `libagent.dll` lives
elsewhere.
- `Mode = "CustomJar"` requires `JarPath`, `EntryClass` and `EntryMethod`
(there are no defaults in that mode); `Enabled` and `InjectionDir` are unused.
- Paths starting with `./` are resolved against the runtime directory; absolute
paths are used as-is.
### Which directory is the runtime directory?
This is where most failed setups go wrong: `libloader` does not take the config
directory from the `injector.exe` command line.
| How you inject | Directory `config.toml` is read from |
| --- | --- |
| Interactive `injector.exe` (type the PID) | the **injector process's** current directory — so `cd app` first |
| `injector.exe <pid> <libloader.dll> [libinject.dll]` | the **target JVM's** current directory (no directory is passed) |
| JavaInjector (JNI) | the `config_path` you enter; an empty value falls back to the target JVM's working directory |
Consequences:
- With the argument form, `config.toml` **and** every `./` path inside it
(`JarPath`, `InjectionDir`, `libagent.dll`) resolve against the target JVM's
working directory.
- If the user cannot control the target's working directory, use absolute paths
in `config.toml` — including `JuiceAgentNativeLibraryPath`.
- JNI injection is the most predictable option, because the config directory is
passed explicitly.
## Step 5 — Run the injection
### 5.1 Use `injector.exe`
```
cd app
```
`cd app` matters: `injector.exe` loads `libinject.dll` **by name from the
current directory**, and in interactive mode the current directory is also the
runtime directory.
**Interactive:**
```
.\injector.exe
```
It prints the `jps -l` output, then `Input PID:`. Type the PID of the target JVM
and press Enter.
> The program always ends with `Press any key to exit...` and waits for stdin.
> If you drive it from a script, feed it a newline after the PID and do not wait
> for the process to exit on its own.
**With arguments:**
```
.\injector.exe <PID> "<path-to-app>\libloader.dll" "<path-to-app>\libinject.dll"
```
The third argument is the path to **`libinject.dll`**, not a config directory.
Omit it to let `injector.exe` load `libinject.dll` from the current directory.
Remember that this form reads `config.toml` from the *target's* working
directory (Step 4).
### 5.2 Use JNI JavaInjector
Run it from `app`, because the example loads `./libinject.dll`:
```
java -cp injector\JuiceAgent-JavaInjector-1.0-SNAPSHOT.jar JavaInjector
```
```
PID: 1234
Dll: <path-to-app>\libloader.dll
config_path: <path-to-app>
```
Enter the target PID, the path to `libloader.dll`, and the directory containing
`config.toml`. Leaving `config_path` empty behaves like the argument form above:
the runtime directory falls back to the **target JVM's** working directory, so
always pass the directory explicitly.
## Step 6 — Verify
Verification has two independent sources. Do not confuse them: the
`[JuiceAgent JarLoader]` progress lines are printed to the **target's stdout**,
while the diagnostic logs are written to **files**.
**1. Target stdout** — this is the user-visible proof:
```
[JuiceAgent API] RuntimeDir : <the directory actually used>
[JuiceAgent JarLoader] Loading entry jar: ...
[JuiceAgent JarLoader] Resolving class: Main
[JuiceAgent JarLoader] Invoking method: Main.run
[JuiceAgent JarLoader] Entry method invoked successfully.
[Demo] Injection succeeded! Hello from JuiceAgent.
```
The `[JuiceAgent API]` banner prints the effective runtime directory and the
native library path, which is the fastest way to confirm the Step 4 rules.
**2. Log files** — two files are written **relative to the target JVM's working
directory** and truncated on every injection:
| File | Look for |
| --- | --- |
| `libloader.log` | `DllMain: DLL_PROCESS_ATTACH, runtime_dir:` and `[PreLoad] Runtime directory:` |
| `libagent.log` | `[JuiceAgent] Added JVMTI capabilities`, `[JarLoaderService] Loaded jar:`, and `JNI Exception occurred at:` when the payload itself throws |
If the target has no console (a service or a detached window), the stdout
markers are invisible — verify through the log files instead.
Report the outcome to the user, including the exact `app` path, the injection
command used, and the observed output.
## Troubleshooting
| Symptom | Likely cause |
| --- | --- |
| Injection reports success but nothing happens | `config.toml` is not in the directory `libloader` actually used — see Step 4 |
| `RuntimeDir :` in the banner is not `app` | The runtime directory fell back to the target JVM's working directory — see Step 4 |
| `[JuiceAgent API] JuiceAgent library not found at: <path>` | `libagent.dll` could not be resolved — set an absolute `JuiceAgentNativeLibraryPath`, or fix the runtime directory |
| `Failed to load injector library` / error 2 | `injector.exe` was not started from `app`, and no `libinject.dll` path was passed |
| `Failed to open DLL file` | The `libloader.dll` path is wrong |
| `libloader.log` / `libagent.log` seem missing | They are written in the target JVM's working directory, not your shell's |
| Loader refuses to start | `[JuiceAgent] Version` is not `2` |
| `Missing required config key: JarLoader.Mode` | `JarLoader.Mode` was omitted |
| Errors about missing `JarPath` / `EntryClass` / `EntryMethod` | `Mode = "CustomJar"` requires all three |
| `Failed to load jar: ...\Entry.jar` | `JarPath` was omitted and the default was used |
| The JAR loads but the entry call fails | The method is not `public static` with no parameters, or `EntryClass` is not fully qualified |
| `JNI Exception occurred at: CallStaticVoidMethod failed` | The payload threw — read the stack trace printed next to it |
| The injected process hangs for ~30 s, then `Failed to attach to JVM!` | The target process is not a JVM (the loader retries 30 × 1 s before giving up) |
| `jps` does not list the target | The target is 32-bit (JuiceAgent ships x64 only) or runs with different privileges |
| Injection fails on an elevated target | Run `injector.exe` elevated too |
| Antivirus flags the binaries | Expected false positive — see `docs/Antivirus-False-Positive.md` |
| Native-access warning on JDK 22+ | The payload loads a native library; the target JVM needs `--enable-native-access=ALL-UNNAMED` |
## Done checklist
- [ ] A JDK 1.8+ with `javac`, `jar` and `jps` is available
- [ ] `app/` contains all four JuiceAgent binaries
- [ ] The payload JAR exists and its entry method is `public static` and takes no arguments
- [ ] `config.toml` is in the directory `libloader` actually uses (Step 4), `Version = 2`, and every key matches the Q3–Q5 answers
- [ ] The injection command reported success
- [ ] The `[JuiceAgent API]` banner shows the expected `RuntimeDir`, and the payload output appears with no errors in the logs
+7
View File
@@ -14,6 +14,13 @@ Welcome to join our QQ/Discord group for more information and support:
- Discord: [JuiceDev](https://discord.gg/AQTnUyWNNJ)
- QQ Group: 1103504356
> **New to JuiceAgent?** You do not have to wire up the injection by hand. A
> coding agent such as OpenCode can do it for you: open this repository in the
> agent and ask it to read [`QuickStartForAgents.md`](QuickStartForAgents.md) and
> follow it. That guide covers the whole process — environment check, requirement
> gathering, `config.toml`, injection and verification — and is written to be
> executed by an agent. Simply tell the agent:
> "Read `QuickStartForAgents.md` and follow it to inject my JAR."
![License](https://img.shields.io/github/license/xiaozhou233/JuiceAgent)
![Release](https://img.shields.io/github/v/release/xiaozhou233/JuiceAgent)
+3
View File
@@ -16,6 +16,9 @@ JuiceAgent 是一个基于 JVMTI 的高级注入框架,用于运行时 JAR 加
- Discord:[JuiceDev](https://discord.gg/AQTnUyWNNJ)
- QQ 群:1103504356
> **不知道该怎么用?** 不必手动折腾注入流程:用支持读写文件和执行命令的 AI Agent(例如 OpenCode)即可。在本仓库中打开 Agent,让它先阅读 [`QuickStartForAgents.md`](QuickStartForAgents.md) 并照着执行——该文档覆盖了完整流程(环境检查、需求确认、`config.toml`、注入与验证),并且是专门写给 Agent 执行的。你只需要告诉它:
> "请阅读 `QuickStartForAgents.md`,并照着里面的步骤把我的 JAR 注入到目标 JVM。"
![License](https://img.shields.io/github/license/xiaozhou233/JuiceAgent)
![Release](https://img.shields.io/github/v/release/xiaozhou233/JuiceAgent)
![GitHub last commit](https://img.shields.io/github/last-commit/xiaozhou233/JuiceAgent)
+1 -1
View File
@@ -3,5 +3,5 @@ out/
# Do not ignore root build artifacts:
!new_target.class
!playload.jar
!payload.jar
!target.jar
+12 -12
View File
@@ -10,10 +10,10 @@
| `config.toml` | Injection config |
| `build.bat` | Build script |
| `run.bat` | Run target JVM |
| `playload.jar` | JAR to inject (built by `build.bat`) |
| `payload.jar` | JAR to inject (built by `build.bat`) |
| `target.jar` | Target JVM program (built by `build.bat`) |
| `new_target.class` | Retransformed bytecode (built by `build.bat`) |
| `playload/` | Payload source |
| `payload/` | Payload source |
| `target/` | Target source |
| `new_target/` | Modified copy of target source |
@@ -31,7 +31,7 @@ Hello!
Retransformed!
```
This example injects `playload.jar` into a running JVM. The payload reads
This example injects `payload.jar` into a running JVM. The payload reads
`new_target.class` from its own JAR and calls
`JuiceAgent.retransformClassByName("target", ...)` to swap the already-loaded
`target` class on the fly. After that, `say()` starts printing the new message
@@ -41,14 +41,14 @@ without restarting the JVM.
### 1. Build (optional)
`playload.jar` and `target.jar` are already included by default.
If you modified `playload/`, `target/` or `new_target/`, run:
`payload.jar` and `target.jar` are already included by default.
If you modified `payload/`, `target/` or `new_target/`, run:
```
build.bat
```
to regenerate `playload.jar`, `target.jar` and `new_target.class`.
to regenerate `payload.jar`, `target.jar` and `new_target.class`.
### 2. Run the target JVM
@@ -77,8 +77,8 @@ Input PID: 6644
Go back to the target window. Injection succeeded if you see:
```
Playload loaded!
Playload executed!
Payload loaded!
Payload executed!
```
and the output of `say()` changes from `Hello!` to:
@@ -92,8 +92,8 @@ Retransformed!
| Key | Description |
| --- | --- |
| `JarPath` | JAR path to inject (default: `./playload.jar`) |
| `EntryClass` | Entry class (default: `playload`) |
| `JarPath` | JAR path to inject (default: `./payload.jar`) |
| `EntryClass` | Entry class (default: `payload`) |
| `EntryMethod` | Entry method, must be `public static void entry()` |
## Troubleshooting
@@ -102,8 +102,8 @@ Retransformed!
Install a JDK and add its `bin` directory to `PATH`.
- `injector.exe` reports injection failure:
Make sure the target JVM is running and the PID is correct.
- No `Playload loaded!` output appears:
- No `Payload loaded!` output appears:
Check `libagent.log` and `libloader.log` in this directory for the cause.
- `say()` output does not change:
Make sure `build.bat` was run after editing `new_target/`, and that
`new_target.class` inside `playload.jar` is up to date.
`new_target.class` inside `payload.jar` is up to date.
+12 -12
View File
@@ -9,10 +9,10 @@ Directory Files:
config.toml - injection config
build.bat - build script
run.bat - run target JVM
playload.jar - JAR to inject (built by build.bat)
payload.jar - JAR to inject (built by build.bat)
target.jar - target JVM program (built by build.bat)
new_target.class - retransformed bytecode (built by build.bat)
playload/ - payload source
payload/ - payload source
target/ - target source
new_target/ - modified copy of target source
@@ -26,7 +26,7 @@ The target class "target" has a method say() that prints:
new_target/target.java is a modified copy that also prints:
Retransformed!
This example injects playload.jar into a running JVM. The payload reads
This example injects payload.jar into a running JVM. The payload reads
new_target.class from its own JAR and calls
JuiceAgent.retransformClassByName("target", ...) to swap the already-loaded
"target" class on the fly. After that, say() starts printing the new message
@@ -37,10 +37,10 @@ without restarting the JVM.
============================================
1. Build (optional)
playload.jar and target.jar are already included by default.
If you modified playload/, target/ or new_target/, run:
payload.jar and target.jar are already included by default.
If you modified payload/, target/ or new_target/, run:
build.bat
to regenerate playload.jar, target.jar and new_target.class.
to regenerate payload.jar, target.jar and new_target.class.
2. Run the target JVM
Double-click run.bat (or run: java -jar target.jar). A black window
@@ -57,8 +57,8 @@ without restarting the JVM.
4. Verify
Go back to the target window. Injection succeeded if you see:
Playload loaded!
Playload executed!
Payload loaded!
Payload executed!
and the output of say() changes from "Hello!" to:
Hello!
Retransformed!
@@ -67,8 +67,8 @@ without restarting the JVM.
Config / config.toml
============================================
JarPath - JAR path to inject (default: ./playload.jar)
EntryClass - Entry class (default: playload)
JarPath - JAR path to inject (default: ./payload.jar)
EntryClass - Entry class (default: payload)
EntryMethod - Entry method, must be public static void entry()
============================================
@@ -79,8 +79,8 @@ without restarting the JVM.
Install a JDK and add its bin directory to PATH.
- injector.exe reports injection failure:
Make sure the target JVM is running and the PID is correct.
- No "Playload loaded!" output appears:
- No "Payload loaded!" output appears:
Check libagent.log and libloader.log in this directory for the cause.
- say() output does not change:
Make sure build.bat was run after editing new_target/, and that
new_target.class inside playload.jar is up to date.
new_target.class inside payload.jar is up to date.
+6 -6
View File
@@ -1,13 +1,13 @@
@echo off
setlocal
set "API_JAR=playload\JuiceAgent-API-1.4.1+build.1.jar"
set "PAYLOAD_JAR=playload.jar"
set "API_JAR=payload\JuiceAgent-API-1.4.1+build.1.jar"
set "PAYLOAD_JAR=payload.jar"
set "TARGET_JAR=target.jar"
set "OUT=out"
set "OUT_NT=%OUT%\new_target"
set "OUT_PL=%OUT%\playload"
set "OUT_PL=%OUT%\payload"
set "OUT_TG=%OUT%\target"
set "NEW_TARGET_CLASS=new_target.class"
@@ -29,8 +29,8 @@ if errorlevel 1 goto :error
copy /y "%OUT_NT%\new_target.class" "%NEW_TARGET_CLASS%"
if errorlevel 1 goto :error
echo === Compiling playload ===
javac -encoding UTF-8 --release 8 -cp "%API_JAR%" -d "%OUT_PL%" playload\playload.java
echo === Compiling payload ===
javac -encoding UTF-8 --release 8 -cp "%API_JAR%" -d "%OUT_PL%" payload\payload.java
if errorlevel 1 goto :error
echo === Compiling target ===
@@ -38,7 +38,7 @@ javac -encoding UTF-8 --release 8 -d "%OUT_TG%" target\target.java
if errorlevel 1 goto :error
echo === Packaging payload jar ===
jar --create --file "%PAYLOAD_JAR%" -C "%OUT_PL%" playload.class
jar --create --file "%PAYLOAD_JAR%" -C "%OUT_PL%" payload.class
if errorlevel 1 goto :error
echo === Packaging target jar ===
+2 -2
View File
@@ -14,6 +14,6 @@ Mode = "BuiltIn"
# InjectionDir only works when Mode is BuiltIn
InjectionDir = "./injection"
JarPath = "./playload.jar"
EntryClass = "playload"
JarPath = "./payload.jar"
EntryClass = "payload"
EntryMethod = "entry"
Binary file not shown.
@@ -1,8 +1,8 @@
import cn.xiaozhou233.juiceagent.api.JuiceAgent;
public class playload {
public class payload {
public static void entry() throws java.io.IOException {
System.out.println("Playload loaded!");
System.out.println("Payload loaded!");
java.io.InputStream in = new java.io.FileInputStream("new_target.class");
java.io.ByteArrayOutputStream out = new java.io.ByteArrayOutputStream();
@@ -20,6 +20,6 @@ public class playload {
bytes.length
);
System.out.println("Playload executed!");
System.out.println("Payload executed!");
}
}
Binary file not shown.
+12 -12
View File
@@ -10,10 +10,10 @@
| `config.toml` | 注入配置 |
| `build.bat` | 构建脚本 |
| `run.bat` | 运行目标 JVM |
| `playload.jar` | 注入用的 JAR(由 `build.bat` 生成) |
| `payload.jar` | 注入用的 JAR(由 `build.bat` 生成) |
| `target.jar` | 目标 JVM 程序(由 `build.bat` 生成) |
| `new_target.class` | 重变换后的字节码(由 `build.bat` 生成) |
| `playload/` | payload 源码 |
| `payload/` | payload 源码 |
| `target/` | 目标类源码 |
| `new_target/` | target 的修改版源码 |
@@ -31,7 +31,7 @@ Hello!
Retransformed!
```
本示例把 `playload.jar` 注入到运行中的 JVM。payload 从自己的 JAR 中读取
本示例把 `payload.jar` 注入到运行中的 JVM。payload 从自己的 JAR 中读取
`new_target.class`,调用 `JuiceAgent.retransformClassByName("target", ...)`
在运行时动态替换已加载的 `target` 类。之后 `say()` 无需重启 JVM 就会输出新内容。
@@ -39,14 +39,14 @@ Retransformed!
### 1. 构建(可选)
`playload.jar` 和 `target.jar` 默认已包含。
如果修改了 `playload/`、`target/` 或 `new_target/`,运行:
`payload.jar` 和 `target.jar` 默认已包含。
如果修改了 `payload/`、`target/` 或 `new_target/`,运行:
```
build.bat
```
重新生成 `playload.jar`、`target.jar` 和 `new_target.class`。
重新生成 `payload.jar`、`target.jar` 和 `new_target.class`。
### 2. 运行目标 JVM
@@ -72,8 +72,8 @@ Input PID: 6644
回到目标窗口,注入成功应看到:
```
Playload loaded!
Playload executed!
Payload loaded!
Payload executed!
```
并且 `say()` 的输出从 `Hello!` 变为:
@@ -87,8 +87,8 @@ Retransformed!
| 配置项 | 说明 |
| --- | --- |
| `JarPath` | 注入的 JAR 路径(默认 `./playload.jar`) |
| `EntryClass` | 入口类(默认 `playload`) |
| `JarPath` | 注入的 JAR 路径(默认 `./payload.jar`) |
| `EntryClass` | 入口类(默认 `payload`) |
| `EntryMethod` | 入口方法,必须为 `public static void entry()` |
## 常见问题
@@ -97,8 +97,8 @@ Retransformed!
安装 JDK 并将 `bin` 目录加入 `PATH`。
- `injector.exe` 提示注入失败:
确认目标 JVM 正在运行且 PID 正确。
- 没有出现 `Playload loaded!` 输出:
- 没有出现 `Payload loaded!` 输出:
查看本目录下的 `libagent.log` 和 `libloader.log` 定位原因。
- `say()` 输出没有变化:
确认修改 `new_target/` 后重新运行过 `build.bat`,且 `playload.jar` 内的
确认修改 `new_target/` 后重新运行过 `build.bat`,且 `payload.jar` 内的
`new_target.class` 是最新的。
+12 -12
View File
@@ -9,10 +9,10 @@
config.toml - 注入配置
build.bat - 构建脚本
run.bat - 运行目标 JVM
playload.jar - 注入用的 JAR (由 build.bat 生成)
payload.jar - 注入用的 JAR (由 build.bat 生成)
target.jar - 目标 JVM 程序 (由 build.bat 生成)
new_target.class - 重变换后的字节码 (由 build.bat 生成)
playload/ - payload 源码
payload/ - payload 源码
target/ - 目标类源码
new_target/ - target 的修改版源码
@@ -26,7 +26,7 @@
new_target/target.java 是它的修改版, 额外打印:
Retransformed!
本示例把 playload.jar 注入到运行中的 JVM。payload 从自己的 JAR 中读取
本示例把 payload.jar 注入到运行中的 JVM。payload 从自己的 JAR 中读取
new_target.class, 调用 JuiceAgent.retransformClassByName("target", ...)
在运行时动态替换已加载的 "target" 类。之后 say() 无需重启 JVM 就会输出新内容。
@@ -35,10 +35,10 @@ new_target.class, 调用 JuiceAgent.retransformClassByName("target", ...)
============================================
1. 构建 (可选)
playload.jar 和 target.jar 默认已包含。
如果修改了 playload/、target/ 或 new_target/, 运行:
payload.jar 和 target.jar 默认已包含。
如果修改了 payload/、target/ 或 new_target/, 运行:
build.bat
重新生成 playload.jar、target.jar 和 new_target.class。
重新生成 payload.jar、target.jar 和 new_target.class。
2. 运行目标 JVM
双击 run.bat (或执行: java -jar target.jar)。黑窗口出现并每秒打印:
@@ -53,8 +53,8 @@ new_target.class, 调用 JuiceAgent.retransformClassByName("target", ...)
4. 验证
回到目标窗口, 注入成功应看到:
Playload loaded!
Playload executed!
Payload loaded!
Payload executed!
并且 say() 的输出从 "Hello!" 变为:
Hello!
Retransformed!
@@ -63,8 +63,8 @@ new_target.class, 调用 JuiceAgent.retransformClassByName("target", ...)
配置 / config.toml
============================================
JarPath - 注入的 JAR 路径 (默认: ./playload.jar)
EntryClass - 入口类 (默认: playload)
JarPath - 注入的 JAR 路径 (默认: ./payload.jar)
EntryClass - 入口类 (默认: payload)
EntryMethod - 入口方法, 必须为 public static void entry()
============================================
@@ -75,8 +75,8 @@ new_target.class, 调用 JuiceAgent.retransformClassByName("target", ...)
安装 JDK 并将 bin 目录加入 PATH。
- injector.exe 提示注入失败:
确认目标 JVM 正在运行且 PID 正确。
- 没有出现 "Playload loaded!" 输出:
- 没有出现 "Payload loaded!" 输出:
查看本目录下的 libagent.log 和 libloader.log 定位原因。
- say() 输出没有变化:
确认修改 new_target/ 后重新运行过 build.bat, 且 playload.jar 内的
确认修改 new_target/ 后重新运行过 build.bat, 且 payload.jar 内的
new_target.class 是最新的。
+60
View File
@@ -0,0 +1,60 @@
/*
* Copyright (c) 1999, 2001, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
#ifndef _JAVASOFT_JAWT_MD_H_
#define _JAVASOFT_JAWT_MD_H_
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include "jawt.h"
#ifdef __cplusplus
extern "C" {
#endif
/*
* X11-specific declarations for AWT native interface.
* See notes in jawt.h for an example of use.
*/
typedef struct jawt_X11DrawingSurfaceInfo {
Drawable drawable;
Display* display;
VisualID visualID;
Colormap colormapID;
int depth;
/*
* Since 1.4
* Returns a pixel value from a set of RGB values.
* This is useful for paletted color (256 color) modes.
*/
int (JNICALL *GetAWTColor)(JAWT_DrawingSurface* ds,
int r, int g, int b);
} JAWT_X11DrawingSurfaceInfo;
#ifdef __cplusplus
}
#endif
#endif /* !_JAVASOFT_JAWT_MD_H_ */
+66
View File
@@ -0,0 +1,66 @@
/*
* Copyright (c) 1996, 2020, Oracle and/or its affiliates. All rights reserved.
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
*
* This code is free software; you can redistribute it and/or modify it
* under the terms of the GNU General Public License version 2 only, as
* published by the Free Software Foundation. Oracle designates this
* particular file as subject to the "Classpath" exception as provided
* by Oracle in the LICENSE file that accompanied this code.
*
* This code is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
* FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
* version 2 for more details (a copy is included in the LICENSE file that
* accompanied this code).
*
* You should have received a copy of the GNU General Public License version
* 2 along with this work; if not, write to the Free Software Foundation,
* Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
*
* Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
* or visit www.oracle.com if you need additional information or have any
* questions.
*/
#ifndef _JAVASOFT_JNI_MD_H_
#define _JAVASOFT_JNI_MD_H_
#ifndef __has_attribute
#define __has_attribute(x) 0
#endif
#ifndef JNIEXPORT
#if (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4) && (__GNUC_MINOR__ > 2))) || __has_attribute(visibility)
#ifdef ARM
#define JNIEXPORT __attribute__((externally_visible,visibility("default")))
#else
#define JNIEXPORT __attribute__((visibility("default")))
#endif
#else
#define JNIEXPORT
#endif
#endif
#if (defined(__GNUC__) && ((__GNUC__ > 4) || (__GNUC__ == 4) && (__GNUC_MINOR__ > 2))) || __has_attribute(visibility)
#ifdef ARM
#define JNIIMPORT __attribute__((externally_visible,visibility("default")))
#else
#define JNIIMPORT __attribute__((visibility("default")))
#endif
#else
#define JNIIMPORT
#endif
#define JNICALL
typedef int jint;
#ifdef _LP64
typedef long jlong;
#else
typedef long long jlong;
#endif
typedef signed char jbyte;
#endif /* !_JAVASOFT_JNI_MD_H_ */
+5 -1
View File
@@ -1,2 +1,6 @@
# injector
add_executable(injector injector.c)
if(WIN32)
add_executable(injector injector.c)
else()
add_executable(injector injector_linux.c)
endif()
+10
View File
@@ -0,0 +1,10 @@
#include <stdio.h>
int main(int argc, char *argv[]) {
// TODO: Implement Linux injector
// Due to certain reasons, the Injector for Linux is not open source.
// Please wait a moment for the next update.
printf("Due to certain reasons, the Injector for Linux is not open source. Please wait a moment for the next update.\n");
return 0;
}
+11 -5
View File
@@ -10,11 +10,17 @@ add_library(agent SHARED ${agent_sources})
target_include_directories(agent PRIVATE
${CMAKE_SOURCE_DIR}/includes
${CMAKE_SOURCE_DIR}/includes/jvm
${CMAKE_SOURCE_DIR}/includes/jvm/win32
${CMAKE_CURRENT_SOURCE_DIR}/includes
)
target_link_libraries(agent PRIVATE
ReflectiveDLLInjection
jvm
)
if(WIN32)
target_include_directories(agent PRIVATE
${CMAKE_SOURCE_DIR}/includes/jvm/win32
)
target_link_libraries(agent PRIVATE jvm)
else()
target_include_directories(agent PRIVATE
${CMAKE_SOURCE_DIR}/includes/jvm/linux
)
endif()
+20 -5
View File
@@ -12,6 +12,15 @@ if (WIN32)
)
list(APPEND loader_sources ${windows_sources})
else()
message(STATUS "Detected System: Linux or Other")
file(GLOB_RECURSE linux_sources CONFIGURE_DEPENDS
${CMAKE_CURRENT_SOURCE_DIR}/platform/linux/*.cpp
${CMAKE_CURRENT_SOURCE_DIR}/platform/linux/*.c
)
list(APPEND loader_sources ${linux_sources})
endif()
add_library(loader SHARED ${loader_sources})
@@ -27,11 +36,17 @@ endif()
target_include_directories(loader PRIVATE
${CMAKE_SOURCE_DIR}/includes
${CMAKE_SOURCE_DIR}/includes/jvm
${CMAKE_SOURCE_DIR}/includes/jvm/win32
${CMAKE_CURRENT_SOURCE_DIR}/includes
)
target_link_libraries(loader PRIVATE
jvm
ReflectiveDLLInjection
)
if(WIN32)
target_include_directories(loader PRIVATE
${CMAKE_SOURCE_DIR}/includes/jvm/win32
)
target_link_libraries(loader PRIVATE jvm ReflectiveDLLInjection)
else()
target_include_directories(loader PRIVATE
${CMAKE_SOURCE_DIR}/includes/jvm/linux
)
endif()
+8 -1
View File
@@ -92,7 +92,14 @@ void JuiceAgent::Loader::initialize(const char* runtime_dir, JNIEnv* env, jvmtiE
JuiceAgent::Utils::Serializer ser;
ser.add_kv("Version", cfg.get<int>("JuiceAgent.Version", -1));
ser.add_kv("JuiceAgentNativeLibraryPath", cfg.getPath("JuiceAgent.JuiceAgentNativeLibraryPath", (cfg.getRuntimeDir()/"libagent.dll").string()));
#ifdef _WIN32
std::string default_libagent_path = (cfg.getRuntimeDir()/"libagent.dll").string();
#else
std::string default_libagent_path = (cfg.getRuntimeDir()/"libagent.so").string();
#endif
ser.add_kv("JuiceAgentNativeLibraryPath", cfg.getPath("JuiceAgent.JuiceAgentNativeLibraryPath", default_libagent_path));
ser.add_kv("RuntimeDir", cfg.getRuntimeDir().string());
std::string args = ser.serialize();
+59
View File
@@ -0,0 +1,59 @@
#include "JuiceAgent/Logger.hpp"
#include "Loader.hpp"
#include <cstdlib>
#include <filesystem>
#include <string>
#include <system_error>
#include <thread>
namespace fs = std::filesystem;
static void run_loader() {
const char* env = std::getenv("JuiceAgent_ConfigPath");
std::string current_path;
if (env != nullptr && env[0] != '\0') {
// Use the environment variable if it exists and is not empty.
current_path = env;
} else {
spdlog::trace("[libloader] JuiceAgent_ConfigPath is not set");
const char* home = std::getenv("HOME");
if (home == nullptr || home[0] == '\0') {
spdlog::error("[libloader] HOME environment variable is not set");
return;
}
// Fall back to $HOME/.juiceagent.
fs::path config_dir = fs::path(home) / ".juiceagent";
std::error_code ec;
fs::create_directories(config_dir, ec);
if (ec) {
spdlog::error(
"[libloader] Failed to create config directory: {}",
ec.message()
);
return;
}
current_path = config_dir.string();
}
spdlog::info("[libloader] current path: {}", current_path);
JuiceAgent::Loader::entrypoint(current_path.c_str());
}
__attribute__((constructor))
static void entry() {
Logger::init();
spdlog::info("[libloader] loaded!");
std::thread([] {
run_loader();
}).detach();
}