Skip to main content

aft_base/
effective_path.rs

1//! Process-wide PATH enrichment for children spawned by AFT.
2//!
3//! Daemon launches can inherit a system-only PATH that misses the user's package
4//! managers and version-manager shims. AFT initializes this module before any
5//! helper threads start so later subprocesses inherit the same PATH a login
6//! terminal would provide.
7
8use std::ffi::{OsStr, OsString};
9use std::sync::OnceLock;
10
11#[cfg(unix)]
12use std::collections::HashSet;
13#[cfg(unix)]
14use std::fs::File;
15#[cfg(unix)]
16use std::io::Read;
17#[cfg(unix)]
18use std::path::{Path, PathBuf};
19#[cfg(unix)]
20use std::process::{Child, Command, Stdio};
21#[cfg(unix)]
22use std::time::{Duration, Instant, SystemTime, UNIX_EPOCH};
23
24#[cfg(unix)]
25use std::os::unix::ffi::{OsStrExt, OsStringExt};
26#[cfg(unix)]
27use std::os::unix::fs::MetadataExt;
28#[cfg(unix)]
29use std::os::unix::io::AsRawFd;
30#[cfg(unix)]
31use std::os::unix::process::CommandExt;
32
33#[cfg(unix)]
34use serde::{Deserialize, Serialize};
35
36#[cfg(not(unix))]
37static EFFECTIVE_PATH: OnceLock<OsString> = OnceLock::new();
38
39#[cfg(unix)]
40#[derive(Clone, Debug)]
41struct PathState {
42    path: &'static OsStr,
43    source: ProbeSource,
44    shell: String,
45    elapsed: Duration,
46    cache_path: PathBuf,
47    refresh_started: bool,
48    log_emitted: bool,
49}
50
51#[cfg(unix)]
52#[derive(Clone, Copy, Debug, Eq, PartialEq)]
53enum ProbeSource {
54    Cache,
55    Probe,
56    Timeout,
57}
58
59#[cfg(unix)]
60static EFFECTIVE_PATH_STATE: std::sync::Mutex<Option<PathState>> = std::sync::Mutex::new(None);
61
62#[cfg(unix)]
63const LOGIN_SHELL_PATH_PROBE_TIMEOUT: Duration = Duration::from_secs(3);
64#[cfg(unix)]
65const LOGIN_SHELL_PATH_PROBE_TOTAL_BUDGET: Duration = Duration::from_secs(4);
66#[cfg(unix)]
67const SPAWN_BUSY_RETRY_COUNT: usize = 3;
68#[cfg(unix)]
69const SPAWN_BUSY_RETRY_DELAY: Duration = Duration::from_millis(10);
70#[cfg(unix)]
71const EFFECTIVE_PATH_CACHE_SCHEMA: u32 = 1;
72
73/// Compute and export AFT's process PATH.
74///
75/// Call this during process startup, before AFT starts worker threads or async
76/// executors. Mutating process environment variables while other threads may be
77/// reading them is not safe on Unix, so later code should read the cached value
78/// with [`effective_path`] instead of calling this initializer again.
79pub fn initialize_process_path() -> &'static OsStr {
80    let path = effective_path();
81
82    #[cfg(unix)]
83    {
84        if path != OsStr::new("") && std::env::var_os("PATH").as_deref() != Some(path) {
85            std::env::set_var("PATH", path);
86        }
87        spawn_cached_path_refresh();
88    }
89
90    path
91}
92
93/// Emit the single startup record after logging has been initialized.
94///
95/// PATH discovery runs before the logger and before threads, so this is split
96/// from [`initialize_process_path`] rather than delaying the environment write.
97pub fn log_startup_probe_result() {
98    #[cfg(unix)]
99    {
100        let mut guard = EFFECTIVE_PATH_STATE
101            .lock()
102            .unwrap_or_else(|error| error.into_inner());
103        let Some(state) = guard.as_mut() else {
104            return;
105        };
106        if state.log_emitted {
107            return;
108        }
109        state.log_emitted = true;
110        let source = match state.source {
111            ProbeSource::Cache => "cache",
112            ProbeSource::Probe => "probe",
113            ProbeSource::Timeout => "timeout",
114        };
115        log::info!(
116            "login-shell PATH probe: source={source} shell={} elapsed_ms={}",
117            state.shell,
118            state.elapsed.as_millis()
119        );
120    }
121}
122
123/// Configure the child environment before resolving its executable with [`CommandBuilder::build`].
124#[cfg(unix)]
125pub fn new_command<S: AsRef<OsStr>>(program: S) -> CommandBuilder {
126    command_with_path(program.as_ref(), effective_path())
127}
128
129#[cfg(unix)]
130fn command_with_path(program: &OsStr, path: &OsStr) -> CommandBuilder {
131    let mut builder = CommandBuilder::new(program);
132    // Startup exports the effective PATH before threads start. Reapplying even
133    // the same value marks PATH as changed in Rust's Command and disables
134    // posix_spawn for bare executable names, forcing a costly daemon fork.
135    if std::env::var_os("PATH").as_deref() != Some(path) {
136        builder.env("PATH", path);
137    }
138    builder
139}
140
141/// The environment-only construction phase of a child command.
142///
143/// Apply all environment overrides here, then call [`Self::build`] before
144/// configuring arguments, working directory, I/O, or process-group settings.
145/// Resolving sooner would ignore a configured PATH that selects another tool.
146pub struct CommandBuilder {
147    environment: std::process::Command,
148    clear_environment: bool,
149}
150
151impl CommandBuilder {
152    fn new(program: &OsStr) -> Self {
153        Self {
154            environment: std::process::Command::new(program),
155            clear_environment: false,
156        }
157    }
158
159    pub fn env<K: AsRef<OsStr>, V: AsRef<OsStr>>(&mut self, key: K, value: V) -> &mut Self {
160        self.environment.env(key, value);
161        self
162    }
163
164    pub fn envs<I, K, V>(&mut self, vars: I) -> &mut Self
165    where
166        I: IntoIterator<Item = (K, V)>,
167        K: AsRef<OsStr>,
168        V: AsRef<OsStr>,
169    {
170        self.environment.envs(vars);
171        self
172    }
173
174    pub fn env_remove<K: AsRef<OsStr>>(&mut self, key: K) -> &mut Self {
175        self.environment.env_remove(key);
176        self
177    }
178
179    pub fn env_clear(&mut self) -> &mut Self {
180        self.environment.env_clear();
181        self.clear_environment = true;
182        self
183    }
184
185    /// Finish environment configuration and resolve against the final child PATH.
186    /// Only non-environment command settings should be applied after this point.
187    pub fn build(&self) -> std::process::Command {
188        let program = self.environment.get_program();
189        // An absolute executable lets std use posix_spawn even with a changed
190        // PATH; a bare name would require fork+exec to search the child PATH.
191        #[cfg(unix)]
192        let resolved = self
193            .environment
194            .get_envs()
195            .find(|(key, _)| *key == "PATH")
196            .and_then(|(_, path)| path)
197            .and_then(|path| resolve_in_path(program, path));
198        #[cfg(unix)]
199        let mut command = match resolved {
200            Some(resolved) => {
201                let mut command = std::process::Command::new(resolved);
202                command.arg0(program);
203                command
204            }
205            // Inherited PATH needs no pre-resolution. A removed PATH must use
206            // execvp's platform default, not AFT's effective PATH. Relative or
207            // empty entries likewise need lookup in the child's working directory.
208            None => std::process::Command::new(program),
209        };
210        #[cfg(not(unix))]
211        let mut command = std::process::Command::new(program);
212        if self.clear_environment {
213            command.env_clear();
214        }
215        for (key, value) in self.environment.get_envs() {
216            match value {
217                Some(value) => command.env(key, value),
218                None => command.env_remove(key),
219            };
220        }
221        command
222    }
223
224    /// Leave lookup to execvp when a mandatory pre_exec hook requires fork anyway.
225    /// The returned command may still receive environment changes before spawning.
226    #[cfg(unix)]
227    pub fn build_unresolved(self) -> std::process::Command {
228        self.environment
229    }
230}
231
232/// Find `program` in `path`, skipping executable scripts whose interpreter is
233/// known to be unavailable. Returns `None`, leaving lookup to the child, for
234/// names that are already paths and for a PATH with an empty or relative entry,
235/// because those entries resolve against the child's working directory.
236///
237/// Apple's `exec(3)` continues PATH search after `ENOENT`, `ENOTDIR`, and
238/// `EACCES`; glibc's `posix/execvpe.c` also skips `ESTALE`, `ENODEV`, and
239/// `ETIMEDOUT`. This preflight recognizes only deterministic missing or
240/// non-executable interpreter cases; later spawn failures are returned as-is.
241#[cfg(unix)]
242fn resolve_in_path(program: &OsStr, path: &OsStr) -> Option<PathBuf> {
243    if program.is_empty() || program.as_bytes().contains(&b'/') {
244        return None;
245    }
246    if !std::env::split_paths(path).all(|directory| directory.is_absolute()) {
247        return None;
248    }
249    std::env::split_paths(path).find_map(|directory| {
250        let candidate = directory.join(program);
251        (executable_file(&candidate) && script_interpreter_is_available(&candidate))
252            .then_some(candidate)
253    })
254}
255
256#[cfg(unix)]
257fn executable_file(path: &Path) -> bool {
258    let Ok(text) = std::ffi::CString::new(path.as_os_str().as_bytes()) else {
259        return false;
260    };
261    std::fs::metadata(path).is_ok_and(|metadata| metadata.is_file())
262        // SAFETY: `text` is a valid NUL-terminated path for the call.
263        && unsafe { libc::access(text.as_ptr(), libc::X_OK) } == 0
264}
265
266#[cfg(unix)]
267fn script_interpreter_is_available(script: &Path) -> bool {
268    const SHEBANG_LIMIT: usize = 256;
269
270    let Ok(mut file) = File::open(script) else {
271        return true;
272    };
273    let mut bytes = [0_u8; SHEBANG_LIMIT];
274    let mut length = 0;
275    while length < bytes.len() {
276        match file.read(&mut bytes[length..]) {
277            Ok(0) => break,
278            Ok(read) => length += read,
279            Err(_) => return true,
280        }
281    }
282    if length < 2 || &bytes[..2] != b"#!" {
283        return true;
284    }
285    // A truncated, unterminated first line cannot be parsed reliably; let the
286    // kernel decide whether this script is executable.
287    let first_line = &bytes[2..length];
288    let line_end = first_line
289        .iter()
290        .position(|byte| *byte == b'\n')
291        .unwrap_or(first_line.len());
292    let complete_line = length < bytes.len() || line_end < first_line.len();
293    if !complete_line && !first_line.iter().any(|byte| byte.is_ascii_whitespace()) {
294        return true;
295    }
296    let mut words = first_line[..line_end]
297        .split(|byte| byte.is_ascii_whitespace())
298        .filter(|word| !word.is_empty());
299    let Some(interpreter) = words.next() else {
300        return true;
301    };
302    let interpreter = Path::new(OsStr::from_bytes(interpreter));
303    if !interpreter.is_absolute() {
304        return true;
305    }
306    if !executable_file(interpreter) {
307        return false;
308    }
309    true
310}
311
312/// On Windows the process PATH is already correct (registry-backed
313/// environment block); pass through without touching the child env.
314#[cfg(not(unix))]
315pub fn new_command<S: AsRef<OsStr>>(program: S) -> CommandBuilder {
316    CommandBuilder::new(program.as_ref())
317}
318
319/// Return the cached PATH that subprocesses should inherit.
320///
321/// On Windows this is the process PATH unchanged: Windows daemon environments
322/// already receive PATH from the registry-backed environment block.
323#[cfg(not(unix))]
324pub fn effective_path() -> &'static OsStr {
325    EFFECTIVE_PATH
326        .get_or_init(compute_effective_path)
327        .as_os_str()
328}
329
330#[rustfmt::skip]
331test_support_visibility! {
332
333/// Where the probed login-shell PATH is cached between processes.
334#[cfg(unix)]
335pub(crate) fn effective_path_cache_path() -> PathBuf {
336    crate::storage_path::storage_dir(None).join("effective-path.json")
337}
338}
339
340#[cfg(unix)]
341pub fn effective_path() -> &'static OsStr {
342    // Test seam: integration tests construct exact PATHs (e.g. to simulate a
343    // missing formatter binary); probing and enrichment would re-add real tool
344    // dirs from the host and break that isolation. Checked at runtime because
345    // the spawned test binary is a production build.
346    // "0" reads as unset so the PATH feature's own integration tests can
347    // opt back in to probing under a test harness that defaults the seam on.
348    if std::env::var_os("AFT_TEST_RAW_PATH").is_some_and(|value| value != "0" && !value.is_empty())
349    {
350        static RAW: OnceLock<OsString> = OnceLock::new();
351        return RAW
352            .get_or_init(|| std::env::var_os("PATH").unwrap_or_default())
353            .as_os_str();
354    }
355
356    let mut guard = EFFECTIVE_PATH_STATE
357        .lock()
358        .unwrap_or_else(|error| error.into_inner());
359    if let Some(state) = guard.as_ref() {
360        return state.path;
361    }
362
363    let started = Instant::now();
364    let current = std::env::var_os("PATH").unwrap_or_default();
365    let home = crate::environment::non_empty_os_var("HOME");
366    // Use the normal process-state resolver. It is available before the app is
367    // constructed, so no early XDG-only fallback can split this cache from AFT's
368    // configured storage root.
369    let cache_path = effective_path_cache_path();
370    let candidates = login_shell_candidates();
371
372    let (login_path, source, shell) = read_effective_path_cache(&cache_path)
373        .filter(|cache| cache_matches_current_shell(cache, &candidates))
374        .map(|cache| {
375            (
376                cache
377                    .path
378                    .and_then(|path| filter_login_path(OsStr::new(&path))),
379                ProbeSource::Cache,
380                cache.shell,
381            )
382        })
383        .unwrap_or_else(|| {
384            let result = probe_login_shell_path();
385            let cache = EffectivePathCache {
386                schema: EFFECTIVE_PATH_CACHE_SCHEMA,
387                shell: result.shell.to_string_lossy().into_owned(),
388                path: result
389                    .path
390                    .as_ref()
391                    .map(|path| path.to_string_lossy().into_owned()),
392                probed_at_unix: unix_timestamp_secs(),
393                inputs: shell_startup_inputs(&result.shell),
394            };
395            let _ = write_effective_path_cache(&cache_path, &cache);
396            let source = if result.path.is_some() {
397                ProbeSource::Probe
398            } else {
399                ProbeSource::Timeout
400            };
401            (result.path, source, cache.shell)
402        });
403
404    let merged = login_path
405        .as_deref()
406        .map(|path| merge_current_and_login_path(&current, path))
407        .unwrap_or_else(|| current.clone());
408    let enriched = append_missing_standard_dirs(&merged, home.as_deref(), |dir| dir.is_dir());
409    let path = Box::leak(enriched.into_boxed_os_str());
410    *guard = Some(PathState {
411        path,
412        source,
413        shell,
414        elapsed: started.elapsed(),
415        cache_path,
416        refresh_started: false,
417        log_emitted: false,
418    });
419    path
420}
421
422#[cfg(windows)]
423fn compute_effective_path() -> OsString {
424    std::env::var_os("PATH").unwrap_or_default()
425}
426
427#[cfg(not(any(unix, windows)))]
428fn compute_effective_path() -> OsString {
429    std::env::var_os("PATH").unwrap_or_default()
430}
431
432/// Core tool directories are kept first in the standard-directory fallback.
433#[cfg(unix)]
434fn core_standard_path_dirs(home: Option<&OsStr>) -> Vec<PathBuf> {
435    let mut dirs = vec![
436        PathBuf::from("/opt/homebrew/bin"),
437        PathBuf::from("/usr/local/bin"),
438    ];
439    if let Some(home) = home {
440        let home = PathBuf::from(home);
441        dirs.push(home.join(".cargo/bin"));
442        dirs.push(home.join(".local/bin"));
443    }
444    dirs
445}
446
447/// All dirs merged into every constructed PATH when present on disk. Includes
448/// common installer locations that may not be represented in a shell probe.
449#[cfg(unix)]
450fn user_standard_path_dirs(home: Option<&OsStr>) -> Vec<PathBuf> {
451    let mut dirs = core_standard_path_dirs(home);
452    if let Some(home) = home {
453        let home = PathBuf::from(home);
454        dirs.push(home.join(".bun/bin"));
455        dirs.push(home.join("Library/pnpm"));
456        dirs.push(home.join(".local/share/pnpm"));
457        dirs.push(home.join(".local/share/mise/shims"));
458        dirs.push(home.join(".deno/bin"));
459        dirs.push(home.join(".volta/bin"));
460    }
461    dirs
462}
463
464#[cfg(unix)]
465fn append_missing_standard_dirs<D>(
466    path: &OsStr,
467    home: Option<&OsStr>,
468    mut dir_exists: D,
469) -> OsString
470where
471    D: FnMut(&Path) -> bool,
472{
473    let mut entries: Vec<PathBuf> = std::env::split_paths(path).collect();
474    let mut seen: HashSet<PathBuf> = entries.iter().cloned().collect();
475
476    for dir in user_standard_path_dirs(home) {
477        if dir_exists(&dir) && seen.insert(dir.clone()) {
478            entries.push(dir);
479        }
480    }
481
482    std::env::join_paths(entries).unwrap_or_else(|_| path.to_os_string())
483}
484
485#[cfg(unix)]
486#[derive(Debug)]
487struct LoginPathProbe {
488    shell: PathBuf,
489    path: Option<OsString>,
490}
491
492#[cfg(unix)]
493fn probe_login_shell_path() -> LoginPathProbe {
494    probe_login_shell_path_with_budgets(
495        LOGIN_SHELL_PATH_PROBE_TIMEOUT,
496        LOGIN_SHELL_PATH_PROBE_TOTAL_BUDGET,
497    )
498}
499
500#[cfg(unix)]
501// Success-path tests use a generous timeout without changing startup's budget.
502fn probe_login_shell_path_with_budgets(
503    probe_timeout: Duration,
504    total_budget: Duration,
505) -> LoginPathProbe {
506    let candidates = login_shell_candidates();
507    let fallback_shell = candidates
508        .first()
509        .cloned()
510        .unwrap_or_else(|| PathBuf::from("/bin/sh"));
511    let deadline = Instant::now() + total_budget;
512
513    for shell in candidates {
514        let now = Instant::now();
515        if now >= deadline {
516            break;
517        }
518        let timeout = probe_timeout.min(deadline.saturating_duration_since(now));
519        if let Some(path) =
520            probe_login_shell_path_once(&shell, timeout).and_then(|path| filter_login_path(&path))
521        {
522            // Cache against the requested shell, not a fallback that happened
523            // to answer this probe. Otherwise a hanging $SHELL would pay its
524            // timeout again on every launch before the fallback can be reused.
525            return LoginPathProbe {
526                shell: fallback_shell,
527                path: Some(path),
528            };
529        }
530    }
531
532    LoginPathProbe {
533        shell: fallback_shell,
534        path: None,
535    }
536}
537
538#[cfg(unix)]
539fn login_shell_candidates() -> Vec<PathBuf> {
540    // This runtime seam lets integration tests exercise the production binary
541    // with a deterministic shell. Normal launches still use SHELL and fall back
542    // to the common interactive shells below.
543    if let Some(value) = crate::environment::non_empty_os_var("AFT_TEST_LOGIN_SHELL_CANDIDATES") {
544        let candidates = std::env::split_paths(&value).collect::<Vec<_>>();
545        if !candidates.is_empty() {
546            return candidates;
547        }
548    }
549
550    let mut candidates = Vec::new();
551    if let Some(shell) = std::env::var_os("SHELL").filter(|value| !value.is_empty()) {
552        candidates.push(PathBuf::from(shell));
553    }
554    let zsh = PathBuf::from("/bin/zsh");
555    let bash = PathBuf::from("/bin/bash");
556    if !candidates.contains(&zsh) {
557        candidates.push(zsh);
558    }
559    if !candidates.contains(&bash) {
560        candidates.push(bash);
561    }
562    candidates
563}
564
565#[cfg(unix)]
566fn set_nonblocking<F: AsRawFd>(file: &F) -> std::io::Result<()> {
567    let fd = file.as_raw_fd();
568    unsafe {
569        let flags = libc::fcntl(fd, libc::F_GETFL);
570        if flags < 0 {
571            return Err(std::io::Error::last_os_error());
572        }
573        if libc::fcntl(fd, libc::F_SETFL, flags | libc::O_NONBLOCK) < 0 {
574            return Err(std::io::Error::last_os_error());
575        }
576    }
577    Ok(())
578}
579
580#[cfg(unix)]
581fn probe_login_shell_path_once(shell: &Path, timeout: Duration) -> Option<OsString> {
582    let mut command = Command::new(shell);
583
584    command
585        .arg(probe_shell_flags(shell))
586        .arg(probe_shell_command(shell))
587        .stdin(Stdio::null())
588        .stdout(Stdio::piped())
589        .stderr(Stdio::null());
590    // Run the probe in its own session so the timeout can kill login-shell
591    // startup helpers as well as the shell process itself.
592    unsafe {
593        command.pre_exec(|| {
594            if libc::setsid() == -1 {
595                return Err(std::io::Error::last_os_error());
596            }
597            Ok(())
598        });
599    }
600    let mut child = spawn_retrying_executable_file_busy(&mut command, "login shell")?;
601    let mut stdout = child.stdout.take()?;
602    let _ = set_nonblocking(&stdout);
603    let mut output_bytes = Vec::new();
604    let mut buf = [0u8; 1024];
605
606    let deadline = Instant::now() + timeout;
607    loop {
608        use std::io::Read;
609        match stdout.read(&mut buf) {
610            Ok(0) => {
611                // EOF can arrive before a shell-startup child exits. Keep the
612                // existing one-second reap grace, but never let it overrun the
613                // caller's per-candidate share of the total startup budget.
614                let wait_deadline = (Instant::now() + Duration::from_secs(1)).min(deadline);
615                loop {
616                    match child.try_wait() {
617                        Ok(Some(_)) => break,
618                        Ok(None) if Instant::now() >= wait_deadline => {
619                            kill_login_shell_probe(&mut child);
620                            break;
621                        }
622                        Ok(None) => {
623                            std::thread::sleep(Duration::from_millis(10));
624                        }
625                        Err(_) => {
626                            kill_login_shell_probe(&mut child);
627                            break;
628                        }
629                    }
630                }
631                return extract_probe_path(&output_bytes);
632            }
633            Ok(n) => {
634                output_bytes.extend_from_slice(&buf[..n]);
635            }
636            Err(ref error) if error.kind() == std::io::ErrorKind::WouldBlock => {}
637            Err(_) => {
638                kill_login_shell_probe(&mut child);
639                return None;
640            }
641        }
642
643        match child.try_wait() {
644            Ok(Some(_)) => {
645                loop {
646                    match stdout.read(&mut buf) {
647                        Ok(0) => break,
648                        Ok(n) => output_bytes.extend_from_slice(&buf[..n]),
649                        Err(ref error) if error.kind() == std::io::ErrorKind::WouldBlock => {
650                            break;
651                        }
652                        Err(_) => break,
653                    }
654                }
655                let _ = child.wait();
656                return extract_probe_path(&output_bytes);
657            }
658            Ok(None) if Instant::now() >= deadline => {
659                kill_login_shell_probe(&mut child);
660                return None;
661            }
662            Ok(None) => {
663                std::thread::sleep(Duration::from_millis(25));
664            }
665            Err(_) => {
666                kill_login_shell_probe(&mut child);
667                return None;
668            }
669        }
670    }
671}
672
673#[cfg(unix)]
674fn spawn_retrying_executable_file_busy(command: &mut Command, purpose: &str) -> Option<Child> {
675    for retry in 0..=SPAWN_BUSY_RETRY_COUNT {
676        match command.spawn() {
677            Ok(child) => return Some(child),
678            Err(error)
679                if error.kind() == std::io::ErrorKind::ExecutableFileBusy
680                    && retry < SPAWN_BUSY_RETRY_COUNT =>
681            {
682                #[cfg(any(test, feature = "test-support"))]
683                busy_retry_hook::run();
684                std::thread::sleep(SPAWN_BUSY_RETRY_DELAY);
685            }
686            Err(error) => {
687                log::debug!("failed to spawn {purpose}: {error}");
688                return None;
689            }
690        }
691    }
692
693    unreachable!("the final spawn attempt returns or exits the retry loop")
694}
695
696/// Lets a test act at the moment a spawn hit a busy executable and is about
697/// to retry, on the thread that spawns. Parallel tests do not see each
698/// other's hooks.
699#[cfg(all(any(test, feature = "test-support"), unix))]
700mod busy_retry_hook {
701    use std::cell::RefCell;
702
703    thread_local! {
704        static HOOK: RefCell<Option<Box<dyn FnMut()>>> = const { RefCell::new(None) };
705    }
706
707    pub(super) fn run() {
708        HOOK.with(|hook| {
709            if let Some(hook) = hook.borrow_mut().as_mut() {
710                hook();
711            }
712        });
713    }
714
715    /// Run `body` with `hook` called before each busy-file retry. Only the
716    /// Linux busy-executable test calls it.
717    #[cfg_attr(not(target_os = "linux"), allow(dead_code))]
718    #[cfg_attr(not(test), allow(dead_code))]
719    pub(super) fn with<T>(hook: impl FnMut() + 'static, body: impl FnOnce() -> T) -> T {
720        HOOK.with(|slot| *slot.borrow_mut() = Some(Box::new(hook)));
721        let value = body();
722        HOOK.with(|slot| *slot.borrow_mut() = None);
723        value
724    }
725}
726
727#[cfg(unix)]
728fn probe_shell_flags(_shell: &Path) -> &'static str {
729    // Login and interactive modes together cover the startup files that may
730    // contribute PATH entries, including bash's .bashrc and zsh's .zshrc.
731    "-lic"
732}
733
734#[cfg(unix)]
735fn probe_shell_command(shell: &Path) -> &'static str {
736    let name = shell.file_name().and_then(|name| name.to_str());
737    if name.is_some_and(|name| name.eq_ignore_ascii_case("fish")) {
738        r#"printf '\n__AFT_PATH_BEGIN__%s__AFT_PATH_END__\n' (string join : $PATH)"#
739    } else {
740        r#"printf '\n__AFT_PATH_BEGIN__%s__AFT_PATH_END__\n' "$PATH""#
741    }
742}
743
744#[cfg(unix)]
745fn extract_probe_path(output: &[u8]) -> Option<OsString> {
746    const BEGIN: &[u8] = b"__AFT_PATH_BEGIN__";
747    const END: &[u8] = b"__AFT_PATH_END__";
748    let begin = output
749        .windows(BEGIN.len())
750        .position(|window| window == BEGIN)?
751        + BEGIN.len();
752    let end = output[begin..]
753        .windows(END.len())
754        .position(|window| window == END)?
755        + begin;
756    Some(OsString::from_vec(output[begin..end].to_vec()))
757}
758
759#[cfg(unix)]
760fn kill_login_shell_probe(child: &mut std::process::Child) {
761    let pid = child.id() as i32;
762    if pid > 0 {
763        // Negative PID targets the process group created by setsid above.
764        unsafe {
765            let _ = libc::kill(-pid, libc::SIGKILL);
766        }
767    }
768    let _ = child.kill();
769    let _ = child.wait();
770}
771
772#[cfg(unix)]
773fn login_path_is_acceptable(path: &OsStr) -> bool {
774    filter_login_path(path).is_some()
775}
776
777#[cfg(unix)]
778fn filter_login_path(path: &OsStr) -> Option<OsString> {
779    let bytes = path.as_bytes();
780    if bytes.is_empty()
781        || bytes
782            .iter()
783            .any(|byte| matches!(byte, b'\0' | b'\n' | b'\r'))
784    {
785        return None;
786    }
787
788    if bytes.contains(&b' ') {
789        let mut abs_count = 0;
790        for part in bytes.split(|&byte| byte == b' ') {
791            if part.first() == Some(&b'/') {
792                abs_count += 1;
793            }
794        }
795        if abs_count > 1 {
796            return None;
797        }
798    }
799
800    // Relative and empty entries must not discard usable absolute tool paths.
801    let mut filtered = Vec::new();
802    for entry in bytes.split(|byte| *byte == b':') {
803        if entry.first() != Some(&b'/') {
804            continue;
805        }
806        if !filtered.is_empty() {
807            filtered.push(b':');
808        }
809        filtered.extend_from_slice(entry);
810    }
811    (!filtered.is_empty()).then(|| OsString::from_vec(filtered))
812}
813
814#[cfg(unix)]
815fn merge_current_and_login_path(current_path: &OsStr, login_path: &OsStr) -> OsString {
816    let mut seen = HashSet::new();
817    let mut merged = Vec::new();
818
819    // Keep daemon-provided ordering and precedence; shell startup files only
820    // contribute entries that are not already present, appended at the end.
821    for entry in std::env::split_paths(current_path).chain(std::env::split_paths(login_path)) {
822        if seen.insert(entry.clone()) {
823            merged.push(entry);
824        }
825    }
826
827    std::env::join_paths(merged).unwrap_or_else(|_| current_path.to_os_string())
828}
829
830#[cfg(unix)]
831#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
832struct EffectivePathInput {
833    file: String,
834    mtime_ns: Option<i128>,
835    size: Option<u64>,
836}
837
838#[cfg(unix)]
839#[derive(Clone, Debug, Deserialize, Serialize)]
840struct EffectivePathCache {
841    schema: u32,
842    shell: String,
843    path: Option<String>,
844    probed_at_unix: u64,
845    inputs: Vec<EffectivePathInput>,
846}
847
848#[cfg(unix)]
849fn read_effective_path_cache(path: &Path) -> Option<EffectivePathCache> {
850    let content = std::fs::read_to_string(path).ok()?;
851    serde_json::from_str(&content).ok()
852}
853
854#[cfg(unix)]
855fn write_effective_path_cache(path: &Path, cache: &EffectivePathCache) -> std::io::Result<()> {
856    if let Some(parent) = path.parent() {
857        crate::private_storage::create_dir_all(parent)?;
858    }
859    let content = serde_json::to_vec(cache).map_err(std::io::Error::other)?;
860    let temporary = path.with_file_name(format!(
861        ".{}.{}.tmp",
862        path.file_name()
863            .and_then(|name| name.to_str())
864            .unwrap_or("effective-path.json"),
865        std::process::id()
866    ));
867    let result = (|| {
868        crate::private_storage::write(&temporary, content)?;
869        std::fs::rename(&temporary, path)?;
870        Ok(())
871    })();
872    if result.is_err() {
873        let _ = std::fs::remove_file(&temporary);
874    }
875    result
876}
877
878#[cfg(unix)]
879fn cache_matches_current_shell(cache: &EffectivePathCache, candidates: &[PathBuf]) -> bool {
880    let Some(current_shell) = candidates.first() else {
881        return false;
882    };
883    cache.schema == EFFECTIVE_PATH_CACHE_SCHEMA
884        && cache.shell == current_shell.to_string_lossy()
885        && cache.inputs == shell_startup_inputs(current_shell)
886        && cache
887            .path
888            .as_deref()
889            .map(|path| login_path_is_acceptable(OsStr::new(path)))
890            .unwrap_or(false)
891}
892
893#[cfg(unix)]
894fn shell_startup_inputs(shell: &Path) -> Vec<EffectivePathInput> {
895    let name = shell.file_name().and_then(|name| name.to_str());
896    let is_zsh = name.is_some_and(|name| name.eq_ignore_ascii_case("zsh"));
897    let mut files = if is_zsh {
898        vec![
899            PathBuf::from("/etc/zshenv"),
900            PathBuf::from("/etc/zprofile"),
901            PathBuf::from("/etc/zshrc"),
902        ]
903    } else {
904        vec![PathBuf::from("/etc/profile")]
905    };
906    if let Some(home) = std::env::var_os("HOME").filter(|value| !value.is_empty()) {
907        let home = PathBuf::from(home);
908        let names: &[&str] = if is_zsh {
909            &[".zshenv", ".zprofile", ".zshrc"]
910        } else {
911            &[".bash_profile", ".bash_login", ".profile", ".bashrc"]
912        };
913        files.extend(names.iter().map(|name| home.join(name)));
914    }
915    files
916        .into_iter()
917        .map(|file| match std::fs::metadata(&file) {
918            Ok(metadata) => EffectivePathInput {
919                file: file.to_string_lossy().into_owned(),
920                mtime_ns: Some(
921                    i128::from(metadata.mtime()) * 1_000_000_000
922                        + i128::from(metadata.mtime_nsec()),
923                ),
924                size: Some(metadata.len()),
925            },
926            Err(_) => EffectivePathInput {
927                file: file.to_string_lossy().into_owned(),
928                mtime_ns: None,
929                size: None,
930            },
931        })
932        .collect()
933}
934
935#[cfg(unix)]
936fn unix_timestamp_secs() -> u64 {
937    SystemTime::now()
938        .duration_since(UNIX_EPOCH)
939        .unwrap_or_default()
940        .as_secs()
941}
942
943/// Refresh a cache from the helper process without mutating its environment.
944#[cfg(unix)]
945pub fn refresh_login_shell_path_cache(cache_path: &Path) -> Result<(), String> {
946    let result = probe_login_shell_path();
947    let cache = EffectivePathCache {
948        schema: EFFECTIVE_PATH_CACHE_SCHEMA,
949        shell: result.shell.to_string_lossy().into_owned(),
950        path: result
951            .path
952            .as_ref()
953            .map(|path| path.to_string_lossy().into_owned()),
954        probed_at_unix: unix_timestamp_secs(),
955        inputs: shell_startup_inputs(&result.shell),
956    };
957    write_effective_path_cache(cache_path, &cache)
958        .map_err(|error| format!("write {}: {error}", cache_path.display()))
959}
960
961#[cfg(not(unix))]
962pub fn refresh_login_shell_path_cache(_cache_path: &std::path::Path) -> Result<(), String> {
963    Ok(())
964}
965
966#[cfg(unix)]
967fn spawn_cached_path_refresh() {
968    // Integration tests point this seam at a deliberately sleeping shell and
969    // assert the serving binary does not run it on a cache hit. Production
970    // launches do not set the seam and always refresh through the helper.
971    if std::env::var_os("AFT_TEST_LOGIN_SHELL_CANDIDATES").is_some() {
972        return;
973    }
974
975    let cache_path = {
976        let mut guard = EFFECTIVE_PATH_STATE
977            .lock()
978            .unwrap_or_else(|error| error.into_inner());
979        let Some(state) = guard.as_mut() else {
980            return;
981        };
982        if state.source != ProbeSource::Cache || state.refresh_started {
983            return;
984        }
985        state.refresh_started = true;
986        state.cache_path.clone()
987    };
988
989    let Ok(executable) = crate::pinned_executable::path() else {
990        return;
991    };
992    let mut command = Command::new(executable);
993    command
994        .arg("--probe-login-shell-path")
995        .arg(cache_path)
996        .stdin(Stdio::null())
997        .stdout(Stdio::null())
998        .stderr(Stdio::null());
999    // Run the cache-refresh helper independently so it can finish after the
1000    // serving process exits. Its shell probe still enforces the per-candidate
1001    // timeout and kills the probe process group when necessary.
1002    unsafe {
1003        command.pre_exec(|| {
1004            if libc::setsid() == -1 {
1005                return Err(std::io::Error::last_os_error());
1006            }
1007            Ok(())
1008        });
1009    }
1010    spawn_reaped(&mut command);
1011}
1012
1013/// Spawn `command` and hand the child to a short-lived thread that waits on
1014/// it, returning the child pid so callers can observe the reap.
1015///
1016/// `setsid()` only detaches the helper from the session; the spawning process
1017/// remains its parent and is the only one that can reap it. Without a
1018/// `wait()` the finished helper stays a zombie for the life of this process.
1019#[cfg(unix)]
1020fn spawn_reaped(command: &mut Command) -> Option<u32> {
1021    let Some(child) = spawn_retrying_executable_file_busy(command, "login-shell PATH cache helper")
1022    else {
1023        return None;
1024    };
1025    let pid = child.id();
1026    reap_child_in_background(child);
1027    Some(pid)
1028}
1029
1030/// Reap `child` from a named background thread so the caller never blocks.
1031#[cfg(unix)]
1032fn reap_child_in_background(mut child: Child) {
1033    // When the thread cannot be spawned, the error drops the moved closure
1034    // and its child with it: the child goes unreaped, matching the behavior
1035    // callers had before the reaper existed, instead of blocking on wait().
1036    let _ = std::thread::Builder::new()
1037        .name("aft-path-refresh-reaper".to_string())
1038        .spawn(move || {
1039            let _ = child.wait();
1040        });
1041}
1042
1043/// Test seam that tells which spawn mechanism std used for a `Command`.
1044///
1045/// A `pthread_atfork` prepare handler counts fork() calls made by the current
1046/// thread. std's fork+exec fallback calls libc `fork`, which runs the handler;
1047/// its `posix_spawn` path (a syscall on macOS, a CLONE_VFORK clone on glibc)
1048/// does not. The count is per thread, so parallel tests that fork do not
1049/// disturb each other.
1050#[cfg(all(any(test, feature = "test-support"), unix))]
1051pub mod fork_counter {
1052    use std::cell::Cell;
1053    use std::sync::Once;
1054
1055    thread_local! {
1056        static FORKS: Cell<usize> = const { Cell::new(0) };
1057    }
1058
1059    extern "C" fn count_fork() {
1060        FORKS.with(|forks| forks.set(forks.get() + 1));
1061    }
1062
1063    /// Run `body` and return its result with the number of forks this thread
1064    /// made meanwhile.
1065    pub fn forks_during<T>(body: impl FnOnce() -> T) -> (T, usize) {
1066        static REGISTER: Once = Once::new();
1067        REGISTER.call_once(|| {
1068            // SAFETY: the handler only touches a const-initialized thread-local.
1069            let rc = unsafe { libc::pthread_atfork(Some(count_fork), None, None) };
1070            assert_eq!(rc, 0, "pthread_atfork failed");
1071        });
1072        let before = FORKS.with(Cell::get);
1073        let value = body();
1074        (value, FORKS.with(Cell::get) - before)
1075    }
1076}
1077
1078#[cfg(test)]
1079#[cfg(unix)]
1080mod tests {
1081    #[test]
1082    fn helpers_do_not_override_inherited_path() {
1083        let path = std::env::var_os("PATH").unwrap();
1084        let command = super::command_with_path(std::ffi::OsStr::new("git"), &path).build();
1085        assert!(
1086            !command.get_envs().any(|(key, _)| key == "PATH"),
1087            "an explicit PATH, even unchanged, forces Rust's macOS Command to fork"
1088        );
1089    }
1090
1091    #[test]
1092    fn helpers_preserve_distinct_effective_path() {
1093        let path = std::ffi::OsStr::new("/aft-test-distinct-path");
1094        let command = super::command_with_path(std::ffi::OsStr::new("git"), path).build();
1095        assert!(command
1096            .get_envs()
1097            .any(|(key, value)| key == "PATH" && value == Some(path)));
1098    }
1099
1100    #[test]
1101    fn path_set_after_construction_selects_the_child_cargo() {
1102        let effective_tools = tempfile::tempdir().unwrap();
1103        let child_tools = tempfile::tempdir().unwrap();
1104        write_executable_shim(
1105            &effective_tools.path().join("cargo"),
1106            "#!/bin/sh\nprintf 'effective-path cargo'\n",
1107        );
1108        write_executable_shim(
1109            &child_tools.path().join("cargo"),
1110            "#!/bin/sh\nprintf 'configured cargo:%s' \"$PATH\"\n",
1111        );
1112        let mut command =
1113            command_with_path(OsStr::new("cargo"), effective_tools.path().as_os_str());
1114        command.env("PATH", child_tools.path());
1115
1116        let (output, forks) = fork_counter::forks_during(|| command.build().output().unwrap());
1117        assert!(output.status.success(), "{output:?}");
1118        assert_eq!(
1119            String::from_utf8(output.stdout).unwrap(),
1120            format!("configured cargo:{}", child_tools.path().display())
1121        );
1122        assert_eq!(forks, 0, "configured PATH forced a fork+exec spawn");
1123    }
1124
1125    #[test]
1126    fn path_removed_after_construction_uses_execvp_default() {
1127        let tools = tempfile::tempdir().unwrap();
1128        write_executable_shim(
1129            &tools.path().join("sh"),
1130            "#!/bin/sh\nprintf 'effective-path shell'\n",
1131        );
1132        let mut command = command_with_path(OsStr::new("sh"), tools.path().as_os_str());
1133        command.env_remove("PATH");
1134
1135        let output = command
1136            .build()
1137            .args(["-c", "printf 'default-path shell'"])
1138            .output()
1139            .unwrap();
1140        assert!(output.status.success(), "{output:?}");
1141        assert_eq!(
1142            String::from_utf8(output.stdout).unwrap(),
1143            "default-path shell"
1144        );
1145    }
1146
1147    #[test]
1148    fn environment_cleared_after_construction_uses_execvp_default() {
1149        let tools = tempfile::tempdir().unwrap();
1150        write_executable_shim(
1151            &tools.path().join("sh"),
1152            "#!/bin/sh\nprintf 'effective-path shell'\n",
1153        );
1154        let mut command = command_with_path(OsStr::new("sh"), tools.path().as_os_str());
1155        command.env_clear();
1156
1157        let output = command
1158            .build()
1159            .args(["-c", "printf 'default-path shell'"])
1160            .output()
1161            .unwrap();
1162        assert!(output.status.success(), "{output:?}");
1163        assert_eq!(
1164            String::from_utf8(output.stdout).unwrap(),
1165            "default-path shell"
1166        );
1167    }
1168
1169    #[test]
1170    fn configured_relative_path_uses_the_child_working_directory() {
1171        let effective_tools = tempfile::tempdir().unwrap();
1172        let workdir = tempfile::tempdir().unwrap();
1173        fs::create_dir(workdir.path().join("bin")).unwrap();
1174        write_executable_shim(
1175            &effective_tools.path().join("cargo"),
1176            "#!/bin/sh\nprintf 'effective-path cargo'\n",
1177        );
1178        write_executable_shim(
1179            &workdir.path().join("bin/cargo"),
1180            "#!/bin/sh\nprintf 'relative-path cargo'\n",
1181        );
1182        for path in ["bin", ":bin", "bin:"] {
1183            let output = command_with_path(OsStr::new("cargo"), effective_tools.path().as_os_str())
1184                .env("PATH", path)
1185                .build()
1186                .current_dir(workdir.path())
1187                .output()
1188                .unwrap();
1189            assert!(output.status.success(), "{path}: {output:?}");
1190            assert_eq!(output.stdout, b"relative-path cargo", "{path}");
1191        }
1192    }
1193
1194    /// A PATH that differs from the process PATH must not push bare-name
1195    /// helpers (git above all) onto std's fork+exec fallback, and the child
1196    /// must still find the tool on, and inherit, that PATH.
1197    #[test]
1198    fn distinct_effective_path_spawns_bare_names_without_fork() {
1199        let tools = tempfile::tempdir().unwrap();
1200        let tool = tools.path().join("aft-path-probe-tool");
1201        write_executable_shim(&tool, "#!/bin/sh\nprintf '%s' \"$PATH\"\n");
1202        let path =
1203            std::env::join_paths([tools.path(), Path::new("/usr/bin"), Path::new("/bin")]).unwrap();
1204        assert_ne!(std::env::var_os("PATH").as_deref(), Some(path.as_os_str()));
1205
1206        let workdir = tempfile::tempdir().unwrap();
1207        let (output, forks) = fork_counter::forks_during(|| {
1208            let mut command = command_with_path(OsStr::new("aft-path-probe-tool"), &path).build();
1209            command.current_dir(workdir.path()).output().unwrap()
1210        });
1211        assert!(output.status.success(), "{output:?}");
1212        assert_eq!(
1213            output.stdout,
1214            path.as_bytes(),
1215            "child keeps the effective PATH"
1216        );
1217        assert_eq!(
1218            forks, 0,
1219            "bare-name spawn under a distinct PATH used fork+exec"
1220        );
1221
1222        // The fork counter must see the fork of a pre_exec spawn; otherwise the
1223        // zero forks asserted above would not show that posix_spawn was used.
1224        let (_, control) = fork_counter::forks_during(|| {
1225            let mut command = std::process::Command::new("/bin/sh");
1226            command.args(["-c", "exit 0"]);
1227            // SAFETY: the closure does nothing.
1228            unsafe { command.pre_exec(|| Ok(())) };
1229            command.status().unwrap()
1230        });
1231        assert_eq!(control, 1, "fork counter missed a pre_exec spawn");
1232    }
1233
1234    #[test]
1235    fn path_resolution_defers_relative_entries_and_paths_to_the_child() {
1236        let tools = tempfile::tempdir().unwrap();
1237        let tool = tools.path().join("aft-path-probe-tool");
1238        write_executable_shim(&tool, "#!/bin/sh\n");
1239        let absolute = std::env::join_paths([tools.path()]).unwrap();
1240        assert_eq!(
1241            resolve_in_path(OsStr::new("aft-path-probe-tool"), &absolute),
1242            Some(tool.clone())
1243        );
1244        let with_relative = std::env::join_paths([Path::new("bin"), tools.path()]).unwrap();
1245        assert_eq!(
1246            resolve_in_path(OsStr::new("aft-path-probe-tool"), &with_relative),
1247            None
1248        );
1249        assert_eq!(resolve_in_path(tool.as_os_str(), &absolute), None);
1250        fs::set_permissions(&tool, fs::Permissions::from_mode(0o644)).unwrap();
1251        assert_eq!(
1252            resolve_in_path(OsStr::new("aft-path-probe-tool"), &absolute),
1253            None,
1254            "a non-executable entry is skipped, as execvp would"
1255        );
1256    }
1257
1258    #[test]
1259    fn distinct_effective_path_skips_a_script_with_a_missing_interpreter() {
1260        let first = tempfile::tempdir().unwrap();
1261        let second = tempfile::tempdir().unwrap();
1262        let name = "aft-path-probe-tool";
1263        write_executable_shim(
1264            &first.path().join(name),
1265            "#!/aft-test-missing-interpreter\nprintf 'wrong first candidate'\n",
1266        );
1267        write_executable_shim(
1268            &second.path().join(name),
1269            "#!/bin/sh\nprintf 'later candidate ran'\n",
1270        );
1271        let path = std::env::join_paths([first.path(), second.path()]).unwrap();
1272        assert_ne!(std::env::var_os("PATH").as_deref(), Some(path.as_os_str()));
1273
1274        let output = command_with_path(OsStr::new(name), &path)
1275            .build()
1276            .output()
1277            .expect("run the later executable after the broken script");
1278        assert!(output.status.success(), "{output:?}");
1279        assert_eq!(output.stdout, b"later candidate ran");
1280    }
1281
1282    #[test]
1283    fn distinct_effective_path_preserves_env_script_execvp_behavior() {
1284        let first = tempfile::tempdir().unwrap();
1285        let second = tempfile::tempdir().unwrap();
1286        let name = "aft-path-probe-env-tool";
1287        let missing = format!("aft-env-target-missing-{}", std::process::id());
1288        write_executable_shim(
1289            &first.path().join(name),
1290            &format!("#!/usr/bin/env {missing}\nprintf 'wrong first candidate'\n"),
1291        );
1292        write_executable_shim(
1293            &second.path().join(name),
1294            "#!/bin/sh\nprintf 'later candidate ran'\n",
1295        );
1296        let path = std::env::join_paths([first.path(), second.path()]).unwrap();
1297        assert_ne!(std::env::var_os("PATH").as_deref(), Some(path.as_os_str()));
1298
1299        let output = command_with_path(OsStr::new(name), &path)
1300            .build()
1301            .output()
1302            .expect("the first candidate's env interpreter can start");
1303        let shell_output = std::process::Command::new("/bin/sh")
1304            .arg("-c")
1305            .arg(name)
1306            .env("PATH", &path)
1307            .output()
1308            .expect("run the same bare name through shell PATH lookup");
1309
1310        assert_eq!(output.status.code(), Some(127), "{output:?}");
1311        assert_eq!(shell_output.status.code(), Some(127), "{shell_output:?}");
1312        assert_eq!(output.stdout, shell_output.stdout);
1313        assert_eq!(output.stderr, shell_output.stderr);
1314        assert!(String::from_utf8_lossy(&output.stderr).contains(&missing));
1315    }
1316
1317    use super::*;
1318    use std::fs;
1319    use std::os::unix::fs::PermissionsExt;
1320
1321    struct EnvVarGuard {
1322        key: &'static str,
1323        old_value: Option<OsString>,
1324    }
1325
1326    impl EnvVarGuard {
1327        fn set(key: &'static str, value: &str) -> Self {
1328            let old_value = std::env::var_os(key);
1329            std::env::set_var(key, value);
1330            Self { key, old_value }
1331        }
1332    }
1333
1334    impl Drop for EnvVarGuard {
1335        fn drop(&mut self) {
1336            if let Some(val) = &self.old_value {
1337                std::env::set_var(self.key, val);
1338            } else {
1339                std::env::remove_var(self.key);
1340            }
1341        }
1342    }
1343
1344    fn write_executable_shim(path: &Path, body: &str) {
1345        crate::executable_cache::write_executable(path, body.as_bytes()).unwrap();
1346    }
1347
1348    #[test]
1349    fn probe_entries_are_appended_after_current_entries_without_duplicates() {
1350        let current = OsStr::new("/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin");
1351        let login = OsString::from("/usr/bin:/custom/bin:/opt/homebrew/bin");
1352
1353        let effective = merge_current_and_login_path(current, &login);
1354
1355        assert_eq!(
1356            effective,
1357            OsString::from("/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/custom/bin")
1358        );
1359    }
1360
1361    #[test]
1362    fn probe_shell_flags_cover_login_and_interactive_startup_files() {
1363        assert_eq!(probe_shell_flags(Path::new("/bin/zsh")), "-lic");
1364        assert_eq!(probe_shell_flags(Path::new("/bin/bash")), "-lic");
1365        assert_eq!(
1366            probe_shell_flags(Path::new("/opt/homebrew/bin/fish")),
1367            "-lic"
1368        );
1369    }
1370
1371    #[test]
1372    fn marker_extraction_ignores_shell_startup_noise() {
1373        let output = b"banner before\n__AFT_PATH_BEGIN__/custom/bin:/usr/bin__AFT_PATH_END__\nbanner after\n";
1374
1375        assert_eq!(
1376            extract_probe_path(output),
1377            Some(OsString::from("/custom/bin:/usr/bin"))
1378        );
1379    }
1380
1381    /// Generous budget for tests that assert a PROBE SUCCEEDS (spawning a
1382    /// real shim): decoupled from the production timeout so machine load
1383    /// cannot convert a working probe into a test failure.
1384    const TEST_PROBE_SUCCESS_TIMEOUT: Duration = Duration::from_secs(30);
1385
1386    #[test]
1387    fn zsh_probe_uses_interactive_login_and_reads_zshrc() {
1388        let _guard = crate::test_env::process_env_lock();
1389        let dir = tempfile::tempdir().unwrap();
1390        let home = dir.path().join("home");
1391        let custom_bin = home.join(".custom/bin");
1392        let shell = dir.path().join("zsh");
1393        fs::create_dir_all(&custom_bin).unwrap();
1394        fs::write(
1395            home.join(".zshrc"),
1396            format!(
1397                "printf 'banner before\n'; export PATH=\"$PATH:{}\"; printf 'banner after\n'\n",
1398                custom_bin.display()
1399            ),
1400        )
1401        .unwrap();
1402        write_executable_shim(
1403            &shell,
1404            r#"#!/bin/sh
1405if [ "$1" != '-lic' ]; then
1406  exit 64
1407fi
1408if [ -f "$ZDOTDIR/.zshrc" ]; then
1409  . "$ZDOTDIR/.zshrc"
1410fi
1411eval "$2"
1412"#,
1413        );
1414
1415        let _path_guard = EnvVarGuard::set("PATH", "/usr/bin:/bin");
1416        let _home_guard = EnvVarGuard::set("HOME", home.to_str().unwrap());
1417        let _zdotdir_guard = EnvVarGuard::set("ZDOTDIR", home.to_str().unwrap());
1418        // Warm the freshly written shim with one untimed exec: macOS assesses
1419        // never-seen executables on first exec (syspolicyd), which can take
1420        // tens of seconds on a loaded machine and would read as a probe
1421        // failure. The timed probe below then measures the shell, not the OS.
1422        let _ = Command::new(&shell).arg("--warmup").output();
1423        // Success-asserting probe tests use a generous budget: the production
1424        // 3s timeout is a startup-cost bound, and a loaded machine can push a
1425        // real shim spawn past it, which reads as a false test failure.
1426        let probed = probe_login_shell_path_once(&shell, TEST_PROBE_SUCCESS_TIMEOUT);
1427
1428        assert_eq!(
1429            probed,
1430            Some(OsString::from(format!(
1431                "/usr/bin:/bin:{}",
1432                custom_bin.display()
1433            )))
1434        );
1435    }
1436
1437    #[test]
1438    fn invalid_probe_paths_are_rejected() {
1439        let rejected = vec![
1440            OsString::new(),
1441            OsString::from("/fake/login/bin\n/usr/bin"),
1442            OsString::from("relative/bin:~/bin:"),
1443            OsString::from_vec(b"/fake/login/bin\0/usr/bin".to_vec()),
1444            OsString::from("/usr/bin /bin /opt/homebrew/bin"), // fish-shaped space-joined
1445        ];
1446
1447        for probe_path in rejected {
1448            assert!(!login_path_is_acceptable(&probe_path));
1449        }
1450    }
1451
1452    #[test]
1453    fn login_path_mixed_probe_retains_only_absolute_entries() {
1454        let _guard = crate::test_env::process_env_lock();
1455        let dir = tempfile::tempdir().unwrap();
1456        let shell = dir.path().join("shell");
1457        write_executable_shim(&shell, "#!/bin/sh\nprintf '%s' '__AFT_PATH_BEGIN__/custom/bin:./local:~/bin::/usr/bin:__AFT_PATH_END__'\n");
1458        let _candidates =
1459            EnvVarGuard::set("AFT_TEST_LOGIN_SHELL_CANDIDATES", shell.to_str().unwrap());
1460        assert_eq!(
1461            probe_login_shell_path_with_budgets(
1462                TEST_PROBE_SUCCESS_TIMEOUT,
1463                TEST_PROBE_SUCCESS_TIMEOUT,
1464            )
1465            .path,
1466            Some(OsString::from("/custom/bin:/usr/bin"))
1467        );
1468    }
1469
1470    #[cfg(target_os = "linux")]
1471    #[test]
1472    fn login_shell_probe_survives_concurrent_fork_stress() {
1473        use std::os::fd::AsRawFd;
1474        const ITERATIONS: usize = 128;
1475
1476        fn cloexec_pipe() -> (libc::c_int, libc::c_int) {
1477            let mut fds = [0; 2];
1478            assert_eq!(unsafe { libc::pipe2(fds.as_mut_ptr(), libc::O_CLOEXEC) }, 0);
1479            (fds[0], fds[1])
1480        }
1481        fn write_byte(fd: libc::c_int) {
1482            assert_eq!(unsafe { libc::write(fd, b"x".as_ptr().cast(), 1) }, 1);
1483        }
1484        fn read_byte(fd: libc::c_int) {
1485            let mut byte = 0u8;
1486            assert_eq!(
1487                unsafe { libc::read(fd, (&mut byte as *mut u8).cast(), 1) },
1488                1
1489            );
1490        }
1491
1492        let dir = tempfile::tempdir().unwrap();
1493        let shell = dir.path().join("shell");
1494        let body = format!(
1495            "#!/bin/sh\n#{}\nprintf '%s' '__AFT_PATH_BEGIN__/custom/bin:/usr/bin__AFT_PATH_END__'\n",
1496            "x".repeat(64 * 1024)
1497        );
1498        write_executable_shim(&shell, &body);
1499
1500        let expected = Some(OsString::from("/custom/bin:/usr/bin"));
1501        let mut failed_probe = None;
1502        for _ in 0..ITERATIONS {
1503            fs::write(&shell, &body).unwrap();
1504            let writable = fs::OpenOptions::new().write(true).open(&shell).unwrap();
1505            let writable_fd = writable.as_raw_fd();
1506            // The child holds its copy of the writable descriptor until the
1507            // test writes to `release`, reproducing the fork-to-exec window
1508            // that makes a concurrent shell spawn busy. It then closes the
1509            // descriptor and reports that on `closed`. No timing is involved.
1510            let (release_read, release_write) = cloexec_pipe();
1511            let (closed_read, closed_write) = cloexec_pipe();
1512            let pid = unsafe { libc::fork() };
1513            if pid == 0 {
1514                // Only async-signal-safe calls between fork and _exit.
1515                unsafe {
1516                    let mut byte = 0u8;
1517                    libc::read(release_read, (&mut byte as *mut u8).cast(), 1);
1518                    libc::close(writable_fd);
1519                    libc::write(closed_write, b"x".as_ptr().cast(), 1);
1520                    libc::_exit(0);
1521                }
1522            }
1523            assert!(pid > 0, "fork failed with {pid}");
1524            unsafe {
1525                libc::close(release_read);
1526                libc::close(closed_write);
1527            }
1528            drop(writable);
1529
1530            let error = Command::new(&shell)
1531                .spawn()
1532                .expect_err("the forked child should still hold the writable file descriptor");
1533            assert_eq!(
1534                error.kind(),
1535                std::io::ErrorKind::ExecutableFileBusy,
1536                "expected Linux ETXTBSY, got {error}"
1537            );
1538
1539            // The probe's first spawn finds the file busy too. Its retry hook
1540            // releases the child and waits until the descriptor is closed, so
1541            // the retry that follows must succeed.
1542            let busy_retries = std::rc::Rc::new(std::cell::Cell::new(0usize));
1543            let hook_retries = std::rc::Rc::clone(&busy_retries);
1544            let actual = super::busy_retry_hook::with(
1545                move || {
1546                    hook_retries.set(hook_retries.get() + 1);
1547                    if hook_retries.get() == 1 {
1548                        write_byte(release_write);
1549                        read_byte(closed_read);
1550                    }
1551                },
1552                || probe_login_shell_path_once(&shell, Duration::from_secs(10)),
1553            );
1554            if busy_retries.get() == 0 {
1555                // The probe never saw the file busy, so the child was never
1556                // released by the hook. Release it here before reaping.
1557                write_byte(release_write);
1558            }
1559            unsafe {
1560                libc::waitpid(pid, std::ptr::null_mut(), 0);
1561                libc::close(release_write);
1562                libc::close(closed_read);
1563            }
1564            assert!(
1565                busy_retries.get() >= 1,
1566                "the probe's first spawn must find the file busy and retry"
1567            );
1568            if actual != expected {
1569                failed_probe = Some(actual);
1570                break;
1571            }
1572        }
1573
1574        assert_eq!(
1575            failed_probe, None,
1576            "login-shell PATH probe failed during a fork/spawn race"
1577        );
1578        println!("observed ETXTBSY and recovered across {ITERATIONS} concurrent fork/probe cycles");
1579    }
1580
1581    #[test]
1582    fn login_path_failed_cache_is_not_authoritative() {
1583        let _guard = crate::test_env::process_env_lock();
1584        let dir = tempfile::tempdir().unwrap();
1585        let _home = EnvVarGuard::set("HOME", dir.path().to_str().unwrap());
1586        let shell = PathBuf::from("/bin/bash");
1587        let cache = EffectivePathCache {
1588            schema: EFFECTIVE_PATH_CACHE_SCHEMA,
1589            shell: shell.to_string_lossy().into_owned(),
1590            path: None,
1591            probed_at_unix: unix_timestamp_secs(),
1592            inputs: shell_startup_inputs(&shell),
1593        };
1594        assert!(!cache_matches_current_shell(&cache, &[shell]));
1595    }
1596
1597    #[test]
1598    fn inline_probe_total_budget_caps_multiple_hanging_candidates() {
1599        let _guard = crate::test_env::process_env_lock();
1600        let dir = tempfile::tempdir().expect("create tempdir");
1601        let first = dir.path().join("first-shell");
1602        let second = dir.path().join("second-shell");
1603        write_executable_shim(&first, "#!/bin/sh\nsleep 10\n");
1604        write_executable_shim(&second, "#!/bin/sh\nsleep 10\n");
1605        let candidates = std::env::join_paths([&first, &second]).unwrap();
1606        let _candidates_guard = EnvVarGuard::set(
1607            "AFT_TEST_LOGIN_SHELL_CANDIDATES",
1608            candidates.to_str().unwrap(),
1609        );
1610
1611        let started = Instant::now();
1612        let result = probe_login_shell_path();
1613
1614        assert!(result.path.is_none());
1615        assert!(
1616            started.elapsed() < Duration::from_millis(4500),
1617            "two hanging candidates exceeded the four-second total budget"
1618        );
1619    }
1620
1621    #[test]
1622    fn login_shell_probe_times_out() {
1623        let dir = tempfile::tempdir().expect("create tempdir");
1624        let shell = dir.path().join("slow-login-shell");
1625        write_executable_shim(
1626            &shell,
1627            "#!/bin/sh\nsleep 10\nprintf '%s' '/fake/login/bin:/usr/bin:/bin'\n",
1628        );
1629
1630        let started = Instant::now();
1631        let probed = probe_login_shell_path_once(&shell, LOGIN_SHELL_PATH_PROBE_TIMEOUT);
1632
1633        assert!(probed.is_none());
1634        // Upper bound proves the 3s timeout fired instead of waiting out the
1635        // 10s sleep; 8s leaves headroom for a loaded machine to reap the kill.
1636        assert!(
1637            started.elapsed() < Duration::from_secs(8),
1638            "login-shell PATH probe exceeded the 8s test budget"
1639        );
1640    }
1641
1642    #[test]
1643    fn test_login_shell_candidates_includes_fallbacks() {
1644        let _guard = crate::test_env::process_env_lock();
1645        let _shell_guard = EnvVarGuard::set("SHELL", "/opt/zerobrew/bin/fish");
1646        let candidates = login_shell_candidates();
1647        assert_eq!(candidates[0], PathBuf::from("/opt/zerobrew/bin/fish"));
1648        assert!(candidates.contains(&PathBuf::from("/bin/zsh")));
1649        assert!(candidates.contains(&PathBuf::from("/bin/bash")));
1650    }
1651
1652    #[test]
1653    fn effective_path_cache_round_trips_and_rejects_changed_inputs() {
1654        let _guard = crate::test_env::process_env_lock();
1655        let temp = tempfile::tempdir().unwrap();
1656        let home = temp.path().join("home");
1657        fs::create_dir_all(&home).unwrap();
1658        let _home_guard = EnvVarGuard::set("HOME", home.to_str().unwrap());
1659        let shell = PathBuf::from("/bin/bash");
1660        let cache_path = temp.path().join("effective-path.json");
1661        let cache = EffectivePathCache {
1662            schema: EFFECTIVE_PATH_CACHE_SCHEMA,
1663            shell: shell.to_string_lossy().into_owned(),
1664            path: Some("/custom/bin:/usr/bin:/bin".to_string()),
1665            probed_at_unix: unix_timestamp_secs(),
1666            inputs: shell_startup_inputs(&shell),
1667        };
1668
1669        write_effective_path_cache(&cache_path, &cache).unwrap();
1670        let restored = read_effective_path_cache(&cache_path).unwrap();
1671        assert!(cache_matches_current_shell(&restored, &[shell.clone()]));
1672
1673        fs::write(home.join(".bashrc"), "export PATH=changed\n").unwrap();
1674        assert!(!cache_matches_current_shell(&restored, &[shell]));
1675    }
1676
1677    #[test]
1678    fn probe_failure_falls_back_to_current_path_and_appends_standard_dirs() {
1679        let home = Path::new("/home/alice");
1680        let current = OsStr::new("/usr/bin:/bin");
1681        let missing_shell = Path::new("/nonexistent/shell");
1682
1683        assert!(probe_login_shell_path_once(missing_shell, Duration::from_millis(10)).is_none());
1684
1685        let enriched = append_missing_standard_dirs(current, Some(home.as_os_str()), |dir| {
1686            dir == Path::new("/home/alice/.bun/bin")
1687        });
1688        assert_eq!(
1689            enriched,
1690            OsString::from("/usr/bin:/bin:/home/alice/.bun/bin")
1691        );
1692    }
1693
1694    #[test]
1695    fn test_append_missing_standard_dirs() {
1696        let home = OsStr::new("/home/alice");
1697        let path = OsStr::new("/usr/bin:/bin");
1698
1699        // Mock dir_exists to return true only for ~/.bun/bin
1700        let dir_exists = |dir: &Path| dir == Path::new("/home/alice/.bun/bin");
1701
1702        let enriched = append_missing_standard_dirs(path, Some(home), dir_exists);
1703        assert_eq!(
1704            enriched,
1705            OsString::from("/usr/bin:/bin:/home/alice/.bun/bin")
1706        );
1707    }
1708
1709    #[test]
1710    fn test_append_missing_standard_dirs_dedup_and_order() {
1711        let home = OsStr::new("/home/alice");
1712        // ~/.bun/bin is already in the path, but /opt/homebrew/bin is missing
1713        let path = OsStr::new("/home/alice/.bun/bin:/usr/bin:/bin");
1714
1715        let dir_exists = |dir: &Path| {
1716            dir == Path::new("/home/alice/.bun/bin") || dir == Path::new("/opt/homebrew/bin")
1717        };
1718
1719        let enriched = append_missing_standard_dirs(path, Some(home), dir_exists);
1720        // /opt/homebrew/bin should be appended at the end, and ~/.bun/bin should not be duplicated
1721        assert_eq!(
1722            enriched,
1723            OsString::from("/home/alice/.bun/bin:/usr/bin:/bin:/opt/homebrew/bin")
1724        );
1725    }
1726
1727    #[test]
1728    fn reaper_thread_reaps_spawned_child() {
1729        let mut command = Command::new("sh");
1730        command
1731            .arg("-c")
1732            .arg("exit 0")
1733            .stdin(Stdio::null())
1734            .stdout(Stdio::null())
1735            .stderr(Stdio::null());
1736        let pid = spawn_reaped(&mut command).expect("helper spawn failed");
1737
1738        // A finished child that nobody waited on stays in the process table
1739        // as a zombie and still answers kill(pid, 0); only a reaped child
1740        // disappears. Poll with a bounded deadline until the pid is gone,
1741        // which proves the reaper thread called wait().
1742        let deadline = Instant::now() + Duration::from_secs(30);
1743        loop {
1744            let status = unsafe { libc::kill(pid as libc::pid_t, 0) };
1745            if status == -1 {
1746                let error = std::io::Error::last_os_error();
1747                assert_eq!(
1748                    error.raw_os_error(),
1749                    Some(libc::ESRCH),
1750                    "kill(pid, 0) failed with an unexpected error: {error}"
1751                );
1752                break;
1753            }
1754            assert!(
1755                Instant::now() < deadline,
1756                "child {pid} was still in the process table after the reap deadline"
1757            );
1758            std::thread::sleep(Duration::from_millis(10));
1759        }
1760    }
1761}