kh-runtime 0.1.14

Kakehashi native ARM64 execution context, memory layout, traps, and bottle
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
//! Bottle root path translation (macOS-like FS tree under a host directory).
//!
//! Guest absolute paths such as `/usr/lib/libSystem.B.dylib` resolve to
//! `{root}/usr/lib/libSystem.B.dylib`. Path escape via `..` is rejected.

use std::path::{Component, Path, PathBuf};

use thiserror::Error;

use crate::process;

/// Path translation errors.
#[derive(Debug, Error, Clone, PartialEq, Eq)]
pub enum PathError {
    /// Guest path was empty.
    #[error("empty guest path")]
    Empty,

    /// Guest path contained `..` or other disallowed components.
    #[error("guest path escapes bottle: {0}")]
    Escape(String),

    /// Path is not valid UTF-8 / OS string.
    #[error("invalid path encoding")]
    InvalidEncoding,
}

/// Configures the bottle root used by path-taking syscalls (`open`, `access`, …).
///
/// Pass `None` to clear (pass-through absolute guest paths to the host).
pub fn set_bottle_root(root: Option<PathBuf>) {
    process::set_bottle_root(root);
}

/// Returns a clone of the configured bottle root, if any.
#[must_use]
pub fn bottle_root() -> Option<PathBuf> {
    process::bottle_root()
}

/// Translates a guest path string into a host path.
///
/// * Absolute guest path + bottle → `{root}/{stripped absolute}`
/// * Absolute guest path, no bottle → host absolute path as-is
/// * Relative guest path → **host CWD-relative** (Darwin open semantics); bottle
///   is not applied. Still rejects `..` escape components.
pub fn translate_path(guest: &str) -> Result<PathBuf, PathError> {
    // Avoid cloning the bottle root PathBuf on every open/stat.
    process::with_bottle_root(|root| translate_path_with_root(root, guest))
}

/// Repair modern Apple `ld` library-search joins that drop the `/` separator.
///
/// Observed under freestanding (G5): `-L $SDK/usr/lib -lSystem` probes
/// `$SDK/usr/liblibSystem.tbd` instead of `$SDK/usr/lib/libSystem.tbd`
/// (`…/lib` + `libName.ext` glued without `/`). Host macOS `ld` inserts the
/// slash; until freestanding string/path join matches, open/access/stat retry
/// with the first `liblib` → `lib/lib`. Returns `None` when no repair applies.
#[must_use]
pub fn repair_ld_liblib_join(guest: &str) -> Option<String> {
    let i = guest.find("liblib")?;
    let mut out = String::with_capacity(guest.len().saturating_add(1));
    out.push_str(&guest[..i]);
    out.push_str("lib/lib");
    out.push_str(&guest[i.saturating_add(6)..]);
    Some(out)
}

/// Repair `-syslibroot $SDK` joins that drop `/` after the SDK root.
///
/// Observed under freestanding (G5): modern `ld` probes
/// `…/MacOSX.sdkusr/lib` instead of `…/MacOSX.sdk/usr/lib` (and similarly
/// `…sdkLibrary/…`, `…sdkSystem/…`). Host inserts the slash; until freestanding
/// path/string join matches, open/access/stat retry with `/` after `.sdk`.
#[must_use]
pub fn repair_ld_syslibroot_join(guest: &str) -> Option<String> {
    let bytes = guest.as_bytes();
    let mut i = 0_usize;
    while i.saturating_add(4) <= bytes.len() {
        if bytes.get(i..i.saturating_add(4)) == Some(b".sdk") {
            let after = i.saturating_add(4);
            if let Some(&c) = bytes.get(after)
                && c != b'/'
            {
                let mut out = String::with_capacity(guest.len().saturating_add(1));
                out.push_str(&guest[..after]);
                out.push('/');
                out.push_str(&guest[after..]);
                return Some(out);
            }
        }
        i = i.saturating_add(1);
    }
    None
}

/// Apply freestanding `ld` path-join repairs (may chain).
///
/// Order matters: a probe can be both `…sdkusr/liblibSystem.tbd` (missing `/`
/// after `.sdk` **and** `lib`+`libName`). Apply each rewrite that matches so
/// the final path is `…/MacOSX.sdk/usr/lib/libSystem.tbd`.
#[must_use]
pub fn repair_ld_guest_path(guest: &str) -> Option<String> {
    let mut cur = guest.to_string();
    let mut changed = false;
    // Fixed-point: each step inserts at most one `/`; two bug classes max today.
    for _ in 0..4 {
        let next = repair_ld_liblib_join(&cur).or_else(|| repair_ld_syslibroot_join(&cur));
        match next {
            Some(p) if p != cur => {
                cur = p;
                changed = true;
            }
            _ => break,
        }
    }
    changed.then_some(cur)
}

