From 964026901f47e35c5b3da93ca3991bce7d4e3823 Mon Sep 17 00:00:00 2001 From: elforeign <324243036+elforeign@users.noreply.github.com> Date: Tue, 24 Nov 2026 00:40:55 -0600 Subject: [PATCH] shaders: decode inspected instructions at their stream offset xenora shaders inspect passed each identified instruction to decode() on its own. decode() checks that every branch target lands on an instruction in the stream it was given, and a lone branch has no other instruction to land on, so every supported s_branch and s_cbranch_* was reported as "unsupported operands" (3 of 15 rows in bitwise-branch.bin). Add decode_at(), which decodes one instruction at its real stream offset without the stream-wide target check, and DecodedInstruction::branch_target(). inspect now identifies the whole stream first and checks each branch target against those boundaries, reporting a bad target separately. decode() is rebuilt on decode_at() with unchanged behaviour. Signed-off-by: elforeign <324243036+elforeign@users.noreply.github.com> --- CHANGELOG.md | 2 +- crates/cli/src/shaders.rs | 133 +++++++++++++++++++++++++++----- crates/decoder/src/lib.rs | 59 ++++++++++---- crates/decoder/tests/gfx1030.rs | 28 ++++++- 4 files changed, 184 insertions(+), 38 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ada77dc..0527cfa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,7 +13,7 @@ remains unsupported. - Added complete gfx1030 instruction metadata generated from AMD's public RDNA 2 XML: 1,465 base forms across 21 encoding families with fields, operands, flags and allowed extension words. A committed, normalised snapshot lets `crates/isa/generate_rdna2_meta.py --check` verify the generated table offline; CI runs it. - Added `xenora_isa::meta::identify`, which finds any gfx1030 instruction's form and exact length, including literal, SDWA, DPP and NSA words, and rejects truncated, unassigned and disallowed-extension encodings. It agrees with every LLVM-assembled fixture and with LLVM 23.1.6 on a probe set covering each family and extension word. Identification does not make an instruction executable: 25 forms have semantic decoding. -- Added `xenora shaders coverage [--json]` and `xenora shaders inspect ` for per-family coverage and stream listings that separate decoding failures from unsupported semantics. +- Added `xenora shaders coverage [--json]` and `xenora shaders inspect ` for per-family coverage and stream listings that separate decoding failures from unsupported semantics. Each instruction is decoded at its stream offset and branch targets are checked against the whole stream's boundaries, so supported branches are no longer misreported as unsupported operands. `xenora_decoder::decode_at` decodes a single instruction for such callers. - Added CPU block decoders for BC2, BC3, BC4 and BC5 (UNORM and SNORM) in `xenora-texture`, with tests whose expected texels were derived by hand from the Microsoft and Khronos block-compression specifications. Interpolated values truncate toward zero, as the existing BC1 decoder does; GPU upload and sampling of these formats are not implemented yet. - Added `dbt::tests::sib_store_executes_through_the_native_dbt`, an independent DBT execution test that runs the SIB store form `mov [rsp + 0x20], rbx` through the native ARM64 DBT and diff --git a/crates/cli/src/shaders.rs b/crates/cli/src/shaders.rs index d698d69..e2f2c6c 100644 --- a/crates/cli/src/shaders.rs +++ b/crates/cli/src/shaders.rs @@ -2,7 +2,7 @@ use std::process::ExitCode; -use xenora_decoder::{Architecture, SEMANTIC_FORMS, decode}; +use xenora_decoder::{Architecture, SEMANTIC_FORMS, decode_at}; use xenora_isa::meta::{self, EncodingFamily, FORMS, identify}; const USAGE: &str = "usage: xenora shaders >"; @@ -74,43 +74,134 @@ fn inspect(path: &str) -> ExitCode { return ExitCode::FAILURE; } }; + let listing = listing(&bytes); + for row in &listing.rows { + println!("{row}"); + } + if let Some(failure) = listing.failure { + println!("{failure}"); + return ExitCode::FAILURE; + } + println!( + "{} instructions inspected against {} gfx1030 forms; {} not executable", + listing.rows.len(), + FORMS.len(), + listing.unsupported + ); + ExitCode::SUCCESS +} + +/// The printed rows of `xenora shaders inspect`, the number of rows that do +/// not decode into executable instructions and the identification failure +/// that ended the stream early, if any. +struct Listing { + rows: Vec, + unsupported: usize, + failure: Option, +} + +fn listing(bytes: &[u8]) -> Listing { + let mut listing = Listing { + rows: Vec::new(), + unsupported: 0, + failure: None, + }; + // Identify every instruction first: a branch target is valid only if it + // lands on one of these boundaries, which no single instruction can show. + let mut forms = Vec::new(); let mut offset = 0; - let mut unsupported = 0; - let mut count = 0; while offset < bytes.len() { - let found = match identify(&bytes[offset..]) { - Ok(found) => found, - Err(error) => { - println!("{offset:#06x} decode failure: {error}"); - return ExitCode::FAILURE; + match identify(&bytes[offset..]) { + Ok(found) => { + forms.push((offset, found)); + offset += found.len; } - }; - let words: Vec = bytes[offset..offset + found.len] + Err(error) => { + listing.failure = Some(format!("{offset:#06x} decode failure: {error}")); + break; + } + } + } + let boundary = |target: usize| forms.binary_search_by_key(&target, |form| form.0).is_ok(); + for &(offset, found) in &forms { + let instruction = &bytes[offset..offset + found.len]; + let words: Vec = instruction .chunks(4) .map(|chunk| format!("{:08x}", u32::from_le_bytes(chunk.try_into().unwrap()))) .collect(); - let status = match decode(Architecture::Gfx1030, &bytes[offset..offset + found.len]) { - Ok(_) => "semantic".to_owned(), + let status = match decode_at(Architecture::Gfx1030, &bytes[..offset + found.len], offset) { + Ok(decoded) => match decoded.branch_target() { + Some(target) if !boundary(target) => { + format!("invalid branch target {target:#04x}") + } + _ => "semantic".to_owned(), + }, Err(error) if SEMANTIC_FORMS.contains(&(found.form.name, found.form.family)) => { format!("unsupported operands: {error}") } Err(_) => "unsupported instruction semantics".to_owned(), }; if status != "semantic" { - unsupported += 1; + listing.unsupported += 1; } - println!( + listing.rows.push(format!( "{offset:#06x} {:<8} {:<28} {:<26} {status}", found.form.family.name(), found.form.name.to_ascii_lowercase(), words.join(" ") + )); + } + listing +} + +#[cfg(test)] +mod tests { + use super::listing; + + fn program(words: &[u32]) -> Vec { + words.iter().flat_map(|word| word.to_le_bytes()).collect() + } + + #[test] + fn branches_in_a_valid_program_are_semantic() { + let fixture = include_bytes!("../../../fixtures/rdna2/bitwise-branch.bin"); + let listing = listing(fixture); + assert_eq!(listing.failure, None); + assert_eq!(listing.rows.len(), 15); + let branches: Vec<_> = listing + .rows + .iter() + .filter(|row| row.contains("branch")) + .collect(); + assert_eq!(branches.len(), 3); + for row in &branches { + assert!(row.ends_with(" semantic"), "{row}"); + } + assert_eq!(listing.unsupported, 0); + } + + #[test] + fn branch_targets_are_checked_against_the_whole_stream() { + // s_branch 1 skips one word; s_cbranch_scc0 1 lands inside the + // two-word v_mov_b32 literal form; s_endpgm. + let listing = listing(&program(&[ + 0xbf82_0001, + 0xbf84_0001, + 0x7e04_02ff, + 0x00ff_00ff, + 0xbf81_0000, + ])); + assert_eq!(listing.failure, None); + assert!( + listing.rows[0].ends_with(" semantic"), + "{}", + listing.rows[0] ); - offset += found.len; - count += 1; + assert!( + listing.rows[1].ends_with("invalid branch target 0x0c"), + "{}", + listing.rows[1] + ); + assert_eq!(listing.unsupported, 1); } - println!( - "{count} instructions inspected against {} gfx1030 forms; {unsupported} not executable", - FORMS.len() - ); - ExitCode::SUCCESS } diff --git a/crates/decoder/src/lib.rs b/crates/decoder/src/lib.rs index 9e69655..91d28d3 100644 --- a/crates/decoder/src/lib.rs +++ b/crates/decoder/src/lib.rs @@ -56,6 +56,20 @@ pub struct DecodedInstruction { pub instruction: Instruction, } +impl DecodedInstruction { + /// Destination byte offset of a branch, from the start of the stream. + #[must_use] + pub fn branch_target(&self) -> Option { + match self.instruction { + Instruction::Branch { target } + | Instruction::BranchSccZero { target } + | Instruction::BranchExecZero { target } + | Instruction::BranchVccZero { target } => Some(target), + _ => None, + } + } +} + impl fmt::Display for DecodedInstruction { fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { write!(formatter, "{:04x}: {}", self.offset, self.instruction) @@ -140,26 +154,15 @@ pub fn decode( architecture: Architecture, bytes: &[u8], ) -> Result, DecodeError> { - let decode_instruction = match architecture { - Architecture::Gfx1030 => decode_gfx1030, - }; let mut result = Vec::new(); let mut offset = 0; while offset < bytes.len() { - let (instruction, byte_len) = decode_instruction(&bytes[offset..], offset) - .map_err(|kind| DecodeError { offset, kind })?; - result.push(DecodedInstruction { - offset, - byte_len, - instruction, - }); - offset += usize::from(byte_len); + let decoded = decode_at(architecture, bytes, offset)?; + offset += usize::from(decoded.byte_len); + result.push(decoded); } for decoded in &result { - if let Instruction::Branch { target } - | Instruction::BranchSccZero { target } - | Instruction::BranchExecZero { target } - | Instruction::BranchVccZero { target } = decoded.instruction + if let Some(target) = decoded.branch_target() && result .binary_search_by_key(&target, |item| item.offset) .is_err() @@ -173,6 +176,32 @@ pub fn decode( Ok(result) } +/// Decodes the one instruction that starts at `offset` in `bytes`. Branch +/// targets are stream offsets, but whether they land on an instruction +/// boundary is left to the caller, which knows the rest of the stream. +/// +/// # Errors +/// +/// Returns `offset` with a truncated instruction, unsupported opcode or +/// unsupported form. An `offset` at or past the end is truncated. +pub fn decode_at( + architecture: Architecture, + bytes: &[u8], + offset: usize, +) -> Result { + let decode_instruction = match architecture { + Architecture::Gfx1030 => decode_gfx1030, + }; + let rest = bytes.get(offset..).unwrap_or_default(); + let (instruction, byte_len) = + decode_instruction(rest, offset).map_err(|kind| DecodeError { offset, kind })?; + Ok(DecodedInstruction { + offset, + byte_len, + instruction, + }) +} + fn word(bytes: &[u8], end: u8) -> Result { let end_index = usize::from(end); let Some(word) = bytes diff --git a/crates/decoder/tests/gfx1030.rs b/crates/decoder/tests/gfx1030.rs index fcc8905..4e56797 100644 --- a/crates/decoder/tests/gfx1030.rs +++ b/crates/decoder/tests/gfx1030.rs @@ -4,7 +4,7 @@ use std::process::{Command, Stdio}; use xenora_decoder::{ Architecture, DecodeError, DecodeErrorKind, DecodedInstruction, Instruction, ScalarSource, - VectorSource, decode, + VectorSource, decode, decode_at, }; use xenora_ref::{BranchCondition, Op, Source, VectorAlu}; @@ -786,3 +786,29 @@ fn accepts_scalar_destination_105_and_vgpr_zero_add_sources() { } ); } + +#[test] +fn decode_at_resolves_branch_targets_from_the_stream_offset() { + let decoded = decode_at(Architecture::Gfx1030, BITWISE_FIXTURE, 0x1c).unwrap(); + assert_eq!(decoded.offset, 0x1c); + assert_eq!(decoded.byte_len, 4); + assert_eq!(decoded.branch_target(), Some(0x3c)); + // Alone, the same branch still reports its stream target; only the whole + // stream can say whether that target is an instruction boundary. + let isolated = decode_at(Architecture::Gfx1030, &BITWISE_FIXTURE[..0x20], 0x1c).unwrap(); + assert_eq!(isolated.branch_target(), Some(0x3c)); + assert_eq!( + decode_at( + Architecture::Gfx1030, + BITWISE_FIXTURE, + BITWISE_FIXTURE.len() + ), + Err(DecodeError { + offset: BITWISE_FIXTURE.len(), + kind: DecodeErrorKind::Truncated { + needed: 4, + available: 0 + }, + }) + ); +}