From 230db70fb473dd15928ae6c1a885f7e8a5507dae Mon Sep 17 00:00:00 2001 From: Ysopwnable <161784452+N0zoM1z0@users.noreply.github.com> Date: Mon, 16 Nov 2026 09:19:33 +0100 Subject: [PATCH] feat(gdb): bind sessions to an optional executable Hash and load an optional initial executable before GDB readiness, without running it. Preserve initial identity and completed hash diagnostics through cancellation and cleanup retry; share the file owner with Rizin. Fixes #11581. Refs #11682. Co-authored-by: gensokyo-dev <342580529+gensokyo-dev@users.noreply.github.com> --- .../references/runtime-observation.md | 14 +- .../references/runtime-observation.md | 14 +- docs/getting-started/cli.md | 8 +- docs/reference/mcp-contracts.md | 7 +- docs/reverse-engineering-tools.md | 2 +- docs/specs/README.md | 1 + docs/specs/native/gdb-executable/plan.md | 23 + docs/specs/native/gdb-executable/spec.md | 42 ++ docs/specs/native/gdb-executable/tasks.md | 34 ++ .../tools/start_gdb_session.json | 2 +- src/cli/reverseEngineeringCommands.ts | 10 + src/contracts/gdbToolContracts.ts | 7 +- src/gdb/GdbSessionManager.ts | 480 +++++++++++------- src/process/DebuggerLaunchFile.ts | 140 +++++ src/rizin/RizinDebugSessionManager.ts | 142 +----- src/server/serviceToolBindings.ts | 14 +- .../mcp/gdbExecutableSelection.test.ts | 393 ++++++++++++++ .../GdbSessionReviewRegressions.test.ts | 25 +- .../providers/RizinTtyCleanup.test.ts | 131 ++++- 19 files changed, 1148 insertions(+), 341 deletions(-) create mode 100644 docs/specs/native/gdb-executable/plan.md create mode 100644 docs/specs/native/gdb-executable/spec.md create mode 100644 docs/specs/native/gdb-executable/tasks.md create mode 100644 src/process/DebuggerLaunchFile.ts create mode 100644 tests/boundary/mcp/gdbExecutableSelection.test.ts diff --git a/.agents/skills/reverse-engineer-anything/references/runtime-observation.md b/.agents/skills/reverse-engineer-anything/references/runtime-observation.md index db73e4e880..4761daa2ed 100644 --- a/.agents/skills/reverse-engineer-anything/references/runtime-observation.md +++ b/.agents/skills/reverse-engineer-anything/references/runtime-observation.md @@ -8,13 +8,13 @@ to choose a function or hypothesis; `trace_native_values` follows recovered static value dependencies and does not measure runtime values. Prefer static inspection or existing capture comparison when it already answers the question. -| Question | Existing workflow | Host and effects | -| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Which selected native entry is reached, with which integer argument registers? | `observe_native_calls` on the active Mach-O, with exact function/Objective-C breakpoints and a duration/event bound | macOS with LLDB and required debugger access. Launches a new owned process, stops at entries, records and continues; target execution may write files, show UI or use the network. It never attaches to an existing process. Inspect termination and partial coverage after the run. | -| What does caller-authored instrumentation observe? | `list_frida_devices` / `list_frida_processes` when discovery is needed; `start_frida_session`, `load_frida_script`, then status/unload/close | Requires compatible installed Frida bindings and selected device access; the real REA verifier covers Linux. Attach selects an existing PID; spawn selects a program and starts it paused until `resume_frida_session`. Scripts execute in the target and can change memory, files, network activity and behavior. This is not passive inspection. | -| Which debugger state or controlled execution explains the behavior? | `start_gdb_session` and `gdb_console`, or `start_rizin_debug_session` and `rizin_debug_command` | Persistent debugger workflows are Linux-only. GDB starts a debugger; console commands choose/load/attach/run targets. Rizin debug start launches the selected target and requires a durable `inferior_tty`. Both consoles are unrestricted and can change target memory/registers, run shell commands, write files and use the network. | -| How do terminal output, process lifetime and selected files differ between runs? | `capture_process_scenario`, then `compare_process_captures` with compatible recorded inputs | New captures require Linux or macOS and a working native PTY backend; macOS also needs `xcrun`/Swift for ownership inspection. Capture launches an owned command with ordinary user permissions. Observation paths select snapshots, not a filesystem sandbox. Comparing retained captures does not execute targets and is also available on Windows. | -| What does an existing desktop window show, or what changes after a declared UI action? | `observe_native_ui`; use `capture_native_ui_scenario` only for requested actions | macOS 14+ with required Screen Recording/Accessibility access. Select an existing PID/window. Observation does not launch or own the app; scenario actions can change its data or trigger network activity, and leave its state as-is. | +| Question | Existing workflow | Host and effects | +| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Which selected native entry is reached, with which integer argument registers? | `observe_native_calls` on the active Mach-O, with exact function/Objective-C breakpoints and a duration/event bound | macOS with LLDB and required debugger access. Launches a new owned process, stops at entries, records and continues; target execution may write files, show UI or use the network. It never attaches to an existing process. Inspect termination and partial coverage after the run. | +| What does caller-authored instrumentation observe? | `list_frida_devices` / `list_frida_processes` when discovery is needed; `start_frida_session`, `load_frida_script`, then status/unload/close | Requires compatible installed Frida bindings and selected device access; the real REA verifier covers Linux. Attach selects an existing PID; spawn selects a program and starts it paused until `resume_frida_session`. Scripts execute in the target and can change memory, files, network activity and behavior. This is not passive inspection. | +| Which debugger state or controlled execution explains the behavior? | `start_gdb_session` and `gdb_console`, or `start_rizin_debug_session` and `rizin_debug_command` | Persistent debugger workflows are Linux-only. GDB can hash/load an initial `executable` without running it; select it at startup when initial file identity matters. Console commands can load/attach/run other targets without rebinding that initial identity. Rizin debug start launches the selected target and requires a durable `inferior_tty`. Both consoles are unrestricted and can change target memory/registers, run shell commands, write files and use the network. | +| How do terminal output, process lifetime and selected files differ between runs? | `capture_process_scenario`, then `compare_process_captures` with compatible recorded inputs | New captures require Linux or macOS and a working native PTY backend; macOS also needs `xcrun`/Swift for ownership inspection. Capture launches an owned command with ordinary user permissions. Observation paths select snapshots, not a filesystem sandbox. Comparing retained captures does not execute targets and is also available on Windows. | +| What does an existing desktop window show, or what changes after a declared UI action? | `observe_native_ui`; use `capture_native_ui_scenario` only for requested actions | macOS 14+ with required Screen Recording/Accessibility access. Select an existing PID/window. Observation does not launch or own the app; scenario actions can change its data or trigger network activity, and leave its state as-is. | Close each persistent session with its matching tool. `close_frida_session` unloads scripts and detaches; it does not kill the target. A still-paused spawn diff --git a/.cursor-plugin/skills/reverse-engineer-anything/references/runtime-observation.md b/.cursor-plugin/skills/reverse-engineer-anything/references/runtime-observation.md index db73e4e880..4761daa2ed 100644 --- a/.cursor-plugin/skills/reverse-engineer-anything/references/runtime-observation.md +++ b/.cursor-plugin/skills/reverse-engineer-anything/references/runtime-observation.md @@ -8,13 +8,13 @@ to choose a function or hypothesis; `trace_native_values` follows recovered static value dependencies and does not measure runtime values. Prefer static inspection or existing capture comparison when it already answers the question. -| Question | Existing workflow | Host and effects | -| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| Which selected native entry is reached, with which integer argument registers? | `observe_native_calls` on the active Mach-O, with exact function/Objective-C breakpoints and a duration/event bound | macOS with LLDB and required debugger access. Launches a new owned process, stops at entries, records and continues; target execution may write files, show UI or use the network. It never attaches to an existing process. Inspect termination and partial coverage after the run. | -| What does caller-authored instrumentation observe? | `list_frida_devices` / `list_frida_processes` when discovery is needed; `start_frida_session`, `load_frida_script`, then status/unload/close | Requires compatible installed Frida bindings and selected device access; the real REA verifier covers Linux. Attach selects an existing PID; spawn selects a program and starts it paused until `resume_frida_session`. Scripts execute in the target and can change memory, files, network activity and behavior. This is not passive inspection. | -| Which debugger state or controlled execution explains the behavior? | `start_gdb_session` and `gdb_console`, or `start_rizin_debug_session` and `rizin_debug_command` | Persistent debugger workflows are Linux-only. GDB starts a debugger; console commands choose/load/attach/run targets. Rizin debug start launches the selected target and requires a durable `inferior_tty`. Both consoles are unrestricted and can change target memory/registers, run shell commands, write files and use the network. | -| How do terminal output, process lifetime and selected files differ between runs? | `capture_process_scenario`, then `compare_process_captures` with compatible recorded inputs | New captures require Linux or macOS and a working native PTY backend; macOS also needs `xcrun`/Swift for ownership inspection. Capture launches an owned command with ordinary user permissions. Observation paths select snapshots, not a filesystem sandbox. Comparing retained captures does not execute targets and is also available on Windows. | -| What does an existing desktop window show, or what changes after a declared UI action? | `observe_native_ui`; use `capture_native_ui_scenario` only for requested actions | macOS 14+ with required Screen Recording/Accessibility access. Select an existing PID/window. Observation does not launch or own the app; scenario actions can change its data or trigger network activity, and leave its state as-is. | +| Question | Existing workflow | Host and effects | +| -------------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| Which selected native entry is reached, with which integer argument registers? | `observe_native_calls` on the active Mach-O, with exact function/Objective-C breakpoints and a duration/event bound | macOS with LLDB and required debugger access. Launches a new owned process, stops at entries, records and continues; target execution may write files, show UI or use the network. It never attaches to an existing process. Inspect termination and partial coverage after the run. | +| What does caller-authored instrumentation observe? | `list_frida_devices` / `list_frida_processes` when discovery is needed; `start_frida_session`, `load_frida_script`, then status/unload/close | Requires compatible installed Frida bindings and selected device access; the real REA verifier covers Linux. Attach selects an existing PID; spawn selects a program and starts it paused until `resume_frida_session`. Scripts execute in the target and can change memory, files, network activity and behavior. This is not passive inspection. | +| Which debugger state or controlled execution explains the behavior? | `start_gdb_session` and `gdb_console`, or `start_rizin_debug_session` and `rizin_debug_command` | Persistent debugger workflows are Linux-only. GDB can hash/load an initial `executable` without running it; select it at startup when initial file identity matters. Console commands can load/attach/run other targets without rebinding that initial identity. Rizin debug start launches the selected target and requires a durable `inferior_tty`. Both consoles are unrestricted and can change target memory/registers, run shell commands, write files and use the network. | +| How do terminal output, process lifetime and selected files differ between runs? | `capture_process_scenario`, then `compare_process_captures` with compatible recorded inputs | New captures require Linux or macOS and a working native PTY backend; macOS also needs `xcrun`/Swift for ownership inspection. Capture launches an owned command with ordinary user permissions. Observation paths select snapshots, not a filesystem sandbox. Comparing retained captures does not execute targets and is also available on Windows. | +| What does an existing desktop window show, or what changes after a declared UI action? | `observe_native_ui`; use `capture_native_ui_scenario` only for requested actions | macOS 14+ with required Screen Recording/Accessibility access. Select an existing PID/window. Observation does not launch or own the app; scenario actions can change its data or trigger network activity, and leave its state as-is. | Close each persistent session with its matching tool. `close_frida_session` unloads scripts and detaches; it does not kill the target. A still-paused spawn diff --git a/docs/getting-started/cli.md b/docs/getting-started/cli.md index 2f2dfc2e8c..2ec9c8f318 100644 --- a/docs/getting-started/cli.md +++ b/docs/getting-started/cli.md @@ -685,7 +685,13 @@ For one-shot commands, `details.limit` reports `scope: "rea-invocation"` and deadline names `REA_GHIDRA_DECOMPILE_TIMEOUT_SECONDS`. `rea debug-with-gdb` and `rea debug-with-rizin` hold their debugger only for the -command's own process. If cleanup cannot confirm the debugger stopped, they print +command's own process. GDB's optional `--executable ./program` hashes and loads +that initial file before running the caller's console command, without starting +the inferior automatically. The Evidence target retains this initial file +selection; later console loads do not rebind it. Without the option, the session +target remains unknown. `--inferior-tty` still selects the durable output terminal. + +If cleanup cannot confirm the debugger stopped, they print `cleanup_incomplete` and exit nonzero without stopping it. `remediation.action` names the process, as does `retained_debugger_pids` in `details.diagnostics`, or in `details.diagnostics.cleanup_error.details.diagnostics` when the command also diff --git a/docs/reference/mcp-contracts.md b/docs/reference/mcp-contracts.md index 838ea2fe8a..1dbc94a013 100644 --- a/docs/reference/mcp-contracts.md +++ b/docs/reference/mcp-contracts.md @@ -1042,7 +1042,12 @@ command names its session, `{ "kind": "session", "session_kind": …, "id": …, "target": … }`, where `id` is the session ID REA minted and `target` is the launch file hashed when the session started (validated like a file subject), or an `unknown` target when -REA did not observe one (always for GDB, whose session launches no file); +REA did not observe one. `start_gdb_session` accepts an optional absolute +`executable` path: REA hashes the initial file, disables automatic loading, and +loads it without running an inferior. Omission leaves the target unknown. A +physical hash failure also leaves it unknown and records the reason; a failed +descriptor close or cancellation fails startup and retains cleanup ownership. +GDB Evidence records the original and absolute paths in `parameters.launch_provenance`; later debugger commands do not rebind it. Every record has a subject: one whose target REA did not identify names `{ "kind": "unknown", "reason": … }`, where the reason is diff --git a/docs/reverse-engineering-tools.md b/docs/reverse-engineering-tools.md index 4395beac84..01ec8ced8e 100644 --- a/docs/reverse-engineering-tools.md +++ b/docs/reverse-engineering-tools.md @@ -49,7 +49,7 @@ Captured stdout and stderr share `max_output_bytes` (CLI: `--max-output-bytes`), ## GDB -Persistent GDB sessions, including the MCP workflow and one-shot `rea debug-with-gdb` CLI, are available only on Linux. REA verifies a live inferior's output descriptors through `/proc` before detaching it; it does not claim equivalent descriptor verification on macOS. Windows is also unsupported because owned Job Object cleanup can terminate debugger inferiors. On supported Linux hosts, `start_gdb_session`, `gdb_console`, `gdb_session_status`, and `close_gdb_session` manage a persistent GDB/MI session in MCP. The one-shot CLI requires a caller-selected durable TTY: `rea debug-with-gdb --inferior-tty /dev/pts/7 'file ./program'`. The TTY must remain available after GDB exits so a detached inferior can continue writing. MCP starts GDB with `--nx --quiet --interpreter=mi3`, retries initialization with MI2 if MI3 initialization returns an error and cleanup succeeds, waits for its prompt, and disables auto-loading. Pass optional `inferior_tty` to select the terminal that future inferior runs use; REA configures it before the session becomes ready and checks the exact value with GDB/MI. `gdb_session_status` reports the selected path, whether REA still considers the configuration verified, and whether invalid UTF-8 has been observed in MI bytes (`mi_invalid_utf8`) or stderr (`stderr_invalid_utf8`). Commands that can change the inferior TTY or redirect a run revoke that verification permanently for the session, so close retains GDB ownership if a live inferior remains. The complete built-in inspections `show inferior-tty` and `help inferior-tty` preserve verification; compound commands still use the conservative mutation checks. Closing a session with one live inferior and a verified TTY automatically detaches the target, which can resume execution; MCP clients receive destructive-operation annotations for this behavior. The console remains unrestricted and can run shell commands, change target state, access files, and use network in the REA process user's security context. Raw MI records and console/target/log streams are returned with Evidence. Its subject names the session, `{ "kind": "session", "session_kind": "gdb", "id": , "target": { "kind": "unknown", "reason": "not-observed" } }`: `start_gdb_session` launches no program file, and REA does not hash programs that console commands load or attach, so the target stays unknown; command output is retained up to the configured budget (16 MiB by default) and explicitly marked when truncated. A single console, target or log record over the 16 MiB MI line limit is dropped and the command is marked truncated, while an oversized result or async record still stops the session. GDB startup waits 10000 ms with no runtime override. Each MI command defaults to 120000 ms; its deadline, command-output budget, session capacity and pending-command queue use the [shared debugger launch settings](#debugger-launch-settings). `command_timeout_ms` does not change a persistent debugger session. +Persistent GDB sessions, including the MCP workflow and one-shot `rea debug-with-gdb` CLI, are available only on Linux. REA verifies a live inferior's output descriptors through `/proc` before detaching it; it does not claim equivalent descriptor verification on macOS. Windows is also unsupported because owned Job Object cleanup can terminate debugger inferiors. On supported Linux hosts, `start_gdb_session`, `gdb_console`, `gdb_session_status`, and `close_gdb_session` manage a persistent GDB/MI session in MCP. The one-shot CLI requires a caller-selected durable TTY: `rea debug-with-gdb --inferior-tty /dev/pts/7 --executable ./program 'info files'`. The TTY must remain available after GDB exits so a detached inferior can continue writing. MCP starts GDB with `--nx --quiet --interpreter=mi3`, retries protocol initialization with MI2 when applicable and cleanup succeeds, waits for its prompt, and disables auto-loading. Optional `executable` hashes and loads an initial local file without running it; readiness requires a confirmed load. A refused load is not repeated with MI2. Pass optional `inferior_tty` to select the terminal that future inferior runs use; REA configures it before the session becomes ready and checks the exact value with GDB/MI. `gdb_session_status` reports the selected path, whether REA still considers the configuration verified, and whether invalid UTF-8 has been observed in MI bytes (`mi_invalid_utf8`) or stderr (`stderr_invalid_utf8`). Commands that can change the inferior TTY or redirect a run revoke that verification permanently for the session, so close retains GDB ownership if a live inferior remains. The complete built-in inspections `show inferior-tty` and `help inferior-tty` preserve verification; compound commands still use the conservative mutation checks. Closing a session with one live inferior and a verified TTY automatically detaches the target, which can resume execution; MCP clients receive destructive-operation annotations for this behavior. The console remains unrestricted and can run shell commands, change target state, access files, and use network in the REA process user's security context. Raw MI records and console/target/log streams are returned with Evidence. Its subject names the session and its initial file selection: `{ "kind": "session", "session_kind": "gdb", "id": , "target": }`. Selecting `executable` binds the initial stable file hash; omission or a physical hash failure leaves the target unknown, with the failure reason retained. `parameters.launch_provenance` preserves the original and absolute startup paths. Later console loads or attaches do not rebind this initial selection or establish the current inferior's identity; command output is retained up to the configured budget (16 MiB by default) and explicitly marked when truncated. A single console, target or log record over the 16 MiB MI line limit is dropped and the command is marked truncated, while an oversized result or async record still stops the session. GDB startup waits 10000 ms with no runtime override. Each MI command defaults to 120000 ms; its deadline, command-output budget, session capacity and pending-command queue use the [shared debugger launch settings](#debugger-launch-settings). `command_timeout_ms` does not change a persistent debugger session. A truncated GDB command capture includes `output_limits` with the exact causes and effective maxima: `command_bytes`, `command_records`, or `mi_line_bytes`. diff --git a/docs/specs/README.md b/docs/specs/README.md index 19f41f6c4f..9db256c6bf 100644 --- a/docs/specs/README.md +++ b/docs/specs/README.md @@ -18,6 +18,7 @@ for new work, roadmap granularity and producer-owned contracts. ## Other feature records +- [GDB executable selection](native/gdb-executable/spec.md) ([plan](native/gdb-executable/plan.md), [tasks](native/gdb-executable/tasks.md)) - [Core WebAssembly interface comparison (#2356)](2356-wasm-interface-comparison/spec.md) ([plan](2356-wasm-interface-comparison/plan.md), [tasks](2356-wasm-interface-comparison/tasks.md), [verification](2356-wasm-interface-comparison/verification.md)) - [Inspect APK signature schemes (v1–v3.1)](apk-signature/spec.md) - [Documentation organization](documentation/organization/spec.md) ([plan](documentation/organization/plan.md), [tasks](documentation/organization/tasks.md), [verification](documentation/organization/verification.md)) diff --git a/docs/specs/native/gdb-executable/plan.md b/docs/specs/native/gdb-executable/plan.md new file mode 100644 index 0000000000..3314dd5d5b --- /dev/null +++ b/docs/specs/native/gdb-executable/plan.md @@ -0,0 +1,23 @@ +# Implementation plan + +The contract owns the optional input. MCP bindings and the one-shot CLI forward +it to `GdbSessionManager`; the manager owns path admission, file observation, +protocol startup and publication. + +Extract Rizin's existing stable launch-file observation into one shared debugger +helper. Each manager retains failed file handles in its existing resource scope +or an equivalent startup scope drained by shutdown and cleanup retry. Preserve +Rizin's current outcome policy and caller-path semantics. +Completed hash facts also survive cancellation or failed final descriptor close +in both managers; startup still fails, retaining the exact failed cleanup owner. + +Observe the file once per admitted GDB start, before dialect negotiation. Pass +the same observation into each protocol attempt. The adapter quotes the load +path using its MI string owner and requires a complete successful reply. A +refused file load is a semantic startup failure, not a reason to repeat it with +another MI dialect. + +One GDB Evidence producer attaches the session's immutable initial selection and +its provenance to ordinary and partial observations. Native and simulated tests +exercise the public adapters and the startup lifecycle boundaries. Update the +owning CLI/Evidence documentation and regenerate ignored catalogs as required. diff --git a/docs/specs/native/gdb-executable/spec.md b/docs/specs/native/gdb-executable/spec.md new file mode 100644 index 0000000000..104f7d1e80 --- /dev/null +++ b/docs/specs/native/gdb-executable/spec.md @@ -0,0 +1,42 @@ +# Bind a GDB session to its selected load file + +Scope: [#11581](https://github.com/morluto/rea/issues/11581), approved in the +2026-11-16 maintainer handoff and recorded in +[#11682](https://github.com/morluto/rea/issues/11682#needs-an-owner-decision). + +`start_gdb_session` currently records an unknown target because it accepts no +file. An analyst who selects a file at startup needs subsequent command Evidence +to identify that initial file, separately from the current inferior. + +## Requirements + +1. Accept an optional absolute `executable` path on `start_gdb_session`. + The one-shot `debug-with-gdb` command exposes the same selection as + `--executable`, accepting a caller-relative local path. +2. Hash the selected regular file with the existing stable-file owner before + GDB loads it. Share hash outcome and failed-close interpretation with Rizin. + A physical hash failure leaves identity unknown with its reason; cancellation + and outstanding descriptor cleanup fail startup and retain cleanup ownership. + If hashing completed before final close failed or was cancelled, preserve its + SHA-256 and byte count in the startup error, including after cleanup retry. +3. Disable automatic loading before issuing the MI file-load request. Publish + readiness only after the load completes successfully. Loading does not issue + an inferior run, attach or shell command. +4. Bind command and partial startup Evidence to the initial file observation. + Preserve original and absolute startup paths as provenance. Later console + loads and attaches do not rebind it. Omission preserves an unknown target. +5. Preserve cancellation, startup reservations, failed-start cleanup retention, + cleanup retry and shutdown draining through the new stages. + +## Acceptance + +Public MCP and CLI workflows expose the input and retain the initial file hash +in Evidence. A real Linux GDB load of an owned executable leaves its execution +marker absent. Deterministic provider tests cover refused loading, cancellation +during loading and failed cleanup retry. Existing GDB lifecycle and Rizin hash +cleanup regressions continue to pass. Report simulated and real-provider +verification separately. + +This increment leaves unrestricted `gdb_console` authority and the session +identity rules in the [target identity ADR](../../../adr/evidence/target-identity.md) +in place. diff --git a/docs/specs/native/gdb-executable/tasks.md b/docs/specs/native/gdb-executable/tasks.md new file mode 100644 index 0000000000..0b9e3e2eac --- /dev/null +++ b/docs/specs/native/gdb-executable/tasks.md @@ -0,0 +1,34 @@ +# Tasks + +- [x] Add the optional contract/CLI input and forward it to GDB startup (R1). +- [x] Share stable launch-file observation with Rizin and retain failed cleanup + through retry and shutdown (R2, R5). +- [x] Load after automatic loading is disabled, then publish readiness (R3). +- [x] Bind ordinary and partial Evidence to initial selection and provenance; + preserve unknown omission and later-command semantics (R4). +- [x] Verify public MCP/CLI behavior, refused/cancelled loading, cleanup retry, + and the affected existing lifecycle suites (R1–R5). +- [x] Run a real Linux GDB load-only workflow and record its limits; update + product documentation and required static/generated checks (acceptance). + +## Verification (2026-11-16) + +- Serial typecheck/lint and architecture guards passed. +- Ten focused files passed 301 tests before the completed-hash review fix, including advertised-schema/client + admission, CLI selection, late loading/cancellation, retained file and + debugger cleanup, and existing GDB/Rizin lifecycle behavior. +- Temporarily permitting MI2 retry after file-load refusal made the dedicated + regression fail with two loads instead of one; source was restored exactly. +- A public stdio MCP workflow with GNU GDB 13.1 on Linux loaded an owned ELF + whose path contained spaces and quotes. Evidence matched its SHA-256, + Python automatic loading was off, its execution marker remained absent, + and the session closed successfully. Native Rizin was not exercised. +- Six additional GDB/Rizin cases preserve completed hash facts when final close + fails, is cancelled, or both, through public error projection and cleanup retry. + All six fail against the pre-fix shared observer; the twelve-case file passed + with the fix. A broader rerun passed 306/307 tests; the remaining fixture + observed an empty asynchronous signal marker. Publishing that marker + synchronously removed the observation race, and both affected files passed + all 32 tests on the final source. Final CI is recorded in the PR. +- Documentation/generated checks and final native recheck are recorded in the + PR validation evidence. diff --git a/scripts/verify/advertised-schemas/tools/start_gdb_session.json b/scripts/verify/advertised-schemas/tools/start_gdb_session.json index d7997f7c6f..0aef84f8eb 100644 --- a/scripts/verify/advertised-schemas/tools/start_gdb_session.json +++ b/scripts/verify/advertised-schemas/tools/start_gdb_session.json @@ -1,6 +1,6 @@ { "schemas": { - "input compact": "21c503e369a05f57", + "input compact": "3a4bca02d0a44fb8", "output compact": "a14bf3365e44977e" }, "patterns": { diff --git a/src/cli/reverseEngineeringCommands.ts b/src/cli/reverseEngineeringCommands.ts index d68bf92e98..0f693736e7 100644 --- a/src/cli/reverseEngineeringCommands.ts +++ b/src/cli/reverseEngineeringCommands.ts @@ -243,6 +243,13 @@ export const registerReverseEngineeringCommands = ( .describe("One unrestricted GDB console command."), }), options: z.object({ + executable: z + .string() + .min(1) + .optional() + .describe( + "Initial local file to hash and load without running it; command Evidence retains this initial selection.", + ), inferiorTty: z .string() .min(1) @@ -281,6 +288,9 @@ export const registerReverseEngineeringCommands = ( run: async () => { const started = await manager.start(signal, { inferiorTty: options.inferiorTty, + ...(options.executable === undefined + ? {} + : { executable: options.executable }), }); if (!started.ok) return started; sessionId = started.value.session_id; diff --git a/src/contracts/gdbToolContracts.ts b/src/contracts/gdbToolContracts.ts index 9fdc06caf0..cbf2774eb7 100644 --- a/src/contracts/gdbToolContracts.ts +++ b/src/contracts/gdbToolContracts.ts @@ -28,8 +28,13 @@ export const GDB_TOOL_CONTRACTS = [ ), kind: "native-provider", description: - "Start a persistent caller-supplied GDB session and return its session ID. Linux only; detaching a live inferior during close requires a verified durable output TTY. Startup suppresses init files and auto-loading, preferring MI3. Optional inferior_tty selects a verified terminal for later inferior runs; keep it available after GDB exits so close can detach a live inferior safely. The session belongs to this REA server process.", + "Start a persistent caller-supplied GDB session and return its session ID. Linux only; detaching a live inferior during close requires a verified durable output TTY. Startup suppresses init files and auto-loading, preferring MI3. Optional executable hashes and loads an initial file without running it; command Evidence names this initial selection, and later console loads do not rebind it. Omission leaves the session target unknown. Optional inferior_tty selects a verified terminal for later inferior runs; keep it available after GDB exits so close can detach a live inferior safely. The session belongs to this REA server process.", inputSchema: z.strictObject({ + executable: absoluteLocalPathStringSchema + .optional() + .describe( + "Initial file to hash and load, without running it. Later command Evidence retains this initial target identity; it does not establish the current inferior.", + ), inferior_tty: absoluteLocalPathStringSchema .optional() .describe( diff --git a/src/gdb/GdbSessionManager.ts b/src/gdb/GdbSessionManager.ts index 29ab1259ef..16a525967a 100644 --- a/src/gdb/GdbSessionManager.ts +++ b/src/gdb/GdbSessionManager.ts @@ -2,6 +2,15 @@ import { unknownTarget, type SessionTargetIdentity, } from "../domain/targetIdentity.js"; +import { + observeDebuggerLaunchFile, + retryDebuggerStartupFileCleanup, + type DebuggerLaunchFileObservation, +} from "../process/DebuggerLaunchFile.js"; +import { absoluteCallerPath } from "../filesystem/callerPath.js"; +import { ArtifactResourceScope } from "../resources/index.js"; +import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import type { JsonValue } from "../domain/jsonValue.js"; import { gdbMiConstText, gdbMiResultHeader, @@ -53,7 +62,11 @@ import { AnalysisError, type AnalysisErrorOptions, } from "../domain/analysisErrorBase.js"; -import { createEvidence, type Evidence } from "../domain/evidence.js"; +import { + createEvidence, + type Evidence, + type EvidenceObservationInput, +} from "../domain/evidence.js"; import type { GdbCommandResult, GdbOutputLimit, @@ -136,8 +149,28 @@ const gdbLaunchUnavailable = ( ); }; -/** Launch failures: changing the MI dialect cannot start the executable. */ -const gdbLaunchFailures = new WeakSet(); +interface GdbStartOptions { + readonly inferiorTty?: string; + readonly executable?: string; +} + +type GdbStarted = { + readonly session_id: string; + readonly mi_version: "mi3" | "mi2"; +}; + +interface GdbStartupFailure { + readonly error: AnalysisError; + /** A load attempt or a physical launch refusal cannot be repaired by MI2. */ + readonly retryDialect: boolean; +} + +interface GdbLaunchFile extends DebuggerLaunchFileObservation { + readonly provenance?: { + readonly caller_selected_path: string; + readonly resolved_path: string; + }; +} const MAX_COMMAND_OUTPUT_RECORDS = 16_384; const MAX_MI_LINE_BYTES = 16 * 1024 * 1024; @@ -322,6 +355,7 @@ class GdbProtocolFailureError extends Error { interface GdbSession { readonly id: string; + readonly launchFile: GdbLaunchFile; readonly miVersion: "mi3" | "mi2"; /** Identity for this session's Evidence; version is set from -gdb-version. */ provider: GdbProviderIdentity; @@ -364,24 +398,56 @@ interface GdbSession { } /** - * GDB command Evidence names the session REA minted. `start_gdb_session` - * launches no program file: programs are loaded or attached by console - * commands that REA does not hash, so the session target stays unknown. + * The session names its initial file selection. Later unrestricted console + * commands do not rebind it or establish the current inferior's identity. */ const gdbSessionSubject = ( - session: Pick, + session: Pick, ): SessionTargetIdentity => ({ kind: "session", session_kind: "gdb", id: session.id, - target: unknownTarget("not-observed"), + target: session.launchFile.identity, }); +/** Preserve initial selection facts across complete and partial observations. */ +const createGdbSessionEvidence = ( + session: Pick, + observation: Omit & { + readonly parameters: Readonly>; + }, +): Evidence => { + const { provenance, unobservedReason } = session.launchFile; + return createEvidence( + gdbSessionSubject(session), + session.provider, + provenance === undefined + ? observation + : { + ...observation, + parameters: { + ...observation.parameters, + launch_provenance: { ...provenance }, + }, + limitations: [ + "The session target is the initial file selected and hashed before loading; later debugger commands do not rebind it or establish the current inferior's identity.", + ...(unobservedReason === undefined + ? [] + : [ + `The launch file could not be hashed at session start, so the session target is unknown: ${unobservedReason}`, + ]), + ...(observation.limitations ?? []), + ], + }, + ); +}; + const gdbCloseUnavailable = (): AnalysisInputError => unknownDebuggerSessionError(GDB_SESSION_TOOLS, "close_gdb_session"); /** Owns persistent GDB/MI sessions independently from the active binary target. */ export class GdbSessionManager { + readonly #startupResources = new ArtifactResourceScope(); readonly #sessions: OwnedDebuggerSessionRegistry; readonly #command: string; readonly #environment: NodeJS.ProcessEnv; @@ -475,13 +541,22 @@ export class GdbSessionManager { async start( signal?: AbortSignal, - options: { readonly inferiorTty?: string } = {}, - ): Promise< - Result< - { readonly session_id: string; readonly mi_version: "mi3" | "mi2" }, - AnalysisError - > - > { + options: GdbStartOptions = {}, + ): Promise> { + if ( + options.executable !== undefined && + (options.executable.length === 0 || options.executable.includes("\0")) + ) + return err( + new AnalysisInputError("start_gdb_session", undefined, [ + { + path: ["executable"], + reason: "invalid_value", + message: + "The executable path must be non-empty and must not contain NUL.", + }, + ]), + ); if ( options.inferiorTty !== undefined && (options.inferiorTty.length === 0 || options.inferiorTty.includes("\0")) @@ -503,13 +578,8 @@ export class GdbSessionManager { async #startWithReservation( signal: AbortSignal, - options: { readonly inferiorTty?: string } = {}, - ): Promise< - Result< - { readonly session_id: string; readonly mi_version: "mi3" | "mi2" }, - AnalysisError - > - > { + options: GdbStartOptions = {}, + ): Promise> { if (signal?.aborted) return err(cancelledBy("start_gdb_session", signal)); if (!persistentDebuggerHostSupported(this.#platform)) return err( @@ -521,6 +591,8 @@ export class GdbSessionManager { : "Persistent GDB sessions are available only on Linux because REA verifies live inferior output descriptors through /proc.", ), ); + const files = await this.#retryStartupFileCleanup(); + if (!files.ok) return files; const occupied = this.#sessions.occupied(); if (occupied >= this.#maxSessions.value) return err( @@ -547,33 +619,48 @@ export class GdbSessionManager { async #startReserved( releaseReservation: () => void, signal: AbortSignal, - options: { readonly inferiorTty?: string } = {}, - ): Promise< - Result< - { readonly session_id: string; readonly mi_version: "mi3" | "mi2" }, - AnalysisError - > - > { + options: GdbStartOptions = {}, + ): Promise> { + let launchFile: GdbLaunchFile = { identity: unknownTarget("not-observed") }; + if (options.executable !== undefined) { + const resolved = absoluteCallerPath(options.executable); + const observed = await observeDebuggerLaunchFile(resolved, { + provider: "gdb", + operation: "start_gdb_session", + resources: this.#startupResources, + signal, + }); + if (!observed.ok) return observed; + launchFile = { + ...observed.value, + provenance: { + caller_selected_path: options.executable, + resolved_path: resolved, + }, + }; + } + if (signal.aborted) return err(cancelledBy("start_gdb_session", signal)); const id = randomUUID(); const mi3 = await this.#startProtocol( id, "mi3", releaseReservation, signal, - options.inferiorTty, + options, + launchFile, ); - return mi3.ok || - signal.aborted || - this.#sessions.has(id) || - gdbLaunchFailures.has(mi3.error) - ? mi3 - : this.#startProtocol( - id, - "mi2", - releaseReservation, - signal, - options.inferiorTty, - ); + if (mi3.ok) return mi3; + if (signal.aborted || this.#sessions.has(id) || !mi3.error.retryDialect) + return err(mi3.error.error); + const mi2 = await this.#startProtocol( + id, + "mi2", + releaseReservation, + signal, + options, + launchFile, + ); + return mi2.ok ? mi2 : err(mi2.error.error); } async #startProtocol( @@ -581,13 +668,13 @@ export class GdbSessionManager { miVersion: "mi3" | "mi2", releaseReservation: () => void, signal: AbortSignal, - inferiorTty?: string, - ): Promise< - Result< - { readonly session_id: string; readonly mi_version: "mi3" | "mi2" }, - AnalysisError - > - > { + options: GdbStartOptions, + launchFile: GdbLaunchFile, + ): Promise> { + const { inferiorTty } = options; + let loadAttempted = false; + const failed = (error: AnalysisError, retryDialect = !loadAttempted) => + err({ error, retryDialect }); let launched: SpawnedOwnedProviderProcess; try { const spawnOptions: OwnedProviderProcessSpawnOptions = { @@ -604,7 +691,7 @@ export class GdbSessionManager { (signal?.aborted && cause === signal.reason) || cause instanceof AnalysisCancelledError ) - return err(cancelledBy("start_gdb_session", carriedReason(cause))); + return failed(cancelledBy("start_gdb_session", carriedReason(cause))); const launch = launcherFailureOf(cause); if (launch !== undefined) { const command = this.#command; @@ -618,10 +705,9 @@ export class GdbSessionManager { unavailable: (unavailable, details) => gdbLaunchUnavailable(command, unavailable, details), }); - gdbLaunchFailures.add(failure); - return err(failure); + return failed(failure, false); } - return err( + return failed( new AnalysisCapabilityUnavailableError( "gdb", "start_gdb_session", @@ -640,6 +726,7 @@ export class GdbSessionManager { }); const session: GdbSession = { id, + launchFile, miVersion, provider: GDB_PROVIDER_IDENTITY, launched, @@ -824,6 +911,25 @@ export class GdbSessionManager { ); session.inferiorTtyVerified = true; } + if (launchFile.provenance !== undefined) { + loadAttempted = true; + const loaded = await this.#request( + session, + `-file-exec-and-symbols ${miQuote(launchFile.provenance.resolved_path)}`, + signal, + "start_gdb_session", + ); + if ( + loaded.completion_status !== "complete" || + loaded.output_truncated || + !parseGdbMiDoneRecord(loaded.mi).ok + ) + throw new AnalysisCapabilityUnavailableError( + "gdb", + "start_gdb_session", + `GDB did not confirm loading the selected executable (${loaded.mi}). Check the selected file and GDB's load diagnostic before retrying start_gdb_session.`, + ); + } if (signal?.aborted) throw cancelledBy("start_gdb_session", signal); // Give queued exit notifications a turn before publishing startup. await new Promise((resolve) => setImmediate(resolve)); @@ -883,7 +989,7 @@ export class GdbSessionManager { const startupEvidence = startupEvidencePayload === undefined ? undefined - : createEvidence(gdbSessionSubject(session), session.provider, { + : createGdbSessionEvidence(session, { predicateType: "rea.debugger.startup-observation", operation: "start_gdb_session", parameters: { @@ -948,7 +1054,7 @@ export class GdbSessionManager { }; const details = { cause, ...detailsWithoutCause }; if (cause instanceof AnalysisTimeoutError) - return err( + return failed( retainCleanup( new AnalysisTimeoutError(cause.operation, cause.timeoutMs, { ...details, @@ -957,7 +1063,7 @@ export class GdbSessionManager { ), ); if (cause instanceof AnalysisCancelledError) - return err( + return failed( retainCleanup( cancelledBy( cause.operation, @@ -967,7 +1073,7 @@ export class GdbSessionManager { ), ); const startupFailureMessage = errorMessage(cause); - return err( + return failed( retainCleanup( new AnalysisCapabilityUnavailableError( "gdb", @@ -1034,7 +1140,7 @@ export class GdbSessionManager { `GDB startup failed (${errorMessage(cause)}).`, errorDetails, ); - return err(error); + return failed(error); } finally { clearTimeout(startupTimer); signal?.removeEventListener("abort", startupAbortListener); @@ -1097,63 +1203,59 @@ export class GdbSessionManager { command, accepted.value, ); - const evidence = createEvidence( - gdbSessionSubject(session), - session.provider, - { - predicateType: "rea.debugger.console-observation", - operation: "gdb_console", - parameters: { session_id: sessionId, command }, - result: { - command, - mi: result.mi, - records: [...result.records], - console: result.console, - target: result.target, - log: result.log, - output_truncated: result.output_truncated, - ...(result.output_limits === undefined - ? {} - : { output_limits: result.output_limits }), - ...(result.output_invalid_utf8 - ? { output_invalid_utf8: true as const } - : {}), - completion_status: result.completion_status, - }, - rawResult: { - command, - mi: result.mi, - records: [...result.records], - console: result.console, - target: result.target, - log: result.log, - output_truncated: result.output_truncated, - ...(result.output_limits === undefined - ? {} - : { output_limits: result.output_limits }), - ...(result.output_invalid_utf8 - ? { output_invalid_utf8: true as const } - : {}), - completion_status: result.completion_status, - }, - limitations: [ - "The active GDB inferior identity is not established by the debugger session identifier.", - ...(result.mi.length === 0 - ? [ - "A separately tokenized read-only query confirmed return to GDB's command loop. The original result record could not be framed independently from raw stdout; its bytes remain in records and its result class is unknown.", - ] - : []), - "MI records are returned as decoded text; their semantics depend on GDB version and target.", - ...gdbRetainedOutputLimitations(result, acceptedOutput), - ...(result.output_invalid_utf8 - ? [ - "MI stream bytes were not valid UTF-8; returned text contains replacement characters.", - ] - : []), - "The unrestricted GDB console can access local shell, filesystem, network, and target controls.", - ], + const evidence = createGdbSessionEvidence(session, { + predicateType: "rea.debugger.console-observation", + operation: "gdb_console", + parameters: { session_id: sessionId, command }, + result: { + command, + mi: result.mi, + records: [...result.records], + console: result.console, + target: result.target, + log: result.log, + output_truncated: result.output_truncated, + ...(result.output_limits === undefined + ? {} + : { output_limits: result.output_limits }), + ...(result.output_invalid_utf8 + ? { output_invalid_utf8: true as const } + : {}), + completion_status: result.completion_status, }, - ); + rawResult: { + command, + mi: result.mi, + records: [...result.records], + console: result.console, + target: result.target, + log: result.log, + output_truncated: result.output_truncated, + ...(result.output_limits === undefined + ? {} + : { output_limits: result.output_limits }), + ...(result.output_invalid_utf8 + ? { output_invalid_utf8: true as const } + : {}), + completion_status: result.completion_status, + }, + limitations: [ + "The active GDB inferior identity is not established by the debugger session identifier.", + ...(result.mi.length === 0 + ? [ + "A separately tokenized read-only query confirmed return to GDB's command loop. The original result record could not be framed independently from raw stdout; its bytes remain in records and its result class is unknown.", + ] + : []), + "MI records are returned as decoded text; their semantics depend on GDB version and target.", + ...gdbRetainedOutputLimitations(result, acceptedOutput), + ...(result.output_invalid_utf8 + ? [ + "MI stream bytes were not valid UTF-8; returned text contains replacement characters.", + ] + : []), + "The unrestricted GDB console can access local shell, filesystem, network, and target controls.", + ], + }); return ok({ result, evidence }); } catch (cause) { if (cause instanceof AnalysisCancelledError) return err(cause); @@ -1171,22 +1273,18 @@ export class GdbSessionManager { ...processExit.partial, command, }; - const evidence = createEvidence( - gdbSessionSubject(session), - session.provider, - { - predicateType: "rea.debugger.console-observation", - operation: "gdb_console", - parameters: { session_id: sessionId, command }, - result: { ...result, records: [...result.records] }, - rawResult: { ...result, records: [...result.records] }, - limitations: [ - "The active GDB inferior identity is not established by the debugger session identifier.", - "GDB exited before returning a correlated MI result record; only records retained for the active command are returned raw.", - ...gdbRetainedOutputLimitations(result, acceptedOutput), - ], - }, - ); + const evidence = createGdbSessionEvidence(session, { + predicateType: "rea.debugger.console-observation", + operation: "gdb_console", + parameters: { session_id: sessionId, command }, + result: { ...result, records: [...result.records] }, + rawResult: { ...result, records: [...result.records] }, + limitations: [ + "The active GDB inferior identity is not established by the debugger session identifier.", + "GDB exited before returning a correlated MI result record; only records retained for the active command are returned raw.", + ...gdbRetainedOutputLimitations(result, acceptedOutput), + ], + }); const stopped = await this.#stopDebuggerOnly(session); if (stopped.status === "incomplete") return err( @@ -1439,9 +1537,27 @@ export class GdbSessionManager { } async retryCleanupFailures(): Promise> { - return this.#sessions.retryCleanupFailures( + const files = await this.#retryStartupFileCleanup(); + const sessions = await this.#sessions.retryCleanupFailures( (session) => session.ready && !session.closeRequested, ); + if (!files.ok && !sessions.ok) + return err( + analysisErrorWithCleanupFailure( + files.error, + sessions.error, + "start_gdb_session", + ), + ); + return !files.ok ? files : sessions; + } + + #retryStartupFileCleanup(): Promise> { + return retryDebuggerStartupFileCleanup({ + provider: "gdb", + operation: "start_gdb_session", + resources: this.#startupResources, + }); } async closeAll(): Promise { @@ -1460,7 +1576,16 @@ export class GdbSessionManager { await Promise.all( [...this.#sessions.values()].map((session) => session.commandTail), ); - await this.#sessions.closeAll(); + const outcomes = await Promise.allSettled([ + this.#sessions.closeAll(), + this.#startupResources.close(), + ]); + const failures = outcomes.flatMap((outcome) => + outcome.status === "rejected" ? [outcome.reason] : [], + ); + if (failures.length === 1) throw failures[0]; + if (failures.length > 1) + throw new AggregateError(failures, "GDB cleanup remains incomplete"); } async #serialize( @@ -1759,7 +1884,7 @@ export class GdbSessionManager { const partialObservation = partial === undefined ? undefined - : createEvidence(gdbSessionSubject(session), session.provider, { + : createGdbSessionEvidence(session, { predicateType: "rea.debugger.console-observation", operation: "gdb_console", parameters: { @@ -2006,30 +2131,26 @@ export class GdbSessionManager { ), }, ); - const evidence = createEvidence( - gdbSessionSubject(session), - session.provider, - { - predicateType: - operation === "start_gdb_session" - ? "rea.debugger.startup-observation" - : "rea.debugger.console-observation", - operation, - parameters: { - session_id: session.id, - command: pending.evidenceCommand, - }, - result: { ...partial, records: [...partial.records] }, - rawResult: { ...partial, records: [...partial.records] }, - limitations: [ - "The active GDB inferior identity is not established by the debugger session identifier.", - `The GDB command exceeded its ${String(acceptedDeadline.value)} ms deadline (deadlineExpired). ${debuggerAdmissionRecovery(acceptedDeadline)} Retained MI and stream records are partial and command completion is unknown.`, - ...gdbRetainedOutputLimitations(partial, acceptedOutput), - "Cleanup of the owned GDB process was requested because output correlation could no longer be guaranteed.", - "The unrestricted GDB console can access local shell, filesystem, network, and target controls.", - ], + const evidence = createGdbSessionEvidence(session, { + predicateType: + operation === "start_gdb_session" + ? "rea.debugger.startup-observation" + : "rea.debugger.console-observation", + operation, + parameters: { + session_id: session.id, + command: pending.evidenceCommand, }, - ); + result: { ...partial, records: [...partial.records] }, + rawResult: { ...partial, records: [...partial.records] }, + limitations: [ + "The active GDB inferior identity is not established by the debugger session identifier.", + `The GDB command exceeded its ${String(acceptedDeadline.value)} ms deadline (deadlineExpired). ${debuggerAdmissionRecovery(acceptedDeadline)} Retained MI and stream records are partial and command completion is unknown.`, + ...gdbRetainedOutputLimitations(partial, acceptedOutput), + "Cleanup of the owned GDB process was requested because output correlation could no longer be guaranteed.", + "The unrestricted GDB console can access local shell, filesystem, network, and target controls.", + ], + }); void this.#stopDebuggerOnly(session).then((stopped) => { if ( stopped.status === "incomplete" && @@ -2102,27 +2223,26 @@ export class GdbSessionManager { : {}), completion_status: "unknown", }; - const evidence = createEvidence( - gdbSessionSubject(session), - session.provider, - { - predicateType: "rea.debugger.console-observation", - operation: "gdb_console", - parameters: { - session_id: session.id, - command: pending.evidenceCommand, - }, - result: { ...partial, records: [...partial.records] }, - rawResult: { ...partial, records: [...partial.records] }, - limitations: [ - "The active GDB inferior identity is not established by the debugger session identifier.", - "The GDB command was cancelled; retained MI records are partial and command completion is unknown.", - ...gdbRetainedOutputLimitations(partial, acceptedOutput), - "Shutdown of the owned GDB process was requested because output correlation could no longer be guaranteed.", - "The unrestricted GDB console can access local shell, filesystem, network, and target controls.", - ], + const evidence = createGdbSessionEvidence(session, { + predicateType: + operation === "start_gdb_session" + ? "rea.debugger.startup-observation" + : "rea.debugger.console-observation", + operation, + parameters: { + session_id: session.id, + command: pending.evidenceCommand, }, - ); + result: { ...partial, records: [...partial.records] }, + rawResult: { ...partial, records: [...partial.records] }, + limitations: [ + "The active GDB inferior identity is not established by the debugger session identifier.", + "The GDB command was cancelled; retained MI records are partial and command completion is unknown.", + ...gdbRetainedOutputLimitations(partial, acceptedOutput), + "Shutdown of the owned GDB process was requested because output correlation could no longer be guaranteed.", + "The unrestricted GDB console can access local shell, filesystem, network, and target controls.", + ], + }); session.pending.delete(token); session.protocolError = { code: "command-cancelled", @@ -2132,24 +2252,24 @@ export class GdbSessionManager { void this.#stopDebuggerOnly(session).then((stopped) => { if (stopped.status !== "incomplete") { pending.reject( - cancelledBy("gdb_console", carriedReason(signal?.reason), { + cancelledBy(operation, carriedReason(signal?.reason), { partialObservation: evidence, }), ); return; } - const cancellation = new AnalysisCancelledError("gdb_console", { + const cancellation = new AnalysisCancelledError(operation, { cause: signal?.reason, partialObservation: evidence, }); const cleanupFailure = this.#sessions.retainCleanupFailure( session, - "gdb_console", + operation, stopped, { cause: cancellation }, ); pending.reject( - cancelledBy("gdb_console", carriedReason(signal?.reason), { + cancelledBy(operation, carriedReason(signal?.reason), { ...incompleteStopFacts(stopped, [session.id]), partialObservation: evidence, }).bindCleanupDependencies([cleanupFailure], { diff --git a/src/process/DebuggerLaunchFile.ts b/src/process/DebuggerLaunchFile.ts new file mode 100644 index 0000000000..ce76c4161b --- /dev/null +++ b/src/process/DebuggerLaunchFile.ts @@ -0,0 +1,140 @@ +import type { AnalysisError } from "../domain/analysisErrorBase.js"; +import { analysisErrorWithCleanupFailure } from "../domain/analysisErrorCleanup.js"; +import { cancelledBy, carriedReason } from "../domain/analysisErrorCore.js"; +import { ProviderCleanupError } from "../domain/providerCleanupError.js"; +import { err, ok, type Result } from "../domain/result.js"; +import { jsonValueSchema } from "../domain/jsonValue.js"; +import { + unknownTarget, + type FileTargetIdentity, + type UnknownTargetIdentity, +} from "../domain/targetIdentity.js"; +import { + RegularFileCleanupFailure, + RegularFileCancelled, + regularFileCancellation, +} from "../filesystem/OwnedRegularFile.js"; +import { + hashStableFile, + stableFileHashCause, +} from "../filesystem/StableFileHash.js"; +import { errorMessage } from "../kernel/errorMessage.js"; +import { + AnalysisCleanupLease, + bindArtifactFileCleanup, + type ArtifactResourceScope, +} from "../resources/index.js"; + +/** Initial file identity; later debugger commands do not rebind it. */ +export interface DebuggerLaunchFileObservation { + readonly identity: FileTargetIdentity | UnknownTargetIdentity; + readonly unobservedReason?: string; +} + +interface DebuggerStartupFileContext { + readonly provider: string; + readonly operation: string; + readonly resources: ArtifactResourceScope; +} + +/** Retry the exact failed file owners before admitting another startup. */ +export const retryDebuggerStartupFileCleanup = async ({ + provider, + operation, + resources, +}: DebuggerStartupFileContext): Promise> => { + try { + await resources.retryCleanup(); + return ok(null); + } catch (cause: unknown) { + const failure = new ProviderCleanupError( + provider, + resources.cleanupResources, + {}, + { operation, cause }, + ); + bindArtifactFileCleanup(cause, failure); + return err(failure); + } +}; + +/** + * Observe the selected file once before loading it. Physical hash failures + * preserve unknown identity and their reason. Cancellation and outstanding + * descriptor cleanup fail startup; the caller's scope retains failed closes. + */ +export const observeDebuggerLaunchFile = async ( + path: string, + { + provider, + operation, + resources, + signal, + }: DebuggerStartupFileContext & { + readonly signal?: AbortSignal | undefined; + }, +): Promise> => { + let lease: AnalysisCleanupLease | undefined; + try { + const { sha256 } = await hashStableFile(path, { + ...(signal === undefined ? {} : { signal }), + retainFailedClose: (owner) => { + lease = new AnalysisCleanupLease(() => owner.close(), [path]); + resources.retain({ kind: "lease", resource: path, lease }); + }, + }); + return ok({ + identity: { + kind: "file", + sha256, + format: "file", + architecture: null, + selection: null, + }, + }); + } catch (cause: unknown) { + const outcome = + cause instanceof RegularFileCancelled || + cause instanceof RegularFileCleanupFailure + ? cause.outcome + : undefined; + const completed = + outcome?.kind === "completed" + ? { completed_hash: jsonValueSchema.parse(outcome.value) } + : undefined; + const cancellation = regularFileCancellation(cause); + const cancelled = + cancellation === undefined + ? undefined + : cancelledBy(operation, carriedReason(cancellation.reason), { + diagnostics: completed, + }); + const describe = (failure: unknown): string => + errorMessage(stableFileHashCause(failure)); + if (!(cause instanceof RegularFileCleanupFailure)) { + if (cancelled !== undefined) return err(cancelled); + return ok({ + identity: unknownTarget("not-observed"), + unobservedReason: describe(cause), + }); + } + const cleanup = new ProviderCleanupError( + provider, + [path], + { + ...completed, + ...(cause.outcome.kind === "failed" && cancelled === undefined + ? { launch_file_hash_failure: describe(cause.outcome.cause) } + : {}), + }, + { operation, cause: cause.cleanupCause }, + ); + const failure = + cancelled === undefined + ? cleanup + : analysisErrorWithCleanupFailure(cancelled, cleanup, operation); + lease?.bindCleanupError(cleanup); + if (failure !== cleanup) lease?.bindCleanupError(failure); + return err(failure); + } +}; diff --git a/src/rizin/RizinDebugSessionManager.ts b/src/rizin/RizinDebugSessionManager.ts index 151b110c41..ac47aae3fa 100644 --- a/src/rizin/RizinDebugSessionManager.ts +++ b/src/rizin/RizinDebugSessionManager.ts @@ -1,12 +1,8 @@ import { - unknownTarget, - type FileTargetIdentity, - type UnknownTargetIdentity, -} from "../domain/targetIdentity.js"; -import { - hashStableFile, - stableFileHashCause, -} from "../filesystem/StableFileHash.js"; + observeDebuggerLaunchFile, + retryDebuggerStartupFileCleanup, + type DebuggerLaunchFileObservation, +} from "../process/DebuggerLaunchFile.js"; import { readRuntimeSetting } from "../config/runtimeAnalysisSettings.js"; import { RIZIN_DEBUGGER_PROVIDER_IDENTITY } from "./RizinDebuggerProviderIdentity.js"; import { persistentDebuggerHostSupported } from "../process/PersistentDebuggerHost.js"; @@ -19,7 +15,6 @@ import { isatty } from "node:tty"; import { ArtifactResourceScope, AnalysisCleanupLease, - bindArtifactFileCleanup, } from "../resources/index.js"; import { OwnedFileHandle } from "../filesystem/OwnedFileHandle.js"; import { @@ -103,16 +98,6 @@ interface RizinLaunchProvenance { readonly resolved_path: string; } -/** - * The session's launch file, hashed before Rizin started. A hash failure - * other than cleanup or cancellation leaves the target unknown, with the - * failure retained as a limitation. - */ -interface RizinLaunchTarget { - readonly identity: FileTargetIdentity | UnknownTargetIdentity; - readonly unobservedReason?: string; -} - const RIZIN_SESSION_TARGET_LIMITATION = "The session target is the launch file hashed at session start; later debugger commands do not rebind it."; @@ -125,7 +110,7 @@ interface RizinCommandEvidenceInput { readonly result: RizinDebugCommandResult; readonly inferiorTty: string; readonly launchProvenance: RizinLaunchProvenance; - readonly launchTarget: RizinLaunchTarget; + readonly launchTarget: DebuggerLaunchFileObservation; readonly limitations: readonly string[]; } @@ -207,7 +192,7 @@ interface RizinCommandTimeoutEvidenceInput { readonly inferiorTty: string; readonly cleanupFailure: string | undefined; readonly launchProvenance: RizinLaunchProvenance; - readonly launchTarget: RizinLaunchTarget; + readonly launchTarget: DebuggerLaunchFileObservation; readonly deadline: DebuggerAdmissionLimit; } @@ -265,7 +250,7 @@ interface RizinDebugSession { }>; readonly backend: string | null; readonly launchProvenance: RizinLaunchProvenance; - readonly launchTarget: RizinLaunchTarget; + readonly launchTarget: DebuggerLaunchFileObservation; readonly inferiorTty: string; readonly inferiorTtyDevice: number; readonly inferiorTtyInode: number; @@ -409,73 +394,6 @@ export class RizinDebugSessionManager { return parsed.value; } - /** - * Hash the launch file before Rizin starts, so the session names the file - * it launched. Cleanup failure and cancellation fail the start; any other - * hash failure leaves the target unknown and keeps its reason. - */ - async #observeLaunchFile( - path: string, - signal: AbortSignal | undefined, - ): Promise> { - const operation = "start_rizin_debug_session"; - let lease: AnalysisCleanupLease | undefined; - try { - const { sha256 } = await hashStableFile(path, { - ...(signal === undefined ? {} : { signal }), - retainFailedClose: (owner) => { - lease = new AnalysisCleanupLease(() => owner.close(), [path]); - this.#startupResources.retain({ - kind: "lease", - resource: path, - lease, - }); - }, - }); - return ok({ - identity: { - kind: "file", - sha256, - format: "file", - architecture: null, - selection: null, - }, - }); - } catch (cause: unknown) { - const cancellation = regularFileCancellation(cause); - const cancelled = - cancellation === undefined - ? undefined - : cancelledBy(operation, carriedReason(cancellation.reason)); - const describe = (failure: unknown): string => - errorMessage(stableFileHashCause(failure)); - if (!(cause instanceof RegularFileCleanupFailure)) { - if (cancelled !== undefined) return err(cancelled); - return ok({ - identity: unknownTarget("not-observed"), - unobservedReason: describe(cause), - }); - } - // The close failure fails the start; a read failure beside it stays - // in the error, since the retained lease only retries the close. - const cleanup = new ProviderCleanupError( - "rizin", - [path], - cause.outcome.kind === "failed" && cancelled === undefined - ? { launch_file_hash_failure: describe(cause.outcome.cause) } - : {}, - { operation, cause: cause.cleanupCause }, - ); - const error = - cancelled === undefined - ? cleanup - : analysisErrorWithCleanupFailure(cancelled, cleanup, operation); - lease?.bindCleanupError(cleanup); - if (error !== cleanup) lease?.bindCleanupError(error); - return err(error); - } - } - async start( input: { readonly path: string; @@ -562,18 +480,12 @@ export class RizinDebugSessionManager { let ttyDevice: number; let ttyInode: number; let ttyLease: AnalysisCleanupLease | undefined; - try { - await this.#startupResources.retryCleanup(); - } catch (cause: unknown) { - const cleanup = new ProviderCleanupError( - "rizin", - this.#startupResources.cleanupResources, - {}, - { operation: "start_rizin_debug_session", cause }, - ); - bindArtifactFileCleanup(cause, cleanup); - return err(cleanup); - } + const files = await retryDebuggerStartupFileCleanup({ + provider: "rizin", + operation: "start_rizin_debug_session", + resources: this.#startupResources, + }); + if (!files.ok) return files; try { ttyPath = await realpath(input.inferior_tty); const ttyHandle = await open( @@ -664,7 +576,12 @@ export class RizinDebugSessionManager { caller_selected_path: input.path, resolved_path: resolvedPath, }; - const launchTarget = await this.#observeLaunchFile(resolvedPath, signal); + const launchTarget = await observeDebuggerLaunchFile(resolvedPath, { + provider: "rizin", + operation: "start_rizin_debug_session", + resources: this.#startupResources, + signal, + }); if (!launchTarget.ok) return launchTarget; if (signal?.aborted) return err(cancelledBy("start_rizin_debug_session", signal)); @@ -1341,21 +1258,12 @@ export class RizinDebugSessionManager { } async retryCleanupFailures(): Promise> { - try { - await this.#startupResources.retryCleanup(); - } catch (cause: unknown) { - const error = new ProviderCleanupError( - "rizin", - this.#startupResources.cleanupResources, - {}, - { - operation: "start_rizin_debug_session", - cause, - }, - ); - bindArtifactFileCleanup(cause, error); - return err(error); - } + const files = await retryDebuggerStartupFileCleanup({ + provider: "rizin", + operation: "start_rizin_debug_session", + resources: this.#startupResources, + }); + if (!files.ok) return files; return this.#sessions.retryCleanupFailures( (session) => session.published && !session.closeRequested, ); diff --git a/src/server/serviceToolBindings.ts b/src/server/serviceToolBindings.ts index cda5eea33f..1a30053c0e 100644 --- a/src/server/serviceToolBindings.ts +++ b/src/server/serviceToolBindings.ts @@ -1446,19 +1446,21 @@ const SERVICE_TOOL_BINDINGS = { }, }; }) satisfies Bind, - // Starting GDB loads no target, so it runs outside admission; a console + // Starting GDB may load a selected file without running it, outside mutation admission; a console // command may change the bound artifact and runs under external-mutation // admission, keeping a failed cleanup owned for the next retry. gdb: (({ manager, session }) => ({ start_gdb_session: { admission: "sdk", value: (input, { signal }) => - manager.start( - signal, - input.inferior_tty === undefined + manager.start(signal, { + ...(input.inferior_tty === undefined ? {} - : { inferiorTty: input.inferior_tty }, - ), + : { inferiorTty: input.inferior_tty }), + ...(input.executable === undefined + ? {} + : { executable: input.executable }), + }), }, gdb_console: { admission: "sdk", diff --git a/tests/boundary/mcp/gdbExecutableSelection.test.ts b/tests/boundary/mcp/gdbExecutableSelection.test.ts new file mode 100644 index 0000000000..d169290139 --- /dev/null +++ b/tests/boundary/mcp/gdbExecutableSelection.test.ts @@ -0,0 +1,393 @@ +import { createHash } from "node:crypto"; +import { chmod, mkdtemp, readFile, rm, writeFile } from "node:fs/promises"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; + +import { Client, InMemoryTransport } from "@modelcontextprotocol/client"; +import { Ajv2020 } from "ajv/dist/2020.js"; +import { expect, it, onTestFinished } from "vitest"; +import { z } from "zod"; + +import { closeVerifierResources } from "../../../scripts/lib/verifier-cleanup.mjs"; +import { evidenceSchema } from "../../../src/domain/evidence.js"; +import { advertisedInputDialectViolations } from "../../../src/contracts/advertisedDialect.js"; +import { createCliShell } from "../../../src/cli/cliShell.js"; +import { plain } from "../../../src/cli/cliCommandRegistration.js"; +import { registerReverseEngineeringCommands } from "../../../src/cli/reverseEngineeringCommands.js"; +import { serveInProcessCli } from "../../support/cli/serveInProcessCli.js"; +import { phaseGate } from "../../support/lifecycleHarness.js"; +import { GdbSessionManager } from "../../../src/gdb/GdbSessionManager.js"; +import { stopOwnedDebuggerProcess } from "../../../src/process/ownedDebuggerSession.js"; +import { gdbMcpServer } from "../../fixtures/debuggerMcp.js"; +import { createMcpSchemaValidation } from "../../fixtures/mcpSchemaValidation.js"; +import { parseMcpToolError } from "../../fixtures/mcpToolError.js"; +import { waitForStartedFile } from "../../support/reverseDebuggerMcpTestHelpers.js"; +import { + createGdbFixtureOwner, + expectNoUnmodeledGdbCommands, + FAKE_GDB_SESSION_REPLIES, + fakeGdbModeledReplies, + fakeGdbStartupPreamble, +} from "../providers/gdbTestHelpers.js"; + +const selectedBytes = Buffer.from("caller-selected executable bytes\n"); +const selectedDigest = createHash("sha256").update(selectedBytes).digest("hex"); +const startSchema = z.object({ session_id: z.string().uuid() }); + +it.skipIf(process.platform === "win32")( + "loads the selected file through the public one-shot CLI", + async () => { + const f = await fixture("load"); + const registration = plain( + async () => registerReverseEngineeringCommands, + (register, context) => + register( + context.cli, + context.logger, + context.environment, + () => f.manager, + ), + ); + const cli = createCliShell({ + selectedEnvironment: { CI: "1" }, + registrations: [ + { registration, module: registerReverseEngineeringCommands }, + ], + }); + const reply = await serveInProcessCli(cli, [ + "debug-with-gdb", + "info files", + "--executable", + f.executable, + "--inferior-tty", + f.tty, + "--json", + ]); + expect(reply.exitCode).toBe(0); + const evidence = evidenceSchema.parse(JSON.parse(reply.stdout)); + expect(evidence.subject.identity).toMatchObject({ + kind: "session", + target: { kind: "file", sha256: selectedDigest }, + }); + expect(evidence.parameters.launch_provenance).toMatchObject({ + caller_selected_path: f.executable, + }); + expect(await f.requests()).toContain(f.load); + }, +); + +it.skipIf(process.platform === "win32")( + "does not retry a refused executable load after confirmed cleanup", + async () => { + const f = await fixture("refuse"); + const reply = await f.client.callTool({ + name: "start_gdb_session", + arguments: { executable: f.executable }, + }); + expect(parseMcpToolError(reply).error.code).toBe("capability_unavailable"); + expect( + (await f.requests()).filter((command) => command === f.load), + ).toHaveLength(1); + }, +); + +it.skipIf(process.platform === "win32")( + "ignores late load completion when caller cancellation overlaps manager-close cleanup", + async () => { + const cleanup = phaseGate(); + const f = await fixture("wait", { + stopProcess: async (session, name) => { + await cleanup.hold(); + return stopOwnedDebuggerProcess(session, name); + }, + }); + const caller = new AbortController(); + const lateReason = { reason: "late caller cancellation" }; + const starting = f.manager.start(caller.signal, { + executable: f.executable, + }); + let closing: Promise | undefined; + try { + await waitForStartedFile(f.arrived); + closing = f.manager.closeAll(); + await cleanup.reached(starting, "GDB load cleanup"); + caller.abort(lateReason); + await writeFile(f.release, "release"); + await waitForStartedFile(f.lateAck); + cleanup.release(); + const result = await starting; + expect(result.ok).toBe(false); + if (result.ok) + throw new Error("Late load completion published a session"); + expect(result.error._tag).toBe("AnalysisCancelledError"); + expect(result.error.cause).not.toBe(lateReason); + expect(result.error.partialObservation).toMatchObject({ + operation: "start_gdb_session", + }); + await closing; + } finally { + cleanup.release(); + await starting; + await closing; + } + }, +); + +/** The fake acknowledges only modeled MI operations, and never runs an inferior. */ +const fixture = async ( + mode: "load" | "refuse" | "wait", + options: Pick< + NonNullable[0]>, + "stopProcess" + > = {}, +) => { + const root = await mkdtemp(join(tmpdir(), "rea-gdb-selected-file-")); + const owner = createGdbFixtureOwner(); + const managers: GdbSessionManager[] = []; + const connections: Array<() => void | Promise> = []; + const unmodeled = join(root, "unmodeled"); + onTestFinished(() => + closeVerifierResources([ + ...connections, + () => + owner.cleanup(managers, async () => { + try { + await expectNoUnmodeledGdbCommands(unmodeled); + } finally { + await rm(root, { recursive: true, force: true }); + } + }), + ]), + ); + const executable = join(root, 'selected "file".bin'); + await writeFile(executable, selectedBytes); + const requests = join(root, "requests.jsonl"); + const arrived = join(root, "load.arrived"); + const release = join(root, "load.release"); + const lateAck = join(root, "load.replied"); + const tty = join(root, "inferior-tty"); + const provider = join(root, "fake-gdb.mjs"); + const load = `-file-exec-and-symbols ${JSON.stringify(executable)}`; + await writeFile( + provider, + `#!${process.execPath} +${fakeGdbStartupPreamble} +${fakeGdbModeledReplies(unmodeled, { + ...FAKE_GDB_SESSION_REPLIES, + [`-inferior-tty-set ${JSON.stringify(tty)}`]: "^done", + "-inferior-tty-show": `^done,inferior_tty_terminal=${JSON.stringify(tty)}`, + '-interpreter-exec console "info files"': "^done", + '-interpreter-exec console "file /other/file"': "^done", +})} +const fs = process.getBuiltinModule("node:fs"); +process.stdout.write("(gdb)\\n"); +let input = ""; +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); + const parsed = /^(\\d+)(.*)$/.exec(line); + if (!parsed) continue; + const [, token, command] = parsed; + fs.appendFileSync(${JSON.stringify(requests)}, JSON.stringify(command) + "\\n"); + if (command === ${JSON.stringify(load)}) { + if (${JSON.stringify(mode)} === "wait") { + const watcher = fs.watch(${JSON.stringify(root)}, () => { + if (!fs.existsSync(${JSON.stringify(release)})) return; + watcher.close(); + process.stdout.write(token + "^done\\n"); + fs.writeFileSync(${JSON.stringify(lateAck)}, "started"); + }); + } + fs.writeFileSync(${JSON.stringify(arrived)}, "started"); + if (${JSON.stringify(mode)} !== "wait") + process.stdout.write(token + (${JSON.stringify(mode)} === "refuse" ? '^error,msg="load refused"' : "^done") + "\\n"); + } else answerModeled(token, command); + } +}); +`, + ); + await chmod(provider, 0o700); + const manager = new GdbSessionManager({ + platform: "linux", + environment: { REA_GDB_COMMAND: provider }, + spawnProcess: owner.spawnProcess, + ...options, + }); + managers.push(manager); + const server = gdbMcpServer("gdb-executable-selection", manager); + const validation = createMcpSchemaValidation(); + const client = new Client( + { name: "gdb-executable-selection", version: "1" }, + { jsonSchemaValidator: validation }, + ); + connections.push( + () => client.close(), + () => server.close(), + async () => validation.clear(), + ); + const [clientTransport, serverTransport] = + InMemoryTransport.createLinkedPair(); + await server.connect(serverTransport); + await client.connect(clientTransport); + return { + client, + manager, + executable, + load, + arrived, + release, + lateAck, + tty, + requests: async (): Promise => + (await readFile(requests, "utf8")) + .trim() + .split("\n") + .map((line) => z.string().parse(JSON.parse(line))), + }; +}; + +it.skipIf(process.platform === "win32")( + "binds MCP command Evidence to the selected initial file without running or rebinding it", + async () => { + const f = await fixture("load"); + const listed = (await f.client.listTools()).tools.find( + ({ name }) => name === "start_gdb_session", + ); + expect(listed?.inputSchema.properties).toHaveProperty("executable"); + if (listed === undefined) + throw new Error("GDB startup contract is missing"); + expect(advertisedInputDialectViolations(listed)).toEqual([]); + const validate = new Ajv2020({ + strict: false, + validateFormats: false, + }).compile(listed.inputSchema); + expect(validate({})).toBe(true); + expect(validate({ executable: f.executable })).toBe(true); + expect(validate({ executable: 42 })).toBe(false); + expect(validate({ executable: f.executable, unexpected: true })).toBe( + false, + ); + // Advertised patterns may widen; canonical admission must still refuse + // a relative path before any debugger operation is sent. + const invalid = await f.client.callTool({ + name: "start_gdb_session", + arguments: { executable: "relative-file" }, + }); + expect(invalid.isError).toBe(true); + await expect(f.requests()).rejects.toMatchObject({ code: "ENOENT" }); + const started = await f.client.callTool({ + name: "start_gdb_session", + arguments: { executable: f.executable }, + }); + expect(started.isError).not.toBe(true); + const { session_id } = startSchema.parse(started.structuredContent); + const before = await f.requests(); + expect(before).toEqual(["-gdb-set auto-load off", f.load]); + for (const command of ["info files", "file /other/file", "info files"]) { + const reply = await f.client.callTool({ + name: "gdb_console", + arguments: { session_id, command }, + }); + expect(reply.isError).not.toBe(true); + const evidence = evidenceSchema.parse(reply.structuredContent); + expect(evidence.subject.identity).toEqual({ + kind: "session", + session_kind: "gdb", + id: session_id, + target: { + kind: "file", + sha256: selectedDigest, + format: "file", + architecture: null, + selection: null, + }, + }); + expect(evidence.parameters).toMatchObject({ + launch_provenance: { + caller_selected_path: f.executable, + resolved_path: f.executable, + }, + }); + } + }, +); + +it.skipIf(process.platform === "win32")( + "keeps an omitted GDB executable unknown", + async () => { + const f = await fixture("load"); + const started = await f.client.callTool({ + name: "start_gdb_session", + arguments: {}, + }); + const { session_id } = startSchema.parse(started.structuredContent); + const reply = await f.client.callTool({ + name: "gdb_console", + arguments: { session_id, command: "info files" }, + }); + const evidence = evidenceSchema.parse(reply.structuredContent); + expect(evidence.subject.identity).toMatchObject({ + target: { kind: "unknown", reason: "not-observed" }, + }); + expect(evidence.parameters).not.toHaveProperty("launch_provenance"); + expect(await f.requests()).not.toContain(f.load); + }, +); + +it.skipIf(process.platform === "win32")( + "retains failed startup cleanup after a refused load for retry", + async () => { + let stops = 0; + const f = await fixture("refuse", { + stopProcess: async (session, name) => + ++stops === 1 + ? { + status: "incomplete", + code: "stop-failed", + reason: "injected load cleanup uncertainty", + } + : stopOwnedDebuggerProcess(session, name), + }); + const reply = await f.client.callTool({ + name: "start_gdb_session", + arguments: { executable: f.executable }, + }); + const failure = parseMcpToolError(reply); + expect(failure.error).toMatchObject({ code: "cleanup_incomplete" }); + const details = z + .object({ resources: z.tuple([z.string().uuid()]) }) + .parse(failure.error.details); + expect(f.manager.status(details.resources[0])?.state).toBe("closed"); + expect( + (await f.requests()).filter((command) => command === f.load), + ).toHaveLength(1); + const retry = await f.manager.retryCleanupFailures(); + expect(retry.ok).toBe(true); + expect(f.manager.status(details.resources[0])).toBeUndefined(); + expect(stops).toBe(2); + }, +); + +it.skipIf(process.platform === "win32")( + "cancels during executable loading before publishing readiness", + async () => { + const f = await fixture("wait"); + const controller = new AbortController(); + const starting = f.manager.start(controller.signal, { + executable: f.executable, + }); + await waitForStartedFile(f.arrived); + controller.abort("cancel-selected-load"); + const result = await starting; + expect(result.ok).toBe(false); + if (result.ok) throw new Error("Cancelled load published a session"); + expect(result.error._tag).toBe("AnalysisCancelledError"); + expect( + (await f.requests()).filter((command) => command === f.load), + ).toHaveLength(1); + await f.manager.closeAll(); + }, +); diff --git a/tests/boundary/providers/GdbSessionReviewRegressions.test.ts b/tests/boundary/providers/GdbSessionReviewRegressions.test.ts index dc4173c330..63e95edd4b 100644 --- a/tests/boundary/providers/GdbSessionReviewRegressions.test.ts +++ b/tests/boundary/providers/GdbSessionReviewRegressions.test.ts @@ -13,6 +13,7 @@ import { delimiter, join } from "node:path"; import { afterEach, expect, it } from "vitest"; import { GdbSessionManager } from "../../../src/gdb/GdbSessionManager.js"; +import { AnalysisSettings } from "../../../src/application/AnalysisSettings.js"; import { evidenceSchema } from "../../../src/domain/evidence.js"; import { cleanupOwnedProcessGroup } from "../../../src/process/ProcessOwnership.js"; import { spawnOwnedProviderProcess } from "../../../src/process/ProviderProcess.js"; @@ -451,8 +452,11 @@ it.skipIf(process.platform === "win32")( `#!${process.execPath} ${fakeGdbStartupPreamble} import { readFile, writeFile } from "node:fs/promises"; +import { writeFileSync } from "node:fs"; process.on("SIGTERM", async () => { - await writeFile(${JSON.stringify(signalPath)}, "SIGTERM"); + // Publish the signal before yielding: bounded stop may end this fake + // while an asynchronous write has created but not populated its file. + writeFileSync(${JSON.stringify(signalPath)}, "SIGTERM"); while (true) { try { await readFile(${JSON.stringify(releasePath)}, "utf8"); @@ -589,7 +593,6 @@ process.stdin.on("data", (chunk) => { else if (match) process.stdout.write("~\\"partial output\\n\\"\\n"); } }); -setTimeout(() => process.exit(0), 250).unref(); `, ); await chmod(provider, 0o700); @@ -600,7 +603,20 @@ setTimeout(() => process.exit(0), 250).unref(); }, }); managers.push(manager); - const started = await manager.start(); + // The 40 ms budget exercises the console timeout, not provider startup. + const startup = new AnalysisSettings({}); + expect( + startup.update({ + changes: [ + { + setting: "debugger.command_deadline_ms", + action: "set", + value: 5000, + }, + ], + }).ok, + ).toBe(true); + const started = await startup.run(() => manager.start()); expect(started.ok).toBe(true); if (!started.ok) return; @@ -621,6 +637,9 @@ setTimeout(() => process.exit(0), 250).unref(); }); expect(result.error.cleanupIncomplete).toBe(true); } + // Only the fixture knows this provider has no real inferior. Stop it after + // asserting the production cleanup uncertainty instead of racing an exit timer. + await fixtureOwner.cleanup(managers, async () => {}); await expectOwnedProcessExited( await waitForTestPidFile(join(directory, "pid"), 1_000), ); diff --git a/tests/boundary/providers/RizinTtyCleanup.test.ts b/tests/boundary/providers/RizinTtyCleanup.test.ts index 29909184e7..2d462055ad 100644 --- a/tests/boundary/providers/RizinTtyCleanup.test.ts +++ b/tests/boundary/providers/RizinTtyCleanup.test.ts @@ -1,9 +1,13 @@ import { isatty } from "node:tty"; import { open } from "node:fs/promises"; import { join } from "node:path"; +import { createHash } from "node:crypto"; import { expect, it, onTestFinished, vi } from "vitest"; import { createInjectedProcess } from "./RizinDebugSessionCoverage.fixtures.js"; import { createTestTempDirectory } from "../../fixtures/temporaryDirectory.js"; +import { GdbSessionManager } from "../../../src/gdb/GdbSessionManager.js"; +import { resolvedAnalysisError } from "../../../src/domain/analysisErrorBase.js"; +import { projectAnalysisError } from "../../../src/domain/analysisErrorProjection.js"; import { RizinDebugSessionManager } from "../../../src/rizin/RizinDebugSessionManager.js"; vi.mock("node:tty", async (importOriginal) => { @@ -240,9 +244,9 @@ it.skipIf(process.platform === "win32")( }, ); -it.skipIf(process.platform === "win32")( - "keeps the launch file read failure when its descriptor close also fails", - async () => { +it.skipIf(process.platform === "win32").each(["rizin", "gdb"] as const)( + "keeps the %s launch file read failure when its descriptor close also fails", + async (provider) => { const actual = await vi.importActual( "node:fs/promises", @@ -275,20 +279,21 @@ it.skipIf(process.platform === "win32")( vi.restoreAllMocks(); }); let spawned = false; - const manager = new RizinDebugSessionManager( - {}, - { - platform: "linux", - spawnProcess: () => { - spawned = true; - throw new Error("must not spawn after a failed close"); - }, + const options = { + platform: "linux" as const, + spawnProcess: () => { + spawned = true; + throw new Error("must not spawn after a failed close"); }, - ); - const result = await manager.start({ - path: launchFile, - inferior_tty: "/dev/null", - }); + }; + const manager = + provider === "rizin" + ? new RizinDebugSessionManager({}, options) + : new GdbSessionManager(options); + const result = + manager instanceof GdbSessionManager + ? await manager.start(undefined, { executable: launchFile }) + : await manager.start({ path: launchFile, inferior_tty: "/dev/null" }); if (result.ok) throw new Error("expected the failed close to fail start"); expect(spawned, "a retained descriptor fails the start").toBe(false); expect(result.error.cleanupIncomplete).toBe(true); @@ -308,3 +313,97 @@ it.skipIf(process.platform === "win32")( await manager.closeAll(); }, ); + +it.skipIf(process.platform === "win32").each( + (["rizin", "gdb"] as const).flatMap((provider) => + [ + { cancel: false, closeFails: true }, + { cancel: true, closeFails: false }, + { cancel: true, closeFails: true }, + ].map((scenario) => ({ provider, ...scenario })), + ), +)( + "preserves a completed $provider launch hash (cancel: $cancel, close fails: $closeFails)", + async ({ provider, cancel, closeFails }) => { + const actual = + await vi.importActual( + "node:fs/promises", + ); + const actualTty = + await vi.importActual("node:tty"); + vi.mocked(isatty).mockReturnValue(true); + const directory = await createTestTempDirectory("rea-debugger-hash-close-"); + const launchFile = join(directory, "target.bin"); + const contents = "completed launch-file observation"; + await actual.writeFile(launchFile, contents); + const completed = { + completed_hash: { + sha256: createHash("sha256").update(contents).digest("hex"), + bytes: Buffer.byteLength(contents), + }, + }; + const controller = new AbortController(); + const reason = { cancelled: "after launch hash" }; + let allowClose = false; + let releaseFixture: (() => Promise) | undefined; + vi.mocked(open).mockImplementation(async (...args) => { + const handle = await actual.open(...args); + if (args[0] !== launchFile) return handle; + const close = handle.close.bind(handle); + releaseFixture = close; + vi.spyOn(handle, "close").mockImplementation(async () => { + if (!allowClose && closeFails) { + if (cancel) controller.abort(reason); + throw new Error("launch file close refused"); + } + await close(); + if (cancel) controller.abort(reason); + }); + return handle; + }); + onTestFinished(async () => { + await releaseFixture?.().catch(() => undefined); + vi.restoreAllMocks(); + vi.mocked(isatty).mockImplementation(actualTty.isatty); + }); + const options = { + platform: "linux" as const, + spawnProcess: vi.fn(() => { + throw new Error("must not spawn before file observation settles"); + }), + }; + const manager = + provider === "rizin" + ? new RizinDebugSessionManager({}, options) + : new GdbSessionManager(options); + const result = + manager instanceof GdbSessionManager + ? await manager.start(controller.signal, { executable: launchFile }) + : await manager.start( + { path: launchFile, inferior_tty: "/dev/null" }, + controller.signal, + ); + if (result.ok) throw new Error("expected finalization to fail startup"); + expect(options.spawnProcess).not.toHaveBeenCalled(); + expect(result.error.cleanupIncomplete).toBe(closeFails); + const observed = result.error.cleanupPrimary ?? result.error; + expect(observed.diagnostics).toMatchObject(completed); + expect(projectAnalysisError(observed).details?.diagnostics).toMatchObject( + completed, + ); + if (cancel) { + expect(observed._tag).toBe("AnalysisCancelledError"); + expect(observed.cause).toBe(reason); + } + allowClose = true; + expect((await manager.retryCleanupFailures()).ok).toBe(true); + expect(result.error.cleanupIncomplete).toBe(false); + expect(resolvedAnalysisError(result.error).diagnostics).toMatchObject( + completed, + ); + expect( + projectAnalysisError(result.error).details?.diagnostics, + ).toMatchObject(completed); + await manager.closeAll(); + }, +);