loader: map the PE headers at the image base (#333)

Windows maps the first SizeOfHeaders bytes of an image read-only at its
base, and programs read them: the mingw-w64 C runtime walks its own
section table before main. The loader mapped sections only, so that read
faulted.

Map the headers in whole 4 KiB pages before the sections, with the
optional header's ImageBase field set to the base the image is loaded
at. Refuse the load with PeError::InvalidHeaderSize when SizeOfHeaders
ends before the section table, runs past the file, or its pages reach
into a section. The header pages count toward the mapping budget.
ParsedPe::parse is unchanged.

The hand-built image in pe_mapping_limits.rs wrote SizeOfHeaders as
zero; it now writes a valid value.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
This commit is contained in:
zachdoxsee committed 2026-11-24 18:15:56 +01:00
1 parent 1d363c3c34
commit b8fbdf35b9
5 files changed
+417 -11

No files matched your search

+1
View File
@@ -17,6 +17,7 @@ remains unsupported.
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
### Added
- The loader now maps an image's PE headers at its image base (#333): the first `SizeOfHeaders` bytes of the file, read-only, in whole 4 KiB pages, with the optional header's `ImageBase` field holding the base the image was actually loaded at. Programs read their own headers this way; the mingw-w64 C runtime does so before `main`, and until now that read faulted. A load is refused with the new `PeError::InvalidHeaderSize` when `SizeOfHeaders` is zero, ends before the section table, runs past the file, or its pages would reach into a section, and the header pages count toward the 256 MiB mapping budget. `ParsedPe::parse` and the static probe are unchanged. `tests/pe_headers.rs` covers guest reads at the preferred and a relocated base, the write and execute faults and each refusal with original hand-built images; the image in `pe_mapping_limits.rs` now carries a valid `SizeOfHeaders`. Not compared with Windows; awaiting independent review.
- Added four Wave32 gfx1030 VOP2 select and carry forms through the semantic registry. Conditional select, add with carry and both subtract orders with borrow use a per-lane VCC bit and have a guide-derived oracle that passes on both CPU interpreters and on native Metal (local Apple M5, API and shader validation); independent acceptance is pending. Part of #215.
- Added decoding and Metal shader translation for twelve Wave32 VOPC 16-bit integer compares (#215). The signed and unsigned forms compare the low 16 bits of each source and write the Wave32 VCC mask. CPU verification covers 1,572 compiler acceptance cases and 408 rejections from the guide-derived oracle, which also passes on native Metal (1,572 cases in 1,420 programs on a local Apple M5 under API and shader validation); acceptance is pending.
- Added MOVS and STOS for 8- to 64-bit elements, with and without REP, and the direction flag with CLD and STD (#129). A REP form runs one element per step and stays on the instruction until RCX is zero, so every element counts against the step budget, a repeat can stop part-way and resume, a zero count touches nothing, and a fault keeps the elements already done with RSI, RDI and RCX at the one that faulted. An FS or GS override applies to the MOVS source only. Both engines run these on the shared semantics with no bulk-copy path, so large copies are slow. LODS, CMPS, SCAS, REPE, REPNE and the address-size override stay rejected. Fourteen SDM-derived cases already in `cpu_known_answers.rs` moved from refused to verified, and `tests/cpu_rep.rs` adds a byte-array model over every form, direction and count; not compared with x86 hardware and awaiting independent review.
+84 -8
View File
@@ -3,7 +3,8 @@
//! PE32+ (64-bit Portable Executable) format parser and section loader for Xenora.
//!
//! Parses standard PE32+ headers (DOS header, COFF header, Optional Header 64)
//! and loads valid section headers into `GuestMemory` with appropriate permissions.
//! and loads the headers and each section into `GuestMemory` with appropriate
//! permissions.
use crate::memory::{GuestMemory, MemoryError, MemoryPermissions};
use std::fmt;
@@ -19,6 +20,10 @@ pub enum PeError {
InvalidSectionHeaders,
SectionMappingError(MemoryError),
InvalidEntryPoint,
/// `SizeOfHeaders` does not describe headers that can be mapped at the
/// image base: it is zero, ends before the section table does, runs past
/// the end of the file, or its pages reach into a section.
InvalidHeaderSize,
}
impl fmt::Display for PeError {
@@ -42,6 +47,11 @@ impl fmt::Display for PeError {
Self::InvalidSectionHeaders => write!(f, "invalid or corrupt section headers"),
Self::SectionMappingError(e) => write!(f, "failed to map section: {e}"),
Self::InvalidEntryPoint => write!(f, "entry point address is outside executable code"),
Self::InvalidHeaderSize => write!(
f,
"SizeOfHeaders is zero, shorter than the section table, longer than the file, or \
reaches into a section"
),
}
}
}
@@ -94,9 +104,13 @@ pub const PE32_PLUS_MAGIC: u16 = 0x020B;
/// PE32+ optional header length up to and including NumberOfRvaAndSizes.
const PE32_PLUS_MIN_OPTIONAL_HEADER: usize = 112;
const SECTION_HEADER_SIZE: usize = 40;
/// Host memory budget for all mapped sections of one image. This is a loader policy
/// limit, not a property of the PE format.
/// Host memory budget for the mapped headers and sections of one image. This is a
/// loader policy limit, not a property of the PE format.
const MAX_MAPPED_IMAGE_BYTES: u64 = 256 * 1024 * 1024;
/// The mapped headers end on a guest page boundary.
const HEADER_PAGE: u64 = 0x1000;
/// `ImageBase` within the PE32+ optional header.
const OPTIONAL_IMAGE_BASE: usize = 24;
fn read_u16(bytes: &[u8], at: usize) -> u16 {
u16::from_le_bytes([bytes[at], bytes[at + 1]])
@@ -270,25 +284,87 @@ impl ParsedPe {
None
}
/// Load this parsed PE into a fresh `GuestMemory` instance, mapping all sections.
/// The header bytes to map at `base` and the page-rounded length of that
/// mapping. In the copy, `ImageBase` is the base the image is loaded at, as
/// it is on Windows after relocation.
///
/// The header offsets are read again from `bytes`, with every access
/// checked, because a caller may pass bytes other than the ones parsed.
fn headers_for(&self, bytes: &[u8], base: u64) -> Result<(Vec<u8>, u64), PeError> {
let field = |at: usize, len: usize| at.checked_add(len).and_then(|end| bytes.get(at..end));
let layout = || {
let e_lfanew = u32::from_le_bytes(field(0x3C, 4)?.try_into().ok()?) as usize;
let coff = e_lfanew.checked_add(4)?;
let sections = usize::from(u16::from_le_bytes(
field(coff.checked_add(2)?, 2)?.try_into().ok()?,
));
let optional_size = usize::from(u16::from_le_bytes(
field(coff.checked_add(16)?, 2)?.try_into().ok()?,
));
let optional = coff.checked_add(20)?;
let table_end = optional
.checked_add(optional_size)?
.checked_add(sections.checked_mul(SECTION_HEADER_SIZE)?)?;
Some((optional, table_end))
};
let (optional, table_end) = layout().ok_or(PeError::InvalidHeaderSize)?;
let image_base = optional
.checked_add(OPTIONAL_IMAGE_BASE)
.ok_or(PeError::InvalidHeaderSize)?;
// A size of zero is shorter than any section table.
let len = self.size_of_headers as usize;
if len < table_end || len > bytes.len() || image_base + 8 > len {
return Err(PeError::InvalidHeaderSize);
}
let mapped = u64::from(self.size_of_headers).next_multiple_of(HEADER_PAGE);
let reaches_a_section = self.sections.iter().any(|sec| {
sec.virtual_size.max(sec.raw_data_size) > 0 && u64::from(sec.virtual_address) < mapped
});
if reaches_a_section {
return Err(PeError::InvalidHeaderSize);
}
let mut headers = bytes[..len].to_vec();
headers[image_base..image_base + 8].copy_from_slice(&base.to_le_bytes());
Ok((headers, mapped))
}
/// Load this parsed PE into a fresh `GuestMemory` instance, mapping the
/// headers and all sections.
pub fn load_into_memory(&self, bytes: &[u8]) -> Result<LoadedImage, PeError> {
self.load_at_base(bytes, self.image_base)
}
pub(crate) fn load_at_base(&self, bytes: &[u8], base: u64) -> Result<LoadedImage, PeError> {
// Each section becomes a zero-filled host allocation, so bound the total before
// allocating anything. Sections may not overlap, so the sum is the mapped size.
let mapped: u64 = self
let (headers, headers_mapped) = self.headers_for(bytes, base)?;
// The headers and each section become zero-filled host allocations, so bound
// the total before allocating anything. Sections may not overlap, so the sum
// is the mapped size.
let mapped = self
.sections
.iter()
.map(|sec| u64::from(sec.virtual_size.max(sec.raw_data_size)))
.sum();
.sum::<u64>()
+ headers_mapped;
if mapped > MAX_MAPPED_IMAGE_BYTES {
return Err(PeError::SectionMappingError(MemoryError::AllocationFailed));
}
let mut memory = GuestMemory::new();
// Windows maps the headers read-only at the image base, and programs read
// them: a C runtime finds its own sections this way before `main`.
memory
.map_region_with_data(
base,
headers_mapped as usize,
MemoryPermissions::READ_ONLY,
&headers,
)
.map_err(PeError::SectionMappingError)?;
for sec in &self.sections {
let base_addr = base
.checked_add(u64::from(sec.virtual_address))
+312
View File
@@ -0,0 +1,312 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! The PE headers are mapped read-only at the image base (#333).
//!
//! Windows maps the first `SizeOfHeaders` bytes of an image at its base, and
//! programs read them: a C runtime walks its own section table before `main`.
//!
//! Every image here is original and built byte by byte in this file. Expected
//! values are the bytes the builder wrote, never values read back from a run.
use xenora_loader::cpu::{ExitReason, Register};
use xenora_loader::imports::ImportRegistry;
use xenora_loader::startup::{StartupLayout, StartupResult, run_synthetic_startup};
use xenora_loader::{MemoryError, ParsedPe, PeError};
const PREFERRED_BASE: u64 = 0x1_4000_0000;
const OTHER_BASE: u64 = 0x2_5000_0000;
/// Deliberately not the usual 0x40 or 0x80, so a read of it is distinctive.
const E_LFANEW: u32 = 0x90;
const OPTIONAL: usize = E_LFANEW as usize + 4 + 20;
const OPTIONAL_SIZE: usize = 240;
const SECTIONS: u16 = 2;
/// The first byte after the section table.
const TABLE_END: u32 = (OPTIONAL + OPTIONAL_SIZE) as u32 + 40 * SECTIONS as u32;
/// One image: `.text` holding `code` and an uninitialized `.data`.
struct Image {
size_of_headers: u32,
text_rva: u32,
data_rva: u32,
data_size: u32,
/// File offset of the code, and so the length of the file before it.
text_offset: u32,
code: Vec<u8>,
}
impl Image {
fn new(code: &[u8]) -> Self {
Self {
size_of_headers: 0x400,
text_rva: 0x2000,
data_rva: 0x3000,
data_size: 0x100,
text_offset: 0x400,
code: code.to_vec(),
}
}
fn build(&self) -> Vec<u8> {
let mut pe = vec![0u8; self.text_offset as usize + 0x200];
pe[0..2].copy_from_slice(b"MZ");
pe[0x3C..0x40].copy_from_slice(&E_LFANEW.to_le_bytes());
// A recognisable pattern where a DOS stub would be, and in the padding
// after the section table.
for (i, byte) in pe[0x40..E_LFANEW as usize].iter_mut().enumerate() {
*byte = (i * 7 + 3) as u8;
}
for (i, byte) in pe[TABLE_END as usize..self.text_offset as usize]
.iter_mut()
.enumerate()
{
*byte = (i * 5 + 1) as u8;
}
let pe_at = E_LFANEW as usize;
pe[pe_at..pe_at + 4].copy_from_slice(b"PE\0\0");
let coff = pe_at + 4;
pe[coff..coff + 2].copy_from_slice(&0x8664u16.to_le_bytes());
pe[coff + 2..coff + 4].copy_from_slice(&SECTIONS.to_le_bytes());
pe[coff + 16..coff + 18].copy_from_slice(&(OPTIONAL_SIZE as u16).to_le_bytes());
pe[coff + 18..coff + 20].copy_from_slice(&0x0022u16.to_le_bytes());
let opt = OPTIONAL;
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
pe[opt + 16..opt + 20].copy_from_slice(&self.text_rva.to_le_bytes());
pe[opt + 24..opt + 32].copy_from_slice(&PREFERRED_BASE.to_le_bytes());
pe[opt + 32..opt + 36].copy_from_slice(&0x1000u32.to_le_bytes());
pe[opt + 36..opt + 40].copy_from_slice(&0x200u32.to_le_bytes());
pe[opt + 56..opt + 60].copy_from_slice(&0x4000u32.to_le_bytes());
pe[opt + 60..opt + 64].copy_from_slice(&self.size_of_headers.to_le_bytes());
pe[opt + 108..opt + 112].copy_from_slice(&16u32.to_le_bytes());
let mut section = |i: usize, name: &[u8], rva: u32, size: u32, raw: u32, flags: u32| {
let h = opt + OPTIONAL_SIZE + i * 40;
pe[h..h + name.len()].copy_from_slice(name);
pe[h + 8..h + 12].copy_from_slice(&size.to_le_bytes());
pe[h + 12..h + 16].copy_from_slice(&rva.to_le_bytes());
pe[h + 16..h + 20]
.copy_from_slice(&(if raw == 0 { 0 } else { 0x200u32 }).to_le_bytes());
pe[h + 20..h + 24].copy_from_slice(&raw.to_le_bytes());
pe[h + 36..h + 40].copy_from_slice(&flags.to_le_bytes());
};
section(
0,
b".text",
self.text_rva,
0x200,
self.text_offset,
0x6000_0020,
);
section(1, b".data", self.data_rva, self.data_size, 0, 0xC000_0080);
let at = self.text_offset as usize;
pe[at..at + self.code.len()].copy_from_slice(&self.code);
pe
}
}
/// `lea rbx, [rip - (text_rva + 7)]`: the image base, wherever it was loaded.
fn base_into_rbx(text_rva: u32) -> Vec<u8> {
let mut code = vec![0x48, 0x8D, 0x1D];
code.extend((-(text_rva as i32 + 7)).to_le_bytes());
code
}
fn run(bytes: &[u8], base: u64) -> StartupResult {
let layout = StartupLayout {
image_base: base,
stack_top: 0x2_0001_0000,
tls_base: 0x3_0000_0000,
};
run_synthetic_startup(bytes, layout, ImportRegistry::new(), 1_000).expect("startup")
}
fn load_error(image: &Image) -> Option<PeError> {
let bytes = image.build();
let pe = ParsedPe::parse(&bytes).expect("the parser does not judge SizeOfHeaders");
pe.load_into_memory(&bytes).err()
}
#[test]
fn a_guest_reads_its_own_headers_at_the_preferred_and_at_a_relocated_base() {
let mut code = base_into_rbx(0x2000);
code.extend([
0x0F, 0xB7, 0x03, // movzx eax, word [rbx] DOS signature
0x8B, 0x4B, 0x3C, // mov ecx, [rbx + 0x3C] e_lfanew
0x8B, 0x14, 0x0B, // mov edx, [rbx + rcx] PE signature
0x0F, 0xB7, 0x74, 0x0B, 0x06, // movzx esi, word [rbx + rcx + 6] NumberOfSections
0x48, 0x8B, 0x7C, 0x0B, 0x30, // mov rdi, [rbx + rcx + 0x30] ImageBase
0xF4, // hlt
]);
let bytes = Image::new(&code).build();
for base in [PREFERRED_BASE, OTHER_BASE] {
let result = run(&bytes, base);
let cpu = &result.execution.final_state;
assert_eq!(result.execution.exit_reason, ExitReason::Halt, "{base:#x}");
assert_eq!(cpu.get(Register::Rbx), base, "{base:#x}");
assert_eq!(cpu.get(Register::Rax), 0x5A4D, "{base:#x}");
assert_eq!(cpu.get(Register::Rcx), u64::from(E_LFANEW), "{base:#x}");
assert_eq!(cpu.get(Register::Rdx), 0x0000_4550, "{base:#x}");
assert_eq!(cpu.get(Register::Rsi), u64::from(SECTIONS), "{base:#x}");
// The mapped header names the base the image is at, not the preferred one.
assert_eq!(cpu.get(Register::Rdi), base, "{base:#x}");
}
}
#[test]
fn the_mapping_is_the_file_headers_then_zeros_to_the_end_of_the_page() {
let mut code = base_into_rbx(0x2000);
code.push(0xF4);
let bytes = Image::new(&code).build();
for base in [PREFERRED_BASE, OTHER_BASE] {
let result = run(&bytes, base);
let memory = &result.image.memory;
let mut page = [0u8; 0x1000];
memory.read_bytes(base, &mut page).unwrap();
let mut wanted = bytes[..0x400].to_vec();
wanted[OPTIONAL + 24..OPTIONAL + 32].copy_from_slice(&base.to_le_bytes());
assert_eq!(&page[..0x400], wanted.as_slice(), "{base:#x}");
assert!(page[0x400..].iter().all(|&byte| byte == 0), "{base:#x}");
// One page and no more: `.text` starts a page later.
assert_eq!(
memory.read_u8(base + 0x1000),
Err(MemoryError::UnmappedAddress(base + 0x1000)),
"{base:#x}"
);
}
}
#[test]
fn a_guest_write_to_the_headers_faults_and_changes_nothing() {
let mut code = base_into_rbx(0x2000);
code.extend([0xC6, 0x03, 0x00, 0xF4]); // mov byte [rbx], 0; hlt
let result = run(&Image::new(&code).build(), OTHER_BASE);
assert_eq!(
result.execution.exit_reason,
ExitReason::MemoryFault(MemoryError::PermissionViolation {
address: OTHER_BASE,
required: "write",
})
);
assert_eq!(result.image.memory.read_u8(OTHER_BASE), Ok(b'M'));
}
#[test]
fn the_headers_cannot_be_executed() {
let mut code = base_into_rbx(0x2000);
code.extend([0xFF, 0xE3]); // jmp rbx
let result = run(&Image::new(&code).build(), OTHER_BASE);
assert_eq!(
result.execution.exit_reason,
ExitReason::MemoryFault(MemoryError::PermissionViolation {
address: OTHER_BASE,
required: "execute",
})
);
assert_eq!(result.execution.final_state.rip, OTHER_BASE);
}
#[test]
fn headers_longer_than_a_page_take_whole_pages() {
// 0x1001 bytes of headers need two pages, so `.text` must start at 0x2000.
let mut image = Image::new(&[0xF4]);
image.size_of_headers = 0x1001;
image.text_offset = 0x1200;
let bytes = image.build();
let Ok(loaded) = ParsedPe::parse(&bytes).unwrap().load_into_memory(&bytes) else {
panic!("two pages of headers below a section at 0x2000 must load");
};
let memory = &loaded.memory;
assert_eq!(memory.read_u8(PREFERRED_BASE + 0x1000), Ok(bytes[0x1000]));
assert_eq!(memory.read_u8(PREFERRED_BASE + 0x1001), Ok(0));
assert_eq!(memory.read_u8(PREFERRED_BASE + 0x1FFF), Ok(0));
assert_eq!(memory.read_u8(PREFERRED_BASE + 0x2000), Ok(0xF4));
// With `.text` a page earlier the headers would reach into it.
image.text_rva = 0x1000;
assert_eq!(load_error(&image), Some(PeError::InvalidHeaderSize));
// Exactly one page of headers ends where that section starts.
image.size_of_headers = 0x1000;
assert_eq!(load_error(&image), None);
}
#[test]
fn a_header_size_that_cannot_be_mapped_is_refused() {
let mut image = Image::new(&[0xF4]);
image.size_of_headers = 0;
assert_eq!(load_error(&image), Some(PeError::InvalidHeaderSize));
// One byte short of the section table, then exactly the section table.
image.size_of_headers = TABLE_END - 1;
assert_eq!(load_error(&image), Some(PeError::InvalidHeaderSize));
image.size_of_headers = TABLE_END;
assert_eq!(load_error(&image), None);
// The file is 0x600 bytes: exactly that, then one byte more.
image.size_of_headers = 0x600;
assert_eq!(load_error(&image), None);
image.size_of_headers = 0x601;
assert_eq!(load_error(&image), Some(PeError::InvalidHeaderSize));
}
#[test]
fn an_empty_section_inside_the_header_page_is_not_an_overlap() {
// A section that maps nothing has no range to collide with.
let mut image = Image::new(&[0xF4]);
image.data_rva = 0x200;
image.data_size = 0;
assert_eq!(load_error(&image), None);
image.data_size = 1;
assert_eq!(load_error(&image), Some(PeError::InvalidHeaderSize));
}
#[test]
fn loading_with_bytes_shorter_than_the_headers_is_an_error_not_a_panic() {
let bytes = Image::new(&[0xF4]).build();
let pe = ParsedPe::parse(&bytes).unwrap();
for len in [0, 0x3F, OPTIONAL, TABLE_END as usize, 0x3FF] {
assert_eq!(
pe.load_into_memory(&bytes[..len]).err(),
Some(PeError::InvalidHeaderSize),
"{len:#x}"
);
}
// Other bytes of the right length, whose own headers leave no room for the
// `ImageBase` field inside the size that was parsed.
let mut image = Image::new(&[0xF4]);
image.size_of_headers = OPTIONAL as u32 + 8;
let bytes = image.build();
let pe = ParsedPe::parse(&bytes).unwrap();
let mut other = bytes.clone();
let coff = E_LFANEW as usize + 4;
other[coff + 2..coff + 4].copy_from_slice(&0u16.to_le_bytes());
other[coff + 16..coff + 18].copy_from_slice(&0u16.to_le_bytes());
assert_eq!(
pe.load_into_memory(&other).err(),
Some(PeError::InvalidHeaderSize)
);
}
#[test]
fn startup_reports_the_refusal() {
let mut image = Image::new(&[0xF4]);
image.size_of_headers = 0;
let layout = StartupLayout {
image_base: OTHER_BASE,
stack_top: 0x2_0001_0000,
tls_base: 0x3_0000_0000,
};
let error = run_synthetic_startup(&image.build(), layout, ImportRegistry::new(), 1_000)
.err()
.expect("refused");
assert_eq!(error.to_string(), PeError::InvalidHeaderSize.to_string());
assert_eq!(
error.to_string(),
"SizeOfHeaders is zero, shorter than the section table, longer than the file, or reaches \
into a section"
);
}
+8 -3
View File
@@ -4,11 +4,14 @@
//!
//! A section's mapped size is max(VirtualSize, SizeOfRawData) and the loader
//! backs it with zero-filled host memory, so a small file can request a large
//! allocation. The loader's documented budget is 256 MiB per image.
//! allocation. The loader's documented budget is 256 MiB per image, and the
//! page of headers mapped at the image base (#333) counts toward it.
use xenora_loader::{MemoryError, ParsedPe, PeError};
const BUDGET: u32 = 256 * 1024 * 1024;
/// The image's 0x200 bytes of headers are mapped as one 4 KiB page.
const HEADERS: u32 = 0x1000;
/// An original synthetic image: one 0x200-byte code section at RVA 0x1000 followed by
/// uninitialized sections (no raw data) of the given virtual sizes, packed back to back.
@@ -25,6 +28,8 @@ fn build(bss_sizes: &[u32]) -> Vec<u8> {
pe[opt..opt + 2].copy_from_slice(&0x020Bu16.to_le_bytes());
pe[opt + 16..opt + 20].copy_from_slice(&0x1000u32.to_le_bytes());
pe[opt + 24..opt + 32].copy_from_slice(&0x1_4000_0000u64.to_le_bytes());
// SizeOfHeaders: everything before the code's raw data.
pe[opt + 60..opt + 64].copy_from_slice(&0x200u32.to_le_bytes());
let mut section = |i: usize, va: u32, vsize: u32, raw: u32, flags: u32| {
let h = opt + 112 + i * 40;
@@ -56,14 +61,14 @@ fn small_image_loads() {
#[test]
fn image_exactly_at_budget_loads() {
let bytes = build(&[BUDGET - 0x200]);
let bytes = build(&[BUDGET - HEADERS - 0x200]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert!(pe.load_into_memory(&bytes).is_ok());
}
#[test]
fn one_byte_over_budget_is_rejected() {
let bytes = build(&[BUDGET - 0x1FF]);
let bytes = build(&[BUDGET - HEADERS - 0x1FF]);
let pe = ParsedPe::parse(&bytes).unwrap();
assert_eq!(pe.load_into_memory(&bytes).err(), Some(over_budget()));
}
+12
View File
@@ -69,6 +69,18 @@ storage, invokes its callbacks and runs the entry point. The fixture entry point
uses a Win64-aligned stack and terminates with HLT. The result includes the loaded
guest memory and the entry execution outcome.
Loading an image maps its headers as well as its sections. The first
`SizeOfHeaders` bytes of the file are mapped read-only at the image base, as
Windows maps them, in whole 4 KiB pages that are zero past the file bytes. In the
mapped copy the optional header's `ImageBase` field holds the base the image was
loaded at. A guest can read its own DOS header, section table and data
directories there; it cannot write or execute them. The load is refused with
`PeError::InvalidHeaderSize` when `SizeOfHeaders` is zero, ends before the
section table does, runs past the end of the file, or its pages would reach into
a section. The header pages count toward the 256 MiB mapping budget of one
image. `ParsedPe::parse` does not make this check, so static inspection of a
file is unchanged.
`xenora probe --mode static` inventories ordinary and delay-loaded PE imports
without guest execution. `missing_imports.csv` lists unresolved ordinary keys
with their import address table relative virtual addresses. The full inventory,