fix(verification): integrate Linux Hopper lane with current contracts

Integrate main ae8051302 while retaining the Linux setup, orphan detection,
launcher restoration and explicit string-recognition coverage corrections.
Move verification guidance to its current owner and use the test-scoped
temporary-directory helper.

The checkout matches all 3,175 exported source-file digests of the tested
candidate. Git stores the Windows captureGhidraLaunch.cmd fixture with LF;
its exported checkout uses CRLF per .gitattributes. It is outside Linux
Hopper execution. No native run is attributed to different runtime bytes.
Real Hopper conformance: 9e7de373-4686-4820-ae48-801e536589b7.
Uninterrupted Linux setup: 93584b53-944b-47cf-a6a4-b0d4ff8a4961.
The exact 97b76aa2 run remains separate: ae4de7ff-dd2a-4c73-88dc-6dbf1ad7c537.

21 focused tests, check, docs:check, four fixtures, discovery, package
verification and pack dry-run passed. Linux native decoded omissions,
macOS/other builds and installed npm artifacts with Hopper remain unverified.

Refs #339, #340
This commit is contained in:
Luis Taffelli
2026-10-12 19:31:20 -03:00
1239 changed files with 146960 additions and 42763 deletions
@@ -0,0 +1,111 @@
import { afterEach, expect, it, vi } from "vitest";
import { createCli } from "../../src/cli.js";
import { CLI_COMMANDS } from "../../src/cliCommandNames.js";
import * as composition from "../../src/composition/binaryDiagnostics.js";
import { BinaryLayoutService } from "../../src/application/binaryDiagnostics/BinaryLayoutService.js";
import { RecordedCrashService } from "../../src/application/binaryDiagnostics/RecordedCrashService.js";
import { AnalysisOutputError } from "../../src/domain/analysisErrorCore.js";
import { ProviderCleanupError } from "../../src/domain/providerCleanupError.js";
import { err } from "../../src/domain/result.js";
import { analysisErrorWithCleanupFailure } from "../../src/domain/analysisErrorCleanup.js";
const exitCode = process.exitCode;
afterEach(() => {
vi.restoreAllMocks();
process.exitCode = exitCode;
});
it.each(["layout", "recorded"] as const)(
"projects the final owned outcome through the public CLI: %s",
async (scenario) => {
const primary = new AnalysisOutputError(
"inspect_binary_layout",
"fixture decoder output overflow",
{
capturedOutput: {
stdout: "partial original output",
stderr: "warning",
truncated: true,
},
},
);
const cleanup = new ProviderCleanupError(
"fixture-decoder",
["owned-process", "/retained/runtime"],
{ reason: "fixture process inspection still denied" },
);
const inspectAndClose = vi.fn(async () =>
err(
analysisErrorWithCleanupFailure(
primary,
cleanup,
"inspect_binary_layout",
),
),
);
const identity = {
id: "fixture-decoder",
name: "Fixture decoder",
version: "1",
};
if (scenario === "layout")
vi.spyOn(composition, "createBinaryLayoutService").mockReturnValue(
new BinaryLayoutService({
identity,
inspect: () => {
throw new Error("CLI must request a terminal inspection");
},
inspectAndClose,
}),
);
else
vi.spyOn(composition, "createRecordedCrashService").mockReturnValue(
new RecordedCrashService({
identity,
inspect: () => {
throw new Error("CLI must request a terminal inspection");
},
inspectAndClose,
}),
);
const cli = createCli({});
let stdout = "";
await cli.serve(
[
scenario === "layout"
? CLI_COMMANDS.inspectBinaryLayout
: CLI_COMMANDS.inspectRecordedCrash,
"/selected/fixture.elf",
"--json",
],
{
env: {},
stdout: (text) => {
stdout += text;
},
exit: () => undefined,
},
);
const output: unknown = JSON.parse(stdout);
expect(output).toMatchObject({
code: "cleanup_incomplete",
details: {
cleanup: "incomplete",
resources: ["owned-process", "/retained/runtime"],
captured_output: {
stdout: "partial original output",
stderr: "warning",
truncated: true,
},
diagnostics: {
primary_error: { code: "unreadable_output" },
cleanup_error: { code: "cleanup_incomplete" },
},
},
});
expect(inspectAndClose).toHaveBeenCalledOnce();
expect(process.exitCode).toBe(1);
},
);
@@ -1,15 +1,6 @@
import { execFile } from "node:child_process";
import { randomUUID } from "node:crypto";
import {
chmod,
copyFile,
mkdtemp,
readFile,
rm,
symlink,
unlink,
} from "node:fs/promises";
import { tmpdir } from "node:os";
import { chmod, copyFile, readFile, symlink, unlink } from "node:fs/promises";
import { join } from "node:path";
import { promisify } from "node:util";
@@ -18,6 +9,7 @@ import { expect, it } from "vitest";
import { assertCleanLinuxHopperRuntime } from "../../scripts/lib/clean-linux-hopper-runtime.mjs";
import { completeVerifierRun } from "../../scripts/lib/verifier-run.mjs";
import { cleanupOwnedProcessGroup } from "../../src/process/ProcessOwnership.js";
import { createTestTempDirectory } from "../fixtures/temporaryDirectory.js";
const execFileAsync = promisify(execFile);
@@ -29,7 +21,7 @@ it
const runId = randomUUID();
const childCode =
"process.title = 'Xvfb'; setInterval(() => {}, 1000); process.send('ready');";
const directory = await mkdtemp(join(tmpdir(), "rea-clean-runtime-test-"));
const directory = await createTestTempDirectory("rea-clean-runtime-test-");
const launcher = join(directory, "Hopper");
const alternate = join(directory, "Hopper-alternate");
const alternateMode = mode === "alternate launcher";
@@ -116,7 +108,6 @@ it
});
expect(cleanup.cleaned, JSON.stringify(cleanup)).toBe(true);
}
await rm(directory, { recursive: true, force: true });
}
},
);
@@ -86,6 +86,7 @@ it("keeps independent server budgets for successful results and oversized errors
message: diagnostic,
},
]),
false,
),
);
@@ -0,0 +1,264 @@
import { access, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import {
afterEach,
beforeAll,
beforeEach,
expect,
it,
onTestFinished,
} from "vitest";
import { PwntoolsLayoutProvider } from "../../src/native/pwntools/PwntoolsLayoutProvider.js";
import { PrivateRuntimeRoot } from "../../src/process/PrivateRuntimeRoot.js";
import { spawnOwnedProviderProcess } from "../../src/process/ProviderProcess.js";
import { cleanupOwnedProcessGroup } from "../../src/process/ProcessOwnership.js";
import { prepareProcessOwnershipInspection } from "../../src/process/ProcessOwnershipObservation.js";
import { stopProviderProcessFixture } from "../fixtures/providerProcess.js";
import {
createTestWorkspace,
removeTestWorkspace,
} from "../support/workspace/workspaceFixture.js";
const platform = Object.getOwnPropertyDescriptor(process, "platform");
const architecture = Object.getOwnPropertyDescriptor(process, "arch");
const supportedHost = process.platform !== "win32";
beforeAll(() =>
supportedHost ? prepareProcessOwnershipInspection() : undefined,
);
// Only the decoder's availability gate is simulated. The module-owned process
// inspector was created and prepared for the real host before these overrides;
// every fixture launch, output stream, cleanup signal and filesystem is real.
beforeEach(() => {
Object.defineProperty(process, "platform", { value: "linux" });
Object.defineProperty(process, "arch", { value: "x64" });
});
afterEach(() => {
if (platform !== undefined)
Object.defineProperty(process, "platform", platform);
if (architecture !== undefined)
Object.defineProperty(process, "arch", architecture);
});
const fixture = async () => {
const workspace = await createTestWorkspace("rea-pwntools-cleanup-");
onTestFinished(() => removeTestWorkspace(workspace.root));
const path = join(workspace.root, "selected.elf");
await writeFile(path, "source-owned-seam-bytes");
return { workspace, path };
};
it.runIf(supportedHost)(
"retains live worker files, refuses another launch, and retries cleanup on close",
async () => {
const { workspace, path } = await fixture();
let ownedPath = "";
let pid: number | undefined;
let launches = 0;
let cleanupAllowed = false;
let releaseFixture: (() => Promise<void>) | undefined;
const provider = new PwntoolsLayoutProvider(
{ REA_PWNTOOLS_PYTHON: process.execPath },
async (input) => {
launches++;
ownedPath = input.cwd ?? "";
const launched = await spawnOwnedProviderProcess({
...input,
arguments: [
"-e",
'process.stdout.write("x".repeat(1048577)); setInterval(() => undefined, 1000)',
],
});
pid = launched.process.pid;
releaseFixture = () => stopProviderProcessFixture(launched.process);
return {
...launched,
cleanup: () =>
cleanupAllowed
? cleanupOwnedProcessGroup(launched.ownership)
: Promise.resolve({
cleaned: false as const,
reason: "fixture process inspection denied",
}),
};
},
() =>
PrivateRuntimeRoot.create({ parent: workspace.root, prefix: "owned-" }),
);
onTestFinished(async () => {
cleanupAllowed = true;
await provider.close();
await releaseFixture?.();
});
const result = await provider.inspect({ path });
if (result.ok)
throw new Error("Expected output overflow and failed cleanup");
expect(result.error).toMatchObject({
cleanupIncomplete: true,
diagnostics: {
primary_error: {
code: "unreadable_output",
details: { captured_output: { truncated: true } },
},
cleanup_error: { code: "cleanup_incomplete" },
},
});
if (pid === undefined)
throw new Error("The fixture did not acquire a process");
const workerPid = pid;
expect(() => process.kill(workerPid, 0)).not.toThrow();
expect(await readFile(join(ownedPath, "object.snapshot"), "utf8")).toBe(
"source-owned-seam-bytes",
);
const refused = await provider.inspect({ path });
if (refused.ok)
throw new Error("Unreleased ownership must block another launch");
expect(refused.error.cleanupResources).toContain(ownedPath);
expect(launches).toBe(1);
await expect(provider.close()).rejects.toMatchObject({
cleanupIncomplete: true,
});
await expect(access(ownedPath)).resolves.toBeUndefined();
cleanupAllowed = true;
await provider.close();
expect(() => process.kill(workerPid, 0)).toThrow();
await expect(access(ownedPath)).rejects.toMatchObject({ code: "ENOENT" });
},
);
it.runIf(supportedHost)(
"retains a failed root removal and retries it before acquiring another decoder",
async () => {
const { workspace, path } = await fixture();
let releases = 0;
let launches = 0;
let removalAllowed = false;
const root = await PrivateRuntimeRoot.create({
parent: workspace.root,
prefix: "owned-",
});
const provider = new PwntoolsLayoutProvider(
{ REA_PWNTOOLS_PYTHON: process.execPath },
async (input) => {
launches++;
return spawnOwnedProviderProcess({
...input,
arguments: [
"-e",
'process.stdout.write("retained diagnostic"); process.exitCode = 2',
],
});
},
async () => ({
path: root.path,
close: async () => {
releases++;
if (!removalAllowed) throw new Error("fixture root removal denied");
await root.close();
},
}),
);
onTestFinished(async () => {
removalAllowed = true;
await provider.close();
await root.close();
});
const result = await provider.inspect({ path });
if (result.ok)
throw new Error("Expected command and root-removal failures");
expect(result.error).toMatchObject({
cleanupIncomplete: true,
diagnostics: {
primary_error: {
code: "execution_failure",
details: { diagnostics: { stdout: "retained diagnostic" } },
},
cleanup_error: { code: "cleanup_incomplete" },
},
});
const refused = await provider.inspect({ path });
if (refused.ok)
throw new Error("Retained root cleanup must precede a new launch");
expect(refused.error.cleanupResources).toEqual([root.path]);
expect(launches).toBe(1);
expect(releases).toBe(2);
removalAllowed = true;
await provider.close();
await expect(access(root.path)).rejects.toMatchObject({ code: "ENOENT" });
},
);
it.runIf(supportedHost)(
"cancels queued inspections promptly and drains the running inspection when closing",
async () => {
const { workspace, path } = await fixture();
let release: (() => void) | undefined;
let entered: (() => void) | undefined;
const gate = new Promise<void>((resolve) => {
release = resolve;
});
const started = new Promise<void>((resolve) => {
entered = resolve;
});
let launches = 0;
const provider = new PwntoolsLayoutProvider(
{ REA_PWNTOOLS_PYTHON: process.execPath },
async (input) => {
launches++;
entered?.();
await gate;
return spawnOwnedProviderProcess({
...input,
arguments: ["-e", "process.exit(2)"],
});
},
() =>
PrivateRuntimeRoot.create({ parent: workspace.root, prefix: "owned-" }),
);
onTestFinished(async () => {
release?.();
await provider.close();
});
const first = provider.inspect({ path });
await started;
const controller = new AbortController();
const cancelled = provider.inspect({ path }, { signal: controller.signal });
controller.abort();
await expect(cancelled).resolves.toMatchObject({
ok: false,
error: { _tag: "AnalysisCancelledError" },
});
const queued = provider.inspect({ path });
const closing = provider.close();
const late = provider.inspect({ path });
release?.();
const [firstResult, queuedResult, lateResult] = await Promise.all([
first,
queued,
late,
]);
if (firstResult.ok) throw new Error("The fixture exits with failure");
expect(firstResult.error).not.toMatchObject({ cleanupIncomplete: true });
expect(queuedResult).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCapabilityUnavailableError",
cleanupIncomplete: false,
},
});
expect(lateResult).toMatchObject({
ok: false,
error: {
_tag: "AnalysisCapabilityUnavailableError",
cleanupIncomplete: false,
},
});
await closing;
expect(launches).toBe(1);
},
);
@@ -0,0 +1,308 @@
import { z } from "zod";
import { access, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import {
afterEach,
beforeAll,
beforeEach,
expect,
it,
onTestFinished,
vi,
} from "vitest";
import { BinaryLayoutService } from "../../src/application/binaryDiagnostics/BinaryLayoutService.js";
import { createCli } from "../../src/cli.js";
import * as composition from "../../src/composition/binaryDiagnostics.js";
import { projectAnalysisError } from "../../src/domain/analysisErrorProjection.js";
import { PwntoolsLayoutProvider } from "../../src/native/pwntools/PwntoolsLayoutProvider.js";
import type { PwntoolsLauncher } from "../../src/native/pwntools/PwntoolsDecoder.js";
import { PWNTOOLS_PROVIDER_IDENTITY } from "../../src/native/pwntools/PwntoolsRelease.js";
import { PrivateRuntimeRoot } from "../../src/process/PrivateRuntimeRoot.js";
import { cleanupOwnedProcessGroup } from "../../src/process/ProcessOwnership.js";
import { prepareProcessOwnershipInspection } from "../../src/process/ProcessOwnershipObservation.js";
import { spawnOwnedProviderProcess } from "../../src/process/ProviderProcess.js";
import { binaryLayoutFixture } from "../fixtures/binaryDiagnostics/layout.js";
import {
createTestWorkspace,
removeTestWorkspace,
} from "../support/workspace/workspaceFixture.js";
const supportedHost = process.platform !== "win32";
const platform = Object.getOwnPropertyDescriptor(process, "platform");
const architecture = Object.getOwnPropertyDescriptor(process, "arch");
const exitCode = process.exitCode;
beforeAll(() =>
supportedHost ? prepareProcessOwnershipInspection() : undefined,
);
beforeEach(() => {
// Prepare the real host inspector first; only decoder availability is simulated.
Object.defineProperty(process, "platform", { value: "linux" });
Object.defineProperty(process, "arch", { value: "x64" });
});
afterEach(() => {
if (platform !== undefined)
Object.defineProperty(process, "platform", platform);
if (architecture !== undefined)
Object.defineProperty(process, "arch", architecture);
process.exitCode = exitCode;
vi.restoreAllMocks();
});
const fixture = async (outcome: "decoded" | "failed" = "decoded") => {
const workspace = await createTestWorkspace("rea-pwntools-finalization-");
onTestFinished(() => removeTestWorkspace(workspace.root));
const path = workspace.path("selected.elf");
await writeFile(path, Buffer.alloc(128));
const root = await PrivateRuntimeRoot.create({
parent: workspace.root,
prefix: "owned-",
});
const {
artifact: _artifact,
diagnostics: _diagnostics,
...payload
} = binaryLayoutFixture(path);
const launch: PwntoolsLauncher = async (input) => {
const request = z
.object({ reply_path: z.string() })
.parse(
JSON.parse(await readFile(join(root.path, "request.json"), "utf8")),
);
return spawnOwnedProviderProcess({
...input,
arguments: [
"-e",
outcome === "decoded"
? 'require("node:fs").writeFileSync(process.argv[1], process.argv[2]); process.stdout.write("decoder output")'
: 'process.stdout.write("decoder output"); process.exitCode = 2',
request.reply_path,
JSON.stringify({
ok: true,
profile: PWNTOOLS_PROVIDER_IDENTITY.version,
value: payload,
}),
],
});
};
return { path, root, launch };
};
const runCli = async (
provider: PwntoolsLayoutProvider,
path: string,
): Promise<unknown> => {
vi.spyOn(composition, "createBinaryLayoutService").mockReturnValue(
new BinaryLayoutService(provider),
);
let stdout = "";
await createCli({}).serve(["inspect-binary-layout", path, "--json"], {
env: {},
stdout: (text) => {
stdout += text;
},
exit: () => undefined,
});
return JSON.parse(stdout);
};
it.runIf(supportedHost).each(["decoded", "failed"] as const)(
"returns the original %s outcome after a successful runtime-removal retry through the CLI",
async (outcome) => {
const { path, root, launch } = await fixture(outcome);
let removals = 0;
const provider = new PwntoolsLayoutProvider(
{ REA_PWNTOOLS_PYTHON: process.execPath },
launch,
async () => ({
path: root.path,
close: async () => {
if (++removals === 1) throw new Error("transient removal failure");
await root.close();
},
}),
);
onTestFinished(() => provider.close());
const output = await runCli(provider, path);
if (outcome === "decoded") {
expect(output).toMatchObject({
normalized_result: {
artifact: { path },
diagnostics: { stdout: "decoder output", truncated: false },
},
});
expect(process.exitCode ?? 0).toBe(0);
} else {
expect(output).toMatchObject({
code: "execution_failure",
details: {
diagnostics: {
exit_code: 2,
captured_output: { stdout: "decoder output" },
},
},
});
expect(output).not.toHaveProperty("details.cleanup");
expect(process.exitCode).toBe(1);
}
expect(removals).toBe(2);
await expect(access(root.path)).rejects.toMatchObject({ code: "ENOENT" });
},
);
it.runIf(supportedHost)(
"recovers a completed worker reply after terminal process cleanup succeeds",
async () => {
const { path, root, launch } = await fixture();
let stops = 0;
const provider = new PwntoolsLayoutProvider(
{ REA_PWNTOOLS_PYTHON: process.execPath },
async (input) => {
const launched = await launch(input);
return {
...launched,
cleanup: () =>
++stops < 3
? Promise.resolve({
cleaned: false as const,
reason: "transient process inspection failure",
})
: cleanupOwnedProcessGroup(launched.ownership),
};
},
async () => root,
);
onTestFinished(() => provider.close());
expect(await runCli(provider, path)).toMatchObject({
normalized_result: { artifact: { path } },
});
expect(process.exitCode ?? 0).toBe(0);
expect(stops).toBe(3);
await expect(access(root.path)).rejects.toMatchObject({ code: "ENOENT" });
},
);
it.runIf(supportedHost)(
"reports only the runtime still owned after process retirement",
async () => {
const { path, root, launch } = await fixture("failed");
let stops = 0;
let removalAllowed = false;
const provider = new PwntoolsLayoutProvider(
{ REA_PWNTOOLS_PYTHON: process.execPath },
async (input) => {
const launched = await launch(input);
return {
...launched,
cleanup: () =>
++stops === 1
? Promise.resolve({
cleaned: false as const,
reason: "transient process inspection failure",
})
: cleanupOwnedProcessGroup(launched.ownership),
};
},
async () => ({
path: root.path,
close: async () => {
if (!removalAllowed) throw new Error("runtime removal denied");
await root.close();
},
}),
);
onTestFinished(async () => {
removalAllowed = true;
await provider.close();
});
expect(await runCli(provider, path)).toMatchObject({
code: "cleanup_incomplete",
details: {
resources: [root.path],
diagnostics: {
primary_error: { code: "execution_failure" },
cleanup_error: {
code: "cleanup_incomplete",
details: { resources: [root.path] },
},
},
},
});
expect(stops).toBe(2);
await expect(access(root.path)).resolves.toBeUndefined();
},
);
it.runIf(supportedHost)(
"preserves the validated report when runtime removal remains denied",
async () => {
const { path, root, launch } = await fixture();
let removalAllowed = false;
const provider = new PwntoolsLayoutProvider(
{ REA_PWNTOOLS_PYTHON: process.execPath },
launch,
async () => ({
path: root.path,
close: async () => {
if (!removalAllowed) throw new Error("runtime removal denied");
await root.close();
},
}),
);
onTestFinished(async () => {
removalAllowed = true;
await provider.close();
});
expect(await runCli(provider, path)).toMatchObject({
code: "cleanup_incomplete",
details: {
resources: [root.path],
partial_observation: {
artifact: { path },
diagnostics: { stdout: "decoder output", truncated: false },
sections: binaryLayoutFixture(path).sections,
},
},
});
expect(process.exitCode).toBe(1);
await expect(access(root.path)).resolves.toBeUndefined();
},
);
it.runIf(supportedHost)(
"preserves cancellation during successful final cleanup",
async () => {
const { path, root, launch } = await fixture();
const controller = new AbortController();
let removals = 0;
const provider = new PwntoolsLayoutProvider(
{ REA_PWNTOOLS_PYTHON: process.execPath },
launch,
async () => ({
path: root.path,
close: async () => {
if (++removals === 1) {
controller.abort();
throw new Error("transient removal failure");
}
await root.close();
},
}),
);
onTestFinished(() => provider.close());
const result = await provider.inspectAndClose(
{ path },
{ signal: controller.signal },
);
if (result.ok)
throw new Error("Cancelled inspection must not publish success");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "cancelled",
details: {
captured_output: { stdout: "decoder output", truncated: false },
},
});
await expect(access(root.path)).rejects.toMatchObject({ code: "ENOENT" });
},
);
@@ -0,0 +1,356 @@
import { access, mkdir, readFile, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import {
afterEach,
beforeAll,
beforeEach,
expect,
it,
onTestFinished,
vi,
} from "vitest";
import { z } from "zod";
import { projectAnalysisError } from "../../src/domain/analysisErrorProjection.js";
import { PwntoolsRecordedCrashProvider } from "../../src/native/pwntools/PwntoolsRecordedCrashProvider.js";
import type { PwntoolsLauncher } from "../../src/native/pwntools/PwntoolsDecoder.js";
import {
PWNTOOLS_MEMORY_FAILURE_EXIT,
PWNTOOLS_PROVIDER_IDENTITY,
} from "../../src/native/pwntools/PwntoolsRelease.js";
import { cleanupOwnedProcessGroup } from "../../src/process/ProcessOwnership.js";
import { prepareProcessOwnershipInspection } from "../../src/process/ProcessOwnershipObservation.js";
import { spawnOwnedProviderProcess } from "../../src/process/ProviderProcess.js";
import { PrivateRuntimeRoot } from "../../src/process/PrivateRuntimeRoot.js";
import * as artifacts from "../../src/artifacts/readStableArtifact.js";
import {
recordedCrashFixture,
recordedCrashFixtureBytes,
recordedCrashDebuggerFixture,
} from "../fixtures/binaryDiagnostics/recordedCrash.js";
import {
createTestWorkspace,
removeTestWorkspace,
} from "../support/workspace/workspaceFixture.js";
const supportedHost = process.platform !== "win32";
const platform = Object.getOwnPropertyDescriptor(process, "platform");
const architecture = Object.getOwnPropertyDescriptor(process, "arch");
const worker = fileURLToPath(
new URL("../fixtures/pwntoolsChangingArtifact.mjs", import.meta.url),
);
beforeAll(() =>
supportedHost ? prepareProcessOwnershipInspection() : undefined,
);
beforeEach(() => {
// Use the actual host inspector; simulate only the decoder availability gate.
Object.defineProperty(process, "platform", { value: "linux" });
Object.defineProperty(process, "arch", { value: "x64" });
});
afterEach(() => {
if (platform !== undefined)
Object.defineProperty(process, "platform", platform);
if (architecture !== undefined)
Object.defineProperty(process, "arch", architecture);
vi.restoreAllMocks();
});
const fixture = async () => {
const workspace = await createTestWorkspace("rea-stage-retirement-");
onTestFinished(() => removeTestWorkspace(workspace.root));
const path = workspace.path("selected.core");
const value = recordedCrashFixture(path);
await writeFile(path, recordedCrashFixtureBytes(value));
const root = await PrivateRuntimeRoot.create({
parent: workspace.root,
prefix: "owned-",
});
const venv = workspace.path("venv");
const plugin = workspace.path("gdbinit.py");
await mkdir(venv);
await writeFile(plugin, "");
const environment = {
REA_PWNTOOLS_PYTHON: process.execPath,
REA_PWNDBG_GDB: process.execPath,
REA_PWNDBG_GDBINIT: plugin,
REA_PWNDBG_VENV_PATH: venv,
};
const {
artifact: _artifact,
diagnostics: _diagnostics,
debugger: _debugger,
decoder_diagnostics: _decoderDiagnostics,
...payload
} = value;
const reply = JSON.stringify({
ok: true,
profile: PWNTOOLS_PROVIDER_IDENTITY.version,
value: payload,
});
const basic: PwntoolsLauncher = async (spawn) => {
await writeFile(join(root.path, "reply.json"), reply);
return spawnOwnedProviderProcess({
...spawn,
arguments: ["-e", "process.stdout.write('basic diagnostic')"],
});
};
return { path, root, environment, basic };
};
const changingWorker = async (
spawn: Parameters<NonNullable<PwntoolsLauncher>>[0],
path: string,
contents: { initial: string; final: string; exitCode: number },
cleanupAllowed: () => boolean = () => true,
) => {
const trigger = join(spawn.cwd ?? "", "change.trigger");
const ready = join(spawn.cwd ?? "", "descendant.ready");
const done = join(spawn.cwd ?? "", "change.done");
const launched = await spawnOwnedProviderProcess({
...spawn,
arguments: [
worker,
"leader",
path,
contents.initial,
contents.final,
trigger,
ready,
done,
String(contents.exitCode),
],
});
let stops = 0;
return {
...launched,
cleanup: async () => {
if (++stops === 1 || !cleanupAllowed())
return {
cleaned: false as const,
reason: "fixture inspection unavailable",
};
const descendant = Number(await readFile(ready, "utf8"));
expect(() => process.kill(descendant, 0)).not.toThrow();
await writeFile(trigger, "change now");
await expect
.poll(() =>
access(done).then(
() => true,
() => false,
),
)
.toBe(true);
return cleanupOwnedProcessGroup(launched.ownership);
},
};
};
it.runIf(supportedHost).each(["decoder", "debugger"] as const)(
"classifies %s failure markers only after surviving descendants stop",
async (stage) => {
const { path, root, environment, basic } = await fixture();
let launches = 0;
const provider = new PwntoolsRecordedCrashProvider(
environment,
async (spawn) => {
if (stage === "debugger" && ++launches === 1) return basic(spawn);
const marker = join(spawn.cwd ?? "", "resource.failure");
await writeFile(
join(spawn.cwd ?? "", "limits.json"),
JSON.stringify(recordedCrashDebuggerFixture().reported_limits),
);
return changingWorker(spawn, marker, {
initial: "M",
final: "!",
exitCode: PWNTOOLS_MEMORY_FAILURE_EXIT,
});
},
async () => root,
);
onTestFinished(() => provider.close());
const result = await provider.inspectAndClose({
path,
include_debugger_context: stage === "debugger",
});
if (result.ok) throw new Error("Expected the original command failure");
expect(projectAnalysisError(result.error)).toMatchObject({
code: "execution_failure",
details: {
diagnostics: {
phase: stage,
resource_failure_marker: { resource: null },
exit_code: PWNTOOLS_MEMORY_FAILURE_EXIT,
captured_output: { stdout: "stage diagnostic" },
},
},
});
await expect(access(root.path)).rejects.toMatchObject({ code: "ENOENT" });
},
);
it.runIf(supportedHost)(
"publishes debugger replies only after surviving descendants stop",
async () => {
const { path, root, environment, basic } = await fixture();
let launches = 0;
const context = recordedCrashDebuggerFixture();
const finalContext = { ...context, pwndbg_version: "after retirement" };
const provider = new PwntoolsRecordedCrashProvider(
environment,
async (spawn) => {
if (++launches === 1) return basic(spawn);
return changingWorker(spawn, join(spawn.cwd ?? "", "reply.json"), {
initial: JSON.stringify({ ok: true, value: context }),
final: JSON.stringify({ ok: true, value: finalContext }),
exitCode: 0,
});
},
async () => root,
);
onTestFinished(() => provider.close());
const result = await provider.inspectAndClose({
path,
include_debugger_context: true,
});
if (!result.ok) throw result.error;
expect(result.value.debugger).toMatchObject({
status: "available",
pwndbg_version: "after retirement",
});
await expect(access(root.path)).rejects.toMatchObject({ code: "ENOENT" });
},
);
it.runIf(supportedHost).each([
{ stage: "decoder", outcome: "success" },
{ stage: "decoder", outcome: "failure" },
{ stage: "debugger", outcome: "success" },
{ stage: "debugger", outcome: "failure" },
] as const)(
"does not read unresolved $stage files after command $outcome",
async ({ stage, outcome }) => {
const { path, root, environment, basic } = await fixture();
let launches = 0;
let cleanupAllowed = false;
const read = vi.spyOn(artifacts, "readStableArtifact");
const provider = new PwntoolsRecordedCrashProvider(
environment,
async (spawn) => {
if (stage === "debugger" && ++launches === 1) return basic(spawn);
return changingWorker(
spawn,
join(spawn.cwd ?? "", "resource.failure"),
{
initial: "M",
final: "!",
exitCode: outcome === "success" ? 0 : PWNTOOLS_MEMORY_FAILURE_EXIT,
},
() => cleanupAllowed,
);
},
async () => root,
);
onTestFinished(async () => {
cleanupAllowed = true;
await provider.close();
});
const result = await provider.inspectAndClose({
path,
include_debugger_context: true,
});
if (result.ok) throw new Error("Expected unresolved process ownership");
const projected = projectAnalysisError(result.error);
expect(projected.code).toBe("cleanup_incomplete");
if (stage === "debugger")
expect(projected).toMatchObject({
details: {
partial_observation: {
artifact: { path },
debugger: { status: "unavailable", requested: true },
},
},
});
if (outcome === "failure")
expect(projected).toMatchObject({
details: {
diagnostics: {
primary_error: { code: "execution_failure" },
},
},
});
const stagePath =
stage === "debugger" ? join(root.path, "debugger") : root.path;
const paths = read.mock.calls.map(([selected]) => selected);
for (const file of ["reply.json", "resource.failure", "limits.json"])
expect(paths).not.toContain(join(stagePath, file));
const descendant = Number(
await readFile(join(stagePath, "descendant.ready"), "utf8"),
);
expect(() => process.kill(descendant, 0)).not.toThrow();
await expect(access(root.path)).resolves.toBeUndefined();
},
);
it.runIf(supportedHost)(
"retains a live debugger after output overflow with basic evidence and retryable cleanup",
async () => {
const { path, root, environment, basic } = await fixture();
let launches = 0;
let pid: number | undefined;
let cleanupAllowed = false;
const provider = new PwntoolsRecordedCrashProvider(
environment,
async (spawn) => {
if (++launches === 1) return basic(spawn);
const launched = await spawnOwnedProviderProcess({
...spawn,
arguments: [
"-e",
'process.stdout.write("x".repeat(1048577)); setInterval(() => undefined, 1000)',
],
});
pid = launched.process.pid;
return {
...launched,
cleanup: () =>
cleanupAllowed
? cleanupOwnedProcessGroup(launched.ownership)
: Promise.resolve({
cleaned: false as const,
reason: "fixture inspection unavailable",
}),
};
},
async () => root,
);
onTestFinished(async () => {
cleanupAllowed = true;
await provider.close();
});
const result = await provider.inspectAndClose({
path,
include_debugger_context: true,
});
if (result.ok) throw new Error("Expected retained output-limit failure");
const projected = projectAnalysisError(result.error);
expect(projected).toMatchObject({
code: "cleanup_incomplete",
details: {
captured_output: { truncated: true },
diagnostics: { primary_error: { code: "unreadable_output" } },
partial_observation: {
artifact: { path },
diagnostics: { stdout: "basic diagnostic" },
debugger: { status: "unavailable", requested: true },
},
},
});
if (pid === undefined) throw new Error("Expected a live owned debugger");
const debuggerPid = pid;
expect(() => process.kill(debuggerPid, 0)).not.toThrow();
cleanupAllowed = true;
await provider.close();
expect(() => process.kill(debuggerPid, 0)).toThrow();
await expect(access(root.path)).rejects.toMatchObject({ code: "ENOENT" });
},
);
@@ -1,5 +1,5 @@
import { spawn } from "node:child_process";
import { readFile, utimes, writeFile } from "node:fs/promises";
import { copyFile, mkdir, readFile, utimes, writeFile } from "node:fs/promises";
import { join } from "node:path";
import { fileURLToPath } from "node:url";
import { setTimeout as delay } from "node:timers/promises";
@@ -116,6 +116,66 @@ it("does not treat an old database timestamp as permission to replace a live own
}
});
it("preserves executable arguments through the public runner", async () => {
const directory = await createTestTempDirectory("rea-runner-argv-");
const payload = 'spaces, "quotes", & ^ % ! (parens)';
const code = "process.stdout.write(JSON.stringify(process.argv.slice(1)))";
expect(
await execute(directory, process.execPath, ["-e", code, payload]),
).toMatchObject({
code: 0,
stdout: JSON.stringify([payload]),
stderr: "",
});
});
it.runIf(process.platform === "win32")(
"launches an executable from a path containing spaces",
async () => {
const directory = await createTestTempDirectory("rea-runner-spaced-exe-");
const executable = join(directory, "node runtime", "node.exe");
await mkdir(join(directory, "node runtime"), { recursive: true });
await copyFile(process.execPath, executable);
const payload = 'argument with spaces and "quotes" & ^ % !';
const code = "process.stdout.write(JSON.stringify(process.argv.slice(1)))";
expect(
await execute(directory, executable, ["-e", code, payload]),
).toMatchObject({
code: 0,
stdout: JSON.stringify([payload]),
stderr: "",
});
},
);
it.runIf(process.platform === "win32")(
"resolves bare node and Windows command shims without losing arguments",
async () => {
const directory = await createTestTempDirectory("rea-runner-shims-");
const payload = 'argument with spaces and "quotes" & ^ % !';
const code = "process.stdout.write(JSON.stringify(process.argv.slice(1)))";
expect(
await execute(directory, "node", ["-e", code, payload]),
).toMatchObject({
code: 0,
stdout: JSON.stringify([payload]),
stderr: "",
});
const npm = await execute(directory, "npm", ["--version"]);
expect(npm).toMatchObject({ code: 0, stderr: "" });
expect(npm.stdout.trim()).toMatch(/^\d+\.\d+\.\d+/u);
const turbo = await execute(
directory,
join(process.cwd(), "node_modules", ".bin", "turbo"),
["--version"],
);
expect(turbo).toMatchObject({ code: 0, stderr: "" });
expect(turbo.stdout.trim()).toMatch(/^\d+\.\d+\.\d+/u);
},
);
it.runIf(process.platform !== "win32")(
"recovers after abrupt owner death and keeps simultaneous contenders exclusive",
async () => {
@@ -219,6 +279,30 @@ function launch(directory: string, command: string) {
return { child, ready, closed };
}
function execute(
directory: string,
command: string,
arguments_: string[] = [],
) {
return new Promise<{
code: number | null;
stdout: string;
stderr: string;
}>((resolve, reject) => {
const child = spawn(
process.execPath,
[runnerPath, "test", command, ...arguments_],
{ cwd: directory, stdio: ["ignore", "pipe", "pipe"] },
);
let stdout = "";
let stderr = "";
child.stdout.on("data", (chunk) => (stdout += chunk.toString()));
child.stderr.on("data", (chunk) => (stderr += chunk.toString()));
child.once("error", reject);
child.once("close", (code) => resolve({ code, stdout, stderr }));
});
}
function withTimeout<T>(promise: Promise<T>, message: string): Promise<T> {
let timeout: NodeJS.Timeout | undefined;
return Promise.race([