Compare commits

...
5 Commits
Author SHA1 Message Date
xiaozhou233 45da09ff5c Refactor: rework integration tests and add a Linux runner
- tests: add TestSupport with a single RESULT: PASS/FAIL verdict protocol
- tests: assert on native return values and captured output, not runner markers
- tests: replace the brittle "Bytes: 399" marker with a class-file magic check
- tests: read the shared case list from tests/cases.txt
- tests: add run-tests.sh and copy-bin.sh, run the tests on Linux too
- tests: exclude the Loop.java demo from the compiled test output
- CI: set up JDK 25 and run the integration tests in the build-linux job
- Docs: refresh the AGENTS.md test/CI sections and rule 5
2026-11-20 14:09:56 +08:00
xiaozhou233 d31e43af31 Refactor: Vendor ptrace-inject-cpp into includes
- ptrace-inject-cpp: remove the submodule, its .gitmodules entry and config section
- includes/ptrace-inject-cpp: add the injection library sources, public header and LICENSE
- includes/ptrace-inject-cpp: add CMakeLists defining the ptrace_inject static library
- cmake: build includes/ptrace-inject-cpp on non-Windows instead of the submodule
- docs: list the vendored library in the AGENTS.md layout
2026-10-24 23:02:50 +08:00
xiaozhou233 4b1ca5a490 CI: check out submodules in the Linux build job
- ci: add submodules: recursive to the build-linux checkout; without it the
  ptrace-inject-cpp directory is empty and configure fails on add_subdirectory
2026-10-20 13:37:13 +08:00
xiaozhou233 483a12cd3c Feat: implement the Linux injector with ptrace-inject-cpp
- cmake: build the ptrace-inject-cpp submodule on non-Windows with its CLI and
  examples disabled, and link ptrace_inject::ptrace_inject into the injector
- injector: replace the placeholder injector_linux.c with injector_linux.cpp,
  a CLI that injects a shared library into -p PID or -n NAME and forwards the
  library's log output to stderr
2026-10-20 13:36:22 +08:00
xiaozhou233 416e83f36e [Feat] add ptrace-inject-cpp as submodule 2026-10-20 13:36:22 +08:00
44 changed files with 1792 additions and 256 deletions

No files matched your search

