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}
204
205/// Planned virtual memory layout for a loaded image (pre-mmap, slide = 0).
206#[derive(Debug, Clone, PartialEq, Eq)]
207pub struct ImagePlan {
208    /// Guest page size used for alignment checks (bytes).
209    pub guest_page_size: u32,
210    /// Preferred base (lowest non-zero segment `vmaddr`, else 0).
211    pub preferred_base: u64,
212    /// Entry virtual address if known.
213    pub entry: Option<u64>,
214    /// Planned segment mappings.
215    pub mappings: Vec<PlannedMapping>,
216    /// True if every segment is guest-page aligned in addr and size.
217    pub fully_guest_aligned: bool,
218}
219
220impl ImagePlan {
221    /// Empty plan placeholder.
222    #[inline]
223    #[must_use]
224    pub const fn empty() -> Self {
225        Self {
226            guest_page_size: 0,
227            preferred_base: 0,
228            entry: None,
229            mappings: Vec::new(),
230            fully_guest_aligned: true,
231        }
232    }
233
234    /// Builds a plan from a parsed image.
235    #[must_use]
236    pub fn from_image(image: &MachOImage, guest: GuestPageSize) -> Self {
237        use kh_runtime::PageLayout;
238
239        let guest_page = guest.bytes();
240        let mut preferred_base = u64::MAX;
241        let mut mappings = Vec::with_capacity(image.segments.len());
242        let mut fully_aligned = true;
243
244        for seg in &image.segments {
245            let aligned_addr = PageLayout::align_down(seg.vmaddr, guest_page).unwrap_or(seg.vmaddr);
246            let end = seg.vmaddr.saturating_add(seg.vmsize);
247            let aligned_end = PageLayout::align_up(end, guest_page).unwrap_or(end);
248
249            let vmaddr_ok = guest_page != 0 && seg.vmaddr.is_multiple_of(u64::from(guest_page));
250            let vmsize_ok = guest_page != 0
251                && (seg.vmsize == 0 || seg.vmsize.is_multiple_of(u64::from(guest_page)));
252            if !vmaddr_ok || !vmsize_ok {
253                fully_aligned = false;
254            }
255
256            // Preferred load base: lowest mapped segment that is not null-page catch.
257            let is_pagezero = seg.name == "__PAGEZERO" || (seg.initprot == 0 && seg.fileoff == 0);
258            if seg.vmsize > 0 && !is_pagezero && seg.vmaddr < preferred_base {
259                preferred_base = seg.vmaddr;
260            }
261
262            mappings.push(PlannedMapping {
263                name: seg.name.clone(),
264                vmaddr: seg.vmaddr,
265                vmsize: seg.vmsize,
266                // On-disk offset = thin-relative fileoff + fat container slice base.
267                fileoff: seg
268                    .fileoff
269                    .saturating_add(image.summary.file_slice_offset),
270                filesize: seg.filesize,
271                guest_aligned_addr: aligned_addr,
272                guest_aligned_end: aligned_end,
273                initprot: seg.initprot,
274                maxprot: seg.maxprot,
275                vmaddr_guest_aligned: vmaddr_ok,
276                vmsize_guest_aligned: vmsize_ok,
277            });
278        }
279
280        if preferred_base == u64::MAX {
281            preferred_base = 0;
282        }
283
284        Self {
285            guest_page_size: guest_page,
286            preferred_base,
287            entry: image.summary.entry,
288            mappings,
289            fully_guest_aligned: fully_aligned,
290        }
291    }
292
293    /// Number of segments in the plan.
294    #[must_use]
295    pub fn segment_count(&self) -> usize {
296        self.mappings.len()
297    }
298}