use crate::arch;
use crate::error::{Error, Result};
use crate::import::RawImport;
use crate::{ImportKind, Symbol};
use std::collections::{HashMap, HashSet};
use std::sync::Arc;
pub(crate) const MH_MAGIC_64: u32 = 0xfeed_facf;
const MH_MAGIC_32: u32 = 0xfeed_face;
const MH_CIGAM_64: u32 = 0xcffa_edfe;
const MH_CIGAM_32: u32 = 0xcefa_edfe;
pub(crate) const FAT_MAGIC: u32 = 0xcafe_babe;
pub(crate) const FAT_MAGIC_64: u32 = 0xcafe_babf;
const MACH_HEADER_64_SIZE: u64 = 32;
const SEGMENT_COMMAND_64_SIZE: u64 = 72;
const SECTION_64_SIZE: u64 = 80;
const NLIST_64_SIZE: u64 = 16;
const LC_REQ_DYLD: u32 = 0x8000_0000;
const LC_SEGMENT_64: u32 = 0x19;
const LC_SYMTAB: u32 = 0x2;
const LC_DYSYMTAB: u32 = 0xb;
const LC_LOAD_DYLIB: u32 = 0xc;
const LC_LOAD_WEAK_DYLIB: u32 = 0x18 | LC_REQ_DYLD;
const LC_REEXPORT_DYLIB: u32 = 0x1f | LC_REQ_DYLD;
const LC_LOAD_UPWARD_DYLIB: u32 = 0x23 | LC_REQ_DYLD;
const LC_LAZY_LOAD_DYLIB: u32 = 0x20;
const LC_DYLD_INFO: u32 = 0x22;
const LC_DYLD_INFO_ONLY: u32 = 0x22 | LC_REQ_DYLD;
const LC_DYLD_CHAINED_FIXUPS: u32 = 0x34 | LC_REQ_DYLD;
const SECTION_TYPE: u32 = 0xff;
const S_NON_LAZY_SYMBOL_POINTERS: u32 = 0x6;
const S_LAZY_SYMBOL_POINTERS: u32 = 0x7;
const INDIRECT_SYMBOL_LOCAL: u32 = 0x8000_0000;
const INDIRECT_SYMBOL_ABS: u32 = 0x4000_0000;
const N_STAB: u8 = 0xe0;
const N_TYPE: u8 = 0x0e;
const N_UNDF: u8 = 0x00;
const N_EXT: u8 = 0x01;
const BIND_SPECIAL_DYLIB_SELF: i64 = 0;
const BIND_OPCODE_MASK: u8 = 0xf0;
const BIND_IMMEDIATE_MASK: u8 = 0x0f;
const BIND_OPCODE_DONE: u8 = 0x00;
const BIND_OPCODE_SET_DYLIB_ORDINAL_IMM: u8 = 0x10;
const BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB: u8 = 0x20;
const BIND_OPCODE_SET_DYLIB_SPECIAL_IMM: u8 = 0x30;
const BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM: u8 = 0x40;
const BIND_OPCODE_SET_TYPE_IMM: u8 = 0x50;
const BIND_OPCODE_SET_ADDEND_SLEB: u8 = 0x60;
const BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB: u8 = 0x70;
const BIND_OPCODE_ADD_ADDR_ULEB: u8 = 0x80;
const BIND_OPCODE_DO_BIND: u8 = 0x90;
const BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB: u8 = 0xa0;
const BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED: u8 = 0xb0;
const BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB: u8 = 0xc0;
const DYLD_CHAINED_PTR_START_NONE: u16 = 0xffff;
const DYLD_CHAINED_PTR_ARM64E: u16 = 1;
const DYLD_CHAINED_PTR_64: u16 = 2;
const DYLD_CHAINED_PTR_64_OFFSET: u16 = 6;
const DYLD_CHAINED_PTR_ARM64E_KERNEL: u16 = 7;
const DYLD_CHAINED_PTR_ARM64E_USERLAND: u16 = 9;
const DYLD_CHAINED_PTR_ARM64E_FIRMWARE: u16 = 10;
const DYLD_CHAINED_PTR_ARM64E_USERLAND24: u16 = 12;
const DYLD_CHAINED_IMPORT: u32 = 1;
const DYLD_CHAINED_IMPORT_ADDEND: u32 = 2;
const DYLD_CHAINED_IMPORT_ADDEND64: u32 = 3;
const MAX_COMMANDS: u32 = 1 << 16;
const MAX_SECTIONS: u32 = 1 << 16;
const MAX_INDIRECT: u32 = 1 << 24;
const MAX_BIND_BYTES: u64 = 1 << 24;
const MAX_CHAIN_STEPS: u64 = 1 << 24;
const MAX_FIXUP_SEGMENTS: u32 = 1 << 12;
const MAX_NAME_LEN: usize = 8192;
const MAX_DYLIBS: usize = 1 << 12;
const ULEB_MAX_SHIFT: u32 = 63;
#[derive(Debug, Clone, Copy)]
pub(crate) struct Segment {
pub(crate) vmaddr: u64,
#[cfg_attr(not(any(target_os = "macos", target_os = "ios")), allow(dead_code))]
pub(crate) vmsize: u64,
pub(crate) fileoff: u64,
pub(crate) filesize: u64,
}
impl Segment {
#[cfg(test)]
fn contains_fileoff(&self, off: u64) -> bool {
off >= self.fileoff && off < self.fileoff.saturating_add(self.filesize)
}
}
pub(crate) trait MachOView {
fn cpu_type(&self) -> u32;
fn cpu_subtype(&self) -> u32;
fn is_arm64e(&self) -> bool {
self.cpu_type() == arch::CPU_TYPE_ARM64
&& (self.cpu_subtype() & !arch::CPU_SUBTYPE_MASK) == arch::CPU_SUBTYPE_ARM64E
}
fn read(&self, off: u64, buf: &mut [u8]) -> Result<()>;
fn file_backed(&self) -> bool;
fn read_slot_encoding(&self, off: u64) -> Result<u64>;
fn slot_address(&self, off: u64) -> Result<u64>;
}
fn read_u16(view: &dyn MachOView, off: u64) -> Result<u16> {
let mut b = [0u8; 2];
view.read(off, &mut b)?;
Ok(u16::from_le_bytes(b))
}
fn read_u32(view: &dyn MachOView, off: u64) -> Result<u32> {
let mut b = [0u8; 4];
view.read(off, &mut b)?;
Ok(u32::from_le_bytes(b))
}
fn read_u64(view: &dyn MachOView, off: u64) -> Result<u64> {
let mut b = [0u8; 8];
view.read(off, &mut b)?;
Ok(u64::from_le_bytes(b))
}
fn read_cstr_raw(view: &dyn MachOView, off: u64) -> Result<(String, u64)> {
let mut bytes = Vec::new();
for i in 0..=MAX_NAME_LEN as u64 {
let mut byte = [0u8; 1];
view.read(off + i, &mut byte)?;
if byte[0] == 0 {
return Ok((String::from_utf8_lossy(&bytes).into_owned(), i));
}
bytes.push(byte[0]);
}
Err(Error::Malformed("unterminated Mach-O string"))
}
fn read_cstr(view: &dyn MachOView, off: u64) -> Result<String> {
Ok(read_cstr_raw(view, off)?.0)
}
fn read_str_in_table(view: &dyn MachOView, base: u64, size: u64, strx: u32) -> Result<String> {
let strx = u64::from(strx);
if strx >= size {
return Err(Error::Malformed("string-table offset past table size"));
}
let max = (size - strx).min(MAX_NAME_LEN as u64 + 1);
let mut bytes = Vec::new();
for i in 0..max {
let mut byte = [0u8; 1];
view.read(base + strx + i, &mut byte)?;
if byte[0] == 0 {
return Ok(String::from_utf8_lossy(&bytes).into_owned());
}
bytes.push(byte[0]);
}
Err(Error::Malformed("unterminated string-table entry"))
}
pub(crate) fn normalize_symbol_name(raw: &str) -> Option<String> {
let without_underscore = raw.strip_prefix('_').unwrap_or(raw);
let base = without_underscore
.split('$')
.next()
.unwrap_or(without_underscore);
if base.is_empty() {
None
} else {
Some(base.to_owned())
}
}
const TLV_BOOTSTRAP: &str = "_tlv_bootstrap";
#[derive(Debug, Clone, Copy)]
pub(crate) struct SliceRange {
pub(crate) offset: u64,
pub(crate) size: u64,
}
#[derive(Debug, Clone, Copy)]
pub(crate) struct FatArch {
pub(crate) cpu_type: u32,
pub(crate) cpu_subtype: u32,
pub(crate) range: SliceRange,
}
#[derive(Debug)]
pub(crate) enum Container {
Thin,
Fat(Vec<FatArch>),
}
pub(crate) fn classify(bytes: &[u8]) -> Result<Container> {
let magic = read_slice_u32_le(bytes, 0)?;
match magic {
MH_MAGIC_64 => Ok(Container::Thin),
MH_MAGIC_32 | MH_CIGAM_32 => Err(Error::Unsupported("32-bit Mach-O image")),
MH_CIGAM_64 => Err(Error::Unsupported(
"byte-swapped (foreign-endian) Mach-O image",
)),
_ => {
let be = read_slice_u32_be(bytes, 0)?;
match be {
FAT_MAGIC => parse_fat(bytes, false),
FAT_MAGIC_64 => parse_fat(bytes, true),
_ => Err(Error::Malformed("not a Mach-O or universal image")),
}
}
}
}
fn parse_fat(bytes: &[u8], wide: bool) -> Result<Container> {
let nfat = read_slice_u32_be(bytes, 4)?;
if nfat > 1024 {
return Err(Error::Malformed("implausible fat arch count"));
}
let (entry_size, base) = if wide {
(32usize, 8usize)
} else {
(20usize, 8usize)
};
let mut slices = Vec::new();
for i in 0..nfat as usize {
let entry = base + i * entry_size;
let cpu_type = read_slice_u32_be(bytes, entry)?;
let cpu_subtype = read_slice_u32_be(bytes, entry + 4)?;
let (offset, size) = if wide {
(
read_slice_u64_be(bytes, entry + 8)?,
read_slice_u64_be(bytes, entry + 16)?,
)
} else {
(
u64::from(read_slice_u32_be(bytes, entry + 8)?),
u64::from(read_slice_u32_be(bytes, entry + 12)?),
)
};
let end = offset
.checked_add(size)
.ok_or(Error::Malformed("fat slice overflow"))?;
if end > bytes.len() as u64 {
return Err(Error::Malformed("fat slice out of bounds"));
}
slices.push(FatArch {
cpu_type,
cpu_subtype,
range: SliceRange { offset, size },
});
}
Ok(Container::Fat(slices))
}
pub(crate) fn thin_slice_range(
file: &[u8],
cpu_type: u32,
cpu_subtype: u32,
) -> Result<core::ops::Range<usize>> {
match classify(file)? {
Container::Thin => Ok(0..file.len()),
Container::Fat(slices) => {
let want_sub = cpu_subtype & !arch::CPU_SUBTYPE_MASK;
for slice in slices {
if slice.cpu_type != cpu_type
|| (slice.cpu_subtype & !arch::CPU_SUBTYPE_MASK) != want_sub
{
continue;
}
let start = usize::try_from(slice.range.offset)
.map_err(|_| Error::Malformed("fat slice offset overflow"))?;
let end = slice
.range
.offset
.checked_add(slice.range.size)
.and_then(|e| usize::try_from(e).ok())
.ok_or(Error::Malformed("fat slice end overflow"))?;
if read_slice_u32_le(file, start)? != MH_MAGIC_64 {
return Err(Error::Malformed("fat slice is not a thin 64-bit Mach-O"));
}
return Ok(start..end);
}
Err(Error::Malformed(
"no universal slice matches the loaded architecture",
))
}
}
}
fn read_slice_u32_le(bytes: &[u8], off: usize) -> Result<u32> {
let arr: [u8; 4] = bytes
.get(off..off + 4)
.and_then(|s| s.try_into().ok())
.ok_or(Error::Malformed("read past slice bounds"))?;
Ok(u32::from_le_bytes(arr))
}
fn read_slice_u32_be(bytes: &[u8], off: usize) -> Result<u32> {
let arr: [u8; 4] = bytes
.get(off..off + 4)
.and_then(|s| s.try_into().ok())
.ok_or(Error::Malformed("read past slice bounds"))?;
Ok(u32::from_be_bytes(arr))
}
fn read_slice_u64_be(bytes: &[u8], off: usize) -> Result<u64> {
let arr: [u8; 8] = bytes
.get(off..off + 8)
.and_then(|s| s.try_into().ok())
.ok_or(Error::Malformed("read past slice bounds"))?;
Ok(u64::from_be_bytes(arr))
}
#[derive(Debug, Clone, Copy)]
struct PointerSection {
fileoff: u64,
size: u64,
indirect_index: u32,
}
#[derive(Debug, Default)]
struct LoadInfo {
segments: Vec<Segment>,
pointer_sections: Vec<PointerSection>,
symtab: Option<(u64, u32, u64, u64)>,
indirect: Option<(u64, u32)>,
binds: Vec<(u64, u64)>,
chained: Option<(u64, u64)>,
dylibs: Vec<Arc<str>>,
}
fn read_load_commands(view: &dyn MachOView) -> Result<LoadInfo> {
let magic = read_u32(view, 0)?;
if magic != MH_MAGIC_64 {
return Err(Error::Malformed("not a little-endian 64-bit Mach-O header"));
}
let ncmds = read_u32(view, 16)?;
let sizeofcmds = u64::from(read_u32(view, 20)?);
if ncmds > MAX_COMMANDS {
return Err(Error::Malformed("implausible load-command count"));
}
let region_end = MACH_HEADER_64_SIZE
.checked_add(sizeofcmds)
.ok_or(Error::Malformed("load-command region overflow"))?;
let mut info = LoadInfo::default();
let mut cursor = MACH_HEADER_64_SIZE;
for _ in 0..ncmds {
if cursor
.checked_add(8)
.ok_or(Error::Malformed("command header overflow"))?
> region_end
{
return Err(Error::Malformed("load command runs past sizeofcmds"));
}
let cmd = read_u32(view, cursor)?;
let cmdsize = u64::from(read_u32(view, cursor + 4)?);
if cmdsize < 8 || !cmdsize.is_multiple_of(8) {
return Err(Error::Malformed("invalid load-command size"));
}
let next = cursor
.checked_add(cmdsize)
.ok_or(Error::Malformed("command size overflow"))?;
if next > region_end {
return Err(Error::Malformed("load command extends past sizeofcmds"));
}
parse_one_command(view, cmd, cursor, cmdsize, &mut info)?;
cursor = next;
}
Ok(info)
}
fn parse_one_command(
view: &dyn MachOView,
cmd: u32,
base: u64,
cmdsize: u64,
info: &mut LoadInfo,
) -> Result<()> {
match cmd {
LC_SEGMENT_64 => read_segment(view, base, cmdsize, info),
LC_SYMTAB => {
if cmdsize < 24 {
return Err(Error::Malformed("truncated LC_SYMTAB"));
}
let symoff = u64::from(read_u32(view, base + 8)?);
let nsyms = read_u32(view, base + 12)?;
let stroff = u64::from(read_u32(view, base + 16)?);
let strsize = u64::from(read_u32(view, base + 20)?);
info.symtab = Some((symoff, nsyms, stroff, strsize));
Ok(())
}
LC_DYSYMTAB => {
if cmdsize < 80 {
return Err(Error::Malformed("truncated LC_DYSYMTAB"));
}
let indirectsymoff = u64::from(read_u32(view, base + 56)?);
let nindirectsyms = read_u32(view, base + 60)?;
info.indirect = Some((indirectsymoff, nindirectsyms));
Ok(())
}
LC_DYLD_INFO | LC_DYLD_INFO_ONLY => {
if cmdsize < 48 {
return Err(Error::Malformed("truncated LC_DYLD_INFO"));
}
for (off_field, size_field) in [(16u64, 20u64), (24, 28), (32, 36)] {
let off = u64::from(read_u32(view, base + off_field)?);
let size = u64::from(read_u32(view, base + size_field)?);
if size != 0 {
info.binds.push((off, size));
}
}
Ok(())
}
LC_DYLD_CHAINED_FIXUPS => {
if cmdsize < 16 {
return Err(Error::Malformed("truncated LC_DYLD_CHAINED_FIXUPS"));
}
let dataoff = u64::from(read_u32(view, base + 8)?);
let datasize = u64::from(read_u32(view, base + 12)?);
info.chained = Some((dataoff, datasize));
Ok(())
}
LC_LOAD_DYLIB | LC_LOAD_WEAK_DYLIB | LC_REEXPORT_DYLIB | LC_LOAD_UPWARD_DYLIB
| LC_LAZY_LOAD_DYLIB => {
if info.dylibs.len() >= MAX_DYLIBS {
return Ok(()); }
let name_off = u64::from(read_u32(view, base + 8)?);
let name = if name_off < cmdsize {
read_cstr(view, base + name_off).unwrap_or_else(|_| "(unknown-dylib)".to_owned())
} else {
"(unknown-dylib)".to_owned()
};
info.dylibs.push(basename(&name).into());
Ok(())
}
_ => Ok(()),
}
}
fn read_segment(view: &dyn MachOView, base: u64, cmdsize: u64, info: &mut LoadInfo) -> Result<()> {
if cmdsize < SEGMENT_COMMAND_64_SIZE {
return Err(Error::Malformed("truncated LC_SEGMENT_64"));
}
let vmaddr = read_u64(view, base + 24)?;
let vmsize = read_u64(view, base + 32)?;
let fileoff = read_u64(view, base + 40)?;
let filesize = read_u64(view, base + 48)?;
let nsects = read_u32(view, base + 64)?;
info.segments.push(Segment {
vmaddr,
vmsize,
fileoff,
filesize,
});
if nsects > MAX_SECTIONS {
return Err(Error::Malformed("implausible section count"));
}
let sections_bytes = u64::from(nsects)
.checked_mul(SECTION_64_SIZE)
.ok_or(Error::Malformed("section table overflow"))?;
if SEGMENT_COMMAND_64_SIZE
.checked_add(sections_bytes)
.ok_or(Error::Malformed("overflow"))?
> cmdsize
{
return Err(Error::Malformed(
"section table extends past the segment command",
));
}
for i in 0..u64::from(nsects) {
let sec = base + SEGMENT_COMMAND_64_SIZE + i * SECTION_64_SIZE;
let size = read_u64(view, sec + 40)?;
let offset = u64::from(read_u32(view, sec + 48)?);
let flags = read_u32(view, sec + 64)?;
let reserved1 = read_u32(view, sec + 68)?;
if matches!(
flags & SECTION_TYPE,
S_NON_LAZY_SYMBOL_POINTERS | S_LAZY_SYMBOL_POINTERS
) {
info.pointer_sections.push(PointerSection {
fileoff: offset,
size,
indirect_index: reserved1,
});
}
}
Ok(())
}
fn basename(path: &str) -> &str {
path.rsplit(['/', '\\']).next().unwrap_or(path)
}
fn library_of(ordinal: i64, dylibs: &[Arc<str>]) -> Arc<str> {
if ordinal >= 1 {
usize::try_from(ordinal - 1)
.ok()
.and_then(|i| dylibs.get(i))
.cloned()
.unwrap_or_else(|| Arc::from(""))
} else {
Arc::from("")
}
}
fn parse_indirect(view: &dyn MachOView, info: &LoadInfo, out: &mut Vec<RawImport>) -> Result<()> {
let (Some((symoff, nsyms, stroff, strsize)), Some((indirectoff, nindirect))) =
(info.symtab, info.indirect)
else {
return Ok(()); };
let authenticated = view.is_arm64e();
for section in &info.pointer_sections {
let count = section.size / arch::PTR_SIZE as u64;
if count > u64::from(MAX_INDIRECT) {
return Err(Error::Malformed(
"implausible symbol-pointer section length",
));
}
for i in 0..count {
let indirect_idx = u64::from(section.indirect_index)
.checked_add(i)
.ok_or(Error::Malformed("indirect index overflow"))?;
if indirect_idx >= u64::from(nindirect) {
return Err(Error::Malformed("indirect index past nindirectsyms"));
}
let sym_index = read_u32(view, indirectoff + indirect_idx * 4)?;
if sym_index & (INDIRECT_SYMBOL_LOCAL | INDIRECT_SYMBOL_ABS) != 0 {
continue;
}
if u64::from(sym_index) >= u64::from(nsyms) {
return Err(Error::Malformed("indirect symbol index past nsyms"));
}
let nlist = symoff + u64::from(sym_index) * NLIST_64_SIZE;
let n_strx = read_u32(view, nlist)?;
let n_type = {
let mut b = [0u8; 1];
view.read(nlist + 4, &mut b)?;
b[0]
};
let n_desc = read_u16(view, nlist + 6)?;
if n_type & N_STAB != 0 || n_type & N_TYPE != N_UNDF || n_type & N_EXT == 0 {
continue;
}
let raw = read_str_in_table(view, stroff, strsize, n_strx)?;
let Some(name) = normalize_symbol_name(&raw) else {
continue;
};
if name == TLV_BOOTSTRAP {
continue; }
let slot_off = section
.fileoff
.checked_add(i * arch::PTR_SIZE as u64)
.ok_or(Error::Malformed("slot offset overflow"))?;
let library = library_of(i64::from(n_desc >> 8 & 0xff), &info.dylibs);
out.push(RawImport {
library,
symbol: Some(Symbol::Name(name)),
version: None,
slot: usize::try_from(view.slot_address(slot_off)?)
.map_err(|_| Error::Malformed("slot address overflow"))?,
kind: ImportKind::Standard,
authenticated,
});
}
}
Ok(())
}
fn uleb128(view: &dyn MachOView, cursor: &mut u64, end: u64) -> Result<u64> {
let mut result: u64 = 0;
let mut shift: u32 = 0;
loop {
if *cursor >= end {
return Err(Error::Malformed("ULEB128 runs past the bind stream"));
}
let mut b = [0u8; 1];
view.read(*cursor, &mut b)?;
*cursor += 1;
if shift > ULEB_MAX_SHIFT {
return Err(Error::Malformed("ULEB128 overflow"));
}
result |= u64::from(b[0] & 0x7f) << shift;
shift += 7;
if b[0] & 0x80 == 0 {
return Ok(result);
}
}
}
fn sleb128(view: &dyn MachOView, cursor: &mut u64, end: u64) -> Result<i64> {
let mut result: i64 = 0;
let mut shift: u32 = 0;
loop {
if *cursor >= end {
return Err(Error::Malformed("SLEB128 runs past the bind stream"));
}
let mut b = [0u8; 1];
view.read(*cursor, &mut b)?;
*cursor += 1;
if shift > ULEB_MAX_SHIFT {
return Err(Error::Malformed("SLEB128 overflow"));
}
result |= i64::from(b[0] & 0x7f) << shift;
shift += 7;
if b[0] & 0x80 == 0 {
if shift < 64 && b[0] & 0x40 != 0 {
result |= -1i64 << shift;
}
return Ok(result);
}
}
}
struct BindState {
seg_index: usize,
seg_offset: u64,
library_ordinal: i64,
symbol: Option<String>,
}
fn parse_bind_stream(
view: &dyn MachOView,
info: &LoadInfo,
off: u64,
size: u64,
out: &mut Vec<RawImport>,
) -> Result<()> {
if size > MAX_BIND_BYTES {
return Err(Error::Malformed("implausible bind-stream size"));
}
let end = off
.checked_add(size)
.ok_or(Error::Malformed("bind stream overflow"))?;
let mut cursor = off;
let mut state = BindState {
seg_index: 0,
seg_offset: 0,
library_ordinal: BIND_SPECIAL_DYLIB_SELF,
symbol: None,
};
while cursor < end {
let mut b = [0u8; 1];
view.read(cursor, &mut b)?;
cursor += 1;
let opcode = b[0] & BIND_OPCODE_MASK;
let imm = b[0] & BIND_IMMEDIATE_MASK;
match opcode {
BIND_OPCODE_DONE | BIND_OPCODE_SET_TYPE_IMM => {}
BIND_OPCODE_SET_DYLIB_ORDINAL_IMM => state.library_ordinal = i64::from(imm),
BIND_OPCODE_SET_DYLIB_ORDINAL_ULEB => {
state.library_ordinal =
i64::try_from(uleb128(view, &mut cursor, end)?).unwrap_or(i64::MAX);
}
BIND_OPCODE_SET_DYLIB_SPECIAL_IMM => {
state.library_ordinal = if imm == 0 { 0 } else { i64::from(imm) | !0xf };
}
BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM => {
let (name, name_bytes) = read_cstr_raw(view, cursor)?;
cursor += name_bytes + 1;
state.symbol = normalize_symbol_name(&name);
}
BIND_OPCODE_SET_ADDEND_SLEB => {
sleb128(view, &mut cursor, end)?;
}
BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB => {
state.seg_index = usize::from(imm);
state.seg_offset = uleb128(view, &mut cursor, end)?;
}
BIND_OPCODE_ADD_ADDR_ULEB => {
state.seg_offset = state
.seg_offset
.wrapping_add(uleb128(view, &mut cursor, end)?);
}
BIND_OPCODE_DO_BIND => {
emit_bind(view, info, &state, out)?;
state.seg_offset = state.seg_offset.wrapping_add(arch::PTR_SIZE as u64);
}
BIND_OPCODE_DO_BIND_ADD_ADDR_ULEB => {
emit_bind(view, info, &state, out)?;
let add = uleb128(view, &mut cursor, end)?;
state.seg_offset = state
.seg_offset
.wrapping_add(add)
.wrapping_add(arch::PTR_SIZE as u64);
}
BIND_OPCODE_DO_BIND_ADD_ADDR_IMM_SCALED => {
emit_bind(view, info, &state, out)?;
let scaled = u64::from(imm).wrapping_mul(arch::PTR_SIZE as u64);
state.seg_offset = state
.seg_offset
.wrapping_add(scaled)
.wrapping_add(arch::PTR_SIZE as u64);
}
BIND_OPCODE_DO_BIND_ULEB_TIMES_SKIPPING_ULEB => {
let count = uleb128(view, &mut cursor, end)?;
let skip = uleb128(view, &mut cursor, end)?;
if count > MAX_CHAIN_STEPS {
return Err(Error::Malformed("implausible bind repeat count"));
}
for _ in 0..count {
emit_bind(view, info, &state, out)?;
state.seg_offset = state
.seg_offset
.wrapping_add(skip)
.wrapping_add(arch::PTR_SIZE as u64);
}
}
_ => return Err(Error::Malformed("unknown bind opcode")),
}
}
Ok(())
}
fn emit_bind(
view: &dyn MachOView,
info: &LoadInfo,
state: &BindState,
out: &mut Vec<RawImport>,
) -> Result<()> {
let Some(name) = state.symbol.clone() else {
return Err(Error::Malformed("DO_BIND with no symbol set"));
};
if name == TLV_BOOTSTRAP {
return Ok(());
}
let segment = info
.segments
.get(state.seg_index)
.ok_or(Error::Malformed("bind segment index out of range"))?;
let slot_off = segment
.fileoff
.checked_add(state.seg_offset)
.ok_or(Error::Malformed("bind slot offset overflow"))?;
out.push(RawImport {
library: library_of(state.library_ordinal, &info.dylibs),
symbol: Some(Symbol::Name(name)),
version: None,
slot: usize::try_from(view.slot_address(slot_off)?)
.map_err(|_| Error::Malformed("slot address overflow"))?,
kind: ImportKind::Standard,
authenticated: false,
});
Ok(())
}
struct ChainEntry {
is_bind: bool,
ordinal: u32,
authenticated: bool,
next: u64,
}
fn decode_chain(raw: u64, format: u16) -> Option<ChainEntry> {
match format {
DYLD_CHAINED_PTR_64 | DYLD_CHAINED_PTR_64_OFFSET => {
let is_bind = raw >> 63 & 1 == 1;
let next = (raw >> 51 & 0xfff) * 4; let ordinal = if is_bind { (raw & 0xff_ffff) as u32 } else { 0 };
Some(ChainEntry {
is_bind,
ordinal,
authenticated: false,
next,
})
}
DYLD_CHAINED_PTR_ARM64E
| DYLD_CHAINED_PTR_ARM64E_KERNEL
| DYLD_CHAINED_PTR_ARM64E_USERLAND
| DYLD_CHAINED_PTR_ARM64E_FIRMWARE
| DYLD_CHAINED_PTR_ARM64E_USERLAND24 => {
let authenticated = raw >> 63 & 1 == 1;
let is_bind = raw >> 62 & 1 == 1;
let stride = match format {
DYLD_CHAINED_PTR_ARM64E_KERNEL | DYLD_CHAINED_PTR_ARM64E_FIRMWARE => 4,
_ => 8,
};
let next = (raw >> 51 & 0x7ff) * stride; let ordinal = if format == DYLD_CHAINED_PTR_ARM64E_USERLAND24 {
(raw & 0xff_ffff) as u32
} else {
(raw & 0xffff) as u32
};
Some(ChainEntry {
is_bind,
ordinal,
authenticated,
next,
})
}
_ => None,
}
}
#[derive(Clone, Copy)]
struct ImportsTable {
base: u64,
count: u32,
format: u32,
symbols_base: u64,
blob_end: u64,
}
impl ImportsTable {
fn resolve(
&self,
view: &dyn MachOView,
ordinal: u32,
dylibs: &[Arc<str>],
) -> Result<(Arc<str>, Option<String>)> {
if ordinal >= self.count {
return Err(Error::Malformed(
"chained-fixups import ordinal out of range",
));
}
let (name_off, lib_ordinal) = match self.format {
DYLD_CHAINED_IMPORT => {
let word = read_u32(view, self.base + u64::from(ordinal) * 4)?;
(
u64::from(word >> 9 & 0x7f_ffff),
sign_extend(u64::from(word & 0xff), 8),
)
}
DYLD_CHAINED_IMPORT_ADDEND => {
let word = read_u32(view, self.base + u64::from(ordinal) * 8)?;
(
u64::from(word >> 9 & 0x7f_ffff),
sign_extend(u64::from(word & 0xff), 8),
)
}
DYLD_CHAINED_IMPORT_ADDEND64 => {
let word = read_u64(view, self.base + u64::from(ordinal) * 16)?;
(word >> 32 & 0xffff_ffff, sign_extend(word & 0xffff, 16))
}
_ => {
return Err(Error::Malformed(
"unsupported chained-fixups imports_format",
));
}
};
let name_addr = self
.symbols_base
.checked_add(name_off)
.ok_or(Error::Malformed("chained-fixups name offset overflow"))?;
if name_addr >= self.blob_end {
return Err(Error::Malformed("chained-fixups name offset past blob"));
}
let name = read_cstr(view, name_addr)?;
Ok((
library_of(lib_ordinal, dylibs),
normalize_symbol_name(&name),
))
}
}
fn sign_extend(value: u64, bits: u32) -> i64 {
let shift = 64 - bits;
i64::from_ne_bytes((value << shift).to_ne_bytes()) >> shift
}
fn parse_chained_fixups(
view: &dyn MachOView,
info: &LoadInfo,
dataoff: u64,
datasize: u64,
out: &mut Vec<RawImport>,
) -> Result<()> {
if !view.file_backed() {
return Ok(());
}
let blob_end = dataoff
.checked_add(datasize)
.ok_or(Error::Malformed("chained blob overflow"))?;
if datasize < 28 {
return Err(Error::Malformed("truncated chained-fixups header"));
}
let fixups_version = read_u32(view, dataoff)?;
if fixups_version != 0 {
return Err(Error::Unsupported("unknown chained-fixups version"));
}
let starts_offset = u64::from(read_u32(view, dataoff + 4)?);
let imports_offset = u64::from(read_u32(view, dataoff + 8)?);
let symbols_offset = u64::from(read_u32(view, dataoff + 12)?);
let imports_count = read_u32(view, dataoff + 16)?;
let imports_format = read_u32(view, dataoff + 20)?;
let imports = ImportsTable {
base: dataoff
.checked_add(imports_offset)
.ok_or(Error::Malformed("imports off overflow"))?,
count: imports_count,
format: imports_format,
symbols_base: dataoff
.checked_add(symbols_offset)
.ok_or(Error::Malformed("symbols off overflow"))?,
blob_end,
};
let starts = dataoff
.checked_add(starts_offset)
.ok_or(Error::Malformed("starts off overflow"))?;
let seg_count = read_u32(view, starts)?;
if seg_count > MAX_FIXUP_SEGMENTS {
return Err(Error::Malformed("implausible fixup segment count"));
}
for i in 0..u64::from(seg_count) {
let seg_info_offset = u64::from(read_u32(view, starts + 4 + i * 4)?);
if seg_info_offset == 0 {
continue; }
let seg_starts = starts
.checked_add(seg_info_offset)
.ok_or(Error::Malformed("segment starts overflow"))?;
walk_segment_chains(view, info, &imports, seg_starts, out)?;
}
Ok(())
}
fn walk_segment_chains(
view: &dyn MachOView,
info: &LoadInfo,
imports: &ImportsTable,
seg_starts: u64,
out: &mut Vec<RawImport>,
) -> Result<()> {
let page_size = u64::from(read_u16(view, seg_starts + 4)?);
let pointer_format = read_u16(view, seg_starts + 6)?;
let segment_offset = read_u64(view, seg_starts + 8)?;
let page_count = read_u16(view, seg_starts + 20)?;
if page_size == 0 {
return Err(Error::Malformed("zero fixup page size"));
}
for j in 0..u64::from(page_count) {
let page_start = read_u16(view, seg_starts + 22 + j * 2)?;
if page_start == DYLD_CHAINED_PTR_START_NONE {
continue;
}
let mut offset = segment_offset
.checked_add(j * page_size)
.and_then(|v| v.checked_add(u64::from(page_start)))
.ok_or(Error::Malformed("fixup page offset overflow"))?;
for _ in 0..MAX_CHAIN_STEPS {
let raw = view.read_slot_encoding(offset)?;
let Some(entry) = decode_chain(raw, pointer_format) else {
return Err(Error::Unsupported("unsupported chained-pointer format"));
};
if entry.is_bind {
let (library, name) = imports.resolve(view, entry.ordinal, &info.dylibs)?;
if let Some(name) = name.filter(|n| n != TLV_BOOTSTRAP) {
out.push(RawImport {
library,
symbol: Some(Symbol::Name(name)),
version: None,
slot: usize::try_from(view.slot_address(offset)?)
.map_err(|_| Error::Malformed("slot address overflow"))?,
kind: ImportKind::Standard,
authenticated: entry.authenticated,
});
}
}
if entry.next == 0 {
break;
}
offset = offset
.checked_add(entry.next)
.ok_or(Error::Malformed("fixup chain offset overflow"))?;
}
}
Ok(())
}
#[cfg_attr(not(any(target_os = "macos", target_os = "ios")), allow(dead_code))]
pub(crate) fn segments_of(view: &dyn MachOView) -> Result<Vec<Segment>> {
Ok(read_load_commands(view)?.segments)
}
pub(crate) fn parse_imports(view: &dyn MachOView) -> Result<Vec<RawImport>> {
if !arch::macho_cpu_supported(view.cpu_type()) {
return Err(Error::Unsupported("Mach-O cputype is not x86-64 or arm64"));
}
let info = read_load_commands(view)?;
let mut out = Vec::new();
parse_indirect(view, &info, &mut out)?;
let mut complement = Vec::new();
let complement_result = if let Some((dataoff, datasize)) = info.chained {
parse_chained_fixups(view, &info, dataoff, datasize, &mut complement)
} else {
info.binds
.iter()
.try_for_each(|&(off, size)| parse_bind_stream(view, &info, off, size, &mut complement))
};
if complement_result.is_ok() {
merge_complement(&mut out, complement);
}
let mut seen: HashSet<usize> = HashSet::new();
out.retain(|import| seen.insert(import.slot));
Ok(out)
}
fn merge_complement(out: &mut Vec<RawImport>, complement: Vec<RawImport>) {
let mut slot_to_index: HashMap<usize, usize> = HashMap::with_capacity(out.len());
for (i, import) in out.iter().enumerate() {
slot_to_index.entry(import.slot).or_insert(i);
}
for import in complement {
if let Some(&i) = slot_to_index.get(&import.slot) {
if let Some(existing) = out.get_mut(i) {
existing.authenticated = import.authenticated;
}
} else {
slot_to_index.insert(import.slot, out.len());
out.push(import);
}
}
}
#[cfg(test)]
#[allow(
clippy::unwrap_used,
clippy::expect_used,
clippy::indexing_slicing,
clippy::cast_possible_truncation,
clippy::panic,
clippy::too_many_lines
)]
mod tests {
use super::*;
const TEXT_VMADDR: u64 = 0x1_0000_0000;
const DATA_VMADDR: u64 = 0x1_0001_0000;
const DATA_FILEOFF: u64 = 0x4000;
struct FileView<'a> {
bytes: &'a [u8],
base: u64,
segments: Vec<Segment>,
cpu_type: u32,
cpu_subtype: u32,
}
impl<'a> FileView<'a> {
fn new(bytes: &'a [u8], base: u64) -> Result<Self> {
let head = base.checked_add(8).ok_or(Error::Malformed("overflow"))? as usize;
let magic_bytes = bytes
.get(base as usize..head)
.ok_or(Error::Malformed("slice too small"))?;
if u32::from_le_bytes(magic_bytes[0..4].try_into().unwrap()) != MH_MAGIC_64 {
return Err(Error::Malformed("not MH_MAGIC_64"));
}
let cpu_type = u32::from_le_bytes(
bytes
.get(base as usize + 4..base as usize + 8)
.unwrap()
.try_into()
.unwrap(),
);
let cpu_subtype = u32::from_le_bytes(
bytes
.get(base as usize + 8..base as usize + 12)
.unwrap()
.try_into()
.unwrap(),
);
let mut boot = Self {
bytes,
base,
segments: Vec::new(),
cpu_type,
cpu_subtype,
};
let info = read_load_commands(&boot)?;
boot.segments = info.segments;
Ok(boot)
}
}
impl MachOView for FileView<'_> {
fn cpu_type(&self) -> u32 {
self.cpu_type
}
fn cpu_subtype(&self) -> u32 {
self.cpu_subtype
}
fn read(&self, off: u64, buf: &mut [u8]) -> Result<()> {
let start = self
.base
.checked_add(off)
.and_then(|v| usize::try_from(v).ok())
.ok_or(Error::Malformed("cursor overflow"))?;
let end = start
.checked_add(buf.len())
.ok_or(Error::Malformed("read overflow"))?;
let src = self
.bytes
.get(start..end)
.ok_or(Error::Malformed("read past slice"))?;
buf.copy_from_slice(src);
Ok(())
}
fn file_backed(&self) -> bool {
true
}
fn read_slot_encoding(&self, off: u64) -> Result<u64> {
let mut b = [0u8; 8];
self.read(off, &mut b)?;
Ok(u64::from_le_bytes(b))
}
fn slot_address(&self, off: u64) -> Result<u64> {
let seg = self
.segments
.iter()
.find(|s| s.contains_fileoff(off))
.ok_or(Error::Malformed("slot offset outside any segment"))?;
let addr = seg
.vmaddr
.checked_add(off - seg.fileoff)
.ok_or(Error::Malformed("slot vmaddr overflow"))?;
if !addr.is_multiple_of(8) {
return Err(Error::Malformed("slot not pointer-aligned"));
}
Ok(addr)
}
}
struct Image {
bytes: Vec<u8>,
}
impl Image {
fn new(size: usize) -> Self {
Self {
bytes: vec![0u8; size],
}
}
fn put_u16(&mut self, at: usize, v: u16) {
self.bytes[at..at + 2].copy_from_slice(&v.to_le_bytes());
}
fn put_u32(&mut self, at: usize, v: u32) {
self.bytes[at..at + 4].copy_from_slice(&v.to_le_bytes());
}
fn put_u64(&mut self, at: usize, v: u64) {
self.bytes[at..at + 8].copy_from_slice(&v.to_le_bytes());
}
fn put_str(&mut self, at: usize, s: &str) {
self.bytes[at..at + s.len()].copy_from_slice(s.as_bytes());
self.bytes[at + s.len()] = 0;
}
}
struct Layout {
cpu_type: u32,
cpu_subtype: u32,
}
fn build_indirect(layout: &Layout, names: &[&str]) -> (Vec<u8>, Vec<(String, u64)>) {
let n = names.len();
let ptrs_off = DATA_FILEOFF as usize;
let indirect_off = 0x5000usize;
let symtab_off = 0x6000usize;
let strtab_off = 0x7000usize;
let mut img = Image::new(0x8000);
img.put_u32(0, MH_MAGIC_64);
img.put_u32(4, layout.cpu_type);
img.put_u32(8, layout.cpu_subtype);
img.put_u32(12, 0x6);
let mut c = 32usize;
let mut ncmds = 0u32;
let text = c;
img.put_u32(text, LC_SEGMENT_64);
img.put_u32(text + 4, SEGMENT_COMMAND_64_SIZE as u32);
img.put_str(text + 8, "__TEXT");
img.put_u64(text + 24, TEXT_VMADDR); img.put_u64(text + 32, 0x4000); img.put_u64(text + 40, 0); img.put_u64(text + 48, 0x4000); img.put_u32(text + 64, 0); c += SEGMENT_COMMAND_64_SIZE as usize;
ncmds += 1;
let data = c;
let seg_and_one_sec = SEGMENT_COMMAND_64_SIZE + SECTION_64_SIZE;
img.put_u32(data, LC_SEGMENT_64);
img.put_u32(data + 4, seg_and_one_sec as u32);
img.put_str(data + 8, "__DATA");
img.put_u64(data + 24, DATA_VMADDR); img.put_u64(data + 32, 0x1000); img.put_u64(data + 40, DATA_FILEOFF); img.put_u64(data + 48, 0x1000); img.put_u32(data + 64, 1); let sec = data + SEGMENT_COMMAND_64_SIZE as usize;
img.put_str(sec, "__la_symbol_ptr");
img.put_str(sec + 16, "__DATA");
img.put_u64(sec + 32, DATA_VMADDR); img.put_u64(sec + 40, (n * 8) as u64); img.put_u32(sec + 48, ptrs_off as u32); img.put_u32(sec + 64, S_LAZY_SYMBOL_POINTERS); img.put_u32(sec + 68, 0); c += seg_and_one_sec as usize;
ncmds += 1;
let link = c;
img.put_u32(link, LC_SEGMENT_64);
img.put_u32(link + 4, SEGMENT_COMMAND_64_SIZE as u32);
img.put_str(link + 8, "__LINKEDIT");
img.put_u64(link + 24, DATA_VMADDR + 0x1000); img.put_u64(link + 32, 0x4000); img.put_u64(link + 40, indirect_off as u64); img.put_u64(link + 48, 0x3000); img.put_u32(link + 64, 0); c += SEGMENT_COMMAND_64_SIZE as usize;
ncmds += 1;
let dylib = c;
let dylib_size = (24 + "libSystem.B.dylib".len() + 1).next_multiple_of(8); img.put_u32(dylib, LC_LOAD_DYLIB);
img.put_u32(dylib + 4, dylib_size as u32);
img.put_u32(dylib + 8, 24); img.put_str(dylib + 24, "libSystem.B.dylib");
c += dylib_size;
ncmds += 1;
let symtab = c;
img.put_u32(symtab, LC_SYMTAB);
img.put_u32(symtab + 4, 24);
img.put_u32(symtab + 8, symtab_off as u32); img.put_u32(symtab + 12, n as u32); img.put_u32(symtab + 16, strtab_off as u32); img.put_u32(symtab + 20, (0x8000 - strtab_off) as u32); c += 24;
ncmds += 1;
let dysym = c;
img.put_u32(dysym, LC_DYSYMTAB);
img.put_u32(dysym + 4, 80);
img.put_u32(dysym + 56, indirect_off as u32); img.put_u32(dysym + 60, n as u32); c += 80;
ncmds += 1;
img.put_u32(16, ncmds);
img.put_u32(20, (c - 32) as u32);
let mut strx = 1u32; let mut expected = Vec::new();
for (i, name) in names.iter().enumerate() {
let mangled = format!("_{name}");
img.put_u32(indirect_off + i * 4, i as u32); let nl = symtab_off + i * 16;
img.put_u32(nl, strx); img.bytes[nl + 4] = N_UNDF | N_EXT; img.put_u16(nl + 6, 1 << 8); img.put_str(strtab_off + strx as usize, &mangled);
strx += mangled.len() as u32 + 1;
expected.push((
normalize_symbol_name(&mangled).unwrap(),
DATA_VMADDR + (i * 8) as u64,
));
}
(img.bytes, expected)
}
fn find<'a>(imports: &'a [RawImport], name: &str) -> Option<&'a RawImport> {
imports
.iter()
.find(|i| i.symbol == Some(Symbol::name(name)))
}
#[test]
fn indirect_symbol_table_thin_arm64() {
let layout = Layout {
cpu_type: arch::CPU_TYPE_ARM64,
cpu_subtype: 0,
};
let (bytes, expected) = build_indirect(&layout, &["open", "close", "stat"]);
let view = FileView::new(&bytes, 0).expect("valid synthetic thin Mach-O");
assert_eq!(view.cpu_type(), arch::CPU_TYPE_ARM64);
let imports = parse_imports(&view).expect("enumerate indirect-symbol imports");
for (name, slot) in &expected {
let import = find(&imports, name).unwrap_or_else(|| panic!("missing import {name}"));
assert_eq!(import.slot as u64, *slot, "slot vmaddr for {name}");
assert!(!import.authenticated);
assert_eq!(&*import.library, "libSystem.B.dylib");
}
assert_eq!(imports.len(), 3);
}
#[test]
fn leading_underscore_and_inode64_suffix_are_normalized() {
assert_eq!(
normalize_symbol_name("_stat$INODE64").as_deref(),
Some("stat")
);
assert_eq!(normalize_symbol_name("_open").as_deref(), Some("open"));
assert_eq!(
normalize_symbol_name("_readdir$INODE64").as_deref(),
Some("readdir")
);
assert_eq!(
normalize_symbol_name("___getdirentries64").as_deref(),
Some("__getdirentries64")
);
assert_eq!(normalize_symbol_name("_").as_deref(), None);
assert_eq!(normalize_symbol_name("").as_deref(), None);
let layout = Layout {
cpu_type: arch::CPU_TYPE_X86_64,
cpu_subtype: 0,
};
let (bytes, _) = build_indirect(&layout, &["stat$INODE64", "open"]);
let view = FileView::new(&bytes, 0).unwrap();
let imports = parse_imports(&view).unwrap();
assert!(
find(&imports, "stat").is_some(),
"stat$INODE64 normalizes to stat"
);
assert!(find(&imports, "open").is_some());
}
#[test]
fn tlv_bootstrap_is_hidden_from_indirect_enumeration() {
let layout = Layout {
cpu_type: arch::CPU_TYPE_ARM64,
cpu_subtype: 0,
};
let (bytes, _) = build_indirect(&layout, &["open", "_tlv_bootstrap", "close"]);
let view = FileView::new(&bytes, 0).expect("valid synthetic thin Mach-O");
let imports = parse_imports(&view).expect("enumerate indirect imports");
assert!(find(&imports, "open").is_some());
assert!(find(&imports, "close").is_some());
assert!(
find(&imports, "_tlv_bootstrap").is_none(),
"TLS bootstrap must be hidden"
);
assert_eq!(imports.len(), 2, "only the two real imports remain");
}
#[test]
fn tlv_bootstrap_is_hidden_from_chained_enumeration() {
let layout = Layout {
cpu_type: arch::CPU_TYPE_X86_64,
cpu_subtype: 0,
};
let (bytes, _) = build_chained(
&layout,
DYLD_CHAINED_PTR_64_OFFSET,
DYLD_CHAINED_IMPORT,
&["open", "_tlv_bootstrap", "close"],
);
let view = FileView::new(&bytes, 0).expect("valid chained-fixups image");
let imports = parse_imports(&view).expect("enumerate chained binds");
assert!(find(&imports, "open").is_some());
assert!(find(&imports, "close").is_some());
assert!(
find(&imports, "_tlv_bootstrap").is_none(),
"TLS bootstrap must be hidden"
);
assert_eq!(imports.len(), 2);
}
#[test]
fn fat_wrapper_selects_slice() {
let layout = Layout {
cpu_type: arch::CPU_TYPE_ARM64,
cpu_subtype: 0,
};
let (thin, expected) = build_indirect(&layout, &["open", "read"]);
let slice_off = 0x4000usize;
let mut fat = vec![0u8; slice_off + thin.len()];
fat[0..4].copy_from_slice(&FAT_MAGIC.to_be_bytes());
fat[4..8].copy_from_slice(&1u32.to_be_bytes()); fat[8..12].copy_from_slice(&arch::CPU_TYPE_ARM64.to_be_bytes());
fat[12..16].copy_from_slice(&0u32.to_be_bytes()); fat[16..20].copy_from_slice(&(slice_off as u32).to_be_bytes()); fat[20..24].copy_from_slice(&(thin.len() as u32).to_be_bytes()); fat[24..28].copy_from_slice(&14u32.to_be_bytes()); fat[slice_off..].copy_from_slice(&thin);
let container = classify(&fat).expect("fat classify");
let Container::Fat(slices) = container else {
panic!("expected Fat")
};
assert_eq!(slices.len(), 1);
let arch_slice = slices[0];
assert_eq!(arch_slice.cpu_type, arch::CPU_TYPE_ARM64);
assert_eq!(arch_slice.range.offset, slice_off as u64);
assert_eq!(arch_slice.range.size, thin.len() as u64);
let view = FileView::new(&fat, arch_slice.range.offset).expect("thin slice view");
let imports = parse_imports(&view).expect("enumerate fat slice imports");
for (name, slot) in &expected {
assert_eq!(find(&imports, name).unwrap().slot as u64, *slot);
}
}
fn encode_chain_bind(
pointer_format: u16,
ordinal: u64,
authenticated: bool,
is_last: bool,
) -> u64 {
match pointer_format {
DYLD_CHAINED_PTR_64 | DYLD_CHAINED_PTR_64_OFFSET => {
let next: u64 = if is_last { 0 } else { 2 };
(1u64 << 63) | (next << 51) | (ordinal & 0xff_ffff)
}
DYLD_CHAINED_PTR_ARM64E
| DYLD_CHAINED_PTR_ARM64E_USERLAND
| DYLD_CHAINED_PTR_ARM64E_USERLAND24 => {
let next: u64 = u64::from(!is_last);
let ord_mask = if pointer_format == DYLD_CHAINED_PTR_ARM64E_USERLAND24 {
0xff_ffff
} else {
0xffff
};
(u64::from(authenticated) << 63)
| (1u64 << 62)
| (next << 51)
| (ordinal & ord_mask)
}
other => panic!("encode_chain_bind: unsupported pointer format {other}"),
}
}
fn put_chained_import(
img: &mut Image,
base: usize,
index: usize,
imports_format: u32,
name_off: u32,
lib_ordinal: u8,
) {
match imports_format {
DYLD_CHAINED_IMPORT => {
img.put_u32(base + index * 4, (name_off << 9) | u32::from(lib_ordinal));
}
DYLD_CHAINED_IMPORT_ADDEND => {
img.put_u32(base + index * 8, (name_off << 9) | u32::from(lib_ordinal));
img.put_u32(base + index * 8 + 4, 0);
}
DYLD_CHAINED_IMPORT_ADDEND64 => {
img.put_u64(
base + index * 16,
(u64::from(name_off) << 32) | u64::from(lib_ordinal),
);
img.put_u64(base + index * 16 + 8, 0);
}
other => panic!("put_chained_import: unsupported imports_format {other}"),
}
}
fn build_chained(
layout: &Layout,
pointer_format: u16,
imports_format: u32,
names: &[&str],
) -> (Vec<u8>, Vec<(String, u64)>) {
let n = names.len();
let data_off = DATA_FILEOFF as usize;
let blob_off = 0x5000usize;
let mut img = Image::new(0x8000);
img.put_u32(0, MH_MAGIC_64);
img.put_u32(4, layout.cpu_type);
img.put_u32(8, layout.cpu_subtype);
img.put_u32(12, 0x6);
let mut c = 32usize;
let mut ncmds = 0u32;
let text = c;
img.put_u32(text, LC_SEGMENT_64);
img.put_u32(text + 4, SEGMENT_COMMAND_64_SIZE as u32);
img.put_str(text + 8, "__TEXT");
img.put_u64(text + 24, TEXT_VMADDR);
img.put_u64(text + 32, 0x4000);
img.put_u64(text + 40, 0);
img.put_u64(text + 48, 0x4000);
c += SEGMENT_COMMAND_64_SIZE as usize;
ncmds += 1;
let data = c;
img.put_u32(data, LC_SEGMENT_64);
img.put_u32(data + 4, SEGMENT_COMMAND_64_SIZE as u32);
img.put_str(data + 8, "__DATA");
img.put_u64(data + 24, DATA_VMADDR);
img.put_u64(data + 32, 0x1000);
img.put_u64(data + 40, DATA_FILEOFF);
img.put_u64(data + 48, 0x1000);
c += SEGMENT_COMMAND_64_SIZE as usize;
ncmds += 1;
let link = c;
img.put_u32(link, LC_SEGMENT_64);
img.put_u32(link + 4, SEGMENT_COMMAND_64_SIZE as u32);
img.put_str(link + 8, "__LINKEDIT");
img.put_u64(link + 24, DATA_VMADDR + 0x1000);
img.put_u64(link + 32, 0x3000);
img.put_u64(link + 40, blob_off as u64);
img.put_u64(link + 48, 0x3000);
c += SEGMENT_COMMAND_64_SIZE as usize;
ncmds += 1;
let dylib = c;
let dylib_size = (24 + "libSystem.B.dylib".len() + 1).next_multiple_of(8);
img.put_u32(dylib, LC_LOAD_DYLIB);
img.put_u32(dylib + 4, dylib_size as u32);
img.put_u32(dylib + 8, 24);
img.put_str(dylib + 24, "libSystem.B.dylib");
c += dylib_size;
ncmds += 1;
let cf = c;
img.put_u32(cf, LC_DYLD_CHAINED_FIXUPS);
img.put_u32(cf + 4, 16);
img.put_u32(cf + 8, blob_off as u32); img.put_u32(cf + 12, 0x1000); c += 16;
ncmds += 1;
img.put_u32(16, ncmds);
img.put_u32(20, (c - 32) as u32);
let starts_off_rel = 0x40usize;
let imports_off_rel = 0x100usize;
let symbols_off_rel = 0x200usize;
img.put_u32(blob_off, 0); img.put_u32(blob_off + 4, starts_off_rel as u32);
img.put_u32(blob_off + 8, imports_off_rel as u32);
img.put_u32(blob_off + 12, symbols_off_rel as u32);
img.put_u32(blob_off + 16, n as u32); img.put_u32(blob_off + 20, imports_format);
let starts = blob_off + starts_off_rel;
img.put_u32(starts, 2); img.put_u32(starts + 4, 0); let seg_info_rel = 0x20usize; img.put_u32(starts + 8, seg_info_rel as u32);
let seg = starts + seg_info_rel;
img.put_u32(seg, 24); img.put_u16(seg + 4, 0x4000); img.put_u16(seg + 6, pointer_format); img.put_u64(seg + 8, DATA_FILEOFF); img.put_u32(seg + 16, 0); img.put_u16(seg + 20, 1); img.put_u16(seg + 22, 0);
let mut pool = symbols_off_rel; let mut expected = Vec::new();
for (i, name) in names.iter().enumerate() {
let mangled = format!("_{name}");
let name_off = (pool - symbols_off_rel) as u32;
put_chained_import(
&mut img,
blob_off + imports_off_rel,
i,
imports_format,
name_off,
1,
);
img.put_str(blob_off + pool, &mangled);
pool += mangled.len() + 1;
expected.push((
normalize_symbol_name(&mangled).unwrap(),
DATA_VMADDR + (i * 8) as u64,
));
}
for i in 0..n {
let slot = data_off + i * 8;
let is_last = i + 1 == n;
img.put_u64(
slot,
encode_chain_bind(pointer_format, i as u64, false, is_last),
);
}
(img.bytes, expected)
}
#[test]
fn chained_fixups_64_offset_binds() {
let layout = Layout {
cpu_type: arch::CPU_TYPE_X86_64,
cpu_subtype: 0,
};
let (bytes, expected) = build_chained(
&layout,
DYLD_CHAINED_PTR_64_OFFSET,
DYLD_CHAINED_IMPORT,
&["open", "fstat$INODE64", "close"],
);
let view = FileView::new(&bytes, 0).expect("valid chained-fixups image");
let imports = parse_imports(&view).expect("enumerate chained-fixups imports");
for (name, slot) in &expected {
let import = find(&imports, name).unwrap_or_else(|| panic!("missing {name}"));
assert_eq!(import.slot as u64, *slot, "chained slot vmaddr for {name}");
assert!(
!import.authenticated,
"64_offset binds are not authenticated"
);
assert_eq!(&*import.library, "libSystem.B.dylib");
}
assert!(find(&imports, "fstat").is_some());
assert_eq!(imports.len(), 3);
}
#[test]
fn arm64e_authenticated_binds_are_flagged() {
let layout = Layout {
cpu_type: arch::CPU_TYPE_ARM64,
cpu_subtype: arch::CPU_SUBTYPE_ARM64E,
};
let (mut bytes, expected) = build_chained(
&layout,
DYLD_CHAINED_PTR_ARM64E_USERLAND,
DYLD_CHAINED_IMPORT,
&["open", "read"],
);
let n = expected.len();
for i in 0..n {
let slot = DATA_FILEOFF as usize + i * 8;
let raw =
encode_chain_bind(DYLD_CHAINED_PTR_ARM64E_USERLAND, i as u64, true, i + 1 == n);
bytes[slot..slot + 8].copy_from_slice(&raw.to_le_bytes());
}
let view = FileView::new(&bytes, 0).expect("valid arm64e image");
let imports = parse_imports(&view).expect("enumerate arm64e imports");
assert_eq!(imports.len(), n);
for import in &imports {
assert!(
import.authenticated,
"arm64e auth bind must be flagged for refusal"
);
}
}
#[test]
fn legacy_dyld_info_binds() {
let data_seg_index = 1u8; let blob_off = 0x5000usize;
let mut img = Image::new(0x8000);
img.put_u32(0, MH_MAGIC_64);
img.put_u32(4, arch::CPU_TYPE_X86_64);
img.put_u32(8, 0);
img.put_u32(12, 0x6);
let mut c = 32usize;
let mut ncmds = 0u32;
let text = c;
img.put_u32(text, LC_SEGMENT_64);
img.put_u32(text + 4, SEGMENT_COMMAND_64_SIZE as u32);
img.put_str(text + 8, "__TEXT");
img.put_u64(text + 24, TEXT_VMADDR);
img.put_u64(text + 32, 0x4000);
img.put_u64(text + 40, 0);
img.put_u64(text + 48, 0x4000);
c += SEGMENT_COMMAND_64_SIZE as usize;
ncmds += 1;
let data = c;
img.put_u32(data, LC_SEGMENT_64);
img.put_u32(data + 4, SEGMENT_COMMAND_64_SIZE as u32);
img.put_str(data + 8, "__DATA");
img.put_u64(data + 24, DATA_VMADDR);
img.put_u64(data + 32, 0x1000);
img.put_u64(data + 40, DATA_FILEOFF);
img.put_u64(data + 48, 0x1000);
c += SEGMENT_COMMAND_64_SIZE as usize;
ncmds += 1;
let link = c;
img.put_u32(link, LC_SEGMENT_64);
img.put_u32(link + 4, SEGMENT_COMMAND_64_SIZE as u32);
img.put_str(link + 8, "__LINKEDIT");
img.put_u64(link + 24, DATA_VMADDR + 0x1000);
img.put_u64(link + 32, 0x3000);
img.put_u64(link + 40, blob_off as u64);
img.put_u64(link + 48, 0x3000);
c += SEGMENT_COMMAND_64_SIZE as usize;
ncmds += 1;
let dylib = c;
let dylib_size = (24 + "libSystem.B.dylib".len() + 1).next_multiple_of(8);
img.put_u32(dylib, LC_LOAD_DYLIB);
img.put_u32(dylib + 4, dylib_size as u32);
img.put_u32(dylib + 8, 24);
img.put_str(dylib + 24, "libSystem.B.dylib");
c += dylib_size;
ncmds += 1;
let info = c;
img.put_u32(info, LC_DYLD_INFO_ONLY);
img.put_u32(info + 4, 48);
let stream = blob_off;
let mut s = stream;
img.bytes[s] = BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | 1;
s += 1;
img.bytes[s] = BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM;
s += 1;
img.put_str(s, "_open");
s += "_open".len() + 1;
img.bytes[s] = BIND_OPCODE_SET_TYPE_IMM | 1;
s += 1;
img.bytes[s] = BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | data_seg_index;
s += 1;
img.bytes[s] = 0; s += 1;
img.bytes[s] = BIND_OPCODE_DO_BIND;
s += 1;
img.bytes[s] = BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM;
s += 1;
img.put_str(s, "_close");
s += "_close".len() + 1;
img.bytes[s] = BIND_OPCODE_DO_BIND;
s += 1;
img.bytes[s] = BIND_OPCODE_DONE;
s += 1;
let bind_size = s - stream;
img.put_u32(info + 16, stream as u32); img.put_u32(info + 20, bind_size as u32); c += 48;
ncmds += 1;
img.put_u32(16, ncmds);
img.put_u32(20, (c - 32) as u32);
let view = FileView::new(&img.bytes, 0).expect("valid dyld-info image");
let imports = parse_imports(&view).expect("enumerate legacy binds");
let open = find(&imports, "open").expect("open bind");
assert_eq!(open.slot as u64, DATA_VMADDR, "first bind at __DATA+0");
let close = find(&imports, "close").expect("close bind");
assert_eq!(
close.slot as u64,
DATA_VMADDR + 8,
"second bind auto-advanced +8"
);
assert_eq!(&*open.library, "libSystem.B.dylib");
}
#[test]
fn rejects_32bit_and_fat_and_foreign_endian() {
let mut b = vec![0u8; 64];
b[0..4].copy_from_slice(&MH_MAGIC_32.to_le_bytes());
assert!(matches!(classify(&b), Err(Error::Unsupported(_))));
b[0..4].copy_from_slice(&MH_CIGAM_64.to_le_bytes());
assert!(matches!(classify(&b), Err(Error::Unsupported(_))));
b[0..4].copy_from_slice(&0xdead_beefu32.to_le_bytes());
assert!(matches!(classify(&b), Err(Error::Malformed(_))));
}
#[test]
fn unsupported_cputype_is_rejected() {
let layout = Layout {
cpu_type: 0x0000_0007,
cpu_subtype: 0,
}; let (bytes, _) = build_indirect(&layout, &["open"]);
let view = FileView::new(&bytes, 0).unwrap();
assert!(matches!(parse_imports(&view), Err(Error::Unsupported(_))));
}
fn build_indirect_and_chained(
layout: &Layout,
pointer_format: u16,
slots: &[(&str, bool)],
) -> (Vec<u8>, Vec<(String, u64)>) {
let n = slots.len();
let data_off = DATA_FILEOFF as usize;
let blob_off = 0x5000usize;
let indirect_off = 0x6000usize;
let symtab_off = 0x6100usize;
let strtab_off = 0x6200usize;
let strtab_size = 0x8000 - strtab_off;
let mut img = Image::new(0x8000);
img.put_u32(0, MH_MAGIC_64);
img.put_u32(4, layout.cpu_type);
img.put_u32(8, layout.cpu_subtype);
img.put_u32(12, 0x6);
let mut c = 32usize;
let mut ncmds = 0u32;
let text = c;
img.put_u32(text, LC_SEGMENT_64);
img.put_u32(text + 4, SEGMENT_COMMAND_64_SIZE as u32);
img.put_str(text + 8, "__TEXT");
img.put_u64(text + 24, TEXT_VMADDR);
img.put_u64(text + 32, 0x4000);
img.put_u64(text + 40, 0);
img.put_u64(text + 48, 0x4000);
c += SEGMENT_COMMAND_64_SIZE as usize;
ncmds += 1;
let data = c;
let seg_and_one_sec = SEGMENT_COMMAND_64_SIZE + SECTION_64_SIZE;
img.put_u32(data, LC_SEGMENT_64);
img.put_u32(data + 4, seg_and_one_sec as u32);
img.put_str(data + 8, "__DATA");
img.put_u64(data + 24, DATA_VMADDR);
img.put_u64(data + 32, 0x1000);
img.put_u64(data + 40, DATA_FILEOFF);
img.put_u64(data + 48, 0x1000);
img.put_u32(data + 64, 1); let sec = data + SEGMENT_COMMAND_64_SIZE as usize;
img.put_str(sec, "__got");
img.put_str(sec + 16, "__DATA");
img.put_u64(sec + 32, DATA_VMADDR); img.put_u64(sec + 40, (n * 8) as u64); img.put_u32(sec + 48, data_off as u32); img.put_u32(sec + 64, S_NON_LAZY_SYMBOL_POINTERS); img.put_u32(sec + 68, 0); c += seg_and_one_sec as usize;
ncmds += 1;
let link = c;
img.put_u32(link, LC_SEGMENT_64);
img.put_u32(link + 4, SEGMENT_COMMAND_64_SIZE as u32);
img.put_str(link + 8, "__LINKEDIT");
img.put_u64(link + 24, DATA_VMADDR + 0x1000);
img.put_u64(link + 32, 0x3000);
img.put_u64(link + 40, blob_off as u64);
img.put_u64(link + 48, 0x3000);
c += SEGMENT_COMMAND_64_SIZE as usize;
ncmds += 1;
let dylib = c;
let dylib_size = (24 + "libSystem.B.dylib".len() + 1).next_multiple_of(8);
img.put_u32(dylib, LC_LOAD_DYLIB);
img.put_u32(dylib + 4, dylib_size as u32);
img.put_u32(dylib + 8, 24);
img.put_str(dylib + 24, "libSystem.B.dylib");
c += dylib_size;
ncmds += 1;
let symtab = c;
img.put_u32(symtab, LC_SYMTAB);
img.put_u32(symtab + 4, 24);
img.put_u32(symtab + 8, symtab_off as u32);
img.put_u32(symtab + 12, n as u32);
img.put_u32(symtab + 16, strtab_off as u32);
img.put_u32(symtab + 20, strtab_size as u32);
c += 24;
ncmds += 1;
let dysym = c;
img.put_u32(dysym, LC_DYSYMTAB);
img.put_u32(dysym + 4, 80);
img.put_u32(dysym + 56, indirect_off as u32);
img.put_u32(dysym + 60, n as u32);
c += 80;
ncmds += 1;
let cf = c;
img.put_u32(cf, LC_DYLD_CHAINED_FIXUPS);
img.put_u32(cf + 4, 16);
img.put_u32(cf + 8, blob_off as u32);
img.put_u32(cf + 12, 0x1000);
c += 16;
ncmds += 1;
img.put_u32(16, ncmds);
img.put_u32(20, (c - 32) as u32);
let mut strx = 1u32; let mut expected = Vec::new();
for (i, (name, _auth)) in slots.iter().enumerate() {
let mangled = format!("_{name}");
img.put_u32(indirect_off + i * 4, i as u32); let nl = symtab_off + i * 16;
img.put_u32(nl, strx); img.bytes[nl + 4] = N_UNDF | N_EXT; img.put_u16(nl + 6, 1 << 8); img.put_str(strtab_off + strx as usize, &mangled);
strx += mangled.len() as u32 + 1;
expected.push((
normalize_symbol_name(&mangled).unwrap(),
DATA_VMADDR + (i * 8) as u64,
));
}
let starts_off_rel = 0x40usize;
let imports_off_rel = 0x100usize;
let symbols_off_rel = 0x200usize;
img.put_u32(blob_off, 0); img.put_u32(blob_off + 4, starts_off_rel as u32);
img.put_u32(blob_off + 8, imports_off_rel as u32);
img.put_u32(blob_off + 12, symbols_off_rel as u32);
img.put_u32(blob_off + 16, n as u32); img.put_u32(blob_off + 20, DYLD_CHAINED_IMPORT);
let starts = blob_off + starts_off_rel;
img.put_u32(starts, 2); img.put_u32(starts + 4, 0); let seg_info_rel = 0x20usize;
img.put_u32(starts + 8, seg_info_rel as u32);
let seg = starts + seg_info_rel;
img.put_u32(seg, 24); img.put_u16(seg + 4, 0x4000); img.put_u16(seg + 6, pointer_format);
img.put_u64(seg + 8, DATA_FILEOFF); img.put_u32(seg + 16, 0); img.put_u16(seg + 20, 1); img.put_u16(seg + 22, 0);
let mut pool = symbols_off_rel;
for (i, (name, _auth)) in slots.iter().enumerate() {
let mangled = format!("_{name}");
let name_off = (pool - symbols_off_rel) as u32;
put_chained_import(
&mut img,
blob_off + imports_off_rel,
i,
DYLD_CHAINED_IMPORT,
name_off,
1,
);
img.put_str(blob_off + pool, &mangled);
pool += mangled.len() + 1;
}
for (i, (_name, auth)) in slots.iter().enumerate() {
let slot = data_off + i * 8;
img.put_u64(
slot,
encode_chain_bind(pointer_format, i as u64, *auth, i + 1 == n),
);
}
(img.bytes, expected)
}
fn build_chained_multipage(
layout: &Layout,
pointer_format: u16,
pages: &[&[&str]],
page_size: u64,
) -> (Vec<u8>, Vec<(String, u64)>) {
let data_off = DATA_FILEOFF as usize;
let blob_off = 0x5000usize;
let mut img = Image::new(0x8000);
img.put_u32(0, MH_MAGIC_64);
img.put_u32(4, layout.cpu_type);
img.put_u32(8, layout.cpu_subtype);
img.put_u32(12, 0x6);
let mut c = 32usize;
let mut ncmds = 0u32;
let text = c;
img.put_u32(text, LC_SEGMENT_64);
img.put_u32(text + 4, SEGMENT_COMMAND_64_SIZE as u32);
img.put_str(text + 8, "__TEXT");
img.put_u64(text + 24, TEXT_VMADDR);
img.put_u64(text + 32, 0x4000);
img.put_u64(text + 40, 0);
img.put_u64(text + 48, 0x4000);
c += SEGMENT_COMMAND_64_SIZE as usize;
ncmds += 1;
let data = c;
img.put_u32(data, LC_SEGMENT_64);
img.put_u32(data + 4, SEGMENT_COMMAND_64_SIZE as u32);
img.put_str(data + 8, "__DATA");
img.put_u64(data + 24, DATA_VMADDR);
img.put_u64(data + 32, 0x1000);
img.put_u64(data + 40, DATA_FILEOFF);
img.put_u64(data + 48, 0x1000);
c += SEGMENT_COMMAND_64_SIZE as usize;
ncmds += 1;
let link = c;
img.put_u32(link, LC_SEGMENT_64);
img.put_u32(link + 4, SEGMENT_COMMAND_64_SIZE as u32);
img.put_str(link + 8, "__LINKEDIT");
img.put_u64(link + 24, DATA_VMADDR + 0x1000);
img.put_u64(link + 32, 0x3000);
img.put_u64(link + 40, blob_off as u64);
img.put_u64(link + 48, 0x3000);
c += SEGMENT_COMMAND_64_SIZE as usize;
ncmds += 1;
let dylib = c;
let dylib_size = (24 + "libSystem.B.dylib".len() + 1).next_multiple_of(8);
img.put_u32(dylib, LC_LOAD_DYLIB);
img.put_u32(dylib + 4, dylib_size as u32);
img.put_u32(dylib + 8, 24);
img.put_str(dylib + 24, "libSystem.B.dylib");
c += dylib_size;
ncmds += 1;
let cf = c;
img.put_u32(cf, LC_DYLD_CHAINED_FIXUPS);
img.put_u32(cf + 4, 16);
img.put_u32(cf + 8, blob_off as u32);
img.put_u32(cf + 12, 0x1000);
c += 16;
ncmds += 1;
img.put_u32(16, ncmds);
img.put_u32(20, (c - 32) as u32);
let flat: Vec<&str> = pages.iter().flat_map(|p| p.iter().copied()).collect();
let n = flat.len();
let starts_off_rel = 0x40usize;
let imports_off_rel = 0x100usize;
let symbols_off_rel = 0x200usize;
img.put_u32(blob_off, 0);
img.put_u32(blob_off + 4, starts_off_rel as u32);
img.put_u32(blob_off + 8, imports_off_rel as u32);
img.put_u32(blob_off + 12, symbols_off_rel as u32);
img.put_u32(blob_off + 16, n as u32);
img.put_u32(blob_off + 20, DYLD_CHAINED_IMPORT);
let starts = blob_off + starts_off_rel;
img.put_u32(starts, 2); img.put_u32(starts + 4, 0);
let seg_info_rel = 0x20usize;
img.put_u32(starts + 8, seg_info_rel as u32);
let seg = starts + seg_info_rel;
let page_count = pages.len();
img.put_u32(seg, 22 + page_count as u32 * 2); img.put_u16(seg + 4, page_size as u16);
img.put_u16(seg + 6, pointer_format);
img.put_u64(seg + 8, DATA_FILEOFF); img.put_u32(seg + 16, 0);
img.put_u16(seg + 20, page_count as u16); for (j, page) in pages.iter().enumerate() {
let start = if page.is_empty() {
DYLD_CHAINED_PTR_START_NONE
} else {
0
};
img.put_u16(seg + 22 + j * 2, start);
}
let mut pool = symbols_off_rel;
for (i, name) in flat.iter().enumerate() {
let mangled = format!("_{name}");
let name_off = (pool - symbols_off_rel) as u32;
put_chained_import(
&mut img,
blob_off + imports_off_rel,
i,
DYLD_CHAINED_IMPORT,
name_off,
1,
);
img.put_str(blob_off + pool, &mangled);
pool += mangled.len() + 1;
}
let mut ordinal = 0usize;
let mut expected = Vec::new();
for (j, page) in pages.iter().enumerate() {
for (k, name) in page.iter().enumerate() {
let file = data_off + j * page_size as usize + k * 8;
img.put_u64(
file,
encode_chain_bind(pointer_format, ordinal as u64, false, k + 1 == page.len()),
);
let vmaddr = DATA_VMADDR + (j * page_size as usize + k * 8) as u64;
expected.push((normalize_symbol_name(&format!("_{name}")).unwrap(), vmaddr));
ordinal += 1;
}
}
(img.bytes, expected)
}
#[test]
fn indirect_arm64e_flags_all_slots_authenticated() {
let layout = Layout {
cpu_type: arch::CPU_TYPE_ARM64,
cpu_subtype: arch::CPU_SUBTYPE_ARM64E,
};
let (bytes, expected) = build_indirect(&layout, &["open", "read", "close"]);
let view = FileView::new(&bytes, 0).expect("valid arm64e indirect image");
assert!(view.is_arm64e());
let imports = parse_imports(&view).expect("enumerate indirect imports");
assert_eq!(imports.len(), expected.len());
for import in &imports {
assert!(
import.authenticated,
"arm64e indirect slot is coarsely flagged authenticated"
);
}
}
#[test]
fn chained_ptr_64_non_offset_binds() {
let layout = Layout {
cpu_type: arch::CPU_TYPE_X86_64,
cpu_subtype: 0,
};
let (bytes, expected) = build_chained(
&layout,
DYLD_CHAINED_PTR_64,
DYLD_CHAINED_IMPORT,
&["open", "read", "close"],
);
let view = FileView::new(&bytes, 0).expect("valid PTR_64 image");
let imports = parse_imports(&view).expect("enumerate PTR_64 binds");
for (name, slot) in &expected {
let import = find(&imports, name).unwrap_or_else(|| panic!("missing {name}"));
assert_eq!(import.slot as u64, *slot);
assert!(!import.authenticated);
}
assert_eq!(imports.len(), 3);
}
#[test]
fn chained_arm64e_userland24_binds() {
let layout = Layout {
cpu_type: arch::CPU_TYPE_ARM64,
cpu_subtype: arch::CPU_SUBTYPE_ARM64E,
};
let (bytes, expected) = build_chained(
&layout,
DYLD_CHAINED_PTR_ARM64E_USERLAND24,
DYLD_CHAINED_IMPORT,
&["open", "read"],
);
let view = FileView::new(&bytes, 0).expect("valid arm64e userland24 image");
let imports = parse_imports(&view).expect("enumerate userland24 binds");
for (name, slot) in &expected {
let import = find(&imports, name).unwrap_or_else(|| panic!("missing {name}"));
assert_eq!(import.slot as u64, *slot);
assert!(
!import.authenticated,
"non-auth userland24 bind is rebindable"
);
}
assert_eq!(imports.len(), 2);
}
#[test]
fn chained_import_addend_and_addend64_formats() {
for imports_format in [DYLD_CHAINED_IMPORT_ADDEND, DYLD_CHAINED_IMPORT_ADDEND64] {
let layout = Layout {
cpu_type: arch::CPU_TYPE_X86_64,
cpu_subtype: 0,
};
let (bytes, expected) = build_chained(
&layout,
DYLD_CHAINED_PTR_64_OFFSET,
imports_format,
&["open", "stat"],
);
let view = FileView::new(&bytes, 0).expect("valid addend-format image");
let imports = parse_imports(&view)
.unwrap_or_else(|e| panic!("enumerate imports_format {imports_format}: {e:?}"));
for (name, slot) in &expected {
let import = find(&imports, name)
.unwrap_or_else(|| panic!("missing {name} ({imports_format})"));
assert_eq!(import.slot as u64, *slot);
assert_eq!(&*import.library, "libSystem.B.dylib");
}
assert_eq!(imports.len(), 2, "imports_format {imports_format}");
}
}
#[test]
fn chained_multipage_skips_start_none() {
let layout = Layout {
cpu_type: arch::CPU_TYPE_X86_64,
cpu_subtype: 0,
};
let page_size = 0x40u64;
let (bytes, expected) = build_chained_multipage(
&layout,
DYLD_CHAINED_PTR_64_OFFSET,
&[&["open", "read"], &[], &["close", "stat"]],
page_size,
);
let view = FileView::new(&bytes, 0).expect("valid multi-page image");
let imports = parse_imports(&view).expect("enumerate multi-page binds");
assert_eq!(imports.len(), 4);
for (name, slot) in &expected {
let import = find(&imports, name).unwrap_or_else(|| panic!("missing {name}"));
assert_eq!(import.slot as u64, *slot, "multi-page slot for {name}");
}
let close = find(&imports, "close").expect("close").slot as u64;
assert_eq!(
close,
DATA_VMADDR + 2 * page_size,
"page-2 chain starts one page in"
);
}
#[test]
fn indirect_symbol_local_and_abs_are_skipped() {
let layout = Layout {
cpu_type: arch::CPU_TYPE_X86_64,
cpu_subtype: 0,
};
let (mut bytes, expected) = build_indirect(&layout, &["open", "local", "abs"]);
let indirect_off = 0x5000usize;
bytes[indirect_off + 4..indirect_off + 8]
.copy_from_slice(&INDIRECT_SYMBOL_LOCAL.to_le_bytes());
bytes[indirect_off + 8..indirect_off + 12]
.copy_from_slice(&INDIRECT_SYMBOL_ABS.to_le_bytes());
let view = FileView::new(&bytes, 0).expect("valid indirect image");
let imports = parse_imports(&view).expect("enumerate with sentinels");
assert_eq!(imports.len(), 1, "LOCAL and ABS slots are skipped");
assert_eq!(
find(&imports, "open").expect("open").slot as u64,
expected[0].1
);
assert!(find(&imports, "local").is_none());
assert!(find(&imports, "abs").is_none());
}
#[test]
fn indirect_and_chained_merge_prefers_chained_auth() {
let layout = Layout {
cpu_type: arch::CPU_TYPE_ARM64,
cpu_subtype: arch::CPU_SUBTYPE_ARM64E,
};
let (bytes, expected) = build_indirect_and_chained(
&layout,
DYLD_CHAINED_PTR_ARM64E_USERLAND,
&[("open", false), ("read", true)],
);
let view = FileView::new(&bytes, 0).expect("valid combined image");
let imports = parse_imports(&view).expect("enumerate combined image");
assert_eq!(
imports.len(),
2,
"indirect + chained slots dedup to one each"
);
let open = find(&imports, "open").expect("open");
assert_eq!(open.slot as u64, expected[0].1);
assert!(
!open.authenticated,
"non-auth __got slot on arm64e is rebindable (m2)"
);
let read = find(&imports, "read").expect("read");
assert_eq!(read.slot as u64, expected[1].1);
assert!(read.authenticated, "authenticated slot stays refused (R1)");
}
#[test]
fn chained_complement_failure_keeps_indirect() {
let layout = Layout {
cpu_type: arch::CPU_TYPE_X86_64,
cpu_subtype: 0,
};
let (mut bytes, expected) = build_indirect_and_chained(
&layout,
DYLD_CHAINED_PTR_64_OFFSET,
&[("open", false), ("read", false)],
);
let blob_off = 0x5000usize;
bytes[blob_off..blob_off + 4].copy_from_slice(&99u32.to_le_bytes());
let view = FileView::new(&bytes, 0).expect("valid indirect, broken chain");
let imports = parse_imports(&view).expect("indirect survives a broken complement");
assert_eq!(imports.len(), 2, "the two indirect slots are retained");
for (name, slot) in &expected {
assert_eq!(
find(&imports, name).expect("indirect import").slot as u64,
*slot
);
}
}
#[test]
fn decode_chain_stride_is_per_format() {
let raw = (1u64 << 62) | (3u64 << 51);
for pf in [
DYLD_CHAINED_PTR_ARM64E_KERNEL,
DYLD_CHAINED_PTR_ARM64E_FIRMWARE,
] {
assert_eq!(
decode_chain(raw, pf).expect("kernel/firmware decodes").next,
3 * 4
);
}
for pf in [
DYLD_CHAINED_PTR_ARM64E,
DYLD_CHAINED_PTR_ARM64E_USERLAND,
DYLD_CHAINED_PTR_ARM64E_USERLAND24,
] {
assert_eq!(decode_chain(raw, pf).expect("userland decodes").next, 3 * 8);
}
let raw64 = (1u64 << 63) | (3u64 << 51);
assert_eq!(
decode_chain(raw64, DYLD_CHAINED_PTR_64)
.expect("ptr64 decodes")
.next,
3 * 4
);
}
fn build_legacy_bind(layout: &Layout, stream: &[u8]) -> Vec<u8> {
let blob_off = 0x5000usize;
let mut img = Image::new(0x8000);
img.put_u32(0, MH_MAGIC_64);
img.put_u32(4, layout.cpu_type);
img.put_u32(8, layout.cpu_subtype);
img.put_u32(12, 0x6);
let mut c = 32usize;
let mut ncmds = 0u32;
let text = c;
img.put_u32(text, LC_SEGMENT_64);
img.put_u32(text + 4, SEGMENT_COMMAND_64_SIZE as u32);
img.put_str(text + 8, "__TEXT");
img.put_u64(text + 24, TEXT_VMADDR);
img.put_u64(text + 32, 0x4000);
img.put_u64(text + 40, 0);
img.put_u64(text + 48, 0x4000);
c += SEGMENT_COMMAND_64_SIZE as usize;
ncmds += 1;
let data = c;
img.put_u32(data, LC_SEGMENT_64);
img.put_u32(data + 4, SEGMENT_COMMAND_64_SIZE as u32);
img.put_str(data + 8, "__DATA");
img.put_u64(data + 24, DATA_VMADDR);
img.put_u64(data + 32, 0x1000);
img.put_u64(data + 40, DATA_FILEOFF);
img.put_u64(data + 48, 0x1000);
c += SEGMENT_COMMAND_64_SIZE as usize;
ncmds += 1;
let link = c;
img.put_u32(link, LC_SEGMENT_64);
img.put_u32(link + 4, SEGMENT_COMMAND_64_SIZE as u32);
img.put_str(link + 8, "__LINKEDIT");
img.put_u64(link + 24, DATA_VMADDR + 0x1000);
img.put_u64(link + 32, 0x3000);
img.put_u64(link + 40, blob_off as u64);
img.put_u64(link + 48, 0x3000);
c += SEGMENT_COMMAND_64_SIZE as usize;
ncmds += 1;
let dylib = c;
let dylib_size = (24 + "libSystem.B.dylib".len() + 1).next_multiple_of(8);
img.put_u32(dylib, LC_LOAD_DYLIB);
img.put_u32(dylib + 4, dylib_size as u32);
img.put_u32(dylib + 8, 24);
img.put_str(dylib + 24, "libSystem.B.dylib");
c += dylib_size;
ncmds += 1;
let info = c;
img.put_u32(info, LC_DYLD_INFO_ONLY);
img.put_u32(info + 4, 48);
img.bytes[blob_off..blob_off + stream.len()].copy_from_slice(stream);
img.put_u32(info + 16, blob_off as u32); img.put_u32(info + 20, stream.len() as u32); c += 48;
ncmds += 1;
img.put_u32(16, ncmds);
img.put_u32(20, (c - 32) as u32);
img.bytes
}
#[test]
fn non_utf8_bind_symbol_name_keeps_cursor_in_sync() {
let mut s: Vec<u8> = Vec::new();
s.push(BIND_OPCODE_SET_DYLIB_ORDINAL_IMM | 1);
s.push(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM);
s.extend_from_slice(b"_ope\xffn");
s.push(0);
s.push(BIND_OPCODE_SET_TYPE_IMM | 1);
s.push(BIND_OPCODE_SET_SEGMENT_AND_OFFSET_ULEB | 1); s.push(0); s.push(BIND_OPCODE_DO_BIND); s.push(BIND_OPCODE_SET_SYMBOL_TRAILING_FLAGS_IMM);
s.extend_from_slice(b"_close");
s.push(0);
s.push(BIND_OPCODE_DO_BIND); s.push(BIND_OPCODE_DONE);
let layout = Layout {
cpu_type: arch::CPU_TYPE_X86_64,
cpu_subtype: 0,
};
let bytes = build_legacy_bind(&layout, &s);
let view = FileView::new(&bytes, 0).expect("valid legacy-bind image");
let imports = parse_imports(&view).expect("enumerate binds past a non-UTF-8 name");
assert_eq!(
imports.len(),
2,
"both binds recovered — cursor stayed in sync"
);
let close = find(&imports, "close").expect("clean second bind resolved");
assert_eq!(
close.slot as u64,
DATA_VMADDR + 8,
"second bind at __DATA+8 (no desync)"
);
}
#[test]
fn malformed_images_never_read_out_of_bounds() {
let mut state: u64 = 0x1234_5678_9abc_def1;
let mut next = || {
state ^= state << 13;
state ^= state >> 7;
state ^= state << 17;
state
};
for _ in 0..8000 {
let len = (next() as usize % 4096) + 4;
let mut buf = vec![0u8; len];
for b in &mut buf {
*b = next() as u8;
}
if let Ok(Container::Thin) = classify(&buf)
&& let Ok(view) = FileView::new(&buf, 0)
{
let _ = parse_imports(&view);
}
}
let mut fuzz = |base: &mut Vec<u8>| {
let len = base.len();
for _ in 0..30_000 {
let idx = next() as usize % len;
let orig = base[idx];
base[idx] ^= (next() as u8) | 1;
if let Ok(view) = FileView::new(base, 0) {
let _ = parse_imports(&view);
}
base[idx] = orig;
}
};
let layout = Layout {
cpu_type: arch::CPU_TYPE_ARM64,
cpu_subtype: 0,
};
let (mut indirect, _) = build_indirect(&layout, &["open", "close", "stat"]);
fuzz(&mut indirect);
let (mut chained, _) = build_chained(
&layout,
DYLD_CHAINED_PTR_64_OFFSET,
DYLD_CHAINED_IMPORT,
&["open", "read", "write"],
);
fuzz(&mut chained);
let arm64e = Layout {
cpu_type: arch::CPU_TYPE_ARM64,
cpu_subtype: arch::CPU_SUBTYPE_ARM64E,
};
let (mut chained_arm64e, _) = build_chained(
&arm64e,
DYLD_CHAINED_PTR_ARM64E_USERLAND,
DYLD_CHAINED_IMPORT_ADDEND,
&["open", "read"],
);
fuzz(&mut chained_arm64e);
let (mut combined, _) = build_indirect_and_chained(
&arm64e,
DYLD_CHAINED_PTR_ARM64E_USERLAND,
&[("open", false), ("read", true)],
);
fuzz(&mut combined);
}
fn put_be32(buf: &mut [u8], at: usize, v: u32) {
buf[at..at + 4].copy_from_slice(&v.to_be_bytes());
}
fn put_be64(buf: &mut [u8], at: usize, v: u64) {
buf[at..at + 8].copy_from_slice(&v.to_be_bytes());
}
fn put_le32(buf: &mut [u8], at: usize, v: u32) {
buf[at..at + 4].copy_from_slice(&v.to_le_bytes());
}
fn build_fat(wide: bool, arches: &[(u32, u32)]) -> (Vec<u8>, Vec<core::ops::Range<usize>>) {
let n = arches.len();
let slice_size = 0x100usize;
let mut buf = vec![0u8; 0x1000 + n * 0x1000];
put_be32(&mut buf, 0, if wide { FAT_MAGIC_64 } else { FAT_MAGIC });
put_be32(&mut buf, 4, n as u32);
let entry_size = if wide { 32usize } else { 20usize };
let mut ranges = Vec::new();
for (i, &(ct, cs)) in arches.iter().enumerate() {
let slice_off = 0x1000 + i * 0x1000;
let entry = 8 + i * entry_size;
put_be32(&mut buf, entry, ct);
put_be32(&mut buf, entry + 4, cs);
if wide {
put_be64(&mut buf, entry + 8, slice_off as u64);
put_be64(&mut buf, entry + 16, slice_size as u64);
put_be32(&mut buf, entry + 24, 12); } else {
put_be32(&mut buf, entry + 8, slice_off as u32);
put_be32(&mut buf, entry + 12, slice_size as u32);
put_be32(&mut buf, entry + 16, 12); }
put_le32(&mut buf, slice_off, MH_MAGIC_64);
ranges.push(slice_off..slice_off + slice_size);
}
(buf, ranges)
}
#[test]
fn thin_file_is_the_whole_slice() {
let mut buf = vec![0u8; 64];
put_le32(&mut buf, 0, MH_MAGIC_64);
assert_eq!(
thin_slice_range(&buf, arch::CPU_TYPE_ARM64, 0).unwrap(),
0..64
);
}
#[test]
fn fat32_selects_the_loaded_arch_slice() {
let (buf, ranges) = build_fat(
false,
&[(arch::CPU_TYPE_X86_64, 0), (arch::CPU_TYPE_ARM64, 0)],
);
assert_eq!(
thin_slice_range(&buf, arch::CPU_TYPE_X86_64, 0).unwrap(),
ranges[0]
);
let arm = thin_slice_range(&buf, arch::CPU_TYPE_ARM64, 0).unwrap();
assert_eq!(arm, ranges[1]);
assert_ne!(arm.start, 0, "the arm64 slice is at a nonzero fat offset");
assert_eq!(
u32::from_le_bytes(buf[arm.start..arm.start + 4].try_into().unwrap()),
MH_MAGIC_64,
);
assert!(thin_slice_range(&buf, arch::CPU_TYPE_ARM64 + 1, 0).is_err());
}
#[test]
fn fat64_selects_the_loaded_arch_slice() {
let (buf, ranges) = build_fat(
true,
&[(arch::CPU_TYPE_ARM64, 0), (arch::CPU_TYPE_X86_64, 0)],
);
assert_eq!(
thin_slice_range(&buf, arch::CPU_TYPE_ARM64, 0).unwrap(),
ranges[0]
);
assert_eq!(
thin_slice_range(&buf, arch::CPU_TYPE_X86_64, 0).unwrap(),
ranges[1]
);
}
#[test]
fn arm64_and_arm64e_are_distinguished_by_subtype() {
let (buf, ranges) = build_fat(
false,
&[
(arch::CPU_TYPE_ARM64, 0),
(arch::CPU_TYPE_ARM64, arch::CPU_SUBTYPE_ARM64E),
],
);
assert_eq!(
thin_slice_range(&buf, arch::CPU_TYPE_ARM64, 0).unwrap(),
ranges[0]
);
assert_eq!(
thin_slice_range(&buf, arch::CPU_TYPE_ARM64, arch::CPU_SUBTYPE_ARM64E).unwrap(),
ranges[1],
);
}
#[test]
fn subtype_capability_bits_are_masked_off() {
let cap = arch::CPU_SUBTYPE_ARM64E | arch::CPU_SUBTYPE_MASK;
let (buf, ranges) = build_fat(false, &[(arch::CPU_TYPE_ARM64, cap)]);
assert_eq!(
thin_slice_range(&buf, arch::CPU_TYPE_ARM64, arch::CPU_SUBTYPE_ARM64E).unwrap(),
ranges[0],
);
}
#[test]
fn out_of_bounds_or_non_macho_is_rejected_not_read() {
assert!(thin_slice_range(&[0u8; 64], arch::CPU_TYPE_ARM64, 0).is_err());
let (mut buf, _) = build_fat(false, &[(arch::CPU_TYPE_ARM64, 0)]);
put_be32(&mut buf, 16, 0xffff_fff0); assert!(thin_slice_range(&buf, arch::CPU_TYPE_ARM64, 0).is_err());
}
}