Skip to content

fix(gdb): terminate owned debugger process on protocol line overflow and sync loss - #8091

Open
highmachs wants to merge 5 commits into
morluto:mainfrom
highmachs:fix/gdb-line-overflow-teardown
Open

highmachs wants to merge 5 commits into
morluto:mainfrom
highmachs:fix/gdb-line-overflow-teardown

Conversation

@highmachs

@highmachs highmachs commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Fixes #8023.

When GDB emits an MI line exceeding the 16 MiB protocol limit, REA fails the protocol and marks MI synchronization lost. Attempting inferior detachment over the desynchronized MI transport throws and previously aborted process termination in stopOwnedDebuggerProcess, leaving GDB and its inferior processes alive indefinitely as zombies with no way to detach, kill, or close them.

This change:

  1. Adds force?: boolean option to stopOwnedDebuggerProcess to terminate the owned debugger process immediately with SIGTERM/SIGKILL when detachment cannot be verified or MI state is desynchronized.
  2. Clears line accumulator buffers (bufferChunks, bufferTail, bufferBytes) immediately on overflow in GdbSessionManager to release retained memory.
  3. Automatically uses forced shutdown when MI synchronization is lost or during close_gdb_session of a failed session, while preserving detach verification on normal sessions.
  4. Releases unreferenced output streams on supervisor timeout during forced shutdown so REA does not hang on background descendants.
  5. Records forced debugger shutdowns in forcedShutdowns to permit subsequent close calls on already-exited sessions without failing on inferior verification.
  6. Surfaces informative top-level guidance with actionable retry instructions on incomplete cleanup.
  7. Updates docs/reverse-engineering-tools.md to document direct termination and unknown inferior disposition on protocol failure.

Problem and expected behavior

When a GDB console command (such as printing an unbounded data structure with set print elements 0) produces a single MI record over 16 MiB:

  • GDB protocol error occurred.
  • Any subsequent attempt to close or stop the session called detachInferior(), which threw "GDB MI state is not synchronized; inferior state is unknown."
  • stopOwnedDebuggerProcess caught the rejection and returned early (status: "incomplete"), failing to send SIGTERM/SIGKILL.
  • The GDB process and inferior remained alive indefinitely under the MCP server, and REA hung on exit awaiting stream closure.
  • An already-exited session that lost synchronization could never be closed on subsequent retry because it lacked inferior proof.

Expected behavior:
When closing or tearing down a desynchronized or failed debugger session, the owned debugger process must be terminated directly with SIGTERM/SIGKILL, output streams released on timeout, and subsequent close calls allowed to complete cleanly.

