1#![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
18pub const S_MOD_INIT_FUNC_POINTERS: u32 = 0x9;
20
21pub const S_INIT_FUNC_OFFSETS: u32 = 0x16;
26
27pub const SECTION_TYPE: u32 = 0xff;
29
30#[derive(Debug, Clone, PartialEq, Eq)]
32pub struct InitFunc {
33 pub va: u64,
35 pub image_path: String,
37}
38
39pub 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
139pub 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
174pub fn run_initializers(session: &LoadSession, guest_sp: u64) -> Result<usize, LoadError> {
178 let plan = plan_initializers(session.images())?;
179 let mut ran = 0_usize;
180 for init in &plan {
181 tracing::info!(
182 va = format_args!("{:#x}", init.va),
183 image = %init.image_path,
184 "run mod_init"
185 );
186 let _ret = unsafe {
189 call_guest(init.va, guest_sp, 0)
190 .map_err(|err| LoadError::PageLayout(err.to_string()))?
191 };
192 ran = ran.saturating_add(1);
193 }
194 Ok(ran)
195}
196
197#[cfg(test)]
198#[allow(clippy::expect_used, clippy::unwrap_used)]
199mod tests {
200 use super::*;
201 use crate::fixture::{arm64_dylib_ctor, ctor_main_exit};
202 use crate::session::LoadSession;
203 use crate::test_util::map_test_lock;
204 use std::io::Write;
205 use std::sync::atomic::{AtomicU64, Ordering};
206
207 #[test]
208 fn collect_finds_one_mod_init_in_dylib() {
209 static N: AtomicU64 = AtomicU64::new(0);
210 let _guard = map_test_lock();
211 let n = N.fetch_add(1, Ordering::Relaxed);
212 let dir = std::env::temp_dir().join(format!("kh-init-{}-{n}", std::process::id()));
213 std::fs::create_dir_all(&dir).unwrap();
214 let main_path = dir.join("ctor_main.macho");
215 let dylib_path = dir.join("libkh_ctor.dylib");
216 std::fs::File::create(&main_path)
217 .unwrap()
218 .write_all(&ctor_main_exit())
219 .unwrap();
220 std::fs::File::create(&dylib_path)
221 .unwrap()
222 .write_all(&arm64_dylib_ctor())
223 .unwrap();
224
225 let mut session = LoadSession::open(&main_path, None).unwrap();
226 let _ = session.map_process().unwrap();
227 let plan = plan_initializers(session.images()).expect("plan");
228 assert_eq!(plan.len(), 1, "expected one dylib ctor: {plan:?}");
229 let first = plan.first().expect("one");
230 assert!(
231 first.image_path.contains("libkh_ctor"),
232 "ctor should be from dylib: {}",
233 first.image_path
234 );
235 assert_ne!(first.va, 0);
236
237 drop(session);
238 drop(std::fs::remove_dir_all(dir));
239 }
240}