use std::collections::HashMap;
use zerocopy::{FromBytes, IntoBytes};
use super::constants::*;
use super::structs::*;
use crate::error::{Error, Result};
#[derive(Debug, Clone)]
pub struct SegmentInfo {
pub command: SegmentCommand64,
pub command_offset: usize,
pub sections: Vec<SectionInfo>,
}
impl SegmentInfo {
pub fn name(&self) -> &str {
self.command.name()
}
pub fn section(&self, name: &str) -> Option<&SectionInfo> {
self.sections.iter().find(|s| s.section.name() == name)
}
pub fn section_mut(&mut self, name: &str) -> Option<&mut SectionInfo> {
self.sections.iter_mut().find(|s| s.section.name() == name)
}
}
#[derive(Debug, Clone)]
pub struct SectionInfo {
pub section: Section64,
pub struct_offset: usize,
}
impl SectionInfo {
pub fn name(&self) -> &str {
self.section.name()
}
pub fn full_name(&self) -> String {
format!("{},{}", self.section.segment_name(), self.section.name())
}
}
#[derive(Debug, Clone)]
#[allow(missing_docs)] pub enum LoadCommandInfo {
Segment(SegmentInfo),
Symtab {
command: SymtabCommand,
offset: usize,
},
Dysymtab {
command: DysymtabCommand,
offset: usize,
},
DyldInfo {
command: DyldInfoCommand,
offset: usize,
},
LinkeditData {
command: LinkeditDataCommand,
offset: usize,
},
Dylib {
command: DylibCommand,
name: String,
offset: usize,
},
Uuid {
command: UuidCommand,
offset: usize,
},
BuildVersion {
command: BuildVersionCommand,
offset: usize,
},
FilesetEntry {
command: FilesetEntryCommand,
entry_id: String,
offset: usize,
},
Unknown {
cmd: u32,
cmdsize: u32,
offset: usize,
},
}
impl LoadCommandInfo {
pub fn offset(&self) -> usize {
match self {
LoadCommandInfo::Segment(s) => s.command_offset,
LoadCommandInfo::Symtab { offset, .. } => *offset,
LoadCommandInfo::Dysymtab { offset, .. } => *offset,
LoadCommandInfo::DyldInfo { offset, .. } => *offset,
LoadCommandInfo::LinkeditData { offset, .. } => *offset,
LoadCommandInfo::Dylib { offset, .. } => *offset,
LoadCommandInfo::Uuid { offset, .. } => *offset,
LoadCommandInfo::BuildVersion { offset, .. } => *offset,
LoadCommandInfo::FilesetEntry { offset, .. } => *offset,
LoadCommandInfo::Unknown { offset, .. } => *offset,
}
}
pub fn size(&self) -> u32 {
match self {
LoadCommandInfo::Segment(s) => s.command.cmdsize,
LoadCommandInfo::Symtab { command, .. } => command.cmdsize,
LoadCommandInfo::Dysymtab { command, .. } => command.cmdsize,
LoadCommandInfo::DyldInfo { command, .. } => command.cmdsize,
LoadCommandInfo::LinkeditData { command, .. } => command.cmdsize,
LoadCommandInfo::Dylib { command, .. } => command.cmdsize,
LoadCommandInfo::Uuid { command, .. } => command.cmdsize,
LoadCommandInfo::BuildVersion { command, .. } => command.cmdsize,
LoadCommandInfo::FilesetEntry { command, .. } => command.cmdsize,
LoadCommandInfo::Unknown { cmdsize, .. } => *cmdsize,
}
}
}
#[derive(Debug, Clone, Copy)]
struct SegmentRange {
vmaddr: u64,
vmsize: u64,
fileoff: u64,
}
#[derive(Debug)]
pub struct MachOContext {
pub header: MachHeader64,
pub base_offset: usize,
pub data: Vec<u8>,
pub load_commands: Vec<LoadCommandInfo>,
segment_indices: HashMap<String, usize>,
segment_ranges: Vec<SegmentRange>,
}
impl MachOContext {
fn read_header(data: &[u8]) -> Result<MachHeader64> {
let magic = data
.get(..4)
.map(crate::util::read_u32_le)
.ok_or(Error::BufferTooSmall {
needed: 4,
available: data.len(),
})?;
let size = match magic {
MH_MAGIC => 28,
MH_MAGIC_64 => 32,
_ => return Err(Error::InvalidMachoMagic(magic)),
};
if data.len() < size {
return Err(Error::BufferTooSmall {
needed: size,
available: data.len(),
});
}
let mut bytes = [0u8; 32];
bytes[..size].copy_from_slice(&data[..size]);
Ok(MachHeader64::read_from_prefix(&bytes).unwrap().0)
}
pub fn is_64(&self) -> bool {
self.header.magic == MH_MAGIC_64
}
pub fn header_size(&self) -> usize {
if self.is_64() { 32 } else { 28 }
}
pub fn pointer_size(&self) -> usize {
if self.is_64() { 8 } else { 4 }
}
pub fn segment_command_size(&self) -> usize {
if self.is_64() { 72 } else { 56 }
}
pub fn section_size(&self) -> usize {
if self.is_64() { 80 } else { 68 }
}
pub fn nlist_size(&self) -> usize {
if self.is_64() { 16 } else { 12 }
}
pub fn read_pointer(&self, offset: usize) -> Result<u64> {
if self.is_64() {
self.read_u64(offset)
} else {
Ok(self.read_u32(offset)? as u64)
}
}
pub fn write_pointer(&mut self, offset: usize, value: u64) -> Result<()> {
if self.is_64() {
self.write_u64(offset, value)
} else {
let value = u32::try_from(value).map_err(|_| Error::Parse {
offset,
reason: "32-bit pointer overflow".into(),
})?;
self.write_u32(offset, value)
}
}
pub fn write_segment(&mut self, offset: usize, segment: &SegmentCommand64) -> Result<()> {
self.write_at(offset, &self.segment_bytes(segment)?)
}
pub fn segment_bytes(&self, segment: &SegmentCommand64) -> Result<Vec<u8>> {
let offset = 0;
if self.is_64() {
return Ok(segment.as_bytes().to_vec());
}
let mut bytes = Vec::with_capacity(56);
bytes.extend_from_slice(&LC_SEGMENT.to_le_bytes());
bytes.extend_from_slice(&segment.cmdsize.to_le_bytes());
bytes.extend_from_slice(&segment.segname);
for value in [
segment.vmaddr,
segment.vmsize,
segment.fileoff,
segment.filesize,
] {
let value = u32::try_from(value).map_err(|_| Error::Parse {
offset,
reason: "32-bit segment field overflow".into(),
})?;
bytes.extend_from_slice(&value.to_le_bytes());
}
for value in [
segment.maxprot,
segment.initprot,
segment.nsects,
segment.flags,
] {
bytes.extend_from_slice(&value.to_le_bytes());
}
Ok(bytes)
}
pub fn write_section(&mut self, offset: usize, section: &Section64) -> Result<()> {
self.write_at(offset, &self.section_bytes(section)?)
}
pub fn section_bytes(&self, section: &Section64) -> Result<Vec<u8>> {
let offset = 0;
if self.is_64() {
return Ok(section.as_bytes().to_vec());
}
let mut bytes = Vec::with_capacity(68);
bytes.extend_from_slice(§ion.sectname);
bytes.extend_from_slice(§ion.segname);
for value in [section.addr, section.size] {
let value = u32::try_from(value).map_err(|_| Error::Parse {
offset,
reason: "32-bit section field overflow".into(),
})?;
bytes.extend_from_slice(&value.to_le_bytes());
}
for value in [
section.offset,
section.align,
section.reloff,
section.nreloc,
section.flags,
section.reserved1,
section.reserved2,
] {
bytes.extend_from_slice(&value.to_le_bytes());
}
Ok(bytes)
}
pub fn new(data: &[u8], base_offset: usize) -> Result<Self> {
let header = Self::read_header(data)?;
let mut ctx = Self {
header: header.clone(),
base_offset,
data: data.to_vec(),
load_commands: Vec::with_capacity(32), segment_indices: HashMap::new(),
segment_ranges: Vec::with_capacity(8), };
ctx.parse_load_commands()?;
ctx.build_segment_ranges();
Ok(ctx)
}
fn build_segment_ranges(&mut self) {
self.segment_ranges.clear();
for lc in &self.load_commands {
if let LoadCommandInfo::Segment(seg) = lc {
if seg.command.vmsize > 0 {
self.segment_ranges.push(SegmentRange {
vmaddr: seg.command.vmaddr,
vmsize: seg.command.filesize,
fileoff: seg.command.fileoff,
});
}
}
}
self.segment_ranges.sort_by_key(|r| r.vmaddr);
}
pub fn refresh(&mut self) -> Result<()> {
self.header = Self::read_header(&self.data)?;
self.load_commands.clear();
self.segment_indices.clear();
self.parse_load_commands()?;
self.build_segment_ranges();
Ok(())
}
pub fn from_cache_slice(cache_data: &[u8], offset: usize, size: usize) -> Result<Self> {
if offset + size > cache_data.len() {
return Err(Error::BufferTooSmall {
needed: offset + size,
available: cache_data.len(),
});
}
Self::new(&cache_data[offset..offset + size], offset)
}
fn parse_load_commands(&mut self) -> Result<()> {
let mut offset = self.header_size();
let end_offset = self.header_size() + self.header.sizeofcmds as usize;
for _ in 0..self.header.ncmds {
if offset + LoadCommand::SIZE > end_offset
|| offset + LoadCommand::SIZE > self.data.len()
{
return Err(Error::LoadCommandOverflow { offset });
}
let lc = LoadCommand::read_from_prefix(&self.data[offset..])
.map_err(|_| Error::Parse {
offset,
reason: "failed to parse load command".into(),
})?
.0;
if lc.cmdsize < 8
|| offset + lc.cmdsize as usize > end_offset
|| offset + lc.cmdsize as usize > self.data.len()
{
return Err(Error::LoadCommandOverflow { offset });
}
let cmd_data = &self.data[offset..offset + lc.cmdsize as usize];
let cmd_info = self.parse_load_command(lc.cmd, cmd_data, offset)?;
if let LoadCommandInfo::Segment(ref seg) = cmd_info {
self.segment_indices
.insert(seg.name().to_string(), self.load_commands.len());
}
self.load_commands.push(cmd_info);
offset += lc.cmdsize as usize;
}
Ok(())
}
fn parse_load_command(&self, cmd: u32, data: &[u8], offset: usize) -> Result<LoadCommandInfo> {
match cmd {
LC_SEGMENT | LC_SEGMENT_64 => {
let is_64 = cmd == LC_SEGMENT_64;
if is_64 != self.is_64() {
return Err(Error::Parse {
offset,
reason: "segment command width differs from Mach-O header".into(),
});
}
let segment_size = self.segment_command_size();
let section_size = self.section_size();
if data.len() < segment_size {
return Err(Error::LoadCommandOverflow { offset });
}
let seg = if is_64 {
SegmentCommand64::read_from_prefix(data).unwrap().0
} else {
let u = |i| crate::util::read_u32_le(&data[i..]);
SegmentCommand64 {
cmd,
cmdsize: u(4),
segname: data[8..24].try_into().unwrap(),
vmaddr: u(24) as u64,
vmsize: u(28) as u64,
fileoff: u(32) as u64,
filesize: u(36) as u64,
maxprot: u(40),
initprot: u(44),
nsects: u(48),
flags: u(52),
}
};
if (seg.nsects as usize)
.checked_mul(section_size)
.and_then(|n| segment_size.checked_add(n))
.is_none_or(|n| n > data.len())
{
return Err(Error::LoadCommandOverflow { offset });
}
let mut sections = Vec::with_capacity(seg.nsects as usize);
for i in 0..seg.nsects as usize {
let local = segment_size + i * section_size;
let raw = &data[local..local + section_size];
let section = if is_64 {
Section64::read_from_prefix(raw).unwrap().0
} else {
let u = |i| crate::util::read_u32_le(&raw[i..]);
Section64 {
sectname: raw[..16].try_into().unwrap(),
segname: raw[16..32].try_into().unwrap(),
addr: u(32) as u64,
size: u(36) as u64,
offset: u(40),
align: u(44),
reloff: u(48),
nreloc: u(52),
flags: u(56),
reserved1: u(60),
reserved2: u(64),
reserved3: 0,
}
};
sections.push(SectionInfo {
section,
struct_offset: offset + local,
});
}
Ok(LoadCommandInfo::Segment(SegmentInfo {
command: seg,
command_offset: offset,
sections,
}))
}
LC_SYMTAB => {
let symtab = SymtabCommand::read_from_prefix(data)
.map_err(|_| Error::Parse {
offset,
reason: "failed to parse symtab command".into(),
})?
.0;
Ok(LoadCommandInfo::Symtab {
command: symtab.clone(),
offset,
})
}
LC_DYSYMTAB => {
let dysymtab = DysymtabCommand::read_from_prefix(data)
.map_err(|_| Error::Parse {
offset,
reason: "failed to parse dysymtab command".into(),
})?
.0;
Ok(LoadCommandInfo::Dysymtab {
command: dysymtab.clone(),
offset,
})
}
LC_DYLD_INFO | LC_DYLD_INFO_ONLY => {
let dyld_info = DyldInfoCommand::read_from_prefix(data)
.map_err(|_| Error::Parse {
offset,
reason: "failed to parse dyld info command".into(),
})?
.0;
Ok(LoadCommandInfo::DyldInfo {
command: dyld_info.clone(),
offset,
})
}
LC_CODE_SIGNATURE
| LC_SEGMENT_SPLIT_INFO
| LC_FUNCTION_STARTS
| LC_DATA_IN_CODE
| LC_DYLD_EXPORTS_TRIE
| LC_DYLD_CHAINED_FIXUPS
| LC_LINKER_OPTIMIZATION_HINT
| LC_ATOM_INFO => {
let linkedit = LinkeditDataCommand::read_from_prefix(data)
.map_err(|_| Error::Parse {
offset,
reason: "failed to parse linkedit data command".into(),
})?
.0;
Ok(LoadCommandInfo::LinkeditData {
command: linkedit.clone(),
offset,
})
}
LC_LOAD_DYLIB | LC_LOAD_WEAK_DYLIB | LC_REEXPORT_DYLIB | LC_LAZY_LOAD_DYLIB
| LC_LOAD_UPWARD_DYLIB | LC_ID_DYLIB => {
let dylib = DylibCommand::read_from_prefix(data)
.map_err(|_| Error::Parse {
offset,
reason: "failed to parse dylib command".into(),
})?
.0;
let name_offset = dylib.dylib.name_offset as usize;
let name = if name_offset < data.len() {
let name_bytes = &data[name_offset..];
let end = name_bytes
.iter()
.position(|&b| b == 0)
.unwrap_or(name_bytes.len());
String::from_utf8_lossy(&name_bytes[..end]).to_string()
} else {
String::new()
};
Ok(LoadCommandInfo::Dylib {
command: dylib.clone(),
name,
offset,
})
}
LC_UUID => {
let uuid = UuidCommand::read_from_prefix(data)
.map_err(|_| Error::Parse {
offset,
reason: "failed to parse uuid command".into(),
})?
.0;
Ok(LoadCommandInfo::Uuid {
command: uuid.clone(),
offset,
})
}
LC_BUILD_VERSION => {
let build_version = BuildVersionCommand::read_from_prefix(data)
.map_err(|_| Error::Parse {
offset,
reason: "failed to parse build version command".into(),
})?
.0;
Ok(LoadCommandInfo::BuildVersion {
command: build_version.clone(),
offset,
})
}
LC_FILESET_ENTRY => {
let entry = FilesetEntryCommand::read_from_prefix(data)
.map_err(|_| Error::Parse {
offset,
reason: "failed to parse fileset entry command".into(),
})?
.0;
let id_offset = entry.entry_id_offset as usize;
let entry_id = if id_offset < data.len() {
let name_bytes = &data[id_offset..];
let end = name_bytes
.iter()
.position(|&b| b == 0)
.unwrap_or(name_bytes.len());
String::from_utf8_lossy(&name_bytes[..end]).to_string()
} else {
String::new()
};
Ok(LoadCommandInfo::FilesetEntry {
command: entry.clone(),
entry_id,
offset,
})
}
_ => {
let lc = LoadCommand::read_from_prefix(data)
.map_err(|_| Error::Parse {
offset,
reason: "failed to parse load command".into(),
})?
.0;
Ok(LoadCommandInfo::Unknown {
cmd,
cmdsize: lc.cmdsize,
offset,
})
}
}
}
pub fn segment(&self, name: &str) -> Option<&SegmentInfo> {
self.segment_indices.get(name).and_then(|&idx| {
if let LoadCommandInfo::Segment(ref seg) = self.load_commands[idx] {
Some(seg)
} else {
None
}
})
}
pub fn segment_mut(&mut self, name: &str) -> Option<&mut SegmentInfo> {
let idx = *self.segment_indices.get(name)?;
if let LoadCommandInfo::Segment(ref mut seg) = self.load_commands[idx] {
Some(seg)
} else {
None
}
}
pub fn segments(&self) -> impl Iterator<Item = &SegmentInfo> {
self.load_commands.iter().filter_map(|lc| {
if let LoadCommandInfo::Segment(seg) = lc {
Some(seg)
} else {
None
}
})
}
pub fn section(&self, segment: &str, section: &str) -> Option<&SectionInfo> {
self.segment(segment)?.section(section)
}
pub fn text_segment(&self) -> Option<&SegmentInfo> {
self.segment("__TEXT")
}
pub fn data_segment(&self) -> Option<&SegmentInfo> {
self.segment("__DATA")
}
pub fn linkedit_segment(&self) -> Option<&SegmentInfo> {
self.segment("__LINKEDIT")
}
pub fn symtab(&self) -> Option<&SymtabCommand> {
self.load_commands.iter().find_map(|lc| {
if let LoadCommandInfo::Symtab { command, .. } = lc {
Some(command)
} else {
None
}
})
}
pub fn dysymtab(&self) -> Option<&DysymtabCommand> {
self.load_commands.iter().find_map(|lc| {
if let LoadCommandInfo::Dysymtab { command, .. } = lc {
Some(command)
} else {
None
}
})
}
pub fn dyld_info(&self) -> Option<&DyldInfoCommand> {
self.load_commands.iter().find_map(|lc| {
if let LoadCommandInfo::DyldInfo { command, .. } = lc {
Some(command)
} else {
None
}
})
}
pub fn dylibs(&self) -> impl Iterator<Item = (&str, u32)> {
self.load_commands.iter().filter_map(|lc| {
if let LoadCommandInfo::Dylib { command, name, .. } = lc {
Some((name.as_str(), command.cmd))
} else {
None
}
})
}
pub fn dependencies(&self) -> Vec<String> {
self.load_commands
.iter()
.filter_map(|lc| {
if let LoadCommandInfo::Dylib { command, name, .. } = lc {
match command.cmd {
LC_LOAD_DYLIB | LC_LOAD_WEAK_DYLIB | LC_REEXPORT_DYLIB
| LC_LAZY_LOAD_DYLIB | LC_LOAD_UPWARD_DYLIB => Some(name.clone()),
_ => None,
}
} else {
None
}
})
.collect()
}
pub fn is_arm64(&self) -> bool {
self.header.is_arm64()
}
pub fn is_arm64e(&self) -> bool {
self.header.is_arm64e()
}
#[inline]
pub fn read_at(&self, offset: usize, len: usize) -> Result<&[u8]> {
if offset + len > self.data.len() {
return Err(Error::BufferTooSmall {
needed: offset + len,
available: self.data.len(),
});
}
Ok(&self.data[offset..offset + len])
}
#[inline(always)]
pub fn read_u32(&self, offset: usize) -> Result<u32> {
let bytes = self.read_at(offset, 4)?;
Ok(u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]))
}
#[inline(always)]
pub fn read_u64(&self, offset: usize) -> Result<u64> {
let bytes = self.read_at(offset, 8)?;
Ok(u64::from_le_bytes([
bytes[0], bytes[1], bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7],
]))
}
#[inline]
pub fn write_at(&mut self, offset: usize, data: &[u8]) -> Result<()> {
if offset + data.len() > self.data.len() {
return Err(Error::BufferTooSmall {
needed: offset + data.len(),
available: self.data.len(),
});
}
self.data[offset..offset + data.len()].copy_from_slice(data);
Ok(())
}
#[inline(always)]
pub fn write_u32(&mut self, offset: usize, value: u32) -> Result<()> {
self.write_at(offset, &value.to_le_bytes())
}
#[inline(always)]
pub fn write_u64(&mut self, offset: usize, value: u64) -> Result<()> {
self.write_at(offset, &value.to_le_bytes())
}
pub fn write_struct<T: IntoBytes + Immutable>(
&mut self,
offset: usize,
value: &T,
) -> Result<()> {
let bytes = value.as_bytes();
self.write_at(offset, bytes)
}
pub fn sync_header(&mut self) -> Result<()> {
let header = self.header.clone();
self.write_at(0, &header.as_bytes()[..self.header_size()])
}
pub fn load_commands_size(&self) -> usize {
self.load_commands.iter().map(|lc| lc.size() as usize).sum()
}
pub fn available_load_command_space(&self) -> usize {
let text = self
.text_segment()
.map(|s| s.command.fileoff as usize)
.unwrap_or(usize::MAX);
let used = self.header_size() + self.load_commands_size();
text.saturating_sub(used)
}
#[inline]
pub fn addr_to_offset(&self, addr: u64) -> Option<usize> {
let idx = self
.segment_ranges
.partition_point(|r| r.vmaddr + r.vmsize <= addr);
if idx < self.segment_ranges.len() {
let range = &self.segment_ranges[idx];
if addr >= range.vmaddr && addr < range.vmaddr + range.vmsize {
let offset = range.fileoff + (addr - range.vmaddr);
return Some(offset as usize);
}
}
None
}
pub fn offset_to_addr(&self, offset: usize) -> Option<u64> {
let offset = offset as u64;
for seg in self.segments() {
if offset >= seg.command.fileoff && offset < seg.command.fileoff + seg.command.filesize
{
let addr = seg.command.vmaddr + (offset - seg.command.fileoff);
return Some(addr);
}
}
None
}
pub fn contains_addr(&self, addr: u64) -> bool {
self.segments()
.any(|seg| addr >= seg.command.vmaddr && addr < seg.command.vmaddr + seg.command.vmsize)
}
pub fn as_bytes(&self) -> &[u8] {
&self.data
}
pub fn as_bytes_mut(&mut self) -> &mut [u8] {
&mut self.data
}
}
use zerocopy::Immutable;
#[cfg(test)]
mod tests {
use super::*;
fn create_minimal_macho() -> Vec<u8> {
let mut data = vec![0u8; 0x1000];
let header = MachHeader64 {
magic: MH_MAGIC_64,
cputype: CPU_TYPE_ARM64,
cpusubtype: CPU_SUBTYPE_ARM64_ALL,
filetype: MH_DYLIB,
ncmds: 1,
sizeofcmds: SegmentCommand64::SIZE as u32,
flags: 0,
reserved: 0,
};
data[..MachHeader64::SIZE].copy_from_slice(header.as_bytes());
let mut seg = SegmentCommand64::default();
seg.set_name("__TEXT");
seg.vmaddr = 0x100000000;
seg.vmsize = 0x1000;
seg.fileoff = 0;
seg.filesize = 0x1000;
data[MachHeader64::SIZE..MachHeader64::SIZE + SegmentCommand64::SIZE]
.copy_from_slice(seg.as_bytes());
data
}
#[test]
fn test_parse_minimal_macho() {
let data = create_minimal_macho();
let ctx = MachOContext::new(&data, 0).unwrap();
assert!(ctx.header.is_valid());
assert!(ctx.is_arm64());
assert_eq!(ctx.header.ncmds, 1);
assert!(ctx.segment("__TEXT").is_some());
}
}