Compare commits

..
Author SHA1 Message Date
Swastick Chowdhury 7876a625ab Merge 729e1b4cb1 into 0fdb995892 2026-11-25 00:34:33 +05:30
Swastickc 729e1b4cb1 loader: draw nothing for zero-instance flat draws and reject unsupported ones (#148)
Flat DrawInstanced ignored InstanceCount, StartInstanceLocation and
StartVertexLocation, so a zero-instance draw still drew and a changed
start vertex drew the first triangle. Zero instances or fewer than three
vertices now draw nothing; other unsupported parameters fail with
GraphicsError::Unsupported. Vertex reads use the range-checked
read_resource, so a view past its buffer or an overflowing guest address
fails with IndexOutOfRange.

Add tests/repeated_frames.rs: repeated reset, record, close and execute
frames with hand-derived pixels on the software reference backend.

Signed-off-by: Swastickc <28708247+Swastickc@users.noreply.github.com>
2026-11-25 00:34:19 +05:30
12 changed files with 372 additions and 491 deletions

No files matched your search

+1 -3
View File
@@ -41,8 +41,6 @@ jobs:
python3 crates/isa/generate_semantics.py --check
python3 scripts/audit/semantic_coverage.py --check
python3 scripts/audit/status.py --check
# The generated status check must not depend on the host locale encoding.
LC_ALL=C PYTHONCOERCECLOCALE=0 PYTHONUTF8=0 python3 scripts/audit/status.py --check
for fixture in x2 x3 x4; do
python3 "experiments/x1/fixtures/$fixture.py" --check || exit 1
done
@@ -67,7 +65,7 @@ jobs:
cargo test --locked --workspace
cargo test --locked --manifest-path experiments/x1/Cargo.toml
scripts/audit/dependencies.sh
LC_ALL=C PYTHONCOERCECLOCALE=0 PYTHONUTF8=0 scripts/audit/claims.sh
scripts/audit/claims.sh
- name: Inspect native CLI
run: |
cargo build --locked -p xenora
+1 -3
View File
@@ -10,7 +10,6 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Changed
- Relocation reports now build their type histogram once per image, avoiding a tree lookup for every entry. Target checks and fixup order are unchanged; synthetic regressions and an opt-in relocation timing test cover the change (#109).
- Moved the six supported gfx1030 SOPP compute control forms into the semantic registry, preserving instruction decoding and shader lowering. Part of #215.
- Moved gfx1030 `s_mov_b32` (SOP1) into the semantic registry, preserving its existing decode domain and shader output. The move operand rule retains explicit VCC and EXEC half destinations. Part of #215.
- Moved the six hand-written gfx1030 VOP2 logical and shift forms (`v_and_b32`, `v_or_b32`, `v_xor_b32`, `v_lshlrev_b32`, `v_lshrrev_b32`, `v_ashrrev_i32`, AMD guide section 12.7) into the semantic registry under a new VGPR-only operand rule `vop2_vgpr2`, with no behaviour change: a sweep of 132,608 VOP2, VOP1 and SOP1 words decodes to the same text, length and error before and after, the MSL goldens are unchanged, and the runtime-region allowlist admits exactly the same six forms. The per-lane `VectorBinary` gained `And`, `Or`, `Xor` and the three shifts (count masked to S0[4:0]); 6 hand-written instruction variants and their decoder and lowering arms are gone (17 hand-written forms remain). Part of #215.
@@ -18,7 +17,6 @@ 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
- 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).
- 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.
@@ -189,6 +187,7 @@ remains unsupported.
native DBT.
### Fixed
- Fixed flat (untextured) guest `DrawInstanced` draws in the synthetic D3D12-style graphics context (#148). A draw with zero instances or fewer than three vertices now draws nothing. A non-zero start vertex or start instance, more than one instance or more than three vertices now fails with `GraphicsError::Unsupported` instead of drawing the view's first triangle. Vertex reads stay inside the vertex buffer, so a view past its end, or one whose guest address would overflow, fails with `IndexOutOfRange` instead of reading neighbouring guest memory or panicking. `crates/loader/tests/repeated_frames.rs` runs these through repeated reset, record, close and execute frames on the software reference backend, with hand-derived pixels; no native Metal result is claimed.
- Made the static probe and the binder share one bounded import parser, after the truncated-name fix for #270. Truncated, unterminated, empty or non-ASCII names, reserved bits and endless tables are reported by the probe and refused by the binder.
- Fixed import binding writing some slots before finding an unresolved import, and service calls taking effect before an unreadable return address was noticed. A service that changes a nonvolatile register, including XMM6 to XMM15, now stops the guest (part of #201).
- Fixed older import-generator templates that reported success for unimplemented wrappers, used a nonexistent exit reason, and read floating-point arguments from integer registers.
@@ -198,7 +197,6 @@ remains unsupported.
- Fixed 32-bit guest stores and loads in the native DBT (MOV 89/8B and C7 /0), which accessed eight bytes: stores overwrote the next four guest bytes and accesses at the end of a mapping faulted. RIP-relative operands of byte moves and extensions, which were read as RBP-relative, and LEA with a segment prefix, which added the segment base, are fixed too.
- Fixed an x86 prefix-length test that read an untracked fuzz artifact and so failed on every fresh checkout; its input is now inline.
- Fixed agent-queue `apply_actions` crashing on comment-only decisions (claim refusals) by skipping no-op `gh issue edit` calls; accept `summary --now` after the subcommand; grant the audit job `pull-requests: read` so live audits can list open PRs (issue #180).
- Fixed `scripts/audit/status.py` and the Python embedded in `scripts/audit/claims.sh` reading and writing tracked files in the process locale encoding instead of UTF-8: under an ASCII or cp1252 locale the status check crashed on `docs/claims.toml` or reported a spurious `xenora-progress.svg` difference. Both scripts now pass `encoding="utf-8"`, as the rest of `scripts/` does, the two write sites also pin `newline="\n"` so a Windows host cannot turn tracked LF files into CRLF when it regenerates them, and CI runs the two checks again under a non-UTF-8 locale so the requirement stays enforced.
- Generated CRT adapters now report unsupported calls when the required guest ABI or runtime behavior is missing.
+11 -80
View File
@@ -1,12 +1,5 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Synthetic interpreter and DBT timings.
//!
//! The benchmark target disables Cargo's test harness. To run the percentile
//! unit tests, build with
//! `cargo rustc --locked -p xenora-loader --bench dbt_bench --message-format=json -- --test`
//! and run the executable named by the benchmark's compiler-artifact message.
use std::hint::black_box;
use std::time::{Duration, Instant};
use xenora_loader::cpu::{CpuState, ExecutionResult, ExitReason, Interpreter, Register};
@@ -95,25 +88,14 @@ fn check(result: ExecutionResult) {
assert_eq!(result.final_state.get(Register::Rax), ADDS as u64);
}
fn percentile(sorted: &[Duration], fraction: f64) -> Duration {
// Interpolate between adjacent values at rank (n - 1) * fraction.
let rank = (sorted.len() - 1) as f64 * fraction;
let lower = sorted[rank.floor() as usize];
let upper = sorted[rank.ceil() as usize];
lower + (upper - lower).mul_f64(rank.fract())
}
fn report(label: &str, samples: &mut [Duration]) {
samples.sort_unstable();
let median = percentile(samples, 0.50);
let p95 = percentile(samples, 0.95);
let p99 = percentile(samples, 0.99);
let iqr = percentile(samples, 0.75) - percentile(samples, 0.25);
let median = samples[samples.len() / 2];
let min = samples[0];
let max = samples[samples.len() - 1];
let mips = INSTRUCTIONS as f64 / median.as_secs_f64() / 1_000_000.0;
println!(
"{label}: {} samples, median {median:?}, min {min:?}, max {max:?}, p95 {p95:?}, p99 {p99:?}, IQR {iqr:?}, median {mips:.2} MIPS",
"{label}: {} samples, median {median:?}, min {min:?}, max {max:?}, median {mips:.2} MIPS",
samples.len()
);
}
@@ -122,8 +104,6 @@ fn main() {
let sample_count = std::env::var("XENORA_DBT_BENCH_SAMPLES")
.map_or(101, |value| value.parse::<usize>().expect("sample count"));
assert!(sample_count > 0);
let warmup_count = std::env::var("XENORA_DBT_BENCH_WARMUP")
.map_or(10, |value| value.parse::<usize>().expect("warmup count"));
let mut code = vec![0x48, 0xB8, 0, 0, 0, 0, 0, 0, 0, 0]; // mov rax, 0
for _ in 0..ADDS {
@@ -144,52 +124,38 @@ fn main() {
let mut warm = Vec::with_capacity(sample_count);
let mut cold_metrics = None;
for record in
std::iter::repeat_n(false, warmup_count).chain(std::iter::repeat_n(true, sample_count))
{
for _ in 0..sample_count {
let mut interp = Interpreter::new(initial_cpu.clone(), &mut loaded.memory, BUDGET);
let start = Instant::now();
let result = black_box(interp.run());
let interpreter_time = start.elapsed();
interpreter.push(start.elapsed());
check(result);
let mut dbt = DbtEngine::new(4 * 1024 * 1024).unwrap();
let mut cpu = initial_cpu.clone();
let start = Instant::now();
let result = black_box(dbt.run(&mut cpu, &mut loaded.memory, BUDGET));
let cold_time = start.elapsed();
cold.push(start.elapsed());
check(result);
assert!(dbt.metrics.blocks_compiled > 0);
assert_eq!(dbt.metrics.cache_hits, 0);
assert_eq!(dbt.metrics.cache_misses, dbt.metrics.blocks_compiled);
let metrics = dbt.metrics;
cold_metrics = Some(dbt.metrics);
let mut cpu = initial_cpu.clone();
let start = Instant::now();
let result = black_box(dbt.run(&mut cpu, &mut loaded.memory, BUDGET));
let warm_time = start.elapsed();
warm.push(start.elapsed());
check(result);
assert_eq!(dbt.metrics.blocks_compiled, metrics.blocks_compiled);
assert_eq!(
Some(dbt.metrics.blocks_compiled),
cold_metrics.map(|m| m.blocks_compiled)
);
assert_eq!(dbt.metrics.cache_hits, dbt.metrics.blocks_compiled);
assert_eq!(dbt.metrics.cache_misses, dbt.metrics.blocks_compiled);
if record {
interpreter.push(interpreter_time);
cold.push(cold_time);
warm.push(warm_time);
cold_metrics = Some(metrics);
}
}
println!("{INSTRUCTIONS} guest instructions per sample, final RAX={ADDS}");
println!("{warmup_count} warmup rounds excluded (XENORA_DBT_BENCH_WARMUP, default 10)");
println!(
"Cold DBT includes translation with a fresh engine; warm DBT reuses that engine's cache."
);
println!(
"Percentiles describe this synthetic workload on this host; tail estimates vary with sample count."
);
println!("Even sample counts use the midpoint of the two middle values for the median.");
report("Interpreter", &mut interpreter);
report("Cold DBT", &mut cold);
report("Warm DBT", &mut warm);
@@ -199,38 +165,3 @@ fn main() {
metrics.blocks_compiled, metrics.native_bytes_emitted, metrics.dbt_dispatches
);
}
#[cfg(test)]
mod tests {
#[test]
fn single_sample_has_no_spread() {
use super::{Duration, percentile};
let samples = [Duration::from_micros(50)];
for fraction in [0.25, 0.50, 0.75, 0.95, 0.99] {
assert_eq!(percentile(&samples, fraction), samples[0]);
}
}
#[test]
fn percentiles_interpolate_across_even_samples() {
use super::{Duration, percentile};
let samples = [10, 20, 30, 100].map(Duration::from_micros);
assert_eq!(percentile(&samples, 0.50), Duration::from_micros(25));
assert_eq!(percentile(&samples, 0.95), Duration::from_nanos(89_500));
assert_eq!(percentile(&samples, 0.99), Duration::from_nanos(97_900));
assert_eq!(
percentile(&samples, 0.75) - percentile(&samples, 0.25),
Duration::from_nanos(30_000)
);
}
#[test]
fn median_uses_the_middle_of_odd_samples() {
use super::{Duration, percentile};
let samples = [10, 20, 100].map(Duration::from_micros);
assert_eq!(percentile(&samples, 0.50), Duration::from_micros(20));
}
}
+24 -15
View File
@@ -120,10 +120,11 @@ pub enum GraphicsError {
/// An index buffer format other than DXGI `R16_UINT` (57) or `R32_UINT` (42).
InvalidIndexFormat(u32),
/// An indexed draw reads past its index buffer or fetches a vertex,
/// after applying the base vertex, outside its vertex buffer.
/// after applying the base vertex, outside its vertex buffer, or a flat
/// draw reads its vertices outside the vertex buffer.
IndexOutOfRange,
/// A descriptor heap, view, sampler, root signature or binding outside
/// the supported texture-binding subset. Nothing is drawn.
/// A descriptor heap, view, sampler, root signature, binding or draw
/// outside the supported subset. Nothing is drawn.
Unsupported(&'static str),
}
@@ -151,8 +152,8 @@ impl std::fmt::Display for GraphicsError {
Self::InvalidIndexFormat(format) => {
write!(f, "unsupported index buffer format {format}")
}
Self::IndexOutOfRange => write!(f, "indexed draw outside its index or vertex buffer"),
Self::Unsupported(what) => write!(f, "unsupported texture binding: {what}"),
Self::IndexOutOfRange => write!(f, "draw outside its index or vertex buffer"),
Self::Unsupported(what) => write!(f, "unsupported graphics operation: {what}"),
}
}
}
@@ -1673,9 +1674,22 @@ impl GraphicsContext {
rendered_output = Some(pixels);
continue;
}
if *vertex_count_per_instance < 3 {
// Zero instances, or fewer vertices than one triangle,
// draw nothing. The flat path draws only the first
// triangle of the view, once; anything else is rejected
// rather than drawn as a different triangle.
if *vertex_count_per_instance < 3 || *instance_count == 0 {
continue;
}
if *vertex_count_per_instance != 3
|| *instance_count != 1
|| *start_vertex_location != 0
|| *start_instance_location != 0
{
return Err(GraphicsError::Unsupported(
"flat draw other than one instance of the view's first three vertices",
));
}
draw_count += 1;
let v_res_handle =
vertex_resource.ok_or(GraphicsError::InvalidResourceHandle)?;
@@ -1684,15 +1698,10 @@ impl GraphicsContext {
.get(&v_res_handle)
.ok_or(GraphicsError::InvalidResourceHandle)?;
// Read vertices from guest memory backing or resource data
let mut raw_vtx = [0u8; 48]; // 3 * 4 * float32
if let Some(guest_addr) = v_res.guest_backing_addr {
memory.read_bytes(guest_addr + vertex_offset as u64, &mut raw_vtx)?;
} else if v_res.data.len() >= vertex_offset + 48 {
raw_vtx.copy_from_slice(&v_res.data[vertex_offset..vertex_offset + 48]);
} else {
return Err(GraphicsError::InvalidDescriptor);
}
// Three float4 positions, inside the resource whether it
// is backed by guest memory or by its own bytes.
let mut raw_vtx = [0u8; 48];
Self::read_resource(v_res, memory, vertex_offset, &mut raw_vtx)?;
let mut vertices = [[0.0f32; 4]; 3];
for (i, row) in vertices.iter_mut().enumerate() {
+1 -234
View File
@@ -163,6 +163,7 @@ pub fn apply_relocations(
let reloc_type = (entry_val >> 12) as u8;
let offset_in_page = (entry_val & 0x0FFF) as u32;
*report.type_counts.entry(reloc_type).or_insert(0) += 1;
report.total_entries += 1;
match reloc_type {
@@ -220,17 +221,6 @@ pub fn apply_relocations(
read_bytes += block_size as usize;
}
// Only these two types can reach a successful return. Build the public
// histogram once instead of searching its tree for every relocation.
for (kind, count) in [
(IMAGE_REL_BASED_ABSOLUTE, report.skipped_absolute),
(IMAGE_REL_BASED_DIR64, report.applied_dir64),
] {
if count != 0 {
report.type_counts.insert(kind, count);
}
}
Ok(report)
}
@@ -284,226 +274,3 @@ fn find_reloc_directory(
Ok(Some((reloc_rva, reloc_size)))
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::memory::MemoryPermissions;
use crate::pe::PeSection;
use std::hint::black_box;
use std::time::Instant;
const PREFERRED: u64 = 0x140000000;
const LOADED: u64 = PREFERRED + 0x200000;
const DATA_RVA: u32 = 0x1000;
const DIRECTORY_RVA: u32 = 0x10000000;
const DIRECTORY_OFFSET: usize = 0x200;
// Original synthetic directory, laid out from Microsoft's PE Format,
// .reloc section: eight-byte block headers and two-byte type/offset words.
// https://learn.microsoft.com/windows/win32/debug/pe-format#the-reloc-section-image-only
// Header fields and metadata are supplied directly: PE parsing is not timed.
fn fixture(blocks: &[(u32, Vec<u16>)], data: &[u8]) -> (ParsedPe, Vec<u8>, GuestMemory) {
let mut bytes = vec![0u8; DIRECTORY_OFFSET];
bytes[0x3c..0x40].copy_from_slice(&0x80u32.to_le_bytes());
bytes[0x94..0x96].copy_from_slice(&240u16.to_le_bytes());
bytes[0x104..0x108].copy_from_slice(&16u32.to_le_bytes());
bytes[0x130..0x134].copy_from_slice(&DIRECTORY_RVA.to_le_bytes());
for (page, entries) in blocks {
bytes.extend_from_slice(&page.to_le_bytes());
bytes.extend_from_slice(&(8u32 + entries.len() as u32 * 2).to_le_bytes());
for entry in entries {
bytes.extend_from_slice(&entry.to_le_bytes());
}
}
let size = (bytes.len() - DIRECTORY_OFFSET) as u32;
bytes[0x134..0x138].copy_from_slice(&size.to_le_bytes());
let pe = ParsedPe {
machine: 0x8664,
number_of_sections: 1,
time_date_stamp: 0,
image_base: PREFERRED,
section_alignment: 4096,
file_alignment: 512,
size_of_image: DIRECTORY_RVA + size.max(4096),
size_of_headers: 512,
entry_point_rva: 0,
sections: vec![PeSection {
name: ".reloc".into(),
virtual_address: DIRECTORY_RVA,
virtual_size: size,
raw_data_ptr: DIRECTORY_OFFSET as u32,
raw_data_size: size,
characteristics: 0x40000040,
permissions: MemoryPermissions::READ_ONLY,
}],
};
let mut memory = GuestMemory::new();
memory
.map_region_with_data(
LOADED + u64::from(DATA_RVA),
data.len(),
MemoryPermissions::READ_ONLY,
data,
)
.unwrap();
(pe, bytes, memory)
}
#[test]
fn counts_padding_and_rebases_read_only_targets() {
for (preferred, initial, expected) in [
(PREFERRED, 0x140001234, 0x140201234),
(LOADED + 0x200000, 0x140001234, 0x13fe01234),
(LOADED - 8, u64::MAX - 3, 4),
(LOADED + 8, 3, u64::MAX - 4),
] {
let (mut pe, bytes, mut memory) =
fixture(&[(DATA_RVA, vec![0x0fff, 0xa000])], &initial.to_le_bytes());
pe.image_base = preferred;
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
assert_eq!(memory.read_u64(LOADED + 0x1000).unwrap(), expected);
assert_eq!(report.total_entries, 2);
assert_eq!(report.applied_dir64, 1);
assert_eq!(report.skipped_absolute, 1);
assert_eq!(report.type_counts, BTreeMap::from([(0, 1), (10, 1)]));
}
}
#[test]
fn histogram_omits_types_that_did_not_occur() {
for (entries, counts) in [
(vec![], BTreeMap::new()),
(vec![0x0fff, 0x0000], BTreeMap::from([(0, 2)])),
(vec![0xa000, 0xa008], BTreeMap::from([(10, 2)])),
] {
let (pe, bytes, mut memory) = fixture(&[(DATA_RVA, entries)], &[0; 16]);
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
assert_eq!(report.type_counts, counts);
}
}
#[test]
fn preserves_duplicate_and_overlapping_entry_order() {
let (pe, bytes, mut memory) = fixture(
&[(DATA_RVA, vec![0xa000, 0xa000, 0xa004, 0x0000])],
&[0; 16],
);
let report = apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
// Two additions of 0x200000 at offset zero, then one at offset four.
let mut actual = [0; 16];
memory.read_bytes(LOADED + 0x1000, &mut actual).unwrap();
assert_eq!(
actual,
[0, 0, 0x40, 0, 0, 0, 0x20, 0, 0, 0, 0, 0, 0, 0, 0, 0]
);
assert_eq!(report.type_counts, BTreeMap::from([(0, 1), (10, 3)]));
}
#[test]
fn overlapping_fields_observe_prior_carries_in_directory_order() {
let initial = [255, 255, 255, 255, 255, 255, 255, 255, 0, 0, 0, 0];
for (entries, expected) in [
(vec![0xa000, 0xa004], [0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0]),
(vec![0xa004, 0xa000], [0, 0, 0, 0, 1, 0, 0, 0, 1, 0, 0, 0]),
] {
let (mut pe, bytes, mut memory) = fixture(&[(DATA_RVA, entries)], &initial);
pe.image_base = LOADED - 1;
apply_relocations(&pe, &bytes, LOADED, &mut memory).unwrap();
let mut actual = [0; 12];
memory.read_bytes(LOADED + 0x1000, &mut actual).unwrap();
assert_eq!(actual, expected);
}
}
#[test]
fn preserves_prior_writes_and_rejects_unsupported_types() {
let (pe, bytes, mut memory) = fixture(&[(DATA_RVA, vec![0xa000, 0xf008])], &[0; 16]);
assert_eq!(
apply_relocations(&pe, &bytes, LOADED, &mut memory),
Err(RelocationError::UnsupportedRelocationType(15))
);
assert_eq!(memory.read_u64(LOADED + 0x1000).unwrap(), 0x200000);
assert_eq!(memory.read_u64(LOADED + 0x1008).unwrap(), 0);
}
#[test]
fn zero_delta_keeps_the_empty_report_without_parsing() {
let (mut pe, _, mut memory) = fixture(&[], &[0; 8]);
pe.image_base = LOADED;
assert_eq!(
apply_relocations(&pe, &[], LOADED, &mut memory).unwrap(),
RelocationReport::default()
);
}
#[test]
#[ignore = "manual relocation timing run; release build on an otherwise idle host"]
fn relocation_profile() {
for pages in [1u32, 128] {
for padding_every in [0usize, 2, 1] {
let blocks: Vec<_> = (0..pages)
.map(|page| {
let entries = (0..512)
.map(|slot| {
let padding = padding_every != 0 && slot % padding_every == 0;
(if padding { 0 } else { 0xa000 }) | (slot as u16 * 8)
})
.collect();
(DATA_RVA + page * 4096, entries)
})
.collect();
let (pe, bytes, initial) = fixture(&blocks, &vec![0; pages as usize * 4096]);
let mut samples = Vec::new();
for run in 0..36 {
let mut memory = initial.clone();
let start = Instant::now();
let report = black_box(
apply_relocations(
black_box(&pe),
black_box(&bytes),
LOADED,
black_box(&mut memory),
)
.unwrap(),
);
let elapsed = start.elapsed().as_secs_f64() * 1e6;
assert_eq!(report.total_entries, pages as usize * 512);
let padding = match padding_every {
0 => 0,
2 => report.total_entries / 2,
_ => report.total_entries,
};
assert_eq!(report.skipped_absolute, padding);
assert_eq!(report.applied_dir64, report.total_entries - padding);
// Check every output against the fixture's independently specified pattern.
for slot in 0..pages as usize * 512 {
let expected = if padding_every != 0 && slot % padding_every == 0 {
0
} else {
0x200000
};
assert_eq!(
memory.read_u64(LOADED + 0x1000 + slot as u64 * 8).unwrap(),
expected
);
}
if run >= 5 {
samples.push(elapsed);
}
}
samples.sort_by(f64::total_cmp);
let mean = samples.iter().sum::<f64>() / samples.len() as f64;
let variance =
samples.iter().map(|s| (s - mean).powi(2)).sum::<f64>() / samples.len() as f64;
println!(
"pages={pages} padding_every={padding_every} n={} median_us={:.3} variance_us2={variance:.3} min_us={:.3} max_us={:.3}",
samples.len(),
samples[samples.len() / 2],
samples[0],
samples[samples.len() - 1]
);
}
}
}
}
+325
View File
@@ -0,0 +1,325 @@
// SPDX-License-Identifier: GPL-3.0-or-later
//! Repeated-frame regression for the guest graphics context (issue #148).
//!
//! One device, queue, allocator and command list are driven through the
//! per-frame loop a D3D12 guest uses: reset, record, close, execute. Each
//! frame changes the guest-backed vertex data, the clear colour or the draw
//! parameters. Expected pixels are written out by hand below for triangles
//! chosen so their coverage of a 4×3 viewport is obvious; they are not
//! computed by the rasterizer under test. These tests use the software
//! reference backend only; no native Metal result is claimed here.
use xenora_loader::graphics::{
CommandListType, GraphicsBackendId, GraphicsContext, GraphicsError, GraphicsHandle,
ResourceDesc, ResourceDimension, ResourceStates,
};
use xenora_loader::memory::{GuestMemory, MemoryPermissions};
const WIDTH: usize = 4;
const HEIGHT: usize = 3;
const VERTICES: u64 = 0x0010_0000;
/// Two triangles of three float4 positions each.
const VERTEX_BYTES: usize = 96;
const RED: [u8; 4] = [255, 0, 0, 255];
/// Covers every pixel centre of the viewport.
const FULL: [[f32; 4]; 3] = [
[-1.0, -1.0, 0.0, 1.0],
[3.0, -1.0, 0.0, 1.0],
[-1.0, 3.0, 0.0, 1.0],
];
/// Its right edge is x = 0 in clip space, so it covers the two left columns
/// (centres at x = -0.75 and -0.25) and none of the two right ones.
const LEFT_HALF: [[f32; 4]; 3] = [
[0.0, 10.0, 0.0, 1.0],
[0.0, -10.0, 0.0, 1.0],
[-30.0, 0.0, 0.0, 1.0],
];
/// Lies wholly outside the viewport.
const OFFSCREEN: [[f32; 4]; 3] = [
[2.0, 2.0, 0.0, 1.0],
[3.0, 2.0, 0.0, 1.0],
[2.0, 3.0, 0.0, 1.0],
];
struct Rig {
ctx: GraphicsContext,
memory: GuestMemory,
queue: GraphicsHandle,
alloc: GraphicsHandle,
list: GraphicsHandle,
vertices: GraphicsHandle,
target: GraphicsHandle,
}
fn rig() -> Rig {
let mut ctx = GraphicsContext::new();
let device = ctx.create_device().unwrap();
let queue = ctx
.create_command_queue(device, CommandListType::Direct)
.unwrap();
let alloc = ctx
.create_command_allocator(device, CommandListType::Direct)
.unwrap();
let list = ctx
.create_command_list(device, alloc, CommandListType::Direct)
.unwrap();
// A new list starts open; close it so every frame begins with a reset.
ctx.close_command_list(list).unwrap();
let mut memory = GuestMemory::new();
memory
.map_region(VERTICES, 0x1000, MemoryPermissions::READ_WRITE)
.unwrap();
let buffer = ResourceDesc {
dimension: ResourceDimension::Buffer,
width: VERTEX_BYTES as u64,
height: 1,
depth_or_array_size: 1,
mip_levels: 1,
format_rgba8: false,
};
let vertices = ctx
.create_committed_resource(
device,
buffer,
ResourceStates::VERTEX_AND_CONSTANT_BUFFER,
Some(VERTICES),
)
.unwrap();
let texture = ResourceDesc {
dimension: ResourceDimension::Texture2D,
width: WIDTH as u64,
height: HEIGHT as u32,
depth_or_array_size: 1,
mip_levels: 1,
format_rgba8: true,
};
let target = ctx
.create_committed_resource(device, texture, ResourceStates::PRESENT, None)
.unwrap();
Rig {
ctx,
memory,
queue,
alloc,
list,
vertices,
target,
}
}
fn write_triangle(memory: &mut GuestMemory, slot: u64, triangle: [[f32; 4]; 3]) {
let bytes: Vec<u8> = triangle
.iter()
.flatten()
.flat_map(|value| value.to_le_bytes())
.collect();
memory.write_bytes(VERTICES + slot * 48, &bytes).unwrap();
}
/// Pixels with `columns` red from the left and the rest in `clear`.
fn expected(columns: usize, clear: [u8; 4]) -> Vec<u8> {
(0..WIDTH * HEIGHT)
.flat_map(|pixel| if pixel % WIDTH < columns { RED } else { clear })
.collect()
}
struct Draw {
clear: [u8; 4],
offset: usize,
vertex_count: u32,
instance_count: u32,
start_vertex: u32,
start_instance: u32,
}
impl Draw {
fn one(clear: [u8; 4]) -> Self {
Self {
clear,
offset: 0,
vertex_count: 3,
instance_count: 1,
start_vertex: 0,
start_instance: 0,
}
}
}
/// Record one frame: target to RENDER_TARGET, draw, back to PRESENT.
fn record(rig: &mut Rig, draw: &Draw) -> Result<(), GraphicsError> {
let ctx = &mut rig.ctx;
ctx.reset_command_list(rig.list, rig.alloc)?;
ctx.cmd_resource_barrier(
rig.list,
rig.target,
ResourceStates::PRESENT,
ResourceStates::RENDER_TARGET,
)?;
ctx.cmd_set_viewport(rig.list, WIDTH, HEIGHT)?;
ctx.cmd_set_render_targets(rig.list, Some(rig.target), draw.clear)?;
ctx.cmd_set_vertex_buffer(rig.list, rig.vertices, draw.offset, 48)?;
ctx.cmd_draw_instanced(
rig.list,
draw.vertex_count,
draw.instance_count,
draw.start_vertex,
draw.start_instance,
)?;
ctx.cmd_resource_barrier(
rig.list,
rig.target,
ResourceStates::RENDER_TARGET,
ResourceStates::PRESENT,
)?;
ctx.close_command_list(rig.list)
}
fn frame(rig: &mut Rig, draw: &Draw) -> Result<(Vec<u8>, usize), GraphicsError> {
record(rig, draw)?;
let outcome = rig
.ctx
.execute_command_list(rig.queue, rig.list, &rig.memory)?;
assert_eq!(outcome.backend, GraphicsBackendId::SoftwareReference);
assert_eq!((outcome.width, outcome.height), (WIDTH, HEIGHT));
Ok((outcome.pixels, outcome.draw_count))
}
fn frame_index(rig: &Rig) -> u64 {
rig.ctx.last_presentation.lock().unwrap().frame_index
}
#[test]
fn each_frame_reflects_its_own_guest_vertices_and_clear_colour() {
let mut rig = rig();
let frames = [
(LEFT_HALF, [0, 0, 64, 255], 2),
(FULL, [10, 20, 30, 255], WIDTH),
(OFFSCREEN, [1, 2, 3, 4], 0),
(LEFT_HALF, [9, 9, 9, 255], 2),
];
for (index, (triangle, clear, columns)) in frames.into_iter().enumerate() {
write_triangle(&mut rig.memory, 0, triangle);
let (pixels, draws) = frame(&mut rig, &Draw::one(clear)).unwrap();
let want = expected(columns, clear);
assert_eq!(pixels, want, "frame {index}");
assert_eq!(draws, 1, "frame {index}");
assert_eq!(frame_index(&rig), index as u64 + 1);
// The presentation holds this frame's pixels, not an earlier one's.
let presented = rig.ctx.last_presentation.lock().unwrap().pixels.clone();
assert_eq!(presented, want, "presented frame {index}");
}
}
#[test]
fn a_zero_instance_or_zero_vertex_frame_draws_nothing() {
let mut rig = rig();
write_triangle(&mut rig.memory, 0, FULL);
let clear = [5, 6, 7, 255];
for (vertices, instances) in [(3, 0), (0, 1), (2, 1)] {
let draw = Draw {
vertex_count: vertices,
instance_count: instances,
..Draw::one(clear)
};
let (pixels, draws) = frame(&mut rig, &draw).unwrap();
assert_eq!(pixels, expected(0, clear), "{vertices} x {instances}");
assert_eq!(draws, 0, "{vertices} x {instances}");
}
// The next ordinary frame still draws.
let (pixels, draws) = frame(&mut rig, &Draw::one(clear)).unwrap();
assert_eq!((pixels, draws), (expected(WIDTH, clear), 1));
}
#[test]
fn unsupported_draw_parameters_fail_and_the_next_frame_recovers() {
let mut rig = rig();
write_triangle(&mut rig.memory, 0, LEFT_HALF);
write_triangle(&mut rig.memory, 1, FULL);
let clear = [0, 0, 0, 255];
frame(&mut rig, &Draw::one(clear)).unwrap();
let rejected = [
Draw {
start_vertex: 3,
..Draw::one(clear)
},
Draw {
instance_count: 2,
..Draw::one(clear)
},
Draw {
start_instance: 1,
..Draw::one(clear)
},
Draw {
vertex_count: 6,
..Draw::one(clear)
},
];
for draw in &rejected {
// Only the draw is rejected. The barrier before it already ran, so
// the target is left in RENDER_TARGET, as a guest would see it.
let before = frame_index(&rig);
let result = frame(&mut rig, draw);
assert!(
matches!(result, Err(GraphicsError::Unsupported(_))),
"{result:?}"
);
assert_eq!(frame_index(&rig), before, "a failed frame is not presented");
rig.ctx.reset_command_list(rig.list, rig.alloc).unwrap();
rig.ctx
.cmd_resource_barrier(
rig.list,
rig.target,
ResourceStates::RENDER_TARGET,
ResourceStates::PRESENT,
)
.unwrap();
rig.ctx.close_command_list(rig.list).unwrap();
rig.ctx
.execute_command_list(rig.queue, rig.list, &rig.memory)
.unwrap();
}
// The second triangle is still reachable through the view offset.
let draw = Draw {
offset: 48,
..Draw::one(clear)
};
let (pixels, _) = frame(&mut rig, &draw).unwrap();
assert_eq!(pixels, expected(WIDTH, clear));
}
#[test]
fn a_vertex_view_outside_its_buffer_fails_without_reading_past_it() {
let mut rig = rig();
write_triangle(&mut rig.memory, 0, FULL);
write_triangle(&mut rig.memory, 1, FULL);
// Mapped guest memory continues past the buffer; the view must not.
write_triangle(&mut rig.memory, 2, FULL);
let clear = [0, 0, 0, 255];
for offset in [VERTEX_BYTES - 47, VERTEX_BYTES, usize::MAX - 100] {
let draw = Draw {
offset,
..Draw::one(clear)
};
assert_eq!(
frame(&mut rig, &draw),
Err(GraphicsError::IndexOutOfRange),
"offset {offset}"
);
rig.ctx.reset_command_list(rig.list, rig.alloc).unwrap();
rig.ctx
.cmd_resource_barrier(
rig.list,
rig.target,
ResourceStates::RENDER_TARGET,
ResourceStates::PRESENT,
)
.unwrap();
rig.ctx.close_command_list(rig.list).unwrap();
rig.ctx
.execute_command_list(rig.queue, rig.list, &rig.memory)
.unwrap();
}
}
-2
View File
@@ -40,8 +40,6 @@ either path. The [changelog](../CHANGELOG.md) records notable changes.
## Testing, validation, and benchmarks
- [Testing and acceptance index](testing/README.md) — Entry point for test procedures, evidence and review records.
- [AMD RDNA2 desktop GPU (gfx1030) form acceptance](testing/shader-form-acceptance.md) — Independence, command, log and promotion rules for fixture-verified instruction forms.
- [Engineering progress](progress.md) — Verification commands, metric definitions, and open release gates.
- [Test inventory comparison](testing/test-inventory.md) — Detect missing or newly ignored Cargo tests across commits.
- [Persistent resource and translated rendering acceptance](testing/x9-acceptance.md) — Pinned upstream tests, native ARM64 results and unsupported cases.
-9
View File
@@ -1,9 +0,0 @@
# Testing and acceptance
- [AMD RDNA2 desktop GPU (gfx1030) form acceptance](shader-form-acceptance.md) — Rule and evidence required to promote a form from local results to `fixture verified`.
- [Test inventory comparison](test-inventory.md) — Detect missing or newly ignored Cargo tests across commits.
- [Persistent resource and translated rendering acceptance](x9-acceptance.md) — Native ARM64 results and unsupported cases.
- [Baseline acceptance](phase-02-baseline.md) and [Phase 01 assurance](phase01-assurance.md) — Candidate-specific evidence.
- [Independent reviews](review-log.md) — Review findings and acceptance records.
- [Mutation testing](mutation.md) and [benchmark protocol](benchmarks.md) — Sensitivity and timing requirements.
- [Infrastructure QA tooling](infrastructure/README.md) — Advisory orchestration, PR validation, benchmark analysis and release checks.
-7
View File
@@ -1,12 +1,5 @@
# Independent review
## gfx1030 form acceptance
Use the [AMD RDNA2 desktop GPU (gfx1030) form acceptance rule](shader-form-acceptance.md) for entries that
promote instruction forms to `fixture verified`. Record only completed runs with
a named commit, independent runner, host, exact commands and real counts. Raw
logs stay under ignored `artifacts/acceptance/<commit>/`.
## R1. First synthetic compute checkpoint, 2026-11-22
Reviewed the integrated working tree before a candidate commit. The findings below cover the first checkpoint.
-129
View File
@@ -1,129 +0,0 @@
# AMD RDNA2 desktop GPU (gfx1030) form acceptance
This is the promotion rule for AMD RDNA2 desktop GPU (`gfx1030`) instruction
forms in [`docs/status.toml`](../status.toml). It implements the documentation
step of [#302](https://github.com/ranveersoni98/Xenora/issues/302). It does not
claim Xbox-hardware verification or commercial-game compatibility.
The **LLVM three-way decoder check** is the ignored `llvm-mc` comparison in
[`crates/decoder/tests/gfx1030.rs`](../../crates/decoder/tests/gfx1030.rs). It
compares Xenora's decoder with LLVM's gfx1030 decoder over the fixture and
probe encodings; it is encoding evidence, not GPU-semantics evidence.
## Status meanings
| Status | Meaning |
| --- | --- |
| `local known-answer test passed` | The implementation's CPU known-answer test passed locally. This is not independent acceptance. |
| `local Apple M5 readback passed; acceptance pending` | A local native Metal readback passed with validation, but the independence and evidence rules below are incomplete. |
| `fixture verified on Apple M5` | The host-qualified spelling used by three existing rows. `scripts/audit/status.py` treats it as equivalent to `fixture verified`; existing rows do not need re-acceptance solely for this wording. New entries should normally use `fixture verified` and record the host in the review log. |
| `fixture verified` | The form or documented family batch passed independent acceptance at a named commit, with CPU, LLVM and native Metal evidence recorded. |
A skipped test is not a pass. A shader compile without readback is not GPU
verification. Agreement with a spec-derived reference is not agreement with
Xbox hardware.
## Independence
> **Proposed policy, pending maintainer confirmation.** The independence rule in
> this section is the proposal from #302. Do not use it to promote forms until
> the maintainer confirms or revises it.
The person running the acceptance pass must not be the author of the pull
request that added the form being accepted. The runner may use the existing
tests and commands, but must record their own results and review the evidence.
If the maintainer runs the pass for forms they authored, the review-log entry
must say so explicitly; that exception is not silent self-certification.
The expected values used by the test must remain independent of the production
decoder, translator or Metal backend. Do not change fixtures, thresholds or test
filters to make a form pass.
## Acceptance procedure
1. **Use a clean named commit.** Start from a clean checkout of `main` at the
commit being accepted. Record the full commit hash. Do not accept a working
tree with uncommitted changes.
2. **Name the scope.** List each form, or a family batch with an explicit list of
forms, covered by the pass. A family name alone is not enough.
3. **Run the standard gates.** Format, Clippy, workspace tests, fixture checks,
the LLVM three-way decoder check and the native GPU suite must pass. Record
exact commands, environment variables and pass/fail/skip counts.
4. **Run the form's CPU and Metal tests.** The CPU known-answer/reference tests
and the native Metal readback must both pass. Metal API and shader validation
must be enabled. Use a targeted test filter where useful, but keep the full
standard-gate result for the same commit.
5. **Check negative cases.** Unsupported encodings, malformed inputs and any
documented rejection cases for the form must still pass.
6. **Save raw logs.** Put raw output under ignored
`artifacts/acceptance/<commit>/`. Do not commit raw logs.
7. **Write the review-log summary.** Add an entry to
[`review-log.md`](review-log.md) with the commit, runner's GitHub login, host,
scope, exact commands or log path, and CPU/LLVM/Metal results. A reviewer
confirms the entry if the runner is not the maintainer.
8. **Promote only passed forms.** Change `cpu` and `gpu` in `docs/status.toml`
only for forms covered by a passing entry. Regenerate the status tables and
progress graphic, then run `python3 scripts/audit/status.py --check`.
## Standard gate set
Run on native Apple Silicon. The exact host and tool versions belong in the
review-log entry.
```sh
export CARGO_BUILD_JOBS=2
cargo fmt --all -- --check
cargo clippy --locked --workspace --all-targets --all-features -- -D warnings
cargo test --locked --workspace
scripts/assemble-fixture.sh --check
LLVM_BIN="$(brew --prefix llvm)/bin" \
cargo test --locked -p xenora-decoder --test gfx1030 -- --include-ignored --nocapture
cargo test --locked -p xenora-semantic-review
scripts/test-gpu.sh
python3 scripts/audit/status.py --check
```
For a targeted semantic-review pass, record the filter and use the same Metal
validation environment as `scripts/test-gpu.sh`:
```sh
cargo test --locked -p xenora-semantic-review <cpu-test-filter>
MTL_DEBUG_LAYER=1 \
MTL_SHADER_VALIDATION=1 \
MTL_SHADER_VALIDATION_REPORT_TO_STDERR=1 \
MTL_SHADER_VALIDATION_ABORT_ON_FAULT=1 \
cargo test --locked -p xenora-semantic-review <native-metal-test-filter> \
-- --ignored --exact --nocapture --test-threads=1
```
A targeted filter does not replace the standard gate set; it attributes the
result to a form or family batch.
## Review-log entry
Use one row per commit and scope. Add rows to
[`review-log.md`](review-log.md); keep raw output only in `artifacts/`.
| Date | Commit | Runner (GitHub login) | Host and tools | Forms or batch | Commands / raw log | CPU | LLVM | Metal | Review |
| --- | --- | --- | --- | --- | --- | --- | --- | --- | --- |
| YYYY-MM-DD | full SHA | @login | Mac, macOS, Xcode, Rust, LLVM | explicit form list | exact commands and `artifacts/acceptance/<commit>/` path | pass/fail/skip counts | pass/fail counts | pass/fail/skip counts; validation on | reviewer GitHub login or maintainer exception |
Do not write `pass` without counts. Do not count a skipped native test as Metal
evidence.
## Promotion and failures
After a passing entry, set the accepted rows to `fixture verified` and regenerate:
```sh
python3 scripts/audit/status.py
python3 scripts/audit/status.py --check
```
If any required check fails or skips, leave the form pending. Record the commit,
host, command and failure in the review log, and open a separate issue for the
failure. Do not weaken the test or change the expected result in the acceptance
pass.
The automated status-check enforcement proposed in #302 is a separate change.
Until it lands, reviewers must enforce the review-log requirement manually.
+3 -3
View File
@@ -10,7 +10,7 @@ import sys
import tomllib
registry = Path("docs/claims.toml")
claims = tomllib.loads(registry.read_text(encoding="utf-8"))["claim"]
claims = tomllib.loads(registry.read_text())["claim"]
classes = {}
errors = []
claim_id = re.compile(r"\bCLAIM-[A-Z0-9]+(?:-[A-Z0-9]+)*\b")
@@ -37,10 +37,10 @@ files = [Path("README.md"), Path("AGENTS.md"), *Path("docs").rglob("*"),
for source in files:
if source == registry or source.suffix not in {".md", ".toml", ".rs"}:
continue
for reference in set(claim_id.findall(source.read_text(encoding="utf-8"))) - classes.keys():
for reference in set(claim_id.findall(source.read_text())) - classes.keys():
errors.append(f"{source}: unregistered {reference}")
status = tomllib.loads(Path("docs/status.toml").read_text(encoding="utf-8"))
status = tomllib.loads(Path("docs/status.toml").read_text())
for feature in status["feature"]:
verification = feature.get("hardware_verification", "")
if verification.casefold() != "verified":
+6 -6
View File
@@ -18,7 +18,7 @@ def table(headers, rows):
def replace_block(path, name, body, check):
original = path.read_text(encoding="utf-8")
original = path.read_text()
start = f"<!-- status:{name}:start -->\n"
stop = f"\n<!-- status:{name}:end -->"
head, _, tail = original.partition(start)
@@ -30,7 +30,7 @@ def replace_block(path, name, body, check):
if check:
print(f"{path}: status table differs from docs/status.toml", file=sys.stderr)
return False
path.write_text(updated, encoding="utf-8", newline="\n")
path.write_text(updated)
return True
@@ -90,12 +90,12 @@ def render_progress(status):
def check_asset(path, svg, check):
if path.exists() and path.read_text(encoding="utf-8") == svg:
if path.exists() and path.read_text() == svg:
return True
if check:
print(f"{path}: progress graphic differs from docs/status.toml", file=sys.stderr)
return False
path.write_text(svg, encoding="utf-8", newline="\n")
path.write_text(svg)
return True
@@ -105,8 +105,8 @@ def main():
check = parser.parse_args().check
root = Path(__file__).resolve().parents[2]
docs = root / "docs"
status = tomllib.loads((docs / "status.toml").read_text(encoding="utf-8"))
claims = tomllib.loads((docs / "claims.toml").read_text(encoding="utf-8"))
status = tomllib.loads((docs / "status.toml").read_text())
claims = tomllib.loads((docs / "claims.toml").read_text())
classes = {claim["id"]: claim["class"] for claim in claims["claim"]}
features = table(