/// Pure translation helper (testable without process globals).
pub fn translate_path_with_root(root: Option<&Path>, guest: &str) -> Result<PathBuf, PathError> {
    if guest.is_empty() {
        return Err(PathError::Empty);
    }

    // Relative paths follow host CWD (fixtures / argv paths), not the bottle tree.
    if !guest.starts_with('/') {
        // Reject `..` while keeping the original relative string for open(2).
        strip_root_components(Path::new(guest))?;
        return Ok(PathBuf::from(guest));
    }

    // Host bridge prefixes: do **not** walk through bottle symlinks. Apple git
    // realpath's `/Volumes/linux/tmp/…` via `readlink` → `/tmp/…`; that must still
    // hit the host FS, not bottle `private/tmp`.
    if let Some(host) = host_bridge_guest_to_host(guest)? {
        return Ok(host);
    }

    // Fast path: no `..` and no empty components → strip leading slashes / `.`
    // without allocating intermediate PathBufs for each component.
    if let Some(rel) = try_fast_relative(guest) {
        return match root {
            Some(r) => {
                let mut out = PathBuf::with_capacity(
                    r.as_os_str()
                        .len()
                        .saturating_add(rel.len())
                        .saturating_add(1),
                );
                out.push(r);
                if !rel.is_empty() {
                    out.push(rel);
                }
                Ok(out)
            }
            None => Ok(PathBuf::from(guest)),
        };
    }

    let guest_path = Path::new(guest);
    let relative = strip_root_components(guest_path)?;

    match root {
        Some(r) => {
            let mut out = r.to_path_buf();
            out.push(relative);
            Ok(out)
        }
        None => Ok(guest_path.to_path_buf()),
    }
}

/// Map guest bridge paths to host absolute paths (no bottle join).
///
/// | Guest | Host |
/// | --- | --- |
/// | `/Volumes/linux` + rest | `/` + rest |
/// | `/tmp` + rest | `/tmp` + rest |
/// | `/private/tmp` + rest | `/tmp` + rest (Darwin layout) |
fn host_bridge_guest_to_host(guest: &str) -> Result<Option<PathBuf>, PathError> {
    const VOL: &str = "/Volumes/linux";
    if guest == VOL || guest.starts_with("/Volumes/linux/") {
        let rest = guest.strip_prefix(VOL).unwrap_or("");
        // Reject `..` in the host-relative rest.
        let host = if rest.is_empty() {
            PathBuf::from("/")
        } else {
            strip_root_components(Path::new(rest))?;
            PathBuf::from(rest)
        };
        return Ok(Some(host));
    }
    if guest == "/private/tmp" || guest.starts_with("/private/tmp/") {
        let rest = guest.strip_prefix("/private/tmp").unwrap_or("");
        let host = if rest.is_empty() {
            PathBuf::from("/tmp")
        } else {
            strip_root_components(Path::new(rest))?;
            PathBuf::from(format!("/tmp{rest}"))
        };
        return Ok(Some(host));
    }
    if guest == "/tmp" || guest.starts_with("/tmp/") {
        strip_root_components(Path::new(guest))?;
        return Ok(Some(PathBuf::from(guest)));
    }
    Ok(None)
}

/// Bottle-relative openat target for an absolute guest path (B1).
///
/// When `Some((dirfd, rel))`, callers should `openat`/`fstatat` with `rel`
/// (`"."` when the guest path is `/`) instead of allocating `{root}/{rel}`.
/// Host-bridge paths (`/Volumes/linux`, `/tmp`, `/private/tmp`) return `None`
/// so callers use [`translate_path`] instead.
#[must_use]
pub fn bottle_openat_rel(guest: &str) -> Option<(std::os::fd::RawFd, &str)> {
    if !guest.starts_with('/') {
        return None;
    }
    if host_bridge_guest_to_host(guest).ok().flatten().is_some() {
        return None;
    }
    let dirfd = process::bottle_dirfd()?;
    let rel = try_fast_relative(guest)?;
    Some((dirfd, if rel.is_empty() { "." } else { rel }))
}

/// Returns stripped relative guest path when it has no `..` (and no empty segs).
///
/// `None` means fall back to the full component walker.
fn try_fast_relative(guest: &str) -> Option<&str> {
    if guest.contains("..") {
        // May be `foo..bar` (ok) or `../x` / `a/../b` — let the slow path decide.
        if guest == ".."
            || guest.starts_with("../")
            || guest.ends_with("/..")
            || guest.contains("/../")
        {
            return None;
        }
    }
    let mut s = guest;
    while let Some(rest) = s.strip_prefix('/') {
        s = rest;
    }
    // Drop a single leading "./"
    if let Some(rest) = s.strip_prefix("./") {
        s = rest;
    }
    // Reject remaining "./" or empty segments that need normalization.
    if s.contains("/./") || s.contains("//") || s.ends_with("/.") {
        return None;
    }
    Some(s)
}

/// Strips leading `/` (and Windows-style prefixes if any) and rejects `..`.
fn strip_root_components(path: &Path) -> Result<PathBuf, PathError> {
    let mut out = PathBuf::new();
    for comp in path.components() {
        match comp {
            Component::Prefix(_) | Component::RootDir | Component::CurDir => {}
            Component::ParentDir => {
                return Err(PathError::Escape(path.display().to_string()));
            }
            Component::Normal(s) => out.push(s),
        }
    }
    Ok(out)
}

/// Guest absolute path for the host process CWD.
///
/// * Host under bottle → bottle-relative absolute (`/usr/…`).
/// * Host under `/tmp` → Darwin-style `/private/tmp/…` (bridged to host `/tmp`).
/// * Else → `/Volumes/linux` + host absolute (bridged to host).
#[must_use]
pub fn guest_cwd_string() -> Option<String> {
    let host = std::env::current_dir().ok()?;
    host_path_to_guest(&host)
}

/// Maps an absolute host path to a guest absolute path (bottle or host bridge).
///
/// Intermediate directory symlinks are resolved (bottle root may itself be a
/// symlink), but the **invoked leaf name** is preserved when `canonicalize`
/// would replace it with a multi-call target (CLT `ranlib` → `libtool`). Darwin
/// `argv[0]` / `getprogname()` / `_NSGetExecutablePath` use the path as
/// invoked; restoring the leaf keeps multi-call tools in the right mode.
#[must_use]
pub fn host_path_to_guest(host: &Path) -> Option<String> {
    let host_abs = if host.is_absolute() {
        host.to_path_buf()
    } else {
        std::env::current_dir().ok()?.join(host)
    };
    // Leaf before canonicalize resolves multi-call symlinks (ranlib→libtool).
    let invoked_leaf = host_abs
        .file_name()
        .and_then(|s| s.to_str())
        .filter(|s| !s.is_empty())
        .map(str::to_owned);

    // Prefer real paths so strip_prefix works across directory symlinks.
    let host_real = host_abs.canonicalize().unwrap_or_else(|_| host_abs.clone());

    let mut guest = if let Some(root) = bottle_root() {
        let root_real = root.canonicalize().unwrap_or(root);
        if let Ok(rel) = host_real.strip_prefix(&root_real) {
            if rel.as_os_str().is_empty() {
                "/".to_owned()
            } else {
                let mut s = String::from("/");
                s.push_str(&rel.to_string_lossy());
                s.replace('\\', "/")
            }
        } else {
            host_bridge_guest_path(&host_real)
        }
    } else {
        host_bridge_guest_path(&host_real)
    };

    // Restore invoked basename when only the leaf was a multi-call symlink.
    if let (Some(inv), Some(real_leaf)) = (
        invoked_leaf.as_deref(),
        host_real.file_name().and_then(|s| s.to_str()),
    ) && inv != real_leaf
        && let Some((parent, _)) = guest.rsplit_once('/')
    {
        guest = if parent.is_empty() {
            format!("/{inv}")
        } else {
            format!("{parent}/{inv}")
        };
    }

    Some(guest)
}

/// Host path → guest path outside the bottle (`/private/tmp`, `/Volumes/linux…`).
fn host_bridge_guest_path(host_real: &Path) -> String {
    let lossy = host_real.to_string_lossy();
    // Prefer Darwin `/private/tmp` for host `/tmp` so realpath/readlink walks
    // stay on the host bridge (see [`host_bridge_guest_to_host`]).
    if lossy == "/tmp" {
        return "/private/tmp".to_owned();
    }
    if let Some(rest) = lossy.strip_prefix("/tmp/") {
        return format!("/private/tmp/{rest}");
    }
    if lossy == "/" {
        return format!("/{}", super::layout::VOLUMES_LINUX);
    }
    format!("/{}{lossy}", super::layout::VOLUMES_LINUX).replace('\\', "/")
}

