Skip to main content

kh_loader/
init.rs

1//! Load-time initializers (`S_MOD_INIT_FUNC_POINTERS` / `S_INIT_FUNC_OFFSETS`).
2//!
3//! After map + bind, dyld runs module constructors bottom-up (dependencies
4//! before dependents) before transferring to `LC_MAIN`. Phase 7 implements the
5//! same order for mapped images using [`kh_runtime::call_guest`].
6//!
7//! Modern Apple toolchains emit `__TEXT,__init_offsets` (`S_INIT_FUNC_OFFSETS`)
8//! with 32-bit image-relative offsets instead of classic pointer arrays. Real
9//! guests such as `7zz` use that form; older images keep `mod_init_func`.
10#![allow(unsafe_code)]
11
12use kh_runtime::{GuestMemory, call_guest};
13
14use crate::error::LoadError;
15use crate::image::MachOImage;
16use crate::session::{ImageLoadStatus, ImageRole, LoadSession, ProcessImage};
17
18/// Section type: array of function pointers run at load (`S_MOD_INIT_FUNC_POINTERS`).
19pub const S_MOD_INIT_FUNC_POINTERS: u32 = 0x9;
20
21/// Section type: 32-bit offsets to initializers (`S_INIT_FUNC_OFFSETS`).
22///
23/// Each entry is a little-endian `u32` offset from the image preferred load
24/// address (mach_header). Actual VA = preferred_base + slide + offset.
25pub const S_INIT_FUNC_OFFSETS: u32 = 0x16;
26
27/// Mask for Mach-O section type bits in `flags`.
28pub const SECTION_TYPE: u32 = 0xff;
29
30/// One initializer to invoke (already slide-adjusted guest VA).
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct InitFunc {
33    /// Guest VA of the function (`void (*)(void)`).
34    pub va: u64,
35    /// Image path for diagnostics.
36    pub image_path: String,
37}
38
39/// Collects initializer VAs for one mapped image.
40///
41/// Supports both:
42/// - classic `S_MOD_INIT_FUNC_POINTERS` (8-byte preferred pointers; post-rebase
43///   they are already runnable VAs when `slide != 0`);
44/// - modern `S_INIT_FUNC_OFFSETS` (4-byte offsets from preferred image base).
45///
46/// `preferred_base` is the image's planned preferred load address (lowest
47/// non-`__PAGEZERO` segment); required for `S_INIT_FUNC_OFFSETS`.
48pub fn collect_mod_init(
49    image: &MachOImage,
50    memory: &GuestMemory,
51    preferred_base: u64,
52) -> Result<Vec<u64>, LoadError> {
53    let slide = memory.slide();
54    let mut out = Vec::new();
55    for seg in &image.segments {
56        for sect in &seg.sections {
57            let kind = sect.flags & SECTION_TYPE;
58            if kind == S_MOD_INIT_FUNC_POINTERS {
59                collect_mod_init_pointers(sect, memory, slide, &mut out)?;
60            } else if kind == S_INIT_FUNC_OFFSETS {
61                collect_init_func_offsets(sect, memory, preferred_base, slide, &mut out)?;
62            }
63        }
64    }
65    Ok(out)
66}
67
68fn collect_mod_init_pointers(
69    sect: &crate::image::SectionInfo,
70    memory: &GuestMemory,
71    slide: u64,
72    out: &mut Vec<u64>,
73) -> Result<(), LoadError> {
74    if sect.size == 0 {
75        return Ok(());
76    }
77    if !sect.size.is_multiple_of(8) {
78        return Err(LoadError::Resolve(format!(
79            "mod_init section {}/{} size {:#x} not multiple of 8",
80            sect.segname, sect.name, sect.size
81        )));
82    }
83    let base = sect.addr.wrapping_add(slide);
84    let count = usize::try_from(sect.size.saturating_div(8)).unwrap_or(0);
85    for i in 0..count {
86        let slot_off = u64::try_from(i).unwrap_or(0).saturating_mul(8);
87        let slot = base.wrapping_add(slot_off);
88        let va = memory.read_u64_le(slot).ok_or_else(|| {
89            LoadError::Resolve(format!(
90                "mod_init slot unreadable at {slot:#x} ({}/{})",
91                sect.segname, sect.name
92            ))
93        })?;
94        if va == 0 {
95            continue;
96        }
97        out.push(va);
98    }
99    Ok(())
100}
101
102fn collect_init_func_offsets(
103    sect: &crate::image::SectionInfo,
104    memory: &GuestMemory,
105    preferred_base: u64,
106    slide: u64,
107    out: &mut Vec<u64>,
108) -> Result<(), LoadError> {
109    if sect.size == 0 {
110        return Ok(());
111    }
112    if !sect.size.is_multiple_of(4) {
113        return Err(LoadError::Resolve(format!(
114            "init_offsets section {}/{} size {:#x} not multiple of 4",
115            sect.segname, sect.name, sect.size
116        )));
117    }
118    let base = sect.addr.wrapping_add(slide);
119    let image_load = preferred_base.wrapping_add(slide);
120    let count = usize::try_from(sect.size.saturating_div(4)).unwrap_or(0);
121    for i in 0..count {
122        let slot_off = u64::try_from(i).unwrap_or(0).saturating_mul(4);
123        let slot = base.wrapping_add(slot_off);
124        let raw = memory.read_u32_le(slot).ok_or_else(|| {
125            LoadError::Resolve(format!(
126                "init_offsets slot unreadable at {slot:#x} ({}/{})",
127                sect.segname, sect.name
128            ))
129        })?;
130        if raw == 0 {
131            continue;
132        }
133        let va = image_load.wrapping_add(u64::from(raw));
134        out.push(va);
135    }
136    Ok(())
137}
138
139/// Bottom-up initializer list: mapped dylibs in reverse map order, then main.
140pub fn plan_initializers(images: &[ProcessImage]) -> Result<Vec<InitFunc>, LoadError> {
141    let mut plan = Vec::new();
142
143    let dylibs: Vec<&ProcessImage> = images
144        .iter()
145        .filter(|i| i.role == ImageRole::Dylib && matches!(i.status, ImageLoadStatus::Mapped))
146        .collect();
147    for img in dylibs.into_iter().rev() {
148        push_image_inits(img, &mut plan)?;
149    }
150
151    if let Some(main) = images.first()
152        && main.role == ImageRole::Main
153        && matches!(main.status, ImageLoadStatus::Mapped)
154    {
155        push_image_inits(main, &mut plan)?;
156    }
157
158    Ok(plan)
159}
160
161fn push_image_inits(img: &ProcessImage, plan: &mut Vec<InitFunc>) -> Result<(), LoadError> {
162    let (Some(image), Some(memory)) = (img.image.as_ref(), img.memory.as_ref()) else {
163        return Ok(());
164    };
165    for va in collect_mod_init(image, memory, img.preferred_base())? {
166        plan.push(InitFunc {
167            va,
168            image_path: img.path.display().to_string(),
169        });
170    }
171    Ok(())
172}
173
174/// Runs all planned initializers on `guest_sp` (16-byte aligned).
175///
176/// Returns the number of functions successfully called.
177pub fn run_initializers(session: &LoadSession, guest_sp: u64) -> Result<usize, LoadError> {
178    let plan = plan_initializers(session.images())?;
179    let total = plan.len();
180    tracing::info!(total, "mod_init plan");
181    let mut ran = 0_usize;
182    for init in &plan {
183        tracing::info!(
184            idx = ran,
185            total,
186            va = format_args!("{:#x}", init.va),
187            image = %init.image_path,
188            "run mod_init"
189        );
190        // SAFETY: VA comes from mapped image sections; stack is the process
191        // guest stack; trap handlers installed by caller before live run.
192        let _ret = unsafe {
193            call_guest(init.va, guest_sp, 0)
194                .map_err(|err| LoadError::PageLayout(err.to_string()))?
195        };
196        ran = ran.saturating_add(1);
197        tracing::debug!(
198            idx = ran.saturating_sub(1),
199            va = format_args!("{:#x}", init.va),
200            "mod_init done"
201        );
202    }
203    Ok(ran)
204}