fix(reverse): reconcile cleanup ownership and mutation diagnostics (#2799)
* feat(process): add owned debugger shutdown lifecycle * feat(reverse): add local inspection commands * feat(gdb): add persistent debugger integration * feat(cutter): add Cutter bridge integration * test(reverse): enforce complete integration coverage * fix(process): preserve debugger shutdown ownership * fix(reverse): retain evidence across interrupted commands * fix(gdb): honor captured provider environment * test(process): cover debugger shutdown retries * fix(reverse): retain evidence for interrupted providers * test(process): cover debugger shutdown retries * fix(reverse): retain evidence for interrupted providers * fix(server): snapshot provider environment at creation * fix(reverse): close review gaps with complete coverage * fix(reverse): address inspection review findings * fix(gdb): bound sessions and retain cleanup ownership * fix(ci): require reverse-tools quality lane * fix(process): unref inherited debugger output pipes * fix(reverse): address remaining PR 1960 findings * fix(gdb): address remaining PR 1961 findings * fix(reverse): account for unrestricted provider execution * fix(process): retain debugger ownership until safe shutdown * fix(process): preserve replacement debugger sessions * fix(reverse): preserve admission and output provenance * fix(process): retain exited debugger until output settles * fix(mcp): bound provider admission and debugger cleanup * fix(reverse): preserve failure provenance and classify E2BIG * fix(gdb): preserve startup cleanup and detach safety * fix(process): retain debugger ownership after detach failure * fix(reverse): preserve mutation and failure provenance * fix(gdb): address debugger review findings * fix(reverse): rebind sessions after external mutation * fix(process): cap debugger output after exit * fix(gdb): protect one-shot detach verification * feat(debugger): add reverse tool coverage gate * test(debugger): cover integrated failure paths * fix(gdb): bound and preserve session observations * fix(gdb): address review regressions * style: format merged integration files * fix(reverse): preserve session and output evidence * refactor(gdb): share repeated test and partial result setup * fix(gdb): invalidate TTY proof for Python aliases * fix(reverse): retain failure output byte counts * test(process): synchronize late debugger output * fix(gdb): invalidate TTY proof for wrapped commands * fix(gdb): recognize wit command abbreviation * test(reverse): wait for cancelled descendant readiness * test(reverse): bound descendant cancellation cleanup * style(reverse): format integration tests and adapters * style: format reverse engineering integration files * test(reverse): remove duplicate environment harness * test(gdb): share session startup assertions * fix(gdb): invalidate output proof for command abbreviations * test(reverse): share composition edge case scenarios * fix(ci): recognize verification and mutation tool entries * test(rizin): cover successful fake inferior detach * test(cli): align full output failure envelope * test(cli): isolate reverse command lifecycle service * test(process): share debugger output fixture setup * fix(binary): preserve high-bit Windows signature bytes * style(binary): format Windows signature parser * test(mcp): preserve call coverage in unchanged comparison * fix(ci): include reverse tools Vitest configs in lint cache * fix(mcp): preserve target content on delivery errors * ci: align duplication ceiling with expanded suite * test(reverse): allow signal admission mutants * fix(reverse): bound retained cleanup failures to process owners * fix(test): replace drifting mutation ranges with owned selectors * fix(reverse): admit persistent commands and retain cleanup ownership * fix(cutter): recover timed-out commands from exact receipts * fix(cutter): reject unsupported bridge request kinds * fix(ci): repair client format and shared verification fixtures * fix(native): preserve debugger cleanup ownership and bridge authentication * test(native): retain diagnostics without perfect coverage requirements * chore(licenses): refresh locked dependency inventory and notices * fix(test): exclude transient command locks from mutation sandboxes * fix(gdb): admit only platforms with safe detach verification * fix(cutter): retain bounded completion receipts until acknowledgement * fix(cutter): acknowledge commands rejected before UI dispatch * test(reverse): fail cancellation checks before fixture teardown * test(gdb): clean up the retained broken-stdin fixture owner * docs(test): clarify focused provider verification scope * fix(rizin): retain close cleanup failures * fix(gdb): wait for inferior stop and bound MI buffering * fix(cutter): retain failed receipt acknowledgements * fix(rizin): return retained session identity on rebind failure * fix(gdb): preserve startup cancellation and lossy status * fix(rizin): retain launch provenance and assemble frames once * fix(cutter): recover receipts across callers and bound discovery * docs: describe debugger evidence and bridge recovery * fix(process): keep cleanup incomplete while writers remain Stopping a debugger no longer reports success when inherited output streams stay open, so BinarySession cannot reopen a binary a child is still changing. Concurrent Cutter cleanup retries share one receipt acknowledgement instead of treating a consumed receipt as failure. * fix(debuggers): recover cleanup with captured process identities * fix(analysis): retire sessions after unrestricted commands * fix(cli): preserve completed evidence after cleanup recovery * fix(cutter): bound frame collection and coalesce cleanup * fix(windows): resolve selected provider paths absolutely * fix(gdb): report decoding loss in failed startup evidence * fix(rizin): scope decoding loss to collected command frames * test(mcp): cover snapshot retirement in reverse tools CI --------- Co-authored-by: Daniel Gonçalves Araujo <47118053+dandgabr@users.noreply.github.com> Co-authored-by: REA Maintainers <noreply@github.com> Co-authored-by: OpenAI Codex <codex@users.noreply.github.com> Co-authored-by: Cursor Agent <cursoragent@cursor.com>
This commit is contained in:
co-authored by
Daniel Gonçalves Araujo
REA Maintainers
OpenAI Codex
Cursor Agent
parent
2ad2a044d4
commit
4aa51bfe19
@@ -0,0 +1,132 @@
|
||||
import { randomUUID } from "node:crypto";
|
||||
import { chmod, writeFile } from "node:fs/promises";
|
||||
import { createServer, type Socket } from "node:net";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { CutterBridgeClient } from "../../../src/cutter/CutterBridgeClient.js";
|
||||
import { CutterBridgeService } from "../../../src/cutter/CutterBridgeService.js";
|
||||
import { cutterDiscoverySchema } from "../../../src/contracts/cutterToolContracts.js";
|
||||
import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js";
|
||||
|
||||
const descriptor = async (directory: string, port: number): Promise<string> => {
|
||||
const sessionId = randomUUID();
|
||||
await writeFile(
|
||||
join(directory, `cutter-${process.pid}-${sessionId}.json`),
|
||||
JSON.stringify({
|
||||
session_id: sessionId,
|
||||
pid: process.pid,
|
||||
host: "127.0.0.1",
|
||||
port,
|
||||
token: "capacity-test-token-123456789",
|
||||
document_generation: 0,
|
||||
current_file: null,
|
||||
cutter_version: null,
|
||||
identity_status: "partial",
|
||||
}),
|
||||
{ mode: 0o600 },
|
||||
);
|
||||
return sessionId;
|
||||
};
|
||||
|
||||
it("reports descriptor capacity without opening candidates or claiming no live sessions", async () => {
|
||||
const directory = await createTestTempDirectory("rea-cutter-capacity-");
|
||||
await chmod(directory, 0o700);
|
||||
const selectedSession = await descriptor(directory, 1);
|
||||
for (let index = 1; index < 257; index += 1) await descriptor(directory, 1);
|
||||
const client = new CutterBridgeClient(
|
||||
{ REA_CUTTER_BRIDGE_DIR: directory },
|
||||
{ platform: "linux" },
|
||||
);
|
||||
const result = await client.listSessions();
|
||||
expect(cutterDiscoverySchema.parse(result)).toMatchObject({
|
||||
sessions: [],
|
||||
discovery_status: "bridge_directory_capacity_exceeded",
|
||||
bridge_directory_security: "private_verified",
|
||||
});
|
||||
const service = new CutterBridgeService(client);
|
||||
expect(
|
||||
await service.execute({
|
||||
session_id: selectedSession,
|
||||
expected_generation: 0,
|
||||
command: "iI",
|
||||
json: false,
|
||||
}),
|
||||
).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisResourceConstraintError",
|
||||
cleanupIncomplete: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("bounds simultaneous socket probes while examining every admitted descriptor", async () => {
|
||||
const directory = await createTestTempDirectory("rea-cutter-probes-");
|
||||
await chmod(directory, 0o700);
|
||||
const sockets = new Set<Socket>();
|
||||
let peak = 0;
|
||||
let probes = 0;
|
||||
const server = createServer((socket) => {
|
||||
sockets.add(socket);
|
||||
probes += 1;
|
||||
peak = Math.max(peak, sockets.size);
|
||||
socket.once("close", () => sockets.delete(socket));
|
||||
setTimeout(() => socket.destroy(), 20);
|
||||
});
|
||||
await new Promise<void>((resolve) => server.listen(0, "127.0.0.1", resolve));
|
||||
try {
|
||||
const address = server.address();
|
||||
if (address === null || typeof address === "string")
|
||||
throw new Error("listener missing");
|
||||
for (let index = 0; index < 24; index += 1)
|
||||
await descriptor(directory, address.port);
|
||||
const client = new CutterBridgeClient(
|
||||
{ REA_CUTTER_BRIDGE_DIR: directory },
|
||||
{ platform: "linux" },
|
||||
);
|
||||
expect((await client.listSessions()).discovery_status).toBe(
|
||||
"no_live_bridge_found",
|
||||
);
|
||||
expect(probes).toBe(24);
|
||||
expect(peak).toBeGreaterThan(1);
|
||||
expect(peak).toBeLessThanOrEqual(8);
|
||||
} finally {
|
||||
for (const socket of sockets) socket.destroy();
|
||||
await new Promise<void>((resolve) => server.close(() => resolve()));
|
||||
}
|
||||
});
|
||||
|
||||
it("rejects expanded authenticated frames before dispatch and retains no cleanup owner", async () => {
|
||||
const directory = await createTestTempDirectory("rea-cutter-frame-");
|
||||
await chmod(directory, 0o700);
|
||||
const sessionId = await descriptor(directory, 1);
|
||||
const service = new CutterBridgeService(
|
||||
new CutterBridgeClient(
|
||||
{ REA_CUTTER_BRIDGE_DIR: directory },
|
||||
{ platform: "linux" },
|
||||
),
|
||||
);
|
||||
const input = { session_id: sessionId, expected_generation: 0, json: false };
|
||||
const rejected = await service.execute({
|
||||
...input,
|
||||
command: '"'.repeat(4 * 1024 * 1024 + 1024),
|
||||
});
|
||||
expect(rejected).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisResourceConstraintError",
|
||||
cleanupIncomplete: false,
|
||||
},
|
||||
});
|
||||
expect(await service.retryCleanup()).toEqual({ ok: true, value: null });
|
||||
// A later valid command reaches transport, rather than replaying the resource failure.
|
||||
expect(await service.execute({ ...input, command: "iI" })).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisCapabilityUnavailableError",
|
||||
cleanupIncomplete: false,
|
||||
},
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,177 @@
|
||||
import { createServer } from "node:net";
|
||||
import { createHmac } from "node:crypto";
|
||||
import { readFileSync } from "node:fs";
|
||||
import { mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
|
||||
import { CutterBridgeClient } from "../../../src/cutter/CutterBridgeClient.js";
|
||||
|
||||
const SESSION_ID = "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a";
|
||||
const TOKEN = "synthetic-cutter-bridge-token-for-test";
|
||||
let directory: string | undefined;
|
||||
let server: ReturnType<typeof createServer> | undefined;
|
||||
|
||||
afterEach(async () => {
|
||||
if (server !== undefined)
|
||||
await new Promise<void>((resolve) => server?.close(() => resolve()));
|
||||
if (directory !== undefined)
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
server = undefined;
|
||||
directory = undefined;
|
||||
});
|
||||
|
||||
const listen = async (
|
||||
listener: ReturnType<typeof createServer>,
|
||||
): Promise<number> => {
|
||||
await new Promise<void>((resolve) =>
|
||||
listener.listen(0, "127.0.0.1", resolve),
|
||||
);
|
||||
const address = listener.address();
|
||||
if (address === null || typeof address === "string")
|
||||
throw new Error("Expected an ephemeral IPv4 listener");
|
||||
return address.port;
|
||||
};
|
||||
|
||||
const bridgeServer = (
|
||||
currentFile: string | null,
|
||||
documentGeneration: number,
|
||||
): ReturnType<typeof createServer> => {
|
||||
let ordinal = 0;
|
||||
return createServer((connection) => {
|
||||
const connectionOrdinal = ++ordinal;
|
||||
connection.setEncoding("utf8");
|
||||
let input = "";
|
||||
let clientNonce = "";
|
||||
let serverNonce = "";
|
||||
connection.on("data", (chunk: string) => {
|
||||
input += chunk;
|
||||
const newline = input.indexOf("\n");
|
||||
if (newline < 0) return;
|
||||
const frame = JSON.parse(input.slice(0, newline)) as Record<
|
||||
string,
|
||||
unknown
|
||||
>;
|
||||
input = input.slice(newline + 1);
|
||||
if (frame.kind === "rea-auth-v2") {
|
||||
clientNonce = String(frame.nonce);
|
||||
serverNonce =
|
||||
connectionOrdinal.toString(16).padStart(16, "0") + "d".repeat(48);
|
||||
connection.write(
|
||||
`${JSON.stringify({ session_id: SESSION_ID, nonce: serverNonce, proof: createHmac("sha256", TOKEN).update(`rea-cutter-server-v2:${SESSION_ID}:${clientNonce}:${serverNonce}`).digest("hex") })}\n`,
|
||||
);
|
||||
return;
|
||||
}
|
||||
const requestBytes = String(frame.request);
|
||||
const request = JSON.parse(requestBytes) as Record<string, unknown>;
|
||||
const expected = createHmac("sha256", TOKEN)
|
||||
.update(
|
||||
`rea-cutter-client-v2:${SESSION_ID}:${clientNonce}:${serverNonce}:${requestBytes}`,
|
||||
)
|
||||
.digest("hex");
|
||||
if (frame.proof !== expected) {
|
||||
connection.destroy();
|
||||
return;
|
||||
}
|
||||
if (!["status", "command", "ack"].includes(String(request.kind)))
|
||||
throw new Error(`Unmodeled bridge request: ${String(request.kind)}`);
|
||||
const response = JSON.stringify(
|
||||
request.kind === "ack"
|
||||
? {
|
||||
ok: true,
|
||||
acknowledged: false,
|
||||
}
|
||||
: {
|
||||
ok: true,
|
||||
session_id: request.session_id,
|
||||
current_file: currentFile,
|
||||
document_generation: documentGeneration,
|
||||
cutter_version: "Cutter fixture version",
|
||||
identity_status: "partial",
|
||||
...(request.kind === "status"
|
||||
? {
|
||||
completed_connection: (connectionOrdinal - 1)
|
||||
.toString(16)
|
||||
.padStart(16, "0"),
|
||||
completed_commands: [],
|
||||
}
|
||||
: { execution_state: "complete" }),
|
||||
},
|
||||
);
|
||||
const proof = createHmac("sha256", TOKEN)
|
||||
.update(
|
||||
`rea-cutter-response-v2:${SESSION_ID}:${clientNonce}:${serverNonce}:${response}`,
|
||||
)
|
||||
.digest("hex");
|
||||
connection.end(`${JSON.stringify({ response, proof })}\n`);
|
||||
});
|
||||
});
|
||||
};
|
||||
|
||||
const clientFor = (bridgeDirectory: string): CutterBridgeClient =>
|
||||
process.platform === "win32"
|
||||
? new CutterBridgeClient(
|
||||
{ REA_CUTTER_BRIDGE_DIR: bridgeDirectory },
|
||||
{
|
||||
windowsPrivateReader: {
|
||||
verifyDirectory: () => true,
|
||||
readDescriptor: (root, name, maxBytes) => {
|
||||
const bytes = readFileSync(join(root, name));
|
||||
if (bytes.byteLength > maxBytes)
|
||||
throw new Error("Descriptor too large");
|
||||
return bytes;
|
||||
},
|
||||
},
|
||||
},
|
||||
)
|
||||
: new CutterBridgeClient({ REA_CUTTER_BRIDGE_DIR: bridgeDirectory });
|
||||
|
||||
const writeDescriptor = async (port: number): Promise<void> => {
|
||||
if (directory === undefined) throw new Error("Test directory is unavailable");
|
||||
await writeFile(
|
||||
join(directory, `cutter-${process.pid}-${SESSION_ID}.json`),
|
||||
JSON.stringify({
|
||||
session_id: SESSION_ID,
|
||||
pid: process.pid,
|
||||
host: "127.0.0.1",
|
||||
port,
|
||||
token: TOKEN,
|
||||
document_generation: 1,
|
||||
current_file: "/old/sample.bin",
|
||||
cutter_version: "Cutter fixture version",
|
||||
identity_status: "partial",
|
||||
}),
|
||||
{ mode: 0o600 },
|
||||
);
|
||||
};
|
||||
|
||||
it("preserves a live Cutter status that explicitly has no active document", async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "rea-cutter-null-status-"));
|
||||
server = bridgeServer(null, 2);
|
||||
await writeDescriptor(await listen(server));
|
||||
|
||||
const result = await clientFor(directory).listSessions();
|
||||
|
||||
expect(result.sessions[0]).toMatchObject({
|
||||
session_id: SESSION_ID,
|
||||
document_generation: 2,
|
||||
current_file: null,
|
||||
});
|
||||
});
|
||||
|
||||
it("preserves a null active document returned after a Cutter command", async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "rea-cutter-null-command-"));
|
||||
server = bridgeServer(null, 2);
|
||||
await writeDescriptor(await listen(server));
|
||||
|
||||
const result = await clientFor(directory).execute({
|
||||
sessionId: SESSION_ID,
|
||||
expectedGeneration: 2,
|
||||
command: "ij",
|
||||
json: true,
|
||||
});
|
||||
|
||||
expect(result.currentFile).toBeNull();
|
||||
});
|
||||
@@ -0,0 +1,406 @@
|
||||
import { expect, it, vi } from "vitest";
|
||||
|
||||
import { CutterBridgeService } from "../../../src/cutter/CutterBridgeService.js";
|
||||
|
||||
const cutterInput = {
|
||||
session_id: "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a",
|
||||
expected_generation: 7,
|
||||
command: "pd 4",
|
||||
};
|
||||
|
||||
it("retains uncertain command completion as Evidence without encouraging a retry", async () => {
|
||||
const service = new CutterBridgeService({
|
||||
listSessions: async () => ({
|
||||
sessions: [],
|
||||
bridge_directory: "/private/bridge",
|
||||
discovery_status: "no_live_bridge_found",
|
||||
bridge_directory_security: "private_verified",
|
||||
}),
|
||||
execute: async () => ({
|
||||
requestId: "4b18ce4d-bf31-456e-ae31-e8c547b2f9db",
|
||||
output: null,
|
||||
currentFile: "/fixtures/sample.bin",
|
||||
documentGeneration: 7,
|
||||
identityStatus: "partial",
|
||||
cutterVersion: "Cutter fixture version",
|
||||
executionState: "unknown",
|
||||
error: "transport-response-missing",
|
||||
message: "The command may have completed; do not retry automatically",
|
||||
outputTruncated: false,
|
||||
}),
|
||||
});
|
||||
|
||||
const result = await service.execute({
|
||||
session_id: "27d3e3f1-f1e5-49ae-91ec-95af1f343a5a",
|
||||
expected_generation: 7,
|
||||
command: "Ps /tmp/project.rzdb",
|
||||
});
|
||||
|
||||
expect(result).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisOutputError",
|
||||
cleanupIncomplete: true,
|
||||
partialObservation: {
|
||||
normalized_result: {
|
||||
command: "Ps /tmp/project.rzdb",
|
||||
output: null,
|
||||
execution_state: "unknown",
|
||||
error: "transport-response-missing",
|
||||
message: expect.stringContaining("do not retry automatically"),
|
||||
document_generation: 7,
|
||||
cutter_version: "Cutter fixture version",
|
||||
},
|
||||
limitations: expect.arrayContaining([
|
||||
"Command completion or its output could not be confirmed; do not retry automatically because the command may have produced partial or persistent effects.",
|
||||
]),
|
||||
provider: { version: "Cutter fixture version" },
|
||||
},
|
||||
},
|
||||
});
|
||||
});
|
||||
|
||||
it("clears a poisoned command only after its exact UI-dispatcher receipt", async () => {
|
||||
const requestId = "4b18ce4d-bf31-456e-ae31-e8c547b2f9db";
|
||||
const wrongId = "8ca93d11-107d-41ed-8b40-31dd53cd26a6";
|
||||
let receipt: string | undefined;
|
||||
let uiPending = true;
|
||||
let dispatches = 0;
|
||||
const confirmCommandCompletion = vi.fn(
|
||||
async (_session: string, id: string) =>
|
||||
receipt === id && !uiPending
|
||||
? { ok: true as const, value: true }
|
||||
: { ok: true as const, value: false },
|
||||
);
|
||||
const service = new CutterBridgeService({
|
||||
listSessions: async () => ({
|
||||
sessions: [],
|
||||
bridge_directory: "/private/bridge",
|
||||
discovery_status: "no_live_bridge_found",
|
||||
bridge_directory_security: "private_verified",
|
||||
}),
|
||||
confirmCommandCompletion,
|
||||
execute: async () => {
|
||||
dispatches += 1;
|
||||
return {
|
||||
requestId,
|
||||
output: null,
|
||||
currentFile: "/fixtures/sample.bin",
|
||||
documentGeneration: 7,
|
||||
identityStatus: "partial",
|
||||
cutterVersion: "Cutter fixture version",
|
||||
executionState: dispatches === 1 ? "unknown" : "complete",
|
||||
error: dispatches === 1 ? "ui-thread-request-timeout" : null,
|
||||
message: null,
|
||||
outputTruncated: false,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
const first = await service.execute(cutterInput);
|
||||
expect(first).toMatchObject({
|
||||
ok: false,
|
||||
error: { cleanupIncomplete: true },
|
||||
});
|
||||
|
||||
for (const unconfirmed of [
|
||||
undefined,
|
||||
"ede4bbfd-6348-46aa-963b-0de0e78ccbdc",
|
||||
wrongId,
|
||||
]) {
|
||||
receipt = unconfirmed;
|
||||
const blocked = await service.execute(cutterInput);
|
||||
expect(blocked).toMatchObject({
|
||||
ok: false,
|
||||
error: { cleanupIncomplete: true },
|
||||
});
|
||||
expect(dispatches).toBe(1);
|
||||
}
|
||||
receipt = requestId;
|
||||
const pending = await service.execute(cutterInput);
|
||||
expect(pending).toMatchObject({
|
||||
ok: false,
|
||||
error: { cleanupIncomplete: true },
|
||||
});
|
||||
expect(dispatches).toBe(1);
|
||||
expect(confirmCommandCompletion).toHaveBeenLastCalledWith(
|
||||
cutterInput.session_id,
|
||||
requestId,
|
||||
undefined,
|
||||
);
|
||||
|
||||
receipt = requestId;
|
||||
uiPending = false;
|
||||
const recovered = await service.execute(cutterInput);
|
||||
expect(recovered.ok).toBe(true);
|
||||
expect(dispatches).toBe(2);
|
||||
});
|
||||
|
||||
it("recovers canceled command A after B and does not retain poisoned B", async () => {
|
||||
const requestA = "4b18ce4d-bf31-456e-ae31-e8c547b2f9db";
|
||||
const completionTokenA = "0000000000000007";
|
||||
const requestB = "8ca93d11-107d-41ed-8b40-31dd53cd26a6";
|
||||
const receipts = new Set<string>();
|
||||
let dispatches = 0;
|
||||
const confirmCommandCompletion = vi.fn(
|
||||
async (_session: string, id: string) =>
|
||||
receipts.delete(id)
|
||||
? { ok: true as const, value: true }
|
||||
: { ok: true as const, value: false },
|
||||
);
|
||||
const execute = async () => {
|
||||
dispatches += 1;
|
||||
if (dispatches === 1) {
|
||||
receipts.add(requestA);
|
||||
return {
|
||||
requestId: requestA,
|
||||
output: null,
|
||||
currentFile: "/fixtures/sample.bin",
|
||||
documentGeneration: 7,
|
||||
identityStatus: "partial" as const,
|
||||
cutterVersion: null,
|
||||
executionState: "unknown" as const,
|
||||
error: "transport-response-missing",
|
||||
message: "cancelled after dispatch",
|
||||
outputTruncated: false,
|
||||
completionToken: completionTokenA,
|
||||
};
|
||||
}
|
||||
if (dispatches === 2)
|
||||
return {
|
||||
requestId: requestB,
|
||||
output: "B complete",
|
||||
currentFile: "/fixtures/sample.bin",
|
||||
documentGeneration: 7,
|
||||
identityStatus: "partial" as const,
|
||||
cutterVersion: null,
|
||||
executionState: "complete" as const,
|
||||
error: null,
|
||||
message: null,
|
||||
outputTruncated: false,
|
||||
};
|
||||
if (dispatches === 3)
|
||||
return {
|
||||
requestId: requestB,
|
||||
output: null,
|
||||
currentFile: "/fixtures/sample.bin",
|
||||
documentGeneration: 7,
|
||||
identityStatus: "partial" as const,
|
||||
cutterVersion: null,
|
||||
executionState: "not_started" as const,
|
||||
error: "session-poisoned-after-ui-timeout",
|
||||
message: null,
|
||||
outputTruncated: false,
|
||||
};
|
||||
return {
|
||||
requestId: "c31130c6-fc6c-46ad-949e-586724d8fd84",
|
||||
output: "recovered",
|
||||
currentFile: "/fixtures/sample.bin",
|
||||
documentGeneration: 7,
|
||||
identityStatus: "partial" as const,
|
||||
cutterVersion: null,
|
||||
executionState: "complete" as const,
|
||||
error: null,
|
||||
message: null,
|
||||
outputTruncated: false,
|
||||
};
|
||||
};
|
||||
const client = {
|
||||
listSessions: async () => ({
|
||||
sessions: [],
|
||||
bridge_directory: "/private/bridge",
|
||||
discovery_status: "no_live_bridge_found" as const,
|
||||
bridge_directory_security: "private_verified" as const,
|
||||
}),
|
||||
confirmCommandCompletion,
|
||||
execute,
|
||||
};
|
||||
const callerA = new CutterBridgeService(client);
|
||||
const callerB = new CutterBridgeService(client);
|
||||
|
||||
const cancelledA = await callerA.execute(cutterInput);
|
||||
expect(cancelledA).toMatchObject({
|
||||
ok: false,
|
||||
error: { cleanupIncomplete: true },
|
||||
});
|
||||
expect(await callerB.execute(cutterInput)).toMatchObject({ ok: true });
|
||||
expect(receipts.has(requestA)).toBe(true);
|
||||
|
||||
const poisonedB = await callerA.execute(cutterInput);
|
||||
expect(poisonedB).toMatchObject({
|
||||
ok: true,
|
||||
value: { normalized_result: { execution_state: "not_started" } },
|
||||
});
|
||||
expect(confirmCommandCompletion).toHaveBeenCalledTimes(1);
|
||||
expect(confirmCommandCompletion).toHaveBeenCalledWith(
|
||||
cutterInput.session_id,
|
||||
requestA,
|
||||
completionTokenA,
|
||||
);
|
||||
|
||||
expect(await callerA.execute(cutterInput)).toMatchObject({ ok: true });
|
||||
expect(confirmCommandCompletion).toHaveBeenCalledTimes(1);
|
||||
expect(dispatches).toBe(4);
|
||||
});
|
||||
|
||||
it("rejects malformed Cutter commands and pre-aborted calls", async () => {
|
||||
const service = new CutterBridgeService({
|
||||
listSessions: async () => ({
|
||||
sessions: [],
|
||||
bridge_directory: "/private/bridge",
|
||||
discovery_status: "no_live_bridge_found",
|
||||
bridge_directory_security: "private_verified",
|
||||
}),
|
||||
execute: async () => {
|
||||
throw new Error("must not dispatch");
|
||||
},
|
||||
});
|
||||
|
||||
const malformed = await service.execute({ ...cutterInput, command: "" });
|
||||
expect(malformed).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisInputError" },
|
||||
});
|
||||
const controller = new AbortController();
|
||||
controller.abort();
|
||||
const cancelled = await service.execute(cutterInput, {
|
||||
signal: controller.signal,
|
||||
});
|
||||
expect(cancelled).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
});
|
||||
|
||||
it.each([
|
||||
[new Error("session generation changed"), "AnalysisInputError"],
|
||||
[new Error("bridge disconnected"), "AnalysisCapabilityUnavailableError"],
|
||||
["plain failure", "AnalysisCapabilityUnavailableError"],
|
||||
])("maps a Cutter bridge failure to %s", async (failure, tag) => {
|
||||
const service = new CutterBridgeService({
|
||||
listSessions: async () => ({
|
||||
sessions: [],
|
||||
bridge_directory: "/private/bridge",
|
||||
discovery_status: "no_live_bridge_found",
|
||||
bridge_directory_security: "private_verified",
|
||||
}),
|
||||
execute: async () => {
|
||||
throw failure;
|
||||
},
|
||||
});
|
||||
|
||||
const result = await service.execute(cutterInput);
|
||||
expect(result).toMatchObject({ ok: false, error: { _tag: tag } });
|
||||
});
|
||||
|
||||
it("preserves cancellation unless the bridge reports an ambiguous completion", async () => {
|
||||
const createService = (message: string, controller: AbortController) =>
|
||||
new CutterBridgeService({
|
||||
listSessions: async () => ({
|
||||
sessions: [],
|
||||
bridge_directory: "/private/bridge",
|
||||
discovery_status: "no_live_bridge_found",
|
||||
bridge_directory_security: "private_verified",
|
||||
}),
|
||||
execute: async () => {
|
||||
controller.abort();
|
||||
throw new Error(message);
|
||||
},
|
||||
});
|
||||
const cancelledController = new AbortController();
|
||||
|
||||
const cancelled = await createService(
|
||||
"transport cancelled",
|
||||
cancelledController,
|
||||
).execute(cutterInput, { signal: cancelledController.signal });
|
||||
expect(cancelled).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCancelledError" },
|
||||
});
|
||||
|
||||
const uncertainController = new AbortController();
|
||||
const uncertain = await createService(
|
||||
"command may have completed",
|
||||
uncertainController,
|
||||
).execute(cutterInput, { signal: uncertainController.signal });
|
||||
expect(uncertain).toMatchObject({
|
||||
ok: false,
|
||||
error: { _tag: "AnalysisCapabilityUnavailableError" },
|
||||
});
|
||||
});
|
||||
|
||||
it("shares one cleanup attempt when commands retry the same receipt together", async () => {
|
||||
const requestId = "4b18ce4d-bf31-456e-ae31-e8c547b2f9db";
|
||||
let receiptPresent = false;
|
||||
let releaseConfirm: (() => void) | undefined;
|
||||
let confirms = 0;
|
||||
const confirmCommandCompletion = vi.fn(async () => {
|
||||
confirms += 1;
|
||||
if (!receiptPresent) return { ok: true as const, value: false };
|
||||
if (confirms === 1) {
|
||||
await new Promise<void>((resolve) => {
|
||||
releaseConfirm = resolve;
|
||||
});
|
||||
}
|
||||
if (!receiptPresent) return { ok: true as const, value: false };
|
||||
receiptPresent = false;
|
||||
return { ok: true as const, value: true };
|
||||
});
|
||||
let dispatches = 0;
|
||||
const service = new CutterBridgeService({
|
||||
listSessions: async () => ({
|
||||
sessions: [],
|
||||
bridge_directory: "/private/bridge",
|
||||
discovery_status: "no_live_bridge_found",
|
||||
bridge_directory_security: "private_verified",
|
||||
}),
|
||||
confirmCommandCompletion,
|
||||
execute: async () => {
|
||||
dispatches += 1;
|
||||
if (dispatches === 1) {
|
||||
receiptPresent = true;
|
||||
return {
|
||||
requestId,
|
||||
output: null,
|
||||
currentFile: "/fixtures/sample.bin",
|
||||
documentGeneration: 7,
|
||||
identityStatus: "partial" as const,
|
||||
cutterVersion: null,
|
||||
executionState: "unknown" as const,
|
||||
error: "transport-response-missing",
|
||||
message: "cancelled after dispatch",
|
||||
outputTruncated: false,
|
||||
};
|
||||
}
|
||||
return {
|
||||
requestId: "8ca93d11-107d-41ed-8b40-31dd53cd26a6",
|
||||
output: "complete",
|
||||
currentFile: "/fixtures/sample.bin",
|
||||
documentGeneration: 7,
|
||||
identityStatus: "partial" as const,
|
||||
cutterVersion: null,
|
||||
executionState: "complete" as const,
|
||||
error: null,
|
||||
message: null,
|
||||
outputTruncated: false,
|
||||
};
|
||||
},
|
||||
});
|
||||
|
||||
const blocked = await service.execute(cutterInput);
|
||||
expect(blocked).toMatchObject({
|
||||
ok: false,
|
||||
error: { cleanupIncomplete: true },
|
||||
});
|
||||
|
||||
const concurrent = [
|
||||
service.execute(cutterInput),
|
||||
service.execute(cutterInput),
|
||||
];
|
||||
if (releaseConfirm === undefined) throw new Error("cleanup did not start");
|
||||
releaseConfirm();
|
||||
const recovered = await Promise.all(concurrent);
|
||||
expect(recovered.every((result) => result.ok)).toBe(true);
|
||||
expect(confirms).toBe(1);
|
||||
expect(dispatches).toBe(3);
|
||||
});
|
||||
@@ -0,0 +1,145 @@
|
||||
import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
|
||||
import { GdbSessionManager } from "../../../src/gdb/GdbSessionManager.js";
|
||||
|
||||
let directory: string | undefined;
|
||||
const managers: GdbSessionManager[] = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
managers
|
||||
.splice(0)
|
||||
.map((manager) => manager.closeAll().catch(() => undefined)),
|
||||
);
|
||||
if (directory !== undefined)
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
directory = undefined;
|
||||
});
|
||||
|
||||
it("bounds active and queued GDB commands, including cancelled placeholders", async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "rea-gdb-command-queue-limit-"));
|
||||
const provider = join(directory, "fake-gdb-queue.mjs");
|
||||
const activePath = join(directory, "active-command");
|
||||
const releasePath = join(directory, "release-command");
|
||||
await writeFile(
|
||||
provider,
|
||||
`#!${process.execPath}
|
||||
import { access, writeFile } from "node:fs/promises";
|
||||
process.stdout.write("(gdb)\\n");
|
||||
let input = "";
|
||||
let firstConsoleCommand = true;
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", async (chunk) => {
|
||||
input += chunk;
|
||||
for (;;) {
|
||||
const boundary = input.indexOf("\\n");
|
||||
if (boundary < 0) break;
|
||||
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
|
||||
const match = /^(\\d+)/.exec(line);
|
||||
if (!match) continue;
|
||||
if (line.includes("-interpreter-exec console") && firstConsoleCommand) {
|
||||
firstConsoleCommand = false;
|
||||
await writeFile(${JSON.stringify(activePath)}, "active");
|
||||
for (;;) {
|
||||
try { await access(${JSON.stringify(releasePath)}); break; }
|
||||
catch { await new Promise((resolve) => setTimeout(resolve, 10)); }
|
||||
}
|
||||
}
|
||||
process.stdout.write(match[1] + "^done\\n");
|
||||
}
|
||||
});
|
||||
`,
|
||||
);
|
||||
await chmod(provider, 0o700);
|
||||
const manager = new GdbSessionManager({
|
||||
platform: "linux",
|
||||
environment: { REA_GDB_COMMAND: provider },
|
||||
});
|
||||
managers.push(manager);
|
||||
const started = await manager.start();
|
||||
expect(started.ok).toBe(true);
|
||||
if (!started.ok) return;
|
||||
|
||||
const active = manager.execute(started.value.session_id, "hold");
|
||||
let activeSeen = false;
|
||||
for (let attempt = 0; attempt < 100 && !activeSeen; attempt += 1) {
|
||||
try {
|
||||
await readFile(activePath, "utf8");
|
||||
activeSeen = true;
|
||||
} catch {
|
||||
await new Promise((resolve) => setTimeout(resolve, 10));
|
||||
}
|
||||
}
|
||||
expect(activeSeen).toBe(true);
|
||||
|
||||
const controllers = Array.from({ length: 15 }, () => new AbortController());
|
||||
const queued = controllers.map((controller, index) =>
|
||||
manager.execute(
|
||||
started.value.session_id,
|
||||
`queued-${index}`,
|
||||
controller.signal,
|
||||
),
|
||||
);
|
||||
const safetyRelease = setTimeout(() => {
|
||||
void writeFile(releasePath, "safety release");
|
||||
}, 250);
|
||||
const overflow = await manager.execute(started.value.session_id, "overflow");
|
||||
clearTimeout(safetyRelease);
|
||||
expect(overflow).toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisResourceConstraintError",
|
||||
operation: "gdb_console",
|
||||
resource: "transport",
|
||||
reportedLimits: {
|
||||
max_pending_commands: 16,
|
||||
active_or_queued_commands: 16,
|
||||
},
|
||||
},
|
||||
});
|
||||
|
||||
for (const controller of controllers) controller.abort();
|
||||
const cancelled = await Promise.all(queued);
|
||||
expect(cancelled).toHaveLength(15);
|
||||
expect(
|
||||
cancelled.every(
|
||||
(result) => !result.ok && result.error._tag === "AnalysisCancelledError",
|
||||
),
|
||||
).toBe(true);
|
||||
const cancellationSafetyRelease = setTimeout(() => {
|
||||
void writeFile(releasePath, "safety release after cancellation");
|
||||
}, 250);
|
||||
try {
|
||||
await expect(
|
||||
manager.execute(
|
||||
started.value.session_id,
|
||||
"cannot-bypass-cancelled-placeholders",
|
||||
),
|
||||
).resolves.toMatchObject({
|
||||
ok: false,
|
||||
error: {
|
||||
_tag: "AnalysisResourceConstraintError",
|
||||
reportedLimits: { active_or_queued_commands: 16 },
|
||||
},
|
||||
});
|
||||
} finally {
|
||||
clearTimeout(cancellationSafetyRelease);
|
||||
}
|
||||
await writeFile(releasePath, "release");
|
||||
expect((await active).ok).toBe(true);
|
||||
const admittedAfterDrain = await manager.execute(
|
||||
started.value.session_id,
|
||||
"admitted-after-drain",
|
||||
);
|
||||
expect(admittedAfterDrain.ok).toBe(true);
|
||||
await expect(
|
||||
manager.execute(started.value.session_id, "after-drain"),
|
||||
).resolves.toMatchObject({
|
||||
ok: true,
|
||||
value: { result: { completion_status: "complete" } },
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,109 @@
|
||||
import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { GdbSessionManager } from "../../../src/gdb/GdbSessionManager.js";
|
||||
|
||||
describe("persistent debugger session managers", () => {
|
||||
let directory: string | undefined;
|
||||
const managers: Array<{ closeAll(): Promise<void> }> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
managers
|
||||
.splice(0)
|
||||
.map((manager) => manager.closeAll().catch(() => undefined)),
|
||||
);
|
||||
if (directory !== undefined)
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
directory = undefined;
|
||||
});
|
||||
|
||||
it("runs a correlated GDB MI command, reports status, and closes its owned process", async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "rea-gdb-manager-"));
|
||||
const provider = join(directory, "fake-gdb.mjs");
|
||||
await writeFile(
|
||||
provider,
|
||||
`#!${process.execPath}
|
||||
process.stdout.write("(gdb)\\n");
|
||||
let input = "";
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", (chunk) => {
|
||||
input += chunk;
|
||||
for (;;) {
|
||||
const boundary = input.indexOf("\\n");
|
||||
if (boundary < 0) break;
|
||||
const line = input.slice(0, boundary);
|
||||
input = input.slice(boundary + 1);
|
||||
const match = /^(\\d+)/.exec(line);
|
||||
if (match && line.includes("list-thread-groups"))
|
||||
process.stdout.write(match[1] + "^done,groups=[]\\n");
|
||||
else if (match) process.stdout.write(match[1] + "^done\\n");
|
||||
}
|
||||
});
|
||||
`,
|
||||
);
|
||||
await chmod(provider, 0o700);
|
||||
const manager = new GdbSessionManager({
|
||||
platform: "linux",
|
||||
environment: { REA_GDB_COMMAND: provider },
|
||||
});
|
||||
managers.push(manager);
|
||||
|
||||
const started = await manager.start();
|
||||
expect(started.ok).toBe(true);
|
||||
if (!started.ok) return;
|
||||
expect(manager.status(started.value.session_id)?.state).toBe("ready");
|
||||
|
||||
const result = await manager.execute(
|
||||
started.value.session_id,
|
||||
"show version",
|
||||
);
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) expect(result.value.result.mi).toMatch(/^\d+\^done/u);
|
||||
|
||||
const closed = await manager.close(started.value.session_id);
|
||||
expect(closed.ok).toBe(true);
|
||||
expect(manager.status(started.value.session_id)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("does not start GDB when it rejects the required auto-load setting", async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "rea-gdb-autoload-"));
|
||||
const provider = join(directory, "fake-gdb-reject.mjs");
|
||||
await writeFile(
|
||||
provider,
|
||||
`#!${process.execPath}
|
||||
process.stdout.write("(gdb)\\n");
|
||||
let input = "";
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", (chunk) => {
|
||||
input += chunk;
|
||||
for (;;) {
|
||||
const boundary = input.indexOf("\\n");
|
||||
if (boundary < 0) break;
|
||||
const line = input.slice(0, boundary);
|
||||
input = input.slice(boundary + 1);
|
||||
const match = /^(\\d+)(.*)/.exec(line);
|
||||
if (match) process.stdout.write(match[1] + (match[2].includes("-gdb-set auto-load off") ? "^error,msg=\\"rejected\\"\\n" : "^done\\n"));
|
||||
}
|
||||
});
|
||||
`,
|
||||
);
|
||||
await chmod(provider, 0o700);
|
||||
const manager = new GdbSessionManager({
|
||||
platform: "linux",
|
||||
environment: { REA_GDB_COMMAND: provider },
|
||||
});
|
||||
managers.push(manager);
|
||||
|
||||
const started = await manager.start();
|
||||
|
||||
expect(started.ok).toBe(false);
|
||||
if (!started.ok)
|
||||
expect(JSON.stringify(started.error)).toContain(
|
||||
"automatic-loading disable command",
|
||||
);
|
||||
});
|
||||
});
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,28 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import {
|
||||
createRizinCommandTimeoutError,
|
||||
isRizinCommandDeadlineExpired,
|
||||
RizinCommandTimeoutError,
|
||||
} from "../../../src/rizin/RizinDebugSessionManager.js";
|
||||
|
||||
describe("Rizin command timeout semantics", () => {
|
||||
it("treats zero and negative remaining time as expired", () => {
|
||||
expect(isRizinCommandDeadlineExpired(1)).toBe(false);
|
||||
expect(isRizinCommandDeadlineExpired(0)).toBe(true);
|
||||
expect(isRizinCommandDeadlineExpired(-1)).toBe(true);
|
||||
});
|
||||
|
||||
it("retains partial frames separated by newlines in the timeout error", () => {
|
||||
const error = createRizinCommandTimeoutError([
|
||||
"first frame",
|
||||
"second frame",
|
||||
]);
|
||||
|
||||
expect(error).toBeInstanceOf(RizinCommandTimeoutError);
|
||||
expect(error.partialOutput).toBe("first frame\nsecond frame");
|
||||
expect(error.message).toBe(
|
||||
"Timed out waiting for Rizin's command-completion marker",
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,245 @@
|
||||
import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { EventEmitter } from "node:events";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { PassThrough, Writable } from "node:stream";
|
||||
|
||||
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
|
||||
import {
|
||||
createRizinTestManager,
|
||||
rizinTestInferiorTty,
|
||||
} from "./RizinTestInferiorTty.js";
|
||||
import { stopOwnedDebuggerProcess } from "../../../src/process/ownedDebuggerSession.js";
|
||||
import type {
|
||||
ProviderProcessHandle,
|
||||
SpawnedOwnedProviderProcess,
|
||||
} from "../../../src/process/ProviderProcess.js";
|
||||
|
||||
interface InjectedProcessControl {
|
||||
output(chunk: Buffer | string): void;
|
||||
stdinError(): void;
|
||||
closeStdin(): void;
|
||||
exitLeader(signal?: NodeJS.Signals): void;
|
||||
closeOutput(): void;
|
||||
exit(signal?: NodeJS.Signals): void;
|
||||
}
|
||||
|
||||
type InjectedSpawnProcess = NonNullable<
|
||||
NonNullable<
|
||||
ConstructorParameters<typeof RizinDebugSessionManager>[1]
|
||||
>["spawnProcess"]
|
||||
>;
|
||||
|
||||
export const incompleteStop: typeof stopOwnedDebuggerProcess = async (
|
||||
session,
|
||||
name,
|
||||
) => {
|
||||
await stopOwnedDebuggerProcess(session, name);
|
||||
return { status: "incomplete", reason: "injected stop uncertainty" };
|
||||
};
|
||||
|
||||
export const abortOnCheck = (targetCheck: number): AbortSignal => {
|
||||
let checks = 0;
|
||||
let aborted = false;
|
||||
type Listener = Parameters<AbortSignal["addEventListener"]>[1];
|
||||
const listeners = new Set<Listener>();
|
||||
return {
|
||||
get aborted() {
|
||||
checks += 1;
|
||||
if (checks >= targetCheck) aborted = true;
|
||||
return aborted;
|
||||
},
|
||||
addEventListener: (
|
||||
_type: Parameters<AbortSignal["addEventListener"]>[0],
|
||||
listener: Listener,
|
||||
) => {
|
||||
if (listener !== null) listeners.add(listener);
|
||||
},
|
||||
removeEventListener: (
|
||||
_type: Parameters<AbortSignal["removeEventListener"]>[0],
|
||||
listener: Parameters<AbortSignal["removeEventListener"]>[1],
|
||||
) => {
|
||||
if (listener !== null) listeners.delete(listener);
|
||||
},
|
||||
dispatchEvent: () => true,
|
||||
onabort: null,
|
||||
reason: undefined,
|
||||
throwIfAborted: () => undefined,
|
||||
} as AbortSignal;
|
||||
};
|
||||
|
||||
export const createInjectedProcess = (
|
||||
options: {
|
||||
readonly stdin?:
|
||||
| "normal"
|
||||
| "null"
|
||||
| "destroyed"
|
||||
| "throws"
|
||||
| "throws-opaque"
|
||||
| "write-error";
|
||||
readonly onWrite?: (text: string, control: InjectedProcessControl) => void;
|
||||
readonly startup?: (control: InjectedProcessControl) => void;
|
||||
readonly beforeSpawnReturns?: () => void;
|
||||
readonly spawnError?: unknown;
|
||||
} = {},
|
||||
): {
|
||||
readonly spawnProcess: InjectedSpawnProcess;
|
||||
readonly control: InjectedProcessControl;
|
||||
} => {
|
||||
const stdout = new PassThrough();
|
||||
const stderr = new PassThrough();
|
||||
let exitCode: number | null = null;
|
||||
let signalCode: NodeJS.Signals | null = null;
|
||||
const processHandle = new EventEmitter() as EventEmitter & {
|
||||
pid: number;
|
||||
stdout: PassThrough;
|
||||
stdin: Writable | null;
|
||||
stderr: PassThrough;
|
||||
exitCode: number | null;
|
||||
signalCode: NodeJS.Signals | null;
|
||||
kill(signal?: NodeJS.Signals | number): boolean;
|
||||
};
|
||||
processHandle.pid = process.pid;
|
||||
processHandle.stdout = stdout;
|
||||
processHandle.stderr = stderr;
|
||||
processHandle.exitCode = exitCode;
|
||||
processHandle.signalCode = signalCode;
|
||||
|
||||
const control: InjectedProcessControl = {
|
||||
output: (chunk) => stdout.emit("data", Buffer.from(chunk)),
|
||||
stdinError: () => stdin?.emit("error", new Error("injected stdin error")),
|
||||
closeStdin: () => stdin?.destroy(),
|
||||
exitLeader: (signal = "SIGTERM") => {
|
||||
exitCode = null;
|
||||
signalCode = signal;
|
||||
processHandle.exitCode = exitCode;
|
||||
processHandle.signalCode = signalCode;
|
||||
processHandle.emit("exit", exitCode, signalCode);
|
||||
},
|
||||
closeOutput: () => {
|
||||
stdout.destroy();
|
||||
stderr.destroy();
|
||||
processHandle.emit("close", exitCode, signalCode);
|
||||
},
|
||||
exit: (signal = "SIGTERM") => {
|
||||
control.exitLeader(signal);
|
||||
control.closeOutput();
|
||||
},
|
||||
};
|
||||
const stdin =
|
||||
options.stdin === "null"
|
||||
? null
|
||||
: new Writable({
|
||||
write(chunk, _encoding, callback) {
|
||||
options.onWrite?.(Buffer.from(chunk).toString("utf8"), control);
|
||||
callback(
|
||||
options.stdin === "write-error"
|
||||
? new Error("injected write callback failure")
|
||||
: undefined,
|
||||
);
|
||||
},
|
||||
});
|
||||
if (stdin !== null) {
|
||||
if (options.stdin === "destroyed")
|
||||
Object.defineProperty(stdin, "destroyed", { value: true });
|
||||
if (options.stdin === "throws" || options.stdin === "throws-opaque")
|
||||
stdin.write = (() => {
|
||||
if (options.stdin === "throws-opaque")
|
||||
throw "injected opaque write failure";
|
||||
throw new Error("injected synchronous write failure");
|
||||
}) as typeof stdin.write;
|
||||
processHandle.stdin = stdin;
|
||||
} else processHandle.stdin = null;
|
||||
processHandle.kill = (signal = "SIGTERM") => {
|
||||
if (exitCode !== null || signalCode !== null) return false;
|
||||
control.exit(typeof signal === "string" ? signal : "SIGTERM");
|
||||
return true;
|
||||
};
|
||||
|
||||
const spawnProcess: InjectedSpawnProcess = async (spawnOptions) => {
|
||||
options.beforeSpawnReturns?.();
|
||||
if (options.spawnError !== undefined) throw options.spawnError;
|
||||
setImmediate(() => {
|
||||
if (options.startup !== undefined) options.startup(control);
|
||||
else control.output(Buffer.from([0]));
|
||||
});
|
||||
return {
|
||||
process: processHandle as unknown as ProviderProcessHandle,
|
||||
ownership: {
|
||||
runId: spawnOptions.runId,
|
||||
leaderPid: process.pid,
|
||||
processGroupId: process.pid,
|
||||
expectedParentPid: process.pid,
|
||||
},
|
||||
} satisfies SpawnedOwnedProviderProcess;
|
||||
};
|
||||
return { spawnProcess, control };
|
||||
};
|
||||
|
||||
export const createRizinCoverageHarness = () => {
|
||||
let directory: string | undefined;
|
||||
const managers: RizinDebugSessionManager[] = [];
|
||||
const track = (manager: RizinDebugSessionManager): void => {
|
||||
managers.push(manager);
|
||||
};
|
||||
const makeProvider = async (
|
||||
body: string,
|
||||
shebang = "#!/usr/bin/env node",
|
||||
): Promise<string> => {
|
||||
directory = await mkdtemp(join(tmpdir(), "rea-rizin-coverage-"));
|
||||
const provider = join(directory, "fake-rizin.mjs");
|
||||
await writeFile(provider, `${shebang}\n${body}\n`);
|
||||
await chmod(provider, 0o700);
|
||||
return provider;
|
||||
};
|
||||
const start = async (
|
||||
provider: string,
|
||||
options: ConstructorParameters<typeof RizinDebugSessionManager>[1] = {},
|
||||
): Promise<{ manager: RizinDebugSessionManager; sessionId: string }> => {
|
||||
const manager = createRizinTestManager(
|
||||
{ REA_RIZIN_COMMAND: provider },
|
||||
options,
|
||||
);
|
||||
track(manager);
|
||||
const result = await manager.start({
|
||||
path: "/tmp/coverage-target",
|
||||
inferior_tty: await rizinTestInferiorTty(),
|
||||
});
|
||||
if (!result.ok) throw result.error;
|
||||
return { manager, sessionId: result.value.session_id };
|
||||
};
|
||||
const startInjected = async (
|
||||
spawnProcess: InjectedSpawnProcess,
|
||||
options: ConstructorParameters<typeof RizinDebugSessionManager>[1] = {},
|
||||
) => {
|
||||
const manager = createRizinTestManager(
|
||||
{ REA_RIZIN_COMMAND: "injected-rizin" },
|
||||
{ ...options, spawnProcess },
|
||||
);
|
||||
track(manager);
|
||||
const started = await manager.start({
|
||||
path: "/tmp/injected",
|
||||
inferior_tty: await rizinTestInferiorTty(),
|
||||
});
|
||||
return { manager, started };
|
||||
};
|
||||
const cleanup = async (): Promise<void> => {
|
||||
await Promise.all(
|
||||
managers
|
||||
.splice(0)
|
||||
.map((manager) => manager.closeAll().catch(() => undefined)),
|
||||
);
|
||||
if (directory !== undefined)
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
directory = undefined;
|
||||
};
|
||||
const missingProviderPath = (): string => join(directory!, "does-not-exist");
|
||||
return {
|
||||
cleanup,
|
||||
makeProvider,
|
||||
missingProviderPath,
|
||||
start,
|
||||
startInjected,
|
||||
track,
|
||||
};
|
||||
};
|
||||
@@ -0,0 +1,422 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
|
||||
import {
|
||||
createRizinTestManager,
|
||||
stopFakeNoInferior,
|
||||
rizinTestInferiorTty,
|
||||
} from "./RizinTestInferiorTty.js";
|
||||
import { rizinCommand } from "../../../src/rizin/RizinCommand.js";
|
||||
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
|
||||
import {
|
||||
createRizinCoverageHarness,
|
||||
createInjectedProcess,
|
||||
abortOnCheck,
|
||||
incompleteStop,
|
||||
} from "./RizinDebugSessionCoverage.fixtures.js";
|
||||
|
||||
const {
|
||||
cleanup,
|
||||
makeProvider,
|
||||
missingProviderPath,
|
||||
start,
|
||||
startInjected,
|
||||
track,
|
||||
} = createRizinCoverageHarness();
|
||||
afterEach(cleanup);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"builds the one-shot command with the caller's path and command",
|
||||
() => {
|
||||
expect(rizinCommand({ path: "./sample file", command: "izz" })).toEqual([
|
||||
"-N",
|
||||
"-q",
|
||||
"-c",
|
||||
"izz",
|
||||
expect.stringMatching(/sample file/u),
|
||||
]);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"rejects unsupported, pre-cancelled, and failed startup requests",
|
||||
async () => {
|
||||
const windows = createRizinTestManager({}, { platform: "win32" });
|
||||
expect(
|
||||
(
|
||||
await windows.start({
|
||||
path: "/tmp/a",
|
||||
inferior_tty: "unused-before-platform-admission",
|
||||
})
|
||||
).ok,
|
||||
).toBe(false);
|
||||
const aborted = new AbortController();
|
||||
aborted.abort();
|
||||
expect(
|
||||
(
|
||||
await windows.start(
|
||||
{ path: "/tmp/a", inferior_tty: await rizinTestInferiorTty() },
|
||||
aborted.signal,
|
||||
)
|
||||
).ok,
|
||||
).toBe(false);
|
||||
|
||||
const failed = await makeProvider("process.exit(9);");
|
||||
const manager = createRizinTestManager({
|
||||
REA_RIZIN_COMMAND: failed,
|
||||
});
|
||||
track(manager);
|
||||
const result = await manager.start({
|
||||
path: "/tmp/a",
|
||||
inferior_tty: await rizinTestInferiorTty(),
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
|
||||
const missing = createRizinTestManager({
|
||||
REA_RIZIN_COMMAND: missingProviderPath(),
|
||||
});
|
||||
track(missing);
|
||||
const spawnFailure = await missing.start({
|
||||
path: "/tmp/a",
|
||||
inferior_tty: await rizinTestInferiorTty(),
|
||||
});
|
||||
expect(spawnFailure.ok).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"returns a startup timeout when Rizin exits before its initial frame",
|
||||
async () => {
|
||||
const provider = await makeProvider("process.exit(0);");
|
||||
const manager = createRizinTestManager({
|
||||
REA_RIZIN_COMMAND: provider,
|
||||
});
|
||||
track(manager);
|
||||
const result = await manager.start({
|
||||
path: "/tmp/early-exit",
|
||||
inferior_tty: await rizinTestInferiorTty(),
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"times out startup through the frame wait when Rizin never emits a frame",
|
||||
async () => {
|
||||
let resolveSpawned!: () => void;
|
||||
const spawned = new Promise<void>((resolve) => {
|
||||
resolveSpawned = resolve;
|
||||
});
|
||||
const injected = createInjectedProcess({
|
||||
startup: () => undefined,
|
||||
beforeSpawnReturns: resolveSpawned,
|
||||
});
|
||||
const manager = createRizinTestManager(
|
||||
{ REA_RIZIN_COMMAND: "injected-rizin" },
|
||||
{
|
||||
spawnProcess: injected.spawnProcess,
|
||||
stopProcess: async () => ({ status: "stopped" }),
|
||||
},
|
||||
);
|
||||
track(manager);
|
||||
vi.useFakeTimers({ toFake: ["setTimeout", "clearTimeout"] });
|
||||
try {
|
||||
const starting = manager.start({
|
||||
path: "/tmp/no-startup-frame",
|
||||
inferior_tty: await rizinTestInferiorTty(),
|
||||
});
|
||||
await spawned;
|
||||
await vi.advanceTimersByTimeAsync(30_001);
|
||||
const result = await starting;
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error.message).toContain("timed out");
|
||||
} finally {
|
||||
vi.useRealTimers();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"does not spawn Rizin when cancellation arrives during TTY validation",
|
||||
async () => {
|
||||
let spawned = false;
|
||||
const manager = createRizinTestManager(
|
||||
{ REA_RIZIN_COMMAND: "injected-rizin" },
|
||||
{
|
||||
spawnProcess: async () => {
|
||||
spawned = true;
|
||||
throw new Error("must not spawn after cancellation");
|
||||
},
|
||||
},
|
||||
);
|
||||
const result = await manager.start(
|
||||
{
|
||||
path: "/tmp/cancel-before-spawn",
|
||||
inferior_tty: await rizinTestInferiorTty(),
|
||||
},
|
||||
abortOnCheck(2),
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
expect(spawned).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"rejects a non-TTY path before spawning Rizin",
|
||||
async () => {
|
||||
let spawned = false;
|
||||
const manager = createRizinTestManager(
|
||||
{ REA_RIZIN_COMMAND: "injected-rizin" },
|
||||
{
|
||||
spawnProcess: async () => {
|
||||
spawned = true;
|
||||
throw new Error("must not spawn with an invalid TTY");
|
||||
},
|
||||
},
|
||||
);
|
||||
const result = await manager.start({
|
||||
path: "/tmp/not-a-tty-target",
|
||||
inferior_tty: "/dev/null",
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
expect(spawned).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"closeAll drains concurrent startups and blocks later admission",
|
||||
async () => {
|
||||
let spawnCount = 0;
|
||||
let resolveSpawnCalls!: () => void;
|
||||
const bothSpawnsCalled = new Promise<void>((resolve) => {
|
||||
resolveSpawnCalls = resolve;
|
||||
});
|
||||
let releaseSpawns!: () => void;
|
||||
const spawnGate = new Promise<void>((resolve) => {
|
||||
releaseSpawns = resolve;
|
||||
});
|
||||
const injected = createInjectedProcess();
|
||||
const manager = createRizinTestManager(
|
||||
{ REA_RIZIN_COMMAND: "injected-rizin" },
|
||||
{
|
||||
spawnProcess: async (options) => {
|
||||
spawnCount += 1;
|
||||
if (spawnCount === 2) resolveSpawnCalls();
|
||||
await spawnGate;
|
||||
return injected.spawnProcess(options);
|
||||
},
|
||||
stopProcess: async () => ({ status: "stopped" }),
|
||||
},
|
||||
);
|
||||
const tty = await rizinTestInferiorTty();
|
||||
const starts = [
|
||||
manager.start({ path: "/tmp/start-one", inferior_tty: tty }),
|
||||
manager.start({ path: "/tmp/start-two", inferior_tty: tty }),
|
||||
];
|
||||
await bothSpawnsCalled;
|
||||
let closeAllResolved = false;
|
||||
const closing = manager.closeAll().then(() => {
|
||||
closeAllResolved = true;
|
||||
});
|
||||
await Promise.resolve();
|
||||
expect(closeAllResolved).toBe(false);
|
||||
releaseSpawns();
|
||||
const started = await Promise.all(starts);
|
||||
expect(started.every((result) => result.ok)).toBe(true);
|
||||
await closing;
|
||||
expect(
|
||||
manager.status(started[0]!.ok ? started[0]!.value.session_id : "missing"),
|
||||
).toBeUndefined();
|
||||
expect(
|
||||
(await manager.start({ path: "/tmp/after-close-all", inferior_tty: tty }))
|
||||
.ok,
|
||||
).toBe(false);
|
||||
expect((await manager.close("missing")).ok).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"rejects an oversized initial frame instead of marking the session ready",
|
||||
async () => {
|
||||
const provider = await makeProvider(
|
||||
'process.stdout.write("x".repeat(16 * 1024 * 1024 + 1) + "\\0"); process.stdin.resume();',
|
||||
);
|
||||
const manager = createRizinTestManager({
|
||||
REA_RIZIN_COMMAND: provider,
|
||||
});
|
||||
track(manager);
|
||||
|
||||
const result = await manager.start({
|
||||
path: "/tmp/oversized-startup",
|
||||
inferior_tty: await rizinTestInferiorTty(),
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"cancels startup while waiting for the initial NUL frame",
|
||||
async () => {
|
||||
let resolveSpawned!: () => void;
|
||||
const spawned = new Promise<void>((resolve) => {
|
||||
resolveSpawned = resolve;
|
||||
});
|
||||
const provider = await makeProvider(
|
||||
'setTimeout(() => process.stdout.write("\\0"), 500); process.stdin.resume();',
|
||||
);
|
||||
const manager = createRizinTestManager(
|
||||
{
|
||||
REA_RIZIN_COMMAND: provider,
|
||||
},
|
||||
{
|
||||
spawnProcess: async (options) => {
|
||||
const launched = await spawnOwnedProviderProcess(options);
|
||||
resolveSpawned();
|
||||
return launched;
|
||||
},
|
||||
},
|
||||
);
|
||||
track(manager);
|
||||
const abort = new AbortController();
|
||||
const starting = manager.start(
|
||||
{ path: "/tmp/cancel-start", inferior_tty: await rizinTestInferiorTty() },
|
||||
abort.signal,
|
||||
);
|
||||
await spawned;
|
||||
abort.abort();
|
||||
expect((await starting).ok).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"preserves startup cleanup uncertainty after cancellation",
|
||||
async () => {
|
||||
let resolveSpawned!: () => void;
|
||||
const spawned = new Promise<void>((resolve) => {
|
||||
resolveSpawned = resolve;
|
||||
});
|
||||
const provider = await makeProvider(
|
||||
"process.stdin.resume(); setInterval(() => {}, 1000);",
|
||||
);
|
||||
const manager = createRizinTestManager(
|
||||
{ REA_RIZIN_COMMAND: provider },
|
||||
{
|
||||
stopProcess: incompleteStop,
|
||||
spawnProcess: async (options) => {
|
||||
const launched = await spawnOwnedProviderProcess(options);
|
||||
resolveSpawned();
|
||||
return launched;
|
||||
},
|
||||
},
|
||||
);
|
||||
track(manager);
|
||||
const abort = new AbortController();
|
||||
const starting = manager.start(
|
||||
{ path: "/tmp/cancel-start", inferior_tty: await rizinTestInferiorTty() },
|
||||
abort.signal,
|
||||
);
|
||||
await spawned;
|
||||
abort.abort();
|
||||
const result = await starting;
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok)
|
||||
expect(result.error.message).toContain("injected stop uncertainty");
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"rejects commands for missing and pre-cancelled sessions",
|
||||
async () => {
|
||||
const provider = await makeProvider(
|
||||
'process.stdout.write("\\0"); process.stdin.resume();',
|
||||
);
|
||||
const { manager, sessionId } = await start(provider);
|
||||
expect((await manager.execute("missing", "dr")).ok).toBe(false);
|
||||
const aborted = new AbortController();
|
||||
aborted.abort();
|
||||
expect((await manager.execute(sessionId, "dr", aborted.signal)).ok).toBe(
|
||||
false,
|
||||
);
|
||||
expect(manager.status(sessionId)?.state).toBe("ready");
|
||||
expect((await manager.close("missing")).ok).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"retains close failures and resolves their owner after cleanup retry",
|
||||
async () => {
|
||||
const provider = await makeProvider(
|
||||
'process.stdout.write("\\0"); process.stdin.resume();',
|
||||
);
|
||||
let stopCalls = 0;
|
||||
const { manager, sessionId } = await start(provider, {
|
||||
stopProcess: async (session, name, options) => {
|
||||
stopCalls += 1;
|
||||
if (stopCalls === 1) {
|
||||
session.launched.process.kill("SIGTERM");
|
||||
return {
|
||||
status: "incomplete",
|
||||
reason: "first stop result is uncertain",
|
||||
};
|
||||
}
|
||||
await session.supervisor.waitForExit(1000);
|
||||
return stopFakeNoInferior(session, name, options);
|
||||
},
|
||||
});
|
||||
const closed = await manager.close(sessionId);
|
||||
expect(closed.ok).toBe(false);
|
||||
if (!closed.ok) {
|
||||
expect(closed.error.cleanupIncomplete).toBe(true);
|
||||
expect(closed.error.cleanup?.resources).toEqual([sessionId]);
|
||||
const retainedFailure = closed.error;
|
||||
expect(await manager.retryCleanupFailures()).toEqual({
|
||||
ok: true,
|
||||
value: null,
|
||||
});
|
||||
expect(retainedFailure.cleanupIncomplete).toBe(false);
|
||||
}
|
||||
expect(stopCalls).toBe(2);
|
||||
expect(manager.status(sessionId)).toBeUndefined();
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"retains a Rizin close owner until inherited output writers close",
|
||||
async () => {
|
||||
const injected = createInjectedProcess();
|
||||
const { manager, started } = await startInjected(injected.spawnProcess);
|
||||
expect(started.ok).toBe(true);
|
||||
if (!started.ok) return;
|
||||
const sessionId = started.value.session_id;
|
||||
injected.control.exitLeader();
|
||||
|
||||
const firstClose = await manager.close(sessionId);
|
||||
expect(firstClose.ok).toBe(false);
|
||||
if (!firstClose.ok) {
|
||||
expect(firstClose.error.cleanupIncomplete).toBe(true);
|
||||
expect(firstClose.error.message).toMatch(/inherited output streams/i);
|
||||
}
|
||||
expect(manager.status(sessionId)).toBeDefined();
|
||||
|
||||
injected.control.closeOutput();
|
||||
const retried = await manager.retryCleanupFailures();
|
||||
|
||||
expect(retried).toEqual({ ok: true, value: null });
|
||||
expect(manager.status(sessionId)).toBeUndefined();
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"closes a session after unsolicited frames make command correlation unsafe",
|
||||
async () => {
|
||||
const provider = await makeProvider(
|
||||
'process.stdout.write("\\0"); setTimeout(() => process.stdout.write("unexpected\\0"), 20); process.stdin.resume();',
|
||||
);
|
||||
const { manager, sessionId } = await start(provider);
|
||||
await new Promise((resolve) => setTimeout(resolve, 50));
|
||||
const result = await manager.execute(sessionId, "dr");
|
||||
expect(result.ok).toBe(false);
|
||||
expect(manager.status(sessionId)?.state).toBe("closed");
|
||||
expect((await manager.close(sessionId)).ok).toBe(true);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,210 @@
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
|
||||
import {
|
||||
createRizinTestManager,
|
||||
rizinTestInferiorTty,
|
||||
} from "./RizinTestInferiorTty.js";
|
||||
import {
|
||||
createRizinCoverageHarness,
|
||||
abortOnCheck,
|
||||
createInjectedProcess,
|
||||
incompleteStop,
|
||||
} from "./RizinDebugSessionCoverage.fixtures.js";
|
||||
|
||||
const { cleanup, makeProvider, start, startInjected, track } =
|
||||
createRizinCoverageHarness();
|
||||
afterEach(cleanup);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"stops the session when the provider closes its stdin pipe",
|
||||
async () => {
|
||||
const provider = await makeProvider(
|
||||
'printf "\\000"; exec 0<&-; while :; do :; done',
|
||||
"#!/bin/sh",
|
||||
);
|
||||
const { manager, sessionId } = await start(provider, {
|
||||
frameTimeoutMs: 500,
|
||||
});
|
||||
const result = await manager.execute(sessionId, "dr");
|
||||
expect(result.ok).toBe(false);
|
||||
expect(manager.status(sessionId)?.state).toBe("closed");
|
||||
},
|
||||
);
|
||||
|
||||
it
|
||||
.skipIf(process.platform === "win32")
|
||||
.each([
|
||||
"null",
|
||||
"destroyed",
|
||||
"throws",
|
||||
"throws-opaque",
|
||||
"write-error",
|
||||
] as const)(
|
||||
"fails safely when injected Rizin stdin is %s",
|
||||
async (stdinMode) => {
|
||||
const injected = createInjectedProcess({ stdin: stdinMode });
|
||||
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(false);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"fails an active command when the injected stdin stream closes",
|
||||
async () => {
|
||||
const injected = createInjectedProcess();
|
||||
const { manager, started } = await startInjected(injected.spawnProcess);
|
||||
expect(started.ok).toBe(true);
|
||||
if (!started.ok) return;
|
||||
injected.control.closeStdin();
|
||||
const result = await manager.execute(started.value.session_id, "dr");
|
||||
expect(result.ok).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32").each([false, true])(
|
||||
"uses protocol cleanup when an injected write callback fails (incomplete=%s)",
|
||||
async (incomplete) => {
|
||||
const injected = createInjectedProcess({ stdin: "write-error" });
|
||||
const { manager, started } = await startInjected(injected.spawnProcess, {
|
||||
stopProcess: incomplete
|
||||
? incompleteStop
|
||||
: async () => ({ status: "stopped" }),
|
||||
});
|
||||
expect(started.ok).toBe(true);
|
||||
if (!started.ok) return;
|
||||
const result = await manager.execute(started.value.session_id, "dr");
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok && incomplete)
|
||||
expect(result.error.message).toContain("injected stop uncertainty");
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"maps injected spawn errors and startup protocol failure",
|
||||
async () => {
|
||||
for (const spawnError of [new Error("injected spawn failure"), "opaque"]) {
|
||||
const injected = createInjectedProcess({ spawnError });
|
||||
const manager = createRizinTestManager(
|
||||
{ REA_RIZIN_COMMAND: "injected-rizin" },
|
||||
{ spawnProcess: injected.spawnProcess },
|
||||
);
|
||||
const result = await manager.start({
|
||||
path: "/tmp/injected",
|
||||
inferior_tty: await rizinTestInferiorTty(),
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
}
|
||||
|
||||
const injected = createInjectedProcess({
|
||||
startup: (control) => control.closeStdin(),
|
||||
});
|
||||
const manager = createRizinTestManager(
|
||||
{ REA_RIZIN_COMMAND: "injected-rizin" },
|
||||
{ spawnProcess: injected.spawnProcess },
|
||||
);
|
||||
const result = await manager.start({
|
||||
path: "/tmp/injected",
|
||||
inferior_tty: await rizinTestInferiorTty(),
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok)
|
||||
expect(result.error.message).toContain("stdin stream closed");
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"maps spawn rejection as cancellation when the signal changes during spawn",
|
||||
async () => {
|
||||
const abort = new AbortController();
|
||||
const injected = createInjectedProcess({
|
||||
beforeSpawnReturns: () => abort.abort(),
|
||||
spawnError: new Error("spawn interrupted"),
|
||||
});
|
||||
const manager = createRizinTestManager(
|
||||
{ REA_RIZIN_COMMAND: "injected-rizin" },
|
||||
{ spawnProcess: injected.spawnProcess },
|
||||
);
|
||||
const result = await manager.start(
|
||||
{ path: "/tmp/injected", inferior_tty: await rizinTestInferiorTty() },
|
||||
abort.signal,
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) expect(result.error.message).toContain("cancelled");
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"cancels startup after receiving its initial frame",
|
||||
async () => {
|
||||
const abort = new AbortController();
|
||||
const injected = createInjectedProcess({
|
||||
startup: (control) => {
|
||||
control.output(Buffer.from([0]));
|
||||
abort.abort();
|
||||
},
|
||||
});
|
||||
const manager = createRizinTestManager(
|
||||
{ REA_RIZIN_COMMAND: "injected-rizin" },
|
||||
{ spawnProcess: injected.spawnProcess },
|
||||
);
|
||||
const result = await manager.start(
|
||||
{ path: "/tmp/injected", inferior_tty: await rizinTestInferiorTty() },
|
||||
abort.signal,
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"observes startup cancellation before the first frame waiter is installed",
|
||||
async () => {
|
||||
const abort = new AbortController();
|
||||
const injected = createInjectedProcess({
|
||||
beforeSpawnReturns: () => abort.abort(),
|
||||
});
|
||||
const manager = createRizinTestManager(
|
||||
{ REA_RIZIN_COMMAND: "injected-rizin" },
|
||||
{ spawnProcess: injected.spawnProcess },
|
||||
);
|
||||
const result = await manager.start(
|
||||
{ path: "/tmp/injected", inferior_tty: await rizinTestInferiorTty() },
|
||||
abort.signal,
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"cancels a command after its turn is granted",
|
||||
async () => {
|
||||
const injected = createInjectedProcess();
|
||||
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",
|
||||
abortOnCheck(3),
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"cancels while waiting for the previous command turn",
|
||||
async () => {
|
||||
const injected = createInjectedProcess();
|
||||
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",
|
||||
abortOnCheck(2),
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,291 @@
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
import { AnalysisInputError } from "../../../src/domain/analysisErrorCore.js";
|
||||
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
|
||||
import {
|
||||
createRizinTestManager,
|
||||
rizinTestInferiorTty,
|
||||
} from "./RizinTestInferiorTty.js";
|
||||
import {
|
||||
createRizinCoverageHarness,
|
||||
abortOnCheck,
|
||||
createInjectedProcess,
|
||||
} from "./RizinDebugSessionCoverage.fixtures.js";
|
||||
|
||||
const { cleanup, startInjected, track } = 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, {
|
||||
frameTimeoutMs: 10,
|
||||
stopProcess: async () => ({ status: "stopped" }),
|
||||
});
|
||||
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.completion_status).toBe("unknown");
|
||||
expect(result.value.evidence.raw_result).toEqual(result.value.result);
|
||||
expect(result.value.evidence.parameters.launch_provenance).toEqual({
|
||||
caller_selected_path: "/tmp/injected",
|
||||
resolved_path: "/tmp/injected",
|
||||
});
|
||||
expect(result.value.evidence.limitations).toEqual([
|
||||
"The current debugger target identity is not established by the Rizin session identifier.",
|
||||
"The command timed out before its completion marker; retained output is partial and completion is unknown.",
|
||||
"The owned debugger session was stopped because output correlation could no longer be guaranteed.",
|
||||
"The command is unrestricted and may access local files, the shell, network, or mutate the target.",
|
||||
"Launch provenance records the original and resolved startup paths; it does not establish the current target after unrestricted debugger commands.",
|
||||
]);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
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, {
|
||||
frameTimeoutMs: 1000,
|
||||
stopProcess: async () => ({ status: "stopped" }),
|
||||
});
|
||||
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")(
|
||||
"preserves queued partial frames when the command deadline reaches zero",
|
||||
async () => {
|
||||
const injected = createInjectedProcess({
|
||||
onWrite: (_text, control) => {
|
||||
control.output("first frame\0second frame\0third frame\0");
|
||||
},
|
||||
});
|
||||
const { manager, started } = await startInjected(injected.spawnProcess, {
|
||||
frameTimeoutMs: 1000,
|
||||
});
|
||||
expect(started.ok).toBe(true);
|
||||
if (!started.ok) return;
|
||||
|
||||
const clock = vi.spyOn(Date, "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) {
|
||||
expect(result.value.result.output).toBe("first frame\nsecond frame");
|
||||
expect(result.value.result.completion_status).toBe("unknown");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
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, {
|
||||
frameTimeoutMs: 100,
|
||||
stopProcess: async () => ({ status: "stopped" }),
|
||||
});
|
||||
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 () => {
|
||||
let signal: AbortSignal;
|
||||
const injected = createInjectedProcess({
|
||||
onWrite: (text, control) => {
|
||||
const marker = /!echo (.+)\n/u.exec(text)?.[1];
|
||||
if (marker !== undefined) control.output(Buffer.from(`${marker}\0`));
|
||||
},
|
||||
});
|
||||
const { manager, started } = await startInjected(injected.spawnProcess);
|
||||
expect(started.ok).toBe(true);
|
||||
if (!started.ok) return;
|
||||
signal = abortOnCheck(5);
|
||||
const result = await manager.execute(
|
||||
started.value.session_id,
|
||||
"dr",
|
||||
signal,
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
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" }),
|
||||
});
|
||||
expect(started.ok).toBe(true);
|
||||
if (!started.ok) return;
|
||||
const result = await manager.execute(
|
||||
started.value.session_id,
|
||||
"wait",
|
||||
abortOnCheck(5),
|
||||
);
|
||||
expect(result.ok).toBe(false);
|
||||
},
|
||||
);
|
||||
|
||||
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", reason: "injected stop uncertainty" }
|
||||
: { status: "stopped" },
|
||||
frameTimeoutMs: 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.message).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([
|
||||
"The current debugger target identity is not established by the Rizin session identifier.",
|
||||
"Rizin exited before the command-completion marker; retained frame output is partial and command completion is unknown.",
|
||||
"The command is unrestricted and may access local files, the shell, network, or mutate the target.",
|
||||
"Launch provenance records the original and resolved startup paths; it does not establish the current target after unrestricted debugger commands.",
|
||||
]);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
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).toBeInstanceOf(AnalysisInputError);
|
||||
expect(writes.some((text) => text.includes("second\n"))).toBe(false);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,266 @@
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { evidenceSchema } from "../../../src/domain/evidence.js";
|
||||
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
|
||||
import {
|
||||
createRizinTestManager,
|
||||
rizinTestInferiorTty,
|
||||
} from "./RizinTestInferiorTty.js";
|
||||
import {
|
||||
createRizinCoverageHarness,
|
||||
createInjectedProcess,
|
||||
incompleteStop,
|
||||
} from "./RizinDebugSessionCoverage.fixtures.js";
|
||||
|
||||
const { cleanup, makeProvider, start, startInjected, track } =
|
||||
createRizinCoverageHarness();
|
||||
afterEach(cleanup);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"assembles a multi-chunk NUL frame once and preserves its command output",
|
||||
async () => {
|
||||
const chunk = Buffer.alloc(64 * 1024, 0x61);
|
||||
const chunkCount = 32;
|
||||
const outputBytes = chunk.length * chunkCount;
|
||||
const injected = createInjectedProcess({
|
||||
onWrite: (text, control) => {
|
||||
const marker = /!echo (.+)\n/u.exec(text)?.[1];
|
||||
if (marker !== undefined)
|
||||
setImmediate(() => {
|
||||
for (let index = 0; index < chunkCount; index += 1)
|
||||
control.output(chunk);
|
||||
control.output(Buffer.from([0]));
|
||||
control.output(Buffer.from(`${marker}\0`));
|
||||
});
|
||||
},
|
||||
});
|
||||
const { manager, started } = await startInjected(injected.spawnProcess, {
|
||||
frameTimeoutMs: 1000,
|
||||
});
|
||||
expect(started.ok).toBe(true);
|
||||
if (!started.ok) return;
|
||||
|
||||
const result = await manager.execute(started.value.session_id, "chunked");
|
||||
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) {
|
||||
expect(Buffer.byteLength(result.value.result.output)).toBe(outputBytes);
|
||||
expect(result.value.result.output).toBe("a".repeat(outputBytes));
|
||||
expect(result.value.result.completion_status).toBe("complete");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"discards an oversized frame split across deterministic stream chunks",
|
||||
async () => {
|
||||
const injected = createInjectedProcess({
|
||||
onWrite: (text, control) => {
|
||||
const marker = /!echo (.+)\n/u.exec(text)?.[1];
|
||||
if (marker !== undefined)
|
||||
setImmediate(() => {
|
||||
control.output(Buffer.alloc(16 * 1024 * 1024 + 1, 0x61));
|
||||
control.output(Buffer.from("discard tail"));
|
||||
control.output(Buffer.from([0]));
|
||||
control.output(Buffer.from(`${marker}\0`));
|
||||
});
|
||||
},
|
||||
});
|
||||
const { manager, started } = await startInjected(injected.spawnProcess, {
|
||||
frameTimeoutMs: 1000,
|
||||
stopProcess: async () => ({ status: "stopped" }),
|
||||
});
|
||||
expect(started.ok).toBe(true);
|
||||
if (!started.ok) return;
|
||||
const result = await manager.execute(started.value.session_id, "large");
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) expect(result.value.result.output_truncated).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"closes an injected session on an oversized unsolicited frame",
|
||||
async () => {
|
||||
const injected = createInjectedProcess();
|
||||
const { manager, started } = await startInjected(injected.spawnProcess);
|
||||
expect(started.ok).toBe(true);
|
||||
if (!started.ok) return;
|
||||
injected.control.output(Buffer.alloc(16 * 1024 * 1024 + 1, 0x61));
|
||||
expect(manager.status(started.value.session_id)?.state).toBe("closed");
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"preserves unsolicited history and marks oversized recent frames",
|
||||
async () => {
|
||||
const provider = await makeProvider(
|
||||
'process.stdout.write("\\0"); process.stdin.resume(); setTimeout(() => process.stdout.write("x".repeat(17000) + "\\0"), 20);',
|
||||
);
|
||||
const { manager, sessionId } = await start(provider);
|
||||
await new Promise((resolve) => setTimeout(resolve, 100));
|
||||
const status = manager.status(sessionId);
|
||||
expect(status?.recent_output_truncated).toBe(true);
|
||||
expect(status?.recent_output.at(-1)).toContain("[recent frame truncated]");
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"bounds recent history after many unsolicited frames",
|
||||
async () => {
|
||||
const provider = await makeProvider(
|
||||
'process.stdout.write("\\0" + Array.from({ length: 70 }, (_, i) => "frame" + i + "\\0").join("")); process.stdin.resume();',
|
||||
);
|
||||
const { manager, sessionId } = await start(provider);
|
||||
const status = manager.status(sessionId);
|
||||
expect(status?.recent_output).toHaveLength(64);
|
||||
expect(status?.recent_output_truncated).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"returns partial unknown evidence when the process exits mid-command",
|
||||
async () => {
|
||||
const provider = await makeProvider(
|
||||
'process.stdout.write("\\0"); process.stdin.setEncoding("utf8"); process.stdin.on("data", () => { process.stdout.write("partial\\0"); process.exit(0); });',
|
||||
);
|
||||
const { manager, sessionId } = await start(provider);
|
||||
const result = await manager.execute(sessionId, "dr");
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) {
|
||||
expect(result.value.result).toMatchObject({
|
||||
output: "partial",
|
||||
completion_status: "unknown",
|
||||
});
|
||||
expect(result.value.evidence.limitations.join(" ")).toContain(
|
||||
"Rizin exited before",
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"cancels a command after sending it and stops its owned session",
|
||||
async () => {
|
||||
const provider = await makeProvider(
|
||||
'process.stdout.write("\\0"); process.stdin.resume();',
|
||||
);
|
||||
const { manager, sessionId } = await start(provider);
|
||||
const abort = new AbortController();
|
||||
const execution = manager.execute(sessionId, "slow", abort.signal);
|
||||
setTimeout(() => abort.abort(), 30);
|
||||
expect((await execution).ok).toBe(false);
|
||||
expect(manager.status(sessionId)?.state).toBe("closed");
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"preserves partial timeout evidence when cleanup cannot be confirmed",
|
||||
async () => {
|
||||
const provider = await makeProvider(
|
||||
'process.stdout.write("\\0"); process.stdin.setEncoding("utf8"); process.stdin.on("data", (chunk) => { if (chunk.includes("slow")) process.stdout.write("partial\\0"); });',
|
||||
);
|
||||
const { manager, sessionId } = await start(provider, {
|
||||
frameTimeoutMs: 25,
|
||||
stopProcess: incompleteStop,
|
||||
});
|
||||
const result = await manager.execute(sessionId, "slow");
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error.cleanupIncomplete).toBe(true);
|
||||
expect(result.error.cleanupResources).toEqual([sessionId]);
|
||||
const evidence = evidenceSchema.parse(result.error.partialObservation);
|
||||
expect(evidence.normalized_result).toMatchObject({
|
||||
completion_status: "unknown",
|
||||
});
|
||||
expect(evidence.limitations.join(" ")).toContain(
|
||||
"injected stop uncertainty",
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"preserves truncated output when cleanup cannot be confirmed",
|
||||
async () => {
|
||||
const provider = await makeProvider(
|
||||
`process.stdout.write("\\0");
|
||||
let input = "";
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", (chunk) => {
|
||||
input += chunk;
|
||||
for (;;) {
|
||||
const end = input.indexOf("\\n");
|
||||
if (end < 0) break;
|
||||
const line = input.slice(0, end); input = input.slice(end + 1);
|
||||
if (line === "many") process.stdout.write(Array.from({ length: 4100 }, (_, i) => "frame" + i + "\\0").join(""));
|
||||
else if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\0");
|
||||
}
|
||||
});`,
|
||||
);
|
||||
const { manager, sessionId } = await start(provider, {
|
||||
frameTimeoutMs: 1000,
|
||||
stopProcess: incompleteStop,
|
||||
});
|
||||
const result = await manager.execute(sessionId, "many");
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error.cleanupIncomplete).toBe(true);
|
||||
expect(result.error.cleanupResources).toEqual([sessionId]);
|
||||
const evidence = evidenceSchema.parse(result.error.partialObservation);
|
||||
expect(evidence.normalized_result).toMatchObject({
|
||||
completion_status: "unknown",
|
||||
});
|
||||
expect(evidence.limitations.join(" ")).toContain(
|
||||
"injected stop uncertainty",
|
||||
);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"preserves the cleanup uncertainty when cancellation cannot confirm process stop",
|
||||
async () => {
|
||||
const provider = await makeProvider(
|
||||
'process.stdout.write("\\0"); process.stdin.resume();',
|
||||
);
|
||||
const { manager, sessionId } = await start(provider, {
|
||||
stopProcess: incompleteStop,
|
||||
});
|
||||
const abort = new AbortController();
|
||||
const execution = manager.execute(sessionId, "slow", abort.signal);
|
||||
setTimeout(() => abort.abort(), 30);
|
||||
const result = await execution;
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok)
|
||||
expect(result.error.message).toContain("injected stop uncertainty");
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"cancels a queued command without sending it after the prior command completes",
|
||||
async () => {
|
||||
const provider = await makeProvider(
|
||||
`process.stdout.write("\\0");
|
||||
let input = "";
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", (chunk) => {
|
||||
input += chunk;
|
||||
for (;;) {
|
||||
const end = input.indexOf("\\n");
|
||||
if (end < 0) break;
|
||||
const line = input.slice(0, end); input = input.slice(end + 1);
|
||||
if (line === "first") setTimeout(() => {}, 100);
|
||||
else if (line.startsWith("!echo ")) setTimeout(() => process.stdout.write(line.slice(6) + "\\0"), 100);
|
||||
}
|
||||
});`,
|
||||
);
|
||||
const { manager, sessionId } = await start(provider, {
|
||||
frameTimeoutMs: 300,
|
||||
});
|
||||
const first = manager.execute(sessionId, "first");
|
||||
const abort = new AbortController();
|
||||
const queued = manager.execute(sessionId, "second", abort.signal);
|
||||
setTimeout(() => abort.abort(), 20);
|
||||
expect((await queued).ok).toBe(false);
|
||||
expect((await first).ok).toBe(true);
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,198 @@
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
import { createRizinCoverageHarness } from "./RizinDebugSessionCoverage.fixtures.js";
|
||||
|
||||
const { cleanup, makeProvider, start } = createRizinCoverageHarness();
|
||||
afterEach(cleanup);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"keeps command output bounded when many frames arrive for a command",
|
||||
async () => {
|
||||
const provider = await makeProvider(
|
||||
`process.stdout.write("\\0");
|
||||
let input = "";
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", (chunk) => {
|
||||
input += chunk;
|
||||
for (;;) {
|
||||
const end = input.indexOf("\\n");
|
||||
if (end < 0) break;
|
||||
const line = input.slice(0, end); input = input.slice(end + 1);
|
||||
if (line === "many") process.stdout.write(Array.from({ length: 4100 }, (_, i) => "frame" + i + "\\0").join(""));
|
||||
else if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\0");
|
||||
}
|
||||
});`,
|
||||
);
|
||||
const { manager, sessionId } = await start(provider, {
|
||||
frameTimeoutMs: 1000,
|
||||
});
|
||||
const result = await manager.execute(sessionId, "many");
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok)
|
||||
expect(result.value.result).toMatchObject({
|
||||
output_truncated: true,
|
||||
completion_status: "unknown",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"returns partial evidence when the command frame deadline is already expired",
|
||||
async () => {
|
||||
const provider = await makeProvider(
|
||||
'process.stdout.write("\\0"); process.stdin.resume();',
|
||||
);
|
||||
const { manager, sessionId } = await start(provider, {
|
||||
frameTimeoutMs: 0,
|
||||
});
|
||||
const result = await manager.execute(sessionId, "dr");
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok)
|
||||
expect(result.value.result).toMatchObject({
|
||||
output: "",
|
||||
output_truncated: true,
|
||||
completion_status: "unknown",
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"does not exceed the exact command byte cap when marker output follows a full frame",
|
||||
async () => {
|
||||
const provider = await makeProvider(
|
||||
`process.stdout.write("\\0");
|
||||
let input = "";
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", (chunk) => {
|
||||
input += chunk;
|
||||
for (;;) {
|
||||
const end = input.indexOf("\\n");
|
||||
if (end < 0) break;
|
||||
const line = input.slice(0, end); input = input.slice(end + 1);
|
||||
if (line === "full") process.stdout.write(Buffer.alloc(16 * 1024 * 1024, 0x61).toString() + "\\0");
|
||||
else if (line.startsWith("!echo ")) process.stdout.write("x" + line.slice(6) + "\\0");
|
||||
}
|
||||
});`,
|
||||
);
|
||||
const { manager, sessionId } = await start(provider, {
|
||||
frameTimeoutMs: 3000,
|
||||
});
|
||||
const result = await manager.execute(sessionId, "full");
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) {
|
||||
expect(Buffer.byteLength(result.value.result.output, "utf8")).toBe(
|
||||
16 * 1024 * 1024,
|
||||
);
|
||||
expect(result.value.result).toMatchObject({
|
||||
output_truncated: true,
|
||||
completion_status: "unknown",
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"caps aggregate output across multiple valid NUL frames",
|
||||
async () => {
|
||||
const provider = await makeProvider(
|
||||
`process.stdout.write("\\0");
|
||||
let input = "";
|
||||
let aggregatePending = false;
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", (chunk) => {
|
||||
input += chunk;
|
||||
for (;;) {
|
||||
const end = input.indexOf("\\n");
|
||||
if (end < 0) break;
|
||||
const line = input.slice(0, end); input = input.slice(end + 1);
|
||||
if (line === "aggregate") {
|
||||
process.stdout.write("a".repeat(10 * 1024 * 1024) + "\\0");
|
||||
aggregatePending = true;
|
||||
} else if (line.startsWith("!echo ")) {
|
||||
process.stdout.write((aggregatePending ? "b".repeat(7 * 1024 * 1024) : "") + line.slice(6) + "\\0");
|
||||
aggregatePending = false;
|
||||
}
|
||||
}
|
||||
});`,
|
||||
);
|
||||
const { manager, sessionId } = await start(provider, {
|
||||
frameTimeoutMs: 3000,
|
||||
});
|
||||
const result = await manager.execute(sessionId, "aggregate");
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) {
|
||||
expect(Buffer.byteLength(result.value.result.output, "utf8")).toBe(
|
||||
16 * 1024 * 1024,
|
||||
);
|
||||
expect(result.value.result.completion_status).toBe("unknown");
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"truncates an oversized NUL frame without decoding a split UTF-8 character",
|
||||
async () => {
|
||||
const provider = await makeProvider(
|
||||
`process.stdout.write("\\0");
|
||||
let input = "";
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", (chunk) => {
|
||||
input += chunk;
|
||||
for (;;) {
|
||||
const end = input.indexOf("\\n");
|
||||
if (end < 0) break;
|
||||
const line = input.slice(0, end); input = input.slice(end + 1);
|
||||
if (line === "large") {
|
||||
process.stdout.write("prefix\\0");
|
||||
process.stdout.write(Buffer.alloc(16 * 1024 * 1024 + 1, 0xF0));
|
||||
} else if (line.startsWith("!echo ")) process.stdout.write("\\0" + line.slice(6) + "\\0");
|
||||
}
|
||||
});`,
|
||||
);
|
||||
const { manager, sessionId } = await start(provider, {
|
||||
frameTimeoutMs: 2000,
|
||||
});
|
||||
const result = await manager.execute(sessionId, "large");
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) {
|
||||
expect(result.value.result).toMatchObject({
|
||||
output_truncated: true,
|
||||
completion_status: "unknown",
|
||||
});
|
||||
expect(result.value.result.output.startsWith("prefix\n")).toBe(true);
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"truncates an oversized frame when its NUL boundary arrives with the crossing chunk",
|
||||
async () => {
|
||||
const provider = await makeProvider(
|
||||
`process.stdout.write("\\0");
|
||||
let input = "";
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", (chunk) => {
|
||||
input += chunk;
|
||||
for (;;) {
|
||||
const end = input.indexOf("\\n");
|
||||
if (end < 0) break;
|
||||
const line = input.slice(0, end); input = input.slice(end + 1);
|
||||
if (line === "large") {
|
||||
const frame = Buffer.alloc(16 * 1024 * 1024 + 2, 0x61);
|
||||
frame[frame.length - 1] = 0;
|
||||
process.stdout.write(frame);
|
||||
} else if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\0");
|
||||
}
|
||||
});`,
|
||||
);
|
||||
const { manager, sessionId } = await start(provider, {
|
||||
frameTimeoutMs: 2000,
|
||||
});
|
||||
const result = await manager.execute(sessionId, "large");
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok)
|
||||
expect(result.value.result).toMatchObject({
|
||||
output_truncated: true,
|
||||
completion_status: "unknown",
|
||||
});
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,196 @@
|
||||
import { chmod, mkdtemp, rm, writeFile } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
|
||||
import { afterEach, describe, expect, it } from "vitest";
|
||||
|
||||
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
|
||||
import {
|
||||
createRizinTestManager,
|
||||
rizinTestInferiorTty,
|
||||
} from "./RizinTestInferiorTty.js";
|
||||
|
||||
describe.skipIf(process.platform === "win32")(
|
||||
"persistent Rizin debugger session manager",
|
||||
() => {
|
||||
let directory: string | undefined;
|
||||
const managers: Array<{ closeAll(): Promise<void> }> = [];
|
||||
|
||||
afterEach(async () => {
|
||||
await Promise.all(
|
||||
managers
|
||||
.splice(0)
|
||||
.map((manager) => manager.closeAll().catch(() => undefined)),
|
||||
);
|
||||
if (directory !== undefined)
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
directory = undefined;
|
||||
});
|
||||
|
||||
it("uses an absolute target path and waits for Rizin's completion marker", async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "rea-rizin-manager-"));
|
||||
const provider = join(directory, "fake-rizin.mjs");
|
||||
const argsFile = join(directory, "args.json");
|
||||
await writeFile(
|
||||
provider,
|
||||
`#!/usr/bin/env node
|
||||
const fs = await import("node:fs");
|
||||
fs.writeFileSync(${JSON.stringify(argsFile)}, JSON.stringify(process.argv.slice(2)));
|
||||
process.stdout.write("\\0");
|
||||
let input = "";
|
||||
let stalled = false;
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", (chunk) => {
|
||||
input += chunk;
|
||||
for (;;) {
|
||||
const boundary = input.indexOf("\\n");
|
||||
if (boundary < 0) break;
|
||||
const line = input.slice(0, boundary);
|
||||
input = input.slice(boundary + 1);
|
||||
if (line === "dr") process.stdout.write("backend-event\\0rax=0x1234\\0");
|
||||
else if (line === "olj") process.stdout.write("[]\\0");
|
||||
else if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\n\\0");
|
||||
}
|
||||
});
|
||||
`,
|
||||
);
|
||||
await chmod(provider, 0o700);
|
||||
const manager = createRizinTestManager({
|
||||
REA_RIZIN_COMMAND: provider,
|
||||
});
|
||||
managers.push(manager);
|
||||
|
||||
const started = await manager.start({
|
||||
path: "-target.bin",
|
||||
inferior_tty: await rizinTestInferiorTty(),
|
||||
backend: "test-backend",
|
||||
});
|
||||
expect(started.ok).toBe(true);
|
||||
if (!started.ok) return;
|
||||
const providerArgs = await import("node:fs/promises").then(
|
||||
({ readFile }) => readFile(argsFile, "utf8"),
|
||||
);
|
||||
expect(JSON.parse(providerArgs)).toEqual([
|
||||
"-N",
|
||||
"-0",
|
||||
"-d",
|
||||
"-R",
|
||||
`stdout=${await rizinTestInferiorTty()}`,
|
||||
"-R",
|
||||
`stderr=${await rizinTestInferiorTty()}`,
|
||||
"-e",
|
||||
"dbg.exitkills=false",
|
||||
"-D",
|
||||
"test-backend",
|
||||
resolve("-target.bin"),
|
||||
]);
|
||||
|
||||
const result = await manager.execute(started.value.session_id, "dr");
|
||||
expect(result.ok).toBe(true);
|
||||
if (result.ok) {
|
||||
expect(result.value.result.output).toBe("backend-event\nrax=0x1234");
|
||||
expect(result.value.result.output_scope).toBe(
|
||||
"command_and_interleaved_session_output",
|
||||
);
|
||||
expect(result.value.result.backend).toBe("test-backend");
|
||||
}
|
||||
expect((await manager.close(started.value.session_id)).ok).toBe(true);
|
||||
expect(manager.status(started.value.session_id)).toBeUndefined();
|
||||
});
|
||||
|
||||
it("stops and invalidates a Rizin session after its completion-marker timeout", async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "rea-rizin-timeout-"));
|
||||
const provider = join(directory, "fake-rizin-stall.mjs");
|
||||
await writeFile(
|
||||
provider,
|
||||
`#!/usr/bin/env node
|
||||
process.stdout.write("\\0");
|
||||
let input = "";
|
||||
let stalled = false;
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", (chunk) => {
|
||||
input += chunk;
|
||||
for (;;) {
|
||||
const boundary = input.indexOf("\\n");
|
||||
if (boundary < 0) break;
|
||||
const line = input.slice(0, boundary);
|
||||
input = input.slice(boundary + 1);
|
||||
if (line === "dr") process.stdout.write("rax=0x1234\\0");
|
||||
else if (line === "slow") {
|
||||
stalled = true;
|
||||
process.stdout.write("partial-timeout\\0");
|
||||
}
|
||||
else if (line.startsWith("!echo ") && !stalled) process.stdout.write(line.slice(6) + "\\n\\0");
|
||||
}
|
||||
});
|
||||
`,
|
||||
);
|
||||
await chmod(provider, 0o700);
|
||||
const manager = createRizinTestManager(
|
||||
{ REA_RIZIN_COMMAND: provider },
|
||||
{ frameTimeoutMs: 50 },
|
||||
);
|
||||
managers.push(manager);
|
||||
|
||||
const started = await manager.start({
|
||||
path: "/tmp/fixture.bin",
|
||||
inferior_tty: await rizinTestInferiorTty(),
|
||||
});
|
||||
expect(started.ok).toBe(true);
|
||||
if (!started.ok) return;
|
||||
const timedOut = await manager.execute(started.value.session_id, "slow");
|
||||
expect(timedOut.ok).toBe(true);
|
||||
if (timedOut.ok) {
|
||||
expect(timedOut.value.result).toMatchObject({
|
||||
output: "partial-timeout",
|
||||
output_truncated: true,
|
||||
completion_status: "unknown",
|
||||
});
|
||||
expect(timedOut.value.evidence.limitations.join(" ")).toContain(
|
||||
"timed out",
|
||||
);
|
||||
}
|
||||
expect(manager.status(started.value.session_id)?.state).toBe("closed");
|
||||
expect((await manager.execute(started.value.session_id, "dr")).ok).toBe(
|
||||
false,
|
||||
);
|
||||
expect((await manager.close(started.value.session_id)).ok).toBe(true);
|
||||
});
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"stops Rizin when empty unsolicited NUL frames exhaust the bounded queue",
|
||||
async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-rizin-empty-frames-"));
|
||||
const provider = join(directory, "fake-rizin-empty.mjs");
|
||||
const manager = createRizinTestManager({
|
||||
REA_RIZIN_COMMAND: provider,
|
||||
});
|
||||
try {
|
||||
await writeFile(
|
||||
provider,
|
||||
`#!/usr/bin/env node
|
||||
process.stdout.write("\\0");
|
||||
setTimeout(() => process.stdout.write("\\0".repeat(5000)), 10);
|
||||
process.stdin.resume();
|
||||
`,
|
||||
);
|
||||
await chmod(provider, 0o700);
|
||||
|
||||
const started = await manager.start({
|
||||
path: "/tmp/fixture.bin",
|
||||
inferior_tty: await rizinTestInferiorTty(),
|
||||
});
|
||||
expect(started.ok).toBe(true);
|
||||
if (!started.ok) return;
|
||||
await new Promise((resolveDelay) => setTimeout(resolveDelay, 100));
|
||||
|
||||
expect(manager.status(started.value.session_id)?.state).toBe("closed");
|
||||
expect((await manager.close(started.value.session_id)).ok).toBe(true);
|
||||
} finally {
|
||||
await manager.closeAll().catch(() => undefined);
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,894 @@
|
||||
import { spawn, type ChildProcess } from "node:child_process";
|
||||
import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises";
|
||||
import { resolve } from "node:path";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
|
||||
import { afterEach, expect, it } from "vitest";
|
||||
|
||||
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
|
||||
import {
|
||||
spawnOwnedProviderProcess,
|
||||
type ProviderProcessHandle,
|
||||
} from "../../../src/process/ProviderProcess.js";
|
||||
import { evidenceSchema } from "../../../src/domain/evidence.js";
|
||||
import {
|
||||
createRizinTestManager,
|
||||
rizinTestInferiorTty,
|
||||
} from "./RizinTestInferiorTty.js";
|
||||
import { createInjectedProcess } from "./RizinDebugSessionCoverage.fixtures.js";
|
||||
|
||||
let directory: string | undefined;
|
||||
const managers: Array<{ closeAll(): Promise<void> }> = [];
|
||||
const inferiorProcesses: ChildProcess[] = [];
|
||||
|
||||
const startRizinWithProvider = async (
|
||||
provider: string,
|
||||
): Promise<{
|
||||
manager: RizinDebugSessionManager;
|
||||
sessionId: string | undefined;
|
||||
}> => {
|
||||
const manager = createRizinTestManager({ REA_RIZIN_COMMAND: provider });
|
||||
managers.push(manager);
|
||||
const started = await manager.start({
|
||||
path: "/tmp/fixture.bin",
|
||||
inferior_tty: await rizinTestInferiorTty(),
|
||||
});
|
||||
expect(started.ok).toBe(true);
|
||||
return {
|
||||
manager,
|
||||
sessionId: started.ok ? started.value.session_id : undefined,
|
||||
};
|
||||
};
|
||||
|
||||
const startRizinWithOwnedStop = async (provider: string) => {
|
||||
let debuggerProcess: ProviderProcessHandle | undefined;
|
||||
const manager = new RizinDebugSessionManager(
|
||||
{ ...process.env, REA_RIZIN_COMMAND: provider },
|
||||
{
|
||||
platform: "linux",
|
||||
spawnProcess: async (options) => {
|
||||
const launched = await spawnOwnedProviderProcess(options);
|
||||
debuggerProcess = launched.process;
|
||||
return launched;
|
||||
},
|
||||
},
|
||||
);
|
||||
managers.push(manager);
|
||||
const started = await manager.start({
|
||||
path: "/tmp/fixture.bin",
|
||||
inferior_tty: await rizinTestInferiorTty(),
|
||||
});
|
||||
if (!started.ok) throw started.error;
|
||||
return {
|
||||
manager,
|
||||
sessionId: started.value.session_id,
|
||||
exitDebugger: async () => {
|
||||
if (debuggerProcess === undefined)
|
||||
throw new Error("Provider did not spawn");
|
||||
const exited = new Promise<void>((resolve) =>
|
||||
debuggerProcess?.once("exit", () => resolve()),
|
||||
);
|
||||
debuggerProcess.kill("SIGTERM");
|
||||
await exited;
|
||||
},
|
||||
};
|
||||
};
|
||||
|
||||
const expectOwnedProcessExited = async (pidText: string): Promise<void> => {
|
||||
const pid = Number(pidText);
|
||||
expect(Number.isInteger(pid)).toBe(true);
|
||||
expect(() => process.kill(pid, 0)).toThrow();
|
||||
};
|
||||
|
||||
afterEach(async () => {
|
||||
for (const inferior of inferiorProcesses.splice(0)) {
|
||||
if (inferior.exitCode !== null || inferior.signalCode !== null) continue;
|
||||
const exited = new Promise<void>((resolveExit) =>
|
||||
inferior.once("exit", () => resolveExit()),
|
||||
);
|
||||
inferior.kill("SIGTERM");
|
||||
await exited;
|
||||
}
|
||||
await Promise.all(
|
||||
managers
|
||||
.splice(0)
|
||||
.map((manager) => manager.closeAll().catch(() => undefined)),
|
||||
);
|
||||
if (directory !== undefined)
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
directory = undefined;
|
||||
});
|
||||
|
||||
const spawnTestInferior = async (): Promise<ChildProcess> => {
|
||||
const inferior = spawn(
|
||||
process.execPath,
|
||||
["-e", "setInterval(() => {}, 1000)"],
|
||||
{
|
||||
stdio: "ignore",
|
||||
},
|
||||
);
|
||||
inferiorProcesses.push(inferior);
|
||||
await new Promise<void>((resolveSpawn, rejectSpawn) => {
|
||||
inferior.once("spawn", resolveSpawn);
|
||||
inferior.once("error", rejectSpawn);
|
||||
});
|
||||
return inferior;
|
||||
};
|
||||
|
||||
const createInferiorInventoryProvider = async (
|
||||
rows: readonly { readonly fd: number; readonly pid: number }[],
|
||||
): Promise<string> => {
|
||||
directory = await mkdtemp(join(tmpdir(), "rea-rizin-owned-inferior-"));
|
||||
const provider = join(directory, "fake-rizin-owned-inferior.mjs");
|
||||
await writeFile(
|
||||
provider,
|
||||
`#!/usr/bin/env node
|
||||
process.stdout.write("\\0");
|
||||
let input = "";
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", (chunk) => {
|
||||
input += chunk;
|
||||
for (;;) {
|
||||
const boundary = input.indexOf("\\n"); if (boundary < 0) break;
|
||||
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
|
||||
if (line === "olj") process.stdout.write(JSON.stringify(${JSON.stringify(rows.map(({ fd, pid }) => ({ fd, raised: true, uri: `ptrace://${pid}` })))} ) + "\\0");
|
||||
else if (line === "e dbg.exitkills") process.stdout.write("true\\0");
|
||||
else if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\0");
|
||||
else process.stdout.write("\\0");
|
||||
}
|
||||
});
|
||||
`,
|
||||
);
|
||||
await chmod(provider, 0o700);
|
||||
return provider;
|
||||
};
|
||||
|
||||
it("keeps persistent Rizin sessions unavailable on Windows", async () => {
|
||||
const rizin = await createRizinTestManager(
|
||||
{ REA_RIZIN_COMMAND: "/missing/rizin" },
|
||||
{ platform: "win32" },
|
||||
).start({
|
||||
path: "/tmp/fixture.bin",
|
||||
inferior_tty: "unused-before-platform-admission",
|
||||
});
|
||||
expect(rizin.ok).toBe(false);
|
||||
if (!rizin.ok) {
|
||||
expect(rizin.error._tag).toBe("AnalysisCapabilityUnavailableError");
|
||||
expect(rizin.error.message).toContain("Linux /proc descriptor readback");
|
||||
}
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"rejects startup when Rizin exits immediately after its initial frame",
|
||||
async () => {
|
||||
const injected = createInjectedProcess({
|
||||
startup: (control) => {
|
||||
control.output(Buffer.from("startup diagnostic\0partial trailing"));
|
||||
control.exit();
|
||||
},
|
||||
});
|
||||
const manager = createRizinTestManager(
|
||||
{ REA_RIZIN_COMMAND: "injected-rizin" },
|
||||
{ spawnProcess: injected.spawnProcess },
|
||||
);
|
||||
managers.push(manager);
|
||||
|
||||
const started = await manager.start({
|
||||
path: "/tmp/fixture.bin",
|
||||
inferior_tty: await rizinTestInferiorTty(),
|
||||
});
|
||||
|
||||
expect(started.ok).toBe(false);
|
||||
if (!started.ok) {
|
||||
expect(started.error._tag).toBe("AnalysisCapabilityUnavailableError");
|
||||
expect(started.error.message).toContain("exited");
|
||||
expect(started.error.message).not.toContain("timed out");
|
||||
expect(started.error.capturedOutput).toMatchObject({
|
||||
stdout: "startup diagnostic\npartial trailing",
|
||||
stderr: "",
|
||||
truncated: false,
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"preserves partial Rizin stdout when startup times out before its first frame",
|
||||
async () => {
|
||||
const injected = createInjectedProcess({
|
||||
startup: (control) => control.output("partial startup diagnostic"),
|
||||
});
|
||||
const manager = createRizinTestManager(
|
||||
{ REA_RIZIN_COMMAND: "injected-rizin" },
|
||||
{ spawnProcess: injected.spawnProcess, startupTimeoutMs: 25 },
|
||||
);
|
||||
managers.push(manager);
|
||||
|
||||
const started = await manager.start({
|
||||
path: "/tmp/fixture.bin",
|
||||
inferior_tty: await rizinTestInferiorTty(),
|
||||
});
|
||||
|
||||
expect(started.ok).toBe(false);
|
||||
if (!started.ok) {
|
||||
expect(started.error._tag).toBe("AnalysisTimeoutError");
|
||||
expect(started.error.capturedOutput).toMatchObject({
|
||||
stdout: expect.stringContaining("partial startup diagnostic"),
|
||||
stderr: "",
|
||||
truncated: false,
|
||||
});
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"keeps session UTF-8 status cumulative while command evidence reports only its frames",
|
||||
async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "rea-rizin-command-utf8-scope-"));
|
||||
const provider = join(directory, "fake-rizin-command-utf8-scope.mjs");
|
||||
await writeFile(
|
||||
provider,
|
||||
`#!/usr/bin/env node
|
||||
process.stdout.write(Buffer.from([0xff, 0]));
|
||||
let input = "";
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", (chunk) => {
|
||||
input += chunk;
|
||||
for (;;) {
|
||||
const boundary = input.indexOf("\\n"); if (boundary < 0) break;
|
||||
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
|
||||
if (line === "invalid-output") process.stdout.write(Buffer.from([0xfe, 0]));
|
||||
else if (!line.startsWith("!echo ")) process.stdout.write("valid output\\0");
|
||||
else process.stdout.write(line.slice(6) + "\\0");
|
||||
}
|
||||
});
|
||||
`,
|
||||
);
|
||||
await chmod(provider, 0o700);
|
||||
const { manager, sessionId } = await startRizinWithProvider(provider);
|
||||
if (sessionId === undefined) return;
|
||||
|
||||
expect(manager.status(sessionId)?.output_invalid_utf8).toBe(true);
|
||||
const firstValid = await manager.execute(sessionId, "valid-before-invalid");
|
||||
expect(firstValid.ok).toBe(true);
|
||||
if (firstValid.ok) {
|
||||
expect(firstValid.value.result).not.toHaveProperty("output_invalid_utf8");
|
||||
expect(firstValid.value.evidence.raw_result).not.toHaveProperty(
|
||||
"output_invalid_utf8",
|
||||
);
|
||||
expect(firstValid.value.evidence.normalized_result).not.toHaveProperty(
|
||||
"output_invalid_utf8",
|
||||
);
|
||||
expect(firstValid.value.evidence.limitations.join(" ")).not.toContain(
|
||||
"Collected command frames contained invalid UTF-8 bytes",
|
||||
);
|
||||
}
|
||||
|
||||
const invalid = await manager.execute(sessionId, "invalid-output");
|
||||
expect(invalid.ok).toBe(true);
|
||||
if (invalid.ok) {
|
||||
expect(invalid.value.result.output_invalid_utf8).toBe(true);
|
||||
expect(invalid.value.evidence.raw_result).toMatchObject({
|
||||
output_invalid_utf8: true,
|
||||
});
|
||||
expect(invalid.value.evidence.normalized_result).toMatchObject({
|
||||
output_invalid_utf8: true,
|
||||
});
|
||||
expect(invalid.value.evidence.limitations.join(" ")).toContain(
|
||||
"Collected command frames contained invalid UTF-8 bytes; decoded text may contain replacement characters.",
|
||||
);
|
||||
}
|
||||
|
||||
const laterValid = await manager.execute(sessionId, "valid-after-invalid");
|
||||
expect(laterValid.ok).toBe(true);
|
||||
if (laterValid.ok) {
|
||||
expect(laterValid.value.result).not.toHaveProperty("output_invalid_utf8");
|
||||
expect(laterValid.value.evidence.raw_result).not.toHaveProperty(
|
||||
"output_invalid_utf8",
|
||||
);
|
||||
expect(laterValid.value.evidence.normalized_result).not.toHaveProperty(
|
||||
"output_invalid_utf8",
|
||||
);
|
||||
expect(laterValid.value.evidence.limitations.join(" ")).not.toContain(
|
||||
"Collected command frames contained invalid UTF-8 bytes",
|
||||
);
|
||||
}
|
||||
expect(manager.status(sessionId)?.output_invalid_utf8).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform !== "linux")(
|
||||
"clears retained Rizin cleanup after its identified inferior exits",
|
||||
async () => {
|
||||
const inferior = await spawnTestInferior();
|
||||
const pid = inferior.pid;
|
||||
expect(pid).toBeDefined();
|
||||
if (pid === undefined) return;
|
||||
const provider = await createInferiorInventoryProvider([{ fd: 12, pid }]);
|
||||
const { manager, sessionId, exitDebugger } =
|
||||
await startRizinWithOwnedStop(provider);
|
||||
if (sessionId === undefined) return;
|
||||
|
||||
const firstClose = await manager.close(sessionId);
|
||||
|
||||
expect(firstClose.ok, JSON.stringify(firstClose)).toBe(false);
|
||||
if (!firstClose.ok) expect(firstClose.error.cleanupIncomplete).toBe(true);
|
||||
await exitDebugger();
|
||||
expect((await manager.retryCleanupFailures()).ok).toBe(false);
|
||||
expect(manager.status(sessionId)?.state).toBe("closed");
|
||||
|
||||
const inferiorExited = new Promise<void>((resolveExit) =>
|
||||
inferior.once("exit", () => resolveExit()),
|
||||
);
|
||||
inferior.kill("SIGTERM");
|
||||
await inferiorExited;
|
||||
const retried = await manager.retryCleanupFailures();
|
||||
|
||||
expect(retried).toEqual({ ok: true, value: null });
|
||||
if (!firstClose.ok) expect(firstClose.error.cleanupIncomplete).toBe(false);
|
||||
expect(manager.status(sessionId)).toBeUndefined();
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform !== "linux")(
|
||||
"keeps Rizin cleanup unknown when an inferior inventory is only partially captured",
|
||||
async () => {
|
||||
const inferior = await spawnTestInferior();
|
||||
const pid = inferior.pid;
|
||||
expect(pid).toBeDefined();
|
||||
if (pid === undefined) return;
|
||||
const provider = await createInferiorInventoryProvider([
|
||||
{ fd: 12, pid },
|
||||
{ fd: 13, pid: 999_999_999 },
|
||||
]);
|
||||
const { manager, sessionId, exitDebugger } =
|
||||
await startRizinWithOwnedStop(provider);
|
||||
if (sessionId === undefined) return;
|
||||
|
||||
expect((await manager.close(sessionId)).ok).toBe(false);
|
||||
await exitDebugger();
|
||||
const closed = await manager.close(sessionId);
|
||||
|
||||
expect(closed.ok, JSON.stringify(closed)).toBe(false);
|
||||
if (!closed.ok)
|
||||
expect(closed.error.message).toContain("no owner proof confirms");
|
||||
expect(manager.status(sessionId)).toBeDefined();
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"retains Rizin cleanup when target state is unknown at debugger exit",
|
||||
async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "rea-rizin-unknown-target-"));
|
||||
const provider = join(directory, "fake-rizin-unknown-target.mjs");
|
||||
await writeFile(
|
||||
provider,
|
||||
`#!/usr/bin/env node
|
||||
process.stdout.write("\\0");
|
||||
let input = "";
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", (chunk) => {
|
||||
input += chunk;
|
||||
for (;;) {
|
||||
const boundary = input.indexOf("\\n"); if (boundary < 0) break;
|
||||
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
|
||||
if (line === "olj") process.stdout.write("not-json\\0");
|
||||
else if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\0");
|
||||
}
|
||||
});
|
||||
`,
|
||||
);
|
||||
await chmod(provider, 0o700);
|
||||
const { manager, sessionId, exitDebugger } =
|
||||
await startRizinWithOwnedStop(provider);
|
||||
if (sessionId === undefined) return;
|
||||
|
||||
expect((await manager.close(sessionId)).ok).toBe(false);
|
||||
await exitDebugger();
|
||||
const closed = await manager.close(sessionId);
|
||||
|
||||
expect(closed.ok, JSON.stringify(closed)).toBe(false);
|
||||
if (!closed.ok)
|
||||
expect(closed.error.message).toContain("no owner proof confirms");
|
||||
expect(manager.status(sessionId)).toBeDefined();
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"preserves command parameters in Rizin observation evidence",
|
||||
async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "rea-rizin-command-evidence-"));
|
||||
const provider = join(directory, "fake-rizin-command-evidence.mjs");
|
||||
const inferiorTty = await rizinTestInferiorTty();
|
||||
await writeFile(
|
||||
provider,
|
||||
`#!/usr/bin/env node
|
||||
process.stdout.write("\\0");
|
||||
let input = "";
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", (chunk) => {
|
||||
input += chunk;
|
||||
for (;;) {
|
||||
const boundary = input.indexOf("\\n"); if (boundary < 0) break;
|
||||
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
|
||||
if (!line.startsWith("!echo ")) process.stdout.write("command output\\0");
|
||||
else process.stdout.write(line.slice(6) + "\\0");
|
||||
}
|
||||
});
|
||||
`,
|
||||
);
|
||||
await chmod(provider, 0o700);
|
||||
const manager = createRizinTestManager({ REA_RIZIN_COMMAND: provider });
|
||||
managers.push(manager);
|
||||
const callerSelectedPath = "./relative/../fixture.bin";
|
||||
const resolvedPath = resolve(callerSelectedPath);
|
||||
const started = await manager.start({
|
||||
path: callerSelectedPath,
|
||||
inferior_tty: inferiorTty,
|
||||
});
|
||||
expect(started.ok).toBe(true);
|
||||
if (!started.ok) return;
|
||||
|
||||
const executed = await manager.execute(started.value.session_id, "dr");
|
||||
|
||||
expect(executed.ok).toBe(true);
|
||||
if (executed.ok)
|
||||
expect(executed.value.evidence.parameters).toEqual({
|
||||
session_id: started.value.session_id,
|
||||
command: "dr",
|
||||
inferior_tty: inferiorTty,
|
||||
launch_provenance: {
|
||||
caller_selected_path: callerSelectedPath,
|
||||
resolved_path: resolvedPath,
|
||||
},
|
||||
});
|
||||
if (executed.ok)
|
||||
expect(executed.value.evidence.limitations).toContain(
|
||||
"Launch provenance records the original and resolved startup paths; it does not establish the current target after unrestricted debugger commands.",
|
||||
);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"keeps queued Rizin commands serialized when a waiting request is cancelled",
|
||||
async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "rea-rizin-queue-cancel-"));
|
||||
const provider = join(directory, "fake-rizin-queue-cancel.mjs");
|
||||
const overlapPath = join(directory, "overlap");
|
||||
await writeFile(
|
||||
provider,
|
||||
`#!/usr/bin/env node
|
||||
process.stdout.write("\\0");
|
||||
let input = "";
|
||||
let firstActive = false;
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", (chunk) => {
|
||||
input += chunk;
|
||||
for (;;) {
|
||||
const boundary = input.indexOf("\\n"); if (boundary < 0) break;
|
||||
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
|
||||
if (line === "first") firstActive = true;
|
||||
if (line === "third" && firstActive) import("node:fs/promises").then((fs) => fs.writeFile(${JSON.stringify(overlapPath)}, "overlap"));
|
||||
if (line.startsWith("!echo ")) {
|
||||
const marker = line.slice(6);
|
||||
if (firstActive) setTimeout(() => { firstActive = false; process.stdout.write(marker + "\\0"); }, 100);
|
||||
else process.stdout.write(marker + "\\0");
|
||||
}
|
||||
}
|
||||
});
|
||||
`,
|
||||
);
|
||||
await chmod(provider, 0o700);
|
||||
const { manager, sessionId } = await startRizinWithProvider(provider);
|
||||
if (sessionId === undefined) return;
|
||||
const first = manager.execute(sessionId, "first");
|
||||
const controller = new AbortController();
|
||||
const second = manager.execute(sessionId, "second", controller.signal);
|
||||
await new Promise((resolveDelay) => setTimeout(resolveDelay, 20));
|
||||
controller.abort();
|
||||
const third = manager.execute(sessionId, "third");
|
||||
expect((await second).ok).toBe(false);
|
||||
expect((await first).ok).toBe(true);
|
||||
expect((await third).ok).toBe(true);
|
||||
await expect(readFile(overlapPath, "utf8")).rejects.toThrow();
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"preserves a truncated single Rizin frame that exceeds the protocol limit",
|
||||
async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "rea-rizin-frame-overflow-"));
|
||||
const provider = join(directory, "fake-rizin-frame-overflow.mjs");
|
||||
await writeFile(
|
||||
provider,
|
||||
`#!/usr/bin/env node
|
||||
process.stdout.write("\\0");
|
||||
let input = "";
|
||||
let sent = false;
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", (chunk) => {
|
||||
input += chunk;
|
||||
for (;;) {
|
||||
const boundary = input.indexOf("\\n"); if (boundary < 0) break;
|
||||
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
|
||||
if (!line.startsWith("!echo ") && !sent) {
|
||||
sent = true;
|
||||
process.stdout.write("z".repeat(16 * 1024 * 1024 + 32) + "\\0");
|
||||
}
|
||||
}
|
||||
});
|
||||
`,
|
||||
);
|
||||
await chmod(provider, 0o700);
|
||||
const { manager, sessionId } = await startRizinWithProvider(provider);
|
||||
if (sessionId === undefined) return;
|
||||
|
||||
const result = await manager.execute(sessionId, "px");
|
||||
|
||||
expect(result.ok, result.ok ? "" : result.error.message).toBe(true);
|
||||
if (result.ok) {
|
||||
expect(
|
||||
Buffer.byteLength(result.value.result.output, "utf8"),
|
||||
).toBeLessThanOrEqual(16 * 1024 * 1024);
|
||||
expect(result.value.result).toMatchObject({
|
||||
output_truncated: true,
|
||||
completion_status: "unknown",
|
||||
});
|
||||
expect(result.value.evidence.parameters).toMatchObject({
|
||||
session_id: sessionId,
|
||||
command: "px",
|
||||
inferior_tty: expect.any(String),
|
||||
});
|
||||
}
|
||||
expect(manager.status(sessionId)).toBeDefined();
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"returns bounded partial Rizin output with unknown completion after overflow",
|
||||
async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "rea-rizin-output-overflow-"));
|
||||
const provider = join(directory, "fake-rizin-output-overflow.mjs");
|
||||
await writeFile(
|
||||
provider,
|
||||
`#!/usr/bin/env node
|
||||
process.stdout.write("\\0");
|
||||
let input = "";
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", (chunk) => {
|
||||
input += chunk;
|
||||
for (;;) {
|
||||
const boundary = input.indexOf("\\n"); if (boundary < 0) break;
|
||||
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
|
||||
if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\0");
|
||||
else if (line === "olj") process.stdout.write(JSON.stringify([{ fd: 12, raised: true, uri: "ptrace://" + process.ppid }]) + "\\0");
|
||||
else if (line === "px") process.stdout.write("x".repeat(10 * 1024 * 1024) + "\\0" + "y".repeat(10 * 1024 * 1024) + "\\0");
|
||||
else process.stdout.write("\\0");
|
||||
}
|
||||
});
|
||||
`,
|
||||
);
|
||||
await chmod(provider, 0o700);
|
||||
const { manager, sessionId } = await startRizinWithProvider(provider);
|
||||
if (sessionId === undefined) return;
|
||||
|
||||
const result = await manager.execute(sessionId, "px");
|
||||
|
||||
expect(result.ok, result.ok ? "" : result.error.message).toBe(true);
|
||||
if (result.ok) {
|
||||
expect(
|
||||
Buffer.byteLength(result.value.result.output, "utf8"),
|
||||
).toBeLessThanOrEqual(16 * 1024 * 1024);
|
||||
expect(result.value.result).toMatchObject({
|
||||
output_truncated: true,
|
||||
completion_status: "unknown",
|
||||
});
|
||||
}
|
||||
expect(manager.status(sessionId)).toBeDefined();
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"waits for the Rizin process to exit when command correlation times out",
|
||||
async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "rea-rizin-command-timeout-"));
|
||||
const provider = join(directory, "fake-rizin-command-timeout.mjs");
|
||||
await writeFile(
|
||||
provider,
|
||||
`#!/usr/bin/env node
|
||||
await import("node:fs/promises").then((fs) => fs.writeFile(${JSON.stringify(join(directory ?? "", "pid"))}, String(process.pid)));
|
||||
process.stdout.write("\\0");
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", () => process.stdout.write(Buffer.from([0xff, 0])));
|
||||
`,
|
||||
);
|
||||
await chmod(provider, 0o700);
|
||||
const manager = createRizinTestManager(
|
||||
{ REA_RIZIN_COMMAND: provider },
|
||||
{ frameTimeoutMs: 40 },
|
||||
);
|
||||
managers.push(manager);
|
||||
const started = await manager.start({
|
||||
path: "/tmp/fixture.bin",
|
||||
inferior_tty: await rizinTestInferiorTty(),
|
||||
});
|
||||
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).toMatchObject({
|
||||
output: "�",
|
||||
output_truncated: true,
|
||||
completion_status: "unknown",
|
||||
output_invalid_utf8: true,
|
||||
});
|
||||
expect(result.value.evidence.limitations).toContain(
|
||||
"Collected command frames contained invalid UTF-8 bytes; decoded text may contain replacement characters.",
|
||||
);
|
||||
}
|
||||
await expectOwnedProcessExited(
|
||||
await readFile(join(directory, "pid"), "utf8"),
|
||||
);
|
||||
expect(manager.status(started.value.session_id)?.state).toBe("closed");
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"cancels a running Rizin command and retains its closed status",
|
||||
async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "rea-rizin-command-cancel-"));
|
||||
const provider = join(directory, "fake-rizin-command-cancel.mjs");
|
||||
await writeFile(
|
||||
provider,
|
||||
`#!/usr/bin/env node
|
||||
process.stdout.write("\\0");
|
||||
let input = "";
|
||||
let stalled = false;
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", (chunk) => {
|
||||
input += chunk;
|
||||
for (;;) {
|
||||
const boundary = input.indexOf("\\n"); if (boundary < 0) break;
|
||||
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
|
||||
if (line === "slow") {
|
||||
stalled = true;
|
||||
process.stdout.write(Buffer.from([0xff, 0]));
|
||||
}
|
||||
else if (line.startsWith("!echo ") && !stalled) process.stdout.write(line.slice(6) + "\\n\\0");
|
||||
}
|
||||
});
|
||||
`,
|
||||
);
|
||||
await chmod(provider, 0o700);
|
||||
const manager = createRizinTestManager(
|
||||
{ REA_RIZIN_COMMAND: provider },
|
||||
{ frameTimeoutMs: 5_000 },
|
||||
);
|
||||
managers.push(manager);
|
||||
const callerSelectedPath = "./cancelled/../fixture.bin";
|
||||
const resolvedPath = resolve(callerSelectedPath);
|
||||
const started = await manager.start({
|
||||
path: callerSelectedPath,
|
||||
inferior_tty: await rizinTestInferiorTty(),
|
||||
});
|
||||
expect(started.ok).toBe(true);
|
||||
if (!started.ok) return;
|
||||
const controller = new AbortController();
|
||||
setTimeout(() => controller.abort(), 50);
|
||||
|
||||
const result = await manager.execute(
|
||||
started.value.session_id,
|
||||
"slow",
|
||||
controller.signal,
|
||||
);
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
if (!result.ok) {
|
||||
expect(result.error._tag).toBe("AnalysisCancelledError");
|
||||
expect(result.error.partialObservation).toMatchObject({
|
||||
normalized_result: { output_invalid_utf8: true },
|
||||
limitations: expect.arrayContaining([
|
||||
"Collected command frames contained invalid UTF-8 bytes; decoded text may contain replacement characters.",
|
||||
]),
|
||||
parameters: {
|
||||
launch_provenance: {
|
||||
caller_selected_path: callerSelectedPath,
|
||||
resolved_path: resolvedPath,
|
||||
},
|
||||
},
|
||||
});
|
||||
}
|
||||
expect(manager.status(started.value.session_id)?.state).toBe("closed");
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"reports bounded Rizin stderr retention in session status",
|
||||
async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "rea-rizin-diagnostic-limit-"));
|
||||
const provider = join(directory, "fake-rizin-diagnostic-limit.mjs");
|
||||
await writeFile(
|
||||
provider,
|
||||
`#!/usr/bin/env node
|
||||
process.stderr.write("x".repeat(100000));
|
||||
process.stdout.write("\\0");
|
||||
process.stdin.resume();
|
||||
`,
|
||||
);
|
||||
await chmod(provider, 0o700);
|
||||
const manager = createRizinTestManager({
|
||||
REA_RIZIN_COMMAND: provider,
|
||||
});
|
||||
managers.push(manager);
|
||||
const started = await manager.start({
|
||||
path: "/tmp/fixture.bin",
|
||||
inferior_tty: await rizinTestInferiorTty(),
|
||||
});
|
||||
expect(started.ok).toBe(true);
|
||||
if (!started.ok) return;
|
||||
await new Promise((resolveDelay) => setTimeout(resolveDelay, 50));
|
||||
|
||||
expect(
|
||||
manager.status(started.value.session_id)?.diagnostics_truncated,
|
||||
).toBe(true);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"returns cancellation when Rizin startup is cancelled after spawn",
|
||||
async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "rea-rizin-start-cancel-"));
|
||||
const provider = join(directory, "fake-rizin-start-cancel.mjs");
|
||||
await writeFile(
|
||||
provider,
|
||||
`#!/usr/bin/env node\nprocess.stdin.resume();\nsetInterval(() => {}, 1000);\n`,
|
||||
);
|
||||
await chmod(provider, 0o700);
|
||||
const manager = createRizinTestManager({
|
||||
REA_RIZIN_COMMAND: provider,
|
||||
});
|
||||
managers.push(manager);
|
||||
const controller = new AbortController();
|
||||
setTimeout(() => controller.abort(), 50);
|
||||
|
||||
const started = await manager.start(
|
||||
{ path: "/tmp/fixture.bin", inferior_tty: await rizinTestInferiorTty() },
|
||||
controller.signal,
|
||||
);
|
||||
|
||||
expect(started.ok).toBe(false);
|
||||
if (!started.ok) expect(started.error._tag).toBe("AnalysisCancelledError");
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"converts a Rizin stdin pipe failure into a provider session error",
|
||||
async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "rea-rizin-stdin-error-"));
|
||||
const provider = join(directory, "fake-rizin-stdin-error.mjs");
|
||||
await writeFile(
|
||||
provider,
|
||||
`#!/usr/bin/env node
|
||||
process.stdout.write("\\0");
|
||||
setTimeout(() => import("node:fs").then((fs) => fs.closeSync(0)), 40);
|
||||
setInterval(() => {}, 1000);
|
||||
`,
|
||||
);
|
||||
await chmod(provider, 0o700);
|
||||
const manager = createRizinTestManager({
|
||||
REA_RIZIN_COMMAND: provider,
|
||||
});
|
||||
managers.push(manager);
|
||||
const started = await manager.start({
|
||||
path: "/tmp/fixture.bin",
|
||||
inferior_tty: await rizinTestInferiorTty(),
|
||||
});
|
||||
expect(started.ok).toBe(true);
|
||||
if (!started.ok) return;
|
||||
await new Promise((resolveDelay) => setTimeout(resolveDelay, 80));
|
||||
|
||||
const result = await manager.execute(started.value.session_id, "dr");
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
expect(manager.status(started.value.session_id)?.state).toBe("closed");
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"preserves Rizin process-exit reason and partial command output",
|
||||
async () => {
|
||||
directory = await mkdtemp(join(tmpdir(), "rea-rizin-command-exit-"));
|
||||
const provider = join(directory, "fake-rizin-command-exit.mjs");
|
||||
const writerPidPath = join(directory, "writer.pid");
|
||||
await writeFile(
|
||||
provider,
|
||||
`#!/usr/bin/env node
|
||||
import { spawn } from "node:child_process";
|
||||
import { writeFileSync } from "node:fs";
|
||||
process.stdout.write("\\0");
|
||||
let input = "";
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", (chunk) => {
|
||||
input += chunk;
|
||||
for (;;) {
|
||||
const boundary = input.indexOf("\\n");
|
||||
if (boundary < 0) break;
|
||||
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
|
||||
if (line === "exit-now") {
|
||||
const writer = spawn(process.execPath, ["-e", "setInterval(() => {}, 1000)"], { stdio: "inherit" });
|
||||
writeFileSync(${JSON.stringify(writerPidPath)}, String(writer.pid));
|
||||
process.stdout.write(Buffer.concat([Buffer.from("partial-before-exit\\0second-partial\\0"), Buffer.from([0xff, 0])]), () => process.exit(7));
|
||||
}
|
||||
}
|
||||
});
|
||||
`,
|
||||
);
|
||||
await chmod(provider, 0o700);
|
||||
let writerObserved = false;
|
||||
const manager = createRizinTestManager(
|
||||
{ REA_RIZIN_COMMAND: provider },
|
||||
{
|
||||
stopProcess: async () => {
|
||||
const writerPid = Number(await readFile(writerPidPath, "utf8"));
|
||||
try {
|
||||
process.kill(writerPid, 0);
|
||||
writerObserved = true;
|
||||
} catch {
|
||||
writerObserved = false;
|
||||
}
|
||||
return {
|
||||
status: "incomplete",
|
||||
reason: "owned output writer is still active",
|
||||
};
|
||||
},
|
||||
},
|
||||
);
|
||||
managers.push(manager);
|
||||
const callerSelectedPath = "./exit/../fixture.bin";
|
||||
const resolvedPath = resolve(callerSelectedPath);
|
||||
const started = await manager.start({
|
||||
path: callerSelectedPath,
|
||||
inferior_tty: await rizinTestInferiorTty(),
|
||||
});
|
||||
expect(started.ok).toBe(true);
|
||||
if (!started.ok) return;
|
||||
|
||||
const exited = await manager.execute(started.value.session_id, "exit-now");
|
||||
|
||||
expect(exited.ok).toBe(false);
|
||||
expect(writerObserved).toBe(true);
|
||||
if (!exited.ok) {
|
||||
expect(exited.error.cleanup).toEqual({
|
||||
reason: "owned output writer is still active",
|
||||
resources: [started.value.session_id],
|
||||
});
|
||||
expect(exited.error.partialObservation).toMatchObject({
|
||||
normalized_result: {
|
||||
output: ["partial-before-exit", "second-partial", "�"].join("\n"),
|
||||
completion_status: "unknown",
|
||||
output_invalid_utf8: true,
|
||||
},
|
||||
parameters: {
|
||||
command: "exit-now",
|
||||
session_id: started.value.session_id,
|
||||
launch_provenance: {
|
||||
caller_selected_path: callerSelectedPath,
|
||||
resolved_path: resolvedPath,
|
||||
},
|
||||
},
|
||||
});
|
||||
const partialEvidence = evidenceSchema.parse(
|
||||
exited.error.partialObservation,
|
||||
);
|
||||
expect(partialEvidence.limitations.join(" ")).toContain(
|
||||
"Rizin exited before the command-completion marker; retained frame output is partial and command completion is unknown.",
|
||||
);
|
||||
}
|
||||
const writerPid = Number(await readFile(writerPidPath, "utf8"));
|
||||
process.kill(writerPid, "SIGKILL");
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,645 @@
|
||||
import { execFileSync, spawn as spawnChild } from "node:child_process";
|
||||
import {
|
||||
chmod,
|
||||
mkdtemp,
|
||||
readFile,
|
||||
realpath,
|
||||
rm,
|
||||
writeFile,
|
||||
} from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join } from "node:path";
|
||||
import { spawn } from "@lydell/node-pty";
|
||||
import { afterEach, expect, it, vi } from "vitest";
|
||||
|
||||
import {
|
||||
assertRizinProcessStartTimeStable,
|
||||
parseRizinProcStartTime,
|
||||
RizinDebugSessionManager,
|
||||
} from "../../../src/rizin/RizinDebugSessionManager.js";
|
||||
import { evidenceSchema } from "../../../src/domain/evidence.js";
|
||||
import { TOOL_EFFECTS } from "../../../src/contracts/toolEffects.js";
|
||||
import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js";
|
||||
import {
|
||||
createRizinTestManager,
|
||||
rizinTestInferiorTty,
|
||||
} from "./RizinTestInferiorTty.js";
|
||||
import { createInjectedProcess } from "./RizinDebugSessionCoverage.fixtures.js";
|
||||
|
||||
let terminal: ReturnType<typeof spawn> | undefined;
|
||||
let manager: RizinDebugSessionManager | undefined;
|
||||
let testDirectory: string | undefined;
|
||||
let inferiorPid: number | undefined;
|
||||
let providerPid: number | undefined;
|
||||
let providerWatchdogPid: number | undefined;
|
||||
const rizinBinary = findRizinBinary();
|
||||
|
||||
afterEach(async () => {
|
||||
await manager?.closeAll().catch(() => undefined);
|
||||
manager = undefined;
|
||||
if (providerPid !== undefined && testDirectory !== undefined) {
|
||||
try {
|
||||
const commandLine = await readFile(
|
||||
`/proc/${providerPid}/cmdline`,
|
||||
"utf8",
|
||||
);
|
||||
if (commandLine.includes(testDirectory))
|
||||
process.kill(providerPid, "SIGKILL");
|
||||
} catch {
|
||||
// The owned fake provider may already have exited.
|
||||
}
|
||||
}
|
||||
providerPid = undefined;
|
||||
if (providerWatchdogPid !== undefined) {
|
||||
try {
|
||||
process.kill(providerWatchdogPid, "SIGTERM");
|
||||
} catch {
|
||||
// The watchdog may already have completed.
|
||||
}
|
||||
}
|
||||
providerWatchdogPid = undefined;
|
||||
terminal?.kill();
|
||||
terminal = undefined;
|
||||
let ownedPid = inferiorPid;
|
||||
if (ownedPid === undefined && testDirectory !== undefined) {
|
||||
try {
|
||||
ownedPid = Number(
|
||||
await readFile(join(testDirectory, "target.pid"), "utf8"),
|
||||
);
|
||||
} catch {
|
||||
// The target may not have started before the test failed.
|
||||
}
|
||||
}
|
||||
if (
|
||||
ownedPid !== undefined &&
|
||||
Number.isSafeInteger(ownedPid) &&
|
||||
ownedPid > 0
|
||||
) {
|
||||
try {
|
||||
const commandLine = await readFile(`/proc/${ownedPid}/cmdline`, "utf8");
|
||||
if (testDirectory !== undefined && commandLine.includes(testDirectory))
|
||||
process.kill(ownedPid, "SIGKILL");
|
||||
} catch {
|
||||
// The test target may already have exited.
|
||||
}
|
||||
}
|
||||
inferiorPid = undefined;
|
||||
if (testDirectory !== undefined)
|
||||
await rm(testDirectory, { recursive: true, force: true });
|
||||
testDirectory = undefined;
|
||||
});
|
||||
|
||||
it("requires an explicit inferior TTY before spawning Rizin", async () => {
|
||||
let spawned = false;
|
||||
const manager = new RizinDebugSessionManager(
|
||||
{ REA_RIZIN_COMMAND: "rizin" },
|
||||
{
|
||||
spawnProcess: async () => {
|
||||
spawned = true;
|
||||
throw new Error("must not spawn");
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const result = await manager.start({ path: "/tmp/fixture.bin" } as never);
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
expect(spawned).toBe(false);
|
||||
});
|
||||
|
||||
it.skipIf(process.platform === "win32")(
|
||||
"fails the protocol when a NUL delimiter does not advance the frame parser",
|
||||
async () => {
|
||||
const injected = createInjectedProcess({
|
||||
startup: (control) => control.output(Buffer.from([0, 0])),
|
||||
});
|
||||
manager = createRizinTestManager(
|
||||
{ REA_RIZIN_COMMAND: "injected-rizin" },
|
||||
{ spawnProcess: injected.spawnProcess },
|
||||
);
|
||||
const originalIndexOf = Buffer.prototype.indexOf;
|
||||
let forcedNonAdvancingBoundary = false;
|
||||
const indexOf = vi
|
||||
.spyOn(Buffer.prototype, "indexOf")
|
||||
.mockImplementation(function (this: Buffer, value, byteOffset, encoding) {
|
||||
if (
|
||||
this.length === 2 &&
|
||||
this[0] === 0 &&
|
||||
this[1] === 0 &&
|
||||
byteOffset === 1
|
||||
) {
|
||||
forcedNonAdvancingBoundary = true;
|
||||
return 0;
|
||||
}
|
||||
return originalIndexOf.call(this, value, byteOffset, encoding);
|
||||
});
|
||||
try {
|
||||
const started = await manager.start({
|
||||
path: "/tmp/injected",
|
||||
inferior_tty: await rizinTestInferiorTty(),
|
||||
});
|
||||
expect(forcedNonAdvancingBoundary).toBe(true);
|
||||
expect(started.ok).toBe(false);
|
||||
if (!started.ok)
|
||||
expect(started.error.message).toContain(
|
||||
"frame parser failed to advance past a NUL delimiter",
|
||||
);
|
||||
} finally {
|
||||
indexOf.mockRestore();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it("declares that Rizin close can resume target code and mutate target state", () => {
|
||||
expect(TOOL_EFFECTS.close_rizin_debug_session).toMatchObject({
|
||||
mutatesTarget: true,
|
||||
executesForeignCode: true,
|
||||
});
|
||||
});
|
||||
|
||||
it.skipIf(process.platform !== "linux").each([
|
||||
{ name: "empty inferior list", response: "[]", closeSucceeds: true },
|
||||
{ name: "malformed JSON", response: "not-json", closeSucceeds: false },
|
||||
{ name: "non-array JSON", response: "{}", closeSucceeds: false },
|
||||
{
|
||||
name: "valid non-ptrace descriptor",
|
||||
response: '[{"raised":true,"fd":3,"uri":"file:///tmp/target"}]',
|
||||
closeSucceeds: true,
|
||||
},
|
||||
{
|
||||
name: "malformed descriptor row",
|
||||
response: "[null]",
|
||||
closeSucceeds: false,
|
||||
},
|
||||
{
|
||||
name: "inactive ptrace row",
|
||||
response: '[{"raised":false,"fd":3,"uri":"ptrace://1"}]',
|
||||
closeSucceeds: false,
|
||||
},
|
||||
{
|
||||
name: "malformed ptrace URI",
|
||||
response: '[{"raised":true,"fd":3,"uri":"ptrace://bad"}]',
|
||||
closeSucceeds: false,
|
||||
},
|
||||
{
|
||||
name: "multiple ptrace rows",
|
||||
response:
|
||||
'[{"raised":true,"fd":3,"uri":"ptrace://1"},{"raised":true,"fd":4,"uri":"ptrace://2"}]',
|
||||
closeSucceeds: false,
|
||||
},
|
||||
])(
|
||||
"validates Rizin `olj` close response: $name",
|
||||
async ({ response, closeSucceeds }) => {
|
||||
const tty = await rizinTestInferiorTty();
|
||||
testDirectory = await mkdtemp(join(tmpdir(), "rea-rizin-olj-"));
|
||||
const provider = join(testDirectory, "fake-rizin.cjs");
|
||||
await writeFile(
|
||||
provider,
|
||||
`#!/usr/bin/env node
|
||||
process.stdout.write("\\0");
|
||||
let oljCalls = 0;
|
||||
let input = "";
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", (chunk) => {
|
||||
input += chunk;
|
||||
for (;;) {
|
||||
const end = input.indexOf("\\n");
|
||||
if (end < 0) break;
|
||||
const line = input.slice(0, end); input = input.slice(end + 1);
|
||||
if (line === "olj") process.stdout.write((++oljCalls === 1 ? ${JSON.stringify(response)} : "[]") + "\\0");
|
||||
else if (line === "e dbg.exitkills") process.stdout.write("false\\0");
|
||||
else if (line.startsWith("!echo ")) process.stdout.write(line.slice(6) + "\\0");
|
||||
}
|
||||
});
|
||||
`,
|
||||
);
|
||||
execFileSync(process.execPath, ["--check", provider]);
|
||||
await chmod(provider, 0o700);
|
||||
manager = new RizinDebugSessionManager({ REA_RIZIN_COMMAND: provider });
|
||||
const started = await manager.start({
|
||||
path: "/tmp/fake-target",
|
||||
inferior_tty: tty,
|
||||
});
|
||||
expect(started.ok).toBe(true);
|
||||
if (!started.ok) return;
|
||||
const closed = await manager.close(started.value.session_id);
|
||||
expect(closed.ok).toBe(closeSucceeds);
|
||||
if (!closeSucceeds) {
|
||||
expect(manager.status(started.value.session_id)?.state).toBe("closed");
|
||||
await manager.closeAll();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform !== "linux").each([
|
||||
{
|
||||
name: "same descriptor remains listed after detach",
|
||||
afterDetach: (pid: number) =>
|
||||
`[{"raised":true,"fd":3,"uri":"ptrace://${pid}"}]`,
|
||||
},
|
||||
{
|
||||
name: "same inferior remains listed under a different FD",
|
||||
afterDetach: (pid: number) =>
|
||||
`[{"raised":true,"fd":4,"uri":"ptrace://${pid}"}]`,
|
||||
},
|
||||
{
|
||||
name: "an unexpected ptrace inferior remains listed",
|
||||
afterDetach: () => '[{"raised":true,"fd":4,"uri":"ptrace://999999999"}]',
|
||||
},
|
||||
])(
|
||||
"retains ownership when o- readback finds $name",
|
||||
async ({ afterDetach }) => {
|
||||
const sessionId = await startFakeInferiorSession({ afterDetach });
|
||||
await expectCloseRejectedAndReleased(sessionId);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform !== "linux")(
|
||||
"detaches a verified fake inferior before stopping the Rizin debugger",
|
||||
async () => {
|
||||
const sessionId = await startFakeInferiorSession();
|
||||
|
||||
const closed = await manager!.close(sessionId);
|
||||
|
||||
expect(closed.ok).toBe(true);
|
||||
if (!closed.ok) return;
|
||||
expect(manager!.status(sessionId)).toBeUndefined();
|
||||
expect(inferiorPid).toBeDefined();
|
||||
expect(() => process.kill(inferiorPid!, 0)).not.toThrow();
|
||||
const stat = await readFile(`/proc/${inferiorPid!}/stat`, "utf8");
|
||||
const commandEnd = stat.lastIndexOf(") ");
|
||||
expect(commandEnd).toBeGreaterThan(0);
|
||||
expect(stat.slice(commandEnd + 2).trimStart()[0]).not.toBe("Z");
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform !== "linux")(
|
||||
"refuses detach when Rizin reports dbg.exitkills=true",
|
||||
async () => {
|
||||
const sessionId = await startFakeInferiorSession({ exitKills: "true" });
|
||||
await expectCloseRejectedAndReleased(sessionId);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform !== "linux")(
|
||||
"refuses detach when the inferior stderr is not routed to the selected TTY",
|
||||
async () => {
|
||||
const sessionId = await startFakeInferiorSession({
|
||||
stderrPath: "/dev/null",
|
||||
});
|
||||
await expectCloseRejectedAndReleased(sessionId);
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform !== "linux")(
|
||||
"retains ownership when the ptrace PID has no proc identity",
|
||||
async () => {
|
||||
const sessionId = await startFakeInferiorSession({
|
||||
launchTarget: false,
|
||||
initialRows: '[{"raised":true,"fd":3,"uri":"ptrace://999999999"}]',
|
||||
startupWatchdogMs: 2_000,
|
||||
});
|
||||
await expectCloseRejectedAndReleased(sessionId);
|
||||
},
|
||||
4_000,
|
||||
);
|
||||
|
||||
it("parses Rizin's Linux proc stat start time and rejects malformed identity data", () => {
|
||||
const fields = Array.from({ length: 20 }, (_, index) => String(index + 1));
|
||||
expect(
|
||||
parseRizinProcStartTime(`123 (target ) name) ${fields.join(" ")}`),
|
||||
).toBe("20");
|
||||
expect(() => parseRizinProcStartTime("malformed stat contents")).toThrow(
|
||||
"Inferior process identity is malformed",
|
||||
);
|
||||
expect(() => parseRizinProcStartTime("123 (target) short")).toThrow(
|
||||
"Inferior process start time could not be verified",
|
||||
);
|
||||
expect(() => assertRizinProcessStartTimeStable("11", "12")).toThrow(
|
||||
"disappeared or was reused",
|
||||
);
|
||||
expect(() => assertRizinProcessStartTimeStable("11", "11")).not.toThrow();
|
||||
});
|
||||
|
||||
it.skipIf(process.platform !== "linux")(
|
||||
"retains ownership when cleanup cannot read Rizin stdin",
|
||||
async () => {
|
||||
const injected = createInjectedProcess({ stdin: "null" });
|
||||
manager = new RizinDebugSessionManager(
|
||||
{ REA_RIZIN_COMMAND: "injected-rizin" },
|
||||
{
|
||||
spawnProcess: injected.spawnProcess,
|
||||
stopProcess: async (session) => {
|
||||
try {
|
||||
await session.detachInferior?.();
|
||||
} catch {
|
||||
// This fixture verifies the manager's fail-closed read path only.
|
||||
}
|
||||
return { status: "incomplete", reason: "unreachable" };
|
||||
},
|
||||
},
|
||||
);
|
||||
const started = await manager.start({
|
||||
path: "/tmp/fake-target",
|
||||
inferior_tty: await rizinTestInferiorTty(),
|
||||
});
|
||||
expect(started.ok).toBe(true);
|
||||
if (!started.ok) return;
|
||||
expect((await manager.close(started.value.session_id)).ok).toBe(false);
|
||||
expect(manager.status(started.value.session_id)?.state).toBe("closed");
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform !== "linux")(
|
||||
"retains ownership when an internal Rizin frame is truncated",
|
||||
async () => {
|
||||
const sessionId = await startFakeInferiorSession({
|
||||
truncateCleanupFrame: true,
|
||||
maxCommandOutputBytes: 1_024,
|
||||
});
|
||||
expect((await manager!.close(sessionId)).ok).toBe(false);
|
||||
expect(manager!.status(sessionId)?.state).toBe("closed");
|
||||
await expect(manager!.closeAll()).rejects.toThrow("did not stop cleanly");
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(process.platform !== "linux")(
|
||||
"retains a verified active inferior after public command output truncation makes protocol state ambiguous",
|
||||
async () => {
|
||||
const sessionId = await startFakeInferiorSession({
|
||||
overflowPxCommand: true,
|
||||
maxCommandOutputBytes: 1_024,
|
||||
});
|
||||
let watchdog: ReturnType<typeof setTimeout> | undefined;
|
||||
const completed = await Promise.race([
|
||||
manager!.execute(sessionId, "px"),
|
||||
new Promise<never>((_, reject) => {
|
||||
watchdog = setTimeout(
|
||||
() => reject(new Error("detach watchdog expired")),
|
||||
3_000,
|
||||
);
|
||||
}),
|
||||
])
|
||||
.catch(async (error: unknown) => {
|
||||
if (providerPid !== undefined) {
|
||||
try {
|
||||
process.kill(providerPid, "SIGKILL");
|
||||
} catch {
|
||||
// The watchdog may race with provider exit.
|
||||
}
|
||||
}
|
||||
// The mutated path can leave commandTail permanently held. Prevent cleanup
|
||||
// from awaiting that same tail; afterEach still kills both child processes.
|
||||
manager = undefined;
|
||||
throw error;
|
||||
})
|
||||
.finally(() => {
|
||||
if (watchdog !== undefined) clearTimeout(watchdog);
|
||||
});
|
||||
|
||||
expect(completed.ok).toBe(false);
|
||||
if (completed.ok) return;
|
||||
expect(completed.error.cleanupIncomplete).toBe(true);
|
||||
expect(completed.error.cleanupResources).toEqual([sessionId]);
|
||||
const evidence = evidenceSchema.parse(completed.error.partialObservation);
|
||||
expect(evidence.normalized_result).toMatchObject({
|
||||
output_truncated: true,
|
||||
});
|
||||
expect(evidence.limitations.join(" ")).toContain(
|
||||
"The owned debugger session remains retained because cleanup could not be verified",
|
||||
);
|
||||
expect(manager!.status(sessionId)?.state).toBe("closed");
|
||||
},
|
||||
);
|
||||
|
||||
it.skipIf(
|
||||
process.platform !== "linux" ||
|
||||
rizinBinary === undefined ||
|
||||
!rizinAvailable(rizinBinary),
|
||||
)(
|
||||
"routes the inferior to the selected TTY and verifies detach with Rizin 0.7.4 protocol",
|
||||
async () => {
|
||||
let terminalOutput = "";
|
||||
terminal = spawn("sh", ["-c", "tty; exec sleep 60"], {
|
||||
name: "xterm",
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
encoding: "utf8",
|
||||
});
|
||||
const ttyPath = await new Promise<string>((resolve, reject) => {
|
||||
const timer = setTimeout(
|
||||
() => reject(new Error("TTY path not printed")),
|
||||
2_000,
|
||||
);
|
||||
terminal!.onData((data) => {
|
||||
terminalOutput += data;
|
||||
const match = /\/dev\/pts\/\d+/u.exec(terminalOutput);
|
||||
if (match) {
|
||||
clearTimeout(timer);
|
||||
resolve(match[0]);
|
||||
}
|
||||
});
|
||||
});
|
||||
const tty = await realpath(ttyPath);
|
||||
testDirectory = await mkdtemp(join(tmpdir(), "rea-rizin-tty-"));
|
||||
const wrapper = join(testDirectory, "rizin-with-long-lived-inferior.sh");
|
||||
const pidPath = join(testDirectory, "target.pid");
|
||||
const releasePath = join(testDirectory, "emit-output");
|
||||
const target = join(testDirectory, "target.py");
|
||||
await writeFile(
|
||||
target,
|
||||
`import os, sys, time\nopen(${JSON.stringify(pidPath)}, "w").write(str(os.getpid()))\nwhile not os.path.exists(${JSON.stringify(releasePath)}): time.sleep(0.02)\nprint("REA_RIZIN_STDOUT_MARKER", flush=True)\nprint("REA_RIZIN_STDERR_MARKER", file=sys.stderr, flush=True)\ntime.sleep(60)\n`,
|
||||
);
|
||||
await writeFile(
|
||||
wrapper,
|
||||
`#!/bin/sh\nexec ${shellQuote(rizinBinary!)} -R arg1=${target} "$@"\n`,
|
||||
);
|
||||
await chmod(wrapper, 0o700);
|
||||
manager = new RizinDebugSessionManager({ REA_RIZIN_COMMAND: wrapper });
|
||||
const started = await manager.start({
|
||||
path: "/usr/bin/python3",
|
||||
inferior_tty: tty,
|
||||
});
|
||||
expect(started.ok, started.ok ? "" : started.error.message).toBe(true);
|
||||
if (!started.ok) return;
|
||||
const closing = manager.close(started.value.session_id);
|
||||
expect((await manager.execute(started.value.session_id, "dr")).ok).toBe(
|
||||
false,
|
||||
);
|
||||
const closed = await closing;
|
||||
expect(closed.ok, closed.ok ? "" : closed.error.message).toBe(true);
|
||||
const deadline = Date.now() + 5_000;
|
||||
let pidText = "";
|
||||
while (Date.now() < deadline) {
|
||||
try {
|
||||
pidText = await readFile(pidPath, "utf8");
|
||||
break;
|
||||
} catch {
|
||||
await new Promise((resolveDelay) => setTimeout(resolveDelay, 50));
|
||||
}
|
||||
}
|
||||
inferiorPid = Number(pidText);
|
||||
expect(Number.isSafeInteger(inferiorPid) && inferiorPid > 0).toBe(true);
|
||||
expect(() => process.kill(inferiorPid!, 0)).not.toThrow();
|
||||
await writeFile(releasePath, "release after close");
|
||||
const outputDeadline = Date.now() + 3_000;
|
||||
while (
|
||||
Date.now() < outputDeadline &&
|
||||
(!terminalOutput.includes("REA_RIZIN_STDOUT_MARKER") ||
|
||||
!terminalOutput.includes("REA_RIZIN_STDERR_MARKER"))
|
||||
)
|
||||
await new Promise((resolveDelay) => setTimeout(resolveDelay, 25));
|
||||
expect(terminalOutput).toContain("REA_RIZIN_STDOUT_MARKER");
|
||||
expect(terminalOutput).toContain("REA_RIZIN_STDERR_MARKER");
|
||||
expect(() => process.kill(inferiorPid!, 0)).not.toThrow();
|
||||
},
|
||||
);
|
||||
|
||||
function findRizinBinary(): string | undefined {
|
||||
try {
|
||||
return execFileSync("which", ["rizin"], { encoding: "utf8" }).trim();
|
||||
} catch {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
function rizinAvailable(binary: string): boolean {
|
||||
try {
|
||||
return execFileSync(binary, ["-v"], { encoding: "utf8" }).includes("0.7.4");
|
||||
} catch {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
function shellQuote(value: string): string {
|
||||
return `'${value.replaceAll("'", `'\\''`)}'`;
|
||||
}
|
||||
|
||||
async function startFakeInferiorSession(
|
||||
options: {
|
||||
readonly launchTarget?: boolean;
|
||||
readonly initialRows?: string;
|
||||
readonly afterDetach?: (pid: number) => string;
|
||||
readonly exitKills?: string;
|
||||
readonly stderrPath?: string;
|
||||
readonly truncateOlj?: boolean;
|
||||
readonly truncateCleanupFrame?: boolean;
|
||||
readonly overflowPxCommand?: boolean;
|
||||
readonly startupWatchdogMs?: number;
|
||||
readonly maxCommandOutputBytes?: number;
|
||||
} = {},
|
||||
): Promise<string> {
|
||||
const tty = await realpath(await rizinTestInferiorTty());
|
||||
testDirectory = await mkdtemp(join(tmpdir(), "rea-rizin-protocol-"));
|
||||
const targetPath = join(testDirectory, "inferior.mjs");
|
||||
const pidPath = join(testDirectory, "target.pid");
|
||||
const provider = join(testDirectory, "fake-rizin.cjs");
|
||||
const launchTarget = options.launchTarget ?? true;
|
||||
await writeFile(targetPath, "setInterval(() => {}, 1000);\n");
|
||||
const initialRows = options.initialRows ?? null;
|
||||
const afterDetach = options.afterDetach ?? (() => "[]");
|
||||
const stderrPath = options.stderrPath ?? tty;
|
||||
await writeFile(
|
||||
provider,
|
||||
`#!/usr/bin/env node
|
||||
const fs = require("node:fs");
|
||||
const { spawn } = require("node:child_process");
|
||||
process.stdout.write("\\0");
|
||||
${launchTarget ? `const ttyFlags = fs.constants.O_WRONLY | fs.constants.O_NOCTTY | fs.constants.O_NONBLOCK; const stdoutFd = fs.openSync(${JSON.stringify(tty)}, ttyFlags); const stderrFd = fs.openSync(${JSON.stringify(stderrPath)}, ttyFlags); const target = spawn(process.execPath, [${JSON.stringify(targetPath)}], { detached: true, stdio: ["ignore", stdoutFd, stderrFd] }); fs.closeSync(stdoutFd); fs.closeSync(stderrFd); target.unref(); const inferiorPid = target.pid; fs.writeFileSync(${JSON.stringify(pidPath)}, String(inferiorPid));` : "const inferiorPid = 999999999;"}
|
||||
const initialRows = ${JSON.stringify(initialRows)} ?? JSON.stringify([{ raised: true, fd: 3, uri: "ptrace://" + inferiorPid }]);
|
||||
const afterDetach = ${JSON.stringify(afterDetach(inferiorPid ?? 999999999))};
|
||||
const exitKills = ${JSON.stringify(options.exitKills ?? "false")};
|
||||
const truncateOlj = ${JSON.stringify(options.truncateOlj ?? false)};
|
||||
const truncateCleanupFrame = ${JSON.stringify(options.truncateCleanupFrame ?? false)};
|
||||
const overflowPxCommand = ${JSON.stringify(options.overflowPxCommand ?? false)};
|
||||
let oljCalls = 0;
|
||||
let input = "";
|
||||
process.stdin.setEncoding("utf8");
|
||||
process.stdin.on("data", (chunk) => {
|
||||
input += chunk;
|
||||
for (;;) {
|
||||
const end = input.indexOf("\\n");
|
||||
if (end < 0) break;
|
||||
const line = input.slice(0, end); input = input.slice(end + 1);
|
||||
if (line === "olj") {
|
||||
oljCalls += 1;
|
||||
if (truncateOlj && oljCalls === 1) process.stdout.write("x".repeat(16 * 1024 * 1024 + 1) + "\\0");
|
||||
else process.stdout.write((oljCalls === 1 ? initialRows : oljCalls === 2 ? afterDetach : "[]") + "\\0");
|
||||
}
|
||||
else if (overflowPxCommand && line === "px") process.stdout.write("x".repeat(2_048) + "\\0");
|
||||
else if (line === "e dbg.exitkills") process.stdout.write(exitKills + "\\0");
|
||||
else if (line.startsWith("!echo ")) process.stdout.write((truncateCleanupFrame ? "x".repeat(2_048) : "") + line.slice(6) + "\\0");
|
||||
}
|
||||
});
|
||||
`,
|
||||
);
|
||||
await chmod(provider, 0o700);
|
||||
let providerStderr = "";
|
||||
manager = new RizinDebugSessionManager(
|
||||
{ REA_RIZIN_COMMAND: provider },
|
||||
{
|
||||
spawnProcess: async (spawnOptions) => {
|
||||
const launched = await spawnOwnedProviderProcess(spawnOptions);
|
||||
providerPid = launched.process.pid;
|
||||
if (options.startupWatchdogMs !== undefined) {
|
||||
const watchdog = spawnChild(
|
||||
process.execPath,
|
||||
[
|
||||
"-e",
|
||||
`const fs = require("node:fs"); const provider = Number(process.argv[1]); const directory = process.argv[2]; const targetFile = process.argv[3]; const delay = Number(process.argv[4]); setTimeout(() => { let target; try { target = Number(fs.readFileSync(targetFile, "utf8")); } catch {} for (const pid of [provider, target]) { if (!Number.isSafeInteger(pid) || pid <= 0) continue; try { const commandLine = fs.readFileSync("/proc/" + pid + "/cmdline", "utf8"); if (commandLine.includes(directory)) process.kill(pid, "SIGKILL"); } catch {} } }, delay);`,
|
||||
String(launched.process.pid),
|
||||
testDirectory!,
|
||||
join(testDirectory!, "target.pid"),
|
||||
String(options.startupWatchdogMs),
|
||||
],
|
||||
{ detached: true, stdio: "ignore" },
|
||||
);
|
||||
providerWatchdogPid = watchdog.pid;
|
||||
watchdog.unref();
|
||||
}
|
||||
launched.process.stderr?.on("data", (chunk) => {
|
||||
providerStderr += Buffer.from(chunk).toString("utf8");
|
||||
});
|
||||
return launched;
|
||||
},
|
||||
...(options.maxCommandOutputBytes === undefined
|
||||
? {}
|
||||
: { maxCommandOutputBytes: options.maxCommandOutputBytes }),
|
||||
},
|
||||
);
|
||||
const started = await manager.start({
|
||||
path: "/tmp/fake-target",
|
||||
inferior_tty: tty,
|
||||
});
|
||||
expect(
|
||||
started.ok,
|
||||
started.ok ? "" : `${started.error.message} ${providerStderr}`,
|
||||
).toBe(true);
|
||||
if (!started.ok) throw started.error;
|
||||
if (launchTarget) {
|
||||
let pidText: string | undefined;
|
||||
const deadline = Date.now() + 2_000;
|
||||
while (pidText === undefined && Date.now() < deadline) {
|
||||
try {
|
||||
pidText = await readFile(pidPath, "utf8");
|
||||
} catch {
|
||||
await new Promise((resolveDelay) => setTimeout(resolveDelay, 10));
|
||||
}
|
||||
}
|
||||
const parsedInferiorPid =
|
||||
pidText === undefined ? Number.NaN : Number(pidText);
|
||||
if (!Number.isSafeInteger(parsedInferiorPid) || parsedInferiorPid <= 0)
|
||||
throw new Error("The test inferior did not publish a valid PID.");
|
||||
inferiorPid = parsedInferiorPid;
|
||||
}
|
||||
return started.value.session_id;
|
||||
}
|
||||
|
||||
async function expectCloseRejectedAndReleased(
|
||||
sessionId: string,
|
||||
): Promise<void> {
|
||||
expect((await manager!.close(sessionId)).ok).toBe(false);
|
||||
expect(manager!.status(sessionId)?.state).toBe("closed");
|
||||
await manager!.closeAll();
|
||||
expect(manager!.status(sessionId)).toBeUndefined();
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
import { afterAll } from "vitest";
|
||||
import { spawn } from "@lydell/node-pty";
|
||||
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
|
||||
import { stopOwnedDebuggerProcess } from "../../../src/process/ownedDebuggerSession.js";
|
||||
|
||||
let ttyPathPromise: Promise<string> | undefined;
|
||||
let terminal: ReturnType<typeof spawn> | undefined;
|
||||
|
||||
export const rizinTestInferiorTty = (): Promise<string> => {
|
||||
if (process.platform === "win32")
|
||||
return Promise.reject(
|
||||
new Error("The Rizin test TTY requires a POSIX host."),
|
||||
);
|
||||
ttyPathPromise ??= new Promise<string>((resolve, reject) => {
|
||||
terminal = spawn("sh", ["-c", "tty; exec sleep 600"], {
|
||||
name: "xterm",
|
||||
cols: 80,
|
||||
rows: 24,
|
||||
encoding: "utf8",
|
||||
});
|
||||
let output = "";
|
||||
const timer = setTimeout(
|
||||
() => reject(new Error("test TTY path timeout")),
|
||||
2_000,
|
||||
);
|
||||
terminal.onData((chunk) => {
|
||||
output += chunk;
|
||||
const pattern =
|
||||
process.platform === "darwin"
|
||||
? /\/dev\/ttys[0-9a-z]+/u
|
||||
: /\/dev\/pts\/\d+/u;
|
||||
const match = pattern.exec(output);
|
||||
if (match !== null) {
|
||||
clearTimeout(timer);
|
||||
resolve(match[0]);
|
||||
}
|
||||
});
|
||||
});
|
||||
return ttyPathPromise;
|
||||
};
|
||||
|
||||
afterAll(() => terminal?.kill());
|
||||
|
||||
/** These fixture processes do not launch or attach an inferior. */
|
||||
export const stopFakeNoInferior = async (
|
||||
session: Parameters<typeof stopOwnedDebuggerProcess>[0],
|
||||
debuggerName: string,
|
||||
options?: Parameters<typeof stopOwnedDebuggerProcess>[2],
|
||||
) =>
|
||||
stopOwnedDebuggerProcess(
|
||||
{
|
||||
...session,
|
||||
inferiorStateUnknown: () => false,
|
||||
detachInferior: async () => ({ status: "no-inferior" }),
|
||||
},
|
||||
debuggerName,
|
||||
options,
|
||||
);
|
||||
|
||||
export const createRizinTestManager = (
|
||||
environment: Readonly<NodeJS.ProcessEnv> = process.env,
|
||||
options: ConstructorParameters<typeof RizinDebugSessionManager>[1] = {},
|
||||
): RizinDebugSessionManager =>
|
||||
new RizinDebugSessionManager(
|
||||
{ ...process.env, ...environment },
|
||||
{
|
||||
// These fake-provider tests model Linux protocol behavior independently of
|
||||
// the host running the suite. Real-provider coverage checks the host platform.
|
||||
platform: "linux",
|
||||
stopProcess: stopFakeNoInferior,
|
||||
...options,
|
||||
},
|
||||
);
|
||||
@@ -0,0 +1,45 @@
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { createRizinCommandTimeoutEvidence } from "../../../src/rizin/RizinDebugSessionManager.js";
|
||||
|
||||
it("preserves every field of partial Rizin timeout Evidence", () => {
|
||||
const result = {
|
||||
command: "dr",
|
||||
output: "partial register output",
|
||||
output_scope: "command_and_interleaved_session_output" as const,
|
||||
output_truncated: true,
|
||||
completion_status: "unknown" as const,
|
||||
backend: null,
|
||||
};
|
||||
|
||||
const evidence = createRizinCommandTimeoutEvidence({
|
||||
sessionId: "session-123",
|
||||
command: "dr",
|
||||
result,
|
||||
inferiorTty: "/dev/pts/7",
|
||||
cleanupFailure: undefined,
|
||||
launchProvenance: {
|
||||
caller_selected_path: "./sample/../program",
|
||||
resolved_path: "/workspace/program",
|
||||
},
|
||||
});
|
||||
|
||||
expect(evidence.parameters).toEqual({
|
||||
session_id: "session-123",
|
||||
command: "dr",
|
||||
inferior_tty: "/dev/pts/7",
|
||||
launch_provenance: {
|
||||
caller_selected_path: "./sample/../program",
|
||||
resolved_path: "/workspace/program",
|
||||
},
|
||||
});
|
||||
expect(evidence.raw_result).toEqual(result);
|
||||
expect(evidence.normalized_result).toEqual(result);
|
||||
expect(evidence.limitations).toEqual([
|
||||
"The current debugger target identity is not established by the Rizin session identifier.",
|
||||
"The command timed out before its completion marker; retained output is partial and completion is unknown.",
|
||||
"The owned debugger session was stopped because output correlation could no longer be guaranteed.",
|
||||
"The command is unrestricted and may access local files, the shell, network, or mutate the target.",
|
||||
"Launch provenance records the original and resolved startup paths; it does not establish the current target after unrestricted debugger commands.",
|
||||
]);
|
||||
});
|
||||
@@ -47,9 +47,12 @@ const fixture = async (duringCollection?: (root: string) => Promise<void>) => {
|
||||
let reportedPath = "";
|
||||
vi.mocked(execFileOutput).mockImplementation(async (_binary, args) => {
|
||||
expect(args).toEqual(["version"]);
|
||||
const stdout = `Android Debug Bridge version 1.0.41\nVersion 34.0.5-stub\nInstalled as ${binary}\n`;
|
||||
return {
|
||||
stdout: `Android Debug Bridge version 1.0.41\nVersion 34.0.5-stub\nInstalled as ${binary}\n`,
|
||||
stdout,
|
||||
stderr: "",
|
||||
stdoutBytes: Buffer.byteLength(stdout),
|
||||
stderrBytes: 0,
|
||||
};
|
||||
});
|
||||
vi.mocked(execFileBytes).mockImplementation(async (_binary, args) => {
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
import { execFileSync } from "node:child_process";
|
||||
import { chmod, mkdtemp, rm } from "node:fs/promises";
|
||||
import { tmpdir } from "node:os";
|
||||
import { join, resolve } from "node:path";
|
||||
|
||||
import { expect, it } from "vitest";
|
||||
|
||||
import { CutterBridgeClient } from "../../../src/cutter/CutterBridgeClient.js";
|
||||
import { CutterBridgeService } from "../../../src/cutter/CutterBridgeService.js";
|
||||
import {
|
||||
createTestProcessRegistry,
|
||||
waitForExit,
|
||||
} from "../../../tests/support/process/processFixture.js";
|
||||
|
||||
const startPythonBridge = async () => {
|
||||
const directory = await mkdtemp(join(tmpdir(), "rea-cutter-receipt-"));
|
||||
await chmod(directory, 0o700);
|
||||
const processes = createTestProcessRegistry();
|
||||
const child = processes.spawn(
|
||||
"python3",
|
||||
[resolve("tests/fixtures/cutter_bridge_protocol_test.py"), "--serve"],
|
||||
{ env: { ...process.env, REA_CUTTER_BRIDGE_DIR: directory } },
|
||||
);
|
||||
let stdout = "";
|
||||
let stderr = "";
|
||||
child.stdout.setEncoding("utf8");
|
||||
child.stderr.setEncoding("utf8");
|
||||
child.stdout.on("data", (chunk: string) => {
|
||||
stdout += chunk;
|
||||
});
|
||||
child.stderr.on("data", (chunk: string) => {
|
||||
stderr += chunk;
|
||||
});
|
||||
try {
|
||||
await new Promise<void>((resolveReady, rejectReady) => {
|
||||
const timeout = setTimeout(
|
||||
() =>
|
||||
rejectReady(
|
||||
new Error(`Python bridge did not become ready: ${stderr}`),
|
||||
),
|
||||
5_000,
|
||||
);
|
||||
const onData = (_chunk: string): void => {
|
||||
if (!stdout.includes("ready\n")) return;
|
||||
clearTimeout(timeout);
|
||||
child.stdout.off("data", onData);
|
||||
resolveReady();
|
||||
};
|
||||
child.stdout.on("data", onData);
|
||||
child.once("error", (error) => {
|
||||
clearTimeout(timeout);
|
||||
rejectReady(error);
|
||||
});
|
||||
child.once("exit", (code, signal) => {
|
||||
if (stdout.includes("ready\n")) return;
|
||||
clearTimeout(timeout);
|
||||
rejectReady(
|
||||
new Error(
|
||||
`Python bridge exited before ready (${code ?? signal}): ${stderr}`,
|
||||
),
|
||||
);
|
||||
});
|
||||
if (stdout.includes("ready\n")) onData("");
|
||||
});
|
||||
const client = new CutterBridgeClient({
|
||||
...process.env,
|
||||
REA_CUTTER_BRIDGE_DIR: directory,
|
||||
});
|
||||
const discovery = await client.listSessions();
|
||||
const session = discovery.sessions[0];
|
||||
if (session === undefined) throw new Error("Python bridge session missing");
|
||||
return {
|
||||
client,
|
||||
directory,
|
||||
session,
|
||||
stderr: () => stderr,
|
||||
async close(): Promise<void> {
|
||||
child.stdin.end("shutdown\n");
|
||||
const exited = await waitForExit(child, 3_000);
|
||||
try {
|
||||
await processes.shutdown();
|
||||
} finally {
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
}
|
||||
if (!exited) throw new Error(`Python bridge did not exit: ${stderr}`);
|
||||
},
|
||||
};
|
||||
} catch (error) {
|
||||
child.stdin.end("shutdown\n");
|
||||
await waitForExit(child, 3_000);
|
||||
await processes.shutdown();
|
||||
await rm(directory, { recursive: true, force: true });
|
||||
throw error;
|
||||
}
|
||||
};
|
||||
|
||||
it("authenticates bridge peers before payloads and permits status recovery after a poisoned UI timeout", () => {
|
||||
execFileSync(
|
||||
"python3",
|
||||
[resolve("tests/fixtures/cutter_bridge_protocol_test.py")],
|
||||
{
|
||||
encoding: "utf8",
|
||||
timeout: 10_000,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
it("round-trips authenticated status and command bytes across the Python producer boundary", async () => {
|
||||
const bridge = await startPythonBridge();
|
||||
try {
|
||||
const { client, session } = bridge;
|
||||
expect(session.document_generation).toBe(4);
|
||||
expect(session.current_file).toBe("/tmp/cutter-interop-雪.bin");
|
||||
|
||||
for (let index = 0; index <= 64; index += 1) {
|
||||
await expect(
|
||||
client.execute({
|
||||
sessionId: session.session_id,
|
||||
expectedGeneration: 3,
|
||||
command: "iI",
|
||||
json: false,
|
||||
}),
|
||||
).rejects.toThrow("List sessions again");
|
||||
}
|
||||
|
||||
const result = await client.execute({
|
||||
sessionId: session.session_id,
|
||||
expectedGeneration: session.document_generation,
|
||||
command: 'print("雪 ☃️ \\\"quoted\\\" \\\\ slash\\nline\\ttab")',
|
||||
json: false,
|
||||
});
|
||||
expect(result.output).toBe(
|
||||
'round-trip: 雪 ☃️ quote=" slash=\\\\ line=\\n tab=\\t',
|
||||
);
|
||||
expect(result.executionState).toBe("complete");
|
||||
expect(result.documentGeneration).toBe(4);
|
||||
expect(result.currentFile).toBe("/tmp/cutter-interop-雪.bin");
|
||||
expect(result.outputTruncated).toBe(false);
|
||||
} finally {
|
||||
await bridge.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("preserves caller A service cleanup proof after caller B acknowledges A", async () => {
|
||||
const bridge = await startPythonBridge();
|
||||
try {
|
||||
const commandInput = {
|
||||
session_id: bridge.session.session_id,
|
||||
expected_generation: bridge.session.document_generation,
|
||||
command: "fixture-unknown",
|
||||
json: false,
|
||||
};
|
||||
const callerA = new CutterBridgeService(bridge.client);
|
||||
const executionA = await callerA.execute(commandInput);
|
||||
expect(executionA).toMatchObject({
|
||||
ok: false,
|
||||
error: { cleanupIncomplete: true },
|
||||
});
|
||||
|
||||
const callerB = new CutterBridgeService(
|
||||
new CutterBridgeClient({
|
||||
...process.env,
|
||||
REA_CUTTER_BRIDGE_DIR: bridge.directory,
|
||||
}),
|
||||
);
|
||||
await expect(
|
||||
callerB.execute({
|
||||
...commandInput,
|
||||
command: "iI",
|
||||
json: false,
|
||||
}),
|
||||
).resolves.toMatchObject({ ok: true });
|
||||
await expect(callerA.retryCleanup()).resolves.toEqual({
|
||||
ok: true,
|
||||
value: null,
|
||||
});
|
||||
await expect(
|
||||
callerA.execute({ ...commandInput, command: "iI" }),
|
||||
).resolves.toMatchObject({ ok: true });
|
||||
} finally {
|
||||
await bridge.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("recovers orphan receipts across more than 64 fresh CLI clients", async () => {
|
||||
const bridge = await startPythonBridge();
|
||||
try {
|
||||
for (let index = 0; index < 65; index += 1) {
|
||||
const freshClient = new CutterBridgeClient({
|
||||
...process.env,
|
||||
REA_CUTTER_BRIDGE_DIR: bridge.directory,
|
||||
});
|
||||
const execution = await freshClient.execute({
|
||||
sessionId: bridge.session.session_id,
|
||||
expectedGeneration: bridge.session.document_generation,
|
||||
command: "fixture-unknown",
|
||||
json: false,
|
||||
});
|
||||
expect(execution.executionState, `orphan ${index}`).toBe("unknown");
|
||||
}
|
||||
const nextInvocation = new CutterBridgeClient({
|
||||
...process.env,
|
||||
REA_CUTTER_BRIDGE_DIR: bridge.directory,
|
||||
});
|
||||
await expect(
|
||||
nextInvocation.execute({
|
||||
sessionId: bridge.session.session_id,
|
||||
expectedGeneration: bridge.session.document_generation,
|
||||
command: "iI",
|
||||
json: false,
|
||||
}),
|
||||
).resolves.toMatchObject({ executionState: "complete" });
|
||||
} finally {
|
||||
await bridge.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("retains failed receipt acknowledgements and retries before another command", async () => {
|
||||
const bridge = await startPythonBridge();
|
||||
try {
|
||||
await expect(
|
||||
bridge.client.execute({
|
||||
sessionId: bridge.session.session_id,
|
||||
expectedGeneration: bridge.session.document_generation,
|
||||
command: "fixture-fail-ack",
|
||||
json: false,
|
||||
}),
|
||||
).resolves.toMatchObject({ executionState: "complete" });
|
||||
await expect(
|
||||
bridge.client.execute({
|
||||
sessionId: bridge.session.session_id,
|
||||
expectedGeneration: bridge.session.document_generation,
|
||||
command: "iI",
|
||||
json: false,
|
||||
}),
|
||||
).resolves.toMatchObject({ executionState: "complete" });
|
||||
} finally {
|
||||
await bridge.close();
|
||||
}
|
||||
});
|
||||
|
||||
it("retains a receipt when an ACK reply omits its acknowledgement field", async () => {
|
||||
const bridge = await startPythonBridge();
|
||||
try {
|
||||
await expect(
|
||||
bridge.client.execute({
|
||||
sessionId: bridge.session.session_id,
|
||||
expectedGeneration: bridge.session.document_generation,
|
||||
command: "fixture-malformed-ack",
|
||||
json: false,
|
||||
}),
|
||||
).resolves.toMatchObject({ executionState: "complete" });
|
||||
await expect(
|
||||
bridge.client.execute({
|
||||
sessionId: bridge.session.session_id,
|
||||
expectedGeneration: bridge.session.document_generation,
|
||||
command: "iI",
|
||||
json: false,
|
||||
}),
|
||||
).resolves.toMatchObject({ executionState: "complete" });
|
||||
} finally {
|
||||
await bridge.close();
|
||||
}
|
||||
});
|
||||
@@ -0,0 +1,16 @@
|
||||
import { expect } from "vitest";
|
||||
|
||||
import type { GdbSessionManager } from "../../../src/gdb/GdbSessionManager.js";
|
||||
|
||||
type GdbSessionStart = Awaited<ReturnType<GdbSessionManager["start"]>>;
|
||||
type StartedGdbSession = Extract<GdbSessionStart, { readonly ok: true }>;
|
||||
|
||||
export const expectGdbSessionStarted = async (
|
||||
manager: GdbSessionManager,
|
||||
...arguments_: Parameters<GdbSessionManager["start"]>
|
||||
): Promise<StartedGdbSession> => {
|
||||
const started = await manager.start(...arguments_);
|
||||
expect(started.ok).toBe(true);
|
||||
if (!started.ok) throw new Error(started.error.message);
|
||||
return started;
|
||||
};
|
||||
@@ -42,7 +42,7 @@ it("retains the delayed dependency in the complete real framed otool output", as
|
||||
|
||||
it("rejects a repeated options field even when the duplicate has no value", async () => {
|
||||
const output = (await nativeFixture("otool-dylib-use.txt")).replace(
|
||||
" options delay-init ",
|
||||
" options delay-init",
|
||||
" options delay-init\n options",
|
||||
);
|
||||
expect(() => parseOtoolLoadCommands(output)).toThrow(/otool/u);
|
||||
|
||||
Reference in New Issue
Block a user