native.rs 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254
  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. const FSPX_VERSION: u32 = 1;
  122. const FSPX_HEADER: usize = 0x10;
  123. const FSPX_PACKET: u32 = 0;
  124. const FSPX_CODE: u32 = 6;
  125. const FSPX_METADATA: u32 = 7;
  126. const PACKET_THREADS: usize = 0x0c;
  127. const PACKET_FLAGS: usize = 0x12;
  128. const PACKET_WAVE32: u16 = 1 << 4;
  129. const PACKET_RSRC1: usize = 0x14;
  130. const PACKET_RSRC2: usize = 0x18;
  131. const FSPX_RECORDS: usize = 0x18;
  132. const FSPX_RECORD: usize = 32;
  133. /// Unpacked blobs are a few KiB; refuse to allocate for absurd sizes.
  134. const MAX_UNPACKED: u64 = 16 << 20;
  135. /// Hardware shader stage a native program runs as.
  136. #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
  137. pub enum HwStage {
  138. Ls,
  139. Hs,
  140. Es,
  141. Gs,
  142. Vs,
  143. Ps,
  144. /// Mesh shader.
  145. Ms,
  146. Cs,
  147. }
  148. impl HwStage {
  149. /// The SGPR holding user-data dword `index`: merged stages (and mesh
  150. /// shaders, which run as one) have 8 system SGPRs first.
  151. pub fn user_sgpr(self, index: u8) -> u8 {
  152. match self {
  153. HwStage::Ls | HwStage::Hs | HwStage::Es | HwStage::Gs | HwStage::Ms => index + 8,
  154. HwStage::Vs | HwStage::Ps | HwStage::Cs => index,
  155. }
  156. }
  157. }
  158. #[derive(Debug, Clone, PartialEq, Eq)]
  159. pub struct NativeProgram {
  160. pub stage: HwStage,
  161. /// Runs as 64 lanes per wave (else 32); sizes lane masks.
  162. pub wave64: bool,
  163. /// VGPRs the program uses (v0 up to this), the bound of indexed access.
  164. pub vgprs: u16,
  165. /// Where the root signature's parameters arrive (user SGPRs).
  166. pub layout: Vec<RootParam>,
  167. /// The descriptors the program reads, by root parameter.
  168. pub used: Vec<UsedResource>,
  169. pub io: StageIo,
  170. /// GFX10 machine code, as stored.
  171. pub code: Vec<u8>,
  172. }
  173. impl NativeProgram {
  174. /// The code with each render target's export patched for its full
  175. /// 32-bit format, so exports carry the shader's values unconverted (as
  176. /// the console does at pipeline creation for that format).
  177. pub fn patched_code(&self) -> Vec<u8> {
  178. let mut code = self.code.clone();
  179. if let StageIo::Ps { patches, .. } = &self.io {
  180. for p in patches {
  181. let at = p.offset as usize * 4;
  182. for (i, word) in p.code.iter().enumerate() {
  183. code[at + 4 * i..at + 4 * i + 4].copy_from_slice(&word.to_le_bytes());
  184. }
  185. }
  186. }
  187. code
  188. }
  189. }
  190. /// What a semantic is, as the stage data names it.
  191. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
  192. pub enum Usage {
  193. Generic,
  194. ClipDistance,
  195. Other(u8),
  196. }
  197. impl Usage {
  198. fn from_raw(raw: u8) -> Self {
  199. match raw {
  200. 6 => Usage::Generic,
  201. 7 => Usage::ClipDistance,
  202. n => Usage::Other(n),
  203. }
  204. }
  205. }
  206. /// A pixel shader input: what `v_interp` of attribute `attr` reads.
  207. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  208. pub struct PsInput {
  209. pub usage: Usage,
  210. /// Register in the input signature.
  211. pub row: u8,
  212. pub mask: u8,
  213. pub attr: u8,
  214. pub flat: bool,
  215. pub fp16: bool,
  216. /// Two 16-bit values per dword ([`VsOutput::pack2`]); `row2` is the
  217. /// second element's register.
  218. pub pack2: bool,
  219. pub row2: u8,
  220. }
  221. /// A vertex attribute the fetch shader loads: channel k into VGPR `vgpr + k`.
  222. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  223. pub struct VsInput {
  224. pub usage: Usage,
  225. pub row: u8,
  226. pub mask: u8,
  227. pub vgpr: u8,
  228. }
  229. /// What `exp param<param>` of a vertex shader writes.
  230. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  231. pub struct VsOutput {
  232. pub usage: Usage,
  233. /// Register in the output signature.
  234. pub row: u8,
  235. pub param: u8,
  236. /// 16-bit values, one per dword (low half) unless `pack2`: then two per
  237. /// dword, channel c of this row in dword c / 2 (odd channels in the
  238. /// high half), then a second 16-bit row from the next whole dword (the
  239. /// next 16-bit row of the signature no entry names).
  240. pub fp16: bool,
  241. pub pack2: bool,
  242. }
  243. /// The export code of one render target for its full 32-bit format.
  244. #[derive(Debug, Clone, PartialEq, Eq)]
  245. pub struct ExportPatch {
  246. pub mrt: u8,
  247. /// Where it goes in the code, in dwords.
  248. pub offset: u32,
  249. pub code: Vec<u32>,
  250. }
  251. /// Inputs and outputs, for the stages whose stage data is read.
  252. #[derive(Debug, Clone, Default, PartialEq, Eq)]
  253. pub enum StageIo {
  254. #[default]
  255. None,
  256. Vs {
  257. inputs: Vec<VsInput>,
  258. outputs: Vec<VsOutput>,
  259. },
  260. Ps {
  261. inputs: Vec<PsInput>,
  262. /// `SPI_PS_INPUT_ADDR`: which system values arrive in VGPRs.
  263. input_addr: u32,
  264. /// `DB_SHADER_CONTROL`: depth export, kill.
  265. db_shader_control: u32,
  266. patches: Vec<ExportPatch>,
  267. },
  268. Cs(ComputeIo),
  269. Ms(MeshIo),
  270. }
  271. /// A mesh program's outputs and limits. It runs as one hardware NGG stage:
  272. /// lane n of the group (`threads` lanes) exports vertex n (`exp pos`,
  273. /// `exp param`) and primitive n (`exp prim`).
  274. #[derive(Debug, Clone, PartialEq, Eq)]
  275. pub struct MeshIo {
  276. /// `exp param<n>` targets; `param` bit 7 set: a per-primitive output,
  277. /// `row` then a row of the primitive signature (`PSG1`).
  278. pub outputs: Vec<VsOutput>,
  279. /// `PA_CL_VS_OUT_CNTL`: which clip and cull distances `pos1+` carry.
  280. pub clip_cntl: u32,
  281. /// Thread-group size in lanes (the HLSL group rounded up to waves).
  282. pub threads: u32,
  283. pub max_vertices: u32,
  284. pub max_primitives: u32,
  285. /// 1 lines, 2 triangles.
  286. pub topology: u8,
  287. pub lds_bytes: u32,
  288. }
  289. /// A compute program's dispatch settings.
  290. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  291. pub struct ComputeIo {
  292. /// `COMPUTE_PGM_RSRC2`: user SGPRs, which system SGPRs and VGPRs
  293. /// follow them, LDS size.
  294. pub rsrc2: u32,
  295. /// Thread-group size (`numthreads`).
  296. pub threads: [u32; 3],
  297. }
  298. impl ComputeIo {
  299. /// User SGPRs before the system ones.
  300. pub fn user_sgprs(&self) -> u8 {
  301. (self.rsrc2 >> 1 & 0x1F) as u8
  302. }
  303. /// The SGPR of each enabled thread-group id component, in order after
  304. /// the user SGPRs, then the thread-group info SGPR if enabled.
  305. pub fn system_sgprs(&self) -> ([Option<u8>; 3], Option<u8>) {
  306. let mut next = self.user_sgprs();
  307. let mut take = |bit: u32| {
  308. (self.rsrc2 >> bit & 1 != 0).then(|| {
  309. next += 1;
  310. next - 1
  311. })
  312. };
  313. let ids = [take(7), take(8), take(9)];
  314. (ids, take(10))
  315. }
  316. /// SGPRs the hardware initializes: the user SGPRs, the enabled system
  317. /// ones, then the scratch wave offset when scratch is enabled (bit 0).
  318. /// The ones above hold whatever the previous wave left.
  319. pub fn initialized_sgprs(&self) -> u8 {
  320. let (ids, info) = self.system_sgprs();
  321. let end = ids.into_iter().chain([info]).flatten().map(|s| s + 1).max();
  322. end.unwrap_or(0).max(self.user_sgprs()) + (self.rsrc2 & 1) as u8
  323. }
  324. /// Thread id components in v0, v1, v2 (1 to 3).
  325. pub fn thread_id_vgprs(&self) -> u8 {
  326. (self.rsrc2 >> 11 & 3) as u8 + 1
  327. }
  328. /// LDS bytes per thread group (512-byte granules).
  329. pub fn lds_bytes(&self) -> u32 {
  330. (self.rsrc2 >> 15 & 0x1FF) * 512
  331. }
  332. }
  333. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
  334. pub enum RootType {
  335. Constants,
  336. /// A 64-bit buffer address.
  337. Descriptor,
  338. /// The 32-bit heap address of a descriptor table range.
  339. Table,
  340. /// A sampler the root signature fixes.
  341. ImmediateSampler,
  342. /// The 32-bit address of the CBV/SRV/UAV heap (SM 6.6 dynamic resources).
  343. ResourceHeap,
  344. /// The 32-bit address of the sampler heap.
  345. SamplerHeap,
  346. Other(u32),
  347. }
  348. impl RootType {
  349. fn from_raw(raw: u32) -> Self {
  350. match raw {
  351. 0 => RootType::Constants,
  352. 1 => RootType::Descriptor,
  353. 3 => RootType::Table,
  354. 4 => RootType::ImmediateSampler,
  355. 5 => RootType::ResourceHeap,
  356. 6 => RootType::SamplerHeap,
  357. n => RootType::Other(n),
  358. }
  359. }
  360. }
  361. /// One root parameter (or table range) and the user SGPRs holding it.
  362. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  363. pub struct RootParam {
  364. pub root: RootType,
  365. /// Of the range within its table.
  366. pub table_offset_dwords: u32,
  367. /// User SGPRs from `user_data` on.
  368. pub sgprs: u32,
  369. /// Shader register of the first descriptor (`b`/`t`/`u`/`s` number).
  370. pub base_register: u32,
  371. /// First user-data dword ([`HwStage::user_sgpr`]).
  372. pub user_data: u8,
  373. /// Index of the parameter in the root signature.
  374. pub slot: u8,
  375. }
  376. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
  377. pub enum ResourceType {
  378. Srv,
  379. Sampler,
  380. Cbv,
  381. Uav,
  382. Other(u8),
  383. }
  384. /// A descriptor range the program reads.
  385. #[derive(Debug, Clone, Copy, PartialEq, Eq)]
  386. pub struct UsedResource {
  387. pub kind: ResourceType,
  388. pub root: RootType,
  389. pub table_offset_dwords: u32,
  390. /// Shader register of the first descriptor read.
  391. pub lower_bound: u32,
  392. pub stride: u32,
  393. /// Size of the descriptor (4 or 8).
  394. pub dwords: u8,
  395. pub user_data: u8,
  396. pub slot: u8,
  397. }
  398. /// The native programs in a `DXIL` part's data, or in an `ACCC` part's
  399. /// ([`fspx_program`]); empty for the PC layout.
  400. pub fn native_programs(part: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> {
  401. if part.starts_with(b"FSPX") {
  402. return Ok(vec![fspx_program(part)?]);
  403. }
  404. if part.get(XDAT_OFFSET..XDAT_OFFSET + 4) != Some(b"XDAT") {
  405. return Ok(Vec::new());
  406. }
  407. let count = u32_at(part, XDAT_OFFSET + 4)? as usize;
  408. if count > MAX_XDAT_ENTRIES {
  409. return Err(Malformed("implausible XDAT entry count"));
  410. }
  411. let mut out = Vec::new();
  412. for i in 0..count {
  413. let at = XDAT_OFFSET + 12 + 12 * i;
  414. if u32_at(part, at)? != KIND_NATIVE {
  415. continue;
  416. }
  417. let offset = u32_at(part, at + 4)?.into();
  418. let size = u32_at(part, at + 8)?.into();
  419. let blob = bytes(part, offset, size).ok_or(Malformed("XDAT entry out of bounds"))?;
  420. out.extend(programs(&unpack(blob)?)?);
  421. }
  422. Ok(out)
  423. }
  424. /// The compute program of an `ACCC` part, which a container carries in place
  425. /// of `DXIL` when another compiler made the native code (the AMD
  426. /// FidelityFX upscaler's shaders). Layout as observed (offsets from "FSPX"):
  427. ///
  428. /// ```text
  429. /// +0x00 "FSPX" u32 version (1), u32 entry count, u32 size; entries of 16 B
  430. /// from +0x10: u32 kind, u32 offset, u32 size, u32 0
  431. /// kind 0 pipeline registers, 0x1c B: +0x0c u16 x3 thread-group size,
  432. /// +0x12 u16 flags (bit 4 wave32), +0x14 COMPUTE_PGM_RSRC1,
  433. /// +0x18 COMPUTE_PGM_RSRC2
  434. /// kind 1 pipeline metadata (a hash); kind 6 the GFX10 code
  435. /// kind 7 program metadata: u32 0x403, u32 size - 0x14, u32 code dwords,
  436. /// u64 0, u8 0x40, u8 first user-data dword, u8 count of 0x41
  437. /// records, u8 0; then 32-byte records from +0x18, each a u32 tag:
  438. /// 0x41 a resource the code reads: u8 resource type (as FSSM's used
  439. /// entries), u8 root type, u16 0, u32 table offset (dwords), u32
  440. /// register, u32 view dimension (1 buffer, 4 2D, 0 root view),
  441. /// u8 descriptor dwords, u8 user-data dword, u8 root slot, u8 0,
  442. /// u32 -1, u32 0
  443. /// 0x42 a view declaration: u32 0, u8 1, u8 class (0 SRV, 1 UAV),
  444. /// u8 resource kind (DXIL's), u8 0, u32 register
  445. /// 0x43 the shader hash (16 B); the last record
  446. /// ```
  447. pub fn fspx_program(part: &[u8]) -> Result<NativeProgram, ShaderError> {
  448. if u32_at(part, 4)? != FSPX_VERSION {
  449. return Err(Malformed("unknown FSPX version"));
  450. }
  451. let count = u32_at(part, 8)? as usize;
  452. if count > MAX_XDAT_ENTRIES {
  453. return Err(Malformed("implausible FSPX entry count"));
  454. }
  455. let entry = |kind: u32| -> Result<&[u8], ShaderError> {
  456. for i in 0..count {
  457. let at = FSPX_HEADER + 16 * i;
  458. if u32_at(part, at)? == kind {
  459. let (offset, size) = (u32_at(part, at + 4)?, u32_at(part, at + 8)?);
  460. return bytes(part, offset.into(), size.into())
  461. .ok_or(Malformed("FSPX entry out of bounds"));
  462. }
  463. }
  464. Err(Malformed("FSPX entry missing"))
  465. };
  466. let packet = entry(FSPX_PACKET)?;
  467. let code = entry(FSPX_CODE)?;
  468. let meta = entry(FSPX_METADATA)?;
  469. if u32_at(meta, 8)? as usize * 4 != code.len() {
  470. return Err(Malformed("FSPX code size disagrees"));
  471. }
  472. let wave64 = u16_at(packet, PACKET_FLAGS)? & PACKET_WAVE32 == 0;
  473. // VGPRs in granules of 4 (wave64) or 8 (wave32).
  474. let granules = (u32_at(packet, PACKET_RSRC1)? & 0x3F) + 1;
  475. let vgprs = (granules * if wave64 { 4 } else { 8 }).min(256) as u16;
  476. let threads = |i: usize| u16_at(packet, PACKET_THREADS + 2 * i).map(u32::from);
  477. let mut layout: Vec<RootParam> = Vec::new();
  478. let mut used = Vec::new();
  479. for e in meta
  480. .get(FSPX_RECORDS..)
  481. .unwrap_or(&[])
  482. .as_chunks::<FSPX_RECORD>()
  483. .0
  484. {
  485. match e[0] {
  486. 0x41 => {}
  487. 0x42 => continue,
  488. 0x43 => break,
  489. _ => return Err(Malformed("unknown FSPX metadata record")),
  490. }
  491. let root = RootType::from_raw(e[5].into());
  492. let u = UsedResource {
  493. kind: match e[4] {
  494. 0 => ResourceType::Srv,
  495. 1 => ResourceType::Sampler,
  496. 2 => ResourceType::Cbv,
  497. 3 => ResourceType::Uav,
  498. n => ResourceType::Other(n),
  499. },
  500. root,
  501. table_offset_dwords: le32(e, 8),
  502. lower_bound: le32(e, 12),
  503. stride: 0,
  504. dwords: e[20],
  505. user_data: e[21],
  506. slot: e[22],
  507. };
  508. let sgprs = match root {
  509. RootType::Table => 1,
  510. RootType::Descriptor => 2,
  511. // The code holds its words; no user data.
  512. RootType::ImmediateSampler => 0,
  513. _ => return Err(Malformed("an FSPX resource of an unknown root type")),
  514. };
  515. if sgprs > 0 && !layout.iter().any(|p| p.slot == u.slot) {
  516. layout.push(RootParam {
  517. root,
  518. table_offset_dwords: 0,
  519. sgprs,
  520. base_register: u.lower_bound,
  521. user_data: u.user_data,
  522. slot: u.slot,
  523. });
  524. }
  525. used.push(u);
  526. }
  527. Ok(NativeProgram {
  528. stage: HwStage::Cs,
  529. wave64,
  530. vgprs,
  531. layout,
  532. used,
  533. io: StageIo::Cs(ComputeIo {
  534. rsrc2: u32_at(packet, PACKET_RSRC2)?,
  535. threads: [threads(0)?, threads(1)?, threads(2)?],
  536. }),
  537. code: code.to_vec(),
  538. })
  539. }
  540. fn u16_at(data: &[u8], at: usize) -> Result<u16, ShaderError> {
  541. data.get(at..at + 2)
  542. .map(|b| u16::from_le_bytes([b[0], b[1]]))
  543. .ok_or(Malformed("FSPX data out of bounds"))
  544. }
  545. fn unpack(blob: &[u8]) -> Result<Vec<u8>, ShaderError> {
  546. if blob.get(0..4) != Some(b"XBCH") {
  547. return Err(Malformed("native blob lacks XBCH magic"));
  548. }
  549. if u32_at(blob, 4)? != XBCH_VERSION {
  550. return Err(Malformed("unknown XBCH version"));
  551. }
  552. let packed = u64_at(blob, 8)?;
  553. let unpacked = u64_at(blob, 16)?;
  554. if unpacked > MAX_UNPACKED {
  555. return Err(Malformed("implausible XBCH unpacked size"));
  556. }
  557. let stream =
  558. bytes(blob, XBCH_HEADER as u64, packed).ok_or(Malformed("XBCH stream out of bounds"))?;
  559. let out = inflate_zlib_exact(stream, unpacked as usize)
  560. .ok_or(Malformed("XBCH stream does not inflate to its stated size"))?;
  561. Ok(out)
  562. }
  563. /// Inflates a zlib stream incrementally up to `expected` bytes, rejecting
  564. /// truncated, corrupt, under-filled, or oversized streams without eagerly
  565. /// allocating the full declared size up front.
  566. fn inflate_zlib_exact(source: &[u8], expected: usize) -> Option<Vec<u8>> {
  567. let mut state = zlib_rs::Inflate::new(true, 15);
  568. let mut out = Vec::new();
  569. let (mut in_pos, mut out_pos) = (0usize, 0usize);
  570. loop {
  571. if out_pos == expected {
  572. let mut extra = [0u8; 1];
  573. let status = state
  574. .decompress(
  575. &source[in_pos..],
  576. &mut extra,
  577. zlib_rs::InflateFlush::NoFlush,
  578. )
  579. .ok()?;
  580. return (status == zlib_rs::Status::StreamEnd
  581. && state.total_out() as usize == expected)
  582. .then_some(out);
  583. }
  584. if out_pos == out.len() {
  585. let next_len = if out.is_empty() {
  586. expected.min(source.len().saturating_mul(4).max(4096))
  587. } else {
  588. out.len().saturating_mul(2).min(expected)
  589. };
  590. out.resize(next_len, 0);
  591. }
  592. let status = state
  593. .decompress(
  594. &source[in_pos..],
  595. &mut out[out_pos..],
  596. zlib_rs::InflateFlush::NoFlush,
  597. )
  598. .ok()?;
  599. let next_in = state.total_in() as usize;
  600. let next_out = state.total_out() as usize;
  601. match status {
  602. zlib_rs::Status::StreamEnd => {
  603. out.truncate(next_out);
  604. return (next_out == expected).then_some(out);
  605. }
  606. zlib_rs::Status::Ok if next_in != in_pos || next_out != out_pos => {
  607. in_pos = next_in;
  608. out_pos = next_out;
  609. }
  610. zlib_rs::Status::Ok | zlib_rs::Status::BufError => return None,
  611. }
  612. }
  613. }
  614. fn programs(fssm: &[u8]) -> Result<Vec<NativeProgram>, ShaderError> {
  615. if fssm.get(0..4) != Some(b"FSSM") {
  616. return Err(Malformed("native blob lacks FSSM magic"));
  617. }
  618. if u32_at(fssm, 4)? != FSSM_VERSION {
  619. return Err(Malformed("unknown FSSM version"));
  620. }
  621. let payload = &fssm[FSSM_HEADER.min(fssm.len())..];
  622. if u64_at(fssm, 8)? != payload.len() as u64 {
  623. return Err(Malformed("FSSM payload size disagrees"));
  624. }
  625. if u64_at(payload, 0)? != GRAPHICS_SLOT_COUNT {
  626. return Err(Malformed("unexpected FSSM slot count"));
  627. }
  628. let mut out = Vec::new();
  629. for (stage, at) in SLOTS {
  630. let start = u64_at(payload, at)?;
  631. if start == ABSENT {
  632. continue;
  633. }
  634. let record =
  635. bytes(payload, start, RECORD_SIZE).ok_or(Malformed("FSSM record out of bounds"))?;
  636. let code = bytes(payload, u64_at(record, 0)?, u64_at(record, 8)?)
  637. .ok_or(Malformed("native code out of bounds"))?;
  638. let vgprs = (u32_at(record, RECORD_REGS)? & 0x3FF) as u16;
  639. if vgprs > 256 {
  640. return Err(Malformed("implausible VGPR count"));
  641. }
  642. let table = |at: usize, count_at: usize| -> Result<&[u8], ShaderError> {
  643. let len = ENTRY_SIZE * u64::from(u32_at(record, count_at)?);
  644. if len == 0 {
  645. return Ok(&[]);
  646. }
  647. bytes(payload, u64_at(record, at)?, len)
  648. .ok_or(Malformed("FSSM root table out of bounds"))
  649. };
  650. let layout = table(RECORD_LAYOUT, RECORD_COUNTS)?
  651. .as_chunks::<{ ENTRY_SIZE as usize }>()
  652. .0
  653. .iter()
  654. .map(|e| RootParam {
  655. root: RootType::from_raw(le32(e, 0)),
  656. table_offset_dwords: le32(e, 4),
  657. sgprs: le32(e, 8),
  658. base_register: le32(e, 12),
  659. user_data: e[16],
  660. slot: e[17],
  661. })
  662. .collect();
  663. let used = table(RECORD_USED, RECORD_COUNTS + 4)?
  664. .as_chunks::<{ ENTRY_SIZE as usize }>()
  665. .0
  666. .iter()
  667. .map(|e| UsedResource {
  668. kind: match e[0] {
  669. 0 => ResourceType::Srv,
  670. 1 => ResourceType::Sampler,
  671. 2 => ResourceType::Cbv,
  672. 3 => ResourceType::Uav,
  673. n => ResourceType::Other(n),
  674. },
  675. root: RootType::from_raw(e[1].into()),
  676. table_offset_dwords: le32(e, 4),
  677. lower_bound: le32(e, 8),
  678. stride: le32(e, 12),
  679. dwords: e[16],
  680. user_data: e[17],
  681. slot: e[18],
  682. })
  683. .collect();
  684. // The record is in bounds, so its end is too.
  685. let stage_data = &payload[(start + RECORD_SIZE) as usize..];
  686. let io = match stage {
  687. HwStage::Ps => ps_io(stage_data, code.len())?,
  688. HwStage::Vs => vs_io(stage_data)?,
  689. HwStage::Cs => StageIo::Cs(ComputeIo {
  690. rsrc2: u32_at(stage_data, CS_RSRC2)?,
  691. threads: [
  692. u32_at(stage_data, CS_THREADS)?,
  693. u32_at(stage_data, CS_THREADS + 4)?,
  694. u32_at(stage_data, CS_THREADS + 8)?,
  695. ],
  696. }),
  697. HwStage::Ms => ms_io(stage_data, u32_at(record, RECORD_LDS)?)?,
  698. _ => StageIo::None,
  699. };
  700. out.push(NativeProgram {
  701. stage,
  702. wave64: u32_at(record, RECORD_FLAGS)? & FLAG_WAVE32 == 0,
  703. vgprs,
  704. layout,
  705. used,
  706. io,
  707. code: code.to_vec(),
  708. });
  709. }
  710. Ok(out)
  711. }
  712. /// The entries of `size` bytes from `at`, with their count at `count_at`.
  713. fn semantics(data: &[u8], at: usize, size: usize, count_at: usize) -> Result<&[u8], ShaderError> {
  714. let count = u32_at(data, count_at)?;
  715. if count > MAX_SEMANTICS {
  716. return Err(Malformed("implausible semantic count"));
  717. }
  718. data.get(at..at + size * count as usize)
  719. .ok_or(Malformed("stage data out of bounds"))
  720. }
  721. fn ps_io(data: &[u8], code_len: usize) -> Result<StageIo, ShaderError> {
  722. let inputs = semantics(data, PS_INPUTS, 8, PS_INPUT_COUNT)?
  723. .as_chunks::<8>()
  724. .0
  725. .iter()
  726. .map(|e| PsInput {
  727. usage: Usage::from_raw(e[0]),
  728. row: e[1],
  729. mask: e[2] & 0xf,
  730. attr: e[3],
  731. flat: e[7] & 1 != 0,
  732. fp16: e[7] & 8 != 0,
  733. pack2: e[7] & 0x10 != 0,
  734. row2: e[5],
  735. })
  736. .collect();
  737. let size = u32_at(data, PS_PATCH_SIZE)? as usize;
  738. if size > PATCH_SLOT_DWORDS {
  739. return Err(Malformed("implausible export patch size"));
  740. }
  741. let mut patches = Vec::new();
  742. for mrt in 0..MRTS {
  743. let at = PS_PATCHES + mrt * PATCH_BYTES;
  744. let offset = u32_at(data, at)?;
  745. if offset == u32::MAX {
  746. continue;
  747. }
  748. if (offset as usize + size) * 4 > code_len {
  749. return Err(Malformed("export patch outside the code"));
  750. }
  751. let full = at + 4 + PATCH_FULL * PATCH_SLOT_DWORDS * 4;
  752. let code = (0..size)
  753. .map(|i| u32_at(data, full + 4 * i))
  754. .collect::<Result<_, _>>()?;
  755. patches.push(ExportPatch {
  756. mrt: mrt as u8,
  757. offset,
  758. code,
  759. });
  760. }
  761. Ok(StageIo::Ps {
  762. inputs,
  763. input_addr: u32_at(data, PS_INPUT_ADDR)?,
  764. db_shader_control: u32_at(data, PS_DB_SHADER_CONTROL)?,
  765. patches,
  766. })
  767. }
  768. fn vs_outputs(data: &[u8]) -> Result<Vec<VsOutput>, ShaderError> {
  769. Ok(semantics(data, VS_OUTPUTS, 6, VS_OUTPUT_COUNT)?
  770. .as_chunks::<6>()
  771. .0
  772. .iter()
  773. .map(|e| VsOutput {
  774. usage: Usage::from_raw(e[0]),
  775. row: e[1],
  776. param: e[2],
  777. fp16: e[5] & 1 != 0,
  778. pack2: e[5] & 2 != 0,
  779. })
  780. .collect())
  781. }
  782. fn vs_io(data: &[u8]) -> Result<StageIo, ShaderError> {
  783. let inputs = semantics(data, VS_INPUTS, 5, VS_INPUT_COUNT)?
  784. .as_chunks::<5>()
  785. .0
  786. .iter()
  787. .map(|e| VsInput {
  788. usage: Usage::from_raw(e[0]),
  789. row: e[1],
  790. mask: e[2] & 0xf,
  791. vgpr: e[3],
  792. })
  793. .collect();
  794. let outputs = vs_outputs(data)?;
  795. Ok(StageIo::Vs { inputs, outputs })
  796. }
  797. fn ms_io(data: &[u8], lds_bytes: u32) -> Result<StageIo, ShaderError> {
  798. let outputs = vs_outputs(data)?;
  799. let info = data
  800. .get(MS_INFO..MS_INFO + 8)
  801. .ok_or(Malformed("stage data out of bounds"))?;
  802. let half = |at: usize| u32::from(u16::from_le_bytes([info[at], info[at + 1]]));
  803. Ok(StageIo::Ms(MeshIo {
  804. outputs,
  805. clip_cntl: u32_at(data, MS_CLIP_CNTL)?,
  806. threads: half(0),
  807. max_vertices: half(2),
  808. max_primitives: half(4),
  809. topology: info[7],
  810. lds_bytes,
  811. }))
  812. }
  813. /// For entries already sized by `as_chunks`.
  814. fn le32(entry: &[u8], at: usize) -> u32 {
  815. u32::from_le_bytes(entry[at..at + 4].try_into().unwrap())
  816. }
  817. /// `data[offset..offset + len]` with untrusted 64-bit bounds.
  818. fn bytes(data: &[u8], offset: u64, len: u64) -> Option<&[u8]> {
  819. let start = usize::try_from(offset).ok()?;
  820. data.get(start..start.checked_add(usize::try_from(len).ok()?)?)
  821. }
  822. #[cfg(test)]
  823. mod tests {
  824. use super::*;
  825. const VS_CODE: [u8; 8] = [1, 2, 3, 4, 5, 6, 7, 8];
  826. const PS_CODE: [u8; 4] = [9, 10, 11, 12];
  827. const VGPRS: u32 = 28;
  828. fn slot(stage: HwStage) -> usize {
  829. SLOTS.iter().find(|s| s.0 == stage).unwrap().1
  830. }
  831. /// Stage data: no semantics, and every export patch absent.
  832. const STAGE_DATA: usize = PS_PATCHES + MRTS * PATCH_BYTES;
  833. fn empty_stage_data() -> Vec<u8> {
  834. let mut data = vec![0; STAGE_DATA];
  835. for mrt in 0..MRTS {
  836. let at = PS_PATCHES + mrt * PATCH_BYTES;
  837. data[at..at + 4].copy_from_slice(&u32::MAX.to_le_bytes());
  838. }
  839. data
  840. }
  841. /// Where a one-program blob's stage data starts.
  842. fn stage_data_at(blob: &[u8], stage: HwStage) -> usize {
  843. FSSM_HEADER
  844. + u64_at(blob, FSSM_HEADER + slot(stage)).unwrap() as usize
  845. + RECORD_SIZE as usize
  846. }
  847. /// FSSM blob with `programs` as (stage, code) pairs.
  848. fn fssm(programs: &[(HwStage, &[u8])]) -> Vec<u8> {
  849. let mut payload = GRAPHICS_SLOT_COUNT.to_le_bytes().to_vec();
  850. payload.resize(slot(HwStage::Cs) + 8, 0);
  851. for (_, at) in SLOTS {
  852. payload[at..at + 8].copy_from_slice(&ABSENT.to_le_bytes());
  853. }
  854. for &(stage, code) in programs {
  855. let slot = slot(stage);
  856. let record = payload.len() as u64;
  857. payload[slot..slot + 8].copy_from_slice(&record.to_le_bytes());
  858. let code_at = record + RECORD_SIZE + STAGE_DATA as u64;
  859. payload.extend_from_slice(&code_at.to_le_bytes());
  860. payload.extend_from_slice(&(code.len() as u64).to_le_bytes());
  861. let flags = if stage == HwStage::Ps { FLAG_WAVE32 } else { 0 };
  862. payload.extend_from_slice(&[0; 4]);
  863. payload.extend_from_slice(&flags.to_le_bytes());
  864. payload.resize(record as usize + RECORD_REGS, 0);
  865. payload.extend_from_slice(&(VGPRS | 31 << 20).to_le_bytes());
  866. payload.extend_from_slice(&empty_stage_data());
  867. payload.extend_from_slice(code);
  868. }
  869. let mut out = b"FSSM".to_vec();
  870. out.extend_from_slice(&FSSM_VERSION.to_le_bytes());
  871. out.extend_from_slice(&(payload.len() as u64).to_le_bytes());
  872. out.extend_from_slice(&payload);
  873. out
  874. }
  875. fn xbch(unpacked: &[u8]) -> Vec<u8> {
  876. let mut buf = vec![0u8; zlib_rs::compress_bound(unpacked.len())];
  877. let (stream, rc) =
  878. zlib_rs::compress_slice(&mut buf, unpacked, zlib_rs::DeflateConfig::new(6));
  879. assert_eq!(rc, zlib_rs::ReturnCode::Ok);
  880. let mut out = b"XBCH".to_vec();
  881. out.extend_from_slice(&XBCH_VERSION.to_le_bytes());
  882. out.extend_from_slice(&(stream.len() as u64).to_le_bytes());
  883. out.extend_from_slice(&(unpacked.len() as u64).to_le_bytes());
  884. out.extend_from_slice(stream);
  885. out
  886. }
  887. /// `DXIL` part data: program header, XDAT index, then the blobs.
  888. fn part(blobs: &[(u32, &[u8])]) -> Vec<u8> {
  889. let mut out = vec![0u8; XDAT_OFFSET];
  890. out.extend_from_slice(b"XDAT");
  891. out.extend_from_slice(&(blobs.len() as u32).to_le_bytes());
  892. out.extend_from_slice(&0x24u32.to_le_bytes());
  893. let mut offset = out.len() + 12 * blobs.len();
  894. for (kind, blob) in blobs {
  895. for v in [*kind, offset as u32, blob.len() as u32] {
  896. out.extend_from_slice(&v.to_le_bytes());
  897. }
  898. offset += blob.len();
  899. }
  900. for (_, blob) in blobs {
  901. out.extend_from_slice(blob);
  902. }
  903. out
  904. }
  905. #[test]
  906. fn finds_graphics_programs() {
  907. let native = xbch(&fssm(&[(HwStage::Vs, &VS_CODE), (HwStage::Ps, &PS_CODE)]));
  908. let data = part(&[(0x0a, b"xbop"), (KIND_NATIVE, &native)]);
  909. let found = native_programs(&data).unwrap();
  910. assert_eq!(
  911. found,
  912. [
  913. NativeProgram {
  914. stage: HwStage::Vs,
  915. wave64: true,
  916. vgprs: 28,
  917. layout: vec![],
  918. used: vec![],
  919. io: StageIo::Vs {
  920. inputs: vec![],
  921. outputs: vec![],
  922. },
  923. code: VS_CODE.to_vec()
  924. },
  925. NativeProgram {
  926. stage: HwStage::Ps,
  927. wave64: false,
  928. vgprs: 28,
  929. layout: vec![],
  930. used: vec![],
  931. io: StageIo::Ps {
  932. inputs: vec![],
  933. input_addr: 0,
  934. db_shader_control: 0,
  935. patches: vec![],
  936. },
  937. code: PS_CODE.to_vec()
  938. },
  939. ]
  940. );
  941. }
  942. #[test]
  943. fn reads_root_tables() {
  944. let mut blob = fssm(&[(HwStage::Ps, &PS_CODE)]);
  945. let record = FSSM_HEADER + u64_at(&blob, FSSM_HEADER + slot(HwStage::Ps)).unwrap() as usize;
  946. let tables = (blob.len() - FSSM_HEADER) as u64;
  947. // A table range in s9 (root slot 1), and an SRV read from it.
  948. for v in [3u32, 2, 1, 5] {
  949. blob.extend_from_slice(&v.to_le_bytes());
  950. }
  951. blob.extend_from_slice(&[9, 1, 0, 0, 0, 3, 0, 0]);
  952. for v in [2u32, 5, 4] {
  953. blob.extend_from_slice(&v.to_le_bytes());
  954. }
  955. blob.extend_from_slice(&[8, 9, 1, 0]);
  956. let payload = (blob.len() - FSSM_HEADER) as u64;
  957. blob[8..16].copy_from_slice(&payload.to_le_bytes());
  958. blob[record + RECORD_LAYOUT..][..8].copy_from_slice(&tables.to_le_bytes());
  959. blob[record + RECORD_USED..][..8].copy_from_slice(&(tables + ENTRY_SIZE).to_le_bytes());
  960. blob[record + RECORD_COUNTS..][..8].copy_from_slice(&[1, 0, 0, 0, 1, 0, 0, 0]);
  961. let p = &native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).unwrap()[0];
  962. assert_eq!(
  963. p.layout,
  964. [RootParam {
  965. root: RootType::Table,
  966. table_offset_dwords: 2,
  967. sgprs: 1,
  968. base_register: 5,
  969. user_data: 9,
  970. slot: 1
  971. }]
  972. );
  973. assert_eq!(
  974. p.used,
  975. [UsedResource {
  976. kind: ResourceType::Srv,
  977. root: RootType::Table,
  978. table_offset_dwords: 2,
  979. lower_bound: 5,
  980. stride: 4,
  981. dwords: 8,
  982. user_data: 9,
  983. slot: 1
  984. }]
  985. );
  986. blob[record + RECORD_COUNTS] = 9;
  987. assert!(native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).is_err());
  988. }
  989. #[test]
  990. fn reads_pixel_io_and_applies_the_full_export_patch() {
  991. let code = [0xBF80_0000u32; 4]; // s_nop
  992. let bytes: Vec<u8> = code.iter().flat_map(|w| w.to_le_bytes()).collect();
  993. let mut blob = fssm(&[(HwStage::Ps, &bytes)]);
  994. let e = stage_data_at(&blob, HwStage::Ps);
  995. // TEXCOORD in row 1 (xy), read as attr0, flat.
  996. blob[e + PS_INPUTS..][..8].copy_from_slice(&[6, 1, 3, 0, 0, 0, 1, 1]);
  997. blob[e + PS_INPUT_COUNT..][..4].copy_from_slice(&1u32.to_le_bytes());
  998. blob[e + PS_INPUT_ADDR..][..4].copy_from_slice(&2u32.to_le_bytes());
  999. blob[e + PS_PATCH_SIZE..][..4].copy_from_slice(&2u32.to_le_bytes());
  1000. // MRT1 at dword 1: the 32_ABGR variant is `exp mrt1 v0-v3 done`.
  1001. let patch = e + PS_PATCHES + PATCH_BYTES;
  1002. blob[patch..][..4].copy_from_slice(&1u32.to_le_bytes());
  1003. let full = patch + 4 + PATCH_FULL * PATCH_SLOT_DWORDS * 4;
  1004. blob[full..][..8].copy_from_slice(&[0x1f, 0x18, 0, 0xf8, 0, 1, 2, 3]);
  1005. let p = &native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).unwrap()[0];
  1006. let StageIo::Ps {
  1007. inputs,
  1008. input_addr,
  1009. patches,
  1010. ..
  1011. } = &p.io
  1012. else {
  1013. panic!("{:?}", p.io)
  1014. };
  1015. let input = PsInput {
  1016. usage: Usage::Generic,
  1017. row: 1,
  1018. mask: 3,
  1019. attr: 0,
  1020. flat: true,
  1021. fp16: false,
  1022. pack2: false,
  1023. row2: 0,
  1024. };
  1025. assert_eq!((&inputs[..], *input_addr), (&[input][..], 2));
  1026. assert_eq!(patches.len(), 1);
  1027. assert_eq!((patches[0].mrt, patches[0].offset), (1, 1));
  1028. let patched = p.patched_code();
  1029. assert_eq!(patched[..4], p.code[..4]);
  1030. assert_eq!(patched[4..12], [0x1f, 0x18, 0, 0xf8, 0, 1, 2, 3]);
  1031. assert_eq!(patched[12..], p.code[12..]);
  1032. blob[patch..][..4].copy_from_slice(&3u32.to_le_bytes());
  1033. assert!(native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).is_err());
  1034. }
  1035. #[test]
  1036. fn finds_mesh_and_compute_programs() {
  1037. for stage in [HwStage::Ms, HwStage::Cs] {
  1038. let data = part(&[(KIND_NATIVE, &xbch(&fssm(&[(stage, &VS_CODE)])))]);
  1039. let found = native_programs(&data).unwrap();
  1040. assert_eq!(found.len(), 1);
  1041. assert_eq!(found[0].stage, stage);
  1042. }
  1043. }
  1044. #[test]
  1045. fn reads_mesh_outputs_and_limits() {
  1046. let mut blob = fssm(&[(HwStage::Ms, &VS_CODE)]);
  1047. let e = stage_data_at(&blob, HwStage::Ms);
  1048. // param0 is row 1 per vertex, param2 row 0 of the primitive signature.
  1049. blob[e + VS_OUTPUTS..][..12].copy_from_slice(&[6, 1, 0, 0, 0, 0, 6, 0, 0x82, 0, 0, 0]);
  1050. blob[e + VS_OUTPUT_COUNT..][..4].copy_from_slice(&2u32.to_le_bytes());
  1051. blob[e + MS_CLIP_CNTL..][..4].copy_from_slice(&0x0040_000Fu32.to_le_bytes());
  1052. // 128 lanes, 128 vertices, 64 primitives, 13 user SGPRs, triangles.
  1053. blob[e + MS_INFO..][..8].copy_from_slice(&[0x80, 0, 0x80, 0, 0x40, 0, 13, 2]);
  1054. let record = e - RECORD_SIZE as usize;
  1055. blob[record + RECORD_LDS..][..4].copy_from_slice(&16u32.to_le_bytes());
  1056. let p = &native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).unwrap()[0];
  1057. let out = |row, param| VsOutput {
  1058. usage: Usage::Generic,
  1059. row,
  1060. param,
  1061. fp16: false,
  1062. pack2: false,
  1063. };
  1064. assert_eq!(
  1065. p.io,
  1066. StageIo::Ms(MeshIo {
  1067. outputs: vec![out(1, 0), out(0, 0x82)],
  1068. clip_cntl: 0x0040_000F,
  1069. threads: 128,
  1070. max_vertices: 128,
  1071. max_primitives: 64,
  1072. topology: 2,
  1073. lds_bytes: 16,
  1074. })
  1075. );
  1076. }
  1077. #[test]
  1078. fn mesh_stage_io_ignores_unused_vs_input_count() {
  1079. let mut blob = fssm(&[(HwStage::Ms, &VS_CODE)]);
  1080. let e = stage_data_at(&blob, HwStage::Ms);
  1081. // Mesh stage data has no vertex inputs; E+0xc4 is unused by MS.
  1082. blob[e + VS_INPUT_COUNT..][..4].copy_from_slice(&u32::MAX.to_le_bytes());
  1083. let p = &native_programs(&part(&[(KIND_NATIVE, &xbch(&blob))])).unwrap()[0];
  1084. assert!(matches!(p.io, StageIo::Ms(_)));
  1085. }
  1086. #[test]
  1087. fn compute_dispatch_settings() {
  1088. // 5 user SGPRs, group id x and y, thread ids in v0-v1, 1 KiB LDS.
  1089. let cs = ComputeIo {
  1090. rsrc2: 0x1098A,
  1091. threads: [16, 16, 1],
  1092. };
  1093. assert_eq!(cs.user_sgprs(), 5);
  1094. assert_eq!(cs.system_sgprs(), ([Some(5), Some(6), None], None));
  1095. assert_eq!((cs.thread_id_vgprs(), cs.lds_bytes()), (2, 1024));
  1096. // 6 user SGPRs, all three group ids, v0-v2, no LDS.
  1097. let cs = ComputeIo {
  1098. rsrc2: 0x138C,
  1099. threads: [8, 8, 1],
  1100. };
  1101. assert_eq!(cs.system_sgprs(), ([Some(6), Some(7), Some(8)], None));
  1102. assert_eq!((cs.thread_id_vgprs(), cs.lds_bytes()), (3, 0));
  1103. }
  1104. #[test]
  1105. fn initialized_sgprs_covers_user_system_and_scratch() {
  1106. // 5 user SGPRs, group ids x and y (s5, s6), no scratch: s0..=s6.
  1107. let cs = ComputeIo {
  1108. rsrc2: 0x1098A,
  1109. threads: [16, 16, 1],
  1110. };
  1111. assert_eq!(cs.initialized_sgprs(), 7);
  1112. // All three group ids after 6 user SGPRs, plus the info SGPR: s0..=s9.
  1113. let cs = ComputeIo {
  1114. rsrc2: 0x78C,
  1115. threads: [8, 8, 1],
  1116. };
  1117. assert_eq!(cs.initialized_sgprs(), 10);
  1118. // The same with scratch enabled adds the wave offset: s0..=s10.
  1119. let cs = ComputeIo {
  1120. rsrc2: 0x78D,
  1121. threads: [8, 8, 1],
  1122. };
  1123. assert_eq!(cs.initialized_sgprs(), 11);
  1124. }
  1125. #[test]
  1126. fn reads_every_native_blob() {
  1127. let es = xbch(&fssm(&[(HwStage::Es, &VS_CODE)]));
  1128. let vs = xbch(&fssm(&[(HwStage::Vs, &VS_CODE)]));
  1129. let data = part(&[(0x12, &[0; 16]), (KIND_NATIVE, &es), (KIND_NATIVE, &vs)]);
  1130. let stages: Vec<_> = native_programs(&data)
  1131. .unwrap()
  1132. .iter()
  1133. .map(|p| p.stage)
  1134. .collect();
  1135. assert_eq!(stages, [HwStage::Es, HwStage::Vs]);
  1136. }
  1137. #[test]
  1138. fn pc_layout_has_none() {
  1139. assert!(native_programs(&[0u8; 64]).unwrap().is_empty());
  1140. assert!(
  1141. native_programs(&part(&[(0x0a, b"xbop")]))
  1142. .unwrap()
  1143. .is_empty()
  1144. );
  1145. }
  1146. #[test]
  1147. fn rejects_corrupt_blobs() {
  1148. let good = xbch(&fssm(&[(HwStage::Ls, &VS_CODE)]));
  1149. let corrupt = |at: usize, byte: u8| {
  1150. let mut blob = good.clone();
  1151. blob[at] = byte;
  1152. native_programs(&part(&[(KIND_NATIVE, &blob)]))
  1153. };
  1154. assert!(corrupt(4, 9).is_err(), "unknown version");
  1155. assert!(corrupt(16, 0xFF).is_err(), "stated size");
  1156. assert!(corrupt(XBCH_HEADER + 2, 0xFF).is_err(), "zlib stream");
  1157. assert!(native_programs(&part(&[(KIND_NATIVE, &good[..20])])).is_err());
  1158. let mut bad_record = fssm(&[(HwStage::Ls, &VS_CODE)]);
  1159. let at = FSSM_HEADER + slot(HwStage::Ls);
  1160. bad_record[at..at + 8].copy_from_slice(&u64::MAX.to_le_bytes());
  1161. assert!(native_programs(&part(&[(KIND_NATIVE, &xbch(&bad_record))])).is_err());
  1162. }
  1163. #[test]
  1164. fn rejects_truncated_oversized_and_bad_checksum_xbch_streams() {
  1165. let plain = fssm(&[(HwStage::Vs, &VS_CODE)]);
  1166. let good = xbch(&plain);
  1167. assert_eq!(unpack(&good).unwrap(), plain);
  1168. // Truncated zlib stream (drop last byte, update packed length).
  1169. let mut truncated = good[..good.len() - 1].to_vec();
  1170. let new_packed = (truncated.len() - XBCH_HEADER) as u64;
  1171. truncated[8..16].copy_from_slice(&new_packed.to_le_bytes());
  1172. assert!(unpack(&truncated).is_err());
  1173. // Stated unpacked size smaller than the inflated output.
  1174. let mut oversized = good.clone();
  1175. oversized[16..24].copy_from_slice(&((plain.len() - 1) as u64).to_le_bytes());
  1176. assert!(unpack(&oversized).is_err());
  1177. // Stated unpacked size larger than the inflated output.
  1178. let mut underfilled = good.clone();
  1179. underfilled[16..24].copy_from_slice(&((plain.len() + 1) as u64).to_le_bytes());
  1180. assert!(unpack(&underfilled).is_err());
  1181. // Corrupt Adler-32 trailer.
  1182. let mut bad_adler = good.clone();
  1183. *bad_adler.last_mut().unwrap() ^= 1;
  1184. assert!(unpack(&bad_adler).is_err());
  1185. }
  1186. }