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: Cargo `target/…` and the vendored crate resource
10//!    `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   # → crates/kh-runtime/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/` / 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    // Prefer a just-built product, then the staged crates.io embed path.
211    let dirs = [
212        "target/aarch64-apple-darwin/release",
213        "target/aarch64-apple-darwin/debug",
214        "target/release",
215        "target/debug",
216        // Vendored crates.io embed (same bytes as `include_bytes!` in manage).
217        "crates/kh-runtime/resources",
218        "resources",
219    ];
220    let mut candidates = Vec::new();
221    for d in dirs {
222        for n in names {
223            candidates.push(base.join(d).join(n));
224        }
225    }
226    first_file(&candidates)
227}
228
229fn first_file(paths: &[PathBuf]) -> Option<PathBuf> {
230    paths.iter().find(|p| p.is_file()).cloned()
231}
232
233fn patch_lc_id_dylib(bytes: &mut [u8], new_id: &str) -> Result<bool, BottleError> {
234    if bytes.len() < 32 {
235        return Err(id_err("file too small to be Mach-O"));
236    }
237
238    let magic = read_u32_le(bytes, 0)?;
239    if magic == 0xcafe_babe || magic == 0xcafe_babf || magic == 0xbeba_feca || magic == 0xbfba_feca
240    {
241        return Err(id_err(
242            "fat Mach-O is not supported; ship a thin aarch64 libSystem.B.dylib",
243        ));
244    }
245    if magic != MH_MAGIC_64 {
246        return Err(id_err(format!(
247            "not a little-endian 64-bit Mach-O (magic {magic:#x})"
248        )));
249    }
250
251    let ncmds = usize_from_u32(read_u32_le(bytes, 16)?)?;
252    let sizeofcmds = usize_from_u32(read_u32_le(bytes, 20)?)?;
253    let cmds_start = 32usize;
254    let cmds_end = cmds_start
255        .checked_add(sizeofcmds)
256        .ok_or_else(|| id_err("sizeofcmds overflow"))?;
257    if cmds_end > bytes.len() {
258        return Err(id_err("load commands extend past file"));
259    }
260
261    let mut off = cmds_start;
262    for _ in 0..ncmds {
263        if off.checked_add(8).is_none_or(|e| e > cmds_end) {
264            return Err(id_err("truncated load command"));
265        }
266        let cmd = read_u32_le(bytes, off)?;
267        let cmdsize = usize_from_u32(read_u32_le(bytes, off.saturating_add(4))?)?;
268        if cmdsize < 8 {
269            return Err(id_err("invalid load command size"));
270        }
271        let cmd_end = off
272            .checked_add(cmdsize)
273            .ok_or_else(|| id_err("cmdsize overflow"))?;
274        if cmd_end > cmds_end {
275            return Err(id_err("load command extends past sizeofcmds"));
276        }
277
278        if cmd == LC_ID_DYLIB {
279            return rewrite_id_name(bytes, off, cmdsize, new_id);
280        }
281        off = cmd_end;
282    }
283    Err(id_err("LC_ID_DYLIB not found"))
284}
285
286fn rewrite_id_name(
287    bytes: &mut [u8],
288    cmd_off: usize,
289    cmdsize: usize,
290    new_id: &str,
291) -> Result<bool, BottleError> {
292    // struct dylib_command { cmd, cmdsize, dylib { name.offset, timestamp, current, compat } }
293    if cmdsize < 24 {
294        return Err(id_err("LC_ID_DYLIB too small"));
295    }
296    let name_off = usize_from_u32(read_u32_le(bytes, cmd_off.saturating_add(8))?)?;
297    if name_off >= cmdsize {
298        return Err(id_err("LC_ID_DYLIB name offset out of range"));
299    }
300    let name_start = cmd_off
301        .checked_add(name_off)
302        .ok_or_else(|| id_err("name offset overflow"))?;
303    let name_cap = cmdsize
304        .checked_sub(name_off)
305        .ok_or_else(|| id_err("name capacity underflow"))?;
306    let new_bytes = new_id.as_bytes();
307    let need = new_bytes
308        .len()
309        .checked_add(1)
310        .ok_or_else(|| id_err("new id length overflow"))?;
311    if need > name_cap {
312        return Err(id_err(format!(
313            "LC_ID_DYLIB name field too short for {new_id} (cap {name_cap})"
314        )));
315    }
316
317    let cmd_end = cmd_off
318        .checked_add(cmdsize)
319        .ok_or_else(|| id_err("cmd end overflow"))?;
320    let field = bytes
321        .get(name_start..cmd_end)
322        .ok_or_else(|| id_err("name field out of range"))?;
323    let old_len = field.iter().position(|&c| c == 0).unwrap_or(field.len());
324    let old = field
325        .get(..old_len)
326        .ok_or_else(|| id_err("old name slice"))?;
327    if old == new_bytes {
328        return Ok(false);
329    }
330
331    let dest = bytes
332        .get_mut(name_start..cmd_end)
333        .ok_or_else(|| id_err("name field mut out of range"))?;
334    if new_bytes.len() > dest.len() {
335        return Err(id_err("new id does not fit"));
336    }
337    let (head, tail) = dest.split_at_mut(new_bytes.len());
338    head.copy_from_slice(new_bytes);
339    for b in tail {
340        *b = 0;
341    }
342    Ok(true)
343}
344
345fn read_u32_le(bytes: &[u8], off: usize) -> Result<u32, BottleError> {
346    let end = off
347        .checked_add(4)
348        .ok_or_else(|| id_err("u32 offset overflow"))?;
349    let raw = bytes
350        .get(off..end)
351        .ok_or_else(|| id_err("out of range u32"))?;
352    let arr: [u8; 4] = raw.try_into().map_err(|_| id_err("u32 slice length"))?;
353    Ok(u32::from_le_bytes(arr))
354}
355
356fn usize_from_u32(v: u32) -> Result<usize, BottleError> {
357    usize::try_from(v).map_err(|_| id_err("u32 does not fit usize"))
358}
359
360fn id_err(msg: impl Into<String>) -> BottleError {
361    BottleError::Io(std::io::Error::new(
362        std::io::ErrorKind::InvalidData,
363        msg.into(),
364    ))
365}
366
367#[cfg(test)]
368#[allow(
369    clippy::expect_used,
370    clippy::panic,
371    clippy::unwrap_used,
372    clippy::indexing_slicing,
373    clippy::as_conversions,
374    clippy::cast_possible_truncation,
375    clippy::arithmetic_side_effects
376)]
377mod tests {
378    use super::*;
379    use std::sync::atomic::{AtomicU64, Ordering};
380
381    fn temp_dir(prefix: &str) -> PathBuf {
382        static N: AtomicU64 = AtomicU64::new(0);
383        let n = N.fetch_add(1, Ordering::Relaxed);
384        let dir =
385            std::env::temp_dir().join(format!("kh-libsys-{}-{}-{n}", prefix, std::process::id()));
386        drop(fs::remove_dir_all(&dir));
387        fs::create_dir_all(&dir).expect("mkdir");
388        dir
389    }
390
391    /// Minimal MH_DYLIB with LC_ID_DYLIB only (enough for the patcher).
392    fn minimal_dylib(id: &str) -> Vec<u8> {
393        const CPU_TYPE_ARM64: u32 = 0x0100_000c;
394        const MH_DYLIB: u32 = 6;
395
396        let mut name = id.as_bytes().to_vec();
397        name.push(0);
398        while !name.len().is_multiple_of(8) {
399            name.push(0);
400        }
401        while name.len() < 40 {
402            name.push(0);
403        }
404        let cmdsize = 24 + name.len();
405        let sizeofcmds = u32::try_from(cmdsize).expect("cmdsize");
406        let cmdsize_u = sizeofcmds;
407
408        let mut buf = Vec::new();
409        buf.extend_from_slice(&MH_MAGIC_64.to_le_bytes());
410        buf.extend_from_slice(&CPU_TYPE_ARM64.to_le_bytes());
411        buf.extend_from_slice(&0u32.to_le_bytes());
412        buf.extend_from_slice(&MH_DYLIB.to_le_bytes());
413        buf.extend_from_slice(&1u32.to_le_bytes());
414        buf.extend_from_slice(&sizeofcmds.to_le_bytes());
415        buf.extend_from_slice(&0u32.to_le_bytes());
416        buf.extend_from_slice(&0u32.to_le_bytes());
417
418        buf.extend_from_slice(&LC_ID_DYLIB.to_le_bytes());
419        buf.extend_from_slice(&cmdsize_u.to_le_bytes());
420        buf.extend_from_slice(&24u32.to_le_bytes());
421        buf.extend_from_slice(&1u32.to_le_bytes());
422        buf.extend_from_slice(&0x0001_0000u32.to_le_bytes());
423        buf.extend_from_slice(&0x0001_0000u32.to_le_bytes());
424        buf.extend_from_slice(&name);
425        buf
426    }
427
428    fn read_id(bytes: &[u8]) -> String {
429        let ncmds = u32::from_le_bytes(bytes[16..20].try_into().unwrap()) as usize;
430        let mut off = 32usize;
431        for _ in 0..ncmds {
432            let cmd = u32::from_le_bytes(bytes[off..off + 4].try_into().unwrap());
433            let cmdsize = u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize;
434            if cmd == LC_ID_DYLIB {
435                let name_off =
436                    u32::from_le_bytes(bytes[off + 8..off + 12].try_into().unwrap()) as usize;
437                let start = off + name_off;
438                let end = bytes[start..]
439                    .iter()
440                    .position(|&c| c == 0)
441                    .map(|n| start + n)
442                    .unwrap();
443                return String::from_utf8(bytes[start..end].to_vec()).unwrap();
444            }
445            off += cmdsize;
446        }
447        panic!("no LC_ID_DYLIB");
448    }
449
450    #[test]
451    fn rewrite_rpath_id_to_guest() {
452        let mut bytes = minimal_dylib("@rpath/libkh_libsystem.dylib");
453        assert_eq!(read_id(&bytes), "@rpath/libkh_libsystem.dylib");
454        let changed = ensure_libsystem_id(&mut bytes).expect("patch");
455        assert!(changed);
456        assert_eq!(read_id(&bytes), GUEST_LIBSYSTEM_ID);
457        let changed_again = ensure_libsystem_id(&mut bytes).expect("idempotent");
458        assert!(!changed_again);
459    }
460
461    #[test]
462    fn install_copies_and_sets_id() {
463        let root = temp_dir("install");
464        super::super::layout::materialize(&root).expect("materialize");
465        let src_dir = temp_dir("src");
466        let src = src_dir.join("libkh_libsystem.dylib");
467        fs::write(&src, minimal_dylib("@rpath/libkh_libsystem.dylib")).expect("write src");
468
469        let inst = install(&root, &src, LibsystemOrigin::Explicit).expect("install");
470        assert!(inst.id_rewritten);
471        assert_eq!(inst.dest, root.join(GUEST_LIBSYSTEM_REL));
472        assert_eq!(inst.source, src);
473        assert!(inst.dest.is_file());
474        let on_disk = fs::read(&inst.dest).expect("read dest");
475        assert_eq!(read_id(&on_disk), GUEST_LIBSYSTEM_ID);
476
477        drop(fs::remove_dir_all(&root));
478        drop(fs::remove_dir_all(&src_dir));
479    }
480
481    #[test]
482    fn install_bytes_sets_embedded_label() {
483        let root = temp_dir("bytes");
484        super::super::layout::materialize(&root).expect("materialize");
485        let raw = minimal_dylib("@rpath/libkh_libsystem.dylib");
486        let inst = install_bytes(&root, &raw, LibsystemOrigin::Embedded).expect("install_bytes");
487        assert_eq!(inst.source, PathBuf::from(EMBEDDED_SOURCE_LABEL));
488        assert_eq!(inst.origin, LibsystemOrigin::Embedded);
489        assert!(inst.id_rewritten);
490        assert_eq!(
491            read_id(&fs::read(&inst.dest).expect("read")),
492            GUEST_LIBSYSTEM_ID
493        );
494        drop(fs::remove_dir_all(&root));
495    }
496
497    #[test]
498    fn discover_explicit_missing_is_none() {
499        assert!(discover(Some(Path::new("/no/such/libSystem.B.dylib"))).is_none());
500    }
501
502    #[test]
503    fn rejects_fat_magic() {
504        let mut bytes = vec![0u8; 64];
505        bytes[0..4].copy_from_slice(&0xcafe_babeu32.to_be_bytes());
506        let err = ensure_libsystem_id(&mut bytes).expect_err("fat");
507        let msg = err.to_string();
508        assert!(msg.contains("fat"), "{msg}");
509    }
510}