Repository navigation
fix(exec): place persistent exec redirects onto their kernel fds (Refs #3917) - #3930
Conversation
|
队长复核(修法头 13d4d09):待改——服务器腿全绿,但 CI 头上缺陷格仍红,且带出 fd 面回归与交叉编译错误。 仍红(核心未解):自带钉两只缺陷格在 CI 仍红—— 回归(census 86 vs 尖 79,新增七格皆 fd/exec 面):
编译硬错(linux/android 交叉腿): 干净面:goldens 仅基线二名(lib 1383/0 通过);Rust tests 双腿、darwin、shell、Windows 编译、ledger、niu-build 全绿;issue1902 一格翻转为既判抖动族。 修法方向:先在 CI 形态下复现(查 CI pipe 祖先,REPORT §7 已留此缺口),再收窄 dup2 放置的适用面——当前放置动了 fdvar 关闭恢复、dup 快照、compound 重绑三条相邻语义;S_IFMT 处加 u32 转换。基底 f983851 已落后尖 db580be,重做后须 rebase 再推。 |
…#3917) `exec 3>file` / `exec 4>file` never landed the file on kernel fd 3/4: the fd table is virtual, so the file sat on whatever kernel fd open() returned (the lowest free one). When the number was already occupied — an inherited pipe pair in the census runner — /proc/$$/fd/3 still showed the pipe and the pin's two cells went red, while direct runs (with fd 3 free) stayed green. GNU dup2's the opened file onto the redirector (redir.c:1017/:1120), so the number IS the file. - FdTable gains kernel_place_persistent: while the bare top-level `exec` walk runs, file-backed installs for fds below SHELL_FD_BASE are dup2'd onto their logical kernel number. The scoped walk never sets it (a scoped dup2 would lose a foreign occupant the restore cannot bring back). Placement refuses a number held by another live entry's handle, or by a directory (cwd anchor) / socket (signal pair, /dev/tcp); pipes and regular files are replaced. - Internal pipes move out of the user range (create_capture_pipe, wrapper_relay_install via move_to_high_fd), so a persistent redirect cannot displace one. - The startup pin cell was vacuous (its own comsub pipe made fd 3 read as a pipe); rewritten to probe the real invariant — no low fd 3..9 names the cwd — without a command substitution. Refs #3917. UNVERIFIED-BY-CAPTAIN.
…undoable (Refs #3917) Captain review of PR #3930 — four points: 1. Census fd regressions (issue2310 x2, issue2690, issue3403 x2, issue726 x2): kernel_place_persistent was armed for every bare walk at builtin_wrapper_depth == 0, but this executor is in-process while GNU forks for subshell and compound bodies (execute_cmd.c execute_in_subshell), so a placement inside a scope whose restore is table-only leaked into the outer scope's descriptors. Arming now also requires subshell_depth == 0 and compound_redirect_scope_depth == 0 (new Executor counter raised by with_command_input_redirects_scoped around a compound body that carries redirections). Separately, the placement dup2 cleared FD_CLOEXEC, leaking the placed descriptor raw into every spawned child and bypassing the fd delivery's close decisions (issue2310: a {v}<&- close for the child must close a placed fd too); the placed descriptor is CLOEXEC again right after the dup2, per the fd layer's discipline (src/fd/unix.rs). 2. CLI cell c_exec_invalid_expanded_option_discards_redirect: the provisional exec scope restored only the table, leaving the kernel placement behind it. FdTable gains a placement undo log — GNU's add_undo_redirect port (redir.c): the displaced occupant is saved on a CLOEXEC dup before the placement dup2. execute_exec's provisional branch holds the undo open across option parsing (redir.c exec_redirection_undo_list): status 2 rolls the kernel back before the snapshot is restored, a clean parse commits; the genuine redirects-only path commits when its walk returns. 3. Cross-target compile error: the S_IFMT occupant check in place_persistent_file compared st_mode against S_IFDIR / S_IFSOCK directly (u32 vs u16 on linux/android, E0308/E0277); compare through u32 like external_file_builtins does. 4. Defect cells in CI (issue3640 exec_3/exec_4): see REPORT s9 — the saved CI census log carries 7 cells for the stem, matching the server; every constructible CI-equivalent shape (distinct inherited pipes on 3/4, many-fd inheritance, nextest ci profile, parallel stems) passes with the fix on the server. Snapshots no longer inherit placement arming or the undo log. Legs (server, rebased tree): nextest ci profile issue3640 / issue2310 / issue2690 / issue3403 / issue726 stems 39/39, CLI rollback cell pass, lib 1280 passed / 0 failed / 4 skipped (base name set unchanged), RUSTFLAGS=-D warnings check rc=0, rustfmt clean on touched files, hygiene scripts clean.
13d4d09 to
8189ce5
Compare
队长复核(返工头 8189ce5):待改——回归全清、CLI 转绿,但缺陷格在 CI 仍红已修好的部分(确认):头 CI census 里 7 格 fd 回归全绿(issue2310 8/0、issue2690 4/0、issue3403 11/0、issue726 15/0);CLI 全绿(回滚格转绿);census 79,新增仅 issue1902/issue2340 两抖动族;goldens 基线二名;服务器腿五 stem 39/39、lib 1280/0 名集一致。作用域门 + CLOEXEC 恢复 + undo 日志的方向都对。 仍红的本体: 即探针时刻父壳的 fd 3/4 仍是继承来的两条管道——落点在 CI 形态下根本没触发(不是落错位置)。钉的生成形态:测试进程以 std Command 拉起 rubash(stdin=null、stdout/stderr=piped、其余 fd 继承)。CI 里测试进程由 nextest→cargo→runner agent 链拉起,测试进程自身多半还持有继承 fd,rubash 启程时 fd 3/4 已被管道占住;服务器上从 shell 直跑测试二进制时测试进程无额外 fd,rubash 启程干净,常规路径恰好落在 3——这解释了为何服务器各种构造形态(含 nextest ci profile 直跑)全绿而 CI 独红:差别在测试进程→rubash 的继承集,不在 rubash 内部脚本形态。 下一轮返工的入口(队长已派专查车道):先在服务器上按 CI census 的确切调用(读 .github/workflows 的 census 步原文:nextest 命令与 env)复现红,再逐项二分继承集差异(fd 数/类型/来源),定位落点布防为何在「启程 fd 3/4 已占」时不触发;修后以 CI 头 census 该两格转绿为终局判据,服务器绿不单独结案。 |
…le (Fixes #3321) Fixes #3321 ## What was fixed `controlling_terminal_available()` only asked whether stderr is a tty (or `/dev/tty` opens) and never attempted the foreground acquisition, so an interactive shell started in a background process group ran straight through with job control on (`$-` = `himBHc`) where GNU stops on SIGTTIN until foregrounded or, with SIGTTIN blocked, bails after 18 attempts with `initialize_job_control: no job control in background` and drops `m` (`jobs.c:4731-4869`). The fix makes `controlling_terminal_available()` return a `TerminalAvailability` enum (Available / Unavailable / BackgroundBail) running GNU's loop: `shell_tty` is dup(stderr) or open(`/dev/tty`) when forced-interactive and stderr is not a tty (`jobs.c:4749-4766`); while `tcgetpgrp` says background, restore SIGTTIN to DFL and stop, bailing after the 18th kill (`tty_sigs++ > 16`, `jobs.c:4798`) with only the first diagnostic (`goto just_bail` skips the second line, `jobs.c:4797`). `establish_interactive_job_control` dispatches on the enum; the Unavailable arm keeps the two existing diagnostics untouched. The stop is delivered with `pthread_kill` to the looping thread, not `kill(0, SIGTTIN)`: rubash's main logic runs on a spawned worker thread (`main.rs`, 512MiB stack) while the OS thread parks in join, so a group-directed kill lands on an arbitrary thread and the group stop reaches the looping thread only asynchronously — supervisor verification measured `kill(0, ...)` returning in 2-3us while the loop spun up to all 18 iterations before any stop took effect, making the pin flaky (2/4, 3/4). A thread-directed `pthread_kill` stops the looping thread synchronously inside the call (270-680us round-trip through fg+CONT in a C model, one iteration, deterministic over 10 runs); the stop still arrests the whole process group, so the session leader's waitpid sees it exactly as with GNU's kill. ## What was deleted Nothing. No files, features, or tests were removed. ## A correction to the issue text (please do not quote it verbatim) The issue says the shape "would be misjudged as no ctty", but the measured direction is the opposite: unpatched rubash misjudges UNAVAILABLE job control as available (never stops, never errors, `$-` stays `himBHc`). The fix adds the foreground-acquire attempt the issue asks for. ## Verification (all run, per-item counts) - Regression pin `tests/issue3321_background_pgrp_job_control.rs`: **4/4 pass** (new pty harness `tests/interactive/support/pty_background_pgrp_probe.py`, built per the issue's gate note: one fresh pty session per leg, session leader holds the ctty, shell forked into a new background group). Legs: `bg-stop-then-fg` (must SIGTTIN-stop, then `himBHc` after fg, no diagnostics), `bg-sigttin-blocked` (no stop, only the background diagnostic, no second diagnostic, `hiBHc`), `bg-stderr-pipe` (same stop-then-fg with piped stderr), `fg-control` (direct `himBHc`, no stop). Fail-first on the unpatched tree (supervisor re-ran with the patch method): **1 passed / 3 failed** — green was exactly the `fg-control`. Supervisor re-ran the pin **10 times, 4/4 every time** (the `kill(0, ...)` form was flaky at 2/4 and 3/4, which is how the thread-delivery race was found). - GNU 5.3.20 oracle: **4/4** on the same harness (5/5 on the `bg-stop-then-fg` leg alone); blocked-face stderr byte-identical except the program-name prefix (`bash:` vs `target/debug/rubash:`, expected). - Adjacent: `issue2948_monitor_flag_regressions` 6/6, `issue2731_interactive_monitor_default` 6/6, `issue2774_interactive_no_tty_job_control` 4/4, `issue2487_suspend_job_control_gate` 11/11. - `cargo build -j 2` clean, `cargo fmt --check` clean. `src/lexer/continuation.rs` untouched. ## Owed 1. **Behaviour change for the captain to know about**: an interactive rubash started in a background process group now stops like GNU until foregrounded — this is GNU behaviour itself (`bash -i &` does this), but rubash previously ran straight through; a `run_interactive_stdin` library host driving it from a background group stops the same way (GNU stops at the same place). 2. The non-interactive `-m` arm (`main.rs`) still only looks at whether stderr is a tty — that is GNU's force path, a different face, and #2948 already pins its current behaviour. Out of scope here. 3. `running_in_background` (`jobs.c:4865`) has no rubash counterpart and no consumer; not introduced here. 4. The pin needs python3 + the pty module (same pattern as `pty_read_probe.py`); without that environment the test skips cleanly. ## 队长复核(新头 a5012fd,第 11 轮) - 旧头(973ae7a3,2026-11-12 代)三红已点名并在新代全部消失:`issue2859_jobs_face_stopped_job_counts`(Rust tests/macOS 转绿)、`issue2875_input_procsub_child_runs_as_rubash_shell`(goldens 回到基线二名)——均为旧基底伪影,与 foreground-acquire 改动无涉。 - 新头 CI:自带钉 issue3321 **4/4 全绿**(census 内);census 72,新增仅 issue2883 read-prompt 抖动格;CLI 唯一红 = 已裁定 coproc flake;其余腿全绿。 - 本 PR 删除了什么:script_driver.rs 内旧的 `controlling_terminal_available()` 实现体(stderr-is-terminal + /dev/tty 开探版,约 40 行)由 foreground-acquire 尝试版整体替换;无其他删除。 - 与现尖(4b582664,#3935 的两个测试文件)零交集,免再 update-branch。合后 #3321 由 Fixes 自动关;A29 与 #3320 的 script_driver 面随之解闸(#3320 仍待 #3538/#3930)。
|
队长复核(新头 9f7ce17,第二轮):待改——两格缺陷格已按名转绿,但 census 出现一组新的 fd 面红。 已达标
新红(census 63,总数反降,但新增 14 名)
具象线索: 下一轮任务:逐族二分——哪一处下限改动(dup_adopted_fd 还是 FileFd::duplicate)引起哪几族;每格先以 GNU 5.3.20 oracle 判定新行为与钉期望孰对:钉对则修法保住钉,新行为对则凭 oracle 证据对齐钉(不许只改期望)。两格缺陷格与新钉在新头上保持绿是本轮的硬约束,勿动根因修法本身的落点语义。 |
Round 3 of the #3917 fix. The bisect over the 12-cell set (r2 / A / B / AB x S1 / S2) showed the lever is the adopted copy's parking number, not the save floor: variant A (adoption dup floor 10 -> 0) turned all five issue3213 cells green, B (FileFd::duplicate floor) changed nothing. The borrowed-handle design (adopted entries naming the inherited descriptor itself) was implemented first and rejected on evidence: the lib suite aborted in issue863_gap11_provider_merge_keeps_engine_mark_and_provider_kind with an IO Safety violation — a second Session's init census adopted the first Session's cwd anchor (fd 255), an engine lifecycle closed it by number, and the owning session's anchor File drop hit EBADF. Borrowed handles remove the #1838 insulation the private copy exists for; reverted in full. Landed instead: adopted copies become evictable. FileFd gains an `adopted` flag set only by register_inherited_process_fds. evict_adopted_copy_from relocates a copy parked on a contested number to a fresh F_DUPFD_CLOEXEC descriptor at or above SHELL_FD_BASE and repoints every table arm, so a materialization or placement never refuses a bind because of the executor's own bookkeeping. GNU has no such copy (its table names the inherited descriptor by its own number, redir.c:1160) and itself relocates internal descriptors out of the way (move_to_high_fd, general.c:702; F_DUPFD saves, redir.c:965/:1082/:1144). No floor moved anywhere. The materialize arms also mark the source displaced when a replacement is installed, so a dup of an adopted copy onto its own parking number ({v}>&3) is not closed by the source object's drop. Server legs (r3-fix-leg): five stems 47/47; per-cell S1 and S2 issue3213 x5 green, issue3640 defect cells green; lib 1280/0/4 on both fix and base with an empty fail-set diff; RUSTFLAGS="-D warnings" rc=0; hygiene scripts rc=0. issue1184 is pin-environment (red under S1 for every variant incl. GNU-silent oracle) — pin alignment proposed in the REPORT, not applied. issue1523 fails identically under every variant and is not an occupancy face; the head census arbitrates. Full record: fix-3917 REPORT section 11.5. This change deletes no files, functions, or tests: it adds one FileFd field (filled at all constructors), one eviction method and its call sites, and displaced-marking calls in the materialize arms.
… shape (Refs #3936) fix(parser): return latched loop body/condition errors instead of EOF shape (Refs #3936) ## 根因 `parse_loop_body(...)?` 的 None 臂把体部已锁存的错误吞回 EOF 形:`while`/`until` 体部算术参数在 EOF 处报错时,解析器丢弃了 `compound_body_parse_error` 已锁存的错误,报成 `while`/`until` 控制词缺失。#3184 缺陷 B(if 形) 的同族,另一文件(loop_command.rs)。GNU 锚:parse.y:6724/6841、:4896/4926。 ## 修法 三处锁存错误丢失点改为同形直接返回 `compound_body_parse_error` (loop_command.rs),不改任何其他语义。残差 w7(`while x; do do echo hi; done`, GNU 点名 `do`、本品点名 `done`)有意不钉。 ## 本 PR 删除了什么 无删除。本 PR 为纯加法:3 处直接返回 + 1 个新回归钉文件 (tests/issue3936_while_until_body_latched_error.rs,18 格); 队长卫生提交 3090347 仅做 rustfmt 空白对齐。 ## 队长裁定(头 3090347,CI run 44470616506;服务器腿 run-3936 + run-3936-resume) - 钉:CI 普查里 issue3936 stem **18/18 PASS**;服务器 fail-first base 树 **8 passed / 10 failed**(10 个 latched-error 形态全红,与预期逐格一致)。 - 服务器腿:探针矩阵 **20/20 SAME**(对 GNU 5.3.20 oracle);相邻钉 issue3184 两 stem 21/21 + 7/7、issue3204 7/7 全绿;issue2741_2742 stem 在 base 树同为 2/7 逐格一致(tip 与本 PR 头的 CI 普查名集均无此 stem)—— 本地 harness 既存形态,非本 PR 回归;lib base 与 fix 均 1280/0/4, 失败名集双向对齐;`RUSTFLAGS="-D warnings"` rc=0。 - 普查:70 名;较尖(69 名)新增 2 格——issue2029 `head_two_lines_then_read_continues` 与 issue3633 `dead_coproc_unbinds_after_pipe_read`,二者均在 #3928、#3930-r2 的头普查里翻红过(其修复到不了这两个面),且本头与零新增的前头 75d014c 只差一处空白 fmt 提交——按既定普查抖动标准裁为抖动,非回归;尖集里 issue1902 stdin 格翻绿。 - Goldens 恰好基线 2 名;CLI 仅 1 红——已记录的 coproc CLI 抖动 `c_command_keeps_named_coproc_output_fds_distinct`;其余腿(Rust tests、 Shell、darwin、linux/android、Windows 编译、niubash 构建、API ledger)全绿。 - 零交集证明:base 6c8ff4e...尖 e9e3d7a = 26 文件,与本 PR 的 2 文件无交集, 免 update-branch 合入。
|
队长裁定:待改(头 e2645ce,CI run 44470376453)。 先说好的:缺陷格(issue3640 阻合项(三件,第四轮做):
不阻合的:issue1902 第四轮续跑:修 (1) 的可移植调用 + 复现定性并处理 (2) + 按备稿 |
rubash#3917 (round 4): `exec 3<>file` left fd 3 closed when fd 3 started closed (a2_11 mapfile + issue2298 control red, and the shared-offset cell hung). Root cause: the pregate probe retains its opened File in pending_preopened_redirects, the exec walk re-opens the target (fd 4), and the persistent placement dup2's 4 onto 3 — then the retained probe FileFd still naming 3 is dropped and closes the placed descriptor. Consuming the preopened entry for the position before the application opens the target again restores GNU's single-open walk (redir.c:237 do_redirections): the probe handle is dropped while fd 3 is still free, so the application open lands on 3 and no dup2 runs. The 1523 S1 cells are NOT fixed here: they fail identically on pristine 44823dd (pre-existing procsub fd-3 leak; GNU oracle proves the pins GNU-correct in S1 — separate issue).
|
队长裁定:第四轮头 138748b(CI run 44486016849)仍待改,
|
…930, round 5) A persistent exec N<&- removed only the FdTable entry: the startup-adopted copy was dropped (close(10)) while the inherited kernel fd N stayed open. A respawned child re-adopted it and the spawn pin pass installed it, so the procsub body's >&N succeeded after the parent's own >&N already failed (issue1184 f4cond red in S1/S2). Close the kernel descriptor too, gated threefold: the removed entry was an adopted copy, the persistent-close flag is armed (the exec walk at true persistent scope - same gate as kernel_place_persistent), and the fstat (dev, ino) identity of the copy matches kernel fd N, so a dup-shared adopted Rc or a runtime pipe on the number is never closed by mistake. fd < 3 stays with close_orphaned_process_fd. GNU redir.c:1239 case r_close_this, redir.c:1267 close_buffered_fd.
…930, round 5 follow-up) spawn_whitelisted's doc promises 'dup2 each spec fd onto its own number, then close everything else', but only the dup2 half was implemented. The parent's lazily-installed signal self-pipe socketpair (kill.rs install) lands on the lowest free fd - fd 3 once exec 3<&- freed it - and, being non-CLOEXEC, survived execve into the respawned procsub body, where the startup adoption took it as user fd 3 and the body's >&3 succeeded, resurrecting the number the user had explicitly closed (issue1184 f4cond S1/S2). Implement the missing close: in pre_exec, after pinning the extras, close every fd >= 3 except the extras and the cwd anchor (mirroring spawn_async_direct's 'GNU close_fd_bitmap: nothing above fd 2 survives into the exec', floored at 1024). User fds are all stamped into extras, so none is closed; the child is born with only stdio + stamped fds + anchor. GNU: redir.c:1239 r_close_this / redir.c:1267 close_buffered_fd (redirector) for the explicit-close semantics; the respawn must reproduce GNU's fork-child fd table (a closed number stays closed in the child). Refs #3917.
…30, round 6) duplicate_handle_inheritable used plain dup, landing on the lowest free descriptor — which can be a user fd the shell considers CLOSED (3 after `exec 3<&-`). Made inheritable and inherited by a plain-spawn `>(...)` body, it resurrected fd 3 in the child's table, so the body's `>&3` succeeded where GNU reports `Bad file descriptor` (f4cond S1). GNU: redir.c:86 SHELL_FD_BASE=10; subst.c:6362 process_substitute fork inherits the parent's fd table (fd 4 open, fd 3 closed). Fix: F_DUPFD_CLOEXEC at/above 10; every consumer re-dups the transport key onto its target number at restore, so the floor costs nothing.
|
审计复核(2026-11-19,头 ec17d63,round 6):待改——合并被一个新 CI 红阻塞。 红本体:Rust tests(Linux,run 44508636352/job 135506724458) 根因(已复现证实,非猜测):round 6(ec17d6389)把 修法建议(test 侧即可):Linux 腿改走 /proc/self/fd(本来就可用),数字 dup 路径留给 macOS(bash 认 <&N);或子进程显式用 bash。产品代码(下限本身)不需要回退——SHELL_FD_BASE 口径正确。 Windows 侧我已复核:lib 失败集 {issue2084} 与 base 一致。GNU 锚点(redir.c:86/:1017/:1120/:1239-1266 close_buffered_fd、exec.def undo list、general.c:702 move_to_high_fd、general.h:257)全部对树核实无误;与已合 #3849/#3850 快照族的关系(base 已含两 PR;snapshot 清 placement_undo/arming)在 diff 里是显式处理的。修掉测试机制后重新进入审计。 |
… (rubash#3930)
The SHELL_FD_BASE floor (round 6) puts duplicate_handle_inheritable
results at >= 10 by design (redir.c:940 floors GNU's own descriptor
saves the same way). The probe spawned POSIX sh and wrote <&{extra},
but dash rejects a multi-digit dup target outright - "sh: 1: Syntax
error: Bad fd number" for <&10 (dash 0.5.12: the literal, the
variable-expanded and the left-side forms are all refused; verified
against the runner shape) - so the contract under test (the extra
survives AT ITS OWN NUMBER) was unexpressable past fd 9. Drive the
probe with bash; the /proc alternative stays rejected because macOS
has no /proc.
Also drop a nested unsafe block in the spawn_whitelisted close loop
(the pre_exec closure body is already one unsafe block) so
RUSTFLAGS=-Dwarnings builds again.
Fixes the deterministic "Rust tests" red on this PR. Verified: cargo
test --lib 1280/1280 green; the probe passes 10/10 repeats;
rustfmt --check clean; -D warnings clean.
…onto the slot (rubash#3938) (#3957) Three residuals of the #3930 placement, fixed through the same landing mechanism (one dup2 discipline, not per-face patches), all verified against WSL GNU bash 5.3.20 script-file probes: Face A - dup redirects materialize. `exec 3>&1` was a table-only Rc alias: kernel descriptor 3 never existed and `readlink /proc/$$/fd/3` failed while GNU's duplicating redirector dup2's the source onto the redirector unconditionally (redir.c:1190, case r_duplicating_input/r_duplicating_output). New FdTable::place_persistent_dup_arms runs the same guard suite as place_persistent_file (arming, adopted-copy eviction, held-scan, dir/socket refusal, placement undo save, CLOEXEC restore) and lands the kernel dup2. The caller's clone arms stay: a kernel-backed source keeps sharing the source's Rc (one open file description), a symbolic stdio source keeps its marker arm - the rubash#3432 fact marks are minted per endpoint kind, and rewriting a marker slot to a File arm rewrote `[ -e /proc/$$/fd/N ]` operands to an unresolvable path label (measured: the -e verdict flipped). The known residual: `exec 3>&1 > /dev/null; echo hi >&3` still follows the live stdout through the marker (pre-#3938 behavior, the Stdout-marker model, unchanged by this lane). Face B - fd >= SHELL_FD_BASE occupied. `exec 12>b` when 12 was already occupied kept the #3213 free-only materialization (refuse and stay virtual) while GNU's dup2 replaces the occupant unconditionally (redir.c:1017). The SHELL_FD_BASE ceiling inside place_persistent_file is lifted; the held-scan still refuses a number a live {var} allocation owns and the dir/socket refusal still protects the cwd anchor and the signal socketpair. Face C - scope restores land the save back on the slot. A scope save (saved_entry/saved_table, rubash#3706/#3814) duplicates each kernel-backed endpoint so the bind-time retire cannot kill the description; replaying it into a slot whose kernel number the scope's bind vacated used to leave the entry naming the PARKED duplicate - kernel fd 3 vanished (the compound's own bind closed it) and the private duplicate leaked until process end (`exec 3>f; { :; } 3</dev/null` left an extra /proc descriptor naming f beside a dead fd 3). The three compound restore points (numbered input, compound output, dynamic-close snapshots) now run FdTable::land_restored_entry: kernel fd free -> dup2 the save onto the number, rebuild the arms on the landed descriptor, close the parked duplicate once nothing else names it - GNU's undo replay, a r_move record (redir.c:1399 add_undo_fd_redirect; dup2 at :1190, source close at :1230). The landing never clobbers: an occupied slot number keeps the parked shape. Legs: new pins tests/issue3938_exec_redirect_integrity.rs 7/7 (fail-first verified on the merged master: 5 of 7 red there); issue3640 9/9; issue1184 f4 7/7; cli fd_redirects 19/19, dev_fd_operands 21/21, process_substitution 11/11; full lib 1280/1280; rustfmt --check clean; RUSTFLAGS=-Dwarnings clean. GNU oracle: `exec 3>&1`, `exec 3<&0`, `exec 12>a; exec 12>b` and the compound/function restore shapes byte-identical on /proc/$$/fd stable sets (the #3640 cwd anchor at 255 remains the one documented non-GNU descriptor). Refs #3917. Fixes #3938. Co-authored-by: caomengxuan666 <[email protected]>
…onto the slot (rubash#3938) Three residuals of the #3930 placement, fixed through the same landing mechanism (one dup2 discipline, not per-face patches), all verified against WSL GNU bash 5.3.20 script-file probes: Face A - dup redirects materialize. `exec 3>&1` was a table-only Rc alias: kernel descriptor 3 never existed and `readlink /proc/$$/fd/3` failed while GNU's duplicating redirector dup2's the source onto the redirector unconditionally (redir.c:1190, case r_duplicating_input/r_duplicating_output). New FdTable::place_persistent_dup_arms lands the kernel dup2 through the same guard suite as place_persistent_file (arming, adopted-copy eviction, held-scan, dir/socket refusal, CLOEXEC restore). The placement lands on a FREE number only: an occupied target means a descriptor of this very install chain sits there (the rubash#2385 complementary-write flow opens the O_WRONLY end at the slot's number and adds the read arm through dup_input - dup2-ing the read source over it would destroy that fresh description behind the caller's back). The caller's clone arms stay: a kernel-backed source keeps sharing the source's Rc (one open file description), a symbolic stdio source keeps its MARKER arm - the rubash#3432 fact marks are minted per endpoint kind, and rewriting a marker slot to a File arm rewrote `[ -e /proc/$$/fd/N ]` operands to an unresolvable path label (measured: the -e verdict flipped). The known residual: `exec 3>&1 > /dev/null; echo hi >&3` still follows the live stdout through the marker (pre-#3938 behavior, the Stdout-marker model, unchanged by this lane), and an occupied-target dup keeps the pre-#3938 virtual model. Face B - fd >= SHELL_FD_BASE occupied. `exec 12>b` when 12 was already occupied kept the #3213 free-only materialization (refuse and stay virtual) while GNU's dup2 replaces the occupant unconditionally (redir.c:1017). The SHELL_FD_BASE ceiling inside place_persistent_file is lifted; the held-scan still refuses a number a live {var} allocation owns and the dir/socket refusal still protects the cwd anchor and the signal socketpair. The readwrite wrapper refuses a placement whose OTHER arm's own kernel handle sits on the target number (the #2385 complementary write - the placement dup2 would clobber it; measured as an EBADF write regression before the guard). Face C - scope restores land the save back on the slot. A scope save (saved_entry/saved_table, rubash#3706/#3814) duplicates each kernel-backed endpoint so the bind-time retire cannot kill the description; replaying it into a slot whose kernel number the scope's bind vacated used to leave the entry naming the PARKED duplicate - kernel fd 3 vanished (the compound's own bind closed it) and the private duplicate leaked until process end (`exec 3>f; { :; } 3</dev/null` left an extra /proc descriptor naming f beside a dead fd 3). The three compound restore points (numbered input, compound output, dynamic-close snapshots) now run FdTable::land_restored_entry: kernel fd free -> dup2 the save onto the number, rebuild the arms on the landed descriptor, close the parked duplicate once nothing else - INCLUDING the entry's own opposite arm - names it (a saved `<>` pair is one Rc across the arms; measured: closing it orphaned the write arm into EBADF). GNU's undo replay, a r_move record (redir.c:1399 add_undo_fd_redirect; dup2 at :1190, source close at :1230). The landing never clobbers: an occupied slot number keeps the parked shape. Legs: new pins tests/issue3938_exec_redirect_integrity.rs 7/7 (fail-first verified on the merged master: 5 of 7 red there); issue3640 9/9; issue1184 f4 7/7; issue2385 19/19; issue3706 12/12; cli fd_redirects 19/19, dev_fd_operands 21/21, process_substitution 11/11; full lib 1280/1280; rustfmt --check clean; RUSTFLAGS=-Dwarnings clean. GNU oracle: `exec 3>&1`, `exec 3<&0`, `exec 12>a; exec 12>b` and the compound/function restore shapes byte-identical on /proc/$$/fd stable sets (the #3640 cwd anchor at 255 remains the one documented non-GNU descriptor). Refs #3917. Fixes #3938.
根因
exec 3>file/exec 4>file从不把文件落到内核 fd 3/4 上:rubash 的 fd 表是虚拟的,FileFd::open_write返回open()给出的任意内核 fd(最低空闲号),FdTable::open_output只把它装进虚拟表,从不dup2到目标号。fd 3/4 空闲时(直接运行、服务器)open()正好返回 3/4,钉绿;census runner 里内核 fd 3/4 被继承的 pipe 对占用时,文件落在更高的内核 fd 上,/proc/$$/fd/3仍显示 pipe,两格恒红。GNU 是dup2到 redirector 上(redir.c:1017/:1120),所以号本身就是文件。证据链:GNU 5.3.20 oracle 上钉的两个脚本均得
fd3-is-file/fd4-is-file;服务器上cargo nextest run --profile ci --test issue3640_startup_cwd_fd37/7 绿(nextest 无罪);服务器上从持有 pipe(fd 3,4)的 bash 父进程 spawn rubash 跑同一脚本,复现出与 CI 完全一致的输出(fd3-not-file / pipe:[...] / pipe:[...])。GNU 锚点
redir.c:237 do_redirections、redir.c:790 do_redirection_internal、redir.c:725 redir_open(fix(executor): open existing FIFO redirect targets via the cwd anchor in a deleted cwd #3363 吸收链已纠正的行号)redir.c:1017/:1120:else if ((fd != redirector) && (dup2 (fd, redirector) < 0))—— 打开的文件dup2到 redirector 号上general.c:702 move_to_high_fd、general.h:257 HIGH_FD_MAX=256—— 内部描述符移出低位区redir.c:86 SHELL_FD_BASE=10—— varredir 物化 fd 在 shell 自身 /proc/$$/fd 视图不可见(GNU 可见) #3213 物化机制的分界(本修法沿用同一分界)改动
src/executor/fd_table.rs:新增FdTable::kernel_place_persistent标志与place_persistent_file/place_persistent_{read,write,readwrite}_endpoint/mark_displaced_by_dup2。裸顶层exec游走期间,fd < 10 的文件型安装dup2到其逻辑内核号上;fd ≥ 10 保持 varredir 物化 fd 在 shell 自身 /proc/$$/fd 视图不可见(GNU 可见) #3213 的 free-only 物化({var} 分配也在此区,其 replay snapshot 共享 Rc,replace-dup2 会使其失效,故不碰)。拒绝条件:号被另一 live 表项的非 retired File/Coproc handle 持有,或号上是目录(cwd anchor)/ socket(signal socketpair、/dev/tcp)——二者绝不替换;pipe 与普通文件按 GNU 语义替换。被dup2关掉的 outgoing 描述符记 retired,防止 retire 步骤关掉新文件。src/executor/trap_exec.rs:execute_stdio_only_exec_redirect拆为 wrapper + inner,wrapper 按place_persistent参数设/复位标志(覆盖全部 early return)。裸顶层exec(builtin_wrapper_depth == 0)传true;scoped 游走传false——scoped 的 undo 只回放虚拟表,带不回被dup2关掉的外部占用者,故绝不 placement。src/fd/unix.rs(create_capture_pipe)与src/builtins/kill.rs(wrapper_relay_install):内部 pipe 两端move_to_high_fd移出用户区,否则持久exec N>file可能把 capture/relay pipe 当作占用者替换掉。tests/issue3640_startup_cwd_fd3.rs:启动格issue3640_startup_fd3_is_pipe_not_cwd是空洞的——fd 3 空闲时探针自身的 comsub capture pipe 占 (3,4),readlink看到的是探针自己的 pipe;且 残差(#3640/#3891):exec 3>file / exec 4>file 不落指定 fd,自带钉两格恒红 #3917 的 capture pipe 上移会把它 unmask。改写为issue3640_startup_no_low_fd_is_cwd:无 comsub 探针,逐个readlinkfd 3..9 到 scratch 文件,断言其中没有 cwd 路径。本 PR 删除了什么
issue3640_startup_fd3_is_pipe_not_cwd的旧探针形态($(readlink /proc/$$/fd/3)判 pipe)——该形态是空洞的,见上;由issue3640_startup_no_low_fd_is_cwd(无 comsub 探针)替代,断言的真实不变量不变(cwd anchor 不在低位 fd 上)。exec 3>file等持久重定向的内核落点由“虚拟”改为 GNU 的dup2语义。验证(UNVERIFIED-BY-CAPTAIN)
RUSTFLAGS="-D warnings"check、hygiene + 逐文件 rustfmt --check。exec 3>&1类 dup 重定向仍共享 Rc、无内核 fd 3;{var}带操作数的持久绑定未覆盖;fd ≥ 10 被占用时仍保持 varredir 物化 fd 在 shell 自身 /proc/$$/fd 视图不可见(GNU 可见) #3213 的 free-only 物化(虚拟回退)。Refs #3917