Skip to main content

artifactize_tools/platform/
program.rs

1//! Literal program lookup, shared by preflight and process launches.
2
3use crate::platform;
4use std::{
5    env,
6    ffi::{OsStr, OsString},
7    io,
8    path::{Path, PathBuf},
9};
10
11/// The variable listing the directories a bare program name is looked up in.
12const SEARCH_PATH: &str = "PATH";
13/// The Windows variable listing the extensions an extensionless name is tried with.
14const EXTENSIONS: &str = "PATHEXT";
15
16/// Resolve against the PATH and, on Windows, PATHEXT that a started program receives (see
17/// [`super::environment::user`]). A bare name never implicitly searches the working directory;
18/// relative PATH entries are based on `cwd`.
19pub fn resolve(program: &Path, cwd: &Path) -> io::Result<PathBuf> {
20    resolve_with(program, cwd, super::environment::var)
21}
22
23/// Resolve using the environment that the child will receive, not the caller's PATH:
24/// `variable` reads one variable of that environment.
25pub fn resolve_with(
26    program: &Path,
27    cwd: &Path,
28    variable: impl Fn(&str) -> Option<OsString>,
29) -> io::Result<PathBuf> {
30    resolve_from(
31        program,
32        cwd,
33        variable(SEARCH_PATH).as_deref(),
34        variable(EXTENSIONS).as_deref(),
35    )
36}
37
38fn resolve_from(
39    program: &Path,
40    cwd: &Path,
41    path: Option<&OsStr>,
42    pathext: Option<&OsStr>,
43) -> io::Result<PathBuf> {
44    lookup_paths(program, cwd, path, pathext)
45        .into_iter()
46        .find(|candidate| platform::is_executable(candidate))
47        .ok_or_else(|| {
48            io::Error::new(
49                io::ErrorKind::NotFound,
50                format!(
51                    "Program is unavailable: {}",
52                    super::files::path_text(program)
53                ),
54            )
55        })
56}
57
58fn lookup_paths(
59    program: &Path,
60    cwd: &Path,
61    path: Option<&OsStr>,
62    pathext: Option<&OsStr>,
63) -> Vec<PathBuf> {
64    let candidates = candidates_from(program, pathext);
65    if program.is_absolute() || program.components().count() > 1 {
66        return candidates
67            .into_iter()
68            .map(|candidate| cwd.join(candidate))
69            .collect();
70    }
71    env::split_paths(path.unwrap_or_default())
72        .flat_map(|directory| {
73            let directory = cwd.join(directory);
74            candidates
75                .iter()
76                .map(move |candidate| directory.join(candidate))
77        })
78        .collect()
79}
80
81/// Candidate paths in lookup order, for the environment `variable` reads. Scoped callers
82/// validate each candidate inside their own access boundary before allowing it to reach a
83/// process launcher.
84pub fn candidates(program: &Path, variable: impl Fn(&str) -> Option<OsString>) -> Vec<PathBuf> {
85    candidates_from(program, variable(EXTENSIONS).as_deref())
86}
87
88fn candidates_from(program: &Path, pathext: Option<&OsStr>) -> Vec<PathBuf> {
89    if platform::USES_PATHEXT && program.extension().is_none() {
90        pathext_candidates(program, pathext)
91    } else {
92        vec![program.to_owned()]
93    }
94}
95
96/// The Windows default when the variable is absent, not when explicitly empty.
97const DEFAULT_PATHEXT: &str = ".COM;.EXE;.BAT;.CMD";
98
99/// One candidate per `PATHEXT` suffix, in its order.
100fn pathext_candidates(program: &Path, pathext: Option<&OsStr>) -> Vec<PathBuf> {
101    let pathext = pathext.unwrap_or_else(|| OsStr::new(DEFAULT_PATHEXT));
102    // Split the native string itself, so an extension keeps every byte or UTF-16 unit it was
103    // given rather than a lossy text copy.
104    split_list(pathext)
105        .into_iter()
106        .filter(|extension| {
107            let bytes = extension.as_encoded_bytes();
108            bytes.first() == Some(&b'.') && !bytes.iter().any(|byte| matches!(byte, b'/' | b'\\'))
109        })
110        .map(|extension| {
111            let mut candidate = program.as_os_str().to_owned();
112            candidate.push(extension);
113            PathBuf::from(candidate)
114        })
115        .collect()
116}
117
118/// The `;`-separated entries of a native list, each exactly as the OS string holds it.
119#[cfg(windows)]
120fn split_list(list: &OsStr) -> Vec<OsString> {
121    use std::os::windows::ffi::{OsStrExt, OsStringExt};
122    let units: Vec<u16> = list.encode_wide().collect();
123    units
124        .split(|unit| *unit == u16::from(b';'))
125        .map(OsString::from_wide)
126        .collect()
127}
128
129/// The `;`-separated entries of a native list, each exactly as the OS string holds it.
130#[cfg(unix)]
131fn split_list(list: &OsStr) -> Vec<OsString> {
132    use std::os::unix::ffi::{OsStrExt, OsStringExt};
133    list.as_bytes()
134        .split(|byte| *byte == b';')
135        .map(|entry| OsString::from_vec(entry.to_vec()))
136        .collect()
137}
138
139#[cfg(test)]
140mod tests {
141    use super::*;
142
143    #[test]
144    fn lookup_uses_path_order_relative_to_child_cwd_and_never_implicit_local_search() {
145        let root = crate::test_os::tempdir();
146        for directory in ["first", "second"] {
147            std::fs::create_dir(root.path().join(directory)).unwrap();
148            crate::test_os::lookup_program(&root.path().join(directory), "shim", None);
149        }
150        let program = crate::test_os::executable_name("shim");
151        let path = OsString::from(crate::test_os::path_list(["second", "first"]));
152        assert_eq!(
153            resolve_with(Path::new(&program), root.path(), |name| (name
154                == SEARCH_PATH)
155                .then(|| path.clone()))
156            .unwrap(),
157            root.path().join("second").join(&program)
158        );
159        assert!(resolve_with(Path::new(&program), root.path(), |_| None).is_err());
160    }
161
162    // Only Windows applies PATHEXT when producing executable candidates.
163    #[cfg(windows)]
164    #[test]
165    fn pathext_candidates_keep_the_variable_order_and_skip_unsafe_suffixes() {
166        assert_eq!(
167            candidates(Path::new("dir/shim"), |_| Some(".CMD;bad;.a/b;.EXE".into())),
168            [PathBuf::from("dir/shim.CMD"), PathBuf::from("dir/shim.EXE")]
169        );
170        assert_eq!(
171            candidates(Path::new("shim"), |_| None),
172            [".COM", ".EXE", ".BAT", ".CMD"].map(|suffix| PathBuf::from(format!("shim{suffix}")))
173        );
174    }
175
176    // Only Windows looks up extensionless names with PATHEXT, on a case-insensitive volume.
177    #[cfg(windows)]
178    #[test]
179    fn extensionless_names_follow_pathext_order_not_exe_preference() {
180        let root = crate::test_os::tempdir();
181        for extension in ["cmd", "exe", "bat"] {
182            crate::test_os::lookup_program(root.path(), "shim", Some(extension));
183        }
184        let path = OsString::from(crate::test_os::path_list([root.path()]));
185        assert_eq!(
186            resolve_with(Path::new("shim"), root.path(), |name| match name {
187                SEARCH_PATH => Some(path.clone()),
188                EXTENSIONS => Some(".CMD;.EXE".into()),
189                _ => None,
190            })
191            .unwrap(),
192            root.path().join("shim.CMD")
193        );
194        assert_eq!(
195            resolve_with(Path::new("shim"), root.path(), |name| match name {
196                SEARCH_PATH => Some(path.clone()),
197                EXTENSIONS => Some(".BAT;.CMD".into()),
198                _ => None,
199            })
200            .unwrap(),
201            root.path().join("shim.BAT")
202        );
203    }
204}