Skip to main content

kh_loader/
file_image.rs

1//! On-disk Mach-O container bytes for parse → map → bind.
2//!
3//! Prefer a read-only file `mmap` so only pages actually touched by parse /
4//! segment fill / bind enter RSS (large CLT tools, any guest). Fall back to
5//! `fs::read` when mapping fails (empty path edge cases, exotic hosts).
6
7use std::ops::Deref;
8use std::path::Path;
9
10use kh_runtime::MappedFile;
11
12use crate::error::LoadError;
13
14/// Full container of a guest Mach-O (thin or fat).
15#[derive(Debug)]
16pub enum FileImage {
17    /// Lazy `mmap` of the whole file.
18    Map(MappedFile),
19    /// Eager heap copy (`fs::read` fallback).
20    Heap(Vec<u8>),
21}
22
23impl FileImage {
24    /// Open `path` via `mmap` when possible; otherwise `fs::read`.
25    pub fn open(path: &Path) -> Result<Self, LoadError> {
26        match MappedFile::open(path) {
27            Ok(m) => Ok(Self::Map(m)),
28            Err(_mmap_err) => {
29                let bytes = std::fs::read(path)?;
30                Ok(Self::Heap(bytes))
31            }
32        }
33    }
34
35    /// Contiguous container bytes.
36    #[must_use]
37    pub fn as_slice(&self) -> &[u8] {
38        match self {
39            Self::Map(m) => m.as_slice(),
40            Self::Heap(v) => v.as_slice(),
41        }
42    }
43
44    /// Length in bytes.
45    #[must_use]
46    pub fn len(&self) -> usize {
47        self.as_slice().len()
48    }
49
50    /// Empty container.
51    #[must_use]
52    pub fn is_empty(&self) -> bool {
53        self.as_slice().is_empty()
54    }
55}
56
57impl Deref for FileImage {
58    type Target = [u8];
59
60    fn deref(&self) -> &Self::Target {
61        self.as_slice()
62    }
63}