1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
21pub enum ImageRole {
22 Main,
24 Dylib,
26}
27
28#[derive(Debug, Clone, PartialEq, Eq)]
30pub enum SkipReason {
31 MissingPath,
33 NoBottle,
35 WeakMissing,
37 Duplicate,
39 KindNotFollowed,
41 OutsideAllowlist,
43}
44
45impl SkipReason {
46 #[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#[derive(Debug, Clone, PartialEq, Eq)]
62pub enum ImageLoadStatus {
63 Mapped,
65 Skipped(SkipReason),
67}
68
69impl ImageLoadStatus {
70 #[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#[derive(Debug)]
82pub struct ProcessImage {
83 pub role: ImageRole,
85 pub path: PathBuf,
87 pub real_path: PathBuf,
93 pub install_name: String,
95 pub status: ImageLoadStatus,
97 pub image: Option<MachOImage>,
99 pub plan: ImagePlan,
101 pub memory: Option<GuestMemory>,
103 pub requested_kind: DylibKind,
105 pub exports: Vec<DefinedSymbol>,
107}
108
109impl ProcessImage {
110 #[must_use]
112 pub fn slide(&self) -> u64 {
113 self.memory.as_ref().map_or(0, GuestMemory::slide)
114 }
115
116 #[must_use]
118 pub fn preferred_base(&self) -> u64 {
119 self.plan.preferred_base
120 }
121
122 #[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#[derive(Debug)]
147struct StagedMain {
148 image: MachOImage,
149 plan: ImagePlan,
150}
151
152#[derive(Debug)]
158pub struct LoadSession {
159 pub executable: PathBuf,
161 pub root: Option<PathBuf>,
163 pub pages: PageLayout,
165 pub images: Vec<ProcessImage>,
167 staged_main: Option<StagedMain>,
169}
170
171#[derive(Debug)]
173pub struct DryLoadReport {
174 pub path: PathBuf,
176 pub slide: u64,
178 pub preferred_base: u64,
180 pub guest_page_size: u32,
182 pub host_page_size: u32,
184 pub entry: Option<u64>,
186 pub regions: Vec<MappedRegionInfo>,
188 pub fully_guest_aligned: bool,
190 pub images: Vec<DryLoadImageInfo>,
192}
193
194#[derive(Debug, Clone, PartialEq, Eq)]
196pub struct DryLoadImageInfo {
197 pub role: &'static str,
199 pub path: PathBuf,
201 pub install_name: String,
203 pub status: String,
205 pub slide: u64,
207 pub preferred_base: u64,
209 pub regions: Vec<MappedRegionInfo>,
211}
212
213#[derive(Debug, Clone, PartialEq, Eq)]
215pub struct MappedRegionInfo {
216 pub name: String,
218 pub guest_addr: u64,
220 pub host_addr: u64,
222 pub host_len: u64,
224 pub vmsize: u64,
226 pub file_bytes: u64,
228 pub prot: u32,
230}
231
232impl LoadSession {
233 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 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 #[inline]
256 pub fn executable(&self) -> &Path {
257 &self.executable
258 }
259
260 #[must_use]
262 pub fn images(&self) -> &[ProcessImage] {
263 &self.images
264 }
265
266 pub fn images_mut(&mut self) -> &mut [ProcessImage] {
268 &mut self.images
269 }
270
271 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 pub fn load_main_image(&mut self) -> Result<&MachOImage, LoadError> {
278 self.main_image_ref()
279 }
280
281 pub fn plan_main_image(&mut self) -> Result<&ImagePlan, LoadError> {
283 self.main_plan_ref()
284 }
285
286 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 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 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 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 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 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 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 #[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 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 fn map_main_only(&mut self) -> Result<(), LoadError> {
436 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 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 lc_id = image_install_name(&parsed, &edge.install_name);
570 let install = if edge.install_name.is_empty() {
571 lc_id.clone()
572 } else {
573 edge.install_name.clone()
574 };
575 let loader_dir = host_path
576 .parent()
577 .map_or_else(|| PathBuf::from("."), Path::to_path_buf);
578 let dylib_rpaths = parsed.rpaths.clone();
579 let child_rpaths = concat_rpaths(&dylib_rpaths, &main_rpaths);
580
581 tracing::info!(
582 path = %host_path.display(),
583 install_name = %install,
584 lc_id = %lc_id,
585 slide = memory.slide(),
586 base = preferred,
587 "mapped dylib"
588 );
589
590 let child_edges = edges_from_image(&parsed, &loader_dir, &child_rpaths);
591
592 self.images.push(ProcessImage {
593 role: ImageRole::Dylib,
594 path: host_path,
595 real_path: key,
596 install_name: install,
597 status: ImageLoadStatus::Mapped,
598 image: Some(parsed),
599 plan,
600 memory: Some(memory),
601 requested_kind: edge.kind,
602 exports: Vec::new(),
603 });
604
605 for child in child_edges {
606 queue.push_back(child);
607 }
608 }
609
610 Ok(())
611 }
612
613 fn push_skipped(
614 &mut self,
615 path_display: String,
616 install_name: String,
617 kind: DylibKind,
618 reason: SkipReason,
619 err: &ResolveError,
620 ) {
621 log_skip(&install_name, &reason);
622 tracing::debug!(
623 install_name = %install_name,
624 reason = reason.as_str(),
625 resolve = %err,
626 "skipped dylib"
627 );
628 let path = PathBuf::from(path_display);
629 let real_path = real_path_key(&path).unwrap_or_else(|| path.clone());
630 self.images.push(ProcessImage {
631 role: ImageRole::Dylib,
632 path,
633 real_path,
634 install_name,
635 status: ImageLoadStatus::Skipped(reason),
636 image: None,
637 plan: ImagePlan::empty(),
638 memory: None,
639 requested_kind: kind,
640 exports: Vec::new(),
641 });
642 }
643
644 fn push_skipped_path(
645 &mut self,
646 path: PathBuf,
647 install_name: String,
648 kind: DylibKind,
649 reason: SkipReason,
650 ) {
651 let real_path = real_path_key(&path).unwrap_or_else(|| path.clone());
652 self.images.push(ProcessImage {
653 role: ImageRole::Dylib,
654 path,
655 real_path,
656 install_name,
657 status: ImageLoadStatus::Skipped(reason),
658 image: None,
659 plan: ImagePlan::empty(),
660 memory: None,
661 requested_kind: kind,
662 exports: Vec::new(),
663 });
664 }
665}
666
667fn skip_reason_from_resolve(err: &ResolveError, kind: DylibKind) -> SkipReason {
668 match err {
669 ResolveError::NoBottle => SkipReason::NoBottle,
670 ResolveError::OutsideAllowlist(_)
671 | ResolveError::Escape(_)
672 | ResolveError::NestedRpath
673 | ResolveError::Empty => {
674 if kind == DylibKind::Weak {
675 SkipReason::WeakMissing
676 } else {
677 SkipReason::OutsideAllowlist
678 }
679 }
680 ResolveError::InvalidEncoding => SkipReason::OutsideAllowlist,
681 }
682}
683
684fn log_skip(install_name: &str, reason: &SkipReason) {
685 match reason {
687 SkipReason::NoBottle
688 | SkipReason::MissingPath
689 | SkipReason::WeakMissing
690 | SkipReason::Duplicate
691 | SkipReason::KindNotFollowed => {
692 tracing::debug!(install_name, reason = reason.as_str(), "skip dylib");
693 }
694 SkipReason::OutsideAllowlist => {
695 tracing::warn!(install_name, reason = reason.as_str(), "skip dylib");
696 }
697 }
698}
699
700fn real_path_key(path: &Path) -> Option<PathBuf> {
701 path.canonicalize().ok().or_else(|| {
702 if path.as_os_str().is_empty() {
703 None
704 } else {
705 Some(path.to_path_buf())
706 }
707 })
708}
709
710#[must_use]
712pub fn map_requests_from_plan(plan: &ImagePlan) -> Vec<MapRequest> {
713 plan.mappings.iter().map(mapping_to_request).collect()
714}
715
716fn mapping_to_request(m: &PlannedMapping) -> MapRequest {
717 MapRequest {
718 name: m.name.clone(),
719 preferred_va: m.vmaddr,
720 vmsize: m.vmsize,
721 fileoff: m.fileoff,
722 filesize: m.filesize,
723 initprot: m.initprot,
724 maxprot: m.maxprot,
725 }
726}
727
728#[cfg(test)]
729#[allow(clippy::expect_used, clippy::unwrap_used)]
730mod tests {
731 use super::*;
732 use crate::fixture::minimal_arm64_execute;
733 use crate::test_util::{map_test_lock, temp_dir, write_temp_bytes, write_under};
734
735 fn write_temp_fixture() -> PathBuf {
736 write_temp_bytes("session-fixture", &minimal_arm64_execute())
737 }
738
739 #[test]
740 fn dry_load_maps_text_skips_pagezero() {
741 let _guard = map_test_lock();
742 let path = write_temp_fixture();
743 let mut session = LoadSession::open(&path, None).expect("open");
744 let report = session.dry_load().expect("dry_load");
745 assert!(
746 report.regions.iter().all(|r| r.name != "__PAGEZERO"),
747 "PAGEZERO must not be materialized"
748 );
749 assert!(
750 report.regions.iter().any(|r| r.name == "__TEXT"),
751 "expected __TEXT mapping"
752 );
753 let text = report.regions.iter().find(|r| r.name == "__TEXT").unwrap();
754 assert!(text.vmsize >= 0x1000);
755 assert!(text.file_bytes > 0);
756 assert_eq!(text.guest_addr, text.host_addr);
757 drop(session);
758 drop(std::fs::remove_file(path));
759 }
760
761 #[test]
762 fn dry_load_fat_arm64_wrapper_maps_like_thin() {
763 use crate::fixture::{minimal_arm64_execute, wrap_fat_arm64_only};
764
765 let _guard = map_test_lock();
766 let fat = wrap_fat_arm64_only(&minimal_arm64_execute());
767 let path = write_temp_bytes("fat-minimal", &fat);
768 let mut session = LoadSession::open(&path, None).expect("open fat");
769 let report = session.dry_load().expect("dry_load fat");
770 assert!(
771 report.regions.iter().any(|r| r.name == "__TEXT"),
772 "fat arm64 must map __TEXT"
773 );
774 let text = report
775 .regions
776 .iter()
777 .find(|r| r.name == "__TEXT")
778 .expect("TEXT");
779 assert!(text.file_bytes > 0, "TEXT must be filled from fat slice");
780 assert!(
781 report.images.iter().any(|i| {
782 i.role == "dylib"
783 && i.status == "skipped:no_bottle"
784 && i.install_name.contains("libSystem")
785 }),
786 "deps still soft-skipped without bottle: {:?}",
787 report.images
788 );
789 drop(session);
790 drop(std::fs::remove_file(path));
791 }
792
793 #[test]
794 fn minimal_fixture_skips_libsystem_no_bottle() {
795 let _guard = map_test_lock();
796 let path = write_temp_fixture();
797 let mut session = LoadSession::open(&path, None).expect("open");
798 let images = session.map_process().expect("map_process");
799 let main = images.first().expect("main image");
800 assert_eq!(main.role, ImageRole::Main);
801 assert!(matches!(main.status, ImageLoadStatus::Mapped));
802 let skipped: Vec<_> = images
803 .iter()
804 .filter(|i| matches!(i.status, ImageLoadStatus::Skipped(_)))
805 .collect();
806 assert!(
807 !skipped.is_empty(),
808 "expected at least one skipped dylib (libSystem)"
809 );
810 assert!(
811 skipped.iter().any(|i| {
812 matches!(i.status, ImageLoadStatus::Skipped(SkipReason::NoBottle))
813 && i.install_name.contains("libSystem")
814 }),
815 "libSystem must be Skipped(NoBottle), got: {:?}",
816 skipped
817 .iter()
818 .map(|i| (&i.install_name, i.status.as_str()))
819 .collect::<Vec<_>>()
820 );
821 assert!(
822 images
823 .iter()
824 .filter(|i| matches!(i.status, ImageLoadStatus::Mapped))
825 .count()
826 == 1,
827 "only main should be mapped without bottle"
828 );
829 drop(session);
830 drop(std::fs::remove_file(path));
831 }
832
833 #[test]
834 fn map_main_image_does_not_walk_deps() {
835 let _guard = map_test_lock();
836 let path = write_temp_fixture();
837 let mut session = LoadSession::open(&path, None).expect("open");
838 let _ = session.map_main_image().expect("map_main");
839 assert_eq!(session.images().len(), 1);
840 assert_eq!(
841 session.images().first().expect("main").role,
842 ImageRole::Main
843 );
844 drop(session);
845 drop(std::fs::remove_file(path));
846 }
847
848 #[test]
849 fn dry_load_report_lists_skipped_libsystem() {
850 let _guard = map_test_lock();
851 let path = write_temp_fixture();
852 let mut session = LoadSession::open(&path, None).expect("open");
853 let report = session.dry_load().expect("dry_load");
854 assert!(
855 report.images.iter().any(|i| {
856 i.role == "dylib"
857 && i.status == "skipped:no_bottle"
858 && i.install_name.contains("libSystem")
859 }),
860 "dry-load images must include skipped libSystem: {:?}",
861 report.images
862 );
863 drop(session);
864 drop(std::fs::remove_file(path));
865 }
866
867 #[test]
868 fn bottle_libsystem_maps_and_binds() {
869 use crate::fixture::{
870 CALL_LIBSYSTEM_GOT_VA, KH_BOTTLE_MARK_SYMBOL, LIBSYSTEM_INSTALL_NAME,
871 arm64_libsystem_stub, call_libsystem_exit,
872 };
873
874 let _guard = map_test_lock();
875 let dir = temp_dir("bottle-session");
876 let bottle = dir.join("bottle");
877 let main_path = write_under(&dir, "call_libsystem.macho", &call_libsystem_exit());
878 let _sys_path = write_under(
879 &bottle,
880 "usr/lib/libSystem.B.dylib",
881 &arm64_libsystem_stub(),
882 );
883
884 let mut session = LoadSession::open(&main_path, Some(bottle.clone())).expect("open");
885 let report = session.dry_load().expect("dry_load with bottle");
886 assert!(
887 report.images.iter().any(|i| {
888 i.role == "dylib"
889 && i.status == "mapped"
890 && i.install_name == LIBSYSTEM_INSTALL_NAME
891 }),
892 "libSystem must map under bottle: {:?}",
893 report.images
894 );
895 assert!(
896 !report
897 .images
898 .iter()
899 .any(|i| i.status.starts_with("skipped:")),
900 "no skips expected when bottle has libSystem: {:?}",
901 report.images
902 );
903
904 drop(session);
906 let mut session = LoadSession::open(&main_path, Some(bottle)).expect("reopen");
907 let _ = session.map_process().expect("map_process");
908 let main = session.images().first().expect("main");
909 let main_slide = main.slide();
910 let export_va = session
911 .images()
912 .iter()
913 .find(|i| {
914 i.role == ImageRole::Dylib
915 && matches!(i.status, ImageLoadStatus::Mapped)
916 && i.install_name == LIBSYSTEM_INSTALL_NAME
917 })
918 .and_then(|dylib| {
919 dylib
920 .exports
921 .iter()
922 .find(|e| e.name == KH_BOTTLE_MARK_SYMBOL)
923 .map(|e| e.value.wrapping_add(dylib.slide()))
924 })
925 .expect("libSystem export");
926
927 let got_va = CALL_LIBSYSTEM_GOT_VA.wrapping_add(main_slide);
928 let main_mem = session
929 .images()
930 .first()
931 .and_then(|i| i.memory.as_ref())
932 .expect("main mem");
933 let region = main_mem
934 .regions()
935 .iter()
936 .find(|r| got_va >= r.guest_addr && got_va < r.guest_addr.saturating_add(r.vmsize))
937 .expect("DATA region");
938 let off = usize::try_from(got_va.saturating_sub(region.guest_addr)).unwrap();
939 let end = off.saturating_add(8);
940 let bytes = region.host_bytes().get(off..end).expect("got bytes");
941 let mut le = [0_u8; 8];
942 le.copy_from_slice(bytes);
943 assert_eq!(u64::from_le_bytes(le), export_va);
944
945 drop(session);
946 drop(std::fs::remove_dir_all(dir));
947 }
948
949 #[test]
950 fn call_libsystem_without_bottle_fails_bind() {
951 use crate::error::LoadError;
952 use crate::fixture::call_libsystem_exit;
953
954 let _guard = map_test_lock();
955 let path = write_temp_bytes("call-libsys-nobottle", &call_libsystem_exit());
956 let mut session = LoadSession::open(&path, None).expect("open");
957 let err = session.map_process().expect_err("bind must fail");
958 assert!(
959 matches!(err, LoadError::UnresolvedSymbol { .. }),
960 "expected UnresolvedSymbol, got {err:?}"
961 );
962 assert!(
964 session.images().iter().any(|i| {
965 matches!(i.status, ImageLoadStatus::Skipped(SkipReason::NoBottle))
966 && i.install_name.contains("libSystem")
967 }),
968 "libSystem should be skipped:no_bottle before bind fail: {:?}",
969 session
970 .images()
971 .iter()
972 .map(|i| (i.install_name.as_str(), i.status.as_str()))
973 .collect::<Vec<_>>()
974 );
975 drop(session);
976 drop(std::fs::remove_file(path));
977 }
978}