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 (image, _) = parse_path_with_bytes(path)?;
120    Ok(image)
121}
122
123/// Like [`parse_path`], but returns the **full on-disk container** as a
124/// [`crate::FileImage`] (prefer `mmap`, demand-paged).
125///
126/// Callers reuse that buffer for segment fill ([`GuestMemory::map_image_bytes`])
127/// and bind (via [`thin_arm64_bytes`]) so large guests avoid a second disk pass
128/// and avoid forcing the entire multi‑hundred‑MiB file into RSS up front.
129///
130/// **Fat containers:** parse uses the full container so
131/// [`MachOSummary::file_slice_offset`] stays correct for map `fileoff`.
132pub fn parse_path_with_bytes(
133    path: &Path,
134) -> Result<(MachOImage, crate::FileImage), LoadError> {
135    let file = crate::FileImage::open(path)?;
136    let image = parse_bytes(file.as_slice(), &path.display().to_string())?;
137    Ok((image, file))
138}
139
140/// Parses Mach-O bytes. `path_label` is stored in the summary for display.
141///
142/// Fat images are reduced to the arm64 thin slice; [`MachOSummary::file_slice_offset`]
143/// is the container offset of that slice (0 for thin files).
144pub fn parse_bytes(bytes: &[u8], path_label: &str) -> Result<MachOImage, LoadError> {
145    let slice = locate_arm64_slice(bytes)?;
146    let thin = thin_arm64_bytes(bytes)?;
147    let mach = Mach::parse(thin).map_err(|err| LoadError::NotMachO(err.to_string()))?;
148    match mach {
149        Mach::Binary(macho) => {
150            image_from_macho(thin, &macho, path_label, slice.was_fat, slice.offset)
151        }
152        Mach::Fat(_) => Err(LoadError::NotMachO(
153            "nested fat image inside arm64 slice".into(),
154        )),
155    }
156}
157
158fn is_arm64(macho: &MachO<'_>) -> bool {
159    macho.header.cputype() == CPU_TYPE_ARM64
160}
161
162fn image_from_macho(
163    bytes: &[u8],
164    macho: &MachO<'_>,
165    path_label: &str,
166    fat: bool,
167    file_slice_offset: u64,
168) -> Result<MachOImage, LoadError> {
169    if !macho.is_64 {
170        return Err(LoadError::UnsupportedArch(
171            "32-bit Mach-O is not supported".to_owned(),
172        ));
173    }
174
175    let cputype = macho.header.cputype();
176    let cpusubtype = macho.header.cpusubtype();
177    if cputype != CPU_TYPE_ARM64 {
178        let name = get_arch_name_from_types(cputype, cpusubtype)
179            .unwrap_or("unknown")
180            .to_owned();
181        let hint = if cputype == CPU_TYPE_X86_64 {
182            format!("{name} (need arm64; no x86 translation in kakehashi)")
183        } else {
184            name
185        };
186        return Err(LoadError::UnsupportedArch(hint));
187    }
188
189    let cpu = get_arch_name_from_types(cputype, cpusubtype)
190        .unwrap_or("arm64")
191        .to_owned();
192
193    let mut uuid = None;
194    let mut minos = None;
195    let mut platform = None;
196    let mut dylibs = Vec::new();
197    let mut load_commands = Vec::with_capacity(macho.load_commands.len());
198
199    for (index, lc) in macho.load_commands.iter().enumerate() {
200        let cmdsize = u32::try_from(lc.command.cmdsize()).unwrap_or(u32::MAX);
201        let name = cmd_to_str(lc.command.cmd()).to_owned();
202        let detail = command_detail(bytes, lc.offset, &lc.command);
203
204        match &lc.command {
205            CommandVariant::Uuid(u) => {
206                uuid = Some(format_uuid(&u.uuid));
207            }
208            CommandVariant::BuildVersion(bv) => {
209                minos = Some(format_packed_version(bv.minos));
210                platform = Some(platform_name(bv.platform).to_owned());
211            }
212            CommandVariant::VersionMinMacosx(v) => {
213                minos = Some(format_packed_version(v.version));
214                platform = Some("macos".to_owned());
215            }
216            CommandVariant::VersionMinIphoneos(v) => {
217                minos = Some(format_packed_version(v.version));
218                platform = Some("ios".to_owned());
219            }
220            CommandVariant::LoadDylib(c) => {
221                if let Some(path) = read_lc_string(bytes, lc.offset, c.dylib.name) {
222                    dylibs.push(DylibDep {
223                        kind: DylibKind::Load,
224                        name: path,
225                    });
226                }
227            }
228            CommandVariant::LoadWeakDylib(c) => {
229                if let Some(path) = read_lc_string(bytes, lc.offset, c.dylib.name) {
230                    dylibs.push(DylibDep {
231                        kind: DylibKind::Weak,
232                        name: path,
233                    });
234                }
235            }
236            CommandVariant::ReexportDylib(c) => {
237                if let Some(path) = read_lc_string(bytes, lc.offset, c.dylib.name) {
238                    dylibs.push(DylibDep {
239                        kind: DylibKind::Reexport,
240                        name: path,
241                    });
242                }
243            }
244            CommandVariant::LazyLoadDylib(c) => {
245                if let Some(path) = read_lc_string(bytes, lc.offset, c.dylib.name) {
246                    dylibs.push(DylibDep {
247                        kind: DylibKind::Lazy,
248                        name: path,
249                    });
250                }
251            }
252            CommandVariant::LoadUpwardDylib(c) => {
253                if let Some(path) = read_lc_string(bytes, lc.offset, c.dylib.name) {
254                    dylibs.push(DylibDep {
255                        kind: DylibKind::Upward,
256                        name: path,
257                    });
258                }
259            }
260            CommandVariant::IdDylib(c) => {
261                if let Some(path) = read_lc_string(bytes, lc.offset, c.dylib.name) {
262                    dylibs.push(DylibDep {
263                        kind: DylibKind::Id,
264                        name: path,
265                    });
266                }
267            }
268            _ => {}
269        }
270
271        load_commands.push(LoadCommandInfo {
272            index: u32::try_from(index).unwrap_or(u32::MAX),
273            name,
274            cmdsize,
275            detail,
276        });
277    }
278
279    let mut segments = Vec::with_capacity(macho.segments.len());
280    for seg in &macho.segments {
281        let name = seg
282            .name()
283            .map_err(|err| LoadError::NotMachO(format!("segment name: {err}")))?
284            .to_owned();
285        let mut sections = Vec::new();
286        let section_pairs = seg
287            .sections()
288            .map_err(|err| LoadError::NotMachO(format!("sections: {err}")))?;
289        for (section, _data) in section_pairs {
290            let sect_name = section
291                .name()
292                .map_err(|err| LoadError::NotMachO(format!("section name: {err}")))?
293                .to_owned();
294            let segname = section
295                .segname()
296                .map_err(|err| LoadError::NotMachO(format!("section segname: {err}")))?
297                .to_owned();
298            sections.push(SectionInfo {
299                name: sect_name,
300                segname,
301                addr: section.addr,
302                size: section.size,
303                offset: section.offset,
304                align: section.align,
305                flags: section.flags,
306            });
307        }
308        segments.push(SegmentInfo {
309            name,
310            vmaddr: seg.vmaddr,
311            vmsize: seg.vmsize,
312            fileoff: seg.fileoff,
313            filesize: seg.filesize,
314            maxprot: seg.maxprot,
315            initprot: seg.initprot,
316            sections,
317        });
318    }
319
320    let entry = if macho.entry == 0 {
321        None
322    } else {
323        Some(macho.entry)
324    };
325
326    let summary = MachOSummary {
327        path: path_label.to_owned(),
328        fat,
329        file_slice_offset,
330        cpu,
331        file_type: filetype_to_str(macho.header.filetype).to_owned(),
332        file_type_raw: macho.header.filetype,
333        flags: macho.header.flags,
334        ncmds: u32::try_from(macho.header.ncmds).unwrap_or(u32::MAX),
335        sizeofcmds: macho.header.sizeofcmds,
336        entry,
337        old_style_entry: macho.old_style_entry,
338        uuid,
339        minos,
340        platform,
341        is_64: macho.is_64,
342        little_endian: macho.little_endian,
343    };
344
345    let rpaths = macho.rpaths.iter().map(|s| (*s).to_owned()).collect();
346
347    Ok(MachOImage {
348        summary,
349        segments,
350        dylibs,
351        load_commands,
352        rpaths,
353    })
354}
355
356fn command_detail(bytes: &[u8], offset: usize, command: &CommandVariant) -> Option<String> {
357    match command {
358        CommandVariant::Segment64(seg) => {
359            let segname = cstr16(&seg.segname);
360            Some(format!(
361                "{segname} vm={:#x}+{:#x} file={:#x}+{:#x} prot={}/{}",
362                seg.vmaddr, seg.vmsize, seg.fileoff, seg.filesize, seg.initprot, seg.maxprot
363            ))
364        }
365        CommandVariant::Segment32(seg) => {
366            let segname = cstr16(&seg.segname);
367            Some(format!("{segname} vm={:#x}+{:#x}", seg.vmaddr, seg.vmsize))
368        }
369        CommandVariant::Uuid(u) => Some(format_uuid(&u.uuid)),
370        CommandVariant::Main(m) => Some(format!(
371            "entryoff={:#x} stacksize={:#x}",
372            m.entryoff, m.stacksize
373        )),
374        CommandVariant::BuildVersion(bv) => Some(format!(
375            "platform={} minos={} sdk={}",
376            platform_name(bv.platform),
377            format_packed_version(bv.minos),
378            format_packed_version(bv.sdk)
379        )),
380        CommandVariant::LoadDylib(c)
381        | CommandVariant::LoadWeakDylib(c)
382        | CommandVariant::ReexportDylib(c)
383        | CommandVariant::LazyLoadDylib(c)
384        | CommandVariant::LoadUpwardDylib(c)
385        | CommandVariant::IdDylib(c) => read_lc_string(bytes, offset, c.dylib.name),
386        CommandVariant::Rpath(r) => read_lc_string(bytes, offset, r.path),
387        _ => None,
388    }
389}
390
391fn read_lc_string(bytes: &[u8], cmd_offset: usize, name_off: u32) -> Option<String> {
392    let abs = cmd_offset.checked_add(usize::try_from(name_off).ok()?)?;
393    bytes.pread::<&str>(abs).ok().map(str::to_owned)
394}
395
396fn cstr16(field: &[u8; 16]) -> String {
397    let end = field.iter().position(|&b| b == 0).unwrap_or(field.len());
398    String::from_utf8_lossy(field.get(..end).unwrap_or(field.as_slice())).into_owned()
399}
400
401fn format_uuid(uuid: &[u8; 16]) -> String {
402    format!(
403        "{:02X}{:02X}{:02X}{:02X}-{:02X}{:02X}-{:02X}{:02X}-{:02X}{:02X}-{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}",
404        uuid[0],
405        uuid[1],
406        uuid[2],
407        uuid[3],
408        uuid[4],
409        uuid[5],
410        uuid[6],
411        uuid[7],
412        uuid[8],
413        uuid[9],
414        uuid[10],
415        uuid[11],
416        uuid[12],
417        uuid[13],
418        uuid[14],
419        uuid[15]
420    )
421}
422
423/// X.Y.Z packed as nibbles xxxx.yy.zz (Apple version encoding).
424fn format_packed_version(v: u32) -> String {
425    let major = v >> 16;
426    let minor = (v >> 8) & 0xff;
427    let patch = v & 0xff;
428    format!("{major}.{minor}.{patch}")
429}
430
431fn platform_name(platform: u32) -> &'static str {
432    match platform {
433        1 => "macos",
434        2 => "ios",
435        3 => "tvos",
436        4 => "watchos",
437        5 => "bridgeos",
438        6 => "maccatalyst",
439        7 => "iossimulator",
440        8 => "tvossimulator",
441        9 => "watchossimulator",
442        10 => "driverkit",
443        11 => "visionos",
444        _ => "unknown",
445    }
446}
447
448#[cfg(test)]
449#[allow(clippy::expect_used, clippy::unwrap_used)]
450mod tests {
451    use super::*;
452
453    #[test]
454    fn reject_garbage() {
455        let err = parse_bytes(b"not a macho", "bad").unwrap_err();
456        assert!(matches!(err, LoadError::NotMachO(_)));
457        assert_eq!(err.exit_code(), 2);
458    }
459}