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::{HashMap, HashSet, VecDeque};
4use std::path::{Path, PathBuf};
5
6use goblin::mach::header::MH_DYLIB;
7use kh_runtime::{GuestMemory, GuestPageSize, HostPageSize, MapRequest, PageLayout};
8
9use crate::bind;
10use crate::deps::{DepEdge, MAX_DYLIBS, concat_rpaths, edges_from_image, image_install_name};
11use crate::error::LoadError;
12use crate::image::{DylibKind, ImagePlan, MachOImage, PlannedMapping};
13use crate::link::DefinedSymbol;
14use crate::parse;
15use crate::rebase;
16use crate::resolve::{ResolveContext, ResolveError, resolve_install_name};
17
18/// Role of an image in the process set.
19#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum ImageRole {
21    /// Main `MH_EXECUTE` (always `images[0]` when mapped).
22    Main,
23    /// Mapped or skipped dylib dependency.
24    Dylib,
25}
26
27/// Why a dependency was not mapped.
28#[derive(Debug, Clone, PartialEq, Eq)]
29pub enum SkipReason {
30    /// Resolved host path does not exist (or soft-failed open).
31    MissingPath,
32    /// Absolute install name with no bottle root — never probe host FS.
33    NoBottle,
34    /// Weak load and missing / not allowlisted.
35    WeakMissing,
36    /// Already loaded under another install name / real path.
37    Duplicate,
38    /// Lazy/Upward not followed in Phase 6.
39    KindNotFollowed,
40    /// Resolved path is outside bottle ∪ executable_dir allowlist.
41    OutsideAllowlist,
42}
43
44impl SkipReason {
45    /// Stable dry-load / JSON status suffix (`skipped:<label>`).
46    #[must_use]
47    pub const fn as_str(&self) -> &'static str {
48        match self {
49            Self::MissingPath => "missing_path",
50            Self::NoBottle => "no_bottle",
51            Self::WeakMissing => "weak_missing",
52            Self::Duplicate => "duplicate",
53            Self::KindNotFollowed => "kind_not_followed",
54            Self::OutsideAllowlist => "outside_allowlist",
55        }
56    }
57}
58
59/// Mapped vs skipped status for one process image entry.
60#[derive(Debug, Clone, PartialEq, Eq)]
61pub enum ImageLoadStatus {
62    /// Image was planned and `mmap`'d.
63    Mapped,
64    /// Dependency walk soft-skipped this edge.
65    Skipped(SkipReason),
66}
67
68impl ImageLoadStatus {
69    /// Stable status string for dry-load text/JSON.
70    #[must_use]
71    pub fn as_str(&self) -> String {
72        match self {
73            Self::Mapped => "mapped".to_owned(),
74            Self::Skipped(reason) => format!("skipped:{}", reason.as_str()),
75        }
76    }
77}
78
79/// One image in the process set (mapped or skipped).
80#[derive(Debug)]
81pub struct ProcessImage {
82    /// Main vs dylib.
83    pub role: ImageRole,
84    /// Host path attempted / opened.
85    pub path: PathBuf,
86    /// Canonical (or best-effort absolute) path, computed **once** at insert.
87    ///
88    /// Used for duplicate detection and bottle alias matching (`libc++` →
89    /// `libSystem`) without re-running `canonicalize` / `readlinkat` on every
90    /// bind site (roadmap A4).
91    pub real_path: PathBuf,
92    /// Install name from the load command (or `LC_ID_DYLIB` when mapped).
93    pub install_name: String,
94    /// Map outcome.
95    pub status: ImageLoadStatus,
96    /// Present when status is [`ImageLoadStatus::Mapped`].
97    pub image: Option<MachOImage>,
98    /// Full plan when mapped; [`ImagePlan::empty`] when skipped.
99    pub plan: ImagePlan,
100    /// Guest mapping when mapped.
101    pub memory: Option<GuestMemory>,
102    /// How this edge was requested. Main uses [`DylibKind::Load`] as sentinel.
103    pub requested_kind: DylibKind,
104    /// Defined external nlist symbols (PR2; empty in PR1).
105    pub exports: Vec<DefinedSymbol>,
106    /// Preferred-VA index of [`Self::exports`] for O(1) bind / chained resolve.
107    ///
108    /// Built in `fill_exports` (same pass as the nlist scan). Includes the
109    /// `dyld_stub_binder` → `_dyld_stub_binder` alias when present.
110    pub export_by_name: HashMap<String, u64>,
111    /// Full on-disk container from the first parse (`mmap` preferred).
112    ///
113    /// Reused for (1) segment fill without a second disk pass and (2) bind /
114    /// chained fixups (arm64 thin view). Any guest benefits — not tool-specific.
115    /// Taken/dropped during bind after use.
116    pub file_bytes: Option<crate::FileImage>,
117}
118
119impl ProcessImage {
120    /// Slide applied to this image (0 if unmapped).
121    #[must_use]
122    pub fn slide(&self) -> u64 {
123        self.memory.as_ref().map_or(0, GuestMemory::slide)
124    }
125
126    /// Preferred base from the plan (0 if empty).
127    #[must_use]
128    pub fn preferred_base(&self) -> u64 {
129        self.plan.preferred_base
130    }
131
132    /// Region infos for dry-load (empty when skipped).
133    #[must_use]
134    pub fn region_infos(&self) -> Vec<MappedRegionInfo> {
135        let Some(memory) = self.memory.as_ref() else {
136            return Vec::new();
137        };
138        memory
139            .regions()
140            .iter()
141            .map(|r| MappedRegionInfo {
142                name: r.name.clone(),
143                guest_addr: r.guest_addr,
144                host_addr: r.host_addr(),
145                host_len: u64::try_from(r.host_len()).unwrap_or(u64::MAX),
146                vmsize: r.vmsize,
147                file_bytes: r.file_bytes,
148                prot: r.prot,
149            })
150            .collect()
151    }
152}
153
154/// Parsed + planned main image held only until [`LoadSession::map_main_only`]
155/// moves ownership into `images[0]`.
156#[derive(Debug)]
157struct StagedMain {
158    image: MachOImage,
159    plan: ImagePlan,
160    /// Full container (fat or thin) from `parse_path_with_bytes`.
161    file_bytes: crate::FileImage,
162}
163
164/// Configuration and state for loading one guest process image set.
165///
166/// **Ownership model:** after map, `images` is the single source of truth for
167/// parse / plan / `GuestMemory`. Before map, the main executable may live in
168/// private staging only (no duplicated top-level fields).
169#[derive(Debug)]
170pub struct LoadSession {
171    /// Path to the main executable.
172    pub executable: PathBuf,
173    /// Optional bottle root (`KAKEHASHI_ROOT` / `--root`).
174    pub root: Option<PathBuf>,
175    /// Host/guest page geometry.
176    pub pages: PageLayout,
177    /// Process image set (main at index 0 when mapped). Sole owner after map.
178    pub images: Vec<ProcessImage>,
179    /// Pre-map main parse/plan; cleared when main is pushed into `images`.
180    staged_main: Option<StagedMain>,
181}
182
183/// Result of a successful map-only (`--dry-load`) session.
184#[derive(Debug)]
185pub struct DryLoadReport {
186    /// Path that was mapped (main executable).
187    pub path: PathBuf,
188    /// Main image slide (0 if preferred base worked).
189    pub slide: u64,
190    /// Preferred base of the main image.
191    pub preferred_base: u64,
192    /// Guest page size used for planning.
193    pub guest_page_size: u32,
194    /// Host page size used for mapping.
195    pub host_page_size: u32,
196    /// Entry VA after main slide (if known).
197    pub entry: Option<u64>,
198    /// Concatenated mapped regions (all images) for simple consumers.
199    pub regions: Vec<MappedRegionInfo>,
200    /// Whether every planned segment on the main image was guest-page aligned.
201    pub fully_guest_aligned: bool,
202    /// Per-image status (mapped + skipped).
203    pub images: Vec<DryLoadImageInfo>,
204}
205
206/// One image entry in a dry-load report.
207#[derive(Debug, Clone, PartialEq, Eq)]
208pub struct DryLoadImageInfo {
209    /// `"main"` or `"dylib"`.
210    pub role: &'static str,
211    /// Host path.
212    pub path: PathBuf,
213    /// Install name.
214    pub install_name: String,
215    /// `"mapped"` or `"skipped:<reason>"`.
216    pub status: String,
217    /// Slide (0 if skipped).
218    pub slide: u64,
219    /// Preferred base (0 if skipped / empty plan).
220    pub preferred_base: u64,
221    /// Mapped regions for this image.
222    pub regions: Vec<MappedRegionInfo>,
223}
224
225/// One mapped region for CLI / JSON output.
226#[derive(Debug, Clone, PartialEq, Eq)]
227pub struct MappedRegionInfo {
228    /// Segment name.
229    pub name: String,
230    /// Guest VA after slide.
231    pub guest_addr: u64,
232    /// Host VA (identity model: equals guest when placement succeeds).
233    pub host_addr: u64,
234    /// Host mapping length.
235    pub host_len: u64,
236    /// Declared virtual size.
237    pub vmsize: u64,
238    /// File bytes copied in.
239    pub file_bytes: u64,
240    /// Darwin `initprot` bits applied.
241    pub prot: u32,
242}
243
244impl LoadSession {
245    /// Starts a session for `executable` with detected host pages and default guest size.
246    pub fn open(executable: impl Into<PathBuf>, root: Option<PathBuf>) -> Result<Self, LoadError> {
247        Self::open_with_guest(executable, root, GuestPageSize::default())
248    }
249
250    /// Starts a session with an explicit guest page policy.
251    pub fn open_with_guest(
252        executable: impl Into<PathBuf>,
253        root: Option<PathBuf>,
254        guest: GuestPageSize,
255    ) -> Result<Self, LoadError> {
256        let host = HostPageSize::detect().map_err(|err| LoadError::PageLayout(err.to_string()))?;
257        Ok(Self {
258            executable: executable.into(),
259            root,
260            pages: PageLayout::new(host, guest),
261            images: Vec::new(),
262            staged_main: None,
263        })
264    }
265
266    /// Executable path.
267    #[inline]
268    pub fn executable(&self) -> &Path {
269        &self.executable
270    }
271
272    /// All process images (mapped + skipped), main at index 0 when mapped.
273    #[must_use]
274    pub fn images(&self) -> &[ProcessImage] {
275        &self.images
276    }
277
278    /// Mutable view of images (bind / patch prep).
279    pub fn images_mut(&mut self) -> &mut [ProcessImage] {
280        &mut self.images
281    }
282
283    /// Iterator of mapped `GuestMemory` mut refs (main then dylibs, map order).
284    pub fn mapped_memories_mut(&mut self) -> impl Iterator<Item = &mut GuestMemory> {
285        self.images.iter_mut().filter_map(|img| img.memory.as_mut())
286    }
287
288    /// Parses the main executable into staged (or already mapped) state.
289    pub fn load_main_image(&mut self) -> Result<&MachOImage, LoadError> {
290        self.main_image_ref()
291    }
292
293    /// Parses (if needed) and builds an image plan for the main executable.
294    pub fn plan_main_image(&mut self) -> Result<&ImagePlan, LoadError> {
295        self.main_plan_ref()
296    }
297
298    /// Maps main only into `images = [main]` (no dependency walk).
299    ///
300    /// Unit tests / simple tooling. Production `dry_load` and `run_micro` use
301    /// [`Self::map_process`].
302    pub fn map_main_image(&mut self) -> Result<&GuestMemory, LoadError> {
303        self.map_main_only()?;
304        self.main_memory()
305            .ok_or(LoadError::NotImplemented("memory missing after map"))
306    }
307
308    /// Main image: mapped `images[0]` or staged pre-map parse.
309    fn main_image_ref(&mut self) -> Result<&MachOImage, LoadError> {
310        if self
311            .images
312            .first()
313            .and_then(|img| img.image.as_ref())
314            .is_some()
315        {
316            return self
317                .images
318                .first()
319                .and_then(|img| img.image.as_ref())
320                .ok_or(LoadError::NotImplemented("image missing after load"));
321        }
322        self.ensure_staged_main()?;
323        self.staged_main
324            .as_ref()
325            .map(|s| &s.image)
326            .ok_or(LoadError::NotImplemented("image missing after load"))
327    }
328
329    /// Main plan: mapped `images[0]` or staged pre-map plan.
330    fn main_plan_ref(&mut self) -> Result<&ImagePlan, LoadError> {
331        if self
332            .images
333            .first()
334            .is_some_and(|img| matches!(img.status, ImageLoadStatus::Mapped) && img.image.is_some())
335        {
336            return self
337                .images
338                .first()
339                .map(|img| &img.plan)
340                .ok_or(LoadError::NotImplemented("plan missing after map"));
341        }
342        self.ensure_staged_main()?;
343        self.staged_main
344            .as_ref()
345            .map(|s| &s.plan)
346            .ok_or(LoadError::NotImplemented("plan missing after load"))
347    }
348
349    /// Ensures `staged_main` holds a parse + plan for the executable.
350    fn ensure_staged_main(&mut self) -> Result<(), LoadError> {
351        if self.staged_main.is_some() {
352            return Ok(());
353        }
354        let (image, file_bytes) = parse::parse_path_with_bytes(&self.executable)?;
355        let plan = image.plan(self.pages.guest);
356        self.staged_main = Some(StagedMain {
357            image,
358            plan,
359            file_bytes,
360        });
361        Ok(())
362    }
363
364    /// Map main once, BFS-load allowed dylibs, rebase pointer arrays, bind.
365    ///
366    /// Order matches a minimal dyld load sequence: map → rebase → bind.
367    ///
368    /// Bind prefers chained fixups, then classic opcodes, else nlist → `__got`.
369    /// Section rebase is skipped for images that use chained fixups.
370    pub fn map_process(&mut self) -> Result<&[ProcessImage], LoadError> {
371        // parse_main + mmap_main recorded inside map_main_only when timing is on.
372        self.map_main_only()?;
373        crate::load_timing::time_result("walk_deps", || self.walk_dependencies())?;
374        let _ = crate::load_timing::time_result("rebase", || rebase::rebase_process(self))?;
375        // bind records sub-phases (fill_exports / chained|sites / apply).
376        bind::bind_process(self)?;
377        if crate::load_timing::enabled() {
378            let mapped = self
379                .images
380                .iter()
381                .filter(|i| matches!(i.status, ImageLoadStatus::Mapped))
382                .count();
383            let skipped = self.images.len().saturating_sub(mapped);
384            let mut file_bytes: u64 = 0;
385            for img in &self.images {
386                if !matches!(img.status, ImageLoadStatus::Mapped) {
387                    continue;
388                }
389                if let Ok(meta) = std::fs::metadata(&img.path) {
390                    file_bytes = file_bytes.saturating_add(meta.len());
391                }
392            }
393            crate::load_timing::note(format!(
394                "images mapped={mapped} skipped={skipped} file_bytes={file_bytes}"
395            ));
396            for img in &self.images {
397                if matches!(img.status, ImageLoadStatus::Mapped) {
398                    let sz = std::fs::metadata(&img.path).map_or(0, |m| m.len());
399                    crate::load_timing::note(format!(
400                        "  {}  bytes={sz}  {}",
401                        match img.role {
402                            ImageRole::Main => "main ",
403                            ImageRole::Dylib => "dylib",
404                        },
405                        img.path.display()
406                    ));
407                }
408            }
409        }
410        Ok(self.images())
411    }
412
413    /// Maps the process image set and builds a dry-load report for the CLI.
414    pub fn dry_load(&mut self) -> Result<DryLoadReport, LoadError> {
415        let _ = self.map_process()?;
416
417        let main = self
418            .images
419            .first()
420            .ok_or(LoadError::NotImplemented("main image missing after map"))?;
421        let slide = main.slide();
422        let preferred_base = main.preferred_base();
423        let fully_guest_aligned = main.plan.fully_guest_aligned;
424        let entry = main.plan.entry.map(|e| e.wrapping_add(slide));
425        let guest_page_size = self.pages.guest_bytes();
426        let host_page_size = self.pages.host_bytes();
427        let path = self.executable.clone();
428
429        let mut regions = Vec::new();
430        let mut image_infos = Vec::with_capacity(self.images.len());
431        for img in &self.images {
432            let info_regions = img.region_infos();
433            if matches!(img.status, ImageLoadStatus::Mapped) {
434                regions.extend(info_regions.iter().cloned());
435            }
436            image_infos.push(DryLoadImageInfo {
437                role: match img.role {
438                    ImageRole::Main => "main",
439                    ImageRole::Dylib => "dylib",
440                },
441                path: img.path.clone(),
442                install_name: img.install_name.clone(),
443                status: img.status.as_str(),
444                slide: img.slide(),
445                preferred_base: img.preferred_base(),
446                regions: info_regions,
447            });
448        }
449
450        Ok(DryLoadReport {
451            path,
452            slide,
453            preferred_base,
454            guest_page_size,
455            host_page_size,
456            entry,
457            regions,
458            fully_guest_aligned,
459            images: image_infos,
460        })
461    }
462
463    /// Mutable access to main mapped memory (after map).
464    pub fn memory_mut(&mut self) -> Option<&mut GuestMemory> {
465        self.images
466            .first_mut()
467            .and_then(|main| main.memory.as_mut())
468    }
469
470    /// Guest entry VA after main slide, if known.
471    #[must_use]
472    pub fn entry_va(&self) -> Option<u64> {
473        if let Some(main) = self.images.first() {
474            let slide = main.slide();
475            return main.plan.entry.map(|e| e.wrapping_add(slide));
476        }
477        // Pre-map: preferred entry without slide (placement not yet known).
478        self.staged_main.as_ref().and_then(|s| s.plan.entry)
479    }
480
481    fn main_memory(&self) -> Option<&GuestMemory> {
482        self.images.first().and_then(|i| i.memory.as_ref())
483    }
484
485    /// Parse + plan + map main into `images[0]`; does not walk deps.
486    fn map_main_only(&mut self) -> Result<(), LoadError> {
487        // Drop previous process set (unmaps dylibs + main via GuestMemory Drop).
488        self.images.clear();
489
490        crate::load_timing::time_result("parse_main", || self.ensure_staged_main())?;
491        let StagedMain {
492            image,
493            plan,
494            file_bytes,
495        } = self
496            .staged_main
497            .take()
498            .ok_or(LoadError::NotImplemented("image missing after load"))?;
499        let requests = map_requests_from_plan(&plan);
500        let preferred = plan.preferred_base;
501        // Prefer path/`File` map so host-page-aligned interiors use file-backed
502        // `MAP_PRIVATE` (no full-TEXT memcpy). `file_bytes` stays for bind.
503        let memory = crate::load_timing::time_result("mmap_main", || {
504            let mut file = std::fs::File::open(&self.executable)?;
505            GuestMemory::map_image(self.pages.host, preferred, &requests, &mut file)
506                .map_err(LoadError::from)
507        })?;
508
509        let main = ProcessImage {
510            role: ImageRole::Main,
511            path: self.executable.clone(),
512            real_path: real_path_key(&self.executable).unwrap_or_else(|| self.executable.clone()),
513            install_name: self.executable.display().to_string(),
514            status: ImageLoadStatus::Mapped,
515            image: Some(image),
516            plan,
517            memory: Some(memory),
518            requested_kind: DylibKind::Load,
519            exports: Vec::new(),
520            export_by_name: HashMap::new(),
521            file_bytes: Some(file_bytes),
522        };
523        self.images.push(main);
524        Ok(())
525    }
526
527    /// BFS dependency walk (main already in `images[0]`).
528    fn walk_dependencies(&mut self) -> Result<(), LoadError> {
529        let main = self
530            .images
531            .first()
532            .ok_or(LoadError::NotImplemented("main missing before dep walk"))?;
533        let main_image = main
534            .image
535            .as_ref()
536            .ok_or(LoadError::NotImplemented("main image missing"))?
537            .clone();
538        let main_rpaths = main_image.rpaths.clone();
539        let exe_dir = self
540            .executable
541            .parent()
542            .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
543
544        let mut seen_real_paths: HashSet<PathBuf> = HashSet::new();
545        if let Some(key) = real_path_key(&self.executable) {
546            seen_real_paths.insert(key);
547        }
548
549        let mut queue: VecDeque<DepEdge> =
550            edges_from_image(&main_image, &exe_dir, &main_rpaths).into();
551
552        while let Some(edge) = queue.pop_front() {
553            let dylib_count = self
554                .images
555                .iter()
556                .filter(|i| {
557                    i.role == ImageRole::Dylib && matches!(i.status, ImageLoadStatus::Mapped)
558                })
559                .count();
560            if dylib_count >= MAX_DYLIBS {
561                return Err(LoadError::TooManyDylibs(MAX_DYLIBS));
562            }
563
564            let ctx = ResolveContext {
565                bottle_root: self.root.as_deref(),
566                executable_dir: &exe_dir,
567                loader_dir: &edge.loader_dir,
568                rpaths: &edge.rpaths,
569            };
570
571            let host_path = match resolve_install_name(&edge.install_name, &ctx) {
572                Ok(p) => p,
573                Err(ResolveError::InvalidEncoding) => {
574                    return Err(LoadError::Resolve(
575                        ResolveError::InvalidEncoding.to_string(),
576                    ));
577                }
578                Err(err) => {
579                    let reason = skip_reason_from_resolve(&err, edge.kind);
580                    self.push_skipped(
581                        edge.install_name.clone(),
582                        edge.install_name.clone(),
583                        edge.kind,
584                        reason,
585                        &err,
586                    );
587                    continue;
588                }
589            };
590
591            if !host_path.exists() {
592                let reason = if edge.kind == DylibKind::Weak {
593                    SkipReason::WeakMissing
594                } else {
595                    SkipReason::MissingPath
596                };
597                log_skip(&edge.install_name, &reason);
598                self.push_skipped_path(host_path, edge.install_name.clone(), edge.kind, reason);
599                continue;
600            }
601
602            let key = real_path_key(&host_path).unwrap_or_else(|| host_path.clone());
603            if !seen_real_paths.insert(key.clone()) {
604                self.push_skipped_path(
605                    host_path,
606                    edge.install_name.clone(),
607                    edge.kind,
608                    SkipReason::Duplicate,
609                );
610                continue;
611            }
612
613            let (parsed, file_bytes) = parse::parse_path_with_bytes(&host_path)?;
614            if parsed.summary.file_type_raw != MH_DYLIB {
615                return Err(LoadError::NotDylib(host_path.display().to_string()));
616            }
617
618            let plan = parsed.plan(self.pages.guest);
619            let requests = map_requests_from_plan(&plan);
620            let preferred = plan.preferred_base;
621            let memory = {
622                let mut file = std::fs::File::open(&host_path)?;
623                GuestMemory::map_image(self.pages.host, preferred, &requests, &mut file)?
624            };
625
626            // Prefer the **LC_LOAD** install name (`edge.install_name`) over the
627            // dylib's LC_ID. Bottle aliases (`libc++.1.dylib` / `libcurl.4.dylib`
628            // → freestanding `libSystem.B.dylib`) share one real file whose LC_ID
629            // is always `/usr/lib/libSystem.B.dylib`. Two-level binds use the
630            // consumer's LC_LOAD string as the ordinal target, so the mapped
631            // image must be findable under that name (see `find_mapped_by_install_name`
632            // + duplicate real_path alias for the true libSystem edge).
633            let lc_id = image_install_name(&parsed, &edge.install_name);
634            let install = if edge.install_name.is_empty() {
635                lc_id.clone()
636            } else {
637                edge.install_name.clone()
638            };
639            let loader_dir = host_path
640                .parent()
641                .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
642            let dylib_rpaths = parsed.rpaths.clone();
643            let child_rpaths = concat_rpaths(&dylib_rpaths, &main_rpaths);
644
645            tracing::info!(
646                path = %host_path.display(),
647                install_name = %install,
648                lc_id = %lc_id,
649                slide = memory.slide(),
650                base = preferred,
651                "mapped dylib"
652            );
653
654            let child_edges = edges_from_image(&parsed, &loader_dir, &child_rpaths);
655
656            self.images.push(ProcessImage {
657                role: ImageRole::Dylib,
658                path: host_path,
659                real_path: key,
660                install_name: install,
661                status: ImageLoadStatus::Mapped,
662                image: Some(parsed),
663                plan,
664                memory: Some(memory),
665                requested_kind: edge.kind,
666                exports: Vec::new(),
667                export_by_name: HashMap::new(),
668                file_bytes: Some(file_bytes),
669            });
670
671            for child in child_edges {
672                queue.push_back(child);
673            }
674        }
675
676        Ok(())
677    }
678
679    fn push_skipped(
680        &mut self,
681        path_display: String,
682        install_name: String,
683        kind: DylibKind,
684        reason: SkipReason,
685        err: &ResolveError,
686    ) {
687        log_skip(&install_name, &reason);
688        tracing::debug!(
689            install_name = %install_name,
690            reason = reason.as_str(),
691            resolve = %err,
692            "skipped dylib"
693        );
694        let path = PathBuf::from(path_display);
695        let real_path = real_path_key(&path).unwrap_or_else(|| path.clone());
696        self.images.push(ProcessImage {
697            role: ImageRole::Dylib,
698            path,
699            real_path,
700            install_name,
701            status: ImageLoadStatus::Skipped(reason),
702            image: None,
703            plan: ImagePlan::empty(),
704            memory: None,
705            requested_kind: kind,
706            exports: Vec::new(),
707            export_by_name: HashMap::new(),
708            file_bytes: None,
709        });
710    }
711
712    fn push_skipped_path(
713        &mut self,
714        path: PathBuf,
715        install_name: String,
716        kind: DylibKind,
717        reason: SkipReason,
718    ) {
719        let real_path = real_path_key(&path).unwrap_or_else(|| path.clone());
720        self.images.push(ProcessImage {
721            role: ImageRole::Dylib,
722            path,
723            real_path,
724            install_name,
725            status: ImageLoadStatus::Skipped(reason),
726            image: None,
727            plan: ImagePlan::empty(),
728            memory: None,
729            requested_kind: kind,
730            exports: Vec::new(),
731            export_by_name: HashMap::new(),
732            file_bytes: None,
733        });
734    }
735}
736
737fn skip_reason_from_resolve(err: &ResolveError, kind: DylibKind) -> SkipReason {
738    match err {
739        ResolveError::NoBottle => SkipReason::NoBottle,
740        ResolveError::OutsideAllowlist(_)
741        | ResolveError::Escape(_)
742        | ResolveError::NestedRpath
743        | ResolveError::Empty => {
744            if kind == DylibKind::Weak {
745                SkipReason::WeakMissing
746            } else {
747                SkipReason::OutsideAllowlist
748            }
749        }
750        ResolveError::InvalidEncoding => SkipReason::OutsideAllowlist,
751    }
752}
753
754fn log_skip(install_name: &str, reason: &SkipReason) {
755    // Expected soft skips (CF/libz/libiconv/…) are debug; only odd failures stay warn.
756    match reason {
757        SkipReason::NoBottle
758        | SkipReason::MissingPath
759        | SkipReason::WeakMissing
760        | SkipReason::Duplicate
761        | SkipReason::KindNotFollowed => {
762            tracing::debug!(install_name, reason = reason.as_str(), "skip dylib");
763        }
764        SkipReason::OutsideAllowlist => {
765            tracing::warn!(install_name, reason = reason.as_str(), "skip dylib");
766        }
767    }
768}
769
770fn real_path_key(path: &Path) -> Option<PathBuf> {
771    path.canonicalize().ok().or_else(|| {
772        if path.as_os_str().is_empty() {
773            None
774        } else {
775            Some(path.to_path_buf())
776        }
777    })
778}
779
780/// Builds runtime map requests from a planned image.
781#[must_use]
782pub fn map_requests_from_plan(plan: &ImagePlan) -> Vec<MapRequest> {
783    plan.mappings.iter().map(mapping_to_request).collect()
784}
785
786fn mapping_to_request(m: &PlannedMapping) -> MapRequest {
787    MapRequest {
788        name: m.name.clone(),
789        preferred_va: m.vmaddr,
790        vmsize: m.vmsize,
791        fileoff: m.fileoff,
792        filesize: m.filesize,
793        initprot: m.initprot,
794        maxprot: m.maxprot,
795        svc_scan_ranges: m.svc_scan_ranges.clone(),
796    }
797}