Change and scope

  • src/process/ownedDebuggerSession.ts:
    • Added force?: boolean option to stopOwnedDebuggerProcess.
    • Skips attempting inferior detachment when forced and proceeds to terminate the owned debugger process.
    • Releases unreferenced output streams and disposes supervisor on timeout when forced.
    • Tracks forced sessions in forcedShutdowns so subsequent close calls on already-exited sessions succeed without inferior verification.
  • src/gdb/GdbSessionManager.ts:
    • Cleared line accumulation buffers in #receive when lineBytes > MAX_MI_LINE_BYTES.
    • Passed { platform: this.#platform, force: options?.force ?? session.protocolError !== undefined } in #stopDebuggerOnly.
    • Conditioned forced close on session.protocolError !== undefined so normal sessions still verify detachment.
    • Set descriptive userMessage and remediationAction on AnalysisCapabilityUnavailableError in #stopAfterProtocolFailure, distinguishing confirmed stops from incomplete ones.
  • docs/reverse-engineering-tools.md:
    • Documented direct termination on MI line overflow/sync loss and noted that target disposition remains unknown.
  • tests/boundary/process/ownedDebuggerSession.test.ts:
    • Added unit test verifying that stopOwnedDebuggerProcess with force: true immediately terminates the debugger process with SIGTERM without calling detachInferior.
    • Added unit test verifying that forced stop unrefs output streams and disposes supervisor when streams fail to close.
    • Added unit test verifying that subsequent close of an exited forced session completes cleanly without inferior verification.
  • tests/boundary/providers/GdbSessionManagerCoverage.test.ts:
    • Updated test asserting direct SIGTERM termination on protocol failure.
    • Added test asserting owned debugger termination on line overflow and clean close.
    • Added test asserting incomplete stop recovery and successful close retry.

Contract and boundary impact

  • Semantic owner and earliest changed stage: stopOwnedDebuggerProcess process termination gate; GdbSessionManager protocol failure teardown.
  • Contribution scope fit and linked maintainer decision: Fixes bug [Bug] A GDB console command whose output is one MI line over 16 MiB ends the session with no way to detach, kill or close it #8023 within existing debugger process lifecycle boundaries.
  • CLI and MCP/tool-catalog contract: close_gdb_session reliably cleans up and terminates the session when MI sync is lost.
  • Provider, bridge, target-format, or platform compatibility: Linux GDB session management; preserves Windows job object invariants.
  • Evidence, artifact, provenance, or reconstruction contract: Retains partial observation with protocol error and limitation records.
  • Target selection, authority, upstream behavior, and cleanup details: Guarantees process termination and cleanup of owned debugger processes.
  • Generated metadata, package, or installation impact: None.

Expected effects:

  • Read existing files or captured data.
  • Launch or attach to a process.
  • Inject instrumentation or run scripts/code.
  • Change process memory, registers, files, or configuration.
  • Contact network services.
  • Recover protected code or work around protections.
  • Documentation or usability only; no target interaction.
  • Not sure yet; investigation or maintainer guidance needed.

Evidence and regression coverage

  • Tests added or updated:
    • tests/boundary/process/ownedDebuggerSession.test.ts: tests for forced SIGTERM, stream unreferencing on timeout, and exited session close without inferior checks.
    • tests/boundary/providers/GdbSessionManagerCoverage.test.ts: tests for direct termination on sync loss, line overflow teardown, and close retry.
  • Base reproduction or other evidence: On base revision, stopOwnedDebuggerProcess returned { status: "incomplete" } and did not invoke process.kill() when detachInferior rejected.
  • User-visible CLI/MCP output: close_gdb_session returns cleanly rather than failing with cleanup_incomplete, and GDB process terminates.
  • Remaining proof gaps: None.

For evidence-bearing changes:

  • Observed, derived, and inferred claims remain distinguishable.
  • Artifact identity, source provenance, and failed attempts remain preserved.
  • Unsupported, incomplete, unavailable, or uncertain outcomes remain visible.

Validation performed

  • npm run compile - clean build.
  • npm run check:fast - full turbo typecheck & lint passed (2 successful).
  • npm run verify:module-boundaries - checked 3429 source files successfully.
  • npm run verify:test-discovery - discovered all 2865 test files exactly once.
  • npx vitest run tests/boundary/process/ownedDebuggerSession.test.ts - 39 passed, 4 skipped.
  • npx vitest run tests/boundary/providers/GdbSessionManagerCoverage.test.ts -t "sync loss|overflow|retains ownership without signaling" - 5 passed.

Compatibility, safety, and release

  • Breaking changes or migration steps: None.
  • Real Hopper/Ghidra, browser, or OS coverage: Validated on Node.js 24 with mocked supervisor and process suites.
  • Package or release metadata impact: None.
  • Security, privacy, process, or containment review: Eliminates process and file descriptor leak on error path.

Author readiness

Human owner: @highmachs

  • I reviewed the final diff and relevant existing code, understand the change and its edge cases, and take responsibility for the complete PR, including AI-assisted work.
  • I checked the evidence above, confirmed it supports the current change, and recorded meaningful validation gaps.
  • I declare this PR ready for initial maintainer review.

Before merge

  • This PR addresses a concrete problem or an agreed enhancement.
  • Material scope and authority questions are resolved, and any required maintainer scope decision covers the final diff.
  • The PR has one focused outcome and the title follows type(scope): outcome.
  • Related issue is linked, or the reason for not linking one is stated above.
  • Tests cover changed observable behavior and meaningful failure paths.
  • Owning docs, contracts, and generated metadata are updated where needed.
  • User-visible CLI/MCP changes include representative output.
  • I checked the final diff for secrets, unrelated cleanup, and unsupported claims.

…and sync loss

When GDB emits an MI line exceeding the 16 MiB protocol limit, protocol failure marks MI synchronization lost. Attempting inferior detachment over the desynchronized MI transport throws and previously aborted process termination, leaving GDB and its inferior running indefinitely as zombie processes.

Support forced termination in stopOwnedDebuggerProcess, clear line buffers on overflow, pass force: true when MI sync is lost or during close, and surface informative top-level guidance.
Copilot AI balanced review requested due to automatic review settings October 30, 2026 04:41
@chatgpt-codex-connector

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ⚠️ Failed 2026-10-30T04:41:31.126306Z
We couldn’t complete this review. Comment @codex review to try again.
bc25baf PR opened
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot was unable to review this pull request because the user who requested the review has insufficient remaining quota.

@chatgpt-codex-connector

Copy link
Copy Markdown

Codex usage limits have been reached for code reviews. Please check with the admins of this repo to increase the limits by adding credits.
Repo admins can enable using credits for code reviews in their settings.

@greptile-apps

greptile-apps Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerView in GreptileConfidence Score: 4/5 Tier: plus

[Medium impact] The changed cleanup path is limited to GDB sessions that lose MI synchronization.

The PR needs a fix before merging because MI failure during detach can still leave the owned GDB process running.

Findings

  1. P1 Shutdown leaves GDB running ▶
  2. P2 Recovery fills session slots ▶
Fix with agent prompt
### Issue 1
src/gdb/GdbSessionManager.ts:1942-1945
`force` is chosen only when a stop starts. If `closeAll()` loses MI sync while `#detachInferior()` awaits a reply, that stop is already running with `force: false`. An oversized reply returns `incomplete` before `SIGTERM`. A command timeout calls `#stopDebuggerOnly()` again but gets the same non-forced promise. GDB stays alive until another cleanup call.

Once the first attempt settles, retry with force if MI synchronization was lost during detachment.

### Issue 2
src/gdb/GdbSessionManager.ts:1920
After successful forced shutdown, `#stopAfterProtocolFailure()` leaves the session in `#sessions`, but this advice says it was closed and tells the caller only to start another one. `start()` still counts that entry against `REA_DEBUGGER_MAX_SESSIONS`. Following the advice repeatedly fills the available slots; with a one-session limit, the first replacement already fails.

Remove the finished entry, or tell the caller to run `close_gdb_session` with this `session_id` before starting a replacement.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

Summary

Adds forced shutdown of the owned GDB process after MI failure, clears overflow buffers, and preserves cleanup retries.

  • GDB sessions with lost MI synchronization stop their owned debugger directly.
  • Protocol failures release oversized line data and explain how to retry cleanup.
  • JavaScript artifact graphs keep the same behavior after import cleanup.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Stop requested] --> B{MI already failed?}
  B -- Yes --> C[Terminate owned GDB]
  B -- No --> D[Verify inferior]
  D -- Confirmed --> C
  D -- Sync lost --> E[Cleanup incomplete]
  E --> F[Another cleanup call]
  F --> C
  C --> G{Output closed?}
  G -- Yes --> H[Release supervisor]
  G -- No --> I[Retain owner for retry]
  I --> J[Forced POSIX stop unrefs output]
