Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(rizin): bound recent history frames by UTF-8 byte budget (#5246)

NoThing1b3ac9424288
diff --git a/docs/reverse-engineering-tools.md b/docs/reverse-engineering-tools.md
index fea7b3224..7bbb5852f 100644
--- a/docs/reverse-engineering-tools.md
+++ b/docs/reverse-engineering-tools.md
@@ -49,6 +49,8 @@ close_gdb_session {"session_id":"…"}
Persistent command Evidence retains the caller-selected and resolved startup paths in `parameters.launch_provenance`. These paths describe launch provenance, not the current target after unrestricted commands. `rizin_debug_session_status.output_invalid_utf8` reports whether lossy frame decoding has been observed during the session. Command Evidence sets `output_invalid_utf8` only when loss was observed in frames collected for that command, including retained partial output; earlier startup or command frames do not mark later valid output as lossy.
+Session status retains up to 64 recent protocol frames. Each history entry keeps a complete-character UTF-8 prefix of at most 16 KiB, plus a truncation marker when needed; `recent_output_truncated` reports omitted history. This history budget also accounts for replacement characters from invalid UTF-8. It does not shorten command Evidence, which has its own 16 MiB output budget.
+
```sh
rea debug-with-rizin --inferior-tty /dev/pts/7 ./program dr
```
diff --git a/src/rizin/RizinDebugSessionManager.ts b/src/rizin/RizinDebugSessionManager.ts
index a8bc54894..3e742a6a1 100644
--- a/src/rizin/RizinDebugSessionManager.ts
+++ b/src/rizin/RizinDebugSessionManager.ts
@@ -1041,20 +1041,13 @@ export class RizinDebugSessionManager {
const protocolOutput = [...session.history, partialFrame]
.filter((frame) => frame.length > 0)
.join("\n");
- const protocolBytes = Buffer.from(protocolOutput, "utf8");
- let stdoutBytes = Math.min(protocolBytes.length, MAX_DIAGNOSTIC_BYTES);
- while (
- stdoutBytes > 0 &&
- stdoutBytes < protocolBytes.length &&
- (protocolBytes[stdoutBytes]! & 0xc0) === 0x80
- )
- stdoutBytes -= 1;
+ const stdout = truncateUtf8(protocolOutput, MAX_DIAGNOSTIC_BYTES);
return {
- stdout: protocolBytes.subarray(0, stdoutBytes).toString("utf8"),
+ stdout,
stderr: output.stderr.text,
truncated:
session.historyTruncated ||
- protocolBytes.length > stdoutBytes ||
+ protocolOutput.length > stdout.length ||
output.diagnosticTruncated === true ||
output.stdout.observedBytes > output.stdout.bytes ||
output.stderr.observedBytes > output.stderr.bytes,
@@ -1066,13 +1059,15 @@ export class RizinDebugSessionManager {
frame: RizinFrame,
frameBytes: number,
): void {
- const historyFrame =
- frameBytes > MAX_RECENT_FRAME_BYTES || frame.truncated
- ? `${frame.text.slice(0, MAX_RECENT_FRAME_BYTES)}[recent frame truncated]`
- : frame.text;
- if (frameBytes > MAX_RECENT_FRAME_BYTES || frame.truncated)
- session.historyTruncated = true;
- session.history.push(historyFrame);
+ const historyPrefix = truncateUtf8(frame.text, MAX_RECENT_FRAME_BYTES);
+ const historyTruncated =
+ historyPrefix.length < frame.text.length || frame.truncated;
+ if (historyTruncated) session.historyTruncated = true;
+ session.history.push(
+ historyTruncated
+ ? `${historyPrefix}[recent frame truncated]`
+ : historyPrefix,
+ );
if (session.history.length > 64) {
session.history.splice(0, session.history.length - 64);
session.historyTruncated = true;
@@ -1548,11 +1543,11 @@ const waitForCommandFrames = async (
const truncateUtf8 = (value: string, maximumBytes: number): string => {
if (maximumBytes <= 0) return "";
- const bytes = Buffer.from(value, "utf8");
- let end = Math.min(bytes.length, maximumBytes);
- while (end > 0 && end < bytes.length && (bytes[end]! & 0xc0) === 0x80)
- end -= 1;
- return bytes.subarray(0, end).toString("utf8");
+ // A UTF-16 code unit needs at most three UTF-8 bytes. Buffer.write stops
+ // before a partial character; only decode bytes it actually initialized.
+ const bytes = Buffer.allocUnsafe(Math.min(value.length * 3, maximumBytes));
+ const written = bytes.write(value, "utf8");
+ return bytes.toString("utf8", 0, written);
};
const waitForFrame = (
diff --git a/tests/boundary/providers/RizinDebugSessionCoverage.part4.test.ts b/tests/boundary/providers/RizinDebugSessionCoverage.part4.test.ts
index 11e68e3e6..838298976 100644
--- a/tests/boundary/providers/RizinDebugSessionCoverage.part4.test.ts
+++ b/tests/boundary/providers/RizinDebugSessionCoverage.part4.test.ts
@@ -70,6 +70,12 @@ it.skipIf(process.platform === "win32")(
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);
+ expect(manager.status(started.value.session_id)).toMatchObject({
+ recent_output_truncated: true,
+ recent_output: expect.arrayContaining([
+ "a".repeat(16384) + "[recent frame truncated]",
+ ]),
+ });
},
);
@@ -85,17 +91,107 @@ it.skipIf(process.platform === "win32")(
},
);
-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);',
+it.skipIf(process.platform === "win32").each([
+ { name: "empty", bytes: Buffer.alloc(0), prefix: "", truncated: false },
+ {
+ name: "short CJK",
+ bytes: Buffer.from("雪".repeat(10)),
+ prefix: "雪".repeat(10),
+ truncated: false,
+ },
+ {
+ name: "exact ASCII budget",
+ bytes: Buffer.from("a".repeat(16384)),
+ prefix: "a".repeat(16384),
+ truncated: false,
+ },
+ {
+ name: "oversized ASCII",
+ bytes: Buffer.from("a".repeat(17000)),
+ prefix: "a".repeat(16384),
+ truncated: true,
+ },
+ {
+ name: "two-byte boundary",
+ bytes: Buffer.from("a".repeat(16383) + "é"),
+ prefix: "a".repeat(16383),
+ truncated: true,
+ },
+ {
+ name: "oversized CJK",
+ bytes: Buffer.from("雪".repeat(20000)),
+ prefix: "雪".repeat(5461),
+ truncated: true,
+ },
+ {
+ name: "split emoji boundary",
+ bytes: Buffer.from("a".repeat(16383) + "😀" + "x".repeat(100)),
+ prefix: "a".repeat(16383),
+ truncated: true,
+ },
+ {
+ name: "complete emoji boundary",
+ bytes: Buffer.from("a".repeat(16380) + "😀" + "x"),
+ prefix: "a".repeat(16380) + "😀",
+ truncated: true,
+ },
+ {
+ name: "invalid UTF-8 expansion below the wire budget",
+ bytes: Buffer.alloc(6000, 0xff),
+ prefix: "\uFFFD".repeat(5461),
+ truncated: true,
+ invalidUtf8: true,
+ },
+])(
+ "bounds $name history while preserving complete command Evidence",
+ async ({ bytes, prefix, truncated, ...flags }) => {
+ const injected = createInjectedProcess({
+ onWrite: (text, control) => {
+ const marker = /!echo (.+)\n/u.exec(text)?.[1];
+ if (marker === undefined) return;
+ setImmediate(() => {
+ control.output(bytes);
+ control.output(Buffer.from([0]));
+ control.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,
+ "history-fixture",
+ );
+ expect(result.ok).toBe(true);
+ if (!result.ok) return;
+ const expected = {
+ output: bytes.toString("utf8"),
+ output_truncated: false,
+ completion_status: "complete",
+ };
+ expect(result.value.evidence).toMatchObject({
+ normalized_result: expected,
+ raw_result: expected,
+ });
+ expect(result.value.result.output_invalid_utf8).toBe(
+ "invalidUtf8" in flags ? true : undefined,
+ );
+
+ // Exercise unsolicited frames too, without relying on child scheduling.
+ injected.control.output(bytes);
+ injected.control.output(Buffer.from([0]));
+ const status = manager.status(started.value.session_id);
+ expect(status?.recent_output_truncated).toBe(truncated);
+ expect(status?.output_invalid_utf8).toBe("invalidUtf8" in flags);
+ const retained = status?.recent_output.at(-1);
+ expect(retained).toBe(
+ prefix + (truncated ? "[recent frame truncated]" : ""),
+ );
+ expect(Buffer.byteLength(retained ?? "", "utf8")).toBeLessThanOrEqual(
+ 16 * 1024 + 24,
);
- 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]");
},
);