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/// Pure translation helper (testable without process globals).
53pub fn translate_path_with_root(root: Option<&Path>, guest: &str) -> Result<PathBuf, PathError> {
54    if guest.is_empty() {
55        return Err(PathError::Empty);
56    }
57
58    // Relative paths follow host CWD (fixtures / argv paths), not the bottle tree.
59    if !guest.starts_with('/') {
60        // Reject `..` while keeping the original relative string for open(2).
61        strip_root_components(Path::new(guest))?;
62        return Ok(PathBuf::from(guest));
63    }
64
65    // Fast path: no `..` and no empty components → strip leading slashes / `.`
66    // without allocating intermediate PathBufs for each component.
67    if let Some(rel) = try_fast_relative(guest) {
68        return match root {
69            Some(r) => {
70                let mut out = PathBuf::with_capacity(
71                    r.as_os_str()
72                        .len()
73                        .saturating_add(rel.len())
74                        .saturating_add(1),
75                );
76                out.push(r);
77                if !rel.is_empty() {
78                    out.push(rel);
79                }
80                Ok(out)
81            }
82            None => Ok(PathBuf::from(guest)),
83        };
84    }
85
86    let guest_path = Path::new(guest);
87    let relative = strip_root_components(guest_path)?;
88
89    match root {
90        Some(r) => {
91            let mut out = r.to_path_buf();
92            out.push(relative);
93            Ok(out)
94        }
95        None => Ok(guest_path.to_path_buf()),
96    }
97}
98
99/// Returns stripped relative guest path when it has no `..` (and no empty segs).
100///
101/// `None` means fall back to the full component walker.
102fn try_fast_relative(guest: &str) -> Option<&str> {
103    if guest.contains("..") {
104        // May be `foo..bar` (ok) or `../x` / `a/../b` — let the slow path decide.
105        if guest == ".."
106            || guest.starts_with("../")
107            || guest.ends_with("/..")
108            || guest.contains("/../")
109        {
110            return None;
111        }
112    }
113    let mut s = guest;
114    while let Some(rest) = s.strip_prefix('/') {
115        s = rest;
116    }
117    // Drop a single leading "./"
118    if let Some(rest) = s.strip_prefix("./") {
119        s = rest;
120    }
121    // Reject remaining "./" or empty segments that need normalization.
122    if s.contains("/./") || s.contains("//") || s.ends_with("/.") {
123        return None;
124    }
125    Some(s)
126}
127
128/// Strips leading `/` (and Windows-style prefixes if any) and rejects `..`.
129fn strip_root_components(path: &Path) -> Result<PathBuf, PathError> {
130    let mut out = PathBuf::new();
131    for comp in path.components() {
132        match comp {
133            Component::Prefix(_) | Component::RootDir | Component::CurDir => {}
134            Component::ParentDir => {
135                return Err(PathError::Escape(path.display().to_string()));
136            }
137            Component::Normal(s) => out.push(s),
138        }
139    }
140    Ok(out)
141}
142
143/// Stack buffer size for typical guest paths (avoids heap on open/stat).
144const PATH_STACK: usize = 512;
145
146/// Reads a NUL-terminated C string from an identity-mapped guest pointer.
147///
148/// Used by `open` / `access` handlers. Caps length to avoid runaway scans.
149#[must_use]
150#[allow(unsafe_code)]
151pub fn read_c_string(ptr: u64, max_len: usize) -> Option<String> {
152    if ptr == 0 || max_len == 0 {
153        return None;
154    }
155    let base = usize::try_from(ptr).ok()?;
156    let base_ptr: *const u8 = std::ptr::with_exposed_provenance(base);
157
158    let mut stack = [0_u8; PATH_STACK];
159    let stack_cap = PATH_STACK.min(max_len);
160    for i in 0..stack_cap {
161        // SAFETY: identity map — guest VA == host VA for mapped pages.
162        let byte = unsafe { *base_ptr.wrapping_add(i) };
163        if byte == 0 {
164            return stack.get(..i).and_then(|s| std::str::from_utf8(s).ok()).map(str::to_owned);
165        }
166        if let Some(slot) = stack.get_mut(i) {
167            *slot = byte;
168        }
169    }
170    if stack_cap == max_len {
171        return None; // no NUL within cap
172    }
173
174    // Longer path: fall back to heap.
175    let mut buf = Vec::with_capacity(stack_cap.saturating_add(64));
176    if let Some(prefix) = stack.get(..stack_cap) {
177        buf.extend_from_slice(prefix);
178    }
179    for i in stack_cap..max_len {
180        let byte = unsafe { *base_ptr.wrapping_add(i) };
181        if byte == 0 {
182            return String::from_utf8(buf).ok();
183        }
184        buf.push(byte);
185    }
186    None
187}
188
189#[cfg(test)]
190#[allow(clippy::expect_used)]
191mod tests {
192    use super::*;
193
194    #[test]
195    fn absolute_under_bottle() {
196        let root = Path::new("/opt/bottle");
197        let host = translate_path_with_root(Some(root), "/usr/lib/libSystem.B.dylib")
198            .expect("translate absolute");
199        assert_eq!(host, PathBuf::from("/opt/bottle/usr/lib/libSystem.B.dylib"));
200    }
201
202    #[test]
203    fn relative_stays_host_cwd_even_with_bottle() {
204        let root = Path::new("/opt/bottle");
205        let host = translate_path_with_root(Some(root), "tmp/x").expect("translate relative");
206        assert_eq!(host, PathBuf::from("tmp/x"));
207    }
208
209    #[test]
210    fn relative_rejects_dotdot() {
211        let root = Path::new("/opt/bottle");
212        let err = translate_path_with_root(Some(root), "../etc/passwd").expect_err("..");
213        assert!(matches!(err, PathError::Escape(_)));
214    }
215
216    #[test]
217    fn no_bottle_passthrough() {
218        let host = translate_path_with_root(None, "/tmp/foo").expect("passthrough");
219        assert_eq!(host, PathBuf::from("/tmp/foo"));
220    }
221
222    #[test]
223    fn rejects_parent_dir() {
224        let root = Path::new("/opt/bottle");
225        let err =
226            translate_path_with_root(Some(root), "/usr/../etc/passwd").expect_err("must reject ..");
227        assert!(matches!(err, PathError::Escape(_)));
228    }
229
230    #[test]
231    fn empty_rejected() {
232        assert_eq!(translate_path_with_root(None, ""), Err(PathError::Empty));
233    }
234
235    #[test]
236    fn volumes_linux_under_bottle() {
237        let root = Path::new("/var/lib/my-renamed-bottle");
238        let host = translate_path_with_root(Some(root), "/Volumes/linux/tmp/x")
239            .expect("translate volumes");
240        assert_eq!(
241            host,
242            PathBuf::from("/var/lib/my-renamed-bottle/Volumes/linux/tmp/x")
243        );
244    }
245
246    #[test]
247    fn fast_path_dots_in_name_ok() {
248        let root = Path::new("/b");
249        let host = translate_path_with_root(Some(root), "/foo..bar")
250            .expect("dots in name");
251        assert_eq!(host, PathBuf::from("/b/foo..bar"));
252    }
253}