kh-loader 0.1.14

Kakehashi Mach-O loader and process environment setup
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
//! Mach-O arm64 parsing via goblin (thin + fat).
//!
//! Fat containers are always reduced to the **arm64 thin slice** before header /
//! segment / nlist interpretation. [`MachOSummary::file_slice_offset`] records
//! where that slice sits in the on-disk container so map `fileoff` values can be
//! adjusted when reading from the original path.

use std::fs;
use std::ops::Range;
use std::path::Path;

use goblin::mach::constants::cputype::{CPU_TYPE_ARM64, CPU_TYPE_X86_64, get_arch_name_from_types};
use goblin::mach::header::filetype_to_str;
use goblin::mach::load_command::{CommandVariant, cmd_to_str};
use goblin::mach::{Mach, MachO, SingleArch};
use scroll::Pread;

use crate::error::LoadError;
use crate::image::{
    DylibDep, DylibKind, LoadCommandInfo, MachOImage, MachOSummary, SectionInfo, SegmentInfo,
};

/// Location of the arm64 thin Mach-O inside a file buffer (thin or fat).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Arm64Slice {
    /// Byte offset of the thin header within the container.
    pub offset: u64,
    /// Thin image size in bytes.
    pub size: u64,
    /// True when the container was a fat binary.
    pub was_fat: bool,
}

impl Arm64Slice {
    /// Half-open range into the container buffer.
    pub fn range(self) -> Result<Range<usize>, LoadError> {
        let start = usize::try_from(self.offset)
            .map_err(|_| LoadError::NotMachO("fat slice offset out of range".into()))?;
        let size = usize::try_from(self.size)
            .map_err(|_| LoadError::NotMachO("fat slice size out of range".into()))?;
        let end = start
            .checked_add(size)
            .ok_or_else(|| LoadError::NotMachO("fat slice end overflow".into()))?;
        Ok(start..end)
    }
}

/// Locates the arm64 thin Mach-O inside `bytes` (identity for thin arm64).
pub fn locate_arm64_slice(bytes: &[u8]) -> Result<Arm64Slice, LoadError> {
    let mach = Mach::parse(bytes).map_err(|err| LoadError::NotMachO(err.to_string()))?;
    match mach {
        Mach::Binary(macho) => {
            if !is_arm64(&macho) {
                let cputype = macho.header.cputype();
                let cpusubtype = macho.header.cpusubtype();
                let name = get_arch_name_from_types(cputype, cpusubtype)
                    .unwrap_or("unknown")
                    .to_owned();
                let hint = if cputype == CPU_TYPE_X86_64 {
                    format!("{name} (need arm64; no x86 translation in kakehashi)")
                } else {
                    name
                };
                return Err(LoadError::UnsupportedArch(hint));
            }
            Ok(Arm64Slice {
                offset: 0,
                size: u64::try_from(bytes.len()).unwrap_or(u64::MAX),
                was_fat: false,
            })
        }
        Mach::Fat(multi) => {
            if let Ok(Some(arch)) = multi.find_cputype(CPU_TYPE_ARM64) {
                return Ok(Arm64Slice {
                    offset: u64::from(arch.offset),
                    size: u64::from(arch.size),
                    was_fat: true,
                });
            }
            for entry in &multi {
                let entry = entry.map_err(|err| LoadError::NotMachO(err.to_string()))?;
                if let SingleArch::MachO(macho) = entry
                    && is_arm64(&macho)
                {
                    // MultiArch iteration does not expose offset; re-scan arches.
                    if let Ok(Some(arch)) = multi.find_cputype(macho.header.cputype()) {
                        return Ok(Arm64Slice {
                            offset: u64::from(arch.offset),
                            size: u64::from(arch.size),
                            was_fat: true,
                        });
                    }
                }
            }
            Err(LoadError::UnsupportedArch(
                "fat binary has no arm64 slice".to_owned(),
            ))
        }
    }
}

/// Returns a view of the arm64 thin Mach-O inside `bytes`.
pub fn thin_arm64_bytes(bytes: &[u8]) -> Result<&[u8], LoadError> {
    let slice = locate_arm64_slice(bytes)?;
    let range = slice.range()?;
    bytes
        .get(range)
        .ok_or_else(|| LoadError::NotMachO("fat arm64 slice out of file bounds".into()))
}

