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