Skip to content

WIP: arith/expansion residuals — #2374 #2375 #2384 #2378 (#2227 faces) - #2420

Merged
caomengxuan666 merged 7 commits into
masterfrom
fix/arith-expansion-residuals
Nov 1, 2026
Merged

caomengxuan666 merged 7 commits into
masterfrom
fix/arith-expansion-residuals

Conversation

@caomengxuan666

Copy link
Copy Markdown
Member

Cluster PR for the arithmetic/expansion residuals. Refs #2374, #2375, #2384, #2378, #2227. Code-first per the 2026-11-01 directive: local verification is cargo check; pins are batch-verified scrubbed by the main session before merge. Per-issue commits with GNU source citations. The #2227 double-quoted segment-scope face is analyzed in the cluster report (documented remainder — needs a new cooked-word carrier, registry-governed).

…removal (#2374)

GNU subst.c:1301 extract_arithmetic_subst extracts a $[...] body with
subst.c:1361 extract_delimited_string: a backslash or CTLESC passes the
next character (it can neither delimit nor nest), single/double-quoted
and backquote units are skipped whole, and nested [ / $[ openers nest.
rubash's three collectors (embedded_mutations, embedded_parameters,
expand_braced_replacement::dollar_bracket_end) used plain bracket
counting, so $[1\]] collected `1\` and the diagnostic named `\` where
GNU names `]`, $[1\[2] never collected at all, and $["]"] mis-split.

The extracted string then goes through subst.c:3981
expand_arith_string: with no expansion character ($, backquote, CTLESC
— subst.c:3802 ARITH_EXP_CHAR) a body containing ' \ " goes through
subst.c:12199 string_quote_removal (Q_DOUBLE_QUOTES|Q_ARITH), which
drops a backslash before [ ] ~ and the CBSDQUOTE set, keeps it
elsewhere, and drops unescaped ". Port that branch as
arith_string_quote_removal and run it on the expanded arithmetic
string in eval_arithmetic_expansion_value (the same point GNU runs it
for $(( )) — $(( 1\] )) also named \] where GNU names ]) and in the
embedded-parameters $[...] arm before eval_conditional_arith_value.

Refs #2374
remove_shell_quotes_inner_cursor (the walk behind both plain word
cooking and remove_shell_quotes_assignment) dispatched $ followed by
( ' " { but not [: a $[...] body was cooked as ordinary word text, so
an inner " opened the walk's double-quote arm, which CTLESC-prefixed
the arithmetic characters and dropped the quotes — v=$["1+1"] reached
the evaluator as the corrupted token 1\u{11}+1 instead of evaluating.

GNU parse.y:5527 read_token_word hands $[ to parse_matched_pair with
P_ARITH: the body is one self-contained unit (the double-quote cookers
already treat it so via copy_dollar_bracket_arithmetic_cursor). Add
the [ arm to the unquoted walk, copying the whole span verbatim with
its end found by subst.c:1361 extract_delimited_string's machine
(dollar_bracket_body_end: backslash/CTLESC pass, quote units skipped,
nested [ / $[ nest). The expansion collectors re-extract and evaluate
the span (#2374). Verbatim copying also stops the cooked word for
$[1\]] carrying a carrier-split body, which is the assignment face of
#2374's wrong-token diagnostic.

The issue2227 pins cover the extraction faces this + #2374 deliver
(quoted ] inside the body, leading-blank quoted body, nested
subscripts). The remaining #2227 face — a $[...] inside a
double-quoted segment, where GNU's reader hunts segment-scoped and
reports `bad substitution: no closing ']' in <segment prefix>` — is
not addressed here: it needs a cooked-word carrier for the verdict
and stays as the issue's documented remainder.

Refs #2375
Refs #2227
GNU keeps PIPESTATUS in ONE store: the array object written by
variables.c:6291 set_pipestatus_array and read by both
${PIPESTATUS[i]} expansion and expr.c evalexp. rubash split it —
completion writes the live cell in shell_state, arithmetic reads
consult a snapshot of that cell taken at evaluation start
(rubash#1364 R3), and arithmetic writes land in the env mirror — so
((PIPESTATUS[0] = 3, PIPESTATUS[0] == 3)) was false, and a write in
one $(( )) of a word was invisible to the next.

Share the read-ownership rule with ${PIPESTATUS[i]} expansion:

- indexed_element_text, arith_negative_subscript_is_bad and the
  bare-name read in variable_value consult the live-cell snapshot
  only while this evaluation has recorded no PIPESTATUS write
  (arith_write_recorded over the evaluation's write log); after a
  write, the mirror legs own the read — the mirror is where
  set_array_element put the value.
- sync_arith_writes_to_shell_state also applies a PIPESTATUS write
  to the live cell (indexed render -> entry vector + LiveArray
  shape; plain scalar -> Scalar shape), so the next evaluation's
  snapshot and ${PIPESTATUS[i]} expansion see it (t1/t2 faces).

Refs #2384
…#2378)

GNU redir.c r_close_this leaves a `>&-`-closed fd closed in the
child: the child's write fails EBADF inside the child, the shell
reports nothing, and the child's exit status stands.
builtins/common.c:320-334 sh_chkwrite — the `write error` + status 1
verdict — folds only a BUILTIN's flush failure, because the shell
itself performs a builtin's writes.

rubash's spawn planner substitutes a capture pipe when an output fd
is closed (external_output_fds_closed) and the parent replays the
drained bytes through the ordered redirect walk; the replay
manufactured the builtin verdict for foreign commands
(`python3 w10.py >&-` -> `write error: Bad file descriptor`, rc 1,
where GNU is silent rc 0) and dropped the child's captured stderr
when fd 1 was closed.

Mechanism: the post-external route
(route_builtin_buffered_output_resolve_only_numbered, whose only
caller is the foreign drain) now marks its OutputFdState
foreign_drain. In that mode a Closed target discards the drained
bytes with no diagnostic and no status change at all three verdict
sites (the walk-declined fallback, the post-walk closed check, and
write_state_output_or_diagnostic's closed-error arm); the sibling
stream still routes on its own binding. The builtin buffered route
is untouched and keeps the sh_chkwrite verdict (pin c5).

Refs #2378
…me is the search join

Refs #2378

- Stdio planning: a Null slot (ambient `exec 1>&-`) and a per-command
  `>&-` on the plan path now realize as inherit + close-in-child
  (pre_exec libc::close) instead of Stdio::null() or a captured pipe
  the child could write through. GNU keeps the fd closed in the child
  (redir.c r_close_this): the child's own write fails EBADF and its
  diagnostic on the surviving stream is what surfaces; the shell
  reports nothing. sh_chkwrite (builtins/common.c:320-334) stays
  builtin-only.
- external_command_for_named_program_with_exec_name: the plain
  foreground spawn passes the as-written PATH-element join as the
  execve filename when it anchors to the resolved program
  (findcmd.c: find_in_path_element builds the name with sh_makepath
  from the element as searched), so a PATH-found script child sees
  $0 = ./emit or bin/zero, not the anchored absolute path. Binary
  argv[0] remains the typed word; hash hits and slash-less joins
  decline to the anchored path.
…e, PIPESTATUS mirror reconcile

Refs #2374
Refs #2375
Refs #2384

Extraction copies the $[...] body verbatim (subst.c:1301/1361,
strncpy at subst.c:1512-1518); a backslash or CTLESC-passed char
neither delimits nor nests (subst.c:1420-1425). Three places broke
that stream before the collector could read it:

- parameter_core: the quoted-assignment-shaped argument branch
  re-spelled every RHS backslash as a data carrier; a $[...] body is
  nested-parse syntax like the already-excluded $(, ${ and backtick
  bodies, so it now bails the same way (`echo "t1=$[1\]]"` named the
  backslash; the assignment face stayed right because the assignment
  pipeline dequotes itself).
- lexer span copier (double-quote cookers): a `\\` pair inside the
  span stays raw — it is extraction pass structure, and collapsing
  it here left a lone backslash that passed the closing `]` in the
  collectors so the span never closed (`"t6=$[1\\]+2"` printed
  literally). Only `\"` is still resolved at copy time; the pair's
  collapse is string_quote_removal's job.
- collector and span end-finders: a lone data backslash is a plain
  body char, never a pass; pass pairs are copied into the body
  verbatim for the evaluation routes to resolve.

Route choice is GNU's (subst.c:3981): ARITH_EXP_CHAR is `$`,
backquote and CTLESC only (subst.c:3802). eval now runs the two
routes exclusively — word expansion when an expansion char is
present, string_quote_removal on the extracted string otherwise —
instead of letting a raw backslash pair or a plain quote force the
word route. The collectors also accept the assignment channel's
carrier spellings for quotes and decode them back to real quote
characters in the body, so `v=$["1+1"]` evaluates the grouped body
and `v=$['1+1']` errors naming the real quotes (GNU evaluates the
body of an assignment-shaped $[...] the same way).

PIPESTATUS: the environment mirror is reconciled from the live
cell before arithmetic evaluation, so a pipeline completion and an
arithmetic write share the one store GNU keeps
(variables.c:6291 set_pipestatus_array); a scalar element-0 write
preserves the rest of the current store.
@caomengxuan666
caomengxuan666 marked this pull request as ready for review November 1, 2026 04:54
@caomengxuan666
caomengxuan666 merged commit e917e3c into master Nov 1, 2026
1 of 2 checks passed
@caomengxuan666
caomengxuan666 deleted the fix/arith-expansion-residuals branch November 2, 2026 01:10
SpookyWaste pushed a commit to SpookyWaste/rubash that referenced this pull request Nov 12, 2026
Refs unixwin#2442

