Skip to content

Commit 1d1dd75

Browse files
dandgabrclaude
andcommitted
fix(debuggers): retain cancelled-command cleanup and bound Rizin evidence
- GDB: a cancelled command whose owned shutdown is incomplete, or whose shutdown attempt rejects, now keeps its cleanup failure on the session so a later close resolves it instead of leaving an untracked error. - Rizin: failed-startup captured output reports `output_invalid_utf8`. - Rizin: recent-frame truncation is bounded in UTF-8 bytes, not UTF-16 units. - Rizin: persistent command text rejects NUL, which is the frame delimiter. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
1 parent da4d7d8 commit 1d1dd75

6 files changed

Lines changed: 174 additions & 24 deletions

File tree

‎src/contracts/rizinDebugToolContracts.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -53,6 +53,10 @@ export const RIZIN_DEBUG_TOOL_CONTRACTS = [
5353
.refine(
5454
(value) => !/[\r\n]/u.test(value),
5555
"A single command line is required",
56+
)
57+
.refine(
58+
(value) => !value.includes("\0"),
59+
"NUL bytes are not allowed because Rizin frames its output with NUL",
5660
),
5761
}),
5862
outputSchema: evidenceResultOf(commandResult),

‎src/domain/analysisErrorBase.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -41,6 +41,8 @@ export interface AnalysisCapturedOutput {
4141
readonly truncated: boolean;
4242
readonly stdout_bytes?: number;
4343
readonly stderr_bytes?: number;
44+
/** Present when decoded text replaced bytes that were not valid UTF-8. */
45+
readonly output_invalid_utf8?: true;
4446
readonly exit_code?: number | null;
4547
readonly signal?: string | null;
4648
}

‎src/gdb/GdbSessionManager.ts‎

Lines changed: 21 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -1853,29 +1853,33 @@ export class GdbSessionManager {
18531853
session.pending.delete(token);
18541854
session.protocolError =
18551855
"A GDB MI command was cancelled; owned-session shutdown was requested because output correlation can no longer be guaranteed.";
1856+
const retainCancellation = (reason: string, cause: unknown): void => {
1857+
const failure = new AnalysisCancelledError("gdb_console", {
1858+
cause,
1859+
cleanup: { reason, resources: [session.id] },
1860+
partialObservation: evidence,
1861+
});
1862+
// The owned process may still be running; keep its cleanup owner
1863+
// attached to the session so a later close or retry can resolve it.
1864+
session.cleanupFailures.add(failure);
1865+
pending.reject(failure);
1866+
};
18561867
void this.#stopDebuggerOnly(session).then(
18571868
(stopped) => {
1858-
pending.reject(
1859-
stopped.status === "incomplete"
1860-
? new AnalysisCancelledError("gdb_console", {
1861-
cause: new Error(stopped.reason),
1862-
cleanup: {
1863-
reason: stopped.reason,
1864-
resources: [session.id],
1865-
},
1866-
partialObservation: evidence,
1867-
})
1868-
: new AnalysisCancelledError("gdb_console", {
1869-
partialObservation: evidence,
1870-
}),
1871-
);
1872-
},
1873-
(cause: unknown) =>
1869+
if (stopped.status === "incomplete") {
1870+
retainCancellation(stopped.reason, new Error(stopped.reason));
1871+
return;
1872+
}
18741873
pending.reject(
18751874
new AnalysisCancelledError("gdb_console", {
1876-
cause,
18771875
partialObservation: evidence,
18781876
}),
1877+
);
1878+
},
1879+
(cause: unknown) =>
1880+
retainCancellation(
1881+
cause instanceof Error ? cause.message : String(cause),
1882+
cause,
18791883
),
18801884
);
18811885
};

