1use core::fmt;
4
5if_std! {
6 use std::fs::File;
7 use std::io::{self, Read};
8}
9
10use crate::error;
11use crate::mach::constants::cputype::{CPU_ARCH_ABI64, CPU_SUBTYPE_MASK, CpuSubType, CpuType};
12use scroll::{Pread, Pwrite, SizeWith};
13
14pub const FAT_MAGIC: u32 = 0xcafe_babe;
15pub const FAT_CIGAM: u32 = 0xbeba_feca;
16
17#[repr(C)]
18#[derive(Clone, Copy, Default, Pread, Pwrite, SizeWith)]
19pub struct FatHeader {
21 pub magic: u32,
23 pub nfat_arch: u32,
25}
26
27pub const SIZEOF_FAT_HEADER: usize = 8;
28
29impl fmt::Debug for FatHeader {
30 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
31 f.debug_struct("FatHeader")
32 .field("magic", &format_args!("0x{:x}", self.magic))
33 .field("nfat_arch", &self.nfat_arch)
34 .finish()
35 }
36}
37
38impl FatHeader {
39 pub fn from_bytes(bytes: [u8; SIZEOF_FAT_HEADER]) -> FatHeader {
41 let mut offset = 0;
42 let magic = bytes.gread_with(&mut offset, scroll::BE).unwrap();
43 let nfat_arch = bytes.gread_with(&mut offset, scroll::BE).unwrap();
44 FatHeader { magic, nfat_arch }
45 }
46
47 #[cfg(feature = "std")]
49 pub fn from_fd(fd: &mut File) -> io::Result<FatHeader> {
50 let mut header = [0; SIZEOF_FAT_HEADER];
51 fd.read_exact(&mut header)?;
52 Ok(FatHeader::from_bytes(header))
53 }
54
55 pub fn parse(bytes: &[u8]) -> error::Result<FatHeader> {
57 Ok(bytes.pread_with::<FatHeader>(0, scroll::BE)?)
58 }
59}
60
61#[repr(C)]
62#[derive(Clone, Copy, Default, Pread, Pwrite, SizeWith)]
63pub struct FatArch {
65 pub cputype: u32,
67 pub cpusubtype: u32,
68 pub offset: u32,
70 pub size: u32,
72 pub align: u32,
73}
74
75pub const SIZEOF_FAT_ARCH: usize = 20;
76
77impl fmt::Debug for FatArch {
78 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
79 fmt.debug_struct("FatArch")
80 .field("cputype", &self.cputype())
81 .field("cmdsize", &self.cpusubtype())
82 .field("offset", &format_args!("{:#x}", &self.offset))
83 .field("size", &self.size)
84 .field("align", &self.align)
85 .finish()
86 }
87}
88
89impl FatArch {
90 pub fn slice<'a>(&self, bytes: &'a [u8]) -> &'a [u8] {
92 let start = self.offset as usize;
95 match start
96 .checked_add(self.size as usize)
97 .and_then(|end| bytes.get(start..end))
98 {
99 Some(slice) => slice,
100 None => {
101 log::warn!("invalid `FatArch` offset");
102 &[]
103 }
104 }
105 }
106
107 pub fn cputype(&self) -> CpuType {
109 self.cputype
110 }
111
112 pub fn cpusubtype(&self) -> CpuSubType {
114 self.cpusubtype & !CPU_SUBTYPE_MASK
115 }
116
117 pub fn cpu_caps(&self) -> u32 {
119 (self.cpusubtype & CPU_SUBTYPE_MASK) >> 24
120 }
121
122 pub fn is_64(&self) -> bool {
124 (self.cputype & CPU_ARCH_ABI64) == CPU_ARCH_ABI64
125 }
126
127 pub fn parse(bytes: &[u8], offset: usize) -> error::Result<Self> {
129 let arch = bytes.pread_with::<FatArch>(offset, scroll::BE)?;
130 Ok(arch)
131 }
132}