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