Compare commits

..
Author SHA1 Message Date
zachdoxsee 496938aef4 Merge upstream main into task/333-pe-headers
Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-25 01:56:51 +01:00
Ranveer Soni 8c188b04c9 Merge pull request #377 from katherinebytes/codex/cpu-differential-corpus
Test 524 seeded x86-64 programs on the interpreter and native DBT
2026-11-25 06:24:35 +05:30
Ranveer Soni 9eb75522f0 Merge pull request #375 from Arths17/test/194-c7-immediate-store
test: add known answers for C6 and C7 immediate stores (#194)
2026-11-25 06:23:04 +05:30
Ranveer Soni 3f41f7406b Merge pull request #339 from jelly013/phase3b-runtime
runtime: add a deterministic guest thread scheduler (#323, part 1)
2026-11-25 06:22:00 +05:30
zachdoxsee 652c6ae02f Merge upstream main into the C6/C7 immediate-store tests branch
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 22:24:27 +01:00
zachdoxsee 0529c62226 Merge upstream main into task/333-pe-headers
Any conflict was in CHANGELOG.md, where every entry is kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 22:24:13 +01:00
katherinebytes bd46504a97 Add a seeded CPU differential corpus
Signed-off-by: katherinebytes <rebooteduck+kr@gmail.com>
2026-11-24 21:11:03 +00:00
zachdoxsee cc4dd092cf Merge upstream main into task/333-pe-headers
Any conflict was in CHANGELOG.md, where every entry is kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 22:01:29 +01:00
zachdoxsee fd0e73bc28 Merge upstream main into task/333-pe-headers
Conflict in CHANGELOG.md only: every entry is kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 21:43:49 +01:00
atharvranjan 6bac25f099 test: add known answers for C6 and C7 immediate stores (#194)
Covers byte to qword widths, SIB and displacement forms, imm32 sign extension, register forms and store faults. Both engines already agree.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-24 14:35:48 -06:00
zachdoxsee 685217e61b Merge upstream main into task/333-pe-headers
Conflict in CHANGELOG.md only: every entry is kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 20:21:39 +01:00
zachdoxsee 67dfb18166 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 <zachdoxsee36@gmail.com>
2026-11-24 19:47:11 +01:00
zachdoxsee d2491dee07 Merge upstream main into task/333-pe-headers
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 19:43:39 +01:00
zachdoxsee 6947fe7ff6 Merge upstream main into task/333-pe-headers
Conflict in CHANGELOG.md only: both new entries are kept.

Signed-off-by: zachdoxsee <zachdoxsee36@gmail.com>
2026-11-24 18:22:23 +01:00
zachdoxsee b8fbdf35b9 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>
2026-11-24 18:15:56 +01:00
8 changed files with 1354 additions and 11 deletions

No files matched your search

+2
View File
@@ -29,6 +29,8 @@ remains unsupported.
- Added a Python 3 fallback for `timeout` in `scripts/test-gpu.sh`, so the native Metal suite runs on stock macOS without GNU coreutils while preserving bounded execution and the usual timeout exit status.
### 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 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 35 known-answer cases for MOV with an immediate operand, opcodes C6 /0 and C7 /0 (#194), to `cpu_known_answers.rs`: byte, word, dword and qword stores through base, SIB, R12, R13, RSP and RBP addressing with 8-bit and 32-bit displacements; the imm32 sign extension of the 64-bit form; the register forms, including AH and a REX-selected SIL; unmapped and read-only store faults at each width; and #UD for reg field 1. Expected values come from the Intel SDM and were worked out by hand. The interpreter and the DBT already agreed with all of them, so this is new coverage and fixes no defect. The 16-bit forms covered are those that already run, and #118 stays open. Not compared with x86 hardware; awaiting independent review.
- `dbt_bench` can also write its results as one JSON document when `XENORA_DBT_BENCH_JSON=<path>` is set (#112). The document records the host CPU, OS and architecture, the git revision and whether the tree had local changes, debug assertions, the workload and sample counts, the median, minimum, maximum, p95, p99, IQR and MIPS for the interpreter and for cold and warm DBT, and the cold DBT counters. Anything the benchmark cannot determine is `null`. The text output and the timed work are unchanged.
- Added synthetic guest handle-lifetime regression tests (#205) for capacity reuse, stale handles, duplicate rights and lifetime, wrong object types, thread pseudo handles and failed-output nonmutation. Runtime behavior is unchanged; independent acceptance is pending.
- Added a documented independent acceptance rule for promoting AMD RDNA2 desktop GPU (gfx1030) forms from local CPU and Metal results to `fixture verified`, including clean-commit evidence, reviewer independence, raw-log location, review-log summary, failure handling and status regeneration (#302).
+95 -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,11 @@ pub enum PeError {
InvalidSectionHeaders,
SectionMappingError(MemoryError),
InvalidEntryPoint,
/// 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,
}
impl fmt::Display for PeError {
@@ -42,6 +48,12 @@ 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,
"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"
),
}
}
}
@@ -80,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
@@ -94,9 +109,14 @@ 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` 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]])
@@ -270,25 +290,91 @@ impl ParsedPe {
None
}
/// Load this parsed PE into a fresh `GuestMemory` instance, mapping all sections.
/// 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.
///
/// 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 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(usize::from(sections).checked_mul(SECTION_HEADER_SIZE)?)?;
agrees.then_some((image_base, table_end))
};
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() {
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);
}
Ok((len, mapped, image_base))
}
/// 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_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
// 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`. 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,
&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
.checked_add(u64::from(sec.virtual_address))
@@ -323,6 +409,7 @@ impl ParsedPe {
pe: self.clone(),
memory,
entry_point,
image_base_field,
})
}
}
+7
View File
@@ -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,
});
+644
View File
@@ -0,0 +1,644 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Seeded sequences of original x86-64 instructions for issue #74.
//!
//! Expected states follow the Intel SDM (Vol. 1, §§3.4.1 and 3.4.3,
//! Vol. 2, ADD, SUB, CMP, XOR, MOV, Jcc, CALL, RET, DEC, MOVDQU, PADDB,
//! PSUBW and PXOR, and Vol. 3A, §7.15, Page-Fault Exception). The oracles work from arithmetic operands, branch
//! predicates, array indices and vector lanes. They never decode the emitted
//! bytes or use Xenora's instruction or flag helpers.
//!
//! <https://www.intel.com/content/www/us/en/developer/articles/technical/intel-sdm.html>
//!
//! The x86 bytes run as guest code through a synthetic memory map and end at
//! Xenora's HLT sentinel. To replay a failure, use the printed test name and
//! XENORA_CPU_DIFFERENTIAL_CASE index. For example:
//!
//! ```sh
//! XENORA_CPU_DIFFERENTIAL_CASE=0 cargo test --locked -p xenora-loader \
//! --test cpu_differential seeded_register_sequences -- --exact
//! ```
//!
//! The seed and bytes are printed for reproducing the program outside this
//! harness as well.
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, RFlags, Register};
use xenora_loader::dbt::DbtEngine;
use xenora_loader::memory::{GuestMemory, MemoryError, MemoryPermissions};
const CODE: u64 = 0x40_0000;
const DATA: u64 = 0x50_0000;
const DATA_LEN: usize = 192;
const STACK_TOP: u64 = DATA + DATA_LEN as u64;
const BUDGET: usize = 128;
const TEST_SEED: u64 = 0x74_da7a_c0de_ba5e;
// SplitMix64 with a fresh stream per case. Changing the corpus order does not
// affect replay of an existing index.
struct Random(u64);
impl Random {
fn next(&mut self) -> u64 {
self.0 = self.0.wrapping_add(0x9e37_79b9_7f4a_7c15);
let mut word = self.0;
word = (word ^ (word >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
word = (word ^ (word >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
word ^ (word >> 31)
}
fn below(&mut self, end: usize) -> usize {
(self.next() % end as u64) as usize
}
}
#[derive(Clone)]
struct State {
cpu: CpuState,
data: [u8; DATA_LEN],
af_defined: bool,
}
impl State {
fn seeded(random: &mut Random) -> Self {
let mut cpu = CpuState::new(CODE, STACK_TOP);
cpu.gpr = std::array::from_fn(|_| random.next());
cpu.set(Register::Rsp, STACK_TOP);
cpu.xmm =
std::array::from_fn(|_| (u128::from(random.next()) << 64) | u128::from(random.next()));
let flags = random.next();
cpu.flags = RFlags {
cf: flags & 1 != 0,
pf: flags & 2 != 0,
af: flags & 4 != 0,
zf: flags & 8 != 0,
sf: flags & 16 != 0,
of: flags & 32 != 0,
};
cpu.df = flags & 64 != 0;
cpu.fs_base = DATA;
cpu.gs_base = DATA + 64;
Self {
cpu,
data: std::array::from_fn(|_| random.next() as u8),
af_defined: true,
}
}
fn checkpoint(&mut self, trace: &mut Vec<Self>, offset: usize) {
self.cpu.rip = CODE + offset as u64;
trace.push(self.clone());
}
fn word(&self, offset: usize) -> u64 {
u64::from_le_bytes(self.data[offset..offset + 8].try_into().unwrap())
}
fn put_word(&mut self, offset: usize, value: u64) {
self.data[offset..offset + 8].copy_from_slice(&value.to_le_bytes());
}
}
struct Case {
code: Vec<u8>,
initial: State,
// State after each attempted instruction, including the terminal instruction.
trace: Vec<State>,
native_only: bool,
exit: ExitReason,
}
impl Case {
fn memory(&self) -> GuestMemory {
let mut memory = GuestMemory::new();
memory
.map_region_with_data(
CODE,
self.code.len(),
MemoryPermissions::READ_EXECUTE,
&self.code,
)
.unwrap();
memory
.map_region_with_data(
DATA,
DATA_LEN,
MemoryPermissions::READ_WRITE,
&self.initial.data,
)
.unwrap();
memory
}
fn verify(&self, id: &str) {
let steps = self.trace.len();
assert!(steps < BUDGET);
let compare = |engine: &str,
result: ExecutionResult,
memory: &GuestMemory,
budget: usize,
offset: usize| {
let steps = (steps - offset).min(budget);
let expected = &self.trace[offset + steps - 1];
let label = || {
let start_rip = if offset == 0 {
self.initial.cpu.rip
} else {
self.trace[offset - 1].cpu.rip
};
format!(
"{id} {engine} from {start_rip:#x}, after {} guest steps, bytes {:02x?}",
offset + steps,
self.code
)
};
let finished = offset + steps == self.trace.len();
let exit = if finished {
self.exit
} else {
ExitReason::StepLimitExceeded
};
let retired = steps - usize::from(finished && self.exit != ExitReason::Halt);
assert_eq!(result.exit_reason, exit, "{}", label());
assert_eq!(result.instructions_executed, retired, "{}", label());
let mut actual = result.final_state;
if !expected.af_defined {
actual.flags.af = expected.cpu.flags.af;
}
assert_eq!(actual, expected.cpu, "{}", label());
let mut data = [0; DATA_LEN];
memory.read_bytes(DATA, &mut data).unwrap();
if let Some(index) = data.iter().zip(expected.data).position(|(&a, b)| a != b) {
panic!(
"{}: guest byte at {:#x}: got {:#04x}, expected {:#04x}",
label(),
DATA + index as u64,
data[index],
expected.data[index]
);
}
};
let mut stepped = DbtEngine::new(128 * 1024).unwrap();
let mut interpreted_memory = self.memory();
let mut translated_memory = self.memory();
let mut interpreted_cpu = self.initial.cpu.clone();
let mut translated_cpu = self.initial.cpu.clone();
// Check the first divergent retired instruction before testing full
// blocks. Each engine continues from its own state at every step.
for offset in 0..steps {
let result = Interpreter::new(interpreted_cpu, &mut interpreted_memory, 1).run();
interpreted_cpu = result.final_state.clone();
compare(
"interpreter (1 step)",
result,
&interpreted_memory,
1,
offset,
);
let result = stepped.run(&mut translated_cpu, &mut translated_memory, 1);
compare("DBT (1 step)", result, &translated_memory, 1, offset);
}
// Exercise native block lowering and then reuse those blocks with a
// fresh copy of the guest input and memory at the same addresses.
let mut dbt = DbtEngine::new(128 * 1024).unwrap();
let mut memory = self.memory();
let result = Interpreter::new(self.initial.cpu.clone(), &mut memory, BUDGET).run();
compare("interpreter", result, &memory, BUDGET, 0);
let mut run_full = |engine| {
let mut memory = self.memory();
let result = dbt.run(&mut self.initial.cpu.clone(), &mut memory, BUDGET);
compare(engine, result, &memory, BUDGET, 0);
dbt.metrics
};
let cold = run_full("DBT (cold)");
let cached = run_full("DBT (cached)");
assert!(cold.blocks_compiled > 0, "{id}");
assert_eq!(cold.blocks_compiled, cached.blocks_compiled, "{id}");
assert!(cached.cache_hits > cold.cache_hits, "{id}");
assert!(cached.dbt_dispatches > cold.dbt_dispatches, "{id}");
// These budgets cut the longer programs around a 16-instruction
// native block boundary, including a resume from the truncated block.
for budget in [15, 16, 17].into_iter().filter(|&budget| budget < steps) {
let mut memory = self.memory();
let mut cpu = self.initial.cpu.clone();
let result = dbt.run(&mut cpu, &mut memory, budget);
compare("DBT (limited)", result, &memory, budget, 0);
let result = dbt.run(&mut cpu, &mut memory, BUDGET);
compare("DBT (resumed)", result, &memory, BUDGET, budget);
}
if self.native_only {
assert_eq!(dbt.metrics.interpreter_fallbacks, 0, "{id}");
assert_eq!(stepped.metrics.interpreter_fallbacks, 0, "{id}");
}
}
}
#[derive(Clone, Copy, Debug)]
enum Alu {
Add,
Sub,
Compare,
Xor,
Move,
}
impl Alu {
const OPS: [Self; 5] = [Self::Add, Self::Sub, Self::Compare, Self::Xor, Self::Move];
// SDM Vol. 2, §2.1 and the r/m,reg forms for each instruction. A bare
// REX prefix selects SPL/BPL/SIL/DIL instead of the high byte registers.
fn encode(self, code: &mut Vec<u8>, bits: u32, dst: usize, src: usize) {
if bits == 16 {
code.push(0x66);
}
let rex = 0x40 | (u8::from(bits == 64) << 3) | ((src as u8 >> 3) << 2) | (dst as u8 >> 3);
if rex != 0x40 || (bits == 8 && (src >= 4 || dst >= 4)) {
code.push(rex);
}
let byte_opcode = match self {
Self::Add => 0x00,
Self::Sub => 0x28,
Self::Compare => 0x38,
Self::Xor => 0x30,
Self::Move => 0x88,
};
code.extend([
byte_opcode | u8::from(bits != 8),
0xc0 | ((src as u8 & 7) << 3) | (dst as u8 & 7),
]);
}
fn expect(self, state: &mut State, bits: u32, dst: usize, src: usize) {
let mask = u64::MAX >> (64 - bits);
let left = state.cpu.gpr[dst] & mask;
let right = state.cpu.gpr[src] & mask;
let result = match self {
Self::Move => right,
Self::Xor => {
let result = left ^ right;
state.cpu.flags = result_flags(result, bits);
state.af_defined = false;
result
}
Self::Add | Self::Compare | Self::Sub => {
let (result, flags) = arithmetic(left, right, bits, matches!(self, Self::Add));
state.cpu.flags = flags;
state.af_defined = true;
result
}
};
if !matches!(self, Self::Compare) {
state.cpu.gpr[dst] = if bits >= 32 {
result
} else {
(state.cpu.gpr[dst] & !mask) | result
};
}
}
}
fn result_flags(result: u64, bits: u32) -> RFlags {
RFlags {
zf: result == 0,
sf: result >> (bits - 1) == 1,
pf: (result as u8).count_ones().is_multiple_of(2),
..RFlags::default()
}
}
// Carry, auxiliary carry and signed overflow are derived by separate
// widened calculations. The exact signed result determines overflow.
fn arithmetic(left: u64, right: u64, bits: u32, add: bool) -> (u64, RFlags) {
let modulus = 1i128 << bits;
let signed = |word: u64| {
let word = i128::from(word);
if word >= modulus / 2 {
word - modulus
} else {
word
}
};
let operation = |a: i128, b: i128| if add { a + b } else { a - b };
let wide = operation(i128::from(left), i128::from(right));
let result = wide.rem_euclid(modulus) as u64;
let mut flags = result_flags(result, bits);
flags.cf = !(0..modulus).contains(&wide);
let nibble = operation(i128::from(left & 15), i128::from(right & 15));
flags.af = !(0..16).contains(&nibble);
let signed_result = operation(signed(left), signed(right));
flags.of = !(-modulus / 2..modulus / 2).contains(&signed_result);
(result, flags)
}
fn seeded_cases(
test: &str,
family: u64,
count: usize,
make_case: impl Fn(usize, &mut Random) -> Case,
) {
let selected = std::env::var("XENORA_CPU_DIFFERENTIAL_CASE")
.ok()
.map(|text| {
let index = text
.parse::<usize>()
.expect("XENORA_CPU_DIFFERENTIAL_CASE must be a decimal case index");
assert!(index < count, "{test} has case indices 0..{count}");
index
});
for index in selected.map_or(0..count, |index| index..index + 1) {
let seed = TEST_SEED ^ (family << 48) ^ index as u64;
let case = make_case(index, &mut Random(seed));
case.verify(&format!(
"{test}: XENORA_CPU_DIFFERENTIAL_CASE={index} (seed {seed:#018x})"
));
}
}
#[test]
fn seeded_register_sequences() {
const WIDTHS: [u32; 4] = [8, 16, 32, 64];
seeded_cases("seeded_register_sequences", 1, 240, |index, random| {
let mixed_widths = index >= 160;
let bits = WIDTHS[index % 4];
let edges = [
0,
1,
15,
16,
(1u64 << (bits - 1)) - 1,
1 << (bits - 1),
u64::MAX,
];
let mut initial = State::seeded(random);
// Keep random high bits when the operand is narrower than the GPR.
let mask = u64::MAX >> (64 - bits);
for reg in [0, 1, 2, 3, 8, 9, 10, 11] {
let edge = edges[random.below(edges.len())];
initial.cpu.gpr[reg] = (initial.cpu.gpr[reg] & !mask) | (edge & mask);
}
let mut state = initial.clone();
let mut code = Vec::new();
let mut trace = Vec::new();
for step in 0..24 {
let bits = if mixed_widths {
WIDTHS[(index + step) % WIDTHS.len()]
} else {
bits
};
let op = Alu::OPS[random.below(Alu::OPS.len())];
let dst = random.below(16);
let src = random.below(16);
op.encode(&mut code, bits, dst, src);
op.expect(&mut state, bits, dst, src);
state.checkpoint(&mut trace, code.len());
}
code.push(0xf4);
state.checkpoint(&mut trace, code.len());
Case {
code,
initial,
trace,
native_only: !mixed_widths && bits >= 32,
exit: ExitReason::Halt,
}
});
}
fn branch_predicate(condition: usize, flags: RFlags) -> bool {
let base = [
flags.of,
flags.cf,
flags.zf,
flags.cf || flags.zf,
flags.sf,
flags.pf,
flags.sf != flags.of,
flags.zf || flags.sf != flags.of,
][condition / 2];
base ^ !condition.is_multiple_of(2)
}
#[test]
fn seeded_compare_branch_pairs() {
seeded_cases("seeded_compare_branch_pairs", 2, 128, |index, random| {
let condition = index % 16;
let taken = index / 16 % 2 != 0;
let bits = [32, 64][index / 32 % 2];
let near = index >= 64;
let sign = 1u64 << (bits - 1);
let boundary = [0, 1, 2, sign - 1, sign, sign | 1, (sign - 1) | sign];
let pairs = boundary
.into_iter()
.flat_map(|left| boundary.map(|right| (left, right)));
let eligible: Vec<_> = pairs
.filter(|&(left, right)| {
branch_predicate(condition, arithmetic(left, right, bits, false).1) == taken
})
.collect();
let (left, right) = eligible[random.below(eligible.len())];
let mut initial = State::seeded(random);
let mask = u64::MAX >> (64 - bits);
initial.cpu.gpr[0] = (initial.cpu.gpr[0] & !mask) | left;
initial.cpu.gpr[8] = (initial.cpu.gpr[8] & !mask) | right;
let mut state = initial.clone();
let mut code = Vec::new();
let mut trace = Vec::new();
Alu::Compare.encode(&mut code, bits, 0, 8);
Alu::Compare.expect(&mut state, bits, 0, 8);
let branch = code.len();
state.checkpoint(&mut trace, branch);
if near {
code.extend([0x0f, 0x80 + condition as u8, 3, 0, 0, 0]);
} else {
code.extend([0x70 + condition as u8, 3]);
}
// The two arms set distinct low bytes of RDX, then stop.
let fallthrough = code.len();
code.extend([0xb2, 0x31, 0xf4, 0xb2, 0x73, 0xf4]);
let arm = fallthrough + if taken { 3 } else { 0 };
state.checkpoint(&mut trace, arm);
state.cpu.gpr[2] = (state.cpu.gpr[2] & !255) | if taken { 0x73 } else { 0x31 };
state.checkpoint(&mut trace, arm + 2);
state.checkpoint(&mut trace, arm + 3);
Case {
code,
initial,
trace,
native_only: true,
exit: ExitReason::Halt,
}
});
}
#[test]
fn seeded_memory_loop_with_calls() {
seeded_cases("seeded_memory_loop_with_calls", 3, 64, |_, random| {
let count = random.below(8) + 1;
let input = random.below(8);
let output = 80 + random.below(8);
let mut initial = State::seeded(random);
initial.cpu.set(Register::Rcx, count as u64);
initial.cpu.set(Register::Rsi, DATA + input as u64);
initial.cpu.set(Register::Rdi, DATA + output as u64);
let code = vec![
0xe8, 10, 0, 0, 0, // 0: call sum
0x48, 0x89, 0x44, 0xcf, 0xf8, // 5: mov [rdi + rcx*8 - 8], rax
0xff, 0xc9, // 10: dec ecx
0x75, 0xf2, // 12: jnz start
0xf4, // 14: hlt
0x48, 0x03, 0x44, 0xce, 0xf8, // 15: sum: add rax, [rsi + rcx*8 - 8]
0xc3, // 20: ret
];
let mut state = initial.clone();
let mut trace = Vec::new();
let mut sum = state.cpu.get(Register::Rax);
for remaining in (1..=count).rev() {
state.put_word(DATA_LEN - 8, CODE + 5);
state.cpu.set(Register::Rsp, STACK_TOP - 8);
state.checkpoint(&mut trace, 15);
let index = (remaining - 1) * 8;
let (next, flags) = arithmetic(sum, initial.word(input + index), 64, true);
sum = next;
state.cpu.set(Register::Rax, sum);
state.cpu.flags = flags;
state.checkpoint(&mut trace, 20);
state.cpu.set(Register::Rsp, STACK_TOP);
state.checkpoint(&mut trace, 5);
state.put_word(output + index, sum);
state.checkpoint(&mut trace, 10);
let (counter, mut flags) = arithmetic(remaining as u64, 1, 32, false);
flags.cf = state.cpu.flags.cf; // DEC leaves carry intact.
state.cpu.set(Register::Rcx, counter);
state.cpu.flags = flags;
state.checkpoint(&mut trace, 12);
state.checkpoint(&mut trace, if counter == 0 { 14 } else { 0 });
}
state.checkpoint(&mut trace, 15);
Case {
code,
initial,
trace,
native_only: true,
exit: ExitReason::Halt,
}
});
}
#[test]
fn seeded_vector_load_arithmetic_store() {
seeded_cases("seeded_vector_load_arithmetic_store", 4, 64, |_, random| {
let mut initial = State::seeded(random);
let input = random.below(16);
let output = 64 + random.below(16);
initial.cpu.set(Register::Rsi, DATA + input as u64);
initial.cpu.set(Register::Rdi, DATA + output as u64);
let code = vec![
0xf3, 0x44, 0x0f, 0x6f, 0x0e, // 0: movdqu xmm9, [rsi]
0x66, 0x44, 0x0f, 0xfc, 0xca, // 5: paddb xmm9, xmm2
0x66, 0x45, 0x0f, 0xf9, 0xcf, // 10: psubw xmm9, xmm15
0x66, 0x44, 0x0f, 0xef, 0xc8, // 15: pxor xmm9, xmm0
0xf3, 0x44, 0x0f, 0x7f, 0x0f, // 20: movdqu [rdi], xmm9
0xf4,
];
let mut state = initial.clone();
let mut trace = Vec::new();
let mut lanes: [u8; 16] = initial.data[input..input + 16].try_into().unwrap();
state.cpu.xmm[9] = u128::from_le_bytes(lanes);
state.checkpoint(&mut trace, 5);
for (lane, addend) in lanes.iter_mut().zip(initial.cpu.xmm[2].to_le_bytes()) {
*lane = lane.wrapping_add(addend);
}
state.cpu.xmm[9] = u128::from_le_bytes(lanes);
state.checkpoint(&mut trace, 10);
let subtrahend = initial.cpu.xmm[15].to_le_bytes();
let (words, _) = lanes.as_chunks_mut::<2>();
let (subtrahends, _) = subtrahend.as_chunks::<2>();
for (word, &rhs) in words.iter_mut().zip(subtrahends) {
let left = u16::from_le_bytes(*word);
let right = u16::from_le_bytes(rhs);
*word = left.wrapping_sub(right).to_le_bytes();
}
state.cpu.xmm[9] = u128::from_le_bytes(lanes);
state.checkpoint(&mut trace, 15);
state.cpu.xmm[9] ^= initial.cpu.xmm[0];
state.checkpoint(&mut trace, 20);
state.data[output..output + 16].copy_from_slice(&state.cpu.xmm[9].to_le_bytes());
state.checkpoint(&mut trace, 25);
state.checkpoint(&mut trace, 26);
Case {
code,
initial,
trace,
native_only: true,
exit: ExitReason::Halt,
}
});
}
#[test]
fn seeded_precise_memory_faults() {
seeded_cases("seeded_precise_memory_faults", 5, 28, |index, random| {
// Both branch outcomes and both operand directions at each of the
// seven possible byte splits of an eight-byte operand.
let store = index.is_multiple_of(2);
let taken = (index / 2).is_multiple_of(2);
let split = index / 4 + 1;
let mut initial = State::seeded(random);
let output = random.below(32);
let value = initial.cpu.get(Register::Rax);
let rhs = if taken { value } else { value ^ (1 << 63) };
initial.cpu.set(Register::R8, rhs);
initial.cpu.set(Register::Rdi, DATA + output as u64);
initial.cpu.set(Register::Rsi, STACK_TOP - split as u64);
let code = vec![
0x48,
0x89,
0x07, // 0: mov [rdi], rax
0x4c,
0x39,
0xc0, // 3: cmp rax, r8
0x74,
0x03, // 6: je faulting_move
0x4d,
0x89,
0xd1, // 8: mov r9, r10
0x48,
if store { 0x89 } else { 0x8b },
0x06, // 11: mov [rsi], rax or mov rax, [rsi]
0xf4,
];
let mut state = initial.clone();
let mut trace = Vec::new();
state.put_word(output, value);
state.checkpoint(&mut trace, 3);
state.cpu.flags = arithmetic(value, rhs, 64, false).1;
state.checkpoint(&mut trace, 6);
if taken {
state.checkpoint(&mut trace, 11);
} else {
state.checkpoint(&mut trace, 8);
state.cpu.set(Register::R9, initial.cpu.get(Register::R10));
state.checkpoint(&mut trace, 11);
}
// The faulting instruction leaves RIP, registers and all mapped bytes
// intact. The preceding store and optional register move stay retired.
state.checkpoint(&mut trace, 11);
Case {
code,
initial,
trace,
native_only: true,
exit: ExitReason::MemoryFault(MemoryError::UnmappedAddress(STACK_TOP)),
}
});
}
+146
View File
@@ -1294,6 +1294,147 @@ gs_xadd_without_lock: rbx=8 rcx=5 gs8=03000000 => rcx=3 gs8=08000000 f=cpazso
fs_rep_movsb_overrides_source_only_df_clear: rsi=8 rdi=D rcx=2 fs8=a1a2 m0=0000 => rsi=a rdi=D+2 rcx=0 m0=a1a2 f=*
";
/// MOV r/m, imm (opcodes C6 /0 and C7 /0), issue #194.
///
/// Memory-form encodings came from Apple clang's assembler. The register forms
/// of C6/C7 are the long alternatives to B0+r and B8+r, which that assembler
/// never emits, so they were written by hand from the opcode map (ModRM
/// `11 000 rm`). Expected values follow SDM 2B MOV, where the imm32 of the
/// 64-bit form is sign-extended, and were computed by hand before the first run,
/// without reading how the interpreter or the DBT execute C6 and C7. The author is
/// an AI model, as for the rest of this file. Both engines already agreed with
/// every case, so this group closes a coverage gap and fixes no defect.
const IMMEDIATE_STORES: &str = r"
@ mov byte ptr [rdi], 0x80
c60780
SDM 2B MOV (C6 /0)
store_byte_base: rdi=D m0=aaaaaaaa => m0=80aaaaaa f=*
@ mov word ptr [rdi], 0x8001
66c7070180
SDM 2B MOV (C7 /0, 66 prefix)
store_word_base: rdi=D m0=aaaaaaaa => m0=0180aaaa f=*
@ mov dword ptr [rdi], 0x80000001
c70701000080
SDM 2B MOV (C7 /0)
store_dword_base_is_not_sign_extended: rdi=D m0=aaaaaaaaaaaaaaaa => m0=01000080aaaaaaaa f=*
@ mov qword ptr [rdi], -0x7fffffff
48c70701000080
SDM 2B MOV (REX.W C7 /0, imm32 sign-extended to 64 bits)
store_qword_negative_immediate_sign_extends: rdi=D m0=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa => m0=01000080ffffffffaaaaaaaaaaaaaaaa f=*
@ mov qword ptr [rdi], 1
48c70701000000
SDM 2B MOV (REX.W C7 /0)
store_qword_positive_immediate_clears_upper_half: rdi=D m0=ffffffffffffffffaaaaaaaaaaaaaaaa => m0=0100000000000000aaaaaaaaaaaaaaaa f=*
@ mov qword ptr [rdi+rcx*8+0x10], -2
48c744cf10feffffff
SDM 2B MOV; 2A 2.1.5 (SIB, disp8)
store_qword_sib_scale_8_disp8: rdi=D rcx=2 m20=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa => m20=feffffffffffffffaaaaaaaaaaaaaaaa f=*
@ mov dword ptr [rdi+0x7f], 0x11223344
c7477f44332211
SDM 2B MOV; 2A 2.1.5 (disp8, largest positive)
store_dword_disp8_positive_limit: rdi=D m7e=aaaaaaaaaaaaaaaaaaaa => m7e=aa44332211aaaaaaaaaa f=*
@ mov dword ptr [rdi-0x80], 0x11223344
c7478044332211
SDM 2B MOV; 2A 2.1.5 (disp8 is sign-extended)
store_dword_disp8_negative_limit: rdi=D+80 m0=aaaaaaaaaaaaaaaa => m0=44332211aaaaaaaa f=*
@ mov dword ptr [rdi+0x100], 0x11223344
c7870001000044332211
SDM 2B MOV; 2A 2.1.5 (disp32)
store_dword_disp32: rdi=D m100=aaaaaaaaaaaaaaaa => m100=44332211aaaaaaaa f=*
@ mov byte ptr [r9+r10*2+1], 7
43c644510107
SDM 2B MOV; 2A 2.1.5 (REX.X and REX.B)
store_byte_rex_base_and_index: r9=D+10 r10=8 m20=aaaaaaaa => m20=aa07aaaa f=*
@ mov qword ptr [r12], 5
49c7042405000000
SDM 2B MOV; 2A 2.1.5 (R12 needs a SIB byte)
store_qword_r12_base: r12=D+30 m30=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa => m30=0500000000000000aaaaaaaaaaaaaaaa f=*
@ mov qword ptr [r13], 5
49c7450005000000
SDM 2B MOV; 2A 2.1.5 (R13 with mod 00 would be RIP-relative, so disp8 0)
store_qword_r13_base: r13=D+40 m40=aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa => m40=0500000000000000aaaaaaaaaaaaaaaa f=*
@ mov word ptr [rsp+8], 0x1234
66c74424083412
SDM 2B MOV; 2A 2.1.5 (RSP needs a SIB byte)
store_word_rsp_base: rsp=D+58 m60=aaaaaaaa => m60=3412aaaa f=*
@ mov byte ptr [rbp+2], 0x7f
c645027f
SDM 2B MOV
store_byte_rbp_disp8: rbp=D+70 m72=aaaa => m72=7faa f=*
@ mov byte ptr [rdi+rcx], -1
c6040fff
SDM 2B MOV
store_byte_base_plus_index: rdi=D+80 rcx=5 m84=aaaaaaaa => m84=aaffaaaa f=*
@ mov word ptr [r8+r9*4+0x20], 0x7ffe
6643c7448820fe7f
SDM 2B MOV; 2A 2.1.5
store_word_r8_r9_scaled: r8=D r9=10 m60=aaaaaaaa => m60=fe7faaaa f=*
@ mov eax, 0x80000001
c7c001000080
SDM 2B MOV (C7 /0, register form); 1 3.4.1.1
register_dword_zero_extends: rax=ffffffffffffffff => rax=0000000080000001 f=*
@ mov ax, 0x8001
66c7c00180
SDM 2B MOV; 1 3.4.1.1
register_word_keeps_upper_bits: rax=1122334455667788 => rax=1122334455668001 f=*
@ mov rax, -2
48c7c0feffffff
SDM 2B MOV (REX.W C7 /0, register form)
register_qword_sign_extends: rax=0 => rax=fffffffffffffffe f=*
@ mov r10, 0x7fffffff
49c7c2ffffff7f
SDM 2B MOV
register_qword_rex_b_positive: r10=ffffffffffffffff => r10=000000007fffffff f=*
@ mov r8d, -1
41c7c0ffffffff
SDM 2B MOV; 1 3.4.1.1
register_dword_rex_b_zero_extends: r8=1122334455667788 => r8=00000000ffffffff f=*
@ mov al, 0x80
c6c080
SDM 2B MOV (C6 /0, register form)
register_byte_al: rax=1122334455667788 => rax=1122334455667780 f=*
@ mov ah, 5
c6c405
SDM 2B MOV; 1 3.4.1.1 (no REX: ModRM 4 is AH)
register_byte_ah: rax=1122334455667788 => rax=1122334455660588 f=*
@ mov sil, 3
40c6c603
SDM 2B MOV; 1 3.4.1.1 (a REX prefix makes ModRM 6 SIL)
register_byte_sil: rsi=1122334455667788 => rsi=1122334455667703 f=*
@ mov r9b, 4
41c6c104
SDM 2B MOV
register_byte_r9b: r9=1122334455667788 => r9=1122334455667704 f=*
@ mov byte ptr [rdi], 0x80
!c60780
SDM 3A 7.15 Interrupt 14
store_byte_unmapped: rdi=U => ! PFW U
store_byte_readonly: rdi=R+8 => ! PFW R+8
@ mov word ptr [rdi], 0x8001
!66c7070180
SDM 3A 7.15 Interrupt 14
store_word_unmapped: rdi=U => ! PFW U
store_word_readonly: rdi=R+8 => ! PFW R+8
@ mov dword ptr [rdi], 0x80000001
!c70701000080
SDM 3A 7.15 Interrupt 14
store_dword_unmapped: rdi=U => ! PFW U
store_dword_readonly: rdi=R+8 => ! PFW R+8
@ mov qword ptr [rdi], -0x7fffffff
!48c70701000080
SDM 3A 7.15 Interrupt 14
store_qword_unmapped: rdi=U => ! PFW U
store_qword_readonly: rdi=R+8 => ! PFW R+8
@ C6 with ModRM reg field 1 (no such instruction)
!c60f01
SDM 2B MOV (C6 is defined only as /0); 3A 7.15 Interrupt 6
c6_reg_field_1_is_ud: rdi=D m0=aaaaaaaa => ! UD
@ C7 with ModRM reg field 1 (no such instruction)
!c70f01000000
SDM 2B MOV (C7 is defined only as /0); 3A 7.15 Interrupt 6
c7_reg_field_1_is_ud: rdi=D m0=aaaaaaaa => ! UD
";
const DECODING: &str = r"
@ mov eax, [ebx]
678b03
@@ -3407,6 +3548,11 @@ fn exchange() {
check_group(EXCHANGE);
}
#[test]
fn immediate_stores() {
check_group(IMMEDIATE_STORES);
}
#[test]
fn flag_moves() {
check_group(FLAG_MOVES);
+430
View File
@@ -0,0 +1,430 @@
// 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>,
/// Base relocation blocks, placed in `.text` 0x100 bytes after the code.
relocations: 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(),
relocations: Vec::new(),
}
}
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;
}
// 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;
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);
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
}
}
/// `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(),
"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<u8> {
let mut entries: Vec<u16> = 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<u8>)| {
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))
);
}
+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()));
}
+22
View File
@@ -69,6 +69,28 @@ 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, 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. Without `--report` it writes to `diagnostics/probe`,
where `xenora imports sync` also looks. `missing_imports.csv` lists unresolved ordinary keys