1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum ImageRole {
21 Main,
23 Dylib,
25}
26
27#[derive(Debug, Clone, PartialEq, Eq)]
29pub enum SkipReason {
30 MissingPath,
32 NoBottle,
34 WeakMissing,
36 Duplicate,
38 KindNotFollowed,
40 OutsideAllowlist,
42}
43
44impl SkipReason {
45 #[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#[derive(Debug, Clone, PartialEq, Eq)]
61pub enum ImageLoadStatus {
62 Mapped,
64 Skipped(SkipReason),
66}
67
68impl ImageLoadStatus {
69 #[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#[derive(Debug)]
81pub struct ProcessImage {
82 pub role: ImageRole,
84 pub path: PathBuf,
86 pub real_path: PathBuf,
92 pub install_name: String,
94 pub status: ImageLoadStatus,
96 pub image: Option<MachOImage>,
98 pub plan: ImagePlan,
100 pub memory: Option<GuestMemory>,
102 pub requested_kind: DylibKind,
104 pub exports: Vec<DefinedSymbol>,
106 pub export_by_name: HashMap<String, u64>,
111 pub file_bytes: Option<crate::FileImage>,
117}
118
119impl ProcessImage {
120 #[must_use]
122 pub fn slide(&self) -> u64 {
123 self.memory.as_ref().map_or(0, GuestMemory::slide)
124 }
125
126 #[must_use]
128 pub fn preferred_base(&self) -> u64 {
129 self.plan.preferred_base
130 }
131
132 #[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#[derive(Debug)]
157struct StagedMain {
158 image: MachOImage,
159 plan: ImagePlan,
160 file_bytes: crate::FileImage,
162}
163
164#[derive(Debug)]
170pub struct LoadSession {
171 pub executable: PathBuf,
173 pub root: Option<PathBuf>,
175 pub pages: PageLayout,
177 pub images: Vec<ProcessImage>,
179 staged_main: Option<StagedMain>,
181}
182
183#[derive(Debug)]
185pub struct DryLoadReport {
186 pub path: PathBuf,
188 pub slide: u64,
190 pub preferred_base: u64,
192 pub guest_page_size: u32,
194 pub host_page_size: u32,
196 pub entry: Option<u64>,
198 pub regions: Vec<MappedRegionInfo>,
200 pub fully_guest_aligned: bool,
202 pub images: Vec<DryLoadImageInfo>,
204}
205
206#[derive(Debug, Clone, PartialEq, Eq)]
208pub struct DryLoadImageInfo {
209 pub role: &'static str,
211 pub path: PathBuf,
213 pub install_name: String,
215 pub status: String,
217 pub slide: u64,
219 pub preferred_base: u64,
221 pub regions: Vec<MappedRegionInfo>,
223}
224
225#[derive(Debug, Clone, PartialEq, Eq)]
227pub struct MappedRegionInfo {
228 pub name: String,
230 pub guest_addr: u64,
232 pub host_addr: u64,
234 pub host_len: u64,
236 pub vmsize: u64,
238 pub file_bytes: u64,
240 pub prot: u32,
242}
243
244impl LoadSession {
245 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 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 #[inline]
268 pub fn executable(&self) -> &Path {
269 &self.executable
270 }
271
272 #[must_use]
274 pub fn images(&self) -> &[ProcessImage] {
275 &self.images
276 }
277
278 pub fn images_mut(&mut self) -> &mut [ProcessImage] {
280 &mut self.images
281 }
282
283 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 pub fn load_main_image(&mut self) -> Result<&MachOImage, LoadError> {
290 self.main_image_ref()
291 }
292
293 pub fn plan_main_image(&mut self) -> Result<&ImagePlan, LoadError> {
295 self.main_plan_ref()
296 }
297
298 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 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 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 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 pub fn map_process(&mut self) -> Result<&[ProcessImage], LoadError> {
371 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::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 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 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 #[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 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 fn map_main_only(&mut self) -> Result<(), LoadError> {
487 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 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 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 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 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#[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}