Skip to main content

kh_loader/
session.rs

1//! Load session: ties a bottle root, page layout, planned images, and maps.
2
3use std::collections::{HashSet, VecDeque};
4use std::fs::File;
5use std::path::{Path, PathBuf};
6
7use goblin::mach::header::MH_DYLIB;
8use kh_runtime::{GuestMemory, GuestPageSize, HostPageSize, MapRequest, PageLayout};
9
10use crate::bind;
11use crate::deps::{DepEdge, MAX_DYLIBS, concat_rpaths, edges_from_image, image_install_name};
12use crate::error::LoadError;
13use crate::image::{DylibKind, ImagePlan, MachOImage, PlannedMapping};
14use crate::link::DefinedSymbol;
15use crate::parse;
16use crate::rebase;
17use crate::resolve::{ResolveContext, ResolveError, resolve_install_name};
18
19/// Role of an image in the process set.
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum ImageRole {
22    /// Main `MH_EXECUTE` (always `images[0]` when mapped).
23    Main,
24    /// Mapped or skipped dylib dependency.
25    Dylib,
26}
27
28/// Why a dependency was not mapped.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub enum SkipReason {
31    /// Resolved host path does not exist (or soft-failed open).
32    MissingPath,
33    /// Absolute install name with no bottle root — never probe host FS.
34    NoBottle,
35    /// Weak load and missing / not allowlisted.
36    WeakMissing,
37    /// Already loaded under another install name / real path.
38    Duplicate,
39    /// Lazy/Upward not followed in Phase 6.
40    KindNotFollowed,
41    /// Resolved path is outside bottle ∪ executable_dir allowlist.
42    OutsideAllowlist,
43}
44
45impl SkipReason {
46    /// Stable dry-load / JSON status suffix (`skipped:<label>`).
47    #[must_use]
48    pub const fn as_str(&self) -> &'static str {
49        match self {
50            Self::MissingPath => "missing_path",
51            Self::NoBottle => "no_bottle",
52            Self::WeakMissing => "weak_missing",
53            Self::Duplicate => "duplicate",
54            Self::KindNotFollowed => "kind_not_followed",
55            Self::OutsideAllowlist => "outside_allowlist",
56        }
57    }
58}
59
60/// Mapped vs skipped status for one process image entry.
61#[derive(Debug, Clone, PartialEq, Eq)]
62pub enum ImageLoadStatus {
63    /// Image was planned and `mmap`'d.
64    Mapped,
65    /// Dependency walk soft-skipped this edge.
66    Skipped(SkipReason),
67}
68
69impl ImageLoadStatus {
70    /// Stable status string for dry-load text/JSON.
71    #[must_use]
72    pub fn as_str(&self) -> String {
73        match self {
74            Self::Mapped => "mapped".to_owned(),
75            Self::Skipped(reason) => format!("skipped:{}", reason.as_str()),
76        }
77    }
78}
79
80/// One image in the process set (mapped or skipped).
81#[derive(Debug)]
82pub struct ProcessImage {
83    /// Main vs dylib.
84    pub role: ImageRole,
85    /// Host path attempted / opened.
86    pub path: PathBuf,
87    /// Install name from the load command (or `LC_ID_DYLIB` when mapped).
88    pub install_name: String,
89    /// Map outcome.
90    pub status: ImageLoadStatus,
91    /// Present when status is [`ImageLoadStatus::Mapped`].
92    pub image: Option<MachOImage>,
93    /// Full plan when mapped; [`ImagePlan::empty`] when skipped.
94    pub plan: ImagePlan,
95    /// Guest mapping when mapped.
96    pub memory: Option<GuestMemory>,
97    /// How this edge was requested. Main uses [`DylibKind::Load`] as sentinel.
98    pub requested_kind: DylibKind,
99    /// Defined external nlist symbols (PR2; empty in PR1).
100    pub exports: Vec<DefinedSymbol>,
101}
102
103impl ProcessImage {
104    /// Slide applied to this image (0 if unmapped).
105    #[must_use]
106    pub fn slide(&self) -> u64 {
107        self.memory.as_ref().map_or(0, GuestMemory::slide)
108    }
109
110    /// Preferred base from the plan (0 if empty).
111    #[must_use]
112    pub fn preferred_base(&self) -> u64 {
113        self.plan.preferred_base
114    }
115
116    /// Region infos for dry-load (empty when skipped).
117    #[must_use]
118    pub fn region_infos(&self) -> Vec<MappedRegionInfo> {
119        let Some(memory) = self.memory.as_ref() else {
120            return Vec::new();
121        };
122        memory
123            .regions()
124            .iter()
125            .map(|r| MappedRegionInfo {
126                name: r.name.clone(),
127                guest_addr: r.guest_addr,
128                host_addr: r.host_addr(),
129                host_len: u64::try_from(r.host_len()).unwrap_or(u64::MAX),
130                vmsize: r.vmsize,
131                file_bytes: r.file_bytes,
132                prot: r.prot,
133            })
134            .collect()
135    }
136}
137
138/// Parsed + planned main image held only until [`LoadSession::map_main_only`]
139/// moves ownership into `images[0]`.
140#[derive(Debug)]
141struct StagedMain {
142    image: MachOImage,
143    plan: ImagePlan,
144}
145
146/// Configuration and state for loading one guest process image set.
147///
148/// **Ownership model:** after map, `images` is the single source of truth for
149/// parse / plan / `GuestMemory`. Before map, the main executable may live in
150/// private staging only (no duplicated top-level fields).
151#[derive(Debug)]
152pub struct LoadSession {
153    /// Path to the main executable.
154    pub executable: PathBuf,
155    /// Optional bottle root (`KAKEHASHI_ROOT` / `--root`).
156    pub root: Option<PathBuf>,
157    /// Host/guest page geometry.
158    pub pages: PageLayout,
159    /// Process image set (main at index 0 when mapped). Sole owner after map.
160    pub images: Vec<ProcessImage>,
161    /// Pre-map main parse/plan; cleared when main is pushed into `images`.
162    staged_main: Option<StagedMain>,
163}
164
165/// Result of a successful map-only (`--dry-load`) session.
166#[derive(Debug)]
167pub struct DryLoadReport {
168    /// Path that was mapped (main executable).
169    pub path: PathBuf,
170    /// Main image slide (0 if preferred base worked).
171    pub slide: u64,
172    /// Preferred base of the main image.
173    pub preferred_base: u64,
174    /// Guest page size used for planning.
175    pub guest_page_size: u32,
176    /// Host page size used for mapping.
177    pub host_page_size: u32,
178    /// Entry VA after main slide (if known).
179    pub entry: Option<u64>,
180    /// Concatenated mapped regions (all images) for simple consumers.
181    pub regions: Vec<MappedRegionInfo>,
182    /// Whether every planned segment on the main image was guest-page aligned.
183    pub fully_guest_aligned: bool,
184    /// Per-image status (mapped + skipped).
185    pub images: Vec<DryLoadImageInfo>,
186}
187
188/// One image entry in a dry-load report.
189#[derive(Debug, Clone, PartialEq, Eq)]
190pub struct DryLoadImageInfo {
191    /// `"main"` or `"dylib"`.
192    pub role: &'static str,
193    /// Host path.
194    pub path: PathBuf,
195    /// Install name.
196    pub install_name: String,
197    /// `"mapped"` or `"skipped:<reason>"`.
198    pub status: String,
199    /// Slide (0 if skipped).
200    pub slide: u64,
201    /// Preferred base (0 if skipped / empty plan).
202    pub preferred_base: u64,
203    /// Mapped regions for this image.
204    pub regions: Vec<MappedRegionInfo>,
205}
206
207/// One mapped region for CLI / JSON output.
208#[derive(Debug, Clone, PartialEq, Eq)]
209pub struct MappedRegionInfo {
210    /// Segment name.
211    pub name: String,
212    /// Guest VA after slide.
213    pub guest_addr: u64,
214    /// Host VA (identity model: equals guest when placement succeeds).
215    pub host_addr: u64,
216    /// Host mapping length.
217    pub host_len: u64,
218    /// Declared virtual size.
219    pub vmsize: u64,
220    /// File bytes copied in.
221    pub file_bytes: u64,
222    /// Darwin `initprot` bits applied.
223    pub prot: u32,
224}
225
226impl LoadSession {
227    /// Starts a session for `executable` with detected host pages and default guest size.
228    pub fn open(executable: impl Into<PathBuf>, root: Option<PathBuf>) -> Result<Self, LoadError> {
229        Self::open_with_guest(executable, root, GuestPageSize::default())
230    }
231
232    /// Starts a session with an explicit guest page policy.
233    pub fn open_with_guest(
234        executable: impl Into<PathBuf>,
235        root: Option<PathBuf>,
236        guest: GuestPageSize,
237    ) -> Result<Self, LoadError> {
238        let host = HostPageSize::detect().map_err(|err| LoadError::PageLayout(err.to_string()))?;
239        Ok(Self {
240            executable: executable.into(),
241            root,
242            pages: PageLayout::new(host, guest),
243            images: Vec::new(),
244            staged_main: None,
245        })
246    }
247
248    /// Executable path.
249    #[inline]
250    pub fn executable(&self) -> &Path {
251        &self.executable
252    }
253
254    /// All process images (mapped + skipped), main at index 0 when mapped.
255    #[must_use]
256    pub fn images(&self) -> &[ProcessImage] {
257        &self.images
258    }
259
260    /// Mutable view of images (bind / patch prep).
261    pub fn images_mut(&mut self) -> &mut [ProcessImage] {
262        &mut self.images
263    }
264
265    /// Iterator of mapped `GuestMemory` mut refs (main then dylibs, map order).
266    pub fn mapped_memories_mut(&mut self) -> impl Iterator<Item = &mut GuestMemory> {
267        self.images.iter_mut().filter_map(|img| img.memory.as_mut())
268    }
269
270    /// Parses the main executable into staged (or already mapped) state.
271    pub fn load_main_image(&mut self) -> Result<&MachOImage, LoadError> {
272        self.main_image_ref()
273    }
274
275    /// Parses (if needed) and builds an image plan for the main executable.
276    pub fn plan_main_image(&mut self) -> Result<&ImagePlan, LoadError> {
277        self.main_plan_ref()
278    }
279
280    /// Maps main only into `images = [main]` (no dependency walk).
281    ///
282    /// Unit tests / simple tooling. Production `dry_load` and `run_micro` use
283    /// [`Self::map_process`].
284    pub fn map_main_image(&mut self) -> Result<&GuestMemory, LoadError> {
285        self.map_main_only()?;
286        self.main_memory()
287            .ok_or(LoadError::NotImplemented("memory missing after map"))
288    }
289
290    /// Main image: mapped `images[0]` or staged pre-map parse.
291    fn main_image_ref(&mut self) -> Result<&MachOImage, LoadError> {
292        if self
293            .images
294            .first()
295            .and_then(|img| img.image.as_ref())
296            .is_some()
297        {
298            return self
299                .images
300                .first()
301                .and_then(|img| img.image.as_ref())
302                .ok_or(LoadError::NotImplemented("image missing after load"));
303        }
304        self.ensure_staged_main()?;
305        self.staged_main
306            .as_ref()
307            .map(|s| &s.image)
308            .ok_or(LoadError::NotImplemented("image missing after load"))
309    }
310
311    /// Main plan: mapped `images[0]` or staged pre-map plan.
312    fn main_plan_ref(&mut self) -> Result<&ImagePlan, LoadError> {
313        if self
314            .images
315            .first()
316            .is_some_and(|img| matches!(img.status, ImageLoadStatus::Mapped) && img.image.is_some())
317        {
318            return self
319                .images
320                .first()
321                .map(|img| &img.plan)
322                .ok_or(LoadError::NotImplemented("plan missing after map"));
323        }
324        self.ensure_staged_main()?;
325        self.staged_main
326            .as_ref()
327            .map(|s| &s.plan)
328            .ok_or(LoadError::NotImplemented("plan missing after load"))
329    }
330
331    /// Ensures `staged_main` holds a parse + plan for the executable.
332    fn ensure_staged_main(&mut self) -> Result<(), LoadError> {
333        if self.staged_main.is_some() {
334            return Ok(());
335        }
336        let image = parse::parse_path(&self.executable)?;
337        let plan = image.plan(self.pages.guest);
338        self.staged_main = Some(StagedMain { image, plan });
339        Ok(())
340    }
341
342    /// Map main once, BFS-load allowed dylibs, rebase pointer arrays, bind.
343    ///
344    /// Order matches a minimal dyld load sequence: map → rebase → bind.
345    ///
346    /// Bind prefers chained fixups, then classic opcodes, else nlist → `__got`.
347    /// Section rebase is skipped for images that use chained fixups.
348    pub fn map_process(&mut self) -> Result<&[ProcessImage], LoadError> {
349        self.map_main_only()?;
350        self.walk_dependencies()?;
351        let _ = rebase::rebase_process(self)?;
352        bind::bind_process(self)?;
353        Ok(self.images())
354    }
355
356    /// Maps the process image set and builds a dry-load report for the CLI.
357    pub fn dry_load(&mut self) -> Result<DryLoadReport, LoadError> {
358        let _ = self.map_process()?;
359
360        let main = self
361            .images
362            .first()
363            .ok_or(LoadError::NotImplemented("main image missing after map"))?;
364        let slide = main.slide();
365        let preferred_base = main.preferred_base();
366        let fully_guest_aligned = main.plan.fully_guest_aligned;
367        let entry = main.plan.entry.map(|e| e.wrapping_add(slide));
368        let guest_page_size = self.pages.guest_bytes();
369        let host_page_size = self.pages.host_bytes();
370        let path = self.executable.clone();
371
372        let mut regions = Vec::new();
373        let mut image_infos = Vec::with_capacity(self.images.len());
374        for img in &self.images {
375            let info_regions = img.region_infos();
376            if matches!(img.status, ImageLoadStatus::Mapped) {
377                regions.extend(info_regions.iter().cloned());
378            }
379            image_infos.push(DryLoadImageInfo {
380                role: match img.role {
381                    ImageRole::Main => "main",
382                    ImageRole::Dylib => "dylib",
383                },
384                path: img.path.clone(),
385                install_name: img.install_name.clone(),
386                status: img.status.as_str(),
387                slide: img.slide(),
388                preferred_base: img.preferred_base(),
389                regions: info_regions,
390            });
391        }
392
393        Ok(DryLoadReport {
394            path,
395            slide,
396            preferred_base,
397            guest_page_size,
398            host_page_size,
399            entry,
400            regions,
401            fully_guest_aligned,
402            images: image_infos,
403        })
404    }
405
406    /// Mutable access to main mapped memory (after map).
407    pub fn memory_mut(&mut self) -> Option<&mut GuestMemory> {
408        self.images
409            .first_mut()
410            .and_then(|main| main.memory.as_mut())
411    }
412
413    /// Guest entry VA after main slide, if known.
414    #[must_use]
415    pub fn entry_va(&self) -> Option<u64> {
416        if let Some(main) = self.images.first() {
417            let slide = main.slide();
418            return main.plan.entry.map(|e| e.wrapping_add(slide));
419        }
420        // Pre-map: preferred entry without slide (placement not yet known).
421        self.staged_main.as_ref().and_then(|s| s.plan.entry)
422    }
423
424    fn main_memory(&self) -> Option<&GuestMemory> {
425        self.images.first().and_then(|i| i.memory.as_ref())
426    }
427
428    /// Parse + plan + map main into `images[0]`; does not walk deps.
429    fn map_main_only(&mut self) -> Result<(), LoadError> {
430        // Drop previous process set (unmaps dylibs + main via GuestMemory Drop).
431        self.images.clear();
432
433        self.ensure_staged_main()?;
434        let StagedMain { image, plan } = self
435            .staged_main
436            .take()
437            .ok_or(LoadError::NotImplemented("image missing after load"))?;
438        let requests = map_requests_from_plan(&plan);
439        let preferred = plan.preferred_base;
440        let mut file = File::open(&self.executable)?;
441        let memory = GuestMemory::map_image(self.pages.host, preferred, &requests, &mut file)?;
442
443        let main = ProcessImage {
444            role: ImageRole::Main,
445            path: self.executable.clone(),
446            install_name: self.executable.display().to_string(),
447            status: ImageLoadStatus::Mapped,
448            image: Some(image),
449            plan,
450            memory: Some(memory),
451            requested_kind: DylibKind::Load,
452            exports: Vec::new(),
453        };
454        self.images.push(main);
455        Ok(())
456    }
457
458    /// BFS dependency walk (main already in `images[0]`).
459    fn walk_dependencies(&mut self) -> Result<(), LoadError> {
460        let main = self
461            .images
462            .first()
463            .ok_or(LoadError::NotImplemented("main missing before dep walk"))?;
464        let main_image = main
465            .image
466            .as_ref()
467            .ok_or(LoadError::NotImplemented("main image missing"))?
468            .clone();
469        let main_rpaths = main_image.rpaths.clone();
470        let exe_dir = self
471            .executable
472            .parent()
473            .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
474
475        let mut seen_real_paths: HashSet<PathBuf> = HashSet::new();
476        if let Some(key) = real_path_key(&self.executable) {
477            seen_real_paths.insert(key);
478        }
479
480        let mut queue: VecDeque<DepEdge> =
481            edges_from_image(&main_image, &exe_dir, &main_rpaths).into();
482
483        while let Some(edge) = queue.pop_front() {
484            let dylib_count = self
485                .images
486                .iter()
487                .filter(|i| {
488                    i.role == ImageRole::Dylib && matches!(i.status, ImageLoadStatus::Mapped)
489                })
490                .count();
491            if dylib_count >= MAX_DYLIBS {
492                return Err(LoadError::TooManyDylibs(MAX_DYLIBS));
493            }
494
495            let ctx = ResolveContext {
496                bottle_root: self.root.as_deref(),
497                executable_dir: &exe_dir,
498                loader_dir: &edge.loader_dir,
499                rpaths: &edge.rpaths,
500            };
501
502            let host_path = match resolve_install_name(&edge.install_name, &ctx) {
503                Ok(p) => p,
504                Err(ResolveError::InvalidEncoding) => {
505                    return Err(LoadError::Resolve(
506                        ResolveError::InvalidEncoding.to_string(),
507                    ));
508                }
509                Err(err) => {
510                    let reason = skip_reason_from_resolve(&err, edge.kind);
511                    self.push_skipped(
512                        edge.install_name.clone(),
513                        edge.install_name.clone(),
514                        edge.kind,
515                        reason,
516                        &err,
517                    );
518                    continue;
519                }
520            };
521
522            if !host_path.exists() {
523                let reason = if edge.kind == DylibKind::Weak {
524                    SkipReason::WeakMissing
525                } else {
526                    SkipReason::MissingPath
527                };
528                log_skip(&edge.install_name, &reason);
529                self.push_skipped_path(host_path, edge.install_name.clone(), edge.kind, reason);
530                continue;
531            }
532
533            if let Some(key) = real_path_key(&host_path)
534                && !seen_real_paths.insert(key)
535            {
536                self.push_skipped_path(
537                    host_path,
538                    edge.install_name.clone(),
539                    edge.kind,
540                    SkipReason::Duplicate,
541                );
542                continue;
543            }
544
545            let parsed = parse::parse_path(&host_path)?;
546            if parsed.summary.file_type_raw != MH_DYLIB {
547                return Err(LoadError::NotDylib(host_path.display().to_string()));
548            }
549
550            let plan = parsed.plan(self.pages.guest);
551            let requests = map_requests_from_plan(&plan);
552            let preferred = plan.preferred_base;
553            let mut file = File::open(&host_path)?;
554            let memory = GuestMemory::map_image(self.pages.host, preferred, &requests, &mut file)?;
555
556            let install = image_install_name(&parsed, &edge.install_name);
557            let loader_dir = host_path
558                .parent()
559                .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
560            let dylib_rpaths = parsed.rpaths.clone();
561            let child_rpaths = concat_rpaths(&dylib_rpaths, &main_rpaths);
562
563            tracing::info!(
564                path = %host_path.display(),
565                install_name = %install,
566                slide = memory.slide(),
567                base = preferred,
568                "mapped dylib"
569            );
570
571            let child_edges = edges_from_image(&parsed, &loader_dir, &child_rpaths);
572
573            self.images.push(ProcessImage {
574                role: ImageRole::Dylib,
575                path: host_path,
576                install_name: install,
577                status: ImageLoadStatus::Mapped,
578                image: Some(parsed),
579                plan,
580                memory: Some(memory),
581                requested_kind: edge.kind,
582                exports: Vec::new(),
583            });
584
585            for child in child_edges {
586                queue.push_back(child);
587            }
588        }
589
590        Ok(())
591    }
592
593    fn push_skipped(
594        &mut self,
595        path_display: String,
596        install_name: String,
597        kind: DylibKind,
598        reason: SkipReason,
599        err: &ResolveError,
600    ) {
601        log_skip(&install_name, &reason);
602        tracing::debug!(
603            install_name = %install_name,
604            reason = reason.as_str(),
605            resolve = %err,
606            "skipped dylib"
607        );
608        self.images.push(ProcessImage {
609            role: ImageRole::Dylib,
610            path: PathBuf::from(path_display),
611            install_name,
612            status: ImageLoadStatus::Skipped(reason),
613            image: None,
614            plan: ImagePlan::empty(),
615            memory: None,
616            requested_kind: kind,
617            exports: Vec::new(),
618        });
619    }
620
621    fn push_skipped_path(
622        &mut self,
623        path: PathBuf,
624        install_name: String,
625        kind: DylibKind,
626        reason: SkipReason,
627    ) {
628        self.images.push(ProcessImage {
629            role: ImageRole::Dylib,
630            path,
631            install_name,
632            status: ImageLoadStatus::Skipped(reason),
633            image: None,
634            plan: ImagePlan::empty(),
635            memory: None,
636            requested_kind: kind,
637            exports: Vec::new(),
638        });
639    }
640}
641
642fn skip_reason_from_resolve(err: &ResolveError, kind: DylibKind) -> SkipReason {
643    match err {
644        ResolveError::NoBottle => SkipReason::NoBottle,
645        ResolveError::OutsideAllowlist(_)
646        | ResolveError::Escape(_)
647        | ResolveError::NestedRpath
648        | ResolveError::Empty => {
649            if kind == DylibKind::Weak {
650                SkipReason::WeakMissing
651            } else {
652                SkipReason::OutsideAllowlist
653            }
654        }
655        ResolveError::InvalidEncoding => SkipReason::OutsideAllowlist,
656    }
657}
658
659fn log_skip(install_name: &str, reason: &SkipReason) {
660    let is_libsystem = install_name.contains("/usr/lib/libSystem");
661    match reason {
662        SkipReason::NoBottle | SkipReason::MissingPath if is_libsystem => {
663            tracing::debug!(install_name, reason = reason.as_str(), "skip dylib");
664        }
665        SkipReason::NoBottle
666        | SkipReason::MissingPath
667        | SkipReason::OutsideAllowlist
668        | SkipReason::WeakMissing => {
669            tracing::warn!(install_name, reason = reason.as_str(), "skip dylib");
670        }
671        SkipReason::Duplicate | SkipReason::KindNotFollowed => {
672            tracing::debug!(install_name, reason = reason.as_str(), "skip dylib");
673        }
674    }
675}
676
677fn real_path_key(path: &Path) -> Option<PathBuf> {
678    path.canonicalize().ok().or_else(|| {
679        if path.as_os_str().is_empty() {
680            None
681        } else {
682            Some(path.to_path_buf())
683        }
684    })
685}
686
687/// Builds runtime map requests from a planned image.
688#[must_use]
689pub fn map_requests_from_plan(plan: &ImagePlan) -> Vec<MapRequest> {
690    plan.mappings.iter().map(mapping_to_request).collect()
691}
692
693fn mapping_to_request(m: &PlannedMapping) -> MapRequest {
694    MapRequest {
695        name: m.name.clone(),
696        preferred_va: m.vmaddr,
697        vmsize: m.vmsize,
698        fileoff: m.fileoff,
699        filesize: m.filesize,
700        initprot: m.initprot,
701        maxprot: m.maxprot,
702    }
703}
704
705#[cfg(test)]
706#[allow(clippy::expect_used, clippy::unwrap_used)]
707mod tests {
708    use super::*;
709    use crate::fixture::minimal_arm64_execute;
710    use crate::test_util::{map_test_lock, temp_dir, write_temp_bytes, write_under};
711
712    fn write_temp_fixture() -> PathBuf {
713        write_temp_bytes("session-fixture", &minimal_arm64_execute())
714    }
715
716    #[test]
717    fn dry_load_maps_text_skips_pagezero() {
718        let _guard = map_test_lock();
719        let path = write_temp_fixture();
720        let mut session = LoadSession::open(&path, None).expect("open");
721        let report = session.dry_load().expect("dry_load");
722        assert!(
723            report.regions.iter().all(|r| r.name != "__PAGEZERO"),
724            "PAGEZERO must not be materialized"
725        );
726        assert!(
727            report.regions.iter().any(|r| r.name == "__TEXT"),
728            "expected __TEXT mapping"
729        );
730        let text = report.regions.iter().find(|r| r.name == "__TEXT").unwrap();
731        assert!(text.vmsize >= 0x1000);
732        assert!(text.file_bytes > 0);
733        assert_eq!(text.guest_addr, text.host_addr);
734        drop(session);
735        drop(std::fs::remove_file(path));
736    }
737
738    #[test]
739    fn dry_load_fat_arm64_wrapper_maps_like_thin() {
740        use crate::fixture::{minimal_arm64_execute, wrap_fat_arm64_only};
741
742        let _guard = map_test_lock();
743        let fat = wrap_fat_arm64_only(&minimal_arm64_execute());
744        let path = write_temp_bytes("fat-minimal", &fat);
745        let mut session = LoadSession::open(&path, None).expect("open fat");
746        let report = session.dry_load().expect("dry_load fat");
747        assert!(
748            report.regions.iter().any(|r| r.name == "__TEXT"),
749            "fat arm64 must map __TEXT"
750        );
751        let text = report
752            .regions
753            .iter()
754            .find(|r| r.name == "__TEXT")
755            .expect("TEXT");
756        assert!(text.file_bytes > 0, "TEXT must be filled from fat slice");
757        assert!(
758            report.images.iter().any(|i| {
759                i.role == "dylib"
760                    && i.status == "skipped:no_bottle"
761                    && i.install_name.contains("libSystem")
762            }),
763            "deps still soft-skipped without bottle: {:?}",
764            report.images
765        );
766        drop(session);
767        drop(std::fs::remove_file(path));
768    }
769
770    #[test]
771    fn minimal_fixture_skips_libsystem_no_bottle() {
772        let _guard = map_test_lock();
773        let path = write_temp_fixture();
774        let mut session = LoadSession::open(&path, None).expect("open");
775        let images = session.map_process().expect("map_process");
776        let main = images.first().expect("main image");
777        assert_eq!(main.role, ImageRole::Main);
778        assert!(matches!(main.status, ImageLoadStatus::Mapped));
779        let skipped: Vec<_> = images
780            .iter()
781            .filter(|i| matches!(i.status, ImageLoadStatus::Skipped(_)))
782            .collect();
783        assert!(
784            !skipped.is_empty(),
785            "expected at least one skipped dylib (libSystem)"
786        );
787        assert!(
788            skipped.iter().any(|i| {
789                matches!(i.status, ImageLoadStatus::Skipped(SkipReason::NoBottle))
790                    && i.install_name.contains("libSystem")
791            }),
792            "libSystem must be Skipped(NoBottle), got: {:?}",
793            skipped
794                .iter()
795                .map(|i| (&i.install_name, i.status.as_str()))
796                .collect::<Vec<_>>()
797        );
798        assert!(
799            images
800                .iter()
801                .filter(|i| matches!(i.status, ImageLoadStatus::Mapped))
802                .count()
803                == 1,
804            "only main should be mapped without bottle"
805        );
806        drop(session);
807        drop(std::fs::remove_file(path));
808    }
809
810    #[test]
811    fn map_main_image_does_not_walk_deps() {
812        let _guard = map_test_lock();
813        let path = write_temp_fixture();
814        let mut session = LoadSession::open(&path, None).expect("open");
815        let _ = session.map_main_image().expect("map_main");
816        assert_eq!(session.images().len(), 1);
817        assert_eq!(
818            session.images().first().expect("main").role,
819            ImageRole::Main
820        );
821        drop(session);
822        drop(std::fs::remove_file(path));
823    }
824
825    #[test]
826    fn dry_load_report_lists_skipped_libsystem() {
827        let _guard = map_test_lock();
828        let path = write_temp_fixture();
829        let mut session = LoadSession::open(&path, None).expect("open");
830        let report = session.dry_load().expect("dry_load");
831        assert!(
832            report.images.iter().any(|i| {
833                i.role == "dylib"
834                    && i.status == "skipped:no_bottle"
835                    && i.install_name.contains("libSystem")
836            }),
837            "dry-load images must include skipped libSystem: {:?}",
838            report.images
839        );
840        drop(session);
841        drop(std::fs::remove_file(path));
842    }
843
844    #[test]
845    fn bottle_libsystem_maps_and_binds() {
846        use crate::fixture::{
847            CALL_LIBSYSTEM_GOT_VA, KH_BOTTLE_MARK_SYMBOL, LIBSYSTEM_INSTALL_NAME,
848            arm64_libsystem_stub, call_libsystem_exit,
849        };
850
851        let _guard = map_test_lock();
852        let dir = temp_dir("bottle-session");
853        let bottle = dir.join("bottle");
854        let main_path = write_under(&dir, "call_libsystem.macho", &call_libsystem_exit());
855        let _sys_path = write_under(
856            &bottle,
857            "usr/lib/libSystem.B.dylib",
858            &arm64_libsystem_stub(),
859        );
860
861        let mut session = LoadSession::open(&main_path, Some(bottle.clone())).expect("open");
862        let report = session.dry_load().expect("dry_load with bottle");
863        assert!(
864            report.images.iter().any(|i| {
865                i.role == "dylib"
866                    && i.status == "mapped"
867                    && i.install_name == LIBSYSTEM_INSTALL_NAME
868            }),
869            "libSystem must map under bottle: {:?}",
870            report.images
871        );
872        assert!(
873            !report
874                .images
875                .iter()
876                .any(|i| i.status.starts_with("skipped:")),
877            "no skips expected when bottle has libSystem: {:?}",
878            report.images
879        );
880
881        // Re-open to re-map (dry_load already bound).
882        drop(session);
883        let mut session = LoadSession::open(&main_path, Some(bottle)).expect("reopen");
884        let _ = session.map_process().expect("map_process");
885        let main = session.images().first().expect("main");
886        let main_slide = main.slide();
887        let export_va = session
888            .images()
889            .iter()
890            .find(|i| {
891                i.role == ImageRole::Dylib
892                    && matches!(i.status, ImageLoadStatus::Mapped)
893                    && i.install_name == LIBSYSTEM_INSTALL_NAME
894            })
895            .and_then(|dylib| {
896                dylib
897                    .exports
898                    .iter()
899                    .find(|e| e.name == KH_BOTTLE_MARK_SYMBOL)
900                    .map(|e| e.value.wrapping_add(dylib.slide()))
901            })
902            .expect("libSystem export");
903
904        let got_va = CALL_LIBSYSTEM_GOT_VA.wrapping_add(main_slide);
905        let main_mem = session
906            .images()
907            .first()
908            .and_then(|i| i.memory.as_ref())
909            .expect("main mem");
910        let region = main_mem
911            .regions()
912            .iter()
913            .find(|r| got_va >= r.guest_addr && got_va < r.guest_addr.saturating_add(r.vmsize))
914            .expect("DATA region");
915        let off = usize::try_from(got_va.saturating_sub(region.guest_addr)).unwrap();
916        let end = off.saturating_add(8);
917        let bytes = region.host_bytes().get(off..end).expect("got bytes");
918        let mut le = [0_u8; 8];
919        le.copy_from_slice(bytes);
920        assert_eq!(u64::from_le_bytes(le), export_va);
921
922        drop(session);
923        drop(std::fs::remove_dir_all(dir));
924    }
925
926    #[test]
927    fn call_libsystem_without_bottle_fails_bind() {
928        use crate::error::LoadError;
929        use crate::fixture::call_libsystem_exit;
930
931        let _guard = map_test_lock();
932        let path = write_temp_bytes("call-libsys-nobottle", &call_libsystem_exit());
933        let mut session = LoadSession::open(&path, None).expect("open");
934        let err = session.map_process().expect_err("bind must fail");
935        assert!(
936            matches!(err, LoadError::UnresolvedSymbol { .. }),
937            "expected UnresolvedSymbol, got {err:?}"
938        );
939        // Soft-skip still recorded before bind fails.
940        assert!(
941            session.images().iter().any(|i| {
942                matches!(i.status, ImageLoadStatus::Skipped(SkipReason::NoBottle))
943                    && i.install_name.contains("libSystem")
944            }),
945            "libSystem should be skipped:no_bottle before bind fail: {:?}",
946            session
947                .images()
948                .iter()
949                .map(|i| (i.install_name.as_str(), i.status.as_str()))
950                .collect::<Vec<_>>()
951        );
952        drop(session);
953        drop(std::fs::remove_file(path));
954    }
955}