/// Reads a path and returns only the arm64 thin Mach-O bytes.
pub fn read_thin_arm64(path: &Path) -> Result<Vec<u8>, LoadError> {
    let bytes = fs::read(path)?;
    Ok(thin_arm64_bytes(&bytes)?.to_vec())
}

/// Reads and parses a Mach-O file, selecting the arm64 slice from fat images.
pub fn parse_path(path: &Path) -> Result<MachOImage, LoadError> {
    let (image, _) = parse_path_with_bytes(path)?;
    Ok(image)
}

/// Like [`parse_path`], but returns the **full on-disk container** as a
/// [`crate::FileImage`] (prefer `mmap`, demand-paged).
///
/// Callers reuse that buffer for segment fill ([`GuestMemory::map_image_bytes`])
/// and bind (via [`thin_arm64_bytes`]) so large guests avoid a second disk pass
/// and avoid forcing the entire multi‑hundred‑MiB file into RSS up front.
///
/// **Fat containers:** parse uses the full container so
/// [`MachOSummary::file_slice_offset`] stays correct for map `fileoff`.
pub fn parse_path_with_bytes(
    path: &Path,
) -> Result<(MachOImage, crate::FileImage), LoadError> {
    let file = crate::FileImage::open(path)?;
    let image = parse_bytes(file.as_slice(), &path.display().to_string())?;
    Ok((image, file))
}

/// Parses Mach-O bytes. `path_label` is stored in the summary for display.
///
/// Fat images are reduced to the arm64 thin slice; [`MachOSummary::file_slice_offset`]
/// is the container offset of that slice (0 for thin files).
pub fn parse_bytes(bytes: &[u8], path_label: &str) -> Result<MachOImage, LoadError> {
    let slice = locate_arm64_slice(bytes)?;
    let thin = thin_arm64_bytes(bytes)?;
    let mach = Mach::parse(thin).map_err(|err| LoadError::NotMachO(err.to_string()))?;
    match mach {
        Mach::Binary(macho) => {
            image_from_macho(thin, &macho, path_label, slice.was_fat, slice.offset)
        }
        Mach::Fat(_) => Err(LoadError::NotMachO(
            "nested fat image inside arm64 slice".into(),
        )),
    }
}

fn is_arm64(macho: &MachO<'_>) -> bool {
    macho.header.cputype() == CPU_TYPE_ARM64
}

