Skip to main content

kh_loader/
image.rs

1//! Owned Mach-O views and image planning types.
2
3use kh_runtime::GuestPageSize;
4
5/// High-level header summary used by `kh inspect`.
6#[derive(Debug, Clone, PartialEq, Eq)]
7#[allow(clippy::struct_excessive_bools)]
8pub struct MachOSummary {
9    /// Path that was opened (or synthetic label).
10    pub path: String,
11    /// True when the on-disk container was a fat binary.
12    pub fat: bool,
13    /// Byte offset of the arm64 thin Mach-O within the on-disk container.
14    ///
15    /// Zero for thin files. Segment `fileoff` values are relative to the thin
16    /// header; map requests add this offset when reading the container path.
17    pub file_slice_offset: u64,
18    /// Architecture name (e.g. `arm64`).
19    pub cpu: String,
20    /// File type string (e.g. `EXECUTE`).
21    pub file_type: String,
22    /// Raw filetype constant.
23    pub file_type_raw: u32,
24    /// Header flags.
25    pub flags: u32,
26    /// Number of load commands.
27    pub ncmds: u32,
28    /// Size of all load commands in bytes.
29    pub sizeofcmds: u32,
30    /// Entry virtual address if known (0 means unknown / not present).
31    pub entry: Option<u64>,
32    /// True when entry came from `LC_UNIXTHREAD` rather than `LC_MAIN`.
33    pub old_style_entry: bool,
34    /// UUID if present (`LC_UUID`).
35    pub uuid: Option<String>,
36    /// Minimum OS version from `LC_BUILD_VERSION` / `LC_VERSION_MIN_*` if any.
37    pub minos: Option<String>,
38    /// Platform from `LC_BUILD_VERSION` if any.
39    pub platform: Option<String>,
40    /// Whether this is a 64-bit Mach-O.
41    pub is_64: bool,
42    /// Little-endian image.
43    pub little_endian: bool,
44}
45
46/// One segment from the image.
47#[derive(Debug, Clone, PartialEq, Eq)]
48pub struct SegmentInfo {
49    /// Segment name (`__TEXT`, `__DATA`, …).
50    pub name: String,
51    /// Preferred virtual address.
52    pub vmaddr: u64,
53    /// Virtual size.
54    pub vmsize: u64,
55    /// File offset.
56    pub fileoff: u64,
57    /// Bytes mapped from file.
58    pub filesize: u64,
59    /// Maximum VM protection bits.
60    pub maxprot: u32,
61    /// Initial VM protection bits.
62    pub initprot: u32,
63    /// Sections contained in this segment.
64    pub sections: Vec<SectionInfo>,
65}
66
67/// One section within a segment.
68#[derive(Debug, Clone, PartialEq, Eq)]
69pub struct SectionInfo {
70    /// Section name.
71    pub name: String,
72    /// Containing segment name.
73    pub segname: String,
74    /// Virtual address.
75    pub addr: u64,
76    /// Size in bytes.
77    pub size: u64,
78    /// File offset.
79    pub offset: u32,
80    /// Alignment as power of two (`1 << align`).
81    pub align: u32,
82    /// Section flags.
83    pub flags: u32,
84}
85
86/// Kind of dylib dependency load command.
87#[derive(Debug, Clone, Copy, PartialEq, Eq)]
88pub enum DylibKind {
89    /// `LC_LOAD_DYLIB`
90    Load,
91    /// `LC_LOAD_WEAK_DYLIB`
92    Weak,
93    /// `LC_REEXPORT_DYLIB`
94    Reexport,
95    /// `LC_LAZY_LOAD_DYLIB`
96    Lazy,
97    /// `LC_LOAD_UPWARD_DYLIB`
98    Upward,
99    /// `LC_ID_DYLIB` (install name of this image)
100    Id,
101}
102
103impl DylibKind {
104    /// Stable short label for CLI output.
105    #[must_use]
106    pub const fn as_str(self) -> &'static str {
107        match self {
108            Self::Load => "load",
109            Self::Weak => "weak",
110            Self::Reexport => "reexport",
111            Self::Lazy => "lazy",
112            Self::Upward => "upward",
113            Self::Id => "id",
114        }
115    }
116}
117
118/// A dylib path referenced by a load command.
119#[derive(Debug, Clone, PartialEq, Eq)]
120pub struct DylibDep {
121    /// Dependency kind.
122    pub kind: DylibKind,
123    /// Path string from the load command.
124    pub name: String,
125}
126
127/// Compact description of one load command for dumps.
128#[derive(Debug, Clone, PartialEq, Eq)]
129pub struct LoadCommandInfo {
130    /// Command index (0-based).
131    pub index: u32,
132    /// Command name (`LC_SEGMENT_64`, …).
133    pub name: String,
134    /// Command size in bytes.
135    pub cmdsize: u32,
136    /// Optional one-line detail (segment name, dylib path, …).
137    pub detail: Option<String>,
138}
139
140/// Fully parsed arm64 Mach-O (owned).
141#[derive(Debug, Clone, PartialEq, Eq)]
142pub struct MachOImage {
143    /// Header summary.
144    pub summary: MachOSummary,
145    /// Segments and sections.
146    pub segments: Vec<SegmentInfo>,
147    /// Dylib-related dependencies (and optional id).
148    pub dylibs: Vec<DylibDep>,
149    /// All load commands (compact).
150    pub load_commands: Vec<LoadCommandInfo>,
151    /// Raw rpaths.
152    pub rpaths: Vec<String>,
153}
154
155impl MachOImage {
156    /// Header summary.
157    #[must_use]
158    pub fn summary(&self) -> &MachOSummary {
159        &self.summary
160    }
161
162    /// Filter dylib deps by substring (case-sensitive).
163    #[must_use]
164    pub fn dylibs_matching(&self, find: Option<&str>) -> Vec<&DylibDep> {
165        self.dylibs
166            .iter()
167            .filter(|dep| find.is_none_or(|needle| dep.name.contains(needle)))
168            .collect()
169    }
170
171    /// Builds a virtual-memory plan at slide 0 for the given guest page size.
172    #[must_use]
173    pub fn plan(&self, guest: GuestPageSize) -> ImagePlan {
174        ImagePlan::from_image(self, guest)
175    }
176}
177
178/// One planned mapping region (segment-level).
179#[derive(Debug, Clone, PartialEq, Eq)]
180pub struct PlannedMapping {
181    /// Segment name.
182    pub name: String,
183    /// Preferred VA (slide 0).
184    pub vmaddr: u64,
185    /// Virtual size as declared.
186    pub vmsize: u64,
187    /// File offset of the first mapped byte.
188    pub fileoff: u64,
189    /// Bytes to load from the file.
190    pub filesize: u64,
191    /// `vmaddr` rounded down to guest page.
192    pub guest_aligned_addr: u64,
193    /// End address rounded up to guest page.
194    pub guest_aligned_end: u64,
195    /// Initial protection bits.
196    pub initprot: u32,
197    /// Maximum protection bits.
198    pub maxprot: u32,
199    /// True when `vmaddr` is guest-page aligned.
200    pub vmaddr_guest_aligned: bool,
201    /// True when `vmsize` is a guest-page multiple (or zero).
202    pub vmsize_guest_aligned: bool,
203    /// Residual `svc` scan ranges relative to this segment's file content
204    /// (`offset` from segment `fileoff`, `len`). Instruction sections only
205    /// (`S_ATTR_PURE_INSTRUCTIONS` / `S_ATTR_SOME_INSTRUCTIONS`). Empty →
206    /// trap backend scans the whole segment filesize.
207    pub svc_scan_ranges: Vec<(u64, u64)>,
208}
209
210/// Planned virtual memory layout for a loaded image (pre-mmap, slide = 0).
211#[derive(Debug, Clone, PartialEq, Eq)]
212pub struct ImagePlan {
213    /// Guest page size used for alignment checks (bytes).
214    pub guest_page_size: u32,
215    /// Preferred base (lowest non-zero segment `vmaddr`, else 0).
216    pub preferred_base: u64,
217    /// Entry virtual address if known.
218    pub entry: Option<u64>,
219    /// Planned segment mappings.
220    pub mappings: Vec<PlannedMapping>,
221    /// True if every segment is guest-page aligned in addr and size.
222    pub fully_guest_aligned: bool,
223}
224
225impl ImagePlan {
226    /// Empty plan placeholder.
227    #[inline]
228    #[must_use]
229    pub const fn empty() -> Self {
230        Self {
231            guest_page_size: 0,
232            preferred_base: 0,
233            entry: None,
234            mappings: Vec::new(),
235            fully_guest_aligned: true,
236        }
237    }
238
239    /// Builds a plan from a parsed image.
240    #[must_use]
241    pub fn from_image(image: &MachOImage, guest: GuestPageSize) -> Self {
242        use kh_runtime::PageLayout;
243
244        let guest_page = guest.bytes();
245        let mut preferred_base = u64::MAX;
246        let mut mappings = Vec::with_capacity(image.segments.len());
247        let mut fully_aligned = true;
248
249        for seg in &image.segments {
250            let aligned_addr = PageLayout::align_down(seg.vmaddr, guest_page).unwrap_or(seg.vmaddr);
251            let end = seg.vmaddr.saturating_add(seg.vmsize);
252            let aligned_end = PageLayout::align_up(end, guest_page).unwrap_or(end);
253
254            let vmaddr_ok = guest_page != 0 && seg.vmaddr.is_multiple_of(u64::from(guest_page));
255            let vmsize_ok = guest_page != 0
256                && (seg.vmsize == 0 || seg.vmsize.is_multiple_of(u64::from(guest_page)));
257            if !vmaddr_ok || !vmsize_ok {
258                fully_aligned = false;
259            }
260
261            // Preferred load base: lowest mapped segment that is not null-page catch.
262            let is_pagezero = seg.name == "__PAGEZERO" || (seg.initprot == 0 && seg.fileoff == 0);
263            if seg.vmsize > 0 && !is_pagezero && seg.vmaddr < preferred_base {
264                preferred_base = seg.vmaddr;
265            }
266
267            let svc_scan_ranges = instruction_scan_ranges(seg);
268
269            mappings.push(PlannedMapping {
270                name: seg.name.clone(),
271                vmaddr: seg.vmaddr,
272                vmsize: seg.vmsize,
273                // On-disk offset = thin-relative fileoff + fat container slice base.
274                fileoff: seg.fileoff.saturating_add(image.summary.file_slice_offset),
275                filesize: seg.filesize,
276                guest_aligned_addr: aligned_addr,
277                guest_aligned_end: aligned_end,
278                initprot: seg.initprot,
279                maxprot: seg.maxprot,
280                vmaddr_guest_aligned: vmaddr_ok,
281                vmsize_guest_aligned: vmsize_ok,
282                svc_scan_ranges,
283            });
284        }
285
286        if preferred_base == u64::MAX {
287            preferred_base = 0;
288        }
289
290        Self {
291            guest_page_size: guest_page,
292            preferred_base,
293            entry: image.summary.entry,
294            mappings,
295            fully_guest_aligned: fully_aligned,
296        }
297    }
298
299    /// Number of segments in the plan.
300    #[must_use]
301    pub fn segment_count(&self) -> usize {
302        self.mappings.len()
303    }
304}
305
306/// Darwin section attribute: pure instructions (code).
307const S_ATTR_PURE_INSTRUCTIONS: u32 = 0x8000_0000;
308/// Darwin section attribute: some instructions mixed in.
309const S_ATTR_SOME_INSTRUCTIONS: u32 = 0x0000_0400;
310
311/// Collect residual-`svc` scan ranges for a segment (instruction sections only).
312///
313/// Offsets are relative to the segment's thin `fileoff` / mapped file content.
314/// Scanning only pure/some-instruction sections avoids rewriting data that
315/// merely looks like an `svc` encoding in `__const` / `__cstring` (CLT tools
316/// had false positives on a full-TEXT walk) and skips non-code bytes.
317fn instruction_scan_ranges(seg: &SegmentInfo) -> Vec<(u64, u64)> {
318    let mut out = Vec::new();
319    for sect in &seg.sections {
320        if sect.flags & (S_ATTR_PURE_INSTRUCTIONS | S_ATTR_SOME_INSTRUCTIONS) == 0 {
321            continue;
322        }
323        if sect.size == 0 {
324            continue;
325        }
326        let sect_off = u64::from(sect.offset);
327        if sect_off < seg.fileoff {
328            continue;
329        }
330        let rel = sect_off.saturating_sub(seg.fileoff);
331        if rel >= seg.filesize {
332            continue;
333        }
334        let max_len = seg.filesize.saturating_sub(rel);
335        let len = sect.size.min(max_len);
336        if len > 0 {
337            out.push((rel, len));
338        }
339    }
340    out
341}