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