diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0fde199..bd3c97f 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -95,7 +95,7 @@ jobs: retention-days: 14 build-linux: - name: Build (Linux, GCC) + name: Build & integration tests (Linux, GCC) runs-on: ubuntu-latest steps: @@ -104,6 +104,12 @@ jobs: with: submodules: recursive + - name: Set up JDK + uses: actions/setup-java@v4 + with: + distribution: temurin + java-version: '25' + - name: Install build tools run: | sudo apt-get update @@ -124,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 diff --git a/AGENTS.md b/AGENTS.md index 55f8d30..a52818e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -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 ` / `RESULT: FAIL : ...`). +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 ` or +`RESULT: FAIL : ` - and the runners match `RESULT: PASS ` +(and reject any `RESULT: FAIL`) instead of trusting the exit code, which would +silently pass broken builds. Notes when adding tests: @@ -160,7 +174,7 @@ includes/JuiceAgent Config.hpp / Logger.hpp / Utils.hpp / JuiceAgent.hpp (CONFIG includes/toml++ vendored includes/spdlog vendored includes/ptrace-inject-cpp vendored Linux injector library (libptrace_inject.a) -tests/ integration tests + run-tests.ps1 + copy-bin.bat +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 @@ -210,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: diff --git a/tests/cases.txt b/tests/cases.txt new file mode 100644 index 0000000..cbcd44a --- /dev/null +++ b/tests/cases.txt @@ -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 diff --git a/tests/copy-bin.sh b/tests/copy-bin.sh new file mode 100644 index 0000000..c660912 --- /dev/null +++ b/tests/copy-bin.sh @@ -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." diff --git a/tests/run-tests.ps1 b/tests/run-tests.ps1 index 80cfe81..8ef9eb2 100644 --- a/tests/run-tests.ps1 +++ b/tests/run-tests.ps1 @@ -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 " / "RESULT: FAIL : ...") 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 } } diff --git a/tests/run-tests.sh b/tests/run-tests.sh new file mode 100644 index 0000000..d0eb08f --- /dev/null +++ b/tests/run-tests.sh @@ -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." diff --git a/tests/src/AddToBootstrapClassLoaderSearch.java b/tests/src/AddToBootstrapClassLoaderSearch.java index 8ebec1e..491456b 100644 --- a/tests/src/AddToBootstrapClassLoaderSearch.java +++ b/tests/src/AddToBootstrapClassLoaderSearch.java @@ -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"); + }); } } diff --git a/tests/src/AddToClassLoader.java b/tests/src/AddToClassLoader.java index f99a947..c067539 100644 --- a/tests/src/AddToClassLoader.java +++ b/tests/src/AddToClassLoader.java @@ -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()); + }); } } diff --git a/tests/src/AddToSystemClassLoaderSearch.java b/tests/src/AddToSystemClassLoaderSearch.java index bb0433b..844ee7c 100644 --- a/tests/src/AddToSystemClassLoaderSearch.java +++ b/tests/src/AddToSystemClassLoaderSearch.java @@ -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()); + }); } } diff --git a/tests/src/DefineClass.java b/tests/src/DefineClass.java index fc2bab6..2047162 100644 --- a/tests/src/DefineClass.java +++ b/tests/src/DefineClass.java @@ -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()); + }); } } diff --git a/tests/src/GetClassByName.java b/tests/src/GetClassByName.java index d10c894..f989fff 100644 --- a/tests/src/GetClassByName.java +++ b/tests/src/GetClassByName.java @@ -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()); + }); } } diff --git a/tests/src/GetClassBytes.java b/tests/src/GetClassBytes.java index ffbcdef..85d3cd8 100644 --- a/tests/src/GetClassBytes.java +++ b/tests/src/GetClassBytes.java @@ -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 + ")"); + }); } -} \ No newline at end of file +} diff --git a/tests/src/GetClassBytesByName.java b/tests/src/GetClassBytesByName.java index 1fd590c..a141151 100644 --- a/tests/src/GetClassBytesByName.java +++ b/tests/src/GetClassBytesByName.java @@ -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 + ")"); + }); } -} \ No newline at end of file +} diff --git a/tests/src/GetLoadedClasses.java b/tests/src/GetLoadedClasses.java index bf06276..b0ae286 100644 --- a/tests/src/GetLoadedClasses.java +++ b/tests/src/GetLoadedClasses.java @@ -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"); + }); } } diff --git a/tests/src/RedefineClass.java b/tests/src/RedefineClass.java index 71ef349..de04c27 100644 --- a/tests/src/RedefineClass.java +++ b/tests/src/RedefineClass.java @@ -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); + }); } } diff --git a/tests/src/RedefineClassByName.java b/tests/src/RedefineClassByName.java index 1fc7007..dc3401b 100644 --- a/tests/src/RedefineClassByName.java +++ b/tests/src/RedefineClassByName.java @@ -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); + }); } } diff --git a/tests/src/RetransformClass.java b/tests/src/RetransformClass.java index 741b99c..7f0ee6a 100644 --- a/tests/src/RetransformClass.java +++ b/tests/src/RetransformClass.java @@ -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); + }); } } diff --git a/tests/src/RetransformClassByName.java b/tests/src/RetransformClassByName.java index c06a791..874461b 100644 --- a/tests/src/RetransformClassByName.java +++ b/tests/src/RetransformClassByName.java @@ -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); + }); } } diff --git a/tests/src/TestSupport.java b/tests/src/TestSupport.java new file mode 100644 index 0000000..ffc02c9 --- /dev/null +++ b/tests/src/TestSupport.java @@ -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. + * + *

Every test prints exactly one verdict line: {@code RESULT: PASS } or + * {@code RESULT: FAIL : }. 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. + * + *

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; + } +}