sgd5.rs 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218
  1. //! `SGD5`: the engine's shader file. Each record holds one shader container,
  2. //! deflate-packed. The header tables are not decoded yet, so records are
  3. //! found by their marker and cross-checked by their sizes:
  4. //!
  5. //! ```text
  6. //! u8 name length (with NUL), name, NUL, u8 kind,
  7. //! u32 n, u32 0x000DDCE7, u32 n, u32 unpacked size, raw deflate (n - 12 bytes)
  8. //! ```
  9. pub const MAGIC: &[u8; 4] = b"SGD5";
  10. const MARKER: [u8; 4] = 0x000D_DCE7_u32.to_le_bytes();
  11. /// Containers are at most a few MiB; refuse to allocate for absurd sizes.
  12. const MAX_UNPACKED: usize = 64 << 20;
  13. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  14. pub struct Record<'a> {
  15. /// Offset of the marker in the file.
  16. pub offset: usize,
  17. /// Like `PS_<name>_<hash>_Wrapped`; `None` if the bytes before the
  18. /// record do not read as one.
  19. pub name: Option<&'a str>,
  20. /// Record type, meaning unknown (0x32 most shaders, 0x41 mesh shaders
  21. /// and some material families, 0x3c compute, 0x40, 0x42).
  22. pub kind: u8,
  23. packed: &'a [u8],
  24. unpacked_size: usize,
  25. }
  26. impl Record<'_> {
  27. /// The container, or `None` if the stream is corrupt.
  28. pub fn unpack(&self) -> Option<Vec<u8>> {
  29. let mut state = zlib_rs::Inflate::new(false, 15);
  30. let mut out = Vec::new();
  31. let (mut in_pos, mut out_pos) = (0usize, 0usize);
  32. loop {
  33. if out_pos == self.unpacked_size {
  34. let mut extra = [0u8; 1];
  35. let status = state
  36. .decompress(
  37. &self.packed[in_pos..],
  38. &mut extra,
  39. zlib_rs::InflateFlush::NoFlush,
  40. )
  41. .ok()?;
  42. return (status == zlib_rs::Status::StreamEnd
  43. && state.total_out() as usize == self.unpacked_size)
  44. .then_some(out);
  45. }
  46. if out_pos == out.len() {
  47. let next_len = if out.is_empty() {
  48. self.unpacked_size
  49. .min(self.packed.len().saturating_mul(4).max(4096))
  50. } else {
  51. out.len().saturating_mul(2).min(self.unpacked_size)
  52. };
  53. out.resize(next_len, 0);
  54. }
  55. let status = state
  56. .decompress(
  57. &self.packed[in_pos..],
  58. &mut out[out_pos..],
  59. zlib_rs::InflateFlush::NoFlush,
  60. )
  61. .ok()?;
  62. let next_in = state.total_in() as usize;
  63. let next_out = state.total_out() as usize;
  64. match status {
  65. zlib_rs::Status::StreamEnd => {
  66. out.truncate(next_out);
  67. return (next_out == self.unpacked_size).then_some(out);
  68. }
  69. zlib_rs::Status::Ok if next_in != in_pos || next_out != out_pos => {
  70. in_pos = next_in;
  71. out_pos = next_out;
  72. }
  73. zlib_rs::Status::Ok | zlib_rs::Status::BufError => return None,
  74. }
  75. }
  76. }
  77. }
  78. /// An SGD5 file, or a file holding one (an archive: records are found by
  79. /// their marker, so no index is needed).
  80. pub fn is_sgd5(file: &[u8]) -> bool {
  81. memchr::memmem::find(file, MAGIC).is_some()
  82. }
  83. /// Every record in an SGD5 file, in file order.
  84. pub fn records(file: &[u8]) -> impl Iterator<Item = Record<'_>> {
  85. memchr::memmem::find_iter(file, &MARKER).filter_map(|at| record(file, at))
  86. }
  87. fn record(file: &[u8], at: usize) -> Option<Record<'_>> {
  88. let u32_at = |o: usize| {
  89. file.get(o..o + 4)
  90. .map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes")) as usize)
  91. };
  92. let n = u32_at(at.checked_sub(4)?)?;
  93. let unpacked_size = u32_at(at + 8)?;
  94. if u32_at(at + 4)? != n || n < 12 || unpacked_size > MAX_UNPACKED {
  95. return None;
  96. }
  97. let nul = at.checked_sub(6)?;
  98. Some(Record {
  99. offset: at,
  100. name: (file[nul] == 0).then(|| name_before(file, nul)).flatten(),
  101. kind: file[at - 5],
  102. packed: file.get(at + 12..at + n)?,
  103. unpacked_size,
  104. })
  105. }
  106. /// The printable name that ends at `nul` and follows its length byte.
  107. fn name_before(file: &[u8], nul: usize) -> Option<&str> {
  108. let run = file[..nul]
  109. .iter()
  110. .rposition(|b| !b.is_ascii_graphic())
  111. .map_or(0, |p| p + 1);
  112. // From 32 characters on, the length byte is printable too.
  113. (run.saturating_sub(1)..nul)
  114. .find(|&l| usize::from(file[l]) == nul - l)
  115. .and_then(|l| std::str::from_utf8(&file[l + 1..nul]).ok())
  116. }
  117. #[cfg(test)]
  118. mod tests {
  119. use super::*;
  120. fn record_bytes(name: &str, kind: u8, payload: &[u8]) -> Vec<u8> {
  121. let mut buf = vec![0u8; zlib_rs::compress_bound(payload.len())];
  122. let config = zlib_rs::DeflateConfig {
  123. window_bits: -15,
  124. ..zlib_rs::DeflateConfig::new(6)
  125. };
  126. let (packed, rc) = zlib_rs::compress_slice(&mut buf, payload, config);
  127. assert_eq!(rc, zlib_rs::ReturnCode::Ok);
  128. let n = (packed.len() + 12) as u32;
  129. let mut out = vec![0xF4, 0x01, 0, 0, name.len() as u8 + 1];
  130. out.extend_from_slice(name.as_bytes());
  131. out.extend_from_slice(&[0, kind]);
  132. for v in [n, 0x000D_DCE7, n, payload.len() as u32] {
  133. out.extend_from_slice(&v.to_le_bytes());
  134. }
  135. out.extend_from_slice(packed);
  136. out
  137. }
  138. #[test]
  139. fn reads_records() {
  140. let long = format!("PS_{}_Wrapped", "x".repeat(40));
  141. let mut file = MAGIC.to_vec();
  142. file.extend_from_slice(&[1, 2, 3, 4]);
  143. file.extend(record_bytes(
  144. "VS_Blit_0011aabb_Wrapped",
  145. 0x32,
  146. b"first container",
  147. ));
  148. // A marker whose sizes disagree is not a record.
  149. file.extend_from_slice(&[9, 0, 0, 0, 0xE7, 0xDC, 0x0D, 0, 8, 0, 0, 0]);
  150. file.extend(record_bytes(&long, 0x41, &[7; 300]));
  151. assert!(is_sgd5(&file));
  152. let found: Vec<_> = records(&file).collect();
  153. assert_eq!(found.len(), 2);
  154. assert_eq!(found[0].name, Some("VS_Blit_0011aabb_Wrapped"));
  155. assert_eq!(found[0].kind, 0x32);
  156. assert_eq!(found[0].unpack().as_deref(), Some(&b"first container"[..]));
  157. assert_eq!(found[1].name, Some(long.as_str()));
  158. assert_eq!(found[1].unpack(), Some(vec![7; 300]));
  159. // The same file inside an archive.
  160. let mut archive = vec![0x5A; 0x1000];
  161. archive.extend_from_slice(&file);
  162. assert!(is_sgd5(&archive));
  163. assert_eq!(records(&archive).count(), 2);
  164. assert!(!is_sgd5(&archive[..0x1000]));
  165. }
  166. #[test]
  167. fn corrupt_stream_does_not_unpack() {
  168. let mut file = record_bytes("CS_x", 0x3c, &[1; 64]);
  169. file[27] = 0xFF; // first packed byte: reserved block type
  170. let r = records(&file).next().unwrap();
  171. assert_eq!(r.unpack(), None);
  172. }
  173. #[test]
  174. fn handles_empty_and_rejects_mismatched_or_truncated_streams() {
  175. let empty = record_bytes("CS_empty", 0x3c, &[]);
  176. assert_eq!(records(&empty).next().unwrap().unpack(), Some(Vec::new()));
  177. let payload: Vec<u8> = (0..16_384u32)
  178. .map(|i| (i.wrapping_mul(31) ^ (i >> 5)) as u8)
  179. .collect();
  180. let good = record_bytes("PS_big", 0x32, &payload);
  181. let r = records(&good).next().unwrap();
  182. assert_eq!(r.unpack(), Some(payload.clone()));
  183. // Oversized stream (declared unpacked_size smaller than actual output).
  184. let mut smaller = good.clone();
  185. smaller[r.offset + 8..r.offset + 12]
  186. .copy_from_slice(&((payload.len() - 1) as u32).to_le_bytes());
  187. assert_eq!(records(&smaller).next().unwrap().unpack(), None);
  188. // Under-filled stream (declared unpacked_size larger than actual output).
  189. let mut larger = good.clone();
  190. larger[r.offset + 8..r.offset + 12]
  191. .copy_from_slice(&((payload.len() + 1) as u32).to_le_bytes());
  192. assert_eq!(records(&larger).next().unwrap().unpack(), None);
  193. // Truncated raw deflate stream.
  194. let mut truncated = good[..good.len() - 1].to_vec();
  195. let new_n = (truncated.len() - r.offset) as u32;
  196. truncated[r.offset - 4..r.offset].copy_from_slice(&new_n.to_le_bytes());
  197. truncated[r.offset + 4..r.offset + 8].copy_from_slice(&new_n.to_le_bytes());
  198. assert_eq!(records(&truncated).next().unwrap().unpack(), None);
  199. }
  200. }