Reverse engineer anything with agents, from app behavior down to native binaries.
TypeScript agent-skillsai-agentsbinary-analysisclaude-codeclicodexcordisdecompilerdeveloper-toolsdshdsh-pluginghidrahopperllmmcpmodel-context-protocolreareverse-engineeringstatic-analysistouhou
fix(rizin): accept proven inferior exit after detach (#5281)
gensokyo-deve84e17e30f7d
diff --git a/docs/reverse-engineering-tools.md b/docs/reverse-engineering-tools.mdindex 7bbb5852f..5b0793aca 100644--- a/docs/reverse-engineering-tools.md+++ b/docs/reverse-engineering-tools.md@@ -45,7 +45,7 @@ close_gdb_session {"session_id":"…"}## Rizin-`start_rizin_debug_session` and `rea debug-with-rizin` require an explicit `inferior_tty` on Linux. Rizin launches the target with stdout and stderr routed to that caller-selected TTY and `dbg.exitkills=false`; the target can therefore continue running and writing to the TTY after REA closes the debugger. This is a visible target output effect, and the caller is responsible for selecting a suitable terminal that remains available. Before closing, REA serializes after the active command, parses the structured `olj` descriptor list, detaches only a unique `ptrace://` descriptor, confirms its absence, reads back `dbg.exitkills=false`, and verifies `/proc/<pid>/fd/1` and `/proc/<pid>/fd/2` still identify the selected TTY by device and inode. Any malformed or ambiguous readback keeps the Rizin session owned for retry. Persistent Rizin debugger sessions are unavailable outside Linux because this verification depends on `/proc`.+`start_rizin_debug_session` and `rea debug-with-rizin` require an explicit `inferior_tty` on Linux. Rizin launches the target with stdout and stderr routed to that caller-selected TTY and `dbg.exitkills=false`; the target can therefore continue running and writing to the TTY after REA closes the debugger. This is a visible target output effect, and the caller is responsible for selecting a suitable terminal that remains available. Before closing, REA serializes after the active command, parses the structured `olj` descriptor list, detaches only a unique `ptrace://` descriptor, confirms its absence, reads back `dbg.exitkills=false`, and verifies `/proc/<pid>/fd/1` and `/proc/<pid>/fd/2` still identify the selected TTY by device and inode. If a previously identified inferior exits after Rizin confirms detach, REA verifies that the original process has ended instead of requiring output descriptors from an exited process. Unresolved identity or ambiguous readback keeps the Rizin session owned for retry. Persistent Rizin debugger sessions are unavailable outside Linux because this verification depends on `/proc`.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.diff --git a/src/process/ownedDebuggerSession.ts b/src/process/ownedDebuggerSession.tsindex 8f01dc4ef..3e67e85f0 100644--- a/src/process/ownedDebuggerSession.ts+++ b/src/process/ownedDebuggerSession.ts@@ -19,7 +19,10 @@ export interface OwnedInferiorIdentity {export type ProcessStartTimeReader = (pid: string) => Promise<string | null>;-const readLinuxProcessStartTime: ProcessStartTimeReader = async (pid) => {+/** Read one Linux identity; absence is distinct from unreadable or malformed data. */+export const readLinuxProcessStartTime: ProcessStartTimeReader = async (+ pid,+) => {if (process.platform !== "linux")throw new Error("Inferior process identity verification requires Linux /proc.",diff --git a/src/rizin/RizinDebugSessionManager.ts b/src/rizin/RizinDebugSessionManager.tsindex 3e742a6a1..c3657fadc 100644--- a/src/rizin/RizinDebugSessionManager.ts+++ b/src/rizin/RizinDebugSessionManager.ts@@ -1,6 +1,6 @@import { randomUUID } from "node:crypto";import { isUtf8 } from "node:buffer";-import { open, readFile, readlink, realpath, stat } from "node:fs/promises";+import { open, readlink, realpath, stat } from "node:fs/promises";import { constants as fsConstants } from "node:fs";import { isatty } from "node:tty";@@ -25,6 +25,7 @@ import {import {closeOwnedDebuggerSessions,stopOwnedDebuggerProcess,+ readLinuxProcessStartTime,verifyOwnedInferiorsEnded,type OwnedInferiorIdentity,type OwnedDebuggerDetachResult,@@ -1133,10 +1134,7 @@ export class RizinDebugSessionManager {async #detachInferior(session: RizinDebugSession,- ): Promise<- | { readonly status: "no-inferior" }- | { readonly status: "detached"; readonly outputSink: "durable" }- > {+ ): Promise<OwnedDebuggerDetachResult> {if (session.exited || session.protocolError !== undefined)throw new Error("Rizin protocol state is ambiguous; inferior detach is unverified.",@@ -1154,63 +1152,71 @@ export class RizinDebugSessionManager {async #detachInferiorUnlocked(session: RizinDebugSession,- ): Promise<- | { readonly status: "no-inferior" }- | { readonly status: "detached"; readonly outputSink: "durable" }- > {+ ): Promise<OwnedDebuggerDetachResult> {if (session.exited || session.protocolError !== undefined)throw new Error("Rizin protocol state is ambiguous; inferior detach is unverified.",);- {- session.inferiorInventoryComplete = false;- session.knownInferiorIdentities.clear();- const initial = parseRizinPtraceRows(- await this.#runInternalCommand(session, "olj"),- );- const inferior = initial;- if (inferior.length === 0) {- session.knownInferiorIdentities.clear();- session.inferiorInventoryComplete = true;- return { status: "no-inferior" };- }+ session.inferiorInventoryComplete = false;+ session.knownInferiorIdentities.clear();+ const inferior = parseRizinPtraceRows(+ await this.#runInternalCommand(session, "olj"),+ );+ if (inferior.length === 0) {session.knownInferiorIdentities.clear();- for (const [, pid] of inferior) {- if (session.knownInferiorIdentities.has(pid)) continue;- const startTime = await readProcStartTime(pid);- session.knownInferiorIdentities.set(pid, {- pid,- startTime,- });- }session.inferiorInventoryComplete = true;- if (inferior.length !== 1)+ return { status: "no-inferior" };+ }+ session.knownInferiorIdentities.clear();+ for (const [, pid] of inferior) {+ if (session.knownInferiorIdentities.has(pid)) continue;+ const startTime = await readLinuxProcessStartTime(pid);+ if (startTime === null)throw new Error(- "Rizin reported multiple or ambiguous ptrace inferiors.",+ `Inferior PID ${pid} ended before its identity could be established.`,);- const [fd, pid] = inferior[0]!;- const processStartTime = await readProcStartTime(pid);- await this.#verifyInferiorOutputConfiguration(session, pid);- await this.#runInternalCommand(session, `o- ${fd}`);- const after = parseRizinPtraceRows(- await this.#runInternalCommand(session, "olj"),+ session.knownInferiorIdentities.set(pid, {+ pid,+ startTime,+ });+ }+ session.inferiorInventoryComplete = true;+ if (inferior.length !== 1)+ throw new Error("Rizin reported multiple or ambiguous ptrace inferiors.");+ const [fd, pid] = inferior[0]!;+ const identity = session.knownInferiorIdentities.get(pid)!;+ assertRizinProcessStartTimeStable(+ identity.startTime,+ await readLinuxProcessStartTime(pid),+ );+ await this.#verifyInferiorOutputConfiguration(session, pid);+ await this.#runInternalCommand(session, `o- ${fd}`);+ const after = parseRizinPtraceRows(+ await this.#runInternalCommand(session, "olj"),+ );+ if (+ after.some(+ ([activeFd, activePid]) => activeFd === fd || activePid === pid,+ ) ||+ after.length !== 0+ )+ throw new Error(+ "Rizin did not confirm that the selected inferior FD was detached.",);- if (- after.some(- ([activeFd, activePid]) => activeFd === fd || activePid === pid,- ) ||- after.length !== 0- )- throw new Error(- "Rizin did not confirm that the selected inferior FD was detached.",- );+ try {assertRizinProcessStartTimeStable(- processStartTime,- await readProcStartTime(pid),+ identity.startTime,+ await readLinuxProcessStartTime(pid),);await this.#verifyInferiorOutputConfiguration(session, pid);- return { status: "detached", outputSink: "durable" };+ } catch (cause) {+ // Detach resumes the inferior. Its identity or descriptors may disappear+ // before readback; only a previously identified process can prove its end.+ if (!(await verifyOwnedInferiorsEnded([identity]))) throw cause;+ session.knownInferiorIdentities.clear();+ return { status: "no-inferior" };}+ return { status: "detached", outputSink: "durable" };}async #verifyInferiorOutputConfiguration(@@ -1364,25 +1370,10 @@ const parseRizinPtraceRows = (output: string): Array<[string, string]> => {return rows;};-/** @internal Pure parser kept separately testable from live `/proc` access. */-export const parseRizinProcStartTime = (statContents: string): string => {- const commandEnd = statContents.lastIndexOf(")");- if (commandEnd < 0)- throw new Error("Inferior process identity is malformed.");- const fieldsAfterCommand = statContents- .slice(commandEnd + 1)- .trim()- .split(/\s+/u);- const startTime = fieldsAfterCommand[19];- if (startTime === undefined || !/^\d+$/u.test(startTime))- throw new Error("Inferior process start time could not be verified.");- return startTime;-};-/** @internal Reject a PID that changed identity during inferior detach. */export const assertRizinProcessStartTimeStable = (before: string,- after: string,+ after: string | null,): void => {if (after !== before)throw new Error(@@ -1390,9 +1381,6 @@ export const assertRizinProcessStartTimeStable = ();};-const readProcStartTime = async (pid: string): Promise<string> =>- parseRizinProcStartTime(await readFile(`/proc/${pid}/stat`, "utf8"));-const hasUnclaimedRizinFrames = (session: RizinDebugSession): boolean =>session.frames.length > 0 ||session.bufferedFrameBytes > 0 ||diff --git a/tests/boundary/providers/RizinInferiorExit.test.ts b/tests/boundary/providers/RizinInferiorExit.test.tsnew file mode 100644index 000000000..8a73e010a--- /dev/null+++ b/tests/boundary/providers/RizinInferiorExit.test.ts@@ -0,0 +1,166 @@+import { randomUUID } from "node:crypto";+import { mkdtemp, readFile, rm } from "node:fs/promises";+import { tmpdir } from "node:os";+import { join } from "node:path";+import { afterEach, expect, it } from "vitest";++import {+ ProviderProcessSupervisor,+ spawnOwnedProviderProcess,+} from "../../../src/process/ProviderProcess.js";+import { stopOwnedDebuggerProcess } from "../../../src/process/ownedDebuggerSession.js";+import { createInjectedProcess } from "./RizinDebugSessionCoverage.fixtures.js";+import {+ createRizinTestManager,+ rizinTestInferiorTty,+} from "./RizinTestInferiorTty.js";++const targets = new Set<ProviderProcessSupervisor>();+const directories = new Set<string>();+afterEach(async () => {+ const failures: Error[] = [];+ for (const supervisor of targets) {+ const stopped = await supervisor.stop();+ if (stopped.status === "incomplete")+ failures.push(new Error(`Fixture cleanup incomplete: ${stopped.reason}`));+ else targets.delete(supervisor);+ }+ if (failures.length > 0)+ throw new AggregateError(failures, "Retained owned inferior fixtures");+ for (const directory of directories) {+ await rm(directory, { recursive: true, force: true });+ directories.delete(directory);+ }+});++it.skipIf(process.platform !== "linux").each(["exit", "redirect"] as const)(+ "verifies the original inferior after %s during detach",+ async (mode) => {+ const directory = await mkdtemp(join(tmpdir(), "rea-rizin-exit-"));+ directories.add(directory);+ const ready = join(directory, "ready");+ const redirected = join(directory, "redirected");+ const tty = await rizinTestInferiorTty();+ const launched = await spawnOwnedProviderProcess({+ command: process.execPath,+ arguments: [+ "-e",+ `const fs = require("node:fs");+const [tty, ready, redirected] = process.argv.slice(1);+function route(destination) {+ for (const fd of [1, 2]) {+ fs.closeSync(fd);+ if (fs.openSync(destination, fs.constants.O_WRONLY | fs.constants.O_NOCTTY) !== fd)+ throw new Error("Unexpected fixture descriptor allocation");+ }+}+route(tty);+fs.writeFileSync(ready, "ready");+process.stdin.once("data", (command) => {+ if (command.toString().trim() === "exit") process.exit(0);+ route("/dev/null");+ fs.writeFileSync(redirected, "redirected");+});+process.stdin.resume();`,+ tty,+ ready,+ redirected,+ ],+ runId: randomUUID(),+ stdin: "pipe",+ });+ const supervisor = new ProviderProcessSupervisor(+ { ...launched, ownsProcessLifetime: true },+ { captureStdout: false, maxDiagnosticBytes: 0 },+ );+ targets.add(supervisor);+ let descriptorOpen = true;+ let commandTail = Promise.resolve();+ let protocolFailure: unknown;+ const injected = createInjectedProcess({+ onWrite: (text, control) => {+ commandTail = commandTail+ .then(async () => {+ for (const line of text.trimEnd().split("\n")) {+ if (line === "olj")+ control.output(+ JSON.stringify(+ descriptorOpen+ ? [+ {+ raised: true,+ fd: 3,+ uri: `ptrace://${launched.process.pid}`,+ },+ ]+ : [],+ ) + "\0",+ );+ else if (line === "o- 3") {+ descriptorOpen = false;+ launched.process.stdin!.write(`${mode}\n`);+ if (mode === "exit")+ expect(await supervisor.waitForExit(1_000)).toBe(true);+ else+ await expect+ .poll(() => readFile(redirected, "utf8"), {+ timeout: 1_000,+ })+ .toBe("redirected");+ } else if (line === "e dbg.exitkills") control.output("false\0");+ else if (line.startsWith("!echo "))+ control.output(`${line.slice(6)}\0`);+ }+ })+ .catch((cause: unknown) => {+ protocolFailure = cause;+ control.exit();+ });+ },+ });+ const manager = createRizinTestManager(+ {},+ {+ spawnProcess: injected.spawnProcess,+ stopProcess: stopOwnedDebuggerProcess,+ },+ );+ try {+ await expect+ .poll(() => readFile(ready, "utf8"), { timeout: 2_000 })+ .toBe("ready");+ const started = await manager.start({+ path: "fixture.bin",+ inferior_tty: tty,+ });+ expect(started.ok).toBe(true);+ if (!started.ok) return;++ const closed = await manager.close(started.value.session_id);+ await commandTail;+ if (protocolFailure !== undefined) throw protocolFailure;+ if (mode === "exit") {+ expect(closed.ok).toBe(true);+ expect(manager.status(started.value.session_id)).toBeUndefined();+ expect(supervisor.observedExit()?.code).toBe(0);+ } else {+ expect(closed.ok).toBe(false);+ expect(manager.status(started.value.session_id)).toBeDefined();+ expect(supervisor.observedExit()).toBeUndefined();+ if (!closed.ok)+ expect(closed.error.message).toContain(+ "not routed to the selected TTY",+ );+ }+ } finally {+ const stopped = await supervisor.stop();+ try {+ await manager.closeAll();+ } finally {+ injected.control.exit();+ }+ if (stopped.status === "incomplete")+ throw new Error(`Fixture cleanup incomplete: ${stopped.reason}`);+ }+ },+);diff --git a/tests/boundary/providers/RizinInferiorTty.test.ts b/tests/boundary/providers/RizinInferiorTty.test.tsindex 61774b192..8b23f52f9 100644--- a/tests/boundary/providers/RizinInferiorTty.test.ts+++ b/tests/boundary/providers/RizinInferiorTty.test.ts@@ -14,7 +14,6 @@ import { afterEach, expect, it, vi } from "vitest";import {assertRizinProcessStartTimeStable,- parseRizinProcStartTime,RizinDebugSessionManager,} from "../../../src/rizin/RizinDebugSessionManager.js";import { evidenceSchema } from "../../../src/domain/evidence.js";@@ -307,21 +306,14 @@ it.skipIf(process.platform !== "linux")(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",- );+it("rejects changed or missing Rizin inferior identity during detach", () => {expect(() => assertRizinProcessStartTimeStable("11", "12")).toThrow("disappeared or was reused",);expect(() => assertRizinProcessStartTimeStable("11", "11")).not.toThrow();+ expect(() => assertRizinProcessStartTimeStable("11", null)).toThrow(+ "disappeared or was reused",+ );});it.skipIf(process.platform !== "linux")(