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 => ResolveError::InvalidEncoding,
252    }
253}
254
255#[cfg(test)]
256#[allow(clippy::expect_used, clippy::unwrap_used)]
257mod tests {
258    use super::*;
259    use std::fs::{self, File};
260    use std::io::Write;
261
262    fn ctx<'a>(
263        bottle: Option<&'a Path>,
264        exe_dir: &'a Path,
265        loader_dir: &'a Path,
266        rpaths: &'a [String],
267    ) -> ResolveContext<'a> {
268        ResolveContext {
269            bottle_root: bottle,
270            executable_dir: exe_dir,
271            loader_dir,
272            rpaths,
273        }
274    }
275
276    #[test]
277    fn absolute_without_bottle_is_no_bottle() {
278        let exe = Path::new("/tmp/kh-exe-dir");
279        let c = ctx(None, exe, exe, &[]);
280        let err = resolve_install_name("/usr/lib/libSystem.B.dylib", &c).unwrap_err();
281        assert_eq!(err, ResolveError::NoBottle);
282    }
283
284    #[test]
285    fn absolute_with_bottle_under_root() {
286        let root = std::env::temp_dir().join(format!("kh-resolve-bottle-{}", std::process::id()));
287        let lib_dir = root.join("usr/lib");
288        fs::create_dir_all(&lib_dir).unwrap();
289        let lib = lib_dir.join("libFoo.dylib");
290        File::create(&lib).unwrap().write_all(b"x").unwrap();
291
292        let exe = root.join("bin");
293        fs::create_dir_all(&exe).unwrap();
294
295        let c = ctx(Some(root.as_path()), &exe, &exe, &[]);
296        let host = resolve_install_name("/usr/lib/libFoo.dylib", &c).unwrap();
297        assert_eq!(host, lib);
298        drop(fs::remove_dir_all(root));
299    }
300
301    #[test]
302    fn executable_path_relative() {
303        let dir = std::env::temp_dir().join(format!("kh-resolve-exe-{}", std::process::id()));
304        fs::create_dir_all(&dir).unwrap();
305        let dylib = dir.join("libkh_add.dylib");
306        File::create(&dylib).unwrap().write_all(b"x").unwrap();
307
308        let c = ctx(None, &dir, &dir, &[]);
309        let host = resolve_install_name("@executable_path/libkh_add.dylib", &c).unwrap();
310        assert_eq!(host, dylib);
311        drop(fs::remove_dir_all(dir));
312    }
313
314    #[test]
315    fn loader_path_relative() {
316        // Allowlist is bottle ∪ executable_dir; nested loaders must sit under that tree.
317        let exe_dir =
318            std::env::temp_dir().join(format!("kh-resolve-loader-{}", std::process::id()));
319        let loader = exe_dir.join("Frameworks");
320        fs::create_dir_all(&loader).unwrap();
321        let dylib = loader.join("Inner.dylib");
322        File::create(&dylib).unwrap().write_all(b"x").unwrap();
323
324        let c = ctx(None, &exe_dir, &loader, &[]);
325        let host = resolve_install_name("@loader_path/Inner.dylib", &c).unwrap();
326        assert_eq!(host, dylib);
327        drop(fs::remove_dir_all(exe_dir));
328    }
329
330    #[test]
331    fn rpath_first_hit() {
332        let dir = std::env::temp_dir().join(format!("kh-resolve-rpath-{}", std::process::id()));
333        let a = dir.join("a");
334        let b = dir.join("b");
335        fs::create_dir_all(&a).unwrap();
336        fs::create_dir_all(&b).unwrap();
337        // Only b has the file.
338        let target = b.join("libX.dylib");
339        File::create(&target).unwrap().write_all(b"x").unwrap();
340
341        let rpaths = vec![
342            "@executable_path/a".to_owned(),
343            "@executable_path/b".to_owned(),
344        ];
345        let c = ctx(None, &dir, &dir, &rpaths);
346        let host = resolve_install_name("@rpath/libX.dylib", &c).unwrap();
347        assert_eq!(host, target);
348        drop(fs::remove_dir_all(dir));
349    }
350
351    #[test]
352    fn rejects_dotdot() {
353        let exe = Path::new("/tmp/kh-exe");
354        let c = ctx(None, exe, exe, &[]);
355        let err = resolve_install_name("@executable_path/../etc/passwd", &c).unwrap_err();
356        assert!(matches!(err, ResolveError::Escape(_)));
357    }
358
359    #[test]
360    fn bottle_symlink_escape_rejected() {
361        let root = std::env::temp_dir().join(format!("kh-resolve-symlink-{}", std::process::id()));
362        let outside =
363            std::env::temp_dir().join(format!("kh-resolve-outside-{}", std::process::id()));
364        fs::create_dir_all(&root).unwrap();
365        fs::create_dir_all(&outside).unwrap();
366        let outside_lib = outside.join("evil.dylib");
367        File::create(&outside_lib).unwrap().write_all(b"x").unwrap();
368
369        let link = root.join("escape.dylib");
370        #[cfg(unix)]
371        std::os::unix::fs::symlink(&outside_lib, &link).unwrap();
372
373        let exe = root.join("bin");
374        fs::create_dir_all(&exe).unwrap();
375
376        let c = ctx(Some(root.as_path()), &exe, &exe, &[]);
377        // Absolute install name maps under bottle, but canonicalize follows the
378        // symlink outside → OutsideAllowlist.
379        let result = resolve_install_name("/escape.dylib", &c);
380        assert!(
381            matches!(result, Err(ResolveError::OutsideAllowlist(_))),
382            "expected OutsideAllowlist, got {result:?}"
383        );
384
385        drop(fs::remove_dir_all(root));
386        drop(fs::remove_dir_all(outside));
387    }
388
389    #[test]
390    fn absolute_planted_host_path_still_no_bottle() {
391        // Even if a file exists at the absolute path, without a bottle we must
392        // not resolve it (no exists probe / no map candidate).
393        let planted =
394            std::env::temp_dir().join(format!("kh-fake-libsystem-{}", std::process::id()));
395        File::create(&planted).unwrap().write_all(b"x").unwrap();
396        let abs = planted.to_str().expect("utf8 temp path");
397        let exe = Path::new("/tmp/kh-exe-dir");
398        let c = ctx(None, exe, exe, &[]);
399        let err = resolve_install_name(abs, &c).unwrap_err();
400        assert_eq!(err, ResolveError::NoBottle);
401        drop(fs::remove_file(planted));
402    }
403}