Skip to content

P1 Wave1: six semantic fixes (#524 #525 #529 #532 #535 #536) — trap exit unwind, pipeline redirect failures, indirect declared-unset, runtime bad substitution, redirect-word nounset, malformed subscripts - #561

Merged
caomengxuan666 merged 7 commits into
masterfrom
fix/p1-wave1
Oct 12, 2026

Conversation

@caomengxuan666

Copy link
Copy Markdown
Member

P1 批量修复 Wave1 — 六条 P1-high 语义 bug(每条独立 commit + 独立回归测试)

基线:GNU Bash 5.3.0(WSL stdin/script-file 双向 oracle)× vendored 源码 third_party/bash(b4608166, 5.3 patch 15)为语义一手依据;每条修复均带 file:line 锚点与双侧字节对照。基于 rebased origin/master eb06295(Wave2a #560 已并入)。

1. #524 — trap action 内 exit N 被吞(ERR/DEBUG/RETURN 统一)

  • 根因:run_error_trap(src/executor/trap_exec.rs)丢弃 trap action 的执行结果(let _ =),exit 的 unwind 被吞、$? 回滚,脚本带着 rc0 继续。GNU:exit.def exit_or_logout 从任意 trap action 内直接顶层 unwind(EXITBLTIN,execute_cmd.c:5537 承接),shell 以该状态终止。
  • 修法:ERR runner 传播 ExecuteError::ExitCode(DEBUG/RETURN/SIGCHLD/EXIT 各 runner 原已传播或正确消费)。bare exit 语义一并修复:GNU trap.c:367 在跑 action 前保存 $?(trap_saved_exit_value),get_exitstat(builtins/common.c:519,POSIX interp 1602)把 trap 内 bare exit 解析为该保存值——新增 executor 三字段(保存值/触发时嵌套层级/source-nest 计数),消费侧在 execute_exit。EXIT trap 守卫全深度开放(GNU 退出路径先重置嵌套,execute_cmd.c:6090;该格以行为探针钉死,C 层记账差异未决已注明);ERR/RETURN 仅限 action 本层。
  • 站点覆盖:顶层/函数体/复合花括号(wave2a 补站点,{ false; })/子 shell 成员均验证。
  • 测试:tests/issue524_trap_exit_unwind_regressions.rs 12 例。

2. #525 — 管线段 redirect 失败静默丢弃 + 管线 rc 错(含 B24)

3. #529 — ${!x} declared-unset 致命中止

  • 根因:词错误扫描把 declared-unset 当"条目不存在"。GNU subst.c:7883 parameter_brace_expand_indir 仅在 find_variable_last_nameref(variables.c:2051)返回 NULL(无条目,或空 cell/环 nameref)时才报 invalid indirect;bare declare x/local x 是真实条目 → 空展开。
  • 修法:扫描按 NamerefResolution 门控;nounset ${!name} 臂对齐 GNU 求值顺序(缺失→indirect 错先于 nounset;declared-unset→!x: unbound variable(subst.c:10164-10175);无效目标值→invalid variable name 先于 nounset(subst.c:7955-7961))。
  • 测试:tests/issue529_indirect_declared_unset_regressions.rs 8 例(11 格双侧对照 + new-exp15 上游钉)。

4. #532 — ${x[} parse 期杀全脚本

  • 根因:skip.rs 下标扫描里 { 臂在词中重置命令位,${x[} 的 [ 误开下标配对hunt,parse 期 EOF rc2 全灭。GNU 词层只配对 ${…}(parse.y:3877),体内 [ 是参数体文本;畸形 reference 延迟到展开期报 ${x[}: bad substitution(仅弃当前命令列表:同行后续死、次行继续、循环整体弃但脚本继续)。
  • 修法:oracle walk 与 continuation.rs 增量状态机同加 ${ 体跳过臂(嵌套/引号/$'/换行感知;此改动触及 captain 专属的 continuation.rs,为保持 oracle/增量逐字节一致,additive arm,已在随机化一致性测试下验证);运行期由 [expansion] 畸形下标/算术在读取路径被静默吞:${x[]}/${a[0][1]}/${a[$((1/0))]} 全部静默空 rc=0(GNU bad substitution/division by 0 rc=1)(P1) #536 的 reference 校验把未闭合 [ 判为 bad substitution。
  • 测试:tests/issue532_unclosed_brace_subscript_regressions.rs 5 例。残留:引号体("${x[}")abort 类一致但措辞不同(GNU subst.c:1797 引号形诊断),已注明。

5. #535 — redirect 词缺 set -u 检查

  • 根因:GNU redir.c:298 redirection_expand 走 expand_words_no_vars(带 nounset 检查),报 bare 名 nope: unbound variable;波及面随 do_redirections 运行位置——外段子进程(脚本继续)/内建与空命令主 shell(脚本终止,-c 127)。here-string 体同机制:<<< $nope 与 <<< "$nope" 报、<<< '$nope' 字面。rubash 静默空展开或误报 ambiguous redirect。
  • 修法:reject_invalid_redirects 逐序扫描 redirect 词(先于其自身展开,防 memo 提交静默空),诊断按 [bug] Redirection-open diagnostics bypass an already-applied stderr redirect: 'cat 2>/dev/null < /nonexistent' leaks the error (default mode, set -o posix, and comsub bodies; GNU silent) #250 有序 fd2 路由(cat 2>/dev/null < $nope 静默、反序泄漏);FatalNounset 类经现成主 shell/子进程分类器(finish_heredoc_expansion_error;空命令补判主 shell);空命令路径同跑校验;段边界包含。
  • 测试:tests/issue535_redirect_nounset_regressions.rs 12 例(16 格双侧对照)。

6. #536 — 畸形下标/除零读取路径静默吞(D4)

  • 根因:GNU subst.c:10053 valid_brace_expansion_word(7583)在算子分发前校验 reference——空下标/双下标(valid_array_reference 要求非空且单层)→ ${...}: bad substitution(10278);下标算术失败走 evalexp 的算术错误(1/0: division by 0,arrayfunc.c:1353 → expr.c evalerror)。rubash 读取路径三者全部静默空。
  • 修法:malformed_braced_reference 形状校验进词错误扫描(先于算子分发,覆盖 ${!x[]}/${#x[]} 前缀,模式串中的 [ 不参与);$((...)) 下标求值失败挂算术错误闩(新分类变体带 RANDOM/动态状态,rubash#299 语义保持),由 abort rails 弃命令。赋值路径原已一致,测试钉死。
  • 测试:tests/issue536_malformed_subscript_regressions.rs 6 例。

全量验证

…ead of fatal abort (#529)

GNU parameter_brace_expand_indir (subst.c:7883) raises the fatal
"invalid indirect expansion" only when find_variable_last_nameref
(variables.c:2051) returns NULL: the name has no entry, or a nameref
chain stops on an empty cell / cycles / exceeds depth. A bare
`declare x` / `local x` creates a real att_invisible entry, so
parameter_brace_find_indir yields a NULL value and the expansion is
EMPTY - WSL GNU Bash 5.3.0: `declare x; echo "[${!x}]"; echo done`
prints `[]` + `done` rc 0. rubash treated declared-unset as absent
and aborted the whole script with rc 1.

Two ordering fixes in parameter_errors.rs, both mirroring the C flow:

1. Word error scan (plain ${!name}): skip the invalid-indirect fatal
   when the entry exists but is declared-unset; NamerefResolution gates
   the check so empty-cell/circular namerefs keep the fatal.

2. nounset_braced_parameter_is_unbound ${!name} arm - align to GNU's
   evaluation order: absent source defers to the invalid-indirect scan
   (fires before any nounset check); declared-unset source reports
   `!x` (subst.c:10164-10175 err_unboundvar(name)); a source value
   that is not a valid indirect target defers to the invalid-variable-
   name scan (subst.c:7955-7961 fires inside indir before the caller's
   unbound check - WSL: `set -u; x=1bad; ${!x}` reports the VALUE).

Verified byte-for-byte against WSL GNU Bash 5.3.0 on 11 cells:
declare/local x (empty, continue), set -u x (all sub-shapes),
x=1bad, x=, x=qq, never-set, empty-cell nameref, resolving nameref
(unchanged cell text), plus new-exp15 -uc ${!bar@a} upstream pins.
…uses the pre-trap status (#524)

GNU builtins/exit.def unwinds to the top level from inside any trap
action (the EXITBLTIN jump, honored at execute_cmd.c:5537), so the
shell ends with the exit's own status instead of returning to the
interrupted flow. rubash's ERR trap runner discarded the action's
execution result, so `trap 'echo ETRAP; exit 42' ERR; false; echo
never` printed ETRAP + never and exited 0; GNU prints ETRAP and exits
42. The DEBUG, RETURN, SIGCHLD, and EXIT runners already propagate or
consume the unwind; the ERR runner now propagates it too.

Bare `exit` inside a trap action resolves to the $? saved BEFORE the
trap ran (trap.c:367 saves it; builtins/common.c get_exitstat applies
it per POSIX interp 1602), so commands inside the action cannot change
the bare-exit status. Three new executor fields port that: the saved
value, the fire-time function+source nesting level (trap.c:383), and a
source-nest counter held across sourced bodies plus their evalfile.c:
395 RETURN-trap action. consume side (execute_exit): the saved value
applies when the exit runs at the recorded level and the immediate
trap is not DEBUG.

Two nesting cells are pinned behaviorally against the WSL GNU 5.3.0
oracle (12 probe scripts, 2026-10-12):
- EXIT trap: the guard is open at every depth - inside a function
  called by the action, `false` then bare `exit` still exits with the
  pre-trap status (GNU 5, rubash was 0). The exit path wipes the
  function/source nesting before the trap fires (execute_cmd.c:6090);
  the vendored source does not settle the remaining bookkeeping
  difference vs ERR/RETURN, so the cell is pinned by probes.
- ERR/RETURN: the exit must run at the action's own level; a bare exit
  inside a called function uses the current $? (GNU probe: rc 0).

Regression tests: tests/issue524_trap_exit_unwind_regressions.rs (10
cases: ERR/DEBUG/RETURN explicit exits, bare-exit saved vs current
status cells, sourced exit inside an ERR action, EXIT-trap status
preservation). Existing trap suites green (host_internal_trap_
suppression, issue343/345, issue426 sourced exit, issue433, issue439,
issue70).
…ember with status 1 (#525)

GNU applies each pipeline member's redirections in its own subshell
before the command runs (redir.c do_redirections from
execute_simple_command), so an unopenable fd-0 `< file` reports
`{target}: No such file or directory`, kills that member with status 1,
and never falls back to another stdin source. The pipeline status keeps
counting the surviving members. rubash dropped the redirect on the
in-process stage paths: `echo a | { cat < /nonexistent; }` read the
upstream payload, printed `a`, and exited 0 with no diagnostic; a
member `read x <$(echo a b)` was routed to the external spawner
(`read: command not found`, PIPESTATUS 127) where GNU reports
`$(echo a b): ambiguous redirect` and the member dies with 1; and a
failed middle member left the whole-pipeline status at 1 where GNU
keeps the last member's 0.

Three changes, all anchored to the ordered redirect machinery:

1. reject_invalid_redirects (redirection.rs) now probes plain Input
   file opens at validation time, rejecting with the routed diagnostic
   (redir.c:135 redirection_error semantics — through the fd 2
   bindings applied before the failure, issue #250). This runs at the
   universal materialized-command dispatch, covering top-level
   commands, brace/subshell bodies, and compound members. `true <
   /nonexistent` now fails even though true never reads stdin, and the
   in-process emulated-cat path can no longer silently consume the
   upstream payload on an unopenable target.

2. The sequential stage preflight (pipeline_exec.rs) runs the same
   validation before its own arms, so member-level input-redirect
   failures report and mark PIPESTATUS 1 without reaching the external
   spawner.

3. The fd-0 file-redirect stage gate no longer forces BUILTIN members
   onto the external spawner: a member whose first word resolves to a
   shell builtin stays in the builtin subshell path (GNU runs the
   builtin in the forked member with its stdin on the file); external
   programs keep the spawner route.

Byte-verified against WSL GNU Bash 5.3.0 on the three issue repros
plus the openable-redirect, non-reading-command, 2>/dev/null-routing,
and PIPESTATUS boundary cells. Existing suites green: issue429
(pipeline stdin redirect), issue158, issue436, issue320/324/330/359/
362/382, cat_redirect_stream, issue165/166.
…dies (#535)

GNU redir.c:298 redirection_expand runs the redirect word through
expand_words_no_vars, whose nounset check fires when THAT redirect
applies: `cat < $nope` reports `nope: unbound variable` (the bare
name), the command dies with status 1, and the blast radius follows
where do_redirections runs - a forked child for external targets (the
script continues), the main shell for builtin/function and null-command
targets (the noninteractive script ends; -c exits 127 via the
shell.c:1471 remap). Here-string bodies expand at application time with
the same check: `<<< $nope` and `<<< "$nope"` report, `<<< '$nope'`
stays literal. rubash used to expand unbound redirect words silently
(`<<< $nope`) or misclassify them as `ambiguous redirect` (`< $nope`).

- reject_invalid_redirects now carries the nounset scan per ordered
  redirect (before its own expansion, so the target memo never commits
  the silent empty) and reports through the fd 2 bindings applied
  before the failing word (order-routed, issue #250 semantics: `cat
  2>/dev/null < $nope` is silent, the reversed order leaks). The walker
  returns a rejection class; the dispatch sites translate it.
- execute_materialized_command maps the FatalNounset class through the
  existing main-shell/child classifier (finish_heredoc_expansion_error,
  which now treats a NULL command as a main-shell target - GNU
  execute_null_command runs do_redirections directly).
- execute_empty_words_command runs the same validation for null
  commands with redirects.
- parameter_heredoc_expansion_error covers the unnumbered `<<< word`
  body (single-quoted and ANSI-C forms skip; unquoted and
  double-quoted scan).
- The sequential pipeline stage preflight contains any rejection at the
  member boundary (a member dies with status 1, the script continues).

Byte-verified against WSL GNU Bash 5.3.0 on 16 cells: input/output x
builtin/external/null-command, here-string quote forms, -c remap,
order-routed diagnostics, pipeline containment, heredoc bodies. The
heredoc surface was already conformant and is pinned unchanged.
The wave2a site - the failing command inside { false; } fires the ERR
trap like any top-level command, so the action exit terminates with its
own status - is already covered by the run_error_trap unwind
propagation fix; pin both the same-line and multi-line spellings plus
the subshell-member boundary.
… report on the read path (#536)

GNU validates the ${...} reference before the operator dispatch
(subst.c:10053 parameter_brace_expand -> valid_brace_expansion_word,
subst.c:7583): an empty subscript (${x[]}) or a second subscript
(${a[0][1]}) fails valid_array_reference (arrayfunc.c:885 - the
subscript must be non-empty and simply bracketed) and reports
"${...}: bad substitution" (subst.c:10278, status 1, the command is
abandoned, the script continues). A failing subscript EXPRESSION
(${a[$((1/0))]}) raises the arithmetic expansion error instead
("1/0: division by 0 (error token is \"0\")", expr.c evalerror via
arrayfunc.c:1353 array_expand_index -> evalexp). rubash expanded all
three silently empty with rc 0 - guard scripts kept running on data
that never existed.

- parameter_expansion_error_in_word_context now validates the braced
  reference first (malformed_braced_reference): an empty subscript or
  an immediately-following second subscript is a bad substitution
  reported with the whole ${...} text. The check covers the indirect
  and length prefixes (${!x[]}, ${#x[]}) because GNU validates the
  reference before the indir/length dispatch, and it stays off for
  non-reference shapes (patterns, operator tails with brackets).
- The $((...)) subscript evaluator (array_element_parameter_value)
  raises the arithmetic error rails on failure instead of returning
  empty: latch the category from the real evaluation (new
  eval_conditional_arith_value_categorized_with_writes_and_state -
  the caller's RANDOM/dynamic state participates, rubash#299) and let
  command_execute's abort_on_expansion_errors discard the command.

Byte-verified against WSL GNU Bash 5.3.0 on the three repros plus the
indirect/length prefixes, assoc arrays, operator tails, and the
valid-shape boundary (negative indices, @/*, element substring,
arithmetic, nested-subscript arithmetic). The assignment path was
already conformant (ledger huck#703/572) and stays pinned.
…ead of a parse-time whole-script abort (#532)

GNU's word level matches only the ${...} brace pair (parse.y:3877
read_token_word -> parse_matched_pair ('{', '}')); a `[` inside the body
is parameter text and never opens the P_ARRAYSUB subscript hunt
(parse.y:5635 runs for a bare-word subscript). The malformed reference
reaches the expansion, which reports `${x[}: bad substitution` with
status 1 and abandons only the current command list: `echo BEFORE;
echo ${x[}; echo AFTER` runs BEFORE (the same-line list dies, rc 1);
on separate lines AFTER still runs (rc 0); a loop abandons with the
error and the next top-level command continues. rubash's subscript
walk opened a subscript hunt at the body's `[` (the `{` arm reset the
command position mid-word), so the whole input died at parse time with
`unexpected EOF while looking for matching ]'` rc 2 - no statement ran.

- skip.rs unclosed_array_subscript_walk consumes the `${`...`}` body
  as one unit (nesting-, quote-, and $'...' aware, newline count
  kept); an UNCLOSED `${` falls out with the hunt untouched so the
  generic close-char scan keeps owning the `}` EOF (`echo ${x` class).
- continuation.rs subscript_residuals_advance mirrors the same arm so
  the incremental state machine stays byte-consistent with the oracle
  (the parked snapshot is taken before the arm's line-count
  mutations). This touches the captain-exclusive file and is called
  out here: the additive arm keeps oracle/extension equivalence,
  pinned by the randomized incremental test.
- parameter_errors malformed_braced_reference (rubash#536) now treats
  an unclosed subscript bracket as a runtime bad substitution, which
  is where the deferred diagnostic comes from.

Known residual, same abort class but different wording: a QUOTED body
(`echo "${x[}"`) reports `${x[}: bad substitution` where GNU prints
`bad substitution: no closing }' in "${x[}"` (subst.c:1797
extract_dollar_brace_string's quoted-form diagnostic). Byte-verified
against WSL GNU Bash 5.3.0 on the same-line / separate-line / loop /
prefix-variant cells plus the unchanged-neighborhood cells (valid
subscripts, literal a[b words, the `}` EOF class).
@caomengxuan666
caomengxuan666 merged commit 973496a into master Oct 12, 2026
8 checks passed
caomengxuan666 added a commit that referenced this pull request Oct 12, 2026
…Rejection protocol

#561 reshaped reject_invalid_redirects to classify rejections
(RedirectRejection::Command / FatalNounset). The function-invocation
fast path follows the execute_materialized_command consumer shape:
FatalNounset raises the same finish_heredoc_expansion_error the
materialized path raises (rubash#535's main-shell/child split), Command
skips the call with the tempenv restore and process-substitution
finishes still applied.
caomengxuan666 added a commit that referenced this pull request Oct 12, 2026
… caller frames, ERR trap function-entry, extdebug skip sites, parse_loop diagnostics, kill signal names (#569)

* fix(wave3): P3 batch — xtrace/redir-message/caller/trap-p/extdebug/syntax-echo/job-notice (#517 #518 #519 #520 #521 #522 #550)

#517 xtrace case head (src/executor/compound_exec.rs): trace the RAW word
(word_metadata.raw, the WORD_DESC-text equivalent) instead of the
quote-stripped lexer value, decoding at the output boundary. GNU
xtrace_print_case_command_head (print_cmd.c:742-749) prints
case_command->word->word, which still carries the source quotes. The old
path leaked the PARAM_NAME_END_MARKER boundary byte (0x13) into the
trace: `+ case $x^S in` -> `+ case "$x" in`.

#518 redirection message fidelity:
- expand_redirect_target strips the fully-quoted-word role marker
  (STORAGE_WORD_PREFIX) from the expanded operand; the marker corrupted
  dup-word classification and leaked 0x1d into diagnostics.
  `r <&"${X[0]}"` (X set-empty) is one anchored empty field, not
  ambiguous; all_digits("") vacuous + valid_number("") fail -> dest -1 ->
  EBADF with the raw word: `"${X[0]}": Bad file descriptor`
  (redir.c:784-843 + redirection_error redir.c:149-176).
- the function-invocation fast path (command_prepare.rs
  execute_function_command_invocation) now runs the same
  reject_invalid_redirects gate as execute_materialized_command — GNU
  applies one do_redirections list for every simple command kind
  (redir.c:246).
- append-open errors map through posix_errors::path_error at every bare
  open site (redirection.rs open_command_output_target,
  builtin_redirects.rs, external_redirects.rs open_external_combined_
  target): redirection_error (redir.c:149-176) carries the target word,
  so `cmd >> word &` reports `word: No such file or directory` on every
  attempt instead of a wordless strerror line.

#519 caller (src/executor/arrays/executor.rs indexed_array_stack): the
synthetic FUNCNAME bottom frame "main" is pushed ONLY when
has_script_main_frame() (GNU shell.c:1636-1648 open_shell_script pushes
funcname_a "main" for script files; bash -s/-c never enter it), matching
the dynamic_stack_array_values view. caller.def:108-121 fails with
EXECUTION_SUCCESS=1 and no output when FUNCNAME[expr+1] is absent, so
`caller 1`/`caller 2` at g->f depth are empty rc=1 — no fabricated
`10 main <path>` line.

#520 trap -p ERR in functions (src/builtins/trap.rs, function_calls.rs):
execute_cmd.c:5279-5286 removes the inherited ERR trap for the function
body unless error_trace_mode (set -E), with uw_maybe_set_error_trap
restoring it at exit. Rubash now saves/clears/restores the ERR action at
the function boundary, so `trap -p ERR` shows an empty context while the
firing behavior (already GNU-correct) is unchanged.

#521 extdebug DEBUG-skip (trap_exec.rs run_debug_trap + fire sites): the
skip rule is now `extdebug && trap status != 0` — GNU's fire-site
contract (execute_cmd.c:3057/3191/3532/3672/3924/4157/4510/5391) —
replacing the old status==2-without-extdebug rule, and $? is preserved
across a DEBUG firing (probe: `trap 'false' DEBUG; true; echo $?` -> 0).
The decision is now HONORED at: case head (3672: skip whole case, status
SUCCESS), select head (3532), for header (3057: continue — skip the
iteration, next word runs; final-iteration skip leaves the trap's
status), arith-for init/test/update (3191-3199: expression evaluates as
0 with ok=1), pipeline stage (4510 in the element child: empty output,
stage status = trap status), function entry (5391: skip body and RETURN
trap, call status SUCCESS). Statuses after skips follow the probes:
skipped simple/case/select/function leave $? = 0 (m1/k9/m2); the
pipeline of two skipped stages is 1 (i521d).

#522 arith-for syntax error echo (src/parser/parse_loop.rs): the error
node carries its line (`line N:` prefix via
parser_diagnostic_prefix_for_line) and the between-parens text is
rebuilt VERBATIM from token leading_ws+raw (`((i=0; i<3))`, not the
normalized `(( i=0; i<3 ))`) — GNU error.c:300-316 parser_error +
parse.y:6813-6826 print_offending_line echo the source as read.

#550 cell 2, job signal notices (src/builtins/kill.rs
signal_death_description): the Windows fallback maps the invariant
signal numbers to the glibc strsignal wording the oracle prints
(SIGKILL -> `Killed`, jobs.c:1955 j_strsignal), keeping j_strsignal's
`Signal %d` only beyond the table. Cell 1 (`~root:x`) is NOT changed:
the lookup logic already matches GNU (unresolvable users stay literal on
both); `/root` comes from Linux's user database, which Windows does not
have — platform discount per the issue's own recommendation.

Tests: tests/issue5{17,18,19,20,21,22}_*.rs,
tests/issue550_job_notice_and_tilde_regressions.rs (36 cases, all
byte-verified against WSL GNU Bash 5.3.0 script-file/stdin probes).
Full cargo test --no-fail-fast: the failing set is IDENTICAL to fresh
origin/master (db3218a) by test name in both directions (44 failed
names, 8 failing targets on each side; the master reds are pre-existing
and untouched).

* fix(#518): adapt the function-path redirect gate to the #561 RedirectRejection protocol

#561 reshaped reject_invalid_redirects to classify rejections
(RedirectRejection::Command / FatalNounset). The function-invocation
fast path follows the execute_materialized_command consumer shape:
FatalNounset raises the same finish_heredoc_expansion_error the
materialized path raises (rubash#535's main-shell/child split), Command
skips the call with the tempenv restore and process-substitution
finishes still applied.
@caomengxuan666
caomengxuan666 deleted the fix/p1-wave1 branch October 13, 2026 02:00
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant