Skip to main content

kh_runtime/bottle/
libsystem.rs

1//! Install guest `libSystem.B.dylib` into a bottle.
2//!
3//! Discovery / install order used by `kh bottle create|ensure`:
4//!
5//! 1. **`--libsystem PATH`** / explicit argument
6//! 2. **`KAKEHASHI_LIBSYSTEM`**
7//! 3. Paths next to the running `kh` binary (release layout:
8//!    `lib/kakehashi/libSystem.B.dylib`, …)
9//! 4. Workspace / dev trees: `dist/guest/`, Cargo `target/…`, and the
10//!    vendored crate resource `crates/kh-runtime/resources/libSystem.B.dylib`
11//! 5. **Embedded bytes** shipped inside `kh-runtime` (`resources/libSystem.B.dylib`
12//!    on crates.io) — so `cargo install kakehashi` works with only
13//!    `kh bottle ensure` and no separate dylib download
14//!
15//! Build / refresh the freestanding dylib (macOS or cross target):
16//! ```text
17//! cargo build -p kh-libsystem --release --target aarch64-apple-darwin
18//! ./scripts/stage-libsystem.sh   # → dist/guest + resources/ (crates.io embed)
19//! ```
20
21use std::fs;
22use std::path::{Path, PathBuf};
23
24use super::manage::BottleError;
25
26/// Relative path under the bottle root (guest `/usr/lib/libSystem.B.dylib`).
27pub const GUEST_LIBSYSTEM_REL: &str = "usr/lib/libSystem.B.dylib";
28
29/// Canonical `LC_ID_DYLIB` / guest install name.
30pub const GUEST_LIBSYSTEM_ID: &str = "/usr/lib/libSystem.B.dylib";
31
32/// Env var for an explicit source dylib (release unpack or custom path).
33pub const ENV_LIBSYSTEM: &str = "KAKEHASHI_LIBSYSTEM";
34
35/// Synthetic `LibsystemInstall::source` when bytes came from the crate embed.
36pub const EMBEDDED_SOURCE_LABEL: &str = "<embedded>";
37
38const MH_MAGIC_64: u32 = 0xfeed_facf;
39const LC_ID_DYLIB: u32 = 0xd;
40
41/// How the source dylib was located.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43pub enum LibsystemOrigin {
44    /// `--libsystem` / explicit path.
45    Explicit,
46    /// `KAKEHASHI_LIBSYSTEM`.
47    Env,
48    /// Next to the `kh` binary (release layout or `target/debug/kh`).
49    Adjacent,
50    /// Workspace `target/` / `dist/guest` / crate `resources/` under cwd.
51    DevTarget,
52    /// Bytes compiled into `kh-runtime` (crates.io / `cargo install` path).
53    Embedded,
54}
55
56/// Result of installing libSystem into a bottle.
57#[derive(Debug, Clone, PartialEq, Eq)]
58pub struct LibsystemInstall {
59    /// Host path of the source dylib that was copied, or
60    /// [`EMBEDDED_SOURCE_LABEL`] when installed from the crate embed.
61    pub source: PathBuf,
62    /// Absolute path of `{bottle}/usr/lib/libSystem.B.dylib`.
63    pub dest: PathBuf,
64    /// Where `source` was found.
65    pub origin: LibsystemOrigin,
66    /// Whether `LC_ID_DYLIB` was rewritten to [`GUEST_LIBSYSTEM_ID`].
67    pub id_rewritten: bool,
68}
69
70/// Discovers a guest libSystem dylib **file** for bottle install.
71///
72/// Does not cover the compile-time embed — that is handled by bottle create
73/// after this returns `None` (see `manage`).
74///
75/// Order:
76/// 1. `explicit` argument
77/// 2. `KAKEHASHI_LIBSYSTEM`
78/// 3. Paths relative to the running `kh` executable (release layout)
79/// 4. Common Cargo / staged paths under the current working directory
80#[must_use]
81pub fn discover(explicit: Option<&Path>) -> Option<(PathBuf, LibsystemOrigin)> {
82    if let Some(p) = explicit {
83        if p.is_file() {
84            return Some((p.to_path_buf(), LibsystemOrigin::Explicit));
85        }
86        return None;
87    }
88
89    if let Ok(raw) = std::env::var(ENV_LIBSYSTEM) {
90        let p = PathBuf::from(raw);
91        if p.is_file() {
92            return Some((p, LibsystemOrigin::Env));
93        }
94    }
95
96    if let Some(p) = discover_adjacent() {
97        return Some((p, LibsystemOrigin::Adjacent));
98    }
99
100    if let Some(p) = discover_dev_target() {
101        return Some((p, LibsystemOrigin::DevTarget));
102    }
103
104    None
105}
106
107/// Copies `source` into `{root}/usr/lib/libSystem.B.dylib` and ensures
108/// `LC_ID_DYLIB` is [`GUEST_LIBSYSTEM_ID`] (in-place rewrite when needed).
109pub fn install(
110    root: &Path,
111    source: &Path,
112    origin: LibsystemOrigin,
113) -> Result<LibsystemInstall, BottleError> {
114    if !source.is_file() {
115        return Err(BottleError::Io(std::io::Error::new(
116            std::io::ErrorKind::NotFound,
117            format!("libSystem source not found: {}", source.display()),
118        )));
119    }
120
121    let bytes = fs::read(source)?;
122    let mut result = install_bytes(root, &bytes, origin)?;
123    result.source = source.to_path_buf();
124    Ok(result)
125}
126
127/// Writes raw Mach-O bytes into `{root}/usr/lib/libSystem.B.dylib`, rewriting
128/// `LC_ID_DYLIB` when needed. Used for the crates.io-embedded freestanding
129/// dylib and by [`install`] after reading a file.
130pub fn install_bytes(
131    root: &Path,
132    source_bytes: &[u8],
133    origin: LibsystemOrigin,
134) -> Result<LibsystemInstall, BottleError> {
135    if source_bytes.is_empty() {
136        return Err(BottleError::Io(std::io::Error::new(
137            std::io::ErrorKind::InvalidData,
138            "libSystem source is empty",
139        )));
140    }
141
142    let dest = root.join(GUEST_LIBSYSTEM_REL);
143    if let Some(parent) = dest.parent() {
144        fs::create_dir_all(parent)?;
145    }
146
147    let mut bytes = source_bytes.to_vec();
148    let id_rewritten = ensure_libsystem_id(&mut bytes)?;
149    fs::write(&dest, &bytes)?;
150
151    // Match typical dylib mode (rwxr-xr-x); ignore errors on exotic FS.
152    #[cfg(unix)]
153    {
154        use std::os::unix::fs::PermissionsExt;
155        drop(fs::set_permissions(
156            &dest,
157            fs::Permissions::from_mode(0o755),
158        ));
159    }
160
161    Ok(LibsystemInstall {
162        source: PathBuf::from(EMBEDDED_SOURCE_LABEL),
163        dest,
164        origin,
165        id_rewritten,
166    })
167}
168
169/// Ensures thin little-endian Mach-O `LC_ID_DYLIB` is [`GUEST_LIBSYSTEM_ID`].
170///
171/// Returns `true` if the load-command path was rewritten. Fat binaries and
172/// big-endian images are rejected (guest dylib is always thin arm64).
173pub fn ensure_libsystem_id(bytes: &mut [u8]) -> Result<bool, BottleError> {
174    patch_lc_id_dylib(bytes, GUEST_LIBSYSTEM_ID)
175}
176
177fn discover_adjacent() -> Option<PathBuf> {
178    let exe = std::env::current_exe().ok()?;
179    let dir = exe.parent()?;
180    let candidates = [
181        dir.join("libSystem.B.dylib"),
182        dir.join("libkh_libsystem.dylib"),
183        dir.join("lib/kakehashi/libSystem.B.dylib"),
184        dir.join("lib/kakehashi/libkh_libsystem.dylib"),
185        dir.join("../lib/kakehashi/libSystem.B.dylib"),
186        dir.join("../lib/kakehashi/libkh_libsystem.dylib"),
187        dir.join("share/kakehashi/libSystem.B.dylib"),
188        dir.join("../share/kakehashi/libSystem.B.dylib"),
189    ];
190    first_file(&candidates)
191}
192
193fn discover_dev_target() -> Option<PathBuf> {
194    let cwd = std::env::current_dir().ok()?;
195    // Walk cwd → parents so Docker `-w /src` and nested shells still find a
196    // workspace-staged dylib without hand-building `.tmp-bottle`.
197    let mut dir = Some(cwd.as_path());
198    while let Some(base) = dir {
199        if let Some(p) = discover_under_workspace(base) {
200            return Some(p);
201        }
202        dir = base.parent();
203    }
204    None
205}
206
207/// Candidate relative paths under a Cargo / release workspace root.
208fn discover_under_workspace(base: &Path) -> Option<PathBuf> {
209    let names = ["libSystem.B.dylib", "libkh_libsystem.dylib"];
210    let dirs = [
211        // Staged guest install name (`scripts/stage-libsystem.sh`).
212        "dist/guest",
213        // Vendored crates.io embed (same bytes as `include_bytes!` in manage).
214        "crates/kh-runtime/resources",
215        "resources",
216        "target/release",
217        "target/debug",
218        "target/aarch64-apple-darwin/release",
219        "target/aarch64-apple-darwin/debug",
220    ];
221    let mut candidates = Vec::new();
222    for d in dirs {
223        for n in names {
224            candidates.push(base.join(d).join(n));
225        }
226    }
227    first_file(&candidates)
228}
229
230fn first_file(paths: &[PathBuf]) -> Option<PathBuf> {
231    paths.iter().find(|p| p.is_file()).cloned()
232}
233
234fn patch_lc_id_dylib(bytes: &mut [u8], new_id: &str) -> Result<bool, BottleError> {
235    if bytes.len() < 32 {
236        return Err(id_err("file too small to be Mach-O"));
237    }
238
239    let magic = read_u32_le(bytes, 0)?;
240    if magic == 0xcafe_babe || magic == 0xcafe_babf || magic == 0xbeba_feca || magic == 0xbfba_feca
241    {
242        return Err(id_err(
243            "fat Mach-O is not supported; ship a thin aarch64 libSystem.B.dylib",
244        ));
245    }
246    if magic != MH_MAGIC_64 {
247        return Err(id_err(format!(
248            "not a little-endian 64-bit Mach-O (magic {magic:#x})"
249        )));
250    }
251
252    let ncmds = usize_from_u32(read_u32_le(bytes, 16)?)?;
253    let sizeofcmds = usize_from_u32(read_u32_le(bytes, 20)?)?;
254    let cmds_start = 32usize;
255    let cmds_end = cmds_start
256        .checked_add(sizeofcmds)
257        .ok_or_else(|| id_err("sizeofcmds overflow"))?;
258    if cmds_end > bytes.len() {
259        return Err(id_err("load commands extend past file"));
260    }
261
262    let mut off = cmds_start;
263    for _ in 0..ncmds {
264        if off.checked_add(8).is_none_or(|e| e > cmds_end) {
265            return Err(id_err("truncated load command"));
266        }
267        let cmd = read_u32_le(bytes, off)?;
268        let cmdsize = usize_from_u32(read_u32_le(bytes, off.saturating_add(4))?)?;
269        if cmdsize < 8 {
270            return Err(id_err("invalid load command size"));
271        }
272        let cmd_end = off
273            .checked_add(cmdsize)
274            .ok_or_else(|| id_err("cmdsize overflow"))?;
275        if cmd_end > cmds_end {
276            return Err(id_err("load command extends past sizeofcmds"));
277        }
278
279        if cmd == LC_ID_DYLIB {
280            return rewrite_id_name(bytes, off, cmdsize, new_id);
281        }
282        off = cmd_end;
283    }
284    Err(id_err("LC_ID_DYLIB not found"))
285}
286
287fn rewrite_id_name(
288    bytes: &mut [u8],
289    cmd_off: usize,
290    cmdsize: usize,
291    new_id: &str,
292) -> Result<bool, BottleError> {
293    // struct dylib_command { cmd, cmdsize, dylib { name.offset, timestamp, current, compat } }
294    if cmdsize < 24 {
295        return Err(id_err("LC_ID_DYLIB too small"));
296    }
297    let name_off = usize_from_u32(read_u32_le(bytes, cmd_off.saturating_add(8))?)?;
298    if name_off >= cmdsize {
299        return Err(id_err("LC_ID_DYLIB name offset out of range"));
300    }
301    let name_start = cmd_off
302        .checked_add(name_off)
303        .ok_or_else(|| id_err("name offset overflow"))?;
304    let name_cap = cmdsize
305        .checked_sub(name_off)
306        .ok_or_else(|| id_err("name capacity underflow"))?;
307    let new_bytes = new_id.as_bytes();
308    let need = new_bytes
309        .len()
310        .checked_add(1)
311        .ok_or_else(|| id_err("new id length overflow"))?;
312    if need > name_cap {
313        return Err(id_err(format!(
314            "LC_ID_DYLIB name field too short for {new_id} (cap {name_cap})"
315        )));
316    }
317
318    let cmd_end = cmd_off
319        .checked_add(cmdsize)
320        .ok_or_else(|| id_err("cmd end overflow"))?;
321    let field = bytes
322        .get(name_start..cmd_end)
323        .ok_or_else(|| id_err("name field out of range"))?;
324    let old_len = field.iter().position(|&c| c == 0).unwrap_or(field.len());
325    let old = field
326        .get(..old_len)
327        .ok_or_else(|| id_err("old name slice"))?;
328    if old == new_bytes {
329        return Ok(false);
330    }
331
332    let dest = bytes
333        .get_mut(name_start..cmd_end)
334        .ok_or_else(|| id_err("name field mut out of range"))?;
335    if new_bytes.len() > dest.len() {
336        return Err(id_err("new id does not fit"));
337    }
338    let (head, tail) = dest.split_at_mut(new_bytes.len());
339    head.copy_from_slice(new_bytes);
340    for b in tail {
341        *b = 0;
342    }
343    Ok(true)
344}
345
346fn read_u32_le(bytes: &[u8], off: usize) -> Result<u32, BottleError> {
347    let end = off
348        .checked_add(4)
349        .ok_or_else(|| id_err("u32 offset overflow"))?;
350    let raw = bytes
351        .get(off..end)
352        .ok_or_else(|| id_err("out of range u32"))?;
353    let arr: [u8; 4] = raw.try_into().map_err(|_| id_err("u32 slice length"))?;
354    Ok(u32::from_le_bytes(arr))
355}
356
357fn usize_from_u32(v: u32) -> Result<usize, BottleError> {
358    usize::try_from(v).map_err(|_| id_err("u32 does not fit usize"))
359}
360
361fn id_err(msg: impl Into<String>) -> BottleError {
362    BottleError::Io(std::io::Error::new(
363        std::io::ErrorKind::InvalidData,
364        msg.into(),
365    ))
366}
367
368#[cfg(test)]
369#[allow(
370    clippy::expect_used,
371    clippy::panic,
372    clippy::unwrap_used,
373    clippy::indexing_slicing,
374    clippy::as_conversions,
375    clippy::cast_possible_truncation,
376    clippy::arithmetic_side_effects
377)]
378mod tests {
379    use super::*;
380    use std::sync::atomic::{AtomicU64, Ordering};
381
382    fn temp_dir(prefix: &str) -> PathBuf {
383        static N: AtomicU64 = AtomicU64::new(0);
384        let n = N.fetch_add(1, Ordering::Relaxed);
385        let dir =
386            std::env::temp_dir().join(format!("kh-libsys-{}-{}-{n}", prefix, std::process::id()));
387        drop(fs::remove_dir_all(&dir));
388        fs::create_dir_all(&dir).expect("mkdir");
389        dir
390    }
391
392    /// Minimal MH_DYLIB with LC_ID_DYLIB only (enough for the patcher).
393    fn minimal_dylib(id: &str) -> Vec<u8> {
394        const CPU_TYPE_ARM64: u32 = 0x0100_000c;
395        const MH_DYLIB: u32 = 6;
396
397        let mut name = id.as_bytes().to_vec();
398        name.push(0);
399        while !name.len().is_multiple_of(8) {
400            name.push(0);
401        }
402        while name.len() < 40 {
403            name.push(0);
404        }
405        let cmdsize = 24 + name.len();
406        let sizeofcmds = u32::try_from(cmdsize).expect("cmdsize");
407        let cmdsize_u = sizeofcmds;
408
409        let mut buf = Vec::new();
410        buf.extend_from_slice(&MH_MAGIC_64.to_le_bytes());
411        buf.extend_from_slice(&CPU_TYPE_ARM64.to_le_bytes());
412        buf.extend_from_slice(&0u32.to_le_bytes());
413        buf.extend_from_slice(&MH_DYLIB.to_le_bytes());
414        buf.extend_from_slice(&1u32.to_le_bytes());
415        buf.extend_from_slice(&sizeofcmds.to_le_bytes());
416        buf.extend_from_slice(&0u32.to_le_bytes());
417        buf.extend_from_slice(&0u32.to_le_bytes());
418
419        buf.extend_from_slice(&LC_ID_DYLIB.to_le_bytes());
420        buf.extend_from_slice(&cmdsize_u.to_le_bytes());
421        buf.extend_from_slice(&24u32.to_le_bytes());
422        buf.extend_from_slice(&1u32.to_le_bytes());
423        buf.extend_from_slice(&0x0001_0000u32.to_le_bytes());
424        buf.extend_from_slice(&0x0001_0000u32.to_le_bytes());
425        buf.extend_from_slice(&name);
426        buf
427    }
428
429    fn read_id(bytes: &[u8]) -> String {
430        let ncmds = u32::from_le_bytes(bytes[16..20].try_into().unwrap()) as usize;
431        let mut off = 32usize;
432        for _ in 0..ncmds {
433            let cmd = u32::from_le_bytes(bytes[off..off + 4].try_into().unwrap());
434            let cmdsize = u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize;
435            if cmd == LC_ID_DYLIB {
436                let name_off =
437                    u32::from_le_bytes(bytes[off + 8..off + 12].try_into().unwrap()) as usize;
438                let start = off + name_off;
439                let end = bytes[start..]
440                    .iter()
441                    .position(|&c| c == 0)
442                    .map(|n| start + n)
443                    .unwrap();
444                return String::from_utf8(bytes[start..end].to_vec()).unwrap();
445            }
446            off += cmdsize;
447        }
448        panic!("no LC_ID_DYLIB");
449    }
450
451    #[test]
452    fn rewrite_rpath_id_to_guest() {
453        let mut bytes = minimal_dylib("@rpath/libkh_libsystem.dylib");
454        assert_eq!(read_id(&bytes), "@rpath/libkh_libsystem.dylib");
455        let changed = ensure_libsystem_id(&mut bytes).expect("patch");
456        assert!(changed);
457        assert_eq!(read_id(&bytes), GUEST_LIBSYSTEM_ID);
458        let changed_again = ensure_libsystem_id(&mut bytes).expect("idempotent");
459        assert!(!changed_again);
460    }
461
462    #[test]
463    fn install_copies_and_sets_id() {
464        let root = temp_dir("install");
465        super::super::layout::materialize(&root).expect("materialize");
466        let src_dir = temp_dir("src");
467        let src = src_dir.join("libkh_libsystem.dylib");
468        fs::write(&src, minimal_dylib("@rpath/libkh_libsystem.dylib")).expect("write src");
469
470        let inst = install(&root, &src, LibsystemOrigin::Explicit).expect("install");
471        assert!(inst.id_rewritten);
472        assert_eq!(inst.dest, root.join(GUEST_LIBSYSTEM_REL));
473        assert_eq!(inst.source, src);
474        assert!(inst.dest.is_file());
475        let on_disk = fs::read(&inst.dest).expect("read dest");
476        assert_eq!(read_id(&on_disk), GUEST_LIBSYSTEM_ID);
477
478        drop(fs::remove_dir_all(&root));
479        drop(fs::remove_dir_all(&src_dir));
480    }
481
482    #[test]
483    fn install_bytes_sets_embedded_label() {
484        let root = temp_dir("bytes");
485        super::super::layout::materialize(&root).expect("materialize");
486        let raw = minimal_dylib("@rpath/libkh_libsystem.dylib");
487        let inst = install_bytes(&root, &raw, LibsystemOrigin::Embedded).expect("install_bytes");
488        assert_eq!(inst.source, PathBuf::from(EMBEDDED_SOURCE_LABEL));
489        assert_eq!(inst.origin, LibsystemOrigin::Embedded);
490        assert!(inst.id_rewritten);
491        assert_eq!(
492            read_id(&fs::read(&inst.dest).expect("read")),
493            GUEST_LIBSYSTEM_ID
494        );
495        drop(fs::remove_dir_all(&root));
496    }
497
498    #[test]
499    fn discover_explicit_missing_is_none() {
500        assert!(discover(Some(Path::new("/no/such/libSystem.B.dylib"))).is_none());
501    }
502
503    #[test]
504    fn rejects_fat_magic() {
505        let mut bytes = vec![0u8; 64];
506        bytes[0..4].copy_from_slice(&0xcafe_babeu32.to_be_bytes());
507        let err = ensure_libsystem_id(&mut bytes).expect_err("fat");
508        let msg = err.to_string();
509        assert!(msg.contains("fat"), "{msg}");
510    }
511}