Initial commit
Rust workspace for VIctory: PE analysis, loader, HLE skeleton, DXBC/DXIL parsing with a GFX10 decoder, conversion cache, CLI and asset-policy enforcement. Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
commit
f4504f6413
69 files changed
+7952
No files matched your search
@@ -0,0 +1,472 @@
|
||||
use object::LittleEndian as LE;
|
||||
use object::Object;
|
||||
use object::pe::{self, ImageNtHeaders64};
|
||||
use object::read::pe::{
|
||||
ExportTarget, ImageNtHeaders, ImageOptionalHeader, Import, ImportTable, ImportThunkList,
|
||||
PeFile64,
|
||||
};
|
||||
|
||||
use crate::layout::{self, dir};
|
||||
use crate::{MACHINE_AMD64, PeError};
|
||||
|
||||
/// Everything we need to know about a PE32+ image, extracted in one pass.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ImageInfo {
|
||||
pub machine: u16,
|
||||
/// `IMAGE_FILE_HEADER::Characteristics`.
|
||||
pub characteristics: u16,
|
||||
pub timestamp: u32,
|
||||
pub subsystem: u16,
|
||||
/// `IMAGE_OPTIONAL_HEADER64::DllCharacteristics`.
|
||||
pub dll_characteristics: u16,
|
||||
pub image_base: u64,
|
||||
pub size_of_image: u32,
|
||||
pub entry_rva: u32,
|
||||
pub stack_reserve: u64,
|
||||
pub stack_commit: u64,
|
||||
pub sections: Vec<SectionInfo>,
|
||||
pub imports: Vec<ImportModule>,
|
||||
pub delay_imports: Vec<ImportModule>,
|
||||
pub exports: Vec<ExportInfo>,
|
||||
pub tls: Option<TlsInfo>,
|
||||
pub has_relocations: bool,
|
||||
pub has_exception_table: bool,
|
||||
pub has_load_config: bool,
|
||||
pub codeview: Option<CodeViewInfo>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct SectionInfo {
|
||||
pub name: String,
|
||||
pub rva: u32,
|
||||
pub virtual_size: u32,
|
||||
pub file_offset: u32,
|
||||
pub file_size: u32,
|
||||
pub characteristics: u32,
|
||||
}
|
||||
|
||||
/// One imported DLL and the functions taken from it.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ImportModule {
|
||||
/// DLL name exactly as written in the image (case preserved).
|
||||
pub dll: String,
|
||||
pub entries: Vec<ImportEntry>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ImportEntry {
|
||||
pub symbol: ImportSymbol,
|
||||
/// RVA of the 8-byte IAT slot the loader must fill in.
|
||||
pub iat_slot_rva: u32,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Hash, PartialOrd, Ord)]
|
||||
pub enum ImportSymbol {
|
||||
Name { hint: u16, name: String },
|
||||
Ordinal(u16),
|
||||
}
|
||||
|
||||
impl std::fmt::Display for ImportSymbol {
|
||||
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
|
||||
match self {
|
||||
ImportSymbol::Name { name, .. } => f.write_str(name),
|
||||
ImportSymbol::Ordinal(o) => write!(f, "#{o}"),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ExportInfo {
|
||||
pub name: Option<String>,
|
||||
pub ordinal: u16,
|
||||
/// `None` for forwarded exports.
|
||||
pub rva: Option<u32>,
|
||||
/// `"dll.name"` or `"dll.#ordinal"` for forwarded exports.
|
||||
pub forward: Option<String>,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct TlsInfo {
|
||||
/// RVA of `IMAGE_TLS_DIRECTORY64`.
|
||||
pub directory_rva: u32,
|
||||
/// VA (at the preferred base) of the callback array, 0 if none.
|
||||
pub callbacks_va: u64,
|
||||
/// Callback RVAs, in call order.
|
||||
pub callback_rvas: Vec<u32>,
|
||||
}
|
||||
|
||||
/// CodeView (RSDS) record: identifies the exact build that produced an image.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct CodeViewInfo {
|
||||
pub pdb_path: String,
|
||||
pub guid: [u8; 16],
|
||||
pub age: u32,
|
||||
}
|
||||
|
||||
impl CodeViewInfo {
|
||||
/// The key symbol servers use: GUID (Windows byte order) + age.
|
||||
pub fn symbol_key(&self) -> String {
|
||||
let g = &self.guid;
|
||||
let d1 = u32::from_le_bytes([g[0], g[1], g[2], g[3]]);
|
||||
let d2 = u16::from_le_bytes([g[4], g[5]]);
|
||||
let d3 = u16::from_le_bytes([g[6], g[7]]);
|
||||
let mut s = format!("{d1:08X}{d2:04X}{d3:04X}");
|
||||
for b in &g[8..] {
|
||||
s.push_str(&format!("{b:02X}"));
|
||||
}
|
||||
s.push_str(&format!("{:X}", self.age));
|
||||
s
|
||||
}
|
||||
}
|
||||
|
||||
/// Upper bound on TLS callbacks we are willing to walk (defends against garbage).
|
||||
const MAX_TLS_CALLBACKS: usize = 1024;
|
||||
|
||||
impl ImageInfo {
|
||||
/// Parses a complete PE32+ x86-64 image from its file bytes.
|
||||
pub fn parse(data: &[u8]) -> Result<Self, PeError> {
|
||||
let kind = object::FileKind::parse(data)?;
|
||||
if kind != object::FileKind::Pe64 {
|
||||
return Err(PeError::Unsupported(format!(
|
||||
"expected PE32+, found {kind:?}"
|
||||
)));
|
||||
}
|
||||
let file = PeFile64::parse(data)?;
|
||||
let nt = file.nt_headers();
|
||||
let fh = nt.file_header();
|
||||
let opt = nt.optional_header();
|
||||
|
||||
let machine = fh.machine.get(LE).0;
|
||||
if machine != MACHINE_AMD64 {
|
||||
return Err(PeError::Unsupported(format!(
|
||||
"machine 0x{machine:04x} is not AMD64"
|
||||
)));
|
||||
}
|
||||
|
||||
let sections = file
|
||||
.section_table()
|
||||
.iter()
|
||||
.map(|s| SectionInfo {
|
||||
name: String::from_utf8_lossy(s.raw_name()).into_owned(),
|
||||
rva: s.virtual_address.get(LE),
|
||||
virtual_size: s.virtual_size.get(LE),
|
||||
file_offset: s.pointer_to_raw_data.get(LE),
|
||||
file_size: s.size_of_raw_data.get(LE),
|
||||
characteristics: s.characteristics.get(LE).0,
|
||||
})
|
||||
.collect();
|
||||
|
||||
let dir_present = |index: usize| {
|
||||
file.data_directory(index)
|
||||
.is_some_and(|d| d.virtual_address.get(LE) != 0 && d.size.get(LE) != 0)
|
||||
};
|
||||
|
||||
let imports = match file.import_table()? {
|
||||
Some(table) => parse_imports(&table, opt.size_of_image())?,
|
||||
None => Vec::new(),
|
||||
};
|
||||
let delay_imports = parse_delay_imports(&file, opt.size_of_image())?;
|
||||
let exports = parse_exports(&file)?;
|
||||
let tls = parse_tls(&file, data, opt.image_base())?;
|
||||
let codeview = file.pdb_info()?.map(|cv| CodeViewInfo {
|
||||
pdb_path: String::from_utf8_lossy(cv.path()).into_owned(),
|
||||
guid: cv.guid(),
|
||||
age: cv.age(),
|
||||
});
|
||||
|
||||
Ok(ImageInfo {
|
||||
machine,
|
||||
characteristics: fh.characteristics.get(LE).0,
|
||||
timestamp: fh.time_date_stamp.get(LE),
|
||||
subsystem: opt.subsystem().0,
|
||||
dll_characteristics: opt.dll_characteristics().0,
|
||||
image_base: opt.image_base(),
|
||||
size_of_image: opt.size_of_image(),
|
||||
entry_rva: opt.address_of_entry_point(),
|
||||
stack_reserve: opt.size_of_stack_reserve(),
|
||||
stack_commit: opt.size_of_stack_commit(),
|
||||
sections,
|
||||
imports,
|
||||
delay_imports,
|
||||
exports,
|
||||
tls,
|
||||
has_relocations: dir_present(dir::BASERELOC)
|
||||
&& !has_flag(
|
||||
fh.characteristics.get(LE).0,
|
||||
layout::file_flags::RELOCS_STRIPPED,
|
||||
),
|
||||
has_exception_table: dir_present(dir::EXCEPTION),
|
||||
has_load_config: dir_present(dir::LOAD_CONFIG),
|
||||
codeview,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn is_dll(&self) -> bool {
|
||||
has_flag(self.characteristics, layout::file_flags::DLL)
|
||||
}
|
||||
|
||||
/// Maps an RVA to an offset in the file, if it is backed by file data.
|
||||
pub fn rva_to_file_offset(&self, rva: u32) -> Option<u32> {
|
||||
self.sections.iter().find_map(|s| {
|
||||
let delta = rva.checked_sub(s.rva)?;
|
||||
// Raw data may be padded past the virtual size; that padding is
|
||||
// not part of the section in memory.
|
||||
let backed = match s.virtual_size {
|
||||
0 => s.file_size,
|
||||
vs => vs.min(s.file_size),
|
||||
};
|
||||
(delta < backed).then(|| s.file_offset + delta)
|
||||
})
|
||||
}
|
||||
|
||||
pub fn import_count(&self) -> usize {
|
||||
self.imports.iter().map(|m| m.entries.len()).sum()
|
||||
}
|
||||
|
||||
pub fn subsystem_name(&self) -> &'static str {
|
||||
use layout::subsystem::*;
|
||||
match self.subsystem {
|
||||
WINDOWS_GUI => "windows-gui",
|
||||
WINDOWS_CUI => "windows-cui",
|
||||
XBOX => "xbox",
|
||||
XBOX_CODE_CATALOG => "xbox-code-catalog",
|
||||
_ => "other",
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn has_flag(value: u16, flag: u16) -> bool {
|
||||
value & flag != 0
|
||||
}
|
||||
|
||||
fn utf8(bytes: &[u8]) -> String {
|
||||
String::from_utf8_lossy(bytes).into_owned()
|
||||
}
|
||||
|
||||
fn convert_import(import: Import<'_>) -> ImportSymbol {
|
||||
match import {
|
||||
Import::Ordinal(o) => ImportSymbol::Ordinal(o),
|
||||
Import::Name(hint, name) => ImportSymbol::Name {
|
||||
hint,
|
||||
name: utf8(name),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
fn parse_imports(
|
||||
table: &ImportTable<'_>,
|
||||
size_of_image: u32,
|
||||
) -> Result<Vec<ImportModule>, PeError> {
|
||||
let mut modules = Vec::new();
|
||||
let mut descriptors = table.descriptors()?;
|
||||
while let Some(desc) = descriptors.next()? {
|
||||
let iat_rva = desc.first_thunk.get(LE);
|
||||
// Prefer the unbound name table; fall back to the IAT for old linkers.
|
||||
let int_rva = match desc.original_first_thunk.get(LE) {
|
||||
0 => iat_rva,
|
||||
rva => rva,
|
||||
};
|
||||
modules.push(ImportModule {
|
||||
dll: utf8(table.name(desc.name.get(LE))?),
|
||||
entries: entries(table.thunks(int_rva)?, iat_rva, size_of_image, |t| {
|
||||
table.import::<ImageNtHeaders64>(t)
|
||||
})?,
|
||||
});
|
||||
}
|
||||
Ok(modules)
|
||||
}
|
||||
|
||||
fn parse_delay_imports(
|
||||
file: &PeFile64<'_>,
|
||||
size_of_image: u32,
|
||||
) -> Result<Vec<ImportModule>, PeError> {
|
||||
let Some(table) = file.delay_load_import_table()? else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
let mut modules = Vec::new();
|
||||
let mut descriptors = table.descriptors()?;
|
||||
while let Some(desc) = descriptors.next()? {
|
||||
modules.push(ImportModule {
|
||||
dll: utf8(table.name(desc.dll_name_rva.get(LE))?),
|
||||
entries: entries(
|
||||
table.thunks(desc.import_name_table_rva.get(LE))?,
|
||||
desc.import_address_table_rva.get(LE),
|
||||
size_of_image,
|
||||
|t| table.import::<ImageNtHeaders64>(t),
|
||||
)?,
|
||||
});
|
||||
}
|
||||
Ok(modules)
|
||||
}
|
||||
|
||||
/// Pairs each name-table entry with its IAT slot. The IAT RVA is not checked
|
||||
/// by `object`, so every slot is checked to lie inside the image here.
|
||||
fn entries<'data>(
|
||||
mut thunks: ImportThunkList<'data>,
|
||||
iat_rva: u32,
|
||||
size_of_image: u32,
|
||||
import: impl Fn(pe::ImageThunkData64) -> object::read::Result<Import<'data>>,
|
||||
) -> Result<Vec<ImportEntry>, PeError> {
|
||||
let mut entries = Vec::new();
|
||||
while let Some(thunk) = thunks.next::<ImageNtHeaders64>()? {
|
||||
let iat_slot_rva = u32::try_from(entries.len() * 8)
|
||||
.ok()
|
||||
.and_then(|offset| iat_rva.checked_add(offset))
|
||||
.filter(|&rva| rva.checked_add(8).is_some_and(|end| end <= size_of_image))
|
||||
.ok_or_else(|| {
|
||||
PeError::Malformed(format!("IAT at {iat_rva:#x} runs outside the image"))
|
||||
})?;
|
||||
entries.push(ImportEntry {
|
||||
symbol: convert_import(import(thunk)?),
|
||||
iat_slot_rva,
|
||||
});
|
||||
}
|
||||
Ok(entries)
|
||||
}
|
||||
|
||||
fn parse_exports(file: &PeFile64<'_>) -> Result<Vec<ExportInfo>, PeError> {
|
||||
let Some(table) = file.export_table()? else {
|
||||
return Ok(Vec::new());
|
||||
};
|
||||
Ok(table
|
||||
.exports()?
|
||||
.into_iter()
|
||||
.map(|e| {
|
||||
let (rva, forward) = match e.target {
|
||||
ExportTarget::Address(rva) => (Some(rva), None),
|
||||
ExportTarget::ForwardByName(d, n) => {
|
||||
(None, Some(format!("{}.{}", utf8(d), utf8(n))))
|
||||
}
|
||||
ExportTarget::ForwardByOrdinal(d, o) => {
|
||||
(None, Some(format!("{}.#{}", utf8(d), o.0)))
|
||||
}
|
||||
};
|
||||
ExportInfo {
|
||||
name: e.name.map(utf8),
|
||||
ordinal: e.ordinal.0,
|
||||
rva,
|
||||
forward,
|
||||
}
|
||||
})
|
||||
.collect())
|
||||
}
|
||||
|
||||
fn parse_tls(
|
||||
file: &PeFile64<'_>,
|
||||
data: &[u8],
|
||||
image_base: u64,
|
||||
) -> Result<Option<TlsInfo>, PeError> {
|
||||
let Some(dd) = file.data_directory(pe::IMAGE_DIRECTORY_ENTRY_TLS) else {
|
||||
return Ok(None);
|
||||
};
|
||||
let directory_rva = dd.virtual_address.get(LE);
|
||||
if directory_rva == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let sections = file.section_table();
|
||||
let tls = sections
|
||||
.pe_data_at(data, directory_rva)
|
||||
.ok_or_else(|| PeError::Malformed("TLS directory outside of sections".into()))?;
|
||||
let callbacks_va = layout::read_u64(tls, layout::TLS64_ADDRESS_OF_CALLBACKS)
|
||||
.ok_or_else(|| PeError::Malformed("truncated TLS directory".into()))?;
|
||||
|
||||
let mut callback_rvas = Vec::new();
|
||||
if callbacks_va != 0 {
|
||||
let array_rva = va_to_rva(callbacks_va, image_base)?;
|
||||
let array = sections
|
||||
.pe_data_at(data, array_rva)
|
||||
.ok_or_else(|| PeError::Malformed("TLS callback array outside of sections".into()))?;
|
||||
for slot in array.as_chunks::<8>().0.iter().take(MAX_TLS_CALLBACKS) {
|
||||
let va = u64::from_le_bytes(*slot);
|
||||
if va == 0 {
|
||||
break;
|
||||
}
|
||||
callback_rvas.push(va_to_rva(va, image_base)?);
|
||||
}
|
||||
}
|
||||
Ok(Some(TlsInfo {
|
||||
directory_rva,
|
||||
callbacks_va,
|
||||
callback_rvas,
|
||||
}))
|
||||
}
|
||||
|
||||
fn va_to_rva(va: u64, image_base: u64) -> Result<u32, PeError> {
|
||||
va.checked_sub(image_base)
|
||||
.and_then(|rva| u32::try_from(rva).ok())
|
||||
.ok_or_else(|| PeError::Malformed(format!("VA 0x{va:x} is outside the image")))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// The test binary itself is a real MSVC-linked PE32+ image.
|
||||
fn own_image() -> Vec<u8> {
|
||||
std::fs::read(std::env::current_exe().unwrap()).unwrap()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn parses_own_test_binary() {
|
||||
let info = ImageInfo::parse(&own_image()).unwrap();
|
||||
assert_eq!(info.machine, MACHINE_AMD64);
|
||||
assert!(!info.is_dll());
|
||||
assert!(info.entry_rva != 0);
|
||||
assert!(info.has_exception_table, "x64 images always carry .pdata");
|
||||
assert!(info.sections.iter().any(|s| s.name.starts_with(".text")));
|
||||
let kernel32 = info
|
||||
.imports
|
||||
.iter()
|
||||
.find(|m| m.dll.eq_ignore_ascii_case("kernel32.dll"))
|
||||
.expect("Rust std imports kernel32");
|
||||
assert!(kernel32.entries.iter().all(|e| e.iat_slot_rva != 0));
|
||||
// Rust std uses static TLS, so a TLS directory must be present (its
|
||||
// callback array may legitimately be empty).
|
||||
assert!(info.tls.is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rva_to_file_offset_maps_entry_point() {
|
||||
let data = own_image();
|
||||
let info = ImageInfo::parse(&data).unwrap();
|
||||
let off = info.rva_to_file_offset(info.entry_rva).unwrap() as usize;
|
||||
assert!(off < data.len());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_garbage_without_panicking() {
|
||||
assert!(ImageInfo::parse(b"").is_err());
|
||||
assert!(ImageInfo::parse(b"MZ not really").is_err());
|
||||
let mut truncated = own_image();
|
||||
truncated.truncate(0x200);
|
||||
assert!(ImageInfo::parse(&truncated).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn rejects_iat_outside_image() {
|
||||
let mut data = own_image();
|
||||
let dd = layout::data_directory_offset(&data, dir::IMPORT).unwrap();
|
||||
let import_rva = layout::read_u32(&data, dd).unwrap();
|
||||
let desc = ImageInfo::parse(&data)
|
||||
.unwrap()
|
||||
.rva_to_file_offset(import_rva)
|
||||
.unwrap() as usize;
|
||||
// First descriptor's FirstThunk, at the 4 GiB limit: used to overflow.
|
||||
data[desc + 16..desc + 20].copy_from_slice(&0xFFFF_FFF8u32.to_le_bytes());
|
||||
assert!(matches!(
|
||||
ImageInfo::parse(&data),
|
||||
Err(PeError::Malformed(_))
|
||||
));
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod dbg_tls {
|
||||
#[test]
|
||||
fn dump_tls() {
|
||||
let data = std::fs::read(std::env::current_exe().unwrap()).unwrap();
|
||||
let info = super::ImageInfo::parse(&data).unwrap();
|
||||
eprintln!("TLS = {:?}", info.tls);
|
||||
eprintln!("image_base = {:x}", info.image_base);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
//! COFF import libraries (`.lib`).
|
||||
//!
|
||||
//! An umbrella import library tells us which DLL provides each API that a
|
||||
//! console title may link against. That is the map the runtime needs to
|
||||
//! decide which of our implementations answers which import.
|
||||
|
||||
use object::read::archive::ArchiveFile;
|
||||
use object::read::coff::{ImportFile, ImportName, ImportType};
|
||||
|
||||
use crate::{ImportSymbol, PeError};
|
||||
|
||||
/// One `dll!export` pair described by an import library.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub struct LibImport {
|
||||
pub dll: String,
|
||||
pub export: ImportSymbol,
|
||||
pub kind: LibImportKind,
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
|
||||
pub enum LibImportKind {
|
||||
Code,
|
||||
Data,
|
||||
Const,
|
||||
}
|
||||
|
||||
/// Result of reading an import library.
|
||||
#[derive(Debug, Default)]
|
||||
pub struct ImportLibrary {
|
||||
pub imports: Vec<LibImport>,
|
||||
/// Members that are not short-format import objects (regular objects,
|
||||
/// long-format import descriptors). Reported so nothing is silently lost.
|
||||
pub other_members: usize,
|
||||
}
|
||||
|
||||
impl ImportLibrary {
|
||||
pub fn parse(data: &[u8]) -> Result<Self, PeError> {
|
||||
let archive = ArchiveFile::parse(data)?;
|
||||
let mut lib = ImportLibrary::default();
|
||||
for member in archive.members() {
|
||||
let member = member?;
|
||||
let bytes = member.data(data)?;
|
||||
match ImportFile::parse(bytes) {
|
||||
Ok(import) => lib.imports.push(LibImport {
|
||||
dll: String::from_utf8_lossy(import.dll()).into_owned(),
|
||||
export: match import.import() {
|
||||
ImportName::Name(name) => ImportSymbol::Name {
|
||||
hint: 0,
|
||||
name: String::from_utf8_lossy(name).into_owned(),
|
||||
},
|
||||
ImportName::Ordinal(o) => ImportSymbol::Ordinal(o),
|
||||
},
|
||||
kind: match import.import_type() {
|
||||
ImportType::Code => LibImportKind::Code,
|
||||
ImportType::Data => LibImportKind::Data,
|
||||
ImportType::Const => LibImportKind::Const,
|
||||
},
|
||||
}),
|
||||
Err(_) => lib.other_members += 1,
|
||||
}
|
||||
}
|
||||
lib.imports.sort();
|
||||
lib.imports.dedup();
|
||||
Ok(lib)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
//! Raw byte offsets of PE32+ header fields, for code that patches images.
|
||||
//!
|
||||
//! All offsets are relative to the start of the structure named in the
|
||||
//! constant's prefix. They follow the published PE/COFF specification.
|
||||
|
||||
/// Offset of `e_lfanew` (u32) in the DOS header.
|
||||
pub const DOS_E_LFANEW: usize = 0x3C;
|
||||
|
||||
/// Size of the `PE\0\0` signature that precedes the file header.
|
||||
pub const NT_SIGNATURE_SIZE: usize = 4;
|
||||
/// Size of `IMAGE_FILE_HEADER`.
|
||||
pub const FILE_HEADER_SIZE: usize = 20;
|
||||
|
||||
/// `IMAGE_FILE_HEADER::Characteristics` (u16).
|
||||
pub const FILE_HEADER_CHARACTERISTICS: usize = 18;
|
||||
|
||||
/// `IMAGE_OPTIONAL_HEADER64::AddressOfEntryPoint` (u32).
|
||||
pub const OPT_ADDRESS_OF_ENTRY_POINT: usize = 16;
|
||||
/// `IMAGE_OPTIONAL_HEADER64::CheckSum` (u32).
|
||||
pub const OPT_CHECKSUM: usize = 64;
|
||||
/// `IMAGE_OPTIONAL_HEADER64::DllCharacteristics` (u16).
|
||||
pub const OPT_DLL_CHARACTERISTICS: usize = 70;
|
||||
/// `IMAGE_OPTIONAL_HEADER64::NumberOfRvaAndSizes` (u32).
|
||||
pub const OPT_NUMBER_OF_RVA_AND_SIZES: usize = 108;
|
||||
/// First `IMAGE_DATA_DIRECTORY` entry (each is `{ rva: u32, size: u32 }`).
|
||||
pub const OPT_DATA_DIRECTORY: usize = 112;
|
||||
/// Size of one `IMAGE_DATA_DIRECTORY`.
|
||||
pub const DATA_DIRECTORY_SIZE: usize = 8;
|
||||
|
||||
/// `IMAGE_TLS_DIRECTORY64::AddressOfCallBacks` (u64 VA).
|
||||
pub const TLS64_ADDRESS_OF_CALLBACKS: usize = 24;
|
||||
|
||||
/// Data directory indices.
|
||||
pub mod dir {
|
||||
pub const IMPORT: usize = 1;
|
||||
pub const EXCEPTION: usize = 3;
|
||||
pub const BASERELOC: usize = 5;
|
||||
pub const LOAD_CONFIG: usize = 10;
|
||||
pub const BOUND_IMPORT: usize = 11;
|
||||
}
|
||||
|
||||
/// `IMAGE_FILE_HEADER::Characteristics` flags.
|
||||
pub mod file_flags {
|
||||
pub const RELOCS_STRIPPED: u16 = 0x0001;
|
||||
pub const DLL: u16 = 0x2000;
|
||||
}
|
||||
|
||||
/// `IMAGE_OPTIONAL_HEADER64::DllCharacteristics` flags.
|
||||
pub mod dll_flags {
|
||||
pub const HIGH_ENTROPY_VA: u16 = 0x0020;
|
||||
pub const DYNAMIC_BASE: u16 = 0x0040;
|
||||
pub const FORCE_INTEGRITY: u16 = 0x0080;
|
||||
pub const NX_COMPAT: u16 = 0x0100;
|
||||
pub const APPCONTAINER: u16 = 0x1000;
|
||||
pub const GUARD_CF: u16 = 0x4000;
|
||||
}
|
||||
|
||||
/// `IMAGE_OPTIONAL_HEADER64::Subsystem` values.
|
||||
pub mod subsystem {
|
||||
pub const WINDOWS_GUI: u16 = 2;
|
||||
pub const WINDOWS_CUI: u16 = 3;
|
||||
pub const XBOX: u16 = 14;
|
||||
pub const XBOX_CODE_CATALOG: u16 = 17;
|
||||
}
|
||||
|
||||
/// Offset of the optional header from the start of the file.
|
||||
pub fn optional_header_offset(data: &[u8]) -> Option<usize> {
|
||||
let lfanew = read_u32(data, DOS_E_LFANEW)? as usize;
|
||||
Some(lfanew + NT_SIGNATURE_SIZE + FILE_HEADER_SIZE)
|
||||
}
|
||||
|
||||
/// Offset of the file header from the start of the file.
|
||||
pub fn file_header_offset(data: &[u8]) -> Option<usize> {
|
||||
let lfanew = read_u32(data, DOS_E_LFANEW)? as usize;
|
||||
Some(lfanew + NT_SIGNATURE_SIZE)
|
||||
}
|
||||
|
||||
/// Offset of data directory `index` from the start of the file.
|
||||
pub fn data_directory_offset(data: &[u8], index: usize) -> Option<usize> {
|
||||
let opt = optional_header_offset(data)?;
|
||||
let count = read_u32(data, opt + OPT_NUMBER_OF_RVA_AND_SIZES)? as usize;
|
||||
(index < count).then_some(opt + OPT_DATA_DIRECTORY + index * DATA_DIRECTORY_SIZE)
|
||||
}
|
||||
|
||||
pub fn read_u32(data: &[u8], at: usize) -> Option<u32> {
|
||||
Some(u32::from_le_bytes(data.get(at..at + 4)?.try_into().ok()?))
|
||||
}
|
||||
|
||||
pub fn read_u64(data: &[u8], at: usize) -> Option<u64> {
|
||||
Some(u64::from_le_bytes(data.get(at..at + 8)?.try_into().ok()?))
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
//! Read-only analysis of PE32+ (x86-64) images and COFF import libraries.
|
||||
//!
|
||||
//! Xbox Series X|S titles are ordinary x86-64 PE32+ images (the console CPU
|
||||
//! is a Zen 2), so the same parser serves titles, console system DLLs and
|
||||
//! host binaries alike. This crate never modifies anything; patching lives in
|
||||
//! `victory-loader`, which uses the raw offsets exported from [`layout`].
|
||||
|
||||
mod image;
|
||||
pub mod implib;
|
||||
pub mod layout;
|
||||
|
||||
pub use image::{
|
||||
CodeViewInfo, ExportInfo, ImageInfo, ImportEntry, ImportModule, ImportSymbol, SectionInfo,
|
||||
TlsInfo,
|
||||
};
|
||||
|
||||
/// Errors produced while parsing an image or import library.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum PeError {
|
||||
/// The file is a valid PE but not one we handle (e.g. 32-bit or ARM64).
|
||||
#[error("unsupported image: {0}")]
|
||||
Unsupported(String),
|
||||
/// The file is truncated or internally inconsistent.
|
||||
#[error("malformed image: {0}")]
|
||||
Malformed(String),
|
||||
}
|
||||
|
||||
impl From<object::read::Error> for PeError {
|
||||
fn from(e: object::read::Error) -> Self {
|
||||
PeError::Malformed(e.to_string())
|
||||
}
|
||||
}
|
||||
|
||||
/// `IMAGE_FILE_MACHINE_AMD64`.
|
||||
pub const MACHINE_AMD64: u16 = 0x8664;
|
||||
Reference in new issue
Block a user