container.rs 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380
  1. //! The PC container around emitted DXIL: feature flags (`SFI0`), the
  2. //! signatures (`ISG1`, `OSG1`), pipeline state validation (`PSV0`) and the
  3. //! program (`DXIL`), laid out as validator version 1.6 lays them out, plus
  4. //! the container hash that D3D12 checks.
  5. /// One signature element: one row (D3D12 links stages by semantic).
  6. #[derive(Debug, Clone, PartialEq, Eq)]
  7. pub(crate) struct SigElement {
  8. pub name: String,
  9. pub index: u32,
  10. /// DXIL semantic kind (0 arbitrary, 1 vertex id, 3 position, 16 target...).
  11. pub kind: u8,
  12. /// DXIL component type (4 i32, 5 u32, 9 f32, 1 i1).
  13. pub comp: u8,
  14. /// DXIL interpolation mode (0 for none).
  15. pub interp: u8,
  16. /// Start row, if the element has a register.
  17. pub row: Option<u32>,
  18. pub col: u8,
  19. pub cols: u8,
  20. /// Components read (inputs) or written (outputs), relative to `col`.
  21. pub usage: u8,
  22. /// 16-bit on the console (declared 32-bit here).
  23. pub half: bool,
  24. }
  25. impl SigElement {
  26. fn system_value(&self) -> u32 {
  27. match self.kind {
  28. 1 => 6, // vertex id
  29. 2 => 8, // instance id
  30. 3 => 1, // position
  31. 4 => 4, // render target array index
  32. 5 => 5, // viewport array index
  33. 6 => 2, // clip distance
  34. 7 => 3, // cull distance
  35. 10 => 7, // primitive id
  36. 12 => 10,
  37. 13 => 9, // front face
  38. 14 => 66,
  39. 15 => 70,
  40. 16 => 64, // target
  41. 17 => 65, // depth
  42. 18 => 68,
  43. 19 => 67,
  44. 20 => 69,
  45. 30 => 25, // cull primitive
  46. _ => 0,
  47. }
  48. }
  49. fn sig_comp(&self) -> u32 {
  50. match self.comp {
  51. 1 | 5 => 1, // bool and u32
  52. 4 => 2,
  53. 9 => 3,
  54. _ => 0,
  55. }
  56. }
  57. fn mask(&self) -> u8 {
  58. ((1u8 << self.cols) - 1) << self.col
  59. }
  60. }
  61. /// `ISG1`/`OSG1`: 32-byte rows, then the names.
  62. pub(crate) fn signature(elements: &[SigElement], input: bool) -> Vec<u8> {
  63. let mut out = Vec::new();
  64. out.extend((elements.len() as u32).to_le_bytes());
  65. out.extend(8u32.to_le_bytes());
  66. // Validator 1.6 writes one name per element in element order, repeats
  67. // included, except that system values share theirs (it keys names by
  68. // the semantic's string, which is one static string per system value);
  69. // the rows sorted by register (unallocated last).
  70. let mut offsets: Vec<u32> = Vec::new();
  71. let mut next = 8 + 32 * elements.len() as u32;
  72. let mut names = Vec::new();
  73. for (i, e) in elements.iter().enumerate() {
  74. let shared = (e.kind != 0)
  75. .then(|| (0..i).find(|&j| elements[j].kind == e.kind))
  76. .flatten();
  77. match shared {
  78. Some(j) => offsets.push(offsets[j]),
  79. None => {
  80. offsets.push(next);
  81. next += e.name.len() as u32 + 1;
  82. names.push(&e.name);
  83. }
  84. }
  85. }
  86. let mut order: Vec<usize> = (0..elements.len()).collect();
  87. order.sort_by_key(|&i| (elements[i].row.unwrap_or(u32::MAX), elements[i].col));
  88. for i in order {
  89. let (e, offset) = (&elements[i], offsets[i]);
  90. let used = e.usage << e.col;
  91. let rw = if input { used } else { !used & 0xf };
  92. for v in [
  93. 0,
  94. offset,
  95. e.index,
  96. e.system_value(),
  97. e.sig_comp(),
  98. e.row.unwrap_or(u32::MAX),
  99. ] {
  100. out.extend(v.to_le_bytes());
  101. }
  102. out.extend([e.mask(), rw, 0, 0]);
  103. out.extend(0u32.to_le_bytes());
  104. }
  105. for name in names {
  106. out.extend(name.as_bytes());
  107. out.push(0);
  108. }
  109. out
  110. }
  111. /// A resource bound by register, as `PSV0` lists it.
  112. #[derive(Debug, Clone, Copy)]
  113. pub(crate) struct Binding {
  114. /// PSV resource type: 1 sampler, 2 CBV.
  115. pub kind: u32,
  116. pub space: u32,
  117. pub register: u32,
  118. /// DXIL resource kind (13 cbuffer, 14 sampler).
  119. pub dxil_kind: u32,
  120. }
  121. pub(crate) struct Psv<'a> {
  122. /// PSV shader kind: 0 pixel, 1 vertex, 5 compute.
  123. pub stage: u8,
  124. /// Vertex: writes `SV_Position`. Pixel: writes depth.
  125. pub flag: bool,
  126. pub inputs: &'a [SigElement],
  127. pub outputs: &'a [SigElement],
  128. /// Mesh: per-primitive outputs.
  129. pub prims: &'a [SigElement],
  130. /// Mesh: its state and the group-shared bytes it declares.
  131. pub mesh: Option<(super::shader::Mesh, u32)>,
  132. pub bindings: &'a [Binding],
  133. /// Compute: thread-group size and required wave size.
  134. pub threads: [u32; 3],
  135. pub wave_size: Option<u32>,
  136. }
  137. /// `PSV0` with runtime info version 2 (validator 1.6).
  138. pub(crate) fn psv(p: &Psv) -> Vec<u8> {
  139. let vectors = |els: &[SigElement]| {
  140. els.iter()
  141. .filter_map(|e| e.row)
  142. .map(|r| r + 1)
  143. .max()
  144. .unwrap_or(0)
  145. };
  146. let (in_vectors, out_vectors) = (vectors(p.inputs), vectors(p.outputs));
  147. let mut out = Vec::new();
  148. let u32s = |out: &mut Vec<u8>, vs: &[u32]| {
  149. for v in vs {
  150. out.extend(v.to_le_bytes());
  151. }
  152. };
  153. u32s(&mut out, &[48]);
  154. let mut info = [0u8; 48];
  155. info[0] = u8::from(p.flag);
  156. let (min, max) = p.wave_size.map_or((0, u32::MAX), |n| (n, n));
  157. info[16..20].copy_from_slice(&min.to_le_bytes());
  158. info[20..24].copy_from_slice(&max.to_le_bytes());
  159. info[24] = p.stage;
  160. for (k, n) in p.threads.into_iter().enumerate() {
  161. info[36 + 4 * k..40 + 4 * k].copy_from_slice(&n.to_le_bytes());
  162. }
  163. info[28] = p.inputs.len() as u8;
  164. info[29] = p.outputs.len() as u8;
  165. info[31] = in_vectors as u8;
  166. info[32] = out_vectors as u8;
  167. if let Some((mesh, shared)) = p.mesh {
  168. info[0..4].copy_from_slice(&shared.to_le_bytes());
  169. info[12..14].copy_from_slice(&(mesh.max_vertices as u16).to_le_bytes());
  170. info[14..16].copy_from_slice(&(mesh.max_primitives as u16).to_le_bytes());
  171. info[26] = vectors(p.prims) as u8;
  172. info[27] = mesh.topology;
  173. info[30] = p.prims.len() as u8;
  174. }
  175. out.extend(info);
  176. u32s(&mut out, &[p.bindings.len() as u32]);
  177. if !p.bindings.is_empty() {
  178. u32s(&mut out, &[24]);
  179. for b in p.bindings {
  180. u32s(
  181. &mut out,
  182. &[b.kind, b.space, b.register, b.register, b.dxil_kind, 0],
  183. );
  184. }
  185. }
  186. // Names of arbitrary semantics (system values use ""), then indices.
  187. let mut strings = vec![0u8];
  188. let mut indices: Vec<u32> = Vec::new();
  189. let mut elements = Vec::new();
  190. for e in p.inputs.iter().chain(p.outputs).chain(p.prims) {
  191. let name = if e.kind == 0 {
  192. let needle: Vec<u8> = e.name.bytes().chain([0]).collect();
  193. match find(&strings, &needle) {
  194. Some(at) => at,
  195. None => {
  196. strings.extend(&needle);
  197. strings.len() - needle.len()
  198. }
  199. }
  200. } else {
  201. 0
  202. };
  203. let index = match indices.iter().position(|&i| i == e.index) {
  204. Some(at) => at,
  205. None => {
  206. indices.push(e.index);
  207. indices.len() - 1
  208. }
  209. };
  210. let (start, alloc) = match e.row {
  211. Some(r) => (r as u8, 0x40 | (e.col << 4)),
  212. None => (0, 0),
  213. };
  214. elements.push((name as u32, index as u32, start, e.cols | alloc, e));
  215. }
  216. strings.resize(strings.len().next_multiple_of(4), 0);
  217. u32s(&mut out, &[strings.len() as u32]);
  218. out.extend(&strings);
  219. u32s(&mut out, &[indices.len() as u32]);
  220. u32s(&mut out, &indices);
  221. if !elements.is_empty() {
  222. u32s(&mut out, &[16]);
  223. for (name, index, start, cols, e) in elements {
  224. u32s(&mut out, &[name, index]);
  225. out.extend([1, start, cols, e.kind, e.sig_comp() as u8, e.interp, 0, 0]);
  226. }
  227. }
  228. // Input-to-output dependencies, as the view-id state declares them:
  229. // every output scalar on every input scalar.
  230. if in_vectors > 0 && out_vectors > 0 {
  231. let scalars = |els: &[SigElement]| {
  232. els.iter()
  233. .filter_map(|e| e.row.map(|r| r * 4 + u32::from(e.col + e.cols)))
  234. .max()
  235. .unwrap_or(0)
  236. };
  237. let (ni, no) = (scalars(p.inputs), scalars(p.outputs));
  238. let per = (out_vectors * 4).div_ceil(32);
  239. for i in 0..in_vectors * 4 {
  240. for k in 0..per {
  241. let bits = if i < ni {
  242. no.saturating_sub(32 * k).min(32)
  243. } else {
  244. 0
  245. };
  246. let mask = if bits == 32 {
  247. u32::MAX
  248. } else {
  249. (1u32 << bits) - 1
  250. };
  251. u32s(&mut out, &[mask]);
  252. }
  253. }
  254. }
  255. out
  256. }
  257. fn find(hay: &[u8], needle: &[u8]) -> Option<usize> {
  258. hay.windows(needle.len()).position(|w| w == needle)
  259. }
  260. /// The container: parts in order, hashed.
  261. pub(crate) fn build(parts: &[(&[u8; 4], &[u8])]) -> Vec<u8> {
  262. let table = 0x20 + 4 * parts.len();
  263. let total = table + parts.iter().map(|(_, d)| 8 + d.len()).sum::<usize>();
  264. let mut out = Vec::with_capacity(total);
  265. out.extend(b"DXBC");
  266. out.extend([0; 16]);
  267. out.extend(1u16.to_le_bytes());
  268. out.extend(0u16.to_le_bytes());
  269. out.extend((total as u32).to_le_bytes());
  270. out.extend((parts.len() as u32).to_le_bytes());
  271. let mut offset = table;
  272. for (_, d) in parts {
  273. out.extend((offset as u32).to_le_bytes());
  274. offset += 8 + d.len();
  275. }
  276. for (fourcc, d) in parts {
  277. out.extend(*fourcc);
  278. out.extend((d.len() as u32).to_le_bytes());
  279. out.extend(*d);
  280. }
  281. let digest = hash(&out[20..]);
  282. out[4..20].copy_from_slice(&digest);
  283. out
  284. }
  285. /// The container hash D3D12 checks: MD5 whose last block carries the bit
  286. /// count first and `2 × bytes + 1` last instead of standard padding.
  287. pub(crate) fn hash(data: &[u8]) -> [u8; 16] {
  288. let len = data.len();
  289. let left = len % 64;
  290. let mut tail = Vec::with_capacity(128);
  291. if left < 56 {
  292. tail.extend(((len as u32) << 3).to_le_bytes());
  293. tail.extend(&data[len - left..]);
  294. tail.push(0x80);
  295. tail.resize(60, 0);
  296. } else {
  297. tail.extend(&data[len - left..]);
  298. tail.push(0x80);
  299. tail.resize(64, 0);
  300. tail.extend(((len as u32) << 3).to_le_bytes());
  301. tail.resize(124, 0);
  302. }
  303. tail.extend(((len as u32) << 1 | 1).to_le_bytes());
  304. let mut state = [0x6745_2301u32, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476];
  305. for block in data[..len - left]
  306. .as_chunks::<64>()
  307. .0
  308. .iter()
  309. .chain(tail.as_chunks::<64>().0)
  310. {
  311. md5_block(&mut state, block);
  312. }
  313. let mut out = [0; 16];
  314. for (o, s) in out.as_chunks_mut::<4>().0.iter_mut().zip(state) {
  315. o.copy_from_slice(&s.to_le_bytes());
  316. }
  317. out
  318. }
  319. fn md5_block(state: &mut [u32; 4], block: &[u8; 64]) {
  320. const S: [u32; 16] = [7, 12, 17, 22, 5, 9, 14, 20, 4, 11, 16, 23, 6, 10, 15, 21];
  321. let x: Vec<u32> = block
  322. .as_chunks::<4>()
  323. .0
  324. .iter()
  325. .map(|c| u32::from_le_bytes(*c))
  326. .collect();
  327. let [mut a, mut b, mut c, mut d] = *state;
  328. for i in 0..64 {
  329. let (f, g) = match i / 16 {
  330. 0 => ((b & c) | (!b & d), i),
  331. 1 => ((d & b) | (!d & c), (5 * i + 1) % 16),
  332. 2 => (b ^ c ^ d, (3 * i + 5) % 16),
  333. _ => (c ^ (b | !d), (7 * i) % 16),
  334. };
  335. let k = ((i as f64 + 1.0).sin().abs() * 4_294_967_296.0) as u32;
  336. let rotated = a
  337. .wrapping_add(f)
  338. .wrapping_add(k)
  339. .wrapping_add(x[g])
  340. .rotate_left(S[(i / 16) * 4 + i % 4]);
  341. (a, b, c, d) = (d, b.wrapping_add(rotated), b, c);
  342. }
  343. for (s, v) in state.iter_mut().zip([a, b, c, d]) {
  344. *s = s.wrapping_add(v);
  345. }
  346. }
  347. #[cfg(test)]
  348. mod tests {
  349. use super::*;
  350. #[test]
  351. fn md5_core_matches_the_standard() {
  352. // Standard MD5 of "abc" with standard padding, through md5_block.
  353. let mut block = b"abc".to_vec();
  354. block.push(0x80);
  355. block.resize(56, 0);
  356. block.extend(24u64.to_le_bytes());
  357. let mut state = [0x6745_2301u32, 0xefcd_ab89, 0x98ba_dcfe, 0x1032_5476];
  358. md5_block(&mut state, block.as_slice().try_into().unwrap());
  359. let hex: String = state
  360. .iter()
  361. .flat_map(|s| s.to_le_bytes())
  362. .map(|b| format!("{b:02x}"))
  363. .collect();
  364. assert_eq!(hex, "900150983cd24fb0d6963f7d28e17f72");
  365. }
  366. }