Loading

Reviews (4) · Last reviewed commit: "Merge remote-tracking branch 'upstream/m..." · Reviewed by Greptile

Comment thread src/process/ownedDebuggerSession.ts Resolved
Comment thread src/gdb/GdbSessionManager.ts Resolved
Comment thread src/gdb/GdbSessionManager.ts Resolved
Comment thread src/gdb/GdbSessionManager.ts Resolved
Comment thread src/process/ownedDebuggerSession.ts Resolved
@Rinkia

Rinkia commented Nov 3, 2026

Copy link
Copy Markdown
Contributor

I tested this PR at 001d8032c against main at 4b961e371. I used the #8023 repro: GNU gdb 15.1 in a Linux x64 container, the utf8 probe with int big[4000000], and print elements and print repeats both set to 0. I ran the sequence over MCP with /dev/pts/0 as the inferior TTY.

main:

  • print big, every later call and close_gdb_session return cleanup_incomplete.
  • GDB and the stopped inferior stay behind.

This PR:

One gap remains. Each command sent to the closed session afterwards returns a generic invalid_request with "Analysis input is invalid. Check the arguments and try again", plus the issue detail "GDB session is unavailable or closed". The status doesn't keep the stop reason either. For Rizin, #8024 / #8025 return a typed error with the retained reason, and add closed_reason to the status. Doing the same here would keep the two debuggers consistent.

