native.rs 36 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023
  1. //! Native GFX10 programs that the console compiler stores in a `DXIL` part.
  2. //!
  3. //! An `XDAT` index after the program header lists blobs stored around the
  4. //! bitcode; one or more of them hold native programs, zlib-packed (a vertex
  5. //! shader can carry two: compiled for use with and without a geometry
  6. //! shader). Layout as observed in shipped titles (index offsets are relative
  7. //! to the part data):
  8. //!
  9. //! ```text
  10. //! +0x18 "XDAT" u32 entry count, u32 (0x24 seen), then per entry:
  11. //! u32 kind, u32 offset, u32 size
  12. //! kind 0x0d "XBCH" u32 version (3), u64 packed size, u64 unpacked size,
  13. //! zlib stream
  14. //! unpacked "FSSM" u32 version (0x101), u64 payload size, payload
  15. //! payload +0x00 u64 graphics slot count (6)
  16. //! +0x08 u64 record offsets: LS HS ES GS VS PS (0x08..0x30),
  17. //! mesh 0x48, compute 0x60; unused ones are 0xDEADBEEF_DEADBEEF
  18. //! record +0x00 u64 code offset, +0x08 u64 code size (payload-relative),
  19. //! +0x14 u32 flags: bit 5 wave32 (else wave64)
  20. //! +0x28 u64 root layout table, +0x30 u64 used-resource table
  21. //! (payload-relative), +0x38 u32 and +0x3c u32 their counts
  22. //! +0x50 u32 bits 0-9 VGPRs used, bits 20-27 SGPRs used
  23. //! layout 20 B: u32 root type, u32 table offset (dwords), u32 user SGPRs,
  24. //! u32 base register, u8 first user-data dword, u8 root slot,
  25. //! u16 0
  26. //! used 20 B: u8 resource type, u8 root type, u16 0, u32 table offset
  27. //! (dwords), u32 lower bound, u32 stride, u8 descriptor
  28. //! dwords, u8 first user-data dword, u8 root slot, u8 0
  29. //! ```
  30. //!
  31. //! Stage data follows the record; offsets from its end (E = record + 0x54):
  32. //!
  33. //! ```text
  34. //! PS E+0x24 32 inputs of 8 B: u8 usage, u8 signature row, u8 channel
  35. //! mask, u8 attribute (v_interp `attr`), u8 default, u8 second
  36. //! row (of a packed pair), u8 parameter slot, u8 flags (bit 0
  37. //! flat, 1 linear, 3 fp16, 4 fp16 packed); E+0x124 u32 count
  38. //! E+0x134 u32 SPI_PS_INPUT_ADDR, E+0x138 u32 DB_SHADER_CONTROL
  39. //! E+0x148 u32 export patch size (dwords), E+0x14c 8 patches, one per
  40. //! MRT: u32 code offset (dwords, -1 none), then the export code
  41. //! for each color format in 10 slots of 10 dwords (ZERO, 32_R,
  42. //! 32_GR, 32_AR, FP16, UNORM16, SNORM16, UINT16, SINT16, 32_ABGR)
  43. //! VS E+0x24 32 inputs of 5 B: u8 usage, u8 row, u8 channel mask, u8 VGPR
  44. //! of channel 0 (channel k in VGPR + k), u8 highest channel;
  45. //! E+0xc4 u32 count
  46. //! E+0xc8 32 outputs of 6 B: u8 usage, u8 row, u8 parameter (`exp
  47. //! param<n>`), u8 row again, u8 slot, u8 flags (bit 0 fp16,
  48. //! bit 1 two fp16 values per dword); E+0x188 u32 count
  49. //! CS E+0x24 u32 COMPUTE_PGM_RSRC2, E+0x28 u32 x3 thread-group size
  50. //! MS E+0xc8 outputs as VS, E+0x188 count; the param byte's bit 7 marks a
  51. //! per-primitive output (`PSG1` row); the 3 bytes more are the
  52. //! second row of a packed pair, a slot, flags (bit 0 fp16, bit 1
  53. //! two fp16 elements packed)
  54. //! E+0x18c u32 SPI_VS_OUT_CONFIG, SPI_SHADER_POS_FORMAT,
  55. //! PA_CL_VS_OUT_CNTL, VGT_STRMOUT_CONFIG, SPI_SHADER_PGM_RSRC2_GS,
  56. //! VGT_GS_OUT_PRIM_TYPE, VGT_GS_INSTANCE_CNT, SPI_SHADER_IDX_FORMAT
  57. //! E+0x448 u16 thread-group size in lanes, u16 maximum vertices,
  58. //! u16 maximum primitives, u8 user SGPRs, u8 output topology
  59. //! (2 triangles); code follows at E+0x45c
  60. //! record +0x4c u32 LDS bytes (`lds_byte_size`; mesh programs read it here)
  61. //! ```
  62. //!
  63. //! Rows are registers of the container's signature parts (`ISG1`, `OSG1`).
  64. //! Merged stages keep their stage data in another layout (not read).
  65. //!
  66. //! Other kinds seen: 0x07 program header + bitcode (or a stub when stripped),
  67. //! 0x0a `xbop` (compiler options), 0x0e a table not decoded yet, 0x10 and
  68. //! 0x12 16-byte blobs (0x10 is the shader hash).
  69. //! Unknown versions are rejected so a format change shows up as an error.
  70. use crate::ShaderError::{self, Malformed};
  71. use crate::dxbc::{u32_at, u64_at};
  72. const XDAT_OFFSET: usize = 0x18;
  73. const MAX_XDAT_ENTRIES: usize = 64;
  74. const KIND_NATIVE: u32 = 0x0d;
  75. const XBCH_VERSION: u32 = 3;
  76. const XBCH_HEADER: usize = 0x18;
  77. const FSSM_VERSION: u32 = 0x101;
  78. const FSSM_HEADER: usize = 0x10;
  79. const GRAPHICS_SLOT_COUNT: u64 = 6;
  80. /// Where each stage's record offset sits in the FSSM payload.
  81. const SLOTS: [(HwStage, usize); 8] = [
  82. (HwStage::Ls, 0x08),
  83. (HwStage::Hs, 0x10),
  84. (HwStage::Es, 0x18),
  85. (HwStage::Gs, 0x20),
  86. (HwStage::Vs, 0x28),
  87. (HwStage::Ps, 0x30),
  88. (HwStage::Ms, 0x48),
  89. (HwStage::Cs, 0x60),
  90. ];
  91. const ABSENT: u64 = 0xDEAD_BEEF_DEAD_BEEF;
  92. const RECORD_SIZE: u64 = 0x54;
  93. const RECORD_FLAGS: usize = 0x14;
  94. const FLAG_WAVE32: u32 = 1 << 5;
  95. const RECORD_REGS: usize = 0x50;
  96. const RECORD_LAYOUT: usize = 0x28;
  97. const RECORD_USED: usize = 0x30;
  98. const RECORD_COUNTS: usize = 0x38;
  99. const ENTRY_SIZE: u64 = 20;
  100. const MAX_SEMANTICS: u32 = 32;
  101. const PS_INPUTS: usize = 0x24;
  102. const PS_INPUT_COUNT: usize = 0x124;
  103. const PS_INPUT_ADDR: usize = 0x134;
  104. const PS_DB_SHADER_CONTROL: usize = 0x138;
  105. const PS_PATCH_SIZE: usize = 0x148;
  106. const PS_PATCHES: usize = 0x14c;
  107. const PATCH_SLOT_DWORDS: usize = 10;
  108. /// The variant that exports every channel as a raw 32-bit value.
  109. const PATCH_FULL: usize = 9;
  110. const PATCH_BYTES: usize = 4 + 10 * PATCH_SLOT_DWORDS * 4;
  111. const MRTS: usize = 8;
  112. const VS_INPUTS: usize = 0x24;
  113. const VS_INPUT_COUNT: usize = 0xc4;
  114. const VS_OUTPUTS: usize = 0xc8;
  115. const VS_OUTPUT_COUNT: usize = 0x188;
  116. const CS_RSRC2: usize = 0x24;
  117. const CS_THREADS: usize = 0x28;
  118. const RECORD_LDS: usize = 0x4c;
  119. const MS_CLIP_CNTL: usize = 0x194;
  120. const MS_INFO: usize = 0x448;
  121. /// Unpacked blobs are a few KiB; refuse to allocate for absurd sizes.
  122. const MAX_UNPACKED: u64 = 16 << 20;
  123. /// Hardware shader stage a native program runs as.
  124. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
  125. pub enum HwStage {
  126. Ls,
  127. Hs,
  128. Es,
  129. Gs,
  130. Vs,
  131. Ps,
  132. /// Mesh shader.
  133. Ms,
  134. Cs,
  135. }
  136. impl HwStage {
  137. /// The SGPR holding user-data dword `index`: merged stages (and mesh
  138. /// shaders, which run as one) have 8 system SGPRs first.
  139. pub fn user_sgpr(self, index: u8) -> u8 {
  140. match self {
  141. HwStage::Ls | HwStage::Hs | HwStage::Es | HwStage::Gs | HwStage::Ms => index + 8,
  142. HwStage::Vs | HwStage::Ps | HwStage::Cs => index,
  143. }
  144. }
  145. }
  146. #[derive(Debug, Clone, PartialEq, Eq)]
  147. pub struct NativeProgram {
  148. pub stage: HwStage,
  149. /// Runs as 64 lanes per wave (else 32); sizes lane masks.
  150. pub wave64: bool,
  151. /// VGPRs the program uses (v0 up to this), the bound of indexed access.
  152. pub vgprs: u16,
  153. /// Where the root signature's parameters arrive (user SGPRs).
  154. pub layout: Vec<RootParam>,
  155. /// The descriptors the program reads, by root parameter.
  156. pub used: Vec<UsedResource>,
  157. pub io: StageIo,
  158. /// GFX10 machine code, as stored.
  159. pub code: Vec<u8>,
  160. }
  161. impl NativeProgram {
  162. /// The code with each render target's export patched for its full
  163. /// 32-bit format, so exports carry the shader's values unconverted (as
  164. /// the console does at pipeline creation for that format).
  165. pub fn patched_code(&self) -> Vec<u8> {
  166. let mut code = self.code.clone();
  167. if let StageIo::Ps { patches, .. } = &self.io {
  168. for p in patches {
  169. let at = p.offset as usize * 4;
  170. for (i, word) in p.code.iter().enumerate() {
  171. code[at + 4 * i..at + 4 * i + 4].copy_from_slice(&word.to_le_bytes());
  172. }
  173. }
  174. }
  175. code
  176. }
  177. }
  178. /// What a semantic is, as the stage data names it.
  179. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
  180. pub enum Usage {
  181. Generic,
  182. ClipDistance,
  183. Other(u8),
  184. }
  185. impl Usage {
  186. fn from_raw(raw: u8) -> Self {
  187. match raw {
  188. 6 => Usage::Generic,
  189. 7 => Usage::ClipDistance,
  190. n => Usage::Other(n),
  191. }
  192. }
  193. }
  194. /// A pixel shader input: what `v_interp` of attribute `attr` reads.
  195. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  196. pub struct PsInput {
  197. pub usage: Usage,
  198. /// Register in the input signature.
  199. pub row: u8,
  200. pub mask: u8,
  201. pub attr: u8,
  202. pub flat: bool,
  203. pub fp16: bool,
  204. /// Two 16-bit values per dword ([`VsOutput::pack2`]); `row2` is the
  205. /// second element's register.
  206. pub pack2: bool,
  207. pub row2: u8,
  208. }
  209. /// A vertex attribute the fetch shader loads: channel k into VGPR `vgpr + k`.
  210. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  211. pub struct VsInput {
  212. pub usage: Usage,
  213. pub row: u8,
  214. pub mask: u8,
  215. pub vgpr: u8,
  216. }
  217. /// What `exp param<param>` of a vertex shader writes.
  218. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  219. pub struct VsOutput {
  220. pub usage: Usage,
  221. /// Register in the output signature.
  222. pub row: u8,
  223. pub param: u8,
  224. /// 16-bit values, one per dword (low half) unless `pack2`: then two per
  225. /// dword, channel c of this row in dword c / 2 (odd channels in the
  226. /// high half), then a second 16-bit row from the next whole dword (the
  227. /// next 16-bit row of the signature no entry names).
  228. pub fp16: bool,
  229. pub pack2: bool,
  230. }
  231. /// The export code of one render target for its full 32-bit format.
  232. #[derive(Debug, Clone, PartialEq, Eq)]
  233. pub struct ExportPatch {
  234. pub mrt: u8,
  235. /// Where it goes in the code, in dwords.
  236. pub offset: u32,
  237. pub code: Vec<u32>,
  238. }
  239. /// Inputs and outputs, for the stages whose stage data is read.
  240. #[derive(Debug, Clone, Default, PartialEq, Eq)]
  241. pub enum StageIo {
  242. #[default]
  243. None,
  244. Vs {
  245. inputs: Vec<VsInput>,
  246. outputs: Vec<VsOutput>,
  247. },
  248. Ps {
  249. inputs: Vec<PsInput>,
  250. /// `SPI_PS_INPUT_ADDR`: which system values arrive in VGPRs.
  251. input_addr: u32,
  252. /// `DB_SHADER_CONTROL`: depth export, kill.
  253. db_shader_control: u32,
  254. patches: Vec<ExportPatch>,
  255. },
  256. Cs(ComputeIo),
  257. Ms(MeshIo),
  258. }
  259. /// A mesh program's outputs and limits. It runs as one hardware NGG stage:
  260. /// lane n of the group (`threads` lanes) exports vertex n (`exp pos`,
  261. /// `exp param`) and primitive n (`exp prim`).
  262. #[derive(Debug, Clone, PartialEq, Eq)]
  263. pub struct MeshIo {
  264. /// `exp param<n>` targets; `param` bit 7 set: a per-primitive output,
  265. /// `row` then a row of the primitive signature (`PSG1`).
  266. pub outputs: Vec<VsOutput>,
  267. /// `PA_CL_VS_OUT_CNTL`: which clip and cull distances `pos1+` carry.
  268. pub clip_cntl: u32,
  269. /// Thread-group size in lanes (the HLSL group rounded up to waves).
  270. pub threads: u32,
  271. pub max_vertices: u32,
  272. pub max_primitives: u32,
  273. /// 1 lines, 2 triangles.
  274. pub topology: u8,
  275. pub lds_bytes: u32,
  276. }
  277. /// A compute program's dispatch settings.
  278. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  279. pub struct ComputeIo {
  280. /// `COMPUTE_PGM_RSRC2`: user SGPRs, which system SGPRs and VGPRs
  281. /// follow them, LDS size.
  282. pub rsrc2: u32,
  283. /// Thread-group size (`numthreads`).
  284. pub threads: [u32; 3],
  285. }
  286. impl ComputeIo {
  287. /// User SGPRs before the system ones.
  288. pub fn user_sgprs(&self) -> u8 {
  289. (self.rsrc2 >> 1 & 0x1F) as u8
  290. }
  291. /// The SGPR of each enabled thread-group id component, in order after
  292. /// the user SGPRs, then the thread-group info SGPR if enabled.
  293. pub fn system_sgprs(&self) -> ([Option<u8>; 3], Option<u8>) {
  294. let mut next = self.user_sgprs();
  295. let mut take = |bit: u32| {
  296. (self.rsrc2 >> bit & 1 != 0).then(|| {
  297. next += 1;
  298. next - 1
  299. })
  300. };
  301. let ids = [take(7), take(8), take(9)];
  302. (ids, take(10))
  303. }
  304. /// SGPRs the hardware initializes: the user SGPRs, the enabled system
  305. /// ones, then the scratch wave offset when scratch is enabled (bit 0).
  306. /// The ones above hold whatever the previous wave left.
  307. pub fn initialized_sgprs(&self) -> u8 {
  308. let (ids, info) = self.system_sgprs();
  309. let end = ids.into_iter().chain([info]).flatten().map(|s| s + 1).max();
  310. end.unwrap_or(0).max(self.user_sgprs()) + (self.rsrc2 & 1) as u8
  311. }
  312. /// Thread id components in v0, v1, v2 (1 to 3).
  313. pub fn thread_id_vgprs(&self) -> u8 {
  314. (self.rsrc2 >> 11 & 3) as u8 + 1
  315. }
  316. /// LDS bytes per thread group (512-byte granules).
  317. pub fn lds_bytes(&self) -> u32 {
  318. (self.rsrc2 >> 15 & 0x1FF) * 512
  319. }
  320. }
  321. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
  322. pub enum RootType {
  323. Constants,
  324. /// A 64-bit buffer address.
  325. Descriptor,
  326. /// The 32-bit heap address of a descriptor table range.
  327. Table,
  328. /// A sampler the root signature fixes.
  329. ImmediateSampler,
  330. /// The 32-bit address of the CBV/SRV/UAV heap (SM 6.6 dynamic resources).
  331. ResourceHeap,
  332. /// The 32-bit address of the sampler heap.
  333. SamplerHeap,
  334. Other(u32),
  335. }
  336. impl RootType {
  337. fn from_raw(raw: u32) -> Self {
  338. match raw {
  339. 0 => RootType::Constants,
  340. 1 => RootType::Descriptor,
  341. 3 => RootType::Table,
  342. 4 => RootType::ImmediateSampler,
  343. 5 => RootType::ResourceHeap,
  344. 6 => RootType::SamplerHeap,
  345. n => RootType::Other(n),
  346. }
  347. }
  348. }
  349. /// One root parameter (or table range) and the user SGPRs holding it.
  350. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  351. pub struct RootParam {
  352. pub root: RootType,
  353. /// Of the range within its table.
  354. pub table_offset_dwords: u32,
  355. /// User SGPRs from `user_data` on.
  356. pub sgprs: u32,
  357. /// Shader register of the first descriptor (`b`/`t`/`u`/`s` number).
  358. pub base_register: u32,
  359. /// First user-data dword ([`HwStage::user_sgpr`]).
  360. pub user_data: u8,
  361. /// Index of the parameter in the root signature.
  362. pub slot: u8,
  363. }
  364. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
  365. pub enum ResourceType {
  366. Srv,
  367. Sampler,
  368. Cbv,
  369. Uav,
  370. Other(u8),
  371. }
  372. /// A descriptor range the program reads.
  373. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  374. pub struct UsedResource {
  375. pub kind: ResourceType,
  376. pub root: RootType,
  377. pub table_offset_dwords: u32,
  378. /// Shader register of the first descriptor read.
  379. pub lower_bound: u32,
  380. pub stride: u32,
  381. /// Size of the descriptor (4 or 8).
  382. pub dwords: u8,
  383. pub user_data: u8,
  384. pub slot: u8,
  385. }
  386. /// The native programs in a `DXIL` part's data; empty for the PC layout.
  387. pub fn native_programs(part: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> {
  388. if part.get(XDAT_OFFSET..XDAT_OFFSET + 4) != Some(b"XDAT") {
  389. return Ok(Vec::new());
  390. }
  391. let count = u32_at(part, XDAT_OFFSET + 4)? as usize;
  392. if count > MAX_XDAT_ENTRIES {
  393. return Err(Malformed("implausible XDAT entry count"));
  394. }
  395. let mut out = Vec::new();
  396. for i in 0..count {
  397. let at = XDAT_OFFSET + 12 + 12 * i;
  398. if u32_at(part, at)? != KIND_NATIVE {
  399. continue;
  400. }
  401. let offset = u32_at(part, at + 4)?.into();
  402. let size = u32_at(part, at + 8)?.into();
  403. let blob = bytes(part, offset, size).ok_or(Malformed("XDAT entry out of bounds"))?;
  404. out.extend(programs(&unpack(blob)?)?);
  405. }
  406. Ok(out)
  407. }
  408. fn unpack(blob: &[u8]) -> Result<Vec<u8>, ShaderError> {
  409. if blob.get(0..4) != Some(b"XBCH") {
  410. return Err(Malformed("native blob lacks XBCH magic"));
  411. }
  412. if u32_at(blob, 4)? != XBCH_VERSION {
  413. return Err(Malformed("unknown XBCH version"));
  414. }
  415. let packed = u64_at(blob, 8)?;
  416. let unpacked = u64_at(blob, 16)?;
  417. if unpacked > MAX_UNPACKED {
  418. return Err(Malformed("implausible XBCH unpacked size"));
  419. }
  420. let stream =
  421. bytes(blob, XBCH_HEADER as u64, packed).ok_or(Malformed("XBCH stream out of bounds"))?;
  422. let out = miniz_oxide::inflate::decompress_to_vec_zlib_with_limit(stream, unpacked as usize)
  423. .map_err(|_| Malformed("XBCH stream does not inflate to its stated size"))?;
  424. if out.len() as u64 != unpacked {
  425. return Err(Malformed("XBCH stream does not inflate to its stated size"));
  426. }
  427. Ok(out)
  428. }
  429. fn programs(fssm: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> {
  430. if fssm.get(0..4) != Some(b"FSSM") {
  431. return Err(Malformed("native blob lacks FSSM magic"));
  432. }
  433. if u32_at(fssm, 4)? != FSSM_VERSION {
  434. return Err(Malformed("unknown FSSM version"));
  435. }
  436. let payload = &fssm[FSSM_HEADER.min(fssm.len())..];
  437. if u64_at(fssm, 8)? != payload.len() as u64 {
  438. return Err(Malformed("FSSM payload size disagrees"));
  439. }
  440. if u64_at(payload, 0)? != GRAPHICS_SLOT_COUNT {
  441. return Err(Malformed("unexpected FSSM slot count"));
  442. }
  443. let mut out = Vec::new();
  444. for (stage, at) in SLOTS {
  445. let start = u64_at(payload, at)?;
  446. if start == ABSENT {
  447. continue;
  448. }
  449. let record =
  450. bytes(payload, start, RECORD_SIZE).ok_or(Malformed("FSSM record out of bounds"))?;
  451. let code = bytes(payload, u64_at(record, 0)?, u64_at(record, 8)?)
  452. .ok_or(Malformed("native code out of bounds"))?;
  453. let vgprs = (u32_at(record, RECORD_REGS)? & 0x3FF) as u16;
  454. if vgprs > 256 {
  455. return Err(Malformed("implausible VGPR count"));
  456. }
  457. let table = |at: usize, count_at: usize| -> Result<&[u8], ShaderError> {
  458. let len = ENTRY_SIZE * u64::from(u32_at(record, count_at)?);
  459. if len == 0 {
  460. return Ok(&[]);
  461. }
  462. bytes(payload, u64_at(record, at)?, len)
  463. .ok_or(Malformed("FSSM root table out of bounds"))
  464. };
  465. let layout = table(RECORD_LAYOUT, RECORD_COUNTS)?
  466. .as_chunks::<{ ENTRY_SIZE as usize }>()
  467. .0
  468. .iter()
  469. .map(|e| RootParam {
  470. root: RootType::from_raw(le32(e, 0)),
  471. table_offset_dwords: le32(e, 4),
  472. sgprs: le32(e, 8),
  473. base_register: le32(e, 12),
  474. user_data: e[16],
  475. slot: e[17],
  476. })
  477. .collect();
  478. let used = table(RECORD_USED, RECORD_COUNTS + 4)?
  479. .as_chunks::<{ ENTRY_SIZE as usize }>()
  480. .0
  481. .iter()
  482. .map(|e| UsedResource {
  483. kind: match e[0] {
  484. 0 => ResourceType::Srv,
  485. 1 => ResourceType::Sampler,
  486. 2 => ResourceType::Cbv,
  487. 3 => ResourceType::Uav,
  488. n => ResourceType::Other(n),
  489. },
  490. root: RootType::from_raw(e[1].into()),
  491. table_offset_dwords: le32(e, 4),
  492. lower_bound: le32(e, 8),
  493. stride: le32(e, 12),
  494. dwords: e[16],
  495. user_data: e[17],
  496. slot: e[18],
  497. })
  498. .collect();
  499. // The record is in bounds, so its end is too.
  500. let stage_data = &payload[(start + RECORD_SIZE) as usize..];
  501. let io = match stage {
  502. HwStage::Ps => ps_io(stage_data, code.len())?,
  503. HwStage::Vs => vs_io(stage_data)?,
  504. HwStage::Cs => StageIo::Cs(ComputeIo {
  505. rsrc2: u32_at(stage_data, CS_RSRC2)?,
  506. threads: [
  507. u32_at(stage_data, CS_THREADS)?,
  508. u32_at(stage_data, CS_THREADS + 4)?,
  509. u32_at(stage_data, CS_THREADS + 8)?,
  510. ],
  511. }),
  512. HwStage::Ms => ms_io(stage_data, u32_at(record, RECORD_LDS)?)?,
  513. _ => StageIo::None,
  514. };
  515. out.push(NativeProgram {
  516. stage,
  517. wave64: u32_at(record, RECORD_FLAGS)? & FLAG_WAVE32 == 0,
  518. vgprs,
  519. layout,
  520. used,
  521. io,
  522. code: code.to_vec(),
  523. });
  524. }
  525. Ok(out)
  526. }
  527. /// The entries of `size` bytes from `at`, with their count at `count_at`.
  528. fn semantics(data: &[u8], at: usize, size: usize, count_at: usize) -> Result<&[u8], ShaderError> {
  529. let count = u32_at(data, count_at)?;
  530. if count > MAX_SEMANTICS {
  531. return Err(Malformed("implausible semantic count"));
  532. }
  533. data.get(at..at + size * count as usize)
  534. .ok_or(Malformed("stage data out of bounds"))
  535. }
  536. fn ps_io(data: &[u8], code_len: usize) -> Result<StageIo, ShaderError> {
  537. let inputs = semantics(data, PS_INPUTS, 8, PS_INPUT_COUNT)?
  538. .as_chunks::<8>()
  539. .0
  540. .iter()
  541. .map(|e| PsInput {
  542. usage: Usage::from_raw(e[0]),
  543. row: e[1],
  544. mask: e[2] & 0xf,
  545. attr: e[3],
  546. flat: e[7] & 1 != 0,
  547. fp16: e[7] & 8 != 0,
  548. pack2: e[7] & 0x10 != 0,
  549. row2: e[5],
  550. })
  551. .collect();
  552. let size = u32_at(data, PS_PATCH_SIZE)? as usize;
  553. if size > PATCH_SLOT_DWORDS {
  554. return Err(Malformed("implausible export patch size"));
  555. }
  556. let mut patches = Vec::new();
  557. for mrt in 0..MRTS {
  558. let at = PS_PATCHES + mrt * PATCH_BYTES;
  559. let offset = u32_at(data, at)?;
  560. if offset == u32::MAX {
  561. continue;
  562. }
  563. if (offset as usize + size) * 4 > code_len {
  564. return Err(Malformed("export patch outside the code"));
  565. }
  566. let full = at + 4 + PATCH_FULL * PATCH_SLOT_DWORDS * 4;
  567. let code = (0..size)
  568. .map(|i| u32_at(data, full + 4 * i))
  569. .collect::<Result<_, _>>()?;
  570. patches.push(ExportPatch {
  571. mrt: mrt as u8,
  572. offset,
  573. code,
  574. });
  575. }
  576. Ok(StageIo::Ps {
  577. inputs,
  578. input_addr: u32_at(data, PS_INPUT_ADDR)?,
  579. db_shader_control: u32_at(data, PS_DB_SHADER_CONTROL)?,
  580. patches,
  581. })
  582. }
  583. fn vs_io(data: &[u8]) -> Result<StageIo, ShaderError> {
  584. let inputs = semantics(data, VS_INPUTS, 5, VS_INPUT_COUNT)?
  585. .as_chunks::<5>()
  586. .0
  587. .iter()
  588. .map(|e| VsInput {
  589. usage: Usage::from_raw(e[0]),
  590. row: e[1],
  591. mask: e[2] & 0xf,
  592. vgpr: e[3],
  593. })
  594. .collect();
  595. let outputs = semantics(data, VS_OUTPUTS, 6, VS_OUTPUT_COUNT)?
  596. .as_chunks::<6>()
  597. .0
  598. .iter()
  599. .map(|e| VsOutput {
  600. usage: Usage::from_raw(e[0]),
  601. row: e[1],
  602. param: e[2],
  603. fp16: e[5] & 1 != 0,
  604. pack2: e[5] & 2 != 0,
  605. })
  606. .collect();
  607. Ok(StageIo::Vs { inputs, outputs })
  608. }
  609. fn ms_io(data: &[u8], lds_bytes: u32) -> Result<StageIo, ShaderError> {
  610. let StageIo::Vs { outputs, .. } = vs_io(data)? else {
  611. unreachable!()
  612. };
  613. let info = data
  614. .get(MS_INFO..MS_INFO + 8)
  615. .ok_or(Malformed("stage data out of bounds"))?;
  616. let half = |at: usize| u32::from(u16::from_le_bytes([info[at], info[at + 1]]));
  617. Ok(StageIo::Ms(MeshIo {
  618. outputs,
  619. clip_cntl: u32_at(data, MS_CLIP_CNTL)?,
  620. threads: half(0),
  621. max_vertices: half(2),
  622. max_primitives: half(4),
  623. topology: info[7],
  624. lds_bytes,
  625. }))
  626. }
  627. /// For entries already sized by `as_chunks`.
  628. fn le32(entry: &[u8], at: usize) -> u32 {
  629. u32::from_le_bytes(entry[at..at + 4].try_into().unwrap())
  630. }
  631. /// `data[offset..offset + len]` with untrusted 64-bit bounds.
  632. fn bytes(data: &[u8], offset: u64, len: u64) -> Option<&[u8]> {
  633. let start = usize::try_from(offset).ok()?;
  634. data.get(start..start.checked_add(usize::try_from(len).ok()?)?)
  635. }
  636. #[cfg(test)]
  637. mod tests {
  638. use super::*;
  639. const VS_CODE: [u8; 8] = [1, 2, 3, 4, 5, 6, 7, 8];
  640. const PS_CODE: [u8; 4] = [9, 10, 11, 12];
  641. const VGPRS: u32 = 28;
  642. fn slot(stage: HwStage) -> usize {
  643. SLOTS.iter().find(|s| s.0 == stage).unwrap().1
  644. }
  645. /// Stage data: no semantics, and every export patch absent.
  646. const STAGE_DATA: usize = PS_PATCHES + MRTS * PATCH_BYTES;
  647. fn empty_stage_data() -> Vec<u8> {
  648. let mut data = vec![0; STAGE_DATA];
  649. for mrt in 0..MRTS {
  650. let at = PS_PATCHES + mrt * PATCH_BYTES;
  651. data[at..at + 4].copy_from_slice(&u32::MAX.to_le_bytes());
  652. }
  653. data
  654. }
  655. /// Where a one-program blob's stage data starts.
  656. fn stage_data_at(blob: &[u8], stage: HwStage) -> usize {
  657. FSSM_HEADER
  658. + u64_at(blob, FSSM_HEADER + slot(stage)).unwrap() as usize
  659. + RECORD_SIZE as usize
  660. }
  661. /// FSSM blob with `programs` as (stage, code) pairs.
  662. fn fssm(programs: &[(HwStage, &[u8])]) -> Vec<u8> {
  663. let mut payload = GRAPHICS_SLOT_COUNT.to_le_bytes().to_vec();
  664. payload.resize(slot(HwStage::Cs) + 8, 0);
  665. for (_, at) in SLOTS {
  666. payload[at..at + 8].copy_from_slice(&ABSENT.to_le_bytes());
  667. }
  668. for &(stage, code) in programs {
  669. let slot = slot(stage);
  670. let record = payload.len() as u64;
  671. payload[slot..slot + 8].copy_from_slice(&record.to_le_bytes());
  672. let code_at = record + RECORD_SIZE + STAGE_DATA as u64;
  673. payload.extend_from_slice(&code_at.to_le_bytes());
  674. payload.extend_from_slice(&(code.len() as u64).to_le_bytes());
  675. let flags = if stage == HwStage::Ps { FLAG_WAVE32 } else { 0 };
  676. payload.extend_from_slice(&[0; 4]);
  677. payload.extend_from_slice(&flags.to_le_bytes());
  678. payload.resize(record as usize + RECORD_REGS, 0);
  679. payload.extend_from_slice(&(VGPRS | 31 << 20).to_le_bytes());
  680. payload.extend_from_slice(&empty_stage_data());
  681. payload.extend_from_slice(code);
  682. }
  683. let mut out = b"FSSM".to_vec();
  684. out.extend_from_slice(&FSSM_VERSION.to_le_bytes());
  685. out.extend_from_slice(&(payload.len() as u64).to_le_bytes());
  686. out.extend_from_slice(&payload);
  687. out
  688. }
  689. fn xbch(unpacked: &[u8]) -> Vec<u8> {
  690. let stream = miniz_oxide::deflate::compress_to_vec_zlib(unpacked, 6);
  691. let mut out = b"XBCH".to_vec();
  692. out.extend_from_slice(&XBCH_VERSION.to_le_bytes());
  693. out.extend_from_slice(&(stream.len() as u64).to_le_bytes());
  694. out.extend_from_slice(&(unpacked.len() as u64).to_le_bytes());
  695. out.extend_from_slice(&stream);
  696. out
  697. }
  698. /// `DXIL` part data: program header, XDAT index, then the blobs.
  699. fn part(blobs: &[(u32, &[u8])]) -> Vec<u8> {
  700. let mut out = vec![0u8; XDAT_OFFSET];
  701. out.extend_from_slice(b"XDAT");
  702. out.extend_from_slice(&(blobs.len() as u32).to_le_bytes());
  703. out.extend_from_slice(&0x24u32.to_le_bytes());
  704. let mut offset = out.len() + 12 * blobs.len();
  705. for (kind, blob) in blobs {
  706. for v in [*kind, offset as u32, blob.len() as u32] {
  707. out.extend_from_slice(&v.to_le_bytes());
  708. }
  709. offset += blob.len();
  710. }
  711. for (_, blob) in blobs {
  712. out.extend_from_slice(blob);
  713. }
  714. out
  715. }
  716. #[test]
  717. fn finds_graphics_programs() {
  718. let native = xbch(&fssm(&[(HwStage::Vs, &VS_CODE), (HwStage::Ps, &PS_CODE)]));
  719. let data = part(&[(0x0a, b"xbop"), (KIND_NATIVE, &native)]);
  720. let found = native_programs(&data).unwrap();
  721. assert_eq!(
  722. found,
  723. [
  724. NativeProgram {
  725. stage: HwStage::Vs,
  726. wave64: true,
  727. vgprs: 28,
  728. layout: vec![],
  729. used: vec![],
  730. io: StageIo::Vs {
  731. inputs: vec![],
  732. outputs: vec![],
  733. },
  734. code: VS_CODE.to_vec()
  735. },
  736. NativeProgram {
  737. stage: HwStage::Ps,
  738. wave64: false,
  739. vgprs: 28,
  740. layout: vec![],
  741. used: vec![],
  742. io: StageIo::Ps {
  743. inputs: vec![],
  744. input_addr: 0,
  745. db_shader_control: 0,
  746. patches: vec![],
  747. },
  748. code: PS_CODE.to_vec()
  749. },
  750. ]
  751. );
  752. }
  753. #[test]
  754. fn reads_root_tables() {
  755. let mut blob = fssm(&[(HwStage::Ps, &PS_CODE)]);
  756. let record = FSSM_HEADER + u64_at(&blob, FSSM_HEADER + slot(HwStage::Ps)).unwrap() as usize;
  757. let tables = (blob.len() - FSSM_HEADER) as u64;
  758. // A table range in s9 (root slot 1), and an SRV read from it.
  759. for v in [3u32, 2, 1, 5] {
  760. blob.extend_from_slice(&v.to_le_bytes());
  761. }
  762. blob.extend_from_slice(&[9, 1, 0, 0, 0, 3, 0, 0]);
  763. for v in [2u32, 5, 4] {
  764. blob.extend_from_slice(&v.to_le_bytes());
  765. }
  766. blob.extend_from_slice(&[8, 9, 1, 0]);
  767. let payload = (blob.len() - FSSM_HEADER) as u64;
  768. blob[8..16].copy_from_slice(&payload.to_le_bytes());
  769. blob[record + RECORD_LAYOUT..][..8].copy_from_slice(&tables.to_le_bytes());
  770. blob[record + RECORD_USED..][..8].copy_from_slice(&(tables + ENTRY_SIZE).to_le_bytes());
  771. blob[record + RECORD_COUNTS..][..8].copy_from_slice(&[1, 0, 0, 0, 1, 0, 0, 0]);
  772. let p = &native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).unwrap()[0];
  773. assert_eq!(
  774. p.layout,
  775. [RootParam {
  776. root: RootType::Table,
  777. table_offset_dwords: 2,
  778. sgprs: 1,
  779. base_register: 5,
  780. user_data: 9,
  781. slot: 1
  782. }]
  783. );
  784. assert_eq!(
  785. p.used,
  786. [UsedResource {
  787. kind: ResourceType::Srv,
  788. root: RootType::Table,
  789. table_offset_dwords: 2,
  790. lower_bound: 5,
  791. stride: 4,
  792. dwords: 8,
  793. user_data: 9,
  794. slot: 1
  795. }]
  796. );
  797. blob[record + RECORD_COUNTS] = 9;
  798. assert!(native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).is_err());
  799. }
  800. #[test]
  801. fn reads_pixel_io_and_applies_the_full_export_patch() {
  802. let code = [0xBF80_0000u32; 4]; // s_nop
  803. let bytes: Vec<u8> = code.iter().flat_map(|w| w.to_le_bytes()).collect();
  804. let mut blob = fssm(&[(HwStage::Ps, &bytes)]);
  805. let e = stage_data_at(&blob, HwStage::Ps);
  806. // TEXCOORD in row 1 (xy), read as attr0, flat.
  807. blob[e + PS_INPUTS..][..8].copy_from_slice(&[6, 1, 3, 0, 0, 0, 1, 1]);
  808. blob[e + PS_INPUT_COUNT..][..4].copy_from_slice(&1u32.to_le_bytes());
  809. blob[e + PS_INPUT_ADDR..][..4].copy_from_slice(&2u32.to_le_bytes());
  810. blob[e + PS_PATCH_SIZE..][..4].copy_from_slice(&2u32.to_le_bytes());
  811. // MRT1 at dword 1: the 32_ABGR variant is `exp mrt1 v0-v3 done`.
  812. let patch = e + PS_PATCHES + PATCH_BYTES;
  813. blob[patch..][..4].copy_from_slice(&1u32.to_le_bytes());
  814. let full = patch + 4 + PATCH_FULL * PATCH_SLOT_DWORDS * 4;
  815. blob[full..][..8].copy_from_slice(&[0x1f, 0x18, 0, 0xf8, 0, 1, 2, 3]);
  816. let p = &native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).unwrap()[0];
  817. let StageIo::Ps {
  818. inputs,
  819. input_addr,
  820. patches,
  821. ..
  822. } = &p.io
  823. else {
  824. panic!("{:?}", p.io)
  825. };
  826. let input = PsInput {
  827. usage: Usage::Generic,
  828. row: 1,
  829. mask: 3,
  830. attr: 0,
  831. flat: true,
  832. fp16: false,
  833. pack2: false,
  834. row2: 0,
  835. };
  836. assert_eq!((&inputs[..], *input_addr), (&[input][..], 2));
  837. assert_eq!(patches.len(), 1);
  838. assert_eq!((patches[0].mrt, patches[0].offset), (1, 1));
  839. let patched = p.patched_code();
  840. assert_eq!(patched[..4], p.code[..4]);
  841. assert_eq!(patched[4..12], [0x1f, 0x18, 0, 0xf8, 0, 1, 2, 3]);
  842. assert_eq!(patched[12..], p.code[12..]);
  843. blob[patch..][..4].copy_from_slice(&3u32.to_le_bytes());
  844. assert!(native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).is_err());
  845. }
  846. #[test]
  847. fn finds_mesh_and_compute_programs() {
  848. for stage in [HwStage::Ms, HwStage::Cs] {
  849. let data = part(&[(KIND_NATIVE, &xbch(&fssm(&[(stage, &VS_CODE)])))]);
  850. let found = native_programs(&data).unwrap();
  851. assert_eq!(found.len(), 1);
  852. assert_eq!(found[0].stage, stage);
  853. }
  854. }
  855. #[test]
  856. fn reads_mesh_outputs_and_limits() {
  857. let mut blob = fssm(&[(HwStage::Ms, &VS_CODE)]);
  858. let e = stage_data_at(&blob, HwStage::Ms);
  859. // param0 is row 1 per vertex, param2 row 0 of the primitive signature.
  860. blob[e + VS_OUTPUTS..][..12].copy_from_slice(&[6, 1, 0, 0, 0, 0, 6, 0, 0x82, 0, 0, 0]);
  861. blob[e + VS_OUTPUT_COUNT..][..4].copy_from_slice(&2u32.to_le_bytes());
  862. blob[e + MS_CLIP_CNTL..][..4].copy_from_slice(&0x0040_000Fu32.to_le_bytes());
  863. // 128 lanes, 128 vertices, 64 primitives, 13 user SGPRs, triangles.
  864. blob[e + MS_INFO..][..8].copy_from_slice(&[0x80, 0, 0x80, 0, 0x40, 0, 13, 2]);
  865. let record = e - RECORD_SIZE as usize;
  866. blob[record + RECORD_LDS..][..4].copy_from_slice(&16u32.to_le_bytes());
  867. let p = &native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).unwrap()[0];
  868. let out = |row, param| VsOutput {
  869. usage: Usage::Generic,
  870. row,
  871. param,
  872. fp16: false,
  873. pack2: false,
  874. };
  875. assert_eq!(
  876. p.io,
  877. StageIo::Ms(MeshIo {
  878. outputs: vec![out(1, 0), out(0, 0x82)],
  879. clip_cntl: 0x0040_000F,
  880. threads: 128,
  881. max_vertices: 128,
  882. max_primitives: 64,
  883. topology: 2,
  884. lds_bytes: 16,
  885. })
  886. );
  887. }
  888. #[test]
  889. fn compute_dispatch_settings() {
  890. // 5 user SGPRs, group id x and y, thread ids in v0-v1, 1 KiB LDS.
  891. let cs = ComputeIo {
  892. rsrc2: 0x1098A,
  893. threads: [16, 16, 1],
  894. };
  895. assert_eq!(cs.user_sgprs(), 5);
  896. assert_eq!(cs.system_sgprs(), ([Some(5), Some(6), None], None));
  897. assert_eq!((cs.thread_id_vgprs(), cs.lds_bytes()), (2, 1024));
  898. // 6 user SGPRs, all three group ids, v0-v2, no LDS.
  899. let cs = ComputeIo {
  900. rsrc2: 0x138C,
  901. threads: [8, 8, 1],
  902. };
  903. assert_eq!(cs.system_sgprs(), ([Some(6), Some(7), Some(8)], None));
  904. assert_eq!((cs.thread_id_vgprs(), cs.lds_bytes()), (3, 0));
  905. }
  906. #[test]
  907. fn initialized_sgprs_covers_user_system_and_scratch() {
  908. // 5 user SGPRs, group ids x and y (s5, s6), no scratch: s0..=s6.
  909. let cs = ComputeIo {
  910. rsrc2: 0x1098A,
  911. threads: [16, 16, 1],
  912. };
  913. assert_eq!(cs.initialized_sgprs(), 7);
  914. // All three group ids after 6 user SGPRs, plus the info SGPR: s0..=s9.
  915. let cs = ComputeIo {
  916. rsrc2: 0x78C,
  917. threads: [8, 8, 1],
  918. };
  919. assert_eq!(cs.initialized_sgprs(), 10);
  920. // The same with scratch enabled adds the wave offset: s0..=s10.
  921. let cs = ComputeIo {
  922. rsrc2: 0x78D,
  923. threads: [8, 8, 1],
  924. };
  925. assert_eq!(cs.initialized_sgprs(), 11);
  926. }
  927. #[test]
  928. fn reads_every_native_blob() {
  929. let es = xbch(&fssm(&[(HwStage::Es, &VS_CODE)]));
  930. let vs = xbch(&fssm(&[(HwStage::Vs, &VS_CODE)]));
  931. let data = part(&[(0x12, &[0; 16]), (KIND_NATIVE, &es), (KIND_NATIVE, &vs)]);
  932. let stages: Vec<_> = native_programs(&data)
  933. .unwrap()
  934. .iter()
  935. .map(|p| p.stage)
  936. .collect();
  937. assert_eq!(stages, [HwStage::Es, HwStage::Vs]);
  938. }
  939. #[test]
  940. fn pc_layout_has_none() {
  941. assert!(native_programs(&[0u8; 64]).unwrap().is_empty());
  942. assert!(
  943. native_programs(&part(&[(0x0a, b"xbop")]))
  944. .unwrap()
  945. .is_empty()
  946. );
  947. }
  948. #[test]
  949. fn rejects_corrupt_blobs() {
  950. let good = xbch(&fssm(&[(HwStage::Ls, &VS_CODE)]));
  951. let corrupt = |at: usize, byte: u8| {
  952. let mut blob = good.clone();
  953. blob[at] = byte;
  954. native_programs(&part(&[(KIND_NATIVE, &blob)]))
  955. };
  956. assert!(corrupt(4, 9).is_err(), "unknown version");
  957. assert!(corrupt(16, 0xFF).is_err(), "stated size");
  958. assert!(corrupt(XBCH_HEADER + 2, 0xFF).is_err(), "zlib stream");
  959. assert!(native_programs(&part(&[(KIND_NATIVE, &good[..20])])).is_err());
  960. let mut bad_record = fssm(&[(HwStage::Ls, &VS_CODE)]);
  961. let at = FSSM_HEADER + slot(HwStage::Ls);
  962. bad_record[at..at + 8].copy_from_slice(&u64::MAX.to_le_bytes());
  963. assert!(native_programs(&part(&[(KIND_NATIVE, &xbch(&bad_record))])).is_err());
  964. }
  965. }