diff --git a/CHANGELOG.md b/CHANGELOG.md index 16ee66a..8ad5f50 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,7 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game remains unsupported. ### Added +- `dxbc-accc` parses a synthetic FSPX section table inside DXBC `ACCC` chunks (section descriptors, section 1 stage configuration using the `bx_shader_stage_t` values, and section 6 RDNA 2 code bounds) and returns a parse error for truncated or out-of-range input instead of panicking. It exports `bx_shader_inspect`, `bx_shader_prepare_for_d3dmetal`, and `bx_shader_free_buffer` with the layouts in `abi/include/bx_shader_bridge.h`. `bx_shader_inspect` fills that struct without logging. `bx_shader_prepare_for_d3dmetal` copies the `container_size` prefix, including when a DXIL container also has a malformed FSPX table. ACCC-only input returns `BX_SHADER_ERR_UNSUPPORTED` and writes one stderr inspection line; a failed stderr write does not panic. RDNA 2 bytes are not translated to DXIL. The section layout is synthetic and is not a console container specification or an Xbox hardware result (#416). - Added Section 0 (`First-Time Contributor Onboarding`) to `AGENTS.md` (`CLAUDE.md` symlink) giving coding agents a turnkey step-by-step onboarding flow (preflight, `bx-cli doctor`, unclaimed `status: ready` issue discovery, claiming, scoped implementation, local verification including hosts without CrossOver, DCO commit, and PR CI watching). - Overhauled the repository into a clean 6-track parallel hybrid workspace (Milestone M0) designed for 5–8+ concurrent contributors and coding agents: added frozen cross-DLL ABI headers and canonical `.def` export tables (`abi/`), native ARM64 Rust workspace (`launcher/crates/{bx-cli,bx-probe,bx-telemetry}` with `env_clear()` child environment isolation, and `shader-transpiler/crates/dxbc-accc`), CMake + `mingw-w64` superbuild (`shims/`, `scripts/build-shims.sh`) producing 16 standalone x86-64 PE32+ shim DLLs (`bx_runtime_veh.dll` with working `clwb` VEH trap and JSONL logger, `xmem.dll`, `XCRDAPI.dll`, `d3d12_xs.dll`, `xg_xs.dll`, `xgameruntime.dll`, `GameInput.dll`, `AcpHal.dll`, `xapu.dll`, `chad.dll`, and PSM/ntuser forwarders) with strict PE Export Directory verification (exact names, ordinals, forwarders, zero extra exports, zero dynamic MinGW runtime dependencies), auto-discovered synthetic PE32+ conformance tests (`tests/conformance/`), `.github/workflows/hybrid-ci.yml`, `.github/ISSUE_TEMPLATE/track-handoff.yml`, `docs/adr/0006-retire-in-tree-native-workspace.md`, `docs/architecture/parallel-tracks.md`, and `docs/issues/wave-1-backlog.md`. Unified `docs/roadmap.md`, `CONTRIBUTING.md`, `AGENTS.md`, `README.md`, and `.github/CODEOWNERS` (retaining global `* @MacosPorters/maintainers` fallback and full provenance/independent-verification rules). Verified locally on Apple M5 (macOS 27.2.1, CrossOver 26.3, Rosetta 2) with all Rust checks, strict 16-DLL export verification, and live `test_veh_clwb.exe` + `test_shim_exports.exe` smoke tests passing. - Documented the original Windows workload set and Phase 1 hybrid measurement protocol (#353), including receipt-field sources, percentile definitions, negative controls and independent reproduction requirements. The protocol identifies the unmerged runner candidate and its missing raw traces and measurements; it adds no execution or compatibility claim. diff --git a/shader-transpiler/crates/dxbc-accc/Cargo.toml b/shader-transpiler/crates/dxbc-accc/Cargo.toml index e7a35c6..09942f8 100644 --- a/shader-transpiler/crates/dxbc-accc/Cargo.toml +++ b/shader-transpiler/crates/dxbc-accc/Cargo.toml @@ -5,5 +5,8 @@ edition.workspace = true license.workspace = true rust-version.workspace = true +[lib] +crate-type = ["rlib", "cdylib"] + [lints] workspace = true diff --git a/shader-transpiler/crates/dxbc-accc/src/c_abi.rs b/shader-transpiler/crates/dxbc-accc/src/c_abi.rs new file mode 100644 index 0000000..3da9d35 --- /dev/null +++ b/shader-transpiler/crates/dxbc-accc/src/c_abi.rs @@ -0,0 +1,421 @@ +//! C ABI entry points from `abi/include/bx_shader_bridge.h`. +//! +//! `bx_shader_inspect` classifies a blob and fills `bx_shader_inspection_t` +//! without logging or retaining chunk lists. `bx_shader_prepare_for_d3dmetal` +//! copies `container_size` bytes when the container has a `DXIL` chunk, even +//! if an `FSPX` table in the same container is malformed. It returns +//! `BX_SHADER_ERR_UNSUPPORTED` for ACCC-only input and writes that inspection +//! record to stderr. Other statuses are not logged. RDNA 2 to DXIL translation +//! is not implemented. `bx_shader_free_buffer` releases a buffer returned by +//! prepare. +//! +//! The shim logger `bx_log_emit` (declared in `abi/include/bx_log.h`) is +//! provided by `bx_runtime_veh.dll`. This crate does not link that DLL. A +//! failed stderr write is ignored so it cannot abort the host. + +use std::alloc::{Layout, alloc, dealloc}; +#[cfg(test)] +use std::cell::RefCell; +use std::io::Write; +use std::panic::{AssertUnwindSafe, catch_unwind}; +use std::ptr; + +use super::{ + DxbcSummary, ShaderInspection, ShaderKind, ShaderStage, dxil_container_len, inspect_dxbc, + summarize_dxbc, +}; + +pub const BX_SHADER_OK: i32 = 0; +pub const BX_SHADER_ERR_INVALID_BLOB: i32 = 1; +pub const BX_SHADER_ERR_UNSUPPORTED: i32 = 2; +pub const BX_SHADER_ERR_TRANSLATE: i32 = 3; +pub const BX_SHADER_ERR_OOM: i32 = 4; + +const _: () = { + assert!(BX_SHADER_OK == 0); + assert!(BX_SHADER_ERR_INVALID_BLOB == 1); + assert!(BX_SHADER_ERR_UNSUPPORTED == 2); + assert!(BX_SHADER_ERR_TRANSLATE == 3); + assert!(BX_SHADER_ERR_OOM == 4); +}; + +/// Rust layout of `bx_shader_inspection_t`. +/// +/// The frozen header uses C enums, which are 4-byte `int` values on the +/// mingw-w64 and Apple targets this ABI is written for, then six `uint32_t` +/// fields and a 16-byte digest. The struct is 48 bytes with 4-byte alignment. +#[repr(C)] +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub struct BxShaderInspection { + pub kind: i32, + pub stage: i32, + pub shader_model_major: u32, + pub shader_model_minor: u32, + pub container_size: u32, + pub dxil_chunk_size: u32, + pub accc_chunk_size: u32, + pub has_root_signature: u32, + pub digest_hash: [u8; 16], +} + +const _: () = { + assert!(std::mem::size_of::() == 48); + assert!(std::mem::align_of::() == 4); + assert!(std::mem::offset_of!(BxShaderInspection, kind) == 0); + assert!(std::mem::offset_of!(BxShaderInspection, stage) == 4); + assert!(std::mem::offset_of!(BxShaderInspection, shader_model_major) == 8); + assert!(std::mem::offset_of!(BxShaderInspection, shader_model_minor) == 12); + assert!(std::mem::offset_of!(BxShaderInspection, container_size) == 16); + assert!(std::mem::offset_of!(BxShaderInspection, dxil_chunk_size) == 20); + assert!(std::mem::offset_of!(BxShaderInspection, accc_chunk_size) == 24); + assert!(std::mem::offset_of!(BxShaderInspection, has_root_signature) == 28); + assert!(std::mem::offset_of!(BxShaderInspection, digest_hash) == 32); +}; + +#[cfg(test)] +thread_local! { + static SHADER_LOG: RefCell> = const { RefCell::new(Vec::new()) }; +} + +#[cfg(test)] +pub(crate) fn clear_shader_log() { + SHADER_LOG.with(|log| log.borrow_mut().clear()); +} + +#[cfg(test)] +pub(crate) fn shader_log_lines() -> Vec { + SHADER_LOG.with(|log| log.borrow().clone()) +} + +fn emit(line: String) { + let _ = writeln!(std::io::stderr().lock(), "{line}"); + #[cfg(test)] + SHADER_LOG.with(|log| log.borrow_mut().push(line)); +} + +fn kind_name(kind: ShaderKind) -> &'static str { + match kind { + ShaderKind::Unknown => "unknown", + ShaderKind::Dxil => "dxil", + ShaderKind::LegacyDxbc => "legacy_dxbc", + ShaderKind::AcccOnly => "accc_only", + ShaderKind::DualDxilAndAccc => "dual", + } +} + +fn stage_name(stage: ShaderStage) -> &'static str { + match stage { + ShaderStage::Unknown => "unknown", + ShaderStage::Pixel => "pixel", + ShaderStage::Vertex => "vertex", + ShaderStage::Geometry => "geometry", + ShaderStage::Hull => "hull", + ShaderStage::Domain => "domain", + ShaderStage::Compute => "compute", + ShaderStage::Library => "library", + ShaderStage::Mesh => "mesh", + ShaderStage::Amplification => "amplification", + } +} + +fn abi_kind(kind: ShaderKind) -> i32 { + match kind { + ShaderKind::Unknown => 0, + ShaderKind::Dxil => 1, + ShaderKind::LegacyDxbc => 2, + ShaderKind::AcccOnly => 3, + ShaderKind::DualDxilAndAccc => 4, + } +} + +fn abi_stage(stage: ShaderStage) -> i32 { + match stage { + ShaderStage::Unknown => 0, + ShaderStage::Pixel => 1, + ShaderStage::Vertex => 2, + ShaderStage::Geometry => 3, + ShaderStage::Hull => 4, + ShaderStage::Domain => 5, + ShaderStage::Compute => 6, + ShaderStage::Library => 7, + ShaderStage::Mesh => 8, + ShaderStage::Amplification => 9, + } +} + +fn hex_digest(bytes: &[u8; 16]) -> String { + const HEX: &[u8; 16] = b"0123456789abcdef"; + let mut out = String::with_capacity(32); + for byte in bytes { + out.push(HEX[usize::from(byte >> 4)] as char); + out.push(HEX[usize::from(byte & 0x0f)] as char); + } + out +} + +fn format_inspection(event: &str, status: &str, detail: &str, info: &ShaderInspection) -> String { + let (fspx, version, sections, rdna_off, rdna_size) = if let Some(fspx) = &info.fspx { + let sections = if fspx.sections.is_empty() { + "none".to_string() + } else { + fspx.sections + .iter() + .map(|section| format!("{}@{}+{}", section.id, section.offset, section.size)) + .collect::>() + .join(",") + }; + let (rdna_off, rdna_size) = match fspx.rdna_code { + Some(code) => (code.offset.to_string(), code.size.to_string()), + None => ("none".to_string(), "none".to_string()), + }; + ("1", fspx.version.to_string(), sections, rdna_off, rdna_size) + } else { + ( + "0", + "none".to_string(), + "none".to_string(), + "none".to_string(), + "none".to_string(), + ) + }; + format!( + "bx-shader event={event} status={status} detail={detail} kind={}({}) stage={}({}) sm_major={} sm_minor={} container_size={} dxil_chunk_size={} accc_chunk_size={} has_root_signature={} digest={} fspx={fspx} fspx_version={version} sections={sections} rdna_off={rdna_off} rdna_size={rdna_size}", + kind_name(info.kind), + abi_kind(info.kind), + stage_name(info.stage), + abi_stage(info.stage), + info.shader_model_major, + info.shader_model_minor, + info.container_size, + info.dxil_size, + info.accc_size, + u32::from(info.has_root_signature), + hex_digest(&info.digest), + ) +} + +fn log_accc_unsupported(info: &ShaderInspection) { + emit(format_inspection( + "prepare", + "unsupported", + "no_dxil_passthrough", + info, + )); +} + +fn to_c_inspection(info: &DxbcSummary) -> BxShaderInspection { + BxShaderInspection { + kind: abi_kind(info.kind), + stage: abi_stage(info.stage), + shader_model_major: u32::from(info.shader_model_major), + shader_model_minor: u32::from(info.shader_model_minor), + container_size: info.container_size, + dxil_chunk_size: info.dxil_size, + accc_chunk_size: info.accc_size, + has_root_signature: u32::from(info.has_root_signature), + digest_hash: info.digest, + } +} + +fn input_bytes<'a>(bytes: *const u8, len: usize) -> Option<&'a [u8]> { + if len == 0 { + return Some(&[]); + } + if bytes.is_null() { + return None; + } + // SAFETY: The caller of the unsafe entry point guarantees `bytes` is + // readable for `len` bytes when it is non-null. `len` is non-zero here. + Some(unsafe { std::slice::from_raw_parts(bytes, len) }) +} + +fn alloc_copy(src: &[u8]) -> Result<*mut u8, ()> { + if src.is_empty() { + return Err(()); + } + let layout = Layout::from_size_align(src.len(), 1).map_err(|_| ())?; + // SAFETY: `layout` has a non-zero size and alignment 1. + let ptr = unsafe { alloc(layout) }; + if ptr.is_null() { + return Err(()); + } + // SAFETY: `alloc` returned a writable block of `src.len()` bytes, and + // `src` is a valid readable region of that length. The regions do not + // overlap. + unsafe { + ptr::copy_nonoverlapping(src.as_ptr(), ptr, src.len()); + } + Ok(ptr) +} + +fn guard(body: impl FnOnce() -> i32 + std::panic::UnwindSafe) -> i32 { + match catch_unwind(body) { + Ok(status) => status, + Err(_) => BX_SHADER_ERR_INVALID_BLOB, + } +} + +fn inspect_status(bytes: *const u8, len: usize, out_info: *mut BxShaderInspection) -> i32 { + if out_info.is_null() { + return BX_SHADER_ERR_INVALID_BLOB; + } + let Some(bytes) = input_bytes(bytes, len) else { + // SAFETY: `out_info` was checked non-null and the caller guarantees it + // is writable for one `BxShaderInspection`. + unsafe { out_info.write(BxShaderInspection::default()) }; + return BX_SHADER_ERR_INVALID_BLOB; + }; + match summarize_dxbc(bytes) { + Ok(info) => { + let c_info = to_c_inspection(&info); + // SAFETY: `out_info` is non-null and writable for one inspection. + unsafe { out_info.write(c_info) }; + BX_SHADER_OK + } + Err(_) => { + // SAFETY: `out_info` is non-null and writable for one inspection. + unsafe { out_info.write(BxShaderInspection::default()) }; + BX_SHADER_ERR_INVALID_BLOB + } + } +} + +fn prepare_status( + in_bytes: *const u8, + in_len: usize, + out_bytes: *mut *mut u8, + out_len: *mut usize, +) -> i32 { + if out_bytes.is_null() || out_len.is_null() { + return BX_SHADER_ERR_INVALID_BLOB; + } + // SAFETY: both pointers were checked non-null and the caller guarantees + // they are writable. + unsafe { + *out_bytes = ptr::null_mut(); + *out_len = 0; + } + let Some(bytes) = input_bytes(in_bytes, in_len) else { + return BX_SHADER_ERR_INVALID_BLOB; + }; + let container_size = match dxil_container_len(bytes) { + Ok(Some(size)) => size, + Ok(None) => { + return match inspect_dxbc(bytes) { + Ok(info) if info.kind == ShaderKind::AcccOnly => { + log_accc_unsupported(&info); + BX_SHADER_ERR_UNSUPPORTED + } + Ok(_) => BX_SHADER_ERR_UNSUPPORTED, + Err(_) => BX_SHADER_ERR_INVALID_BLOB, + }; + } + Err(_) => return BX_SHADER_ERR_INVALID_BLOB, + }; + let Some(len) = usize::try_from(container_size).ok() else { + return BX_SHADER_ERR_INVALID_BLOB; + }; + if len == 0 || len > bytes.len() { + return BX_SHADER_ERR_INVALID_BLOB; + } + let ptr = match alloc_copy(&bytes[..len]) { + Ok(ptr) => ptr, + Err(()) => return BX_SHADER_ERR_OOM, + }; + // SAFETY: `out_bytes` and `out_len` are non-null and writable. `len` is + // the container size, which is not larger than `bytes`. + unsafe { + *out_bytes = ptr; + *out_len = len; + } + BX_SHADER_OK +} + +/// Inspect `bytes` without allocating. +/// +/// # Safety +/// +/// When `bytes` is non-null it must be readable for `len` bytes. A null +/// `bytes` pointer is not dereferenced. `out_info` must be non-null and +/// writable; a null `out_info` returns [`BX_SHADER_ERR_INVALID_BLOB`]. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn bx_shader_inspect( + bytes: *const u8, + len: usize, + out_info: *mut BxShaderInspection, +) -> i32 { + let status = guard(AssertUnwindSafe(|| inspect_status(bytes, len, out_info))); + if status == BX_SHADER_ERR_INVALID_BLOB && !out_info.is_null() { + // SAFETY: a non-null `out_info` is writable for one inspection. This + // also covers a panic after a partial write. + unsafe { out_info.write(BxShaderInspection::default()) }; + } + status +} + +/// Copy a DXIL container, or report that an ACCC-only container cannot be +/// prepared for D3DMetal. +/// +/// On [`BX_SHADER_OK`], `*out_bytes` is a copy of the first `container_size` +/// bytes and `*out_len` is that size. Bytes past `container_size` are not +/// copied. A `DXIL` chunk is copied even when an `FSPX` table in the same +/// container is malformed. The caller frees the pointer with +/// [`bx_shader_free_buffer`]. On every other status, `*out_bytes` is null and +/// `*out_len` is 0 when the output pointers are non-null. +/// +/// # Safety +/// +/// When `in_bytes` is non-null it must be readable for `in_len` bytes. +/// `out_bytes` and `out_len` must both be non-null and writable. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn bx_shader_prepare_for_d3dmetal( + in_bytes: *const u8, + in_len: usize, + out_bytes: *mut *mut u8, + out_len: *mut usize, +) -> i32 { + let status = guard(AssertUnwindSafe(|| { + prepare_status(in_bytes, in_len, out_bytes, out_len) + })); + if status != BX_SHADER_OK && !out_bytes.is_null() && !out_len.is_null() { + // SAFETY: the caller guarantees both pointers are writable. A panic + // after publication drops the copy instead of returning it. + unsafe { + let ptr = *out_bytes; + let len = *out_len; + *out_bytes = ptr::null_mut(); + *out_len = 0; + if !ptr.is_null() && len > 0 { + free_buffer(ptr, len); + } + } + } + status +} + +fn free_buffer(ptr: *mut u8, len: usize) { + if ptr.is_null() || len == 0 { + return; + } + let Ok(layout) = Layout::from_size_align(len, 1) else { + return; + }; + // SAFETY: The caller guarantees `ptr` was allocated by `alloc_copy` with + // this layout (size `len`, alignment 1) and has not been freed. + unsafe { dealloc(ptr, layout) }; +} + +/// Free a buffer allocated by [`bx_shader_prepare_for_d3dmetal`]. +/// +/// A null `ptr` or a `len` of 0 is a no-op. `len` must be the length returned +/// in `out_len` for that pointer. The allocation uses alignment 1. +/// +/// # Safety +/// +/// When `ptr` is non-null and `len` is non-zero, `ptr` must have been returned +/// by [`bx_shader_prepare_for_d3dmetal`] and `len` must be the matching length. +/// The pointer must not be freed twice. +#[unsafe(no_mangle)] +pub unsafe extern "C" fn bx_shader_free_buffer(ptr: *mut u8, len: usize) { + let _ = catch_unwind(AssertUnwindSafe(|| free_buffer(ptr, len))); +} diff --git a/shader-transpiler/crates/dxbc-accc/src/fspx.rs b/shader-transpiler/crates/dxbc-accc/src/fspx.rs new file mode 100644 index 0000000..2a137ba --- /dev/null +++ b/shader-transpiler/crates/dxbc-accc/src/fspx.rs @@ -0,0 +1,297 @@ +//! Synthetic `FSPX` section table carried inside an `ACCC` chunk payload. +//! +//! This is BetterXen's clean-room layout for synthetic blobs and for inputs +//! that adopt the same layout. It is not a description of a console compiler's +//! on-disk format. A successful parse does not mean the bytes are RDNA 2 +//! machine code from any particular GPU, and it is not Xbox hardware +//! verification. Section 6 is a byte range only; this module does not +//! disassemble it. + +use super::{ShaderStage, read_u32_le}; + +/// One bounds-checked section descriptor. +/// +/// `offset` is relative to the first byte of the `FSPX` payload (the `FSPX` +/// magic), not relative to the enclosing DXBC container. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct FspxSection { + pub id: u32, + pub offset: u32, + pub size: u32, +} + +/// Section 1, the shader stage configuration. +/// +/// `stage` uses the `bx_shader_stage_t` numbering from +/// `abi/include/bx_shader_bridge.h`: 0 unknown, 1 pixel, 2 vertex, 3 geometry, +/// 4 hull, 5 domain, 6 compute, 7 library, 8 mesh, 9 amplification. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct FspxStageConfig { + pub offset: u32, + pub size: u32, + pub stage: ShaderStage, + pub shader_model_major: u8, + pub shader_model_minor: u8, +} + +/// Section 6, the RDNA 2 code byte range inside the `FSPX` payload. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct FspxCodeBounds { + pub offset: u32, + pub size: u32, +} + +/// A parsed synthetic `FSPX` table. +/// +/// Version 0 is the magic-only stub: `section_count` must be 0 and no section +/// bytes are read. Version 1 is the section table. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct FspxInfo { + pub version: u32, + pub flags: u32, + pub sections: Vec, + pub section0: Option, + pub stage_config: Option, + pub rdna_code: Option, + pub section7: Option, +} + +impl FspxInfo { + /// Return the section 6 bytes, or `None` when the recorded bounds do not + /// fit in `fspx_payload`. + pub fn rdna_code_bytes<'a>(&self, fspx_payload: &'a [u8]) -> Option<&'a [u8]> { + let code = self.rdna_code.as_ref()?; + let start = code.offset as usize; + let end = start.checked_add(code.size as usize)?; + fspx_payload.get(start..end) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(crate) enum FspxError { + Truncated, + BadVersion(u32), + SectionOutOfBounds { section_id: u32 }, + DuplicateSection { section_id: u32 }, + Overlap { section_id: u32 }, + BadStageConfig, +} + +const HEADER_LEN: usize = 16; +const DESCRIPTOR_LEN: usize = 12; +const STAGE_CONFIG_LEN: usize = 12; + +fn stage_from_abi(raw: u32) -> Option { + Some(match raw { + 0 => ShaderStage::Unknown, + 1 => ShaderStage::Pixel, + 2 => ShaderStage::Vertex, + 3 => ShaderStage::Geometry, + 4 => ShaderStage::Hull, + 5 => ShaderStage::Domain, + 6 => ShaderStage::Compute, + 7 => ShaderStage::Library, + 8 => ShaderStage::Mesh, + 9 => ShaderStage::Amplification, + _ => return None, + }) +} + +fn section_end(offset: u32, size: u32, table_end: usize, payload_len: usize) -> Option { + let start = usize::try_from(offset).ok()?; + let len = usize::try_from(size).ok()?; + let end = start.checked_add(len)?; + if start < table_end || end > payload_len { + return None; + } + Some(end) +} + +fn ranges_overlap(a_off: u32, a_size: u32, b_off: u32, b_size: u32) -> bool { + let a0 = u64::from(a_off); + let a1 = a0 + u64::from(a_size); + let b0 = u64::from(b_off); + let b1 = b0 + u64::from(b_size); + a0 < b1 && b0 < a1 +} + +fn stage_from_body(body: &[u8]) -> Result<(ShaderStage, u8, u8), FspxError> { + if body.len() != STAGE_CONFIG_LEN { + return Err(FspxError::BadStageConfig); + } + let stage_raw = read_u32_le(body, 0).ok_or(FspxError::BadStageConfig)?; + let major = read_u32_le(body, 4).ok_or(FspxError::BadStageConfig)?; + let minor = read_u32_le(body, 8).ok_or(FspxError::BadStageConfig)?; + let stage = stage_from_abi(stage_raw).ok_or(FspxError::BadStageConfig)?; + let shader_model_major = u8::try_from(major).map_err(|_| FspxError::BadStageConfig)?; + let shader_model_minor = u8::try_from(minor).map_err(|_| FspxError::BadStageConfig)?; + Ok((stage, shader_model_major, shader_model_minor)) +} + +fn descriptor_at(payload: &[u8], index: usize) -> Result<(u32, u32, u32), FspxError> { + let at = HEADER_LEN + .checked_add( + index + .checked_mul(DESCRIPTOR_LEN) + .ok_or(FspxError::Truncated)?, + ) + .ok_or(FspxError::Truncated)?; + let id = read_u32_le(payload, at).ok_or(FspxError::Truncated)?; + let offset = read_u32_le(payload, at + 4).ok_or(FspxError::Truncated)?; + let size = read_u32_le(payload, at + 8).ok_or(FspxError::Truncated)?; + Ok((id, offset, size)) +} + +struct FspxHeader { + version: u32, + flags: u32, + count: usize, + table_end: usize, +} + +/// `Ok(None)` when the payload does not start with `FSPX`. +fn read_fspx_header(payload: &[u8]) -> Result, FspxError> { + if payload.get(..4) != Some(b"FSPX".as_slice()) { + return Ok(None); + } + if payload.len() < HEADER_LEN { + return Err(FspxError::Truncated); + } + let version = read_u32_le(payload, 4).ok_or(FspxError::Truncated)?; + let section_count = read_u32_le(payload, 8).ok_or(FspxError::Truncated)?; + let flags = read_u32_le(payload, 12).ok_or(FspxError::Truncated)?; + if version == 0 { + if section_count != 0 { + return Err(FspxError::BadVersion(0)); + } + return Ok(Some(FspxHeader { + version, + flags, + count: 0, + table_end: HEADER_LEN, + })); + } + if version != 1 { + return Err(FspxError::BadVersion(version)); + } + let count = usize::try_from(section_count).map_err(|_| FspxError::Truncated)?; + let table_bytes = count + .checked_mul(DESCRIPTOR_LEN) + .ok_or(FspxError::Truncated)?; + let table_end = HEADER_LEN + .checked_add(table_bytes) + .ok_or(FspxError::Truncated)?; + if table_end > payload.len() { + return Err(FspxError::Truncated); + } + Ok(Some(FspxHeader { + version, + flags, + count, + table_end, + })) +} + +/// Validate every descriptor by re-reading earlier ones from `payload`. +/// +/// The check does not allocate. `on_section` receives the section bytes. +fn walk_sections( + payload: &[u8], + header: &FspxHeader, + mut on_section: impl FnMut(FspxSection, &[u8]) -> Result<(), FspxError>, +) -> Result<(), FspxError> { + for index in 0..header.count { + let (id, offset, size) = descriptor_at(payload, index)?; + let end = section_end(offset, size, header.table_end, payload.len()) + .ok_or(FspxError::SectionOutOfBounds { section_id: id })?; + for prev in 0..index { + let (prev_id, prev_off, prev_size) = descriptor_at(payload, prev)?; + if prev_id == id { + return Err(FspxError::DuplicateSection { section_id: id }); + } + if ranges_overlap(prev_off, prev_size, offset, size) { + return Err(FspxError::Overlap { section_id: id }); + } + } + let start = usize::try_from(offset) + .map_err(|_| FspxError::SectionOutOfBounds { section_id: id })?; + let body = payload + .get(start..end) + .ok_or(FspxError::SectionOutOfBounds { section_id: id })?; + on_section(FspxSection { id, offset, size }, body)?; + } + Ok(()) +} + +/// Stage word from a version-1 table, without retaining the section list. +/// +/// `Ok(None)` means the payload is not `FSPX`. `Ok(Some(scan))` is a +/// magic-only stub or a valid table. `scan.stage` is set only when section 1 +/// is present. +pub(crate) struct FspxStageScan { + pub stage: Option<(ShaderStage, u8, u8)>, +} + +pub(crate) fn scan_fspx(payload: &[u8]) -> Result, FspxError> { + let Some(header) = read_fspx_header(payload)? else { + return Ok(None); + }; + let mut stage = None; + walk_sections(payload, &header, |section, body| { + if section.id == 1 { + stage = Some(stage_from_body(body)?); + } + Ok(()) + })?; + Ok(Some(FspxStageScan { stage })) +} + +/// Parse an `ACCC` payload. +/// +/// `Ok(None)` means the payload does not start with `FSPX`. `Ok(Some(_))` is a +/// magic-only stub or a complete section table. Malformed `FSPX` bytes are +/// `Err` and never panic. +pub(crate) fn parse_fspx(payload: &[u8]) -> Result, FspxError> { + let Some(header) = read_fspx_header(payload)? else { + return Ok(None); + }; + let mut sections = Vec::new(); + let mut section0 = None; + let mut stage_config = None; + let mut rdna_code = None; + let mut section7 = None; + walk_sections(payload, &header, |section, body| { + match section.id { + 0 => section0 = Some(section), + 1 => { + let (stage, shader_model_major, shader_model_minor) = stage_from_body(body)?; + stage_config = Some(FspxStageConfig { + offset: section.offset, + size: section.size, + stage, + shader_model_major, + shader_model_minor, + }); + } + 6 => { + rdna_code = Some(FspxCodeBounds { + offset: section.offset, + size: section.size, + }); + } + 7 => section7 = Some(section), + _ => {} + } + sections.push(section); + Ok(()) + })?; + Ok(Some(FspxInfo { + version: header.version, + flags: header.flags, + sections, + section0, + stage_config, + rdna_code, + section7, + })) +} diff --git a/shader-transpiler/crates/dxbc-accc/src/lib.rs b/shader-transpiler/crates/dxbc-accc/src/lib.rs index 8882b9f..65f330f 100644 --- a/shader-transpiler/crates/dxbc-accc/src/lib.rs +++ b/shader-transpiler/crates/dxbc-accc/src/lib.rs @@ -3,9 +3,35 @@ //! Parses standard DirectX `DXBC` containers to classify whether an incoming shader //! blob contains standard `DXIL` (fast path to D3DMetal 3.0), legacy `SHDR`/`SHEX`, //! or console-compiled `ACCC` (`FSPX`) AMD RDNA 2 machine code. +//! +//! # Synthetic FSPX section table +//! +//! An `ACCC` payload that begins with `FSPX` uses the layout documented on +//! [`fspx`]. Version 0 is a magic-only stub. Version 1 is a section table. +//! Section 0 and section 7 are opaque header ranges, section 1 is the stage +//! configuration (`bx_shader_stage_t` values), and section 6 is the RDNA 2 +//! code byte range. The code bytes are not decoded. This layout is synthetic. +//! Parsing it does not establish that a console compiler produced the blob +//! and is not Xbox hardware verification. +//! +//! The C entry points in [`c_abi`] match `abi/include/bx_shader_bridge.h`. +//! `bx_shader_inspect` fills the C struct without logging. `bx_shader_prepare_for_d3dmetal` +//! copies `container_size` bytes when a `DXIL` chunk is present, including when +//! an accompanying `FSPX` table is malformed, and logs only an ACCC-only +//! `BX_SHADER_ERR_UNSUPPORTED` result. RDNA 2 to DXIL translation is not implemented. + +mod c_abi; +mod fspx; use std::fmt; +pub use c_abi::{ + BX_SHADER_ERR_INVALID_BLOB, BX_SHADER_ERR_OOM, BX_SHADER_ERR_TRANSLATE, + BX_SHADER_ERR_UNSUPPORTED, BX_SHADER_OK, BxShaderInspection, bx_shader_free_buffer, + bx_shader_inspect, bx_shader_prepare_for_d3dmetal, +}; +pub use fspx::{FspxCodeBounds, FspxInfo, FspxSection, FspxStageConfig}; + #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum ShaderKind { Unknown, @@ -48,6 +74,9 @@ pub struct ShaderInspection { pub dxil_size: u32, pub accc_size: u32, pub accc_is_fspx: bool, + /// The first well-formed `FSPX` table in the container, if any. + /// `accc_size` remains the payload size of the last `ACCC` chunk. + pub fspx: Option, pub chunks: Vec, } @@ -58,6 +87,13 @@ pub enum ParseError { UnsupportedVersion(u32), TruncatedChunkTable, ChunkOutOfBounds { index: usize }, + TruncatedContainer, + FspxTruncated { chunk: usize }, + FspxBadVersion { chunk: usize, version: u32 }, + FspxSectionOutOfBounds { chunk: usize, section_id: u32 }, + FspxDuplicateSection { chunk: usize, section_id: u32 }, + FspxSectionOverlap { chunk: usize, section_id: u32 }, + FspxBadStageConfig { chunk: usize }, } impl fmt::Display for ParseError { @@ -68,13 +104,35 @@ impl fmt::Display for ParseError { Self::UnsupportedVersion(v) => write!(f, "unsupported DXBC version {v}"), Self::TruncatedChunkTable => write!(f, "chunk offset table exceeds buffer"), Self::ChunkOutOfBounds { index } => write!(f, "chunk {index} out of bounds"), + Self::TruncatedContainer => write!(f, "DXBC container size is outside the buffer"), + Self::FspxTruncated { chunk } => { + write!(f, "FSPX section table truncated in chunk {chunk}") + } + Self::FspxBadVersion { chunk, version } => { + write!(f, "unsupported FSPX version {version} in chunk {chunk}") + } + Self::FspxSectionOutOfBounds { chunk, section_id } => { + write!( + f, + "FSPX section {section_id} out of bounds in chunk {chunk}" + ) + } + Self::FspxDuplicateSection { chunk, section_id } => { + write!(f, "duplicate FSPX section {section_id} in chunk {chunk}") + } + Self::FspxSectionOverlap { chunk, section_id } => { + write!(f, "overlapping FSPX section {section_id} in chunk {chunk}") + } + Self::FspxBadStageConfig { chunk } => { + write!(f, "malformed FSPX stage configuration in chunk {chunk}") + } } } } impl std::error::Error for ParseError {} -fn read_u32_le(bytes: &[u8], off: usize) -> Option { +pub(crate) fn read_u32_le(bytes: &[u8], off: usize) -> Option { let slice = bytes.get(off..off + 4)?; Some(u32::from_le_bytes([slice[0], slice[1], slice[2], slice[3]])) } @@ -94,36 +152,231 @@ fn decode_stage(program_type: u16) -> ShaderStage { } } -/// Inspect a `DXBC` shader container blob and classify its payload chunks. -pub fn inspect_dxbc(bytes: &[u8]) -> Result { +fn fspx_error(chunk: usize, err: fspx::FspxError) -> ParseError { + match err { + fspx::FspxError::Truncated => ParseError::FspxTruncated { chunk }, + fspx::FspxError::BadVersion(version) => ParseError::FspxBadVersion { chunk, version }, + fspx::FspxError::SectionOutOfBounds { section_id } => { + ParseError::FspxSectionOutOfBounds { chunk, section_id } + } + fspx::FspxError::DuplicateSection { section_id } => { + ParseError::FspxDuplicateSection { chunk, section_id } + } + fspx::FspxError::Overlap { section_id } => { + ParseError::FspxSectionOverlap { chunk, section_id } + } + fspx::FspxError::BadStageConfig => ParseError::FspxBadStageConfig { chunk }, + } +} + +struct ContainerLimit { + container_size: u32, + limit: usize, + table_end: usize, + chunk_count: usize, + digest: [u8; 16], +} + +fn container_limit(bytes: &[u8]) -> Result { if bytes.len() < 32 { return Err(ParseError::TooShort); } - if &bytes[0..4] != b"DXBC" { + if bytes.get(..4) != Some(b"DXBC".as_slice()) { return Err(ParseError::BadMagic); } let mut digest = [0u8; 16]; - digest.copy_from_slice(&bytes[4..20]); + let digest_bytes = bytes.get(4..20).ok_or(ParseError::TooShort)?; + digest.copy_from_slice(digest_bytes); let version = read_u32_le(bytes, 20).ok_or(ParseError::TooShort)?; if version != 1 { return Err(ParseError::UnsupportedVersion(version)); } let container_size = read_u32_le(bytes, 24).ok_or(ParseError::TooShort)?; - let chunk_count = read_u32_le(bytes, 28).ok_or(ParseError::TooShort)? as usize; - + let chunk_count_u32 = read_u32_le(bytes, 28).ok_or(ParseError::TooShort)?; + let chunk_count = + usize::try_from(chunk_count_u32).map_err(|_| ParseError::TruncatedChunkTable)?; + let table_bytes = chunk_count + .checked_mul(4) + .ok_or(ParseError::TruncatedChunkTable)?; let table_end = 32usize - .checked_add( - chunk_count - .checked_mul(4) - .ok_or(ParseError::TruncatedChunkTable)?, - ) + .checked_add(table_bytes) .ok_or(ParseError::TruncatedChunkTable)?; if table_end > bytes.len() { return Err(ParseError::TruncatedChunkTable); } + let limit = usize::try_from(container_size).map_err(|_| ParseError::TruncatedContainer)?; + if limit > bytes.len() || limit < table_end { + return Err(ParseError::TruncatedContainer); + } + Ok(ContainerLimit { + container_size, + limit, + table_end, + chunk_count, + digest, + }) +} - let mut chunks = Vec::with_capacity(chunk_count); +fn program_stage(word: u32) -> (ShaderStage, u8, u8) { + let stage = decode_stage(u16::try_from(word >> 16).unwrap_or(u16::MAX)); + let major = u8::try_from((word >> 4) & 0xF).unwrap_or(0); + let minor = u8::try_from(word & 0xF).unwrap_or(0); + (stage, major, minor) +} + +fn visit_chunks( + bytes: &[u8], + mut visit: impl FnMut(usize, u32, [u8; 4], u32, &[u8]) -> Result<(), ParseError>, +) -> Result { + let header = container_limit(bytes)?; + for index in 0..header.chunk_count { + let offset = read_u32_le(bytes, 32 + index * 4).ok_or(ParseError::TruncatedChunkTable)?; + let off = usize::try_from(offset).map_err(|_| ParseError::ChunkOutOfBounds { index })?; + if off < header.table_end { + return Err(ParseError::ChunkOutOfBounds { index }); + } + let header_end = off + .checked_add(8) + .ok_or(ParseError::ChunkOutOfBounds { index })?; + if header_end > header.limit { + return Err(ParseError::ChunkOutOfBounds { index }); + } + let hdr = bytes + .get(off..header_end) + .ok_or(ParseError::ChunkOutOfBounds { index })?; + let fourcc = [hdr[0], hdr[1], hdr[2], hdr[3]]; + let size = u32::from_le_bytes([hdr[4], hdr[5], hdr[6], hdr[7]]); + let payload_len = + usize::try_from(size).map_err(|_| ParseError::ChunkOutOfBounds { index })?; + let payload_end = header_end + .checked_add(payload_len) + .ok_or(ParseError::ChunkOutOfBounds { index })?; + if payload_end > header.limit { + return Err(ParseError::ChunkOutOfBounds { index }); + } + let payload = bytes + .get(header_end..payload_end) + .ok_or(ParseError::ChunkOutOfBounds { index })?; + visit(index, offset, fourcc, size, payload)?; + } + Ok(header) +} + +fn kind_from_flags(has_dxil: bool, has_accc: bool, has_legacy: bool) -> ShaderKind { + match (has_dxil, has_accc, has_legacy) { + (true, true, _) => ShaderKind::DualDxilAndAccc, + (true, false, _) => ShaderKind::Dxil, + (false, true, _) => ShaderKind::AcccOnly, + (false, false, true) => ShaderKind::LegacyDxbc, + (false, false, false) => ShaderKind::Unknown, + } +} + +/// Scalar fields of a container. Used by `bx_shader_inspect`, which does not +/// keep chunk or section lists. +pub(crate) struct DxbcSummary { + pub kind: ShaderKind, + pub stage: ShaderStage, + pub shader_model_major: u8, + pub shader_model_minor: u8, + pub container_size: u32, + pub digest: [u8; 16], + pub has_root_signature: bool, + pub dxil_size: u32, + pub accc_size: u32, +} + +/// Classify a container without allocating. +/// +/// A malformed `FSPX` table is still [`Err`], so inspection can report it. +pub(crate) fn summarize_dxbc(bytes: &[u8]) -> Result { + let mut has_dxil = false; + let mut has_accc = false; + let mut has_legacy = false; + let mut has_root_signature = false; + let mut dxil_size = 0u32; + let mut accc_size = 0u32; + let mut dxil_stage = None; + let mut legacy_stage = None; + let mut fspx_stage = None; + let header = visit_chunks(bytes, |index, _offset, fourcc, size, payload| { + match &fourcc { + b"DXIL" => { + has_dxil = true; + dxil_size = size; + if let Some(prog_ver) = read_u32_le(payload, 0) { + dxil_stage = Some(program_stage(prog_ver)); + } + } + b"ACCC" => { + has_accc = true; + accc_size = size; + match fspx::scan_fspx(payload) { + Ok(Some(scan)) => { + if fspx_stage.is_none() { + fspx_stage = scan.stage; + } + } + Ok(None) => {} + Err(err) => return Err(fspx_error(index, err)), + } + } + b"SHDR" | b"SHEX" => { + has_legacy = true; + if let Some(tok) = read_u32_le(payload, 0) { + legacy_stage = Some(program_stage(tok)); + } + } + b"RTS0" => has_root_signature = true, + _ => {} + } + Ok(()) + })?; + let (stage, shader_model_major, shader_model_minor) = dxil_stage + .or(legacy_stage) + .or(fspx_stage) + .unwrap_or((ShaderStage::Unknown, 0, 0)); + Ok(DxbcSummary { + kind: kind_from_flags(has_dxil, has_accc, has_legacy), + stage, + shader_model_major, + shader_model_minor, + container_size: header.container_size, + digest: header.digest, + has_root_signature, + dxil_size, + accc_size, + }) +} + +/// `Ok(Some(container_size))` when the container is structurally valid and +/// contains a `DXIL` chunk. A malformed `FSPX` table does not hide that chunk. +/// `Ok(None)` means the container is structurally valid and has no `DXIL` chunk. +pub(crate) fn dxil_container_len(bytes: &[u8]) -> Result, ParseError> { + let mut has_dxil = false; + let header = visit_chunks(bytes, |_index, _offset, fourcc, _size, _payload| { + if &fourcc == b"DXIL" { + has_dxil = true; + } + Ok(()) + })?; + Ok(if has_dxil { + Some(header.container_size) + } else { + None + }) +} + +/// Inspect a `DXBC` shader container blob and classify its payload chunks. +/// +/// Malformed input returns [`ParseError`]. This function does not panic on +/// truncated headers, oversized chunk counts, or `FSPX` sections that fall +/// outside the payload. A malformed `FSPX` table fails the inspection even +/// when a `DXIL` chunk is also present; preparation still passes that `DXIL` +/// container through. +pub fn inspect_dxbc(bytes: &[u8]) -> Result { + let mut chunks = Vec::new(); let mut has_dxil = false; let mut has_accc = false; let mut has_legacy = false; @@ -131,96 +384,89 @@ pub fn inspect_dxbc(bytes: &[u8]) -> Result { let mut dxil_size = 0u32; let mut accc_size = 0u32; let mut accc_is_fspx = false; - let mut stage = ShaderStage::Unknown; - let mut sm_major = 0u8; - let mut sm_minor = 0u8; - - for i in 0..chunk_count { - let off = read_u32_le(bytes, 32 + i * 4).ok_or(ParseError::TruncatedChunkTable)? as usize; - let hdr = bytes - .get(off..off + 8) - .ok_or(ParseError::ChunkOutOfBounds { index: i })?; - let fourcc = [hdr[0], hdr[1], hdr[2], hdr[3]]; - let size = u32::from_le_bytes([hdr[4], hdr[5], hdr[6], hdr[7]]); - let payload_start = off + 8; - let payload_end = payload_start - .checked_add(size as usize) - .ok_or(ParseError::ChunkOutOfBounds { index: i })?; - if payload_end > bytes.len() { - return Err(ParseError::ChunkOutOfBounds { index: i }); - } - let payload = &bytes[payload_start..payload_end]; + let mut dxil_stage = None; + let mut legacy_stage = None; + let mut fspx_stage = None; + let mut fspx = None; + let header = visit_chunks(bytes, |index, offset, fourcc, size, payload| { match &fourcc { b"DXIL" => { has_dxil = true; dxil_size = size; if let Some(prog_ver) = read_u32_le(payload, 0) { - stage = decode_stage((prog_ver >> 16) as u16); - sm_major = ((prog_ver >> 4) & 0xF) as u8; - sm_minor = (prog_ver & 0xF) as u8; + dxil_stage = Some(program_stage(prog_ver)); } } b"ACCC" => { has_accc = true; accc_size = size; - if payload.get(0..4) == Some(b"FSPX") { - accc_is_fspx = true; + match fspx::parse_fspx(payload) { + Ok(Some(info)) => { + accc_is_fspx = true; + if fspx.is_none() { + if let Some(cfg) = info.stage_config { + fspx_stage = Some(( + cfg.stage, + cfg.shader_model_major, + cfg.shader_model_minor, + )); + } + fspx = Some(info); + } + } + Ok(None) => {} + Err(err) => return Err(fspx_error(index, err)), } } b"SHDR" | b"SHEX" => { has_legacy = true; if let Some(tok) = read_u32_le(payload, 0) { - stage = decode_stage((tok >> 16) as u16); - sm_major = ((tok >> 4) & 0xF) as u8; - sm_minor = (tok & 0xF) as u8; + legacy_stage = Some(program_stage(tok)); } } b"RTS0" => has_root_signature = true, _ => {} } - chunks.push(ChunkInfo { fourcc, - offset: off as u32, + offset, size, }); - } + Ok(()) + })?; - let kind = match (has_dxil, has_accc, has_legacy) { - (true, true, _) => ShaderKind::DualDxilAndAccc, - (true, false, _) => ShaderKind::Dxil, - (false, true, _) => ShaderKind::AcccOnly, - (false, false, true) => ShaderKind::LegacyDxbc, - (false, false, false) => ShaderKind::Unknown, - }; + let (stage, sm_major, sm_minor) = + dxil_stage + .or(legacy_stage) + .or(fspx_stage) + .unwrap_or((ShaderStage::Unknown, 0, 0)); Ok(ShaderInspection { - kind, + kind: kind_from_flags(has_dxil, has_accc, has_legacy), stage, shader_model_major: sm_major, shader_model_minor: sm_minor, - container_size, - digest, + container_size: header.container_size, + digest: header.digest, has_root_signature, dxil_size, accc_size, accc_is_fspx, + fspx, chunks, }) } #[cfg(test)] -mod tests { - use super::*; - - fn build_synthetic_dxbc(chunks: &[(&[u8; 4], &[u8])]) -> Vec { +pub(crate) mod testutil { + pub(crate) fn build_synthetic_dxbc(chunks: &[(&[u8; 4], &[u8])]) -> Vec { let header_size = 32 + chunks.len() * 4; let mut out = Vec::new(); out.extend_from_slice(b"DXBC"); out.extend_from_slice(&[0xAB; 16]); out.extend_from_slice(&1u32.to_le_bytes()); - out.extend_from_slice(&0u32.to_le_bytes()); // total size patched below + out.extend_from_slice(&0u32.to_le_bytes()); out.extend_from_slice(&(chunks.len() as u32).to_le_bytes()); let mut offset = header_size as u32; @@ -238,26 +484,88 @@ mod tests { out } - #[test] - fn classifies_synthetic_dxil_cs_6_6() { + /// 104-byte synthetic FSPX payload. + /// + /// Header 16 bytes, four 12-byte descriptors, then section bodies at the + /// literal offsets 64, 72, 84 and 100. + pub(crate) fn synthetic_fspx_payload() -> Vec { + let mut payload = Vec::new(); + payload.extend_from_slice(b"FSPX"); + payload.extend_from_slice(&1u32.to_le_bytes()); + payload.extend_from_slice(&4u32.to_le_bytes()); + payload.extend_from_slice(&0u32.to_le_bytes()); + for (id, offset, size) in [(0u32, 64u32, 8u32), (1, 72, 12), (6, 84, 16), (7, 100, 4)] { + payload.extend_from_slice(&id.to_le_bytes()); + payload.extend_from_slice(&offset.to_le_bytes()); + payload.extend_from_slice(&size.to_le_bytes()); + } + payload.extend_from_slice(&[0xA0, 0x01, 0x00, 0x00, 0xA7, 0x00, 0x00, 0x00]); + payload.extend_from_slice(&6u32.to_le_bytes()); + payload.extend_from_slice(&6u32.to_le_bytes()); + payload.extend_from_slice(&0u32.to_le_bytes()); + payload.extend_from_slice(b"SYNTH_RDNA2_CODE"); + payload.extend_from_slice(&[0x70, 0x07, 0x00, 0x00]); + payload + } + + pub(crate) fn synthetic_dxil_blob() -> Vec { let mut dxil_payload = Vec::new(); - let prog_ver: u32 = (5u32 << 16) | (6u32 << 4) | 6u32; // cs_6_6 + let prog_ver: u32 = (5u32 << 16) | (6u32 << 4) | 6u32; dxil_payload.extend_from_slice(&prog_ver.to_le_bytes()); dxil_payload.extend_from_slice(&4u32.to_le_bytes()); dxil_payload.extend_from_slice(b"DXIL"); dxil_payload.extend_from_slice(&[0u8; 12]); + build_synthetic_dxbc(&[(b"RTS0", &[1, 2, 3, 4]), (b"DXIL", &dxil_payload)]) + } +} - let blob = build_synthetic_dxbc(&[(b"RTS0", &[1, 2, 3, 4]), (b"DXIL", &dxil_payload)]); +#[cfg(test)] +mod tests { + use super::c_abi::{clear_shader_log, shader_log_lines}; + use super::testutil::{build_synthetic_dxbc, synthetic_dxil_blob, synthetic_fspx_payload}; + use super::*; + + fn push_u32(buf: &mut Vec, value: u32) { + buf.extend_from_slice(&value.to_le_bytes()); + } + + fn fspx_header( + version: u32, + count: u32, + descriptors: &[(u32, u32, u32)], + len: usize, + ) -> Vec { + let mut payload = vec![0u8; len]; + payload[..4].copy_from_slice(b"FSPX"); + payload[4..8].copy_from_slice(&version.to_le_bytes()); + payload[8..12].copy_from_slice(&count.to_le_bytes()); + for (index, (id, offset, size)) in descriptors.iter().enumerate() { + let at = 16 + index * 12; + payload[at..at + 4].copy_from_slice(&id.to_le_bytes()); + payload[at + 4..at + 8].copy_from_slice(&offset.to_le_bytes()); + payload[at + 8..at + 12].copy_from_slice(&size.to_le_bytes()); + } + payload + } + + #[test] + fn classifies_synthetic_dxil_cs_6_6() { + let blob = synthetic_dxil_blob(); + assert_eq!(blob.len(), 84); let info = inspect_dxbc(&blob).expect("valid synthetic DXBC"); assert_eq!(info.kind, ShaderKind::Dxil); assert_eq!(info.stage, ShaderStage::Compute); assert_eq!((info.shader_model_major, info.shader_model_minor), (6, 6)); assert!(info.has_root_signature); assert!(!info.accc_is_fspx); + assert!(info.fspx.is_none()); + assert_eq!(info.dxil_size, 24); + assert_eq!(info.container_size, 84); + assert_eq!(info.digest, [0xAB; 16]); } #[test] - fn classifies_synthetic_accc_fspx() { + fn classifies_synthetic_accc_fspx_magic_only() { let mut accc_payload = Vec::new(); accc_payload.extend_from_slice(b"FSPX"); accc_payload.extend_from_slice(&[0u8; 28]); @@ -267,10 +575,492 @@ mod tests { assert_eq!(info.kind, ShaderKind::AcccOnly); assert!(info.accc_is_fspx); assert_eq!(info.accc_size, 32); + let fspx = info.fspx.expect("version 0 stub"); + assert_eq!(fspx.version, 0); + assert!(fspx.sections.is_empty()); + assert!(fspx.stage_config.is_none()); + assert!(fspx.rdna_code.is_none()); } #[test] - fn rejects_invalid_magic() { + fn extracts_synthetic_fspx_sections_stage_and_rdna_bounds() { + let payload = synthetic_fspx_payload(); + assert_eq!(payload.len(), 104); + assert_eq!( + &payload[64..72], + &[0xA0, 0x01, 0x00, 0x00, 0xA7, 0x00, 0x00, 0x00] + ); + assert_eq!(&payload[84..100], b"SYNTH_RDNA2_CODE"); + assert_eq!(&payload[100..104], &[0x70, 0x07, 0x00, 0x00]); + + let blob = build_synthetic_dxbc(&[(b"ACCC", &payload)]); + assert_eq!(blob.len(), 148); + let info = inspect_dxbc(&blob).expect("section table"); + assert_eq!(info.kind, ShaderKind::AcccOnly); + assert_eq!(info.stage, ShaderStage::Compute); + assert_eq!((info.shader_model_major, info.shader_model_minor), (6, 0)); + assert_eq!(info.accc_size, 104); + assert_eq!(info.container_size, 148); + assert!(info.accc_is_fspx); + + let fspx = info.fspx.expect("fspx table"); + assert_eq!(fspx.version, 1); + assert_eq!( + fspx.sections, + vec![ + FspxSection { + id: 0, + offset: 64, + size: 8 + }, + FspxSection { + id: 1, + offset: 72, + size: 12 + }, + FspxSection { + id: 6, + offset: 84, + size: 16 + }, + FspxSection { + id: 7, + offset: 100, + size: 4 + }, + ] + ); + let section0 = fspx.section0.expect("section 0"); + assert_eq!((section0.offset, section0.size), (64, 8)); + let stage = fspx.stage_config.expect("section 1"); + assert_eq!(stage.stage, ShaderStage::Compute); + assert_eq!((stage.offset, stage.size), (72, 12)); + assert_eq!((stage.shader_model_major, stage.shader_model_minor), (6, 0)); + let code = fspx.rdna_code.expect("section 6"); + assert_eq!((code.offset, code.size), (84, 16)); + assert_eq!( + fspx.rdna_code_bytes(&payload), + Some(b"SYNTH_RDNA2_CODE".as_slice()) + ); + let section7 = fspx.section7.expect("section 7"); + assert_eq!((section7.offset, section7.size), (100, 4)); + } + + #[test] + fn dxil_stage_wins_over_fspx_stage_in_dual_container() { + let mut dxil_payload = Vec::new(); + push_u32(&mut dxil_payload, (5u32 << 16) | (6u32 << 4) | 6u32); + let mut fspx = synthetic_fspx_payload(); + // Section 1 stage word is at payload offset 72. Overwrite compute (6) + // with the ABI pixel value 1, and shader model 6.0 with 5.1. + fspx[72..76].copy_from_slice(&1u32.to_le_bytes()); + fspx[76..80].copy_from_slice(&5u32.to_le_bytes()); + fspx[80..84].copy_from_slice(&1u32.to_le_bytes()); + + let blob = build_synthetic_dxbc(&[(b"DXIL", &dxil_payload), (b"ACCC", &fspx)]); + let info = inspect_dxbc(&blob).expect("dual container"); + assert_eq!(info.kind, ShaderKind::DualDxilAndAccc); + assert_eq!(info.stage, ShaderStage::Compute); + assert_eq!((info.shader_model_major, info.shader_model_minor), (6, 6)); + let stage = info.fspx.expect("fspx").stage_config.expect("section 1"); + assert_eq!(stage.stage, ShaderStage::Pixel); + assert_eq!((stage.shader_model_major, stage.shader_model_minor), (5, 1)); + } + + #[test] + fn classifies_synthetic_legacy_shdr() { + let tok: u32 = (1u32 << 16) | (5u32 << 4) | 1u32; + let payload = tok.to_le_bytes(); + let blob = build_synthetic_dxbc(&[(b"SHDR", &payload)]); + let info = inspect_dxbc(&blob).expect("legacy container"); + assert_eq!(info.kind, ShaderKind::LegacyDxbc); + assert_eq!(info.stage, ShaderStage::Vertex); + assert_eq!((info.shader_model_major, info.shader_model_minor), (5, 1)); + assert!(info.fspx.is_none()); + } + + #[test] + fn rejects_invalid_magic_and_short_headers() { assert_eq!(inspect_dxbc(&[0u8; 64]), Err(ParseError::BadMagic)); + assert_eq!(inspect_dxbc(&[]), Err(ParseError::TooShort)); + assert_eq!(inspect_dxbc(b"DXBC"), Err(ParseError::TooShort)); + assert_eq!(inspect_dxbc(&[0u8; 31]), Err(ParseError::TooShort)); + + let mut version = vec![0u8; 32]; + version[..4].copy_from_slice(b"DXBC"); + version[20..24].copy_from_slice(&2u32.to_le_bytes()); + assert_eq!( + inspect_dxbc(&version), + Err(ParseError::UnsupportedVersion(2)) + ); + } + + #[test] + fn rejects_truncated_tables_and_chunk_bounds() { + let mut huge = vec![0u8; 32]; + huge[..4].copy_from_slice(b"DXBC"); + huge[20..24].copy_from_slice(&1u32.to_le_bytes()); + huge[24..28].copy_from_slice(&32u32.to_le_bytes()); + huge[28..32].copy_from_slice(&u32::MAX.to_le_bytes()); + assert_eq!(inspect_dxbc(&huge), Err(ParseError::TruncatedChunkTable)); + + let mut short_container = vec![0u8; 32]; + short_container[..4].copy_from_slice(b"DXBC"); + short_container[20..24].copy_from_slice(&1u32.to_le_bytes()); + short_container[24..28].copy_from_slice(&16u32.to_le_bytes()); + assert_eq!( + inspect_dxbc(&short_container), + Err(ParseError::TruncatedContainer) + ); + + let mut declared_too_big = vec![0u8; 32]; + declared_too_big[..4].copy_from_slice(b"DXBC"); + declared_too_big[20..24].copy_from_slice(&1u32.to_le_bytes()); + declared_too_big[24..28].copy_from_slice(&1_000u32.to_le_bytes()); + assert_eq!( + inspect_dxbc(&declared_too_big), + Err(ParseError::TruncatedContainer) + ); + + let mut wild_offset = vec![0u8; 36]; + wild_offset[..4].copy_from_slice(b"DXBC"); + wild_offset[20..24].copy_from_slice(&1u32.to_le_bytes()); + wild_offset[24..28].copy_from_slice(&36u32.to_le_bytes()); + wild_offset[28..32].copy_from_slice(&1u32.to_le_bytes()); + wild_offset[32..36].copy_from_slice(&0xFFFF_FFF0u32.to_le_bytes()); + assert_eq!( + inspect_dxbc(&wild_offset), + Err(ParseError::ChunkOutOfBounds { index: 0 }) + ); + + let mut oversized = vec![0u8; 80]; + oversized[..4].copy_from_slice(b"DXBC"); + oversized[20..24].copy_from_slice(&1u32.to_le_bytes()); + oversized[24..28].copy_from_slice(&40u32.to_le_bytes()); + oversized[28..32].copy_from_slice(&1u32.to_le_bytes()); + oversized[32..36].copy_from_slice(&36u32.to_le_bytes()); + oversized[36..40].copy_from_slice(b"DXIL"); + oversized[40..44].copy_from_slice(&20u32.to_le_bytes()); + assert_eq!( + inspect_dxbc(&oversized), + Err(ParseError::ChunkOutOfBounds { index: 0 }) + ); + } + + #[test] + fn rejects_malformed_fspx_sections() { + let cases = [ + ( + fspx_header(1, 3, &[], 16), + ParseError::FspxTruncated { chunk: 0 }, + ), + ( + fspx_header(99, 0, &[], 16), + ParseError::FspxBadVersion { + chunk: 0, + version: 99, + }, + ), + ( + fspx_header(0, 1, &[], 16), + ParseError::FspxBadVersion { + chunk: 0, + version: 0, + }, + ), + ( + { + let mut payload = fspx_header(1, 1, &[(6, 64, u32::MAX)], 28); + payload.truncate(28); + payload + }, + ParseError::FspxSectionOutOfBounds { + chunk: 0, + section_id: 6, + }, + ), + ( + fspx_header(1, 1, &[(1, 0, 4)], 28), + ParseError::FspxSectionOutOfBounds { + chunk: 0, + section_id: 1, + }, + ), + ( + fspx_header(1, 2, &[(6, 40, 4), (6, 48, 4)], 52), + ParseError::FspxDuplicateSection { + chunk: 0, + section_id: 6, + }, + ), + ( + fspx_header(1, 2, &[(0, 64, 16), (6, 72, 8)], 80), + ParseError::FspxSectionOverlap { + chunk: 0, + section_id: 6, + }, + ), + ( + fspx_header(1, 1, &[(1, 28, 4)], 32), + ParseError::FspxBadStageConfig { chunk: 0 }, + ), + ]; + for (payload, expected) in cases { + let blob = build_synthetic_dxbc(&[(b"ACCC", &payload)]); + assert_eq!(inspect_dxbc(&blob), Err(expected)); + } + + let mut bad_stage = fspx_header(1, 1, &[(1, 28, 12)], 40); + bad_stage[28..32].copy_from_slice(&99u32.to_le_bytes()); + let blob = build_synthetic_dxbc(&[(b"ACCC", &bad_stage)]); + assert_eq!( + inspect_dxbc(&blob), + Err(ParseError::FspxBadStageConfig { chunk: 0 }) + ); + + let mut big_major = fspx_header(1, 1, &[(1, 28, 12)], 40); + big_major[28..32].copy_from_slice(&6u32.to_le_bytes()); + big_major[32..36].copy_from_slice(&256u32.to_le_bytes()); + let blob = build_synthetic_dxbc(&[(b"ACCC", &big_major)]); + assert_eq!( + inspect_dxbc(&blob), + Err(ParseError::FspxBadStageConfig { chunk: 0 }) + ); + + let magic_only = b"FSPX".to_vec(); + let blob = build_synthetic_dxbc(&[(b"ACCC", &magic_only)]); + assert_eq!( + inspect_dxbc(&blob), + Err(ParseError::FspxTruncated { chunk: 0 }) + ); + } + + #[test] + fn truncated_prefixes_do_not_panic() { + let blobs = [ + synthetic_dxil_blob(), + build_synthetic_dxbc(&[(b"ACCC", &synthetic_fspx_payload())]), + vec![0xFF; 64], + ]; + for blob in blobs { + for len in 0..=blob.len() { + let _ = inspect_dxbc(&blob[..len]); + } + } + } + + #[test] + fn c_abi_inspect_and_passthrough_round_trip() { + clear_shader_log(); + let blob = synthetic_dxil_blob(); + let mut info = BxShaderInspection { + kind: 99, + stage: 99, + shader_model_major: 99, + shader_model_minor: 99, + container_size: 99, + dxil_chunk_size: 99, + accc_chunk_size: 99, + has_root_signature: 99, + digest_hash: [0x11; 16], + }; + let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut info) }; + assert_eq!(status, BX_SHADER_OK); + assert_eq!(info.kind, 1); + assert_eq!(info.stage, 6); + assert_eq!(info.shader_model_major, 6); + assert_eq!(info.shader_model_minor, 6); + assert_eq!(info.container_size, 84); + assert_eq!(info.dxil_chunk_size, 24); + assert_eq!(info.accc_chunk_size, 0); + assert_eq!(info.has_root_signature, 1); + assert_eq!(info.digest_hash, [0xAB; 16]); + + let mut out_ptr: *mut u8 = ptr_sentinel(); + let mut out_len = 99usize; + let status = unsafe { + bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len) + }; + assert_eq!(status, BX_SHADER_OK); + assert_eq!(out_len, 84); + assert!(!out_ptr.is_null()); + let copied = unsafe { std::slice::from_raw_parts(out_ptr, out_len) }; + assert_eq!(copied, blob.as_slice()); + unsafe { bx_shader_free_buffer(out_ptr, out_len) }; + assert!(shader_log_lines().is_empty()); + } + + #[test] + fn c_abi_accc_only_is_unsupported_and_logged() { + clear_shader_log(); + let payload = synthetic_fspx_payload(); + let blob = build_synthetic_dxbc(&[(b"ACCC", &payload)]); + assert_eq!(blob.len(), 148); + + let mut info = BxShaderInspection::default(); + let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut info) }; + assert_eq!(status, BX_SHADER_OK); + assert_eq!(info.kind, 3); + assert_eq!(info.stage, 6); + assert_eq!(info.shader_model_major, 6); + assert_eq!(info.shader_model_minor, 0); + assert_eq!(info.accc_chunk_size, 104); + assert_eq!(info.dxil_chunk_size, 0); + assert_eq!(info.container_size, 148); + assert_eq!(info.digest_hash, [0xAB; 16]); + assert!(shader_log_lines().is_empty(), "inspect does not log"); + + let mut out_ptr = ptr_sentinel(); + let mut out_len = 99usize; + let status = unsafe { + bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len) + }; + assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED); + assert!(out_ptr.is_null()); + assert_eq!(out_len, 0); + + let lines = shader_log_lines(); + assert_eq!(lines.len(), 1); + let prepare = lines + .iter() + .find(|line| line.contains("event=prepare")) + .expect("prepare log"); + for field in [ + "status=unsupported", + "detail=no_dxil_passthrough", + "kind=accc_only(3)", + "stage=compute(6)", + "sm_major=6", + "sm_minor=0", + "container_size=148", + "dxil_chunk_size=0", + "accc_chunk_size=104", + "has_root_signature=0", + "digest=abababababababababababababababab", + "fspx=1", + "fspx_version=1", + "sections=0@64+8,1@72+12,6@84+16,7@100+4", + "rdna_off=84", + "rdna_size=16", + ] { + assert!(prepare.contains(field), "missing {field} in {prepare}"); + } + } + + #[test] + fn c_abi_legacy_is_unsupported_and_invalid_inputs_allocate_nothing() { + clear_shader_log(); + let tok: u32 = (1u32 << 16) | (5u32 << 4) | 1u32; + let blob = build_synthetic_dxbc(&[(b"SHDR", &tok.to_le_bytes())]); + let mut out_ptr = ptr_sentinel(); + let mut out_len = 7usize; + let status = unsafe { + bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len) + }; + assert_eq!(status, BX_SHADER_ERR_UNSUPPORTED); + assert!(out_ptr.is_null()); + assert_eq!(out_len, 0); + assert!(shader_log_lines().is_empty()); + + clear_shader_log(); + let mut info = BxShaderInspection { + kind: 4, + ..BxShaderInspection::default() + }; + let status = unsafe { bx_shader_inspect(b"nope".as_ptr(), 4, &mut info) }; + assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB); + assert_eq!(info, BxShaderInspection::default()); + + let mut out_ptr = ptr_sentinel(); + let mut out_len = 7usize; + let status = unsafe { + bx_shader_prepare_for_d3dmetal(b"nope".as_ptr(), 4, &mut out_ptr, &mut out_len) + }; + assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB); + assert!(out_ptr.is_null()); + assert_eq!(out_len, 0); + + assert_eq!( + unsafe { bx_shader_inspect(std::ptr::null(), 0, std::ptr::null_mut()) }, + BX_SHADER_ERR_INVALID_BLOB + ); + assert_eq!( + unsafe { + bx_shader_prepare_for_d3dmetal( + std::ptr::null(), + 0, + std::ptr::null_mut(), + std::ptr::null_mut(), + ) + }, + BX_SHADER_ERR_INVALID_BLOB + ); + unsafe { bx_shader_free_buffer(std::ptr::null_mut(), 0) }; + unsafe { bx_shader_free_buffer(std::ptr::null_mut(), 32) }; + } + + #[test] + fn prepare_copies_container_size_not_trailing_bytes() { + clear_shader_log(); + let mut blob = synthetic_dxil_blob(); + let container_size = blob.len(); + assert_eq!(container_size, 84); + blob.extend_from_slice(&[0xEE, 0xEE, 0xEE, 0xEE]); + + let mut out_ptr = ptr_sentinel(); + let mut out_len = 0usize; + let status = unsafe { + bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len) + }; + assert_eq!(status, BX_SHADER_OK); + assert_eq!(out_len, container_size); + let copied = unsafe { std::slice::from_raw_parts(out_ptr, out_len) }; + assert_eq!(copied, &blob[..container_size]); + unsafe { bx_shader_free_buffer(out_ptr, out_len) }; + assert!(shader_log_lines().is_empty()); + } + + #[test] + fn prepare_passes_dxil_through_when_fspx_is_malformed() { + clear_shader_log(); + let mut dxil_payload = Vec::new(); + push_u32(&mut dxil_payload, (5u32 << 16) | (6u32 << 4) | 6u32); + let bad_fspx = fspx_header(99, 0, &[], 16); + let mut blob = build_synthetic_dxbc(&[(b"DXIL", &dxil_payload), (b"ACCC", &bad_fspx)]); + let container_size = blob.len(); + blob.extend_from_slice(&[0xEE; 4]); + + assert_eq!( + inspect_dxbc(&blob), + Err(ParseError::FspxBadVersion { + chunk: 1, + version: 99, + }) + ); + + let mut info = BxShaderInspection { + kind: 7, + ..BxShaderInspection::default() + }; + let status = unsafe { bx_shader_inspect(blob.as_ptr(), blob.len(), &mut info) }; + assert_eq!(status, BX_SHADER_ERR_INVALID_BLOB); + assert_eq!(info, BxShaderInspection::default()); + assert!(shader_log_lines().is_empty()); + + let mut out_ptr = ptr_sentinel(); + let mut out_len = 1usize; + let status = unsafe { + bx_shader_prepare_for_d3dmetal(blob.as_ptr(), blob.len(), &mut out_ptr, &mut out_len) + }; + assert_eq!(status, BX_SHADER_OK); + assert_eq!(out_len, container_size); + let copied = unsafe { std::slice::from_raw_parts(out_ptr, out_len) }; + assert_eq!(copied, &blob[..container_size]); + unsafe { bx_shader_free_buffer(out_ptr, out_len) }; + assert!(shader_log_lines().is_empty()); + } + + fn ptr_sentinel() -> *mut u8 { + std::ptr::dangling_mut() } }