1use std::fs;
17use std::path::{Path, PathBuf};
18
19use super::manage::BottleError;
20
21pub const GUEST_LIBSYSTEM_REL: &str = "usr/lib/libSystem.B.dylib";
23
24pub const GUEST_LIBSYSTEM_ID: &str = "/usr/lib/libSystem.B.dylib";
26
27pub const ENV_LIBSYSTEM: &str = "KAKEHASHI_LIBSYSTEM";
29
30const MH_MAGIC_64: u32 = 0xfeed_facf;
31const LC_ID_DYLIB: u32 = 0xd;
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub enum LibsystemOrigin {
36 Explicit,
38 Env,
40 Adjacent,
42 DevTarget,
44}
45
46#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct LibsystemInstall {
49 pub source: PathBuf,
51 pub dest: PathBuf,
53 pub origin: LibsystemOrigin,
55 pub id_rewritten: bool,
57}
58
59#[must_use]
67pub fn discover(explicit: Option<&Path>) -> Option<(PathBuf, LibsystemOrigin)> {
68 if let Some(p) = explicit {
69 if p.is_file() {
70 return Some((p.to_path_buf(), LibsystemOrigin::Explicit));
71 }
72 return None;
73 }
74
75 if let Ok(raw) = std::env::var(ENV_LIBSYSTEM) {
76 let p = PathBuf::from(raw);
77 if p.is_file() {
78 return Some((p, LibsystemOrigin::Env));
79 }
80 }
81
82 if let Some(p) = discover_adjacent() {
83 return Some((p, LibsystemOrigin::Adjacent));
84 }
85
86 if let Some(p) = discover_dev_target() {
87 return Some((p, LibsystemOrigin::DevTarget));
88 }
89
90 None
91}
92
93pub fn install(
96 root: &Path,
97 source: &Path,
98 origin: LibsystemOrigin,
99) -> Result<LibsystemInstall, BottleError> {
100 if !source.is_file() {
101 return Err(BottleError::Io(std::io::Error::new(
102 std::io::ErrorKind::NotFound,
103 format!("libSystem source not found: {}", source.display()),
104 )));
105 }
106
107 let dest = root.join(GUEST_LIBSYSTEM_REL);
108 if let Some(parent) = dest.parent() {
109 fs::create_dir_all(parent)?;
110 }
111
112 let mut bytes = fs::read(source)?;
113 let id_rewritten = ensure_libsystem_id(&mut bytes)?;
114 fs::write(&dest, &bytes)?;
115
116 #[cfg(unix)]
118 {
119 use std::os::unix::fs::PermissionsExt;
120 drop(fs::set_permissions(
121 &dest,
122 fs::Permissions::from_mode(0o755),
123 ));
124 }
125
126 Ok(LibsystemInstall {
127 source: source.to_path_buf(),
128 dest,
129 origin,
130 id_rewritten,
131 })
132}
133
134pub fn ensure_libsystem_id(bytes: &mut [u8]) -> Result<bool, BottleError> {
139 patch_lc_id_dylib(bytes, GUEST_LIBSYSTEM_ID)
140}
141
142fn discover_adjacent() -> Option<PathBuf> {
143 let exe = std::env::current_exe().ok()?;
144 let dir = exe.parent()?;
145 let candidates = [
146 dir.join("libSystem.B.dylib"),
147 dir.join("libkh_libsystem.dylib"),
148 dir.join("lib/kakehashi/libSystem.B.dylib"),
149 dir.join("lib/kakehashi/libkh_libsystem.dylib"),
150 dir.join("../lib/kakehashi/libSystem.B.dylib"),
151 dir.join("../lib/kakehashi/libkh_libsystem.dylib"),
152 dir.join("share/kakehashi/libSystem.B.dylib"),
153 dir.join("../share/kakehashi/libSystem.B.dylib"),
154 ];
155 first_file(&candidates)
156}
157
158fn discover_dev_target() -> Option<PathBuf> {
159 let cwd = std::env::current_dir().ok()?;
160 let mut dir = Some(cwd.as_path());
163 while let Some(base) = dir {
164 if let Some(p) = discover_under_workspace(base) {
165 return Some(p);
166 }
167 dir = base.parent();
168 }
169 None
170}
171
172fn discover_under_workspace(base: &Path) -> Option<PathBuf> {
174 let names = ["libSystem.B.dylib", "libkh_libsystem.dylib"];
175 let dirs = [
176 "dist/guest",
178 "target/release",
179 "target/debug",
180 "target/aarch64-apple-darwin/release",
181 "target/aarch64-apple-darwin/debug",
182 ];
183 let mut candidates = Vec::new();
184 for d in dirs {
185 for n in names {
186 candidates.push(base.join(d).join(n));
187 }
188 }
189 first_file(&candidates)
190}
191
192fn first_file(paths: &[PathBuf]) -> Option<PathBuf> {
193 paths.iter().find(|p| p.is_file()).cloned()
194}
195
196fn patch_lc_id_dylib(bytes: &mut [u8], new_id: &str) -> Result<bool, BottleError> {
197 if bytes.len() < 32 {
198 return Err(id_err("file too small to be Mach-O"));
199 }
200
201 let magic = read_u32_le(bytes, 0)?;
202 if magic == 0xcafe_babe || magic == 0xcafe_babf || magic == 0xbeba_feca || magic == 0xbfba_feca
203 {
204 return Err(id_err(
205 "fat Mach-O is not supported; ship a thin aarch64 libSystem.B.dylib",
206 ));
207 }
208 if magic != MH_MAGIC_64 {
209 return Err(id_err(format!(
210 "not a little-endian 64-bit Mach-O (magic {magic:#x})"
211 )));
212 }
213
214 let ncmds = usize_from_u32(read_u32_le(bytes, 16)?)?;
215 let sizeofcmds = usize_from_u32(read_u32_le(bytes, 20)?)?;
216 let cmds_start = 32usize;
217 let cmds_end = cmds_start
218 .checked_add(sizeofcmds)
219 .ok_or_else(|| id_err("sizeofcmds overflow"))?;
220 if cmds_end > bytes.len() {
221 return Err(id_err("load commands extend past file"));
222 }
223
224 let mut off = cmds_start;
225 for _ in 0..ncmds {
226 if off.checked_add(8).is_none_or(|e| e > cmds_end) {
227 return Err(id_err("truncated load command"));
228 }
229 let cmd = read_u32_le(bytes, off)?;
230 let cmdsize = usize_from_u32(read_u32_le(bytes, off.saturating_add(4))?)?;
231 if cmdsize < 8 {
232 return Err(id_err("invalid load command size"));
233 }
234 let cmd_end = off
235 .checked_add(cmdsize)
236 .ok_or_else(|| id_err("cmdsize overflow"))?;
237 if cmd_end > cmds_end {
238 return Err(id_err("load command extends past sizeofcmds"));
239 }
240
241 if cmd == LC_ID_DYLIB {
242 return rewrite_id_name(bytes, off, cmdsize, new_id);
243 }
244 off = cmd_end;
245 }
246 Err(id_err("LC_ID_DYLIB not found"))
247}
248
249fn rewrite_id_name(
250 bytes: &mut [u8],
251 cmd_off: usize,
252 cmdsize: usize,
253 new_id: &str,
254) -> Result<bool, BottleError> {
255 if cmdsize < 24 {
257 return Err(id_err("LC_ID_DYLIB too small"));
258 }
259 let name_off = usize_from_u32(read_u32_le(bytes, cmd_off.saturating_add(8))?)?;
260 if name_off >= cmdsize {
261 return Err(id_err("LC_ID_DYLIB name offset out of range"));
262 }
263 let name_start = cmd_off
264 .checked_add(name_off)
265 .ok_or_else(|| id_err("name offset overflow"))?;
266 let name_cap = cmdsize
267 .checked_sub(name_off)
268 .ok_or_else(|| id_err("name capacity underflow"))?;
269 let new_bytes = new_id.as_bytes();
270 let need = new_bytes
271 .len()
272 .checked_add(1)
273 .ok_or_else(|| id_err("new id length overflow"))?;
274 if need > name_cap {
275 return Err(id_err(format!(
276 "LC_ID_DYLIB name field too short for {new_id} (cap {name_cap})"
277 )));
278 }
279
280 let cmd_end = cmd_off
281 .checked_add(cmdsize)
282 .ok_or_else(|| id_err("cmd end overflow"))?;
283 let field = bytes
284 .get(name_start..cmd_end)
285 .ok_or_else(|| id_err("name field out of range"))?;
286 let old_len = field.iter().position(|&c| c == 0).unwrap_or(field.len());
287 let old = field
288 .get(..old_len)
289 .ok_or_else(|| id_err("old name slice"))?;
290 if old == new_bytes {
291 return Ok(false);
292 }
293
294 let dest = bytes
295 .get_mut(name_start..cmd_end)
296 .ok_or_else(|| id_err("name field mut out of range"))?;
297 if new_bytes.len() > dest.len() {
298 return Err(id_err("new id does not fit"));
299 }
300 let (head, tail) = dest.split_at_mut(new_bytes.len());
301 head.copy_from_slice(new_bytes);
302 for b in tail {
303 *b = 0;
304 }
305 Ok(true)
306}
307
308fn read_u32_le(bytes: &[u8], off: usize) -> Result<u32, BottleError> {
309 let end = off
310 .checked_add(4)
311 .ok_or_else(|| id_err("u32 offset overflow"))?;
312 let raw = bytes
313 .get(off..end)
314 .ok_or_else(|| id_err("out of range u32"))?;
315 let arr: [u8; 4] = raw.try_into().map_err(|_| id_err("u32 slice length"))?;
316 Ok(u32::from_le_bytes(arr))
317}
318
319fn usize_from_u32(v: u32) -> Result<usize, BottleError> {
320 usize::try_from(v).map_err(|_| id_err("u32 does not fit usize"))
321}
322
323fn id_err(msg: impl Into<String>) -> BottleError {
324 BottleError::Io(std::io::Error::new(
325 std::io::ErrorKind::InvalidData,
326 msg.into(),
327 ))
328}
329
330#[cfg(test)]
331#[allow(
332 clippy::expect_used,
333 clippy::panic,
334 clippy::unwrap_used,
335 clippy::indexing_slicing,
336 clippy::as_conversions,
337 clippy::cast_possible_truncation,
338 clippy::arithmetic_side_effects
339)]
340mod tests {
341 use super::*;
342 use std::sync::atomic::{AtomicU64, Ordering};
343
344 fn temp_dir(prefix: &str) -> PathBuf {
345 static N: AtomicU64 = AtomicU64::new(0);
346 let n = N.fetch_add(1, Ordering::Relaxed);
347 let dir =
348 std::env::temp_dir().join(format!("kh-libsys-{}-{}-{n}", prefix, std::process::id()));
349 drop(fs::remove_dir_all(&dir));
350 fs::create_dir_all(&dir).expect("mkdir");
351 dir
352 }
353
354 fn minimal_dylib(id: &str) -> Vec<u8> {
356 const CPU_TYPE_ARM64: u32 = 0x0100_000c;
357 const MH_DYLIB: u32 = 6;
358
359 let mut name = id.as_bytes().to_vec();
360 name.push(0);
361 while !name.len().is_multiple_of(8) {
362 name.push(0);
363 }
364 while name.len() < 40 {
365 name.push(0);
366 }
367 let cmdsize = 24 + name.len();
368 let sizeofcmds = u32::try_from(cmdsize).expect("cmdsize");
369 let cmdsize_u = sizeofcmds;
370
371 let mut buf = Vec::new();
372 buf.extend_from_slice(&MH_MAGIC_64.to_le_bytes());
373 buf.extend_from_slice(&CPU_TYPE_ARM64.to_le_bytes());
374 buf.extend_from_slice(&0u32.to_le_bytes());
375 buf.extend_from_slice(&MH_DYLIB.to_le_bytes());
376 buf.extend_from_slice(&1u32.to_le_bytes());
377 buf.extend_from_slice(&sizeofcmds.to_le_bytes());
378 buf.extend_from_slice(&0u32.to_le_bytes());
379 buf.extend_from_slice(&0u32.to_le_bytes());
380
381 buf.extend_from_slice(&LC_ID_DYLIB.to_le_bytes());
382 buf.extend_from_slice(&cmdsize_u.to_le_bytes());
383 buf.extend_from_slice(&24u32.to_le_bytes());
384 buf.extend_from_slice(&1u32.to_le_bytes());
385 buf.extend_from_slice(&0x0001_0000u32.to_le_bytes());
386 buf.extend_from_slice(&0x0001_0000u32.to_le_bytes());
387 buf.extend_from_slice(&name);
388 buf
389 }
390
391 fn read_id(bytes: &[u8]) -> String {
392 let ncmds = u32::from_le_bytes(bytes[16..20].try_into().unwrap()) as usize;
393 let mut off = 32usize;
394 for _ in 0..ncmds {
395 let cmd = u32::from_le_bytes(bytes[off..off + 4].try_into().unwrap());
396 let cmdsize = u32::from_le_bytes(bytes[off + 4..off + 8].try_into().unwrap()) as usize;
397 if cmd == LC_ID_DYLIB {
398 let name_off =
399 u32::from_le_bytes(bytes[off + 8..off + 12].try_into().unwrap()) as usize;
400 let start = off + name_off;
401 let end = bytes[start..]
402 .iter()
403 .position(|&c| c == 0)
404 .map(|n| start + n)
405 .unwrap();
406 return String::from_utf8(bytes[start..end].to_vec()).unwrap();
407 }
408 off += cmdsize;
409 }
410 panic!("no LC_ID_DYLIB");
411 }
412
413 #[test]
414 fn rewrite_rpath_id_to_guest() {
415 let mut bytes = minimal_dylib("@rpath/libkh_libsystem.dylib");
416 assert_eq!(read_id(&bytes), "@rpath/libkh_libsystem.dylib");
417 let changed = ensure_libsystem_id(&mut bytes).expect("patch");
418 assert!(changed);
419 assert_eq!(read_id(&bytes), GUEST_LIBSYSTEM_ID);
420 let changed_again = ensure_libsystem_id(&mut bytes).expect("idempotent");
421 assert!(!changed_again);
422 }
423
424 #[test]
425 fn install_copies_and_sets_id() {
426 let root = temp_dir("install");
427 super::super::layout::materialize(&root).expect("materialize");
428 let src_dir = temp_dir("src");
429 let src = src_dir.join("libkh_libsystem.dylib");
430 fs::write(&src, minimal_dylib("@rpath/libkh_libsystem.dylib")).expect("write src");
431
432 let inst = install(&root, &src, LibsystemOrigin::Explicit).expect("install");
433 assert!(inst.id_rewritten);
434 assert_eq!(inst.dest, root.join(GUEST_LIBSYSTEM_REL));
435 assert!(inst.dest.is_file());
436 let on_disk = fs::read(&inst.dest).expect("read dest");
437 assert_eq!(read_id(&on_disk), GUEST_LIBSYSTEM_ID);
438
439 drop(fs::remove_dir_all(&root));
440 drop(fs::remove_dir_all(&src_dir));
441 }
442
443 #[test]
444 fn discover_explicit_missing_is_none() {
445 assert!(discover(Some(Path::new("/no/such/libSystem.B.dylib"))).is_none());
446 }
447
448 #[test]
449 fn rejects_fat_magic() {
450 let mut bytes = vec![0u8; 64];
451 bytes[0..4].copy_from_slice(&0xcafe_babeu32.to_be_bytes());
452 let err = ensure_libsystem_id(&mut bytes).expect_err("fat");
453 let msg = err.to_string();
454 assert!(msg.contains("fat"), "{msg}");
455 }
456}