Skip to main content

kh_loader/
link.rs

1//! Nlist export/import extraction and nlist→GOT fallback bind.
2//!
3//! Prefer classic dyld bind opcodes via [`crate::bind`] when
4//! `LC_DYLD_INFO` / `LC_DYLD_INFO_ONLY` is present. This module still
5//! implements the Phase 6 nlist → `__DATA,__got` path for images without
6//! bind streams.
7
8use std::collections::HashMap;
9
10use goblin::mach::Mach;
11use goblin::mach::symbols::{N_EXT, N_SECT, N_TYPE, N_UNDF, N_WEAK_REF};
12
13use kh_runtime::{mprotect_darwin, mprotect_rw};
14
15use crate::error::LoadError;
16use crate::image::MachOImage;
17use crate::parse::{read_thin_arm64, thin_arm64_bytes};
18use crate::session::{ImageLoadStatus, LoadSession, ProcessImage};
19
20/// Defined external nlist symbol (`N_SECT | N_EXT`, non-STAB).
21#[derive(Debug, Clone, PartialEq, Eq)]
22pub struct DefinedSymbol {
23    /// Exact nlist string (e.g. `_kh_add`).
24    pub name: String,
25    /// `n_value` at slide 0 (preferred VA).
26    pub value: u64,
27    /// Section ordinal (`n_sect`).
28    pub sect: u8,
29}
30
31/// Undefined external nlist symbol.
32#[derive(Debug, Clone, PartialEq, Eq)]
33pub struct UndefinedSymbol {
34    /// Exact nlist string.
35    pub name: String,
36    /// `N_WEAK_REF` in `n_desc`.
37    pub weak_ref: bool,
38}
39
40/// External defined symbols from the nlist (empty if no symtab).
41///
42/// Does **not** use dyld export tries or bind opcodes.
43pub fn defined_exports(bytes: &[u8]) -> Result<Vec<DefinedSymbol>, LoadError> {
44    let mut out = Vec::new();
45    for_each_nlist(bytes, |name, nlist| {
46        if nlist.is_stab() || (nlist.n_type & N_EXT) == 0 {
47            return;
48        }
49        if nlist.n_type & N_TYPE != N_SECT {
50            return;
51        }
52        out.push(DefinedSymbol {
53            name: name.to_owned(),
54            value: nlist.n_value,
55            sect: u8::try_from(nlist.n_sect).unwrap_or(u8::MAX),
56        });
57    })?;
58    Ok(out)
59}
60
61/// External undefined symbols from the nlist in table order (empty if no symtab).
62///
63/// Does **not** call goblin `MachO::imports()` / bind opcodes.
64pub fn undefined_imports(bytes: &[u8]) -> Result<Vec<UndefinedSymbol>, LoadError> {
65    let mut out = Vec::new();
66    for_each_nlist(bytes, |name, nlist| {
67        if nlist.is_stab() || (nlist.n_type & N_EXT) == 0 {
68            return;
69        }
70        // N_UNDF external (and prebound-undef treated the same for Micro).
71        if nlist.n_type & N_TYPE != N_UNDF {
72            return;
73        }
74        if nlist.n_sect != 0 {
75            return;
76        }
77        out.push(UndefinedSymbol {
78            name: name.to_owned(),
79            weak_ref: nlist.n_desc & N_WEAK_REF != 0,
80        });
81    })?;
82    Ok(out)
83}
84
85/// Bind main external undefined nlist symbols into contiguous `__got` slots.
86///
87/// Used when no image in the process set has classic bind opcodes.
88/// No-op when the main image has no external undefined nlist symbols.
89pub(crate) fn bind_main_got_nlist(session: &mut LoadSession) -> Result<(), LoadError> {
90    let main_path = session
91        .images
92        .first()
93        .map(|i| i.path.clone())
94        .ok_or(LoadError::NotImplemented("main missing before bind"))?;
95    let main_bytes = read_thin_arm64(&main_path)?;
96    let undefs = undefined_imports(&main_bytes)?;
97    if undefs.is_empty() {
98        return Ok(());
99    }
100
101    let main = session
102        .images
103        .first()
104        .ok_or(LoadError::NotImplemented("main missing before bind"))?;
105    // ADRP/ADR to the main image's own __got are PC-relative, so a uniform
106    // main slide is fine. (Plan's ImageSlid was over-conservative; keep the
107    // error variant for a future non-uniform / absolute-address case.)
108    let main_slide = main.slide();
109
110    let export_map = build_export_map(session.images());
111    let (got_pref, got_size) =
112        find_got_section(main.image.as_ref()).ok_or(LoadError::MissingGot {
113            count: undefs.len(),
114        })?;
115    let need = undefs.len().checked_mul(8).ok_or(LoadError::MissingGot {
116        count: undefs.len(),
117    })?;
118    let need_u64 = u64::try_from(need).unwrap_or(u64::MAX);
119    if got_size < need_u64 {
120        return Err(LoadError::MissingGot {
121            count: undefs.len(),
122        });
123    }
124    let got_va = got_pref.wrapping_add(main_slide);
125
126    let mut values = Vec::with_capacity(undefs.len());
127    for u in &undefs {
128        match export_map.get(&u.name) {
129            Some(&va) => {
130                tracing::debug!(name = %u.name, va, "bind GOT nlist");
131                values.push(va);
132            }
133            None if u.weak_ref => {
134                tracing::debug!(name = %u.name, "weak undef → GOT 0");
135                values.push(0);
136            }
137            None => {
138                return Err(LoadError::UnresolvedSymbol {
139                    name: u.name.clone(),
140                });
141            }
142        }
143    }
144
145    write_got_slots(session, got_va, &values)?;
146    Ok(())
147}
148
149pub(crate) fn fill_exports(session: &mut LoadSession) -> Result<(), LoadError> {
150    for img in &mut session.images {
151        if !matches!(img.status, ImageLoadStatus::Mapped) {
152            img.exports.clear();
153            continue;
154        }
155        if img.path.as_os_str().is_empty() {
156            img.exports.clear();
157            continue;
158        }
159        let bytes = read_thin_arm64(&img.path)?;
160        img.exports = defined_exports(&bytes)?;
161    }
162    Ok(())
163}
164
165pub(crate) fn build_export_map(images: &[ProcessImage]) -> HashMap<String, u64> {
166    let mut map = HashMap::new();
167    for img in images {
168        if !matches!(img.status, ImageLoadStatus::Mapped) {
169            continue;
170        }
171        let slide = img.slide();
172        for exp in &img.exports {
173            map.entry(exp.name.clone())
174                .or_insert_with(|| exp.value.wrapping_add(slide));
175        }
176    }
177    map
178}
179
180fn find_got_section(image: Option<&MachOImage>) -> Option<(u64, u64)> {
181    let image = image?;
182    for seg in &image.segments {
183        for sect in &seg.sections {
184            if sect.name == "__got" {
185                return Some((sect.addr, sect.size));
186            }
187        }
188    }
189    None
190}
191
192fn write_got_slots(
193    session: &mut LoadSession,
194    got_va: u64,
195    values: &[u64],
196) -> Result<(), LoadError> {
197    let main = session
198        .images
199        .first_mut()
200        .ok_or(LoadError::NotImplemented("main missing for GOT write"))?;
201    let memory = main.memory.as_mut().ok_or(LoadError::NotImplemented(
202        "main memory missing for GOT write",
203    ))?;
204
205    // Locate the region that covers the GOT, mprotect RW, write, restore.
206    let region_idx = memory
207        .regions()
208        .iter()
209        .position(|r| {
210            let start = r.guest_addr;
211            let end = start.saturating_add(r.vmsize);
212            got_va >= start && got_va < end
213        })
214        .ok_or(LoadError::MissingGot {
215            count: values.len(),
216        })?;
217
218    let region = memory
219        .regions_mut()
220        .get_mut(region_idx)
221        .ok_or(LoadError::MissingGot {
222            count: values.len(),
223        })?;
224    let region_base = region.guest_addr;
225    let restore = region.prot;
226    mprotect_rw(region).map_err(LoadError::Map)?;
227
228    for (i, &va) in values.iter().enumerate() {
229        let slot = got_va.saturating_add(u64::try_from(i).unwrap_or(0).saturating_mul(8));
230        let offset = usize::try_from(slot.saturating_sub(region_base)).map_err(|_| {
231            LoadError::MissingGot {
232                count: values.len(),
233            }
234        })?;
235        let end = offset.saturating_add(8);
236        let host = region.host_bytes_mut();
237        let Some(slot_bytes) = host.get_mut(offset..end) else {
238            return Err(LoadError::MissingGot {
239                count: values.len(),
240            });
241        };
242        slot_bytes.copy_from_slice(&va.to_le_bytes());
243    }
244
245    mprotect_darwin(region, restore).map_err(LoadError::Map)?;
246    Ok(())
247}
248
249fn for_each_nlist<F>(bytes: &[u8], mut f: F) -> Result<(), LoadError>
250where
251    F: FnMut(&str, goblin::mach::symbols::Nlist),
252{
253    // Accept fat containers: reduce to arm64 thin before nlist walk.
254    let thin = thin_arm64_bytes(bytes)?;
255    let macho = match Mach::parse(thin) {
256        Ok(Mach::Binary(m)) => m,
257        Ok(Mach::Fat(_)) => {
258            return Err(LoadError::NotMachO(
259                "nested fat image inside arm64 slice".into(),
260            ));
261        }
262        Err(err) => return Err(LoadError::NotMachO(err.to_string())),
263    };
264
265    for entry in macho.symbols() {
266        match entry {
267            Ok((name, nlist)) => f(name, nlist),
268            Err(err) => {
269                return Err(LoadError::NotMachO(format!("nlist: {err}")));
270            }
271        }
272    }
273    Ok(())
274}
275
276#[cfg(test)]
277#[allow(clippy::expect_used, clippy::unwrap_used)]
278mod tests {
279    use super::*;
280    use crate::fixture::{
281        KH_BOTTLE_MARK_SYMBOL, arm64_dylib_add, arm64_libsystem_stub, call_dylib_exit,
282        call_libsystem_exit, minimal_arm64_execute,
283    };
284    use crate::session::{ImageLoadStatus, ImageRole, LoadSession};
285    use crate::test_util::map_test_lock;
286    use std::io::Write;
287    use std::sync::atomic::{AtomicU64, Ordering};
288
289    #[test]
290    fn no_symtab_means_zero_undefs() {
291        let bytes = minimal_arm64_execute();
292        let undefs = undefined_imports(&bytes).expect("undefs");
293        assert!(undefs.is_empty());
294        let exports = defined_exports(&bytes).expect("exports");
295        assert!(exports.is_empty());
296    }
297
298    #[test]
299    fn fixture_export_and_import_names() {
300        let dylib = arm64_dylib_add();
301        let exports = defined_exports(&dylib).expect("exports");
302        assert_eq!(exports.len(), 1);
303        let exp = exports.first().expect("one export");
304        assert_eq!(exp.name, "_kh_add");
305        assert!(
306            exp.value >= crate::fixture::LIBKH_ADD_TEXT_VA
307                && exp.value < crate::fixture::LIBKH_ADD_TEXT_VA + 0x4000,
308            "export VA in dylib TEXT: {:#x}",
309            exp.value
310        );
311
312        let main = call_dylib_exit();
313        let undefs = undefined_imports(&main).expect("undefs");
314        assert_eq!(undefs.len(), 1);
315        let und = undefs.first().expect("one undef");
316        assert_eq!(und.name, "_kh_add");
317        assert!(!und.weak_ref);
318    }
319
320    #[test]
321    fn bind_one_got_slot() {
322        static N: AtomicU64 = AtomicU64::new(0);
323        let _guard = map_test_lock();
324        let n = N.fetch_add(1, Ordering::Relaxed);
325        let dir = std::env::temp_dir().join(format!("kh-bind-{}-{n}", std::process::id()));
326        std::fs::create_dir_all(&dir).expect("mkdir");
327        let main_path = dir.join("call_dylib.macho");
328        let dylib_path = dir.join("libkh_add.dylib");
329        {
330            let mut f = std::fs::File::create(&main_path).expect("create main");
331            f.write_all(&call_dylib_exit()).expect("write main");
332        }
333        {
334            let mut f = std::fs::File::create(&dylib_path).expect("create dylib");
335            f.write_all(&arm64_dylib_add()).expect("write dylib");
336        }
337
338        let mut session = LoadSession::open(&main_path, None).expect("open");
339        let _ = session.map_process().expect("map_process");
340        let mapped_count = session
341            .images()
342            .iter()
343            .filter(|i| matches!(i.status, ImageLoadStatus::Mapped))
344            .count();
345        assert!(
346            mapped_count >= 2,
347            "main + dylib should map: {:?}",
348            session
349                .images()
350                .iter()
351                .map(|i| (i.role, i.status.as_str(), i.install_name.as_str()))
352                .collect::<Vec<_>>()
353        );
354        let main = session.images().first().expect("main");
355        assert_eq!(main.role, ImageRole::Main);
356        let main_slide = main.slide();
357
358        let export_va = session
359            .images()
360            .iter()
361            .find(|i| i.role == ImageRole::Dylib && matches!(i.status, ImageLoadStatus::Mapped))
362            .and_then(|dylib| {
363                dylib
364                    .exports
365                    .iter()
366                    .find(|e| e.name == "_kh_add")
367                    .map(|e| e.value.wrapping_add(dylib.slide()))
368            })
369            .expect("dylib export");
370
371        let got_va = crate::fixture::CALL_DYLIB_GOT_VA.wrapping_add(main_slide);
372        let main_mem = session
373            .images()
374            .first()
375            .and_then(|i| i.memory.as_ref())
376            .expect("main mem");
377        let region = main_mem
378            .regions()
379            .iter()
380            .find(|r| got_va >= r.guest_addr && got_va < r.guest_addr.saturating_add(r.vmsize))
381            .expect("DATA region");
382        let off = usize::try_from(got_va.saturating_sub(region.guest_addr)).unwrap();
383        let end = off.saturating_add(8);
384        let bytes = region.host_bytes().get(off..end).expect("got bytes");
385        let mut le = [0_u8; 8];
386        le.copy_from_slice(bytes);
387        assert_eq!(u64::from_le_bytes(le), export_va);
388
389        drop(session);
390        drop(std::fs::remove_dir_all(dir));
391    }
392
393    #[test]
394    fn libsystem_stub_export_name() {
395        use crate::fixture::{
396            LIBSYSTEM_EXIT_SYMBOL, LIBSYSTEM_PRINTF_SYMBOL, LIBSYSTEM_PUTS_SYMBOL,
397            LIBSYSTEM_WRITE_SYMBOL,
398        };
399
400        let exports = defined_exports(&arm64_libsystem_stub()).expect("exports");
401        assert_eq!(exports.len(), 5);
402        let names: Vec<&str> = exports.iter().map(|e| e.name.as_str()).collect();
403        assert!(names.contains(&LIBSYSTEM_WRITE_SYMBOL));
404        assert!(names.contains(&LIBSYSTEM_EXIT_SYMBOL));
405        assert!(names.contains(&LIBSYSTEM_PUTS_SYMBOL));
406        assert!(names.contains(&LIBSYSTEM_PRINTF_SYMBOL));
407        assert!(names.contains(&KH_BOTTLE_MARK_SYMBOL));
408        for exp in &exports {
409            assert!(
410                exp.value >= crate::fixture::LIBSYSTEM_TEXT_VA
411                    && exp.value < crate::fixture::LIBSYSTEM_TEXT_VA + 0x4000,
412                "export VA in stub TEXT: {} @ {:#x}",
413                exp.name,
414                exp.value
415            );
416        }
417
418        let undefs = undefined_imports(&call_libsystem_exit()).expect("undefs");
419        assert_eq!(undefs.len(), 1);
420        assert_eq!(undefs.first().expect("one").name, KH_BOTTLE_MARK_SYMBOL);
421    }
422}