fix(native): retain failed pwntools process and runtime cleanup (#1708)

* fix(native): retain failed pwntools process and runtime cleanup

Keep failed worker/debugger cleanup owners and their private files until
verified process shutdown and successful directory removal. Retry cleanup
before another inspection and expose shutdown through the shared services,
CLI and MCP server. Serialize acquisition without delaying cancellation of
queued callers, and preserve primary diagnostics when CLI cleanup fails.

The original decoder reproduction left a live owned Node child with its
runtime deleted and no retained cleanup owner; the regression now verifies
retention, admission blocking, retries and eventual process/file cleanup.

Validation: 10 lifecycle/public CLI/MCP tests, 20 service tests, test
discovery 814/814, build:cached and full check including architecture guards.
Actual POSIX process/filesystem boundaries used injected Node workers on
macOS; real Linux pwntools/GDB provider parsing was not exercised.

* test(native): verify retained recorded-crash cleanup lifecycle

* fix(native): finalize diagnostic cleanup before publishing results

* fix(native): retire decoder stages before reading runtime evidence

---------

Co-authored-by: morluto <76467478+morluto@users.noreply.github.com>
This commit is contained in:
Yijie Lu
2026-10-13 01:37:47 +08:00
committed by GitHub
co-authored by morluto
parent ad08510a11
commit 11fe5a13f8
26 changed files with 1716 additions and 135 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);
},
);
@@ -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" });
},
);