sgd5.rs 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136
  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. miniz_oxide::inflate::decompress_to_vec_with_limit(self.packed, self.unpacked_size)
  30. .ok()
  31. .filter(|out| out.len() == self.unpacked_size)
  32. }
  33. }
  34. /// An SGD5 file, or a file holding one (an archive: records are found by
  35. /// their marker, so no index is needed).
  36. pub fn is_sgd5(file: &[u8]) -> bool {
  37. memchr::memmem::find(file, MAGIC).is_some()
  38. }
  39. /// Every record in an SGD5 file, in file order.
  40. pub fn records(file: &[u8]) -> impl Iterator<Item = Record<'_>> {
  41. memchr::memmem::find_iter(file, &MARKER).filter_map(|at| record(file, at))
  42. }
  43. fn record(file: &[u8], at: usize) -> Option<Record<'_>> {
  44. let u32_at = |o: usize| {
  45. file.get(o..o + 4)
  46. .map(|b| u32::from_le_bytes(b.try_into().expect("4 bytes")) as usize)
  47. };
  48. let n = u32_at(at.checked_sub(4)?)?;
  49. let unpacked_size = u32_at(at + 8)?;
  50. if u32_at(at + 4)? != n || n < 12 || unpacked_size > MAX_UNPACKED {
  51. return None;
  52. }
  53. let nul = at.checked_sub(6)?;
  54. Some(Record {
  55. offset: at,
  56. name: (file[nul] == 0).then(|| name_before(file, nul)).flatten(),
  57. kind: file[at - 5],
  58. packed: file.get(at + 12..at + n)?,
  59. unpacked_size,
  60. })
  61. }
  62. /// The printable name that ends at `nul` and follows its length byte.
  63. fn name_before(file: &[u8], nul: usize) -> Option<&str> {
  64. let run = file[..nul]
  65. .iter()
  66. .rposition(|b| !b.is_ascii_graphic())
  67. .map_or(0, |p| p + 1);
  68. // From 32 characters on, the length byte is printable too.
  69. (run.saturating_sub(1)..nul)
  70. .find(|&l| usize::from(file[l]) == nul - l)
  71. .and_then(|l| std::str::from_utf8(&file[l + 1..nul]).ok())
  72. }
  73. #[cfg(test)]
  74. mod tests {
  75. use super::*;
  76. fn record_bytes(name: &str, kind: u8, payload: &[u8]) -> Vec<u8> {
  77. let packed = miniz_oxide::deflate::compress_to_vec(payload, 6);
  78. let n = (packed.len() + 12) as u32;
  79. let mut out = vec![0xF4, 0x01, 0, 0, name.len() as u8 + 1];
  80. out.extend_from_slice(name.as_bytes());
  81. out.extend_from_slice(&[0, kind]);
  82. for v in [n, 0x000D_DCE7, n, payload.len() as u32] {
  83. out.extend_from_slice(&v.to_le_bytes());
  84. }
  85. out.extend_from_slice(&packed);
  86. out
  87. }
  88. #[test]
  89. fn reads_records() {
  90. let long = format!("PS_{}_Wrapped", "x".repeat(40));
  91. let mut file = MAGIC.to_vec();
  92. file.extend_from_slice(&[1, 2, 3, 4]);
  93. file.extend(record_bytes(
  94. "VS_Blit_0011aabb_Wrapped",
  95. 0x32,
  96. b"first container",
  97. ));
  98. // A marker whose sizes disagree is not a record.
  99. file.extend_from_slice(&[9, 0, 0, 0, 0xE7, 0xDC, 0x0D, 0, 8, 0, 0, 0]);
  100. file.extend(record_bytes(&long, 0x41, &[7; 300]));
  101. assert!(is_sgd5(&file));
  102. let found: Vec<_> = records(&file).collect();
  103. assert_eq!(found.len(), 2);
  104. assert_eq!(found[0].name, Some("VS_Blit_0011aabb_Wrapped"));
  105. assert_eq!(found[0].kind, 0x32);
  106. assert_eq!(found[0].unpack().as_deref(), Some(&b"first container"[..]));
  107. assert_eq!(found[1].name, Some(long.as_str()));
  108. assert_eq!(found[1].unpack(), Some(vec![7; 300]));
  109. // The same file inside an archive.
  110. let mut archive = vec![0x5A; 0x1000];
  111. archive.extend_from_slice(&file);
  112. assert!(is_sgd5(&archive));
  113. assert_eq!(records(&archive).count(), 2);
  114. assert!(!is_sgd5(&archive[..0x1000]));
  115. }
  116. #[test]
  117. fn corrupt_stream_does_not_unpack() {
  118. let mut file = record_bytes("CS_x", 0x3c, &[1; 64]);
  119. file[27] = 0xFF; // first packed byte: reserved block type
  120. let r = records(&file).next().unwrap();
  121. assert_eq!(r.unpack(), None);
  122. }
  123. }