dxbc.rs 6.0 KB

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