Initial commit

Rust workspace for VIctory: PE analysis, loader, HLE skeleton,
DXBC/DXIL parsing with a GFX10 decoder, conversion cache, CLI and
asset-policy enforcement.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
This commit is contained in:
MarvisandClaude Sonnet 5.5 committed 2026-11-23 01:15:26 +01:00
commit f4504f6413
69 files changed
+7952

No files matched your search

+15
View File
@@ -0,0 +1,15 @@
[package]
name = "victory-shader"
description = "Xbox shader containers (DXBC/DXIL + precompiled GFX10) to host shaders."
version.workspace = true
edition.workspace = true
rust-version.workspace = true
license.workspace = true
publish.workspace = true
[dependencies]
thiserror.workspace = true
miniz_oxide.workspace = true
[lints]
workspace = true
+179
View File
@@ -0,0 +1,179 @@
//! The DXBC container: a header, then a table of FourCC-tagged parts.
//!
//! ```text
//! 0x00 "DXBC"
//! 0x04 digest[16]
//! 0x14 version major u16, minor u16
//! 0x18 total size u32
//! 0x1C part count u32
//! 0x20 part offsets u32[count]
//! part: fourcc[4], size u32, data[size]
//! ```
use crate::ShaderError;
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct FourCC(pub [u8; 4]);
impl FourCC {
pub const DXIL: FourCC = FourCC(*b"DXIL");
pub const STAT: FourCC = FourCC(*b"STAT");
pub const RTS0: FourCC = FourCC(*b"RTS0");
pub const PSV0: FourCC = FourCC(*b"PSV0");
pub const ISG1: FourCC = FourCC(*b"ISG1");
pub const OSG1: FourCC = FourCC(*b"OSG1");
pub const SFI0: FourCC = FourCC(*b"SFI0");
pub const HASH: FourCC = FourCC(*b"HASH");
pub const ILDB: FourCC = FourCC(*b"ILDB");
pub const ILDN: FourCC = FourCC(*b"ILDN");
}
impl std::fmt::Debug for FourCC {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self)
}
}
impl std::fmt::Display for FourCC {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
for &b in &self.0 {
let c = if b.is_ascii_graphic() { b as char } else { '.' };
write!(f, "{c}")?;
}
Ok(())
}
}
#[derive(Debug, Clone, Copy)]
pub struct Part<'a> {
pub fourcc: FourCC,
/// Offset of the part header within the container.
pub offset: usize,
pub data: &'a [u8],
}
#[derive(Debug, Clone)]
pub struct Container<'a> {
pub digest: [u8; 16],
pub version: (u16, u16),
pub parts: Vec<Part<'a>>,
}
const HEADER_SIZE: usize = 0x20;
const MAX_PARTS: usize = 256;
impl<'a> Container<'a> {
pub fn parse(data: &'a [u8]) -> Result<Self, ShaderError> {
if data.len() < HEADER_SIZE || &data[0..4] != b"DXBC" {
return Err(ShaderError::NotDxbc);
}
let digest = data[4..20].try_into().expect("16 bytes");
let version = (u16_at(data, 0x14)?, u16_at(data, 0x16)?);
let total = u32_at(data, 0x18)? as usize;
if total > data.len() || total < HEADER_SIZE {
return Err(ShaderError::Malformed("container size disagrees with data"));
}
let data = &data[..total];
let count = u32_at(data, 0x1C)? as usize;
if count > MAX_PARTS {
return Err(ShaderError::Malformed("implausible part count"));
}
let mut parts = Vec::with_capacity(count);
for i in 0..count {
let offset = u32_at(data, HEADER_SIZE + 4 * i)? as usize;
let fourcc = FourCC(
data.get(offset..offset + 4)
.ok_or(ShaderError::Malformed("part header out of bounds"))?
.try_into()
.expect("4 bytes"),
);
let size = u32_at(data, offset + 4)? as usize;
let body = data
.get(offset + 8..offset + 8 + size)
.ok_or(ShaderError::Malformed("part data out of bounds"))?;
parts.push(Part {
fourcc,
offset,
data: body,
});
}
Ok(Container {
digest,
version,
parts,
})
}
pub fn part(&self, fourcc: FourCC) -> Option<&Part<'a>> {
self.parts.iter().find(|p| p.fourcc == fourcc)
}
}
pub(crate) fn u16_at(data: &[u8], at: usize) -> Result<u16, ShaderError> {
data.get(at..at + 2)
.map(|b| u16::from_le_bytes(b.try_into().expect("2 bytes")))
.ok_or(ShaderError::Malformed("truncated"))
}
pub(crate) fn u32_at(data: &[u8], at: usize) -> Result<u32, ShaderError> {
data.get(at..at + 4)
.map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes")))
.ok_or(ShaderError::Malformed("truncated"))
}
pub(crate) fn u64_at(data: &[u8], at: usize) -> Result<u64, ShaderError> {
data.get(at..at + 8)
.map(|b| u64::from_le_bytes(b.try_into().expect("8 bytes")))
.ok_or(ShaderError::Malformed("truncated"))
}
/// Builds a container from parts (test helper).
#[cfg(test)]
pub fn build(parts: &[(FourCC, &[u8])]) -> Vec<u8> {
let table = HEADER_SIZE + 4 * parts.len();
let total = table + parts.iter().map(|(_, d)| 8 + d.len()).sum::<usize>();
let mut out = Vec::with_capacity(total);
out.extend_from_slice(b"DXBC");
out.extend_from_slice(&[0; 16]);
out.extend_from_slice(&1u16.to_le_bytes());
out.extend_from_slice(&0u16.to_le_bytes());
out.extend_from_slice(&(total as u32).to_le_bytes());
out.extend_from_slice(&(parts.len() as u32).to_le_bytes());
let mut offset = table;
for (_, d) in parts {
out.extend_from_slice(&(offset as u32).to_le_bytes());
offset += 8 + d.len();
}
for (fourcc, d) in parts {
out.extend_from_slice(&fourcc.0);
out.extend_from_slice(&(d.len() as u32).to_le_bytes());
out.extend_from_slice(d);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trips_parts() {
let bytes = build(&[(FourCC::SFI0, &[1, 2, 3, 4]), (FourCC::HASH, &[9; 20])]);
let c = Container::parse(&bytes).unwrap();
assert_eq!(c.parts.len(), 2);
assert_eq!(c.part(FourCC::SFI0).unwrap().data, &[1, 2, 3, 4]);
assert_eq!(c.part(FourCC::HASH).unwrap().data.len(), 20);
assert!(c.part(FourCC::DXIL).is_none());
}
#[test]
fn rejects_bad_input() {
assert_eq!(Container::parse(b"nope").unwrap_err(), ShaderError::NotDxbc);
let mut bytes = build(&[(FourCC::SFI0, &[0; 8])]);
let last = bytes.len() - 1;
bytes[0x20] = 0xFF; // corrupt the first part offset
assert!(Container::parse(&bytes).is_err());
bytes.truncate(last);
assert!(Container::parse(&bytes).is_err());
}
}
+211
View File
@@ -0,0 +1,211 @@
//! The DXIL program inside a container's `DXIL` (or `STAT`) part.
//!
//! ```text
//! 0x00 program version u32 (kind << 16 | major << 4 | minor)
//! 0x04 size in dwords u32
//! 0x08 "DXIL" <- bitcode offset is relative to here
//! 0x0C dxil version u32
//! 0x10 bitcode offset u32 (16 in standard PC DXIL)
//! 0x14 bitcode size u32
//! ```
use crate::ShaderError;
use crate::dxbc::u32_at;
const LLVM_BITCODE_MAGIC: [u8; 4] = [0x42, 0x43, 0xC0, 0xDE];
#[cfg(test)]
const STANDARD_BITCODE_OFFSET: u32 = 16;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ShaderKind {
Pixel,
Vertex,
Geometry,
Hull,
Domain,
Compute,
Library,
RayGeneration,
Intersection,
AnyHit,
ClosestHit,
Miss,
Callable,
Mesh,
Amplification,
Node,
Unknown(u16),
}
impl ShaderKind {
fn from_raw(v: u16) -> Self {
use ShaderKind::*;
match v {
0 => Pixel,
1 => Vertex,
2 => Geometry,
3 => Hull,
4 => Domain,
5 => Compute,
6 => Library,
7 => RayGeneration,
8 => Intersection,
9 => AnyHit,
10 => ClosestHit,
11 => Miss,
12 => Callable,
13 => Mesh,
14 => Amplification,
15 => Node,
other => Unknown(other),
}
}
}
#[derive(Debug, Clone)]
pub struct DxilProgram<'a> {
pub kind: ShaderKind,
pub shader_model: (u8, u8),
pub dxil_version: u32,
/// LLVM bitcode (starts with `BC C0 DE`).
pub bitcode: &'a [u8],
/// Bytes between the bitcode header and the bitcode. Empty on PC.
pub prefix: &'a [u8],
/// Bytes after the bitcode, up to the program size. Empty on PC.
pub trailer: &'a [u8],
}
/// Xbox additions recognised around the bitcode.
#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
pub struct XboxExtras {
/// The prefix starts with an `XDAT` table.
pub xdat: bool,
/// The trailer contains an `xbop` blob (compiler options).
pub xbop: bool,
}
impl<'a> DxilProgram<'a> {
pub fn parse(part: &'a [u8]) -> Result<Self, ShaderError> {
let version = u32_at(part, 0)?;
let size = (u32_at(part, 4)? as usize)
.checked_mul(4)
.filter(|&s| s <= part.len() && s >= 24)
.ok_or(ShaderError::Malformed(
"program size disagrees with part size",
))?;
let part = &part[..size];
if part.get(8..12) != Some(b"DXIL") {
return Err(ShaderError::Malformed("missing DXIL magic"));
}
let dxil_version = u32_at(part, 12)?;
let offset = u32_at(part, 16)?;
let len = u32_at(part, 20)? as usize;
let start = 8 + offset as usize;
let bitcode = part
.get(start..start + len)
.ok_or(ShaderError::Malformed("bitcode out of bounds"))?;
if bitcode.get(0..4) != Some(&LLVM_BITCODE_MAGIC) {
return Err(ShaderError::Malformed("bitcode lacks LLVM magic"));
}
let prefix = part
.get(24..start)
.ok_or(ShaderError::Malformed("bitcode offset too small"))?;
Ok(DxilProgram {
kind: ShaderKind::from_raw((version >> 16) as u16),
shader_model: (((version >> 4) & 0xF) as u8, (version & 0xF) as u8),
dxil_version,
bitcode,
prefix,
trailer: &part[start + len..],
})
}
/// True for a program laid out exactly like PC DXIL.
pub fn is_standard_layout(&self) -> bool {
self.prefix.is_empty() && self.trailer.is_empty()
}
pub fn xbox_extras(&self) -> XboxExtras {
XboxExtras {
xdat: self.prefix.starts_with(b"XDAT"),
xbop: self.trailer.windows(4).any(|w| w == b"xbop"),
}
}
}
/// Builds a standard PC-layout program around `bitcode` (test helper).
#[cfg(test)]
pub fn build_standard(kind: u16, sm: (u8, u8), dxil_version: u32, bitcode: &[u8]) -> Vec<u8> {
let mut out = Vec::new();
let version = (u32::from(kind) << 16) | (u32::from(sm.0) << 4) | u32::from(sm.1);
let padded = bitcode.len().next_multiple_of(4);
let size_dwords = (24 + padded) / 4;
out.extend_from_slice(&version.to_le_bytes());
out.extend_from_slice(&(size_dwords as u32).to_le_bytes());
out.extend_from_slice(b"DXIL");
out.extend_from_slice(&dxil_version.to_le_bytes());
out.extend_from_slice(&STANDARD_BITCODE_OFFSET.to_le_bytes());
out.extend_from_slice(&(bitcode.len() as u32).to_le_bytes());
out.extend_from_slice(bitcode);
out.resize(24 + padded, 0);
out
}
#[cfg(test)]
mod tests {
use super::*;
fn fake_bitcode() -> Vec<u8> {
let mut b = LLVM_BITCODE_MAGIC.to_vec();
b.extend_from_slice(&[0xAA; 12]);
b
}
#[test]
fn parses_standard_layout() {
let bytes = build_standard(0, (6, 0), 0x100, &fake_bitcode());
let p = DxilProgram::parse(&bytes).unwrap();
assert_eq!(p.kind, ShaderKind::Pixel);
assert_eq!(p.shader_model, (6, 0));
assert!(p.is_standard_layout());
assert_eq!(p.xbox_extras(), XboxExtras::default());
}
#[test]
fn detects_xbox_layout() {
// Xbox layout: XDAT table before the bitcode, xbop blob after it.
let bitcode = fake_bitcode();
let xdat = b"XDAT\x01\x00\x00\x00";
let trailer = b"xbop\x02\x00\x00\x00";
let mut bytes = Vec::new();
let size = 24 + xdat.len() + bitcode.len() + trailer.len();
bytes.extend_from_slice(&((5u32 << 16) | 0x65).to_le_bytes()); // cs_6_5
bytes.extend_from_slice(&((size / 4) as u32).to_le_bytes());
bytes.extend_from_slice(b"DXIL");
bytes.extend_from_slice(&0x105u32.to_le_bytes());
bytes.extend_from_slice(&(16 + xdat.len() as u32).to_le_bytes());
bytes.extend_from_slice(&(bitcode.len() as u32).to_le_bytes());
bytes.extend_from_slice(xdat);
bytes.extend_from_slice(&bitcode);
bytes.extend_from_slice(trailer);
let p = DxilProgram::parse(&bytes).unwrap();
assert_eq!(p.kind, ShaderKind::Compute);
assert_eq!(p.shader_model, (6, 5));
assert!(!p.is_standard_layout());
assert_eq!(
p.xbox_extras(),
XboxExtras {
xdat: true,
xbop: true
}
);
assert_eq!(p.bitcode, &bitcode[..]);
}
#[test]
fn rejects_missing_bitcode_magic() {
let bytes = build_standard(0, (6, 0), 0x100, &[0u8; 16]);
assert!(DxilProgram::parse(&bytes).is_err());
}
}
+447
View File
@@ -0,0 +1,447 @@
//! GFX10 machine code: instruction boundaries, encodings and opcodes.
//!
//! Instructions are found by following control flow from offset 0, not by a
//! linear sweep: compilers place data (constant tables) in the code region
//! after the end of the program. Operand fields are not decoded yet; each
//! instruction keeps its raw dwords.
//!
//! Encodings by the top bits of the first dword:
//!
//! ```text
//! 0xxxxxxx VOP2; 0111111 VOP1; 0111110 VOPC
//! 10 SOP2; 1011 SOPK; 101111101 SOP1; 101111110 SOPC; 101111111 SOPP
//! 110010 VINTRP 110011 VOP3P 110101 VOP3 110110 DS 110111 FLAT/GLOBAL/SCRATCH
//! 111000 MUBUF 111010 MTBUF 111100 MIMG 111101 SMEM 111110 EXP
//! ```
mod opcodes;
use std::collections::BTreeMap;
use crate::ShaderError;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Encoding {
Sop2,
Sopk,
Sop1,
Sopc,
Sopp,
Smem,
Vop2,
Vop1,
Vopc,
Vop3,
Vop3p,
Vintrp,
Ds,
Mubuf,
Mtbuf,
Mimg,
Exp,
Flat,
Global,
Scratch,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Instruction {
/// Byte offset in the program.
pub offset: usize,
pub encoding: Encoding,
pub opcode: u16,
/// Every dword of the instruction, including literals and extra dwords.
pub words: Vec<u32>,
}
impl Instruction {
/// AMD's name for the opcode, if it is in our table.
pub fn name(&self) -> Option<&'static str> {
name(self.encoding, self.opcode)
}
}
/// Decodes every instruction reachable from offset 0, sorted by offset.
pub fn decode(code: &[u8]) -> Result<Vec<Instruction>, ShaderError> {
if !code.len().is_multiple_of(4) {
return Err(isa(code.len(), "code size is not a multiple of 4"));
}
let mut found = BTreeMap::new();
let mut pending = vec![0usize];
while let Some(mut offset) = pending.pop() {
while !found.contains_key(&offset) {
let inst = instruction(code, offset)?;
let next = offset + 4 * inst.words.len();
let flow = match flow(&inst, next, code.len())? {
Flow::Stop if inst.name() == Some("s_setpc_b64") => {
far_jump(&found, &inst, code.len())?.map_or(Flow::Stop, Flow::Jump)
}
flow => flow,
};
found.insert(offset, inst);
match flow {
Flow::Next => offset = next,
Flow::Stop => break,
Flow::Jump(target) => offset = target,
Flow::Branch(target) => {
pending.push(target);
offset = next;
}
}
}
}
let list: Vec<Instruction> = found.into_values().collect();
if let Some(w) = list
.windows(2)
.find(|w| w[0].offset + 4 * w[0].words.len() > w[1].offset)
{
return Err(isa(w[1].offset, "a branch lands inside an instruction"));
}
Ok(list)
}
enum Flow {
Next,
Stop,
Jump(usize),
Branch(usize),
}
fn flow(inst: &Instruction, next: usize, len: usize) -> Result<Flow, ShaderError> {
let target = || {
let delta = 4 * i64::from(inst.words[0] as u16 as i16);
usize::try_from(next as i64 + delta)
.ok()
.filter(|&t| t < len)
.ok_or(isa(inst.offset, "branch target outside the code"))
};
Ok(match (inst.encoding, inst.name().unwrap_or("")) {
(
Encoding::Sopp,
"s_endpgm" | "s_endpgm_saved" | "s_endpgm_ordered_ps_done" | "s_code_end",
) => Flow::Stop,
(Encoding::Sopp, "s_branch") => Flow::Jump(target()?),
(Encoding::Sopp, name) if name.starts_with("s_cbranch_") => Flow::Branch(target()?),
(Encoding::Sopk, "s_call_b64") => Flow::Branch(target()?),
// Indirect jump; `decode` resolves the compiler's far-jump form.
(Encoding::Sop1, "s_setpc_b64") => Flow::Stop,
_ => Flow::Next,
})
}
/// Resolves the far jump compilers emit beyond the reach of a branch offset:
/// `s_getpc_b64 s[n:n+1]`, `s_add_u32|s_sub_u32 sn, sn, literal`, a carry
/// into s(n+1), `s_setpc_b64 s[n:n+1]`, looking back over the straight-line
/// run just decoded. Any other `s_setpc_b64` (e.g. a handover to the next
/// merged stage through registers) gives `None`.
fn far_jump(
found: &BTreeMap<usize, Instruction>,
setpc: &Instruction,
len: usize,
) -> Result<Option<usize>, ShaderError> {
let n = setpc.words[0] & 0xFF;
let mut delta = None;
let mut at = setpc.offset;
for _ in 0..4 {
let Some((_, prev)) = found.range(..at).next_back() else {
break;
};
if prev.offset + 4 * prev.words.len() != at {
break;
}
let w = prev.words[0];
let (sdst, ssrc0, ssrc1) = ((w >> 16) & 0x7F, w & 0xFF, (w >> 8) & 0xFF);
match (prev.encoding, prev.name()) {
(Encoding::Sop2, Some(op @ ("s_add_u32" | "s_sub_u32")))
if sdst == n && ssrc0 == n && ssrc1 == 0xFF && delta.is_none() =>
{
let literal = i64::from(prev.words[1]);
delta = Some(if op == "s_add_u32" { literal } else { -literal });
}
(Encoding::Sop1, Some("s_getpc_b64")) if sdst == n => {
let Some(delta) = delta else { break };
// s_getpc_b64 yields the address of the instruction after it.
return usize::try_from(prev.offset as i64 + 4 + delta)
.ok()
.filter(|&t| t < len)
.map(Some)
.ok_or(isa(setpc.offset, "far jump target outside the code"));
}
_ => {}
}
at = prev.offset;
}
Ok(None)
}
fn instruction(code: &[u8], offset: usize) -> Result<Instruction, ShaderError> {
let word = |i: usize| {
code.get(offset + 4 * i..offset + 4 * i + 4)
.map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes")))
.ok_or(isa(offset, "instruction runs past the end of the code"))
};
let w = word(0)?;
let (encoding, opcode, len) = if w >> 31 == 0 {
let src0 = w & 0x1FF;
// Literal constant, SDWA, DPP16, DPP8, DPP8 with fetch-inactive.
let extra = usize::from(matches!(src0, 0xFF | 0xF9 | 0xFA | 0xE9 | 0xEA));
match w >> 25 {
0x3F => (Encoding::Vop1, (w >> 9) & 0xFF, 1 + extra),
0x3E => (Encoding::Vopc, (w >> 17) & 0xFF, 1 + extra),
op => {
let mk_ak = name(Encoding::Vop2, op as u16).is_some_and(|n| {
matches!(
n,
"v_madmk_f32"
| "v_madak_f32"
| "v_fmamk_f32"
| "v_fmaak_f32"
| "v_madmk_f16"
| "v_madak_f16"
| "v_fmamk_f16"
| "v_fmaak_f16"
)
});
(Encoding::Vop2, op, 1 + extra.max(usize::from(mk_ak)))
}
}
} else if w >> 30 == 0b10 {
let literal = |srcs: &[u32]| 1 + usize::from(srcs.contains(&0xFF));
match w >> 23 {
0x17D => (Encoding::Sop1, (w >> 8) & 0xFF, literal(&[w & 0xFF])),
0x17E => (
Encoding::Sopc,
(w >> 16) & 0x7F,
literal(&[w & 0xFF, (w >> 8) & 0xFF]),
),
0x17F => (Encoding::Sopp, (w >> 16) & 0x7F, 1),
_ if w >> 28 == 0b1011 => {
let op = (w >> 23) & 0x1F;
let imm32 = name(Encoding::Sopk, op as u16) == Some("s_setreg_imm32_b32");
(Encoding::Sopk, op, 1 + usize::from(imm32))
}
_ => (
Encoding::Sop2,
(w >> 23) & 0x7F,
literal(&[w & 0xFF, (w >> 8) & 0xFF]),
),
}
} else {
let vop3 =
|w1: u32| 2 + usize::from([w1, w1 >> 9, w1 >> 18].iter().any(|s| s & 0x1FF == 0xFF));
match w >> 26 {
0x32 => (Encoding::Vintrp, (w >> 16) & 0x3, 1),
0x33 => (Encoding::Vop3p, (w >> 16) & 0x7F, vop3(word(1)?)),
0x35 => (Encoding::Vop3, (w >> 16) & 0x3FF, vop3(word(1)?)),
0x36 => (Encoding::Ds, (w >> 18) & 0xFF, 2),
0x37 => {
let encoding = match (w >> 14) & 3 {
0 => Encoding::Flat,
1 => Encoding::Scratch,
2 => Encoding::Global,
_ => return Err(isa(offset, "reserved FLAT segment")),
};
(encoding, (w >> 18) & 0x7F, 2)
}
0x38 => (Encoding::Mubuf, (w >> 18) & 0x7F | (w >> 25 & 1) << 7, 2),
0x3A => (
Encoding::Mtbuf,
(w >> 16) & 0x7 | (word(1)? >> 21 & 1) << 3,
2,
),
// Bits 2:1 count extra dwords of non-sequential address registers.
0x3C => (
Encoding::Mimg,
(w >> 18) & 0x7F | (w & 1) << 7,
2 + (w as usize >> 1 & 3),
),
0x3D => (Encoding::Smem, (w >> 18) & 0xFF, 2),
0x3E => (Encoding::Exp, 0, 2),
_ => return Err(isa(offset, "unknown encoding")),
}
};
Ok(Instruction {
offset,
encoding,
opcode: opcode as u16,
words: (0..len).map(word).collect::<Result<_, _>>()?,
})
}
fn name(encoding: Encoding, opcode: u16) -> Option<&'static str> {
use opcodes as t;
let (table, op) = match encoding {
Encoding::Sop2 => (t::SOP2, opcode),
Encoding::Sopk => (t::SOPK, opcode),
Encoding::Sop1 => (t::SOP1, opcode),
Encoding::Sopc => (t::SOPC, opcode),
Encoding::Sopp => (t::SOPP, opcode),
Encoding::Smem => (t::SMEM, opcode),
Encoding::Vop2 => (t::VOP2, opcode),
Encoding::Vop1 => (t::VOP1, opcode),
Encoding::Vopc => (t::VOPC, opcode),
// VOP3 also encodes the VOPC, VOP2 and VOP1 opcodes at fixed bases.
Encoding::Vop3 => match opcode {
0x000..0x100 => (t::VOPC, opcode),
0x100..0x140 => (t::VOP2, opcode - 0x100),
0x180..0x200 => (t::VOP1, opcode - 0x180),
_ => (t::VOP3, opcode),
},
Encoding::Vop3p => (t::VOP3P, opcode),
Encoding::Vintrp => (t::VINTRP, opcode),
Encoding::Ds => (t::DS, opcode),
Encoding::Mubuf => (t::MUBUF, opcode),
Encoding::Mtbuf => (t::MTBUF, opcode),
Encoding::Mimg => (t::MIMG, opcode),
Encoding::Exp => return Some("exp"),
Encoding::Flat => (t::FLAT, opcode),
Encoding::Global => (t::GLOBAL, opcode),
Encoding::Scratch => (t::SCRATCH, opcode),
};
table
.binary_search_by_key(&op, |&(o, _)| o)
.ok()
.map(|i| table[i].1)
}
fn isa(offset: usize, reason: &'static str) -> ShaderError {
ShaderError::Isa { offset, reason }
}
#[cfg(test)]
mod tests {
use super::*;
const S_ENDPGM: u32 = 0xBF81_0000;
/// s_branch / s_cbranch_scc0 with a dword offset relative to the next instruction.
const fn sopp(op: u32, simm16: i16) -> u32 {
0xBF80_0000 | op << 16 | simm16 as u16 as u32
}
fn bytes(words: &[u32]) -> Vec<u8> {
words.iter().flat_map(|w| w.to_le_bytes()).collect()
}
fn summary(code: &[u32]) -> Vec<(usize, usize, &'static str)> {
decode(&bytes(code))
.unwrap()
.iter()
.map(|i| (i.offset, i.words.len(), i.name().unwrap_or("?")))
.collect()
}
#[test]
fn tables_are_sorted() {
for t in [
opcodes::SOP2,
opcodes::SOPK,
opcodes::SOP1,
opcodes::SOPC,
opcodes::SOPP,
opcodes::SMEM,
opcodes::VOP2,
opcodes::VOP1,
opcodes::VOPC,
opcodes::VOP3,
opcodes::VOP3P,
opcodes::VINTRP,
opcodes::DS,
opcodes::MUBUF,
opcodes::MTBUF,
opcodes::MIMG,
opcodes::FLAT,
opcodes::GLOBAL,
opcodes::SCRATCH,
] {
assert!(t.windows(2).all(|w| w[0].0 < w[1].0));
}
}
#[test]
fn lengths_and_names() {
let code = [
0xBE80_03FF,
0x3F80_0000, // s_mov_b32 s0, literal
0x0600_0000, // v_add_f32 v0, s0, v0
0xD54B_0000,
0x03FE_0000,
0x4000_0000, // v_fma_f32 with a literal src2
0xF080_0F0A,
0,
0, // image_sample (2D) with one extra address dword
0xF800_080F,
0, // exp
S_ENDPGM,
];
assert_eq!(
summary(&code),
[
(0, 2, "s_mov_b32"),
(8, 1, "v_add_f32"),
(12, 3, "v_fma_f32"),
(24, 3, "image_sample"),
(36, 2, "exp"),
(44, 1, "s_endpgm"),
]
);
}
#[test]
fn follows_branches_and_skips_data() {
let code = [
sopp(0x04, 1), // s_cbranch_scc0 -> 8
sopp(0x02, 1), // s_branch -> 12
S_ENDPGM,
S_ENDPGM,
S_ENDPGM, // data follows the program end
0xFFFF_FFFF,
];
let found: Vec<_> = summary(&code).iter().map(|i| i.0).collect();
assert_eq!(found, [0, 4, 8, 12]);
}
#[test]
fn follows_far_jumps() {
let code = [
0xBE88_1F00, // s_getpc_b64 s[8:9]
0x8008_FF08,
20, // s_add_u32 s8, s8, 20 -> 4 + 20 = 24
0x8209_8009, // s_addc_u32 s9, s9, 0
0xBE80_2008, // s_setpc_b64 s[8:9]
0xFFFF_FFFF, // not code
S_ENDPGM,
];
let found: Vec<_> = summary(&code).iter().map(|i| (i.0, i.2)).collect();
assert_eq!(
found,
[
(0, "s_getpc_b64"),
(4, "s_add_u32"),
(12, "s_addc_u32"),
(16, "s_setpc_b64"),
(24, "s_endpgm"),
]
);
// Through other registers (a handover to another stage): the path ends.
assert_eq!(summary(&[0xBE80_2018, S_ENDPGM]).len(), 1);
}
#[test]
fn rejects_bad_code() {
assert!(decode(&[0; 3]).is_err(), "size not a multiple of 4");
assert!(
decode(&bytes(&[sopp(0x02, 100)])).is_err(),
"branch out of range"
);
assert!(
decode(&bytes(&[0xBE80_03FF])).is_err(),
"literal past the end"
);
assert!(
decode(&bytes(&[0xE400_0000, 0])).is_err(),
"unknown encoding"
);
// s_cbranch_scc0 into the literal of the s_mov_b32 at 4.
assert!(decode(&bytes(&[sopp(0x04, 1), 0xBE80_03FF, S_ENDPGM, S_ENDPGM])).is_err());
}
}
File diff suppressed because it is too large. Load diff
+26
View File
@@ -0,0 +1,26 @@
//! Xbox Series shaders to host shaders.
//!
//! An Xbox Series shader is a standard DXBC container ([`dxbc`]). Its `DXIL`
//! part ([`dxil`]) may carry Xbox additions around the LLVM bitcode: an
//! `XDAT` table before it indexing blobs after it, among them `xbop`
//! (compiler options) and the zlib-compressed GFX10 code. The bitcode may use
//! console-only intrinsics, so the GFX10 code is translated in general.
pub mod dxbc;
pub mod dxil;
pub mod gfx10;
pub mod native;
pub use dxbc::{Container, FourCC, Part};
pub use dxil::{DxilProgram, ShaderKind, XboxExtras};
pub use native::{HwStage, NativeProgram, native_programs};
#[derive(Debug, thiserror::Error, PartialEq, Eq)]
pub enum ShaderError {
#[error("not a DXBC container")]
NotDxbc,
#[error("malformed shader: {0}")]
Malformed(&'static str),
#[error("GFX10 code at {offset:#x}: {reason}")]
Isa { offset: usize, reason: &'static str },
}
+288
View File
@@ -0,0 +1,288 @@
//! Native GFX10 programs that the console compiler stores in a `DXIL` part.
//!
//! An `XDAT` index after the program header lists blobs stored around the
//! bitcode; one or more of them hold native programs, zlib-packed (a vertex
//! shader can carry two: compiled for use with and without a geometry
//! shader). Layout as observed in shipped titles (index offsets are relative
//! to the part data):
//!
//! ```text
//! +0x18 "XDAT" u32 entry count, u32 (0x24 seen), then per entry:
//! u32 kind, u32 offset, u32 size
//! kind 0x0d "XBCH" u32 version (3), u64 packed size, u64 unpacked size,
//! zlib stream
//! unpacked "FSSM" u32 version (0x101), u64 payload size, payload
//! payload +0x00 u64 graphics slot count (6)
//! +0x08 u64 record offsets: LS HS ES GS VS PS (0x08..0x30),
//! mesh 0x48, compute 0x60; unused ones are 0xDEADBEEF_DEADBEEF
//! record +0x00 u64 code offset, +0x08 u64 code size (payload-relative)
//! ```
//!
//! Other kinds seen: 0x07 program header + bitcode (or a stub when stripped),
//! 0x0a `xbop` (compiler options), 0x0e a table not decoded yet, 0x10 and
//! 0x12 16-byte blobs (0x10 is the shader hash).
//! Unknown versions are rejected so a format change shows up as an error.
use crate::ShaderError::{self, Malformed};
use crate::dxbc::{u32_at, u64_at};
const XDAT_OFFSET: usize = 0x18;
const MAX_XDAT_ENTRIES: usize = 64;
const KIND_NATIVE: u32 = 0x0d;
const XBCH_VERSION: u32 = 3;
const XBCH_HEADER: usize = 0x18;
const FSSM_VERSION: u32 = 0x101;
const FSSM_HEADER: usize = 0x10;
const GRAPHICS_SLOT_COUNT: u64 = 6;
/// Where each stage's record offset sits in the FSSM payload.
const SLOTS: [(HwStage, usize); 8] = [
(HwStage::Ls, 0x08),
(HwStage::Hs, 0x10),
(HwStage::Es, 0x18),
(HwStage::Gs, 0x20),
(HwStage::Vs, 0x28),
(HwStage::Ps, 0x30),
(HwStage::Ms, 0x48),
(HwStage::Cs, 0x60),
];
const ABSENT: u64 = 0xDEAD_BEEF_DEAD_BEEF;
/// Unpacked blobs are a few KiB; refuse to allocate for absurd sizes.
const MAX_UNPACKED: u64 = 16 << 20;
/// Hardware shader stage a native program runs as.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum HwStage {
Ls,
Hs,
Es,
Gs,
Vs,
Ps,
/// Mesh shader.
Ms,
Cs,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NativeProgram {
pub stage: HwStage,
/// GFX10 machine code.
pub code: Vec<u8>,
}
/// The native programs in a `DXIL` part's data; empty for the PC layout.
pub fn native_programs(part: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> {
if part.get(XDAT_OFFSET..XDAT_OFFSET + 4) != Some(b"XDAT") {
return Ok(Vec::new());
}
let count = u32_at(part, XDAT_OFFSET + 4)? as usize;
if count > MAX_XDAT_ENTRIES {
return Err(Malformed("implausible XDAT entry count"));
}
let mut out = Vec::new();
for i in 0..count {
let at = XDAT_OFFSET + 12 + 12 * i;
if u32_at(part, at)? != KIND_NATIVE {
continue;
}
let offset = u32_at(part, at + 4)?.into();
let size = u32_at(part, at + 8)?.into();
let blob = bytes(part, offset, size).ok_or(Malformed("XDAT entry out of bounds"))?;
out.extend(programs(&unpack(blob)?)?);
}
Ok(out)
}
fn unpack(blob: &[u8]) -> Result<Vec<u8>, ShaderError> {
if blob.get(0..4) != Some(b"XBCH") {
return Err(Malformed("native blob lacks XBCH magic"));
}
if u32_at(blob, 4)? != XBCH_VERSION {
return Err(Malformed("unknown XBCH version"));
}
let packed = u64_at(blob, 8)?;
let unpacked = u64_at(blob, 16)?;
if unpacked > MAX_UNPACKED {
return Err(Malformed("implausible XBCH unpacked size"));
}
let stream =
bytes(blob, XBCH_HEADER as u64, packed).ok_or(Malformed("XBCH stream out of bounds"))?;
let out = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(stream, unpacked as usize)
.map_err(|_| Malformed("XBCH stream does not inflate to its stated size"))?;
if out.len() as u64 != unpacked {
return Err(Malformed("XBCH stream does not inflate to its stated size"));
}
Ok(out)
}
fn programs(fssm: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> {
if fssm.get(0..4) != Some(b"FSSM") {
return Err(Malformed("native blob lacks FSSM magic"));
}
if u32_at(fssm, 4)? != FSSM_VERSION {
return Err(Malformed("unknown FSSM version"));
}
let payload = &fssm[FSSM_HEADER.min(fssm.len())..];
if u64_at(fssm, 8)? != payload.len() as u64 {
return Err(Malformed("FSSM payload size disagrees"));
}
if u64_at(payload, 0)? != GRAPHICS_SLOT_COUNT {
return Err(Malformed("unexpected FSSM slot count"));
}
let mut out = Vec::new();
for (stage, at) in SLOTS {
let record = u64_at(payload, at)?;
if record == ABSENT {
continue;
}
let record = bytes(payload, record, 16).ok_or(Malformed("FSSM record out of bounds"))?;
let code = bytes(payload, u64_at(record, 0)?, u64_at(record, 8)?)
.ok_or(Malformed("native code out of bounds"))?;
out.push(NativeProgram {
stage,
code: code.to_vec(),
});
}
Ok(out)
}
/// `data[offset..offset + len]` with untrusted 64-bit bounds.
fn bytes(data: &[u8], offset: u64, len: u64) -> Option<&[u8]> {
let start = usize::try_from(offset).ok()?;
data.get(start..start.checked_add(usize::try_from(len).ok()?)?)
}
#[cfg(test)]
mod tests {
use super::*;
const VS_CODE: [u8; 8] = [1, 2, 3, 4, 5, 6, 7, 8];
const PS_CODE: [u8; 4] = [9, 10, 11, 12];
fn slot(stage: HwStage) -> usize {
SLOTS.iter().find(|s| s.0 == stage).unwrap().1
}
/// FSSM blob with `programs` as (stage, code) pairs.
fn fssm(programs: &[(HwStage, &[u8])]) -> Vec<u8> {
let mut payload = GRAPHICS_SLOT_COUNT.to_le_bytes().to_vec();
payload.resize(slot(HwStage::Cs) + 8, 0);
for (_, at) in SLOTS {
payload[at..at + 8].copy_from_slice(&ABSENT.to_le_bytes());
}
for &(stage, code) in programs {
let slot = slot(stage);
let record = payload.len() as u64;
payload[slot..slot + 8].copy_from_slice(&record.to_le_bytes());
payload.extend_from_slice(&(record + 16).to_le_bytes());
payload.extend_from_slice(&(code.len() as u64).to_le_bytes());
payload.extend_from_slice(code);
}
let mut out = b"FSSM".to_vec();
out.extend_from_slice(&FSSM_VERSION.to_le_bytes());
out.extend_from_slice(&(payload.len() as u64).to_le_bytes());
out.extend_from_slice(&payload);
out
}
fn xbch(unpacked: &[u8]) -> Vec<u8> {
let stream = miniz_oxide::deflate::compress_to_vec_zlib(unpacked, 6);
let mut out = b"XBCH".to_vec();
out.extend_from_slice(&XBCH_VERSION.to_le_bytes());
out.extend_from_slice(&(stream.len() as u64).to_le_bytes());
out.extend_from_slice(&(unpacked.len() as u64).to_le_bytes());
out.extend_from_slice(&stream);
out
}
/// `DXIL` part data: program header, XDAT index, then the blobs.
fn part(blobs: &[(u32, &[u8])]) -> Vec<u8> {
let mut out = vec![0u8; XDAT_OFFSET];
out.extend_from_slice(b"XDAT");
out.extend_from_slice(&(blobs.len() as u32).to_le_bytes());
out.extend_from_slice(&0x24u32.to_le_bytes());
let mut offset = out.len() + 12 * blobs.len();
for (kind, blob) in blobs {
for v in [*kind, offset as u32, blob.len() as u32] {
out.extend_from_slice(&v.to_le_bytes());
}
offset += blob.len();
}
for (_, blob) in blobs {
out.extend_from_slice(blob);
}
out
}
#[test]
fn finds_graphics_programs() {
let native = xbch(&fssm(&[(HwStage::Vs, &VS_CODE), (HwStage::Ps, &PS_CODE)]));
let data = part(&[(0x0a, b"xbop"), (KIND_NATIVE, &native)]);
let found = native_programs(&data).unwrap();
assert_eq!(
found,
[
NativeProgram {
stage: HwStage::Vs,
code: VS_CODE.to_vec()
},
NativeProgram {
stage: HwStage::Ps,
code: PS_CODE.to_vec()
},
]
);
}
#[test]
fn finds_mesh_and_compute_programs() {
for stage in [HwStage::Ms, HwStage::Cs] {
let data = part(&[(KIND_NATIVE, &xbch(&fssm(&[(stage, &VS_CODE)])))]);
let found = native_programs(&data).unwrap();
assert_eq!(found.len(), 1);
assert_eq!(found[0].stage, stage);
}
}
#[test]
fn reads_every_native_blob() {
let es = xbch(&fssm(&[(HwStage::Es, &VS_CODE)]));
let vs = xbch(&fssm(&[(HwStage::Vs, &VS_CODE)]));
let data = part(&[(0x12, &[0; 16]), (KIND_NATIVE, &es), (KIND_NATIVE, &vs)]);
let stages: Vec<_> = native_programs(&data)
.unwrap()
.iter()
.map(|p| p.stage)
.collect();
assert_eq!(stages, [HwStage::Es, HwStage::Vs]);
}
#[test]
fn pc_layout_has_none() {
assert!(native_programs(&[0u8; 64]).unwrap().is_empty());
assert!(
native_programs(&part(&[(0x0a, b"xbop")]))
.unwrap()
.is_empty()
);
}
#[test]
fn rejects_corrupt_blobs() {
let good = xbch(&fssm(&[(HwStage::Ls, &VS_CODE)]));
let corrupt = |at: usize, byte: u8| {
let mut blob = good.clone();
blob[at] = byte;
native_programs(&part(&[(KIND_NATIVE, &blob)]))
};
assert!(corrupt(4, 9).is_err(), "unknown version");
assert!(corrupt(16, 0xFF).is_err(), "stated size");
assert!(corrupt(XBCH_HEADER + 2, 0xFF).is_err(), "zlib stream");
assert!(native_programs(&part(&[(KIND_NATIVE, &good[..20])])).is_err());
let mut bad_record = fssm(&[(HwStage::Ls, &VS_CODE)]);
let at = FSSM_HEADER + slot(HwStage::Ls);
bad_record[at..at + 8].copy_from_slice(&u64::MAX.to_le_bytes());
assert!(native_programs(&part(&[(KIND_NATIVE, &xbch(&bad_record))])).is_err());
}
}