use crate::{
errors::{FileParseError, Result},
pe::PE,
};
use alloc::{
collections::BTreeMap,
rc::Rc,
string::{String, ToString},
vec,
vec::Vec,
};
mod emit;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Target {
X86,
X64,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ImageKind {
Executable,
Dll,
}
macro_rules! handle {
($name:ident) => {
#[derive(Clone, Debug)]
pub struct $name {
owner: Rc<()>,
index: usize,
}
};
}
handle!(SectionId);
handle!(SymbolId);
handle!(ImportId);
#[derive(Clone, Debug)]
pub struct SectionSpec {
pub name: String,
pub data: Vec<u8>,
pub virtual_size: u32,
pub characteristics: u32,
}
impl SectionSpec {
pub fn new(name: &str, data: Vec<u8>, characteristics: u32) -> Self {
Self {
name: name.to_string(),
virtual_size: u32::try_from(data.len()).unwrap_or(u32::MAX),
data,
characteristics,
}
}
}
#[derive(Clone, Copy, Debug)]
pub enum FixupKind {
Rva32,
Va32,
Va64,
Rel32 { origin: u32 },
}
#[derive(Clone, Debug)]
pub enum FixupTarget {
Symbol(SymbolId),
Import(ImportId),
}
#[derive(Clone, Debug)]
pub struct Fixup {
pub section: SectionId,
pub offset: u32,
pub target: FixupTarget,
pub kind: FixupKind,
pub addend: i64,
}
#[derive(Clone, Debug)]
pub struct TlsSpec {
pub start: SymbolId,
pub end: SymbolId,
pub index: SymbolId,
pub callbacks: Vec<SymbolId>,
pub zero_fill: u32,
pub alignment: u32,
}
#[derive(Clone, Debug)]
pub struct ResolvedLocation {
pub rva: u32,
pub va: u64,
pub file_offset: Option<usize>,
}
#[derive(Clone, Debug)]
pub struct ResolvedSection {
pub rva: u32,
pub file_offset: usize,
pub raw_size: u32,
pub virtual_size: u32,
}
pub struct LayoutReport {
owner: Rc<()>,
sections: Vec<ResolvedSection>,
symbols: Vec<ResolvedLocation>,
imports: Vec<ResolvedLocation>,
}
impl LayoutReport {
pub fn section(&self, id: &SectionId) -> Option<&ResolvedSection> {
Rc::ptr_eq(&self.owner, &id.owner)
.then(|| self.sections.get(id.index))
.flatten()
}
pub fn symbol(&self, id: &SymbolId) -> Option<&ResolvedLocation> {
Rc::ptr_eq(&self.owner, &id.owner)
.then(|| self.symbols.get(id.index))
.flatten()
}
pub fn import(&self, id: &ImportId) -> Option<&ResolvedLocation> {
Rc::ptr_eq(&self.owner, &id.owner)
.then(|| self.imports.get(id.index))
.flatten()
}
}
#[derive(Clone, PartialEq, Eq)]
enum ImportName {
Name(String),
Ordinal(u16),
}
#[derive(Clone)]
struct Import {
dll: String,
name: ImportName,
}
struct Export {
ordinal: u32,
name: Option<String>,
symbol: SymbolId,
}
pub struct PeBuilder {
owner: Rc<()>,
target: Target,
kind: ImageKind,
pub image_base: u64,
pub file_alignment: u32,
pub section_alignment: u32,
pub subsystem: u16,
sections: Vec<SectionSpec>,
symbols: Vec<(SectionId, u32)>,
imports: Vec<Import>,
exports: Vec<Export>,
export_name: String,
export_base: Option<u32>,
resources: Option<super::resource::ResourceDirectoryOwned>,
entry: Option<SymbolId>,
fixups: Vec<Fixup>,
tls: Option<TlsSpec>,
functions: Vec<(SymbolId, SymbolId, SymbolId)>,
}
fn invalid<T>() -> Result<T> {
Err(FileParseError::InvalidFileFormat)
}
fn u32n(n: usize) -> Result<u32> {
u32::try_from(n).map_err(|_| FileParseError::ValueTooLarge)
}
fn add(a: u32, b: u32) -> Result<u32> {
a.checked_add(b).ok_or(FileParseError::ValueTooLarge)
}
fn align(n: u32, a: u32) -> Result<u32> {
Ok(add(n, a - 1)? & !(a - 1))
}
fn string_ok(s: &str) -> bool {
!s.is_empty() && !s.as_bytes().contains(&0)
}
impl PeBuilder {
pub fn new(target: Target, kind: ImageKind) -> Self {
Self {
owner: Rc::new(()),
target,
kind,
image_base: if target == Target::X86 {
0x400000
} else {
0x140000000
},
file_alignment: 0x200,
section_alignment: 0x1000,
subsystem: 3,
sections: Vec::new(),
symbols: Vec::new(),
imports: Vec::new(),
exports: Vec::new(),
export_name: "hexspell.dll".to_string(),
export_base: None,
resources: None,
entry: None,
fixups: Vec::new(),
tls: None,
functions: Vec::new(),
}
}
fn owns(&self, owner: &Rc<()>) -> Result<()> {
if Rc::ptr_eq(&self.owner, owner) {
Ok(())
} else {
invalid()
}
}
fn symbol_index(&self, s: &SymbolId) -> Result<usize> {
self.owns(&s.owner)?;
if s.index >= self.symbols.len() {
return invalid();
}
Ok(s.index)
}
pub fn add_section(&mut self, s: SectionSpec) -> Result<SectionId> {
if !string_ok(&s.name)
|| s.name.len() > 8
|| [".idata", ".edata", ".reloc", ".tlsdir", ".pdata", ".rsrc"]
.contains(&s.name.as_str())
|| s.virtual_size < u32n(s.data.len())?
{
return invalid();
}
let id = SectionId {
owner: self.owner.clone(),
index: self.sections.len(),
};
self.sections.push(s);
Ok(id)
}
pub fn define_symbol(&mut self, section: &SectionId, offset: u32) -> Result<SymbolId> {
self.owns(§ion.owner)?;
let s = self
.sections
.get(section.index)
.ok_or(FileParseError::InvalidFileFormat)?;
if offset > s.virtual_size {
return invalid();
}
let id = SymbolId {
owner: self.owner.clone(),
index: self.symbols.len(),
};
self.symbols.push((section.clone(), offset));
Ok(id)
}
fn executable(&self, id: &SymbolId) -> Result<()> {
let (s, o) = &self.symbols[self.symbol_index(id)?];
let sec = &self.sections[s.index];
if sec.characteristics & 0x20000000 == 0 || *o as usize >= sec.data.len() {
return invalid();
}
Ok(())
}
pub fn set_entry_point(&mut self, s: &SymbolId) -> Result<()> {
self.executable(s)?;
self.entry = Some(s.clone());
Ok(())
}
pub fn set_export_name(&mut self, name: &str) -> Result<()> {
if !string_ok(name) {
return invalid();
}
self.export_name = name.to_string();
Ok(())
}
pub fn add_import(&mut self, dll: &str, name: &str) -> Result<ImportId> {
if !string_ok(name) {
return invalid();
}
self.import(dll, ImportName::Name(name.to_string()))
}
pub fn add_import_ordinal(&mut self, dll: &str, ordinal: u16) -> Result<ImportId> {
if ordinal == 0 {
return invalid();
}
self.import(dll, ImportName::Ordinal(ordinal))
}
fn import(&mut self, dll: &str, name: ImportName) -> Result<ImportId> {
if !string_ok(dll) {
return invalid();
}
let index = if let Some(i) = self
.imports
.iter()
.position(|i| i.dll == dll && i.name == name)
{
i
} else {
let i = self.imports.len();
self.imports.push(Import {
dll: dll.to_string(),
name,
});
i
};
Ok(ImportId {
owner: self.owner.clone(),
index,
})
}
pub fn add_export(
&mut self,
ordinal: u32,
name: Option<&str>,
symbol: &SymbolId,
) -> Result<()> {
self.executable(symbol)?;
if ordinal == 0
|| ordinal > 65535
|| name.is_some_and(|n| !string_ok(n))
|| self
.exports
.iter()
.any(|e| e.ordinal == ordinal || name.is_some_and(|n| e.name.as_deref() == Some(n)))
{
return invalid();
}
self.exports.push(Export {
ordinal,
name: name.map(ToString::to_string),
symbol: symbol.clone(),
});
Ok(())
}
pub fn add_fixup(&mut self, f: Fixup) -> Result<()> {
self.owns(&f.section.owner)?;
match &f.target {
FixupTarget::Symbol(s) => {
self.symbol_index(s)?;
}
FixupTarget::Import(i) => {
self.owns(&i.owner)?;
if i.index >= self.imports.len() {
return invalid();
}
}
}
self.fixups.push(f);
Ok(())
}
pub fn set_tls(&mut self, t: TlsSpec) -> Result<()> {
for s in [&t.start, &t.end, &t.index] {
self.symbol_index(s)?;
}
for s in &t.callbacks {
self.executable(s)?;
}
if !t.alignment.is_power_of_two() || t.alignment > 8192 {
return invalid();
}
let (a, ao) = &self.symbols[t.start.index];
let (b, bo) = &self.symbols[t.end.index];
if a.index != b.index || ao > bo || *bo as usize > self.sections[a.index].data.len() {
return invalid();
}
let (i, o) = &self.symbols[t.index.index];
let sec = &self.sections[i.index];
if sec.characteristics & 0x80000000 == 0 || add(*o, 4)? as usize > sec.data.len() {
return invalid();
}
self.tls = Some(t);
Ok(())
}
pub fn add_runtime_function(
&mut self,
begin: &SymbolId,
end: &SymbolId,
unwind: &SymbolId,
) -> Result<()> {
if self.target != Target::X64 {
return Err(FileParseError::UnsupportedFeature(
"x86 runtime function".to_string(),
));
}
self.executable(begin)?;
self.symbol_index(end)?;
self.symbol_index(unwind)?;
let (a, x) = &self.symbols[begin.index];
let (b, y) = &self.symbols[end.index];
let (u, o) = &self.symbols[unwind.index];
if a.index != b.index
|| x >= y
|| *y as usize > self.sections[a.index].data.len()
|| o % 4 != 0
|| add(*o, 4)? as usize > self.sections[u.index].data.len()
{
return invalid();
}
self.functions
.push((begin.clone(), end.clone(), unwind.clone()));
Ok(())
}
pub fn set_export_base(&mut self, base: u32) -> Result<()> {
if base == 0 || base > 65535 {
return invalid();
}
self.export_base = Some(base);
Ok(())
}
pub fn set_resources(&mut self, resources: super::resource::ResourceDirectoryOwned) {
self.resources = Some(resources);
}
pub fn build(&self) -> Result<PE> {
Ok(self.build_with_layout()?.0)
}
pub fn build_with_layout(&self) -> Result<(PE, LayoutReport)> {
emit::build(self)
}
}