fn image_from_macho(
    bytes: &[u8],
    macho: &MachO<'_>,
    path_label: &str,
    fat: bool,
    file_slice_offset: u64,
) -> Result<MachOImage, LoadError> {
    if !macho.is_64 {
        return Err(LoadError::UnsupportedArch(
            "32-bit Mach-O is not supported".to_owned(),
        ));
    }

    let cputype = macho.header.cputype();
    let cpusubtype = macho.header.cpusubtype();
    if cputype != CPU_TYPE_ARM64 {
        let name = get_arch_name_from_types(cputype, cpusubtype)
            .unwrap_or("unknown")
            .to_owned();
        let hint = if cputype == CPU_TYPE_X86_64 {
            format!("{name} (need arm64; no x86 translation in kakehashi)")
        } else {
            name
        };
        return Err(LoadError::UnsupportedArch(hint));
    }

    let cpu = get_arch_name_from_types(cputype, cpusubtype)
        .unwrap_or("arm64")
        .to_owned();

    let mut uuid = None;
    let mut minos = None;
    let mut platform = None;
    let mut dylibs = Vec::new();
    let mut load_commands = Vec::with_capacity(macho.load_commands.len());

    for (index, lc) in macho.load_commands.iter().enumerate() {
        let cmdsize = u32::try_from(lc.command.cmdsize()).unwrap_or(u32::MAX);
        let name = cmd_to_str(lc.command.cmd()).to_owned();
        let detail = command_detail(bytes, lc.offset, &lc.command);

        match &lc.command {
            CommandVariant::Uuid(u) => {
                uuid = Some(format_uuid(&u.uuid));
            }
            CommandVariant::BuildVersion(bv) => {
                minos = Some(format_packed_version(bv.minos));
                platform = Some(platform_name(bv.platform).to_owned());
            }
            CommandVariant::VersionMinMacosx(v) => {
                minos = Some(format_packed_version(v.version));
                platform = Some("macos".to_owned());
            }
            CommandVariant::VersionMinIphoneos(v) => {
                minos = Some(format_packed_version(v.version));
                platform = Some("ios".to_owned());
            }
            CommandVariant::LoadDylib(c) => {
                if let Some(path) = read_lc_string(bytes, lc.offset, c.dylib.name) {
                    dylibs.push(DylibDep {
                        kind: DylibKind::Load,
                        name: path,
                    });
                }
            }
            CommandVariant::LoadWeakDylib(c) => {
                if let Some(path) = read_lc_string(bytes, lc.offset, c.dylib.name) {
                    dylibs.push(DylibDep {
                        kind: DylibKind::Weak,
                        name: path,
                    });
                }
            }
            CommandVariant::ReexportDylib(c) => {
                if let Some(path) = read_lc_string(bytes, lc.offset, c.dylib.name) {
                    dylibs.push(DylibDep {
                        kind: DylibKind::Reexport,
                        name: path,
                    });
                }
            }
            CommandVariant::LazyLoadDylib(c) => {
                if let Some(path) = read_lc_string(bytes, lc.offset, c.dylib.name) {
                    dylibs.push(DylibDep {
                        kind: DylibKind::Lazy,
                        name: path,
                    });
                }
            }
            CommandVariant::LoadUpwardDylib(c) => {
                if let Some(path) = read_lc_string(bytes, lc.offset, c.dylib.name) {
                    dylibs.push(DylibDep {
                        kind: DylibKind::Upward,
                        name: path,
                    });
                }
            }
            CommandVariant::IdDylib(c) => {
                if let Some(path) = read_lc_string(bytes, lc.offset, c.dylib.name) {
                    dylibs.push(DylibDep {
                        kind: DylibKind::Id,
                        name: path,
                    });
                }
            }
            _ => {}
        }

        load_commands.push(LoadCommandInfo {
            index: u32::try_from(index).unwrap_or(u32::MAX),
            name,
            cmdsize,
            detail,
        });
    }

    let mut segments = Vec::with_capacity(macho.segments.len());
    for seg in &macho.segments {
        let name = seg
            .name()
            .map_err(|err| LoadError::NotMachO(format!("segment name: {err}")))?
            .to_owned();
        let mut sections = Vec::new();
        let section_pairs = seg
            .sections()
            .map_err(|err| LoadError::NotMachO(format!("sections: {err}")))?;
        for (section, _data) in section_pairs {
            let sect_name = section
                .name()
                .map_err(|err| LoadError::NotMachO(format!("section name: {err}")))?
                .to_owned();
            let segname = section
                .segname()
                .map_err(|err| LoadError::NotMachO(format!("section segname: {err}")))?
                .to_owned();
            sections.push(SectionInfo {
                name: sect_name,
                segname,
                addr: section.addr,
                size: section.size,
                offset: section.offset,
                align: section.align,
                flags: section.flags,
            });
        }
        segments.push(SegmentInfo {
            name,
            vmaddr: seg.vmaddr,
            vmsize: seg.vmsize,
            fileoff: seg.fileoff,
            filesize: seg.filesize,
            maxprot: seg.maxprot,
            initprot: seg.initprot,
            sections,
        });
    }

    let entry = if macho.entry == 0 {
        None
    } else {
        Some(macho.entry)
    };

    let summary = MachOSummary {
        path: path_label.to_owned(),
        fat,
        file_slice_offset,
        cpu,
        file_type: filetype_to_str(macho.header.filetype).to_owned(),
        file_type_raw: macho.header.filetype,
        flags: macho.header.flags,
        ncmds: u32::try_from(macho.header.ncmds).unwrap_or(u32::MAX),
        sizeofcmds: macho.header.sizeofcmds,
        entry,
        old_style_entry: macho.old_style_entry,
        uuid,
        minos,
        platform,
        is_64: macho.is_64,
        little_endian: macho.little_endian,
    };

    let rpaths = macho.rpaths.iter().map(|s| (*s).to_owned()).collect();

    Ok(MachOImage {
        summary,
        segments,
        dylibs,
        load_commands,
        rpaths,
    })
}

