use crate::{Error, Rd, Result, bad};
const W: &str = "compiled bytecode";
pub const RTYPE: u32 = 0x0E2B_02F7;
pub const TAG_AT: usize = 0x20;
const MAGIC: &[u8; 4] = b"DXBC";
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct Span {
pub offset: usize,
pub size: usize,
}
pub fn tag(payload: &[u8]) -> Option<[u8; 4]> {
payload.get(TAG_AT..)?.first_chunk().copied()
}
fn header(payload: &[u8], at: usize) -> Result<usize> {
let r = Rd::new(payload, W);
let word = |o: usize| -> Result<usize> {
let w = r.u32le(at.saturating_add(o)).map_err(|_| {
bad(
W,
at.saturating_add(o),
"a container header past the end: expected a 32-bit word",
)
})?;
usize::try_from(w).map_err(|_| bad(W, at.saturating_add(o), "word does not fit the address space"))
};
if word(20)? != 1 {
return Err(bad(W, at, format!("version {:#x}, not 1", word(20)?)));
}
let (size, n) = (word(24)?, word(28)?);
let directory = n.checked_mul(4).and_then(|d| d.checked_add(32));
if directory.is_none_or(|d| d > size) || at.checked_add(size).is_none_or(|e| e > payload.len()) {
return Err(bad(
W,
at,
format!("size {size} with {n} parts in a payload of {}", payload.len()),
));
}
let directory_end = directory.unwrap_or(usize::MAX);
for i in 0..n {
let part = word(crate::at(32, i, 4))?;
if part < directory_end || part.saturating_add(8) > size {
return Err(bad(W, at, format!("part {i} at {part} in a container of {size}")));
}
}
Ok(size)
}
pub fn containers(payload: &[u8]) -> Result<Vec<Span>> {
let (mut out, mut from) = (Vec::new(), 0);
while let Some(p) = payload
.get(from..)
.and_then(|rest| rest.windows(4).position(|w| w == MAGIC))
{
let offset = from.saturating_add(p);
let size = header(payload, offset)?;
out.push(Span { offset, size });
from = offset.saturating_add(size);
}
if out.is_empty() {
return Err(Error::Unsupported(format!(
"{W}: no DXBC container in {} bytes",
payload.len()
)));
}
Ok(out)
}