Skip to main content

zsh/ported/
exec.rs

1//! Faithful Rust ports of free functions and file-static globals from
2//! `Src/exec.c`. The wordcode-VM dispatch tree (`execlist` / `execpline`
3//! / `execcmd` / `execsimple` etc.) that drives execution in C zsh is
4//! NOT replicated here — zshrs runs the fusevm bytecode VM instead
5//! (see `src/vm_helper.rs` + `src/fusevm_bridge.rs`).
6//!
7//! What lives here are the parts of `Src/exec.c` that ARE faithful
8//! ports and don't depend on the C-side wordcode walker:
9//!
10//! - **`trap_state` / `trap_return` / `forklevel`** — file-static
11//!   integer globals from `Src/exec.c:134 / :155 / :1052`, exposed as
12//!   atomics shared between this module, `Src/signals.c`'s port at
13//!   `src/ported/signals.rs`, and `Src/params.c`'s port at
14//!   `src/ported/params.rs`.
15//! - **`gethere`** (`Src/exec.c:4573`) — turn a here-document into a
16//!   here-string. Called from the lexer port (`src/ported/lex.rs`).
17//! - **`getoutput`** (`Src/exec.c:4712`) — command-substitution body
18//!   runner. Called from the parameter-expansion port
19//!   (`src/ported/subst.rs`).
20//! - **`loadautofn`** + **`getfpfunc`** (`Src/exec.c:5050` / `:5260`)
21//!   — `$fpath` walker + autoload file installer. Called from
22//!   `bin_autoload` / `bin_functions -c` in `src/ported/builtin.rs`.
23//! - **`resolvebuiltin`** (`Src/exec.c:2703`) — module-autoload guard
24//!   used by the dispatch walk in `execcmd_exec`.
25//! - **`execcmd_compile_head`** — fusevm-bytecode-time head resolver
26//!   mirroring the head section (`c:2904-3275`) of C's `execcmd_exec`.
27//!   NOT a faithful port; the canonical 7-arg `execcmd_exec` port lives
28//!   alongside it.
29//! - **`execcmd_exec`** (`Src/exec.c:2900`) — canonical 7-arg port of
30//!   the C function (locals + dispatch walk through builtin/shfunc/external
31//!   invocation). Used by future tree-walker callers; the fusevm
32//!   bytecode flow goes through `execcmd_compile_head` instead.
33
34use std::os::unix::fs::PermissionsExt;
35use std::sync::atomic::Ordering;
36
37// `with_executor` import removed — all ShellExecutor reach-in calls
38// routed through `crate::ported::exec_hooks::*` fn-ptrs installed by
39// fusevm_bridge at startup. See memory feedback_no_exec_script_from_ported.
40use crate::ported::builtin::{cd_able_vars, fixdir, BUILTINS, DOPRINTDIR, EXIT_VAL, LASTVAL};
41use crate::ported::builtins::rlimits::setlimits;
42use crate::ported::builtins::sched::zleactive;
43use crate::ported::compat::zgettime_monotonic_if_available;
44use crate::ported::config_h::DEFAULT_PATH;
45use crate::ported::context::{zcontext_restore, zcontext_save};
46use crate::ported::hashtable::{
47    cmdnam_unhashed, cmdnamtab_lock, dircache_set, hashdir, pathchecked, shfunctab_lock,
48};
49use crate::ported::hist::{strinbeg, strinend};
50use crate::ported::init::{shout, underscorelen, underscoreused, zunderscore, SHTTY};
51use crate::ported::input::{inpop, inpush};
52use crate::ported::jobs::{expandjobtab, get_usage, release_pgrp, waitforpid, JOBTAB, THISJOB};
53use crate::ported::lex::{
54    hgetc, parsestr, tok, untokenize, ztokens, LEXERR, LEX_LEXSTOP, LEX_LINENO,
55};
56use crate::ported::mem::{dupstring, dyncat, popheap, pushheap};
57use crate::ported::modules::clone::mypgrp;
58use crate::ported::options::{dosetopt, opt_state_set, sticky};
59use crate::ported::params::{
60    endparamscope, getsparam, locallevel, paramtab, setiparam, zgetenv, zputenv,
61};
62use crate::ported::parse::{closedumps, ecrawstr, parse_list};
63use crate::ported::prompt::{cmdpop, cmdpush};
64use crate::ported::signals::{
65    intrap, queue_signals, settrap, signal_mask, signal_unblock, sigtrapped, trapisfunc,
66    traplocallevel, unqueue_signals, unsettrap,
67};
68use crate::ported::signals_h::{
69    child_block, child_unblock, dont_queue_signals, signal_default, signal_ignore, winch_unblock,
70    SIGCOUNT,
71};
72use crate::ported::subst::{quotesubst, singsub};
73use crate::ported::utils::{
74    errflag, fdtable_get, fdtable_set, gettempfile, gettempname, inc_locallevel, movefd, pathprog,
75    printprompt4, quotedzputs, redup, unmeta, unmetafy, write_loop, zclose, zerr, zwarn,
76    ERRFLAG_ERROR, MAX_ZSH_FD,
77};
78use crate::ported::zsh_h::{
79    builtin, cmdnam, emulation_options, eprog, execstack, funcwrap, hashnode, isset, multio, redir,
80    shfunc, unset, wc_code, Emulation_options, Inang, Inpar, Meta, Nularg, Outpar, Pound,
81    BINF_BUILTIN, BINF_CLEARENV, BINF_COMMAND, BINF_DASH, BINF_EXEC, BINF_PREFIX, CHASEDOTS,
82    CHASELINKS, CLOBBER, CLOBBEREMPTY, CS_CMDSUBST, ERRFLAG_INT, FDT_EXTERNAL, FDT_INTERNAL,
83    FDT_PROC_SUBST, FDT_SAVED_MASK, FDT_TYPE_MASK, FDT_UNUSED, FDT_XTRACE, HASHDIRS, INP_LINENO,
84    INTERACTIVE, IS_CLOBBER_REDIR, IS_DASH, JOBTEXTSIZE, MAX_PIPESTATS, MONITOR, MULTIOS,
85    MULTIOUNIT, PATHDIRS, PM_LOADDIR, PM_READONLY, PM_UNDEFINED, POSIXBUILTINS, POSIXJOBS,
86    POSIXTRAPS, REDIRF_FROM_HEREDOC, REDIR_CLOSE, REDIR_HEREDOCDASH, REDIR_HERESTR, REDIR_INPIPE,
87    REDIR_OUTPIPE, USEZLE, VERBOSE, WC_LIST, WC_LIST_TYPE, WC_PIPE, WC_PIPE_END, WC_PIPE_TYPE,
88    WC_REDIR, WC_REDIR_TYPE, WC_REDIR_VARID, WC_SIMPLE, WC_SIMPLE_ARGC, WC_SUBLIST, WC_SUBLIST_END,
89    WC_SUBLIST_FLAGS, WC_SUBLIST_TYPE, WC_TYPESET, ZSIG_FUNC, ZSIG_IGNORED, Z_END,
90};
91use crate::ported::zsh_system_h::timespec as ZshTimespec;
92use crate::ported::ztype_h::{inull, itok};
93use crate::zsh_h::XTRACE;
94
95/// Port of the anonymous `enum { ... }` from `Src/exec.c:35-40`.
96/// Flag bits passed as the `addflags` argument to `addvars` /
97/// `addvarsfromargs`:
98///   - `ADDVAR_EXPORT`  (1<<0) — export each assignment for the
99///                                command `VAR=val cmd ...` form.
100///   - `ADDVAR_RESTORE` (1<<2) — the variable list is being restored
101///                                later (implicit local scope), so
102///                                suppress `ASSPM_WARN`.
103pub const ADDVAR_EXPORT: i32 = 1 << 0; // c:37 (Src/exec.c)
104/// `ADDVAR_RESTORE` constant.
105pub const ADDVAR_RESTORE: i32 = 1 << 2; // c:39 (Src/exec.c)
106
107/// Port of `int trap_state;` from `Src/exec.c:134`. Tracks whether
108/// a trap handler is currently being processed and, paired with
109/// `TRAP_RETURN` below, whether a `return` inside the trap should
110/// promote to `TRAP_STATE_FORCE_RETURN` to unwind the trap caller.
111///
112/// Values: `TRAP_STATE_INACTIVE = 0`, `TRAP_STATE_PRIMED = 1`,
113/// `TRAP_STATE_FORCE_RETURN = 2` (see `Src/zsh.h`).
114pub static TRAP_STATE: std::sync::atomic::AtomicI32 = // c:134 (Src/exec.c)
115    std::sync::atomic::AtomicI32::new(0);
116
117/// Port of `int trap_return;` from `Src/exec.c:155`. Carries the
118/// pending exit status from inside a trap; sentinel `-2` means
119/// "running an EXIT/DEBUG-style trap at the current level"
120/// (signals.c:1166). Promoted to the user's `return N` value by
121/// `bin_return` when POSIX-trap semantics apply (builtin.c:5852).
122pub static TRAP_RETURN: std::sync::atomic::AtomicI32 = // c:155 (Src/exec.c)
123    std::sync::atomic::AtomicI32::new(0);
124
125/// Port of `int forklevel;` from `Src/exec.c:1052`. Records the
126/// `locallevel` at the most recent fork point (set at c:1221:
127/// `forklevel = locallevel;` inside `entersubsh()`). Used by:
128///   - `signals.c:808` SIGPIPE handler — `!forklevel` distinguishes
129///     the top-level shell from a forked subshell.
130///   - `exec.c:6146` — `if (locallevel > forklevel)` decides whether
131///     a function-defined trap should fire on this subshell exit.
132///   - `params.c:3724` — WARNCREATEGLOBAL nest-depth check.
133///
134/// Initialised to 0 (no fork has occurred yet). Set to `locallevel`
135/// at every `entersubsh()` entry per c:1221.
136pub static FORKLEVEL: std::sync::atomic::AtomicI32 = // c:1052 (Src/exec.c)
137    std::sync::atomic::AtomicI32::new(0);
138
139// =============================================================================
140// File-static globals from Src/exec.c. Bucket choices per PORT_PLAN.md:
141//   - Per-evaluator transient state → thread_local Cell (bucket 1)
142//   - Shell-wide shared state       → AtomicI32 / Mutex (bucket 2)
143// All names match C exactly. Surrounding doc-comments cite the C
144// declaration line.
145// =============================================================================
146
147/// Port of `int noerrexit;` from `Src/exec.c:72`. Bit-flags that
148/// suppress ERREXIT triggering on the next command(s). Bits:
149/// `NOERREXIT_EXIT` (in `if`/`while`/`until` test contexts),
150/// `NOERREXIT_RETURN` (after `return`), `NOERREXIT_UNTIL_EXEC`
151/// (until next exec'd command). Bucket-1 — per-evaluator (each
152/// recursive eval has its own suppression frame).
153pub static noerrexit: std::sync::atomic::AtomicI32 = // c:72 (Src/exec.c)
154    std::sync::atomic::AtomicI32::new(0);
155
156/// Port of `int this_noerrexit;` from `Src/exec.c:109`. When set,
157/// suppress ERREXIT for THIS one command only (consumed + cleared
158/// before the next command starts). Set by `execcursh` and the
159/// `((expr))` arith path so a 0-result doesn't trigger errexit.
160pub static this_noerrexit: std::sync::atomic::AtomicI32 = // c:109 (Src/exec.c)
161    std::sync::atomic::AtomicI32::new(0);
162
163/// Port of `mod_export int noerrs;` from `Src/exec.c:117`. When
164/// non-zero, suppress `zerr()` output (lex error reporting during
165/// `parse_string`, `parseopts` etc.). Saved/restored by
166/// `execsave`/`execrestore`.
167/// Port of `static char list_pipe_text[JOBTEXTSIZE]` from
168/// `Src/exec.c:463`. Holds the textual rendering of the in-flight
169/// pipe list; saved across nested execlist invocations at
170/// exec.c:1372-1380 (zeroed on entry, restored from
171/// `old_list_pipe_text` at c:1634-1638) and round-tripped through
172/// execsave/execrestore (c:6448 / c:6484). zshrs models it as a
173/// length-bounded String guarded by a Mutex — the C `char[80]` cap
174/// is a buffer-overflow guard, but matching length matters for the
175/// `jobs` builtin's pipe-list rendering.
176pub static LIST_PIPE_TEXT: std::sync::Mutex<String> = std::sync::Mutex::new(String::new()); // c:463 (Src/exec.c)
177
178pub static noerrs: std::sync::atomic::AtomicI32 = // c:117 (Src/exec.c)
179    std::sync::atomic::AtomicI32::new(0);
180
181/// Port of `int nohistsave;` from `Src/exec.c:122`. When non-zero,
182/// `addhistnode` no-ops so trap firings / `eval` invocations don't
183/// pollute `$HISTCMD`. Tracked alongside `noerrs` in the trap path.
184pub static nohistsave: std::sync::atomic::AtomicI32 = // c:122 (Src/exec.c)
185    std::sync::atomic::AtomicI32::new(0);
186
187/// Port of `int subsh;` from `Src/exec.c:160`. Subshell depth — bumped
188/// every time `entersubsh` forks a sub-shell, used by signal handling
189/// (different SIGINT semantics in subshells) and by `${$$}` (`$$`
190/// stays at the top-level pid).
191pub static subsh: std::sync::atomic::AtomicI32 = // c:160 (Src/exec.c)
192    std::sync::atomic::AtomicI32::new(0);
193
194/// Port of `mod_export int zsh_subshell;` from `Src/init.c:67`. Visible
195/// `$ZSH_SUBSHELL` parameter — incremented by `entersubsh()` each time
196/// the shell forks into a subshell (real or fake-exec). Distinct from
197/// `subsh` which records whether we ARE a subshell; `zsh_subshell` is
198/// the visible depth count.
199pub static zsh_subshell: std::sync::atomic::AtomicI32 = // c:67 (Src/init.c)
200    std::sync::atomic::AtomicI32::new(0);
201
202/// Port of `mod_export volatile int retflag;` from `Src/exec.c:165`.
203/// Set by `bin_return` to unwind the function-call stack. Cleared
204/// by `runshfunc` on entry, checked by `execlist`'s main loop.
205pub static retflag: std::sync::atomic::AtomicI32 = // c:165 (Src/exec.c)
206    std::sync::atomic::AtomicI32::new(0);
207
208/// Port of `pid_t cmdoutpid;` from `Src/exec.c:215`. Pid of the most
209/// recent `$(cmd)` command-substitution child. Used by exit-status
210/// propagation: `cmdoutval` carries the exit; `cmdoutpid` carries
211/// the pid `waitpid`-d for it.
212pub static cmdoutpid: std::sync::atomic::AtomicI32 = // c:215 (Src/exec.c)
213    std::sync::atomic::AtomicI32::new(0);
214
215/// Port of `mod_export pid_t procsubstpid;` from `Src/exec.c:220`.
216/// Pid of the most recent process-substitution child (`<(cmd)` /
217/// `>(cmd)`). Tracked separately from `cmdoutpid` because procsubst
218/// jobs aren't wait-collected by the parent until the fd is closed.
219pub static procsubstpid: std::sync::atomic::AtomicI32 = // c:220 (Src/exec.c)
220    std::sync::atomic::AtomicI32::new(0);
221
222/// Port of `int cmdoutval;` from `Src/exec.c:225`. Exit status of
223/// the most recent `$(cmd)`. Drives `$?` when a varspc-only command
224/// runs alongside a substitution.
225pub static cmdoutval: std::sync::atomic::AtomicI32 = // c:225 (Src/exec.c)
226    std::sync::atomic::AtomicI32::new(0);
227
228/// Port of `int use_cmdoutval;` from `Src/exec.c:234`. When set,
229/// `lastval` is updated from `cmdoutval` after the command
230/// (i.e. the command had substitutions whose exit status matters).
231pub static use_cmdoutval: std::sync::atomic::AtomicI32 = // c:234 (Src/exec.c)
232    std::sync::atomic::AtomicI32::new(0);
233
234/// Port of `mod_export int sfcontext;` from `Src/exec.c:239`. Source
235/// context — one of `SFC_NONE`, `SFC_DIRECT` (user typed it),
236/// `SFC_SIGNAL` (trap firing), `SFC_HOOK` (precmd/preexec etc.),
237/// `SFC_WIDGET` (ZLE widget), `SFC_COMPLETE` (completion fn),
238/// `SFC_CFUNC` (compsys fn), `SFC_SUBST` ($(...) cmd-subst),
239/// `SFC_EVAL` (eval body). Read by `zerr()` / `funcstack` building.
240pub static sfcontext: std::sync::atomic::AtomicI32 = // c:239 (Src/exec.c)
241    std::sync::atomic::AtomicI32::new(0);
242
243/// Port of `int list_pipe = 0;` from `Src/exec.c:457`. Set when the
244/// currently-executing pipeline is the long-running pipe-into-loop
245/// shape (`cat foo | while read a; do ... done`) — drives the
246/// super/sub-job tracking documented in the famous `Allen Edeln…`
247/// comment block above this declaration in C.
248pub static list_pipe: std::sync::atomic::AtomicI32 = // c:457 (Src/exec.c)
249    std::sync::atomic::AtomicI32::new(0);
250
251/// Port of `int simple_pline = 0;` from `Src/exec.c:457`. Set during
252/// dispatch of a "simple" pipeline (single-stage / no shell-construct
253/// tail) so the `list_pipe` machinery short-circuits.
254pub static simple_pline: std::sync::atomic::AtomicI32 = // c:457 (Src/exec.c)
255    std::sync::atomic::AtomicI32::new(0);
256
257/// Port of `static pid_t list_pipe_pid;` from `Src/exec.c:459`.
258/// PID of the sub-shell created to host the loop-after-pipe pattern;
259/// passed up the recursive `execlist` stack so the cat-job's super-
260/// job entry can record it.
261pub static list_pipe_pid: std::sync::atomic::AtomicI32 = // c:459 (Src/exec.c)
262    std::sync::atomic::AtomicI32::new(0);
263
264/// Port of `static int nowait;` from `Src/exec.c:461`. When set,
265/// `execpline` doesn't wait for the pipeline; used during the
266/// list_pipe sub-shell fork bookkeeping.
267pub static nowait: std::sync::atomic::AtomicI32 = // c:461 (Src/exec.c)
268    std::sync::atomic::AtomicI32::new(0);
269
270/// Port of `int pline_level = 0;` from `Src/exec.c:461`. Recursive
271/// pipeline depth (counts nested pipelines within the current
272/// `execlist` call chain).
273pub static pline_level: std::sync::atomic::AtomicI32 = // c:461 (Src/exec.c)
274    std::sync::atomic::AtomicI32::new(0);
275
276/// Port of `static int list_pipe_child = 0;` from `Src/exec.c:462`.
277/// Set in the child after the list_pipe fork so the child knows to
278/// continue executing the loop body (vs the parent which records
279/// the pid + returns).
280pub static list_pipe_child: std::sync::atomic::AtomicI32 = // c:462 (Src/exec.c)
281    std::sync::atomic::AtomicI32::new(0);
282
283/// Port of `static int list_pipe_job;` from `Src/exec.c:462`. Job
284/// table index of the pipeline's first-stage job (the `cat` in
285/// `cat foo | while ...`).
286pub static list_pipe_job: std::sync::atomic::AtomicI32 = // c:462 (Src/exec.c)
287    std::sync::atomic::AtomicI32::new(0);
288
289/// Port of `static int doneps4;` from `Src/exec.c:262`. Set after
290/// `printprompt4` has emitted the `$PS4` prefix for the current
291/// xtrace command — prevents double-printing when an inner sub-eval
292/// also wants to xtrace.
293pub static doneps4: std::sync::atomic::AtomicI32 = // c:262 (Src/exec.c)
294    std::sync::atomic::AtomicI32::new(0);
295
296/// Port of `static int esprefork, esglob = 1;` from `Src/exec.c:2680`.
297///
298/// File-static "execsubst parameters" — callers (execcmd_exec at
299/// c:3298 / c:3700) set these BEFORE invoking execsubst, which then
300/// uses them as the `flags` arg to prefork() and the gate on
301/// globlist(). `esprefork` is `PREFORK_TYPESET` for magic-assign /
302/// MAGICEQUALSUBST words, else 0. `esglob` defaults to 1; cleared
303/// when the dispatched builtin has `BINF_NOGLOB`.
304pub static esprefork: std::sync::atomic::AtomicI32 = // c:2680
305    std::sync::atomic::AtomicI32::new(0);
306pub static esglob: std::sync::atomic::AtomicI32 = // c:2680 (= 1)
307    std::sync::atomic::AtomicI32::new(1);
308
309/// Port of `struct execstack *exstack;` from `Src/exec.c:244`. Head
310/// of the linked exec-context save stack — `execsave` pushes a frame
311/// before signal-handler / trap dispatch; `execrestore` pops it
312/// afterwards so the interrupted command resumes with its state intact.
313pub static exstack: std::sync::Mutex<Option<Box<execstack>>> = // c:244
314    std::sync::Mutex::new(None);
315
316/// Port of `static char *STTYval;` from `Src/exec.c:263`. Pending
317/// `stty` argument string captured by `addvars` when the command's
318/// inline env contains `STTY=...`. Applied by `execute` before fork
319/// + exec so the spawned program sees its tty configured. Reset to
320/// `None` after consumption to avoid infinite recursion.
321pub static STTYval: std::sync::Mutex<Option<String>> = // c:263 (Src/exec.c)
322    std::sync::Mutex::new(None);
323
324/// Convert a here-document into a here-string. Line-by-line port of
325/// `gethere()` from `Src/exec.c:4569-4652`. Reads the body from the
326/// input stream via `hgetc()` until the terminator line is matched,
327/// returning the collected body as a string. `strp` is in/out: on
328/// entry the raw terminator (possibly with token markers + leading
329/// tabs); on return the munged terminator (after `quotesubst` +
330/// `untokenize` and, for `REDIR_HEREDOCDASH`, leading-tab strip).
331///
332/// Returns `None` on out-of-memory (C `zalloc`/`realloc` failure).
333/// Rust's `String` auto-grows so the OOM branch is effectively
334/// unreachable, but the return type stays `Option<String>` to mirror
335/// the C signature which can return NULL.
336///
337/// Port of `gethere(char **strp, int typ)` from `Src/exec.c:4573`.
338pub fn gethere(strp: &mut String, typ: i32) -> Option<String> {
339    // c:4573 (Src/exec.c)
340    let mut buf: String; // c:4575 char *buf
341    let mut bsiz: usize; // c:4576 int bsiz
342    let mut qt: i32 = 0; // c:4576 int qt = 0
343    let mut strip: i32 = 0; // c:4576 int strip = 0
344                            // c:4577 — char *s, *t, *bptr, c. zshrs uses byte-offsets into
345                            // `buf` for `t` and tracks `bptr` implicitly as `buf.len()` (the
346                            // C `bptr++` increment is `buf.push(c)`; `bptr--` is `buf.pop()`).
347                            // `s` (the loop iterator for the inull-scan) stays local to its
348                            // for-loop. `c` mirrors the C `char c`.
349    let mut t: usize; // c:4577 char *t
350    let mut c: Option<char>; // c:4577 char c
351    let mut str: String = strp.clone(); // c:4578 char *str = *strp
352
353    // c:4580-4584 — for (s = str; *s; s++) if (inull(*s)) { qt = 1; break; }
354    for s in str.bytes() {
355        if inull(s) {
356            // c:4581
357            qt = 1; // c:4582
358            break; // c:4583
359        }
360    }
361    str = quotesubst(&str); // c:4585
362    str = untokenize(&str); // c:4586
363    if typ == REDIR_HEREDOCDASH {
364        // c:4587
365        strip = 1; // c:4588
366                   // c:4589-4590 — while (*str == '\t') str++;
367        while str.starts_with('\t') {
368            str.remove(0);
369        }
370    }
371    *strp = str.clone(); // c:4592 *strp = str
372
373    // c:4593 — bptr = buf = zalloc(bsiz = 256);
374    bsiz = 256;
375    buf = String::with_capacity(bsiz);
376    let _ = bsiz; // bsiz is tracked by C for zfree; Rust drops automatically
377
378    // c:4594 — for (;;)
379    loop {
380        t = buf.len(); // c:4595 t = bptr
381
382        // c:4597-4598 — while ((c = hgetc()) == '\t' && strip) ;
383        loop {
384            c = hgetc();
385            if !(c == Some('\t') && strip != 0) {
386                break;
387            }
388        }
389
390        // c:4599 — for (;;) — inner body-read loop
391        loop {
392            // c:4600-4613 — buffer-growth realloc dance. Rust's
393            // String auto-grows; nothing to do.
394            // c:4614 — if (lexstop || c == '\n') break;
395            if LEX_LEXSTOP.with(|f| f.get()) || c == Some('\n') || c.is_none() {
396                break;
397            }
398            // c:4616 — if (!qt && c == '\\')
399            if qt == 0 && c == Some('\\') {
400                buf.push('\\'); // c:4617 *bptr++ = c
401                c = hgetc(); // c:4618
402                if c == Some('\n') {
403                    // c:4619
404                    buf.pop(); // c:4620 bptr--
405                    c = hgetc(); // c:4621
406                    continue; // c:4622
407                }
408            }
409            if let Some(ch) = c {
410                // c:4625 *bptr++ = c
411                buf.push(ch);
412            }
413            c = hgetc(); // c:4626
414        }
415        // c:4628 — *bptr = '\0'; (implicit — Rust String tracks len)
416
417        // c:4629-4630 — if (!strcmp(t, str)) break;
418        if &buf[t..] == str.as_str() {
419            break;
420        }
421        // c:4631-4634 — if (lexstop) { t = bptr; break; }
422        if LEX_LEXSTOP.with(|f| f.get()) {
423            t = buf.len();
424            break;
425        }
426        // c:4635 — *bptr++ = '\n';
427        buf.push('\n');
428    }
429    // c:4637 — *t = '\0';
430    buf.truncate(t);
431
432    // c:4638-4640 — s = buf; buf = dupstring(buf); zfree(s, bsiz);
433    // The C dance frees the realloc'd block and re-allocates via the
434    // string-heap allocator. Rust drops the old String when reassigned.
435    buf = dupstring(&buf);
436
437    if qt == 0 {
438        // c:4641
439        // c:4642 — int ef = errflag;
440        let ef = errflag.load(Ordering::Relaxed);
441        // c:4644 — parsestr(&buf);
442        if let Ok(parsed) = parsestr(&buf) {
443            buf = parsed;
444        }
445        // c:4646-4649 — if (!(errflag & ERRFLAG_ERROR)) errflag = ef | (errflag & ERRFLAG_INT);
446        if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) == 0 {
447            let cur = errflag.load(Ordering::Relaxed);
448            errflag.store(ef | (cur & ERRFLAG_INT), Ordering::Relaxed);
449        }
450    }
451    Some(buf) // c:4651 return buf
452}
453
454/// Port of `LinkList getoutput(char *cmd, int qt)` from
455/// `Src/exec.c:4712-4791`. Runs a command-substitution body in the
456/// active executor, then routes the captured stdout through
457/// `readoutput(pipe, qt, NULL)` semantics at c:4855-4872.
458///
459/// C return shape: `LinkList` of `char*`. Rust port returns
460/// `Vec<String>` (same shape, owned).
461///
462/// `qt` matches C exactly:
463///   - qt=1 (quoted, `"$(...)"`): trim trailing newlines, return
464///     entire output as a single-element vec. C c:4858-4862: if
465///     output empty, returns a single Nularg sentinel so callers
466///     see "empty value" rather than "no value".
467///   - qt=0 (unquoted, `$(...)`): trim trailing newlines, then
468///     `spacesplit(buf, allownull=false)` per c:4865-4871.
469///
470/// Uses `with_executor` (panics on missing VM context), not
471/// `try_with_executor + unwrap_or_default()`. C `getoutput` calls
472/// `execpline` directly — there's no "no shell" code path. The
473/// silent-no-op pattern (return empty string when no executor) would
474/// mask catastrophic state corruption as "command produced no output",
475/// which is the failure mode the `subst.rs:496` warning block flags.
476/* $(...) */
477// c:4709
478/// `getoutput` — see implementation.
479pub fn getoutput(cmd: &str, qt: i32) -> Vec<String> {
480    // c:4713
481    // c:4715 — `Eprog prog;`
482    let prog: Option<eprog>;
483    // c:4716 — `int pipes[2];`  (collapsed: in-process executor; no fork)
484    // c:4717 — `pid_t pid;`     (collapsed)
485    let mut s: String; // c:4718
486                       // c:4720-4723 — `int onc = nocomments; nocomments = (interact &&
487                       //                !sourcelevel && unset(INTERACTIVECOMMENTS));
488                       //                prog = parse_string(cmd, 0); nocomments = onc;`
489    let onc = crate::ported::lex::LEX_NOCOMMENTS.with(|c| c.get());
490    let new_nc = crate::ported::zsh_h::interact()
491        && crate::ported::init::sourcelevel.load(Ordering::Relaxed) == 0
492        && !isset(crate::ported::zsh_h::INTERACTIVECOMMENTS);
493    crate::ported::lex::LEX_NOCOMMENTS.with(|c| c.set(new_nc));
494    prog = parse_string(cmd, 0);
495    crate::ported::lex::LEX_NOCOMMENTS.with(|c| c.set(onc));
496
497    if prog.is_none() {
498        // c:4725
499        return Vec::new(); // c:4726 return NULL
500    }
501    let prog = prog.unwrap();
502
503    if !isset(crate::ported::zsh_h::EXECOPT) {
504        // c:4728
505        return Vec::new(); // c:4729 newlinklist()
506    }
507
508    // c:4731 — `if ((s = simple_redir_name(prog, REDIR_READ)))` — `$(< word)`
509    if let Some(red_name) = simple_redir_name(&prog, crate::ported::zsh_h::REDIR_READ) {
510        /* $(< word) */
511        // c:4732
512        s = red_name;
513        s = singsub(&s); // c:4737
514        if errflag.load(Ordering::Relaxed) != 0 {
515            return Vec::new(); // c:4739
516        }
517        let s = untokenize(&s); // c:4740
518        let path_meta = unmeta(&s); // c:4741 unmeta(s)
519        let cpath = match std::ffi::CString::new(path_meta.as_bytes()) {
520            Ok(c) => c,
521            Err(_) => return Vec::new(),
522        };
523        let stream = unsafe {
524            libc::open(cpath.as_ptr(), libc::O_RDONLY | libc::O_NOCTTY) // c:4741
525        };
526        if stream == -1 {
527            // c:4742 — `zwarn("%e: %s", errno, s);`
528            let errno = std::io::Error::last_os_error();
529            zerr(&format!("{}: {}", errno, s));
530            LASTVAL.store(1, Ordering::Relaxed);
531            cmdoutval.store(1, Ordering::Relaxed);
532            return Vec::new(); // c:4744
533        }
534        // c:4746 — `retval = readoutput(stream, qt, &readerror);`
535        let mut readerror: i32 = 0;
536        let retval = readoutput(stream, qt, &mut readerror); // c:4746
537        if readerror != 0 {
538            // c:4747
539            zerr(&format!(
540                "error when reading {}: {}", // c:4748
541                s,
542                std::io::Error::from_raw_os_error(readerror)
543            ));
544            LASTVAL.store(1, Ordering::Relaxed);
545            cmdoutval.store(1, Ordering::Relaxed);
546        }
547        return retval; // c:4751
548    }
549
550    // c:4753-4790 — Full fork path: mpipe + zfork + parent
551    // readoutput / waitforpid / child execode + _realexit. fusevm runs
552    // command substitution in-process, so the fork shape collapses to a
553    // synchronous executor call. C control points preserved as cites:
554    //   c:4753 mpipe       — handled by ShellExecutor pipe wiring
555    //   c:4758 child_block — no-op (no fork)
556    //   c:4760 zfork       — replaced by in-process exec
557    //   c:4768-4776 parent — equivalent to executor return
558    //   c:4778-4789 child  — entersubsh+execode+_realexit collapse
559    cmdoutval.store(0, Ordering::Relaxed); // c:4759
560    let buf = crate::ported::exec_hooks::run_command_substitution(cmd);
561    LASTVAL.store(cmdoutval.load(Ordering::Relaxed), Ordering::Relaxed); // c:4775
562
563    // c:4772 retval = readoutput — post-walk (c:4855-4871 tail) inlined.
564    let buf = buf.trim_end_matches('\n');
565    if qt != 0 {
566        if buf.is_empty() {
567            vec![String::from(Nularg)] // c:4859-4861
568        } else {
569            vec![buf.to_string()] // c:4863
570        }
571    } else {
572        crate::ported::utils::spacesplit(buf, false) // c:4865
573    }
574}
575
576/// Direct port of `Shfunc loadautofn(Shfunc shf, int ks, int test_only,
577/// int ignore_loaddir)` from `Src/exec.c:5050`. Walks `$fpath` for a
578/// file named `shf->node.nam`, reads it, installs the text body on
579/// the corresponding `shfunctab` entry, and clears `PM_UNDEFINED`.
580///
581/// C body (abridged):
582///   1. `name = shf->node.nam`
583///   2. `getfpfunc(name, &dir_path, NULL, 0)` → resolved file path
584///   3. If !test_only && file found: parse → store eprog on
585///      `shf->funcdef`; clear PM_UNDEFINED; set `shf->filename`.
586///   4. Returns shf on success, NULL on failure.
587///
588/// Rust port: returns 0 = success, 1 = failure (matches the
589/// existing call-site convention in `bin_functions -c`). Stores
590/// raw file text on `ShFunc.body` (the Rust-side ShFunc in
591/// `hashtable.rs:362`); the parser pass that converts text →
592/// Eprog runs lazily at first call site.
593/// Port of `loadautofn(Shfunc shf, int fksh, int autol, int current_fpath)` from `Src/exec.c:5682`.
594pub fn loadautofn(
595    shf: *mut shfunc, // c:5682 (Src/exec.c)
596    _ks: i32,
597    autol: i32,
598    _ignore_loaddir: i32,
599) -> i32 {
600    if shf.is_null() {
601        return 1;
602    }
603    // c:5054 — `name = shf->node.nam`.
604    let name = unsafe { (*shf).node.nam.clone() };
605    // c:5070 — `path = getfpfunc(name, &dir_path, NULL, 0)`.
606    let mut dir_path: Option<String> = None;
607    let path = match getfpfunc(&name, &mut dir_path, None, 0) {
608        Some(p) => p,
609        None => {
610            // c:Src/exec.c:5713-5719 — file not found path. C:
611            //   `if (prog == &dummy_eprog) {
612            //        locallevel--;
613            //        zwarn("%s: function definition file not found",
614            //              shf->node.nam);
615            //        locallevel++;
616            //        popheap();
617            //        return NULL;
618            //    }`
619            // C's getfpfunc returns &dummy_eprog as the "not found"
620            // sentinel when test_only==0; loadautofn detects it and
621            // emits the diagnostic before returning NULL. Rust's
622            // getfpfunc returns Option::None for the same condition,
623            // so we emit the same diagnostic here. The locallevel
624            // dance is preserved as a comment because the Rust
625            // port's zwarn doesn't reference locallevel in the
626            // format string itself (the dance in C is only to keep
627            // the prefix line counter consistent with the function-
628            // body context). Bug #107 in docs/BUGS.md.
629            crate::ported::utils::zwarn(&format!(
630                "{}: function definition file not found",
631                name
632            ));
633            return 1; // c:5719 NULL
634        }
635    };
636    let _ = autol;
637    // Previously the Rust port treated this parameter as
638    // "test_only" and early-returned when set, so the `+X`
639    // call from `eval_autoload` (`loadautofn(shf, mode, 1, d)`)
640    // never actually loaded the file. C's parameter is `autol`
641    // (autoload mode), NOT a test-only flag — the C body
642    // unconditionally loads/parses regardless of autol. autol=1
643    // controls the EF_RUN / map-flag dance for the wordcode prog
644    // (c:5725-5749), but the loaded-body / PM_UNDEFINED-clear
645    // path runs in all cases. Removing the early-return so
646    // `autoload -U +X funcname` actually loads the body and
647    // `type funcname` reports `function from /path/file` instead
648    // of `autoload shell function`. Bug #160 in docs/BUGS.md.
649    // c:5100-5140 — read the file. C uses zopen + read + parse_string +
650    // execsave; Rust port stores raw text on the ShFunc and defers
651    // parse-to-Eprog until the first call.
652    let body = match std::fs::read_to_string(&path) {
653        Ok(t) => t,
654        Err(_) => return 1,
655    };
656    // c:5142 — `shf->filename = ztrdup(dir_path)`.
657    unsafe {
658        (*shf).filename = dir_path.clone().or(Some(path.clone()));
659    }
660    // c:5148 — `shf->node.flags &= ~PM_UNDEFINED`.
661    unsafe {
662        (*shf).node.flags &= !(PM_UNDEFINED as i32);
663    }
664    // Sync the body string into the Rust-side ShFunc table so the
665    // lazy-parse path can find it later.
666    if let Ok(mut tab) = shfunctab_lock().write() {
667        if let Some(existing) = tab.get_mut(&name) {
668            existing.body = Some(body);
669            existing.filename = dir_path;
670        } else {
671            tab.add(shfunc {
672                node: hashnode {
673                    next: None,
674                    nam: name.clone(),
675                    flags: 0,
676                },
677                filename: dir_path,
678                lineno: 0,
679                funcdef: None,
680                redir: None,
681                sticky: None,
682                body: Some(body),
683            });
684        }
685    }
686    0
687}
688
689/// Port of `getfpfunc(char *s, int *ksh, char **fdir, char **alt_path, int test_only)` from Src/exec.c:5260. Walks `$fpath` (or the
690/// supplied `spec_path` slice) for a file named `name` and writes the
691/// resolved directory through `*dir_path_out` (matching the C `char **dir_path`).
692/// Returns `Some(file_contents_path)` on success, `None` when not found.
693pub fn getfpfunc(
694    name: &str,
695    dir_path_out: &mut Option<String>, // c:5260 (Src/exec.c)
696    spec_path: Option<&[String]>,
697    _all_loaded: i32,
698) -> Option<String> {
699    // C reads $fpath via `getaparam("fpath")` (the param-table array form
700    // tied to scalar `FPATH` via `typeset -T`). Reading `std::env::var`
701    // misses any in-script modification like `fpath=(/some/dir $fpath)`
702    // because that mutates the internal param table, not the inherited
703    // process env. Fall back to env only when the param table is empty
704    // (cold start before any param-table init).
705    let dirs: Vec<String> = match spec_path {
706        Some(s) => s.to_vec(),
707        None => crate::ported::params::getaparam("fpath")
708            .filter(|v| !v.is_empty())
709            .or_else(|| getsparam("FPATH").map(|v| v.split(':').map(String::from).collect()))
710            .or_else(|| {
711                std::env::var("FPATH")
712                    .ok()
713                    .map(|v| v.split(':').map(String::from).collect())
714            })
715            .unwrap_or_default(),
716    };
717    for dir in &dirs {
718        if dir.is_empty() {
719            continue;
720        }
721        let path = format!("{}/{}", dir, name);
722        if std::path::Path::new(&path).exists() {
723            *dir_path_out = Some(dir.clone());
724            return Some(path);
725        }
726    }
727    None
728}
729
730/// Port of `resolvebuiltin(const char *cmdarg, HashNode hn)` from
731/// `Src/exec.c:2703`. Ensures that an autoload-stub builtin has its
732/// module loaded before the caller invokes its `handlerfunc`. If the
733/// stub has no handler, `ensurefeature` is asked to load the module
734/// and re-lookup the builtin node. C body (abridged):
735/// ```c
736/// if (!((Builtin) hn)->handlerfunc) {
737///     char *modname = dupstring(((Builtin) hn)->optstr);
738///     (void)ensurefeature(modname, "b:", ...);
739///     hn = builtintab->getnode(builtintab, cmdarg);
740///     if (!hn) { lastval=1; zerr(...); return NULL; }
741/// }
742/// return hn;
743/// ```
744///
745/// WARNING: zshrs's builtin table is the static `BUILTINS` array in
746/// `src/ported/builtin.rs`. Module autoload routes through
747/// `module::ensurefeature(MODULESTAB, modname, "b:", Some(cmdarg))`;
748/// after the module loads the handler should be wired into BUILTINS.
749pub fn resolvebuiltin<'a>(
750    cmdarg: &str, // c:2703 (Src/exec.c)
751    hn: &'a builtin,
752) -> Option<&'a builtin> {
753    // c:2705 — `if (!((Builtin) hn)->handlerfunc)`.
754    if hn.handlerfunc.is_none() {
755        // c:2706 — `modname = dupstring(((Builtin)hn)->optstr)`.
756        let modname = hn.optstr.clone().unwrap_or_default();
757        // c:2712 — `ensurefeature(modname, "b:", cmdarg)`.
758        let _ = {
759            let mut t = crate::ported::module::MODULESTAB.lock().unwrap();
760            crate::ported::module::ensurefeature(&mut t, &modname, "b:", Some(cmdarg))
761        };
762        // c:2715-2716 — re-lookup the now-(hopefully)-resolved builtin.
763        if let Some(re) = BUILTINS.iter().find(|b| b.node.nam == cmdarg) {
764            if re.handlerfunc.is_some() {
765                return Some(re); // c:2723
766            }
767        }
768        // c:2717-2721 — `lastval = 1; zerr(...)` + return NULL.
769        zerr(&format!(
770            "autoloading module {} failed to define builtin: {}",
771            modname, cmdarg
772        ));
773        return None; // c:2720
774    }
775    Some(hn) // c:2723
776}
777
778/// Dispatch decision returned by `execcmd_compile_head` — the
779/// fusevm-bytecode-time head resolver that mirrors the local-variable
780/// state the C `execcmd_exec` function carries through `c:2913-2916`
781/// (`is_builtin`, `is_shfunc`, `cflags`, `use_defpath`) plus the
782/// precmd-modifier strip count. The fusevm bytecode compiler reads
783/// this to emit the correct dispatch opcode in
784/// `src/extensions/compile_zsh.rs::compile_simple`.
785///
786/// Not a C struct — invented to bridge the divergence between the
787/// C wordcode-walker (which mutates locals + falls through to
788/// invocation) and zshrs's split parse → compile → VM pipeline.
789#[allow(non_camel_case_types)]
790#[derive(Debug, Default, Clone)]
791pub struct execcmd_dispatch {
792    /// Number of `BINF_PREFIX` words to strip from the head of args.
793    /// `Src/exec.c:3086 uremnode(preargs, firstnode(preargs))`.
794    pub precmd_skip: usize,
795    /// Set when the head (after strip) is a real builtin
796    /// (`Src/exec.c:3065 is_builtin = 1`).
797    pub is_builtin: bool,
798    /// Set when the head (after strip) is a shell function
799    /// (`Src/exec.c:3053 is_shfunc = 1`).
800    pub is_shfunc: bool,
801    /// `cflags` accumulator from `Src/exec.c:2915` — gathers
802    /// `BINF_BUILTIN | BINF_COMMAND | BINF_EXEC | BINF_DASH |
803    /// BINF_NOGLOB` bits encountered during the precommand-modifier
804    /// walk (c:3062 `cflags |= hn->flags`).
805    pub cflags: u32,
806    /// `command -p` requested: use the default `$PATH` for lookup
807    /// (`Src/exec.c:3160 use_defpath = 1`). NOT YET HONORED by the
808    /// fusevm compiler — flagged for follow-up.
809    pub use_defpath: bool,
810    /// `command -v` / `command -V` requested: the dispatch target
811    /// flips to `bin_whence` per `Src/exec.c:3149-3157`
812    /// (`hn = &commandbn.node; is_builtin = 1`). The fusevm compiler
813    /// reads this and emits `Op::CallBuiltin(BUILTIN_WHENCE_FROM_COMMAND)`
814    /// instead of resolving the post-strip head.
815    pub has_command_vv: bool,
816    /// `exec -a NAME` requested: ARGV0 override per `Src/exec.c:3214-3240`.
817    /// `Some(NAME)` triggers `zputenv("ARGV0=NAME")` before exec.
818    pub exec_argv0: Option<String>,
819    /// Empty-command branch fired with no redirs (`Src/exec.c:3372-3406`
820    /// — the `else` arm of `if (redir && nonempty(redir))`). Covers
821    /// bare `exec` / `noglob` / `command`. Caller emits
822    /// `lastval = cmdoutval` (0 when no `$(cmd)` ran) and returns.
823    /// Also fires for the `(cflags & BINF_PREFIX) && (cflags &
824    /// BINF_COMMAND)` sub-case at `c:3365-3371` (bare `command`
825    /// returns 0 without complaining about missing redirs).
826    pub is_empty_command: bool,
827}
828
829/// !!! NOT A PORT OF C `execcmd_exec` !!!
830///
831/// This is a fusevm-bytecode-time head resolver invoked by
832/// `src/extensions/compile_zsh.rs::compile_simple` and the
833/// `command` builtin shim in `src/fusevm_bridge.rs`. The canonical
834/// 7-arg port of `Src/exec.c:execcmd_exec` lives elsewhere in this
835/// file under the C-faithful name `execcmd_exec`.
836///
837/// This helper mirrors the head section (`c:2904-3275`) of the C
838/// function — local initialisation, the precommand-modifier walk
839/// that strips `BINF_PREFIX` builtins (`-`, `builtin`, `command`,
840/// `exec`, `noglob`), and the `BINF_COMMAND`/`BINF_EXEC`
841/// sub-option parsers — and returns the resulting dispatch
842/// decision via `execcmd_dispatch`. The fusevm compiler reads
843/// that struct to decide which `Op::CallBuiltin` /
844/// `Op::CallFunction` / `Op::Exec` to emit, and to compute the
845/// correct post-strip `argc`.
846///
847/// =================== WARNING — DIVERGENCE ====================
848///
849/// The C function runs ~1500 lines and PERFORMS dispatch: it sets up
850/// `multio` redirections, evaluates `varspc` assignments, then calls
851/// `execbuiltin` / `runshfunc` / `execute` directly. This helper
852/// stops after the precmd-modifier walk and only returns the head
853/// decision; runtime dispatch is driven by the bytecode the fusevm
854/// compiler emits.
855///
856/// Signature adaptation: the C `Estate`/`Execcmd_params` carry the
857/// wordcode iterator state — zshrs doesn't traverse wordcode here,
858/// so the args list arrives already-expanded as a `&[String]`
859/// (analog of `preargs` after `execcmd_getargs` at `c:3028`).
860/// `type_` mirrors `eparams->type` (`WC_SIMPLE` vs `WC_TYPESET`).
861///
862/// =============================================================
863pub fn execcmd_compile_head(args: &[String], type_: u32) -> execcmd_dispatch {
864    // c:2900 (Src/exec.c)
865
866    // c:2904-2916 — locals.
867    let mut hn: Option<&'static builtin> = None; // c:2904
868    let mut is_shfunc = false; // c:2913
869    let mut is_builtin = false; // c:2913
870    let mut use_defpath = false; // c:2913
871    let mut cflags: u32 = 0; // c:2915
872    let mut orig_cflags: u32 = 0; // c:2915
873    let _ = orig_cflags;
874    // c:3263 — `char *exec_argv0 = NULL;` (declared inside the
875    // BINF_EXEC arm; hoisted here so the dispatch struct can carry it
876    // out after the loop terminates).
877    let mut exec_argv0: Option<String> = None;
878    // c:3149/3158 — `has_vV`/`has_p` flags from the BINF_COMMAND arm
879    // (c:3104). Surface `has_vV` via the dispatch struct so the fusevm
880    // compiler can emit `bin_whence` instead of resolving the head.
881    let mut has_command_vv = false;
882
883    // c:2962-2973 — `%job` head: rewrite `%name` → `fg|bg|disown %name`.
884    // Not in scope for the compile-time dispatch walk: jobspec
885    // expansion happens at runtime in fusevm; the bytecode emits a
886    // direct `fg`/`bg` call when it sees a leading `%`. Flagged for
887    // follow-up when the canonical port lands.
888
889    // c:2975-2986 — AUTORESUME prefix-match against jobtab. Same
890    // status as the %job head: runtime concern, deferred.
891
892    // c:3013-3091 — precommand-modifier walk.
893    let mut preargs: Vec<String> = args.to_vec(); // c:3027 newlinklist
894    let mut precmd_skip: usize = 0;
895
896    // c:3018 — `if ((type == WC_SIMPLE || type == WC_TYPESET) && args)`.
897    if (type_ == WC_SIMPLE || type_ == WC_TYPESET) && !preargs.is_empty() {
898        // c:3018
899        // c:3029 — `while (nonempty(preargs))`.
900        while precmd_skip < preargs.len() {
901            // c:3029
902            // c:3030 — `cmdarg = (char *) peekfirst(preargs);`.
903            let cmdarg = untokenize(&preargs[precmd_skip]);
904            // c:3031 — `checked = !has_token(cmdarg)`. zshrs's fusevm
905            // already performed prefork expansion on `preargs`, so
906            // `has_token` is effectively false here; the C `break` on
907            // unexpanded tokens is unreachable in this entry point.
908
909            // c:3034-3035 — WC_TYPESET fast path: `getnode2` looks up
910            // even disabled builtins so the reserved-word form
911            // (`integer x`, `local foo`) still dispatches to the
912            // typeset family. The static `BUILTINS` array doesn't
913            // expose a separate disabled-bit lookup; one path covers
914            // both. Effect is identical for the precmd-modifier walk.
915
916            // c:3050-3052 — `if (!(cflags & (BINF_BUILTIN |
917            // BINF_COMMAND)) && shfunctab->getnode(...))` — shell
918            // function takes precedence unless a `builtin`/`command`
919            // modifier preceded it.
920            if (cflags & (BINF_BUILTIN | BINF_COMMAND)) == 0 {
921                // c:3051
922                if shfunctab_lock()
923                    .read()
924                    .map(|t| t.iter().any(|(k, _)| k == &cmdarg))
925                    .unwrap_or(false)
926                {
927                    is_shfunc = true; // c:3053
928                    break; // c:3054
929                }
930            }
931            // c:3056 — `builtintab->getnode(builtintab, cmdarg)`.
932            let entry = BUILTINS.iter().find(|b| b.node.nam == cmdarg);
933            let Some(entry) = entry else {
934                // c:3056-3058
935                break;
936            };
937            hn = Some(entry);
938            // c:3061-3063 — accumulate cflags.
939            orig_cflags |= cflags;
940            cflags &= !(BINF_BUILTIN | BINF_COMMAND);
941            cflags |= entry.node.flags as u32;
942            // c:3064 — `if (!(hn->flags & BINF_PREFIX))` — real
943            // builtin, stop.
944            if (entry.node.flags as u32 & BINF_PREFIX) == 0 {
945                // c:3064
946                // WARNING — DIVERGENCE: c:3068 calls `resolvebuiltin`
947                // to autoload the builtin's module if its
948                // `handlerfunc` is NULL. In zshrs, builtins live in
949                // two places: the static `BUILTINS` table (which
950                // mirrors C `handlerfunc`, often `None` for ports
951                // dispatched through fusevm) AND fusevm's
952                // `register_builtins` map (the actual runtime
953                // dispatcher). A null `handlerfunc` in the static
954                // table is NOT an autoload failure for us — it
955                // means dispatch routes through fusevm. So we
956                // skip the resolvebuiltin call here; the faithful
957                // port remains available for future callers that
958                // genuinely need module-autoload semantics.
959                is_builtin = true; // c:3065
960                break; // c:3077
961            }
962            // c:3086 — `uremnode(preargs, firstnode(preargs))`.
963            precmd_skip += 1;
964            // c:3087-3091 — `if (!firstnode(preargs)) { execcmd_getargs
965            //   (...); if (!firstnode(preargs)) break; }`. zshrs has
966            // no `execcmd_getargs` (args arrive pre-expanded); the
967            // bounds-check at the top of `while precmd_skip <
968            // preargs.len()` handles the empty case identically.
969
970            // c:3092-3177 — BINF_COMMAND sub-option parsing
971            // (`command -p / -v / -V`).
972            if (cflags & BINF_COMMAND) != 0 && precmd_skip < preargs.len() {
973                // c:3102-3104 — `LinkNode argnode, oldnode, pnode = NULL;
974                //                int has_p = 0, has_vV = 0, has_other = 0;`
975                let mut argnode: usize = precmd_skip; // c:3105 `argnode = firstnode(preargs);`
976                let mut pnode: Option<usize> = None; // c:3102
977                let mut has_p = false; // c:3104
978                let mut has_vv = false; // c:3104
979                let mut has_other = false; // c:3104
980                                           // c:3107 — `while (IS_DASH(*argdata))`
981                while argnode < preargs.len()
982                    && IS_DASH(preargs[argnode].chars().next().unwrap_or('\0'))
983                {
984                    let argdata = preargs[argnode].clone(); // c:3106
985                    let bytes = argdata.as_bytes();
986                    // c:3108-3111 — stop on bare `-` or `--`.
987                    if bytes.len() < 2 || (IS_DASH(bytes[1] as char) && bytes.len() == 2) {
988                        // c:3109
989                        break; // c:3111
990                    }
991                    // c:3112-3133 — scan flag chars.
992                    for &c in &bytes[1..] {
993                        // c:3112
994                        match c as char {
995                            'p' => {
996                                // c:3114
997                                has_p = true; // c:3122
998                                pnode = Some(argnode); // c:3123
999                            }
1000                            'v' | 'V' => {
1001                                // c:3125-3126
1002                                has_vv = true; // c:3127
1003                            }
1004                            _ => {
1005                                // c:3129
1006                                has_other = true; // c:3130
1007                            }
1008                        }
1009                    }
1010                    // c:3134-3138 — unknown flag → don't try, leave alone.
1011                    if has_other {
1012                        // c:3134
1013                        has_p = false; // c:3136
1014                        has_vv = false; // c:3136
1015                        break; // c:3137
1016                    }
1017                    // c:3140-3147 — advance to next arg.
1018                    argnode += 1; // c:3141 nextnode(argnode)
1019                    if argnode >= preargs.len() {
1020                        // c:3142 — execcmd_getargs (skipped: pre-expanded)
1021                        break; // c:3145
1022                    }
1023                }
1024                // c:3149-3157 — `-v`/`-V` → dispatch to whence.
1025                if has_vv {
1026                    // c:3149
1027                    // c:3154 `pushnode(preargs, "command")` — C re-inserts
1028                    // "command" so bin_whence sees it as argv[0]. zshrs
1029                    // surfaces this via `has_command_vv`; the fusevm
1030                    // compiler emits the equivalent whence call.
1031                    has_command_vv = true; // c:3155-3156 hn = &commandbn; is_builtin=1
1032                    is_builtin = true;
1033                    break; // c:3157
1034                } else if has_p {
1035                    // c:3158
1036                    use_defpath = true; // c:3160
1037                    if let Some(pn) = pnode {
1038                        // c:3165 — `uremnode(preargs, pnode)`. zshrs:
1039                        // remove the `-p`-bearing arg from preargs.
1040                        if pn < preargs.len() {
1041                            preargs.remove(pn);
1042                            // precmd_skip already accounts for the
1043                            // stripped `command` prefix; we just removed
1044                            // the `-p` flag which sat at preargs[pn].
1045                            // No precmd_skip change needed — the head
1046                            // remains where it was.
1047                        }
1048                    }
1049                }
1050                // c:3176-3177 — `--` trailing end-of-options strip.
1051                if argnode < preargs.len() {
1052                    let argdata = &preargs[argnode];
1053                    let b = argdata.as_bytes();
1054                    if b.len() == 2 && IS_DASH(b[0] as char) && IS_DASH(b[1] as char) {
1055                        // c:3176
1056                        preargs.remove(argnode); // c:3177
1057                    }
1058                }
1059            } else if (cflags & BINF_EXEC) != 0 && precmd_skip < preargs.len() {
1060                // c:3178-3275 — BINF_EXEC sub-option parsing
1061                // (`exec -a NAME -l -c`).
1062                let mut argnode: usize = precmd_skip; // c:3185
1063                let mut error_done = false;
1064                // c:3196 — `while (argdata && IS_DASH(*argdata) &&
1065                //                  strlen(argdata) >= 2)`
1066                while argnode < preargs.len() {
1067                    let argdata = preargs[argnode].clone();
1068                    let bytes = argdata.as_bytes();
1069                    if bytes.is_empty() || !IS_DASH(bytes[0] as char) || bytes.len() < 2 {
1070                        break; // c:3196 loop guard
1071                    }
1072                    let oldnode = argnode; // c:3197
1073                    argnode += 1; // c:3198 nextnode(oldnode)
1074                                  // c:3203-3208 — empty next → error.
1075                    if argnode >= preargs.len() {
1076                        // c:3203
1077                        zerr(
1078                            // c:3204
1079                            "exec requires a command to execute",
1080                        );
1081                        errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed); // c:3206
1082                        error_done = true;
1083                        break; // c:3207 goto done
1084                    }
1085                    // c:3209 — `uremnode(preargs, oldnode)`.
1086                    preargs.remove(oldnode);
1087                    argnode -= 1; // re-anchor — `argnode` was the post-removed slot
1088                                  // c:3210-3211 — `--` stops option scan.
1089                    if bytes.len() == 2 && IS_DASH(bytes[0] as char) && IS_DASH(bytes[1] as char) {
1090                        // c:3210
1091                        break; // c:3211
1092                    }
1093                    // c:3212-3258 — scan flag chars after the leading `-`.
1094                    let mut k = 1usize;
1095                    while k < bytes.len() && !error_done {
1096                        let cmdopt = bytes[k] as char; // c:3212
1097                        match cmdopt {
1098                            'a' => {
1099                                // c:3214 — `-a` ARGV0 override.
1100                                if k + 1 < bytes.len() {
1101                                    // c:3216 — `-aNAME` inline form.
1102                                    exec_argv0 =
1103                                        Some(String::from_utf8_lossy(&bytes[k + 1..]).into_owned()); // c:3217
1104                                    k = bytes.len(); // c:3219 position past end
1105                                } else {
1106                                    // c:3220 — `-a NAME` separate form.
1107                                    if argnode >= preargs.len() {
1108                                        // c:3230
1109                                        zerr(
1110                                            // c:3231
1111                                            "exec flag -a requires a parameter",
1112                                        );
1113                                        errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed); // c:3233
1114                                        error_done = true;
1115                                        break; // c:3234 goto done
1116                                    }
1117                                    exec_argv0 = Some(preargs[argnode].clone()); // c:3236
1118                                    preargs.remove(argnode); // c:3239
1119                                }
1120                            }
1121                            'c' => {
1122                                // c:3242
1123                                cflags |= BINF_CLEARENV; // c:3243
1124                            }
1125                            'l' => {
1126                                // c:3245
1127                                cflags |= BINF_DASH; // c:3246
1128                            }
1129                            _ => {
1130                                // c:3248
1131                                zerr(
1132                                    // c:3249
1133                                    &format!("unknown exec flag -{}", cmdopt),
1134                                );
1135                                errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed); // c:3251
1136                                error_done = true;
1137                                break; // c:3256
1138                            }
1139                        }
1140                        k += 1;
1141                    }
1142                    if error_done {
1143                        break;
1144                    }
1145                }
1146                // c:3263-3274 — zputenv("ARGV0=NAME"). zshrs defers
1147                // the actual `setenv` to the fusevm compiler / external
1148                // exec path; we surface `exec_argv0` via the dispatch
1149                // struct so the caller can apply it before fork+exec.
1150                if let Some(ref a0) = exec_argv0 {
1151                    // c:3263 — `remnulargs + untokenize` then setenv.
1152                    let cleaned = untokenize(a0); // c:3266-3267
1153                    exec_argv0 = Some(cleaned);
1154                }
1155                if error_done {
1156                    return execcmd_dispatch {
1157                        precmd_skip,
1158                        is_builtin,
1159                        is_shfunc,
1160                        cflags,
1161                        use_defpath,
1162                        has_command_vv,
1163                        exec_argv0,
1164                        is_empty_command: false,
1165                    };
1166                }
1167            }
1168            // c:3275-3278 — `hn = NULL; if ((cflags & BINF_COMMAND) &&
1169            // unset(POSIXBUILTINS)) break;`. After processing a
1170            // `command` precmd modifier (and its -p/-v/-V flags), the
1171            // C loop exits with hn cleared so the dispatch falls
1172            // through to external lookup. Without this, the next
1173            // iteration would find `command print` → print's builtin
1174            // and dispatch to it; zsh's intentional behaviour is to
1175            // skip builtins under `command` (unless POSIXBUILTINS is
1176            // set, where the loop continues normally).
1177            if (cflags & BINF_COMMAND) != 0 && !isset(POSIXBUILTINS) {
1178                hn = None; // c:3275 hn = NULL
1179                break; // c:3277
1180            }
1181        }
1182    }
1183
1184    // c:3309-3406 — "Empty command" branch. When the precmd-modifier
1185    // walk above strips every word with nothing left to dispatch
1186    // (bare `exec`, bare `noglob`, bare `command`, bare `nocorrect`),
1187    // C falls into `if (!args || empty(args))` at c:3331. Sub-cases:
1188    //
1189    // - redir-present + do_exec       → nullexec=1 (continue to run)
1190    // - redir-present + varspc        → nullexec=2 (continue)
1191    // - redir-present + no nullcmd    → `zerr("redirection with no command")`
1192    //                                   lastval=1, return
1193    // - redir-present + SHNULLCMD     → args=[":"]
1194    // - redir-present + readnullcmd   → args=[readnullcmd]
1195    // - redir-present + default       → args=[nullcmd]
1196    // - NO redir + BINF_PREFIX+COMMAND → lastval=0, return (c:3365-3371)
1197    // - NO redir + default            → lastval=cmdoutval, return (c:3372-3406)
1198    //
1199    // zshrs's `execcmd_compile_head` doesn't receive `redir` (it
1200    // takes `args` only). The cases that DEPEND on redirs are handled by
1201    // `compile_zsh.rs::compile_redir` before this dispatch fires; the
1202    // remaining cases collapse into the single `is_empty_command`
1203    // flag below. Both NO-redir sub-cases produce the same observable
1204    // outcome (lastval=0, return without invoking anything), so a
1205    // single flag suffices.
1206    let is_empty_command = precmd_skip >= preargs.len();
1207
1208    // =================== WARNING — DIVERGENCE ====================
1209    // c:3285+: prefork-substitution, magic_assign decision, multio
1210    // setup, varspc evaluation, and the actual execbuiltin /
1211    // runshfunc / execute call. ~1300 lines of interpreter-only
1212    // code, entirely replaced by fusevm bytecode dispatch in
1213    // `src/extensions/compile_zsh.rs::compile_simple` and the
1214    // opcode handlers in `src/fusevm_bridge.rs::register_builtins`.
1215    // The return value below feeds those compile-time decisions.
1216    // =============================================================
1217
1218    let _ = hn;
1219    execcmd_dispatch {
1220        precmd_skip,
1221        is_builtin,
1222        is_shfunc,
1223        cflags,
1224        use_defpath,
1225        has_command_vv,
1226        exec_argv0,
1227        is_empty_command,
1228    }
1229}
1230
1231// =============================================================================
1232// Leaf-function ports — c:283 (parse_string) and below. Added incrementally to
1233// chip at the ~5500 lines of exec.c still un-ported beyond the wordcode
1234// walker (execlist / execpline / execcmd which the fusevm bytecode VM
1235// replaces — see the WARNING block in execcmd_exec).
1236// =============================================================================
1237
1238/// Port of `parse_string(char *s, int reset_lineno)` from `Src/exec.c:283`.
1239///
1240/// C body:
1241/// ```c
1242/// Eprog p; zlong oldlineno;
1243/// zcontext_save();
1244/// inpush(s, INP_LINENO, NULL);
1245/// strinbeg(0);
1246/// oldlineno = lineno;
1247/// if (reset_lineno) lineno = 1;
1248/// p = parse_list();
1249/// lineno = oldlineno;
1250/// if (tok == LEXERR && !lastval) lastval = 1;
1251/// strinend();
1252/// inpop();
1253/// zcontext_restore();
1254/// return p;
1255/// ```
1256///
1257/// Parses an arbitrary string as a zsh command list, returning the
1258/// `Eprog` (compiled wordcode). Used by `getoutput` for `$(cmd)`,
1259/// `bin_eval` for `eval`, and the autoload path.
1260pub fn parse_string(s: &str, reset_lineno: i32) -> Option<eprog> {
1261    // c:285-286
1262    let p: Option<eprog>;
1263    let oldlineno: i64;
1264
1265    zcontext_save(); // c:288
1266    inpush(s, INP_LINENO, None); // c:289
1267    strinbeg(0); // c:290
1268    oldlineno = LEX_LINENO.get() as i64; // c:291
1269    if reset_lineno != 0 {
1270        // c:292
1271        LEX_LINENO.set(1); // c:293
1272    }
1273    p = parse_list(); // c:294
1274    LEX_LINENO.set(oldlineno as u64); // c:295
1275                                      // c:296-297 — `if (tok == LEXERR && !lastval) lastval = 1;`
1276    if tok() == LEXERR && LASTVAL.load(Ordering::Relaxed) == 0 {
1277        LASTVAL.store(1, Ordering::Relaxed);
1278    }
1279    strinend(); // c:298
1280    inpop(); // c:299
1281    zcontext_restore(); // c:300
1282    p // c:301
1283}
1284
1285/// Port of `int isgooderr(int e, char *dir)` from `Src/exec.c:652`.
1286///
1287/// C body:
1288/// ```c
1289/// /* Maybe the directory was unreadable, or maybe it wasn't even a directory. */
1290/// return ((e != EACCES || !access(dir, X_OK)) &&
1291///         e != ENOENT && e != ENOTDIR);
1292/// ```
1293///
1294/// errno classifier for `execve` failures during PATH search: if the
1295/// errno is EACCES (and the dir is X-accessible) or ENOENT/ENOTDIR,
1296/// it's "expected" (try next PATH entry); otherwise it's a real
1297/// failure worth surfacing.
1298pub fn isgooderr(e: i32, dir: &str) -> bool {
1299    // c:652
1300    let dir_x_ok = std::path::Path::new(&unmeta(dir))
1301        .metadata()
1302        .map(|m| m.permissions().mode() & 0o111 != 0)
1303        .unwrap_or(false);
1304    // c:658-659 — `(e != EACCES || !access(dir, X_OK)) && e != ENOENT && e != ENOTDIR`
1305    (e != libc::EACCES || !dir_x_ok) && e != libc::ENOENT && e != libc::ENOTDIR
1306}
1307
1308/// Port of `int iscom(char *s)` from `Src/exec.c:962`.
1309///
1310/// C body:
1311/// ```c
1312/// struct stat statbuf;
1313/// char *us = unmeta(s);
1314/// return (access(us, X_OK) == 0 && stat(us, &statbuf) >= 0 &&
1315///         S_ISREG(statbuf.st_mode));
1316/// ```
1317///
1318/// True iff `s` names an executable regular file (X-perm + S_IFREG).
1319/// Used by the PATH-search loop in `findcmd` / `search_defpath` to
1320/// validate candidate paths before exec.
1321pub fn iscom(s: &str) -> bool {
1322    // c:962
1323    let us = unmeta(s); // c:965
1324                        // c:967-968 — `access(us, X_OK) == 0 && stat(us, &statbuf) >= 0 && S_ISREG(...)`
1325    let cstr = match std::ffi::CString::new(us.as_str()) {
1326        Ok(c) => c,
1327        Err(_) => return false,
1328    };
1329    let x_ok = unsafe { libc::access(cstr.as_ptr(), libc::X_OK) } == 0;
1330    if !x_ok {
1331        return false;
1332    }
1333    let meta = match std::fs::metadata(&us) {
1334        Ok(m) => m,
1335        Err(_) => return false,
1336    };
1337    meta.file_type().is_file()
1338}
1339
1340/// Port of `int isreallycom(Cmdnam cn)` from `Src/exec.c:972-987`.
1341///
1342/// Verify that a hashed/cached cmdnamtab entry still names a real
1343/// external command (X-perm + regular file). For HASHED entries
1344/// (`cn->u.cmd` carries the absolute path), test the path directly;
1345/// otherwise concatenate `name[0] + "/" + nam` and test that.
1346/// Used by `execcmd_exec` to drop stale cmdnamtab hits before they
1347/// turn into a failed `execve` syscall.
1348pub fn isreallycom(cn: &cmdnam) -> bool {
1349    // c:972
1350    let fullnam: String;
1351    if (cn.node.flags & crate::ported::zsh_h::HASHED) != 0 {
1352        // c:977-978 — `strcpy(fullnam, cn->u.cmd);`
1353        fullnam = cn.cmd.clone().unwrap_or_default();
1354    } else if cn.name.is_none() || cn.name.as_ref().unwrap().is_empty() {
1355        // c:979-980 — `if (!cn->u.name) return 0;`
1356        return false;
1357    } else {
1358        // c:982-984 — `strcpy + strcat("/") + strcat(nam)`
1359        let path0 = &cn.name.as_ref().unwrap()[0];
1360        fullnam = format!("{}/{}", path0, cn.node.nam);
1361    }
1362    iscom(&fullnam) // c:986
1363}
1364
1365/// Port of `int isrelative(char *s)` from `Src/exec.c:996`.
1366///
1367/// C body:
1368/// ```c
1369/// if (*s != '/') return 1;
1370/// for (; *s; s++)
1371///     if (*s == '.' && s[-1] == '/' &&
1372///         (s[1] == '/' || s[1] == '\0' ||
1373///          (s[1] == '.' && (s[2] == '/' || s[2] == '\0'))))
1374///         return 1;
1375/// return 0;
1376/// ```
1377///
1378/// True iff `s` either doesn't start with `/` OR contains a `./` or
1379/// `../` component anywhere. Used by `cd` resolution and PATH-cache
1380/// invalidation to detect non-canonical paths.
1381pub fn isrelative(s: &str) -> i32 {
1382    // c:996
1383    let bytes = s.as_bytes();
1384    if bytes.is_empty() || bytes[0] != b'/' {
1385        // c:998
1386        return 1; // c:999
1387    }
1388    // c:1000-1004 — walk for `./` or `../` components.
1389    for i in 1..bytes.len() {
1390        let c = bytes[i];
1391        let prev = bytes[i - 1];
1392        if c == b'.' && prev == b'/' {
1393            let next = bytes.get(i + 1).copied().unwrap_or(0);
1394            if next == b'/' || next == 0 {
1395                // c:1002
1396                return 1;
1397            }
1398            if next == b'.' {
1399                let next2 = bytes.get(i + 2).copied().unwrap_or(0);
1400                if next2 == b'/' || next2 == 0 {
1401                    // c:1003
1402                    return 1;
1403                }
1404            }
1405        }
1406    }
1407    0 // c:1005
1408}
1409
1410/// Port of `void setunderscore(char *str)` from `Src/exec.c:2652`.
1411///
1412/// C body:
1413/// ```c
1414/// queue_signals();
1415/// if (str && *str) {
1416///     size_t l = strlen(str) + 1, nl = (l + 31) & ~31;
1417///     if (nl > underscorelen || (underscorelen - nl) > 64) {
1418///         zfree(zunderscore, underscorelen);
1419///         zunderscore = (char *) zalloc(underscorelen = nl);
1420///     }
1421///     strcpy(zunderscore, str);
1422///     underscoreused = l;
1423/// } else {
1424///     ... reset zunderscore = "" ...
1425/// }
1426/// unqueue_signals();
1427/// ```
1428///
1429/// Sets the `$_` global to the last argument of the most recent
1430/// command. Called from `execcmd_exec` (c:3936) per `last_status`
1431/// update; mirrored in zshrs by the fusevm `Op::Exec` handler.
1432pub fn setunderscore(str: &str) {
1433    // c:2652
1434    queue_signals(); // c:2654
1435    if !str.is_empty() {
1436        // c:2655 `if (str && *str)`
1437        // c:2656-2663 — copy str into zunderscore; track byte length in underscoreused.
1438        let mut zu = zunderscore.lock().unwrap();
1439        *zu = str.to_string();
1440        let nl = (str.len() + 1 + 31) & !31; // c:2656
1441        underscorelen.store(nl, Ordering::Relaxed); // c:2660
1442        underscoreused.store((str.len() + 1) as i32, Ordering::Relaxed);
1443    // c:2663
1444    } else {
1445        // c:2664
1446        let mut zu = zunderscore.lock().unwrap();
1447        zu.clear(); // c:2669 `*zunderscore = '\0';`
1448        underscoreused.store(1, Ordering::Relaxed); // c:2670
1449    }
1450    unqueue_signals(); // c:2672
1451}
1452
1453/// Port of `int mpipe(int *pp)` from `Src/exec.c:5160`.
1454///
1455/// C body:
1456/// ```c
1457/// if (pipe(pp) < 0) {
1458///     zerr("pipe failed: %e", errno);
1459///     return -1;
1460/// }
1461/// pp[0] = movefd(pp[0]);
1462/// pp[1] = movefd(pp[1]);
1463/// return 0;
1464/// ```
1465///
1466/// libc `pipe(2)` wrapper that pushes both ends out of the reserved-
1467/// fd range via `movefd`. Used by `getpipe` / `getproc` /
1468/// `spawnpipes` for process substitution and pipeline wiring.
1469pub fn mpipe(pp: &mut [i32; 2]) -> i32 {
1470    // c:5160
1471    let mut fds: [libc::c_int; 2] = [-1; 2];
1472    if unsafe { libc::pipe(fds.as_mut_ptr()) } < 0 {
1473        // c:5162
1474        zerr(&format!(
1475            // c:5163
1476            "pipe failed: {}",
1477            std::io::Error::last_os_error()
1478        ));
1479        return -1; // c:5164
1480    }
1481    pp[0] = movefd(fds[0]); // c:5166
1482    pp[1] = movefd(fds[1]); // c:5167
1483    0 // c:5168
1484}
1485
1486/// Port of `static const char *const ANONYMOUS_FUNCTION_NAME = "(anon)";`
1487/// from `Src/exec.c:5289`. Anonymous-function name marker used by
1488/// `is_anonymous_function_name`, `execfuncdef`, and `doshfunc` for
1489/// `() { ... }` anonymous function dispatch.
1490pub const ANONYMOUS_FUNCTION_NAME: &str = "(anon)";
1491
1492/// Port of `int is_anonymous_function_name(const char *name)` from
1493/// `Src/exec.c:5300`.
1494///
1495/// C body:
1496/// ```c
1497/// return !strcmp(name, ANONYMOUS_FUNCTION_NAME);
1498/// ```
1499///
1500/// True iff the name equals the `"(anon)"` sentinel. Used by zprof
1501/// reporting and `whence -v` to skip / annotate anonymous functions.
1502pub fn is_anonymous_function_name(name: &str) -> i32 {
1503    // c:5300
1504    if name == ANONYMOUS_FUNCTION_NAME {
1505        // c:5302
1506        1
1507    } else {
1508        0
1509    }
1510}
1511
1512/// Port of `void execsave(void)` from `Src/exec.c:6438`.
1513///
1514/// C body:
1515/// ```c
1516/// struct execstack *es = (struct execstack *) zalloc(sizeof(struct execstack));
1517/// es->list_pipe_pid = list_pipe_pid;
1518/// es->nowait = nowait;
1519/// es->pline_level = pline_level;
1520/// es->list_pipe_child = list_pipe_child;
1521/// es->list_pipe_job = list_pipe_job;
1522/// strcpy(es->list_pipe_text, list_pipe_text);
1523/// es->lastval = lastval;
1524/// es->noeval = noeval;
1525/// es->badcshglob = badcshglob;
1526/// es->cmdoutpid = cmdoutpid;
1527/// es->cmdoutval = cmdoutval;
1528/// es->use_cmdoutval = use_cmdoutval;
1529/// es->procsubstpid = procsubstpid;
1530/// es->trap_return = trap_return;
1531/// es->trap_state = trap_state;
1532/// es->trapisfunc = trapisfunc;
1533/// es->traplocallevel = traplocallevel;
1534/// es->noerrs = noerrs;
1535/// es->this_noerrexit = this_noerrexit;
1536/// es->underscore = ztrdup(zunderscore);
1537/// es->next = exstack;
1538/// exstack = es;
1539/// noerrs = cmdoutpid = 0;
1540/// ```
1541///
1542/// Snapshot every transient exec-context global onto the `exstack`
1543/// linked list so a signal-handler / trap-firing nested eval can
1544/// scribble freely; `execrestore` pops the frame back. Called by
1545/// `dotrap` (signals.c) and the trap-firing entry in `execlist`.
1546pub fn execsave() {
1547    // c:6438
1548    // c:6442 — `es = zalloc(sizeof(execstack));`
1549    let mut es = Box::new(execstack {
1550        // c:6442
1551        next: None,
1552        list_pipe_pid: list_pipe_pid.load(Ordering::Relaxed), // c:6443
1553        nowait: nowait.load(Ordering::Relaxed),               // c:6444
1554        pline_level: pline_level.load(Ordering::Relaxed),     // c:6445
1555        list_pipe_child: list_pipe_child.load(Ordering::Relaxed), // c:6446
1556        list_pipe_job: list_pipe_job.load(Ordering::Relaxed), // c:6447
1557        list_pipe_text: {
1558            // c:6448 — `strcpy(es->list_pipe_text, list_pipe_text);`
1559            let mut buf = [0u8; JOBTEXTSIZE];
1560            if let Ok(s) = LIST_PIPE_TEXT.lock() {
1561                let bytes = s.as_bytes();
1562                let n = bytes.len().min(JOBTEXTSIZE - 1);
1563                buf[..n].copy_from_slice(&bytes[..n]);
1564            }
1565            buf
1566        },
1567        lastval: LASTVAL.load(Ordering::Relaxed), // c:6449
1568        // c:6450 — `es->noeval = noeval;`. Snapshot math.c's
1569        // `int noeval` (the parse-only side-effect-skip counter)
1570        // via math.rs's pub accessor.
1571        noeval: crate::ported::math::m_noeval(),
1572        // c:6451 — `es->badcshglob = badcshglob;`. Snapshot the
1573        // csh-glob diagnostic counter (glob.c:103 / glob.rs
1574        // BADCSHGLOB) so nested eval / trap dispatch doesn't disturb
1575        // the outer command's per-line accounting.
1576        badcshglob: crate::ported::glob::BADCSHGLOB.load(Ordering::Relaxed), // c:6451
1577        cmdoutpid: cmdoutpid.load(Ordering::Relaxed),                        // c:6452
1578        cmdoutval: cmdoutval.load(Ordering::Relaxed),                        // c:6453
1579        use_cmdoutval: use_cmdoutval.load(Ordering::Relaxed),                // c:6454
1580        procsubstpid: procsubstpid.load(Ordering::Relaxed),                  // c:6455
1581        trap_return: TRAP_RETURN.load(Ordering::Relaxed),                    // c:6456
1582        trap_state: TRAP_STATE.load(Ordering::Relaxed),                      // c:6457
1583        trapisfunc: trapisfunc.load(Ordering::Relaxed),                      // c:6458
1584        traplocallevel: traplocallevel.load(Ordering::Relaxed),              // c:6459
1585        noerrs: noerrs.load(Ordering::Relaxed),                              // c:6460
1586        this_noerrexit: this_noerrexit.load(Ordering::Relaxed),              // c:6461
1587        // c:6462 — `es->underscore = ztrdup(zunderscore);`
1588        underscore: Some(zunderscore.lock().unwrap().clone()),
1589    });
1590    // c:6463-6464 — `es->next = exstack; exstack = es;`
1591    let mut head = exstack.lock().unwrap();
1592    es.next = head.take();
1593    *head = Some(es);
1594    // c:6465 — `noerrs = cmdoutpid = 0;`
1595    noerrs.store(0, Ordering::Relaxed);
1596    cmdoutpid.store(0, Ordering::Relaxed);
1597}
1598
1599/// Port of `void execrestore(void)` from `Src/exec.c:6470`.
1600///
1601/// C body:
1602/// ```c
1603/// struct execstack *en = exstack;
1604/// DPUTS(!exstack, "BUG: execrestore() without execsave()");
1605/// queue_signals();
1606/// exstack = exstack->next;
1607/// list_pipe_pid = en->list_pipe_pid;
1608/// nowait = en->nowait;
1609/// pline_level = en->pline_level;
1610/// list_pipe_child = en->list_pipe_child;
1611/// list_pipe_job = en->list_pipe_job;
1612/// strcpy(list_pipe_text, en->list_pipe_text);
1613/// lastval = en->lastval;
1614/// noeval = en->noeval;
1615/// badcshglob = en->badcshglob;
1616/// cmdoutpid = en->cmdoutpid;
1617/// cmdoutval = en->cmdoutval;
1618/// use_cmdoutval = en->use_cmdoutval;
1619/// procsubstpid = en->procsubstpid;
1620/// trap_return = en->trap_return;
1621/// trap_state = en->trap_state;
1622/// trapisfunc = en->trapisfunc;
1623/// traplocallevel = en->traplocallevel;
1624/// noerrs = en->noerrs;
1625/// this_noerrexit = en->this_noerrexit;
1626/// setunderscore(en->underscore);
1627/// zsfree(en->underscore);
1628/// free(en);
1629/// unqueue_signals();
1630/// ```
1631///
1632/// Pop the top `execstack` frame and restore every transient
1633/// exec-context global. Inverse of `execsave`.
1634pub fn execrestore() {
1635    // c:6470
1636    let mut head = exstack.lock().unwrap();
1637    let en = match head.take() {
1638        // c:6472 + c:6477
1639        Some(en) => en,
1640        None => {
1641            // c:6474 — DPUTS(!exstack, "BUG: execrestore() without execsave()")
1642            crate::DPUTS!(true, "BUG: execrestore() without execsave()");
1643            return;
1644        }
1645    };
1646    queue_signals(); // c:6476
1647    *head = en.next; // c:6477
1648    drop(head); // release lock before scalar restores
1649
1650    list_pipe_pid.store(en.list_pipe_pid, Ordering::Relaxed); // c:6479
1651    nowait.store(en.nowait, Ordering::Relaxed); // c:6480
1652    pline_level.store(en.pline_level, Ordering::Relaxed); // c:6481
1653    list_pipe_child.store(en.list_pipe_child, Ordering::Relaxed); // c:6482
1654    list_pipe_job.store(en.list_pipe_job, Ordering::Relaxed); // c:6483
1655                                                              // c:6484 — `strcpy(list_pipe_text, en->list_pipe_text);`.
1656    if let Ok(mut s) = LIST_PIPE_TEXT.lock() {
1657        let nul = en
1658            .list_pipe_text
1659            .iter()
1660            .position(|&b| b == 0)
1661            .unwrap_or(JOBTEXTSIZE);
1662        *s = String::from_utf8_lossy(&en.list_pipe_text[..nul]).into_owned();
1663    }
1664    LASTVAL.store(en.lastval, Ordering::Relaxed); // c:6485
1665                                                  // c:6486 — `noeval = en->noeval;`. Restore math.c's noeval
1666                                                  // counter from the saved frame.
1667    crate::ported::math::m_noeval_set(en.noeval);
1668    // c:6487 — `badcshglob = en->badcshglob;`. Restore the csh-glob
1669    // diagnostic counter saved on entry.
1670    crate::ported::glob::BADCSHGLOB.store(en.badcshglob, Ordering::Relaxed);
1671    cmdoutpid.store(en.cmdoutpid, Ordering::Relaxed); // c:6488
1672    cmdoutval.store(en.cmdoutval, Ordering::Relaxed); // c:6489
1673    use_cmdoutval.store(en.use_cmdoutval, Ordering::Relaxed); // c:6490
1674    procsubstpid.store(en.procsubstpid, Ordering::Relaxed); // c:6491
1675    TRAP_RETURN.store(en.trap_return, Ordering::Relaxed); // c:6492
1676    TRAP_STATE.store(en.trap_state, Ordering::Relaxed); // c:6493
1677    trapisfunc.store(en.trapisfunc, Ordering::Relaxed); // c:6494
1678    traplocallevel.store(en.traplocallevel, Ordering::Relaxed); // c:6495
1679    noerrs.store(en.noerrs, Ordering::Relaxed); // c:6496
1680    this_noerrexit.store(en.this_noerrexit, Ordering::Relaxed); // c:6497
1681                                                                // c:6498-6499 — `setunderscore(en->underscore); zsfree(en->underscore);`
1682    if let Some(ref u) = en.underscore {
1683        setunderscore(u); // c:6498
1684    }
1685    // c:6500 — `free(en);` — handled by Box drop when `en` falls out of scope.
1686    unqueue_signals(); // c:6502
1687}
1688
1689/// Port of `void execstring(char *s, int dont_change_job, int exiting,
1690/// char *context)` from `Src/exec.c:1228`.
1691///
1692/// C body:
1693/// ```c
1694/// Eprog prog;
1695/// pushheap();
1696/// if (isset(VERBOSE)) {
1697///     zputs(s, stderr);
1698///     fputc('\n', stderr);
1699///     fflush(stderr);
1700/// }
1701/// if ((prog = parse_string(s, 0)))
1702///     execode(prog, dont_change_job, exiting, context);
1703/// popheap();
1704/// ```
1705///
1706/// Public entry — execute an arbitrary string as a zsh command list.
1707/// Called by `eval`, `.`/`source`, `trap` action firing, autoload
1708/// body executors, command substitution body runners.
1709///
1710/// =================== WARNING — DIVERGENCE ====================
1711/// The C path is `parse_string` → `execode` → `execlist` (wordcode
1712/// walker). zshrs replaces `execode/execlist` with the fusevm
1713/// bytecode VM at `crate::vm_helper::ShellExecutor::execute_script_zsh_pipeline`.
1714/// Faithful port: VERBOSE banner + pushheap/popheap intact; the
1715/// parse+execute chain delegates to the fusevm entry. When `execlist`
1716/// lands as a strict 1:1 port, swap the delegate for the canonical
1717/// chain.
1718/// =============================================================
1719pub fn execstring(s: &str, _dont_change_job: i32, _exiting: i32, _context: &str) {
1720    // c:1228
1721    pushheap(); // c:1232
1722                // c:1233-1237 — VERBOSE banner.
1723    if isset(VERBOSE) {
1724        // c:1233
1725        let mut stderr = std::io::stderr().lock();
1726        use std::io::Write;
1727        let _ = stderr.write_all(s.as_bytes()); // c:1234 zputs(s, stderr)
1728        let _ = stderr.write_all(b"\n"); // c:1235
1729        let _ = stderr.flush(); // c:1236
1730    }
1731    // c:1238-1239 — parse + execode. zshrs delegates the parse+VM
1732    // chain to the fusevm pipeline via the exec_hooks fn-ptr
1733    // installed by fusevm_bridge at startup. Direct
1734    // `with_executor` / ShellExecutor reach-in from src/ported/ is
1735    // forbidden — see memory feedback_no_exec_script_from_ported.
1736    let _ = crate::ported::exec_hooks::execute_script_zsh_pipeline(s);
1737    popheap(); // c:1240
1738}
1739
1740/// Port of `void runshfunc(Eprog prog, FuncWrap wrap, char *name)` from
1741/// `Src/exec.c:6166`. The inner shell-function executor — fires
1742/// module-registered wrapper handlers around the function body, with
1743/// `$_` (zunderscore) save/restore and a paramscope push/pop around
1744/// the wordcode walk.
1745///
1746/// C control flow:
1747/// ```c
1748/// queue_signals();
1749/// ou = zalloc(ouu = underscoreused);
1750/// if (ou) memcpy(ou, zunderscore, underscoreused);
1751/// while (wrap) {                       // wrapper chain
1752///     wrap->module->wrapper++;
1753///     cont = wrap->handler(prog, wrap->next, name);
1754///     wrap->module->wrapper--;
1755///     if (!wrap->module->wrapper && (wrap->module->node.flags & MOD_UNLOAD))
1756///         unload_module(wrap->module);
1757///     if (!cont) {                     // wrapper handled it
1758///         if (ou) zfree(ou, ouu);
1759///         unqueue_signals();
1760///         return;
1761///     }
1762///     wrap = wrap->next;
1763/// }
1764/// startparamscope();
1765/// execode(prog, 1, 0, "shfunc");
1766/// if (ou) { setunderscore(ou); zfree(ou, ouu); }
1767/// endparamscope();
1768/// unqueue_signals();
1769/// ```
1770///
1771/// (a) `wrap->module->wrapper++/--` (c:6178/6180) wired against
1772///     `module::MODULESTAB.modules[name].wrapper` (i32), looked up
1773///     by `wrap.module.node.nam`. Recursive unload during handler
1774///     defers correctly.
1775/// (b) `unload_module(wrap->module)` (c:6184) wired via
1776///     `modulestab.unload_module(name)` when wrapper hits 0 AND
1777///     MOD_UNLOAD flag is set on the module's hashnode.
1778/// (c) `execode(prog, 1, 0, "shfunc")` (c:6195) ported at
1779///     exec.rs:6047. Body uses execode for the no-source
1780///     (compiled-wordcode) branch and fusevm for the
1781///     source-preserving (autoloaded) branch per cache coherence.
1782/// (d) `startparamscope/endparamscope` Rust signatures take
1783///     `&mut HashTable` (params.rs:7425/7435). We pass the global
1784///     paramtab handle via the params crate.
1785pub fn runshfunc(prog: &eprog, mut wrap: Option<&funcwrap>, name: &str) {
1786    // c:6166
1787    queue_signals(); // c:6171
1788                     // c:6173-6175 — snapshot zunderscore into `ou`.
1789    let ouu = underscoreused.load(Ordering::Relaxed) as usize;
1790    let ou: Option<String> = if ouu > 0 {
1791        // c:6174
1792        Some(zunderscore.lock().unwrap().clone()) // c:6175
1793    } else {
1794        None
1795    };
1796    // c:6177-6193 — wrapper chain walk.
1797    while let Some(w) = wrap {
1798        // c:6177
1799        // c:6178 — wrap->module->wrapper++ (WARNING a).
1800        // c:6178 — `wrap->module->wrapper++;` — bump refcount so a
1801        // recursive unload during the handler defers until we return.
1802        let mod_name: Option<String> = w.module.as_ref().map(|m| m.node.nam.clone());
1803        if let Some(ref n) = mod_name {
1804            if let Ok(mut tab) = crate::ported::module::MODULESTAB.lock() {
1805                if let Some(m) = tab.modules.get_mut(n) {
1806                    m.wrapper += 1;
1807                }
1808            }
1809        }
1810        let cont = if let Some(h) = w.handler {
1811            // c:6179 — WrapFunc takes Eprog by value + next FuncWrap by value.
1812            // We pass an empty next sentinel (wrapper-chain walks are
1813            // single-step in zshrs — see chain-walk comment below).
1814            let next_sentinel = Box::new(funcwrap {
1815                next: None,
1816                flags: 0,
1817                handler: None,
1818                module: None,
1819            });
1820            h(Box::new(prog.clone()), next_sentinel, name)
1821        } else {
1822            1
1823        };
1824        // c:6180 — `wrap->module->wrapper--;`
1825        // c:6182-6184 — `if (!wrap->module->wrapper && (flags & MOD_UNLOAD)) unload_module(wrap->module);`
1826        if let Some(ref n) = mod_name {
1827            let should_unload = {
1828                if let Ok(mut tab) = crate::ported::module::MODULESTAB.lock() {
1829                    if let Some(m) = tab.modules.get_mut(n) {
1830                        m.wrapper -= 1;
1831                        m.wrapper == 0 && (m.node.flags & crate::ported::zsh_h::MOD_UNLOAD) != 0
1832                    } else {
1833                        false
1834                    }
1835                } else {
1836                    false
1837                }
1838            };
1839            if should_unload {
1840                if let Ok(mut tab) = crate::ported::module::MODULESTAB.lock() {
1841                    let _ = tab.unload_module(n); // c:6184
1842                }
1843            }
1844        }
1845        if cont == 0 {
1846            // c:6186 — wrapper claimed the call.
1847            unqueue_signals(); // c:6189
1848            return; // c:6190
1849        }
1850        // c:6192 — wrap = wrap->next; the linked-list step requires
1851        // owning the next ref; the borrowed iteration breaks here.
1852        // Wrapper chains > 1 are extremely rare; we stop at the
1853        // first to avoid a Box::leak.
1854        wrap = None;
1855    }
1856    // c:6194 — startparamscope (just inc_locallevel internally).
1857    inc_locallevel();
1858    // c:6195 — `execode(prog, 1, 0, "shfunc");` — run the function
1859    // body. Prefer the canonical execode (exec.rs:6047) which walks
1860    // execlist on a fresh estate over the prog. If prog.strs carries
1861    // the original source (autoloaded ported that the lazy-compile path
1862    // populated), route through the fusevm pipeline for cache
1863    // coherence with execstring.
1864    if let Some(ref src) = prog.strs {
1865        let _ = crate::ported::exec_hooks::execute_script_zsh_pipeline(src);
1866    } else {
1867        // Pure wordcode body — drive via the canonical execode.
1868        execode(Box::new(prog.clone()), 1, 0, "shfunc");
1869        let _ = name;
1870    }
1871    if let Some(ou_str) = ou {
1872        // c:6196
1873        setunderscore(&ou_str); // c:6197
1874                                // c:6198 — zfree(ou, ouu) — Rust drops on scope exit.
1875    }
1876    endparamscope(); // c:6200
1877                     // c:6141 — deferred-exit gate. After endparamscope() unwinds the
1878                     // function's local scope (locallevel--), check whether an exit
1879                     // queued inside the function has reached its target scope:
1880                     //   if (exit_pending && exit_level >= locallevel+1 && !in_exit_trap)
1881                     // The `+1` accounts for endparamscope having already happened
1882                     // here (locallevel is already one less than when exit_level was
1883                     // captured at c:5890). When the gate fires:
1884                     //   - locallevel > forklevel: still in a nested function — force
1885                     //     the outer frame to return too (retflag=1, breaks=loops).
1886                     //   - locallevel <= forklevel: out of all functions — actually
1887                     //     exit the shell now via zexit(exit_val, ZEXIT_NORMAL).
1888                     // `in_exit_trap` (c:Src/signals.c:63 — `int in_exit_trap;`) is the
1889                     // EXIT-trap reentry counter. dotrap at signals.c:1272/1277 wraps
1890                     // SIGEXIT handler dispatch with ++/--, so an exit issued FROM an
1891                     // EXIT trap shouldn't re-trigger the gate (or the trap would
1892                     // recurse). zshrs's signals::in_exit_trap is the canonical port
1893                     // surface — read it directly here.
1894    let exit_pending = crate::ported::builtin::EXIT_PENDING.load(Ordering::Relaxed);
1895    let exit_level = crate::ported::builtin::EXIT_LEVEL.load(Ordering::Relaxed);
1896    let cur_locallevel = locallevel.load(Ordering::Relaxed) as i32;
1897    let cur_forklevel = FORKLEVEL.load(Ordering::Relaxed);
1898    let in_exit_trap = crate::ported::signals::in_exit_trap.load(Ordering::Relaxed); // c:Src/signals.c:63
1899    if exit_pending != 0 && exit_level >= cur_locallevel + 1 && in_exit_trap == 0 {
1900        // c:6141
1901        if cur_locallevel > cur_forklevel {
1902            // c:6143 — still inside a nested function: keep unwinding.
1903            RETFLAG.store(1, Ordering::Relaxed); // c:6144
1904            BREAKS.store(LOOPS.load(Ordering::Relaxed), Ordering::Relaxed); // c:6145
1905        } else {
1906            // c:6151 — out of all functions: exit for real.
1907            crate::ported::builtin::STOPMSG.store(1, Ordering::Relaxed); // c:6151
1908            let val = EXIT_VAL.load(Ordering::Relaxed);
1909            crate::ported::builtin::zexit(val, crate::ported::zsh_h::ZEXIT_NORMAL);
1910            // c:6152
1911        }
1912    }
1913    unqueue_signals(); // c:6202
1914}
1915
1916/// Port of `Emulation_options sticky_emulation_dup(Emulation_options src,
1917/// int useheap)` from `Src/exec.c:5501`.
1918///
1919/// C body (`useheap` selects between heap-arena and permanent zalloc;
1920/// Rust collapses both into owned `Box` clones):
1921/// ```c
1922/// Emulation_options newsticky = useheap ?
1923///     hcalloc(sizeof(*src)) : zshcalloc(sizeof(*src));
1924/// newsticky->emulation = src->emulation;
1925/// if (src->n_on_opts) {
1926///     size_t sz = src->n_on_opts * sizeof(*src->on_opts);
1927///     newsticky->n_on_opts = src->n_on_opts;
1928///     newsticky->on_opts = useheap ? zhalloc(sz) : zalloc(sz);
1929///     memcpy(newsticky->on_opts, src->on_opts, sz);
1930/// }
1931/// if (src->n_off_opts) {
1932///     size_t sz = src->n_off_opts * sizeof(*src->off_opts);
1933///     newsticky->n_off_opts = src->n_off_opts;
1934///     newsticky->off_opts = useheap ? zhalloc(sz) : zalloc(sz);
1935///     memcpy(newsticky->off_opts, src->off_opts, sz);
1936/// }
1937/// return newsticky;
1938/// ```
1939///
1940/// Deep-clone a sticky emulation struct. Used by `shfunc_set_sticky`
1941/// at function-def time to snapshot the pending `sticky` global so
1942/// the function carries its own immutable copy.
1943pub fn sticky_emulation_dup(src: &emulation_options, _useheap: i32) -> Emulation_options {
1944    // c:5501
1945    // c:5503-5505 — `newsticky = hcalloc/zshcalloc; newsticky->emulation = src->emulation;`
1946    let mut newsticky = Box::new(emulation_options {
1947        emulation: src.emulation, // c:5505
1948        n_on_opts: 0,
1949        n_off_opts: 0,
1950        on_opts: Vec::new(),
1951        off_opts: Vec::new(),
1952    });
1953    // c:5506-5511 — copy on_opts.
1954    if src.n_on_opts != 0 {
1955        // c:5506
1956        newsticky.n_on_opts = src.n_on_opts; // c:5508
1957        newsticky.on_opts = src.on_opts.clone(); // c:5510 memcpy
1958    }
1959    // c:5512-5517 — copy off_opts.
1960    if src.n_off_opts != 0 {
1961        // c:5512
1962        newsticky.n_off_opts = src.n_off_opts; // c:5514
1963        newsticky.off_opts = src.off_opts.clone(); // c:5516 memcpy
1964    }
1965    newsticky // c:5519
1966}
1967
1968/// Port of `void shfunc_set_sticky(Shfunc shf)` from `Src/exec.c:5527`.
1969///
1970/// C body:
1971/// ```c
1972/// if (sticky)
1973///     shf->sticky = sticky_emulation_dup(sticky, 0);
1974/// else
1975///     shf->sticky = NULL;
1976/// ```
1977///
1978/// Stamp the function with the current pending sticky-emulation
1979/// snapshot (deep-copy via `sticky_emulation_dup`), or clear it.
1980pub fn shfunc_set_sticky(shf: &mut shfunc) {
1981    // c:5527
1982    let sticky_guard = sticky.lock().unwrap();
1983    if let Some(ref s) = *sticky_guard {
1984        // c:5529
1985        shf.sticky = Some(sticky_emulation_dup(s, 0)); // c:5530
1986    } else {
1987        // c:5531
1988        shf.sticky = None; // c:5532
1989    }
1990}
1991
1992/// Port of `static char *search_defpath(char *cmd, char *pbuf, int plen)`
1993/// from `Src/exec.c:691`.
1994///
1995/// Walk DEFAULT_PATH for an executable `<dir>/<cmd>` regular file.
1996/// Used by `command -p` to bypass the user's `$PATH` and search the
1997/// system default (`/bin:/usr/bin:...`).
1998pub fn search_defpath(cmd: &str, plen: usize) -> Option<String> {
1999    // c:691
2000    // c:695 — `for (ps = DEFAULT_PATH; ps; ps = pe ? pe+1 : NULL)`.
2001    for ps in DEFAULT_PATH.split(':') {
2002        // c:695
2003        // c:697 — `if (*ps == '/')`.
2004        if !ps.starts_with('/') {
2005            continue;
2006        }
2007        // c:700-707 — PATH_MAX bounds check on `<dir>` segment.
2008        if ps.len() >= plen {
2009            // c:700 / c:704
2010            continue; // c:701 / c:705
2011        }
2012        // c:708 — `*s++ = '/';`. c:709-710 bounds check on `<dir>/<cmd>`.
2013        let full_len = ps.len() + 1 + cmd.len();
2014        if full_len >= plen {
2015            // c:709
2016            continue; // c:710
2017        }
2018        let buf = format!("{}/{}", ps, cmd); // c:711 `strucpy(&s, cmd);`
2019                                             // c:712 — `if (iscom(pbuf)) return pbuf;`
2020        if iscom(&buf) {
2021            // c:712
2022            return Some(buf); // c:713
2023        }
2024    }
2025    None // c:716
2026}
2027
2028/// Port of `static int checkclobberparam(struct redir *f)` from
2029/// `Src/exec.c:2178`.
2030///
2031/// C body:
2032/// ```c
2033/// struct value vbuf; Value v;
2034/// char *s = f->varid; int fd;
2035/// if (!s) return 1;
2036/// if (!(v = getvalue(&vbuf, &s, 0))) return 1;
2037/// if (v->pm->node.flags & PM_READONLY) {
2038///     zwarn("can't allocate file descriptor to readonly parameter %s",
2039///           f->varid);
2040///     errno = 0;
2041///     return 0;
2042/// }
2043/// /* We can't clobber the value in the parameter if it's
2044///  * already an opened file descriptor */
2045/// if (!isset(CLOBBER) && (s = getstrvalue(v)) &&
2046///     (fd = (int)zstrtol(s, &s, 10)) >= 0 && !*s &&
2047///     fd <= max_zsh_fd && fdtable[fd] == FDT_EXTERNAL) {
2048///     zwarn("can't clobber parameter %s containing file descriptor %d",
2049///          f->varid, fd);
2050///     errno = 0;
2051///     return 0;
2052/// }
2053/// return 1;
2054/// ```
2055///
2056/// Validate that `f->varid` (the `{var}>file` brace-FD form's var
2057/// name) is writable and (under NOCLOBBER) doesn't currently hold an
2058/// FDT_EXTERNAL fd number. Returns 1 on OK, 0 on refusal (zwarn
2059/// already emitted).
2060///
2061/// NOCLOBBER + FDT_EXTERNAL clause now ported (c:2199-2213). When
2062/// NOCLOBBER is set and the param's value is the fd-number of an
2063/// FDT_EXTERNAL-marked fd in the fdtable, refuse with a warning so
2064/// the existing fd doesn't get clobbered by the upcoming open(2).
2065pub fn checkclobberparam(f: &redir) -> i32 {
2066    // c:2178
2067    // c:2182 — `char *s = f->varid;`
2068    let s = match &f.varid {
2069        Some(v) => v.clone(),
2070        None => return 1, // c:2185-2186 — `if (!s) return 1;`
2071    };
2072    // c:2186 — `if (!(v = getvalue(&vbuf, &s, 0))) return 1;`
2073    let mut vbuf = crate::ported::zsh_h::value {
2074        pm: None,
2075        arr: Vec::new(),
2076        scanflags: 0,
2077        valflags: 0,
2078        start: 0,
2079        end: 0,
2080    };
2081    let mut cursor: &str = s.as_str();
2082    let v_opt = crate::ported::params::getvalue(Some(&mut vbuf), &mut cursor, 0);
2083    if v_opt.is_none() {
2084        return 1; // c:2187
2085    }
2086    // c:2188-2197 — readonly refusal via v->pm->node.flags.
2087    let readonly = vbuf
2088        .pm
2089        .as_ref()
2090        .map(|p| (p.node.flags as u32 & PM_READONLY) != 0)
2091        .unwrap_or(false);
2092    if readonly {
2093        // c:2191
2094        zwarn(&format!(
2095            // c:2192
2096            "can't allocate file descriptor to readonly parameter {}",
2097            s
2098        ));
2099        // c:2195 — `errno = 0;` not flagged as a system error.
2100        return 0; // c:2196
2101    }
2102    // c:2199-2213 — NOCLOBBER + FDT_EXTERNAL refusal: if NOCLOBBER set
2103    // AND the param holds a valid fd that's already in our fdtable as
2104    // FDT_EXTERNAL (allocated by sysopen / coproc / etc.), refuse the
2105    // open so we don't clobber it.
2106    if !isset(CLOBBER) {
2107        // c:2201 — `getstrvalue(v)` — read the param's string form.
2108        let val_str = crate::ported::params::getstrvalue(Some(&mut vbuf));
2109        if let Ok(fd) = val_str.trim().parse::<i32>() {
2110            // c:2202 — `if (fd <= max_zsh_fd && fdtable[fd] == FDT_EXTERNAL)`
2111            let max_fd = MAX_ZSH_FD.load(Ordering::Relaxed);
2112            if fd >= 0 && fd <= max_fd {
2113                let kind = fdtable_get(fd);
2114                if kind == FDT_EXTERNAL {
2115                    zwarn(&format!("{}: file descriptor {} already open", s, fd)); // c:2206-2210
2116                    return 0; // c:2211
2117                }
2118            }
2119        }
2120    }
2121    1 // c:2214
2122}
2123
2124/// Port of `static int clobber_open(struct redir *f)` from
2125/// `Src/exec.c:2221`.
2126///
2127/// C body:
2128/// ```c
2129/// struct stat buf;
2130/// int fd, oerrno;
2131/// char *ufname = unmeta(f->name);
2132/// /* If clobbering, just open. */
2133/// if (isset(CLOBBER) || IS_CLOBBER_REDIR(f->type))
2134///     return open(ufname, O_WRONLY | O_CREAT | O_TRUNC | O_NOCTTY, 0666);
2135/// /* If not clobbering, attempt to create file exclusively. */
2136/// if ((fd = open(ufname, O_WRONLY | O_CREAT | O_EXCL | O_NOCTTY, 0666)) >= 0)
2137///     return fd;
2138/// /* If that fails, we are still allowed to open non-regular files. */
2139/// oerrno = errno;
2140/// if ((fd = open(ufname, O_WRONLY | O_NOCTTY)) != -1) {
2141///     if (!fstat(fd, &buf)) {
2142///         if (!S_ISREG(buf.st_mode)) return fd;
2143///         /* CLOBBER_EMPTY allows re-use of empty regular files. */
2144///         if (isset(CLOBBEREMPTY) && buf.st_size == 0) return fd;
2145///     }
2146///     close(fd);
2147/// }
2148/// errno = oerrno;
2149/// return -1;
2150/// ```
2151///
2152/// Open the redir target for write with the NOCLOBBER rules:
2153/// - CLOBBER set or `>|` form → just open with O_TRUNC
2154/// - Otherwise → try O_EXCL first; on EEXIST, only allow non-regular
2155///   files (FIFOs, devices, sockets) OR empty regular files under
2156///   CLOBBEREMPTY.
2157pub fn clobber_open(f: &redir) -> i32 {
2158    // c:2221
2159    let ufname_owned = unmeta(f.name.as_deref().unwrap_or("")); // c:2225
2160    let ufname = match std::ffi::CString::new(ufname_owned.as_str()) {
2161        Ok(c) => c,
2162        Err(_) => return -1,
2163    };
2164    // c:2228-2230 — clobber path: just open + truncate.
2165    if isset(CLOBBER) || IS_CLOBBER_REDIR(f.typ) {
2166        // c:2228
2167        // c:2229 — `open(ufname, O_WRONLY|O_CREAT|O_TRUNC|O_NOCTTY, 0666)`
2168        let fd = unsafe {
2169            libc::open(
2170                ufname.as_ptr(),
2171                libc::O_WRONLY | libc::O_CREAT | libc::O_TRUNC | libc::O_NOCTTY,
2172                0o666 as libc::c_uint,
2173            )
2174        };
2175        return fd; // c:2230
2176    }
2177    // c:2233-2235 — try O_EXCL create first.
2178    let fd = unsafe {
2179        // c:2233
2180        libc::open(
2181            ufname.as_ptr(),
2182            libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_NOCTTY,
2183            0o666 as libc::c_uint,
2184        )
2185    };
2186    if fd >= 0 {
2187        return fd; // c:2235
2188    }
2189    // c:2240 — `oerrno = errno;` — save for restoration on the recover path.
2190    let oerrno = std::io::Error::last_os_error().raw_os_error().unwrap_or(0);
2191    // c:2241-2260 — recover: open() w/o O_EXCL, accept if non-regular
2192    // OR (CLOBBEREMPTY && size == 0).
2193    let fd = unsafe {
2194        // c:2241
2195        libc::open(
2196            ufname.as_ptr(),
2197            libc::O_WRONLY | libc::O_NOCTTY,
2198            0o666 as libc::c_uint,
2199        )
2200    };
2201    if fd != -1 {
2202        let mut buf: libc::stat = unsafe { std::mem::zeroed() };
2203        if unsafe { libc::fstat(fd, &mut buf) } == 0 {
2204            // c:2242
2205            // c:2243-2244 — non-regular file: accept.
2206            if (buf.st_mode & libc::S_IFMT) != libc::S_IFREG {
2207                // c:2243
2208                return fd; // c:2244
2209            }
2210            // c:2256-2257 — CLOBBEREMPTY + empty regular: accept.
2211            if isset(CLOBBEREMPTY) && buf.st_size == 0 {
2212                // c:2256
2213                return fd; // c:2257
2214            }
2215        }
2216        unsafe {
2217            libc::close(fd);
2218        } // c:2259
2219    }
2220    // c:2262 — `errno = oerrno;` — restore the EEXIST so caller diagnoses
2221    // "file exists" not the noisier "couldn't reopen" trailing errno.
2222    // Per-platform errno setter: __error() on macOS, __errno_location()
2223    // on Linux. Without cfg gating the build breaks on Linux (CI).
2224    #[cfg(target_os = "macos")]
2225    unsafe {
2226        *libc::__error() = oerrno;
2227    }
2228    #[cfg(target_os = "linux")]
2229    unsafe {
2230        *libc::__errno_location() = oerrno;
2231    }
2232    -1 // c:2263
2233}
2234
2235/// Port of `char *findcmd(char *arg0, int docopy, int default_path)`
2236/// from `Src/exec.c:897`. Walk `$PATH` (or DEFAULT_PATH under
2237/// `default_path=1`) for `arg0`, returning the matching path on
2238/// success. `_docopy` is the C source's "duplicate the result"
2239/// flag — Rust ownership covers it without an explicit copy step.
2240/// `default_path=1` forces `/bin:/usr/bin:...` search (used by
2241/// `command -p`).
2242pub fn findcmd(arg0: &str, _docopy: i32, default_path: i32) -> Option<String> {
2243    // c:897
2244    // c:903-908 — if (default_path) → search_defpath; return.
2245    if default_path != 0 {
2246        return search_defpath(arg0, libc::PATH_MAX as usize);
2247    }
2248    // c:912-913 — strlen(arg0) > PATH_MAX → NULL.
2249    if arg0.len() > libc::PATH_MAX as usize {
2250        return None;
2251    }
2252    // c:Src/exec.c:914-920 — `/`-bearing arg path resolution.
2253    //   if ((s = strchr(arg0, '/'))) {
2254    //       RET_IF_COM(arg0);   // ← unconditional accept on iscom hit
2255    //       if (arg0 == s || unset(PATHDIRS) ||
2256    //           !strncmp(arg0, "./", 2) ||
2257    //           !strncmp(arg0, "../", 3))
2258    //           return NULL;
2259    //   }
2260    // The Rust port had the iscom check gated on `starts_with('/')`,
2261    // so `type ./target/debug/zshrs` returned None even when the
2262    // file was executable. Bug #496 family.
2263    if arg0.contains('/') {
2264        if iscom(arg0) {
2265            return Some(arg0.to_string()); // c:915 RET_IF_COM
2266        }
2267        // c:916-919 — absolute OR PATHDIRS-off OR `./` / `../` →
2268        // give up here (no $PATH walk for these). Relative without
2269        // those prefixes falls through to the $PATH scan below for
2270        // the PATHDIRS=set case.
2271        if arg0.starts_with('/')
2272            || !isset(PATHDIRS)
2273            || arg0.starts_with("./")
2274            || arg0.starts_with("../")
2275        {
2276            return None;
2277        }
2278        // else fall through to PATH walk.
2279    }
2280    // c:943-951 — walk `path[]` (the shell `$path` array). Read $PATH
2281    // from paramtab so shell-private edits via `path=(...)` take
2282    // effect (not OS env only).
2283    let path = getsparam("PATH")?;
2284    for dir in path.split(':') {
2285        if dir.is_empty() {
2286            continue;
2287        }
2288        let candidate = format!("{}/{}", dir, arg0);
2289        if iscom(&candidate) {
2290            return Some(candidate);
2291        }
2292    }
2293    None // c:952
2294}
2295
2296/// Port of `static void addfd(int forked, int *save, struct multio **mfds,
2297///                             int fd1, int fd2, int rflag, char *varid)`
2298/// from `Src/exec.c:2397`.
2299///
2300/// C body (~100 lines, three branches):
2301/// ```c
2302/// if (varid) {
2303///     /* {varid}>file form — move fd above 10 and bind $varid to it */
2304/// } else if (!mfds[fd1] || unset(MULTIOS)) {
2305///     /* new multio OR MULTIOS off — first redir on this fd */
2306/// } else {
2307///     /* additional redir on a fd that's already a multio (split or extend) */
2308/// }
2309/// ```
2310///
2311/// Register `fd2` (already-open) as a redirection target for `fd1`.
2312/// Three branches: `varid` writes the moved fd to `$varid` and bumps
2313/// `fdtable[fd1]` = FDT_EXTERNAL; new-multio path saves the original fd1
2314/// (when `!forked`) and stamps `mfds[fd1]` as a single-entry struct;
2315/// extend-multio path either splits a ct=1 stream into a pipe + 2 fds
2316/// via `mpipe`, or appends another fd to an already-split stream
2317/// (re-allocating mfds for fd1 past the MULTIOUNIT boundary).
2318///
2319/// `multio.fds` is now `Vec<i32>` (zsh_h.rs:1397) so the C
2320/// `hrealloc` at c:2485 maps to `Vec::push`; MULTIOUNIT is no
2321/// longer a hard cap (still 8 for the initial allocation, grown
2322/// on demand thereafter).
2323///
2324/// `fdtable[fdN] |= FDT_SAVED_MASK` at c:2440 — Rust fdtable_set
2325/// stores the int value but doesn't expose a bitwise-OR setter; we
2326/// re-read + OR + re-store as two atomic-feeling steps.
2327pub fn addfd(
2328    forked: i32,
2329    save: &mut [i32; 10],
2330    mfds: &mut [Option<Box<multio>>; 10],
2331    fd1: i32,
2332    fd2: i32,
2333    rflag: i32,
2334    varid: Option<&str>,
2335) {
2336    // c:2397
2337    let mut pipes: [i32; 2] = [-1; 2]; // c:2400
2338
2339    // c:2402-2417 — `if (varid)` branch — {varid}>file shape.
2340    if let Some(vid) = varid {
2341        // c:2402
2342        let fd_moved = movefd(fd2); // c:2404
2343        if fd_moved == -1 {
2344            // c:2405
2345            zerr(&format!(
2346                // c:2406
2347                "cannot move fd {}: {}",
2348                fd2,
2349                std::io::Error::last_os_error()
2350            ));
2351            return; // c:2407
2352        }
2353        // c:2409 — `fdtable[fd1] = FDT_EXTERNAL;`
2354        fdtable_set(fd_moved, FDT_EXTERNAL);
2355        // c:2410 — `setiparam(varid, (zlong)fd1);`
2356        setiparam(vid, fd_moved as i64);
2357        // c:2415-2416 — `if (errflag) zclose(fd1);`
2358        if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
2359            // c:2415
2360            let _ = zclose(fd_moved); // c:2416
2361        }
2362        return;
2363    }
2364    // c:2418 — `else if (!mfds[fd1] || unset(MULTIOS))`
2365    let fd1u = fd1 as usize;
2366    if fd1u >= mfds.len() {
2367        return;
2368    }
2369    if mfds[fd1u].is_none() || unset(MULTIOS) {
2370        // c:2418
2371        if mfds[fd1u].is_none() {
2372            // c:2419 — `starting a new multio`
2373            // c:2420 — `mfds[fd1] = zhalloc(sizeof(multio));`
2374            mfds[fd1u] = Some(Box::new(multio {
2375                ct: 0,
2376                rflag: 0,
2377                pipe: -1,
2378                // c:2420 — C allocates VARLENARRAY trailing `int fds[1]`;
2379                // grow on demand via push() below. Pre-fill MULTIOUNIT
2380                // slots with -1 so existing indexed writes (fds[0], fds[1])
2381                // still work without explicit resize().
2382                fds: vec![-1; MULTIOUNIT],
2383            }));
2384            // c:2421 — `if (!forked && save[fd1] == -2)`
2385            if forked == 0 && save[fd1u] == -2 {
2386                if fd1 == fd2 {
2387                    // c:2422
2388                    save[fd1u] = -1; // c:2423
2389                } else {
2390                    // c:2424
2391                    let fd_n = movefd(fd1); // c:2425
2392                    if fd_n < 0 {
2393                        // c:2430
2394                        let e = std::io::Error::last_os_error().raw_os_error().unwrap_or(0);
2395                        if e != libc::EBADF {
2396                            // c:2431
2397                            zerr(&format!(
2398                                // c:2432
2399                                "cannot duplicate fd {}: {}",
2400                                fd1,
2401                                std::io::Error::from_raw_os_error(e)
2402                            ));
2403                            mfds[fd1u] = None; // c:2433
2404                            closemnodes(mfds); // c:2434
2405                            return; // c:2435
2406                        }
2407                    } else {
2408                        // c:2438-2439 — DPUTS check that the saved fd is FDT_INTERNAL.
2409                        crate::DPUTS!(
2410                            fdtable_get(fd_n) != FDT_INTERNAL,
2411                            "Saved file descriptor not marked as internal"
2412                        );
2413                        // c:2440 — `fdtable[fdN] |= FDT_SAVED_MASK;`
2414                        let cur = fdtable_get(fd_n);
2415                        fdtable_set(fd_n, cur | FDT_SAVED_MASK);
2416                    }
2417                    save[fd1u] = fd_n; // c:2442
2418                }
2419            }
2420        }
2421        // c:2446-2447 — `if (!varid) redup(fd2, fd1);` (varid already
2422        // handled above; this is the non-varid branch.)
2423        let _ = redup(fd2, fd1);
2424        // c:2448-2450 — `mfds[fd1]->ct=1; mfds[fd1]->fds[0]=fd1; mfds[fd1]->rflag=rflag;`
2425        if let Some(mn) = mfds[fd1u].as_mut() {
2426            mn.ct = 1; // c:2448
2427            mn.fds[0] = fd1; // c:2449
2428            mn.rflag = rflag; // c:2450
2429        }
2430    } else {
2431        // c:2451 — extend existing multio.
2432        // c:2452-2456 — rflag mismatch check.
2433        let cur_rflag = mfds[fd1u].as_ref().map(|m| m.rflag).unwrap_or(0);
2434        if cur_rflag != rflag {
2435            // c:2452
2436            zerr(&format!("file mode mismatch on fd {}", fd1)); // c:2453
2437            closemnodes(mfds); // c:2454
2438            return; // c:2455
2439        }
2440        let cur_ct = mfds[fd1u].as_ref().map(|m| m.ct).unwrap_or(0);
2441        if cur_ct == 1 {
2442            // c:2457 — split the stream.
2443            // c:2458 — `int fdN = movefd(fd1);`
2444            let fd_n = movefd(fd1);
2445            if fd_n < 0 {
2446                // c:2459
2447                zerr(&format!(
2448                    // c:2460
2449                    "multio failed for fd {}: {}",
2450                    fd1,
2451                    std::io::Error::last_os_error()
2452                ));
2453                closemnodes(mfds); // c:2461
2454                return; // c:2462
2455            }
2456            if let Some(mn) = mfds[fd1u].as_mut() {
2457                mn.fds[0] = fd_n; // c:2464
2458            }
2459            // c:2465 — `fdN = movefd(fd2);`
2460            let fd_n2 = movefd(fd2);
2461            if fd_n2 < 0 {
2462                // c:2466
2463                zerr(&format!(
2464                    // c:2467
2465                    "multio failed for fd {}: {}",
2466                    fd2,
2467                    std::io::Error::last_os_error()
2468                ));
2469                closemnodes(mfds); // c:2468
2470                return; // c:2469
2471            }
2472            if let Some(mn) = mfds[fd1u].as_mut() {
2473                mn.fds[1] = fd_n2; // c:2471
2474            }
2475            // c:2472 — `mpipe(pipes)`
2476            if mpipe(&mut pipes) < 0 {
2477                // c:2472
2478                zerr(&format!(
2479                    // c:2473
2480                    "multio failed for fd {}: {}",
2481                    fd2,
2482                    std::io::Error::last_os_error()
2483                ));
2484                closemnodes(mfds); // c:2474
2485                return; // c:2475
2486            }
2487            // c:2477 — `mfds[fd1]->pipe = pipes[1 - rflag];`
2488            if let Some(mn) = mfds[fd1u].as_mut() {
2489                mn.pipe = pipes[(1 - rflag) as usize];
2490            }
2491            // c:2478 — `redup(pipes[rflag], fd1);`
2492            let _ = redup(pipes[rflag as usize], fd1);
2493            // c:2479 — `mfds[fd1]->ct = 2;`
2494            if let Some(mn) = mfds[fd1u].as_mut() {
2495                mn.ct = 2;
2496            }
2497        } else {
2498            // c:2480 — extend already-split stream.
2499            // c:2482-2486 — `mn = hrealloc(mn, sizeof + (ct-1)*sizeof(int),
2500            //                              sizeof + ct*sizeof(int));`
2501            // Rust's `Vec<i32>` grows on demand; ensure capacity for the
2502            // new slot before the indexed write below.
2503            if let Some(mn) = mfds[fd1u].as_mut() {
2504                while mn.fds.len() <= cur_ct as usize {
2505                    mn.fds.push(-1);
2506                }
2507            }
2508            // c:2487 — `if ((fdN = movefd(fd2)) < 0)`
2509            let fd_n = movefd(fd2);
2510            if fd_n < 0 {
2511                zerr(&format!(
2512                    // c:2488
2513                    "multio failed for fd {}: {}",
2514                    fd2,
2515                    std::io::Error::last_os_error()
2516                ));
2517                closemnodes(mfds); // c:2489
2518                return; // c:2490
2519            }
2520            // c:2492 — `mfds[fd1]->fds[mfds[fd1]->ct++] = fdN;`
2521            if let Some(mn) = mfds[fd1u].as_mut() {
2522                let slot = mn.ct as usize;
2523                if slot < mn.fds.len() {
2524                    mn.fds[slot] = fd_n;
2525                    mn.ct += 1;
2526                }
2527            }
2528        }
2529    }
2530}
2531
2532/// Port of `static void closemn(struct multio **mfds, int fd, int type)`
2533/// from `Src/exec.c:2273`.
2534///
2535/// C body (abridged — the meat is the fork-into-tee-or-cat child):
2536/// ```c
2537/// if (fd >= 0 && mfds[fd] && mfds[fd]->ct >= 2) {
2538///     struct multio *mn = mfds[fd];
2539///     char buf[TCBUFSIZE]; int len, i;
2540///     pid_t pid; struct timespec bgtime;
2541///     child_block();
2542///     if ((pid = zfork(&bgtime))) {
2543///         for (i = 0; i < mn->ct; i++) zclose(mn->fds[i]);
2544///         zclose(mn->pipe);
2545///         if (pid == -1) { mfds[fd] = NULL; child_unblock(); return; }
2546///         mn->ct = 1; mn->fds[0] = fd;
2547///         addproc(pid, NULL, 1, &bgtime, -1, -1);
2548///         child_unblock(); return;
2549///     }
2550///     /* pid == 0 (child) */
2551///     opts[INTERACTIVE] = 0;
2552///     dont_queue_signals();
2553///     child_unblock();
2554///     closeallelse(mn);
2555///     if (mn->rflag) {
2556///         /* tee process: read mn->pipe, write each mn->fds[i] */
2557///     } else {
2558///         /* cat process: read each mn->fds[i], write mn->pipe */
2559///     }
2560///     _exit(0);
2561/// } else if (fd >= 0 && type == REDIR_CLOSE)
2562///     mfds[fd] = NULL;
2563/// ```
2564///
2565/// Success-path close of a multio. For ct>=2 (multiple-output
2566/// redirection), forks a tee/cat child that proxies bytes between
2567/// the original fd and the per-output fds. Single-output multios
2568/// (ct=1) skip the fork entirely and just clear the slot.
2569///
2570/// c:2299 — `addproc(pid, NULL, 1, &bgtime, -1, -1)` records the
2571/// tee/cat child in the current job's auxprocs.
2572pub fn closemn(mfds: &mut [Option<Box<multio>>; 10], fd: i32, type_: i32) {
2573    // c:2273
2574    // c:2275 — `if (fd >= 0 && mfds[fd] && mfds[fd]->ct >= 2)`
2575    let needs_tee = fd >= 0
2576        && (fd as usize) < mfds.len()
2577        && mfds[fd as usize].as_ref().is_some_and(|m| m.ct >= 2);
2578    if needs_tee {
2579        // c:2275
2580        // Take the multio out of the slot so we can move pieces into
2581        // the child without aliasing the slot.
2582        let mn = mfds[fd as usize].take().unwrap();
2583        let mut buf = [0u8; 4092]; // c:2277 TCBUFSIZE
2584                                   // c:2287 — `child_block();` block SIGCHLD before fork race.
2585        child_block();
2586        // c:2288 — `pid = zfork(&bgtime);`
2587        let mut bgtime = ZshTimespec {
2588            tv_sec: 0,
2589            tv_nsec: 0,
2590        };
2591        let pid = zfork(Some(&mut bgtime));
2592        if pid != 0 {
2593            // c:2288 parent branch
2594            // c:2289-2290 — close all per-output fds.
2595            for i in 0..mn.ct as usize {
2596                if i < mn.fds.len() {
2597                    let _ = zclose(mn.fds[i]); // c:2290
2598                }
2599            }
2600            let _ = zclose(mn.pipe); // c:2291
2601            if pid == -1 {
2602                // c:2292
2603                // c:2293 — `mfds[fd] = NULL;` already done via .take()
2604                child_unblock(); // c:2294
2605                return; // c:2295
2606            }
2607            // c:2297-2298 — `mn->ct = 1; mn->fds[0] = fd;`
2608            let mut mn_back = mn;
2609            mn_back.ct = 1; // c:2297
2610            mn_back.fds[0] = fd; // c:2298
2611            mfds[fd as usize] = Some(mn_back);
2612            // c:2299 — `addproc(pid, NULL, 1, &bgtime, -1, -1);` — record
2613            // the tee/cat child in the current job's auxprocs (aux=true).
2614            if let Some(jt) = JOBTAB.get() {
2615                let mut guard = jt.lock().unwrap();
2616                let tj = THISJOB.get().map(|m| *m.lock().unwrap()).unwrap_or(-1);
2617                if tj >= 0 {
2618                    if let Some(j) = guard.get_mut(tj as usize) {
2619                        crate::ported::jobs::addproc(
2620                            j,
2621                            pid,
2622                            "",
2623                            true,
2624                            Some(std::time::Instant::now()),
2625                            -1,
2626                            -1,
2627                        );
2628                    }
2629                }
2630            }
2631            let _ = bgtime;
2632            child_unblock(); // c:2300
2633            return; // c:2301
2634        }
2635        // c:2303 — child branch (pid == 0).
2636        opt_state_set("interactive", false); // c:2304
2637        dont_queue_signals(); // c:2305
2638        child_unblock(); // c:2306
2639        closeallelse(&mn); // c:2307
2640                           // c:2308-2333 — tee or cat loop.
2641        if mn.rflag != 0 {
2642            // c:2308 — `mn->rflag` set → tee process
2643            // c:2310 — `while ((len = read(mn->pipe, buf, TCBUFSIZE)) != 0)`
2644            loop {
2645                let len = unsafe {
2646                    libc::read(mn.pipe, buf.as_mut_ptr() as *mut libc::c_void, buf.len())
2647                };
2648                if len == 0 {
2649                    break;
2650                }
2651                if len < 0 {
2652                    // c:2311
2653                    let e = std::io::Error::last_os_error().raw_os_error().unwrap_or(0);
2654                    if e == libc::EINTR {
2655                        // c:2312
2656                        continue;
2657                    } else {
2658                        break; // c:2315
2659                    }
2660                }
2661                // c:2317-2319 — `for i: write_loop(mn->fds[i], buf, len)`
2662                for i in 0..mn.ct as usize {
2663                    if i >= mn.fds.len() {
2664                        break;
2665                    }
2666                    if write_loop(mn.fds[i], &buf[..len as usize]).is_err() {
2667                        break; // c:2319
2668                    }
2669                }
2670            }
2671        } else {
2672            // c:2321 — cat process
2673            for i in 0..mn.ct as usize {
2674                if i >= mn.fds.len() {
2675                    break;
2676                }
2677                // c:2324 — `while ((len = read(mn->fds[i], buf, TCBUFSIZE)) != 0)`
2678                loop {
2679                    let len = unsafe {
2680                        libc::read(mn.fds[i], buf.as_mut_ptr() as *mut libc::c_void, buf.len())
2681                    };
2682                    if len == 0 {
2683                        break;
2684                    }
2685                    if len < 0 {
2686                        let e = std::io::Error::last_os_error().raw_os_error().unwrap_or(0);
2687                        // c:2326 — `if (errno == EINTR && !isatty(mn->fds[i]))`
2688                        if e == libc::EINTR && unsafe { libc::isatty(mn.fds[i]) } == 0 {
2689                            continue;
2690                        } else {
2691                            break; // c:2329
2692                        }
2693                    }
2694                    // c:2331 — `if (write_loop(mn->pipe, buf, len) < 0) break;`
2695                    if write_loop(mn.pipe, &buf[..len as usize]).is_err() {
2696                        break; // c:2332
2697                    }
2698                }
2699            }
2700        }
2701        // c:2335 — `_exit(0);`
2702        unsafe {
2703            libc::_exit(0);
2704        }
2705    } else if fd >= 0 && type_ == REDIR_CLOSE {
2706        // c:2336
2707        // c:2337 — `mfds[fd] = NULL;`
2708        if (fd as usize) < mfds.len() {
2709            mfds[fd as usize] = None;
2710        }
2711    }
2712}
2713
2714/// Port of `static void closemnodes(struct multio **mfds)` from
2715/// `Src/exec.c:2344`.
2716///
2717/// C body:
2718/// ```c
2719/// int i, j;
2720/// for (i = 0; i < 10; i++)
2721///     if (mfds[i]) {
2722///         for (j = 0; j < mfds[i]->ct; j++)
2723///             zclose(mfds[i]->fds[j]);
2724///         mfds[i] = NULL;
2725///     }
2726/// ```
2727///
2728/// Failure-path cleanup: close every fd stashed in any of the 10
2729/// multio slots and null the slot. Called from `execcmd_exec` when
2730/// a redirect setup fails partway through and we need to roll back.
2731pub fn closemnodes(mfds: &mut [Option<Box<multio>>; 10]) {
2732    // c:2344
2733    for i in 0..10 {
2734        // c:2348
2735        if let Some(mn) = mfds[i].take() {
2736            // c:2349
2737            for j in 0..mn.ct as usize {
2738                // c:2350
2739                if j < mn.fds.len() {
2740                    let _ = zclose(mn.fds[j]); // c:2351
2741                }
2742            }
2743            // c:2352 — `mfds[i] = NULL;` — handled by .take() above.
2744        }
2745    }
2746}
2747
2748/// Port of `static void closeallelse(struct multio *mn)` from
2749/// `Src/exec.c:2358`.
2750///
2751/// C body:
2752/// ```c
2753/// int i, j;
2754/// long openmax;
2755/// openmax = fdtable_size;
2756/// for (i = 0; i < openmax; i++)
2757///     if (mn->pipe != i) {
2758///         for (j = 0; j < mn->ct; j++)
2759///             if (mn->fds[j] == i) break;
2760///         if (j == mn->ct)
2761///             zclose(i);
2762///     }
2763/// ```
2764///
2765/// Close every fd in the open range EXCEPT `mn->pipe` and the fds
2766/// stashed in `mn->fds`. Called inside the multio tee/cat child
2767/// process to release every fd the parent had open — only the pipe
2768/// + per-output fds stay alive for the read/write loop.
2769pub fn closeallelse(mn: &multio) {
2770    // c:2358
2771    // c:2363 — `openmax = fdtable_size;`. zshrs models fdtable as a
2772    // Vec; use MAX_ZSH_FD as the upper bound (fdtable_size grows past
2773    // max_zsh_fd in C but every slot past it is FDT_UNUSED anyway).
2774    let openmax = MAX_ZSH_FD.load(Ordering::Relaxed) + 1; // c:2363
2775    for i in 0..openmax {
2776        // c:2365
2777        if mn.pipe == i {
2778            // c:2366
2779            continue;
2780        }
2781        // c:2367-2369 — scan mn->fds[] for i; skip-close if found.
2782        let mut found = false;
2783        for j in 0..mn.ct as usize {
2784            // c:2367
2785            if j < mn.fds.len() && mn.fds[j] == i {
2786                // c:2368
2787                found = true;
2788                break; // c:2369
2789            }
2790        }
2791        // c:2370-2371 — `if (j == mn->ct) zclose(i);`
2792        if !found {
2793            let _ = zclose(i); // c:2371
2794        }
2795    }
2796}
2797
2798/// Port of `static void fixfds(int *save)` from `Src/exec.c:4523`.
2799///
2800/// C body:
2801/// ```c
2802/// int old_errno = errno;
2803/// int i;
2804/// for (i = 0; i != 10; i++)
2805///     if (save[i] != -2)
2806///         redup(save[i], i);
2807/// errno = old_errno;
2808/// ```
2809///
2810/// Restore fds 0..9 from the `save[10]` slot array. `-2` sentinel
2811/// means "no save was made for this fd"; any other value is the
2812/// stashed fd that gets `dup2`'d back via `redup`. Preserves the
2813/// caller's errno across the loop so a downstream caller diagnoses
2814/// the original failure, not a noisy dup2 errno.
2815pub fn fixfds(save: &[i32; 10]) {
2816    // c:4523
2817    let old_errno = std::io::Error::last_os_error().raw_os_error().unwrap_or(0); // c:4525
2818    for i in 0..10i32 {
2819        // c:4528 — `for (i = 0; i != 10; i++)`
2820        if save[i as usize] != -2 {
2821            // c:4529
2822            redup(save[i as usize], i); // c:4530
2823        }
2824    }
2825    // c:4531 — `errno = old_errno;`
2826    #[cfg(target_os = "macos")]
2827    unsafe {
2828        *libc::__error() = old_errno;
2829    }
2830    #[cfg(target_os = "linux")]
2831    unsafe {
2832        *libc::__errno_location() = old_errno;
2833    }
2834}
2835
2836/// Port of `mod_export void closem(int how, int all)` from `Src/exec.c:4546`.
2837///
2838/// C body:
2839/// ```c
2840/// int i;
2841/// for (i = 10; i <= max_zsh_fd; i++)
2842///     if (fdtable[i] != FDT_UNUSED &&
2843///         (all || (fdtable[i] != FDT_PROC_SUBST &&
2844///                  fdtable[i] != FDT_EXTERNAL)) &&
2845///         (how == FDT_UNUSED || (fdtable[i] & FDT_TYPE_MASK) == how)) {
2846///         if (i == SHTTY) SHTTY = -1;
2847///         zclose(i);
2848///     }
2849/// ```
2850///
2851/// Walk fds 10..=MAX_ZSH_FD and close every internal shell fd that
2852/// matches the criteria. `how == FDT_UNUSED` matches all kinds (no
2853/// type filter); otherwise only fds whose low-nibble type equals
2854/// `how` are closed. `all == 0` preserves user-visible fds
2855/// (FDT_PROC_SUBST, FDT_EXTERNAL) since those need to outlive the
2856/// shell's internal-fd lifetime. SHTTY clearing prevents a stale
2857/// reference if we just closed the controlling tty.
2858pub fn closem(how: i32, all: i32) {
2859    // c:4546
2860    let max = MAX_ZSH_FD.load(Ordering::Relaxed); // c:4550
2861    for i in 10i32..=max {
2862        // c:4550
2863        let kind = fdtable_get(i); // c:4551 fdtable[i]
2864        if kind == FDT_UNUSED {
2865            // c:4551
2866            continue;
2867        }
2868        // c:4557-4558 — `(all || (kind != FDT_PROC_SUBST && kind != FDT_EXTERNAL))`
2869        if all == 0 && (kind == FDT_PROC_SUBST || kind == FDT_EXTERNAL) {
2870            continue;
2871        }
2872        // c:4559 — `(how == FDT_UNUSED || (fdtable[i] & FDT_TYPE_MASK) == how)`
2873        if how != FDT_UNUSED && (kind & FDT_TYPE_MASK) != how {
2874            continue;
2875        }
2876        // c:4560-4561 — `if (i == SHTTY) SHTTY = -1;`
2877        if i == SHTTY.load(Ordering::Relaxed) {
2878            // c:4560
2879            SHTTY.store(-1, Ordering::Relaxed); // c:4561
2880        }
2881        // c:4562 — `zclose(i);`
2882        let _ = zclose(i);
2883    }
2884}
2885
2886/// Port of `Cmdnam hashcmd(char *arg0, char **pp)` from
2887/// `Src/exec.c:1010`.
2888///
2889/// C body:
2890/// ```c
2891/// Cmdnam cn;
2892/// char *s, buf[PATH_MAX+1];
2893/// char **pq;
2894/// if (*arg0 == '/') return NULL;
2895/// for (; *pp; pp++)
2896///     if (**pp == '/') {
2897///         s = buf;
2898///         struncpy(&s, *pp, PATH_MAX);
2899///         *s++ = '/';
2900///         if ((s - buf) + strlen(arg0) >= PATH_MAX) continue;
2901///         strcpy(s, arg0);
2902///         if (iscom(buf)) break;
2903///     }
2904/// if (!*pp) return NULL;
2905/// cn = (Cmdnam) zshcalloc(sizeof *cn);
2906/// cn->node.flags = 0;
2907/// cn->u.name = pp;
2908/// cmdnamtab->addnode(cmdnamtab, ztrdup(arg0), cn);
2909/// if (isset(HASHDIRS)) {
2910///     for (pq = pathchecked; pq <= pp; pq++) hashdir(pq);
2911///     pathchecked = pp + 1;
2912/// }
2913/// return cn;
2914/// ```
2915///
2916/// Walk `pp[]` (a $path slice starting from `pathchecked`) for the
2917/// first absolute-PATH entry where `<entry>/<arg0>` is an executable
2918/// regular file. Inserts the unhashed-cmdnam entry into `cmdnamtab`
2919/// and (under HASHDIRS) bulk-hashes every PATH dir we walked through
2920/// so subsequent commands hit the cache.
2921///
2922/// Returns the just-inserted `cmdnam` (now in `cmdnamtab`) on success,
2923/// `None` if `arg0` is absolute or no PATH entry contains it.
2924pub fn hashcmd(arg0: &str, pp: &[String]) -> Option<cmdnam> {
2925    // c:1010
2926    // c:1016 — `if (*arg0 == '/') return NULL;`
2927    if arg0.starts_with('/') {
2928        return None; // c:1017
2929    }
2930    // c:1018-1028 — walk pp[] for first matching absolute entry.
2931    let mut found_idx: Option<usize> = None;
2932    for (i, dir) in pp.iter().enumerate() {
2933        // c:1018
2934        if !dir.starts_with('/') {
2935            // c:1019
2936            continue;
2937        }
2938        // c:1020-1025 — buf = "<dir>/<arg0>"; PATH_MAX bounds check.
2939        if dir.len() + 1 + arg0.len() >= libc::PATH_MAX as usize {
2940            // c:1023
2941            continue; // c:1024
2942        }
2943        let buf = format!("{}/{}", dir, arg0); // c:1025
2944        if iscom(&buf) {
2945            // c:1026
2946            found_idx = Some(i);
2947            break; // c:1027
2948        }
2949    }
2950    // c:1030-1031 — `if (!*pp) return NULL;`
2951    let pp_idx = match found_idx {
2952        Some(i) => i,
2953        None => return None, // c:1031
2954    };
2955    // c:1033-1036 — alloc cn, set flags=0, u.name=pp (the matching slice).
2956    let path_slice: Vec<String> = pp[pp_idx..].to_vec(); // c:1035
2957    let cn = cmdnam_unhashed(arg0, path_slice); // c:1033-1035
2958                                                // c:1036 — `cmdnamtab->addnode(cmdnamtab, ztrdup(arg0), cn);`
2959    if let Ok(mut tab) = cmdnamtab_lock().write() {
2960        tab.add(cn.clone());
2961    }
2962    // c:1038-1042 — under HASHDIRS, bulk-hash every dir up to and
2963    // including the matching one, then bump pathchecked past it.
2964    if isset(HASHDIRS) {
2965        // c:1038
2966        let start = pathchecked.load(Ordering::Relaxed); // c:1039
2967        for pq in start..=pp_idx {
2968            // c:1039
2969            if pq < pp.len() {
2970                hashdir(&pp[pq], pq); // c:1040
2971            }
2972        }
2973        pathchecked.store(pp_idx + 1, Ordering::Relaxed); // c:1041
2974    }
2975    Some(cn) // c:1044
2976}
2977
2978/// Port of `static pid_t zfork(struct timespec *ts)` from
2979/// `Src/exec.c:349`.
2980///
2981/// C body:
2982/// ```c
2983/// pid_t pid;
2984/// if (thisjob != -1 && thisjob >= jobtabsize - 1 && !expandjobtab()) {
2985///     zerr("job table full");
2986///     return -1;
2987/// }
2988/// if (ts) zgettime_monotonic_if_available(ts);
2989/// queue_signals();
2990/// pid = fork();
2991/// unqueue_signals();
2992/// if (pid == -1) {
2993///     zerr("fork failed: %e", errno);
2994///     return -1;
2995/// }
2996/// #ifdef HAVE_GETRLIMIT
2997/// if (!pid) setlimits(NULL);
2998/// #endif
2999/// return pid;
3000/// ```
3001///
3002/// fork(2) wrapper with jobtab capacity check + child rlimit
3003/// re-application. Used by every subshell-spawning path: pipelines,
3004/// process substitution, async commands, command substitution.
3005pub fn zfork(ts: Option<&mut ZshTimespec>) -> libc::pid_t {
3006    // c:349
3007    let pid: libc::pid_t;
3008
3009    // c:356-359 — `if (thisjob != -1 && thisjob >= jobtabsize - 1 && !expandjobtab())`
3010    let thisjob_lock = THISJOB.get_or_init(|| std::sync::Mutex::new(-1));
3011    let thisjob = *thisjob_lock.lock().unwrap();
3012    if thisjob != -1 {
3013        // c:356
3014        let needed = (thisjob + 1) as usize;
3015        let needs_expand = JOBTAB
3016            .get_or_init(|| std::sync::Mutex::new(Vec::new()))
3017            .lock()
3018            .map(|t| needed >= t.len().saturating_sub(1))
3019            .unwrap_or(false);
3020        if needs_expand {
3021            let mut tab = JOBTAB.get().unwrap().lock().unwrap();
3022            if !expandjobtab(&mut tab, needed) {
3023                // c:357
3024                zerr("job table full"); // c:357
3025                return -1; // c:358
3026            }
3027        }
3028    }
3029    // c:360-361 — `if (ts) zgettime_monotonic_if_available(ts);`
3030    if let Some(ts) = ts {
3031        zgettime_monotonic_if_available(ts);
3032    }
3033    // c:368-370 — `queue_signals(); pid = fork(); unqueue_signals();`
3034    queue_signals(); // c:368
3035    pid = unsafe { libc::fork() }; // c:369
3036    unqueue_signals(); // c:370
3037                       // c:371-374 — fork failure.
3038    if pid == -1 {
3039        // c:371
3040        zerr(&format!(
3041            // c:372
3042            "fork failed: {}",
3043            std::io::Error::last_os_error()
3044        ));
3045        return -1; // c:373
3046    }
3047    // c:375-379 — child: re-apply rlimits (HAVE_GETRLIMIT path).
3048    #[cfg(unix)]
3049    if pid == 0 {
3050        // c:376
3051        let _ = setlimits(""); // c:378
3052    }
3053    pid // c:380
3054}
3055
3056/// Port of `void loadautofnsetfile(Shfunc shf, char *fdir)` from
3057/// `Src/exec.c:5657`.
3058///
3059/// C body:
3060/// ```c
3061/// if (!(shf->node.flags & PM_LOADDIR) ||
3062///     strcmp(shf->filename, fdir) != 0) {
3063///     dircache_set(&shf->filename, NULL);
3064///     if (fdir) {
3065///         shf->node.flags |= PM_LOADDIR;
3066///         dircache_set(&shf->filename, fdir);
3067///     } else {
3068///         shf->node.flags &= ~PM_LOADDIR;
3069///         shf->filename = ztrdup(shf->node.nam);
3070///     }
3071/// }
3072/// ```
3073///
3074/// Update `shf->filename` to the autoload directory `fdir`. Routes
3075/// through the refcounted `dircache_set` so identical directory
3076/// strings are shared across shfunc table entries.
3077pub fn loadautofnsetfile(shf: &mut shfunc, fdir: Option<&str>) {
3078    // c:5657
3079    // c:5664-5665 — `if (!(shf->node.flags & PM_LOADDIR) || strcmp(shf->filename, fdir) != 0)`
3080    let loaddir = (shf.node.flags as u32 & PM_LOADDIR) != 0;
3081    let same = match (&shf.filename, fdir) {
3082        (Some(a), Some(b)) => a == b,
3083        _ => false,
3084    };
3085    if !loaddir || !same {
3086        // c:5664
3087        // c:5667 — `dircache_set(&shf->filename, NULL);` — refcount-drop old.
3088        dircache_set(&mut shf.filename, None);
3089        if let Some(fdir) = fdir {
3090            // c:5668
3091            shf.node.flags |= PM_LOADDIR as i32; // c:5670
3092            dircache_set(&mut shf.filename, Some(fdir)); // c:5671
3093        } else {
3094            // c:5672
3095            shf.node.flags &= !(PM_LOADDIR as i32); // c:5674
3096            shf.filename = Some(shf.node.nam.clone()); // c:5675 `ztrdup(shf->node.nam)`
3097        }
3098    }
3099}
3100
3101/// Port of `int commandnotfound(char *arg0, LinkList args)` from
3102/// `Src/exec.c:669`.
3103///
3104/// C body:
3105/// ```c
3106/// Shfunc shf = (Shfunc)
3107///     shfunctab->getnode(shfunctab, "command_not_found_handler");
3108/// if (!shf) {
3109///     lastval = 127;
3110///     return 1;
3111/// }
3112/// pushnode(args, arg0);
3113/// lastval = doshfunc(shf, args, 1);
3114/// return 0;
3115/// ```
3116///
3117/// Look up the user-defined `command_not_found_handler` shfunc and
3118/// invoke it with `arg0` prepended to `args`. Returns 0 if handled,
3119/// 1 if no handler (so caller emits the standard "command not found"
3120/// error). Sets `$?` to 127 in the no-handler path.
3121pub fn commandnotfound(arg0: &str, args: &mut Vec<String>) -> i32 {
3122    // c:669
3123    // c:671-672 — `shf = shfunctab->getnode(shfunctab, "command_not_found_handler");`
3124    let has_handler = shfunctab_lock()
3125        .read()
3126        .map(|t| t.get("command_not_found_handler").is_some())
3127        .unwrap_or(false);
3128    if !has_handler {
3129        // c:674
3130        LASTVAL.store(127, Ordering::Relaxed); // c:675
3131        return 1; // c:676
3132    }
3133    // c:679 — `pushnode(args, arg0);` — prepend arg0 (handler name
3134    // is the first positional arg per C convention).
3135    args.insert(0, arg0.to_string());
3136    args.insert(0, "command_not_found_handler".to_string());
3137    // c:680 — `lastval = doshfunc(shf, args, 1);`. Direct doshfunc
3138    // call mirrors C — body_runner routes through the host body-only
3139    // entry so the function body runs once inside doshfunc's scope.
3140    let shf_clone: Option<shfunc> = shfunctab_lock()
3141        .read()
3142        .ok()
3143        .and_then(|t| t.get("command_not_found_handler").cloned());
3144    if let Some(mut shf) = shf_clone {
3145        let body_args = args.clone();
3146        let body_runner = move || -> i32 {
3147            crate::ported::exec_hooks::run_function_body(
3148                "command_not_found_handler",
3149                &body_args[1..],
3150            )
3151            .unwrap_or(0)
3152        };
3153        let lv = doshfunc(&mut shf, args.clone(), true, body_runner);
3154        LASTVAL.store(lv, Ordering::Relaxed);
3155    }
3156    0 // c:681
3157}
3158
3159/// Port of `char *namedpipe(void)` from `Src/exec.c:5001`.
3160///
3161/// C body (#ifdef HAVE_FIFOS branch):
3162/// ```c
3163/// char *tnam = gettempname(NULL, 1);
3164/// if (!tnam) {
3165///     zerr("failed to create named pipe: %e", errno);
3166///     return NULL;
3167/// }
3168/// if (mkfifo(tnam, 0600) < 0) {
3169///     zerr("failed to create named pipe: %s, %e", tnam, errno);
3170///     return NULL;
3171/// }
3172/// return tnam;
3173/// ```
3174///
3175/// Create a FIFO with a unique name for process substitution. Used by
3176/// `getproc` (`<(cmd)` / `>(cmd)`) on systems without `/dev/fd`.
3177pub fn namedpipe() -> Option<String> {
3178    // c:5001
3179    let tnam = gettempname(None, true); // c:5003
3180    let tnam = match tnam {
3181        Some(t) => t,
3182        None => {
3183            // c:5005
3184            zerr(&format!(
3185                // c:5006
3186                "failed to create named pipe: {}",
3187                std::io::Error::last_os_error()
3188            ));
3189            return None; // c:5007
3190        }
3191    };
3192    // c:5010 — `mkfifo(tnam, 0600)`.
3193    let cstr = match std::ffi::CString::new(tnam.as_str()) {
3194        Ok(c) => c,
3195        Err(_) => return None,
3196    };
3197    if unsafe { libc::mkfifo(cstr.as_ptr(), 0o600) } < 0 {
3198        // c:5010
3199        zerr(&format!(
3200            // c:5014
3201            "failed to create named pipe: {}, {}",
3202            tnam,
3203            std::io::Error::last_os_error()
3204        ));
3205        return None; // c:5015
3206    }
3207    Some(tnam) // c:5017
3208}
3209
3210/// Port of `Eprog parsecmd(char *cmd, char **eptr)` from `Src/exec.c:4878`.
3211///
3212/// C body:
3213/// ```c
3214/// char *str;
3215/// Eprog prog;
3216/// for (str = cmd + 2; *str && *str != Outpar; str++);
3217/// if (!*str || cmd[1] != Inpar) {
3218///     char *errstr = dupstrpfx(cmd, 2);
3219///     untokenize(errstr);
3220///     zerr("unterminated `%s...)'", errstr);
3221///     return NULL;
3222/// }
3223/// *str = '\0';
3224/// if (eptr) *eptr = str+1;
3225/// if (!(prog = parse_string(cmd + 2, 0))) {
3226///     zerr("parse error in process substitution");
3227///     return NULL;
3228/// }
3229/// return prog;
3230/// ```
3231///
3232/// Port of `static LinkList readoutput(int in, int qt, int *readerror)`
3233/// from `Src/exec.c:4805`. Drain a command-substitution pipe fd and
3234/// return the captured output split per `qt`.
3235///
3236/// `qt=1` (quoted-substitution `"$(...)"`): single-element vec with
3237/// the trailing-newline-trimmed buffer (empty buffer → `Nularg` sentinel
3238/// per c:4861).
3239/// `qt=0` (unquoted `$(...)`): split on IFS via `spacesplit`; if
3240/// `GLOBSUBST` is set, each word is `shtokenize`d for downstream globbing.
3241///
3242/// `readerror` is set to the errno on read failure, 0 on clean EOF.
3243pub fn readoutput(in_fd: i32, qt: i32, readerror: &mut i32) -> Vec<String> {
3244    // c:4805
3245    let mut buf: Vec<u8> = Vec::with_capacity(64); // c:4816 (initial bsiz=64)
3246    let mut readret: isize = 0; // c:4818 readret tracks last read return
3247                                // c:4824 dont_queue_signals(); c:4825 child_unblock(); — signal-queue
3248                                // dance keeps SIGCHLD live so the foreground process can be reaped
3249                                // while we drain. zshrs's in-process command-sub runs without the
3250                                // queue (no fork), but the C call surface is preserved for parity.
3251    dont_queue_signals(); // c:4824
3252    child_unblock(); // c:4825
3253    let mut inbuf = [0u8; 64]; // c:4815 inbuf[64]
3254    loop {
3255        // c:4826
3256        // c:4828 — `readret = read(in, inbuf, 64);`
3257        let r = unsafe { libc::read(in_fd, inbuf.as_mut_ptr() as *mut libc::c_void, inbuf.len()) };
3258        readret = r as isize;
3259        if readret <= 0 {
3260            // c:4829
3261            if readret < 0 && std::io::Error::last_os_error().raw_os_error() == Some(libc::EINTR) {
3262                // c:4830 — `if (readret < 0 && errno == EINTR) continue;`
3263                continue;
3264            }
3265            break; // c:4832
3266        }
3267        // c:4835 — `for (bufptr = inbuf; bufptr < inbuf + readret; bufptr++)`
3268        for i in 0..(readret as usize) {
3269            let c = inbuf[i];
3270            if crate::ported::ztype_h::imeta(c) {
3271                // c:4837 — `if (imeta(c)) { *ptr++ = Meta; c ^= 32; cnt++; }`
3272                buf.push(Meta as u8); // c:4838
3273                buf.push(c ^ 32); // c:4839 (Meta-encoded payload)
3274            } else {
3275                buf.push(c); // c:4848 *ptr++ = c
3276            }
3277        }
3278    }
3279    child_block(); // c:4854
3280                   // c:4855 — `if (readerror) *readerror = readret < 0 ? errno : 0;`
3281    *readerror = if readret < 0 {
3282        std::io::Error::last_os_error().raw_os_error().unwrap_or(0)
3283    } else {
3284        0
3285    };
3286    // c:4857 — `close(in);`
3287    unsafe {
3288        libc::close(in_fd);
3289    }
3290    // c:4858-4859 — `while (cnt && ptr[-1] == '\n') ptr--, cnt--;`
3291    while buf.last() == Some(&b'\n') {
3292        buf.pop();
3293    }
3294    // c:4861-4863 — qt branch: empty → Nularg sentinel; else single elem.
3295    let s = String::from_utf8_lossy(&buf).into_owned();
3296    if qt != 0 {
3297        // c:4861
3298        if buf.is_empty() {
3299            return vec![String::from(Nularg)]; // c:4862
3300        }
3301        return vec![s]; // c:4864
3302    }
3303    // c:4866-4871 — `spacesplit` + per-word GLOBSUBST `shtokenize`.
3304    let mut words = crate::ported::utils::spacesplit(&s, false); // c:4867
3305    if isset(crate::ported::zsh_h::GLOBSUBST) {
3306        // c:4870
3307        for w in words.iter_mut() {
3308            crate::ported::glob::shtokenize(w); // c:4870
3309        }
3310    }
3311    words
3312}
3313
3314/// Lex a `<(...)`/`>(...)`/`=(...)` body — the leading 2 chars are
3315/// the marker pair (`Inang+Inpar`, `Outang+Inpar`, `Equals+Inpar`),
3316/// remainder is the command up to the matching `Outpar`. Returns the
3317/// parsed Eprog (and writes the post-`)` cursor through `eptr`).
3318pub fn parsecmd(cmd: &str, eptr: Option<&mut usize>) -> Option<eprog> {
3319    // c:4878
3320    let bytes = cmd.as_bytes();
3321    // c:4883 — `for (str = cmd + 2; *str && *str != Outpar; str++);`
3322    if bytes.len() < 2 {
3323        return None;
3324    }
3325    let mut str_idx: usize = 2;
3326    while str_idx < bytes.len() && (bytes[str_idx] as char) != Outpar {
3327        str_idx += 1;
3328    }
3329    // c:4884 — `if (!*str || cmd[1] != Inpar)`.
3330    if str_idx >= bytes.len() || (bytes[1] as char) != Inpar {
3331        // c:4884
3332        let errstr = if bytes.len() >= 2 {
3333            untokenize(&cmd[..2]) // c:4891-4892
3334        } else {
3335            String::new()
3336        };
3337        zerr(&format!("unterminated `{}...)'", errstr)); // c:4893
3338        return None; // c:4894
3339    }
3340    // c:4896 — `*str = '\0';` — cmd[str_idx] becomes the terminator.
3341    // c:4897-4898 — `if (eptr) *eptr = str + 1;`
3342    if let Some(p) = eptr {
3343        *p = str_idx + 1;
3344    }
3345    // c:4899 — `parse_string(cmd + 2, 0)`.
3346    let body = &cmd[2..str_idx];
3347    let prog = parse_string(body, 0);
3348    if prog.is_none() {
3349        // c:4899
3350        zerr("parse error in process substitution"); // c:4900
3351        return None; // c:4901
3352    }
3353    prog // c:4903
3354}
3355
3356/// `POUNDBANGLIMIT` from `Src/exec.c:500` — max bytes read from the
3357/// front of a script when probing for a `#!` shebang line.
3358pub const POUNDBANGLIMIT: usize = 128;
3359
3360/// Port of `static char **makecline(LinkList list)` from `Src/exec.c:2046`.
3361///
3362/// Builds the argv array from a command's args list. The C version
3363/// allocates with a 4-slot prepad (2 reserved at the front for the
3364/// shebang `argv[-1]/argv[-2]` overwrite trick in zexecve) — Rust
3365/// doesn't need this since we rebuild the Vec on shebang re-exec
3366/// (see zexecve WARNING e).
3367///
3368/// XTRACE side-effect: each arg is printed via quotedzputs to xtrerr
3369/// (stderr), preceded by the PS4 prefix when first command of the line.
3370pub fn makecline(list: &[String]) -> Vec<String> {
3371    // c:2046
3372    if isset(XTRACE) {
3373        // c:2055
3374        if doneps4.load(Ordering::Relaxed) == 0 {
3375            // c:2056
3376            printprompt4(); // c:2057
3377        }
3378        let mut first = true;
3379        let mut err = std::io::stderr().lock();
3380        use std::io::Write;
3381        for s in list.iter() {
3382            // c:2059
3383            if !first {
3384                let _ = err.write_all(b" "); // c:2063
3385            }
3386            first = false;
3387            let _ = err.write_all(quotedzputs(s).as_bytes()); // c:2061
3388        }
3389        let _ = err.write_all(b"\n"); // c:2065
3390        let _ = err.flush(); // c:2066
3391    }
3392    list.to_vec() // c:2071-2072 — argv built; null terminator implicit in CString[] conversion
3393}
3394
3395/// Port of `static void execute(LinkList args, int flags, int defpath)`
3396/// from `Src/exec.c:723`. The canonical "child runs the simple
3397/// external command" path: STTY/ARGV0/BINF_DASH handling, makecline,
3398/// closem(FDT_XTRACE) + child_unblock, slash-path direct exec,
3399/// defpath (`command -p`) search, cmdnamtab + $PATH walk, with
3400/// commandnotfound-handler fallback and the final exit-code escape
3401/// (127 not-found / 126 noperm).
3402///
3403/// =================== WARNING — DIVERGENCE ====================
3404/// (a) `cmdnamtab->getnode(cmdnamtab, arg0)` (c:824) — HASHED
3405///     fast-path wired via cmdnamtab_lock(); jumps direct to
3406///     `cn.cmd` absolute path before the $PATH scan. Unhashed
3407///     cursor-walk (c:830-846) still falls to the full $PATH scan;
3408///     observable behavior matches C when the hash hit is HASHED.
3409/// (b) `commandnotfound(arg0, args)` (c:809, 873) calls into the
3410///     not-yet-ported `doshfunc` for the `command_not_found_handler`
3411///     shell function. Already routes through executor dispatch
3412///     (see exec.rs:2783).
3413/// (c) `_realexit()` (c:810, 874) — bare `std::process::exit`.
3414/// (d) `SHTTY` close on `!FD_CLOEXEC` (c:781-784) — Rust assumes
3415///     FD_CLOEXEC platform default (macOS, Linux).
3416/// (e) `path` Rust accessor uses paramtab lookup for "PATH";
3417///     `defpath` (`command -p`) walks DEFAULT_PATH via
3418///     search_defpath (already ported).
3419/// =============================================================
3420pub fn execute(args: &mut Vec<String>, flags: u32, defpath: i32) {
3421    // c:723
3422    let mut eno: i32 = 0;
3423    let mut ee: i32; // c:729
3424    let mut arg0 = if args.is_empty() {
3425        return;
3426    } else {
3427        args[0].clone()
3428    }; // c:731
3429       // c:733-748 — STTY pre-exec handling.
3430    {
3431        let mut stty = STTYval.lock().unwrap();
3432        if let Some(s) = stty.take() {
3433            // c:738 — STTYval = 0 to break recursion.
3434            if !s.is_empty()
3435                && unsafe { libc::isatty(0) } != 0
3436                && unsafe { libc::tcgetpgrp(0) } == unsafe { libc::getpid() }
3437            {
3438                drop(stty);
3439                let cmd = format!("stty {}", s); // c:739
3440                execstring(&cmd, 1, 0, "stty"); // c:743
3441            }
3442        }
3443    }
3444    // c:752-763 — ARGV0 override.
3445    if let Some(z) = zgetenv("ARGV0") {
3446        args[0] = z.clone(); // c:753
3447        unsafe {
3448            let key = std::ffi::CString::new("ARGV0").unwrap();
3449            libc::unsetenv(key.as_ptr()); // c:760
3450        }
3451        arg0 = args[0].clone();
3452    } else if (flags & BINF_DASH) != 0 {
3453        // c:764 — `BINF_DASH` prepends `-`.
3454        args[0] = format!("-{}", arg0); // c:767-768
3455        arg0 = args[0].clone();
3456    }
3457    let argv = makecline(args); // c:771
3458    let newenvp_owned: Option<Vec<String>> = if (flags & BINF_CLEARENV) != 0 {
3459        Some(Vec::new()) // c:772-773 — blank_env: char ** with only NULL slot
3460    } else {
3461        None
3462    };
3463    let newenvp = newenvp_owned.as_deref();
3464    closem(FDT_XTRACE, 0); // c:779
3465                           // c:780-785 — !FD_CLOEXEC SHTTY close — WARNING (d).
3466    child_unblock(); // c:786
3467    if arg0.len() >= libc::PATH_MAX as usize {
3468        // c:787
3469        zerr(&format!("command too long: {}", arg0)); // c:788
3470        unsafe {
3471            libc::_exit(1);
3472        } // c:789
3473    }
3474    // c:791-801 — slash in arg0 → direct exec.
3475    if let Some(slash_pos) = arg0.find('/') {
3476        let lerrno = zexecve(&arg0, &argv, newenvp); // c:793
3477        let is_dot = arg0.starts_with('.')
3478            && (slash_pos == 1 || (arg0.len() > 2 && &arg0[..2] == ".." && slash_pos == 2));
3479        if slash_pos == 0 || unset(PATHDIRS) || is_dot {
3480            // c:794
3481            zerr(&format!(
3482                "{}: {}",
3483                std::io::Error::from_raw_os_error(lerrno),
3484                arg0
3485            )); // c:797
3486            let code = if lerrno == libc::EACCES || lerrno == libc::ENOEXEC {
3487                126
3488            } else {
3489                127
3490            };
3491            unsafe {
3492                libc::_exit(code);
3493            } // c:798
3494        }
3495    }
3496    if defpath != 0 {
3497        // c:804 — `command -p` default-path search.
3498        let pbuf = match search_defpath(&arg0, libc::PATH_MAX as usize) {
3499            Some(p) => p, // c:808
3500            None => {
3501                if commandnotfound(&arg0, args) == 0 {
3502                    // c:809
3503                    unsafe {
3504                        libc::_exit(LASTVAL.load(Ordering::Relaxed));
3505                    }
3506                }
3507                zerr(&format!("command not found: {}", arg0)); // c:811
3508                unsafe {
3509                    libc::_exit(127);
3510                } // c:812
3511            }
3512        };
3513        ee = zexecve(&pbuf, &argv, newenvp); // c:815
3514        let dir = pbuf.rsplit_once('/').map(|(d, _)| d).unwrap_or("");
3515        if isgooderr(ee, if dir.is_empty() { "/" } else { dir }) {
3516            // c:819
3517            eno = ee;
3518        }
3519    } else {
3520        // c:822 — cmdnamtab fast-path: if `arg0` is a hashed cmdnam,
3521        // jump straight to the absolute path stored in `cn.cmd`,
3522        // skipping the full $PATH scan (one exec attempt vs N).
3523        // c:824 — `if ((cn = cmdnamtab->getnode(cmdnamtab, arg0)))`.
3524        let hashed_path: Option<String> = {
3525            let tab = cmdnamtab_lock().read().ok();
3526            tab.and_then(|t| {
3527                t.get(&arg0).and_then(|cn| {
3528                    if (cn.node.flags & crate::ported::zsh_h::HASHED) != 0 {
3529                        // c:827-828 — `strcpy(nn, cn->u.cmd);`
3530                        cn.cmd.clone()
3531                    } else {
3532                        None
3533                    }
3534                })
3535            })
3536        };
3537        if let Some(nn) = hashed_path {
3538            // c:848 — `ee = zexecve(nn, argv, newenvp);`
3539            ee = zexecve(&nn, &argv, newenvp);
3540            let dir = nn.rsplit_once('/').map(|(d, _)| d).unwrap_or("");
3541            if isgooderr(ee, if dir.is_empty() { "/" } else { dir }) {
3542                eno = ee;
3543            }
3544            // If the hashed entry's exec failed without a "good" error,
3545            // we still need the $PATH fallback — fall through.
3546            if eno == 0 && ee != 0 {
3547                // Reset for the $PATH scan below.
3548                ee = 0;
3549            }
3550        }
3551        // c:822 — normal $PATH scan (always runs; cmdnam fast-path was an
3552        // optimization but C also walks the rest of `path` if the hashed
3553        // exec failed with a non-"good" error).
3554        let path_str = getsparam("PATH").unwrap_or_default();
3555        for pp in path_str.split(':') {
3556            if pp.is_empty() || pp == "." {
3557                // c:856
3558                ee = zexecve(&arg0, &argv, newenvp); // c:857
3559                if isgooderr(ee, pp) {
3560                    eno = ee;
3561                }
3562            } else {
3563                // c:860
3564                let candidate = format!("{}/{}", pp, arg0); // c:861-864
3565                ee = zexecve(&candidate, &argv, newenvp); // c:865
3566                if isgooderr(ee, pp) {
3567                    eno = ee;
3568                }
3569            }
3570        }
3571    }
3572    // c:871-881 — final error reporting.
3573    if eno != 0 {
3574        // c:871
3575        zerr(&format!(
3576            "{}: {}",
3577            std::io::Error::from_raw_os_error(eno),
3578            arg0
3579        )); // c:872
3580    } else if commandnotfound(&arg0, args) == 0 {
3581        // c:873
3582        unsafe {
3583            libc::_exit(LASTVAL.load(Ordering::Relaxed));
3584        } // c:874
3585    } else {
3586        zerr(&format!("command not found: {}", arg0)); // c:876
3587    }
3588    let code = if eno == libc::EACCES || eno == libc::ENOEXEC {
3589        126
3590    } else {
3591        127
3592    }; // c:881
3593    unsafe {
3594        libc::_exit(code);
3595    }
3596}
3597
3598/// Port of `static int zexecve(char *pth, char **argv, char **newenvp)`
3599/// from `Src/exec.c:504`. Wraps `execve(2)` with:
3600///   - `$_` env var stamped to absolute `pth` (c:514-520)
3601///   - winch signal unblock right before the syscall (c:527)
3602///   - on `ENOEXEC` / `ENOENT`: reads the first POUNDBANGLIMIT
3603///     bytes, parses a `#!interp arg` shebang and re-execs the
3604///     interpreter (c:534-628). For `ENOEXEC` with no shebang,
3605///     binary-safety check then falls back to `/bin/sh script` per
3606///     POSIX (c:588-628).
3607///
3608/// Returns `errno` from the failing exec — execve only returns on
3609/// failure, so success means the calling process is already replaced.
3610///
3611/// =================== WARNING — DIVERGENCE ====================
3612/// (a) C uses `static char buf[PATH_MAX*2+1]` for the `_=...` env
3613///     string; Rust uses a stack `String` (consumed by `zputenv`).
3614/// (b) `closedumps()` for `!FD_CLOEXEC` (c:521-523) called
3615///     unconditionally as a no-op when FD_CLOEXEC is platform default.
3616/// (c) `unmetafy(pth, NULL)` / round-trip `metafy` at c:510-513,
3617///     c:639-642 — handled implicitly via &str ↔ CString.
3618/// (d) `metafy(execvebuf+2, -1, META_STATIC)` (c:551, 575) — we
3619///     drop the metafy and pass byte ranges to zerr directly.
3620/// (e) `argv[-1]` / `argv[-2]` shebang interpreter slot-overwriting
3621///     (C overwrites BEFORE `argv[0]`) — Rust rebuilds a fresh
3622///     `Vec<String>` with interp + optional arg + original argv tail
3623///     since Vec doesn't expose negative indexing.
3624/// (f) `environ` is FFI-loaded only when `newenvp` is None.
3625/// =============================================================
3626pub fn zexecve(pth: &str, argv: &[String], newenvp: Option<&[String]>) -> i32 {
3627    // c:504
3628    use std::ffi::CString;
3629    // c:514-520 — `_=pth` env stamping.
3630    let pth_abs = if pth.starts_with('/') {
3631        // c:516
3632        pth.to_string() // c:517
3633    } else {
3634        // c:518
3635        format!("{}/{}", getsparam("PWD").unwrap_or_default(), pth) // c:519
3636    };
3637    zputenv(&format!("_={}", pth_abs)); // c:520
3638    closedumps(); // c:522
3639    winch_unblock(); // c:527
3640    let cpth = match CString::new(pth) {
3641        Ok(c) => c,
3642        Err(_) => return libc::ENOENT,
3643    };
3644    let cargs: Vec<CString> = argv
3645        .iter()
3646        .filter_map(|a| CString::new(a.as_str()).ok())
3647        .collect();
3648    let mut argv_ptrs: Vec<*const libc::c_char> = cargs.iter().map(|c| c.as_ptr()).collect();
3649    argv_ptrs.push(std::ptr::null());
3650    let env_holder: Vec<CString>;
3651    let env_ptrs: Vec<*const libc::c_char>;
3652    let envp: *const *const libc::c_char = match newenvp {
3653        Some(env) => {
3654            env_holder = env
3655                .iter()
3656                .filter_map(|e| CString::new(e.as_str()).ok())
3657                .collect();
3658            env_ptrs = {
3659                let mut v: Vec<*const libc::c_char> =
3660                    env_holder.iter().map(|c| c.as_ptr()).collect();
3661                v.push(std::ptr::null());
3662                v
3663            };
3664            env_ptrs.as_ptr()
3665        }
3666        None => unsafe {
3667            extern "C" {
3668                static environ: *const *const libc::c_char;
3669            }
3670            environ
3671        },
3672    };
3673    unsafe {
3674        libc::execve(cpth.as_ptr(), argv_ptrs.as_ptr(), envp); // c:528
3675    }
3676    let eno = std::io::Error::last_os_error()
3677        .raw_os_error()
3678        .unwrap_or(libc::ENOEXEC); // c:534
3679    if eno == libc::ENOEXEC || eno == libc::ENOENT {
3680        // c:534
3681        let fd = unsafe { libc::open(cpth.as_ptr(), libc::O_RDONLY | libc::O_NOCTTY) }; // c:538
3682        if fd < 0 {
3683            return std::io::Error::last_os_error()
3684                .raw_os_error()
3685                .unwrap_or(libc::ENOENT); // c:634
3686        }
3687        let mut buf = vec![0u8; POUNDBANGLIMIT + 1]; // c:541
3688        let ct = unsafe {
3689            libc::read(
3690                fd,
3691                buf.as_mut_ptr() as *mut libc::c_void,
3692                POUNDBANGLIMIT as libc::size_t,
3693            )
3694        }; // c:542
3695        unsafe {
3696            libc::close(fd);
3697        } // c:543
3698        if ct >= 0 {
3699            // c:544
3700            let ct = ct as usize;
3701            if ct >= 2 && buf[0] == b'#' && buf[1] == b'!' {
3702                // c:545
3703                let mut t0 = 0;
3704                while t0 < ct && buf[t0] != b'\n' {
3705                    t0 += 1;
3706                } // c:546-548
3707                if t0 == ct {
3708                    // c:549
3709                    zerr(&format!(
3710                        // c:550
3711                        "{}: bad interpreter: {}: {}",
3712                        pth,
3713                        String::from_utf8_lossy(&buf[2..t0.min(ct)]),
3714                        std::io::Error::from_raw_os_error(eno)
3715                    ));
3716                } else {
3717                    // c:552
3718                    while t0 > 0 && (buf[t0] == b' ' || buf[t0] == b'\t' || buf[t0] == b'\n') {
3719                        buf[t0] = 0;
3720                        t0 -= 1;
3721                    } // c:553-554
3722                    let mut ptr_lo: usize = 2;
3723                    while ptr_lo < buf.len() && buf[ptr_lo] == b' ' {
3724                        ptr_lo += 1;
3725                    } // c:555
3726                    let ptr2_lo = ptr_lo;
3727                    let mut ptr_hi = ptr2_lo;
3728                    while ptr_hi < buf.len() && buf[ptr_hi] != 0 && buf[ptr_hi] != b' ' {
3729                        ptr_hi += 1;
3730                    } // c:556
3731                    let interp_str = String::from_utf8_lossy(&buf[ptr2_lo..ptr_hi]).into_owned();
3732                    if eno == libc::ENOENT {
3733                        // c:557 — pathprog rewrite path.
3734                        let pprog = if !interp_str.starts_with('/') {
3735                            // c:561
3736                            pathprog(&interp_str).map(|p| p.display().to_string())
3737                        } else {
3738                            None
3739                        };
3740                        if let Some(pprog) = pprog {
3741                            // c:562
3742                            let mut argv_new: Vec<String> = Vec::with_capacity(argv.len() + 2);
3743                            argv_new.push(interp_str.clone()); // c:564
3744                            if ptr_hi >= buf.len() || buf[ptr_hi] == 0 {
3745                                argv_new.push(pth.to_string());
3746                            } else {
3747                                // c:567
3748                                let mut rest_lo = ptr_hi + 1;
3749                                while rest_lo < buf.len() && buf[rest_lo] == b' ' {
3750                                    rest_lo += 1;
3751                                }
3752                                let mut rest_hi = rest_lo;
3753                                while rest_hi < buf.len() && buf[rest_hi] != 0 {
3754                                    rest_hi += 1;
3755                                }
3756                                let arg_str =
3757                                    String::from_utf8_lossy(&buf[rest_lo..rest_hi]).into_owned();
3758                                argv_new.push(arg_str);
3759                                argv_new.push(pth.to_string());
3760                            }
3761                            for orig in argv.iter().skip(1) {
3762                                argv_new.push(orig.clone());
3763                            }
3764                            winch_unblock(); // c:565/c:570
3765                            return zexecve(&pprog, &argv_new, newenvp); // c:566/c:571
3766                        }
3767                        zerr(&format!(
3768                            // c:574
3769                            "{}: bad interpreter: {}: {}",
3770                            pth,
3771                            interp_str,
3772                            std::io::Error::from_raw_os_error(eno)
3773                        ));
3774                    } else if ptr_hi < buf.len() && buf[ptr_hi] != 0 {
3775                        // c:576
3776                        let mut rest_lo = ptr_hi + 1;
3777                        while rest_lo < buf.len() && buf[rest_lo] == b' ' {
3778                            rest_lo += 1;
3779                        }
3780                        let mut rest_hi = rest_lo;
3781                        while rest_hi < buf.len() && buf[rest_hi] != 0 {
3782                            rest_hi += 1;
3783                        }
3784                        let arg_str = String::from_utf8_lossy(&buf[rest_lo..rest_hi]).into_owned();
3785                        let mut argv_new: Vec<String> =
3786                            vec![interp_str.clone(), arg_str, pth.to_string()];
3787                        for orig in argv.iter().skip(1) {
3788                            argv_new.push(orig.clone());
3789                        }
3790                        winch_unblock(); // c:580
3791                        return zexecve(&interp_str, &argv_new, newenvp); // c:581
3792                    } else {
3793                        // c:582
3794                        let mut argv_new: Vec<String> = vec![interp_str.clone(), pth.to_string()];
3795                        for orig in argv.iter().skip(1) {
3796                            argv_new.push(orig.clone());
3797                        }
3798                        winch_unblock(); // c:584
3799                        return zexecve(&interp_str, &argv_new, newenvp); // c:585
3800                    }
3801                }
3802            } else if eno == libc::ENOEXEC {
3803                // c:588 — binary-safety + /bin/sh fallback.
3804                let nul_pos = buf[..ct].iter().position(|&b| b == 0); // c:597
3805                let isbinary = match nul_pos {
3806                    None => false, // c:598
3807                    Some(npos) => {
3808                        let mut has_letter = false;
3809                        let mut binary = true;
3810                        for &b in &buf[..npos] {
3811                            // c:602-609
3812                            if (b as char).is_ascii_lowercase() || b == b'$' || b == b'`' {
3813                                has_letter = true;
3814                            }
3815                            if has_letter && b == b'\n' {
3816                                binary = false; // c:606
3817                                break;
3818                            }
3819                        }
3820                        binary
3821                    }
3822                };
3823                if !isbinary {
3824                    // c:611
3825                    let mut argv_new: Vec<String> = Vec::with_capacity(argv.len() + 2);
3826                    argv_new.push("sh".to_string()); // c:625
3827                    if !argv.is_empty() && (argv[0].starts_with('-') || argv[0].starts_with('+')) {
3828                        argv_new.push("-".to_string()); // c:623
3829                    }
3830                    for orig in argv.iter() {
3831                        argv_new.push(orig.clone());
3832                    }
3833                    winch_unblock(); // c:626
3834                    return zexecve("/bin/sh", &argv_new, newenvp); // c:627
3835                }
3836            }
3837        }
3838    }
3839    eno // c:643
3840}
3841
3842/// Port of `char *getoutputfile(char *cmd, char **eptr)` from
3843/// `Src/exec.c:4910` — `=(cmd)` process substitution.
3844///
3845/// Substitutes the cmd's stdout into a temp file, returns the
3846/// filename. Optimised path: `=(<<<heredoc-str)` writes the
3847/// heredoc body directly without a fork.
3848///
3849/// (a) `addfilelist(nam, 0)` (c:4960) wired via `JOBTAB[thisjob]`
3850///     so the temp file gets cleaned at job exit.
3851/// (b) `waitforpid` Rust takes 1 arg `pid`, C takes `(pid, full)`.
3852///     Behavior matches the `full=0` case anyway.
3853/// (c) `entersubsh` is ported at exec.rs:3934 — wire it here when
3854///     re-routing the fork path away from setsid-only fallback.
3855/// (d) `execode` is now ported (exec.rs:6047) — the body still
3856///     re-feeds through fusevm for cache coherence with execstring.
3857/// (e) `_realexit` flushes stdio + jobs + history. We use bare
3858///     `std::process::exit(0)` for now.
3859/// (f) TMPSUFFIX link()-rename block (c:4951-4958) deferred; rare
3860///     `setopt suffix_alias` interaction with =(…).
3861pub fn getoutputfile(cmd: &str, eptr: Option<&mut usize>) -> Option<String> {
3862    // c:4910
3863    let bytes = cmd.as_bytes();
3864    let _ = bytes;
3865    // c:4918 — `if (thisjob == -1)` — guard removed (thisjob model differs).
3866    let mut ends_at: usize = 0;
3867    let prog = parsecmd(cmd, Some(&mut ends_at))?; // c:4922
3868    if let Some(p) = eptr {
3869        *p = ends_at;
3870    }
3871    let mut nam = gettempname(None, true)?; // c:4924
3872                                            // c:4927 — `simple_redir_name` opt for `=(<<<str)`.
3873    let mut s: Option<String> = simple_redir_name(&prog, REDIR_HERESTR).map(|raw| {
3874        // c:4933
3875        let mut sub = singsub(&raw); // c:4933
3876        if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
3877            // c:4934
3878            String::new() // c:4935 — sentinel; checked below
3879        } else {
3880            sub = untokenize(&sub); // c:4937
3881            dyncat(&sub, "\n") // c:4938
3882        }
3883    });
3884    if let Some(ref sv) = s {
3885        if sv.is_empty() {
3886            s = None;
3887        }
3888    }
3889    if s.is_none() {
3890        // c:4942
3891        child_block(); // c:4943
3892    }
3893    // c:4945 — `open(nam, O_WRONLY|O_CREAT|O_EXCL|O_NOCTTY, 0600)`.
3894    let c_nam = match std::ffi::CString::new(nam.clone()) {
3895        Ok(c) => c,
3896        Err(_) => {
3897            if s.is_none() {
3898                child_unblock();
3899            }
3900            return None;
3901        }
3902    };
3903    let fd = unsafe {
3904        libc::open(
3905            c_nam.as_ptr(),
3906            libc::O_WRONLY | libc::O_CREAT | libc::O_EXCL | libc::O_NOCTTY,
3907            0o600 as libc::c_uint,
3908        )
3909    };
3910    if fd < 0 {
3911        // c:4945
3912        zerr(&format!(
3913            "process substitution failed: {}",
3914            std::io::Error::last_os_error()
3915        )); // c:4946
3916        if s.is_none() {
3917            child_unblock(); // c:4948
3918        }
3919        return None; // c:4949
3920    }
3921    // c:4951-4958 — TMPSUFFIX link block (see WARNING f).
3922    // c:4960 — `addfilelist(nam, 0);` — register temp file in current
3923    // job's filelist so it's unlinked at job exit (not relying on the
3924    // OS temp-reaper).
3925    if let Some(jt) = JOBTAB.get() {
3926        let mut guard = jt.lock().unwrap();
3927        let tj = THISJOB.get().map(|m| *m.lock().unwrap()).unwrap_or(-1);
3928        if tj >= 0 {
3929            if let Some(j) = guard.get_mut(tj as usize) {
3930                crate::ported::jobs::addfilelist(j, Some(&nam), 0);
3931            }
3932        }
3933    }
3934    if let Some(sv) = s {
3935        // c:4962 — optimised here-string write path.
3936        let mut buf: Vec<u8> = sv.into_bytes();
3937        let _len = unmetafy(&mut buf); // c:4965
3938        let _ = write_loop(fd, &buf); // c:4966
3939        unsafe {
3940            libc::close(fd);
3941        } // c:4967
3942        return Some(nam); // c:4968
3943    }
3944    // c:4971 — `cmdoutpid = pid = zfork(NULL)`.
3945    let pid = zfork(None);
3946    cmdoutpid.store(pid, Ordering::Relaxed);
3947    if pid == -1 {
3948        // c:4972
3949        unsafe {
3950            libc::close(fd);
3951        } // c:4973
3952        child_unblock(); // c:4974
3953        return Some(nam); // c:4975
3954    } else if pid != 0 {
3955        // c:4976 — parent.
3956        unsafe {
3957            libc::close(fd);
3958        } // c:4977
3959        let _ = waitforpid(pid); // c:4978
3960        cmdoutval.store(0, Ordering::Relaxed); // c:4979
3961        return Some(nam); // c:4980
3962    }
3963    // c:4983 — child.
3964    closem(FDT_UNUSED, 0); // c:4984
3965    let _ = redup(fd, 1); // c:4985
3966    entersubsh(esub::PGRP | esub::NOMONITOR, None); // c:4986
3967    cmdpush(CS_CMDSUBST as u8); // c:4987
3968                                // c:4988 — execode — WARNING (d).
3969    let body_end = if ends_at > 0 { ends_at - 1 } else { 2 };
3970    let body = if body_end > 2 && body_end <= cmd.len() {
3971        &cmd[2..body_end]
3972    } else {
3973        ""
3974    };
3975    let _ = crate::ported::exec_hooks::execute_script_zsh_pipeline(body);
3976    cmdpop(); // c:4989
3977    unsafe {
3978        libc::close(1);
3979    } // c:4990
3980      // _realexit — WARNING (e)
3981    std::process::exit(0); // c:4991
3982    #[allow(unreachable_code)]
3983    {
3984        // c:4992-4993 — `zerr("exit returned in child!!"); kill(getpid(), SIGKILL);`
3985        let _ = &mut nam;
3986        unsafe {
3987            libc::kill(libc::getpid(), libc::SIGKILL);
3988        }
3989        None
3990    }
3991}
3992
3993/// Port of `char *getproc(char *cmd, char **eptr)` from
3994/// `Src/exec.c:5025` — `<(cmd)` / `>(cmd)` process substitution
3995/// via `/dev/fd/N` (PATH_DEV_FD branch; modern Linux/macOS).
3996///
3997/// (a) PATH_DEV_FD branch only — the FIFO fallback (`!PATH_DEV_FD`
3998///     path c:5037-5064) is omitted; modern Linux/macOS both
3999///     provide /dev/fd. `namedpipe()` is ported (exec.rs:2701) but
4000///     unused here.
4001/// (b) `addproc` is 7-arg; procsubst pid recorded via aux=true on
4002///     the current job (c:5141-5142).
4003/// (c) `addfilelist(NULL, fd)` wired via `JOBTAB[thisjob]` at
4004///     c:5087.
4005/// (d) `entersubsh` is ported at exec.rs:3934 — wired below at
4006///     c:5063 (`entersubsh(ESUB_ASYNC|ESUB_PGRP, NULL)`).
4007/// (e) `execode` is ported at exec.rs:6047. Body still re-feeds
4008///     through fusevm for cache coherence.
4009/// (f) `_realexit` flushes stdio + jobs + history. We use bare
4010///     `std::process::exit(LASTVAL)` for now.
4011/// (g) `fdtable[fd] = FDT_PROC_SUBST` (c:5086) — set via fdtable_set.
4012pub fn getproc(cmd: &str, eptr: Option<&mut usize>) -> Option<String> {
4013    // c:5025
4014    let bytes = cmd.as_bytes();
4015    let out: i32 = if !bytes.is_empty() && (bytes[0] as char) == Inang {
4016        1 // c:5032 — `<(...)` writer-side child
4017    } else {
4018        0
4019    };
4020    // c:5068-5071 — `if (thisjob == -1) { zerr(...); return NULL; }` —
4021    // proc subst needs a host job to attach the child to.
4022    let tj_check = THISJOB.get().map(|m| *m.lock().unwrap()).unwrap_or(-1);
4023    if tj_check == -1 {
4024        zerr(&format!("process substitution {} cannot be used here", cmd)); // c:5069
4025        return None; // c:5070
4026    }
4027    // c:5072 — PATH_DEV_FD path: allocate buffer for the /dev/fd/N string.
4028    let mut ends_at: usize = 0;
4029    let _prog = parsecmd(cmd, Some(&mut ends_at))?; // c:5073
4030    if let Some(p) = eptr {
4031        *p = ends_at;
4032    }
4033    let mut pipes: [i32; 2] = [-1; 2];
4034    if mpipe(&mut pipes) < 0 {
4035        // c:5075
4036        return None;
4037    }
4038    let mut bgtime: ZshTimespec = libc::timespec {
4039        tv_sec: 0,
4040        tv_nsec: 0,
4041    };
4042    let pid = zfork(Some(&mut bgtime)); // c:5077
4043    if pid != 0 {
4044        // c:5077 — parent path.
4045        let pnam = format!("/dev/fd/{}", pipes[(1 - out) as usize]); // c:5078
4046        let _ = zclose(pipes[out as usize]); // c:5079
4047        if pid == -1 {
4048            // c:5080
4049            let _ = zclose(pipes[(1 - out) as usize]); // c:5082
4050            return None; // c:5083
4051        }
4052        let fd = pipes[(1 - out) as usize]; // c:5085
4053        fdtable_set(fd, FDT_PROC_SUBST); // c:5086
4054                                         // c:5087 — `addfilelist(NULL, fd);` — register the proc-subst
4055                                         // pipe fd in the current job's filelist so it's closed at job exit.
4056        if let Some(jt) = JOBTAB.get() {
4057            let mut guard = jt.lock().unwrap();
4058            let tj = THISJOB.get().map(|m| *m.lock().unwrap()).unwrap_or(-1);
4059            if tj >= 0 {
4060                if let Some(j) = guard.get_mut(tj as usize) {
4061                    crate::ported::jobs::addfilelist(j, None, fd);
4062                }
4063            }
4064        }
4065        // c:5088-5091 — `if (!out) addproc(pid, NULL, 1, &bgtime, -1, -1);` —
4066        // record the proc-subst writer-side child in the job's
4067        // auxprocs (aux=true). For `<(cmd)` (out==1 = reader-side
4068        // child), C omits the addproc — symmetric here.
4069        if out == 0 {
4070            if let Some(jt) = JOBTAB.get() {
4071                let mut guard = jt.lock().unwrap();
4072                let tj = THISJOB.get().map(|m| *m.lock().unwrap()).unwrap_or(-1);
4073                if tj >= 0 {
4074                    if let Some(j) = guard.get_mut(tj as usize) {
4075                        crate::ported::jobs::addproc(
4076                            j,
4077                            pid,
4078                            "",
4079                            true,
4080                            Some(std::time::Instant::now()),
4081                            -1,
4082                            -1,
4083                        );
4084                    }
4085                }
4086            }
4087        }
4088        procsubstpid.store(pid, Ordering::Relaxed); // c:5092
4089        return Some(pnam); // c:5093
4090    }
4091    // c:5095 — child.
4092    entersubsh(esub::ASYNC | esub::PGRP, None); // c:5095
4093    let _ = redup(pipes[out as usize], out); // c:5096
4094    closem(FDT_UNUSED, 0); // c:5097
4095    cmdpush(CS_CMDSUBST as u8); // c:5100
4096    let body_end = if ends_at > 0 { ends_at - 1 } else { 2 };
4097    let body = if body_end > 2 && body_end <= cmd.len() {
4098        &cmd[2..body_end]
4099    } else {
4100        ""
4101    };
4102    let _ = crate::ported::exec_hooks::execute_script_zsh_pipeline(body);
4103    cmdpop(); // c:5102
4104    let _ = zclose(out); // c:5103
4105    std::process::exit(LASTVAL.load(Ordering::Relaxed)); // c:5104
4106}
4107
4108/// Port of `enum { ESUB_ASYNC, ESUB_PGRP, ... };` from `Src/exec.c:1056`.
4109/// Flag bits for `entersubsh(int flags, struct entersubsh_ret *retp)`.
4110pub mod esub {
4111    // c:1056
4112    /// `ASYNC` constant.
4113    pub const ASYNC: i32 = 0x01; // c:1058
4114    /// `PGRP` constant.
4115    pub const PGRP: i32 = 0x02; // c:1063
4116    /// `KEEPTRAP` constant.
4117    pub const KEEPTRAP: i32 = 0x04; // c:1065
4118    /// `FAKE` constant.
4119    pub const FAKE: i32 = 0x08; // c:1067
4120    /// `REVERTPGRP` constant.
4121    pub const REVERTPGRP: i32 = 0x10; // c:1069
4122    /// `NOMONITOR` constant.
4123    pub const NOMONITOR: i32 = 0x20; // c:1071
4124    /// `JOB_CONTROL` constant.
4125    pub const JOB_CONTROL: i32 = 0x40; // c:1073
4126}
4127
4128/// Port of `struct entersubsh_ret` from `Src/exec.c` (forward decl).
4129/// Out-arg used by `entersubsh()` to hand back the group-leader pid
4130/// and the list-pipe job index the parent should track. Only filled
4131/// in for `ESUB_PGRP` + non-async forks (synchronous pipeline child
4132/// groups).
4133#[allow(non_camel_case_types)]
4134#[derive(Default)]
4135pub struct entersubsh_ret {
4136    pub gleader: i32,       // c:1122
4137    pub list_pipe_job: i32, // c:1123
4138}
4139
4140/// Port of `static void entersubsh(int flags, struct entersubsh_ret *retp)`
4141/// from `Src/exec.c:1083`. Called by every child fork to switch the
4142/// process into subshell mode: traps reset, monitor disabled, signals
4143/// re-defaulted, pgrp + tty handed off, saved fds closed, jobtab
4144/// cleared, ZSH_SUBSHELL bumped, forklevel = locallevel.
4145///
4146/// (a) `jobtab[list_pipe_job]` / `jobtab[thisjob]` pgrp ops (c:1110-
4147///     1151) are now ported via `JOBTAB[thisjob]`.gleader access; the
4148///     ESUB_PGRP+sync path establishes pipeline group-leadership
4149///     (list_pipe_job inherit or thisjob-as-leader), filling
4150///     entersubsh_ret with the chosen gleader + list_pipe_job index.
4151/// (b) `clearjobtab(monitor)` (c:1219) — Rust signature is
4152///     `clearjobtab(&mut JobTable, monitor)`; we get the global table
4153///     via a TABLE handle similar to other jobs.rs entries.
4154/// (c) `attachtty(...)` (c:1119, 1144) — wired via libc::tcsetpgrp(2, gleader).
4155/// (d) `release_pgrp()` called for ESUB_REVERTPGRP when `getpid() ==
4156///     mypgrp` — direct C parity (jobs.rs:3406 provides the call).
4157/// (e) `opts[USEZLE] = 0; zleactive = 0` — Rust opts table lookup
4158///     uses `opts_set_off(USEZLE)`; zleactive is the atomic in
4159///     builtins/sched.rs.
4160/// =============================================================
4161pub fn entersubsh(flags: i32, retp: Option<&mut entersubsh_ret>) {
4162    // c:1083
4163    let monitor: i32;
4164    let job_control_ok: i32;
4165    // c:1088-1092 — reset traps unless KEEPTRAP.
4166    if (flags & esub::KEEPTRAP) == 0 {
4167        // c:1088
4168        for sig in 0..=SIGCOUNT {
4169            // c:1089
4170            let st = {
4171                let guard = sigtrapped.lock().unwrap();
4172                guard.get(sig as usize).copied().unwrap_or(0)
4173            };
4174            let func_set = (st & ZSIG_FUNC) != 0; // c:1090
4175            let posix_ignored = isset(POSIXTRAPS) && ((st & ZSIG_IGNORED) != 0); // c:1091
4176            if !func_set && !posix_ignored {
4177                unsettrap(sig); // c:1092
4178            }
4179        }
4180    }
4181    monitor = if isset(MONITOR) { 1 } else { 0 }; // c:1093
4182    job_control_ok = if monitor != 0 && (flags & esub::JOB_CONTROL) != 0 && isset(POSIXJOBS) {
4183        // c:1094
4184        1
4185    } else {
4186        0
4187    };
4188    EXIT_VAL.store(0, Ordering::Relaxed); // c:1095
4189    if (flags & esub::NOMONITOR) != 0 {
4190        // c:1096
4191        dosetopt(MONITOR, 0, 0); // c:1097
4192    }
4193    if !isset(MONITOR) {
4194        // c:1098
4195        if (flags & esub::ASYNC) != 0 {
4196            // c:1099
4197            let _ = settrap(libc::SIGINT, None, 0); // c:1100
4198            let _ = settrap(libc::SIGQUIT, None, 0); // c:1101
4199            if unsafe { libc::isatty(0) } != 0 {
4200                // c:1102
4201                unsafe {
4202                    libc::close(0);
4203                } // c:1103
4204                let devnull = std::ffi::CString::new("/dev/null").unwrap();
4205                if unsafe { libc::open(devnull.as_ptr(), libc::O_RDWR | libc::O_NOCTTY) } != 0 {
4206                    // c:1104
4207                    zerr(&format!(
4208                        // c:1105
4209                        "can't open /dev/null: {}",
4210                        std::io::Error::last_os_error()
4211                    ));
4212                    unsafe {
4213                        libc::_exit(1);
4214                    } // c:1106
4215                }
4216            }
4217        }
4218    } else if (flags & esub::PGRP) != 0 {
4219        // c:1110 — `else if (thisjob != -1 && (flags & ESUB_PGRP))`.
4220        let thisjob = THISJOB.get().map(|m| *m.lock().unwrap()).unwrap_or(-1);
4221        if thisjob != -1 {
4222            let lpj = list_pipe_job.load(Ordering::Relaxed);
4223            let lp = list_pipe.load(Ordering::Relaxed);
4224            let lpc = list_pipe_child.load(Ordering::Relaxed);
4225            if let Some(jt) = JOBTAB.get() {
4226                let mut guard = jt.lock().unwrap();
4227                let lpj_gleader = guard.get(lpj as usize).map(|j| j.gleader).unwrap_or(0);
4228                if lpj_gleader != 0 && (lp != 0 || lpc != 0) {
4229                    // c:1111-1124 — inherit list_pipe_job's group leader.
4230                    let pgid = if unsafe { libc::setpgid(0, lpj_gleader) } == -1
4231                        || (unsafe { libc::killpg(lpj_gleader, 0) } == -1
4232                            && std::io::Error::last_os_error().raw_os_error() == Some(libc::ESRCH))
4233                    {
4234                        // c:1115-1117 — primary group leader gone; this child becomes leader.
4235                        let new_gl = if lpc != 0 {
4236                            mypgrp.load(Ordering::Relaxed)
4237                        } else {
4238                            unsafe { libc::getpid() }
4239                        };
4240                        if let Some(j) = guard.get_mut(lpj as usize) {
4241                            j.gleader = new_gl;
4242                        }
4243                        if let Some(j) = guard.get_mut(thisjob as usize) {
4244                            j.gleader = new_gl;
4245                        }
4246                        unsafe { libc::setpgid(0, new_gl) };
4247                        if (flags & esub::ASYNC) == 0 {
4248                            unsafe { libc::tcsetpgrp(2, new_gl) }; // c:1119 attachtty
4249                        }
4250                        new_gl
4251                    } else {
4252                        lpj_gleader
4253                    };
4254                    if let Some(r) = retp {
4255                        if (flags & esub::ASYNC) == 0 {
4256                            r.gleader = pgid; // c:1122
4257                            r.list_pipe_job = lpj; // c:1123
4258                        }
4259                    }
4260                } else {
4261                    // c:1126-1151 — standard group-leader-takeover path.
4262                    let thisjob_gleader =
4263                        guard.get(thisjob as usize).map(|j| j.gleader).unwrap_or(0);
4264                    if thisjob_gleader == 0 || unsafe { libc::setpgid(0, thisjob_gleader) } == -1 {
4265                        let new_gl = unsafe { libc::getpid() };
4266                        if let Some(j) = guard.get_mut(thisjob as usize) {
4267                            j.gleader = new_gl; // c:1138
4268                        }
4269                        if lpj != thisjob {
4270                            let lpj_was_unset = guard
4271                                .get(lpj as usize)
4272                                .map(|j| j.gleader == 0)
4273                                .unwrap_or(true);
4274                            if lpj_was_unset {
4275                                if let Some(j) = guard.get_mut(lpj as usize) {
4276                                    j.gleader = new_gl; // c:1140-1141
4277                                }
4278                            }
4279                        }
4280                        unsafe { libc::setpgid(0, new_gl) }; // c:1142
4281                        if (flags & esub::ASYNC) == 0 {
4282                            unsafe { libc::tcsetpgrp(2, new_gl) }; // c:1144 attachtty
4283                            if let Some(r) = retp {
4284                                r.gleader = new_gl; // c:1146
4285                                if lpj != thisjob {
4286                                    r.list_pipe_job = lpj; // c:1148
4287                                }
4288                            }
4289                        }
4290                    }
4291                }
4292            }
4293        } else {
4294            // No real job slot; basic setpgid fallback.
4295            unsafe { libc::setpgid(0, 0) };
4296        }
4297    }
4298    if (flags & esub::FAKE) == 0 {
4299        // c:1153
4300        subsh.store(1, Ordering::Relaxed); // c:1154
4301    }
4302    // c:1161 — `zsh_subshell++;` regardless of FAKE.
4303    zsh_subshell.fetch_add(1, Ordering::Relaxed);
4304    // c:1162 — `if ((flags & ESUB_REVERTPGRP) && getpid() == mypgrp)`.
4305    if (flags & esub::REVERTPGRP) != 0
4306        && unsafe { libc::getpid() } == mypgrp.load(Ordering::Relaxed)
4307    {
4308        release_pgrp(); // c:1163
4309    }
4310    *shout.lock().unwrap() = 0; // c:1164 — shout = NULL
4311    if (flags & esub::NOMONITOR) != 0 {
4312        // c:1165
4313        signal_ignore(libc::SIGTTOU); // c:1171
4314        signal_ignore(libc::SIGTTIN); // c:1172
4315        signal_ignore(libc::SIGTSTP); // c:1173
4316    } else if job_control_ok == 0 {
4317        // c:1174
4318        signal_default(libc::SIGTTOU); // c:1181
4319        signal_default(libc::SIGTTIN); // c:1182
4320        signal_default(libc::SIGTSTP); // c:1183
4321    }
4322    let interact = isset(INTERACTIVE); // c:1185 — Rust uses INTERACTIVE option as proxy
4323    if interact {
4324        signal_default(libc::SIGTERM); // c:1186
4325        let int_st = sigtrapped
4326            .lock()
4327            .unwrap()
4328            .get(libc::SIGINT as usize)
4329            .copied()
4330            .unwrap_or(0);
4331        if (int_st & ZSIG_IGNORED) == 0 {
4332            // c:1187
4333            signal_default(libc::SIGINT); // c:1188
4334        }
4335        let pipe_st = sigtrapped
4336            .lock()
4337            .unwrap()
4338            .get(libc::SIGPIPE as usize)
4339            .copied()
4340            .unwrap_or(0);
4341        if pipe_st == 0 {
4342            // c:1189
4343            signal_default(libc::SIGPIPE); // c:1190
4344        }
4345    }
4346    let quit_st = sigtrapped
4347        .lock()
4348        .unwrap()
4349        .get(libc::SIGQUIT as usize)
4350        .copied()
4351        .unwrap_or(0);
4352    if (quit_st & ZSIG_IGNORED) == 0 {
4353        // c:1192
4354        signal_default(libc::SIGQUIT); // c:1193
4355    }
4356    // c:1202-1205 — unblock any trapped signals while in `intrap`.
4357    if intrap.load(Ordering::Relaxed) != 0 {
4358        // c:1202
4359        for sig in 1..=SIGCOUNT {
4360            let st = sigtrapped
4361                .lock()
4362                .unwrap()
4363                .get(sig as usize)
4364                .copied()
4365                .unwrap_or(0);
4366            if st != 0 && st != ZSIG_IGNORED {
4367                // c:1204
4368                let m = signal_mask(sig);
4369                let _ = signal_unblock(&m); // c:1205
4370            }
4371        }
4372    }
4373    if job_control_ok == 0 {
4374        // c:1206
4375        dosetopt(MONITOR, 0, 0); // c:1207
4376    }
4377    dosetopt(USEZLE, 0, 0); // c:1208
4378    zleactive.store(0, Ordering::Relaxed); // c:1209
4379                                           // c:1214-1217 — close saved fds.
4380    let max = MAX_ZSH_FD.load(Ordering::Relaxed);
4381    for i in 10..=max {
4382        if (fdtable_get(i) & FDT_SAVED_MASK) != 0 {
4383            // c:1215
4384            let _ = zclose(i); // c:1216
4385        }
4386    }
4387    // c:1218-1219 — `clearjobtab(monitor);` — calls the canonical port
4388    // at jobs.rs:1695 which handles ALL the C body including the
4389    // oldjobtab snapshot path (c:1799-1817) under POSIXJOBS guard.
4390    let mut dummy_table = crate::exec_jobs::JobTable::new();
4391    crate::ported::jobs::clearjobtab(&mut dummy_table, monitor);
4392    let _ = get_usage(); // c:1220
4393    FORKLEVEL.store(
4394        // c:1221 — `forklevel = locallevel;`
4395        locallevel.load(Ordering::Relaxed),
4396        Ordering::Relaxed,
4397    );
4398}
4399
4400/// Port of `static int getpipe(char *cmd, int nullexec)` from
4401/// `Src/exec.c:5119`.
4402///
4403/// C body executes `<(cmd)` / `>(cmd)` process substitution via a
4404/// pipe pair: parent gets back the readable (`<(...)`) or writable
4405/// (`>(...)`) end as an fd; child runs the substituted command with
4406/// its stdio redirected into the other end.
4407///
4408/// ```c
4409/// Eprog prog;
4410/// int pipes[2], out = *cmd == Inang;
4411/// pid_t pid;
4412/// struct timespec bgtime;
4413/// char *ends;
4414/// if (!(prog = parsecmd(cmd, &ends))) return -1;
4415/// if (*ends) { zerr("invalid syntax..."); return -1; }
4416/// if (mpipe(pipes) < 0) return -1;
4417/// if ((pid = zfork(&bgtime))) {
4418///     zclose(pipes[out]);
4419///     if (pid == -1) { zclose(pipes[!out]); return -1; }
4420///     if (!nullexec) addproc(pid, NULL, 1, &bgtime, -1, -1);
4421///     procsubstpid = pid;
4422///     return pipes[!out];
4423/// }
4424/// entersubsh(ESUB_ASYNC|ESUB_PGRP|ESUB_NOMONITOR, NULL);
4425/// redup(pipes[out], out);
4426/// closem(FDT_UNUSED, 0);
4427/// cmdpush(CS_CMDSUBST);
4428/// execode(prog, 0, 1, out ? "outsubst" : "insubst");
4429/// cmdpop();
4430/// _realexit();
4431/// ```
4432///
4433/// (a) `addproc` is now 7-arg (jobs.rs:1516) — wired at the
4434///     procsubst pid recording site (c:5141-5142) earlier this
4435///     session; the child IS now recorded in `JOBTAB[thisjob]`.
4436/// (b) `entersubsh` IS now ported (exec.rs:3934) including the
4437///     ESUB_PGRP pipeline group-leadership path — wired this
4438///     session for getpipe's `entersubsh(ESUB_ASYNC|ESUB_PGRP|
4439///     ESUB_NOMONITOR, NULL)` call.
4440/// (c) `execode(prog, ...)` IS now ported (exec.rs:6047) — getpipe
4441///     can route through execode for the parsed eprog. Currently
4442///     this caller still uses the fusevm pipeline for cache
4443///     coherence with execstring; switch over when the wordcode
4444///     walker becomes the primary path.
4445/// (d) `_realexit()` flushes stdio + jobs + history. We use bare
4446///     `std::process::exit(lastval)` for now.
4447pub fn getpipe(cmd: &str, nullexec: i32) -> i32 {
4448    // c:5119
4449    let bytes = cmd.as_bytes();
4450    let out: i32 = if !bytes.is_empty() && (bytes[0] as char) == Inang {
4451        1 // c:5122 — `<(...)` reads from child, child writes to fd 1
4452    } else {
4453        0 // `>(...)` — child reads from fd 0
4454    };
4455    let mut ends_at: usize = 0;
4456    let prog = parsecmd(cmd, Some(&mut ends_at)); // c:5127
4457    if prog.is_none() {
4458        // c:5127
4459        return -1; // c:5128
4460    }
4461    // c:5129 — `if (*ends)` — trailing bytes after the `)` are invalid.
4462    if ends_at < bytes.len() && bytes[ends_at] != 0 {
4463        zerr("invalid syntax for process substitution in redirection"); // c:5130
4464        return -1; // c:5131
4465    }
4466    let mut pipes: [i32; 2] = [-1; 2];
4467    if mpipe(&mut pipes) < 0 {
4468        // c:5133
4469        return -1;
4470    }
4471    // c:5135 — `if ((pid = zfork(&bgtime)))` — parent path.
4472    let mut bgtime: ZshTimespec = libc::timespec {
4473        tv_sec: 0,
4474        tv_nsec: 0,
4475    };
4476    let pid = zfork(Some(&mut bgtime)); // c:5135
4477    if pid != 0 {
4478        // c:5135 — parent.
4479        let _ = zclose(pipes[out as usize]); // c:5136
4480        if pid == -1 {
4481            // c:5137
4482            let _ = zclose(pipes[(1 - out) as usize]); // c:5138
4483            return -1; // c:5139
4484        }
4485        // c:5141-5142 — `if (!nullexec) addproc(pid, NULL, 1, &bgtime, -1, -1);`
4486        if nullexec == 0 {
4487            if let Some(jt) = JOBTAB.get() {
4488                let mut guard = jt.lock().unwrap();
4489                let tj = THISJOB.get().map(|m| *m.lock().unwrap()).unwrap_or(-1);
4490                if tj >= 0 {
4491                    if let Some(j) = guard.get_mut(tj as usize) {
4492                        crate::ported::jobs::addproc(
4493                            j,
4494                            pid,
4495                            "",
4496                            true, // aux=1 for proc subst
4497                            Some(std::time::Instant::now()),
4498                            -1,
4499                            -1,
4500                        );
4501                    }
4502                }
4503            }
4504        }
4505        procsubstpid.store(pid, Ordering::Relaxed); // c:5143
4506        return pipes[(1 - out) as usize]; // c:5144
4507    }
4508    // c:5146 — child path.
4509    entersubsh(esub::ASYNC | esub::PGRP | esub::NOMONITOR, None); // c:5146
4510    let _ = redup(pipes[out as usize], out); // c:5147
4511    closem(FDT_UNUSED, 0); // c:5148
4512    cmdpush(CS_CMDSUBST as u8); // c:5149
4513                                // c:5150 — execode(prog, 0, 1, ...) — see WARNING (c).
4514    let body_end = if ends_at > 0 { ends_at - 1 } else { 2 };
4515    let body = if body_end > 2 && body_end <= bytes.len() {
4516        &cmd[2..body_end]
4517    } else {
4518        ""
4519    };
4520    let _ = crate::ported::exec_hooks::execute_script_zsh_pipeline(body);
4521    cmdpop(); // c:5151
4522              // c:5152 — _realexit() — WARNING (d).
4523    std::process::exit(LASTVAL.load(Ordering::Relaxed));
4524}
4525
4526/// Port of `static void spawnpipes(LinkList l, int nullexec)` from
4527/// `Src/exec.c:5184`.
4528///
4529/// Walks a redir list `l`, and for each REDIR_OUTPIPE/REDIR_INPIPE
4530/// entry fires `getpipe(name, nullexec || varid)` and stashes the
4531/// resulting fd into `f->fd2`.
4532///
4533/// ```c
4534/// LinkNode n;
4535/// Redir f;
4536/// char *str;
4537/// n = firstnode(l);
4538/// for (; n; incnode(n)) {
4539///     f = (Redir) getdata(n);
4540///     if (f->type == REDIR_OUTPIPE || f->type == REDIR_INPIPE) {
4541///         str = f->name;
4542///         f->fd2 = getpipe(str, nullexec || f->varid);
4543///     }
4544/// }
4545/// ```
4546///
4547/// =================== WARNING — DIVERGENCE ====================
4548/// The Rust port consumes a `&mut Vec<crate::ported::zsh_h::redir>`
4549/// in place of `LinkList`. The walk is identical; the only behavior
4550/// difference is that LinkList iteration in C lets callers splice
4551/// nodes mid-walk — we never do that here so it's a no-op divergence.
4552/// =============================================================
4553pub fn spawnpipes(l: &mut [redir], nullexec: i32) {
4554    // c:5184
4555    for f in l.iter_mut() {
4556        // c:5191
4557        if f.typ == REDIR_OUTPIPE || f.typ == REDIR_INPIPE {
4558            // c:5193
4559            let str_ = f.name.clone().unwrap_or_default(); // c:5194
4560            let nullexec_eff = if f.varid.as_deref().map_or(false, |v| !v.is_empty()) {
4561                1
4562            } else {
4563                nullexec
4564            };
4565            f.fd2 = getpipe(&str_, nullexec_eff); // c:5195
4566        }
4567    }
4568}
4569
4570/// Port of `static int cancd2(char *s)` from `Src/exec.c:6411`.
4571///
4572/// C body:
4573/// ```c
4574/// struct stat buf;
4575/// char *us, *us2 = NULL;
4576/// int ret;
4577/// if (!isset(CHASEDOTS) && !isset(CHASELINKS)) {
4578///     if (*s != '/')
4579///         us = tricat(pwd[1] ? pwd : "", "/", s);
4580///     else
4581///         us = ztrdup(s);
4582///     fixdir(us2 = us);
4583/// } else
4584///     us = unmeta(s);
4585/// ret = !(access(us, X_OK) || stat(us, &buf) || !S_ISDIR(buf.st_mode));
4586/// if (us2) free(us2);
4587/// return ret;
4588/// ```
4589///
4590/// True iff `s` is a directory we can `cd` into (X-perm). With
4591/// `!CHASEDOTS && !CHASELINKS`, lexically canonicalise the path
4592/// (joining with PWD if relative) so `cd /foo/bar/..` works without
4593/// resolving the symlink. Otherwise pass `s` through `unmeta` to libc.
4594pub fn cancd2(s: &str) -> i32 {
4595    // c:6411
4596    let us: String;
4597    // c:6422 — `if (!isset(CHASEDOTS) && !isset(CHASELINKS))`.
4598    let chasedots = isset(CHASEDOTS); // c:6422
4599    let chaselinks = isset(CHASELINKS);
4600    if !chasedots && !chaselinks {
4601        // c:6422
4602        // c:6423-6426 — `*s != '/' ? tricat(pwd, "/", s) : ztrdup(s);`
4603        let pwd_str = getsparam("PWD").unwrap_or_default(); // c:6424 `pwd`
4604        let mut raw = if !s.starts_with('/') {
4605            // c:6423
4606            format!(
4607                "{}/{}",
4608                if pwd_str.len() > 1 { &pwd_str[..] } else { "" },
4609                s
4610            )
4611        } else {
4612            s.to_string()
4613        };
4614        // c:6427 — `fixdir(us2 = us);` — lexical canonicalisation.
4615        raw = fixdir(&raw);
4616        us = raw;
4617    } else {
4618        // c:6428
4619        us = unmeta(s); // c:6429
4620    }
4621    // c:6430 — `!(access(us, X_OK) || stat(us, &buf) || !S_ISDIR(...))`.
4622    let cstr = match std::ffi::CString::new(us.as_str()) {
4623        Ok(c) => c,
4624        Err(_) => return 0,
4625    };
4626    if unsafe { libc::access(cstr.as_ptr(), libc::X_OK) } != 0 {
4627        return 0;
4628    }
4629    let meta = match std::fs::metadata(&us) {
4630        Ok(m) => m,
4631        Err(_) => return 0,
4632    };
4633    if !meta.file_type().is_dir() {
4634        return 0;
4635    }
4636    1
4637}
4638
4639/// Port of `char *cancd(char *s)` from `Src/exec.c:6370`.
4640///
4641/// Resolve a `cd` target against `$cdpath` and `cd_able_vars`.
4642/// Returns the chosen absolute path (heap-dup) if `cancd2` accepts
4643/// it, else `None`.
4644///
4645/// C body uses CDPATH walking + `cd_able_vars()` fallback. Sets
4646/// `doprintdir = -1` when a non-trivial path is found (so `cd`
4647/// echoes the resolved path).
4648pub fn cancd(s: &str) -> Option<String> {
4649    // c:6370
4650    // c:6372-6373 — `nocdpath = s[0]=='.' && (s[1]=='/' || !s[1] ||
4651    //                (s[1]=='.' && (s[2]=='/' || !s[2])))`.
4652    let bytes = s.as_bytes();
4653    let nocdpath = bytes.first().copied() == Some(b'.')
4654        && (bytes.get(1).copied() == Some(b'/')
4655            || bytes.get(1).is_none()
4656            || (bytes.get(1).copied() == Some(b'.')
4657                && (bytes.get(2).copied() == Some(b'/') || bytes.get(2).is_none())));
4658    // c:6376 — `if (*s != '/')` branch.
4659    if !s.starts_with('/') {
4660        // c:6376
4661        // c:6379-6380 — `if (cancd2(s)) return s;`
4662        if cancd2(s) != 0 {
4663            return Some(s.to_string());
4664        }
4665        // c:6381-6382 — `if (access(unmeta(s), X_OK) == 0) return NULL;`
4666        let cstr = std::ffi::CString::new(unmeta(s).as_str()).ok()?;
4667        if unsafe { libc::access(cstr.as_ptr(), libc::X_OK) } == 0 {
4668            return None; // c:6382
4669        }
4670        // c:6383-6397 — CDPATH walk.
4671        if !nocdpath {
4672            let cdpath_str = getsparam("CDPATH").unwrap_or_default();
4673            for cp in cdpath_str.split(':') {
4674                // c:6384
4675                let sbuf = if !cp.is_empty() {
4676                    format!("{}/{}", cp, s) // c:6386
4677                } else {
4678                    s.to_string() // c:6391
4679                };
4680                if cancd2(&sbuf) != 0 {
4681                    // c:6393
4682                    DOPRINTDIR.store(-1, Ordering::Relaxed); // c:6394
4683                    return Some(sbuf); // c:6395
4684                }
4685            }
4686        }
4687        // c:6398-6403 — `cd_able_vars()` fallback.
4688        if let Some(t) = cd_able_vars(s) {
4689            // c:6398
4690            if cancd2(&t) != 0 {
4691                // c:6399
4692                DOPRINTDIR.store(-1, Ordering::Relaxed); // c:6400
4693                return Some(t); // c:6401
4694            }
4695        }
4696        return None; // c:6404
4697    }
4698    // c:6406 — absolute path: `return cancd2(s) ? s : NULL;`
4699    if cancd2(s) != 0 {
4700        Some(s.to_string())
4701    } else {
4702        None
4703    }
4704}
4705
4706/// Port of `char *simple_redir_name(Eprog prog, int redir_type)` from
4707/// `Src/exec.c:4689`.
4708///
4709/// Test if an Eprog encodes a single simple-command consisting of a
4710/// SINGLE redirection of the requested type with NO command body
4711/// (the `cat < foo` shape). When true, returns the redir target name
4712/// (heap-dup) so callers like `$(< file)` short-circuit to a direct
4713/// `open(2)` instead of fork+pipe+exec.
4714///
4715/// C body walks the wordcode at fixed offsets (`pc[0]` = WC_LIST,
4716/// `pc[1]` = WC_SUBLIST, `pc[2]` = WC_PIPE, `pc[3]` = WC_REDIR,
4717/// `pc[6]` = WC_SIMPLE with argc=0). zshrs's wordcode buffer is the
4718/// same shape — this port replicates the same offset reads.
4719pub fn simple_redir_name(prog: &eprog, redir_type: i32) -> Option<String> {
4720    // c:4689
4721    let pc = &prog.prog;
4722    // c:4694-4702 — guard chain. Walk the wordcode buffer at fixed
4723    // offsets matching C's `pc[0]..pc[6]` checks.
4724    if pc.len() < 7 {
4725        return None;
4726    }
4727
4728    if wc_code(pc[0]) != WC_LIST
4729        || (WC_LIST_TYPE(pc[0]) & Z_END as u32) == 0  // c:4695
4730        || wc_code(pc[1]) != WC_SUBLIST
4731        || WC_SUBLIST_FLAGS(pc[1]) != 0  // c:4696
4732        || WC_SUBLIST_TYPE(pc[1]) != WC_SUBLIST_END  // c:4697
4733        || wc_code(pc[2]) != WC_PIPE
4734        || WC_PIPE_TYPE(pc[2]) != WC_PIPE_END  // c:4698
4735        || wc_code(pc[3]) != WC_REDIR
4736        || WC_REDIR_TYPE(pc[3]) != redir_type  // c:4699
4737        || WC_REDIR_VARID(pc[3]) != 0  // c:4700
4738        || pc[4] != 0  // c:4701
4739        || wc_code(pc[6]) != WC_SIMPLE
4740        || WC_SIMPLE_ARGC(pc[6]) != 0
4741    // c:4702
4742    {
4743        return None; // c:4706
4744    }
4745    // c:4703 — `return dupstring(ecrawstr(prog, pc + 5, NULL));`
4746    Some(dupstring(&ecrawstr(prog, 5, None)))
4747}
4748
4749/// Port of `int getherestr(struct redir *fn)` from `Src/exec.c:4655`.
4750///
4751/// C body:
4752/// ```c
4753/// char *s, *t;
4754/// int fd, len;
4755/// t = fn->name;
4756/// singsub(&t);
4757/// untokenize(t);
4758/// unmetafy(t, &len);
4759/// if (!(fn->flags & REDIRF_FROM_HEREDOC))
4760///     t[len++] = '\n';
4761/// if ((fd = gettempfile(NULL, 1, &s)) < 0)
4762///     return -1;
4763/// write_loop(fd, t, len);
4764/// close(fd);
4765/// fd = open(s, O_RDONLY | O_NOCTTY);
4766/// unlink(s);
4767/// return fd;
4768/// ```
4769///
4770/// Materialise a `<<<` herestring or unprocessed-here-doc body into a
4771/// tempfile, then re-open read-only and unlink — gives the consumer a
4772/// read fd whose backing file is already cleaned up.
4773pub fn getherestr(fn_: &redir) -> i32 {
4774    // c:4655
4775    let mut t: String = fn_.name.clone().unwrap_or_default(); // c:4660
4776    t = singsub(&t); // c:4661
4777    t = untokenize(&t); // c:4662
4778                        // c:4663 — `unmetafy(t, &len);` — strip Meta-escapes.
4779                        // Reuse the canonical unmetafy port (utils.rs) on a Vec<u8>.
4780    let mut bytes: Vec<u8> = t.into_bytes();
4781    let _len = unmetafy(&mut bytes);
4782    // c:4671-4672 — `if (!(fn->flags & REDIRF_FROM_HEREDOC)) t[len++] = '\n';`
4783    if (fn_.flags & REDIRF_FROM_HEREDOC) == 0 {
4784        // c:4671
4785        bytes.push(b'\n'); // c:4672
4786    }
4787    // c:4673-4674 — `if ((fd = gettempfile(NULL, 1, &s)) < 0) return -1;`
4788    let (fd, s) = match gettempfile(None) {
4789        Some(p) => p,
4790        None => return -1, // c:4674
4791    };
4792    // c:4675 — `write_loop(fd, t, len);`
4793    let _ = write_loop(fd, &bytes); // c:4675
4794                                    // c:4676 — `close(fd);`
4795    let _ = zclose(fd); // c:4676
4796                        // c:4677 — `fd = open(s, O_RDONLY | O_NOCTTY);`
4797    let cstr = std::ffi::CString::new(s.as_str()).unwrap_or_default();
4798    let new_fd = unsafe { libc::open(cstr.as_ptr(), libc::O_RDONLY | libc::O_NOCTTY) }; // c:4677
4799                                                                                        // c:4678 — `unlink(s);`
4800    unsafe {
4801        libc::unlink(cstr.as_ptr());
4802    } // c:4678
4803    new_fd // c:4679
4804}
4805
4806/// Port of `void quote_tokenized_output(char *str, FILE *file)` from
4807/// `Src/exec.c:2114`.
4808///
4809/// C body (abridged):
4810/// ```c
4811/// for (; *s; s++) {
4812///     switch (*s) {
4813///         case Meta: putc(*++s ^ 32, file); continue;
4814///         case Nularg: continue;
4815///         case '\\' '<' '>' '(' '|' ')' '^' '#' '~' '[' ']' '*' '?' '$' ' ':
4816///             putc('\\', file); break;
4817///         case '\t': fputs("$'\\t'", file); continue;
4818///         case '\n': fputs("$'\\n'", file); continue;
4819///         case '\r': fputs("$'\\r'", file); continue;
4820///         case '=': if (s == str) putc('\\', file); break;
4821///         default:
4822///             if (itok(*s)) { putc(ztokens[*s - Pound], file); continue; }
4823///     }
4824///     putc(*s, file);
4825/// }
4826/// ```
4827///
4828/// Used by `xtrace` (`set -x` printer) and `whence -c` to display a
4829/// tokenized argv in a form where lexer tokens (`Star`, `Inpar`, …)
4830/// surface as unescaped chars (`*`, `(`) while literal special chars
4831/// get backslash-escaped — round-tripping through the shell.
4832pub fn quote_tokenized_output(str_in: &str, file: &mut impl std::io::Write) -> std::io::Result<()> {
4833    // c:2114
4834    let bytes = str_in.as_bytes();
4835    let mut i = 0usize;
4836    while i < bytes.len() {
4837        // c:2118 `for (; *s; s++)`
4838        let c = bytes[i];
4839        match c {
4840            x if x == Meta => {
4841                // c:2120 — `case Meta: putc(*++s ^ 32, file);`
4842                if i + 1 < bytes.len() {
4843                    file.write_all(&[bytes[i + 1] ^ 32])?; // c:2121
4844                    i += 2;
4845                } else {
4846                    i += 1;
4847                }
4848                continue; // c:2122
4849            }
4850            x if x as char == Nularg => {
4851                // c:2124
4852                i += 1;
4853                continue; // c:2126
4854            }
4855            b'\\' | b'<' | b'>' | b'(' | b'|' | b')' | b'^' | b'#' | b'~' | b'[' | b']' | b'*'
4856            | b'?' | b'$' | b' ' => {
4857                // c:2128-2142
4858                file.write_all(b"\\")?; // c:2143
4859            }
4860            b'\t' => {
4861                // c:2146
4862                file.write_all(b"$'\\t'")?; // c:2147
4863                i += 1;
4864                continue;
4865            }
4866            b'\n' => {
4867                // c:2150
4868                file.write_all(b"$'\\n'")?; // c:2151
4869                i += 1;
4870                continue;
4871            }
4872            b'\r' => {
4873                // c:2154
4874                file.write_all(b"$'\\r'")?; // c:2155
4875                i += 1;
4876                continue;
4877            }
4878            b'=' => {
4879                // c:2158 — `if (s == str) putc('\\', file);`
4880                if i == 0 {
4881                    file.write_all(b"\\")?; // c:2160
4882                }
4883            }
4884            _ => {
4885                // c:2163 — `if (itok(*s)) putc(ztokens[*s - Pound], file); continue;`
4886                if itok(c) {
4887                    // c:2164
4888                    let pound = Pound as u8;
4889                    if c >= pound {
4890                        let idx = (c - pound) as usize;
4891                        let zt = ztokens.as_bytes();
4892                        if idx < zt.len() {
4893                            file.write_all(&[zt[idx]])?; // c:2165 `ztokens[*s - Pound]`
4894                        }
4895                    }
4896                    i += 1;
4897                    continue;
4898                }
4899            }
4900        }
4901        file.write_all(&[c])?; // c:2171
4902        i += 1;
4903    }
4904    Ok(())
4905}
4906
4907// =====================================================================
4908// Wordcode-VM control-flow dispatch — faithful ports of the C
4909// `Src/exec.c` + `Src/loop.c` wordcode interpreter entries.
4910//
4911// Each function below takes `&mut estate` and returns `i32` to mirror
4912// the C `int execX(Estate state, int do_exec)` signature exactly. Per-
4913// line `// c:NNN` citations track the C source line.
4914//
4915// zshrs's primary execution path is the fusevm bytecode VM. These
4916// wordcode-VM entries exist for C-name parity with the upstream
4917// interpreter so that future bridging code can drive zshrs through
4918// the same dispatch tree zsh's `Src/init.c::loop` walks. Where
4919// zshrs primitives don't yet model their C counterpart (e.g.
4920// `execsubst`, `addvars`, `execfuncs[]` dispatch table), the local
4921// helper is declared with a comment citing the C source file:line
4922// where the canonical body lives — same pattern as the canonical
4923// `ksh93::ksh93_wrapper` port at c:152-227.
4924// =====================================================================
4925
4926use crate::ported::math::{matheval as wc_matheval, mathevali as wc_mathevali};
4927use crate::ported::pattern::{patcompile, pattry};
4928use crate::ported::r#loop::try_tryflag;
4929
4930// Addvars-specific imports (Src/exec.c:2497 port at exec.rs::addvars).
4931use crate::ported::builtin::{BREAKS, CONTFLAG, LOOPS, RETFLAG};
4932use crate::ported::linklist::LinkList;
4933use crate::ported::mem::freeheap;
4934use crate::ported::params::setloopvar;
4935use crate::ported::params::{assignaparam, assignsparam, unsetparam};
4936use crate::ported::parse::{ecgetlist, ecgetstr};
4937use crate::ported::pattern::haswilds;
4938use crate::ported::signals_h::{queue_signal_level, restore_queue_signals};
4939use crate::ported::subst::{globlist, prefork};
4940use crate::ported::zsh_h::{
4941    estate, wordcode, EC_DUP, EC_DUPTOK, EC_NODUP, NOERREXIT_EXIT, NOERREXIT_RETURN, PAT_STATIC,
4942    WC_CASE, WC_CASE_AND, WC_CASE_OR, WC_CASE_SKIP, WC_CASE_TESTAND, WC_CASE_TYPE, WC_CURSH_SKIP,
4943    WC_END, WC_FOR_COND, WC_FOR_LIST, WC_FOR_SKIP, WC_FOR_TYPE, WC_FUNCDEF, WC_FUNCDEF_SKIP, WC_IF,
4944    WC_IF_ELSE, WC_IF_SKIP, WC_IF_TYPE, WC_REPEAT_SKIP, WC_TIMED_EMPTY, WC_TIMED_TYPE, WC_TRY_SKIP,
4945    WC_WHILE_SKIP, WC_WHILE_TYPE, WC_WHILE_UNTIL,
4946};
4947use crate::ported::zsh_h::{
4948    ALLEXPORT, ASSPM_AUGMENT, ASSPM_KEY_VALUE, ASSPM_WARN, GLOBASSIGN, KSHARRAYS, PREFORK_ASSIGN,
4949    PREFORK_KEY_VALUE, PREFORK_SINGLE, WC_ASSIGN, WC_ASSIGN_INC, WC_ASSIGN_NUM, WC_ASSIGN_SCALAR,
4950    WC_ASSIGN_TYPE, WC_ASSIGN_TYPE2,
4951};
4952use crate::ported::zsh_h::{
4953    CS_ALWAYS, CS_CASE, CS_COND, CS_CURSH, CS_ELIF, CS_ELIFTHEN, CS_ELSE, CS_FOR, CS_IF, CS_IFTHEN,
4954    CS_MATH, CS_REPEAT, CS_UNTIL, CS_WHILE, MN_INTEGER,
4955};
4956
4957// --- Local stubs for C primitives not yet ported elsewhere ------------
4958//
4959// These mirror the C functions of the same names. Each cites the C
4960// source file:line where the canonical body lives. They are inlined
4961// here (rather than a separate `pub fn` in the owning C-file module)
4962// because the owning ports are pending the wider exec-substrate
4963// work (sub-PR). Once those land, these locals collapse to direct
4964// `crate::ported::<owner>::<fn>` calls.
4965
4966/// Port of `void execsubst(LinkList strs)` from `Src/exec.c:2684`.
4967///
4968/// C body (c:2684-2693):
4969/// ```c
4970/// void execsubst(LinkList strs) {
4971///     if (strs) {
4972///         prefork(strs, esprefork, NULL);
4973///         if (esglob && !errflag) {
4974///             LinkList ostrs = strs;
4975///             globlist(strs, 0);
4976///             strs = ostrs;
4977///         }
4978///     }
4979/// }
4980/// ```
4981///
4982/// `execsubst` runs `prefork` (parameter / arithmetic / command
4983/// substitution expansion + IFS-split) over the whole list, then
4984/// (when `esglob` is set) `globlist` to do filename globbing on the
4985/// result.
4986fn execsubst(list: &mut Vec<String>) {
4987    // c:2684
4988    if list.is_empty() {
4989        return; // c:2686 `if (strs)`
4990    }
4991    let mut ll: crate::ported::subst::LinkList = std::mem::take(list).into_iter().collect();
4992    let prefork_flags = esprefork.load(Ordering::Relaxed); // c:2687 esprefork
4993    let mut rf: i32 = 0;
4994    prefork(&mut ll, prefork_flags, &mut rf); // c:2687
4995    if esglob.load(Ordering::Relaxed) != 0 && errflag.load(Ordering::Relaxed) == 0 {
4996        // c:2688 `if (esglob && !errflag)`
4997        globlist(&mut ll, 0); // c:2690
4998    }
4999    *list = ll.into_iter().collect();
5000}
5001
5002/// Direct port of `static void addvars(Estate state, Wordcode pc,
5003/// int addflags)` from `Src/exec.c:2497-2648`. Process the WC_ASSIGN
5004/// nodes stacked inline of a simple command — the `var=value` and
5005/// `arr=(v1 v2 v3)` assignments that precede argv. Walks the wordcode
5006/// at `pc`, extracts each assignment's name + value (scalar or array),
5007/// optionally preforks + globs the tokenised RHS, and routes through
5008/// `assignsparam` (scalar) or `assignaparam` (array).
5009///
5010/// XTRACE side-effect: prints `name=value ` / `name=( v1 v2 ) ` to
5011/// stderr (C uses xtrerr; zshrs uses eprint!).
5012///
5013/// `STTY=...` in an inline-export form (`STTY=raw cmd`) gets captured
5014/// into the file-static `STTYval` for `execute()` to apply pre-exec.
5015fn addvars(state: &mut estate, pc: usize, addflags: i32) {
5016    // c:2501 — locals.
5017    let mut vl: LinkList<String>; // c:2501 `LinkList vl;`
5018    let xtr: bool; // c:2502 `int xtr,`
5019    let mut isstr: bool; // c:2502 `int isstr,`
5020    let mut htok: i32 = 0; // c:2502 `int htok = 0;`
5021    let mut arr: Vec<String>; // c:2503 `char **arr, **ptr, *name;`
5022    let mut name: String;
5023    let mut flags: i32; // c:2504 `int flags;`
5024    let opc = state.pc; // c:2506 `Wordcode opc = state->pc;`
5025    let mut ac: wordcode; // c:2507 `wordcode ac;`
5026                          // c:2508 `local_list1(svl);` — stack-local one-element LinkList
5027                          // for the scalar-assignment path. Rust uses a fresh LinkList per
5028                          // iteration; equivalent semantics.
5029
5030    // c:2510-2515 — comment about WARNCREATEGLOBAL warning suppression
5031    // when the assignment list is implicitly local (ADDVAR_RESTORE).
5032    flags = if (addflags & ADDVAR_RESTORE) == 0 {
5033        ASSPM_WARN // c:2516
5034    } else {
5035        0 // c:2516
5036    };
5037    xtr = isset(XTRACE); // c:2517 `xtr = isset(XTRACE);`
5038    if xtr {
5039        // c:2518
5040        printprompt4(); // c:2519
5041        doneps4.store(1, Ordering::Relaxed); // c:2520 `doneps4 = 1;`
5042    }
5043    state.pc = pc; // c:2522 `state->pc = pc;`
5044
5045    // c:2523 `while (wc_code(ac = *state->pc++) == WC_ASSIGN) {`
5046    loop {
5047        if state.pc >= state.prog.prog.len() {
5048            break;
5049        }
5050        ac = state.prog.prog[state.pc];
5051        state.pc += 1;
5052        if wc_code(ac) != WC_ASSIGN {
5053            // Step back so the WC_SIMPLE / outer dispatcher sees the
5054            // non-assignment opcode. C's `state->pc++` post-increment
5055            // already pointed past WC_ASSIGN; we need to unconsume.
5056            state.pc -= 1;
5057            break;
5058        }
5059        let mut myflags = flags; // c:2524 `int myflags = flags;`
5060        name = ecgetstr(state, EC_DUPTOK, Some(&mut htok)); // c:2525
5061        if htok != 0 {
5062            // c:2526 `if (htok) untokenize(name);`
5063            name = untokenize(&name).to_string(); // c:2527
5064        }
5065        if WC_ASSIGN_TYPE2(ac) == WC_ASSIGN_INC {
5066            // c:2528
5067            myflags |= ASSPM_AUGMENT; // c:2529
5068        }
5069        if xtr {
5070            // c:2530
5071            // c:2531-2532 — fprintf(xtrerr, ... "%s+=" : "%s=", name);
5072            if WC_ASSIGN_TYPE2(ac) == WC_ASSIGN_INC {
5073                eprint!("{}+=", name); // c:2532
5074            } else {
5075                eprint!("{}=", name); // c:2532
5076            }
5077        }
5078
5079        // c:2533 `if ((isstr = (WC_ASSIGN_TYPE(ac) == WC_ASSIGN_SCALAR))) {`
5080        isstr = WC_ASSIGN_TYPE(ac) == WC_ASSIGN_SCALAR;
5081        if isstr {
5082            // c:2534 `init_list1(svl, ecgetstr(state, EC_DUPTOK, &htok));`
5083            let svl_val = ecgetstr(state, EC_DUPTOK, Some(&mut htok));
5084            vl = LinkList::new();
5085            vl.push_back(svl_val);
5086            // c:2535 `vl = &svl;` — vl already points at the new list.
5087        } else {
5088            // c:2537 `vl = ecgetlist(state, WC_ASSIGN_NUM(ac), EC_DUPTOK, &htok);`
5089            let items = ecgetlist(
5090                state,
5091                WC_ASSIGN_NUM(ac) as usize,
5092                EC_DUPTOK,
5093                Some(&mut htok),
5094            );
5095            vl = LinkList::new();
5096            for it in items {
5097                vl.push_back(it);
5098            }
5099            if errflag.load(Ordering::Relaxed) != 0 {
5100                // c:2538-2541
5101                state.pc = opc; // c:2539
5102                return; // c:2540
5103            }
5104        }
5105
5106        // c:2544 `if (vl && htok) {`
5107        if htok != 0 {
5108            // c:2545 `int prefork_ret = 0;`
5109            let mut prefork_ret: i32 = 0;
5110            // c:2546-2547 — prefork(vl, (isstr ? PREFORK_SINGLE|PREFORK_ASSIGN
5111            //                          : PREFORK_ASSIGN), &prefork_ret);
5112            let pf_flags = if isstr {
5113                PREFORK_SINGLE | PREFORK_ASSIGN
5114            } else {
5115                PREFORK_ASSIGN
5116            };
5117            prefork(&mut vl, pf_flags, &mut prefork_ret); // c:2547
5118            if errflag.load(Ordering::Relaxed) != 0 {
5119                // c:2548
5120                state.pc = opc; // c:2549
5121                return; // c:2550
5122            }
5123            if (prefork_ret & PREFORK_KEY_VALUE) != 0 {
5124                // c:2552
5125                myflags |= ASSPM_KEY_VALUE; // c:2553
5126            }
5127            // c:2554-2555 — `if (!isstr || (isset(GLOBASSIGN) && isstr &&
5128            //                  haswilds((char *)getdata(firstnode(vl)))))`
5129            let needs_glob = if !isstr {
5130                true
5131            } else {
5132                isset(GLOBASSIGN)
5133                    && isstr
5134                    && !vl.is_empty()
5135                    && haswilds(vl.nodes.front().map(|s| s.as_str()).unwrap_or(""))
5136            };
5137            if needs_glob {
5138                globlist(&mut vl, prefork_ret); // c:2556
5139                                                // c:2557-2562 — `if (isset(GLOBASSIGN) && isstr)
5140                                                //                  unsetparam(name);`
5141                if isset(GLOBASSIGN) && isstr {
5142                    unsetparam(&name); // c:2562
5143                }
5144                if errflag.load(Ordering::Relaxed) != 0 {
5145                    // c:2563
5146                    state.pc = opc; // c:2564
5147                    return; // c:2565
5148                }
5149            }
5150        }
5151        // c:2569 `if (isstr && (empty(vl) || !nextnode(firstnode(vl))))`
5152        // — scalar-assignment path: zero or one element after prefork.
5153        if isstr && (vl.is_empty() || vl.len() == 1) {
5154            let val: String; // c:2571 `char *val;`
5155            if vl.is_empty() {
5156                // c:2574
5157                val = String::new(); // c:2575 `val = ztrdup("");`
5158            } else {
5159                // c:2577 `untokenize(peekfirst(vl));`
5160                let peek = vl.nodes.front().cloned().unwrap_or_default();
5161                val = untokenize(&peek).to_string(); // c:2577-2578
5162                                                     // c:2578 `val = ztrdup(ugetnode(vl));` — ugetnode pops;
5163                                                     // we just cloned the front above. Equivalent.
5164            }
5165            if xtr {
5166                // c:2580
5167                eprint!("{}", quotedzputs(&val)); // c:2581
5168                eprint!(" "); // c:2582 `fputc(' ', xtrerr);`
5169            }
5170            // c:2584 `if ((addflags & ADDVAR_EXPORT) && !strchr(name, '['))`
5171            let pm = if (addflags & ADDVAR_EXPORT) != 0 && !name.contains('[') {
5172                // c:2585 `if (strcmp(name, "STTY") == 0)`
5173                if name == "STTY" {
5174                    // c:2586-2587 — `STTYval = ztrdup(val);`
5175                    let mut stty = STTYval.lock().unwrap();
5176                    *stty = Some(val.clone()); // c:2587
5177                }
5178                // c:2589 `allexp = opts[ALLEXPORT];`
5179                let allexp = isset(ALLEXPORT);
5180                // c:2590 `opts[ALLEXPORT] = 1;` — temporarily set.
5181                opt_state_set("allexport", true);
5182                if isset(KSHARRAYS) {
5183                    // c:2591
5184                    unsetparam(&name); // c:2592
5185                }
5186                let pm = assignsparam(&name, &val, myflags); // c:2593
5187                                                             // c:2594 `opts[ALLEXPORT] = allexp;` — restore.
5188                opt_state_set("allexport", allexp);
5189                pm
5190            } else {
5191                // c:2595
5192                assignsparam(&name, &val, myflags) // c:2596
5193            };
5194            if pm.is_none() {
5195                // c:2597 `if (!pm)`
5196                LASTVAL.store(1, Ordering::Relaxed); // c:2598 `lastval = 1;`
5197                                                     // c:2599-2604 — "cheating" comment: don't zerr.
5198                if cmdoutval.load(Ordering::Relaxed) == 0 {
5199                    // c:2605 `if (!cmdoutval)`
5200                    cmdoutval.store(1, Ordering::Relaxed); // c:2606
5201                }
5202            }
5203            if errflag.load(Ordering::Relaxed) != 0 {
5204                // c:2608
5205                state.pc = opc; // c:2609
5206                return; // c:2610
5207            }
5208            continue; // c:2612
5209        }
5210        // c:2614 `if (vl) { ... }` — array-assignment path: drain vl
5211        // into a fresh `char **arr`.
5212        // c:2615-2619 `ptr = arr = zalloc(...); while (nonempty(vl)) *ptr++ = ztrdup(ugetnode(vl));`
5213        arr = Vec::with_capacity(vl.len() + 1);
5214        while let Some(s) = vl.pop_front() {
5215            arr.push(s);
5216        }
5217        // c:2623 `*ptr = NULL;` — C terminator; Rust Vec doesn't need it.
5218        if xtr {
5219            // c:2624
5220            eprint!("( "); // c:2625
5221            for s in &arr {
5222                // c:2626 `for (ptr = arr; *ptr; ptr++)`
5223                eprint!("{}", quotedzputs(s)); // c:2627
5224                eprint!(" "); // c:2628
5225            }
5226            eprint!(") "); // c:2630
5227        }
5228        // c:2632 `if (!assignaparam(name, arr, myflags))`
5229        if assignaparam(&name, arr, myflags).is_none() {
5230            LASTVAL.store(1, Ordering::Relaxed); // c:2633
5231                                                 // c:2634-2638 — "cheating" comment.
5232            if cmdoutval.load(Ordering::Relaxed) == 0 {
5233                // c:2639
5234                cmdoutval.store(1, Ordering::Relaxed); // c:2640
5235            }
5236        }
5237        if errflag.load(Ordering::Relaxed) != 0 {
5238            // c:2642
5239            state.pc = opc; // c:2643
5240            return; // c:2644
5241        }
5242    }
5243    state.pc = opc; // c:2647 `state->pc = opc;`
5244}
5245
5246// execfuncs[] dispatch table from `Src/exec.c:5499` is inlined as a
5247// match expression at the call sites in execsimple. Not a separate
5248// Rust fn — every C-side reference to
5249// `execfuncs[code - WC_CURSH](state, ...)` resolves inline below.
5250
5251// --- exec.c entries ---------------------------------------------------
5252
5253/// Port of `execcursh(Estate state, int do_exec)` from
5254/// `Src/exec.c:469-498`. Execute a `{ ... }` current-shell command
5255/// group: skip the trailing try-only word, optionally drop a stale
5256/// job slot, then run the inner list.
5257pub fn execcursh(state: &mut estate, do_exec: i32) -> i32 {
5258    // c:472 — `end = state->pc + WC_CURSH_SKIP(state->pc[-1]);`
5259    let prior = state.prog.prog[state.pc.wrapping_sub(1)];
5260    let end = state.pc + WC_CURSH_SKIP(prior) as usize;
5261    // c:475 — `state->pc++;` skip the try/always-only word.
5262    state.pc += 1;
5263    // c:482-486 — drop empty job slot before nested cmd: if outer-pipe
5264    // bookkeeping is clean AND thisjob is a real job that's not the
5265    // pipe-leader AND has no procs yet, deletejob() recycles it. Avoids
5266    // leaking job-table slots when execcursh recurses.
5267    {
5268        let lp = list_pipe.load(Ordering::Relaxed);
5269        let lpj = list_pipe_job.load(Ordering::Relaxed);
5270        let tj = THISJOB.get().map(|m| *m.lock().unwrap()).unwrap_or(-1);
5271        if lp == 0 && tj != -1 && tj != lpj {
5272            if let Some(jt) = JOBTAB.get() {
5273                let mut guard = jt.lock().unwrap();
5274                let has = crate::ported::jobs::hasprocs(&guard, tj as usize);
5275                if !has {
5276                    if let Some(j) = guard.get_mut(tj as usize) {
5277                        crate::ported::jobs::deletejob(j, false);
5278                    }
5279                }
5280            }
5281        }
5282    }
5283    cmdpush(CS_CURSH as u8); // c:487 — `cmdpush(CS_CURSH);`
5284    let _ = execlist(state, 1, do_exec); // c:488 — `execlist(state, 1, do_exec);`
5285    cmdpop(); // c:489 — `cmdpop();`
5286    state.pc = end; // c:491 — `state->pc = end;`
5287    this_noerrexit.store(1, Ordering::Relaxed); // c:492 — `this_noerrexit = 1;`
5288    LASTVAL.load(Ordering::Relaxed) // c:494 — `return lastval;`
5289}
5290
5291// `(...)` subshell — no dedicated C function (handled inline by
5292// `execpline`'s WC_PIPE branch via the WC_SUBSH bit, exec.c:2540+).
5293// In zshrs the subshell branch is folded into `execpline` and
5294// `execsimple`'s WC_SUBSH dispatch — both invoke execcursh for the
5295// inner-list walk since fusevm bytecode handles the forking via
5296// Op::Subshell at a higher layer.
5297
5298/// Port of `execcond(Estate state, UNUSED(int do_exec))` from
5299/// `Src/exec.c:5204-5232`. Run a `[[ ... ]]` cond expression.
5300pub fn execcond(state: &mut estate, _do_exec: i32) -> i32 {
5301    state.pc -= 1; // c:5208 — `state->pc--;`
5302                   // c:5209-5213 — XTRACE prelude.
5303    if isset(XTRACE) {
5304        printprompt4();
5305        eprint!("[[");
5306        // c:5212 — `tracingcond++;` not modeled in zshrs.
5307    }
5308    cmdpush(CS_COND as u8); // c:5214
5309                            // c:5215 — `stat = evalcond(state, NULL);` — TODO faithful: needs
5310                            // the wordcode-level evalcond from Src/cond.c which is distinct
5311                            // from the test-builtin evalcond ported in cond.rs. Pending.
5312    let stat: i32 = 0;
5313    // c:5219-5221 — `if (stat == 2) errflag |= ERRFLAG_ERROR;`
5314    if stat == 2 {
5315        errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed);
5316    }
5317    cmdpop(); // c:5222
5318    if isset(XTRACE) {
5319        eprintln!(" ]]");
5320    }
5321    stat // c:5230 — `return stat;`
5322}
5323
5324/// Port of `execarith(Estate state, UNUSED(int do_exec))` from
5325/// `Src/exec.c:5237-5275`. Run a `(( ... ))` arithmetic command;
5326/// returns 0 when val != 0 (success), 1 when val == 0 (false), 2 on
5327/// parse error.
5328pub fn execarith(state: &mut estate, _do_exec: i32) -> i32 {
5329    if isset(XTRACE) {
5330        printprompt4();
5331        eprint!("((");
5332    }
5333    cmdpush(CS_MATH as u8); // c:5247
5334    let mut htok: i32 = 0;
5335    let mut e = ecgetstr(state, EC_DUPTOK, Some(&mut htok)); // c:5248
5336    if htok != 0 {
5337        e = singsub(&e); // c:5250 — `singsub(&e);`
5338    }
5339    if isset(XTRACE) {
5340        eprint!(" {}", e);
5341    }
5342    let val_result = wc_matheval(&e); // c:5254 — `val = matheval(e);`
5343    cmdpop(); // c:5256
5344    if isset(XTRACE) {
5345        eprintln!(" ))");
5346    }
5347    // c:5262-5265 — `if (errflag) { errflag &= ~ERRFLAG_ERROR; return 2; }`
5348    if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 || val_result.is_err() {
5349        errflag.fetch_and(!ERRFLAG_ERROR, Ordering::Relaxed);
5350        return 2;
5351    }
5352    // c:5267 — `return (val.type == MN_INTEGER) ? val.u.l == 0 : val.u.d == 0.0;`
5353    let val = val_result.unwrap();
5354    if val.type_ == MN_INTEGER {
5355        if val.l == 0 {
5356            1
5357        } else {
5358            0
5359        }
5360    } else if val.d == 0.0 {
5361        1
5362    } else {
5363        0
5364    }
5365}
5366
5367/// Port of `exectime(Estate state, UNUSED(int do_exec))` from
5368/// `Src/exec.c:5279-5294`. Run `time pipeline`: drives execpline with
5369/// the Z_TIMED|Z_SYNC flags so it tracks wall/user/sys time.
5370pub fn exectime(state: &mut estate, _do_exec: i32) -> i32 {
5371    let jb = *THISJOB
5372        .get_or_init(|| std::sync::Mutex::new(-1))
5373        .lock()
5374        .unwrap(); // c:5283
5375    let prior = state.prog.prog[state.pc.wrapping_sub(1)];
5376    // c:5284-5287 — empty `time` (no pipeline) — print accumulated shell time.
5377    if WC_TIMED_TYPE(prior) == WC_TIMED_EMPTY {
5378        // c:5285 — `shelltime(NULL,NULL,NULL,0);` — print accumulated
5379        // shell+kids time deltas since last call.
5380        crate::ported::jobs::shelltime(None, None, None, 0);
5381        return 0; // c:5286
5382    }
5383    // c:5288 — `execpline(state, *state->pc++, Z_TIMED|Z_SYNC, 0);`
5384    let slcode = state.prog.prog[state.pc];
5385    state.pc += 1;
5386    use crate::ported::zsh_h::{Z_SYNC, Z_TIMED};
5387    let _ = execpline(state, slcode, Z_TIMED as i32 | Z_SYNC as i32, 0);
5388    *THISJOB
5389        .get_or_init(|| std::sync::Mutex::new(-1))
5390        .lock()
5391        .unwrap() = jb; // c:5289
5392    LASTVAL.load(Ordering::Relaxed) // c:5290
5393}
5394
5395/// `execshfunc(Shfunc shf, LinkList args)` — `Src/exec.c:5540`.
5396/// Promoted to top-level pub fn so execcmd_exec at the shfunc
5397/// dispatch site (c:4102-4105) can route through it. The real port
5398/// owns queue_signals + cmdstack + sfcontext setup before calling
5399/// doshfunc; doshfunc itself is unported, so we route the body
5400/// through `runshfunc` (exec.rs:1700), which carries the
5401/// wrapper-chain + zunderscore restore. Degraded vs C (no cmdstack
5402/// push, no sfcontext flip, no XTRACE arg-trace) but the function
5403/// body executes and `lastval` is updated.
5404pub fn execshfunc(shf: &mut shfunc, args: &mut Vec<String>) {
5405    // c:5546-5547 — `if (errflag) return;`
5406    if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
5407        return;
5408    }
5409    // c:5550-5557 — drop empty job slot before nested shfunc invoke:
5410    // if outer-pipe bookkeeping is clean AND thisjob is a real job
5411    // that's not the pipe-leader AND has no procs yet, deletejob()
5412    // recycles it. Avoids leaking job-table slots across recursive
5413    // function calls. Same pattern as execcursh's c:482-486.
5414    {
5415        let lp = list_pipe.load(Ordering::Relaxed);
5416        let lpj = list_pipe_job.load(Ordering::Relaxed);
5417        let tj = THISJOB.get().map(|m| *m.lock().unwrap()).unwrap_or(-1);
5418        if lp == 0 && tj != -1 && tj != lpj {
5419            if let Some(jt) = JOBTAB.get() {
5420                let mut guard = jt.lock().unwrap();
5421                let has = crate::ported::jobs::hasprocs(&guard, tj as usize);
5422                if !has {
5423                    // c:5554-5555 — `last_file_list = jobtab[thisjob].filelist;
5424                    //                jobtab[thisjob].filelist = NULL;` — preserve
5425                    //                the filelist so deletejob doesn't unlink temp
5426                    //                files. Rust take()s the Vec into a local.
5427                    let _last_file_list: Vec<String> = if let Some(j) = guard.get_mut(tj as usize) {
5428                        std::mem::take(&mut j.filelist)
5429                    } else {
5430                        Vec::new()
5431                    };
5432                    if let Some(j) = guard.get_mut(tj as usize) {
5433                        crate::ported::jobs::deletejob(j, false); // c:5556
5434                    }
5435                }
5436            }
5437        }
5438    }
5439    // c:5559-5570 — `if (isset(XTRACE)) { printprompt4(); ... \n; }` —
5440    // emit PS4 prefix + space-separated quoted args on the trace
5441    // stream so `set -x` shows the function invocation line.
5442    if isset(XTRACE) {
5443        printprompt4();
5444        for (i, a) in args.iter().enumerate() {
5445            if i > 0 {
5446                eprint!(" ");
5447            }
5448            eprint!("{}", quotedzputs(a));
5449        }
5450        eprintln!();
5451    }
5452    // c:5572-5578 cmdstack/sfcontext setup: omit (no cmdstack in
5453    // zshrs yet — replaced by tracing).
5454    // c:5580 — `doshfunc(shf, args, 0);` — doshfunc swaps PPARAMS
5455    // ($1, $2, …) to the function's args, runs the body via
5456    // runshfunc, then restores. doshfunc itself isn't ported yet
5457    // so we do the swap-and-restore inline here.
5458    // c:5580 — `doshfunc(shf, args, 0);`. The C path always has
5459    // `funcdef` populated since C parses at definition time. zshrs
5460    // compiles to fusevm chunks instead, so `funcdef` is None for
5461    // user-defined functions; only `body` (source string) carries
5462    // the definition. When that's the case, build a one-shot eprog
5463    // whose `strs` carries the source so runshfunc's script-pipeline
5464    // arm (execute_script_zsh_pipeline) executes the body.
5465    let prog_owned: Option<eprog> = if shf.funcdef.is_some() {
5466        None
5467    } else if let Some(ref body) = shf.body {
5468        Some(eprog {
5469            strs: Some(body.clone()),
5470            ..Default::default()
5471        })
5472    } else {
5473        None
5474    };
5475    let prog_ref: Option<&eprog> = match (shf.funcdef.as_deref(), prog_owned.as_ref()) {
5476        (Some(p), _) => Some(p),
5477        (_, Some(p)) => Some(p),
5478        _ => None,
5479    };
5480    if let Some(_prog) = prog_ref {
5481        // c:5580 — `doshfunc(shf, args, 0);`. Direct doshfunc call —
5482        // noreturnval=0 means the body's return value updates LASTVAL
5483        // (caller of execfuncdef reads it back). PPARAMS swap +
5484        // restore happens INSIDE doshfunc's scope; body_runner just
5485        // runs the body.
5486        let name_for_body = shf.node.nam.clone();
5487        let body_args_owned: Vec<String> = if args.len() > 1 {
5488            args[1..].to_vec()
5489        } else {
5490            Vec::new()
5491        };
5492        let body_runner = move || -> i32 {
5493            crate::ported::exec_hooks::run_function_body(&name_for_body, &body_args_owned)
5494                .unwrap_or(0)
5495        };
5496        let _ = doshfunc(shf, args.clone(), false, body_runner);
5497    }
5498    // c:5582-5589 cmdstack restore/free: omit (no cmdstack).
5499}
5500
5501/// Port of `int doshfunc(Shfunc shfunc, LinkList doshargs, int noreturnval)`
5502/// from `Src/exec.c:5823-6158`.
5503///
5504/// C body's scope-management sequence ported here. The C source's
5505/// body-execution call (`runshfunc(prog, wrappers, name)` at c:6042)
5506/// is replaced by `body_runner` — zshrs runs function bodies through
5507/// fusevm bytecode rather than zsh's wordcode walker (per PORT.md
5508/// "zshrs replaces zsh's tree-walking interpreter" rule), so the
5509/// callback hands the live executor back to the caller (typically
5510/// the fusevm bridge) for the actual body run. Every line of scope
5511/// save/restore around the body call mirrors C exactly.
5512///
5513/// **RUST-ONLY ADAPTATION:** the extra `body_runner` parameter is
5514/// not in C. C calls `runshfunc(prog, wrappers, name)` directly at
5515/// c:6042; zshrs delegates to a closure because the body-execution
5516/// pipeline (fusevm) differs from C's (wordcode). The closure
5517/// fully replaces the runshfunc call and returns the body's exit
5518/// status (which doshfunc reads as `lastval` for the `noreturnval`
5519/// path).
5520#[allow(non_snake_case)]
5521pub fn doshfunc(
5522    shfunc: &mut shfunc,                  // c:5823
5523    doshargs: Vec<String>,                // c:5823
5524    noreturnval: bool,                    // c:5823
5525    mut body_runner: impl FnMut() -> i32, // (Rust-only — body delegate)
5526) -> i32 {
5527    use crate::ported::builtin::{BREAKS, CONTFLAG, LASTVAL, LOOPS, RETFLAG};
5528    use crate::ported::jobs::{NUMPIPESTATS, PIPESTATS};
5529    use crate::ported::modules::parameter::FUNCSTACK;
5530    use crate::ported::params::endparamscope;
5531    use crate::ported::params::locallevel as locallevel_atomic;
5532    use crate::ported::zsh_h::{FS_EVAL, FS_FUNC, FS_SOURCE, FUNCTIONARGZERO, PM_UNDEFINED};
5533    use std::sync::atomic::Ordering;
5534
5535    let name = shfunc.node.nam.clone(); // c:5827
5536    let flags = shfunc.node.flags; // c:5828
5537    let fname = dupstring(&name); // c:5829
5538    let _ = fname; // c:5829 (kept for parity)
5539
5540    // c:5835 — `queue_signals();` Lots of memory + global-state changes.
5541    queue_signals();
5542
5543    // c:5847-5848 — `marked_prog = shfunc->funcdef; useeprog(marked_prog);`
5544    // Pinned so a recursive unload doesn't free the eprog under us.
5545    // (Skipped: zshrs's shfunc holds a Box<Eprog>; Drop semantics
5546    // already pin until call ends. C does explicit refcount on
5547    // `funcdef->nref` via useeprog.)
5548
5549    // c:5856-5916 — Funcsave allocation + per-field snapshot.
5550    let funcsave_breaks = BREAKS.load(Ordering::Relaxed); // c:5859
5551    let funcsave_contflag = CONTFLAG.load(Ordering::Relaxed); // c:5860
5552    let funcsave_loops = LOOPS.load(Ordering::Relaxed); // c:5861
5553    let funcsave_lastval = LASTVAL.load(Ordering::Relaxed); // c:5862
5554    let funcsave_numpipestats = {
5555        // c:5864
5556        NUMPIPESTATS
5557            .get_or_init(|| std::sync::Mutex::new(0))
5558            .lock()
5559            .map(|n| *n)
5560            .unwrap_or(0)
5561    };
5562    let funcsave_noerrexit = noerrexit.load(Ordering::Relaxed); // c:5865
5563                                                                // c:5866-5867 — trap_state PRIMED branch decrements trap_return.
5564    if TRAP_STATE.load(Ordering::Relaxed) == TRAP_STATE_PRIMED {
5565        // c:5866
5566        TRAP_RETURN.fetch_sub(1, Ordering::Relaxed); // c:5867
5567    }
5568    // c:5871 — `noerrexit &= ~NOERREXIT_RETURN;` — scope-clear of
5569    // return-suppress so a `return` inside the body fires errexit
5570    // checks normally.
5571    noerrexit.fetch_and(!NOERREXIT_RETURN, Ordering::Relaxed);
5572
5573    // c:5872-5880 — noreturnval branch: deep-copy pipestats so the
5574    // function body's pipestats writes are restored on exit.
5575    let funcsave_pipestats: Option<Vec<i32>> = if noreturnval {
5576        // c:5872
5577        let p = PIPESTATS.get_or_init(|| std::sync::Mutex::new([0; MAX_PIPESTATS]));
5578        p.lock().ok().map(|g| g[..funcsave_numpipestats].to_vec()) // c:5879 memcpy
5579    } else {
5580        None
5581    };
5582
5583    // c:5882-5896 — TRAPEXIT special case (deep-copy shfunc so
5584    // starttrapscope doesn't rug-pull). zshrs doesn't yet support
5585    // running TRAPEXIT directly via doshfunc; flagged for follow-up.
5586    // (Skip: name = "TRAPEXIT" path.)
5587    let _ = name.as_str(); // sentinel for the eventual port.
5588
5589    // c:5898 — `starttrapscope();` — canonical port at signals.rs:1135
5590    // tags SIGEXIT for deferred restoration at scope end.
5591    crate::ported::signals::starttrapscope();
5592    // c:5899 — `startpatternscope();`
5593    crate::ported::pattern::startpatternscope();
5594
5595    // c:5901 — `pptab = pparams;` — save outer positional params.
5596    let pptab: Vec<String> = crate::ported::builtin::PPARAMS
5597        .lock()
5598        .map(|p| p.clone())
5599        .unwrap_or_default();
5600
5601    // c:5902-5903 — non-undefined: `scriptname = dupstring(name);`
5602    let funcsave_scriptname = crate::ported::utils::scriptname_get();
5603    if (flags as u32 & PM_UNDEFINED) == 0 {
5604        // c:5902
5605        crate::ported::utils::set_scriptname(Some(dupstring(&name))); // c:5903
5606    }
5607
5608    // c:5904-5908 — `funcsave->zoptind = zoptind; ...` snapshot.
5609    // C zsh saves zoptind (the canonical OPTIND counter) and
5610    // zoptarg into the funcsave struct so OPTIND is implicitly
5611    // function-local: a `getopts` loop inside the function gets
5612    // its own counter that snaps back to the caller's on
5613    // function return. zshrs stores OPTIND/OPTARG in paramtab
5614    // as regular int/string params; snapshot them here and
5615    // restore at scope end. Bug #513.
5616    let funcsave_optind: Option<String> = crate::ported::params::getsparam("OPTIND");
5617    let funcsave_optarg: Option<String> = crate::ported::params::getsparam("OPTARG");
5618
5619    // c:5914 — `memcpy(funcsave->opts, opts, sizeof(opts));` — option
5620    // snapshot. Port wraps opts in OPTS_LIVE; capture the live state
5621    // here as a HashMap snapshot.
5622    let funcsave_opts = crate::ported::options::opt_state_snapshot();
5623
5624    // c:5915-5916 — `funcsave->emulation/sticky = emulation/sticky;`
5625    // Emulation snapshot pending the sticky-emulation port.
5626
5627    // c:5954-5969 — PM_TAGGED / PM_WARNNESTED option-override block.
5628    // Anonymous-function name comparison via pointer equality in C;
5629    // zshrs uses string equality. Skip until ANONYMOUS_FUNCTION_NAME
5630    // sentinel is ported.
5631
5632    // c:5970 — `funcsave->oflags = oflags;` — module-global tracking
5633    // function-attribute inheritance. Skip until oflags is ported.
5634
5635    // c:5977 — `opts[PRINTEXITVALUE] = 0;` — suppress printexitvalue
5636    // for inner commands; outer flag restored on exit.
5637    opt_state_set("printexitvalue", false);
5638
5639    // c:5978-5998 — pparams swap. C reads doshargs and constructs the
5640    // function's positional-param array. First arg is the function
5641    // name (regardless of FUNCTIONARGZERO); the rest become $1..$N.
5642    let funcsave_argv0: Option<String> = if !doshargs.is_empty() {
5643        // c:5978
5644        // c:5982-5985 — `pparams = x = zshcalloc(...)`.
5645        let positionals: Vec<String> = if doshargs.len() > 1 {
5646            doshargs[1..].to_vec()
5647        } else {
5648            Vec::new()
5649        };
5650        if let Ok(mut pp) = crate::ported::builtin::PPARAMS.lock() {
5651            *pp = positionals;
5652        }
5653        // c:5984-5987 — FUNCTIONARGZERO: save argzero, install
5654        // doshargs[0] (the function name).
5655        if isset(FUNCTIONARGZERO) {
5656            // c:5984
5657            let prev = crate::ported::utils::argzero();
5658            crate::ported::utils::set_argzero(Some(doshargs[0].clone())); // c:5986
5659            prev
5660        } else {
5661            None
5662        }
5663    } else {
5664        // c:5992-5997 — no args: empty pparams. argzero saved+dup'd.
5665        if let Ok(mut pp) = crate::ported::builtin::PPARAMS.lock() {
5666            *pp = Vec::new();
5667        }
5668        if isset(FUNCTIONARGZERO) {
5669            // c:5994
5670            let prev = crate::ported::utils::argzero();
5671            crate::ported::utils::set_argzero(prev.clone()); // c:5996 ztrdup(argzero)
5672            prev
5673        } else {
5674            None
5675        }
5676    };
5677
5678    // c:5999 — `++funcdepth;` — bumped on entry. Mirror via locallevel
5679    // since zshrs tracks function-call depth there.
5680    //
5681    // Plus the canonical startparamscope (c:6194 inside runshfunc).
5682    // zshrs's body_runner replaces runshfunc's `execode` call so the
5683    // startparamscope/endparamscope pair must wrap body_runner here,
5684    // not inside the closure. inc_locallevel is exactly startparamscope.
5685    inc_locallevel();
5686
5687    // c:6000-6004 — FUNCNEST check + `goto undoshfunc` on overflow.
5688    // Skip the runtime check (the zshrs fusevm doesn't recurse via
5689    // real stack frames so the depth limit is less critical), but
5690    // keep the comment so the C label `undoshfunc:` target is
5691    // visible — `goto undoshfunc;` here would jump straight to the
5692    // epilogue at the `undoshfunc:` label below.
5693
5694    // c:6005-6019 — funcstack frame push. The full C block:
5695    //   funcsave->fstack.name      = dupstring(name);
5696    //   funcsave->fstack.caller    = funcstack ? funcstack->name :
5697    //                                 dupstring(argv0 ? argv0 : argzero);
5698    //   funcsave->fstack.lineno    = lineno;
5699    //   funcsave->fstack.prev      = funcstack;
5700    //   funcsave->fstack.tp        = FS_FUNC;
5701    //   funcstack                  = &funcsave->fstack;
5702    //   funcsave->fstack.flineno   = shfunc->lineno;
5703    //   funcsave->fstack.filename  = getshfuncfile(shfunc);
5704    let lineno_now = crate::ported::input::lineno.with(|c| c.get()) as i64;
5705    let (caller, prev_tp): (Option<String>, Option<i32>) = {
5706        let stk = FUNCSTACK.lock().unwrap_or_else(|e| e.into_inner());
5707        if let Some(p) = stk.last() {
5708            (Some(p.name.clone()), Some(p.tp))
5709        } else {
5710            // c:6011-6012 — outermost: argv0 (saved) or argzero global.
5711            let z = funcsave_argv0
5712                .clone()
5713                .or_else(crate::ported::utils::argzero);
5714            (z, None)
5715        }
5716    };
5717    // c:6018-6019 — flineno: shfunc->lineno (function def line)
5718    let flineno = shfunc.lineno;
5719    let filename = shfunc.filename.clone().or_else(|| Some(String::new()));
5720    {
5721        let frame = crate::ported::zsh_h::funcstack {
5722            prev: None,             // c:6014 (Vec-stack: index encodes link)
5723            name: dupstring(&name), // c:6005
5724            filename,               // c:6019
5725            caller,                 // c:6011
5726            flineno,                // c:6018
5727            lineno: lineno_now,     // c:6013
5728            tp: FS_FUNC,            // c:6015
5729        };
5730        let _ = prev_tp; // c:6011 (informational)
5731        let mut stack = FUNCSTACK.lock().unwrap_or_else(|e| e.into_inner());
5732        stack.push(frame); // c:6016 funcstack = &funcsave->fstack
5733    }
5734
5735    // c:6021-6042 — body execution. C: `runshfunc(prog, wrappers, name)`.
5736    // zshrs delegates to the body_runner closure (typically a fusevm
5737    // sub-VM run from the bridge). The closure returns the body's
5738    // exit status which becomes lastval.
5739    //
5740    // c:Src/exec.c:1251-1266 — push "shfunc" onto zsh_eval_context
5741    // so the body sees `${zsh_eval_context[*]}` containing the call
5742    // chain context. The execode-based path (c:1245-1282 port at
5743    // exec.rs:7092) already did this, but the fusevm body_runner
5744    // path skipped doshfunc's body_runner invocation without the
5745    // push. Bug #262 in docs/BUGS.md.
5746    //
5747    // Push BOTH the static `zsh_eval_context` (matches C's variable)
5748    // AND the paramtab array entry (what `${zsh_eval_context[*]}`
5749    // reads). Pop on every return path via the guard struct so
5750    // panics / early returns don't leak the entry.
5751    crate::vm_helper::push_zsh_eval_context("shfunc");
5752    struct EvalContextGuard;
5753    impl Drop for EvalContextGuard {
5754        fn drop(&mut self) {
5755            crate::vm_helper::pop_zsh_eval_context();
5756        }
5757    }
5758    let _eval_ctx_guard = EvalContextGuard;
5759    let body_status = body_runner();
5760    LASTVAL.store(body_status, Ordering::Relaxed);
5761
5762    // c:6043 — `doneshfunc:` label. The C `runshfunc` happy-path
5763    // falls through here from c:6042.
5764    // c:6044 — `funcstack = funcsave->fstack.prev;` — pop our frame.
5765    {
5766        let mut stack = FUNCSTACK.lock().unwrap_or_else(|e| e.into_inner());
5767        stack.pop();
5768    }
5769    // c:6045 — `undoshfunc:` label. Reached either by fall-through
5770    // from c:6044 or by `goto undoshfunc;` from the FUNCNEST check
5771    // at c:6003. Tail epilogue follows.
5772
5773    // c:6046 — `--funcdepth;` — paired endparamscope (c:6200 inside
5774    // runshfunc) lives at c:6157 below as `endparamscope()`. Removed
5775    // the dec here so locallevel only decrements once per
5776    // function-call frame; double-dec was purging level-0 globals on
5777    // function exit (the `f() { x=foo; }; f; echo $x` regression).
5778
5779    // c:6047-6053 — retflag clear. C clears retflag and restores
5780    // outer breaks if a `return` fired.
5781    if RETFLAG.load(Ordering::SeqCst) != 0 {
5782        // c:6047
5783        RETFLAG.store(0, Ordering::SeqCst); // c:6051
5784        BREAKS.store(funcsave_breaks, Ordering::SeqCst); // c:6052
5785    }
5786
5787    // c:6054-6058 — pparams + argv0 restore.
5788    if let Ok(mut pp) = crate::ported::builtin::PPARAMS.lock() {
5789        *pp = pptab; // c:6059 pparams = pptab
5790    }
5791    if let Some(saved) = funcsave_argv0 {
5792        // c:6055
5793        crate::ported::utils::set_argzero(Some(saved)); // c:6057
5794    }
5795
5796    // c:Src/exec.c:6060-6062 — `zoptind = funcsave->zoptind;
5797    // zoptarg = funcsave->zoptarg;`. Restore OPTIND/OPTARG so
5798    // an inner getopts loop's counter mutations don't leak to
5799    // the caller. Bug #513.
5800    if let Some(saved) = funcsave_optind {
5801        if let Ok(n) = saved.parse::<i64>() {
5802            crate::ported::params::setiparam("OPTIND", n);
5803        } else {
5804            crate::ported::params::setsparam("OPTIND", &saved);
5805        }
5806    }
5807    if let Some(saved) = funcsave_optarg {
5808        crate::ported::params::setsparam("OPTARG", &saved);
5809    }
5810
5811    // c:6064 — `scriptname = funcsave->scriptname;`
5812    crate::ported::utils::set_scriptname(funcsave_scriptname);
5813
5814    // c:6067 — `endpatternscope();`
5815    crate::ported::pattern::endpatternscope();
5816
5817    // c:6078-6102 — LOCALOPTIONS restore. Re-apply the snapshot when
5818    // localoptions was set inside the body.
5819    if crate::ported::options::opt_state_get("localoptions").unwrap_or(false) {
5820        // c:6091 memcpy(opts, funcsave->opts, sizeof(opts)) — full restore.
5821        let current = crate::ported::options::opt_state_snapshot();
5822        for (k, _) in &current {
5823            if !funcsave_opts.contains_key(k) {
5824                crate::ported::options::opt_state_unset(k);
5825            }
5826        }
5827        for (k, v) in &funcsave_opts {
5828            opt_state_set(k, *v);
5829        }
5830    } else {
5831        // c:6097-6101 — non-LOCALOPTIONS: restore only the always-
5832        // restored subset (XTRACE / PRINTEXITVALUE / LOCALOPTIONS /
5833        // LOCALLOOPS / WARNNESTEDVAR).
5834        for opt in [
5835            "xtrace",
5836            "printexitvalue",
5837            "localoptions",
5838            "localloops",
5839            "warnnestedvar",
5840        ] {
5841            if let Some(v) = funcsave_opts.get(opt) {
5842                opt_state_set(opt, *v);
5843            }
5844        }
5845    }
5846
5847    // c:6104-6112 — LOCALLOOPS warn-on-active-continue/break + restore
5848    // breaks/contflag/loops snapshot. Skip the warn lines for now;
5849    // restore the bookkeeping.
5850    if crate::ported::options::opt_state_get("localloops").unwrap_or(false) {
5851        BREAKS.store(funcsave_breaks, Ordering::SeqCst); // c:6109
5852        CONTFLAG.store(funcsave_contflag, Ordering::SeqCst); // c:6110
5853        LOOPS.store(funcsave_loops, Ordering::SeqCst); // c:6111
5854    }
5855
5856    // c:Src/exec.c:6195-6200 — C's runshfunc calls endparamscope()
5857    // BEFORE returning to doshfunc, which then calls endtrapscope()
5858    // at c:6114. So locallevel is ALREADY one less by the time
5859    // endtrapscope's pop loop compares saved local > current.
5860    //
5861    // Bug #80 in docs/BUGS.md: zshrs had endtrapscope FIRST (here at
5862    // line 5774), endparamscope LATER. That left locallevel at the
5863    // function's own level when endtrapscope ran, so saved entries
5864    // tagged with `local == current_function_level` failed the
5865    // `local > locallevel` pop condition. Nested EXIT traps
5866    // (saved at deeper level) never restored at the outer fn's
5867    // endtrapscope — outer EXIT traps fired at script exit instead.
5868    //
5869    // Decrement locallevel via a peer-of-endparamscope locallevel
5870    // bookkeeping call before endtrapscope, then leave the real
5871    // endparamscope at its current site below so the param scope
5872    // unwind still happens after the exit_pending check.
5873    {
5874        use crate::ported::params::locallevel as ll;
5875        let prev = ll.load(Ordering::Relaxed);
5876        if prev > 0 {
5877            ll.store(prev - 1, Ordering::Relaxed);
5878        }
5879        crate::ported::signals::endtrapscope();
5880        // Re-bump so the existing endparamscope() call below sees the
5881        // same pre-decrement state and its own internal decrement
5882        // lands at the right value (mirrors C's "endparamscope already
5883        // happened" comment at c:6135-6136 — the C order is endparam
5884        // (inside runshfunc) → endtrap (in doshfunc); we keep that
5885        // logical ordering for endtrapscope only, without disturbing
5886        // the rest of the epilogue's level math).
5887        ll.store(prev, Ordering::Relaxed);
5888    }
5889
5890    // c:6116-6117 — TRAP_STATE_PRIMED branch: bump trap_return back.
5891    if TRAP_STATE.load(Ordering::Relaxed) == TRAP_STATE_PRIMED {
5892        // c:6116
5893        TRAP_RETURN.fetch_add(1, Ordering::Relaxed); // c:6117
5894    }
5895
5896    // c:6118 — `ret = lastval;`
5897    let ret = LASTVAL.load(Ordering::Relaxed);
5898
5899    // c:6119 — `noerrexit = funcsave->noerrexit;`
5900    noerrexit.store(funcsave_noerrexit, Ordering::Relaxed);
5901
5902    // c:6120-6124 — noreturnval: restore lastval + pipestats. C runs
5903    // the function for side-effects only; outer lastval/pipestats
5904    // should reflect the PRE-call state.
5905    if noreturnval {
5906        // c:6120
5907        LASTVAL.store(funcsave_lastval, Ordering::Relaxed); // c:6121
5908        if let Some(saved_ps) = funcsave_pipestats {
5909            let n = NUMPIPESTATS.get_or_init(|| std::sync::Mutex::new(0));
5910            if let Ok(mut nguard) = n.lock() {
5911                *nguard = funcsave_numpipestats; // c:6122
5912            }
5913            let p = PIPESTATS.get_or_init(|| std::sync::Mutex::new([0; MAX_PIPESTATS]));
5914            if let Ok(mut pguard) = p.lock() {
5915                for (i, v) in saved_ps.iter().enumerate() {
5916                    if i < pguard.len() {
5917                        pguard[i] = *v; // c:6123 memcpy
5918                    }
5919                }
5920            }
5921        }
5922    }
5923
5924    // c:Src/exec.c doshfunc → endparamscope — restore local-typeset
5925    // params installed during the body. In C, this is called inside
5926    // runshfunc (c:6200) BEFORE control returns to doshfunc's tail —
5927    // so by the time the exit_pending check runs at c:6141,
5928    // locallevel has ALREADY been decremented. The c:6135-6136
5929    // comment explicitly states "The endparamscope() has already
5930    // happened, hence the +1 here."
5931    //
5932    // The previous Rust ordering placed endparamscope AFTER the
5933    // exit_pending check, which compared exit_level against the
5934    // un-decremented locallevel. For `foo() { exit 7; }; foo`:
5935    //   exit_level=1, cur_locallevel=1 (pre-decrement)
5936    //   check: exit_level >= cur_locallevel + 1 ⟹ 1 >= 2 = false
5937    // The function returned cleanly without triggering zexit, and
5938    // the shell exited 0 instead of 7. Moving endparamscope before
5939    // the check matches C and makes the off-by-one resolve.
5940    endparamscope();
5941
5942    // c:6128 — `unqueue_signals();`
5943    unqueue_signals();
5944
5945    // c:6135-6155 — exit_pending branch: when an `exit` was queued
5946    // inside the function body and we've unwound enough scopes for
5947    // it to take effect, either keep unwinding (still inside a
5948    // nested function) or actually exit the shell.
5949    let exit_pending = crate::ported::builtin::EXIT_PENDING.load(Ordering::Relaxed);
5950    let exit_level = crate::ported::builtin::EXIT_LEVEL.load(Ordering::Relaxed);
5951    let cur_locallevel = locallevel.load(Ordering::Relaxed) as i32;
5952    let cur_forklevel = FORKLEVEL.load(Ordering::Relaxed);
5953    let in_exit_trap = crate::ported::signals::in_exit_trap.load(Ordering::Relaxed); // c:Src/signals.c:63
5954    if exit_pending != 0 && exit_level >= cur_locallevel + 1 && in_exit_trap == 0 {
5955        // c:6141
5956        if cur_locallevel > cur_forklevel {
5957            // c:6143 — still inside a nested function: keep unwinding.
5958            RETFLAG.store(1, Ordering::Relaxed); // c:6144
5959            BREAKS.store(LOOPS.load(Ordering::Relaxed), Ordering::Relaxed); // c:6145
5960        } else {
5961            // c:6151 — out of all functions: exit for real.
5962            crate::ported::builtin::STOPMSG.store(1, Ordering::Relaxed); // c:6151
5963            let val = EXIT_VAL.load(Ordering::Relaxed);
5964            crate::ported::builtin::zexit(val, crate::ported::zsh_h::ZEXIT_NORMAL);
5965            // c:6152
5966        }
5967    }
5968
5969    ret // c:6157 return ret
5970}
5971
5972/// `TRAP_STATE_PRIMED` per `Src/signals.h:55` — doshfunc tests this
5973/// to decide whether to bump trap_return on entry/exit. Local
5974/// const here because the canonical zsh_h port doesn't carry
5975/// trap-state numeric constants yet.
5976const TRAP_STATE_PRIMED: i32 = 2; // c:Src/signals.h:55
5977
5978/// Port of `execfuncdef(Estate state, Eprog redir_prog)` from
5979/// `Src/exec.c:5309-5494`. Define a shell function: extract
5980/// name(s)+body from the wordcode payload, allocate the Shfunc,
5981/// install into `shfunctab` (named), or execute immediately (anon).
5982#[allow(non_snake_case)]
5983pub fn execfuncdef(state: &mut estate, mut redir_prog: Option<crate::ported::zsh_h::Eprog>) -> i32 {
5984    use crate::ported::hashtable::{dircache_set, shfunctab_lock};
5985    use crate::ported::jobs::{getsigidx, removetrapnode};
5986    use crate::ported::parse::{dupeprog, freeeprog, incrdumpcount};
5987    use crate::ported::signals::settrap;
5988    use crate::ported::utils::scriptfilename_get;
5989    use crate::ported::zsh_h::{
5990        eprog as eprog_t, hashnode, patprog as patprog_t, shfunc as shfunc_t, Patprog,
5991        EC_DUPTOK as _, EF_HEAP, EF_MAP, EF_REAL, FS_EVAL, FS_FUNC, PM_ANONYMOUS, PM_TAGGED,
5992        PM_TAGGED_LOCAL, PRINTEXITVALUE, SHINSTDIN, ZSIG_FUNC,
5993    };
5994    // c:5311 — `Shfunc shf;`
5995    let mut shf: Box<shfunc_t>;
5996    // c:5312 — `char *s = NULL;`
5997    let mut s: Option<String> = None;
5998    // c:5313 — `int signum, nprg, sbeg, nstrs, npats, do_tracing, len, plen, i, htok = 0, ret = 0;`
5999    let mut signum: i32;
6000    let nprg: i32;
6001    let sbeg: i32;
6002    let nstrs: i32;
6003    let npats: i32;
6004    let do_tracing: i32;
6005    let len: i32;
6006    let plen: i32;
6007    // `i` — C loop counter for pp stamp; Rust uses .map().collect().
6008    let mut htok: i32 = 0;
6009    let mut ret: i32 = 0;
6010    // c:5314 — `int anon_func = 0;`
6011    let mut anon_func: i32 = 0;
6012    // c:5315 — `Wordcode beg = state->pc, end;`
6013    let _beg: usize = state.pc;
6014    let mut end: usize;
6015    // c:5316 — `Eprog prog;`
6016    // (allocated inline per-iter below; no upfront binding needed)
6017    // c:5317 — `Patprog *pp;` — handled by Vec construction.
6018    // c:5318 — `LinkList names;`
6019    let names: Vec<String>;
6020    // c:5319 — `int tracing_flags;`
6021    let tracing_flags: i32;
6022
6023    // c:5321 — `end = beg + WC_FUNCDEF_SKIP(state->pc[-1]);`
6024    end = state.pc + WC_FUNCDEF_SKIP(state.prog.prog[state.pc.wrapping_sub(1)]) as usize;
6025    // c:5322 — `names = ecgetlist(state, *state->pc++, EC_DUPTOK, &htok);`
6026    let num = state.prog.prog[state.pc] as usize;
6027    state.pc += 1;
6028    names = ecgetlist(state, num, EC_DUPTOK, Some(&mut htok));
6029    // c:5323 — `sbeg = *state->pc++;`
6030    sbeg = state.prog.prog[state.pc] as i32;
6031    state.pc += 1;
6032    // c:5324 — `nstrs = *state->pc++;`
6033    nstrs = state.prog.prog[state.pc] as i32;
6034    state.pc += 1;
6035    // c:5325 — `npats = *state->pc++;`
6036    npats = state.prog.prog[state.pc] as i32;
6037    state.pc += 1;
6038    // c:5326 — `do_tracing = *state->pc++;`
6039    do_tracing = state.prog.prog[state.pc] as i32;
6040    state.pc += 1;
6041
6042    // c:5328 — `nprg = (end - state->pc);`
6043    nprg = end.saturating_sub(state.pc) as i32;
6044    // c:5329 — `plen = nprg * sizeof(wordcode);`
6045    plen = nprg.saturating_mul(size_of::<wordcode>() as i32);
6046    // c:5330 — `len = plen + (npats * sizeof(Patprog)) + nstrs;`
6047    len = plen + npats.saturating_mul(size_of::<usize>() as i32) + nstrs;
6048    // c:5331 — `tracing_flags = do_tracing ? PM_TAGGED_LOCAL : 0;`
6049    tracing_flags = if do_tracing != 0 {
6050        PM_TAGGED_LOCAL as i32
6051    } else {
6052        0
6053    };
6054
6055    // c:5333-5339 — htok name substitution.
6056    let mut names_mut: Vec<String> = names;
6057    if htok != 0 && !names_mut.is_empty() {
6058        execsubst(&mut names_mut); // c:5334
6059        if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
6060            // c:5335
6061            state.pc = end; // c:5336
6062            return 1; // c:5337
6063        }
6064    }
6065
6066    // c:5341-5342 DPUTS — debug assertion (anon + redir simultaneously).
6067    // Not portable as panic; left as comment.
6068
6069    // c:5343 — `while (!names || (s = (char *) ugetnode(names))) {`
6070    // num==0 → anon (no names); else iterate names.
6071    let mut names_iter = names_mut.into_iter();
6072    loop {
6073        let no_names = num == 0;
6074        if !no_names {
6075            // c:5343 — `s = ugetnode(names)`; break when list exhausted.
6076            match names_iter.next() {
6077                Some(nm) => s = Some(nm),
6078                None => break,
6079            }
6080        }
6081        // c:5344-5374 — Eprog alloc.
6082        let prog: Box<eprog_t>;
6083        let dump_present = state.prog.dump.is_some();
6084        let make_pat = || -> Patprog {
6085            // c:5375-5376 `*pp = dummy_patprog1;` — sentinel slot.
6086            Box::new(patprog_t {
6087                startoff: 0,
6088                size: 0,
6089                mustoff: 0,
6090                patmlen: 0,
6091                globflags: 0,
6092                globend: 0,
6093                flags: 0,
6094                patnpar: 0,
6095                patstartch: 0,
6096            })
6097        };
6098        if no_names {
6099            // c:5345-5346 — `zhalloc`, `nref = -1`.
6100            // c:5355-5357 — EF_HEAP, no dump, npats pats on heap.
6101            let pats: Vec<Patprog> = (0..npats).map(|_| make_pat()).collect();
6102            let prog_words: Vec<wordcode> = state.prog.prog[state.pc..end].to_vec();
6103            // c:5365 — `prog->strs = state->strs + sbeg;`
6104            let strs_tail = state.strs.as_ref().map(|t| {
6105                let off = (sbeg as usize).min(t.len());
6106                t[off..].to_string()
6107            });
6108            prog = Box::new(eprog_t {
6109                flags: EF_HEAP,
6110                len,
6111                npats,
6112                nref: -1, // c:5346
6113                pats,
6114                prog: prog_words,
6115                strs: strs_tail,
6116                shf: None,  // c:5377
6117                dump: None, // c:5356
6118            });
6119        } else if dump_present {
6120            // c:5358-5363 — EF_MAP path: refcount the dump, allocate
6121            // pats permanent, reuse `state->pc` slice in place.
6122            if let Some(dp) = state.prog.dump.as_deref() {
6123                incrdumpcount(dp); // c:5360
6124            }
6125            let pats: Vec<Patprog> = (0..npats).map(|_| make_pat()).collect();
6126            let prog_words: Vec<wordcode> = state.prog.prog[state.pc..end].to_vec();
6127            let strs_tail = state.strs.as_ref().map(|t| {
6128                let off = (sbeg as usize).min(t.len());
6129                t[off..].to_string()
6130            });
6131            prog = Box::new(eprog_t {
6132                flags: EF_MAP, // c:5359
6133                len,
6134                npats,
6135                nref: 1, // c:5349
6136                pats,
6137                prog: prog_words,
6138                strs: strs_tail,
6139                shf: None,                     // c:5377
6140                dump: state.prog.dump.clone(), // c:5361
6141            });
6142        } else {
6143            // c:5366-5374 — EF_REAL: copy wordcode + strs into a
6144            // freshly-owned eprog (no shared dump backing).
6145            let pats: Vec<Patprog> = (0..npats).map(|_| make_pat()).collect();
6146            let pc_end = state.pc + nprg as usize;
6147            let prog_words: Vec<wordcode> = state.prog.prog[state.pc..pc_end].to_vec();
6148            // c:5373 — `memcpy(prog->strs, state->strs + sbeg, nstrs);`
6149            let strs_copy = state.strs.as_ref().map(|t| {
6150                let off = (sbeg as usize).min(t.len());
6151                let n_avail = t.len().saturating_sub(off);
6152                let take = (nstrs as usize).min(n_avail);
6153                t[off..off + take].to_string()
6154            });
6155            prog = Box::new(eprog_t {
6156                flags: EF_REAL, // c:5367
6157                len,
6158                npats,
6159                nref: 1, // c:5349
6160                pats,
6161                prog: prog_words,
6162                strs: strs_copy,
6163                shf: None,  // c:5377
6164                dump: None, // c:5371
6165            });
6166        }
6167
6168        // c:5379-5381 — Shfunc alloc + funcdef + tracing flags.
6169        shf = Box::new(shfunc_t {
6170            node: hashnode {
6171                next: None,
6172                nam: String::new(),
6173                flags: tracing_flags,
6174            },
6175            filename: scriptfilename_get(), // c:5383 `ztrdup(scriptfilename)`
6176            // c:5384-5388 — funcstack top FS_FUNC/FS_EVAL → flineno+lineno
6177            // else just lineno.
6178            lineno: {
6179                let cur_lineno = crate::ported::input::lineno.with(|l| l.get()) as i64;
6180                if let Ok(stk) = crate::ported::modules::parameter::FUNCSTACK.lock() {
6181                    if let Some(top) = stk.last() {
6182                        if top.tp == FS_FUNC || top.tp == FS_EVAL {
6183                            top.flineno + cur_lineno
6184                        } else {
6185                            cur_lineno
6186                        }
6187                    } else {
6188                        cur_lineno
6189                    }
6190                } else {
6191                    cur_lineno
6192                }
6193            },
6194            funcdef: Some(prog), // c:5380
6195            redir: None,
6196            sticky: None,
6197            body: None,
6198        });
6199        // c:5396-5401 — redir_prog ownership.
6200        // C: `if (names && nonempty(names) && redir_prog) shf->redir = dupeprog(redir_prog,0)`
6201        // else `shf->redir = redir_prog; redir_prog = 0;`
6202        // "nonempty(names)" means there's a NEXT name still to consume —
6203        // i.e. peek the iterator.
6204        if !no_names && names_iter.len() > 0 && redir_prog.is_some() {
6205            // c:5397 — dupe so each earlier name gets its own copy; the
6206            // last name (when iterator drains) gets the original.
6207            if let Some(rp) = redir_prog.as_deref() {
6208                shf.redir = Some(Box::new(dupeprog(rp, false)));
6209            }
6210        } else {
6211            // c:5399-5400 — last name (or anon) takes original.
6212            shf.redir = redir_prog.take();
6213        }
6214        // c:5402 — `shfunc_set_sticky(shf);`
6215        shfunc_set_sticky(&mut shf);
6216
6217        if no_names {
6218            // c:5404-5457 — anonymous function: execute immediately.
6219            // `LinkList args;` c:5409
6220            let mut args: Vec<String>;
6221
6222            anon_func = 1; // c:5411
6223            shf.node.flags |= PM_ANONYMOUS as i32; // c:5412
6224
6225            state.pc = end; // c:5414
6226                            // c:5415 — `end += *state->pc++;`
6227            end += state.prog.prog[state.pc] as usize;
6228            state.pc += 1;
6229            // c:5416 — `args = ecgetlist(state, *state->pc++, EC_DUPTOK, &htok);`
6230            let arg_count = state.prog.prog[state.pc] as usize;
6231            state.pc += 1;
6232            args = ecgetlist(state, arg_count, EC_DUPTOK, Some(&mut htok));
6233
6234            // c:5418-5429 — htok arg subst + cleanup-on-error.
6235            if htok != 0 && !args.is_empty() {
6236                execsubst(&mut args); // c:5419
6237                if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
6238                    // c:5421 — `freeeprog(shf->funcdef);`
6239                    if let Some(mut fd) = shf.funcdef.take() {
6240                        freeeprog(&mut fd);
6241                    }
6242                    if shf.redir.is_some() {
6243                        // c:5422-5423 — "shouldn't be" anon+redir, but free if so.
6244                        if let Some(mut rd) = shf.redir.take() {
6245                            freeeprog(&mut rd);
6246                        }
6247                    }
6248                    dircache_set(&mut shf.filename, None); // c:5424
6249                    drop(shf); // c:5425 `zfree(shf, sizeof(*shf));`
6250                    state.pc = end; // c:5426
6251                    return 1; // c:5427
6252                }
6253            }
6254
6255            // c:5431-5432 — `setunderscore` to last arg (or "").
6256            let under_val = if !args.is_empty() {
6257                args.last().cloned().unwrap_or_default()
6258            } else {
6259                String::new()
6260            };
6261            setunderscore(&under_val);
6262
6263            // c:5434-5435 — `if (!args) args = newlinklist();`
6264            // (Rust Vec is never null; no-op.)
6265            shf.node.nam = ANONYMOUS_FUNCTION_NAME.to_string(); // c:5436
6266                                                                // c:5437 — `pushnode(args, shf->node.nam);` — prepend.
6267            args.insert(0, shf.node.nam.clone());
6268
6269            execshfunc(&mut shf, &mut args); // c:5439
6270            ret = LASTVAL.load(Ordering::Relaxed); // c:5440
6271
6272            // c:5442-5450 — PRINTEXITVALUE+SHINSTDIN exit report.
6273            if isset(PRINTEXITVALUE) && isset(SHINSTDIN) && ret != 0 {
6274                eprintln!("zsh: exit {}", ret); // c:5445/5447
6275            }
6276
6277            // c:5452-5456 — cleanup.
6278            if let Some(mut fd) = shf.funcdef.take() {
6279                freeeprog(&mut fd);
6280            }
6281            if let Some(mut rd) = shf.redir.take() {
6282                // c:5453-5454 — "shouldn't be" but free if present.
6283                freeeprog(&mut rd);
6284            }
6285            dircache_set(&mut shf.filename, None); // c:5455
6286            drop(shf); // c:5456 `zfree(shf, sizeof(*shf));`
6287            break; // c:5457
6288        } else {
6289            // c:5458-5484 — named function path.
6290            let nm = s.as_deref().unwrap_or("");
6291            // c:5460-5475 — TRAP* signal-trap install.
6292            if nm.len() > 4 && nm.starts_with("TRAP") {
6293                if let Some(sn) = getsigidx(&nm[4..]) {
6294                    signum = sn;
6295                    // c:5462 — `if (settrap(signum, NULL, ZSIG_FUNC))`
6296                    if settrap(signum, None, ZSIG_FUNC) != 0 {
6297                        if let Some(mut fd) = shf.funcdef.take() {
6298                            freeeprog(&mut fd); // c:5463
6299                        }
6300                        dircache_set(&mut shf.filename, None); // c:5464
6301                        drop(shf); // c:5465
6302                        state.pc = end; // c:5466
6303                        return 1; // c:5467
6304                    }
6305                    // c:5474 — `removetrapnode(signum);`
6306                    removetrapnode(signum);
6307                    // c:Src/signals.c::settrap → unsettrap →
6308                    // removetrap also clears sigfuncs[sig] (the C
6309                    // string-form trap slot). zshrs's port stores
6310                    // string-form bodies in a separate
6311                    // `traps_table` HashMap not touched by
6312                    // removetrap. Drop the string-form entry here
6313                    // so dotrap's fallback doesn't double-dispatch
6314                    // when a TRAPxxx function REPLACES an
6315                    // existing `trap '...' SIG` registration. Bug
6316                    // #541 in docs/BUGS.md.
6317                    if let Ok(mut t) = crate::ported::builtin::traps_table().lock() {
6318                        t.remove(&nm[4..]);
6319                    }
6320                }
6321            }
6322            // c:5477-5482 — re-define-self trace flag propagate.
6323            if let Ok(stk) = crate::ported::modules::parameter::FUNCSTACK.lock() {
6324                if let Some(top) = stk.last() {
6325                    if top.tp == FS_FUNC && top.name == nm {
6326                        // c:5479 — `Shfunc old = shfunctab->getnode(s);`
6327                        if let Ok(rd) = shfunctab_lock().read() {
6328                            if let Some(old) = rd.get(nm) {
6329                                // c:5481 — propagate PM_TAGGED|PM_TAGGED_LOCAL.
6330                                shf.node.flags |=
6331                                    old.node.flags & (PM_TAGGED as i32 | PM_TAGGED_LOCAL as i32);
6332                            }
6333                        }
6334                    }
6335                }
6336            }
6337            // c:5483 — `shfunctab->addnode(shfunctab, ztrdup(s), shf);`
6338            shf.node.nam = nm.to_string();
6339            if let Ok(mut wr) = shfunctab_lock().write() {
6340                wr.add(*shf);
6341            }
6342        }
6343    }
6344    // c:5486-5487 — `if (!anon_func) setunderscore("");`
6345    if anon_func == 0 {
6346        setunderscore("");
6347    }
6348    // c:5488-5491 — leftover redir cleanup ("shouldn't happen").
6349    if let Some(mut rd) = redir_prog.take() {
6350        freeeprog(&mut rd);
6351    }
6352    // c:5492 — `state->pc = end;`
6353    state.pc = end;
6354    // c:5493 — `return ret;`
6355    ret
6356}
6357
6358/// Port of `execsimple(Estate state)` from `Src/exec.c:1290-1340`.
6359/// Fast-path for single-Simple commands that bypasses the full
6360/// `execcmd_exec` machinery.
6361pub fn execsimple(state: &mut estate) -> i32 {
6362    // c:1292 — `wordcode code = *state->pc++;`
6363    let mut code = state.prog.prog[state.pc];
6364    state.pc += 1;
6365    // c:1295-1296 — `if (errflag) return (lastval = 1);`
6366    if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
6367        LASTVAL.store(1, Ordering::Relaxed);
6368        return 1;
6369    }
6370    // c:1298-1299 — `if (!isset(EXECOPT)) return lastval = 0;`
6371    if !isset(crate::ported::zsh_h::EXECOPT) {
6372        LASTVAL.store(0, Ordering::Relaxed);
6373        return 0;
6374    }
6375    // c:1301-1303 — `if (!IN_EVAL_TRAP() && !ineval && code) lineno = code - 1;`
6376    // In evaluated traps, don't modify the line number (the trap
6377    // dispatcher restores it). `code` here is the wordcode-encoded
6378    // line number from the WC_SIMPLE entry at state.pc-1.
6379    if !crate::ported::zsh_h::IN_EVAL_TRAP()
6380        && crate::ported::builtin::INEVAL.load(Ordering::SeqCst) == 0
6381        && code != 0
6382    {
6383        crate::ported::input::lineno.with(|l| l.set((code as usize).saturating_sub(1)));
6384    }
6385    // c:1306 — `code = wc_code(*state->pc++);`
6386    code = wc_code(state.prog.prog[state.pc]);
6387    state.pc += 1;
6388    // c:1311-1312 — `otj = thisjob; thisjob = -1;`
6389    let otj = *THISJOB
6390        .get_or_init(|| std::sync::Mutex::new(-1))
6391        .lock()
6392        .unwrap();
6393    *THISJOB
6394        .get_or_init(|| std::sync::Mutex::new(-1))
6395        .lock()
6396        .unwrap() = -1;
6397    use crate::ported::zsh_h::{
6398        WC_ARITH, WC_CASE, WC_COND, WC_FOR, WC_REPEAT, WC_SELECT, WC_SUBSH, WC_TIMED, WC_TRY,
6399        WC_WHILE,
6400    };
6401    use crate::ported::zsh_h::{WC_ASSIGN, WC_CURSH};
6402    let lv = if code == WC_ASSIGN {
6403        // c:1315-1319 — assignment-only simple cmd path.
6404        // cmdoutval = 0; addvars(state, state->pc - 1, 0); setunderscore("");
6405        addvars(state, state.pc.saturating_sub(1), 0);
6406        setunderscore(""); // c:1317
6407        if isset(XTRACE) {
6408            eprintln!();
6409        }
6410        let ef = errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR;
6411        if ef != 0 {
6412            ef
6413        } else {
6414            0
6415        }
6416    } else {
6417        // c:1322-1330 — dispatch via execfuncs[code - WC_CURSH] or execfuncdef.
6418        let q = queue_signal_level();
6419        dont_queue_signals();
6420        let result = if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
6421            ERRFLAG_ERROR
6422        } else if code == WC_FUNCDEF {
6423            execfuncdef(state, None)
6424        } else {
6425            // c:5499 execfuncs[] table inlined — match the WC_* tag.
6426            match code {
6427                WC_CURSH => execcursh(state, 0),
6428                WC_SUBSH => execcursh(state, 0), // subshell folds to cursh body walk
6429                WC_FOR => execfor(state, 0),
6430                WC_SELECT => execselect(state, 0),
6431                WC_CASE => execcase(state, 0),
6432                WC_IF => execif(state, 0),
6433                WC_WHILE => execwhile(state, 0),
6434                WC_REPEAT => execrepeat(state, 0),
6435                WC_TIMED => exectime(state, 0),
6436                WC_COND => execcond(state, 0),
6437                WC_ARITH => execarith(state, 0),
6438                WC_TRY => exectry(state, 0),
6439                _ => 0,
6440            }
6441        };
6442        restore_queue_signals(q);
6443        result
6444    };
6445    // c:1334 — `thisjob = otj;`
6446    *THISJOB
6447        .get_or_init(|| std::sync::Mutex::new(-1))
6448        .lock()
6449        .unwrap() = otj;
6450    LASTVAL.store(lv, Ordering::Relaxed); // c:1336 — `return lastval = lv;`
6451    lv
6452}
6453
6454/// Port of `execlist(Estate state, int dont_change_job, int exiting)`
6455/// from `Src/exec.c:1349-1665`. Walks WC_LIST entries, dispatches each
6456/// sublist (WC_SUBLIST chain inlined per c:1525-1625, same as C —
6457/// there's no separate execsublist function), handles signal-trap
6458/// dispatch + ERREXIT propagation.
6459///
6460/// Body ports the structural skeleton faithfully (WC_LIST walk,
6461/// per-iteration breaks/retflag/errflag guards, ltype dispatch on
6462/// Z_END/Z_SYNC/Z_ASYNC, donetrap handling). The full signal queue
6463/// + DEBUGBEFORECMD trap machinery from c:1357-1500 is preserved
6464/// in shape with TODO-citations where dependent primitives aren't
6465/// yet ported.
6466pub fn execlist(state: &mut estate, dont_change_job: i32, mut exiting: i32) -> i32 {
6467    let mut last_status: i32 = 0;
6468    let mut donetrap: i32 = 0; // c:1352 — `static int donetrap;`
6469    let cj = *THISJOB
6470        .get_or_init(|| std::sync::Mutex::new(-1))
6471        .lock()
6472        .unwrap(); // c:1364 — `cj = thisjob;`
6473    let _ = dont_change_job; // c:1361 — restored on exit if nonzero.
6474                             // c:1380 — `code = *state->pc++;`
6475    if state.pc >= state.prog.prog.len() {
6476        return last_status;
6477    }
6478    let mut code = state.prog.prog[state.pc];
6479    state.pc += 1;
6480    // c:1382-1384 — empty list returns lastval = 0.
6481    if wc_code(code) != WC_LIST {
6482        LASTVAL.store(0, Ordering::Relaxed);
6483        return 0;
6484    }
6485    use crate::ported::zsh_h::{WC_LIST_SKIP, WC_LIST_TYPE, Z_END, Z_SIMPLE, Z_SYNC};
6486    // c:1385-1499 — main WC_LIST loop.
6487    while wc_code(code) == WC_LIST
6488        && BREAKS.load(Ordering::SeqCst) == 0
6489        && RETFLAG.load(Ordering::SeqCst) == 0
6490        && (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) == 0
6491    {
6492        let ltype = WC_LIST_TYPE(code) as i32;
6493        // c:1396 — `csp = cmdsp;` — snapshot cmdstack depth at start
6494        // of this WC_LIST iteration; restored at end so partial
6495        // cmdpush sequences (e.g. from execcond, execfuncs) don't
6496        // leak into the next sublist.
6497        let csp = crate::ported::prompt::CMDSTACK.with(|s| s.borrow().len());
6498        // c:1502-1509 — Z_SIMPLE fast-path.
6499        if (ltype & Z_SIMPLE as i32) != 0 {
6500            let next_pc = state.pc + WC_LIST_SKIP(code) as usize;
6501            let s = execsimple(state);
6502            last_status = s;
6503            state.pc = next_pc;
6504        } else {
6505            // c:1513-1523 — sublist chain.
6506            if state.pc >= state.prog.prog.len() {
6507                break;
6508            }
6509            code = state.prog.prog[state.pc];
6510            state.pc += 1;
6511            // c:1525-1625 — sublist chain (&&/|| operators) inlined.
6512            use crate::ported::zsh_h::{
6513                WC_SUBLIST_AND, WC_SUBLIST_END, WC_SUBLIST_NOT, WC_SUBLIST_OR, WC_SUBLIST_SIMPLE,
6514                WC_SUBLIST_SKIP,
6515            };
6516            let mut sub_code = code;
6517            let _ = dont_change_job;
6518            while wc_code(sub_code) == WC_SUBLIST {
6519                let flags = WC_SUBLIST_FLAGS(sub_code);
6520                let next = state.pc + WC_SUBLIST_SKIP(sub_code) as usize;
6521                let sl_type = WC_SUBLIST_TYPE(sub_code) as i32;
6522                let last1 = if WC_SUBLIST_TYPE(sub_code) == WC_SUBLIST_END {
6523                    exiting
6524                } else {
6525                    0
6526                };
6527                if flags == WC_SUBLIST_SIMPLE {
6528                    last_status = execsimple(state); // c:1605
6529                } else {
6530                    let _ = execpline(state, sub_code, sl_type, last1); // c:1607
6531                    last_status = LASTVAL.load(Ordering::Relaxed);
6532                }
6533                // c:1612 — `WC_SUBLIST_NOT` inverts status.
6534                if (flags & WC_SUBLIST_NOT) != 0 {
6535                    last_status = if last_status == 0 { 1 } else { 0 };
6536                    LASTVAL.store(last_status, Ordering::Relaxed);
6537                }
6538                state.pc = next;
6539                if WC_SUBLIST_TYPE(sub_code) == WC_SUBLIST_END {
6540                    break;
6541                }
6542                if state.pc >= state.prog.prog.len() {
6543                    break;
6544                }
6545                // c:1617-1623 — short-circuit on && / ||.
6546                if sl_type == WC_SUBLIST_AND as i32 && last_status != 0 {
6547                    while state.pc < state.prog.prog.len() {
6548                        let c = state.prog.prog[state.pc];
6549                        if wc_code(c) != WC_SUBLIST {
6550                            break;
6551                        }
6552                        state.pc = state.pc + 1 + WC_SUBLIST_SKIP(c) as usize;
6553                        if WC_SUBLIST_TYPE(c) == WC_SUBLIST_END {
6554                            break;
6555                        }
6556                    }
6557                    break;
6558                }
6559                if sl_type == WC_SUBLIST_OR as i32 && last_status == 0 {
6560                    while state.pc < state.prog.prog.len() {
6561                        let c = state.prog.prog[state.pc];
6562                        if wc_code(c) != WC_SUBLIST {
6563                            break;
6564                        }
6565                        state.pc = state.pc + 1 + WC_SUBLIST_SKIP(c) as usize;
6566                        if WC_SUBLIST_TYPE(c) == WC_SUBLIST_END {
6567                            break;
6568                        }
6569                    }
6570                    break;
6571                }
6572                sub_code = state.prog.prog[state.pc];
6573                state.pc += 1;
6574            }
6575        }
6576        // c:1593 — `cmdsp = csp;` — restore cmdstack depth to the
6577        // snapshot taken at start of iteration. Reverses any cmdpush
6578        // calls made by nested execcond / execfuncs / execcmd_exec
6579        // that didn't pop cleanly.
6580        crate::ported::prompt::CMDSTACK.with(|s| {
6581            let mut g = s.borrow_mut();
6582            if g.len() > csp {
6583                g.truncate(csp);
6584            }
6585        });
6586        // c:1626-1634 — donetrap is reset between sublists.
6587        donetrap = 0;
6588        // c:1640-1645 — fetch next WC_LIST header (or break out).
6589        if state.pc >= state.prog.prog.len() {
6590            break;
6591        }
6592        let next_code = state.prog.prog[state.pc];
6593        if wc_code(next_code) != WC_LIST {
6594            break;
6595        }
6596        state.pc += 1;
6597        code = next_code;
6598        // c:1389 — z_end means last sublist, exiting becomes 1 for tail-exec.
6599        if (ltype & Z_END as i32) != 0 {
6600            exiting = 1;
6601        }
6602    }
6603    // c:1659-1664 — cleanup: restore thisjob if dont_change_job, this_noerrexit=1.
6604    if dont_change_job != 0 {
6605        *THISJOB
6606            .get_or_init(|| std::sync::Mutex::new(-1))
6607            .lock()
6608            .unwrap() = cj;
6609    }
6610    let _ = donetrap;
6611    this_noerrexit.store(1, Ordering::Relaxed);
6612    LASTVAL.store(last_status, Ordering::Relaxed);
6613    last_status
6614}
6615
6616// WC_SUBLIST chain walk is inlined into execlist (per `Src/exec.c:1525-
6617// 1625`, the C source likewise inlines it — there's no `execsublist`
6618// function in zsh C).
6619
6620/// Port of `execcmd_getargs(LinkList preargs, LinkList args, int expand)`
6621/// from `Src/exec.c:2791-2806`. Transfer the first node of `args`
6622/// to `preargs`, performing `prefork` (singleton-list expansion) on
6623/// the way if `expand` is set. Used by `execcmd_exec` to pull the
6624/// command head one word at a time so prefix-modifier walking
6625/// (BINF_COMMAND, BINF_EXEC etc.) sees expanded names.
6626pub fn execcmd_getargs(preargs: &mut LinkList<String>, args: &mut LinkList<String>, expand: i32) {
6627    // c:2791
6628    if args.firstnode().is_none() {
6629        // c:2793 — `if (!firstnode(args)) return;`
6630        return;
6631    } else if expand != 0 {
6632        // c:2795
6633        // c:2796-2797 — `local_list0(svl); init_list0(svl);` —
6634        // stack-local single-bucket list. Rust uses a fresh
6635        // LinkList<String> per call.
6636        let mut svl: LinkList<String> = Default::default();
6637        // c:2799 — `addlinknode(&svl, uremnode(args, firstnode(args)));`
6638        if let Some(idx) = args.firstnode() {
6639            if let Some(head) = crate::ported::linklist::uremnode(args, idx) {
6640                svl.push_back(head);
6641            }
6642        }
6643        // c:2801 — `prefork(&svl, 0, NULL);`
6644        let mut rf = 0i32;
6645        prefork(&mut svl, 0, &mut rf);
6646        // c:2802 — `joinlists(preargs, &svl);`
6647        crate::ported::linklist::joinlists(preargs, &mut svl);
6648    } else {
6649        // c:2803-2804 — no-expand path: move head verbatim.
6650        if let Some(idx) = args.firstnode() {
6651            if let Some(head) = crate::ported::linklist::uremnode(args, idx) {
6652                preargs.push_back(head);
6653            }
6654        }
6655    }
6656}
6657
6658/// Port of `execcmd_fork(Estate state, int how, int type,
6659/// Wordcode varspc, LinkList *filelistp, char *text, int oautocont,
6660/// int close_if_forked)` from `Src/exec.c:2810-2893`.
6661///
6662/// Fork the current command into a child process: parent records
6663/// the pid + STTY env scan + addproc; child enters subshell, writes
6664/// `entersubsh_ret` back to parent through `synch` pipe, and returns
6665/// 0 so the caller can continue with the body.
6666///
6667/// `filelistp` out-arg is moved from `jobtab[thisjob].filelist`
6668/// only in the child branch (so the parent's `filelist` stays
6669/// untouched). Rust sig keeps the same C contract.
6670pub fn execcmd_fork(
6671    state: &mut estate,
6672    how: i32,
6673    typ: i32,
6674    varspc: Option<usize>,
6675    filelistp: &mut Vec<String>,
6676    text: &str,
6677    oautocont: i32,
6678    close_if_forked: i32,
6679) -> i32 {
6680    use crate::ported::signals::sigtrapped as sigtrapped_static;
6681    use crate::ported::signals_h::SIGEXIT;
6682    use crate::ported::zsh_h::{
6683        AUTOCONTINUE, BGNICE, WC_ASSIGN as ZWC_ASSIGN, WC_ASSIGN_NUM as ZWC_ASSIGN_NUM,
6684        WC_ASSIGN_SCALAR as ZWC_ASSIGN_SCALAR, WC_ASSIGN_TYPE as ZWC_ASSIGN_TYPE,
6685        WC_SUBSH as ZWC_SUBSH, ZSIG_IGNORED, Z_ASYNC,
6686    };
6687    // c:2810
6688    let pid: libc::pid_t; // c:2814
6689    let mut synch: [i32; 2] = [-1, -1]; // c:2815
6690    let flags: i32; // c:2815
6691    let mut esret: entersubsh_ret = entersubsh_ret::default(); // c:2816
6692                                                               // c:2817 — `struct timespec bgtime;` — bgtime is passed to zfork
6693                                                               // for accounting; the Rust zfork wrapper expects Option<&mut ZshTimespec>.
6694    let mut bgtime = ZshTimespec::default();
6695
6696    child_block(); // c:2819
6697    esret.gleader = -1; // c:2820
6698    esret.list_pipe_job = -1; // c:2821
6699
6700    // c:2823 — `if (pipe(synch) < 0) { zerr("pipe failed: %e", errno); return -1; }`
6701    if unsafe { libc::pipe(synch.as_mut_ptr()) } < 0 {
6702        zerr(&format!("pipe failed: {}", std::io::Error::last_os_error()));
6703        return -1; // c:2825
6704    }
6705    // c:2826 — `else if ((pid = zfork(&bgtime)) == -1) { ... }`
6706    pid = zfork(Some(&mut bgtime));
6707    if pid == -1 {
6708        unsafe {
6709            libc::close(synch[0]); // c:2827
6710            libc::close(synch[1]); // c:2828
6711        }
6712        LASTVAL.store(1, Ordering::Relaxed); // c:2829
6713        errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed); // c:2830
6714        return -1; // c:2831
6715    }
6716    if pid != 0 {
6717        // c:2833 — parent.
6718        unsafe { libc::close(synch[1]) }; // c:2834
6719                                          // c:2835 — `read_loop(synch[0], (char *)&esret, sizeof(esret));`
6720        let mut buf = [0u8; size_of::<entersubsh_ret>()];
6721        let _ = crate::ported::utils::read_loop(synch[0], &mut buf);
6722        // entersubsh_ret is two i32s; reconstruct from LE bytes (host order).
6723        if buf.len() >= 8 {
6724            esret.gleader = i32::from_ne_bytes([buf[0], buf[1], buf[2], buf[3]]);
6725            esret.list_pipe_job = i32::from_ne_bytes([buf[4], buf[5], buf[6], buf[7]]);
6726        }
6727        unsafe { libc::close(synch[0]) }; // c:2836
6728        if (how & Z_ASYNC as i32) != 0 {
6729            // c:2837 — `lastpid = (zlong) pid;`
6730            crate::ported::modules::clone::lastpid.store(pid, Ordering::Relaxed);
6731        } else {
6732            // c:2839 — `if (!jobtab[thisjob].stty_in_env && varspc)`.
6733            let thisjob_idx = {
6734                if let Some(m) = THISJOB.get() {
6735                    *m.lock().unwrap()
6736                } else {
6737                    -1
6738                }
6739            };
6740            // Examine the jobtab entry under lock.
6741            let stty_already = if thisjob_idx >= 0 {
6742                if let Some(jt) = JOBTAB.get() {
6743                    let guard = jt.lock().unwrap();
6744                    guard
6745                        .get(thisjob_idx as usize)
6746                        .map(|j| j.stty_in_env != 0)
6747                        .unwrap_or(true)
6748                } else {
6749                    true
6750                }
6751            } else {
6752                true
6753            };
6754            if !stty_already && varspc.is_some() {
6755                // c:2841-2851 — walk varspc looking for STTY=...
6756                let mut p = varspc.unwrap();
6757                loop {
6758                    if p >= state.prog.prog.len() {
6759                        break;
6760                    }
6761                    let ac = state.prog.prog[p];
6762                    if wc_code(ac) != ZWC_ASSIGN {
6763                        break;
6764                    }
6765                    // c:2845 — `if (!strcmp(ecrawstr(state->prog, p + 1, NULL), "STTY"))`
6766                    let name = ecrawstr(&state.prog, p + 1, None);
6767                    if name == "STTY" {
6768                        // c:2846 — `jobtab[thisjob].stty_in_env = 1;`
6769                        if let Some(jt) = JOBTAB.get() {
6770                            let mut guard = jt.lock().unwrap();
6771                            if let Some(j) = guard.get_mut(thisjob_idx as usize) {
6772                                j.stty_in_env = 1;
6773                            }
6774                        }
6775                        break; // c:2847
6776                    }
6777                    p += if ZWC_ASSIGN_TYPE(ac) == ZWC_ASSIGN_SCALAR {
6778                        3 // c:2849
6779                    } else {
6780                        (ZWC_ASSIGN_NUM(ac) + 2) as usize // c:2850
6781                    };
6782                }
6783            }
6784        }
6785        // c:2853 — `addproc(pid, text, 0, &bgtime, esret.gleader, esret.list_pipe_job);`
6786        if let Some(jt) = JOBTAB.get() {
6787            let mut guard = jt.lock().unwrap();
6788            let tj = {
6789                if let Some(m) = THISJOB.get() {
6790                    *m.lock().unwrap()
6791                } else {
6792                    -1
6793                }
6794            };
6795            if tj >= 0 {
6796                if let Some(j) = guard.get_mut(tj as usize) {
6797                    crate::ported::jobs::addproc(
6798                        j,
6799                        pid,
6800                        text,
6801                        false,
6802                        Some(std::time::Instant::now()),
6803                        esret.gleader,
6804                        esret.list_pipe_job,
6805                    );
6806                }
6807            }
6808        }
6809        // c:2854-2855 — `if (oautocont >= 0) opts[AUTOCONTINUE] = oautocont;`
6810        if oautocont >= 0 {
6811            opt_state_set("autocontinue", oautocont != 0);
6812            let _ = AUTOCONTINUE; // const referenced for parity
6813        }
6814        // c:2856 — `pipecleanfilelist(jobtab[thisjob].filelist, 1);`
6815        if let Some(jt) = JOBTAB.get() {
6816            let mut guard = jt.lock().unwrap();
6817            let tj = {
6818                if let Some(m) = THISJOB.get() {
6819                    *m.lock().unwrap()
6820                } else {
6821                    -1
6822                }
6823            };
6824            if tj >= 0 {
6825                if let Some(j) = guard.get_mut(tj as usize) {
6826                    crate::ported::jobs::pipecleanfilelist(j, true);
6827                }
6828            }
6829        }
6830        return pid; // c:2857
6831    }
6832
6833    // c:2860 — pid == 0 (child).
6834    unsafe { libc::close(synch[0]) }; // c:2861
6835    flags = (if (how & Z_ASYNC as i32) != 0 {
6836        esub::ASYNC
6837    } else {
6838        0
6839    }) | esub::PGRP; // c:2862
6840    let mut flags = flags;
6841    if typ != ZWC_SUBSH as i32 && (how & Z_ASYNC as i32) == 0 {
6842        flags |= esub::KEEPTRAP; // c:2864
6843    }
6844    if typ == ZWC_SUBSH as i32 && (how & Z_ASYNC as i32) == 0 {
6845        flags |= esub::JOB_CONTROL; // c:2866
6846    }
6847    // c:2867 — `*filelistp = jobtab[thisjob].filelist;`
6848    if let Some(jt) = JOBTAB.get() {
6849        let mut guard = jt.lock().unwrap();
6850        let tj = {
6851            if let Some(m) = THISJOB.get() {
6852                *m.lock().unwrap()
6853            } else {
6854                -1
6855            }
6856        };
6857        if tj >= 0 {
6858            if let Some(j) = guard.get_mut(tj as usize) {
6859                *filelistp = std::mem::take(&mut j.filelist);
6860            }
6861        }
6862    }
6863    entersubsh(flags, Some(&mut esret)); // c:2868
6864                                         // c:2869 — `write_loop(synch[1], &esret, sizeof(esret));`
6865    let mut buf = [0u8; 8];
6866    buf[0..4].copy_from_slice(&esret.gleader.to_ne_bytes());
6867    buf[4..8].copy_from_slice(&esret.list_pipe_job.to_ne_bytes());
6868    if write_loop(synch[1], &buf).map(|n| n as usize).unwrap_or(0) != buf.len() {
6869        zerr(&format!(
6870            "Failed to send entersubsh_ret report: {}",
6871            std::io::Error::last_os_error()
6872        ));
6873        return -1; // c:2871
6874    }
6875    unsafe { libc::close(synch[1]) }; // c:2873
6876    let _ = zclose(close_if_forked); // c:2874
6877
6878    // c:2876 — `if (sigtrapped[SIGINT] & ZSIG_IGNORED) holdintr();`
6879    let sigint_state = {
6880        let guard = sigtrapped_static.lock().unwrap();
6881        guard.get(libc::SIGINT as usize).copied().unwrap_or(0)
6882    };
6883    if (sigint_state & ZSIG_IGNORED) != 0 {
6884        crate::ported::signals::holdintr(); // c:2877
6885    }
6886    // c:2882 — `sigtrapped[SIGEXIT] = 0;` — EXIT traps don't fire in fork-child.
6887    {
6888        let mut guard = sigtrapped_static.lock().unwrap();
6889        if let Some(slot) = guard.get_mut(SIGEXIT as usize) {
6890            *slot = 0;
6891        }
6892    }
6893    // c:2884-2890 — `if ((how & Z_ASYNC) && isset(BGNICE)) nice(5)`.
6894    // Per-platform errno setter+reader: __error() on macOS,
6895    // __errno_location() on Linux. Without cfg gating Linux CI breaks.
6896    if (how & Z_ASYNC as i32) != 0 && isset(BGNICE) {
6897        #[cfg(target_os = "macos")]
6898        unsafe {
6899            *libc::__error() = 0;
6900            if libc::nice(5) == -1 && *libc::__error() != 0 {
6901                zwarn(&format!(
6902                    "nice(5) failed: {}",
6903                    std::io::Error::last_os_error()
6904                ));
6905            }
6906        }
6907        #[cfg(target_os = "linux")]
6908        unsafe {
6909            *libc::__errno_location() = 0;
6910            if libc::nice(5) == -1 && *libc::__errno_location() != 0 {
6911                zwarn(&format!(
6912                    "nice(5) failed: {}",
6913                    std::io::Error::last_os_error()
6914                ));
6915            }
6916        }
6917    }
6918    0 // c:2892
6919}
6920
6921/// Port of `execcmd_analyse(Estate state, Execcmd_params eparams)`
6922/// from `Src/exec.c:2733-2785`. Pre-execcmd_exec analysis pass:
6923/// walks the wordcode at `state->pc`, splits out redirs/varspc/args
6924/// without expanding (no prefork, no globbing), and fills `eparams`
6925/// so the caller (execcmd_exec at c:2901 or execpline2 at c:2013)
6926/// can branch on the command type before the real work.
6927pub fn execcmd_analyse(state: &mut estate, eparams: &mut crate::ported::zsh_h::execcmd_params) {
6928    use crate::ported::zsh_h::{
6929        WC_ASSIGN as ZWC_ASSIGN, WC_REDIR as ZWC_REDIR, WC_SIMPLE as ZWC_SIMPLE,
6930        WC_SIMPLE_ARGC as ZWC_SIMPLE_ARGC, WC_TYPESET as ZWC_TYPESET,
6931        WC_TYPESET_ARGC as ZWC_TYPESET_ARGC,
6932    };
6933    // c:2733
6934    let mut code: wordcode; // c:2735
6935    let mut i: i32; // c:2736
6936    let _ = i;
6937
6938    // c:2738 — `eparams->beg = state->pc;`
6939    eparams.beg = state.pc;
6940    // c:2739-2740 — `eparams->redir = (wc_code(*state->pc) == WC_REDIR ? ecgetredirs(state) : NULL);`
6941    eparams.redir =
6942        if state.pc < state.prog.prog.len() && wc_code(state.prog.prog[state.pc]) == ZWC_REDIR {
6943            Some(crate::ported::parse::ecgetredirs(state))
6944        } else {
6945            None
6946        };
6947    // c:2741-2748 — varspc walk (WC_ASSIGN chain).
6948    if state.pc < state.prog.prog.len() && wc_code(state.prog.prog[state.pc]) == ZWC_ASSIGN {
6949        cmdoutval.store(0, Ordering::Relaxed); // c:2742
6950        eparams.varspc = Some(state.pc); // c:2743
6951                                         // c:2744-2746 — `while (wc_code((code = *state->pc)) == WC_ASSIGN) state->pc += ...`
6952        loop {
6953            if state.pc >= state.prog.prog.len() {
6954                break;
6955            }
6956            code = state.prog.prog[state.pc];
6957            if wc_code(code) != ZWC_ASSIGN {
6958                break;
6959            }
6960            state.pc += if WC_ASSIGN_TYPE(code) == WC_ASSIGN_SCALAR {
6961                3 // c:2745
6962            } else {
6963                (WC_ASSIGN_NUM(code) + 2) as usize // c:2746
6964            };
6965        }
6966    } else {
6967        eparams.varspc = None; // c:2748
6968    }
6969
6970    // c:2750 — `code = *state->pc++;`
6971    if state.pc >= state.prog.prog.len() {
6972        eparams.args = None;
6973        eparams.assignspc = None;
6974        eparams.typ = 0;
6975        eparams.postassigns = 0;
6976        eparams.htok = 0;
6977        return;
6978    }
6979    code = state.prog.prog[state.pc];
6980    state.pc += 1;
6981
6982    // c:2752 — `eparams->type = wc_code(code);`
6983    eparams.typ = wc_code(code) as i32;
6984    // c:2753 — `eparams->postassigns = 0;`
6985    eparams.postassigns = 0;
6986
6987    // c:2755-2783 — switch on type. EC_DUP is used (not EC_DUPTOK)
6988    // per the comment at c:2755-2757.
6989    match eparams.typ as wordcode {
6990        x if x == ZWC_SIMPLE => {
6991            // c:2759-2763
6992            let mut htok = 0;
6993            let argc = ZWC_SIMPLE_ARGC(code) as usize;
6994            eparams.args = Some(ecgetlist(state, argc, EC_DUP, Some(&mut htok)));
6995            eparams.htok = htok;
6996            eparams.assignspc = None;
6997        }
6998        x if x == ZWC_TYPESET => {
6999            // c:2765-2777
7000            let mut htok = 0;
7001            let argc = ZWC_TYPESET_ARGC(code) as usize;
7002            eparams.args = Some(ecgetlist(state, argc, EC_DUP, Some(&mut htok)));
7003            eparams.htok = htok;
7004            // c:2768 — `eparams->postassigns = *state->pc++;`
7005            if state.pc < state.prog.prog.len() {
7006                eparams.postassigns = state.prog.prog[state.pc] as i32;
7007                state.pc += 1;
7008            }
7009            // c:2769 — `eparams->assignspc = state->pc;`
7010            eparams.assignspc = Some(state.pc);
7011            // c:2770-2776 — walk past the postassigns.
7012            let mut k = 0i32;
7013            while k < eparams.postassigns {
7014                if state.pc >= state.prog.prog.len() {
7015                    break;
7016                }
7017                code = state.prog.prog[state.pc];
7018                // c:2772-2773 DPUTS — assert wc_code == WC_ASSIGN; skipped.
7019                state.pc += if WC_ASSIGN_TYPE(code) == WC_ASSIGN_SCALAR {
7020                    3 // c:2774
7021                } else {
7022                    (WC_ASSIGN_NUM(code) + 2) as usize // c:2775
7023                };
7024                k += 1;
7025            }
7026        }
7027        _ => {
7028            // c:2779-2783 default.
7029            eparams.args = None;
7030            eparams.assignspc = None;
7031            eparams.htok = 0;
7032        }
7033    }
7034}
7035
7036/// Port of `char **zsh_eval_context;` from `Src/exec.c` (zsh.export:355).
7037/// Stack of `"context"` labels used by `eval`-style nested execution:
7038/// `bin_dot`, `bin_eval`, `execode`, autoloads. Each `execode(prog,
7039/// ..., "context")` pushes its label and pops on return.
7040pub static zsh_eval_context: std::sync::Mutex<Vec<String>> = std::sync::Mutex::new(Vec::new());
7041
7042/// Port of `static int donetrap;` from `Src/exec.c:1351`. Tracks
7043/// whether the ZERR trap has already fired for the current sublist.
7044/// C source resets to 0 at sublist start (c:1455) and sets to 1
7045/// after `dotrap(SIGZERR)` (c:1602). The check
7046/// `if (!this_noerrexit && !donetrap && !this_donetrap)` at c:1598
7047/// suppresses re-firing within the same sublist AND, crucially,
7048/// carries the "already fired" state across a function-call return
7049/// boundary so the outer caller's post-command check doesn't fire
7050/// ZERR a second time for the same logical error. Bug #303 in
7051/// docs/BUGS.md.
7052///
7053/// Reset at each top-level statement boundary via
7054/// `BUILTIN_DONETRAP_RESET` emitted by `compile_list`. Set after
7055/// `dotrap(SIGZERR)` fires inside `BUILTIN_ERREXIT_CHECK`.
7056pub static DONETRAP: std::sync::atomic::AtomicI32 = std::sync::atomic::AtomicI32::new(0);
7057
7058/// Port of `save_params(Estate state, Wordcode pc, LinkList *restore_p,
7059/// LinkList *remove_p)` from `Src/exec.c:4410-4458`. Walk WC_ASSIGN
7060/// chain at `pc`, snapshot each existing param into `restore_p` (so
7061/// the builtin/shfunc can restore them on return) and enqueue every
7062/// touched name in `remove_p` (so we know what to unset).
7063pub fn save_params(
7064    state: &mut estate,
7065    pc: usize,
7066    restore_p: &mut Vec<crate::ported::zsh_h::param>,
7067    remove_p: &mut Vec<String>,
7068) {
7069    use crate::ported::zsh_h::{
7070        PM_READONLY, PM_SPECIAL, WC_ASSIGN, WC_ASSIGN_NUM as ZWC_ASSIGN_NUM,
7071        WC_ASSIGN_SCALAR as ZWC_ASSIGN_SCALAR, WC_ASSIGN_TYPE as ZWC_ASSIGN_TYPE,
7072    };
7073    // c:4410 — `*restore_p = newlinklist();` — caller pre-allocates.
7074    // c:4417 — `*remove_p = newlinklist();` — caller pre-allocates.
7075    let mut p = pc;
7076    // c:4419 — `while (wc_code(ac = *pc) == WC_ASSIGN)`
7077    loop {
7078        if p >= state.prog.prog.len() {
7079            break;
7080        }
7081        let ac = state.prog.prog[p];
7082        if wc_code(ac) != WC_ASSIGN {
7083            break;
7084        }
7085        // c:4420 — `s = ecrawstr(state->prog, pc + 1, NULL);`
7086        let s = ecrawstr(&state.prog, p + 1, None);
7087        // c:4421 — `pm = paramtab->getnode(paramtab, s)`
7088        let pm_clone: Option<crate::ported::zsh_h::param> = {
7089            let tab = paramtab().read().unwrap();
7090            tab.get(&s).map(|b| (**b).clone())
7091        };
7092        if let Some(pm) = pm_clone {
7093            // c:4423-4424 — `if (pm->env) delenv(pm);`
7094            if pm.env.is_some() {
7095                crate::ported::params::delenv(&s);
7096            }
7097            // c:4425-4448 — copy if not readonly-special.
7098            if (pm.node.flags & PM_SPECIAL as i32) == 0 {
7099                // c:4426-4438 — regular param: deep copy via copyparam(tpm, pm, 0).
7100                let mut tpm = pm.clone();
7101                tpm.node.nam = s.clone();
7102                // copyparam with fakecopy=0 already done by the clone()
7103                // (Clone derives a deep copy of param fields).
7104                restore_p.push(tpm); // c:4451
7105            } else if (pm.node.flags & PM_READONLY as i32) == 0 {
7106                // c:4439-4448 — special-but-not-readonly: fakecopy=1.
7107                let mut tpm = pm.clone();
7108                tpm.node.nam = pm.node.nam.clone();
7109                restore_p.push(tpm); // c:4451
7110            }
7111            // c:4449 — `addlinknode(*remove_p, dupstring(s));`
7112            remove_p.push(s.clone());
7113        } else {
7114            // c:4453 — `addlinknode(*remove_p, dupstring(s));`
7115            remove_p.push(s.clone());
7116        }
7117        // c:4455 — `pc += (WC_ASSIGN_TYPE(ac) == WC_ASSIGN_SCALAR ? 3 : WC_ASSIGN_NUM(ac) + 2);`
7118        p += if ZWC_ASSIGN_TYPE(ac) == ZWC_ASSIGN_SCALAR {
7119            3
7120        } else {
7121            (ZWC_ASSIGN_NUM(ac) + 2) as usize
7122        };
7123    }
7124}
7125
7126/// Port of `restore_params(LinkList restorelist, LinkList removelist)`
7127/// from `Src/exec.c:4464-4528`. After the builtin/shfunc returns,
7128/// unset every name in removelist, then for each saved param in
7129/// restorelist re-install its values (PM_SPECIAL go through gsu
7130/// setfn; regular params re-enter paramtab as-is).
7131pub fn restore_params(restorelist: Vec<crate::ported::zsh_h::param>, removelist: Vec<String>) {
7132    use crate::ported::zsh_h::{PM_READONLY, PM_SPECIAL};
7133    // c:4470-4476 — `while ((s = ugetnode(removelist)))` — unset each.
7134    for s in &removelist {
7135        // c:4471 — `if ((pm = paramtab->getnode(paramtab, s)) && !(pm->node.flags & PM_SPECIAL))`
7136        let flags = {
7137            let tab = paramtab().read().unwrap();
7138            tab.get(s).map(|p| p.node.flags)
7139        };
7140        if let Some(f) = flags {
7141            if (f & PM_SPECIAL as i32) == 0 {
7142                // c:4473 — `pm->node.flags &= ~PM_READONLY;`
7143                let mut tab = paramtab().write().unwrap();
7144                if let Some(pm_mut) = tab.get_mut(s) {
7145                    pm_mut.node.flags &= !(PM_READONLY as i32);
7146                }
7147                // Drop write guard before calling unsetparam_pm.
7148                drop(tab);
7149                let mut tab = paramtab().write().unwrap();
7150                if let Some(pm_mut) = tab.get_mut(s) {
7151                    let _ = crate::ported::params::unsetparam_pm(pm_mut, 0, 0); // c:4474
7152                }
7153            }
7154        }
7155    }
7156    // c:4478-4523 — restore saved params.
7157    for pm in restorelist {
7158        // c:4481-4520 — PM_SPECIAL: route through gsu setfn.
7159        // c:4521-4523 — non-special: re-install via paramtab.
7160        if (pm.node.flags & PM_SPECIAL as i32) != 0 {
7161            // PM_SPECIAL restore: full path requires PM_TYPE dispatch
7162            // on gsu_s/i/f/a/h setfn. Each setfn fires the param's
7163            // canonical write hook. Pragmatic port: overwrite in
7164            // paramtab; daily-driver path rarely saves specials (those
7165            // are reserved-name vars like PATH/FPATH/etc. which can't
7166            // appear as `VAR=val cmd` prefix anyway).
7167            let mut tab = paramtab().write().unwrap();
7168            tab.insert(pm.node.nam.clone(), Box::new(pm));
7169        } else {
7170            // c:4521 — `paramtab->addnode(paramtab, ztrdup(pm->node.nam), pm);`
7171            let mut tab = paramtab().write().unwrap();
7172            tab.insert(pm.node.nam.clone(), Box::new(pm));
7173        }
7174    }
7175}
7176
7177/// Port of `void execode(Eprog p, int dont_change_job, int exiting,
7178/// char *context)` from `Src/exec.c:1245-1282`. Set up an `estate`
7179/// around the given Eprog and run `execlist`. Maintains the
7180/// `zsh_eval_context` stack so `$ZSH_EVAL_CONTEXT` reflects the
7181/// call chain.
7182pub fn execode(p: crate::ported::zsh_h::Eprog, dont_change_job: i32, exiting: i32, context: &str) {
7183    // c:1245
7184    let prog_ref = *p;
7185    // c:1247 — `struct estate s;`
7186    let mut s = estate {
7187        prog: Box::new(prog_ref.clone()),
7188        // c:1269 — `s.pc = p->prog;` — start at index 0.
7189        pc: 0,
7190        // c:1270 — `s.strs = p->strs;`
7191        strs: prog_ref.strs.clone(),
7192        strs_offset: 0,
7193    };
7194    // c:1251-1266 — push context onto zsh_eval_context.
7195    let pushed = {
7196        if let Ok(mut ctx) = zsh_eval_context.lock() {
7197            ctx.push(context.to_string());
7198            true
7199        } else {
7200            false
7201        }
7202    };
7203    // c:1271 — `useeprog(p);`
7204    crate::ported::parse::useeprog(&mut s.prog);
7205    // c:1273 — `execlist(&s, dont_change_job, exiting);`
7206    execlist(&mut s, dont_change_job, exiting);
7207    // c:1275 — `freeeprog(p);`
7208    crate::ported::parse::freeeprog(&mut s.prog);
7209    // c:1281 — `zsh_eval_context[alen] = NULL;` — pop our entry.
7210    if pushed {
7211        if let Ok(mut ctx) = zsh_eval_context.lock() {
7212            ctx.pop();
7213        }
7214    }
7215}
7216
7217/// Port of `execautofn_basic(Estate state, UNUSED(int do_exec))` from
7218/// `Src/exec.c:5608-5630`. Run a pre-loaded autoload function body
7219/// via `execode`, snapshotting `scriptname`/`scriptfilename` around
7220/// the call so `%N` / `%x` reflect the autoload target during
7221/// execution.
7222pub fn execautofn_basic(state: &mut estate, _do_exec: i32) -> i32 {
7223    // c:5608
7224    // c:5613 — `shf = state->prog->shf;`
7225    let shf = match state.prog.shf.as_deref() {
7226        Some(s) => s.clone(),
7227        None => return LASTVAL.load(Ordering::Relaxed),
7228    };
7229
7230    // c:5619-5620 — funcstack filename catch-up. zshrs's funcstack
7231    // top-of-stack tracking is in modules::parameter::FUNCSTACK.
7232    {
7233        let mut stk = crate::ported::modules::parameter::FUNCSTACK.lock().unwrap();
7234        if let Some(top) = stk.last_mut() {
7235            if top.filename.is_none() {
7236                // c:5620 — `funcstack->filename = getshfuncfile(shf);`
7237                top.filename = crate::ported::hashtable::getshfuncfile(&shf.node.nam);
7238            }
7239        }
7240    }
7241
7242    // c:5622-5623 — `oldscriptname/oldscriptfilename = scriptname/scriptfilename;`
7243    let oldscriptname = crate::ported::utils::scriptname_get();
7244    let oldscriptfilename = crate::ported::utils::scriptfilename_get();
7245    // c:5624 — `scriptname = dupstring(shf->node.nam);`
7246    crate::ported::utils::set_scriptname(Some(shf.node.nam.clone()));
7247    // c:5625 — `scriptfilename = getshfuncfile(shf);`
7248    crate::ported::utils::set_scriptfilename(crate::ported::hashtable::getshfuncfile(
7249        &shf.node.nam,
7250    ));
7251    // c:5626 — `execode(shf->funcdef, 1, 0, "loadautofunc");`
7252    if let Some(funcdef) = shf.funcdef.clone() {
7253        execode(funcdef, 1, 0, "loadautofunc");
7254    }
7255    // c:5627-5628 — restore.
7256    crate::ported::utils::set_scriptname(oldscriptname);
7257    crate::ported::utils::set_scriptfilename(oldscriptfilename);
7258
7259    LASTVAL.load(Ordering::Relaxed) // c:5630
7260}
7261
7262/// Port of `static int execautofn(Estate state, UNUSED(int do_exec))`
7263/// from `Src/exec.c:5635-5644`. The autoload-aware dispatch entry
7264/// for `WC_AUTOFN`: fault the function body in via `loadautofn`,
7265/// then hand off to `execautofn_basic` to actually run it.
7266///
7267/// C body:
7268/// ```c
7269/// static int
7270/// execautofn(Estate state, UNUSED(int do_exec))
7271/// {
7272///     Shfunc shf;
7273///     if (!(shf = loadautofn(state->prog->shf, 1, 0, 0)))
7274///         return 1;
7275///     state->prog->shf = shf;
7276///     return execautofn_basic(state, 0);
7277/// }
7278/// ```
7279///
7280/// Rust port: `loadautofn` mutates the `shfunc` in place via a raw
7281/// pointer and returns 0/1 (success/failure), so the explicit
7282/// `state->prog->shf = shf` assignment in C is implicit here.
7283pub fn execautofn(state: &mut estate, _do_exec: i32) -> i32 {
7284    // c:5638-5640 — `if (!(shf = loadautofn(state->prog->shf, 1, 0, 0))) return 1;`
7285    let shf_ptr: *mut shfunc = match state.prog.shf.as_mut() {
7286        Some(b) => &mut **b as *mut shfunc,
7287        None => return 1,
7288    };
7289    if loadautofn(shf_ptr, 1, 0, 0) != 0 {
7290        return 1;
7291    }
7292    // c:5643 — `return execautofn_basic(state, 0);`
7293    execautofn_basic(state, 0)
7294}
7295
7296/// Port of `execpline2(Estate state, wordcode pcode, int how, int input,
7297/// int output, int last1)` from `Src/exec.c:1989-2040`. Recursive
7298/// multi-stage pipe walker: at each step, analyse the current
7299/// command, fork-into-pipe (if mid-pipeline) or exec directly (if
7300/// WC_PIPE_END), then recurse on the next stage with `pipes[0]` as
7301/// its input fd.
7302pub fn execpline2(
7303    state: &mut estate,
7304    pcode: wordcode,
7305    how: i32,
7306    input: i32,
7307    output: i32,
7308    last1: i32,
7309) {
7310    use crate::ported::builtin::{BREAKS, INEVAL, RETFLAG};
7311    use crate::ported::zsh_h::{
7312        execcmd_params, CS_PIPE, WC_PIPE_END, WC_PIPE_LINENO as ZWC_PIPE_LINENO,
7313        WC_PIPE_TYPE as ZWC_PIPE_TYPE, Z_ASYNC,
7314    };
7315    // c:1991
7316    let mut eparams: execcmd_params = execcmd_params::default(); // c:1994 `struct execcmd_params eparams;`
7317
7318    // c:1996-1997 — `if (breaks || retflag) return;`
7319    if BREAKS.load(Ordering::SeqCst) != 0 || RETFLAG.load(Ordering::SeqCst) != 0 {
7320        return;
7321    }
7322
7323    // c:1999-2001 — `if (!IN_EVAL_TRAP() && !ineval && WC_PIPE_LINENO(pcode))
7324    //                  lineno = WC_PIPE_LINENO(pcode) - 1;`
7325    if !crate::ported::zsh_h::IN_EVAL_TRAP()
7326        && INEVAL.load(Ordering::SeqCst) == 0
7327        && ZWC_PIPE_LINENO(pcode) != 0
7328    {
7329        let new_lineno = ZWC_PIPE_LINENO(pcode).saturating_sub(1) as usize;
7330        crate::ported::input::lineno.with(|l| l.set(new_lineno));
7331    }
7332
7333    // c:2003-2011 — pline_level == 1 → snapshot to list_pipe_text for `jobs` output.
7334    if pline_level.load(Ordering::Relaxed) == 1 {
7335        // c:2003
7336        if (how & Z_ASYNC as i32) != 0 || sfcontext.load(Ordering::Relaxed) == 0 {
7337            // c:2004 — `(how & Z_ASYNC) || !sfcontext`
7338            // c:2005-2008 — `strcpy(list_pipe_text, getjobtext(state->prog,
7339            //   state->pc + (WC_PIPE_TYPE(pcode) == WC_PIPE_END ? 0 : 1)));`
7340            let pc_for_text = state.pc
7341                + if ZWC_PIPE_TYPE(pcode) == WC_PIPE_END {
7342                    0
7343                } else {
7344                    1
7345                };
7346            let text = crate::ported::text::getjobtext(state.prog.clone(), Some(pc_for_text));
7347            if let Ok(mut lpt) = LIST_PIPE_TEXT.lock() {
7348                *lpt = text;
7349            }
7350        } else {
7351            // c:2010 — `list_pipe_text[0] = '\0';`
7352            if let Ok(mut lpt) = LIST_PIPE_TEXT.lock() {
7353                lpt.clear();
7354            }
7355        }
7356    }
7357
7358    if ZWC_PIPE_TYPE(pcode) == WC_PIPE_END {
7359        // c:2012-2014 — terminal stage: analyse + exec directly.
7360        execcmd_analyse(state, &mut eparams); // c:2013
7361        execcmd_exec(
7362            state,
7363            &mut eparams,
7364            input,
7365            output,
7366            how,
7367            if last1 != 0 { 1 } else { 2 }, // c:2014 `last1 ? 1 : 2`
7368            -1,                             // c:2014 close_if_forked = -1
7369        );
7370    } else {
7371        // c:2015-2039 — non-terminal stage: pipe + fork + recurse.
7372        let mut pipes: [i32; 2] = [-1, -1]; // c:2016
7373        let old_list_pipe = list_pipe.load(Ordering::Relaxed); // c:2017
7374                                                               // c:2018 — `Wordcode next = state->pc + (*state->pc);`
7375        let next = if state.pc < state.prog.prog.len() {
7376            state.pc + state.prog.prog[state.pc] as usize
7377        } else {
7378            state.pc
7379        };
7380        // c:2020 — `++state->pc;`
7381        if state.pc < state.prog.prog.len() {
7382            state.pc += 1;
7383        }
7384        execcmd_analyse(state, &mut eparams); // c:2021
7385
7386        if mpipe(&mut pipes) < 0 {
7387            // c:2023-2025 — pipe() failure — `/* FIXME */` in C, fall through.
7388        }
7389
7390        // c:2027 — `addfilelist(NULL, pipes[0]);`
7391        // C uses the current thisjob's filelist; Rust port wires through JOBTAB.
7392        if let Some(jt) = JOBTAB.get() {
7393            let mut guard = jt.lock().unwrap();
7394            let tj = {
7395                if let Some(m) = THISJOB.get() {
7396                    *m.lock().unwrap()
7397                } else {
7398                    -1
7399                }
7400            };
7401            if tj >= 0 {
7402                if let Some(j) = guard.get_mut(tj as usize) {
7403                    crate::ported::jobs::addfilelist(j, None, pipes[0]);
7404                }
7405            }
7406        }
7407
7408        // c:2028 — `execcmd_exec(state, &eparams, input, pipes[1], how, 0, pipes[0]);`
7409        execcmd_exec(state, &mut eparams, input, pipes[1], how, 0, pipes[0]);
7410        let _ = zclose(pipes[1]); // c:2029
7411        state.pc = next; // c:2030
7412
7413        // c:2034 — `cmdpush(CS_PIPE);`
7414        cmdpush(CS_PIPE as u8);
7415        // c:2035 — `list_pipe = 1;`
7416        list_pipe.store(1, Ordering::Relaxed);
7417        // c:2036 — `execpline2(state, *state->pc++, how, pipes[0], output, last1);`
7418        let next_pcode = if state.pc < state.prog.prog.len() {
7419            state.prog.prog[state.pc]
7420        } else {
7421            0
7422        };
7423        if state.pc < state.prog.prog.len() {
7424            state.pc += 1;
7425        }
7426        execpline2(state, next_pcode, how, pipes[0], output, last1);
7427        // c:2037 — `list_pipe = old_list_pipe;`
7428        list_pipe.store(old_list_pipe, Ordering::Relaxed);
7429        // c:2038 — `cmdpop();`
7430        cmdpop();
7431    }
7432}
7433
7434/// Port of `execpline(Estate state, wordcode slcode, int how, int last1)`
7435/// from `Src/exec.c:1668-1942`. Walks the WC_PIPE chain, sets up
7436/// pipes/fork between stages, handles Z_TIMED / Z_ASYNC.
7437///
7438/// The full body needs: pipe(), fork(), execcmd_exec per-stage, job-
7439/// table installation, wait-status reaping. Until those primitives
7440/// land in faithfully-ported form, the structural shape is preserved
7441/// here: walk the WC_PIPE chain, exec each cmd inline (the inlined
7442/// match is the same dispatch C's exec.c:2901-3700 uses), propagate
7443/// LASTVAL through stages. Single-cmd pipelines work end-to-end;
7444/// multi-stage pipelines fall back to sequential execution (status
7445/// of last stage) until pipe + fork land.
7446pub fn execpline(state: &mut estate, slcode: wordcode, how: i32, last1: i32) -> i32 {
7447    use crate::ported::zsh_h::{WC_SUBLIST_FLAGS, WC_SUBLIST_NOT, Z_TIMED};
7448    let slflags = WC_SUBLIST_FLAGS(slcode); // c:1673
7449                                            // c:1677-1680 — `if (wc_code(code) != WC_PIPE && !(how & Z_TIMED))
7450                                            //                  return lastval = (slflags & WC_SUBLIST_NOT) != 0;
7451                                            //                else if (slflags & WC_SUBLIST_NOT) last1 = 0;`
7452    if state.pc >= state.prog.prog.len() || wc_code(state.prog.prog[state.pc]) != WC_PIPE {
7453        if (how & Z_TIMED as i32) == 0 {
7454            let ret = if (slflags & WC_SUBLIST_NOT) != 0 {
7455                1
7456            } else {
7457                0
7458            };
7459            LASTVAL.store(ret, Ordering::Relaxed);
7460            return ret;
7461        }
7462    }
7463    let mut last1 = last1;
7464    if (slflags & WC_SUBLIST_NOT) != 0 {
7465        last1 = 0; // c:1680
7466    }
7467    let mut code = state.prog.prog[state.pc];
7468    state.pc += 1;
7469    let mut last_status: i32 = 0;
7470    use crate::ported::zsh_h::{WC_PIPE_END, WC_PIPE_TYPE};
7471    let _ = how;
7472    let _ = last1;
7473    // c:1700-1940 — main WC_PIPE loop. Each iter: exec one cmd, advance.
7474    loop {
7475        // c:2901-3700 — execcmd_exec dispatch tail inlined: match the
7476        // WC_* tag at state.pc and dispatch to the matching execX.
7477        // Same dispatch as `execfuncs[]` (exec.c:5499).
7478        use crate::ported::zsh_h::{
7479            WC_ARITH, WC_CASE, WC_COND, WC_CURSH, WC_FOR, WC_FUNCDEF, WC_IF, WC_REPEAT, WC_SELECT,
7480            WC_SIMPLE, WC_SUBSH, WC_TIMED, WC_TRY, WC_WHILE,
7481        };
7482        let s = if state.pc < state.prog.prog.len() {
7483            let inner = state.prog.prog[state.pc];
7484            match wc_code(inner) {
7485                WC_SIMPLE => execsimple(state),
7486                WC_SUBSH | WC_CURSH => execcursh(state, 0),
7487                WC_FOR => execfor(state, 0),
7488                WC_SELECT => execselect(state, 0),
7489                WC_CASE => execcase(state, 0),
7490                WC_IF => execif(state, 0),
7491                WC_WHILE => execwhile(state, 0),
7492                WC_REPEAT => execrepeat(state, 0),
7493                WC_FUNCDEF => execfuncdef(state, None),
7494                WC_TIMED => exectime(state, 0),
7495                WC_COND => execcond(state, 0),
7496                WC_ARITH => execarith(state, 0),
7497                WC_TRY => exectry(state, 0),
7498                _ => {
7499                    state.pc += 1;
7500                    0
7501                }
7502            }
7503        } else {
7504            0
7505        };
7506        last_status = s;
7507        // c:1885-1893 — last pipe stage check.
7508        if WC_PIPE_TYPE(code) == WC_PIPE_END {
7509            break;
7510        }
7511        // c:1897-1900 — fetch next WC_PIPE header for the next stage.
7512        if state.pc >= state.prog.prog.len() {
7513            break;
7514        }
7515        let next_code = state.prog.prog[state.pc];
7516        if wc_code(next_code) != WC_PIPE {
7517            break;
7518        }
7519        state.pc += 1;
7520        code = next_code;
7521        // Multi-stage pipe() + fork() per cmd is now ported via
7522        // `execpline2` (c:1991-2040). Callers wanting full pipeline
7523        // isolation route through that path; this inline dispatch
7524        // serves the single-process simple-command tree-walker used
7525        // by the fusevm bytecode shim, which does its own
7526        // pipe/fork via `OpPipeCreate`/`OpFork` ops.
7527    }
7528    LASTVAL.store(last_status, Ordering::Relaxed);
7529    last_status
7530}
7531
7532// `execcmd_exec`'s wordcode dispatch tail from Src/exec.c:2901-3700 is
7533// inlined at every call site (execsimple, execpline) as the match
7534// expression that selects the right execX function. There's no
7535// separate Rust fn for it because:
7536//   - The arg-side `execcmd_exec(args, type_)` at exec.rs:795 already
7537//     occupies the canonical name (handling precommand modifiers).
7538//   - The C dispatch tail is conceptually `execfuncs[code - WC_CURSH]`,
7539//     a table lookup at exec.c:5499 — not a separate function.
7540#[cfg(any())]
7541mod _execcmd_tail_doc_anchor {
7542    // c:2901-3700 — see inlined match in execpline + execsimple above.
7543    // c:5499 — execfuncs[] table inlined as the same match.
7544}
7545
7546// --- loop.c entries ---------------------------------------------------
7547
7548/// Port of `execfor(Estate state, int do_exec)` from `Src/loop.c:50-202`.
7549/// `for var in args; do body; done` and the C-style `for ((init;cond;adv))`
7550/// variant. WC_FOR_TYPE distinguishes PPARAM (use $@) / LIST (explicit
7551/// words) / COND (C-style).
7552pub fn execfor(state: &mut estate, do_exec: i32) -> i32 {
7553    use crate::ported::zsh_h::Z_END;
7554    let code = state.prog.prog[state.pc.wrapping_sub(1)]; // c:54
7555    let iscond = WC_FOR_TYPE(code) == WC_FOR_COND; // c:55
7556    let mut last_iter = false; // c:57 — `int last = 0;`
7557    let mut val: i64 = 0; // c:59
7558    let mut vars: Vec<String> = Vec::new();
7559    let mut args: Vec<String> = Vec::new();
7560    let mut cond_expr: String = String::new();
7561    let mut advance_expr: String = String::new();
7562    let old_simple_pline = simple_pline.swap(1, Ordering::Relaxed); // c:62-63
7563    let end_pc = state.pc + WC_FOR_SKIP(code) as usize; // c:65
7564    let mut ctok = 0i32;
7565    let mut atok = 0i32;
7566    if iscond {
7567        // c:68-82 — C-style for: init expr at top, then cond/advance.
7568        let init = ecgetstr(state, EC_NODUP, None); // c:68
7569        let init_sub = singsub(&init); // c:69
7570        if isset(XTRACE) {
7571            // c:70-75
7572            let init_show = untokenize(&init_sub);
7573            printprompt4();
7574            eprintln!("{}", init_show);
7575        }
7576        if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) == 0 {
7577            let _ = wc_matheval(&init_sub); // c:77 — `matheval(str);`
7578        }
7579        if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
7580            // c:79-82
7581            state.pc = end_pc;
7582            simple_pline.store(old_simple_pline, Ordering::Relaxed);
7583            return 1;
7584        }
7585        cond_expr = ecgetstr(state, EC_NODUP, Some(&mut ctok)); // c:83
7586        advance_expr = ecgetstr(state, EC_NODUP, Some(&mut atok)); // c:84
7587    } else {
7588        // c:86 — `vars = ecgetlist(state, *state->pc++, EC_NODUP, NULL);`
7589        let count = state.prog.prog[state.pc] as usize;
7590        state.pc += 1;
7591        vars = ecgetlist(state, count, EC_NODUP, None);
7592        if WC_FOR_TYPE(code) == WC_FOR_LIST {
7593            // c:88-100 — explicit `for var in words`
7594            let mut htok = 0i32;
7595            let arg_count = state.prog.prog[state.pc] as usize;
7596            state.pc += 1;
7597            args = ecgetlist(state, arg_count, EC_DUPTOK, Some(&mut htok));
7598            if args.is_empty() {
7599                state.pc = end_pc;
7600                simple_pline.store(old_simple_pline, Ordering::Relaxed);
7601                return 0;
7602            }
7603            if htok != 0 {
7604                execsubst(&mut args); // c:96
7605                if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
7606                    state.pc = end_pc;
7607                    simple_pline.store(old_simple_pline, Ordering::Relaxed);
7608                    return 1;
7609                }
7610            }
7611        } else {
7612            // c:102-107 — implicit `for var` (no `in` clause) uses
7613            // the positional params $@ from PPARAMS (params.rs Mutex).
7614            args = crate::ported::builtin::PPARAMS
7615                .lock()
7616                .map(|p| p.clone())
7617                .unwrap_or_default();
7618        }
7619    }
7620    // c:111-112 — empty args ⇒ lastval = 0.
7621    if !iscond && args.is_empty() {
7622        LASTVAL.store(0, Ordering::Relaxed);
7623    }
7624    LOOPS.fetch_add(1, Ordering::SeqCst); // c:114 — `loops++;`
7625    pushheap(); // c:115
7626    cmdpush(CS_FOR as u8); // c:116
7627    let loop_pc = state.pc; // c:117
7628    let mut args_iter = args.into_iter();
7629    while !last_iter {
7630        if iscond {
7631            // c:119-138 — eval cond expression.
7632            let mut cs = cond_expr.clone();
7633            if ctok != 0 {
7634                cs = singsub(&cs);
7635            }
7636            if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) == 0 {
7637                let trimmed = cs.trim_start();
7638                if !trimmed.is_empty() {
7639                    if isset(XTRACE) {
7640                        printprompt4();
7641                        eprintln!("{}", trimmed);
7642                    }
7643                    val = wc_mathevali(trimmed).unwrap_or(0);
7644                } else {
7645                    val = 1;
7646                }
7647            }
7648            if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
7649                if BREAKS.load(Ordering::SeqCst) > 0 {
7650                    BREAKS.fetch_sub(1, Ordering::SeqCst);
7651                }
7652                LASTVAL.store(1, Ordering::Relaxed);
7653                break;
7654            }
7655            if val == 0 {
7656                break;
7657            }
7658        } else {
7659            // c:140-162 — for var binding from args.
7660            let mut count = 0;
7661            for name in &vars {
7662                let value = match args_iter.next() {
7663                    Some(v) => v,
7664                    None => {
7665                        if count != 0 {
7666                            last_iter = true;
7667                            String::new()
7668                        } else {
7669                            break;
7670                        }
7671                    }
7672                };
7673                if isset(XTRACE) {
7674                    printprompt4();
7675                    eprintln!("{}={}", name, value);
7676                }
7677                setloopvar(name, &value);
7678                count += 1;
7679            }
7680            if count == 0 {
7681                break;
7682            }
7683        }
7684        state.pc = loop_pc; // c:163
7685        let _do_exec_now = do_exec != 0 && !args_iter.clone().any(|_| true); // c:164 — `do_exec && args && empty(args)`
7686        let _ = execlist(state, 1, if _do_exec_now { 1 } else { 0 });
7687        // c:166-169 — breaks/continue handling.
7688        if BREAKS.load(Ordering::SeqCst) > 0 {
7689            let prev = BREAKS.fetch_sub(1, Ordering::SeqCst);
7690            if prev - 1 > 0 || CONTFLAG.load(Ordering::SeqCst) == 0 {
7691                break;
7692            }
7693            CONTFLAG.store(0, Ordering::SeqCst);
7694        }
7695        if RETFLAG.load(Ordering::SeqCst) != 0 {
7696            break;
7697        }
7698        // c:170-178 — C-style advance step.
7699        if iscond && (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) == 0 {
7700            let mut adv = advance_expr.clone();
7701            if atok != 0 {
7702                adv = singsub(&adv);
7703            }
7704            if isset(XTRACE) {
7705                printprompt4();
7706                eprintln!("{}", adv);
7707            }
7708            if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) == 0 {
7709                let _ = wc_matheval(&adv);
7710            }
7711        }
7712        if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
7713            if BREAKS.load(Ordering::SeqCst) > 0 {
7714                BREAKS.fetch_sub(1, Ordering::SeqCst);
7715            }
7716            LASTVAL.store(1, Ordering::Relaxed);
7717            break;
7718        }
7719        freeheap(); // c:184
7720    }
7721    popheap(); // c:186
7722    cmdpop(); // c:187
7723    LOOPS.fetch_sub(1, Ordering::SeqCst); // c:188
7724    simple_pline.store(old_simple_pline, Ordering::Relaxed);
7725    state.pc = end_pc;
7726    this_noerrexit.store(1, Ordering::Relaxed);
7727    let _ = Z_END;
7728    LASTVAL.load(Ordering::Relaxed)
7729}
7730
7731/// Port of `execselect(Estate state, UNUSED(int do_exec))` from
7732/// `Src/loop.c:217-410`. `select var in words; do body; done` REPL.
7733pub fn execselect(state: &mut estate, _do_exec: i32) -> i32 {
7734    // The full select body manages a REPL prompt, terminal columns,
7735    // selectlist redraw, etc. The `selectlist` helper at loop.rs:130
7736    // already ports c:347 (menu display). Structural execselect:
7737    // c:225-410 — read vars + words like execfor, then loop on stdin
7738    // input prompting via PROMPT3, set var=word, run body.
7739    let code = state.prog.prog[state.pc.wrapping_sub(1)];
7740    let end_pc = state.pc + WC_FOR_SKIP(code) as usize;
7741    // c:228-237 — read var name + words. Skip body and use existing
7742    // bridge handler at BUILTIN_RUN_SELECT for actual REPL until full
7743    // wordcode driver lands.
7744    state.pc = end_pc;
7745    this_noerrexit.store(1, Ordering::Relaxed);
7746    LASTVAL.load(Ordering::Relaxed)
7747}
7748
7749/// Port of `execwhile(Estate state, UNUSED(int do_exec))` from
7750/// `Src/loop.c:413-498`. `while/until cond; do body; done`.
7751pub fn execwhile(state: &mut estate, _do_exec: i32) -> i32 {
7752    let code = state.prog.prog[state.pc.wrapping_sub(1)]; // c:417
7753    let isuntil = WC_WHILE_TYPE(code) == WC_WHILE_UNTIL; // c:419
7754    let end_pc = state.pc + WC_WHILE_SKIP(code) as usize; // c:422
7755    let olderrexit = noerrexit.load(Ordering::Relaxed); // c:423
7756    let mut oldval: i32 = 0; // c:424
7757    pushheap(); // c:425
7758    cmdpush(if isuntil {
7759        CS_UNTIL as u8
7760    } else {
7761        CS_WHILE as u8
7762    }); // c:426
7763    LOOPS.fetch_add(1, Ordering::SeqCst); // c:427
7764    let loop_pc = state.pc; // c:428
7765    let old_simple_pline = simple_pline.load(Ordering::Relaxed); // c:419
7766                                                                 // c:430-456 — empty-loop fast path. If loop body is two WC_ENDs,
7767                                                                 // sit in a tight signal-wait loop until ^C breaks us.
7768    if state.prog.prog.get(loop_pc) == Some(&WC_END)
7769        && state.prog.prog.get(loop_pc + 1) == Some(&WC_END)
7770    {
7771        simple_pline.store(1, Ordering::Relaxed);
7772        // c:438-439 — spin until breaks.
7773        while BREAKS.load(Ordering::SeqCst) == 0 {
7774            std::thread::yield_now();
7775        }
7776        BREAKS.fetch_sub(1, Ordering::SeqCst);
7777        simple_pline.store(old_simple_pline, Ordering::Relaxed);
7778    } else {
7779        // c:441-485 — normal loop.
7780        loop {
7781            state.pc = loop_pc; // c:442
7782            noerrexit.fetch_or(NOERREXIT_EXIT | NOERREXIT_RETURN, Ordering::Relaxed); // c:443
7783            simple_pline.store(1, Ordering::Relaxed); // c:446
7784            let _ = execlist(state, 1, 0); // c:448 — exec cond.
7785            simple_pline.store(old_simple_pline, Ordering::Relaxed);
7786            noerrexit.store(olderrexit, Ordering::Relaxed); // c:451
7787            let cond_status = LASTVAL.load(Ordering::Relaxed); // c:452
7788                                                               // c:453-460 — `if (!((lastval == 0) ^ isuntil)) break;`
7789            let cond_passed = (cond_status == 0) ^ isuntil;
7790            if !cond_passed {
7791                if BREAKS.load(Ordering::SeqCst) > 0 {
7792                    BREAKS.fetch_sub(1, Ordering::SeqCst);
7793                }
7794                if RETFLAG.load(Ordering::SeqCst) == 0 {
7795                    LASTVAL.store(oldval, Ordering::Relaxed);
7796                }
7797                break;
7798            }
7799            if RETFLAG.load(Ordering::SeqCst) != 0 {
7800                // c:461
7801                if BREAKS.load(Ordering::SeqCst) > 0 {
7802                    BREAKS.fetch_sub(1, Ordering::SeqCst);
7803                }
7804                break;
7805            }
7806            simple_pline.store(1, Ordering::Relaxed); // c:468
7807            let _ = execlist(state, 1, 0); // c:470 — exec body.
7808            simple_pline.store(old_simple_pline, Ordering::Relaxed);
7809            // c:472-477 — breaks/continue handling.
7810            if BREAKS.load(Ordering::SeqCst) > 0 {
7811                let prev = BREAKS.fetch_sub(1, Ordering::SeqCst);
7812                if prev - 1 > 0 || CONTFLAG.load(Ordering::SeqCst) == 0 {
7813                    break;
7814                }
7815                CONTFLAG.store(0, Ordering::SeqCst);
7816            }
7817            // c:478-481 — errflag bail.
7818            if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
7819                LASTVAL.store(1, Ordering::Relaxed);
7820                break;
7821            }
7822            // c:482-483 — retflag bail.
7823            if RETFLAG.load(Ordering::SeqCst) != 0 {
7824                break;
7825            }
7826            freeheap(); // c:484
7827            oldval = LASTVAL.load(Ordering::Relaxed); // c:485
7828        }
7829    }
7830    cmdpop(); // c:489
7831    popheap(); // c:490
7832    LOOPS.fetch_sub(1, Ordering::SeqCst); // c:491
7833    state.pc = end_pc; // c:492
7834    this_noerrexit.store(1, Ordering::Relaxed); // c:493
7835    LASTVAL.load(Ordering::Relaxed)
7836}
7837
7838/// Port of `execrepeat(Estate state, UNUSED(int do_exec))` from
7839/// `Src/loop.c:499-551`. `repeat N; do body; done`.
7840pub fn execrepeat(state: &mut estate, _do_exec: i32) -> i32 {
7841    let code = state.prog.prog[state.pc.wrapping_sub(1)]; // c:503
7842    let old_simple_pline = simple_pline.swap(1, Ordering::Relaxed); // c:507
7843    let end_pc = state.pc + WC_REPEAT_SKIP(code) as usize; // c:510
7844    let mut htok = 0i32;
7845    let mut tmp = ecgetstr(state, EC_DUPTOK, Some(&mut htok)); // c:512
7846    if htok != 0 {
7847        tmp = singsub(&tmp); // c:514
7848        tmp = untokenize(&tmp); // c:515
7849    }
7850    let count = wc_mathevali(&tmp).unwrap_or(0); // c:517
7851    if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
7852        simple_pline.store(old_simple_pline, Ordering::Relaxed);
7853        return 1;
7854    }
7855    LASTVAL.store(0, Ordering::Relaxed); // c:520
7856    pushheap(); // c:521
7857    cmdpush(CS_REPEAT as u8); // c:522
7858    LOOPS.fetch_add(1, Ordering::SeqCst); // c:523
7859    let loop_pc = state.pc; // c:524
7860    let mut remaining = count;
7861    while remaining > 0 {
7862        // c:525
7863        remaining -= 1;
7864        state.pc = loop_pc;
7865        let _ = execlist(state, 1, 0); // c:527
7866        freeheap(); // c:528
7867                    // c:529-534 — breaks/continue handling.
7868        if BREAKS.load(Ordering::SeqCst) > 0 {
7869            let prev = BREAKS.fetch_sub(1, Ordering::SeqCst);
7870            if prev - 1 > 0 || CONTFLAG.load(Ordering::SeqCst) == 0 {
7871                break;
7872            }
7873            CONTFLAG.store(0, Ordering::SeqCst);
7874        }
7875        if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
7876            // c:536-538
7877            LASTVAL.store(1, Ordering::Relaxed);
7878            break;
7879        }
7880        if RETFLAG.load(Ordering::SeqCst) != 0 {
7881            // c:540
7882            break;
7883        }
7884    }
7885    cmdpop(); // c:544
7886    popheap(); // c:545
7887    LOOPS.fetch_sub(1, Ordering::SeqCst); // c:546
7888    simple_pline.store(old_simple_pline, Ordering::Relaxed);
7889    state.pc = end_pc; // c:548
7890    this_noerrexit.store(1, Ordering::Relaxed); // c:549
7891    LASTVAL.load(Ordering::Relaxed)
7892}
7893
7894/// Port of `execif(Estate state, int do_exec)` from `Src/loop.c:553-598`.
7895/// `if cond; then body; elif ...; else ...; fi`.
7896pub fn execif(state: &mut estate, do_exec: i32) -> i32 {
7897    let code0 = state.prog.prog[state.pc.wrapping_sub(1)]; // c:558
7898    let olderrexit = noerrexit.load(Ordering::Relaxed); // c:559
7899    let end_pc = state.pc + WC_IF_SKIP(code0) as usize; // c:560
7900    noerrexit.fetch_or(NOERREXIT_EXIT | NOERREXIT_RETURN, Ordering::Relaxed); // c:562
7901    let mut s = 0i32; // c:557 — `s = 0`
7902    let mut run = 0i32; // c:557 — `run = 0`
7903    while state.pc < end_pc {
7904        // c:563
7905        let code = state.prog.prog[state.pc];
7906        state.pc += 1;
7907        // c:565-571 — non-IF, or IF_ELSE: break out.
7908        if wc_code(code) != WC_IF || WC_IF_TYPE(code) == WC_IF_ELSE {
7909            run = if wc_code(code) == WC_IF && WC_IF_TYPE(code) == WC_IF_ELSE {
7910                2
7911            } else {
7912                1
7913            };
7914            if run == 1 {
7915                state.pc -= 1; // back up onto the body header
7916            }
7917            break;
7918        }
7919        let next_pc = state.pc + WC_IF_SKIP(code) as usize; // c:572
7920        cmdpush(if s != 0 { CS_ELIF as u8 } else { CS_IF as u8 }); // c:573
7921        let _ = execlist(state, 1, 0); // c:574
7922        cmdpop(); // c:575
7923                  // c:576-579 — selected branch: lastval == 0.
7924        if LASTVAL.load(Ordering::Relaxed) == 0 {
7925            run = 1;
7926            break;
7927        }
7928        if RETFLAG.load(Ordering::SeqCst) != 0 {
7929            // c:580
7930            break;
7931        }
7932        s = 1;
7933        state.pc = next_pc;
7934    }
7935    noerrexit.store(olderrexit, Ordering::Relaxed); // c:584
7936                                                    // c:585-591 — run selected branch.
7937    if run != 0 {
7938        cmdpush(if run == 2 {
7939            CS_ELSE as u8
7940        } else if s != 0 {
7941            CS_ELIFTHEN as u8
7942        } else {
7943            CS_IFTHEN as u8
7944        });
7945        let _ = execlist(state, 1, do_exec);
7946        cmdpop();
7947    } else if RETFLAG.load(Ordering::SeqCst) == 0
7948        && (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) == 0
7949    {
7950        LASTVAL.store(0, Ordering::Relaxed); // c:592
7951    }
7952    state.pc = end_pc; // c:594
7953    this_noerrexit.store(1, Ordering::Relaxed); // c:595
7954    LASTVAL.load(Ordering::Relaxed)
7955}
7956
7957/// Port of `execcase(Estate state, int do_exec)` from `Src/loop.c:600-733`.
7958/// `case word in pat) body ;; ... esac` with `;;`/`;&`/`;|` separators.
7959pub fn execcase(state: &mut estate, do_exec: i32) -> i32 {
7960    let code0 = state.prog.prog[state.pc.wrapping_sub(1)]; // c:603
7961    let end_pc = state.pc + WC_CASE_SKIP(code0) as usize; // c:607
7962                                                          // c:609-611 — read & expand the case-word.
7963    let raw_word = ecgetstr(state, EC_DUP, None);
7964    let word_sub = singsub(&raw_word);
7965    let word = untokenize(&word_sub);
7966    let mut anypatok = false; // c:613
7967    cmdpush(CS_CASE as u8); // c:615
7968    let mut code = 0u32;
7969    while state.pc < end_pc {
7970        // c:616
7971        code = state.prog.prog[state.pc];
7972        state.pc += 1;
7973        if wc_code(code) != WC_CASE {
7974            break;
7975        }
7976        let next_pc = state.pc + WC_CASE_SKIP(code) as usize; // c:621
7977        let nalts = state.prog.prog[state.pc] as i32; // c:622
7978        state.pc += 1;
7979        let mut patok = false;
7980        let mut nalts_remaining = nalts;
7981        while !patok && nalts_remaining > 0 {
7982            // c:629-672 — try each alternative pattern.
7983            // c:631-633 — `npat = state->pc[1]; spprog = state->prog->pats + npat;`
7984            // zshrs's pat-compile-on-demand path: extract raw pat text + try patcompile/pattry.
7985            queue_signals(); // c:636
7986            let mut htok = 0i32;
7987            let pat_raw = ecrawstr(&state.prog, state.pc, Some(&mut htok));
7988            let pat = if htok != 0 {
7989                singsub(&pat_raw)
7990            } else {
7991                pat_raw
7992            };
7993            if let Some(pprog) = patcompile(&pat, PAT_STATIC, None) {
7994                // c:660 — `if (pprog && pattry(pprog, word)) patok = anypatok = 1;`
7995                if pattry(&pprog, &word) {
7996                    patok = true;
7997                    anypatok = true;
7998                }
7999            } else {
8000                zerr(&format!("bad pattern: {}", pat)); // c:657
8001            }
8002            state.pc += 2; // c:664 — `state->pc += 2;`
8003            nalts_remaining -= 1;
8004            unqueue_signals(); // c:666
8005        }
8006        state.pc += (2 * nalts_remaining) as usize; // c:668
8007        if patok {
8008            // c:672-684 — run selected arm body.
8009            let _ = execlist(
8010                state,
8011                1,
8012                ((WC_CASE_TYPE(code) == WC_CASE_OR) as i32) & do_exec,
8013            );
8014            // c:675-682 — chain into ;& and ;| siblings.
8015            while RETFLAG.load(Ordering::SeqCst) == 0
8016                && wc_code(code) == WC_CASE
8017                && WC_CASE_TYPE(code) == WC_CASE_AND
8018                && state.pc < end_pc
8019            {
8020                state.pc = next_pc;
8021                code = state.prog.prog[state.pc];
8022                state.pc += 1;
8023                let inner_next = state.pc + WC_CASE_SKIP(code) as usize;
8024                let inner_nalts = state.prog.prog[state.pc] as usize;
8025                state.pc += 1 + 2 * inner_nalts;
8026                let _ = execlist(
8027                    state,
8028                    1,
8029                    ((WC_CASE_TYPE(code) == WC_CASE_OR) as i32) & do_exec,
8030                );
8031                let _ = inner_next;
8032            }
8033            if WC_CASE_TYPE(code) != WC_CASE_TESTAND {
8034                break;
8035            }
8036        }
8037        state.pc = next_pc; // c:687
8038    }
8039    cmdpop(); // c:691
8040    state.pc = end_pc; // c:693
8041    if !anypatok {
8042        // c:695-696
8043        LASTVAL.store(0, Ordering::Relaxed);
8044    }
8045    this_noerrexit.store(1, Ordering::Relaxed); // c:697
8046    LASTVAL.load(Ordering::Relaxed)
8047}
8048
8049/// Port of `exectry(Estate state, int do_exec)` from `Src/loop.c:735-798`.
8050/// `{ try } always { finally }`: capture errflag/retflag/breaks/contflag
8051/// from the try-clause, reset them around the always-clause, then
8052/// restore if always-clause didn't override.
8053pub fn exectry(state: &mut estate, _do_exec: i32) -> i32 {
8054    let header = state.prog.prog[state.pc.wrapping_sub(1)]; // c:741
8055    let end_pc = state.pc + WC_TRY_SKIP(header) as usize; // c:742
8056    let try_inner = state.prog.prog[state.pc]; // c:743
8057    let always_pc = state.pc + 1 + WC_TRY_SKIP(try_inner) as usize; // c:743
8058    state.pc += 1; // c:744
8059    pushheap(); // c:745
8060    cmdpush(CS_CURSH as u8); // c:746
8061    try_tryflag.fetch_add(1, Ordering::SeqCst); // c:749
8062    let _ = execlist(state, 1, 0); // c:750
8063    try_tryflag.fetch_sub(1, Ordering::SeqCst); // c:751
8064    let try_status = LASTVAL.load(Ordering::Relaxed);
8065    let endval = if try_status != 0 {
8066        // c:754
8067        try_status
8068    } else {
8069        (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) as i32
8070    };
8071    freeheap(); // c:756
8072    cmdpop(); // c:758
8073    cmdpush(CS_ALWAYS as u8); // c:759
8074                              // c:762-763 — save try_errflag / try_interrupt.
8075    let saved_err = errflag.load(Ordering::Relaxed);
8076    let save_try_err = (saved_err & ERRFLAG_ERROR) != 0;
8077    let save_try_int = (saved_err & ERRFLAG_INT) != 0;
8078    // c:768 — `errflag = 0;` (clear both bits).
8079    errflag.fetch_and(!(ERRFLAG_ERROR | ERRFLAG_INT), Ordering::Relaxed);
8080    // c:769-774 — save retflag/breaks/contflag.
8081    let save_retflag = RETFLAG.swap(0, Ordering::SeqCst);
8082    let save_breaks = BREAKS.swap(0, Ordering::SeqCst);
8083    let save_contflag = CONTFLAG.swap(0, Ordering::SeqCst);
8084    state.pc = always_pc; // c:776
8085    let _ = execlist(state, 1, 0); // c:777
8086                                   // c:779-786 — restore errflag bits.
8087    if save_try_err {
8088        errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed);
8089    } else {
8090        errflag.fetch_and(!ERRFLAG_ERROR, Ordering::Relaxed);
8091    }
8092    if save_try_int {
8093        errflag.fetch_or(ERRFLAG_INT, Ordering::Relaxed);
8094    } else {
8095        errflag.fetch_and(!ERRFLAG_INT, Ordering::Relaxed);
8096    }
8097    // c:789-794 — re-arm retflag/breaks/contflag only if always didn't override.
8098    if RETFLAG.load(Ordering::SeqCst) == 0 {
8099        RETFLAG.store(save_retflag, Ordering::SeqCst);
8100    }
8101    if BREAKS.load(Ordering::SeqCst) == 0 {
8102        BREAKS.store(save_breaks, Ordering::SeqCst);
8103    }
8104    if CONTFLAG.load(Ordering::SeqCst) == 0 {
8105        CONTFLAG.store(save_contflag, Ordering::SeqCst);
8106    }
8107    cmdpop(); // c:796
8108    popheap(); // c:797
8109    state.pc = end_pc; // c:798
8110    this_noerrexit.store(1, Ordering::Relaxed); // c:799
8111    endval
8112}
8113
8114/// Port of `execcmd_exec(Estate state, Execcmd_params eparams,
8115/// int input, int output, int how, int last1, int close_if_forked)`
8116/// from `Src/exec.c:2900-4404`. Execute a command at the lowest
8117/// level of the hierarchy.
8118///
8119/// Line-by-line port of the full 1500-line C body. Sections:
8120///   c:2904-2916  — locals
8121///   c:2917-2924  — eparams field unpacking
8122///   c:2934-2939  — Z_TIMED + doneps4 reset
8123///   c:2945-2960  — old_lastval + use_cmdoutval + `save[]`/`mfds[]` init
8124///   c:2962-2986  — %job head rewrite + AUTORESUME prefix match
8125///   c:2988-3011  — Z_ASYNC / pipeline-not-last / sh-emulation fork-immediately
8126///   c:3013-3283  — precommand-modifier walk (BINF_PREFIX strip)
8127///                  + BINF_COMMAND (-p/-v/-V) + BINF_EXEC (-a/-c/-l)
8128///   c:3285-3307  — prefork substitutions + magic_assign
8129///   c:3309-3406  — empty-command branch (redir / nullexec / BINF_COMMAND)
8130///   c:3409-3466  — main resolution loop (shfunc / builtin / autocd)
8131///   c:3468-3479  — errflag bail-out
8132///   c:3480-3492  — text fetch + setunderscore
8133///   c:3494-3524  — rm * safety prompt
8134///   c:3526-3591  — type-specific dispatch prep (WC_FUNCDEF / is_shfunc / WC_AUTOFN)
8135///   c:3593-3632  — external resolution (cmdnamtab, hashcmd, AUTOCD)
8136///   c:3634-3697  — fork decision
8137///   c:3700-3955  — redir loop + multio + addfd + xpandredir
8138///   c:3957-3961  — multio close (`mfds[i].ct >= 2` → closemn)
8139///   c:3963-3995  — nullexec branch
8140///   c:3996-4327  — main dispatch (entersubsh + execfuncdef / `execcurshtable[]` /
8141///                  execbuiltin / execshfunc / execute)
8142///   c:4330-4365  — `err:` label: forked-child fd cleanup, fixfds
8143///   c:4366-4403  — `done:` label: POSIX special-builtin error escalation,
8144///                  shelltime stop, newxtrerr close, AUTOCONTINUE restore
8145///
8146/// **Substrate stubs (declared inside this fn citing home C file):**
8147///   - `save_params(state, varspc, restorelist, removelist)` → Src/exec.c:4409
8148///   - `restore_params(restorelist, removelist)` → Src/exec.c:4463
8149///   - `isreallycom(cn)` → Src/exec.c:2670
8150///   - `execerr()` → Src/exec.c:2700 (label-style; converts to errflag set + goto-equivalent)
8151///   - `execautofn_basic(state, do_exec)` → Src/exec.c:5050
8152///   - `ensurefeature(modname, "b:", ...)` → Src/module.c:1654
8153///
8154/// **NOT routed through fusevm.** This canonical port targets the
8155/// tree-walker dispatcher; the fusevm bytecode VM uses
8156/// `execcmd_compile_head` + `compile_simple` instead. No call
8157/// site yet — the port closes the substrate gap so future
8158/// wordcode-walker code can use it.
8159#[allow(non_snake_case)]
8160#[allow(clippy::too_many_arguments)]
8161#[allow(clippy::redundant_field_names)]
8162#[allow(unused_assignments)]
8163#[allow(unused_variables)]
8164#[allow(unused_mut)]
8165#[allow(unused_imports)]
8166#[allow(unreachable_code)]
8167#[allow(dead_code)]
8168pub fn execcmd_exec(
8169    state: &mut estate,
8170    eparams: &mut crate::ported::zsh_h::execcmd_params,
8171    input: i32,
8172    output: i32,
8173    mut how: i32,
8174    mut last1: i32,
8175    close_if_forked: i32,
8176) {
8177    use crate::ported::zsh_h::{
8178        Star, ASG_ARRAY, ASG_KEY_VALUE, AUTOCD, AUTOCONTINUE, AUTORESUME, BGNICE,
8179        BINF_ASSIGN as BINF_ASSIGN_FLAG, BINF_BUILTIN, BINF_COMMAND, BINF_EXEC, BINF_MAGICEQUALS,
8180        BINF_NOGLOB, BINF_PREFIX, BINF_PSPECIAL, CSHNULLCMD, ERRFLAG_INT, EXECOPT, FDT_EXTERNAL,
8181        FDT_INTERNAL, FDT_TYPE_MASK, FDT_UNUSED, FDT_XTRACE, HASHCMDS, HFILE_USE_OPTIONS,
8182        IS_APPEND_REDIR, IS_DASH, IS_ERROR_REDIR, MAGICEQUALSUBST, NOTIFY, PM_READONLY, PM_SPECIAL,
8183        POSIXBUILTINS, PREFORK_ASSIGN, PREFORK_KEY_VALUE, PREFORK_SINGLE, PREFORK_TYPESET,
8184        PRINTEXITVALUE, RCS, REDIR_CLOSE, REDIR_HERESTR, REDIR_INPIPE, REDIR_MERGEIN,
8185        REDIR_MERGEOUT, REDIR_OUTPIPE, REDIR_READ, REDIR_READWRITE, RMSTARSILENT, SHINSTDIN,
8186        SHNULLCMD, STAT_BUILTIN, STAT_CURSH, STAT_DONE, STAT_NOPRINT, WC_ASSIGN as ZWC_ASSIGN,
8187        WC_ASSIGN_INC as ZWC_ASSIGN_INC, WC_ASSIGN_NUM as ZWC_ASSIGN_NUM,
8188        WC_ASSIGN_SCALAR as ZWC_ASSIGN_SCALAR, WC_ASSIGN_TYPE as ZWC_ASSIGN_TYPE,
8189        WC_ASSIGN_TYPE2 as ZWC_ASSIGN_TYPE2, WC_AUTOFN, WC_CURSH, WC_FUNCDEF, WC_REDIR, WC_SIMPLE,
8190        WC_SUBSH, WC_TIMED, WC_TYPESET, XTRACE, Z_ASYNC, Z_DISOWN, Z_SYNC, Z_TIMED,
8191    };
8192
8193    // c:2900
8194
8195    // c:2904-2916 — locals.
8196    let mut hn: Option<*mut builtin> = None; // c:2904 HashNode hn = NULL
8197    let mut filelist: Vec<String> = Vec::new(); // c:2905 LinkList filelist = NULL
8198                                                // c:2906 LinkNode node; (loop locals)
8199                                                // c:2907 Redir fn;       (loop locals)
8200    let mut mfds: [Option<Box<multio>>; 10] =                              // c:2908 struct multio *mfds[10]
8201        [None, None, None, None, None, None, None, None, None, None];
8202    let mut text: Option<String> = None; // c:2909 char *text
8203    let mut save: [i32; 10] = [-2; 10]; // c:2910 int save[10]
8204    let mut fil: i32; // c:2911 int fil
8205    let mut dfil: i32 = 0; // c:2911 int dfil
8206    let mut is_cursh: i32 = 0; // c:2911 int is_cursh = 0
8207    let mut do_exec: i32 = 0; // c:2911 int do_exec = 0
8208    let mut redir_err: i32 = 0; // c:2911 int redir_err = 0
8209    let mut i: i32; // c:2911 int i
8210    let mut nullexec: i32 = 0; // c:2912 int nullexec = 0
8211    let mut magic_assign: i32 = 0; // c:2912 int magic_assign = 0
8212    let mut forked: i32 = 0; // c:2912 int forked = 0
8213    let mut old_lastval: i32; // c:2912 int old_lastval
8214    let mut is_shfunc: i32 = 0; // c:2913 int is_shfunc = 0
8215    let mut is_builtin: i32 = 0; // c:2913 int is_builtin = 0
8216    let mut is_exec: i32 = 0; // c:2913 int is_exec = 0
8217    let mut use_defpath: i32 = 0; // c:2913 int use_defpath = 0
8218                                  // c:2914 — `Various flags to the command.`
8219    let mut cflags: u32 = 0; // c:2915 int cflags = 0
8220    let mut orig_cflags: u32 = 0; // c:2915 int orig_cflags = 0
8221    let mut checked: i32 = 0; // c:2915 int checked = 0
8222    let mut oautocont: i32 = -1; // c:2915 int oautocont = -1
8223                                 // c:2916 — `FILE *oxtrerr = xtrerr, *newxtrerr = NULL;` — xtrerr
8224                                 // accessor is stub; track newxtrerr state via Option<RawFd>.
8225    let mut newxtrerr: Option<i32> = None; // c:2916
8226
8227    // c:2917-2924 — eparams field unpacking. `args` / `redir` are
8228    // pulled into mutable locals so the body can mutate them
8229    // independently of the eparams struct.
8230    let mut args: Option<Vec<String>> = eparams.args.take(); // c:2921 LinkList args
8231    let mut redir: Option<Vec<redir>> = eparams.redir.take(); // c:2922 LinkList redir
8232    let varspc: Option<usize> = eparams.varspc; // c:2923 Wordcode varspc
8233    let typ: i32 = eparams.typ; // c:2924 int type
8234                                // c:2925-2929 — `preargs comes from expanding the head of the args
8235                                // list in order to check for prefix commands.` declared later.
8236
8237    // c:2933-2937 — `for the "time" keyword` — child_times_t shti, chti
8238    // + struct timespec then. Rust port keeps the names so the shelltime
8239    // start+stop calls map directly. Use jobs.rs's existing types.
8240    let mut shti = crate::ported::jobs::timeinfo::default(); // c:2934
8241    let mut chti = crate::ported::jobs::timeinfo::default(); // c:2934
8242    let mut then_ts = std::time::Instant::now(); // c:2935 struct timespec then
8243    if (how & Z_TIMED as i32) != 0 {
8244        // c:2936
8245        crate::ported::jobs::shelltime(Some(&mut shti), Some(&mut chti), Some(&mut then_ts), 0);
8246        // c:2937
8247    }
8248
8249    doneps4.store(0, Ordering::Relaxed); // c:2939
8250
8251    // c:2941-2947 — `If assignment but no command get the status from
8252    // variable assignment.`
8253    old_lastval = LASTVAL.load(Ordering::Relaxed); // c:2945
8254    if args.is_none() && varspc.is_some() {
8255        // c:2946
8256        let ef = errflag.load(Ordering::Relaxed);
8257        LASTVAL.store(
8258            if ef != 0 {
8259                ef
8260            } else {
8261                cmdoutval.load(Ordering::Relaxed)
8262            },
8263            Ordering::Relaxed,
8264        ); // c:2947
8265    }
8266    // c:2948-2954 — `If there are arguments, we should reset the status
8267    // for the command before execution---unless we are using the result
8268    // of a command substitution...`
8269    use_cmdoutval.store(if args.is_none() { 1 } else { 0 }, Ordering::Relaxed); // c:2955
8270
8271    // c:2957-2960 — `for (i = 0; i < 10; i++) { save[i] = -2; mfds[i] = NULL; }`
8272    // Already initialised above via array literals; preserved as
8273    // comment for parity. The C loop maps to a no-op in Rust.
8274
8275    // c:2962-2973 — `%job` head rewrite.
8276    if (typ == WC_SIMPLE as i32 || typ == WC_TYPESET as i32)
8277        && args.as_ref().map(|v| !v.is_empty()).unwrap_or(false)
8278        && args.as_ref().unwrap()[0].starts_with('%')
8279    {
8280        // c:2964-2965
8281        if (how & Z_DISOWN as i32) != 0 {
8282            // c:2966
8283            oautocont = if crate::ported::options::opt_state_get("autocontinue").unwrap_or(false) {
8284                1
8285            } else {
8286                0
8287            }; // c:2967
8288            opt_state_set("autocontinue", true); // c:2968
8289        }
8290        // c:2970-2971 — `pushnode(args, dupstring((how & Z_DISOWN) ? "disown" : (how & Z_ASYNC) ? "bg" : "fg"));`
8291        let head = if (how & Z_DISOWN as i32) != 0 {
8292            "disown".to_string()
8293        } else if (how & Z_ASYNC as i32) != 0 {
8294            "bg".to_string()
8295        } else {
8296            "fg".to_string()
8297        };
8298        if let Some(ref mut v) = args {
8299            v.insert(0, head);
8300        }
8301        how = Z_SYNC as i32; // c:2972
8302    }
8303
8304    // c:2975-2986 — AUTORESUME prefix match against jobtab.
8305    if isset(AUTORESUME)
8306        && typ == WC_SIMPLE as i32
8307        && (how & Z_SYNC as i32) != 0
8308        && args.as_ref().map(|v| !v.is_empty()).unwrap_or(false)
8309        && redir.as_ref().map(|v| v.is_empty()).unwrap_or(true)
8310        && input == 0
8311        && args.as_ref().unwrap().len() == 1
8312    {
8313        // c:2979-2981
8314        if unset(NOTIFY) {
8315            // c:2982 — `scanjobs();` inlined: walk JOBTAB and printjob
8316            // each STAT_CHANGED entry. C scanjobs body at jobs.c:1993
8317            // is identical to this 5-line walk.
8318            if let Some(jt) = JOBTAB.get() {
8319                let mut guard = jt.lock().unwrap();
8320                let long_list = isset(crate::ported::zsh_h::LONGLISTJOBS);
8321                for i in 1..guard.len() {
8322                    // jobs.c:1997 — `for (i = 1; i <= maxjob; i++)`
8323                    if (guard[i].stat & crate::ported::zsh_h::STAT_CHANGED) != 0 {
8324                        let s = crate::ported::jobs::printjob(&guard[i], i, long_list, None, None); // jobs.c:1999
8325                        if !s.is_empty() {
8326                            eprint!("{}", s);
8327                        }
8328                    }
8329                }
8330            }
8331        }
8332        // c:2984 — `if (findjobnam(peekfirst(args)) != -1)`
8333        let head = args.as_ref().unwrap()[0].clone();
8334        let maxjob = JOBTAB
8335            .get()
8336            .map(|m| m.lock().unwrap().len() as i32)
8337            .unwrap_or(0);
8338        let thisjob = THISJOB.get().map(|m| *m.lock().unwrap()).unwrap_or(-1);
8339        // c:2982 — `findjobnam(s)`. Canonical port at
8340        // jobs.rs::findjobnam matches against `proc.text`, which is
8341        // the command text actually saved into the job at fork —
8342        // matching C exactly. Returns the job index if any non-
8343        // SUBJOB jobtab entry's first-proc text starts with `s`.
8344        let found = if let Some(jt) = JOBTAB.get() {
8345            let guard = jt.lock().unwrap();
8346            crate::ported::jobs::findjobnam(&head, &guard, maxjob - 1, thisjob).is_some()
8347        } else {
8348            false
8349        };
8350        if found {
8351            // c:2985 — `pushnode(args, dupstring("fg"));`
8352            if let Some(ref mut v) = args {
8353                v.insert(0, "fg".to_string());
8354            }
8355        }
8356    }
8357
8358    // ====================================================================
8359    // SUBSTRATE STUBS — same-named locals citing their home C file per
8360    // [[feedback_no_shortcuts_in_porting]]. Each stub mirrors the C
8361    // signature and returns a degenerate value that keeps the body
8362    // executing while the real port lands.
8363    // ====================================================================
8364    // save_params + restore_params — top-level ports in exec.rs
8365    // (c:4410 / c:4464). Both bridged via `use` below.
8366    use crate::ported::exec::{restore_params, save_params};
8367    // isreallycom — top-level port at exec.rs (c:972). Bridges the
8368    // local shadow that this fn body used pre-port.
8369    use crate::ported::exec::isreallycom;
8370    // execautofn_basic — top-level port at exec.rs (c:5608).
8371    use crate::ported::exec::execautofn_basic;
8372    // C `execerr` macro (c:2700) was a goto-equivalent:
8373    //   errflag |= ERRFLAG_ERROR; lastval = 1; goto err;
8374    // Rust expansion: each call site inlines the errflag+LASTVAL set
8375    // and then `break`s out of the enclosing redir loop. The loop's
8376    // post-loop errflag check at c:3949 routes to execcmd_exec_err_path
8377    // for the cleanup tail. No macro needed.
8378
8379    // c:2988-3011 — Z_ASYNC / pipeline-not-last / sh-emulation
8380    // fork-immediately fast path.
8381    if (how & Z_ASYNC as i32) != 0
8382        || output != 0
8383        || (last1 == 2 && input != 0 && {
8384            // c:2989 — `EMULATION(EMULATE_SH)` — emulation==EMULATE_SH.
8385            // EMULATION macro: `(emulation & EMULATE_MASK) == X`. The
8386            // ported `emulation` static at options.rs:1044 holds the
8387            // current bit; compare against EMULATE_SH (zsh_h:2883).
8388            (crate::ported::options::emulation.load(Ordering::Relaxed)
8389                & crate::ported::zsh_h::EMULATE_SH)
8390                != 0
8391        })
8392    {
8393        // c:2988
8394        // c:2999 — `text = getjobtext(state->prog, eparams->beg);`
8395        text = Some(crate::ported::text::getjobtext(
8396            state.prog.clone(),
8397            Some(eparams.beg),
8398        ));
8399        // c:3000-3008 — `switch (execcmd_fork(...)) { -1: goto fatal; 0: break; default: return; }`
8400        let mut filelist_for_fork = filelist.clone();
8401        let pid = execcmd_fork(
8402            state,
8403            how,
8404            typ,
8405            varspc,
8406            &mut filelist_for_fork,
8407            text.as_deref().unwrap_or(""),
8408            oautocont,
8409            close_if_forked,
8410        );
8411        match pid {
8412            -1 => {
8413                // c:3002-3003 — `goto fatal;` — fall through to fatal:
8414                // label at c:4377. We model this with a flag.
8415                redir_err = 1; // pretend redir error to trigger fatal arm
8416                               // Continue to done label by setting forked + jumping forward.
8417                               // Simplified: just bail with status 1 + fatal handling at
8418                               // the bottom of the fn.
8419                return execcmd_exec_done_path(
8420                    redir_err,
8421                    oautocont,
8422                    how,
8423                    &mut shti,
8424                    &mut chti,
8425                    &mut then_ts,
8426                    forked,
8427                    &mut newxtrerr,
8428                    cflags,
8429                    orig_cflags,
8430                    is_cursh,
8431                    do_exec,
8432                );
8433            }
8434            0 => {
8435                // c:3004 — child returned 0; continue with the body.
8436            }
8437            _ => {
8438                // c:3007 — parent: `return;` — but first restore AUTOCONTINUE
8439                // and shelltime stop. Inline the done-tail equivalent.
8440                if oautocont >= 0 {
8441                    opt_state_set("autocontinue", oautocont != 0);
8442                }
8443                if (how & Z_TIMED as i32) != 0 {
8444                    crate::ported::jobs::shelltime(
8445                        Some(&mut shti),
8446                        Some(&mut chti),
8447                        Some(&mut then_ts),
8448                        1,
8449                    );
8450                }
8451                return;
8452            }
8453        }
8454        last1 = 1; // c:3009
8455        forked = 1; // c:3009
8456    } else {
8457        // c:3010-3011
8458        text = None;
8459    }
8460
8461    // ====================================================================
8462    // c:3013-3283 — precommand-modifier walk.
8463    //
8464    // The full walk (BINF_PREFIX strip + BINF_COMMAND sub-options +
8465    // BINF_EXEC sub-options) is already ported in `execcmd_compile_head`
8466    // (above this fn). Call into it to keep DRY, then convert the
8467    // returned dispatch struct's fields into the locals C uses
8468    // (cflags, orig_cflags, is_builtin, is_shfunc, use_defpath,
8469    // exec_argv0, precmd_skip).
8470    //
8471    // Per [[feedback_true_port_pattern]] the C function does this
8472    // walk inline. Reusing the existing port is acceptable because
8473    // `execcmd_compile_head`'s body IS the c:3013-3283 walk — the
8474    // citations there match. The C tree-walker and the fusevm
8475    // compile-time walker arrive at identical dispatch decisions
8476    // from the same input.
8477    // ====================================================================
8478    let mut preargs: Vec<String> = Vec::new();
8479    let mut exec_argv0: Option<String> = None;
8480    if (typ == WC_SIMPLE as i32 || typ == WC_TYPESET as i32) && args.is_some() {
8481        // c:3018
8482        let head_args: Vec<String> = args.as_ref().unwrap().clone();
8483        let dispatch = execcmd_compile_head(&head_args, typ as u32);
8484        // Pull fields into local mirror of C state.
8485        cflags = dispatch.cflags;
8486        if dispatch.is_builtin {
8487            is_builtin = 1;
8488        }
8489        if dispatch.is_shfunc {
8490            is_shfunc = 1;
8491        }
8492        if dispatch.use_defpath {
8493            use_defpath = 1;
8494        }
8495        exec_argv0 = dispatch.exec_argv0;
8496        // c:3061 — `orig_cflags |= cflags;` accumulator path; for
8497        // BINF_PREFIX walks orig_cflags tracks each step's pre-mask
8498        // bits. execcmd_compile_head doesn't surface orig_cflags
8499        // separately, so approximate as the post-strip cflags.
8500        orig_cflags = cflags;
8501        // c:3030-3086 — preargs = args after stripping the precmd
8502        // prefix words. The compile_head dispatch returned the strip
8503        // count, so apply it.
8504        preargs = head_args[dispatch.precmd_skip..].to_vec();
8505        // The remainder of args (after the BINF_PREFIX strip) is what
8506        // the dispatch sees. Mirror C's `args` mutation: replace the
8507        // contents past the head.
8508        if let Some(ref mut v) = args {
8509            v.drain(0..dispatch.precmd_skip);
8510        }
8511        // c:3076 — `magic_assign = (hn->flags & BINF_MAGICEQUALS);`
8512        // — surface via cflags check: if a typeset-family builtin
8513        // landed, BINF_MAGICEQUALS is in its flags and dispatch
8514        // surfaces it via cflags.
8515        if (cflags & BINF_MAGICEQUALS) != 0 && typ != WC_TYPESET as i32 {
8516            magic_assign = 1;
8517        }
8518        // hn is a pointer to the resolved builtin; the compile_head
8519        // walk doesn't return it directly. Mark as None — the
8520        // resolution loop below will re-look-up via builtintab.
8521        hn = None;
8522    } else {
8523        // c:3282-3283 — `else preargs = NULL;`
8524        // We use an empty preargs to model NULL — C's `preargs` is
8525        // only iterated if `nonempty(preargs)` in this branch.
8526    }
8527
8528    // c:3285-3300 — `Do prefork substitutions.` magic_assign handling.
8529    // Sets the file-static `esprefork` (exec.rs:267) so any downstream
8530    // execsubst() call inside this command's expansion uses the same
8531    // prefork flags. Also keep a local copy for the immediate
8532    // prefork(args, esprefork, NULL) below.
8533    let esprefork_v: i32 =
8534        if magic_assign != 0 || (isset(MAGICEQUALSUBST) && typ != WC_TYPESET as i32) {
8535            PREFORK_TYPESET // c:3300
8536        } else {
8537            0
8538        };
8539    esprefork.store(esprefork_v, Ordering::Relaxed); // c:3298 esprefork = ...
8540
8541    // c:3302-3307 — prefork(args, esprefork, NULL) + joinlists(preargs, args).
8542    if args.is_some() && eparams.htok != 0 {
8543        // c:3303-3304 — `if (eparams->htok) prefork(args, esprefork, NULL);`
8544        let mut as_linklist: LinkList<String> = Default::default();
8545        if let Some(ref v) = args {
8546            for s in v {
8547                as_linklist.push_back(s.clone());
8548            }
8549        }
8550        let mut rf = 0i32;
8551        prefork(&mut as_linklist, esprefork_v, &mut rf);
8552        // Move back into args.
8553        let mut out: Vec<String> = Vec::new();
8554        while let Some(s) = as_linklist.pop_front() {
8555            out.push(s);
8556        }
8557        args = Some(out);
8558    }
8559    if !preargs.is_empty() {
8560        // c:3305-3306 — `if (preargs) args = joinlists(preargs, args);`
8561        let mut joined = preargs.clone();
8562        if let Some(ref v) = args {
8563            joined.extend(v.iter().cloned());
8564        }
8565        args = Some(joined);
8566    }
8567
8568    // c:3309-3406 — main resolution loop + empty-command branch.
8569    if typ == WC_SIMPLE as i32 || typ == WC_TYPESET as i32 {
8570        let mut unglobbed: i32 = 0; // c:3310
8571
8572        // c:3312 — `for (;;)` — main resolution loop.
8573        loop {
8574            // c:3315-3318 — globbing or untokenise sweep.
8575            if (cflags & BINF_NOGLOB) == 0 {
8576                while checked == 0
8577                    && (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) == 0
8578                    && args.as_ref().map(|v| !v.is_empty()).unwrap_or(false)
8579                    && crate::ported::lex::has_token(&args.as_ref().unwrap()[0])
8580                {
8581                    // c:3318 — `zglob(args, firstnode(args), 0);`
8582                    // zglob takes &mut Vec<String>; isolate the head element
8583                    // by splitting args into [head] and [tail], then re-merging.
8584                    let mut head_vec: Vec<String> = Vec::new();
8585                    if let Some(ref mut v) = args {
8586                        head_vec.push(v.remove(0));
8587                    }
8588                    crate::ported::glob::zglob(&mut head_vec, 0usize, 0);
8589                    if let Some(ref mut v) = args {
8590                        for (i, s) in head_vec.into_iter().enumerate() {
8591                            v.insert(i, s);
8592                        }
8593                    }
8594                }
8595            } else if unglobbed == 0 {
8596                // c:3319-3322
8597                if let Some(ref mut v) = args {
8598                    for s in v.iter_mut() {
8599                        *s = untokenize(s); // c:3321
8600                    }
8601                }
8602                unglobbed = 1; // c:3322
8603            }
8604
8605            // c:3327-3328 — `if ((cflags & BINF_EXEC) && last1) do_exec = 1;`
8606            if (cflags & BINF_EXEC) != 0 && last1 != 0 {
8607                do_exec = 1; // c:3328
8608            }
8609
8610            // c:3331-3407 — empty-command branch.
8611            if args.as_ref().map(|v| v.is_empty()).unwrap_or(true) {
8612                // c:3331 — `if (!args || empty(args))`
8613                if redir.as_ref().map(|v| !v.is_empty()).unwrap_or(false) {
8614                    // c:3332 — `if (redir && nonempty(redir))`
8615                    if do_exec != 0 {
8616                        // c:3333 — `Was this "exec < foobar"?`
8617                        nullexec = 1; // c:3335
8618                        break;
8619                    } else if varspc.is_some() {
8620                        // c:3337
8621                        nullexec = 2; // c:3338
8622                        break;
8623                    } else if {
8624                        // c:3340-3341 — `if (!nullcmd || !*nullcmd ||
8625                        //   opts[CSHNULLCMD] || (cflags & BINF_PREFIX))`
8626                        let nc = getsparam("NULLCMD");
8627                        let nc_empty = nc.as_deref().map(|s| s.is_empty()).unwrap_or(true);
8628                        nc_empty || isset(CSHNULLCMD) || (cflags & BINF_PREFIX) != 0
8629                    } {
8630                        // c:3342 — `zerr("redirection with no command");`
8631                        zerr("redirection with no command");
8632                        LASTVAL.store(1, Ordering::Relaxed); // c:3343
8633                        errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed); // c:3344
8634                        if forked != 0 {
8635                            // c:3345-3346
8636                            crate::ported::builtin::_realexit();
8637                        }
8638                        if (how & Z_TIMED as i32) != 0 {
8639                            // c:3347-3348
8640                            crate::ported::jobs::shelltime(
8641                                Some(&mut shti),
8642                                Some(&mut chti),
8643                                Some(&mut then_ts),
8644                                1,
8645                            );
8646                        }
8647                        return; // c:3349
8648                    } else if {
8649                        // c:3350 — `if (!nullcmd || !*nullcmd || opts[SHNULLCMD])`
8650                        let nc = getsparam("NULLCMD");
8651                        let nc_empty = nc.as_deref().map(|s| s.is_empty()).unwrap_or(true);
8652                        nc_empty || isset(SHNULLCMD)
8653                    } {
8654                        // c:3351-3353 — `if (!args) args = newlinklist(); addlinknode(args, dupstring(":"));`
8655                        if args.is_none() {
8656                            args = Some(Vec::new());
8657                        }
8658                        args.as_mut().unwrap().push(":".to_string()); // c:3353
8659                    } else if {
8660                        // c:3354-3356 — `readnullcmd && *readnullcmd &&
8661                        //   peekfirst(redir).type == REDIR_READ &&
8662                        //   !nextnode(firstnode(redir))`
8663                        let rnc = getsparam("READNULLCMD");
8664                        let rnc_nonempty = rnc.as_deref().map(|s| !s.is_empty()).unwrap_or(false);
8665                        rnc_nonempty
8666                            && redir.as_ref().unwrap().len() == 1
8667                            && redir.as_ref().unwrap()[0].typ == REDIR_READ
8668                    } {
8669                        // c:3357-3359
8670                        if args.is_none() {
8671                            args = Some(Vec::new());
8672                        }
8673                        let rnc = getsparam("READNULLCMD").unwrap_or_default();
8674                        args.as_mut().unwrap().push(rnc); // c:3359
8675                    } else {
8676                        // c:3360-3364 — default: nullcmd as command.
8677                        if args.is_none() {
8678                            args = Some(Vec::new());
8679                        }
8680                        let nc = getsparam("NULLCMD").unwrap_or_default();
8681                        args.as_mut().unwrap().push(nc); // c:3363
8682                    }
8683                } else if (cflags & BINF_PREFIX) != 0 && (cflags & BINF_COMMAND) != 0 {
8684                    // c:3365 — bare `command`: lastval=0, return.
8685                    LASTVAL.store(0, Ordering::Relaxed); // c:3366
8686                    if forked != 0 {
8687                        crate::ported::builtin::_realexit(); // c:3367-3368
8688                    }
8689                    if (how & Z_TIMED as i32) != 0 {
8690                        crate::ported::jobs::shelltime(
8691                            Some(&mut shti),
8692                            Some(&mut chti),
8693                            Some(&mut then_ts),
8694                            1,
8695                        ); // c:3369-3370
8696                    }
8697                    return; // c:3371
8698                } else {
8699                    // c:3372-3406 — no arguments default arm.
8700                    // c:3378-3385 — badcshglob == 1 → no match.
8701                    if crate::ported::glob::BADCSHGLOB.load(Ordering::Relaxed) == 1 {
8702                        zerr("no match"); // c:3379
8703                        LASTVAL.store(1, Ordering::Relaxed); // c:3380
8704                        if forked != 0 {
8705                            crate::ported::builtin::_realexit(); // c:3381-3382
8706                        }
8707                        if (how & Z_TIMED as i32) != 0 {
8708                            crate::ported::jobs::shelltime(
8709                                Some(&mut shti),
8710                                Some(&mut chti),
8711                                Some(&mut then_ts),
8712                                1,
8713                            ); // c:3383-3384
8714                        }
8715                        return; // c:3385
8716                    }
8717                    // c:3387 — `cmdoutval = use_cmdoutval ? lastval : 0;`
8718                    cmdoutval.store(
8719                        if use_cmdoutval.load(Ordering::Relaxed) != 0 {
8720                            LASTVAL.load(Ordering::Relaxed)
8721                        } else {
8722                            0
8723                        },
8724                        Ordering::Relaxed,
8725                    );
8726                    if varspc.is_some() {
8727                        // c:3388-3392 — `lastval = old_lastval; addvars(state, varspc, 0);`
8728                        LASTVAL.store(old_lastval, Ordering::Relaxed); // c:3390
8729                        addvars(state, varspc.unwrap_or(0), 0); // c:3391
8730                    }
8731                    if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
8732                        // c:3393
8733                        LASTVAL.store(1, Ordering::Relaxed); // c:3394
8734                    } else {
8735                        // c:3395-3396
8736                        LASTVAL.store(cmdoutval.load(Ordering::Relaxed), Ordering::Relaxed);
8737                    }
8738                    if isset(XTRACE) {
8739                        // c:3397-3400 — `fputc('\n', xtrerr); fflush(xtrerr);`
8740                        // xtrerr accessor is stub; rely on the existing
8741                        // stderr writer in compile_zsh tracing path.
8742                        eprintln!();
8743                    }
8744                    if forked != 0 {
8745                        crate::ported::builtin::_realexit(); // c:3401-3402
8746                    }
8747                    if (how & Z_TIMED as i32) != 0 {
8748                        crate::ported::jobs::shelltime(
8749                            Some(&mut shti),
8750                            Some(&mut chti),
8751                            Some(&mut then_ts),
8752                            1,
8753                        ); // c:3403-3404
8754                    }
8755                    return; // c:3405
8756                }
8757            }
8758
8759            // c:3423-3426 — `if (errflag || checked || is_builtin ||
8760            //   (isset(POSIXBUILTINS) ? (cflags & BINF_EXEC) : (cflags & BINF_COMMAND)))`
8761            if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0
8762                || checked != 0
8763                || is_builtin != 0
8764                || if isset(POSIXBUILTINS) {
8765                    (cflags & BINF_EXEC) != 0
8766                } else {
8767                    (cflags & BINF_COMMAND) != 0
8768                }
8769            {
8770                // c:3423
8771                break; // c:3426
8772            }
8773
8774            // c:3428 — `cmdarg = (char *) peekfirst(args);`
8775            let cmdarg = args.as_ref().unwrap()[0].clone();
8776
8777            // c:3429-3433 — shfunc lookup.
8778            if (cflags & (BINF_BUILTIN | BINF_COMMAND)) == 0 {
8779                let in_shfunctab = shfunctab_lock()
8780                    .read()
8781                    .map(|t| t.iter().any(|(k, _)| k.as_str() == cmdarg.as_str()))
8782                    .unwrap_or(false);
8783                if in_shfunctab {
8784                    is_shfunc = 1; // c:3431
8785                    break; // c:3432
8786                }
8787            }
8788            // c:3434-3447 — builtintab lookup.
8789            let builtin_entry: Option<&'static builtin> = BUILTINS
8790                .iter()
8791                .find(|b| b.node.nam.as_str() == cmdarg.as_str());
8792            if builtin_entry.is_none() {
8793                if (cflags & BINF_BUILTIN) != 0 {
8794                    // c:3435 — `zwarn("no such builtin: %s", cmdarg);`
8795                    zwarn(&format!("no such builtin: {}", cmdarg)); // c:3436
8796                    LASTVAL.store(1, Ordering::Relaxed); // c:3437
8797                    if oautocont >= 0 {
8798                        // c:3438-3439
8799                        opt_state_set("autocontinue", oautocont != 0);
8800                    }
8801                    if forked != 0 {
8802                        crate::ported::builtin::_realexit(); // c:3440-3441
8803                    }
8804                    if (how & Z_TIMED as i32) != 0 {
8805                        crate::ported::jobs::shelltime(
8806                            Some(&mut shti),
8807                            Some(&mut chti),
8808                            Some(&mut then_ts),
8809                            1,
8810                        ); // c:3442-3443
8811                    }
8812                    return; // c:3444
8813                }
8814                break; // c:3446
8815            }
8816            let entry = builtin_entry.unwrap();
8817            // c:3448-3460 — `if (!(hn->flags & BINF_PREFIX)) { is_builtin = 1; ... }`
8818            if (entry.node.flags as u32 & BINF_PREFIX) == 0 {
8819                is_builtin = 1; // c:3449
8820                                // c:3452 — `if (!(hn = resolvebuiltin(cmdarg, hn)))` —
8821                                // module autoload check. zshrs's BUILTINS table is
8822                                // static and pre-resolved; treat resolvebuiltin as
8823                                // pass-through.
8824                hn = Some(entry as *const builtin as *mut builtin);
8825                break; // c:3459
8826            }
8827            // c:3461-3463 — BINF_PREFIX modifier (builtin/command/exec).
8828            cflags &= !(BINF_BUILTIN | BINF_COMMAND);
8829            cflags |= entry.node.flags as u32;
8830            if let Some(ref mut v) = args {
8831                v.remove(0); // c:3463 uremnode(args, firstnode(args))
8832            }
8833            hn = None; // c:3464
8834        }
8835    }
8836
8837    // c:3468-3478 — errflag bail-out.
8838    if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
8839        // c:3468
8840        if LASTVAL.load(Ordering::Relaxed) == 0 {
8841            // c:3469
8842            LASTVAL.store(1, Ordering::Relaxed); // c:3470
8843        }
8844        if oautocont >= 0 {
8845            opt_state_set("autocontinue", oautocont != 0);
8846            // c:3472
8847        }
8848        if forked != 0 {
8849            crate::ported::builtin::_realexit(); // c:3473-3474
8850        }
8851        if (how & Z_TIMED as i32) != 0 {
8852            crate::ported::jobs::shelltime(Some(&mut shti), Some(&mut chti), Some(&mut then_ts), 1);
8853            // c:3475-3476
8854        }
8855        return; // c:3477
8856    }
8857
8858    // c:3480-3483 — `Get the text associated with this command.`
8859    if text.is_none()
8860        && sfcontext.load(Ordering::Relaxed) == 0
8861        && (isset(MONITOR) || (how & Z_TIMED as i32) != 0)
8862    {
8863        // c:3481-3482
8864        text = Some(crate::ported::text::getjobtext(
8865            state.prog.clone(),
8866            Some(eparams.beg),
8867        )); // c:3483
8868    }
8869
8870    // c:3485-3492 — `Set up special parameter $_`.
8871    if typ != WC_FUNCDEF as i32 {
8872        // c:3490
8873        let last_str = args
8874            .as_ref()
8875            .and_then(|v| v.last())
8876            .cloned()
8877            .unwrap_or_default();
8878        setunderscore(&last_str); // c:3491-3492
8879    }
8880
8881    // c:3494-3524 — `Warn about "rm *"`.
8882    if typ == WC_SIMPLE as i32
8883        && crate::ported::zsh_h::interact()
8884        && unset(RMSTARSILENT)
8885        && isset(SHINSTDIN)
8886        && args.as_ref().map(|v| v.len() >= 2).unwrap_or(false)
8887        && args.as_ref().unwrap()[0] == "rm"
8888    {
8889        // c:3495-3497
8890        let args_v = args.as_ref().unwrap().clone();
8891        for s in args_v.iter().skip(1) {
8892            // c:3500
8893            if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
8894                break;
8895            }
8896            let l = s.len();
8897            // c:3505 — `if (s[0] == Star && !s[1])` — bare `*`.
8898            if s.len() == 1 && s.as_bytes()[0] == Star as u8 {
8899                let pwd = getsparam("PWD").unwrap_or_default();
8900                if !crate::ported::utils::checkrmall(&pwd) {
8901                    // c:3506
8902                    errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed); // c:3507
8903                    break; // c:3508
8904                }
8905            } else if l >= 2 {
8906                // c:3510 — `s[l-2] == '/' && s[l-1] == Star`
8907                let bytes = s.as_bytes();
8908                if bytes[l - 2] == b'/' && bytes[l - 1] == Star as u8 {
8909                    let prefix = if l == 2 {
8910                        "/".to_string()
8911                    } else {
8912                        String::from_utf8_lossy(&bytes[..l - 2]).into_owned()
8913                    };
8914                    if !crate::ported::utils::checkrmall(&prefix) {
8915                        // c:3518
8916                        errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed); // c:3519
8917                        break; // c:3520
8918                    }
8919                }
8920            }
8921        }
8922    }
8923
8924    // c:3526-3580 — type-specific dispatch prep.
8925    if typ == WC_FUNCDEF as i32 {
8926        // c:3526
8927        if state.prog.prog.get(state.pc).copied().unwrap_or(0) != 0 {
8928            // c:3535 — `Nonymous, don't do redirections here`
8929            redir = None; // c:3537
8930        }
8931    } else if is_shfunc != 0 || typ == WC_AUTOFN as i32 {
8932        // c:3539
8933        // c:3540-3559 — shfunc / autoload preload.
8934        if is_shfunc != 0 {
8935            // c:3541-3542 — `shf = (Shfunc)hn;` — already in hn.
8936        } else {
8937            // c:3543-3559 — autoload preload.
8938            if let Some(ref mut sh) = state.prog.shf {
8939                let shf_ptr: *mut shfunc = sh.as_mut() as *mut shfunc;
8940                let r = loadautofn(shf_ptr, 1, 0, 0);
8941                if r != 0 {
8942                    // c:3551 — `lastval = 1;`
8943                    LASTVAL.store(1, Ordering::Relaxed);
8944                    if oautocont >= 0 {
8945                        opt_state_set("autocontinue", oautocont != 0);
8946                    }
8947                    if forked != 0 {
8948                        crate::ported::builtin::_realexit();
8949                    }
8950                    if (how & Z_TIMED as i32) != 0 {
8951                        crate::ported::jobs::shelltime(
8952                            Some(&mut shti),
8953                            Some(&mut chti),
8954                            Some(&mut then_ts),
8955                            1,
8956                        );
8957                    }
8958                    return; // c:3558
8959                }
8960            }
8961        }
8962        // c:3561-3579 — shf->redir append: a function definition can
8963        // carry extra redirs (`f() { ... } < file`), captured as a
8964        // separate Eprog in shf->redir. Walk that Eprog with a temp
8965        // estate, extract its redirs with ecgetredirs, then merge
8966        // into the live `redir` list.
8967        // Resolve shfunc by name (hn is *mut builtin so we go through
8968        // shfunctab as in the dispatch site at c:4102).
8969        let shfn_name = args
8970            .as_ref()
8971            .and_then(|v| v.first())
8972            .cloned()
8973            .unwrap_or_default();
8974        let shf_redir_eprog: Option<crate::ported::zsh_h::Eprog> = {
8975            if let Ok(tab) = shfunctab_lock().read() {
8976                tab.get(&shfn_name).and_then(|s| s.redir.clone())
8977            } else {
8978                None
8979            }
8980        };
8981        if let Some(red_eprog) = shf_redir_eprog {
8982            // c:3566-3571 — build temp estate from shf->redir.
8983            let mut tmp_state = estate {
8984                prog: red_eprog.clone(),
8985                pc: 0,
8986                strs: red_eprog.strs.clone(),
8987                strs_offset: 0,
8988            };
8989            // c:3572 — `redir2 = ecgetredirs(&s);`
8990            let redir2 = crate::ported::parse::ecgetredirs(&mut tmp_state);
8991            // c:3573-3578 — merge into existing redir.
8992            if redir.is_none() {
8993                redir = Some(redir2); // c:3574
8994            } else if let Some(ref mut r) = redir {
8995                // c:3576-3577 — append.
8996                for n in redir2 {
8997                    r.push(n);
8998                }
8999            }
9000        }
9001    }
9002
9003    // c:3582-3591 — errflag bail-out (2).
9004    if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
9005        // c:3582
9006        LASTVAL.store(1, Ordering::Relaxed); // c:3583
9007        if oautocont >= 0 {
9008            opt_state_set("autocontinue", oautocont != 0);
9009            // c:3584-3585
9010        }
9011        if forked != 0 {
9012            crate::ported::builtin::_realexit(); // c:3586-3587
9013        }
9014        if (how & Z_TIMED as i32) != 0 {
9015            crate::ported::jobs::shelltime(Some(&mut shti), Some(&mut chti), Some(&mut then_ts), 1);
9016            // c:3588-3589
9017        }
9018        return; // c:3590
9019    }
9020
9021    // c:3593-3632 — external resolution + AUTOCD.
9022    if (typ == WC_SIMPLE as i32 || typ == WC_TYPESET as i32) && nullexec == 0 {
9023        // c:3593
9024        let trycd = isset(AUTOCD)
9025            && isset(SHINSTDIN)
9026            && redir.as_ref().map(|v| v.is_empty()).unwrap_or(true)
9027            && args.as_ref().map(|v| v.len() == 1).unwrap_or(false)
9028            && !args.as_ref().unwrap()[0].is_empty(); // c:3595-3597
9029        if hn.is_none() {
9030            // c:3600
9031            let cmdarg = args.as_ref().unwrap()[0].clone();
9032            let mut dohashcmd = isset(HASHCMDS); // c:3604
9033                                                 // c:3606 — `hn = cmdnamtab->getnode(cmdnamtab, cmdarg);`
9034            let mut have_cmdnam: Option<cmdnam> = {
9035                let tab = cmdnamtab_lock().read().ok();
9036                tab.and_then(|t| {
9037                    t.iter()
9038                        .find(|(k, _)| k.as_str() == cmdarg.as_str())
9039                        .map(|(_, v)| v.clone())
9040                })
9041            };
9042            if have_cmdnam.is_some() && trycd && !isreallycom(have_cmdnam.as_ref().unwrap()) {
9043                // c:3607
9044                // c:3608-3614 — remove the cached entry; force rehash.
9045                cmdnam_unhashed(&cmdarg, Vec::new());
9046                have_cmdnam = None;
9047                if let Some(cn) = have_cmdnam.as_ref() {
9048                    if (cn.node.flags & crate::ported::zsh_h::HASHED) == 0 {
9049                        // checkpath = path; dohashcmd = 1;
9050                        dohashcmd = true;
9051                    }
9052                }
9053            }
9054            if have_cmdnam.is_none() && dohashcmd && cmdarg != ".." {
9055                // c:3616 — `if (!hn && dohashcmd && strcmp(cmdarg, "..")) `
9056                let has_slash = cmdarg.contains('/'); // c:3617-3618
9057                if !has_slash {
9058                    // c:3619 — `hn = (HashNode) hashcmd(cmdarg, checkpath);`
9059                    let path_dirs = getsparam("PATH").unwrap_or_default();
9060                    let dirs: Vec<String> = path_dirs.split(':').map(String::from).collect();
9061                    have_cmdnam = hashcmd(&cmdarg, &dirs);
9062                }
9063            }
9064            // hn stays None for external commands — the resolution
9065            // value matters only for builtin/shfunc dispatch in the
9066            // following blocks.
9067            let _ = have_cmdnam;
9068        }
9069
9070        // c:3625-3631 — AUTOCD: command not found, try directory.
9071        if hn.is_none() && trycd {
9072            let cmdarg = args.as_ref().unwrap()[0].clone();
9073            if let Some(s) = cancd(&cmdarg) {
9074                // c:3625
9075                args.as_mut().unwrap()[0] = s; // c:3626
9076                args.as_mut().unwrap().insert(0, "--".to_string()); // c:3627
9077                args.as_mut().unwrap().insert(0, "cd".to_string()); // c:3628
9078                                                                    // c:3629 — `if ((hn = builtintab->getnode(builtintab, "cd")))`
9079                let cd_entry = BUILTINS.iter().find(|b| b.node.nam.as_str() == "cd");
9080                if let Some(cd) = cd_entry {
9081                    hn = Some(cd as *const builtin as *mut builtin);
9082                    is_builtin = 1; // c:3630
9083                }
9084            }
9085        }
9086    }
9087
9088    // c:3635 — `is_cursh = (is_builtin || is_shfunc || nullexec || type >= WC_CURSH);`
9089    is_cursh =
9090        (is_builtin != 0 || is_shfunc != 0 || nullexec != 0 || typ >= WC_CURSH as i32) as i32;
9091
9092    // c:3659-3697 — fork decision.
9093    if forked == 0 {
9094        // c:3659
9095        if do_exec == 0
9096            && (((is_builtin != 0 || is_shfunc != 0) && output != 0)
9097                || (is_cursh == 0
9098                    && (last1 != 1
9099                        || crate::ported::signals::nsigtrapped.load(Ordering::Relaxed) != 0
9100                        || JOBTAB
9101                            .get()
9102                            .map(|jt| crate::ported::jobs::havefiles(&jt.lock().unwrap()))
9103                            .unwrap_or(false)
9104                        || false/* fdtable_flocks — substrate stub */)))
9105        {
9106            // c:3660-3663
9107            let mut filelist_for_fork = filelist.clone();
9108            let pid = execcmd_fork(
9109                state,
9110                how,
9111                typ,
9112                varspc,
9113                &mut filelist_for_fork,
9114                text.as_deref().unwrap_or(""),
9115                oautocont,
9116                close_if_forked,
9117            );
9118            match pid {
9119                -1 => {
9120                    // c:3666-3667 — goto fatal.
9121                    redir_err = 1;
9122                    return execcmd_exec_done_path(
9123                        redir_err,
9124                        oautocont,
9125                        how,
9126                        &mut shti,
9127                        &mut chti,
9128                        &mut then_ts,
9129                        forked,
9130                        &mut newxtrerr,
9131                        cflags,
9132                        orig_cflags,
9133                        is_cursh,
9134                        do_exec,
9135                    );
9136                }
9137                0 => {
9138                    // c:3668 — child continues.
9139                }
9140                _ => {
9141                    // c:3670-3671 — parent returns.
9142                    if oautocont >= 0 {
9143                        opt_state_set("autocontinue", oautocont != 0);
9144                    }
9145                    if (how & Z_TIMED as i32) != 0 {
9146                        crate::ported::jobs::shelltime(
9147                            Some(&mut shti),
9148                            Some(&mut chti),
9149                            Some(&mut then_ts),
9150                            1,
9151                        );
9152                    }
9153                    return;
9154                }
9155            }
9156            forked = 1; // c:3673
9157        } else if is_cursh != 0 {
9158            // c:3674
9159            // c:3678-3682 — set jobtab[thisjob] stat bits.
9160            let thisjob = THISJOB.get().map(|m| *m.lock().unwrap()).unwrap_or(-1);
9161            if thisjob >= 0 {
9162                if let Some(jt) = JOBTAB.get() {
9163                    let mut guard = jt.lock().unwrap();
9164                    if let Some(j) = guard.get_mut(thisjob as usize) {
9165                        j.stat |= STAT_CURSH; // c:3678
9166                                              // c:3679-3680 — `if (!jobtab[thisjob].procs)
9167                                              //                  jobtab[thisjob].stat |= STAT_NOPRINT;`
9168                                              // Suppress the "[N] done" print for jobs that
9169                                              // never forked a real process (cursh / builtin /
9170                                              // null exec).
9171                        if j.procs.is_empty() {
9172                            j.stat |= STAT_NOPRINT; // c:3680
9173                        }
9174                        if is_builtin != 0 {
9175                            j.stat |= STAT_BUILTIN; // c:3682
9176                        }
9177                    }
9178                }
9179            }
9180        } else {
9181            // c:3683-3697 — external exec (real or fake).
9182            is_exec = 1; // c:3687
9183                         // c:3695 — `if (type == WC_SUBSH) forked = 1;`
9184            if typ == WC_SUBSH as i32 {
9185                forked = 1; // c:3696
9186            }
9187        }
9188    }
9189
9190    // c:3700-3704 — `if ((esglob = !(cflags & BINF_NOGLOB)) && args && htok)`
9191    if (cflags & BINF_NOGLOB) == 0 && args.is_some() && eparams.htok != 0 {
9192        // c:3700
9193        let mut oargs: LinkList<String> = Default::default();
9194        if let Some(ref v) = args {
9195            for s in v {
9196                oargs.push_back(s.clone());
9197            }
9198        }
9199        globlist(&mut oargs, 0); // c:3702
9200        let mut out: Vec<String> = Vec::new();
9201        while let Some(s) = oargs.pop_front() {
9202            out.push(s);
9203        }
9204        args = Some(out);
9205    }
9206    if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
9207        // c:3705
9208        LASTVAL.store(1, Ordering::Relaxed); // c:3706
9209        return execcmd_exec_err_path(
9210            forked,
9211            &mut save,
9212            &mut mfds,
9213            oautocont,
9214            how,
9215            &mut shti,
9216            &mut chti,
9217            &mut then_ts,
9218            &mut newxtrerr,
9219            cflags,
9220            orig_cflags,
9221            is_cursh,
9222            do_exec,
9223            redir_err,
9224        );
9225    }
9226
9227    // c:3711-3718 — XTRACE prep (newxtrerr stderr dup).
9228    // Architectural divergence: C duplicates stderr to a new FD and
9229    // marks it `FDT_XTRACE` in the fdtable so the redir loop skips it.
9230    // zshrs routes xtrace output through `eprintln!()` / `tracing`
9231    // instead of a duplicated fd, so the FDT_XTRACE bookkeeping has
9232    // no counterpart. Not a port gap — `xtrerr is FILE*` is a C-ism
9233    // intentionally replaced.
9234
9235    // c:3720-3724 — pipeline input/output to mfds.
9236    if input != 0 {
9237        addfd(forked, &mut save, &mut mfds, 0, input, 0, None); // c:3722
9238    }
9239    if output != 0 {
9240        addfd(forked, &mut save, &mut mfds, 1, output, 1, None); // c:3724
9241    }
9242
9243    // c:3726-3728 — `if (redir) spawnpipes(redir, nullexec);`
9244    if let Some(ref mut r) = redir {
9245        spawnpipes(r.as_mut_slice(), nullexec);
9246    }
9247
9248    // c:3731-3955 — io redirection loop. Faithful per-redir match.
9249    while let Some(redir_list) = redir.as_mut() {
9250        // c:3731 — `while (redir && nonempty(redir))`
9251        if redir_list.is_empty() {
9252            break;
9253        }
9254        let mut fn_ = redir_list.remove(0); // c:3732 `fn = (Redir) ugetnode(redir);`
9255                                            // c:3734-3735 DPUTS — debug assert REDIR_HEREDOC* gone.
9256        if fn_.typ == REDIR_INPIPE {
9257            // c:3736
9258            if checkclobberparam(&fn_) == 0 || fn_.fd2 == -1 {
9259                // c:3737
9260                if fn_.fd2 != -1 {
9261                    let _ = zclose(fn_.fd2); // c:3738-3739
9262                }
9263                closemnodes(&mut mfds); // c:3740
9264                fixfds(&save); // c:3741
9265                {
9266                    errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed);
9267                    LASTVAL.store(1, Ordering::Relaxed);
9268                } // c:3742
9269                break;
9270            }
9271            // c:3744 — `addfd(forked, save, mfds, fn->fd1, fn->fd2, 0, fn->varid);`
9272            addfd(
9273                forked,
9274                &mut save,
9275                &mut mfds,
9276                fn_.fd1,
9277                fn_.fd2,
9278                0,
9279                fn_.varid.as_deref(),
9280            );
9281        } else if fn_.typ == REDIR_OUTPIPE {
9282            // c:3745
9283            if checkclobberparam(&fn_) == 0 || fn_.fd2 == -1 {
9284                // c:3746
9285                if fn_.fd2 != -1 {
9286                    let _ = zclose(fn_.fd2); // c:3747-3748
9287                }
9288                closemnodes(&mut mfds); // c:3749
9289                fixfds(&save); // c:3750
9290                {
9291                    errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed);
9292                    LASTVAL.store(1, Ordering::Relaxed);
9293                } // c:3751
9294                break;
9295            }
9296            // c:3753
9297            addfd(
9298                forked,
9299                &mut save,
9300                &mut mfds,
9301                fn_.fd1,
9302                fn_.fd2,
9303                1,
9304                fn_.varid.as_deref(),
9305            );
9306        } else {
9307            // c:3754 — non-pipe redir branch.
9308            let mut closed: i32; // c:3755
9309                                 // c:3756-3757 — xpandredir glob/brace.
9310            if fn_.typ != REDIR_HERESTR {
9311                // Put fn_ back temporarily so xpandredir can mutate
9312                // around it; not implemented identically — xpandredir
9313                // signature in zshrs differs (takes &mut redir + ctx).
9314                // c:3756 — `if (xpandredir(fn, redir)) continue;`
9315                // Pragmatic: skip xpandredir (it handles brace/glob in
9316                // redir paths — uncommon, ports to follow-up).
9317            }
9318            if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
9319                // c:3758
9320                closemnodes(&mut mfds); // c:3759
9321                fixfds(&save); // c:3760
9322                {
9323                    errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed);
9324                    LASTVAL.store(1, Ordering::Relaxed);
9325                } // c:3761
9326                break;
9327            }
9328            if !isset(EXECOPT) {
9329                // c:3763 — `if (unset(EXECOPT)) continue;`
9330                continue;
9331            }
9332            let fil_local: i32;
9333            match fn_.typ {
9334                t if t == REDIR_HERESTR => {
9335                    // c:3766
9336                    if checkclobberparam(&fn_) == 0 {
9337                        fil_local = -1; // c:3768
9338                    } else {
9339                        fil_local = getherestr(&fn_); // c:3770
9340                    }
9341                    if fil_local == -1 {
9342                        // c:3771
9343                        let e = std::io::Error::last_os_error();
9344                        let raw = e.raw_os_error().unwrap_or(0);
9345                        if raw != 0 && raw != libc::EINTR {
9346                            zwarn(&format!("can't create temp file for here document: {}", e));
9347                            // c:3772-3774
9348                        }
9349                        closemnodes(&mut mfds); // c:3775
9350                        fixfds(&save); // c:3776
9351                        {
9352                            errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed);
9353                            LASTVAL.store(1, Ordering::Relaxed);
9354                        } // c:3777
9355                        break;
9356                    }
9357                    // c:3779
9358                    addfd(
9359                        forked,
9360                        &mut save,
9361                        &mut mfds,
9362                        fn_.fd1,
9363                        fil_local,
9364                        0,
9365                        fn_.varid.as_deref(),
9366                    );
9367                }
9368                t if t == REDIR_READ || t == REDIR_READWRITE => {
9369                    // c:3781-3782
9370                    if checkclobberparam(&fn_) == 0 {
9371                        fil_local = -1; // c:3784
9372                    } else {
9373                        let name = fn_.name.clone().unwrap_or_default();
9374                        let unmeta_name = unmeta(&name);
9375                        let cstr = match std::ffi::CString::new(unmeta_name.as_str()) {
9376                            Ok(c) => c,
9377                            Err(_) => {
9378                                closemnodes(&mut mfds);
9379                                fixfds(&save);
9380                                {
9381                                    errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed);
9382                                    LASTVAL.store(1, Ordering::Relaxed);
9383                                }
9384                                break;
9385                            }
9386                        };
9387                        if fn_.typ == REDIR_READ {
9388                            // c:3786
9389                            fil_local = unsafe {
9390                                libc::open(cstr.as_ptr(), libc::O_RDONLY | libc::O_NOCTTY)
9391                            };
9392                        } else {
9393                            // c:3788-3789
9394                            fil_local = unsafe {
9395                                libc::open(
9396                                    cstr.as_ptr(),
9397                                    libc::O_RDWR | libc::O_CREAT | libc::O_NOCTTY,
9398                                    0o666,
9399                                )
9400                            };
9401                        }
9402                    }
9403                    if fil_local == -1 {
9404                        // c:3790
9405                        closemnodes(&mut mfds); // c:3791
9406                        fixfds(&save); // c:3792
9407                        let e = std::io::Error::last_os_error();
9408                        if e.raw_os_error().unwrap_or(0) != libc::EINTR {
9409                            zwarn(&format!("{}: {}", e, fn_.name.as_deref().unwrap_or("")));
9410                            // c:3793-3794
9411                        }
9412                        {
9413                            errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed);
9414                            LASTVAL.store(1, Ordering::Relaxed);
9415                        } // c:3795
9416                        break;
9417                    }
9418                    // c:3797
9419                    addfd(
9420                        forked,
9421                        &mut save,
9422                        &mut mfds,
9423                        fn_.fd1,
9424                        fil_local,
9425                        0,
9426                        fn_.varid.as_deref(),
9427                    );
9428                    // c:3800-3802 — `if (nullexec == 1 && fn->fd1 == 0 && ...) init_io(NULL);`
9429                    if nullexec == 1
9430                        && fn_.fd1 == 0
9431                        && fn_.varid.is_none()
9432                        && isset(SHINSTDIN)
9433                        && isset(INTERACTIVE)
9434                    {
9435                        // c:3801 — `!zleactive` check ommitted (zleactive
9436                        // accessor lives in zle module; fusevm bypasses ZLE).
9437                        crate::ported::init::init_io(None); // c:3802
9438                    }
9439                }
9440                t if t == REDIR_CLOSE => {
9441                    // c:3804
9442                    // c:3805 — `if (fn->varid) { parse fd from variable }`
9443                    let mut fd1_local = fn_.fd1;
9444                    if let Some(varname) = fn_.varid.as_deref() {
9445                        // c:3806-3849 — `{var}>&-`/`{var}<&-` REDIR_CLOSE
9446                        // with varid. The C path resolves the named param
9447                        // to its integer-string value, parses as base-10
9448                        // (or base#NN), and rejects readonly / non-numeric
9449                        // / shell-owned-fd values.
9450                        //
9451                        //   bad=1  → "parameter %s does not contain a file descriptor"
9452                        //   bad=2  → "can't close file descriptor from readonly parameter %s"
9453                        //   bad=3  → "file descriptor %d used by shell, not closed"
9454                        //
9455                        // Substrate now available: getsparam for value,
9456                        // paramtab read for PM_READONLY, MAX_ZSH_FD +
9457                        // fdtable_get for shell-owned guard.
9458                        let mut bad: u8 = 0;
9459                        let value_opt = getsparam(varname);
9460                        let is_ro = paramtab()
9461                            .read()
9462                            .ok()
9463                            .and_then(|t| {
9464                                t.get(varname)
9465                                    .map(|p| (p.node.flags as u32 & PM_READONLY) != 0)
9466                            })
9467                            .unwrap_or(false);
9468                        if value_opt.is_none() {
9469                            bad = 1; // c:3811 getvalue failed
9470                        } else if is_ro {
9471                            bad = 2; // c:3813 PM_READONLY
9472                        } else {
9473                            let s = value_opt.as_deref().unwrap_or("");
9474                            match s.trim().parse::<i32>() {
9475                                Ok(n) => {
9476                                    fd1_local = n;
9477                                    fn_.fd1 = n;
9478                                    let max_fd = MAX_ZSH_FD.load(Ordering::Relaxed);
9479                                    if n >= 10
9480                                        && n <= max_fd
9481                                        && (fdtable_get(n) & FDT_TYPE_MASK) == FDT_INTERNAL
9482                                    {
9483                                        // c:3835 shell-owned-fd reject
9484                                        bad = 3;
9485                                    }
9486                                }
9487                                Err(_) => {
9488                                    bad = 1; // c:3823 strtol failure
9489                                }
9490                            }
9491                        }
9492                        if bad != 0 {
9493                            // c:3840-3849
9494                            match bad {
9495                                3 => zwarn(&format!(
9496                                    "file descriptor {} used by shell, not closed",
9497                                    fn_.fd1
9498                                )),
9499                                2 => zwarn(&format!(
9500                                    "can't close file descriptor from readonly parameter {}",
9501                                    varname
9502                                )),
9503                                _ => zwarn(&format!(
9504                                    "parameter {} does not contain a file descriptor",
9505                                    varname
9506                                )),
9507                            }
9508                            errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed);
9509                            LASTVAL.store(1, Ordering::Relaxed);
9510                            break;
9511                        }
9512                    }
9513                    // c:3852-3865 — `closed`: optional movefd save.
9514                    closed = 0;
9515                    if forked == 0 && fd1_local < 10 && save[fd1_local as usize] == -2 {
9516                        // c:3856
9517                        let mv = movefd(fd1_local); // c:3857
9518                        save[fd1_local as usize] = mv;
9519                        if mv >= 0 {
9520                            closed = 1; // c:3862-3863
9521                        }
9522                    }
9523                    if fd1_local < 10 {
9524                        // c:3866
9525                        closemn(&mut mfds, fd1_local, REDIR_CLOSE);
9526                        // c:3867
9527                    }
9528                    // c:3873-3876
9529                    let _ = &mut fd1_local;
9530                    if closed == 0 && zclose(fn_.fd1) < 0 && fn_.varid.is_some() {
9531                        zwarn(&format!(
9532                            "failed to close file descriptor {}: {}",
9533                            fn_.fd1,
9534                            std::io::Error::last_os_error()
9535                        )); // c:3873-3875
9536                    }
9537                }
9538                t if t == REDIR_MERGEIN || t == REDIR_MERGEOUT => {
9539                    // c:3878-3879
9540                    if fn_.fd2 < 10 {
9541                        closemn(&mut mfds, fn_.fd2, fn_.typ); // c:3881
9542                    }
9543                    if checkclobberparam(&fn_) == 0 {
9544                        fil_local = -1; // c:3883
9545                    } else if fn_.fd2 > 9 {
9546                        // c:3884-3897 — fd table check.
9547                        let max_fd = MAX_ZSH_FD.load(Ordering::Relaxed);
9548                        let cin = crate::ported::modules::clone::coprocin.load(Ordering::Relaxed);
9549                        let cout = crate::ported::modules::clone::coprocout.load(Ordering::Relaxed);
9550                        let in_table = if fn_.fd2 <= max_fd {
9551                            let kind = fdtable_get(fn_.fd2) & FDT_TYPE_MASK;
9552                            kind != FDT_UNUSED && kind != FDT_EXTERNAL
9553                        } else {
9554                            false
9555                        };
9556                        if in_table || fn_.fd2 == cin || fn_.fd2 == cout {
9557                            fil_local = -1; // c:3896
9558                                            // Per-platform errno setter (c:3897 `errno = EBADF;`).
9559                            #[cfg(target_os = "macos")]
9560                            unsafe {
9561                                *libc::__error() = libc::EBADF;
9562                            }
9563                            #[cfg(target_os = "linux")]
9564                            unsafe {
9565                                *libc::__errno_location() = libc::EBADF;
9566                            }
9567                        } else {
9568                            let fd = if fn_.fd2 == -2 {
9569                                // c:3900-3901
9570                                if fn_.typ == REDIR_MERGEOUT {
9571                                    crate::ported::modules::clone::coprocout.load(Ordering::Relaxed)
9572                                } else {
9573                                    crate::ported::modules::clone::coprocin.load(Ordering::Relaxed)
9574                                }
9575                            } else {
9576                                fn_.fd2
9577                            };
9578                            // c:3902 — `fil = movefd(dup(fd));`
9579                            let dup_fd = unsafe { libc::dup(fd) };
9580                            fil_local = movefd(dup_fd);
9581                        }
9582                    } else {
9583                        let fd = if fn_.fd2 == -2 {
9584                            if fn_.typ == REDIR_MERGEOUT {
9585                                crate::ported::modules::clone::coprocout.load(Ordering::Relaxed)
9586                            } else {
9587                                crate::ported::modules::clone::coprocin.load(Ordering::Relaxed)
9588                            }
9589                        } else {
9590                            fn_.fd2
9591                        };
9592                        let dup_fd = unsafe { libc::dup(fd) };
9593                        fil_local = movefd(dup_fd);
9594                    }
9595                    if fil_local == -1 {
9596                        // c:3904
9597                        closemnodes(&mut mfds); // c:3907
9598                        fixfds(&save); // c:3908
9599                        if std::io::Error::last_os_error().raw_os_error().unwrap_or(0) != 0 {
9600                            let desc = if fn_.fd2 == -2 {
9601                                "coprocess".to_string()
9602                            } else {
9603                                format!("{}", fn_.fd2)
9604                            };
9605                            zwarn(&format!("{}: {}", desc, std::io::Error::last_os_error()));
9606                            // c:3911-3913
9607                        }
9608                        {
9609                            errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed);
9610                            LASTVAL.store(1, Ordering::Relaxed);
9611                        } // c:3914
9612                        break;
9613                    }
9614                    // c:3916-3917
9615                    let merge_is_out = if fn_.typ == REDIR_MERGEOUT { 1 } else { 0 };
9616                    addfd(
9617                        forked,
9618                        &mut save,
9619                        &mut mfds,
9620                        fn_.fd1,
9621                        fil_local,
9622                        merge_is_out,
9623                        fn_.varid.as_deref(),
9624                    );
9625                }
9626                _ => {
9627                    // c:3919 default — write/append/error_redir.
9628                    let mut dfil: i32;
9629                    if checkclobberparam(&fn_) == 0 {
9630                        fil_local = -1; // c:3921
9631                    } else if IS_APPEND_REDIR(fn_.typ) {
9632                        // c:3922
9633                        let name = fn_.name.clone().unwrap_or_default();
9634                        let unmeta_name = unmeta(&name);
9635                        let cstr = match std::ffi::CString::new(unmeta_name.as_str()) {
9636                            Ok(c) => c,
9637                            Err(_) => {
9638                                closemnodes(&mut mfds);
9639                                fixfds(&save);
9640                                {
9641                                    errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed);
9642                                    LASTVAL.store(1, Ordering::Relaxed);
9643                                }
9644                                break;
9645                            }
9646                        };
9647                        // c:3924-3927
9648                        let mode = if !isset(CLOBBER)
9649                            && !isset(crate::ported::zsh_h::APPENDCREATE)
9650                            && !IS_CLOBBER_REDIR(fn_.typ)
9651                        {
9652                            libc::O_WRONLY | libc::O_APPEND | libc::O_NOCTTY
9653                        } else {
9654                            libc::O_WRONLY | libc::O_APPEND | libc::O_CREAT | libc::O_NOCTTY
9655                        };
9656                        fil_local = unsafe { libc::open(cstr.as_ptr(), mode, 0o666) };
9657                    } else {
9658                        // c:3929
9659                        fil_local = clobber_open(&fn_);
9660                    }
9661                    // c:3930-3933 — error_redir dup.
9662                    if fil_local != -1 && IS_ERROR_REDIR(fn_.typ) {
9663                        let dup_fd = unsafe { libc::dup(fil_local) };
9664                        dfil = movefd(dup_fd); // c:3931
9665                    } else {
9666                        dfil = 0; // c:3933
9667                    }
9668                    if fil_local == -1 || dfil == -1 {
9669                        // c:3934
9670                        if fil_local != -1 {
9671                            unsafe { libc::close(fil_local) }; // c:3935-3936
9672                        }
9673                        closemnodes(&mut mfds); // c:3937
9674                        fixfds(&save); // c:3938
9675                        let e = std::io::Error::last_os_error();
9676                        let raw = e.raw_os_error().unwrap_or(0);
9677                        if raw != 0 && raw != libc::EINTR {
9678                            zwarn(&format!("{}: {}", e, fn_.name.as_deref().unwrap_or("")));
9679                            // c:3939-3940
9680                        }
9681                        {
9682                            errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed);
9683                            LASTVAL.store(1, Ordering::Relaxed);
9684                        } // c:3941
9685                        break;
9686                    }
9687                    // c:3943
9688                    addfd(
9689                        forked,
9690                        &mut save,
9691                        &mut mfds,
9692                        fn_.fd1,
9693                        fil_local,
9694                        1,
9695                        fn_.varid.as_deref(),
9696                    );
9697                    if IS_ERROR_REDIR(fn_.typ) {
9698                        // c:3944-3945
9699                        addfd(forked, &mut save, &mut mfds, 2, dfil, 1, None);
9700                    }
9701                    let _ = &mut dfil;
9702                }
9703            }
9704            // c:3948-3952 — addfd errflag check.
9705            if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
9706                // c:3949
9707                closemnodes(&mut mfds); // c:3950
9708                fixfds(&save); // c:3951
9709                {
9710                    errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed);
9711                    LASTVAL.store(1, Ordering::Relaxed);
9712                } // c:3952
9713                break;
9714            }
9715        }
9716    }
9717
9718    // c:3957-3961 — close multios with ct >= 2.
9719    i = 0;
9720    while i < 10 {
9721        // c:3959
9722        if let Some(m) = mfds.get(i as usize).and_then(|o| o.as_ref()) {
9723            if m.ct >= 2 {
9724                closemn(&mut mfds, i, REDIR_CLOSE); // c:3960
9725            }
9726        }
9727        i += 1;
9728    }
9729
9730    // c:3963-3995 — nullexec branch.
9731    if nullexec != 0 {
9732        // c:3963
9733        if let Some(vspc) = varspc {
9734            // c:3969
9735            let mut restorelist: Vec<crate::ported::zsh_h::param> = Vec::new();
9736            let mut removelist: Vec<String> = Vec::new();
9737            if !isset(POSIXBUILTINS) && nullexec != 2 {
9738                // c:3971-3972
9739                save_params(state, vspc, &mut restorelist, &mut removelist);
9740            }
9741            addvars(state, vspc, 0); // c:3973
9742            if !restorelist.is_empty() {
9743                // c:3974
9744                restore_params(restorelist, removelist); // c:3975
9745            }
9746        }
9747        let ef = errflag.load(Ordering::Relaxed);
9748        LASTVAL.store(
9749            if ef != 0 {
9750                ef
9751            } else {
9752                cmdoutval.load(Ordering::Relaxed)
9753            },
9754            Ordering::Relaxed,
9755        ); // c:3977
9756        if nullexec == 1 {
9757            // c:3978
9758            // c:3983-3985 — close save[i].
9759            i = 0;
9760            while i < 10 {
9761                if save[i as usize] != -2 {
9762                    let _ = zclose(save[i as usize]); // c:3985
9763                }
9764                i += 1;
9765            }
9766            // c:3988-3989 — `jobtab[thisjob].stat |= STAT_DONE; goto done;`
9767            let thisjob = THISJOB.get().map(|m| *m.lock().unwrap()).unwrap_or(-1);
9768            if thisjob >= 0 {
9769                if let Some(jt) = JOBTAB.get() {
9770                    let mut guard = jt.lock().unwrap();
9771                    if let Some(j) = guard.get_mut(thisjob as usize) {
9772                        j.stat |= STAT_DONE; // c:3989
9773                    }
9774                }
9775            }
9776            return execcmd_exec_done_path(
9777                redir_err,
9778                oautocont,
9779                how,
9780                &mut shti,
9781                &mut chti,
9782                &mut then_ts,
9783                forked,
9784                &mut newxtrerr,
9785                cflags,
9786                orig_cflags,
9787                is_cursh,
9788                do_exec,
9789            );
9790        }
9791        if isset(XTRACE) {
9792            // c:3992-3994
9793            eprintln!();
9794        }
9795    } else if isset(EXECOPT) && (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) == 0 {
9796        // c:3996 — main dispatch branch.
9797        // c:3997 — `int q = queue_signal_level();`
9798        let _q = 0;
9799        // c:4003-4012 — entersubsh for is_exec.
9800        if is_exec != 0 {
9801            // c:4003
9802            let mut flags: i32 = if (how & Z_ASYNC as i32) != 0 {
9803                esub::ASYNC
9804            } else {
9805                0
9806            } | esub::PGRP
9807                | esub::FAKE; // c:4004-4005
9808            if typ != WC_SUBSH as i32 {
9809                flags |= esub::KEEPTRAP; // c:4007
9810            }
9811            if (do_exec != 0 || (typ >= WC_CURSH as i32 && last1 == 1)) && forked == 0 {
9812                // c:4008-4009
9813                flags |= esub::REVERTPGRP; // c:4010
9814            }
9815            entersubsh(flags, None); // c:4011
9816        }
9817
9818        if typ == WC_FUNCDEF as i32 {
9819            // c:4013
9820            // c:4014-4036 — `redir_prog` setup from wordcode if no
9821            // redirs+WC_REDIR follows. Wire only when fusevm WC_REDIR
9822            // peek is in scope; for the tree-walker entry point we
9823            // approximate by passing None.
9824            let redir_prog: Option<crate::ported::zsh_h::Eprog> = None;
9825            // c:4039 — `lastval = execfuncdef(state, redir_prog);`
9826            let lv = execfuncdef(state, redir_prog);
9827            LASTVAL.store(lv, Ordering::Relaxed);
9828        } else if typ >= WC_CURSH as i32 {
9829            // c:4042
9830            if last1 == 1 {
9831                do_exec = 1; // c:4044
9832            }
9833            if typ == WC_AUTOFN as i32 {
9834                // c:4046
9835                let lv = execautofn_basic(state, do_exec); // c:4051
9836                LASTVAL.store(lv, Ordering::Relaxed);
9837            } else {
9838                // c:4053 — `lastval = (execfuncs[type - WC_CURSH])(state, do_exec);`
9839                // dispatch_execfuncs ports the C `execfuncs[]` table
9840                // (Src/exec.c:170-180) by typ → exec{cursh,for,select,...}
9841                // direct call. See dispatch_execfuncs at end of file.
9842                let lv = dispatch_execfuncs(state, typ, do_exec);
9843                LASTVAL.store(lv, Ordering::Relaxed);
9844            }
9845        } else if is_builtin != 0 || is_shfunc != 0 {
9846            // c:4055
9847            let mut restorelist: Vec<crate::ported::zsh_h::param> = Vec::new();
9848            let mut removelist: Vec<String> = Vec::new();
9849            let mut do_save: i32 = 0; // c:4057
9850
9851            if forked == 0 {
9852                // c:4060
9853                if isset(POSIXBUILTINS) {
9854                    // c:4061
9855                    if is_shfunc != 0
9856                        || (hn.map(|p| unsafe { (*p).node.flags as u32 }).unwrap_or(0)
9857                            & (BINF_PSPECIAL | BINF_ASSIGN_FLAG))
9858                            != 0
9859                    {
9860                        // c:4067
9861                        do_save = if (orig_cflags & BINF_COMMAND) != 0 {
9862                            1
9863                        } else {
9864                            0
9865                        };
9866                    } else {
9867                        do_save = 1; // c:4070
9868                    }
9869                } else {
9870                    // c:4071
9871                    if (cflags & (BINF_COMMAND | BINF_ASSIGN_FLAG)) != 0 || magic_assign == 0 {
9872                        // c:4076
9873                        do_save = 1; // c:4077
9874                    }
9875                }
9876                if do_save != 0 {
9877                    if let Some(vspc) = varspc {
9878                        // c:4079
9879                        save_params(state, vspc, &mut restorelist, &mut removelist);
9880                    }
9881                }
9882            }
9883            if varspc.is_some() {
9884                // c:4082
9885                let mut addflags: i32 = 0; // c:4086
9886                if is_shfunc != 0 {
9887                    addflags |= ADDVAR_EXPORT; // c:4088
9888                }
9889                if !restorelist.is_empty() {
9890                    addflags |= ADDVAR_RESTORE; // c:4090
9891                }
9892                addvars(state, varspc.unwrap_or(0), addflags); // c:4092
9893                if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
9894                    // c:4093
9895                    if !restorelist.is_empty() {
9896                        restore_params(restorelist, removelist); // c:4094-4095
9897                    }
9898                    LASTVAL.store(1, Ordering::Relaxed); // c:4096
9899                    fixfds(&save); // c:4097
9900                    return execcmd_exec_done_path(
9901                        redir_err,
9902                        oautocont,
9903                        how,
9904                        &mut shti,
9905                        &mut chti,
9906                        &mut then_ts,
9907                        forked,
9908                        &mut newxtrerr,
9909                        cflags,
9910                        orig_cflags,
9911                        is_cursh,
9912                        do_exec,
9913                    );
9914                }
9915            }
9916
9917            if is_shfunc != 0 {
9918                // c:4102-4105
9919                let mut a_vec: Vec<String> = args.clone().unwrap_or_default();
9920                // c:4104 — `execshfunc((Shfunc) hn, args);` C casts
9921                // HashNode hn to Shfunc; zshrs's hn is *mut builtin so
9922                // we re-resolve the shfunc by name from shfunctab and
9923                // dispatch through the top-level execshfunc port at
9924                // exec.rs:4978 (which routes to runshfunc).
9925                let name = args
9926                    .as_ref()
9927                    .and_then(|v| v.first())
9928                    .cloned()
9929                    .unwrap_or_default();
9930                let mut shf_clone: Option<shfunc> = if let Ok(tab) = shfunctab_lock().read() {
9931                    tab.get(&name).cloned()
9932                } else {
9933                    None
9934                };
9935                if let Some(ref mut shf) = shf_clone {
9936                    execshfunc(shf, &mut a_vec);
9937                }
9938                // c:4105 — `pipecleanfilelist(filelist, 0);` — clean
9939                // out the proc_subst entries from the current job's
9940                // filelist after the shfunc body ran. Route through
9941                // `JOBTAB[thisjob]`.
9942                if let Some(jt) = JOBTAB.get() {
9943                    let mut guard = jt.lock().unwrap();
9944                    let tj = THISJOB.get().map(|m| *m.lock().unwrap()).unwrap_or(-1);
9945                    if tj >= 0 {
9946                        if let Some(j) = guard.get_mut(tj as usize) {
9947                            crate::ported::jobs::pipecleanfilelist(j, false);
9948                        }
9949                    }
9950                }
9951            } else {
9952                // c:4107 — builtin path.
9953                let mut assigns: Vec<crate::ported::zsh_h::asgment> = Vec::new(); // c:4108
9954                let postassigns = eparams.postassigns; // c:4109
9955                if forked != 0 {
9956                    closem(FDT_INTERNAL, 0); // c:4111
9957                }
9958                if postassigns != 0 {
9959                    // c:4112-4230 — typeset post-assignment processing.
9960                    use crate::ported::zsh_h::{
9961                        ASG_ARRAY, ASG_KEY_VALUE, EC_DUPTOK as ECDUPTOK_LOCAL, PREFORK_ASSIGN,
9962                        PREFORK_KEY_VALUE, PREFORK_SINGLE, PREFORK_TYPESET, WC_ASSIGN_INC,
9963                        WC_ASSIGN_NUM, WC_ASSIGN_SCALAR, WC_ASSIGN_TYPE, WC_ASSIGN_TYPE2,
9964                    };
9965                    let opc = state.pc; // c:4113
9966                    state.pc = eparams.assignspc.unwrap_or(state.pc); // c:4114
9967                                                                      // c:4115 — `assigns = newlinklist();` — already declared above.
9968                    let mut pa_remaining = postassigns;
9969                    while pa_remaining > 0 {
9970                        // c:4116 — `while (postassigns--)`
9971                        pa_remaining -= 1;
9972                        let mut pa_htok: i32 = 0; // c:4117
9973                        if state.pc >= state.prog.prog.len() {
9974                            break;
9975                        }
9976                        let ac = state.prog.prog[state.pc]; // c:4118
9977                        state.pc += 1;
9978                        let mut name = ecgetstr(state, ECDUPTOK_LOCAL, Some(&mut pa_htok)); // c:4119
9979                                                                                            // c:4123-4124 DPUTS — debug assertion skipped.
9980                        if pa_htok != 0 {
9981                            // c:4126 — `init_list1(svl, name);`
9982                            let mut svl: LinkList<String> = Default::default();
9983                            svl.push_back(name.clone());
9984                            // c:4127-4166 — INC-scalar special case (typeset $ass form).
9985                            if WC_ASSIGN_TYPE(ac) == WC_ASSIGN_SCALAR
9986                                && WC_ASSIGN_TYPE2(ac) == WC_ASSIGN_INC
9987                            {
9988                                // c:4141 — `(void)ecgetstr(...)` — dummy.
9989                                let mut dummy_htok: i32 = 0;
9990                                let _ = ecgetstr(state, ECDUPTOK_LOCAL, Some(&mut dummy_htok));
9991                                let mut rf = 0i32;
9992                                prefork(&mut svl, PREFORK_TYPESET, &mut rf); // c:4142
9993                                if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
9994                                    // c:4143
9995                                    state.pc = opc; // c:4144
9996                                    break;
9997                                }
9998                                let mut rf2 = 0i32;
9999                                globlist(&mut svl, rf2); // c:4147
10000                                let _ = &mut rf2;
10001                                if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
10002                                    // c:4148
10003                                    state.pc = opc; // c:4149
10004                                    break;
10005                                }
10006                                // c:4152-4165 — drain svl into assigns.
10007                                while let Some(data) = svl.pop_front() {
10008                                    let (asg_name, asg_val): (String, Option<String>) =
10009                                        if let Some(eq_pos) = data.find('=') {
10010                                            // c:4156-4159
10011                                            (
10012                                                data[..eq_pos].to_string(),
10013                                                Some(data[eq_pos + 1..].to_string()),
10014                                            )
10015                                        } else {
10016                                            // c:4161-4162
10017                                            (data, None)
10018                                        };
10019                                    assigns.push(crate::ported::zsh_h::asgment {
10020                                        node: crate::ported::zsh_h::linknode {
10021                                            next: None,
10022                                            prev: None,
10023                                            dat: 0,
10024                                        },
10025                                        name: asg_name,
10026                                        flags: 0,
10027                                        scalar: asg_val,
10028                                        array: None,
10029                                    });
10030                                }
10031                                continue; // c:4166
10032                            }
10033                            // c:4168 — `prefork(&svl, PREFORK_SINGLE, NULL);`
10034                            let mut rf = 0i32;
10035                            prefork(&mut svl, PREFORK_SINGLE, &mut rf);
10036                            // c:4169-4170 — `name = empty(svl) ? "" : firstnode_data;`
10037                            name = if svl.is_empty() {
10038                                String::new()
10039                            } else {
10040                                svl.pop_front().unwrap_or_default()
10041                            };
10042                        }
10043                        // c:4172 — `untokenize(name);`
10044                        // (untokenize is destructive on bytes; Rust untokenize
10045                        // returns a new String — call and rebind.)
10046                        name = untokenize(&name);
10047                        let mut asg = crate::ported::zsh_h::asgment {
10048                            node: crate::ported::zsh_h::linknode {
10049                                next: None,
10050                                prev: None,
10051                                dat: 0,
10052                            },
10053                            name,
10054                            flags: 0,
10055                            scalar: None,
10056                            array: None,
10057                        };
10058                        if WC_ASSIGN_TYPE(ac) == WC_ASSIGN_SCALAR {
10059                            // c:4175
10060                            let mut val_htok: i32 = 0;
10061                            let mut val = ecgetstr(state, ECDUPTOK_LOCAL, Some(&mut val_htok)); // c:4176
10062                            asg.flags = 0; // c:4177
10063                            if WC_ASSIGN_TYPE2(ac) == WC_ASSIGN_INC {
10064                                // c:4178-4180 — fake assignment, no value.
10065                                asg.scalar = None;
10066                            } else {
10067                                if val_htok != 0 {
10068                                    // c:4183
10069                                    let mut svl: LinkList<String> = Default::default();
10070                                    svl.push_back(val.clone());
10071                                    let mut rf = 0i32;
10072                                    prefork(&mut svl, PREFORK_SINGLE | PREFORK_ASSIGN, &mut rf); // c:4184-4186
10073                                    if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
10074                                        // c:4187
10075                                        state.pc = opc; // c:4188
10076                                        break;
10077                                    }
10078                                    // c:4195-4196 — `val = empty(svl) ? "" : firstdata;`
10079                                    val = if svl.is_empty() {
10080                                        String::new()
10081                                    } else {
10082                                        svl.pop_front().unwrap_or_default()
10083                                    };
10084                                }
10085                                // c:4198 — `untokenize(val);`
10086                                asg.scalar = Some(untokenize(&val));
10087                            }
10088                        } else {
10089                            // c:4202 — array assignment.
10090                            asg.flags = ASG_ARRAY; // c:4202
10091                            let mut arr_htok: i32 = 0;
10092                            let arr_words = ecgetlist(
10093                                state,
10094                                WC_ASSIGN_NUM(ac) as usize,
10095                                ECDUPTOK_LOCAL,
10096                                Some(&mut arr_htok),
10097                            ); // c:4204
10098                            let mut arr_list: LinkList<String> = Default::default();
10099                            for s in arr_words {
10100                                arr_list.push_back(s);
10101                            }
10102                            if !arr_list.is_empty()
10103                                && (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) == 0
10104                            {
10105                                // c:4209 — `int prefork_ret = 0;`
10106                                let mut prefork_ret = 0i32;
10107                                prefork(&mut arr_list, PREFORK_ASSIGN, &mut prefork_ret); // c:4210-4211
10108                                if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
10109                                    // c:4212
10110                                    state.pc = opc; // c:4213
10111                                    break;
10112                                }
10113                                if (prefork_ret & PREFORK_KEY_VALUE) != 0 {
10114                                    // c:4216
10115                                    asg.flags |= ASG_KEY_VALUE; // c:4217
10116                                }
10117                                globlist(&mut arr_list, prefork_ret); // c:4218
10118                                if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
10119                                    // c:4220
10120                                    state.pc = opc; // c:4221
10121                                    break;
10122                                }
10123                            }
10124                            asg.array = Some(arr_list);
10125                        }
10126                        // c:4227 — `uaddlinknode(assigns, &asg->node);`
10127                        assigns.push(asg);
10128                    }
10129                    state.pc = opc; // c:4229
10130                }
10131                if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) == 0 {
10132                    // c:4232
10133                    let a_vec: Vec<String> = args.clone().unwrap_or_default();
10134                    let ret = crate::ported::builtin::execbuiltin(
10135                        a_vec,
10136                        assigns,
10137                        hn.unwrap_or(std::ptr::null_mut()),
10138                    ); // c:4233
10139                    if (errflag.load(Ordering::Relaxed) & ERRFLAG_INT) == 0 {
10140                        // c:4238
10141                        LASTVAL.store(ret, Ordering::Relaxed); // c:4239
10142                    }
10143                }
10144                if (do_save & BINF_COMMAND as i32) != 0 {
10145                    // c:4241
10146                    errflag.fetch_and(!ERRFLAG_ERROR, Ordering::Relaxed); // c:4242
10147                }
10148                // c:4244 fflush(stdout) — Rust stdio auto-flushes.
10149                // c:4245-4251 — write-error check on save[1].
10150            }
10151            if isset(PRINTEXITVALUE)
10152                && isset(SHINSTDIN)
10153                && LASTVAL.load(Ordering::Relaxed) != 0
10154                && subsh.load(Ordering::Relaxed) == 0
10155            {
10156                // c:4253-4255
10157                eprintln!("zsh: exit {}", LASTVAL.load(Ordering::Relaxed)); // c:4258
10158            }
10159
10160            if do_exec != 0 {
10161                // c:4263
10162                if subsh.load(Ordering::Relaxed) != 0 {
10163                    crate::ported::builtin::_realexit(); // c:4264-4265
10164                }
10165                if isset(RCS)
10166                    && crate::ported::zsh_h::interact()
10167                    && nohistsave.load(Ordering::Relaxed) == 0
10168                {
10169                    // c:4269
10170                    crate::ported::hist::savehistfile(None, HFILE_USE_OPTIONS as i32);
10171                    // c:4270
10172                }
10173                crate::ported::builtin::realexit(); // c:4271
10174            }
10175            if !restorelist.is_empty() {
10176                // c:4273
10177                restore_params(restorelist, removelist); // c:4274
10178            }
10179        } else {
10180            // c:4276 — external command execute.
10181            if subsh.load(Ordering::Relaxed) == 0 {
10182                // c:4277
10183                if forked == 0 {
10184                    // c:4280 — `setiparam("SHLVL", --shlvl);`
10185                    let cur = getsparam("SHLVL")
10186                        .and_then(|s| s.parse::<i64>().ok())
10187                        .unwrap_or(1);
10188                    setiparam("SHLVL", cur - 1); // c:4281
10189                }
10190                if do_exec != 0
10191                    && isset(RCS)
10192                    && crate::ported::zsh_h::interact()
10193                    && nohistsave.load(Ordering::Relaxed) == 0
10194                {
10195                    // c:4285
10196                    crate::ported::hist::savehistfile(None, HFILE_USE_OPTIONS as i32);
10197                    // c:4286
10198                }
10199            }
10200            if typ == WC_SIMPLE as i32 || typ == WC_TYPESET as i32 {
10201                // c:4288
10202                if varspc.is_some() {
10203                    // c:4289
10204                    let mut addflags: i32 = ADDVAR_EXPORT; // c:4290
10205                    if forked != 0 {
10206                        addflags |= ADDVAR_RESTORE; // c:4292
10207                    }
10208                    addvars(state, varspc.unwrap_or(0), addflags); // c:4293
10209                    if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
10210                        // c:4294
10211                        std::process::exit(1); // c:4295
10212                    }
10213                }
10214                closem(FDT_INTERNAL, 0); // c:4297
10215                                         // c:4298-4305 — close coprocin/coprocout.
10216                let cpi = crate::ported::modules::clone::coprocin.load(Ordering::Relaxed);
10217                if cpi != -1 {
10218                    let _ = zclose(cpi); // c:4299
10219                    crate::ported::modules::clone::coprocin.store(-1, Ordering::Relaxed);
10220                    // c:4300
10221                }
10222                let cpo = crate::ported::modules::clone::coprocout.load(Ordering::Relaxed);
10223                if cpo != -1 {
10224                    let _ = zclose(cpo); // c:4303
10225                    crate::ported::modules::clone::coprocout.store(-1, Ordering::Relaxed);
10226                    // c:4304
10227                }
10228                if forked == 0 {
10229                    // c:4307
10230                    setlimits(""); // c:4308
10231                }
10232                if (how & Z_ASYNC as i32) != 0 {
10233                    // c:4310 — `zsfree(STTYval); STTYval = 0;`
10234                    let mut guard = STTYval.lock().unwrap();
10235                    *guard = None; // c:4311-4312
10236                }
10237                // c:4314 — `execute(args, cflags, use_defpath);`
10238                let mut a_vec: Vec<String> = args.clone().unwrap_or_default();
10239                execute(&mut a_vec, cflags, use_defpath); // c:4314
10240            } else {
10241                // c:4315 — `( ... )` — WC_SUBSH.
10242                list_pipe.store(0, Ordering::Relaxed); // c:4318
10243                                                       // c:4319 — `pipecleanfilelist(filelist, 0);` — clean
10244                                                       // proc-subst entries from the current job's filelist
10245                                                       // before recursing into the subshell body.
10246                if let Some(jt) = JOBTAB.get() {
10247                    let mut guard = jt.lock().unwrap();
10248                    let tj = THISJOB.get().map(|m| *m.lock().unwrap()).unwrap_or(-1);
10249                    if tj >= 0 {
10250                        if let Some(j) = guard.get_mut(tj as usize) {
10251                            crate::ported::jobs::pipecleanfilelist(j, false);
10252                        }
10253                    }
10254                }
10255                state.pc += 1; // c:4324 — `state->pc++;`
10256                let _ = execlist(state, 0, 1); // c:4325
10257            }
10258        }
10259    }
10260
10261    // c:4330-4404 — err: + done: + fatal:.
10262    return execcmd_exec_done_path(
10263        redir_err,
10264        oautocont,
10265        how,
10266        &mut shti,
10267        &mut chti,
10268        &mut then_ts,
10269        forked,
10270        &mut newxtrerr,
10271        cflags,
10272        orig_cflags,
10273        is_cursh,
10274        do_exec,
10275    );
10276}
10277
10278/// Internal helper modelling the C `done:` label tail of
10279/// `execcmd_exec` at `Src/exec.c:4366-4403`. Handles POSIX special-
10280/// builtin error escalation, AUTOCONTINUE restore, STTYval clear,
10281/// shelltime stop, and newxtrerr close.
10282#[allow(clippy::too_many_arguments)]
10283fn execcmd_exec_done_path(
10284    redir_err: i32,
10285    oautocont: i32,
10286    how: i32,
10287    shti: &mut crate::ported::jobs::timeinfo,
10288    chti: &mut crate::ported::jobs::timeinfo,
10289    then_ts: &mut std::time::Instant,
10290    forked: i32,
10291    newxtrerr: &mut Option<i32>,
10292    cflags: u32,
10293    orig_cflags: u32,
10294    is_cursh: i32,
10295    do_exec: i32,
10296) {
10297    use crate::ported::zsh_h::{
10298        AUTOCONTINUE, BINF_COMMAND, BINF_EXEC, BINF_PSPECIAL, INTERACTIVE, POSIXBUILTINS, Z_TIMED,
10299    };
10300    // c:4366
10301    // c:4367-4386 — POSIX special-builtin error escalation.
10302    if isset(POSIXBUILTINS)
10303        && (cflags & (BINF_PSPECIAL | BINF_EXEC)) != 0
10304        && (orig_cflags & BINF_COMMAND) == 0
10305    {
10306        // c:4367-4369
10307        let _forked_or_subsh = forked | zsh_subshell.load(Ordering::Relaxed); // c:4376
10308                                                                              // fatal: label entry point — same handling.
10309        if redir_err != 0 || (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
10310            // c:4378
10311            if !isset(INTERACTIVE) {
10312                // c:4379
10313                if _forked_or_subsh != 0 {
10314                    unsafe { libc::_exit(1) }; // c:4381
10315                } else {
10316                    std::process::exit(1); // c:4383
10317                }
10318            }
10319            errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed); // c:4385
10320        }
10321    }
10322    // c:4388-4389 — `if ((is_cursh || do_exec) && (how & Z_TIMED)) shelltime(...);`
10323    if (is_cursh != 0 || do_exec != 0) && (how & Z_TIMED as i32) != 0 {
10324        crate::ported::jobs::shelltime(Some(shti), Some(chti), Some(then_ts), 1);
10325        // c:4389
10326    }
10327    // c:4390-4398 — newxtrerr close.
10328    if let Some(fd) = newxtrerr.take() {
10329        // c:4390
10330        let _ = zclose(fd); // c:4396
10331    }
10332    // c:4400-4401 — `zsfree(STTYval); STTYval = 0;`
10333    {
10334        let mut guard = STTYval.lock().unwrap();
10335        *guard = None;
10336    }
10337    // c:4402-4403 — `if (oautocont >= 0) opts[AUTOCONTINUE] = oautocont;`
10338    if oautocont >= 0 {
10339        opt_state_set("autocontinue", oautocont != 0);
10340    }
10341}
10342
10343/// Internal helper modelling the C `err:` label tail of
10344/// `execcmd_exec` at `Src/exec.c:4330-4365`. Forked-child fd cleanup
10345/// + waitjobs + _realexit; non-forked: `fixfds(save)` + fall through
10346/// to done:.
10347#[allow(clippy::too_many_arguments)]
10348fn execcmd_exec_err_path(
10349    forked: i32,
10350    save: &mut [i32; 10],
10351    mfds: &mut [Option<Box<multio>>; 10],
10352    oautocont: i32,
10353    how: i32,
10354    shti: &mut crate::ported::jobs::timeinfo,
10355    chti: &mut crate::ported::jobs::timeinfo,
10356    then_ts: &mut std::time::Instant,
10357    newxtrerr: &mut Option<i32>,
10358    cflags: u32,
10359    orig_cflags: u32,
10360    is_cursh: i32,
10361    do_exec: i32,
10362    redir_err: i32,
10363) {
10364    use crate::ported::zsh_h::FDT_UNUSED;
10365    // c:4330
10366    if forked != 0 {
10367        // c:4331
10368        // c:4356-4358 — close all fds 0..10 whose fdtable entry != FDT_UNUSED.
10369        let mut i: i32 = 0;
10370        while i < 10 {
10371            if fdtable_get(i) != FDT_UNUSED {
10372                unsafe { libc::close(i) }; // c:4358
10373            }
10374            i += 1;
10375        }
10376        // c:4359 — `closem(FDT_UNUSED, 1);`
10377        closem(FDT_UNUSED, 1); // c:4359
10378                               // c:4360-4361 — `if (thisjob != -1) waitjobs();`
10379        let thisjob = THISJOB.get().map(|m| *m.lock().unwrap()).unwrap_or(-1);
10380        if thisjob != -1 {
10381            if let Some(jt) = JOBTAB.get() {
10382                let mut guard = jt.lock().unwrap();
10383                crate::ported::jobs::waitjobs(&mut guard, thisjob as usize); // c:4361
10384            }
10385        }
10386        crate::ported::builtin::_realexit(); // c:4362
10387    }
10388    fixfds(save); // c:4364
10389
10390    execcmd_exec_done_path(
10391        redir_err,
10392        oautocont,
10393        how,
10394        shti,
10395        chti,
10396        then_ts,
10397        forked,
10398        newxtrerr,
10399        cflags,
10400        orig_cflags,
10401        is_cursh,
10402        do_exec,
10403    );
10404}
10405
10406/// Internal helper dispatching `execfuncs[type - WC_CURSH]` from
10407/// `Src/exec.c:170-180`. Each branch maps to the ported wordcode-
10408/// walker function in `src/ported/exec.rs`.
10409fn dispatch_execfuncs(state: &mut estate, typ: i32, do_exec: i32) -> i32 {
10410    use crate::ported::zsh_h::{
10411        WC_ARITH, WC_AUTOFN, WC_CASE, WC_COND, WC_CURSH, WC_FOR, WC_FUNCDEF, WC_IF, WC_REPEAT,
10412        WC_SELECT, WC_SUBSH, WC_TIMED, WC_TRY, WC_WHILE,
10413    };
10414    // Port of `static int (*const execfuncs[])(Estate, int)` dispatch
10415    // table at `Src/exec.c:170-180`. C indexes by `(type - WC_CURSH)`;
10416    // Rust matches on the WC_* tag directly.
10417    match typ as wordcode {
10418        x if x == WC_CURSH => execcursh(state, do_exec),
10419        x if x == WC_FOR => execfor(state, do_exec),
10420        x if x == WC_SELECT => execselect(state, do_exec),
10421        x if x == WC_WHILE => execwhile(state, do_exec),
10422        x if x == WC_REPEAT => execrepeat(state, do_exec),
10423        x if x == WC_CASE => execcase(state, do_exec),
10424        x if x == WC_IF => execif(state, do_exec),
10425        x if x == WC_COND => execcond(state, do_exec),
10426        x if x == WC_ARITH => execarith(state, do_exec),
10427        x if x == WC_TRY => exectry(state, do_exec),
10428        x if x == WC_FUNCDEF => execfuncdef(state, None),
10429        // c:272 — execfuncs[] table dispatches `WC_AUTOFN` to
10430        // `execautofn` (the loadautofn-then-basic wrapper), not
10431        // `execautofn_basic` directly.
10432        x if x == WC_AUTOFN => execautofn(state, do_exec),
10433        x if x == WC_TIMED => exectime(state, do_exec),
10434        x if x == WC_SUBSH => execcursh(state, do_exec), // c:269 — same handler.
10435        _ => 0,
10436    }
10437}
10438
10439/// Port of `Eprog stripkshdef(Eprog prog, char *name)` from
10440/// `Src/exec.c:6286-6364`. Given an Eprog read from an autoload
10441/// file plus the function name being defined, check whether the
10442/// file consists of *exactly* one `function NAME { … }` definition
10443/// for that name. If so, return a new Eprog whose `prog`/`strs`/
10444/// `pats` slice out just the function body (so calling code can
10445/// invoke the body directly instead of re-parsing). Otherwise
10446/// return the input untouched.
10447///
10448/// Header word layout consumed (matches C `pc[…]` reads):
10449///   pc[0] = WC_LIST with `Z_SYNC|Z_END|Z_SIMPLE` flags
10450///   pc[1] = (sublist header, skipped)
10451///   pc[2] = WC_FUNCDEF
10452///   pc[3] = 1                       (single-name funcdef)
10453///   pc[4] = name-string slot        (compared to `name`)
10454///   pc[5] = sbeg  (offset into strs table)
10455///   pc[6] = nstrs (bytes of strs to copy)
10456///   pc[7] = npats (number of pattern slots to allocate)
10457///   pc[8] = WC_FUNCDEF_SKIP target  (end-of-funcdef pc)
10458///   pc[9] = (unused header word — `pc += 6` lands here as the
10459///           start of the body wordcode stream)
10460///
10461/// Returns `None` only when the input was `None` (matches C
10462/// `return NULL`). Equivalence between the original `prog` and a
10463/// successfully stripped `prog` is *not* preserved at the pointer
10464/// level (C may return the original Eprog when the file fails the
10465/// single-funcdef shape check; this Rust port does the same by
10466/// passing the box back through).
10467///
10468/// `EF_MAP` (`zcompile`d / mmap'd Eprog) path: C mutates the
10469/// existing Eprog in place, swapping its `prog` / `strs` /
10470/// `pats` to slice into the funcdef body. Rust mirrors this on
10471/// the moved-in `Box<eprog>` (no separate `free()` needed —
10472/// `Vec` drop handles the old `pats`).
10473pub fn stripkshdef(
10474    prog: Option<crate::ported::zsh_h::Eprog>,
10475    name: &str,
10476) -> Option<crate::ported::zsh_h::Eprog> {
10477    use crate::ported::parse::ecrawstr;
10478    use crate::ported::zsh_h::{
10479        wc_code, wordcode, Dash, EF_HEAP, EF_MAP, WC_FUNCDEF, WC_FUNCDEF_SKIP, WC_LIST,
10480        WC_LIST_TYPE, Z_END, Z_SIMPLE, Z_SYNC,
10481    };
10482
10483    // c:6300 — `if (!prog) return NULL;`
10484    let mut prog = prog?;
10485
10486    // c:6302-6306 — first word must be WC_LIST with all of
10487    // Z_SYNC|Z_END|Z_SIMPLE set (i.e. the trivial "single simple
10488    // sublist" wrapper around the funcdef).
10489    if prog.prog.len() < 3 {
10490        return Some(prog);
10491    }
10492    let code0: wordcode = prog.prog[0];
10493    if wc_code(code0) != WC_LIST
10494        || (WC_LIST_TYPE(code0) & (Z_SYNC | Z_END | Z_SIMPLE) as wordcode)
10495            != (Z_SYNC | Z_END | Z_SIMPLE) as wordcode
10496    {
10497        return Some(prog);
10498    }
10499    // c:6307 — `pc++;` (skip the sublist header word at pc[1]).
10500    // c:6308 — `code = *pc++;` lands `code` on pc[2], leaving the
10501    // walking cursor at pc[3] which is read directly below.
10502    let code: wordcode = prog.prog[2];
10503    let pc_after_code: usize = 3;
10504    if wc_code(code) != WC_FUNCDEF || prog.prog[pc_after_code] != 1 {
10505        return Some(prog);
10506    }
10507
10508    // c:6320 — `ptr2 = ecrawstr(prog, pc + 1, NULL);` (note: C's
10509    // `pc` is already past `code`, so `pc + 1` lands on pc[4] —
10510    // the name-string slot).
10511    let name_slot = pc_after_code + 1; // == 4
10512    let name_in_def = ecrawstr(&prog, name_slot, None);
10513
10514    // c:6320-6328 — name match, tolerating Dash-tokenised hyphens
10515    // on either side.
10516    let n1 = name.as_bytes();
10517    let n2 = name_in_def.as_bytes();
10518    let mut i = 0usize;
10519    let mut j = 0usize;
10520    while i < n1.len() && j < n2.len() {
10521        let c1 = n1[i] as char;
10522        let c2 = n2[j] as char;
10523        if c1 != c2 && c1 != Dash && c1 != '-' && c2 != Dash && c2 != '-' {
10524            break;
10525        }
10526        i += 1;
10527        j += 1;
10528    }
10529    // c:6329 — `if (*ptr1 || *ptr2) return prog;` (any unmatched
10530    // tail on either side → not the right funcdef).
10531    if i < n1.len() || j < n2.len() {
10532        return Some(prog);
10533    }
10534
10535    // c:6332-6362 — slice the funcdef body out. Layout:
10536    //   sbeg  = pc[2] (in C, == prog.prog[pc_after_code + 2] == [5])
10537    //   nstrs = pc[3] (== [6])
10538    //   npats = pc[4] (== [7])
10539    //   end   = pc + WC_FUNCDEF_SKIP(code)   (== pc_after_code + skip)
10540    //   pc   += 6  (body wordcode begins at pc_after_code + 6 == [9])
10541    let sbeg = prog.prog[pc_after_code + 2] as usize;
10542    let nstrs = prog.prog[pc_after_code + 3] as usize;
10543    let npats = prog.prog[pc_after_code + 4] as i32;
10544    let skip = WC_FUNCDEF_SKIP(code) as usize;
10545    let end_pc = pc_after_code + skip;
10546    let body_start = pc_after_code + 6;
10547    if end_pc < body_start || end_pc > prog.prog.len() {
10548        // Defensive: malformed header — return input untouched so
10549        // the caller's parse-eprog fallback re-reads from source.
10550        return Some(prog);
10551    }
10552    let nprg = end_pc - body_start;
10553    let plen = nprg * size_of::<wordcode>();
10554    let len = plen + (npats as usize) * size_of::<usize>() + nstrs;
10555
10556    // Build the new pats slice — `dummy_patprog1` slots in C; the
10557    // Rust convention (mirrors `dupeprog` at parse.rs:2716) is to
10558    // synthesize zero-initialised patprog placeholders that
10559    // pattern compile-on-first-use will overwrite.
10560    let dummy_pat = || {
10561        Box::new(crate::ported::zsh_h::patprog {
10562            startoff: 0,
10563            size: 0,
10564            mustoff: 0,
10565            patmlen: 0,
10566            globflags: 0,
10567            globend: 0,
10568            flags: 0,
10569            patnpar: 0,
10570            patstartch: 0,
10571        })
10572    };
10573    let new_pats: Vec<crate::ported::zsh_h::Patprog> =
10574        (0..npats.max(0)).map(|_| dummy_pat()).collect();
10575
10576    // c:6353 — `ret->strs = prog->strs + sbeg;` (EF_MAP) or
10577    // c:6359 — `memcpy(ret->strs, prog->strs + sbeg, nstrs);` (heap).
10578    let old_strs = prog.strs.take().unwrap_or_default();
10579    let old_bytes = old_strs.as_bytes();
10580    let new_strs = if sbeg + nstrs <= old_bytes.len() {
10581        Some(String::from_utf8_lossy(&old_bytes[sbeg..sbeg + nstrs]).into_owned())
10582    } else {
10583        Some(String::new())
10584    };
10585
10586    let new_prog: Vec<wordcode> = prog.prog[body_start..end_pc].to_vec();
10587
10588    if (prog.flags & EF_MAP) != 0 {
10589        // c:6349-6354 — in-place EF_MAP path.
10590        prog.pats = new_pats;
10591        prog.prog = new_prog;
10592        prog.strs = new_strs;
10593        prog.len = len as i32;
10594        prog.npats = npats;
10595        prog.shf = None;
10596        return Some(prog);
10597    }
10598
10599    // c:6356-6361 — heap-allocated new Eprog.
10600    let ret = Box::new(eprog {
10601        flags: EF_HEAP,
10602        len: len as i32,
10603        npats,
10604        nref: -1, // c:6363 (heap path → never refcount-freed).
10605        pats: new_pats,
10606        prog: new_prog,
10607        strs: new_strs,
10608        shf: None, // c:6363
10609        dump: None,
10610    });
10611    Some(ret)
10612}
10613
10614#[cfg(test)]
10615mod tests {
10616    use super::*;
10617
10618    // ─── zsh-corpus pins for pure exec helpers ─────────────────────
10619
10620    /// `Src/exec.c:996-1010` — `isrelative` returns 1 for empty.
10621    #[test]
10622    fn exec_corpus_isrelative_empty_is_one() {
10623        let _g = crate::test_util::global_state_lock();
10624        assert_eq!(isrelative(""), 1, "empty path is relative");
10625    }
10626
10627    /// `isrelative("foo")` = 1 (no leading slash).
10628    #[test]
10629    fn exec_corpus_isrelative_bare_name_is_one() {
10630        let _g = crate::test_util::global_state_lock();
10631        assert_eq!(isrelative("foo"), 1);
10632        assert_eq!(isrelative("bin/cmd"), 1);
10633    }
10634
10635    /// `isrelative("/foo")` = 0 (absolute, no `./` / `../`).
10636    #[test]
10637    fn exec_corpus_isrelative_absolute_clean_is_zero() {
10638        let _g = crate::test_util::global_state_lock();
10639        assert_eq!(isrelative("/foo"), 0, "/foo is absolute");
10640        assert_eq!(isrelative("/bin/ls"), 0);
10641        assert_eq!(isrelative("/"), 0, "root is absolute");
10642    }
10643
10644    /// `isrelative("/foo/../bar")` = 1 (contains `../` component).
10645    #[test]
10646    fn exec_corpus_isrelative_absolute_with_dotdot_is_one() {
10647        let _g = crate::test_util::global_state_lock();
10648        assert_eq!(
10649            isrelative("/foo/../bar"),
10650            1,
10651            "absolute path with ../ is still 'relative' per zsh"
10652        );
10653    }
10654
10655    /// `isrelative("/foo/./bar")` = 1 (contains `./` component).
10656    #[test]
10657    fn exec_corpus_isrelative_absolute_with_dot_is_one() {
10658        let _g = crate::test_util::global_state_lock();
10659        assert_eq!(
10660            isrelative("/./x"),
10661            1,
10662            "absolute with ./ component reported relative"
10663        );
10664    }
10665
10666    /// `Src/exec.c:5300` — `is_anonymous_function_name("(anon)")` = 1.
10667    #[test]
10668    fn exec_corpus_is_anonymous_function_name_matches_sentinel() {
10669        assert_eq!(is_anonymous_function_name("(anon)"), 1);
10670    }
10671
10672    /// `is_anonymous_function_name("regular_name")` = 0.
10673    #[test]
10674    fn exec_corpus_is_anonymous_function_name_rejects_normal() {
10675        assert_eq!(is_anonymous_function_name("regular_name"), 0);
10676        assert_eq!(is_anonymous_function_name(""), 0);
10677        assert_eq!(
10678            is_anonymous_function_name("anon"),
10679            0,
10680            "plain 'anon' (no parens) is NOT the sentinel"
10681        );
10682    }
10683
10684    /// `iscom("/nonexistent/never_a_path")` = false.
10685    #[test]
10686    fn exec_corpus_iscom_missing_path_false() {
10687        assert!(!iscom("/this/path/does/not/exist/zshrs_xyz"));
10688    }
10689
10690    /// `iscom("/tmp")` is a directory not a regular file → false.
10691    #[test]
10692    fn exec_corpus_iscom_directory_false() {
10693        assert!(!iscom("/tmp"), "/tmp is a dir, not a regular command");
10694    }
10695
10696    /// `iscom("/bin/sh")` is true on POSIX systems.
10697    #[test]
10698    fn exec_corpus_iscom_known_binary_true() {
10699        // /bin/sh exists on all POSIX systems with X perms.
10700        if std::path::Path::new("/bin/sh").exists() {
10701            assert!(iscom("/bin/sh"), "/bin/sh is a real executable");
10702        }
10703    }
10704
10705    // ─── stripkshdef (Src/exec.c:6286) early-return paths ──────────
10706
10707    /// `stripkshdef(None, "foo")` → `None` (matches C `if (!prog)
10708    /// return NULL;` at exec.c:6300).
10709    #[test]
10710    fn exec_corpus_stripkshdef_null_input_returns_none() {
10711        assert!(stripkshdef(None, "foo").is_none());
10712    }
10713
10714    /// `stripkshdef` on an empty/degenerate Eprog returns the same
10715    /// Eprog unchanged (no funcdef-shape to strip).
10716    #[test]
10717    fn exec_corpus_stripkshdef_empty_prog_returns_input() {
10718        let prog = Box::new(eprog {
10719            prog: vec![],
10720            ..Default::default()
10721        });
10722        let out = stripkshdef(Some(prog), "foo");
10723        assert!(out.is_some(), "empty prog → returned unchanged");
10724        assert!(out.unwrap().prog.is_empty(), "no mutation");
10725    }
10726
10727    /// `stripkshdef` on a non-WC_LIST head returns the input
10728    /// untouched (early return at exec.c:6304-6306).
10729    #[test]
10730    fn exec_corpus_stripkshdef_non_list_head_returns_input() {
10731        use crate::ported::zsh_h::{wc_bld, WC_SUBLIST};
10732        let prog = Box::new(eprog {
10733            prog: vec![wc_bld(WC_SUBLIST, 0), 0, 0],
10734            ..Default::default()
10735        });
10736        let out = stripkshdef(Some(prog), "foo");
10737        assert!(out.is_some());
10738        // first word is the WC_SUBLIST sentinel we passed in,
10739        // unchanged (the function bailed before doing any slicing).
10740        let p = out.unwrap();
10741        use crate::ported::zsh_h::wc_code;
10742        assert_eq!(
10743            wc_code(p.prog[0]),
10744            WC_SUBLIST,
10745            "header word preserved verbatim"
10746        );
10747    }
10748
10749    // ═══════════════════════════════════════════════════════════════════
10750    // C-parity tests pinning Src/exec.c. Tests that capture KNOWN
10751    // ZSHRS BUGS use #[ignore = "ZSHRS BUG: …"].
10752    // ═══════════════════════════════════════════════════════════════════
10753
10754    /// `isrelative("/abs/path")` returns 0 (false = absolute path).
10755    /// C `Src/exec.c:996-1006` — leading `/` and no `.`/`..` components.
10756    #[test]
10757    fn isrelative_absolute_path_returns_zero() {
10758        let _g = crate::test_util::global_state_lock();
10759        assert_eq!(isrelative("/usr/local/bin"), 0);
10760    }
10761
10762    /// `isrelative("foo/bar")` returns 1 (no leading slash).
10763    #[test]
10764    fn isrelative_no_leading_slash_returns_one() {
10765        let _g = crate::test_util::global_state_lock();
10766        assert_eq!(isrelative("foo/bar"), 1);
10767    }
10768
10769    /// `isrelative("/foo/./bar")` returns 1 — contains `/./` walk.
10770    /// C c:1001 — `.` with prev `/` + next `/` triggers relative flag.
10771    #[test]
10772    fn isrelative_dot_component_returns_one() {
10773        let _g = crate::test_util::global_state_lock();
10774        assert_eq!(isrelative("/foo/./bar"), 1, "/./ in path → relative");
10775    }
10776
10777    /// `isrelative("/foo/../bar")` returns 1 — contains `/..` walk.
10778    #[test]
10779    fn isrelative_dotdot_component_returns_one() {
10780        let _g = crate::test_util::global_state_lock();
10781        assert_eq!(isrelative("/foo/../bar"), 1, "/../ in path → relative");
10782    }
10783
10784    /// `isrelative("")` returns 1 — empty input has no leading `/`.
10785    /// C c:998 — `*s != '/'` includes the NUL terminator case.
10786    #[test]
10787    fn isrelative_empty_returns_one() {
10788        let _g = crate::test_util::global_state_lock();
10789        assert_eq!(isrelative(""), 1, "empty string → not absolute");
10790    }
10791
10792    /// `isrelative("/a/.b")` returns 0 — `.b` is NOT a `/./` walk
10793    /// (followed by another non-`/` char `b`).
10794    #[test]
10795    fn isrelative_dotfile_in_path_returns_zero() {
10796        let _g = crate::test_util::global_state_lock();
10797        assert_eq!(
10798            isrelative("/usr/.config/zsh"),
10799            0,
10800            "dotfile name '.config' is NOT a relative walk"
10801        );
10802    }
10803
10804    /// `is_anonymous_function_name("(anon)")` returns 1 (true).
10805    /// C `Src/exec.c` — `!strcmp(name, ANONYMOUS_FUNCTION_NAME)`.
10806    #[test]
10807    fn is_anonymous_function_name_anon_returns_one() {
10808        let _g = crate::test_util::global_state_lock();
10809        assert_eq!(is_anonymous_function_name("(anon)"), 1);
10810    }
10811
10812    /// `is_anonymous_function_name("foo")` returns 0 (false).
10813    #[test]
10814    fn is_anonymous_function_name_normal_returns_zero() {
10815        let _g = crate::test_util::global_state_lock();
10816        assert_eq!(is_anonymous_function_name("foo"), 0);
10817        assert_eq!(is_anonymous_function_name(""), 0);
10818        assert_eq!(is_anonymous_function_name("(other)"), 0);
10819    }
10820
10821    /// `isgooderr(EACCES, "/no/such/dir")` returns true when the dir
10822    /// is not actually accessible. C `Src/exec.c:isgooderr` filters
10823    /// out "unreadable / not directory" errnos so caller doesn't
10824    /// emit spurious warnings.
10825    #[test]
10826    #[ignore = "ZSHRS BUG: isgooderr exact semantics need verification — C: `((e != EACCES || !access(dir, X_OK)) && e != ENOENT && e != ENOTDIR)`"]
10827    fn isgooderr_eacces_unreadable_dir_returns_false() {
10828        let _g = crate::test_util::global_state_lock();
10829        // /no/such/dir doesn't exist → access(X_OK) fails non-zero
10830        // → !access() is 0 (false) → returns false.
10831        assert!(
10832            !isgooderr(libc::EACCES, "/no/such/dir/zshrs_test"),
10833            "unreadable dir with EACCES should NOT be 'good error'"
10834        );
10835    }
10836
10837    // ═══════════════════════════════════════════════════════════════════
10838    // Additional C-parity tests for Src/exec.c basic accessors/predicates.
10839    // ═══════════════════════════════════════════════════════════════════
10840
10841    /// c:658 — `isgooderr(ENOENT, _)` always false (regardless of dir).
10842    /// Pin: ENOENT is NEVER a "good error" because the path itself
10843    /// doesn't exist — caller should suppress the warning.
10844    #[test]
10845    fn isgooderr_enoent_always_false() {
10846        let _g = crate::test_util::global_state_lock();
10847        assert!(!isgooderr(libc::ENOENT, "/tmp"));
10848        assert!(!isgooderr(libc::ENOENT, "/no/such/dir"));
10849        assert!(!isgooderr(libc::ENOENT, ""));
10850    }
10851
10852    /// c:658 — `isgooderr(ENOTDIR, _)` always false. A path component
10853    /// being a non-dir is a structural error, not a permission issue.
10854    #[test]
10855    fn isgooderr_enotdir_always_false() {
10856        let _g = crate::test_util::global_state_lock();
10857        assert!(!isgooderr(libc::ENOTDIR, "/tmp"));
10858        assert!(!isgooderr(libc::ENOTDIR, "/"));
10859    }
10860
10861    /// c:658 — Other errnos (EPERM, EIO, ENOMEM) are "good errors"
10862    /// because they're not the suppressed three (EACCES/ENOENT/ENOTDIR).
10863    #[test]
10864    fn isgooderr_other_errno_returns_true() {
10865        let _g = crate::test_util::global_state_lock();
10866        assert!(isgooderr(libc::EPERM, "/tmp"));
10867        assert!(isgooderr(libc::EIO, "/tmp"));
10868        assert!(isgooderr(libc::ENOMEM, "/tmp"));
10869    }
10870
10871    /// c:962 — `iscom("/tmp")` returns false (directory, not S_ISREG).
10872    #[test]
10873    fn iscom_directory_returns_false() {
10874        let _g = crate::test_util::global_state_lock();
10875        assert!(!iscom("/tmp"));
10876        assert!(!iscom("/"));
10877    }
10878
10879    /// c:962 — `iscom` on non-existent path returns false (access
10880    /// X_OK fails).
10881    #[test]
10882    fn iscom_nonexistent_path_returns_false() {
10883        let _g = crate::test_util::global_state_lock();
10884        assert!(!iscom("/no/such/path/zshrs_iscom_test"));
10885        assert!(!iscom(""));
10886    }
10887
10888    /// c:962 — `iscom("/bin/sh")` returns true on every POSIX system.
10889    #[test]
10890    #[cfg(unix)]
10891    fn iscom_bin_sh_returns_true() {
10892        let _g = crate::test_util::global_state_lock();
10893        // /bin/sh is a POSIX-required executable.
10894        assert!(iscom("/bin/sh"), "/bin/sh must be executable on POSIX");
10895    }
10896
10897    /// c:5300 — anonymous function name is exactly "(anon)" — must
10898    /// not match prefixes/suffixes/case variants.
10899    #[test]
10900    fn is_anonymous_function_name_strict_match_only() {
10901        let _g = crate::test_util::global_state_lock();
10902        assert_eq!(is_anonymous_function_name("(anon"), 0, "no trailing paren");
10903        assert_eq!(is_anonymous_function_name("anon)"), 0, "no leading paren");
10904        assert_eq!(is_anonymous_function_name("(ANON)"), 0, "wrong case");
10905        assert_eq!(
10906            is_anonymous_function_name(" (anon) "),
10907            0,
10908            "leading/trailing space"
10909        );
10910        assert_eq!(is_anonymous_function_name("(anon) "), 0, "trailing space");
10911        assert_eq!(is_anonymous_function_name(" (anon)"), 0, "leading space");
10912    }
10913
10914    /// c:5289 — `ANONYMOUS_FUNCTION_NAME` constant is exactly `"(anon)"`.
10915    /// Pin so a regen that flips parens / changes case / adds prefix
10916    /// would be caught.
10917    #[test]
10918    fn anonymous_function_name_const_is_literal_anon() {
10919        let _g = crate::test_util::global_state_lock();
10920        assert_eq!(ANONYMOUS_FUNCTION_NAME, "(anon)");
10921    }
10922
10923    /// c:147-148 — `isrelative("./")` returns 1 (dot-slash prefix
10924    /// is the canonical relative-path form).
10925    #[test]
10926    fn isrelative_dot_slash_returns_one() {
10927        let _g = crate::test_util::global_state_lock();
10928        assert_eq!(isrelative("./foo"), 1);
10929        assert_eq!(isrelative("./"), 1);
10930    }
10931
10932    /// c:147-148 — `isrelative("../foo")` returns 1.
10933    #[test]
10934    fn isrelative_dotdot_slash_returns_one() {
10935        let _g = crate::test_util::global_state_lock();
10936        assert_eq!(isrelative("../foo"), 1);
10937        assert_eq!(isrelative("../"), 1);
10938    }
10939
10940    /// c:147-148 — `/.foo` (hidden file under root) is absolute.
10941    /// Pin: only `/.` (with trailing `/`) or end-of-string counts as
10942    /// a `.` component, NOT `/.foo` (which is a normal file `.foo`).
10943    #[test]
10944    fn isrelative_root_hidden_file_returns_zero() {
10945        let _g = crate::test_util::global_state_lock();
10946        assert_eq!(isrelative("/.foo"), 0, "/.foo is absolute path to dotfile");
10947        assert_eq!(isrelative("/.bashrc"), 0, "/.bashrc is absolute");
10948    }
10949
10950    /// c:147-148 — `/..bar` (file named `..bar`) is also absolute,
10951    /// since `..bar` is a regular file name, not a `..` component.
10952    #[test]
10953    fn isrelative_root_double_dot_file_returns_zero() {
10954        let _g = crate::test_util::global_state_lock();
10955        assert_eq!(isrelative("/..bar"), 0);
10956    }
10957
10958    /// c:2652 — `setunderscore("")` clears `zunderscore` and resets
10959    /// `underscoreused` to 1 (null terminator only).
10960    #[test]
10961    fn setunderscore_empty_clears_state() {
10962        let _g = crate::test_util::global_state_lock();
10963        setunderscore(""); // initialize to known empty state
10964        let zu = zunderscore.lock().unwrap();
10965        assert!(zu.is_empty(), "zunderscore must be empty after clear");
10966        drop(zu);
10967        let used = underscoreused.load(Ordering::Relaxed);
10968        assert_eq!(used, 1, "underscoreused must be 1 (NUL only) after clear");
10969    }
10970
10971    /// c:2652 — `setunderscore(str)` sets `zunderscore=str` and
10972    /// `underscoreused = str.len()+1` (string + null terminator).
10973    #[test]
10974    fn setunderscore_with_value_stores_string_and_length() {
10975        let _g = crate::test_util::global_state_lock();
10976        setunderscore("hello");
10977        let zu = zunderscore.lock().unwrap();
10978        assert_eq!(*zu, "hello");
10979        drop(zu);
10980        let used = underscoreused.load(Ordering::Relaxed);
10981        assert_eq!(used, 6, "len('hello')+1 = 6");
10982    }
10983
10984    /// c:2656 — `underscorelen` is rounded up to 32-byte boundary
10985    /// for the bump-allocator-friendly buffer growth.
10986    #[test]
10987    fn setunderscore_rounds_underscorelen_to_32() {
10988        let _g = crate::test_util::global_state_lock();
10989        setunderscore("ab"); // len 2 + 1 = 3 → ceil(32) = 32
10990        let nl = underscorelen.load(Ordering::Relaxed);
10991        assert_eq!(nl, 32, "(2+1+31) & !31 = 32");
10992    }
10993
10994    // ═══════════════════════════════════════════════════════════════════
10995    // Additional C-parity tests for Src/exec.c cancd2 +
10996    // quote_tokenized_output.
10997    // ═══════════════════════════════════════════════════════════════════
10998
10999    /// c:6411 — `cancd2("/tmp")` returns 1 (directory with X_OK exists).
11000    #[test]
11001    #[cfg(unix)]
11002    fn cancd2_existing_dir_returns_one() {
11003        let _g = crate::test_util::global_state_lock();
11004        assert_eq!(cancd2("/tmp"), 1, "/tmp is a valid cd target");
11005    }
11006
11007    /// c:6411 — `cancd2("/nonexistent")` returns 0.
11008    #[test]
11009    fn cancd2_nonexistent_returns_zero() {
11010        let _g = crate::test_util::global_state_lock();
11011        assert_eq!(cancd2("/__never_exists_zshrs_cancd2__"), 0);
11012    }
11013
11014    /// c:6411 — `cancd2` for a file (not dir) returns 0.
11015    #[test]
11016    #[cfg(unix)]
11017    fn cancd2_regular_file_returns_zero() {
11018        let _g = crate::test_util::global_state_lock();
11019        let dir = tempfile::tempdir().unwrap();
11020        let p = dir.path().join("regular_file");
11021        std::fs::write(&p, "x").unwrap();
11022        assert_eq!(
11023            cancd2(p.to_str().unwrap()),
11024            0,
11025            "regular file not a cd target"
11026        );
11027    }
11028
11029    /// c:2114 — `quote_tokenized_output` on empty string writes nothing.
11030    #[test]
11031    fn quote_tokenized_output_empty_writes_nothing() {
11032        let _g = crate::test_util::global_state_lock();
11033        let mut buf = Vec::new();
11034        quote_tokenized_output("", &mut buf).unwrap();
11035        assert!(buf.is_empty());
11036    }
11037
11038    /// c:2114 — plain ASCII passes through unchanged.
11039    #[test]
11040    fn quote_tokenized_output_plain_ascii_unchanged() {
11041        let _g = crate::test_util::global_state_lock();
11042        let mut buf = Vec::new();
11043        quote_tokenized_output("hello", &mut buf).unwrap();
11044        assert_eq!(buf, b"hello");
11045    }
11046
11047    /// c:2143 — space gets backslash-quoted.
11048    #[test]
11049    fn quote_tokenized_output_space_backslash_quoted() {
11050        let _g = crate::test_util::global_state_lock();
11051        let mut buf = Vec::new();
11052        quote_tokenized_output("a b", &mut buf).unwrap();
11053        assert_eq!(buf, b"a\\ b");
11054    }
11055
11056    /// c:2147 — tab → $'\\t'.
11057    #[test]
11058    fn quote_tokenized_output_tab_dollar_escape() {
11059        let _g = crate::test_util::global_state_lock();
11060        let mut buf = Vec::new();
11061        quote_tokenized_output("a\tb", &mut buf).unwrap();
11062        assert_eq!(buf, b"a$'\\t'b");
11063    }
11064
11065    /// c:2151 — newline → $'\\n'.
11066    #[test]
11067    fn quote_tokenized_output_newline_dollar_escape() {
11068        let _g = crate::test_util::global_state_lock();
11069        let mut buf = Vec::new();
11070        quote_tokenized_output("a\nb", &mut buf).unwrap();
11071        assert_eq!(buf, b"a$'\\n'b");
11072    }
11073
11074    /// c:2155 — CR → $'\\r'.
11075    #[test]
11076    fn quote_tokenized_output_cr_dollar_escape() {
11077        let _g = crate::test_util::global_state_lock();
11078        let mut buf = Vec::new();
11079        quote_tokenized_output("a\rb", &mut buf).unwrap();
11080        assert_eq!(buf, b"a$'\\r'b");
11081    }
11082
11083    /// c:2128 — shell metacharacters all get backslash-quoted.
11084    #[test]
11085    fn quote_tokenized_output_shell_metas_get_backslash() {
11086        let _g = crate::test_util::global_state_lock();
11087        for c in &[b'<', b'>', b'(', b')', b'|', b'#', b'$', b'*', b'?', b'~'] {
11088            let mut buf = Vec::new();
11089            let s = String::from_utf8(vec![b'a', *c, b'b']).unwrap();
11090            quote_tokenized_output(&s, &mut buf).unwrap();
11091            assert_eq!(buf, vec![b'a', b'\\', *c, b'b'], "char {:?}", *c as char);
11092        }
11093    }
11094
11095    /// c:2158 — `=` at position 0 gets quoted (path-spec).
11096    #[test]
11097    fn quote_tokenized_output_equals_at_start_quoted() {
11098        let _g = crate::test_util::global_state_lock();
11099        let mut buf = Vec::new();
11100        quote_tokenized_output("=foo", &mut buf).unwrap();
11101        assert_eq!(buf, b"\\=foo");
11102    }
11103
11104    // ═══════════════════════════════════════════════════════════════════
11105    // Additional C-parity tests for Src/exec.c
11106    // c:1287 iscom / c:1347 isrelative / c:1398 setunderscore /
11107    // c:1468 is_anonymous_function_name / c:2208 findcmd / c:3273 parsecmd
11108    // c:1264 isgooderr / c:1226 parse_string
11109    // ═══════════════════════════════════════════════════════════════════
11110
11111    /// c:1287 — `iscom("")` empty input returns false.
11112    #[test]
11113    fn iscom_empty_string_returns_false() {
11114        let _g = crate::test_util::global_state_lock();
11115        assert!(!iscom(""), "empty cmd name → not a command");
11116    }
11117
11118    /// c:1287 — `iscom` returns bool (compile-time type pin).
11119    #[test]
11120    fn iscom_returns_bool_type() {
11121        let _g = crate::test_util::global_state_lock();
11122        let _: bool = iscom("ls");
11123    }
11124
11125    /// c:1347 — `isrelative("/abs")` returns 0 (absolute path).
11126    #[test]
11127    fn isrelative_absolute_path_returns_zero_pin() {
11128        assert_eq!(isrelative("/usr/bin"), 0, "/usr/bin is absolute");
11129        assert_eq!(isrelative("/"), 0, "/ is absolute");
11130    }
11131
11132    /// c:1347 — `isrelative("rel/path")` returns 1 (relative).
11133    #[test]
11134    fn isrelative_relative_path_returns_one_pin() {
11135        assert_eq!(isrelative("foo"), 1, "foo is relative");
11136        assert_eq!(isrelative("./foo"), 1, "./foo is relative");
11137        assert_eq!(isrelative("../foo"), 1, "../foo is relative");
11138    }
11139
11140    /// c:1347 — `isrelative("")` empty returns 1 (relative by C convention).
11141    #[test]
11142    fn isrelative_empty_returns_relative() {
11143        let r = isrelative("");
11144        assert!(r == 0 || r == 1, "must be 0 or 1");
11145    }
11146
11147    /// c:1468 — `is_anonymous_function_name` returns i32 (type pin).
11148    #[test]
11149    fn is_anonymous_function_name_returns_i32_type() {
11150        let _: i32 = is_anonymous_function_name("(anon)");
11151    }
11152
11153    /// c:1468 — `is_anonymous_function_name("")` empty returns 0.
11154    #[test]
11155    fn is_anonymous_function_name_empty_returns_zero() {
11156        assert_eq!(
11157            is_anonymous_function_name(""),
11158            0,
11159            "empty name is not anonymous"
11160        );
11161    }
11162
11163    /// c:1468 — `is_anonymous_function_name` is deterministic.
11164    #[test]
11165    fn is_anonymous_function_name_is_deterministic() {
11166        for s in ["", "name", "(anon)", "(anon: foo)"] {
11167            let first = is_anonymous_function_name(s);
11168            for _ in 0..3 {
11169                assert_eq!(
11170                    is_anonymous_function_name(s),
11171                    first,
11172                    "is_anonymous_function_name({:?}) must be deterministic",
11173                    s
11174                );
11175            }
11176        }
11177    }
11178
11179    /// c:1226 — `parse_string("")` empty returns Option<eprog> (type pin).
11180    #[test]
11181    fn parse_string_returns_option_eprog_type() {
11182        let _g = crate::test_util::global_state_lock();
11183        let _: Option<eprog> = parse_string("", 0);
11184    }
11185
11186    /// c:1398 — `setunderscore("")` empty string is safe.
11187    #[test]
11188    fn setunderscore_empty_no_panic() {
11189        let _g = crate::test_util::global_state_lock();
11190        setunderscore("");
11191    }
11192
11193    /// c:1264 — `isgooderr` returns bool (compile-time type pin).
11194    #[test]
11195    fn isgooderr_returns_bool_type() {
11196        let _: bool = isgooderr(0, "/tmp");
11197    }
11198
11199    // ═══════════════════════════════════════════════════════════════════
11200    // Additional C-parity tests for Src/exec.c
11201    // c:3325 makecline / c:4603 cancd / c:4674 simple_redir_name /
11202    // c:1287 iscom / c:1314 isreallycom / c:3076 commandnotfound
11203    // ═══════════════════════════════════════════════════════════════════
11204
11205    /// c:3325 — `makecline` returns Vec<String> (compile-time type pin).
11206    #[test]
11207    fn makecline_returns_vec_string_type() {
11208        let _g = crate::test_util::global_state_lock();
11209        let _: Vec<String> = makecline(&[]);
11210    }
11211
11212    /// c:3325 — `makecline([])` empty returns empty Vec.
11213    #[test]
11214    fn makecline_empty_input_returns_empty() {
11215        let _g = crate::test_util::global_state_lock();
11216        let r = makecline(&[]);
11217        assert!(r.is_empty(), "empty input → empty output");
11218    }
11219
11220    /// c:3325 — `makecline` preserves input order.
11221    #[test]
11222    fn makecline_preserves_input_order() {
11223        let _g = crate::test_util::global_state_lock();
11224        let input = vec!["one".to_string(), "two".to_string(), "three".to_string()];
11225        let out = makecline(&input);
11226        assert_eq!(out, input, "makecline must preserve order");
11227    }
11228
11229    /// c:3325 — `makecline` clones (output is independent of input).
11230    #[test]
11231    fn makecline_returns_independent_copy() {
11232        let _g = crate::test_util::global_state_lock();
11233        let input = vec!["a".to_string(), "b".to_string()];
11234        let out = makecline(&input);
11235        assert_eq!(out.len(), input.len(), "lengths match");
11236        // Output can be mutated without affecting input.
11237        let mut out_mut = out;
11238        out_mut.push("c".to_string());
11239        assert_eq!(input.len(), 2, "input unchanged");
11240    }
11241
11242    /// c:4603 — `cancd("")` empty path returns None.
11243    /// ZSHRS BUG: empty path returns Some(...) instead of None. C path
11244    /// at Src/exec.c:6376 enters relative-path branch which calls cancd2("")
11245    /// — that should return 0 (not a valid dir), causing the fn to fall
11246    /// through CDPATH and cd_able_vars, both of which should miss for
11247    /// the empty string. Likely cd_able_vars("") or CDPATH-with-empty-element
11248    /// is silently matching $HOME or "." here.
11249    #[test]
11250    #[ignore = "ZSHRS BUG: cancd('') returns Some instead of None — likely cd_able_vars or empty CDPATH element matching $HOME (Src/exec.c:6383-6403)"]
11251    fn cancd_empty_returns_none() {
11252        let _g = crate::test_util::global_state_lock();
11253        assert!(cancd("").is_none(), "empty path → None");
11254    }
11255
11256    /// c:4603 — `cancd("/")` root dir returns Some (always exists).
11257    #[test]
11258    fn cancd_root_returns_some() {
11259        let _g = crate::test_util::global_state_lock();
11260        let r = cancd("/");
11261        assert_eq!(r.as_deref(), Some("/"), "root dir cancd → Some(/)");
11262    }
11263
11264    /// c:4603 — `cancd` returns Option<String> (compile-time type pin).
11265    #[test]
11266    fn cancd_returns_option_string_type() {
11267        let _g = crate::test_util::global_state_lock();
11268        let _: Option<String> = cancd("/");
11269    }
11270
11271    /// c:4603 — `cancd("/__nonexistent__")` returns None.
11272    #[test]
11273    fn cancd_nonexistent_returns_none() {
11274        let _g = crate::test_util::global_state_lock();
11275        assert!(
11276            cancd("/__nonexistent_zshrs_dir_xyz__").is_none(),
11277            "nonexistent dir → None"
11278        );
11279    }
11280
11281    /// c:4603 — `cancd("/tmp")` exists → Some.
11282    #[test]
11283    fn cancd_tmp_returns_some() {
11284        let _g = crate::test_util::global_state_lock();
11285        let r = cancd("/tmp");
11286        assert!(r.is_some(), "/tmp exists → Some");
11287    }
11288
11289    /// c:4603 — `cancd` is deterministic for stable paths.
11290    #[test]
11291    fn cancd_is_deterministic_for_stable_paths() {
11292        let _g = crate::test_util::global_state_lock();
11293        for p in ["/", "/tmp", "/__never__"] {
11294            let first = cancd(p).is_some();
11295            for _ in 0..3 {
11296                assert_eq!(
11297                    cancd(p).is_some(),
11298                    first,
11299                    "cancd({:?}) must be deterministic",
11300                    p
11301                );
11302            }
11303        }
11304    }
11305
11306    /// c:1287 — `iscom` is deterministic for stable paths.
11307    #[test]
11308    fn iscom_is_deterministic_for_stable_paths() {
11309        let _g = crate::test_util::global_state_lock();
11310        for p in ["/tmp", "/__never__", "/bin/sh"] {
11311            let first = iscom(p);
11312            for _ in 0..3 {
11313                assert_eq!(iscom(p), first, "iscom({:?}) must be deterministic", p);
11314            }
11315        }
11316    }
11317
11318    /// c:3076 — `commandnotfound("", ...)` empty cmd returns i32.
11319    #[test]
11320    fn commandnotfound_returns_i32_type() {
11321        let _g = crate::test_util::global_state_lock();
11322        let mut args = Vec::new();
11323        let _: i32 = commandnotfound("", &mut args);
11324    }
11325}