Skip to main content

artifactize_foundation/platform/
program.rs

1//! Literal program lookup, shared by preflight and process launches.
2
3use std::{
4    env,
5    ffi::{OsStr, OsString},
6    io,
7    path::{Path, PathBuf},
8};
9
10/// The variable listing the directories a bare program name is looked up in.
11const SEARCH_PATH: &str = "PATH";
12/// The Windows variable listing the extensions an extensionless name is tried with.
13const EXTENSIONS: &str = "PATHEXT";
14
15/// Look up a pathname using the child environment, not the caller's PATH. This is for
16/// inspection only. Use [`super::process::resolve_with`] to select an image for execution.
17/// `variable` may be a case-sensitive lookup into a stored environment snapshot.
18pub fn resolve_with(
19    program: &Path,
20    cwd: &Path,
21    variable: impl Fn(&str) -> Option<OsString>,
22) -> io::Result<PathBuf> {
23    resolve_from(
24        program,
25        cwd,
26        lookup_variable(&variable, SEARCH_PATH).as_deref(),
27        extensions(&variable).as_deref(),
28    )
29}
30
31#[cfg(unix)]
32fn lookup_variable(variable: &impl Fn(&str) -> Option<OsString>, name: &str) -> Option<OsString> {
33    variable(name)
34}
35
36#[cfg(windows)]
37fn lookup_variable(variable: &impl Fn(&str) -> Option<OsString>, name: &str) -> Option<OsString> {
38    // Our only lookup keys are the short, ASCII-alphabetic PATH and PATHEXT. Try their
39    // spellings in reverse map order, so the last entry wins just as in Command::envs.
40    // A native environment lookup succeeds on the first spelling whenever set.
41    let mut spelling = name.as_bytes().to_owned();
42    (0..(1 << name.len())).rev().find_map(|variant| {
43        for (bit, byte) in spelling.iter_mut().rev().enumerate() {
44            *byte = if variant & (1 << bit) == 0 {
45                byte.to_ascii_uppercase()
46            } else {
47                byte.to_ascii_lowercase()
48            };
49        }
50        variable(std::str::from_utf8(&spelling).expect("ASCII environment key"))
51    })
52}
53
54fn extensions(variable: &impl Fn(&str) -> Option<OsString>) -> Option<OsString> {
55    USES_PATHEXT
56        .then(|| lookup_variable(variable, EXTENSIONS))
57        .flatten()
58}
59
60fn resolve_from(
61    program: &Path,
62    cwd: &Path,
63    path: Option<&OsStr>,
64    pathext: Option<&OsStr>,
65) -> io::Result<PathBuf> {
66    lookup_paths(program, cwd, path, pathext)
67        .into_iter()
68        .find(|candidate| is_executable(candidate))
69        .ok_or_else(|| {
70            io::Error::new(
71                io::ErrorKind::NotFound,
72                format!(
73                    "Program is unavailable: {}",
74                    super::files::path_text(program)
75                ),
76            )
77        })
78}
79
80fn lookup_paths(
81    program: &Path,
82    cwd: &Path,
83    path: Option<&OsStr>,
84    pathext: Option<&OsStr>,
85) -> Vec<PathBuf> {
86    let candidates = candidates_from(program, pathext);
87    if program.has_root()
88        || program.components().count() > 1
89        || matches!(
90            program.components().next(),
91            Some(std::path::Component::Prefix(_))
92        )
93    {
94        return candidates
95            .into_iter()
96            .filter_map(|candidate| anchor(cwd, &candidate))
97            .collect();
98    }
99    path.into_iter()
100        .flat_map(env::split_paths)
101        .filter_map(|directory| anchor(cwd, &directory))
102        .flat_map(|directory| {
103            candidates
104                .iter()
105                .map(move |candidate| directory.join(candidate))
106        })
107        .collect()
108}
109
110#[cfg(unix)]
111fn anchor(cwd: &Path, path: &Path) -> Option<PathBuf> {
112    Some(cwd.join(path))
113}
114
115#[cfg(windows)]
116fn anchor(cwd: &Path, path: &Path) -> Option<PathBuf> {
117    use std::path::{Component, Prefix};
118
119    let mut components = path.components();
120    if let Some(Component::Prefix(prefix)) = components.next()
121        && !path.is_absolute()
122    {
123        // Resolve C:tool against the *child's* directory on C:, never the parent's
124        // implicit per-drive working directory. No base was given for other drives.
125        let drive = |prefix| match prefix {
126            Prefix::Disk(drive) | Prefix::VerbatimDisk(drive) => Some(drive.to_ascii_uppercase()),
127            _ => None,
128        };
129        let Some(Component::Prefix(base)) = cwd.components().next() else {
130            return None;
131        };
132        return (cwd.is_absolute()
133            && drive(prefix.kind()).is_some()
134            && drive(prefix.kind()) == drive(base.kind()))
135        .then(|| cwd.join(components.as_path()));
136    }
137    Some(cwd.join(path))
138}
139
140/// Candidate paths in lookup order. A scoped caller validates candidates inside its own
141/// access boundary before allowing them to reach a process launcher.
142pub fn candidates(program: &Path, variable: impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
143    candidates_from(program, extensions(&variable).as_deref())
144}
145
146fn candidates_from(program: &Path, pathext: Option<&OsStr>) -> Vec<PathBuf> {
147    if USES_PATHEXT && program.extension().is_none() {
148        pathext_candidates(program, pathext)
149    } else {
150        vec![program.to_owned()]
151    }
152}
153
154/// The Windows default when the variable is absent, not when explicitly empty.
155const DEFAULT_PATHEXT: &str = ".COM;.EXE;.BAT;.CMD";
156
157/// One candidate per `PATHEXT` suffix, in its order.
158fn pathext_candidates(program: &Path, pathext: Option<&OsStr>) -> Vec<PathBuf> {
159    let pathext = pathext.unwrap_or_else(|| OsStr::new(DEFAULT_PATHEXT));
160    // Split the native string itself, so an extension keeps every byte or UTF-16 unit it was
161    // given rather than a lossy text copy.
162    split_list(pathext)
163        .into_iter()
164        .filter(|extension| {
165            let bytes = extension.as_encoded_bytes();
166            bytes.first() == Some(&b'.') && !bytes.iter().any(|byte| matches!(byte, b'/' | b'\\'))
167        })
168        .map(|extension| {
169            let mut candidate = program.as_os_str().to_owned();
170            candidate.push(extension);
171            PathBuf::from(candidate)
172        })
173        .collect()
174}
175
176/// The `;`-separated entries of a native list, each exactly as the OS string holds it.
177#[cfg(windows)]
178fn split_list(list: &OsStr) -> Vec<OsString> {
179    use std::os::windows::ffi::{OsStrExt, OsStringExt};
180    let units: Vec<u16> = list.encode_wide().collect();
181    units
182        .split(|unit| *unit == u16::from(b';'))
183        .map(OsString::from_wide)
184        .collect()
185}
186
187/// The `;`-separated entries of a native list, each exactly as the OS string holds it.
188#[cfg(unix)]
189fn split_list(list: &OsStr) -> Vec<OsString> {
190    use std::os::unix::ffi::{OsStrExt, OsStringExt};
191    list.as_bytes()
192        .split(|byte| *byte == b';')
193        .map(|entry| OsString::from_vec(entry.to_vec()))
194        .collect()
195}
196
197#[cfg(unix)]
198/// Unix names programs exactly; extensions carry no meaning for lookup.
199const USES_PATHEXT: bool = false;
200
201#[cfg(unix)]
202fn is_executable(path: &Path) -> bool {
203    use rustix::fs::{Access, AtFlags, CWD, accessat};
204
205    path.is_file() && accessat(CWD, path, Access::EXEC_OK, AtFlags::EACCESS).is_ok()
206}
207
208#[cfg(windows)]
209/// An extensionless program name is tried with each `PATHEXT` suffix.
210const USES_PATHEXT: bool = true;
211
212/// Windows has no execute bit; any regular file is a lookup candidate, including batch shims.
213#[cfg(windows)]
214fn is_executable(path: &Path) -> bool {
215    path.is_file()
216}
217
218#[cfg(test)]
219mod tests;