Skip to content

Native script debugger (rubash --debug / --dap): M0 design consensus #497

Closed

Description

@caomengxuan666

Native script debugger (rubash --debug / rubash --dap): M0 design consensus

Summary

Add a native bash-script debugger welded into the rubash engine. The debuggee is the script (pdb/debugpy model — the debugger lives inside the interpreter because the interpreter is the substrate), not the LLDB/ptrace model (external process debugger). Two thin frontends over one engine-owned event stream:

  • rubash --debug script.sh — gdb-grammar CLI (b file:line, b func, bt, info locals, n/s/finish, c, conditional breakpoints, breakpoint command lists). bashdb already mimics this grammar — its users upgrade in place.
  • rubash --dap — DAP (Debug Adapter Protocol) adapter, Content-Length-framed JSON over stdio. One implementation, every editor free (VS Code, Neovim dap, Emacs dap-mode, JetBrains, Zed). VS Code extension stays a zero-JS shell (debugAdapterExecutable → rubash --dap, vscode-rdbg shape).

Architecture rule (same as #186): the engine emits semantic DebugEvents (Stopped{frame, reason}, ...); both frontends are pure views. The adapter holds zero semantics.

Why binary beats bashdb: bashdb is a script because GNU bash only offers it that path (DEBUG trap + extdebug + fake frames). Engine ownership buys: real breakpoints/stepping, watchpoints (impossible in GNU — no assignment hook), subshell/pipeline visibility, no per-command trap slowdown, variable-tree rendering. Strategic: debugging is an adoption wedge — scripts destined for GNU bash get debugged under rubash.

This issue records the design consensus from a three-way review (engine feasibility vs GNU C-source semantics vs DAP practice), with every claim anchored to src/**.rs or third_party/bash C source.

Consensus decisions

D1 — Stop sites & ordering (agreed, one hole found and patched)

M0 stop sites = GNU's exact DEBUG-trap distribution (C evidence):

Site C anchor
every simple command execute_cmd.c:4506
function entry, before body (showing_function_line) execute_cmd.c:5383-5391
for head, per iteration execute_cmd.c:3053
each arith-for expression (init/test/update) execute_cmd.c:3187
select head execute_cmd.c:3528
case head, once execute_cmd.c:3668
((...)) execute_cmd.c:3920
[[...]] execute_cmd.c:4153

while/until/if/{...}/(...) heads never stop (no run_debug_trap there); their components stop as inner commands. Stops fire before word expansion.

Ordering at each site (GNU trap.c:1263 run_debug_trap): lineno update → BASH_COMMAND print → user DEBUG trap runs in full → extdebug skip/force-return decision (execute_cmd.c:4495-4511, trap.c:1310-1316) → debugger stop → execute. One dispatch channel only — no second pre/post hook stream.

Rubash implementation shape: the existing run_debug_trap call family (9 sites funneling into src/executor/trap_exec.rs:680; consult at src/executor/ast_exec.rs:497-528) already mirrors this distribution. The debugger stop check sits immediately after the extdebug skip decision at each of the 9 sites. Breakpoint admission must reuse the existing skips_debug_trap gate predicate verbatim — no new admission list (#117 rule).

Hole found during review: with extdebug, trap status 2 sh_longjmps from inside run_debug_trap (trap.c:1310-1316) — a beside-hook never executes. The stop/stack-change event must also fire at the return_catch target, or stepping over a skip loses the frame transition.

DAP note: lines that never fire return verified:false + message ("DEBUG trap never fires on this line") — never silent.

D2 — Watchpoints: phased, honestly labeled (dispute resolved)

Engine fact: rubash has no single variable-write choke point today. env_vars: VarTable exposes the raw HashMap via DerefMut (src/executor/var_table.rs:149-160); 181 direct .insert() sites across 42 files; arithmetic writes go through a thread-local ARITH_WRITES log; VariableStore::set is a parallel mirror. GNU's C funnels (variables.c:3054 bind_variable_internal, variables.c:3322 bind_variable_value, arrayfunc.c:382 assign_array_element_internal) have no Rust equivalent yet.

Consensus:

  • M0/M1: stop-and-diff at stop sites — label "changed since last stop", never "write interception". Do not claim supportsDataBreakpoints. VS Code re-issues evaluate (watch context) on every stopped, so this surfaces with zero protocol work; add output console lines (watch: $x 'a'→'b').
  • Endgame (separate workstream, never bundled with debugger PRs): VarTable funnel refactor providing bind_variable_internal/assign_array_element_internal analogues. Note this refactor buys correctness by itself — the 181 raw-insert sites are exactly GNU's dynamic-assign set (PWD, DIRSTACK, printf -v); the funnel gives them one semantic owner. Days of mechanical edit + full regression, own lane, own suite ledger.

GNU defines no watchpoint semantics, so stop-and-diff violates no fidelity rule (it is exactly bashdb's model too).

D3 — Thread/frame model (engine position conceded)

  • M0/M1: single DAP thread + synthesized frames. Synchronous comsubs/subshells become synthesized frames on one stack (gdb inline-frame style: "subshell: stage 2/3", "$(...) depth 1"), built by walking clone→parent Executor links into one merged stackTrace. Per-entity DAP threads for synchronous entities are a protocol lie: the caller is blocked, yet the thread would show as running.
  • Steppability constraint: synthesized comsub/subshell frames must not be independently steppable unless functrace would propagate the DEBUG trap there (trap.c:1469-1477).
  • M2+: background jobs are attach targets only. Engine fact: background commands re-exec rubash as new OS processes (src/executor/compound_exec.rs:340-344, traps stripped :364-378) — there is no in-memory steering without an attach protocol, and separate processes is also the only GNU-faithful model. True DAP threads only where steering is genuinely concurrent and pausable-all (pipeline stages, allThreadsStopped).

D4 — Evaluate safety: engine-owned AST whitelist (agreed, list finalized)

The checker parses with rubash's own parser and inspects the AST — never regex (#117 lesson). It lives in the engine and is shared by both frontends (single semantic owner).

  • Strict mode (hover/watch): allow read-only forms — plain parameters, positionals, array subscripts, ${!x} indirection, casemod, ${x@Q} (formatting only), pattern/substring ops, assignment-free arithmetic.
  • Reject: $(...), backticks, <(...)/>(...), ${x:=y} and colon-less ${x=y}, ${x:?} and ${x?}, $((x+=1)), $((x++))/x-- (prefix/postfix).
  • REPL context: full commands, opt-in.
  • setVariable = real assignment semantics through the real parser (user-initiated → side effects allowed), gated behind supportsSetVariable.

D5 — Gating & state unification (agreed, extended)

  • Dedicated AtomicBool checked before has_active_trap_action (today at src/executor/ast_exec.rs:497); admission-only, zero semantics. Flag-off cost = one load + one well-predicted branch.
  • Unify debugger state with debug_trap_in_scope / debug_trap_running / functrace inheritance so trap and breakpoint semantics never diverge.
  • The no-recursion invariant (src/executor/trap_exec.rs:681 pattern, mirroring SIG_INPROGRESS at trap.c:1270) extends to debugger stops: no debugger stop inside a trap body re-enters the DEBUG path.
  • Snapshot reads (variables/evaluate while stopped) sit outside executor flow — re-entrancy is structurally impossible.

D6 — Acceptance: bashdb oracle + golden DAP transcripts (agreed)

Every fixture = script + recorded framed DAP transcript + bashdb oracle log, stored under target/issue-suites/results/dap/. M0 minimum golden set:

  1. initialize/handshake + capabilities
  2. launch → configurationDone → terminated lifecycle
  3. setBreakpoints: hit + dead-line unverified
  4. next/stepIn/stepOut across a function
  5. stackTrace cross-checked against bashdb stop positions + FUNCNAME/BASH_LINENO
  6. scopes/variables incl. array children
  7. evaluate: safe form + rejected :=/$(...) forms
  8. output categories (stdout/stderr/console)

Three additional C-level pins from the review: RETURN trap suppressed when function entry is skipped (execute_cmd.c:5391); line_number restored on skipped case/arith (execute_cmd.c:3670-3675); BASH_COMMAND = the_printed_command_except_trap during trap bodies (execute_cmd.c:4502-4505).

DAP surface

M0 requests: initialize, launch, setBreakpoints, setExceptionBreakpoints (VS Code sends it unconditionally — accept, may no-op), configurationDone, threads, stackTrace, scopes, variables, evaluate, next, stepIn, stepOut, continue, pause, terminate, disconnect. Events: initialized, stopped, terminated, exited, output, thread, breakpoint. Conditional breakpoints and logpoints ride setBreakpoints fields (condition, logMessage) gated by supportsConditionalBreakpoints / supportsLogPoints / supportsEvaluateForHovers — never claim an unimplemented supports*. M1 adds: attach, setVariable, exceptionInfo. Exception breakpoint filters: err-trap, set -e, parse-error.

Release gates (repo-discipline consequences)

  • perfbudget: assert startup/loop timing with the debug flag off is within noise; ratchet.
  • Binary size ratchet: debugger code grows the release binary by ≤512KB (budgets.toml style). Today's release baseline: 10,158,080 bytes. JSON layer: minimal hand-rolled writer or tiny crate — the repo has no serde_json today; do not pull the full serde stack for this.
  • M0 touches src/executor/** → captain-exclusive lane per multi-agent discipline; members must not edit the stop-seam sites directly.
  • bashdb compat obligation is unchanged and parallel: bashdb failing commands still drive root-cause fixes; bashdb is additionally the M0 regression oracle.

Milestones

  • M0: engine stop events at the 9 seams (incl. the return_catch patch point) + gdb-grammar CLI. Launch-only. The first deliverable of M0 is the event-semantics definition document for the five seams, as the captain-review artifact.
  • M1: --dap adapter + zero-JS VS Code extension (launch).
  • M2: conditional breakpoints, logpoints, watch (stop-and-diff), setVariable, attach protocol design for background jobs.
  • M3: VarTable funnel refactor (separate prerequisite lane) → true write-interception watchpoints; trace ring buffer post-mortem (flag-gated, preallocated, never default-on).

Review provenance

Consensus produced by a three-way cross-review (engine-feasibility reviewer bound to src/, GNU-semantics reviewer bound to third_party/bash, DAP-practice reviewer), two rounds: independent positions then per-decision AGREE/DEFEND/CONCEDE. All six contested decisions converged; the extdebug force-return hole (D1) and the background-jobs-as-OS-processes fact (D3) were discovered during cross-attack, not present in any single reviewer's round-1 position.

Activity

  1. added
    enhancement
    on Oct 10, 2026
  2. added
    P3-low
    on Oct 10, 2026
  3. caomengxuan666 commented on Oct 13, 2026

    @caomengxuan666
    MemberAuthor

    M0 design PR #582 merged — docs/design/debugger-m0.md is now the M0 draft of record (anchors verified at 7f18b44; scope pinned to DAP-over-stdio, one same-process debuggee topology, stop substrate = the existing run_debug_trap seam family + the function-return patch point, breakpoint injection via executor PC hooks with the parse-tree line walk serving only verified:false resolution).

    Consensus requested on the three decision points left open in §11 — each needs an owner ruling before implementation opens:

    1. DP1 — frontend order: the draft pins the DAP adapter as the M0 frontend (DAP-first, per the 2026-10-13 instruction), reordering the originally recorded milestones (gdb-grammar CLI in M0, --dap in M1). The CLI design is unchanged (pure view over the same event stream) and lands immediately after. Confirm DAP-first, or restore CLI-first?

    2. DP2 — --debug flag semantics: --debug/--debugger currently parse as an alias that enables extdebug (src/invocation.rs:160-161, applied at :251-254; GNU's bash --debugger means extdebug). Draft recommendation: repurpose rubash --debug script.sh as the DAP host switch, keep --debugger with the GNU extdebug meaning, leave extdebug itself reachable via shopt -s extdebug. Repurposing is a deliberate compat-surface divergence — accept, or prefer a separate --dap flag?

    3. DP3 — M0 stop-site granularity: full GNU-exact distribution across all eleven seams (simple command, [[ ]]/(( )), time body, arith-for init/test/update, case head, function entry, for head, pipeline element, select head — near-zero marginal cost since all funnel into one consult at trap_exec.rs:716), or an M0 cut down to simple commands + function entry + returns? Draft recommends GNU-exact: it is what makes the bashdb oracle comparable on loop/case/select heads.

    Issue intentionally left open until these three are ruled on.

  4. changed the issue type fromtoon Oct 13, 2026
  5. caomengxuan666 commented on Oct 18, 2026

    @caomengxuan666
    MemberAuthor

    裁决(owner 授权按最佳实践 + owner 指认 GNU 依据,2026-10-18):

    • DP2(旗标形态)= --debugger:GNU bash 5.3 确有该选项("Arrange for the bash debugger to be executed before the shell starts")——rubash 接受同拼写,语义=装配调试器就绪(GNU 对齐),--debug 不是 GNU 选项、不采用。
    • DP1 = DAP-first:bashdb 是外部 GPL 工具不可随发;rubash 原生调试器对编辑器/工具链的接口用 DAP(Zed/VS Code 即插),--debugger 旗标负责"就绪装配",DAP server 是它的消费者。
    • DP3(停点粒度)= 行级 + 函数入口两级(先于 M0 实现定案,实现期可加数据断言级)。
    • 实现排期:1.5.0(core 拆分后 debugger 是 core 的天然消费者),M0 设计稿继续有效,实现期按本裁决细化。
  6. caomengxuan666 commented on Oct 23, 2026

    @caomengxuan666
    MemberAuthor

    --debug实际上是GNU选项,但是是老遗留物,可以用,--dap也可以用做原生公民,不过用户可能更喜欢--debug,我个人倾向于这两个都要,保持一个选项解析的含义,用作我们原生的,--debugger的话是bashdb他们的

  7. caomengxuan666 commented on Oct 25, 2026

    @caomengxuan666
    MemberAuthor

    Design finalized — 2026-10-25. The full native-debugger design is approved as written and lands in the tree with PR #1535 (docs/design/debugger-full-design.md, extending docs/design/debugger-m0.md, which remains in force). The §14 decision points are settled, each per the recommendation recorded in the document:

    • Q1 — entry-stop default: stop at the first command, for both frontends.
    • Q2 — the session core is built in-tree now, shaped for its rubash-core home, with the funnel consult landing with/after the [1.5.0] rubash-as-engine: a stable embeddable API to replace partial shells like brush-core in editor integrations #595 split (settles prerequisite P-6).
    • Q3 — breakpoint conditions stay full shell commands evaluated in-frame (the bashdb rule); no whitelist restriction.
    • Q4 — trace mode writes through the xtrace fd machinery (BASH_XTRACEFD).
    • Q5 — the CLI command stream is an engine-level injectable; the console device is the default when no host supplies one.

    The finalization is recorded in §15 of the landed document; all earlier rulings stand (one session, two native frontends — --debug for people, --dap for editors; --debugger keeps its GNU meaning). Prerequisites P-1 (#1184 f4) and P-2 (#1511 + part_036) landed on 2026-10-25 (PRs #1522, #1527), so M0's groundwork no longer blocks the start. This design and the #595 Session API RFC are finalized together as one 1.5.0 implementation program (split and debugger interleaved, module by module); the plan is established, and work starts with the WP-1 event-semantics document and the session-core skeleton, ahead of the funnel consult.

  8. added a commit that references this issue on Oct 25, 2026
  9. added
    deferred
    on Oct 29, 2026
  10. caomengxuan666 commented on Oct 29, 2026

    @caomengxuan666
    MemberAuthor

    按实现关单(2026-10-29)。#497 设计(docs/design/debugger-full-design.md,PR #1535 定版)的实现已全量合入:

    真机验收发现的共存缺陷已单独立案跟踪、不属本设计单的实现缺口:niu #681(函数值 DEBUG trap 与 --debug 断点共存时断点静默丢失,修复簇在飞)。

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

Metadata

Metadata

Labels

P3-lowdeferredenhancement

Projects

No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions