Skip to main content

vtcode_commons/
spawn_program.rs

1//! Build child commands that Rust's standard library can launch with
2//! `posix_spawn` instead of falling back to `fork` + `exec`.
3//!
4//! `fork` cost grows with the parent's address space (page tables and
5//! copy-on-write mappings), so a long-running, memory-heavy agent pays more for
6//! every child it starts. `std::process::Command` (Rust 1.100) uses
7//! `posix_spawnp` unless, among other cases:
8//!
9//! - the child environment changes `PATH` (`env_clear()` counts) and the
10//!   program is a bare name, because `posix_spawnp` would search the parent's
11//!   `PATH` instead of the child's;
12//! - on Apple platforms, a relative program containing `/` is combined with
13//!   `current_dir`, because of a historical `posix_spawnp` bug.
14//!
15//! Resolving the program to an absolute path up front, using the same search
16//! `execvp` would perform in the child, keeps both cases on `posix_spawn`
17//! without changing which executable runs or what `argv[0]` it sees.
18
19use std::ffi::OsStr;
20use std::path::{Path, PathBuf};
21
22/// The `PATH` the child process will see.
23#[derive(Debug, Clone, Copy)]
24pub enum ChildPath<'a> {
25    /// The child inherits the parent environment's `PATH` unchanged.
26    Inherited,
27    /// The child environment sets `PATH` to this value.
28    Set(&'a OsStr),
29    /// The child environment has no `PATH` (for example `env_clear()` without
30    /// re-adding it); `execvp` then uses a libc-specific default.
31    Unset,
32}
33
34impl<'a> ChildPath<'a> {
35    /// Describe a child whose environment is exactly `env`.
36    pub fn from_exact_env<K, V>(env: impl IntoIterator<Item = (&'a K, &'a V)>) -> Self
37    where
38        K: AsRef<OsStr> + ?Sized + 'a,
39        V: AsRef<OsStr> + ?Sized + 'a,
40    {
41        // The last entry wins, matching how `Command::env` applies repeated keys.
42        env.into_iter()
43            .filter(|(key, _)| key.as_ref() == OsStr::new("PATH"))
44            .last()
45            .map_or(Self::Unset, |(_, value)| Self::Set(value.as_ref()))
46    }
47}
48
49/// Create a `Command` for `program` that stays on the `posix_spawn` path when
50/// the program can be resolved the way the child would resolve it.
51///
52/// When the program is rewritten to an absolute path, `argv[0]` keeps the
53/// original `program`. Otherwise the command is exactly `Command::new(program)`,
54/// so launch behavior and errors are unchanged.
55#[must_use]
56pub fn command_for_spawn(program: &OsStr, child_path: ChildPath<'_>, cwd: Option<&Path>) -> std::process::Command {
57    let Some(resolved) = resolve_spawn_program(program, child_path, cwd) else {
58        return std::process::Command::new(program);
59    };
60    let mut command = std::process::Command::new(resolved);
61    #[cfg(unix)]
62    {
63        use std::os::unix::process::CommandExt;
64        let _ = command.arg0(program);
65    }
66    command
67}
68
69/// Resolve `program` to the absolute executable path the child would run.
70///
71/// Returns `None` when no rewrite is needed (absolute program, inherited
72/// `PATH` with a bare name), when the child's search is libc-defined (`Unset`),
73/// or when no candidate exists, leaving the original behavior in place.
74#[must_use]
75pub fn resolve_spawn_program(program: &OsStr, child_path: ChildPath<'_>, cwd: Option<&Path>) -> Option<PathBuf> {
76    if !cfg!(unix) || program.is_empty() {
77        return None;
78    }
79    let program_path = Path::new(program);
80    if program_path.is_absolute() {
81        return None;
82    }
83    let has_separator = program.as_encoded_bytes().contains(&b'/');
84    if has_separator {
85        // Only the cwd case needs a rewrite; without one, std already spawns
86        // relative paths with `posix_spawnp`.
87        return cwd
88            .and_then(|cwd| child_base_dir(Some(cwd)))
89            .map(|base| base.join(program_path));
90    }
91    let ChildPath::Set(search_path) = child_path else {
92        return None;
93    };
94    let base = child_base_dir(cwd)?;
95    search_path_like_execvp(program, search_path, &base)
96}
97
98/// The child's absolute working directory: `cwd` applies relative to the
99/// parent's current directory, exactly as `chdir` in the child would.
100fn child_base_dir(cwd: Option<&Path>) -> Option<PathBuf> {
101    match cwd {
102        Some(cwd) if cwd.is_absolute() => Some(cwd.to_path_buf()),
103        Some(cwd) => std::env::current_dir().ok().map(|current| current.join(cwd)),
104        None => std::env::current_dir().ok(),
105    }
106}
107
108/// Mirror `execvp`: try each `PATH` entry in order (an empty entry means the
109/// current directory, relative entries are relative to it, no `~` expansion)
110/// and take the first regular file this process may execute.
111fn search_path_like_execvp(program: &OsStr, search_path: &OsStr, base: &Path) -> Option<PathBuf> {
112    std::env::split_paths(search_path)
113        .map(|entry| {
114            if entry.as_os_str().is_empty() {
115                base.join(program)
116            } else {
117                base.join(entry).join(program)
118            }
119        })
120        .find(|candidate| is_executable_file(candidate))
121}
122
123/// A regular file this process may execute. Permission is checked like
124/// `execve` does (effective IDs, owner/group/other classes), not by "any
125/// execute bit", so a candidate `execvp` would skip with `EACCES` is skipped
126/// here too instead of being chosen and then failing to launch.
127#[cfg(unix)]
128#[expect(unsafe_code, reason = "faccessat has no safe std wrapper")]
129fn is_executable_file(path: &Path) -> bool {
130    use std::os::unix::ffi::OsStrExt;
131    if !std::fs::metadata(path).is_ok_and(|metadata| metadata.is_file()) {
132        return false;
133    }
134    let Ok(c_path) = std::ffi::CString::new(path.as_os_str().as_bytes()) else {
135        return false;
136    };
137    // SAFETY: `c_path` is a live NUL-terminated string for the duration of the
138    // call; `faccessat` only reads it and writes nothing.
139    unsafe { libc::faccessat(libc::AT_FDCWD, c_path.as_ptr(), libc::X_OK, libc::AT_EACCESS) == 0 }
140}
141
142#[cfg(not(unix))]
143fn is_executable_file(_path: &Path) -> bool {
144    false
145}
146
147#[cfg(all(test, unix))]
148mod tests;