Skip to main content

kh_loader/
parse.rs

1//! Mach-O arm64 parsing via goblin (thin + fat).
2//!
3//! Fat containers are always reduced to the **arm64 thin slice** before header /
4//! segment / nlist interpretation. [`MachOSummary::file_slice_offset`] records
5//! where that slice sits in the on-disk container so map `fileoff` values can be
6//! adjusted when reading from the original path.
7
8use std::fs;
9use std::ops::Range;
10use std::path::Path;
11
12use goblin::mach::constants::cputype::{CPU_TYPE_ARM64, CPU_TYPE_X86_64, get_arch_name_from_types};
13use goblin::mach::header::filetype_to_str;
14use goblin::mach::load_command::{CommandVariant, cmd_to_str};
15use goblin::mach::{Mach, MachO, SingleArch};
16use scroll::Pread;
17
18use crate::error::LoadError;
19use crate::image::{
20    DylibDep, DylibKind, LoadCommandInfo, MachOImage, MachOSummary, SectionInfo, SegmentInfo,
21};
22
23/// Location of the arm64 thin Mach-O inside a file buffer (thin or fat).
24#[derive(Debug, Clone, Copy, PartialEq, Eq)]
25pub struct Arm64Slice {
26    /// Byte offset of the thin header within the container.
27    pub offset: u64,
28    /// Thin image size in bytes.
29    pub size: u64,
30    /// True when the container was a fat binary.
31    pub was_fat: bool,
32}
33
34impl Arm64Slice {
35    /// Half-open range into the container buffer.
36    pub fn range(self) -> Result<Range<usize>, LoadError> {
37        let start = usize::try_from(self.offset)
38            .map_err(|_| LoadError::NotMachO("fat slice offset out of range".into()))?;
39        let size = usize::try_from(self.size)
40            .map_err(|_| LoadError::NotMachO("fat slice size out of range".into()))?;
41        let end = start
42            .checked_add(size)
43            .ok_or_else(|| LoadError::NotMachO("fat slice end overflow".into()))?;
44        Ok(start..end)
45    }
46}
47
48/// Locates the arm64 thin Mach-O inside `bytes` (identity for thin arm64).
49pub fn locate_arm64_slice(bytes: &[u8]) -> Result<Arm64Slice, LoadError> {
50    let mach = Mach::parse(bytes).map_err(|err| LoadError::NotMachO(err.to_string()))?;
51    match mach {
52        Mach::Binary(macho) => {
53            if !is_arm64(&macho) {
54                let cputype = macho.header.cputype();
55                let cpusubtype = macho.header.cpusubtype();
56                let name = get_arch_name_from_types(cputype, cpusubtype)
57                    .unwrap_or("unknown")
58                    .to_owned();
59                let hint = if cputype == CPU_TYPE_X86_64 {
60                    format!("{name} (need arm64; no x86 translation in kakehashi)")
61                } else {
62                    name
63                };
64                return Err(LoadError::UnsupportedArch(hint));
65            }
66            Ok(Arm64Slice {
67                offset: 0,
68                size: u64::try_from(bytes.len()).unwrap_or(u64::MAX),
69                was_fat: false,
70            })
71        }
72        Mach::Fat(multi) => {
73            if let Ok(Some(arch)) = multi.find_cputype(CPU_TYPE_ARM64) {
74                return Ok(Arm64Slice {
75                    offset: u64::from(arch.offset),
76                    size: u64::from(arch.size),
77                    was_fat: true,
78                });
79            }
80            for entry in &multi {
81                let entry = entry.map_err(|err| LoadError::NotMachO(err.to_string()))?;
82                if let SingleArch::MachO(macho) = entry
83                    && is_arm64(&macho)
84                {
85                    // MultiArch iteration does not expose offset; re-scan arches.
86                    if let Ok(Some(arch)) = multi.find_cputype(macho.header.cputype()) {
87                        return Ok(Arm64Slice {
88                            offset: u64::from(arch.offset),
89                            size: u64::from(arch.size),
90                            was_fat: true,
91                        });
92                    }
93                }
94            }
95            Err(LoadError::UnsupportedArch(
96                "fat binary has no arm64 slice".to_owned(),
97            ))
98        }
99    }
100}
101
102/// Returns a view of the arm64 thin Mach-O inside `bytes`.
103pub fn thin_arm64_bytes(bytes: &[u8]) -> Result<&[u8], LoadError> {
104    let slice = locate_arm64_slice(bytes)?;
105    let range = slice.range()?;
106    bytes
107        .get(range)
108        .ok_or_else(|| LoadError::NotMachO("fat arm64 slice out of file bounds".into()))
109}
110
111/// Reads a path and returns only the arm64 thin Mach-O bytes.
112pub fn read_thin_arm64(path: &Path) -> Result<Vec<u8>, LoadError> {
113    let bytes = fs::read(path)?;
114    Ok(thin_arm64_bytes(&bytes)?.to_vec())
115}
116
117/// Reads and parses a Mach-O file, selecting the arm64 slice from fat images.
118pub fn parse_path(path: &Path) -> Result<MachOImage, LoadError> {
119    let bytes = fs::read(path)?;
120    parse_bytes(&bytes, &path.display().to_string())
121}
122
123/// Parses Mach-O bytes. `path_label` is stored in the summary for display.
124///
125/// Fat images are reduced to the arm64 thin slice; [`MachOSummary::file_slice_offset`]
126/// is the container offset of that slice (0 for thin files).
127pub fn parse_bytes(bytes: &[u8], path_label: &str) -> Result<MachOImage, LoadError> {
128    let slice = locate_arm64_slice(bytes)?;
129    let thin = thin_arm64_bytes(bytes)?;
130    let mach = Mach::parse(thin).map_err(|err| LoadError::NotMachO(err.to_string()))?;
131    match mach {
132        Mach::Binary(macho) => {
133            image_from_macho(thin, &macho, path_label, slice.was_fat, slice.offset)
134        }
135        Mach::Fat(_) => Err(LoadError::NotMachO(
136            "nested fat image inside arm64 slice".into(),
137        )),
138    }
139}
140
141fn is_arm64(macho: &MachO<'_>) -> bool {
142    macho.header.cputype() == CPU_TYPE_ARM64
143}
144
145fn image_from_macho(
146    bytes: &[u8],
147    macho: &MachO<'_>,
148    path_label: &str,
149    fat: bool,
150    file_slice_offset: u64,
151) -> Result<MachOImage, LoadError> {
152    if !macho.is_64 {
153        return Err(LoadError::UnsupportedArch(
154            "32-bit Mach-O is not supported".to_owned(),
155        ));
156    }
157
158    let cputype = macho.header.cputype();
159    let cpusubtype = macho.header.cpusubtype();
160    if cputype != CPU_TYPE_ARM64 {
161        let name = get_arch_name_from_types(cputype, cpusubtype)
162            .unwrap_or("unknown")
163            .to_owned();
164        let hint = if cputype == CPU_TYPE_X86_64 {
165            format!("{name} (need arm64; no x86 translation in kakehashi)")
166        } else {
167            name
168        };
169        return Err(LoadError::UnsupportedArch(hint));
170    }
171
172    let cpu = get_arch_name_from_types(cputype, cpusubtype)
173        .unwrap_or("arm64")
174        .to_owned();
175
176    let mut uuid = None;
177    let mut minos = None;
178    let mut platform = None;
179    let mut dylibs = Vec::new();
180    let mut load_commands = Vec::with_capacity(macho.load_commands.len());
181
182    for (index, lc) in macho.load_commands.iter().enumerate() {
183        let cmdsize = u32::try_from(lc.command.cmdsize()).unwrap_or(u32::MAX);
184        let name = cmd_to_str(lc.command.cmd()).to_owned();
185        let detail = command_detail(bytes, lc.offset, &lc.command);
186
187        match &lc.command {
188            CommandVariant::Uuid(u) => {
189                uuid = Some(format_uuid(&u.uuid));
190            }
191            CommandVariant::BuildVersion(bv) => {
192                minos = Some(format_packed_version(bv.minos));
193                platform = Some(platform_name(bv.platform).to_owned());
194            }
195            CommandVariant::VersionMinMacosx(v) => {
196                minos = Some(format_packed_version(v.version));
197                platform = Some("macos".to_owned());
198            }
199            CommandVariant::VersionMinIphoneos(v) => {
200                minos = Some(format_packed_version(v.version));
201                platform = Some("ios".to_owned());
202            }
203            CommandVariant::LoadDylib(c) => {
204                if let Some(path) = read_lc_string(bytes, lc.offset, c.dylib.name) {
205                    dylibs.push(DylibDep {
206                        kind: DylibKind::Load,
207                        name: path,
208                    });
209                }
210            }
211            CommandVariant::LoadWeakDylib(c) => {
212                if let Some(path) = read_lc_string(bytes, lc.offset, c.dylib.name) {
213                    dylibs.push(DylibDep {
214                        kind: DylibKind::Weak,
215                        name: path,
216                    });
217                }
218            }
219            CommandVariant::ReexportDylib(c) => {
220                if let Some(path) = read_lc_string(bytes, lc.offset, c.dylib.name) {
221                    dylibs.push(DylibDep {
222                        kind: DylibKind::Reexport,
223                        name: path,
224                    });
225                }
226            }
227            CommandVariant::LazyLoadDylib(c) => {
228                if let Some(path) = read_lc_string(bytes, lc.offset, c.dylib.name) {
229                    dylibs.push(DylibDep {
230                        kind: DylibKind::Lazy,
231                        name: path,
232                    });
233                }
234            }
235            CommandVariant::LoadUpwardDylib(c) => {
236                if let Some(path) = read_lc_string(bytes, lc.offset, c.dylib.name) {
237                    dylibs.push(DylibDep {
238                        kind: DylibKind::Upward,
239                        name: path,
240                    });
241                }
242            }
243            CommandVariant::IdDylib(c) => {
244                if let Some(path) = read_lc_string(bytes, lc.offset, c.dylib.name) {
245                    dylibs.push(DylibDep {
246                        kind: DylibKind::Id,
247                        name: path,
248                    });
249                }
250            }
251            _ => {}
252        }
253
254        load_commands.push(LoadCommandInfo {
255            index: u32::try_from(index).unwrap_or(u32::MAX),
256            name,
257            cmdsize,
258            detail,
259        });
260    }
261
262    let mut segments = Vec::with_capacity(macho.segments.len());
263    for seg in &macho.segments {
264        let name = seg
265            .name()
266            .map_err(|err| LoadError::NotMachO(format!("segment name: {err}")))?
267            .to_owned();
268        let mut sections = Vec::new();
269        let section_pairs = seg
270            .sections()
271            .map_err(|err| LoadError::NotMachO(format!("sections: {err}")))?;
272        for (section, _data) in section_pairs {
273            let sect_name = section
274                .name()
275                .map_err(|err| LoadError::NotMachO(format!("section name: {err}")))?
276                .to_owned();
277            let segname = section
278                .segname()
279                .map_err(|err| LoadError::NotMachO(format!("section segname: {err}")))?
280                .to_owned();
281            sections.push(SectionInfo {
282                name: sect_name,
283                segname,
284                addr: section.addr,
285                size: section.size,
286                offset: section.offset,
287                align: section.align,
288                flags: section.flags,
289            });
290        }
291        segments.push(SegmentInfo {
292            name,
293            vmaddr: seg.vmaddr,
294            vmsize: seg.vmsize,
295            fileoff: seg.fileoff,
296            filesize: seg.filesize,
297            maxprot: seg.maxprot,
298            initprot: seg.initprot,
299            sections,
300        });
301    }
302
303    let entry = if macho.entry == 0 {
304        None
305    } else {
306        Some(macho.entry)
307    };
308
309    let summary = MachOSummary {
310        path: path_label.to_owned(),
311        fat,
312        file_slice_offset,
313        cpu,
314        file_type: filetype_to_str(macho.header.filetype).to_owned(),
315        file_type_raw: macho.header.filetype,
316        flags: macho.header.flags,
317        ncmds: u32::try_from(macho.header.ncmds).unwrap_or(u32::MAX),
318        sizeofcmds: macho.header.sizeofcmds,
319        entry,
320        old_style_entry: macho.old_style_entry,
321        uuid,
322        minos,
323        platform,
324        is_64: macho.is_64,
325        little_endian: macho.little_endian,
326    };
327
328    let rpaths = macho.rpaths.iter().map(|s| (*s).to_owned()).collect();
329
330    Ok(MachOImage {
331        summary,
332        segments,
333        dylibs,
334        load_commands,
335        rpaths,
336    })
337}
338
339fn command_detail(bytes: &[u8], offset: usize, command: &CommandVariant) -> Option<String> {
340    match command {
341        CommandVariant::Segment64(seg) => {
342            let segname = cstr16(&seg.segname);
343            Some(format!(
344                "{segname} vm={:#x}+{:#x} file={:#x}+{:#x} prot={}/{}",
345                seg.vmaddr, seg.vmsize, seg.fileoff, seg.filesize, seg.initprot, seg.maxprot
346            ))
347        }
348        CommandVariant::Segment32(seg) => {
349            let segname = cstr16(&seg.segname);
350            Some(format!("{segname} vm={:#x}+{:#x}", seg.vmaddr, seg.vmsize))
351        }
352        CommandVariant::Uuid(u) => Some(format_uuid(&u.uuid)),
353        CommandVariant::Main(m) => Some(format!(
354            "entryoff={:#x} stacksize={:#x}",
355            m.entryoff, m.stacksize
356        )),
357        CommandVariant::BuildVersion(bv) => Some(format!(
358            "platform={} minos={} sdk={}",
359            platform_name(bv.platform),
360            format_packed_version(bv.minos),
361            format_packed_version(bv.sdk)
362        )),
363        CommandVariant::LoadDylib(c)
364        | CommandVariant::LoadWeakDylib(c)
365        | CommandVariant::ReexportDylib(c)
366        | CommandVariant::LazyLoadDylib(c)
367        | CommandVariant::LoadUpwardDylib(c)
368        | CommandVariant::IdDylib(c) => read_lc_string(bytes, offset, c.dylib.name),
369        CommandVariant::Rpath(r) => read_lc_string(bytes, offset, r.path),
370        _ => None,
371    }
372}
373
374fn read_lc_string(bytes: &[u8], cmd_offset: usize, name_off: u32) -> Option<String> {
375    let abs = cmd_offset.checked_add(usize::try_from(name_off).ok()?)?;
376    bytes.pread::<&str>(abs).ok().map(str::to_owned)
377}
378
379fn cstr16(field: &[u8; 16]) -> String {
380    let end = field.iter().position(|&b| b == 0).unwrap_or(field.len());
381    String::from_utf8_lossy(field.get(..end).unwrap_or(field.as_slice())).into_owned()
382}
383
384fn format_uuid(uuid: &[u8; 16]) -> String {
385    format!(
386        "{:02X}{:02X}{:02X}{:02X}-{:02X}{:02X}-{:02X}{:02X}-{:02X}{:02X}-{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}",
387        uuid[0],
388        uuid[1],
389        uuid[2],
390        uuid[3],
391        uuid[4],
392        uuid[5],
393        uuid[6],
394        uuid[7],
395        uuid[8],
396        uuid[9],
397        uuid[10],
398        uuid[11],
399        uuid[12],
400        uuid[13],
401        uuid[14],
402        uuid[15]
403    )
404}
405
406/// X.Y.Z packed as nibbles xxxx.yy.zz (Apple version encoding).
407fn format_packed_version(v: u32) -> String {
408    let major = v >> 16;
409    let minor = (v >> 8) & 0xff;
410    let patch = v & 0xff;
411    format!("{major}.{minor}.{patch}")
412}
413
414fn platform_name(platform: u32) -> &'static str {
415    match platform {
416        1 => "macos",
417        2 => "ios",
418        3 => "tvos",
419        4 => "watchos",
420        5 => "bridgeos",
421        6 => "maccatalyst",
422        7 => "iossimulator",
423        8 => "tvossimulator",
424        9 => "watchossimulator",
425        10 => "driverkit",
426        11 => "visionos",
427        _ => "unknown",
428    }
429}
430
431#[cfg(test)]
432#[allow(clippy::expect_used, clippy::unwrap_used, clippy::panic)]
433mod tests {
434    use super::*;
435    use crate::fixture::minimal_arm64_execute;
436    use kh_runtime::GuestPageSize;
437
438    #[test]
439    fn parse_minimal_arm64_fixture() {
440        let bytes = minimal_arm64_execute();
441        let image = parse_bytes(&bytes, "minimal").expect("parse");
442        assert_eq!(image.summary.cpu, "arm64");
443        assert_eq!(image.summary.file_type, "EXECUTE");
444        assert!(!image.summary.fat);
445        assert!(image.summary.is_64);
446        assert!(image.summary.little_endian);
447        assert_eq!(
448            image.summary.uuid.as_deref(),
449            Some("00112233-4455-6677-8899-AABBCCDDEEFF")
450        );
451        assert!(
452            image
453                .dylibs
454                .iter()
455                .any(|d| d.name == "/usr/lib/libSystem.B.dylib")
456        );
457        assert!(image.segments.iter().any(|s| s.name == "__TEXT"));
458        assert!(image.segments.iter().any(|s| s.name == "__PAGEZERO"));
459        assert!(image.summary.entry.is_some());
460    }
461
462    #[test]
463    fn reject_garbage() {
464        let err = parse_bytes(b"not a macho", "bad").unwrap_err();
465        assert!(matches!(err, LoadError::NotMachO(_)));
466        assert_eq!(err.exit_code(), 2);
467    }
468
469    #[test]
470    fn image_plan_guest_16k() {
471        let bytes = minimal_arm64_execute();
472        let image = parse_bytes(&bytes, "minimal").expect("parse");
473        let plan = image.plan(GuestPageSize::Darwin16K);
474        assert_eq!(plan.guest_page_size, 16_384);
475        assert!(!plan.mappings.is_empty());
476        assert!(plan.segment_count() >= 2);
477    }
478
479    #[test]
480    fn parse_fat_arm64_wrapper_sets_slice_offset() {
481        use crate::fixture::wrap_fat_arm64_only;
482
483        let thin = minimal_arm64_execute();
484        let fat = wrap_fat_arm64_only(&thin);
485        let slice = locate_arm64_slice(&fat).expect("locate");
486        assert!(slice.was_fat);
487        assert_eq!(slice.offset, 32);
488        assert_eq!(usize::try_from(slice.size).unwrap(), thin.len());
489
490        let image = parse_bytes(&fat, "fat-minimal").expect("parse fat");
491        assert!(image.summary.fat);
492        assert_eq!(image.summary.file_slice_offset, 32);
493        assert_eq!(image.summary.cpu, "arm64");
494        assert_eq!(image.summary.entry, parse_bytes(&thin, "thin").unwrap().summary.entry);
495
496        let plan = image.plan(GuestPageSize::Darwin16K);
497        let text = plan
498            .mappings
499            .iter()
500            .find(|m| m.name == "__TEXT")
501            .expect("TEXT");
502        // Thin TEXT fileoff is 0; fat plan must add container offset for map.
503        assert_eq!(text.fileoff, 32);
504    }
505
506    #[test]
507    fn thin_arm64_bytes_accepts_fat_and_thin() {
508        use crate::fixture::wrap_fat_arm64_only;
509
510        let thin = minimal_arm64_execute();
511        let fat = wrap_fat_arm64_only(&thin);
512        assert_eq!(thin_arm64_bytes(&thin).unwrap(), thin.as_slice());
513        assert_eq!(thin_arm64_bytes(&fat).unwrap(), thin.as_slice());
514    }
515}