unixwin#2378 (PR unixwin#2420) threaded the as-written PATH-element join as the
execve filename only through the plain foreground spawn. GNU has
exactly one resolution point per disk command — execute_cmd.c:5810
execute_disk_command's search_for_command — and shell_execve
(execute_cmd.c:6133) hands its result to execve for every spawn
shape: pipeline members (execute_cmd.c:2620 re-enters
execute_simple_command per element), command substitution
(subst.c:7143), background and coproc children. The result is
findcmd.c:553 find_in_path_element's sh_makepath join (the PATH
element as written), or the typed word itself for a slash name
(findcmd.c:385-387). Pipeline-stage and other non-foreground
spawns still passed the anchored absolute path, so a script
child's $0 diverged (echo p | bin/zero -> /tmp/.../bin/zero
instead of bin/zero).

Fix by mechanism: one funnel, path::spawn_exec_name(name,
program, env_vars) — slash name yields the typed word, a
slash-less name yields exec_name_for_program's as-written join
(which declines unless the join anchors to exactly the resolved
program). Every route that resolves its program from a typed
word now derives its filename through it:

- plain foreground (refactored onto the helper; identical value);
- all four pipeline spawn loops and the sequential stage
  executor in pipeline_stages.rs;
- the command-substitution fast path;
- the env wrapper (against its resolution env; env -C keeps the
  anchored program — its child is born in the -C directory, not
  the session cwd the resolution ran against);
- the background & and coproc direct spawns, which bypass the
  named constructor: the funnel supplies the Command program
  spelling and argv[0] becomes the typed word, mirroring the
  named constructor.

Deliberately left: the exec builtin. GNU resolves it through
search_for_command (builtins/exec.def:151) but then rebinds the
target with full_pathname (exec.def:172) before shell_execve
(exec.def:231), so its filename is the anchored absolute path —
oracle-verified (( exec bin/zero ) -> zero=/tmp/d0/bin/zero).
A comment at the call site records the exception. Self-respawn
routes (procsub, internal stand-ins, rubash -c wrappers) spawn
rubash itself, whose inner externals take the funneled routes.

Regression: tests/issue2442_spawn_dollar0_regressions.rs pins
both verified shapes (pipeline stage; relative PATH element on
a non-foreground route) plus the sequential-stage, comsub,
background, env, coproc faces and the exec exception, all with
GNU bash 5.3.20 expectations.
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