I also tested #8029, which keeps the session usable by dropping the oversized stream record. The two approaches look complementary: #8029 for stream records, and this PR's forced stop for protocol failures that still close the session.

@highmachs

Copy link
Copy Markdown
Contributor Author

Thanks @Rinkia for testing this with GNU gdb 15.1 and verifying that the lingering GDB and inferior processes are cleanly removed!

Regarding retaining the stop reason on subsequent commands and adding a closed_reason field to status (as reported in #8024): that is a great observation and makes complete sense for aligning debugger session ergonomics. Keeping this PR strictly scoped to the primary process teardown on line overflow and sync loss (#8023) allows it to merge cleanly, and we can address typed error preservation across both Rizin (#8024) and GDB in a dedicated followup.

Comment on lines +1942 to +1945
this.#stopProcess(session, "GDB", {
platform: this.#platform,
force: options?.force ?? session.protocolError !== undefined,
}),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Shutdown leaves GDB running

force is chosen only when a stop starts. If closeAll() loses MI sync while #detachInferior() awaits a reply, that stop is already running with force: false. An oversized reply returns incomplete before SIGTERM. A command timeout calls #stopDebuggerOnly() again but gets the same non-forced promise. GDB stays alive until another cleanup call.

Once the first attempt settles, retry with force if MI synchronization was lost during detachment.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/gdb/GdbSessionManager.ts
Line: 1942-1945

Comment:
**Shutdown leaves GDB running**

`force` is chosen only when a stop starts. If `closeAll()` loses MI sync while `#detachInferior()` awaits a reply, that stop is already running with `force: false`. An oversized reply returns `incomplete` before `SIGTERM`. A command timeout calls `#stopDebuggerOnly()` again but gets the same non-forced promise. GDB stays alive until another cleanup call.

Once the first attempt settles, retry with force if MI synchronization was lost during detachment.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

remediationAction:
stopped.status === "incomplete"
? `The GDB session protocol failed and cleanup could not be confirmed: ${stopped.reason}. Retry close_gdb_session with session_id "${session.id}".`
: "The GDB session protocol failed and the session was closed. Start a new GDB session to continue.",

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Recovery fills session slots

After successful forced shutdown, #stopAfterProtocolFailure() leaves the session in #sessions, but this advice says it was closed and tells the caller only to start another one. start() still counts that entry against REA_DEBUGGER_MAX_SESSIONS. Following the advice repeatedly fills the available slots; with a one-session limit, the first replacement already fails.

Remove the finished entry, or tell the caller to run close_gdb_session with this session_id before starting a replacement.

Prompt To Fix With AI
This is a comment left during a code review.
Path: src/gdb/GdbSessionManager.ts
Line: 1920

Comment:
**Recovery fills session slots**

After successful forced shutdown, `#stopAfterProtocolFailure()` leaves the session in `#sessions`, but this advice says it was closed and tells the caller only to start another one. `start()` still counts that entry against `REA_DEBUGGER_MAX_SESSIONS`. Following the advice repeatedly fills the available slots; with a one-session limit, the first replacement already fails.

Remove the finished entry, or tell the caller to run `close_gdb_session` with this `session_id` before starting a replacement.

---

For each issue above, determine whether it is valid and should be fixed. If so, fix it directly.

@morluto morluto added area: runtime Process capture and runtime observation bug Something isn't working provider: gdb Analysis provider / engine: gdb labels Nov 26, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: runtime Process capture and runtime observation bug Something isn't working provider: gdb Analysis provider / engine: gdb

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[Bug] A GDB console command whose output is one MI line over 16 MiB ends the session with no way to detach, kill or close it

4 participants