/// Stack buffer size for typical guest paths (avoids heap on open/stat).
const PATH_STACK: usize = 512;

/// Reads a NUL-terminated C string from an identity-mapped guest pointer.
///
/// Read a NUL-terminated guest C string as raw bytes (no UTF-8 requirement).
///
/// Darwin paths are byte sequences; rejecting non-UTF-8 as `EFAULT` broke modern
/// `ld`/`libtapi` (G5): `open` saw a short binary blob and failed before ENOENT.
#[must_use]
#[allow(unsafe_code)]
pub fn read_c_bytes(ptr: u64, max_len: usize) -> Option<Vec<u8>> {
    if ptr == 0 || max_len == 0 {
        return None;
    }
    let base = usize::try_from(ptr).ok()?;
    let base_ptr: *const u8 = std::ptr::with_exposed_provenance(base);

    let mut stack = [0_u8; PATH_STACK];
    let stack_cap = PATH_STACK.min(max_len);
    for i in 0..stack_cap {
        // SAFETY: identity map — guest VA == host VA for mapped pages.
        let byte = unsafe { *base_ptr.wrapping_add(i) };
        if byte == 0 {
            return stack.get(..i).map(<[u8]>::to_vec);
        }
        if let Some(slot) = stack.get_mut(i) {
            *slot = byte;
        }
    }
    if stack_cap == max_len {
        return None; // no NUL within cap
    }

    // Longer path: fall back to heap.
    let mut buf = Vec::with_capacity(stack_cap.saturating_add(64));
    if let Some(prefix) = stack.get(..stack_cap) {
        buf.extend_from_slice(prefix);
    }
    for i in stack_cap..max_len {
        let byte = unsafe { *base_ptr.wrapping_add(i) };
        if byte == 0 {
            return Some(buf);
        }
        buf.push(byte);
    }
    None
}

/// Used by `open` / `access` handlers. Caps length to avoid runaway scans.
///
/// Accepts any byte path (lossy UTF-8). Prefer [`read_c_bytes`] when the caller
/// must not invent replacement characters.
#[must_use]
#[allow(unsafe_code)]
pub fn read_c_string(ptr: u64, max_len: usize) -> Option<String> {
    let bytes = read_c_bytes(ptr, max_len)?;
    Some(String::from_utf8_lossy(&bytes).into_owned())
}

#[cfg(test)]
#[allow(clippy::expect_used)]
mod tests {
    use super::*;

    #[test]
    fn repair_ld_liblib_join_inserts_slash() {
        assert_eq!(
            repair_ld_liblib_join(
                "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/liblibSystem.tbd"
            )
            .as_deref(),
            Some("/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib/libSystem.tbd")
        );
        assert_eq!(
            repair_ld_liblib_join("/usr/liblibcache.tbd").as_deref(),
            Some("/usr/lib/libcache.tbd")
        );
        assert_eq!(repair_ld_liblib_join("/usr/lib/libSystem.tbd"), None);
    }

    #[test]
    fn repair_ld_syslibroot_join_inserts_slash_after_sdk() {
        assert_eq!(
            repair_ld_syslibroot_join("/Library/Developer/CommandLineTools/SDKs/MacOSX.sdkusr/lib")
                .as_deref(),
            Some("/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib")
        );
        assert_eq!(
            repair_ld_syslibroot_join(
                "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdkSystem/Library/Frameworks"
            )
            .as_deref(),
            Some("/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/System/Library/Frameworks")
        );
        assert_eq!(
            repair_ld_syslibroot_join(
                "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib"
            ),
            None
        );
        assert_eq!(
            repair_ld_guest_path(
                "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/liblibSystem.tbd"
            )
            .as_deref(),
            Some("/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib/libSystem.tbd")
        );
        // Both bugs stacked: dropped `/` after `.sdk` and `lib`+`libName`.
        assert_eq!(
            repair_ld_guest_path(
                "/Library/Developer/CommandLineTools/SDKs/MacOSX.sdkusr/liblibSystem.tbd"
            )
            .as_deref(),
            Some("/Library/Developer/CommandLineTools/SDKs/MacOSX.sdk/usr/lib/libSystem.tbd")
        );
    }

    #[test]
    fn absolute_under_bottle() {
        let root = Path::new("/opt/bottle");
        let host = translate_path_with_root(Some(root), "/usr/lib/libSystem.B.dylib")
            .expect("translate absolute");
        assert_eq!(host, PathBuf::from("/opt/bottle/usr/lib/libSystem.B.dylib"));
    }

