Skip to main content

kh_runtime/bottle/
xcrun_tool.rs

1//! Install guest `/usr/bin/xcrun` into a bottle.
2//!
3//! Discovery / install order used by `kh bottle create|ensure` (same shape as
4//! [`super::libsystem`]):
5//!
6//! 1. **`KAKEHASHI_XCRUN`** (host path of a Mach-O `xcrun`)
7//! 2. Paths next to the running `kh` binary
8//! 3. Workspace / dev trees: Cargo `target/…` and
9//!    `crates/kh-runtime/resources/xcrun`
10//! 4. **Embedded bytes** shipped inside `kh-runtime` (`resources/xcrun`)
11//!
12//! Build / refresh (macOS arm64 host or cross target):
13//! ```text
14//! cargo build -p kh-xcrun --release --target aarch64-apple-darwin
15//! ./scripts/stage-xcrun.sh
16//! ```
17
18use std::fs;
19use std::path::{Path, PathBuf};
20
21use super::manage::BottleError;
22
23/// Relative path under the bottle root (guest `/usr/bin/xcrun`).
24pub const GUEST_XCRUN_REL: &str = "usr/bin/xcrun";
25
26/// Env var for an explicit source binary.
27pub const ENV_XCRUN: &str = "KAKEHASHI_XCRUN";
28
29/// Synthetic source label when bytes came from the crate embed.
30pub const EMBEDDED_SOURCE_LABEL: &str = "<embedded>";
31
32/// How the source `xcrun` binary was located.
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
34pub enum XcrunOrigin {
35    /// `KAKEHASHI_XCRUN` or explicit path.
36    Explicit,
37    /// Next to the `kh` binary.
38    Adjacent,
39    /// Workspace `target/` / crate `resources/` under cwd.
40    DevTarget,
41    /// Bytes compiled into `kh-runtime`.
42    Embedded,
43}
44
45/// Result of installing xcrun into a bottle.
46#[derive(Debug, Clone, PartialEq, Eq)]
47pub struct XcrunInstall {
48    /// Host path of the source binary, or [`EMBEDDED_SOURCE_LABEL`].
49    pub source: PathBuf,
50    /// Absolute path of `{bottle}/usr/bin/xcrun`.
51    pub dest: PathBuf,
52    /// Where `source` was found.
53    pub origin: XcrunOrigin,
54}
55
56/// Discovers a guest `xcrun` **file** for bottle install (not the embed).
57#[must_use]
58pub fn discover(explicit: Option<&Path>) -> Option<(PathBuf, XcrunOrigin)> {
59    if let Some(p) = explicit {
60        if p.is_file() {
61            return Some((p.to_path_buf(), XcrunOrigin::Explicit));
62        }
63        return None;
64    }
65
66    if let Ok(raw) = std::env::var(ENV_XCRUN) {
67        let p = PathBuf::from(raw);
68        if p.is_file() {
69            return Some((p, XcrunOrigin::Explicit));
70        }
71    }
72
73    if let Some(p) = discover_adjacent() {
74        return Some((p, XcrunOrigin::Adjacent));
75    }
76
77    if let Some(p) = discover_dev_target() {
78        return Some((p, XcrunOrigin::DevTarget));
79    }
80
81    None
82}
83
84/// Copies `source` into `{root}/usr/bin/xcrun`.
85pub fn install(
86    root: &Path,
87    source: &Path,
88    origin: XcrunOrigin,
89) -> Result<XcrunInstall, BottleError> {
90    if !source.is_file() {
91        return Err(BottleError::Io(std::io::Error::new(
92            std::io::ErrorKind::NotFound,
93            format!("xcrun source not found: {}", source.display()),
94        )));
95    }
96    let bytes = fs::read(source)?;
97    let mut result = install_bytes(root, &bytes, origin)?;
98    result.source = source.to_path_buf();
99    Ok(result)
100}
101
102/// Writes raw Mach-O bytes into `{root}/usr/bin/xcrun`.
103pub fn install_bytes(
104    root: &Path,
105    source_bytes: &[u8],
106    origin: XcrunOrigin,
107) -> Result<XcrunInstall, BottleError> {
108    if source_bytes.is_empty() {
109        return Err(BottleError::Io(std::io::Error::new(
110            std::io::ErrorKind::InvalidData,
111            "xcrun source is empty",
112        )));
113    }
114    if !looks_like_macho(source_bytes) {
115        return Err(BottleError::Io(std::io::Error::new(
116            std::io::ErrorKind::InvalidData,
117            "xcrun source is not a Mach-O binary (build with --target aarch64-apple-darwin)",
118        )));
119    }
120
121    let dest = root.join(GUEST_XCRUN_REL);
122    if let Some(parent) = dest.parent() {
123        fs::create_dir_all(parent)?;
124    }
125    fs::write(&dest, source_bytes)?;
126
127    #[cfg(unix)]
128    {
129        use std::os::unix::fs::PermissionsExt;
130        drop(fs::set_permissions(
131            &dest,
132            fs::Permissions::from_mode(0o755),
133        ));
134    }
135
136    Ok(XcrunInstall {
137        source: PathBuf::from(EMBEDDED_SOURCE_LABEL),
138        dest,
139        origin,
140    })
141}
142
143fn discover_adjacent() -> Option<PathBuf> {
144    let exe = std::env::current_exe().ok()?;
145    let dir = exe.parent()?;
146    let candidates = [
147        dir.join("xcrun"),
148        dir.join("lib/kakehashi/xcrun"),
149        dir.join("../lib/kakehashi/xcrun"),
150        dir.join("share/kakehashi/xcrun"),
151        dir.join("../share/kakehashi/xcrun"),
152    ];
153    first_file(&candidates)
154}
155
156fn discover_dev_target() -> Option<PathBuf> {
157    let cwd = std::env::current_dir().ok()?;
158    let mut dir = Some(cwd.as_path());
159    while let Some(base) = dir {
160        if let Some(p) = discover_under_workspace(base) {
161            return Some(p);
162        }
163        dir = base.parent();
164    }
165    None
166}
167
168fn discover_under_workspace(base: &Path) -> Option<PathBuf> {
169    let candidates = [
170        base.join("target/aarch64-apple-darwin/release/xcrun"),
171        base.join("target/aarch64-apple-darwin/debug/xcrun"),
172        base.join("target/release/xcrun"),
173        base.join("target/debug/xcrun"),
174        base.join("crates/kh-runtime/resources/xcrun"),
175        base.join("resources/xcrun"),
176    ];
177    first_file(&candidates)
178}
179
180fn first_file(paths: &[PathBuf]) -> Option<PathBuf> {
181    paths.iter().find(|p| p.is_file()).cloned()
182}
183
184/// Thin / fat Mach-O magics (LE and BE). Rejects ELF host builds on Linux CI.
185fn looks_like_macho(bytes: &[u8]) -> bool {
186    let Some(header) = bytes.get(..4) else {
187        return false;
188    };
189    // MH_MAGIC_64 LE / BE, FAT_MAGIC / FAT_MAGIC_64 / CIGAM variants
190    matches!(
191        header,
192        [0xcf, 0xfa, 0xed, 0xfe]
193            | [0xfe, 0xed, 0xfa, 0xcf]
194            | [0xca, 0xfe, 0xba, 0xbe | 0xbf]
195            | [0xbe | 0xbf, 0xba, 0xfe, 0xca]
196    )
197}
198
199#[cfg(test)]
200#[allow(clippy::expect_used, clippy::panic)]
201mod tests {
202    use super::*;
203    use std::time::{SystemTime, UNIX_EPOCH};
204
205    fn tmp_root(label: &str) -> PathBuf {
206        let n = SystemTime::now()
207            .duration_since(UNIX_EPOCH)
208            .expect("time")
209            .as_nanos();
210        std::env::temp_dir().join(format!("kh-xcrun-{label}-{n}"))
211    }
212
213    #[test]
214    fn install_bytes_writes_executable_path() {
215        let root = tmp_root("install");
216        fs::create_dir_all(&root).expect("mkdir");
217        let payload = b"\xcf\xfa\xed\xfekh-xcrun-test-bytes";
218        let report = install_bytes(&root, payload, XcrunOrigin::Embedded).expect("install");
219        assert_eq!(report.dest, root.join(GUEST_XCRUN_REL));
220        assert_eq!(fs::read(&report.dest).expect("read"), payload);
221        drop(fs::remove_dir_all(&root));
222    }
223
224    #[test]
225    fn rejects_elf_payload() {
226        let root = tmp_root("elf");
227        fs::create_dir_all(&root).expect("mkdir");
228        let elf = b"\x7fELF\x02\x01\x01";
229        let err = install_bytes(&root, elf, XcrunOrigin::Embedded).expect_err("elf");
230        assert!(format!("{err}").contains("Mach-O"));
231        drop(fs::remove_dir_all(&root));
232    }
233}