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 named_handler = export_map.get("_kh_missing_symbol_named").copied();
127    let missing_stub = export_map.get("_kh_missing_symbol").copied();
128    let mut values = Vec::with_capacity(undefs.len());
129    for u in &undefs {
130        match export_map.get(&u.name) {
131            Some(&va) => {
132                tracing::debug!(name = %u.name, va, "bind GOT nlist");
133                values.push(va);
134            }
135            None if u.weak_ref => {
136                tracing::debug!(name = %u.name, "weak undef → GOT 0");
137                values.push(0);
138            }
139            None => {
140                if let Some(handler) = named_handler {
141                    match crate::missing_stub::trampoline_for(&u.name, handler) {
142                        Ok(va) => {
143                            tracing::warn!(
144                                name = %u.name,
145                                stub = format_args!("{va:#x}"),
146                                "unresolved strong nlist; bound to named missing trampoline"
147                            );
148                            values.push(va);
149                            continue;
150                        }
151                        Err(err) => {
152                            tracing::warn!(
153                                name = %u.name,
154                                error = %err,
155                                "missing trampoline emit failed; falling back"
156                            );
157                        }
158                    }
159                }
160                if let Some(stub) = missing_stub {
161                    tracing::warn!(
162                        name = %u.name,
163                        "unresolved strong nlist; bound to _kh_missing_symbol"
164                    );
165                    values.push(stub);
166                } else if let Some(handler) = named_handler {
167                    values.push(handler);
168                } else {
169                    return Err(LoadError::UnresolvedSymbol {
170                        name: u.name.clone(),
171                    });
172                }
173            }
174        }
175    }
176
177    write_got_slots(session, got_va, &values)?;
178    Ok(())
179}
180
181pub(crate) fn fill_exports(session: &mut LoadSession) -> Result<(), LoadError> {
182    for img in &mut session.images {
183        if !matches!(img.status, ImageLoadStatus::Mapped) {
184            img.exports.clear();
185            continue;
186        }
187        if img.path.as_os_str().is_empty() {
188            img.exports.clear();
189            continue;
190        }
191        let bytes = read_thin_arm64(&img.path)?;
192        img.exports = defined_exports(&bytes)?;
193    }
194    Ok(())
195}
196
197pub(crate) fn build_export_map(images: &[ProcessImage]) -> HashMap<String, u64> {
198    let mut map = HashMap::new();
199    for img in images {
200        if !matches!(img.status, ImageLoadStatus::Mapped) {
201            continue;
202        }
203        let slide = img.slide();
204        for exp in &img.exports {
205            map.entry(exp.name.clone())
206                .or_insert_with(|| exp.value.wrapping_add(slide));
207        }
208    }
209    // Darwin clients (e.g. curl) import the unadorned dyld helper name; freestanding
210    // libSystem exports the C-style `_dyld_stub_binder` nlist.
211    if let Some(&va) = map.get("_dyld_stub_binder") {
212        map.entry("dyld_stub_binder".into()).or_insert(va);
213    }
214    map
215}
216
217fn find_got_section(image: Option<&MachOImage>) -> Option<(u64, u64)> {
218    let image = image?;
219    for seg in &image.segments {
220        for sect in &seg.sections {
221            if sect.name == "__got" {
222                return Some((sect.addr, sect.size));
223            }
224        }
225    }
226    None
227}
228
229fn write_got_slots(
230    session: &mut LoadSession,
231    got_va: u64,
232    values: &[u64],
233) -> Result<(), LoadError> {
234    let main = session
235        .images
236        .first_mut()
237        .ok_or(LoadError::NotImplemented("main missing for GOT write"))?;
238    let memory = main.memory.as_mut().ok_or(LoadError::NotImplemented(
239        "main memory missing for GOT write",
240    ))?;
241
242    // Locate the region that covers the GOT, mprotect RW, write, restore.
243    let region_idx = memory
244        .regions()
245        .iter()
246        .position(|r| {
247            let start = r.guest_addr;
248            let end = start.saturating_add(r.vmsize);
249            got_va >= start && got_va < end
250        })
251        .ok_or(LoadError::MissingGot {
252            count: values.len(),
253        })?;
254
255    let region = memory
256        .regions_mut()
257        .get_mut(region_idx)
258        .ok_or(LoadError::MissingGot {
259            count: values.len(),
260        })?;
261    let region_base = region.guest_addr;
262    let restore = region.prot;
263    mprotect_rw(region).map_err(LoadError::Map)?;
264
265    for (i, &va) in values.iter().enumerate() {
266        let slot = got_va.saturating_add(u64::try_from(i).unwrap_or(0).saturating_mul(8));
267        let offset = usize::try_from(slot.saturating_sub(region_base)).map_err(|_| {
268            LoadError::MissingGot {
269                count: values.len(),
270            }
271        })?;
272        let end = offset.saturating_add(8);
273        let host = region.host_bytes_mut();
274        let Some(slot_bytes) = host.get_mut(offset..end) else {
275            return Err(LoadError::MissingGot {
276                count: values.len(),
277            });
278        };
279        slot_bytes.copy_from_slice(&va.to_le_bytes());
280    }
281
282    mprotect_darwin(region, restore).map_err(LoadError::Map)?;
283    Ok(())
284}
285
286fn for_each_nlist<F>(bytes: &[u8], mut f: F) -> Result<(), LoadError>
287where
288    F: FnMut(&str, goblin::mach::symbols::Nlist),
289{
290    // Accept fat containers: reduce to arm64 thin before nlist walk.
291    let thin = thin_arm64_bytes(bytes)?;
292    let macho = match Mach::parse(thin) {
293        Ok(Mach::Binary(m)) => m,
294        Ok(Mach::Fat(_)) => {
295            return Err(LoadError::NotMachO(
296                "nested fat image inside arm64 slice".into(),
297            ));
298        }
299        Err(err) => return Err(LoadError::NotMachO(err.to_string())),
300    };
301
302    for entry in macho.symbols() {
303        match entry {
304            Ok((name, nlist)) => f(name, nlist),
305            Err(err) => {
306                return Err(LoadError::NotMachO(format!("nlist: {err}")));
307            }
308        }
309    }
310    Ok(())
311}
312
313#[cfg(test)]
314#[allow(clippy::expect_used, clippy::unwrap_used)]
315mod tests {
316    use super::*;
317    use crate::fixture::{
318        KH_BOTTLE_MARK_SYMBOL, arm64_dylib_add, arm64_libsystem_stub, call_dylib_exit,
319        call_libsystem_exit, minimal_arm64_execute,
320    };
321    use crate::session::{ImageLoadStatus, ImageRole, LoadSession};
322    use crate::test_util::map_test_lock;
323    use std::io::Write;
324    use std::sync::atomic::{AtomicU64, Ordering};
325
326    #[test]
327    fn no_symtab_means_zero_undefs() {
328        let bytes = minimal_arm64_execute();
329        let undefs = undefined_imports(&bytes).expect("undefs");
330        assert!(undefs.is_empty());
331        let exports = defined_exports(&bytes).expect("exports");
332        assert!(exports.is_empty());
333    }
334
335    #[test]
336    fn fixture_export_and_import_names() {
337        let dylib = arm64_dylib_add();
338        let exports = defined_exports(&dylib).expect("exports");
339        assert_eq!(exports.len(), 1);
340        let exp = exports.first().expect("one export");
341        assert_eq!(exp.name, "_kh_add");
342        assert!(
343            exp.value >= crate::fixture::LIBKH_ADD_TEXT_VA
344                && exp.value < crate::fixture::LIBKH_ADD_TEXT_VA + 0x4000,
345            "export VA in dylib TEXT: {:#x}",
346            exp.value
347        );
348
349        let main = call_dylib_exit();
350        let undefs = undefined_imports(&main).expect("undefs");
351        assert_eq!(undefs.len(), 1);
352        let und = undefs.first().expect("one undef");
353        assert_eq!(und.name, "_kh_add");
354        assert!(!und.weak_ref);
355    }
356
357    #[test]
358    fn bind_one_got_slot() {
359        static N: AtomicU64 = AtomicU64::new(0);
360        let _guard = map_test_lock();
361        let n = N.fetch_add(1, Ordering::Relaxed);
362        let dir = std::env::temp_dir().join(format!("kh-bind-{}-{n}", std::process::id()));
363        std::fs::create_dir_all(&dir).expect("mkdir");
364        let main_path = dir.join("call_dylib.macho");
365        let dylib_path = dir.join("libkh_add.dylib");
366        {
367            let mut f = std::fs::File::create(&main_path).expect("create main");
368            f.write_all(&call_dylib_exit()).expect("write main");
369        }
370        {
371            let mut f = std::fs::File::create(&dylib_path).expect("create dylib");
372            f.write_all(&arm64_dylib_add()).expect("write dylib");
373        }
374
375        let mut session = LoadSession::open(&main_path, None).expect("open");
376        let _ = session.map_process().expect("map_process");
377        let mapped_count = session
378            .images()
379            .iter()
380            .filter(|i| matches!(i.status, ImageLoadStatus::Mapped))
381            .count();
382        assert!(
383            mapped_count >= 2,
384            "main + dylib should map: {:?}",
385            session
386                .images()
387                .iter()
388                .map(|i| (i.role, i.status.as_str(), i.install_name.as_str()))
389                .collect::<Vec<_>>()
390        );
391        let main = session.images().first().expect("main");
392        assert_eq!(main.role, ImageRole::Main);
393        let main_slide = main.slide();
394
395        let export_va = session
396            .images()
397            .iter()
398            .find(|i| i.role == ImageRole::Dylib && matches!(i.status, ImageLoadStatus::Mapped))
399            .and_then(|dylib| {
400                dylib
401                    .exports
402                    .iter()
403                    .find(|e| e.name == "_kh_add")
404                    .map(|e| e.value.wrapping_add(dylib.slide()))
405            })
406            .expect("dylib export");
407
408        let got_va = crate::fixture::CALL_DYLIB_GOT_VA.wrapping_add(main_slide);
409        let main_mem = session
410            .images()
411            .first()
412            .and_then(|i| i.memory.as_ref())
413            .expect("main mem");
414        let region = main_mem
415            .regions()
416            .iter()
417            .find(|r| got_va >= r.guest_addr && got_va < r.guest_addr.saturating_add(r.vmsize))
418            .expect("DATA region");
419        let off = usize::try_from(got_va.saturating_sub(region.guest_addr)).unwrap();
420        let end = off.saturating_add(8);
421        let bytes = region.host_bytes().get(off..end).expect("got bytes");
422        let mut le = [0_u8; 8];
423        le.copy_from_slice(bytes);
424        assert_eq!(u64::from_le_bytes(le), export_va);
425
426        drop(session);
427        drop(std::fs::remove_dir_all(dir));
428    }
429
430    #[test]
431    fn libsystem_stub_export_name() {
432        use crate::fixture::{
433            LIBSYSTEM_EXIT_SYMBOL, LIBSYSTEM_PRINTF_SYMBOL, LIBSYSTEM_PUTS_SYMBOL,
434            LIBSYSTEM_WRITE_SYMBOL,
435        };
436
437        let exports = defined_exports(&arm64_libsystem_stub()).expect("exports");
438        assert_eq!(exports.len(), 5);
439        let names: Vec<&str> = exports.iter().map(|e| e.name.as_str()).collect();
440        assert!(names.contains(&LIBSYSTEM_WRITE_SYMBOL));
441        assert!(names.contains(&LIBSYSTEM_EXIT_SYMBOL));
442        assert!(names.contains(&LIBSYSTEM_PUTS_SYMBOL));
443        assert!(names.contains(&LIBSYSTEM_PRINTF_SYMBOL));
444        assert!(names.contains(&KH_BOTTLE_MARK_SYMBOL));
445        for exp in &exports {
446            assert!(
447                exp.value >= crate::fixture::LIBSYSTEM_TEXT_VA
448                    && exp.value < crate::fixture::LIBSYSTEM_TEXT_VA + 0x4000,
449                "export VA in stub TEXT: {} @ {:#x}",
450                exp.name,
451                exp.value
452            );
453        }
454
455        let undefs = undefined_imports(&call_libsystem_exit()).expect("undefs");
456        assert_eq!(undefs.len(), 1);
457        assert_eq!(undefs.first().expect("one").name, KH_BOTTLE_MARK_SYMBOL);
458    }
459}