mod arch;
mod symbols;
mod target_os;
pub mod blob;
pub mod eh_frame;
pub mod elf;
pub mod le;
pub mod pe;
pub use arch::Arch;
pub use target_os::TargetOs;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Endian {
Little,
Big,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Format {
Elf,
Pe,
Le,
}
impl Format {
pub fn detect(bytes: &[u8]) -> Option<Format> {
if bytes.starts_with(b"\x7fELF") {
return Some(Format::Elf);
}
if bytes.starts_with(b"MZ") {
let e_lfanew = bytes.get(0x3c..0x40)?;
let at = u32::from_le_bytes(e_lfanew.try_into().ok()?) as usize;
if bytes.get(at..at + 4) == Some(b"PE\0\0") {
return Some(Format::Pe);
}
if bytes.get(at..at + 2) == Some(b"LE") {
return Some(Format::Le);
}
}
None
}
}
impl std::fmt::Display for Format {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.write_str(match self {
Format::Elf => "elf",
Format::Pe => "pe",
Format::Le => "le",
})
}
}
#[derive(Debug)]
pub enum LoadError {
UnknownFormat,
Elf(elf::ElfError),
Pe(pe::PeError),
Le(le::LeError),
}
impl std::fmt::Display for LoadError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
LoadError::UnknownFormat => write!(f, "not an ELF, PE or LE file"),
LoadError::Elf(e) => write!(f, "failed to parse ELF: {e}"),
LoadError::Pe(e) => write!(f, "failed to parse PE: {e}"),
LoadError::Le(e) => write!(f, "failed to parse LE: {e}"),
}
}
}
impl std::error::Error for LoadError {
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
match self {
LoadError::UnknownFormat => None,
LoadError::Elf(e) => Some(e),
LoadError::Pe(e) => Some(e),
LoadError::Le(e) => Some(e),
}
}
}
pub fn load(bytes: &[u8]) -> Result<Box<dyn BinaryFormat>, LoadError> {
match Format::detect(bytes).ok_or(LoadError::UnknownFormat)? {
Format::Elf => elf::ElfBinary::parse(bytes)
.map(|b| Box::new(b) as Box<dyn BinaryFormat>)
.map_err(LoadError::Elf),
Format::Pe => pe::PeBinary::parse(bytes)
.map(|b| Box::new(b) as Box<dyn BinaryFormat>)
.map_err(LoadError::Pe),
Format::Le => le::LeBinary::parse(bytes)
.map(|b| Box::new(b) as Box<dyn BinaryFormat>)
.map_err(LoadError::Le),
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Section {
pub name: String,
pub address: u64,
pub size: u64,
pub writable: bool,
pub executable: bool,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Symbol {
pub name: String,
pub address: u64,
pub size: Option<u64>,
pub is_external: bool,
pub library: Option<String>,
}
pub const fn printable_byte(b: u8) -> u8 {
if b >= 0x20 && b <= 0x7e { b } else { b'.' }
}
pub const fn is_printable_ascii_byte(b: u8) -> bool {
b >= 0x20 && b <= 0x7e
}
pub trait BinaryFormat: Send + Sync {
fn load_address(&self) -> u64;
fn byte_at(&self, addr: u64) -> Option<u8>;
fn bytes_at(&self, addr: u64) -> Option<&[u8]>;
fn entry_points(&self) -> Vec<u64>;
fn entrypoint(&self) -> Option<u64> {
None
}
fn architecture(&self) -> Arch;
fn endianness(&self) -> Endian {
Endian::Little
}
fn bits(&self) -> u32 {
64
}
fn os(&self) -> TargetOs {
TargetOs::Unknown
}
fn linked_libraries(&self) -> Vec<String> {
Vec::new()
}
fn sections(&self) -> Vec<Section> {
Vec::new()
}
fn symbols(&self) -> Vec<Symbol> {
Vec::new()
}
fn symbol_name(&self, _addr: u64) -> Option<&str> {
None
}
fn symbol_address(&self, _name: &str) -> Option<u64> {
None
}
fn is_external_symbol(&self, _addr: u64) -> bool {
false
}
fn import_library(&self, _addr: u64) -> Option<&str> {
None
}
fn import_symbol_name(&self, _addr: u64) -> Option<&str> {
None
}
fn hex_rows(&self, addr: u64, len: usize, width: usize) -> Vec<(u64, Vec<Option<u8>>)> {
assert!(width > 0, "hex row width must be non-zero");
let row_start = addr - addr % width as u64;
let end = addr.saturating_add(len as u64);
let mut rows = Vec::new();
let mut cur = row_start;
while cur < end {
let bytes = (0..width as u64).map(|i| self.byte_at(cur + i)).collect();
rows.push((cur, bytes));
cur = cur.saturating_add(width as u64);
}
rows
}
fn contains(&self, addr: u64) -> bool {
self.byte_at(addr).is_some()
}
fn mapped_regions(&self) -> Vec<(u64, Vec<u8>, bool, bool)> {
Vec::new()
}
fn is_executable(&self, addr: u64) -> bool {
self.contains(addr)
}
fn segment_bounds(&self, _addr: u64) -> Option<(u64, u64)> {
None
}
fn is_known_writable(&self, _addr: u64) -> bool {
false
}
fn is_known_read_only(&self, _addr: u64) -> bool {
false
}
fn read_bytes(&self, addr: u64, n: usize) -> Option<Vec<u8>> {
let mut out = Vec::with_capacity(n);
for offset in 0..n {
out.push(self.byte_at(addr.checked_add(offset as u64)?)?);
}
Some(out)
}
fn read_uint(&self, addr: u64, size: usize) -> Option<u64> {
if size == 0 || size > 8 {
return None;
}
let bytes = self.read_bytes(addr, size)?;
let mut value = 0u64;
for (i, &b) in bytes.iter().enumerate() {
value |= (b as u64) << (i * 8);
}
Some(value)
}
fn read_cstring(&self, addr: u64, max_len: Option<usize>) -> Option<Vec<u8>> {
let limit = max_len.unwrap_or(usize::MAX);
let mut out = Vec::new();
for offset in 0..limit {
let byte = self.byte_at(addr.checked_add(offset as u64)?)?;
if byte == 0 {
return Some(out);
}
out.push(byte);
}
None
}
fn read_printable_cstring(&self, addr: u64, max_len: Option<usize>) -> Option<Vec<u8>> {
let limit = max_len.unwrap_or(usize::MAX);
let mut out = Vec::new();
for offset in 0..limit {
let byte = self.byte_at(addr.checked_add(offset as u64)?)?;
if byte == 0 {
return Some(out);
}
if !is_printable_ascii_byte(byte) {
return None;
}
out.push(byte);
}
None
}
}
#[cfg(test)]
mod tests {
use super::{BinaryFormat, Endian, Format, LoadError, blob::Blob, load};
#[test]
fn detects_elf_by_magic() {
assert_eq!(Format::detect(b"\x7fELF\x02\x01\x01"), Some(Format::Elf));
assert_eq!(Format::detect(b"\x7fEL"), None);
}
#[test]
fn detects_pe_only_behind_a_pe_signature() {
let mut pe = vec![0u8; 0x80];
pe[..2].copy_from_slice(b"MZ");
pe[0x3c..0x40].copy_from_slice(&0x40u32.to_le_bytes());
assert_eq!(Format::detect(&pe), None);
pe[0x40..0x44].copy_from_slice(b"PE\0\0");
assert_eq!(Format::detect(&pe), Some(Format::Pe));
assert_eq!(Format::detect(b"MZ\x90\x00"), None);
let mut dos = vec![0u8; 0x80];
dos[..2].copy_from_slice(b"MZ");
assert_eq!(Format::detect(&dos), None);
dos[0x3c..0x40].copy_from_slice(&0x40u32.to_le_bytes());
dos[0x40..0x42].copy_from_slice(b"LE");
assert_eq!(Format::detect(&dos), Some(Format::Le));
dos[0x40..0x42].copy_from_slice(b"LX");
assert_eq!(Format::detect(&dos), None);
}
#[test]
fn detects_nothing_in_a_blob() {
assert_eq!(Format::detect(b""), None);
assert_eq!(Format::detect(&[0x55, 0x48, 0x89, 0xe5]), None);
assert!(matches!(load(b"\x90\x90"), Err(LoadError::UnknownFormat)));
}
#[test]
fn blob_keeps_the_trait_defaults() {
let blob = Blob::new(0x1000, vec![0x90]);
assert_eq!(blob.endianness(), Endian::Little);
assert_eq!(blob.bits(), 64);
assert!(blob.sections().is_empty());
assert!(blob.symbols().is_empty());
}
#[test]
fn read_printable_cstring_accepts_printable_ascii() {
let blob = Blob::new(0x1000, b"hello, world!\0next".to_vec());
assert_eq!(
blob.read_printable_cstring(0x1000, None),
Some(b"hello, world!".to_vec())
);
}
#[test]
fn read_printable_cstring_rejects_control_bytes() {
let blob = Blob::new(0x1000, b"line\nbreak\0".to_vec());
assert_eq!(
blob.read_cstring(0x1000, None),
Some(b"line\nbreak".to_vec())
);
assert_eq!(blob.read_printable_cstring(0x1000, None), None);
}
#[test]
fn read_printable_cstring_rejects_non_ascii_bytes() {
let blob = Blob::new(0x1000, b"caf\xe9\0".to_vec());
assert_eq!(blob.read_printable_cstring(0x1000, None), None);
}
#[test]
fn read_printable_cstring_honors_max_len() {
let blob = Blob::new(0x1000, b"hello\0".to_vec());
assert_eq!(blob.read_printable_cstring(0x1000, Some(3)), None);
assert_eq!(
blob.read_printable_cstring(0x1000, Some(6)),
Some(b"hello".to_vec())
);
}
}