dxbc.rs 5.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181
  1. //! The DXBC container: a header, then a table of FourCC-tagged parts.
  2. //!
  3. //! ```text
  4. //! 0x00 "DXBC"
  5. //! 0x04 digest[16]
  6. //! 0x14 version major u16, minor u16
  7. //! 0x18 total size u32
  8. //! 0x1C part count u32
  9. //! 0x20 part offsets u32[count]
  10. //! part: fourcc[4], size u32, data[size]
  11. //! ```
  12. use crate::ShaderError;
  13. #[derive(Clone, Copy, PartialEq, Eq, Hash)]
  14. pub struct FourCC(pub [u8; 4]);
  15. impl FourCC {
  16. pub const DXIL: FourCC = FourCC(*b"DXIL");
  17. pub const STAT: FourCC = FourCC(*b"STAT");
  18. pub const RTS0: FourCC = FourCC(*b"RTS0");
  19. pub const PSV0: FourCC = FourCC(*b"PSV0");
  20. pub const ISG1: FourCC = FourCC(*b"ISG1");
  21. pub const OSG1: FourCC = FourCC(*b"OSG1");
  22. /// Per-primitive outputs of a mesh shader.
  23. pub const PSG1: FourCC = FourCC(*b"PSG1");
  24. pub const SFI0: FourCC = FourCC(*b"SFI0");
  25. pub const HASH: FourCC = FourCC(*b"HASH");
  26. pub const ILDB: FourCC = FourCC(*b"ILDB");
  27. pub const ILDN: FourCC = FourCC(*b"ILDN");
  28. }
  29. impl std::fmt::Debug for FourCC {
  30. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  31. write!(f, "{}", self)
  32. }
  33. }
  34. impl std::fmt::Display for FourCC {
  35. fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
  36. for &b in &self.0 {
  37. let c = if b.is_ascii_graphic() { b as char } else { '.' };
  38. write!(f, "{c}")?;
  39. }
  40. Ok(())
  41. }
  42. }
  43. #[derive(Debug, Clone, Copy)]
  44. pub struct Part<'a> {
  45. pub fourcc: FourCC,
  46. /// Offset of the part header within the container.
  47. pub offset: usize,
  48. pub data: &'a [u8],
  49. }
  50. #[derive(Debug, Clone)]
  51. pub struct Container<'a> {
  52. pub digest: [u8; 16],
  53. pub version: (u16, u16),
  54. pub parts: Vec<Part<'a>>,
  55. }
  56. const HEADER_SIZE: usize = 0x20;
  57. const MAX_PARTS: usize = 256;
  58. impl<'a> Container<'a> {
  59. pub fn parse(data: &'a [u8]) -> Result<Self, ShaderError> {
  60. if data.len() < HEADER_SIZE || &data[0..4] != b"DXBC" {
  61. return Err(ShaderError::NotDxbc);
  62. }
  63. let digest = data[4..20].try_into().expect("16 bytes");
  64. let version = (u16_at(data, 0x14)?, u16_at(data, 0x16)?);
  65. let total = u32_at(data, 0x18)? as usize;
  66. if total > data.len() || total < HEADER_SIZE {
  67. return Err(ShaderError::Malformed("container size disagrees with data"));
  68. }
  69. let data = &data[..total];
  70. let count = u32_at(data, 0x1C)? as usize;
  71. if count > MAX_PARTS {
  72. return Err(ShaderError::Malformed("implausible part count"));
  73. }
  74. let mut parts = Vec::with_capacity(count);
  75. for i in 0..count {
  76. let offset = u32_at(data, HEADER_SIZE + 4 * i)? as usize;
  77. let fourcc = FourCC(
  78. data.get(offset..offset + 4)
  79. .ok_or(ShaderError::Malformed("part header out of bounds"))?
  80. .try_into()
  81. .expect("4 bytes"),
  82. );
  83. let size = u32_at(data, offset + 4)? as usize;
  84. let body = data
  85. .get(offset + 8..offset + 8 + size)
  86. .ok_or(ShaderError::Malformed("part data out of bounds"))?;
  87. parts.push(Part {
  88. fourcc,
  89. offset,
  90. data: body,
  91. });
  92. }
  93. Ok(Container {
  94. digest,
  95. version,
  96. parts,
  97. })
  98. }
  99. pub fn part(&self, fourcc: FourCC) -> Option<&Part<'a>> {
  100. self.parts.iter().find(|p| p.fourcc == fourcc)
  101. }
  102. }
  103. pub(crate) fn u16_at(data: &[u8], at: usize) -> Result<u16, ShaderError> {
  104. data.get(at..at + 2)
  105. .map(|b| u16::from_le_bytes(b.try_into().expect("2 bytes")))
  106. .ok_or(ShaderError::Malformed("truncated"))
  107. }
  108. pub(crate) fn u32_at(data: &[u8], at: usize) -> Result<u32, ShaderError> {
  109. data.get(at..at + 4)
  110. .map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes")))
  111. .ok_or(ShaderError::Malformed("truncated"))
  112. }
  113. pub(crate) fn u64_at(data: &[u8], at: usize) -> Result<u64, ShaderError> {
  114. data.get(at..at + 8)
  115. .map(|b| u64::from_le_bytes(b.try_into().expect("8 bytes")))
  116. .ok_or(ShaderError::Malformed("truncated"))
  117. }
  118. /// Builds a container from parts (test helper).
  119. #[cfg(test)]
  120. pub fn build(parts: &[(FourCC, &[u8])]) -> Vec<u8> {
  121. let table = HEADER_SIZE + 4 * parts.len();
  122. let total = table + parts.iter().map(|(_, d)| 8 + d.len()).sum::<usize>();
  123. let mut out = Vec::with_capacity(total);
  124. out.extend_from_slice(b"DXBC");
  125. out.extend_from_slice(&[0; 16]);
  126. out.extend_from_slice(&1u16.to_le_bytes());
  127. out.extend_from_slice(&0u16.to_le_bytes());
  128. out.extend_from_slice(&(total as u32).to_le_bytes());
  129. out.extend_from_slice(&(parts.len() as u32).to_le_bytes());
  130. let mut offset = table;
  131. for (_, d) in parts {
  132. out.extend_from_slice(&(offset as u32).to_le_bytes());
  133. offset += 8 + d.len();
  134. }
  135. for (fourcc, d) in parts {
  136. out.extend_from_slice(&fourcc.0);
  137. out.extend_from_slice(&(d.len() as u32).to_le_bytes());
  138. out.extend_from_slice(d);
  139. }
  140. out
  141. }
  142. #[cfg(test)]
  143. mod tests {
  144. use super::*;
  145. #[test]
  146. fn round_trips_parts() {
  147. let bytes = build(&[(FourCC::SFI0, &[1, 2, 3, 4]), (FourCC::HASH, &[9; 20])]);
  148. let c = Container::parse(&bytes).unwrap();
  149. assert_eq!(c.parts.len(), 2);
  150. assert_eq!(c.part(FourCC::SFI0).unwrap().data, &[1, 2, 3, 4]);
  151. assert_eq!(c.part(FourCC::HASH).unwrap().data.len(), 20);
  152. assert!(c.part(FourCC::DXIL).is_none());
  153. }
  154. #[test]
  155. fn rejects_bad_input() {
  156. assert_eq!(Container::parse(b"nope").unwrap_err(), ShaderError::NotDxbc);
  157. let mut bytes = build(&[(FourCC::SFI0, &[0; 8])]);
  158. let last = bytes.len() - 1;
  159. bytes[0x20] = 0xFF; // corrupt the first part offset
  160. assert!(Container::parse(&bytes).is_err());
  161. bytes.truncate(last);
  162. assert!(Container::parse(&bytes).is_err());
  163. }
  164. }