Files
reverse-engineering-anything/tests/boundary/providers/RizinDebugSessionCoverage.part3.test.ts
T
morluto 48b4bcd19a feat!: name process capture, Rizin and gdb Evidence by their target identities (#11568)
* feat(process)!: name process capture Evidence by its launched root process

The capture result now carries the launched root process in
`manifest.root_process`: its PID with the start identity that
`observeProcessStartIdentity` read for that PID at launch, bound to the
capture's run token. The harness reads that identity once and shares it
between finalization signalling and the manifest, so the read no longer
depends on a positive finalization interval.

Capture Evidence names the root as its subject,
`{ kind: "process", pid, start_time, executable_sha256 }`. A PID without
its start identity is not an identity, so an unread start identity leaves
the subject `unknown`/`not-observed`. When the caller selects PID
normalization, the raw PID and start identity are not recorded:
`root_process` is `withheld-by-caller` and the subject is
`unknown`/`withheld-by-caller`, a new unknown reason. Capture validation
requires the withheld state exactly when PID normalization is selected.

Refs #11417

BREAKING CHANGE: process capture Evidence IDs change: captures without PID
normalization name `{ kind: "process", pid, start_time, executable_sha256 }`
as their subject, and captures with PID normalization name
`{ kind: "unknown", reason: "withheld-by-caller" }`. Capture results
require `manifest.root_process`; captures without it are refused.
Recreate stored process capture Evidence.

* fix(process): join the launch identity read and let cancellation interrupt its wait

The root's launch identity read now runs for every capture and the
manifest awaits it. The read stays unsignalled, because finalization
signals after a cancellation still need the retained identity, so the
manifest's wait observes cancellation through `waitForAbortable` instead.
`finishProcessRun` and the startup-failure path join the read, so a
capture never returns while it is still running.

* feat(rizin)!: bind Rizin command Evidence to its session and launch file (#11570)

* feat(rizin)!: bind Rizin command Evidence to its session and launch file

Rizin command Evidence was subject-less (`unknown`/`not-observed`). A new
`session` target identity names the debugger session REA minted and the
target it launched: `{ kind: "session", session_kind, id, target }`, where
`target` is a file identity or an explicit unknown. The Evidence subject
validates the nested launch file with the format-owned subject
declaration.

`start_rizin_debug_session` hashes the launch file with the shared stable
file hasher before Rizin starts and binds the session to it (`format:
"file"`, no architecture or selection). Later debugger commands do not
rebind it. A descriptor whose close fails is retained in the startup
resource scope, like the inferior TTY lease, and fails the start, as does
cancellation; any other hash failure leaves the target
`unknown`/`not-observed` and records the reason as a limitation. The
"target identity is not established" limitation is replaced by the
binding's meaning.

Refs #11417

BREAKING CHANGE: `rizin_debug_command` Evidence IDs change: its subject is
`{ kind: "session", session_kind: "rizin", id: <session_id>, target }`
with `target` the launch file hashed at start (`{ kind: "file", sha256,
format: "file", architecture: null, selection: null }`) or
`{ kind: "unknown", reason: "not-observed" }`. Recreate stored Rizin
command Evidence.

* feat(gdb)!: name GDB command Evidence by its debugger session (#11572)

GDB startup and console Evidence was subject-less (`unknown`/`not-observed`).
It now names the session REA minted with the shared `session` identity:
`{ kind: "session", session_kind: "gdb", id, target }`. One projection,
`gdbSessionSubject`, replaces the six `unknownTarget("not-observed")` sites.

`start_gdb_session` launches no program file; programs are loaded or
attached by console commands that REA does not hash, so the session target
stays `unknown`/`not-observed`. REA does not infer a file from a PID or a
path. The existing limitation that the active inferior identity is not
established still applies.

Refs #11417

BREAKING CHANGE: `start_gdb_session` startup Evidence and `gdb_console`
Evidence IDs change: their subject is `{ kind: "session", session_kind:
"gdb", id: <session_id>, target: { kind: "unknown", reason: "not-observed" } }`.
Recreate stored GDB Evidence.

* fix(rizin): keep the launch file read failure when its close also fails

When hashing the launch file failed and closing its descriptor failed
too, the start error kept only the close failure; the retained lease
retries only the close, so the read failure was lost. The cleanup error
now carries it as `launch_file_hash_failure`.

The session-binding test now rewrites the launch file after spawn and
between two commands, and checks that both records keep the digest read
before launch.

* fix(process): keep the descriptor a failed launch identity read could not close

The launch identity read reduced every rejection to an unverified reason, so an inspection-owner failure carrying an unclosed descriptor was dropped and the capture could succeed without retaining it. The retained identity now keeps that owner's failure; startup cleanup and finishProcessRun pass it through the same secondary inspection-failure path as the sampler, which fails the capture and keeps the descriptor owned for cleanup retry.

* refactor(rizin): describe a launch-file hash failure through errorMessage

* test(rizin): create launch-file fixtures through createTestTempDirectory

* fix(process): keep the descriptor a finalization signal's identity check left open (#11603)

* fix(process): keep the descriptor a finalization signal's identity check left open

The root signaller now catches a delivery whose identity check fails through the inspection owner, records the attempt as unverified, and keeps the inspection failure. finishProcessRun joins every delivery (including one that outlasted the finalization grace) and retains those failures through the same secondary inspection-failure path as the launch identity read, so the capture fails with the descriptor still owned for a cleanup retry.

* test(process): release descriptor-retention captures when an assertion fails

Both descriptor-retention regressions register their resource-scope release before the capture starts and use the project deadline instead of a fixed 15 s timeout.
2026-11-16 08:06:35 +08:00

804 lines
28 KiB
TypeScript

import { createHash } from "node:crypto";
import { writeFileSync } from "node:fs";
import { writeFile } from "node:fs/promises";
import { join } from "node:path";
import { afterEach, expect, it, vi } from "vitest";
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
import { withVerifierCleanup } from "../../../scripts/lib/verifier-cleanup.mjs";
import { phaseGate } from "../../support/lifecycleHarness.js";
import { AnalysisCancelledError } from "../../../src/domain/analysisErrorCore.js";
import { stopOwnedDebuggerProcess } from "../../../src/process/ownedDebuggerSession.js";
import { rizinTestInferiorTty } from "./RizinTestInferiorTty.js";
import {
createRizinCoverageHarness,
abortOnCheck,
createInjectedProcess,
} from "./RizinDebugSessionCoverage.fixtures.js";
const { cleanup, startInjected, createManager } = createRizinCoverageHarness();
afterEach(cleanup);
it.skipIf(process.platform === "win32")(
"times out when an active command produces no frame",
async () => {
const injected = createInjectedProcess();
const { manager, started } = await startInjected(
injected.spawnProcess,
{ stopProcess: async () => ({ status: "stopped" }) },
{ REA_DEBUGGER_COMMAND_DEADLINE_MS: "10" },
);
if (!started.ok) throw started.error;
const result = await manager.execute(started.value.session_id, "wait");
if (!result.ok) throw result.error;
expect(result.value.result.completion_status).toBe("unknown");
expect(result.value.evidence.raw_result).toEqual(result.value.result);
expect(result.value.evidence.normalized_result).toEqual(
result.value.result,
);
expect(result.value.evidence.parameters).toMatchObject({
session_id: started.value.session_id,
command: "wait",
inferior_tty: await rizinTestInferiorTty(),
launch_provenance: {
caller_selected_path: "/tmp/injected",
resolved_path: "/tmp/injected",
},
});
expect(result.value.evidence.limitations).toEqual([
expect.stringMatching(
/session target is the launch file.*do not rebind/iu,
),
expect.stringMatching(/launch file could not be hashed.*unknown/iu),
expect.stringMatching(
/timed out.*10 ms.*REA_DEBUGGER_COMMAND_DEADLINE_MS.*partial.*completion is unknown/iu,
),
expect.stringMatching(/session.*stopped.*output correlation/iu),
expect.stringMatching(/unrestricted.*shell.*network.*mutate/iu),
expect.stringMatching(
/incomplete completion.marker prefix.*diagnostics/iu,
),
expect.stringMatching(
/launch provenance.*does not establish.*current target/iu,
),
]);
},
);
it.skipIf(process.platform === "win32")(
"preserves frame separators in partial output when a command times out",
async () => {
const injected = createInjectedProcess({
onWrite: (_text, control) => {
control.output("first frame\0second frame\0");
},
});
const { manager, started } = await startInjected(
injected.spawnProcess,
{
stopProcess: async () => ({ status: "stopped" }),
},
{ REA_DEBUGGER_COMMAND_DEADLINE_MS: "1000" },
);
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(started.value.session_id, "wait");
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value.result.output).toBe("first frame\nsecond frame");
expect(result.value.result.completion_status).toBe("unknown");
}
},
);
it.skipIf(process.platform === "win32")(
"keeps completion unknown when a queued marker reaches an expired deadline",
async () => {
const injected = createInjectedProcess({
onWrite: (text, control) => {
const marker = /!echo (.+)\n/u.exec(text)?.[1];
if (marker !== undefined)
control.output(`first frame\0second frame\0${marker}\0`);
},
});
const { manager, started } = await startInjected(
injected.spawnProcess,
{},
{ REA_DEBUGGER_COMMAND_DEADLINE_MS: "1000" },
);
expect(started.ok).toBe(true);
if (!started.ok) return;
// The command deadline is monotonic: it starts on the first reading and
// expires on the fourth, while the marker frame is still queued.
const clock = vi.spyOn(performance, "now");
clock
.mockReturnValueOnce(100)
.mockReturnValueOnce(100)
.mockReturnValueOnce(100)
.mockReturnValue(1100);
let result;
try {
result = await manager.execute(started.value.session_id, "wait");
} finally {
clock.mockRestore();
}
expect(result.ok).toBe(true);
if (result.ok) {
// The completion marker is still queued when the deadline expires.
expect(result.value.result.output).toBe("first frame\nsecond frame");
expect(result.value.result.completion_status).toBe("unknown");
expect(result.value.result.output_truncated).toBe(true);
expect(result.value.evidence.normalized_result).toEqual(
result.value.result,
);
}
},
);
it.skipIf(process.platform === "win32")(
"does not convert an unexpected frame waiter error into a timeout",
async () => {
const injected = createInjectedProcess({
onWrite: (_text, control) => {
setImmediate(() => control.stdinError());
},
});
const { manager, started } = await startInjected(
injected.spawnProcess,
{
stopProcess: async () => ({ status: "stopped" }),
},
{ REA_DEBUGGER_COMMAND_DEADLINE_MS: "100" },
);
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(started.value.session_id, "wait");
expect(result.ok).toBe(false);
if (!result.ok)
expect(result.error.message).toContain("Rizin stdin stream failed");
},
);
it.skipIf(process.platform === "win32")(
"cancels a command after capturing its completion frame",
async () => {
const reason = { stage: "completion frame captured" };
const injected = createInjectedProcess({
onWrite: (text, control) => {
const marker = /!echo (.+)\n/u.exec(text)?.[1];
if (marker !== undefined)
control.output(Buffer.from(`registers${marker}\0`));
},
});
const { manager, started } = await startInjected(injected.spawnProcess, {
stopProcess: async () => ({ status: "stopped" }),
});
if (!started.ok) throw started.error;
const signal = abortOnCheck(5, reason);
const registration = vi.spyOn(signal, "addEventListener");
const result = await manager.execute(
started.value.session_id,
"dr",
signal,
);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error).toBeInstanceOf(AnalysisCancelledError);
expect(result.error.cause).toBe(reason);
expect(registration).toHaveBeenCalledTimes(1);
expect(result.error.capturedOutput?.stdout).toBe("registers");
expect(result.error.partialObservation).toMatchObject({
parameters: { session_id: started.value.session_id, command: "dr" },
raw_result: { output: "registers", completion_status: "unknown" },
});
expect(manager.status(started.value.session_id)?.state).toBe("closed");
},
);
it.skipIf(process.platform === "win32")(
"handles cancellation observed immediately after installing the frame waiter",
async () => {
const injected = createInjectedProcess();
const { manager, started } = await startInjected(injected.spawnProcess, {
stopProcess: async () => ({ status: "stopped" }),
});
if (!started.ok) throw started.error;
const reason = { stage: "frame waiter installation" };
const signal = abortOnCheck(5, reason);
const registration = vi.spyOn(signal, "addEventListener");
const result = await manager.execute(
started.value.session_id,
"wait",
signal,
);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(registration).toHaveBeenCalledTimes(2);
expect(registration).toHaveBeenCalledWith("abort", expect.any(Function), {
once: true,
});
expect(result.error).toBeInstanceOf(AnalysisCancelledError);
expect(result.error.cause).toBe(reason);
expect(result.error.capturedOutput?.stdout).toBe("");
expect(result.error.partialObservation).toMatchObject({
parameters: { session_id: started.value.session_id, command: "wait" },
raw_result: { output: "", completion_status: "unknown" },
});
expect(manager.status(started.value.session_id)?.state).toBe("closed");
},
);
it.skipIf(process.platform === "win32").each([false, true])(
"maps a frame-wait listener installation failure without losing cleanup (incomplete=%s)",
async (incomplete) => {
const injected = createInjectedProcess();
const { manager, started } = await startInjected(
injected.spawnProcess,
{
stopProcess: async () =>
incomplete
? {
status: "incomplete",
code: "stop-failed",
reason: "injected stop uncertainty",
}
: { status: "stopped" },
},
{ REA_DEBUGGER_COMMAND_DEADLINE_MS: "1000" },
);
expect(started.ok).toBe(true);
if (!started.ok) return;
const controller = new AbortController();
let registrations = 0;
const signal = {
get aborted() {
return false;
},
addEventListener(
type: Parameters<AbortSignal["addEventListener"]>[0],
listener: Parameters<AbortSignal["addEventListener"]>[1],
options?: Parameters<AbortSignal["addEventListener"]>[2],
) {
registrations += 1;
if (registrations === 2)
throw new Error("injected frame waiter registration failure");
controller.signal.addEventListener(type, listener, options);
},
removeEventListener: controller.signal.removeEventListener.bind(
controller.signal,
),
dispatchEvent: controller.signal.dispatchEvent.bind(controller.signal),
onabort: null,
reason: undefined,
throwIfAborted: () => undefined,
} as AbortSignal;
const result = await manager.execute(
started.value.session_id,
"wait",
signal,
);
expect(result.ok).toBe(false);
if (!result.ok && incomplete)
expect(result.error.cleanup?.reason).toContain(
"injected stop uncertainty",
);
},
);
it.skipIf(process.platform === "win32")(
"correlates an injected command frame with its generated marker",
async () => {
const injected = createInjectedProcess({
onWrite: (text, control) => {
const marker = /!echo (.+)\n/u.exec(text)?.[1];
if (marker !== undefined)
setImmediate(() => control.output(Buffer.from(`output${marker}\0`)));
},
});
const { manager, started } = await startInjected(injected.spawnProcess);
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(started.value.session_id, "dr");
expect(result.ok).toBe(true);
if (result.ok) expect(result.value.result.output).toBe("output");
},
);
it.skipIf(process.platform === "win32")(
"preserves process-exit evidence when exit occurs before frame waiting",
async () => {
const injected = createInjectedProcess({
onWrite: (_text, control) => control.exit(),
});
const { manager, started } = await startInjected(injected.spawnProcess);
expect(started.ok).toBe(true);
if (!started.ok) return;
const result = await manager.execute(started.value.session_id, "dr");
expect(result.ok).toBe(true);
if (result.ok) {
expect(result.value.result.completion_status).toBe("unknown");
expect(result.value.result).toMatchObject({
command: "dr",
output: "",
output_truncated: false,
completion_status: "unknown",
backend: null,
});
expect(result.value.evidence.raw_result).toEqual(result.value.result);
expect(result.value.evidence.limitations).toEqual([
expect.stringMatching(
/session target is the launch file.*do not rebind/iu,
),
expect.stringMatching(/launch file could not be hashed.*unknown/iu),
expect.stringMatching(
/Rizin exited.*output is partial.*completion is unknown/iu,
),
expect.stringMatching(/unrestricted.*shell.*network.*mutate/iu),
expect.stringMatching(
/incomplete completion.marker prefix.*diagnostics/iu,
),
expect.stringMatching(
/launch provenance.*does not establish.*current target/iu,
),
]);
}
},
);
it.skipIf(process.platform === "win32")(
"rejects a queued command when the process exits before its frame wait begins",
async () => {
const writes: string[] = [];
const injected = createInjectedProcess({
onWrite: (text, control) => {
writes.push(text);
const marker = /!echo (.+)\n/u.exec(text)?.[1];
if (marker !== undefined) setImmediate(() => control.exit());
},
});
const { manager, started } = await startInjected(injected.spawnProcess);
expect(started.ok).toBe(true);
if (!started.ok) return;
const first = manager.execute(started.value.session_id, "first");
const queued = manager.execute(started.value.session_id, "second");
expect((await first).ok).toBe(true);
const second = await queued;
expect(second.ok).toBe(false);
if (!second.ok)
expect(second.error).toMatchObject({
_tag: "AnalysisCapabilityUnavailableError",
reason: expect.stringContaining(
"The Rizin process exited (exit code null, signal SIGTERM)",
),
});
expect(writes.some((text) => text.includes("second\n"))).toBe(false);
},
);
it
.skipIf(process.platform === "win32")
.each([null, { selected: "opaque reason" }])(
"preserves exact caller cancellation through incomplete cleanup: %j",
async (reason) => {
const controller = new AbortController();
const injected = createInjectedProcess({
onWrite: (_text, control) => {
control.output("partial\0");
controller.abort(reason);
},
});
let retained = true;
const { manager, started } = await startInjected(injected.spawnProcess, {
stopProcess: async () =>
retained
? {
status: "incomplete",
code: "stop-failed",
reason: "owned stop pending",
}
: { status: "stopped" },
});
if (!started.ok) throw started.error;
const result = await manager.execute(
started.value.session_id,
"wait",
controller.signal,
);
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error).toBeInstanceOf(AnalysisCancelledError);
expect(result.error.cause).toBe(reason);
expect(result.error.capturedOutput?.stdout).toContain("partial");
expect(result.error.partialObservation).toBeDefined();
expect(result.error.cleanupIncomplete).toBe(true);
retained = false;
expect((await manager.close(started.value.session_id)).ok).toBe(true);
expect(result.error.cleanupIncomplete).toBe(false);
},
);
it.skipIf(process.platform === "win32").each([false, true])(
"recovers output-limit cleanup only after a fresh marker and inferior readback (retry=%s)",
async (retry) => {
let synchronizationAllowed = !retry;
const writes: string[] = [];
const injected = createInjectedProcess({
onWrite: (text, control) => {
writes.push(text);
const marker = /!echo (.+)\n/u.exec(text)?.[1];
if (marker === undefined) return;
if (text.startsWith("noisy\n"))
control.output(`too much output\0${marker}\0`);
else if (text.startsWith("!echo __REA_CLEANUP_SYNC_")) {
if (synchronizationAllowed)
control.output(`stale frame\0${marker}\0`);
} else if (text.startsWith("olj\n")) control.output(`[]\0${marker}\0`);
else throw new Error(`Unexpected cleanup command: ${text}`);
},
});
const { manager, started } = await startInjected(
injected.spawnProcess,
{
// The injected stream has no OS process identity. Exercise protocol detach
// here; real debugger process ownership is covered by process boundaries.
stopProcess: async (session) => {
if (session.exited) return { status: "already_exited" };
try {
await session.detachInferior?.();
injected.control.exit();
return { status: "stopped" };
} catch (cause) {
return {
status: "incomplete",
code: "stop-failed",
reason: String(cause),
};
}
},
},
{ REA_DEBUGGER_MAX_COMMAND_OUTPUT_BYTES: "8" },
);
if (!started.ok) throw started.error;
const result = await manager.execute(started.value.session_id, "noisy");
expect(result.ok).toBe(!retry);
expect(writes.some((text) => text.startsWith("olj\n"))).toBe(!retry);
if (retry) {
if (result.ok) throw new Error("Expected retained cleanup");
expect(result.error.cleanupIncomplete).toBe(true);
expect(manager.status(started.value.session_id)).toBeDefined();
expect(
(await manager.execute(started.value.session_id, "later")).ok,
).toBe(false);
synchronizationAllowed = true;
expect((await manager.close(started.value.session_id)).ok).toBe(true);
expect(result.error.cleanupIncomplete).toBe(false);
}
expect(writes.some((text) => text.startsWith("olj\n"))).toBe(true);
if (!retry)
expect((await manager.close(started.value.session_id)).ok).toBe(true);
expect(manager.status(started.value.session_id)).toBeUndefined();
},
);
it.skipIf(process.platform === "win32")(
"retains the producing protocol diagnosis after cleanup synchronization recovers transport",
async () => {
const injected = createInjectedProcess({
onWrite: (text, control) => {
const marker = /!echo (.+)\n/u.exec(text)?.[1];
if (marker === undefined) return;
if (text.startsWith("!echo __REA_CLEANUP_SYNC_"))
control.output(`${marker}\0`);
else if (text.startsWith("olj\n")) control.output(`[]\0${marker}\0`);
else throw new Error(`Unexpected command: ${text}`);
},
});
const { manager, started } = await startInjected(injected.spawnProcess, {
stopProcess: stopOwnedDebuggerProcess,
});
if (!started.ok) throw started.error;
injected.control.output("unsolicited\0");
const result = await manager.execute(
started.value.session_id,
"never dispatched",
);
expect(result.ok).toBe(false);
if (!result.ok) {
expect(result.error).toMatchObject({
_tag: "AnalysisCapabilityUnavailableError",
reason: expect.stringMatching(
/unsolicited Rizin frames.*before a command.*no longer.*safely correlated/i,
),
});
expect(result.error.cleanupIncomplete).toBe(false);
}
expect(manager.status(started.value.session_id)?.state).toBe("closed");
},
);
it.skipIf(process.platform === "win32").each([
{ stage: "output", incomplete: false },
{ stage: "output", incomplete: true },
{ stage: "timeout", incomplete: false },
{ stage: "timeout", incomplete: true },
{ stage: "exited", incomplete: false },
{ stage: "exited", incomplete: true },
] as const)(
"preserves cancellation during $stage final cleanup (incomplete=$incomplete)",
async ({ stage, incomplete }) => {
const controller = new AbortController();
const reason = { boundary: "final cleanup" };
const debuggerFinalCleanup = phaseGate();
let stopping = true;
const injected = createInjectedProcess({
onWrite: (_text, control) => {
if (stage === "output")
control.output("beyond selected output budget\0");
if (stage === "exited") {
control.output("partial\0");
control.exit();
}
},
});
const { manager, started } = await startInjected(
injected.spawnProcess,
{
stopProcess: async () => {
if (stopping) {
await debuggerFinalCleanup.hold();
}
return incomplete && stopping
? {
status: "incomplete",
code: "stop-failed",
reason: "stop settlement pending",
}
: { status: "stopped" };
},
},
{
REA_DEBUGGER_COMMAND_DEADLINE_MS: "10",
REA_DEBUGGER_MAX_COMMAND_OUTPUT_BYTES: stage === "output" ? "8" : "128",
},
);
if (!started.ok) throw started.error;
const pending = manager.execute(
started.value.session_id,
"noisy",
controller.signal,
);
await withVerifierCleanup(async () => {
await debuggerFinalCleanup.reached(pending, "debugger final cleanup");
controller.abort(reason);
debuggerFinalCleanup.release();
const result = await pending;
expect(result.ok).toBe(false);
if (result.ok) return;
expect(result.error).toMatchObject({
_tag: "AnalysisCancelledError",
cleanupIncomplete: incomplete,
});
expect(result.error.cause).toBe(reason);
expect(result.error.capturedOutput?.stdout).toBe(
stage === "output" ? "beyond s" : stage === "exited" ? "partial" : "",
);
expect(result.error.partialObservation).toBeDefined();
if (incomplete) {
stopping = false;
expect((await manager.close(started.value.session_id)).ok).toBe(true);
expect(result.error.cleanupIncomplete).toBe(false);
}
}, [
debuggerFinalCleanup.release,
async () => {
await pending;
},
() => {
stopping = false;
},
]);
},
);
it.skipIf(process.platform === "win32")(
"accepts cleanup readback larger than the caller command-output cap",
async () => {
const cleanupReadback = `${" ".repeat(32)}[]`;
const injected = createInjectedProcess({
onWrite: (text, control) => {
const marker = /!echo (.+)\n/u.exec(text)?.[1];
if (marker === undefined) return;
if (text.startsWith("ok\n")) control.output(`ok\0${marker}\0`);
else if (text.startsWith("olj\n"))
control.output(`${cleanupReadback}\0${marker}\0`);
else control.output(`${marker}\0`);
},
});
const { manager, started } = await startInjected(
injected.spawnProcess,
{
stopProcess: async (session) => {
try {
await session.detachInferior?.();
injected.control.exit();
return { status: "stopped" };
} catch (cause) {
return {
status: "incomplete",
code: "stop-failed",
reason: String(cause),
};
}
},
},
{ REA_DEBUGGER_MAX_COMMAND_OUTPUT_BYTES: "8" },
);
if (!started.ok) throw started.error;
const executed = await manager.execute(started.value.session_id, "ok");
if (!executed.ok) throw executed.error;
expect(executed.value.result.completion_status).toBe("complete");
expect(Buffer.byteLength(cleanupReadback, "utf8")).toBeGreaterThan(8);
const closed = await manager.close(started.value.session_id);
if (!closed.ok) throw closed.error;
expect(closed.value).toEqual({ target_state: "unknown" });
},
);
it.skipIf(process.platform === "win32")(
"retains a startup protocol diagnosis across successful cleanup synchronization",
async () => {
const injected = createInjectedProcess({
startup: (control) => control.stdinError(),
onWrite: (text, control) => {
const marker = /!echo (.+)\n/u.exec(text)?.[1];
if (marker === undefined) return;
control.output(
text.startsWith("olj\n") ? `[]\0${marker}\0` : `${marker}\0`,
);
},
});
const { started } = await startInjected(injected.spawnProcess, {
stopProcess: stopOwnedDebuggerProcess,
});
expect(started.ok).toBe(false);
if (!started.ok)
expect(started.error).toMatchObject({
_tag: "AnalysisCapabilityUnavailableError",
reason: "Rizin stdin stream failed: injected stdin error",
cleanupIncomplete: false,
});
},
);
it.skipIf(process.platform === "win32").each([false, true])(
"preserves cancellation observed during failed startup cleanup (incomplete=%s)",
async (incomplete) => {
const controller = new AbortController();
const reason = { boundary: "startup cleanup" };
const injected = createInjectedProcess({
startup: (control) => control.stdinError(),
});
let retained = true;
const manager = createManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{
spawnProcess: injected.spawnProcess,
stopProcess: async () => {
controller.abort(reason);
return incomplete && retained
? {
status: "incomplete",
code: "stop-failed",
reason: "stop settlement pending",
}
: { status: "stopped" };
},
},
);
const result = await manager.start(
{ path: "/tmp/injected", inferior_tty: await rizinTestInferiorTty() },
controller.signal,
);
expect(result.ok).toBe(false);
if (result.ok) return;
const primary = result.error.cleanupPrimary ?? result.error;
expect(primary).toMatchObject({
_tag: "AnalysisCapabilityUnavailableError",
reason: "Rizin stdin stream failed: injected stdin error",
});
expect(primary.secondaryFailures[0]).toMatchObject({
_tag: "AnalysisCancelledError",
});
expect(primary.secondaryFailures[0]?.cause).toBe(reason);
expect(result.error.cleanupIncomplete).toBe(incomplete);
if (incomplete) {
// The composed failure names why cleanup is incomplete at its top level.
expect(result.error.diagnostics).toMatchObject({
debugger_cleanup: "stop-failed",
});
retained = false;
await manager.closeAll();
expect(result.error.cleanupIncomplete).toBe(false);
}
},
);
it.skipIf(process.platform === "win32")(
"binds command Evidence to the session and the launch file hashed before Rizin starts",
async () => {
const directory = await createTestTempDirectory("rea-rizin-launch-");
const launchFile = join(directory, "target.bin");
await writeFile(launchFile, "launch bytes");
const missing = join(directory, "missing.bin");
for (const path of [launchFile, missing]) {
const injected = createInjectedProcess({
// Rewriting the file after the hash must not rebind the session.
beforeSpawnReturns: () => {
if (path === launchFile) writeFileSync(launchFile, "after spawn");
},
onWrite: (text, control) => {
const marker = /!echo (.+)\n/u.exec(text)?.[1];
if (marker !== undefined)
setImmediate(() => {
control.output(Buffer.from([0]));
control.output(Buffer.from(`${marker}\0`));
});
},
});
const manager = createManager(
{ REA_RIZIN_COMMAND: "injected-rizin" },
{ spawnProcess: injected.spawnProcess },
);
const started = await manager.start({
path,
inferior_tty: await rizinTestInferiorTty(),
});
if (!started.ok) throw started.error;
const first = await manager.execute(started.value.session_id, "dr");
if (!first.ok) throw first.error;
await writeFile(launchFile, "between commands");
const result = await manager.execute(started.value.session_id, "dr");
if (!result.ok) throw result.error;
expect(
result.value.evidence.subject,
"later commands keep the subject bound at start",
).toEqual(first.value.evidence.subject);
expect(
result.value.evidence.subject,
"the subject is the minted session bound to its launch file, or an explicit unknown when the file could not be hashed",
).toEqual({
identity: {
kind: "session",
session_kind: "rizin",
id: started.value.session_id,
target:
path === launchFile
? {
kind: "file",
sha256: createHash("sha256")
.update("launch bytes")
.digest("hex"),
format: "file",
architecture: null,
selection: null,
}
: { kind: "unknown", reason: "not-observed" },
},
name: null,
local_path: null,
});
expect(
result.value.evidence.limitations.some((limitation) =>
/launch file could not be hashed/iu.test(limitation),
),
"only an unhashable launch file records the hash failure",
).toBe(path === missing);
}
},
);