Skip to main content

kh_runtime/bottle/
path.rs

1//! Bottle root path translation (macOS-like FS tree under a host directory).
2//!
3//! Guest absolute paths such as `/usr/lib/libSystem.B.dylib` resolve to
4//! `{root}/usr/lib/libSystem.B.dylib`. Path escape via `..` is rejected.
5
6use std::path::{Component, Path, PathBuf};
7
8use thiserror::Error;
9
10use crate::process;
11
12/// Path translation errors.
13#[derive(Debug, Error, Clone, PartialEq, Eq)]
14pub enum PathError {
15    /// Guest path was empty.
16    #[error("empty guest path")]
17    Empty,
18
19    /// Guest path contained `..` or other disallowed components.
20    #[error("guest path escapes bottle: {0}")]
21    Escape(String),
22
23    /// Path is not valid UTF-8 / OS string.
24    #[error("invalid path encoding")]
25    InvalidEncoding,
26}
27
28/// Configures the bottle root used by path-taking syscalls (`open`, `access`, …).
29///
30/// Pass `None` to clear (pass-through absolute guest paths to the host).
31pub fn set_bottle_root(root: Option<PathBuf>) {
32    process::set_bottle_root(root);
33}
34
35/// Returns a clone of the configured bottle root, if any.
36#[must_use]
37pub fn bottle_root() -> Option<PathBuf> {
38    process::bottle_root()
39}
40
41/// Translates a guest path string into a host path.
42///
43/// * Absolute guest path + bottle → `{root}/{stripped absolute}`
44/// * Absolute guest path, no bottle → host absolute path as-is
45/// * Relative guest path → **host CWD-relative** (Darwin open semantics); bottle
46///   is not applied. Still rejects `..` escape components.
47pub fn translate_path(guest: &str) -> Result<PathBuf, PathError> {
48    // Avoid cloning the bottle root PathBuf on every open/stat.
49    process::with_bottle_root(|root| translate_path_with_root(root, guest))
50}
51
52/// Repair modern Apple `ld` library-search joins that drop the `/` separator.
53///
54/// Observed under freestanding (G5): `-L $SDK/usr/lib -lSystem` probes
55/// `$SDK/usr/liblibSystem.tbd` instead of `$SDK/usr/lib/libSystem.tbd`
56/// (`…/lib` + `libName.ext` glued without `/`). Host macOS `ld` inserts the
57/// slash; until freestanding string/path join matches, open/access/stat retry
58/// with the first `liblib` → `lib/lib`. Returns `None` when no repair applies.
59#[must_use]
60pub fn repair_ld_liblib_join(guest: &str) -> Option<String> {
61    let i = guest.find("liblib")?;
62    let mut out = String::with_capacity(guest.len().saturating_add(1));
63    out.push_str(&guest[..i]);
64    out.push_str("lib/lib");
65    out.push_str(&guest[i.saturating_add(6)..]);
66    Some(out)
67}
68
69/// Repair `-syslibroot $SDK` joins that drop `/` after the SDK root.
70///
71/// Observed under freestanding (G5): modern `ld` probes
72/// `…/MacOSX.sdkusr/lib` instead of `…/MacOSX.sdk/usr/lib` (and similarly
73/// `…sdkLibrary/…`, `…sdkSystem/…`). Host inserts the slash; until freestanding
74/// path/string join matches, open/access/stat retry with `/` after `.sdk`.
75#[must_use]
76pub fn repair_ld_syslibroot_join(guest: &str) -> Option<String> {
77    let bytes = guest.as_bytes();
78    let mut i = 0_usize;
79    while i.saturating_add(4) <= bytes.len() {
80        if bytes.get(i..i.saturating_add(4)) == Some(b".sdk") {
81            let after = i.saturating_add(4);
82            if let Some(&c) = bytes.get(after)
83                && c != b'/'
84            {
85                let mut out = String::with_capacity(guest.len().saturating_add(1));
86                out.push_str(&guest[..after]);
87                out.push('/');
88                out.push_str(&guest[after..]);
89                return Some(out);
90            }
91        }
92        i = i.saturating_add(1);
93    }
94    None
95}
96
97/// Apply freestanding `ld` path-join repairs (may chain).
98///
99/// Order matters: a probe can be both `…sdkusr/liblibSystem.tbd` (missing `/`
100/// after `.sdk` **and** `lib`+`libName`). Apply each rewrite that matches so
101/// the final path is `…/MacOSX.sdk/usr/lib/libSystem.tbd`.
102#[must_use]
103pub fn repair_ld_guest_path(guest: &str) -> Option<String> {
104    let mut cur = guest.to_string();
105    let mut changed = false;
106    // Fixed-point: each step inserts at most one `/`; two bug classes max today.
107    for _ in 0..4 {
108        let next = repair_ld_liblib_join(&cur).or_else(|| repair_ld_syslibroot_join(&cur));
109        match next {
110            Some(p) if p != cur => {
111                cur = p;
112                changed = true;
113            }
114            _ => break,
115        }
116    }
117    changed.then_some(cur)
118}
119
120/// Pure translation helper (testable without process globals).
121pub fn translate_path_with_root(root: Option<&Path>, guest: &str) -> Result<PathBuf, PathError> {
122    if guest.is_empty() {
123        return Err(PathError::Empty);
124    }
125
126    // Relative paths follow host CWD (fixtures / argv paths), not the bottle tree.
127    if !guest.starts_with('/') {
128        // Reject `..` while keeping the original relative string for open(2).
129        strip_root_components(Path::new(guest))?;
130        return Ok(PathBuf::from(guest));
131    }
132
133    // Host bridge prefixes: do **not** walk through bottle symlinks. Apple git
134    // realpath's `/Volumes/linux/tmp/…` via `readlink` → `/tmp/…`; that must still
135    // hit the host FS, not bottle `private/tmp`.
136    if let Some(host) = host_bridge_guest_to_host(guest)? {
137        return Ok(host);
138    }
139
140    // Fast path: no `..` and no empty components → strip leading slashes / `.`
141    // without allocating intermediate PathBufs for each component.
142    if let Some(rel) = try_fast_relative(guest) {
143        return match root {
144            Some(r) => {
145                let mut out = PathBuf::with_capacity(
146                    r.as_os_str()
147                        .len()
148                        .saturating_add(rel.len())
149                        .saturating_add(1),
150                );
151                out.push(r);
152                if !rel.is_empty() {
153                    out.push(rel);
154                }
155                Ok(out)
156            }
157            None => Ok(PathBuf::from(guest)),
158        };
159    }
160
161    let guest_path = Path::new(guest);
162    let relative = strip_root_components(guest_path)?;
163
164    match root {
165        Some(r) => {
166            let mut out = r.to_path_buf();
167            out.push(relative);
168            Ok(out)
169        }
170        None => Ok(guest_path.to_path_buf()),
171    }
172}
173
174/// Map guest bridge paths to host absolute paths (no bottle join).
175///
176/// | Guest | Host |
177/// | --- | --- |
178/// | `/Volumes/linux` + rest | `/` + rest |
179/// | `/tmp` + rest | `/tmp` + rest |
180/// | `/private/tmp` + rest | `/tmp` + rest (Darwin layout) |
181fn host_bridge_guest_to_host(guest: &str) -> Result<Option<PathBuf>, PathError> {
182    const VOL: &str = "/Volumes/linux";
183    if guest == VOL || guest.starts_with("/Volumes/linux/") {
184        let rest = guest.strip_prefix(VOL).unwrap_or("");
185        // Reject `..` in the host-relative rest.
186        let host = if rest.is_empty() {
187            PathBuf::from("/")
188        } else {
189            strip_root_components(Path::new(rest))?;
190            PathBuf::from(rest)
191        };
192        return Ok(Some(host));
193    }
194    if guest == "/private/tmp" || guest.starts_with("/private/tmp/") {
195        let rest = guest.strip_prefix("/private/tmp").unwrap_or("");
196        let host = if rest.is_empty() {
197            PathBuf::from("/tmp")
198        } else {
199            strip_root_components(Path::new(rest))?;
200            PathBuf::from(format!("/tmp{rest}"))
201        };
202        return Ok(Some(host));
203    }
204    if guest == "/tmp" || guest.starts_with("/tmp/") {
205        strip_root_components(Path::new(guest))?;
206        return Ok(Some(PathBuf::from(guest)));
207    }
208    Ok(None)
209}
210
211/// Bottle-relative openat target for an absolute guest path (B1).
212///
213/// When `Some((dirfd, rel))`, callers should `openat`/`fstatat` with `rel`
214/// (`"."` when the guest path is `/`) instead of allocating `{root}/{rel}`.
215/// Host-bridge paths (`/Volumes/linux`, `/tmp`, `/private/tmp`) return `None`
216/// so callers use [`translate_path`] instead.
217#[must_use]
218pub fn bottle_openat_rel(guest: &str) -> Option<(std::os::fd::RawFd, &str)> {
219    if !guest.starts_with('/') {
220        return None;
221    }
222    if host_bridge_guest_to_host(guest).ok().flatten().is_some() {
223        return None;
224    }
225    let dirfd = process::bottle_dirfd()?;
226    let rel = try_fast_relative(guest)?;
227    Some((dirfd, if rel.is_empty() { "." } else { rel }))
228}
229
230/// Returns stripped relative guest path when it has no `..` (and no empty segs).
231///
232/// `None` means fall back to the full component walker.
233fn try_fast_relative(guest: &str) -> Option<&str> {
234    if guest.contains("..") {
235        // May be `foo..bar` (ok) or `../x` / `a/../b` — let the slow path decide.
236        if guest == ".."
237            || guest.starts_with("../")
238            || guest.ends_with("/..")
239            || guest.contains("/../")
240        {
241            return None;
242        }
243    }
244    let mut s = guest;
245    while let Some(rest) = s.strip_prefix('/') {
246        s = rest;
247    }
248    // Drop a single leading "./"
249    if let Some(rest) = s.strip_prefix("./") {
250        s = rest;
251    }
252    // Reject remaining "./" or empty segments that need normalization.
253    if s.contains("/./") || s.contains("//") || s.ends_with("/.") {
254        return None;
255    }
256    Some(s)
257}
258
259/// Strips leading `/` (and Windows-style prefixes if any) and rejects `..`.
260fn strip_root_components(path: &Path) -> Result<PathBuf, PathError> {
261    let mut out = PathBuf::new();
262    for comp in path.components() {
263        match comp {
264            Component::Prefix(_) | Component::RootDir | Component::CurDir => {}
265            Component::ParentDir => {
266                return Err(PathError::Escape(path.display().to_string()));
267            }
268            Component::Normal(s) => out.push(s),
269        }
270    }
271    Ok(out)
272}
273
274/// Guest absolute path for the host process CWD.
275///
276/// * Host under bottle → bottle-relative absolute (`/usr/…`).
277/// * Host under `/tmp` → Darwin-style `/private/tmp/…` (bridged to host `/tmp`).
278/// * Else → `/Volumes/linux` + host absolute (bridged to host).
279#[must_use]
280pub fn guest_cwd_string() -> Option<String> {
281    let host = std::env::current_dir().ok()?;
282    host_path_to_guest(&host)
283}
284
285/// Maps an absolute host path to a guest absolute path (bottle or host bridge).
286///
287/// Intermediate directory symlinks are resolved (bottle root may itself be a
288/// symlink), but the **invoked leaf name** is preserved when `canonicalize`
289/// would replace it with a multi-call target (CLT `ranlib` → `libtool`). Darwin
290/// `argv[0]` / `getprogname()` / `_NSGetExecutablePath` use the path as
291/// invoked; restoring the leaf keeps multi-call tools in the right mode.
292#[must_use]
293pub fn host_path_to_guest(host: &Path) -> Option<String> {
294    let host_abs = if host.is_absolute() {
295        host.to_path_buf()
296    } else {
297        std::env::current_dir().ok()?.join(host)
298    };
299    // Leaf before canonicalize resolves multi-call symlinks (ranlib→libtool).
300    let invoked_leaf = host_abs
301        .file_name()
302        .and_then(|s| s.to_str())
303        .filter(|s| !s.is_empty())
304        .map(str::to_owned);
305
306    // Prefer real paths so strip_prefix works across directory symlinks.
307    let host_real = host_abs.canonicalize().unwrap_or_else(|_| host_abs.clone());
308
309    let mut guest = if let Some(root) = bottle_root() {
310        let root_real = root.canonicalize().unwrap_or(root);
311        if let Ok(rel) = host_real.strip_prefix(&root_real) {
312            if rel.as_os_str().is_empty() {
313                "/".to_owned()
314            } else {
315                let mut s = String::from("/");
316                s.push_str(&rel.to_string_lossy());
317                s.replace('\\', "/")
318            }
319        } else {
320            host_bridge_guest_path(&host_real)
321        }
322    } else {
323        host_bridge_guest_path(&host_real)
324    };
325
326    // Restore invoked basename when only the leaf was a multi-call symlink.
327    if let (Some(inv), Some(real_leaf)) = (
328        invoked_leaf.as_deref(),
329        host_real.file_name().and_then(|s| s.to_str()),
330    ) && inv != real_leaf
331        && let Some((parent, _)) = guest.rsplit_once('/')
332    {
333        guest = if parent.is_empty() {
334            format!("/{inv}")
335        } else {
336            format!("{parent}/{inv}")
337        };
338    }
339
340    Some(guest)
341}
342
343/// Host path → guest path outside the bottle (`/private/tmp`, `/Volumes/linux…`).
344fn host_bridge_guest_path(host_real: &Path) -> String {
345    let lossy = host_real.to_string_lossy();
346    // Prefer Darwin `/private/tmp` for host `/tmp` so realpath/readlink walks
347    // stay on the host bridge (see [`host_bridge_guest_to_host`]).
348    if lossy == "/tmp" {
349        return "/private/tmp".to_owned();
350    }
351    if let Some(rest) = lossy.strip_prefix("/tmp/") {
352        return format!("/private/tmp/{rest}");
353    }
354    if lossy == "/" {
355        return format!("/{}", super::layout::VOLUMES_LINUX);
356    }
357    format!("/{}{lossy}", super::layout::VOLUMES_LINUX).replace('\\', "/")
358}
359
360/// Stack buffer size for typical guest paths (avoids heap on open/stat).
361const PATH_STACK: usize = 512;
362
363/// Reads a NUL-terminated C string from an identity-mapped guest pointer.
364///
365/// Read a NUL-terminated guest C string as raw bytes (no UTF-8 requirement).
366///
367/// Darwin paths are byte sequences; rejecting non-UTF-8 as `EFAULT` broke modern
368/// `ld`/`libtapi` (G5): `open` saw a short binary blob and failed before ENOENT.
369#[must_use]
370#[allow(unsafe_code)]
371pub fn read_c_bytes(ptr: u64, max_len: usize) -> Option<Vec<u8>> {
372    if ptr == 0 || max_len == 0 {
373        return None;
374    }
375    let base = usize::try_from(ptr).ok()?;
376    let base_ptr: *const u8 = std::ptr::with_exposed_provenance(base);
377
378    let mut stack = [0_u8; PATH_STACK];
379    let stack_cap = PATH_STACK.min(max_len);
380    for i in 0..stack_cap {
381        // SAFETY: identity map — guest VA == host VA for mapped pages.
382        let byte = unsafe { *base_ptr.wrapping_add(i) };
383        if byte == 0 {
384            return stack.get(..i).map(<[u8]>::to_vec);
385        }
386        if let Some(slot) = stack.get_mut(i) {
387            *slot = byte;
388        }
389    }
390    if stack_cap == max_len {
391        return None; // no NUL within cap
392    }
393
394    // Longer path: fall back to heap.
395    let mut buf = Vec::with_capacity(stack_cap.saturating_add(64));
396    if let Some(prefix) = stack.get(..stack_cap) {
397        buf.extend_from_slice(prefix);
398    }
399    for i in stack_cap..max_len {
400        let byte = unsafe { *base_ptr.wrapping_add(i) };
401        if byte == 0 {
402            return Some(buf);
403        }
404        buf.push(byte);
405    }
406    None
407}
408
409/// Used by `open` / `access` handlers. Caps length to avoid runaway scans.
410///
411/// Accepts any byte path (lossy UTF-8). Prefer [`read_c_bytes`] when the caller
412/// must not invent replacement characters.
413#[must_use]
414#[allow(unsafe_code)]
415pub fn read_c_string(ptr: u64, max_len: usize) -> Option<String> {
416    let bytes = read_c_bytes(ptr, max_len)?;
417    Some(String::from_utf8_lossy(&bytes).into_owned())
418}
419
420#[cfg(test)]
421#[allow(clippy::expect_used)]
422mod tests {
423    use super::*;
424
425    #[test]
426    fn repair_ld_liblib_join_inserts_slash() {
427        assert_eq!(
428            repair_ld_liblib_join(
429                "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/liblibSystem.tbd"
430            )
431            .as_deref(),
432            Some("/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib/libSystem.tbd")
433        );
434        assert_eq!(
435            repair_ld_liblib_join("/usr/liblibcache.tbd").as_deref(),
436            Some("/usr/lib/libcache.tbd")
437        );
438        assert_eq!(repair_ld_liblib_join("/usr/lib/libSystem.tbd"), None);
439    }
440
441    #[test]
442    fn repair_ld_syslibroot_join_inserts_slash_after_sdk() {
443        assert_eq!(
444            repair_ld_syslibroot_join("/Library/Developer/CommandLineTools/SDKs/MacOSX.sdkusr/lib")
445                .as_deref(),
446            Some("/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib")
447        );
448        assert_eq!(
449            repair_ld_syslibroot_join(
450                "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdkSystem/Library/Frameworks"
451            )
452            .as_deref(),
453            Some("/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks")
454        );
455        assert_eq!(
456            repair_ld_syslibroot_join(
457                "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib"
458            ),
459            None
460        );
461        assert_eq!(
462            repair_ld_guest_path(
463                "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/liblibSystem.tbd"
464            )
465            .as_deref(),
466            Some("/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib/libSystem.tbd")
467        );
468        // Both bugs stacked: dropped `/` after `.sdk` and `lib`+`libName`.
469        assert_eq!(
470            repair_ld_guest_path(
471                "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdkusr/liblibSystem.tbd"
472            )
473            .as_deref(),
474            Some("/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib/libSystem.tbd")
475        );
476    }
477
478    #[test]
479    fn absolute_under_bottle() {
480        let root = Path::new("/opt/bottle");
481        let host = translate_path_with_root(Some(root), "/usr/lib/libSystem.B.dylib")
482            .expect("translate absolute");
483        assert_eq!(host, PathBuf::from("/opt/bottle/usr/lib/libSystem.B.dylib"));
484    }
485
486    #[test]
487    fn relative_stays_host_cwd_even_with_bottle() {
488        let root = Path::new("/opt/bottle");
489        let host = translate_path_with_root(Some(root), "tmp/x").expect("translate relative");
490        assert_eq!(host, PathBuf::from("tmp/x"));
491    }
492
493    #[test]
494    fn relative_rejects_dotdot() {
495        let root = Path::new("/opt/bottle");
496        let err = translate_path_with_root(Some(root), "../etc/passwd").expect_err("..");
497        assert!(matches!(err, PathError::Escape(_)));
498    }
499
500    #[test]
501    fn no_bottle_passthrough() {
502        let host = translate_path_with_root(None, "/tmp/foo").expect("passthrough");
503        assert_eq!(host, PathBuf::from("/tmp/foo"));
504    }
505
506    #[test]
507    fn rejects_parent_dir() {
508        let root = Path::new("/opt/bottle");
509        let err =
510            translate_path_with_root(Some(root), "/usr/../etc/passwd").expect_err("must reject ..");
511        assert!(matches!(err, PathError::Escape(_)));
512    }
513
514    #[test]
515    fn empty_rejected() {
516        assert_eq!(translate_path_with_root(None, ""), Err(PathError::Empty));
517    }
518
519    #[test]
520    fn volumes_linux_is_host_bridge_not_bottle_join() {
521        let root = Path::new("/var/lib/my-renamed-bottle");
522        let host = translate_path_with_root(Some(root), "/Volumes/linux/tmp/x")
523            .expect("translate volumes");
524        assert_eq!(host, PathBuf::from("/tmp/x"));
525    }
526
527    #[test]
528    fn fast_path_dots_in_name_ok() {
529        let root = Path::new("/b");
530        let host = translate_path_with_root(Some(root), "/foo..bar").expect("dots in name");
531        assert_eq!(host, PathBuf::from("/b/foo..bar"));
532    }
533
534    #[test]
535    fn host_tmp_maps_to_private_tmp_guest() {
536        set_bottle_root(None);
537        let guest = host_path_to_guest(Path::new("/tmp/kh-guest-cwd-test")).expect("map");
538        assert_eq!(guest, "/private/tmp/kh-guest-cwd-test");
539    }
540
541    #[test]
542    fn host_path_preserves_multicall_symlink_leaf() {
543        let tmp = std::env::temp_dir().join(format!("kh-ranlib-leaf-{}", std::process::id()));
544        drop(std::fs::remove_dir_all(&tmp));
545        let bin = tmp.join("usr/bin");
546        std::fs::create_dir_all(&bin).expect("mkdir");
547        let libtool = bin.join("libtool");
548        std::fs::write(&libtool, b"x").expect("write libtool");
549        let ranlib = bin.join("ranlib");
550        #[cfg(unix)]
551        std::os::unix::fs::symlink("libtool", &ranlib).expect("symlink ranlib");
552        set_bottle_root(Some(tmp.clone()));
553        let guest = host_path_to_guest(&ranlib).expect("map ranlib");
554        assert_eq!(guest, "/usr/bin/ranlib", "multi-call leaf must stay ranlib");
555        set_bottle_root(None);
556        drop(std::fs::remove_dir_all(&tmp));
557    }
558
559    #[test]
560    fn bridge_private_tmp_to_host() {
561        let host = translate_path_with_root(Some(Path::new("/opt/bottle")), "/private/tmp/x")
562            .expect("bridge");
563        assert_eq!(host, PathBuf::from("/tmp/x"));
564    }
565
566    #[test]
567    fn bridge_volumes_linux_to_host() {
568        let host =
569            translate_path_with_root(Some(Path::new("/opt/bottle")), "/Volumes/linux/home/a")
570                .expect("bridge");
571        assert_eq!(host, PathBuf::from("/home/a"));
572    }
573
574    #[test]
575    fn bottle_openat_rel_uses_dirfd_when_configured() {
576        let tmp = std::env::temp_dir().join(format!("kh-b1-openat-{}", std::process::id()));
577        drop(std::fs::remove_dir_all(&tmp));
578        std::fs::create_dir_all(tmp.join("usr/lib")).expect("mkdir");
579        set_bottle_root(Some(tmp.clone()));
580        let (fd, rel) = bottle_openat_rel("/usr/lib/libSystem.B.dylib").expect("openat parts");
581        assert!(fd >= 0);
582        assert_eq!(rel, "usr/lib/libSystem.B.dylib");
583        assert!(bottle_openat_rel("relative").is_none());
584        set_bottle_root(None);
585        assert!(bottle_openat_rel("/usr/lib/x").is_none());
586        drop(std::fs::remove_dir_all(&tmp));
587    }
588}