use std::sync::OnceLock;
use object::{
LittleEndian, pe,
read::{
Object,
coff::{
CoffFile as ObjCoffFile, CoffHeader, ImageSymbol,
SymbolTable as ObjSymbolTable,
},
pe::{ImageNtHeaders, ImageOptionalHeader, PeFile64},
},
};
use crate::{
coff::{
constants::{
IMAGE_FILE_MACHINE_AMD64, IMAGE_FILE_MACHINE_ARM64,
IMAGE_FILE_MACHINE_I386, IMAGE_SYM_CLASS_WEAK_EXTERNAL,
},
structs::{
CoffReloc, CoffSection, CoffSymbol, FunctionAux, SectionAux,
SymbolAux, WeakAux,
},
},
error::{Error, Result},
util::trim_nul,
};
const LE: LittleEndian = LittleEndian;
pub struct CoffFile<'data> {
inner: ObjCoffFile<'data>,
bytes: &'data [u8],
sections: OnceLock<Vec<CoffSection<'data>>>,
symbols: OnceLock<CoffSymbolTable<'data>>,
}
#[derive(Clone)]
pub struct CoffSymbolTable<'data> {
syms: Vec<CoffSymbol<'data>>,
}
impl<'data> CoffFile<'data> {
pub fn parse(bytes: &'data [u8]) -> Result<Self> {
reject_pe_image(bytes)?;
let inner = ObjCoffFile::parse(bytes)
.map_err(|_| Error::Format("invalid COFF header"))?;
Ok(Self {
inner,
bytes,
sections: OnceLock::new(),
symbols: OnceLock::new(),
})
}
pub fn machine(&self) -> u16 {
self.inner.coff_header().machine()
}
pub fn is_x86_64(&self) -> bool {
self.machine() == IMAGE_FILE_MACHINE_AMD64
}
pub fn is_i386(&self) -> bool {
self.machine() == IMAGE_FILE_MACHINE_I386
}
pub fn is_arm64(&self) -> bool {
self.machine() == IMAGE_FILE_MACHINE_ARM64
}
pub fn characteristics(&self) -> u16 {
self.inner.coff_header().characteristics()
}
pub fn number_of_sections(&self) -> u32 {
self.inner.coff_header().number_of_sections()
}
pub fn section_at(&self, ordinal: u32) -> Option<&CoffSection<'data>> {
let at = usize::try_from(ordinal).ok()?.checked_sub(1)?;
self.sections().get(at)
}
pub fn sections(&self) -> &[CoffSection<'data>] {
self.sections.get_or_init(|| self.decode_sections())
}
fn decode_sections(&self) -> Vec<CoffSection<'data>> {
let table = self.inner.coff_section_table();
let strings = self.inner.coff_symbol_table().strings();
let mut out = Vec::with_capacity(table.len());
for (i, raw) in table.iter().enumerate() {
let name = raw.name(strings).unwrap_or_else(|_| raw.raw_name());
let data = raw.coff_data(self.bytes).unwrap_or(&[]);
let relocations = raw
.coff_relocations(self.bytes)
.map(decode_relocations)
.unwrap_or_default();
out.push(CoffSection {
index: u32::try_from(i + 1).unwrap_or(u32::MAX),
name,
virtual_size: raw.virtual_size.get(LE),
virtual_address: raw.virtual_address.get(LE),
size_of_raw_data: raw.size_of_raw_data.get(LE),
pointer_to_raw_data: raw.pointer_to_raw_data.get(LE),
number_of_relocations: u32::from(
raw.number_of_relocations.get(LE),
),
characteristics: raw.characteristics.get(LE),
data,
relocations,
});
}
out
}
pub fn symbols(&self) -> &CoffSymbolTable<'data> {
self.symbols.get_or_init(|| self.decode_symbols())
}
fn decode_symbols(&self) -> CoffSymbolTable<'data> {
let symtab = self.inner.coff_symbol_table();
let strings = symtab.strings();
let mut out = Vec::with_capacity(symtab.len());
for (idx, sym) in symtab.iter() {
let name = sym.name(strings).unwrap_or(&[]);
out.push(CoffSymbol {
index: u32::try_from(idx.0).unwrap_or(u32::MAX),
name,
value: sym.value(),
section_number: sym.section_number(),
typ: sym.typ(),
storage_class: sym.storage_class(),
number_of_aux_symbols: sym.number_of_aux_symbols(),
aux: decode_aux(symtab, idx.0, sym),
});
}
CoffSymbolTable { syms: out }
}
}
impl<'data> CoffSymbolTable<'data> {
pub fn len(&self) -> usize {
self.syms.len()
}
pub fn is_empty(&self) -> bool {
self.syms.is_empty()
}
pub fn iter(&self) -> core::slice::Iter<'_, CoffSymbol<'data>> {
self.syms.iter()
}
}
impl<'data> IntoIterator for &'data CoffSymbolTable<'data> {
type Item = &'data CoffSymbol<'data>;
type IntoIter = core::slice::Iter<'data, CoffSymbol<'data>>;
fn into_iter(self) -> Self::IntoIter {
self.syms.iter()
}
}
fn reject_pe_image(bytes: &[u8]) -> Result<()> {
if bytes.len() >= 2 && bytes[0] == b'M' && bytes[1] == b'Z' {
return Err(Error::Format(
"PE image not supported by the COFF object reader",
));
}
Ok(())
}
fn decode_relocations(entries: &[pe::ImageRelocation]) -> Vec<CoffReloc> {
entries
.iter()
.map(|r| CoffReloc {
virtual_address: r.virtual_address.get(LE),
symbol_table_index: r.symbol_table_index.get(LE),
typ: r.typ.get(LE),
})
.collect()
}
fn decode_aux<'data>(
symtab: &ObjSymbolTable<'data, &'data [u8], pe::ImageFileHeader>,
index: usize,
sym: &pe::ImageSymbol,
) -> SymbolAux {
if sym.has_aux_section()
&& let Ok(aux) = symtab.aux_section(object::SymbolIndex(index))
{
let number = u32::from(aux.number.get(LE))
| (u32::from(aux.high_number.get(LE)) << 16);
return SymbolAux::Section(SectionAux {
length: aux.length.get(LE),
selection: aux.selection,
number,
});
}
if sym.storage_class() == IMAGE_SYM_CLASS_WEAK_EXTERNAL
&& sym.number_of_aux_symbols() > 0
&& let Ok(aux) = symtab.aux_weak_external(object::SymbolIndex(index))
{
return SymbolAux::Weak(WeakAux {
tag_index: aux.weak_default_sym_index.get(LE),
search_type: aux.weak_search_type.get(LE),
});
}
if sym.has_aux_function()
&& let Ok(aux) = symtab.aux_function(object::SymbolIndex(index))
{
return SymbolAux::Function(FunctionAux {
total_size: aux.total_size.get(LE),
});
}
SymbolAux::None
}
pub struct PeImage<'data> {
inner: PeFile64<'data>,
bytes: &'data [u8],
}
#[derive(Clone)]
pub struct PeSection<'data> {
pub name: &'data [u8],
pub virtual_size: u32,
pub virtual_address: u32,
pub size_of_raw_data: u32,
pub pointer_to_raw_data: u32,
pub characteristics: u32,
pub data: &'data [u8],
}
impl<'data> PeImage<'data> {
pub fn parse(bytes: &'data [u8]) -> Result<Self> {
let inner = PeFile64::parse(bytes)
.map_err(|_| Error::Format("invalid PE32+ image"))?;
Ok(Self { inner, bytes })
}
pub fn machine(&self) -> u16 {
self.inner.nt_headers().file_header().machine.get(LE)
}
pub fn is_x86_64(&self) -> bool {
self.machine() == IMAGE_FILE_MACHINE_AMD64
}
pub fn characteristics(&self) -> u16 {
self.inner
.nt_headers()
.file_header()
.characteristics
.get(LE)
}
pub fn magic(&self) -> u16 {
self.inner.nt_headers().optional_header().magic()
}
pub fn image_base(&self) -> u64 {
self.inner.nt_headers().optional_header().image_base()
}
pub fn address_of_entry_point(&self) -> u32 {
self.inner
.nt_headers()
.optional_header()
.address_of_entry_point()
}
pub fn section_alignment(&self) -> u32 {
self.inner
.nt_headers()
.optional_header()
.section_alignment()
}
pub fn file_alignment(&self) -> u32 {
self.inner.nt_headers().optional_header().file_alignment()
}
pub fn size_of_image(&self) -> u32 {
self.inner.nt_headers().optional_header().size_of_image()
}
pub fn size_of_headers(&self) -> u32 {
self.inner.nt_headers().optional_header().size_of_headers()
}
pub fn subsystem(&self) -> u16 {
self.inner.nt_headers().optional_header().subsystem()
}
pub fn data_directory(&self, id: usize) -> Option<(u32, u32)> {
self.inner
.data_directory(id)
.map(|d| (d.virtual_address.get(LE), d.size.get(LE)))
}
pub fn sections(&self) -> Vec<PeSection<'data>> {
let table = self.inner.section_table();
let mut out = Vec::with_capacity(table.len());
for raw in table.iter() {
let name = trim_nul(&raw.name);
let raw_size = raw.size_of_raw_data.get(LE);
let raw_ptr = raw.pointer_to_raw_data.get(LE);
let start = usize::try_from(raw_ptr).unwrap_or(usize::MAX);
let end = start
.checked_add(usize::try_from(raw_size).unwrap_or(0))
.unwrap_or(self.bytes.len());
let data = self.bytes.get(start..end).unwrap_or(&[]);
out.push(PeSection {
name,
virtual_size: raw.virtual_size.get(LE),
virtual_address: raw.virtual_address.get(LE),
size_of_raw_data: raw_size,
pointer_to_raw_data: raw_ptr,
characteristics: raw.characteristics.get(LE),
data,
});
}
out
}
pub fn imports(&self) -> Vec<(Vec<u8>, Vec<u8>)> {
Object::imports(&self.inner)
.unwrap_or_default()
.into_iter()
.map(|imp| (imp.library().to_vec(), imp.name().to_vec()))
.collect()
}
}