use alloc::vec::Vec;
use core::fmt::Debug;
use core::{mem, str};
use crate::read::coff::{CoffCommon, CoffSymbol, CoffSymbolIterator, CoffSymbolTable, SymbolTable};
use crate::read::{
self, Architecture, ComdatKind, Error, Export, FileFlags, Import, NoDynamicRelocationIterator,
Object, ObjectComdat, ReadError, Result, SectionIndex, SymbolIndex,
};
use crate::{pe, ByteString, Bytes, LittleEndian as LE, Pod, U16Bytes, U32Bytes, U32, U64};
use super::{PeSection, PeSectionIterator, PeSegment, PeSegmentIterator, SectionTable};
pub type PeFile32<'data> = PeFile<'data, pe::ImageNtHeaders32>;
pub type PeFile64<'data> = PeFile<'data, pe::ImageNtHeaders64>;
#[derive(Debug)]
pub struct PeFile<'data, Pe: ImageNtHeaders> {
pub(super) dos_header: &'data pe::ImageDosHeader,
pub(super) nt_headers: &'data Pe,
pub(super) data_directories: &'data [pe::ImageDataDirectory],
pub(super) common: CoffCommon<'data>,
pub(super) data: Bytes<'data>,
}
impl<'data, Pe: ImageNtHeaders> PeFile<'data, Pe> {
pub fn optional_header_magic(data: &'data [u8]) -> Result<u16> {
let data = Bytes(data);
let dos_header = pe::ImageDosHeader::parse(data)?;
let nt_headers = data
.read_at::<Pe>(dos_header.e_lfanew.get(LE) as usize)
.read_error("Invalid NT headers offset, size, or alignment")?;
if nt_headers.signature() != pe::IMAGE_NT_SIGNATURE {
return Err(Error("Invalid PE magic"));
}
Ok(nt_headers.optional_header().magic())
}
pub fn parse(data: &'data [u8]) -> Result<Self> {
let data = Bytes(data);
let dos_header = pe::ImageDosHeader::parse(data)?;
let (nt_headers, data_directories, nt_tail) = dos_header.nt_headers::<Pe>(data)?;
let sections = nt_headers.sections(nt_tail)?;
let symbols = nt_headers.symbols(data)?;
let image_base = u64::from(nt_headers.optional_header().image_base());
Ok(PeFile {
dos_header,
nt_headers,
data_directories,
common: CoffCommon {
sections,
symbols,
image_base,
},
data,
})
}
pub(super) fn section_alignment(&self) -> u64 {
u64::from(self.nt_headers.optional_header().section_alignment())
}
fn data_directory(&self, id: usize) -> Option<&'data pe::ImageDataDirectory> {
self.data_directories
.get(id)
.filter(|d| d.size.get(LE) != 0)
}
fn data_at(&self, va: u32) -> Option<Bytes<'data>> {
self.common
.sections
.iter()
.filter_map(|section| section.pe_data_at(self.data, va))
.next()
}
}
impl<'data, Pe: ImageNtHeaders> read::private::Sealed for PeFile<'data, Pe> {}
impl<'data, 'file, Pe> Object<'data, 'file> for PeFile<'data, Pe>
where
'data: 'file,
Pe: ImageNtHeaders,
{
type Segment = PeSegment<'data, 'file, Pe>;
type SegmentIterator = PeSegmentIterator<'data, 'file, Pe>;
type Section = PeSection<'data, 'file, Pe>;
type SectionIterator = PeSectionIterator<'data, 'file, Pe>;
type Comdat = PeComdat<'data, 'file, Pe>;
type ComdatIterator = PeComdatIterator<'data, 'file, Pe>;
type Symbol = CoffSymbol<'data, 'file>;
type SymbolIterator = CoffSymbolIterator<'data, 'file>;
type SymbolTable = CoffSymbolTable<'data, 'file>;
type DynamicRelocationIterator = NoDynamicRelocationIterator;
fn architecture(&self) -> Architecture {
match self.nt_headers.file_header().machine.get(LE) {
pe::IMAGE_FILE_MACHINE_I386 => Architecture::I386,
pe::IMAGE_FILE_MACHINE_AMD64 => Architecture::X86_64,
_ => Architecture::Unknown,
}
}
#[inline]
fn is_little_endian(&self) -> bool {
true
}
#[inline]
fn is_64(&self) -> bool {
self.nt_headers.is_type_64()
}
fn segments(&'file self) -> PeSegmentIterator<'data, 'file, Pe> {
PeSegmentIterator {
file: self,
iter: self.common.sections.iter(),
}
}
fn section_by_name(&'file self, section_name: &str) -> Option<PeSection<'data, 'file, Pe>> {
self.common
.sections
.section_by_name(self.common.symbols.strings(), section_name.as_bytes())
.map(|(index, section)| PeSection {
file: self,
index: SectionIndex(index),
section,
})
}
fn section_by_index(&'file self, index: SectionIndex) -> Result<PeSection<'data, 'file, Pe>> {
let section = self.common.sections.section(index.0)?;
Ok(PeSection {
file: self,
index,
section,
})
}
fn sections(&'file self) -> PeSectionIterator<'data, 'file, Pe> {
PeSectionIterator {
file: self,
iter: self.common.sections.iter().enumerate(),
}
}
fn comdats(&'file self) -> PeComdatIterator<'data, 'file, Pe> {
PeComdatIterator { file: self }
}
fn symbol_by_index(&'file self, index: SymbolIndex) -> Result<CoffSymbol<'data, 'file>> {
let symbol = self.common.symbols.symbol(index.0)?;
Ok(CoffSymbol {
file: &self.common,
index,
symbol,
})
}
fn symbols(&'file self) -> CoffSymbolIterator<'data, 'file> {
CoffSymbolIterator {
file: &self.common,
index: 0,
}
}
fn symbol_table(&'file self) -> Option<CoffSymbolTable<'data, 'file>> {
Some(CoffSymbolTable { file: &self.common })
}
fn dynamic_symbols(&'file self) -> CoffSymbolIterator<'data, 'file> {
CoffSymbolIterator {
file: &self.common,
index: self.common.symbols.len(),
}
}
fn dynamic_symbol_table(&'file self) -> Option<CoffSymbolTable<'data, 'file>> {
None
}
fn dynamic_relocations(&'file self) -> Option<NoDynamicRelocationIterator> {
None
}
fn imports(&self) -> Result<Vec<Import<'data>>> {
let data_dir = match self.data_directory(pe::IMAGE_DIRECTORY_ENTRY_IMPORT) {
Some(data_dir) => data_dir,
None => return Ok(Vec::new()),
};
let import_data = self
.data_at(data_dir.virtual_address.get(LE))
.read_error("Invalid PE import dir virtual address")?
.read_bytes(data_dir.size.get(LE) as usize)
.read_error("Invalid PE import dir size")?;
let mut imports = Vec::new();
let mut import_descriptors = import_data;
loop {
let import_desc = import_descriptors
.read::<pe::ImageImportDescriptor>()
.read_error("Missing PE null import descriptor")?;
if import_desc.original_first_thunk.get(LE) == 0 {
break;
}
let library = self
.data_at(import_desc.name.get(LE))
.read_error("Invalid PE import descriptor name")?
.read_string()
.read_error("Invalid PE import descriptor name")?;
let thunk_va = import_desc.original_first_thunk.get(LE);
let mut thunk_data = self
.data_at(thunk_va)
.read_error("Invalid PE import thunk address")?;
loop {
let hint_name = if self.is_64() {
let thunk = thunk_data
.read::<U64<_>>()
.read_error("Missing PE null import thunk")?
.get(LE);
if thunk == 0 {
break;
}
if thunk & pe::IMAGE_ORDINAL_FLAG64 != 0 {
continue;
}
thunk as u32
} else {
let thunk = thunk_data
.read::<U32<_>>()
.read_error("Missing PE null import thunk")?
.get(LE);
if thunk == 0 {
break;
}
if thunk & pe::IMAGE_ORDINAL_FLAG32 != 0 {
continue;
}
thunk
};
let name = self
.data_at(hint_name)
.read_error("Invalid PE import thunk name")?
.read_string_at(2)
.read_error("Invalid PE import thunk name")?;
imports.push(Import {
name: ByteString(name),
library: ByteString(library),
});
}
}
Ok(imports)
}
fn exports(&self) -> Result<Vec<Export<'data>>> {
let data_dir = match self.data_directory(pe::IMAGE_DIRECTORY_ENTRY_EXPORT) {
Some(data_dir) => data_dir,
None => return Ok(Vec::new()),
};
let export_va = data_dir.virtual_address.get(LE);
let export_size = data_dir.size.get(LE);
let export_data = self
.data_at(export_va)
.read_error("Invalid PE export dir virtual address")?
.read_bytes(export_size as usize)
.read_error("Invalid PE export dir size")?;
let export_dir = export_data
.read_at::<pe::ImageExportDirectory>(0)
.read_error("Invalid PE export dir size")?;
let addresses = export_data
.read_slice_at::<U32Bytes<_>>(
export_dir
.address_of_functions
.get(LE)
.wrapping_sub(export_va) as usize,
export_dir.number_of_functions.get(LE) as usize,
)
.read_error("Invalid PE export address table")?;
let number = export_dir.number_of_names.get(LE) as usize;
let names = export_data
.read_slice_at::<U32Bytes<_>>(
export_dir.address_of_names.get(LE).wrapping_sub(export_va) as usize,
number,
)
.read_error("Invalid PE export name table")?;
let ordinals = export_data
.read_slice_at::<U16Bytes<_>>(
export_dir
.address_of_name_ordinals
.get(LE)
.wrapping_sub(export_va) as usize,
number,
)
.read_error("Invalid PE export ordinal table")?;
let mut exports = Vec::new();
for (name, ordinal) in names.iter().zip(ordinals.iter()) {
let name = export_data
.read_string_at(name.get(LE).wrapping_sub(export_va) as usize)
.read_error("Invalid PE export name entry")?;
let address = addresses
.get(ordinal.get(LE) as usize)
.read_error("Invalid PE export ordinal entry")?
.get(LE);
if address < export_va || (address - export_va) >= export_size {
exports.push(Export {
name: ByteString(name),
address: self.common.image_base.wrapping_add(address.into()),
})
}
}
Ok(exports)
}
fn has_debug_symbols(&self) -> bool {
self.section_by_name(".debug_info").is_some()
}
fn entry(&self) -> u64 {
u64::from(self.nt_headers.optional_header().address_of_entry_point())
}
fn flags(&self) -> FileFlags {
FileFlags::Coff {
characteristics: self.nt_headers.file_header().characteristics.get(LE),
}
}
}
pub type PeComdatIterator32<'data, 'file> = PeComdatIterator<'data, 'file, pe::ImageNtHeaders32>;
pub type PeComdatIterator64<'data, 'file> = PeComdatIterator<'data, 'file, pe::ImageNtHeaders64>;
#[derive(Debug)]
pub struct PeComdatIterator<'data, 'file, Pe: ImageNtHeaders> {
file: &'file PeFile<'data, Pe>,
}
impl<'data, 'file, Pe: ImageNtHeaders> Iterator for PeComdatIterator<'data, 'file, Pe> {
type Item = PeComdat<'data, 'file, Pe>;
#[inline]
fn next(&mut self) -> Option<Self::Item> {
None
}
}
pub type PeComdat32<'data, 'file> = PeComdat<'data, 'file, pe::ImageNtHeaders32>;
pub type PeComdat64<'data, 'file> = PeComdat<'data, 'file, pe::ImageNtHeaders64>;
#[derive(Debug)]
pub struct PeComdat<'data, 'file, Pe: ImageNtHeaders> {
file: &'file PeFile<'data, Pe>,
}
impl<'data, 'file, Pe: ImageNtHeaders> read::private::Sealed for PeComdat<'data, 'file, Pe> {}
impl<'data, 'file, Pe: ImageNtHeaders> ObjectComdat<'data> for PeComdat<'data, 'file, Pe> {
type SectionIterator = PeComdatSectionIterator<'data, 'file, Pe>;
#[inline]
fn kind(&self) -> ComdatKind {
unreachable!();
}
#[inline]
fn symbol(&self) -> SymbolIndex {
unreachable!();
}
#[inline]
fn name(&self) -> Result<&str> {
unreachable!();
}
#[inline]
fn sections(&self) -> Self::SectionIterator {
unreachable!();
}
}
pub type PeComdatSectionIterator32<'data, 'file> =
PeComdatSectionIterator<'data, 'file, pe::ImageNtHeaders32>;
pub type PeComdatSectionIterator64<'data, 'file> =
PeComdatSectionIterator<'data, 'file, pe::ImageNtHeaders64>;
#[derive(Debug)]
pub struct PeComdatSectionIterator<'data, 'file, Pe: ImageNtHeaders>
where
'data: 'file,
{
file: &'file PeFile<'data, Pe>,
}
impl<'data, 'file, Pe: ImageNtHeaders> Iterator for PeComdatSectionIterator<'data, 'file, Pe> {
type Item = SectionIndex;
fn next(&mut self) -> Option<Self::Item> {
None
}
}
impl pe::ImageDosHeader {
pub fn parse<'data>(data: Bytes<'data>) -> read::Result<&'data Self> {
let dos_header = data
.read_at::<pe::ImageDosHeader>(0)
.read_error("Invalid DOS header size or alignment")?;
if dos_header.e_magic.get(LE) != pe::IMAGE_DOS_SIGNATURE {
return Err(Error("Invalid DOS magic"));
}
Ok(dos_header)
}
#[inline]
pub fn nt_headers<'data, Pe: ImageNtHeaders>(
&self,
data: Bytes<'data>,
) -> read::Result<(&'data Pe, &'data [pe::ImageDataDirectory], Bytes<'data>)> {
Pe::parse(self, data)
}
}
#[allow(missing_docs)]
pub trait ImageNtHeaders: Debug + Pod {
type ImageOptionalHeader: ImageOptionalHeader;
fn is_type_64(&self) -> bool;
fn is_valid_optional_magic(&self) -> bool;
fn signature(&self) -> u32;
fn file_header(&self) -> &pe::ImageFileHeader;
fn optional_header(&self) -> &Self::ImageOptionalHeader;
fn parse<'data>(
dos_header: &pe::ImageDosHeader,
mut data: Bytes<'data>,
) -> read::Result<(&'data Self, &'data [pe::ImageDataDirectory], Bytes<'data>)> {
data.skip(dos_header.e_lfanew.get(LE) as usize)
.read_error("Invalid PE headers offset")?;
let nt_headers = data
.read::<Self>()
.read_error("Invalid PE headers size or alignment")?;
if nt_headers.signature() != pe::IMAGE_NT_SIGNATURE {
return Err(Error("Invalid PE magic"));
}
if !nt_headers.is_valid_optional_magic() {
return Err(Error("Invalid PE optional header magic"));
}
let optional_data_size = (nt_headers.file_header().size_of_optional_header.get(LE)
as usize)
.checked_sub(mem::size_of::<Self::ImageOptionalHeader>())
.read_error("PE optional header size is too small")?;
let mut optional_data = data
.read_bytes(optional_data_size)
.read_error("Invalid PE optional header size")?;
let data_directories = optional_data
.read_slice(nt_headers.optional_header().number_of_rva_and_sizes() as usize)
.read_error("Invalid PE number of RVA and sizes")?;
Ok((nt_headers, data_directories, data))
}
#[inline]
fn sections<'data>(&self, nt_tail: Bytes<'data>) -> read::Result<SectionTable<'data>> {
SectionTable::parse(self.file_header(), nt_tail)
}
#[inline]
fn symbols<'data>(&self, data: Bytes<'data>) -> read::Result<SymbolTable<'data>> {
SymbolTable::parse(self.file_header(), data)
}
}
#[allow(missing_docs)]
pub trait ImageOptionalHeader: Debug + Pod {
fn magic(&self) -> u16;
fn major_linker_version(&self) -> u8;
fn minor_linker_version(&self) -> u8;
fn size_of_code(&self) -> u32;
fn size_of_initialized_data(&self) -> u32;
fn size_of_uninitialized_data(&self) -> u32;
fn address_of_entry_point(&self) -> u32;
fn base_of_code(&self) -> u32;
fn image_base(&self) -> u64;
fn section_alignment(&self) -> u32;
fn file_alignment(&self) -> u32;
fn major_operating_system_version(&self) -> u16;
fn minor_operating_system_version(&self) -> u16;
fn major_image_version(&self) -> u16;
fn minor_image_version(&self) -> u16;
fn major_subsystem_version(&self) -> u16;
fn minor_subsystem_version(&self) -> u16;
fn win32_version_value(&self) -> u32;
fn size_of_image(&self) -> u32;
fn size_of_headers(&self) -> u32;
fn check_sum(&self) -> u32;
fn subsystem(&self) -> u16;
fn dll_characteristics(&self) -> u16;
fn size_of_stack_reserve(&self) -> u64;
fn size_of_stack_commit(&self) -> u64;
fn size_of_heap_reserve(&self) -> u64;
fn size_of_heap_commit(&self) -> u64;
fn loader_flags(&self) -> u32;
fn number_of_rva_and_sizes(&self) -> u32;
}
impl ImageNtHeaders for pe::ImageNtHeaders32 {
type ImageOptionalHeader = pe::ImageOptionalHeader32;
#[inline]
fn is_type_64(&self) -> bool {
false
}
#[inline]
fn is_valid_optional_magic(&self) -> bool {
self.optional_header.magic.get(LE) == pe::IMAGE_NT_OPTIONAL_HDR32_MAGIC
}
#[inline]
fn signature(&self) -> u32 {
self.signature.get(LE)
}
#[inline]
fn file_header(&self) -> &pe::ImageFileHeader {
&self.file_header
}
#[inline]
fn optional_header(&self) -> &Self::ImageOptionalHeader {
&self.optional_header
}
}
impl ImageOptionalHeader for pe::ImageOptionalHeader32 {
#[inline]
fn magic(&self) -> u16 {
self.magic.get(LE)
}
#[inline]
fn major_linker_version(&self) -> u8 {
self.major_linker_version
}
#[inline]
fn minor_linker_version(&self) -> u8 {
self.minor_linker_version
}
#[inline]
fn size_of_code(&self) -> u32 {
self.size_of_code.get(LE)
}
#[inline]
fn size_of_initialized_data(&self) -> u32 {
self.size_of_initialized_data.get(LE)
}
#[inline]
fn size_of_uninitialized_data(&self) -> u32 {
self.size_of_uninitialized_data.get(LE)
}
#[inline]
fn address_of_entry_point(&self) -> u32 {
self.address_of_entry_point.get(LE)
}
#[inline]
fn base_of_code(&self) -> u32 {
self.base_of_code.get(LE)
}
#[inline]
fn image_base(&self) -> u64 {
self.image_base.get(LE).into()
}
#[inline]
fn section_alignment(&self) -> u32 {
self.section_alignment.get(LE)
}
#[inline]
fn file_alignment(&self) -> u32 {
self.file_alignment.get(LE)
}
#[inline]
fn major_operating_system_version(&self) -> u16 {
self.major_operating_system_version.get(LE)
}
#[inline]
fn minor_operating_system_version(&self) -> u16 {
self.minor_operating_system_version.get(LE)
}
#[inline]
fn major_image_version(&self) -> u16 {
self.major_image_version.get(LE)
}
#[inline]
fn minor_image_version(&self) -> u16 {
self.minor_image_version.get(LE)
}
#[inline]
fn major_subsystem_version(&self) -> u16 {
self.major_subsystem_version.get(LE)
}
#[inline]
fn minor_subsystem_version(&self) -> u16 {
self.minor_subsystem_version.get(LE)
}
#[inline]
fn win32_version_value(&self) -> u32 {
self.win32_version_value.get(LE)
}
#[inline]
fn size_of_image(&self) -> u32 {
self.size_of_image.get(LE)
}
#[inline]
fn size_of_headers(&self) -> u32 {
self.size_of_headers.get(LE)
}
#[inline]
fn check_sum(&self) -> u32 {
self.check_sum.get(LE)
}
#[inline]
fn subsystem(&self) -> u16 {
self.subsystem.get(LE)
}
#[inline]
fn dll_characteristics(&self) -> u16 {
self.dll_characteristics.get(LE)
}
#[inline]
fn size_of_stack_reserve(&self) -> u64 {
self.size_of_stack_reserve.get(LE).into()
}
#[inline]
fn size_of_stack_commit(&self) -> u64 {
self.size_of_stack_commit.get(LE).into()
}
#[inline]
fn size_of_heap_reserve(&self) -> u64 {
self.size_of_heap_reserve.get(LE).into()
}
#[inline]
fn size_of_heap_commit(&self) -> u64 {
self.size_of_heap_commit.get(LE).into()
}
#[inline]
fn loader_flags(&self) -> u32 {
self.loader_flags.get(LE)
}
#[inline]
fn number_of_rva_and_sizes(&self) -> u32 {
self.number_of_rva_and_sizes.get(LE)
}
}
impl ImageNtHeaders for pe::ImageNtHeaders64 {
type ImageOptionalHeader = pe::ImageOptionalHeader64;
#[inline]
fn is_type_64(&self) -> bool {
true
}
#[inline]
fn is_valid_optional_magic(&self) -> bool {
self.optional_header.magic.get(LE) == pe::IMAGE_NT_OPTIONAL_HDR64_MAGIC
}
#[inline]
fn signature(&self) -> u32 {
self.signature.get(LE)
}
#[inline]
fn file_header(&self) -> &pe::ImageFileHeader {
&self.file_header
}
#[inline]
fn optional_header(&self) -> &Self::ImageOptionalHeader {
&self.optional_header
}
}
impl ImageOptionalHeader for pe::ImageOptionalHeader64 {
#[inline]
fn magic(&self) -> u16 {
self.magic.get(LE)
}
#[inline]
fn major_linker_version(&self) -> u8 {
self.major_linker_version
}
#[inline]
fn minor_linker_version(&self) -> u8 {
self.minor_linker_version
}
#[inline]
fn size_of_code(&self) -> u32 {
self.size_of_code.get(LE)
}
#[inline]
fn size_of_initialized_data(&self) -> u32 {
self.size_of_initialized_data.get(LE)
}
#[inline]
fn size_of_uninitialized_data(&self) -> u32 {
self.size_of_uninitialized_data.get(LE)
}
#[inline]
fn address_of_entry_point(&self) -> u32 {
self.address_of_entry_point.get(LE)
}
#[inline]
fn base_of_code(&self) -> u32 {
self.base_of_code.get(LE)
}
#[inline]
fn image_base(&self) -> u64 {
self.image_base.get(LE)
}
#[inline]
fn section_alignment(&self) -> u32 {
self.section_alignment.get(LE)
}
#[inline]
fn file_alignment(&self) -> u32 {
self.file_alignment.get(LE)
}
#[inline]
fn major_operating_system_version(&self) -> u16 {
self.major_operating_system_version.get(LE)
}
#[inline]
fn minor_operating_system_version(&self) -> u16 {
self.minor_operating_system_version.get(LE)
}
#[inline]
fn major_image_version(&self) -> u16 {
self.major_image_version.get(LE)
}
#[inline]
fn minor_image_version(&self) -> u16 {
self.minor_image_version.get(LE)
}
#[inline]
fn major_subsystem_version(&self) -> u16 {
self.major_subsystem_version.get(LE)
}
#[inline]
fn minor_subsystem_version(&self) -> u16 {
self.minor_subsystem_version.get(LE)
}
#[inline]
fn win32_version_value(&self) -> u32 {
self.win32_version_value.get(LE)
}
#[inline]
fn size_of_image(&self) -> u32 {
self.size_of_image.get(LE)
}
#[inline]
fn size_of_headers(&self) -> u32 {
self.size_of_headers.get(LE)
}
#[inline]
fn check_sum(&self) -> u32 {
self.check_sum.get(LE)
}
#[inline]
fn subsystem(&self) -> u16 {
self.subsystem.get(LE)
}
#[inline]
fn dll_characteristics(&self) -> u16 {
self.dll_characteristics.get(LE)
}
#[inline]
fn size_of_stack_reserve(&self) -> u64 {
self.size_of_stack_reserve.get(LE)
}
#[inline]
fn size_of_stack_commit(&self) -> u64 {
self.size_of_stack_commit.get(LE)
}
#[inline]
fn size_of_heap_reserve(&self) -> u64 {
self.size_of_heap_reserve.get(LE)
}
#[inline]
fn size_of_heap_commit(&self) -> u64 {
self.size_of_heap_commit.get(LE)
}
#[inline]
fn loader_flags(&self) -> u32 {
self.loader_flags.get(LE)
}
#[inline]
fn number_of_rva_and_sizes(&self) -> u32 {
self.number_of_rva_and_sizes.get(LE)
}
}