descriptor.rs 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790
  1. //! Descriptor heaps: zeroed memory, with handles that are plain addresses
  2. //! (CPU and GPU alike, as on the console).
  3. //!
  4. //! Descriptor sizes: views 32 bytes and samplers 16, the size of RDNA 2's
  5. //! image and sampler descriptors, so a title that copies descriptors itself
  6. //! moves whole ones. Render target and depth views are ours alone; 128 bytes
  7. //! leaves room for whatever stride a title assumes.
  8. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  9. use crate::object::{self, DESCRIPTOR_HEAP, E_INVALIDARG, HRESULT, Iid, Object, Table, This, guid};
  10. use crate::resource::{Memory, PAGEABLE_IIDS};
  11. #[cfg(windows)]
  12. pub(crate) mod host;
  13. const HEAP_IIDS: [Iid; 4] = [
  14. guid(
  15. 0x8efb471d,
  16. 0x616c,
  17. 0x4f49,
  18. [0x90, 0xf7, 0x12, 0x7b, 0xb7, 0x63, 0xfa, 0x51],
  19. ),
  20. PAGEABLE_IIDS[0],
  21. PAGEABLE_IIDS[1],
  22. PAGEABLE_IIDS[2],
  23. ];
  24. #[repr(C)]
  25. #[derive(Debug, Clone, Copy)]
  26. pub(crate) struct HeapDesc {
  27. kind: u32,
  28. count: u32,
  29. flags: u32,
  30. nodes: u32,
  31. }
  32. /// Newer titles (Grand Theft Auto VI) pass the description followed by
  33. /// memory of their own for the descriptors: an address and its size in
  34. /// bytes, or a null address to have the heap allocate (inferred from the
  35. /// title's call sites; older titles pass the plain description).
  36. #[repr(C)]
  37. #[derive(Debug, Clone, Copy)]
  38. struct Placement {
  39. address: u64,
  40. size: u64,
  41. }
  42. #[repr(C)]
  43. pub(crate) struct Heap {
  44. object: Object,
  45. desc: HeapDesc,
  46. /// The first descriptor: in `memory`, or in the title's own memory.
  47. pub(crate) start: u64,
  48. memory: Option<Memory>,
  49. /// Shader-visible view and sampler heaps get a host heap with the same
  50. /// descriptor order when a draw first uses them (decision 0007, step
  51. /// 3); slots written before wait in `pending`.
  52. #[cfg(windows)]
  53. host: std::sync::OnceLock<Option<host::HostHeap>>,
  54. #[cfg(windows)]
  55. pending: std::sync::Mutex<Vec<u32>>,
  56. }
  57. pub(crate) fn heap<'a>(this: This) -> &'a Heap {
  58. // SAFETY: called from descriptor heap methods only.
  59. unsafe { &*this.cast::<Heap>() }
  60. }
  61. impl Heap {
  62. /// Whether this is a sampler heap.
  63. pub(crate) fn samplers(&self) -> bool {
  64. self.desc.kind == SAMPLERS
  65. }
  66. /// The host heap, made on first use from what the title wrote so far.
  67. /// Made late because a host view heap the size of Grand Theft Auto VI's
  68. /// costs over 100 MB of commit, which its boot needs for its page pool.
  69. #[cfg(windows)]
  70. pub(crate) fn host(&self) -> Option<&host::HostHeap> {
  71. if let Some(h) = self.host.get() {
  72. return h.as_ref();
  73. }
  74. if self.desc.flags & SHADER_VISIBLE == 0 || !matches!(self.desc.kind, VIEWS_KIND | SAMPLERS)
  75. {
  76. return None;
  77. }
  78. let mut pending = self.pending.lock().unwrap_or_else(|e| e.into_inner());
  79. let h = self
  80. .host
  81. .get_or_init(|| host::HostHeap::new(self.samplers(), self.desc.count))
  82. .as_ref()?;
  83. let step = u64::from(increment(self.desc.kind)?);
  84. for i in pending.drain(..) {
  85. h.mirror(i, self.start + u64::from(i) * step, false);
  86. }
  87. Some(h)
  88. }
  89. /// The descriptor index of `handle` in this heap, if it lies in it.
  90. pub(crate) fn index(&self, handle: u64) -> Option<u32> {
  91. let step = u64::from(increment(self.desc.kind)?);
  92. let at = handle.checked_sub(self.start)?;
  93. let index = at / step;
  94. (index < u64::from(self.desc.count)).then_some(index as u32)
  95. }
  96. }
  97. const VIEWS_KIND: u32 = 0;
  98. const SAMPLERS: u32 = 1;
  99. const SHADER_VISIBLE: u32 = 1;
  100. /// Shader-visible heaps by address range, for mirroring descriptor writes:
  101. /// start, end, heap.
  102. #[cfg(windows)]
  103. static SHADER_HEAPS: std::sync::Mutex<Vec<(u64, u64, usize)>> = std::sync::Mutex::new(Vec::new());
  104. /// The shader-visible heap holding `handle`, and the descriptor's index.
  105. #[cfg(windows)]
  106. fn shader_slot<'a>(handle: u64) -> Option<(&'a Heap, u32)> {
  107. let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
  108. let &(_, _, at) = heaps
  109. .iter()
  110. .find(|&&(start, end, _)| (start..end).contains(&handle))?;
  111. // SAFETY: registered heaps are live (removed when dropped).
  112. let heap = unsafe { &*(at as *const Heap) };
  113. Some((heap, heap.index(handle)?))
  114. }
  115. /// Makes the host descriptor for what the title wrote at `handle`, if it
  116. /// is in a shader-visible heap.
  117. #[cfg(windows)]
  118. fn mirror(handle: u64) {
  119. let Some((heap, index)) = shader_slot(handle) else {
  120. return;
  121. };
  122. let mut pending = heap.pending.lock().unwrap_or_else(|e| e.into_inner());
  123. match heap.host.get() {
  124. None => pending.push(index),
  125. Some(host) => {
  126. drop(pending);
  127. if let Some(host) = host {
  128. host.mirror(index, handle, false);
  129. }
  130. }
  131. }
  132. }
  133. /// Gives back dynamic slots of the host heap behind the title heap at
  134. /// `heap`, if that heap still exists.
  135. #[cfg(windows)]
  136. pub(crate) fn release_dynamic(heap: usize, first: u32, n: u32) {
  137. let heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
  138. if heaps.iter().any(|&(_, _, h)| h == heap)
  139. // SAFETY: registered heaps are live (removed when dropped).
  140. && let Some(Some(host)) = unsafe { &*(heap as *const Heap) }.host.get()
  141. {
  142. host.release(first, n);
  143. }
  144. }
  145. #[cfg(windows)]
  146. impl Drop for Heap {
  147. fn drop(&mut self) {
  148. let at = std::ptr::from_ref::<Heap>(self) as usize;
  149. let mut heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
  150. heaps.retain(|&(_, _, h)| h != at);
  151. }
  152. }
  153. /// Bytes per descriptor, by heap type (views, samplers, render targets,
  154. /// depth).
  155. fn increment(kind: u32) -> Option<u32> {
  156. [32, 16, 128, 128].get(kind as usize).copied()
  157. }
  158. /// Device method.
  159. pub(crate) extern "system" fn increment_size(_: This, kind: u32) -> u32 {
  160. increment(kind).unwrap_or(0)
  161. }
  162. /// What our render target views hold: the resource and the view
  163. /// description, turned into a host view when a command uses them.
  164. #[repr(C)]
  165. #[derive(Clone, Copy)]
  166. pub(crate) struct RtvRecord {
  167. tag: u32,
  168. described: u32,
  169. pub(crate) resource: This,
  170. desc: [u32; 6],
  171. }
  172. const RTV_TAG: u32 = u32::from_le_bytes(*b"vRTV");
  173. const _: () = assert!(size_of::<RtvRecord>() <= 112);
  174. impl RtvRecord {
  175. /// The view description in the host's type (the same layout).
  176. #[cfg(windows)]
  177. pub(crate) fn desc(
  178. &self,
  179. ) -> Option<windows::Win32::Graphics::Direct3D12::D3D12_RENDER_TARGET_VIEW_DESC> {
  180. const TEXTURE_2D: u32 = 4;
  181. self.host_desc(TEXTURE_2D)
  182. }
  183. /// The depth view description in the host's type (the same layout).
  184. #[cfg(windows)]
  185. pub(crate) fn depth_desc(
  186. &self,
  187. ) -> Option<windows::Win32::Graphics::Direct3D12::D3D12_DEPTH_STENCIL_VIEW_DESC> {
  188. const TEXTURE_2D: u32 = 3;
  189. self.host_desc(TEXTURE_2D)
  190. }
  191. /// The description words as a host type, the format as the host has it.
  192. /// Without one, a typeless host copy gets a 2D view (`dimension`) in
  193. /// the title's format, which the host needs spelled out.
  194. #[cfg(windows)]
  195. fn host_desc<T>(&self, dimension: u32) -> Option<T> {
  196. assert!(size_of::<T>() <= size_of::<[u32; 6]>());
  197. let mut words = if self.described != 0 {
  198. self.desc
  199. } else {
  200. [
  201. crate::resource::view_format(self.resource)?,
  202. dimension,
  203. 0,
  204. 0,
  205. 0,
  206. 0,
  207. ]
  208. };
  209. words[0] = crate::resource::pc_format(words[0]);
  210. // SAFETY: both host view descriptions are 24 bytes in this layout.
  211. Some(unsafe { (&raw const words).cast::<T>().read_unaligned() })
  212. }
  213. }
  214. /// Device method: records the view at `handle` (descriptor memory).
  215. pub(crate) extern "system" fn create_rtv(
  216. _: This,
  217. resource: This,
  218. desc: *const [u32; 6],
  219. handle: u64,
  220. ) {
  221. if handle == 0 {
  222. return;
  223. }
  224. // SAFETY: the title passes a description or null.
  225. let described = unsafe { desc.as_ref() };
  226. let record = RtvRecord {
  227. tag: RTV_TAG,
  228. described: u32::from(described.is_some()),
  229. resource,
  230. desc: described.copied().unwrap_or_default(),
  231. };
  232. // SAFETY: the handle is a descriptor slot, at least 112 bytes.
  233. unsafe { (handle as *mut RtvRecord).write_unaligned(record) };
  234. }
  235. /// Device method: a depth view, recorded as render target views are.
  236. pub(crate) extern "system" fn create_dsv(
  237. this: This,
  238. resource: This,
  239. desc: *const [u32; 6],
  240. handle: u64,
  241. ) {
  242. create_rtv(this, resource, desc, handle);
  243. if handle != 0 {
  244. // SAFETY: just written by `create_rtv`.
  245. unsafe { (handle as *mut u32).write_unaligned(DSV_TAG) };
  246. }
  247. }
  248. const DSV_TAG: u32 = u32::from_le_bytes(*b"vDSV");
  249. /// A shader view or sampler as the title described it (descriptions in the
  250. /// host's layout, kept as words), for the host to build its own from.
  251. #[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord)]
  252. pub(crate) enum View {
  253. /// Constant buffer: GPU address and size.
  254. Constant(u64, u32),
  255. /// Shader resource: resource, description (none: the resource's own).
  256. Shader(usize, Option<[u32; 10]>),
  257. /// Unordered access: resource, counter resource, description.
  258. Unordered(usize, usize, Option<[u32; 10]>),
  259. Sampler([u32; 13]),
  260. /// The console's own sampler description: flags, filters per axis,
  261. /// addressing, LOD and anisotropy settings, border color, then
  262. /// console-only tuning words.
  263. ConsoleSampler([u32; 27]),
  264. /// A view of memory without a resource object: whether it is unordered
  265. /// access, the resource description, then the view's (the plain one
  266. /// followed by the memory address and console fields).
  267. Placed(bool, [u32; 14], [u32; 16]),
  268. }
  269. impl View {
  270. /// Whether the view reads buffer memory (constant buffers, buffer views
  271. /// of resources or of memory) or memory the title placed a texture in:
  272. /// such views get host slots only for draws.
  273. #[cfg(windows)]
  274. fn is_buffer(&self) -> bool {
  275. match self {
  276. View::Constant(..) | View::Placed(..) => true,
  277. View::Shader(r, _) | View::Unordered(r, _, _) => {
  278. crate::resource::buffer_bytes(*r as This).is_some()
  279. }
  280. View::Sampler(_) | View::ConsoleSampler(_) => false,
  281. }
  282. }
  283. }
  284. /// Every distinct view in use; a descriptor holds a tag, an index into it
  285. /// and the entry's generation, which survive titles copying descriptors as
  286. /// bytes. A view of a resource lives as long as the resource: when the
  287. /// title releases it, its entries are freed for reuse under a new
  288. /// generation, so descriptors (and host slots made from them) naming the
  289. /// old one go stale instead of naming whatever is made at the same address
  290. /// next.
  291. /// shortcut: views without a resource object (constant buffers, memory
  292. /// views, samplers) are kept for the run; they are bounded by the title's
  293. /// memory and sampler states.
  294. struct Views {
  295. /// Each entry's view and generation.
  296. list: Vec<(View, u32)>,
  297. index: std::collections::BTreeMap<View, u32>,
  298. /// Entries naming each resource.
  299. by_resource: std::collections::BTreeMap<usize, Vec<u32>>,
  300. free: Vec<u32>,
  301. }
  302. static VIEWS: std::sync::Mutex<Views> = std::sync::Mutex::new(Views {
  303. list: Vec::new(),
  304. index: std::collections::BTreeMap::new(),
  305. by_resource: std::collections::BTreeMap::new(),
  306. free: Vec::new(),
  307. });
  308. const VIEW_TAG: u32 = u32::from_le_bytes(*b"vVIE");
  309. impl View {
  310. /// The resource objects the view names.
  311. fn resources(&self) -> [usize; 2] {
  312. match *self {
  313. View::Shader(r, _) => [r, 0],
  314. View::Unordered(r, counter, _) => [r, counter],
  315. _ => [0, 0],
  316. }
  317. }
  318. }
  319. fn record(handle: u64, view: View) {
  320. if handle == 0 {
  321. return;
  322. }
  323. let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
  324. let i = match views.index.get(&view) {
  325. Some(&i) => i,
  326. None => {
  327. let i = match views.free.pop() {
  328. Some(i) => {
  329. views.list[i as usize].0 = view.clone();
  330. i
  331. }
  332. None => {
  333. views.list.push((view.clone(), 1));
  334. views.list.len() as u32 - 1
  335. }
  336. };
  337. for r in view.resources().into_iter().filter(|&r| r != 0) {
  338. views.by_resource.entry(r).or_default().push(i);
  339. }
  340. views.index.insert(view, i);
  341. i
  342. }
  343. };
  344. let generation = views.list[i as usize].1;
  345. // SAFETY: the handle is a descriptor slot, at least 16 bytes.
  346. unsafe { (handle as *mut [u32; 3]).write_unaligned([VIEW_TAG, i, generation]) };
  347. drop(views);
  348. #[cfg(windows)]
  349. mirror(handle);
  350. }
  351. /// The title released `resource`: the views naming it go stale.
  352. pub(crate) fn forget(resource: usize) {
  353. let mut views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
  354. let Some(entries) = views.by_resource.remove(&resource) else {
  355. return;
  356. };
  357. for i in entries {
  358. let (view, generation) = views.list[i as usize].clone();
  359. // Entries freed through a view's other resource may hold another
  360. // view by now.
  361. if views.index.get(&view) != Some(&i) || !view.resources().contains(&resource) {
  362. continue;
  363. }
  364. views.index.remove(&view);
  365. views.list[i as usize].1 = generation.wrapping_add(1).max(1);
  366. // The view's other resource (a counter) keeps a stale entry, which
  367. // `forget` of that resource skips.
  368. views.free.push(i);
  369. }
  370. }
  371. /// The view of entry `i` if `generation` is still its own.
  372. #[cfg(windows)]
  373. fn view_at(i: u32, generation: u32) -> Option<View> {
  374. let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
  375. let (view, current) = views.list.get(i as usize)?;
  376. (*current == generation).then(|| view.clone())
  377. }
  378. /// The view recorded at `handle`, if one is (and its resource is alive).
  379. pub(crate) fn view(handle: u64) -> Option<View> {
  380. if handle == 0 {
  381. return None;
  382. }
  383. // SAFETY: the handle is a descriptor slot the title passes back.
  384. let [tag, i, generation] = unsafe { (handle as *const [u32; 3]).read_unaligned() };
  385. let views = VIEWS.lock().unwrap_or_else(|e| e.into_inner());
  386. let (view, current) = views.list.get(i as usize)?;
  387. (tag == VIEW_TAG && *current == generation).then(|| view.clone())
  388. }
  389. /// A description of `N` words, if the title passes one.
  390. fn words<const N: usize>(desc: *const [u32; N]) -> Option<[u32; N]> {
  391. // SAFETY: the title passes a description or null.
  392. (!desc.is_null()).then(|| unsafe { desc.read_unaligned() })
  393. }
  394. /// Device method.
  395. pub(crate) extern "system" fn create_cbv(_: This, desc: *const [u32; 4], handle: u64) {
  396. if let Some([lo, hi, size, _]) = words(desc) {
  397. let address = u64::from(lo) | u64::from(hi) << 32;
  398. record(handle, View::Constant(address, size));
  399. }
  400. }
  401. /// Device method.
  402. pub(crate) extern "system" fn create_srv(
  403. _: This,
  404. resource: This,
  405. desc: *const [u32; 10],
  406. handle: u64,
  407. ) {
  408. record(handle, View::Shader(resource as usize, words(desc)));
  409. }
  410. /// Device method.
  411. pub(crate) extern "system" fn create_uav(
  412. _: This,
  413. resource: This,
  414. counter: This,
  415. desc: *const [u32; 10],
  416. handle: u64,
  417. ) {
  418. let view = View::Unordered(resource as usize, counter as usize, words(desc));
  419. record(handle, view);
  420. }
  421. /// Device methods 0x230 and 0x238: shader resource and unordered access
  422. /// views of memory the title placed itself, `(resource desc, view desc,
  423. /// handle)`.
  424. pub(crate) extern "system" fn create_placed_srv(
  425. _: This,
  426. resource: *const [u32; 14],
  427. desc: *const [u32; 16],
  428. handle: u64,
  429. ) {
  430. if let (Some(resource), Some(desc)) = (words(resource), words(desc)) {
  431. record(handle, View::Placed(false, resource, desc));
  432. }
  433. }
  434. pub(crate) extern "system" fn create_placed_uav(
  435. _: This,
  436. resource: *const [u32; 14],
  437. desc: *const [u32; 16],
  438. handle: u64,
  439. ) {
  440. if let (Some(resource), Some(desc)) = (words(resource), words(desc)) {
  441. record(handle, View::Placed(true, resource, desc));
  442. }
  443. }
  444. /// Device method.
  445. pub(crate) extern "system" fn create_sampler(_: This, desc: *const [u32; 13], handle: u64) {
  446. if let Some(desc) = words(desc) {
  447. record(handle, View::Sampler(desc));
  448. }
  449. }
  450. /// Device method 0x1e8.
  451. pub(crate) extern "system" fn create_sampler_x(_: This, desc: *const [u32; 27], handle: u64) {
  452. if let Some(desc) = words(desc) {
  453. record(handle, View::ConsoleSampler(desc));
  454. }
  455. }
  456. /// Device method: `count` descriptors of `kind` from `src` to `dst`.
  457. pub(crate) extern "system" fn copy_simple(_: This, count: u32, dst: u64, src: u64, kind: u32) {
  458. let step = u64::from(increment(kind).unwrap_or(0));
  459. let len = u64::from(count) * step;
  460. if dst != 0 && src != 0 {
  461. // SAFETY: both ranges are descriptor slots the title owns.
  462. unsafe { std::ptr::copy(src as *const u8, dst as *mut u8, len as usize) };
  463. #[cfg(windows)]
  464. for i in 0..u64::from(count) {
  465. mirror(dst + i * step);
  466. }
  467. }
  468. }
  469. /// Device method: ranges of descriptors (start and count each) gathered
  470. /// from the sources and scattered to the destinations, in order.
  471. #[allow(clippy::too_many_arguments)] // the method's own arguments
  472. pub(crate) extern "system" fn copy(
  473. _: This,
  474. dst_ranges: u32,
  475. dst_starts: *const u64,
  476. dst_sizes: *const u32,
  477. src_ranges: u32,
  478. src_starts: *const u64,
  479. src_sizes: *const u32,
  480. kind: u32,
  481. ) {
  482. let Some(step) = increment(kind) else {
  483. return;
  484. };
  485. // Each range as (start, count); a null size array means one descriptor
  486. // per range.
  487. let ranges = |n: u32, starts: *const u64, sizes: *const u32| -> Vec<(u64, u32)> {
  488. (0..n as usize)
  489. .map(|i| {
  490. // SAFETY: the title passes `n` starts and sizes (or null sizes).
  491. unsafe {
  492. (
  493. *starts.add(i),
  494. if sizes.is_null() { 1 } else { *sizes.add(i) },
  495. )
  496. }
  497. })
  498. .collect()
  499. };
  500. if dst_starts.is_null() || src_starts.is_null() {
  501. return;
  502. }
  503. let src = ranges(src_ranges, src_starts, src_sizes);
  504. let mut dst = ranges(dst_ranges, dst_starts, dst_sizes).into_iter();
  505. let (mut to, mut room) = dst.next().unwrap_or((0, 0));
  506. for (mut from, mut left) in src {
  507. while left > 0 {
  508. while room == 0 {
  509. let Some(next) = dst.next() else { return };
  510. (to, room) = next;
  511. }
  512. let n = left.min(room);
  513. copy_simple(std::ptr::null(), n, to, from, kind);
  514. let bytes = u64::from(n) * u64::from(step);
  515. (to, from, room, left) = (to + bytes, from + bytes, room - n, left - n);
  516. }
  517. }
  518. }
  519. /// The view recorded at `handle`, if one is.
  520. pub(crate) fn rtv_record(handle: u64) -> Option<RtvRecord> {
  521. tagged_record(handle, RTV_TAG)
  522. }
  523. /// The depth view recorded at `handle`, if one is.
  524. pub(crate) fn dsv_record(handle: u64) -> Option<RtvRecord> {
  525. tagged_record(handle, DSV_TAG)
  526. }
  527. fn tagged_record(handle: u64, tag: u32) -> Option<RtvRecord> {
  528. if handle == 0 {
  529. return None;
  530. }
  531. // SAFETY: the handle is a descriptor slot the title passes back.
  532. let record = unsafe { (handle as *const RtvRecord).read_unaligned() };
  533. (record.tag == tag).then_some(record)
  534. }
  535. /// Device method.
  536. pub(crate) extern "system" fn create_heap(
  537. _: This,
  538. desc_ptr: *const HeapDesc,
  539. iid: *const Iid,
  540. out: *mut This,
  541. ) -> HRESULT {
  542. // SAFETY: the title passes a description (null is tolerated).
  543. let Some(&desc) = (unsafe { desc_ptr.as_ref() }) else {
  544. return E_INVALIDARG;
  545. };
  546. let Some(size) = increment(desc.kind).map(|i| u64::from(i) * u64::from(desc.count.max(1)))
  547. else {
  548. return E_INVALIDARG;
  549. };
  550. // SAFETY: read only as a hint: a title that passes the plain
  551. // description has its own stack or data after it.
  552. let placement = unsafe { desc_ptr.add(1).cast::<Placement>().read_unaligned() };
  553. // shortcut: a placement is recognised by its size matching the count,
  554. // since the plain and extended descriptions share the slot and the
  555. // interface version; find the flag that tells them apart if a title
  556. // trips over this.
  557. let placed = placement.address != 0 && placement.size == size;
  558. tracing::debug!(?desc, placed, "descriptor heap");
  559. let (start, memory) = if placed {
  560. (placement.address, None)
  561. } else {
  562. match Memory::zeroed(size, 64) {
  563. Ok(memory) => (memory.address(), Some(memory)),
  564. Err(hr) => return hr,
  565. }
  566. };
  567. let visible = desc.flags & SHADER_VISIBLE != 0 && matches!(desc.kind, VIEWS_KIND | SAMPLERS);
  568. let heap = Box::new(Heap {
  569. object: Object::new(&FUNCTIONS),
  570. desc,
  571. start,
  572. memory,
  573. #[cfg(windows)]
  574. host: std::sync::OnceLock::new(),
  575. #[cfg(windows)]
  576. pending: Default::default(),
  577. });
  578. #[cfg(windows)]
  579. if visible {
  580. let at = std::ptr::from_ref::<Heap>(&heap) as usize;
  581. let mut heaps = SHADER_HEAPS.lock().unwrap_or_else(|e| e.into_inner());
  582. heaps.push((start, start + size, at));
  583. }
  584. #[cfg(not(windows))]
  585. let _ = visible;
  586. object::hand_out(DESCRIPTOR_HEAP, heap, iid, &HEAP_IIDS, out)
  587. }
  588. extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
  589. let found = object::is(iid, &HEAP_IIDS).then_some(this);
  590. object::answer(DESCRIPTOR_HEAP, iid, found, out)
  591. }
  592. extern "system" fn release(this: This) -> u32 {
  593. object::release_boxed::<Heap>(this)
  594. }
  595. extern "system" fn desc(this: This, out: *mut HeapDesc) {
  596. if !out.is_null() {
  597. // SAFETY: checked non-null; the title passes room for a description.
  598. unsafe { out.write(heap(this).desc) };
  599. }
  600. }
  601. /// The same address for the CPU and the GPU start.
  602. extern "system" fn start(this: This) -> u64 {
  603. heap(this).start
  604. }
  605. /// IUnknown 3, object 4, device child 1, heap 3.
  606. static FUNCTIONS: Table<24> = {
  607. let mut f = object::d3d12_object(object::missing_table::<DESCRIPTOR_HEAP, 24>());
  608. f[0] = query as *const ();
  609. f[2] = release as *const ();
  610. f[7] = object::parent_device as *const (); // 0x38
  611. f[8] = desc as *const (); // 0x40
  612. f[9] = start as *const (); // 0x48 CPU
  613. f[10] = start as *const (); // 0x50 GPU
  614. Table(f)
  615. };
  616. #[cfg(test)]
  617. mod tests {
  618. use super::*;
  619. use crate::object::{S_OK, slot};
  620. /// What newer titles pass; tests use it throughout, so that reading the
  621. /// placement stays inside the value.
  622. #[repr(C)]
  623. struct Extended(HeapDesc, Placement);
  624. fn create(desc: HeapDesc, placement: Placement, out: &mut This) -> HRESULT {
  625. let extended = Extended(desc, placement);
  626. create_heap(std::ptr::null(), &extended.0, &HEAP_IIDS[0], out)
  627. }
  628. #[test]
  629. fn heaps_hold_count_descriptors_from_their_start() {
  630. let null = std::ptr::null();
  631. let desc = HeapDesc {
  632. kind: 0,
  633. count: 1000,
  634. flags: 1,
  635. nodes: 0,
  636. };
  637. let none = Placement {
  638. address: 0,
  639. size: 0,
  640. };
  641. let mut h = null;
  642. assert_eq!(create(desc, none, &mut h), S_OK);
  643. let cpu = slot::<extern "system" fn(This) -> u64>(h, 0x48)(h);
  644. assert_eq!(cpu % 64, 0);
  645. assert_eq!(slot::<extern "system" fn(This) -> u64>(h, 0x50)(h), cpu);
  646. assert_eq!(increment_size(null, 0), 32);
  647. // SAFETY: the heap holds 1000 descriptors of 32 bytes.
  648. unsafe { (cpu as *mut u8).add(999 * 32 + 31).write(1) };
  649. assert_eq!(increment_size(null, 9), 0);
  650. let bad = HeapDesc { kind: 9, ..desc };
  651. assert_eq!(create(bad, none, &mut h), E_INVALIDARG);
  652. }
  653. #[test]
  654. fn views_survive_copies() {
  655. let null = std::ptr::null();
  656. let mut heap = vec![0u64; 4 * 8]; // four 32-byte slots
  657. let at = |i: usize| heap.as_ptr() as u64 + 32 * i as u64;
  658. let (s0, s1, s2, s3) = (at(0), at(1), at(2), at(3));
  659. create_cbv(null, &[0x1000, 1, 256, 0], s0);
  660. assert_eq!(view(s0), Some(View::Constant(0x1_0000_1000, 256)));
  661. create_srv(null, null, std::ptr::null(), s1);
  662. assert_eq!(view(s1), Some(View::Shader(0, None)));
  663. // The same view twice is one entry.
  664. create_srv(null, null, std::ptr::null(), s2);
  665. // SAFETY: both slots are in `heap`.
  666. assert_eq!(unsafe { *(s1 as *const [u32; 3]) }, unsafe {
  667. *(s2 as *const [u32; 3])
  668. });
  669. // Two ranges of one into one range of two.
  670. let (dst, dst_n, src, src_n) = ([s2], [2u32], [s0, s1], [1u32, 1]);
  671. copy(
  672. null,
  673. 1,
  674. dst.as_ptr(),
  675. dst_n.as_ptr(),
  676. 2,
  677. src.as_ptr(),
  678. src_n.as_ptr(),
  679. 0,
  680. );
  681. assert_eq!(view(s2), view(s0));
  682. assert_eq!(view(s3), view(s1));
  683. assert_eq!(view(at(0) + 8), None);
  684. heap[0] = 0;
  685. }
  686. /// A released resource's views go stale; the same view of a new
  687. /// resource at the same address is a new record.
  688. #[test]
  689. fn views_die_with_their_resource() {
  690. let null = std::ptr::null();
  691. let slots = [0u64; 2 * 4];
  692. let (a, b) = (slots.as_ptr() as u64, slots.as_ptr() as u64 + 32);
  693. let resource = 0x7777_0000usize as This;
  694. create_srv(null, resource, std::ptr::null(), a);
  695. assert_eq!(view(a), Some(View::Shader(0x7777_0000, None)));
  696. forget(0x7777_0000);
  697. assert_eq!(view(a), None, "stale after release");
  698. create_srv(null, resource, std::ptr::null(), b);
  699. assert_eq!(view(b), Some(View::Shader(0x7777_0000, None)));
  700. // SAFETY: both slots are in `slots`.
  701. let (old, new) = unsafe { (*(a as *const [u32; 3]), *(b as *const [u32; 3])) };
  702. assert_ne!(old, new, "a new generation");
  703. }
  704. /// Grand Theft Auto VI places its shader-visible heap in its own memory
  705. /// and checks that the heap starts there.
  706. #[test]
  707. fn placed_heaps_start_at_the_title_memory() {
  708. let mut memory = vec![0u8; 64 * 32];
  709. let address = memory.as_mut_ptr() as u64;
  710. let desc = HeapDesc {
  711. kind: 0,
  712. count: 64,
  713. flags: 1,
  714. nodes: 1,
  715. };
  716. let mut h = std::ptr::null();
  717. assert_eq!(
  718. create(
  719. desc,
  720. Placement {
  721. address,
  722. size: 64 * 32
  723. },
  724. &mut h
  725. ),
  726. S_OK
  727. );
  728. assert_eq!(slot::<extern "system" fn(This) -> u64>(h, 0x48)(h), address);
  729. assert_eq!(slot::<extern "system" fn(This) -> u64>(h, 0x50)(h), address);
  730. // A size that does not match the count is not a placement.
  731. assert_eq!(create(desc, Placement { address, size: 7 }, &mut h), S_OK);
  732. assert_ne!(slot::<extern "system" fn(This) -> u64>(h, 0x48)(h), address);
  733. }
  734. }