From 67dfb18166944256ac61cd6a44600ed86f57cccd Mon Sep 17 00:00:00 2001 From: zachdoxsee Date: Tue, 24 Nov 2026 19:47:11 +0100 Subject: [PATCH] loader: address review of the PE header mapping (#333) - Check the mapping budget before anything is mapped, and map the header bytes straight from the file instead of copying them first. - Refuse bytes that are not the PE32+ headers that were parsed: the optional header magic and size, the section count, the preferred base and SizeOfHeaders must agree before anything is patched. - Write the load base into the mapped ImageBase field after relocations are applied, so a DIR64 entry aimed at that field cannot move it twice. - Describe the ImageBase rewrite as Xenora's policy, and document the zero fill past SizeOfHeaders and the stricter page rule. Signed-off-by: zachdoxsee --- CHANGELOG.md | 2 +- crates/loader/src/pe.rs | 79 ++++++++++-------- crates/loader/src/startup.rs | 7 ++ crates/loader/tests/pe_headers.rs | 130 ++++++++++++++++++++++++++++-- docs/interfaces.md | 30 ++++--- 5 files changed, 197 insertions(+), 51 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index b6fee18..1c6148b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -17,7 +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. +- 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 that are zero past `SizeOfHeaders`. Programs read their own headers this way; the mingw-w64 C runtime does so before `main`, and until now that read faulted. When startup relocates an image it writes the load base into the mapped `ImageBase` field after the relocations, so an entry aimed at that field cannot move it twice; this is Xenora's policy and has not been compared with Windows. 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 when the bytes handed to the loader are not the PE32+ headers that were parsed. The page rule refuses images with sub-page section alignment whose first section starts inside the header page, which loaded before. The header pages count toward the 256 MiB mapping budget, which is checked before anything is mapped. `ParsedPe::parse` and the static probe are unchanged. `tests/pe_headers.rs` covers guest reads at the preferred and a relocated base, a relocation aimed at `ImageBase`, 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`. Awaiting independent re-review. - Added the VOP3A (`_e64`) encodings of eleven gfx1030 VOP2 integer forms (`v_mul_{i32_i24,hi_i32_i24,u32_u24,hi_u32_u24}`, `v_{min,max}_{i32,u32}`, `v_xnor_b32`, `v_sub_nc_u32`, `v_subrev_nc_u32`) and of the sixteen Wave32 integer compares (explicit SGPR mask destination, `s_cbranch_vccz` through `vcc_lo`, a translation error for reads of runtime-only SGPR results) as semantic-registry encoding variants, with VGPR sources only. New fixtures `vop3-integer` and `vop3-compare` with IR and MSL goldens, and an independent guide-derived oracle (`tests/validation/tests/vop3_{integer,compare}.rs`) that agrees on both reference interpreters and on native Metal. Part of #215. - Added guest texture binding through D3D12-style descriptor tables (#303): shader-visible CBV_SRV_UAV and sampler heaps, `CreateShaderResourceView` for one-level RGBA8 and BC1 2D textures, a point/clamp `CreateSampler`, a root signature with one pixel-stage SRV table and one sampler table, and `SetDescriptorHeaps`/`SetGraphicsRootDescriptorTable` in `crates/loader/src/graphics.rs`, plus `NativeCompute::render_rgba8_sampled_bc1`. Verified locally on an Apple M5 Pro under Metal validation: a guest draw with the translated `image_sample_lz` pixel stage matches the software reference and hand-derived images on 16 of 16 pixels for two RGBA8 textures and 64 of 64 for an 8×8 BC1 texture. A wrong descriptor slot changes the image, off-centre and out-of-range coordinates point-sample with clamping, and a rejected binding, draw shape or resource state never reaches the backend. The software reference samples BC1 with the spec-exact decoder, while Apple's hardware rounds BC1's interpolated palette entries differently (171/84 against 170/85), so the BC1 fixtures use only endpoint colours. Not yet reachable from guest imports. Not yet independently accepted. - 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. diff --git a/crates/loader/src/pe.rs b/crates/loader/src/pe.rs index cfabf6c..7311ec2 100644 --- a/crates/loader/src/pe.rs +++ b/crates/loader/src/pe.rs @@ -20,9 +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. + /// The headers cannot be mapped at the image base: `SizeOfHeaders` is + /// zero, ends before the section table does, runs past the end of the + /// file, or its pages reach into a section; or the bytes given to the + /// loader do not hold the PE32+ headers that were parsed. InvalidHeaderSize, } @@ -49,8 +50,9 @@ impl fmt::Display for PeError { 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" + "the PE headers cannot be mapped: SizeOfHeaders is zero, shorter than the section \ + table, longer than the file or reaches into a section, or the bytes do not match \ + the parsed headers" ), } } @@ -90,6 +92,9 @@ pub struct LoadedImage { pub pe: ParsedPe, pub memory: GuestMemory, pub entry_point: u64, + /// Guest address of the `ImageBase` field in the mapped optional header. + /// Startup writes the load base there once relocations have been applied. + pub(crate) image_base_field: u64, } // Windows PE Characteristic Constants @@ -109,8 +114,9 @@ const SECTION_HEADER_SIZE: usize = 40; 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. +/// `ImageBase` and `SizeOfHeaders` within the PE32+ optional header. const OPTIONAL_IMAGE_BASE: usize = 24; +const OPTIONAL_SIZE_OF_HEADERS: usize = 60; fn read_u16(bytes: &[u8], at: usize) -> u16 { u16::from_le_bytes([bytes[at], bytes[at + 1]]) @@ -284,37 +290,39 @@ impl ParsedPe { None } - /// 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. + /// Where the headers are and how much to map for them: the file length of + /// the headers, the page-rounded length of the mapping, and the file offset + /// of the optional header's `ImageBase` field. Nothing is copied or + /// allocated here. /// - /// 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, u64), PeError> { + /// A caller may pass bytes other than the ones parsed, so the header + /// layout is read again from `bytes` with every access checked, and must + /// be a PE32+ optional header that agrees with the parsed metadata. + fn headers_for(&self, bytes: &[u8]) -> Result<(usize, u64, usize), PeError> { let field = |at: usize, len: usize| at.checked_add(len).and_then(|end| bytes.get(at..end)); + let u16_at = |at: usize| Some(u16::from_le_bytes(field(at, 2)?.try_into().ok()?)); + let u32_at = |at: usize| Some(u32::from_le_bytes(field(at, 4)?.try_into().ok()?)); 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 coff = (u32_at(0x3C)? as usize).checked_add(4)?; + let sections = u16_at(coff.checked_add(2)?)?; + let optional_size = usize::from(u16_at(coff.checked_add(16)?)?); let optional = coff.checked_add(20)?; + let image_base = optional.checked_add(OPTIONAL_IMAGE_BASE)?; + let agrees = u16_at(optional)? == PE32_PLUS_MAGIC + && optional_size >= PE32_PLUS_MIN_OPTIONAL_HEADER + && sections == self.number_of_sections + && u64::from_le_bytes(field(image_base, 8)?.try_into().ok()?) == self.image_base + && u32_at(optional.checked_add(OPTIONAL_SIZE_OF_HEADERS)?)? == self.size_of_headers; let table_end = optional .checked_add(optional_size)? - .checked_add(sections.checked_mul(SECTION_HEADER_SIZE)?)?; - Some((optional, table_end)) + .checked_add(usize::from(sections).checked_mul(SECTION_HEADER_SIZE)?)?; + agrees.then_some((image_base, table_end)) }; - let (optional, table_end) = layout().ok_or(PeError::InvalidHeaderSize)?; - let image_base = optional - .checked_add(OPTIONAL_IMAGE_BASE) - .ok_or(PeError::InvalidHeaderSize)?; + let (image_base, table_end) = layout().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 { + if len < table_end || len > bytes.len() { return Err(PeError::InvalidHeaderSize); } let mapped = u64::from(self.size_of_headers).next_multiple_of(HEADER_PAGE); @@ -324,10 +332,7 @@ impl ParsedPe { 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)) + Ok((len, mapped, image_base)) } /// Load this parsed PE into a fresh `GuestMemory` instance, mapping the @@ -337,7 +342,7 @@ impl ParsedPe { } pub(crate) fn load_at_base(&self, bytes: &[u8], base: u64) -> Result { - let (headers, headers_mapped) = self.headers_for(bytes, base)?; + let (headers_len, headers_mapped, image_base_field) = self.headers_for(bytes)?; // The headers and each section become zero-filled host allocations, so bound // the total before allocating anything. Sections may not overlap, so the sum @@ -355,15 +360,20 @@ impl ParsedPe { 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`. + // them: a C runtime finds its own sections this way before `main`. The + // budget above is checked first, and the file bytes are the initial data + // of the mapping, so nothing else is copied. memory .map_region_with_data( base, headers_mapped as usize, MemoryPermissions::READ_ONLY, - &headers, + &bytes[..headers_len], ) .map_err(PeError::SectionMappingError)?; + let image_base_field = base + .checked_add(image_base_field as u64) + .ok_or(PeError::InvalidHeaderSize)?; for sec in &self.sections { let base_addr = base @@ -399,6 +409,7 @@ impl ParsedPe { pe: self.clone(), memory, entry_point, + image_base_field, }) } } diff --git a/crates/loader/src/startup.rs b/crates/loader/src/startup.rs index af40b2a..3afa920 100644 --- a/crates/loader/src/startup.rs +++ b/crates/loader/src/startup.rs @@ -95,6 +95,7 @@ pub fn run_synthetic_startup_with_observer( entry_rva: pe.entry_point_rva, }); let mut image = pe.load_at_base(bytes, layout.image_base)?; + let image_base_field = image.image_base_field; let memory = &mut image.memory; memory .fetch_instruction_byte(image.entry_point) @@ -104,6 +105,12 @@ pub fn run_synthetic_startup_with_observer( }); let relocations = apply_relocations(&pe, bytes, layout.image_base, memory)?; + // The mapped optional header names the base the image is loaded at. This + // is written after the relocations so that an entry aimed at the field + // itself cannot leave it holding anything else. + memory + .write_u64_bypass(image_base_field, layout.image_base) + .map_err(PeError::SectionMappingError)?; observe(StartupEvent::Relocated { applied_dir64: relocations.applied_dir64, }); diff --git a/crates/loader/tests/pe_headers.rs b/crates/loader/tests/pe_headers.rs index 10290d7..804d24f 100644 --- a/crates/loader/tests/pe_headers.rs +++ b/crates/loader/tests/pe_headers.rs @@ -32,6 +32,8 @@ struct Image { /// File offset of the code, and so the length of the file before it. text_offset: u32, code: Vec, + /// Base relocation blocks, placed in `.text` 0x100 bytes after the code. + relocations: Vec, } impl Image { @@ -43,6 +45,7 @@ impl Image { data_size: 0x100, text_offset: 0x400, code: code.to_vec(), + relocations: Vec::new(), } } @@ -55,10 +58,9 @@ impl Image { 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() - { + // The pattern stops after two pages so that a very large header stays cheap. + let padding_end = (self.text_offset as usize).min(0x2000); + for (i, byte) in pe[TABLE_END as usize..padding_end].iter_mut().enumerate() { *byte = (i * 5 + 1) as u8; } let pe_at = E_LFANEW as usize; @@ -100,6 +102,14 @@ impl Image { let at = self.text_offset as usize; pe[at..at + self.code.len()].copy_from_slice(&self.code); + if !self.relocations.is_empty() { + // Data directory 5 is the base relocation table. + let directory = OPTIONAL + 112 + 5 * 8; + pe[directory..directory + 4].copy_from_slice(&(self.text_rva + 0x100).to_le_bytes()); + pe[directory + 4..directory + 8] + .copy_from_slice(&(self.relocations.len() as u32).to_le_bytes()); + pe[at + 0x100..at + 0x100 + self.relocations.len()].copy_from_slice(&self.relocations); + } pe } } @@ -306,7 +316,115 @@ fn startup_reports_the_refusal() { 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" + "the PE headers cannot be mapped: SizeOfHeaders is zero, shorter than the section table, \ + longer than the file or reaches into a section, or the bytes do not match the parsed \ + headers" + ); +} + +/// One base relocation block: `IMAGE_REL_BASED_DIR64` entries for the given +/// offsets in the page at `page_rva`, padded to a multiple of four bytes. +fn dir64_block(page_rva: u32, offsets: &[u16]) -> Vec { + let mut entries: Vec = offsets.iter().map(|offset| 0xA000 | offset).collect(); + if entries.len() % 2 == 1 { + entries.push(0); // IMAGE_REL_BASED_ABSOLUTE padding + } + let mut block = page_rva.to_le_bytes().to_vec(); + block.extend((8 + 2 * entries.len() as u32).to_le_bytes()); + for entry in entries { + block.extend(entry.to_le_bytes()); + } + block +} + +#[test] +fn a_relocation_aimed_at_image_base_does_not_move_it_twice() { + // The image carries two DIR64 entries: one for the `ImageBase` field in the + // headers, and one for a pointer in `.text` so the table is seen to apply. + let mut code = base_into_rbx(0x2000); + code.extend([ + 0x8B, 0x4B, 0x3C, // mov ecx, [rbx + 0x3C] + 0x48, 0x8B, 0x7C, 0x0B, 0x30, // mov rdi, [rbx + rcx + 0x30] ImageBase + // mov rax, [rip + 0x2A]: the pointer at 0x2040 + 0x48, 0x8B, 0x05, 0x2A, 0x00, 0x00, 0x00, 0xF4, // hlt + ]); + // The load ends 0x16 bytes into the code, and 0x16 + 0x2A is 0x40. + assert_eq!(code.len(), 0x17); + code.resize(0x40, 0x90); + code.extend((PREFERRED_BASE + 0x2040).to_le_bytes()); + let mut image = Image::new(&code); + image.relocations = dir64_block(0, &[OPTIONAL as u16 + 24]); + image.relocations.extend(dir64_block(0x2000, &[0x40])); + let bytes = image.build(); + + for base in [PREFERRED_BASE, OTHER_BASE] { + let result = run(&bytes, base); + assert_eq!(result.execution.exit_reason, ExitReason::Halt, "{base:#x}"); + // Nothing is applied when the image is already at its preferred base. + let applied = if base == PREFERRED_BASE { 0 } else { 2 }; + assert_eq!(result.relocations.applied_dir64, applied, "{base:#x}"); + let cpu = &result.execution.final_state; + assert_eq!(cpu.get(Register::Rax), base + 0x2040, "{base:#x}"); + // Not the preferred base, and not the load base plus the delta again. + assert_eq!(cpu.get(Register::Rdi), base, "{base:#x}"); + } +} + +#[test] +fn bytes_that_are_not_the_parsed_headers_are_refused() { + let bytes = Image::new(&[0xF4]).build(); + let pe = ParsedPe::parse(&bytes).unwrap(); + let coff = E_LFANEW as usize + 4; + let refused = |change: &dyn Fn(&mut Vec)| { + let mut other = bytes.clone(); + change(&mut other); + pe.load_into_memory(&other).err() + }; + assert_eq!(refused(&|_| {}), None); + + // An optional header declared empty: the section table would start where + // the optional header is, and `ImageBase` would be patched inside it. + assert_eq!( + refused(&|b| b[coff + 16..coff + 18].copy_from_slice(&0u16.to_le_bytes())), + Some(PeError::InvalidHeaderSize) + ); + // One byte short of the PE32+ fields the loader relies on. + assert_eq!( + refused(&|b| b[coff + 16..coff + 18].copy_from_slice(&111u16.to_le_bytes())), + Some(PeError::InvalidHeaderSize) + ); + // Not a PE32+ optional header. + assert_eq!( + refused(&|b| b[OPTIONAL..OPTIONAL + 2].copy_from_slice(&0x010Bu16.to_le_bytes())), + Some(PeError::InvalidHeaderSize) + ); + // A different section count, preferred base or header size. + assert_eq!( + refused(&|b| b[coff + 2..coff + 4].copy_from_slice(&1u16.to_le_bytes())), + Some(PeError::InvalidHeaderSize) + ); + assert_eq!( + refused(&|b| b[OPTIONAL + 24] ^= 1), + Some(PeError::InvalidHeaderSize) + ); + assert_eq!( + refused(&|b| b[OPTIONAL + 60..OPTIONAL + 64].copy_from_slice(&0x200u32.to_le_bytes())), + Some(PeError::InvalidHeaderSize) + ); +} + +#[test] +fn headers_over_the_mapping_budget_are_refused() { + // 256 MiB of headers and one more page. The file really is that long, so + // only the budget stands between this image and a mapping of that size. + const BUDGET: u32 = 256 * 1024 * 1024; + let mut image = Image::new(&[0xF4]); + image.size_of_headers = BUDGET + 0x1000; + image.text_offset = BUDGET + 0x1000; + image.text_rva = BUDGET + 0x1000; + image.data_rva = BUDGET + 0x2000; + assert_eq!( + load_error(&image), + Some(PeError::SectionMappingError(MemoryError::AllocationFailed)) ); } diff --git a/docs/interfaces.md b/docs/interfaces.md index d59fbad..6314fe5 100644 --- a/docs/interfaces.md +++ b/docs/interfaces.md @@ -70,16 +70,26 @@ uses a Win64-aligned stack and terminates with HLT. The result includes the load 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. +`SizeOfHeaders` bytes of the file are mapped read-only at the image base, in +whole 4 KiB pages. Everything in those pages past `SizeOfHeaders` is zero, even +where the file holds more bytes there. A guest can read its own DOS header, +section table and data directories; it cannot write or execute them. + +When startup loads an image away from its preferred base, it writes the load +base into the mapped optional header's `ImageBase` field after the relocations +have been applied, so an entry aimed at that field cannot leave any other value +there. This is Xenora's policy: the PE specification defines `ImageBase` as the +preferred base, and the behaviour has not been compared with Windows. + +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, and when the bytes given to the loader are not +the PE32+ headers that were parsed. The page rule is stricter than the loader +was before: an image whose section alignment is below 4 KiB, with a section +that starts inside the header page, used to load and is now refused. The header +pages count toward the 256 MiB mapping budget of one image, which is checked +before anything is mapped. `ParsedPe::parse` does not make these checks, 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