Skip to main content

kh_loader/
resolve.rs

1//! Install-name → host path resolution with a map allowlist.
2//!
3//! Absolute guest paths require a bottle root and never probe host `/usr/...`
4//! when `root` is `None`. Sibling paths under the executable directory remain
5//! loadable without a bottle (`@executable_path` fixtures).
6
7use std::path::{Component, Path, PathBuf};
8
9use kh_runtime::translate_path_with_root;
10
11/// Context for resolving one dependency install name.
12#[derive(Debug, Clone, Copy)]
13pub struct ResolveContext<'a> {
14    /// Bottle root (`--root` / session root). Absolute installs require this.
15    pub bottle_root: Option<&'a Path>,
16    /// Directory containing the main executable (host path).
17    pub executable_dir: &'a Path,
18    /// Directory containing the image that holds this load command (host path).
19    pub loader_dir: &'a Path,
20    /// `LC_RPATH` strings: loader image first, then main (caller concatenates).
21    pub rpaths: &'a [String],
22}
23
24/// Failures while turning an install name into an allowlisted host path.
25#[derive(Debug, Clone, PartialEq, Eq)]
26pub enum ResolveError {
27    /// Empty install name.
28    Empty,
29    /// Path contained `..` or otherwise escaped the intended tree.
30    Escape(String),
31    /// Nested `@rpath` inside an rpath value.
32    NestedRpath,
33    /// Absolute install name but session has no bottle root.
34    NoBottle,
35    /// Resolved path is outside bottle ∪ executable_dir.
36    OutsideAllowlist(PathBuf),
37    /// Path is not valid for the host OS string model.
38    InvalidEncoding,
39}
40
41impl std::fmt::Display for ResolveError {
42    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
43        match self {
44            Self::Empty => write!(f, "empty install name"),
45            Self::Escape(p) => write!(f, "path escape: {p}"),
46            Self::NestedRpath => write!(f, "nested @rpath in LC_RPATH"),
47            Self::NoBottle => write!(f, "absolute install name requires bottle root"),
48            Self::OutsideAllowlist(p) => {
49                write!(f, "path outside map allowlist: {}", p.display())
50            }
51            Self::InvalidEncoding => write!(f, "invalid path encoding"),
52        }
53    }
54}
55
56impl std::error::Error for ResolveError {}
57
58/// Resolves `install_name` to a host path that is allowlisted for open+map.
59///
60/// Does **not** open or map the file. Callers apply soft-skip policy for most
61/// errors; [`ResolveError::InvalidEncoding`] is treated as a hard load error.
62pub fn resolve_install_name(
63    install_name: &str,
64    ctx: &ResolveContext<'_>,
65) -> Result<PathBuf, ResolveError> {
66    if install_name.is_empty() {
67        return Err(ResolveError::Empty);
68    }
69
70    let host = if let Some(rest) = install_name.strip_prefix("@executable_path/") {
71        join_no_dotdot(ctx.executable_dir, rest)?
72    } else if install_name == "@executable_path" {
73        ctx.executable_dir.to_path_buf()
74    } else if let Some(rest) = install_name.strip_prefix("@loader_path/") {
75        join_no_dotdot(ctx.loader_dir, rest)?
76    } else if install_name == "@loader_path" {
77        ctx.loader_dir.to_path_buf()
78    } else if let Some(rest) = install_name.strip_prefix("@rpath/") {
79        resolve_rpath(rest, ctx)?
80    } else if install_name == "@rpath" {
81        return Err(ResolveError::Empty);
82    } else if install_name.starts_with('@') {
83        // Unknown token — treat as escape/reject rather than relative join.
84        return Err(ResolveError::Escape(install_name.to_owned()));
85    } else if is_absolute_install_name(install_name) {
86        resolve_absolute(install_name, ctx)?
87    } else {
88        // Relative (no leading `/`, no `@` token).
89        join_no_dotdot(ctx.loader_dir, install_name)?
90    };
91
92    ensure_allowlisted(&host, ctx)?;
93    Ok(host)
94}
95
96fn is_absolute_install_name(name: &str) -> bool {
97    name.starts_with('/')
98}
99
100fn resolve_absolute(install_name: &str, ctx: &ResolveContext<'_>) -> Result<PathBuf, ResolveError> {
101    let Some(root) = ctx.bottle_root else {
102        // Host-safety: never exists()-probe absolute guest paths without a bottle.
103        return Err(ResolveError::NoBottle);
104    };
105    translate_path_with_root(Some(root), install_name).map_err(path_err_to_resolve)
106}
107
108fn resolve_rpath(rest: &str, ctx: &ResolveContext<'_>) -> Result<PathBuf, ResolveError> {
109    if rest.is_empty() {
110        return Err(ResolveError::Empty);
111    }
112
113    let mut last_allowlisted: Option<PathBuf> = None;
114
115    for rpath in ctx.rpaths {
116        if rpath.contains("@rpath") {
117            return Err(ResolveError::NestedRpath);
118        }
119        let base = expand_rpath_value(rpath, ctx)?;
120        let candidate = join_no_dotdot(&base, rest)?;
121        match ensure_allowlisted(&candidate, ctx) {
122            Ok(()) => {
123                if candidate.exists() {
124                    return Ok(candidate);
125                }
126                last_allowlisted = Some(candidate);
127            }
128            Err(ResolveError::OutsideAllowlist(_)) => {}
129            Err(err) => return Err(err),
130        }
131    }
132
133    last_allowlisted.ok_or_else(|| ResolveError::OutsideAllowlist(PathBuf::from(rest)))
134}
135
136fn expand_rpath_value(rpath: &str, ctx: &ResolveContext<'_>) -> Result<PathBuf, ResolveError> {
137    if rpath.is_empty() {
138        return Err(ResolveError::Empty);
139    }
140    if let Some(rest) = rpath.strip_prefix("@executable_path/") {
141        join_no_dotdot(ctx.executable_dir, rest)
142    } else if rpath == "@executable_path" {
143        Ok(ctx.executable_dir.to_path_buf())
144    } else if let Some(rest) = rpath.strip_prefix("@loader_path/") {
145        join_no_dotdot(ctx.loader_dir, rest)
146    } else if rpath == "@loader_path" {
147        Ok(ctx.loader_dir.to_path_buf())
148    } else if rpath.starts_with('@') {
149        Err(ResolveError::Escape(rpath.to_owned()))
150    } else if is_absolute_install_name(rpath) {
151        resolve_absolute(rpath, ctx)
152    } else {
153        // Relative LC_RPATH: anchor at loader directory.
154        join_no_dotdot(ctx.loader_dir, rpath)
155    }
156}
157
158fn join_no_dotdot(base: &Path, rest: &str) -> Result<PathBuf, ResolveError> {
159    if rest.is_empty() {
160        return Ok(base.to_path_buf());
161    }
162    let mut out = base.to_path_buf();
163    for comp in Path::new(rest).components() {
164        match comp {
165            Component::Normal(s) => out.push(s),
166            Component::CurDir => {}
167            Component::ParentDir | Component::Prefix(_) | Component::RootDir => {
168                return Err(ResolveError::Escape(rest.to_owned()));
169            }
170        }
171    }
172    Ok(out)
173}
174
175/// Map allowlist: under bottle root (when set) **or** under executable_dir.
176fn ensure_allowlisted(host: &Path, ctx: &ResolveContext<'_>) -> Result<(), ResolveError> {
177    let check = path_for_allowlist_check(host);
178
179    if let Some(root) = ctx.bottle_root {
180        let root_canon = canonicalize_or_owned(root);
181        if is_path_under(&check, &root_canon) {
182            return Ok(());
183        }
184    }
185
186    let exe_canon = canonicalize_or_owned(ctx.executable_dir);
187    if is_path_under(&check, &exe_canon) {
188        return Ok(());
189    }
190
191    Err(ResolveError::OutsideAllowlist(host.to_path_buf()))
192}
193
194fn path_for_allowlist_check(host: &Path) -> PathBuf {
195    if host.exists() {
196        return host
197            .canonicalize()
198            .unwrap_or_else(|_| lexical_normalize(host));
199    }
200    // Non-existent: canonicalize the longest existing prefix, then rejoin tail.
201    canonicalize_with_missing_tail(host)
202}
203
204fn canonicalize_with_missing_tail(host: &Path) -> PathBuf {
205    let mut components: Vec<_> = host.components().collect();
206    let mut tail = Vec::new();
207    while !components.is_empty() {
208        let prefix: PathBuf = components.iter().collect();
209        if prefix.exists() {
210            let mut base = prefix.canonicalize().unwrap_or(prefix);
211            for c in tail.into_iter().rev() {
212                base.push(c);
213            }
214            return base;
215        }
216        if let Some(Component::Normal(s)) = components.pop() {
217            tail.push(s.to_os_string());
218        } else {
219            break;
220        }
221    }
222    lexical_normalize(host)
223}
224
225fn canonicalize_or_owned(path: &Path) -> PathBuf {
226    path.canonicalize().unwrap_or_else(|_| path.to_path_buf())
227}
228
229fn lexical_normalize(path: &Path) -> PathBuf {
230    let mut out = PathBuf::new();
231    for comp in path.components() {
232        match comp {
233            Component::ParentDir => {
234                let _ = out.pop();
235            }
236            Component::CurDir => {}
237            other => out.push(other.as_os_str()),
238        }
239    }
240    out
241}
242
243fn is_path_under(path: &Path, base: &Path) -> bool {
244    path.starts_with(base)
245}
246
247fn path_err_to_resolve(err: kh_runtime::PathError) -> ResolveError {
248    match err {
249        kh_runtime::PathError::Empty => ResolveError::Empty,
250        kh_runtime::PathError::Escape(s) => ResolveError::Escape(s),
251        kh_runtime::PathError::InvalidEncoding | kh_runtime::PathError::TooLong => {
252            ResolveError::InvalidEncoding
253        }
254    }
255}
256
257#[cfg(test)]
258#[allow(clippy::expect_used, clippy::unwrap_used)]
259mod tests {
260    use super::*;
261    use std::fs::{self, File};
262    use std::io::Write;
263
264    fn ctx<'a>(
265        bottle: Option<&'a Path>,
266        exe_dir: &'a Path,
267        loader_dir: &'a Path,
268        rpaths: &'a [String],
269    ) -> ResolveContext<'a> {
270        ResolveContext {
271            bottle_root: bottle,
272            executable_dir: exe_dir,
273            loader_dir,
274            rpaths,
275        }
276    }
277
278    #[test]
279    fn absolute_without_bottle_is_no_bottle() {
280        let exe = Path::new("/tmp/kh-exe-dir");
281        let c = ctx(None, exe, exe, &[]);
282        let err = resolve_install_name("/usr/lib/libSystem.B.dylib", &c).unwrap_err();
283        assert_eq!(err, ResolveError::NoBottle);
284    }
285
286    #[test]
287    fn absolute_with_bottle_under_root() {
288        let root = std::env::temp_dir().join(format!("kh-resolve-bottle-{}", std::process::id()));
289        let lib_dir = root.join("usr/lib");
290        fs::create_dir_all(&lib_dir).unwrap();
291        let lib = lib_dir.join("libFoo.dylib");
292        File::create(&lib).unwrap().write_all(b"x").unwrap();
293
294        let exe = root.join("bin");
295        fs::create_dir_all(&exe).unwrap();
296
297        let c = ctx(Some(root.as_path()), &exe, &exe, &[]);
298        let host = resolve_install_name("/usr/lib/libFoo.dylib", &c).unwrap();
299        assert_eq!(host, lib);
300        drop(fs::remove_dir_all(root));
301    }
302
303    #[test]
304    fn executable_path_relative() {
305        let dir = std::env::temp_dir().join(format!("kh-resolve-exe-{}", std::process::id()));
306        fs::create_dir_all(&dir).unwrap();
307        let dylib = dir.join("libkh_add.dylib");
308        File::create(&dylib).unwrap().write_all(b"x").unwrap();
309
310        let c = ctx(None, &dir, &dir, &[]);
311        let host = resolve_install_name("@executable_path/libkh_add.dylib", &c).unwrap();
312        assert_eq!(host, dylib);
313        drop(fs::remove_dir_all(dir));
314    }
315
316    #[test]
317    fn loader_path_relative() {
318        // Allowlist is bottle ∪ executable_dir; nested loaders must sit under that tree.
319        let exe_dir =
320            std::env::temp_dir().join(format!("kh-resolve-loader-{}", std::process::id()));
321        let loader = exe_dir.join("Frameworks");
322        fs::create_dir_all(&loader).unwrap();
323        let dylib = loader.join("Inner.dylib");
324        File::create(&dylib).unwrap().write_all(b"x").unwrap();
325
326        let c = ctx(None, &exe_dir, &loader, &[]);
327        let host = resolve_install_name("@loader_path/Inner.dylib", &c).unwrap();
328        assert_eq!(host, dylib);
329        drop(fs::remove_dir_all(exe_dir));
330    }
331
332    #[test]
333    fn rpath_first_hit() {
334        let dir = std::env::temp_dir().join(format!("kh-resolve-rpath-{}", std::process::id()));
335        let a = dir.join("a");
336        let b = dir.join("b");
337        fs::create_dir_all(&a).unwrap();
338        fs::create_dir_all(&b).unwrap();
339        // Only b has the file.
340        let target = b.join("libX.dylib");
341        File::create(&target).unwrap().write_all(b"x").unwrap();
342
343        let rpaths = vec![
344            "@executable_path/a".to_owned(),
345            "@executable_path/b".to_owned(),
346        ];
347        let c = ctx(None, &dir, &dir, &rpaths);
348        let host = resolve_install_name("@rpath/libX.dylib", &c).unwrap();
349        assert_eq!(host, target);
350        drop(fs::remove_dir_all(dir));
351    }
352
353    #[test]
354    fn rejects_dotdot() {
355        let exe = Path::new("/tmp/kh-exe");
356        let c = ctx(None, exe, exe, &[]);
357        let err = resolve_install_name("@executable_path/../etc/passwd", &c).unwrap_err();
358        assert!(matches!(err, ResolveError::Escape(_)));
359    }
360
361    #[test]
362    fn bottle_symlink_escape_rejected() {
363        let root = std::env::temp_dir().join(format!("kh-resolve-symlink-{}", std::process::id()));
364        let outside =
365            std::env::temp_dir().join(format!("kh-resolve-outside-{}", std::process::id()));
366        fs::create_dir_all(&root).unwrap();
367        fs::create_dir_all(&outside).unwrap();
368        let outside_lib = outside.join("evil.dylib");
369        File::create(&outside_lib).unwrap().write_all(b"x").unwrap();
370
371        let link = root.join("escape.dylib");
372        #[cfg(unix)]
373        std::os::unix::fs::symlink(&outside_lib, &link).unwrap();
374
375        let exe = root.join("bin");
376        fs::create_dir_all(&exe).unwrap();
377
378        let c = ctx(Some(root.as_path()), &exe, &exe, &[]);
379        // Absolute install name maps under bottle, but canonicalize follows the
380        // symlink outside → OutsideAllowlist.
381        let result = resolve_install_name("/escape.dylib", &c);
382        assert!(
383            matches!(result, Err(ResolveError::OutsideAllowlist(_))),
384            "expected OutsideAllowlist, got {result:?}"
385        );
386
387        drop(fs::remove_dir_all(root));
388        drop(fs::remove_dir_all(outside));
389    }
390
391    #[test]
392    fn absolute_planted_host_path_still_no_bottle() {
393        // Even if a file exists at the absolute path, without a bottle we must
394        // not resolve it (no exists probe / no map candidate).
395        let planted =
396            std::env::temp_dir().join(format!("kh-fake-libsystem-{}", std::process::id()));
397        File::create(&planted).unwrap().write_all(b"x").unwrap();
398        let abs = planted.to_str().expect("utf8 temp path");
399        let exe = Path::new("/tmp/kh-exe-dir");
400        let c = ctx(None, exe, exe, &[]);
401        let err = resolve_install_name(abs, &c).unwrap_err();
402        assert_eq!(err, ResolveError::NoBottle);
403        drop(fs::remove_file(planted));
404    }
405}