    #[test]
    fn relative_stays_host_cwd_even_with_bottle() {
        let root = Path::new("/opt/bottle");
        let host = translate_path_with_root(Some(root), "tmp/x").expect("translate relative");
        assert_eq!(host, PathBuf::from("tmp/x"));
    }

    #[test]
    fn relative_rejects_dotdot() {
        let root = Path::new("/opt/bottle");
        let err = translate_path_with_root(Some(root), "../etc/passwd").expect_err("..");
        assert!(matches!(err, PathError::Escape(_)));
    }

    #[test]
    fn no_bottle_passthrough() {
        let host = translate_path_with_root(None, "/tmp/foo").expect("passthrough");
        assert_eq!(host, PathBuf::from("/tmp/foo"));
    }

    #[test]
    fn rejects_parent_dir() {
        let root = Path::new("/opt/bottle");
        let err =
            translate_path_with_root(Some(root), "/usr/../etc/passwd").expect_err("must reject ..");
        assert!(matches!(err, PathError::Escape(_)));
    }

    #[test]
    fn empty_rejected() {
        assert_eq!(translate_path_with_root(None, ""), Err(PathError::Empty));
    }

    #[test]
    fn volumes_linux_is_host_bridge_not_bottle_join() {
        let root = Path::new("/var/lib/my-renamed-bottle");
        let host = translate_path_with_root(Some(root), "/Volumes/linux/tmp/x")
            .expect("translate volumes");
        assert_eq!(host, PathBuf::from("/tmp/x"));
    }

    #[test]
    fn fast_path_dots_in_name_ok() {
        let root = Path::new("/b");
        let host = translate_path_with_root(Some(root), "/foo..bar").expect("dots in name");
        assert_eq!(host, PathBuf::from("/b/foo..bar"));
    }

    #[test]
    fn host_tmp_maps_to_private_tmp_guest() {
        set_bottle_root(None);
        let guest = host_path_to_guest(Path::new("/tmp/kh-guest-cwd-test")).expect("map");
        assert_eq!(guest, "/private/tmp/kh-guest-cwd-test");
    }

    #[test]
    fn host_path_preserves_multicall_symlink_leaf() {
        let tmp = std::env::temp_dir().join(format!("kh-ranlib-leaf-{}", std::process::id()));
        drop(std::fs::remove_dir_all(&tmp));
        let bin = tmp.join("usr/bin");
        std::fs::create_dir_all(&bin).expect("mkdir");
        let libtool = bin.join("libtool");
        std::fs::write(&libtool, b"x").expect("write libtool");
        let ranlib = bin.join("ranlib");
        #[cfg(unix)]
        std::os::unix::fs::symlink("libtool", &ranlib).expect("symlink ranlib");
        set_bottle_root(Some(tmp.clone()));
        let guest = host_path_to_guest(&ranlib).expect("map ranlib");
        assert_eq!(guest, "/usr/bin/ranlib", "multi-call leaf must stay ranlib");
        set_bottle_root(None);
        drop(std::fs::remove_dir_all(&tmp));
    }

    #[test]
    fn bridge_private_tmp_to_host() {
        let host = translate_path_with_root(Some(Path::new("/opt/bottle")), "/private/tmp/x")
            .expect("bridge");
        assert_eq!(host, PathBuf::from("/tmp/x"));
    }

    #[test]
    fn bridge_volumes_linux_to_host() {
        let host =
            translate_path_with_root(Some(Path::new("/opt/bottle")), "/Volumes/linux/home/a")
                .expect("bridge");
        assert_eq!(host, PathBuf::from("/home/a"));
    }

    #[test]
    fn bottle_openat_rel_uses_dirfd_when_configured() {
        let tmp = std::env::temp_dir().join(format!("kh-b1-openat-{}", std::process::id()));
        drop(std::fs::remove_dir_all(&tmp));
        std::fs::create_dir_all(tmp.join("usr/lib")).expect("mkdir");
        set_bottle_root(Some(tmp.clone()));
        let (fd, rel) = bottle_openat_rel("/usr/lib/libSystem.B.dylib").expect("openat parts");
        assert!(fd >= 0);
        assert_eq!(rel, "usr/lib/libSystem.B.dylib");
        assert!(bottle_openat_rel("relative").is_none());
        set_bottle_root(None);
        assert!(bottle_openat_rel("/usr/lib/x").is_none());
        drop(std::fs::remove_dir_all(&tmp));
    }
}