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. Whatever the format does not define (an opcode outside the instruction
12//! set of the program's version, a register type it has no name for, a reserved bit set, an instruction whose length
13//! disagrees with its operands) is an [`Error`] naming the 32-bit word where it is; it never panics on untrusted input.
14//!
15//! ```
16//! # fn main() -> Result<(), d3d9_reader::Error> {
17//! // ps_2_0: dcl t0.xy; dcl_2d s0; texld r0, t0, s0; mov oC0, r0; end
18//! let words: [u32; 14] = [
19//! 0xffff_0200,
20//! 0x0200_001f, 0x8000_0000, 0xb003_0000,
21//! 0x0200_001f, 0x9000_0000, 0xa00f_0800,
22//! 0x0300_0042, 0x800f_0000, 0xb0e4_0000, 0xa0e4_0800,
23//! 0x0200_0001, 0x800f_0800, 0x80e4_0000,
24//! ];
25//! let bytes: Vec<u8> = words.iter().chain(&[0xffff]).flat_map(|w| w.to_le_bytes()).collect();
26//! let program = d3d9_reader::read(&bytes)?;
27//! assert_eq!(program.version.to_string(), "ps_2_0");
28//! assert_eq!(program.declarations().count(), 2);
29//! let names: Vec<_> = program.instructions().map(|i| i.opcode.name()).collect();
30//! assert_eq!(names, ["tex", "mov"]);
31//! # Ok(()) }
32//! ```
33#![deny(
34 clippy::arithmetic_side_effects,
35 clippy::indexing_slicing,
36 clippy::cast_possible_truncation
37)]
38#![deny(missing_docs)]
39#![deny(clippy::disallowed_methods, clippy::disallowed_types)]
40
41mod ctab;
42mod debug;
43mod disasm;
44mod opcodes;
45mod program;
46
47pub use ctab::{Constant, ConstantTable, Type, TypeMember};
48pub use debug::{DebugInfo, Location, SourceLine, Variable};
49pub use disasm::{Options, disassemble, disassemble_with};
50pub use opcodes::Opcode;
51pub use program::{
52 Comment, Comparison, Declaration, Declared, Definition, Destination, Instruction, Item, Literal,
53 Modifier, Program, Records, Register, RegisterType, Relative, Source, TextureType, frame, read, records,
54};
55
56/// Something the reader can't read: the 32-bit word of the token stream where it is (the version token is word 0), and
57/// what was expected there or found instead.
58#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
59#[error("D3D9 at word {word}: {detail}")]
60pub struct Error {
61 /// The word offset from the version token.
62 pub word: usize,
63 /// What was expected there, or what was found instead.
64 pub detail: String,
65}
66
67/// The reader's result: an [`Error`] naming the word where reading failed.
68pub type Result<T> = std::result::Result<T, Error>;
69
70pub(crate) fn error(word: usize, detail: impl Into<String>) -> Error {
71 Error {
72 word,
73 detail: detail.into(),
74 }
75}
76
77/// The stage a program is for: the high 16 bits of its version token, `0xfffe` vertex and `0xffff` pixel.
78#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
79pub enum Stage {
80 /// A vertex program (`vs_*`).
81 Vertex,
82 /// A pixel program (`ps_*`).
83 Pixel,
84}
85
86/// A program's version token: the stage, and the major and minor version in its low 16 bits.
87///
88/// 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
89/// 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`
90/// compile to it), 3.0, 2.255 and 3.255.
91#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
92pub struct Version {
93 /// Vertex or pixel.
94 pub stage: Stage,
95 /// Bits 8 to 15 of the token.
96 pub major: u8,
97 /// Bits 0 to 7 of the token; 255 for a software version.
98 pub minor: u8,
99}
100
101impl Version {
102 /// The version of a version token, `None` for a token that is not one of the versions this reader reads.
103 pub fn from_token(token: u32) -> Option<Self> {
104 let [minor, major, ..] = token.to_le_bytes();
105 let stage = match token >> 16 {
106 0xfffe => Stage::Vertex,
107 0xffff => Stage::Pixel,
108 _ => return None,
109 };
110 let known = matches!(
111 (stage, major, minor),
112 (Stage::Vertex, 1, 0 | 1) | (Stage::Pixel, 1, 0..=4) | (_, 2, 0 | 1 | 255) | (_, 3, 0 | 255)
113 );
114 known.then_some(Self { stage, major, minor })
115 }
116
117 /// The version token.
118 pub fn token(self) -> u32 {
119 let stage: u32 = match self.stage {
120 Stage::Vertex => 0xfffe,
121 Stage::Pixel => 0xffff,
122 };
123 (stage << 16) | (u32::from(self.major) << 8) | u32::from(self.minor)
124 }
125}
126
127impl std::fmt::Display for Version {
128 /// The profile name as Microsoft's disassembler writes it: `vs_1_1`, `ps_2_x`, `vs_3_sw`.
129 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
130 let stage = match self.stage {
131 Stage::Vertex => "vs",
132 Stage::Pixel => "ps",
133 };
134 match (self.major, self.minor) {
135 (2, 1) => write!(f, "{stage}_2_x"),
136 (major, 255) => write!(f, "{stage}_{major}_sw"),
137 (major, minor) => write!(f, "{stage}_{major}_{minor}"),
138 }
139 }
140}