Skip to main content

frostbite_formats/
bytecode.rs

1//! CompiledBytecode resources (type [`RTYPE`], named `shaders/bytecode/<guid>`): a program's compiled form as skate.'s
2//! shader database holds it. A resource is a relocatable payload (its 16-byte metadata gives the payload size, then
3//! the relocation size) that begins with a header and holds one DXBC container with a DXIL part (Shader Model 6), or
4//! two (a raytracing pipeline's, whose header names `RPTR` at offset 0x20 where the others name `RC2S`); more bytes
5//! follow a container in most resources. The header's fields are not interpreted here: the bytes before the first
6//! container and after each container are kept as stored. A container is found by its magic and delimited by its own
7//! size field; a magic that is not a container is an error, not skipped.
8
9use crate::{Error, Rd, Result, bad};
10
11const W: &str = "compiled bytecode";
12/// The resource type id of a CompiledBytecode resource.
13pub const RTYPE: u32 = 0x0E2B_02F7;
14/// The offset of the four-byte tag (`RC2S`, `RPTR`) a payload's header carries.
15pub const TAG_AT: usize = 0x20;
16const MAGIC: &[u8; 4] = b"DXBC";
17
18/// A container's place in a payload: its offset and its size, as its own header states it.
19#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub struct Span {
21    /// Byte offset of the container's `DXBC` magic within the payload.
22    pub offset: usize,
23    /// The container's size in bytes, from its own header (offset 24); the container ends at `offset + size`.
24    pub size: usize,
25}
26
27/// The payload's tag at [`TAG_AT`], if it has one.
28pub fn tag(payload: &[u8]) -> Option<[u8; 4]> {
29    payload.get(TAG_AT..)?.first_chunk().copied()
30}
31
32/// A container header at `at`: the magic, version 1.0, a size that holds the part directory and lies within the
33/// payload, and a directory of parts that lie within the container. `Ok(size)` when it is one.
34fn header(payload: &[u8], at: usize) -> Result<usize> {
35    let r = Rd::new(payload, W);
36    let word = |o: usize| -> Result<usize> {
37        let w = r.u32le(at.saturating_add(o)).map_err(|_| {
38            bad(
39                W,
40                at.saturating_add(o),
41                "a container header past the end: expected a 32-bit word",
42            )
43        })?;
44        usize::try_from(w).map_err(|_| bad(W, at.saturating_add(o), "word does not fit the address space"))
45    };
46    if word(20)? != 1 {
47        return Err(bad(W, at, format!("version {:#x}, not 1", word(20)?)));
48    }
49    let (size, n) = (word(24)?, word(28)?);
50    let directory = n.checked_mul(4).and_then(|d| d.checked_add(32));
51    if directory.is_none_or(|d| d > size) || at.checked_add(size).is_none_or(|e| e > payload.len()) {
52        return Err(bad(
53            W,
54            at,
55            format!("size {size} with {n} parts in a payload of {}", payload.len()),
56        ));
57    }
58    let directory_end = directory.unwrap_or(usize::MAX);
59    for i in 0..n {
60        let part = word(crate::at(32, i, 4))?;
61        if part < directory_end || part.saturating_add(8) > size {
62            return Err(bad(W, at, format!("part {i} at {part} in a container of {size}")));
63        }
64    }
65    Ok(size)
66}
67
68/// Every container of `payload`, in order. A container's bytes are not searched for another; a magic outside a
69/// container that does not head one is an error naming its offset, and so is a payload with none.
70pub fn containers(payload: &[u8]) -> Result<Vec<Span>> {
71    let (mut out, mut from) = (Vec::new(), 0);
72    while let Some(p) = payload
73        .get(from..)
74        .and_then(|rest| rest.windows(4).position(|w| w == MAGIC))
75    {
76        let offset = from.saturating_add(p);
77        let size = header(payload, offset)?;
78        out.push(Span { offset, size });
79        from = offset.saturating_add(size);
80    }
81    if out.is_empty() {
82        return Err(Error::Unsupported(format!(
83            "{W}: no DXBC container in {} bytes",
84            payload.len()
85        )));
86    }
87    Ok(out)
88}