fn command_detail(bytes: &[u8], offset: usize, command: &CommandVariant) -> Option<String> {
    match command {
        CommandVariant::Segment64(seg) => {
            let segname = cstr16(&seg.segname);
            Some(format!(
                "{segname} vm={:#x}+{:#x} file={:#x}+{:#x} prot={}/{}",
                seg.vmaddr, seg.vmsize, seg.fileoff, seg.filesize, seg.initprot, seg.maxprot
            ))
        }
        CommandVariant::Segment32(seg) => {
            let segname = cstr16(&seg.segname);
            Some(format!("{segname} vm={:#x}+{:#x}", seg.vmaddr, seg.vmsize))
        }
        CommandVariant::Uuid(u) => Some(format_uuid(&u.uuid)),
        CommandVariant::Main(m) => Some(format!(
            "entryoff={:#x} stacksize={:#x}",
            m.entryoff, m.stacksize
        )),
        CommandVariant::BuildVersion(bv) => Some(format!(
            "platform={} minos={} sdk={}",
            platform_name(bv.platform),
            format_packed_version(bv.minos),
            format_packed_version(bv.sdk)
        )),
        CommandVariant::LoadDylib(c)
        | CommandVariant::LoadWeakDylib(c)
        | CommandVariant::ReexportDylib(c)
        | CommandVariant::LazyLoadDylib(c)
        | CommandVariant::LoadUpwardDylib(c)
        | CommandVariant::IdDylib(c) => read_lc_string(bytes, offset, c.dylib.name),
        CommandVariant::Rpath(r) => read_lc_string(bytes, offset, r.path),
        _ => None,
    }
}

fn read_lc_string(bytes: &[u8], cmd_offset: usize, name_off: u32) -> Option<String> {
    let abs = cmd_offset.checked_add(usize::try_from(name_off).ok()?)?;
    bytes.pread::<&str>(abs).ok().map(str::to_owned)
}

fn cstr16(field: &[u8; 16]) -> String {
    let end = field.iter().position(|&b| b == 0).unwrap_or(field.len());
    String::from_utf8_lossy(field.get(..end).unwrap_or(field.as_slice())).into_owned()
}

fn format_uuid(uuid: &[u8; 16]) -> String {
    format!(
        "{:02X}{:02X}{:02X}{:02X}-{:02X}{:02X}-{:02X}{:02X}-{:02X}{:02X}-{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}",
        uuid[0],
        uuid[1],
        uuid[2],
        uuid[3],
        uuid[4],
        uuid[5],
        uuid[6],
        uuid[7],
        uuid[8],
        uuid[9],
        uuid[10],
        uuid[11],
        uuid[12],
        uuid[13],
        uuid[14],
        uuid[15]
    )
}

/// X.Y.Z packed as nibbles xxxx.yy.zz (Apple version encoding).
fn format_packed_version(v: u32) -> String {
    let major = v >> 16;
    let minor = (v >> 8) & 0xff;
    let patch = v & 0xff;
    format!("{major}.{minor}.{patch}")
}

fn platform_name(platform: u32) -> &'static str {
    match platform {
        1 => "macos",
        2 => "ios",
        3 => "tvos",
        4 => "watchos",
        5 => "bridgeos",
        6 => "maccatalyst",
        7 => "iossimulator",
        8 => "tvossimulator",
        9 => "watchossimulator",
        10 => "driverkit",
        11 => "visionos",
        _ => "unknown",
    }
}

#[cfg(test)]
#[allow(clippy::expect_used, clippy::unwrap_used)]
mod tests {
    use super::*;

    #[test]
    fn reject_garbage() {
        let err = parse_bytes(b"not a macho", "bad").unwrap_err();
        assert!(matches!(err, LoadError::NotMachO(_)));
        assert_eq!(err.exit_code(), 2);
    }
}