kh_runtime/bottle/
path.rs1use std::path::{Component, Path, PathBuf};
7
8use thiserror::Error;
9
10use crate::process;
11
12#[derive(Debug, Error, Clone, PartialEq, Eq)]
14pub enum PathError {
15 #[error("empty guest path")]
17 Empty,
18
19 #[error("guest path escapes bottle: {0}")]
21 Escape(String),
22
23 #[error("invalid path encoding")]
25 InvalidEncoding,
26}
27
28pub fn set_bottle_root(root: Option<PathBuf>) {
32 process::set_bottle_root(root);
33}
34
35#[must_use]
37pub fn bottle_root() -> Option<PathBuf> {
38 process::bottle_root()
39}
40
41pub fn translate_path(guest: &str) -> Result<PathBuf, PathError> {
48 process::with_bottle_root(|root| translate_path_with_root(root, guest))
50}
51
52#[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#[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#[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 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
120pub 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 if !guest.starts_with('/') {
128 strip_root_components(Path::new(guest))?;
130 return Ok(PathBuf::from(guest));
131 }
132
133 if let Some(host) = host_bridge_guest_to_host(guest)? {
137 return Ok(host);
138 }
139
140 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
174fn 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 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#[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
230fn try_fast_relative(guest: &str) -> Option<&str> {
234 if guest.contains("..") {
235 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 if let Some(rest) = s.strip_prefix("./") {
250 s = rest;
251 }
252 if s.contains("/./") || s.contains("//") || s.ends_with("/.") {
254 return None;
255 }
256 Some(s)
257}
258
259fn 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#[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#[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 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 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 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
343fn host_bridge_guest_path(host_real: &Path) -> String {
345 let lossy = host_real.to_string_lossy();
346 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
360const PATH_STACK: usize = 512;
362
363#[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 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; }
393
394 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#[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 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}