frostbite_formats/
bytecode.rs1use crate::{Error, Rd, Result, bad};
10
11const W: &str = "compiled bytecode";
12pub const RTYPE: u32 = 0x0E2B_02F7;
14pub const TAG_AT: usize = 0x20;
16const MAGIC: &[u8; 4] = b"DXBC";
17
18#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20pub struct Span {
21 pub offset: usize,
23 pub size: usize,
25}
26
27pub fn tag(payload: &[u8]) -> Option<[u8; 4]> {
29 payload.get(TAG_AT..)?.first_chunk().copied()
30}
31
32fn 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
68pub 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}