+12 -1
View File
@@ -95,12 +95,20 @@ jobs:
retention-days: 14
build-linux:
name: Build (Linux, GCC)
name: Build & integration tests (Linux, GCC)
runs-on: ubuntu-latest
steps:
- name: Checkout
uses: actions/checkout@v4
with:
submodules: recursive
- name: Set up JDK
uses: actions/setup-java@v4
with:
distribution: temurin
java-version: '25'
- name: Install build tools
run: |
@@ -122,6 +130,9 @@ jobs:
echo "--- build/bin ---"
ls -1 build/bin
- name: Run integration tests
run: bash tests/run-tests.sh
- name: Package release tarball
run: ./script/package.sh
+27 -12
View File
@@ -45,20 +45,32 @@ 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`.
that load the native agent (`resources/libagent.dll` on Windows,
`resources/libagent.so` on Linux) and call `JuiceAgent.init("")`. The shared
`tests/src/TestSupport.java` performs that bootstrap and prints the single verdict
line each test is judged on (`RESULT: PASS <name>` / `RESULT: FAIL <name>: ...`).
Some tests also need the `injection` module compiled into
`out/production/injection`.
Build first, then:
```powershell
# Windows
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**.
```bash
# Linux
bash tests/run-tests.sh
# or: JAVA_HOME=/path/to/jdk bash tests/run-tests.sh
```
Both runners compile the modules, refresh `tests/resources` from `build/bin`
(`tests/copy-bin.bat` / `tests/copy-bin.sh`), compile the tests, then run every
case listed in `tests/cases.txt` and **assert on its verdict output**. `Loop.java`
is a manual demo (infinite loop) and is not compiled into the test 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.
@@ -136,9 +148,11 @@ 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.
The test programs print diagnostics and **still exit 0** when a step fails. Each
one ends by printing a single verdict line - `RESULT: PASS <name>` or
`RESULT: FAIL <name>: <reason>` - and the runners match `RESULT: PASS <name>`
(and reject any `RESULT: FAIL`) instead of trusting the exit code, which would
silently pass broken builds.
Notes when adding tests:
@@ -159,7 +173,8 @@ src/libagent libagent.dll (JVMTI agent)
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
includes/ptrace-inject-cpp vendored Linux injector library (libptrace_inject.a)
tests/ integration tests + run-tests.{ps1,sh} + copy-bin.{bat,sh} + cases.txt
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
@@ -209,9 +224,9 @@ Tracked text files are **LF in the index, CRLF in the working tree** (no
- `build-and-test` on `windows-latest`: JDK 25 (Temurin) + MinGW-w64 (MSYS2) +
Ninja, then `configure -> build -> tests -> package`, uploading
`dist/JuiceAgent_*.zip` as an artifact (14-day retention).
- `build-linux` on `ubuntu-latest`: GCC + Ninja, then
`configure -> build -> package` only — the integration tests are Windows-only —
uploading `dist/JuiceAgent_*.tar.gz`.
- `build-linux` on `ubuntu-latest`: JDK 25 (Temurin) + GCC + Ninja, then
`configure -> build -> tests -> package`, uploading
`dist/JuiceAgent_*.tar.gz`.
CI-specific notes:
+2
View File
@@ -18,6 +18,8 @@ endif()
# libraries
if (WIN32)
add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ReflectiveDLLInjection)
else()
add_subdirectory(${CMAKE_SOURCE_DIR}/includes/ptrace-inject-cpp)
endif()
# modules
+27
View File
@@ -0,0 +1,27 @@
add_library(ptrace_inject STATIC
src/library.cpp
src/log.cpp
src/util.cpp
src/maps.cpp
src/memory.cpp
src/ptrace_utils.cpp
src/symbols.cpp
src/inject.cpp
src/process_lookup.cpp
)
add_library(ptrace_inject::ptrace_inject ALIAS ptrace_inject)
target_include_directories(ptrace_inject
PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/include
PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/src
)
target_compile_options(ptrace_inject PRIVATE -Wall -Wextra -Wpedantic)
target_link_libraries(ptrace_inject PRIVATE dl)
set_target_properties(ptrace_inject PROPERTIES
CXX_VISIBILITY_PRESET hidden
VISIBILITY_INLINES_HIDDEN ON
POSITION_INDEPENDENT_CODE ON
)
+21
View File
@@ -0,0 +1,21 @@
MIT License
Copyright (c) 2026 xiaozhou233
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
@@ -0,0 +1,90 @@
/*
* ptrace_inject - C ABI for injecting shared libraries with ptrace.
*
* Part of ptrace-inject-cpp, a C++ port of the original Rust project:
* https://github.com/Artemis21/ptrace-inject
*/
#ifndef PTRACE_INJECT_H
#define PTRACE_INJECT_H
#include <stddef.h>
#include <sys/types.h>
#ifdef __cplusplus
extern "C" {
#endif
#define PTRACE_INJECT_VERSION_MAJOR 1
#define PTRACE_INJECT_VERSION_MINOR 0
#define PTRACE_INJECT_VERSION_PATCH 0
#define PTRACE_INJECT_VERSION_STRING "1.0.0"
#if defined(__GNUC__) || defined(__clang__)
#define PTRACE_INJECT_API __attribute__((visibility("default")))
#else
#define PTRACE_INJECT_API
#endif
/* Return values. */
enum ptrace_inject_result {
PTRACE_INJECT_OK = 0,
PTRACE_INJECT_ERROR = -1
};
/* Log levels passed to ptrace_inject_log_fn. */
enum ptrace_inject_log_level {
PTRACE_INJECT_LOG_DEBUG = 0,
PTRACE_INJECT_LOG_INFO = 1,
PTRACE_INJECT_LOG_WARN = 2,
PTRACE_INJECT_LOG_ERROR = 3
};
/*
* Optional logging callback.
*
* `message` is only valid for the duration of the call. Pass the same
* `ptrace_inject_options` to every injection; the callback runs on the
* thread that called ptrace_inject_*().
*/
typedef void (*ptrace_inject_log_fn)(int level, const char *message,
void *user_data);
typedef struct ptrace_inject_options {
ptrace_inject_log_fn log_fn; /* may be NULL */
void *log_user_data; /* passed back to log_fn */
} ptrace_inject_options;
/*
* Inject `library_path` into the process `pid`.
*
* `options` may be NULL (silent). `error` may be NULL; when non-NULL and
* `error_size > 0`, it receives a NUL-terminated error message on failure and
* an empty string on success.
*
* Returns PTRACE_INJECT_OK on success, PTRACE_INJECT_ERROR on failure.
*
* The call is synchronous and blocks until the library has been dlopen()ed
* (or the call failed). It is safe to call from multiple threads at the same
* time as long as the targets are different.
*/
PTRACE_INJECT_API int
ptrace_inject_by_pid(pid_t pid, const char *library_path,
const ptrace_inject_options *options, char *error,
size_t error_size);
/*
* Same as ptrace_inject_by_pid(), but finds the target by executable path or
* file name. `resolved_pid` may be NULL; when non-NULL it receives the PID
* that was found (only on success).
*/
PTRACE_INJECT_API int
ptrace_inject_by_name(const char *process_name, const char *library_path,
const ptrace_inject_options *options,
pid_t *resolved_pid, char *error, size_t error_size);
#ifdef __cplusplus
} /* extern "C" */
#endif
#endif /* PTRACE_INJECT_H */
+25
View File
@@ -0,0 +1,25 @@
#pragma once
#include <array>
#include <cstdint>
// The 6-byte shellcode patched into the tracee:
//
// 90 90 nop; nop
// 41 ff d1 call r9
// cc int3
//
// The tracer sets r9 to the function to call, rdi/rsi to its arguments, and
// rip to kShellcode + 2 (the nop slide covers a possible RIP rewind).
inline constexpr std::array<std::uint8_t, 6> kShellcode = {
0x90, 0x90,
0x41, 0xff, 0xd1,
0xcc,
};
// Keep this much free space below the target's rsp so we do not clobber the
// 128-byte red zone of the function that was interrupted.
inline constexpr std::uint64_t kStackMargin = 256;
// How many times to re-scan /proc/<pid>/task while stopping threads.
inline constexpr int kMaxAttachRounds = 8;
+219
View File
@@ -0,0 +1,219 @@
#include "inject.h"
#include <dlfcn.h>
#include <unistd.h>
#include <array>
#include <cstdint>
#include <filesystem>
#include <stdexcept>
#include <string>
#include <vector>
#include "config.h"
#include "log.h"
#include "maps.h"
#include "memory.h"
#include "ptrace_utils.h"
#include "symbols.h"
#include "util.h"
// ---------------------------------------------------------------------------
// Choosing where to patch
// ---------------------------------------------------------------------------
static bool overlaps(std::uint64_t address, std::uint64_t other,
std::uint64_t length) {
return address + length > other && address < other + length;
}
// Pick a page-aligned spot in a private, file-backed executable mapping that
// no stopped thread is currently sitting in.
static std::uint64_t find_patch_site(pid_t pid,
const std::vector<pid_t>& threads) {
std::vector<std::uint64_t> instruction_pointers;
instruction_pointers.reserve(threads.size());
for (const pid_t tid : threads) {
instruction_pointers.push_back(get_registers(tid).rip);
}
for (const Mapping& map : read_maps(pid)) {
if (!is_executable(map) || map.perms.size() < 4 || map.perms[3] != 'p') {
continue;
}
if (map.path.empty() || map.path[0] == '[') {
continue; // skip [vdso], [vsyscall], anonymous mappings
}
for (std::uint64_t address = map.start;
address + kShellcode.size() <= map.end; address += 0x1000) {
bool busy = false;
for (const std::uint64_t rip : instruction_pointers) {
if (overlaps(address, rip, kShellcode.size())) {
busy = true;
break;
}
}
if (!busy) {
return address;
}
}
}
throw std::runtime_error("could not find a safe executable place to patch");
}
// Use the target's own stack, but keep clear of the red zone below rsp. If
// that region is not writable, fall back to the aligned rsp.
static std::uint64_t choose_stack_pointer(pid_t pid, std::uint64_t saved_rsp) {
if (saved_rsp > kStackMargin) {
const std::uint64_t candidate =
(saved_rsp - kStackMargin) & ~std::uint64_t{0xf};
if (address_is_writable(pid, candidate)) {
return candidate;
}
}
const std::uint64_t fallback = saved_rsp & ~std::uint64_t{0xf};
if (address_is_writable(pid, fallback)) {
return fallback;
}
throw std::runtime_error(
"target stack is not writable; refusing to continue");
}
// ---------------------------------------------------------------------------
// Remote calls
// ---------------------------------------------------------------------------
static std::uint64_t call_in_tracee(pid_t tid,
std::uint64_t shellcode_address,
std::uint64_t stack_pointer,
const user_regs_struct& saved_registers,
std::uint64_t function, std::uint64_t rdi,
std::uint64_t rsi) {
user_regs_struct regs = saved_registers;
// +2 skips the two NOPs. If resuming rewinds RIP by 2, execution starts at
// the NOPs instead, and the nop slide still reaches "call r9".
regs.rip = shellcode_address + 2;
regs.r9 = function;
regs.rdi = rdi;
regs.rsi = rsi;
// rsp must be 16-byte aligned before the call (x86-64 SysV ABI).
regs.rsp = stack_pointer;
set_registers(tid, regs);
continue_tracee(tid);
wait_for_trap(tid, shellcode_address + kShellcode.size());
return get_registers(tid).rax;
}
// ---------------------------------------------------------------------------
// Top-level injection
// ---------------------------------------------------------------------------
// Validate the library path before anything in the target is modified.
static std::string resolve_library_path(const std::string& library) {
std::string path;
try {
path = std::filesystem::canonical(library).string();
} catch (const std::filesystem::filesystem_error& error) {
throw std::runtime_error("cannot resolve library path '" + library +
"': " + error.what());
}
if (!std::filesystem::is_regular_file(path)) {
throw std::runtime_error("'" + path + "' is not a regular file");
}
path.push_back('\0');
return path;
}
void inject_process(pid_t pid, pid_t tracee,
const std::vector<pid_t>& threads,
const std::string& library, const LogSink* log) {
// Validate the library and the remote function addresses before patching.
const std::string path = resolve_library_path(library);
const LibcAddresses libc = find_libc_addresses(pid);
const std::uint64_t shellcode_address = find_patch_site(pid, threads);
log_debug(log, "remote malloc: 0x" + hex_string(libc.malloc) +
", dlopen: 0x" + hex_string(libc.dlopen) +
", free: 0x" + hex_string(libc.free));
const int memory_fd = open_target_memory(pid);
user_regs_struct saved_registers{};
std::array<std::uint8_t, kShellcode.size()> saved_bytes{};
std::uint64_t stack_pointer = 0;
bool patched = false;
try {
saved_registers = get_registers(tracee);
stack_pointer = choose_stack_pointer(pid, saved_registers.rsp);
read_memory(memory_fd, shellcode_address, saved_bytes.data(),
saved_bytes.size());
patched = true;
write_memory(memory_fd, shellcode_address, kShellcode.data(),
kShellcode.size());
log_debug(log, "patched shellcode at 0x" + hex_string(shellcode_address));
// 1. malloc() space in the target for the path.
const std::uint64_t remote_path =
call_in_tracee(tracee, shellcode_address, stack_pointer,
saved_registers, libc.malloc, path.size(), 0);
if (remote_path == 0) {
throw std::runtime_error("malloc inside tracee returned NULL");
}
log_debug(log, "remote malloc(" + std::to_string(path.size()) + ") = 0x" +
hex_string(remote_path));
write_memory(memory_fd, remote_path, path.data(), path.size());
// 2. dlopen(path, RTLD_LAZY).
const std::uint64_t handle =
call_in_tracee(tracee, shellcode_address, stack_pointer,
saved_registers, libc.dlopen, remote_path, RTLD_LAZY);
if (handle == 0) {
throw std::runtime_error("dlopen inside tracee returned NULL");
}
log_debug(log, "remote dlopen(\"" + library + "\") = 0x" +
hex_string(handle));
// 3. free() the path buffer. Failure is not fatal.
call_in_tracee(tracee, shellcode_address, stack_pointer, saved_registers,
libc.free, remote_path, 0);
log_debug(log, "remote free() done");
} catch (...) {
// Best effort: write both the bytes and the registers back.
if (patched) {
try {
write_memory(memory_fd, shellcode_address, saved_bytes.data(),
saved_bytes.size());
} catch (const std::exception& error) {
log_warn(log, "failed to restore code: " + std::string(error.what()));
}
try {
set_registers(tracee, saved_registers);
} catch (const std::exception& error) {
log_warn(log,
"failed to restore registers: " + std::string(error.what()));
}
}
close_target_memory(memory_fd);
throw;
}
try {
write_memory(memory_fd, shellcode_address, saved_bytes.data(),
saved_bytes.size());
set_registers(tracee, saved_registers);
} catch (...) {
close_target_memory(memory_fd);
throw;
}
close_target_memory(memory_fd);
log_info(log, "restored original code and registers");
}
+20
View File
@@ -0,0 +1,20 @@
#pragma once
#include <sys/types.h>
#include <string>
#include <vector>
#include "log.h"
// Load `library` into the already-stopped target process.
//
// `pid` is the target process, `tracee` is the specific (stopped) thread used
// to execute the remote calls, and `threads` is the full list of stopped
// threads (used to avoid patching code a thread is currently executing).
//
// Throws on failure. Any code/register modification is rolled back before the
// exception leaves this function.
void inject_process(pid_t pid, pid_t tracee,
const std::vector<pid_t>& threads,
const std::string& library, const LogSink* log);
+131
View File
@@ -0,0 +1,131 @@
#include "ptrace_inject.h"
#include <unistd.h>
#include <algorithm>
#include <cstddef>
#include <cstdio>
#include <exception>
#include <string>
#include <vector>
#include "inject.h"
#include "log.h"
#include "process_lookup.h"
#include "ptrace_utils.h"
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
static void write_error(char* error, std::size_t error_size,
const std::string& message) {
if (error != nullptr && error_size > 0) {
std::snprintf(error, error_size, "%s", message.c_str());
}
}
static LogSink make_log_sink(const ptrace_inject_options* options) {
LogSink sink;
if (options != nullptr) {
sink.fn = options->log_fn;
sink.user_data = options->log_user_data;
}
return sink;
}
// Shared implementation for both entry points. `pid` is already resolved.
static int inject_impl(pid_t pid, const char* library_path,
const ptrace_inject_options* options, char* error,
std::size_t error_size) {
if (library_path == nullptr || library_path[0] == '\0') {
write_error(error, error_size, "library path is null or empty");
return PTRACE_INJECT_ERROR;
}
if (pid <= 1) {
write_error(error, error_size,
"refusing to attach to pid " + std::to_string(pid));
return PTRACE_INJECT_ERROR;
}
if (pid == getpid()) {
write_error(error, error_size, "refusing to inject into the injector itself");
return PTRACE_INJECT_ERROR;
}
const LogSink log = make_log_sink(options);
std::vector<pid_t> attached;
try {
attach_all_threads(pid, attached, &log);
// Prefer the main thread, but any stopped thread works.
pid_t tracee = pid;
if (std::find(attached.begin(), attached.end(), tracee) ==
attached.end()) {
tracee = attached.front();
}
inject_process(pid, tracee, attached, library_path, &log);
detach_all_threads(attached, -1, 0, &log);
write_error(error, error_size, "");
log_info(&log, "injected " + std::string(library_path) + " into pid " +
std::to_string(pid));
return PTRACE_INJECT_OK;
} catch (const TraceeSignalError& caught) {
// Give the pending signal back to the thread instead of swallowing it.
detach_all_threads(attached, caught.tid, caught.signal, &log);
write_error(error, error_size, caught.what());
return PTRACE_INJECT_ERROR;
} catch (const std::exception& caught) {
detach_all_threads(attached, -1, 0, &log);
write_error(error, error_size, caught.what());
return PTRACE_INJECT_ERROR;
}
}
// ---------------------------------------------------------------------------
// Public API
// ---------------------------------------------------------------------------
extern "C" int ptrace_inject_by_pid(pid_t pid, const char* library_path,
const ptrace_inject_options* options,
char* error, std::size_t error_size) {
return inject_impl(pid, library_path, options, error, error_size);
}
extern "C" int ptrace_inject_by_name(const char* process_name,
const char* library_path,
const ptrace_inject_options* options,
pid_t* resolved_pid, char* error,
std::size_t error_size) {
if (process_name == nullptr || process_name[0] == '\0') {
write_error(error, error_size, "process name is null or empty");
return PTRACE_INJECT_ERROR;
}
const LogSink log = make_log_sink(options);
pid_t pid = -1;
try {
pid = find_pid_by_name(process_name);
} catch (const std::exception& caught) {
write_error(error, error_size, caught.what());
return PTRACE_INJECT_ERROR;
}
if (pid == -1) {
write_error(error, error_size,
"could not find process named '" + std::string(process_name) +
"'");
return PTRACE_INJECT_ERROR;
}
if (resolved_pid != nullptr) {
*resolved_pid = pid;
}
log_info(&log, "found pid " + std::to_string(pid) + " for name '" +
std::string(process_name) + "'");
return inject_impl(pid, library_path, options, error, error_size);
}
+19
View File
@@ -0,0 +1,19 @@
#include "log.h"
void log_message(const LogSink* sink, int level, const std::string& message) {
if (sink != nullptr && sink->fn != nullptr) {
sink->fn(level, message.c_str(), sink->user_data);
}
}
void log_debug(const LogSink* sink, const std::string& message) {
log_message(sink, PTRACE_INJECT_LOG_DEBUG, message);
}
void log_info(const LogSink* sink, const std::string& message) {
log_message(sink, PTRACE_INJECT_LOG_INFO, message);
}
void log_warn(const LogSink* sink, const std::string& message) {
log_message(sink, PTRACE_INJECT_LOG_WARN, message);
}
+17
View File
@@ -0,0 +1,17 @@
#pragma once
#include <string>
#include "ptrace_inject.h"
// Internal representation of ptrace_inject_options.
struct LogSink {
ptrace_inject_log_fn fn = nullptr;
void* user_data = nullptr;
};
// All of these do nothing when `sink` is null or `sink->fn` is null.
void log_message(const LogSink* sink, int level, const std::string& message);
void log_debug(const LogSink* sink, const std::string& message);
void log_info(const LogSink* sink, const std::string& message);
void log_warn(const LogSink* sink, const std::string& message);
+93
View File
@@ -0,0 +1,93 @@
#include "maps.h"
#include <filesystem>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <string>
#include "util.h"
bool is_executable(const Mapping& map) {
return map.perms.size() >= 3 && map.perms[2] == 'x';
}
bool is_writable(const Mapping& map) {
return map.perms.size() >= 2 && map.perms[1] == 'w';
}
std::vector<Mapping> read_maps(pid_t pid) {
const std::string file = "/proc/" + std::to_string(pid) + "/maps";
std::ifstream in(file);
if (!in) {
throw std::runtime_error("cannot open " + file);
}
std::vector<Mapping> maps;
std::string line;
while (std::getline(in, line)) {
std::istringstream iss(line);
std::string range;
std::string offset;
std::string dev;
std::string inode;
Mapping map;
if (!(iss >> range >> map.perms >> offset >> dev >> inode)) {
continue;
}
const auto dash = range.find('-');
if (dash == std::string::npos) {
continue;
}
try {
map.start = std::stoull(range.substr(0, dash), nullptr, 16);
map.end = std::stoull(range.substr(dash + 1), nullptr, 16);
map.inode = std::stoull(inode, nullptr, 10);
} catch (const std::exception&) {
continue;
}
map.dev = dev;
// The file name may contain spaces, so take the rest of the line.
std::string rest;
std::getline(iss, rest);
map.path = trim(rest);
maps.push_back(map);
}
return maps;
}
std::string file_name_of(const std::string& path) {
return std::filesystem::path(strip_deleted(path)).filename().string();
}
bool address_is_executable(pid_t pid, std::uint64_t address) {
for (const Mapping& map : read_maps(pid)) {
if (address >= map.start && address < map.end) {
return is_executable(map);
}
}
return false;
}
bool address_is_writable(pid_t pid, std::uint64_t address) {
for (const Mapping& map : read_maps(pid)) {
if (address >= map.start && address < map.end) {
return is_writable(map);
}
}
return false;
}
ObjectInfo find_object(pid_t pid, const std::string& object_name) {
for (const Mapping& map : read_maps(pid)) {
if (file_name_of(map.path) == object_name) {
return ObjectInfo{map.start, map.dev, map.inode};
}
}
throw std::runtime_error("could not find " + object_name + " in process " +
std::to_string(pid));
}
+38
View File
@@ -0,0 +1,38 @@
#pragma once
#include <sys/types.h>
#include <cstdint>
#include <string>
#include <vector>
// One line of /proc/<pid>/maps.
struct Mapping {
std::uint64_t start = 0;
std::uint64_t end = 0;
std::string dev;
std::uint64_t inode = 0;
std::string perms;
std::string path;
};
// Load base and file identity of a shared object in a given process.
struct ObjectInfo {
std::uint64_t base = 0;
std::string dev;
std::uint64_t inode = 0;
};
std::vector<Mapping> read_maps(pid_t pid);
bool is_executable(const Mapping& map);
bool is_writable(const Mapping& map);
std::string file_name_of(const std::string& path);
bool address_is_executable(pid_t pid, std::uint64_t address);
bool address_is_writable(pid_t pid, std::uint64_t address);
// Find the first mapping (file offset 0, i.e. the load base) of a shared
// object identified by its file name.
ObjectInfo find_object(pid_t pid, const std::string& object_name);
+69
View File
@@ -0,0 +1,69 @@
#include "memory.h"
#include <fcntl.h>
#include <unistd.h>
#include <cerrno>
#include <cstdint>
#include <stdexcept>
#include <string>
#include "util.h"
int open_target_memory(pid_t pid) {
const std::string path = "/proc/" + std::to_string(pid) + "/mem";
const int fd = open(path.c_str(), O_RDWR | O_CLOEXEC);
if (fd == -1) {
throw_errno("open " + path);
}
return fd;
}
void close_target_memory(int fd) {
if (fd >= 0) {
close(fd);
}
}
void read_memory(int fd, std::uint64_t address, void* buffer,
std::size_t length) {
auto* out = static_cast<std::uint8_t*>(buffer);
std::size_t done = 0;
while (done < length) {
const ssize_t n =
pread(fd, out + done, length - done, static_cast<off_t>(address + done));
if (n == -1) {
if (errno == EINTR) {
continue;
}
throw_errno("pread from target memory at 0x" +
hex_string(address + done));
}
if (n == 0) {
throw std::runtime_error("short read from target memory at 0x" +
hex_string(address + done));
}
done += static_cast<std::size_t>(n);
}
}
void write_memory(int fd, std::uint64_t address, const void* buffer,
std::size_t length) {
const auto* in = static_cast<const std::uint8_t*>(buffer);
std::size_t done = 0;
while (done < length) {
const ssize_t n = pwrite(fd, in + done, length - done,
static_cast<off_t>(address + done));
if (n == -1) {
if (errno == EINTR) {
continue;
}
throw_errno("pwrite to target memory at 0x" + hex_string(address + done));
}
if (n == 0) {
throw std::runtime_error("short write to target memory at 0x" +
hex_string(address + done));
}
done += static_cast<std::size_t>(n);
}
}
+17
View File
@@ -0,0 +1,17 @@
#pragma once
#include <sys/types.h>
#include <cstddef>
#include <cstdint>
// Open /proc/<pid>/mem for reading and writing.
// The process must already be ptrace-stopped.
int open_target_memory(pid_t pid);
void close_target_memory(int fd);
void read_memory(int fd, std::uint64_t address, void* buffer, std::size_t length);
void write_memory(int fd, std::uint64_t address, const void* buffer,
std::size_t length);
@@ -0,0 +1,46 @@
#include "process_lookup.h"
#include <limits.h>
#include <unistd.h>
#include <filesystem>
#include <stdexcept>
#include <string>
#include "util.h"
pid_t find_pid_by_name(const std::string& name) {
std::error_code ec;
std::filesystem::directory_iterator iterator("/proc", ec);
const std::filesystem::directory_iterator end;
if (ec) {
throw std::runtime_error("cannot open /proc: " + ec.message());
}
for (; iterator != end; iterator.increment(ec)) {
if (ec) {
break;
}
const std::string pid_text = iterator->path().filename().string();
if (!all_digits(pid_text)) {
continue;
}
char buffer[PATH_MAX + 1] = {};
const ssize_t length =
readlink((iterator->path() / "exe").c_str(), buffer, PATH_MAX);
if (length <= 0) {
continue; // usually a permission problem
}
buffer[length] = '\0';
const std::string executable = strip_deleted(buffer);
const std::string executable_name =
std::filesystem::path(executable).filename().string();
if (executable_name == name || executable == name) {
return static_cast<pid_t>(std::stoi(pid_text));
}
}
return -1;
}
@@ -0,0 +1,9 @@
#pragma once
#include <sys/types.h>
#include <string>
// Return the PID of the first process whose executable path or file name is
// `name`, or -1 if no process matches.
pid_t find_pid_by_name(const std::string& name);
@@ -0,0 +1,191 @@
#include "ptrace_utils.h"
#include <sys/ptrace.h>
#include <sys/wait.h>
#include <signal.h>
#include <unistd.h>
#include <algorithm>
#include <cerrno>
#include <cstdint>
#include <cstring>
#include <filesystem>
#include <stdexcept>
#include <string>
#include <vector>
#include "config.h"
#include "log.h"
#include "util.h"
#ifndef __WALL
#define __WALL 0x40000000
#endif
user_regs_struct get_registers(pid_t tid) {
user_regs_struct regs{};
if (ptrace(PTRACE_GETREGS, tid, nullptr, &regs) == -1) {
throw_errno("PTRACE_GETREGS on tid " + std::to_string(tid));
}
return regs;
}
void set_registers(pid_t tid, const user_regs_struct& regs) {
user_regs_struct copy = regs;
if (ptrace(PTRACE_SETREGS, tid, nullptr, &copy) == -1) {
throw_errno("PTRACE_SETREGS on tid " + std::to_string(tid));
}
}
void continue_tracee(pid_t tid) {
// The last argument is the signal to deliver. 0 suppresses the SIGTRAP
// from int3 (and the SIGSTOP from PTRACE_ATTACH).
if (ptrace(PTRACE_CONT, tid, nullptr, nullptr) == -1) {
throw_errno("PTRACE_CONT on tid " + std::to_string(tid));
}
}
void wait_for_trap(pid_t tid, std::uint64_t expected_rip) {
int status = 0;
for (;;) {
pid_t waited;
do {
waited = waitpid(tid, &status, __WALL);
} while (waited == -1 && errno == EINTR);
if (waited == -1) {
throw_errno("waitpid on tid " + std::to_string(tid));
}
if (WIFEXITED(status)) {
throw std::runtime_error("tracee exited with status " +
std::to_string(WEXITSTATUS(status)));
}
if (WIFSIGNALED(status)) {
throw std::runtime_error("tracee was killed by signal " +
std::to_string(WTERMSIG(status)));
}
if (!WIFSTOPPED(status)) {
continue;
}
const int signal = WSTOPSIG(status);
if (signal == SIGTRAP) {
// Only accept the SIGTRAP generated by our own int3. On x86-64 RIP
// points just past the int3 instruction at that stop.
const user_regs_struct regs = get_registers(tid);
if (regs.rip == expected_rip) {
return;
}
throw TraceeSignalError(
tid, signal,
"unexpected SIGTRAP at rip=0x" + hex_string(regs.rip) +
" (expected 0x" + hex_string(expected_rip) + ")");
}
const user_regs_struct regs = get_registers(tid);
throw TraceeSignalError(tid, signal,
"shellcode in tracee received unexpected signal " +
std::to_string(signal) + " (" +
strsignal(signal) + ") at rip=0x" +
hex_string(regs.rip));
}
}
static std::vector<pid_t> list_threads(pid_t pid) {
const std::string directory = "/proc/" + std::to_string(pid) + "/task";
std::error_code ec;
std::filesystem::directory_iterator iterator(directory, ec);
const std::filesystem::directory_iterator end;
if (ec) {
throw std::runtime_error("cannot list threads of pid " +
std::to_string(pid) + ": " + ec.message());
}
std::vector<pid_t> threads;
for (; iterator != end; iterator.increment(ec)) {
if (ec) {
break;
}
const std::string name = iterator->path().filename().string();
if (!all_digits(name)) {
continue;
}
try {
threads.push_back(static_cast<pid_t>(std::stoi(name)));
} catch (const std::exception&) {
continue;
}
}
std::sort(threads.begin(), threads.end());
return threads;
}
static bool attach_one_thread(pid_t tid, std::vector<pid_t>& attached) {
if (ptrace(PTRACE_ATTACH, tid, nullptr, nullptr) == -1) {
if (errno == ESRCH) {
return false; // thread exited while we were enumerating
}
throw_errno("PTRACE_ATTACH on tid " + std::to_string(tid));
}
// Record it before waiting: if waitpid fails, the thread is still attached
// and the caller must be able to detach it.
attached.push_back(tid);
int status = 0;
pid_t waited;
do {
waited = waitpid(tid, &status, __WALL);
} while (waited == -1 && errno == EINTR);
if (waited == -1) {
throw_errno("waitpid after attaching to tid " + std::to_string(tid));
}
if (!WIFSTOPPED(status)) {
throw std::runtime_error("thread " + std::to_string(tid) +
" did not stop after PTRACE_ATTACH");
}
return true;
}
void attach_all_threads(pid_t pid, std::vector<pid_t>& attached,
const LogSink* log) {
// A running target can create threads while we are attaching, so re-scan
// until there is nothing new to attach.
for (int round = 0; round < kMaxAttachRounds; ++round) {
bool attached_anything = false;
for (const pid_t tid : list_threads(pid)) {
if (std::find(attached.begin(), attached.end(), tid) != attached.end()) {
continue;
}
if (attach_one_thread(tid, attached)) {
attached_anything = true;
}
}
if (!attached_anything) {
break;
}
}
if (attached.empty()) {
throw std::runtime_error("could not attach to any thread");
}
log_info(log, "attached to " + std::to_string(attached.size()) +
" thread(s) of pid " + std::to_string(pid));
}
void detach_all_threads(std::vector<pid_t>& attached, pid_t signal_tid,
int signal, const LogSink* log) {
for (const pid_t tid : attached) {
void* data = nullptr;
if (tid == signal_tid && signal != 0) {
data = reinterpret_cast<void*>(static_cast<intptr_t>(signal));
}
if (ptrace(PTRACE_DETACH, tid, nullptr, data) == -1 && errno != ESRCH) {
const int err = errno;
log_warn(log, "PTRACE_DETACH on tid " + std::to_string(tid) +
" failed: " + std::strerror(err));
}
}
attached.clear();
}
@@ -0,0 +1,37 @@
#pragma once
#include <sys/types.h>
#include <sys/user.h>
#include <cstdint>
#include <stdexcept>
#include <string>
#include <vector>
#include "log.h"
// Thrown when the tracee stops with a signal that is not our int3 SIGTRAP.
// main() uses it to deliver that signal back to the target on detach.
struct TraceeSignalError : public std::runtime_error {
TraceeSignalError(pid_t tracee, int signo, const std::string& what)
: std::runtime_error(what), tid(tracee), signal(signo) {}
pid_t tid;
int signal;
};
user_regs_struct get_registers(pid_t tid);
void set_registers(pid_t tid, const user_regs_struct& regs);
void continue_tracee(pid_t tid);
// Wait for our int3. expected_rip must be kShellcodeAddress + kShellcode.size().
void wait_for_trap(pid_t tid, std::uint64_t expected_rip);
// Stop every thread of `pid`; on return all of them are ptrace-stopped.
void attach_all_threads(pid_t pid, std::vector<pid_t>& attached,
const LogSink* log);
// Detach all threads. If signal != 0, deliver it to signal_tid on detach.
void detach_all_threads(std::vector<pid_t>& attached, pid_t signal_tid,
int signal, const LogSink* log);
@@ -0,0 +1,66 @@
#include "symbols.h"
#include <dlfcn.h>
#include <unistd.h>
#include <cstdint>
#include <stdexcept>
#include <string>
#include "maps.h"
#include "util.h"
struct SymbolAddress {
const char* name;
std::uint64_t address;
std::string object;
};
static SymbolAddress resolve_symbol(const char* name) {
dlerror(); // clear any previous error
void* address = dlsym(RTLD_DEFAULT, name);
if (const char* error = dlerror()) {
throw std::runtime_error(std::string("dlsym(") + name + ") failed: " +
error);
}
Dl_info info{};
if (dladdr(address, &info) == 0 || info.dli_fname == nullptr) {
throw std::runtime_error(std::string("dladdr(") + name + ") failed");
}
return SymbolAddress{name, reinterpret_cast<std::uint64_t>(address),
file_name_of(info.dli_fname)};
}
// Translate one local symbol address into the target's address space.
//
// malloc/free are in libc.so.6; dlopen is in libc.so.6 on new glibc and in
// libdl.so.2 on old glibc. dladdr() tells us which object owns the symbol.
static std::uint64_t relocate_symbol(const SymbolAddress& symbol,
pid_t target_pid) {
const ObjectInfo local = find_object(getpid(), symbol.object);
const ObjectInfo target = find_object(target_pid, symbol.object);
if (local.dev != target.dev || local.inode != target.inode) {
throw std::runtime_error(
std::string("injector and target use different builds of ") +
symbol.object + "; refusing to guess the address of " + symbol.name);
}
const std::uint64_t address = symbol.address - local.base + target.base;
if (!address_is_executable(target_pid, address)) {
throw std::runtime_error(std::string("relocated ") + symbol.name +
" is not executable in the target; refusing to "
"continue");
}
return address;
}
LibcAddresses find_libc_addresses(pid_t target_pid) {
return LibcAddresses{
relocate_symbol(resolve_symbol("malloc"), target_pid),
relocate_symbol(resolve_symbol("dlopen"), target_pid),
relocate_symbol(resolve_symbol("free"), target_pid),
};
}
+20
View File
@@ -0,0 +1,20 @@
#pragma once
#include <sys/types.h>
#include <cstdint>
// Addresses of the libc functions we need, already relocated into the target.
struct LibcAddresses {
std::uint64_t malloc = 0;
std::uint64_t dlopen = 0;
std::uint64_t free = 0;
};
// Resolve malloc/dlopen/free locally and translate their addresses into the
// address space of `target_pid`.
//
// Refuses to continue (throws) if the injector and the target use different
// builds of the owning shared object, or if a relocated address is not
// executable there.
LibcAddresses find_libc_addresses(pid_t target_pid);
+44
View File
@@ -0,0 +1,44 @@
#include "util.h"
#include <algorithm>
#include <cctype>
#include <cerrno>
#include <cstring>
#include <sstream>
#include <stdexcept>
void throw_errno(const std::string& what) {
const int err = errno;
throw std::runtime_error(what + ": " + std::strerror(err));
}
bool all_digits(const std::string& text) {
return !text.empty() &&
std::all_of(text.begin(), text.end(), [](unsigned char c) {
return std::isdigit(c) != 0;
});
}
std::string strip_deleted(std::string path) {
static const std::string suffix = " (deleted)";
if (path.size() > suffix.size() &&
path.compare(path.size() - suffix.size(), suffix.size(), suffix) == 0) {
path.resize(path.size() - suffix.size());
}
return path;
}
std::string trim(std::string text) {
const auto begin = text.find_first_not_of(" \t\r\n");
if (begin == std::string::npos) {
return {};
}
const auto end = text.find_last_not_of(" \t\r\n");
return text.substr(begin, end - begin + 1);
}
std::string hex_string(std::uint64_t value) {
std::ostringstream out;
out << std::hex << value;
return out.str();
}
+16
View File
@@ -0,0 +1,16 @@
#pragma once
#include <cstdint>
#include <string>
// Throw std::runtime_error with strerror(errno) appended.
[[noreturn]] void throw_errno(const std::string& what);
bool all_digits(const std::string& text);
// Remove the " (deleted)" suffix that /proc/<pid>/maps adds to unlinked files.
std::string strip_deleted(std::string path);
std::string trim(std::string text);
std::string hex_string(std::uint64_t value);
+2 -1
View File
@@ -2,5 +2,6 @@
if(WIN32)
add_executable(injector injector.c)
else()
add_executable(injector injector_linux.c)
add_executable(injector injector_linux.cpp)
target_link_libraries(injector PRIVATE ptrace_inject::ptrace_inject)
endif()
-10
View File
@@ -1,10 +0,0 @@
#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;
}
+115
View File
@@ -0,0 +1,115 @@
#include <limits.h>
#include <unistd.h>
#include <cstdio>
#include <cstdlib>
#include <exception>
#include <stdexcept>
#include <string>
#include "ptrace_inject.h"
static void print_log(int level, const char* message, void* /*user_data*/) {
const char* prefix = "[*]";
switch (level) {
case PTRACE_INJECT_LOG_DEBUG:
prefix = "[debug]";
break;
case PTRACE_INJECT_LOG_INFO:
prefix = "[*]";
break;
case PTRACE_INJECT_LOG_WARN:
prefix = "[!]";
break;
case PTRACE_INJECT_LOG_ERROR:
prefix = "[error]";
break;
default:
break;
}
std::fprintf(stderr, "%s %s\n", prefix, message);
}
static void usage(const char* program) {
std::fprintf(stderr,
"Usage: %s (-p PID | -n NAME) <library.so>\n"
"\n"
"Inject a shared library into a running x86-64 Linux process.\n"
"\n"
" -p PID attach to this PID\n"
" -n NAME attach to the first process whose executable name\n"
" or path matches NAME\n"
" -h show this help\n"
"\n"
"Requires the same uid and CAP_SYS_PTRACE, or a suitable\n"
"kernel.yama.ptrace_scope setting.\n"
"\n"
"Example: %s -p 123456 ./libloader.so\n"
"\n"
"Default runtime directory: ${HOME}/.juiceagent/ \n"
"See README for more information.\n",
program, program);
}
int main(int argc, char** argv) {
pid_t pid = -1;
std::string name;
int option;
while ((option = getopt(argc, argv, "p:n:h")) != -1) {
switch (option) {
case 'p': {
try {
const long value = std::stol(optarg);
if (value <= 0 || value > INT_MAX) {
throw std::out_of_range("pid");
}
pid = static_cast<pid_t>(value);
} catch (const std::exception&) {
std::fprintf(stderr, "error: invalid pid '%s'\n", optarg);
return 1;
}
break;
}
case 'n':
name = optarg;
break;
case 'h':
usage(argv[0]);
return 0;
default:
usage(argv[0]);
return 1;
}
}
if (optind + 1 != argc) {
usage(argv[0]);
return 1;
}
const char* library = argv[optind];
if ((pid == -1) == name.empty()) {
std::fprintf(stderr, "error: specify exactly one of -p PID or -n NAME\n");
usage(argv[0]);
return 1;
}
ptrace_inject_options options{};
options.log_fn = print_log;
char error[512] = {};
int result;
if (!name.empty()) {
result = ptrace_inject_by_name(name.c_str(), library, &options, nullptr,
error, sizeof(error));
} else {
result = ptrace_inject_by_pid(pid, library, &options, error, sizeof(error));
}
if (result != PTRACE_INJECT_OK) {
std::fprintf(stderr, "error: %s\n", error);
return 1;
}
return 0;
}
+14
View File
@@ -0,0 +1,14 @@
# Integration test programs, one per line. Blank lines and # comments are ignored.
# Shared by run-tests.ps1 (Windows) and run-tests.sh (Linux).
GetClassByName
GetLoadedClasses
GetClassBytes
GetClassBytesByName
DefineClass
RedefineClass
RedefineClassByName
RetransformClass
RetransformClassByName
AddToClassLoader
AddToSystemClassLoaderSearch
AddToBootstrapClassLoaderSearch
+24
View File
@@ -0,0 +1,24 @@
#!/usr/bin/env bash
#
# Refresh tests/resources with the freshly built native binaries (Linux).
#
# Mirror of tests/copy-bin.bat: always operates relative to this script and
# fails loudly when there is nothing to copy.
set -euo pipefail
here="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$here"
mkdir -p resources
shopt -s nullglob
libs=(../build/bin/*.so)
if (( ${#libs[@]} == 0 )); then
echo "[ERROR] No shared libraries found in ../build/bin." >&2
echo " Build the project first: cmake --build build" >&2
exit 1
fi
cp -f "${libs[@]}" resources/
echo "[SUCCESS] Copied build binaries to tests/resources."
+18 -22
View File
@@ -8,7 +8,10 @@
The test programs always exit 0, even when a step fails (e.g. a bad config
or a missing class is printed but the process still returns 0), so exit
codes alone are not enough - we match an expected marker per test.
codes alone are not enough. Instead every test prints a single verdict line
("RESULT: PASS <name>" / "RESULT: FAIL <name>: ...") and we match that.
The case list lives in tests/cases.txt and is shared with run-tests.sh.
Requires the native binaries in build/bin; run `cmake --build build` first.
@@ -113,36 +116,29 @@ try {
if ($LASTEXITCODE -ne 0) { throw "copy-bin.bat failed." }
# --- 4. Compile the tests ---------------------------------------------
# Loop.java is a manual demo (infinite loop), not a test case.
$testsOut = "out\production\tests"
New-Item -ItemType Directory -Force -Path $testsOut | Out-Null
$testSources = (Get-ChildItem "src" -Filter *.java).FullName
$testSources = (Get-ChildItem "src" -Filter *.java |
Where-Object { $_.Name -ne "Loop.java" }).FullName
& $javac -cp $apiJar -d $testsOut $testSources
if ($LASTEXITCODE -ne 0) { throw "Compiling the tests failed." }
# --- 5. Run every test and assert on a marker -------------------------
# --- 5. Run every test and assert on its verdict ----------------------
$classpath = "$testsOut;$apiJar"
$cases = @(
@{ Name = "GetClassByName"; Expect = "class java\.lang\.String" },
@{ Name = "GetLoadedClasses"; Expect = "class " },
@{ Name = "GetClassBytes"; Expect = "Bytes: 399" },
@{ Name = "GetClassBytesByName"; Expect = "Bytes: 399" },
@{ Name = "DefineClass"; Expect = "Injection Invoked!" },
@{ Name = "RedefineClass"; Expect = "Modified!" },
@{ Name = "RedefineClassByName"; Expect = "Modified!" },
@{ Name = "RetransformClass"; Expect = "Modified!" },
@{ Name = "RetransformClassByName"; Expect = "Modified!" },
@{ Name = "AddToClassLoader"; Expect = "Injection Invoked!" },
@{ Name = "AddToSystemClassLoaderSearch"; Expect = "Injection Invoked!" },
@{ Name = "AddToBootstrapClassLoaderSearch"; Expect = "Injection Invoked!" }
)
$cases = Get-Content (Join-Path $TestsDir "cases.txt") |
ForEach-Object { $_.Split('#')[0].Trim() } |
Where-Object { $_ -ne "" }
if ($cases.Count -eq 0) { throw "No test cases found in tests/cases.txt." }
$failed = @()
foreach ($case in $cases) {
$output = (& $java @nativeAccessArgs -cp $classpath $case.Name 2>&1 | Out-String)
if ($output -match $case.Expect) {
Write-Host (" [PASS] {0}" -f $case.Name) -ForegroundColor Green
$output = (& $java @nativeAccessArgs -cp $classpath $case 2>&1 | Out-String)
$verdict = "RESULT: PASS $case"
if ($output -match [regex]::Escape($verdict) -and $output -notmatch "RESULT: FAIL") {
Write-Host (" [PASS] {0}" -f $case) -ForegroundColor Green
} else {
Write-Host (" [FAIL] {0} (expected /{1}/)" -f $case.Name, $case.Expect) -ForegroundColor Red
Write-Host (" [FAIL] {0} (expected `"$verdict`")" -f $case) -ForegroundColor Red
# Show what the test actually printed so failures are diagnosable
# (the test programs exit 0 even when a step fails).
$lines = @($output -split "`r?`n" | Where-Object { $_.Trim() })
@@ -152,7 +148,7 @@ try {
if ($lines.Count -gt 25) {
Write-Host (" | ... ({0} more lines)" -f ($lines.Count - 25)) -ForegroundColor DarkGray
}
$failed += $case.Name
$failed += $case
}
}
+128
View File
@@ -0,0 +1,128 @@
#!/usr/bin/env bash
#
# Build and run the JuiceAgent integration tests on Linux.
#
# Mirror of tests/run-tests.ps1: compiles the injection + test modules,
# refreshes tests/resources from build/bin, then runs every case listed in
# tests/cases.txt and asserts on the RESULT: PASS/FAIL verdict each prints
# (the test programs always exit 0, even on failure - see AGENTS.md rule 5).
#
# Requires the native binaries in build/bin; run `cmake --build build` first.
#
# Usage:
# bash tests/run-tests.sh
# JAVA_HOME=/path/to/jdk bash tests/run-tests.sh
set -euo pipefail
tests_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
repo_root="$(cd "$tests_dir/.." && pwd)"
# --- Locate JDK tools ------------------------------------------------------
if [[ -n "${JAVA_HOME:-}" ]]; then
java="$JAVA_HOME/bin/java"
javac="$JAVA_HOME/bin/javac"
jar="$JAVA_HOME/bin/jar"
else
java="$(command -v java || true)"
javac="$(command -v javac || true)"
jar="$(command -v jar || true)"
fi
for tool in "$java" "$javac" "$jar"; do
if [[ -z "$tool" || ! -x "$tool" ]]; then
echo "JDK tools not found. Install a JDK (17+) and put it on PATH, or set JAVA_HOME." >&2
exit 1
fi
done
# --- JDK version -> native-access flag -------------------------------------
# --enable-native-access exists since JDK 22 and is needed to silence the JNI
# warnings added in JDK 24.
version_text="$("$java" -version 2>&1)"
if [[ "$version_text" =~ version\ \"([0-9]+) ]]; then
java_major="${BASH_REMATCH[1]}"
else
echo "Could not parse the Java version from: $version_text" >&2
exit 1
fi
if (( java_major < 17 )); then
echo "JDK $java_major is too old; the tests need JDK 17+." >&2
exit 1
fi
native_access_args=()
if (( java_major >= 22 )); then
native_access_args=("--enable-native-access=ALL-UNNAMED")
fi
# --- Locate the JuiceAgent API jar -----------------------------------------
api_jar="$(find "$tests_dir/lib" -maxdepth 1 -name 'JuiceAgent-API-*.jar' -print -quit)"
if [[ -z "$api_jar" ]]; then
echo "JuiceAgent API jar not found under tests/lib." >&2
exit 1
fi
# --- Require native binaries ----------------------------------------------
bin_dir="$repo_root/build/bin"
if [[ ! -f "$bin_dir/libagent.so" ]]; then
echo "Missing libagent.so in build/bin. Build the native binaries first: cmake --build build" >&2
exit 1
fi
echo "=== JuiceAgent integration tests ==="
echo "JDK: $java (major $java_major)"
echo "API jar: $api_jar"
echo "Binaries: $bin_dir"
echo
cd "$tests_dir"
# --- 1. Compile the injection module (used by redefine/retransform) --------
injection_out="out/production/injection"
mkdir -p "$injection_out"
"$javac" -d "$injection_out" injection/src/*.java
# --- 2. Rebuild injection.jar (used by the AddTo* tests) -------------------
"$jar" cf injection.jar -C "$injection_out" .
# --- 3. Refresh tests/resources from build/bin -----------------------------
bash copy-bin.sh
# --- 4. Compile the tests (Loop.java is a manual demo, not a test) ---------
tests_out="out/production/tests"
mkdir -p "$tests_out"
test_sources=()
for src in src/*.java; do
[[ "$(basename "$src")" == "Loop.java" ]] && continue
test_sources+=("$src")
done
"$javac" -cp "$api_jar" -d "$tests_out" "${test_sources[@]}"
# --- 5. Run every case and assert on the verdict ---------------------------
classpath="$tests_out:$api_jar"
failed=()
total=0
while IFS= read -r case_name || [[ -n "$case_name" ]]; do
case_name="${case_name%%#*}" # strip comments
case_name="$(printf '%s' "$case_name" | xargs)" # trim
[[ -z "$case_name" ]] && continue
total=$((total + 1))
output="$("$java" "${native_access_args[@]}" -cp "$classpath" "$case_name" 2>&1 || true)"
if grep -q "RESULT: PASS $case_name" <<<"$output" && ! grep -q "RESULT: FAIL" <<<"$output"; then
printf ' [PASS] %s\n' "$case_name"
else
printf ' [FAIL] %s (expected "RESULT: PASS %s")\n' "$case_name" "$case_name"
head -n 25 <<<"$output" | sed 's/^/ | /'
failed+=("$case_name")
fi
done < cases.txt
echo
if (( ${#failed[@]} > 0 )); then
echo "${#failed[@]}/$total tests failed: ${failed[*]}" >&2
exit 1
fi
echo "All $total tests passed."
+12 -24
View File
@@ -1,34 +1,22 @@
import java.io.File;
import cn.xiaozhou233.juiceagent.api.JuiceAgent;
public class AddToBootstrapClassLoaderSearch {
public static void main(String[] args) {
System.load(new File("resources/libagent.dll").getAbsolutePath());
JuiceAgent.init("");
TestSupport.run("AddToBootstrapClassLoaderSearch", () -> {
TestSupport.bootstrap();
System.out.println("========= Before =========");
invokeTest();
System.out.println("========= After =========");
JuiceAgent.addToBootstrapClassLoaderSearch(new File("Injection.jar").getAbsolutePath());
invokeTest();
System.out.println("========= Done =========");
TestSupport.require(JuiceAgent.addToBootstrapClassLoaderSearch(TestSupport.injectionJar()),
"addToBootstrapClassLoaderSearch returned false");
}
public static void invokeTest() {
try {
Class<?> clazz = Class.forName("Injection");
ClassLoader loader = clazz.getClassLoader();
System.out.println("ClassLoader: " + (loader == null ? "BootstrapClassLoader" : loader));
clazz.getMethod("test").invoke(null);
} catch (ClassNotFoundException e) {
System.err.println("Injection class not found: " + e.getMessage());
TestSupport.require(clazz.getClassLoader() == null,
"Injection was not loaded by the bootstrap loader");
} catch (ReflectiveOperationException e) {
System.err.println("Invoke failed: " + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
String out = TestSupport.capture(() -> TestSupport.invokeStatic(clazz, "test"));
TestSupport.require(out.contains("Injection Invoked!"),
"Injection.test() did not run: " + out);
System.out.println("ClassLoader: BootstrapClassLoader");
});
}
}
+14 -21
View File
@@ -1,30 +1,23 @@
import cn.xiaozhou233.juiceagent.api.JuiceAgent;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
public class AddToClassLoader {
public static void main(String[] args) throws ClassNotFoundException, NoSuchMethodException, InvocationTargetException, IllegalAccessException {
System.load(new File("resources/libagent.dll").getAbsolutePath());
JuiceAgent.init("");
public static void main(String[] args) {
TestSupport.run("AddToClassLoader", () -> {
TestSupport.bootstrap();
ClassLoader cl = new ClassLoader(){};
ClassLoader cl = new ClassLoader() {};
invokeTest(cl);
TestSupport.require(JuiceAgent.addToClassLoader(TestSupport.injectionJar(), cl),
"addToClassLoader returned false");
JuiceAgent.addToClassLoader(new File("Injection.jar").getAbsolutePath(), cl);
// A plain ClassLoader is not a URLClassLoader, so the API falls back
// to appending the jar to the system class loader search path.
Class<?> clazz = cl.loadClass("Injection");
String out = TestSupport.capture(() -> TestSupport.invokeStatic(clazz, "test"));
TestSupport.require(out.contains("Injection Invoked!"),
"Injection.test() did not run: " + out);
invokeTest(cl);
}
public static void invokeTest(ClassLoader cl) {
try {
Class<?> clz = cl.loadClass("Injection");
System.out.println("ClassLoader: " + clz.getClassLoader().toString());
clz.getMethod("test").invoke(null);
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("ClassLoader: " + clazz.getClassLoader());
});
}
}
+9 -24
View File
@@ -1,34 +1,19 @@
import java.io.File;
import cn.xiaozhou233.juiceagent.api.JuiceAgent;
public class AddToSystemClassLoaderSearch {
public static void main(String[] args) {
System.load(new File("resources/libagent.dll").getAbsolutePath());
JuiceAgent.init("");
TestSupport.run("AddToSystemClassLoaderSearch", () -> {
TestSupport.bootstrap();
System.out.println("========= Before =========");
invokeTest();
System.out.println("========= After =========");
JuiceAgent.addToSystemClassLoaderSearch(new File("Injection.jar").getAbsolutePath());
invokeTest();
System.out.println("========= Done =========");
TestSupport.require(JuiceAgent.addToSystemClassLoaderSearch(TestSupport.injectionJar()),
"addToSystemClassLoaderSearch returned false");
}
public static void invokeTest() {
try {
Class<?> clazz = Class.forName("Injection");
ClassLoader loader = clazz.getClassLoader();
System.out.println("ClassLoader: " + loader);
clazz.getMethod("test").invoke(null);
} catch (ClassNotFoundException e) {
System.err.println("Injection class not found: " + e.getMessage());
String out = TestSupport.capture(() -> TestSupport.invokeStatic(clazz, "test"));
TestSupport.require(out.contains("Injection Invoked!"),
"Injection.test() did not run: " + out);
} catch (ReflectiveOperationException e) {
System.err.println("Invoke failed: " + e.getMessage());
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("ClassLoader: " + clazz.getClassLoader());
});
}
}
+14 -24
View File
@@ -1,34 +1,24 @@
import cn.xiaozhou233.juiceagent.api.JuiceAgent;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
public class DefineClass {
public static void main(String[] args) throws IOException {
System.load(new File("resources/libagent.dll").getAbsolutePath());
JuiceAgent.init("");
public static void main(String[] args) {
TestSupport.run("DefineClass", () -> {
TestSupport.bootstrap();
ClassLoader cl = new ClassLoader() {};
ClassLoader cl = new ClassLoader() {};
invokeTest(cl);
byte[] bytes = TestSupport.readClass("Injection");
System.out.println("Read bytes: " + bytes.length);
byte[] bytes = Files.readAllBytes(new File("out/production/injection/Injection.class").toPath());
System.out.println("Read bytes: " + bytes.length);
Class<?> clazz = JuiceAgent.defineClass(cl, bytes);
TestSupport.require(clazz != null, "defineClass returned null");
TestSupport.require(clazz.getClassLoader() == cl, "defined class has the wrong class loader");
JuiceAgent.defineClass(cl, bytes);
String out = TestSupport.capture(() -> TestSupport.invokeStatic(clazz, "test"));
TestSupport.require(out.contains("Injection Invoked!"),
"Injection.test() did not run: " + out);
invokeTest(cl);
}
public static void invokeTest(ClassLoader cl) {
try {
Class<?> clazz = cl.loadClass("Injection");
clazz.getMethod("test").invoke(null);
System.out.println("ClassLoader: " + clazz.getClassLoader().toString());
} catch (Exception e) {
e.printStackTrace();
}
System.out.println("ClassLoader: " + clazz.getClassLoader());
});
}
}
+8 -9
View File
@@ -1,17 +1,16 @@
import cn.xiaozhou233.juiceagent.api.JuiceAgent;
import java.io.File;
import java.util.Arrays;
public class GetClassByName {
public static void main(String[] args) {
System.load(new File("resources/libagent.dll").getAbsolutePath());
JuiceAgent.init("");
TestSupport.run("GetClassByName", () -> {
TestSupport.bootstrap();
Class<?> clazz = JuiceAgent.getClassByName("java.lang.String");
Class<?> clazz = JuiceAgent.getClassByName("java.lang.String");
TestSupport.require(clazz != null, "getClassByName returned null");
TestSupport.require(clazz == String.class, "resolved a different Class instance");
System.out.println(clazz);
System.out.println(clazz.getName());
System.out.println(Arrays.toString(clazz.getDeclaredMethods()));
System.out.println("Class: " + clazz);
System.out.println("Name: " + clazz.getName());
});
}
}
+10 -23
View File
@@ -1,29 +1,16 @@
import cn.xiaozhou233.juiceagent.api.JuiceAgent;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
public class GetClassBytes {
public static void main(String[] args) throws IOException {
System.load(new File("resources/libagent.dll").getAbsolutePath());
JuiceAgent.init("");
public static void main(String[] args) {
TestSupport.run("GetClassBytes", () -> {
TestSupport.bootstrap();
byte[] bytes = JuiceAgent.getClassBytes(Target.class);
byte[] bytes = JuiceAgent.getClassBytes(Target.class);
TestSupport.require(TestSupport.looksLikeClassFile(bytes),
"getClassBytes did not return a class file");
File output = new File("tmp", Target.class.getName().replace('.', '/') + ".class");
File parent = output.getParentFile();
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
try (FileOutputStream fos = new FileOutputStream(output)) {
fos.write(bytes);
}
System.out.println("Class: " + Target.class.getName());
System.out.println("Bytes: " + bytes.length);
System.out.println("Saved: " + output.getAbsolutePath());
System.out.println("Class: " + Target.class.getName());
System.out.println("Bytes: OK (" + bytes.length + ")");
});
}
}
}
+14 -33
View File
@@ -1,40 +1,21 @@
import cn.xiaozhou233.juiceagent.api.JuiceAgent;
import java.io.File;
import java.io.FileOutputStream;
public class GetClassBytesByName {
public static void main(String[] args) throws Exception {
System.load(new File("resources/libagent.dll").getAbsolutePath());
JuiceAgent.init("");
public static void main(String[] args) {
TestSupport.run("GetClassBytesByName", () -> {
TestSupport.bootstrap();
// getClassBytesByName only resolves classes that are already loaded,
// so make sure the target class is loaded before looking it up.
Class.forName("Target");
// getClassBytesByName only resolves classes that are already loaded,
// so make sure the target class is loaded before looking it up.
Class.forName("Target");
String className = "Target";
byte[] bytes = JuiceAgent.getClassBytesByName(className);
String className = "Target";
byte[] bytes = JuiceAgent.getClassBytesByName(className);
TestSupport.require(TestSupport.looksLikeClassFile(bytes),
"getClassBytesByName did not return a class file for " + className);
if (bytes == null || bytes.length == 0) {
System.out.println("Failed to get class bytes: " + className);
return;
}
// Convert JVM internal class name to a file path.
String fileName = className.replace('.', '/').replace('$', '_') + ".class";
File output = new File("tmp", fileName);
File parent = output.getParentFile();
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
try (FileOutputStream out = new FileOutputStream(output)) {
out.write(bytes);
}
System.out.println("Class: " + className);
System.out.println("Bytes: " + bytes.length);
System.out.println("Saved: " + output.getAbsolutePath());
System.out.println("Class: " + className);
System.out.println("Bytes: OK (" + bytes.length + ")");
});
}
}
}
+9 -4
View File
@@ -1,13 +1,18 @@
import cn.xiaozhou233.juiceagent.api.JuiceAgent;
import java.io.File;
import java.util.Arrays;
public class GetLoadedClasses {
public static void main(String[] args) {
System.load(new File("resources/libagent.dll").getAbsolutePath());
JuiceAgent.init("");
TestSupport.run("GetLoadedClasses", () -> {
TestSupport.bootstrap();
System.out.println(Arrays.toString(JuiceAgent.getLoadedClasses()));
Class<?>[] classes = JuiceAgent.getLoadedClasses();
TestSupport.require(classes != null && classes.length > 0, "getLoadedClasses returned nothing");
TestSupport.require(Arrays.asList(classes).contains(String.class),
"java.lang.String is not among the loaded classes");
System.out.println("Loaded: " + classes.length + " classes");
});
}
}
+10 -12
View File
@@ -1,20 +1,18 @@
import cn.xiaozhou233.juiceagent.api.JuiceAgent;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
public class RedefineClass {
public static void main(String[] args) throws IOException {
System.load(new File("resources/libagent.dll").getAbsolutePath());
JuiceAgent.init("");
public static void main(String[] args) {
TestSupport.run("RedefineClass", () -> {
TestSupport.bootstrap();
Target.targetTest();
Target.targetTest();
byte[] bytes = Files.readAllBytes(new File("out/production/injection/Target.class").toPath());
JuiceAgent.redefineClass(Target.class, bytes, bytes.length);
Target.targetTest();
byte[] bytes = TestSupport.readClass("Target");
TestSupport.require(JuiceAgent.redefineClass(Target.class, bytes, bytes.length),
"redefineClass returned false");
String out = TestSupport.capture(Target::targetTest);
TestSupport.require(out.contains("Modified!"), "redefinition had no effect: " + out);
});
}
}
+10 -12
View File
@@ -1,20 +1,18 @@
import cn.xiaozhou233.juiceagent.api.JuiceAgent;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
public class RedefineClassByName {
public static void main(String[] args) throws IOException {
System.load(new File("resources/libagent.dll").getAbsolutePath());
JuiceAgent.init("");
public static void main(String[] args) {
TestSupport.run("RedefineClassByName", () -> {
TestSupport.bootstrap();
Target.targetTest();
Target.targetTest();
byte[] bytes = Files.readAllBytes(new File("out/production/injection/Target.class").toPath());
JuiceAgent.redefineClassByName("Target", bytes, bytes.length);
Target.targetTest();
byte[] bytes = TestSupport.readClass("Target");
TestSupport.require(JuiceAgent.redefineClassByName("Target", bytes, bytes.length),
"redefineClassByName returned false");
String out = TestSupport.capture(Target::targetTest);
TestSupport.require(out.contains("Modified!"), "redefinition had no effect: " + out);
});
}
}
+10 -12
View File
@@ -1,20 +1,18 @@
import cn.xiaozhou233.juiceagent.api.JuiceAgent;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
public class RetransformClass {
public static void main(String[] args) throws IOException {
System.load(new File("resources/libagent.dll").getAbsolutePath());
JuiceAgent.init("");
public static void main(String[] args) {
TestSupport.run("RetransformClass", () -> {
TestSupport.bootstrap();
Target.targetTest();
Target.targetTest();
byte[] bytes = Files.readAllBytes(new File("out/production/injection/Target.class").toPath());
JuiceAgent.retransformClass(Target.class, bytes, bytes.length);
Target.targetTest();
byte[] bytes = TestSupport.readClass("Target");
TestSupport.require(JuiceAgent.retransformClass(Target.class, bytes, bytes.length),
"retransformClass returned false");
String out = TestSupport.capture(Target::targetTest);
TestSupport.require(out.contains("Modified!"), "retransformation had no effect: " + out);
});
}
}
+10 -12
View File
@@ -1,20 +1,18 @@
import cn.xiaozhou233.juiceagent.api.JuiceAgent;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
public class RetransformClassByName {
public static void main(String[] args) throws IOException {
System.load(new File("resources/libagent.dll").getAbsolutePath());
JuiceAgent.init("");
public static void main(String[] args) {
TestSupport.run("RetransformClassByName", () -> {
TestSupport.bootstrap();
Target.targetTest();
Target.targetTest();
byte[] bytes = Files.readAllBytes(new File("out/production/injection/Target.class").toPath());
JuiceAgent.retransformClassByName("Target", bytes, bytes.length);
Target.targetTest();
byte[] bytes = TestSupport.readClass("Target");
TestSupport.require(JuiceAgent.retransformClassByName("Target", bytes, bytes.length),
"retransformClassByName returned false");
String out = TestSupport.capture(Target::targetTest);
TestSupport.require(out.contains("Modified!"), "retransformation had no effect: " + out);
});
}
}
+105
View File
@@ -0,0 +1,105 @@
import cn.xiaozhou233.juiceagent.api.JuiceAgent;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.PrintStream;
import java.nio.file.Files;
import java.nio.file.Path;
/**
* Shared plumbing for the integration tests.
*
* <p>Every test prints exactly one verdict line: {@code RESULT: PASS <name>} or
* {@code RESULT: FAIL <name>: <reason>}. The runner (run-tests.ps1 / run-tests.sh)
* keys off those lines, so the tests can assert on native return values and on
* captured program output instead of a brittle marker in the runner's own table.
*
* <p>These are still plain {@code main()} programs - no test framework.
*/
public final class TestSupport {
private TestSupport() {}
// Windows ships libagent.dll, Linux ships libagent.so; pick per OS.
private static final String NATIVE_LIB =
System.getProperty("os.name", "").toLowerCase().contains("win")
? "libagent.dll"
: "libagent.so";
private static boolean bootstrapped = false;
/** Loads the native agent and initialises JuiceAgent (once per process). */
public static void bootstrap() {
if (bootstrapped) {
return;
}
System.load(new File("resources", NATIVE_LIB).getAbsolutePath());
require(JuiceAgent.init(""), "JuiceAgent.init returned false");
bootstrapped = true;
}
/** Runs a test body and prints the single PASS/FAIL verdict line. */
public static void run(String name, Body body) {
try {
body.run();
System.out.println("RESULT: PASS " + name);
} catch (Throwable t) {
System.out.println("RESULT: FAIL " + name + ": " + t);
t.printStackTrace(System.err);
}
}
public static void require(boolean condition, String message) {
if (!condition) {
throw new AssertionError(message);
}
}
/** Absolute path of the injection.jar the AddTo* tests append. */
public static String injectionJar() {
return new File("injection.jar").getAbsolutePath();
}
/** Reads a class file produced by the injection module build. */
public static byte[] readClass(String name) {
Path path = Path.of("out", "production", "injection", name.replace('.', '/') + ".class");
try {
return Files.readAllBytes(path);
} catch (Exception e) {
throw new AssertionError("cannot read " + path + ": " + e);
}
}
/** A compiled class starts with the JVM magic number 0xCAFEBABE. */
public static boolean looksLikeClassFile(byte[] bytes) {
return bytes != null && bytes.length >= 4
&& bytes[0] == (byte) 0xCA && bytes[1] == (byte) 0xFE
&& bytes[2] == (byte) 0xBA && bytes[3] == (byte) 0xBE;
}
/** Invokes a public static no-arg method, failing the test on error. */
public static void invokeStatic(Class<?> clazz, String method) {
try {
clazz.getMethod(method).invoke(null);
} catch (Exception e) {
throw new AssertionError("invoking " + clazz.getName() + "." + method + " failed", e);
}
}
/** Captures everything {@code body} writes to {@code System.out}. */
public static String capture(Runnable body) {
PrintStream original = System.out;
ByteArrayOutputStream buffer = new ByteArrayOutputStream();
try (PrintStream capture = new PrintStream(buffer, true)) {
System.setOut(capture);
body.run();
} finally {
System.setOut(original);
}
return buffer.toString();
}
@FunctionalInterface
public interface Body {
void run() throws Exception;
}
}