Skip to main content

d3d9_reader/
lib.rs

1//! A reader of Direct3D 9 shader bytecode: the token stream a Direct3D 9 compiler or assembler writes for a vertex or
2//! pixel program of Shader Model 1.x, 2.x or 3.0, from its version token to `END`, with no container around it.
3//!
4//! [`read`] decodes the stream into typed records in stream order ([`Program::items`]): every comment, every
5//! declaration (`dcl`), every literal definition (`def`, `defi`, `defb`) and every instruction with its opcode, control
6//! bits, co-issue and predicate, destination (register, write mask, saturate, partial precision, centroid, the pixel 1.x
7//! result shift) and sources (register, swizzle, modifier, relative address). The `CTAB` comment D3DX writes is decoded
8//! as well ([`ConstantTable`]), and so is the `DBUG` comment of a `/Zi` build ([`DebugInfo`]). [`frame`] reads the first program of a buffer that holds more after it.
9//!
10//! It reads and checks bytes and never interprets them for an API: registers are Direct3D's register types and numbers,
11//! modifiers and usages Direct3D's own values. An instruction, register type or operand flag of another version (a
12//! pixel instruction in a vertex program, `i0` in vs_1_1, predication in 2.0) is read, as Microsoft's disassembler lists
13//! it. Whatever the format does not define (an opcode or register type with no name, a version that is none of 1.0 to
14//! 3.0, a reserved bit set, an instruction whose length disagrees with its operands) is an [`Error`] naming the 32-bit
15//! word where it is, where Microsoft's disassembler lists such a stream as garbage (`???`, `ps_2_254`); it never panics
16//! on untrusted input.
17//!
18//! ```
19//! # fn main() -> Result<(), d3d9_reader::Error> {
20//! // ps_2_0: dcl t0.xy; dcl_2d s0; texld r0, t0, s0; mov oC0, r0; end
21//! let words: [u32; 14] = [
22//!     0xffff_0200,
23//!     0x0200_001f, 0x8000_0000, 0xb003_0000,
24//!     0x0200_001f, 0x9000_0000, 0xa00f_0800,
25//!     0x0300_0042, 0x800f_0000, 0xb0e4_0000, 0xa0e4_0800,
26//!     0x0200_0001, 0x800f_0800, 0x80e4_0000,
27//! ];
28//! let bytes: Vec<u8> = words.iter().chain(&[0xffff]).flat_map(|w| w.to_le_bytes()).collect();
29//! let program = d3d9_reader::read(&bytes)?;
30//! assert_eq!(program.version.to_string(), "ps_2_0");
31//! assert_eq!(program.declarations().count(), 2);
32//! let names: Vec<_> = program.instructions().map(|i| i.opcode.name()).collect();
33//! assert_eq!(names, ["tex", "mov"]);
34//! # Ok(()) }
35//! ```
36#![deny(
37    clippy::arithmetic_side_effects,
38    clippy::indexing_slicing,
39    clippy::cast_possible_truncation
40)]
41#![deny(missing_docs)]
42#![deny(clippy::disallowed_methods, clippy::disallowed_types)]
43
44mod ctab;
45mod debug;
46mod disasm;
47mod opcodes;
48mod program;
49
50pub use ctab::{Constant, ConstantTable, Type, TypeMember};
51pub use debug::{DebugInfo, Location, SourceLine, Variable};
52pub use disasm::{Options, disassemble, disassemble_with};
53pub use opcodes::Opcode;
54pub use program::{
55    Comment, Comparison, Declaration, Declared, Definition, Destination, Instruction, Item, Literal,
56    Modifier, Program, Records, Register, RegisterType, Relative, Source, TextureType, frame, read, records,
57};
58
59/// Something the reader can't read: the 32-bit word of the token stream where it is (the version token is word 0), and
60/// what was expected there or found instead.
61#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
62#[error("D3D9 at word {word}: {detail}")]
63pub struct Error {
64    /// The word offset from the version token.
65    pub word: usize,
66    /// What was expected there, or what was found instead.
67    pub detail: String,
68}
69
70/// The reader's result: an [`Error`] naming the word where reading failed.
71pub type Result<T> = std::result::Result<T, Error>;
72
73pub(crate) fn error(word: usize, detail: impl Into<String>) -> Error {
74    Error {
75        word,
76        detail: detail.into(),
77    }
78}
79
80/// The stage a program is for: the high 16 bits of its version token, `0xfffe` vertex and `0xffff` pixel.
81#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
82pub enum Stage {
83    /// A vertex program (`vs_*`).
84    Vertex,
85    /// A pixel program (`ps_*`).
86    Pixel,
87}
88
89/// A program's version token: the stage, and the major and minor version in its low 16 bits.
90///
91/// The versions read are vertex 1.0, 1.1, 2.0, 2.1 (`vs_2_x`, which `vs_2_a` compiles to), 3.0 and the software
92/// versions 2.255 and 3.255 (`vs_2_sw`, `vs_3_sw`), and pixel 1.0 to 1.4, 2.0, 2.1 (`ps_2_x`: `ps_2_a` and `ps_2_b`
93/// compile to it), 3.0, 2.255 and 3.255.
94#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
95pub struct Version {
96    /// Vertex or pixel.
97    pub stage: Stage,
98    /// Bits 8 to 15 of the token.
99    pub major: u8,
100    /// Bits 0 to 7 of the token; 255 for a software version.
101    pub minor: u8,
102}
103
104impl Version {
105    /// The version of a version token, `None` for a token that is not one of the versions this reader reads.
106    pub fn from_token(token: u32) -> Option<Self> {
107        let [minor, major, ..] = token.to_le_bytes();
108        let stage = match token >> 16 {
109            0xfffe => Stage::Vertex,
110            0xffff => Stage::Pixel,
111            _ => return None,
112        };
113        let known = matches!(
114            (stage, major, minor),
115            (Stage::Vertex, 1, 0 | 1) | (Stage::Pixel, 1, 0..=4) | (_, 2, 0 | 1 | 255) | (_, 3, 0 | 255)
116        );
117        known.then_some(Self { stage, major, minor })
118    }
119
120    /// The version token.
121    pub fn token(self) -> u32 {
122        let stage: u32 = match self.stage {
123            Stage::Vertex => 0xfffe,
124            Stage::Pixel => 0xffff,
125        };
126        (stage << 16) | (u32::from(self.major) << 8) | u32::from(self.minor)
127    }
128}
129
130impl std::fmt::Display for Version {
131    /// The profile name as Microsoft's disassembler writes it: `vs_1_1`, `ps_2_x`, `vs_3_sw`.
132    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
133        let stage = match self.stage {
134            Stage::Vertex => "vs",
135            Stage::Pixel => "ps",
136        };
137        match (self.major, self.minor) {
138            (2, 1) => write!(f, "{stage}_2_x"),
139            (major, 255) => write!(f, "{stage}_{major}_sw"),
140            (major, minor) => write!(f, "{stage}_{major}_{minor}"),
141        }
142    }
143}