Skip to main content

kh_loader/
lib.rs

1//! Mach-O loading, image planning, and process session orchestration.
2//!
3//! Depends on `kh-runtime` for page geometry and register types.
4//! Must not depend on `kh-cli`.
5
6pub mod bind;
7pub mod chained;
8pub mod deps;
9pub mod error;
10pub mod execute;
11pub mod fixture;
12pub mod image;
13pub mod init;
14pub mod link;
15pub mod missing_stub;
16pub mod parse;
17pub mod rebase;
18pub mod resolve;
19pub mod session;
20
21pub use bind::{BindSite, bind_process, collect_bind_sites, encode_pointer_bind};
22pub use chained::{
23    ChainDecode, ChainedImport, DYLD_CHAINED_PTR_64, DYLD_CHAINED_PTR_64_OFFSET,
24    apply_chained_fixups, bytes_have_chained_fixups, decode_ptr_64, encode_chained_fixups_blob,
25    encode_ptr_64_bind, encode_ptr_64_rebase, image_has_chained_fixups,
26};
27pub use deps::{DepEdge, MAX_DYLIBS, is_followable};
28pub use error::LoadError;
29pub use execute::{RunOptions, RunResult, run_micro};
30pub use image::{
31    DylibDep, DylibKind, ImagePlan, LoadCommandInfo, MachOImage, MachOSummary, PlannedMapping,
32    SectionInfo, SegmentInfo,
33};
34pub use init::{
35    InitFunc, S_INIT_FUNC_OFFSETS, S_MOD_INIT_FUNC_POINTERS, collect_mod_init, plan_initializers,
36    run_initializers,
37};
38pub use link::{DefinedSymbol, UndefinedSymbol, defined_exports, undefined_imports};
39pub use parse::{
40    Arm64Slice, locate_arm64_slice, parse_bytes, parse_path, read_thin_arm64, thin_arm64_bytes,
41};
42pub use rebase::{
43    S_INTERPOSING, S_LITERAL_POINTERS, S_MOD_TERM_FUNC_POINTERS, is_rebasable_section_type,
44    rebase_image, rebase_memory, rebase_process,
45};
46// Note: `S_MOD_INIT_FUNC_POINTERS` is exported from `init` (same numeric value).
47pub use resolve::{ResolveContext, ResolveError, resolve_install_name};
48pub use session::{
49    DryLoadImageInfo, DryLoadReport, ImageLoadStatus, ImageRole, LoadSession, MappedRegionInfo,
50    ProcessImage, SkipReason, map_requests_from_plan,
51};
52
53#[cfg(test)]
54#[allow(clippy::expect_used)]
55pub(crate) mod test_util {
56    use std::fs::File;
57    use std::io::Write;
58    use std::path::{Path, PathBuf};
59    use std::sync::atomic::{AtomicU64, Ordering};
60    use std::sync::{Mutex, MutexGuard, OnceLock, PoisonError};
61
62    /// Serialize identity-map unit tests so preferred-VA races under
63    /// `MAP_FIXED_NOREPLACE` (Linux) do not flake as `PlacementFailed`.
64    pub(crate) fn map_test_lock() -> MutexGuard<'static, ()> {
65        static LOCK: OnceLock<Mutex<()>> = OnceLock::new();
66        LOCK.get_or_init(|| Mutex::new(()))
67            .lock()
68            .unwrap_or_else(PoisonError::into_inner)
69    }
70
71    /// Unique path under the system temp directory.
72    pub(crate) fn temp_path(prefix: &str) -> PathBuf {
73        static N: AtomicU64 = AtomicU64::new(0);
74        let n = N.fetch_add(1, Ordering::Relaxed);
75        std::env::temp_dir().join(format!("kh-{prefix}-{}-{n}", std::process::id()))
76    }
77
78    /// Write `bytes` to a new unique temp file; returns the path.
79    pub(crate) fn write_temp_bytes(prefix: &str, bytes: &[u8]) -> PathBuf {
80        let path = temp_path(prefix);
81        let mut f = File::create(&path).expect("create temp");
82        f.write_all(bytes).expect("write temp");
83        path
84    }
85
86    /// Create a unique temp directory.
87    pub(crate) fn temp_dir(prefix: &str) -> PathBuf {
88        let dir = temp_path(prefix);
89        std::fs::create_dir_all(&dir).expect("mkdir temp");
90        dir
91    }
92
93    /// Write a file under `dir` (creating parents as needed).
94    pub(crate) fn write_under(dir: &Path, rel: &str, bytes: &[u8]) -> PathBuf {
95        let path = dir.join(rel);
96        if let Some(parent) = path.parent() {
97            std::fs::create_dir_all(parent).expect("mkdir parent");
98        }
99        let mut f = File::create(&path).expect("create under");
100        f.write_all(bytes).expect("write under");
101        path
102    }
103}