Fuzz the standard guest service registry

Drive random service call sequences with adversarial arguments and
check memory and register invariants after every call. The libFuzzer
target and a stable replay test share one driver.

Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
Co-authored-by: Cursor <cursoragent@cursor.com>
(cherry picked from commit 3027b9eb06904793c464b80490aa3903bfe7e173)
Signed-off-by: Adeeb Rahman <therealabeeb@icloud.com>
This commit is contained in:
Adeeb Rahman committed 2026-11-24 10:33:26 -05:00
1 parent b9f6985d57
commit b3a6a57a8e
8 files changed
+241 -3

No files matched your search

+1 -1
View File
@@ -91,7 +91,7 @@ A coding agent claims in the name of the person it works for and follows the sam
- Run source mutation on decoder/shader/ref: `scripts/mutation.sh` (R2 owns triage) - Run source mutation on decoder/shader/ref: `scripts/mutation.sh` (R2 owns triage)
- Check generated status tables: `python3 scripts/audit/status.py --check`. - Check generated status tables: `python3 scripts/audit/status.py --check`.
- Check claims and dependency direction: `scripts/audit/claims.sh` and `scripts/audit/dependencies.sh` - Check claims and dependency direction: `scripts/audit/claims.sh` and `scripts/audit/dependencies.sh`
- Fuzz one CPU-only parser at a time: `scripts/fuzz.sh <instruction_stream|fixture|reference>` (600 seconds by default). - Fuzz one target at a time: `scripts/fuzz.sh <instruction_stream|fixture|reference|runtime_services>` (600 seconds by default). `runtime_services` drives the standard guest service registry.
Keep generated and gate logs under ignored `artifacts/`. Use at most four Cargo build jobs across two simultaneous CPU-heavy jobs, with one GPU job and one fuzz or mutation campaign at a time. Keep generated and gate logs under ignored `artifacts/`. Use at most four Cargo build jobs across two simultaneous CPU-heavy jobs, with one GPU job and one fuzz or mutation campaign at a time.
+2
View File
@@ -43,6 +43,8 @@ remains unsupported.
- Added guest mutexes, critical sections, SRW locks, condition variables, synchronous one-time initialization, interlocked SLists, and TLS and FLS slots. Ownership is per guest thread (TEB). Calls that would have to block stop the guest with an explicit runtime-limit fault, because there is no guest scheduler yet. An original PE32+ fixture calls every service through its import table, using two guest TEBs. See `docs/interfaces.md`. - Added guest mutexes, critical sections, SRW locks, condition variables, synchronous one-time initialization, interlocked SLists, and TLS and FLS slots. Ownership is per guest thread (TEB). Calls that would have to block stop the guest with an explicit runtime-limit fault, because there is no guest scheduler yet. An original PE32+ fixture calls every service through its import table, using two guest TEBs. See `docs/interfaces.md`.
- Added a `runtime_services` fuzz target (`scripts/fuzz.sh runtime_services`) and a stable-toolchain replay test sharing the same driver. Both call random sequences of the standard guest services with zero, all-ones, writable, read-only, executable, unmapped, raw and earlier-result arguments, and check after every call that read-only and code memory are unchanged and nonvolatile registers are preserved. A local 300-second campaign on Apple M2 Pro ran 131,744 inputs (1,573 coverage edges) without a crash. Services that wait on real time or reach native Metal are excluded.
- Added guest system information, memory status, calendar time conversion, interrupt time and sleeping. The guest sees a configurable simulated machine (`GuestSystemProfile`, one processor by default), kept separate from the detected host hardware (`HostCapabilities`). Sleeping goes through the injectable clock, so tests advance time deterministically. An original PE32+ fixture verifies `SYSTEM_INFO`, `MEMORYSTATUSEX` and `SYSTEMTIME` layouts and leap-year handling against dates computed independently. - Added guest system information, memory status, calendar time conversion, interrupt time and sleeping. The guest sees a configurable simulated machine (`GuestSystemProfile`, one processor by default), kept separate from the detected host hardware (`HostCapabilities`). Sleeping goes through the injectable clock, so tests advance time deterministically. An original PE32+ fixture verifies `SYSTEM_INFO`, `MEMORYSTATUSEX` and `SYSTEMTIME` layouts and leap-year handling against dates computed independently.
- Added services that call guest code and continue when it returns. The import dispatcher can run a sequence of guest callbacks on a checked stack frame, verifying the Win64 nonvolatile registers after each one. The CRT uses this for `qsort`, `qsort_s`, `bsearch`, `bsearch_s`, `_initterm`, `_initterm_e`, onexit tables, `atexit` and `_cexit`. Kernel32 uses it for `InitOnceExecuteOnce` and `FlsFree` cleanup callbacks. Original guest comparators and initializers in a PE32+ fixture verify ordering, stop-on-failure and register preservation. - Added services that call guest code and continue when it returns. The import dispatcher can run a sequence of guest callbacks on a checked stack frame, verifying the Win64 nonvolatile registers after each one. The CRT uses this for `qsort`, `qsort_s`, `bsearch`, `bsearch_s`, `_initterm`, `_initterm_e`, onexit tables, `atexit` and `_cexit`. Kernel32 uses it for `InitOnceExecuteOnce` and `FlsFree` cleanup callbacks. Original guest comparators and initializers in a PE32+ fixture verify ordering, stop-on-failure and register preservation.
+33
View File
@@ -0,0 +1,33 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Stable-toolchain replay of the `runtime_services` fuzz driver: seeded
//! pseudo-random call sequences against the standard service registry.
mod support;
use support::robustness::Driver;
/// xorshift64*, so every run uses the same inputs.
fn inputs(seed: u64, count: usize, length: usize) -> impl Iterator<Item = Vec<u8>> {
let mut state = seed;
(0..count).map(move |_| {
(0..length)
.map(|_| {
state ^= state >> 12;
state ^= state << 25;
state ^= state >> 27;
(state.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 56) as u8
})
.collect()
})
}
#[test]
fn random_service_sequences_keep_memory_and_register_invariants() {
let driver = Driver::new();
assert!(driver.service_count() > 150, "{}", driver.service_count());
for input in inputs(0x5EED_CAFE, 300, 1024) {
driver.run(&input);
}
driver.run(&[]);
}
+2
View File
@@ -6,6 +6,8 @@
#![allow(dead_code)] #![allow(dead_code)]
pub mod robustness;
use std::sync::Arc; use std::sync::Arc;
use xenora_loader::cpu::{CpuState, ExitReason, Register}; use xenora_loader::cpu::{CpuState, ExitReason, Register};
use xenora_loader::dbt::DbtEngine; use xenora_loader::dbt::DbtEngine;
+182
View File
@@ -0,0 +1,182 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Drives sequences of standard runtime services with adversarial arguments.
//!
//! Shared by the `runtime_services` libFuzzer target and the stable-toolchain
//! regression test. Each call takes its arguments from the input: zero, all
//! ones, pointers into writable, read-only and unmapped memory, raw values,
//! small integers or an earlier result (so handles flow between calls). After
//! every call the driver checks that read-only and code memory are unchanged
//! and that the Win64 nonvolatile registers are preserved. A panic, a broken
//! invariant or a hang is a bug.
use std::sync::Arc;
use xenora_loader::cpu::{CpuState, Register};
use xenora_loader::imports::{ImportRegistry, Win64Args};
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
use xenora_loader::services::{MockClock, ServicesState, register_standard_services};
const WRITABLE: u64 = 0x5_0000;
const WRITABLE_LEN: usize = 0x1_0000;
const READ_ONLY: u64 = 0x7_0000;
const CODE: u64 = 0x7_8000;
const REGION_LEN: usize = 0x1000;
const STACK: u64 = 0x9_0000;
const STACK_LEN: usize = 0x2000;
const UNMAPPED: u64 = 0xDEAD_0000;
const MAX_CALLS: usize = 48;
/// Services that wait on real time, run guest code or reach native Metal are
/// left out, so each input runs quickly and deterministically.
fn excluded(module: &str, symbol: &str) -> bool {
module.eq_ignore_ascii_case("xenora_fixture.dll")
|| matches!(symbol, "WSAPoll" | "XTaskQueueDispatch")
}
pub struct Driver {
services: Vec<(String, String)>,
}
impl Default for Driver {
fn default() -> Self {
Self::new()
}
}
impl Driver {
pub fn new() -> Self {
let mut registry = ImportRegistry::new();
register_standard_services(
&mut registry,
Arc::new(ServicesState::new(Arc::new(MockClock::new(0)))),
);
let mut services: Vec<(String, String)> = registry
.iter_registered()
.filter(|(module, symbol, _)| !excluded(module, symbol))
.map(|(module, symbol, _)| (module.to_owned(), symbol.to_owned()))
.collect();
services.sort();
Self { services }
}
pub fn service_count(&self) -> usize {
self.services.len()
}
/// Run one input against fresh service state and fresh guest memory.
pub fn run(&self, data: &[u8]) {
let mut registry = ImportRegistry::new();
let clock = Arc::new(MockClock::new(0x01DA_0000_0000_0000));
register_standard_services(&mut registry, Arc::new(ServicesState::new(clock)));
let mut input = Input(data);
let mut memory = GuestMemory::new();
memory
.map_region(WRITABLE, WRITABLE_LEN, MemoryPermissions::READ_WRITE)
.unwrap();
memory
.map_region(STACK, STACK_LEN, MemoryPermissions::READ_WRITE)
.unwrap();
let fill: Vec<u8> = (0..WRITABLE_LEN).map(|i| input.byte_or(i as u8)).collect();
memory.write_bytes(WRITABLE, &fill).unwrap();
let read_only: Vec<u8> = (0..REGION_LEN).map(|i| (i * 7) as u8).collect();
memory
.map_region_with_data(
READ_ONLY,
REGION_LEN,
MemoryPermissions::READ_ONLY,
&read_only,
)
.unwrap();
memory
.map_region_with_data(
CODE,
REGION_LEN,
MemoryPermissions::READ_EXECUTE,
&[0xC3; REGION_LEN],
)
.unwrap();
let mut results = vec![0u64];
for _ in 0..MAX_CALLS {
let Some(selector) = input.u16() else { break };
let (module, symbol) = &self.services[selector as usize % self.services.len()];
let mut args = [0u64; 7];
for arg in &mut args {
*arg = input.argument(&results);
}
let rsp = STACK + STACK_LEN as u64 / 2;
let mut cpu = CpuState::new(CODE, rsp);
cpu.gs_base = [0x7_F000, 0x7_F800][input.byte_or(0) as usize % 2];
for (register, value) in [Register::Rcx, Register::Rdx, Register::R8, Register::R9]
.into_iter()
.zip(args)
{
cpu.set(register, value);
}
for (slot, value) in args[4..].iter().enumerate() {
memory
.write_u64(rsp + 40 + 8 * slot as u64, *value)
.unwrap();
}
use Register::{R12, R13, R14, R15, Rbp, Rbx, Rdi, Rsi, Rsp};
let preserved = [Rbx, Rbp, Rdi, Rsi, Rsp, R12, R13, R14, R15];
let before = preserved.map(|register| cpu.get(register));
let service = registry
.binding(module, symbol)
.expect("registered service");
let outcome = (service.handler)(&Win64Args::new(&cpu), &mut cpu, &mut memory);
assert_eq!(
preserved.map(|register| cpu.get(register)),
before,
"{module}!{symbol} changed a nonvolatile register"
);
let mut check = vec![0; REGION_LEN];
memory.read_bytes(READ_ONLY, &mut check).unwrap();
assert_eq!(check, read_only, "{module}!{symbol} wrote read-only memory");
memory.read_bytes(CODE, &mut check).unwrap();
assert!(
check.iter().all(|&byte| byte == 0xC3),
"{module}!{symbol} wrote code memory"
);
if let Ok(value) = outcome {
results.push(value);
}
}
}
}
struct Input<'a>(&'a [u8]);
impl Input<'_> {
fn take<const N: usize>(&mut self) -> Option<[u8; N]> {
let (head, rest) = self.0.split_first_chunk::<N>()?;
self.0 = rest;
Some(*head)
}
fn byte_or(&mut self, default: u8) -> u8 {
self.take::<1>().map_or(default, |[byte]| byte)
}
fn u16(&mut self) -> Option<u16> {
self.take::<2>().map(u16::from_le_bytes)
}
fn argument(&mut self, results: &[u64]) -> u64 {
let offset = u64::from(self.u16().unwrap_or(0));
match self.byte_or(0) % 9 {
0 => 0,
1 => u64::MAX,
2 => WRITABLE + offset % WRITABLE_LEN as u64,
3 => READ_ONLY + offset % REGION_LEN as u64,
4 => CODE + offset % REGION_LEN as u64,
5 => UNMAPPED + offset,
6 => self.take::<8>().map_or(offset, u64::from_le_bytes),
7 => offset % 512,
_ => results[offset as usize % results.len()],
}
}
}
+6
View File
@@ -46,3 +46,9 @@ name = "reference"
path = "fuzz_targets/reference.rs" path = "fuzz_targets/reference.rs"
test = false test = false
doc = false doc = false
[[bin]]
name = "runtime_services"
path = "fuzz_targets/runtime_services.rs"
test = false
doc = false
+13
View File
@@ -0,0 +1,13 @@
// SPDX-License-Identifier: GPL-3.0-or-later
#![no_main]
#[path = "../../crates/loader/tests/support/robustness.rs"]
mod robustness;
use libfuzzer_sys::fuzz_target;
use std::sync::OnceLock;
fuzz_target!(|data: &[u8]| {
static DRIVER: OnceLock<robustness::Driver> = OnceLock::new();
DRIVER.get_or_init(robustness::Driver::new).run(data);
});
+2 -2
View File
@@ -5,8 +5,8 @@ cd "$(dirname "$0")/.."
target=${1:-} target=${1:-}
case "$target" in case "$target" in
instruction_stream|fixture|reference) ;; instruction_stream|fixture|reference|runtime_services) ;;
*) printf '%s\n' 'usage: scripts/fuzz.sh <instruction_stream|fixture|reference> [seconds]' >&2; exit 2 ;; *) printf '%s\n' 'usage: scripts/fuzz.sh <instruction_stream|fixture|reference|runtime_services> [seconds]' >&2; exit 2 ;;
esac esac
seconds=${2:-600} seconds=${2:-600}
case "$seconds" in case "$seconds" in