root.rs 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324
  1. //! Root signatures.
  2. //!
  3. //! Serializing goes to the host's `D3D12SerializeRootSignature` (or its
  4. //! versioned form): the description is laid out as on PC, and the blob it
  5. //! returns works as the console's, whose two methods sit in the same slots.
  6. //! The console's own flags (bit 24 and up) are dropped first.
  7. #![allow(clippy::not_unsafe_ptr_arg_deref)]
  8. use std::ffi::{CStr, c_void};
  9. use std::sync::OnceLock;
  10. use crate::object::{
  11. self, E_INVALIDARG, E_NOTIMPL, HRESULT, Iid, Object, ROOT_SIGNATURE, Table, This, guid,
  12. };
  13. use crate::resource::PAGEABLE_IIDS;
  14. const ROOT_SIGNATURE_IIDS: [Iid; 3] = [
  15. guid(
  16. 0xc54a6b66,
  17. 0x72df,
  18. 0x4ee8,
  19. [0x8b, 0xe5, 0xa9, 0x46, 0xa1, 0x42, 0x92, 0x14],
  20. ),
  21. PAGEABLE_IIDS[1],
  22. PAGEABLE_IIDS[2],
  23. ];
  24. const CONSOLE_FLAGS: u32 = 0xff00_0000;
  25. #[repr(C)]
  26. #[derive(Clone, Copy)]
  27. pub struct Desc {
  28. parameter_count: u32,
  29. parameters: *const c_void,
  30. sampler_count: u32,
  31. samplers: *const c_void,
  32. flags: u32,
  33. }
  34. /// Every version's description starts with the fields of [`Desc`].
  35. #[repr(C)]
  36. #[derive(Clone, Copy)]
  37. pub struct VersionedDesc {
  38. version: u32,
  39. desc: Desc,
  40. }
  41. type Serialize =
  42. unsafe extern "system" fn(*const Desc, u32, *mut *mut c_void, *mut *mut c_void) -> HRESULT;
  43. type SerializeVersioned =
  44. unsafe extern "system" fn(*const VersionedDesc, *mut *mut c_void, *mut *mut c_void) -> HRESULT;
  45. /// An export of the host's `d3d12.dll` in System32, looked up once.
  46. fn host_export(cache: &OnceLock<Option<usize>>, name: &CStr) -> Option<usize> {
  47. *cache.get_or_init(|| {
  48. #[cfg(windows)]
  49. {
  50. use windows_sys::Win32::System::LibraryLoader::{
  51. GetProcAddress, LOAD_LIBRARY_SEARCH_SYSTEM32, LoadLibraryExW,
  52. };
  53. let dll: Vec<u16> = "d3d12.dll".encode_utf16().chain([0]).collect();
  54. // SAFETY: a NUL-terminated name; System32 only.
  55. let module = unsafe {
  56. LoadLibraryExW(
  57. dll.as_ptr(),
  58. std::ptr::null_mut(),
  59. LOAD_LIBRARY_SEARCH_SYSTEM32,
  60. )
  61. };
  62. if module.is_null() {
  63. return None;
  64. }
  65. // SAFETY: a loaded module and a NUL-terminated name.
  66. unsafe { GetProcAddress(module, name.as_ptr().cast()) }.map(|f| f as usize)
  67. }
  68. #[cfg(not(windows))]
  69. None
  70. })
  71. }
  72. fn without_console_flags(desc: Desc) -> Desc {
  73. if desc.flags & CONSOLE_FLAGS != 0 {
  74. tracing::debug!(
  75. flags = format_args!("{:#x}", desc.flags),
  76. "console root signature flags dropped"
  77. );
  78. }
  79. Desc {
  80. flags: desc.flags & !CONSOLE_FLAGS,
  81. ..desc
  82. }
  83. }
  84. /// `d3d12_xs!D3D12SerializeRootSignature`.
  85. pub extern "system" fn serialize(
  86. desc: *const Desc,
  87. version: u32,
  88. blob: *mut *mut c_void,
  89. error: *mut *mut c_void,
  90. ) -> HRESULT {
  91. // SAFETY: the title passes a description (null is tolerated).
  92. let Some(&desc) = (unsafe { desc.as_ref() }) else {
  93. return E_INVALIDARG;
  94. };
  95. static FUNCTION: OnceLock<Option<usize>> = OnceLock::new();
  96. let Some(address) = host_export(&FUNCTION, c"D3D12SerializeRootSignature") else {
  97. tracing::warn!("no host d3d12.dll to serialize root signatures");
  98. return E_NOTIMPL;
  99. };
  100. // SAFETY: the export has this signature; it takes what the title passed.
  101. unsafe {
  102. std::mem::transmute::<usize, Serialize>(address)(
  103. &without_console_flags(desc),
  104. version,
  105. blob,
  106. error,
  107. )
  108. }
  109. }
  110. /// `d3d12_xs!D3D12SerializeVersionedRootSignature`.
  111. pub extern "system" fn serialize_versioned(
  112. desc: *const VersionedDesc,
  113. blob: *mut *mut c_void,
  114. error: *mut *mut c_void,
  115. ) -> HRESULT {
  116. // SAFETY: the title passes a description (null is tolerated).
  117. let Some(&desc) = (unsafe { desc.as_ref() }) else {
  118. return E_INVALIDARG;
  119. };
  120. static FUNCTION: OnceLock<Option<usize>> = OnceLock::new();
  121. let Some(address) = host_export(&FUNCTION, c"D3D12SerializeVersionedRootSignature") else {
  122. tracing::warn!("no host d3d12.dll to serialize root signatures");
  123. return E_NOTIMPL;
  124. };
  125. let desc = VersionedDesc {
  126. desc: without_console_flags(desc.desc),
  127. ..desc
  128. };
  129. // SAFETY: the export has this signature; it takes what the title passed.
  130. unsafe { std::mem::transmute::<usize, SerializeVersioned>(address)(&desc, blob, error) }
  131. }
  132. type Deserialize =
  133. unsafe extern "system" fn(*const u8, usize, *const Iid, *mut *mut c_void) -> HRESULT;
  134. /// `d3d12_xs!D3D12CreateRootSignatureDeserializer`: our blobs are the
  135. /// host's serialization, so the host's deserializer reads them, and its
  136. /// object (IUnknown, then the description getter) is laid out as the
  137. /// console's. Grand Theft Auto VI's upscaler asks with the PC interface id.
  138. pub extern "system" fn create_deserializer(
  139. blob: *const u8,
  140. size: usize,
  141. iid: *const Iid,
  142. out: *mut *mut c_void,
  143. ) -> HRESULT {
  144. if blob.is_null() || out.is_null() {
  145. return E_INVALIDARG;
  146. }
  147. static FUNCTION: OnceLock<Option<usize>> = OnceLock::new();
  148. let Some(address) = host_export(&FUNCTION, c"D3D12CreateRootSignatureDeserializer") else {
  149. tracing::warn!("no host d3d12.dll to deserialize root signatures");
  150. return E_NOTIMPL;
  151. };
  152. // SAFETY: the export has this signature; it takes what the title passed.
  153. unsafe { std::mem::transmute::<usize, Deserialize>(address)(blob, size, iid, out) }
  154. }
  155. #[repr(C)]
  156. struct RootSignature {
  157. object: Object,
  158. /// The serialized form, kept for translating pipelines later.
  159. blob: Vec<u8>,
  160. }
  161. /// Device method.
  162. pub(crate) extern "system" fn create(
  163. _: This,
  164. _nodes: u32,
  165. blob: *const u8,
  166. size: usize,
  167. iid: *const Iid,
  168. out: *mut This,
  169. ) -> HRESULT {
  170. if blob.is_null() || size == 0 {
  171. return E_INVALIDARG;
  172. }
  173. // SAFETY: the title passes `size` bytes.
  174. let blob = unsafe { std::slice::from_raw_parts(blob, size) }.to_vec();
  175. tracing::debug!(size, "root signature");
  176. let root = Box::new(RootSignature {
  177. object: Object::new(&FUNCTIONS),
  178. blob,
  179. });
  180. object::hand_out(ROOT_SIGNATURE, root, iid, &ROOT_SIGNATURE_IIDS, out)
  181. }
  182. extern "system" fn query(this: This, iid: *const Iid, out: *mut This) -> HRESULT {
  183. let found = object::is(iid, &ROOT_SIGNATURE_IIDS).then_some(this);
  184. object::answer(ROOT_SIGNATURE, iid, found, out)
  185. }
  186. extern "system" fn release(this: This) -> u32 {
  187. object::release_boxed::<RootSignature>(this)
  188. }
  189. /// IUnknown 3, object 4, device child 1.
  190. static FUNCTIONS: Table<24> = {
  191. let mut f = object::d3d12_object(object::missing_table::<ROOT_SIGNATURE, 24>());
  192. f[0] = query as *const ();
  193. f[2] = release as *const ();
  194. f[7] = object::parent_device as *const (); // 0x38
  195. Table(f)
  196. };
  197. #[cfg(test)]
  198. mod tests {
  199. use super::*;
  200. use crate::object::{S_OK, slot};
  201. /// One 32-bit constant at b0, serialized by the host, then created.
  202. #[cfg(windows)]
  203. #[test]
  204. fn host_serialized_blobs_create_root_signatures() {
  205. #[repr(C)]
  206. struct Constants {
  207. kind: u32,
  208. register: u32,
  209. space: u32,
  210. count: u32,
  211. visibility: u32,
  212. }
  213. let parameter = Constants {
  214. kind: 1,
  215. register: 0,
  216. space: 0,
  217. count: 1,
  218. visibility: 0,
  219. };
  220. let desc = Desc {
  221. parameter_count: 1,
  222. parameters: (&raw const parameter).cast(),
  223. sampler_count: 0,
  224. samplers: std::ptr::null(),
  225. flags: 0x0100_0001,
  226. };
  227. let (mut blob, mut error) = (std::ptr::null_mut(), std::ptr::null_mut());
  228. assert_eq!(serialize(&desc, 1, &mut blob, &mut error), S_OK);
  229. let blob = blob.cast_const().cast::<Object>();
  230. let data = slot::<extern "system" fn(This) -> *const u8>(blob, 0x18)(blob);
  231. let size = slot::<extern "system" fn(This) -> usize>(blob, 0x20)(blob);
  232. assert!(size > 0);
  233. let null = std::ptr::null();
  234. let mut root = null;
  235. assert_eq!(
  236. create(null, 0, data, size, &ROOT_SIGNATURE_IIDS[0], &mut root),
  237. S_OK
  238. );
  239. assert_eq!(slot::<extern "system" fn(This) -> u32>(root, 0x10)(root), 0);
  240. slot::<extern "system" fn(This) -> u32>(blob, 0x10)(blob);
  241. }
  242. /// The host's deserializer reads our blobs back (the upscaler's call).
  243. #[cfg(windows)]
  244. #[test]
  245. fn our_blobs_deserialize_on_the_host() {
  246. use windows::Win32::Graphics::Direct3D12::ID3D12RootSignatureDeserializer;
  247. use windows::core::Interface;
  248. let desc = VersionedDesc {
  249. version: 1,
  250. desc: Desc {
  251. parameter_count: 0,
  252. parameters: std::ptr::null(),
  253. sampler_count: 0,
  254. samplers: std::ptr::null(),
  255. flags: 1,
  256. },
  257. };
  258. let (mut blob, mut error) = (std::ptr::null_mut(), std::ptr::null_mut());
  259. assert_eq!(serialize_versioned(&desc, &mut blob, &mut error), S_OK);
  260. let blob = blob.cast_const().cast::<Object>();
  261. let data = slot::<extern "system" fn(This) -> *const u8>(blob, 0x18)(blob);
  262. let size = slot::<extern "system" fn(This) -> usize>(blob, 0x20)(blob);
  263. let iid: Iid = ID3D12RootSignatureDeserializer::IID.to_u128().to_be_bytes();
  264. let iid = guid(
  265. u32::from_be_bytes(iid[0..4].try_into().unwrap()),
  266. u16::from_be_bytes(iid[4..6].try_into().unwrap()),
  267. u16::from_be_bytes(iid[6..8].try_into().unwrap()),
  268. iid[8..16].try_into().unwrap(),
  269. );
  270. let mut out = std::ptr::null_mut();
  271. assert_eq!(create_deserializer(data, size, &iid, &mut out), S_OK);
  272. // SAFETY: the host handed out this interface.
  273. let deserializer = unsafe { ID3D12RootSignatureDeserializer::from_raw(out) };
  274. // SAFETY: valid while the deserializer lives.
  275. let read = unsafe { &*deserializer.GetRootSignatureDesc() };
  276. assert_eq!((read.NumParameters, read.Flags.0), (0, 1));
  277. slot::<extern "system" fn(This) -> u32>(blob, 0x10)(blob);
  278. }
  279. /// Version 1.0 through the versioned entry point, with a console flag.
  280. #[cfg(windows)]
  281. #[test]
  282. fn versioned_descriptions_serialize_on_the_host() {
  283. let desc = VersionedDesc {
  284. version: 1,
  285. desc: Desc {
  286. parameter_count: 0,
  287. parameters: std::ptr::null(),
  288. sampler_count: 0,
  289. samplers: std::ptr::null(),
  290. flags: 0x0200_0001,
  291. },
  292. };
  293. let (mut blob, mut error) = (std::ptr::null_mut(), std::ptr::null_mut());
  294. assert_eq!(serialize_versioned(&desc, &mut blob, &mut error), S_OK);
  295. let blob = blob.cast_const().cast::<Object>();
  296. assert!(slot::<extern "system" fn(This) -> usize>(blob, 0x20)(blob) > 0);
  297. slot::<extern "system" fn(This) -> u32>(blob, 0x10)(blob);
  298. assert_eq!(
  299. serialize_versioned(std::ptr::null(), &mut blob.cast_mut().cast(), &mut error),
  300. E_INVALIDARG
  301. );
  302. }
  303. }