pub mod le;
pub mod strings;
use std::collections::{HashMap, HashSet};
use serde::{Deserialize, Serialize};
use object::{FileKind, Object, ObjectSection, ObjectSegment, ObjectSymbol};
use crate::disasm::Arch;
use crate::error::{Error, Result};
use crate::loader::le::{LeImage, LeTarget};
pub const MAX_SEGMENTS: usize = 256;
pub const MAX_SECTIONS: usize = 2048;
pub const MAX_MAPPED_BYTES: u64 = 256 * 1024 * 1024;
pub const MAX_IMPORTS: usize = 100_000;
pub const MAX_EXPORTS: usize = 100_000;
pub const MAX_SYMBOLS: usize = 100_000;
pub const MAX_INPUT_BYTES: u64 = 512 * 1024 * 1024;
pub const MAX_NAME_BYTES: usize = 4096;
pub const MAX_DEMANGLED_BYTES: usize = 8192;
pub const MAX_METADATA_BYTES: u64 = 16 * 1024 * 1024;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Segment {
pub vaddr: u64,
pub mem_size: u64,
pub data: Vec<u8>,
pub readable: bool,
pub writable: bool,
pub executable: bool,
}
impl Segment {
#[must_use]
pub fn arch(&self) -> Arch {
Arch::X86_32
}
#[must_use]
pub fn file_size(&self) -> usize {
self.data.len()
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum BinaryFormat {
Elf,
Pe,
MachO,
Coff,
Le,
Raw,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Section {
pub name: String,
pub vaddr: u64,
pub size: u64,
pub file_off: u64,
pub data: Vec<u8>,
pub readable: bool,
pub writable: bool,
pub executable: bool,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct ImportRef {
pub library: String,
pub name: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ordinal: Option<u32>,
#[serde(default)]
pub unresolved: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub demangled: Option<String>,
#[serde(default)]
pub address: Option<u64>,
}
impl Serialize for ImportRef {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
let mut len = 5;
if self.ordinal.is_some() {
len += 1;
}
if self.demangled.is_some() {
len += 1;
}
let mut st = serializer.serialize_struct("ImportRef", len)?;
st.serialize_field("library", &self.library)?;
st.serialize_field("name", &self.name)?;
if self.ordinal.is_some() {
st.serialize_field("ordinal", &self.ordinal)?;
} else {
st.skip_field("ordinal")?;
}
st.serialize_field("unresolved", &self.unresolved)?;
if self.demangled.is_some() {
st.serialize_field("demangled", &self.demangled)?;
} else {
st.skip_field("demangled")?;
}
st.serialize_field("address", &self.address)?;
st.serialize_field("address_hex", &self.address.map(crate::addr_hex))?;
st.end()
}
}
type LeImportKey = (String, String, Option<u32>, bool, Option<String>);
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct ExportRef {
pub name: String,
pub address: Option<u64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub ordinal: Option<u32>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub demangled: Option<String>,
}
impl Serialize for ExportRef {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
let mut len = 3;
if self.ordinal.is_some() {
len += 1;
}
if self.demangled.is_some() {
len += 1;
}
let mut st = serializer.serialize_struct("ExportRef", len)?;
st.serialize_field("name", &self.name)?;
st.serialize_field("address", &self.address)?;
st.serialize_field("address_hex", &self.address.map(crate::addr_hex))?;
if self.ordinal.is_some() {
st.serialize_field("ordinal", &self.ordinal)?;
} else {
st.skip_field("ordinal")?;
}
if self.demangled.is_some() {
st.serialize_field("demangled", &self.demangled)?;
} else {
st.skip_field("demangled")?;
}
st.end()
}
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct SymbolRef {
pub name: String,
pub address: u64,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub demangled: Option<String>,
}
impl Serialize for SymbolRef {
fn serialize<S: serde::Serializer>(
&self,
serializer: S,
) -> std::result::Result<S::Ok, S::Error> {
use serde::ser::SerializeStruct;
let mut len = 3;
if self.demangled.is_some() {
len += 1;
}
let mut st = serializer.serialize_struct("SymbolRef", len)?;
st.serialize_field("name", &self.name)?;
st.serialize_field("address", &self.address)?;
st.serialize_field("address_hex", &crate::addr_hex(self.address))?;
if self.demangled.is_some() {
st.serialize_field("demangled", &self.demangled)?;
} else {
st.skip_field("demangled")?;
}
st.end()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct LoadedBinary {
pub format: BinaryFormat,
pub arch: Arch,
pub entry: Option<u64>,
pub segments: Vec<Segment>,
pub sections: Vec<Section>,
pub imports: Vec<ImportRef>,
pub exports: Vec<ExportRef>,
pub symbols: Vec<SymbolRef>,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct RawOptions {
pub base: u64,
pub arch: Arch,
pub entry: Option<u64>,
}
#[must_use]
pub fn is_recognized(bytes: &[u8]) -> bool {
le::is_le(bytes) || FileKind::parse(bytes).is_ok()
}
pub fn load(bytes: &[u8]) -> Result<LoadedBinary> {
load_with_slice(bytes, None)
}
pub fn load_with_slice(bytes: &[u8], fat_arch: Option<&str>) -> Result<LoadedBinary> {
if bytes.is_empty() {
return Err(Error::Invalid("empty input".to_string()));
}
if bytes.len() as u64 > MAX_INPUT_BYTES {
return Err(Error::Limit("input exceeds 512 MiB".to_string()));
}
if le::is_le(bytes) {
return Ok(convert_le(le::parse_le(bytes)?));
}
let kind = FileKind::parse(bytes)
.map_err(|e| Error::Invalid(format!("unrecognized binary format: {e}")))?;
match kind {
FileKind::Elf32 | FileKind::Elf64 => load_object(bytes, BinaryFormat::Elf),
FileKind::Pe32 | FileKind::Pe64 => load_object(bytes, BinaryFormat::Pe),
FileKind::MachO32 | FileKind::MachO64 => load_object(bytes, BinaryFormat::MachO),
FileKind::MachOFat32 | FileKind::MachOFat64 => load_fat_slice(bytes, kind, fat_arch),
FileKind::Coff => load_object(bytes, BinaryFormat::Coff),
other => Err(Error::Unsupported(format!("file kind {other:?}"))),
}
}
#[must_use]
pub fn raw_arch_name(arch: Arch) -> &'static str {
match arch {
Arch::X86_64 => "x86_64",
Arch::X86_32 => "x86_32",
Arch::Aarch64 => "aarch64",
Arch::Arm32 => "arm32",
Arch::Thumb => "thumb",
}
}
#[must_use]
pub fn raw_entry_alignment(arch: Arch) -> u64 {
match arch {
Arch::X86_64 | Arch::X86_32 => 1,
Arch::Aarch64 | Arch::Arm32 => 4,
Arch::Thumb => 2,
}
}
pub fn load_raw(bytes: &[u8], opts: RawOptions) -> Result<LoadedBinary> {
if bytes.is_empty() {
return Err(Error::Invalid("empty raw input".to_string()));
}
if bytes.len() as u64 > MAX_MAPPED_BYTES {
return Err(Error::Limit("raw blob exceeds 256 MiB".to_string()));
}
let len = bytes.len() as u64;
let end = opts.base.checked_add(len).ok_or_else(|| {
Error::Invalid(format!(
"raw base {:#x} with length {len} overflows address space",
opts.base
))
})?;
if let Some(entry) = opts.entry {
if entry < opts.base || entry >= end {
return Err(Error::Invalid(format!(
"raw entry {entry:#x} outside mapped range {:#x}..{end:#x}",
opts.base
)));
}
let align = raw_entry_alignment(opts.arch);
if entry % align != 0 {
return Err(Error::Invalid(format!(
"raw entry {entry:#x} misaligned for {} (needs {align}-byte alignment)",
raw_arch_name(opts.arch)
)));
}
}
Ok(LoadedBinary {
format: BinaryFormat::Raw,
arch: opts.arch,
entry: opts.entry,
segments: vec![Segment {
vaddr: opts.base,
mem_size: bytes.len() as u64,
data: bytes.to_vec(),
readable: true,
writable: true,
executable: true,
}],
sections: Vec::new(),
imports: Vec::new(),
exports: Vec::new(),
symbols: Vec::new(),
})
}
pub fn arch_from_object(arch: object::Architecture) -> Result<Arch> {
use object::Architecture as A;
match arch {
A::X86_64 | A::X86_64_X32 => Ok(Arch::X86_64),
A::I386 => Ok(Arch::X86_32),
A::Aarch64 | A::Aarch64_Ilp32 => Ok(Arch::Aarch64),
A::Arm => Ok(Arch::Arm32),
other => Err(Error::Unsupported(format!("architecture {other:?}"))),
}
}
#[must_use]
pub fn canonical_code_addr(arch: Arch, addr: u64) -> u64 {
match arch {
Arch::Arm32 => addr & !1,
_ => addr,
}
}
fn load_object(bytes: &[u8], format: BinaryFormat) -> Result<LoadedBinary> {
let file =
object::File::parse(bytes).map_err(|e| Error::Invalid(format!("object parse: {e}")))?;
let arch = arch_from_object(file.architecture())?;
let mut meta_bytes: u64 = 0;
let mut demangle_cache: HashMap<String, Option<String>> = HashMap::new();
let mut mapped: u64 = 0;
let mut segments = Vec::new();
for seg in file.segments() {
if segments.len() >= MAX_SEGMENTS {
return Err(Error::Limit("segments exceed cap".to_string()));
}
let data = seg
.data()
.map_err(|e| Error::Invalid(format!("bad segment data: {e}")))?;
mapped = mapped
.checked_add(data.len() as u64)
.filter(|m| *m <= MAX_MAPPED_BYTES)
.ok_or_else(|| Error::Limit("segment bytes exceed 256 MiB".to_string()))?;
let perms = seg.permissions();
segments.push(Segment {
vaddr: seg.address(),
mem_size: seg.size(),
data: data.to_vec(),
readable: perms.readable(),
writable: perms.writable(),
executable: perms.executable(),
});
}
let mut smapped: u64 = 0;
let mut sections = Vec::new();
for sec in file.sections() {
if sections.len() >= MAX_SECTIONS {
return Err(Error::Limit("sections exceed cap".to_string()));
}
let name = match sec.name_bytes() {
Ok(b) => decode_owned_name(b, &mut meta_bytes)?,
Err(_) => {
account_meta(&mut meta_bytes, "<invalid>".len())?;
"<invalid>".to_string()
}
};
let data = match sec.data() {
Ok(d) => d,
Err(_) if sec.size() == 0 || is_bss(sec.kind()) => &[],
Err(e) => return Err(Error::Invalid(format!("bad section data: {e}"))),
};
smapped = smapped
.checked_add(data.len() as u64)
.filter(|m| *m <= MAX_MAPPED_BYTES)
.ok_or_else(|| Error::Limit("section bytes exceed 256 MiB".to_string()))?;
let (readable, writable, executable) = section_perms(sec.kind());
let (file_off, _) = sec.file_range().unwrap_or((0, 0));
sections.push(Section {
name,
vaddr: sec.address(),
size: sec.size(),
file_off,
data: data.to_vec(),
readable,
writable,
executable,
});
}
let entry = match file.entry() {
0 => None,
e => Some(e),
};
let mut imports = Vec::new();
for imp in file
.imports()
.map_err(|e| Error::Invalid(format!("bad import table: {e}")))?
{
let imp = imp.map_err(|e| Error::Invalid(format!("bad import: {e}")))?;
if imports.len() >= MAX_IMPORTS {
return Err(Error::Limit("imports exceed cap".to_string()));
}
imports.push(import_from_object(
imp.library(),
imp.name(),
&mut meta_bytes,
&mut demangle_cache,
)?);
}
if format == BinaryFormat::MachO
&& let Some(stubs) = macho_stub_addresses(&file, bytes, imports.len())
{
for (imp, addr) in imports.iter_mut().zip(stubs) {
imp.address = Some(addr);
}
}
if format == BinaryFormat::Pe
&& let Some(slots) = pe_iat_slots(bytes, imports.len())
{
for (imp, slot) in imports.iter_mut().zip(slots) {
imp.address = Some(slot);
}
}
if format == BinaryFormat::Elf {
elf_got_slots(&file, bytes, arch, &mut imports);
}
let mut exports = Vec::new();
for exp in file
.exports()
.map_err(|e| Error::Invalid(format!("bad export table: {e}")))?
{
let exp = exp.map_err(|e| Error::Invalid(format!("bad export: {e}")))?;
if exports.len() >= MAX_EXPORTS {
return Err(Error::Limit("exports exceed cap".to_string()));
}
exports.push(export_from_object(
exp.name(),
match exp.target() {
object::ExportTarget::Address { address } => Some(address),
_ => None,
},
&mut meta_bytes,
&mut demangle_cache,
)?);
}
let symbols = collect_symbols(
&file,
arch,
§ions,
&segments,
&mut meta_bytes,
&mut demangle_cache,
)?;
Ok(LoadedBinary {
format,
arch,
entry,
segments,
sections,
imports,
exports,
symbols,
})
}
fn macho_stub_addresses<'a>(
file: &object::File<'a, &'a [u8]>,
bytes: &'a [u8],
import_count: usize,
) -> Option<Vec<u64>> {
use object::{Object, ObjectSection};
if import_count == 0 || import_count > MAX_IMPORTS {
return None;
}
if !is_thin_le_macho(bytes) {
return None;
}
if macho_has_chained_fixups(bytes) != Some(false) {
return None;
}
let mut addrs = Vec::new();
let mut stubbed = false;
for sec in file.sections() {
if !matches!(sec.name(), Ok("__stubs" | "__auth_stubs")) {
continue;
}
let in_text = sec
.segment_name()
.ok()
.flatten()
.is_some_and(|s| s.starts_with("__TEXT"));
let stride = match sec.flags() {
object::SectionFlags::MachO { flags, reserved2 }
if flags.typ() == object::macho::S_SYMBOL_STUBS && reserved2 != 0 =>
{
u64::from(reserved2)
}
_ => return None,
};
if !in_text {
return None;
}
let size = sec.size();
if size == 0 || size % stride != 0 {
return None;
}
let base = sec.address();
for i in 0..size / stride {
addrs.push(base.checked_add(i.checked_mul(stride)?)?);
if addrs.len() > import_count {
return None;
}
}
stubbed = true;
}
if !stubbed || addrs.len() != import_count {
return None;
}
Some(addrs)
}
fn pe_iat_slots(bytes: &[u8], import_count: usize) -> Option<Vec<u64>> {
use object::read::pe::{PeFile32, PeFile64};
if import_count == 0 || import_count > MAX_IMPORTS {
return None;
}
match FileKind::parse(bytes) {
Ok(FileKind::Pe32) => PeFile32::parse(bytes)
.ok()
.and_then(|pe| pe_slots(&pe, import_count, 4)),
Ok(FileKind::Pe64) => PeFile64::parse(bytes)
.ok()
.and_then(|pe| pe_slots(&pe, import_count, 8)),
_ => None,
}
}
fn pe_slots<Pe>(
pe: &object::read::pe::PeFile<'_, Pe>,
import_count: usize,
stride: u64,
) -> Option<Vec<u64>>
where
Pe: object::read::pe::ImageNtHeaders,
{
use object::LittleEndian as LE;
let table = pe.import_table().ok()??;
let base = pe.relative_address_base();
let mut descs = table.descriptors().ok()?;
let mut slots = Vec::new();
while let Some(desc) = descs.next().ok()? {
let first_thunk = desc.first_thunk.get(LE);
let mut thunks = table.thunks(first_thunk).ok()?;
let mut idx: u64 = 0;
while thunks.next::<Pe>().ok()?.is_some() {
if slots.len() >= MAX_IMPORTS {
return None;
}
let rva = u64::from(first_thunk).checked_add(idx.checked_mul(stride)?)?;
slots.push(base.checked_add(rva)?);
idx += 1;
}
}
if slots.len() != import_count {
return None;
}
Some(slots)
}
fn elf_got_slots<'a>(
file: &object::File<'a, &'a [u8]>,
bytes: &[u8],
arch: Arch,
imports: &mut [ImportRef],
) {
if imports.is_empty() {
return;
}
let jump_slot: u32 = match arch {
Arch::X86_64 | Arch::X86_32 => 7,
Arch::Arm32 | Arch::Thumb => 22,
Arch::Aarch64 => 1026,
};
let is64 = bytes.get(4).is_some_and(|&c| c == 2);
let le = file.endianness() == object::Endianness::Little;
let mut dynsyms: Vec<Vec<u8>> = vec![Vec::new()];
dynsyms.extend(
file.dynamic_symbols()
.map(|s| s.name_bytes().unwrap_or_default().to_vec()),
);
if dynsyms.len() < 2 {
return;
}
let mut assigned = 0usize;
for sec in file.sections() {
if assigned >= imports.len() || assigned >= MAX_IMPORTS {
break;
}
let is_rela = match sec.name() {
Ok(".rela.plt") => true,
Ok(".rel.plt") => false,
_ => continue,
};
let data = match sec.data() {
Ok(d) => d,
Err(_) => continue,
};
let entry = if is64 {
if is_rela { 24 } else { 16 }
} else if is_rela {
12
} else {
8
};
if data.is_empty() || data.len() % entry != 0 {
continue;
}
let get32 = |off: usize| -> Option<u32> {
let b: [u8; 4] = data.get(off..off + 4)?.try_into().ok()?;
Some(if le {
u32::from_le_bytes(b)
} else {
u32::from_be_bytes(b)
})
};
let get64 = |off: usize| -> Option<u64> {
let b: [u8; 8] = data.get(off..off + 8)?.try_into().ok()?;
Some(if le {
u64::from_le_bytes(b)
} else {
u64::from_be_bytes(b)
})
};
let mut off = 0;
while off + entry <= data.len() {
if assigned >= MAX_IMPORTS {
break;
}
let (slot, sym, rtype) = if is64 {
let (Some(r_offset), Some(r_info)) = (get64(off), get64(off + 8)) else {
break;
};
(r_offset, (r_info >> 32) as usize, r_info as u32)
} else {
let (Some(r_offset), Some(r_info)) = (get32(off), get32(off + 4)) else {
break;
};
(u64::from(r_offset), (r_info >> 8) as usize, r_info & 0xff)
};
off += entry;
if rtype != jump_slot || slot == 0 {
continue;
}
let sym_name = match dynsyms.get(sym) {
Some(n) if !n.is_empty() => n,
_ => continue,
};
let want = String::from_utf8_lossy(sym_name);
if let Some(imp) = imports
.iter_mut()
.find(|i| i.address.is_none() && i.name.as_str() == want.as_ref())
{
imp.address = Some(slot);
assigned += 1;
}
}
}
}
fn is_thin_le_macho(bytes: &[u8]) -> bool {
if bytes.len() < 4 {
return false;
}
let magic = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
magic == 0xFEED_FACE || magic == 0xFEED_FACF
}
fn macho_has_chained_fixups(bytes: &[u8]) -> Option<bool> {
const LC_DYLD_CHAINED_FIXUPS: u32 = 0x8000_0034;
const MAX_COMMANDS: u32 = 4096;
if bytes.len() < 32 {
return None;
}
let magic = u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]);
let header: usize = match magic {
0xFEED_FACE => 28,
0xFEED_FACF => 32,
_ => return None,
};
let ncmds = u32::from_le_bytes([bytes[16], bytes[17], bytes[18], bytes[19]]);
if ncmds > MAX_COMMANDS {
return None;
}
let mut off = header;
for _ in 0..ncmds {
if off.saturating_add(8) > bytes.len() {
return None;
}
let cmd = u32::from_le_bytes([bytes[off], bytes[off + 1], bytes[off + 2], bytes[off + 3]]);
let cmdsize = u32::from_le_bytes([
bytes[off + 4],
bytes[off + 5],
bytes[off + 6],
bytes[off + 7],
]);
if cmd == LC_DYLD_CHAINED_FIXUPS {
return Some(true);
}
if cmdsize < 8 {
return None;
}
off = off.saturating_add(cmdsize as usize);
if off > bytes.len() {
return None;
}
}
Some(false)
}
fn canonical_fat_name(arch: object::Architecture) -> Option<&'static str> {
use object::Architecture as A;
match arch {
A::X86_64 | A::X86_64_X32 => Some("x86_64"),
A::I386 => Some("x86_32"),
A::Aarch64 | A::Aarch64_Ilp32 => Some("aarch64"),
A::Arm => Some("arm32"),
_ => None,
}
}
fn normalize_fat_selector(s: &str) -> Option<&'static str> {
match s.to_lowercase().as_str() {
"x86_64" | "x86-64" => Some("x86_64"),
"x86_32" | "i386" | "x86" => Some("x86_32"),
"aarch64" | "arm64" => Some("aarch64"),
"arm32" | "arm" => Some("arm32"),
_ => None,
}
}
fn fat_label(arch: object::Architecture) -> String {
match canonical_fat_name(arch) {
Some(name) => name.to_string(),
None => format!("{arch:?}"),
}
}
fn fat_table<Fat>(
fat: &object::read::macho::MachOFatFile<'_, Fat>,
) -> Vec<(object::Architecture, u64, u64)>
where
Fat: object::read::macho::FatArch,
{
fat.arches()
.iter()
.map(|a| {
let (offset, size) = a.file_range();
(a.architecture(), offset, size)
})
.collect()
}
fn load_fat_slice(bytes: &[u8], kind: FileKind, fat_arch: Option<&str>) -> Result<LoadedBinary> {
use object::read::macho::{MachOFatFile32, MachOFatFile64};
let table: Vec<(object::Architecture, u64, u64)> = match kind {
FileKind::MachOFat32 => {
let fat = MachOFatFile32::parse(bytes)
.map_err(|e| Error::Invalid(format!("bad fat Mach-O header: {e}")))?;
fat_table(&fat)
}
FileKind::MachOFat64 => {
let fat = MachOFatFile64::parse(bytes)
.map_err(|e| Error::Invalid(format!("bad fat Mach-O header: {e}")))?;
fat_table(&fat)
}
_ => return Err(Error::Invalid("not a fat Mach-O container".to_string())),
};
if table.is_empty() {
return Err(Error::Invalid(
"fat Mach-O container holds no slices".to_string(),
));
}
let available: Vec<String> = table.iter().map(|(a, _, _)| fat_label(*a)).collect();
let Some(want) = fat_arch else {
let plural = if table.len() == 1 { "" } else { "s" };
return Err(Error::Invalid(format!(
"fat Mach-O container with {} slice{plural} requires a slice selection (available: {})",
table.len(),
available.join(", "),
)));
};
let Some(canonical) = normalize_fat_selector(want) else {
return Err(Error::Invalid(format!(
"unknown fat slice arch {want:?} (available: {})",
available.join(", "),
)));
};
let hits: Vec<usize> = table
.iter()
.enumerate()
.filter(|(_, (a, _, _))| canonical_fat_name(*a) == Some(canonical))
.map(|(i, _)| i)
.collect();
let idx = match hits.len() {
0 => {
return Err(Error::Invalid(format!(
"fat Mach-O container has no {canonical} slice (available: {})",
available.join(", "),
)));
}
1 => hits[0],
n => {
return Err(Error::Invalid(format!(
"ambiguous fat slice arch {want:?}: matches {n} slices (available: {})",
available.join(", "),
)));
}
};
let (_, offset, size) = table[idx];
let start = usize::try_from(offset)
.ok()
.and_then(|o| {
usize::try_from(size)
.ok()
.and_then(|s| o.checked_add(s).map(|e| (o, e)))
})
.and_then(|(s, e)| bytes.get(s..e))
.ok_or_else(|| Error::Invalid(format!("bad fat slice range {offset:#x}+{size:#x}")))?;
load_object(start, BinaryFormat::MachO)
}
fn account_meta(meta: &mut u64, len: usize) -> Result<()> {
*meta = meta
.checked_add(len as u64)
.filter(|m| *m <= MAX_METADATA_BYTES)
.ok_or_else(|| Error::Limit("owned metadata exceeds 16 MiB".to_string()))?;
Ok(())
}
fn decode_owned_name(raw: &[u8], meta: &mut u64) -> Result<String> {
if raw.len() > MAX_NAME_BYTES {
return Err(Error::Limit(format!(
"name of {} bytes exceeds {MAX_NAME_BYTES}",
raw.len()
)));
}
let owned = String::from_utf8_lossy(raw).into_owned();
if owned.len() > MAX_NAME_BYTES {
return Err(Error::Limit(format!(
"decoded name of {} bytes exceeds {MAX_NAME_BYTES}",
owned.len()
)));
}
account_meta(meta, owned.len())?;
Ok(owned)
}
fn demangle_bounded(
raw: &str,
meta: &mut u64,
cache: &mut HashMap<String, Option<String>>,
) -> Result<Option<String>> {
if let Some(hit) = cache.get(raw) {
if let Some(d) = hit {
account_meta(meta, d.len())?;
}
return Ok(hit.clone());
}
let demangled = demangle_cpp(raw);
if let Some(d) = &demangled {
if d.len() > MAX_DEMANGLED_BYTES {
return Err(Error::Limit(format!(
"demangled name of {} bytes exceeds {MAX_DEMANGLED_BYTES}",
d.len()
)));
}
account_meta(meta, d.len())?;
}
if cache.len() < 4096 {
cache.insert(raw.to_string(), demangled.clone());
}
Ok(demangled)
}
#[must_use]
pub fn convert_le(img: LeImage) -> LoadedBinary {
let LeImage {
objects,
segments,
entry,
fixups,
entries,
import_modules,
..
} = img;
let mut imports = Vec::new();
let mut seen: HashSet<LeImportKey> = HashSet::with_capacity(fixups.len().min(MAX_IMPORTS));
for fix in &fixups {
let imp = match &fix.target {
LeTarget::Internal { .. } | LeTarget::Entry { .. } => continue,
LeTarget::ImportOrdinal { module, ordinal } => ImportRef {
library: le_module(&import_modules, *module),
name: format!("#{ordinal}"),
ordinal: Some(*ordinal),
unresolved: true,
demangled: None,
address: None,
},
LeTarget::ImportName {
module,
name_offset,
} => ImportRef {
library: le_module(&import_modules, *module),
name: format!("@{name_offset:#x}"),
ordinal: None,
unresolved: false,
demangled: None,
address: None,
},
};
let key: LeImportKey = (
imp.library.clone(),
imp.name.clone(),
imp.ordinal,
imp.unresolved,
imp.demangled.clone(),
);
if seen.insert(key) {
imports.push(imp);
}
if imports.len() >= MAX_IMPORTS {
break;
}
}
let mut exports = Vec::new();
for e in &entries {
if exports.len() >= MAX_EXPORTS {
break;
}
let Some(obj) = e
.object
.checked_sub(1)
.and_then(|i| objects.get(i as usize))
else {
continue;
};
exports.push(ExportRef {
name: e.ordinal.to_string(),
address: Some(obj.reloc_base as u64 + e.offset as u64),
ordinal: Some(e.ordinal),
demangled: None,
});
}
let sections = objects
.iter()
.zip(segments.iter())
.map(|(o, s)| Section {
name: format!("obj{}", o.index),
vaddr: o.reloc_base as u64,
size: o.virtual_size as u64,
file_off: 0,
data: s.data.clone(),
readable: o.readable,
writable: o.writable,
executable: o.executable,
})
.collect();
LoadedBinary {
format: BinaryFormat::Le,
arch: Arch::X86_32,
entry,
segments,
sections,
imports,
exports,
symbols: Vec::new(),
}
}
fn le_module(modules: &[String], module: u32) -> String {
module
.checked_sub(1)
.and_then(|i| modules.get(i as usize))
.cloned()
.unwrap_or_else(|| format!("mod#{module}"))
}
fn import_from_object(
library: &[u8],
name: object::NameOrOrdinal<&[u8]>,
meta: &mut u64,
cache: &mut HashMap<String, Option<String>>,
) -> Result<ImportRef> {
let library = decode_owned_name(library, meta)?;
match name {
object::NameOrOrdinal::Ordinal(o) => {
let name = format!("#{o}");
account_meta(meta, name.len())?;
Ok(ImportRef {
library,
name,
ordinal: Some(u32::from(o)),
unresolved: true,
demangled: None,
address: None,
})
}
object::NameOrOrdinal::Name(b) => {
let raw = decode_owned_name(b, meta)?;
let demangled = demangle_bounded(&raw, meta, cache)?;
Ok(ImportRef {
library,
name: raw,
ordinal: None,
unresolved: false,
demangled,
address: None,
})
}
}
}
fn export_from_object(
name: object::NameOrOrdinal<&[u8]>,
address: Option<u64>,
meta: &mut u64,
cache: &mut HashMap<String, Option<String>>,
) -> Result<ExportRef> {
match name {
object::NameOrOrdinal::Ordinal(o) => {
let name = format!("#{o}");
account_meta(meta, name.len())?;
Ok(ExportRef {
name,
address,
ordinal: Some(u32::from(o)),
demangled: None,
})
}
object::NameOrOrdinal::Name(b) => {
let raw = decode_owned_name(b, meta)?;
let demangled = demangle_bounded(&raw, meta, cache)?;
Ok(ExportRef {
name: raw,
address,
ordinal: None,
demangled,
})
}
}
}
fn collect_symbols<'a>(
file: &object::File<'a, &'a [u8]>,
arch: Arch,
sections: &[Section],
segments: &[Segment],
meta: &mut u64,
cache: &mut HashMap<String, Option<String>>,
) -> Result<Vec<SymbolRef>> {
let mut ranges: Vec<(u64, u64)> = Vec::new();
for s in sections {
if s.executable && s.size > 0 {
ranges.push((s.vaddr, s.vaddr.saturating_add(s.size)));
}
}
if ranges.is_empty() {
for s in segments {
if s.executable && s.mem_size > 0 {
ranges.push((s.vaddr, s.vaddr.saturating_add(s.mem_size)));
}
}
}
ranges.sort_unstable();
let mut merged: Vec<(u64, u64)> = Vec::with_capacity(ranges.len());
for (lo, hi) in ranges {
if let Some((_, last_hi)) = merged.last_mut()
&& lo <= *last_hi
{
*last_hi = (*last_hi).max(hi);
continue;
}
merged.push((lo, hi));
}
let ranges = merged;
let in_exec = |addr: u64| -> bool {
ranges
.binary_search_by(|(lo, hi)| {
if addr < *lo {
std::cmp::Ordering::Greater
} else if addr >= *hi {
std::cmp::Ordering::Less
} else {
std::cmp::Ordering::Equal
}
})
.is_ok()
};
let mut out: Vec<SymbolRef> = Vec::new();
let mut seen: HashSet<u64> = HashSet::new();
for sym in file.symbols().chain(file.dynamic_symbols()) {
if sym.kind() != object::SymbolKind::Text {
continue;
}
if !matches!(sym.section(), object::SymbolSection::Section(_)) {
continue;
}
let address = canonical_code_addr(arch, sym.address());
if !in_exec(address) {
continue;
}
let raw = match sym.name_bytes() {
Ok(b) if !b.is_empty() => decode_owned_name(b, meta)?,
_ => continue,
};
if !seen.insert(address) {
continue;
}
if out.len() >= MAX_SYMBOLS {
return Err(Error::Limit("symbols exceed cap".to_string()));
}
let demangled = demangle_bounded(&raw, meta, cache)?;
out.push(SymbolRef {
name: raw,
address,
demangled,
});
}
Ok(out)
}
#[must_use]
pub fn demangle_cpp(name: &str) -> Option<String> {
if name.is_empty() || name.starts_with('#') || name.starts_with('@') {
return None;
}
if let Ok(d) = msvc_demangler::demangle(name, msvc_demangler::DemangleFlags::llvm())
&& !d.is_empty()
&& d != name
{
return Some(d);
}
if name.contains("_Z") {
let mut candidates = [name, ""];
let stripped = name.strip_prefix('_').unwrap_or(name);
if stripped != name {
candidates[1] = stripped;
}
for cand in candidates.into_iter().filter(|c| !c.is_empty()) {
if let Ok(sym) = cpp_demangle::Symbol::new(cand.as_bytes())
&& let Ok(d) = sym.demangle()
&& !d.is_empty()
&& d != name
{
return Some(d);
}
}
}
None
}
fn is_bss(kind: object::SectionKind) -> bool {
kind.is_bss()
}
fn section_perms(kind: object::SectionKind) -> (bool, bool, bool) {
use object::SectionKind as K;
match kind {
K::Text => (true, false, true),
K::Data | K::Tls | K::UninitializedData | K::UninitializedTls => (true, true, false),
_ => (true, false, false),
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::loader::le::{LeEntry, LeFixup, LeObject};
#[test]
fn arch_mapping_covers_supported_targets() {
use object::Architecture as A;
assert_eq!(arch_from_object(A::X86_64).unwrap(), Arch::X86_64);
assert_eq!(arch_from_object(A::I386).unwrap(), Arch::X86_32);
assert_eq!(arch_from_object(A::Aarch64).unwrap(), Arch::Aarch64);
assert_eq!(arch_from_object(A::Arm).unwrap(), Arch::Arm32);
assert!(matches!(
arch_from_object(A::Mips).unwrap_err(),
Error::Unsupported(_)
));
}
#[test]
fn le_conversion_maps_entry_tables_and_sections() {
let img = LeImage {
page_size: 0x1000,
cpu: 2,
os: 3,
module_flags: 0,
objects: vec![LeObject {
index: 1,
virtual_size: 0x1000,
reloc_base: 0x10000,
flags: 0x2005,
readable: true,
writable: false,
executable: true,
}],
segments: vec![Segment {
vaddr: 0x10000,
mem_size: 0x1000,
data: vec![0x90, 0x90, 0xC3],
readable: true,
writable: false,
executable: true,
}],
entry: Some(0x10000),
fixups: vec![LeFixup {
page: 1,
sources: vec![0],
target: LeTarget::ImportOrdinal {
module: 1,
ordinal: 7,
},
additive: None,
}],
entries: vec![LeEntry {
ordinal: 1,
object: 1,
offset: 0,
exported: true,
}],
import_modules: vec!["KERNEL".to_string()],
import_procs: vec!["ExitProcess".to_string()],
};
let bin = convert_le(img);
assert_eq!(bin.format, BinaryFormat::Le);
assert_eq!(bin.arch, Arch::X86_32);
assert_eq!(bin.entry, Some(0x10000));
assert_eq!(
bin.imports,
[ImportRef {
library: "KERNEL".to_string(),
name: "#7".to_string(),
ordinal: Some(7),
unresolved: true,
demangled: None,
address: None,
}]
);
assert_eq!(
bin.exports,
[ExportRef {
name: "1".to_string(),
address: Some(0x10000),
ordinal: Some(1),
demangled: None,
}]
);
assert_eq!(bin.sections.len(), 1);
assert_eq!(bin.sections[0].name, "obj1");
assert_eq!(bin.sections[0].data, [0x90, 0x90, 0xC3]);
}
#[test]
fn chained_fixups_scan_vetoes_only_on_evidence() {
fn header(ncmds: u32, cmds: &[u8]) -> Vec<u8> {
let mut f = vec![0u8; 32];
f[0..4].copy_from_slice(&0xFEED_FACFu32.to_le_bytes());
f[16..20].copy_from_slice(&ncmds.to_le_bytes());
f.extend_from_slice(cmds);
f
}
fn cmd(id: u32, size: u32) -> Vec<u8> {
let mut c = vec![0u8; size as usize];
c[0..4].copy_from_slice(&id.to_le_bytes());
c[4..8].copy_from_slice(&size.to_le_bytes());
c
}
let plain = header(1, &cmd(0x19, 72));
assert_eq!(macho_has_chained_fixups(&plain), Some(false));
let chained = header(2, &[cmd(0x19, 72), cmd(0x8000_0034, 16)].concat());
assert_eq!(macho_has_chained_fixups(&chained), Some(true));
assert_eq!(macho_has_chained_fixups(&[]), None);
assert_eq!(macho_has_chained_fixups(b"garbage........"), None);
assert_eq!(macho_has_chained_fixups(&header(4, &cmd(0x19, 72))), None);
let mut fat = plain.clone();
fat[0..4].copy_from_slice(&0xCAFEBABEu32.to_be_bytes());
assert_eq!(macho_has_chained_fixups(&fat), None);
}
#[test]
fn load_rejects_empty_input() {
assert!(matches!(load(&[]).unwrap_err(), Error::Invalid(_)));
assert!(matches!(
load_raw(
&[],
RawOptions {
base: 0,
arch: Arch::X86_64,
entry: None
}
)
.unwrap_err(),
Error::Invalid(_)
));
}
#[test]
fn load_rejects_garbage() {
assert!(matches!(
load(b"this is not a binary at all..........").unwrap_err(),
Error::Invalid(_)
));
}
#[test]
fn demangle_cpp_handles_msvc_itanium_and_plain() {
let msvc = demangle_cpp("?myfunc@@YAXH@Z").expect("MSVC demangles");
assert!(msvc.contains("myfunc"), "got {msvc:?}");
let itanium = demangle_cpp("_ZN5space3fooEibc").expect("Itanium demangles");
assert_eq!(itanium, "space::foo(int, bool, char)");
assert_eq!(demangle_cpp("plain_c_func"), None);
assert_eq!(demangle_cpp("#1"), None);
assert_eq!(demangle_cpp("@0x10"), None);
}
}