‎src/rizin/RizinDebugSessionManager.ts‎

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1050,13 +1050,12 @@ export class RizinDebugSessionManager {
10501050

10511051
#startupCapturedOutput(session: RizinDebugSession) {
10521052
const output = session.supervisor.snapshot();
1053-
const partialFrame =
1053+
const partialBytes =
10541054
session.bufferedFrameBytes === 0
1055-
? ""
1056-
: Buffer.concat(
1057-
session.frameChunks,
1058-
session.bufferedFrameBytes,
1059-
).toString("utf8");
1055+
? Buffer.alloc(0)
1056+
: Buffer.concat(session.frameChunks, session.bufferedFrameBytes);
1057+
const partialFrame = partialBytes.toString("utf8");
1058+
const invalidUtf8 = session.invalidUtf8Observed || !isUtf8(partialBytes);
10601059
const protocolOutput = [...session.history, partialFrame]
10611060
.filter((frame) => frame.length > 0)
10621061
.join("\n");
@@ -1071,6 +1070,7 @@ export class RizinDebugSessionManager {
10711070
return {
10721071
stdout: protocolBytes.subarray(0, stdoutBytes).toString("utf8"),
10731072
stderr: output.stderr.text,
1073+
...(invalidUtf8 ? { output_invalid_utf8: true as const } : {}),
10741074
truncated:
10751075
session.historyTruncated ||
10761076
protocolBytes.length > stdoutBytes ||
@@ -1087,7 +1087,7 @@ export class RizinDebugSessionManager {
10871087
): void {
10881088
const historyFrame =
10891089
frameBytes > MAX_RECENT_FRAME_BYTES || frame.truncated
1090-
? `${frame.text.slice(0, MAX_RECENT_FRAME_BYTES)}[recent frame truncated]`
1090+
? `${truncateUtf8(frame.text, MAX_RECENT_FRAME_BYTES)}[recent frame truncated]`
10911091
: frame.text;
10921092
if (frameBytes > MAX_RECENT_FRAME_BYTES || frame.truncated)
10931093
session.historyTruncated = true;

‎tests/boundary/providers/GdbSessionReviewRegressions.test.ts‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1202,3 +1202,68 @@ setTimeout(() => process.exit(0), 250);
12021202
}
12031203
},
12041204
);
1205+
1206+
it.skipIf(process.platform === "win32")(
1207+
"keeps a cancelled command's cleanup failure owned until the session stops",
1208+
async () => {
1209+
directory = await mkdtemp(join(tmpdir(), "rea-gdb-cancel-cleanup-owner-"));
1210+
const provider = join(directory, "fake-gdb-cancel-cleanup-owner.mjs");
1211+
await writeFile(
1212+
provider,
1213+
`#!${process.execPath}
1214+
process.stdout.write("(gdb)\\n");
1215+
let input = "";
1216+
process.stdin.setEncoding("utf8");
1217+
process.stdin.on("data", (chunk) => {
1218+
input += chunk;
1219+
for (;;) {
1220+
const boundary = input.indexOf("\\n");
1221+
if (boundary < 0) break;
1222+
const line = input.slice(0, boundary); input = input.slice(boundary + 1);
1223+
const match = /^(\\d+)/.exec(line); if (!match) continue;
1224+
if (line.includes("auto-load off")) process.stdout.write(match[1] + "^done\\n");
1225+
}
1226+
});
1227+
setTimeout(() => process.exit(0), 250);
1228+
`,
1229+
);
1230+
await chmod(provider, 0o700);
1231+
let stopCalls = 0;
1232+
const manager = createGdbManagerForInjectedPlatform({
1233+
environment: { REA_GDB_COMMAND: provider },
1234+
stopProcess: async () => {
1235+
stopCalls += 1;
1236+
if (stopCalls === 1)
1237+
throw new Error("simulated unexpected shutdown rejection");
1238+
return { status: "stopped" };
1239+
},
1240+
});
1241+
managers.push(manager);
1242+
const started = await manager.start();
1243+
expect(started.ok).toBe(true);
1244+
if (!started.ok) return;
1245+
const controller = new AbortController();
1246+
const execution = manager.execute(
1247+
started.value.session_id,
1248+
"shell sleep 600",
1249+
controller.signal,
1250+
);
1251+
await new Promise((resolveDelay) => setTimeout(resolveDelay, 30));
1252+
controller.abort();
1253+
1254+
const cancelled = await execution;
1255+
1256+
expect(cancelled.ok).toBe(false);
1257+
if (cancelled.ok) return;
1258+
expect(cancelled.error._tag).toBe("AnalysisCancelledError");
1259+
expect(cancelled.error.cleanup?.reason).toContain(
1260+
"simulated unexpected shutdown rejection",
1261+
);
1262+
expect(cancelled.error.cleanupIncomplete).toBe(true);
1263+
1264+
const closed = await manager.close(started.value.session_id);
1265+
1266+
expect(closed.ok).toBe(true);
1267+
expect(cancelled.error.cleanupIncomplete).toBe(false);
1268+
},
1269+
);

‎tests/boundary/providers/RizinDebugSessionReviewRegressions.test.ts‎

Lines changed: 75 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { join } from "node:path";
66

77
import { afterEach, expect, it } from "vitest";
88

9+
import { RIZIN_DEBUG_TOOL_CONTRACTS } from "../../../src/contracts/rizinDebugToolContracts.js";
910
import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js";
1011
import {
1112
spawnOwnedProviderProcess,
@@ -892,3 +893,77 @@ process.stdin.on("data", (chunk) => {
892893
process.kill(writerPid, "SIGKILL");
893894
},
894895
);
896+
897+
it.skipIf(process.platform === "win32")(
898+
"reports invalid UTF-8 in failed Rizin startup output",
899+
async () => {
900+
const injected = createInjectedProcess({
901+
startup: (control) => {
902+
control.output(Buffer.from([0x61, 0xff, 0x00, 0x62, 0xfe]));
903+
control.exit();
904+
},
905+
});
906+
const manager = createRizinTestManager(
907+
{ REA_RIZIN_COMMAND: "injected-rizin" },
908+
{ spawnProcess: injected.spawnProcess },
909+
);
910+
managers.push(manager);
911+
912+
const started = await manager.start({
913+
path: "/tmp/fixture.bin",
914+
inferior_tty: await rizinTestInferiorTty(),
915+
});
916+
917+
expect(started.ok).toBe(false);
918+
if (!started.ok)
919+
expect(started.error.capturedOutput).toMatchObject({
920+
output_invalid_utf8: true,
921+
});
922+
},
923+
);
924+
925+
it.skipIf(process.platform === "win32")(
926+
"bounds recent Rizin frames by UTF-8 bytes rather than UTF-16 units",
927+
async () => {
928+
const injected = createInjectedProcess();
929+
const manager = createRizinTestManager(
930+
{ REA_RIZIN_COMMAND: "injected-rizin" },
931+
{ spawnProcess: injected.spawnProcess },
932+
);
933+
managers.push(manager);
934+
const started = await manager.start({
935+
path: "/tmp/fixture.bin",
936+
inferior_tty: await rizinTestInferiorTty(),
937+
});
938+
expect(started.ok).toBe(true);
939+
if (!started.ok) return;
940+
941+
// 9000 two-byte characters: under 16 KiB as UTF-16 units, over it as bytes.
942+
injected.control.output(Buffer.from(`${"é".repeat(9000)}\0`, "utf8"));
943+
944+
const status = manager.status(started.value.session_id);
945+
const recent = status?.recent_output.at(-1) ?? "";
946+
const marker = "[recent frame truncated]";
947+
expect(status?.recent_output_truncated).toBe(true);
948+
expect(recent.endsWith(marker)).toBe(true);
949+
expect(
950+
Buffer.byteLength(recent.slice(0, -marker.length), "utf8"),
951+
).toBeLessThanOrEqual(16 * 1024);
952+
},
953+
);
954+
955+
it("rejects NUL in persistent Rizin command text", () => {
956+
const contract = RIZIN_DEBUG_TOOL_CONTRACTS.find(
957+
(candidate) => candidate.name === "rizin_debug_command",
958+
);
959+
const input = {
960+
session_id: "00000000-0000-4000-8000-000000000001",
961+
};
962+
963+
expect(
964+
contract?.inputSchema.safeParse({ ...input, command: "dr" }).success,
965+
).toBe(true);
966+
expect(
967+
contract?.inputSchema.safeParse({ ...input, command: "dr\0px" }).success,
968+
).toBe(false);
969+
});

0 commit comments

Comments
 (0)