zsh/vm_helper.rs
1//! Shell executor state for zshrs.
2//!
3//! ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
4//! !!! LAST-RESORT FILE — NOT FOR NEW LOGIC !!!
5//!
6//! This file holds the `ShellExecutor` runtime state struct + VM-adjacent
7//! helpers. It is **not** the place to add zsh logic — every line here that
8//! does real shell work is a tax we pay because zshrs uses fusevm bytecode
9//! instead of C zsh's wordcode walker.
10//!
11//! **Before adding code to this file, STOP and ask:**
12//!
13//! 1. Does the C source have a fn that does this? (Check `src/zsh/Src/*.c`)
14//! → Port it into `src/ported/<file>.rs` with line-by-line citations.
15//! Then call the canonical fn from here.
16//!
17//! 2. Does `src/ported/` already have a port?
18//! → Call it directly. Don't reimplement.
19//!
20//! 3. Is this purely a Rust-only state-struct accessor (getter/setter on
21//! ShellExecutor fields, VM init plumbing, executor-context guards)?
22//! → OK to put it here. Mark it `WARNING: RUST-ONLY HELPER` per memory
23//! `feedback_rust_only_helpers_need_warning`.
24//!
25//! **NEVER:** reinvent paramsubst/expansion/glob/typeset/redirect/scope
26//! management here. Every one of those has a canonical port in `src/ported/`.
27//! When a bridge-side fn grows past ~30 lines of shell logic, that's a
28//! signal the work belongs in `src/ported/` — port it, don't inline.
29//!
30//! This file should be SHRINKING over time. Every PR that adds lines here
31//! should justify it; every PR that moves lines OUT to `src/ported/` is
32//! aligned with the project direction.
33//!
34//! See also: memory `feedback_no_shortcuts_in_porting`, `feedback_true_port_pattern`,
35//! `feedback_no_shellexecutor_in_ported` (the inverse direction).
36//! ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
37//!
38//! **Not a port of Src/exec.c.** C zsh runs compiled programs on the native
39//! **wordcode walker** in `Src/exec.c` (`execlist` / `execpline` / `execcmd`).
40//! zshrs uses fusevm bytecode instead; the bridge lives in `src/fusevm_bridge.rs`.
41//! This file holds:
42//! - `ShellExecutor` — the runtime state struct that the VM and
43//! every ported builtin/utility threads through
44//! - VM-adjacent helpers that read/write that state
45//!
46//! Path-wise this file lives at the crate root (`src/vm_helper`) rather
47//! than in `src/ported/` because nothing here corresponds 1:1 to a
48//! `Src/*.c` source file. `crate::ported::exec` is kept as a
49//! re-export alias so existing call-sites continue to compile.
50
51use crate::compsys::cache::CompsysCache;
52use crate::compsys::CompInitResult;
53use crate::history::HistoryEngine;
54use crate::options::ZSH_OPTIONS_SET;
55use crate::ported::builtin::{BREAKS, CONTFLAG};
56use crate::ported::math::mathevali;
57use crate::ported::modules::parameter::*;
58use crate::ported::subst::singsub;
59
60thread_local! {
61 /// Eval-recursion depth counter — no C counterpart by design.
62 ///
63 /// !!! WARNING: RUST-ONLY BACKSTOP — reproduces C behaviour, no C fn !!!
64 ///
65 /// zsh bounds runaway `eval` recursion via its job table: every eval'd
66 /// list runs through `execpline`, which grabs a job slot per pipeline
67 /// (`initjob`), and the table caps at `MAX_MAXJOBS` → `zerr("job table
68 /// full or recursion limit exceeded")` (Src/jobs.c:1878-1884). The fusevm
69 /// runtime that executes eval bodies allocates no job per pipeline, and
70 /// nested evals push no funcstack frame (INEVAL suppression, matching zsh's
71 /// `if (!ineval)` at Src/builtin.c:6164), so neither the job table nor the
72 /// FUNCNEST/FUNCSTACK depth reflects eval nesting — leaving eval recursion
73 /// unbounded until the (256 MB but finite) main-thread stack overflows →
74 /// uncatchable SIGBUS. This counter is the Rust proxy for zsh's count of
75 /// concurrently-held job slots: `builtin.rs::eval` bumps it around each
76 /// eval body and refuses to recurse at the same `MAX_MAXJOBS` ceiling.
77 /// Lives here (not src/ported/) because it is an architectural Rust-only
78 /// backstop with no 1:1 C symbol.
79 pub static EVAL_RECURSION_DEPTH: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
80 /// Set by `execute_cmdarg` for the next compile_script_isolated only —
81 /// the `-c` string itself, not an `eval` or trap it runs.
82 ///
83 /// !!! WARNING: RUST-ONLY FLAG — C PASSES `exiting` TO execode !!!
84 static CMDARG_EXITING: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
85}
86
87/// O(1) single-key probe against the canonical hashed storage — the
88/// fast-path companion to subst.rs `assoc_get` for order-independent
89/// single-key reads. Returns `None` when `name` (post-nameref) isn't
90/// an assoc; otherwise `Some((key_present, value))` under ONE lock,
91/// with no whole-map clone and no zsh-bucket-order rebuild (that
92/// reorder is only observable to whole-map enumeration). Hot: shell
93/// loops reading `${assoc[$k]}` per iteration were O(n²) through
94/// assoc_get — zpwr expandstats over 42k records took 43s vs zsh's ~1s.
95/// Lives here (not src/ported/) because it has no C counterpart — C's
96/// getarg IS the single-key path.
97/// Classify an assoc subscript as an EXACT-key lookup and return the
98/// key: plain text (no leading flag group) passes through; a leading
99/// `(e…)`/`(E…)` group (c:Src/params.c:1449 — literal-key flag) is
100/// stripped. Search groups ((r)/(i)/(k)/…) return `None` — they need
101/// the full getarg walk. Companion gate for [`assoc_key_hit`]'s O(1)
102/// fast paths.
103/// !!! WARNING: RUST-ONLY HELPER — body of c:Src/init.c:180-215, lifted out
104/// of loop() so the script-file event loop (`run_events_per_command`) runs
105/// the same code; src/ported/ may not gain functions. !!!
106///
107/// The `toplevel` preexec branch of loop(): when a `preexec` function or
108/// `preexec_functions` exists, call the hook with `$1` (the history line, or
109/// "" when the history ring does not hold the current line — always the
110/// case for a script), `$2` (getjobtext) and `$3` (getpermtext), then clear
111/// ERRFLAG_ERROR (c:214). `event_src` is the event's source text captured
112/// around parse_event; zshrs's parse_event returns the fusevm AST, which the
113/// text renderers cannot walk, so the source is compiled to the wordcode
114/// Eprog C would already hold. That compile is silent and leaves errflag as
115/// it found it; an event it cannot take gets empty `$2`/`$3`.
116pub fn run_preexec_hook(event_src: Option<&str>) {
117 use crate::ported::zsh_h::{interact, isset, INTERACTIVECOMMENTS, SHINSTDIN};
118 // Native p10k engine command timer (src/extensions/p10k): stamp the
119 // command start for command_execution_time, with or without a user hook.
120 crate::p10k::note_exec_start();
121 let preexec_fn = crate::ported::utils::getshfunc("preexec"); // c:181
122 let preexec_hook = crate::ported::params::paramtab()
123 .read()
124 .ok()
125 .and_then(|t| {
126 t.get(&format!("preexec{}", crate::ported::zsh_h::HOOK_SUFFIX))
127 .map(|_| ())
128 }); // c:182 realparamtab->getnode2(realparamtab, "preexec" HOOK_SUFFIX)
129 if preexec_fn.is_none() && preexec_hook.is_none() {
130 return;
131 }
132 let mut args: Vec<String> = Vec::new(); // c:191 newlinklist()
133 args.push("preexec".to_string()); // c:192
134 {
135 // c:195 — `if (hist_ring && curline.histnum == curhist)`
136 let hr = crate::ported::hist::hist_ring.lock().unwrap();
137 let cl = crate::ported::hist::curline.lock().unwrap();
138 let same = !hr.is_empty()
139 && cl.as_ref().map(|c| c.histnum).unwrap_or(0)
140 == crate::ported::hist::curhist.load(Ordering::SeqCst);
141 if same {
142 args.push(hr.first().map(|h| h.node.nam.clone()).unwrap_or_default()); // c:196
143 } else {
144 args.push(String::new()); // c:198
145 }
146 }
147 let event_prog: Option<crate::ported::zsh_h::eprog> = event_src.and_then(|src| {
148 let noerrs = crate::ported::utils::noerrs_lock();
149 let saved_noerrs = std::mem::replace(&mut *noerrs.lock().unwrap(), 1);
150 let saved_errflag = errflag.load(Ordering::SeqCst);
151 // The event was lexed with `strin == 0`, where a `#` starts a comment
152 // only under INTERACTIVECOMMENTS in an interactive stdin shell
153 // (c:Src/lex.c:678-681). parse_string lexes under `strin`, which would
154 // turn comments on; `nocomments` restores that decision, the way
155 // getoutput does around its own parse_string (c:Src/exec.c:4720-4723).
156 let onc = crate::ported::lex::LEX_NOCOMMENTS.with(|c| c.get());
157 crate::ported::lex::LEX_NOCOMMENTS.with(|c| {
158 c.set(interact() && isset(SHINSTDIN) && !isset(INTERACTIVECOMMENTS))
159 });
160 let p = crate::ported::exec::parse_string(src, 0);
161 crate::ported::lex::LEX_NOCOMMENTS.with(|c| c.set(onc));
162 errflag.store(saved_errflag, Ordering::SeqCst);
163 *noerrs.lock().unwrap() = saved_noerrs;
164 p
165 });
166 // c:210 — addlinknode(args, dupstring(getjobtext(prog, NULL)))
167 // c:211 — addlinknode(args, cmdstr = getpermtext(prog, NULL, 0))
168 let (job_text, cmdstr) = match event_prog {
169 Some(p) => (
170 crate::ported::text::getjobtext(Box::new(p.clone()), None), // c:210
171 crate::ported::text::getpermtext(Box::new(p), None, 0), // c:211
172 ),
173 None => (String::new(), String::new()),
174 };
175 args.push(crate::ported::mem::dupstring(&job_text));
176 args.push(cmdstr.clone());
177 crate::ported::utils::callhookfunc("preexec", Some(&args), 1, std::ptr::null_mut()); // c:202
178 crate::ported::mem::zsfree(cmdstr); // c:205
179 errflag.fetch_and(!ERRFLAG_ERROR, Ordering::SeqCst); // c:214
180}
181
182pub fn exact_assoc_sub_key(sub: &str) -> Option<&str> {
183 match sub.strip_prefix('(') {
184 None => Some(sub),
185 Some(rest) => {
186 let close = rest.find(')')?;
187 let grp = &rest[..close];
188 if !grp.is_empty() && grp.chars().all(|c| c == 'e' || c == 'E') {
189 Some(&rest[close + 1..])
190 } else {
191 None
192 }
193 }
194 }
195}
196
197pub fn assoc_key_hit(name: &str, key: &str) -> Option<(bool, Option<String>)> {
198 let resolved = match crate::ported::params::resolve_nameref_name(name, None) {
199 crate::ported::params::nameref_resolution::Target { name: t_, .. } => t_,
200 _ => name.to_string(),
201 };
202 // c:Src/params.c:1090-1115 createparam — a `local NAME` / `typeset
203 // NAME` replaces a special's paramtab node with a plain one, so the
204 // name is no longer a hash. Answering here would strand the read on
205 // the O(1) assoc fast path and never reach paramsubst's scalar
206 // subscript arm (`${options[1]}` came back empty for a local).
207 //
208 // …but "no longer the magic row" is NOT the same as "no longer a
209 // hash": a `local -A commands` shadow owns a table of its own and the
210 // key read must be served FROM IT (c:Src/params.c:2270 / :1597-1606).
211 // See `magic_special_shadowed_by_nonhash`, which every sibling
212 // dispatch site shares so the qualification cannot drift.
213 if magic_special_shadowed_by_nonhash(resolved.as_str()) {
214 return None;
215 }
216 // c:Src/Zle/complete.c:1272/1411 — `compstate[nmatches]` is a LIVE gsu
217 // integer (`get_nmatches` = `permmatches(0) ? 0 : nmatches`), not stored
218 // data, so the hashed store never held it and every shell-side read
219 // returned the EMPTY string. `_parameters` (`local -i nm=$compstate[
220 // nmatches]` … `(( compstate[nmatches] > nm ))`) therefore always
221 // reported "added nothing" and returned 1 — `unset <TAB>` offered 197
222 // names against zsh's 496 — and the same idiom in `_alternative`,
223 // `_describe` and `_arguments` mis-fired the same way.
224 // The same applies to the other NINE gsu-backed rows
225 // (c:complete.c:1261-1300): list_lines, list_max, unambiguous,
226 // unambiguous_cursor, unambiguous_positions, insert_positions, vared,
227 // all_quotes, ignored. Only `nmatches` was served live here, so
228 // `$compstate[list_lines]` and friends read empty from shell code
229 // where zsh reports a value.
230 if resolved == "compstate" && crate::ported::zle::compcore::LIVE_COMPSTATE_KEYS.contains(&key) {
231 return Some((
232 true,
233 Some(
234 crate::ported::zle::compcore::get_compstate_str(key).unwrap_or_else(|| {
235 if key == "nmatches" {
236 "0".to_string()
237 } else {
238 String::new()
239 }
240 }),
241 ),
242 ));
243 }
244 crate::ported::params::paramtab_hashed_storage()
245 .lock()
246 .ok()
247 .and_then(|s| {
248 s.get(resolved.as_str())
249 .map(|m| (m.contains_key(key), m.get(key).cloned()))
250 })
251}
252use crate::ported::utils::{errflag, ERRFLAG_ERROR};
253use crate::ported::zsh_h::PM_UNDEFINED;
254use crate::ported::zsh_h::WC_SIMPLE;
255use crate::ported::zsh_h::{options, MAX_OPS};
256use crate::ported::zsh_h::{PM_ARRAY, PM_HASHED, PM_INTEGER, PM_READONLY};
257use parking_lot::Mutex;
258use std::collections::HashSet;
259use std::ffi::CStr;
260use std::ffi::CString;
261use std::ffi::OsStr;
262use std::fs;
263use std::io::Read;
264use std::os::unix::ffi::OsStrExt;
265use std::os::unix::fs::FileTypeExt;
266use std::os::unix::fs::PermissionsExt;
267use std::os::unix::io::FromRawFd;
268use std::sync::atomic::AtomicI32;
269use std::sync::atomic::Ordering;
270use std::time::{SystemTime, UNIX_EPOCH};
271use walkdir::WalkDir;
272
273// Backward-compat re-exports for free ported recently relocated to their
274// canonical-C-file Rust modules. Existing call-sites in this file (and
275// elsewhere) still reference these unqualified.
276#[allow(unused_imports)]
277pub(crate) use crate::func_body_fmt::FuncBodyFmt;
278#[allow(unused_imports)]
279pub(crate) use crate::ported::hist::bufferwords as bufferwords_z_tuple;
280#[allow(unused_imports)]
281pub(crate) use crate::ported::math::{parse_assign, parse_compound, parse_pre_inc};
282#[allow(unused_imports)]
283pub use crate::ported::params::convbase as format_int_in_base;
284pub use crate::ported::params::convbase_underscore;
285// `getarrvalue` is already re-exported by `pub use crate::ported::params::*`
286// below; an explicit `pub(crate) use` here only shadowed that public export.
287#[allow(unused_imports)]
288pub(crate) use crate::ported::utils::base64_decode;
289#[allow(unused_imports)]
290pub(crate) use crate::ported::utils::{ispwd, printprompt4, quotedzputs};
291
292pub(crate) use crate::intercepts::intercept_matches;
293/// AOP advice type — before, after, or around.
294pub use crate::intercepts::{AdviceKind, Intercept};
295
296/// Result from background compinit thread.
297pub use crate::compinit_bg::CompInitBgResult;
298use std::io::Write;
299use std::sync::LazyLock;
300
301/// State snapshot for plugin delta computation.
302pub(crate) use crate::plugin_cache::PluginSnapshot;
303
304/// Cached compiled regexes for hot paths
305pub(crate) static REGEX_CACHE: LazyLock<Mutex<HashMap<String, Regex>>> =
306 LazyLock::new(|| Mutex::new(HashMap::with_capacity(64)));
307
308// fusevm VM bridge (extension; not a port of Src/exec.c) lives in
309// src/fusevm_bridge.rs. Re-exports below let the rest of the codebase
310// reference symbols as `crate::ported::exec::X`.
311pub(crate) use crate::fusevm_bridge::ExecutorContext;
312pub use crate::fusevm_bridge::*;
313
314/// `ZSH_VERSION` / `ZSH_PATCHLEVEL` / `ZSH_VERSION_DATE` consts
315/// generated by `build.rs` from `src/zsh/Config/version.mk`. Use
316/// `zsh_version::ZSH_VERSION` etc. at call sites so version bumps
317/// pick up automatically.
318pub mod zsh_version {
319 include!(concat!(env!("OUT_DIR"), "/zsh_version.rs"));
320}
321
322/// Match an intercept pattern against a command name or full command string.
323/// Supports: exact match, glob ("git *", "_*", "*"), or "all".
324
325/// O(1) builtin-name lookup set derived from the canonical
326/// `BUILTINS` table (`src/ported/builtin.rs:122`, the 1:1 port of
327/// `static struct builtin builtins[]` at `Src/builtin.c:40-137`).
328/// Earlier incarnation hardcoded a separate 130-entry list which
329/// drifted whenever new builtins landed in the canonical table — and
330/// shadowed the `fusevm::shell_builtins::BUILTIN_SET` u16 opcode
331/// constant. Renaming to `BUILTIN_NAMES` removes the shadow; the
332/// initialiser walks `BUILTINS` so the set stays in sync.
333///
334/// The hardcoded entries inside `LazyLock::new` below are kept as
335/// the union of: (1) names from `BUILTINS` (walked at first access),
336/// (2) zshrs daemon-side builtins from `ZSHRS_BUILTIN_NAMES`. Both
337/// arms run once at static init.
338pub(crate) static BUILTIN_NAMES: LazyLock<HashSet<String>> = LazyLock::new(|| {
339 let mut s: HashSet<String> = HashSet::new();
340 // Walk the canonical `BUILTINS` table — the 1:1 port of
341 // `static struct builtin builtins[]` at `Src/builtin.c:40-137`
342 // (ported at `src/ported/builtin.rs:122`). Every name in there is
343 // a real zsh builtin; the set stays in sync as new ports land.
344 for b in crate::ported::builtin::BUILTINS.iter() {
345 s.insert(b.node.nam.clone());
346 }
347 // Daemon-side (zshrs-specific extensions).
348 for &n in crate::daemon::builtins::ZSHRS_BUILTIN_NAMES.iter() {
349 s.insert(n.to_string());
350 }
351 s
352});
353
354use crate::exec_jobs::{JobState, JobTable};
355use crate::parse::{Redirect, RedirectOp, ShellCommand, ShellWord, VarModifier, ZshParamFlag};
356use indexmap::IndexMap;
357use std::collections::HashMap;
358use std::env;
359use std::fs::{File, OpenOptions};
360use std::io;
361use std::path::{Path, PathBuf};
362use std::process::{Child, Command, Stdio};
363
364// Re-exports for call-sites that reference `crate::ported::exec::<Name>`.
365pub use crate::bash_complete::CompSpec;
366pub use crate::ported::builtin::AutoloadFlags;
367pub use crate::ported::modules::zutil::zstyle_entry;
368
369/// One inline-assignment scope (`X=foo Y=bar cmd`).
370///
371/// `saved` holds `(name, prev_var, prev_env)` for each name the
372/// PREFIX assignments touched, so END_INLINE_ENV can put the shell
373/// var and the process env back.
374///
375/// `recording` is what keeps the frame from swallowing assignments
376/// the *command itself* performs. zsh's `addvars()` (Src/exec.c:4142)
377/// walks only the parsed WC_ASSIGN chain, and `save_params`
378/// (Src/exec.c:4410) snapshots only those names; once the command
379/// runs, the save list is closed. The bytecode emits the prefix
380/// assignments between BEGIN_INLINE_ENV and SEAL_INLINE_ENV, and
381/// SEAL clears this flag, so `X=y . file` no longer records (and
382/// then reverts) every global the sourced file assigns.
383pub struct InlineEnvFrame {
384 /// Per-name pre-assignment state, one entry per prefix assignment.
385 pub saved: Vec<SavedInlineParam>,
386 /// True only while the prefix assignments are being executed.
387 pub recording: bool,
388 /// C's `ADDVAR_EXPORT` bit for this command (c:Src/exec.c:37), decided
389 /// where C decides it: `if (is_shfunc) flags |= ADDVAR_EXPORT`
390 /// (c:Src/exec.c:4142-4143), under the comment "Export this if the
391 /// command is a shell function, but not if it's a builtin"
392 /// (c:4138-4140). `addvars` reads it to run the prefix assignment with
393 /// `opts[ALLEXPORT]` forced on (c:2646-2651), which is what makes
394 /// `X=y shellfn` leave `X` marked exported for the duration of the
395 /// call while `X=y builtin` does not.
396 pub export: bool,
397}
398
399/// One parameter a prefix assignment displaced — the Rust twin of the
400/// `tpm` that C's `save_params` builds with
401/// `copyparam(tpm, pm, 0)` (c:Src/exec.c:4491-4493).
402pub struct SavedInlineParam {
403 /// The assigned name (C's `s`, c:Src/exec.c:4475).
404 pub name: String,
405 /// The WHOLE pre-assignment `Param` — type flags, base, width, level
406 /// and the value union, with the value read back through the type's
407 /// GSU getfn exactly as `copyparam` does (c:Src/params.c:1273-1291).
408 /// `None` when the name did not exist, which is C's remove-only arm
409 /// at c:Src/exec.c:4507-4508.
410 pub pm: Option<crate::ported::zsh_h::param>,
411 /// !!! RUST-ONLY FIELD — THE SECOND HALF OF c:Src/params.c:1289 !!!
412 /// C's `copyparam` copies an association's pairs into `tpm->u.hash`,
413 /// so they travel inside the `Param` above. zshrs keeps them in the
414 /// name-keyed `paramtab_hashed_storage` instead, OUTSIDE the `Param`
415 /// (the structural mismatch `stdunsetfn` documents at
416 /// params.rs:11044), so the pairs must be carried — and restored —
417 /// alongside the node rather than within it.
418 pub hashed: Option<IndexMap<String, String>>,
419 /// Pre-assignment `environ` entry for the name.
420 pub prev_env: Option<String>,
421}
422
423impl InlineEnvFrame {
424 /// New frame, open for recording until SEAL_INLINE_ENV runs.
425 pub fn new() -> Self {
426 Self {
427 saved: Vec::new(),
428 recording: true,
429 // c:4141 `int flags = 0;` — BEGIN_INLINE_ENV sets the
430 // ADDVAR_EXPORT bit once it has resolved the command word.
431 export: false,
432 }
433 }
434
435 /// Put every displaced parameter back — the frame's half of
436 /// `restore_params` (c:Src/exec.c:4519), run when the prefixed
437 /// command returns.
438 ///
439 /// Saves are pushed as the prefix assignments execute, so a name
440 /// assigned twice (`X=1 X=2 cmd`) has its ORIGINAL in the first
441 /// entry; walking in reverse makes that the last write, which is
442 /// what C's single pre-`addvars` snapshot achieves.
443 pub fn restore(self) {
444 for saved in self.saved.into_iter().rev() {
445 // c:4525-4531 (remove the temporary parameter) followed by
446 // c:4533-4570 (put the saved one back). C's `remove_p` carries
447 // the name in BOTH arms of `save_params` (c:4504 runs whether or
448 // not a `tpm` was made), so the name is always in the remove
449 // list and the restore list holds the snapshot only if there was
450 // one.
451 crate::ported::exec::restore_params(
452 saved.pm.into_iter().collect(),
453 vec![saved.name.clone()],
454 );
455 // !!! RUST-ONLY — see `SavedInlineParam::hashed` !!!
456 // c:4561's `tpm->gsu.h->setfn(tpm, pm->u.hash)` in zshrs terms.
457 // Unconditional: when nothing was saved the row must be gone, or
458 // the pairs the command itself wrote would outlive the frame.
459 if let Ok(mut store) = crate::ported::params::paramtab_hashed_storage().lock() {
460 match saved.hashed {
461 Some(pairs) => {
462 store.insert(saved.name.clone(), pairs);
463 }
464 None => {
465 store.remove(saved.name.as_str());
466 }
467 }
468 }
469 // c:4568-4569 — `if ((pm->node.flags & PM_EXPORTED) && ...)
470 // addenv(pm, s);`. zshrs's prefix-assignment path publishes the
471 // value with `zputenv` on the way in, so the way out is the
472 // matching restore of the pre-assignment `environ` entry.
473 match saved.prev_env {
474 Some(v) => std::env::set_var(&saved.name, &v),
475 None => std::env::remove_var(&saved.name),
476 }
477 }
478 }
479}
480
481impl Default for InlineEnvFrame {
482 fn default() -> Self {
483 Self::new()
484 }
485}
486
487/// Snapshot of subshell-isolated state. Captured at `(` entry, restored at
488/// `)` exit. zsh subshell semantics: assignments inside `(…)` don't leak to
489/// the outer scope — and that includes `export`. zsh forks a child for the
490/// subshell so the child's env::set_var dies with the child; without a fork
491/// (zshrs runs subshells in-process for perf), we snapshot+restore the OS
492/// env table around the subshell. Otherwise `(export y=v)` would leak `y`
493/// to the parent shell, breaking every script that uses a subshell to
494/// scope an env override.
495/// Snapshot of mutable executor state across a subshell
496/// boundary.
497/// Port of the `entersubsh()` save/restore Src/exec.c does at
498/// line 1084 — captures everything that must be replaced when a
499/// `(...)` group fires.
500pub struct SubshellSnapshot {
501 /// Snapshot of `paramtab` (the C-canonical parameter store) at
502 /// subshell entry. Step 1 of the unification mirrors writes to
503 /// paramtab, so subshell-scoped assignments now show up there
504 /// too — without this snapshot, restoring only `variables` /
505 /// `arrays` / `assoc_arrays` leaks the subshell's writes to the
506 /// parent via paramtab (e.g. `x=outer; (x=inner); echo $x` returned
507 /// `inner` because paramsubst reads through paramtab).
508 /// Same node storage as the live table (`Src/params.c:854`
509 /// `newparamtable(151, "paramtab")`) so restoring a snapshot restores
510 /// C's bucket-walk order too, not just the name→value mapping.
511 pub paramtab: crate::ported::hashtable::hashtable_nodes<crate::ported::zsh_h::Param>,
512 /// `paramtab_hashed_storage` field.
513 pub paramtab_hashed_storage: crate::cow_map::CowHashMap<String, IndexMap<String, String>>,
514 /// `positional_params` field.
515 pub positional_params: Vec<String>,
516 /// Values of the special parameters whose backing store is a process
517 /// GLOBAL rather than the parameter table — `Src/params.c`'s `char *ifs`
518 /// (IFS), `wordchars`, `home`, `histsiz`, … — each reached through a GSU
519 /// getfn/setfn pair (the dispatch list at params.rs:12548).
520 ///
521 /// The `paramtab` snapshot above restores the param NODE, but the node only
522 /// carries the GSU pair; the value itself lives in the global, which a
523 /// paramtab restore doesn't touch. C forks for `(...)`, so a child's writes
524 /// to those globals die with it. zshrs runs subshells in-process, so
525 /// `(IFS=,; :)` left the PARENT's IFS as `,` — and every later word-split
526 /// in the parent silently used it. Same fork-copy reasoning as `opts`
527 /// and `tables`.
528 pub special_globals: Vec<(String, String)>,
529 /// Flock fds (`Src/utils.c:2111` `addlockfd`) live at subshell
530 /// entry. `zsystem flock FILE` keeps the fd open for the life of
531 /// the shell; under C's forked `(...)` the child's fd — and hence
532 /// the lock — dies when the subshell exits. zshrs runs subshells
533 /// in-process, so the lock outlived the subshell and every later
534 /// `zsystem flock` on that file (from a real forked background job)
535 /// blocked forever. Recorded here so `subshell_end` can close the
536 /// fds the subshell itself opened.
537 pub flock_fds: Vec<i32>,
538 /// `loops` / `breaks` / `contflag` at subshell entry
539 /// (c:Src/loop.c, c:Src/builtin.c bin_break). C forks for `(...)`,
540 /// so a `break` executed inside dies with the child and the parent's
541 /// loop runs on: `for i in 1 2; do (break); print after; done` prints
542 /// `after` twice. zshrs runs subshells in-process, so the three
543 /// counters have to be restored by hand at the boundary.
544 /// Fourth slot: `ancestor_loops` (c:Src/loop.c:36), which entry moves
545 /// `loops` into (c:Src/exec.c:1263-1264, 55061).
546 pub loop_flags: (i32, i32, i32, i32),
547 /// `cmdoutval` (c:Src/exec.c:225) at subshell entry. A process global
548 /// the forked child owns a private copy of: `x=$(exit 3); (y=1); exec
549 /// 3>f` still reports 3 in zsh although the subshell's assignment reset
550 /// its own copy (c:2796). Restored by hand like `loop_flags`.
551 pub cmdoutval: i32,
552 /// `stopmsg` (c:Src/builtin.c) at subshell entry. Another process
553 /// global the child owns a copy of: a nofork `${ exit N }` in a
554 /// subshell sets it (c:Src/subst.c:2100) and the child then exits, so
555 /// in C it never reaches the parent. Leaked here it made every later
556 /// `exit` in a function or nofork skip its deferral (c:5884).
557 pub stopmsg: i32,
558 /// Parent's traps at subshell entry. zsh's `(trap "echo X" EXIT;
559 /// true)` runs the trap when the subshell exits — BEFORE the parent
560 /// continues. Without this snapshot, the trap inherited from parent
561 /// would fire, OR a trap set inside the subshell would leak to the
562 /// parent's process exit. Restored on subshell_end after the
563 /// subshell's own EXIT trap (if any) has fired. Stores a snapshot
564 /// of `crate::ported::builtin::traps_table()` (canonical).
565 pub traps: HashMap<String, String>,
566 /// Parent's shell options at subshell entry. `(set -e)` /
567 /// `(setopt extendedglob)` mustn't leak; zsh forks the subshell
568 /// so child options die with the child. We run in-process, so we
569 /// must restore the option store on subshell_end.
570 pub opts: HashMap<String, bool>,
571 /// The fork-copied hash tables — `aliastab`, `sufaliastab`, … — at
572 /// subshell entry (see `crate::ported::exec::SubshForkCopy`). zsh forks
573 /// for `(...)` so `(alias x=y)` inside a subshell dies with the child
574 /// and doesn't leak to the parent. Bug #209 in docs/BUGS.md. The
575 /// tables are restored whole — node flags (ALIAS_GLOBAL / DISABLED)
576 /// and bucket order included — which the `(name, text, flags)` list
577 /// this replaced got only partly right, and it never covered
578 /// `sufaliastab` at all: `(alias -s x=y)` leaked.
579 pub tables: crate::ported::exec::SubshForkCopy,
580 /// Parent's shell-function table at subshell entry. C zsh's
581 /// `entersubsh` (`Src/exec.c`) forks before running the
582 /// subshell body so `(f() { ... })` defining a function dies
583 /// with the child and never leaks to the parent. zshrs runs
584 /// subshells in-process, so we must clone `shfunctab` on entry
585 /// and restore on exit. Bug #208 in docs/BUGS.md. Stored as a
586 /// clone of the whole `shfunc_table` — the bucket layout is part
587 /// of the state, because `${(k)functions}` / `compadd -k functions`
588 /// emit C's bucket-walk order verbatim
589 /// (`Src/Modules/parameter.c:480-481`); rebuilding the table from
590 /// an unordered map on restore would reshuffle that order after
591 /// every `( … )` / `$( … )`.
592 pub shfuncs: std::sync::Arc<crate::ported::hashtable::shfunc_table>,
593 /// Parent's compiled-function chunks at subshell entry. Companion
594 /// to `shfuncs` above — `ShellExecutor.functions_compiled` is the
595 /// runtime dispatch table that `Op::CallFunction` reads through;
596 /// without restoring it, a subshell `(g() { override; })` leaves
597 /// the override bytecode chunk in place so the parent's
598 /// `g` call still runs the override after `subshell_end`
599 /// restored shfunctab. Bug #208 in docs/BUGS.md.
600 ///
601 /// Copy-on-write (`crate::cow_map`): taking this snapshot is a
602 /// refcount bump, and the deep copy happens only if the subshell
603 /// body actually compiles or redefines a function.
604 pub functions_compiled: crate::cow_map::CowHashMap<String, fusevm::Chunk>,
605 /// Parent's function source map at subshell entry. Companion to
606 /// `functions_compiled` so `typeset -f` / `whence` show the
607 /// parent's source after subshell exit, not the subshell's
608 /// overridden body. Bug #208 in docs/BUGS.md.
609 ///
610 /// Copy-on-write, for the same reason as `functions_compiled`.
611 pub function_source: crate::cow_map::CowHashMap<String, String>,
612 /// Parent's THINGYTAB (ZLE widget registry) at subshell entry.
613 /// zsh forks for `(...)` so `zle -N w f` / `zle -D w` inside the
614 /// subshell flip widget bindings only in the child; when the
615 /// child exits the parent's widget table is untouched. zshrs runs
616 /// subshells in-process so a subshell's `zle -D w` would
617 /// otherwise unbind the parent's widget. Bug #453 in docs/BUGS.md.
618 pub thingytab: HashMap<String, crate::ported::zle::zle_thingy::Thingy>,
619 /// Parent's KEYMAPNAMTAB (named keymap registry) at subshell
620 /// entry. Same fork-copy semantics as THINGYTAB — a subshell's
621 /// `bindkey -N km` / `bindkey -D km` mutates only the child's
622 /// keymap registry in C zsh. Bug #454 in docs/BUGS.md.
623 pub keymapnamtab:
624 crate::ported::hashtable::hashtable_nodes<crate::ported::zle::zle_keymap::KeymapName>,
625 /// Parent's `$!` (clone::lastpid) at subshell entry. C zsh forks
626 /// for `(...)`, so a background job started INSIDE the subshell
627 /// sets the child's `lastpid` only — `( : & ); echo $!` prints 0
628 /// in zsh. zshrs runs subshells in-process, so restore on end.
629 pub lastpid: i32,
630 /// Job-control state at subshell entry: (JOBTAB clone, CURJOB,
631 /// PREVJOB, MAXJOB, THISJOB). C zsh forks for `(...)` so any
632 /// `disown` / `wait` / new `&` job inside the subshell mutates the
633 /// CHILD's copy of jobtab and dies with it (Src/exec.c::entersubsh
634 /// fork semantics); the parent's table is untouched. zshrs's
635 /// in-process subshell must snapshot/restore to match — without
636 /// this, `sleep 1 & (disown); jobs` shows an empty table where
637 /// zsh still lists the job. Bug #462.
638 pub jobtab: Vec<crate::ported::zsh_h::job>,
639 /// `curjob` at subshell entry (Src/jobs.c:75 global).
640 pub curjob: i32,
641 /// `prevjob` at subshell entry (Src/jobs.c:80 global).
642 pub prevjob: i32,
643 /// `maxjob` at subshell entry (Src/jobs.c:71 global).
644 pub maxjob: usize,
645 /// `thisjob` at subshell entry (Src/jobs.c:77 global).
646 pub thisjob: i32,
647 /// `oldjobtab` / `oldmaxjob` at subshell entry (Src/jobs.c:101/104).
648 /// The subshell's `clearjobtab` (c:1808-1825) saves the parent's jobs
649 /// there; in C that copy lives in the forked child only, so the
650 /// parent's own `oldjobtab` must come back unchanged or its `jobs`,
651 /// `$jobstates` and `disown` would read the dead subshell's snapshot.
652 pub oldjobtab: Vec<crate::ported::zsh_h::job>,
653 pub oldmaxjob: usize,
654 /// The descriptors 0-9 a bare `exec` redirection in the body moves
655 /// are saved here on first touch and put back when this is dropped
656 /// (see `crate::ported::exec::SubshFdFrame`). C zsh forks for `(...)`
657 /// so the child's `exec >file` / `exec 3<&-` dies with it; without
658 /// this, `(exec >t.log; ...); cat t.log` left the PARENT's fd 1
659 /// pointing at t.log and `cat` looped forever copying the file into
660 /// itself.
661 pub fd_frame: crate::ported::exec::SubshFdFrame,
662 /// `redirect_scope_stack` depth at entry. A body aborted by an error
663 /// skips its `WithRedirectsEnd`; C's forked child takes those fds with
664 /// it, so subshell_end unwinds to here.
665 pub redir_depth: usize,
666 /// Pipeline job slots held at entry (`exec_jobs::execpline_slots_mark`).
667 /// Slots the body takes come from the cleared child table, so
668 /// subshell_end drops their records along with that table.
669 pub slots_mark: usize,
670 /// `sigtrapped[]` at subshell entry (Src/signals.c:39). C's
671 /// `entersubsh` clears per-signal trap STATE via `unsettrap(sig)`
672 /// (c:Src/exec.c:1088-1092), which zeroes both the body and the
673 /// sigtrapped flags. zshrs cleared only the body table, so the flags
674 /// desynced: a subshell that dropped a trap body still reported the
675 /// signal as trapped. Snapshot the whole vector so subshell_end can
676 /// restore the parent's exact state (including an inherited
677 /// ZSIG_IGNORED on SIGQUIT).
678 pub sigtrapped: Vec<i32>,
679 /// `subsh` at subshell entry (Src/exec.c:160 global). C's
680 /// `entersubsh` sets `subsh = 1` for a real (non-ESUB_FAKE)
681 /// subshell at c:Src/exec.c:1192-1193, and the forked child
682 /// carries it for the whole body. PRINT_EXIT_VALUE reads it
683 /// (c:4309 `&& !subsh`), which is why zsh prints nothing for
684 /// `setopt printexitvalue; (false)` while still reporting a
685 /// bare `false`. zshrs runs `( … )` in-process, so the flag has
686 /// to be set on entry and restored by hand on End.
687 pub subsh: i32,
688 /// The libc locale on entry, as `setlocale(LC_ALL, NULL)` reports it.
689 /// `LC_ALL=C` / `LANG=…` / `LC_CTYPE=…` inside the body reach libc via
690 /// `setlang` / `lcsetfn` (c:Src/params.c:4811, c:4877), which in C
691 /// changes only the forked child. The paramtab restore puts the
692 /// parameters back without re-running their setfns, so the parent kept
693 /// the child's locale: `() { (LC_ALL=C; true) }` left `${(q+)…}` quoting
694 /// multibyte text as raw bytes for the rest of the script.
695 pub locale: Option<std::ffi::CString>,
696}
697
698/// !!! WARNING: RUST-ONLY !!! C forks `( … )` and `$( … )`, so a locale the
699/// body sets dies with the child. zshrs runs both in-process; this records
700/// the parent's libc locale on entry for `subsh_locale_restore`.
701pub(crate) fn subsh_locale_save() -> Option<std::ffi::CString> {
702 let cur = unsafe { libc::setlocale(libc::LC_ALL, std::ptr::null()) };
703 (!cur.is_null()).then(|| unsafe { std::ffi::CStr::from_ptr(cur) }.to_owned())
704}
705
706/// !!! WARNING: RUST-ONLY !!! Put back the locale `subsh_locale_save`
707/// recorded, if the body changed it, and redo what the locale setfns do after
708/// `setlocale` (c:Src/params.c:4841 `clear_mbstate()`, c:4842 `inittyptab()`).
709/// Call it after the paramtab restore: inittyptab reads $IFS. The typtab is
710/// rebuilt only when the locale differs, so an ordinary subshell does not
711/// rewrite the table concurrent lexers read.
712pub(crate) fn subsh_locale_restore(saved: Option<&std::ffi::CStr>) {
713 let Some(loc) = saved else { return };
714 let cur = unsafe { libc::setlocale(libc::LC_ALL, std::ptr::null()) };
715 if !cur.is_null() && unsafe { std::ffi::CStr::from_ptr(cur) } == loc {
716 return;
717 }
718 unsafe { libc::setlocale(libc::LC_ALL, loc.as_ptr()) };
719 crate::ported::params::clear_mbstate();
720 crate::ported::utils::inittyptab();
721}
722
723#[allow(unused_imports)]
724pub(crate) use crate::ported::pattern::{
725 extract_numeric_ranges, numeric_range_contains, numeric_ranges_to_star,
726};
727
728/// Top-level shell executor state.
729/// Fork-equivalent event counter — incremented on every external
730/// spawn and in-process subshell entry. C zsh's `time` keyword
731/// reports only for JOBS (forked work, Src/jobs.c printtime via the
732/// job table); zshrs runs builtins/braces/functions in-process with
733/// no job, so the TIME_SUBLIST handler compares this counter across
734/// the timed body to decide whether to emit the report.
735pub static FORK_EVENTS: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(0);
736
737/// Port of the file-static globals + `Estate` chain Src/exec.c
738/// uses — `execlist()` (line 1349) drives every list, with
739/// `execpline()` (line 1668), `execpline2()` (line 1991),
740/// `execsimple()` (line 1290), and the per-`WC_*` `execfuncs[]`
741/// table (line 268) feeding off it. The Rust port collapses
742/// everything into one `ShellExecutor` so we don't need
743/// thread-local globals.
744pub struct ShellExecutor {
745 /// Mirrors C zsh's file-static `scriptname` (Src/init.c). Used by
746 /// PS4's `%N` and the `scriptname:line: …` prefix on error
747 /// messages. Inside a function, MUTATES to the function name
748 /// (Src/exec.c:5903 `scriptname = dupstring(name)`). Init sets
749 /// this in `-c` mode to the binary basename per init.c:479; when
750 /// sourcing a file via `source`/`bin_dot`, it becomes the
751 /// resolved file path; otherwise it falls back through `$0` →
752 /// `$ZSH_ARGZERO`.
753 pub scriptname: Option<String>,
754 /// Mirrors C zsh's `scriptfilename` global (Src/init.c). Tracks
755 /// the FILE BEING READ (vs scriptname which tracks the active
756 /// function name during a call). Used by PS4's `%x` and certain
757 /// error-message prefixes that want the file location, NOT the
758 /// function name.
759 ///
760 /// At -c-mode init, scriptname == scriptfilename == "zsh"
761 /// (Src/init.c:479). When entering a function, ONLY scriptname
762 /// updates (exec.c:5903); scriptfilename stays at the outer
763 /// file path, so `%x` inside a function still shows the file
764 /// the function was called from.
765 pub scriptfilename: Option<String>,
766 /// Stack of subshell-state snapshots. Each `(…)` subshell pushes a copy
767 /// of variables/arrays/assoc_arrays at entry and pops/restores at exit.
768 /// Without this, `(x=inner; …); echo $x` shows `inner` instead of the
769 /// outer-scope value.
770 pub subshell_snapshots: Vec<SubshellSnapshot>,
771 /// Stack of inline-assignment scopes — `X=foo Y=bar cmd` pushes
772 /// a frame at the start, the assigns run inside it, and `cmd`
773 /// returns into END_INLINE_ENV which restores both shell-vars
774 /// and process-env to the pre-frame state. Each frame holds
775 /// `(name, prev_var, prev_env)` per assigned name. zsh's
776 /// equivalent is the parser-level "addvar" list executed under
777 /// `addvars()` (Src/exec.c) right before the command exec.
778 pub inline_env_stack: Vec<InlineEnvFrame>,
779 /// Set by `expand_glob`'s no-match arm when `nomatch` is on (zsh
780 /// default) — instructs the simple-command dispatcher to skip
781 /// executing the current command, set last_status=1, and continue
782 /// to the next command in the script. zsh's bin_simple uses the
783 /// errflag global for the same role: error printed, command
784 /// suppressed, script continues. Without this we were calling
785 /// `process::exit(1)` deep inside expand_glob, killing the whole
786 /// shell on any unmatched glob even with multi-statement input.
787 /// `Cell` because the no-match site only has a `&self` borrow.
788 pub current_command_glob_failed: std::cell::Cell<bool>,
789 /// `jobs` field.
790 pub jobs: JobTable,
791 /// `fpath` field.
792 pub fpath: Vec<PathBuf>,
793 /// SQLite history index, opened on FIRST USE rather than at startup.
794 ///
795 /// Only `--doctor`, the cache report and `dbview history` read it, and
796 /// none of them runs on a script or `-c` invocation — but opening it
797 /// eagerly cost every `zshrs script.zsh` an sqlite open plus
798 /// `init_schema` (0.40 ms of a 1.75 ms startup, measured with
799 /// `ZSHRS_STARTUP_TRACE`). A pre-filled `None` is how a pool worker
800 /// declares it must never open one.
801 pub history: std::cell::OnceCell<Option<HistoryEngine>>,
802 pub(crate) process_sub_counter: u32,
803 pub completions: HashMap<String, CompSpec>, // command -> completion spec
804 pub zstyles: Vec<zstyle_entry>, // zstyle configurations
805 /// Current function scope depth for `local` tracking.
806 pub local_scope_depth: usize,
807 /// Last arg of the currently-running command, deferred into `$_`
808 /// when the next command dispatches. zsh: `$_` reflects the LAST
809 /// command's last arg, so `echo hi; echo $_` prints `hi` (not the
810 /// `_` arg of `echo $_` itself). Promoted in `pop_args` and
811 /// `host.exec` before the command's args are read.
812 pub pending_underscore: Option<String>,
813 /// True while expanding inside a double-quoted context. Set by
814 /// `BUILTIN_EXPAND_TEXT` mode 1 around `expand_string` calls.
815 /// Used by parameter-flag application to suppress array-only flags
816 /// (`(o)`/`(O)`/`(n)`/`(i)`/`(M)`/`(u)`) — zsh's behaviour: those
817 /// flags only fire in array context.
818 pub in_dq_context: u32,
819 /// True (>0) while expanding the RHS of a scalar assignment.
820 /// Direct port of zsh's `PREFORK_SINGLE` bit set by
821 /// Src/exec.c::addvars line 2546 (`prefork(vl, isstr ?
822 /// (PREFORK_SINGLE|PREFORK_ASSIGN) : PREFORK_ASSIGN, ...)`).
823 /// Subst_port's paramsubst reads this via `ssub` and suppresses
824 /// `(f)` / `(s:STR:)` / `(0)` / `(z)` split flags per
825 /// Src/subst.c:1759 + 3902, so `y="${(f)x}"` preserves x's
826 /// original separator (newlines) instead of re-joining with
827 /// IFS-first-char (space).
828 pub in_scalar_assign: u32,
829 /// `profiling_enabled` field.
830 pub profiling_enabled: bool,
831 // compsys - completion system cache
832 /// `compsys_cache` field.
833 /// SQLite mirror, opened on FIRST USE via [`ShellExecutor::compsys_cache`].
834 ///
835 /// It is a dbview/FTS mirror for inspection — the authoritative completion
836 /// cache is the rkyv shards — so nothing on a normal command path touches
837 /// it. Opening it in the constructor still cost every shell three file
838 /// opens (`compsys.db`, `-wal`, `-shm`) plus WAL setup, including
839 /// `zshrs -f -c exit`, which cannot consult it at all.
840 pub compsys_cache: std::cell::OnceCell<Option<CompsysCache>>,
841 // Background compinit — receiver for async fpath scan result
842 /// `compinit_pending` field.
843 pub compinit_pending: Option<(
844 std::sync::mpsc::Receiver<CompInitBgResult>,
845 std::time::Instant,
846 )>,
847 // Plugin source cache — stores side effects of source/. in SQLite
848 /// `plugin_cache` field.
849 pub plugin_cache: Option<crate::plugin_cache::PluginCache>,
850 // cdreplay - deferred compdef calls for zinit turbo mode
851 /// `deferred_compdefs` field.
852 pub deferred_compdefs: Vec<Vec<String>>,
853 // Control flow signals
854 pub returning: Option<i32>, // Set by return builtin, cleared after function returns
855 /// zsh compatibility mode - use .zcompdump, fpath scanning, etc.
856 /// Also serves as the `--zsh` parity-test flag: caches off, daemon
857 /// off, plugin_cache replay off so every `source` re-runs the file
858 /// fresh per Src/builtin.c:6080-6123 bin_dot semantics.
859 pub zsh_compat: bool,
860 /// bash compatibility mode (`--bash`). Same parity-mode semantics
861 /// as `zsh_compat` (caches/daemon/replay off) plus bash-specific
862 /// behavior tweaks where bash 5.x diverges from zsh — e.g.
863 /// `BASH_VERSION` / `BASH_REMATCH` exposed, `[[ =~ ]]` populates
864 /// match indices the bash way, mapfile/readarray as builtins.
865 pub bash_compat: bool,
866 /// POSIX sh strict mode — no SQLite, no worker pool, no zsh extensions
867 pub posix_mode: bool,
868 /// Worker thread pool for background tasks (compinit, process subs, etc.)
869 pub worker_pool: std::sync::Arc<crate::worker::WorkerPool>,
870 /// AOP intercept table: command/function name → advice chain.
871 /// Glob patterns supported (e.g. "git *", "*").
872 pub intercepts: Vec<Intercept>,
873 /// Async job handles: id → receiver for (status, stdout)
874 pub async_jobs: HashMap<u32, crossbeam_channel::Receiver<(i32, String)>>,
875 /// Next async job ID
876 pub next_async_id: u32,
877 /// Per-scope saved-fd stacks for `Op::WithRedirectsBegin/End`. Each entry
878 /// is a Vec of (fd, saved_dup_fd) pairs taken from `dup(fd)` before the
879 /// redirect was applied; `with_redirects_end` `dup2`s them back and closes.
880 pub redirect_scope_stack: Vec<Vec<(i32, i32)>>,
881 /// Per-scope MULTIOS tee state. Each entry is `(pipe_write_fd,
882 /// JoinHandle)`: the pipe write-end currently dup2'd onto the
883 /// command's fd, and the splitter thread that reads from the
884 /// pipe read-end and writes to every collected target. Closed
885 /// + joined by `host_redirect_scope_end` BEFORE the saved fds
886 /// are restored so the splitter drains every byte the body
887 /// wrote into the pipe. Bug #36 in docs/BUGS.md.
888 pub multios_scope_stack: Vec<Vec<(i32, std::thread::JoinHandle<()>)>>,
889 /// True while applying a bare `exec`'s redirect list (`exec 1>&-`,
890 /// `exec 2>/dev/null` — no command words). `host_apply_redirect`
891 /// then skips pushing the saved fd into the enclosing scope so the
892 /// fd change survives group/command teardown.
893 /// c:Src/exec.c:3978-3986 — nullexec==1: "we specifically *don't*
894 /// restore the original fd's before returning"; C's per-execcmd
895 /// `save[]` means exec's redirs never enter the enclosing group's
896 /// save list either. Toggled by `BUILTIN_EXEC_PERM_REDIRS`.
897 pub exec_redirs_permanent: bool,
898 /// Set in a forked pipeline-stage child right after its stdout is
899 /// dup2'd onto the pipe write-end. Consumed by the FIRST
900 /// `host_redirect_scope_begin` (the stage command's own redirect
901 /// list) into `pipe_output_scope`.
902 /// c:Src/exec.c:3722-3724 — `addfd(forked, save, mfds, 1, output,
903 /// 1, NULL)`: the pipe occupies mfds[1] in the SAME execcmd that
904 /// processes the stage command's redirect list.
905 pub pipe_output_pending: bool,
906 /// Index into `redirect_scope_stack` of the scope whose redirect
907 /// list shares an execcmd with the pipeline output on fd 1. A
908 /// write-side redirect of fd 1 applied at exactly this scope depth
909 /// MULTIOS-splits (tees) instead of replacing — c:Src/exec.c:
910 /// 2447-2480 addfd "split the stream". Cleared when that scope ends.
911 pub pipe_output_scope: Option<usize>,
912 /// Set by `host_apply_redirect` when a redirect target couldn't be
913 /// opened (permission denied, no such directory, etc). The next
914 /// builtin/command checks this at entry and short-circuits with
915 /// status 1 instead of running. Mirrors zsh's "command skip" on
916 /// redirect failure.
917 pub redirect_failed: bool,
918 /// Compiled function bodies — name → fusevm::Chunk. Populated by
919 /// `BUILTIN_REGISTER_FUNCTION` (from `FunctionDef` lowering) and lazily by
920 /// `ZshrsHost::call_function` when only an AST exists in `self.functions`
921 /// (autoloaded, sourced, etc.). `Op::CallFunction` dispatches through here.
922 ///
923 /// COPY-ON-WRITE. `$( … )` and `( … )` snapshot this whole map for
924 /// subshell isolation (Bug #208), so a plain `HashMap` made entering
925 /// a substitution cost one `Chunk` clone per compiled function. It
926 /// is a `CowHashMap`, so the snapshot shares and the first write
927 /// inside the body splits. Reads and writes are unchanged —
928 /// `Deref`/`DerefMut` keep every call site as it was.
929 pub functions_compiled: crate::cow_map::CowHashMap<String, fusevm::Chunk>,
930 /// Canonical source text for functions. Populated by autoload paths (the
931 /// raw file/cache body), runtime FuncDef compile (the parsed source span),
932 /// and `unfunction` removal. Used by introspection (`whence`, `which`,
933 /// `typeset -f`) instead of reconstructing from a ShellCommand AST. When a
934 /// function is in `functions_compiled` but not here, introspection falls
935 /// back to `text::getpermtext(self.functions[name])`.
936 ///
937 /// Copy-on-write for the same reason as `functions_compiled`: a
938 /// subshell snapshots it whole, and the body usually never writes.
939 pub function_source: crate::cow_map::CowHashMap<String, String>,
940 /// `first_body_line - 1` per compiled function — matches inner
941 /// `ZshCompiler::lineno_offset` / zsh `funcstack->flineno` combined with
942 /// relative `$LINENO` for Src/prompt.c:909 `%I`.
943 pub function_line_base: HashMap<String, i64>,
944 /// `scriptfilename` when `BUILTIN_REGISTER_COMPILED_FN` ran — `%x` inside
945 /// a function (prompt.c:931-934) reads `funcstack->filename`.
946 pub function_def_file: HashMap<String, Option<String>>,
947 /// Innermost-last stack of active compiled-call frames for prompt `%I` / `%x`.
948 pub prompt_funcstack: Vec<(String, i64, Option<String>)>,
949 /// Scalar→(array, sep) tie table set up by `typeset -T VAR var [SEP]`.
950 /// Array→(scalar, sep) reverse-tie table. Used by BUILTIN_SET_ARRAY to
951 /// join the array elements with `sep` and mirror to the scalar side.
952 pub tied_array_to_scalar: HashMap<String, (String, String)>,
953
954 // ── ztest framework counters (extensions/ztest.rs) ──────────────────
955 //
956 // Mirrors strykelang's per-VMHelper test counters
957 // (strykelang/builtins.rs:22292-22308 + builtins.rs::test_pass/_fail/_skip,
958 // builtins.rs::test_pass_count etc.). Each `zassert_*` builtin bumps
959 // the per-block counter; `ztest_run` rolls per-block into _total and
960 // resets the per-block side, so a single test file with multiple
961 // `ztest_run` calls can reuse the counters. The worker-pool runner in
962 // src/extensions/ztest.rs reads pass_total+pass_count and
963 // fail_total+fail_count after `execute_script` returns for the cumulative
964 // numbers (strykelang/cli_runners.rs:115-118). `ztest_run_failed` is a
965 // sticky bool the runner reads so a test that asserts but then exits
966 // 0 still flags as failed. `ztest_suppress_stdout` matches
967 // VMHelper::suppress_stdout — the runner sets it inside the forked
968 // grandchild so the per-test stderr capture stays clean.
969 /// Per-block pass count (reset by `ztest_run`).
970 pub ztest_pass_count: std::sync::atomic::AtomicUsize,
971 /// Per-block fail count (reset by `ztest_run`).
972 pub ztest_fail_count: std::sync::atomic::AtomicUsize,
973 /// Per-block skip count (reset by `ztest_run`).
974 pub ztest_skip_count: std::sync::atomic::AtomicUsize,
975 /// Cumulative pass total across the run.
976 pub ztest_pass_total: std::sync::atomic::AtomicUsize,
977 /// Cumulative fail total across the run.
978 pub ztest_fail_total: std::sync::atomic::AtomicUsize,
979 /// Cumulative skip total across the run.
980 pub ztest_skip_total: std::sync::atomic::AtomicUsize,
981 /// Sticky failure flag — set by any `ztest_run` that observed fails;
982 /// the CLI runner reads this so a test that asserts then exits 0
983 /// still counts as a failed file.
984 pub ztest_run_failed: std::sync::atomic::AtomicBool,
985 /// Suppress per-assertion `✓`/`✗` lines on stderr. Set by the worker
986 /// runner inside the forked child when it has already redirected
987 /// fd 2 to a tmp file (we still want the lines, but only after the
988 /// runner re-emits them under print_lock to avoid line-tearing).
989 pub ztest_suppress_stdout: bool,
990}
991
992/// Context-isolated nested parse — the AST-path bridge for C's
993/// `parse_string` (`Src/exec.c:283`). zshrs executes via the ZshProgram
994/// AST + `compile_zsh`, not wordcode, so this can't live in `src/ported/`
995/// (C's `parse_string` returns `Eprog`, and the build.rs port-gate rejects
996/// any non-C-named fn there). It's the bridge that wraps the AST
997/// `parse_init`+`parse` in the SAME isolation `parse_string` provides.
998///
999/// Why this exists: a runtime parse — command-substitution body,
1000/// process-substitution argv — must not clobber the outer
1001/// `loop()`/`parse_event` reader's live input when it interleaves parsing
1002/// with execution (faithful single-event mode).
1003///
1004/// The load-bearing piece is `strinbeg(0)`/`strinend()` (c:290/298). It
1005/// sets the `strin` flag so that when the nested lexer drains `cmd_str`,
1006/// `ingetc` returns EOF (input.rs:391) instead of falling through to
1007/// `inputline()`, which would STEAL the outer reader's next SHIN line —
1008/// e.g. `echo A` / `v=$(echo hi)` / `echo B` had the cmd-subst swallow
1009/// `echo B` off stdin, and the outer loop then hit EOF after one command.
1010/// `strinbeg` also runs `hbegin`/`lexinit`, so it must execute on isolated
1011/// history+lexer state — hence the surrounding `zcontext_save`/`restore`
1012/// (c:288/300), which saves+restores `tok`/`tokstr`/`lexbuf`/`isnewlin`/
1013/// `incmdpos`/heredocs/`lexstop`/`toklineno`/history.
1014///
1015/// Two zshrs-specific globals `zcontext` doesn't cover are saved here too:
1016/// the lexer-input window (`LEX_INPUT`/`LEX_POS`/`LEX_UNGET_BUF`) that
1017/// `lex_init` overwrites with `cmd_str`, and the line counter `LEX_LINENO`
1018/// (C saves `oldlineno` explicitly at parse_string c:291/295).
1019///
1020/// NOTE: using `inpush` (the literal C input stack) instead does NOT work
1021/// in zshrs's hybrid input model — the outer piped reader pulls from SHIN
1022/// via `inputline`, and pushing/popping the `inbuf` stack severs that
1023/// continuation. The `LEX_INPUT` window + `strin` flag is the working
1024/// equivalent.
1025pub(crate) fn parse_isolated(input: &str) -> crate::parse::ZshProgram {
1026 parse_isolated_at(input, None)
1027}
1028
1029/// `parse_isolated` with C's `reset_lineno` argument inverted: `Some(n)` is
1030/// `parse_string(s, 0)` (c:Src/exec.c:291-293), which parses from the line the
1031/// shell is executing, `n`, instead of from line 1. A parse error in a body
1032/// parsed at run time (`` `…` `` in getoutput c:4778) then carries that line,
1033/// or none at all when it is 0 (c:Src/utils.c:301).
1034pub(crate) fn parse_isolated_at(input: &str, lineno: Option<u64>) -> crate::parse::ZshProgram {
1035 use crate::ported::lex::{
1036 tok, LEXERR, LEX_INPUT, LEX_LINENO, LEX_POS, LEX_UNGET_BUF, LEX_FILE_WINDOW_STRIN,
1037 };
1038
1039 // Inline Rust FFI: rewrite every `rust { ... }` block into a
1040 // `__rust_compile '<base64>' <line>` command before it reaches the lexer.
1041 // This is the shared source-string chokepoint for `-c`, script files, and
1042 // nested (command/process-substitution) parses. The `.contains("rust")`
1043 // gate keeps the common case (no FFI block) allocation-free — the vast
1044 // majority of nested parses never mention `rust`.
1045 let ffi_desugared = input
1046 .contains("rust")
1047 .then(|| crate::rust_ffi::desugar(input));
1048 let input: &str = ffi_desugared.as_deref().unwrap_or(input);
1049
1050 crate::ported::context::zcontext_save(); // c:288
1051 // Save the zshrs-specific lexer window + line counter that lex_init
1052 // overwrites but zcontext doesn't cover.
1053 let saved_input = LEX_INPUT.with_borrow(|s| s.clone());
1054 let saved_pos = LEX_POS.get();
1055 let saved_unget = LEX_UNGET_BUF.with_borrow(|b| b.clone());
1056 let saved_lineno = LEX_LINENO.get(); // c:291 oldlineno
1057 // The nested parse installs its own window; `lex_init` marks it a
1058 // string unit. Put the outer window's kind back with the window.
1059 let saved_file_window = LEX_FILE_WINDOW_STRIN.get();
1060 // input.rs `lexstop` is the input-side half of C's single `lexstop`;
1061 // draining the nested LEX_INPUT sets it true and zcontext only covers
1062 // the lex.rs half (LEX_LEXSTOP). Restore it so the outer reader isn't
1063 // left at EOF.
1064 let saved_in_lexstop = crate::ported::input::lexstop.with(|c| c.get());
1065
1066 // c:Src/exec.c:294 `inpush(s, INP_LINENO, NULL)` — the nested parse
1067 // gets its own input frame, so whatever the OUTER reader still has
1068 // queued is parked on the input stack until the inpop below. The text
1069 // itself is lexed from LEX_INPUT (parse_init), so the pushed frame is
1070 // empty: once that window drains, ingetc hits the end of THIS frame
1071 // and returns EOF. Without the frame it fell through to the outer
1072 // buffer — the rest of a multi-line command line, still unread while
1073 // `preexec` ran an `eval` or `$(…)` — and swallowed it.
1074 crate::ported::input::inpush("", crate::ported::zsh_h::INP_LINENO, None);
1075 crate::ported::hist::strinbeg(0); // c:290 — strin++ → drained nested input EOFs (no SHIN steal)
1076 crate::ported::parse::parse_init(input); // install cmd_str as LEX_INPUT (lex_init), LEX_LINENO=1
1077 if let Some(n) = lineno {
1078 LEX_LINENO.set(n); // c:292 `if (reset_lineno)` not taken: keep the running line
1079 }
1080 let program = crate::ported::parse::parse(); // c:294 (AST analog of par_list)
1081
1082 // Capture parse failure BEFORE the restores wipe the signals.
1083 let parse_err = (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 || tok() == LEXERR;
1084 if tok() == LEXERR && crate::ported::builtin::LASTVAL.load(Ordering::Relaxed) == 0 {
1085 crate::ported::builtin::LASTVAL.store(1, Ordering::Relaxed); // c:296-297
1086 }
1087
1088 crate::ported::hist::strinend(); // c:298 — strin--
1089 // c:Src/exec.c:304 `inpop()` — pops the pushed frame AND its continuations. An
1090 // alias expanded at the end of the body sits on top as an
1091 // INP_ALIAS|INP_CONT frame (c:Src/input.c:695), so this is also where its
1092 // `inuse` is cleared (c:Src/input.c:773): left behind, the alias stayed
1093 // `inuse` and every later `$(m)` / `m` reported "command not found".
1094 // Popping the frame pushed above restores the outer reader's queue.
1095 crate::ported::input::inpop();
1096 // Restore the zshrs window, then the token/parse/history state.
1097 LEX_INPUT.with_borrow_mut(|s| *s = saved_input);
1098 LEX_POS.set(saved_pos);
1099 LEX_UNGET_BUF.with_borrow_mut(|b| *b = saved_unget);
1100 LEX_LINENO.set(saved_lineno); // c:295
1101 LEX_FILE_WINDOW_STRIN.set(saved_file_window);
1102 crate::ported::input::lexstop.with(|c| c.set(saved_in_lexstop));
1103 crate::ported::context::zcontext_restore(); // c:300
1104 // zcontext_restore → parse_context_restore clears ERRFLAG_ERROR
1105 // (parse.c:354); re-raise so callers gating on the bit still see it.
1106 if parse_err {
1107 errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed);
1108 }
1109 program
1110}
1111
1112/// Build the `scriptname[:lineno]` prefix zsh puts on an execution error.
1113///
1114/// c:Src/utils.c:301 — `zerrmsg` prints the line number ONLY when it is
1115/// non-zero: `if ((unset(SHINSTDIN) || locallevel) && lineno) fprintf(file,
1116/// "%lld: ", lineno);`. The command-not-found / no-such-file / permission-denied
1117/// sites below emit DIRECTLY rather than through `zerr` (deliberately — see
1118/// their comments, routing through zerr would set errflag and abort a script
1119/// that zsh continues), but they hand-rolled `"{}:{}"` and so printed a bare
1120/// `:0` inside a one-line function where zsh prints no line number at all:
1121/// `f(){ nosuchcmd }; f` gave `f:0: command not found:` vs zsh's `f: command
1122/// not found:`. Mirrors the C condition exactly. Bug #1070.
1123fn zerr_prefix(sn: &str) -> String {
1124 let lineno = crate::ported::lex::lineno();
1125 let ll = crate::ported::params::locallevel.load(std::sync::atomic::Ordering::Relaxed);
1126 if (crate::ported::zsh_h::unset(crate::ported::zsh_h::SHINSTDIN) || ll != 0) && lineno != 0 {
1127 format!("{}:{}", sn, lineno)
1128 } else {
1129 sn.to_string()
1130 }
1131}
1132
1133thread_local! {
1134 /// `(function name, its source file)` while that function's AUTOLOAD body
1135 /// is being run. Empty at every other moment.
1136 pub static AUTOLOAD_DEF_FILE: std::cell::RefCell<Vec<(String, String)>> =
1137 const { std::cell::RefCell::new(Vec::new()) };
1138}
1139
1140/// Scope guard for [`AUTOLOAD_DEF_FILE`].
1141pub struct AutoloadFileGuard(bool);
1142
1143impl AutoloadFileGuard {
1144 fn enter(name: &str) -> Self {
1145 match crate::ported::hashtable::getshfuncfile(name) {
1146 Some(f) => {
1147 AUTOLOAD_DEF_FILE.with(|s| s.borrow_mut().push((name.to_string(), f)));
1148 Self(true)
1149 }
1150 None => Self(false),
1151 }
1152 }
1153}
1154
1155impl Drop for AutoloadFileGuard {
1156 fn drop(&mut self) {
1157 if self.0 {
1158 AUTOLOAD_DEF_FILE.with(|s| {
1159 s.borrow_mut().pop();
1160 });
1161 }
1162 }
1163}
1164
1165/// The file `name` is being autoloaded from, if that is happening right now.
1166pub fn autoload_def_file(name: &str) -> Option<String> {
1167 AUTOLOAD_DEF_FILE.with(|s| {
1168 s.borrow()
1169 .iter()
1170 .rev()
1171 .find(|(n, _)| n == name)
1172 .map(|(_, f)| f.clone())
1173 })
1174}
1175
1176/// !!! WARNING: RUST-ONLY HELPER — NO DIRECT C COUNTERPART !!!
1177///
1178/// C's `zexecve` (Src/exec.c:504-643) performs the whole `#!` recovery
1179/// in place: it is only ever reached in the already-forked child that is
1180/// about to BECOME the command, so at c:566/571/581/585/627 it simply
1181/// calls `execve()` a second time and never returns. zshrs reaches the
1182/// same decision from a second call site — the `std::process::Command`
1183/// spawn in `vm_helper::execute_external_bg` — which hands argv to the
1184/// kernel from the PARENT process and therefore cannot "re-exec in
1185/// place". This helper is c:534-634 verbatim with each of those five
1186/// `execve(prog, argv)` calls replaced by `Ok((prog, argv))`, so both
1187/// call sites share one implementation of the shebang rules.
1188///
1189/// `Err(eno)` is what C's `return eno` (c:643) would hand back — either
1190/// the original `eno` or the `errno` from a failed open/read (c:632/634).
1191#[allow(non_snake_case)]
1192pub fn zexecve_recover(pth: &str, argv: &[String], eno: i32) -> Result<(String, Vec<String>), i32> {
1193 if eno == libc::ENOEXEC || eno == libc::ENOENT {
1194 // c:534
1195 let cpth = match std::ffi::CString::new(pth) {
1196 Ok(c) => c,
1197 Err(_) => return Err(libc::ENOENT),
1198 };
1199 let fd = unsafe { libc::open(cpth.as_ptr(), libc::O_RDONLY | libc::O_NOCTTY) }; // c:538
1200 if fd < 0 {
1201 // c:633-634 — `} else eno = errno;` then fall through to `return eno`.
1202 return Err(std::io::Error::last_os_error()
1203 .raw_os_error()
1204 .unwrap_or(libc::ENOENT));
1205 }
1206 let mut buf = vec![0u8; crate::ported::exec::POUNDBANGLIMIT + 1]; // c:541
1207 let ct = unsafe {
1208 libc::read(
1209 fd,
1210 buf.as_mut_ptr() as *mut libc::c_void,
1211 crate::ported::exec::POUNDBANGLIMIT as libc::size_t,
1212 )
1213 }; // c:542
1214 unsafe {
1215 libc::close(fd);
1216 } // c:543
1217 if ct >= 0 {
1218 // c:544
1219 let ct = ct as usize;
1220 if ct >= 2 && buf[0] == b'#' && buf[1] == b'!' {
1221 // c:545
1222 let mut t0 = 0;
1223 while t0 < ct && buf[t0] != b'\n' {
1224 t0 += 1;
1225 } // c:546-548
1226 if t0 == ct {
1227 // c:549
1228 // c:550 `zerr(...)`. C is inside the forked child that is
1229 // about to `_exit`, so the errflag `zerr` raises is
1230 // irrelevant there. This runs in the PARENT, where a raised
1231 // errflag aborts the enclosing script — `( if
1232 // bad-interp-cmd; then exit 0; else exit 1; fi )` returned
1233 // 127 instead of running its else branch. `zwarn`
1234 // (utils.rs:260) emits the identical text without the flag.
1235 crate::ported::utils::zwarn(&format!(
1236 // c:550
1237 "{}: bad interpreter: {}: {}",
1238 pth,
1239 String::from_utf8_lossy(&buf[2..t0.min(ct)]),
1240 std::io::Error::from_raw_os_error(eno)
1241 ));
1242 } else {
1243 // c:552
1244 while t0 > 0 && (buf[t0] == b' ' || buf[t0] == b'\t' || buf[t0] == b'\n') {
1245 buf[t0] = 0;
1246 t0 -= 1;
1247 } // c:553-554
1248 let mut ptr_lo: usize = 2;
1249 while ptr_lo < buf.len() && buf[ptr_lo] == b' ' {
1250 ptr_lo += 1;
1251 } // c:555
1252 let ptr2_lo = ptr_lo;
1253 let mut ptr_hi = ptr2_lo;
1254 while ptr_hi < buf.len() && buf[ptr_hi] != 0 && buf[ptr_hi] != b' ' {
1255 ptr_hi += 1;
1256 } // c:556
1257 let interp_str = String::from_utf8_lossy(&buf[ptr2_lo..ptr_hi]).into_owned();
1258 if eno == libc::ENOENT {
1259 // c:557 — pathprog rewrite path.
1260 let pprog = if !interp_str.starts_with('/') {
1261 // c:561
1262 crate::ported::utils::pathprog(&interp_str)
1263 .map(|p| p.display().to_string())
1264 } else {
1265 None
1266 };
1267 if let Some(pprog) = pprog {
1268 // c:562
1269 let mut argv_new: Vec<String> = Vec::with_capacity(argv.len() + 2);
1270 argv_new.push(interp_str.clone()); // c:564
1271 if ptr_hi >= buf.len() || buf[ptr_hi] == 0 {
1272 argv_new.push(pth.to_string());
1273 } else {
1274 // c:567
1275 let mut rest_lo = ptr_hi + 1;
1276 while rest_lo < buf.len() && buf[rest_lo] == b' ' {
1277 rest_lo += 1;
1278 }
1279 let mut rest_hi = rest_lo;
1280 while rest_hi < buf.len() && buf[rest_hi] != 0 {
1281 rest_hi += 1;
1282 }
1283 let arg_str =
1284 String::from_utf8_lossy(&buf[rest_lo..rest_hi]).into_owned();
1285 argv_new.push(arg_str);
1286 argv_new.push(pth.to_string());
1287 }
1288 for orig in argv.iter().skip(1) {
1289 argv_new.push(orig.clone());
1290 }
1291 // c:565/c:570 — `winch_unblock(); execve(...)`.
1292 // Deliberately NOT ported here. In C that unblock is
1293 // the last statement before `execve` in the FORKED
1294 // CHILD, so all it decides is the mask the new
1295 // program starts with; the parent never sees it.
1296 // This resolver runs in the PARENT (see the c:550
1297 // note above) and RETURNS, so calling it dropped the
1298 // shell's standing `winch_block()`
1299 // (c:Src/init.c:1458) with nothing here to re-arm
1300 // it. The next re-arm is whenever `raw_getbyte`
1301 // returns from its read (zle_main.rs:507/654/762),
1302 // so the leak spans the REST OF THE CURRENT COMMAND,
1303 // not the session — and a completer that execs a
1304 // shebang-less script therefore finishes its
1305 // completion with the handler live. That is the one
1306 // state c:1458 exists to prevent: `adjustwinsize(1)`
1307 // inside a widget makes `calclist` count display
1308 // strings against a width they were not built at,
1309 // and repaints over the prompt row.
1310 //
1311 // The new image still gets SIGWINCH unblocked: the
1312 // child-side `zexecve` unblocks at c:527 (ported at
1313 // src/ported/exec.rs:4215), and the spawn-based
1314 // callers of this function go through
1315 // `std::process::Command`, whose child resets the
1316 // signal mask to empty before `execvp`.
1317 return Ok((pprog, argv_new)); // c:566/c:571
1318 }
1319 crate::ported::utils::zwarn(&format!(
1320 // c:574 — `zerr`; see the c:550 note above for why
1321 // this is `zwarn` in the parent-side port.
1322 "{}: bad interpreter: {}: {}",
1323 pth,
1324 interp_str,
1325 std::io::Error::from_raw_os_error(eno)
1326 ));
1327 } else if ptr_hi < buf.len() && buf[ptr_hi] != 0 {
1328 // c:576
1329 let mut rest_lo = ptr_hi + 1;
1330 while rest_lo < buf.len() && buf[rest_lo] == b' ' {
1331 rest_lo += 1;
1332 }
1333 let mut rest_hi = rest_lo;
1334 while rest_hi < buf.len() && buf[rest_hi] != 0 {
1335 rest_hi += 1;
1336 }
1337 let arg_str = String::from_utf8_lossy(&buf[rest_lo..rest_hi]).into_owned();
1338 let mut argv_new: Vec<String> =
1339 vec![interp_str.clone(), arg_str, pth.to_string()];
1340 for orig in argv.iter().skip(1) {
1341 argv_new.push(orig.clone());
1342 }
1343 // c:580 — `winch_unblock()` omitted: child-side in C,
1344 // parent-side here. See the c:565/c:570 note above.
1345 return Ok((interp_str, argv_new)); // c:581
1346 } else {
1347 // c:582
1348 let mut argv_new: Vec<String> = vec![interp_str.clone(), pth.to_string()];
1349 for orig in argv.iter().skip(1) {
1350 argv_new.push(orig.clone());
1351 }
1352 // c:584 — `winch_unblock()` omitted: child-side in C,
1353 // parent-side here. See the c:565/c:570 note above.
1354 return Ok((interp_str, argv_new)); // c:585
1355 }
1356 }
1357 } else if eno == libc::ENOEXEC {
1358 // c:588 — binary-safety + /bin/sh fallback.
1359 let nul_pos = buf[..ct].iter().position(|&b| b == 0); // c:597
1360 let isbinary = match nul_pos {
1361 None => false, // c:598
1362 Some(npos) => {
1363 let mut has_letter = false;
1364 let mut binary = true;
1365 for &b in &buf[..npos] {
1366 // c:602-609
1367 if (b as char).is_ascii_lowercase() || b == b'$' || b == b'`' {
1368 has_letter = true;
1369 }
1370 if has_letter && b == b'\n' {
1371 binary = false; // c:606
1372 break;
1373 }
1374 }
1375 binary
1376 }
1377 };
1378 if !isbinary {
1379 // c:611
1380 let mut argv_new: Vec<String> = Vec::with_capacity(argv.len() + 2);
1381 argv_new.push("sh".to_string()); // c:625
1382 // c:544 — `*argv = pth;`: by now argv[0] IS the path
1383 // being executed, not the command word, so both the
1384 // `-`/`+` guard and the operand handed to sh are `pth`.
1385 // Testing the word let `PATH=-dir tstcmd` hand sh
1386 // `-dir/tstcmd` with no `-` guard (sh: `-d: invalid
1387 // option`), and ran a bare-word script as `sh tstcmd`.
1388 if pth.starts_with('-') || pth.starts_with('+') {
1389 argv_new.push("-".to_string()); // c:623
1390 }
1391 argv_new.push(pth.to_string()); // c:544
1392 for orig in argv.iter().skip(1) {
1393 argv_new.push(orig.clone());
1394 }
1395 // c:626 — `winch_unblock()` omitted: child-side in C,
1396 // parent-side here. See the c:565/c:570 note above.
1397 return Ok(("/bin/sh".to_string(), argv_new)); // c:627
1398 }
1399 }
1400 }
1401 }
1402 Err(eno) // c:643
1403}
1404
1405
1406/// !!! WARNING: RUST-ONLY HELPER — the non-forking form of `execute()`'s
1407/// search (Src/exec.c:791-895) !!!
1408///
1409/// C runs `execute()` in the forked child, where every `zexecve` either
1410/// replaces the process or returns an errno and the walk moves on to the
1411/// next candidate. zshrs spawns from the parent, so each `zexecve` here is a
1412/// `posix_spawn(2)` attempt (`zexecve_spawn`) and the first one that starts a
1413/// process ends the walk with its pid. The candidates, their order and the
1414/// `isgooderr` bookkeeping are C's:
1415///
1416/// * c:791-801 — an `arg0` holding a `/` is exec'd as spelled; unless it is
1417/// relative, not `./…`/`../…`, and PATH_DIRS is set, a failure is final.
1418/// * c:803-819 — `command -p`: the default-path hit alone.
1419/// * c:822-870 — the `cmdnamtab` candidate, then c:877-895
1420/// `execute_skip_exec:`, the full `$path` walk (empty and `.` entries
1421/// mean `arg0` itself).
1422///
1423/// `Err(eno)` is C's `eno` at c:871: non-zero means `zerr("%e: %s")`, zero
1424/// means nothing usable was found (`command not found`).
1425pub(crate) fn execute_spawn(
1426 arg0: &str,
1427 argv: &[String],
1428 defpath: Option<&str>,
1429 hashed: Option<&str>,
1430 drop_argv0: bool,
1431 in_place: bool,
1432) -> Result<libc::pid_t, i32> {
1433 use crate::ported::exec::isgooderr;
1434 // c:791-801
1435 if let Some(slash) = arg0.find('/') {
1436 let lerrno = match zexecve_spawn(arg0, argv, drop_argv0, in_place) {
1437 Ok(pid) => return Ok(pid),
1438 Err(e) => e,
1439 }; // c:793
1440 let dotted = arg0.starts_with('.')
1441 && (slash == 1 || (arg0.starts_with("..") && slash == 2));
1442 if slash == 0 || crate::ported::zsh_h::unset(crate::ported::zsh_h::PATHDIRS) || dotted {
1443 return Err(lerrno); // c:794-798
1444 }
1445 }
1446 let mut eno = 0;
1447 let mut attempt = |pth: &str, dir: &str| -> Option<libc::pid_t> {
1448 match zexecve_spawn(pth, argv, drop_argv0, in_place) {
1449 Ok(pid) => Some(pid),
1450 Err(ee) => {
1451 if isgooderr(ee, dir) {
1452 eno = ee;
1453 }
1454 None
1455 }
1456 }
1457 };
1458 let dir_of = |p: &str| -> String {
1459 // c:817-818 / c:866-867 — `if ((dptr = strrchr(nn, '/'))) *dptr =
1460 // '\0'; isgooderr(ee, *nn ? nn : "/")`.
1461 match p.rfind('/') {
1462 Some(0) | None => "/".to_string(),
1463 Some(i) => p[..i].to_string(),
1464 }
1465 };
1466 if let Some(pbuf) = defpath {
1467 // c:815 — `ee = zexecve(pbuf, argv, newenvp);`
1468 if let Some(pid) = attempt(pbuf, &dir_of(pbuf)) {
1469 return Ok(pid);
1470 }
1471 return Err(eno);
1472 }
1473 if let Some(nn) = hashed {
1474 // c:863 — `ee = zexecve(nn, argv, newenvp);`
1475 if let Some(pid) = attempt(nn, &dir_of(nn)) {
1476 return Ok(pid);
1477 }
1478 }
1479 // c:877 `execute_skip_exec:` — `for (pp = path; *pp; pp++)`.
1480 let path = crate::ported::params::getaparam("path").unwrap_or_default();
1481 for pp in &path {
1482 let pth = if pp.is_empty() || pp == "." {
1483 arg0.to_string() // c:879-880
1484 } else {
1485 format!("{}/{}", pp, arg0) // c:884-888
1486 };
1487 if pth.len() >= libc::PATH_MAX as usize {
1488 continue; // c:887-888
1489 }
1490 if let Some(pid) = attempt(&pth, pp) {
1491 return Ok(pid); // c:890 `ee = zexecve(buf, argv, newenvp);`
1492 }
1493 }
1494 Err(eno)
1495}
1496
1497/// !!! WARNING: RUST-ONLY HELPER — `zexecve()` (Src/exec.c:504-643) from the
1498/// parent via `posix_spawn(2)` !!!
1499///
1500/// Same steps as the forked-child port (`crate::ported::exec::zexecve`), with
1501/// each `execve` a `posix_spawn` of the SAME path — never `posix_spawnp`,
1502/// whose libc-internal `/bin/sh` fallback on ENOEXEC runs a shebang-less
1503/// script without C's `-`/`+` operand guard (c:611-624) and so hands
1504/// `-dir/tstcmd` to sh as an option. The kernel's refusal comes back here
1505/// and `zexecve_recover` makes C's decision.
1506///
1507/// The environment is the child's `environ` as C leaves it right before
1508/// `execve`, built as a copy so the parent's own array is untouched (C does
1509/// these writes in the child that is about to vanish):
1510///
1511/// * c:514-520 — `zputenv("_=<pth>")`: an existing `_` entry is replaced in
1512/// place, otherwise the entry is appended.
1513/// * c:765-768 (`execute`) — `unsetenv("ARGV0")` when ARGV0 supplied argv[0].
1514///
1515/// The array keeps `environ`'s order: `std::process::Command` rebuilds any
1516/// environment it modifies from a sorted map, so externals saw the variables
1517/// alphabetically instead of in the order the shell added them.
1518fn zexecve_spawn(pth: &str, argv: &[String], drop_argv0: bool, in_place: bool) -> Result<libc::pid_t, i32> {
1519 use std::ffi::CString;
1520 use std::os::unix::ffi::OsStrExt as _;
1521 // c:514-520 — `_=pth`, made absolute against `pwd`.
1522 let underscore = if pth.starts_with('/') {
1523 pth.to_string() // c:516-517
1524 } else {
1525 format!("{}/{}", crate::ported::params::getsparam("PWD").unwrap_or_default(), pth) // c:519
1526 };
1527 let mut underscore_entry = b"_=".to_vec();
1528 underscore_entry.extend_from_slice(&crate::ported::utils::unmetafy_str(&underscore));
1529 let mut envp: Vec<CString> = Vec::new();
1530 let mut have_underscore = false;
1531 for (k, v) in std::env::vars_os() {
1532 let k = k.as_bytes();
1533 if drop_argv0 && k == b"ARGV0" {
1534 continue; // c:768 `unsetenv("ARGV0")`
1535 }
1536 let entry = if k == b"_" {
1537 have_underscore = true;
1538 underscore_entry.clone() // c:520 — replaced in place
1539 } else {
1540 let mut e = k.to_vec();
1541 e.push(b'=');
1542 e.extend_from_slice(v.as_bytes());
1543 e
1544 };
1545 if let Ok(c) = CString::new(entry) {
1546 envp.push(c);
1547 }
1548 }
1549 if !have_underscore {
1550 if let Ok(c) = CString::new(underscore_entry) {
1551 envp.push(c); // c:520 — appended
1552 }
1553 }
1554 // c:528 — `execve(pth, argv, newenvp);`
1555 let eno = match posix_spawn_argv(pth, argv, &envp, in_place) {
1556 Ok(pid) => return Ok(pid),
1557 Err(eno) => eno,
1558 };
1559 // c:534-634 — the kernel refused the file: the `#!` line's interpreter,
1560 // or `/bin/sh` for a shebang-less script.
1561 match zexecve_recover(pth, argv, eno) {
1562 // c:566/571/581/585/627 — the second `execve`; when it fails too, C
1563 // falls through to c:643 `return eno` with the ORIGINAL errno.
1564 Ok((prog, newargv)) => posix_spawn_argv(&prog, &newargv, &envp, in_place).map_err(|_| eno),
1565 Err(e) => Err(e), // c:632/634/643
1566 }
1567}
1568
1569/// !!! WARNING: RUST-ONLY HELPER — the dispositions `entersubsh` resets in the
1570/// child C forks for an external, applied at the spawn instead !!!
1571///
1572/// c:Src/exec.c:1185-1193 —
1573/// ```c
1574/// if (interact) {
1575/// signal_default(SIGTERM);
1576/// if (!(sigtrapped[SIGINT] & ZSIG_IGNORED))
1577/// signal_default(SIGINT);
1578/// if (!(sigtrapped[SIGPIPE]))
1579/// signal_default(SIGPIPE);
1580/// }
1581/// if (!(sigtrapped[SIGQUIT] & ZSIG_IGNORED))
1582/// signal_default(SIGQUIT);
1583/// ```
1584/// The shell ignores SIGQUIT always and SIGTERM when interactive
1585/// (c:Src/init.c:1448/1463), and SIG_IGN survives `execve`, so without this a
1586/// spawned `sh -c 'kill -QUIT $$'` survived its own signal. SIGPIPE is reset
1587/// unless a `trap '' PIPE` ignores it: C never ignores it otherwise, but the
1588/// Rust runtime does. The job-control stops (c:1174-1183) stay as they are: a foreground
1589/// wait here does not watch for a stopped child, so a ^Z'd child would hang
1590/// the shell.
1591fn entersubsh_sigdef() -> Vec<i32> {
1592 use crate::ported::zsh_h::{isset, INTERACTIVE, ZSIG_IGNORED};
1593 let trapped = |sig: i32| -> i32 {
1594 crate::ported::signals::sigtrapped
1595 .lock()
1596 .ok()
1597 .and_then(|t| t.get(sig as usize).copied())
1598 .unwrap_or(0)
1599 };
1600 let mut sigs = Vec::with_capacity(4);
1601 if trapped(libc::SIGPIPE) & ZSIG_IGNORED == 0 {
1602 sigs.push(libc::SIGPIPE); // c:1189-1190, and the Rust runtime's ignore
1603 }
1604 if isset(INTERACTIVE) {
1605 sigs.push(libc::SIGTERM); // c:1186
1606 if trapped(libc::SIGINT) & ZSIG_IGNORED == 0 {
1607 sigs.push(libc::SIGINT); // c:1187-1188
1608 }
1609 }
1610 if trapped(libc::SIGQUIT) & ZSIG_IGNORED == 0 {
1611 sigs.push(libc::SIGQUIT); // c:1192-1193
1612 }
1613 sigs
1614}
1615
1616/// !!! WARNING: RUST-ONLY HELPER — the signal mask the child C forks for an
1617/// external carries into `execve`, computed in the parent instead !!!
1618///
1619/// The child inherits the shell's mask minus what C unblocks on the way to
1620/// the exec:
1621///
1622/// * c:Src/exec.c:1162-1166 (`entersubsh`) — while `intrap`, every trapped,
1623/// non-ignored signal is unblocked: the trap dispatcher blocks the signal
1624/// being handled, and a command run from the trap body must not inherit it.
1625/// * c:Src/exec.c:751 (`execute`) — `child_unblock()` right before the
1626/// `zexecve` walk, so SIGCHLD is never blocked in an external.
1627///
1628/// Without this a command run from a `trap '...' USR2` handler started with
1629/// SIGUSR2 blocked, and every external started with SIGCHLD blocked.
1630fn execute_sigmask() -> libc::sigset_t {
1631 use crate::ported::signals_h::SIGCOUNT;
1632 use crate::ported::zsh_h::ZSIG_IGNORED;
1633 unsafe {
1634 let mut mask: libc::sigset_t = std::mem::zeroed();
1635 libc::sigemptyset(&mut mask);
1636 libc::pthread_sigmask(libc::SIG_BLOCK, std::ptr::null(), &mut mask);
1637 if crate::ported::signals::intrap.load(std::sync::atomic::Ordering::Relaxed) != 0 {
1638 // c:1163-1166 — `for (sig = 1; sig <= SIGCOUNT; sig++) if
1639 // (sigtrapped[sig] && sigtrapped[sig] != ZSIG_IGNORED)
1640 // signal_unblock(signal_mask(sig));`
1641 let trapped = crate::ported::signals::sigtrapped
1642 .lock()
1643 .map(|t| t.clone())
1644 .unwrap_or_default();
1645 for sig in 1..=SIGCOUNT {
1646 let st = trapped.get(sig as usize).copied().unwrap_or(0);
1647 if st != 0 && st != ZSIG_IGNORED {
1648 libc::sigdelset(&mut mask, sig);
1649 }
1650 }
1651 }
1652 libc::sigdelset(&mut mask, libc::SIGCHLD); // c:751 `child_unblock();`
1653 mask
1654 }
1655}
1656
1657/// !!! WARNING: RUST-ONLY HELPER — the `posix_spawn(2)` call standing in for
1658/// `execve(2)` in `zexecve_spawn` !!!
1659///
1660/// argv and path are unmetafied first, as C's `zexecve` does at c:510-513
1661/// (`$'\xff'` reaches the child as the raw byte). The child starts with
1662/// `execute_sigmask`'s mask and `entersubsh_sigdef`'s dispositions.
1663///
1664/// `in_place` is c:Src/exec.c:4369 in a child already forked for the command
1665/// (`last1 = forked = 1`, c:3063): `execve(2)` replaces this process instead
1666/// of spawning, and returns only on failure.
1667fn posix_spawn_argv(
1668 pth: &str,
1669 argv: &[String],
1670 envp: &[std::ffi::CString],
1671 in_place: bool,
1672) -> Result<libc::pid_t, i32> {
1673 use std::ffi::CString;
1674 let cstr = |s: &str| {
1675 let mut b = crate::ported::utils::unmetafy_str(s);
1676 if let Some(n) = b.iter().position(|c| *c == 0) {
1677 b.truncate(n); // a C string ends at its first NUL
1678 }
1679 CString::new(b).unwrap_or_default()
1680 };
1681 let cpth = cstr(pth);
1682 let cargs: Vec<CString> = argv.iter().map(|a| cstr(a)).collect();
1683 let mut argv_ptrs: Vec<*mut libc::c_char> = cargs.iter().map(|c| c.as_ptr() as *mut _).collect();
1684 argv_ptrs.push(std::ptr::null_mut());
1685 let mut envp_ptrs: Vec<*mut libc::c_char> = envp.iter().map(|c| c.as_ptr() as *mut _).collect();
1686 envp_ptrs.push(std::ptr::null_mut());
1687 let sigdef = entersubsh_sigdef();
1688 let sigmask = execute_sigmask();
1689 unsafe {
1690 if in_place {
1691 for &sig in &sigdef {
1692 libc::signal(sig, libc::SIG_DFL);
1693 }
1694 libc::pthread_sigmask(libc::SIG_SETMASK, &sigmask, std::ptr::null_mut());
1695 libc::execve(cpth.as_ptr(), argv_ptrs.as_ptr() as *const *const _, envp_ptrs.as_ptr() as *const *const _);
1696 return Err(std::io::Error::last_os_error().raw_os_error().unwrap_or(libc::ENOEXEC));
1697 }
1698 let mut attrs: libc::posix_spawnattr_t = std::mem::zeroed();
1699 let rc = libc::posix_spawnattr_init(&mut attrs);
1700 if rc != 0 {
1701 return Err(rc);
1702 }
1703 let mut dfl: libc::sigset_t = std::mem::zeroed();
1704 libc::sigemptyset(&mut dfl);
1705 for &sig in &sigdef {
1706 libc::sigaddset(&mut dfl, sig);
1707 }
1708 libc::posix_spawnattr_setsigdefault(&mut attrs, &dfl);
1709 libc::posix_spawnattr_setsigmask(&mut attrs, &sigmask);
1710 libc::posix_spawnattr_setflags(
1711 &mut attrs,
1712 (libc::POSIX_SPAWN_SETSIGDEF | libc::POSIX_SPAWN_SETSIGMASK) as _,
1713 );
1714 let mut pid: libc::pid_t = 0;
1715 let rc = libc::posix_spawn(
1716 &mut pid,
1717 cpth.as_ptr(),
1718 std::ptr::null(),
1719 &attrs,
1720 argv_ptrs.as_ptr(),
1721 envp_ptrs.as_ptr(),
1722 );
1723 libc::posix_spawnattr_destroy(&mut attrs);
1724 if rc != 0 {
1725 return Err(rc);
1726 }
1727 Ok(pid)
1728 }
1729}
1730
1731impl ShellExecutor {
1732 /// Set a scalar parameter via the canonical `paramtab`
1733 /// (`Src/params.c:3350 setsparam`). The single store.
1734 pub fn set_scalar(&mut self, name: String, value: String) {
1735 setsparam(&name, &value); // c:params.c:3350
1736 }
1737
1738 /// Read positional parameters from canonical `PPARAMS`
1739 /// `Mutex<Vec<String>>` (Src/init.c:pparams). The single store.
1740 pub fn pparams(&self) -> Vec<String> {
1741 crate::ported::builtin::PPARAMS
1742 .lock()
1743 .map(|p| p.clone())
1744 .unwrap_or_default()
1745 }
1746
1747 /// Write positional parameters to canonical `PPARAMS`.
1748 pub fn set_pparams(&mut self, params: Vec<String>) {
1749 if let Ok(mut p) = crate::ported::builtin::PPARAMS.lock() {
1750 *p = params;
1751 }
1752 }
1753
1754 /// Read PM_* type flags from the paramtab Param entry. Used by
1755 /// SET_VAR / `+=` arms (case-fold, integer-add, readonly guard).
1756 /// Returns 0 when the name isn't in paramtab. Mirrors the C
1757 /// source's direct `pm->node.flags & PM_INTEGER` checks.
1758 pub fn param_flags(&self, name: &str) -> i32 {
1759 paramtab()
1760 .read()
1761 .ok()
1762 .and_then(|t| t.get(name).map(|p| p.node.flags))
1763 .unwrap_or(0)
1764 }
1765
1766 /// `readonly` / `typeset -r` / read-only-by-design (LINENO, PPID,
1767 /// $$, $?, $!, ...) — match user-side rejection in C's
1768 /// assignstrvalue at `Src/params.c:2699-2703` which gates on
1769 /// `pm->node.flags & PM_READONLY` where the IPDEF4 family declares
1770 /// `PM_READONLY_SPECIAL = PM_SPECIAL | PM_READONLY | PM_RO_BY_DESIGN`
1771 /// (all three bits set together), which `init_partab_params` now
1772 /// stamps in full. The PM_RO_BY_DESIGN arm below is therefore no
1773 /// longer the IPDEF4 rows' only read-only marker — it remains
1774 /// because `private` params (c:Src/Modules/param_private.c:174)
1775 /// carry PM_RO_BY_DESIGN WITHOUT PM_READONLY and need the
1776 /// scope-gated test. Bug #418-family / test_lineno_intrinsic_readonly.
1777 pub fn is_readonly_param(&self, name: &str) -> bool {
1778 // c:Src/params.c:2235 fetchvalue looks the name up through
1779 // realparamtab->getnode, i.e. getprivatenode (Src/Modules/
1780 // param_private.c:678): a private of an enclosing scope with nothing
1781 // beneath it is ABSENT, and createparam reports the write.
1782 let (flags, pm_level) = crate::ported::params::paramtab()
1783 .read()
1784 .ok()
1785 .and_then(|t| {
1786 t.get(name).and_then(|p| {
1787 let vis = crate::ported::modules::param_private::getprivatenode(&**p as *const _);
1788 (!vis.is_null()).then(|| unsafe { ((*vis).node.flags as u32, (*vis).level) })
1789 })
1790 })
1791 .unwrap_or((0, 0));
1792 // c:Src/params.c:2264-2265 — assignsparam reaches its c:3216 PM_READONLY
1793 // test only through fetchvalue, which reports a node that is PM_UNSET
1794 // without PM_DECLARED as ABSENT; createparam then decides (for an
1795 // outer-scope private, hidden by scopeprivate's PM_UNSET|PM_READONLY,
1796 // that is "can't modify read-only parameter"). So such a node is not
1797 // a read-only rejection here; assignsparam reports it.
1798 if (flags & crate::ported::zsh_h::PM_UNSET) != 0 && (flags & crate::ported::zsh_h::PM_DECLARED) == 0 {
1799 return false;
1800 }
1801 // c:Src/params.c assignsparam — a real PM_READONLY param always
1802 // rejects writes.
1803 if (flags & PM_READONLY) != 0 {
1804 return true;
1805 }
1806 if (flags & crate::ported::zsh_h::PM_RO_BY_DESIGN) != 0 {
1807 // c:Src/Modules/param_private.c pps_setfn (c:300-307) — a
1808 // PRIVATE param (PM_RO_BY_DESIGN + PM_REMOVABLE) is NOT blanket
1809 // read-only: a write is permitted iff it is in the SAME scope
1810 // (`locallevel == pm->level`, e.g. `() { private p=1; p=2 }`
1811 // → 2) or above the wrap level (`locallevel >
1812 // private_wraplevel`). A deeper nested-scope write is rejected
1813 // (setfn_error) — that is how a nested fn writing an OUTER
1814 // function's private still errors and aborts. zshrs never
1815 // wires the private GSU, so the level gate is enforced here.
1816 if (flags & crate::ported::zsh_h::PM_REMOVABLE) != 0 {
1817 let ll = crate::ported::params::locallevel.load(Ordering::Relaxed);
1818 let wrap = crate::ported::modules::param_private::private_wraplevel
1819 .load(Ordering::Relaxed);
1820 return !(ll == pm_level || ll > wrap); // c:304 (negated: blocked)
1821 }
1822 // Non-removable PM_RO_BY_DESIGN = IPDEF4-family special
1823 // (LINENO/$?/$$…). These now also carry PM_READONLY and so
1824 // return true from the branch above; this arm stays as the
1825 // c:Src/zsh.h:1923 "readonly by design" fallback for any row
1826 // reached before `init_partab_params` has stamped the flag.
1827 return true;
1828 }
1829 false
1830 }
1831
1832 /// Most-recent-command exit status. Reads canonical
1833 /// `builtin::LASTVAL` AtomicI32 (`Src/builtin.c:6443`).
1834 pub fn last_status(&self) -> i32 {
1835 crate::ported::builtin::LASTVAL.load(Ordering::Relaxed)
1836 }
1837
1838 /// Write the most-recent-command exit status. The canonical
1839 /// store is `builtin::LASTVAL`; this is the single setter.
1840 /// Used everywhere `$?` / `%?` / errexit / ZERR trap read.
1841 pub fn set_last_status(&mut self, status: i32) {
1842 crate::ported::builtin::LASTVAL.store(status, Ordering::Relaxed);
1843 }
1844
1845 /// Set an indexed array parameter via canonical paramtab
1846 /// (`assignaparam`, `Src/params.c:3357`). The single store.
1847 ///
1848 /// Callers mean "make NAME this array" — `typeset -a h=(…)` over an
1849 /// existing assoc among them, whose type conversion C does in
1850 /// typeset_single before it assigns. `setaparam` now keeps an existing
1851 /// assoc hashed (C's c:3341-3342), so go one level down to the
1852 /// type-resetting store with the same `ASSPM_WARN` flag setaparam used.
1853 pub fn set_array(&mut self, name: String, value: Vec<String>) {
1854 assignaparam(&name, value, crate::ported::zsh_h::ASSPM_WARN); // c:params.c:3766
1855 }
1856
1857 /// Set an associative array parameter via canonical
1858 /// `sethparam` (`Src/params.c:3602`). The single store.
1859 pub fn set_assoc(&mut self, name: String, value: IndexMap<String, String>) {
1860 let mut flat: Vec<String> = Vec::with_capacity(value.len() * 2);
1861 for (k, v) in &value {
1862 flat.push(k.clone());
1863 flat.push(v.clone());
1864 }
1865 sethparam(&name, flat); // c:params.c:3602
1866 }
1867
1868 /// Read a scalar parameter. Mirrors C `getsparam` at
1869 /// `Src/params.c:3076` — reads through paramtab, falls back to
1870 /// special-var hooks and env.
1871 pub fn scalar(&self, name: &str) -> Option<String> {
1872 getsparam(name)
1873 }
1874
1875 /// Read an array parameter via canonical `getaparam`
1876 /// (`Src/params.c:3101`).
1877 pub fn array(&self, name: &str) -> Option<Vec<String>> {
1878 getaparam(name)
1879 }
1880
1881 /// Read an associative array parameter from canonical
1882 /// `paramtab_hashed_storage`. Mirrors C `gethparam` at
1883 /// `Src/params.c:3115` — returns the typed `IndexMap`.
1884 pub fn assoc(&self, name: &str) -> Option<IndexMap<String, String>> {
1885 // c:Src/params.c:570-575 — nameref deref before the read.
1886 let resolved = match crate::ported::params::resolve_nameref_name(name, None) {
1887 // c:2264-2267 + c:2297 — a reference to an ELEMENT leaves its
1888 // `[sub]` unparsed for a bracks-0 getvalue, so it is no hash.
1889 crate::ported::params::nameref_resolution::Target { subscript: Some(_), .. } => {
1890 return Default::default()
1891 }
1892 crate::ported::params::nameref_resolution::Target { name: t_, .. } => t_,
1893 _ => name.to_string(),
1894 };
1895 // The live param's TYPE is authoritative — paramtab_hashed_storage is
1896 // keyed by NAME ONLY (no scope), so a local ARRAY that shadows a special
1897 // assoc (`local -a options` / `local -a commands` over the hidden
1898 // `options`/`commands` specials) leaves a stale (emptied) hashed_storage
1899 // entry behind. Without this guard `exec.assoc("options")` returned
1900 // Some(empty), so a subsequent bare `options=(-a -b -c)` routed through
1901 // sethparam → "bad set of key/value pairs for associative array"
1902 // (odd count), breaking `_sqlite`'s `local -a options; options=(…)`
1903 // (separate statements — the one-statement `local -a commands=(…)` form
1904 // that openssl uses is typed correctly by bin_typeset). Consult the
1905 // current param: if it exists and is NOT PM_HASHED, it's an array/scalar
1906 // shadow and the stale assoc storage must not be seen.
1907 if let Some(flags) = crate::ported::params::paramtab()
1908 .read()
1909 .ok()
1910 .and_then(|t| t.get(resolved.as_str()).map(|p| p.node.flags as u32))
1911 {
1912 if (flags & PM_HASHED) == 0 {
1913 return None;
1914 }
1915 }
1916 paramtab_hashed_storage()
1917 .lock()
1918 .ok()
1919 .and_then(|m| m.get(resolved.as_str()).cloned())
1920 }
1921
1922 /// Test whether a scalar parameter exists in paramtab.
1923 /// Mirrors the C `paramtab->getnode(name) != NULL` check.
1924 pub fn has_scalar(&self, name: &str) -> bool {
1925 getsparam(name).is_some()
1926 }
1927
1928 /// Test whether an array parameter exists in paramtab. Mirrors
1929 /// `getaparam(name).is_some()` (PM_ARRAY + populated `u_arr`, with
1930 /// digit-first-name rejection and nameref deref) WITHOUT cloning the
1931 /// backing vector — `getaparam` returns an owned `Vec<String>`, so a
1932 /// bare existence probe on a large array copied every element. Hot in
1933 /// the subscript-store dispatch (`a[i]=v` in a loop), so keep it a
1934 /// flag read.
1935 pub fn has_array(&self, name: &str) -> bool {
1936 if name.starts_with(|c: char| c.is_ascii_digit()) {
1937 return false;
1938 }
1939 let resolved = match crate::ported::params::resolve_nameref_name(name, None) {
1940 crate::ported::params::nameref_resolution::Target { name: t_, .. } => t_,
1941 _ => name.to_string(),
1942 };
1943 crate::ported::params::paramtab()
1944 .read()
1945 .ok()
1946 .and_then(|t| {
1947 t.get(resolved.as_str()).map(|p| {
1948 (p.node.flags as u32 & crate::ported::zsh_h::PM_ARRAY) != 0 && p.u_arr.is_some()
1949 })
1950 })
1951 .unwrap_or(false)
1952 }
1953
1954 /// Test whether an associative array parameter exists. Reads
1955 /// canonical `paramtab_hashed_storage` (Src/params.c hashed
1956 /// PM_HASHED slot).
1957 pub fn has_assoc(&self, name: &str) -> bool {
1958 // c:Src/params.c:570-575 — nameref deref before the read.
1959 let resolved = match crate::ported::params::resolve_nameref_name(name, None) {
1960 // c:2264-2267 + c:2297 — a reference to an ELEMENT leaves its
1961 // `[sub]` unparsed for a bracks-0 getvalue, so it is no hash.
1962 crate::ported::params::nameref_resolution::Target { subscript: Some(_), .. } => {
1963 return Default::default()
1964 }
1965 crate::ported::params::nameref_resolution::Target { name: t_, .. } => t_,
1966 _ => name.to_string(),
1967 };
1968 // Live-param type is authoritative (see `assoc` above): a non-PM_HASHED
1969 // shadow (e.g. `local -a options`) hides the stale name-keyed
1970 // hashed_storage entry.
1971 if let Some(flags) = crate::ported::params::paramtab()
1972 .read()
1973 .ok()
1974 .and_then(|t| t.get(resolved.as_str()).map(|p| p.node.flags as u32))
1975 {
1976 if (flags & PM_HASHED) == 0 {
1977 return false;
1978 }
1979 }
1980 paramtab_hashed_storage()
1981 .lock()
1982 .ok()
1983 .map(|m| m.contains_key(resolved.as_str()))
1984 .unwrap_or(false)
1985 }
1986
1987 /// Unset an associative array parameter via canonical
1988 /// `unsetparam` (Src/params.c:3819) — PM_READONLY rejection,
1989 /// stdunsetfn dispatch, env clear. Also clears the zshrs-side
1990 /// `paramtab_hashed_storage` parallel IndexMap shadow.
1991 pub fn unset_assoc(&mut self, name: &str) {
1992 unsetparam(name);
1993 let _ = paramtab_hashed_storage()
1994 .lock()
1995 .ok()
1996 .as_deref_mut()
1997 .map(|m| m.remove(name));
1998 }
1999
2000 /// Set a regular alias. Writes canonical aliastab with
2001 /// ALIAS_GLOBAL bit cleared.
2002 pub fn set_alias(&mut self, name: String, value: String) {
2003 if let Ok(mut tab) = crate::ported::hashtable::aliastab_lock().write() {
2004 tab.add(crate::ported::hashtable::createaliasnode(&name, &value, 0));
2005 }
2006 }
2007
2008 /// Set a global alias (`alias -g`). Writes canonical aliastab
2009 /// with ALIAS_GLOBAL bit set.
2010 pub fn set_global_alias(&mut self, name: String, value: String) {
2011 if let Ok(mut tab) = crate::ported::hashtable::aliastab_lock().write() {
2012 tab.add(crate::ported::hashtable::createaliasnode(
2013 &name,
2014 &value,
2015 crate::ported::zsh_h::ALIAS_GLOBAL as u32,
2016 ));
2017 }
2018 }
2019
2020 /// Set a suffix alias (`alias -s ext=cmd`). Writes canonical
2021 /// sufaliastab with ALIAS_SUFFIX node flag — mirrors C
2022 /// Src/builtin.c:4480-4481 (`flags1 |= ALIAS_SUFFIX; ht =
2023 /// sufaliastab;`) → c:4527 (`createaliasnode(value, flags1)`).
2024 /// Without ALIAS_SUFFIX in node.flags, `${saliases[k]}` /
2025 /// `${(k)saliases}` introspection (parameter.c:1953/2018) fails
2026 /// because both paths strict-equality-match flags == ALIAS_SUFFIX.
2027 pub fn set_suffix_alias(&mut self, name: String, value: String) {
2028 if let Ok(mut tab) = crate::ported::hashtable::sufaliastab_lock().write() {
2029 tab.add(crate::ported::hashtable::createaliasnode(
2030 &name,
2031 &value,
2032 crate::ported::zsh_h::ALIAS_SUFFIX as u32,
2033 ));
2034 }
2035 }
2036
2037 /// Snapshot the alias map as a sorted `Vec<(name, value)>`,
2038 /// only entries WITHOUT the ALIAS_GLOBAL flag (regular aliases).
2039 pub fn alias_entries(&self) -> Vec<(String, String)> {
2040 if let Ok(tab) = crate::ported::hashtable::aliastab_lock().read() {
2041 tab.iter_sorted()
2042 .into_iter()
2043 .filter(|(_, a)| (a.node.flags & crate::ported::zsh_h::ALIAS_GLOBAL as i32) == 0)
2044 .map(|(k, a)| (k.clone(), a.text.clone()))
2045 .collect()
2046 } else {
2047 Vec::new()
2048 }
2049 }
2050
2051 /// Snapshot the global-alias entries (ALIAS_GLOBAL flag set).
2052 pub fn global_alias_entries(&self) -> Vec<(String, String)> {
2053 if let Ok(tab) = crate::ported::hashtable::aliastab_lock().read() {
2054 tab.iter_sorted()
2055 .into_iter()
2056 .filter(|(_, a)| (a.node.flags & crate::ported::zsh_h::ALIAS_GLOBAL as i32) != 0)
2057 .map(|(k, a)| (k.clone(), a.text.clone()))
2058 .collect()
2059 } else {
2060 Vec::new()
2061 }
2062 }
2063
2064 /// Snapshot the suffix-alias entries.
2065 pub fn suffix_alias_entries(&self) -> Vec<(String, String)> {
2066 if let Ok(tab) = crate::ported::hashtable::sufaliastab_lock().read() {
2067 tab.iter_sorted()
2068 .into_iter()
2069 .map(|(k, a)| (k.clone(), a.text.clone()))
2070 .collect()
2071 } else {
2072 Vec::new()
2073 }
2074 }
2075
2076 /// Unset an array parameter. Direct port of `unsetparam_pm` for
2077 /// a PM_ARRAY Param. Mirrors are kept for now while the field
2078 /// transitions.
2079 /// Unset an array parameter via canonical `unsetparam`
2080 /// (Src/params.c:3819). Routes through the C-faithful port
2081 /// that runs PM_NAMEREF skip + PM_READONLY rejection via
2082 /// unsetparam_pm + stdunsetfn dispatch + pm.old scope restore.
2083 /// Inline `tab.remove(name)` skipped all four.
2084 pub fn unset_array(&mut self, name: &str) {
2085 unsetparam(name);
2086 }
2087
2088 /// Unset a scalar parameter via canonical `unsetparam`. Same
2089 /// C-faithful path as `unset_array`; the C `unsetparam` itself
2090 /// is type-agnostic and dispatches through PM_TYPE inside.
2091 pub fn unset_scalar(&mut self, name: &str) {
2092 unsetparam(name);
2093 }
2094 /// Lightweight executor for a POOL WORKER THREAD. Unlike [`new`] (a full
2095 /// session bootstrap that re-derives PWD, imports the environment, seeds
2096 /// `OPTS_LIVE`, and writes ~30 default params into the GLOBAL param table),
2097 /// this constructs ONLY the per-executor struct fields and touches NO
2098 /// global state. A worker shares the already-populated, `RwLock`-synchronized
2099 /// globals (params / functions / options); re-seeding them here would clobber
2100 /// the live main session's values (IFS, OPTIND, `$_`, user options, …).
2101 ///
2102 /// The worker pool is shared (Arc) — a worker never spins up its own pool.
2103 /// Per-worker SQLite caches (compsys / plugin) and the history engine are
2104 /// left `None`: a worker runs short compute bodies, not interactive editing.
2105 ///
2106 /// Phase 1 of the in-process thread-execution model (replaces the
2107 /// subprocess-forking parallel builtins). The caller runs the body under
2108 /// `ExecutorContext::enter(&mut wex)` so the VM's thread_local executor
2109 /// resolves on the worker thread; param writes flow to the shared globals.
2110 pub fn new_worker(pool: std::sync::Arc<crate::worker::WorkerPool>) -> Self {
2111 // fpath from the inherited env, same as new() — pure read, no global write.
2112 let raw_fpath: Vec<PathBuf> = env::var("FPATH")
2113 .unwrap_or_default()
2114 .split(':')
2115 .filter(|s| !s.is_empty())
2116 .map(PathBuf::from)
2117 .collect();
2118 // c:Src/init.c:1132-1143 seeds `<prefix>/share/zsh/<ver>/functions` at
2119 // a FIXED position, and every `#compdef` claim is resolved against
2120 // `$fpath` ORDER. The bundled tree is that tree's replacement — a
2121 // byte-identical superset of it — so it belongs AT ITS INDEX, not at
2122 // either end.
2123 let host_at = raw_fpath.iter().position(|d| is_host_zsh_function_tree(d));
2124 let mut fpath: Vec<PathBuf> = raw_fpath
2125 .into_iter()
2126 .filter(|d| !is_host_zsh_function_tree(d))
2127 .collect();
2128 if fpath.is_empty() {
2129 fpath = default_fpath(); // c:Src/init.c:1143
2130 }
2131 // Same directory as the main constructor, and LAST for the same
2132 // reason, but never written from a pool worker -- materialisation
2133 // is the session's job.
2134 if let Some(d) = crate::bundled_functions::functions_dir() {
2135 if d.is_dir() && !fpath.contains(&d) {
2136 // Insert AT the host tree's inherited index, not at either
2137 // end. `host_at` is that index in the raw FPATH; the filter
2138 // above removed only host-tree entries, all of which are at or
2139 // after it, so the index still addresses the same slot.
2140 //
2141 // Both ends are wrong, and each was tried. LAST (the previous
2142 // behaviour) let `zsh-more-completions`' appended dirs
2143 // out-rank the distribution for 343 files / 729 commands —
2144 // the opposite of real zsh, where the tree sits at index 24
2145 // and those plugins at 40-49, and the opposite of what
2146 // `zsh-more-completions.plugin.zsh` itself asks for: it
2147 // PREPENDS `override_src` and APPENDS `src`/`more_src*`/
2148 // `man_src`. FIRST shadowed everything the user curated,
2149 // `override_src` included (that is the `ls -<TAB>` regression
2150 // recorded in this comment's earlier revision). The host
2151 // tree's own index is after `override_src` and before the
2152 // appended plugin dirs, which is exactly where zsh has it.
2153 //
2154 // Measured on a 60-cell corpus of contested commands:
2155 // 1 PASS -> 57 PASS, zero regressions.
2156 match host_at {
2157 Some(i) if i <= fpath.len() => fpath.insert(i, d),
2158 _ => fpath.push(d),
2159 }
2160 }
2161 }
2162 Self {
2163 scriptname: Some("zsh".to_string()),
2164 scriptfilename: Some("zsh".to_string()),
2165 subshell_snapshots: Vec::new(),
2166 inline_env_stack: Vec::new(),
2167 current_command_glob_failed: std::cell::Cell::new(false),
2168 jobs: JobTable::new(),
2169 fpath,
2170 // Worker: no interactive history engine, ever — a pre-filled
2171 // cell so `history()` cannot open one from a pool thread.
2172 history: std::cell::OnceCell::from(None),
2173 completions: HashMap::new(),
2174 process_sub_counter: 0,
2175 zstyles: Vec::new(),
2176 local_scope_depth: 0,
2177 pending_underscore: None,
2178 in_dq_context: 0,
2179 in_scalar_assign: 0,
2180 profiling_enabled: false,
2181 compsys_cache: std::cell::OnceCell::from(None), // worker: no per-thread SQLite mirror
2182 compinit_pending: None,
2183 plugin_cache: None, // worker: no per-thread plugin cache
2184 deferred_compdefs: Vec::new(),
2185 returning: None,
2186 zsh_compat: false,
2187 bash_compat: false,
2188 posix_mode: false,
2189 worker_pool: pool, // SHARED — never spawn a nested pool
2190 intercepts: Vec::new(),
2191 async_jobs: HashMap::new(),
2192 next_async_id: 1,
2193 redirect_scope_stack: Vec::new(),
2194 multios_scope_stack: Vec::new(),
2195 exec_redirs_permanent: false,
2196 pipe_output_pending: false,
2197 pipe_output_scope: None,
2198 redirect_failed: false,
2199 functions_compiled: crate::cow_map::CowHashMap::new(),
2200 function_source: crate::cow_map::CowHashMap::new(),
2201 function_line_base: HashMap::new(),
2202 function_def_file: HashMap::new(),
2203 prompt_funcstack: Vec::new(),
2204 tied_array_to_scalar: HashMap::new(),
2205 ztest_pass_count: std::sync::atomic::AtomicUsize::new(0),
2206 ztest_fail_count: std::sync::atomic::AtomicUsize::new(0),
2207 ztest_skip_count: std::sync::atomic::AtomicUsize::new(0),
2208 ztest_pass_total: std::sync::atomic::AtomicUsize::new(0),
2209 ztest_fail_total: std::sync::atomic::AtomicUsize::new(0),
2210 ztest_skip_total: std::sync::atomic::AtomicUsize::new(0),
2211 ztest_run_failed: std::sync::atomic::AtomicBool::new(false),
2212 ztest_suppress_stdout: false,
2213 }
2214 }
2215
2216 /// `new` — see implementation.
2217 pub fn new() -> Self {
2218 tracing::debug!("ShellExecutor::new() initializing");
2219
2220 // zsh's man/info pages ride along with the function tree: same
2221 // reason (zshrs is not installed under a zsh prefix), same
2222 // one-stamp-read steady-state cost. This runs FIRST because it
2223 // edits MANPATH/INFOPATH in the OS environment, and the env is
2224 // read into paramtab further down -- publishing after that point
2225 // left an inherited $INFOPATH untouched in the shell while the
2226 // process environment carried the new value.
2227 crate::bundled_docs::install_and_publish();
2228
2229 // c:Src/init.c:1236-1259 — setupvals' pwd/oldpwd init, ported
2230 // here because the bin entry skips setupvals (see the
2231 // init_bltinmods note below). The validated value lands in the
2232 // live OS env: the bin entry's `$PWD` carrier (the analog of
2233 // C's `pwd` global — see the subshell-snapshot comment at
2234 // fusevm_bridge.rs `cwd:` field). set_pwd_env() pours it into
2235 // paramtab after the env-import loop, same order as C
2236 // (params.c:955).
2237 //
2238 // c:1242-1245 — "Try a cheap test to see if we can initialize
2239 // `PWD' from `HOME'." EMULATE_ZSH reads the `home` global,
2240 // which setupvals derives from getpwuid(getuid())->pw_dir
2241 // (c:1222-1225), falling back to "/" (c:1230-1232).
2242 let home = unsafe {
2243 let pw = libc::getpwuid(libc::getuid());
2244 if pw.is_null() {
2245 None
2246 } else {
2247 Some(
2248 std::ffi::CStr::from_ptr((*pw).pw_dir)
2249 .to_string_lossy()
2250 .into_owned(),
2251 )
2252 }
2253 }
2254 .unwrap_or_else(|| "/".to_string()); // c:1230-1232 EMULATE_ZSH home = "/"
2255 // ispwd (src/zsh/Src/utils.c:809-829): a candidate is honored
2256 // only when it (a) is absolute, (b) stat's to the same
2257 // dev+inode as ".", and (c) has no `.`/`..` components.
2258 // Without this chain, a child that inherits $PWD from a parent
2259 // run in a different directory (cargo test setting
2260 // current_dir(tempdir) while leaking PWD=/project/root) treats
2261 // the stale PWD as the logical-path base, so `cd sub` resolves
2262 // against the wrong directory.
2263 let pwd_val = if ispwd(&home) {
2264 home // c:1245-1246 — pwd = ztrdup(ptr) [HOME]
2265 } else if let Some(p) = env::var("PWD")
2266 .ok()
2267 .filter(|p| p.len() < libc::PATH_MAX as usize && ispwd(p))
2268 {
2269 p // c:1247-1249 — pwd = ztrdup(getenv("PWD"))
2270 } else {
2271 crate::ported::compat::zgetcwd() // c:1250-1252 — pwd = zgetcwd()
2272 };
2273 // c:1255-1259 — oldpwd = getenv("OLDPWD") ?: ztrdup(pwd).
2274 let oldpwd_val = env::var("OLDPWD").unwrap_or_else(|_| pwd_val.clone()); // c:1257
2275 // Both stay out of the environment until set_pwd_env below: in C they
2276 // are the `pwd`/`oldpwd` globals, and only set_pwd_env's addenv
2277 // (c:Src/builtin.c:821-826) exports them, after HOME, LOGNAME and
2278 // SHLVL (c:Src/params.c:960-977). Publishing them here put a
2279 // non-inherited PWD/OLDPWD ahead of those in every child's env.
2280
2281 // Initialize fpath from FPATH env var, or from the compiled-in
2282 // defaults when it is absent (c:Src/init.c:1132-1143).
2283 let raw_fpath: Vec<PathBuf> = env::var("FPATH")
2284 .unwrap_or_default()
2285 .split(':')
2286 .filter(|s| !s.is_empty())
2287 .map(PathBuf::from)
2288 .collect();
2289 // c:Src/init.c:1132-1143 seeds `<prefix>/share/zsh/<ver>/functions` at
2290 // a FIXED position, and every `#compdef` claim is resolved against
2291 // `$fpath` ORDER. The bundled tree is that tree's replacement — a
2292 // byte-identical superset of it — so it belongs AT ITS INDEX, not at
2293 // either end.
2294 let host_at = raw_fpath.iter().position(|d| is_host_zsh_function_tree(d));
2295 let mut fpath: Vec<PathBuf> = raw_fpath
2296 .into_iter()
2297 .filter(|d| !is_host_zsh_function_tree(d))
2298 .collect();
2299 if fpath.is_empty() {
2300 fpath = default_fpath();
2301 }
2302 // zshrs ships zsh's function tree with the binary; its directory
2303 // goes LAST, so it supplies only what nothing else on fpath does.
2304 //
2305 // It was first at one point, mirroring where zsh's own
2306 // <prefix>/share/zsh/<ver>/functions sits. That is wrong here: zsh
2307 // puts its tree ahead of nothing the user curated, because the
2308 // user's own directories are prepended to it, whereas an inherited
2309 // FPATH arrives ALREADY assembled. Leading it shadowed every
2310 // curated completion of the same name -- 242 of
2311 // zsh-more-completions' files on this author's setup, `_ls` among
2312 // them, which is how `ls -<TAB>` started diverging from zsh.
2313 //
2314 // Being last costs nothing: the only tree that could out-rank the
2315 // bundle is a host zsh's own, and `is_host_zsh_function_tree`
2316 // already removes that from fpath entirely. Materialised here (not
2317 // only when FPATH is absent) so an inherited FPATH from a shell
2318 // that lacks these still resolves is-at-least/colors/add-zsh-hook.
2319 if let Some(d) = crate::bundled_functions::functions_dir() {
2320 let _ = crate::bundled_functions::ensure_installed();
2321 if d.is_dir() && !fpath.contains(&d) {
2322 // Insert AT the host tree's inherited index, not at either
2323 // end. `host_at` is that index in the raw FPATH; the filter
2324 // above removed only host-tree entries, all of which are at or
2325 // after it, so the index still addresses the same slot.
2326 //
2327 // Both ends are wrong, and each was tried. LAST (the previous
2328 // behaviour) let `zsh-more-completions`' appended dirs
2329 // out-rank the distribution for 343 files / 729 commands —
2330 // the opposite of real zsh, where the tree sits at index 24
2331 // and those plugins at 40-49, and the opposite of what
2332 // `zsh-more-completions.plugin.zsh` itself asks for: it
2333 // PREPENDS `override_src` and APPENDS `src`/`more_src*`/
2334 // `man_src`. FIRST shadowed everything the user curated,
2335 // `override_src` included (that is the `ls -<TAB>` regression
2336 // recorded in this comment's earlier revision). The host
2337 // tree's own index is after `override_src` and before the
2338 // appended plugin dirs, which is exactly where zsh has it.
2339 //
2340 // Measured on a 60-cell corpus of contested commands:
2341 // 1 PASS -> 57 PASS, zero regressions.
2342 match host_at {
2343 Some(i) if i <= fpath.len() => fpath.insert(i, d),
2344 _ => fpath.push(d),
2345 }
2346 }
2347 }
2348
2349 let history = std::cell::OnceCell::new();
2350
2351 // Seed canonical OPTS_LIVE with defaults BEFORE any setsparam
2352 // call. assignstrvalue early-returns when `unset(EXECOPT)`
2353 // (c:2701 guard); without the option table populated, EXECOPT
2354 // reads false and every paramtab write below is a silent no-op.
2355 if opt_state_len() == 0 {
2356 for (k, v) in Self::default_options() {
2357 opt_state_set(&k, v);
2358 }
2359 }
2360
2361 // c:Src/params.c:838-847 — `for (ip = special_params; ip->node.nam;
2362 // ip++) paramtab->addnode(paramtab, ztrdup(ip->node.nam), ip);`
2363 // The specials go into paramtab FIRST, ahead of every non-special
2364 // seed below, because creation ORDER is observable: a new key is
2365 // front-inserted into its bucket chain (c:Src/hashtable.c:214-215)
2366 // and `${(k)parameters}` prints that chain walk verbatim
2367 // (c:Src/hashtable.c:420-434). Seeding NULLCMD / FUNCNEST / PS1 /
2368 // … before this loop put them AHEAD of the specials they follow in
2369 // the C table (`#` at c:304 vs NULLCMD at c:378; UID at c:312 vs
2370 // FUNCNEST at c:366), which is exactly where zshrs's parameter
2371 // order diverged from zsh's. With the table seeded first, those
2372 // later `setsparam`/`setiparam` calls hit an existing node and
2373 // replace it IN PLACE (c:187-203 `replacing:`), keeping C's slot.
2374 // c:Src/params.c:384-394 — IPDEF8/IPDEF9 macros stamp
2375 // `PM_SCALAR|PM_SPECIAL` (IPDEF8 for `PATH`/`FPATH`/etc.) and
2376 // `PM_ARRAY|PM_SPECIAL|PM_DONTIMPORT` (IPDEF9 for `path`/
2377 // `fpath`/etc.) on every entry in the createparamtable table.
2378 // setsparam/setaparam above create plain PM_SCALAR/PM_ARRAY
2379 // entries; this loop applies the PM_SPECIAL + PM_TIED bits
2380 // (plus the IPDEF9 PM_DONTIMPORT bit on the array side) so
2381 // `${(t)PATH}` reads `scalar-tied-export-special` and
2382 // `${(t)path}` reads `array-tied-special`.
2383 //
2384 // Walks the `special_params` table (params.rs:464+) which is
2385 // the Rust port of the C IPDEF list. For each entry: OR the
2386 // declared pm_flags onto the existing paramtab entry. The
2387 // tied-pair entries (PM_TIED) also need PM_SPECIAL OR'd in
2388 // since the IPDEF8/IPDEF9 macros add PM_SPECIAL implicitly;
2389 // the table declares only the per-entry-distinct flags.
2390 let stamp_special_params = || {
2391 use crate::ported::params::{paramtab, special_params};
2392 use crate::ported::zsh_h::{PM_ARRAY, PM_DONTIMPORT, PM_SCALAR, PM_SPECIAL, PM_TIED};
2393 if let Ok(mut tab) = paramtab().write() {
2394 // Stamp PM_SPECIAL onto every entry the special_params
2395 // table declares. For tied scalars (PATH/FPATH/etc),
2396 // also walks `tied_name` to apply IPDEF9-flag bits
2397 // (PM_ARRAY|PM_SPECIAL|PM_DONTIMPORT|PM_TIED) onto the
2398 // partner array entry (path/fpath/etc) — those array
2399 // names aren't in the special_params table directly
2400 // but C zsh's createparamtable emits IPDEF9 rows for
2401 // them at Src/params.c:425-432.
2402 use crate::ported::zsh_h::{hashnode, param, PM_DONTIMPORT as PM_DI, PM_UNSET};
2403 // c:Src/params.c:838-847 — the first section is always
2404 // loaded; past it, sh/ksh emulation loads the untied scalar
2405 // `special_params_sh` rows INSTEAD of the zsh-only tail
2406 // (array-tied pairs, lowercase aliases, pipestatus):
2407 // if (EMULATION(EMULATE_SH|EMULATE_KSH))
2408 // for (ip = special_params_sh; ...) addnode(...);
2409 // else
2410 // while ((++ip)->node.nam) addnode(...);
2411 // `zsh --emulate sh -c 'typeset -p PATH'` therefore prints
2412 // `export PATH=…`, never `export -T PATH path=( … )`.
2413 let head = &special_params[..crate::ported::params::SPECIAL_PARAMS_ZSH_START];
2414 let tail: &[crate::ported::params::special_paramdef] = if crate::ported::zsh_h::EMULATION(
2415 crate::ported::zsh_h::EMULATE_SH | crate::ported::zsh_h::EMULATE_KSH,
2416 ) {
2417 crate::ported::params::special_params_sh // c:841-843
2418 } else {
2419 &special_params[crate::ported::params::SPECIAL_PARAMS_ZSH_START..] // c:845-847
2420 };
2421 for entry in head.iter().chain(tail.iter()) {
2422 // c:384/394 IPDEF8/9 — `D|PM_SCALAR|PM_SPECIAL` or
2423 // `D|PM_ARRAY|PM_SPECIAL|PM_DONTIMPORT`.
2424 //
2425 // Mask `entry.pm_flags` to the attribute bits that
2426 // may be OR'd onto an existing Param.
2427 //
2428 // PM_READONLY IS included. C declares it on 16 rows
2429 // via `PM_READONLY_SPECIAL` (c:Src/zsh.h:1925 —
2430 // `PM_SPECIAL|PM_READONLY|PM_RO_BY_DESIGN`): the
2431 // IPDEF1 pair `#`/`TTYIDLE` (c:304,314), IPDEF2 `-`
2432 // (c:318), the IPDEF4 block `!`/`$`/`?`/`HISTCMD`/
2433 // `LINENO`/`PPID`/`ZSH_SUBSHELL` (c:351-358) plus
2434 // `status` (c:424), IPDEF9 `*`/`@` (c:392-393) and
2435 // `zsh_eval_context` (c:438), and IPDEF8
2436 // `ZSH_EVAL_CONTEXT` (c:408). `special_params`
2437 // (params.rs:477+) declares exactly those 16 and no
2438 // others, so the bit lands on precisely C's set.
2439 //
2440 // An earlier revision stripped PM_READONLY here to
2441 // keep internal-runtime writes from tripping
2442 // `assignstrvalue`'s guard. Nearly all of those
2443 // writers already mutate the paramtab node in place
2444 // — exactly as C writes the backing C global behind
2445 // a no-op GSU (c:Src/params.c:351, IPDEF4 uses
2446 // `varint_readonly_gsu` =
2447 // `{intvargetfn, nullintsetfn, stdunsetfn}`). The
2448 // in-place sites are `fusevm_bridge.rs:242,261,13045`
2449 // (ZSH_SUBSHELL bump on `u_val`) and
2450 // `fusevm_bridge.rs:12590,12594,12714,12718` +
2451 // `exec.rs:7651,7655` (zsh_eval_context /
2452 // ZSH_EVAL_CONTEXT push+pop). None call
2453 // `setsparam`/`setiparam`.
2454 //
2455 // The ONE writer that did route through `setsparam`
2456 // was `endparamscope`'s deferred scope-pop restore
2457 // (`params.rs`, the `None =>` arm of the `deferred`
2458 // loop): with no GSU wired it name-routes the
2459 // restore and so re-entered the guard, emitting a
2460 // spurious `read-only variable: NAME` while
2461 // unwinding a scope that had shadowed one. C cannot
2462 // reach the guard there because c:5915-5933 calls
2463 // the setfn directly. That arm now drops the bit for
2464 // the duration of the restore, matching C.
2465 //
2466 // With that handled, restoring the flag costs the
2467 // runtime nothing while making `typeset X=v`,
2468 // `readonly X=v` and `X+=v` reject the way
2469 // c:Src/params.c:3216 does, and making
2470 // `paramtypestr` (c:Src/Modules/parameter.c:75-76)
2471 // emit the `-readonly` component that
2472 // `${parameters[X]}` is read for.
2473 //
2474 // PM_UNSET is included: lookup_special_var arms for
2475 // TRY_BLOCK_ERROR / TRY_BLOCK_INTERRUPT (and other
2476 // PM_UNSET entries with sentinel defaults) check
2477 // this bit to decide between "stored value" vs
2478 // "uninitialized → return -1 sentinel". The flag
2479 // gets cleared by assignstrvalue at c:3660 on any
2480 // write, so it correctly tracks "ever assigned".
2481 // Bug #143 in docs/BUGS.md.
2482 let safe_pm_flags = entry.pm_flags
2483 & (PM_TIED | PM_DI | PM_UNSET | crate::ported::zsh_h::PM_READONLY);
2484 // c:Src/params.c — IPDEF macros set PM_TYPE bits
2485 // (PM_INTEGER for IPDEF5/6, PM_ARRAY for IPDEF9,
2486 // PM_HASHED for IPDEF-hash) along with PM_SPECIAL.
2487 // zshrs's previous init only ORed PM_SPECIAL +
2488 // tied/di/unset/readonly — never the type bit. If
2489 // setsparam ran BEFORE init_partab_params (it does
2490 // for OPTIND/SHLVL at vm_helper.rs:874/878), the
2491 // param entry stayed PM_SCALAR and `typeset -p
2492 // OPTIND` emitted `typeset OPTIND=1` instead of
2493 // zsh's `typeset -i10 OPTIND=1`. OR the pm_type
2494 // into the bits so the type attribute lands.
2495 let mut bits = safe_pm_flags | PM_SPECIAL | entry.pm_type;
2496 // c:Src/zsh.h:1925 — `PM_READONLY_SPECIAL` is the
2497 // three-bit set `PM_SPECIAL|PM_READONLY|
2498 // PM_RO_BY_DESIGN`. `special_params` stores only
2499 // PM_READONLY per row (the other two are implied by
2500 // the IPDEF macro), so complete the triple here:
2501 // PM_SPECIAL is already OR'd into `bits` above, and
2502 // this adds the PM_RO_BY_DESIGN companion that
2503 // distinguishes a by-design readonly special from a
2504 // user `readonly` (c:Src/zsh.h:1923).
2505 if (entry.pm_flags & crate::ported::zsh_h::PM_READONLY) != 0 {
2506 bits |= crate::ported::zsh_h::PM_RO_BY_DESIGN;
2507 }
2508 if entry.pm_type == PM_ARRAY {
2509 bits |= PM_DI;
2510 }
2511 let _ = PM_SCALAR;
2512 let _ = PM_DONTIMPORT;
2513 if let Some(pm) = tab.get_mut(entry.name) {
2514 let was_integer =
2515 (pm.node.flags as u32 & crate::ported::zsh_h::PM_INTEGER) != 0;
2516 pm.node.flags |= bits as i32;
2517 // c:Src/params.c:344 IPDEF4 / c:353 IPDEF5 — the
2518 // C struct literal initialises the `base` field
2519 // to 10 for every PM_INTEGER special. zshrs's
2520 // initial paramtab seeding doesn't carry that
2521 // through (the special_paramdef table has no
2522 // `base` field). Set the default here so
2523 // `printparamnode`'s PMTF_USE_BASE arm at
2524 // params.rs:9341 emits "10" between
2525 // `integer` and the name (`integer 10 readonly
2526 // !=0`). Bug #297 in docs/BUGS.md.
2527 if entry.pm_type == crate::ported::zsh_h::PM_INTEGER && pm.base == 0 {
2528 pm.base = 10;
2529 }
2530 // When OR-ing PM_INTEGER onto a param that
2531 // was previously PM_SCALAR (i.e. setsparam ran
2532 // BEFORE init_partab_params, storing the value
2533 // in u_str), parse the u_str into u_val so the
2534 // integer getter reads the correct value. C
2535 // zsh's setsparam-equivalent path detects the
2536 // pm's PM_TYPE first and routes through
2537 // intsetfn, but zshrs's setsparam at the bin
2538 // entry point predates init_partab_params, so
2539 // it lands as PM_SCALAR storage that the
2540 // type-flip needs to migrate.
2541 if !was_integer
2542 && entry.pm_type == crate::ported::zsh_h::PM_INTEGER
2543 && pm.u_val == 0
2544 {
2545 if let Some(ref s) = pm.u_str {
2546 pm.u_val = s.parse::<i64>().unwrap_or(0);
2547 pm.u_str = None;
2548 }
2549 }
2550 // c:Src/zsh.h IPDEF8/IPDEF9 — the third macro
2551 // arg is the tied partner name; mapped into
2552 // `pm->ename` so `typeset -p` can find the
2553 // peer for the PM_TIED swap. Bug #410.
2554 if let Some(peer) = entry.tied_name {
2555 pm.ename = Some(peer.to_string());
2556 }
2557 } else {
2558 // Param hasn't been created yet (e.g. PATH gets
2559 // imported lazily via the env fallback in
2560 // getsparam at params.rs:4104; array specials
2561 // like `pipestatus` / `funcstack` / `dirstack`
2562 // / `zsh_scheduled_events` aren't pre-populated).
2563 // Seed an empty placeholder carrying the
2564 // canonical flag set so subsequent setsparam /
2565 // `(t)X` / `${+X}` observers see the IPDEF
2566 // attribute bits AND `${+X}` returns 1.
2567 let u_arr = if entry.pm_type == PM_ARRAY {
2568 Some(Vec::new())
2569 } else {
2570 None
2571 };
2572 let pm: crate::ported::zsh_h::Param = Box::new(param {
2573 node: hashnode {
2574 next: None,
2575 nam: entry.name.to_string(),
2576 flags: (entry.pm_type as i32) | bits as i32,
2577 },
2578 u_data: 0,
2579 u_tied: None,
2580 u_arr,
2581 u_str: None,
2582 u_val: 0,
2583 u_dval: 0.0,
2584 u_hash: None,
2585 gsu_s: None,
2586 gsu_i: None,
2587 gsu_f: None,
2588 gsu_a: None,
2589 gsu_h: None,
2590 // c:Src/params.c:344 IPDEF4 / c:353 IPDEF5 —
2591 // PM_INTEGER specials default base=10.
2592 base: if entry.pm_type == crate::ported::zsh_h::PM_INTEGER {
2593 10
2594 } else {
2595 0
2596 },
2597 width: 0,
2598 env: None,
2599 // c:Src/zsh.h IPDEF8/IPDEF9 — tied partner
2600 // name. Bug #410.
2601 ename: entry.tied_name.map(|s| s.to_string()),
2602 old: None,
2603 level: 0,
2604 });
2605 tab.insert(entry.name.to_string(), pm);
2606 }
2607 // Tied partner side. The previous loop body ORed
2608 // PM_ARRAY|PM_SPECIAL|PM_DONTIMPORT|PM_TIED onto the
2609 // partner indiscriminately, but for a SCALAR ↔
2610 // ARRAY tied pair (PATH ↔ path, FIGNORE ↔ fignore),
2611 // that incorrectly stamped PM_ARRAY onto the scalar
2612 // partner (FIGNORE, PATH, FPATH, MAILPATH, MANPATH,
2613 // PSVAR, CDPATH, MODULE_PATH). Result: `(t)PATH`
2614 // returned `array-tied-export-special` instead of
2615 // `scalar-tied-export-special`.
2616 //
2617 // Both partners are already listed in `special_params`
2618 // (the scalar at the IPDEF8 block, the array at the
2619 // IPDEF9 block past the sentinel), so each gets its
2620 // own pass through this loop and ends up with the
2621 // correct flags. No cross-stamping needed.
2622 let _ = entry.tied_name;
2623 }
2624 }
2625 };
2626 // c:Src/init.c:1277 — `inittyptab(); /* initialize the ztypes table */`
2627 // runs inside setupvals BEFORE `createparamtable()` (c:Src/init.c:1286).
2628 // This executor is the fusevm runtime's createparamtable entry point,
2629 // and the seeding below reaches `isident()` (WORDCHARS, …), which is
2630 // typtab-driven — with a zeroed typtab every name fails IIDENT and the
2631 // seed aborts with "not an identifier: WORDCHARS".
2632 crate::ported::utils::inittyptab(); // c:1277
2633 crate::startup_trace::mark("inittyptab");
2634 stamp_special_params(); // c:838-847 — create in C's order
2635 // Standard zsh scalar param defaults — direct port of
2636 // `createparamtable` (Src/params.c:817-988) + the `setupvals`
2637 // tail. Writes through canonical `setsparam` (Src/params.c:3350).
2638 //
2639 // c:params.c:972-973 — ZSH_VERSION / ZSH_PATCHLEVEL.
2640 // `zsh_version::ZSH_VERSION` (emitted by build.rs from the
2641 // vendored `Config/version.mk`) is the development snapshot
2642 // tag `5.9.0.3-test`; shipped zsh binaries report the clean
2643 // release form (`5.9`). Bug #73 in docs/BUGS.md — cross-shell
2644 // scripts that gate on `[[ $ZSH_VERSION = 5.9 ]]` or split on
2645 // `.` expecting MAJOR.MINOR break on the `-test` suffix.
2646 //
2647 // Use the cleaned `patchlevel::ZSH_VERSION` here ("5.9") and
2648 // surface the full snapshot tag as `$ZSHRS_VERSION` for
2649 // zshrs-specific identity checks.
2650 // ZSH_VERSION / ZSH_PATCHLEVEL / ZSHRS_VERSION / ZSH_NAME /
2651 // ZSH_ARGZERO are NOT seeded here: C creates them at the END of
2652 // `createparamtable` (c:970-973, after the environ import) and
2653 // ZSH_NAME at `Src/init.c:1364` (setupvals, later still). They
2654 // are seeded at those C positions further down, because a name
2655 // created before the import lands in a different chain slot —
2656 // `ZSH_NAME` seeded here came out BEHIND every same-bucket
2657 // environment variable in `${(k)parameters}` instead of ahead
2658 // of them (c:Src/hashtable.c:214-215 front-insert).
2659 setsparam("WORDCHARS", "*?_-.[]~=/&;!#$%^(){}<>");
2660 // SHLVL is NOT seeded here. c:Src/params.c:948-951 increments it
2661 // AFTER the environ-import loop, so the +1 lives at the end of that
2662 // loop below — see the `c:948-951` block. Doing it here instead meant
2663 // parsing the raw env string with `parse::<i32>()`, which mis-read
2664 // every non-decimal form C accepts via zstrtol_underscore
2665 // (SHLVL=0x10 must give 17, 010 → 9, 1_0 → 11, 9abc → 10, abc → 1).
2666 // POSIX/zsh default IFS: space + tab + newline + NUL.
2667 setsparam("IFS", " \t\n\0");
2668 // POSIX getopts: OPTIND starts at 1.
2669 setsparam("OPTIND", "1");
2670 // Note: OPTERR is NOT pre-initialised. zsh leaves it unset
2671 // even after `getopts` calls (verified: `getopts ":a" opt -a`
2672 // does not set it). It's a user-writable variable that
2673 // starts unset. Bug #150 in docs/BUGS.md.
2674 // zsh wipes inherited `$_` (unlike bash).
2675 setsparam("_", "");
2676 // c:params.c:5064 — histchars derives from bangchar+hatchar+
2677 // hashchar (defaults `!`, `^`, `#`). At init the special
2678 // entry may not exist yet — fall back to the literal default.
2679 let histchars_val = paramtab()
2680 .read()
2681 .ok()
2682 .and_then(|t| {
2683 t.get("histchars")
2684 .or_else(|| t.get("HISTCHARS"))
2685 .map(|pm| histcharsgetfn(pm))
2686 })
2687 .unwrap_or_else(|| "!^#".to_string());
2688 setsparam("histchars", &histchars_val);
2689
2690 // c:Src/params.c:870-871 — `setsparam("TIMEFMT", ...)` etc.
2691 // Seed TIMEFMT explicitly so `${(k)parameters}` lists it
2692 // (the createparamtable() ported in ported::params isn't
2693 // invoked from this bin entry — its setsparam calls don't
2694 // run, so TIMEFMT only existed via the lookup_special_var
2695 // fallback, which scanpmparameters can't see).
2696 setsparam("TIMEFMT", crate::ported::zsh_system_h::DEFAULT_TIMEFMT);
2697 // c:Src/params.c:892 — `setsparam("TMPPREFIX",
2698 // ztrdup_metafy(DEFAULT_TMPPREFIX));`, the line immediately
2699 // before the TIMEFMT seed above. `DEFAULT_TMPPREFIX` is
2700 // "/tmp/zsh" (c:configure.ac:3030 → config.h). Same reason as
2701 // TIMEFMT: createparamtable() is not reached from this bin
2702 // entry, so without this seed `$TMPPREFIX` existed only when
2703 // the environment happened to export it — every scrubbed-env
2704 // launch (cron, launchd/systemd unit, container entrypoint,
2705 // `env -i`) left it unset and every temp-file path derived
2706 // from it fell back per-call-site.
2707 //
2708 // C seeds unconditionally BEFORE the import loop (c:870 vs
2709 // c:893+) and the import then overwrites via assignsparam, so
2710 // an exported $TMPPREFIX still wins. zshrs's import only
2711 // rewrites an entry that is still PM_UNSET, so the env value is
2712 // resolved HERE instead — same end state, and the node is
2713 // created at C's position in the bucket chain. Skipping the
2714 // seed when the environment had TMPPREFIX (the previous shape)
2715 // deferred creation into the import loop, which put TMPPREFIX
2716 // behind every environment variable that hashes to its bucket.
2717 //
2718 // The lookup reads the process-entry environ snapshot, the same
2719 // source the import loop below walks (see the `environ` static
2720 // in ported::params for why the live environment is not it).
2721 let env_at_entry = |name: &str| -> Option<String> {
2722 crate::ported::params::environ
2723 .get()
2724 .and_then(|v| {
2725 v.iter()
2726 .find(|(k, _)| k == name)
2727 .map(|(_, val)| val.clone())
2728 })
2729 .or_else(|| std::env::var(name).ok())
2730 };
2731 setsparam(
2732 "TMPPREFIX",
2733 env_at_entry("TMPPREFIX")
2734 .as_deref()
2735 .unwrap_or(crate::ported::config_h::DEFAULT_TMPPREFIX),
2736 ); // c:870
2737 // c:Src/init.c:1214-1215 — `nullcmd = ztrdup("cat");
2738 // readnullcmd = ztrdup(DEFAULT_READNULLCMD);`. Real paramtab
2739 // seeds (NOT read-time fallbacks) so `unset NULLCMD` truly
2740 // unsets — the bare-redirect "redirection with no command"
2741 // diagnostic depends on getsparam returning None afterwards.
2742 // c:config.h:48 DEFAULT_READNULLCMD "more" — the parity
2743 // floor agrees: scrubbed-env Homebrew zsh 5.9.1 -fc reports
2744 // READNULLCMD=more (probed; the previous macOS arm's "less"
2745 // guess came from the USER's env exporting READNULLCMD=less
2746 // — zpwr sets it). This block runs AFTER the env import, so
2747 // these are DEFAULT seeds only: an env-imported value must
2748 // win (C seeds before the import loop, c:854-885 vs c:893+).
2749 if getsparam("NULLCMD").map_or(true, |v| v.is_empty()) {
2750 setsparam("NULLCMD", "cat");
2751 }
2752 if getsparam("READNULLCMD").map_or(true, |v| v.is_empty()) {
2753 setsparam("READNULLCMD", crate::ported::config_h::DEFAULT_READNULLCMD);
2754 }
2755 // c:Src/params.c:873-876 — `gethostname(hostnam, 256);
2756 // setsparam("HOST", ztrdup_metafy(hostnam));`
2757 // Seeded HERE, before the import loop, exactly like C; it used
2758 // to run at the very end of this constructor, which put HOST
2759 // ahead of same-bucket specials (PROMPT) that C creates first.
2760 // The env value is resolved up front for the same reason as
2761 // TMPPREFIX above (C's import would overwrite it).
2762 let mut host_buf = [0u8; 256];
2763 let host_rc = unsafe { libc::gethostname(host_buf.as_mut_ptr() as *mut libc::c_char, 256) }; // c:874
2764 let hostname = if host_rc == 0 {
2765 std::ffi::CStr::from_bytes_until_nul(&host_buf)
2766 .ok()
2767 .and_then(|c| c.to_str().ok())
2768 .unwrap_or("")
2769 .to_string()
2770 } else {
2771 String::new()
2772 };
2773 setsparam("HOST", env_at_entry("HOST").as_deref().unwrap_or(&hostname)); // c:875
2774 // c:Src/params.c:878-882 — `setsparam("LOGNAME", (str = getlogin())
2775 // && *str ? ztrdup_metafy(str) : ztrdup(cached_username));`
2776 // Also pre-import in C (c:878 vs c:893+); creating it during the
2777 // import instead put LOGNAME behind the environment variables
2778 // sharing its bucket.
2779 let logname_default = {
2780 let from_getlogin = unsafe {
2781 let p = libc::getlogin(); // c:880
2782 if p.is_null() {
2783 String::new()
2784 } else {
2785 std::ffi::CStr::from_ptr(p).to_string_lossy().into_owned()
2786 }
2787 };
2788 if from_getlogin.is_empty() {
2789 crate::ported::utils::get_username() // c:882 cached_username
2790 } else {
2791 from_getlogin
2792 }
2793 };
2794 setsparam(
2795 "LOGNAME",
2796 env_at_entry("LOGNAME")
2797 .as_deref()
2798 .unwrap_or(&logname_default),
2799 ); // c:878
2800 // c:Src/init.c:1186-1193 — default prompt strings. zsh sets
2801 // PS4 to "+%N:%i> " for ZSH emulation ("+ " for KSH/SH).
2802 // Without seeding, PS4 reads empty and `set -x` output has
2803 // no prefix at all. Bug #92 in docs/BUGS.md.
2804 //
2805 // C zsh runs createparamtable's env-import loop (c:893-924)
2806 // BEFORE init.c:1186 fires, so an exported $PS4 in the parent
2807 // env wins over the default seed. zshrs's env import happens
2808 // further down in ShellExecutor::new() (at the createparamtable
2809 // call site), so getsparam() reads None here even when env has
2810 // a value, and the default would clobber the user's PS4.
2811 //
2812 // Additional wrinkle: C zsh's PROMPT / PROMPT2 / PROMPT3 /
2813 // PROMPT4 params are ALIASES for PS1..PS4 (Src/params.c:381,
2814 // 415-421 — both IPDEF7R entries bind to the same `prompt*`
2815 // global). So `export PROMPT4=...` in the parent env sets the
2816 // shared global, and `$PS4` reads the same string. The user's
2817 // interactive shell exports PROMPT4 (the form zsh's prompt
2818 // theme system uses), so when zshrs -x runs, PROMPT4 is in
2819 // env but PS4 is not. Without aliasing in the env-probe step,
2820 // zshrs seeds default PS4 and ignores the user's customised
2821 // prefix.
2822 //
2823 // Probe env::var directly for the name AND its alias; first
2824 // non-empty wins. Only fall through to the default seed when
2825 // every candidate is empty. Mirrors C zsh's behavior without
2826 // reshuffling the rest of new(). Bug: `zshrs -x` ignored the
2827 // user's custom PS4/PROMPT4 unless re-forwarded with
2828 // `PS4=$PROMPT4 zshrs -x`.
2829 let seed_prompt = |name: &str, alias: Option<&str>, default: &str| {
2830 let cur = crate::ported::params::getsparam(name);
2831 let have_param = cur.as_deref().map_or(false, |s| !s.is_empty());
2832 if have_param {
2833 return;
2834 }
2835 // Probe primary name first, then the C-side alias.
2836 // An EMPTY exported value counts: C's env import (c:893-924)
2837 // assigns whatever `environ` holds, empty string included, and
2838 // it runs before the c:1196 defaults, so `export PS1=` yields
2839 // an empty prompt rather than `%m%# `. Testing only for a
2840 // NON-empty value skipped that case and re-seeded the default.
2841 for candidate in std::iter::once(name).chain(alias.into_iter()) {
2842 if let Ok(env_val) = std::env::var(candidate) {
2843 setsparam(name, &env_val);
2844 return;
2845 }
2846 }
2847 setsparam(name, default);
2848 };
2849 seed_prompt("PS4", Some("PROMPT4"), "+%N:%i> ");
2850 // c:Src/init.c:1181-1190 —
2851 // if(unset(INTERACTIVE)) {
2852 // prompt = ztrdup("");
2853 // prompt2 = ztrdup("");
2854 // } else ... {
2855 // prompt = ztrdup("%m%# ");
2856 // prompt2 = ztrdup("%_> ");
2857 // }
2858 // Non-interactive shells get EMPTY primary/secondary prompts
2859 // — `zsh -fc 'typeset'` lists PS1='' — while interactive ones
2860 // get the %m%# defaults. PS3/PS4/SPROMPT are seeded
2861 // unconditionally in C (c:1191-1194). PS1 may be reset by the
2862 // prompt-theme layer; only seed when the slot is empty so any
2863 // prior theme write wins.
2864 let interactive = crate::ported::zsh_h::isset(crate::ported::zsh_h::INTERACTIVE);
2865 seed_prompt(
2866 "PS1",
2867 Some("PROMPT"),
2868 if interactive { "%m%# " } else { "" },
2869 );
2870 seed_prompt(
2871 "PS2",
2872 Some("PROMPT2"),
2873 if interactive { "%_> " } else { "" },
2874 );
2875 // c:Src/init.c:1191 — `prompt3 = ztrdup("?# ");`
2876 seed_prompt("PS3", Some("PROMPT3"), "?# ");
2877 // c:Src/init.c:1194 — `sprompt = ztrdup("zsh: correct '%R'
2878 // to '%r' [nyae]? ");` — spelling-correction prompt.
2879 seed_prompt("SPROMPT", None, "zsh: correct '%R' to '%r' [nyae]? ");
2880 // c:Src/params.c:417-422 — `PROMPT*` aliases for `PS*`.
2881 // C zsh's IPDEF7("PROMPT", &prompt), IPDEF7("PROMPT2",
2882 // &prompt2), IPDEF7("PROMPT3", &prompt3), IPDEF7("PROMPT4",
2883 // &prompt4) all point to the same C globals as the matching
2884 // IPDEF7("PS{1..4}", ...) entries — they're aliases in C,
2885 // sharing storage. zshrs's paramtab keeps them as separate
2886 // entries; mirror the alias by mirroring the value here.
2887 // Bug #274 in docs/BUGS.md (PROMPT3 was the visible report;
2888 // PROMPT/PROMPT2/PROMPT4 had the same gap silently).
2889 for (alias, source) in &[
2890 ("PROMPT", "PS1"),
2891 ("PROMPT2", "PS2"),
2892 ("PROMPT3", "PS3"),
2893 ("PROMPT4", "PS4"),
2894 ] {
2895 if crate::ported::params::getsparam(alias).map_or(true, |s| s.is_empty()) {
2896 if let Some(v) = crate::ported::params::getsparam(source) {
2897 setsparam(alias, &v);
2898 }
2899 }
2900 }
2901 // c:params.c:858-860 — standard non-special param defaults.
2902 // C uses `setiparam(...)` (PM_INTEGER) for these so
2903 // `(t)MAILCHECK` etc. report `integer`. zshrs previously
2904 // routed through `setsparam` (PM_SCALAR) — the value worked
2905 // but the type bit was wrong, breaking
2906 // `case "${(t)LISTMAX}" in *integer*)` and any path that
2907 // gates on arithmetic-typed semantics. Bug #268 in
2908 // docs/BUGS.md.
2909 crate::ported::params::setiparam("MAILCHECK", 60); // c:858
2910 crate::ported::params::setiparam("KEYTIMEOUT", 40); // c:859
2911 crate::ported::params::setiparam("LISTMAX", 100); // c:860
2912 // c:config.h:1004 — MAX_FUNCTION_DEPTH=500. Advisory cap;
2913 // dispatch_function_call enforces against this.
2914 crate::ported::params::setiparam("FUNCNEST", 500);
2915
2916 // Run setlocale(LC_ALL, "") so nl_langinfo() (used by the
2917 // `langinfo` module) returns the host's actual locale instead
2918 // of the C/POSIX default ("US-ASCII"). Direct port of zsh's
2919 // Src/init.c:1208 setlocale call. unsafe { } around libc is
2920 // standard for this exact use-case — setlocale is process-
2921 // global and must run once at startup.
2922 unsafe {
2923 libc::setlocale(libc::LC_ALL, c"".as_ptr());
2924 }
2925
2926 // c:hashtable.c:1206 createaliastables() — seeds aliastab with
2927 // the `run-help` / `which-command` defaults. Run once at shell
2928 // init so the canonical port owns the default-alias set; the
2929 // Executor's `aliases` HashMap then mirrors aliastab.
2930 crate::ported::hashtable::createaliastables();
2931 crate::startup_trace::mark("createaliastables");
2932 // Build the initial $path tied array as a local — fans out
2933 // to paramtab below; no ShellExecutor mirror anymore.
2934 let mut arrays: HashMap<String, Vec<String>> = HashMap::new();
2935 // c:Src/init.c:1125-1130 — `path` starts as the compiled-in default;
2936 // an inherited $PATH replaces it in the environ import. With no PATH
2937 // in the environment the default stands and is not exported.
2938 let path_dirs: Vec<String> = match env::var("PATH") {
2939 Ok(p) => p.split(':').map(|s| s.to_string()).collect(),
2940 Err(_) => ["/bin", "/usr/bin", "/usr/ucb", "/usr/local/bin"] // c:1126-1129
2941 .iter()
2942 .map(|s| s.to_string())
2943 .collect(),
2944 };
2945 arrays.insert("path".to_string(), path_dirs);
2946 let mut exec = Self {
2947 // c:Src/init.c:479 — `-c` mode: scriptname = scriptfilename
2948 // = ztrdup("zsh"). Both start at the literal "zsh".
2949 // dispatch_function_call overrides scriptname per c:5903;
2950 // scriptfilename stays at the outer file.
2951 scriptname: Some("zsh".to_string()),
2952 scriptfilename: Some("zsh".to_string()),
2953 subshell_snapshots: Vec::new(),
2954 inline_env_stack: Vec::new(),
2955 current_command_glob_failed: std::cell::Cell::new(false),
2956 jobs: JobTable::new(),
2957 fpath,
2958 history,
2959 completions: HashMap::new(),
2960 process_sub_counter: 0,
2961 zstyles: Vec::new(),
2962 local_scope_depth: 0,
2963 pending_underscore: None,
2964 in_dq_context: 0,
2965 in_scalar_assign: 0,
2966 profiling_enabled: false,
2967 compsys_cache: std::cell::OnceCell::new(),
2968 compinit_pending: None, // (receiver, start_time)
2969 plugin_cache: {
2970 let pc_path = crate::plugin_cache::default_cache_path();
2971 if let Some(parent) = pc_path.parent() {
2972 let _ = fs::create_dir_all(parent);
2973 }
2974 match crate::plugin_cache::PluginCache::open(&pc_path) {
2975 Ok(pc) => {
2976 let (plugins, functions) = pc.stats();
2977 tracing::info!(
2978 plugins,
2979 cached_functions = functions,
2980 path = %pc_path.display(),
2981 "plugin_cache: sqlite opened"
2982 );
2983 Some(pc)
2984 }
2985 Err(e) => {
2986 // A corrupt cache file is not a permanent condition:
2987 // `plugins.db` is derived data, rebuilt by the next
2988 // plugin scan. SQLite answers a clobbered header with
2989 // SQLITE_NOTADB ("file is not a database"), and the
2990 // old behaviour logged that and moved on — so the
2991 // cache stayed dead for every future shell too, with
2992 // nothing but a log line to say why plugin lookups
2993 // were slow. Discard the file and open once more;
2994 // this is the same "drop it and rebuild silently"
2995 // rule the shard cache already applies to a version
2996 // mismatch. A second failure keeps the old
2997 // behaviour, so a permissions problem still degrades
2998 // instead of looping.
2999 let corrupt = matches!(
3000 e.sqlite_error_code(),
3001 Some(rusqlite::ErrorCode::NotADatabase)
3002 | Some(rusqlite::ErrorCode::DatabaseCorrupt)
3003 );
3004 if corrupt {
3005 tracing::warn!(
3006 error = %e,
3007 path = %pc_path.display(),
3008 "plugin_cache: corrupt — discarding and rebuilding"
3009 );
3010 let _ = fs::remove_file(&pc_path);
3011 // The -wal/-shm side files belong to the database
3012 // that just went away; leaving them makes the
3013 // fresh open inherit a journal for a file that no
3014 // longer exists.
3015 for side in ["-wal", "-shm"] {
3016 let mut p = pc_path.clone().into_os_string();
3017 p.push(side);
3018 let _ = fs::remove_file(PathBuf::from(p));
3019 }
3020 match crate::plugin_cache::PluginCache::open(&pc_path) {
3021 Ok(pc) => {
3022 tracing::info!(
3023 path = %pc_path.display(),
3024 "plugin_cache: rebuilt after corruption"
3025 );
3026 Some(pc)
3027 }
3028 Err(e2) => {
3029 tracing::warn!(error = %e2, "plugin_cache: reopen after discard failed");
3030 None
3031 }
3032 }
3033 } else {
3034 tracing::warn!(error = %e, "plugin_cache: failed to open");
3035 None
3036 }
3037 }
3038 }
3039 },
3040 deferred_compdefs: Vec::new(),
3041 returning: None,
3042 zsh_compat: false,
3043 bash_compat: false,
3044 posix_mode: false,
3045 worker_pool: {
3046 let config = crate::config::load();
3047 let pool_size = crate::config::resolve_pool_size(&config.worker_pool);
3048 std::sync::Arc::new(crate::worker::WorkerPool::new(pool_size))
3049 },
3050 intercepts: Vec::new(),
3051 async_jobs: HashMap::new(),
3052 next_async_id: 1,
3053 redirect_scope_stack: Vec::new(),
3054 multios_scope_stack: Vec::new(),
3055 exec_redirs_permanent: false,
3056 pipe_output_pending: false,
3057 pipe_output_scope: None,
3058 redirect_failed: false,
3059 functions_compiled: crate::cow_map::CowHashMap::new(),
3060 function_source: crate::cow_map::CowHashMap::new(),
3061 function_line_base: HashMap::new(),
3062 function_def_file: HashMap::new(),
3063 prompt_funcstack: Vec::new(),
3064 tied_array_to_scalar: HashMap::new(),
3065 ztest_pass_count: std::sync::atomic::AtomicUsize::new(0),
3066 ztest_fail_count: std::sync::atomic::AtomicUsize::new(0),
3067 ztest_skip_count: std::sync::atomic::AtomicUsize::new(0),
3068 ztest_pass_total: std::sync::atomic::AtomicUsize::new(0),
3069 ztest_fail_total: std::sync::atomic::AtomicUsize::new(0),
3070 ztest_skip_total: std::sync::atomic::AtomicUsize::new(0),
3071 ztest_run_failed: std::sync::atomic::AtomicBool::new(false),
3072 ztest_suppress_stdout: false,
3073 };
3074 // Publish the session worker pool so preprompt-time async hooks
3075 // (async_precmd) can reach it without an entered executor context.
3076 crate::async_precmd::set_session_pool(std::sync::Arc::clone(&exec.worker_pool));
3077 crate::startup_trace::mark("worker pool ready");
3078 // Mirror env-derived path arrays into the `arrays` table so
3079 // user-level `fpath` / `path` array reads see the inherited
3080 // entries. zsh: `fpath+=…` should append to the inherited
3081 // 43-entry array, not replace it. Same for `path` (PATH).
3082 crate::startup_trace::mark("exec struct built");
3083 let fpath_arr: Vec<String> = exec
3084 .fpath
3085 .iter()
3086 .map(|p| p.to_string_lossy().to_string())
3087 .collect();
3088 if !fpath_arr.is_empty() {
3089 exec.set_array("fpath".to_string(), fpath_arr);
3090 }
3091 if let Ok(path) = env::var("PATH") {
3092 let path_arr: Vec<String> = path
3093 .split(':')
3094 .filter(|s| !s.is_empty())
3095 .map(String::from)
3096 .collect();
3097 if !path_arr.is_empty() {
3098 exec.set_array("path".to_string(), path_arr);
3099 }
3100 }
3101 // Register the standard tied path-family pairs so `path+=` /
3102 // `fpath+=` / etc. mirror through the array→scalar sync hook
3103 // in BUILTIN_APPEND_ARRAY (and the SET_ARRAY tied path).
3104 // Direct port of the implicit ties that zsh wires up at
3105 // startup for PATH/path, FPATH/fpath, etc. Source-of-truth
3106 // for the pairs is Src/init.c's `setupvals()` PM_TIED entries.
3107 // c:Src/params.c:395-422 IPDEF8 — full PM_TIED colonarr list:
3108 // CDPATH, FIGNORE, FPATH, MAILPATH, PATH, PSVAR, MODULE_PATH,
3109 // MANPATH (ZSH_EVAL_CONTEXT is readonly-special, excluded).
3110 for (scalar, arr) in [
3111 ("PATH", "path"),
3112 ("FPATH", "fpath"),
3113 ("MANPATH", "manpath"),
3114 ("CDPATH", "cdpath"),
3115 ("MODULE_PATH", "module_path"),
3116 ("PSVAR", "psvar"),
3117 ("FIGNORE", "fignore"),
3118 ("MAILPATH", "mailpath"),
3119 ] {
3120 exec.tied_array_to_scalar
3121 .insert(arr.to_string(), (scalar.to_string(), ":".to_string()));
3122 }
3123
3124 // Pour `path` (from env PATH split) into paramtab. The IPDEF9
3125 // flag set was stamped by the c:838-847 pass above and survives
3126 // the assignment (`assignaparam` keeps PM_DONTIMPORT on a
3127 // PM_SPECIAL node — c:3374 + params.rs), so no re-stamp is
3128 // needed here.
3129 for (k, v) in &arrays {
3130 setaparam(k, v.clone()); // c:params.c:3595
3131 }
3132
3133 // c:Src/params.c:893-924 — the environment import runs AFTER the
3134 // specials table (moved above, c:838-847) and after the c:854-885
3135 // non-special seeds, exactly as `createparamtable` sequences them.
3136 //
3137 // Carries c:951's `addenv(pm, buf)` argument out of the paramtab
3138 // write-lock below: `addenv` takes that same lock itself, so the call
3139 // cannot be made while the guard is alive.
3140 let mut shlvl_env: Option<String> = None;
3141 // !!! LOCK DISCIPLINE — NO GSU CALLBACK MAY RUN UNDER THE PARAMTAB GUARD !!!
3142 //
3143 // C's import loop calls `assignsparam(..., ASSPM_ENV_IMPORT)` (c:907-908)
3144 // and holds no lock at all, so a setfn reached from there is free to read
3145 // any parameter — and several do. `intsetfn` name-dispatches `$COLUMNS` /
3146 // `$LINES` to `zlevarsetfn` (c:4226), which re-enters `adjustwinsize`,
3147 // which falls back to `getsparam("COLUMNS")` when its ioctl comes back
3148 // empty. `paramtab()` is a non-reentrant `std::sync::RwLock`, so running
3149 // that under the write guard below parked the shell on itself:
3150 //
3151 // COLUMNS=200 zshrs -f -c 'print $COLUMNS'
3152 //
3153 // never printed anything and never exited, with `sample` showing
3154 // 2665/2665 samples in `semaphore_wait_trap` down
3155 // `ShellExecutor::new → intsetfn → zlevarsetfn → adjustwinsize →
3156 // adjustlines → getsparam → RwLock::lock_contended`. That is the same
3157 // chain 5929e82b81 diagnosed on the startup path; that fix removed a
3158 // Rust-only return value from `adjustwinsize` so the ONE caller it knew
3159 // about stopped re-entering, and left the pattern in place for this one.
3160 //
3161 // So the dispatches are queued here and replayed after the guard is
3162 // released, the way `shlvl_env` and `tied_env_arrays` already are. One
3163 // queue, not one per signature, because C's order is per-variable and
3164 // must survive: `termsetfn` populates the termcap geometry that a later
3165 // `$LINES` import reads back through `adjustwinsize`.
3166 enum DeferredEnvSetfn {
3167 /// c:2774 — `v->pm->gsu.i->setfn(v->pm, ival)`.
3168 Int(String, i64),
3169 /// c:907-908 — the cached-storage scalar specials' setfn.
3170 Scalar(String, String),
3171 }
3172 let mut deferred_env_setfns: Vec<DeferredEnvSetfn> = Vec::new();
3173 {
3174 use crate::ported::params::paramtab;
3175 if let Ok(mut tab) = paramtab().write() {
3176 use crate::ported::zsh_h::{param, PM_UNSET};
3177 // c:Src/params.c:893-924 environment-import loop —
3178 // every env var gets either a fresh exported paramtab
3179 // entry OR (when the entry pre-exists from
3180 // special_params) PM_EXPORTED OR'd onto its flags.
3181 // Without this, `declare -p PATH` printed `typeset -T
3182 // PATH=''` and `declare -p USER` printed nothing at
3183 // all because USER was never in paramtab.
3184 use crate::ported::zsh_h::hashnode as _hn;
3185 use crate::ported::zsh_h::{PM_EXPORTED, PM_SCALAR};
3186 // c:Src/params.c:4329-4342 colonarrsetfn — assigning a
3187 // tied IPDEF8 scalar (MANPATH, CDPATH, MODULE_PATH, …)
3188 // colonsplit()s the value into the partner array,
3189 // preserving empty components. The env import below
3190 // bypasses the GSU setfn, so collect the tied pairs
3191 // here and pour them through setaparam after the
3192 // paramtab lock drops. PATH→path / FPATH→fpath are
3193 // seeded earlier (vm_helper ~1160-1199) and skipped.
3194 let mut tied_env_arrays: Vec<(String, Vec<String>)> = Vec::new();
3195 // c:Src/params.c:893 — walk the process-entry environ
3196 // snapshot, not the live env (frameworks can mutate it
3197 // before init — see params.rs `environ` static).
3198 let environ_vars: Vec<(String, String)> = crate::ported::params::environ
3199 .get()
3200 .cloned()
3201 .unwrap_or_else(|| std::env::vars().collect());
3202 for (env_name, env_value) in environ_vars {
3203 if env_name.is_empty() || env_name.contains('[') {
3204 continue;
3205 }
3206 if env_name.as_bytes()[0].is_ascii_digit() {
3207 continue;
3208 }
3209 if !crate::ported::params::isident(&env_name) {
3210 continue;
3211 }
3212 if let Some(pm) = tab.get_mut(&env_name) {
3213 // c:Src/params.c:902-906 — the import loop runs
3214 // `dontimport(pm->node.flags)` BEFORE doing
3215 // anything to the entry; PM_DONTIMPORT names
3216 // (`_`, IFS, GID/EGID, KEYBOARD_HACK — the
3217 // IPDEF7/IPDEF2 rows, c:796-800) are skipped
3218 // ENTIRELY: no PM_EXPORTED stamp, no value
3219 // seed. zshrs previously OR'd PM_EXPORTED
3220 // first, so an inherited env `_` made the
3221 // special `_` exported and it leaked into
3222 // `typeset +x -r` / `export -p` listings where
3223 // zsh shows nothing.
3224 if (pm.node.flags as u32 & crate::ported::zsh_h::PM_DONTIMPORT) != 0 {
3225 continue; // c:905 `continue;`
3226 }
3227 pm.node.flags |= PM_EXPORTED as i32;
3228 // c:Src/params.c:2769-2776 — assignstrvalue's
3229 // PM_INTEGER arm, which C's env import reaches via
3230 // `assignsparam(..., ASSPM_ENV_IMPORT)` (c:907-908;
3231 // assignsparam forwards its `flags` verbatim at
3232 // c:params.c assignstrvalue(v, val, flags)):
3233 // if (flags & ASSPM_ENV_IMPORT) {
3234 // char *ptr;
3235 // ival = zstrtol_underscore(val, &ptr, 0, 1);
3236 // } else
3237 // ival = mathevali(val);
3238 // v->pm->gsu.i->setfn(v->pm, ival);
3239 // An integer param keeps its value in `u.val`, NOT in
3240 // the scalar slot, so the `pm.u_str = env_value` seed
3241 // below stored the digits somewhere no integer reader
3242 // ever looks and EVERY pre-existing PM_INTEGER param
3243 // silently ignored the environment: COLUMNS/LINES
3244 // (IPDEF5, c:355-356) read back 0, while HISTSIZE,
3245 // SAVEHIST, LISTMAX, MAILCHECK, KEYTIMEOUT and
3246 // FUNCNEST kept their built-in defaults — i.e.
3247 // `HISTSIZE=5000 zshrs -c ...` was a no-op.
3248 //
3249 // Base 0 + underscore=1 is not incidental: it is what
3250 // makes `COLUMNS=0x10` 16, `COLUMNS=0b101` 5,
3251 // `COLUMNS=010` 8 (octal — c:utils.c:2452-2461 takes
3252 // the leading `0` then falls to `base = 8`),
3253 // `COLUMNS=1_0` 10, and a trailing-garbage value like
3254 // `9abc` a silent 9. mathevali would instead ERROR on
3255 // `9abc`, which is precisely why C splits the two
3256 // paths — importing a hostile environment must not
3257 // abort the shell (upstream 546203a770, "33276: safer
3258 // import of numerical variables from environment").
3259 if (pm.node.flags as u32 & crate::ported::zsh_h::PM_INTEGER) != 0 {
3260 let (ival, _) =
3261 crate::ported::utils::zstrtol_underscore(&env_value, 0, true); // c:2773
3262 // c:3660 — any assignstrvalue write clears PM_UNSET.
3263 pm.node.flags &= !(PM_UNSET as i32);
3264 // c:2774 — `v->pm->gsu.i->setfn(v->pm, ival)`.
3265 // intsetfn is this port's stand-in for the gsu_i
3266 // vtable: it name-dispatches the specials whose
3267 // setter has side effects (SECONDS, RANDOM,
3268 // HISTSIZE, …) and writes u.val otherwise. Queued,
3269 // not called: see the lock-discipline note above.
3270 //
3271 // The plain storage half of the setfn still lands
3272 // HERE, synchronously, because C's write is
3273 // synchronous and code further down this same guard
3274 // reads it back: the c:948-951 SHLVL block computes
3275 // `++shlvl` from the value this loop just imported,
3276 // and the C comment on it ("the increment must
3277 // observe the imported value") is load-bearing.
3278 // Deferring the storage too made `SHLVL=5 zshrs -f
3279 // -c 'print $SHLVL'` answer 1 instead of 6. The
3280 // queued dispatch then re-applies it along with the
3281 // side effects only it can produce.
3282 pm.u_val = ival; // c:2774 (the `pm->u.val = x` half)
3283 deferred_env_setfns
3284 .push(DeferredEnvSetfn::Int(env_name.clone(), ival)); // c:2774
3285 pm.env = Some(format!("{env_name}={env_value}"));
3286 continue;
3287 }
3288 // c:Src/params.c:893-924 — C's env-import calls
3289 // `assignsparam(..., ASSPM_ENV_IMPORT)` which
3290 // routes through the param's GSU setfn. For
3291 // SPECIAL scalars with cached storage (HOME,
3292 // USERNAME, TERM, WORDCHARS, TERMINFO,
3293 // TERMINFO_DIRS, KEYBOARD_HACK, histchars) the
3294 // setfn writes to a separate `*_lock` global
3295 // (e.g. home_lock). Just OR'ing PM_EXPORTED
3296 // leaves those globals empty, so `$HOME` reads
3297 // back "" even though HOME is in env. Mirror
3298 // C by copying the env value into pm.u_str and
3299 // (for cached specials) the matching global.
3300 // Only seed cached state when the param was
3301 // still marked PM_UNSET — i.e. nothing has set
3302 // it yet. ShellExecutor::new's earlier init
3303 // block (vm_helper line 837+) already ran
3304 // setsparam for a few names (ZSH_ARGZERO,
3305 // WORDCHARS, SHLVL with the +1 increment, IFS,
3306 // OPTIND, …); those calls clear PM_UNSET so we
3307 // must not overwrite them with the raw env
3308 // value here. The PM_UNSET-still-set case is
3309 // the "C zsh would have called
3310 // assignsparam(...,ASSPM_ENV_IMPORT) and ours
3311 // didn't yet" gap that bug #599 (HOME=` `) and
3312 // %~ prompt expansion need.
3313 let still_unset =
3314 (pm.node.flags as u32 & crate::ported::zsh_h::PM_UNSET) != 0;
3315 if still_unset {
3316 pm.u_str = Some(env_value.clone());
3317 pm.env = Some(format!("{}={}", env_name, env_value));
3318 // c:Src/params.c:3660 — `assignstrvalue`
3319 // clears PM_UNSET on any write. HOME / TERM
3320 // / TERMINFO / TERMINFO_DIRS / WORDCHARS
3321 // start life with PM_UNSET in
3322 // `special_params` (params.rs SPECIAL_PARAMS
3323 // table) so `lookup_special_var` skips the
3324 // getfn for uninitialized specials; env
3325 // import is the canonical "now it's set"
3326 // event, so clear the bit.
3327 pm.node.flags &= !(PM_UNSET as i32);
3328 // Cached-state specials: route through
3329 // the matching setfn so the global cache
3330 // (home_lock / wordchars_lock / etc.)
3331 // reflects the env value. Queued, not
3332 // called: see the lock-discipline note
3333 // above. `termsetfn` in particular reaches
3334 // the terminal setup, which is exactly the
3335 // kind of callee that reads parameters.
3336 if matches!(
3337 env_name.as_str(),
3338 "HOME"
3339 | "USERNAME"
3340 | "TERM"
3341 | "WORDCHARS"
3342 | "TERMINFO"
3343 | "TERMINFO_DIRS"
3344 ) {
3345 deferred_env_setfns.push(DeferredEnvSetfn::Scalar(
3346 env_name.clone(),
3347 env_value.clone(),
3348 )); // c:907-908
3349 }
3350 }
3351 // c:Src/params.c:907-908 — env import always
3352 // assigns through the GSU setfn; for tied
3353 // IPDEF8 scalars that is colonarrsetfn
3354 // (c:4329-4342), which colonsplit()s the value
3355 // into the partner array, empties preserved.
3356 // Not gated on still_unset: C re-assigns on
3357 // import regardless.
3358 if (pm.node.flags as u32 & crate::ported::zsh_h::PM_TIED) != 0 {
3359 if let Some(ref peer) = pm.ename {
3360 if peer != "path" && peer != "fpath" {
3361 tied_env_arrays.push((
3362 peer.clone(),
3363 env_value.split(':').map(String::from).collect(), // c:4339 colonsplit
3364 ));
3365 }
3366 }
3367 }
3368 } else {
3369 // Fresh entry — PM_SCALAR + PM_EXPORTED, value
3370 // taken from env. Mirrors C zsh's c:907-908
3371 // `assignsparam(..., ASSPM_ENV_IMPORT)` for
3372 // names not already in the special table.
3373 let pm: crate::ported::zsh_h::Param = Box::new(param {
3374 node: _hn {
3375 next: None,
3376 nam: env_name.clone(),
3377 flags: (PM_SCALAR | PM_EXPORTED) as i32,
3378 },
3379 u_data: 0,
3380 u_tied: None,
3381 u_arr: None,
3382 u_str: Some(env_value.clone()),
3383 u_val: 0,
3384 u_dval: 0.0,
3385 u_hash: None,
3386 gsu_s: None,
3387 gsu_i: None,
3388 gsu_f: None,
3389 gsu_a: None,
3390 gsu_h: None,
3391 base: 0,
3392 width: 0,
3393 env: Some(format!("{}={}", env_name, env_value)),
3394 ename: None,
3395 old: None,
3396 level: 0,
3397 });
3398 tab.insert(env_name, pm);
3399 }
3400 }
3401 // Apply the collected tied-pair splits after the env
3402 // walk. setaparam (the canonical store) needs the
3403 // same paramtab write lock held here, so write u_arr
3404 // directly on the peer entry — array reads route
3405 // through paramtab so this is the single store.
3406 for (peer, parts) in tied_env_arrays {
3407 if let Some(apm) = tab.get_mut(peer.as_str()) {
3408 apm.u_arr = Some(parts); // c:4339 — `*dptr = colonsplit(x, …)`
3409 apm.node.flags &= !(crate::ported::zsh_h::PM_UNSET as i32);
3410 }
3411 }
3412 // c:Src/params.c:948-951 — runs AFTER the import loop:
3413 // pm = (Param) paramtab->getnode(paramtab, "SHLVL");
3414 // sprintf(buf, "%d", (int)++shlvl);
3415 // /* shlvl value in environment needs updating unconditionally */
3416 // addenv(pm, buf);
3417 // SHLVL is `IPDEF5("SHLVL", &shlvl, varinteger_gsu)` (c:358), so
3418 // the loop above has already parsed any inherited value into it
3419 // with zstrtol_underscore; C then increments THAT, in place.
3420 // Ordering is the whole point: the increment must observe the
3421 // imported value, and the import must not clobber the
3422 // increment. When SHLVL is absent from the environment the
3423 // param is still 0 here, so ++ yields 1 — matching C, whose
3424 // `shlvl` global starts at 0.
3425 //
3426 // addenv also exports the INCREMENTED value, which is why a
3427 // forked child sees 6 for `SHLVL=5 zsh -fc 'printenv SHLVL; true'`.
3428 // (A bare `printenv SHLVL` shows 5 because zsh exec's the last
3429 // command in place and backs the increment out — the shell is
3430 // being replaced, not nested. That is a separate mechanism,
3431 // ported for the explicit `exec` form at
3432 // fusevm_bridge.rs's BUILTIN_EXEC.)
3433 if let Some(pm) = tab.get_mut("SHLVL") {
3434 let next = pm.u_val + 1; // c:949 `++shlvl`
3435 // Queued like the import loop's dispatches above — SHLVL's
3436 // setfn is a leaf today, but the rule is the pattern, not
3437 // the current callee list. Storage half applied here for
3438 // the same reason it is up there: c:951's `addenv` and
3439 // everything after this guard must see the incremented
3440 // value.
3441 pm.u_val = next; // c:949 (the `*pm->u.valptr = x` half)
3442 deferred_env_setfns.push(DeferredEnvSetfn::Int("SHLVL".to_string(), next)); // c:949
3443 pm.node.flags &= !(PM_UNSET as i32);
3444 // c:951 — the argument of the unconditional `addenv`.
3445 // C renders it with `sprintf(buf, "%d", (int)shlvl)`
3446 // AFTER the increment, so it is the incremented value.
3447 shlvl_env = Some(next.to_string()); // c:950
3448 }
3449 }
3450 }
3451 // ---- paramtab guard released; replay the queued dispatches ----
3452 //
3453 // This is the c:907-908 / c:2774 / c:949 setfn call, moved to where no
3454 // lock is held, in the order C makes it. Each one runs against a
3455 // detached node — which is what C's pointer-to-the-live-node amounts to
3456 // once the lock is out of the way — and the integer arm publishes the
3457 // union slot the setfn wrote back onto the table afterwards. The scalar
3458 // specials need no publish: their setfns write a cached global
3459 // (`home_lock`, `wordchars_lock`, …) and ignore `pm`, matching C's
3460 // `UNUSED(Param pm)`. A node the setfn removed outright is simply
3461 // skipped.
3462 for deferred in deferred_env_setfns {
3463 match deferred {
3464 DeferredEnvSetfn::Int(name, ival) => {
3465 let staged = crate::ported::params::paramtab()
3466 .read()
3467 .ok()
3468 .and_then(|tab| tab.get(name.as_str()).map(|pm| (**pm).clone()));
3469 let Some(mut staged) = staged else { continue };
3470 crate::ported::params::intsetfn(&mut staged, ival); // c:2774
3471 if let Ok(mut tab) = crate::ported::params::paramtab().write() {
3472 if let Some(pm) = tab.get_mut(name.as_str()) {
3473 pm.u_val = staged.u_val;
3474 }
3475 }
3476 }
3477 DeferredEnvSetfn::Scalar(name, value) => {
3478 let staged = crate::ported::params::paramtab()
3479 .read()
3480 .ok()
3481 .and_then(|tab| tab.get(name.as_str()).map(|pm| (**pm).clone()));
3482 let Some(mut staged) = staged else { continue };
3483 match name.as_str() {
3484 "HOME" => crate::ported::params::homesetfn(&mut staged, value),
3485 "USERNAME" => crate::ported::params::usernamesetfn(&mut staged, value),
3486 "TERM" => crate::ported::params::termsetfn(&mut staged, value),
3487 "WORDCHARS" => crate::ported::params::wordcharssetfn(&mut staged, value),
3488 "TERMINFO" => crate::ported::params::terminfosetfn(&mut staged, value),
3489 "TERMINFO_DIRS" => {
3490 crate::ported::params::terminfodirssetfn(&mut staged, value)
3491 }
3492 _ => {}
3493 }
3494 }
3495 }
3496 }
3497 // c:Src/params.c:960-965 — HOME wiring, which C runs right
3498 // after the environment-import loop:
3499 // pm = (Param) realparamtab->getnode2(realparamtab, "HOME");
3500 // if (EMULATION(EMULATE_ZSH))
3501 // {
3502 // pm->node.flags &= ~PM_UNSET;
3503 // if (!(pm->node.flags & PM_EXPORTED))
3504 // addenv(pm, home);
3505 // } else if (!home)
3506 // pm->node.flags |= PM_UNSET;
3507 // `home` itself was synthesised from the password database
3508 // back in setupvals (c:Src/init.c:1237-1250) BEFORE the import
3509 // loop, so an inherited $HOME wins: the import calls
3510 // `homesetfn` and overwrites the synthesised value.
3511 //
3512 // zshrs reaches neither of those C sites from this bin entry,
3513 // so `$HOME` was whatever the environment supplied and nothing
3514 // else — a scrubbed launch (cron, launchd/systemd unit,
3515 // container entrypoint, `env -i`) got no $HOME at all, and
3516 // every `~`, rc-file path and cache path derived from it
3517 // silently resolved to "" (`~/x` expanded to `/x`).
3518 //
3519 // Ordering is preserved by only synthesising when the import
3520 // produced nothing: `var_os` is the exact "was it in the
3521 // environment" test C's loop keys off, so an explicitly empty
3522 // `HOME=` still stays empty (reference binary: `env -i … HOME=
3523 // zsh -f -c 'print -r -- "[${HOME-UNSET}]"'` prints `[]`).
3524 //
3525 // `home` itself comes from c:Src/init.c:1237-1250, inlined here
3526 // because C has no function to port — it is straight-line code
3527 // inside `setupvals()`:
3528 // #ifdef USE_GETPWUID
3529 // if ((pswd = getpwuid(cached_uid))) {
3530 // if (EMULATION(EMULATE_ZSH))
3531 // home = ztrdup_metafy(pswd->pw_dir);
3532 // cached_username = ztrdup_metafy(pswd->pw_name);
3533 // }
3534 // else
3535 // #endif /* USE_GETPWUID */
3536 // {
3537 // if (EMULATION(EMULATE_ZSH))
3538 // home = ztrdup("/");
3539 // cached_username = ztrdup("");
3540 // }
3541 // Both arms are guarded on EMULATE_ZSH: under sh/ksh emulation
3542 // the C global stays NULL and `$HOME` can only come from the
3543 // environment. Reference binary agrees — `env -i TERM=dumb
3544 // PATH=/usr/bin:/bin zsh --emulate sh -f -c 'echo
3545 // "HOME=${HOME-UNSET}"'` prints `HOME=UNSET`, while the same
3546 // command without `--emulate sh` prints the password-database
3547 // home. `cached_username` is seeded separately (see the
3548 // getlogin() block below), so only the `home` half is here.
3549 if std::env::var_os("HOME").is_none()
3550 && crate::ported::zsh_h::EMULATION(crate::ported::zsh_h::EMULATE_ZSH)
3551 {
3552 // c:Src/init.c:1239 — `getpwuid(cached_uid)`, cached_uid
3553 // being `getuid()` from c:1235.
3554 let pswd = unsafe { libc::getpwuid(libc::getuid()) };
3555 let pw_dir = if pswd.is_null() {
3556 std::ptr::null()
3557 } else {
3558 unsafe { (*pswd).pw_dir }
3559 };
3560 let h = if pw_dir.is_null() {
3561 // c:1248 — password lookup failed: `home = ztrdup("/")`.
3562 // A NULL `pw_dir` on a present entry is the same
3563 // "no usable home" case.
3564 "/".to_string()
3565 } else {
3566 // c:1241 — `home = ztrdup_metafy(pswd->pw_dir)`.
3567 crate::ported::utils::metafy(
3568 &unsafe { std::ffi::CStr::from_ptr(pw_dir) }.to_string_lossy(),
3569 )
3570 };
3571 // Routes through `homesetfn`, so the `home` global and the
3572 // paramtab entry agree (c:Src/params.c:5118).
3573 crate::ported::params::setsparam("HOME", &h);
3574 // c:964-965 — the param is not PM_EXPORTED (it was not
3575 // imported), so C addenv's it. The reference binary
3576 // confirms the synthesised value reaches children:
3577 // `env -i TERM=dumb PATH=/usr/bin:/bin zsh -f -c
3578 // '/usr/bin/env'` lists `HOME=/Users/…`.
3579 crate::ported::params::addenv("HOME", &h);
3580 }
3581
3582 // c:Src/params.c:968-970 — `pm = realparamtab->getnode2(realparamtab,
3583 // "LOGNAME"); if (!(pm->node.flags & PM_EXPORTED)) addenv(pm, pm->u.str);`
3584 //
3585 // Unconditional in C, right after the HOME block above, and the same
3586 // shape: the param was SEEDED (c:878-882, from `getlogin()`) rather
3587 // than imported, so it carries no PM_EXPORTED and C exports it here.
3588 // The faithful port of this lives in `createparamtable`
3589 // (ported/params.rs, c:968-970) but that function is not on this
3590 // entry path — `ShellExecutor::new` is — so the seeded value never
3591 // reached the environment. Measured under a scrubbed env:
3592 //
3593 // env -i HOME=$HOME TERM=xterm PATH=... <shell> -f -c '${(t)LOGNAME}'
3594 // zsh : scalar-export zshrs: scalar
3595 //
3596 // and a child of zshrs saw no LOGNAME at all where a child of zsh did.
3597 // Like the SHLVL case above, C exports a value the import loop did not
3598 // supply; unlike it, there is no paired exec-time adjustment.
3599 if let Some(v) = crate::ported::params::getsparam("LOGNAME") {
3600 crate::ported::params::addenv("LOGNAME", &v); // c:970
3601 }
3602
3603 // c:Src/params.c:951 — `addenv(pm, buf)`. Unconditional: the C comment
3604 // on the line above it is "shlvl value in environment needs updating
3605 // unconditionally". `addenv` both zputenv's the string and stamps
3606 // `pm->node.flags |= PM_EXPORTED` (c:Src/params.c:5482-5484), so this
3607 // one call is what makes `${(t)SHLVL}` read `integer-export-special`
3608 // AND what puts the incremented number in a forked child's
3609 // environment.
3610 //
3611 // Omitting it left $SHLVL unable to count nesting at all — measured
3612 // with each shell nesting itself twice, the inner shells FORKED so
3613 // that no exec-in-place decrement applies:
3614 // zsh L1=1 L2=2 L3=3
3615 // zshrs L1=1 L2=1 L3=1
3616 // because every nested zshrs re-read the grandparent's stale
3617 // environment entry instead of the parent's incremented one. It also
3618 // left the parameter unexported under a scrubbed environment
3619 // (`env -i … -f -c '${(t)SHLVL}'`: zsh `integer-export-special`,
3620 // zshrs `integer-special`), which a completion listing sees directly:
3621 // `env <TAB>` runs `_parameters -g "*export*"` and zsh offered SHLVL
3622 // there where zshrs did not.
3623 // It follows the HOME and LOGNAME exports, as in C (c:960-974), so a
3624 // child sees them in zsh's environment order.
3625 if let Some(v) = shlvl_env {
3626 crate::ported::params::addenv("SHLVL", &v); // c:951
3627 }
3628
3629 // SHLVL's paired exec-time half — c:Src/exec.c:
3630 // 4332-4336, "for either implicit or explicit exec, decrease $SHLVL as
3631 // we're now done as a shell", guarded by `!subsh && !forked` — is
3632 // ported for the EXPLICIT `exec cmd` form at fusevm_bridge.rs's
3633 // BUILTIN_EXEC, the one place fusevm replaces its own process.
3634 //
3635 // Still open: C also execs IN PLACE for the LAST command of a `-c`
3636 // script, and fusevm always forks there (`zsh -fc 'echo $$; /bin/sh -c
3637 // "echo \$\$"'` reports one pid on zsh, two on zshrs). So
3638 // `SHLVL=5 <shell> -fc '/usr/bin/env'` shows SHLVL=5 on zsh (exec'd,
3639 // decremented) and SHLVL=6 on zshrs (forked, so C's own rule says do
3640 // not decrement). That divergence belongs to the unported implicit
3641 // exec-in-place, not to the SHLVL wiring: fixing it means teaching
3642 // fusevm C's `do_exec` for the final command, and until then the
3643 // forked answer is the one C would give for a forked command.
3644 // c:Src/init.c:1907-1909 — `SHTTY = -1; init_io(cmd); setupvals(...)`.
3645 // zsh_main runs those three in that order, and this constructor stands
3646 // in for setupvals's param setup on the drivers that never reach
3647 // zsh_main: `zshrs -c CODE` dispatches at bins/zshrs.rs:1716 (after
3648 // --zsh/-f are stripped) straight into ShellExecutor::new + exit. So
3649 // init_io has to happen here, or SHTTY is still -1 and the winsize
3650 // probe below silently no-ops (adjustwinsize early-returns at
3651 // c:1900-1901). setupvals's own adjustwinsize(0) covers the zsh_main
3652 // path; init_io is idempotent (c:615-618 closes and reopens SHTTY), so
3653 // that path just re-establishes it a moment later.
3654 crate::ported::init::init_io(None); // c:1908
3655 crate::startup_trace::mark("exec: init_io");
3656
3657 // c:Src/init.c:1274-1276 — `adjustwinsize(0)`, the first thing after
3658 // createparamtable (c:1270). Probes the tty via TIOCGWINSZ and
3659 // publishes the geometry to $COLUMNS/$LINES.
3660 //
3661 // Ordering is C's, and load-bearing in both directions: it must FOLLOW
3662 // init_io (which sets SHTTY) and it must FOLLOW the environ import
3663 // above, because the tty geometry OVERRIDES an inherited COLUMNS — a
3664 // 97-column terminal reports 97 even when COLUMNS=10 was exported in.
3665 // (C gets that via the c:1906-1907 "Signal missed while a job owned the
3666 // tty?" promotion of from=0 to from=1, which makes adjustcolumns take
3667 // the signalled path and overwrite zterm_columns with ws_col.)
3668 //
3669 // With no terminal at all, SHTTY stays -1 and the imported value (or 0)
3670 // survives untouched — which is what C's zterm_columns does there, and
3671 // why a piped `COLUMNS=20 zshrs -c` still reports 20. Note SHTTY does
3672 // NOT require stdin/stdout to be a tty: init_io's last resort is
3673 // `open("/dev/tty")` (c:667-670), so a piped-but-still-attached shell
3674 // gets the real width, matching `zsh -fc 'print $COLUMNS | cat'`.
3675 let _ = crate::ported::utils::adjustwinsize(0); // c:1276
3676 crate::startup_trace::mark("exec: adjustwinsize");
3677
3678 // c:Src/params.c:955 — `set_pwd_env();` runs AFTER the environ
3679 // import loop, overwriting the imported $PWD/$OLDPWD paramtab
3680 // entries with the ispwd()-validated values computed above
3681 // (c:Src/init.c:1242-1259). Without this, a stale inherited
3682 // $PWD (env-import snapshot taken at process entry) survives
3683 // in paramtab even though the live env was corrected.
3684 // The live environment is the carrier set_pwd_env reads for C's
3685 // `pwd`/`oldpwd` globals (see the c:Src/init.c:1242-1259 block above).
3686 env::set_var("PWD", &pwd_val);
3687 env::set_var("OLDPWD", &oldpwd_val);
3688 crate::ported::builtin::set_pwd_env();
3689 crate::startup_trace::mark("exec: set_pwd_env");
3690
3691 // c:Src/params.c:975-992 — host/arch identification params:
3692 // CPUTYPE / MACHTYPE / OSTYPE / VENDOR. C zsh reads from
3693 // compile-time `#define`s (set by ./configure) for MACHTYPE /
3694 // OSTYPE / VENDOR, and from uname().machine at runtime for
3695 // CPUTYPE.
3696 //
3697 // Rust port: probe uname() at startup for CPUTYPE, and use
3698 // const strings parameterized by build-target for the
3699 // others. Match homebrew zsh's values where possible.
3700 let mut uname_buf: libc::utsname = unsafe { std::mem::zeroed() };
3701 let _ = unsafe { libc::uname(&mut uname_buf) };
3702 let to_str = |b: &[libc::c_char]| -> String {
3703 // c-string → owned String, truncated at first NUL.
3704 let bytes: Vec<u8> = b
3705 .iter()
3706 .take_while(|&&c| c != 0)
3707 .map(|&c| c as u8)
3708 .collect();
3709 String::from_utf8_lossy(&bytes).into_owned()
3710 };
3711 let cputype = to_str(&uname_buf.machine);
3712 crate::ported::params::setsparam("CPUTYPE", &cputype); // c:961
3713 // OSTYPE: configure's `$host_os`, resolved on the build host and
3714 // frozen into config.h — C never re-derives it from uname() at
3715 // startup. Deriving it here made the two writers disagree, so the
3716 // same binary answered `darwin25.5.0` under -c and `darwin23.6.0`
3717 // under -i. Single source of truth: config_h::OSTYPE, exactly as
3718 // MACHTYPE below.
3719 crate::ported::params::setsparam("OSTYPE", crate::ported::config_h::OSTYPE); // c:990
3720 // MACHTYPE: configure's `$host_cpu`, i.e. the config.guess
3721 // canonical arch name — NOT uname's `machine`. The two differ
3722 // on Apple Silicon (uname says `arm64`, config.guess says
3723 // `aarch64`), and zsh reports the latter. Single source of
3724 // truth: config_h::MACHTYPE (= build target arch).
3725 crate::ported::params::setsparam("MACHTYPE", crate::ported::config_h::MACHTYPE); // c:967
3726 // VENDOR: configure's `$host_vendor`. Deriving it from uname's
3727 // `sysname` here was a second, non-C writer that disagreed with
3728 // `config_h::VENDOR` off Darwin: config.guess emits `pc` for x86_64
3729 // Linux (config.guess:1222) and `unknown` for aarch64 Linux
3730 // (config.guess:1009), a distinction `sysname` cannot make. Single
3731 // source of truth, exactly as OSTYPE/MACHTYPE above.
3732 crate::ported::params::setsparam("VENDOR", crate::ported::config_h::VENDOR); // c:992
3733
3734 // c:Src/init.c:963 — `setsparam("TTY", ttyname(0) ?: "")`, which
3735 // C reaches at c:969 in the createparamtable tail. Even a
3736 // non-interactive -fc shell creates the param.
3737 let tty_str = unsafe {
3738 let p = libc::ttyname(0);
3739 if p.is_null() {
3740 String::new()
3741 } else {
3742 std::ffi::CStr::from_ptr(p)
3743 .to_str()
3744 .unwrap_or("")
3745 .to_string()
3746 }
3747 };
3748 crate::ported::params::setsparam("TTY", &tty_str); // c:969
3749 // c:Src/params.c:971 — `setsparam("ZSH_ARGZERO", ztrdup(posixzero))`:
3750 // the kernel-supplied argv[0] of THIS binary, in --zsh parity mode
3751 // too. The bin entrypoint overrides this with the script path for
3752 // -c / runscript invocations. (A previous revision probed the
3753 // system zsh install path and reported THAT as ZSH_ARGZERO for
3754 // byte-parity — faking the shell's identity. Parity tests that
3755 // compare the value must normalize the machine-specific binary
3756 // path in the test row instead.)
3757 let argzero_default = env::args().next().unwrap_or_else(|| "zsh".to_string());
3758 crate::ported::params::setsparam("ZSH_ARGZERO", &argzero_default); // c:971
3759 // c:Src/params.c:972 — ZSH_VERSION. `zsh_version::ZSH_VERSION`
3760 // (emitted by build.rs from the vendored `Config/version.mk`) is
3761 // the development snapshot tag `5.9.0.3-test`; shipped zsh
3762 // binaries report the clean release form (`5.9`). Bug #73 in
3763 // docs/BUGS.md — cross-shell scripts that gate on
3764 // `[[ $ZSH_VERSION = 5.9 ]]` or split on `.` expecting
3765 // MAJOR.MINOR break on the `-test` suffix. Use the cleaned
3766 // `patchlevel::ZSH_VERSION` here ("5.9") and surface the full
3767 // snapshot tag as `$ZSHRS_VERSION` for zshrs identity checks.
3768 crate::ported::params::setsparam("ZSH_VERSION", crate::ported::patchlevel::ZSH_VERSION); // c:972
3769 // c:Src/params.c:973 + Src/patchlevel.h — `ZSH_PATCHLEVEL` is a
3770 // git-describe-style identifier (`zsh-MAJOR.MINOR-N-gHASH`) of
3771 // the upstream commit zshrs targets. `build.rs` emits "unknown"
3772 // because the vendored zsh tarball ships no CUSTOM_PATCHLEVEL
3773 // define; use the canonical const in `patchlevel.rs` instead.
3774 // Bug #90 in docs/BUGS.md — scripts that fingerprint by
3775 // $ZSH_PATCHLEVEL fell to the wildcard arm under "unknown".
3776 crate::ported::params::setsparam(
3777 "ZSH_PATCHLEVEL",
3778 crate::ported::patchlevel::ZSH_PATCHLEVEL,
3779 ); // c:973
3780 // Skip ZSHRS_VERSION whenever the zsh-compatible namespace must
3781 // stay free of zshrs-original names, so `${(k)parameters}`
3782 // doesn't carry a name zsh doesn't ship — same predicate and
3783 // reasoning as the guard in `ported::params::createparamtable`.
3784 // `hide_ext_builtins()` is `--zsh` OR `ZSHRS_HIDE_EXT_BUILTINS`
3785 // (the parity harnesses' knob). Scripts can still detect zshrs
3786 // via `$ZSH_VERSION`, which carries a `-test` suffix.
3787 if !crate::ext_builtins::hide_ext_builtins() {
3788 crate::ported::params::setsparam(
3789 "ZSHRS_VERSION",
3790 crate::ported::patchlevel::ZSHRS_VERSION,
3791 );
3792 }
3793 // `$HELPDIR` points at the bundled help tree that
3794 // `bundled_docs::install_and_publish` (top of this constructor)
3795 // materialised, so `run-help` works on a host with no zsh install.
3796 // It is seeded HERE, after the environment-import loop above, for
3797 // two reasons: the table has to exist to hold it, and an exported
3798 // `HELPDIR` the user supplied is already imported by now, so the
3799 // seed's own guard leaves that value (and its PM_EXPORTED) alone.
3800 //
3801 // The parameter is NOT exported. `run-help` is a shell function
3802 // that reads `${HELPDIR:-…}` out of the shell's own table, so the
3803 // environment entry this used to create bought nothing and leaked
3804 // the name into every child process — `env <TAB>`, which lists
3805 // exported names, offered a name zsh does not have.
3806 crate::bundled_docs::seed_helpdir_param();
3807 // c:Src/params.c:974-979 — `setaparam("signals", …)`.
3808 {
3809 use crate::ported::signals_h::SIGS;
3810 // c:signames.c sigs[] (generated) — index 0 is "EXIT",
3811 // entries 1..=SIGCOUNT are in PLATFORM SIGNAL-NUMBER
3812 // order, tail is "ZERR", "DEBUG" (zsh.h SIGZERR/SIGDEBUG).
3813 // SIGS is declared in Linux textual order, so sort by the
3814 // libc number to reproduce the generated table's order on
3815 // every platform. Same construction as params.rs — keep
3816 // in sync.
3817 let mut by_num: Vec<(&str, i32)> = SIGS.to_vec();
3818 by_num.sort_by_key(|&(_, n)| n);
3819 let mut signals_arr: Vec<String> = Vec::with_capacity(by_num.len() + 3);
3820 signals_arr.push("EXIT".to_string()); // c:sigs[0]
3821 signals_arr.extend(by_num.iter().map(|(n, _)| n.to_string()));
3822 // c:Src/params.c:1018-1021 — the real-time names follow.
3823 #[cfg(target_os = "linux")]
3824 signals_arr.extend(
3825 (libc::SIGRTMIN()..=libc::SIGRTMAX()).map(crate::ported::signals::rtsigname),
3826 );
3827 signals_arr.push("ZERR".to_string()); // c:sigs tail
3828 signals_arr.push("DEBUG".to_string()); // c:sigs tail
3829 crate::ported::params::setaparam("signals", signals_arr); // c:974
3830 }
3831 // c:Src/init.c:1364 — `setsparam("ZSH_NAME", ztrdup(zsh_name))`,
3832 // which setupvals runs AFTER createparamtable, so the node lands
3833 // ahead of the imported environment in its bucket chain.
3834 crate::ported::params::setsparam("ZSH_NAME", "zsh"); // c:Src/init.c:1364
3835 crate::startup_trace::mark("exec: base params set");
3836 // LOGNAME is seeded pre-import now (c:878) — see the block by the
3837 // TMPPREFIX/HOST seeds above.
3838 //
3839 // DO NOT setsparam("USERNAME", ...) anywhere in init. `$USERNAME`
3840 // is a special parameter whose SETTER (`usernamesetfn` in
3841 // params.rs) performs setgid(2) + setuid(2) to actually change
3842 // the effective user — a deliberate upstream zsh feature for
3843 // `USERNAME=other-user cmd`. Calling it at init seeds the value
3844 // AND tries to change uid/gid; when the resolved pwd's pw_uid
3845 // differs from `getuid()` (sudo launches, macOS Keychain-helper
3846 // inherited env, container entry points, etc.) the setgid call
3847 // fails with EPERM and emits `zsh:1: failed to change group ID:
3848 // Operation not permitted`. Upstream seeds `$USERNAME` via the
3849 // GETTER path (`usernamegetfn` reads through `cached_username`
3850 // populated by `inittyptab` → `get_username`), no setter call.
3851
3852 // c:Src/init.c:1176 — `module_path = mkarray(MODULE_DIR)`.
3853 // The canonical init lives in `init::setupvals` (port of
3854 // `Src/init.c:setupvals`); the bin entry skips setupvals (per
3855 // the init_bltinmods comment above), so call the lightweight
3856 // module_path bootstrap exposed by init.rs from here. This
3857 // mirrors the HOST gethostname seeding pattern above:
3858 // duplicated init that should collapse into a full setupvals
3859
3860 // c:Src/init.c:1945 init_bltinmods — runs right after setupvals
3861 // (c:1942), i.e. after createparamtable's import, so the module
3862 // autoload stubs (`WATCH`, `watch`, …) are created HERE. The bin
3863 // entry skips zsh_main → init_bltinmods, so run it from
3864 // ShellExecutor::new for the same effect. Bug #270.
3865 // c:Src/init.c:1085 — `(void)addhookdefs(NULL, zshhooks, ...)`, a
3866 // setupvals step. The bin entry skips setupvals, so without this
3867 // hooktab stayed empty: `zmodload zsh/nearcolor`'s boot_
3868 // (nearcolor.c:199) found no "get_color_attr" hookdef to attach
3869 // getnearestcolor to, and `%F{#hex}` never mapped to the palette.
3870 // Shared once-guard with setupvals (see init::ZSHHOOKS_ADDED).
3871 crate::ported::init::ZSHHOOKS_ADDED.call_once(|| {
3872 let base = crate::ported::init::zshhooks.load(std::sync::atomic::Ordering::SeqCst);
3873 let _ = crate::ported::module::addhookdefs(std::ptr::null(), base, 4);
3874 });
3875 crate::ported::init::init_bltinmods(); // c:Src/init.c:1945
3876 crate::startup_trace::mark("exec: init_bltinmods");
3877
3878 // Populate paramtab with PM_SPECIAL Params for every PARTAB /
3879 // PARTAB_ARRAY magic-assoc name. Mirrors what C's zsh/parameter
3880 // module boot_ → handlefeatures chain does — which happens when
3881 // the module LOADS, after init_bltinmods planted its autoload
3882 // stubs, and `addparamdef` unsets the stub before creating the
3883 // real param (c:Src/module.c addparamdef → unsetparam_pm +
3884 // createparam), so these names take a FRESH chain slot ahead of
3885 // the stubs. Running this before init_bltinmods put `usergroups`
3886 // and friends behind `WATCH` in `${(k)parameters}`.
3887 init_partab_params(); // c:Src/Modules/parameter.c:2341 boot_/enables_ chain
3888 crate::startup_trace::mark("exec: init_partab_params");
3889
3890 // HOST is seeded pre-import now (c:875) — see the block next to
3891 // the TMPPREFIX/LOGNAME seeds above.
3892 // bash startup delta: bash defines TERM itself when the
3893 // environment does not carry one, and exports it. zsh leaves
3894 // TERM unset in that case, so `zshrs --bash` inherited zsh's
3895 // behavior and diverged from the reference shell:
3896 //
3897 // $ env -u TERM /bin/bash -c 'printf "%s\n" "${TERM+set}"'
3898 // set
3899 // $ env -u TERM /bin/bash -c 'echo "$TERM"'
3900 // dumb
3901 // $ env -u TERM /bin/zsh -f -c 'printf "%s\n" "${TERM+set}"'
3902 // (empty — zsh leaves it unset)
3903 //
3904 // Same on bash 3.2.57 (macOS /bin/bash) and 5.3.15, so it is
3905 // not a version artifact. Only the bare `--bash` drop-in takes
3906 // it: `--bash --zsh` asks for zsh-STYLE emulation, where zsh's
3907 // leave-it-unset behavior is the correct answer. Guarded on the
3908 // environment so an inherited TERM always wins.
3909 if crate::extensions::dash_mode::bash_mode() && std::env::var_os("TERM").is_none() {
3910 crate::ported::params::setsparam("TERM", "dumb");
3911 // bash exports it (`declare -x TERM` shows up in `export -p`);
3912 // addenv stamps PM_EXPORTED and pushes it into the child env.
3913 crate::ported::params::addenv("TERM", "dumb");
3914 }
3915
3916 // c:Src/init.c:479 — `-c` mode: scriptname = scriptfilename
3917 // = ztrdup("zsh"). Both globals start as the literal "zsh"
3918 // (not the binary path) so PS4's %x / %N print "zsh" not
3919 // "/path/to/zshrs" at the top level. Function dispatch
3920 // overrides scriptname per c:5903; scriptfilename stays.
3921 crate::startup_trace::mark("exec: pre-scriptname");
3922 crate::ported::utils::set_scriptname(Some("zsh".to_string()));
3923 // c:Src/init.c:470-479 — `scriptname = scriptfilename =
3924 // ztrdup("zsh")` sits INSIDE the `-c` branch of the option parse.
3925 // An interactive shell (or one running a script file) leaves
3926 // `scriptfilename` NULL, and exec.c:5383 copies it onto every
3927 // Shfunc it defines — which is why zsh reports an EMPTY
3928 // `$functions_source[f]` for a function typed at the prompt.
3929 // Stamping "zsh" unconditionally made zshrs answer "zsh" there.
3930 let dash_c = std::env::args_os()
3931 .skip(1)
3932 .map(|a| a.to_string_lossy().into_owned())
3933 .any(|a| a.starts_with('-') && !a.starts_with("--") && a.contains('c'));
3934 if dash_c {
3935 crate::ported::utils::set_scriptfilename(Some("zsh".to_string())); // c:479
3936 }
3937
3938 // call once that port is complete.
3939 crate::startup_trace::mark("exec: pre-module_path_init");
3940 crate::ported::init::module_path_init();
3941
3942 // Publish `fpath` LAST, once every special has been seeded.
3943 //
3944 // The earlier `set_array("fpath", …)` above lands before the tied
3945 // FPATH/fpath special is created, and creating it resets the node
3946 // to empty -- so an INTERACTIVE shell reached its first prompt with
3947 // typeset -aT FPATH fpath=( )
3948 // while `$FPATH` still read the full four-entry string. `path`
3949 // hid the bug: `PATH` is always in the environ, so the env import
3950 // refills it, whereas zsh never exports `FPATH` and nothing
3951 // refilled that one.
3952 //
3953 // The damage was not a missing default: a `.zshrc` that does
3954 // `fpath=( mydir $fpath )` -- the standard idiom -- appended to
3955 // NOTHING, so the shell ended up with only what the rc file added
3956 // and lost the bundled tree entirely.
3957 //
3958 // `-c` was unaffected, which is why every non-interactive probe of
3959 // this passed.
3960 let fpath_final: Vec<String> = exec
3961 .fpath
3962 .iter()
3963 .map(|p| p.to_string_lossy().to_string())
3964 .collect();
3965 if !fpath_final.is_empty() {
3966 // The ENVIRONMENT has to carry the final value too, not just
3967 // paramtab. `setupvals` re-seeds the tied specials and the
3968 // split that refills `fpath` reads the FPATH string; with an
3969 // inherited FPATH that string was still the one this process
3970 // started with, so the bundled tree -- appended to the param
3971 // only -- vanished the moment a shell was interactive AND had
3972 // FPATH set. `-c` never re-seeds, which is why it kept showing
3973 // the correct list.
3974 unsafe { std::env::set_var("FPATH", fpath_final.join(":")) };
3975 exec.set_array("fpath".to_string(), fpath_final);
3976 }
3977 crate::startup_trace::mark("new() end");
3978
3979 exec
3980 }
3981
3982 /// The SQLite history index, opened on first call.
3983 ///
3984 /// Startup no longer pays for it: only the three diagnostic readers
3985 /// (`--doctor`, the cache report, `dbview history`) reach this, and a
3986 /// pool worker's cell is pre-filled with `None` so it stays closed
3987 /// there.
3988 pub fn history(&self) -> Option<&HistoryEngine> {
3989 self.history
3990 .get_or_init(|| HistoryEngine::new().ok())
3991 .as_ref()
3992 }
3993
3994 /// Execute a script file with bytecode caching — skips lex+parse+compile on cache hit.
3995 /// Bytecode is stored in rkyv keyed by (path, mtime).
3996 pub fn execute_script_file(&mut self, file_path: &str) -> Result<i32, String> {
3997 let path = Path::new(file_path);
3998 let abs_path = path
3999 .canonicalize()
4000 .unwrap_or_else(|_| path.to_path_buf())
4001 .to_string_lossy()
4002 .to_string();
4003
4004 // Try bytecode cache first — rkyv shard at ~/.zshrs/scripts.rkyv.
4005 // The cache validates path + mtime + zshrs binary mtime; on any
4006 // miss we fall through to lex/parse/compile. Cached path uses
4007 // `run_chunk` (the shared VM-execution helper); script-eval
4008 // path delegates to `execute_script_zsh_pipeline` so the
4009 // full parse/compile/cache-save/run flow stays in one place.
4010 if let Some(bc_blob) = crate::script_cache::try_load_bytes(path) {
4011 if let Ok(chunk) = bincode::deserialize::<fusevm::Chunk>(&bc_blob) {
4012 if !chunk.ops.is_empty() {
4013 tracing::trace!(
4014 path = %abs_path,
4015 ops = chunk.ops.len(),
4016 "execute_script_file: bytecode cache hit"
4017 );
4018 return self.run_chunk(chunk, &format!("execute_script_file:cache:{abs_path}"));
4019 }
4020 }
4021 }
4022
4023 // Cache miss.
4024 // c:Src/init.c:1394-1395 — `SHIN = movefd(open(funmeta, …))`, then
4025 // zsh_main's `loop(1,0)` (c:1963) reads the script ONE EVENT AT A
4026 // TIME: `lexinit(); parse_event(ENDINPUT); … execode(prog, …)`
4027 // (c:155-220). Every complete command runs before the next is
4028 // lexed, so an `alias` a line installs is in force for the next
4029 // line, and a syntax error on line N leaves lines 1..N-1 already
4030 // executed. A whole-file compile lexed every line with the state
4031 // the file started with and ran nothing when any line failed to
4032 // parse. The event loop is the one `source` uses (c:1626-1627
4033 // `loop(0, 0)`): with `interact` unset, c:234's
4034 // `(!interact || sourcelevel) && errflag` break is the same test.
4035 // c:Src/init.c:1566 / Src/input.c — the file is read as RAW BYTES and
4036 // metafied (Src/utils.c:4856), never rejected for non-UTF-8.
4037 let content = crate::script_bytes::read_script_file(file_path)
4038 .map_err(|e| format!("{}: {}", file_path, e))?;
4039 let mut events: Vec<crate::parse::ZshList> = Vec::new();
4040 // c:Src/init.c:1963 — zsh_main runs the script through `loop(1, 0)`:
4041 // toplevel.
4042 let mut status = self.run_events_per_command(&content, Some(&mut events), true)?;
4043 // c:Src/init.c:1969-1974 — `if (tok == LEXERR || errexit) { if
4044 // (!lastval) lastval = 1; stopmsg = 1; zexit(lastval, …); }`: a
4045 // parse error, or an error abort in a non-interactive shell, exits
4046 // non-zero even when the last command that ran succeeded.
4047 if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
4048 if status == 0 {
4049 status = 1; // c:1971-1972
4050 self.set_last_status(status);
4051 }
4052 // c:Src/builtin.c:6006 zexit — `errflag = 0;` before the EXIT trap
4053 // runs, so the trap body is not itself aborted by the error.
4054 errflag.fetch_and(!ERRFLAG_ERROR, Ordering::Relaxed);
4055 }
4056 let status = self.fire_script_exit_hooks(status)?;
4057
4058 // Best-effort cache save — failures don't block execution. The
4059 // cached program is the events exactly as the loop lexed them, so
4060 // a hit replays what this run parsed; `events` is empty unless the
4061 // loop drained the whole file without an error.
4062 if !events.is_empty() {
4063 let program = crate::parse::ZshProgram { lists: events };
4064 let compiler = crate::compile_zsh::ZshCompiler::new();
4065 let chunk = compiler.compile(&program);
4066 if let Ok(blob) = bincode::serialize(&chunk) {
4067 let _ = crate::script_cache::try_save_bytes(path, &blob);
4068 tracing::trace!(
4069 path = %abs_path,
4070 bytes = blob.len(),
4071 "execute_script_file: bytecode cached"
4072 );
4073 }
4074 }
4075
4076 Ok(status)
4077 }
4078
4079 /// Run a compiled `fusevm::Chunk` to completion inside this
4080 /// executor's context. Shared by `execute_script_zsh_pipeline`,
4081 /// `execute_script_file`'s bytecode-cache hit path, and the
4082 /// function-dispatch body_runner. Centralises the VM setup so
4083 /// `register_builtins` and `ExecutorContext::enter` invariants
4084 /// stay in lockstep.
4085 fn run_chunk(&mut self, chunk: fusevm::Chunk, label: &str) -> Result<i32, String> {
4086 if chunk.ops.is_empty() {
4087 return Ok(self.last_status());
4088 }
4089 crate::fusevm_disasm::maybe_print_stdout(label, &chunk);
4090 let mut vm = crate::vm_pool::acquire(chunk);
4091 // Seed vm.last_status with the executor's current LASTVAL so
4092 // sub-VMs (EXIT trap bodies, eval, source) see the inherited
4093 // `$?` from the caller's last command — matching C zsh where
4094 // lastval is a process global. Without this, the new VM
4095 // started at 0 and BUILTIN_GET_VAR's sync_status would write
4096 // 0 back into LASTVAL on the first `$?` read.
4097 vm.last_status = self.last_status();
4098 let _ctx = ExecutorContext::enter(self);
4099 // c:Src/loop.c — `loops` is bracketed by the C interpreter's own
4100 // recursion, so a `return` or an errflag abort out of a loop
4101 // unwinds it for free. A compiled chunk instead jumps straight to
4102 // its end, skipping the loop's `loops--`. Restoring the count the
4103 // chunk started with makes that structurally impossible to leak:
4104 // whatever loops this chunk opened are closed when it finishes.
4105 let loops_entry = crate::ported::builtin::LOOPS.load(Ordering::Relaxed);
4106 // c:Src/exec.c:4364 `done:` → `fixfds(save)` — every execcmd puts
4107 // back the fds its redirections replaced, whether it ran or was
4108 // abandoned on errflag. A chunk abandoned mid-command (`eval 'echo >
4109 // nx(N)'`: the target's expansion raises errflag after the scope
4110 // opened) jumped past its WithRedirectsEnd, so the caller kept
4111 // writing into the failed redirection's sink. Same unwind the
4112 // function-call path does (`unwind_redirect_scopes_to`).
4113 let redir_depth = self.redirect_scope_stack.len();
4114 // Same for the job slots of pipelines the chunk was running when it
4115 // was abandoned (see exec_jobs::execpline_slot_open).
4116 let slots_entry = crate::exec_jobs::execpline_slots_mark();
4117 let result = vm.run();
4118 crate::ported::builtin::LOOPS.store(loops_entry, Ordering::Relaxed);
4119 crate::exec_jobs::execpline_slots_release_to(slots_entry);
4120 self.unwind_redirect_scopes_to(redir_depth);
4121 match result {
4122 fusevm::VMResult::Ok(_) | fusevm::VMResult::Halted => {
4123 self.set_last_status(vm.last_status);
4124 }
4125 fusevm::VMResult::Error(e) => return Err(format!("VM error: {}", e)),
4126 }
4127 Ok(self.last_status())
4128 }
4129
4130 /// Execute via the lex+parse free ported + ZshCompiler pipeline.
4131 /// This is the only execution path; `execute_script` delegates here.
4132 /// Parse + compile `script` in an isolated lexer context, without
4133 /// running it.
4134 ///
4135 /// Split out of [`ShellExecutor::execute_script_zsh_pipeline`] so the
4136 /// autoload loader can get its hands on the compiled chunk: that chunk
4137 /// is what lands in `~/.zshrs/autoloads.rkyv`, so the next process can
4138 /// install the same function without re-parsing the definition file.
4139 fn compile_script_isolated(&mut self, script: &str) -> Result<fusevm::Chunk, String> {
4140 self.compile_script_isolated_at(script, None)
4141 }
4142
4143 /// `compile_script_isolated` with C's `parse_string(s, reset_lineno)`
4144 /// argument: `Some(n)` is `parse_string(s, 0)` (c:Src/exec.c:291-300),
4145 /// the body parsed from the running line `n` (see `parse_isolated_at`).
4146 fn compile_script_isolated_at(
4147 &mut self,
4148 script: &str,
4149 lineno: Option<u64>,
4150 ) -> Result<fusevm::Chunk, String> {
4151 // Skip history expansion for non-interactive script execution
4152 // (`zsh -c '…'`, internal eval, sourced files). zsh's `!`
4153 // history sub only fires on the REPL command line, never on
4154 // a pre-parsed script body. The interactive REPL has its
4155 // own dedicated path that calls expand_history before
4156 // dispatching here.
4157 // Save & clear errflag around the parse so a fresh syntax
4158 // error is distinguishable from one already in flight. Mirrors
4159 // Src/init.c loop()'s pre-parse `errflag &= ~ERRFLAG_ERROR;`.
4160 let saved_errflag = errflag.load(Ordering::Relaxed);
4161 errflag.fetch_and(!ERRFLAG_ERROR, Ordering::Relaxed);
4162 // Context-isolated parse (c:Src/exec.c:283 parse_string). eval /
4163 // source / autoload-register / trap bodies all reach here and run
4164 // DURING execution; on the faithful single-event loop()/parse_event
4165 // reader, a bare parse_init/lex_init would steal the outer's next
4166 // SHIN line into this nested program (e.g. `eval "x=5"` swallowed the
4167 // following `echo $x` off stdin). parse_isolated sets `strin` so the
4168 // string drains to EOF; execution below stays in the current shell.
4169 let program = parse_isolated_at(script, lineno);
4170 let parse_failed = (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0;
4171 errflag.store(saved_errflag, Ordering::Relaxed);
4172 if parse_failed {
4173 // c:Src/init.c — when the parser fires `zerr(...)`, the C
4174 // shell's `loop()` body skips the eval pass and continues;
4175 // there's no second "parse error" diagnostic. The Rust
4176 // binary's call sites print `zshrs: <e>` on Err, doubling
4177 // up on the message the parser already emitted via zerr.
4178 // Use a `__SILENCED__` sentinel that the binary's
4179 // execute_script wrapper recognizes as "already reported,
4180 // exit silently". Bug #142 in docs/BUGS.md (double-print
4181 // half).
4182 return Err("__SILENCED__".to_string());
4183 }
4184
4185 let mut compiler = crate::compile_zsh::ZshCompiler::new();
4186 compiler.nested_lineno_base = lineno; // c:Src/exec.c:297 reset_lineno == 0
4187 if CMDARG_EXITING.with(|c| c.replace(false)) {
4188 // c:Src/init.c:1568 — `execstring(cmd, 0, 1, "cmdarg")`: the `-c`
4189 // string runs as an EXITING list, so its last command is the
4190 // fake exec's candidate (BUILTIN_EXEC_FORKED_SIMPLE mode 2).
4191 compiler.forked_tail_list = crate::compile_zsh::program_exiting_tail(&program);
4192 compiler.exiting_tail_mode = 2;
4193 }
4194 Ok(compiler.compile(&program))
4195 }
4196
4197 /// `execstring(cmd, 0, 1, "cmdarg")` (c:Src/init.c:1568) — run the `-c`
4198 /// string as the shell's last act: [`Self::execute_script`] with the
4199 /// string compiled as an exiting list (see CMDARG_EXITING).
4200 pub fn execute_cmdarg(&mut self, script: &str) -> Result<i32, String> {
4201 CMDARG_EXITING.with(|c| c.set(true));
4202 let chunk = self.compile_script_isolated(script);
4203 CMDARG_EXITING.with(|c| c.set(false));
4204 let status = self.run_chunk(chunk?, "cmdarg")?;
4205 // c:Src/init.c:1572 — `zexit(lastval, ZEXIT_NORMAL)` follows the
4206 // `-c` string, and c:Src/builtin.c:6012-6015 clears the error state
4207 // before the EXIT trap (`errflag = intrap = 0; if
4208 // (sigtrapped[SIGEXIT]) dotrap(SIGEXIT);`): dotrapargs refuses to
4209 // run anything while errflag is set (c:Src/signals.c:1101), so a
4210 // script that ended on an error abort (`ro=2` on a readonly, `${x?}`,
4211 // `$((1/0))`) would otherwise skip its EXIT trap. The flag is put
4212 // back afterwards because the caller still reads it to pick the
4213 // exit status of the dash-family drop-ins.
4214 let saved_errflag = errflag.load(Ordering::Relaxed);
4215 errflag.store(0, Ordering::Relaxed); // c:6012
4216 let result = self.fire_script_exit_hooks(status);
4217 errflag.fetch_or(saved_errflag, Ordering::Relaxed);
4218 result
4219 }
4220
4221 /// Run an already-compiled top-level chunk, then fire the end-of-script
4222 /// hooks (`EXIT` trap, `TRAPEXIT`, `zshexit` + `zshexit_functions`) the
4223 /// script pipeline owes them.
4224 fn run_chunk_with_exit_hooks(
4225 &mut self,
4226 chunk: fusevm::Chunk,
4227 label: &str,
4228 ) -> Result<i32, String> {
4229 let status = self.run_chunk(chunk, label)?;
4230 self.fire_script_exit_hooks(status)
4231 }
4232
4233 /// The end-of-script hooks alone (`EXIT` trap, `TRAPEXIT`, `zshexit` +
4234 /// `zshexit_functions`), for a script that already ran; `status` is the
4235 /// script's `$?` and is what the call returns.
4236 fn fire_script_exit_hooks(&mut self, status: i32) -> Result<i32, String> {
4237 // Fire EXIT trap if set. Two storage paths:
4238 // (a) `trap 'cmd' EXIT` writes the body text into
4239 // `traps_table` via bin_trap (Src/builtin.c) — fire
4240 // directly via execute_script.
4241 // (b) `TRAPEXIT() { ... }` function-named form goes
4242 // through settrap(SIGEXIT, None, ZSIG_FUNC) at
4243 // funcdef time (fusevm_bridge.rs BUILTIN_REGISTER_COMPILED_FN
4244 // arm) and lives in shfunctab + sigtrapped — fire
4245 // via dotrap(SIGEXIT) which dispatches the named
4246 // shfunc. Bug #157 in docs/BUGS.md.
4247 // Remove the trap from `traps_table` first to prevent
4248 // infinite recursion of `(a)`; `(b)`'s sigtrapped flag
4249 // is cleared by dotrap's own intrap guard.
4250 let exit_body = crate::ported::builtin::traps_table()
4251 .lock()
4252 .ok()
4253 .and_then(|mut t| t.remove("EXIT"));
4254 if let Some(action) = exit_body {
4255 tracing::debug!("firing EXIT trap (new pipeline)");
4256 // c:Src/signals.c — the EXIT trap body sees $? at the
4257 // value the script left off (so `trap 'echo $?' EXIT;
4258 // (exit 7)` prints 7), but the SHELL's final exit code
4259 // is still the pre-trap value (running `echo` inside
4260 // the trap doesn't reset the script's exit status).
4261 // Preserve `status` and re-apply it after the trap
4262 // body returns.
4263 //
4264 // c:Src/signals.c:1123/1236 — `intrap++` … `intrap--` bracket a
4265 // trap body, and while intrap the EXIT, DEBUG and ZERR traps are
4266 // suppressed (c:1112-1119, the guard in dotrap). This path runs
4267 // the EXIT body through the script pipeline rather than dotrap,
4268 // so nothing raised intrap and the body's own failure re-entered
4269 // the ERR trap: `trap 'print err' ERR; trap 'true; false' EXIT`
4270 // printed err where zsh prints nothing.
4271 //
4272 // A counter, not a flag, and paired with dotrap's SELECTIVE
4273 // guard: signals zsh does deliver from inside a trap body (e.g.
4274 // `trap 'kill -USR1 $$' EXIT`) must still dispatch.
4275 crate::ported::signals::intrap.fetch_add(1, Ordering::SeqCst); // c:1123
4276 // c:Src/signals.c:1170 — `execode((Eprog)sigfn, 1, 0, "trap")`:
4277 // the EXIT body sees "trap" in zsh_eval_context (c:Src/exec.c:1251).
4278 let trap_ctx = crate::ported::exec::EvalContextFrame::push("trap");
4279 let _ = self.execute_script_zsh_pipeline(&action);
4280 drop(trap_ctx);
4281 crate::ported::signals::intrap.fetch_sub(1, Ordering::SeqCst); // c:1236
4282 self.set_last_status(status);
4283 }
4284 // c:Src/signals.c::dotrap(SIGEXIT) — fire TRAPEXIT() shfunc
4285 // if installed via the function-name path. The TRAPEXIT()
4286 // form goes through settrap(SIGEXIT, None, ZSIG_FUNC) at
4287 // funcdef time (sets sigtrapped[SIGEXIT] |= ZSIG_FUNC).
4288 // Dispatching from here AFTER run_chunk returns means we're
4289 // outside the VM context — dotrap can't safely re-enter
4290 // via dispatch_function_call (which uses with_executor).
4291 // Route through execute_script_zsh_pipeline which sets up
4292 // a fresh VM context — invoke the function by name.
4293 let trapped = crate::ported::signals::sigtrapped
4294 .lock()
4295 .ok()
4296 .and_then(|g| g.get(crate::signals_h::SIGEXIT as usize).copied())
4297 .unwrap_or(0);
4298 // c:Src/signals.c:1112-1119 — `if (intrap) { switch (sig) { case
4299 // SIGEXIT: … return; } }`, and c:Src/signals.c:892 `if (!intrap &&
4300 // …)` in endtrapscope. An EXIT trap never fires from inside another
4301 // trap body. This site is a Rust-only end-of-pipeline hook (every
4302 // `eval` / `source` / trap body runs its own pipeline and reaches
4303 // here), and it dispatches TRAPEXIT by NAME without going through
4304 // dotrap — so nothing consulted `intrap` and nothing cleared
4305 // sigtrapped. Once `endtrapscope` started restoring a saved
4306 // ZSIG_FUNC EXIT trap (the c:929-931 arm), the TRAPEXIT body's own
4307 // nested pipeline re-entered this hook with the flag still set and
4308 // recursed without bound:
4309 // f() { eval 'TRAPEXIT() { echo T; }' }; f
4310 // The `intrap++ … intrap--` bracket is the same one the string-form
4311 // branch above already carries (c:1123 / c:1236).
4312 // c:Src/signals.c:744-752 — `sigtrapped[sig] |= (locallevel <<
4313 // ZSIG_SHIFT)`: a trap installed inside a function carries its
4314 // scope's locallevel, and `endtrapscope` (c:892-903/945-956) is what
4315 // fires THAT one, at the scope exit. Only an untagged (locallevel 0)
4316 // EXIT trap belongs to the shell-exit path this hook stands in for.
4317 // Without the test, `f() { TRAPEXIT() { echo T } }; f` fired twice —
4318 // once from f's endtrapscope and once more from the pipeline hook.
4319 let exit_trap_locallevel = trapped >> crate::ported::zsh_h::ZSIG_SHIFT;
4320 if (trapped & crate::ported::zsh_h::ZSIG_FUNC as i32) != 0
4321 && exit_trap_locallevel == 0
4322 && crate::ported::signals::intrap.load(Ordering::SeqCst) == 0
4323 {
4324 // The TRAP<SIG> function is stored in shfunctab as
4325 // "TRAPEXIT"; calling it by name re-enters
4326 // execute_script_zsh_pipeline with a fresh VM context.
4327 crate::ported::signals::intrap.fetch_add(1, Ordering::SeqCst); // c:1123
4328 let _ = self.execute_script_zsh_pipeline("TRAPEXIT");
4329 crate::ported::signals::intrap.fetch_sub(1, Ordering::SeqCst); // c:1236
4330 }
4331 // c:Src/init.c::zexit — `callhookfunc("zshexit", NULL, 1, NULL)`.
4332 // Fire the `zshexit` shfunc + walk `zshexit_functions` array.
4333 // Routed through execute_script_zsh_pipeline calls because
4334 // we're outside the VM context here (post-run_chunk). Iterate
4335 // the array directly + call zshexit by name. Bug #215 in
4336 // docs/BUGS.md.
4337 //
4338 // Re-entry guard: each call to execute_script_zsh_pipeline
4339 // (whether top-level script or the named-fn dispatch below)
4340 // hits this code at its tail. Without a guard, the zshexit
4341 // hook recurses infinitely (calls itself at end via this
4342 // path). Use a thread-local depth counter and skip the
4343 // dispatch when depth > 0.
4344 thread_local! {
4345 static ZSHEXIT_HOOK_DEPTH: std::cell::Cell<u32> = const {
4346 std::cell::Cell::new(0)
4347 };
4348 }
4349 let hook_depth = ZSHEXIT_HOOK_DEPTH.with(|c| c.get());
4350 if hook_depth == 0 {
4351 ZSHEXIT_HOOK_DEPTH.with(|c| c.set(hook_depth + 1));
4352 if crate::ported::hashtable::shfunctab_lock()
4353 .read()
4354 .ok()
4355 .map(|t| t.contains_key("zshexit"))
4356 .unwrap_or(false)
4357 {
4358 let _ = self.execute_script_zsh_pipeline("zshexit");
4359 }
4360 let exit_arr = crate::ported::params::paramtab()
4361 .read()
4362 .ok()
4363 .and_then(|t| t.get("zshexit_functions").and_then(|p| p.u_arr.clone()))
4364 .unwrap_or_default();
4365 for fn_name in exit_arr {
4366 let exists = crate::ported::hashtable::shfunctab_lock()
4367 .read()
4368 .ok()
4369 .map(|t| t.contains_key(&fn_name))
4370 .unwrap_or(false);
4371 if exists {
4372 let _ = self.execute_script_zsh_pipeline(&fn_name);
4373 }
4374 }
4375 ZSHEXIT_HOOK_DEPTH.with(|c| c.set(hook_depth));
4376 }
4377 // Preserve script status; trap body shouldn't override it.
4378 self.set_last_status(status);
4379
4380 let _ = status;
4381 Ok(self.last_status())
4382 }
4383 /// zshrs's script entry: lex + parse + compile + run, then the
4384 /// end-of-script hooks. `eval`, `source`, trap bodies and autoload
4385 /// registration all funnel through here.
4386 pub fn execute_script_zsh_pipeline(&mut self, script: &str) -> Result<i32, String> {
4387 let chunk = self.compile_script_isolated(script)?;
4388 self.run_chunk_with_exit_hooks(chunk, "execute_script_zsh_pipeline")
4389 }
4390
4391 /// Run a source string the way C's `execstring` does (c:Src/exec.c:1228
4392 /// → `execode`, c:1245): parse, execute, return the status. No `EXIT`
4393 /// trap, `TRAPEXIT` or `zshexit` hook runs here. In C those belong to
4394 /// `zexit` (c:Src/builtin.c:6037-6043) and to the end of a function's
4395 /// trap scope (`endtrapscope`, c:Src/signals.c:880), never to the end of
4396 /// an `eval`, a trap body or a `sched` command. Firing them there ran a
4397 /// script's EXIT trap in the middle of the script:
4398 /// `trap 'print T' EXIT; eval :; print after` printed T before `after`.
4399 pub fn execute_string_without_exit_hooks(&mut self, script: &str) -> Result<i32, String> {
4400 let chunk = self.compile_script_isolated(script)?;
4401 self.run_chunk(chunk, "execstring")
4402 }
4403
4404 /// `execode(parse_string(cmdarg, 0), 1, 0, "cmdsubst")` — a nofork
4405 /// substitution body (c:Src/subst.c:2044-2046) parsed from the running
4406 /// line, so its statements carry the outer line numbers and leave
4407 /// `lineno` on them, as C's do.
4408 pub fn execute_string_at_lineno(&mut self, script: &str, lineno: u64) -> Result<i32, String> {
4409 let chunk = self.compile_script_isolated_at(script, Some(lineno))?;
4410 self.run_chunk(chunk, "execstring")
4411 }
4412
4413 /// Run the TEXT that `getpermtext` reconstructed from an already-compiled
4414 /// `.zwc` program.
4415 ///
4416 /// c:Src/init.c:1618-1622 — the compiled arm of `source()` is
4417 /// `execode(prog, 1, 0, "filecode")`. The wordcode runs as it stands and
4418 /// NOTHING is lexed; a `.zwc` is quote-resolved once, at `zcompile` time.
4419 ///
4420 /// !!! WARNING: RUST-ONLY HELPER !!!
4421 /// zshrs has no execute-the-wordcode path — it deparses the program back
4422 /// to source (`getpermtext`) and lexes it again — so the round trip is
4423 /// lossless only while the lexer reads quotes the way the deparse writes
4424 /// them. `untokenize` (c:Src/exec.c:2134) renders EVERY quote null through
4425 /// `ztokens[Snull - Pound]`, and that entry is a bare single quote
4426 /// (c:Src/lex.c:38), so a closing null followed by an opening one comes
4427 /// back out as two adjacent quotes. Under RCQUOTES the lexer reads that
4428 /// pair inside a quoted word as one LITERAL quote (c:Src/lex.c:1328)
4429 /// instead of as two delimiters, so the openshift-aliases plugin's
4430 /// `alias opodr='oc …=''{…}'''` — which `zcompile` resolved with no
4431 /// literal quotes at all — re-lexed with two of them. The deparse
4432 /// spelling is by construction the DEFAULT-option spelling, so the option
4433 /// is cleared for the compile to restore C's "not lexed at all" property.
4434 ///
4435 /// It is cleared for the COMPILE ONLY. A `.zwc` that does `setopt
4436 /// rcquotes` (zsh-expand's plugin entry does, at its line 39) must still
4437 /// set the option for real, and that setting must outlive the source — so
4438 /// the previous value is restored before the chunk RUNS, not after. The
4439 /// same split applies to alias expansion: a function or `eval` body the
4440 /// program runs is lexed at RUNTIME and must see the live alias table.
4441 pub fn execute_zwc_program(&mut self, script: &str) -> Result<i32, String> {
4442 let chunk = {
4443 let _relex = ZwcRelexGuard::enter();
4444 self.compile_script_isolated(script)
4445 };
4446 self.run_chunk_with_exit_hooks(chunk?, "execute_zwc_program")
4447 }
4448
4449 /// Run `script` the way C runs a PLAIN sourced file: parse ONE event,
4450 /// execute it, parse the next — so lexer-time state that one line
4451 /// establishes is in force when the next line is lexed.
4452 ///
4453 /// c:Src/init.c:1618-1641 — `source()` has two arms. A file that was
4454 /// already compiled (`try_source_file` found a `.zwc`) runs whole, as one
4455 /// program: `execode(prog, 1, 0, "filecode")` (c:1621). A plain file runs
4456 /// through the per-command loop: `/* loop through the file to be sourced
4457 /// */ switch (loop(0, 0))` (c:1626-1627), whose body is `lexinit();
4458 /// parse_event(ENDINPUT); … execode(prog, 0, 0, "file")` (c:155-220).
4459 /// This is the second arm.
4460 ///
4461 /// The difference is observable whenever a line changes something the
4462 /// LEXER consults, because a whole-file compile lexes every line with the
4463 /// state the file STARTED with:
4464 ///
4465 /// ```text
4466 /// alias greet='print -r -- hello' # takes effect at execution time
4467 /// greet # …but this line is lexed after it
4468 /// ```
4469 ///
4470 /// Same for `setopt rcquotes` (c:Src/lex.c:1326), `unsetopt aliases`, and
4471 /// a syntax error late in the file (C has already run the good lines).
4472 ///
4473 /// **Re-entrancy.** Every nested context — `$(source f)`, `` `source f` ``,
4474 /// `eval "source f"`, a pipe stage, a `( … )` subshell, a `source` inside
4475 /// a sourced file — reaches here through the normal builtin path, so this
4476 /// must be safe to enter while an outer instance of itself is parked
4477 /// mid-file. Two properties make it so, and both are deliberate:
4478 ///
4479 /// * It never touches the shell's INPUT STACK. C's `source` points
4480 /// `SHIN` at the file (c:1584) and lets `loop`'s `ingetc` pull from
4481 /// it; doing that here would fight the outer reader for the one
4482 /// global. Instead the file body is installed as the lexer's own
4483 /// `LEX_INPUT` window under `strinbeg` — the exact parking
4484 /// [`parse_isolated`] uses for a command-substitution body — and the
4485 /// outer window is saved on the Rust stack and restored on the way
4486 /// out. Nesting is then just stack discipline.
4487 /// * It never dispatches through `execode`. `execode`
4488 /// (`src/ported/exec.rs`) runs its program on the installed SESSION
4489 /// executor, which is the right one only for the top-level REPL; from
4490 /// inside a command substitution the live executor is the sub-VM that
4491 /// owns the capture. Each event is compiled and run here on `self` —
4492 /// the same executor `execute_script` would have used — via
4493 /// [`Self::run_chunk`]. `$(source f)` therefore captures exactly what
4494 /// `$(…)` captures from any other builtin.
4495 ///
4496 /// Returns the file's `$?`. `Err` only for a VM error, as
4497 /// [`Self::run_chunk`] reports it.
4498 pub fn execute_script_per_command(&mut self, script: &str) -> Result<i32, String> {
4499 // c:Src/init.c:1626-1627 — source() runs `loop(0, 0)`: not toplevel.
4500 self.run_events_per_command(script, None, false)
4501 }
4502
4503 /// The `loop()` body shared by a sourced file and a script file.
4504 ///
4505 /// `events`, when given, receives every executed event's lists, and is
4506 /// CLEARED unless the loop drained the input to a clean `ENDINPUT` — so a
4507 /// caller holding a non-empty collection after the call has the exact
4508 /// program the lexer produced, one event at a time, for the whole file.
4509 ///
4510 /// `toplevel` is loop()'s parameter of the same name: true only for the
4511 /// script file zsh_main runs (c:Src/init.c:1963 `loop(1, 0)`), false for
4512 /// `source` / `.` (c:1626-1627 `loop(0, 0)`). It gates the preexec hook
4513 /// (c:180).
4514 fn run_events_per_command(
4515 &mut self,
4516 script: &str,
4517 mut events: Option<&mut Vec<crate::parse::ZshList>>,
4518 toplevel: bool,
4519 ) -> Result<i32, String> {
4520 use crate::ported::lex::{
4521 tok, ENDINPUT, LEXERR, LEX_FILE_WINDOW_STRIN, LEX_INPUT, LEX_LINENO, LEX_POS,
4522 LEX_UNGET_BUF,
4523 };
4524
4525 // Inline Rust FFI blocks are rewritten before the lexer sees them,
4526 // as on every other source-string entry (see `parse_isolated`).
4527 let ffi_desugared = script
4528 .contains("rust")
4529 .then(|| crate::rust_ffi::desugar(script));
4530 let script: &str = ffi_desugared.as_deref().unwrap_or(script);
4531
4532 // c:Src/init.c:121 — `if (!toplevel) zcontext_save();`, plus the
4533 // zshrs-only lexer window that `zcontext` doesn't cover (identical
4534 // list to `parse_isolated`, which parks it for the same reason).
4535 crate::ported::context::zcontext_save(); // c:121
4536 let saved_input = LEX_INPUT.with_borrow(|s| s.clone());
4537 let saved_pos = LEX_POS.get();
4538 let saved_unget = LEX_UNGET_BUF.with_borrow(|b| b.clone());
4539 let saved_lineno = LEX_LINENO.get();
4540 let saved_in_lexstop = crate::ported::input::lexstop.with(|c| c.get());
4541 let saved_file_window = LEX_FILE_WINDOW_STRIN.get();
4542
4543 // `strin` makes a drained window report EOF instead of falling
4544 // through to `inputline()` and STEALING the outer reader's next line
4545 // (input.rs:391). Without it a sourced file's last event swallows the
4546 // caller's next stdin line.
4547 crate::ported::hist::strinbeg(0);
4548 // c:1588 — `lineno = 1;`. `lex_init` (called by `parse_init`)
4549 // installs the body as the window and resets the line counter.
4550 crate::ported::parse::parse_init(script);
4551 // C reads this file through `inputline` (c:Src/input.c:366) with
4552 // `strin == 0`: ONE LINE per buffer, which is what makes each line
4553 // its own event (c:Src/lex.c:310 / c:Src/parse.c:657), and every
4554 // newline counted (c:Src/input.c:330). zshrs installs the body as
4555 // one window under one `strinbeg`, so the file kind is declared
4556 // here, tagged with THIS strinbeg's depth — a nested string push
4557 // inside the file is deeper and stays a string.
4558 LEX_FILE_WINDOW_STRIN.set(crate::ported::input::strin.with(|s| s.get()));
4559
4560 // c:116 — `int err, non_empty = 0;`
4561 let mut non_empty = false;
4562 let mut vm_error: Option<String> = None;
4563 let mut drained = false;
4564
4565 loop {
4566 // c:155 — `lexinit();` Resets `tok` and BOTH `lexstop` copies;
4567 // it does NOT move the window, so the next event resumes where
4568 // the last one stopped.
4569 crate::ported::lex::lexinit(); // c:155
4570 // Event source for preexec's `$2`/`$3` — see run_preexec_hook.
4571 let event_mark = toplevel.then(crate::funcdef_capture::body_mark_begin);
4572 let prog = crate::ported::parse::parse_event(ENDINPUT); // c:156
4573 let event_src = event_mark.and_then(crate::funcdef_capture::event_text);
4574 let Some(prog) = prog else {
4575 // c:159-174 — no event this pass. Break on clean EOF or on a
4576 // parse error (`!toplevel` makes C's LEXERR arm
4577 // unconditional here); a bare separator just goes round
4578 // again, which is C's `continue` at c:174.
4579 let tok_v = tok(); // c:159
4580 let errflag_v = errflag.load(Ordering::Relaxed);
4581 if (tok_v == ENDINPUT && errflag_v == 0) || tok_v == LEXERR {
4582 // c:159-162
4583 drained = tok_v == ENDINPUT;
4584 if tok_v == LEXERR
4585 && crate::ported::builtin::LASTVAL.load(Ordering::Relaxed) == 0
4586 {
4587 crate::ported::builtin::LASTVAL.store(1, Ordering::Relaxed); // c:173
4588 }
4589 break;
4590 }
4591 if tok_v == ENDINPUT || errflag_v != 0 {
4592 // Drained (or aborted) with a flag set — nothing left to
4593 // read, so looping again would spin.
4594 break;
4595 }
4596 continue; // c:174
4597 };
4598 non_empty = true; // c:179
4599 if toplevel {
4600 // callhookfunc dispatches through the live executor, which
4601 // is only installed while a chunk runs (see run_chunk).
4602 let _ctx = ExecutorContext::enter(self);
4603 run_preexec_hook(event_src.as_deref()); // c:180-215
4604 }
4605
4606 // c:220 — `execode(prog, 0, 0, "file")`. The eval-context entry
4607 // C's `execode` pushes for this arm is already on the stack:
4608 // `bin_dot` pushes it once around the whole file (builtin.rs), so
4609 // pushing it per event would report `file:file:file:…`.
4610 //
4611 // `LEX_LINENO` is saved across execution for the same reason
4612 // `loop()` does it (init.rs, c:Src/exec.c:1376/1640): each
4613 // statement's `SET_LINENO` overwrites the counter while it runs,
4614 // and the NEXT event must be lexed from the line the file is
4615 // really on.
4616 let chunk = crate::compile_zsh::ZshCompiler::new().compile(&prog);
4617 let saved_lex_lineno = LEX_LINENO.get();
4618 let run = self.run_chunk(chunk, "source");
4619 LEX_LINENO.set(saved_lex_lineno);
4620 if let Some(ev) = events.as_deref_mut() {
4621 ev.extend(prog.lists);
4622 }
4623 if let Err(e) = run {
4624 vm_error = Some(e);
4625 break;
4626 }
4627
4628 // c:234 — `if (((!interact || sourcelevel) && errflag) || retflag)
4629 // break;`. A sourced file always runs with `sourcelevel` bumped
4630 // (bin_dot, c:1606), so the errflag half is unconditional here.
4631 if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0
4632 || crate::ported::builtin::RETFLAG.load(Ordering::Relaxed) != 0
4633 {
4634 // c:Src/init.c:1960-1968 — after loop(1,0) breaks on a
4635 // runtime error, zsh_main re-enters it unless
4636 // `errflag && !interact && !isset(CONTINUEONERROR)`; the
4637 // re-entered loop's hbegin clears ERRFLAG_ERROR
4638 // (c:Src/hist.c:1115) before the next event. Only the script
4639 // file (toplevel) has that outer loop: `source` breaks
4640 // (c:234 `sourcelevel`), and a parse error never gets here
4641 // (the LEXERR arm above breaks first).
4642 if toplevel
4643 && crate::ported::builtin::RETFLAG.load(Ordering::Relaxed) == 0
4644 && crate::ported::builtin::EXIT_PENDING.load(Ordering::Relaxed) == 0
4645 && !crate::ported::zsh_h::isset(crate::ported::zsh_h::INTERACTIVE)
4646 && crate::ported::zsh_h::isset(crate::ported::zsh_h::CONTINUEONERROR)
4647 {
4648 errflag.fetch_and(!ERRFLAG_ERROR, Ordering::Relaxed); // c:Src/hist.c:1115
4649 continue;
4650 }
4651 break; // c:235
4652 }
4653 // C's `exit` inside a sourced file calls `zexit` → `realexit()`
4654 // and the process is gone, so C never reaches the next event.
4655 // zshrs defers the exit (EXIT_PENDING plus a jump to chunk end)
4656 // and lets the caller unwind, so the loop has to stop on its own.
4657 if crate::ported::builtin::EXIT_PENDING.load(Ordering::Relaxed) != 0 {
4658 break;
4659 }
4660 }
4661
4662 // c:245 — `err = errflag;` is read BEFORE the context is restored,
4663 // because `zcontext_restore` → `parse_context_restore` ends with
4664 // `errflag &= ~ERRFLAG_ERROR` (c:Src/parse.c:354). C carries the
4665 // answer out as the `LOOP_ERROR` return value; zshrs's `bin_dot`
4666 // reads the flag itself (its c:1623-1624 + c:1663 block), so the bit
4667 // is put back after the restore instead.
4668 let err = (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0; // c:245
4669 if let Some(ev) = events {
4670 if !drained || err || vm_error.is_some() {
4671 ev.clear();
4672 }
4673 }
4674
4675 // c:246-249 — leave the loop's context exactly as it was found.
4676 crate::ported::hist::strinend();
4677 LEX_INPUT.with_borrow_mut(|s| *s = saved_input);
4678 LEX_POS.set(saved_pos);
4679 LEX_UNGET_BUF.with_borrow_mut(|b| *b = saved_unget);
4680 LEX_LINENO.set(saved_lineno);
4681 crate::ported::input::lexstop.with(|c| c.set(saved_in_lexstop));
4682 LEX_FILE_WINDOW_STRIN.set(saved_file_window);
4683 crate::ported::context::zcontext_restore(); // c:247
4684 if err {
4685 errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed); // see the c:245 note
4686 }
4687
4688 if let Some(e) = vm_error {
4689 return Err(e);
4690 }
4691 // c:1633-1636 — `case LOOP_EMPTY: /* Empty code resets status */
4692 // lastval = 0;`. `source /dev/null` (or a comments-only file) clears
4693 // `$?` rather than leaving the caller's.
4694 if !non_empty {
4695 self.set_last_status(0); // c:1635
4696 }
4697 Ok(self.last_status())
4698 }
4699
4700 /// Install an autoloaded function by running its definition program,
4701 /// reusing the rkyv-cached chunk when the cache can PROVE the chunk
4702 /// was compiled from this same definition text by this same binary.
4703 ///
4704 /// `registered` is what `autoload_register_source` produced: either
4705 /// `name() { <file body> }` or, for a file that already contains the
4706 /// definition, the body verbatim. Running it installs the function;
4707 /// the compiled chunk for it is exactly what the cache stores, so a hit
4708 /// skips lex+parse+compile of the whole file. For `_git` that is 424 KB
4709 /// of shell — the dominant cost of the first `git <tab>`.
4710 ///
4711 /// Two conditions gate caching, because outside them the chunk is not a
4712 /// function of the definition text alone:
4713 /// * ksh-style autoload (`KSHAUTOLOAD` / `PM_KSHSTORED`) runs the file
4714 /// at top level instead of wrapping it, so the same bytes produce a
4715 /// different program depending on a runtime option;
4716 /// * without `PM_UNALIASED` (`autoload` without `-U`) the body is
4717 /// parsed WITH alias expansion, so the chunk depends on the alias
4718 /// table too. Every compsys / plugin autoload uses `-Uz`.
4719 ///
4720 /// A hit that runs without defining `name` is treated as a corrupt
4721 /// entry, not as a failed load: the entry is dropped and the real
4722 /// source compiled. Installing a function is the one thing this
4723 /// function exists to do, so "it ran and the function is not there"
4724 /// is a fact the loader can check for itself rather than leaving the
4725 /// caller to report `function not defined by file` for what is
4726 /// actually a bad cache line.
4727 ///
4728 /// `from_wordcode` says the text is a `.zwc` deparse rather than file
4729 /// bytes. C never re-lexes such a body at all — `shf->funcdef =
4730 /// stripkshdef(prog, …)` (c:Src/exec.c:5753-5755) installs the dump's own
4731 /// wordcode and the ksh arm runs it with `execode(prog, 1, 0,
4732 /// "evalautofunc")` (c:5795) — so the compile here, which is zshrs's
4733 /// stand-in for that install, runs under [`ZwcRelexGuard`]. The guard
4734 /// covers the COMPILE only: a ksh-style body executes real user code, and
4735 /// an `eval` or function body IT reaches is lexed at runtime against the
4736 /// live alias table and the live RCQUOTES, exactly as in C.
4737 fn run_autoload_definition(
4738 &mut self,
4739 name: &str,
4740 registered: &str,
4741 ksh_style: bool,
4742 from_wordcode: bool,
4743 parse_failed: bool,
4744 ) -> Result<i32, String> {
4745 let unaliased = crate::ported::utils::getshfunc(name)
4746 .map(|f| (f.node.flags as u32 & crate::ported::zsh_h::PM_UNALIASED) != 0)
4747 .unwrap_or(false);
4748 let key = if ksh_style || !unaliased {
4749 None
4750 } else {
4751 autoload_source_key(name, registered, from_wordcode)
4752 };
4753 if let Some((dir, sha)) = key.as_ref() {
4754 if let Some(blob) = crate::autoload_cache::try_load_for_source(name, dir, sha) {
4755 match bincode::deserialize::<fusevm::Chunk>(&blob) {
4756 Ok(chunk) if !chunk.ops.is_empty() => {
4757 tracing::debug!(
4758 name,
4759 ops = chunk.ops.len(),
4760 "autoload: rkyv chunk hit, skipping parse+compile"
4761 );
4762 let status = self.run_chunk(chunk, "autoload:cached");
4763 if self.functions_compiled.contains_key(name) {
4764 return status;
4765 }
4766 // The chunk ran and `name` is still undefined, so
4767 // it is not this function's definition program
4768 // whatever the key said. Drop it and fall through
4769 // to a real compile — a wrong answer here costs
4770 // every completion on the shell.
4771 tracing::warn!(
4772 name,
4773 "autoload: cached chunk did not define the function; \
4774 dropping the entry and recompiling"
4775 );
4776 crate::autoload_cache::try_remove(name);
4777 }
4778 _ => {}
4779 }
4780 }
4781 }
4782 let chunk = {
4783 // c:Src/exec.c:5753-5755 / c:5795 — the dump's wordcode is
4784 // installed/executed as it stands, so nothing about the live
4785 // option or alias state can reach it. zshrs lexes the deparse
4786 // instead; pin the lexer to the spelling the deparse was written
4787 // in for the duration of that compile, and only that compile.
4788 let _relex = from_wordcode.then(ZwcRelexGuard::enter);
4789 // c:Src/exec.c:6264-6266 / c:5726 — C parses the file ONCE and a
4790 // failure ends the load (`return NULL`), so exactly one diagnostic
4791 // reaches the terminal. zshrs parsed the raw body in
4792 // `autoload_definition_source` and parses the WRAPPED text again
4793 // here, so a body zsh rejects printed the error twice — the second
4794 // time shifted one line by the wrap's leading `name() {`. The
4795 // first pass already reported it against the loadee's name; mute
4796 // this one. `noerrs` still sets ERRFLAG_ERROR (c:Src/utils.c:175),
4797 // which is what `compile_script_isolated` reads, so the load still
4798 // fails.
4799 let _muted = parse_failed.then(ZerrMute::enter);
4800 self.compile_script_isolated(registered)?
4801 };
4802 if let Some((dir, sha)) = key.as_ref() {
4803 match bincode::serialize(&chunk) {
4804 Ok(blob) => {
4805 if let Err(e) = crate::autoload_cache::try_save_one(name, &blob, dir, *sha) {
4806 tracing::warn!(name, error = %e, "autoload: rkyv chunk save failed");
4807 }
4808 }
4809 Err(e) => tracing::warn!(name, error = %e, "autoload: chunk serialize failed"),
4810 }
4811 }
4812 // c:Src/exec.c:5807-5816 — installing the definition is a funcdef
4813 // store (`execode(…, "evalautofunc")` for ksh style); nothing on that
4814 // path reaches the shell-exit hooks. Running the definition through
4815 // `run_chunk_with_exit_hooks` fired the EXIT trap, `TRAPEXIT` and
4816 // `zshexit` on the first call of EVERY autoloaded function (and
4817 // consumed a string EXIT trap so it never ran at exit): `trap 'echo T'
4818 // EXIT; autoload -Uz is-at-least; is-at-least 1.0` printed T first.
4819 self.run_chunk(chunk, "autoload:compiled")
4820 }
4821
4822 /// `execute_script` — see implementation.
4823 #[tracing::instrument(skip(self, script), fields(len = script.len()))]
4824 pub fn execute_script(&mut self, script: &str) -> Result<i32, String> {
4825 // lex+parse free ported + ZshCompiler is the only execution path.
4826 self.execute_script_zsh_pipeline(script)
4827 }
4828
4829 /// Run `script` with stdout AND stderr captured, returning `(exit status,
4830 /// output)` — the entry point for an embedder that owns the terminal (a
4831 /// TUI), where a stray `echo` corrupts the display.
4832 ///
4833 /// A shell cannot capture its output into an in-process buffer the way a
4834 /// single-runtime language can: a forked child writes fd 1 directly and
4835 /// knows nothing about the parent's buffers. The capture is therefore at fd
4836 /// level, and it differs from `$(…)` in the one way that matters to an
4837 /// embedder: [`Self::run_command_substitution`] runs on a sub-VM, as a
4838 /// subshell must, so a variable it sets is gone afterwards. This runs the
4839 /// script on THIS VM, so state persists across captured runs exactly as it
4840 /// does across ordinary [`Self::execute_script`] calls.
4841 ///
4842 /// The saved fds go through `movefd` to land at fd >= 10 and marked
4843 /// `FDT_INTERNAL`, per zsh's invariant that shell-internal fds never live
4844 /// below 10 — otherwise a script doing `exec 9>&-` closes the capture's own
4845 /// bookkeeping. A temp file, not a pipe, receives the output: with no
4846 /// concurrent reader, a pipe deadlocks the moment a script writes past the
4847 /// 64 KiB buffer.
4848 ///
4849 /// # Concurrency contract
4850 ///
4851 /// **While a capture is in flight, no other thread in the process may write
4852 /// fd 1 or fd 2.** POSIX has no per-thread fd table, so pointing fd 1 at the
4853 /// capture points it there for every thread at once; any byte another thread
4854 /// writes during the window lands in the returned `String` instead of on the
4855 /// terminal. The `CAPTURE_LOCK` below excludes a second *capture*, which is
4856 /// all a lock can do — a thread that never calls this function (a logger, a
4857 /// progress meter, a test harness's own reporter) is not excluded by
4858 /// anything, and its output is silently absorbed.
4859 ///
4860 /// This is not a gap that a different capture mechanism closes. C zsh dodges
4861 /// it for `$(…)` by forking: `getoutput` (`Src/exec.c:4816`) calls `zfork`
4862 /// and only the child does `redup(pipes[1], 1)` (`Src/exec.c:4837`), so the
4863 /// parent's fd 1 is never touched — but the child then runs `entersubsh`
4864 /// (`Src/exec.c:4838`) and a variable it sets is gone. Forking here would
4865 /// throw away the one property this call exists to provide (state persists
4866 /// on THIS VM across captured runs), so the cost is paid as a contract
4867 /// instead: **capture from one thread, and quiesce the rest.**
4868 pub fn execute_script_captured(&mut self, script: &str) -> (i32, String) {
4869 use std::io::{Read, Seek, SeekFrom};
4870 use std::os::unix::io::AsRawFd;
4871
4872 /// Serializes the redirect/restore window. fd 1 belongs to the process,
4873 /// not to a `ShellExecutor`, so two threads capturing at once would
4874 /// restore each other's fds mid-run and each would read back an empty
4875 /// file. An embedder that evaluates on one thread never contends here.
4876 /// It excludes another *capture* and nothing else: see the concurrency
4877 /// contract on this function for what remains the caller's problem.
4878 static CAPTURE_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
4879 let _guard = CAPTURE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
4880
4881 let Ok(mut tmp) = tempfile::tempfile() else {
4882 // No temp file, no capture: run it anyway rather than silently
4883 // dropping the script, and report nothing captured.
4884 let status = self.execute_script(script).unwrap_or(1);
4885 return (status, String::new());
4886 };
4887
4888 // Flush Rust's buffered stdout against the REAL fd 1 before the swap,
4889 // or bytes written before this call drain into the capture instead
4890 // (the same ordering bug `run_command_substitution` documents).
4891 let _ = io::stdout().flush();
4892
4893 /// Puts fds 1 and 2 back on the way out, including when the run
4894 /// unwinds. A panic anywhere under `execute_script` would otherwise
4895 /// leave the whole PROCESS writing into a temp file that is already
4896 /// unlinked — every later write vanishes, starting with the one
4897 /// reporting the panic, which turns a localized bug into a silent one.
4898 struct RestoreFds {
4899 saved_out: i32,
4900 saved_err: i32,
4901 }
4902 impl Drop for RestoreFds {
4903 fn drop(&mut self) {
4904 let _ = io::stdout().flush();
4905 unsafe {
4906 libc::dup2(self.saved_out, libc::STDOUT_FILENO);
4907 libc::dup2(self.saved_err, libc::STDERR_FILENO);
4908 }
4909 crate::ported::utils::zclose(self.saved_out);
4910 crate::ported::utils::zclose(self.saved_err);
4911 }
4912 }
4913
4914 let saved_out = crate::ported::utils::movefd(unsafe { libc::dup(libc::STDOUT_FILENO) });
4915 let saved_err = crate::ported::utils::movefd(unsafe { libc::dup(libc::STDERR_FILENO) });
4916 unsafe {
4917 libc::dup2(tmp.as_raw_fd(), libc::STDOUT_FILENO);
4918 libc::dup2(tmp.as_raw_fd(), libc::STDERR_FILENO);
4919 }
4920 let restore = RestoreFds {
4921 saved_out,
4922 saved_err,
4923 };
4924
4925 let status = self.execute_script(script);
4926
4927 // Explicit, not end-of-scope: the temp file must be read back only
4928 // after the real fds are restored, or a diagnostic emitted while
4929 // reading would land in the very buffer being read.
4930 drop(restore);
4931
4932 let mut output = String::new();
4933 let _ = tmp.seek(SeekFrom::Start(0));
4934 let mut bytes = Vec::new();
4935 if tmp.read_to_end(&mut bytes).is_ok() {
4936 // Lossless for the same reason as the `$( cmd )` capture above:
4937 // a captured byte that is not valid UTF-8 is a byte the script
4938 // really wrote, not an encoding error to paper over.
4939 output = crate::script_bytes::decode_script_bytes(&bytes);
4940 }
4941 // Match `$(…)`: one trailing newline is an artifact of the last `echo`,
4942 // not part of the output.
4943 while output.ends_with('\n') {
4944 output.pop();
4945 }
4946
4947 (status.unwrap_or_else(|_| self.last_status()), output)
4948 }
4949
4950 /// Run an ALREADY-PARSED program (the back half of
4951 /// `execute_script_zsh_pipeline`): compile the `ZshProgram` to a
4952 /// fusevm Chunk and run it. Used by the ported `loop()` REPL
4953 /// (Src/init.c:220 `execode`), which parses via `parse_event` and
4954 /// hands the program here through the `execute_program` exec hook.
4955 /// Returns the resulting `$?` (1 on a compile/run error).
4956 pub fn execute_program(&mut self, program: &crate::parse::ZshProgram) -> i32 {
4957 let chunk = crate::compile_zsh::ZshCompiler::new().compile(program);
4958 match self.run_chunk(chunk, "loop") {
4959 Ok(status) => status,
4960 Err(_) => 1,
4961 }
4962 }
4963
4964 /// Whether `name` is a known function. Checks the compiled-functions
4965 /// table and the autoload-pending registry — `autoload foo` should
4966 /// make `whence foo`/`type foo`/`functions foo` recognize `foo` as
4967 /// a function before it's actually loaded. Doesn't trigger autoload
4968 /// itself; use `maybe_autoload` first if you need to load before
4969 /// introspecting.
4970 pub fn function_exists(&self, name: &str) -> bool {
4971 // Either compiled (already loaded) or shfunctab has an
4972 // autoload stub with PM_UNDEFINED set (pending). Matches C's
4973 // `lookupshfunc(name)` semantics at `Src/exec.c:5215`.
4974 if self.functions_compiled.contains_key(name) {
4975 return true;
4976 }
4977 crate::ported::hashtable::shfunctab_lock()
4978 .read()
4979 .ok()
4980 .map(|t| t.get(name).is_some())
4981 .unwrap_or(false)
4982 }
4983
4984 /// Sorted list of every known function name (union of compiled + source).
4985 pub fn function_names(&self) -> Vec<String> {
4986 let mut set: std::collections::BTreeSet<String> = std::collections::BTreeSet::new();
4987 for k in self.functions_compiled.keys() {
4988 set.insert(k.clone());
4989 }
4990 for k in self.function_source.keys() {
4991 set.insert(k.clone());
4992 }
4993 set.into_iter().collect()
4994 }
4995
4996 /// Dispatch a function by name. Thin passthru — autoload-materialize
4997 /// the body if needed, build a synthetic `shfunc`, and hand off to
4998 /// the canonical `doshfunc` port (`Src/exec.c:5823` →
4999 /// `src/ported/exec.rs::doshfunc`). doshfunc owns ALL scope
5000 /// management (starttrapscope/endtrapscope, startparamscope/
5001 /// endparamscope, funcdepth bump, pipestats save/restore, scriptname
5002 /// snapshot, BREAKS/CONTFLAG/LOOPS/RETFLAG snapshot+restore, `$0`
5003 /// override via FUNCTIONARGZERO, etc.). The body run itself is the
5004 /// Rust-only adaptation passed via the `body_runner` closure because
5005 /// zshrs runs function bodies through fusevm bytecode (not C zsh's
5006 /// wordcode walker via `runshfunc`).
5007 ///
5008 /// Returns `None` when the name isn't a known function so the caller
5009 /// can fall through to external dispatch.
5010 /// Body-only counterpart to [`dispatch_function_call`] — runs
5011 /// the function body WITHOUT wrapping in `doshfunc`. Used as the
5012 /// `body_runner` closure target by `src/ported/` callers that
5013 /// already wrap their own `crate::ported::exec::doshfunc(...)`
5014 /// call (so going back through `dispatch_function_call` would
5015 /// double-wrap the scope). Mirrors C's `runshfunc(prog, wrappers,
5016 /// name)` at `exec.c:6042` from doshfunc's perspective.
5017 pub fn run_function_body_only(&mut self, name: &str, args: &[String]) -> Option<i32> {
5018 // Held for the WHOLE call, not just the load: an autoloaded function is
5019 // registered TWICE — once when its file's text defines it, and again
5020 // (unchanged) when its chunk is compiled at call time — and the second
5021 // stamp would otherwise relabel it with the caller's scriptfilename.
5022 // See the AUTOLOAD_DEF_FILE consumer in fusevm_bridge.
5023 let mut _autoload_file_guard: Option<AutoloadFileGuard> = None;
5024 // Same Rust-port short-circuit as dispatch_function_call,
5025 // sans the doshfunc wrap.
5026 //
5027 // c:Src/exec.c:3760-3763 — `if (errflag) { lastval = 1; goto err; }`,
5028 // the gate execcmd_exec applies AFTER argument expansion and BEFORE it
5029 // invokes anything. A shell function whose argument list raised errflag
5030 // (`_describe -t t "${(j:,:)${(s: :)x y z}}" d` — a bad substitution)
5031 // is therefore never entered. zshrs's ordinary function path honours
5032 // that, but the compsys router short-circuits above it, so a NATIVE
5033 // PORT ran where the stock shell function did not and the completion
5034 // listed matches zsh never offered. Gate the short-circuit on the same
5035 // condition; the ordinary path below is left alone, since it already
5036 // aborts upstream.
5037 if (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0 {
5038 crate::ported::builtin::LASTVAL.store(1, Ordering::Relaxed); // c:3761
5039 return Some(1); // c:3762 goto err
5040 }
5041 if let Some(rc) = crate::compsys::router::dispatch_compsys(name, args) {
5042 // Plugin override (ABI v4) wins over the built-in Rust port.
5043 return Some(rc);
5044 }
5045 // Bug #657 gap #2 — `_regex_arguments`-generated completion functions
5046 // live in a runtime registry, not the static router table (a plain
5047 // `fn` ptr can't carry the dynamic name). Consult that registry here
5048 // so `compdef mycmd` → `_comps[cmd]=mycmd` → this call routes to the
5049 // compiled regex state machine.
5050 if let Some(rc) = crate::compsys::ported::_regex_arguments::dispatch_if_registered(name) {
5051 return Some(rc);
5052 }
5053 // c:Src/exec.c:5626 — see the twin site in
5054 // `dispatch_function_call`: a body loaded on THIS call runs one
5055 // `zsh_eval_context` frame deeper ("loadautofunc") than the
5056 // caller's "shfunc".
5057 let mut did_autoload = false;
5058 // Autoload prelude (same as dispatch_function_call's).
5059 if !self.functions_compiled.contains_key(name) {
5060 // On-demand $fpath autoload for `_`-prefixed compsys helpers that
5061 // compinit didn't register as autoload stubs — see the fuller
5062 // note in dispatch_function_call.
5063 if name.starts_with('_') && crate::ported::utils::getshfunc(name).is_none() {
5064 // c:6219 getfpfunc — gate the stub on the definition file
5065 // actually existing in $fpath, mirroring zsh's `compdef -na`
5066 // (only autoloads `_`-names present in fpath). Without this a
5067 // `_`-name with no file (e.g. a fasd completer trigger absent
5068 // from this fpath) got a phantom PM_UNDEFINED stub, and
5069 // loadautofn then leaked "function definition file not found"
5070 // to the terminal during completion. test_only=1 is a pure
5071 // probe; dump_out is preserved so .zwc-dump autoloads resolve.
5072 let mut _dir: Option<String> = None;
5073 let mut _dump = None;
5074 if crate::ported::exec::getfpfunc(name, &mut _dir, None, 1, &mut _dump).is_some() {
5075 let _ = self.execute_script_zsh_pipeline(&format!("autoload -rUz -- {name}"));
5076 }
5077 }
5078 if let Some(stub) = crate::ported::utils::getshfunc(name) {
5079 // c:Src/exec.c:5684-5704 (loadautofn) —
5080 // int noalias = noaliases;
5081 // noaliases = (shf->node.flags & PM_UNALIASED);
5082 // prog = getfpfunc(...); /* parses the file */
5083 // noaliases = noalias;
5084 // `autoload -U` records PM_UNALIASED (c:3354-3357), and its ONLY
5085 // effect is that the autoloaded body is PARSED with alias
5086 // expansion disabled. zshrs recorded the bit but never consulted
5087 // it, so a body calling `helper` picked up a caller-defined
5088 // `alias helper=...` — exactly what -U exists to prevent.
5089 let unaliased = (stub.node.flags as u32 & crate::ported::zsh_h::PM_UNALIASED) != 0;
5090 let noalias_save = crate::ported::lex::noaliases(); // c:5684
5091 crate::ported::lex::set_noaliases(unaliased); // c:5697
5092 let _restore_noaliases = NoAliasesRestore(noalias_save); // c:5704
5093 if (stub.node.flags as u32 & PM_UNDEFINED) != 0 {
5094 did_autoload = true; // c:5626 — body runs as "loadautofunc"
5095 let _sticky_load = AutoloadStickyGuard::enter(&stub);
5096 let boxed = Box::new(stub.clone());
5097 let ptr = Box::into_raw(boxed);
5098 let load_rc = crate::ported::exec::loadautofn(ptr, 0, 0, 0);
5099 unsafe {
5100 let _ = Box::from_raw(ptr);
5101 }
5102 // c:Src/exec.c:5713-5719 — `if (prog == &dummy_eprog) {
5103 // zwarn("%s: function definition file not found",
5104 // shf->node.nam); … return NULL; }`, and
5105 // c:5635-5644 execautofn: `if (!loadautofn(...)) return 1;`
5106 // A failed load is TERMINAL: C has already replaced
5107 // shf->funcdef with the mkautofn trampoline (c:3180), so
5108 // nothing of the old stub body survives to be re-run.
5109 // zshrs keeps the stub's TEXT on the shfunc node, and the
5110 // `if let Some(body)` arm below would hand that text back
5111 // to run_autoload_definition — re-executing the very
5112 // `autoload -X` that triggered this load. `cod() {
5113 // autoload -XUz }; cod` recursed until FUNCNEST and
5114 // printed the diagnostic 500 times (C04funcdef:38,39,40).
5115 if load_rc != 0 {
5116 return Some(1); // c:5719 NULL → c:5644 `return 1`
5117 }
5118 // c:5657 — preserve the fpath dir + PM_LOADDIR across the
5119 // funcdef re-register (which stamps filename="zsh"), so
5120 // `whence -v` reports the source. See the twin site below.
5121 let loaded_dir = crate::ported::utils::getshfunc(name)
5122 .and_then(|f| f.filename)
5123 .filter(|d| d != "zsh");
5124 // c:Src/exec.c:5682-5760 — C loads the body IN PLACE on the
5125 // existing Shfunc, so every stub flag except PM_UNDEFINED
5126 // survives. See the twin site below for why PM_ABSPATH_USED
5127 // in particular has to come back.
5128 let abspath_used =
5129 (stub.node.flags as u32 & crate::ported::zsh_h::PM_ABSPATH_USED) != 0;
5130 let ksh_style = autoload_is_ksh_style(name); // c:5781 (pre-registration)
5131 if let Some(body) = crate::ported::utils::getshfunc(name).and_then(|f| f.body) {
5132 _autoload_file_guard = Some(AutoloadFileGuard::enter(name));
5133 let AutoloadSource {
5134 text: registered,
5135 from_wordcode,
5136 parse_failed,
5137 } = autoload_register_source(name, &body);
5138 {
5139 // c:Src/exec.c:5735-5760 — C INSTALLS the parsed Eprog
5140 // as the function body; it executes nothing at load
5141 // time, so the global `lineno` still holds the line the
5142 // CALL was made on when doshfunc records
5143 // `funcsave->fstack.lineno = lineno` (c:6013). zshrs
5144 // installs the body by RUNNING `name() { … }` through
5145 // the pipeline, which walks the counter to the file's
5146 // last line — so the very first call of an autoloaded
5147 // function reported its caller's line as that instead:
5148 // `$functrace` read `script.zsh:1` where zsh reads
5149 // `script.zsh:4`, and inside completion `_subscript:0`
5150 // where zsh reads `_subscript:125`. Every LATER call
5151 // was already correct, because the load only happens
5152 // once.
5153 let caller_lineno = crate::ported::lex::lineno();
5154 // c:5384-5388 assigns `shf->lineno` only when a
5155 // `name() { … }` STATEMENT defines the function. An
5156 // autoload stub's Shfunc keeps the 0 it was created
5157 // with, and loadautofn replaces only `funcdef`, so zsh
5158 // reports `funcsourcetrace` as `<file>:0`. Running a
5159 // synthesized wrapper here stamps line 1 instead, so
5160 // put the stub's value back when the wrapper was ours.
5161 let synthesized = registered != body;
5162 let _ = self.run_autoload_definition(
5163 name,
5164 ®istered,
5165 ksh_style,
5166 from_wordcode,
5167 parse_failed,
5168 );
5169 crate::ported::lex::set_lineno(caller_lineno);
5170 if synthesized {
5171 // c:5384-5388 sets `shf->lineno` only where a
5172 // `name() { … }` STATEMENT defines the function; an
5173 // autoload stub keeps the 0 it was created with and
5174 // loadautofn replaces only `funcdef`, so
5175 // `funcsourcetrace` reads `<file>:0`. Executing our
5176 // synthesized wrapper records a line base of 1
5177 // instead. -1 marks "autoload-installed" so the
5178 // call-time clamp below can tell that apart from an
5179 // INLINE `f() { … }`, whose base underflows to 0 but
5180 // whose def line really is >= 1.
5181 self.function_line_base.insert(name.to_string(), -1);
5182 }
5183 }
5184 }
5185 if let Some(dir) = loaded_dir.as_deref() {
5186 restore_loaddir(name, dir, abspath_used, ksh_style);
5187 }
5188 } else if let Some(body) = stub.body.clone() {
5189 // c:Src/exec.c:5978 — the body runs under the stub's sticky
5190 // emulation; see AutoloadStickyGuard.
5191 let _sticky_load = AutoloadStickyGuard::enter(&stub);
5192 // c:Src/builtin.c:3180 (eval_autoload) — `autoload +X NAME`
5193 // loads the body EAGERLY through `loadautofn`, which sets
5194 // `body` + `filename`/PM_LOADDIR and clears PM_UNDEFINED
5195 // but leaves no compiled chunk behind. The first CALL of
5196 // such a function therefore lands in THIS arm, never the
5197 // PM_UNDEFINED arm above, so it needs the same
5198 // post-registration restore — otherwise `autoload +X
5199 // /abs/dir/NAME` lost the pair before the body ran and a
5200 // sibling `autoload -Uz SIB` inside it failed with
5201 // "function definition file not found" where zsh loads
5202 // /abs/dir/SIB. `functions[name]=body` (parameter.c
5203 // setpmfunction) reaches this arm too and simply has no
5204 // PM_LOADDIR, so the restore is skipped for it.
5205 let loaded_dir = ((stub.node.flags as u32 & crate::ported::zsh_h::PM_LOADDIR)
5206 != 0)
5207 .then(|| stub.filename.clone())
5208 .flatten();
5209 let abspath_used =
5210 (stub.node.flags as u32 & crate::ported::zsh_h::PM_ABSPATH_USED) != 0;
5211 // c:Src/Modules/parameter.c:295-315 — a body that arrived
5212 // through `functions[NAME]=BODY` is NOT a file. See
5213 // `body_came_from_param_assignment`.
5214 let param_body = body_came_from_param_assignment(stub.node.flags);
5215 let ksh_style = !param_body && autoload_is_ksh_style(name); // c:5781 (pre-registration)
5216 _autoload_file_guard = Some(AutoloadFileGuard::enter(name));
5217 // A `functions[name]=body` assignment is already a parsed
5218 // body, so it takes no file parse and cannot have reported
5219 // one (`parse_failed` is false by construction).
5220 let (registered, from_wordcode, parse_failed) = if param_body {
5221 (param_definition_source(name, &body), false, false)
5222 } else {
5223 let AutoloadSource {
5224 text,
5225 from_wordcode,
5226 parse_failed,
5227 } = autoload_register_source(name, &body);
5228 (text, from_wordcode, parse_failed)
5229 };
5230 {
5231 // c:Src/exec.c:5735-5760 — C INSTALLS the parsed Eprog
5232 // as the function body; it executes nothing at load
5233 // time, so the global `lineno` still holds the line the
5234 // CALL was made on when doshfunc records
5235 // `funcsave->fstack.lineno = lineno` (c:6013). zshrs
5236 // installs the body by RUNNING `name() { … }` through
5237 // the pipeline, which walks the counter to the file's
5238 // last line — so the very first call of an autoloaded
5239 // function reported its caller's line as that instead:
5240 // `$functrace` read `script.zsh:1` where zsh reads
5241 // `script.zsh:4`, and inside completion `_subscript:0`
5242 // where zsh reads `_subscript:125`. Every LATER call
5243 // was already correct, because the load only happens
5244 // once.
5245 let caller_lineno = crate::ported::lex::lineno();
5246 // c:5384-5388 assigns `shf->lineno` only when a
5247 // `name() { … }` STATEMENT defines the function. An
5248 // autoload stub's Shfunc keeps the 0 it was created
5249 // with, and loadautofn replaces only `funcdef`, so zsh
5250 // reports `funcsourcetrace` as `<file>:0`. Running a
5251 // synthesized wrapper here stamps line 1 instead, so
5252 // put the stub's value back when the wrapper was ours.
5253 let synthesized = registered != body;
5254 let _ = self.run_autoload_definition(
5255 name,
5256 ®istered,
5257 ksh_style,
5258 from_wordcode,
5259 parse_failed,
5260 );
5261 crate::ported::lex::set_lineno(caller_lineno);
5262 if synthesized {
5263 // c:5384-5388 sets `shf->lineno` only where a
5264 // `name() { … }` STATEMENT defines the function; an
5265 // autoload stub keeps the 0 it was created with and
5266 // loadautofn replaces only `funcdef`, so
5267 // `funcsourcetrace` reads `<file>:0`. Executing our
5268 // synthesized wrapper records a line base of 1
5269 // instead. -1 marks "autoload-installed" so the
5270 // call-time clamp below can tell that apart from an
5271 // INLINE `f() { … }`, whose base underflows to 0 but
5272 // whose def line really is >= 1.
5273 self.function_line_base.insert(name.to_string(), -1);
5274 }
5275 }
5276 if let Some(dir) = loaded_dir.as_deref() {
5277 restore_loaddir(name, dir, abspath_used, ksh_style);
5278 }
5279 }
5280 }
5281 }
5282 let chunk = self.functions_compiled.get(name).cloned()?;
5283 // c:5626 — `execode(shf->funcdef, 1, 0, "loadautofunc")`. Held
5284 // across the body run and dropped with the VM below.
5285 let _load_ctx =
5286 did_autoload.then(|| crate::ported::exec::EvalContextFrame::push("loadautofunc"));
5287 // c:Src/exec.c:5551-5557 (zsh-5.9.1, execautofn_basic) — the freshly
5288 // loaded body runs with `scriptname = shf->node.nam` and
5289 // `scriptfilename = getshfuncfile(shf)`, restored afterwards.
5290 // `doshfunc` skips its own `scriptname = name` for a PM_UNDEFINED
5291 // function (c:5835-5836), so without this every diagnostic in a body
5292 // autoloaded here kept the CALLER's name: `_complete:117:` printed as
5293 // `_main_complete:117:`. `lineno` is zeroed for the body here rather
5294 // than in `doshfunc` (see the PM_UNDEFINED note there), because the
5295 // load above must still see the caller's line.
5296 let autofn_saved = did_autoload.then(|| {
5297 let saved = (
5298 crate::ported::utils::scriptname_get(),
5299 crate::ported::utils::scriptfilename_get(),
5300 );
5301 crate::ported::utils::set_scriptname(Some(name.to_string())); // c:5553
5302 crate::ported::utils::set_scriptfilename(crate::ported::hashtable::getshfuncfile(
5303 name,
5304 )); // c:5554
5305 crate::ported::lex::set_lineno(0);
5306 saved
5307 });
5308 let seed_status = self.last_status();
5309 let _ = args; // fusevm body reads $1..$N from PPARAMS
5310 // Reuse a VM from the per-thread pool instead of building one from
5311 // scratch every call. `register_builtins` installs ~hundreds of
5312 // fn-pointer handlers into the VM's builtin_table; the table is
5313 // identical for every VM, so re-running it per function call was
5314 // pure waste (~130 profile samples in a tight call loop, the #2 hot
5315 // spot after option lookups). `VM::reset(chunk)` clears execution
5316 // state but PRESERVES builtin_table / host / JIT wiring, so a
5317 // recycled VM is call-ready without re-registration. Fresh VMs pay
5318 // the registration once. Nested calls simply check out additional
5319 // VMs; the pool grows to the max call depth. Re-entrant and
5320 // panic-safe: the VM is returned on the normal path below.
5321 // c:Src/exec.c:4364 — a `return` out of a redirected compound
5322 // command still runs `fixfds(save)`. See
5323 // `unwind_redirect_scopes_to`.
5324 let redir_depth = self.redirect_scope_stack.len();
5325 // A `return` past an open pipeline leaves its job slot held; see
5326 // exec_jobs::execpline_slots_mark.
5327 let slots_entry = crate::exec_jobs::execpline_slots_mark();
5328 let mut vm = crate::vm_pool::acquire(chunk);
5329 vm.last_status = seed_status;
5330 let _ = vm.run();
5331 let status = vm.last_status;
5332 drop(vm);
5333 crate::exec_jobs::execpline_slots_release_to(slots_entry);
5334 self.unwind_redirect_scopes_to(redir_depth);
5335 if let Some((sn, sfn)) = autofn_saved {
5336 crate::ported::utils::set_scriptname(sn); // c:5556
5337 crate::ported::utils::set_scriptfilename(sfn); // c:5557
5338 }
5339 Some(status)
5340 }
5341
5342 pub fn dispatch_function_call(&mut self, name: &str, args: &[String]) -> Option<i32> {
5343 // Held for the WHOLE call, not just the load: an autoloaded function is
5344 // registered TWICE — once when its file's text defines it, and again
5345 // (unchanged) when its chunk is compiled at call time — and the second
5346 // stamp would otherwise relabel it with the caller's scriptfilename.
5347 // See the AUTOLOAD_DEF_FILE consumer in fusevm_bridge.
5348 let mut _autoload_file_guard: Option<AutoloadFileGuard> = None;
5349 // Nested scope for `>(cmd)` fd ownership — builtins running
5350 // inside the function body must not close the CALLER's
5351 // pending psub fds (`myfn >(cmd)` keeps /dev/fd/N alive for
5352 // the whole function, like C's per-job filelist). See
5353 // PSUB_SCOPE_DEPTH in fusevm_bridge.rs.
5354 let _psub_scope = crate::fusevm_bridge::PsubScope::enter();
5355 // c:Src/exec.c — `disable -f NAME` flips the DISABLED flag on
5356 // the shfunctab entry. `lookupshfunc` (which dispatch consults)
5357 // returns NULL for DISABLED entries, falling through to PATH
5358 // lookup → "command not found". zshrs keeps the compiled body
5359 // in functions_compiled independently of the flag, so check
5360 // shfunctab and short-circuit when DISABLED is set. Bug #221
5361 // in docs/BUGS.md.
5362 let is_disabled = crate::ported::hashtable::shfunctab_lock()
5363 .read()
5364 .ok()
5365 .and_then(|t| {
5366 let entry = t.get_including_disabled(name)?;
5367 Some((entry.node.flags as u32 & crate::ported::zsh_h::DISABLED as u32) != 0)
5368 })
5369 .unwrap_or(false);
5370 if is_disabled {
5371 return None;
5372 }
5373 // `_regex_arguments NAME …` (e.g. `_regex_arguments _sed_expressions …`
5374 // in `_sed`) eval-defines a real shell function NAME in zsh. This port
5375 // stores it in a runtime registry keyed by NAME (a static router fn-ptr
5376 // can't carry a dynamic name). `run_function_body_only` already consults
5377 // that registry, but `dispatch_function_call` — the path an `_arguments`
5378 // action (`:sed script:_sed_expressions`) or any by-name caller takes —
5379 // did not, so the call fell through to the autoload prelude and errored
5380 // "function definition file not found" (`sed -<TAB>`). Consult the
5381 // registry here too, before autoload. Returned directly (like
5382 // run_function_body_only) — the regex body drives compsys globals, not
5383 // function locals, so it needs no doshfunc scope wrap.
5384 if let Some(rc) = crate::compsys::ported::_regex_arguments::dispatch_if_registered(name) {
5385 return Some(rc);
5386 }
5387 // zshrs-original: `[compsys] backend = "rust"` short-circuit.
5388 // When a `_NAME` has a Rust port AND the user opted into the
5389 // rust backend, run the Rust fn directly here — but still
5390 // through the canonical doshfunc scope-management path below
5391 // (we synthesize a body_runner from the fn pointer). Router
5392 // returns None for names without a Rust port → graceful
5393 // fallback to the shfunc autoload path.
5394 //
5395 // Note: `compcore::callcompfunc` (the compsys entry hit by
5396 // Tab) wraps doshfunc itself per C `compcore.c:835`, so the
5397 // Rust _main_complete dispatch lands HERE only when called
5398 // from a non-compcore caller (e.g. a user shell script
5399 // directly invoking `_main_complete`). The doshfunc scope
5400 // wrap below applies uniformly to both.
5401 let direct_rust_fn: Option<fn(&[String]) -> i32> =
5402 crate::compsys::router::try_rust_dispatch(name);
5403 // A plugin-registered override (ABI v4, `zmodload -R`) also
5404 // intercepts natively: it supplies the body, so no shell autoload
5405 // or compiled chunk is needed — same as a built-in Rust port.
5406 let has_plugin_override = crate::extensions::plugin_host::compfn_override(name).is_some();
5407 // c:Src/exec.c:3760-3763 — the twin of the gate in
5408 // `run_function_body_only`: a native compsys port stands in for the
5409 // COMMAND here, so it must not run when the argument expansion that
5410 // built its argument list already raised errflag. Scoped to the ported
5411 // names on purpose — this function is also the shim ports use to call
5412 // ordinary shell functions (src/ported/exec.rs:8588), and those keep
5413 // whatever behaviour the executor gives them.
5414 if (direct_rust_fn.is_some() || has_plugin_override)
5415 && (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0
5416 {
5417 crate::ported::builtin::LASTVAL.store(1, Ordering::Relaxed); // c:3761
5418 return Some(1); // c:3762 goto err
5419 }
5420 // c:Src/exec.c:5626 — the body of a function loaded on THIS call
5421 // runs through `execode(shf->funcdef, 1, 0, "loadautofunc")`
5422 // (execautofn_basic), nested inside runshfunc's "shfunc" frame.
5423 // zshrs performs the load here, before `doshfunc`, so the flag
5424 // carries the fact into the body_runner that pushes the frame.
5425 let mut did_autoload = false;
5426 // Autoload prelude skipped when a Rust port OR plugin override wins
5427 // — no upstream shell function to load.
5428 if direct_rust_fn.is_none()
5429 && !has_plugin_override
5430 && !self.functions_compiled.contains_key(name)
5431 {
5432 // c:Src/exec.c:3105-3109 — `execcmd` resolves a command word as
5433 // if (!(cflags & (BINF_BUILTIN | BINF_COMMAND)) &&
5434 // (hn = shfunctab->getnode(shfunctab, cmdarg))) {
5435 // is_shfunc = 1; break; }
5436 // the identical gate repeating at c:3484-3488, then `builtintab`,
5437 // then `$PATH`, with a name that resolves nowhere ending at c:903
5438 // `zerr("command not found: %s", arg0)`. `getnode` finds a node
5439 // ALREADY IN `shfunctab` — a real definition, or the autoload STUB
5440 // that `autoload` / `compinit` put there. A file merely PRESENT in
5441 // `$fpath` is NOT a command in zsh; nothing autoloads it on demand.
5442 //
5443 // This used to probe `$fpath` with `getfpfunc` (c:Src/exec.c:6279)
5444 // for ANY `_`-prefixed name with no shfunctab entry and, on a hit,
5445 // run `autoload -rUz -- NAME` and execute the file. That gate keyed
5446 // on the FILENAME, where zsh keys on the file's TAG LINE: compinit
5447 // sh:511-525 reads `IFS=$' \t' read -rA _i_line < $_i_file` and then
5448 // `case $_i_tag in (\#compdef) compdef -na … ;; (\#autoload)
5449 // autoload -rUz "$_i_line[@]" ${_i_name} ;; esac`, so an UNTAGGED
5450 // `_`-file is registered by neither mechanism — yet zshrs ran it:
5451 // fpath=(/tmp/d); __zzz_probe
5452 // zsh zsh:1: command not found: __zzz_probe (rc 127)
5453 // zshrs RAN (rc 0)
5454 // The cost was a SWALLOWED DIAGNOSTIC: with the untagged
5455 // `__fasd_files_comp` / `__fasd_dirs_comp` in `$fpath`, a `_files`
5456 // override offering them as `_alternative` actions makes zsh report
5457 // `_alternative:71: command not found: __fasd_files_comp`, where
5458 // zshrs reported nothing at all because it executed the file.
5459 //
5460 // Nothing replaces the probe. The providers that stand in for a
5461 // stock `$fpath` file already short-circuit ABOVE this block
5462 // (`direct_rust_fn`, `has_plugin_override`), and `compinit` installs
5463 // a real PM_UNDEFINED stub for every `#compdef`/`#autoload` file it
5464 // scans — on the scan path and from a dump alike
5465 // (`register_autoload_stubs`, src/compsys/ported/compinit.rs:831-855,
5466 // called at :1137). So the `getshfunc` below IS C's
5467 // `shfunctab->getnode`, and a name it misses falls through to
5468 // builtin → `$PATH` → command-not-found, exactly as `execcmd` does.
5469 if let Some(stub) = crate::ported::utils::getshfunc(name) {
5470 // c:Src/exec.c:5684-5704 (loadautofn) — `autoload -U` records
5471 // PM_UNALIASED, whose ONLY effect is that the autoloaded body is
5472 // PARSED with alias expansion disabled:
5473 // int noalias = noaliases;
5474 // noaliases = (shf->node.flags & PM_UNALIASED);
5475 // prog = getfpfunc(...); /* parses the file */
5476 // noaliases = noalias;
5477 let unaliased = (stub.node.flags as u32 & crate::ported::zsh_h::PM_UNALIASED) != 0;
5478 let noalias_save = crate::ported::lex::noaliases(); // c:5684
5479 crate::ported::lex::set_noaliases(unaliased); // c:5697
5480 // c:5704 — restored on EVERY exit from this block, including the
5481 // early `return Some(1)` paths below.
5482 let _restore_noaliases = NoAliasesRestore(noalias_save);
5483 if (stub.node.flags as u32 & PM_UNDEFINED) != 0 {
5484 did_autoload = true; // c:5626 — body runs as "loadautofunc"
5485 let _sticky_load = AutoloadStickyGuard::enter(&stub);
5486 let boxed = Box::new(stub.clone());
5487 let ptr = Box::into_raw(boxed);
5488 let load_rc = crate::ported::exec::loadautofn(ptr, 0, 0, 0);
5489 unsafe {
5490 let _ = Box::from_raw(ptr);
5491 }
5492 // c:Src/exec.c:5713-5719 / 5635-5644 — a failed load is
5493 // TERMINAL: `loadautofn` already emitted "function
5494 // definition file not found" and C's `execautofn` returns
5495 // 1 without ever touching a body (C replaced shf->funcdef
5496 // with the mkautofn trampoline at c:3180). zshrs still has
5497 // the stub's TEXT on the shfunc node, and the `if let
5498 // Some(body)` arm below would re-run it — for an
5499 // `autoload -X` stub that means re-entering the autoload
5500 // path, which recursed to FUNCNEST and printed the
5501 // diagnostic 500 times (C04funcdef:38,39,40). The
5502 // `else if load_rc != 0` arm below stays as the (now
5503 // unreachable) faithful mirror of the same C line.
5504 if load_rc != 0 {
5505 return Some(1); // c:5719 NULL → c:5644 `return 1`
5506 }
5507 // c:Src/exec.c:5657 loadautofnsetfile — capture the fpath
5508 // directory loadautofn wrote so it can be restored (as an
5509 // absolutized path with PM_LOADDIR) after the funcdef pipeline
5510 // below clobbers `filename` to scriptfilename ("zsh"). Without
5511 // this, `whence -v <autoloaded>` printed "from zsh".
5512 let loaded_dir = crate::ported::utils::getshfunc(name)
5513 .and_then(|f| f.filename)
5514 .filter(|d| d != "zsh");
5515 // c:Src/exec.c:5682-5760 — C loads the body IN PLACE on the
5516 // existing Shfunc: `shf->node.flags &= ~PM_UNDEFINED`
5517 // (c:5751) is the only flag C clears, so PM_ABSPATH_USED —
5518 // stamped by `autoload -Uz /abs/dir/NAME`
5519 // (`add_autoload_function`, Src/builtin.c:3290-3291) —
5520 // survives the load. zshrs re-registers the body through the
5521 // funcdef pipeline, which builds a FRESH node and drops the
5522 // whole flag word; `loadautofnsetfile` below puts filename +
5523 // PM_LOADDIR back, and PM_ABSPATH_USED has to come back with
5524 // them. It is read by `add_autoload_function`'s sibling arm
5525 // (Src/builtin.c:3310-3323): when a function loaded by
5526 // absolute path autoloads a sibling with a bare name, C
5527 // inherits the CALLER's load directory — `if ((shf2 = ...
5528 // getnode2(shfunctab, calling_f)) && (shf2->node.flags &
5529 // PM_LOADDIR) && (shf2->node.flags & PM_ABSPATH_USED) && ...`
5530 // Without the restore that test never fired, so
5531 // `autoload -Uz $D/wrapper; wrapper` → `autoload -Uz sibling`
5532 // failed with "function definition file not found" (zsh runs
5533 // $D/sibling), and compsys `_`-names fell through to the Rust
5534 // port instead of the user's file.
5535 let abspath_used =
5536 (stub.node.flags as u32 & crate::ported::zsh_h::PM_ABSPATH_USED) != 0;
5537 if let Some(body) = crate::ported::utils::getshfunc(name).and_then(|f| f.body) {
5538 let ksh_style = autoload_is_ksh_style(name); // c:5781 (pre-registration)
5539 _autoload_file_guard = Some(AutoloadFileGuard::enter(name));
5540 let AutoloadSource {
5541 text: registered,
5542 from_wordcode,
5543 parse_failed,
5544 } = autoload_register_source(name, &body);
5545 // c:Src/exec.c:5739 — the ksh-autoload body runs via
5546 // `execode(prog, 1, 0, "evalautofunc")` at the function
5547 // invocation's locallevel, so a `return`/`break`/
5548 // `continue` inside the file body is CONTAINED to the
5549 // autoload call. add-zle-hook-widget's first line is
5550 // `zmodload -e zsh/zle || return 1`; when a plugin has
5551 // leaked `ksh_autoload` on (e.g. a bare `emulate sh`),
5552 // that `return` must NOT propagate out and abort the
5553 // caller's precmd/shell (zsh warns "not defined by file"
5554 // and CONTINUES). Save & restore the control-flow flags
5555 // around the body run to reinstate that boundary.
5556 {
5557 use crate::ported::builtin::{
5558 BREAKS, EXIT_PENDING, EXIT_VAL, RETFLAG, SHELL_EXITING,
5559 };
5560 use std::sync::atomic::Ordering::Relaxed;
5561 // c:Src/exec.c:5739 — `execode(prog, 1, 0,
5562 // "evalautofunc")` runs the file body as part of the
5563 // autoload invocation. add-zle-hook-widget's
5564 // `zmodload -e zsh/zle || return 1` sits at the
5565 // file's TOP LEVEL (above its anon-func wrapper); at
5566 // script scope a top-level `return` is a shell EXIT,
5567 // so running the body as a plain script aborted the
5568 // caller's precmd/shell. `return` is contained when
5569 // `locallevel || sourcelevel` (bin_return, c:5840) —
5570 // raise SOURCELEVEL (the file-source counter, which
5571 // unlike locallevel does NOT open a local scope, so
5572 // the body's global assignments still land globally)
5573 // so the top-level `return` returns from the load
5574 // instead of exiting. Save/restore the control-flow
5575 // flags so nothing leaks — matching zsh's
5576 // warn-and-continue.
5577 use crate::ported::init::sourcelevel;
5578 let saved_retflag = RETFLAG.swap(0, Relaxed);
5579 let saved_breaks = BREAKS.swap(0, Relaxed);
5580 let saved_exit_pending = EXIT_PENDING.swap(0, Relaxed);
5581 let saved_exit_val = EXIT_VAL.swap(0, Relaxed);
5582 let saved_shell_exiting = SHELL_EXITING.swap(0, Relaxed);
5583 sourcelevel.fetch_add(1, Relaxed);
5584 {
5585 // c:Src/exec.c:5739 — the ksh-autoload branch
5586 // runs the file through
5587 // `execode(prog, 1, 0, "evalautofunc")`, so
5588 // that label is on `zsh_eval_context` while
5589 // the file body executes.
5590 let _ctx =
5591 crate::ported::exec::EvalContextFrame::push("evalautofunc");
5592 {
5593 // c:Src/exec.c:5735-5760 — C INSTALLS the parsed Eprog
5594 // as the function body; it executes nothing at load
5595 // time, so the global `lineno` still holds the line the
5596 // CALL was made on when doshfunc records
5597 // `funcsave->fstack.lineno = lineno` (c:6013). zshrs
5598 // installs the body by RUNNING `name() { … }` through
5599 // the pipeline, which walks the counter to the file's
5600 // last line — so the very first call of an autoloaded
5601 // function reported its caller's line as that instead:
5602 // `$functrace` read `script.zsh:1` where zsh reads
5603 // `script.zsh:4`, and inside completion `_subscript:0`
5604 // where zsh reads `_subscript:125`. Every LATER call
5605 // was already correct, because the load only happens
5606 // once.
5607 let caller_lineno = crate::ported::lex::lineno();
5608 // c:5384-5388 assigns `shf->lineno` only when a
5609 // `name() { … }` STATEMENT defines the function. An
5610 // autoload stub's Shfunc keeps the 0 it was created
5611 // with, and loadautofn replaces only `funcdef`, so zsh
5612 // reports `funcsourcetrace` as `<file>:0`. Running a
5613 // synthesized wrapper here stamps line 1 instead, so
5614 // put the stub's value back when the wrapper was ours.
5615 let synthesized = registered != body;
5616 let _ = self.run_autoload_definition(
5617 name,
5618 ®istered,
5619 ksh_style,
5620 from_wordcode,
5621 parse_failed,
5622 );
5623 crate::ported::lex::set_lineno(caller_lineno);
5624 if synthesized {
5625 // c:5384-5388 sets `shf->lineno` only where a
5626 // `name() { … }` STATEMENT defines the function; an
5627 // autoload stub keeps the 0 it was created with and
5628 // loadautofn replaces only `funcdef`, so
5629 // `funcsourcetrace` reads `<file>:0`. Executing our
5630 // synthesized wrapper records a line base of 1
5631 // instead. -1 marks "autoload-installed" so the
5632 // call-time clamp below can tell that apart from an
5633 // INLINE `f() { … }`, whose base underflows to 0 but
5634 // whose def line really is >= 1.
5635 self.function_line_base.insert(name.to_string(), -1);
5636 }
5637 }
5638 }
5639 sourcelevel.fetch_sub(1, Relaxed);
5640 RETFLAG.store(saved_retflag, Relaxed);
5641 BREAKS.store(saved_breaks, Relaxed);
5642 EXIT_PENDING.store(saved_exit_pending, Relaxed);
5643 EXIT_VAL.store(saved_exit_val, Relaxed);
5644 SHELL_EXITING.store(saved_shell_exiting, Relaxed);
5645 }
5646 if let Some(dir) = loaded_dir.as_deref() {
5647 restore_loaddir(name, dir, abspath_used, ksh_style);
5648 }
5649 if !self.functions_compiled.contains_key(name) {
5650 // c:Src/exec.c:5742-5745 — ksh-style load ran
5651 // the file (`execode`, "evalautofunc") but it
5652 // didn't define NAME:
5653 // `zwarn("%s: function not defined by file", n);`
5654 // That diagnostic lives INSIDE C's
5655 // `ksh == 2 || (ksh == 1 && isset(KSHAUTOLOAD))`
5656 // branch (c:5726). The zsh-style branch (c:5753-
5657 // 5758) installs the parsed program as the body
5658 // outright and cannot fail this way, so zsh prints
5659 // nothing there — and when the file did not parse,
5660 // `getfpfunc` already returned NULL and the load
5661 // ended at c:5722 with only the parse error.
5662 // zshrs used to print it for every failed
5663 // registration, so `g(){ emulate ksh -c _files }`
5664 // gained a `_files: function not defined by file`
5665 // line zsh never emits. Status still propagates:
5666 // c:5644 `if (!loadautofn(...)) return 1`.
5667 if ksh_style {
5668 crate::ported::utils::zwarn(&format!(
5669 "{}: function not defined by file",
5670 name
5671 ));
5672 }
5673 return Some(1);
5674 }
5675 } else if load_rc != 0 {
5676 // c:Src/exec.c:5713-5719 / 5635-5644 —
5677 // `execautofn`'s `if (!loadautofn(...)) return 1`
5678 // propagates the loadautofn failure as the
5679 // command's exit status. zshrs's previous
5680 // path returned None here, falling through to
5681 // execute_external which emitted a SECOND
5682 // diagnostic (`command not found: NAME`) on
5683 // top of loadautofn's `function definition
5684 // file not found`. Mirror C: when load failed
5685 // AND the stub still has no body, surface
5686 // status=1 so the caller does NOT fall back
5687 // to PATH search.
5688 return Some(1);
5689 }
5690 } else if let Some(body) = stub.body.clone() {
5691 // c:Src/exec.c:5978 — the body runs under the stub's sticky
5692 // emulation; see AutoloadStickyGuard.
5693 let _sticky_load = AutoloadStickyGuard::enter(&stub);
5694 // c:Src/Modules/parameter.c::setpmfunction — function
5695 // registered via `functions[name]=body` lives in
5696 // shfunctab with `body` set but `functions_compiled`
5697 // empty (the canonical port stores the parsed eprog,
5698 // not a fusevm Chunk). Lazy-compile here by feeding
5699 // the body through the standard funcdef pipeline so
5700 // the next CallFunction op finds the chunk.
5701 //
5702 // c:Src/builtin.c:3180 (eval_autoload) — `autoload +X NAME`
5703 // reaches this arm as well: it loads the body EAGERLY via
5704 // `loadautofn`, which sets `body` + `filename`/PM_LOADDIR
5705 // and clears PM_UNDEFINED but leaves no compiled chunk, so
5706 // the first CALL never sees the PM_UNDEFINED arm above.
5707 // Restore the load directory after re-registration exactly
5708 // as that arm does — otherwise `autoload +X /abs/dir/NAME`
5709 // dropped PM_LOADDIR|PM_ABSPATH_USED before the body ran
5710 // and a sibling `autoload -Uz SIB` inside it failed with
5711 // "function definition file not found" where zsh loads
5712 // /abs/dir/SIB. The `functions[name]=body` case has no
5713 // PM_LOADDIR, so the restore is skipped for it.
5714 let loaded_dir = ((stub.node.flags as u32 & crate::ported::zsh_h::PM_LOADDIR)
5715 != 0)
5716 .then(|| stub.filename.clone())
5717 .flatten();
5718 let abspath_used =
5719 (stub.node.flags as u32 & crate::ported::zsh_h::PM_ABSPATH_USED) != 0;
5720 // c:Src/Modules/parameter.c:295-315 — a body that arrived
5721 // through `functions[NAME]=BODY` is NOT a file. See
5722 // `body_came_from_param_assignment`.
5723 let param_body = body_came_from_param_assignment(stub.node.flags);
5724 let ksh_style = !param_body && autoload_is_ksh_style(name); // c:5781 (pre-registration)
5725 _autoload_file_guard = Some(AutoloadFileGuard::enter(name));
5726 // A `functions[name]=body` assignment is already a parsed
5727 // body, so it takes no file parse and cannot have reported
5728 // one (`parse_failed` is false by construction).
5729 let (registered, from_wordcode, parse_failed) = if param_body {
5730 (param_definition_source(name, &body), false, false)
5731 } else {
5732 let AutoloadSource {
5733 text,
5734 from_wordcode,
5735 parse_failed,
5736 } = autoload_register_source(name, &body);
5737 (text, from_wordcode, parse_failed)
5738 };
5739 {
5740 // c:Src/exec.c:5735-5760 — C INSTALLS the parsed Eprog
5741 // as the function body; it executes nothing at load
5742 // time, so the global `lineno` still holds the line the
5743 // CALL was made on when doshfunc records
5744 // `funcsave->fstack.lineno = lineno` (c:6013). zshrs
5745 // installs the body by RUNNING `name() { … }` through
5746 // the pipeline, which walks the counter to the file's
5747 // last line — so the very first call of an autoloaded
5748 // function reported its caller's line as that instead:
5749 // `$functrace` read `script.zsh:1` where zsh reads
5750 // `script.zsh:4`, and inside completion `_subscript:0`
5751 // where zsh reads `_subscript:125`. Every LATER call
5752 // was already correct, because the load only happens
5753 // once.
5754 let caller_lineno = crate::ported::lex::lineno();
5755 // c:5384-5388 assigns `shf->lineno` only when a
5756 // `name() { … }` STATEMENT defines the function. An
5757 // autoload stub's Shfunc keeps the 0 it was created
5758 // with, and loadautofn replaces only `funcdef`, so zsh
5759 // reports `funcsourcetrace` as `<file>:0`. Running a
5760 // synthesized wrapper here stamps line 1 instead, so
5761 // put the stub's value back when the wrapper was ours.
5762 let synthesized = registered != body;
5763 let _ = self.run_autoload_definition(
5764 name,
5765 ®istered,
5766 ksh_style,
5767 from_wordcode,
5768 parse_failed,
5769 );
5770 crate::ported::lex::set_lineno(caller_lineno);
5771 if synthesized {
5772 // c:5384-5388 sets `shf->lineno` only where a
5773 // `name() { … }` STATEMENT defines the function; an
5774 // autoload stub keeps the 0 it was created with and
5775 // loadautofn replaces only `funcdef`, so
5776 // `funcsourcetrace` reads `<file>:0`. Executing our
5777 // synthesized wrapper records a line base of 1
5778 // instead. -1 marks "autoload-installed" so the
5779 // call-time clamp below can tell that apart from an
5780 // INLINE `f() { … }`, whose base underflows to 0 but
5781 // whose def line really is >= 1.
5782 self.function_line_base.insert(name.to_string(), -1);
5783 }
5784 }
5785 if let Some(dir) = loaded_dir.as_deref() {
5786 restore_loaddir(name, dir, abspath_used, ksh_style);
5787 }
5788 }
5789 }
5790 }
5791 // When a Rust port is registered, skip the fusevm Chunk
5792 // lookup entirely — the body_runner closure below will run
5793 // the Rust fn pointer directly. Otherwise require a compiled
5794 // chunk for the autoloaded body.
5795 let mut chunk_opt = if direct_rust_fn.is_some() || has_plugin_override {
5796 None
5797 } else {
5798 Some(self.functions_compiled.get(name).cloned()?)
5799 };
5800
5801 // c:Src/exec.c:5634 (execshfunc) — `xtrerr = stderr;`: the body traces
5802 // to the stderr the call's own redirections set up.
5803 crate::ported::utils::xtrerr.store(2, Ordering::Relaxed);
5804
5805 // zshrs-specific bookkeeping that doshfunc doesn't own:
5806 // - prompt_funcstack (PS4 trace) push/pop
5807 // - local_scope_depth FUNCNEST guard
5808 //
5809 // c:Src/exec.c::funcnest_check — C zsh allows FUNCNEST=500 by
5810 // default. zshrs's per-call stack usage is heavier (vm_helper
5811 // state, fusevm closures, parse buffers), so on the default 8MB
5812 // stack a deep recursion overflowed around depth ~80-120 and
5813 // crashed. That is now fixed at the source: the shell runs on a
5814 // 512MB-stack thread (see bins/zshrs.rs::main), which comfortably
5815 // fits FUNCNEST (500) nested heavy frames. So the effective limit
5816 // is the user's FUNCNEST (default 500), matching zsh — no premature
5817 // clamp — with a generous hard ceiling as a last-resort backstop
5818 // that stays well under the big stack's capacity. Bug #519 (the
5819 // crash) / #643 (the false-positive clamp at 80 that broke
5820 // legitimately deep recursion). The authoritative FUNCNEST error
5821 // is also enforced in doshfunc (exec.rs) on the FS_FUNC depth.
5822 const FUNCNEST_RUST_CEILING: usize = 6000;
5823 let funcnest_user: usize = self
5824 .scalar("FUNCNEST")
5825 .and_then(|s| s.parse().ok())
5826 .unwrap_or(500);
5827 let funcnest_limit = funcnest_user.min(FUNCNEST_RUST_CEILING);
5828 if self.local_scope_depth >= funcnest_limit {
5829 // c:Src/exec.c:6060-6063 —
5830 // zerr("maximum nested function level reached; increase FUNCNEST?");
5831 // lastval = 1;
5832 // goto undoshfunc;
5833 // `zerr` is what makes this FATAL: it raises errflag, so the
5834 // enclosing list stops and a non-interactive shell exits.
5835 // zsh 5.9:
5836 // zsh -fc 'FUNCNEST=2; f() { f; }; f; printf after'
5837 // prints only the diagnostic and exits 1 — no `after`. bash
5838 // agrees ("Function invocations that exceed this nesting level
5839 // cause the current command to abort", bash(1) FUNCNEST), and
5840 // its own message is likewise followed by exit 1.
5841 //
5842 // This guard printed with a bare `eprintln!` and returned 1
5843 // WITHOUT raising errflag, so the runaway recursion stopped but
5844 // the script kept running — `printf after` ran and the shell
5845 // exited 0. The ported check in exec.rs::doshfunc already does
5846 // the C trio, but this one fires first (it is the zshrs-only
5847 // stack backstop, evaluated before dispatch reaches doshfunc),
5848 // so it has to carry the same side effects.
5849 //
5850 // The message is written here rather than through `zerr`
5851 // because C's prefix is the *function* name — `scriptname` is
5852 // the running function inside doshfunc — and this guard runs
5853 // before that switch; going through zerr would print the outer
5854 // script name instead. Byte-compared against zsh 5.9.
5855 // c:Src/utils.c zerr → zerrmsg prints `scriptname:lineno: msg`
5856 // whenever `scriptname` is set (which it is here: c:5963
5857 // `scriptname = dupstring(name)` runs BEFORE the c:6060 check).
5858 // The `:lineno` half was missing, so
5859 // ( FUNCNEST=0; fn() { true; }; fn )
5860 // printed `fn: maximum …` where zsh prints `fn:4: maximum …`
5861 // (C04funcdef:46).
5862 // c:Src/utils.c:301-308 zerrmsg — the `lineno: ` part is only
5863 // printed when `lineno` is non-zero (else a single space), so a
5864 // recursion on a function's first line reads `f: maximum …`.
5865 let lineno = crate::ported::lex::lineno();
5866 let shows_lineno = (crate::ported::zsh_h::unset(crate::ported::zsh_h::SHINSTDIN)
5867 || crate::ported::params::locallevel.here() != 0)
5868 && lineno != 0;
5869 if shows_lineno {
5870 eprintln!(
5871 "{}:{}: maximum nested function level reached; increase FUNCNEST?",
5872 name, lineno
5873 );
5874 } else {
5875 eprintln!("{}: maximum nested function level reached; increase FUNCNEST?", name);
5876 }
5877 errflag.fetch_or(ERRFLAG_ERROR, Ordering::Relaxed); // c:6061 (zerr)
5878 crate::ported::builtin::LASTVAL.store(1, Ordering::Relaxed); // c:6062
5879 return Some(1);
5880 }
5881 let display_name = if name.starts_with("_zshrs_anon_") {
5882 "(anon)".to_string()
5883 } else {
5884 name.to_string()
5885 };
5886 let line_base = self.function_line_base.get(name).copied().unwrap_or(0);
5887 let def_file = self.function_def_file.get(name).cloned().flatten();
5888 self.prompt_funcstack
5889 .push((name.to_string(), line_base, def_file));
5890 self.local_scope_depth += 1;
5891
5892 // Synthetic shfunc for doshfunc — carries the name + def-file
5893 // info so funcstack push gets a proper filename. funcdef/body
5894 // stay None because the wordcode body is irrelevant on this
5895 // path (body_runner runs the fusevm Chunk directly).
5896 // c:Src/exec.c:5390-5410 — execfuncdef records the
5897 // current `scriptfilename` on the shfunc at definition
5898 // time so funcsourcetrace can show file:line of the
5899 // function's source. The function_def_file map stores
5900 // this; fall back to the live scriptfilename so dynamic
5901 // / non-`compile_funcdef`-routed definitions still get a
5902 // sensible filename. Without the fallback, the synth_shf
5903 // saw None and the funcstack push at exec.rs:5719
5904 // defaulted to an empty string, which the funcsourcetrace
5905 // getfn rendered as `:N` (or worse, picked up the
5906 // function name from a parallel field). Bug #515.
5907 // c:Src/exec.c:5620/5625 — the source file is `getshfuncfile(shf)`,
5908 // which reads the shfunc's own `filename` (authoritative: set by
5909 // execfuncdef for a normally-defined function, and by loadautofn — as
5910 // the fpath dir with PM_LOADDIR — for an AUTOLOADED one). Prefer it.
5911 // `function_def_file` is a zshrs-only side map that, for an autoloaded
5912 // function, was stamped with the OUTER `scriptfilename` ("zsh") at
5913 // compile time, not the fpath file — so it must NOT override
5914 // getshfuncfile. Consulting it second still covers functions whose
5915 // shfunc `filename` wasn't recorded (compile_funcdef-routed defs);
5916 // scriptfilename is the final fallback. Without getshfuncfile winning,
5917 // funcsourcetrace reported "zsh" for every autoloaded completer, which
5918 // broke `_git`: its first git-completion.bash search path is
5919 // `"$(dirname ${funcsourcetrace[1]%:*})"/git-completion.bash` — "zsh"
5920 // resolved to `./git-completion.bash`, found nothing, and
5921 // `. "$script"` errored (`_git:.:48: no such file or directory`).
5922 let synth_filename = crate::ported::hashtable::getshfuncfile(name)
5923 .or_else(|| self.function_def_file.get(name).cloned().flatten())
5924 .or_else(|| self.scriptfilename.clone());
5925 // c:Src/exec.c:5409 — `shf->lineno = lineno;` (def line).
5926 // `function_line_base[name]` carries compile_funcdef's
5927 // `lineno_offset = first_body_line - 1` — equals the def line
5928 // for multi-line `f() {\n body }` but underflows to 0 for
5929 // INLINE `f() { body }` (def and body share a line). zsh's
5930 // funcsourcetrace reports the def line as 1-based, so clamp
5931 // to >= 1 to handle the inline case without rebuilding
5932 // line tracking through the parser. Bug #396.
5933 let synth_lineno = {
5934 let base = self.function_line_base.get(name).copied().unwrap_or(0);
5935 if base < 0 {
5936 // Autoload-installed (see the -1 marker at the install
5937 // site): c:5384 never runs for it, so the def line is 0.
5938 0
5939 } else {
5940 std::cmp::max(1i64, base)
5941 }
5942 };
5943 // Carry the REAL function's attribute flags over from shfunctab.
5944 // `functions -t/-T/-W` store PM_TAGGED / PM_TAGGED_LOCAL /
5945 // PM_WARNNESTED on the shfunctab node (builtin.rs c:3719), and
5946 // doshfunc turns PM_TAGGED* into XTRACE for the duration of the call
5947 // (exec.c:5954-5960). Hardcoding 0 here severed that link: the flags
5948 // were parsed and stored correctly, but the synthesized shfunc handed
5949 // to doshfunc always claimed "no attributes", so `functions -t f; f`
5950 // ran silently while `setopt xtrace` (a global option, not routed
5951 // through this struct) traced normally. Bug #1058.
5952 // The shfunctab key is the REGISTRATION name, which for an
5953 // anonymous function is the generated `_zshrs_anon_*` (only the
5954 // DISPLAY name is `(anon)` — c:Src/exec.c:5492 sets
5955 // `shf->node.nam = ANONYMOUS_FUNCTION_NAME` on the same struct
5956 // that already carries `tracing_flags` from c:5437). Looking the
5957 // flags up under the display name missed every anonymous
5958 // function, so `function -T { … }` ran untraced (E02xtrace:7,9).
5959 let synth_flags = crate::ported::hashtable::shfunctab_lock()
5960 .read()
5961 .ok()
5962 .and_then(|t| {
5963 t.get(name)
5964 .or_else(|| t.get(display_name.as_str()))
5965 .map(|s| s.node.flags)
5966 })
5967 .unwrap_or(0)
5968 // PM_LOADDIR is the ONE flag that must not ride along, because it
5969 // describes the `filename` FIELD and `synth_filename` above is not
5970 // that field — it is already `getshfuncfile`'s ANSWER.
5971 // c:Src/hashtable.c:1061 `zhtricat(shf->filename, "/", shf->node.nam)`
5972 // says PM_LOADDIR means "filename holds the fpath DIRECTORY, append
5973 // the name"; doshfunc re-applies exactly that when it builds the
5974 // funcstack frame (exec.rs c:6019, the PM_LOADDIR arm). Carrying
5975 // the flag onto a node whose filename is the resolved FILE appended
5976 // `/name` a SECOND time, so an autoloaded completer's
5977 // `$funcsourcetrace[1]` read `<dir>/_git/_git:0` where zsh reads
5978 // `<dir>/_git:0`. That is not cosmetic: `_git` (git's own zsh
5979 // wrapper) locates git-completion.bash with
5980 // `"$(dirname ${funcsourcetrace[1]%:*})"/git-completion.bash`, so
5981 // the doubled component sent it to a directory that does not exist,
5982 // left `$script` empty, and `. "$script"` failed with
5983 // `_git:.:48: no such file or directory:`. This silently undid
5984 // 8d8adf9c48, whose whole purpose was to make that search succeed.
5985 // `functions_source` / `whence -v` were unaffected — they call
5986 // `getshfuncfile` against the REAL shfunctab node, which is
5987 // correct; only the synthesized frame doubled.
5988 & !(crate::ported::zsh_h::PM_LOADDIR as i32);
5989 // c:Src/exec.c:5978 — `if (sticky_emulation_differs(shfunc->sticky))`
5990 // reads the STORED per-function sticky snapshot that
5991 // `shfunc_set_sticky` (c:5402) stamped at definition time. The
5992 // synthesized shfunc hardcoded `sticky: None`, so a function
5993 // defined under `emulate sh -c '...'` never re-entered its
5994 // emulation when called (B07emulate.ztst:6,7,8,12,13,14).
5995 // Carry it over from shfunctab like `synth_flags` above.
5996 let synth_sticky = crate::ported::hashtable::shfunctab_lock()
5997 .read()
5998 .ok()
5999 .and_then(|t| {
6000 t.get(name)
6001 .or_else(|| t.get(display_name.as_str()))
6002 .and_then(|s| {
6003 s.sticky
6004 .as_deref()
6005 .map(|b| crate::ported::exec::sticky_emulation_dup(b, 0))
6006 })
6007 });
6008 let mut synth_shf = crate::ported::zsh_h::shfunc {
6009 node: crate::ported::zsh_h::hashnode {
6010 next: None,
6011 nam: display_name.clone(),
6012 flags: synth_flags,
6013 },
6014 filename: synth_filename,
6015 lineno: synth_lineno,
6016 funcdef: None,
6017 redir: None,
6018 sticky: synth_sticky,
6019 body: None,
6020 redir_text: None,
6021 };
6022 // doshargs: C convention — argv[0] = function name (for
6023 // FUNCTIONARGZERO `$0`), argv[1..] = real positional args.
6024 let mut doshargs: Vec<String> = vec![display_name.clone()];
6025 doshargs.extend(args.iter().cloned());
6026
6027 // Seed `$?` with the parent's last status — C zsh's
6028 // doshfunc inherits lastval automatically because it's a
6029 // process-global; the fusevm VM creates a fresh
6030 // `vm.last_status = 0` per call, so we mirror the inherit
6031 // explicitly. Without this, a function reading `$?` BEFORE
6032 // running any command sees 0 instead of the caller's status.
6033 let seed_status = self.last_status();
6034 let body_args: Vec<String> = args.to_vec();
6035 let name_owned = name.to_string();
6036 let body_runner = move || -> i32 {
6037 // c:Src/exec.c:5626 — `execode(shf->funcdef, 1, 0,
6038 // "loadautofunc")`. On the call that autoloaded the function,
6039 // C runs its body one `zsh_eval_context` frame deeper than
6040 // runshfunc's "shfunc", which is why zsh reports
6041 // `shfunc:loadautofunc:…` down a chain of freshly autoloaded
6042 // completers where zshrs reported a flat `shfunc:shfunc:…`.
6043 let _load_ctx =
6044 did_autoload.then(|| crate::ported::exec::EvalContextFrame::push("loadautofunc"));
6045 // Branch: plugin override (ABI v4) → built-in Rust port →
6046 // fusevm Chunk (autoloaded shell body). All run INSIDE
6047 // doshfunc's scope so prologue/epilogue applies identically.
6048 if let Some(rc) =
6049 crate::extensions::plugin_host::dispatch_compfn(&name_owned, &body_args)
6050 {
6051 return rc;
6052 }
6053 if let Some(f) = direct_rust_fn {
6054 return crate::compsys::router::run_port(&name_owned, &body_args, f);
6055 }
6056 // The function body is already this closure's own copy (taken at
6057 // dispatch, above), and fusevm's VM owns the chunk it runs. Move
6058 // it into the VM and take it back afterwards instead of copying
6059 // it again: compinit alone runs compdef ~15,000 times, and the
6060 // second deep copy of every body was the largest single cost in
6061 // its profile. `VM::run` never writes `vm.chunk`, so what comes
6062 // back is the same body. Taking it back also keeps a repeated
6063 // invocation working — C's runshfunc runs the body again when a
6064 // wrapper handler returns `cont` after running it
6065 // (Src/exec.c runshfunc: `while (wrap) { cont = handler(...);
6066 // if (!cont) return; ... } execode(prog, ...)`).
6067 let chunk = chunk_opt
6068 .take()
6069 .expect("chunk_opt must be Some when direct_rust_fn is None");
6070 crate::fusevm_disasm::maybe_print_stdout(
6071 &format!(
6072 "function:{}",
6073 body_args.first().map(|s| s.as_str()).unwrap_or("")
6074 ),
6075 &chunk,
6076 );
6077 let mut vm = crate::vm_pool::acquire(chunk);
6078 vm.last_status = seed_status;
6079 let _ = vm.run();
6080 chunk_opt = Some(std::mem::take(&mut vm.chunk));
6081 vm.last_status
6082 };
6083
6084 // Enter executor context BEFORE doshfunc so the body_runner's
6085 // VM builtins can `with_executor(...)` to reach this state.
6086 // c:Src/exec.c:5572-5585 — execshfunc swaps in a FRESH, EMPTY cmdstack
6087 // for the duration of a shell-function call and restores the caller's
6088 // afterwards:
6089 // ocs = cmdstack; ocsp = cmdsp;
6090 // cmdstack = zalloc(CMDSTACKSZ); cmdsp = 0;
6091 // doshfunc(shf, args, 0);
6092 // free(cmdstack); cmdstack = ocs; cmdsp = ocsp;
6093 // The cmdstack is what `%_` renders, so without the swap a function
6094 // body inherits the CALLER's parser context: `f(){ print -rP "[%_]" }`
6095 // printed `[cursh]` inside `{ f }`, `[then]` inside an `if`, `[for]`
6096 // inside a loop and `[case]` inside a case arm, where zsh prints `[]`
6097 // in every one. Most visible under xtrace, whose default PS4 ends in
6098 // `%_`, so every traced line inside a called function carried a stale
6099 // field. `( f )` was already correct only because the subshell forks.
6100 // Bug #1059.
6101 let saved_cmdstack: Vec<u8> =
6102 crate::ported::prompt::CMDSTACK.with(|s| std::mem::take(&mut *s.borrow_mut()));
6103 // c:Src/exec.c:4364 — a `return` out of a redirected compound
6104 // command still runs `fixfds(save)`. See
6105 // `unwind_redirect_scopes_to`.
6106 let redir_depth = self.redirect_scope_stack.len();
6107 // c:Src/exec.c:5632-5638 — `if ((osfc = sfcontext) == SFC_NONE)
6108 // sfcontext = SFC_DIRECT; … doshfunc(shf, args, 0); sfcontext = osfc;`.
6109 // Read by the job-text gates (c:2060, c:3537): a command run inside a
6110 // function is not given the source text `time` reports as %J.
6111 let osfc = crate::ported::exec::sfcontext.load(std::sync::atomic::Ordering::Relaxed);
6112 if osfc == crate::ported::zsh_h::SFC_NONE {
6113 crate::ported::exec::sfcontext.store(
6114 crate::ported::zsh_h::SFC_DIRECT,
6115 std::sync::atomic::Ordering::Relaxed,
6116 ); // c:5633
6117 }
6118 let _ctx = ExecutorContext::enter(self);
6119 let status = crate::ported::exec::doshfunc(&mut synth_shf, doshargs, false, body_runner);
6120 drop(_ctx);
6121 crate::ported::exec::sfcontext.store(osfc, std::sync::atomic::Ordering::Relaxed); // c:5638
6122 self.unwind_redirect_scopes_to(redir_depth);
6123 crate::ported::prompt::CMDSTACK.with(|s| *s.borrow_mut() = saved_cmdstack);
6124
6125 self.prompt_funcstack.pop();
6126 self.local_scope_depth -= 1;
6127
6128 // Honor explicit `return N` from inside the function body.
6129 if let Some(ret) = self.returning.take() {
6130 self.set_last_status(ret);
6131 Some(ret)
6132 } else {
6133 self.set_last_status(status);
6134 Some(status)
6135 }
6136 }
6137
6138 pub(crate) fn execute_external(
6139 &mut self,
6140 cmd: &str,
6141 args: &[String],
6142 redirects: &[Redirect],
6143 ) -> Result<i32, String> {
6144 // FORK_EVENTS is bumped at the real spawn site inside
6145 // execute_external_bg — this entry is only ONE of several
6146 // callers of that spawn (the common static-head command path
6147 // calls execute_external_bg directly), so counting here would
6148 // miss `time sleep 0` while double-counting this path.
6149 self.execute_external_bg(cmd, args, redirects, false, 0)
6150 }
6151
6152 /// `command -p cmd …` — `execute(args, cflags, defpath=1)`.
6153 ///
6154 /// c:Src/exec.c:3212-3214 — the `command` precommand modifier's `-p`
6155 /// sets `use_defpath = 1`, and c:4369 `execute(args, cflags,
6156 /// use_defpath)` carries it into the exec. C never touches `$path` for
6157 /// this: the default-path search happens inside `execute()` alone
6158 /// (c:810-828), so `$PATH`, the child's environment and `cmdnamtab` all
6159 /// stay exactly as they were.
6160 pub(crate) fn execute_external_defpath(
6161 &mut self,
6162 cmd: &str,
6163 args: &[String],
6164 redirects: &[Redirect],
6165 ) -> Result<i32, String> {
6166 self.execute_external_bg(cmd, args, redirects, false, 1)
6167 }
6168
6169 /// Port of `execute()` from `Src/exec.c:729` — C decl
6170 /// `execute(LinkList args, int flags, int defpath)`. `defpath` is the
6171 /// third C parameter and is non-zero only for `command -p`.
6172 fn execute_external_bg(
6173 &mut self,
6174 cmd: &str,
6175 args: &[String],
6176 _redirects: &[Redirect],
6177 background: bool,
6178 defpath: i32, // c:729
6179 ) -> Result<i32, String> {
6180 tracing::trace!(cmd, bg = background, "exec external");
6181 // c:Src/exec.c:3545-3547 — `setunderscore((args && nonempty(args)) ?
6182 // ((char *) getdata(lastnode(args))) : "")`. execcmd_exec sets `$_`
6183 // to the last word of the command it is about to run, in the PARENT,
6184 // before any builtin/plugin resolution or fork — so `cat /dev/null;
6185 // print $_` reports `/dev/null` and a pipeline's stages each leave
6186 // their own last word behind. This is the single funnel every
6187 // external spawn reaches (the static-head command path calls it
6188 // directly and bypasses ZshrsHost::exec / host_exec_external), so
6189 // the write belongs here. C's `args` list carries argv[0], hence the
6190 // fallback to `cmd` for a bare command.
6191 {
6192 let last = args.last().cloned().unwrap_or_else(|| cmd.to_string());
6193 crate::ported::params::set_zunderscore(std::slice::from_ref(&last));
6194 // c:3546
6195 }
6196 // !!! WARNING: RUST-ONLY — NO C COUNTERPART !!!
6197 // Native (Rust) plugin builtins registered via `zmodload -R`
6198 // (src/extensions/plugin_host.rs). fusevm compiles unknown
6199 // names into external execution, so a plugin command arrives
6200 // here as an "external". Resolve it BEFORE the PATH-unset guard
6201 // and the process spawn — plugin builtins are in-process and
6202 // need no PATH. This is the analog of C's `resolvebuiltin`
6203 // slot (Src/exec.c:2700), which likewise runs before the fork.
6204 // Bare names only: a `/`-qualified token is always a filesystem
6205 // path, never a plugin command name. Runs synchronously even
6206 // when backgrounded — zshrs is non-forking and an in-process
6207 // builtin has nothing to background.
6208 if !cmd.contains('/') {
6209 if let Some(status) = crate::plugin_host::dispatch(cmd, args) {
6210 return Ok(status);
6211 }
6212 }
6213 // !!! WARNING: RUST-ONLY — NO C COUNTERPART !!!
6214 // Host-registered native commands (`extensions/native_cmds.rs`) — the
6215 // sibling runtimes a fat binary links into the shell's address space:
6216 // `git` (zvcs), `arb` (arblang) and `stryke` (strykelang) in the
6217 // zshrs-native build. Same slot and same reason as the plugin-builtin
6218 // dispatch directly above: the compiler has never heard of these names,
6219 // so it lowered them to external execution and they arrive here — this
6220 // is where they must be caught, BEFORE the PATH guard and before the
6221 // spawn, because an in-process builtin needs no PATH and no process.
6222 //
6223 // Two escape hatches to the binary on disk stay open, and both are
6224 // checked here. A `/`-qualified token (`/usr/bin/git`) is a filesystem
6225 // path the user named, never a registry key. And `command git`
6226 // explicitly asks past the in-process one — the `command` handler
6227 // raises `native_cmds::force_external` around this call, exactly as
6228 // `command cat` already escapes the coreutils shadow.
6229 //
6230 // The registry's contract is full argv (argv[0] = the name as
6231 // invoked), which zvcs reads for its `git-<verb>` dashed form.
6232 //
6233 // Empty in the thin shell: one map lookup that always misses.
6234 if !cmd.contains('/')
6235 && !crate::native_cmds::is_forced_external()
6236 && crate::native_cmds::is_enabled(cmd)
6237 {
6238 let full: Vec<String> = std::iter::once(cmd.to_string())
6239 .chain(args.iter().cloned())
6240 .collect();
6241 if let Some(status) = crate::native_cmds::dispatch(cmd, &full) {
6242 return Ok(status);
6243 }
6244 }
6245 // c:Src/exec.c:824-876 — when arg0 has no `/`, C zsh requires
6246 // a PATH search. With PATH unset, the search yields no hit
6247 // and C emits `command not found: <cmd>`. Rust's
6248 // `Command::new(name)` delegates to libc `execvp`, which on
6249 // many platforms falls back to a built-in default PATH when
6250 // the env entry is missing — so `unset PATH; ls` still finds
6251 // `/bin/ls` and runs it, breaking the security boundary the
6252 // unset is supposed to establish (#416). Gate explicitly:
6253 // when cmd is a bare name (no `/`) and zshrs's own PATH
6254 // param is unset OR empty, emit the canonical
6255 // "command not found" diagnostic and return 127 BEFORE
6256 // touching libc.
6257 //
6258 // c:810-815 — `if (defpath) { … search_defpath(arg0, …) … }` runs
6259 // INSTEAD OF the `$path` walk, so `command -p` must not be judged by
6260 // `$PATH` at all: the oracle runs `PATH=; command -p awk …` fine.
6261 if !cmd.contains('/') && defpath == 0 {
6262 let path_set_and_nonempty = crate::ported::params::getsparam("PATH")
6263 .map(|p| !p.is_empty())
6264 .unwrap_or(false);
6265 if !path_set_and_nonempty {
6266 let sn =
6267 crate::ported::utils::scriptname_get().unwrap_or_else(|| "zshrs".to_string());
6268 // c:Src/exec.c:811 `zerr("command not found: %s", arg0)`
6269 // — the diagnostic carries the CURRENT line, not a
6270 // hardcoded 1. `lineno()` is the same counter zwarning
6271 // (utils.rs:179) uses and is live during VM execution
6272 // (verified: read-only / div-by-zero errors already
6273 // report the right line). Emitted directly (not via
6274 // zerr) to avoid setting errflag — command-not-found is
6275 // non-fatal and the script must continue.
6276 // Inline Rust FFI export: needs no PATH, so run it here rather
6277 // than reporting not-found when PATH is unset/empty.
6278 if let Some(rc) = self.try_registered_ffi_command(cmd, args) {
6279 return Ok(rc);
6280 }
6281 eprintln!("{}: command not found: {}", zerr_prefix(&sn), crate::ported::utils::nicedupstring(&cmd));
6282 return Ok(127);
6283 }
6284 }
6285 // c:Src/exec.c:2700-2724 resolvebuiltin — names registered via
6286 // `zmodload -ab MOD NAME` resolve through builtintab BEFORE
6287 // PATH search in C (execcmd's builtin lookup precedes the
6288 // external fork). Names the compiler didn't know as builtins
6289 // land here; consult the autoload ledger, load the module,
6290 // and re-dispatch through the builtin chokepoint. Without
6291 // this, `zmodload -ab zsh/bogus mybltn; mybltn` skipped the
6292 // C autoload-fire entirely (PATH miss → 127 instead of the
6293 // load_module diagnostic → 1).
6294 if !cmd.contains('/') {
6295 if let Some(rc) = crate::ported::exec::resolvebuiltin(cmd) {
6296 if rc != 0 {
6297 return Ok(1);
6298 }
6299 return Ok(crate::fusevm_bridge::dispatch_builtin_raw(
6300 cmd,
6301 args.to_vec(),
6302 ));
6303 }
6304 }
6305 // c:Src/exec.c:3655-3675 — execcmd_exec's external-command
6306 // resolution, the step that populates `cmdnamtab`:
6307 //
6308 // hn = cmdnamtab->getnode(cmdnamtab, cmdarg); c:3661
6309 // if (!hn && dohashcmd && strcmp(cmdarg, "..")) { c:3671
6310 // for (s = cmdarg; *s && *s != '/'; s++); c:3672
6311 // if (!*s) hn = (HashNode) hashcmd(cmdarg, ...); c:3674
6312 // }
6313 //
6314 // and c:831-869 in `execute()`, which turns the resulting node into
6315 // the pathname it hands `zexecve`: a HASHED entry execs `cn->u.cmd`
6316 // verbatim, an unhashed one execs `"<*cn->u.name>/<arg0>"`.
6317 //
6318 // Neither step ran here. This is the funnel every statically-spelled
6319 // external command reaches (`awk …` compiles to a fusevm exec op →
6320 // host_exec_external → here), and it handed the bare word straight to
6321 // `Command::new`, i.e. to libc `execvp`, which does its own PATH walk
6322 // and knows nothing about the shell's table. Two consequences:
6323 // `cmdnamtab` stayed empty for the whole life of the shell, so `hash`
6324 // listed nothing after running a command and everything reading the
6325 // table (`hash`, `unhash`, `whence`, `$commands`, completion) saw an
6326 // empty one; and an explicit `hash awk=/bin/echo` was ignored at exec
6327 // time because libc re-derived the path from `$PATH`. Only the
6328 // run-time-resolved head (`c=awk; $c …`) went through execcmd_exec
6329 // and hashed correctly, which is why the gap was invisible from the
6330 // ported side.
6331 //
6332 // `hashed_prog` also records that the pathname came from the table,
6333 // so the ENOENT arms below can fall back to the bare name the way
6334 // c:877 `execute_skip_exec:` falls through to a full `$path` walk
6335 // when the cmdnamtab candidate fails to exec.
6336 let mut hashed_prog: Option<String> = None;
6337 // c:3672-3673 — bare names only; a `/` in the word means the user
6338 // named a file and C never consults the table for it. c:3671 —
6339 // `..` is excluded by name.
6340 if !cmd.contains('/') && cmd != ".." {
6341 // c:3661 — `cmdnamtab->getnode(cmdnamtab, cmdarg)`.
6342 let mut have = crate::ported::hashtable::cmdnamtab_lock()
6343 .read()
6344 .ok()
6345 .and_then(|t| t.get(cmd).cloned());
6346 // c:3659 + c:3671 — `dohashcmd = isset(HASHCMDS)`.
6347 if have.is_none() && crate::ported::zsh_h::isset(crate::ported::zsh_h::HASHCMDS) {
6348 // c:3674 — `hashcmd(cmdarg, checkpath)`. Passing the whole
6349 // `$path` matches the sibling call in execcmd_exec
6350 // (exec.rs:11106) and hashcmd's own indexing of `pathchecked`.
6351 let dirs: Vec<String> = crate::ported::params::getsparam("PATH")
6352 .unwrap_or_default()
6353 .split(':')
6354 .map(String::from)
6355 .collect();
6356 have = crate::ported::exec::hashcmd(cmd, &dirs);
6357 }
6358 if have.is_some() {
6359 // c:834 / c:861 — `cn->u.cmd` for a HASHED node, else
6360 // `"<*cn->u.name>/<arg0>"`. `get_full_path` is that arm.
6361 hashed_prog = crate::ported::hashtable::cmdnamtab_lock()
6362 .read()
6363 .ok()
6364 .and_then(|t| t.get_full_path(cmd))
6365 .map(|p| p.display().to_string());
6366 }
6367 }
6368 // c:Src/exec.c:3650-3652 + c:3678-3685 — AUTOCD. With no command
6369 // found, a one-word command with no redirections, in a shell
6370 // reading commands from its input (SHINSTDIN), that names a
6371 // directory — or, under CDABLEVARS, a parameter or user whose value
6372 // or home is one — runs as `cd -- DIR`:
6373 // trycd = isset(AUTOCD) && isset(SHINSTDIN) && (!redir ||
6374 // empty(redir)) && args && !empty(args) &&
6375 // !nextnode(firstnode(args)) && *peekfirst(args);
6376 // if (!hn && trycd && (s = cancd(peekfirst(args)))) { … "cd" … }
6377 // The ported execcmd_exec carries this; the compiled path every
6378 // literal command takes reaches only here, so `tmp` from `/`,
6379 // `/tmp` or a CDABLEVARS name reported "command not found".
6380 if hashed_prog.is_none()
6381 && defpath == 0
6382 && args.is_empty()
6383 && !cmd.is_empty()
6384 && crate::ported::zsh_h::isset(crate::ported::zsh_h::AUTOCD)
6385 && crate::ported::zsh_h::isset(crate::ported::zsh_h::SHINSTDIN)
6386 && !crate::fusevm_bridge::own_redirect_scope(self)
6387 {
6388 if let Some(dir) = crate::ported::exec::cancd(cmd) {
6389 return Ok(crate::fusevm_bridge::dispatch_builtin_raw(
6390 "cd",
6391 vec!["--".to_string(), dir],
6392 ));
6393 }
6394 }
6395 // c:Src/exec.c:810-828 — `/* for command -p, search the default path */
6396 // if (defpath) {
6397 // char pbuf[MAXCMDLEN];
6398 // if (!search_defpath(arg0, pbuf, MAXCMDLEN)) {
6399 // if (commandnotfound(arg0, args) == 0) _realexit();
6400 // zerr("command not found: %s", arg0);
6401 // _exit(127);
6402 // }
6403 // ee = zexecve(pbuf, argv, newenvp);
6404 // } else { … cmdnamtab / $path walk … }`
6405 //
6406 // The two arms are mutually exclusive in C, so under `-p` the exec'd
6407 // pathname is the DEFAULT_PATH hit and nothing else — no `$path` walk,
6408 // no bare-name retry, and a miss is final even when the name sits on
6409 // `$PATH`. The `cmdnamtab` population above still runs because it is
6410 // NOT part of `execute()`: it belongs to `execcmd_exec` in the parent
6411 // (c:3671-3674), which hashes `cmdarg` against `$path` regardless of
6412 // `use_defpath`. That asymmetry is visible in the oracle — after
6413 // `PATH=<dir-with-a-fake-awk>:…; command -p awk`, the REAL
6414 // `/usr/bin/awk` runs while the table records the fake one.
6415 //
6416 // c:798-808 runs before this and execs a `/`-bearing arg0 directly, so
6417 // `defpath` never applies to a name the user spelled as a path.
6418 let mut defpath_prog: Option<String> = None;
6419 if defpath != 0 && !cmd.contains('/') {
6420 // c:815 — `if (!search_defpath(arg0, pbuf, MAXCMDLEN))`
6421 match crate::ported::exec::search_defpath(cmd, libc::PATH_MAX as usize) {
6422 // c:822 — `ee = zexecve(pbuf, argv, newenvp)`
6423 Some(pbuf) => defpath_prog = Some(pbuf),
6424 None => {
6425 // c:816-817 — `if (commandnotfound(arg0, args) == 0)
6426 // _realexit();`. The `command_not_found_handler` hook
6427 // runs for a default-path miss exactly as it does for a
6428 // `$path` miss, and its status is the command's status.
6429 // The `$path` miss reaches the same hook from the ENOENT
6430 // arm further down, after the spawn has failed; there is
6431 // no spawn to fail here, so the call is explicit.
6432 let mut hook_args = Vec::with_capacity(args.len() + 1);
6433 hook_args.push(cmd.to_string());
6434 hook_args.extend_from_slice(args);
6435 if let Some(rc) =
6436 self.dispatch_function_call("command_not_found_handler", &hook_args)
6437 {
6438 return Ok(rc);
6439 }
6440 let sn = crate::ported::utils::scriptname_get()
6441 .unwrap_or_else(|| "zshrs".to_string());
6442 // c:818 — `zerr("command not found: %s", arg0)`. Emitted
6443 // directly rather than through `zerr` for the same reason
6444 // as the PATH-unset arm above: command-not-found is
6445 // non-fatal and must not raise errflag.
6446 eprintln!("{}: command not found: {}", zerr_prefix(&sn), crate::ported::utils::nicedupstring(&cmd));
6447 return Ok(127); // c:819 `_exit(127)`
6448 }
6449 }
6450 }
6451 // c:Src/exec.c:758-776 — "If ARGV0 is in the commands environment, we
6452 // use that as argv[0] for this external command" and unsetenv it; else
6453 // "if the pre-command `-' was given, we add `-' to the front of
6454 // argv[0] for this command."
6455 let carrier = crate::fusevm_bridge::take_exec_carrier();
6456 let job_text = crate::fusevm_bridge::take_job_text();
6457 let exec_dash = carrier & crate::fusevm_bridge::EXEC_CARRIER_DASH != 0;
6458 // c:Src/exec.c:4369 — this process was forked for the command
6459 // (BUILTIN_EXEC_FORKED_SIMPLE): exec it here rather than spawn.
6460 //
6461 // !!! WARNING: RUST-ONLY !!! C's multio helpers are forked tee/cat
6462 // processes (closemn, c:Src/exec.c:2288), so they outlive the execve
6463 // that replaces the shell. zshrs runs them as threads of the shell
6464 // (multios_scope_stack), and an execve kills every thread: the
6465 // concatenator of `cat <o1 <<<x` died before writing (cat read EOF)
6466 // and the splitter of `/bin/echo hi >a >b` left the command writing
6467 // into a pipe nobody reads (SIGPIPE, both files empty). While any
6468 // such thread is live the command is spawned and waited for instead,
6469 // which lets the threads finish before the shell exits. The command
6470 // still takes the shell's place for SHLVL, as it does in C.
6471 let exec_forked = !background && carrier & crate::fusevm_bridge::EXEC_CARRIER_FORKED != 0;
6472 let multio_threads_live = self.multios_scope_stack.iter().any(|scope| !scope.is_empty());
6473 let in_place = exec_forked && !multio_threads_live;
6474 if exec_forked && carrier & crate::fusevm_bridge::EXEC_CARRIER_SHLVL != 0 {
6475 crate::fusevm_bridge::exec_shlvl_decrement(); // c:Src/exec.c:4334-4336
6476 }
6477 let argv0_env = std::env::var("ARGV0").ok(); // c:760 zgetenv("ARGV0")
6478 let mut argv: Vec<String> = Vec::with_capacity(args.len() + 1);
6479 argv.push(match &argv0_env {
6480 Some(z) => z.clone(), // c:761
6481 None if exec_dash => format!("-{}", cmd), // c:775-776
6482 None => cmd.to_string(),
6483 });
6484 argv.extend_from_slice(args);
6485
6486 // c:Src/jobs.c — `time` reports only on JOBS (forked work). This
6487 // is the single chokepoint where an external process is actually
6488 // spawned (both fg and bg, all callers), AFTER the
6489 // command-not-found and resolvebuiltin early-returns above — so
6490 // counting here makes BUILTIN_TIME_SUBLIST report `time sleep 0`
6491 // / `time /usr/bin/true` (external → fork) while staying silent
6492 // for `time true` (builtin, never reaches this point). The
6493 // subshell entry counts separately (fusevm_bridge.rs:9573).
6494 FORK_EVENTS.fetch_add(1, std::sync::atomic::Ordering::Relaxed);
6495 // c:Src/exec.c:4352 `closem(FDT_INTERNAL, 0)` before execve.
6496 crate::lowfd::cloexec_internal_fds();
6497
6498 // Redirect handling lives in fusevm's WithRedirectsBegin/End
6499 // ops at compile time; `_redirects` arrives empty here.
6500 let spawned = if background {
6501 execute_spawn(cmd, &argv, defpath_prog.as_deref(), hashed_prog.as_deref(), argv0_env.is_some(), false)
6502 .map_err(|eno| (eno, None))
6503 } else {
6504 // Queue signals across the wait so zshrs's SIGCHLD reaper
6505 // (waitpid(-1) in wait_for_processes, delivered on any thread)
6506 // can't reap this child before the wait does, and claim the
6507 // status back when it wins anyway — see foreground_status.
6508 let _wait_guard = crate::fusevm_bridge::ForegroundWaitGuard::enter();
6509 match execute_spawn(cmd, &argv, defpath_prog.as_deref(), hashed_prog.as_deref(), argv0_env.is_some(), in_place) {
6510 Ok(pid) => match crate::fusevm_bridge::wait_pid_status(pid) {
6511 Ok(status) => {
6512 use std::os::unix::process::ExitStatusExt as _;
6513 drop(_wait_guard);
6514 // c:Src/jobs.c:645-650 — update_job reports the finished job.
6515 crate::exec_jobs::foreground_job_report(
6516 status.into_raw(),
6517 job_text,
6518 !self.subshell_snapshots.is_empty(),
6519 );
6520 // c:Src/jobs.c:654-679 — update_job's foreground tail.
6521 crate::exec_jobs::foreground_job_signalled(status.into_raw());
6522 return Ok(crate::exec_jobs::wait_status_val(status));
6523 }
6524 Err(e) => Err((0, Some(e))),
6525 },
6526 Err(eno) => Err((eno, None)),
6527 }
6528 };
6529 let sn = crate::ported::utils::scriptname_get().unwrap_or_else(|| "zshrs".to_string());
6530 let eno = match spawned {
6531 Ok(pid) => {
6532 let cmd_str = format!("{} {}", cmd, args.join(" "));
6533 let job_id = self.jobs.add_pid_job(pid, cmd_str, JobState::Running);
6534 println!("[{}] {}", job_id, pid);
6535 return Ok(0);
6536 }
6537 Err((_, Some(e))) => return Err(format!("{}: {}: {}", sn, cmd, e)),
6538 Err((eno, None)) => eno,
6539 };
6540 // c:Src/exec.c:871-881 — `if (eno) zerr("%e: %s", eno, arg0); else
6541 // if (commandnotfound(arg0, args) == 0) _realexit(); else
6542 // zerr("command not found: %s", arg0); _exit((eno == EACCES || eno
6543 // == ENOEXEC) ? 126 : 127);`. Emitted directly rather than through
6544 // `zerr`: C prints from the doomed child, so the parent's errflag is
6545 // never raised and the script continues.
6546 if eno != 0 {
6547 eprintln!(
6548 "{}: {}: {}",
6549 zerr_prefix(&sn),
6550 crate::ported::utils::zsh_errno_msg(eno),
6551 cmd
6552 );
6553 return Ok(if eno == libc::EACCES || eno == libc::ENOEXEC { 126 } else { 127 });
6554 }
6555 // c:873 — the `command_not_found_handler` user hook; its status is
6556 // the command's status. Documented in zshmisc(1) under "Special
6557 // Functions". Bug #426.
6558 if !background {
6559 let mut hook_args = Vec::with_capacity(args.len() + 1);
6560 hook_args.push(cmd.to_string());
6561 hook_args.extend_from_slice(args);
6562 if let Some(rc) = self.dispatch_function_call("command_not_found_handler", &hook_args) {
6563 return Ok(rc);
6564 }
6565 }
6566 // Inline Rust FFI export: consulted after builtins, functions, PATH
6567 // search, and command_not_found_handler have all missed — real
6568 // commands keep priority. In the background an in-process FFI call
6569 // has nothing to background, so it runs synchronously.
6570 if let Some(rc) = self.try_registered_ffi_command(cmd, args) {
6571 return Ok(rc);
6572 }
6573 eprintln!("{}: command not found: {}", zerr_prefix(&sn), crate::ported::utils::nicedupstring(&cmd));
6574 Ok(127)
6575 }
6576 /// !!! WARNING: RUST-ONLY — NO C COUNTERPART !!!
6577 /// Inline Rust FFI fallback: when `cmd` names a function exported by a
6578 /// `rust { ... }` block (registered by the `__rust_compile` builtin) run it
6579 /// as a command. Consulted only when `cmd` resolved to nothing else — not a
6580 /// builtin, function, plugin, external on `$PATH`, or
6581 /// `command_not_found_handler` — so real commands keep priority. Positional
6582 /// args are marshalled as strings; fusevm coerces each to the export's
6583 /// signature (`i64` / `f64` / `*const c_char`). The return value is printed
6584 /// to stdout (the redirect-aware process fd 1) and the command exits 0.
6585 /// Bare names only — a `/`-qualified token is a filesystem path, never an
6586 /// FFI export. Returns `None` when `cmd` is not a registered export, so the
6587 /// caller emits its normal "command not found".
6588 fn try_registered_ffi_command(&self, cmd: &str, args: &[String]) -> Option<i32> {
6589 if cmd.contains('/') || !fusevm::ffi::is_registered(cmd) {
6590 return None;
6591 }
6592 let vals: Vec<fusevm::Value> = args.iter().map(|a| fusevm::Value::str(a.clone())).collect();
6593 match fusevm::ffi::try_call(cmd, &vals) {
6594 Some(Ok(v)) => {
6595 use std::io::Write as _;
6596 let mut out = io::stdout().lock();
6597 let _ = writeln!(out, "{}", v.to_str());
6598 let _ = out.flush();
6599 Some(0)
6600 }
6601 Some(Err(e)) => {
6602 eprintln!("zshrs: {e}");
6603 Some(1)
6604 }
6605 // Registered a moment ago but the entry vanished (registry race) —
6606 // treat as unresolved and let the caller report command-not-found.
6607 None => None,
6608 }
6609 }
6610
6611 /// Parse `cmd_str` via parse_init+parse and pull out the first Simple
6612 /// command's words, untokenized + variable-expanded, ready to spawn
6613 /// as argv. Used by process-substitution where we need raw argv to
6614 /// hand to `Command::new`. Returns empty vec if the cmd isn't a
6615 /// simple shape — pipelines / compound forms aren't process-sub
6616 /// friendly anyway.
6617 fn simple_cmd_words(&mut self, cmd_str: &str) -> Vec<String> {
6618 // Mirror Src/init.c-style errflag save/clear/check around the
6619 // parse. Process-sub argv extraction silently bails on syntax
6620 // errors (matches zsh's behavior when the inner command can't
6621 // be parsed).
6622 let saved_errflag = errflag.load(Ordering::Relaxed);
6623 errflag.fetch_and(!ERRFLAG_ERROR, Ordering::Relaxed);
6624 // Context-isolated nested parse (c:Src/exec.c:283 parse_string) —
6625 // same rationale as run_command_substitution: process-sub argv
6626 // extraction runs during execution and must not clobber the outer
6627 // single-event reader's lexer/input position.
6628 let prog = parse_isolated(cmd_str);
6629 let parse_failed = (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0;
6630 errflag.store(saved_errflag, Ordering::Relaxed);
6631 if parse_failed {
6632 return Vec::new();
6633 }
6634 let first = match prog.lists.first() {
6635 Some(l) => l,
6636 None => return Vec::new(),
6637 };
6638 let pipe = &first.sublist.pipe;
6639 if let crate::parse::ZshCommand::Simple(simple) = &pipe.cmd {
6640 simple
6641 .words
6642 .iter()
6643 .map(|w| {
6644 // Untokenize then variable-expand — text-based
6645 // word expansion for the spawned argv.
6646 let untoked = crate::lex::untokenize(w);
6647 singsub(&untoked)
6648 })
6649 .collect()
6650 } else {
6651 Vec::new()
6652 }
6653 }
6654 /// `run_command_substitution` — see implementation.
6655 /// The SQLite mirror, opened the first time anything asks for it.
6656 ///
6657 /// Returns `None` when no cache file exists yet (or it failed to open),
6658 /// which is the same answer the eager constructor produced.
6659 pub fn compsys_cache(&self) -> Option<&CompsysCache> {
6660 self.compsys_cache
6661 .get_or_init(|| {
6662 let cache_path = crate::compsys::cache::default_cache_path();
6663 if !cache_path.exists() {
6664 tracing::debug!("compsys: no cache at {}", cache_path.display());
6665 return None;
6666 }
6667 let db_size = fs::metadata(&cache_path).map(|m| m.len()).unwrap_or(0);
6668 match CompsysCache::open(&cache_path) {
6669 Ok(c) => {
6670 tracing::info!(
6671 db_bytes = db_size,
6672 path = %cache_path.display(),
6673 "compsys: sqlite mirror opened (dbview/SQL inspection only; rkyv shards are the authoritative cache)"
6674 );
6675 Some(c)
6676 }
6677 Err(e) => {
6678 tracing::warn!(error = %e, "compsys: failed to open cache");
6679 None
6680 }
6681 }
6682 })
6683 .as_ref()
6684 }
6685
6686 pub fn run_command_substitution(&mut self, cmd_str: &str) -> String {
6687 // c:Src/subst.c / Src/lex.c — the text inside `$(…)` is a FRESH
6688 // command line. The double quotes that may surround the substitution
6689 // apply to its RESULT, not to the words inside it: in `"$(f $x)"` the
6690 // `$x` is unquoted. `in_dq_context` is the runtime signal the
6691 // `${(flags)…}` bridges read for paramsubst's `qt` (c:1625), and it
6692 // stayed set for the whole body, so every flag-expansion inside a
6693 // DQ command substitution ran as if quoted.
6694 //
6695 // What that broke: `qt` suppresses RC_EXPAND_PARAM's word removal, so
6696 // under `setopt rcexpandparam` an EMPTY array kept a word instead of
6697 // deleting it (c:4327's `while ((x = *aval++))` emits nothing for an
6698 // empty array; the `!plan9` single-empty-word path at c:4261 is the
6699 // one that must NOT run):
6700 // setopt rcexpandparam
6701 // f() { declare -a x; print "n=$(set -- H ${(q)x}; print $#)" }
6702 // f # zsh: n=1, zshrs was n=2
6703 // Only the `"$(…)"` spelling was affected — unquoted `$(…)`,
6704 // backticks, and `v=$(…)` were all already correct, which is what
6705 // made it look like a quoting bug rather than an option bug.
6706 //
6707 // Bit through compsys: completion runs with rcexpandparam ON, and
6708 // `_git`'s __git_recent_commits passes `${(q)commit_opts}` to
6709 // `_call_program` inside `"$(…)"`. The stray empty word became a
6710 // bogus `''` argument to `git rev-list`, the command failed, and
6711 // `git checkout <TAB>` lost its whole recent-commits group.
6712 //
6713 // `SUBEXP_SCALAR_CTX` carries the same thing one level down — it is
6714 // what a NESTED expansion reads as `subexp_dq` (subst.rs:18873) to
6715 // learn that its OUTER `${…}` was quoted. A `$(…)` inside a quoted
6716 // outer expansion is still a fresh command line, so it has to be
6717 // cleared too:
6718 // setopt rcexpandparam
6719 // f() { declare -a co; local -a c
6720 // c=("${(f)"$(cmd HEAD ${(q)co})"}") }
6721 // is `_git`'s exact shape, and the leaked context flipped c:4354's
6722 // `mark_empty`, keeping the empty element that plan9 must delete.
6723 let saved_dq = std::mem::replace(&mut self.in_dq_context, 0);
6724 let saved_subexp = crate::ported::subst::SUBEXP_SCALAR_CTX.with(|c| c.replace(0));
6725 let out = self.run_command_substitution_inner(cmd_str, false);
6726 crate::ported::subst::SUBEXP_SCALAR_CTX.with(|c| c.set(saved_subexp));
6727 self.in_dq_context = saved_dq;
6728 out
6729 }
6730
6731 /// ksh93 funsub `${ list; }` / mksh valsub `${| list; }` — capture the
6732 /// output of `cmd_str` WITHOUT the subshell isolation `$( … )` applies.
6733 ///
6734 /// ksh(1), Command Substitution: "${ command;} … the command is
6735 /// executed in the current shell environment", so an assignment or a
6736 /// `cd` inside survives:
6737 /// `ksh -c 'x=0; y=${ x=5; print -n out; }; print "x=$x y=$y"'`
6738 /// → `x=5 y=out`, where the same body in `$( … )` leaves `x` at 0.
6739 /// mksh behaves identically for both of its forms.
6740 ///
6741 /// Same capture machinery as `$( … )` — only the parent-state
6742 /// snapshot/restore is skipped, which is exactly the difference the
6743 /// two references document.
6744 ///
6745 /// !!! RUST-ONLY ENTRY POINT — zsh has no funsub/valsub !!!
6746 pub fn run_shared_state_substitution(&mut self, cmd_str: &str) -> String {
6747 let saved_dq = std::mem::replace(&mut self.in_dq_context, 0);
6748 let saved_subexp = crate::ported::subst::SUBEXP_SCALAR_CTX.with(|c| c.replace(0));
6749 let out = self.run_command_substitution_inner(cmd_str, true);
6750 crate::ported::subst::SUBEXP_SCALAR_CTX.with(|c| c.set(saved_subexp));
6751 self.in_dq_context = saved_dq;
6752 out
6753 }
6754
6755 /// `shared_state`: skip the parent-state snapshot/restore that makes
6756 /// `$( … )` a subshell. Only the ksh/mksh funsub-valsub entry point
6757 /// passes true.
6758 fn run_command_substitution_inner(&mut self, cmd_str: &str, shared_state: bool) -> String {
6759 // `$(< FILE)` — zsh shorthand for "read FILE contents". Faster
6760 // than spawning `cat`. The leading `<` (after stripping
6761 // whitespace) means "read this file". Trailing newline is
6762 // stripped (same as command-substitution).
6763 let trimmed = cmd_str.trim_start();
6764 // Only treat as `$(<file)` shorthand when the SINGLE leading `<`
6765 // is followed by a filename, not another `<`. `$(<<<"hi" cat)`
6766 // starts with `<<<` (here-string) and must go through the full
6767 // parse path, not the read-file shortcut.
6768 if let Some(rest) = trimmed.strip_prefix('<').filter(|s| !s.starts_with('<')) {
6769 let filename = rest.trim();
6770 // c:Src/lex.c — the `$(<file)` shortcut ONLY applies when
6771 // the body is exactly `<` + ONE word. Anything else (extra
6772 // args, redirects, semicolons, pipes) is a regular command
6773 // list and must go through the full parse path so `2>/dev/null`
6774 // / `>file` / `|cmd` / `; next` etc. work. Without this
6775 // gate, `$(< file 2>/dev/null)` treated `file 2>/dev/null`
6776 // as the literal filename and errored on the missing file.
6777 // Bug #615.
6778 let is_single_word = !filename.is_empty()
6779 && !filename.chars().any(|c| {
6780 matches!(
6781 c,
6782 ' ' | '\t'
6783 | '\n'
6784 | ';'
6785 | '&'
6786 | '|'
6787 | '<'
6788 | '>'
6789 | '('
6790 | ')'
6791 | '`'
6792 | '"'
6793 | '\''
6794 )
6795 });
6796 if is_single_word {
6797 // Expand any leading $ / tilde in the filename so
6798 // `$(< $f)` and `$(< ~/x)` work.
6799 let resolved = if filename.contains('$') || filename.starts_with('~') {
6800 singsub(filename)
6801 } else {
6802 filename.to_string()
6803 };
6804 let resolved = resolved.to_string();
6805 // c:Src/exec.c `readoutput` — `$(<file)` reads the file a
6806 // BYTE at a time and metafies (`if (imeta(c)) { *ptr++ =
6807 // Meta; ... }`); it does not require UTF-8.
6808 match crate::script_bytes::read_script_file(&resolved) {
6809 Ok(contents) => {
6810 return contents.trim_end_matches('\n').to_string();
6811 }
6812 Err(e) => {
6813 // c:Src/exec.c:4797-4800 — `zwarn("%e: %s", errno, s);
6814 // lastval = cmdoutval = 1; return newlinklist();`.
6815 // zwarn carries the real `<script>:<line>:` prefix.
6816 crate::ported::utils::zwarn(&format!(
6817 "{}: {}",
6818 crate::ported::utils::zsh_errno_msg(
6819 e.raw_os_error().unwrap_or(libc::ENOENT)
6820 ),
6821 resolved
6822 ));
6823 self.set_last_status(1); // c:4799
6824 crate::ported::exec::cmdoutval.store(1, Ordering::Relaxed);
6825 return String::new();
6826 }
6827 }
6828 }
6829 // Multi-word / has-redirects → fall through to full parse.
6830 }
6831
6832 // Port of getoutput(char *cmd, int qt) from Src/exec.c. Parse and compile via
6833 // the lex+parse free ported + ZshCompiler pipeline, run on a
6834 // sub-VM with the host wired up. Stdout is captured through
6835 // an in-process pipe via dup2 — no fork. The sub-VM emits
6836 // Op::Exec for unknown command names, which forks/execs
6837 // through the host.
6838
6839 // Set up the stdout-capture pipe. We dup the original stdout
6840 // so post-run we can restore it; the write end is dup2'd onto
6841 // STDOUT_FILENO so all output the sub-VM emits (including from
6842 // forked children, which inherit fd 1) lands in the pipe.
6843 //
6844 // c:Src/exec.c:4753 — `if (mpipe(pipes) < 0)`. mpipe (c:5160)
6845 // moves BOTH pipe ends to fd >= 10 via movefd and marks them
6846 // FDT_INTERNAL. This is load-bearing: zsh's invariant is that
6847 // shell-internal fds never live below 10, so user redirections
6848 // like `exec 9>&-` (which close fd<10 unconditionally, no
6849 // FDT_INTERNAL guard — c:Src/exec.c:3856-3868) can never hit
6850 // them. A raw pipe() here landed the read end on fd 9 when
6851 // fresh-HOME init held fds 3-7, and A04redirect's %prep
6852 // `exec 9>&-` closed our own capture pipe → SIGPIPE killed
6853 // the whole shell.
6854 let (read_fd, write_fd) = {
6855 let mut fds = [0i32; 2];
6856 if crate::ported::exec::mpipe(&mut fds) < 0 {
6857 return String::new();
6858 }
6859 // The read end stays open while the body runs in process; C's
6860 // forked body closes it (c:Src/exec.c:4839), so it must not sit
6861 // where the body's `{var}` allocations land.
6862 (crate::lowfd::movefd_past_script(fds[0]), fds[1])
6863 };
6864 // c:Src/utils.c:1996 — `movefd(dup(fd))`: saved copies of the
6865 // user-visible fds are shell-internal (FDT_INTERNAL), and since
6866 // they exist only for the in-process body they sit past the
6867 // script's `{var}` range too (movefd_past_script).
6868 // A CLOSED stdout saves as -1 and is closed again on the way out
6869 // (c:Src/utils.c:2047-2048 redup `if (x < 0) zclose(y)`). C's forked
6870 // getoutput child needs no save at all (c:4840 `redup(pipes[1], 1)`),
6871 // so the body runs either way: bailing out here lost everything the
6872 // body did, `{ x=$(print b >&2) } >&-` never printed `b`.
6873 let saved_stdout =
6874 crate::lowfd::movefd_past_script(unsafe { libc::dup(libc::STDOUT_FILENO) });
6875 // Flush Rust's stdout BufWriter against the ORIGINAL fd before
6876 // dup2 swaps fd 1 to the capture pipe. Without this, bytes left
6877 // buffered by a prior `print -n` get drained to fd 1 AFTER the
6878 // dup2, which routes them into the cmd-subst's pipe — they end
6879 // up in the captured result and disappear from terminal output.
6880 //
6881 // Bug #10 in docs/BUGS.md — `print -n "A"; v=$(true); print -n
6882 // "B"; v=$(true); print -n "C"; echo` printed only `C` because
6883 // `A` and `B` were redirected into the empty cmd-subst's pipe
6884 // and discarded as its "output". C zsh's getoutput() forks, so
6885 // the child inherits the buffer COPY and the parent's buffer
6886 // stays untouched; zshrs runs cmd-subst in-process so the
6887 // parent buffer is the only one — must flush before the swap.
6888 let _ = io::stdout().flush();
6889 // c:Bug #56 — publish the saved outer stdout so a trap firing
6890 // during the nested run routes body output to the parent's
6891 // real stdout instead of the cmdsub's pipe-bound fd 1.
6892 // Same as saved_stdout above.
6893 let saved_stderr_for_trap =
6894 crate::lowfd::movefd_past_script(unsafe { libc::dup(libc::STDERR_FILENO) });
6895 // A job the body forks must not keep them: they belong to the
6896 // parent C never forked the body from (see mark_saved_fd).
6897 crate::fusevm_bridge::mark_saved_fd(saved_stdout);
6898 crate::fusevm_bridge::mark_saved_fd(saved_stderr_for_trap);
6899 crate::fusevm_bridge::CMDSUBST_OUTER_FDS
6900 .with(|s| s.borrow_mut().push((saved_stdout, saved_stderr_for_trap)));
6901 unsafe {
6902 libc::dup2(write_fd, libc::STDOUT_FILENO);
6903 }
6904 // zclose (not raw close) so the FDT_INTERNAL mark set by mpipe
6905 // is cleared from fdtable — c:Src/utils.c:2137.
6906 crate::ported::utils::zclose(write_fd);
6907
6908 // Drain the capture pipe CONCURRENTLY on a background reader
6909 // thread. The sub-VM (and any children it forks, which inherit
6910 // fd 1) writes to the pipe; reading it only AFTER vm.run()
6911 // returns deadlocks the moment the output exceeds the OS pipe
6912 // buffer (~64KB): the writer blocks on a full pipe that nothing
6913 // is draining, so vm.run() never returns. `$(alias)` over
6914 // zpwr's 2000+ aliases (~177KB) hung the whole shell a few
6915 // prompts in (thefuck's `fuck()` init runs `TF_SHELL_ALIASES=
6916 // $(alias)`). C's getoutput (Src/exec.c) forks the writer child
6917 // so the parent reads concurrently; this reader thread is the
6918 // in-process analog. It does only raw fd reads (no shell state /
6919 // thread-locals). EOF arrives once every write end closes — fd 1
6920 // restored below plus any forked child exiting.
6921 let reader_handle = std::thread::spawn(move || {
6922 let mut buf: Vec<u8> = Vec::new();
6923 let mut chunk = [0u8; 65536];
6924 loop {
6925 let n = unsafe {
6926 libc::read(
6927 read_fd,
6928 chunk.as_mut_ptr() as *mut libc::c_void,
6929 chunk.len(),
6930 )
6931 };
6932 if n < 0 {
6933 // Retry on EINTR (a signal interrupted the read);
6934 // any other error ends the drain.
6935 let e = std::io::Error::last_os_error().raw_os_error().unwrap_or(0);
6936 if e == libc::EINTR {
6937 continue;
6938 }
6939 break;
6940 }
6941 if n == 0 {
6942 break; // EOF — all write ends closed.
6943 }
6944 buf.extend_from_slice(&chunk[..n as usize]);
6945 }
6946 buf
6947 });
6948
6949 // c:Src/exec.c:1161 — forked cmdsub child runs entersubsh()
6950 // which does `zsh_subshell++`; in-process equivalent (RAII,
6951 // restored on every return path below).
6952 // A funsub/valsub is NOT a subshell — ksh(1) says the command runs
6953 // "in the current shell environment" — so it must not bump the
6954 // nesting counter `$ZSH_SUBSHELL` / `$BASH_SUBSHELL` reads.
6955 let _subshell_bump = if shared_state {
6956 None
6957 } else {
6958 Some(crate::fusevm_bridge::CmdSubstSubshellBump::enter())
6959 };
6960
6961 // c:Src/exec.c:1208-1209 — the same forked child clears
6962 // `opts[USEZLE]` and `zleactive`. Without it a substitution run
6963 // from inside a widget still looks "in ZLE", so `fc` refuses with
6964 // "no interactive history within ZLE" (c:Src/builtin.c:1523-1527)
6965 // and history-based completers come back empty. Placed here rather
6966 // than in exec::getoutput so the bridge's own cmdsubst paths
6967 // (BUILTIN_CMD_SUBST_TEXT, backtick) are covered too.
6968 let _subsh_state = crate::ported::exec::SubshStateGuard::enter();
6969
6970 // Parse + compile + run.
6971 // Push CS_CMDSUBST for `%_` xtrace prefix — direct port of
6972 // Src/exec.c:4783 `cmdpush(CS_CMDSUBST);` around execode().
6973 // Trace lines emitted by the inner program inherit this token
6974 // so their PS4 prefix shows "cmdsubst" matching zsh -x.
6975 cmdpush(crate::ported::zsh_h::CS_CMDSUBST as u8); // c:zsh.h:2799
6976 // Save LINENO so the inner cmdsubst's line counter doesn't
6977 // leak into the outer trace — direct port of Src/exec.c:1407
6978 // `oldlineno = lineno;` followed by `lineno = oldlineno;`
6979 // restore at line 1640. Inner program parses fresh as line 1
6980 // and increments from there; once it returns, the outer
6981 // line at the `$(…)` site must read the original outer
6982 // lineno (so xtrace renders `+:5:> echo …` not `+:1:> …`).
6983 let saved_lineno = getsparam("LINENO");
6984 // Anchor the inner program's lineno to the outer's current
6985 // $LINENO so xtrace inside the cmdsubst renders the outer
6986 // line. zsh's execlist preserves lineno across the inner
6987 // exec — for our sub-VM (fresh compile) nested_lineno_base maps
6988 // inner line N → outer_lineno + (N - 1), outer 0 included.
6989 let outer_lineno: u64 = self
6990 .scalar("LINENO")
6991 .and_then(|s| s.parse::<u64>().ok())
6992 .unwrap_or(0);
6993 // Mirror Src/init.c errflag save/clear/check pattern around
6994 // the nested parse so an inner syntax error doesn't bleed into
6995 // the outer execution.
6996 let saved_errflag = errflag.load(Ordering::Relaxed);
6997 errflag.fetch_and(!ERRFLAG_ERROR, Ordering::Relaxed);
6998 // Context-isolated nested parse (c:Src/exec.c:283 parse_string).
6999 // The outer loop()/parse_event reader may be mid-stream when this
7000 // cmd-subst executes (single-event mode), so a destructive
7001 // parse_init/lex_init would clobber its next read. parse_isolated
7002 // brackets the parse with zcontext_save/restore + inpush/inpop.
7003 let parsed = parse_isolated_at(cmd_str, Some(outer_lineno)); // c:4778 parse_string(cmd, 0)
7004 let parse_failed = (errflag.load(Ordering::Relaxed) & ERRFLAG_ERROR) != 0;
7005 errflag.store(saved_errflag, Ordering::Relaxed);
7006 let prog = if parse_failed { None } else { Some(parsed) };
7007 let mut cmd_status: Option<i32> = None;
7008 if let Some(prog) = prog {
7009 let mut compiler = crate::compile_zsh::ZshCompiler::new();
7010 compiler.nested_lineno_base = Some(outer_lineno); // c:Src/exec.c:4778
7011 let chunk = compiler.compile(&prog);
7012 if !chunk.ops.is_empty() {
7013 crate::fusevm_disasm::maybe_print_stdout("run_command_substitution", &chunk);
7014 // c:Src/exec.c:4783 — `$(...)` runs in a subshell, so
7015 // assignments / setopt / cd / trap changes inside
7016 // mustn't leak to the parent. zsh forks; we run
7017 // in-process and snapshot/restore manually. Same
7018 // snapshot shape used by host_subshell_begin/end for
7019 // the `(...)` subshell form.
7020 let paramtab_snap = crate::ported::params::paramtab()
7021 .read()
7022 .ok()
7023 .map(|t| t.clone())
7024 .unwrap_or_default();
7025 let paramtab_hashed_snap = crate::ported::params::paramtab_hashed_storage()
7026 .lock()
7027 .ok()
7028 .map(|m| m.clone())
7029 .unwrap_or_default();
7030 let pparams_snap = self.pparams();
7031 let opts_snap = crate::ported::options::opt_state_snapshot();
7032 // c:Src/exec.c:1161 — a command substitution runs in a
7033 // subshell, so IFS changes inside it must NOT leak to the
7034 // parent. IFS lives in the external `ifs_lock` global (not
7035 // paramtab), so the paramtab snapshot above doesn't cover
7036 // it: `echo $(IFS=:; set -- a b c; echo "$*")` set IFS=":"
7037 // which both produced "a:b:c" AND then word-split the
7038 // UNQUOTED result on the leaked ":" → "a b c". Snapshot the
7039 // global IFS here and restore it (with inittyptab) below.
7040 let ifs_snap = crate::ported::params::ifs_lock()
7041 .lock()
7042 .map(|g| g.clone())
7043 .unwrap_or_default();
7044 let traps_snap = crate::ported::builtin::traps_table()
7045 .lock()
7046 .map(|t| t.clone())
7047 .unwrap_or_default();
7048 // c:Src/exec.c:4783 — function definitions / unfunction
7049 // inside `$(...)` must also be isolated from the parent.
7050 // C zsh's getoutput() forks, so the child's shfunctab
7051 // mutations die with the child. zshrs's in-process
7052 // cmd-subst needs to snapshot/restore the function
7053 // tables manually alongside the param/opts/trap snaps
7054 // already in this block. Bug #455.
7055 let shfunctab_snap = crate::ported::hashtable::shfunctab_lock()
7056 .read()
7057 .ok()
7058 .map(|t| t.snapshot())
7059 .unwrap_or_default();
7060 let functions_compiled_snap = self.functions_compiled.clone();
7061 let function_source_snap = self.function_source.clone();
7062 // c:Src/exec.c:4816 — what the forked child owns a copy of:
7063 // hash tables, `environ`, cwd, umask, rlimits, …; see
7064 // SubshForkCopy.
7065 // A funsub/valsub runs in the current shell and keeps it all.
7066 let tables_snap = (!shared_state).then(crate::ported::exec::SubshForkCopy::save);
7067 let locale_snap = (!shared_state).then(subsh_locale_save).flatten();
7068 let fd_frame = (!shared_state).then(crate::ported::exec::SubshFdFrame::enter);
7069 // c:Src/exec.c:1127-1131 — the child's `entersubsh` unsets
7070 // every trap that is not function-form (`$(trap)` lists
7071 // nothing), in ITS copy of `sigtrapped[]`. Keep the
7072 // parent's for the restore, and route signals that arrive
7073 // meanwhile to it — same as `( … )`, see
7074 // fusevm_bridge::subshell_defer_signal.
7075 let sigtrapped_snap = (!shared_state).then(|| {
7076 let parent = crate::ported::signals::sigtrapped
7077 .lock()
7078 .map(|g| g.clone())
7079 .unwrap_or_default();
7080 crate::fusevm_bridge::subshell_signal_enter();
7081 crate::fusevm_bridge::entersubsh_reset_traps();
7082 parent
7083 });
7084 // c:Src/exec.c:4782 — getoutput's child runs
7085 // `entersubsh(ESUB_PGRP|ESUB_NOMONITOR)`, and c:1219
7086 // `if (flags & ESUB_PGRP) clearjobtab(monitor)` hands
7087 // that child an EMPTY job table. The oldjobtab snapshot
7088 // (c:Src/jobs.c:1800) is monitor-only, so a
7089 // non-interactive shell keeps nothing at all — which is
7090 // why zsh prints nothing for `sleep 5 & print $(jobs)`.
7091 // The `(...)` and pipeline-stage paths already call
7092 // clearjobtab in their forked children; cmd-subst runs
7093 // in-process, so snapshot the globals clearjobtab
7094 // mutates and restore them below. freejob (c:1457) is
7095 // struct-local — no waitpid/kill — so the restore is
7096 // exact.
7097 // c:Src/exec.c:4782 — same fork, one more thing it copies:
7098 // the completion-match arena (c:Src/Zle/compcore.c:124-259).
7099 // A `compadd` run inside `$(…)` lands in the CHILD's
7100 // `matches`/`amatches`/`mgroup`, which die with it, so the
7101 // completing parent never sees those matches. zshrs's
7102 // in-process cmd-subst shares the arena, so `_tmux`'s
7103 // `desc="$(_tmux-backup)"` description probe leaked five
7104 // whole completion groups into `tmux <TAB>` (551 matches vs
7105 // zsh's 450). Snapshot/restore it by hand, exactly as the
7106 // param/opts/trap/job snaps above do.
7107 let comp_arena_snap = crate::comp_match_handles::comp_arena_save();
7108 // !!! WARNING: RUST-ONLY LOCK DISCIPLINE !!! zhandler's SIGCHLD
7109 // branch locks JOBTAB (c:Src/signals.c:429-431 → update_bg_job)
7110 // on whichever thread the signal interrupts. C's jobtab is a
7111 // plain array; here a SIGCHLD landing while this thread holds
7112 // the JOBTAB mutex (the snapshot, clearjobtab, and the restore
7113 // below, which also drops the child's table under the lock)
7114 // blocks the handler forever: `echo $(echo a &) w` hung.
7115 // Queue signals across both windows (c:Src/signals.c:410-424).
7116 crate::ported::signals_h::queue_signals();
7117 let jobtab_snap = crate::ported::jobs::JOBTAB
7118 .get()
7119 .and_then(|t| t.lock().ok().map(|g| g.clone()));
7120 let maxjob_snap = crate::ported::jobs::MAXJOB
7121 .get()
7122 .and_then(|m| m.lock().ok().map(|g| *g));
7123 let thisjob_snap = crate::ported::jobs::THISJOB
7124 .get()
7125 .and_then(|t| t.lock().ok().map(|g| *g));
7126 // curjob/prevjob (c:Src/jobs.c) are plain globals in C,
7127 // so the forked child's setcurjob calls never reach the
7128 // parent — restore them alongside the table, else the
7129 // `+`/`-` markers are lost after a `$(jobs)`.
7130 let curjob_snap = crate::ported::jobs::CURJOB
7131 .get()
7132 .and_then(|t| t.lock().ok().map(|g| *g));
7133 let prevjob_snap = crate::ported::jobs::PREVJOB
7134 .get()
7135 .and_then(|t| t.lock().ok().map(|g| *g));
7136 // Pipeline job slots the body takes come from the cleared
7137 // table below; their records go when the parent's comes back.
7138 let slots_snap = crate::exec_jobs::execpline_slots_mark();
7139 {
7140 let monitor = crate::ported::zsh_h::isset(crate::ported::zsh_h::MONITOR) as i32;
7141 crate::ported::jobs::clearjobtab(&mut self.jobs, monitor);
7142 }
7143 crate::ported::signals_h::unqueue_signals();
7144 let mut vm = fusevm::VM::new(chunk);
7145 register_builtins(&mut vm);
7146 vm.set_shell_host(Box::new(ZshrsHost));
7147 // Seed inner $? with the outer's last_status so the
7148 // sub-shell inherits the parent's exit code. Direct
7149 // port of Src/exec.c:4783 around execcmd_exec — the
7150 // child inherits `lastval` at fork time, so `false;
7151 // echo $(echo $?)` reads 1, not the freshly-zeroed
7152 // sub-VM default. Without this, every cmd-subst
7153 // started with $?==0 regardless of the parent's
7154 // last command.
7155 vm.last_status = self.last_status();
7156 // `exit N` inside a cmd-subst should terminate ONLY
7157 // the sub-shell (C zsh: cmd-subst forks, the child
7158 // `_exit(N)`s; status reaches the parent as
7159 // cmd-subst exit). zshrs runs in-process, so we
7160 // route through the SUBSHELL_DEPTH-gated deferred
7161 // path inside zexit (builtin.rs:7713): bump
7162 // SUBSHELL_DEPTH so `exit` sets EXIT_PENDING/
7163 // EXIT_VAL instead of calling realexit (which would
7164 // process::exit and kill the parent shell). After
7165 // the sub-VM returns, harvest EXIT_PENDING/EXIT_VAL
7166 // as the cmd-subst's status, then restore the
7167 // parent's flags so the outer VM continues normally.
7168 use crate::ported::builtin::{
7169 BREAKS, EXIT_PENDING, EXIT_VAL, RETFLAG, SHELL_EXITING, SUBSHELL_DEPTH,
7170 };
7171 use std::sync::atomic::Ordering::Relaxed;
7172 let saved_exit_pending = EXIT_PENDING.swap(0, Relaxed);
7173 let saved_exit_val = EXIT_VAL.swap(0, Relaxed);
7174 let saved_shell_exiting = SHELL_EXITING.swap(0, Relaxed);
7175 let saved_retflag = RETFLAG.swap(0, Relaxed);
7176 let saved_breaks = BREAKS.swap(0, Relaxed);
7177 // c:Src/exec.c:4784 — `execode(prog, 0, 1, "cmdsubst");`.
7178 // execode (c:1245-1266) APPENDS its `context` argument to
7179 // `zsh_eval_context` for the duration of the body, so code
7180 // inside `$(…)` / backticks sees `cmdarg:cmdsubst` where the
7181 // top level sees just `cmdarg`. zshrs pushed "shfunc" at the
7182 // function-call site but never pushed "cmdsubst", so
7183 // `$(print $ZSH_EVAL_CONTEXT)` reported `cmdarg` and
7184 // `$(f)` reported `cmdarg:shfunc` instead of
7185 // `cmdarg:cmdsubst:shfunc`. Popped on every return path by the
7186 // guard below, mirroring execode's stack discipline.
7187 // Bug #1065.
7188 let sync_eval_ctx = |stack: &[String]| {
7189 let joined = stack.join(":");
7190 if let Ok(mut tab) = crate::ported::params::paramtab().write() {
7191 if let Some(pm) = tab.get_mut("zsh_eval_context") {
7192 pm.u_arr = Some(stack.to_vec());
7193 pm.node.flags &= !(crate::ported::zsh_h::PM_UNSET as i32);
7194 }
7195 if let Some(pm) = tab.get_mut("ZSH_EVAL_CONTEXT") {
7196 pm.u_str = Some(joined);
7197 pm.node.flags &= !(crate::ported::zsh_h::PM_UNSET as i32);
7198 }
7199 }
7200 };
7201 if let Ok(mut ctx) = crate::ported::exec::zsh_eval_context.lock() {
7202 ctx.push("cmdsubst".to_string());
7203 sync_eval_ctx(&ctx);
7204 }
7205 struct CmdsubstEvalCtxGuard<F: Fn(&[String])>(F);
7206 impl<F: Fn(&[String])> Drop for CmdsubstEvalCtxGuard<F> {
7207 fn drop(&mut self) {
7208 if let Ok(mut ctx) = crate::ported::exec::zsh_eval_context.lock() {
7209 ctx.pop();
7210 (self.0)(&ctx);
7211 }
7212 }
7213 }
7214 let _cs_eval_ctx_guard = CmdsubstEvalCtxGuard(sync_eval_ctx);
7215 SUBSHELL_DEPTH.fetch_add(1, Relaxed);
7216 let _ctx = ExecutorContext::enter(self);
7217 let _ = vm.run();
7218 let inner_exit_pending = EXIT_PENDING.load(Relaxed);
7219 let inner_exit_val = EXIT_VAL.load(Relaxed);
7220 let inner_status = if inner_exit_pending != 0 {
7221 inner_exit_val & 0xFF
7222 } else {
7223 vm.last_status
7224 };
7225 cmd_status = Some(inner_status);
7226 SUBSHELL_DEPTH.fetch_sub(1, Relaxed);
7227 // c:Src/exec.c — `$(…)` is a FORK in C: an errflag
7228 // abort inside the child ends the child (its lastval
7229 // becomes the cmd-subst status) and the flag dies
7230 // with the child process — the parent's lists keep
7231 // running. zsh 5.9: `v=$(typeset -A q; q=(odd));
7232 // echo "after $?"` prints `after 1`. Mirror the fork
7233 // isolation by clearing ERRFLAG_ERROR at the
7234 // cmd-subst boundary.
7235 //
7236 // ERRFLAG_HARD dies here too: `${u:?msg}` inside the
7237 // child sets it (c:Src/subst.c:3344) then `_exit(1)`s
7238 // (c:3353) — C's parent never sees the bit. A leaked
7239 // HARD bit makes every later zerr() silent
7240 // (c:Src/utils.c:175-177) and silently fails every
7241 // later parse. Same fix as subshell_end.
7242 // A nofork `${ … }` is no fork: c:Src/subst.c:2056 leaves the
7243 // body's errflag set, so the command around it aborts.
7244 if !shared_state {
7245 errflag.fetch_and(
7246 !(ERRFLAG_ERROR | crate::ported::zsh_h::ERRFLAG_HARD),
7247 Relaxed,
7248 );
7249 }
7250 // c:Src/exec.c:4783 execcmdoutsubst — `$(...)` is a
7251 // subshell, and zsh fires the EXIT trap when the
7252 // subshell ends BUT only if the trap was installed
7253 // INSIDE the subshell. An EXIT trap inherited from
7254 // the parent fires when the parent shell exits, not
7255 // again at cmdsub end. Detect "installed inside" by
7256 // comparing the current traps_table["EXIT"] entry
7257 // against the pre-cmdsub snapshot — fire only when
7258 // the body differs (newly set, removed, or replaced).
7259 // Pop the body before execute_script to avoid the
7260 // re-fire inside execute_script_zsh_pipeline's own
7261 // EXIT-handler tail at vm_helper.rs:1490. Bug #354.
7262 let snap_exit = traps_snap.get("EXIT").cloned();
7263 let live_exit = crate::ported::builtin::traps_table()
7264 .lock()
7265 .ok()
7266 .and_then(|t| t.get("EXIT").cloned());
7267 if !shared_state && live_exit != snap_exit {
7268 if let Some(body) = live_exit {
7269 if let Ok(mut t) = crate::ported::builtin::traps_table().lock() {
7270 t.remove("EXIT");
7271 }
7272 let _ = crate::ported::exec::execute_script(&body);
7273 }
7274 }
7275 // c:Src/signals.c::dotrap(SIGEXIT) — also fire the
7276 // TRAPEXIT() function-named form (ZSIG_FUNC) — but
7277 // only if it was defined INSIDE the subshell (the
7278 // parent's TRAPEXIT fires at parent exit, not here).
7279 // ZSIG_FUNC bit on sigtrapped[SIGEXIT] tells us
7280 // whether a TRAPEXIT function is registered; check
7281 // BEFORE the snapshot restore.
7282 // Skip for now — function-form detection mirrors the
7283 // raw-body check above; deferred until a clean
7284 // sigtrapped snapshot/restore pair exists.
7285 // Restore parent's exit / loop / function-return
7286 // state so the outer VM continues normally.
7287 //
7288 // A nofork `${ … }` runs in the CURRENT shell, so only `return`
7289 // stops at it (c:Src/subst.c:2049-2053 `if (retflag) { retflag
7290 // = 0; breaks = obreaks; }`): an `exit` stays pending for the
7291 // caller's c:2094 zexit and a `break` keeps unwinding the loop
7292 // around the command.
7293 if shared_state {
7294 if RETFLAG.load(Relaxed) != 0 {
7295 RETFLAG.store(saved_retflag, Relaxed); // c:2051
7296 BREAKS.store(saved_breaks, Relaxed); // c:2052
7297 }
7298 } else {
7299 EXIT_PENDING.store(saved_exit_pending, Relaxed);
7300 EXIT_VAL.store(saved_exit_val, Relaxed);
7301 SHELL_EXITING.store(saved_shell_exiting, Relaxed);
7302 RETFLAG.store(saved_retflag, Relaxed);
7303 BREAKS.store(saved_breaks, Relaxed);
7304 }
7305 // Restore parent state. The inner cmd-subst's stdout
7306 // (the captured pipe contents) is the only thing
7307 // that leaks out.
7308 //
7309 // A funsub/valsub skips ALL of it: that is the entire
7310 // difference between `${ list; }` and `$(list)`.
7311 if !shared_state {
7312 // First: rolling a module back looks its parameters up
7313 // in the LIVE paramtab (see SubshForkCopy::restore).
7314 if let Some(snap) = tables_snap {
7315 snap.restore();
7316 }
7317 // Before fd 1 and 2 go back to the parent below.
7318 drop(fd_frame);
7319 if let Ok(mut t) = crate::ported::params::paramtab().write() {
7320 *t = paramtab_snap;
7321 }
7322 if let Ok(mut m) = crate::ported::params::paramtab_hashed_storage().lock() {
7323 *m = paramtab_hashed_snap;
7324 }
7325 self.set_pparams(pparams_snap);
7326 crate::ported::options::opt_state_restore(opts_snap);
7327 // Restore the parent's IFS (subshell isolation): the body's
7328 // `IFS=` must not leak out and word-split the parent's use
7329 // of the cmdsub result. Runtime word-splitting reads the
7330 // IFS *string* (this `ifs_lock` global), so restoring it is
7331 // sufficient. Deliberately do NOT call inittyptab() here —
7332 // that rewrites the process-global typtab the LEXER reads
7333 // on every character, and firing it per-cmdsub races
7334 // concurrent lexing in zshrs's worker threads, producing
7335 // spurious "parse error" flakes (HEAD ran clean 3/3; the
7336 // per-cmdsub inittyptab flaked ~50%). The typtab only
7337 // affects re-lexing — the parent is already compiled — and
7338 // leaving it at the body's value is strictly less divergent
7339 // than the prior behavior, which leaked the whole IFS.
7340 // Except when the body CHANGED IFS: its `ifssetfn` (or the
7341 // unset's c:Src/params.c:4748-4749) already rebuilt the typtab
7342 // that word splitting reads, so the parent's table has to come
7343 // back with its value (`IFS=:; print $(IFS=,; :); s="p,q";
7344 // print -rl -- ${=s}` is one word in zsh). Only that case
7345 // rebuilds, so the per-cmdsub race above does not return.
7346 let ifs_changed = crate::ported::params::ifs_lock()
7347 .lock()
7348 .map(|mut g| {
7349 let changed = *g != ifs_snap;
7350 *g = ifs_snap;
7351 changed
7352 })
7353 .unwrap_or(false);
7354 if ifs_changed {
7355 crate::ported::utils::inittyptab();
7356 }
7357 // The body's `LC_ALL=` / `LANG=` changed only the
7358 // forked child's locale in C.
7359 subsh_locale_restore(locale_snap.as_deref());
7360 if let Ok(mut t) = crate::ported::builtin::traps_table().lock() {
7361 *t = traps_snap;
7362 }
7363 // The trap flags, and the `sigaction`s the body installed
7364 // for its own traps, go back to the parent's.
7365 if let Some(parent) = &sigtrapped_snap {
7366 let child = match crate::ported::signals::sigtrapped.lock() {
7367 Ok(mut st) => std::mem::replace(&mut *st, parent.clone()),
7368 Err(_) => Vec::new(),
7369 };
7370 crate::fusevm_bridge::subshell_restore_signal_dispositions(parent, &child);
7371 }
7372 // Restore function tables (parallel to the trap/param
7373 // restore above). Bug #455.
7374 if let Ok(mut t) = crate::ported::hashtable::shfunctab_lock().write() {
7375 t.restore(shfunctab_snap);
7376 }
7377 self.functions_compiled = functions_compiled_snap;
7378 self.function_source = function_source_snap;
7379 // Discard anything the substitution added to the completion
7380 // arena — the in-process stand-in for the forked child's
7381 // address space going away (see comp_arena_save above).
7382 crate::comp_match_handles::comp_arena_restore(comp_arena_snap);
7383 // Undo the clearjobtab above — in C the cleared table
7384 // belongs to the forked child and dies with it, so the
7385 // parent's table must come back untouched. Signals stay
7386 // queued while the job mutexes are held (see the snapshot).
7387 crate::ported::signals_h::queue_signals();
7388 if let (Some(js), Some(t)) = (jobtab_snap, crate::ported::jobs::JOBTAB.get()) {
7389 if let Ok(mut g) = t.lock() {
7390 *g = js;
7391 }
7392 }
7393 if let (Some(mj), Some(m)) = (maxjob_snap, crate::ported::jobs::MAXJOB.get()) {
7394 if let Ok(mut g) = m.lock() {
7395 *g = mj;
7396 }
7397 }
7398 if let (Some(tj), Some(t)) = (thisjob_snap, crate::ported::jobs::THISJOB.get())
7399 {
7400 if let Ok(mut g) = t.lock() {
7401 *g = tj;
7402 }
7403 }
7404 if let (Some(cj), Some(t)) = (curjob_snap, crate::ported::jobs::CURJOB.get()) {
7405 if let Ok(mut g) = t.lock() {
7406 *g = cj;
7407 }
7408 }
7409 if let (Some(pj), Some(t)) = (prevjob_snap, crate::ported::jobs::PREVJOB.get())
7410 {
7411 if let Ok(mut g) = t.lock() {
7412 *g = pj;
7413 }
7414 }
7415 crate::exec_jobs::execpline_slots_forget_to(slots_snap);
7416 crate::ported::signals_h::unqueue_signals();
7417 // Now that the parent's traps are back, run the ones
7418 // whose signal arrived during the body.
7419 if sigtrapped_snap.is_some() {
7420 crate::fusevm_bridge::subshell_signal_leave();
7421 }
7422 } // if !shared_state
7423 }
7424 }
7425 // Restore LINENO so outer xtrace sees the outer line. LINENO
7426 // carries PM_READONLY (matching zsh's `integer-readonly-special`
7427 // GSU), so the restore must bypass the generic readonly guard
7428 // exactly like BUILTIN_SET_LINENO (fusevm_bridge.rs:5156) — write
7429 // the param's `u_val` directly and mirror the file-static /
7430 // lexer line counters. The previous `set_scalar` went through the
7431 // readonly-checked path: harmless on the `-c` route (LINENO not
7432 // yet flagged readonly there) but fatal on the faithful
7433 // loop()/zsh_main route, where every `$(...)` in piped/redirected
7434 // input died with `read-only variable: LINENO`.
7435 if let Some(ln) = saved_lineno {
7436 let n: crate::ported::zsh_h::zlong = ln.parse().unwrap_or(0);
7437 if let Ok(mut tab) = crate::ported::params::paramtab().write() {
7438 if let Some(pm) = tab.get_mut("LINENO") {
7439 // c:Src/utils.c:121 `zlong lineno` — the value lives in the C
7440 // GLOBAL, reached through LINENO's GSU. A `typeset -h +g LINENO`
7441 // local shadow has no PM_SPECIAL and no GSU, so C's `lineno = N`
7442 // never touches it; skip the paramtab mirror for the same reason.
7443 if (pm.node.flags & crate::ported::zsh_h::PM_SPECIAL as i32) != 0 {
7444 pm.u_val = n;
7445 pm.node.flags &= !(crate::ported::zsh_h::PM_UNSET as i32);
7446 }
7447 }
7448 }
7449 crate::ported::utils::set_lineno(n as i32);
7450 crate::ported::lex::set_lineno(n as u64);
7451 }
7452 cmdpop();
7453 // Propagate the inner cmd's status to the parent shell. zsh:
7454 // `a=$(false); echo $?` → 1 because cmd-subst status leaks to
7455 // $?. Set last_status on the executor so $? reads the right
7456 // value for callers that don't have a SetStatus(0) overwrite
7457 // (echo, test, etc.). Bare assignment paths still get the
7458 // SetStatus(0) from compile_simple — that's a separate gap.
7459 // Empty cmd-subst (`\`\``, `$()`) resets status to 0 per
7460 // Src/exec.c — the inner ran no command so the "last
7461 // command's exit" is the implicit success of "did nothing".
7462 // Without this branch, a prior command's non-zero status
7463 // leaked through the empty cmd-subst.
7464 let final_status = cmd_status.unwrap_or(0);
7465 self.set_last_status(final_status);
7466 // c:Src/exec.c:4775 — `getoutput` (the C cmd-subst path used by
7467 // both `$(…)` and `` `…` ``) propagates the inner exit through
7468 // `cmdoutval`, then the caller does `LASTVAL = cmdoutval`. Mirror
7469 // by writing the cmd-subst's exit into the ported `cmdoutval`
7470 // global so `getoutput()`'s post-call `LASTVAL = cmdoutval` (at
7471 // exec.rs:559-562) and the C-equivalent `cmdoutval = lastval`
7472 // bookkeeping in execcmd_exec's assignment paths both see the
7473 // real exit. Without this, backtick assignments (`a=\`false\`;
7474 // echo $?`) reported 0 because getoutput's caller path read a
7475 // cmdoutval that was never updated by the in-process hook.
7476 crate::ported::exec::cmdoutval.store(final_status, std::sync::atomic::Ordering::Relaxed);
7477
7478 // Flush any buffered Rust-side stdout so it reaches the pipe
7479 // before we restore.
7480 let _ = io::stdout().flush();
7481
7482 // Pop the trap-routing stack BEFORE restoring stdout so any
7483 // trap that fires during the restore goes to the cmdsub's
7484 // pipe (matching what zsh's forked cmdsub would do — the
7485 // child's fd 1 is the pipe right up until the child exits).
7486 crate::fusevm_bridge::CMDSUBST_OUTER_FDS.with(|s| {
7487 s.borrow_mut().pop();
7488 });
7489 // c:Bug #353 — restore fd 2 from the saved outer stderr. A
7490 // body that ran `exec 2>&1` (no command, just redirects)
7491 // would have committed fd 2 → the cmdsub's pipe write end.
7492 // In zsh's forked cmdsub the committed redirect dies with
7493 // the child; zshrs's in-process cmdsub would leak the dup
7494 // back to the parent and keep the pipe write-end alive,
7495 // blocking the parent's read on the read_end forever.
7496 // Always restoring fd 2 here rolls back any commit so the
7497 // pipe write-end count drops to zero when we drop the
7498 // local write_fd reference (which already happened above).
7499 if saved_stderr_for_trap >= 0 {
7500 unsafe {
7501 libc::dup2(saved_stderr_for_trap, libc::STDERR_FILENO);
7502 }
7503 crate::ported::utils::zclose(saved_stderr_for_trap);
7504 }
7505 // Restore stdout and read what was captured.
7506 if saved_stdout >= 0 {
7507 unsafe {
7508 libc::dup2(saved_stdout, libc::STDOUT_FILENO);
7509 }
7510 crate::ported::utils::zclose(saved_stdout);
7511 } else {
7512 unsafe { libc::close(libc::STDOUT_FILENO) }; // c:2048 zclose(y)
7513 }
7514 // Collect the concurrently-drained output. With fd 1 restored
7515 // above, the last shell-side write end is closed, so the reader
7516 // hits EOF and join() returns the full buffer regardless of
7517 // size — no pipe-full deadlock. The reader only read (never
7518 // closed) read_fd, so zclose still clears its FDT_INTERNAL mark
7519 // (c:Src/utils.c:2137).
7520 let bytes = reader_handle.join().unwrap_or_default();
7521 crate::ported::utils::zclose(read_fd);
7522 // This is the `$( cmd )` counterpart of `readoutput`'s c:4835-4849
7523 // conversion, and it has to be just as lossless: with
7524 // `String::from_utf8_lossy` a helper that emitted a latin-1 byte —
7525 // which is routine for the legacy completion corpus, where
7526 // `_call_program` shells out to tools whose descriptions predate
7527 // UTF-8 — had that byte replaced by U+FFFD before any completer saw
7528 // it. `decode_script_bytes` Meta-encodes only what is not valid
7529 // UTF-8, and `utils::unmetafy_str` restores the byte on output.
7530 let mut output = crate::script_bytes::decode_script_bytes(&bytes);
7531
7532 // POSIX: trailing newlines stripped from cmd-sub result.
7533 // c:Src/subst.c:1908 + c:2064-2069 — a nofork `${ … }` does its own
7534 // trim (`trim = !qt` under zsh emulation: ONE newline unquoted, NONE
7535 // quoted), so its caller gets the bytes untouched. Stripping them all
7536 // here left `"${ print INNER } $?"` as `INNER 7`, zsh `INNER\n 7`.
7537 while !shared_state && output.ends_with('\n') {
7538 output.pop();
7539 }
7540 // !!! RUST-ONLY: provenance tap. `$(…)` is a lineage ORIGIN —
7541 // these bytes did not exist in the shell before the inner list
7542 // ran. This is the in-process cmd-subst funnel (the host
7543 // `ShellHost::cmd_subst` path taps the same event for chunks
7544 // that reach the VM as sub-chunks instead of source text).
7545 if crate::provenance::active() {
7546 crate::provenance::on_cmd_subst(cmd_str, &output);
7547 }
7548 if parse_failed {
7549 // c:Src/exec.c:4778-4780 — `getoutput` returns NULL when
7550 // `parse_string` fails, and its caller raises the error:
7551 // c:Src/subst.c:400-402 `zerr("parse error in command
7552 // substitution"); return NULL;`, abandoning the command. Only a
7553 // body parsed at run time gets here (`` `…` ``); the lexer has
7554 // already parsed a `$(…)` body.
7555 crate::ported::utils::zerr("parse error in command substitution");
7556 }
7557 output
7558 }
7559}
7560
7561#[cfg(test)]
7562mod tests {
7563 use super::*;
7564
7565 #[test]
7566 fn test_simple_echo() {
7567 let _g = crate::test_util::global_state_lock();
7568 let mut exec = ShellExecutor::new();
7569 let status = exec.execute_script("true").unwrap();
7570 assert_eq!(status, 0);
7571 }
7572
7573 /// A `zsh/parameter` param is an autoload stub until it is READ; the read
7574 /// materializes it. `$parameters` enumerations type a stub as "undefined"
7575 /// (Src/Modules/parameter.c:49-50) and never resolve it, which is what
7576 /// puts those names in the right `_parameters -g` bucket.
7577 ///
7578 /// Reference behavior (`zsh -f`):
7579 /// `m=( ${(kv)parameters} ); print $m[aliases]` → undefined
7580 /// `${parameters[aliases]}` first, then the same scan → association-…
7581 #[test]
7582 fn module_params_are_autoload_stubs_until_read() {
7583 let _g = crate::test_util::global_state_lock();
7584 // `jobstates` is not touched by shell STARTUP, but
7585 // `MATERIALIZED_MODULE_PARAMS` is a process-global side-set and 10k
7586 // tests share one process — `compsys::_jobs` and friends read the job
7587 // parameters, so by the time this runs the stub may already have been
7588 // materialized. The lock serialises but restores nothing, so put the
7589 // name back to its untouched state here rather than assume nothing
7590 // else in the binary ever reads it. The assertions below are
7591 // unchanged: an untouched stub reads as a stub, and a read
7592 // materializes it.
7593 unmark_module_param_used("jobstates");
7594 assert!(
7595 module_param_is_autoload_stub("jobstates"),
7596 "untouched module param must read as a stub"
7597 );
7598 mark_module_param_used("jobstates");
7599 assert!(
7600 !module_param_is_autoload_stub("jobstates"),
7601 "a read must materialize it"
7602 );
7603 // A core special (not module-provided) is never a stub.
7604 assert!(!module_param_is_autoload_stub("path"));
7605 assert!(!module_param_is_autoload_stub("PATH"));
7606 }
7607
7608 /// Phase 3 diagnostic: a worker must be able to run a USER-DEFINED function
7609 /// (defined on the main executor) — the function source lives in the shared
7610 /// shfunctab, and the worker lazy-compiles it from there. Its `typeset -g`
7611 /// must reach the global param table. This is what `async_precmd` needs.
7612 #[test]
7613 fn phase3_worker_runs_user_defined_function() {
7614 let _g = crate::test_util::global_state_lock();
7615 let mut main = ShellExecutor::new();
7616 main.execute_script("phase3fn() { typeset -g PHASE3_FN_RESULT=fn_ran }")
7617 .unwrap();
7618 // sanity: it ran on main? (define only — not called yet)
7619 assert_eq!(getsparam("PHASE3_FN_RESULT"), None);
7620
7621 let pool = std::sync::Arc::new(crate::worker::WorkerPool::new(2));
7622 let pool2 = std::sync::Arc::clone(&pool);
7623 let (tx, rx) = std::sync::mpsc::channel::<()>();
7624 pool.submit(move || {
7625 let mut wex = ShellExecutor::new_worker(pool2);
7626 let _ = wex.execute_script_zsh_pipeline("phase3fn");
7627 let _ = tx.send(());
7628 });
7629 rx.recv().expect("worker completed");
7630 assert_eq!(
7631 getsparam("PHASE3_FN_RESULT"),
7632 Some("fn_ran".to_string()),
7633 "worker could not run the user-defined function from shared shfunctab"
7634 );
7635 }
7636
7637 /// Phase 1 of the in-process thread-execution model: prove a shell body
7638 /// runs on a POOL WORKER THREAD via `new_worker` and that its `typeset -g`
7639 /// lands in the GLOBAL (RwLock-synchronized) param table. Each worker writes
7640 /// a DISTINCT key, so a green run shows: (a) `ExecutorContext::enter` +
7641 /// `execute_script_zsh_pipeline` work off the main thread, and (b) N
7642 /// concurrent writers don't corrupt the shared table. This is the linchpin
7643 /// for converting the subprocess-forking parallel builtins to threads.
7644 #[test]
7645 fn phase1_worker_shell_writes_reach_global_paramtab() {
7646 let _g = crate::test_util::global_state_lock();
7647 // Seed the globals (options, default params) exactly as a live session
7648 // would — workers SHARE these; new_worker() never re-seeds them.
7649 let _main = ShellExecutor::new();
7650
7651 let pool = std::sync::Arc::new(crate::worker::WorkerPool::new(4));
7652 const N: usize = 16;
7653 let (tx, rx) = std::sync::mpsc::channel::<usize>();
7654 for i in 0..N {
7655 let tx = tx.clone();
7656 let pool_for_worker = std::sync::Arc::clone(&pool);
7657 pool.submit(move || {
7658 // Lightweight per-worker executor; shares the global tables.
7659 let mut wex = ShellExecutor::new_worker(pool_for_worker);
7660 let _ =
7661 wex.execute_script_zsh_pipeline(&format!("typeset -g PHASE1_WK_{i}=val_{i}"));
7662 let _ = tx.send(i);
7663 });
7664 }
7665 drop(tx);
7666 // Barrier: wait for all N workers.
7667 let mut done = 0usize;
7668 while rx.recv().is_ok() {
7669 done += 1;
7670 }
7671 assert_eq!(done, N, "all {N} workers completed");
7672
7673 // Every worker's write must be visible in the global param table.
7674 for i in 0..N {
7675 assert_eq!(
7676 getsparam(&format!("PHASE1_WK_{i}")),
7677 Some(format!("val_{i}")),
7678 "worker {i} typeset -g did not reach the global paramtab"
7679 );
7680 }
7681 }
7682
7683 #[test]
7684 fn test_if_true() {
7685 let _g = crate::test_util::global_state_lock();
7686 let mut exec = ShellExecutor::new();
7687 let status = exec.execute_script("if true; then true; fi").unwrap();
7688 assert_eq!(status, 0);
7689 }
7690
7691 #[test]
7692 fn test_if_false() {
7693 let _g = crate::test_util::global_state_lock();
7694 let mut exec = ShellExecutor::new();
7695 let status = exec
7696 .execute_script("if false; then true; else false; fi")
7697 .unwrap();
7698 assert_eq!(status, 1);
7699 }
7700
7701 #[test]
7702 fn test_for_loop() {
7703 let _g = crate::test_util::global_state_lock();
7704 let mut exec = ShellExecutor::new();
7705 exec.execute_script("for i in a b c; do true; done")
7706 .unwrap();
7707 assert_eq!(exec.last_status(), 0);
7708 }
7709
7710 #[test]
7711 fn test_and_list() {
7712 let _g = crate::test_util::global_state_lock();
7713 let mut exec = ShellExecutor::new();
7714 let status = exec.execute_script("true && true").unwrap();
7715 assert_eq!(status, 0);
7716
7717 let status = exec.execute_script("true && false").unwrap();
7718 assert_eq!(status, 1);
7719 }
7720
7721 #[test]
7722 fn test_or_list() {
7723 let _g = crate::test_util::global_state_lock();
7724 let mut exec = ShellExecutor::new();
7725 let status = exec.execute_script("false || true").unwrap();
7726 assert_eq!(status, 0);
7727 }
7728
7729 /// Pin: `forklevel` matches the C global declared at
7730 /// `Src/exec.c:1052` (`int forklevel;`). Like `int` in C, the
7731 /// Rust port is an AtomicI32 starting at 0 (no fork has occurred
7732 /// at process start). Per `Src/exec.c:1221` (`forklevel =
7733 /// locallevel;`), every subshell entry copies `locallevel` into
7734 /// the global; the SIGPIPE handler at `Src/signals.c:808` reads
7735 /// it back to distinguish the top-level shell from a subshell.
7736 #[test]
7737 fn test_forklevel_default_zero_and_roundtrip() {
7738 let _g = crate::test_util::global_state_lock();
7739 use std::sync::atomic::Ordering;
7740 let prev = crate::ported::exec::FORKLEVEL.load(Ordering::Relaxed);
7741 // Default state at process start: zero (matches C's BSS init
7742 // of `int forklevel;` to 0).
7743 crate::ported::exec::FORKLEVEL.store(0, Ordering::Relaxed);
7744 assert_eq!(crate::ported::exec::FORKLEVEL.load(Ordering::Relaxed), 0);
7745 // Simulate the c:1221 store: `forklevel = locallevel;`.
7746 crate::ported::exec::FORKLEVEL.store(3, Ordering::Relaxed);
7747 assert_eq!(crate::ported::exec::FORKLEVEL.load(Ordering::Relaxed), 3);
7748 crate::ported::exec::FORKLEVEL.store(prev, Ordering::Relaxed);
7749 }
7750
7751 /// `zexecve_recover` is the PARENT-side half of C's `#!`-recovery block
7752 /// (c:Src/exec.c:534-627). Every `execve` in that block is preceded by
7753 /// `winch_unblock()` (c:565/570/580/584/626) because C is inside the
7754 /// forked child and is about to be replaced. This port returns to the
7755 /// caller instead, so those unblocks left the shell's standing
7756 /// `winch_block()` (c:Src/init.c:1458) dropped with nothing to re-arm
7757 /// it — and a SIGWINCH delivered inside a widget makes `calclist`
7758 /// (c:Src/Zle/compresult.c:1495) count display strings against a width
7759 /// they were not built at.
7760 ///
7761 /// The mask is per-thread, so blocking here cannot leak into other
7762 /// tests.
7763 #[test]
7764 #[cfg(unix)]
7765 fn zexecve_recover_keeps_sigwinch_blocked_in_the_parent() {
7766 fn sigwinch_blocked() -> bool {
7767 unsafe {
7768 let mut cur: libc::sigset_t = std::mem::zeroed();
7769 libc::pthread_sigmask(libc::SIG_BLOCK, std::ptr::null(), &mut cur);
7770 libc::sigismember(&cur, libc::SIGWINCH) == 1
7771 }
7772 }
7773
7774 let dir = std::env::temp_dir().join(format!(
7775 "zshrs_winch_recover_{}_{:?}",
7776 std::process::id(),
7777 std::thread::current().id()
7778 ));
7779 std::fs::create_dir_all(&dir).unwrap();
7780
7781 // c:611-627 — shebang-less text file: the `/bin/sh` fallback.
7782 let noshebang = dir.join("noshebang");
7783 std::fs::write(&noshebang, "echo hi\n").unwrap();
7784 // c:576-585 — `#!` line naming an absolute interpreter.
7785 let shebang = dir.join("shebang");
7786 std::fs::write(&shebang, "#!/bin/cat -v\necho hi\n").unwrap();
7787
7788 let saved = sigwinch_blocked();
7789 crate::ported::signals_h::winch_block(); // c:Src/init.c:1458
7790 assert!(sigwinch_blocked(), "precondition: winch_block() holds");
7791
7792 let argv = vec!["script".to_string()];
7793 let sh = zexecve_recover(noshebang.to_str().unwrap(), &argv, libc::ENOEXEC);
7794 assert_eq!(
7795 sh.as_ref().map(|(p, _)| p.as_str()),
7796 Ok("/bin/sh"),
7797 "c:625-627 — a shebang-less script re-execs through /bin/sh"
7798 );
7799 assert!(
7800 sigwinch_blocked(),
7801 "c:626 — the /bin/sh recovery must not unblock SIGWINCH in the parent"
7802 );
7803
7804 let interp = zexecve_recover(shebang.to_str().unwrap(), &argv, libc::ENOEXEC);
7805 assert_eq!(
7806 interp.as_ref().map(|(p, _)| p.as_str()),
7807 Ok("/bin/cat"),
7808 "c:576-585 — the `#!` line names the interpreter"
7809 );
7810 assert!(
7811 sigwinch_blocked(),
7812 "c:580/c:584 — the `#!` recovery must not unblock SIGWINCH in the parent"
7813 );
7814
7815 if !saved {
7816 crate::ported::signals_h::winch_unblock();
7817 }
7818 let _ = std::fs::remove_dir_all(&dir);
7819 }
7820
7821 /// c:Src/exec.c:544 `*argv = pth;` — the shebang-less `/bin/sh`
7822 /// fallback (c:611-627) hands sh the PATH being executed and applies the
7823 /// c:616 `-`/`+` guard to it, not to the command word the user typed.
7824 /// `PATH=-dir tstcmd` (A05execution.ztst, workers/52515) resolves to
7825 /// `-dir/tstcmd`, which sh must see as an operand.
7826 #[test]
7827 #[cfg(unix)]
7828 fn zexecve_recover_sh_fallback_passes_the_path_not_the_word() {
7829 let dir = std::env::temp_dir().join(format!(
7830 "zshrs_recover_argv_{}_{:?}",
7831 std::process::id(),
7832 std::thread::current().id()
7833 ));
7834 std::fs::create_dir_all(&dir).unwrap();
7835 let script = dir.join("tstcmd");
7836 std::fs::write(&script, "echo no shebang\n").unwrap();
7837 let pth = script.to_str().unwrap().to_string();
7838 // A word spelled like an option must neither be handed to sh nor
7839 // trip the guard: only the executed path counts.
7840 let argv = vec!["-tstcmd".to_string(), "arg".to_string()];
7841 let got = zexecve_recover(&pth, &argv, libc::ENOEXEC);
7842 let _ = std::fs::remove_dir_all(&dir);
7843 let want: Vec<String> = vec!["sh".to_string(), pth.clone(), "arg".to_string()];
7844 assert_eq!(got, Ok(("/bin/sh".to_string(), want)));
7845 }
7846}
7847
7848// Plugin-Framework-Agnostic State-Modification Recorder hook helpers.
7849/// Recorder helper: emit one record for an array/scalar mutation
7850/// targeting a path-family parameter (path/fpath/manpath/module_path/
7851/// cdpath, lower- or upper-cased), or one `assign` record for any
7852/// other name. Centralises the path-family list so `BUILTIN_SET_ARRAY`,
7853/// `BUILTIN_APPEND_ARRAY`, and `BUILTIN_APPEND_SCALAR_OR_PUSH` share
7854/// the same routing.
7855///
7856/// `is_append` distinguishes `arr=(...)` from `arr+=(...)` so the
7857/// emitted event carries the APPEND attr bit and replay can choose
7858/// between fresh-set and extend semantics.
7859///
7860/// `attrs` carries any pre-existing type info from
7861/// `recorder_attrs_for(name)` (readonly/export/global) — array shape
7862/// and APPEND get OR'd in by emit_array_assign.
7863#[cfg(feature = "recorder")]
7864pub(crate) fn emit_path_or_assign(
7865 name: &str,
7866 values: &[String],
7867 attrs: crate::recorder::ParamAttrs,
7868 is_append: bool,
7869 ctx: &crate::recorder::RecordCtx,
7870) {
7871 let lower = name.to_ascii_lowercase();
7872 let kind_name: Option<&'static str> = match lower.as_str() {
7873 "path" => Some("path"),
7874 "fpath" => Some("fpath"),
7875 "manpath" => Some("manpath"),
7876 "module_path" => Some("module_path"),
7877 "cdpath" => Some("cdpath"),
7878 _ => None,
7879 };
7880 match kind_name {
7881 Some(k) => {
7882 for v in values {
7883 crate::recorder::emit_path_mod(v, k, ctx.clone());
7884 // Each fpath addition also surfaces every `_completion`
7885 // file inside the directory — matches zinit-report's
7886 // per-plugin "Completions:" listing. Only fpath dirs
7887 // get this treatment; PATH dirs hold executables, not
7888 // completion functions.
7889 if k == "fpath" {
7890 crate::recorder::discover_completions_in_fpath_dir(v, ctx);
7891 }
7892 }
7893 }
7894 None => {
7895 // Non-path arrays: emit ONE `assign` event with the
7896 // ordered element list preserved in value_array. Replay
7897 // reconstructs `name=(elem1 elem2 ...)` exactly without
7898 // having to re-split a joined string.
7899 crate::recorder::emit_array_assign(
7900 name,
7901 values.to_vec(),
7902 attrs,
7903 is_append,
7904 ctx.clone(),
7905 );
7906 }
7907 }
7908}
7909
7910use std::os::unix::fs::MetadataExt;
7911
7912bitflags::bitflags! {
7913 /// Flags for zfork()
7914 #[derive(Debug, Clone, Copy, Default)]
7915 pub struct ForkFlags: u32 {
7916 const NOJOB = 1 << 0; // Don't add to job table
7917 const NEWGRP = 1 << 1; // Create new process group
7918 const FGTTY = 1 << 2; // Take foreground terminal
7919 const KEEPSIGS = 1 << 3; // Keep signal handlers
7920 }
7921}
7922
7923bitflags::bitflags! {
7924 /// Flags for entersubsh()
7925 #[derive(Debug, Clone, Copy, Default)]
7926 pub struct SubshellFlags: u32 {
7927 const NOMONITOR = 1 << 0; // Disable job control
7928 const KEEPFDS = 1 << 1; // Keep file descriptors
7929 const KEEPTRAPS = 1 << 2; // Keep trap handlers
7930 }
7931}
7932
7933/// Result of fork operation
7934#[derive(Debug)]
7935/// `fork()` outcome (parent / child / error).
7936/// Mirrors the integer return of `zfork()` from Src/exec.c:349.
7937pub enum ForkResult {
7938 /// `Parent` variant.
7939 Parent(i32), // Contains child PID
7940 /// `Child` variant.
7941 Child,
7942}
7943
7944/// Redirection mode
7945#[derive(Debug, Clone, Copy)]
7946/// File-redirection mode (`>` / `>>` / `<` / etc.).
7947/// Mirrors the `REDIR_*` enum from Src/zsh.h.
7948pub enum RedirMode {
7949 /// `Dup` variant.
7950 Dup,
7951 /// `Close` variant.
7952 Close,
7953}
7954
7955/// Builtin command type
7956#[derive(Debug, Clone, Copy)]
7957/// Builtin classification.
7958/// Mirrors the `BINF_*` flag set Src/builtin.c uses to
7959/// classify special vs regular builtins.
7960pub enum BuiltinType {
7961 /// `Normal` variant.
7962 Normal,
7963 /// `Disabled` variant.
7964 Disabled,
7965}
7966
7967use crate::fusevm_bridge::with_executor;
7968use crate::ported::glob::*;
7969use crate::ported::hist::*;
7970use crate::ported::jobs::*;
7971use crate::ported::math::*;
7972use crate::ported::module::*;
7973use crate::ported::modules::cap::*;
7974use crate::ported::modules::terminfo::*;
7975use crate::ported::options::*;
7976use crate::ported::params::*;
7977use crate::ported::pattern::*;
7978use crate::ported::prompt::*;
7979use crate::ported::signals::*;
7980use crate::ported::subst::*;
7981use crate::ported::utils::{zerr, zerrnam, zwarn, zwarnnam};
7982use ::regex::{Error as RegexError, Regex, RegexBuilder};
7983
7984pub use crate::ported::modules::regex::posix_ere_bracket_escape;
7985
7986impl ShellExecutor {
7987 /// Every option name in `ZSH_OPTIONS_SET` (port of `optns[]` at
7988 /// `Src/options.c:79+`).
7989 pub(crate) fn all_zsh_options() -> Vec<&'static str> {
7990 ZSH_OPTIONS_SET.iter().copied().collect()
7991 }
7992
7993 /// `name → default-on` map via canonical `default_on_options`
7994 /// (port of `defset()` macro at `Src/options.c:73`).
7995 pub(crate) fn default_options() -> HashMap<String, bool> {
7996 let on = default_on_options();
7997 Self::all_zsh_options()
7998 .into_iter()
7999 .map(|n| (n.to_string(), on.contains(n)))
8000 .collect()
8001 }
8002}
8003impl ShellExecutor {
8004 /// PURE PASSTHRU to the canonical `params::getsparam` (C port of
8005 /// `Src/params.c::getsparam`). Every special-name case the old
8006 /// 316-line body handled lives in `params::lookup_special_var` +
8007 /// `getsparam`'s paramtab/env walk. Returns an empty string for
8008 /// unset names (matching the old fn's signature; callers that
8009 /// need the set/unset distinction call `scalar` / `has_scalar`
8010 /// directly).
8011 pub(crate) fn get_variable(&self, name: &str) -> String {
8012 getsparam(name).unwrap_or_default()
8013 }
8014}
8015
8016// Source-form registration step used by the autoload-load path
8017// (`dispatch_function_call` / `run_function_body_only`). Decides
8018// whether to feed the file body to the funcdef pipeline VERBATIM
8019// (zsh-style: the body's own `function NAME() {...}` definition
8020// registers the function on execution) or to WRAP it in
8021// `NAME() {...}` (ksh-style or multi-statement: the body is just
8022// commands or includes additional statements past the def).
8023//
8024// The classification mirrors c:Src/exec.c:5725 + 5750 — KSHAUTOLOAD-
8025// equivalent vs zsh-style autoload. The structural check is the
8026// canonical `stripkshdef` (Src/exec.c:6291, ported at exec.rs:10548):
8027// parse the body to Eprog, run stripkshdef, and check whether it
8028// returned a stripped (different-length wordcode) Eprog. When it
8029// did, the file is the single-funcdef shape `[function] NAME [()] {
8030// INNER }`; running the file source directly through the funcdef
8031// pipeline registers NAME via the WC_FUNCDEF opcode at
8032// fusevm_bridge.rs:6330, matching C's `shf->funcdef = stripkshdef(
8033// prog, name)` semantics (the inner body becomes the function's
8034// body). When it didn't strip — single statement that isn't a
8035// funcdef, or multiple list nodes (e.g. `function ztm() {...}` +
8036// trailing `ztm "$@"` self-call) — we fall back to wrap-and-run so
8037// the canonical funcdef opcode still fires and any extra
8038// statements run inside the registered body, matching C's
8039// behavior of using the whole prog as funcdef in that case.
8040/// Restore `noaliases` on scope exit.
8041///
8042/// C's `loadautofn` (Src/exec.c:5684-5704) saves `noaliases`, sets it from the
8043/// function's PM_UNALIASED bit for the duration of the body parse, and restores
8044/// it unconditionally. The zshrs autoload block has early `return` paths, so the
8045/// restore has to ride on Drop rather than a trailing statement — otherwise a
8046/// `-U` autoload that failed to load would leave alias expansion disabled for
8047/// the rest of the shell.
8048struct NoAliasesRestore(bool);
8049
8050impl Drop for NoAliasesRestore {
8051 fn drop(&mut self) {
8052 crate::ported::lex::set_noaliases(self.0); // c:5704
8053 }
8054}
8055
8056/// c:Src/exec.c:5735 `loadautofnsetfile(shf, fdir)` + c:5751 — put the load
8057/// directory (and the absolute-path marker) back on a function whose body
8058/// zshrs just re-registered through the funcdef pipeline.
8059///
8060/// C loads an autoloaded body IN PLACE on the existing `Shfunc`, so
8061/// `filename`, PM_LOADDIR and PM_ABSPATH_USED all survive the load:
8062/// `shf->node.flags &= ~PM_UNDEFINED` (c:5751) is the only flag C clears.
8063/// zshrs re-registers the body as SOURCE through the WC_FUNCDEF pipeline,
8064/// which builds a FRESH node whose `filename` is the enclosing script and
8065/// whose flag word starts at zero. Both have to be reinstated, or `whence -v`
8066/// names the calling script instead of the definition file, and the
8067/// PM_LOADDIR|PM_ABSPATH_USED pair that `add_autoload_function`
8068/// (Src/builtin.c:3310-3323) tests — to hand a sibling `autoload -Uz NAME`
8069/// the caller's directory — is gone.
8070///
8071/// One helper rather than four inline copies: all four
8072/// `autoload_register_source` call sites need the identical restore.
8073///
8074/// `ksh_style` must be sampled BEFORE the re-registration (the fresh node's
8075/// flag word no longer carries PM_KSHSTORED / PM_ZSHSTORED, so re-deriving it
8076/// here would read the wrong answer): c:Src/exec.c:5792-5806 is the one arm
8077/// where C does NOT reload the body in place. It runs the whole FILE at top
8078/// level (`execode(prog, 1, 0, "evalautofunc")`, c:5795) and then REFETCHES
8079/// the node (`shf = shfunctab->getnode(shfunctab, n)`, c:5797) because the
8080/// file's own `NAME() { … }` created a brand-new Shfunc. There is no
8081/// `loadautofnsetfile` call on that arm, so zsh itself loses `filename`,
8082/// PM_LOADDIR and PM_ABSPATH_USED there. Verified against the reference shell:
8083///
8084/// ```text
8085/// $ zsh -f -c 'autoload -k /D/kw; kw'
8086/// ksh-kw ran
8087/// kw: ksib: function definition file not found
8088/// $ zsh -f -c 'autoload -k /D/kw; kw >/dev/null; whence -v kw'
8089/// kw is a shell function from zsh
8090/// ```
8091///
8092/// Restoring on that arm would make a ksh-autoloaded function inherit its
8093/// directory to siblings where zsh does not.
8094fn restore_loaddir(name: &str, dir: &str, abspath_used: bool, ksh_style: bool) {
8095 if ksh_style {
8096 return; // c:5792-5806 — no loadautofnsetfile on the ksh arm
8097 }
8098 if let Ok(mut tab) = crate::ported::hashtable::shfunctab_lock().write() {
8099 if let Some(shf) = tab.get_mut(name) {
8100 crate::ported::exec::loadautofnsetfile(shf, Some(dir)); // c:5735
8101 if abspath_used {
8102 shf.node.flags |= crate::ported::zsh_h::PM_ABSPATH_USED as i32; // c:5751
8103 }
8104 }
8105 }
8106}
8107
8108/// !!! WARNING: RUST-ONLY HELPER — NO C COUNTERPART !!!
8109///
8110/// C never has to ask this question. `Src/Modules/parameter.c:295-315`
8111/// (`setfunction`, the `functions[NAME]=BODY` setter) parses the assigned text
8112/// with `parse_string(val, 1)` and stores the result AS THE BODY —
8113/// `shf->funcdef = dupeprog(prog, 0)` (c:313) — so the function is fully
8114/// defined the moment the assignment runs. `loadautofn`
8115/// (`Src/exec.c:5723-5806`), which reads a FILE and therefore has to decide
8116/// between "the file IS the body" and "the file DEFINES the function"
8117/// (c:5781 `ksh == 2 || (ksh == 1 && isset(KSHAUTOLOAD))`), is a different
8118/// entry point that a parameter assignment never reaches.
8119///
8120/// zshrs stores the assigned text on `shfunc.body` with no compiled chunk, so
8121/// the first CALL lands in the same autoload prelude a real `autoload` stub
8122/// uses — and that prelude was applying `loadautofn`'s file rules to it. The
8123/// two cases are told apart by the flag `loadautofn` stamps and a parameter
8124/// assignment does not: `loadautofnsetfile` sets PM_LOADDIR (c:5657) on the
8125/// node it loaded, while `setfunction` leaves the flag word at `dis` (c:314).
8126/// The `loaded_dir` capture at both call sites already reads the same bit for
8127/// the same reason.
8128fn body_came_from_param_assignment(flags: i32) -> bool {
8129 (flags as u32 & crate::ported::zsh_h::PM_LOADDIR) == 0
8130}
8131
8132/// !!! WARNING: RUST-ONLY HELPER — NO C COUNTERPART !!!
8133///
8134/// The text to run to install a `functions[NAME]=BODY` assignment: ALWAYS the
8135/// `NAME() { … }` wrap, never the verbatim run that
8136/// [`autoload_definition_source`] falls back to for a file whose contents are
8137/// already a definition of `NAME`. c:Src/Modules/parameter.c:313 makes the
8138/// parsed text the funcdef unconditionally, so text that happens to READ as
8139/// `NAME () { … }` is a BODY whose execution defines `NAME` — measured
8140/// against the reference shell:
8141///
8142/// ```text
8143/// $ zsh -f -c 'functions[g]="g () { print inner }"; g; print "[${functions[g]}]"'
8144/// [ print inner]
8145/// ```
8146///
8147/// Nothing is printed: the call ran the definition. Running that text verbatim
8148/// at install time instead printed `inner` and defined `g` a call too early.
8149fn param_definition_source(name: &str, body: &str) -> String {
8150 format!("{name}() {{\n{body}\n}}")
8151}
8152
8153/// c:Src/exec.c:5781 — `if (ksh == 2 || (ksh == 1 && isset(KSHAUTOLOAD)))`,
8154/// the ksh-style load branch. `ksh` derives from the stub's stored-style bits
8155/// per c:5762-5766 (`PM_KSHSTORED ? 2 : PM_ZSHSTORED ? 0 : 1`; a decisive
8156/// `.zwc` header flag was already folded into these bits by `loadautofn`).
8157///
8158/// Two zshrs steps need the same answer — `autoload_register_source` (wrap vs
8159/// verbatim) and `restore_loaddir` (whether the load kept the original node)
8160/// — so the decision lives in one place.
8161fn autoload_is_ksh_style(name: &str) -> bool {
8162 let flags = crate::ported::utils::getshfunc(name)
8163 .map(|f| f.node.flags as u32)
8164 .unwrap_or(0);
8165 let ksh = if flags & crate::ported::zsh_h::PM_KSHSTORED != 0 {
8166 2 // c:5765
8167 } else if flags & crate::ported::zsh_h::PM_ZSHSTORED != 0 {
8168 0 // c:5766
8169 } else {
8170 1 // c:5766
8171 };
8172 ksh == 2 || (ksh == 1 && crate::ported::zsh_h::isset(crate::ported::zsh_h::KSHAUTOLOAD))
8173 // c:5781
8174}
8175
8176/// The cache key for an autoloaded function: `(resolved fpath dir,
8177/// SHA-256 of the definition text)`, or `None` when the directory
8178/// cannot be pinned down.
8179///
8180/// `loadautofn` records the resolved fpath directory on the shfunc
8181/// (`filename` + `PM_LOADDIR`, c:Src/exec.c:5657); a function whose
8182/// `filename` is still the placeholder `"zsh"` was not resolved through
8183/// `$fpath` and is not cached.
8184///
8185/// The hash is over `registered` — the exact string about to be
8186/// compiled — and NOT over a `stat` of `<dir>/<name>`. Those are not the
8187/// same thing: `getfpfunc` prefers a `<dir>.zwc` digest over the plain
8188/// file whenever the digest is newer (c:Src/parse.c:3771-3777), so the
8189/// body being installed may have no relationship to the bytes of the
8190/// file that path names. Stamping the path let a chunk built from one
8191/// text be served for another.
8192///
8193/// `from_wordcode` salts the digest because it changes what the same bytes
8194/// COMPILE TO: a wordcode-derived body is compiled under [`ZwcRelexGuard`],
8195/// so it resolves quotes and aliases the way `zcompile` did, while a
8196/// plain-file body of those same bytes resolves them against the live
8197/// RCQUOTES / alias state. One cache line must never be served for both.
8198fn autoload_source_key(
8199 name: &str,
8200 registered: &str,
8201 from_wordcode: bool,
8202) -> Option<(String, [u8; 32])> {
8203 let dir = crate::ported::utils::getshfunc(name)
8204 .and_then(|f| f.filename)
8205 .filter(|d| d != "zsh")?;
8206 let sha = if from_wordcode {
8207 crate::autoload_cache::source_digest(&format!("\0zwc\0{registered}"))
8208 } else {
8209 crate::autoload_cache::source_digest(registered)
8210 };
8211 Some((dir, sha))
8212}
8213
8214/// !!! WARNING: RUST-ONLY HELPER — NO C COUNTERPART !!!
8215///
8216/// Raises `noerrs` (c:Src/utils.c:175 — the gate every `zerr`/`zwarn`
8217/// consults) for the life of the guard, so a pass that only exists because
8218/// zshrs parses text where C carries a parsed `Eprog` cannot report an error
8219/// C would report exactly once. `ERRFLAG_ERROR` is still set while muted, so
8220/// callers that read errflag still see the failure.
8221struct ZerrMute(i32);
8222
8223impl ZerrMute {
8224 fn enter() -> Self {
8225 let mut g = crate::ported::utils::noerrs_lock().lock().unwrap();
8226 let prev = *g;
8227 *g = 1;
8228 Self(prev)
8229 }
8230}
8231
8232impl Drop for ZerrMute {
8233 fn drop(&mut self) {
8234 if let Ok(mut g) = crate::ported::utils::noerrs_lock().lock() {
8235 *g = self.0;
8236 }
8237 }
8238}
8239
8240/// What an autoload of one name will hand the compiler.
8241struct AutoloadSource {
8242 /// The definition text: the file body verbatim, or the `name() { … }` wrap.
8243 text: String,
8244 /// The body is a `.zwc` deparse, so the compile needs [`ZwcRelexGuard`].
8245 from_wordcode: bool,
8246 /// c:Src/exec.c:6264 — `parse_string` rejected the file and has ALREADY
8247 /// reported the error against the loadee's name. C returns NULL from
8248 /// `getfpfunc`, so `loadautofn` abandons the load right there (c:5726) and
8249 /// prints nothing more. zshrs still runs `text` through the compiler
8250 /// (that is where the body becomes a chunk), so the caller silences THAT
8251 /// pass instead — otherwise the same parse error lands twice, the second
8252 /// time one line off because of the wrap's leading `name() {` line.
8253 parse_failed: bool,
8254}
8255
8256/// Returns the text to run to install `name`, plus whether that text came out
8257/// of a `.zwc` (see [`autoload_note_wordcode_body`]) and therefore has to be
8258/// lexed under [`ZwcRelexGuard`] wherever it is lexed, and whether the file's
8259/// one parse rejected it.
8260fn autoload_register_source(name: &str, body: &str) -> AutoloadSource {
8261 let ksh_style = autoload_is_ksh_style(name);
8262 // `loadautofn` took this body from autoloads.rkyv: the registration it
8263 // was stored with is the one the parse below would produce.
8264 if let Some((text, from_wordcode, parse_failed)) =
8265 crate::autoload_cache::take_hit(name, body, ksh_style)
8266 {
8267 return AutoloadSource {
8268 text,
8269 from_wordcode,
8270 parse_failed,
8271 };
8272 }
8273 // c:Src/exec.c:5725 `stripkshdef(prog, …)` — the ksh-vs-zsh wrap decision
8274 // below PARSES `body`, so it is itself a second lex of the deparse and
8275 // needs the same pin as the compile that follows it.
8276 let from_wordcode = autoload_body_from_wordcode(name, body);
8277 let _relex = from_wordcode.then(ZwcRelexGuard::enter);
8278 let (text, parse_failed) = autoload_definition_source(name, body, ksh_style);
8279 crate::autoload_cache::commit_search(name, body, &text, parse_failed, ksh_style);
8280 AutoloadSource {
8281 text,
8282 from_wordcode,
8283 parse_failed,
8284 }
8285}
8286
8287/// !!! WARNING: RUST-ONLY HELPER — NO C COUNTERPART !!!
8288///
8289/// Pins the lexer to the spelling a `.zwc` deparse was written in, for the
8290/// duration of one compile.
8291///
8292/// C never needs this: the compiled arm of `source()` is `execode(prog, 1,
8293/// 0, "filecode")` (c:Src/init.c:1621) and the ksh-autoload arm is
8294/// `execode(prog, 1, 0, "evalautofunc")` (c:Src/exec.c:5795) — the wordcode
8295/// runs as it stands and NOTHING is lexed. A `.zwc` is resolved once, at
8296/// `zcompile` time. zshrs has no execute-the-wordcode path: it deparses back
8297/// to source with `getpermtext` and lexes that, so every piece of LEXER-TIME
8298/// state that C bypassed has to be neutralised by hand, or the second lex
8299/// resolves the text differently from the first.
8300///
8301/// Two such pieces are known to change the result:
8302///
8303/// * **RCQUOTES.** `untokenize` (c:Src/exec.c:2134) renders every quote
8304/// null through `ztokens[Snull - Pound]`, and that entry is a bare
8305/// single quote (c:Src/lex.c:38), so a closing null followed by an
8306/// opening one deparses to two adjacent quotes. Under RCQUOTES the lexer
8307/// reads that pair inside a quoted word as one LITERAL quote
8308/// (c:Src/lex.c:1328) rather than as two delimiters. `zsh-expand`'s
8309/// plugin entry does `setopt rcquotes` at its line 39, so every later
8310/// `.zwc`-sourced alias with adjacent quoted segments — the whole
8311/// `zsh-openshift-aliases` set — gained literal quotes zsh never had.
8312///
8313/// * **Aliases.** `checkalias` (c:Src/lex.c:1909) fires from the lexer, so
8314/// an alias installed before the `source` rewrote words INSIDE the
8315/// compiled program: with `alias mycmd=…` live, a `.zwc` whose second
8316/// line is `mycmd` ran the alias where zsh runs the function. Global
8317/// aliases are worse — they rewrite any word, so `print -r -- GA: x`
8318/// became `print -r -- GA: LEAKED` under `alias -g x=LEAKED`. This is
8319/// C's `noaliases` (c:Src/lex.c:135), the same switch `par_case` uses to
8320/// keep `in` from being alias-expanded.
8321///
8322/// Both are restored on drop, so the restore survives a panic out of the
8323/// compiler — and, more importantly, the program's own RUNTIME lexing is
8324/// unaffected: a `setopt rcquotes` the `.zwc` performs still takes effect
8325/// and still outlives the source, and a function or `eval` body it runs is
8326/// lexed later, against the live alias table.
8327///
8328/// One residual case is out of reach here and needs a real
8329/// execute-the-wordcode path: a `.zwc` COMPILED while RCQUOTES was set holds
8330/// an unescaped literal quote in its tokenized word (c:Src/lex.c:1329 adds
8331/// the character with no `Bnull` prefix), and `untokenize` cannot tell that
8332/// apart from a quote null. No option state at re-lex time recovers it.
8333///
8334/// `noaliases` is a thread-local (`LEX_NOALIASES`), but the option store is
8335/// process-wide, so the RCQUOTES window is visible to a worker thread that
8336/// lexes concurrently. The window is one synchronous compile.
8337pub(crate) struct ZwcRelexGuard {
8338 rcquotes: bool,
8339 noaliases: bool,
8340}
8341
8342impl ZwcRelexGuard {
8343 pub(crate) fn enter() -> Self {
8344 let rcquotes = crate::ported::zsh_h::isset(crate::ported::zsh_h::RCQUOTES);
8345 if rcquotes {
8346 crate::ported::options::opt_state_set("rcquotes", false);
8347 }
8348 let noaliases = crate::ported::lex::noaliases();
8349 crate::ported::lex::set_noaliases(true); // c:Src/lex.c:1909
8350 Self {
8351 rcquotes,
8352 noaliases,
8353 }
8354 }
8355}
8356
8357impl Drop for ZwcRelexGuard {
8358 fn drop(&mut self) {
8359 if self.rcquotes {
8360 crate::ported::options::opt_state_set("rcquotes", true);
8361 }
8362 crate::ported::lex::set_noaliases(self.noaliases);
8363 }
8364}
8365
8366/// !!! WARNING: RUST-ONLY HELPER — NO C COUNTERPART !!!
8367///
8368/// The RCQUOTES state each shell-defined function's body was resolved
8369/// under at DEFINITION time, keyed by name and digested body text.
8370///
8371/// C has no such fact to carry. `execfuncdef` compiles the body into
8372/// wordcode when the definition runs (c:Src/exec.c:5389-5391 —
8373/// `shf->funcdef = dupeprog(...)`), and `printshfuncnode` renders THAT
8374/// program back with `getpermtext(f->funcdef, NULL, 1)`
8375/// (c:Src/hashtable.c:954). Every lexer-time decision is already settled
8376/// in the wordcode, so printing cannot revisit it — `functions f` gives
8377/// the same text no matter which options are set when it runs.
8378///
8379/// zshrs has no `Eprog` for a shell-defined function: `shfunc::body` keeps
8380/// the raw source and `printshfuncnode`'s stand-in RE-LEXES it at print
8381/// time. Under RCQUOTES an adjacent quote pair inside a quoted word lexes
8382/// as one LITERAL quote (c:Src/lex.c:1328) instead of as two delimiters,
8383/// so one unchanged function deparsed two different ways across a
8384/// `setopt rcquotes` — docs/BUGS.md #1105. Pinning the print-time lex to
8385/// defaults is wrong in the other direction: a function defined WHILE
8386/// RCQUOTES was set has to keep printing the RCQUOTES resolution, which is
8387/// why the state has to be recorded rather than assumed.
8388///
8389/// The state is sampled where the definition INSTALLS (the
8390/// `BUILTIN_REGISTER_COMPILED_FN` handler), not where its body was lexed.
8391/// In C those are the same instant, because zsh lexes one command list at
8392/// a time as it runs it; zshrs compiles a whole script ahead of running
8393/// it, so a runtime `setopt rcquotes` on an earlier line of the same file
8394/// is already in force at install time but was NOT in force at the ahead
8395/// -of-time lex. Install time is the one that matches zsh's printed
8396/// output (`setopt rcquotes` on line 1, `f() { … }` on line 2 →
8397/// C prints the RCQUOTES resolution), and it collapses onto lex time the
8398/// day the compiler stops running ahead of execution.
8399///
8400/// The mark is a DIGEST of the body rather than a bare flag, exactly like
8401/// [`AUTOLOAD_WORDCODE_BODY`]: `functions[name]=…`, an autoload, and a
8402/// plain redefinition all install different text, and a stale entry
8403/// simply stops matching instead of pinning the lexer for a body it never
8404/// described.
8405static FUNCDEF_LEX_RCQUOTES: Mutex<Option<HashMap<String, ([u8; 32], bool)>>> = Mutex::new(None);
8406
8407/// !!! WARNING: RUST-ONLY HELPER — NO C COUNTERPART !!!
8408///
8409/// Record the RCQUOTES state `name`'s definition was installed under.
8410/// See [`FUNCDEF_LEX_RCQUOTES`]; called from the funcdef install path
8411/// (c:Src/exec.c:5389 `shf->funcdef = …`, where C bakes the same fact
8412/// into the wordcode instead).
8413pub(crate) fn funcdef_note_rcquotes(name: &str, body: &str, rcquotes: bool) {
8414 let digest = crate::autoload_cache::source_digest(body);
8415 // The state the body was LEXED under wins when the parser recorded it
8416 // (see FUNCDEF_PARSE_RCQUOTES); install time is only the fallback.
8417 let rcquotes = FUNCDEF_PARSE_RCQUOTES
8418 .lock()
8419 .as_ref()
8420 .and_then(|m| m.get(&digest).copied())
8421 .unwrap_or(rcquotes);
8422 FUNCDEF_LEX_RCQUOTES
8423 .lock()
8424 .get_or_insert_with(HashMap::new)
8425 .insert(
8426 name.to_string(),
8427 (digest, rcquotes),
8428 );
8429}
8430
8431/// !!! WARNING: RUST-ONLY HELPER STATE — NO C COUNTERPART !!!
8432///
8433/// RCQUOTES as it stood when the parser lexed each captured function body,
8434/// keyed by the body digest. C bakes the `''` decision into the wordcode at
8435/// lex time (c:Src/lex.c:1326-1328), and zsh lexes one list at a time, so
8436/// `setopt rcquotes; f() { print 'a''b' }` on ONE line lexes `f` before the
8437/// option is on and prints `'a''b'`, while a definition on a later line (or
8438/// through `eval`) prints `'a'b'`. Install time cannot tell those apart.
8439static FUNCDEF_PARSE_RCQUOTES: Mutex<Option<HashMap<[u8; 32], bool>>> = Mutex::new(None);
8440
8441/// !!! WARNING: RUST-ONLY HELPER STATE — NO C COUNTERPART !!!
8442///
8443/// Digests of function bodies the parser captured, which are ALIAS-RESOLVED.
8444///
8445/// C's par_funcdef compiles the body to wordcode after alias expansion, so
8446/// `functions` (getpermtext, c:Src/hashtable.c:954) shows exactly what the
8447/// parse saw, whatever the alias table holds later: an alias removed or
8448/// redefined after the definition changes nothing, and one defined after the
8449/// parse (a `-c` string is parsed whole, c:Src/init.c:1568 execstring) never
8450/// appears. `funcdef_capture::body_text` hands the parser that same
8451/// post-expansion text, so re-lexing it with aliases ON expands a second time
8452/// — `alias ls='ls -G'` listed `ls -G -G x` — and a body recorded here is
8453/// always re-lexed with aliases off. Keyed by digest like
8454/// [`FUNCDEF_LEX_RCQUOTES`]; text that did not come from a capture
8455/// (`functions[f]=…`, an autoload file) has no entry and keeps the live table.
8456static FUNCDEF_ALIAS_RESOLVED: Mutex<Option<std::collections::HashSet<[u8; 32]>>> =
8457 Mutex::new(None);
8458
8459/// !!! WARNING: RUST-ONLY HELPER — NO C COUNTERPART !!!
8460///
8461/// Called by the parser right after it captures a function body. See
8462/// [`FUNCDEF_ALIAS_RESOLVED`].
8463pub(crate) fn funcdef_note_resolved_body(body: Option<&str>) {
8464 let Some(body) = body else { return };
8465 let digest = crate::autoload_cache::source_digest(body);
8466 FUNCDEF_ALIAS_RESOLVED
8467 .lock()
8468 .get_or_insert_with(std::collections::HashSet::new)
8469 .insert(digest);
8470 // Same parse-time capture point: record the RCQUOTES the body was lexed
8471 // under (FUNCDEF_PARSE_RCQUOTES).
8472 FUNCDEF_PARSE_RCQUOTES
8473 .lock()
8474 .get_or_insert_with(HashMap::new)
8475 .insert(digest, crate::ported::zsh_h::isset(crate::ported::zsh_h::RCQUOTES));
8476}
8477
8478/// !!! WARNING: RUST-ONLY HELPER — NO C COUNTERPART !!!
8479///
8480/// Pin RCQUOTES to the value `name`'s body was defined under, for the
8481/// duration of one deparse of that body.
8482///
8483/// This is [`ZwcRelexGuard`]'s sibling: same problem (zshrs lexes text
8484/// where C runs wordcode), same RAII shape, but the target value is the
8485/// RECORDED one rather than "off" — the definition may itself have been
8486/// made under RCQUOTES, and then the RCQUOTES resolution is the correct
8487/// one to print. With no record for this exact body (a function installed
8488/// through a path that does not record — `functions[f]=…`, the ported
8489/// walker, an autoload stub) nothing is pinned and the live option stands,
8490/// which is the behaviour that predates the record.
8491///
8492/// The option store is process-wide, so the pin is visible to a worker
8493/// thread that lexes concurrently; the window is one synchronous deparse,
8494/// as it is for [`ZwcRelexGuard`].
8495pub(crate) fn funcdef_lex_pin(name: &str, body: &str) -> FuncdefLexPin {
8496 // c:Src/hashtable.c:954 renders the STORED wordcode, where every alias the
8497 // body's parse expanded is already baked in and nothing else can expand.
8498 // The re-lex runs with `noaliases` (c:Src/lex.c:135) whenever the text is
8499 // already resolved: the parser captured it (FUNCDEF_ALIAS_RESOLVED), or —
8500 // for an autoload body not yet parsed, as after `autoload +X` — it was
8501 // loaded under `autoload -U` (PM_UNALIASED, c:Src/exec.c:5746) or rendered
8502 // from a `.zwc`. Any other body keeps the live alias table.
8503 let noaliases = crate::ported::lex::noaliases();
8504 // c:Src/exec.c:5389 execfuncdef — C deparses the wordcode parsed when the
8505 // function was DEFINED, and a definition inside `emulate sh -c` is parsed
8506 // under that emulation (stamped as `shf->sticky`, c:5527-5532). Re-lex
8507 // under the same emulation (installemulation + its on/off options, as
8508 // doshfunc applies it at c:5977-6010), so an sh-mode `( one | two )` case
8509 // pattern keeps its separate alternatives and prints `(one | two)`. Only a
8510 // function carrying a sticky emulation is touched: `eval` / `-z` / `+X`
8511 // bodies keep the live state.
8512 let sticky_restore = crate::ported::utils::getshfunc(name)
8513 .and_then(|f| f.sticky.clone())
8514 .filter(|s| crate::ported::exec::sticky_emulation_differs(Some(s)) != 0)
8515 .map(|s| install_sticky_emulation(&s));
8516 let captured = FUNCDEF_ALIAS_RESOLVED
8517 .lock()
8518 .as_ref()
8519 .is_some_and(|set| set.contains(&crate::autoload_cache::source_digest(body)));
8520 let deparse_noaliases = captured
8521 || crate::ported::utils::getshfunc(name).is_some_and(|f| {
8522 (f.node.flags as u32 & crate::ported::zsh_h::PM_UNALIASED) != 0
8523 })
8524 || autoload_body_from_wordcode(name, body);
8525 if deparse_noaliases {
8526 crate::ported::lex::set_noaliases(true); // c:Src/lex.c:1909
8527 }
8528 let want = {
8529 let slot = FUNCDEF_LEX_RCQUOTES.lock();
8530 slot.as_ref()
8531 .and_then(|map| map.get(name))
8532 .filter(|(sha, _)| *sha == crate::autoload_cache::source_digest(body))
8533 .map(|(_, rcquotes)| *rcquotes)
8534 };
8535 let live = crate::ported::zsh_h::isset(crate::ported::zsh_h::RCQUOTES);
8536 match want {
8537 Some(w) if w != live => {
8538 crate::ported::options::opt_state_set("rcquotes", w);
8539 FuncdefLexPin {
8540 restore: Some(live),
8541 noaliases,
8542 sticky_restore,
8543 }
8544 }
8545 _ => FuncdefLexPin {
8546 restore: None,
8547 noaliases,
8548 sticky_restore,
8549 },
8550 }
8551}
8552
8553/// !!! WARNING: RUST-ONLY HELPER — NO C COUNTERPART !!!
8554///
8555/// RAII half of [`funcdef_lex_pin`]. `restore` is `None` when nothing was
8556/// changed, so the common path costs one hash lookup and no option write.
8557pub(crate) struct FuncdefLexPin {
8558 restore: Option<bool>,
8559 noaliases: bool,
8560 /// Options and emulation in force before a sticky emulation was applied
8561 /// for the re-lex; put back on drop.
8562 sticky_restore: Option<(Vec<bool>, i32, i32, bool)>,
8563}
8564
8565impl Drop for FuncdefLexPin {
8566 fn drop(&mut self) {
8567 if let Some(live) = self.restore {
8568 crate::ported::options::opt_state_set("rcquotes", live);
8569 }
8570 crate::ported::lex::set_noaliases(self.noaliases);
8571 if let Some(saved) = self.sticky_restore.take() {
8572 restore_sticky_emulation(saved);
8573 }
8574 }
8575}
8576
8577/// Options and emulation cells saved by [`install_sticky_emulation`].
8578type SavedEmulation = (Vec<bool>, i32, i32, bool);
8579
8580/// !!! WARNING: RUST-ONLY HELPER — NO C COUNTERPART !!!
8581///
8582/// The option half of doshfunc's sticky-emulation entry (c:Src/exec.c:
8583/// 5991-6008): `installemulation(emulation, opts)` then the on/off option
8584/// lists. Returns what it overwrote for [`restore_sticky_emulation`].
8585fn install_sticky_emulation(s: &crate::ported::zsh_h::emulation_options) -> SavedEmulation {
8586 use std::sync::atomic::Ordering;
8587 let size = crate::ported::zsh_h::OPT_SIZE as usize;
8588 let saved: Vec<bool> = (0..size)
8589 .map(|optno| {
8590 optno > 0
8591 && crate::ported::options::opt_state_get(crate::ported::zsh_h::opt_name(optno as i32))
8592 .unwrap_or(false)
8593 })
8594 .collect();
8595 let saved_emu = (
8596 crate::ported::options::emulation.load(Ordering::Relaxed),
8597 crate::ported::options::EMULATION.load(Ordering::Relaxed),
8598 crate::ported::options::FULLY_EMULATING.load(Ordering::Relaxed),
8599 );
8600 let mut new_opts = [-1i8; crate::ported::zsh_h::OPT_SIZE as usize];
8601 crate::ported::options::installemulation(s.emulation, &mut new_opts); // c:5993
8602 for (optno, &v) in new_opts.iter().enumerate().skip(1) {
8603 if v >= 0 {
8604 crate::ported::options::opt_state_set(crate::ported::zsh_h::opt_name(optno as i32), v == 1);
8605 }
8606 }
8607 for on in &s.on_opts {
8608 crate::ported::options::opt_state_set(crate::ported::zsh_h::opt_name(*on as i32), true); // c:5995-6001
8609 }
8610 for off in &s.off_opts {
8611 crate::ported::options::opt_state_set(crate::ported::zsh_h::opt_name(*off as i32), false); // c:6002-6008
8612 }
8613 let emu_base = s.emulation & !crate::ported::zsh_h::EMULATE_FULLY;
8614 crate::ported::options::emulation.store(emu_base, Ordering::Relaxed);
8615 crate::ported::options::EMULATION.store(emu_base, Ordering::Relaxed);
8616 crate::ported::options::FULLY_EMULATING
8617 .store((s.emulation & crate::ported::zsh_h::EMULATE_FULLY) != 0, Ordering::Relaxed);
8618 (saved, saved_emu.0, saved_emu.1, saved_emu.2)
8619}
8620
8621/// !!! WARNING: RUST-ONLY HELPER — NO C COUNTERPART !!!
8622///
8623/// Undo [`install_sticky_emulation`].
8624fn restore_sticky_emulation((opts, emu, emu_cell, fully): SavedEmulation) {
8625 use std::sync::atomic::Ordering;
8626 for (optno, on) in opts.into_iter().enumerate().skip(1) {
8627 crate::ported::options::opt_state_set(crate::ported::zsh_h::opt_name(optno as i32), on);
8628 }
8629 crate::ported::options::emulation.store(emu, Ordering::Relaxed);
8630 crate::ported::options::EMULATION.store(emu_cell, Ordering::Relaxed);
8631 crate::ported::options::FULLY_EMULATING.store(fully, Ordering::Relaxed);
8632}
8633
8634/// !!! WARNING: RUST-ONLY HELPER — NO C COUNTERPART !!!
8635///
8636/// C loads an autoloaded body from INSIDE doshfunc: the stub's funcdef is
8637/// the `mkautofn` trampoline, so `execautofn` → `loadautofn` → `getfpfunc`
8638/// (c:Src/exec.c:5640, 5697) parses the file after doshfunc has entered the
8639/// stub's sticky emulation (c:5978-6010), and the body is installed IN
8640/// PLACE on the same Shfunc, keeping `shf->sticky` (stamped by
8641/// `shfunc_set_sticky` in bin_autoload, c:Src/builtin.c:3766). zshrs loads
8642/// and registers the body before doshfunc runs, so this guard opens the
8643/// same window for the load: the stub's emulation for the parse, and the
8644/// stub's snapshot as the pending `sticky` so the re-registration stamps it
8645/// onto the loaded function.
8646struct AutoloadStickyGuard {
8647 saved_opts: SavedEmulation,
8648 saved_sticky: Option<crate::ported::zsh_h::Emulation_options>,
8649}
8650
8651impl AutoloadStickyGuard {
8652 fn enter(stub: &crate::ported::zsh_h::shfunc) -> Option<Self> {
8653 let s = stub.sticky.as_deref()?;
8654 if crate::ported::exec::sticky_emulation_differs(Some(s)) == 0 {
8655 return None;
8656 }
8657 let dup = crate::ported::exec::sticky_emulation_dup(s, 1);
8658 let saved_opts = install_sticky_emulation(&dup);
8659 let saved_sticky = std::mem::replace(
8660 &mut *crate::ported::options::sticky
8661 .lock()
8662 .unwrap_or_else(|e| e.into_inner()),
8663 Some(dup),
8664 );
8665 Some(Self {
8666 saved_opts,
8667 saved_sticky,
8668 })
8669 }
8670}
8671
8672impl Drop for AutoloadStickyGuard {
8673 fn drop(&mut self) {
8674 *crate::ported::options::sticky
8675 .lock()
8676 .unwrap_or_else(|e| e.into_inner()) = self.saved_sticky.take();
8677 restore_sticky_emulation(std::mem::take(&mut self.saved_opts));
8678 }
8679}
8680
8681/// !!! WARNING: RUST-ONLY HELPER — NO C COUNTERPART !!!
8682///
8683/// Names whose installed autoload body was rendered back from WORDCODE
8684/// (`getpermtext` over a `.zwc` program) rather than read from a source file,
8685/// each mapped to a digest of that body.
8686///
8687/// C has no such fact to carry. `loadautofn` hands the dump's program
8688/// straight to `shf->funcdef = stripkshdef(prog, …)` (c:Src/exec.c:5753-5755),
8689/// and the ksh-style arm runs it with `execode(prog, 1, 0, "evalautofunc")`
8690/// (c:Src/exec.c:5795): a dump-loaded funcdef is never lexed again, at load
8691/// time or ever. zshrs executes function bodies as TEXT, so `loadautofn`
8692/// deparses the program and the REAL compile happens later — at the call that
8693/// installs the function, through [`ShellExecutor::run_autoload_definition`].
8694/// The two are separated by arbitrary user code, so "this text came from
8695/// wordcode" has to survive the gap or the deparse is re-lexed against
8696/// whatever RCQUOTES / alias state is live at call time. See
8697/// [`ZwcRelexGuard`] for exactly what that costs; the `source` leg of the same
8698/// bug is fixed by [`ShellExecutor::execute_zwc_program`].
8699///
8700/// The mark is a DIGEST of the body, not a bare flag, so it self-invalidates.
8701/// `functions[name]=…` (c:Src/Modules/parameter.c setpmfunction) and a later
8702/// load of the same name from a plain file both install different text, and
8703/// the digest simply stops matching — no writer anywhere else has to know this
8704/// table exists, and a stale entry cannot pin the lexer for a body that was
8705/// never wordcode.
8706static AUTOLOAD_WORDCODE_BODY: Mutex<Option<HashMap<String, [u8; 32]>>> = Mutex::new(None);
8707
8708/// !!! WARNING: RUST-ONLY HELPER — NO C COUNTERPART !!!
8709///
8710/// Record (`Some`) or drop (`None`) the "body came from wordcode" mark for
8711/// `name`. Called from `loadautofn` (c:Src/exec.c:5682) on every load, so a
8712/// plain-file load clears a mark an earlier dump load left.
8713pub(crate) fn autoload_note_wordcode_body(name: &str, body: Option<&str>) {
8714 let mut slot = AUTOLOAD_WORDCODE_BODY.lock();
8715 match body {
8716 Some(text) => {
8717 slot.get_or_insert_with(HashMap::new)
8718 .insert(name.to_string(), crate::autoload_cache::source_digest(text));
8719 }
8720 None => {
8721 if let Some(map) = slot.as_mut() {
8722 map.remove(name);
8723 }
8724 }
8725 }
8726}
8727
8728/// !!! WARNING: RUST-ONLY HELPER — NO C COUNTERPART !!!
8729///
8730/// True when `body` is the exact text [`autoload_note_wordcode_body`] recorded
8731/// for `name` — i.e. this is a `.zwc` deparse about to be lexed a second time.
8732pub(crate) fn autoload_body_from_wordcode(name: &str, body: &str) -> bool {
8733 let slot = AUTOLOAD_WORDCODE_BODY.lock();
8734 slot.as_ref()
8735 .and_then(|map| map.get(name))
8736 .is_some_and(|sha| *sha == crate::autoload_cache::source_digest(body))
8737}
8738
8739/// The exact source text an autoload of `name` installs — either the
8740/// file body verbatim (ksh style, or a file that already defines the
8741/// function) or `name() { <body> }`.
8742///
8743/// Split out of [`autoload_register_source`] with the ksh decision
8744/// passed IN so the prewarm (`autoload_prewarm`, which has no shfunc
8745/// flags to consult because nothing is registered yet) compiles
8746/// byte-identical text to what the loader will run. The two drifting
8747/// apart is precisely what made the pre-v2 shard unusable: it cached a
8748/// different program than the one the loader installs.
8749/// Returns the definition text plus whether that parse REJECTED the body
8750/// (c:Src/exec.c:6264 `r = parse_string(d, 1)` returning NULL, which makes
8751/// `loadautofn` abandon the load at c:5726 with no further diagnostic).
8752pub(crate) fn autoload_definition_source(
8753 name: &str,
8754 body: &str,
8755 ksh_style: bool,
8756) -> (String, bool) {
8757 // c:Src/exec.c:5781 — a ksh-style load executes the file contents at top
8758 // level (c:5795 `execode(prog, 1, 0, "evalautofunc")`) and expects the
8759 // file itself to define the function — so the body goes through the
8760 // pipeline VERBATIM, never wrapped.
8761 if ksh_style {
8762 return (body.to_string(), false); // c:5795 execode(prog, ..., "evalautofunc")
8763 }
8764 // c:6257-6265 — `getfpfunc` parses the file under the LOADEE's name:
8765 // char *oldscriptname = scriptname;
8766 // scriptname = dupstring(s);
8767 // r = parse_string(d, 1);
8768 // scriptname = oldscriptname;
8769 // so a syntax error in an autoloaded file is reported as
8770 // `_files:40: parse error: …`, not against the frame that triggered the
8771 // load. zshrs runs the only parse of the raw body right here, so the
8772 // same window belongs around it — without it the diagnostic came out as
8773 // `g:40:` for `g(){ emulate ksh -c _files }`.
8774 //
8775 // `scriptname` is one process-wide cell where C's is a single-thread
8776 // global, and a worker-thread compile prints nothing anyway (`zwarning`,
8777 // utils.rs:150, routes its diagnostics to the log) — so only the shell
8778 // thread takes the window, and no worker can blank out a prefix the shell
8779 // thread is in the middle of writing.
8780 let swap_scriptname = !crate::worker::in_worker_thread();
8781 let old_scriptname = crate::ported::utils::scriptname_get(); // c:6257
8782 if swap_scriptname {
8783 crate::ported::utils::set_scriptname(Some(name.to_string())); // c:6263
8784 }
8785 let saved_errflag = crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed);
8786 crate::ported::utils::errflag.fetch_and(
8787 !crate::ported::utils::ERRFLAG_ERROR,
8788 std::sync::atomic::Ordering::Relaxed,
8789 );
8790 let prog = crate::ported::exec::parse_string(body, 1); // c:6329 `r = parse_string(d, 1);` — reset_lineno: errors count lines within the file
8791 let parse_failed = (crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed)
8792 & crate::ported::utils::ERRFLAG_ERROR)
8793 != 0
8794 || prog.is_none();
8795 crate::ported::utils::errflag.store(saved_errflag, std::sync::atomic::Ordering::Relaxed);
8796 if swap_scriptname {
8797 crate::ported::utils::set_scriptname(old_scriptname); // c:6265
8798 }
8799 let stripped = prog
8800 .map(|prog| {
8801 let original_len = prog.prog.len();
8802 // stripkshdef returns the input untouched when the prog
8803 // doesn't match the single-`function NAME` shape, and a
8804 // shorter (body-only) prog when it does. Compare the
8805 // wordcode length to detect the strip without owning the
8806 // post-strip Eprog (we only need the yes/no answer here).
8807 let prog_box = Box::new(prog);
8808 crate::ported::exec::stripkshdef(Some(prog_box), name)
8809 .map(|p| p.prog.len() != original_len)
8810 .unwrap_or(false)
8811 })
8812 .unwrap_or(false);
8813 let text = if stripped {
8814 body.to_string()
8815 } else {
8816 format!("{name}() {{\n{body}\n}}")
8817 };
8818 (text, parse_failed)
8819}
8820
8821// zsh_eval_context push/pop/sync relocated 2026-06-12 INTO doshfunc
8822// (src/ported/exec.rs) — its sole caller, and `zsh_eval_context` is
8823// that module's own static. The shell-visible mirror writes inline
8824// at the push site + the guard's Drop. No bridge indirection.
8825
8826impl ShellExecutor {
8827 /// Execute the trap body for a signal name from the REPL signal
8828 /// loop (bins/zshrs.rs CtrlC/CtrlD dispatch). Thin passthru to
8829 /// `traps_table` lookup + `execute_script` — kept as a method
8830 /// because the REPL loop owns `&mut ShellExecutor` and needs a
8831 /// single call point. The async signal-handler dispatch path
8832 /// goes through `crate::ported::signals::dotrap` instead.
8833 pub fn run_trap(&mut self, signal: &str) {
8834 let action = crate::ported::builtin::traps_table()
8835 .lock()
8836 .ok()
8837 .and_then(|t| t.get(signal).cloned());
8838 if let Some(body) = action {
8839 if !body.is_empty() {
8840 let _ = self.execute_string_without_exit_hooks(&body);
8841 }
8842 }
8843 }
8844}
8845
8846impl ShellExecutor {
8847 /// Expand glob pattern via canonical `glob_path` (port of
8848 /// `Src/glob.c::zglob`). Adds executor-side `current_command_glob_failed`
8849 /// cell so the dispatch layer skips the current command on NOMATCH +
8850 /// looks_like_glob instead of exiting the shell.
8851 pub fn expand_glob(&self, pattern: &str) -> Vec<String> {
8852 // c:Src/glob.c:1230-1233 — `if (unset(GLOBOPT) || !haswilds(ostr) ||
8853 // unset(EXECOPT)) { untokenize(ostr); return; }`: under NO_EXEC zglob
8854 // never globs, so no word (the command word included) can report
8855 // NOMATCH.
8856 if !crate::ported::zsh_h::isset(crate::ported::zsh_h::EXECOPT) {
8857 return vec![crate::ported::lex::untokenize(pattern)];
8858 }
8859 let errflag_before =
8860 crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed);
8861 let expanded = glob_path(pattern);
8862 if !expanded.is_empty() {
8863 // c:Src/glob.c:1871-1872 — `if (matchct) badcshglob |= 2;`
8864 // (at least one expansion on this command line worked).
8865 // Only real glob patterns count — C's zglob early-returns
8866 // before the matchct accounting for non-wild words, so
8867 // gate on haswilds like the failure path below. Consumed
8868 // per command by fusevm_bridge::consume_badcshglob.
8869 if crate::ported::zsh_h::isset(crate::ported::zsh_h::CSHNULLGLOB) {
8870 let mut pattern_tok = pattern.to_string();
8871 crate::ported::glob::tokenize(&mut pattern_tok);
8872 if crate::ported::pattern::haswilds(&pattern_tok) {
8873 crate::ported::glob::BADCSHGLOB
8874 .fetch_or(2, std::sync::atomic::Ordering::Relaxed);
8875 }
8876 }
8877 return expanded;
8878 }
8879 // c:Src/glob.c:1786-1788 — `if (errflag) { restore_globstate(saved);
8880 // return; }`. A qualifier-parse error returns from `zglob` outright,
8881 // so C never reaches the c:1873-1886 nullglob/nomatch dispatch below.
8882 // The port has to re-derive `gf_nullglob` from the pattern because
8883 // `glob_path` hands back only a `Vec` — and that SECOND qualifier
8884 // parse re-runs every diagnostic the first one already emitted. It is
8885 // normally invisible because `zerr` suppresses itself while
8886 // ERRFLAG_ERROR is set (c:Src/utils.c:175), but a subscript qualifier
8887 // runs the lexer (`getindex` → `parse_subscript` → `strinbeg` →
8888 // `hbegin`, c:Src/hist.c:1115 `errflag &= ~ERRFLAG_ERROR`), which
8889 // clears exactly that bit — so `*(N[1,])` printed `bad math
8890 // expression: empty string` twice. Bail out where C's `return` lands.
8891 if crate::ported::utils::errflag.load(std::sync::atomic::Ordering::Relaxed) != 0 {
8892 // A diagnostic THIS glob raised (`bad pattern: a[B`, a bad
8893 // qualifier) belongs to the same per-command carrier as the
8894 // c:1877 NOMATCH below. C runs an external command's prefork
8895 // expansion in the child forked at Src/exec.c:3719, so the
8896 // `zerr` there only costs that child (status 1) and the list
8897 // goes on; a builtin expands in the shell and the errflag aborts
8898 // the list. The dispatch layer makes exactly that split for
8899 // `current_command_glob_failed`; without it `/bin/echo a[B;
8900 // print after` aborted the list and the `find` shadow ran with
8901 // the raw word after printing the diagnostic.
8902 if errflag_before == 0 {
8903 self.current_command_glob_failed.set(true);
8904 }
8905 return Vec::new();
8906 }
8907 // c:1871-1872 — `if (matchct) badcshglob |= 2;`: files DID match and
8908 // only the `[first,last]` subscript left none (`*([100])`), so this
8909 // is not a failed expansion — the word simply expands to nothing.
8910 if crate::ported::glob::CURGLOBDATA
8911 .lock()
8912 .unwrap_or_else(|e| e.into_inner())
8913 .matchct
8914 > 0
8915 {
8916 if crate::ported::zsh_h::isset(crate::ported::zsh_h::CSHNULLGLOB) {
8917 crate::ported::glob::BADCSHGLOB.fetch_or(2, std::sync::atomic::Ordering::Relaxed);
8918 }
8919 return Vec::new();
8920 }
8921 // No matches. Mirror zsh's `setopt nullglob` / `nomatch`
8922 // dispatch (Src/glob.c:1873-1886) here because glob_path
8923 // returns an empty Vec without knowing executor state.
8924 // c:Src/glob.c:1567-1569 `gf_nullglob` per-glob — the `(N)`
8925 // qualifier acts like `setopt nullglob` for this expression
8926 // alone. parse_qualifiers detects the suffix `(...)` block;
8927 // the resulting `qualifiers.nullglob` mirrors C's gf_nullglob
8928 // carrier.
8929 let per_glob_nullglob = crate::ported::glob::parse_qualifiers(pattern)
8930 .1
8931 .map(|q| q.nullglob)
8932 .unwrap_or(false);
8933 let nullglob = opt_state_get("nullglob").unwrap_or(false) || per_glob_nullglob;
8934 if nullglob {
8935 // c:Src/glob.c:1888-1894 —
8936 // `else if (in_expandredir) {`
8937 // `/* if completing for redirection, we can't remove the`
8938 // ` pattern even if NULL_GLOB is in effect */`
8939 // `zerr("redirection failed (no match): %s", ostr);`
8940 // `zfree(matchbuf, 0);`
8941 // `restore_globstate(saved);`
8942 // `return;`
8943 // `}`
8944 // Reached ONLY when gf_nullglob is set (the `else if` chain at
8945 // c:1873 owns every other no-match case), which is exactly the
8946 // `> file(N)` shape: dropping the word would leave the
8947 // redirection with no target at all, so `echo > nope(N)` failed
8948 // with an empty filename in `no such file or directory:`.
8949 if crate::ported::glob::IN_EXPANDREDIR.load(std::sync::atomic::Ordering::SeqCst) != 0 {
8950 zerr(&format!(
8951 "redirection failed (no match): {}",
8952 crate::ported::lex::untokenize(pattern)
8953 )); // c:1891
8954 self.current_command_glob_failed.set(true);
8955 return Vec::new(); // c:1894
8956 }
8957 return Vec::new();
8958 }
8959 let nomatch = opt_state_get("nomatch").unwrap_or(true);
8960 // Use canonical `haswilds` (port of Src/pattern.c:4306-4376)
8961 // instead of the Rust-only `looks_like_glob`. C zsh's
8962 // `Src/glob.c:1876` NOMATCH branch fires whenever the input
8963 // tripped haswilds during the `zglob` entry check —
8964 // including patterns whose internal `(` / `)` form a group
8965 // or alternation but don't end with `)` (e.g. `abc(a)def`,
8966 // `(abc`). The previous `looks_like_glob` only caught
8967 // trailing-`(...)` qualifiers, leaving mid-word groups and
8968 // unclosed parens to fall through to the literal-passthrough
8969 // branch. #170 in docs/BUGS.md.
8970 //
8971 // haswilds scans TOKENIZED strings (C's zglob gets the
8972 // lexer-tokenized word at Src/glob.c:1230); this entry point
8973 // receives untokenized fast-path patterns, so tokenize a
8974 // local copy first — the same preparation C applies to
8975 // runtime-built strings (compcore.c:2231 tokenizes fignore
8976 // entries before its haswilds call). tokenize Bnull's
8977 // backslash-escaped metachars, so `\*` stays literal here
8978 // exactly as in C. Bug #627: plain multibyte text (`↔`)
8979 // passes through tokenize unchanged and matches no token.
8980 let mut pattern_tok = pattern.to_string();
8981 crate::ported::glob::tokenize(&mut pattern_tok); // c:Src/glob.c:3548
8982 let is_glob = crate::ported::pattern::haswilds(&pattern_tok);
8983 // c:Src/glob.c:1874-1875 — `if (isset(CSHNULLGLOB)) {
8984 // badcshglob |= 1; }` — the else-if chain means neither the
8985 // NOMATCH error nor the literal passthrough runs: the failed
8986 // word is silently DROPPED here, and the per-command boundary
8987 // (fusevm_bridge::consume_badcshglob, Src/subst.c:505-507)
8988 // emits the csh-style `no match` iff NO glob on the line
8989 // matched.
8990 if is_glob && crate::ported::zsh_h::isset(crate::ported::zsh_h::CSHNULLGLOB) {
8991 crate::ported::glob::BADCSHGLOB.fetch_or(1, std::sync::atomic::Ordering::Relaxed);
8992 return Vec::new();
8993 }
8994 if nomatch && is_glob {
8995 // c:Src/glob.c:1876-1880 — `else if (isset(NOMATCH)) {`
8996 // `zerr("no matches found: %s", ostr);`
8997 // `zfree(matchbuf, 0);`
8998 // `restore_globstate(saved);`
8999 // `return;`
9000 // `}`
9001 // C aborts via ERRFLAG_ERROR set by zerr() at c:Src/utils.c
9002 // and the matchbuf/state cleanup. The Rust port mirrors
9003 // both: zerr() in utils.rs sets ERRFLAG_ERROR via
9004 // `errflag.fetch_or(ERRFLAG_ERROR, ...)` already; we then
9005 // re-set explicitly (defensive — historically this line
9006 // had `fetch_and(!ERRFLAG_ERROR)` which CLEARED the flag
9007 // immediately after zerr, making `echo /never/*` print
9008 // the literal and exit 0 instead of erroring like zsh —
9009 // parity bug #13).
9010 // c:1877 `zerr("no matches found: %s", ostr);` — `ostr` is
9011 // the TOKENIZED word, and zerrmsg's `%s` arm renders it
9012 // through `nicezputs` → `sb_niceformat`, which calls
9013 // `untokenize(ums)` (Src/utils.c). Without that step the
9014 // token bytes are dropped by the terminal and the message
9015 // reads `no matches found: /tmp/nope_.txt`.
9016 zerr(&format!(
9017 "no matches found: {}",
9018 crate::ported::lex::untokenize(pattern)
9019 )); // c:1877
9020 self.current_command_glob_failed.set(true);
9021 // c:Src/glob.c:1876-1880 — zerr sets ERRFLAG_ERROR and
9022 // glob_failed cell carries the signal. The ERRFLAG_ERROR
9023 // clear (so subsequent sublists run) now lives at the
9024 // dispatcher's post-command-boundary at
9025 // fusevm_bridge.rs:299 where current_command_glob_failed
9026 // is consumed — matches C's execlist behavior of clearing
9027 // command-error errflag between sublists.
9028 return Vec::new(); // c:1880 return
9029 }
9030 // Pattern has no glob meta — pass through literally.
9031 // c:Src/glob.c:1882-1886 — `/* treat as an ordinary string */
9032 // untokenize(matchptr->name = dupstring(ostr));`. The word
9033 // arrives here in LEXER-TOKENIZED form (c:1221 `ostr =
9034 // getdata(np)`), so the literal fallback MUST untokenize or the
9035 // raw token bytes reach stdout: `unsetopt nomatch; echo
9036 // /tmp/nope_*.txt` printed `/tmp/nope_\u{e187}.txt`.
9037 vec![crate::ported::lex::untokenize(pattern)]
9038 }
9039 /// True iff the literal `pattern` actually contains a glob metachar
9040 /// in a position that would have triggered globbing. Used to avoid
9041 /// spurious "no matches" errors when expand_glob is called on a
9042 /// plain path that happened to route through this code (e.g. some
9043 /// fast paths bridge unconditionally).
9044 pub(crate) fn looks_like_glob(pattern: &str) -> bool {
9045 // A trailing `(qualifier)` is itself a glob trigger — e.g.
9046 // `path(L+10)` should be treated as a glob even when the
9047 // body has no `*`/`?`/`[...]`.
9048 let has_qual_suffix = if let Some(open) = pattern.rfind('(') {
9049 pattern.ends_with(')') && open + 1 < pattern.len() - 1
9050 } else {
9051 false
9052 };
9053 // Strip trailing `(...)` qualifier so we test the pattern body.
9054 let body = if let Some(open) = pattern.rfind('(') {
9055 if pattern.ends_with(')') {
9056 &pattern[..open]
9057 } else {
9058 pattern
9059 }
9060 } else {
9061 pattern
9062 };
9063 // Walk character-by-character so escaped metachars (`\*`, `\?`,
9064 // `\[`) are NOT counted as glob triggers. zsh: `echo \*` prints
9065 // a literal `*`; without the unescaped check, looks_like_glob
9066 // returned true on the bare `*` and the runtime glob expansion
9067 // aborted with NOMATCH.
9068 let chars: Vec<char> = body.chars().collect();
9069 let mut i = 0;
9070 let mut has_unescaped_star = false;
9071 let mut has_unescaped_question = false;
9072 let mut has_unescaped_bracket_open: Option<usize> = None;
9073 while i < chars.len() {
9074 let c = chars[i];
9075 if c == '\\' && i + 1 < chars.len() {
9076 // Escaped char — skip both.
9077 i += 2;
9078 continue;
9079 }
9080 match c {
9081 '*' => has_unescaped_star = true,
9082 '?' => has_unescaped_question = true,
9083 '[' if has_unescaped_bracket_open.is_none() => {
9084 has_unescaped_bracket_open = Some(i);
9085 }
9086 _ => {}
9087 }
9088 i += 1;
9089 }
9090 // `[` only counts when there's a matching `]` after it.
9091 let has_bracket_class = has_unescaped_bracket_open
9092 .map(|i| body[i + 1..].contains(']'))
9093 .unwrap_or(false);
9094 // `<N-M>` numeric range glob is also a trigger — match shape
9095 // `<` + optional digits + `-` + optional digits + `>` outside
9096 // any bracket expression.
9097 let has_numeric_range =
9098 body.contains('<') && body.contains('>') && !extract_numeric_ranges(body).is_empty();
9099 has_unescaped_star
9100 || has_unescaped_question
9101 || has_bracket_class
9102 || has_qual_suffix
9103 || has_numeric_range
9104 }
9105}
9106
9107impl ShellExecutor {
9108 pub(crate) fn copy_dir_recursive(src: &Path, dest: &Path) -> io::Result<()> {
9109 if !dest.exists() {
9110 fs::create_dir_all(dest)?;
9111 }
9112 for entry in fs::read_dir(src)? {
9113 let entry = entry?;
9114 let file_type = entry.file_type()?;
9115 let src_path = entry.path();
9116 let dest_path = dest.join(entry.file_name());
9117
9118 if file_type.is_dir() {
9119 Self::copy_dir_recursive(&src_path, &dest_path)?;
9120 } else {
9121 fs::copy(&src_path, &dest_path)?;
9122 }
9123 }
9124 Ok(())
9125 }
9126}
9127
9128// Magic-assoc scan-by-name aggregator. C's per-table getfn/scanfn
9129// pointers in paramdef[] (Src/Modules/parameter.c:825+) handle this
9130// indirectly via paramtab dispatch; this Rust-only helper exposes a
9131// single `partab_get` / `partab_scan_keys` entry that the bridge
9132// uses for name → keys lookup.
9133use std::cell::RefCell;
9134thread_local! {
9135 static SCAN_KEYS: RefCell<Vec<String>> = const { RefCell::new(Vec::new()) };
9136}
9137
9138/// Lookup helper for `${name[key]}` magic-assoc reads — dispatches
9139/// through canonical `PARTAB` (Src/Modules/parameter.c:2235 ports).
9140/// Returns `None` if name isn't a known magic-assoc.
9141/// Module parameters that have actually been touched this session.
9142///
9143/// zshrs-original bookkeeping for a C behavior that falls out of the module
9144/// system there. zsh registers `zsh/parameter`'s params (`aliases`,
9145/// `commands`, `functions`, …) as PM_AUTOLOAD stubs in `realparamtab`;
9146/// touching ONE of them materializes only that name — its siblings stay
9147/// stubs even though the module is now loaded. `paramtypestr`
9148/// (Src/Modules/parameter.c:49-50) reports a PM_AUTOLOAD node as
9149/// "undefined", which is what an enumeration of `$parameters` shows.
9150/// zshrs seeds all of them eagerly (init_partab_params), so without this
9151/// set every one reported its real type and `${(@k)parameters[(R)a*]}`
9152/// matched 56 names against zsh's 18 — putting them in the wrong
9153/// `_parameters -g` bucket (`unset <TAB>`: 418 entries vs zsh's 496).
9154static MATERIALIZED_MODULE_PARAMS: std::sync::OnceLock<Mutex<HashSet<String>>> =
9155 std::sync::OnceLock::new();
9156
9157/// Record that `name` was read/written, so `$parameters` stops reporting it
9158/// as an unmaterialized autoload stub. See [`MATERIALIZED_MODULE_PARAMS`].
9159pub fn mark_module_param_used(name: &str) {
9160 let set = MATERIALIZED_MODULE_PARAMS.get_or_init(|| Mutex::new(HashSet::new()));
9161 let first_touch = {
9162 let mut g = set.lock();
9163 // Drop the guard before the module load below — `boot_` runs shell
9164 // code (setsparam/setiparam) that can re-enter this function.
9165 g.insert(name.to_string())
9166 };
9167 if first_touch {
9168 materialize_module_param(name);
9169 }
9170}
9171
9172/// The side effect C's `loadparamnode` (`Src/params.c:563-585`) has beyond
9173/// clearing PM_AUTOLOAD: `(void)ensurefeature(mn, "p:", nam)`
9174/// (`Src/module.c:3419-3432`) actually LOADS the owning module, running its
9175/// `setup_`/`boot_`. `zsh/watch`'s `boot_` (`Src/Modules/watch.c:750-753`)
9176/// seeds `WATCHFMT`/`LOGCHECK` when absent, so in zsh
9177/// `${parameters[watch]}` leaves `${parameters[LOGCHECK]}` == "integer".
9178///
9179/// !!! WARNING: RUST-ONLY HELPER !!!
9180/// C has no separate function: `loadparamnode` calls `ensurefeature`
9181/// inline. zshrs models PM_AUTOLOAD as a side-set rather than a node flag
9182/// (see [`MATERIALIZED_MODULE_PARAMS`]), so the load side effect needs its
9183/// own hook off the marking point. The `try_lock` and the re-entrancy guard
9184/// are also Rust-only: C serialises on `queue_signals`, whereas zshrs's
9185/// `MODULESTAB` is a real mutex that several callers of
9186/// `mark_module_param_used` already hold.
9187fn materialize_module_param(name: &str) {
9188 use std::cell::Cell;
9189 thread_local! {
9190 static LOADING: Cell<bool> = const { Cell::new(false) };
9191 }
9192 // c:Src/params.c:566 — only PM_AUTOLOAD stubs carry `pm->u.str` (the
9193 // owning module name); anything else falls straight through.
9194 let Some((_, modname)) = AUTOLOAD_PARAMS.iter().find(|(p, _)| *p == name) else {
9195 return;
9196 };
9197 if LOADING.with(|f| f.get()) {
9198 return;
9199 }
9200 // The whole load chain wants `&mut modulestab`. Every other caller takes
9201 // the same lock for a moment; if one of them is mid-flight (or is our own
9202 // caller), skip rather than deadlock — the mark itself already landed.
9203 let Ok(mut tab) = crate::ported::module::MODULESTAB.try_lock() else {
9204 return;
9205 };
9206 // c:Src/module.c:2352 — require_module short-circuits on an already
9207 // booted module, but check first so the common case never pays for the
9208 // find_module/alias walk.
9209 if tab
9210 .modules
9211 .get(*modname)
9212 .is_some_and(|m| (m.node.flags & crate::ported::zsh_h::MOD_INIT_B) != 0)
9213 {
9214 return;
9215 }
9216 LOADING.with(|f| f.set(true));
9217 // c:3419-3432 ensurefeature(mn, "p:", nam) — `silent` is 0 in C, but a
9218 // failure here is not user-visible in the autoload path (c:571-580 only
9219 // errors when the parameter is still undefined afterwards), and zshrs's
9220 // require_module warns on any module it cannot static-link.
9221 let _ = crate::ported::module::ensurefeature(&mut tab, modname, "p:", Some(name)); // c:3419
9222 LOADING.with(|f| f.set(false));
9223}
9224
9225/// Undo [`mark_module_param_used`] — the `pd->pm = NULL` half of C's
9226/// `deleteparamdef` (`Src/module.c:1128-1179`), reached from
9227/// `setparamdefs` (`c:1176-1180`) whenever a module feature is turned OFF
9228/// (`zmodload -F zsh/parameter -p:functions`, or a single-feature load
9229/// leaving the siblings disabled).
9230///
9231/// !!! WARNING: RUST-ONLY HELPER !!!
9232/// C has no separate function: `deleteparamdef` removes the node from
9233/// `paramtab` outright. zshrs seeds every magic parameter eagerly and models
9234/// PM_AUTOLOAD as the [`MATERIALIZED_MODULE_PARAMS`] side-set, so "removed"
9235/// is "back to being an unmaterialized stub".
9236pub fn unmark_module_param_used(name: &str) {
9237 let set = MATERIALIZED_MODULE_PARAMS.get_or_init(|| Mutex::new(HashSet::new()));
9238 set.lock().remove(name);
9239}
9240
9241/// True when `name` is still an untouched module-parameter stub — i.e. zsh
9242/// would report it as PM_AUTOLOAD ("undefined") when enumerating
9243/// `$parameters`. See [`MATERIALIZED_MODULE_PARAMS`].
9244pub fn module_param_is_autoload_stub(name: &str) -> bool {
9245 if !AUTOLOAD_PARAMS.iter().any(|(p, _)| *p == name) {
9246 return false;
9247 }
9248 MATERIALIZED_MODULE_PARAMS
9249 .get_or_init(|| Mutex::new(HashSet::new()))
9250 .lock()
9251 .contains(name)
9252 .eq(&false)
9253}
9254
9255/// True when the magic special parameter `name` (a `partab[]` row from
9256/// `Src/Modules/parameter.c:2235-2298` — `options`, `functions`,
9257/// `commands`, `parameters`, `dirstack`, …) is currently SHADOWED by a
9258/// plain user parameter of the same name.
9259///
9260/// Rust-only helper with no C counterpart BY CONSTRUCTION: C zsh keeps
9261/// specials and user parameters in the ONE `paramtab` hash, so ordinary
9262/// hash lookup already implements this. `createparam`
9263/// (c:Src/params.c:1090-1115) finds the existing special node, stashes
9264/// it in `pm->old`, and inserts a fresh plain node under the same key;
9265/// every later `getvalue` / `fetchvalue` / `gethashparam` therefore hits
9266/// the plain node and the special's `gsu` callbacks are unreachable
9267/// until `endparamscope` restores `pm->old`. zshrs instead keeps the
9268/// magic rows in SEPARATE static tables (`PARTAB`, `PARTAB_ARRAY`) and
9269/// matches them BY NAME, so a name-only match resurrected the special
9270/// even while a local shadowed it. This predicate re-imposes C's
9271/// shadowing on the split-table layout; it is architecture glue, not a
9272/// port.
9273///
9274/// `init_partab_params` (below) seeds every magic row into `paramtab`
9275/// with `PM_SPECIAL` (C's `SPECIALPMDEF` macro), and `local`/`typeset`
9276/// replaces that node with one carrying no `PM_SPECIAL`, so the live
9277/// node's `PM_SPECIAL` bit is exactly C's "is the special still the
9278/// visible binding" test.
9279///
9280/// Returns false when a MODULE-GATED row (`sysparams`, `errnos`,
9281/// `mapfile`, `langinfo`) has no `paramtab` node and its module is not
9282/// loaded: those are seeded on
9283/// demand by `seed_partab_param`, and the PARTAB walk must still answer
9284/// for them (their own `module` gate decides).
9285///
9286/// For every other magic row an ABSENT node means the binding is gone —
9287/// `unset` removed it. C reaches the same answer through one gate:
9288/// `Src/params.c:2264-2266` `if (!pm || ((pm->node.flags & PM_UNSET) &&
9289/// !(pm->node.flags & PM_DECLARED))) return NULL;` in `fetchvalue`, the
9290/// single choke point every `${X}` / `${#X}` / `${(k)X}` / `${(t)X}` /
9291/// `${X[k]}` read passes through. Both of its arms show up here:
9292/// * `!pm` — `unset functions` at a point where the name is still the
9293/// `PM_AUTOLOAD` stub (`Src/module.c:1218-1223`) finds a PLAIN
9294/// `PM_SCALAR` node with neither `PM_SPECIAL` nor `PM_READONLY`, so
9295/// `unsetparam_pm`'s c:3851-3852 keep-the-node test
9296/// (`(flags & (PM_SPECIAL|PM_REMOVABLE)) == PM_SPECIAL`) is false and
9297/// c:3874 `paramtab->removenode` drops it outright.
9298/// * `PM_UNSET && !PM_DECLARED` — once the special HAS been
9299/// materialized, c:3851-3852 keeps the node and `stdunsetfn`
9300/// (c:3939) marking `PM_UNSET` is the entire record of the unset;
9301/// `setpmfunctions(pm, NULL)` returns immediately on `if (!ht)
9302/// return` (`Src/Modules/parameter.c:361-362`), so `shfunctab` — the
9303/// real table behind the row — survives untouched and `ff` still runs.
9304///
9305/// Both arms mean the same thing for a split-table port: the magic row
9306/// is no longer the visible binding for this name, exactly as when a
9307/// `local` shadows it. Answering that one question here is what lets
9308/// every PARTAB dispatch site keep a single guard.
9309///
9310/// Symptom this fixes: git's `git-completion.bash`
9311/// `__git_resolve_builtins` does `local options; eval
9312/// "options=\${$var-}"` (git 2.55.0
9313/// share/zsh/site-functions/git-completion.bash:500-501). `$options`
9314/// read back the zsh/parameter option table (`off on off …`) instead of
9315/// the local, so `git checkout --<TAB>` completed nothing.
9316pub fn magic_special_shadowed(name: &str) -> bool {
9317 // Only `partab[]` names can be shadowed in this sense — an ordinary
9318 // user assoc / array has no special behind it, and its own paramtab
9319 // node legitimately carries no PM_SPECIAL.
9320 if !PARTAB.iter().any(|e| e.name == name) && !PARTAB_ARRAY.iter().any(|e| e.name == name) {
9321 return false;
9322 }
9323 // A module-gated row (`errnos`, `sysparams`, `mapfile`, `langinfo`)
9324 // gets its paramtab node from the owning module's setparamdefs
9325 // (Src/module.c:1169-1196), so while that module is loaded an absent
9326 // node means its `p:` feature is off: deleteparamdef (c:1190) removed
9327 // it, or the module was loaded with other features only. Read the
9328 // module state before taking the paramtab lock.
9329 let gated_loaded = module_gated_partab_module(name)
9330 .map(|m| crate::ported::module::MODULESTAB.lock().unwrap().is_loaded(m));
9331 crate::ported::params::paramtab()
9332 .read()
9333 .map_or(false, |tab| {
9334 let Some(pm) = tab.get(name) else {
9335 // c:Src/params.c:2264 `if (!pm ...) return NULL` —
9336 // `unset` removed the node (see the doc comment). Only
9337 // a valid reading once the rows have been seeded. A
9338 // gated row whose module is not loaded is left to the
9339 // module gate in partab_get / partab_array_get.
9340 return match gated_loaded {
9341 Some(loaded) => loaded,
9342 None => PARTAB_SEEDED.load(std::sync::atomic::Ordering::Acquire),
9343 };
9344 };
9345 {
9346 // c:Src/params.c:2264-2266 — `(pm->node.flags & PM_UNSET)
9347 // && !(pm->node.flags & PM_DECLARED)`: the materialized
9348 // special was unset and the node kept (c:3851-3852).
9349 let f = pm.node.flags as u32;
9350 if (f & crate::ported::zsh_h::PM_UNSET) != 0
9351 && (f & crate::ported::zsh_h::PM_DECLARED) == 0
9352 {
9353 return true;
9354 }
9355 }
9356 {
9357 // c:Src/module.c:1029-1052 checkaddparam — `if (pm->level ||
9358 // !(pm->node.flags & PM_AUTOLOAD))` is C's OWN test for "is
9359 // this node a blocker or the module's own placeholder": a
9360 // GLOBAL PM_AUTOLOAD node is the autoload STUB
9361 // `add_autoparam` planted (c:1222-1223 `setsparam(pnam,
9362 // module); pm->node.flags |= PM_AUTOLOAD` — its VALUE is the
9363 // owning module's name), and C replaces it with the real
9364 // special via `unsetparam_pm` (c:1051) + `createspecialhash`
9365 // (c:1068) the moment the module loads. Reading the name is
9366 // what triggers that: c:Src/params.c:563-585 loadparamnode
9367 // runs `ensurefeature(mn, "p:", nam)` and re-fetches the node.
9368 // So a stub NEVER makes the special unreachable — treating it
9369 // as a shadow left `${options}` reading the stub's own scalar
9370 // value ("zsh/parameter") and killed every magic-assoc read
9371 // for that name for the rest of the session. A LOCAL stub
9372 // (pm->level != 0) still blocks, exactly as c:1032 says.
9373 let f = pm.node.flags as u32;
9374 if pm.level == 0 && (f & crate::ported::zsh_h::PM_AUTOLOAD) != 0 {
9375 return false;
9376 }
9377 (f & crate::ported::zsh_h::PM_SPECIAL) == 0
9378 }
9379 })
9380}
9381
9382/// [`magic_special_shadowed`] AND the shadow is not itself a hash.
9383///
9384/// "No longer the magic row" is not the same as "no longer a hash". C
9385/// decides the subscript dispatch — and every whole-map read — from the
9386/// TYPE of the node paramtab actually returned:
9387/// c:Src/params.c:2270 `if (PM_TYPE(pm->node.flags) & (PM_ARRAY|PM_HASHED))`
9388/// c:Src/params.c:1597-1606 getarg —
9389/// if (ishash) {
9390/// HashTable ht = v->pm->gsu.h->getfn(v->pm);
9391/// ...
9392/// if (!(v->pm = (Param) ht->getnode(ht, s))) ...
9393/// So a shadow that IS itself PM_HASHED (`local -A commands`, or
9394/// `local -A +h commands` as in Completion/Zsh/Type/_command_names:70)
9395/// owns a table of its own and must be SERVED FROM IT, while a scalar or
9396/// array shadow (`local options`, `local -a options`) must fall through
9397/// to the non-hash arms.
9398///
9399/// Bailing on every shadowed magic name made the hashed shadow invisible
9400/// to each reader in turn: the keyed read (`$commands[fake]`), then
9401/// `${#commands}`, `${(k)commands}`, `${(kv)commands}` and
9402/// `${commands[(I)pat]}`. The values were in `paramtab_hashed_storage`
9403/// the whole time — `${commands[@]}` found them — only these guards
9404/// refused to look. Every dispatch site that means "the magic row is not
9405/// the visible binding, and there is no hash behind it either" asks
9406/// through here so the qualification cannot drift between them.
9407pub fn magic_special_shadowed_by_nonhash(name: &str) -> bool {
9408 magic_special_shadowed(name)
9409 && crate::ported::params::paramtab()
9410 .read()
9411 .ok()
9412 .and_then(|t| t.get(name).map(|pm| pm.node.flags as u32))
9413 // c:2270 — PM_TYPE decides; absent node ⇒ nothing to serve; c:2264-2266 — nor
9414 // does an unset, undeclared node (`zmodload zsh/parameter; unset functions`).
9415 .map_or(true, |f| {
9416 use crate::ported::zsh_h::{PM_DECLARED, PM_TYPE, PM_UNSET};
9417 PM_TYPE(f) != PM_HASHED || (f & (PM_UNSET | PM_DECLARED)) == PM_UNSET
9418 })
9419}
9420
9421pub fn partab_get(name: &str, key: &str) -> Option<String> {
9422 // C's paramtab lookup would already have found the shadowing local;
9423 // the split-table port needs the explicit check.
9424 if magic_special_shadowed(name) {
9425 return None;
9426 }
9427 mark_module_param_used(name);
9428 // c:Src/Modules/system.c:902,904 — `sysparams` and `errnos` are
9429 // bound by zsh/system's boot_/setup_ chain. Same for `mapfile`
9430 // from zsh/mapfile. Without explicit `zmodload`, these names
9431 // are unset in zsh; gate the PARTAB dispatch here so they
9432 // resolve via the empty-fallback path (matching ${sysparams[k]:-x}
9433 // taking the default). Bug #69 in docs/BUGS.md.
9434 if let Some(modname) = module_gated_partab_module(name) {
9435 if !crate::ported::module::MODULESTAB
9436 .lock()
9437 .unwrap()
9438 .is_loaded(modname)
9439 {
9440 return None;
9441 }
9442 }
9443 for entry in PARTAB.iter() {
9444 if entry.name == name {
9445 // c:Src/Modules/parameter.c — a row getfn (`getpmfunction`,
9446 // `getpmcommand`, `getpmoption`, …) answers a missing key with a
9447 // node carrying `PM_UNSET` (e.g. getfunction, parameter.c:449 `pm->node.flags |=
9448 // (PM_UNSET|PM_SPECIAL)`), which `IS_UNSET_VALUE` (params.c:479)
9449 // and `issetvar` (params.c:764-765) read as unset. Keep that
9450 // distinction: dropping the flag turned a miss into a set empty
9451 // value, so `[[ -v functions[nosuch] ]]` was true.
9452 return (entry.getfn)(std::ptr::null_mut(), key)
9453 .filter(|p| p.node.flags as u32 & crate::ported::zsh_h::PM_UNSET == 0)
9454 .and_then(|p| p.u_str);
9455 }
9456 }
9457 None
9458}
9459
9460/// Returns the owning module name for partab entries that are
9461/// bound by an explicit zmodload — `sysparams`/`errnos` from
9462/// zsh/system, `mapfile` from zsh/mapfile. Other partab entries
9463/// (aliases/commands/functions/...) are part of zsh/main and
9464/// always available.
9465fn module_gated_partab_module(name: &str) -> Option<&'static str> {
9466 match name {
9467 "sysparams" | "errnos" => Some("zsh/system"),
9468 "mapfile" => Some("zsh/mapfile"),
9469 "langinfo" => Some("zsh/langinfo"),
9470 ".zle.esc" | ".zle.sgr" => Some("zsh/hlgroup"),
9471 ".sh.match" => Some("zsh/ksh93"),
9472 _ => None,
9473 }
9474}
9475
9476/// Publish a value into a read-only special from shell-INTERNAL code.
9477///
9478/// C binds these params to C variables through a gsu vtable —
9479/// `compvarscalar_gsu` for `$QIPREFIX`/`$QISUFFIX`
9480/// (Src/Zle/complete.c:1308-1324), `keymap_gsu` for `$KEYMAP`
9481/// (Src/Zle/zle_params.c:151) — and the shell's own writes go straight
9482/// to that variable. PM_READONLY is only consulted on the ASSIGNMENT
9483/// path (`assignsparam`, Src/params.c), so the bit stops a user's
9484/// `QIPREFIX=x` without ever standing in the way of the completion
9485/// machinery's own publish.
9486///
9487/// zshrs keeps the value in the param itself, so the internal publish
9488/// has to step around the same gate explicitly: drop PM_READONLY,
9489/// assign through the canonical path, put the bit back.
9490pub fn set_readonly_special(name: &str, value: &str) {
9491 use crate::ported::zsh_h::PM_READONLY;
9492 let was_readonly = crate::ported::params::paramtab()
9493 .write()
9494 .ok()
9495 .and_then(|mut tab| {
9496 tab.get_mut(name).map(|pm| {
9497 let ro = (pm.node.flags & PM_READONLY as i32) != 0;
9498 pm.node.flags &= !(PM_READONLY as i32);
9499 ro
9500 })
9501 })
9502 .unwrap_or(false);
9503 let _ = crate::ported::params::setsparam(name, value);
9504 if was_readonly {
9505 if let Ok(mut tab) = crate::ported::params::paramtab().write() {
9506 if let Some(pm) = tab.get_mut(name) {
9507 pm.node.flags |= PM_READONLY as i32;
9508 }
9509 }
9510 }
9511}
9512
9513/// PM_ARRAY lookup for `${name}` / `${name[N]}` — walks
9514/// PARTAB_ARRAY and dispatches the whole-array getfn (Src/Modules/
9515/// parameter.c:2239-2291 ports). Returns `None` if name isn't a
9516/// known PM_ARRAY magic-assoc.
9517pub fn partab_array_get(name: &str) -> Option<Vec<String>> {
9518 // c:Src/params.c:1090-1115 createparam — see `partab_get`.
9519 if magic_special_shadowed(name) {
9520 return None;
9521 }
9522 mark_module_param_used(name);
9523 // Bug #69 — gate module-bound PARTAB names on the owning
9524 // module's MOD_LINKED && !MOD_UNLOAD state.
9525 if let Some(modname) = module_gated_partab_module(name) {
9526 if !crate::ported::module::MODULESTAB
9527 .lock()
9528 .unwrap()
9529 .is_loaded(modname)
9530 {
9531 return None;
9532 }
9533 }
9534 for entry in PARTAB_ARRAY.iter() {
9535 if entry.name == name {
9536 return Some((entry.getfn)(std::ptr::null_mut()));
9537 }
9538 }
9539 None
9540}
9541
9542/// Scan helper for `${(k)name}` — enumerates keys via canonical
9543/// scanfn, collected into Vec via SCAN_KEYS thread-local.
9544pub fn partab_scan_keys(name: &str) -> Option<Vec<String>> {
9545 // c:Src/params.c:1090-1115 createparam — see `partab_get`.
9546 if magic_special_shadowed(name) {
9547 return None;
9548 }
9549 mark_module_param_used(name);
9550 // Bug #69 — gate module-bound PARTAB names on the owning
9551 // module's MOD_LINKED && !MOD_UNLOAD state.
9552 if let Some(modname) = module_gated_partab_module(name) {
9553 if !crate::ported::module::MODULESTAB
9554 .lock()
9555 .unwrap()
9556 .is_loaded(modname)
9557 {
9558 return None;
9559 }
9560 }
9561 for entry in PARTAB.iter() {
9562 if entry.name == name {
9563 SCAN_KEYS.with(|k| k.borrow_mut().clear());
9564 // c:Src/Modules/parameter.c — a param-table ScanFunc receives
9565 // `&pm.node` of a fully populated `struct param`; the Rust side
9566 // models that as `ParamScanFunc = fn(¶m, i32)`.
9567 fn cb(pm: &crate::ported::zsh_h::param, _flags: i32) {
9568 SCAN_KEYS.with(|k| k.borrow_mut().push(pm.node.nam.clone()));
9569 }
9570 // c:Src/params.c:3138 — `paramvalarr(…, SCANPM_WANTKEYS)`: keys
9571 // only, so a scanfn need not materialize the value side.
9572 (entry.scanfn)(
9573 std::ptr::null_mut(),
9574 Some(cb),
9575 crate::ported::zsh_h::SCANPM_WANTKEYS as i32,
9576 );
9577 return Some(SCAN_KEYS.with(|k| k.borrow().clone()));
9578 }
9579 }
9580 None
9581}
9582/// Populate paramtab with PM_SPECIAL placeholder Params for every
9583/// PARTAB / PARTAB_ARRAY entry — Rust-only init helper, no direct
9584/// C counterpart (closest is `handlefeatures` walking `partab[]`
9585/// in `Src/Modules/parameter.c:2341` boot/enables chain).
9586///
9587/// Each magic-assoc name gets a Param with `entry.flags | PM_SPECIAL`.
9588/// Value reads still route through `partab_get` / `partab_array_get`;
9589/// having the Param in paramtab makes `paramtab.get(name)` return
9590/// Some(Param) so `${+name}` / `${(t)name}` / `typeset -p name` see
9591/// the entry. Without this, those reads returned empty for every
9592/// magic-assoc (aliases, commands, functions, etc.).
9593///
9594/// Called from ShellExecutor::new() since zshrs's bin entry skips
9595/// the canonical module-bootstrap chain.
9596pub fn init_partab_params() {
9597 use crate::ported::modules::parameter::{PARTAB, PARTAB_ARRAY};
9598 use crate::ported::zsh_h::{
9599 hashnode, param, Param, PM_HIDE, PM_HIDEVAL, PM_READONLY, PM_SPECIAL,
9600 };
9601 let mut tab = match paramtab().write() {
9602 Ok(t) => t,
9603 Err(_) => return,
9604 };
9605 // c:Src/zsh.h SPECIALPMDEF macro: `flags | PM_SPECIAL | PM_HIDE |
9606 // PM_HIDEVAL`. All magic-assoc/array params get HIDE+HIDEVAL added
9607 // by the macro itself.
9608 //
9609 // PM_READONLY is preserved on the stub for params that legitimately
9610 // need user-write protection (reswords, dis_reswords, patchars,
9611 // dis_patchars — all compute via getfn and have no legitimate
9612 // internal-write path). Other specials that DO have internal-write
9613 // paths (e.g. funcstack from function-call tracking) get the bit
9614 // stripped so the runtime can mutate their u_arr. Bug #374.
9615 // `parameters` is computed entirely by getpmparameter and has no
9616 // internal-write path either (zsh: PM_READONLY_SPECIAL, c:2287), so it
9617 // keeps the bit — `${parameters[parameters]}` reads
9618 // `association-readonly-hide-hideval-special` in zsh.
9619 // The remaining names below are the rest of C's PM_READONLY_SPECIAL
9620 // rows whose `partab[]` entry has a NULL gsu (c:2237/2243/2255/2265/
9621 // :2272/2276-2280/2284/2296-2298 + Src/Zle/zleparameter.c:133): they
9622 // are computed purely by their getfn/scanfn, so there is nothing for
9623 // the runtime to write and the bit is safe to keep. Without them
9624 // `${(t)builtins}` and friends reported
9625 // `association-hide-hideval-special` where zsh reports
9626 // `association-readonly-hide-hideval-special`.
9627 let user_protected: &[&str] = &[
9628 "parameters",
9629 "reswords",
9630 "dis_reswords",
9631 "patchars",
9632 "dis_patchars",
9633 "historywords",
9634 "errnos",
9635 "keymaps",
9636 "builtins", // c:2237
9637 "dis_builtins", // c:2243
9638 "functions_source", // c:2265
9639 "dis_functions_source", // c:2247
9640 "history", // c:2272
9641 "jobdirs", // c:2276
9642 "jobstates", // c:2278
9643 "jobtexts", // c:2280
9644 "modules", // c:2284
9645 "userdirs", // c:2296
9646 "usergroups", // c:2297
9647 "widgets", // c:Src/Zle/zleparameter.c:133
9648 // c:2279-2280 — `SPECIALPMDEF("funcstack", PM_ARRAY|
9649 // PM_READONLY_SPECIAL, &funcstack_gsu, NULL, NULL)`. The bit was
9650 // being stripped here on the theory that the runtime writes
9651 // `funcstack`'s `u_arr`; it does not — `funcstackgetfn`
9652 // (PARTAB_ARRAY, parameter.rs:4726-4732) computes the value from
9653 // the `FUNCSTACK` global on every read and the row's `setfn` is
9654 // `None`, so there is nothing to protect against. Without the bit
9655 // `${(t)funcstack}` read `array-hide-hideval-special` where zsh
9656 // reads `array-readonly-hide-hideval-special`, which put it in the
9657 // wrong `_parameters -g '^*(readonly|association)*'` bucket and
9658 // added one candidate zsh does not offer.
9659 "funcstack", // c:2279
9660 // Same argument as `funcstack` above, for the three sibling trace
9661 // arrays: `SPECIALPMDEF(..., PM_ARRAY|PM_READONLY_SPECIAL, ...)` in C
9662 // and `setfn: None` in PARTAB_ARRAY (parameter.rs:4717/4725/4741), so
9663 // they are getfn-computed with no internal-write path to protect.
9664 "funcfiletrace", // c:2275
9665 "funcsourcetrace", // c:2277
9666 "functrace", // c:2285
9667 // c:Src/Modules/termcap.c:312 / Src/Modules/terminfo.c:305 —
9668 // `SPECIALPMDEF("termcap", PM_READONLY, NULL, gettermcap, scantermcap)`
9669 // and the terminfo twin: NULL gsu, value produced entirely by the
9670 // getnode/scan fns, so the readonly bit has nothing to fight.
9671 "termcap", // c:Src/Modules/termcap.c:312
9672 "terminfo", // c:Src/Modules/terminfo.c:305
9673 // c:Src/Builtins/sched.c:382 — `SPECIALPMDEF(
9674 // "zsh_scheduled_events", PM_ARRAY|PM_READONLY, &sched_gsu,
9675 // NULL, NULL)`. Same shape as `funcstack` above: `schedgetfn`
9676 // (sched.rs:582) walks the schedcmds list on every read and the
9677 // PARTAB_ARRAY row's `setfn` is `None`, so no internal write
9678 // needs the bit cleared. `sched`/`sched -N` mutate the list,
9679 // never the param.
9680 "zsh_scheduled_events", // c:Src/Builtins/sched.c:382
9681 ];
9682 let mk_pm = |name: &str, flags: i32| -> Param {
9683 let keep_readonly = user_protected.contains(&name);
9684 let pre_readonly_mask = if keep_readonly {
9685 !0i32
9686 } else {
9687 !(PM_READONLY as i32)
9688 };
9689 Box::new(param {
9690 node: hashnode {
9691 next: None,
9692 nam: name.to_string(),
9693 flags: (flags & pre_readonly_mask)
9694 | PM_SPECIAL as i32
9695 | PM_HIDE as i32
9696 | PM_HIDEVAL as i32,
9697 },
9698 u_data: 0,
9699 u_tied: None,
9700 u_arr: None,
9701 u_str: None,
9702 u_val: 0,
9703 u_dval: 0.0,
9704 u_hash: None,
9705 gsu_s: None,
9706 gsu_i: None,
9707 gsu_f: None,
9708 gsu_a: None,
9709 gsu_h: None,
9710 base: 0,
9711 width: 0,
9712 env: None,
9713 ename: None,
9714 old: None,
9715 level: 0,
9716 })
9717 };
9718 // c:Src/Modules/system.c:902,904 + Src/Modules/mapfile.c — these
9719 // params are provided by modules that real zsh requires explicit
9720 // `zmodload` for. Seeding them unconditionally makes
9721 // `${+sysparams}` return 1 by default (bug #69 in docs/BUGS.md),
9722 // diverging from zsh which returns 0 until the user runs
9723 // `zmodload zsh/system`. Skip here; `seed_partab_param` below adds
9724 // them on demand from the module's load path.
9725 let module_gated: &[&str] = &[
9726 "sysparams", // zsh/system
9727 "errnos", // zsh/system
9728 "mapfile", // zsh/mapfile
9729 "langinfo", // zsh/langinfo
9730 ".zle.esc", // zsh/hlgroup
9731 ".zle.sgr", // zsh/hlgroup
9732 ".sh.match", // zsh/ksh93
9733 ];
9734 // c:Src/module.c:1065 `addparamdef` — `checkaddparam` (c:1026) finds
9735 // the PM_AUTOLOAD stub `init_bltinmods` planted, calls
9736 // `unsetparam_pm(pm, 0, 1)` which UNLINKS the node (c:1052), and only
9737 // then does `createparam` re-add it — so the real param takes a FRESH
9738 // chain slot, it does not inherit the stub's. `hashtable_nodes::
9739 // insert` is `addhashnode2` (Src/hashtable.c:168), which replaces an
9740 // existing key IN PLACE (c:187-203) and would pin the special to the
9741 // stub's slot; remove first to reproduce C. Visible in
9742 // `${(k)parameters}`: without the remove, `dis_reswords` and
9743 // `usergroups` came out one position off from `zsh -f`.
9744 for entry in PARTAB.iter() {
9745 if module_gated.contains(&entry.name) {
9746 continue;
9747 }
9748 tab.remove(entry.name); // c:1052 unsetparam_pm
9749 tab.insert(entry.name.to_string(), mk_pm(entry.name, entry.flags));
9750 }
9751 for entry in PARTAB_ARRAY.iter() {
9752 if module_gated.contains(&entry.name) {
9753 continue;
9754 }
9755 tab.remove(entry.name); // c:1052 unsetparam_pm
9756 tab.insert(entry.name.to_string(), mk_pm(entry.name, entry.flags));
9757 }
9758 // See `PARTAB_SEEDED` — every magic row now has its paramtab node,
9759 // so from here on a MISSING node is a real "no binding" answer.
9760 PARTAB_SEEDED.store(true, std::sync::atomic::Ordering::Release);
9761}
9762
9763/// !!! WARNING: RUST-ONLY HELPER !!!
9764///
9765/// True once [`init_partab_params`] has finished planting a paramtab
9766/// node for every `PARTAB` / `PARTAB_ARRAY` row.
9767///
9768/// No C counterpart BY CONSTRUCTION. In C the magic rows only ENTER
9769/// `paramtab` when `zsh/parameter` boots (`handlefeatures` →
9770/// `addparamdef` → `createspecialhash`, `Src/module.c:1065`), and before
9771/// that the name still resolves — to the `PM_AUTOLOAD` stub
9772/// `init_bltinmods` planted (`Src/module.c:1218-1223`). Either way C's
9773/// `paramtab->getnode(name)` answers, so C never has to distinguish
9774/// "not seeded yet" from "unset". zshrs seeds the rows from
9775/// `ShellExecutor::new` (vm_helper.rs:2566) and matches `PARTAB` BY NAME
9776/// out of a separate static table, so a magic read that runs BEFORE that
9777/// seeding would see an absent node. `magic_special_shadowed` reads
9778/// absence as "unset" (C: `getnode` → NULL → `fetchvalue` NULL,
9779/// `Src/params.c:2264-2266`), which is only a valid inference once the
9780/// seeding has run; this flag is that precondition.
9781static PARTAB_SEEDED: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
9782
9783/// Insert a single PARTAB / PARTAB_ARRAY entry into paramtab. Called
9784/// from `zmodload <module>` once the module's boot completes, so that
9785/// `${+sysparams}` (etc.) flip from 0 → 1 only after explicit load.
9786/// No direct C counterpart — the C path runs through the module's
9787/// `setup_/boot_` chain which adds the SPECIALPMDEF entry via the
9788/// general hashtable machinery. Bug #69 in docs/BUGS.md.
9789pub fn seed_partab_param(name: &str) {
9790 use crate::ported::modules::parameter::{PARTAB, PARTAB_ARRAY};
9791 use crate::ported::zsh_h::{hashnode, param, PM_HIDE, PM_HIDEVAL, PM_READONLY, PM_SPECIAL};
9792 let mut tab = match crate::ported::params::paramtab().write() {
9793 Ok(t) => t,
9794 Err(_) => return,
9795 };
9796 // c:Src/module.c:1026-1052 `checkaddparam` — the node already present may
9797 // be the PM_AUTOLOAD STUB that `add_autoparam` planted (c:1218-1223,
9798 // ported at src/ported/module.rs), not a seeded special: forcing
9799 // MODULESTAB registers `p:builtins` and friends as autoload scalars. C
9800 // does NOT treat that as "already added" — `unsetparam_pm(pm, 0, 1)`
9801 // UNLINKS the stub (c:1052) and only then does `createparam` install the
9802 // real special (c:1065). The bulk path here already models that
9803 // (`tab.remove(entry.name); // c:1052 unsetparam_pm`); the single-name
9804 // sibling omitted it, so `builtins` stayed PM_SCALAR and `gethkparam`'s
9805 // PM_TYPE == PM_HASHED test fell through to None.
9806 //
9807 // A genuine user parameter shadowing the name carries no PM_AUTOLOAD, so
9808 // it still short-circuits exactly as before.
9809 if tab
9810 .get(name)
9811 .is_some_and(|pm| (pm.node.flags as u32 & crate::ported::zsh_h::PM_AUTOLOAD) == 0)
9812 {
9813 return; // a real special is already seeded
9814 }
9815 let flags = PARTAB
9816 .iter()
9817 .find(|e| e.name == name)
9818 .map(|e| e.flags)
9819 .or_else(|| {
9820 PARTAB_ARRAY
9821 .iter()
9822 .find(|e| e.name == name)
9823 .map(|e| e.flags)
9824 });
9825 let Some(flags) = flags else {
9826 return;
9827 };
9828 // c:1052 `unsetparam_pm(pm, 0, 1)` — unlink the autoload stub, but only
9829 // once we know a real special is going in to replace it. Doing it before
9830 // the PARTAB lookup above would destroy an existing node for any name
9831 // that is NOT a known special and then return, which is strictly worse
9832 // than the early-return it replaced.
9833 tab.remove(name);
9834 let pm = Box::new(param {
9835 node: hashnode {
9836 next: None,
9837 nam: name.to_string(),
9838 // Keep C's PM_READONLY. `init_partab_params` strips it from
9839 // rows the RUNTIME writes internally (funcstack pushes and
9840 // friends) and keeps it on the getfn/scanfn-computed rows —
9841 // see its `user_protected` list. Every name reaching THIS
9842 // seeder is a zmodload-gated row
9843 // (`module_gated_params_for`), and all of them are the
9844 // computed kind: `SPECIALPMDEF("sysparams", PM_READONLY,
9845 // NULL, getpmsysparams, scanpmsysparams)`
9846 // (Src/Modules/system.c:906), `errnos` (c:904), `langinfo`
9847 // (Src/Modules/langinfo.c:455); `mapfile` carries flags 0 in
9848 // C so it is unaffected either way. Stripping the bit made
9849 // `${(t)sysparams}` read `association-hide-hideval-special`
9850 // against zsh's `association-readonly-hide-hideval-special`,
9851 // and let `unset sysparams` succeed where zsh rejects with
9852 // `read-only variable: sysparams`.
9853 flags: flags | PM_SPECIAL as i32 | PM_HIDE as i32 | PM_HIDEVAL as i32,
9854 },
9855 u_data: 0,
9856 u_tied: None,
9857 u_arr: None,
9858 u_str: None,
9859 u_val: 0,
9860 u_dval: 0.0,
9861 u_hash: None,
9862 gsu_s: None,
9863 gsu_i: None,
9864 gsu_f: None,
9865 gsu_a: None,
9866 gsu_h: None,
9867 base: 0,
9868 width: 0,
9869 env: None,
9870 ename: None,
9871 old: None,
9872 level: 0,
9873 });
9874 tab.insert(name.to_string(), pm);
9875}
9876
9877/// Default autoloadable parameters: name → owning module. Port of the
9878/// `autofeatures` `p:` rows in Src/Modules/parameter.mdd, watch.mdd,
9879/// termcap.mdd, terminfo.mdd, Src/Zle/zleparameter.mdd and
9880/// Src/Builtins/sched.mdd, registered at startup through
9881/// `setautofeatures` → `add_autoparam` (Src/module.c:1198-1229): each
9882/// name becomes a scalar paramtab stub whose VALUE is the module name,
9883/// flagged PM_AUTOLOAD (module.c:1218-1219). Matches `zmodload -ap`
9884/// output of the reference zsh build.
9885pub const AUTOLOAD_PARAMS: &[(&str, &str)] = &[
9886 // Src/Modules/watch.mdd:5 autofeatures
9887 ("WATCH", "zsh/watch"),
9888 ("watch", "zsh/watch"),
9889 // Src/Modules/parameter.mdd:5 autofeatures
9890 ("aliases", "zsh/parameter"),
9891 ("builtins", "zsh/parameter"),
9892 ("commands", "zsh/parameter"),
9893 ("dirstack", "zsh/parameter"),
9894 ("dis_aliases", "zsh/parameter"),
9895 ("dis_builtins", "zsh/parameter"),
9896 ("dis_functions", "zsh/parameter"),
9897 ("dis_functions_source", "zsh/parameter"),
9898 ("dis_galiases", "zsh/parameter"),
9899 ("dis_patchars", "zsh/parameter"),
9900 ("dis_reswords", "zsh/parameter"),
9901 ("dis_saliases", "zsh/parameter"),
9902 ("funcfiletrace", "zsh/parameter"),
9903 ("funcsourcetrace", "zsh/parameter"),
9904 ("funcstack", "zsh/parameter"),
9905 ("functions", "zsh/parameter"),
9906 ("functions_source", "zsh/parameter"),
9907 ("functrace", "zsh/parameter"),
9908 ("galiases", "zsh/parameter"),
9909 ("history", "zsh/parameter"),
9910 ("historywords", "zsh/parameter"),
9911 ("jobdirs", "zsh/parameter"),
9912 ("jobstates", "zsh/parameter"),
9913 ("jobtexts", "zsh/parameter"),
9914 ("modules", "zsh/parameter"),
9915 ("nameddirs", "zsh/parameter"),
9916 ("options", "zsh/parameter"),
9917 ("parameters", "zsh/parameter"),
9918 ("patchars", "zsh/parameter"),
9919 ("reswords", "zsh/parameter"),
9920 ("saliases", "zsh/parameter"),
9921 ("userdirs", "zsh/parameter"),
9922 ("usergroups", "zsh/parameter"),
9923 // Src/Zle/zleparameter.mdd:5 autofeatures
9924 ("keymaps", "zsh/zleparameter"),
9925 ("widgets", "zsh/zleparameter"),
9926 // Src/Modules/termcap.mdd:5 / terminfo.mdd:5 autofeatures
9927 ("termcap", "zsh/termcap"),
9928 ("terminfo", "zsh/terminfo"),
9929 // Src/Builtins/sched.mdd:5 autofeatures
9930 ("zsh_scheduled_events", "zsh/sched"),
9931];
9932
9933/// Autoload stubs whose owning module is NOT loaded — the rows zsh's
9934/// `typeset` listings print as `undefined NAME` (printparamnode's
9935/// PM_AUTOLOAD pmtypes row, Src/params.c:6011 + the PM_AUTOLOAD
9936/// NAMEONLY arm at Src/params.c:6146-6155). Once a module loads, its
9937/// stubs drop out and the real params list instead.
9938pub fn autoload_param_stubs() -> Vec<(&'static str, &'static str)> {
9939 use crate::ported::zsh_h::{MOD_INIT_B, MOD_UNLOAD};
9940 let tab = crate::ported::module::MODULESTAB.lock().unwrap();
9941 AUTOLOAD_PARAMS
9942 .iter()
9943 .copied()
9944 .filter(|(_, m)| {
9945 // "Boot ran" is MOD_INIT_B && !MOD_UNLOAD (the criterion
9946 // printmodulenode uses, src/ported/module.rs:246 — C's
9947 // `m->u.handle` union check at Src/module.c:218-241).
9948 // modulestab::is_loaded checks MOD_LINKED which
9949 // register_builtin_modules pre-seeds for EVERY compiled-in
9950 // module, so it would report zsh/parameter "loaded" in a
9951 // fresh `zsh -f` where real zsh still shows the stubs.
9952 !tab.modules.get(*m).is_some_and(|md| {
9953 (md.node.flags & MOD_INIT_B) != 0 && (md.node.flags & MOD_UNLOAD) == 0
9954 })
9955 })
9956 .collect()
9957}
9958
9959/// Names provided by `zsh/system` / `zsh/mapfile` etc. that are
9960/// gated on explicit `zmodload`. Used by the bin_zmodload path to
9961/// re-seed paramtab after the module's boot completes.
9962pub fn module_gated_params_for(module: &str) -> &'static [&'static str] {
9963 match module {
9964 "zsh/system" => &["sysparams", "errnos"],
9965 "zsh/mapfile" => &["mapfile"],
9966 "zsh/langinfo" => &["langinfo"],
9967 "zsh/hlgroup" => &[".zle.esc", ".zle.sgr"],
9968 "zsh/ksh93" => &[".sh.match"],
9969 _ => &[],
9970 }
9971}
9972impl ShellExecutor {
9973 /// `enter_posix_mode` — see implementation.
9974 pub fn enter_posix_mode(&mut self) {
9975 self.posix_mode = true;
9976 self.plugin_cache = None;
9977 self.compsys_cache = std::cell::OnceCell::new();
9978 self.compinit_pending = None;
9979 self.worker_pool = std::sync::Arc::new(crate::worker::WorkerPool::new(1));
9980 // Direct call to the canonical `emulate()` port
9981 // (Src/options.c:533) — `-R` semantics = fully=true.
9982 // bin_emulate goes through dispatch_builtin which needs an
9983 // ExecutorContext that isn't set up yet at apply_cli_flags
9984 // time; the underlying emulate() doesn't need one.
9985 crate::ported::options::emulate("sh", true);
9986 }
9987 /// `enter_ksh_mode` — see implementation.
9988 pub fn enter_ksh_mode(&mut self) {
9989 self.plugin_cache = None;
9990 self.compsys_cache = std::cell::OnceCell::new();
9991 self.compinit_pending = None;
9992 self.worker_pool = std::sync::Arc::new(crate::worker::WorkerPool::new(1));
9993 crate::ported::options::emulate("ksh", true);
9994 }
9995 /// `enter_dash_mode` — strict-dash (Debian Almquist Shell) runtime.
9996 /// Same executor setup as [`enter_posix_mode`] (dash IS `sh` for every
9997 /// option), but calls `emulate("dash")` so the Rust-only DASH_STRICT
9998 /// flag is raised (and NOT cleared, as `emulate("sh")` would). See
9999 /// `src/extensions/dash_mode.rs`.
10000 pub fn enter_dash_mode(&mut self) {
10001 self.posix_mode = true;
10002 self.plugin_cache = None;
10003 self.compsys_cache = std::cell::OnceCell::new();
10004 self.compinit_pending = None;
10005 self.worker_pool = std::sync::Arc::new(crate::worker::WorkerPool::new(1));
10006 crate::ported::options::emulate("dash", true);
10007 }
10008}
10009
10010/// Thin (text, pattern) → bool wrapper over the canonical
10011/// `patcompile()` + `pattry()` pair from `Src/pattern.c`. Argument
10012/// order is flipped so callers read naturally. Lives in vm_helper.rs
10013/// (non-port file) as the public convenience entry for extensions
10014/// and the VM bridge; `src/ported/*` files inline the compile+match
10015/// idiom directly to preserve PORT.md Rule 1 faithfulness.
10016pub fn glob_match_static(s: &str, pattern: &str) -> bool {
10017 let Some(prog) = patcompile(
10018 &{
10019 let mut __pat_tok = (pattern).to_string();
10020 crate::ported::glob::tokenize(&mut __pat_tok);
10021 __pat_tok
10022 },
10023 PAT_HEAPDUP as i32,
10024 None,
10025 ) else {
10026 return false;
10027 };
10028 // c:Src/pattern.c:2570-2621 — `else if (prog->patnpar && !(patflags &
10029 // PAT_FILE))`: when the caller passes NO nump/begp/endp, `pattryrefs`
10030 // ITSELF publishes $match / $mbegin / $mend. That arm is ported in
10031 // pattern.rs, so this layer must not re-derive them from begp/endp.
10032 //
10033 // Re-deriving required compensating for the EXCLUSIVE end index
10034 // `pattryrefs` used to return, and the compensation was wrong twice over:
10035 // * it would double-correct the c:2562-2564 `- 1` now applied there, and
10036 // collide with the `endp[i] < 0` unset-group sentinel — an empty
10037 // capture at offset 0 reports (0, -1) and was misread as an UNMATCHED
10038 // alternation branch;
10039 // * `saturating_sub(1)` clamped at 0, so under KSHARRAYS an empty capture
10040 // at offset 0 gave `mend=0` where C computes `0 + 0 + 0 - 1` = -1.
10041 // Measured: `setopt ksharrays; [[ abc = (#b)(x#)abc ]]` → zsh mend=-1,
10042 // zshrs mend=0, while the substitution path (which already uses the
10043 // c:2570-2621 arm) printed -1 correctly.
10044 let matched = pattry(&prog, s);
10045 // $MATCH / $MBEGIN / $MEND are set by the MATCHER (pattern.rs, c:2526),
10046 // which is where C decides it — gated on the GLOBAL patglobflags so a later
10047 // `(#M)` can turn GF_MATCHREF back off (c:1099-1100).
10048 //
10049 // This layer used to re-do it with `pattern.contains("(#m)")`, which can
10050 // only ever answer "on": it re-set $MATCH after the matcher had correctly
10051 // declined to, so `(#m)(#M)a*` reported a match string where zsh leaves it
10052 // unset. Wrong mechanism (a substring test cannot see which flag came last)
10053 // and wrong layer (the matcher already has the compiled flags).
10054 matched
10055}
10056
10057pub use crate::ported::lex::untokenize_ztokens;
10058
10059pub use crate::ported::utils::unmetafy_str;
10060
10061pub use crate::ported::utils::zsh_errno_msg;
10062
10063// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
10064// PM_NAMEREF bridge helpers (typeset -n / named references).
10065//
10066// Rust-only adapters around the canonical C nameref machinery in
10067// Src/params.c (resolve_nameref_rec c:6332, setscope c:6382,
10068// upscope c:6455) and Src/builtin.c (bin_typeset nameref arm
10069// c:3117-3150). zshrs's paramtab is a name-keyed HashMap handing
10070// out clones, so the chain walk operates by NAME against the live
10071// table instead of by Param pointer — same hop rule, same loop
10072// detection, same upscope old-chain walk. The ported fns in
10073// params.rs/builtin.rs call into these at the exact C deref points
10074// (getparamnode c:570-575, getvalue/fetchvalue c:2247-2270,
10075// assignsparam c:3252/3258, assignaparam c:3392-3398, bin_unset
10076// c:3939-3951, typeset_single c:2032-2050).
10077// ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
10078
10079pub use crate::ported::params::*;
10080
10081/// True for an `fpath` entry that is a host zsh **distribution's own**
10082/// function tree — the copy of `Completion/**` + `Functions/**` that
10083/// `make install` flattens into the zsh package.
10084///
10085/// c:Src/init.c:1132-1143 — zsh's `setupvals` seeds `fpath` with
10086/// `FIXED_FPATH_DIR`, `SITEFPATH_DIR`, then
10087/// `<prefix>/share/zsh/<version>/functions`. zshrs keeps the first two and
10088/// drops the last, from the compiled-in default and from an inherited
10089/// `FPATH` alike. This is startup construction only: like zsh, a later
10090/// shell-level `fpath=( … )` stores exactly what was assigned.
10091///
10092/// The distribution tree goes because zshrs ships its own: `vendor/zsh` is
10093/// packed into the binary by `build.rs` and materialised into
10094/// `~/.zshrs/functions`, which takes the host tree's index on `fpath`. A host tree is not a
10095/// fallback for that — it is a second, differently-versioned copy of the
10096/// same `compinit`, `_git` and `_describe`, and letting it linger means a
10097/// Homebrew zsh upgrade can change how zshrs completes.
10098///
10099/// `share/zsh/site-functions` STAYS. Nothing in it comes from zsh: it is
10100/// where third-party formulae install their completions (`_brew`,
10101/// `_docker`, `_kubectl`, `_gh` …), the bundle has no copy of them, and
10102/// dropping the directory would silently disable completion for every
10103/// tool installed through a package manager.
10104///
10105/// The two shapes to reject differ in depth — Homebrew's Cellar layout has
10106/// no version component under `share/zsh` — so the test is a `share`
10107/// component followed by `zsh`, plus a final component of exactly
10108/// `functions`:
10109/// /usr/share/zsh/5.9/functions drop
10110/// /opt/homebrew/Cellar/zsh/5.9.2/share/zsh/functions drop
10111/// /opt/homebrew/share/zsh/site-functions keep
10112/// ~/.zinit/plugins/…/src keep
10113pub(crate) fn is_host_zsh_function_tree(p: &Path) -> bool {
10114 if p.file_name() != Some(OsStr::new("functions")) {
10115 return false;
10116 }
10117 let mut comps = p.components().map(|c| c.as_os_str());
10118 while let Some(c) = comps.next() {
10119 if c == "share" && comps.clone().next() == Some(OsStr::new("zsh")) {
10120 return true;
10121 }
10122 }
10123 false
10124}
10125
10126/// Default `fpath` when `FPATH` is absent from the environment.
10127///
10128/// c:Src/init.c:1143 — `SITEFPATH_DIR`, listed by zsh even when it does
10129/// not exist on disk. zshrs adds the same directory under whichever
10130/// prefixes are actually present, because that is where package managers
10131/// put third-party completions and the bundled tree has none of them.
10132///
10133/// The versioned `<prefix>/share/zsh/<version>/functions` that C also
10134/// seeds here is deliberately NOT included — see
10135/// [`is_host_zsh_function_tree`]. `~/.zshrs/functions` supplies it, and is
10136/// appended by both constructors.
10137///
10138/// The prefix list is the set of places a package manager puts
10139/// `share/zsh/site-functions` on the platforms zshrs targets. `/usr/local`
10140/// and `/usr` cover Linux distributions and a from-source install;
10141/// `/opt/homebrew` is Homebrew on Apple silicon, `/usr/local` doubles as
10142/// Homebrew on Intel macOS, and `/home/linuxbrew/.linuxbrew` is
10143/// Homebrew's Linux prefix — which is NOT `/opt/homebrew`, so a Linux box
10144/// with brew-installed completions found none of them before it was
10145/// listed. Only directories that exist are added, so naming a prefix
10146/// costs nothing on a machine that lacks it.
10147fn default_fpath() -> Vec<PathBuf> {
10148 let mut out: Vec<PathBuf> = vec![PathBuf::from("/usr/local/share/zsh/site-functions")];
10149 for pfx in [
10150 "/usr/local",
10151 "/opt/homebrew",
10152 "/home/linuxbrew/.linuxbrew",
10153 "/usr",
10154 ] {
10155 let site = PathBuf::from(format!("{pfx}/share/zsh/site-functions"));
10156 if site.is_dir() && !out.contains(&site) {
10157 out.push(site);
10158 }
10159 }
10160 out
10161}