fix: validate the layout of skipped fixture instructions

This commit is contained in:
Ranveer Soni committed 2026-11-22 18:29:11 +05:30
1 parent 095ec65aee
commit cc0daa79e6
10 files changed
+123 -46

No files matched your search

+6 -5
View File
@@ -8,17 +8,18 @@ Xenora is an experimental, open-source recompilation framework for Xbox Series X
Xenora takes a Metal-first approach rather than relying on a Vulkan runtime, MoltenVK, Rosetta 2 or a Windows compatibility layer.
> [!IMPORTANT]
> Xenora is an early-stage research and development project, not a game-ready emulator. Commercial game compatibility, Xbox hardware equivalence and performance superiority have not been established.
> Xenora is an early-stage research project. Game execution, proprietary Xbox containers and full guest execution-mask divergence are unsupported.
## XenoMetal
XenoMetal is the graphics translation subsystem of Xenora. Its intended scope includes shader decoding, recompilation, GPU resource translation and native Metal execution.
The first working compute fixture passes through the following pipeline:
The synthetic compute fixtures run through this pipeline. An independent CPU interpreter executes the original binary for comparison.
```mermaid
flowchart TD
A[RDNA shader machine code] --> B[Instruction decoder]
A[RDNA shader machine code] --> P[Fixture parser]
P --> B[Instruction decoder]
B --> C[Shader IR]
C --> D[Semantic validation]
D --> E[Metal Shading Language]
@@ -26,7 +27,7 @@ flowchart TD
F --> G[Apple GPU]
```
Run `scripts/demo.sh` to execute three original gfx1030 compute fixtures on Apple Silicon. Integer addition, bitwise and scalar branch, and restricted FP32 outputs matched the independent CPU reference and hand-derived values on Apple M5. Run `scripts/test-gpu.sh` for native Metal correctness, including offscreen rendering with original MSL. The [status file](docs/status.toml) records the verified scope. SPIR-V may be used as an optional compiler intermediate representation without introducing a Vulkan runtime dependency.
Run `scripts/demo.sh` to execute three original gfx1030 compute fixtures on Apple Silicon. Integer addition, bitwise and scalar branch, and restricted FP32 outputs matched the independent CPU reference and hand-derived values on Apple M5 (class A, CLAIM-METAL-M5-RDNA-DEMO). Run `scripts/test-gpu.sh` for native Metal correctness, including offscreen rendering with original MSL (class A, CLAIM-METAL-M5-NATIVE-SUITE). The [status file](docs/status.toml) records the verified scope. SPIR-V may be used as an optional compiler intermediate representation without introducing a Vulkan runtime dependency.
## Development roadmap
@@ -44,7 +45,7 @@ The following describes the project's intended development stages, not a claim t
## Development and testing
Xenora targets the native Rust `aarch64-apple-darwin` toolchain and Apple's Xcode and Metal development tools. LLVM's AMDGPU tools are intended to serve as an independent instruction encoding and decoding reference where applicable.
Xenora targets the native Rust `aarch64-apple-darwin` toolchain and Apple's Xcode and Metal development tools. The gfx1030 oracle tests check the production and reference decoders against Homebrew LLVM AMDGPU.
Run the standard Rust checks from the workspace root:
+29 -33
View File
@@ -270,24 +270,37 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
let mut scc = None;
let mut skip_before = 0;
for instruction in decoded {
let target = match instruction.instruction {
Instruction::Branch { target } | Instruction::BranchSccZero { target } => target,
// Every decoded instruction must satisfy the fixture layout and binding
// contract, even when a known branch skips it.
for (index, instruction) in decoded.iter().enumerate() {
let offset = instruction.offset;
let reason = match instruction.instruction {
Instruction::Branch { target } | Instruction::BranchSccZero { target }
if target <= offset
|| decoded
.binary_search_by_key(&target, |instruction| instruction.offset)
.is_err() =>
{
"branch target must be a forward instruction boundary"
}
Instruction::BufferLoadDword {
index, resource, ..
} if (index, resource) != (0, 0) => "unsupported resource or buffer index",
Instruction::BufferStoreDword {
index, resource, ..
} if (index, resource) != (0, 4) => "unsupported resource or buffer index",
Instruction::EndProgram if index + 1 != decoded.len() => {
return Err(CompileError::Verify {
offset: decoded[index + 1].offset,
reason: "instruction follows program termination",
});
}
_ => continue,
};
if target <= instruction.offset
|| decoded
.binary_search_by_key(&target, |instruction| instruction.offset)
.is_err()
{
return Err(CompileError::Verify {
offset: instruction.offset,
reason: "branch target must be a forward instruction boundary",
});
}
return Err(CompileError::Verify { offset, reason });
}
for (index, instruction) in decoded.iter().enumerate() {
for instruction in decoded {
let offset = instruction.offset;
let error = |reason| CompileError::Verify { offset, reason };
let read = |register: u8| {
@@ -308,11 +321,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
};
let next = Value(operations.len());
let (dest, operation) = match instruction.instruction {
Instruction::BufferLoadDword {
data,
index: 0,
resource: 0,
} => {
Instruction::BufferLoadDword { data, .. } => {
let slot = usize::from(data);
if data == 0 || pending_load.is_some() {
return Err(error(
@@ -323,11 +332,7 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
pending_load = Some((slot, next));
(None, Op::Load)
}
Instruction::BufferStoreDword {
data,
index: 0,
resource: 4,
} => {
Instruction::BufferStoreDword { data, .. } => {
if stored {
return Err(error("only one output store is supported"));
}
@@ -335,9 +340,6 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
store_pending = true;
(None, Op::Store(read(data)?))
}
Instruction::BufferLoadDword { .. } | Instruction::BufferStoreDword { .. } => {
return Err(error("unsupported resource or buffer index"));
}
Instruction::WaitLoad => {
if let Some((register, value)) = pending_load.take() {
registers[register] = Some(value);
@@ -422,12 +424,6 @@ fn lift(decoded: &[DecodedInstruction], code_len: usize) -> Result<Vec<(usize, O
"termination requires one completed store and no pending loads",
));
}
if let Some(next) = decoded.get(index + 1) {
return Err(CompileError::Verify {
offset: next.offset,
reason: "instruction follows program termination",
});
}
return Ok(operations);
}
};
+45
View File
@@ -220,3 +220,48 @@ fn rejects_load_into_index_or_before_waiting_on_previous_load() {
Err(CompileError::Verify { offset: 8, .. })
));
}
#[test]
fn checks_fixture_layout_and_bindings_even_in_skipped_code() {
for (prefix, expected_offset, expected_reason) in [
(
&[0xbf82_0001u32, 0xbf81_0000][..], // Skip an early s_endpgm.
8,
"instruction follows program termination",
),
(
&[0xbf82_0002, 0xe030_2000, 0x8001_0100], // Skip load from s[4:7].
4,
"unsupported resource or buffer index",
),
(
&[0xbf82_0002, 0xe070_2000, 0x8000_0100], // Skip store to s[0:3].
4,
"unsupported resource or buffer index",
),
] {
let code: Vec<_> = prefix
.iter()
.copied()
.flat_map(u32::to_le_bytes)
.chain(FIXTURE.iter().copied())
.collect();
assert!(matches!(
compile(Architecture::Gfx1030, &code),
Err(CompileError::Verify { offset, reason })
if offset == expected_offset && reason == expected_reason
));
}
// A structurally valid instruction on the skipped path need not read an
// initialized register. Here v_mov_b32_e32 v1, v255 never runs.
let code: Vec<_> = [0xbf82_0001u32, 0x7e02_03ff]
.into_iter()
.flat_map(u32::to_le_bytes)
.chain(FIXTURE.iter().copied())
.collect();
let compiled = compile(Architecture::Gfx1030, &code).unwrap();
assert!(compiled.ir.contains("branch.uniform 0x0008 taken=true"));
assert!(compiled.msl.contains("uint t1 = input[index];"));
assert!(compiled.msl.contains("output[index] = t3;"));
}
+1 -1
View File
@@ -4,4 +4,4 @@ For the synthetic compute fixture, the resource beginning at SGPR 0 denotes the
The compiler must reject descriptor forms, offsets, index changes and control flow outside this contract. Both engines must honor the load dependency and completion order. The host reads output after command completion. Supporting shared writable buffers will require a new ordering and aliasing contract.
AMD RDNA 2 specifies implicit outstanding memory waits at program termination. This fixture policy requires explicit corresponding wait instructions before termination to keep the bounded execution model auditable. See the [RDNA 2 source notes](../research/rdna2.md).
AMD RDNA 2 specifies implicit outstanding memory waits at program termination (class B, CLAIM-RDNA2-TRANSFER-WAITS). This fixture policy requires explicit corresponding wait instructions before termination to keep the bounded execution model auditable. See the [RDNA 2 source notes](../research/rdna2.md).
+34
View File
@@ -167,3 +167,37 @@ retrieved = "2026-11-22"
architecture = "Apple M5, macOS 27.3, Xcode 27.2"
test = "scripts/demo.sh"
uncertainty = "Synthetic binding ABI, statically resolved scalar control flow, and exact positive normal FP32."
[[claim]]
id = "CLAIM-METAL-APPLE-FAMILIES"
class = "B"
claim = "Apple lists nonuniform threadgroups from Apple4, SIMD permutes from Apple6, and SIMD reductions from Apple7. M1 maps to Apple7."
sources = ["https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf"]
retrieved = "2026-11-22"
architecture = "Apple GPU families, feature tables revision 2026-10-23"
test = "Independent R1 checked the GPU families and features tables."
uncertainty = "Availability of the feature does not establish Xenora correctness on each device."
[[claim]]
id = "CLAIM-METAL-NATIVE-CONTRACTS"
class = "B"
claim = "Metal dispatchThreads specifies an exact grid subject to supported dispatch and pipeline limits. Shared storage is accessible to CPU and GPU, and waitUntilCompleted waits for command-buffer completion."
sources = [
"https://developer.apple.com/documentation/metal/calculating-threadgroup-and-grid-sizes",
"https://developer.apple.com/documentation/metal/choosing-a-resource-storage-mode-for-apple-gpus",
"https://developer.apple.com/documentation/metal/mtlcommandbuffer/waituntilcompleted()",
]
retrieved = "2026-11-22"
architecture = "Native Metal on Apple GPUs"
test = "The backend applies the documented rules and scripts/test-gpu.sh exercises the bounded submission."
uncertainty = "The API contracts do not establish guest memory ordering."
[[claim]]
id = "CLAIM-RDNA2-TRANSFER-WAITS"
class = "B"
claim = "AMD RDNA 2 distinguishes vector loads and stores in wait accounting and specifies implicit waits at program termination."
sources = ["https://docs.amd.com/v/u/en-US/rdna2-shader-instruction-set-architecture"]
retrieved = "2026-11-22"
architecture = "AMD RDNA 2, document 70648"
test = "Reviewed the wait and program-termination descriptions. Workspace tests exercise the stricter synthetic wait rule."
uncertainty = "The fixture requires explicit waits and does not establish console behavior."
+1 -1
View File
@@ -4,7 +4,7 @@ The first input is little-endian gfx1030 machine code for a compute fixture with
The production decoder takes borrowed code bytes. Its output records typed instructions, operand classes, original offsets and byte lengths. Unknown encodings and unsupported forms fail with a byte offset. The reference interpreter takes the original bytes and input words and performs its own decoding. It shares no production instruction definitions.
The compiler lifts decoded instructions to typed operations and verifies register initialization, supported resource offsets and termination before generating MSL. The initial subset permits only lane-indexed 32-bit buffer accesses against two disjoint buffers with equal lengths. The input is read-only. Each invocation may write only its own output word. Compile-time known forward scalar branches are resolved during verification. Dynamic branches, workgroup barriers and cross-lane operations remain unsupported.
The compiler lifts decoded instructions to typed operations and verifies register initialization, supported resource offsets and termination before generating MSL. The initial subset permits only lane-indexed 32-bit buffer accesses against two disjoint buffers with equal lengths. The input is read-only. Each invocation may write only its own output word. The compiler and reference check instruction boundaries, termination placement and buffer bindings throughout the stream. Register initialization and transfer state are checked on the path selected by compile-time known forward scalar branches. Dynamic branches, workgroup barriers and cross-lane operations remain unsupported.
The native backend exposes `NativeCompute::new()` and `run_words(source, entry, input)` for trusted MSL. It binds input at index 0 and output at index 1, dispatches one invocation per word and returns owned readback after completion. `run_words_profiled` returns the same output plus measured library, pipeline, GPU and host durations for the benchmark harness; those timings are single submissions, not distributions. The caller runs generated MSL in a bounded child process. Raw MSL is a trusted developer input. Errors report the operation and backend detail. Across other stages, diagnostics carry a stage, error kind, optional byte offset and human-readable context.
+3 -3
View File
@@ -1,11 +1,11 @@
# Native Metal evidence
Apple's [Metal Feature Set Tables](https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf), dated May 21, 2026, list nonuniform threadgroups starting with Apple4, SIMD permutes starting with Apple6 and SIMD reductions starting with Apple7. The GPU families table maps the M1 series to Apple7. These are class B API capability claims. Xenora checks for Apple7 capabilities at device creation. Earlier native command submission interfaces allow the baseline to run on systems supporting those capabilities without requiring a Metal 4 queue.
Apple's [Metal Feature Set Tables](https://developer.apple.com/metal/Metal-Feature-Set-Tables.pdf), dated October 23, 2026, list nonuniform threadgroups starting with Apple4, SIMD permutes starting with Apple6 and SIMD reductions starting with Apple7. The GPU families table maps the M1 series to Apple7. These are class B API capability claims (CLAIM-METAL-APPLE-FAMILIES). Xenora checks for Apple7 capabilities at device creation. Earlier native command submission interfaces allow the baseline to run on systems supporting those capabilities without requiring a Metal 4 queue.
Apple's [grid sizing guide](https://developer.apple.com/documentation/metal/calculating-threadgroup-and-grid-sizes) describes exact grid sizing through `dispatchThreads` and kernel-specific threadgroup limits. The backend checks the device and compiled pipeline limits before a single 1D dispatch and caps execution at 64 groups of up to 64 threads. The input and output each hold at most 16 KiB. Metal copies the initialized host data into shared storage for each binding. The first CPU readback occurs after command completion and a successful status check. The platform contracts are class B and apply to the native Apple GPU path. [Shared storage](https://developer.apple.com/documentation/metal/choosing-a-resource-storage-mode-for-apple-gpus), [buffer upload](https://developer.apple.com/documentation/metal/mtldevice/makebuffer(bytes:length:options:)), [command completion](https://developer.apple.com/documentation/metal/mtlcommandbuffer/waituntilcompleted()).
Apple's [grid sizing guide](https://developer.apple.com/documentation/metal/calculating-threadgroup-and-grid-sizes) describes exact grid sizing through `dispatchThreads` and kernel-specific threadgroup limits. The backend checks the device and compiled pipeline limits before a single 1D dispatch and caps execution at 64 groups of up to 64 threads. The input and output each hold at most 16 KiB. Metal copies the initialized host data into shared storage for each binding. The first CPU readback occurs after command completion and a successful status check. The platform contracts are class B and apply to the native Apple GPU path (CLAIM-METAL-NATIVE-CONTRACTS). [Shared storage](https://developer.apple.com/documentation/metal/choosing-a-resource-storage-mode-for-apple-gpus), [buffer upload](https://developer.apple.com/documentation/metal/mtldevice/makebuffer(bytes:length:options:)), [command completion](https://developer.apple.com/documentation/metal/mtlcommandbuffer/waituntilcompleted()).
The locally supplied V1 Swift source, artifact `gpu-lab.2gOe22wp/lab.swift`, matched manifest SHA-256 `c9340fc84c080912f5d4919eb7f5adb6dd8b5e5e34146958b7c3f8fb16f81105`. Its compute helper checks the pipeline width, binds shared buffers, submits, waits and checks the command status. Review covered the relevant atomic, reduction, threadgroup, finite FP and offscreen cases. The laboratory's SIMD and numerical outputs have historical scope. The Rust fixtures are original. They use a new test pattern for offscreen rendering, a threadgroup-scoped counter and an integer SIMD reduction with 32 active lanes per group in the tested host configurations.
On 2026-11-22, `CARGO_BUILD_JOBS=2 scripts/test-gpu.sh` passed 12 native cases on the Apple M5 (class A scoped measurements for the tested fixtures). The runtime reported both API and shader validation enabled. The harness checks the shader validation state on each compiled pipeline and reads the CPU-observable result after completion. It checked 131 integer multiplication outputs including a partial final group and all 48 RGBA8 pixels in an offscreen draw. The FP case uses exactly representable finite inputs and expected results and requires bit equality. The render case uses original vertex and fragment MSL and a fixed shared texture. [Metal API validation](https://developer.apple.com/documentation/xcode/validating-your-apps-metal-api-usage), [Metal shader validation](https://developer.apple.com/documentation/xcode/validating-your-apps-metal-shader-usage), [load and store actions](https://developer.apple.com/documentation/metal/setting-load-and-store-actions).
On 2026-11-22, `CARGO_BUILD_JOBS=2 scripts/test-gpu.sh` passed 12 native cases on the Apple M5 (class A, CLAIM-METAL-M5-NATIVE-SUITE). The runtime reported both API and shader validation enabled. The harness checks the shader validation state on each compiled pipeline and reads the CPU-observable result after completion. It checked 131 integer multiplication outputs including a partial final group and all 48 RGBA8 pixels in an offscreen draw. The FP case uses exactly representable finite inputs and expected results and requires bit equality. The render case uses original vertex and fragment MSL and a fixed shared texture. [Metal API validation](https://developer.apple.com/documentation/xcode/validating-your-apps-metal-api-usage), [Metal shader validation](https://developer.apple.com/documentation/xcode/validating-your-apps-metal-shader-usage), [load and store actions](https://developer.apple.com/documentation/metal/setting-load-and-store-actions).
Sources are official Apple references retrieved 2026-11-22 and cited for API semantics. No Apple source code is reproduced. See [host lab intake](host-lab.md) for historical results and outstanding numerical probes.
+1 -1
View File
@@ -16,7 +16,7 @@ AMD §8.1 describes the index, stride, offsets and bounds rules of a hardware
descriptor. Xenora's fixture supplies two bindings in advance under [ADR
0003](../adr/0003-demo-memory-model.md). It does not decode descriptors. AMD
§12.5 defines separate vector-load and vector-store accounting and describes
implicit waits at termination. The accepted wait operands are chosen narrowly
implicit waits at termination (class B, CLAIM-RDNA2-TRANSFER-WAITS). The accepted wait operands are chosen narrowly
for the fixture. AMD §12.7 specifies a uint32 sum with no carry. The VOP3
encoding for this VOP2 operation is described in §12.7.1 and is identified
separately in AMD's XML.
+1 -1
View File
@@ -7,4 +7,4 @@
| R3 | FP32 subnormal outputs can be flushed even with normal inputs. The historic V4 output-only probe reported three signed-zero mismatches. | Historical host observation, pending project reproduction | Metal and testing. Reproduce both signs and the boundary rounding case. |
| R4 | The V3.1 exceptional arithmetic probe reported five subnormal mismatches and a canonical NaN payload. | Historical host observation, pending project reproduction | Compiler and reference. Keep the strict historical comparisons and establish the required guest policy before supporting float lowering. |
| R5 | Redistribution rights for SDK-derived Rust bindings and locked-version attribution require review before distributing linked binaries. | Pinned upstream license notices and maintainer comments | R1. Review the actual linked artifact and applicable terms. |
| R6 | The compiler skips unreachable instructions during verification. The reference also checks termination and the synthetic resource ABI on unreachable code, which can disagree with compiler acceptance. | R2 source inspection | Compiler and reference. Reproduce both cases and agree on a common acceptance policy. |
| R6 | Compiler and reference previously disagreed on skipped early termination and invalid buffer bindings. | R2 analysis and compiler regression tests | Both now check layout and buffer bindings across the stream and execution state on the selected path. Independent candidate review remains open. |
+2 -1
View File
@@ -27,5 +27,6 @@ id = "xbox-execution"
implementation = "unsupported"
correctness = "untested"
hardware_verification = "unverified"
claims = ["CLAIM-XBOX-ISA-ABI"]
architecture = "Xbox Series X|S"
limitations = "The console shader container and launch ABI are unknown."
limitations = "Game execution, proprietary guest containers and full guest execution-mask divergence are unsupported. The console launch ABI is unknown."