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