diff --git a/README.md b/README.md index 8e28905bd9..131d8247e0 100644 --- a/README.md +++ b/README.md @@ -62,7 +62,7 @@ work on booting can start as soon as one is available to a developer. | Audio banks (AWC: Opus, XMA2) | ✅ Exported whole. Opus repackaged **losslessly** as Ogg Opus; PCM (codec 0/2) as WAV; XMA2 decoded with ffmpeg. `--wav` adds 16-bit PCM WAV ([notes](docs/audio.md)) | | Music/radio config | ? Measured. **1,589** audio-config records with exact durations and AWC stream ids; station grouping and content-id lists; no per-track start offsets ([notes](docs/audio_config.md)) | | PE loader and import shims | ⚠️ Runs a stand-in executable end to end (`gta6rt --run`: CRT startup, statics, heap, files, threads, GDK imports through the shims, exit code back). Controllers through a GameInput shim on SDL3 (any controller SDL supports, rumble, DualSense trigger effects and lightbar; built when SDL3 is installed or with `-DLEONIDA_SDL3_FETCH=ON`, [notes](docs/gameinput.md)). `--trace-d3d12` logs every D3D12 call and its outcome for the first boot. Untested against the real executable | -| Xbox D3D12 → Vulkan | ⚠️ In progress. A Vulkan-backed device behind the Xbox-ABI proxy creates queues, command lists, fences, descriptor heaps, committed, placed and reserved resources, render-target and depth views (3D targets included), texture views and samplers (2D, cube, 1D and 3D views, the depth and stencil planes of depth-stencil textures, packed formats such as B5G6R5, B4G4R4A4 and R9G9B9E5, buffer SRVs — raw, structured and typed; they go into the bindless set), root signatures, pipelines and query heaps, and draws run on Vulkan. Barriers, clears, uploads, copies (BC included), colour resolves, predication, CPU-side texture reads and writes, and occlusion, timestamp and pipeline-statistics queries run on Vulkan, checked on one GPU. The console-shaped command-list proxy, the measured `PresentX` queue slots (30/32, layout-detected) wired to the presentation core, and `AllocateUploadMemory` (list slot 148, a mapped-upload arena whose addresses translate to buffer device addresses in root descriptors and IA/SO views) cover the console-ABI surface the package measures. Still open: the console list tail and the descriptor-table record model ([plan](docs/d3d12_vulkan.md)) | +| Xbox D3D12 → Vulkan | ⚠️ In progress. A Vulkan-backed device behind the Xbox-ABI proxy creates queues, command lists, fences, descriptor heaps, committed, placed and reserved resources, render-target and depth views (3D targets included), texture views and samplers (2D, cube, 1D and 3D views, the depth and stencil planes of depth-stencil textures, packed formats such as B5G6R5, B4G4R4A4 and R9G9B9E5, buffer SRVs — raw, structured and typed; they go into the bindless set), root signatures, pipelines and query heaps, and draws run on Vulkan. Barriers, clears, uploads, copies (BC included), colour resolves, predication, CPU-side texture reads and writes, and occlusion, timestamp and pipeline-statistics queries run on Vulkan, checked on one GPU. The console-shaped command-list proxy, the measured `PresentX` queue slots (30/32, layout-detected) wired to the presentation core, and `AllocateUploadMemory` (list slot 148, a mapped-upload arena whose addresses translate to buffer device addresses in root descriptors and IA/SO views) cover the console-ABI surface the package measures. Still open: the console list tail and the descriptor-table record model ([plan](docs/d3d12_vulkan.md), [console ABI](docs/d3d12_xs_console_abi.md)) | | Ray tracing (BVH) | ⚠️ In progress. `BuildRaytracingAccelerationStructure` builds BLASes and TLASes on the GPU in the console's XDXR BVH4 layout (the default; `LEONIDA_RT_AS=khr` uses Vulkan's own acceleration structures instead), which the translated shaders walk themselves through `image_bvh_intersect_ray` (all four triangle node types, TRI0-TRI3, with the barycentric remap byte); the GPU builder writes TRI0 and TRI1 leaves. Updates refit instead of rebuilding, and clone, compaction and the compacted/current postbuild sizes work; checked against a CPU reference on synthetic scenes. The build descriptions are recovered from the package's `XboxBvhBuilder.dll` ([notes](docs/xdxr.md)). The game's `*_bvh4.rpf` packs are measured: offline-built, dehydrated BLASes that rehydrate through that DLL with their geometry from the drawables in `levels.rpf` (measured on 8 of the 10 sampled BLAS; [notes](docs/bvh.md)). Not done in the builder: serialization. TRI1 pairing (no memory saved yet) and BOX16 nodes for `MINIMIZE_MEMORY` BLASes (an assumed switch) are in ([notes](docs/bvh.md)). Open: whether the game rehydrates the packs or rebuilds them ([#313](https://github.com/ItsNotRexed/Leonida/issues/313)) | The table above is written by hand. To measure it on your own checkout (unit and runtime tests, which rows of diff --git a/docs/README.md b/docs/README.md index f5f878a8ac..62f5eb4d71 100644 --- a/docs/README.md +++ b/docs/README.md @@ -72,13 +72,18 @@ method, scope and caveats. No game data is included. | [descriptor_lookup_intel.md](descriptor_lookup_intel.md) | Intel UHD Graphics 770 (Xe-LP, Windows, driver 101.6129) timings for the same lookups at 1k–100k live entries; both memory placements within 0.6% of each other. | | [d3d12_xs_surface.md](d3d12_xs_surface.md) | The 116-slot `d3d12_xs.dll` export surface; 83/83 standard GUIDs match the PC SDK. | | [xdxr.md](xdxr.md) | `BATCHED_DESC2` (`0x50`) and `XDXR_STREAM_DESC` (`0x10`) from `XboxBvhBuilder.dll`'s reads; stream records' offsets and defaults; offline statistics not in the package. | +| [d3d12_xs_console_abi.md](d3d12_xs_console_abi.md) | The D3D12.X console ABI the `d3d12_xs` shim must reproduce: device/queue/list vtable slots, command-list object fields and record encodings, root-argument SGPR rules, unified memory; sibling-layer measurements marked unverified here. | | [d3d12_command_objects.md](d3d12_command_objects.md) | Measured command queue/list/fence/`PresentX` surface; verified vs prior art vs open. | | [xbox_d3d12_xs.md](xbox_d3d12_xs.md) | The `d3d12_xs` graphics ABI quoted from Microsoft's public GDK reference: root signatures, state objects, DXIL libraries, hit groups, shader cache sessions; which pages are missing or NDA-gated. | | [runtime_imports.md](runtime_imports.md) | The 16 shipped modules' measured imports and shim/host/unimplemented split. | | [xmem_exe_calls.md](xmem_exe_calls.md) | How the retail executable calls `xmem.dll`: call sites and constant arguments per import (`tools/import_call_sites.py`), the 23 `XMemVirtualAlloc` calls that all pass an attribute word, and the inferred shape of the physical-page family. | | [audio_hal_exe_calls.md](audio_hal_exe_calls.md) | How the retail executable calls the 22 audio coprocessor, texture layout and DirectStorage imports that have no shim: call sites, constant arguments, and the four calls with a negative-result branch. | +| [cpu_features.md](cpu_features.md) | CPU instructions in the executable a desktop CPU may lack (`tools/cpu_feature_scan.py`): 19 SSE4a, 10 CLZERO and 4 MONITORX/MWAITX sites (AMD only) and 8 CLWB sites (Intel since Ice Lake), all real code; `#UD` on hosts without them. | | [xcl_compare.md](xcl_compare.md) | XCL's synthetic test title under `gta6rt --run` and under XCL (`tools/xcl_compare.py`): 5 of 50 checks pass here, both hangs are the documented manual-queue terminate deadlock, and each other difference mapped to an open item or a lead. | +| [directstorage.md](directstorage.md) | DirectStorage for the console title: the evidence for the DLL (`dstorage_xs.dll`, also `xcrdapi.dll`, `dstorage.dll`) and the console ABI with its confidence, and the shim: `GAME:` file open, queues, file and memory reads, status arrays, fences, events, cancel and errors; decompression and physical pages still open. | | [gameinput.md](gameinput.md) | The GameInput shim on SDL3: `GameInputCreate` and the v0 `IGameInput`/`IGameInputDevice`/`IGameInputReading`/`IGameInputDispatcher` surface on any SDL gamepad, DualSense adaptive-trigger approximation and lightbar, force-feedback motors and trigger haptics through SDL's haptic API; 261 checks on virtual joysticks and a fake haptic backend; by hand on an Xbox Series X pad (Bluetooth) and a DualSense (USB). 261 checks on virtual joysticks and a fake haptic backend, not yet tried on a real pad. | +| [directstorage.md](directstorage.md) | DirectStorage for the console title: the evidence for the DLL (`dstorage_xs.dll`, also `xcrdapi.dll`, `dstorage.dll`) and the console ABI with its confidence, and the shim: `GAME:` file open, queues, file and memory reads, status arrays, fences, events, cancel and errors, zlib requests inflated with their `E_DSTORAGE_ZLIB_*` errors; BCPack, swizzle and physical pages still open. | +| [gameinput.md](gameinput.md) | The GameInput shim on SDL3: `GameInputCreate` and the v0 `IGameInput`/`IGameInputDevice`/`IGameInputReading`/`IGameInputDispatcher` surface on any SDL gamepad, DualSense adaptive-trigger approximation and lightbar, force-feedback motors and trigger haptics through SDL's haptic API; 261 checks on virtual joysticks and a fake haptic backend, not yet tried on a real pad. | | [saves.md](saves.md) | Save containers: `JSAV` (index + JSON story save, byte-exact rebuild), `ASAV` header, `SLAYER1` packed copy (not decoded); `tools/saves.py` and import into the offline `XGameSave` folder; key hashes are case-sensitive joaat (`tools/save_keys.py`). | | [pipeline_check.md](pipeline_check.md) | Driver-level corpus check: the full corpus, 26,503 of 26,503 modules and pipelines, 0 failures (RTX 4060 Ti); an earlier 10/12-shard run, 22,092 modules and 2,217 compute pipelines, also had 0 failures. Driver-level corpus check: 10/12 shards, 22,092 modules, 2,217 compute pipelines, 0 failures. | | [multi_gpu_validation.md](multi_gpu_validation.md) | Running disjoint shards on eight identical RDNA1/RADV GPUs: PCI-BDF pinning, base controls, per-card logs, the V540 farm's aggregate results and its known driver limitations. | diff --git a/docs/d3d12_command_objects.md b/docs/d3d12_command_objects.md index 5a214e3258..1aef122066 100644 --- a/docs/d3d12_command_objects.md +++ b/docs/d3d12_command_objects.md @@ -375,9 +375,10 @@ section 3.5a), and the console list has methods well past the PC tail: 71, 73, 8 FSR DLL. Slot 148 matters beyond the builder: the address it returns is written by the CPU and passed unchanged to the GPU -as a root SRV address, so console upload memory has the same address for the CPU and the GPU. A replacement must -return memory whose CPU pointer is also a valid GPU address (for this layer: inside the arena of -[d3d12_vulkan.md §3.3](d3d12_vulkan.md)). +as a root SRV address, so console upload memory has the same address for the CPU and the GPU. On a PC the two +address spaces differ, so `d3d12_xs_device.cpp` carves a bump arena out of persistently-mapped UPLOAD-heap +buffers: the title writes the mapped memory and the six root descriptor setters and the IA/SO view setters +translate the CPU pointer to the chunk's buffer device address before forwarding. The function at `0xd580` uses the 71/73 pair instead of the slot-146 barrier when the byte at RVA `0xd773c` is set. That byte is one of seven bools at `0xd7738`–`0xd773e` in zero-initialised `.bss`. The only accesses to them in @@ -764,6 +765,12 @@ Queues and fences are wrapped the same way. object implements but the proxy does not model is logged once and refused. - **The refused tail.** A slot past the public chain, up to the end of the proxy's own table (128 queue and 64 fence slots, every one a thunk), logs its first four argument words once and returns `E_NOTIMPL`. +- **Fence slot 12.** The one served slot past the chain. The retail executable calls it as + `(value, descriptor, flags)` and reads the return as a pointer to the fence's 64-bit completed value: it + compares that value with `~0` (device removed) and subtracts the value it waits for. The proxy returns a + per-fence mirror. Completion events refresh it immediately. A 10 ms wait timeout also refreshes it if the + fence rewinds below the pending event's threshold. Slot 12 and the CPU `Signal` (10) refresh it synchronously. + The descriptor's second word is a code pointer, which is not called. - **The guard region.** Each table sits at the end of the first page of a 64 KiB reservation, and the rest of that reservation is never committed. A slot past the table therefore faults on the vtable read itself, inside the reservation, and a vectored handler logs the slot before the fault goes on. A vtable read that @@ -830,7 +837,7 @@ command object. | Item | Why it is blocked | |---|---| | `PresentX` | No slot, signature, plane struct or swapchain/plane parameters. Prior art gives only names, the 2-plane/8-view limits and four flag names. | -| `CreateCommandQueueX` | No slot or parameter layout; only the UMD message and an inferred shape. | +| `CreateCommandQueueX` | No slot or parameter layout; only the UMD message and an inferred shape. The retail title calls device slot 48 as (desc, riid, out) with a 32-byte desc (#6954), which differs from the (pDesc, pShaderQueueParams, riid, out) shape inferred above. | | `SuspendX` / `ResumeX` | No slot or signature. | | Xbox queue/list/fence/allocator slot deviations | No runtime binary and no game executable; the package has no queue, fence or allocator client, and its only command-list client is the BVH builder. | | Builder's list field `+0x350` | Read once (`0x1d877`) and not explained by the inline buffer of section 3.5a, which covers `+0x18`, `+0x28`, `+0x30`, `+0x140`, `+0x141`, `+0x344` and `+0x544`. | diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 5f711aefa0..2eb07eeb81 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -90,7 +90,13 @@ enough for the bundled middleware's `d3d12_xs` calls, not for the game. The laye desktop order, but also an extra texture-creation method at slot 76, a `CreateComputePipelineState` call at slot 62 where the PC interface it forwarded to presents `CreateStateObject` (different arity), and descriptor-heap start handles returned in RAX at heap slots 9/10. Implement the public chain plus those measured overrides - explicitly; do not assume every slot. Device 11 adds `CreateSampler2`; command list 8 adds + explicitly; do not assume every slot. On the retail executable's higher device slots (`runtime/shims/d3d12_xs_device.cpp`), + slot 86 routes `CreatePipelineState(desc, riid, out)` to PC slot 47 (`ID3D12Device2::CreatePipelineState`), + slot 101 routes `CreateStateObject(desc, riid, out)` to PC slot 62 (`ID3D12Device5::CreateStateObject`), and + slot 108 routes `GetResourceAllocationInfo2` (accepting the console C-ABI struct return with the return buffer in + `RCX` and the device in `RDX`, expanding 56-byte `D3D12_RESOURCE_DESC` entries to `D3D12_RESOURCE_DESC1` and + normalizing Xbox layout words and flag bits on the copy) to PC + slot 68 (`ID3D12Device8::GetResourceAllocationInfo2`). Device 11 adds `CreateSampler2`; command list 8 adds `OMSetFrontAndBackStencilRef` (public SDK). - **Unknown IIDs and slots.** `QueryInterface` must log the IID and return `E_NOINTERFACE` if it is not in the public chain. If the game then fails, the IID and the call site identify the Xbox-specific interface to reverse. @@ -169,7 +175,7 @@ The command-list surface maps to the IR as follows: | `SetGraphicsRootSignature` / `SetComputeRootSignature` | state; select the pipeline layout and root map | | `Set*Root32BitConstant(s)` / `Set*Root*View` / `Set*RootDescriptorTable` | update root args; build the push-constant block at the draw/dispatch | | `SetDescriptorHeaps` | state; scan/populate the bindless arrays and hash table at execute | -| `IASetVertexBuffers` / `IASetIndexBuffer` / `IASetPrimitiveTopology` | state; bind arena buffer + offset, dynamic topology | +| `IASetVertexBuffers` / `IASetIndexBuffer` / `IASetPrimitiveTopology` | state; bind arena buffer + offset, dynamic topology. The console's rectangle list (17, PSO topology type 19) and quad list (19) are drawn as triangles, see *Console rectangle and quad lists* below | | `RSSetViewports` / `RSSetScissorRects` | state; dynamic viewport/scissor | | `OMSetRenderTargets` / `OMSetBlendFactor` / `OMSetStencilRef` | state; rendering scope and dynamic state | | `DrawInstanced` / `DrawIndexedInstanced` | command with a state snapshot | @@ -451,9 +457,17 @@ What is implemented (all of it testable without the game): enables BC texture compression, and `D3D12_OPTIONS12` reports `RelaxedFormatCastingSupported = TRUE`, so a committed or placed texture accepts a castable-format list. Other queries (including `OPTIONS6` and `OPTIONS10`) are logged and refused until the trace shows what the game asks (question 11); - - Single-sampled `A8_UNORM` 2D textures use one byte per texel in `VK_FORMAT_R8_UNORM`. Their SRVs expose + - Single-sampled `A8_UNORM` 1D, 2D and 3D textures use one byte per texel in `VK_FORMAT_R8_UNORM`. Their SRVs expose (0, 0, 0, A) before applying the caller's component mapping. Format support includes `MIP` when the Vulkan - image supports multiple levels. Render-target, depth-stencil and UAV creation are unsupported for this format. + image supports multiple levels. Where the GPU has `VK_FORMAT_A8_UNORM_KHR` (`VK_KHR_maintenance5`) and can + sample, copy and blend it as a colour attachment, a texture created with `ALLOW_RENDER_TARGET` is stored in that + format instead: its RTVs, PSO `RTVFormats` and clears use the alpha channel, its SRVs view it in the same format + (the T# names its one channel X, gfx10's `channels_a`), and format support adds `RENDER_TARGET` and + `BLENDABLE`. Vulkan puts A8 in a compatibility class of its own, so the two kinds of A8 texture cannot share + an image. A castable-format list naming `A8_UNORM` itself is a no-op; any other format in it is refused with + `E_INVALIDARG` for such a render target, since no other format can view its image. Without that format, + render targets are refused as before; depth-stencil and UAV creation are + unsupported for this format. - reserved resources and `GetResourceTiling` (section 4.2); - query heaps for occlusion, timestamps and pipeline statistics, and `GetTimestampFrequency` on the queue (section 4.6); @@ -1526,6 +1540,42 @@ Arena VAs (at most 4095 MiB, so 32-bit) pass. A VA biased from outside the arena VAs above are at or above 2^40 as unsigned values. That is one more reason for the rule above that every buffer a console client can address is an arena range, whichever heap it comes from. +**Title-chosen addresses.** Two kinds of buffer address are the title's choice, not the layer's: +- device slot 133 (`CreatePlacedResourceX`) puts a buffer at the CPU address of the title's own pages; +- the title points root views and V#s at its own memory, for instance a per-frame constant ring (#8862, section + 3.5 of `docs/retail_boot_chain.md`). + +On Windows these are user-mode addresses far above 4 GiB, past the arena (at most 4095 MiB, and descriptor +tables must stay below 4 GiB), so `heap_base + VA` names nothing the layer made (the D3D-53 failure above). The layer +therefore replaces such an address, wherever it sees one, by the console VA of a GPU copy of that memory +(`runtime/src/title_va_alias.h`): + +| Where the address is | When it is replaced | +|---|---| +| Root CBV/SRV/UAV (`Set*Root*View`) | when the argument is set | +| CBV and buffer SRV/UAV V#s the layer writes (`Create*View`, slot 70, counter V#s included) | when the descriptor is written | +| Buffer V#s the title writes into a shader-visible CBV/SRV/UAV heap itself | before each `ExecuteCommandLists`, in place, for the tables the submitted lists bind and only the slots their root signatures declare | + +The copies: +- A **slot-133 buffer** whose pages cannot be imported is the per-submission shadow, and the shadow is an **arena + range** when it fits. Its console VA is its arena offset, which holds in a root argument, in a V#'s 48 bits and in + a 32-bit table pointer alike. Without room in the arena it keeps its own memory and is biased like an upload buffer + (logged once; raise `LEONIDA_ARENA_MB`). An **imported** slot-133 buffer is reached at its device address minus + `heap_base` (mod 2^64): exact for root arguments, and for a V# only when the driver put the import above the arena + (logged once otherwise). +- Any **other address in the title's memory** gets a window: the 64 KiB-aligned pages it covers, clipped to the + title's range, copied into the arena now and before every submission, through the same shadow refresh as slot 133 + (so dirty-page tracking for that refresh applies to both). Windows stay until the device goes, up to + `LEONIDA_TITLE_WINDOWS_MB` (64 MiB by default). +- **Only the title's memory** gets a copy: the blocks and ranges the xmem shims hand the title (`XMemAlloc`, + `XMemAllocDefault`, `XMemVirtualAlloc`, the title's `VirtualAlloc`). An address anywhere else, the runtime's or a + host DLL's memory included, is left as it was and counted, as is an arena VA or a buffer the layer made. + +The title's own VA is still what `GetGPUVirtualAddress` answers, and vertex, index, copy and immediate-write calls +still resolve it through the buffer VA index, which knows slot-133 buffers by that VA. The copies are one way: what +the GPU writes into a copy does not reach the title's pages. A pointer the title hides elsewhere (a raw VA inside its +constant data that a shader dereferences) is not seen by the layer and keeps the title's VA. + Why not give each buffer its own BDA and set `heap_base = 0`? Because 25,865 of the 26,503 shaders (97.6%) truncate descriptor-table pointers to 32 bits, and host BDAs are not guaranteed to be below 4 GB. The arena keeps console VAs low and stable. @@ -2061,6 +2111,17 @@ Pipeline creation: and pipeline-cache UUID. When the file is absent or incompatible, the runtime starts with an empty cache. The offline checker matches the runtime's layout and subgroup request for compute shaders with no descriptor bindings and the standard 144-byte push-constant range. + The runtime also keeps what it compiled itself: `pipeline_cache.session.bin`, written from + `vkGetPipelineCacheData` on device teardown and merged into the cache at the next launch with + `vkMergePipelineCaches` (the offline seed and the session file cannot be passed together as one + `VkPipelineCacheCreateInfo`). The two files are separate so a run never replaces the multi-GB corpus cache with + the handful of pipelines it happened to compile. The session write is capped at 256 MiB + (`LEONIDA_PIPELINE_CACHE_BYTES=`, `0` turns it off): a cache seeded with the corpus file returns the whole + union, which is not worth rewriting at every exit. A session file from another device, driver or pipeline-cache + UUID is ignored with one line, and a write that fails (a read-only install directory) leaves the previous file. + Set `LEONIDA_STARTUP_CACHE_CHECKPOINTS=1` to write the session file after a successful compute pipeline + compile that took at least 500 ms. A later launch can reuse the completed work if the process exits before device + teardown. The session file keeps the same size cap and atomic replacement. `GetCachedBlob` records the vendor, device, driver version, `pipelineCacheUUID` and a SHA-256 of the description without `Flags`, sealed by a checksum (`runtime/src/cached_pso.h`). The answers are the host's, measured on an RTX 3060 and WARP: the same description is accepted; another @@ -2118,11 +2179,22 @@ The trace will enumerate them. - **What it doesn't cover:** whether the console flattens a 3D `DispatchMesh` grid the same way. That is an open question in `docs/design.md`, "Mesh shaders"; the test shader reads the workgroup ID directly. +### Console rectangle and quad lists + +The console has two list topologies Vulkan lacks: rectangle list (`IASetPrimitiveTopology(17)`, with a PSO whose topology type is 19) and quad list (`IASetPrimitiveTopology(19)`). The facts are from xvalkyrie (GPL-3.0, commit `53af7df77c10`; no code taken): a rectangle is three corners and the fourth is v2 + v3 - v1 for the position and every interpolant, after the vertex stage; a quad is four vertices. The layer draws both as triangles (`d3d12_rect_list_test`, RTX 4090: 4096 of 4096 pixels, the colour plane exact, quad list bit-exact). +- **Rectangle list**: PSO type 19 builds a triangle-list pipeline plus a generated geometry stage (`src/rect_list_geometry.h`, written from the vertex shader's own outputs) that takes the three corners and emits the strip v1 v2 v3 v4 (same winding). It has to be post-vertex-stage: the translated vertex shaders fetch by V# themselves, and the fourth corner is a function of what they write. A corner value with the same bits at all three corners (a flat attribute) is copied. Needs `geometryShader` (else `E_NOTIMPL`), no application GS, and a vertex shader with no ClipDistance, CullDistance, Layer or ViewportIndex output. +- **Quad list**: a non-indexed draw uses a shared index buffer containing the triangle-list pattern + `0 1 2, 0 2 3` for each quad. Both triangles start at the first vertex for flat inputs. One draw preserves instance + order and supports up to 16384 quads. The draw's first vertex becomes the vertex offset. Indexed draws still + read the application's index buffer as one four-vertex fan per quad. Vulkan fans use a different provoking + vertex for flat inputs, and overlapping blended instances rasterize quad by quad in this path. The PSO type + is the ordinary triangle type. + ## 4. Object model mapping | D3D12 / Xbox object | Vulkan / layer object | Notes | |---|---|---| -| `ID3D12Device` … `ID3D12Device11` | one `Device` object with the public chain plus measured Xbox overrides | The shipped BVH builder names Device11; slots 1/15/18/19/27/38 matched desktop in prior art, slot 62 is called as `CreateComputePipelineState`, slot 76 is Xbox texture creation, and heap slots 9/10 return in RAX. Unknown Xbox IIDs/slots are logged and refused. | +| `ID3D12Device` … `ID3D12Device11` | one `Device` object with the public chain plus measured Xbox overrides | The shipped BVH builder names Device11; slots 1/15/18/19/27/38 matched desktop in prior art, slot 48 is called as `(desc, riid, out)` with `IID_ID3D12CommandQueue` (PC slot 48 is `OpenExistingHeapFromAddress`; the 32-byte desc is a PC `D3D12_COMMAND_QUEUE_DESC` plus four Xbox words, logged once, and the proxy takes the slot 8 path with the PC prefix and only `DISABLE_GPU_TIMEOUT` kept), slot 62 is called as `CreateComputePipelineState`, slot 76 is Xbox texture creation, and heap slots 9/10 return in RAX. Unknown Xbox IIDs/slots are logged and refused. | | `ID3D12CommandQueue` | one leased `VkQueue` per live queue: direct queues on the graphics family, compute queues on an async-compute family and copy queues on a transfer-only (DMA) family when the GPU has them (`src/queue_families.h`), else graphics-family leases | Distinct Vulkan queues allow cross-queue waits and signals to make progress. With more than one family in use, buffers, images, the arena and staging are created `VK_SHARING_MODE_CONCURRENT` over those families, so no ownership transfers are needed. Barriers on copy and compute queues are narrowed to the stages their family has; render-target and depth clears are refused there (as in D3D12), and the D24/RGB96 copy conversions and bindless flushes stay off a transfer-only queue. Tested by `vk_queue_test`. `PresentX`, `SuspendX`, `ResumeX` are Xbox queue methods, not in the public vtable; public GDKX samples present only through them (§4.5). Call shapes known, slots **Open**. | | `ID3D12CommandAllocator` | IR arena + `VkCommandPool` | Reset only when the previous submission's fence is complete. | | `ID3D12GraphicsCommandList` … `8` | `CommandList` with IR | Replay at `ExecuteCommandLists`; bundles inlined. Supports render passes, mesh dispatch, enhanced barriers; records the GCL8 front/back stencil references (applied only once a pipeline path consumes them). `Draw` views are inlined and moved into the command stream (D3D-289), eliminating per-draw heap allocations. | @@ -2247,18 +2319,47 @@ The trace will enumerate them. Intel Raptor Lake-S (101.7092) and RTX 5060 Laptop (621.24) hosts wrap, two 2^63 buffers to 0, and WARP on that PC still saturates. A wrapped total could make a caller allocate less than one of its resources, so the layer keeps saturating, and the test accepts a host that wraps. + Behind the Xbox-ABI proxy (device slots 25 and 56) a 2D render target of a listed colour format with one sample is + padded to whole console tiles: the size is the sum over its mips (MipLevels 0 is the full chain, an odd extent + rounds up), each mip rounded up to the RDNA2 SW_64KB_D tile shape (`runtime/src/gfx10_tiling.h`: 256 x 128 pixels + for 2-byte elements, 128 x 128 for 4-byte, 128 x 64 for 8-byte, 64 x 64 for 16-byte), with the first mip that fits + in half a tile's width and a whole tile's height, and the mips after it, sharing one tail tile, times the array + size. A 1920 x 1080 RGBA8 target is 135 tiles, 8,847,360 bytes, where the PC answer is 8,323,072. The proxy lays + the descriptions out as the PC device does (each at its own alignment, the total rounded up to the largest + alignment, sums saturating) with each render target at the larger of its console size and its PC size; a 4 MiB + aligned multisampled neighbour therefore keeps its place (a 1 x 1 four-sample target and a 1080p target need 16 MiB, + not 12.5). Slot 56 reports the same offsets. The PC layout stands when no description grows + (`d3d12_xs_alloc_size.h`; `xs_proxy_mock_test`). **Assumption**: the + retail title's own sizes are not measured (#6982, stop 17), so that its allocation is these shapes and no DCC or + CMask memory is open until they are. + The descriptions the title passes to slot 25 carry console values (layout word `0x101`/`0x1`, flag bits above the PC + ones). For console-form calls or descriptors explicitly using layout `0x101`, the proxy strips Xbox-only flags and + translates layout `0x101` to ROW_MAJOR for buffers or UNKNOWN for textures. Other PC-form descriptors reach the host + unchanged for validation (`d3d12_xs_desc_clean.h`; #6982 section 3.7). + A committed resource made through slots 76 and 127 also allocates its console size (the whole tiles above for a + listed render-target shape, never a larger PC answer; otherwise the PC size) through the title's + `__XMemAllocationHooks__`, as the console runtime's `XMemAlloc` for the resource does, and frees it when the + resource is destroyed (a lease kept with `SetPrivateDataInterface`; the bytes are not used). The retail title + budgets its first full-screen render targets with such a hook: it bump-allocates the allocations whose XALLOC + page-size field is 2 out of a range it reserved and asserts that less than 2 MiB is left (RT-5 stop 17); two + 3840 x 2160 RGBA8 targets are 2 x 510 tiles of a 64 MiB range, and AMD's 513 x 64 KiB answer would overrun it. The + lease's attribute word (allocator ID 0x80, page-size field 2, object type 0) is an **assumption**; the measured + hook reads only the page-size field. - `GetAdapterLuid` (implemented): `VkPhysicalDeviceIDProperties::deviceLUID`, which on Windows is the DXGI adapter's LUID; `d3d12_fence_timing_test` finds it with `IDXGIFactory4::EnumAdapterByLuid` (RTX 4090, driver 621.14). A driver that reports `deviceLUIDValid = VK_FALSE` gets a zero LUID, logged. -- `GetCustomHeapProperties` (implemented): the D3D12 documentation's table for the architecture - `D3D12_FEATURE_ARCHITECTURE` reports. On a discrete GPU (`UMA = FALSE`): `DEFAULT` is `NOT_AVAILABLE`/`L1`, - `UPLOAD` `WRITE_COMBINE`/`L0`, `READBACK` `WRITE_BACK`/`L0`, `GPU_UPLOAD` `WRITE_COMBINE`/`L1`. On an integrated - GPU (`UMA = TRUE`, `CacheCoherentUMA = FALSE`) the same pages, all in `L0`, and a custom heap in `L1` is refused - with `E_INVALIDARG` (`CreateHeap`, `CreateCommittedResource`), as the host runtime does on - a Radeon 780M (AMD 32.0.13030.13001) and on WARP. All answers have type `CUSTOM` and node masks 1. `CUSTOM`, - unknown types and node masks above 1 get an all-zero answer, logged. The test compares `DEFAULT`, `UPLOAD` and - `READBACK` byte for byte with the host runtime's answer when the host adapter has the layer's architecture (RTX - 4090: identical); `d3d12_heap_properties` compares the `L1` heaps with the layer's own adapter. +- `GetCustomHeapProperties` (implemented): the D3D12 documentation's table for a NUMA adapter, matching the + `UMA = FALSE` that `D3D12_FEATURE_ARCHITECTURE` reports: `DEFAULT` is `NOT_AVAILABLE`/`L1`, `UPLOAD` + `WRITE_COMBINE`/`L0`, `READBACK` `WRITE_BACK`/`L0`, `GPU_UPLOAD` `WRITE_COMBINE`/`L1`, all with type `CUSTOM` and + node masks 1. `CUSTOM`, unknown types and node masks above 1 get an all-zero answer, logged. The test compares + `DEFAULT`, `UPLOAD` and `READBACK` byte for byte with the host runtime's answer (RTX 4090: identical). + The retail executable calls it (device slot 26) with the buffer for the returned struct in RCX and the device in + RDX, node mask in R8 and heap type in R9: three calls right after device creation, node mask 1 and types 1, 2 + and 3 (measured under `gta6rt --run` with a register probe in the slot's thunk). A PC C++ method has the device + in RCX and the buffer in RDX, so the Xbox-ABI proxy takes the console form when RDX holds the proxy + (`d3d12_xs_device.cpp`; `xs_proxy_mock_test`, `device_proxy_test`). Slot 43 returns a struct too and the + proxy still forwards it in the PC form: no call of slot 43 has been seen. Slots 25 and 56 take the same form by the + same rule (reported later in the boot, #6982; not measured), as #6973 first did for slot 25. - Residency and power (D3D-33) are no-ops that still check their arguments (`d3d12_vulkan_device.cpp`, tested in `d3d12_vulkan_device_test`). Vulkan has no residency API: memory from `vkAllocateMemory` stays usable until `vkFreeMemory`, and paging under pressure is the kernel driver's job, so every pageable object is always resident. @@ -2923,16 +3024,8 @@ SDL2 `src/render/direct3d12/SDL_render_d3d12_xbox.cpp` (zlib). entries carry a `PlaneIndex`; display entries carry `PercentScanned`. 11. Xbox titles do not handle `DXGI_ERROR_DEVICE_REMOVED`/`RESET`. -*Public corroboration (not measured here).* XCL, a GPL-2.0-only compatibility layer that runs retail Xbox Series -titles, records `PresentX` at queue slot 30 for the older runtime layout (XDefiant, Minecraft, Fortnite) and 32 for -a newer one (Unicorn Overlord), and the four frame calls at device slots 78-81: `SetFrameIntervalX`, -`ScheduleFrameEventX`, `WaitFrameEventX`, `GetFrameStatisticsX` (0-based, `QueryInterface` = 0). The Apache-2.0 -ebiten Xbox binding has the same device order, declares `D3D12XBOX_PRESENT_PLANE_PARAMETERS` as a 0x48-byte x64 -struct and `D3D12XBOX_PRESENT_PARAMETERS` as 0x20 bytes, and stores the token in 64 bits. So the plane and -present-parameter layouts and the token width in `runtime/shims/xbox_present.h` are no longer guesses; the enum -values and the `SuspendX`/`ResumeX` slots still are. XCL returns `S_FALSE` from a timed-out `WaitFrameEventX` -where this layer returns `HRESULT_FROM_WIN32(WAIT_TIMEOUT)`. The full comparison is in -[d3d12_xs_surface.md §7.1](d3d12_xs_surface.md#71-public-sources-for-the-presentation-and-device-abi). +*Not measured:* vtable slots of all `*X` methods, exact `D3D12XBOX_*` struct layouts and sizes, enum values, and +whether the token is exactly 64 bits in the ABI. The samples give argument counts and field names only. *Hypothesis (the game is not observed):* a GDKX title follows this pattern, so the DXGI swapchain shim (D3D-2) is probably **not** on its boot path. What is on it: `D3D12XboxCreateDevice`, `IDXGIDevice1`/`IDXGIAdapter`/ @@ -2959,11 +3052,10 @@ Layer plan: **What is implemented (the presentation core).** Everything in the plan above that does not need a slot exists as methods of `rt::d3d12::XboxPresentation` (`runtime/shims/xbox_present.h`), on top of the presenter of section 3.2 and -`leonida::FramePacer` (`runtime/src/frame_pacer.h`, no Vulkan, no Windows headers). The plane and present-parameter -layouts and the 64-bit token are confirmed on x64 by the public code cited above; the constant values and HRESULTs -are **our own provisional definitions**, because the samples give call shapes and field names only and the enum -values are still unmeasured. The class is the surface the proxy will forward to. The queue-side calls ignore which -queue they came on (one `VkQueue` behind all of them). +`leonida::FramePacer` (`runtime/src/frame_pacer.h`, no Vulkan, no Windows headers). The struct layouts, constant +values, HRESULTs and the 64-bit token are **our own provisional definitions**: the samples give call shapes and field +names only, so the real slots, layouts and enum values are still unmeasured and the class is the surface the proxy +will forward to. The queue-side calls ignore which queue they came on (one `VkQueue` behind all of them). - *Frame pacing* (`FramePacer`, time from an injectable clock; real time is a steady timer, a host vblank source can replace it). `SetFrameIntervalX` takes the interval as a period in microseconds and the latency, and starts @@ -3190,10 +3282,9 @@ queue they came on (one `VkQueue` behind all of them). second (GameDVR) output, resolving multisampled planes, a mutable-format swapchain (an sRGB/UNORM alternation recreates the swapchain; `VK_KHR_swapchain_mutable_format` is not enabled on the device), a host-vblank clock (the timer drifts from the display; with FIFO presents the swapchain holds the queue to the real refresh anyway), render statistics, - `PercentScanned` of frames shown at a vblank (a scan position is never measured), and the vtable wiring. The - public slots are the device's `SetFrameIntervalX`/`ScheduleFrameEventX`/`WaitFrameEventX`/`GetFrameStatisticsX` - at 78-81 and `PresentX` at queue 30 (older runtime layout) or 32 (newer); `SuspendX`/`ResumeX` have no public - slot. Nothing here is wired to those slots yet, and the game's own runtime is not observed. + `PercentScanned` of frames shown at a vblank (a scan position is never measured), and the vtable wiring. Slots to measure (all unknown): the device's `SetFrameIntervalX`, + `ScheduleFrameEventX`, `WaitFrameEventX`, `GetFrameStatisticsX` and the queue's `PresentX`, `SuspendX`, `ResumeX` + (the list is in the header). - *Tests*: `frame_pacer_test` (fake clock: interval, offset, late waits, timeouts, latency blocking, tokens, statistics, suspend/resume, a real 10 ms timer; no GPU) and `xbox_present_test` (the Vulkan device, reading the swapchain image back: blank, solid, two colours, source rectangles, RGBA/BGRA/sRGB sources, 2 planes, plane composition @@ -3500,6 +3591,8 @@ to be recovered from call sites (or the NDA GDK headers, if a developer has acce | DCC / texture compatibility | Public release note for `D3D12XBOX_RESOURCE_FLAG_FORCE_TEXTURE_COMPATIBILITY` | Let Vulkan choose compression; fail if the game aliases/reads raw compressed data. | | PresentX / present planes / frame events | Public GDK samples (MIT/zlib), §4.5 | Likely the only present path of a GDKX title. Presenter + vblank-timed frame events; 1-2 planes composed into the Vulkan swapchain (placement, filter, alpha overlay, HDR10 conversions). Call shapes known; slots/layouts **Open**. | | Device slots 48/73/78/79/80 | Public HLE `Freminet`/`ScarlettX` (third-party, not Microsoft documentation) | `d3d12_xs_device.cpp` routes `CreateCommandQueueX` (48), `CreateCommandListX` (73), `SetFrameIntervalX` (78), `ScheduleFrameEventX` (79) and `WaitFrameEventX` (80) before it indexes the PC vtable. Queue and list creation use the existing create paths. The frame-event calls are a per-device token counter: `WaitFrameEventX` returns at once with a fresh non-zero token, because there is no vblank source before a presenter exists. The five indices can be moved with `LEONIDA_XS_QUEUE_X_SLOT`, `LEONIDA_XS_LIST_X_SLOT`, `LEONIDA_XS_FRAME_INTERVAL_SLOT`, `LEONIDA_XS_SCHEDULE_EVENT_SLOT` and `LEONIDA_XS_WAIT_EVENT_SLOT` (3..127; a value that names a slot the proxy already handles keeps that slot's handler); a trace that disagrees wins. | +| Indirect argument type 105 | The retail title's startup creates five one-argument command signatures (device slot 41) with no root signature; one has type 105 and a 12-byte stride. Its two `ExecuteIndirect` sites, read statically, set the compute state first, as the `DISPATCH` sites do, and pass one command from the same argument buffer, on a second command list | `d3d12_xs_device.cpp` creates it as `DISPATCH` (`D3D12_DISPATCH_ARGUMENTS`). What the console does differently for it is **Open**. | +| Device slot 61 | The retail title's boot under `gta6rt --run` (stop 20 of the RT-5 measurements in #6910): called as `(desc, dest handle)` once per sampler | `d3d12_xs_device.cpp` routes it to the PC `CreateSampler` (slot 22) with the description's PC `D3D12_SAMPLER_DESC` prefix; the PC slot 61 is `CreateMetaCommand`. The layout of the description beyond the PC fields is **Open**. | | VRS | Public `D3D12_SHADING_RATE` / `D3D12_AXIS_SHADING_RATE` | `VK_KHR_fragment_shading_rate`; `RSSetShadingRate`/image-based rate map to `vkCmdSetFragmentShadingRateKHR`. | | Mesh shader tier | Public `D3D12_MESH_SHADER_TIER` | `VK_EXT_mesh_shader`; the 9,282 translated mesh shaders make this a hard requirement for any content that uses them. | | Wave MMA | Public `D3D12_WAVE_MMA_TIER` | Not used: no shader sets `WAVE_MMA` in SFI0 and none contains `v_mfma`/`v_wmma` (all 26,503, `tools/feature_scan.py`). Answer the tier query truthfully; no cooperative-matrix mapping is needed. | @@ -3920,7 +4013,7 @@ nothing is copied from their trees. | 8 | What are the layouts of `D3D12XBOX_XDXR_STREAM_DESC`, the batched build desc, and the offline statistics desc? | **Measured** from `XboxBvhBuilder.dll`'s reads ([xdxr.md](xdxr.md)): `BATCHED_DESC2` (`0x50`) and `XDXR_STREAM_DESC` (`0x10`) with every field's offset, and the stream records' offsets, types and defaults. Still open: the record names, and the offline statistics layout, which the DLL never writes (it rejects that postbuild type). | | 9 | Xbox texture creation is device slot 76 with layout `0x101` (tiled) or `0x1` (row-major). What is the tiled data layout, and does the game upload console-tiled or DCC data? | Trace slot 76, `CopyTextureRegion` and the resource descs. If the game uploads console-tiled data, add a detile step or a matching layout. | | 10 | Does the game use binning, DCC, VRS, wave MMA, stream output, tessellation, or amplification shaders? | **Shaders: answered** by `tools/feature_scan.py` over all 26,503 (1.0.2.1): no hull, domain or amplification shader (DXIL program kinds: 2,236 VS, 12,101 PS, 195 GS, 2,689 CS, 9,282 MS); no `WAVE_MMA` or `SHADING_RATE` in any SFI0, and no `v_mfma`/`v_wmma`/`v_smfmac` in the disassembly; no output-signature element on a stream other than 0 (all 195 GS write stream 0 only) and no GDS / `ds_ordered_count` / GWS instruction, so no stream-output path. Also from SFI0: 10 PS need ROVs (pixel interlock), 30 shaders `TILED_RESOURCES` (see #18), 685 `ATOMIC_INT64_ON_TYPED_RESOURCE`. Binning and DCC are not shader-visible; they stay open for the PSO/stream subobjects. | -| 11 | What should `CheckFeatureSupport` answer for UMA, resource binding tier, mesh tier, RT tier? | **Implemented** (D3D-11). Reports truthful host architecture (a discrete GPU: non-UMA; an integrated GPU, `VK_PHYSICAL_DEVICE_TYPE_INTEGRATED_GPU`: UMA, not cache-coherent, as the host runtime answers on a Radeon 780M), ResourceBindingTier 3 (descriptor indexing / bindless support), 48-bit GPU virtual address support matching the arena, and maps `D3D12_FEATURE_FORMAT_SUPPORT` to Vulkan format properties plus multisample render-target/resolve support and one quality level per supported sample count. | +| 11 | What should `CheckFeatureSupport` answer for UMA, resource binding tier, mesh tier, RT tier? | **Implemented** (D3D-11). Reports truthful host architecture (discrete desktop GPU: non-UMA), ResourceBindingTier 3 (descriptor indexing / bindless support), 48-bit GPU virtual address support matching the arena, and maps `D3D12_FEATURE_FORMAT_SUPPORT` to Vulkan format properties plus multisample render-target/resolve support and one quality level per supported sample count. | | 12 | Does the game rely on async compute or copy queues for correctness? | Trace queue creation and cross-queue fences. If only performance, serialize on one queue for boot. | | 13 | Is 144 bytes of push constants available on all target GPUs? | **Resolved / Measured** (D3D-14). Checked at device creation in `runtime/shims/d3d12_vulkan_device.cpp`. Measured across the test fleet (#166): NVIDIA (256 B), desktop AMD (256 B), and Apple M1/MoltenVK (4096 B) satisfy 144 B natively. A Radeon 680M on the Windows driver 22.40.84.06 and the earlier Intel Arc entries expose only the core minimum 128 B (`maxPushConstantsSize == 128`), but an Arc B580 on Windows 11 (driver 32.0.101.9175) reports 256 B (#166), so the 128 B figure for Arc depends on the OS or driver; an Arc result on Linux (Mesa ANV) would settle which side it is. `d3d12_vulkan_device_test` accepts either answer and checks that the fallback flag matches it. Below 144 B, the device logs a warning and marks `push_constants_need_fallback`, routing the 16-byte tail (dwords 32..35: heap base and code base) to a uniform-buffer fallback. | | 14 | Are there PSOs with two code-base stages? | Count from the PSO/shader hash table and the index metadata. If yes, implement per-stage code-base slots (section 5.2). **Per stage, measured** (`tools/feature_scan.py`, `s_getpc_b64` kept for data rather than a far branch): 54 VS, 93 PS, 266 MS, 263 CS, 0 GS; the translator's `uses_code_base` gives the same counts (with LLVM 23 that needs #223, without which these 1,471 shaders are rejected). So VS+PS and MS+PS pipelines with two code-base stages are possible; whether any exists depends on which shaders a PSO pairs, which is in the executable, not in `shaders.rpf`. | @@ -4201,8 +4294,9 @@ on a PC device behind the Xbox-ABI proxy). Measured: - `amd_fidelityfx_loader_xbox.dll`, `Bink2Scarlett.dll`, `libHttpClient.GDK.dll`, `XCurl.dll`: no `d3d12_xs` imports. -- The package layout XML, chunk 1001, lists `game_scarlett_master.exe`; the file is absent from the folder. No - claim in this document depends on the executable's contents. +- The package layout XML, chunk 1001, lists `game_scarlett_master.exe`; the file is absent from the folder. One + claim in this document comes from running the executable from a player's own copy: how it calls device slot 26 + (section 4.1; register roles and argument values only). No other claim depends on the executable's contents. - The repository's existing import survey (`docs/design.md`, "Baseline already recorded") records that the 16 bundled DLLs need only `xmem` and the two `d3d12_xs` root-signature calls; our scan of the six non-CRT DLLs is consistent. diff --git a/docs/d3d12_xs_console_abi.md b/docs/d3d12_xs_console_abi.md new file mode 100644 index 0000000000..e1ec05fc7d --- /dev/null +++ b/docs/d3d12_xs_console_abi.md @@ -0,0 +1,279 @@ +# The D3D12.X console ABI: vtable slots, object fields and record encodings + +Status: measured-facts note, sourced. This page collects the Xbox Series (`d3d12_xs`) ABI facts a +replacement runtime must reproduce — vtable slot numbers, object field layouts and the inline +record encodings the console SDK writes into a command-list object — for the layers that are still +missing: command lists, root arguments, descriptor heaps and present. It complements +[d3d12_vulkan.md](d3d12_vulkan.md) (the Vulkan layer plan) and +[d3d12_command_objects.md](d3d12_command_objects.md) (what this package's own DLLs measure). + +Provenance rules for this page, stated once: + +- **Sibling layer** — measured by a sibling open-source layer on retail Series titles and + published as findings. Not independently reproduced here; treat every such claim as unverified + on this package. +- **Package** — measured on this package's shipped DLLs (`XboxBvhBuilder.dll`, + `amd_fidelityfx_upscaler_xbox.dll`); see + [d3d12_command_objects.md](d3d12_command_objects.md) §§3.3–3.5a. +- **SDK** — the public Windows SDK `d3d12.h` order, for contrast. +- **Unconfirmed** — consistent with the surrounding facts but not yet measured anywhere we can + check. + +All slot numbers below are absolute vtable indices including `IUnknown` (0–2) and the +`ID3D12Object`/`ID3D12DeviceChild`/`ID3D12Pageable` base slots, as in +[d3d12_command_objects.md](d3d12_command_objects.md) §2. + +## 1. Device (`ID3D12DeviceX` over the PC `ID3D12Device` layout) + +The console device keeps the PC slot order where measured, with extra console methods placed in +slots the PC chain uses for newer interfaces, plus a tail of console-only methods. Slots marked +**Package** were called by the shipped upscaler or BVH-builder DLLs with the stated shapes; the +rest are **Sibling layer** measurements. + +| Slot | Method | Evidence | +|---:|---|---| +| 8, 48 | `CreateCommandQueue` variants | Sibling layer | +| 9 | `CreateCommandAllocator` | Sibling layer | +| 10, 60 | `CreateGraphicsPipelineState` variants | Sibling layer | +| 12 | `CreateCommandList` | Sibling layer | +| 14 | `CreateDescriptorHeap` | Package + sibling layer | +| 15 | `GetDescriptorHandleIncrementSize` | Package + sibling layer | +| 17, 18, 19 | `CreateConstantBufferView` / `CreateShaderResourceView` / `CreateUnorderedAccessView` | Package + sibling layer | +| 22 | `CreateSampler` | Sibling layer | +| 23, 24 | `CopyDescriptors` / `CopyDescriptorsSimple` | Package + sibling layer | +| 25 | `GetResourceAllocationInfo` | Sibling layer | +| 29, 44 | `CreatePlacedResource` variants | Sibling layer | +| 38 | `GetCopyableFootprints` | Package + sibling layer | +| 41 | `CreateCommandSignature` | Sibling layer | +| 52 | `SetDebugFlags` | Sibling layer | +| 55 | derived pipeline state | Sibling layer | +| 56, 57, 66, 67 | serialize / deserialize pipeline state | Sibling layer; the package's upscaler calls 67 as `DeserializeComputePipelineStateX` (console desc, `IID_ID3D12PipelineState`) — Package | +| 61 | `CreateSamplerX` | Sibling layer | +| 62 | `CreateComputePipelineState` with two extra args: `(desc, NULL, NULL, riid, ppv)`; the PC interface presents `CreateStateObject` at this slot | **Confirmed here**: Package ([d3d12_vulkan.md](d3d12_vulkan.md) §7) + sibling layer | +| 73 | `CreateCommandListX` | Sibling layer | +| 74, 75 | register / unregister page pool | Sibling layer | +| 76 | `CreateCommittedResource`, same signature family as PC slot 27 | **Confirmed here**: Package ([d3d12_vulkan.md](d3d12_vulkan.md) §7) + sibling layer | +| 78–81 | frame pacing: `SetFrameIntervalX`, `ScheduleFrameEventX`, `WaitFrameEventX`, `GetFrameStatisticsX` | Sibling layer | +| 86 | `CreatePipelineStateX` | Sibling layer | + +The slot-76 console resource descriptor is **larger than 52 bytes** (sibling layer); the package's +upscaler DLL writes a 3 at offset +52 (Package). The `Layout` field sits at +44; value `0x101` +denotes a 2D texture ([d3d12_vulkan.md](d3d12_vulkan.md) §7; a sibling layer measured the same on +retail titles). + +### 1.1 Two runtime layouts + +Two console runtime layouts exist: an older game-OS layout and a newer one in which the queue and +list slots shift **+2** (sibling layer). Detection rule (sibling layer): if a fence object is +passed to queue slot 16/17, the layout is newer — on the older layout those slots are +`GetTimestampFrequency`/`GetClockCalibration`. Which layout this package's titles were built +against is **unverified here**. + +## 2. Descriptor heap + +| Slot | Fact | Evidence | +|---:|---|---| +| 9, 10 | `GetCPUDescriptorHandleForHeapStart` / `GetGPUDescriptorHandleForHeapStart` return the 8-byte handle in `rax` on console; the PC convention is a hidden out-pointer | **Confirmed here**: Package + sibling layer | + +Descriptor contents (sibling layer): CBV/SRV/UAV heaps use **32-byte slots** in unified memory — a +T# is 8 dwords, a V# 4 dwords, inside the 32-byte slot; sampler heaps use **16-byte slots**. The +CPU handle, GPU handle and the address in title memory are the same value. + +## 3. Resource + +| Slot | Fact | Evidence | +|---:|---|---| +| 11 | `GetGPUVirtualAddress` returns the title-memory address | Sibling layer; consistent with the package measurement that a CPU pointer from list slot 148 is passed unchanged as a root SRV GPU address ([d3d12_command_objects.md](d3d12_command_objects.md) §3.3a) | + +## 4. Command queue + +Measured queue slots (sibling layer); the queue follows the two-layout rule of §1.1: + +| Method | Older layout | Newer layout | +|---|---:|---:| +| `Signal` | 14 | 16 | +| `Wait` | 15 | 17 | +| `GetTimestampFrequency` | 16 | 18 | +| `GetClockCalibration` | 17 | — (shifted) | +| `GetDesc` | 18 | — (shifted) | +| `SignalX` | 23 | 25 | +| `PresentX` | 30 | 32 | + +Console-only queue methods the layer does not model should return `S_OK` and log the call: +title frame pacing flows through some of them (sibling layer). + +## 5. Command list object + +Measured by a sibling layer with a fake list — a 600-slot vtable of logging thunks — that let the +console SDK's inline writers record into the object (sibling layer; the package's BVH builder and +upscaler independently measured `+0x18`, `+0x28`, `+0x30`, `+0x140`, `+0x141`, `+0x344` and +`+0x544` — Package, [d3d12_command_objects.md](d3d12_command_objects.md) §§3.4–3.5a). + +### 5.1 Object fields + +| Offset | Field | Evidence | +|---:|---|---| +| +0x00 | vtable pointer | Package + sibling layer | +| +0x18 | inline write pointer | Package + sibling layer | +| +0x28 | dispatch-record limit | Package + sibling layer | +| +0x30 | buffer end | Package + sibling layer | +| +0x140 | dirty flag byte, set when record header bits 31:30 are 0 | Package + sibling layer | +| +0x141 | pipeline flag byte, taken from bit 20 of the pipeline's record word at +0x20 | Package + sibling layer | +| +0x143 | flag byte; read by titles, written only by the runtime | Package (read 31+1 sites, never written) + sibling layer | +| +0x344 + 4·i | header word of root parameter *i* | Package + sibling layer | +| +0x544 | current pipeline record, 16 bytes | Package + sibling layer | + +### 5.2 Inline record encodings + +The console SDK's inline writers emit a record only while the write pointer is below the buffer +end; on a full buffer they call the vtable method the record stands for (Package + sibling layer). + +| Record | Encoding | Evidence | +|---|---|---| +| Pipeline | 28 B: `[PSO ptr][D3D12Core ptr][8 B flags][4 B]` | Package + sibling layer | +| Root parameter *i* | header at +0x344+4·i = `0xC0000000 \| i<<10` + const-offset·4 (bits 9:2) + `(count-1)<<16` | Sibling layer; header table itself confirmed Package | +| Root descriptor | header + 64-bit address = 12 B | Package + sibling layer | +| Root constants | one constant = 8 B; *n* constants = 4+4·*n* B | Package + sibling layer | +| Descriptor table | header + one 32-bit word = the 32-bit GPU address of the first descriptor | Sibling layer | +| `Dispatch` | `0x4002C400` (or `(0x1000BA00 \| flag) << 2`) followed by x, y, z = 16 B | Package + sibling layer | +| Indirect dispatch | `0x4003CC00`, 20 B total | Package (five-word form with W `0x8020`/`0x20`) + sibling layer | +| `IASetPrimitiveTopology` | `0xC000B600 \| topology` | Sibling layer | + +### 5.3 Method slots + +| Slot | Method | Evidence | +|---:|---|---| +| 9 | `Close` | Sibling layer | +| 10 | `Reset` | Sibling layer | +| 12 | `DrawInstanced` | Sibling layer | +| 13 | `DrawIndexedInstanced` | Sibling layer | +| 14 | `Dispatch` | Package + sibling layer | +| 15 | `CopyBufferRegion` | Package + sibling layer | +| 16 | `CopyTextureRegion` | Sibling layer | +| 17 | `CopyResource` | Sibling layer | +| 19 | `ResolveSubresource` | Sibling layer | +| 20 | `IASetPrimitiveTopology` | Sibling layer | +| 25 | `SetPipelineState` | Package + sibling layer | +| 26 | `ResourceBarrier` | Package + sibling layer | +| 32 | `SetDescriptorHeaps` | Package + sibling layer | +| 33 | `SetComputeRootSignature` | Package + sibling layer | +| 37, 39 | `Set*RootConstant(s)` | Package + sibling layer | +| 41, 43, 45 | `Set*RootDescriptor*` / table | Package + sibling layer | +| 48 | `IASetVertexBuffers` | Sibling layer | +| 51 | `ClearDepthStencilView` | Sibling layer | +| 80 | `ExecuteIndirect` | Sibling layer (note: the package measured slot 80 as a console-only call, a `Dispatch`-with-extra-word shape; slot assignments past 61 differ between the two sources — unconfirmed) | +| 83 | `CopyTextureRegionX` (older layout) | Sibling layer; the package measured a `CopyTextureRegion`-shaped call at slot 85 — consistent with the newer layout (+2) | +| 108 | `ResolveSubresourceRegion` | Sibling layer | +| 139 | `Reset(allocator, pso)` → PC slot 10 | **Measured here**: retail 1.0.2.1 (Pipodi) — the title creates a list, `Close`s at slot 9, then calls 139 with `(allocator proxy, 0)` before recording; the proxy unwraps the allocator and forwards to PC `Reset` | +| 146 | enhanced `Barrier` | **Confirmed here**: Package (console slot 146 takes one `D3D12_BARRIER_GROUP`; PC equivalent is GCL7 slot 80) | +| 148 | `AllocateUploadMemory` `(size, alignment)`; the returned CPU pointer is the GPU address in unified memory | Package + sibling layer | + +Layout shift on the list tail (sibling layer): from `CopyTextureRegionX` on, methods sit two slots +later in the newer layout — newer→older pairs 85→83, 86→84, 87→85, 90→88, 91→89, 92→90, 95→93, +96→94. + +The shim hands out console-shaped command lists by default: `GetCommandList`-shaped queries build +the proxy with the console vtable above. `LEONIDA_D3D12_LISTS=pc` makes it hand out PC-shaped lists +instead, for guests compiled against the PC headers (the `tiny_frame` test fixture calls through PC +vtable indices; without the variable its `ClearRenderTargetView` at PC slot 48 lands on the +console's `IASetVertexBuffers` and `Close` never runs). The device, queue, heap and fence stay +console-shaped either way. + +### 5.4 DMA command list + +| Slot | Method | Evidence | +|---:|---|---| +| 9 | `Close` | Sibling layer | +| 10 | `Reset` | Sibling layer | +| 11 | `CopyBufferRegion` | Sibling layer | +| 12 | `CopyTextureRegion` | Sibling layer | +| 13 | `CopyResource` | Sibling layer | + +## 6. Root arguments + +Sibling-layer measurements on retail titles: + +- **Compute.** The root arguments are a packed argument array in title memory; `io[0:1]` of the + dispatch record carries its address. +- **Graphics.** VS and PS receive root arguments in user SGPRs `s8..s31` — `s0..s7` are + driver-reserved; `s[4:5]` of a VS holds the fetch shader — 24 user SGPRs in total. Arguments + past those go through a table whose address is in `s[0:1]`. +- **Descriptor tables** take 4 bytes in the packed array: the record is the parameter header plus + one 32-bit word, the 32-bit GPU address of the first descriptor. +- **Root CBV.** The shader builds its own V#; a measured example sets `DST_SEL xyzw` plus the + format word from `s11`. + +## 7. Resource barriers (list slot 26) + +Sibling layer: console aliasing barriers behave as "any resource" barriers — both resource +pointers are null — where the PC API only allows those between placed or reserved resources. +Console-only state bits must be dropped before forwarding, or `Close` fails `E_INVALIDARG`. + +## 8. Unified memory + +Titles expect graphics memory where the CPU address equals the GPU address (sibling layer; +consistent with the package's slot-148 measurement in §3). + +- The sibling layer backs this with a fully-committed sub-4 GiB region at a 4 GiB-aligned virtual + address, opened via `ID3D12Device3::OpenExistingHeapFromAddress`. Measured limits: a partial + commit is rejected; a full 4 GiB is rejected; 4095 MiB works. +- For reservations above 4 GiB the measured technique is: reserve with `VirtualAlloc2` + `MEM_RESERVE_PLACEHOLDER`, split chunks with `VirtualFree` `MEM_PRESERVE_PLACEHOLDER`, back each + chunk with a `SEC_COMMIT` section mapped via `MapViewOfFile3` `MEM_REPLACE_PLACEHOLDER`. Each + chunk opens as its own heap with GPU/CPU coherence at the title's address. `SEC_RESERVE` + sections are refused even when fully committed. +- Buffers in unified memory are placed resources at 64 KiB alignment. A buffer at a + non-64 KiB-aligned console address is placed from the 64 KiB boundary below it and the copy + paths add the delta. +- `Map` of a unified-memory resource returns its console address. +- GPU-owned textures (resources with RT/DS/UAV flags) go into "arenas" — default heaps standing + for ranges of title addresses — because titles alias several textures at one address. + +## 9. `PresentX` + +Sibling layer: one frame is presented per console queue method call (`PresentX`, §4). The +presented back buffer is detected by tracking render-target binds (RTV creation and +`OMSetRenderTargets`) and `ExecuteCommandLists`. + +## 10. Shader-interface facts + +Measured on real console shaders by a sibling layer; where the claims overlap this repository's +translator docs they are mostly confirmed here. + +- An FSSM stage descriptor at +0x110 looks like `RSRC2`: `USER_SGPR` sits in bits 5:1 (e.g. + `0x18` → 12 SGPRs). A PS header carries an export-variant patch table from about +0x25C. +- User SGPRs (a compute example with 14 per `RSRC2`): `s4` = descriptor table 0, `s5` = table 1, + `s[6:7]` and `s[8:9]` = root CBVs; `s14`/`s15` = thread-group id x/y. +- Mesh-shader interface: `s3[27:24]` = wave index in the group, `v5` = group·128 + thread, + `s16..s24` = user data. +- Console GS runs on-chip: the ES writes vertices to LDS and `s_setpc`s to the GS. The GS writes + vertices to LDS at 64 B per vertex, base = `s2 + ([s8 + 0xB8] << 8)`, and uses `s_sendmsg` + emit/cut/done. No copy shader is present in the pack. +- `IASetPrimitiveTopology` value 17 is rectangle lists, drawn as two triangles on PC. +- Derivatives: console code computes cross-quad derivatives manually (DPP `quad_perm`, + `ds_swizzle`) and reads helper lanes. On PC, reads across quads need quad-aware lane reads: + `WaveReadLaneAt` leaves helper lanes out before SM 6.7, and enabling + `WaveOpsIncludeHelperLanes` caused a device hang in the sibling layer — whole-wave ballots then + never let helper lanes exit. +- A pixel shader doing `v_readfirstlane` after `s_wqm` can read a helper lane's value; the read + must take the value with a quad read inside its own quad plus a wave read from a live lane of + that quad. +- Memory model: a shared "mem" buffer used for flat accesses must be coherent + (`globallycoherent` on D3D12). Bottom-up BVH builds with atomics produce wrong child pointers + otherwise; console code relies on GLC/cache-invalidation semantics. +- ISG1 inputs a VS never reads get no fetch-shader VGPRs. + +## 11. Unverified here + +The sibling-layer measurements above were made on retail Series titles and that project's own +host runtime, not on this package or this layer. Still to be measured on this package: + +- **which runtime layout this title uses** — the older/newer detection rule of §1.1 needs a queue + call trace; +- **draw-record encodings for graphics** — only compute dispatches and copies were measured; the + graphics draw records and their sizes are unknown; +- the `PresentX` signature and plane struct (no signature is recovered anywhere; + [d3d12_command_objects.md](d3d12_command_objects.md) §4); +- queue/fence/allocator slots and the device creation slots 8/9/12/36 for the layout this title + uses ([d3d12_command_objects.md](d3d12_command_objects.md) §5.3); +- the exact newer→older slot pairs on the command-list tail beyond the measured set. diff --git a/docs/design.md b/docs/design.md index a4fbb4404a..2060dfdf78 100644 --- a/docs/design.md +++ b/docs/design.md @@ -73,6 +73,9 @@ This writes `reports/exe/` (JSON plus a readable summary). Check it in this orde `VERIFY` note of the runtime and the docs, with file and line. Notes in a shim whose class the exe calls are marked **called** and come first: those are the ones its first boot reaches, such as the `XStoreGameLicense` sizes. +7. **CPU instructions.** `python -I tools/cpu_feature_scan.py ` lists the instructions a desktop CPU may lack + (AMD-only, newer-Intel-only, privileged), with counts split by `.pdata` range. The retail executable has a few + AMD-only and CLWB sites that raise `#UD` on Intel hosts ([cpu_features.md](cpu_features.md)). Then `runtime\build\gta6rt.exe --dry-run ` maps the image and binds every import to the shim table without running any game code. It reports what it couldn't bind. @@ -181,7 +184,9 @@ Full-scan indexes are also saved to `%LOCALAPPDATA%\RpfPreview\Indexes`, so the `CreateCommittedResource` with the Xbox `0x101`/`0x1` layout word replaced by the PC layout. Slots 9/10 are `ID3D12DescriptorHeap` methods, not device methods. The PC heap getters take a hidden return pointer (RDX), while Xbox expects the 8-byte handle in RAX, so slot 14 wraps the heap and slots 9/10 convert it. The heap holds - a reference to the device proxy and its `GetDevice` returns that same proxy. Queues, fences, command lists and + a reference to the device proxy and its `GetDevice` returns that same proxy. The retail executable calls the + struct-returning device methods with the C ABI, return buffer first: `GetCustomHeapProperties` (slot 26) is + measured as `rcx` = buffer, `rdx` = device. Slots 25 and 26 take that form, and still take the PC one. Queues, fences, command lists and `PresentX` extensions remain unimplemented. - PSO metadata is a new variant (`PSIN`, `LSCH` schema, `LENM`, `LSNS`, `LGID`, `LRSC`, `CHKS`, little-endian). CodeWalker's parser reads the container but not the new schema; dump it once the exe gives the field names. @@ -394,7 +399,7 @@ How the generated SPIR-V expects the runtime to work: | Full-corpus pipeline build | `vk_pipeline_check pipeline_cache.bin --jobs 4` on an RTX 4060 Ti (NVIDIA 595 driver): **all 26,503 shaders become real pipelines, 0 failures** (cs 2,689, ps 12,101, ms 9,282, vs 2,236, gs 195; graphics stages with generated stub partners). Compile time 40,784 s of CPU (2.84 h wall on 4 threads): cs 23,633 s (mean 8.8 s; the ray-tracing ScreenProbes/RTShadowTrace shaders take 2-19 min each), ps 11,481 s, ms 5,395 s, vs 275 s. The resulting `VkPipelineCache` is 3.81 GB; seeding a run with it makes those pipelines instant, which is what a fast first boot needs. The cache is per driver and GPU, and a shader whose SPIR-V changes compiles again (the checker resumes from the file). Neither register storage (one variable per register) nor smaller SPIR-V cut NVIDIA compile time: the big ray-tracing shaders are expensive as such, so the runtime should compile them in the background rather than block on them. | | `v_cndmask_b32` source modifiers | `v_cndmask_b32` only moves bits, so a VOP3 `abs` on `src0`/`src1` clears bit 31 and `neg` flips it (`abs` first) as plain bit moves (`OpBitwiseAnd 0x7FFFFFFF`, then `OpBitwiseXor 0x80000000`, `Gen.src_u_sign_mods`), never `FAbs`/`OpFNegate`: a signalling NaN stays signalling and a denormal isn't flushed. Until 2026-11-23 the sources went through `Gen.modify`, and the mini interpreter quieted them (`-v1` of `0x7F800001` gave `0xFFC00001`, not `0xFF800001`). **Not measured on hardware for this instruction**: the rule follows the same VOP3 input modifiers measured as sign-bit moves on `v_cmp_class_f32` (gfx1036, all four IEEE/denorm modes, row "Floating-point class compare" above), and LLVM's AMDGPU backend moves `fneg`/`fabs` through a select into `v_cndmask_b32_e64`'s source modifiers (`AMDGPUTargetLowering::foldFreeOpFromSelect`), which is only exact if they are sign-bit moves. Checked on the CPU and with `spirv-val` by `tests/semantic/test_cndmask_sign_mods.py` (15 words including signalling/quiet NaNs, denormals, zeros and infinities x `v`, `-v`, `\|v\|`, `-\|v\|` x both operands). | | Wave-uniform branches | VCC and EXEC are wave-wide registers, but one invocation holds only its own lane's bit. `s_cbranch_vccz/vccnz/execz/execnz` therefore reduce the condition across the subgroup (`OpGroupNonUniformAny`), so the whole wave takes the branch together, as on hardware. Before this, each lane decided alone. A lane could skip scalar instructions that the hardware wave executes (its SGPRs went stale for later code), and cross-lane ops or barriers inside the block saw a split wave. `v_cmp`/`v_cmp_class`/64-bit compares now write 0 for inactive lanes (hardware VOPC behaviour), so the reduction sees the true mask. GPU-checked with `runtime/test/shaders/ps_uniform_branch.asm`: lanes whose own VCC bit is 0 run the block's scalar add when their wave has any set bit. `s_cbranch_scc0/1` stay per lane; SCC is uniform as long as the SGPRs feeding it are. | -| Compute shaders | FSSM header word **0x138 = `COMPUTE_PGM_RSRC2`**: USER_SGPR [5:1], TGID_X/Y/Z_EN [9:7], TG_SIZE_EN [10], TIDIG_COMP_CNT [12:11], LDS_SIZE [23:15] in 512-byte units. Words **0x13C/0x140/0x144 = thread-group size**. Counted over all 2,689 CS listings of 1.0.2.1 by the SGPRs each reads before writing (operand roles from `shader_meta._split_operands`, over the code `translate()` keeps; in wave64 code a lane mask printed as one SGPR covers the pair; an earlier check gave 2,281 exact): 2,540 read nothing past the user SGPRs and enabled TGIDs (2,193 up to the last of them, 342 fewer, 5 none), and the other 149 overshoot only through loop-carried registers in the straight-line check: every extra read follows a branch, and the register is written later in program order. Followed through the CFG (written on every path before the read), 22 still overshoot; each extra register is written on some other path (only loop-carried ones in 15), so these are values undefined on some path, not a missing input. Read raw, 268 overshoot: the other 119 are listings with embedded data words, decoded as instructions. 0x110, which looked similar, doesn't match. Layout: s0..user−1 = user data (push constants), then the enabled workgroup IDs (`WorkgroupId`), and v0/v1/v2 = thread ID x/y/z (`LocalInvocationId`, separate VGPRs on GFX10). Example: the 1,013 shaders with RSRC2 `0x998` have 12 user SGPRs, group ID x/y in s12/s13, and compute x = s12·32 + v0. Shaders with TG_SIZE_EN are rejected for now. GPU-checked with `runtime/test/shaders/cs_lds.asm` through `runtime/test/vk_compute_test.cpp`: 4 groups × 64 threads, LDS exchange between the two waves of a group behind `s_barrier`, store through a V# into the device-address heap, 0 mismatches. | +| Compute shaders | FSSM header word **0x138 = `COMPUTE_PGM_RSRC2`**: USER_SGPR [5:1], TGID_X/Y/Z_EN [9:7], TG_SIZE_EN [10], TIDIG_COMP_CNT [12:11], LDS_SIZE [23:15] in 512-byte units. Words **0x13C/0x140/0x144 = thread-group size**. Counted over all 2,689 CS listings of 1.0.2.1 by the SGPRs each reads before writing (operand roles from `shader_meta._split_operands`, over the code `translate()` keeps; in wave64 code a lane mask printed as one SGPR covers the pair; an earlier check gave 2,281 exact): 2,540 read nothing past the user SGPRs and enabled TGIDs (2,193 up to the last of them, 342 fewer, 5 none), and the other 149 overshoot only through loop-carried registers in the straight-line check: every extra read follows a branch, and the register is written later in program order. Followed through the CFG (written on every path before the read), 22 still overshoot; each extra register is written on some other path (only loop-carried ones in 15), so these are values undefined on some path, not a missing input. Read raw, 268 overshoot: the other 119 are listings with embedded data words, decoded as instructions. 0x110, which looked similar, doesn't match. Layout: s0..user−1 = user data (push constants), then the enabled workgroup IDs (`WorkgroupId`), and v0/v1/v2 = thread ID x/y/z (`LocalInvocationId`, separate VGPRs on GFX10). Example: the 1,013 shaders with RSRC2 `0x998` have 12 user SGPRs, group ID x/y in s12/s13, and compute x = s12·32 + v0. With TG_SIZE_EN (none of the 2,689; 91 compute programs of the pipeline library, [shader_library.md](shader_library.md)) the next SGPR is the thread-group word, which the prologue writes: the number of waves in the group in bits [5:0] and this wave's index in it in bits [11:6], the wave index again in bits [24:20] and bit 31 set in the group's first wave (measured on gfx1036 through `tools/hw_oracle`, #6446: wave32 x 128 threads gives `80000004 00100044 00200084 003000c4`; one library program reads [24:20]; not measured on gfx1013) (Mesa `ac_nir_lower_intrinsics_to_args.c`, GFX6-10: `load_num_subgroups` and `load_subgroup_id` read those fields, and a wave64 compute shader's local invocation index is `mbcnt(~0, tg_size & 0xfc0)`; the library programs read it as `s_and_b32 sN, sTG, 0xfc0`, most of them then `v_mbcnt_lo_u32_b32`). Thread i is in wave i / W, as for `s_get_waveid_in_workgroup`. CPU-checked by `tests/semantic/test_cs_tg_size.py`, including the gfx1036 words. GPU-checked with `runtime/test/shaders/cs_lds.asm` through `runtime/test/vk_compute_test.cpp`: 4 groups × 64 threads, LDS exchange between the two waves of a group behind `s_barrier`, store through a V# into the device-address heap, 0 mismatches. | | Signed-byte dot products | `v_dot4_i32_i8 D, S0, S1, S2` (VOP3P) is S2 plus the sum of the four products of the sign-extended bytes of S0 and S1, modulo 2^32; `v_dot4c_i32_i8 D, S0, S1` (VOP2) adds the same sum to D. Emitted as four pairs of `OpBitFieldSExtract`, `OpIMul` and `OpIAdd`. **Confirmed on RDNA2 hardware** (gfx1036, raw kernels through `tools/hw_oracle`): 10 operand sets, both instructions and both source orders of the accumulating one, with sign-mixed bytes and sums that wrap; the measured words are the table in `tests/semantic/test_alu_dot4_i8.py`. `clamp` and `op_sel`/`op_sel_hi` are translated and checked against the same `gfx1036` hardware table: `clamp` saturates `v_dot4_i32_i8` to signed 32-bit `[-2^31, 2^31-1]` (both overflowing sets), and `op_sel`/`op_sel_hi` pick the 16-bit half of S0/S1 for byte pairs 0..1 and 2..3 (e.g. `op_sel` 2 / `op_sel_hi` 5 exchanges the 16-bit halves of S1, matching all 5 measured sets — the form of the 89 words `llvm-mc` does not decode, [fspx.md](fspx.md)); non-default S2 half selection stays refused. `neg_lo`/`neg_hi`, which `llvm-mc` accepts on `v_dot4_i32_i8` only, are not ignored (`neg_lo` flips bit 15 and `neg_hi` bit 31 of S0 or S1, and on S2 `neg_hi` clears bit 31 before `neg_lo` flips it; 5 sets under 8 forms, 45 words): any set bit stays Unsupported, while an all-zero field is the plain instruction. Counts: the 29 FSPX programs use the pair 27,271 times (`v_dot4c_i32_i8` 25,813, `v_dot4_i32_i8` 1,458), all in 13 programs; none of the game's own 26,503 shaders has either encoding (0 of the 12,791 words `llvm-mc` cannot decode there with gfx1013). | | Workgroup barriers | `s_barrier` (cs/ms) is one `OpControlBarrier` (workgroup scope, workgroup memory). On RDNA every `s_barrier` counts against the same workgroup barrier and a wave that has ended no longer counts, while Vulkan requires a barrier to be reached by every invocation in uniform control flow. Under `--wave64-emulate` the round loop keeps a single barrier at the top level, so this holds. **Native wave32 compute shaders run in barrier rounds** when an `s_barrier` sits anywhere but a top-level block of the structured tree (one every invocation runs): under a guard, in a loop, or in the dispatch loop (`needs_barrier_rounds`, `bar_scheduler`). That is the emulated loop without its cross-lane part: `s_barrier` ends a segment, each invocation runs its blocks until its next `s_barrier` or the end, then the whole workgroup meets at one `OpControlBarrier` (the same workgroup/acquire-release/workgroup-memory semantics) at the end of the round. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3) ends the loop. A wave that is done no longer holds the others, and a per-round count of the invocations not done (three `Workgroup` words, by round mod 3, or a borrowed LDS word with a large LDS: "Barrier-round count in LDS (SHADER-579)") ends the loop. Cross-lane operations stay subgroup operations, as in the dispatch loop, since a wave's lanes run the same segment. A barrier in a top-level block keeps the single `OpControlBarrier` in place. In the 1.0.2.1 corpus 43 of the 55 wave32 cs shaders with `s_barrier` have one nested (SHADER-91's count), so those 43 now run in rounds. Why: an Intel GPU does not survive the nested form. `cs_barrier_divergent.asm` (two barrier sites in different branches), `cs_barrier_early_end.asm` (the other waves end without a barrier) and `cs_barrier_loop.asm` (a barrier in a loop whose trip count differs per wave) each lose the device (`vkQueueWaitIdle` → `VK_ERROR_DEVICE_LOST`) on an Intel Arrow Lake Xe-LPG iGPU (Windows 32.0.101.8132), and `cs_barrier_divergent` hangs or writes nothing on a UHD 770 (101.6129, #634). With barrier rounds all three pass there and on an RTX 5070 Ti Laptop (617.42). NVIDIA passed them before too (RTX 4070 Ti on 610.88 and 621.24, RTX 5090 on Linux 595.99, RTX 5070 Ti). **Still not proven on the native wave64 path** (wave64 cs and every ms, run natively only on AMD's 64-wide subgroups): there the barrier stays where `s_barrier` is, inside a selection or loop construct in every ms and most wave64 cs shaders of the corpus. Branches are scalar, so whole waves take the same path, and RDNA's own barrier counts the way the shader expects. | | Barrier-round count in LDS (SHADER-579) | Barrier rounds (see "Workgroup barriers") count the invocations not done in `%x_buf`, three `Workgroup` dwords (#930). On a full 32 KiB LDS that made 32,780 B, 12 bytes over the 32,768 B `maxComputeSharedMemorySize` of the AMD Windows (RX 9070 XT) and Intel (UHD 770) drivers, so the runtime refused those pipelines (2 native wave32 cs in towade's 1.0.2.1 corpus, [finding](https://github.com/ItsNotRexed/Leonida/pull/1882#issuecomment-7084298032)). Rule (`bar_counts_in_lds`): when the shader uses its LDS and the LDS array plus 12 bytes is over 16,384 B (the Vulkan minimum limit, so in practice an array of 16, 32 or 64 KiB), there is no `%x_buf`. The count borrows LDS word 0 at the end of each round (`bar_scheduler_tail`): after the round's barrier every invocation is done or waits at `s_barrier`, so no shader code runs; invocation 0 saves the word in a Function variable and clears it, barrier, every invocation not done adds 1 atomically, barrier, all read the count, barrier, invocation 0 stores the saved word back, barrier. The shader sees its LDS bit for bit as before, and the four extra barriers sit where the whole workgroup already waits, so `s_barrier`'s semantics are unchanged; the cost is four more `OpControlBarrier`s per round in those shaders only. Below the threshold `%x_buf` stays (12 bytes fit every device) with one barrier per round; a shader that never touches its LDS also keeps it (no array to borrow from, 12 B in all). A 32 KiB LDS is now exactly 32,768 B and a 64 KiB one 65,536 B (before: 65,548 B, refused or shrunk to its allocation). Not chosen: putting the count in LDS the shader never touches (unprovable with dynamic addresses), or deciding per device (the translator runs offline). Pinned by `tests/semantic/test_cs_barrier_counts_lds.py` (Workgroup bytes from the emitted SPIR-V and `lds_bytes` for 32 KiB, 64 KiB and small LDS, under a 32 KiB `--max-shared-memory`; ring shifts across 10 barriers that read word 0 and an early-ending wave in the workgroup interpreter, whose LDS starts as 0xDEADBEEF, in both wave orders). Confirmed by those CPU tests only; GPU runs on the 32 KiB devices are pending. | diff --git a/docs/directstorage.md b/docs/directstorage.md new file mode 100644 index 0000000000..dc2987a559 --- /dev/null +++ b/docs/directstorage.md @@ -0,0 +1,197 @@ +# DirectStorage + +The console title reads its streamed data through Xbox DirectStorage: `DStorageGetFactory` hands out a factory, the +factory opens files and creates queues, and a queue reads file or memory ranges into memory and reports completion +through status arrays, `ID3D12Fence` signals and events. `runtime/shims/dstorage.cpp` serves that API on the PC: +files open through the runtime's `GAME:` mapping and write overlay, and a worker thread per queue does the reads +and inflates zlib requests. +This page records which DLL and ABI the console title is expected to use, how sure that is, and what the shim does. + +## Which DLL and which ABI: the evidence + +The game executable is not in the package available here, so its import table is unmeasured +([runtime_imports.md](runtime_imports.md)). What is known: + +| Evidence | Source | What it says | +|---|---|---| +| None of the 16 shipped DLLs imports DirectStorage | [runtime_imports.md](runtime_imports.md) (6 Xbox-specific imports, all `xmem`/`d3d12_xs`), [textures.md](textures.md) "The shipped binaries" (no `DStorage` import, export or string) | DirectStorage, if used, is called by the executable itself | +| The texture chunks carry the `DSTORAGE_BCPACK_MODE` values 1-7 and mix zlib and BCPack chunks | [textures.md](textures.md) "What BCPack is" | The data is laid out for console DirectStorage's decompression (DEFLATE, then BCPack, then swizzle) | +| A sibling console layer's export inventory names `dstorage_xs.dll` as console DirectStorage | [d3d12_vulkan.md §7](d3d12_vulkan.md#7-prior-art-and-measured-xbox-abi) | The console module name, measured elsewhere, not here | +| A retail title run by a sibling layer has `xcrdapi` in its console-only library set | [d3d12_vulkan.md §7](d3d12_vulkan.md#7-prior-art-and-measured-xbox-abi) | Only the name. Nothing in this repository says what `xcrdapi.dll` exports | +| The GDK reference: `DStorageGetFactory` is in header `dstorage_xs.h`, library `dstorage_xs.lib`; the interface pages give library `dstorage.lib`; all say "Xbox Series consoles" | [GDK DStorage reference](https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/dstorage/dstorage_members) | The console API has its own names (`IDStorageFactoryX`, `IDStorageQueueX`, `IDStorageFileX`, `IDStorageStatusArrayX`) and structures that differ from the PC API | +| `registry.cpp` classified `dstorage.dll`/`dstorage_xs.dll` `DStorageGetFactory` as returning an HRESULT | `runtime/shims/registry.cpp` | It was an unimplemented import; `xcrdapi.dll` was not named | + +**Chosen ABI: the console one** (the GDK's `IDStorageFactoryX2`/`IDStorageQueueX2`/`IDStorageFileX`/ +`IDStorageStatusArrayX` and its `DSTORAGE_REQUEST`), served as `DStorageGetFactory` under all three names: + +| Module | Confidence | Why | +|---|---|---| +| `dstorage_xs.dll` | medium | The reference's `dstorage_xs.lib` and the sibling inventory agree; not measured in this title | +| `xcrdapi.dll` | low | Only a name in a library list. Owning the module also means a title's `LoadLibrary("xcrdapi.dll")` gets the shims' pseudo-handle, and `GetProcAddress` for any other name returns `NULL` (logged). Static imports of other `xcrdapi` names are unchanged | +| `dstorage.dll` | low | The interface pages name `dstorage.lib`. Every caller of `gta6rt`'s import table is a console build, so this name serves the console ABI too, not the PC one | + +The PC DirectStorage ABI (`dstorage.h`: `IDStorageFactory` with `DSTORAGE_REQUEST` source and destination unions, +`ID3D12Resource` destinations) is **not served**. A caller that asks for a PC interface id gets `E_NOINTERFACE` and a +log line, never an object of the wrong shape. The one exception is `IDStorageStatusArray`, whose two methods are the +console interface's in the same order (console D3D12 binaries reuse the PC SDK's ids), so a status array accepts its +id. + +Owning a module has a run-time side: `LoadLibrary` of `xcrdapi.dll` or `dstorage.dll` (or `dstorage_xs.dll`) gets +the shims' pseudo-handle even when the package ships its own copy of that DLL, so the shim shadows a packaged copy +at run time (`library_loader.cpp` asks the registry before the bundled loader). None of the 16 shipped DLLs is one +of these, so nothing is shadowed today. + +### What is not public, and the choice made + +| Unknown | Choice | Confidence | Where to change it | +|---|---|---|---| +| Vtable order of the console interfaces (the reference lists methods alphabetically) | The PC header's order for the methods both APIs have; console-only methods where the overview lists them: factory `CreateQueue, OpenFile, CreateStatusArray, SetCpuAffinity, SetDebugFlags, SetStagingBufferSize`, then `GetStats` (X1), `CreateQueue1` (X2); queue `EnqueueRequest, EnqueueStatus, EnqueueSignal, Submit, CancelRequestsWithTag, Close, GetErrorEvent, RetrieveErrorRecord, Query`, then `EnqueueSetEvent` (X1), `Query1` (X2); status array `IsComplete, GetHResult`; file `Close, GetHandle` | queue, status array: medium; file: medium; factory: low (the `SetCpuAffinity` slot is a guess) | `runtime/shims/dstorage_xs_abi.h`, one declaration per interface | +| Interface ids of the X interfaces | A creating call (`DStorageGetFactory`, `CreateQueue*`, `OpenFile`, `CreateStatusArray`) accepts an id it has not seen for the kind of object it hands out and logs it once (`[rt] dstorage: ... asked for {...}: serving the ... interface`), so the first boot records them. It refuses an id seen for another kind, a PC DirectStorage id, and the system COM interfaces (the `{xxxxxxxx-0000-0000-C000-000000000046}` range with `IMarshal`, `IClientSecurity`, ..., and `IAgileObject`, `INoMarshal`, `IInspectable` and a few more). `QueryInterface` follows [d3d12_vulkan.md](d3d12_vulkan.md)'s rule (an unknown id is `E_NOINTERFACE`, logged): it accepts only `IUnknown`, the declared `IDStorageStatusArray` id for a status array, and the ids a creating call accepted for that kind of object | n/a (a policy, not a fact) | `IidPolicy` in `runtime/shims/dstorage.cpp` | +| `DSTORAGE_MIN_QUEUE_CAPACITY`, `DSTORAGE_MAX_QUEUE_CAPACITY`, `DSTORAGE_REQUEST_MAX_NAME` | The PC header's values: `0x80`, `0x2000`, 64 | medium | `dstorage_xs_abi.h` | +| `E_DSTORAGE_*` values | The PC `dstorageerr.h` values (`FACILITY_GAME`, `0x8924xxxx`). That header also defines the console-only failures (zlib, BCPack, swizzle, XVD), so the space is shared. `E_DSTORAGE_DECOMPRESSION_ERROR` (`0x89240030`) is on the public constants page; `E_DSTORAGE_ZLIB_BAD_HEADER`, `_ZLIB_BAD_DATA` and `_ZLIB_PARITY_FAIL` (`0x89240031`-`33`) have no public description, and their names and values come from the header-generated bindings of the `direct-storage` crate (Sources). Which failure the console reports with each zlib code is inferred from the names | medium-high (values); medium (zlib codes' meaning) | `dstorage_xs_abi.h` | +| Struct layouts | The compiler's x64 layout of the reference's declarations, pinned with `static_assert` (`DSTORAGE_REQUEST` 72 bytes, `DSTORAGE_QUEUE_DESC` 24, `DSTORAGE_QUEUE_DESC1` 32); `DSTORAGE_REQUEST_OPTIONS` is decoded from `AsUINT64` by explicit bit positions (zlib bit 0, BCPack 1-4, swizzle 5-20, destination pages 21, source type 22, source pages 23, reserved 24-63) | high for member order and types, medium for the bit allocation (MSVC allocates bit-fields from bit 0 up) | `dstorage_xs_abi.h` | + +The first boot with the executable settles most of this: the dry-run report shows which module it imports +`DStorageGetFactory` from, and the log lines give the interface ids. + +## What the shim does + +- **Factory**: one object for the process, never freed (its reference count does not drop below one). + `SetDebugFlags` and `SetCpuAffinity` are stored only (a console core mask means nothing on the host). + `SetStagingBufferSize` accepts 0, 16, 20, 24, 28 and 32 MiB, fails with `E_DSTORAGE_INVALID_STAGING_BUFFER_SIZE` + otherwise and with `E_DSTORAGE_STAGING_BUFFER_LOCKED` while a queue or file exists; there is no staging buffer. + `GetStats` reports the counts the shim keeps (queues per priority, requests, bytes, files, errors, zlib + inflates: `TotalDecompressionRequestCount` grows when a zlib request's inflate starts, which is after its checks + passed and its source was read, `PendingDecompressionRequestCount` is the inflates running, and + `DecompressionErrors` the streams that failed). As + `DSTORAGE_PRIORITY_STATS` defines them, `TotalRequestCount` and the byte totals grow when a request is submitted + (not when it is enqueued), and `PendingRequestCount` counts the requests the worker is processing; status and fence + entries are counted when they are enqueued. A bad + argument (a null pointer, an invalid queue desc or staging size) is logged once per method and kind, so a wrong + vtable guess shows up in the log as arguments that make no sense for the method. +- **Files**: `OpenFile` goes through the registry's `kernel32.dll!CreateFileW`, the shim in `file_system.cpp`, so a + `GAME:` path reads the overlay copy first, then the package, and a path that climbs out is refused (a host path is + passed through). Read access, `FILE_SHARE_READ`, as the overview says; a failed open returns the Win32 error as an + HRESULT. `GetHandle` returns a handle of its own (`ReOpenFile`, read access, `FILE_SHARE_READ`) that the caller + closes; it has its own file position, which the shim's reads do not move. `Close` waits for the submitted requests + that read the file; a request processed after it fails with `E_DSTORAGE_FILE_NOT_OPEN`. A request holds a reference + on its file, so the last `Release` cannot close a file a request still reads. +- **Queues**: capacity `0x80`..`0x2000`, priority `LOW`..`REALTIME`, a memory-sourced queue must be `REALTIME` + (`E_DSTORAGE_INVALID_QUEUE_CAPACITY`, `_INVALID_QUEUE_PRIORITY`, `_INVALID_MEMORY_QUEUE_PRIORITY`). A queue + holds `capacity - 1` entries; `Query` reports the empty slots and the entries left before the automatic submit, + which happens when the entries enqueued since the last submit reach half the capacity (unless + `DSTORAGE_QUEUE_OPTIONS::AutoSubmitDisabled`). An enqueue into a full queue waits for space, as the reference + says; with auto-submit disabled only a `Submit` from another thread frees it. One worker thread per queue runs + the submitted entries in order, so every notification follows all the entries before it. +- **Requests**: copied at enqueue. A file request reads `SourceSize` bytes at `FileOffset` into `Destination`; a + memory request copies `Source` to `Destination` (`memmove`, so an overlapping pair is safe); a zlib request + inflates those `SourceSize` bytes into `Destination` (below). Checked in this order when the worker reaches the + request: + 1. cancelled: a success, whatever else is wrong with it; + 2. found at enqueue: a null request pointer (`E_INVALIDARG`) or a file object the shim did not make + (`E_DSTORAGE_INVALID_FILE_HANDLE`); + 3. reserved option bits (`E_DSTORAGE_RESERVED_FIELDS`), then the source type against the queue's + (`E_DSTORAGE_INVALID_SOURCE_TYPE`); + 4. BCPack mode above 7, swizzle mode above 4 (`_INVALID_BCPACK_MODE`, `_INVALID_SWIZZLE_MODE`), then BCPack or + swizzle, with or without zlib, then physical pages (`E_NOTIMPL`, logged once: later PRs); + 5. an `IntermediateSize` (`_INVALID_INTERMEDIATE_SIZE`: it is the size between the inflate and the BCPack decode, + so only a zlib + BCPack request has one), a `DestinationSize` other than `SourceSize` without zlib, or not + larger than `SourceSize` with it (`_INVALID_DESTINATION_SIZE`: the rule `dstorageerr.h` gives for that code, + and what `DSTORAGE_REQUEST` says of `DestinationSize`), more than 1 GiB in total, then a buffer over 32 MiB + (`_REQUEST_TOO_LARGE` for both: `DSTORAGE_REQUEST` allows a buffer over 32 MiB only with 64 KiB or 2 MiB pages, + which are not implemented yet; the source is never larger than the destination here, so the destination's + limit covers it), then a zlib file request whose `FileOffset` is not 16-byte aligned (`_INVALID_FILE_OFFSET`, + as `DSTORAGE_REQUEST` requires); + 6. a null destination, a null source (memory) or a null file (`E_INVALIDARG`), a closed file (`_FILE_NOT_OPEN`); + 7. a zero size: a success that touches no memory (an assumption: the reference does not say); + 8. a range past the end of the file (`E_DSTORAGE_END_OF_FILE`), then a destination or source the process cannot + access (`E_DSTORAGE_ACCESS_VIOLATION`; the worker survives it). This needs asynchronous exceptions under + clang-cl, so `runtime/CMakeLists.txt` builds `dstorage.cpp` with `/EHa` there; MSVC always catches it. + + Step 7 does not apply to a zlib request (its `DestinationSize` is never 0 after step 5); its stream fails as + described next. +- **zlib** (`ZlibDecompress` alone): the source, `SourceSize` bytes of the file or of memory, is read into a staging + buffer and inflated there by the runtime's RFC 1950 inflater (`leonida::zlib_inflate` in + `runtime/src/shader_library.h`, the one the shader library uses for XBCH blobs). The result is copied to + `Destination` only when it is exactly `DestinationSize` bytes, so a stream that fails leaves the destination as it + was, and a memory source inside its own destination (in-place loading) inflates correctly. Both buffers are at + most 32 MiB (step 5). Step 5 also means a stream of stored blocks only, which is larger than what it holds, is + refused with `_INVALID_DESTINATION_SIZE` before it is read, as the documented rule implies. The stream is a zlib + stream: the two header bytes, the deflate blocks (stored, fixed and + dynamic Huffman), the Adler-32 of the result. Bytes after the Adler-32 are not read, so a `SourceSize` rounded up + over padding works (an assumption: the reference does not say). The game's own data agrees with RFC 1950: the + texture pools' codec-8 chunks, laid out for this decompression ([textures.md](textures.md)), inflate with + Python's `zlib.decompress`, which checks the header and the Adler-32 (`tools/ttpf_mips.py`). A failure: + + | Stream | HRESULT | + |---|---| + | header not deflate, a window over 32 KiB, a wrong check value, or a preset dictionary | `E_DSTORAGE_ZLIB_BAD_HEADER` (`0x89240031`) | + | a reserved block type, an invalid code, a distance before the start, or a truncated stream | `E_DSTORAGE_ZLIB_BAD_DATA` (`0x89240032`) | + | Adler-32 mismatch | `E_DSTORAGE_ZLIB_PARITY_FAIL` (`0x89240033`) | + | inflates to more or fewer bytes than `DestinationSize` | `E_DSTORAGE_DECOMPRESSION_ERROR` (`0x89240030`; no code names a size mismatch, so the generic one) | + + The inflater decodes one bit at a time, on the queue's worker: correct, not fast. A faster decoder (table lookup) + can replace it behind `zlib_inflate` without touching the request path. +- **Cancel**: `CancelRequestsWithTag(mask, value)` marks every request enqueued before the call and not yet started + whose `(CancellationTag & mask) == value`. A cancelled request completes as a success without reading and is not + counted as a failure, as the overview and the reference say, even when it also had an error found at enqueue. +- **Notifications**: `EnqueueStatus` sets the entry to `E_PENDING` at once and, when reached, to the first failure + since the previous status or signal (else `S_OK`); `IsComplete` is `GetHResult != E_PENDING`; an index past the + array is `E_DSTORAGE_INDEX_BOUND`, a foreign or null array `E_DSTORAGE_INVALID_STATUS_ARRAY`. `EnqueueSignal` calls + `ID3D12Fence::Signal` (PC slot 10, which the `d3d12_xs` fence proxies forward) on the worker thread; a null fence is + `E_DSTORAGE_INVALID_FENCE`. `EnqueueSetEvent` duplicates the handle at once and sets the duplicate, then closes it, + so an event the title closes in the meantime (and a handle value reused for another object) is never the one set; a + null or invalid handle is recorded as a failure. Each notification holds a reference on its array or fence until it + has run. +- **Errors**: a failure goes into the status entry, the queue's error record (failure count and the first failure + since the last `RetrieveErrorRecord`, with the file name the title opened) and sets the error event. + `GetErrorEvent` returns a duplicate handle (the reference says the caller closes it). `RetrieveErrorRecord` + clears the record and resets the event; with nothing recorded it returns `DSTORAGE_COMMAND_TYPE_NONE`. A failed + `SetEvent` is recorded with command type 3 (the PC API's `EVENT`; the console enum stops at 2). +- **Close and release**: `Close` submits what is enqueued, waits until the worker has run it all and stops the + worker; later enqueues are dropped and recorded as `E_DSTORAGE_QUEUE_CLOSED`. The last `Release` closes the same + way, so a queue released with requests in flight finishes them first. + +## Not done yet (later PRs) + +- **BCPack** (`BcpackMode`; `tools/bcpack.py` is the reference decoder), then **swizzle** (`SwizzleMode`). The + decode order is DEFLATE, BCPack, swizzle; with both zlib and BCPack `IntermediateSize` is the size between them + (the inflate's output, the BCPack decoder's input), and `FileOffset` must be 16-byte aligned. Each becomes a stage + after `inflate_request`'s inflate and before its destination write, so the request checks above stay where they + are. +- **Physical pages** (`SourceIsPhysicalPages`, `DestinationIsPhysicalPages`): arrays of 64 KiB page numbers from + `XMemAllocatePhysicalPages`; needs the `xmem` shim to translate a page number to the address it mapped. +- **GPU memory**: the console API has no GPU destinations of its own (memory is unified, so a destination is an + address). An address inside memory the Vulkan layer backs will need its write routed to that memory. The destination + is written in two places, both in `execute_request` (`read_file_range` for a file source, `guarded_move` for a + memory source), so that change stays inside the request path. +- **Parallel reads**: the worker reads one request at a time. Overlapped reads with in-order retirement of + notifications would keep the order guarantee. + +## Tests + +`runtime/test/dstorage_test.cpp` (ctest `dstorage`) runs on synthetic files in `%TEMP%` through the registry entries +under all three module names: `GAME:` reads with an overlay copy winning, offsets, zero size, a range past the end, +cancellation, auto-submit, a full queue, status arrays, fences (a CPU fence object that checks the data is in place +when it is signalled), events, error records, file and queue close with requests in flight, a destination the +process cannot write, four threads enqueueing at once, the interface-id policy (unknown and system ids refused by +`QueryInterface`, learned by creating calls), a `GetHandle` handle with its own file position, an event closed (and +its handle value reused) before it is set, and cancelled requests that also had an enqueue error. zlib requests use +synthetic streams only: two made with Python's `zlib` (level 9: one dynamic-Huffman block; level 1: one +fixed-Huffman block) from text the test rebuilds, and stored-block streams the test builds, one of them a stored +block followed by the dynamic one. They are read from a file and from memory (also in place); a bad header, a +preset dictionary, a reserved block type, a truncated stream, an Adler-32 mismatch, a stream shorter and one longer +than `DestinationSize`, a stored stream larger than its result, an unaligned offset, an `IntermediateSize`, zlib with +BCPack or swizzle (`E_NOTIMPL`), an unreadable source and an unwritable destination each get their code, a failed +stream leaves its destination untouched, and the decompression statistics count them. + +## Sources and licences + +| Source | Facts used | Licence / use | +|---|---|---| +| [GDK DStorage reference](https://learn.microsoft.com/en-us/gaming/gdk/docs/reference/system/dstorage/dstorage_members) and its function, interface, structure and enumeration pages | Names, method signatures, structure members, enum values, requirements rows | [Microsoft Learn Terms of Use](https://learn.microsoft.com/en-us/legal/termsofuse); facts paraphrased, no text copied | +| [DirectStorage overview (GDK)](https://learn.microsoft.com/en-us/gaming/gdk/docs/features/console/storage/directstorage/directstorage-overview) | Queue, auto-submit, cancellation, notification order, file sharing, decode order | Same terms; paraphrased | +| `dstorage.h`, `dstorageerr.h` in the public `Microsoft.Direct3D.DirectStorage` 1.3.0 NuGet package | PC method order, interface ids (to refuse them), capacity and name-length constants, `E_DSTORAGE_*` values | Read for facts only; not vendored. `runtime/shims/dstorage_xs_abi.h` is Leonida's own declaration | +| [DirectStorage constants](https://learn.microsoft.com/en-us/windows/win32/dstorage/dstorage-constants) (Win32 reference) | `E_DSTORAGE_DECOMPRESSION_ERROR` = `0x89240030`; `E_DSTORAGE_INVALID_DESTINATION_SIZE`: equal to the length without decompression, larger with it; `E_DSTORAGE_INVALID_FILE_OFFSET` is the offset invalid for a decompression mode | [Microsoft Learn Terms of Use](https://learn.microsoft.com/en-us/legal/termsofuse); paraphrased | +| [`direct-storage` crate](https://docs.rs/direct-storage/0.5.1/src/direct_storage/bindings.rs.html) 0.5.1 (bindings generated by `windows-bindgen` from the DirectStorage headers; 0.2.0's `errors.rs` has the same values) | `E_DSTORAGE_ZLIB_BAD_HEADER` `0x89240031`, `E_DSTORAGE_ZLIB_BAD_DATA` `0x89240032`, `E_DSTORAGE_ZLIB_PARITY_FAIL` `0x89240033` (names and values only) | MIT/Apache-2.0; two constants' names and values, no code copied | +| [RFC 1950](https://www.rfc-editor.org/rfc/rfc1950) and [RFC 1951](https://www.rfc-editor.org/rfc/rfc1951) | The zlib stream and DEFLATE formats `zlib_inflate` decodes | Public specifications | diff --git a/docs/embedded_shaders.md b/docs/embedded_shaders.md index ed3a254d71..a1277dfc71 100644 --- a/docs/embedded_shaders.md +++ b/docs/embedded_shaders.md @@ -291,12 +291,13 @@ The last line also gets `--wave64-emulate` and the fallback flags of the build, `0x80004001`) after 28 creations. **Run time.** `ShaderLibrary::load(dir)` (`runtime/src/shader_library.h`) reads `/index.json`, then -`/fspx/index.json` and `/bvh/index.json` when they are there. The builder's entries are named -`bvh/`, the path of their module below ``, and go into the table of the game's shaders, so -`create_compute` finds them through the lookup it already had (`compute_program()` gives an `FSSM` program, looked up -by `(cs, fssm_sha256)`). A missing or unreadable `bvh/index.json` leaves the other indexes loaded, and the main -index is still required. `bvh_size()` counts the entries, which `shader_library_corpus_test` leaves out of the -entries a carved container must reach, like the FSPX ones. +`/fspx/index.json`, `/bvh/index.json`, and `/exe/index.json` when they are there. The builder's +entries are named `bvh/` and the executable's `exe/`, the path of their module below ``, and both +go into the table of the game's shaders, so graphics and compute pipeline creation find them through the lookup they +already had (`fssm_program()` / `compute_program()` gives an `FSSM` program, looked up by `(stage, fssm_sha256)`). A +missing or unreadable subfolder `index.json` leaves the other indexes loaded, and the main index is still required. +`bvh_size()` and `exe_size()` count those entries, which `shader_library_corpus_test` leaves out of the entries a +carved container must reach, like the FSPX ones. **Measured: `LEONIDA_BVH_DEVICE=vulkan bvh_builder_test`** (package 1.0.2.1, `LEONIDA_BVH_RECORD62=1`, `LEONIDA_SHADERS` on a folder holding this step's output and an empty main index, since only this step was run). @@ -390,6 +391,17 @@ constructor's pipelines are created, not that a build produces the right tree (s `tests/test_bvh_shaders_stage.py` runs the step on a synthetic DLL (hand-built containers around a made-up `FSSM` blob, no game data): the key the extracted layout gives the translator, the tools and arguments, reuse and each reason to run again, a second run that leaves no duplicate containers, the report of an untranslated program on -every run and the failure when nothing translates. `shader_library_test` covers the `bvh/` index (found by the -container's program hash, counted apart, a broken or missing index beside the others) and `d3d12_compute_test` +every run and the failure when nothing translates. `shader_library_test` covers the `bvh/` and `exe/` indexes (found +by the container's program hash, counted apart, a broken or missing index beside the others) and `d3d12_compute_test` creates a pipeline through slot 62 whose only translation is in `/bvh/index.json`. + +**Retail executable (`exe_shaders()`).** After `bvh_shaders()`, `make_game.py`'s `shaders` stage runs +`exe_shaders()` on `/game_scarlett_master.exe` when present (skipping cleanly and dropping any stale +`/shaders/spirv/exe/index.json` and `exe_build.json` when the package has no executable). It runs the same +four tools into `/shaders/exe` and `/shaders/spirv/exe` (without `--max-shared-memory`, since the +executable's containers are 1 VS + 9 PS graphics shaders), tracking inputs in `exe_build.json` and logging +translated/missing counts on every run. Measured on 1.0.2.1: 10 of 10 programs translate and pass `spirv-val` +natively and with `--wave64-emulate`, `ShaderLibrary::load` finds all 10 (`1 VS + 9 PS`) by `(stage, fssm_sha256)`, +and `vk_pipeline_check` passes 10/10 modules and 10/10 pipelines (0 failed, 0 skipped) on an AMD Radeon RX 9070 XT +(RADV GFX1201, Mesa 26.2.6) and an AMD Ryzen 7 9800X3D integrated GPU (RADV RAPHAEL_MENDOCINO, Mesa 26.2.6). +`tests/test_exe_shaders_stage.py` covers the step on synthetic VS/PS `PSV0` containers without game data. diff --git a/docs/pipeline_check.md b/docs/pipeline_check.md index 62e5417a3d..f0e142746e 100644 --- a/docs/pipeline_check.md +++ b/docs/pipeline_check.md @@ -439,6 +439,24 @@ On Windows with an RTX 5090 (driver 621.14), a synthetic three-compute, one-vert sample reported zero application-cache hits on its first run and five on the seeded run. On Mesa llvmpipe the same five pipelines succeeded both times and neither run reported a hit. +### The cache and the runtime's device + +The runtime seeds its `VkPipelineCache` from the cache this tool saves, so a pipeline hits there only when the +driver gives it the same cache key in both programs. Measured on Windows with an RX 9070 XT (driver +32.0.32029.2010) and one synthetic compute shader, reading the application-cache-hit bit: + +- `robustBufferAccess`, `scalarBlockLayout` and `robustImageAccess` are each part of the key. The runtime's + device enables none of them, so the checker's does not either. Nothing else that differs between the two + devices changed the key: the checker's other features, the runtime's extensions, the application name. +- The executable's file name is part of the key; its folder is not. A copy of the checker under another name + misses the cache the original wrote, and the runtime's device hits the checker's cache only from a program + with the checker's file name. So on this driver a cache written by `vk_pipeline_check.exe` does not hit in + `gta6rt.exe`, and one written by a copy of the checker named `gta6rt.exe` does. + +The `pipeline_cache_seed` test runs the checker, then creates the same pipeline on the runtime's device from +the saved cache; the checker runs as a copy with the test program's file name. It is skipped where the driver +reports no hit even for a cache the device wrote itself, as llvmpipe does. + ## Wave64-emulated corpus (`--wave64-emulate`) A GPU that only runs 32-wide subgroups (NVIDIA, Intel) needs the corpus translated with diff --git a/docs/retail_boot_chain.md b/docs/retail_boot_chain.md index cbe29cf831..9eadb6614a 100644 --- a/docs/retail_boot_chain.md +++ b/docs/retail_boot_chain.md @@ -21,7 +21,7 @@ stand-ins named below (not pull requests yet). Own 1.0.2.1 copy, Windows 11, RTX | 5 | Fatal assert when `DStorageGetFactory` returns null | #4348 | | 6 | `XMemAllocatePhysicalPages` unimplemented; the title asserts on FALSE | Local stand-in, §2 | | 7 | `D3D12XboxCreateDevice` succeeds; device slot 26 is called with its arguments swapped | Local, §3.1 | -| 8 | Device slot 48 is forwarded to the PC slot 48 and fails | Local, §3.2 | +| 8 | Device slot 48 is forwarded to the PC slot 48 and fails | #6954 | | 9 | Device slot 73 is forwarded to the PC slot 73; the title then reads through a null list | #2490's list proxy plus local routing, §3.3 | | 10 | An `XMemVirtualAlloc` reserve of about 185 MiB with type `0x42000`, attribute 7 and `PAGE_NOACCESS` is refused with `ERROR_INVALID_PARAMETER`. `0x40000` is `MEM_RESERVE_PLACEHOLDER` on the PC, which `VirtualAlloc` refuses and only `VirtualAlloc2` accepts; stop 11 supports the same reading on the console | Local: reserve it with `VirtualAlloc2(MEM_RESERVE \| MEM_RESERVE_PLACEHOLDER)` | | 11 | The title carves five sub-ranges out of that placeholder with `MEM_RESERVE \| MEM_REPLACE_PLACEHOLDER \| MEM_PHYSICAL \| MEM_LARGE_PAGES` (`0x20406000`) at addresses inside it, then allocates a second batch of physical pages | Local: a physical reserve inside a known placeholder stays a placeholder (the page maps split it); other `MEM_REPLACE_PLACEHOLDER` calls split the range and allocate it in place | diff --git a/docs/runtime_imports.md b/docs/runtime_imports.md index 7b9f62d5a1..5cba370c6e 100644 --- a/docs/runtime_imports.md +++ b/docs/runtime_imports.md @@ -184,6 +184,20 @@ The seven `xmem.dll` imports are served now (see the `xmem.dll` notes above), so again at detach (reason 0), and there is no `exception`, `error` or `unimplemented_call` event. So none of the 30 unimplemented imports is reached by the TLS callbacks or the `DllMain`s. +The executable's audio imports `xapu.dll` (`XApuConnect`, `XApuDequeueResult`, `XApuDisconnect`, +`XApuEnqueueCommand`, `XApuGetResultCount`) and `chad.dll` (`XDspActivate`, `XDspConnectWithMaximumStreamLimit`, +`XDspDeactivate`, `XDspDisconnect`, `XDspSubmitCommand`) are served by `runtime/shims/xapu_chad.cpp`. The shapes were +read statically from the executable's call sites: one each, four for `XApuEnqueueCommand`. Both connects succeed with +a handle; the APU connect also returns a zeroed shared buffer the title writes stream input to and reads output from. +Commands are accepted and not processed, so the audio stays silent. A stream open (type 1) and a stream close +(type 2) each queue one result of the same type and slot, because the title frees a stream id only when the close +result arrives. `XDspActivate` writes its two outputs as pointers to zeroed memory, which the title reads as "command +done" after each `XDspSubmitCommand`. `XApuConnect` leaves its first argument, a global of the title, untouched. The +buffer size (128 stream slots), the two results and the zeroed DSP status are hypotheses, explained in the file. +`xapu_chad_test` calls all ten in those shapes. With `--trace`, the first call of each, and the first command of each type, is an +`audio_queue` event. +The table above was measured before this shim and still lists these ten as unimplemented; they are served now. The call shapes agree with `docs/audio_hal_exe_calls.md`, which was measured with `tools/import_call_sites.py`. + What this does not show: `--run` has not been run, so the entry point has not been called and no import is known to be reached on the way to the first frame. A bound import is not a working one (the binding only says a function with that name exists), and an unimplemented import stops the run only if the title calls it @@ -192,6 +206,19 @@ functions from `ws2_32.dll` (23 by ordinal, plus `getaddrinfo` and `freeaddrinfo host's, so a `--run` can open real sockets: run it with the network off. `winhttp.dll` is served by the offline shim, which opens none. +## Audio hardware (`AcpHal.dll`) + +The game executable imports nine functions from `AcpHal.dll`, the console's audio hardware layer. +`runtime/shims/acphal.cpp` serves them; the argument shapes come from a static read of the executable's call sites +(one thunk per import, 16 call sites in all), and the names of the parameters and object slots are hypotheses. +`ApuCreateHeap` reserves one block of ordinary memory for both sizes it is given, `ApuAlloc` and `ApuFree` manage it +first fit, and an APU address is a fixed 32-bit base plus the offset in it, so `ApuMapVirtualAddress` and +`ApuMapApuAddress` are arithmetic and `ApuIsVirtualAddressValid` checks a live block and the alignment. +`AcpHalAllocateShapeContexts` fills zeroed 64-byte contexts per count, and `AcpHalCreate` returns an object whose +calls succeed and do nothing: there is no audio processor, so the game gets no sound from this path. Its boot checks +fail hard, which is why every call succeeds. `acphal_test` covers the call shapes. +The table under [The retail executable](#the-retail-executable-rt-5) was measured before this shim and still lists these nine as unimplemented; they are served now. + ## Console paths and the write overlay A title's file calls name the console's drives, so `GAME:\data\x.sps` is a file inside the installed game folder. @@ -292,19 +319,30 @@ measurement in `d3d12_vulkan.md`, because its page could not be found. Not every console module is reached through an import table. `libHttpClient.GDK.dll` and `XCurl.dll` both use the GDK runtime, but `dumpbin /imports` shows **no import of `xgameruntime.dll`** in either. Both carry the wide string `xgameruntime.dll` and the ASCII names `InitializeApiImpl`, `InitializeApiImplEx`, `InitializeApiImplEx2`, -`QueryApiImpl` and `UninitializeApiImpl`, next to a statically linked `XGameRuntimeInitialize`. So `xgameruntime.lib`'s -thunks `LoadLibraryW` the runtime and `GetProcAddress` those five names at run time. xodus-gaming/xgameruntime-docs +`QueryApiImpl`, `UninitializeApiImpl` and `XErrorReport` (one block of strings in each DLL), next to a statically +linked `XGameRuntimeInitialize`. So `xgameruntime.lib`'s thunks `LoadLibraryW` the runtime and `GetProcAddress` those +six names at run time. A runtime without `XErrorReport` is refused before any initializer is called: with only the +five entry points served, the package's own libHttpClient `HCInitialize` returned `0x89240101` +(`E_GAMERUNTIME_DLL_NOT_FOUND`) and XCurl's `curl_global_init` returned `CURLE_FAILED_INIT`, both called through +`gta6rt --run` by a stand-in program that loads the two DLLs from the package. xodus-gaming/xgameruntime-docs (GPL-3.0) documents the same mechanism for PC GDK titles: `InitializeApiImplEx2` is what `XGameRuntimeInitialize[WithOptions]` calls, and `QueryApiImpl` hands out the runtime's COM classes, whose methods mostly correspond one to one to the `xgameruntime.lib` functions. The executable is very likely linked the same way. Bound to the host, those calls would load the PC's Gaming Services runtime, or fail, and never reach the offline shims. `runtime/shims/library_loader.cpp` therefore answers `LoadLibrary*` and `GetModuleHandle*` for a module the +shim registry owns (`rt::shims::owns_dll`: `xgameruntime.dll`, `d3d12_xs.dll`, `xmem.dll`, `gameinput.dll`, and the DirectStorage +modules `dstorage_xs.dll`, `xcrdapi.dll` and `dstorage.dll`, [directstorage.md](directstorage.md)) with a +shim registry owns (`rt::shims::owns_dll`: `xgameruntime.dll`, `d3d12_xs.dll`, `xmem.dll`, `gameinput.dll`, `acphal.dll`) with a +shim registry owns (`rt::shims::owns_dll`: `xgameruntime.dll`, `d3d12_xs.dll`, `xmem.dll`, `gameinput.dll`, `xapu.dll`, `chad.dll`) with a +pseudo-handle, and `GetProcAddress` on it resolves through the registry. A name the registry doesn't serve is `NULL` shim registry owns (`rt::shims::owns_dll`: `xgameruntime.dll`, `d3d12_xs.dll`, `xmem.dll`, `xg_xs.dll`, `gameinput.dll`) with a pseudo-handle, and `GetProcAddress` on it resolves through the registry. A name the registry doesn't serve is `NULL` with `ERROR_PROC_NOT_FOUND` and is logged once. Every other module goes to the host unchanged. -`runtime/shims/xgameruntime.cpp` serves the five entry points. The initializers succeed offline and log the GDK +`runtime/shims/xgameruntime.cpp` serves the five entry points and `XErrorReport(HRESULT, const char*)`, the same +function as `IXErrorImpl` slot 3 (below), so a report reaches the callback `XErrorSetCallback` set either way. The +initializers succeed offline and log the GDK version and mode once. `QueryApiImpl` serves `XThreadingImpl`, `XErrorImpl`, `XNetworkingImpl`, `XSystemImpl`, `XPersistentLocalStorageImpl`, `XPackageImpl`, `XGameImpl`, `XGameRuntimeFeatureImpl` and `XSystemAnalyticsImpl` (below), and `XUserImpl`, `XGameSaveImpl`, `XStoreImpl`, `XGameEventImpl`, `XGameUiImpl`, `XGameStreamingImpl`, @@ -319,7 +357,8 @@ the api-set binding `XCurl.dll` uses, and calls the classes `xgameruntime.cpp` s pointers to 64-bit locals (the result is not read), compares the pair with the one it saw last and keeps it. On the host that load would find a PC's Gaming Services runtime, which bypasses the offline classes, or nothing, in which case XCurl returns `0x87E00196`. The shims own `gameplatformservices.dll` too: its `QueryApiImpl` is the offline -one, and `GetApiVersionImpl(uint64_t*, uint64_t*)` writes the same two values every time. +one, and `GetApiVersionImpl(uint64_t*, uint64_t*)` writes the same two values every time. `curl_global_init` also +asks that module for `InitializeApiImpl`, which is not served; the call succeeds without it. ### Class layouts, measured diff --git a/docs/shader_library.md b/docs/shader_library.md index 09a1997a97..5aaf52d961 100644 --- a/docs/shader_library.md +++ b/docs/shader_library.md @@ -118,9 +118,8 @@ python -I tools/rdna2spirv.py /library/disasm --out /library/spirv * It writes `fspx/.code` and `fspx/.json`, the layout `fspx_unpack.py` writes and `rdna2spirv.py` reads (`native_blob`, `cs_dispatch_state`). A compute program also gets `fspx/.state`, its record's state - blob (FSPX kind 0) as it is, whose SHA-256 is the index's `fspx_state_sha256`; in the 1.0.2.1 `shaders.rpf` library, - every compute program has one distinct state-blob index across `library.json`'s `compute` table (2,684 programs, - 2,693 records). It also writes `index.json` with each program's stage, and + blob (FSPX kind 0) as it is, whose SHA-256 is the index's `fspx_state_sha256`; every compute program has exactly one + (2,684 programs, 2,693 records). It also writes `index.json` with each program's stage, and `library.json` with the header and both pipeline tables, stage to program name. Programs are named `lib__`. * `--disasm` writes `disasm/.s` for the code after the prologue, as `fspx_unpack.py --disasm` does. @@ -134,10 +133,9 @@ The output is game data and must stay in your work folder. `tests/test_shader_li archives by hand and covers the header, both tables, the size checks, the search in an archive and the digest walk. It also checks the `--carve` copy, the translator's reads of the compute sidecar and the compute `.state`. -**In the build.** `make_game.py`'s `shaders` stage runs this for the compute stage after the BVH step -(`library_shaders`): `--stages cs --disasm --carve` into `/shaders/library`, then `translate()` shards -`rdna2spirv.py` across `--jobs` and merges into `/shaders/spirv/library` with the stage's `--wave64-emulate` -and fallback flags. The runtime's shader library +**In the build.** `make_game.py`'s `shaders` stage runs this for the compute stage after the FSPX step +(`library_shaders`): `--stages cs --disasm --carve` into `/shaders/library`, then `rdna2spirv.py` into +`/shaders/spirv/library` with the stage's `--wave64-emulate` and fallback flags. The runtime's shader library reads that index next to `fspx/` and finds its entries by `fspx_code_sha256` and `fspx_state_sha256` ([fspx.md](fspx.md), "Build and run-time lookup"). That is how the executable creates these pipelines: it reads the library through DirectStorage zlib requests and passes each compute record's four parts to Xbox device slot 67, diff --git a/docs/xdxr.md b/docs/xdxr.md index 1a2d104a47..1b8a4cc274 100644 --- a/docs/xdxr.md +++ b/docs/xdxr.md @@ -112,6 +112,40 @@ type is one of two checks, and neither reads past the `InfoType` field: None of the 15 other DLLs in the package names the type or an offline builder. +## 4a. The runtime serves the DLL itself + +`runtime/shims/xbox_bvh_builder.cpp` serves the seven exports the executable imports with the layer's own XDXR +builder (`runtime/src/xdxr_build.*`), so the bundled DLL is not loaded and its 52 console programs are never created. +Their pipeline compile (31.2 s for one of them on an RTX 4080, 59.5 s for all 52 on an RX 9070 XT, #7231/#7049) runs +on the title's thread, longer than its ~30 s startup watchdog, so a cold first boot ends at the builder (boot stop 18). +`LEONIDA_BVH_BUILDER=console` turns the shim off. + +The executable's imports and call sites, measured statically on 1.0.2.1. The counts are `call [rip+disp32]` +through the import table. For `Batched2X`, IDA finds 8 direct calls: 4 in each of two sibling functions with no +static reference, reached through a table (#7516), so 2 of them are calls of another form. + +| Export | Call sites | The shim | +|---|---:|---| +| `XboxBvhBuilder(ID3D12Device11*, bool)` | 1 | keeps the device in a table keyed by `this`; writes nothing into the title's object | +| `~XboxBvhBuilder()` | 1 | releases that entry | +| `Set64BitMortonCodes(bool)` | 8 | recorded; the layer's builder has no such option | +| `GetRaytracingAccelerationStructurePrebuildInfo(INPUTS*, XDXR_STREAM_DESC*, PREBUILD_INFO*)` | 3 | the layer's sizes | +| `BuildRaytracingAccelerationStructureBatched2X(GCL6*, UINT, BATCHED_DESC2*)` | 6 (8) | one layer build per element (§1), with its postbuild descriptions | +| `CopyRaytracingAccelerationStructure(GCL4*, dest, source, mode)` | 2 | the layer's copy | +| `RehydrateRaytracingAccelerationStructureBatched2X(GCL8*, UINT, BUILD_DESC*, UINT64*)` | 4 | `E_NOTIMPL` for now | + +**Where it differs from the DLL:** +- **Stream records (§3):** they tune the console builder's heuristics, so they are ignored (logged once). The result + is still a valid BVH of the same geometry, in the node format the traversal shaders read. +- **Validation errors:** the DLL throws them as C++ exceptions. A shim must not throw into the title, so an element + the DLL would refuse is skipped with a log line. The offline-statistics postbuild type (`0x10`, §4) is one of + those. +- **Rehydration** is the next step: rebuild each structure on the GPU from the source geometry its description + carries ([bvh.md](bvh.md) §4a), in the leaf frame `compressionParams` gives. + +`xbox_bvh_builder_test` calls every export through the shim registry, the way the title's imports bind, and +`xdxr_bvh.py check-build` checks the BLAS, TLAS and compacted BLAS it builds (ctest `xbox_bvh_builder_check`). + ## 5. What is still open - The names of the stream record types and of their values. diff --git a/make_game.py b/make_game.py index 555f804c93..91c3925f24 100644 --- a/make_game.py +++ b/make_game.py @@ -21,7 +21,7 @@ Stages (each skips work that is already done, so a stopped build continues where it left off): check always first: file names and sizes against game/.json (add --full-check for SHA-256, slow) shaders carve shaders.rpf, unpack the native RDNA2 code, disassemble, translate to SPIR-V; then the same for the - compute programs inside amd_fidelityfx_upscaler_xbox.dll and XboxBvhBuilder.dll + programs inside amd_fidelityfx_upscaler_xbox.dll, XboxBvhBuilder.dll and game_scarlett_master.exe assets models (OBJ), texture dictionaries and texture pools (DDS), audio banks (AWC; --wav adds PCM WAV) BCPack uses strict decoding by default. For local calibration use /bcpack-calibration.json. runtime build the loader (needs the game's executable to run, not to build). On Linux it is cross-built with @@ -1324,6 +1324,7 @@ def shaders(game: str, work: str, jobs: int, emulate: bool = False, keep_emulate fspx_shaders(game, work, signature, emulate=emulate, fallbacks=fallbacks) bvh_shaders(game, work, signature, jobs, emulate=emulate, fallbacks=fallbacks) library_shaders(game, work, signature, jobs, emulate=emulate, fallbacks=fallbacks) + exe_shaders(game, work, signature, jobs, emulate=emulate, fallbacks=fallbacks) log("shaders: done") @@ -1613,6 +1614,88 @@ def bvh_shaders(game: str, work: str, mc_signature: str, jobs: int = 1, emulate: f.write(settings + "\n") +EXE_FILE = "game_scarlett_master.exe" +EXE_TOOLS = BVH_TOOLS # pe_shader_containers.py, fssm_unpack.py and shader_disasm.py + + +def exe_settings(exe: str, mc_signature: str, emulate: bool, fallbacks: tuple[str, ...]) -> str: + """What the executable's embedded shader outputs depend on, as one line: the executable, the extracting, + unpacking and translating tools, llvm-mc, the wave64 mode and the fallback flags.""" + return json.dumps({"exe": file_sha256(exe), "tools": sources_digest(TOOLS, EXE_TOOLS), + "translator": translation_sources_digest(), "llvm_mc": mc_signature, + "wave64_emulate": bool(emulate), "fallbacks": list(fallbacks)}, sort_keys=True) + + +def exe_report(programs: "tuple[list[str], list[str]]") -> None: + """One line with the counts, and one that names every program left without a module. It is printed on every + run, also when the step itself is reused: a program the translator has no rule for is never dropped quietly.""" + extracted, missing = programs + log(f"shaders: {len(extracted) - len(missing)} of {len(extracted)} {EXE_FILE} programs translated") + if missing: + log(f"shaders: NOT translated: {', '.join(missing)}. The runtime has no module for " + f"{'it' if len(missing) == 1 else 'them'}, so any pipeline using it will miss its shader. " + "When the step runs, rdna2spirv.py prints the instruction each one stops at " + "(docs/embedded_shaders.md, section 2)") + + +def exe_shaders(game: str, work: str, mc_signature: str, jobs: int = 1, emulate: bool = False, + fallbacks: tuple[str, ...] = ()) -> None: + """game_scarlett_master.exe's embedded graphics shaders (docs/embedded_shaders.md, section 2): + pe_shader_containers.py extracts the executable's DXBC containers into /shaders/exe, fssm_unpack.py and + shader_disasm.py unpack and disassemble their FSSM programs there, as for a shader from shaders.rpf, and + rdna2spirv.py translates them into /shaders/spirv/exe, where the runtime's shader library finds them by + fssm_sha256. The game's RPF shaders neither feed nor depend on this step. + + The 10 programs take seconds, so the step runs whole. Reuse requires both indexes, the translated modules and a + matching exe_build.json (exe_settings).""" + exe = os.path.join(game, EXE_FILE) + unpacked = os.path.join(work, "shaders", "exe") + spirv = os.path.join(work, "shaders", "spirv", "exe") + extracted = os.path.join(unpacked, "index.json") + unpack_index = os.path.join(unpacked, "fssm_index.json") + translated = os.path.join(spirv, "index.json") + settings_file = os.path.join(spirv, "exe_build.json") + if not os.path.isfile(exe): + # A work folder used before with a package that had the executable still holds that run's index, and the + # runtime loads /exe/index.json whenever it is there. Without the index the old modules are not found. + drop(translated, settings_file) + log(f"shaders: no {EXE_FILE} in the game folder, so no executable shader programs to translate") + return + settings = exe_settings(exe, mc_signature, emulate, fallbacks) + programs = bvh_programs(unpacked, spirv) if read_shader_setting(settings_file) == settings else None + if programs and len(programs[1]) < len(programs[0]): + exe_report(programs) + return + log(f"shaders: extracting and translating the embedded shader programs of {EXE_FILE}") + drop(translated, settings_file, extracted, unpack_index) + # pe_shader_containers.py never overwrites a container (a second run would write _NN.dxbc beside the + # first), and a program that no longer translates must not keep a module from the run before. + for folder, suffixes in ((unpacked, (".dxbc",)), (os.path.join(unpacked, "fssm"), (".fssm",)), + (os.path.join(unpacked, "disasm"), (".s",)), (spirv, (".spv", ".spvasm"))): + if os.path.isdir(folder): + with os.scandir(folder) as entries: + for entry in entries: + if entry.name.endswith(suffixes) and entry.is_file(follow_symlinks=False): + os.unlink(entry.path) + py("pe_shader_containers.py", exe, "--extract", unpacked) + py("fssm_unpack.py", unpacked, "--carve-index", extracted) + # rdna2spirv.py reads each program's stage from index.json and its FSSM blob from fssm/, both in the parent of + # the listings' folder, so the disassembly sits inside the extraction folder as it does for shaders.rpf. + disasm = os.path.join(unpacked, "disasm") + py("shader_disasm.py", os.path.join(unpacked, "fssm"), "--unpack-index", unpack_index, "--out", disasm, + "--mcpu", "gfx1013", "--jobs", jobs) + extra = (["--wave64-emulate"] if emulate else []) + list(fallbacks) + py("rdna2spirv.py", disasm, "--out", spirv, "--no-asm", *extra) + programs = bvh_programs(unpacked, spirv) + if not programs or len(programs[1]) == len(programs[0]): + drop(translated) # an empty or unreadable index would read as a finished step + fail(f"shaders: none of the {EXE_FILE} programs translated, so their index is not kept. Run the shaders " + "stage again; if it happens again, the tool output above is why.") + exe_report(programs) + with open(settings_file, "w", encoding="utf-8", newline="\n") as f: + f.write(settings + "\n") + + WAVE64_MODES = ("auto", "on", "off") # The translator's fallback flags make_game.py can forward, and the argparse attribute each one reads. diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 8fce889eb6..a094719f93 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -124,12 +124,18 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) shims/xgameruntime_gamesave.cpp shims/xgameruntime_store.cpp shims/xgameruntime_offline.cpp + shims/xbox_bvh_builder.cpp shims/library_loader.cpp shims/process.cpp shims/com_shim.cpp shims/bcrypt_rng.cpp shims/xapu_chad.cpp + shims/dstorage.cpp ) + # dstorage.cpp's guarded_move turns an access violation in a title's buffer into E_DSTORAGE_ACCESS_VIOLATION with + # __try. MSVC always catches it; clang-cl only with asynchronous exceptions (as for tiny_dll below). A source file + # property, so gta6rt and dstorage_test both get it. + set_source_files_properties(shims/dstorage.cpp PROPERTIES COMPILE_OPTIONS "$<$:/EHa>") add_dependencies(gta6rt gta6rt_tls_host) target_compile_definitions(gta6rt PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) target_compile_options(gta6rt PRIVATE /W4 /permissive- /utf-8) @@ -298,6 +304,19 @@ if(WIN32 AND LEONIDA_BUILD_WINDOWS_RUNTIME) target_compile_options(int3_skip_test PRIVATE /W4 /permissive- /utf-8) target_link_options(int3_skip_test PRIVATE /OPT:NOREF) + # Xbox DirectStorage (DStorageGetFactory under dstorage_xs.dll, xcrdapi.dll and dstorage.dll) over synthetic files: + # GAME: paths through the file shims, queues, status arrays, fences and errors. No GPU, no game data. + add_executable(dstorage_test + test/dstorage_test.cpp + shims/dstorage.cpp + shims/file_system.cpp + shims/registry.cpp + ) + target_include_directories(dstorage_test PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/shims) + target_compile_definitions(dstorage_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(dstorage_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(dstorage_test PRIVATE /OPT:NOREF) + # Offline WinHTTP for mapped images (the package's XCurl.dll and libHttpClient.GDK.dll); no network is touched. add_executable(winhttp_offline_test test/winhttp_offline_test.cpp @@ -511,9 +530,25 @@ if(BUILD_TESTING) add_executable(xbox_present_readback_size_test test/xbox_present_readback_size_test.cpp) add_test(NAME xbox_present_readback_size COMMAND xbox_present_readback_size_test) + # The title's own window, where PresentX shows its frames (shims/title_window.h): user32 only, no device. + if(WIN32) + add_executable(title_window_test test/title_window_test.cpp) + target_include_directories(title_window_test PRIVATE shims) + target_compile_definitions(title_window_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX UNICODE _UNICODE) + if(MSVC) + target_compile_options(title_window_test PRIVATE /W4 /permissive- /utf-8) + endif() + target_link_libraries(title_window_test PRIVATE user32) + add_test(NAME title_window COMMAND title_window_test) + endif() + add_executable(pipeline_cache_file_test test/pipeline_cache_file_test.cpp) add_test(NAME pipeline_cache_file COMMAND pipeline_cache_file_test) + # D3D-704's session-cache limit and header check: pure stdlib, no Vulkan headers. + add_executable(pipeline_cache_store_test test/pipeline_cache_store_test.cpp) + add_test(NAME pipeline_cache_store COMMAND pipeline_cache_store_test) + add_executable(xdxr_build_output_test test/xdxr_build_output_test.cpp) add_test(NAME xdxr_build_output COMMAND xdxr_build_output_test) @@ -884,6 +919,61 @@ if(BUILD_TESTING) COMMAND loader_tls_test "$" ) + # Module TLS index 0 fixture: an EXE built /GA, so its thread_local reads go straight to + # ThreadLocalStoragePointer[0] as a game executable's can. The loader must give a mapped executable index 0; + # loader_tls_index0_test maps it next to tiny_tls.dll and run_tiny_tls_ga runs it under gta6rt. Ordinary test + # code, no game data. The test checks the /GA code shape only where the compiler is MSVC, which implements /GA. + add_executable(tiny_tls_ga test/fixtures/tiny_tls_ga.cpp) + target_compile_options(tiny_tls_ga PRIVATE /W4 /permissive- /utf-8 /EHsc /GA) + set_target_properties(tiny_tls_ga PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + ) + add_executable(loader_tls_index0_test + test/loader_tls_index0_test.cpp + src/pe_loader.cpp + shims/registry.cpp + ) + target_include_directories(loader_tls_index0_test PRIVATE + ${CMAKE_CURRENT_SOURCE_DIR}/src + ) + target_compile_definitions(loader_tls_index0_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + $<$:LEONIDA_GA_FIXTURE_IS_GA=1>) + target_compile_options(loader_tls_index0_test PRIVATE /W4 /permissive- /utf-8 /EHsc) + # Loaded by the threads scenario before the TLS helper: its DllMain(DLL_THREAD_ATTACH) runs test code first. + add_library(tiny_thread_hook SHARED test/fixtures/tiny_thread_hook.cpp) + target_compile_definitions(tiny_thread_hook PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(tiny_thread_hook PRIVATE /W4 /permissive- /utf-8 /GS-) + set_target_properties(tiny_thread_hook PROPERTIES + OUTPUT_NAME tiny_thread_hook + PREFIX "" + RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + ) + add_dependencies(loader_tls_index0_test tiny_tls_ga tiny_tls tiny_thread_hook gta6rt_tls_host) + # Imports tiny_tls.dll and tiny_tls_cb_only.dll, so gta6rt needs a helper clone for one of them + # (check_tls_clone_cleanup.cmake). + add_executable(tiny_tls_clones test/fixtures/tiny_tls_clones.cpp) + target_link_libraries(tiny_tls_clones PRIVATE tiny_tls tiny_tls_cb_only) + target_compile_options(tiny_tls_clones PRIVATE /W4 /permissive- /utf-8) + set_target_properties(tiny_tls_clones PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + ARCHIVE_OUTPUT_DIRECTORY "${TINY_FIXTURE_DIR}" + ) + # One process per scenario: the reservation is once per process. loader_tls_index0 (runs) reserves at start, + # loader_tls_index0_threads reserves while threads are being created, loader_tls_index0_noreserve never does. + foreach(scenario runs threads noreserve) + if(scenario STREQUAL "runs") + set(name loader_tls_index0) + else() + set(name loader_tls_index0_${scenario}) + endif() + add_test(NAME ${name} + COMMAND loader_tls_index0_test ${scenario} "$" "$" + "$" + ) + endforeach() + # DisableThreadLibraryCalls from a mapped DllMain (shims/library_loader.cpp). The fixture is built without the CRT, so # DllMain's only work is that one call. No game files. add_library(dll_thread_calls SHARED test/fixtures/dll_thread_calls.cpp) @@ -1006,6 +1096,8 @@ if(BUILD_TESTING) # The routes are read once per process, so each override case is its own test. add_test(NAME xs_proxy_mock_env_slots COMMAND xs_proxy_mock_test --env-slots) add_test(NAME xs_proxy_mock_env_slots_invalid COMMAND xs_proxy_mock_test --env-slots-invalid) + add_test(NAME xs_proxy_mock_env_slots_70 COMMAND xs_proxy_mock_test --env-slots-70) + add_test(NAME xs_proxy_mock_env_slots_74 COMMAND xs_proxy_mock_test --env-slots-74) endif() if(TARGET root_sig_test) add_test(NAME root_sig COMMAND root_sig_test) @@ -1135,6 +1227,9 @@ if(BUILD_TESTING) add_test(NAME bink_audio COMMAND bink_audio_test) set_tests_properties(bink_audio PROPERTIES SKIP_RETURN_CODE 77) endif() + if(WIN32 AND TARGET cpu_emulation_test) + add_test(NAME cpu_emulation COMMAND cpu_emulation_test) + endif() if(WIN32 AND TARGET xmem_test) add_test(NAME xmem COMMAND xmem_test) endif() @@ -1144,9 +1239,6 @@ if(BUILD_TESTING) if(WIN32 AND TARGET acphal_test) add_test(NAME acphal COMMAND acphal_test) endif() - if(WIN32 AND TARGET cpu_emulation_test) - add_test(NAME cpu_emulation COMMAND cpu_emulation_test) - endif() if(WIN32 AND TARGET xapu_chad_test) add_test(NAME xapu_chad COMMAND xapu_chad_test) endif() @@ -1215,6 +1307,9 @@ if(BUILD_TESTING) set_tests_properties(wait_registration_${_case} PROPERTIES TIMEOUT 15) endforeach() endif() + if(WIN32 AND TARGET dstorage_test) + add_test(NAME dstorage COMMAND dstorage_test) + endif() if(WIN32 AND TARGET xgameruntime_test) add_test(NAME xgameruntime COMMAND xgameruntime_test) add_test(NAME xgameruntime_user COMMAND xgameruntime_user_test) @@ -1302,6 +1397,15 @@ if(BUILD_TESTING) "-DTOOL=$" "-DWANT=${GTA6RT_STACK}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_stack_reserve.cmake") add_test(NAME run_tiny_game_stack COMMAND gta6rt --run $ -- hello 42 stack) + # A /GA executable under --run and --init reads its TLS from slot 0, and the trace names gta6rt.exe as the image + # whose index 0 moved. + add_test(NAME run_tiny_tls_ga COMMAND ${CMAKE_COMMAND} + "-DLOADER=$" "-DGUEST=$" "-DTRACE_DIR=${CMAKE_CURRENT_BINARY_DIR}" + "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_tls_index0.cmake") + # Clone files are deleted when gta6rt exits normally; only the home clone outlives the run, until the next one. + add_test(NAME run_tiny_tls_clone_cleanup COMMAND ${CMAKE_COMMAND} + "-DLOADER=$" "-DGUEST=$" "-DTRACE_DIR=${CMAKE_CURRENT_BINARY_DIR}" + "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_tls_clone_cleanup.cmake") # GAME: is the game folder, absolute, when gta6rt is given a bare image name or `--game-dir .`. add_test(NAME run_tiny_game_dir COMMAND ${CMAKE_COMMAND} "-DLOADER=$" "-DGUEST=$" @@ -1608,6 +1712,15 @@ if(TARGET Vulkan::Headers) endif() add_test(NAME vk_presenter_sync COMMAND vk_presenter_sync_test) set_tests_properties(vk_presenter_sync PROPERTIES SKIP_RETURN_CODE 77) + set(conformance_src ${CMAKE_CURRENT_SOURCE_DIR}/../tools/conformance/native/src) + add_executable(vk_present_dump_test test/vk_present_dump_test.cpp + ${conformance_src}/png_io.cpp ${conformance_src}/diagnostics.cpp) + target_link_libraries(vk_present_dump_test PRIVATE Vulkan::Headers user32 windowscodecs ole32) + target_compile_definitions(vk_present_dump_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + add_test(NAME vk_present_dump COMMAND vk_present_dump_test) + add_test(NAME vk_present_dump_default COMMAND vk_present_dump_test --default) + add_test(NAME vk_present_dump_invalid COMMAND vk_present_dump_test --invalid) + set_tests_properties(vk_present_dump vk_present_dump_default vk_present_dump_invalid PROPERTIES SKIP_RETURN_CODE 77) endif() if(NOT Vulkan_GLSLANG_VALIDATOR_EXECUTABLE) find_program(Vulkan_GLSLANG_VALIDATOR_EXECUTABLE glslangValidator HINTS "$ENV{VULKAN_SDK}/Bin" "$ENV{VULKAN_SDK}/bin") @@ -1789,6 +1902,24 @@ if(TARGET Vulkan::Headers) set_tests_properties(d3d12_xdxr_rt_check PROPERTIES FIXTURES_REQUIRED d3d12_xdxr_cases SKIP_RETURN_CODE 77) endif() + # XboxBvhBuilder.dll served by the layer's builder (RT-5, boot stop 18): the seven exports the executable imports, + # through the shim registry as the title binds them; the structures are checked like d3d12_xdxr_rt's. + set(LEONIDA_XBOX_BVH_BUILDER_OUT "${CMAKE_CURRENT_BINARY_DIR}/xbox_bvh_builder_cases") + add_executable(xbox_bvh_builder_test test/xbox_bvh_builder_test.cpp shims/xbox_bvh_builder.cpp shims/registry.cpp) + target_link_libraries(xbox_bvh_builder_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(xbox_bvh_builder_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(xbox_bvh_builder_test PRIVATE /W4 /permissive- /utf-8) + target_link_options(xbox_bvh_builder_test PRIVATE /OPT:NOREF) + add_test(NAME xbox_bvh_builder COMMAND xbox_bvh_builder_test "${LEONIDA_XBOX_BVH_BUILDER_OUT}") + set_tests_properties(xbox_bvh_builder PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60 FIXTURES_SETUP xbox_bvh_builder_cases) + add_test(NAME xbox_bvh_builder_console COMMAND xbox_bvh_builder_test --console) + set_tests_properties(xbox_bvh_builder_console PROPERTIES ENVIRONMENT "LEONIDA_BVH_BUILDER=console") + if(Python3_FOUND) + add_test(NAME xbox_bvh_builder_check COMMAND "${Python3_EXECUTABLE}" -I + "${CMAKE_CURRENT_SOURCE_DIR}/../tools/xdxr_bvh.py" check-build "${LEONIDA_XBOX_BVH_BUILDER_OUT}" --rays 1000) + set_tests_properties(xbox_bvh_builder_check PROPERTIES FIXTURES_REQUIRED xbox_bvh_builder_cases SKIP_RETURN_CODE 77) + endif() + # GCL8's QueryInterface and its one method need an allocator and a list, not a Vulkan device. add_executable(d3d12_gcl8_test test/d3d12_gcl8_test.cpp) target_link_libraries(d3d12_gcl8_test PRIVATE gta6rt_d3d12_com) @@ -2102,14 +2233,30 @@ if(TARGET Vulkan::Headers) -o ${_indirect_count_spv} ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_indirect_dispatch_count.comp DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/test/glsl/cs_indirect_dispatch_count.comp COMMENT "Compiling the counted indirect dispatch test shader" VERBATIM) - add_executable(d3d12_indirect_dispatch_count_test test/d3d12_indirect_dispatch_count_test.cpp - ${_indirect_count_spv}) + add_custom_target(gta6rt_indirect_count_shader DEPENDS ${_indirect_count_spv}) + add_executable(d3d12_indirect_dispatch_count_test test/d3d12_indirect_dispatch_count_test.cpp) + add_dependencies(d3d12_indirect_dispatch_count_test gta6rt_indirect_count_shader) target_link_libraries(d3d12_indirect_dispatch_count_test PRIVATE gta6rt_d3d12_com d3d12 dxgi version) target_compile_definitions(d3d12_indirect_dispatch_count_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX LEONIDA_TEST_INDIRECT_COUNT_SPV="${_indirect_count_spv}") target_compile_options(d3d12_indirect_dispatch_count_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_indirect_dispatch_count COMMAND d3d12_indirect_dispatch_count_test) set_tests_properties(d3d12_indirect_dispatch_count PROPERTIES SKIP_RETURN_CODE 77) + # The cache vk_pipeline_check saves has to hit on the runtime's device (docs/pipeline_check.md): the checker + # compiles that shader, then the test creates the same pipeline on the runtime's device from the cache. + add_executable(pipeline_cache_seed_test test/pipeline_cache_seed_test.cpp) + add_dependencies(pipeline_cache_seed_test vk_pipeline_check gta6rt_indirect_count_shader) + target_link_libraries(pipeline_cache_seed_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(pipeline_cache_seed_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(pipeline_cache_seed_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME pipeline_cache_seed COMMAND "${CMAKE_COMMAND}" + "-DCHECKER=$" + "-DTEST=$" + "-DSHADER=${_indirect_count_spv}" + "-DTEST_DIR=${CMAKE_CURRENT_BINARY_DIR}/pipeline_cache_seed" + "-DRUNNER=${CMAKE_CROSSCOMPILING_EMULATOR}" + -P "${CMAKE_CURRENT_SOURCE_DIR}/test/check_pipeline_cache_seed.cmake") + set_tests_properties(pipeline_cache_seed PROPERTIES SKIP_REGULAR_EXPRESSION "SKIP: ") endif() # What Close returns after one recorded call, against WARP; today's differences are listed in the test. @@ -2408,6 +2555,15 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_translated_draw COMMAND d3d12_translated_draw_test) set_tests_properties(d3d12_translated_draw PROPERTIES SKIP_RETURN_CODE 77) + # The console's rectangle and quad lists (src/rect_list_geometry.h), through the same translated vs_m15 / ps_m15. + add_executable(d3d12_rect_list_test test/d3d12_rect_list_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_M15_FILES}) + target_link_libraries(d3d12_rect_list_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_rect_list_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_M15_DIR="${LEONIDA_M15_DIR}") + target_compile_options(d3d12_rect_list_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_rect_list COMMAND d3d12_rect_list_test) + set_tests_properties(d3d12_rect_list PROPERTIES SKIP_RETURN_CODE 77) + # vk_bindless_test (the bindless set and its table at the Vulkan level, no D3D12) takes the translated vs_ids, # ps_tex and ps_imgatomic; it was only run by scripts/run_gpu_tests.py and check.py until D3D-314 needed it. set(LEONIDA_BINDLESS_DIR ${CMAKE_CURRENT_BINARY_DIR}/generated/bindless_shaders) @@ -2741,6 +2897,14 @@ if(TARGET Vulkan::Headers) target_compile_options(d3d12_compute_test PRIVATE /W4 /permissive- /utf-8) add_test(NAME d3d12_compute COMMAND d3d12_compute_test) set_tests_properties(d3d12_compute PROPERTIES SKIP_RETURN_CODE 77) + # A buffer at the title's own VA (device slot 133) read by the same shader through a root view and a V#. + add_executable(d3d12_title_va_test test/d3d12_title_va_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_CS}) + target_link_libraries(d3d12_title_va_test PRIVATE gta6rt_d3d12_com) + target_compile_definitions(d3d12_title_va_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX + LEONIDA_TEST_CS_SPV="${LEONIDA_TEST_CS}") + target_compile_options(d3d12_title_va_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_title_va COMMAND d3d12_title_va_test) + set_tests_properties(d3d12_title_va PROPERTIES SKIP_RETURN_CODE 77) # Compute PSOs from FSPX programs (docs/fspx.md): an ACCC container at slot 62 and a bare kind-6 program. add_executable(d3d12_fspx_compute_test test/d3d12_fspx_compute_test.cpp shims/d3d12_xs_device.cpp ${LEONIDA_TEST_CS}) target_link_libraries(d3d12_fspx_compute_test PRIVATE gta6rt_d3d12_com) @@ -3070,6 +3234,13 @@ if(TARGET Vulkan::Headers) add_test(NAME d3d12_clear_formats COMMAND d3d12_clear_formats_test) set_tests_properties(d3d12_clear_formats PROPERTIES SKIP_RETURN_CODE 77) + add_executable(d3d12_a8_dimensions_test test/d3d12_a8_dimensions_test.cpp) + target_link_libraries(d3d12_a8_dimensions_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) + target_compile_definitions(d3d12_a8_dimensions_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + target_compile_options(d3d12_a8_dimensions_test PRIVATE /W4 /permissive- /utf-8) + add_test(NAME d3d12_a8_dimensions COMMAND d3d12_a8_dimensions_test) + set_tests_properties(d3d12_a8_dimensions PROPERTIES SKIP_RETURN_CODE 77) + # SetDescriptorHeaps validation, Reset/ClearState/bundle parity, lifetime pinning, direct-index flags. add_executable(d3d12_set_descriptor_heaps_test test/d3d12_set_descriptor_heaps_test.cpp) target_link_libraries(d3d12_set_descriptor_heaps_test PRIVATE gta6rt_d3d12_com d3d12 dxgi) @@ -3081,7 +3252,7 @@ if(TARGET Vulkan::Headers) # The loader can create this device instead of the host's (D3D12XboxCreateDevice, LEONIDA_D3D12=vulkan). if(TARGET gta6rt) - target_link_libraries(gta6rt PRIVATE gta6rt_d3d12_com) + target_link_libraries(gta6rt PRIVATE gta6rt_d3d12_com user32) # user32: the PresentX window target_compile_definitions(gta6rt PRIVATE LEONIDA_VULKAN_DEVICE) # A stand-in title that imports d3d12_xs.dll!D3D12XboxCreateDevice and runs a clear and a readback on the @@ -3241,6 +3412,12 @@ if(TARGET Vulkan::Headers) target_compile_definitions(replay_readback_stages_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) endif() add_test(NAME replay_readback_stages COMMAND replay_readback_stages_test) + add_executable(replay_quad_list_test test/replay_quad_list_test.cpp) + target_link_libraries(replay_quad_list_test PRIVATE Vulkan::Headers) + if(WIN32) + target_compile_definitions(replay_quad_list_test PRIVATE WIN32_LEAN_AND_MEAN NOMINMAX) + endif() + add_test(NAME replay_quad_list COMMAND replay_quad_list_test) # emit of an enhanced texture barrier: no heap allocation for one layout piece, one barrier for each piece (no GPU). add_executable(replay_texture_barrier_test test/replay_texture_barrier_test.cpp) target_link_libraries(replay_texture_barrier_test PRIVATE Vulkan::Headers) @@ -3341,6 +3518,9 @@ if(TARGET Vulkan::Headers) add_executable(arena_size_test test/arena_size_test.cpp) target_link_libraries(arena_size_test PRIVATE Vulkan::Headers) add_test(NAME arena_size COMMAND arena_size_test) + # Title-placed buffer VAs (device slot 133) and the console VA shaders reach them by (src/title_va_alias.h). + add_executable(title_va_alias_test test/title_va_alias_test.cpp) + add_test(NAME title_va_alias COMMAND title_va_alias_test) # Queue construction cleans its Vulkan handles if holder registration runs out of host memory. add_executable(vk_queue_constructor_oom_test test/vk_queue_constructor_oom_test.cpp) target_link_libraries(vk_queue_constructor_oom_test PRIVATE Vulkan::Headers ${CMAKE_DL_LIBS}) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 4f4904e965..a1aa3ccc55 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -1,3 +1,4 @@ +#include #include "d3d12_com.h" #include "d3d12_stubs.h" // generated @@ -6,13 +7,16 @@ #include "d3d12_trace.h" #include "d3d12_xs_device.h" #include "../src/gfx10_descriptors.h" +#include "../src/title_va_alias.h" #include #include #include #include +#include #include #include +#include #include #include #include @@ -198,6 +202,8 @@ class GraphicsCommandList final } const leonida::CommandList& commands() const { return list_; } + // The descriptor tables this recording binds (console VAs), for the scan before a submission. + const std::vector>& tables() const { return tables_; } // The pipeline states and root signatures the recording names (it holds a reference to each until Reset). const std::vector& pinned() const { return held_; } UINT front_stencil_ref() const { return front_stencil_ref_; } @@ -234,6 +240,7 @@ class GraphicsCommandList final record_into(command_allocator); invalid_ = false; calls_.clear(); + tables_.clear(); release_held(); // what the old recording used: it was replayed at ExecuteCommandLists reset_state(state); // Reset returns every list state to its default if (type_ == D3D12_COMMAND_LIST_TYPE_BUNDLE) set_initial_pipeline(state); // reset_state holds it @@ -834,6 +841,15 @@ class GraphicsCommandList final } else if (count_buffer_offset != 0) { return check(false); } + if (kind == leonida::IndirectKind::dispatch_mesh) { + // Not replayed yet (#3777 replays it as vkCmdDrawMeshTasksIndirectEXT): nothing is recorded, and the + // first such call says so. The list stays valid. + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12: ExecuteIndirect with a DISPATCH_MESH signature is not replayed yet; " + "nothing was recorded\n"); + return; + } // The record size is checked for every call: D3D12 rejects a signature whose stride cannot hold a record // even when no command runs. The argument span is what the signature can walk, max_command_count * stride: // the host refuses a range that ends past the buffer (`240` with stride `20` in a `256`-byte buffer), and @@ -1240,11 +1256,19 @@ class GraphicsCommandList final return; const RootArgumentLayout::Parameter* p = parameter(state, index, type); if (!p) return; + // A root view into the title's own memory (a slot-133 buffer, a constant ring) gets the console VA of a GPU + // copy of it, so the shader's heap_base + VA reaches it (src/title_va_alias.h). A descriptor table is in one + // of the layer's heaps: kept, and its buffer V#s are rewritten the same way before each submission. + if (type == rt::rootsig::ParamType::Descriptor) + va = leonida::title_va_aliases().resolve(va, kRootViewBytes, leonida::TitleVaAliases::root_view); + else if (va && p->table_descriptors && (tables_.empty() || tables_.back().first != va)) + tables_.push_back({va, p->table_descriptors}); const std::uint32_t first = first_dword(state, *p); write(state, first, std::uint32_t(va)); // In the compute layout a descriptor table is one dword, the 32-bit VA of its first descriptor (the heaps // live below 4 GiB); a root view keeps both halves. The graphics layout gives every address two dwords. - if (!(is_compute(state) && type == rt::rootsig::ParamType::Table)) write(state, first + 1, std::uint32_t(va >> 32)); + if (!((is_compute(state) || local_graphics_stage_layout()) && type == rt::rootsig::ParamType::Table)) + write(state, first + 1, std::uint32_t(va >> 32)); } D3D12_COMMAND_LIST_TYPE type_; @@ -1264,6 +1288,10 @@ class GraphicsCommandList final std::uint32_t topology_ = 0; // D3D_PRIMITIVE_TOPOLOGY_UNDEFINED std::array vertex_buffers_{}; leonida::IndexBufferView index_{}; + // SetGraphicsRootDescriptorTable / SetComputeRootDescriptorTable: VA, CBV/SRV/UAV slots the signature declares + std::vector> tables_; + // The span a root view may read: D3D12's largest constant buffer (4096 x 16 bytes). + static constexpr std::uint64_t kRootViewBytes = 65536; leonida::Viewport viewport_{}; leonida::Rect scissor_{}; std::array render_targets_{}; @@ -1378,13 +1406,16 @@ class GraphicsCommandList final void set_vertex_buffers(UINT start, UINT count, const D3D12_VERTEX_BUFFER_VIEW* views) { if (count) draw_views_stale_ = true; - for (UINT i = 0; i < count; ++i) + for (UINT i = 0; i < count; ++i) { + if (views) leonida::title_va_aliases().note(views[i].BufferLocation, leonida::TitleVaAliases::vertex_view); vertex_buffers_[start + i] = views ? leonida::VertexBufferView{views[i].BufferLocation, views[i].SizeInBytes, views[i].StrideInBytes} : leonida::VertexBufferView{}; + } } void set_index_buffer(const D3D12_INDEX_BUFFER_VIEW* view) { + if (view) leonida::title_va_aliases().note(view->BufferLocation, leonida::TitleVaAliases::index_view); index_ = view ? leonida::IndexBufferView{view->BufferLocation, view->SizeInBytes, u(view->Format)} : leonida::IndexBufferView{}; } @@ -1644,6 +1675,21 @@ class CommandQueue final recorded.push_back(&list->commands()); graphics.push_back(list); } + // Buffer V#s the title wrote into a bound table itself may name its own memory: rewritten to a GPU copy's + // console VA before the copies are refreshed for this submission (src/title_va_alias.h). + { + std::map tables; // each table once, with the most slots it was bound with + for (const GraphicsCommandList* list : graphics) + for (const auto& [table, descriptors] : list->tables()) + tables[table] = std::max(tables[table], descriptors); + if (!tables.empty()) { + const auto start = std::chrono::steady_clock::now(); + for (const auto& [table, descriptors] : tables) leonida::title_va_aliases().scan_table(table, descriptors); + leonida::title_va_aliases().note_scan(std::uint64_t( + std::chrono::duration_cast(std::chrono::steady_clock::now() - start) + .count())); + } + } last_result_ = queue_.execute(recorded, [&graphics] { return pin_lists(graphics); }); d3d12_trace::record(method, last_result_ == leonida::ReplayResult::success ? "ok" : "failed"); if (last_result_ != leonida::ReplayResult::success) diff --git a/runtime/shims/d3d12_com.h b/runtime/shims/d3d12_com.h index d0f3b528aa..2811ed1f3d 100644 --- a/runtime/shims/d3d12_com.h +++ b/runtime/shims/d3d12_com.h @@ -10,6 +10,8 @@ // - the CPU handle of an RTV or DSV points at a leonida::TargetView in the device's descriptor heap. #pragma once +#include + #include #include #include @@ -156,6 +158,9 @@ struct VulkanDeviceInfo { bool fragment_shader_barycentric = false; bool fragment_shader_interlock = false; bool maintenance8 = false; + // VK_KHR_maintenance5, enabled where its VK_FORMAT_A8_UNORM_KHR can be sampled and is a colour attachment the GPU + // can blend: A8_UNORM render targets are then stored in that format (other A8_UNORM textures stay R8_UNORM). + bool a8_render_target = false; // The instance enabled VK_EXT_debug_utils: SetMarker/BeginEvent/EndEvent become debug labels. Otherwise they // do nothing. bool debug_utils = false; @@ -383,12 +388,23 @@ std::unique_ptr create_window_presenter(ID3D12Device* device, H // exist, because a mesh shader (s16) and a pixel shader (s8) share one push-constant block); // - compute: rt::rootsig::pack_stage(Stage::Compute), the measured console layout (from s4, one dword per table). // A layout that refuses the signature is marked unusable; binding the signature there invalidates the list. +// LOCAL EXPERIMENT: LEONIDA_GRAPHICS_STAGE_LAYOUT=1 lays graphics root arguments out as the console does for the +// vertex, pixel and geometry stages (rt::rootsig::pack_stage: from s8, a descriptor table in one dword) instead of +// from s0 with two dwords per address. +inline bool local_graphics_stage_layout() { + static const bool on = [] { const char* v = std::getenv("LEONIDA_GRAPHICS_STAGE_LAYOUT"); return v && *v == '1'; }(); + return on; +} + struct RootArgumentLayout { struct Parameter { rt::rootsig::ParamType type; std::uint32_t user_offset; // graphics: first dword; unused for a parameter with no dwords std::uint32_t constant_count; // constants only std::uint32_t compute_offset = rt::rootsig::kNoSgpr; // compute: first user SGPR + // A table: the CBV/SRV/UAV slots its ranges declare (an unbounded range counts as 1024), for the scan of + // title-written V#s before a submission (src/title_va_alias.h). 0: a sampler table, or not a table. + std::uint32_t table_descriptors = 0; }; std::vector parameters; std::uint32_t flags = 0; // D3D12_ROOT_SIGNATURE_FLAGS from the serialized blob diff --git a/runtime/shims/d3d12_com_object.h b/runtime/shims/d3d12_com_object.h index c7d46d775f..f1af871b11 100644 --- a/runtime/shims/d3d12_com_object.h +++ b/runtime/shims/d3d12_com_object.h @@ -25,6 +25,15 @@ template class Object : public Stubs { public: ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } + // Adds a reference unless the count already reached zero (the object is being destroyed). For a caller that found + // the object through a registry it does not own a reference to; the registry entry must still be locked then. + bool try_add_ref() { + ULONG count = refs_.load(); + while (count) { + if (refs_.compare_exchange_weak(count, count + 1)) return true; + } + return false; + } ULONG STDMETHODCALLTYPE Release() override { const ULONG left = --refs_; if (!left) delete static_cast(this); diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 0273f9339b..1a9f1d6e48 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -18,17 +18,21 @@ #include "../src/arena_size.h" #include "../src/gfx10_descriptors.h" #include "../src/depth24_fragment.h" +#include "../src/rect_list_geometry.h" #include "../src/uav_clear.h" #include "../src/vulkan_bindless.h" #include "../src/vulkan_memory.h" #include "../src/vulkan_mesh_limits.h" #include "../src/resource_tiling.h" #include "../src/cached_pso.h" +#include "../src/pipeline_cache_file.h" +#include "../src/pipeline_cache_store.h" #include "../src/conservative_raster.h" #include "../src/resource_detile.h" #include "../src/shader_library.h" #include "../src/spirv_f16_halves.h" #include "../src/spirv_stores.h" +#include "../src/title_va_alias.h" #include "../src/vulkan_present.h" #include "../src/vulkan_device_filter.h" #include "../src/vulkan13_features.h" @@ -42,6 +46,7 @@ #include #include #include +#include #include #include #include @@ -51,10 +56,12 @@ #include #include #include +#include #include #include #include #include +#include #include namespace rt::d3d12 { @@ -65,8 +72,13 @@ namespace { constexpr UINT kDescriptorSize = descriptor_size; // The first 64 KiB of the GPU address arena are never handed out: VA 0 stays invalid, and the page is kept zero // for unbound vertex and index buffers to read (D3D12 reads zeros there). -constexpr VkDeviceSize kArenaReserved = 64 * 1024; +constexpr VkDeviceSize kZeroPage = 64 * 1024; // zeroed: what unbound vertex and index buffers read +constexpr std::uint32_t kQuadIndicesPerQuad = leonida::quad_triangle_indices.size(); +constexpr std::uint32_t kQuadIndexCount = 16 * 1024 * kQuadIndicesPerQuad; +constexpr VkDeviceSize kArenaReserved = kZeroPage + VkDeviceSize(kQuadIndexCount) * sizeof(std::uint32_t); static_assert(sizeof(leonida::TargetView) <= kDescriptorSize); +// pipeline_cache_store.h reads this layout without vulkan.h (D3D-704); remember the two. +static_assert(sizeof(VkPipelineCacheHeaderVersionOne) == leonida::pipeline_cache_store::header_bytes); // The shader model and root signature version this layer can honour. Nothing in the runtime compiles DXIL: the // game's shaders arrive as SPIR-V from the offline translator, and the only DXIL path (the BVH builder) is lowered @@ -85,6 +97,86 @@ void log_once(const char* what, int value) { if (seen.insert({what, value}).second) std::fprintf(stderr, "[rt] d3d12: %s %d\n", what, value); } +// The base address a V# gets for a buffer address: in the title's own memory (a slot-133 buffer, a constant ring), +// the console VA of a GPU copy of it (src/title_va_alias.h, docs/d3d12_vulkan.md section 3.3); anything else +// unchanged. A V# keeps 48 address bits. An arena copy always fits; an imported buffer's address is its device +// address minus heap_base, which wraps when the driver put it below the arena: logged, and written as before. +std::uint64_t vsharp_address(std::uint64_t va, std::uint64_t bytes, + leonida::TitleVaAliases::Kind kind = leonida::TitleVaAliases::created_view) { + const std::uint64_t to = leonida::title_va_aliases().resolve(va, bytes, kind); + if (to != va && (to >> 48)) + log_once("a V# names a title-placed buffer whose GPU copy lies below heap_base, out of a V#'s 48 bits; " + "address bits 48-63:", + int(to >> 48)); + return to; +} + +// The CBV/SRV/UAV slots a descriptor table declares: the end of its furthest range (D3D12 appends a range at +// D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND), an unbounded range counted as 1024. 0 for a sampler table or no table. +std::uint32_t table_view_descriptors(const rt::rootsig::RootParameter& param) { + if (param.type != rt::rootsig::ParamType::Table) return 0; + constexpr std::uint32_t kUnbounded = 1024; + std::uint64_t next = 0, end = 0; + for (const auto& range : param.ranges) { + const std::uint64_t start = range.offset_in_table == D3D12_DESCRIPTOR_RANGE_OFFSET_APPEND ? next + : range.offset_in_table; + const std::uint64_t count = range.num_descriptors == UINT_MAX ? kUnbounded : range.num_descriptors; + next = start + count; + if (range.range_type != D3D12_DESCRIPTOR_RANGE_TYPE_SAMPLER) end = std::max(end, next); + } + return std::uint32_t(std::min(end, kUnbounded)); +} + +// memcpy that a page fault ends instead of killing the process: the title may decommit a page between the +// VirtualQuery that saw it committed and the read. No C++ objects here: it is a __try frame. +// `streaming` reads with MOVNTDQA, for write-combined pages: ordinary loads from them are not cached, and memcpy +// read 64 MiB of them in 253 ms on a Core i9-13900K (253 MiB/s), MOVNTDQA in 13 to 17 ms (4 to 5 GiB/s). Paid at every submission. +#if defined(__clang__) && defined(_M_X64) +__attribute__((target("sse4.1"))) +#endif +bool copy_guarded(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes, bool streaming) { + __try { + if (streaming) { + const std::size_t head = std::min(bytes, (0 - reinterpret_cast(from)) & 63); + std::memcpy(to, from, head); + to += head, from += head, bytes -= head; + for (; bytes >= 64; to += 64, from += 64, bytes -= 64) { + const auto* in = reinterpret_cast(from); + const __m128i a = _mm_stream_load_si128(in), b = _mm_stream_load_si128(in + 1); + const __m128i c = _mm_stream_load_si128(in + 2), d = _mm_stream_load_si128(in + 3); + auto* out = reinterpret_cast<__m128i*>(to); + _mm_storeu_si128(out, a), _mm_storeu_si128(out + 1, b); + _mm_storeu_si128(out + 2, c), _mm_storeu_si128(out + 3, d); + } + } + std::memcpy(to, from, bytes); + return true; + } __except (EXCEPTION_EXECUTE_HANDLER) { + return false; + } +} + +// Copies [from, from + bytes) of the title's address space to `to`, for a slot-133 shadow buffer. Only committed, +// readable pages are read (xmem commits on first touch, and a read of a reserved page faults); the rest is zero. +void copy_title_pages(std::uint8_t* to, const std::uint8_t* from, std::size_t bytes) { + constexpr DWORD readable = PAGE_READONLY | PAGE_READWRITE | PAGE_WRITECOPY | PAGE_EXECUTE_READ | + PAGE_EXECUTE_READWRITE | PAGE_EXECUTE_WRITECOPY; + for (std::size_t at = 0; at < bytes;) { + MEMORY_BASIC_INFORMATION region{}; + std::size_t run = bytes - at; + bool read = false; + if (VirtualQuery(from + at, ®ion, sizeof(region))) { + const auto end = reinterpret_cast(region.BaseAddress) + region.RegionSize; + run = std::min(run, end - reinterpret_cast(from + at)); + read = region.State == MEM_COMMIT && (region.Protect & readable) && + !(region.Protect & (PAGE_GUARD | PAGE_NOACCESS)); + } + if (!read || !copy_guarded(to + at, from + at, run, (region.Protect & PAGE_WRITECOMBINE) != 0)) + std::memset(to + at, 0, run); + at += run; + } +} + // Two test settings that make the standalone device look like a GPU with fewer Vulkan queues, so the path where D3D12 // queues share a VkQueue runs on any GPU; both together give the Intel UHD 770 on Windows and lavapipe (one family, // one queue). LEONIDA_VK_MAX_QUEUES_PER_FAMILY=N (1 to 16): at most N VkQueues per queue family (unset, or not a @@ -134,6 +226,25 @@ std::filesystem::path pipeline_cache_path() { return std::filesystem::path(path).parent_path() / L"pipeline_cache.bin"; } +// What the runtime itself compiled, kept next to the offline seed and never written over it (D3D-704). +std::filesystem::path pipeline_cache_session_path() { + std::filesystem::path path = pipeline_cache_path(); + if (!path.empty()) path.replace_filename(L"pipeline_cache.session.bin"); + return path; +} + +// LEONIDA_PIPELINE_CACHE_BYTES, in bytes; 0 turns the session file off. One line for a value that is not a number. +std::size_t pipeline_cache_save_limit() { + char text[32] = {}; + size_t length = 0; + const bool present = getenv_s(&length, text, "LEONIDA_PIPELINE_CACHE_BYTES") == 0 && length > 1; + const auto limit = leonida::pipeline_cache_store::parse_save_limit(present ? text : ""); + if (!limit.valid) + std::fprintf(stderr, "[rt] d3d12: LEONIDA_PIPELINE_CACHE_BYTES=%s is not a byte count; using %zu\n", text, + limit.bytes); + return limit.bytes; +} + // A corpus cache may be several GiB. Keep the read-only view alive through vkCreatePipelineCache // and deny writers while the view is in use. class PipelineCacheSeed { @@ -166,13 +277,7 @@ class PipelineCacheSeed { std::size_t size() const { return size_; } bool compatible(const leonida::cached_pso::Identity& identity) const { - static_assert(sizeof(VkPipelineCacheHeaderVersionOne) == 32); - VkPipelineCacheHeaderVersionOne header{}; - // The header is little-endian, like the host. The driver interprets the opaque payload. - std::memcpy(&header, data_, sizeof(header)); - return header.headerSize == sizeof(header) && header.headerVersion == VK_PIPELINE_CACHE_HEADER_VERSION_ONE && - header.vendorID == identity.vendor && header.deviceID == identity.device && - std::memcmp(header.pipelineCacheUUID, identity.cache_uuid, VK_UUID_SIZE) == 0; + return leonida::pipeline_cache_store::header_matches(data_, size_, identity); } private: @@ -200,6 +305,95 @@ VkPipelineCache create_seeded_pipeline_cache(PFN_vkCreatePipelineCache create_ca return cache; } +// D3D-704: merges what earlier launches compiled into the cache the pipelines are created against. The offline seed +// and the session file cannot be handed over as one VkPipelineCacheCreateInfo -- Vulkan reads a single blob -- so the +// session cache is created on its own and merged in. A missing, foreign or corrupt session file leaves the cache as +// it was, and so does a driver that does not expose vkMergePipelineCaches. +void merge_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache, + const leonida::cached_pso::Identity& identity) { + if (!cache || !vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache || !vk.vkMergePipelineCaches) return; + if (!pipeline_cache_save_limit()) return; // LEONIDA_PIPELINE_CACHE_BYTES=0 turns the session file off + const PipelineCacheSeed seed(pipeline_cache_session_path()); + if (!seed.data()) return; + if (!seed.compatible(identity)) { + std::fprintf(stderr, "[rt] d3d12: pipeline_cache.session.bin does not match this Vulkan device\n"); + return; + } + const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO, nullptr, 0, seed.size(), + seed.data()}; + VkPipelineCache session = VK_NULL_HANDLE; + if (vk.vkCreatePipelineCache(device, &create, nullptr, &session) != VK_SUCCESS) { + std::fprintf(stderr, "[rt] d3d12: Vulkan declined pipeline_cache.session.bin\n"); + return; + } + const VkResult result = vk.vkMergePipelineCaches(device, cache, 1, &session); + vk.vkDestroyPipelineCache(device, session, nullptr); + if (result == VK_SUCCESS) + std::fprintf(stderr, "[rt] d3d12: merged %zu bytes from pipeline_cache.session.bin\n", seed.size()); + else + std::fprintf(stderr, "[rt] d3d12: vkMergePipelineCaches on pipeline_cache.session.bin returned %d; ignored\n", + static_cast(result)); +} + +bool startup_cache_checkpoints_enabled() { + static const bool enabled = [] { + wchar_t value[2]{}; + return GetEnvironmentVariableW(L"LEONIDA_STARTUP_CACHE_CHECKPOINTS", value, 2) == 1 && value[0] == L'1'; + }(); + return enabled; +} + +// Writes the session cache at a startup checkpoint or during device teardown. The size cap applies to either write. +void save_session_pipeline_cache(const leonida::VulkanDeviceFunctions& vk, VkDevice device, VkPipelineCache cache) { + if (!cache || !vk.vkGetPipelineCacheData) return; + const std::size_t limit = pipeline_cache_save_limit(); + if (!limit) return; // LEONIDA_PIPELINE_CACHE_BYTES=0 turns the session file off + const auto over_limit = [limit](std::size_t size) { + std::fprintf(stderr, + "[rt] d3d12: pipeline cache is %zu bytes, over the %zu-byte session limit " + "(LEONIDA_PIPELINE_CACHE_BYTES); pipeline_cache.session.bin left as it was\n", + size, limit); + }; + std::size_t size = 0; + if (vk.vkGetPipelineCacheData(device, cache, &size, nullptr) != VK_SUCCESS || + size <= sizeof(VkPipelineCacheHeaderVersionOne)) + return; + if (size > limit) { + over_limit(size); + return; + } + std::vector data; + try { + // Leave room in case another thread grows the cache between the size query and the read. + data.resize(size + (size >> 4)); + } catch (const std::bad_alloc&) { + std::fprintf(stderr, + "[rt] d3d12: no memory for the %zu-byte pipeline cache; pipeline_cache.session.bin not " + "written\n", + size); + return; + } + std::size_t written = data.size(); + const VkResult result = vk.vkGetPipelineCacheData(device, cache, &written, data.data()); + if (result != VK_SUCCESS || written < sizeof(VkPipelineCacheHeaderVersionOne) || written > data.size()) { + std::fprintf(stderr, + "[rt] d3d12: could not read the pipeline cache (%d); pipeline_cache.session.bin not written\n", + static_cast(result)); + return; + } + if (written > limit) { + over_limit(written); + return; + } + const std::filesystem::path path = pipeline_cache_session_path(); + if (path.empty()) return; + if (const std::error_code error = write_pipeline_cache_file(path, data.data(), written)) { + std::fprintf(stderr, "[rt] d3d12: pipeline_cache.session.bin not written: %s\n", error.message().c_str()); + return; + } + std::fprintf(stderr, "[rt] d3d12: wrote %zu bytes to pipeline_cache.session.bin\n", written); +} + // A shader whose subgroup size cannot be had runs at the device's: inexact if it crosses the halves of a wave64 (or, // for a wave32 shader on a 64-wide default, reads lanes that are not its own). Logged once per stage with the first // shader's name, then again at 10, 100, 1000... of that stage so a whole corpus stays readable. @@ -231,12 +425,25 @@ void report_subgroup_unavailable(const leonida::ShaderEntry& entry, const leonid "subgroup size)\n", entry.stage.c_str()); } +// VK_FORMAT_A8_UNORM_KHR where the Vulkan headers have VK_KHR_maintenance5. Older headers have no A8 render targets: +// VulkanDeviceInfo::a8_render_target is then never set, so this is never used as UNDEFINED. +#ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME +constexpr VkFormat kA8UnormFormat = VK_FORMAT_A8_UNORM_KHR; +#else +constexpr VkFormat kA8UnormFormat = VK_FORMAT_UNDEFINED; +#endif + struct Format { VkFormat format = VK_FORMAT_UNDEFINED; VkImageAspectFlags aspects = 0; bool typeless = false; // created with MUTABLE_FORMAT so typed views can reinterpret it bool d24_as_float = false; // D24_UNORM_S8_UINT stored as D32_SFLOAT_S8_UINT (no D24 on the GPU) bool d24 = false; // a D24_UNORM_S8_UINT family format, native or stored as D32 + // An A8_UNORM render target stored as VK_FORMAT_A8_UNORM_KHR (VulkanDeviceInfo::a8_render_target): its RTVs render + // to the alpha channel and its SRVs view it in that format, whose one channel the T# names as X (gfx10's + // channels_a). Other A8_UNORM textures are R8_UNORM images. Vulkan puts A8 in a compatibility class of its own, + // so one image cannot be viewed both ways. + bool a8_as_alpha = false; // A UAV texture whose format has no storage support, stored as the mutable unsigned image `format` names (R32_UINT // for R9G9B9E5_SHAREDEXP, R16_UINT for B5G5R5A1_UNORM): the format its SRVs, RTVs and T#s use. Its storage view is // `format`, in the uint class; shaders write the packed bits. UNDEFINED for every other texture. @@ -598,16 +805,19 @@ struct DeviceState { leonida::cached_pso::Identity pso_identity; // what GetCachedBlob records and CachedPSO is checked against std::once_flag pipeline_cache_once; VkPipelineCache pipeline_cache_handle = VK_NULL_HANDLE; + std::mutex startup_cache_checkpoint_mutex; VkPipelineCache pipeline_cache() { std::call_once(pipeline_cache_once, [this] { const auto& vk = context->vk; if (!vk.vkCreatePipelineCache || !vk.vkDestroyPipelineCache) return; pipeline_cache_handle = create_seeded_pipeline_cache(vk.vkCreatePipelineCache, info.device, pso_identity); - if (pipeline_cache_handle) return; - const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; - if (vk.vkCreatePipelineCache(info.device, &create, nullptr, &pipeline_cache_handle) != VK_SUCCESS) - pipeline_cache_handle = VK_NULL_HANDLE; + if (!pipeline_cache_handle) { + const VkPipelineCacheCreateInfo create{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; + if (vk.vkCreatePipelineCache(info.device, &create, nullptr, &pipeline_cache_handle) != VK_SUCCESS) + pipeline_cache_handle = VK_NULL_HANDLE; + } + merge_session_pipeline_cache(vk, info.device, pipeline_cache_handle, pso_identity); }); // Without EXTERNALLY_SYNCHRONIZED_BIT the driver synchronizes concurrent pipeline creation using this cache. return pipeline_cache_handle; @@ -642,6 +852,159 @@ struct DeviceState { // VK_EXT_external_memory_host; null unless info.host_pointer_alignment is set and the entry point loaded. PFN_vkGetMemoryHostPointerPropertiesEXT get_host_pointer_properties = nullptr; + // The live shadow buffers of Xbox device slot 133 (Resource::create_shadow_buffer): title-placed buffers whose + // pages the driver would not import. Each is re-copied from the title's pages before every submission of + // command lists (VulkanContext::set_before_execute), since nothing says which pages the title wrote. The first + // per-submission copy of each buffer size is timed and logged, so the cost shows in a run's log. + struct Shadow { + const std::uint8_t* pages; // the title's + std::uint8_t* mapped; // the shadow's memory + std::size_t size; + }; + std::mutex shadow_mutex; // a leaf: nothing else is taken under it + std::vector shadows; + std::set shadow_sizes_logged; + + void add_shadow(const Shadow& shadow) { + std::lock_guard lock(shadow_mutex); + shadows.push_back(shadow); + } + void remove_shadow(const std::uint8_t* mapped) { + std::lock_guard lock(shadow_mutex); + std::erase_if(shadows, [mapped](const Shadow& s) { return s.mapped == mapped; }); + } + void refresh_shadows() { + std::lock_guard lock(shadow_mutex); + for (const Shadow& s : shadows) { + if (!shadow_sizes_logged.insert(s.size).second) { + copy_title_pages(s.mapped, s.pages, s.size); + continue; + } + const auto start = std::chrono::steady_clock::now(); + copy_title_pages(s.mapped, s.pages, s.size); + const double ms = + std::chrono::duration(std::chrono::steady_clock::now() - start).count(); + std::fprintf(stderr, "[rt] d3d12: slot-133 shadow buffer of %llu KiB: copied from the title's pages in " + "%.3f ms (%.0f MiB/s), paid at every submission\n", + static_cast(s.size / 1024), ms, + ms > 0 ? double(s.size) / (1024.0 * 1024.0) / (ms / 1000.0) : 0.0); + } + } + + // Windows of the title's own memory in the GPU address arena (src/title_va_alias.h, docs/d3d12_vulkan.md + // section 3.3 "Title-chosen addresses"): a root view or buffer V# that names the title's memory outside any + // slot-133 buffer (a per-frame constant ring, #8862 section 3.5) gets a copy of the 64 KiB-aligned pages it + // covers, refreshed before every submission like a slot-133 shadow, and the address of that copy. Windows are + // kept until the device goes (the ring comes round to the same pages), up to LEONIDA_TITLE_WINDOWS_MB (64 MiB + // by default); past that, or with the arena full, the address is left as it was and counted. + struct TitleWindow { + std::uint64_t start; + std::uint64_t shader_va; + }; + static constexpr std::uint64_t kTitleWindowAlign = 65536; + static constexpr std::uint64_t kTitleWindowMax = 16ull << 20; // the most one address pulls in + std::mutex title_window_mutex; // taken before shadow_mutex, never under it + std::vector title_windows; + std::uint64_t title_window_bytes = 0; + std::uint64_t title_window_cap = 64ull << 20; + + // Called through title_va_aliases().resolve for an address with no copy yet. False: not the title's memory. + bool resolve_title_memory(std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { + out = va; + if (!arena.mapped || va < arena.size || !context) return false; + if (context->knows_buffer_va(va)) return false; // an upload or readback buffer's biased VA, say + auto& aliases = leonida::title_va_aliases(); + // Only the title's own memory gets a copy (xmem's ranges): an address anywhere else, the runtime's or a host + // DLL's memory included, is left as it was and counted. + std::uint64_t title_lo = 0, title_hi = 0; + if (!aliases.title_memory(va, title_lo, title_hi)) return true; + MEMORY_BASIC_INFORMATION mbi{}; + if (!VirtualQuery(reinterpret_cast(static_cast(va)), &mbi, sizeof(mbi)) || + mbi.State != MEM_COMMIT || !mbi.Protect || (mbi.Protect & (PAGE_NOACCESS | PAGE_GUARD))) + return true; + std::lock_guard lock(title_window_mutex); + if (const std::uint64_t made = aliases.shader_va(va); made != va) { // another thread made it meanwhile + out = made; + return true; + } + std::uint64_t lo = 0, hi = UINT64_MAX; + aliases.gap(va, lo, hi); // never over a slot-133 buffer's range or another window + lo = std::max(lo, title_lo); // nor past the title's range + hi = std::min(hi, title_hi); + const std::uint64_t want = std::clamp(bytes, 1, kTitleWindowMax); + const std::uint64_t start = std::max(va & ~(kTitleWindowAlign - 1), lo); + std::uint64_t end = va > UINT64_MAX - want - kTitleWindowAlign ? UINT64_MAX + : (va + want + kTitleWindowAlign - 1) & + ~(kTitleWindowAlign - 1); + end = std::min(end, hi); + if (end <= va) return true; + const std::uint64_t size = end - start; + if (title_window_bytes + size > title_window_cap) { + log_once("title memory named by a shader address is past LEONIDA_TITLE_WINDOWS_MB, left untranslated; " + "MiB copied so far:", + int(title_window_bytes >> 20)); + return true; + } + VkDeviceSize offset = 0; + if (!arena_allocate(size, kTitleWindowAlign, offset, arena_buffer)) { + log_once("GPU address arena full (raise LEONIDA_ARENA_MB): title memory left untranslated; window KiB:", + int(std::min(size >> 10, INT_MAX))); + return true; + } + auto* mapped = arena.mapped + offset; + const auto* pages = reinterpret_cast(static_cast(start)); + copy_title_pages(mapped, pages, std::size_t(size)); + add_shadow({pages, mapped, std::size_t(size)}); + aliases.add(start, size, offset); + title_windows.push_back({start, offset}); + title_window_bytes += size; + if (title_windows.size() <= 4 || !(title_windows.size() & (title_windows.size() - 1))) + std::fprintf(stderr, "[rt] d3d12: a %llu KiB window of the title's memory, named by a shader address, is " + "copied into the GPU address arena before every submission (%zu windows, %llu KiB)\n", + static_cast(size >> 10), title_windows.size(), + static_cast(title_window_bytes >> 10)); + out = offset + (va - start); + return true; + } + + // The shader-visible CBV/SRV/UAV heaps (arena offset -> end), for the scan of bound tables before a submission. + std::mutex cbv_heap_mutex; + std::map cbv_heaps; + static constexpr VkDeviceSize kTableScanDescriptors = 1024; // per table and submission + + // The buffer V#s of the table at `table_va` whose base is in the title's own memory get the address of a copy, + // written in place: the title wrote them itself (or copied them), so no Create*View saw them. Images (T#s) and + // null slots are skipped; so is a V# already in the arena, so a rewritten one is left alone next time. + void scan_title_table(std::uint64_t table_va, std::uint32_t descriptors) { + VkDeviceSize end = 0; + { + std::lock_guard lock(cbv_heap_mutex); + auto it = cbv_heaps.upper_bound(table_va); + if (it == cbv_heaps.begin()) return; + --it; + if (table_va >= it->second) return; + end = std::min( + it->second, table_va + VkDeviceSize(std::min(descriptors, kTableScanDescriptors)) * + kDescriptorSize); + } + auto& aliases = leonida::title_va_aliases(); + // Slots the title wrote in its own backing of this heap, if it gave the heap one. + aliases.pull_descriptors(arena.mapped + table_va, std::size_t(end - table_va)); + for (VkDeviceSize at = table_va; at + 16 <= end; at += kDescriptorSize) { + auto* w = reinterpret_cast(arena.mapped + at); + const std::uint32_t w0 = w[0], w1 = w[1], w2 = w[2], w3 = w[3]; + if (!(w0 | w1 | w2 | w3) || (w3 >> 30)) continue; // null, or not a buffer V# (TYPE, dword 3 bits 30-31) + const std::uint64_t base = std::uint64_t(w0) | (std::uint64_t(w1 & 0xFFFFu) << 32); + if (base < arena.size) continue; + const std::uint32_t stride = (w1 >> 16) & 0x3FFFu; + const std::uint64_t to = + aliases.resolve(base, std::uint64_t(w2) * (stride ? stride : 1), leonida::TitleVaAliases::table_view); + if (to == base || (to >> 48)) continue; + w[0] = std::uint32_t(to); + w[1] = (w1 & 0xFFFF0000u) | std::uint32_t((to >> 32) & 0xFFFFu); + } + } + // WriteToSubresource/ReadFromSubresource without host image copy: one staging copy at a time, submitted to // the device's VkQueue and waited for. Created on first use. std::mutex staging_mutex; @@ -953,11 +1316,24 @@ struct DeviceState { // The format a texture description is created with, D24S8 and R9G9B9E5 UAV fallbacks included. Format texture_format(const D3D12_RESOURCE_DESC& desc) const { if (!xr_bias_compatible(desc)) return {}; - if (desc.Format == DXGI_FORMAT_A8_UNORM && - (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D || desc.SampleDesc.Count != 1 || - (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | - D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)))) - return {}; + // A8_UNORM: a 2D render target is VK_FORMAT_A8_UNORM_KHR (#7403); any other A8 texture, in 1D, 2D or 3D, is an + // R8_UNORM image, as the host makes all three (#7755; a title's boot sizes a 1D one). + if (desc.Format == DXGI_FORMAT_A8_UNORM) { + if (desc.SampleDesc.Count != 1 || + (desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))) + return {}; + if (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) { + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return {}; + if (!info.a8_render_target) { + log_once("A8_UNORM render targets need VK_FORMAT_A8_UNORM_KHR (VK_KHR_maintenance5); format", + desc.Format); + return {}; + } + Format alpha{kA8UnormFormat, VK_IMAGE_ASPECT_COLOR_BIT}; + alpha.a8_as_alpha = true; + return alpha; + } + } if (desc.Format == DXGI_FORMAT_R9G9B9E5_SHAREDEXP) { if ((desc.SampleDesc.Count != 1 && (!(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET) || (desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))) || @@ -1413,12 +1789,20 @@ Format texture_format(const DeviceState& device, const D3D12_RESOURCE_DESC& desc // path, D3D-90's placed one). Each format must map and be the same texel size as the resource's: the host PC // runtime refuses other sizes, and a size-mismatched VkImageFormatListCreateInfo is a Vulkan validation error // (VUID-VkImageCreateInfo-pNext-06722). A nonzero count with a null list is no list. E_INVALIDARG on a bad format. -HRESULT castable_view_formats(const Format& format, UINT32 count, const DXGI_FORMAT* castable, - std::vector& out) { +// An A8_UNORM texture's own format is always viewable (create_texture adds the image's format), so naming it is a +// no-op. An A8 render target's VK_FORMAT_A8_UNORM_KHR image (Format::a8_as_alpha) is in a class of its own: no +// other format can be a view format of it, so any other castable format is refused here, before Vulkan. +HRESULT castable_view_formats(const Format& format, DXGI_FORMAT resource_format, UINT32 count, + const DXGI_FORMAT* castable, std::vector& out) { if (!count || !castable) return S_OK; const bool depth = (format.aspects & (VK_IMAGE_ASPECT_DEPTH_BIT | VK_IMAGE_ASPECT_STENCIL_BIT)) != 0; const leonida::BlockFormat own = leonida::block_format(format.format, format.aspects); for (UINT32 i = 0; i < count; ++i) { + if (resource_format == DXGI_FORMAT_A8_UNORM && castable[i] == DXGI_FORMAT_A8_UNORM) continue; + if (format.a8_as_alpha) { + log_once("castable format of an A8_UNORM render target not supported (only A8_UNORM is):", castable[i]); + return E_INVALIDARG; + } const Format cast = vulkan_format(castable[i], depth); if (cast.format == VK_FORMAT_UNDEFINED) { log_once("castable format not supported yet:", castable[i]); @@ -1727,6 +2111,10 @@ class DescriptorHeap final in_arena_ = true; cpu_ = device.arena.mapped + arena_offset_; std::memset(cpu_, 0, std::size_t(bytes)); + if (desc.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { + std::lock_guard lock(device.cbv_heap_mutex); + device.cbv_heaps[arena_offset_] = arena_offset_ + bytes; + } } else { storage_.reset(new std::byte[std::size_t(bytes)]()); cpu_ = reinterpret_cast(storage_.get()); @@ -1734,6 +2122,10 @@ class DescriptorHeap final } ~DescriptorHeap() override { + if (in_arena_ && desc_.Type == D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV) { + std::lock_guard lock(device_.cbv_heap_mutex); + device_.cbv_heaps.erase(arena_offset_); + } if (in_arena_) device_.arena_release(arena_offset_, VkDeviceSize(desc_.NumDescriptors) * kDescriptorSize, DeviceState::arena_descriptor_heap); } @@ -1791,6 +2183,7 @@ class Resource final : device_(device), desc_(desc), heap_(heap), heap_flags_(heap_flags), placed_(true), va_(placed_va) {} ~Resource() override { + if (aliased_) leonida::title_va_aliases().remove(va_, title_alias_); if (accel_) { device_.context->unregister_acceleration_structure(gpu_va_); if (buffer_va_ && buffer_va_ != gpu_va_) device_.context->unregister_acceleration_structure(buffer_va_); @@ -1798,6 +2191,8 @@ class Resource final } if (image_address_) device_.forget_image(image_address_); device_.context->remove_resource(id()); + // Before the memory goes to the deferred queue: no submission copies into it after this. + if (shadow_) device_.remove_shadow(shadow_); if (host_import_) { // VK_EXT_external_memory_host needs the caller's pages to stay valid for the imported memory's whole // lifetime, and a title may free them right after releasing the resource. So the memory is not left to @@ -1837,6 +2232,7 @@ class Resource final return std::find(castable_formats_.begin(), castable_formats_.end(), format) != castable_formats_.end(); } bool has_castable_formats() const { return !castable_formats_.empty(); } + bool a8_as_alpha() const { return a8_as_alpha_; } VkFormat uint_backed() const { return uint_backed_; } // Format::uint_backed VkImageAspectFlags aspects() const { return aspects_; } bool rgb96() const { return rgb96_; } // a 96-bit texture in an RGBA32 image @@ -1974,8 +2370,9 @@ class Resource final // with VK_EXT_external_memory_host and the buffer bound to it at offset 0, so the CPU's writes there are the GPU's // reads with no copy. Its console VA is `address` itself, the VA the title chose, so vertex, index and immediate // writes the title names by that VA find this buffer (VulkanContext::buffer_at). A shader that adds heap_base to - // that VA does not reach it: the title's own V#s into these pages need the single address space of - // docs/d3d12_vulkan.md section 3.3, which this does not decide. The pages stay the caller's: nothing is zeroed. + // that VA would not reach it, so the root views and V#s the layer writes for it name its device address minus + // heap_base instead (alias_title_va, docs/d3d12_vulkan.md section 3.3 "Title-placed buffers"); V#s the title + // writes into memory itself keep its VA. The pages stay the caller's: nothing is zeroed. HRESULT create_host_buffer(void* address) { auto& vk = device_.context->vk; const VkDeviceSize alignment = device_.info.host_pointer_alignment; @@ -2079,6 +2476,108 @@ class Resource final binding.host_readable = true; binding.va = va_; device_.context->add_resource(id(), binding); + // Shaders reach the imported pages by their device address (src/title_va_alias.h). + if (buffer_va_) alias_title_va(buffer_va_ - device_.arena.address); + return S_OK; + } + + // Registers [va_, va_ + width) as reached by shaders at `shader_va` (src/title_va_alias.h): the root views and + // buffer V#s the layer writes for an address in it get the matching address of the buffer's GPU copy. + void alias_title_va(std::uint64_t shader_va) { + if (!leonida::title_va_aliases().add(va_, desc_.Width, shader_va)) return; + title_alias_ = shader_va; + aliased_ = true; + } + + // The fallback of create_host_buffer, for pages the driver will not import: write-combined or uncached ones (in + // retail 74 MiB of the title's 182 MiB range), pages not committed yet, a device without + // VK_EXT_external_memory_host, or a driver past its import budget (an RTX 3070 Ti answers + // VK_ERROR_OUT_OF_DEVICE_MEMORY after about 64 MiB of imports). The buffer has its own host-visible memory, a + // shadow of the title's pages, but keeps the title's VA as its console VA, so the descriptors and views the title + // builds from that VA still find it (an ordinary buffer here had another VA and none of the data: slot 70 wrote + // a null SRV and the UI draws sampled nothing). It is filled from the pages now and again before every + // submission of command lists (DeviceState::refresh_shadows). + // One way only: what the GPU writes to the shadow is NOT copied back to the title's pages, and the next + // submission's copy overwrites it. A title that reads GPU output at `address` needs the import. + HRESULT create_shadow_buffer(void* address) { + auto& vk = device_.context->vk; + if (!address || !desc_.Width || desc_.Width > ~UINT64(0) - D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT) + return E_INVALIDARG; + const auto* pages = static_cast(address); + // The shadow is a range of the GPU address arena when it fits there (docs/d3d12_vulkan.md section 3.3). + // The title's VA is a user-mode Windows address far above 4 GiB, past the arena, so a shader's heap_base + VA would miss + // any buffer of the layer's; the root views and V#s the layer writes for that VA name the arena offset + // instead (src/title_va_alias.h), a VA below 4 GiB that a root view and a V#'s 48 bits both hold. The arena + // is host-visible, so the per-submission copy writes it in place. + if (device_.arena.mapped && device_.arena_allocate(desc_.Width, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT, + arena_offset_, DeviceState::arena_buffer)) { + in_arena_ = true; + shadow_ = device_.arena.mapped + arena_offset_; + copy_title_pages(shadow_, pages, std::size_t(desc_.Width)); + mapped_ = address; + va_ = reinterpret_cast(address); + buffer_va_ = gpu_va_ = device_.arena.address + arena_offset_; + device_.log_va("title-placed buffer (arena shadow)", va_, desc_.Width); + leonida::ResourceBinding binding{}; + binding.buffer = device_.arena.buffer; + binding.buffer_offset = arena_offset_; + binding.size = desc_.Width; + binding.host = shadow_; + binding.va = va_; + device_.context->add_resource(id(), binding); + device_.add_shadow({pages, shadow_, std::size_t(desc_.Width)}); + alias_title_va(arena_offset_); + return S_OK; + } + log_once("a title-placed shadow buffer does not fit the GPU address arena (raise LEONIDA_ARENA_MB), so it " + "has its own memory; size in KiB:", + int(desc_.Width / 1024)); + const bool need_bda = device_.info.buffer_device_address || device_.arena.buffer != VK_NULL_HANDLE; + VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; + info.size = desc_.Width; + info.usage = VK_BUFFER_USAGE_TRANSFER_SRC_BIT | VK_BUFFER_USAGE_TRANSFER_DST_BIT | + VK_BUFFER_USAGE_VERTEX_BUFFER_BIT | VK_BUFFER_USAGE_INDEX_BUFFER_BIT | + VK_BUFFER_USAGE_UNIFORM_BUFFER_BIT | VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | + VK_BUFFER_USAGE_INDIRECT_BUFFER_BIT; + if (device_.info.conditional_rendering) info.usage |= VK_BUFFER_USAGE_CONDITIONAL_RENDERING_BIT_EXT; + if (need_bda) info.usage |= VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT; + device_.share(info); + if (vk.vkCreateBuffer(device_.info.device, &info, nullptr, &buffer_) != VK_SUCCESS) return E_OUTOFMEMORY; + VkMemoryRequirements requirements{}; + vk.vkGetBufferMemoryRequirements(device_.info.device, buffer_, &requirements); + // As an upload buffer (D3D-96): the CPU writes it at every submission and the GPU reads it, so VRAM through + // Resizable BAR where there is one, system memory otherwise. + memory_ = device_.allocate(requirements, + VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_HOST_COHERENT_BIT, + device_.upload_in_vram ? VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT : 0, &memory_flags_, + need_bda); + void* shadow = nullptr; + if (!memory_ || vk.vkBindBufferMemory(device_.info.device, buffer_, memory_, 0) != VK_SUCCESS || + vk.vkMapMemory(device_.info.device, memory_, 0, VK_WHOLE_SIZE, 0, &shadow) != VK_SUCCESS) + return E_OUTOFMEMORY; + shadow_ = static_cast(shadow); + copy_title_pages(shadow_, pages, std::size_t(desc_.Width)); + // Map() answers the title's own pages, as the imported buffer does: a write to the shadow's memory would be + // overwritten by the next copy. + mapped_ = address; + va_ = reinterpret_cast(address); + if (need_bda && vk.vkGetBufferDeviceAddress) { + VkBufferDeviceAddressInfo bda{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; + bda.buffer = buffer_; + buffer_va_ = vk.vkGetBufferDeviceAddress(device_.info.device, &bda); + gpu_va_ = buffer_va_; + } + device_.log_va("title-placed buffer (shadow)", va_, desc_.Width); + leonida::ResourceBinding binding{}; + binding.buffer = buffer_; + binding.size = desc_.Width; + // CPU-side reads take the shadow, not the title's pages: it is as fresh as what the GPU reads and every byte + // of it can be read, which the pages do not promise. Not host_readable: GPU writes are not handed back. + binding.host = shadow_; + binding.va = va_; + device_.context->add_resource(id(), binding); + device_.add_shadow({pages, shadow_, std::size_t(desc_.Width)}); + if (buffer_va_) alias_title_va(buffer_va_ - device_.arena.address); return S_OK; } @@ -2267,6 +2766,7 @@ class Resource final // With the bindless set, a view's descriptor has one layout for as long as it lives (bind_image). binding.sampled_in_general = device_.bindless != nullptr; format_ = format.format; + a8_as_alpha_ = format.a8_as_alpha; uint_backed_ = format.uint_backed; aspects_ = format.aspects; image_address_ = device_.next_image_address.fetch_add(256); @@ -2614,6 +3114,7 @@ class Resource final VkFormat format_ = VK_FORMAT_UNDEFINED; std::vector view_formats_; // creation-time castable list; empty means no restriction std::vector castable_formats_; // the same list as the application gave it + bool a8_as_alpha_ = false; VkFormat uint_backed_ = VK_FORMAT_UNDEFINED; std::uint64_t image_address_ = 0; // what a T# names the texture by bool rgb96_ = false; @@ -2621,6 +3122,9 @@ class Resource final std::uint64_t buffer_va_ = 0; std::uint64_t gpu_va_ = 0; bool host_import_ = false; // memory_ is the caller's pages (create_host_buffer): freed at once, not deferred + std::uint8_t* shadow_ = nullptr; // create_shadow_buffer: memory_ mapped, in DeviceState::shadows + bool aliased_ = false; // va_ is in leonida::title_va_aliases(), reached at title_alias_ + std::uint64_t title_alias_ = 0; bool reserved_ = false; bool sparse_image_ = false; bool placed_ = false; @@ -3063,7 +3567,8 @@ leonida::cached_pso::Key pipeline_key(const D3D12_GRAPHICS_PIPELINE_STATE_DESC& key.text(e.SemanticName).u32(e.SemanticIndex).u32(e.Format).u32(e.InputSlot).u32(e.AlignedByteOffset); key.u32(e.InputSlotClass).u32(e.InstanceDataStepRate); } - key.u32(desc.IBStripCutValue).u32(desc.PrimitiveTopologyType).u32(desc.NumRenderTargets); + key.u32(desc.IBStripCutValue).u32(std::bit_cast(desc.PrimitiveTopologyType)) + .u32(desc.NumRenderTargets); for (const DXGI_FORMAT format : desc.RTVFormats) key.u32(format); key.u32(desc.DSVFormat).u32(desc.SampleDesc.Count).u32(desc.SampleDesc.Quality).u32(desc.NodeMask); return leonida::sha256_hex(key.data()); @@ -3460,8 +3965,18 @@ class PipelineState final log_once("geometry shaders need the Vulkan geometryShader feature; stage", 0); return E_NOTIMPL; } - if (geometry && desc.PrimitiveTopologyType != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { - log_once("a translated geometry shader takes triangles; topology type", desc.PrimitiveTopologyType); + // The console's rectangle topology type (19) draws as triangles through a generated geometry stage that adds + // each rectangle's fourth corner (src/rect_list_geometry.h); it needs the same device feature, and no GS of + // the application's own. + // Decode the ABI field as bits. The console's value is outside the PC enum's range. + const auto topology_type = std::bit_cast(desc.PrimitiveTopologyType); + const bool rect_list = !mesh && topology_type == leonida::topology_type_rect_list; + if (rect_list && (geometry || !device_.info.features.geometryShader)) { + log_once("a rectangle-list pipeline needs the geometryShader feature and no geometry shader; stage", 0); + return geometry ? E_INVALIDARG : E_NOTIMPL; + } + if (geometry && topology_type != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) { + log_once("a translated geometry shader takes triangles; topology type", topology_type); return E_INVALIDARG; } const UINT samples = desc.SampleDesc.Count; @@ -3640,6 +4155,26 @@ class PipelineState final subgroup_size_for(*stage.entry, required_sizes[stage_infos.size()], info); stage_infos.push_back(info); } + if (rect_list) { // the stage that adds each rectangle's fourth corner, from the vertex shader's outputs + std::string why; + const std::vector words = leonida::rect_list_geometry(vs_stage.words, why); + if (words.empty()) { + std::fprintf(stderr, "[rt] d3d12: %s cannot be drawn as a rectangle list: %s\n", + vs_stage.entry->name.c_str(), why.c_str()); + return E_NOTIMPL; + } + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = words.size() * 4; + module_info.pCode = words.data(); + VkShaderModule module = VK_NULL_HANDLE; + if (vk.vkCreateShaderModule(dev, &module_info, nullptr, &module) != VK_SUCCESS) return E_FAIL; + modules_.push_back(module); + VkPipelineShaderStageCreateInfo info{VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + info.stage = VK_SHADER_STAGE_GEOMETRY_BIT; + info.module = module; + info.pName = "main"; + stage_infos.push_back(info); + } if (depth24_fragment && !ps_stage.entry) { // no pixel shader: a built-in one writes the depth const std::vector words = leonida::depth24_depth_only_fragment(depth24_bias); VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; @@ -3714,12 +4249,13 @@ class PipelineState final } } VkPipelineInputAssemblyStateCreateInfo assembly{VK_STRUCTURE_TYPE_PIPELINE_INPUT_ASSEMBLY_STATE_CREATE_INFO}; - switch (mesh ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : desc.PrimitiveTopologyType) { // mesh: not used + // Type 19 is the console's rectangles, drawn as triangle lists through the geometry stage added above. + switch (mesh || rect_list ? D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE : topology_type) { // mesh: not used case D3D12_PRIMITIVE_TOPOLOGY_TYPE_POINT: assembly.topology = VK_PRIMITIVE_TOPOLOGY_POINT_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_LINE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_LINE_LIST; break; case D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE: assembly.topology = VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; break; default: - log_once("primitive topology type not supported:", desc.PrimitiveTopologyType); + log_once("primitive topology type not supported:", topology_type); return E_INVALIDARG; } if (!mesh) { // a mesh PSO has no index buffer: its strip cut is ignored @@ -3741,7 +4277,7 @@ class PipelineState final return E_INVALIDARG; } if (r.FillMode != D3D12_FILL_MODE_SOLID || - desc.PrimitiveTopologyType != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) return E_INVALIDARG; + topology_type != D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE) return E_INVALIDARG; // Target-independent rasterization is a separate pipeline path; do not silently ignore its count. if (r.ForcedSampleCount) return E_NOTIMPL; } @@ -3853,7 +4389,9 @@ class PipelineState final graphics_.color_formats.assign(desc.NumRenderTargets, VK_FORMAT_UNDEFINED); for (UINT i = 0; i < desc.NumRenderTargets; ++i) { if (desc.RTVFormats[i] == DXGI_FORMAT_UNKNOWN) continue; - graphics_.color_formats[i] = vulkan_format(desc.RTVFormats[i], false).format; + graphics_.color_formats[i] = desc.RTVFormats[i] == DXGI_FORMAT_A8_UNORM && device_.info.a8_render_target + ? kA8UnormFormat + : vulkan_format(desc.RTVFormats[i], false).format; if (graphics_.color_formats[i] == VK_FORMAT_UNDEFINED) { log_once("render-target format not supported yet:", desc.RTVFormats[i]); return E_INVALIDARG; @@ -4063,9 +4601,21 @@ class PipelineState final VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{}; subgroup_size_for(*entry, required_size, pipeline_info.stage); pipeline_info.layout = pipeline_.layout; - if (vk.vkCreateComputePipelines(dev, device_.pipeline_cache(), 1, &pipeline_info, nullptr, &pipeline_.pipeline) != - VK_SUCCESS) + const VkPipelineCache cache = device_.pipeline_cache(); + const bool checkpoint = cache && startup_cache_checkpoints_enabled(); + const ULONGLONG started = checkpoint ? GetTickCount64() : 0; + if (vk.vkCreateComputePipelines(dev, cache, 1, &pipeline_info, nullptr, &pipeline_.pipeline) != VK_SUCCESS) return E_FAIL; + if (checkpoint && GetTickCount64() - started >= 500) { + const std::unique_lock lock(device_.startup_cache_checkpoint_mutex, std::try_to_lock); + if (lock.owns_lock()) { + try { + save_session_pipeline_cache(vk, dev, cache); + } catch (const std::exception& error) { + std::fprintf(stderr, "[rt] d3d12: pipeline cache checkpoint failed (%s)\n", error.what()); + } + } + } // The code base: shaders read constant tables embedded in their own program through s_getpc_b64. The // translator's code offsets are into the bytes the key hashes (the FSSM blob, or the kind-6 program). @@ -4762,7 +5312,8 @@ bool image_descriptor(const Resource& resource, const TextureView& view, leonida log_once("incompatible R9G9B9E5 view format:", int(view.format)); return false; } - named = texture_storage_format(view.format, false).format; + // An A8 render target is viewed in its own A8 format (Format::a8_as_alpha), other A8 textures through R8. + named = resource.a8_as_alpha() ? resource_format : texture_storage_format(view.format, false).format; if (g::is_depth_stencil_format(named)) { log_once("depth-stencil view format on a colour texture:", int(view.format)); return false; @@ -5120,6 +5671,21 @@ class Device final info.conditional_rendering, info.ray_tracing, info.xdxr_acceleration_structures && info.buffer_device_address); + state_.context->set_before_execute([this] { state_.refresh_shadows(); }); + { + char text[16] = {}; + size_t length = 0; + if (getenv_s(&length, text, "LEONIDA_TITLE_WINDOWS_MB") == 0 && length > 1) + state_.title_window_cap = std::strtoull(text, nullptr, 10) << 20; + } + leonida::title_va_aliases().set_hooks( + &state_, + [](void* device, std::uint64_t va, std::uint64_t bytes, std::uint64_t& out) { + return static_cast(device)->resolve_title_memory(va, bytes, out); + }, + [](void* device, std::uint64_t table, std::uint32_t descriptors) { + static_cast(device)->scan_title_table(table, descriptors); + }); if (info.physical && state_.format_properties) { state_.context->set_color_attachment_format( [physical = info.physical, get_props = state_.format_properties](VkFormat format) { @@ -5448,7 +6014,13 @@ class Device final return false; } arena.mapped = static_cast(mapped); - std::memset(arena.mapped, 0, kArenaReserved); // the zero page unbound vertex and index buffers read + std::memset(arena.mapped, 0, kZeroPage); // the zero page unbound vertex and index buffers read + auto* indices = reinterpret_cast(arena.mapped + kZeroPage); + for (std::uint32_t i = 0; i < kQuadIndexCount; i += kQuadIndicesPerQuad) { + const std::uint32_t base = i / kQuadIndicesPerQuad * 4; + std::transform(leonida::quad_triangle_indices.begin(), leonida::quad_triangle_indices.end(), indices + i, + [base](std::uint32_t index) { return base + index; }); + } VkBufferDeviceAddressInfo address{VK_STRUCTURE_TYPE_BUFFER_DEVICE_ADDRESS_INFO}; address.buffer = arena.buffer; arena.address = vk.vkGetBufferDeviceAddress(state_.info.device, &address); @@ -5459,11 +6031,57 @@ class Device final length = 0; arena.log = getenv_s(&length, log, "LEONIDA_ARENA_LOG") == 0 && length > 1 && log[0] != '0'; state_.context->set_heap_base(arena.address); - state_.context->set_zero_page(arena.buffer, 0, kArenaReserved); + state_.context->set_zero_page(arena.buffer, 0, kZeroPage); + state_.context->set_quad_indices(arena.buffer, kZeroPage, kQuadIndexCount); + // Vertex and index views that name the title's own CPU memory are copied into a ring carved from the + // arena at replay (not fence-tracked: the ring is large against a frame's few KiB of immediate geometry). + state_.context->set_title_memory( + [st = &state_](std::uint64_t va, std::uint64_t size, VkBuffer& buffer, VkDeviceSize& offset) { + static constexpr VkDeviceSize kRing = 16ull << 20; + static std::mutex mutex; + static VkDeviceSize ring_base = 0, ring_next = 0; + static bool tried = false, logged = false; + if (!va || !size || size > kRing / 4 || !st->arena.mapped) return false; + // The whole range must be committed, readable host memory. + for (std::uint64_t at = va; at < va + size;) { + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(reinterpret_cast(at), &info, sizeof(info))) return false; + if (info.State != MEM_COMMIT || (info.Protect & (PAGE_NOACCESS | PAGE_GUARD)) || !info.Protect) + return false; + at = reinterpret_cast(info.BaseAddress) + info.RegionSize; + } + std::lock_guard lock(mutex); + if (!tried) { + tried = true; + if (!st->arena_allocate(kRing, 256, ring_base, DeviceState::arena_shader)) ring_base = 0; + } + if (!ring_base) return false; + const VkDeviceSize aligned = (size + 255) & ~VkDeviceSize(255); + if (ring_next + aligned > kRing) ring_next = 0; + std::memcpy(st->arena.mapped + ring_base + ring_next, reinterpret_cast(va), + std::size_t(size)); + buffer = st->arena.buffer; + offset = ring_base + ring_next; + ring_next += aligned; + if (!logged) { + logged = true; + std::fprintf(stderr, "[rt] d3d12: vertex/index views in title memory are copied into a " + "%llu MiB ring (first: %llu bytes)\n", + static_cast(kRing >> 20), static_cast(size)); + } + return true; + }); return true; } ~Device() override { + leonida::title_va_aliases().clear_hooks(&state_); + { + std::lock_guard lock(state_.title_window_mutex); + for (const auto& window : state_.title_windows) + leonida::title_va_aliases().remove(window.start, window.shader_va); + state_.title_windows.clear(); + } if (state_.context) { { std::lock_guard lock(state_.context->submit_mutex()); @@ -5488,8 +6106,10 @@ class Device final vk.vkDestroyBuffer(state_.info.device, state_.arena.buffer, nullptr); if (state_.arena.memory) vk.vkFreeMemory(state_.info.device, state_.arena.memory, nullptr); } - if (state_.pipeline_cache_handle) + if (state_.pipeline_cache_handle) { + save_session_pipeline_cache(state_.context->vk, state_.info.device, state_.pipeline_cache_handle); state_.context->vk.vkDestroyPipelineCache(state_.info.device, state_.pipeline_cache_handle, nullptr); + } state_.context.reset(); if (owned_.device) owned_.destroy_device(owned_.device, nullptr); if (owned_.instance) owned_.destroy_instance(owned_.instance, nullptr); @@ -5523,6 +6143,22 @@ class Device final void own(const OwnedRuntime& owned) { owned_ = owned; } void set_outer(IUnknown* outer) { outer_ = outer; } + // The buffer resource holding console VA `va`, with a reference added for the caller, or null when no resource this + // layer made holds it. `start` and `size` are the resource's first VA and byte size. + // Only this layer's own buffers have a VA in the registry (the swapchain's are images, a copy's staging binding has + // no VA), so an ID found by VA is the ID3D12Resource pointer of a Resource (resource_id). + ID3D12Resource* add_ref_buffer_at(std::uint64_t va, std::uint64_t bytes, std::uint64_t& start, std::uint64_t& size) { + leonida::ResourceId id = 0; + ID3D12Resource* found = nullptr; + const bool ok = state_.context->buffer_resource_at(va, bytes, id, start, size, [&](leonida::ResourceId candidate) { + auto* resource = static_cast(reinterpret_cast(candidate)); + if (!resource->try_add_ref()) return false; + found = resource; + return true; + }); + return ok ? found : nullptr; + } + UINT STDMETHODCALLTYPE GetNodeCount() override { return 1; } // The Vulkan physical device's LUID, which is the DXGI adapter's on Windows. Zero (logged) when the driver has @@ -5833,6 +6469,11 @@ class Device final case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW: kind = leonida::IndirectKind::draw; break; case D3D12_INDIRECT_ARGUMENT_TYPE_DRAW_INDEXED: kind = leonida::IndirectKind::draw_indexed; break; case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH: kind = leonida::IndirectKind::dispatch; break; + case D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH: + // As DispatchMesh: only a device with mesh shaders (MeshShaderTier 1) takes it. + if (!state_.info.mesh_shader) return E_NOTIMPL; + kind = leonida::IndirectKind::dispatch_mesh; + break; default: return E_NOTIMPL; } return create_command_signature(kind, desc->ByteStride, riid, out, identity()); @@ -6042,6 +6683,14 @@ class Device final layout.flags = parsed.sig.flags; layout.graphics_ok = packed.ok; layout.compute_ok = compute.ok; + const rt::rootsig::StagePackResult local_stage = rt::rootsig::pack_stage(parsed.sig, rt::rootsig::Stage::Vertex); + const bool local_stage_layout = local_graphics_stage_layout() && local_stage.ok; + if (local_graphics_stage_layout()) { + static std::atomic said{0}; + if (said.fetch_add(1) < 3) + std::fprintf(stderr, "[rt] d3d12: local: graphics root arguments in the console stage layout (from s%u): %s\n", + local_stage.base, local_stage.ok ? "ok" : local_stage.error.c_str()); + } for (std::size_t i = 0; i < parsed.sig.params.size(); ++i) { std::uint32_t first = UINT32_MAX; for (std::uint32_t d = 0; packed.ok && d < packed.dword_count; ++d) @@ -6049,8 +6698,10 @@ class Device final first = d; break; } + if (local_stage_layout) first = local_stage.first_sgpr[i]; layout.parameters.push_back({parsed.sig.params[i].type, first, parsed.sig.params[i].num_values, - compute.ok ? compute.first_sgpr[i] : rt::rootsig::kNoSgpr}); + compute.ok ? compute.first_sgpr[i] : rt::rootsig::kNoSgpr, + table_view_descriptors(parsed.sig.params[i])}); } register_static_samplers(parsed.sig); auto* signature = new RootSignature( @@ -6250,7 +6901,13 @@ class Device final const bool typed_bgra8_listed = r && !typed_rgba8 && rgba8_any_order(rd.Format) && r->has_castable_formats(); if (rd.Format == DXGI_FORMAT_A8_UNORM || (desc && desc->Format == DXGI_FORMAT_A8_UNORM)) { - view = {}; + // Only an A8 render target stored as VK_FORMAT_A8_UNORM_KHR takes an RTV, in its own format: the + // attachment view is the image's. + const bool plain_2d = !desc || desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2D || + desc->ViewDimension == D3D12_RTV_DIMENSION_TEXTURE2DARRAY; + if (!r || !r->a8_as_alpha() || rd.Format != DXGI_FORMAT_A8_UNORM || !plain_2d || + (desc && desc->Format != DXGI_FORMAT_UNKNOWN && desc->Format != DXGI_FORMAT_A8_UNORM)) + view = {}; } else if (r && r->uint_backed() == VK_FORMAT_A1R5G5B5_UNORM_PACK16) { // An R16_UINT-backed B5G5R5A1 UAV texture (Format::uint_backed) renders through an A1R5G5B5 view, in // its own format only. @@ -6411,6 +7068,7 @@ class Device final buffer.num_records = desc->SizeInBytes; buffer.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); buffer.oob_select = leonida::gfx10::OobSelect::raw; + buffer.address = vsharp_address(buffer.address, desc->SizeInBytes); const leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); } @@ -6502,6 +7160,8 @@ class Device final } buffer.oob_select = leonida::gfx10::OobSelect::structured; } + buffer.address = vsharp_address( + buffer.address, std::uint64_t(buffer.num_records) * (buffer.stride ? buffer.stride : 1)); const leonida::gfx10::BufferWords words = leonida::gfx10::encode(buffer); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); return; @@ -6659,11 +7319,13 @@ class Device final buffer.swizzle = channels; buffer.oob_select = typed ? g::OobSelect::structured : structured ? g::OobSelect::structured_with_offset : g::OobSelect::raw; + buffer.address = vsharp_address(buffer.address, + std::uint64_t(buffer.num_records) * (buffer.stride ? buffer.stride : 1)); const g::BufferWords words = g::encode(buffer); std::memcpy(reinterpret_cast(destination.ptr), words.data(), sizeof(words)); if (counter) { g::Buffer counter_buffer{}; - counter_buffer.address = counter_va + view.CounterOffsetInBytes; + counter_buffer.address = vsharp_address(counter_va + view.CounterOffsetInBytes, 4); counter_buffer.num_records = 4; counter_buffer.oob_select = g::OobSelect::raw; const g::BufferWords counter_words = g::encode(counter_buffer); @@ -7181,13 +7843,26 @@ class Device final if (FAILED(hr)) { // The driver would not import these pages: RADV refuses a view of a pagefile-backed section, the form // xmem's physical pages take (found in review on an RX 9070 XT under Wine), and a device without - // VK_EXT_external_memory_host has no import at all. The boot goes on with an ordinary DEFAULT buffer - // of the same description, as #6915's stand-in did: the title gets a resource, but its writes at - // `address` do not reach it. + // VK_EXT_external_memory_host has no import at all; write-combined and uncommitted pages are not tried, + // and some drivers stop importing after a budget (create_shadow_buffer). The title then gets a shadow + // buffer at its VA, copied from its pages before every submission. + resource->Release(); + resource = new Resource(state_, desc, heap, D3D12_HEAP_FLAG_NONE); + resource->attach_device(identity()); + const HRESULT shadow = resource->create_shadow_buffer(address); + if (SUCCEEDED(shadow)) { + log_once("a title-placed buffer (device slot 133) could not import its pages, so it is a shadow " + "copied from them before every submission; HRESULT", + int(hr)); + return d3d12_trace::result(method, hand_out(resource, riid, out)); + } + // No memory for the shadow either: the boot goes on with an ordinary DEFAULT buffer of the same + // description, as #6915's stand-in did. The title gets a resource, but neither its VA nor its writes at + // `address` reach it. resource->Release(); - log_once("a title-placed buffer (device slot 133) could not import its pages, so it is an ordinary buffer " - "the title's writes do not reach; HRESULT", - int(hr)); + log_once("a title-placed buffer (device slot 133) could neither import its pages nor get a shadow, so it " + "is an ordinary buffer the title's writes do not reach; HRESULT", + int(shadow)); const D3D12_HEAP_PROPERTIES fallback{D3D12_HEAP_TYPE_DEFAULT}; return d3d12_trace::result(method, create_committed(&fallback, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, 0, nullptr, riid, out)); @@ -7392,7 +8067,7 @@ class Device final hr = E_INVALIDARG; } else { std::vector cast_formats; - hr = castable_view_formats(format, castable_count, castable, cast_formats); + hr = castable_view_formats(format, desc->Format, castable_count, castable, cast_formats); if (SUCCEEDED(hr)) hr = resource->create_texture(format, cast_formats); if (SUCCEEDED(hr)) resource->keep_castable_formats(castable_count, castable); } @@ -7931,7 +8606,8 @@ class Device final if (fs->Format == DXGI_FORMAT_A8_UNORM) { if (optimal & VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT) { - fs->Support1 = D3D12_FORMAT_SUPPORT1_TEXTURE2D | D3D12_FORMAT_SUPPORT1_TEXTURECUBE | + fs->Support1 = D3D12_FORMAT_SUPPORT1_TEXTURE1D | D3D12_FORMAT_SUPPORT1_TEXTURE2D | + D3D12_FORMAT_SUPPORT1_TEXTURE3D | D3D12_FORMAT_SUPPORT1_TEXTURECUBE | D3D12_FORMAT_SUPPORT1_SHADER_LOAD; if (optimal & VK_FORMAT_FEATURE_SAMPLED_IMAGE_FILTER_LINEAR_BIT) fs->Support1 |= D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE | D3D12_FORMAT_SUPPORT1_SHADER_GATHER; @@ -7943,6 +8619,9 @@ class Device final VK_IMAGE_TILING_OPTIMAL, usage, 0, &limits) == VK_SUCCESS && limits.maxMipLevels > 1) fs->Support1 |= D3D12_FORMAT_SUPPORT1_MIP; + // Render targets are stored as VK_FORMAT_A8_UNORM_KHR, which the device checked can blend. + if (state_.info.a8_render_target) + fs->Support1 |= D3D12_FORMAT_SUPPORT1_RENDER_TARGET | D3D12_FORMAT_SUPPORT1_BLENDABLE; } return d3d12_trace::result(method, S_OK); } @@ -8554,7 +9233,7 @@ class Device final hr = E_INVALIDARG; } else { std::vector cast_formats; - hr = castable_view_formats(format, castable_count, castable, cast_formats); + hr = castable_view_formats(format, desc->Format, castable_count, castable, cast_formats); if (SUCCEEDED(hr)) hr = resource->create_texture(format, cast_formats); if (SUCCEEDED(hr)) resource->keep_castable_formats(castable_count, castable); } @@ -8829,7 +9508,16 @@ void set_device_outer(ID3D12Device* device, IUnknown* outer) { // for IDXGIDevice1: the device's outer identity is the proxy itself either way. if (void* proxy = rt::d3d12_xs::device_proxy_primary(outer)) outer = static_cast(proxy); d->set_outer(outer); - // Second job, for an outer that is the Xbox-ABI proxy: its IDXGIDevice1::GetAdapter (d3d12_xs_device.h) hands + // Another job for an outer that is the Xbox-ABI proxy: its device slot 70 names a buffer by console VA only, and + // this finds the layer's resource for it. + if (rt::d3d12_xs::is_device_proxy(outer)) + rt::d3d12_xs::set_device_resource_provider( + outer, [](ID3D12Device* real, std::uint64_t va, std::uint64_t bytes, std::uint64_t* start, + std::uint64_t* size) -> ID3D12Resource* { + Device* device = Device::from(real); + return device ? device->add_ref_buffer_at(va, bytes, *start, *size) : nullptr; + }); + // And for the same outer: its IDXGIDevice1::GetAdapter (d3d12_xs_device.h) hands // out this layer's adapter, the one create_dxgi_factory enumerates, so a title on the Vulkan device never gets // a host DXGI object from it. if (!rt::d3d12_xs::is_device_proxy(outer)) return; @@ -9388,6 +10076,7 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin LEONIDA_INSTANCE(vkGetPhysicalDeviceProperties); LEONIDA_INSTANCE(vkGetPhysicalDeviceQueueFamilyProperties); LEONIDA_INSTANCE(vkGetPhysicalDeviceFeatures2); + LEONIDA_INSTANCE(vkGetPhysicalDeviceFormatProperties); LEONIDA_INSTANCE(vkGetPhysicalDeviceProperties2); LEONIDA_INSTANCE(vkEnumerateDeviceExtensionProperties); LEONIDA_INSTANCE(vkCreateDevice); @@ -9760,6 +10449,27 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin } #endif +#ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME + // VK_KHR_maintenance5 brings VK_FORMAT_A8_UNORM_KHR (VulkanDeviceInfo::a8_render_target). It is enabled only where + // that format can be sampled, copied (every texture is a transfer source and destination) and is a colour + // attachment the GPU can blend; nothing else here relies on it. + VkPhysicalDeviceMaintenance5FeaturesKHR maintenance5{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_5_FEATURES_KHR}; + if (has_device_extension(VK_KHR_MAINTENANCE_5_EXTENSION_NAME) && vkGetPhysicalDeviceFormatProperties) { + VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &maintenance5}; + vkGetPhysicalDeviceFeatures2(info.physical, &query); + VkFormatProperties a8{}; + vkGetPhysicalDeviceFormatProperties(info.physical, VK_FORMAT_A8_UNORM_KHR, &a8); + const VkFormatFeatureFlags needed = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT | + VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT | + VK_FORMAT_FEATURE_TRANSFER_SRC_BIT | VK_FORMAT_FEATURE_TRANSFER_DST_BIT; + info.a8_render_target = maintenance5.maintenance5 == VK_TRUE && (a8.optimalTilingFeatures & needed) == needed; + if (info.a8_render_target) { + maintenance5.pNext = *v13.next(); + *v13.next() = &maintenance5; + } + } +#endif + #ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME // VK_KHR_shader_fma: OpFmaKHR is a single-rounding multiply-add in SPIR-V (GLSL.std.450 Fma may round twice). // Translated shaders built with `rdna2spirv.py --fma khr` need it (index capability FMAKHR, feature @@ -9910,6 +10620,9 @@ HRESULT create_vulkan_device_standalone(REFIID riid, void** out, QueueTestSettin #ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME if (info.maintenance8) device_extensions.push_back(VK_KHR_MAINTENANCE_8_EXTENSION_NAME); #endif +#ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME + if (info.a8_render_target) device_extensions.push_back(VK_KHR_MAINTENANCE_5_EXTENSION_NAME); +#endif #ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME if (info.shader_fma) device_extensions.push_back(VK_KHR_SHADER_FMA_EXTENSION_NAME); #endif diff --git a/runtime/shims/d3d12_xs.cpp b/runtime/shims/d3d12_xs.cpp index 8e54c3fd56..51241498b4 100644 --- a/runtime/shims/d3d12_xs.cpp +++ b/runtime/shims/d3d12_xs.cpp @@ -117,11 +117,22 @@ HRESULT WINAPI create_root_signature_deserializer(const void* data, SIZE_T size, return fn(data, size, iid, out); } +void* xmem_descriptor_heap_alloc(std::size_t byte_size, std::uint64_t attributes) { + const rt::shims::XMemAllocationHooks* hooks = rt::shims::xmem_allocation_hooks(); + return (hooks && hooks->alloc) ? hooks->alloc(byte_size, attributes) : nullptr; +} + +void xmem_descriptor_heap_free(void* ptr, std::uint64_t attributes) { + const rt::shims::XMemAllocationHooks* hooks = rt::shims::xmem_allocation_hooks(); + if (hooks && hooks->free) hooks->free(ptr, attributes); +} + // Measured shape: D3D12XboxCreateDevice(adapter, params, riid, out), where params is a 24-word block that is only // logged and not used to create the device. The struct's total size is unknown, so the log reads 24 x 32-bit words // (96 bytes) and no more. The PC D3D12CreateDevice needs a minimum feature level instead, so 12_0 is used as the // least restrictive floor; higher feature levels are still exposed by the created device. HRESULT WINAPI D3D12XboxCreateDevice(IUnknown* adapter, const void* params, const IID* riid, void** out) { + rt::d3d12_xs::set_default_descriptor_heap_allocator(&xmem_descriptor_heap_alloc, &xmem_descriptor_heap_free); constexpr auto method = "D3D12XboxCreateDevice"; using rt::d3d12_trace::result; if (!out) return result(method, E_POINTER); @@ -157,6 +168,14 @@ HRESULT WINAPI D3D12XboxCreateDevice(IUnknown* adapter, const void* params, cons "(slot 62 -> CreateComputePipelineState, slot 76 -> CreateCommittedResource).\n"); } + // A console title gets the console-shaped list the Xbox ABI calls. A guest compiled against the PC + // headers (the tiny fixtures, which call the list through PC vtable indices) asks for PC-shaped lists + // with LEONIDA_D3D12_LISTS=pc — the device, queue and friends stay console-shaped either way. + char lists_mode[8] = {}; + size_t lists_length = 0; + const bool pc_lists = getenv_s(&lists_length, lists_mode, "LEONIDA_D3D12_LISTS") == 0 && + std::strcmp(lists_mode, "pc") == 0; + #ifdef LEONIDA_VULKAN_DEVICE // Opt-in until the Vulkan device covers the first frame: LEONIDA_D3D12=vulkan puts the Vulkan-backed device // behind the same proxy instead of the host's D3D12 device. @@ -171,7 +190,7 @@ HRESULT WINAPI D3D12XboxCreateDevice(IUnknown* adapter, const void* params, cons static_cast(vhr)); return result(method, vhr); } - vhr = rt::d3d12_xs::create_device_proxy(vulkan, *riid, out); + vhr = rt::d3d12_xs::create_device_proxy(vulkan, *riid, out, /*console_lists=*/!pc_lists); if (FAILED(vhr)) { vulkan->Release(); std::fprintf(stderr, "[rt] d3d12_xs: D3D12XboxCreateDevice: proxy over the Vulkan device failed " @@ -199,7 +218,7 @@ HRESULT WINAPI D3D12XboxCreateDevice(IUnknown* adapter, const void* params, cons return result(method, FAILED(hr) ? hr : E_FAIL); } - hr = rt::d3d12_xs::create_device_proxy(real, *riid, out); + hr = rt::d3d12_xs::create_device_proxy(real, *riid, out, /*console_lists=*/!pc_lists); if (FAILED(hr)) { // create_device_proxy keeps the caller's reference on failure. real->Release(); diff --git a/runtime/shims/d3d12_xs_alloc_size.h b/runtime/shims/d3d12_xs_alloc_size.h new file mode 100644 index 0000000000..3321c4ec88 --- /dev/null +++ b/runtime/shims/d3d12_xs_alloc_size.h @@ -0,0 +1,156 @@ +// Console allocation sizes for render targets, for the Xbox-ABI device proxy's slots 25 and 56 (GetResourceAllocationInfo and GetResourceAllocationInfo1). +// +// Why: the retail title checks a fixed memory budget against what its first full-screen render targets used and asserts +// when more than 2 MiB is left over (docs/retail_boot_chain.md, stop 17, #6982). The PC device sizes a 2D render target +// from the Vulkan driver's memory requirements, which is about width x height x element bytes. The console lays a +// render target out in 64 KiB tiles (the RDNA2 SW_64KB layouts), so its allocation is the surface padded to whole +// tiles: for 4-byte elements a tile is 128 x 128 pixels, and 1080 rows take nine tile rows, not 8.4. The PC size is +// smaller by that padding, summed over every full-screen target. +// +// What this is: the tile shapes are the RDNA2 SW_64KB_D shapes of runtime/src/gfx10_tiling.h (Mesa addrlib patterns, +// validated against real textures in docs/textures.md). That a console render target uses these shapes and no extra +// (DCC, CMask) memory in its allocation size is an assumption: the title's own sizes are not measured. The rule only +// ever makes a size larger than the PC device's own answer, never smaller. The mip tail follows AMD's addrlib +// (gfx10, 2D): a mip extent is rounded up (ShiftCeil), and the tail starts at the first mip that fits in half a tile's +// width and a whole tile's height; the tail is one tile. +#pragma once + +#include "../src/gfx10_tiling.h" + +#include +#include + +#include +#include +#include +#include + +namespace rt::d3d12_xs { + +constexpr UINT64 kConsoleTileBytes = 64 * 1024; // one SW_64KB tile + +// Bytes per element of the colour formats a render target takes, or 0 for any other format (the PC size then stays). +inline std::size_t render_target_element_bytes(DXGI_FORMAT format) { + switch (format) { + case DXGI_FORMAT_R8_TYPELESS: case DXGI_FORMAT_R8_UNORM: case DXGI_FORMAT_R8_UINT: + case DXGI_FORMAT_R8_SNORM: case DXGI_FORMAT_R8_SINT: case DXGI_FORMAT_A8_UNORM: + return 1; + case DXGI_FORMAT_R8G8_TYPELESS: case DXGI_FORMAT_R8G8_UNORM: case DXGI_FORMAT_R8G8_UINT: + case DXGI_FORMAT_R8G8_SNORM: case DXGI_FORMAT_R8G8_SINT: case DXGI_FORMAT_R16_TYPELESS: + case DXGI_FORMAT_R16_FLOAT: case DXGI_FORMAT_R16_UNORM: case DXGI_FORMAT_R16_UINT: + case DXGI_FORMAT_R16_SNORM: case DXGI_FORMAT_R16_SINT: case DXGI_FORMAT_B5G6R5_UNORM: + case DXGI_FORMAT_B5G5R5A1_UNORM: + return 2; + case DXGI_FORMAT_R10G10B10A2_TYPELESS: case DXGI_FORMAT_R10G10B10A2_UNORM: + case DXGI_FORMAT_R10G10B10A2_UINT: case DXGI_FORMAT_R11G11B10_FLOAT: + case DXGI_FORMAT_R8G8B8A8_TYPELESS: case DXGI_FORMAT_R8G8B8A8_UNORM: + case DXGI_FORMAT_R8G8B8A8_UNORM_SRGB: case DXGI_FORMAT_R8G8B8A8_UINT: + case DXGI_FORMAT_R8G8B8A8_SNORM: case DXGI_FORMAT_R8G8B8A8_SINT: + case DXGI_FORMAT_B8G8R8A8_TYPELESS: case DXGI_FORMAT_B8G8R8A8_UNORM: + case DXGI_FORMAT_B8G8R8A8_UNORM_SRGB: case DXGI_FORMAT_B8G8R8X8_TYPELESS: + case DXGI_FORMAT_B8G8R8X8_UNORM: case DXGI_FORMAT_B8G8R8X8_UNORM_SRGB: + case DXGI_FORMAT_R16G16_TYPELESS: case DXGI_FORMAT_R16G16_FLOAT: case DXGI_FORMAT_R16G16_UNORM: + case DXGI_FORMAT_R16G16_UINT: case DXGI_FORMAT_R16G16_SNORM: case DXGI_FORMAT_R16G16_SINT: + case DXGI_FORMAT_R32_TYPELESS: case DXGI_FORMAT_R32_FLOAT: case DXGI_FORMAT_R32_UINT: + case DXGI_FORMAT_R32_SINT: + return 4; + case DXGI_FORMAT_R16G16B16A16_TYPELESS: case DXGI_FORMAT_R16G16B16A16_FLOAT: + case DXGI_FORMAT_R16G16B16A16_UNORM: case DXGI_FORMAT_R16G16B16A16_UINT: + case DXGI_FORMAT_R16G16B16A16_SNORM: case DXGI_FORMAT_R16G16B16A16_SINT: + case DXGI_FORMAT_R32G32_TYPELESS: case DXGI_FORMAT_R32G32_FLOAT: case DXGI_FORMAT_R32G32_UINT: + case DXGI_FORMAT_R32G32_SINT: + return 8; + case DXGI_FORMAT_R32G32B32A32_TYPELESS: case DXGI_FORMAT_R32G32B32A32_FLOAT: + case DXGI_FORMAT_R32G32B32A32_UINT: case DXGI_FORMAT_R32G32B32A32_SINT: + return 16; + default: + return 0; + } +} + +// The console's allocation size for a single-sampled 2D render target, or 0 when the rule does not apply (not a 2D +// texture, not a render target, more than one sample, an unlisted format, an empty extent, or a size that overflows). +// MipLevels 0 is the full chain, as on the PC device. A mip extent is rounded up. Mips before the tail are padded to +// whole tiles; the first mip that fits in half a tile's width and the whole tile height, and every mip after it, share +// one tail tile. Slices add up. +inline UINT64 console_render_target_size(const D3D12_RESOURCE_DESC& desc) { + if (desc.Dimension != D3D12_RESOURCE_DIMENSION_TEXTURE2D) return 0; + if (!(desc.Flags & D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET)) return 0; + if (desc.SampleDesc.Count > 1) return 0; + const std::size_t element_bytes = render_target_element_bytes(desc.Format); + if (!element_bytes || !desc.Width || !desc.Height || !desc.DepthOrArraySize) return 0; + + const UINT full_chain = static_cast(std::bit_width(std::max(desc.Width, desc.Height))); + const UINT mips = desc.MipLevels ? std::min(desc.MipLevels, full_chain) : full_chain; + UINT64 slice = 0; + bool tail = false; + for (UINT mip = 0; mip < mips; ++mip) { + const UINT64 width = std::max((desc.Width + (UINT64{1} << mip) - 1) >> mip, 1); + const UINT64 height = std::max((UINT64{desc.Height} + (UINT64{1} << mip) - 1) >> mip, 1); + leonida::gfx10::TiledSurface2D surface; + if (width > UINT32_MAX || + !leonida::gfx10::TiledSurface2D::make(leonida::gfx10::TileMode::sw_64kb_d, element_bytes, + static_cast(width), static_cast(height), + surface)) + return 0; + if (width <= surface.tile_width() / 2 && height <= surface.tile_height()) { + tail = true; + break; + } + slice += surface.tiled_size(); + } + if (tail) slice += kConsoleTileBytes; + const UINT64 slices = desc.DepthOrArraySize; + if (slice > UINT64_MAX / slices) return 0; + return slice * slices; +} + +// Rounds up to a multiple of `to`, stopping at the last multiple below 2^64 instead of wrapping (as the PC device's +// totals do). +inline UINT64 align_up_saturating(UINT64 value, UINT64 to) { + return value > UINT64_MAX - (to - 1) ? UINT64_MAX / to * to : (value + to - 1) / to * to; +} + +// Lays the descriptions out as the PC device does (one after another, each at its own alignment, the total rounded up +// to the largest alignment), with a render target's size taken as its console size when that is larger than the PC +// size. pc_one(i) is the PC device's answer for description i alone. Sizes are rounded to each description's own +// alignment, so a multisampled neighbour at 4 MiB keeps its place, and sums saturate instead of wrapping. When +// `each` is given it receives every description's offset, alignment and size. +// +// Returns false, and writes nothing, when no description is a console render target that grows, or when the PC +// device refuses one: the PC answer then stands. A true answer is never below what the PC device gave for the same +// descriptions laid out in that way. +template +bool console_placement(const D3D12_RESOURCE_DESC* descs, UINT count, PcOne pc_one, + D3D12_RESOURCE_ALLOCATION_INFO& total, D3D12_RESOURCE_ALLOCATION_INFO1* each) { + if (!descs) return false; + bool any_target = false; + for (UINT i = 0; i < count && !any_target; ++i) any_target = console_render_target_size(descs[i]) != 0; + if (!any_target) return false; + // Two passes when `each` is wanted: the first decides, the second writes, so a refusal or a list that does not + // grow leaves the array as the PC device filled it. + for (const bool write : {false, true}) { + if (write && !each) break; + bool grows = false; + UINT64 end = 0, alignment = 1; + for (UINT i = 0; i < count; ++i) { + const D3D12_RESOURCE_ALLOCATION_INFO one = pc_one(i); + if (one.SizeInBytes == UINT64_MAX || !one.Alignment) return false; + UINT64 size = one.SizeInBytes; + const UINT64 console = console_render_target_size(descs[i]); + if (console > size) { + size = align_up_saturating(console, one.Alignment); + grows = true; + } + const UINT64 offset = align_up_saturating(end, one.Alignment); + if (write) each[i] = {offset, one.Alignment, size}; + end = size > UINT64_MAX - offset ? UINT64_MAX : offset + size; + alignment = std::max(alignment, one.Alignment); + } + if (!grows) return false; + total = {align_up_saturating(end, alignment), alignment}; + } + return true; +} + +} // namespace rt::d3d12_xs diff --git a/runtime/shims/d3d12_xs_command_list_iid.h b/runtime/shims/d3d12_xs_command_list_iid.h new file mode 100644 index 0000000000..fc149cea90 --- /dev/null +++ b/runtime/shims/d3d12_xs_command_list_iid.h @@ -0,0 +1,68 @@ +// Console command-list interface IDs for device slot 73 (CreateCommandListX). The console passes an IID whose PC +// counterpart is a different GUID with the same first 32 bits, so a call that asks for it fails on the PC device +// with E_NOINTERFACE. Only measured pairs go in the table: +// - console c3827890-4024-474c-98cf-645b51dc4874: the riid the 1.0.2.1 executable passes to slot 73 (its only GUID +// of that form in .rdata); also in TomBox's console QueryInterface list (crates/compat/d3d12_xs/src/perfctr_xs.rs +// line 230, commit f89e4106fe of omonkeyz/xbox-emulator, GPL-3.0); +// - PC ID3D12GraphicsCommandList6, c3827890-e548-4cfa-96cf-5689a9370f80 (Windows SDK 10.0.26100.0 d3d12.h). +// Matching is on the whole GUID. An IID that is not in the table is forwarded unchanged, and logged once. +#pragma once + +#include +#include +#include + +#include +#include + +namespace rt::d3d12_xs { + +struct CommandListIidPair { + GUID console; + GUID pc; +}; + +inline constexpr CommandListIidPair kCommandListIidPairs[] = { + // ID3D12GraphicsCommandList6 + {{0xc3827890, 0x4024, 0x474c, {0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74}}, + {0xc3827890, 0xe548, 0x4cfa, {0x96, 0xcf, 0x56, 0x89, 0xa9, 0x37, 0x0f, 0x80}}}, +}; + +// True for the PC command-list IIDs a title may also pass (ID3D12CommandList, ID3D12GraphicsCommandList..7): those +// need no mapping and no log line. +inline bool is_pc_command_list_iid(const GUID& iid) { + static const GUID kPcIids[] = { + __uuidof(ID3D12CommandList), __uuidof(ID3D12GraphicsCommandList), + __uuidof(ID3D12GraphicsCommandList1), __uuidof(ID3D12GraphicsCommandList2), + __uuidof(ID3D12GraphicsCommandList3), __uuidof(ID3D12GraphicsCommandList4), + __uuidof(ID3D12GraphicsCommandList5), __uuidof(ID3D12GraphicsCommandList6), + __uuidof(ID3D12GraphicsCommandList7), + }; + for (const GUID& pc : kPcIids) { + if (IsEqualGUID(pc, iid)) return true; + } + return false; +} + +// The PC IID for a console command-list IID in the table; `requested` itself otherwise. `mapped` (optional) reports +// whether a substitution was made. +inline const GUID& command_list_iid_for_pc(const GUID& requested, bool* mapped = nullptr) { + for (const CommandListIidPair& pair : kCommandListIidPairs) { + if (IsEqualGUID(pair.console, requested)) { + if (mapped) *mapped = true; + return pair.pc; + } + } + if (mapped) *mapped = false; + if (is_pc_command_list_iid(requested)) return requested; // already a PC IID: nothing to report + static std::atomic logged{false}; + if (!logged.exchange(true)) { + std::fprintf(stderr, + "[rt] d3d12_xs: command list IID %08lx-%04x-%04x is not in the console table; forwarded unchanged\n", + static_cast(requested.Data1), static_cast(requested.Data2), + static_cast(requested.Data3)); + } + return requested; +} + +} // namespace rt::d3d12_xs diff --git a/runtime/shims/d3d12_xs_desc_clean.h b/runtime/shims/d3d12_xs_desc_clean.h new file mode 100644 index 0000000000..77f7e32817 --- /dev/null +++ b/runtime/shims/d3d12_xs_desc_clean.h @@ -0,0 +1,55 @@ +// The PC form of a resource description the retail title builds for the console, for the Xbox-ABI device proxy. +// +// The title's D3D12_RESOURCE_DESC carries console values the PC device cannot take: the layout word is 0x101 (tiled) +// or 0x1 (row-major buffer), and the flags have bits above the PC ones set (docs/retail_boot_chain.md, #6982). Slot 76 +// replaces the layout word the same way before it forwards to CreateCommittedResource; slot 25 and the slot 127 +// stand-in need the same cleaning. The title's own description is never written: a caller gets a copy. +#pragma once + +#include +#include + +#include + +namespace rt::d3d12_xs { + +// The D3D12_RESOURCE_FLAGS bits the PC runtime defines; every other bit is a console one. +constexpr std::uint32_t kPcResourceFlagsMask = + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE | + D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER | D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS | + D3D12_RESOURCE_FLAG_VIDEO_DECODE_REFERENCE_ONLY | D3D12_RESOURCE_FLAG_VIDEO_ENCODE_REFERENCE_ONLY | + D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE; + +// Not constexpr: 0x101 is outside the unfixed enum's value range, which clang-cl rejects in a constant expression. +inline const auto kXboxTiledResourceLayout = static_cast(0x101); + +// The console allows a depth-stencil texture to allow unordered access too (measured locally at a title's call sites: +// a 2D R32G8X24_TYPELESS texture with ALLOW_DEPTH_STENCIL | ALLOW_UNORDERED_ACCESS, sized through slot 25), but the PC +// runtime refuses that pair, and Vulkan has no depth format with storage support to make it with. Stand-in: such a +// texture is a depth-stencil texture without unordered access. Its unordered-access views write no descriptor (the PC +// layer refuses a UAV of a texture without the flag), so what a shader writes through them goes nowhere and their +// reads see whatever the descriptor held. +inline std::uint32_t without_depth_stencil_uav(D3D12_RESOURCE_DIMENSION dimension, std::uint32_t flags) { + if (dimension != D3D12_RESOURCE_DIMENSION_BUFFER && (flags & D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)) + flags &= ~static_cast(D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + return flags; +} + +// The PC flags of a console description: the PC bits only, without unordered access on a depth-stencil texture. +inline std::uint32_t pc_resource_flags(D3D12_RESOURCE_DIMENSION dimension, std::uint32_t xbox_flags) { + return without_depth_stencil_uav(dimension, xbox_flags & kPcResourceFlagsMask); +} + +// Strip Xbox-only flags and translate the Xbox tiled layout. Preserve all other layouts so the host can validate them. +inline D3D12_RESOURCE_DESC pc_resource_desc(const D3D12_RESOURCE_DESC& xbox) { + D3D12_RESOURCE_DESC pc = xbox; + if (pc.Layout == kXboxTiledResourceLayout) { + pc.Layout = pc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? D3D12_TEXTURE_LAYOUT_ROW_MAJOR + : D3D12_TEXTURE_LAYOUT_UNKNOWN; + } + pc.Flags = static_cast(pc_resource_flags(xbox.Dimension, static_cast(xbox.Flags))); + return pc; +} + +} // namespace rt::d3d12_xs diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 1045b86fb9..9bfa5ea7f4 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -5,10 +5,12 @@ // the same index through a 15-argument integer prototype. Every PC D3D12 device method takes integer/pointer // arguments only, so the x64 registers and stack words line up exactly; methods that return a struct keep their // hidden return pointer in RDX, which is passed through as the first argument unchanged. The measured exceptions -// are IUnknown (0-2), slot 14 (which wraps the heap), 62 and 76, plus the heap proxy's 9/10 conversion from the -// PC hidden-pointer form to the Xbox RAX form. Slots 8/75 (command queues), 36 (fences) and 32 (a shared fence) wrap -// what they create in queue and fence proxies built the same way, and slots 31/34/35/45/46/50 hand the real objects -// behind heap, queue and fence proxies to the real device (see the command queue and fence section). +// are IUnknown (0-2), slot 14 (which wraps the heap), 26 (the title passes the return buffer in RCX and the device in +// RDX), the struct-returning slot 25 (same C ABI form: see "Struct-returning device methods" below), +// 48 (a queue creation, where the PC has OpenExistingHeapFromAddress), 62 and 76, plus the heap proxy's 9/10 +// conversion from the PC hidden-pointer form to the Xbox RAX form. Slots 8/75 (command queues), 36 (fences) and 32 (a +// shared fence) wrap what they create in queue and fence proxies built the same way, and slots 31/34/35/45/46/50 hand +// the real objects behind heap, queue and fence proxies to the real device (see the command queue and fence section). // // A thunk declares 14 argument words, but the title passes only as many as the method takes, so the caller's frame // may end right after the four register homes. The compiler owns a function's incoming stack-argument slots and may @@ -22,14 +24,27 @@ // 78 SetFrameIntervalX, 79 ScheduleFrameEventX and 80 WaitFrameEventX. The slots can be moved with LEONIDA_XS_*_SLOT // for a trace that disagrees. The frame-event calls answer from a per-device token counter: there is no vblank source // behind the device before a presenter exists, so WaitFrameEventX returns at once with a fresh non-zero token. +#include "../src/title_va_alias.h" +#include "title_window.h" #include "d3d12_xs_device.h" #include "d3d12_trace.h" +#include "d3d12_xs_alloc_size.h" +#include "d3d12_xs_desc_clean.h" +#include "../src/frame_pacer.h" #include "../src/shader_library.h" // leonida::fspx_payload_from_parts for slot 67 +#ifdef LEONIDA_VULKAN_DEVICE +// PresentX wiring: the queue's console slots land on the Xbox presentation core, which needs the Vulkan layer's +// WindowPresenter. Other builds of this file (mock and COM tests) keep the refused-slot behaviour. +#include "xbox_present.h" +#endif + #include #include +#include #include +#include #include #include #include @@ -37,9 +52,17 @@ #include #include #include +#include +#include #include +#include #include +#include +#include #include +#include + +#include "d3d12_xs_command_list_iid.h" namespace rt::d3d12_xs { namespace { @@ -48,9 +71,6 @@ namespace { // vtable goes through the generic thunk and is refused with E_NOTIMPL, so the table must outlast the highest one. constexpr unsigned kMaxSlots = 192; static_assert(kMaxSlots > 133, "the proxy table must cover the slots the retail title calls (up to 133)"); - -// Set by the Vulkan device behind the proxy; slot 14 uses it for a console-extended CreateDescriptorHeap. -std::atomic g_console_descriptor_heap{nullptr}; static_assert(kMaxSlots > 83, "the proxy table must cover ID3D12Device14 (83 slots)"); static_assert(sizeof(void*) == 8, "the Xbox-ABI proxy is x64-only"); static_assert(sizeof(D3D12_CPU_DESCRIPTOR_HANDLE) == 8, @@ -63,9 +83,23 @@ struct DeviceProxy { void** real_vtable; unsigned slot_count; // number of valid entries in real_vtable std::atomic refs; + // The PresentX state (window, presenter, XboxPresentation) the first queue PresentX builds on this device, + // under LEONIDA_VULKAN_DEVICE; always null elsewhere. Opaque: PresentState is defined with the queue proxy. + void* present_state = nullptr; + // The upload-memory arena console list slot 148 (AllocateUploadMemory) carves from; always null until the + // first call. Opaque: UploadArena is defined with the list proxy. Atomic: lists record on several threads + // at once, so the first AllocateUploadMemory installs the arena by compare-exchange. + std::atomic upload_state{nullptr}; + // The console runtime layout this title was built against (docs/d3d12_xs_console_abi.md §4): the queue proxy + // writes it on detection and every object shares it — the queue/list slot tails shift +2 under the newer one. + std::atomic console_layout{0}; // 0 unknown, 1 older, 2 newer + // Set by create_device_proxy: false hands real (PC-shaped) lists back from CreateCommandList for callers + // compiled against the PC headers. + bool console_lists = true; // The device's IDXGIDevice1 (see "IDXGIDevice1 on the device" below): a title's IDXGIDevice1* points here. void** dxgi_vtable; DxgiAdapterProvider adapter_provider; + ResourceByVaProvider resource_provider; // slot 70: a buffer by console VA; null leaves slot 70 on the null view std::atomic gpu_thread_priority; std::atomic max_frame_latency; // The first-frame subset of SetFrameIntervalX/ScheduleFrameEventX/WaitFrameEventX. Tokens were never measured; @@ -74,9 +108,13 @@ struct DeviceProxy { std::atomic frame_interval_us{0}; std::atomic frame_latency{1}; std::atomic frame_event_scheduled{false}; - std::atomic frame_next_token{1}; + std::shared_ptr frame_tokens = std::make_shared(); }; +// Freed in proxy_release; defined where the states are complete. +void destroy_present_state(void* present_state); +void destroy_upload_state(void* upload_state); + constexpr unsigned kHeapSlots = 11; // IUnknown + ID3D12Object + DeviceChild + Pageable + GetDesc + 2 handles struct HeapProxy { @@ -85,8 +123,164 @@ struct HeapProxy { DeviceProxy* device; // keeps the Xbox-ABI device alive; GetDevice returns it void** real_vtable; std::atomic refs; + // Non-zero when the title's XMem allocation hook supplied the heap's backing address: slot 9 returns + // custom_cpu_start and device descriptor calls translate [custom_cpu_start, +custom_byte_size) to real_cpu_start. + SIZE_T custom_cpu_start; + SIZE_T custom_byte_size; + SIZE_T real_cpu_start; + DescriptorHeapBackingFree custom_free; +}; + +struct DescriptorRange { + SIZE_T custom_start; + SIZE_T custom_end; // exclusive + SIZE_T real_start; + const DeviceProxy* device; + const HeapProxy* heap; }; +// Immortal: late COM Release calls during process teardown may still unregister a heap or check the table. +std::mutex& descriptor_range_mutex() { + static auto* m = new std::mutex; + return *m; +} + +std::vector& descriptor_ranges() { + static auto* v = new std::vector; + return *v; +} + +std::atomic g_custom_range_count{0}; + +std::mutex& heap_alloc_mutex() { + static auto* m = new std::mutex; + return *m; +} + +DescriptorHeapBackingAlloc g_heap_alloc = nullptr; +DescriptorHeapBackingFree g_heap_free = nullptr; +bool g_heap_alloc_explicit = false; + +bool register_descriptor_range(const DeviceProxy* device, const HeapProxy* heap, SIZE_T custom_start, + SIZE_T byte_size, SIZE_T real_start) { + if (custom_start == 0 || byte_size == 0 || custom_start > (std::numeric_limits::max)() - byte_size) + return false; + try { + std::lock_guard lock(descriptor_range_mutex()); + descriptor_ranges().push_back({custom_start, custom_start + byte_size, real_start, device, heap}); + g_custom_range_count.store(descriptor_ranges().size(), std::memory_order_release); + return true; + } catch (const std::bad_alloc&) { + return false; + } +} + +void unregister_descriptor_range(const HeapProxy* heap) { + if (g_custom_range_count.load(std::memory_order_acquire) == 0) return; + std::lock_guard lock(descriptor_range_mutex()); + auto& ranges = descriptor_ranges(); + for (auto it = ranges.begin(); it != ranges.end();) { + if (it->heap == heap) { + it = ranges.erase(it); + } else { + ++it; + } + } + g_custom_range_count.store(ranges.size(), std::memory_order_release); +} + +D3D12_CPU_DESCRIPTOR_HANDLE translate_cpu_handle(const DeviceProxy* device, D3D12_CPU_DESCRIPTOR_HANDLE handle) { + if (handle.ptr == 0 || g_custom_range_count.load(std::memory_order_acquire) == 0) return handle; + std::lock_guard lock(descriptor_range_mutex()); + const auto& ranges = descriptor_ranges(); + for (auto it = ranges.rbegin(); it != ranges.rend(); ++it) { + if (device && it->device != device) continue; + if (handle.ptr >= it->custom_start && handle.ptr < it->custom_end) { + return D3D12_CPU_DESCRIPTOR_HANDLE{it->real_start + (handle.ptr - it->custom_start)}; + } + } + return handle; +} + +// LOCAL (title-backed descriptor heaps): the title copies descriptors between its heaps' backing memory itself, with +// no API call, so (1) every descriptor the layer writes for a title-backed slot is also stored at the title's address, +// and (2) when a table is bound, what the title wrote at that table's address is carried into the real heap. +// LEONIDA_DESC_MIRROR=0 turns both off. +constexpr SIZE_T kLocalDescriptorBytes = 32; +constexpr SIZE_T kLocalMirrorSlots = 64; + +bool local_desc_mirror() { + static const bool on = [] { const char* v = std::getenv("LEONIDA_DESC_MIRROR"); return !(v && *v == '0'); }(); + return on; +} + +// Whether [address, address + bytes) is committed memory that can be read (and, with `write`, written). A handle +// that is only a number (a mock's, or a range the title has released) is left alone instead of faulting. +bool local_accessible(std::uint64_t address, std::uint64_t bytes, bool write) { + const std::uint64_t end = address + bytes; + if (!address || end < address) return false; + while (address < end) { + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(reinterpret_cast(address), &info, sizeof(info)) || info.State != MEM_COMMIT) + return false; + const DWORD protect = info.Protect & 0xff; + if (info.Protect & PAGE_GUARD) return false; + const bool writable = protect == PAGE_READWRITE || protect == PAGE_WRITECOPY || + protect == PAGE_EXECUTE_READWRITE || protect == PAGE_EXECUTE_WRITECOPY; + const bool readable = writable || protect == PAGE_READONLY || protect == PAGE_EXECUTE_READ; + if (write ? !writable : !readable) return false; + address = reinterpret_cast(info.BaseAddress) + info.RegionSize; + } + return true; +} + +void local_write_through(const DeviceProxy* device, D3D12_CPU_DESCRIPTOR_HANDLE custom, SIZE_T count) { + if (!local_desc_mirror() || !custom.ptr || !count) return; + const D3D12_CPU_DESCRIPTOR_HANDLE real = translate_cpu_handle(device, custom); + if (real.ptr == custom.ptr) return; + if (!local_accessible(real.ptr, count * kLocalDescriptorBytes, false) || + !local_accessible(custom.ptr, count * kLocalDescriptorBytes, true)) + return; + std::memcpy(reinterpret_cast(custom.ptr), reinterpret_cast(real.ptr), + count * kLocalDescriptorBytes); + static std::atomic said{false}; + if (!said.exchange(true)) + std::fprintf(stderr, "[rt] d3d12_xs: local: descriptors written for a title-backed heap are also stored at the " + "title's address\n"); +} + +D3D12_GPU_DESCRIPTOR_HANDLE local_real_gpu_start(const HeapProxy* heap); + +void local_mirror_table(const DeviceProxy* device, std::uint64_t gpu_handle) { + if (!local_desc_mirror() || !gpu_handle || g_custom_range_count.load(std::memory_order_acquire) == 0) return; + std::lock_guard lock(descriptor_range_mutex()); + for (const DescriptorRange& range : descriptor_ranges()) { + if ((device && range.device != device) || !range.heap) continue; + const std::uint64_t gpu_start = local_real_gpu_start(range.heap).ptr; + const std::uint64_t bytes = range.custom_end - range.custom_start; + if (!gpu_start || gpu_handle < gpu_start || gpu_handle >= gpu_start + bytes) continue; + const std::uint64_t offset = (gpu_handle - gpu_start) / kLocalDescriptorBytes * kLocalDescriptorBytes; + const std::uint64_t slots = (std::min)(kLocalMirrorSlots, (bytes - offset) / kLocalDescriptorBytes); + if (!local_accessible(range.custom_start + offset, slots * kLocalDescriptorBytes, false) || + !local_accessible(range.real_start + offset, slots * kLocalDescriptorBytes, true)) + return; + std::uint64_t copied = 0; + for (std::uint64_t i = 0; i < slots; ++i) { + const auto* from = reinterpret_cast(range.custom_start + offset + i * kLocalDescriptorBytes); + if (!(from[0] | from[1] | from[2] | from[3])) continue; // nothing the title wrote: keep the real slot + std::memcpy(reinterpret_cast(range.real_start + offset + i * kLocalDescriptorBytes), from, + kLocalDescriptorBytes); + ++copied; + } + static std::atomic said{0}; + if (said.fetch_add(1) < 4) + std::fprintf(stderr, "[rt] d3d12_xs: local: table at heap offset 0x%llx: %llu of %llu slots taken from the " + "title's backing memory\n", static_cast(offset), + static_cast(copied), static_cast(slots)); + return; + } +} + std::atomic g_hits[kMaxSlots]; std::atomic g_first[kMaxSlots]; std::atomic g_beyond_warned[kMaxSlots]; @@ -133,27 +327,45 @@ const char* slot_name(unsigned slot) { case 11: return "CreateComputePipelineState (PC slot 11)"; case 14: return "CreateDescriptorHeap"; case 16: return "CreateRootSignature"; - case 25: return "GetResourceAllocationInfo"; + case 17: return "CreateConstantBufferView (CPU handle translated)"; + case 18: return "CreateShaderResourceView (CPU handle translated)"; + case 19: return "CreateUnorderedAccessView (CPU handle translated)"; + case 20: return "CreateRenderTargetView (CPU handle translated)"; + case 21: return "CreateDepthStencilView (CPU handle translated)"; + case 22: return "CreateSampler (CPU handle translated)"; + case 23: return "CopyDescriptors (CPU handles translated)"; + case 24: return "CopyDescriptorsSimple (CPU handles translated)"; + case 25: return "GetResourceAllocationInfo (C or PC form)"; + case 26: return "GetCustomHeapProperties (C or PC form)"; case 27: return "CreateCommittedResource (PC slot 27)"; case 31: return "CreateSharedHandle (proxies unwrapped)"; case 32: return "OpenSharedHandle (a fence comes back wrapped)"; case 34: return "MakeResident (proxies unwrapped)"; case 35: return "Evict (proxies unwrapped)"; case 36: return "CreateFence -> fence proxy"; + case 41: return "CreateCommandSignature (Xbox argument type 105 as DISPATCH)"; case 43: return "GetAdapterLuid"; case 45: return "SetEventOnMultipleFenceCompletion (fence proxies unwrapped)"; case 46: return "SetResidencyPriority (proxies unwrapped)"; - case 48: return "Xbox CreateCommandQueueX -> queue proxy"; + case 48: return "Xbox CreateCommandQueueX (32-byte desc) -> queue proxy"; case 50: return "EnqueueMakeResident (proxies unwrapped)"; + case 56: return "GetResourceAllocationInfo1 (C or PC form)"; + case 61: return "Xbox CreateSamplerX -> PC CreateSampler"; case 62: return "Xbox CreateComputePipelineState"; case 67: return "Xbox DeserializeComputePipelineStateX"; + case 70: return "Xbox shader-resource view from raw words"; case 73: return "Xbox CreateCommandListX -> PC CreateCommandList"; + case 74: return "Xbox (pointer, u32, pointer) stand-in"; case 75: return "CreateCommandQueue1 -> queue proxy"; + case 133: return "Xbox CreatePlacedResourceX -> committed resource"; case 76: return "Xbox resource creation"; + case 127: return "Xbox CreateCommittedResource3"; case 78: return "Xbox SetFrameIntervalX"; case 79: return "Xbox ScheduleFrameEventX"; case 80: return "Xbox WaitFrameEventX"; - case 133: return "Xbox CreatePlacedResourceX (a buffer on the title's pages)"; + case 86: return "Xbox CreatePipelineState -> PC CreatePipelineState (slot 47)"; + case 101: return "Xbox CreateStateObject -> PC CreateStateObject (slot 62)"; + case 108: return "Xbox GetResourceAllocationInfo2 -> PC GetResourceAllocationInfo2 (slot 68)"; default: return "forwarded"; } } @@ -278,6 +490,8 @@ unsigned long proxy_release(DeviceProxy* self) { note_slot(2); const unsigned long refs = self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; if (refs == 0) { + destroy_present_state(self->present_state); + destroy_upload_state(self->upload_state.load(std::memory_order_relaxed)); ID3D12Device* real = self->real; delete self; if (real) real->Release(); @@ -490,11 +704,15 @@ unsigned long heap_release(HeapProxy* self) { note_heap_slot(2); const unsigned long refs = self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; if (refs == 0) { + if (self->custom_cpu_start != 0) unregister_descriptor_range(self); + void* const backing = reinterpret_cast(self->custom_cpu_start); + const DescriptorHeapBackingFree free_fn = self->custom_free; ID3D12DescriptorHeap* real = self->real; DeviceProxy* device = self->device; delete self; if (real) real->Release(); if (device) proxy_release(device); + if (backing && free_fn) free_fn(backing, kXmemDescriptorHeapAttributes); } return refs; } @@ -529,17 +747,21 @@ HRESULT heap_get_device(HeapProxy* self, const IID* riid, void** out) { // The PC methods write through the hidden return pointer (RDX) on the measured runtime; the Xbox ABI wants the // 8-byte value in RAX. Call with both conventions and keep whichever produced a value, so a runtime that really // returns in RAX also works. The extra register is harmless when the callee ignores it. -D3D12_CPU_DESCRIPTOR_HANDLE heap_get_cpu_handle(HeapProxy* self) { - note_heap_slot(9); +D3D12_CPU_DESCRIPTOR_HANDLE raw_heap_get_cpu_handle(ID3D12DescriptorHeap* real, void** real_vtable) { constexpr SIZE_T kUnset = ~static_cast(0); D3D12_CPU_DESCRIPTOR_HANDLE handle{}; handle.ptr = kUnset; using Fn = D3D12_CPU_DESCRIPTOR_HANDLE(WINAPI*)(ID3D12DescriptorHeap*, D3D12_CPU_DESCRIPTOR_HANDLE*); - const D3D12_CPU_DESCRIPTOR_HANDLE returned = - reinterpret_cast(self->real_vtable[9])(self->real, &handle); + const D3D12_CPU_DESCRIPTOR_HANDLE returned = reinterpret_cast(real_vtable[9])(real, &handle); return handle.ptr != kUnset ? handle : returned; } +D3D12_CPU_DESCRIPTOR_HANDLE heap_get_cpu_handle(HeapProxy* self) { + note_heap_slot(9); + if (self->custom_cpu_start != 0) return D3D12_CPU_DESCRIPTOR_HANDLE{self->custom_cpu_start}; + return raw_heap_get_cpu_handle(self->real, self->real_vtable); +} + D3D12_GPU_DESCRIPTOR_HANDLE heap_get_gpu_handle(HeapProxy* self) { note_heap_slot(10); constexpr UINT64 kUnset = ~static_cast(0); @@ -551,6 +773,15 @@ D3D12_GPU_DESCRIPTOR_HANDLE heap_get_gpu_handle(HeapProxy* self) { return handle.ptr != kUnset ? handle : returned; } +D3D12_GPU_DESCRIPTOR_HANDLE local_real_gpu_start(const HeapProxy* heap) { + constexpr UINT64 kUnset = ~static_cast(0); + D3D12_GPU_DESCRIPTOR_HANDLE handle{}; + handle.ptr = kUnset; + using Fn = D3D12_GPU_DESCRIPTOR_HANDLE(WINAPI*)(ID3D12DescriptorHeap*, D3D12_GPU_DESCRIPTOR_HANDLE*); + const D3D12_GPU_DESCRIPTOR_HANDLE returned = reinterpret_cast(heap->real_vtable[10])(heap->real, &handle); + return handle.ptr != kUnset ? handle : returned; +} + template std::uint64_t WINAPI heap_slot(HeapProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, @@ -595,7 +826,9 @@ void** get_heap_vtable() { return vtable; } -HRESULT create_heap_proxy(ID3D12DescriptorHeap* real, DeviceProxy* device, REFIID riid, void** out) { +HRESULT create_heap_proxy(ID3D12DescriptorHeap* real, DeviceProxy* device, REFIID riid, void** out, + SIZE_T custom_cpu_start = 0, SIZE_T custom_byte_size = 0, SIZE_T real_cpu_start = 0, + DescriptorHeapBackingFree custom_free = nullptr) { if (!real || !device) return E_POINTER; if (!out) return E_POINTER; *out = nullptr; @@ -607,11 +840,23 @@ HRESULT create_heap_proxy(ID3D12DescriptorHeap* real, DeviceProxy* device, REFII proxy->device = device; proxy->real_vtable = *reinterpret_cast(real); proxy->refs.store(1, std::memory_order_relaxed); + proxy->custom_cpu_start = custom_cpu_start; + proxy->custom_byte_size = custom_byte_size; + proxy->real_cpu_start = real_cpu_start; + proxy->custom_free = custom_free; proxy_add_ref(device); // the heap keeps its Xbox-ABI device alive for GetDevice + if (custom_cpu_start != 0 && + !register_descriptor_range(device, proxy, custom_cpu_start, custom_byte_size, real_cpu_start)) { + delete proxy; + proxy_release(device); + return E_OUTOFMEMORY; + } + const HRESULT hr = heap_query_interface(proxy, &riid, out); if (FAILED(hr)) { // No reference escaped, and the caller still owns its references to `real` and `device`. + if (custom_cpu_start != 0) unregister_descriptor_range(proxy); delete proxy; proxy_release(device); return hr; @@ -627,10 +872,17 @@ HRESULT create_heap_proxy(ID3D12DescriptorHeap* real, DeviceProxy* device, REFII // // Device slots 8 (CreateCommandQueue), 75 (CreateCommandQueue1), 36 (CreateFence) and 32 (OpenSharedHandle, for a // fence) wrap what they create, so a title never holds a PC or Vulkan-layer queue or fence. The proxies forward -// the public chain in PC order, exactly like the device proxy, and a slot past the PC vtable is logged and refused -// with E_NOTIMPL. PresentX, SuspendX and ResumeX are queue methods past the public chain -// (docs/d3d12_command_objects.md §5.3). Their slots are not known and nothing is guessed: the first run of the -// executable names them in the log. +// the public chain in PC order, exactly like the device proxy; on a fence a slot past the PC vtable is logged and +// refused with E_NOTIMPL, except fence slot 12, which returns the address of the +// completed value (its section below). PresentX, SuspendX and ResumeX are queue methods past the public chain +// (docs/d3d12_command_objects.md §5.3). A sibling layer measured two queue layouts on retail titles +// (docs/d3d12_xs_console_abi.md §4, unverified here): the older has Signal 14, Wait 15, +// GetTimestampFrequency 16, GetClockCalibration 17, GetDesc 18, SignalX 23, PresentX 30; a newer game +// OS inserts two methods before Signal, shifting to Signal 16, Wait 17, frequency 18, SignalX 25, +// PresentX 32 — a fence passed to slot 16 or 17 marks the newer layout, and the detection is shared +// across queues through the device. PresentX is wired to the Vulkan layer's Xbox presentation, +// SignalX forwards as Signal, and the unmodelled console-only slots answer S_OK (the PresentX +// section below); the first run of the executable confirms which layout. // // Slot numbers are those of the Windows SDK 10.0.26100 d3d12.h: ID3D12CommandQueue has 19, ID3D12Fence 11 and // ID3D12Fence1 12. That the console keeps these public slots, and keeps device slots 8/32/36/75, is an assumption @@ -648,11 +900,10 @@ HRESULT create_heap_proxy(ID3D12DescriptorHeap* real, DeviceProxy* device, REFII // passed there: queue Signal/Wait (14/15) take a fence; device CreateSharedHandle (31) a device child, // MakeResident/Evict (34/35), SetResidencyPriority (46) and EnqueueMakeResident (50) pageables, and // SetEventOnMultipleFenceCompletion (45) and EnqueueMakeResident fences. The heap proxies of slot 14 are pageables -// and device children too and are unwrapped in the same places. Command lists are not wrapped yet, so -// ExecuteCommandLists passes them through, and a heap proxy still reaches the real runtime through the list's -// SetDescriptorHeaps. A command-list proxy (docs/d3d12_command_objects.md §3.5a) adds its vtable to -// proxy_real_object, which every unwrap goes through, and a queue slot 10 branch in child_slot that unwraps the list -// array (UnwrappedArray) before forwarding, and unwraps heap proxies in its own SetDescriptorHeaps. +// and device children too and are unwrapped in the same places. Command lists from device slot 12 come back +// console-shaped (the list proxy below): queue ExecuteCommandLists (10) unwraps the list array, the list's own +// Reset and ExecuteBundle unwrap allocator and bundle proxies, and its SetDescriptorHeaps unwraps heap proxies — +// all through proxy_real_object, so any object kind added later unwraps in every place at once. // // QueryInterface answers only the interfaces the proxy models (the base chain and its own interface, Fence1 when // the real fence has it), like the device and heap proxies, so the COM identity holds and no real object leaks to @@ -681,7 +932,17 @@ static_assert(kQueueSlots * sizeof(void*) <= 4096 && kFenceSlots * sizeof(void*) kAllocatorSlots * sizeof(void*) <= 4096, "a table must fit in the first page of its reservation"); +constexpr unsigned kQueueExecuteCommandLists = 10; // (UINT, ID3D12CommandList* const*) constexpr unsigned kQueueSignal = 14, kQueueWait = 15; // (ID3D12Fence*, UINT64) +constexpr unsigned kFenceSignal = 10; // ID3D12Fence::Signal(UINT64), from the CPU +constexpr unsigned kFenceCompletedValueSlot = 12; // one past ID3D12Fence1: the completed value's address +static_assert(kFenceCompletedValueSlot >= kFence1PublicSlots && kFenceCompletedValueSlot < kFenceSlots, + "fence slot 12 is past the public chain and inside the table"); + +struct FenceMirror; +constexpr unsigned kQueueExecuteCommandListsX = 35; // console ExecuteCommandLists(count, lists) variant +static_assert(kQueueExecuteCommandLists < kQueuePublicSlots && kQueueExecuteCommandListsX < kQueueSlots, + "queue execution slots must stay within their respective tables"); struct ChildProxy { void** vtable; // offset 0: the caller's ID3D12CommandQueue* / ID3D12Fence* points here @@ -690,6 +951,18 @@ struct ChildProxy { void** real_vtable; unsigned slot_count; // public slots the real object implements; the rest of the table is refused std::atomic refs; + // Queues only: the console runtime layout this title was built against (docs/d3d12_xs_console_abi.md §4), + // detected by a fence reaching slot 16/17 or SignalX slot 25. Unused on fences and allocators. A queue is + // used from many threads, so the cache of the device's shared detection is atomic like the shared flag + // itself. + static constexpr unsigned char kQueueLayoutUnknown = 0; + static constexpr unsigned char kQueueLayoutOlder = 1; // PC order; PresentX 30, SignalX 23 + static constexpr unsigned char kQueueLayoutNewer = 2; // +2 shift; PresentX 32, SignalX 25 + std::atomic queue_layout{kQueueLayoutUnknown}; + std::atomic mirror{nullptr}; // fence: slot 12's completed value, made on its first call + // Allocators only: callback and context recorded by console slot 9 (SetAllocatorCallbackX). + std::atomic allocator_callback{0}; + std::atomic allocator_callback_context{0}; }; template @@ -722,10 +995,12 @@ const char* child_public_name(unsigned slot) { if (slot < 8) return object[slot]; if constexpr (K == ChildKind::queue) { if (slot < kQueuePublicSlots) return queue[slot - 8]; + if (slot == kQueueExecuteCommandListsX) return "ExecuteCommandListsX"; } else if constexpr (K == ChildKind::fence) { if (slot < kFence1PublicSlots) return fence[slot - 8]; } else { if (slot == 8) return "Reset"; + if (slot == 9) return "SetAllocatorCallbackX"; } return nullptr; } @@ -781,12 +1056,127 @@ void reset_child_stats() { S::overruns.store(0, std::memory_order_relaxed); } -// Frees a proxy whose last reference is gone, with the real object and the device reference it held. +// ---- Fence slot 12: the completed value at an address ---- +// +// Measured on the retail executable (a run past the PC chain, #6982): fence slot 12, one past ID3D12Fence1, is called +// as (value, descriptor, flags), where the descriptor is four words whose second is a code pointer, and the title +// reads the return as a pointer to the fence's 64-bit completed value. It compares that value with ~0 (device +// removed) and subtracts the value it waits for. Refused with E_NOTIMPL, the title dereferences 0x80004001. +// +// A console fence keeps that value in memory the GPU writes. Here each fence gets a mirror that stays live without +// the title calling anything. A thread-pool wait refreshes on a completion event or a timeout. A timeout can +// observe a rewind and subsequent values below the outstanding event's threshold. It does not add another +// completion event. Slot 12 and CPU Signal refresh synchronously. After device removal the callback stops waiting. +// +// The descriptor's code pointer is not called: the measured run goes on without it, and its contract (when it runs, +// on which thread, with what) is not known. The first call is logged with its arguments. +struct FenceMirror { + alignas(8) volatile std::uint64_t completed = 0; // what the title reads through slot 12's pointer + ID3D12Fence* fence = nullptr; // the real fence; the proxy holds the reference + SRWLOCK lock = SRWLOCK_INIT; // orders refreshes + HANDLE event = nullptr; // auto-reset; the real fence sets it at the armed value + PTP_WAIT wait = nullptr; // the thread-pool wait on the completion event + bool stopping = false; // guarded by lock + std::atomic arm_failed{false}; +}; + +std::uint64_t refresh_mirror(FenceMirror* m) { + AcquireSRWLockExclusive(&m->lock); + const std::uint64_t value = m->fence->GetCompletedValue(); + if (m->completed != value) m->completed = value; + ReleaseSRWLockExclusive(&m->lock); + return value; +} + +void wait_for_fence_progress(FenceMirror* mirror) { + constexpr LONGLONG kRewindPollInterval = -10 * 10'000; // 10 ms in relative 100 ns units + ULARGE_INTEGER due{}; + due.QuadPart = static_cast(kRewindPollInterval); + FILETIME timeout{due.LowPart, due.HighPart}; + SetThreadpoolWait(mirror->wait, mirror->event, &timeout); +} + +VOID CALLBACK on_fence_progress(PTP_CALLBACK_INSTANCE, PVOID context, PTP_WAIT, TP_WAIT_RESULT result) { + auto* mirror = static_cast(context); + const std::uint64_t value = refresh_mirror(mirror); + if (value == ~std::uint64_t{0}) return; + if (result == WAIT_OBJECT_0) { + const HRESULT hr = mirror->fence->SetEventOnCompletion(value + 1, mirror->event); + if (FAILED(hr) && !mirror->arm_failed.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12_xs: fence slot 12: SetEventOnCompletion failed (0x%08lX); the completed " + "value at the returned address now uses periodic refresh\n", + static_cast(hr)); + } + AcquireSRWLockExclusive(&mirror->lock); + if (!mirror->stopping) wait_for_fence_progress(mirror); + ReleaseSRWLockExclusive(&mirror->lock); +} + +// The fence's mirror, made on the first slot 12 call. Null only when it cannot be allocated. +FenceMirror* fence_mirror(ChildProxy* self) { + if (FenceMirror* m = self->mirror.load(std::memory_order_acquire)) return m; + static SRWLOCK create_lock = SRWLOCK_INIT; + AcquireSRWLockExclusive(&create_lock); + FenceMirror* m = self->mirror.load(std::memory_order_relaxed); + if (!m && (m = new (std::nothrow) FenceMirror)) { + m->fence = reinterpret_cast(self->real); + refresh_mirror(m); + m->event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + if (m->event) m->wait = CreateThreadpoolWait(on_fence_progress, m, nullptr); + if (m->wait) { + wait_for_fence_progress(m); + SetEvent(m->event); // the callback makes the first SetEventOnCompletion + } else { + std::fprintf(stderr, "[rt] d3d12_xs: fence slot 12: no wait for the completed value (error %lu); it " + "moves only on slot 12 and Signal\n", GetLastError()); + if (m->event) CloseHandle(m->event); + m->event = nullptr; + m->wait = nullptr; + } + self->mirror.store(m, std::memory_order_release); + } + ReleaseSRWLockExclusive(&create_lock); + return m; +} + +// Fence slot 12 (value, descriptor, flags): the address of the fence's completed value, refreshed now. +std::uint64_t fence_completed_value_address(ChildProxy* self, std::uint64_t value, std::uint64_t descriptor, + std::uint64_t flags) { + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12_xs: fence slot 12 (value %llu, descriptor 0x%llx, flags 0x%llx): returns " + "the address of the fence's completed value, kept live; the descriptor is not used\n", + static_cast(value), static_cast(descriptor), + static_cast(flags)); + FenceMirror* m = fence_mirror(self); + if (!m) { + std::fprintf(stderr, "[rt] d3d12_xs: fence slot 12: out of memory for the completed value\n"); + return 0; + } + refresh_mirror(m); + return reinterpret_cast(&m->completed); +} + +// Frees a proxy whose last reference is gone, with the real object and the device reference it held. A fence's +// mirror wait is unregistered first, waiting for a callback in flight, so none runs on a released fence. void destroy_child(ChildProxy* self) { IUnknown* real = self->real; DeviceProxy* device = self->device; + FenceMirror* mirror = self->mirror.load(std::memory_order_acquire); + if (mirror && mirror->wait) { + AcquireSRWLockExclusive(&mirror->lock); + mirror->stopping = true; + SetThreadpoolWait(mirror->wait, nullptr, nullptr); + ReleaseSRWLockExclusive(&mirror->lock); + WaitForThreadpoolWaitCallbacks(mirror->wait, TRUE); + CloseThreadpoolWait(mirror->wait); + } delete self; if (real) real->Release(); + if (mirror) { + if (mirror->event) CloseHandle(mirror->event); + delete mirror; + } if (device) proxy_release(device); } @@ -880,42 +1270,19 @@ HRESULT child_get_device(ChildProxy* self, const IID* riid, void** out) { return proxy_query_interface(self->device, riid, out); } -void** get_heap_vtable(); -void** get_list_vtable(); - template void** get_child_vtable(); +// The command-list proxy's helpers (defined with the list proxy below): proxy_real_object checks lists through +// list_real_or_null, since the ListProxy type is complete only there. +IUnknown* list_real_or_null(const void* object); + template bool is_child_proxy(const void* object) { return object && *reinterpret_cast(object) == reinterpret_cast(get_child_vtable()); } -constexpr unsigned kListSlots = 160; -constexpr unsigned kConsoleSetDescriptorHeaps = 32; -constexpr unsigned kConsoleExecuteBundle = 31; -constexpr unsigned kConsoleBarrier = 146; - -struct ListProxy { - void** vtable; // +0x00 - ID3D12GraphicsCommandList* real; // +0x08 - DeviceProxy* device; // +0x10: keeps the Xbox-ABI device alive; GetDevice returns it - // +0x18..: the console object body a title's inline writers read. +0x18 holds the write cursor, +0x28 and - // +0x30 the record limits; the rest is room for the measured flags, header table and pipeline record. - alignas(8) std::uint8_t console_fields[0x600]; - std::atomic refs; // past the console body - unsigned pc_slot_count; // slots the real list implements; mapped slots past it are refused - - void pin_cursor_at_limit() { - const std::uint64_t at_limit = static_cast( - reinterpret_cast(this) + 0x18 + 0x500); - for (const size_t offset : {0x18, 0x28, 0x30}) - std::memcpy(reinterpret_cast(this) + offset, &at_limit, sizeof(at_limit)); - } -}; -static_assert(offsetof(ListProxy, console_fields) == 0x18, "the console fields start at +0x18"); - -// The real object behind a heap, queue, fence or list proxy, or null when `object` is none of them. +// The real object behind a heap, queue or fence proxy, or null when `object` is none of them. IUnknown* proxy_real_object(const void* object) { if (!object) return nullptr; void* const vtable = *reinterpret_cast(object); @@ -924,13 +1291,12 @@ IUnknown* proxy_real_object(const void* object) { vtable == reinterpret_cast(get_child_vtable()) || vtable == reinterpret_cast(get_child_vtable())) return static_cast(object)->real; - if (vtable == reinterpret_cast(get_list_vtable())) - return static_cast(object)->real; + if (IUnknown* real = list_real_or_null(object)) return real; return nullptr; } // `object` with a proxy replaced by its real object; anything else (a real object, null) unchanged. -inline std::uint64_t unwrap_object(std::uint64_t object) { +std::uint64_t unwrap_object(std::uint64_t object) { IUnknown* real = proxy_real_object(reinterpret_cast(object)); return real ? reinterpret_cast(real) : object; } @@ -964,190 +1330,6 @@ class UnwrappedArray { std::uint64_t* data_ = nullptr; }; -struct ListStats { - static inline std::atomic hits[kListSlots]; - static inline std::atomic first[kListSlots]; -}; - -inline void note_list_slot(unsigned slot, std::uint64_t a1 = 0, std::uint64_t a2 = 0, std::uint64_t a3 = 0, std::uint64_t a4 = 0) { - if (slot >= kListSlots) return; - ListStats::hits[slot].fetch_add(1, std::memory_order_relaxed); - bool expected = false; - if (ListStats::first[slot].compare_exchange_strong(expected, true, std::memory_order_relaxed)) - std::fprintf(stderr, "[rt] d3d12_xs: list slot %u first call (args 0x%llx 0x%llx 0x%llx 0x%llx)\n", slot, - static_cast(a1), static_cast(a2), - static_cast(a3), static_cast(a4)); -} - -inline bool is_list_iid(const IID& iid) { - return IsEqualIID(iid, __uuidof(IUnknown)) || IsEqualIID(iid, __uuidof(ID3D12Object)) || - IsEqualIID(iid, __uuidof(ID3D12DeviceChild)) || IsEqualIID(iid, __uuidof(ID3D12CommandList)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList1)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList2)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList3)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList4)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList5)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList6)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList7)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList8)); -} - -inline unsigned long list_add_ref(ListProxy* self) { return self->refs.fetch_add(1, std::memory_order_relaxed) + 1; } - -inline void destroy_list(ListProxy* self) { - IUnknown* real = self->real; - DeviceProxy* device = self->device; - delete self; - if (real) real->Release(); - if (device) proxy_release(device); -} - -inline unsigned long list_release(ListProxy* self) { - const unsigned long refs = self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; - if (refs == 0) destroy_list(self); - return refs; -} - -inline HRESULT list_query_interface(ListProxy* self, const IID* riid, void** out) { - note_list_slot(0, reinterpret_cast(riid), reinterpret_cast(out), 0, 0); - if (!out) return E_POINTER; - *out = nullptr; - if (!riid) return E_POINTER; - if (!is_list_iid(*riid)) { - if (supports_iid(self->real, *riid)) log_refused_iid("list", *riid); - return E_NOINTERFACE; - } - if (!supports_iid(self->real, *riid)) return E_NOINTERFACE; - *out = self; - list_add_ref(self); - return S_OK; -} - -inline unsigned detect_list_slot_count(IUnknown* real) { - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList8))) return 82; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList7))) return 81; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList6))) return 80; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList5))) return 79; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList4))) return 77; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList3))) return 68; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList2))) return 67; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList1))) return 66; - if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList))) return 60; - return 9; -} - -template -std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, - std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, - std::uint64_t a8, std::uint64_t a9, std::uint64_t a10, std::uint64_t a11, - std::uint64_t a12, std::uint64_t a13, std::uint64_t a14) { - if constexpr (Slot == 0) { - return hr_to_u64(list_query_interface(self, reinterpret_cast(a1), - reinterpret_cast(a2))); - } else if constexpr (Slot == 1) { - return list_add_ref(self); - } else if constexpr (Slot == 2) { - return list_release(self); - } else if constexpr (Slot == 7) { // GetDevice - note_list_slot(7, a1, a2, 0, 0); - if (a2) *reinterpret_cast(a2) = nullptr; - if (!a1) return hr_to_u64(E_POINTER); - if (!a2) { - using Fn = HRESULT(WINAPI*)(IUnknown*, const IID*, void**); - return hr_to_u64(reinterpret_cast((*reinterpret_cast(self->real))[7])( - self->real, reinterpret_cast(a1), nullptr)); - } - return hr_to_u64(proxy_query_interface(self->device, reinterpret_cast(a1), - reinterpret_cast(a2))); - } else { - note_list_slot(Slot, a1, a2, a3, a4); - constexpr unsigned pc = console_to_pc_list_slot(Slot); - if constexpr (pc == kListNotForwarded) { - if constexpr (Slot == 148) { - static std::atomic logged{false}; - if (!logged.exchange(true, std::memory_order_relaxed)) - std::fprintf(stderr, - "[rt] d3d12_xs: console list slot 148 AllocateUploadMemory stub called (size %llu, align %llu)\n", - static_cast(a1), static_cast(a2)); - } - return 0; - } else { - if (pc >= self->pc_slot_count) { - static std::atomic beyond_warned[kListSlots]; - bool expected = false; - if (beyond_warned[Slot].compare_exchange_strong(expected, true, std::memory_order_relaxed)) - std::fprintf(stderr, - "[rt] d3d12_xs: list slot %u maps to PC slot %u, beyond the real list's %u " - "slots; returning E_NOTIMPL\n", - Slot, pc, self->pc_slot_count); - return hr_to_u64(E_NOTIMPL); - } - using ForwardFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t, std::uint64_t, - std::uint64_t, std::uint64_t); - auto** const real_vtable = *reinterpret_cast(self->real); - UnwrappedArray heaps; - if constexpr (Slot == 10) { - a1 = unwrap_object(a1); - self->pin_cursor_at_limit(); - } else if constexpr (Slot == kConsoleExecuteBundle) { - a1 = unwrap_object(a1); - } else if constexpr (Slot == kConsoleSetDescriptorHeaps) { - if (!heaps.fill(a2, a1)) return 0; - if (heaps.data()) a2 = heaps.data(); - } - return reinterpret_cast(real_vtable[pc])(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, - a10, a11, a12, a13, a14); - } - } -} - -template -void fill_list_vtable(void** vtable, std::index_sequence) { - ((vtable[I] = reinterpret_cast(&list_slot(I)>)), ...); -} - -void** get_list_vtable() { - static void** vtable = [] { - static void* storage[kListSlots]; - fill_list_vtable(storage, std::make_index_sequence{}); - return storage; - }(); - return vtable; -} - -HRESULT wrap_list(IUnknown* created, DeviceProxy* device, const IID* riid, void** out) { - if (out) *out = nullptr; - if (!created) return E_FAIL; - auto* proxy = new (std::nothrow) ListProxy(); - if (!proxy) { - created->Release(); - return E_OUTOFMEMORY; - } - proxy->vtable = get_list_vtable(); - proxy->real = static_cast(created); - proxy->device = device; - proxy->refs.store(1, std::memory_order_relaxed); - proxy->pc_slot_count = detect_list_slot_count(created); - proxy->pin_cursor_at_limit(); - proxy_add_ref(device); - - const HRESULT hr = list_query_interface(proxy, riid, out); - if (FAILED(hr)) { - destroy_list(proxy); - return hr; - } - static std::atomic logged{false}; - if (!d3d12_trace::enabled() && (!logged.exchange(true, std::memory_order_relaxed) || trace_enabled())) - std::fprintf(stderr, "[rt] d3d12_xs: list proxy %p wraps %p (%u PC vtable slots)\n", - static_cast(proxy), static_cast(created), proxy->pc_slot_count); - proxy->refs.fetch_sub(1, std::memory_order_relaxed); - return S_OK; -} - // The vtable read for a slot past a table faults in the reservation behind it; name the slot. Only reads the // exception record and writes with WriteFile, so it is safe whatever the faulting thread holds. template @@ -1190,16 +1372,133 @@ LONG CALLBACK table_overrun_handler(EXCEPTION_POINTERS* info) { return EXCEPTION_CONTINUE_SEARCH; // diagnostics only: the fault goes on to the title's handlers or the crash } -template -std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, - std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, - std::uint64_t a8, std::uint64_t a9, std::uint64_t a10, std::uint64_t a11, - std::uint64_t a12, std::uint64_t a13, std::uint64_t a14) { - if constexpr (Slot == 0) { - d3d12_trace::record(child_trace_name(Slot)); - return hr_to_u64(child_query_interface(self, reinterpret_cast(a1), - reinterpret_cast(a2))); - } else if constexpr (Slot == 1) { +// ---- PresentX on the queue (LEONIDA_VULKAN_DEVICE) --------------------------------------------------------- +// +// The measured console queue slots (docs/d3d12_xs_console_abi.md §4): the older runtime keeps the PC order — +// Signal 14, Wait 15, frequency 16, calibration 17, GetDesc 18 — and presents at slot 30, with SignalX at 23. A +// newer game OS inserts two methods before Signal: Signal 16, Wait 17, frequency 18, calibration 19, GetDesc 20, +// SignalX 25, PresentX 32. The layout is detected once, by a fence object reaching slot 16 or 17 (the older +// layout's frequency and calibration getters take no object argument) or by a fence reaching SignalX slot 25 — +// a title that signals only through SignalX would otherwise stay undetected and lose every signal. +// +// Every other console-only queue method answers S_OK (sibling layer: title frame pacing flows through them, and a +// refusal wedges the present loop), still recorded by note_child_slot. Slot 148's AllocateUploadMemory is a list +// method, not a queue method, so it is not part of this table. + +#ifdef LEONIDA_VULKAN_DEVICE + +struct PresentState { + ~PresentState() { + if (window) DestroyWindow(window); // the presentation and its window die with the device proxy + } + HWND window = nullptr; + std::unique_ptr xbox; + bool tried = false; // creation is attempted once; a null xbox means this device cannot present +}; + +void destroy_present_state(void* present_state) { + delete static_cast(present_state); +} + +LRESULT CALLBACK present_window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { + return DefWindowProcW(window, message, wparam, lparam); +} + +// Lazily builds the window, presenter and XboxPresentation a console PresentX needs, once per device. Returns the +// state even when `xbox` stays null (no presentation support): the failure is logged once, not retried. +PresentState* present_state_for(DeviceProxy* device) { + if (auto* state = static_cast(device->present_state)) return state; + auto* state = new (std::nothrow) PresentState; + if (!state) return nullptr; + device->present_state = state; + state->tried = true; + WNDCLASSW window_class{}; + window_class.lpfnWndProc = present_window_proc; + window_class.hInstance = GetModuleHandleW(nullptr); + window_class.lpszClassName = L"LeonidaPresentX"; + if (!RegisterClassW(&window_class) && GetLastError() != ERROR_CLASS_ALREADY_EXISTS) { + std::fprintf(stderr, "[rt] d3d12_xs: PresentX window class failed (error %lu)\n", GetLastError()); + return state; + } + state->window = CreateWindowExW(0, window_class.lpszClassName, L"Leonida", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, + CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, nullptr, nullptr, + window_class.hInstance, nullptr); + if (!state->window) { + std::fprintf(stderr, "[rt] d3d12_xs: PresentX window failed (error %lu)\n", GetLastError()); + return state; + } + // LOCAL (wiring of #8591): present into the title's own window when it has one; else show the fallback window. + HWND target = rt::d3d12::find_title_window(GetCurrentProcessId(), state->window); + if (target) { + std::fprintf(stderr, "[rt] d3d12_xs: PresentX uses the title's own window %p\n", static_cast(target)); + // LOCAL: LEONIDA_WINDOW=WxH resizes the title's window without waiting on its thread (SWP_ASYNCWINDOWPOS). + if (const char* size = std::getenv("LEONIDA_WINDOW")) { + int w = 0, h = 0; + if (std::sscanf(size, "%dx%d", &w, &h) == 2 && w > 0 && h > 0) + SetWindowPos(target, nullptr, 0, 0, w, h, + SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOMOVE | SWP_ASYNCWINDOWPOS); + } + } else { + target = state->window; + ShowWindow(target, SW_SHOWNOACTIVATE); + } + auto presenter = rt::d3d12::create_window_presenter(device->real, target); + if (!presenter) { + std::fprintf(stderr, "[rt] d3d12_xs: no window presenter on this device; PresentX is a no-op\n"); + return state; + } + // The device's token source: the title takes its frame tokens from device slot 80 (#7685). + state->xbox = std::make_unique(std::move(presenter), nullptr, device->frame_tokens); + std::fprintf(stderr, "[rt] d3d12_xs: PresentX ready (window %p)\n", static_cast(state->window)); + return state; +} + +std::uint64_t queue_present_x(ChildProxy* self, std::uint64_t plane_count, std::uint64_t planes, + std::uint64_t params) { + PresentState* state = self->device ? present_state_for(self->device) : nullptr; + if (!state || !state->xbox) return hr_to_u64(S_OK); // a title still runs with nothing presented + return hr_to_u64(state->xbox->PresentX( + static_cast(plane_count), + reinterpret_cast(planes), + reinterpret_cast(params))); +} + +#else // !LEONIDA_VULKAN_DEVICE: this translation unit stands alone (mock and COM tests) + +void destroy_present_state(void*) {} + +std::uint64_t queue_present_x(ChildProxy*, std::uint64_t, std::uint64_t, std::uint64_t) { + return hr_to_u64(S_OK); +} + +#endif + +// LOCAL (merge of #7286 + list-array unwrap): console ExecuteCommandLists(count, lists) at queue slot 35. Each list +// proxy in the array is replaced by its real list before the PC call. +std::uint64_t queue_execute_command_lists(ChildProxy* self, std::uint64_t count_word, std::uint64_t lists_word) { + const UINT count = static_cast(count_word); + auto* const lists = reinterpret_cast(lists_word); + std::vector real(count); + for (UINT i = 0; lists && i < count; ++i) { + IUnknown* r = proxy_real_object(lists[i]); + real[i] = r ? static_cast(r) : lists[i]; + } + using ExecuteFn = void(WINAPI*)(void*, std::uint64_t, ID3D12CommandList* const*); + reinterpret_cast(self->real_vtable[kQueueExecuteCommandLists])( + self->real, static_cast(count), lists ? real.data() : lists); + return 0; +} + +template +std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, + std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, + std::uint64_t a8, std::uint64_t a9, std::uint64_t a10, std::uint64_t a11, + std::uint64_t a12, std::uint64_t a13, std::uint64_t a14) { + if constexpr (Slot == 0) { + d3d12_trace::record(child_trace_name(Slot)); + return hr_to_u64(child_query_interface(self, reinterpret_cast(a1), + reinterpret_cast(a2))); + } else if constexpr (Slot == 1) { return child_add_ref(self); } else if constexpr (Slot == 2) { return child_release(self); @@ -1207,8 +1506,134 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ d3d12_trace::record(child_trace_name(Slot)); return hr_to_u64(child_get_device(self, reinterpret_cast(a1), reinterpret_cast(a2))); + } else if constexpr (K == ChildKind::fence && Slot == kFenceCompletedValueSlot) { + // Past ID3D12Fence1, so whether the real fence has Fence1 does not matter here. + note_child_slot(Slot); + d3d12_trace::record(child_trace_name(Slot)); + return fence_completed_value_address(self, a1, a2, a3); } else { note_child_slot(Slot); + if constexpr (K == ChildKind::queue && Slot == kQueueExecuteCommandListsX) { + d3d12_trace::record(child_trace_name(Slot)); + return queue_execute_command_lists(self, a1, a2); + } + if constexpr (K == ChildKind::queue) { + // Layout detection (the comment at the PresentX section): a fence reaching slot 16 or 17 is the newer + // layout's Signal/Wait; anything else there is the older layout's frequency/calibration getter. A + // fence at slot 14 or 15 is the older Signal/Wait; a non-fence argument there is one of the newer + // layout's two inserted console methods. + // A queue made after another one detected the layout inherits it from the device; undetected queues + // assume the older layout, whose unshifted slots are also the PC chain. A fence reaching SignalX + // slot 25 while the layout is still unknown is itself the newer-layout evidence: a title that + // signals only through SignalX never reaches Signal/Wait at 16/17, and an unanswered SignalX + // returns S_OK having signalled nothing, leaving a waiter on that fence value hanging. + const bool newer = [&] { + const unsigned char own = self->queue_layout.load(std::memory_order_relaxed); + if (own == ChildProxy::kQueueLayoutNewer) return true; + const unsigned char shared = + self->device->console_layout.load(std::memory_order_relaxed); + return own == ChildProxy::kQueueLayoutUnknown && shared == ChildProxy::kQueueLayoutNewer; + }(); + if (Slot == 16 || Slot == 17) { + if (IUnknown* fence = proxy_real_object(reinterpret_cast(a1))) { + self->queue_layout.store(ChildProxy::kQueueLayoutNewer, std::memory_order_relaxed); + self->device->console_layout.store(ChildProxy::kQueueLayoutNewer, + std::memory_order_relaxed); + using Fn = HRESULT(WINAPI*)(IUnknown*, IUnknown*, UINT64); + return hr_to_u64(reinterpret_cast(self->real_vtable[kQueueSignal + (Slot - 16)])( + self->real, fence, a2)); + } + if (newer) return hr_to_u64(S_OK); // proven newer: a non-fence Signal/Wait arg is malformed, + // not evidence of the older layout — do not downgrade the shared detection on it + if (self->queue_layout.load(std::memory_order_relaxed) == + ChildProxy::kQueueLayoutUnknown) { + self->queue_layout.store(ChildProxy::kQueueLayoutOlder, std::memory_order_relaxed); + self->device->console_layout.store(ChildProxy::kQueueLayoutOlder, + std::memory_order_relaxed); + } + } else if ((Slot == 14 || Slot == 15) && !proxy_real_object(reinterpret_cast(a1)) && + newer) { + return hr_to_u64(S_OK); // the newer layout's two inserted console methods, unmeasured + } + if (newer && Slot >= 18 && Slot <= 20) { + // Newer layout: frequency 18, calibration 19, GetDesc 20 are the PC slots 16-18 shifted. + d3d12_trace::record(child_trace_name(Slot)); + using ForwardFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t); + auto fn = reinterpret_cast(self->real_vtable[Slot - 2]); + return fn(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); + } + // Slot 18 while the layout is still unknown is ambiguous: the older GetDesc (a struct-return + // write of a whole desc) or the newer frequency getter (an 8-byte out). Answering it as GetDesc + // writes far past the 8 bytes a frequency caller passes, so the call goes to the frequency + // getter — the only interpretation that cannot overrun its argument, and a title often queries + // the frequency before its first fence call. A proven-older queue keeps the generic GetDesc + // path below; slots 19 and 20 stay no-ops, since their newer interpretations write through + // caller pointers an unmodelled older method might not supply. + if (Slot == 18 && !newer && self->queue_layout == ChildProxy::kQueueLayoutUnknown && + self->device->console_layout.load(std::memory_order_relaxed) != + ChildProxy::kQueueLayoutOlder) { + d3d12_trace::record(child_trace_name(Slot)); + using Fn = HRESULT(WINAPI*)(IUnknown*, UINT64*); + return hr_to_u64(reinterpret_cast(self->real_vtable[16])( + self->real, reinterpret_cast(a1))); + } + if (Slot == (newer ? 25u : 23u) || + (Slot == 25u && self->queue_layout.load(std::memory_order_relaxed) == + ChildProxy::kQueueLayoutUnknown && + self->device->console_layout.load(std::memory_order_relaxed) == + ChildProxy::kQueueLayoutUnknown)) { + // SignalX: console Signal (older 23, newer 25); the extra X word is dropped. The slot-25 + // alternative is the fence itself carrying the layout evidence, per the comment above; a + // proven-older queue still leaves slot 25 to the console-only no-op, since its fence-taking + // methods sit at 14/15/23 there. + if (IUnknown* fence = proxy_real_object(reinterpret_cast(a1))) { + if (Slot == 25u && !newer) { + self->queue_layout.store(ChildProxy::kQueueLayoutNewer, + std::memory_order_relaxed); + self->device->console_layout.store(ChildProxy::kQueueLayoutNewer, + std::memory_order_relaxed); + } + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12_xs: SignalX (queue slot %u) forwarded as Signal\n", Slot); + using Fn = HRESULT(WINAPI*)(IUnknown*, IUnknown*, UINT64); + return hr_to_u64(reinterpret_cast(self->real_vtable[kQueueSignal])(self->real, fence, a2)); + } + return hr_to_u64(S_OK); + } + if (Slot == (newer ? 32u : 30u)) { // PresentX + const std::uint64_t hr = queue_present_x(self, a1, a2, a3); + // LOCAL: one trace line per present, so a run's presents can be counted. + d3d12_trace::record("XboxID3D12CommandQueue::PresentX", static_cast(hr) < 0 ? "failed" : "ok"); + return hr; + } + if (Slot >= self->slot_count || (newer && (Slot == 14 || Slot == 15))) { + d3d12_trace::record(child_trace_name(Slot), "console-only"); + return hr_to_u64(S_OK); // unmodelled console queue methods: frame pacing flows through them + } + } + if constexpr (K == ChildKind::allocator && Slot == 9) { + // Console-only ID3D12CommandAllocator::SetAllocatorCallbackX(callback, context, ...), observed past the + // 9-slot PC chain on the retail executable (call shape: function pointer, context, plus trailing words). + // The PC/Vulkan layer manages command-buffer backing directly without invoking a title allocator callback, + // so record the callback and context on the proxy and return S_OK while leaving slots 10+ refused. + self->allocator_callback.store(static_cast(a1), std::memory_order_relaxed); + self->allocator_callback_context.store(static_cast(a2), std::memory_order_relaxed); + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) { + std::fprintf(stderr, + "[rt] d3d12_xs: allocator slot 9 (SetAllocatorCallbackX) recorded " + "(callback=0x%llx context=0x%llx a3=0x%llx a4=0x%llx)\n", + static_cast(a1), static_cast(a2), + static_cast(a3), static_cast(a4)); + } + d3d12_trace::record(child_trace_name(Slot)); + return hr_to_u64(S_OK); + } if (Slot >= self->slot_count) { bool expected = false; if (ChildStats::beyond_warned[Slot].compare_exchange_strong(expected, true, @@ -1224,11 +1649,17 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ return hr_to_u64(E_NOTIMPL); } d3d12_trace::record(child_trace_name(Slot)); // "called": the real object's result is not inspected + if constexpr (K == ChildKind::queue && Slot == kQueueExecuteCommandLists) { + return queue_execute_command_lists(self, a1, a2); + } if constexpr (K == ChildKind::queue && (Slot == kQueueSignal || Slot == kQueueWait)) a1 = unwrap_object(a1); - UnwrappedArray unwrapped_lists; + + // Queue slot 10: ExecuteCommandLists(count, lists). The array is copied with each list proxy replaced by + // its real list; a bundle on the list side unwraps the same way at the console's ExecuteBundle. + UnwrappedArray unwrapped; if constexpr (K == ChildKind::queue && Slot == 10) { - if (!unwrapped_lists.fill(a2, a1)) return hr_to_u64(E_OUTOFMEMORY); - if (unwrapped_lists.data()) a2 = unwrapped_lists.data(); + if (!unwrapped.fill(a2, a1)) return hr_to_u64(E_OUTOFMEMORY); + if (unwrapped.data()) a2 = unwrapped.data(); } // The PC vtable entry with the real object as `this`; integer/pointer arguments, the hidden struct-return @@ -1238,6 +1669,11 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t); auto fn = reinterpret_cast(self->real_vtable[Slot]); + if constexpr (K == ChildKind::fence && Slot == kFenceSignal) { + const std::uint64_t result = fn(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); + if (FenceMirror* m = self->mirror.load(std::memory_order_acquire)) refresh_mirror(m); + return result; + } return fn(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); } } @@ -1315,23 +1751,606 @@ HRESULT wrap_child(IUnknown* created, DeviceProxy* device, const IID* riid, void proxy->slot_count = kAllocatorPublicSlots; } proxy->refs.store(1, std::memory_order_relaxed); - proxy_add_ref(device); // the object keeps its Xbox-ABI device alive for GetDevice + proxy_add_ref(device); // the object keeps its Xbox-ABI device alive for GetDevice + + const HRESULT hr = child_query_interface(proxy, riid, out); + if (FAILED(hr)) { + destroy_child(proxy); // no reference escaped + return hr; + } + // Titles create fences at run time: the first proxy of each kind is logged, every one only with XS_TRACE. + static std::atomic logged{false}; + if (!d3d12_trace::enabled() && (!logged.exchange(true, std::memory_order_relaxed) || trace_enabled())) + std::fprintf(stderr, "[rt] d3d12_xs: %s proxy %p wraps %p (device proxy %p, %u public slots)\n", + child_kind_name(), static_cast(proxy), static_cast(created), + static_cast(device), proxy->slot_count); + proxy->refs.fetch_sub(1, std::memory_order_relaxed); // drop the creation reference; `out` holds the caller's + return S_OK; +} + +// ---- Command list proxy --------------------------------------------------------------------------------- +// +// Device slot 12 (CreateCommandList) hands the title a console-shaped command list: the console vtable order, a +// 160-slot table, and the object fields the console SDK's inline writers touch (docs/d3d12_xs_console_abi.md +// §5). The write cursor (+0x18) is pinned at both limits (+0x28, +0x30), so a title always finds the record +// buffer full and takes the vtable path for every command — the proxy never has to interpret inline records. +// The flag bytes (+0x140..+0x143), the root-parameter header table (+0x344) and the pipeline record (+0x544) +// stay zeroed: they are only read while writing a record, which never happens at the limit. +// +// The console slot order keeps the PC order through slot 26 (measured: 9, 10, 12-17, 19, 20, 25, 26), places +// four console-only methods at 27-30, then the PC chain resumes shifted +4 — confirmed at console 32->PC 28 +// (SetDescriptorHeaps), 33->29, 41->37, 43->39, 45->41, 48->44, 51->47 and 53->49, and the same shift fills the +// block through console 59 -> PC 55. The console has no PIX markers: console 60 is EndEvent (PC 58) and 61 is +// ExecuteIndirect (PC 59, package-measured). Console 146 is the enhanced Barrier taking one D3D12_BARRIER_GROUP +// (package-confirmed; PC equivalent is GCL7 slot 80). Console-only slots — the 27-30 extras, AllocateUploadMemory +// (148), the disputed tail past 61 and the newer-layout +2 tail — are recorded with their first argument words +// and return 0 without a PC call: a wrong forward is worse than a clean refusal. + +constexpr unsigned kListSlots = 160; +// ---- Upload memory (console list slot 148, AllocateUploadMemory) ---- +// +// On the console the CPU and GPU share one address space: the pointer AllocateUploadMemory(size, alignment) +// returns is written by the CPU and handed to the GPU unchanged — the package measures it going straight into a +// root SRV (docs/d3d12_xs_console_abi.md §5.3, d3d12_command_objects.md §3.3a). A PC has two address spaces, so +// each arena chunk is a persistently-mapped UPLOAD-heap buffer: the title gets the CPU pointer and writes the +// very memory the GPU samples, and the root-descriptor setters translate a chunk address to the buffer's device +// address (the same backing memory) before forwarding. Translation covers the six root VA setters (console +// 41-46); VAs inside view structs (IASetVertexBuffers/IASetIndexBuffer) and ExecuteIndirect arguments are not +// rewritten yet and stay title addresses. + +struct UploadChunk { + UploadChunk* next; + ID3D12Resource* resource; // the mapped buffer; released with the chunk + std::uint8_t* cpu_base; + D3D12_GPU_VIRTUAL_ADDRESS gpu_base; + std::size_t size; + std::size_t used; +}; + +struct UploadArena { + UploadChunk* chunks = nullptr; + std::mutex lock; +}; + +constexpr std::size_t kUploadChunkMin = 8 << 20; // one chunk serves a title's whole frame of uploads + +UploadChunk* upload_chunk_new(DeviceProxy* device, std::size_t size) { + auto* chunk = new (std::nothrow) UploadChunk{}; + if (!chunk) return nullptr; + chunk->size = size; + + D3D12_HEAP_PROPERTIES heap = {}; + heap.Type = D3D12_HEAP_TYPE_UPLOAD; + D3D12_RESOURCE_DESC desc = {}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = size; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + ID3D12Resource* resource = nullptr; + const HRESULT hr = device->real->CreateCommittedResource( + &heap, D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + __uuidof(ID3D12Resource), reinterpret_cast(&resource)); + void* cpu = nullptr; + if (SUCCEEDED(hr) && resource && SUCCEEDED(resource->Map(0, nullptr, &cpu)) && cpu && + resource->GetGPUVirtualAddress() != 0) { + chunk->resource = resource; + chunk->cpu_base = static_cast(cpu); + chunk->gpu_base = resource->GetGPUVirtualAddress(); + return chunk; + } + if (resource) resource->Release(); + // A device that cannot hand out a mapped buffer (a mock, or an older layer without buffer device + // addresses) still gets memory to write; upload_translate leaves its addresses alone. + auto* cpu_fallback = static_cast( + VirtualAlloc(nullptr, size, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!cpu_fallback) { + delete chunk; + return nullptr; + } + chunk->cpu_base = cpu_fallback; + chunk->gpu_base = reinterpret_cast(cpu_fallback); + return chunk; +} + +std::uint64_t upload_alloc(DeviceProxy* device, std::uint64_t size, std::uint64_t alignment) { + if (!device || !size) return 0; + alignment = alignment < 16 ? 16 : alignment; // every measured call asked for 16 + // Refuse what cannot be served before any arithmetic runs: only power-of-two alignments are measured, + // chunks map at 64K granularity at best, and a size too big to add the alignment to would wrap the + // checks below — one such call returned a pointer and left the cursor so the next request re-handed + // the same range (daemosofchaos's report on #2490). + if ((alignment & (alignment - 1)) != 0 || alignment > (64 << 10) || + size > ~static_cast(0) - alignment) { + std::fprintf(stderr, "[rt] d3d12_xs: AllocateUploadMemory(%llu, %llu) refused\n", + static_cast(size), static_cast(alignment)); + return 0; + } + auto* arena = static_cast(device->upload_state.load(std::memory_order_acquire)); + if (!arena) { + auto* fresh = new (std::nothrow) UploadArena; + if (!fresh) return 0; + void* expected = nullptr; // a concurrent first call loses its arena but keeps the winner's chunks + if (device->upload_state.compare_exchange_strong(expected, fresh, std::memory_order_acq_rel)) + arena = fresh; + else { + delete fresh; + arena = static_cast(expected); + } + } + std::lock_guard lock(arena->lock); + const std::size_t need = static_cast(size); + for (UploadChunk* chunk = arena->chunks; chunk; chunk = chunk->next) { + const std::size_t aligned = (chunk->used + (alignment - 1)) & ~(static_cast(alignment) - 1); + if (aligned >= chunk->used && aligned <= chunk->size && need <= chunk->size - aligned) { + chunk->used = aligned + need; + return reinterpret_cast(chunk->cpu_base + aligned); + } + } + const std::size_t chunk_size = need + alignment > kUploadChunkMin ? need + alignment : kUploadChunkMin; + UploadChunk* chunk = upload_chunk_new(device, chunk_size); + if (!chunk) { + std::fprintf(stderr, "[rt] d3d12_xs: AllocateUploadMemory(%llu, %llu) failed\n", + static_cast(size), static_cast(alignment)); + return 0; + } + chunk->next = arena->chunks; + arena->chunks = chunk; + const std::size_t aligned = (alignment - 1) & ~(static_cast(alignment) - 1); // 0-based + chunk->used = aligned + need; + return reinterpret_cast(chunk->cpu_base + aligned); +} + +// An address inside an upload chunk becomes the chunk's device address plus the offset; anything else — a +// real resource VA the title already holds — passes through. +std::uint64_t upload_translate(DeviceProxy* device, std::uint64_t va) { + auto* arena = static_cast( + device ? device->upload_state.load(std::memory_order_acquire) : nullptr); + if (!arena) return va; + std::lock_guard lock(arena->lock); + for (UploadChunk* chunk = arena->chunks; chunk; chunk = chunk->next) { + const std::uint64_t base = reinterpret_cast(chunk->cpu_base); + if (va >= base && va < base + chunk->size) return chunk->gpu_base + (va - base); + } + return va; +} + +void destroy_upload_state(void* upload_state) { + auto* arena = static_cast(upload_state); + if (!arena) return; + for (UploadChunk* chunk = arena->chunks; chunk;) { + UploadChunk* next = chunk->next; + if (chunk->resource) { + chunk->resource->Unmap(0, nullptr); + chunk->resource->Release(); + } else { + VirtualFree(chunk->cpu_base, 0, MEM_RELEASE); + } + delete chunk; + chunk = next; + } + delete arena; +} + +constexpr unsigned kListNotForwarded = ~0u; +constexpr unsigned kConsoleSetDescriptorHeaps = 32; +constexpr unsigned kConsoleExecuteBundle = 31; +constexpr unsigned kConsoleOMSetRenderTargets = 50; +constexpr unsigned kConsoleClearDepthStencilView = 51; +constexpr unsigned kConsoleClearRenderTargetView = 52; +constexpr unsigned kConsoleClearUavUint = 53; +constexpr unsigned kConsoleClearUavFloat = 54; +constexpr unsigned kConsoleReset = 139; +constexpr unsigned kConsoleBarrier = 146; +constexpr unsigned kConsoleAllocateUpload = 148; + +constexpr unsigned console_to_pc_list_slot(unsigned slot) { + if (slot <= 26) return slot; // PC order, measured + if (slot <= 30) return kListNotForwarded; // console-only extras + if (slot <= 59) return slot - 4; // PC chain, shifted +4 + if (slot == 60) return 58; // EndEvent (no console SetMarker/BeginEvent) + if (slot == 61) return 59; // ExecuteIndirect (Package) + if (slot == kConsoleBarrier) return 80; // D3D12_BARRIER_GROUP (Package; PC GCL7) + if (slot == kConsoleReset) return 10; // Reset(allocator, pso): measured on the retail title (Pipodi) + return kListNotForwarded; +} + +struct ListProxy { + void** vtable; // +0x00 + ID3D12GraphicsCommandList* real; // +0x08 + DeviceProxy* device; // +0x10: keeps the Xbox-ABI device alive; GetDevice returns it + // +0x18..: the console object body a title's inline writers read. +0x18 holds the write cursor, +0x28 and + // +0x30 the record limits; the rest is room for the measured flags, header table and pipeline record. + alignas(8) std::uint8_t console_fields[0x600]; + std::atomic refs; // past the console body + unsigned pc_slot_count; // slots the real list implements; mapped slots past it are refused + std::vector vb_scratch; // slot-48 views with their VAs translated + std::vector so_scratch; // slot-49 views, same treatment + + void pin_cursor_at_limit() { + const std::uint64_t at_limit = static_cast( + reinterpret_cast(this) + 0x18 + 0x500); + for (const size_t offset : {0x18, 0x28, 0x30}) + std::memcpy(reinterpret_cast(this) + offset, &at_limit, sizeof(at_limit)); + } +}; +static_assert(offsetof(ListProxy, console_fields) == 0x18, "the console fields start at +0x18"); + +struct ListStats { + static inline std::atomic hits[kListSlots]; + static inline std::atomic first[kListSlots]; +}; + +// The list tail (D3D-445). From CopyTextureRegionX on, the newer console layout sits two slots later than the older +// one (docs/d3d12_xs_console_abi.md 5.3). The table is keyed by the older-layout slot. Only CopyTextureRegionX has a +// measured name; the other measured pairs are named by their older slot, so that both layouts print the same text +// for the same method. +struct ListTailName { + unsigned older_slot; + const char* name; +}; +constexpr ListTailName kListTailNames[] = { + {83, "CopyTextureRegionX"}, {84, "tail method, older slot 84"}, {85, "tail method, older slot 85"}, + {88, "tail method, older slot 88"}, {89, "tail method, older slot 89"}, {90, "tail method, older slot 90"}, + {93, "tail method, older slot 93"}, {94, "tail method, older slot 94"}, +}; +constexpr unsigned kListTailShift = 2; +static_assert(kConsoleLayoutOlder == ChildProxy::kQueueLayoutOlder && + kConsoleLayoutNewer == ChildProxy::kQueueLayoutNewer, + "the list tail names use the queue proxy's layout values"); + +// Null while the layout is unknown, and for a slot that is not a measured tail slot of that layout: a slot number +// never gets the other layout's name. +const char* list_tail_name(unsigned slot, unsigned char console_layout) { + if (console_layout != kConsoleLayoutOlder && console_layout != kConsoleLayoutNewer) return nullptr; + const unsigned shift = console_layout == kConsoleLayoutNewer ? kListTailShift : 0; + if (slot < shift) return nullptr; + for (const ListTailName& entry : kListTailNames) + if (entry.older_slot == slot - shift) return entry.name; + return nullptr; +} + +void note_list_slot(unsigned slot, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, std::uint64_t a4, + unsigned char console_layout = 0) { + if (slot >= kListSlots) return; + ListStats::hits[slot].fetch_add(1, std::memory_order_relaxed); + bool expected = false; + if (ListStats::first[slot].compare_exchange_strong(expected, true, std::memory_order_relaxed)) { + const char* name = list_tail_name(slot, console_layout); + std::fprintf(stderr, "[rt] d3d12_xs: list slot %u%s%s%s first call (args 0x%llx 0x%llx 0x%llx 0x%llx)\n", slot, + name ? " (" : "", name ? name : "", name ? ")" : "", static_cast(a1), + static_cast(a2), static_cast(a3), + static_cast(a4)); + } +} + +// The interfaces the console list answers: the base chain, ID3D12CommandList and every graphics-command-list +// interface the real list implements — on the console the list is a single object, so any of them returns the +// proxy. +bool is_list_iid(const IID& iid) { + return IsEqualIID(iid, __uuidof(IUnknown)) || IsEqualIID(iid, __uuidof(ID3D12Object)) || + IsEqualIID(iid, __uuidof(ID3D12DeviceChild)) || IsEqualIID(iid, __uuidof(ID3D12CommandList)) || + IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList)) || + IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList1)) || + IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList2)) || + IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList3)) || + IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList4)) || + IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList5)) || + IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList6)) || + IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList7)) || + IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList8)); +} + +unsigned long list_add_ref(ListProxy* self) { return self->refs.fetch_add(1, std::memory_order_relaxed) + 1; } + +void destroy_list(ListProxy* self) { + IUnknown* real = self->real; + DeviceProxy* device = self->device; + delete self; + if (real) real->Release(); + if (device) proxy_release(device); +} + +unsigned long list_release(ListProxy* self) { + const unsigned long refs = self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; + if (refs == 0) destroy_list(self); + return refs; +} + +HRESULT list_query_interface(ListProxy* self, const IID* riid, void** out) { + note_list_slot(0, reinterpret_cast(riid), reinterpret_cast(out), 0, 0); + if (!out) return E_POINTER; + *out = nullptr; + if (!riid) return E_POINTER; + // A console title asks for the console command-list IID (device slot 73 forwards it): it maps to a PC IID the + // real list answers, and the caller gets this console-shaped object back. + const IID& pc_iid = command_list_iid_for_pc(*riid); + if (!is_list_iid(pc_iid)) { + if (supports_iid(self->real, pc_iid)) log_refused_iid("list", *riid); + return E_NOINTERFACE; + } + if (!supports_iid(self->real, pc_iid)) return E_NOINTERFACE; + *out = self; + list_add_ref(self); + return S_OK; +} + +// Highest list interface the real object implements; its cumulative slot count bounds mapped forwards +// (ID3D12GraphicsCommandList8 ends at slot 81, OMSetFrontAndBackStencilRef). +unsigned detect_list_slot_count(IUnknown* real) { + if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList8))) return 82; + if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList7))) return 81; + if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList6))) return 78; + if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList5))) return 75; + if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList4))) return 69; + if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList3))) return 67; + if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList2))) return 66; + if (supports_iid(real, __uuidof(ID3D12GraphicsCommandList1))) return 65; + return 60; +} + +template +std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, + std::uint64_t a4, std::uint64_t a5, std::uint64_t a6, std::uint64_t a7, + std::uint64_t a8, std::uint64_t a9, std::uint64_t a10, std::uint64_t a11, + std::uint64_t a12, std::uint64_t a13, std::uint64_t a14) { + if constexpr (Slot == 0) { + return hr_to_u64(list_query_interface(self, reinterpret_cast(a1), + reinterpret_cast(a2))); + } else if constexpr (Slot == 1) { + return list_add_ref(self); + } else if constexpr (Slot == 2) { + return list_release(self); + } else if constexpr (Slot == 7) { // GetDevice: the Xbox-ABI device, as on the other proxies + note_list_slot(7, a1, a2, 0, 0); + if (a2) *reinterpret_cast(a2) = nullptr; + if (!a1) return hr_to_u64(E_POINTER); + if (!a2) { // no output: the real object's own answer + using Fn = HRESULT(WINAPI*)(IUnknown*, const IID*, void**); + return hr_to_u64(reinterpret_cast((*reinterpret_cast(self->real))[7])( + self->real, reinterpret_cast(a1), nullptr)); + } + return hr_to_u64(proxy_query_interface(self->device, reinterpret_cast(a1), + reinterpret_cast(a2))); + } else { + note_list_slot(Slot, a1, a2, a3, a4, self->device->console_layout.load(std::memory_order_relaxed)); + constexpr unsigned pc = console_to_pc_list_slot(Slot); + if constexpr (pc == kListNotForwarded) { + if constexpr (Slot == kConsoleAllocateUpload) { + return upload_alloc(self->device, a1, a2); // (size, alignment); the comment at UploadChunk + } + return 0; // unmodelled console slot: recorded above, never a PC call + } else { + if (pc >= self->pc_slot_count) { + static std::atomic beyond_warned[kListSlots]; + bool expected = false; + if (beyond_warned[Slot].compare_exchange_strong(expected, true, std::memory_order_relaxed)) + std::fprintf(stderr, + "[rt] d3d12_xs: list slot %u maps to PC slot %u, beyond the real list's %u " + "slots; returning E_NOTIMPL\n", + Slot, pc, self->pc_slot_count); + return hr_to_u64(E_NOTIMPL); + } + using ForwardFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t, std::uint64_t, + std::uint64_t, std::uint64_t); + auto** const real_vtable = *reinterpret_cast(self->real); + // LOCAL: console SetComputeRootDescriptorTable (35) and SetGraphicsRootDescriptorTable (36) + if constexpr (Slot == 35 || Slot == 36) local_mirror_table(self->device, a2); + if constexpr (pc == 10) { + // Reset(allocator, pso) — console 10, and 139 as the retail title calls it: the title hands its + // allocator proxy; the real list takes the real one (and a wrapped pipeline state, if that ever + // exists, the same way). + a1 = unwrap_object(a1); + a2 = unwrap_object(a2); + } else if constexpr (Slot == kConsoleExecuteBundle) { + a1 = unwrap_object(a1); // the bundle is a list proxy too + } else if constexpr (Slot >= 41 && Slot <= 46) { + // The six root descriptor setters (index, GPU VA): an upload-arena CPU pointer becomes the + // chunk's device address (d3d12_xs_console_abi.md §5.3 measures slots 41/43/45 for the compute + // side; the graphics setters interleave on even slots). + a2 = upload_translate(self->device, a2); + } else if constexpr (Slot == 47) { + // IASetIndexBuffer(pView): the view's BufferLocation is a GPU VA; translate in a copy so the + // title's struct is not written. + if (a1) { + auto view = *reinterpret_cast(a1); + view.BufferLocation = upload_translate(self->device, view.BufferLocation); + return reinterpret_cast(real_vtable[pc])( + self->real, reinterpret_cast(&view), a2, a3, a4, a5, a6, a7, a8, a9, + a10, a11, a12, a13, a14); + } + } else if constexpr (Slot == 48) { + // IASetVertexBuffers(start, count, views): each view's BufferLocation is a GPU VA. The views are + // translated in the proxy's scratch array for the same reason as the index view. + if (a3 && a2) { + const auto* in = reinterpret_cast(a3); + self->vb_scratch.assign(in, in + a2); + for (auto& view : self->vb_scratch) + view.BufferLocation = upload_translate(self->device, view.BufferLocation); + return reinterpret_cast(real_vtable[pc])( + self->real, a1, a2, reinterpret_cast(self->vb_scratch.data()), a4, a5, + a6, a7, a8, a9, a10, a11, a12, a13, a14); + } + } else if constexpr (Slot == 49) { + // SOSetTargets(start, count, views): BufferLocation and BufferFilledSizeLocation are both VAs. + if (a3 && a2) { + const auto* in = reinterpret_cast(a3); + self->so_scratch.assign(in, in + a2); + for (auto& view : self->so_scratch) { + view.BufferLocation = upload_translate(self->device, view.BufferLocation); + view.BufferFilledSizeLocation = + upload_translate(self->device, view.BufferFilledSizeLocation); + } + return reinterpret_cast(real_vtable[pc])( + self->real, a1, a2, reinterpret_cast(self->so_scratch.data()), a4, a5, + a6, a7, a8, a9, a10, a11, a12, a13, a14); + } + } else if constexpr (Slot == kConsoleSetDescriptorHeaps) { + UnwrappedArray heaps; + if (!heaps.fill(a2, a1)) return 0; // void on the PC side; the call simply does not happen + const std::uint64_t real_heaps = heaps.data() ? heaps.data() : a2; + return reinterpret_cast(real_vtable[pc])(self->real, a1, real_heaps, a3, a4, a5, a6, + a7, a8, a9, a10, a11, a12, a13, a14); + } else if constexpr (Slot == kConsoleOMSetRenderTargets) { + // OMSetRenderTargets(NumRenderTargetDescriptors, pRenderTargetDescriptors, + // RTsSingleHandleToDescriptorRange, pDepthStencilDescriptor): + // translate title-owned CPU descriptor handles into local copies without mutating caller buffers. + const UINT count = static_cast(a1); + const auto* in_rtvs = reinterpret_cast(a2); + const BOOL single_range = static_cast(a3); + const auto* in_dsv = reinterpret_cast(a4); + D3D12_CPU_DESCRIPTOR_HANDLE rtvs[D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT]{}; + const D3D12_CPU_DESCRIPTOR_HANDLE* out_rtvs = in_rtvs; + if (in_rtvs && count > 0) { + if (single_range) { + rtvs[0] = translate_cpu_handle(self->device, in_rtvs[0]); + out_rtvs = rtvs; + } else if (count <= D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT) { + for (UINT i = 0; i < count; ++i) rtvs[i] = translate_cpu_handle(self->device, in_rtvs[i]); + out_rtvs = rtvs; + } + } + D3D12_CPU_DESCRIPTOR_HANDLE dsv{}; + const D3D12_CPU_DESCRIPTOR_HANDLE* out_dsv = in_dsv; + if (in_dsv) { + dsv = translate_cpu_handle(self->device, *in_dsv); + out_dsv = &dsv; + } + return reinterpret_cast(real_vtable[pc])( + self->real, a1, reinterpret_cast(out_rtvs), a3, + reinterpret_cast(out_dsv), a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); + } else if constexpr (Slot == kConsoleClearRenderTargetView) { + // ClearRenderTargetView(RenderTargetView, ColorRGBA, NumRects, pRects): translate the RTV handle. + a1 = static_cast( + translate_cpu_handle(self->device, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(a1)}).ptr); + } else if constexpr (Slot == kConsoleClearUavUint || Slot == kConsoleClearUavFloat) { + // ClearUnorderedAccessViewUint/Float(ViewGPUHandle, ViewCPUHandle, pResource, Values, NumRects, + // pRects): keep GPU handle, translate CPU handle. + a2 = static_cast( + translate_cpu_handle(self->device, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(a2)}).ptr); + } + return reinterpret_cast(real_vtable[pc])(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, + a10, a11, a12, a13, a14); + } + } +} + +// ClearDepthStencilView (console slot 51 -> PC slot 47) takes FLOAT Depth as its fourth argument (XMM3 on Windows +// x64 ABI). The all-uint64_t list_slot thunk would read R9 instead of XMM3 and clobber Depth, so this slot gets a +// typed thunk that preserves Depth and translates the title-owned CPU descriptor handle. +void WINAPI list_clear_depth_stencil_view(ListProxy* self, D3D12_CPU_DESCRIPTOR_HANDLE dsv, + D3D12_CLEAR_FLAGS flags, FLOAT depth, UINT8 stencil, UINT num_rects, + const D3D12_RECT* rects) { + std::uint32_t depth_bits = 0; + std::memcpy(&depth_bits, &depth, sizeof(depth_bits)); + note_list_slot(kConsoleClearDepthStencilView, static_cast(dsv.ptr), + static_cast(flags), depth_bits, stencil, + self->device->console_layout.load(std::memory_order_relaxed)); + constexpr unsigned pc = console_to_pc_list_slot(kConsoleClearDepthStencilView); + if (pc >= self->pc_slot_count) { + static std::atomic beyond_warned{false}; + bool expected = false; + if (beyond_warned.compare_exchange_strong(expected, true, std::memory_order_relaxed)) + std::fprintf(stderr, + "[rt] d3d12_xs: list slot %u maps to PC slot %u, beyond the real list's %u slots\n", + kConsoleClearDepthStencilView, pc, self->pc_slot_count); + return; + } + const D3D12_CPU_DESCRIPTOR_HANDLE translated = translate_cpu_handle(self->device, dsv); + using ClearDsvFn = void(WINAPI*)(ID3D12GraphicsCommandList*, D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_CLEAR_FLAGS, + FLOAT, UINT8, UINT, const D3D12_RECT*); + auto** const real_vtable = *reinterpret_cast(self->real); + reinterpret_cast(real_vtable[pc])(self->real, translated, flags, depth, stencil, num_rects, rects); +} + +template +void fill_list_vtable(void** vtable, std::index_sequence) { + ((vtable[I] = reinterpret_cast(&list_slot(I)>) ), ...); + vtable[kConsoleClearDepthStencilView] = reinterpret_cast(&list_clear_depth_stencil_view); +} + +void** get_list_vtable() { + static void** vtable = [] { + static void* storage[kListSlots]; + fill_list_vtable(storage, std::make_index_sequence{}); + return storage; + }(); + return vtable; +} + +bool is_list_proxy_impl(const void* list) { + return list && *reinterpret_cast(list) == reinterpret_cast(get_list_vtable()); +} + +IUnknown* list_real_or_null(const void* object) { + return is_list_proxy_impl(object) ? static_cast(static_cast(object)->real) + : nullptr; +} + +// Wraps `created` (one reference, owned by the proxy on success, released on failure) and returns `riid` from the +// proxy through `out`. +HRESULT wrap_list(IUnknown* created, DeviceProxy* device, const IID* riid, void** out) { + if (!created) return E_FAIL; + ListProxy* proxy = new (std::nothrow) ListProxy(); // (): the console body starts zeroed + if (!proxy) { + created->Release(); + return E_OUTOFMEMORY; + } + proxy->vtable = get_list_vtable(); + proxy->real = static_cast(created); + proxy->device = device; + proxy->refs.store(1, std::memory_order_relaxed); + proxy->pc_slot_count = detect_list_slot_count(created); + proxy->pin_cursor_at_limit(); + proxy_add_ref(device); // the list keeps its Xbox-ABI device alive for GetDevice - const HRESULT hr = child_query_interface(proxy, riid, out); + const HRESULT hr = list_query_interface(proxy, riid, out); if (FAILED(hr)) { - destroy_child(proxy); // no reference escaped + destroy_list(proxy); // no reference escaped return hr; } - // Titles create fences at run time: the first proxy of each kind is logged, every one only with XS_TRACE. static std::atomic logged{false}; if (!d3d12_trace::enabled() && (!logged.exchange(true, std::memory_order_relaxed) || trace_enabled())) - std::fprintf(stderr, "[rt] d3d12_xs: %s proxy %p wraps %p (device proxy %p, %u public slots)\n", - child_kind_name(), static_cast(proxy), static_cast(created), - static_cast(device), proxy->slot_count); + std::fprintf(stderr, "[rt] d3d12_xs: list proxy %p wraps %p (%u PC vtable slots)\n", + static_cast(proxy), static_cast(created), proxy->pc_slot_count); proxy->refs.fetch_sub(1, std::memory_order_relaxed); // drop the creation reference; `out` holds the caller's return S_OK; } +// Device slot 12: CreateCommandList(node_mask, type, allocator, initial_pso, riid, out). The title hands its +// allocator proxy, which the real device unwraps to the real allocator; the created list goes back console-shaped. +HRESULT proxy_create_command_list(DeviceProxy* self, std::uint64_t node_mask, std::uint64_t type, + std::uint64_t allocator, std::uint64_t pso, const IID* riid, void** out) { + note_slot(12); + if (out) *out = nullptr; // as slot 8 + if (!riid) return E_POINTER; + if (!out) return self->real->CreateCommandList(static_cast(node_mask), + static_cast(type), + reinterpret_cast(unwrap_object(allocator)), + reinterpret_cast(pso), *riid, nullptr); + if (!self->console_lists) { + // PC caller (create_device_proxy's console_lists=false): the real list answers every PC slot, and the + // console-only pieces (slot 148, the shifted tail) are simply not there for this caller to reach. + return self->real->CreateCommandList(static_cast(node_mask), + static_cast(type), + reinterpret_cast(unwrap_object(allocator)), + reinterpret_cast(pso), *riid, out); + } + void* created = nullptr; + const HRESULT hr = self->real->CreateCommandList( + static_cast(node_mask), static_cast(type), + reinterpret_cast(unwrap_object(allocator)), + reinterpret_cast(pso), __uuidof(ID3D12GraphicsCommandList), &created); + if (FAILED(hr)) return hr; + if (!created) return E_FAIL; + return wrap_list(static_cast(created), self, riid, out); +} + // Calls the real device's slot `Slot` with these five words in the positions the thunk received them (see "A thunk // declares 14 argument words" at the top: no word may move to another stack position on the way). template @@ -1371,6 +2390,25 @@ HRESULT proxy_create_command_queue(DeviceProxy* self, const D3D12_COMMAND_QUEUE_ return wrap_child(static_cast(created), self, riid, out); } +// Device slot 48, measured on the retail title: (desc, riid, out) with riid = IID_ID3D12CommandQueue. On the PC the +// slot is OpenExistingHeapFromAddress, so forwarding it by number fails. desc is a PC D3D12_COMMAND_QUEUE_DESC +// (16 bytes) followed by four more 32-bit Xbox words of unknown meaning, logged once. Only the PC prefix is used and +// only the flag the PC knows is kept; the rest is the slot 8 path. +HRESULT proxy_create_command_queue_xbox(DeviceProxy* self, const std::uint32_t* desc, const IID* riid, void** out) { + if (out) *out = nullptr; + if (!desc) return E_INVALIDARG; + static_assert(sizeof(D3D12_COMMAND_QUEUE_DESC) == 16, "the PC prefix of the Xbox description is 16 bytes"); + D3D12_COMMAND_QUEUE_DESC pc{}; + std::memcpy(&pc, desc, sizeof(pc)); + pc.Flags &= D3D12_COMMAND_QUEUE_FLAG_DISABLE_GPU_TIMEOUT; + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, + "[rt] d3d12_xs: slot 48 queue: flags=0x%x extra words=0x%x 0x%x 0x%x 0x%x\n", + static_cast(desc[2]), desc[4], desc[5], desc[6], desc[7]); + return proxy_create_command_queue(self, &pc, riid, out); +} + // Xbox device slot 78 (public HLE): SetFrameIntervalX(output, interval_us, latency, flags). The output and flags are // not used before a presenter exists. The period is a vblank period in microseconds in the public samples (16667 for // 60 Hz), and latency is the allowed frames in flight. S_OK even for 0: a boot must not abort here, and nothing paces. @@ -1403,9 +2441,7 @@ HRESULT proxy_wait_frame_event_x(DeviceProxy* self, std::uint64_t event, std::ui (void)flags; auto* token = reinterpret_cast(token_word); if (!token) return E_POINTER; - std::uint64_t value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed); - if (value == 0) value = self->frame_next_token.fetch_add(1, std::memory_order_relaxed); // skip the null token - *token = value; + *token = self->frame_tokens->issue(); return S_OK; } @@ -1437,13 +2473,144 @@ HRESULT proxy_create_command_list_x(DeviceProxy* self, std::uint64_t desc_word, auto* allocator = allocator_proxy_real_allocator(reinterpret_cast(allocator_word)); if (!allocator) allocator = reinterpret_cast(allocator_word); auto* initial_state = reinterpret_cast(initial_state_word); + if (!self->console_lists) + return self->real->CreateCommandList(0, type, allocator, initial_state, + command_list_iid_for_pc(*riid), out); void* created = nullptr; const HRESULT hr = self->real->CreateCommandList(0, type, allocator, initial_state, - *riid, &created); + __uuidof(ID3D12GraphicsCommandList), &created); if (FAILED(hr)) return hr; return wrap_list(static_cast(created), self, riid, out); } +// Xbox device slot 70: (texture_words, view_desc, destination), no return value. The retail executable's SRV writer +// makes a view from raw descriptions and a GPU address with no resource object (docs/retail_boot_chain.md, stop 14). +// The PC slot 70 is ID3D12Device8::CreatePlacedResource1, which would take the destination handle for a resource +// description and write through it, so it is never forwarded. +// +// The one measured shape (PR 7066, eugen1763, first retail call) is a raw buffer view: texture_words starts with a +// desktop D3D12_RESOURCE_DESC (buffer), view_desc with a desktop D3D12_SHADER_RESOURCE_VIEW_DESC (R32_TYPELESS, +// BUFFER, RAW flag) followed at once by a D3D12_GPU_VIRTUAL_ADDRESS, the console VA slot 133 registered. For that shape +// and a VA inside a buffer the resource provider knows, the destination gets a raw view of that range: FirstElement +// (va - resource start) / 4, NumElements the description's Width / 4, cut to the end of the resource. Anything else +// (a texture, another dimension or format, no RAW flag, a VA no buffer holds, no provider, unreadable words) keeps the +// PC null view, which a shader reads as zeros, with one log line saying why. Texture shapes are not measured. +struct RawSrvShape { + D3D12_RESOURCE_DESC resource; + D3D12_SHADER_RESOURCE_VIEW_DESC view; + D3D12_GPU_VIRTUAL_ADDRESS va; +}; + +bool readable(std::uint64_t address, std::size_t bytes) { + MEMORY_BASIC_INFORMATION info{}; + if (!address || !VirtualQuery(reinterpret_cast(address), &info, sizeof(info))) return false; + if (info.State != MEM_COMMIT || (info.Protect & (PAGE_NOACCESS | PAGE_GUARD))) return false; + const auto end = reinterpret_cast(info.BaseAddress) + info.RegionSize; + return address + bytes <= end; +} + +// Reads the measured shape from the two words into `out`. Returns null when it parsed, else why it is not that shape. +const char* parse_raw_srv(std::uint64_t texture_words, std::uint64_t view_desc, RawSrvShape& out) { + if (!readable(texture_words, sizeof(D3D12_RESOURCE_DESC)) || + !readable(view_desc, sizeof(D3D12_SHADER_RESOURCE_VIEW_DESC) + sizeof(D3D12_GPU_VIRTUAL_ADDRESS))) + return "the words are not readable"; + std::memcpy(&out.resource, reinterpret_cast(texture_words), sizeof(out.resource)); + std::memcpy(&out.view, reinterpret_cast(view_desc), sizeof(out.view)); + std::memcpy(&out.va, reinterpret_cast(view_desc) + sizeof(out.view), sizeof(out.va)); + if (out.resource.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) return "arg1 is not a buffer description"; + if (out.view.ViewDimension != D3D12_SRV_DIMENSION_BUFFER) return "arg2 is not a buffer view"; + if (out.view.Format != DXGI_FORMAT_R32_TYPELESS || !(out.view.Buffer.Flags & D3D12_BUFFER_SRV_FLAG_RAW)) + return "arg2 is not a raw R32_TYPELESS view"; + if (!out.resource.Width || !out.va) return "no width or no address"; + return nullptr; +} + +void write_null_srv(DeviceProxy* self, std::uint64_t destination) { + D3D12_SHADER_RESOURCE_VIEW_DESC null_view{}; + null_view.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + null_view.ViewDimension = D3D12_SRV_DIMENSION_TEXTURE2D; + null_view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + null_view.Texture2D.MipLevels = 1; + self->real->CreateShaderResourceView(nullptr, &null_view, D3D12_CPU_DESCRIPTOR_HANDLE{destination}); +} + +void log_slot70_null_once(const char* why, std::uint64_t texture_words, std::uint64_t view_desc) { + static std::atomic logged{false}; + if (first_call(logged)) + std::fprintf(stderr, "[rt] d3d12_xs: slot 70 writes a null view: %s (args 0x%llx 0x%llx)\n", why, + static_cast(texture_words), static_cast(view_desc)); +} + +void proxy_create_srv_from_raw_x(DeviceProxy* self, std::uint64_t texture_words, std::uint64_t view_desc, + std::uint64_t destination) { + note_slot(70); + log_xbox_route_once(70, "CreateShaderResourceView from raw words", texture_words, view_desc, destination, 0, 0); + if (!destination) return; + // LOCAL: whatever this call writes to the real slot is stored at the title's address too when it returns. + struct LocalWriteThrough { + DeviceProxy* self; + std::uint64_t custom; + ~LocalWriteThrough() { local_write_through(self, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(custom)}, 1); } + } local_write_back{self, destination}; + // The console hands a CPU descriptor handle in the title's heap memory; #7021 translates it to the real heap's. + destination = translate_cpu_handle(self, D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(destination)}).ptr; + + RawSrvShape shape{}; + const char* why = parse_raw_srv(texture_words, view_desc, shape); + if (why || !self->resource_provider) { + log_slot70_null_once(why ? why : "no resource provider", texture_words, view_desc); + write_null_srv(self, destination); + return; + } + std::uint64_t start = 0, size = 0; + ID3D12Resource* resource = self->resource_provider(self->real, shape.va, shape.resource.Width, &start, &size); + if (!resource || shape.va < start || shape.va - start >= size) { + if (resource) resource->Release(); + // LOCAL: a small raw view over the title's own memory becomes a raw buffer V# through the constant-view path, + // which resolves a title address to its GPU copy (#9137). LEONIDA_SLOT70_TITLE=0 keeps the null view. + static const bool title_views = [] { const char* v = std::getenv("LEONIDA_SLOT70_TITLE"); return !(v && *v == '0'); }(); + std::uint64_t title_lo = 0, title_hi = 0; + if (title_views && shape.resource.Width && shape.resource.Width <= 65536 && + leonida::title_va_aliases().title_memory(shape.va, title_lo, title_hi) && + shape.resource.Width <= title_hi - shape.va) { + D3D12_CONSTANT_BUFFER_VIEW_DESC constants{}; + constants.BufferLocation = shape.va; + constants.SizeInBytes = static_cast(shape.resource.Width); + self->real->CreateConstantBufferView(&constants, D3D12_CPU_DESCRIPTOR_HANDLE{destination}); + static std::atomic said{false}; + if (!said.exchange(true)) + std::fprintf(stderr, "[rt] d3d12_xs: local: slot 70 view over title memory (%llu bytes) written as a raw " + "buffer V# on its GPU copy\n", static_cast(shape.resource.Width)); + return; + } + log_slot70_null_once("no buffer holds the address", texture_words, view_desc); + write_null_srv(self, destination); + return; + } + const std::uint64_t offset = shape.va - start; + const std::uint64_t elements = std::min(shape.resource.Width, size - offset) / 4; + if (offset % 4 || !elements || elements > UINT32_MAX) { + resource->Release(); + log_slot70_null_once("address or width is not 4-byte aligned or too large", texture_words, view_desc); + write_null_srv(self, destination); + return; + } + D3D12_SHADER_RESOURCE_VIEW_DESC view{}; + view.Format = DXGI_FORMAT_R32_TYPELESS; + view.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + view.Shader4ComponentMapping = shape.view.Shader4ComponentMapping; + view.Buffer.FirstElement = offset / 4; + view.Buffer.NumElements = static_cast(elements); + view.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + self->real->CreateShaderResourceView(resource, &view, D3D12_CPU_DESCRIPTOR_HANDLE{destination}); + resource->Release(); + static std::atomic logged{false}; + if (first_call(logged)) + std::fprintf(stderr, "[rt] d3d12_xs: slot 70 wrote a raw buffer view (va 0x%llx, first element %llu, %u elements)\n", + static_cast(shape.va), static_cast(view.Buffer.FirstElement), + view.Buffer.NumElements); +} + // Device slot 75: ID3D12Device9::CreateCommandQueue1(desc, creator_id, riid, out), called by slot index. HRESULT proxy_create_command_queue1(DeviceProxy* self, std::uint64_t desc, std::uint64_t creator_id, const IID* riid, void** out) { @@ -1563,37 +2730,6 @@ HRESULT proxy_unwrapping_call(DeviceProxy* self, std::uint64_t a1, std::uint64_t return static_cast(static_cast(forward_device(self, r1, r2, r3, r4, a5))); } -// A console descriptor heap carries a size as well as an address, and that size is 32 bytes per descriptor. A PC -// desc's trailing words are whatever the caller holds next; they do not encode NumDescriptors * 32, so this -// separates the two layouts without guessing anything about the address itself. -static bool console_heap_range_plausible(const D3D12_DESCRIPTOR_HEAP_DESC* desc, std::uint64_t address, - std::uint64_t size) { - constexpr std::uint64_t kConsoleDescriptorSize = 32; - if (address == 0 || size == 0) return false; - if (desc->NumDescriptors == 0 || desc->NumDescriptors > (0xFFFFFFFFull / kConsoleDescriptorSize)) return false; - if (size != static_cast(desc->NumDescriptors) * kConsoleDescriptorSize) return false; - return true; -} - -static bool readable_range(const void* ptr, std::size_t bytes) { - if (!ptr || !bytes) return false; - const auto* p = static_cast(ptr); - std::size_t remaining = bytes; - while (remaining) { - MEMORY_BASIC_INFORMATION mbi{}; - if (!VirtualQuery(p, &mbi, sizeof(mbi)) || mbi.State != MEM_COMMIT) return false; - const DWORD protect = mbi.Protect & 0xffu; - if (protect == PAGE_NOACCESS || protect == PAGE_GUARD || protect == PAGE_EXECUTE) return false; - const auto base = reinterpret_cast(mbi.BaseAddress); - const auto addr = reinterpret_cast(p); - const std::size_t avail = static_cast(base + mbi.RegionSize - addr); - if (avail >= remaining) return true; - remaining -= avail; - p += avail; - } - return true; -} - HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_HEAP_DESC* desc, const IID* riid, void** out) { note_slot(14); @@ -1603,41 +2739,140 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H if (!out) return self->real->CreateDescriptorHeap(desc, *riid, nullptr); void* created = nullptr; - HRESULT hr = E_INVALIDARG; - bool console_extended = false; - if (desc && desc->Type <= D3D12_DESCRIPTOR_HEAP_TYPE_DSV && - (desc->Flags & ~D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE) == 0) { - const auto* bytes = reinterpret_cast(desc); - const void* tail = bytes + sizeof(D3D12_DESCRIPTOR_HEAP_DESC); - if (readable_range(tail, sizeof(std::uint64_t) * 2)) { - std::uint64_t address = 0; - std::uint64_t size = 0; - std::memcpy(&address, tail, sizeof(address)); - std::memcpy(&size, bytes + sizeof(D3D12_DESCRIPTOR_HEAP_DESC) + sizeof(address), sizeof(size)); - // Console-extended slot 14 (issue #313): address/size follow the PC desc. A non-zero word is not evidence - // of that layout - the bytes after a PC desc are whatever the caller holds next, and they are almost - // always readable and non-zero. The size has to agree with the descriptor count for the path to be taken. - if (console_heap_range_plausible(desc, address, size)) { - const ConsoleDescriptorHeapHandler handler = - g_console_descriptor_heap.load(std::memory_order_acquire); - if (handler) { - console_extended = true; - hr = handler(self->real, desc, static_cast(address), size, - __uuidof(ID3D12DescriptorHeap), &created); + HRESULT hr = self->real->CreateDescriptorHeap(desc, __uuidof(ID3D12DescriptorHeap), &created); + if (FAILED(hr) || !created) return FAILED(hr) ? hr : E_FAIL; + + ID3D12DescriptorHeap* heap = static_cast(created); + SIZE_T custom_cpu_start = 0; + SIZE_T custom_byte_size = 0; + SIZE_T real_cpu_start = 0; + DescriptorHeapBackingAlloc alloc_fn = nullptr; + DescriptorHeapBackingFree free_fn = nullptr; + { + std::lock_guard lock(heap_alloc_mutex()); + alloc_fn = g_heap_alloc; + free_fn = g_heap_free; + } + if (alloc_fn && desc && desc->NumDescriptors > 0) { + const UINT inc = self->real->GetDescriptorHandleIncrementSize(desc->Type); + if (inc > 0 && desc->NumDescriptors <= (std::numeric_limits::max)() / inc) { + const SIZE_T byte_size = static_cast(desc->NumDescriptors) * static_cast(inc); + void* backing = alloc_fn(byte_size, kXmemDescriptorHeapAttributes); + if (backing) { + const auto addr = reinterpret_cast(backing); + if (addr <= (std::numeric_limits::max)() - byte_size) { + custom_cpu_start = addr; + custom_byte_size = byte_size; + real_cpu_start = raw_heap_get_cpu_handle(heap, *reinterpret_cast(heap)).ptr; + } else if (free_fn) { + free_fn(backing, kXmemDescriptorHeapAttributes); } } } } - if (!console_extended) - hr = self->real->CreateDescriptorHeap(desc, __uuidof(ID3D12DescriptorHeap), &created); - if (FAILED(hr) || !created) return FAILED(hr) ? hr : E_FAIL; - ID3D12DescriptorHeap* heap = static_cast(created); - hr = create_heap_proxy(heap, self, *riid, out); - if (FAILED(hr)) heap->Release(); + hr = create_heap_proxy(heap, self, *riid, out, custom_cpu_start, custom_byte_size, real_cpu_start, + custom_cpu_start ? free_fn : nullptr); + if (FAILED(hr)) { + heap->Release(); + if (custom_cpu_start && free_fn) + free_fn(reinterpret_cast(custom_cpu_start), kXmemDescriptorHeapAttributes); + } return hr; } +// Device slots 17-24 write or copy descriptors using CPU handles. When a title supplies its own descriptor-heap base +// via __XMemAllocationHooks__, those handles fall in [custom_start, custom_end) and must be translated back to the +// underlying PC/Vulkan heap before forwarding. +void proxy_create_cbv(DeviceProxy* self, const D3D12_CONSTANT_BUFFER_VIEW_DESC* desc, + D3D12_CPU_DESCRIPTOR_HANDLE dest) { + note_slot(17); + self->real->CreateConstantBufferView(desc, translate_cpu_handle(self, dest)); + local_write_through(self, dest, 1); +} + +void proxy_create_srv(DeviceProxy* self, ID3D12Resource* resource, const D3D12_SHADER_RESOURCE_VIEW_DESC* desc, + D3D12_CPU_DESCRIPTOR_HANDLE dest) { + note_slot(18); + self->real->CreateShaderResourceView(resource, desc, translate_cpu_handle(self, dest)); + local_write_through(self, dest, 1); +} + +void proxy_create_uav(DeviceProxy* self, ID3D12Resource* resource, ID3D12Resource* counter, + const D3D12_UNORDERED_ACCESS_VIEW_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) { + note_slot(19); + self->real->CreateUnorderedAccessView(resource, counter, desc, translate_cpu_handle(self, dest)); + local_write_through(self, dest, 1); +} + +void proxy_create_rtv(DeviceProxy* self, ID3D12Resource* resource, const D3D12_RENDER_TARGET_VIEW_DESC* desc, + D3D12_CPU_DESCRIPTOR_HANDLE dest) { + note_slot(20); + self->real->CreateRenderTargetView(resource, desc, translate_cpu_handle(self, dest)); +} + +void proxy_create_dsv(DeviceProxy* self, ID3D12Resource* resource, const D3D12_DEPTH_STENCIL_VIEW_DESC* desc, + D3D12_CPU_DESCRIPTOR_HANDLE dest) { + note_slot(21); + self->real->CreateDepthStencilView(resource, desc, translate_cpu_handle(self, dest)); +} + +void proxy_create_sampler(DeviceProxy* self, const D3D12_SAMPLER_DESC* desc, D3D12_CPU_DESCRIPTOR_HANDLE dest) { + note_slot(22); + self->real->CreateSampler(desc, translate_cpu_handle(self, dest)); + local_write_through(self, dest, 1); +} + +void proxy_copy_descriptors(DeviceProxy* self, UINT num_dest, const D3D12_CPU_DESCRIPTOR_HANDLE* dest_starts, + const UINT* dest_sizes, UINT num_src, const D3D12_CPU_DESCRIPTOR_HANDLE* src_starts, + const UINT* src_sizes, D3D12_DESCRIPTOR_HEAP_TYPE type) { + note_slot(23); + if (g_custom_range_count.load(std::memory_order_acquire) == 0) { + self->real->CopyDescriptors(num_dest, dest_starts, dest_sizes, num_src, src_starts, src_sizes, type); + return; + } + constexpr UINT kInline = 32; + D3D12_CPU_DESCRIPTOR_HANDLE dest_inline[kInline]; + D3D12_CPU_DESCRIPTOR_HANDLE src_inline[kInline]; + std::vector dest_heap; + std::vector src_heap; + const D3D12_CPU_DESCRIPTOR_HANDLE* dest_out = dest_starts; + const D3D12_CPU_DESCRIPTOR_HANDLE* src_out = src_starts; + try { + if (dest_starts && num_dest > 0) { + D3D12_CPU_DESCRIPTOR_HANDLE* dst = dest_inline; + if (num_dest > kInline) { + dest_heap.resize(num_dest); + dst = dest_heap.data(); + } + for (UINT i = 0; i < num_dest; ++i) dst[i] = translate_cpu_handle(self, dest_starts[i]); + dest_out = dst; + } + if (src_starts && num_src > 0) { + D3D12_CPU_DESCRIPTOR_HANDLE* src = src_inline; + if (num_src > kInline) { + src_heap.resize(num_src); + src = src_heap.data(); + } + for (UINT i = 0; i < num_src; ++i) src[i] = translate_cpu_handle(self, src_starts[i]); + src_out = src; + } + } catch (const std::bad_alloc&) { + return; + } + self->real->CopyDescriptors(num_dest, dest_out, dest_sizes, num_src, src_out, src_sizes, type); + for (UINT i = 0; dest_starts && i < num_dest; ++i) + local_write_through(self, dest_starts[i], dest_sizes ? dest_sizes[i] : 1); +} + +void proxy_copy_descriptors_simple(DeviceProxy* self, UINT num_descriptors, D3D12_CPU_DESCRIPTOR_HANDLE dest_start, + D3D12_CPU_DESCRIPTOR_HANDLE src_start, D3D12_DESCRIPTOR_HEAP_TYPE type) { + note_slot(24); + self->real->CopyDescriptorsSimple(num_descriptors, translate_cpu_handle(self, dest_start), + translate_cpu_handle(self, src_start), type); + local_write_through(self, dest_start, num_descriptors); +} + // The Xbox slot 62 takes two more words between the description and the IID: (desc, w2, w3, riid, out). Measured // on the package's XboxBvhBuilder.dll (its constructor passes w2 = w3 = 0 and IID_ID3D12PipelineState in the fourth // argument), as the prior art had recorded. Their meaning is unknown; non-zero values are logged once. @@ -1656,6 +2891,78 @@ HRESULT proxy_create_compute_pipeline_state(DeviceProxy* self, const D3D12_COMPU return self->real->CreateComputePipelineState(desc, *riid, out); } +// The Xbox slot 41 is CreateCommandSignature at its PC position, (desc, root signature, riid, out), but a console +// description can hold an argument type the PC does not have. The retail title creates five one-argument signatures +// with no root signature at startup; one has type 105 (0x69) and a 12-byte stride, next to a DISPATCH and a +// DISPATCH_MESH of 12 bytes. Read statically from its call sites (counts and shapes only): its two ExecuteIndirect +// sites pass MaxCommandCount 1 and an argument offset into the same upload buffer as the DISPATCH ones, and set the +// compute state (pipeline, compute root signature, tables, constants, SRV/UAV) right before, as the DISPATCH path +// does; they record on a second command list of the title's context. So type 105 is taken as a dispatch whose +// arguments are a D3D12_DISPATCH_ARGUMENTS. HYPOTHESIS: what the console does differently for it (which command +// stream it feeds) is not known; the PC layer has one compute path. Other descriptions are forwarded unchanged. +// 105 is outside D3D12_INDIRECT_ARGUMENT_TYPE's range, so the field is read as its 32 bits (a constant expression that +// casts 105 to the enum does not compile with clang-cl). +constexpr std::uint32_t kXboxIndirectArgumentDispatch105 = 105; + +std::uint32_t argument_type(const D3D12_INDIRECT_ARGUMENT_DESC& arg) { + std::uint32_t type = 0; + std::memcpy(&type, &arg.Type, sizeof(type)); + return type; +} + +HRESULT proxy_create_command_signature(DeviceProxy* self, const D3D12_COMMAND_SIGNATURE_DESC* desc, + std::uint64_t root_signature, const IID* riid, void** out) { + note_slot(41); + using Fn = HRESULT(STDMETHODCALLTYPE*)(ID3D12Device*, const D3D12_COMMAND_SIGNATURE_DESC*, std::uint64_t, + const IID*, void**); + const auto forward = reinterpret_cast(self->real_vtable[41]); + bool console = false; + if (desc && desc->pArgumentDescs) + for (UINT i = 0; i < desc->NumArgumentDescs && !console; ++i) + console = argument_type(desc->pArgumentDescs[i]) == kXboxIndirectArgumentDispatch105; + if (!console) return forward(self->real, desc, root_signature, riid, out); + + std::unique_ptr args(new (std::nothrow) + D3D12_INDIRECT_ARGUMENT_DESC[desc->NumArgumentDescs]); + if (!args) { + if (out) *out = nullptr; + return E_OUTOFMEMORY; + } + for (UINT i = 0; i < desc->NumArgumentDescs; ++i) { + args[i] = desc->pArgumentDescs[i]; + if (argument_type(args[i]) == kXboxIndirectArgumentDispatch105) + args[i].Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH; + } + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12_xs: slot 41 argument type 105 (stride %u) created as DISPATCH\n", + desc->ByteStride); + D3D12_COMMAND_SIGNATURE_DESC pc = *desc; + pc.pArgumentDescs = args.get(); + return forward(self->real, &pc, root_signature, riid, out); +} + +// The Xbox slot 61 is CreateSamplerX(desc, dest): a sampler written to a CPU descriptor handle, with the PC +// CreateSampler's two arguments. Measured on the retail title's boot (stop 20 in #6910's RT-5 measurements): the +// title calls it once per sampler after its descriptor heaps exist, and it goes on when the call is served by the PC +// CreateSampler. The PC slot 61 is CreateMetaCommand, which would take these words as (CommandId, NodeMask, ...). +// HYPOTHESIS: the console description begins with the PC D3D12_SAMPLER_DESC (52 bytes), which is what got the title +// past this call; whatever follows it is not known and not read. The title was not seen testing a result, so a null +// description is skipped rather than reported. The handle is passed as given: a handle in the title's own heap range +// is #7021's translation. +void proxy_create_sampler_x(DeviceProxy* self, const D3D12_SAMPLER_DESC* desc, std::uint64_t dest) { + note_slot(61); + if (!desc) { + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12_xs: slot 61 CreateSamplerX without a description (skipped)\n"); + return; + } + D3D12_CPU_DESCRIPTOR_HANDLE handle{}; + handle.ptr = static_cast(dest); + self->real->CreateSampler(desc, handle); +} + // The Xbox slot 67 creates a compute pipeline from native GPU code: (desc, riid, out), named // DeserializeComputePipelineStateX in amd_fidelityfx_upscaler_xbox.dll's messages (call at RVA 0x56d9). The desc // passes the root signature at +0x00, followed by pointer/size pairs for the shader's FSPX entries (docs/fspx.md): @@ -1738,6 +3045,100 @@ HRESULT proxy_create_compute_pipeline_from_native_code(DeviceProxy* self, const return hr; } +// ---- Committed resources take their memory through the title's XMem hooks (RT-5 stop 17) ---- +// On the console the D3D runtime allocates a committed resource's memory with XMemAlloc, so the allocation goes +// through the title's __XMemAllocationHooks__. Around its first full-screen render targets (slot 127) the retail title +// registers a per-thread matcher that bump-allocates out of a range it reserved, taking any allocation whose XALLOC +// page-size field (bits 14..15) is 2, and afterwards asserts that less than 2 MiB of the range is left. Resources +// created on the PC never allocated through the hooks, so the whole range was left and the assert fired. Each committed +// resource made by slots 76 and 127 therefore allocates its size through the hooks as a lease: the resource holds it +// (SetPrivateDataInterface) and the hooks' free runs when the resource is destroyed. The bytes are not used for the +// resource; the PC device owns its memory. The size is the console's (lease_size): for a render target of a listed +// shape, its whole SW_64KB_D tiles (console_render_target_size), never the PC size. The title's budget is sized for +// exactly those (two 3840 x 2160 RGBA8 targets are 2 x 510 tiles of a 64 MiB range), and a PC driver may answer more: +// AMD's Windows driver gives 513 x 64 KiB for that target, and leasing that overran the range (an int3 in the title's +// hook, @controldebils on #7240). Anything else leases the PC size. +// HYPOTHESIS: the attribute word, allocator ID 0x80 (eXALLOCAllocatorId_D3D) with page-size field 2 and object type 0. +// Of it the measured matcher reads only the page-size field; a title hook that matches on other fields may not take +// these leases for the console's allocations. +inline constexpr std::uint64_t kXmemCommittedResourceAttributes = (0x80ULL << 16) | (2ULL << 14); + +// {6c1f3a52-8d47-4e0b-9b1e-2f7a5c3d9e61}: the private-data entry a committed resource keeps its lease under. +constexpr GUID kTitleMemoryLeaseGuid{0x6c1f3a52, 0x8d47, 0x4e0b, {0x9b, 0x1e, 0x2f, 0x7a, 0x5c, 0x3d, 0x9e, 0x61}}; + +// The console allocation for one clean description: a listed render-target shape's whole tiles, else the PC size. +UINT64 lease_size(ID3D12Device* real, const D3D12_RESOURCE_DESC& clean_desc) { + if (const UINT64 tiles = console_render_target_size(clean_desc)) return tiles; + return real->GetResourceAllocationInfo(0, 1, &clean_desc).SizeInBytes; +} + +// One reference is held by the resource; the last Release gives the memory back through the hooks' free. +class TitleMemoryLease final : public IUnknown { +public: + TitleMemoryLease(void* memory, DescriptorHeapBackingFree free_fn) : memory_(memory), free_(free_fn) {} + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** out) override { + if (!out) return E_POINTER; + if (!IsEqualIID(riid, __uuidof(IUnknown))) { + *out = nullptr; + return E_NOINTERFACE; + } + AddRef(); + *out = this; + return S_OK; + } + ULONG STDMETHODCALLTYPE AddRef() override { return refs_.fetch_add(1, std::memory_order_relaxed) + 1; } + ULONG STDMETHODCALLTYPE Release() override { + const ULONG left = refs_.fetch_sub(1, std::memory_order_acq_rel) - 1; + if (left == 0) { + if (free_) free_(memory_, kXmemCommittedResourceAttributes); + delete this; + } + return left; + } + +private: + std::atomic refs_{1}; + void* memory_; + DescriptorHeapBackingFree free_; +}; + +// `created` is the object a slot 76/127 creation returned (any interface of the resource). Nothing happens without +// installed hooks, for a size the PC device refuses, or when the hooks return null; creation never fails here. +void lease_title_resource_memory(DeviceProxy* self, void* created, const D3D12_RESOURCE_DESC& clean_desc) { + if (!created) return; + DescriptorHeapBackingAlloc alloc_fn = nullptr; + DescriptorHeapBackingFree free_fn = nullptr; + { + std::lock_guard lock(heap_alloc_mutex()); + alloc_fn = g_heap_alloc; + free_fn = g_heap_free; + } + if (!alloc_fn) return; + const UINT64 size = lease_size(self->real, clean_desc); + if (size == 0 || size == UINT64_MAX || size > (std::numeric_limits::max)()) return; + void* const memory = alloc_fn(static_cast(size), kXmemCommittedResourceAttributes); + if (!memory) return; + ID3D12Object* object = nullptr; + auto* const lease = new (std::nothrow) TitleMemoryLease(memory, free_fn); + if (!lease || FAILED(static_cast(created)->QueryInterface(__uuidof(ID3D12Object), + reinterpret_cast(&object)))) { + if (lease) + lease->Release(); // frees the memory + else if (free_fn) + free_fn(memory, kXmemCommittedResourceAttributes); + return; + } + object->SetPrivateDataInterface(kTitleMemoryLeaseGuid, lease); // the resource's reference + object->Release(); + lease->Release(); // ours; from here the resource's reference is the only one + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, + "[rt] d3d12_xs: committed resources lease their size through the title's XMem hooks (first: " + "%llu B)\n", + static_cast(size)); +} + HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* heap_properties, D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* xbox_desc, D3D12_RESOURCE_STATES initial_state, const D3D12_CLEAR_VALUE* clear_value, @@ -1755,6 +3156,10 @@ HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* he const auto xbox_layout = static_cast(pc_desc.Layout); pc_desc.Layout = pc_desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? D3D12_TEXTURE_LAYOUT_ROW_MAJOR : D3D12_TEXTURE_LAYOUT_UNKNOWN; + // A console depth-stencil texture may allow unordered access; the PC one may not (without_depth_stencil_uav, the + // slot 25 stand-in). Only that bit is dropped here: the other flag bits go on as they came. + pc_desc.Flags = static_cast( + without_depth_stencil_uav(pc_desc.Dimension, static_cast(pc_desc.Flags))); static std::atomic logged{false}; if (!logged.exchange(true, std::memory_order_relaxed)) { @@ -1762,8 +3167,328 @@ HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* he "[rt] d3d12_xs: slot 76 resource: dimension=%d xbox layout=0x%x -> PC layout=0x%x\n", static_cast(pc_desc.Dimension), xbox_layout, static_cast(pc_desc.Layout)); } - return self->real->CreateCommittedResource(heap_properties, heap_flags, &pc_desc, initial_state, clear_value, - *riid, out); + const HRESULT hr = self->real->CreateCommittedResource(heap_properties, heap_flags, &pc_desc, initial_state, + clear_value, *riid, out); + if (SUCCEEDED(hr)) lease_title_resource_memory(self, *out, pc_desc); + return hr; +} + +// Xbox device slot 127 (RT-5 stop 15, measured by Pipodi in #6982): the argument list of ID3D12Device10:: +// CreateCommittedResource3, (heap properties, heap flags, desc1, initial layout, clear value, protected session, +// castable format count, castable formats, riid, out), with the Xbox layout word in desc1.Layout and Xbox bits above +// the PC flags in desc1.Flags. The slot is past the PC device's vtable, so the generic thunk could only refuse it. The +// PC device creates the resource through its own CreateCommittedResource3 (PC slot 76) with the layout word replaced +// as slot 76 does and the flags limited to the PC bits. The initial layout, clear value, session and castable list go +// on as the title passed them; 0xFFFFFFFF is D3D12_BARRIER_LAYOUT_UNDEFINED, the value the console passes for the +// state of slot 133 as well. The words take the positions the thunk received them in (see the top of the file). +constexpr unsigned kCreateCommittedResource3X = 127; +constexpr unsigned kPcCreateCommittedResource3 = 76; // ID3D12Device10, the PC device's 77th method +// D3D12_RESOURCE_FLAG_USE_TIGHT_ALIGNMENT: a PC bit the Windows SDK 10.0.26100 header does not name yet; the PC runtime +// accepts it for committed resources (D3D12 tight alignment spec), so a title's request must reach it. +constexpr std::uint32_t kPcResourceFlagUseTightAlignment = 0x400; +constexpr std::uint32_t kPcResourceFlagsMask = + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | D3D12_RESOURCE_FLAG_DENY_SHADER_RESOURCE | + D3D12_RESOURCE_FLAG_ALLOW_CROSS_ADAPTER | D3D12_RESOURCE_FLAG_ALLOW_SIMULTANEOUS_ACCESS | + D3D12_RESOURCE_FLAG_VIDEO_DECODE_REFERENCE_ONLY | D3D12_RESOURCE_FLAG_VIDEO_ENCODE_REFERENCE_ONLY | + D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE | kPcResourceFlagUseTightAlignment; + +HRESULT proxy_create_committed_resource3_x(DeviceProxy* self, std::uint64_t heap_word, std::uint64_t heap_flags, + std::uint64_t desc_word, std::uint64_t layout_word, + std::uint64_t clear_word, std::uint64_t session_word, + std::uint64_t castable_count, std::uint64_t castable_formats, + std::uint64_t riid_word, std::uint64_t out_word) { + note_slot(kCreateCommittedResource3X); + auto* const out = reinterpret_cast(out_word); + if (out) *out = nullptr; // _COM_Outptr_: NULL on every failure, as slots 14/62/76 + const auto* const xbox_desc = reinterpret_cast(desc_word); + const auto* const riid = reinterpret_cast(riid_word); + if (!out || !heap_word || !xbox_desc || !riid) return E_POINTER; + if (self->slot_count <= kPcCreateCommittedResource3) { // the PC device predates ID3D12Device10 + static std::atomic warned{false}; + if (first_call(warned)) + std::fprintf(stderr, + "[rt] d3d12_xs: device slot %u (%s) needs ID3D12Device10 and the PC device has %u slots; " + "returning E_NOTIMPL\n", + kCreateCommittedResource3X, slot_name(kCreateCommittedResource3X), self->slot_count); + return E_NOTIMPL; + } + + D3D12_RESOURCE_DESC1 pc_desc = *xbox_desc; + const auto xbox_layout = static_cast(pc_desc.Layout); + const auto xbox_flags = static_cast(pc_desc.Flags); + pc_desc.Layout = pc_desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? D3D12_TEXTURE_LAYOUT_ROW_MAJOR + : D3D12_TEXTURE_LAYOUT_UNKNOWN; + pc_desc.Flags = static_cast(xbox_flags & kPcResourceFlagsMask); + + static std::atomic logged{false}; + if (first_call(logged)) + std::fprintf(stderr, + "[rt] d3d12_xs: slot 127 resource: dimension=%d xbox layout=0x%x -> PC layout=0x%x, xbox flags " + "0x%x -> PC flags 0x%x\n", + static_cast(pc_desc.Dimension), xbox_layout, static_cast(pc_desc.Layout), + xbox_flags, static_cast(pc_desc.Flags)); + + using Fn = HRESULT(WINAPI*)(ID3D12Device*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS, + const D3D12_RESOURCE_DESC1*, std::uint32_t, const D3D12_CLEAR_VALUE*, + ID3D12ProtectedResourceSession*, std::uint32_t, const DXGI_FORMAT*, const IID*, + void**); + // The ID3D12Device10 interface pointer, not the base device's: COM only promises that QueryInterface on the + // original pointer yields that interface, and a different pointer has its own vtable. Released after the call. + void* device10 = nullptr; +#ifdef __ID3D12Device10_INTERFACE_DEFINED__ + if (FAILED(self->real->QueryInterface(__uuidof(ID3D12Device10), &device10))) device10 = nullptr; +#endif + if (!device10) return E_NOTIMPL; + const auto create = reinterpret_cast((*reinterpret_cast(device10))[kPcCreateCommittedResource3]); + const HRESULT hr = + create(static_cast(device10), reinterpret_cast(heap_word), + static_cast(static_cast(heap_flags)), &pc_desc, + static_cast(layout_word), reinterpret_cast(clear_word), + reinterpret_cast(session_word), + static_cast(castable_count), reinterpret_cast(castable_formats), riid, + out); + static_cast(device10)->Release(); + if (SUCCEEDED(hr)) { + D3D12_RESOURCE_DESC plain{}; // D3D12_RESOURCE_DESC1 without SamplerFeedbackMipRegion + plain.Dimension = pc_desc.Dimension; + plain.Alignment = pc_desc.Alignment; + plain.Width = pc_desc.Width; + plain.Height = pc_desc.Height; + plain.DepthOrArraySize = pc_desc.DepthOrArraySize; + plain.MipLevels = pc_desc.MipLevels; + plain.Format = pc_desc.Format; + plain.SampleDesc = pc_desc.SampleDesc; + plain.Layout = pc_desc.Layout; + plain.Flags = pc_desc.Flags; + lease_title_resource_memory(self, *out, plain); + } + return hr; +} + + +// Device slot 26, GetCustomHeapProperties, as the retail executable calls it. Measured on 1.0.2.1 under +// gta6rt --run with a register probe in this slot's thunk: three calls right after device creation, each with the +// device proxy in RDX and not in RCX, R8 = 1 and R9 = 1, 2, 3 (node mask 1; DEFAULT, UPLOAD, READBACK). So the +// buffer for the returned D3D12_HEAP_PROPERTIES is in RCX and the device in RDX. That is how x64 passes them to a +// plain function that takes the device as its first argument and returns a struct; a PC C++ method has the device +// in RCX and the buffer in RDX. The forwarder took RCX for the proxy, read the PC vtable out of the title's stack +// buffer and faulted. The buffer's address goes back in RAX, as that convention returns it; what the title does with +// RAX is not measured. +D3D12_HEAP_PROPERTIES* proxy_get_custom_heap_properties(D3D12_HEAP_PROPERTIES* out, DeviceProxy* self, + UINT node_mask, D3D12_HEAP_TYPE heap_type) { + note_slot(26); + *out = self->real->GetCustomHeapProperties(node_mask, heap_type); + return out; +} + +// Device slot 133 places a resource at a virtual address: (va, desc, initial_state, clear_value, riid, out), the +// shape of the console's CreatePlacedResourceX. Measured locally at a title's call sites: riid is ID3D12Resource, va is +// the start of a range the title has just reserved for physical pages, desc is a 56-byte D3D12_RESOURCE_DESC with +// Xbox bits in Flags above the PC flags. The fourth word is a D3D12_BARRIER_LAYOUT, not a resource state: the title +// passes all ones (D3D12_BARRIER_LAYOUT_UNDEFINED) for its first buffer and 6 (SHADER_RESOURCE) for 1x1 render-target +// and depth textures, which read as a state would be INDEX_BUFFER | RENDER_TARGET (refused for a texture). The PC has +// no call that puts a resource at a caller's address, so this creates a committed DEFAULT-heap resource from the +// cleaned description (the PC flags only, slot 76's layout rule, the clear value only for a render target or depth +// texture): through ID3D12Device10::CreateCommittedResource3 with the layout as given (UNDEFINED for a buffer), or on +// an older PC device through CreateCommittedResource with the legacy state of that layout (COMMON for UNDEFINED and +// for layouts without one). The resource is not backed by the memory at va: what the title writes there does not reach +// it. Backing it needs the physical-page mapper; until then this gets the title past the call. +constexpr std::uint32_t kPcResourceFlags = 0x3FF; // D3D12_RESOURCE_FLAG_* up to USE_TIGHT_ALIGNMENT (0x200) +constexpr unsigned kPcCreateCommittedResource3Slot = 76; // ID3D12Device10's CreateCommittedResource3 + +D3D12_RESOURCE_STATES legacy_state_for_layout(std::uint32_t layout, bool buffer) { + if (buffer) return D3D12_RESOURCE_STATE_COMMON; + switch (layout) { + case 2: return D3D12_RESOURCE_STATE_RENDER_TARGET; // D3D12_BARRIER_LAYOUT_RENDER_TARGET + case 3: return D3D12_RESOURCE_STATE_UNORDERED_ACCESS; // UNORDERED_ACCESS + case 4: return D3D12_RESOURCE_STATE_DEPTH_WRITE; // DEPTH_STENCIL_WRITE + case 5: return D3D12_RESOURCE_STATE_DEPTH_READ; // DEPTH_STENCIL_READ + case 6: return D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE; // SHADER_RESOURCE + case 7: return D3D12_RESOURCE_STATE_COPY_SOURCE; // COPY_SOURCE + case 8: return D3D12_RESOURCE_STATE_COPY_DEST; // COPY_DEST + default: return D3D12_RESOURCE_STATE_COMMON; // UNDEFINED, COMMON and the rest + } +} + +HRESULT proxy_create_placed_resource_x(DeviceProxy* self, std::uint64_t va, const D3D12_RESOURCE_DESC* xbox_desc, + std::uint32_t initial_state, const D3D12_CLEAR_VALUE* clear_value, + const IID* riid, void** out) { + note_slot(133); + if (out) *out = nullptr; + if (!xbox_desc) return E_INVALIDARG; + if (!riid || !out) return E_POINTER; + + D3D12_RESOURCE_DESC pc_desc = *xbox_desc; + const auto xbox_flags = static_cast(pc_desc.Flags); + pc_desc.Flags = static_cast(xbox_flags & kPcResourceFlags); + const bool buffer = pc_desc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER; + pc_desc.Layout = buffer ? D3D12_TEXTURE_LAYOUT_ROW_MAJOR : D3D12_TEXTURE_LAYOUT_UNKNOWN; + const bool clearable = + !buffer && (pc_desc.Flags & (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL)); + + static std::atomic logged{false}; + if (first_call(logged)) + std::fprintf(stderr, + "[rt] d3d12_xs: slot 133 places a resource at a VA: dimension=%d flags=0x%x -> 0x%x, layout=0x%x; " + "created committed, not backed by the VA\n", + static_cast(pc_desc.Dimension), xbox_flags, static_cast(pc_desc.Flags), + initial_state); + (void)va; + const D3D12_HEAP_PROPERTIES heap{D3D12_HEAP_TYPE_DEFAULT, D3D12_CPU_PAGE_PROPERTY_UNKNOWN, + D3D12_MEMORY_POOL_UNKNOWN, 0, 0}; + const D3D12_CLEAR_VALUE* const clear = clearable ? clear_value : nullptr; +#ifdef __ID3D12Device10_INTERFACE_DEFINED__ + void* device10 = nullptr; + if (self->slot_count > kPcCreateCommittedResource3Slot && + SUCCEEDED(self->real->QueryInterface(__uuidof(ID3D12Device10), &device10)) && device10) { + D3D12_RESOURCE_DESC1 desc1{}; + std::memcpy(&desc1, &pc_desc, sizeof(pc_desc)); // DESC1 is DESC plus SamplerFeedbackMipRegion (zero) + const std::uint32_t layout = buffer ? 0xFFFFFFFFu : initial_state; // a buffer is created UNDEFINED + using Fn = HRESULT(WINAPI*)(void*, const D3D12_HEAP_PROPERTIES*, D3D12_HEAP_FLAGS, const D3D12_RESOURCE_DESC1*, + std::uint32_t, const D3D12_CLEAR_VALUE*, void*, UINT, const DXGI_FORMAT*, + const IID*, void**); + const auto create = + reinterpret_cast((*reinterpret_cast(device10))[kPcCreateCommittedResource3Slot]); + const HRESULT hr = create(device10, &heap, D3D12_HEAP_FLAG_NONE, &desc1, layout, clear, nullptr, 0, nullptr, + riid, out); + static_cast(device10)->Release(); + return hr; + } +#endif + return self->real->CreateCommittedResource(&heap, D3D12_HEAP_FLAG_NONE, &pc_desc, + legacy_state_for_layout(initial_state, buffer), clear, *riid, out); +} + +// The Xbox routes at their configured indices. Returns false when `slot` is none of them. Slot 70 asks too, because an +// override that moves a route onto 70 must win over the built-in 70 handler. +bool route_xbox_device_slot(DeviceProxy* self, unsigned slot, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, + std::uint64_t a4, std::uint64_t a5, std::uint64_t& result) { + const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes(); + if (slot == routes.frame_interval) { + log_xbox_route_once(slot, "SetFrameIntervalX", a1, a2, a3, a4, a5); + result = hr_to_u64(proxy_set_frame_interval_x(self, a1, a2, a3, a4)); + } else if (slot == routes.schedule_event) { + log_xbox_route_once(slot, "ScheduleFrameEventX", a1, a2, a3, a4, a5); + result = hr_to_u64(proxy_schedule_frame_event_x(self, a1, a2, a4)); + } else if (slot == routes.wait_event) { + log_xbox_route_once(slot, "WaitFrameEventX", a1, a2, a3, a4, a5); + result = hr_to_u64(proxy_wait_frame_event_x(self, a1, a2, a4, a5)); + } else if (slot == routes.queue_x) { + log_xbox_route_once(slot, "CreateCommandQueueX", a1, a2, a3, a4, a5); + result = hr_to_u64(proxy_create_command_queue_xbox(self, reinterpret_cast(a1), + reinterpret_cast(a2), + reinterpret_cast(a3))); + } else if (slot == routes.list_x) { + log_xbox_route_once(slot, "CreateCommandListX", a1, a2, a3, a4, a5); + result = hr_to_u64(proxy_create_command_list_x(self, a1, a2, a3, reinterpret_cast(a4), + reinterpret_cast(a5))); + } else { + return false; + } + return true; +} + +// Slot 74: the retail title calls it once with (pointer, u32, pointer) (kapitche, issue 7231). The PC slot 74 is +// ID3D12Device9::ShaderCacheControl(kinds, control), which reads the first word as a flags value and returns +// E_INVALIDARG, and the title then stops on an int3. The words are not measured: nothing is written through the +// pointers, the PC device is not called, and the call succeeds. +std::uint64_t proxy_slot74(std::uint64_t a1, std::uint64_t a2, std::uint64_t a3) { + static std::atomic logged{false}; + bool expected = false; + if (logged.compare_exchange_strong(expected, true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12_xs: slot 74 (pointer, u32, pointer) returns S_OK; words 0x%llx 0x%llx 0x%llx\n", + static_cast(a1), static_cast(a2), + static_cast(a3)); + return hr_to_u64(S_OK); +} + +// Xbox slot 86: CreatePipelineState(desc, riid, out), forwarded to PC ID3D12Device2::CreatePipelineState (PC slot 47). +HRESULT proxy_create_pipeline_state(DeviceProxy* self, const D3D12_PIPELINE_STATE_STREAM_DESC* desc, const IID* riid, + void** out) { + note_slot(86); + if (out) *out = nullptr; + if (self->slot_count <= 47) return refuse_beyond_device(86, self->slot_count); // predates ID3D12Device2 + if (!riid) return E_POINTER; + using Fn = HRESULT(WINAPI*)(ID3D12Device*, const D3D12_PIPELINE_STATE_STREAM_DESC*, const IID*, void**); + return reinterpret_cast(self->real_vtable[47])(self->real, desc, riid, out); +} + +// Xbox slot 101: CreateStateObject(desc, riid, out), forwarded to PC ID3D12Device5::CreateStateObject (PC slot 62, +// displaced on Xbox by compute-PSO slot 62). +HRESULT proxy_create_state_object(DeviceProxy* self, const D3D12_STATE_OBJECT_DESC* desc, const IID* riid, void** out) { + note_slot(101); + if (out) *out = nullptr; + if (self->slot_count <= 62) return refuse_beyond_device(101, self->slot_count); // predates ID3D12Device5 + if (!riid) return E_POINTER; + using Fn = HRESULT(WINAPI*)(ID3D12Device*, const D3D12_STATE_OBJECT_DESC*, const IID*, void**); + return reinterpret_cast(self->real_vtable[62])(self->real, desc, riid, out); +} + +// Xbox slot 108: GetResourceAllocationInfo2, forwarded to PC ID3D12Device8::GetResourceAllocationInfo2 (PC slot 68). +// The retail executable calls struct-returning device methods with the C ABI (return buffer in RCX, device proxy in +// RDX); a PC C++ caller passes the proxy in RCX and the return buffer in RDX. Both orders are accepted. The title's +// descriptor builder populates 56-byte D3D12_RESOURCE_DESC entries, so the input array is indexed with a 56-byte +// stride (sizeof(D3D12_RESOURCE_DESC)), each entry is expanded into a zeroed D3D12_RESOURCE_DESC1 with +// SamplerFeedbackMipRegion cleared, and Xbox layout words (e.g. 0x101, 0x105) and console flag bits above the PC +// D3D12_RESOURCE_FLAGS are normalized on the copy before the PC call. +std::uint64_t proxy_get_resource_allocation_info2(DeviceProxy* self, std::uint64_t a1, std::uint64_t a2, + std::uint64_t a3, std::uint64_t a4, std::uint64_t a5) { + note_slot(108); + DeviceProxy* proxy = nullptr; + D3D12_RESOURCE_ALLOCATION_INFO* ret = nullptr; + if (is_device_proxy(self)) { + proxy = self; + ret = reinterpret_cast(a1); + } else if (is_device_proxy(reinterpret_cast(a1))) { + proxy = reinterpret_cast(a1); + ret = reinterpret_cast(self); + } + if (!ret) return 0; + if (!proxy) { + *ret = {UINT64_MAX, 0}; + return reinterpret_cast(ret); + } + if (proxy->slot_count <= 68) { + refuse_beyond_device(108, proxy->slot_count); + *ret = {UINT64_MAX, 0}; + return reinterpret_cast(ret); + } + const auto visible_mask = static_cast(a2); + const auto count = static_cast(a3); + const auto* raw_descs = reinterpret_cast(a4); + auto* info1 = reinterpret_cast(a5); + + std::vector cleaned; + const D3D12_RESOURCE_DESC1* descs_to_pass = nullptr; + if (raw_descs && count > 0) { + try { + cleaned.resize(count); + } catch (...) { + *ret = {UINT64_MAX, 0}; + return reinterpret_cast(ret); + } + for (UINT i = 0; i < count; ++i) { + D3D12_RESOURCE_DESC1 d{}; + std::memcpy(&d, &raw_descs[i], sizeof(D3D12_RESOURCE_DESC)); + d.SamplerFeedbackMipRegion = {}; + if (static_cast(d.Layout) > + static_cast(D3D12_TEXTURE_LAYOUT_64KB_STANDARD_SWIZZLE)) { + d.Layout = d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? D3D12_TEXTURE_LAYOUT_ROW_MAJOR + : D3D12_TEXTURE_LAYOUT_UNKNOWN; + } + constexpr std::uint32_t kPcResourceFlagsMask = 0x1FFu; + d.Flags = static_cast(static_cast(d.Flags) & kPcResourceFlagsMask); + cleaned[i] = d; + } + descs_to_pass = cleaned.data(); + } + + using Fn = D3D12_RESOURCE_ALLOCATION_INFO*(WINAPI*)( + ID3D12Device*, D3D12_RESOURCE_ALLOCATION_INFO*, UINT, UINT, const D3D12_RESOURCE_DESC1*, + D3D12_RESOURCE_ALLOCATION_INFO1*); + reinterpret_cast(proxy->real_vtable[68])(proxy->real, ret, visible_mask, count, descs_to_pass, info1); + return reinterpret_cast(ret); } // Device slot 133 is the console's CreatePlacedResourceX: (va, desc, state, clear, riid, out), measured on the retail @@ -1774,6 +3499,7 @@ HRESULT proxy_create_resource(DeviceProxy* self, const D3D12_HEAP_PROPERTIES* he // ROW_MAJOR, as slot 76 does. std::atomic g_placed_at_va{nullptr}; std::atomic g_placed_at_va_pages{nullptr}; +std::atomic g_console_descriptor_heap{nullptr}; HRESULT proxy_create_placed_resource_x(DeviceProxy* self, void* va, const D3D12_RESOURCE_DESC* xbox_desc, std::uint32_t state, const IID* riid, void** out) { @@ -1836,17 +3562,8 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 return hr_to_u64(proxy_create_command_allocator(self, a1, reinterpret_cast(a2), reinterpret_cast(a3))); } else if constexpr (Slot == 12) { - note_slot(12); - a3 = unwrap_object(a3); - if (Slot >= self->slot_count) return hr_to_u64(refuse_beyond_device(12, self->slot_count)); - using CreateListFn = HRESULT(WINAPI*)(ID3D12Device*, UINT, D3D12_COMMAND_LIST_TYPE, ID3D12CommandAllocator*, - ID3D12PipelineState*, const IID*, void**); - auto fn = reinterpret_cast(self->real_vtable[12]); - return hr_to_u64(fn(self->real, static_cast(a1), static_cast(a2), - reinterpret_cast(a3), - reinterpret_cast(a4), - reinterpret_cast(a5), - reinterpret_cast(a6))); + return hr_to_u64(proxy_create_command_list(self, a1, a2, a3, a4, reinterpret_cast(a5), + reinterpret_cast(a6))); } else if constexpr (Slot == 36) { return hr_to_u64(proxy_create_fence(self, a1, a2, reinterpret_cast(a3), reinterpret_cast(a4))); @@ -1855,6 +3572,11 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 reinterpret_cast(a3))); } else if constexpr (Slot == 31 || Slot == 34 || Slot == 35 || Slot == 45 || Slot == 46 || Slot == 50) { return hr_to_u64(proxy_unwrapping_call(self, a1, a2, a3, a4, a5)); + } else if constexpr (Slot == 74) { + note_slot(Slot); + std::uint64_t routed = 0; + if (route_xbox_device_slot(self, Slot, a1, a2, a3, a4, a5, routed)) return routed; // an override moved a route here + return proxy_slot74(a1, a2, a3); } else if constexpr (Slot == 75) { return hr_to_u64(proxy_create_command_queue1(self, a1, a2, reinterpret_cast(a3), reinterpret_cast(a4))); @@ -1862,19 +3584,74 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 return hr_to_u64(proxy_create_descriptor_heap( self, reinterpret_cast(a1), reinterpret_cast(a2), reinterpret_cast(a3))); + } else if constexpr (Slot == 17) { + proxy_create_cbv(self, reinterpret_cast(a1), + D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(a2)}); + return 0; + } else if constexpr (Slot == 18) { + proxy_create_srv(self, reinterpret_cast(a1), + reinterpret_cast(a2), + D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(a3)}); + return 0; + } else if constexpr (Slot == 19) { + proxy_create_uav(self, reinterpret_cast(a1), reinterpret_cast(a2), + reinterpret_cast(a3), + D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(a4)}); + return 0; + } else if constexpr (Slot == 20) { + proxy_create_rtv(self, reinterpret_cast(a1), + reinterpret_cast(a2), + D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(a3)}); + return 0; + } else if constexpr (Slot == 21) { + proxy_create_dsv(self, reinterpret_cast(a1), + reinterpret_cast(a2), + D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(a3)}); + return 0; + } else if constexpr (Slot == 22) { + proxy_create_sampler(self, reinterpret_cast(a1), + D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(a2)}); + return 0; + } else if constexpr (Slot == 23) { + proxy_copy_descriptors(self, static_cast(a1), reinterpret_cast(a2), + reinterpret_cast(a3), static_cast(a4), + reinterpret_cast(a5), + reinterpret_cast(a6), + static_cast(static_cast(a7))); + return 0; + } else if constexpr (Slot == 24) { + proxy_copy_descriptors_simple(self, static_cast(a1), + D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(a2)}, + D3D12_CPU_DESCRIPTOR_HANDLE{static_cast(a3)}, + static_cast(static_cast(a4))); + return 0; } else if constexpr (Slot == 62) { return hr_to_u64(proxy_create_compute_pipeline_state( self, reinterpret_cast(a1), a2, a3, reinterpret_cast(a4), reinterpret_cast(a5))); + } else if constexpr (Slot == 41) { + return hr_to_u64(proxy_create_command_signature( + self, reinterpret_cast(a1), a2, reinterpret_cast(a3), + reinterpret_cast(a4))); + } else if constexpr (Slot == 61) { + proxy_create_sampler_x(self, reinterpret_cast(a1), a2); + return 0; } else if constexpr (Slot == 67) { return hr_to_u64(proxy_create_compute_pipeline_from_native_code( self, reinterpret_cast(a1), reinterpret_cast(a2), reinterpret_cast(a3))); } else if constexpr (Slot == 133) { - return hr_to_u64(proxy_create_placed_resource_x(self, reinterpret_cast(a1), - reinterpret_cast(a2), - static_cast(a3), reinterpret_cast(a5), - reinterpret_cast(a6))); + return hr_to_u64(proxy_create_placed_resource_x( + self, a1, reinterpret_cast(a2), static_cast(a3), + reinterpret_cast(a4), reinterpret_cast(a5), + reinterpret_cast(a6))); + } else if constexpr (Slot == kCreateCommittedResource3X) { + return hr_to_u64(proxy_create_committed_resource3_x(self, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10)); + } else if constexpr (Slot == 70) { + std::uint64_t routed = 0; + if (route_xbox_device_slot(self, Slot, a1, a2, a3, a4, a5, routed)) return routed; // an override moved a route here + proxy_create_srv_from_raw_x(self, a1, a2, a3); + return 0; } else if constexpr (Slot == 76) { return hr_to_u64(proxy_create_resource( self, reinterpret_cast(a1), @@ -1883,35 +3660,31 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 static_cast(static_cast(a4)), reinterpret_cast(a5), reinterpret_cast(a6), reinterpret_cast(a7))); + } else if constexpr (Slot == 86) { + return hr_to_u64(proxy_create_pipeline_state( + self, reinterpret_cast(a1), + reinterpret_cast(a2), reinterpret_cast(a3))); + } else if constexpr (Slot == 101) { + return hr_to_u64(proxy_create_state_object( + self, reinterpret_cast(a1), + reinterpret_cast(a2), reinterpret_cast(a3))); + } else if constexpr (Slot == 108) { + return proxy_get_resource_allocation_info2(self, a1, a2, a3, a4, a5); } else { + if constexpr (Slot == 26) { + // The console form has the device in RDX. A PC C++ caller has the proxy in RCX and its return buffer in + // RDX; that call goes to the forwarder below, as before. + if (is_device_proxy(reinterpret_cast(a1))) + return reinterpret_cast(proxy_get_custom_heap_properties( + reinterpret_cast(self), reinterpret_cast(a1), + static_cast(a2), static_cast(static_cast(a3)))); + } note_slot(Slot); // Xbox device slots, before the PC vtable is indexed: the public HLE's 78/79/80 would otherwise reach // CreateReservedResource2/CreateSampler2 or fall past an 80-slot table, and 48/73 would reach unrelated PC // methods. The check is before the slot-count refusal because slot 80 is outside a PC ID3D12Device11 table. - const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes(); - if (Slot == routes.frame_interval) { - log_xbox_route_once(Slot, "SetFrameIntervalX", a1, a2, a3, a4, a5); - return hr_to_u64(proxy_set_frame_interval_x(self, a1, a2, a3, a4)); - } - if (Slot == routes.schedule_event) { - log_xbox_route_once(Slot, "ScheduleFrameEventX", a1, a2, a3, a4, a5); - return hr_to_u64(proxy_schedule_frame_event_x(self, a1, a2, a4)); - } - if (Slot == routes.wait_event) { - log_xbox_route_once(Slot, "WaitFrameEventX", a1, a2, a3, a4, a5); - return hr_to_u64(proxy_wait_frame_event_x(self, a1, a2, a4, a5)); - } - if (Slot == routes.queue_x) { - log_xbox_route_once(Slot, "CreateCommandQueueX", a1, a2, a3, a4, a5); - return hr_to_u64(proxy_create_command_queue(self, reinterpret_cast(a1), - reinterpret_cast(a2), - reinterpret_cast(a3))); - } - if (Slot == routes.list_x) { - log_xbox_route_once(Slot, "CreateCommandListX", a1, a2, a3, a4, a5); - return hr_to_u64(proxy_create_command_list_x(self, a1, a2, a3, reinterpret_cast(a4), - reinterpret_cast(a5))); - } + std::uint64_t routed = 0; + if (route_xbox_device_slot(self, Slot, a1, a2, a3, a4, a5, routed)) return routed; if (Slot >= self->slot_count) return hr_to_u64(refuse_beyond_device(Slot, self->slot_count)); // The PC vtable entry, called with the PC device as `this`. Integer/pointer arguments, the hidden @@ -1930,10 +3703,140 @@ void fill_vtable(void** vtable, std::index_sequence) { ((vtable[I] = reinterpret_cast(&proxy_slot(I)>) ), ...); } +// ---- Struct-returning device methods: the console title calls them with the C ABI ---- +// +// The PC vtable (MSVC C++) takes `this` in RCX and, for a struct return, the hidden return pointer in RDX. The console +// title does not. Measured with the retail game_scarlett_master.exe 1.0.2.1 under gta6rt --run: its first +// GetCustomHeapProperties call (device slot 26) is `rcx = return buffer on the caller's stack, rdx = the device, +// r8 = node mask 1, r9 = heap type` (DEFAULT, then UPLOAD), and it reads the result from that buffer. That is the C +// convention, where a struct wider than 8 bytes comes back through a hidden *first* argument (an 8-byte one comes back +// in RAX, which is what the heap proxy's slots 9/10 already measured). The generic forwarder took the return buffer +// for the device and crashed on its vtable. +// +// The runtime's own code and tests still call the proxy through d3d12.h, in the PC form, so these thunks accept both, +// as the heap proxy's 9/10 do: whichever of the first two arguments is the device proxy (its first word is the proxy +// vtable) is `this`, and the other is the return buffer. A return buffer never starts with that vtable pointer: the +// C-form caller hands over uninitialised memory to be written, and the PC-form caller is this runtime. The buffer is +// returned in RAX, as both conventions require. +// slot 25 GetResourceAllocationInfo -> D3D12_RESOURCE_ALLOCATION_INFO (16 bytes): same rule as slot 26 (inferred, +// no call site measured yet) +// slot 26 GetCustomHeapProperties -> D3D12_HEAP_PROPERTIES (20 bytes): measured; it has its own thunk above +// (proxy_get_custom_heap_properties), not this one +// Not changed: slot 43 GetAdapterLuid (an 8-byte LUID; by the same rule the title would expect it in RAX, but no call +// site is measured yet, so it still forwards in the PC form). +void** get_vtable(); + +struct StructReturnCall { + DeviceProxy* self; + void* ret; + bool console_abi; +}; + +StructReturnCall struct_return_call(std::uint64_t a0, std::uint64_t a1) { + void** const vtable = get_vtable(); + if (a0 && *reinterpret_cast(a0) == vtable) // PC form: this, return buffer + return {reinterpret_cast(a0), reinterpret_cast(a1), false}; + return {reinterpret_cast(a1), reinterpret_cast(a0), true}; // C form: return buffer, this +} + +// The console size of a list of descriptions (d3d12_xs_alloc_size.h): the PC device's answer with every console render +// target laid out at its console size, each at its own alignment. `info` is the PC answer and is replaced only when +// the console layout is larger. `each` is the per-description array of slot 56, or null. +void apply_console_placement(const D3D12_RESOURCE_DESC* descs, UINT count, D3D12_RESOURCE_ALLOCATION_INFO& info, + D3D12_RESOURCE_ALLOCATION_INFO1* each, + const std::function& pc_one, unsigned slot) { + if (info.SizeInBytes == UINT64_MAX) return; + D3D12_RESOURCE_ALLOCATION_INFO console{}; + if (!console_placement(descs, count, pc_one, console, each)) return; + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, + "[rt] d3d12_xs: slot %u: render targets sized as console tiles, %llu B for %llu B on %u " + "description(s)\n", + slot, static_cast(console.SizeInBytes), + static_cast(info.SizeInBytes), static_cast(count)); + if (console.SizeInBytes >= info.SizeInBytes) info = console; +} + +void* WINAPI proxy_get_resource_allocation_info(std::uint64_t a0, std::uint64_t a1, std::uint64_t visible_mask, + std::uint64_t count, const D3D12_RESOURCE_DESC* descs) { + note_slot(25); + const StructReturnCall call = struct_return_call(a0, a1); + ID3D12Device* const real = call.self->real; + // Normalize console descriptors in a copy. PC calls can also pass the Xbox tiled layout explicitly. Otherwise + // their flags and layout reach the host unchanged so the host can validate them. + const UINT desc_count = static_cast(count); + std::unique_ptr clean; + if (descs && desc_count) { + clean.reset(new (std::nothrow) D3D12_RESOURCE_DESC[desc_count]); + if (!clean) { + *static_cast(call.ret) = {UINT64_MAX, D3D12_DEFAULT_RESOURCE_PLACEMENT_ALIGNMENT}; + return call.ret; + } + for (UINT i = 0; i < desc_count; ++i) { + const auto& desc = descs[i]; + clean[i] = call.console_abi || desc.Layout == kXboxTiledResourceLayout ? pc_resource_desc(desc) : desc; + static std::atomic uav_dropped{false}; + if (((static_cast(desc.Flags) & ~static_cast(clean[i].Flags)) & + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS) && + first_call(uav_dropped)) + std::fprintf(stderr, + "[rt] d3d12_xs: slot 25: depth-stencil texture (format %d) sized without unordered " + "access, which the PC refuses with it (stand-in)\n", + static_cast(desc.Format)); + } + descs = clean.get(); + } + const UINT mask = static_cast(visible_mask); + D3D12_RESOURCE_ALLOCATION_INFO info = real->GetResourceAllocationInfo(mask, desc_count, descs); + apply_console_placement(descs, desc_count, info, nullptr, + [&](UINT i) { return real->GetResourceAllocationInfo(mask, 1, &descs[i]); }, 25); + *static_cast(call.ret) = info; + return call.ret; +} + +// Slot 56, ID3D12Device4::GetResourceAllocationInfo1: the same answer, and the per-description offsets follow the +// padded sizes, so a title that places its resources at those offsets does not overlap them. The call is forwarded +// as it came; the console layout then replaces the total and the offsets. +void* WINAPI proxy_get_resource_allocation_info1(std::uint64_t a0, std::uint64_t a1, std::uint64_t visible_mask, + std::uint64_t count, const D3D12_RESOURCE_DESC* descs, + D3D12_RESOURCE_ALLOCATION_INFO1* each) { + const StructReturnCall call = struct_return_call(a0, a1); + DeviceProxy* const self = call.self; + note_slot(56); + if (56 >= self->slot_count) { + return reinterpret_cast(hr_to_u64(refuse_beyond_device(56, self->slot_count))); + } + using Fn = void*(WINAPI*)(void*, void*, UINT, UINT, const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_ALLOCATION_INFO1*); + const UINT n = static_cast(count); + // The per-resource array is optional (_Out_writes_opt_). The console total must not depend on whether the + // caller asked for it, so without one the host's per-resource answers go to a local array (found by Alpha325). + std::vector local; + if (!each && descs && n) { + try { + local.resize(n); + each = local.data(); + } catch (const std::bad_alloc&) { + each = nullptr; // the host total stands + } + } + void* const returned = reinterpret_cast(self->real_vtable[56])( + self->real, call.ret, static_cast(visible_mask), n, descs, each); + if (each) { + auto& info = *static_cast(call.ret); + apply_console_placement(descs, n, info, each, [&](UINT i) { + return D3D12_RESOURCE_ALLOCATION_INFO{each[i].SizeInBytes, each[i].Alignment}; + }, 56); + } + return returned; +} + void** get_vtable() { static void** vtable = [] { static void* storage[kMaxSlots]; fill_vtable(storage, std::make_index_sequence{}); + storage[25] = reinterpret_cast(&proxy_get_resource_allocation_info); + storage[56] = reinterpret_cast(&proxy_get_resource_allocation_info1); return storage; }(); return vtable; @@ -1981,7 +3884,9 @@ unsigned detect_slot_count(ID3D12Device* real) { } // namespace -HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out) { +IUnknown* real_object_behind_proxy(const void* object) { return proxy_real_object(object); } + +HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out, bool console_lists) { if (!real) return E_POINTER; if (!out) return E_POINTER; *out = nullptr; @@ -1992,9 +3897,11 @@ HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out) { proxy->real = real; proxy->real_vtable = *reinterpret_cast(real); proxy->slot_count = detect_slot_count(real); + proxy->console_lists = console_lists; proxy->refs.store(1, std::memory_order_relaxed); proxy->dxgi_vtable = get_dxgi_vtable(); proxy->adapter_provider = nullptr; + proxy->resource_provider = nullptr; proxy->gpu_thread_priority.store(0, std::memory_order_relaxed); proxy->max_frame_latency.store(3, std::memory_order_relaxed); @@ -2038,6 +3945,17 @@ bool set_device_adapter_provider(void* device, DxgiAdapterProvider provider) { return true; } +bool set_device_resource_provider(void* device, ResourceByVaProvider provider) { + auto* proxy = static_cast(device_proxy_primary(device)); + if (!proxy) { + std::fprintf(stderr, "[rt] d3d12_xs: set_device_resource_provider: %p is not a device proxy; no provider set\n", + device); + return false; + } + proxy->resource_provider = provider; + return true; +} + bool is_heap_proxy(const void* heap) { return heap && *reinterpret_cast(heap) == reinterpret_cast(get_heap_vtable()); } @@ -2047,6 +3965,25 @@ ID3D12DescriptorHeap* heap_proxy_real_heap(const void* heap) { return static_cast(heap)->real; } +void set_descriptor_heap_allocator(DescriptorHeapBackingAlloc alloc, DescriptorHeapBackingFree free) { + std::lock_guard lock(heap_alloc_mutex()); + g_heap_alloc = alloc; + g_heap_free = free; + g_heap_alloc_explicit = (alloc != nullptr || free != nullptr); +} + +void set_default_descriptor_heap_allocator(DescriptorHeapBackingAlloc alloc, DescriptorHeapBackingFree free) { + std::lock_guard lock(heap_alloc_mutex()); + if (g_heap_alloc_explicit) return; + g_heap_alloc = alloc; + g_heap_free = free; +} + +D3D12_CPU_DESCRIPTOR_HANDLE translate_cpu_descriptor_handle(const void* device, D3D12_CPU_DESCRIPTOR_HANDLE handle) { + const auto* proxy = is_device_proxy(device) ? static_cast(device) : nullptr; + return translate_cpu_handle(proxy, handle); +} + unsigned device_proxy_slot_count(const void* device) { if (!is_device_proxy(device)) return 0; return static_cast(device)->slot_count; @@ -2060,6 +3997,8 @@ void set_placed_at_va_pages_hook(PlacedAtVaPagesHook hook) { g_placed_at_va_pages.store(hook, std::memory_order_release); } +// MERGE NOTE: main routes slot 14's console-extended heap to this handler; this stack still serves slot 14 with the +// title-backed heaps of #7021 inside the proxy, so the handler is stored and not called yet. void set_console_descriptor_heap_handler(ConsoleDescriptorHeapHandler handler) { g_console_descriptor_heap.store(handler, std::memory_order_release); } @@ -2069,10 +4008,15 @@ ID3D12Device* device_proxy_real_device(const void* device) { return static_cast(device)->real; } +std::shared_ptr device_frame_tokens(const void* device) { + if (!is_device_proxy(device)) return nullptr; + return static_cast(device)->frame_tokens; +} + bool device_slot_overridden(unsigned slot) { - if (slot <= 2 || slot == 8 || slot == 9 || slot == 14 || slot == 31 || slot == 32 || slot == 34 || slot == 35 || - slot == 36 || slot == 45 || slot == 46 || slot == 50 || slot == 62 || slot == 67 || - slot == 75 || slot == 76 || slot == 133) + if (slot <= 2 || slot == 8 || slot == 9 || slot == 12 || slot == 14 || (slot >= 17 && slot <= 24) || slot == 25 || slot == 26 || slot == 31 || slot == 32 || + slot == 34 || slot == 35 || slot == 36 || slot == 45 || slot == 46 || slot == 50 || slot == 56 || slot == 62 || + slot == 67 || slot == 70 || slot == 75 || slot == 76 || slot == kCreateCommittedResource3X || slot == 133 || slot == 41 || slot == 61 || slot == 74 || slot == 86 || slot == 101 || slot == 108) return true; const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes(); return slot == routes.frame_interval || slot == routes.schedule_event || slot == routes.wait_event || @@ -2080,6 +4024,20 @@ bool device_slot_overridden(unsigned slot) { } bool is_queue_proxy(const void* queue) { return is_child_proxy(queue); } + +bool is_list_proxy(const void* list) { return is_list_proxy_impl(list); } + +ID3D12CommandList* list_proxy_real_list(const void* list) { + if (!is_list_proxy_impl(list)) return nullptr; + return static_cast(list)->real; +} + +const char* list_tail_slot_name(unsigned slot, unsigned char console_layout) { + return list_tail_name(slot, console_layout); +} +std::uint64_t list_slot_hits(unsigned slot) { + return slot < kListSlots ? ListStats::hits[slot].load(std::memory_order_relaxed) : 0; +} bool is_fence_proxy(const void* fence) { return is_child_proxy(fence); } bool is_allocator_proxy(const void* allocator) { return is_child_proxy(allocator); } @@ -2108,11 +4066,28 @@ unsigned fence_proxy_slot_count(const void* fence) { unsigned queue_proxy_table_size() { return kQueueSlots; } unsigned fence_proxy_table_size() { return kFenceSlots; } + +bool queue_slot_overridden(unsigned slot) { + return slot <= 2 || slot == 7 || slot == kQueueSignal || slot == kQueueWait || + slot == kQueueExecuteCommandListsX; +} unsigned allocator_proxy_table_size() { return kAllocatorSlots; } unsigned allocator_proxy_slot_count(const void* allocator) { return is_allocator_proxy(allocator) ? static_cast(allocator)->slot_count : 0; } +std::uintptr_t allocator_proxy_callback(const void* allocator) { + return is_allocator_proxy(allocator) + ? static_cast(allocator)->allocator_callback.load(std::memory_order_relaxed) + : 0; +} + +std::uintptr_t allocator_proxy_callback_context(const void* allocator) { + return is_allocator_proxy(allocator) + ? static_cast(allocator)->allocator_callback_context.load(std::memory_order_relaxed) + : 0; +} + unsigned long command_object_proxy_ref_count(const void* object) { if (!is_queue_proxy(object) && !is_fence_proxy(object) && !is_allocator_proxy(object)) return 0; return static_cast(object)->refs.load(std::memory_order_relaxed); @@ -2199,26 +4174,6 @@ bool heap_slot_first_call_seen(unsigned slot) { return slot < kHeapSlots && g_heap_first[slot].load(std::memory_order_relaxed); } -bool is_command_list_proxy(const void* list) { - return list && *reinterpret_cast(list) == reinterpret_cast(get_list_vtable()); -} - -ID3D12GraphicsCommandList* command_list_proxy_real_list(const void* list) { - if (!is_command_list_proxy(list)) return nullptr; - return static_cast(list)->real; -} - -unsigned command_list_proxy_table_size() { return kListSlots; } - -std::uint64_t list_slot_hits(unsigned slot) { - start_hit_counts(); - return slot < kListSlots ? ListStats::hits[slot].load(std::memory_order_relaxed) : 0; -} - -bool list_slot_first_call_seen(unsigned slot) { - return slot < kListSlots && ListStats::first[slot].load(std::memory_order_relaxed); -} - void reset_device_proxy_stats() { start_hit_counts(); for (unsigned slot = 0; slot < kMaxSlots; ++slot) { @@ -2230,10 +4185,6 @@ void reset_device_proxy_stats() { g_heap_hits[slot].store(0, std::memory_order_relaxed); g_heap_first[slot].store(false, std::memory_order_relaxed); } - for (unsigned slot = 0; slot < kListSlots; ++slot) { - ListStats::hits[slot].store(0, std::memory_order_relaxed); - ListStats::first[slot].store(false, std::memory_order_relaxed); - } reset_child_stats(); reset_child_stats(); reset_child_stats(); diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 20ed4afc15..f5cbc76585 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -1,20 +1,57 @@ // Xbox-ABI proxy around a PC ID3D12Device. // // Measured Xbox device deviations used here (vtable indices, x64): +// slot 26 GetCustomHeapProperties, the PC slot, but the retail executable calls it with the buffer for the +// returned struct in RCX and the device in RDX (node mask in R8, heap type in R9). A PC C++ method has +// the device in RCX and the buffer in RDX. The thunk takes the console form when RDX holds a device +// proxy, and forwards the PC form otherwise. Slots 25 and 43 return structs too and are still +// forwarded in the PC form: 25 is reported called the same way later in the boot (#6982), with console +// resource descriptions the PC method cannot take as they are, and no call of 43 has been seen. +// slot 41 CreateCommandSignature at its PC position; a console argument of type 105 (a 12-byte dispatch, read +// from the retail title's call sites) is created as D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH. +// slot 61 CreateSamplerX(desc, dest) -> PC CreateSampler (slot 22); the description's PC +// D3D12_SAMPLER_DESC prefix is passed. The PC slot 61 is CreateMetaCommand. Measured on the retail title's boot. // slot 62 CreateComputePipelineState(desc, w2, w3, iid, out): two words (0 from XboxBvhBuilder, meaning unknown) // before the IID. The PC slot 62 is CreateStateObject. // slot 67 CreateComputePipelineState from native code (desc, iid, out): converts the Xbox native-code desc // (+0x00 root signature, +0x28 code, +0x30 size) to D3D12_COMPUTE_PIPELINE_STATE_DESC and forwards // to PC CreateComputePipelineState (slot 11). The PC slot 67 is CreateProtectedResourceSession1. +// slot 70 (texture words, view desc, destination handle), no return value: a shader-resource view from raw words +// and a GPU address, with no resource (retail boot chain stop 14). The PC slot 70 is CreatePlacedResource1. +// A measured shape (PR 7066, eugen1763): a raw buffer SRV. arg1 starts with a desktop D3D12_RESOURCE_DESC +// (buffer), arg2 with a desktop D3D12_SHADER_RESOURCE_VIEW_DESC (R32_TYPELESS, BUFFER, RAW) followed at +// once by a D3D12_GPU_VIRTUAL_ADDRESS, the console VA a slot-133 call registered. When the VA is inside a +// buffer the device's resource provider knows, the destination gets a raw view of it (PC +// CreateShaderResourceView with that resource). Any other shape, or an unknown VA, gets the PC null view +// (CreateShaderResourceView with no resource) and the call returns. +// slot 74 (pointer, u32, pointer): not measured, returns S_OK. The PC slot 74 is ShaderCacheControl(kinds, control), +// which reads the first word as flags and returns E_INVALIDARG. Nothing is written, the PC device is not called. // slot 76 resource creation -> PC CreateCommittedResource (PC slot 27), with the Xbox layout word ignored. -// slot 48 CreateCommandQueueX(desc, riid, out) -> the same queue proxy as slot 8. The Xbox desc's first fields are -// D3D12_COMMAND_QUEUE_DESC's (public HLE). +// slot 26 GetCustomHeapProperties, called by the retail title with the C ABI: return buffer in RCX, the device +// in RDX (the PC form is `this` in RCX, return buffer in RDX). Slot 25 (GetResourceAllocationInfo, also a +// struct wider than 8 bytes) takes the same form by the same rule. Both accept either form. +// slot 127 CreateCommittedResource3 (heap, flags, desc1, layout, clear, session, castable count/list, riid, out) -> +// PC ID3D12Device10::CreateCommittedResource3 (PC slot 76), with the Xbox layout word replaced and the +// Xbox flag bits dropped (RT-5 stop 15, docs/retail_boot_chain.md). E_NOTIMPL when the PC device lacks it. +// slot 133 CreatePlacedResourceX(va, desc, state, clear, riid, out) -> PC CreateCommittedResource on a DEFAULT heap, +// with the Xbox flag bits dropped and an all-ones state as COMMON. Not backed by the memory at va. +// slot 48 CreateCommandQueueX(desc, riid, out) -> the same queue proxy as slot 8. The 32-byte Xbox desc starts with +// a D3D12_COMMAND_QUEUE_DESC; only that prefix is passed on, with the console-only flag bits cleared +// (DISABLE_GPU_TIMEOUT is kept). The four extra words are logged once. // slot 73 CreateCommandListX(desc, allocator, initialState, riid, out) -> PC CreateCommandList(0, type, allocator, // initialState, riid, out). The type is the first word of the Xbox desc; there is no node-mask argument // in the console call (public HLE; the PC six-argument form differs). // slots 78/79/80 SetFrameIntervalX, ScheduleFrameEventX, WaitFrameEventX. A per-device token state machine answers // them before the PC vtable is indexed; WaitFrameEventX returns at once with a fresh non-zero token. // Slot 80 is outside a PC ID3D12Device11 table, so it is checked before the beyond-table refusal. +// slot 86 CreatePipelineState(desc, riid, out) -> PC ID3D12Device2::CreatePipelineState (PC slot 47). +// slot 101 CreateStateObject(desc, riid, out) -> PC ID3D12Device5::CreateStateObject (PC slot 62, displaced on +// Xbox by compute-PSO slot 62). +// slot 108 GetResourceAllocationInfo2(ret, this, visible_mask, count, descs, info1) -> PC +// ID3D12Device8::GetResourceAllocationInfo2 (PC slot 68), accepting the console C-ABI struct return +// (return buffer in RCX, device in RDX) as well as the PC C++ order, with each 56-byte +// D3D12_RESOURCE_DESC expanded to a zero-initialized D3D12_RESOURCE_DESC1 and Xbox layout words and +// flag bits normalized on the copy. // The slots 48/73/78/79/80 are the public HLE Freminet/ScarlettX's observation, not Microsoft documentation, and can // be moved with LEONIDA_XS_QUEUE_X_SLOT, LEONIDA_XS_LIST_X_SLOT, LEONIDA_XS_FRAME_INTERVAL_SLOT, // LEONIDA_XS_SCHEDULE_EVENT_SLOT and LEONIDA_XS_WAIT_EVENT_SLOT (3..127; anything else is logged once and ignored). @@ -36,28 +73,58 @@ // Command queues and fences (device slots 8, 75, 36, and 32 for a shared fence) come back wrapped in queue and fence // proxies of the same kind: the public chain (19 queue slots, 11 or 12 fence slots in SDK 10.0.26100) is forwarded // in PC order, and a slot past it, up to the end of the proxy's table (128 queue, 64 fence slots), is logged with its -// first four argument words and refused with E_NOTIMPL. A slot past the table faults on the vtable read inside a +// first four argument words and answered S_OK on a queue or refused with E_NOTIMPL on a fence or allocator. A slot +// past the table faults on the vtable read inside a // reserved, never-committed region, and the fault is logged with the slot. That is where the console's queue methods -// (PresentX, SuspendX, ResumeX) will show up; their slots are not known and are not guessed, and that the console -// keeps the public slots is an assumption (docs/d3d12_command_objects.md §5.2). Heap, queue and fence proxies are +// (PresentX, SuspendX, ResumeX) will show up; the sibling-layer measurement puts PresentX at queue slot 30 or 32 +// and SignalX at 23 or 25 by runtime layout (docs/d3d12_xs_console_abi.md §4, unverified here). The proxy detects +// the layout from a fence reaching slot 16/17, forwards SignalX as PC Signal, routes PresentX to the presentation +// core under LEONIDA_VULKAN_DEVICE and answers the remaining console-only queue methods S_OK (frame pacing flows +// through them) without forwarding, and that +// the console keeps the public slots is an assumption (docs/d3d12_command_objects.md §5.2). Heap, queue and fence proxies are // unwrapped wherever a device or queue method hands them to the real runtime: queue Signal/Wait (14/15), device // CreateSharedHandle (31), MakeResident/Evict (34/35), SetEventOnMultipleFenceCompletion (45), SetResidencyPriority -// (46) and EnqueueMakeResident (50). Command lists are not wrapped, so ExecuteCommandLists passes them through and a -// heap proxy given to a list's SetDescriptorHeaps reaches the real list as it is. QueryInterface answers only the +// (46) and EnqueueMakeResident (50). Command lists come back from device slot 12 behind a console-shaped list +// proxy: console vtable order (PC order through slot 26, four console-only extras at 27-30, the PC chain shifted +// +4 through console 59, measured tail slots at 60/61/146), the write cursor pinned at the record limits so a +// title's inline writers always take the vtable path, unmodelled slots recorded and refused. Queue +// ExecuteCommandLists unwraps the list array; the list's own Reset, ExecuteBundle and SetDescriptorHeaps unwrap +// allocator, list and heap proxies. QueryInterface answers only the // modelled interfaces; one the real object has but the proxy does not model is logged once and refused. +// first four argument words and refused with E_NOTIMPL. Fence slot 12 is served instead: the retail executable reads +// its return as the address of the fence's 64-bit completed value, so it returns a per-fence mirror that a wait on +// the real fence keeps current (d3d12_xs_device.cpp, "Fence slot 12"). A slot past the table faults on the vtable +// read inside a reserved, never-committed region, and the fault is logged with the slot. That is where the console's +// queue methods (PresentX, SuspendX, ResumeX) will show up; their slots are not known and are not guessed, and that +// the console keeps the public slots is an assumption (docs/d3d12_command_objects.md §5.2). Heap, queue and fence +// proxies are unwrapped wherever a device or queue method hands them to the real runtime: queue Signal/Wait +// (14/15), device CreateSharedHandle (31), MakeResident/Evict (34/35), SetEventOnMultipleFenceCompletion (45), +// SetResidencyPriority (46) and EnqueueMakeResident (50). Command lists are not wrapped, so ExecuteCommandLists passes +// them through and a heap proxy given to a list's SetDescriptorHeaps reaches the real list as it is. QueryInterface +// answers only the modelled interfaces; one the real object has but the proxy does not model is logged once and +// refused. #pragma once #include #include #include +#include + +namespace leonida { +class FrameTokenSource; +} namespace rt::d3d12_xs { // Wraps `real` and returns the requested device interface through `out`. Takes ownership of one reference to // `real` on success; on failure the caller keeps its reference. Returns E_NOINTERFACE if `riid` is not a D3D12 // device interface the PC device implements. -HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out); +// `console_lists` shapes the command lists CreateCommandList returns: true (the title path) gives the +// console-shaped object the Xbox ABI calls; false hands the real list back for callers compiled against +// the PC headers (the GPU test harnesses), whose vtable indices past slot 26 do not exist in console order. +// D3D12XboxCreateDevice opts in; the default is PC-shaped so direct callers keep the old behaviour. +HRESULT create_device_proxy(ID3D12Device* real, REFIID riid, void** out, bool console_lists = false); // True when `device` points at a proxy created by create_device_proxy. Used by the tests. bool is_device_proxy(const void* device); @@ -75,6 +142,15 @@ bool is_device_proxy(const void* device); using DxgiAdapterProvider = HRESULT (*)(ID3D12Device* real, REFIID riid, void** out); // `device` is the proxy or its DXGI pointer. False, with a line on stderr, when it is neither: nothing is set then. bool set_device_adapter_provider(void* device, DxgiAdapterProvider provider); +// Finds the buffer resource that holds a console GPU virtual address, for device slot 70. `real` is the device behind +// the proxy; `bytes` is how many bytes from `va` the caller wants, so a resource that holds all of them is preferred +// over a shorter alias. Returns the resource with a reference added (the proxy releases it), or null when no resource holds +// `va`; `start` and `size` are then unused, otherwise the resource's first VA and size in bytes. +using ResourceByVaProvider = ID3D12Resource* (*)(ID3D12Device* real, std::uint64_t va, std::uint64_t bytes, + std::uint64_t* start, std::uint64_t* size); +// `device` is the proxy or its DXGI pointer. False, with a line on stderr, when it is neither. Without a provider slot +// 70 writes only the null view. +bool set_device_resource_provider(void* device, ResourceByVaProvider provider); // The device proxy an IDXGIDevice pointer handed out by one belongs to, or null. void* device_proxy_from_dxgi_device(void* dxgi_device); // The device proxy itself, given the proxy or its DXGI pointer; null for anything else. @@ -84,12 +160,31 @@ void* device_proxy_primary(void* device); bool is_heap_proxy(const void* heap); ID3D12DescriptorHeap* heap_proxy_real_heap(const void* heap); +// Console D3D12 descriptor heaps allocate their backing through XMem (allocator ID 0x80 = eXALLOCAllocatorId_D3D in +// bits 16..23, object type 4 in the low 14 bits). A title that intercepts this allocation via __XMemAllocationHooks__ +// returns its own virtual address and expects GetCPUDescriptorHandleForHeapStart() to return that address. +inline constexpr std::uint64_t kXmemDescriptorHeapAttributes = (0x80ULL << 16) | 4ULL; +using DescriptorHeapBackingAlloc = void* (*)(std::size_t byte_size, std::uint64_t attributes); +using DescriptorHeapBackingFree = void (*)(void* ptr, std::uint64_t attributes); +// Installs (or clears when both are null) the backing allocator consulted by CreateDescriptorHeap (slot 14). +void set_descriptor_heap_allocator(DescriptorHeapBackingAlloc alloc, DescriptorHeapBackingFree free); +// Installs the default bridge (used by D3D12XboxCreateDevice) only when no explicit allocator has been set. +void set_default_descriptor_heap_allocator(DescriptorHeapBackingAlloc alloc, DescriptorHeapBackingFree free); +// Translates a CPU descriptor handle from a title-backed descriptor heap to the underlying PC/Vulkan heap handle. +// Returns `handle` unchanged when it does not fall inside any active custom-backed heap. +D3D12_CPU_DESCRIPTOR_HANDLE translate_cpu_descriptor_handle(const void* device, D3D12_CPU_DESCRIPTOR_HANDLE handle); + // Number of PC vtable slots the proxy forwards (detected from the interfaces the PC device supports). unsigned device_proxy_slot_count(const void* device); // The PC device behind a proxy. Null when `device` is not a proxy. ID3D12Device* device_proxy_real_device(const void* device); +// The real object behind any of the child proxies (heap, queue, fence, allocator, and a kind added later, such as a +// console command-list proxy, which joins proxy_real_object), or null when `object` is none of them. For code outside +// this file that is handed a title's object, like the XboxBvhBuilder shim's command lists. +IUnknown* real_object_behind_proxy(const void* object); +std::shared_ptr device_frame_tokens(const void* device); // Device slot 133 (the console's CreatePlacedResourceX) makes a buffer on the title's pages at `va`. The proxy does // not create it itself: the device behind it does, through this handler, which the Vulkan layer registers // (rt::d3d12::create_buffer_at_host_address). With none registered, or a PC device behind the proxy, the slot @@ -118,10 +213,23 @@ using ConsoleDescriptorHeapHandler = HRESULT (*)(ID3D12Device* real, const D3D12 void set_console_descriptor_heap_handler(ConsoleDescriptorHeapHandler handler); // True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue +// proxies), 9 (allocator proxies), 14 (descriptor heap proxy), 17-24 (CPU descriptor handle +// translation), 26 (the console's struct-return form), 31/34/35/45/46/50 (proxies unwrapped), +// 32 and 36 (fence proxies), 48/73 and 78/79/80 (the Xbox slots above, at their configured indices), 62, 67, 70, 76 and 127. +// Slot 10 is intentionally false: the measured 9/10 handle conversion is on the heap proxy, and device slot 9 is +// CreateCommandAllocator, which the proxy handles for the allocator proxy. // proxies), 9 (allocator proxies), 14, 31/34/35/45/46/50 (proxies unwrapped), 32 and 36 (fence proxies), 48/73 and -// 78/79/80 (the Xbox slots above, at their configured indices), 62, 67 and 76. Slot 10 is intentionally false: the +// 78/79/80 (the Xbox slots above, at their configured indices), 62, 67, 74 and 76. Slot 10 is intentionally false: the // measured 9/10 handle conversion is on the heap proxy, and device slot 9 is CreateCommandAllocator, which the proxy // handles for the allocator proxy. +// 78/79/80 (the Xbox slots above, at their configured indices), 62, 67, 76, 86, 101 and 108. Slot 10 is intentionally +// false: the measured 9/10 handle conversion is on the heap proxy, and device slot 9 is CreateCommandAllocator, which +// the proxy handles for the allocator proxy. +// proxies), 9 (allocator proxies), 12 (command list proxies), 14 (descriptor heap proxy), 17-24 (CPU descriptor +// handle translation), 31/34/35/45/46/50 (proxies unwrapped), 32 and 36 (fence proxies), 48/73 and 78/79/80 (the +// Xbox slots above, at their configured indices), 62, 67 and 76. Slot 10 is intentionally false: the measured 9/10 +// handle conversion is on the heap proxy, and device slot 9 is CreateCommandAllocator, which the proxy handles for +// the allocator proxy. bool device_slot_overridden(unsigned slot); // Queue and fence proxies created by device slots 8/75 and 36. The real_* accessors return the wrapped object @@ -149,10 +257,11 @@ std::uint64_t fence_table_overruns(); // or the fault logger failed). bool command_object_tables_guarded(); -// Command allocator proxies (device slot 9): the public chain (9 slots: the base chain and Reset) is forwarded, a -// slot past it up to the end of the table (64 slots) is logged and refused with E_NOTIMPL, and a read past the -// table faults in a guard region, as for queues and fences. The console allocator's extra methods are not -// measured and not guessed. Slot 9 wraps only an allocator that answers kLeonidaCommandAllocatorTag, Leonida's +// Command allocator proxies (device slot 9): the public chain (9 slots: the base chain and Reset) is forwarded, +// slot 9 (console SetAllocatorCallbackX(callback, context, ...)) records the callback and context on the proxy and +// returns S_OK without invoking the callback on the PC/Vulkan path, slots 10..63 are logged and refused with +// E_NOTIMPL, and a read past the table faults in a guard region, as for queues and fences. Slot 9 wraps only an +// allocator that answers kLeonidaCommandAllocatorTag, Leonida's // own Vulkan-layer allocator: its command lists resolve the proxy (CreateCommandList, Reset). A PC runtime // allocator goes back unchanged, because the PC runtime's lists would take a proxy for their own allocator; a // command-list proxy that unwraps at Reset is what lets the host backend wrap allocators too. @@ -160,10 +269,27 @@ bool command_object_tables_guarded(); inline constexpr GUID kLeonidaCommandAllocatorTag{ 0x7d0e6b51, 0x34a2, 0x4f0c, {0x9a, 0x61, 0x0c, 0x5b, 0x2e, 0x8f, 0x4a, 0x10}}; bool is_allocator_proxy(const void* allocator); +// Command-list proxies (device slot 12): the console-shaped object. is_list_proxy / list_proxy_real_list give the +// same access as the queue, fence and allocator helpers; list_slot_hits counts calls per console slot. +bool is_list_proxy(const void* list); +ID3D12CommandList* list_proxy_real_list(const void* list); +std::uint64_t list_slot_hits(unsigned slot); +// The diagnostic name of a command-list slot on the list tail, where the newer console layout sits two slots later +// than the older one from CopyTextureRegionX on (docs/d3d12_xs_console_abi.md 5.3: newer->older pairs 85->83, +// 86->84, 87->85, 90->88, 91->89, 92->90, 95->93, 96->94). `console_layout` is the device-wide layout the queue +// proxy detects (kConsoleLayoutOlder or kConsoleLayoutNewer). Null when the layout is not known yet or the slot is +// not a measured tail slot of that layout, so that a slot number is never given the other layout's name. Naming +// only: no slot is forwarded because of it. +inline constexpr unsigned char kConsoleLayoutOlder = 1; +inline constexpr unsigned char kConsoleLayoutNewer = 2; +const char* list_tail_slot_name(unsigned slot, unsigned char console_layout); // The wrapped allocator (no reference added), or null when `allocator` is not an allocator proxy. ID3D12CommandAllocator* allocator_proxy_real_allocator(const void* allocator); unsigned allocator_proxy_slot_count(const void* allocator); unsigned allocator_proxy_table_size(); +// Callback and context recorded by console allocator slot 9 (SetAllocatorCallbackX), or 0 if unset / not a proxy. +std::uintptr_t allocator_proxy_callback(const void* allocator); +std::uintptr_t allocator_proxy_callback_context(const void* allocator); std::uint64_t allocator_slot_hits(unsigned slot); bool allocator_slot_first_call_seen(unsigned slot); std::uint64_t allocator_table_overruns(); diff --git a/runtime/shims/dstorage.cpp b/runtime/shims/dstorage.cpp new file mode 100644 index 0000000000..81abaea3d9 --- /dev/null +++ b/runtime/shims/dstorage.cpp @@ -0,0 +1,1125 @@ +// Xbox DirectStorage for a mapped title: DStorageGetFactory and the IDStorageFactoryX2 / IDStorageQueueX2 / +// IDStorageFileX / IDStorageStatusArrayX objects of the console API (dstorage_xs_abi.h). +// +// Served as dstorage_xs.dll, xcrdapi.dll and dstorage.dll!DStorageGetFactory; docs/directstorage.md has the evidence +// for those names, the console ABI and what each method does here. In short: +// - OpenFile resolves kernel32.dll!CreateFileW through the shim registry, so a GAME: path goes through the +// runtime's console path mapping and write overlay (file_system.cpp) exactly as the title's own CreateFileW. +// - Each queue has one worker thread that runs its submitted entries in order: a request reads a file range or +// copies a memory range into the destination, a status entry, fence signal or event runs when every entry before +// it has. Completion is therefore in queue order, as the API guarantees. +// - A zlib request (ZlibDecompress alone) reads its source into a staging buffer, inflates it on the worker with +// the runtime's RFC 1950 inflater (leonida::zlib_inflate, src/shader_library.h) and copies the result to the +// destination only when it is exactly DestinationSize bytes; a stream that fails leaves the destination as it was. +// - BCPack, swizzle and physical-page requests fail with E_NOTIMPL for now (later PRs: they become stages between +// the read and the destination write, BCPack after the inflate). +// Nothing here goes online or touches the GPU. +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "../src/shader_library.h" // leonida::zlib_inflate +#include "dstorage_xs_abi.h" +#include "shims.h" + +using namespace dsx; + +namespace { + +// ---- Logging ------------------------------------------------------------------------------------------------------ + +// Process-lifetime state is allocated once and never freed: a worker thread may still run while statics are destroyed +// at exit. +std::mutex& log_mutex() { + static auto* m = new std::mutex; + return *m; +} + +void log_once(const std::string& key, const std::string& line) { + static auto* seen = new std::set; + std::lock_guard lock(log_mutex()); + if (!seen->insert(key).second) return; + std::fprintf(stderr, "[rt] dstorage: %s\n", line.c_str()); +} + +std::string guid_text(const GUID& g) { + char b[48]; + std::snprintf(b, sizeof b, "{%08lx-%04x-%04x-%02x%02x-%02x%02x%02x%02x%02x%02x}", g.Data1, g.Data2, g.Data3, + g.Data4[0], g.Data4[1], g.Data4[2], g.Data4[3], g.Data4[4], g.Data4[5], g.Data4[6], g.Data4[7]); + return b; +} + +bool same_guid(const GUID& a, const GUID& b) { return std::memcmp(&a, &b, sizeof(GUID)) == 0; } + +std::string hr_text(HRESULT hr) { + char b[16]; + std::snprintf(b, sizeof b, "0x%08lx", static_cast(hr)); + return b; +} + +// ---- Interface ids ------------------------------------------------------------------------------------------------ +// +// The X interfaces' ids are not public. A creating call (DStorageGetFactory, CreateQueue*, OpenFile, +// CreateStatusArray) accepts an id it has not seen for the kind of object it hands out and logs it the first time, so +// the first boot records the console's ids. It refuses an id seen for another kind, a PC DirectStorage id of another +// shape, and the system COM interfaces (IMarshal, IAgileObject, ...), which a DirectStorage object never implements. +// QueryInterface is stricter (docs/d3d12_vulkan.md: an unknown id is E_NOINTERFACE): it accepts IUnknown, the +// declared ids (dstorage_xs_abi.h) and the ids a creating call accepted for that kind, and logs anything else. This is +// a policy, not a fact; it lives here so a measured id list can replace it. + +enum class Kind { Factory, Queue, File, StatusArray }; + +const char* kind_name(Kind k) { + switch (k) { + case Kind::Factory: return "factory"; + case Kind::Queue: return "queue"; + case Kind::File: return "file"; + case Kind::StatusArray: return "status array"; + } + return "?"; +} + +// System interfaces: the COM base range {xxxxxxxx-0000-0000-C000-000000000046} (IClassFactory, IMarshal, +// IStdMarshalInfo, IExternalConnection, IMultiQI, IClientSecurity, IServerSecurity, IRpcOptions, IMarshal2, +// IWeakReferenceSource, IDispatch, IPersist, ...) and these others. +constexpr GUID kSystemInterfaceIds[] = { + {0x94ea2b94, 0xe9cc, 0x49e0, {0xc0, 0xff, 0xee, 0x64, 0xca, 0x8f, 0x5b, 0x90}}, // IAgileObject + {0xecc8691b, 0xc1db, 0x4dc0, {0x85, 0x5e, 0x65, 0xf6, 0xc5, 0x51, 0xaf, 0x49}}, // INoMarshal + {0x1c733a30, 0x2a1c, 0x11ce, {0xad, 0xe5, 0x00, 0xaa, 0x00, 0x44, 0x77, 0x3d}}, // ICallFactory + {0xaf86e2e0, 0xb12d, 0x4c6a, {0x9c, 0x5a, 0xd7, 0xaa, 0x65, 0x10, 0x1e, 0x90}}, // IInspectable + {0xdf0b3d60, 0x548f, 0x101b, {0x8e, 0x65, 0x08, 0x00, 0x2b, 0x2b, 0xd1, 0x19}}, // ISupportErrorInfo + {0xb196b283, 0xbab4, 0x101a, {0xb6, 0x9c, 0x00, 0xaa, 0x00, 0x34, 0x1d, 0x07}}, // IProvideClassInfo + {0xb196b284, 0xbab4, 0x101a, {0xb6, 0x9c, 0x00, 0xaa, 0x00, 0x34, 0x1d, 0x07}}, // IConnectionPointContainer + {0xfc4801a3, 0x2ba9, 0x11cf, {0xa2, 0x29, 0x00, 0xaa, 0x00, 0x3d, 0x73, 0x52}}, // IObjectWithSite +}; + +bool system_interface(const GUID& g) { + static const uint8_t kComBase[8] = {0xc0, 0, 0, 0, 0, 0, 0, 0x46}; + if (g.Data2 == 0 && g.Data3 == 0 && std::memcmp(g.Data4, kComBase, 8) == 0) return true; + for (const GUID& s : kSystemInterfaceIds) + if (same_guid(g, s)) return true; + return false; +} + +// The ids declared for a kind: the PC IDStorageStatusArray id, whose interface has the console one's shape (console +// D3D12 binaries reuse the PC SDK's ids). No other X interface id is known. +bool declared(const GUID& g, Kind kind) { + for (const GUID& id : kStatusArrayIds) + if (same_guid(g, id)) return kind == Kind::StatusArray; + return false; +} + +bool declared_for_any(const GUID& g) { + for (const GUID& id : kStatusArrayIds) + if (same_guid(g, id)) return true; + return false; +} + +class IidPolicy { +public: + bool accept_creating(REFIID riid, Kind kind, const char* caller) { + if (same_guid(riid, __uuidof(IUnknown)) || declared(riid, kind)) return true; + if (system_interface(riid)) return refuse(riid, caller, "a system COM interface"); + if (declared_for_any(riid)) return refuse(riid, caller, "an id declared for another kind of object"); + for (const GUID& pc : kPcInterfaceIds) + if (same_guid(riid, pc)) + return refuse(riid, caller, "a PC DirectStorage interface; only the console ABI is served"); + std::lock_guard lock(mutex_); + for (const auto& [id, k] : learned_) + if (same_guid(id, riid)) { + if (k == kind) return true; + return refuse(riid, caller, std::string("seen before as a ") + kind_name(k) + " interface"); + } + learned_.push_back({riid, kind}); + log_once("learn" + guid_text(riid), std::string(caller) + " asked for " + guid_text(riid) + ": serving the " + + kind_name(kind) + " interface"); + return true; + } + + bool accept_query(REFIID riid, Kind kind, const char* caller) { + if (same_guid(riid, __uuidof(IUnknown)) || declared(riid, kind)) return true; + { + std::lock_guard lock(mutex_); + for (const auto& [id, k] : learned_) + if (same_guid(id, riid) && k == kind) return true; + } + return refuse(riid, caller, std::string("not an id a ") + kind_name(kind) + " was created with"); + } + +private: + static bool refuse(REFIID riid, const char* caller, const std::string& why) { + log_once(std::string("refuse") + caller + guid_text(riid), + std::string(caller) + " asked for " + guid_text(riid) + ": " + why + " (E_NOINTERFACE)"); + return false; + } + + std::mutex mutex_; + std::vector> learned_; +}; + +IidPolicy& iid_policy() { + static auto* p = new IidPolicy; + return *p; +} + +// A bad argument to a factory or queue method, logged once per method and kind: a wrong vtable guess for the console +// interfaces would show up here first, as arguments that make no sense for the method. +HRESULT bad_call(const char* method, HRESULT hr, const char* what) { + log_once(std::string("bad") + method + what, + std::string(method) + ": " + what + " (" + hr_text(hr) + + "; logged once; a wrong vtable slot guess would show up like this)"); + return hr; +} + +// ---- Statistics (IDStorageFactoryX1::GetStats) -------------------------------------------------------------------- + +struct Stats { + std::mutex mutex; + DSTORAGE_STATS s{}; + uint32_t live_queues = 0; // all priorities; SetStagingBufferSize is refused while queues or files exist +}; + +Stats& stats() { + static auto* s = new Stats; + return *s; +} + +DSTORAGE_PRIORITY_STATS& priority_stats(DSTORAGE_STATS& s, DSTORAGE_PRIORITY p) { + switch (p) { + case DSTORAGE_PRIORITY_LOW: return s.LowPriorityStats; + case DSTORAGE_PRIORITY_HIGH: return s.HighPriorityStats; + case DSTORAGE_PRIORITY_REALTIME: return s.RealtimePriorityStats; + default: return s.NormalPriorityStats; + } +} + +void count_error() { + std::lock_guard lock(stats().mutex); + ++stats().s.ErrorCount; +} + +// ---- Live objects --------------------------------------------------------------------------------------------------- +// +// A request names its file and a status entry its array by pointer. Only objects this shim made and that are still +// alive are used; anything else is an error in the request, never a call through a stranger's vtable. + +std::mutex& live_mutex() { + static auto* m = new std::mutex; + return *m; +} +// One set per kind, so a status array passed as a file (or the other way round) is not found. +std::unordered_set& live_files() { + static auto* s = new std::unordered_set; + return *s; +} +std::unordered_set& live_status_arrays() { + static auto* s = new std::unordered_set; + return *s; +} + +// AddRef only if the count has not reached zero (an object being released is not revived). +bool add_ref_if_live(std::atomic& refs) { + ULONG r = refs.load(); + while (r != 0) + if (refs.compare_exchange_weak(r, r + 1)) return true; + return false; +} + +// ---- Status arrays ------------------------------------------------------------------------------------------------ + +class StatusArray final : public IDStorageStatusArrayX { +public: + StatusArray(uint32_t capacity, std::unique_ptr[]> entries) + : capacity_(capacity), entries_(std::move(entries)) { + for (uint32_t i = 0; i < capacity_; ++i) entries_[i].store(S_OK, std::memory_order_relaxed); + std::lock_guard lock(live_mutex()); + live_status_arrays().insert(static_cast(this)); + } + + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override { + if (!ppv) return E_POINTER; + *ppv = nullptr; + if (!iid_policy().accept_query(riid, Kind::StatusArray, "IDStorageStatusArrayX::QueryInterface")) + return E_NOINTERFACE; + AddRef(); + *ppv = static_cast(this); + return S_OK; + } + ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } + ULONG STDMETHODCALLTYPE Release() override { + ULONG r; + { + std::lock_guard lock(live_mutex()); + r = --refs_; + if (r == 0) live_status_arrays().erase(static_cast(this)); + } + if (r == 0) delete this; + return r; + } + + // IsComplete is GetHResult(index) != E_PENDING (the reference says so); an index past the array is not pending. + bool STDMETHODCALLTYPE IsComplete(UINT32 index) override { return GetHResult(index) != E_PENDING; } + HRESULT STDMETHODCALLTYPE GetHResult(UINT32 index) override { + if (index >= capacity_) return E_DSTORAGE_INDEX_BOUND; + return entries_[index].load(std::memory_order_acquire); + } + + uint32_t capacity() const { return capacity_; } + void set_pending(uint32_t index) { entries_[index].store(E_PENDING, std::memory_order_release); } + void complete(uint32_t index, HRESULT hr) { entries_[index].store(hr, std::memory_order_release); } + std::atomic& refs() { return refs_; } + +private: + std::atomic refs_{1}; + const uint32_t capacity_; + std::unique_ptr[]> entries_; +}; + +// ---- Files -------------------------------------------------------------------------------------------------------- + +class File final : public IDStorageFileX { +public: + File(HANDLE handle, std::wstring path) : handle_(handle), path_(std::move(path)) { + { + std::lock_guard lock(live_mutex()); + live_files().insert(static_cast(this)); + } + std::lock_guard lock(stats().mutex); + auto& s = stats().s; + ++s.CurrentOpenFileCount; + ++s.CumulativeOpenFileCount; + s.MaxOpenFileCount = std::max(s.MaxOpenFileCount, s.CurrentOpenFileCount); + } + ~File() { + Close(); + std::lock_guard lock(stats().mutex); + --stats().s.CurrentOpenFileCount; + } + + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override { + if (!ppv) return E_POINTER; + *ppv = nullptr; + if (!iid_policy().accept_query(riid, Kind::File, "IDStorageFileX::QueryInterface")) return E_NOINTERFACE; + AddRef(); + *ppv = static_cast(this); + return S_OK; + } + ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } + ULONG STDMETHODCALLTYPE Release() override { + ULONG r; + { + std::lock_guard lock(live_mutex()); + r = --refs_; + if (r == 0) live_files().erase(static_cast(this)); + } + if (r == 0) delete this; + return r; + } + + // Waits for the submitted requests that read this file, then closes the handle. A request submitted later fails + // with E_DSTORAGE_FILE_NOT_OPEN. Waiting only for submitted requests keeps a Close from blocking forever on a + // request that sits unsubmitted in a queue with auto-submit disabled. + void STDMETHODCALLTYPE Close() override { + std::unique_lock lock(mutex_); + closed_ = true; + idle_.wait(lock, [&] { return pending_ == 0; }); + if (handle_ != INVALID_HANDLE_VALUE) { + CloseHandle(handle_); + handle_ = INVALID_HANDLE_VALUE; + } + } + + // A new handle the caller closes (GENERIC_READ, FILE_SHARE_READ, as the reference describes it). ReOpenFile, + // not DuplicateHandle: a duplicate shares the file position with the shim's own reads, so the title's ReadFile + // through it would start wherever the worker's last read ended. + HANDLE STDMETHODCALLTYPE GetHandle() override { + std::lock_guard lock(mutex_); + if (closed_ || handle_ == INVALID_HANDLE_VALUE) { + SetLastError(ERROR_INVALID_HANDLE); + return INVALID_HANDLE_VALUE; + } + return ReOpenFile(handle_, GENERIC_READ, FILE_SHARE_READ, 0); + } + + // Called when a request naming this file is submitted. False once the file is closed. + bool add_pending() { + std::lock_guard lock(mutex_); + if (closed_) return false; + ++pending_; + return true; + } + void finish_pending() { + std::lock_guard lock(mutex_); + if (--pending_ == 0) idle_.notify_all(); + } + // Valid while the caller holds a pending count: Close does not close the handle before it drops to zero. + HANDLE handle() const { return handle_; } + const std::wstring& path() const { return path_; } + std::atomic& refs() { return refs_; } + +private: + std::atomic refs_{1}; + std::mutex mutex_; + std::condition_variable idle_; + HANDLE handle_; + const std::wstring path_; + uint32_t pending_ = 0; + bool closed_ = false; +}; + +StatusArray* live_status_array(IDStorageStatusArrayX* p) { + std::lock_guard lock(live_mutex()); + if (!p || !live_status_arrays().count(p)) return nullptr; + auto* a = static_cast(p); + return add_ref_if_live(a->refs()) ? a : nullptr; +} + +File* live_file(IDStorageFileX* p) { + std::lock_guard lock(live_mutex()); + if (!p || !live_files().count(p)) return nullptr; + auto* f = static_cast(p); + return add_ref_if_live(f->refs()) ? f : nullptr; +} + +// ---- Reads -------------------------------------------------------------------------------------------------------- + +// memmove that turns an access violation into an error instead of ending the process. No C++ objects here: a +// function with __try cannot have any that need unwinding. +bool guarded_move(void* destination, const void* source, size_t size) { + __try { + std::memmove(destination, source, size); + return true; + } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER + : EXCEPTION_CONTINUE_SEARCH) { + return false; + } +} + +HRESULT read_error(DWORD error) { + switch (error) { + case ERROR_NOACCESS: + case ERROR_INVALID_USER_BUFFER: return E_DSTORAGE_ACCESS_VIOLATION; + case ERROR_HANDLE_EOF: return E_DSTORAGE_END_OF_FILE; + default: return HRESULT_FROM_WIN32(error); + } +} + +// Reads exactly "size" bytes at "offset" of a synchronous handle into "destination". +HRESULT read_file_range(HANDLE handle, uint64_t offset, void* destination, uint32_t size) { + LARGE_INTEGER length{}; + if (!GetFileSizeEx(handle, &length)) return HRESULT_FROM_WIN32(GetLastError()); + const uint64_t file_size = static_cast(length.QuadPart); + if (offset > file_size || size > file_size - offset) return E_DSTORAGE_END_OF_FILE; + auto* out = static_cast(destination); + uint32_t done = 0; + while (done < size) { + OVERLAPPED at{}; + const uint64_t position = offset + done; + at.Offset = static_cast(position); + at.OffsetHigh = static_cast(position >> 32); + DWORD got = 0; + if (!ReadFile(handle, out + done, size - done, &got, &at)) return read_error(GetLastError()); + if (got == 0) return E_DSTORAGE_END_OF_FILE; // the file shrank since the size check + done += got; + } + return S_OK; +} + +// ---- Queues ------------------------------------------------------------------------------------------------------- + +struct Entry { + enum class Type { Request, Status, Signal, Event } type = Type::Request; + DSTORAGE_REQUEST request{}; + File* file = nullptr; // a reference, for a file request naming a live file + bool file_counted = false; // the file's pending count was raised at submit + bool cancelled = false; // CancelRequestsWithTag matched it before it started + bool counted = false; // a request the title passed: counted in the statistics when it is submitted + HRESULT enqueue_error = S_OK; // found at enqueue: reported when the entry is reached, in order + StatusArray* status = nullptr; // a reference + IDStorageStatusArrayX* status_as_given = nullptr; + uint32_t index = 0; + ID3D12Fence* fence = nullptr; // a reference + uint64_t value = 0; + HANDLE event = nullptr; // a duplicate the entry owns +}; + +class Queue final : public IDStorageQueueX2 { +public: + explicit Queue(const DSTORAGE_QUEUE_DESC1& desc) : desc_(desc) { + error_event_ = CreateEventW(nullptr, TRUE, FALSE, nullptr); + clear_record_locked(); + std::lock_guard lock(stats().mutex); + auto& p = priority_stats(stats().s, desc_.Priority); + ++p.CurrentQueueCount; + ++p.CumulativeQueueCount; + p.MaxQueueCount = std::max(p.MaxQueueCount, p.CurrentQueueCount); + ++stats().live_queues; + } + // Separate from the constructor so a failure to start the thread can be reported. + bool start() { + if (!error_event_) return false; + try { + worker_ = std::thread([this] { run(); }); + } catch (...) { + return false; + } + return true; + } + ~Queue() { + Close(); + if (error_event_) CloseHandle(error_event_); + std::lock_guard lock(stats().mutex); + --priority_stats(stats().s, desc_.Priority).CurrentQueueCount; + --stats().live_queues; + } + + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override { + if (!ppv) return E_POINTER; + *ppv = nullptr; + if (!iid_policy().accept_query(riid, Kind::Queue, "IDStorageQueueX::QueryInterface")) return E_NOINTERFACE; + AddRef(); + *ppv = static_cast(this); + return S_OK; + } + ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } + // The last Release closes the queue, which runs everything enqueued first. + ULONG STDMETHODCALLTYPE Release() override { + const ULONG r = --refs_; + if (r == 0) delete this; + return r; + } + + void STDMETHODCALLTYPE EnqueueRequest(const DSTORAGE_REQUEST* request) override { + Entry e; + e.type = Entry::Type::Request; + if (!request) { + e.enqueue_error = bad_call("IDStorageQueueX::EnqueueRequest", E_INVALIDARG, "null request"); + } else { + e.request = *request; // the title may reuse its structure as soon as this returns + const uint64_t o = e.request.Options.AsUINT64; + if (options::source_type(o) == DSTORAGE_REQUEST_SOURCE_FILE && + desc_.SourceType == DSTORAGE_REQUEST_SOURCE_FILE && e.request.File) { + e.file = live_file(e.request.File); + if (!e.file) e.enqueue_error = E_DSTORAGE_INVALID_FILE_HANDLE; + } + e.counted = true; // TotalRequestCount is "submitted requests" (DSTORAGE_PRIORITY_STATS): see submit_locked + } + enqueue(std::move(e)); + } + + void STDMETHODCALLTYPE EnqueueStatus(IDStorageStatusArrayX* status_array, UINT32 index) override { + Entry e; + e.type = Entry::Type::Status; + e.status_as_given = status_array; + e.index = index; + e.status = live_status_array(status_array); + if (!e.status) { + e.enqueue_error = E_DSTORAGE_INVALID_STATUS_ARRAY; + } else if (index >= e.status->capacity()) { + e.enqueue_error = E_DSTORAGE_INDEX_BOUND; + } else { + e.status->set_pending(index); // polling after this call sees E_PENDING until the entry is reached + } + { + std::lock_guard lock(stats().mutex); + ++priority_stats(stats().s, desc_.Priority).TotalStatusCount; + } + enqueue(std::move(e)); + } + + void STDMETHODCALLTYPE EnqueueSignal(ID3D12Fence* fence, UINT64 value) override { + Entry e; + e.type = Entry::Type::Signal; + e.fence = fence; + e.value = value; + if (fence) { + fence->AddRef(); + } else { + e.enqueue_error = E_DSTORAGE_INVALID_FENCE; + } + { + std::lock_guard lock(stats().mutex); + ++priority_stats(stats().s, desc_.Priority).TotalFenceCount; + } + enqueue(std::move(e)); + } + + // The handle is duplicated here and the duplicate closed once it has been set (or dropped), so an event the + // title closes, and whose handle value is then reused for another object, is never the one set. + void STDMETHODCALLTYPE EnqueueSetEvent(HANDLE handle) override { + Entry e; + e.type = Entry::Type::Event; + if (!handle) { + e.enqueue_error = bad_call("IDStorageQueueX1::EnqueueSetEvent", HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE), + "null event handle"); + } else if (!DuplicateHandle(GetCurrentProcess(), handle, GetCurrentProcess(), &e.event, 0, FALSE, + DUPLICATE_SAME_ACCESS)) { + e.event = nullptr; + e.enqueue_error = HRESULT_FROM_WIN32(GetLastError()); + } + enqueue(std::move(e)); + } + + void STDMETHODCALLTYPE Submit() override { + std::lock_guard lock(mutex_); + submit_locked(); + } + + // Marks the requests enqueued before this call that have not started. A cancelled request completes as a success + // without being read (the overview: the title may no longer use its result). + void STDMETHODCALLTYPE CancelRequestsWithTag(UINT64 mask, UINT64 value) override { + std::lock_guard lock(mutex_); + for (Entry& e : entries_) + if (e.type == Entry::Type::Request && (e.request.CancellationTag & mask) == value) e.cancelled = true; + } + + // Submits what is enqueued, waits until the worker has run all of it and stops the worker. Later enqueues are + // dropped and recorded as E_DSTORAGE_QUEUE_CLOSED. + void STDMETHODCALLTYPE Close() override { + std::lock_guard close_lock(close_mutex_); + { + std::unique_lock lock(mutex_); + if (closed_) return; + closing_ = true; + submit_locked(); + space_.notify_all(); // an enqueue waiting for space gives up (the queue is closing) + idle_.wait(lock, [&] { return entries_.empty() && !in_flight_; }); + closed_ = true; + work_.notify_all(); + } + if (worker_.joinable()) worker_.join(); + } + + HANDLE STDMETHODCALLTYPE GetErrorEvent() override { + HANDLE dup = nullptr; + if (!error_event_ || !DuplicateHandle(GetCurrentProcess(), error_event_, GetCurrentProcess(), &dup, 0, FALSE, + DUPLICATE_SAME_ACCESS)) + return nullptr; + return dup; // the reference says the title closes it + } + + void STDMETHODCALLTYPE RetrieveErrorRecord(DSTORAGE_ERROR_RECORD* record) override { + if (!record) { + bad_call("IDStorageQueueX::RetrieveErrorRecord", E_POINTER, "null record"); + return; + } + std::lock_guard lock(error_mutex_); + *record = record_; + clear_record_locked(); + if (error_event_) ResetEvent(error_event_); + } + + void STDMETHODCALLTYPE Query(DSTORAGE_QUEUE_INFO* info) override { + if (!info) { + bad_call("IDStorageQueueX::Query", E_POINTER, "null info"); + return; + } + DSTORAGE_QUEUE_INFO1 full{}; + Query1(&full); + info->Desc.SourceType = full.Desc.SourceType; + info->Desc.Capacity = full.Desc.Capacity; + info->Desc.Priority = full.Desc.Priority; + info->Desc.Name = full.Desc.Name; + info->EmptySlotCount = full.EmptySlotCount; + info->RequestCountUntilAutoSubmit = full.RequestCountUntilAutoSubmit; + } + + // An empty queue has capacity - 1 empty slots (one slot tells empty from full). The automatic submit happens when + // the entries enqueued since the last submit reach half the capacity; with it disabled the count is 0. + void STDMETHODCALLTYPE Query1(DSTORAGE_QUEUE_INFO1* info) override { + if (!info) { + bad_call("IDStorageQueueX2::Query1", E_POINTER, "null info"); + return; + } + std::lock_guard lock(mutex_); + info->Desc = desc_; + info->EmptySlotCount = static_cast(usable() - used_locked()); + const size_t unsubmitted = entries_.size() - submitted_; + info->RequestCountUntilAutoSubmit = + auto_submit() ? static_cast(half() > unsubmitted ? half() - unsubmitted : 0) : 0; + } + +private: + size_t usable() const { return desc_.Capacity - 1u; } + size_t half() const { return desc_.Capacity / 2u; } + bool auto_submit() const { return !desc_.Options.AutoSubmitDisabled; } + size_t used_locked() const { return entries_.size() + (in_flight_ ? 1 : 0); } + + void enqueue(Entry&& e) { + { + std::unique_lock lock(mutex_); + // A full queue waits for the worker to free a slot. With auto-submit on, half the queue is always + // submitted by then; with it off, only a Submit from another thread frees one (as the reference warns). + space_.wait(lock, [&] { return closing_ || used_locked() < usable(); }); + if (!closing_) { + entries_.push_back(std::move(e)); + if (auto_submit() && entries_.size() - submitted_ >= half()) submit_locked(); + return; + } + } + DSTORAGE_ERROR_FIRST_FAILURE f{}; + f.HResult = E_DSTORAGE_QUEUE_CLOSED; + describe(e, f); + record_failure(f); + log_once("closed", "an entry was enqueued on a closed queue (E_DSTORAGE_QUEUE_CLOSED); it never completes"); + release_references(e); + } + + void submit_locked() { + uint32_t requests = 0; + uint64_t source_bytes = 0, destination_bytes = 0; + for (size_t i = submitted_; i < entries_.size(); ++i) { + Entry& e = entries_[i]; + if (e.file) e.file_counted = e.file->add_pending(); + if (e.counted) { + ++requests; + source_bytes += e.request.SourceSize; + destination_bytes += e.request.DestinationSize; + } + } + if (requests) { + std::lock_guard stats_lock(stats().mutex); + auto& p = priority_stats(stats().s, desc_.Priority); + p.TotalRequestCount += requests; + p.TotalRequestSourceByteCount += source_bytes; + p.TotalRequestDestinationByteCount += destination_bytes; + } + if (entries_.size() > submitted_) { + submitted_ = entries_.size(); + work_.notify_one(); + } + } + + void run() { + for (;;) { + Entry e; + { + std::unique_lock lock(mutex_); + work_.wait(lock, [&] { return submitted_ > 0 || closed_; }); + if (submitted_ == 0) return; // closed and drained + e = std::move(entries_.front()); + entries_.pop_front(); + --submitted_; + in_flight_ = true; + } + process(e); + release_references(e); + { + std::lock_guard lock(mutex_); + in_flight_ = false; + space_.notify_all(); + if (entries_.empty()) idle_.notify_all(); + } + } + } + + // Runs on the worker. since_notify_ is the first failure since the last status entry or fence signal: the + // HRESULT a status entry reports. + void process(Entry& e) { + HRESULT hr = e.enqueue_error; + switch (e.type) { + case Entry::Type::Request: + // A cancelled request is a success whatever else is wrong with it (the GDK: not counted as a failure). + if (e.cancelled) { + hr = S_OK; + } else if (SUCCEEDED(hr)) { + // Pending: processing has started and not completed (DSTORAGE_PRIORITY_STATS). + set_pending(+1); + hr = execute_request(e); + set_pending(-1); + } + if (e.file && e.file_counted) e.file->finish_pending(); + if (FAILED(hr) && SUCCEEDED(since_notify_)) since_notify_ = hr; + break; + case Entry::Type::Status: + if (SUCCEEDED(hr)) { + e.status->complete(e.index, since_notify_); + since_notify_ = S_OK; + } + break; + case Entry::Type::Signal: + if (SUCCEEDED(hr)) hr = e.fence->Signal(e.value); + since_notify_ = S_OK; + break; + case Entry::Type::Event: + if (SUCCEEDED(hr) && !SetEvent(e.event)) hr = HRESULT_FROM_WIN32(GetLastError()); + break; + } + if (FAILED(hr)) { + DSTORAGE_ERROR_FIRST_FAILURE f{}; + f.HResult = hr; + describe(e, f); + record_failure(f); + } + } + + HRESULT execute_request(const Entry& e) { + const DSTORAGE_REQUEST& r = e.request; + const uint64_t o = r.Options.AsUINT64; + if (o & options::kReservedMask) return E_DSTORAGE_RESERVED_FIELDS; + if (options::source_type(o) != desc_.SourceType) return E_DSTORAGE_INVALID_SOURCE_TYPE; + if (options::bcpack(o) > DSTORAGE_BCPACK_MODE_BC7) return E_DSTORAGE_INVALID_BCPACK_MODE; + if (options::swizzle(o) > DSTORAGE_SWIZZLE_MODE_4K_12K_4K_12K) return E_DSTORAGE_INVALID_SWIZZLE_MODE; + if (options::bcpack(o) != 0 || options::swizzle(o) != 0) { + log_once("decompress", "BCPack and swizzle requests are not implemented yet (E_NOTIMPL)"); + return E_NOTIMPL; + } + if (o & (options::kDestinationPages | options::kSourcePages)) { + log_once("pages", "physical-page requests are not implemented yet (E_NOTIMPL)"); + return E_NOTIMPL; + } + const bool zlib = options::zlib(o); + // IntermediateSize is the BCPack data's size between the inflate and the BCPack decode (DSTORAGE_REQUEST), so + // it is 0 for every request that gets here (BCPack is refused above). + if (r.IntermediateSize != 0) return E_DSTORAGE_INVALID_INTERMEDIATE_SIZE; + // E_DSTORAGE_INVALID_DESTINATION_SIZE: without decompression DestinationSize must equal the source's length, + // with it it must be larger (dstorageerr.h's description; DSTORAGE_REQUEST says the same of DestinationSize). + if (zlib ? r.DestinationSize <= r.SourceSize : r.DestinationSize != r.SourceSize) + return E_DSTORAGE_INVALID_DESTINATION_SIZE; + const bool memory = desc_.SourceType == DSTORAGE_REQUEST_SOURCE_MEMORY; + const uint64_t total = static_cast(r.DestinationSize) + (memory ? r.SourceSize : 0u); + if (total > kMaxRequestBytes) return E_DSTORAGE_REQUEST_TOO_LARGE; + // DSTORAGE_REQUEST: a buffer over 32 MiB is allowed only with 64 KiB or 2 MiB pages, which are not implemented + // yet (refused above). The source is never larger than the destination here (the same size without zlib, + // smaller with it), so this covers both buffers, and bounds the staging buffers of a zlib request too. + if (r.DestinationSize > kMax4kPageDestinationSize) return E_DSTORAGE_REQUEST_TOO_LARGE; + // DSTORAGE_REQUEST: with ZlibDecompress the file offset must be 16-byte aligned. + if (zlib && !memory && r.FileOffset % 16 != 0) return E_DSTORAGE_INVALID_FILE_OFFSET; + if (!r.Destination) return E_INVALIDARG; + if (memory) { + if (!r.Source) return E_INVALIDARG; + } else { + if (!r.File) return E_INVALIDARG; + if (!e.file_counted) return E_DSTORAGE_FILE_NOT_OPEN; + } + if (zlib) return inflate_request(e, memory); + if (r.SourceSize == 0) return S_OK; // nothing to move; the reference does not say this fails + if (memory) return guarded_move(r.Destination, r.Source, r.SourceSize) ? S_OK : E_DSTORAGE_ACCESS_VIOLATION; + return read_file_range(e.file->handle(), r.FileOffset, r.Destination, r.SourceSize); + } + + // A zlib request whose checks have passed: the source (SourceSize bytes of the file or of memory) goes into a + // staging buffer, inflates there, and only a result of exactly DestinationSize bytes is copied to the destination. + // So a failed stream leaves the destination as it was, and a memory source that overlaps its destination is safe. + // Both buffers are at most 32 MiB (execute_request). The stream is RFC 1950: the two header bytes, the deflate + // data, the Adler-32 of the result; bytes after the Adler-32 are not read. A failure is the matching + // dstorageerr.h code: a bad header (not deflate, a window over 32 KiB, a bad check value or a preset dictionary) + // E_DSTORAGE_ZLIB_BAD_HEADER, bad or truncated deflate data E_DSTORAGE_ZLIB_BAD_DATA, an Adler-32 mismatch + // E_DSTORAGE_ZLIB_PARITY_FAIL, and a stream that inflates to more or fewer bytes than DestinationSize + // E_DSTORAGE_DECOMPRESSION_ERROR (no code names a size mismatch; this is the header's generic one). + HRESULT inflate_request(const Entry& e, bool memory) { + const DSTORAGE_REQUEST& r = e.request; + std::vector source, result; + try { + source.resize(r.SourceSize); + result.reserve(r.DestinationSize); + } catch (const std::bad_alloc&) { + return E_OUTOFMEMORY; + } + if (r.SourceSize != 0) { + if (memory) { + if (!guarded_move(source.data(), r.Source, r.SourceSize)) return E_DSTORAGE_ACCESS_VIOLATION; + } else if (const HRESULT hr = read_file_range(e.file->handle(), r.FileOffset, source.data(), r.SourceSize); + FAILED(hr)) { + return hr; + } + } + log_once("zlib", "zlib requests are inflated on the CPU (RFC 1950, leonida::zlib_inflate)"); + set_decompression_pending(+1); + leonida::ZlibError why = leonida::ZlibError::none; + const bool inflated = leonida::zlib_inflate(source, result, r.DestinationSize, &why); + set_decompression_pending(-1); + HRESULT hr = S_OK; + if (!inflated) { + switch (why) { + case leonida::ZlibError::header: hr = E_DSTORAGE_ZLIB_BAD_HEADER; break; + case leonida::ZlibError::checksum: hr = E_DSTORAGE_ZLIB_PARITY_FAIL; break; + case leonida::ZlibError::limit: hr = E_DSTORAGE_DECOMPRESSION_ERROR; break; // longer than the destination + default: hr = E_DSTORAGE_ZLIB_BAD_DATA; break; + } + } else if (result.size() != r.DestinationSize) { + hr = E_DSTORAGE_DECOMPRESSION_ERROR; // shorter than the destination + } + if (FAILED(hr)) { + std::lock_guard lock(stats().mutex); + ++stats().s.DecompressionErrors; + return hr; + } + return guarded_move(r.Destination, result.data(), result.size()) ? S_OK : E_DSTORAGE_ACCESS_VIOLATION; + } + + void set_pending(int delta) { + std::lock_guard lock(stats().mutex); + priority_stats(stats().s, desc_.Priority).PendingRequestCount += static_cast(delta); + } + + // PendingDecompressionRequestCount is the zlib requests being inflated; TotalDecompressionRequestCount counts each + // one that reached its inflate (its source was read), DecompressionErrors those whose stream then failed. + static void set_decompression_pending(int delta) { + std::lock_guard lock(stats().mutex); + auto& s = stats().s; + s.PendingDecompressionRequestCount += static_cast(delta); + if (delta > 0) ++s.TotalDecompressionRequestCount; + } + + void describe(const Entry& e, DSTORAGE_ERROR_FIRST_FAILURE& f) const { + switch (e.type) { + case Entry::Type::Request: { + f.CommandType = DSTORAGE_COMMAND_TYPE_REQUEST; + auto& q = f.Request; + const DSTORAGE_REQUEST& r = e.request; + q.Options = r.Options; + q.Destination = r.Destination; + q.DestinationSize = r.DestinationSize; + q.SourceSize = r.SourceSize; + q.CancellationTag = r.CancellationTag; + if (options::source_type(r.Options.AsUINT64) == DSTORAGE_REQUEST_SOURCE_MEMORY) { + q.Source = r.Source; + } else { + q.FileOffset = r.FileOffset; + if (e.file) wcsncpy_s(q.Filename, e.file->path().c_str(), _TRUNCATE); + } + // The reference says the name stays readable until the request completes. + if (r.Name) + for (size_t i = 0; i + 1 < kRequestMaxName && r.Name[i]; ++i) q.Name[i] = r.Name[i]; + break; + } + case Entry::Type::Status: + f.CommandType = DSTORAGE_COMMAND_TYPE_STATUS; + f.Status.StatusArray = e.status_as_given; + f.Status.Index = e.index; + break; + case Entry::Type::Signal: + f.CommandType = DSTORAGE_COMMAND_TYPE_SIGNAL; + f.Signal.Fence = e.fence; + f.Signal.Value = e.value; + break; + case Entry::Type::Event: + f.CommandType = kCommandTypeEvent; + break; + } + } + + void record_failure(const DSTORAGE_ERROR_FIRST_FAILURE& f) { + count_error(); + { + std::lock_guard lock(error_mutex_); + if (record_.FailureCount++ == 0) record_.FirstFailure = f; + if (error_event_) SetEvent(error_event_); + } + log_once("fail" + hr_text(f.HResult) + std::to_string(f.CommandType), + "an entry failed with " + hr_text(f.HResult) + " (command type " + std::to_string(f.CommandType) + + "; logged once per code)"); + } + + void clear_record_locked() { + record_ = DSTORAGE_ERROR_RECORD{}; + record_.FirstFailure.CommandType = DSTORAGE_COMMAND_TYPE_NONE; + } + + static void release_references(Entry& e) { + if (e.file) e.file->Release(); + if (e.status) e.status->Release(); + if (e.fence) e.fence->Release(); + if (e.event) CloseHandle(e.event); + e.event = nullptr; + e.file = nullptr; + e.status = nullptr; + e.fence = nullptr; + } + + std::atomic refs_{1}; + const DSTORAGE_QUEUE_DESC1 desc_; + std::mutex close_mutex_; // one Close at a time + std::mutex mutex_; // entries_, submitted_, in_flight_, closing_, closed_ + std::condition_variable work_, space_, idle_; + std::deque entries_; + size_t submitted_ = 0; // the first submitted_ entries are submitted + bool in_flight_ = false; + bool closing_ = false; + bool closed_ = false; + std::thread worker_; + HRESULT since_notify_ = S_OK; // worker only + std::mutex error_mutex_; + DSTORAGE_ERROR_RECORD record_{}; + HANDLE error_event_ = nullptr; +}; + +// ---- The factory ---------------------------------------------------------------------------------------------------- + +HRESULT validate_queue_desc(const DSTORAGE_QUEUE_DESC1& d) { + if (d.SourceType != DSTORAGE_REQUEST_SOURCE_FILE && d.SourceType != DSTORAGE_REQUEST_SOURCE_MEMORY) + return E_DSTORAGE_INVALID_SOURCE_TYPE; + if (d.Capacity < kMinQueueCapacity || d.Capacity > kMaxQueueCapacity) return E_DSTORAGE_INVALID_QUEUE_CAPACITY; + if (d.Priority < DSTORAGE_PRIORITY_FIRST || d.Priority > DSTORAGE_PRIORITY_LAST) + return E_DSTORAGE_INVALID_QUEUE_PRIORITY; + if (d.SourceType == DSTORAGE_REQUEST_SOURCE_MEMORY && d.Priority != DSTORAGE_PRIORITY_REALTIME) + return E_DSTORAGE_INVALID_MEMORY_QUEUE_PRIORITY; + if (d.Options.Reserved) return E_DSTORAGE_RESERVED_FIELDS; + return S_OK; +} + +using CreateFileWFn = HANDLE(WINAPI*)(LPCWSTR, DWORD, DWORD, LPSECURITY_ATTRIBUTES, DWORD, DWORD, HANDLE); + +// The title's own CreateFileW: the GAME: mapping and overlay when file_system.cpp is linked, else the host's. +CreateFileWFn create_file_w() { + if (void* fn = rt::shims::find("kernel32.dll", "CreateFileW")) return reinterpret_cast(fn); + return &::CreateFileW; +} + +class Factory final : public IDStorageFactoryX2 { +public: + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override { + if (!ppv) return E_POINTER; + *ppv = nullptr; + if (!iid_policy().accept_query(riid, Kind::Factory, "IDStorageFactoryX::QueryInterface")) return E_NOINTERFACE; + AddRef(); + *ppv = static_cast(this); + return S_OK; + } + ULONG STDMETHODCALLTYPE AddRef() override { return ++refs_; } + // One factory for the process; its count never drops below one, so it is never freed. + ULONG STDMETHODCALLTYPE Release() override { + ULONG r = refs_.load(); + while (r > 1 && !refs_.compare_exchange_weak(r, r - 1)) {} + return r > 1 ? r - 1 : 1; + } + + HRESULT STDMETHODCALLTYPE CreateQueue(const DSTORAGE_QUEUE_DESC* desc, REFIID riid, void** ppv) override { + if (!ppv) return bad_call("IDStorageFactoryX::CreateQueue", E_POINTER, "null ppv"); + *ppv = nullptr; + if (!desc) return bad_call("IDStorageFactoryX::CreateQueue", E_INVALIDARG, "null desc"); + DSTORAGE_QUEUE_DESC1 d{}; + d.SourceType = desc->SourceType; + d.Capacity = desc->Capacity; + d.Priority = desc->Priority; + d.Name = desc->Name; + return create_queue(d, riid, ppv, "IDStorageFactoryX::CreateQueue"); + } + + HRESULT STDMETHODCALLTYPE CreateQueue1(const DSTORAGE_QUEUE_DESC1* desc, REFIID riid, void** ppv) override { + if (!ppv) return bad_call("IDStorageFactoryX2::CreateQueue1", E_POINTER, "null ppv"); + *ppv = nullptr; + if (!desc) return bad_call("IDStorageFactoryX2::CreateQueue1", E_INVALIDARG, "null desc"); + return create_queue(*desc, riid, ppv, "IDStorageFactoryX2::CreateQueue1"); + } + + HRESULT STDMETHODCALLTYPE OpenFile(const WCHAR* path, REFIID riid, void** ppv) override { + if (!ppv) return bad_call("IDStorageFactoryX::OpenFile", E_POINTER, "null ppv"); + *ppv = nullptr; + if (!path || !*path) return bad_call("IDStorageFactoryX::OpenFile", E_INVALIDARG, "null or empty path"); + if (!iid_policy().accept_creating(riid, Kind::File, "IDStorageFactoryX::OpenFile")) return E_NOINTERFACE; + const HANDLE h = create_file_w()(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, + FILE_ATTRIBUTE_NORMAL, nullptr); + if (h == INVALID_HANDLE_VALUE) { + const DWORD error = GetLastError(); + return HRESULT_FROM_WIN32(error ? error : ERROR_FILE_NOT_FOUND); + } + File* f = new (std::nothrow) File(h, path); + if (!f) { + CloseHandle(h); + return E_OUTOFMEMORY; + } + *ppv = static_cast(f); + return S_OK; + } + + HRESULT STDMETHODCALLTYPE CreateStatusArray(UINT32 capacity, PCSTR, REFIID riid, void** ppv) override { + if (!ppv) return bad_call("IDStorageFactoryX::CreateStatusArray", E_POINTER, "null ppv"); + *ppv = nullptr; + if (capacity == 0) return bad_call("IDStorageFactoryX::CreateStatusArray", E_INVALIDARG, "capacity 0"); + if (!iid_policy().accept_creating(riid, Kind::StatusArray, "IDStorageFactoryX::CreateStatusArray")) + return E_NOINTERFACE; + std::unique_ptr[]> entries(new (std::nothrow) std::atomic[capacity]); + if (!entries) return E_OUTOFMEMORY; + auto* a = new (std::nothrow) StatusArray(capacity, std::move(entries)); + if (!a) return E_OUTOFMEMORY; + *ppv = static_cast(a); + return S_OK; + } + + // DirectStorage's own worker work would be pinned to these cores on the console. The mask names console cores, + // so it is stored and not applied to the host's. + HRESULT STDMETHODCALLTYPE SetCpuAffinity(UINT64 affinity) override { + cpu_affinity_.store(affinity); + return S_OK; + } + void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) override { debug_flags_.store(flags); } + + HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT32 size) override { + if (std::find(std::begin(kStagingBufferSizes), std::end(kStagingBufferSizes), size) == + std::end(kStagingBufferSizes)) + return bad_call("IDStorageFactoryX::SetStagingBufferSize", E_DSTORAGE_INVALID_STAGING_BUFFER_SIZE, + "not one of 0, 16, 20, 24, 28 or 32 MiB"); + std::lock_guard lock(stats().mutex); + if (stats().live_queues || stats().s.CurrentOpenFileCount) return E_DSTORAGE_STAGING_BUFFER_LOCKED; + staging_size_ = size; // there is no staging buffer here; the size is only kept + return S_OK; + } + + void STDMETHODCALLTYPE GetStats(DSTORAGE_STATS* out) override { + if (!out) { + bad_call("IDStorageFactoryX1::GetStats", E_POINTER, "null stats"); + return; + } + std::lock_guard lock(stats().mutex); + *out = stats().s; + } + +private: + HRESULT create_queue(const DSTORAGE_QUEUE_DESC1& desc, REFIID riid, void** ppv, const char* caller) { + if (const HRESULT hr = validate_queue_desc(desc); FAILED(hr)) return bad_call(caller, hr, "invalid queue desc"); + if (!iid_policy().accept_creating(riid, Kind::Queue, caller)) return E_NOINTERFACE; + auto* q = new (std::nothrow) Queue(desc); + if (!q) return E_OUTOFMEMORY; + if (!q->start()) { + q->Release(); + return E_OUTOFMEMORY; + } + *ppv = static_cast(q); + return S_OK; + } + + std::atomic refs_{1}; + std::atomic cpu_affinity_{~0ull}; + std::atomic debug_flags_{0}; + uint32_t staging_size_ = 32u << 20; // under stats().mutex +}; + +Factory& factory() { + static auto* f = new Factory; + return *f; +} + +HRESULT WINAPI dstorage_get_factory(REFIID riid, void** ppv) { + if (!ppv) return bad_call("DStorageGetFactory", E_POINTER, "null ppv"); + *ppv = nullptr; + if (!iid_policy().accept_creating(riid, Kind::Factory, "DStorageGetFactory")) return E_NOINTERFACE; + Factory& f = factory(); + f.AddRef(); + *ppv = static_cast(&f); + return S_OK; +} + +} // namespace + +// The console module names; docs/directstorage.md has the evidence and the confidence for each. +SHIM_TABLE(dstorage, + {"dstorage_xs.dll", "DStorageGetFactory", reinterpret_cast(&dstorage_get_factory)}, + {"xcrdapi.dll", "DStorageGetFactory", reinterpret_cast(&dstorage_get_factory)}, + {"dstorage.dll", "DStorageGetFactory", reinterpret_cast(&dstorage_get_factory)}, +); diff --git a/runtime/shims/dstorage_xs_abi.h b/runtime/shims/dstorage_xs_abi.h new file mode 100644 index 0000000000..aec6ac59dc --- /dev/null +++ b/runtime/shims/dstorage_xs_abi.h @@ -0,0 +1,387 @@ +// Xbox DirectStorage ABI: the console API (dstorage_xs.h on the console) a title calls through DStorageGetFactory. +// +// These are Leonida's own declarations. Names, member order and types follow the public GDK reference +// (learn.microsoft.com/gaming/gdk/docs/reference/system/dstorage); docs/directstorage.md has the evidence for which +// DLL serves it and how sure each part is. No Microsoft header is copied. +// +// VERIFY (docs/directstorage.md "What is not public"): +// - Vtable order. The reference lists methods alphabetically; the order below is the PC dstorage.h order for the +// methods both APIs share, with the console-only ones (SetCpuAffinity, GetStats, CreateQueue1, GetHandle, +// Query1) where the GDK overview lists them. Reorder a declaration here and every object follows. +// - Interface ids. The X interfaces' ids are not public. The one declared id is the PC IDStorageStatusArray's, whose +// interface has the same shape (console D3D12 binaries reuse PC SDK ids); dstorage.cpp's creating calls learn and +// log the others. The other PC ids are declared only so they can be refused. +// - The capacity bounds, DSTORAGE_REQUEST_MAX_NAME and the E_DSTORAGE_* values are the PC header's. +#pragma once +#include +#include + +#include +#include + +struct ID3D12Fence; // d3d12.h; the shim calls Signal through it + +namespace dsx { + +#pragma warning(push) +#pragma warning(disable : 4201) // nameless struct/union: the reference declares the members that way + +// ---- Constants and enumerations ----------------------------------------------------------------------------------- + +constexpr uint16_t kMinQueueCapacity = 0x80; // DSTORAGE_MIN_QUEUE_CAPACITY (PC value) +constexpr uint16_t kMaxQueueCapacity = 0x2000; // DSTORAGE_MAX_QUEUE_CAPACITY (PC value) +constexpr size_t kRequestMaxName = 64; // DSTORAGE_REQUEST_MAX_NAME (PC value) +constexpr uint64_t kMaxRequestBytes = 1ull << 30; // DSTORAGE_MAX_REQUEST_SIZE: source + destination +constexpr uint32_t kMax4kPageDestinationSize = 32u << 20; // DSTORAGE_MAX_4K_PAGE_DESTINATION_SIZE + +enum DSTORAGE_PRIORITY : int8_t { + DSTORAGE_PRIORITY_LOW = -1, + DSTORAGE_PRIORITY_NORMAL = 0, + DSTORAGE_PRIORITY_HIGH = 1, + DSTORAGE_PRIORITY_REALTIME = 2, + DSTORAGE_PRIORITY_FIRST = DSTORAGE_PRIORITY_LOW, + DSTORAGE_PRIORITY_LAST = DSTORAGE_PRIORITY_REALTIME, + DSTORAGE_PRIORITY_COUNT = 4, +}; + +enum DSTORAGE_REQUEST_SOURCE_TYPE : uint64_t { + DSTORAGE_REQUEST_SOURCE_FILE = 0, + DSTORAGE_REQUEST_SOURCE_MEMORY = 1, +}; + +enum DSTORAGE_BCPACK_MODE : uint64_t { + DSTORAGE_BCPACK_MODE_NONE = 0, + DSTORAGE_BCPACK_MODE_BC1 = 1, + DSTORAGE_BCPACK_MODE_BC2 = 2, + DSTORAGE_BCPACK_MODE_BC3 = 3, + DSTORAGE_BCPACK_MODE_BC4 = 4, + DSTORAGE_BCPACK_MODE_BC5 = 5, + DSTORAGE_BCPACK_MODE_BC6H = 6, + DSTORAGE_BCPACK_MODE_BC7 = 7, +}; + +enum DSTORAGE_SWIZZLE_MODE : uint64_t { + DSTORAGE_SWIZZLE_MODE_NONE = 0, + DSTORAGE_SWIZZLE_MODE_4K_4K_8K = 1, + DSTORAGE_SWIZZLE_MODE_4K_4K_24K = 2, + DSTORAGE_SWIZZLE_MODE_4K_12K_4K_4K_8K = 3, + DSTORAGE_SWIZZLE_MODE_4K_12K_4K_12K = 4, +}; + +enum DSTORAGE_COMMAND_TYPE : int32_t { + DSTORAGE_COMMAND_TYPE_NONE = -1, + DSTORAGE_COMMAND_TYPE_REQUEST = 0, + DSTORAGE_COMMAND_TYPE_STATUS = 1, + DSTORAGE_COMMAND_TYPE_SIGNAL = 2, +}; +// Not in the console enum: the PC API's DSTORAGE_COMMAND_TYPE_EVENT, used here for a failed EnqueueSetEvent. +constexpr DSTORAGE_COMMAND_TYPE kCommandTypeEvent = static_cast(3); + +enum DSTORAGE_DEBUG : uint32_t { + DSTORAGE_DEBUG_NONE = 0x00, + DSTORAGE_DEBUG_SHOW_ERRORS = 0x01, + DSTORAGE_DEBUG_BREAK_ON_ERROR = 0x02, + DSTORAGE_DEBUG_RECORD_OBJECT_NAMES = 0x04, +}; + +// The staging-buffer sizes the GDK overview lists as valid (its enumeration page is not public). +constexpr uint32_t kStagingBufferSizes[] = {0, 16u << 20, 20u << 20, 24u << 20, 28u << 20, 32u << 20}; + +// ---- Errors (FACILITY_GAME, the PC dstorageerr.h values) ---------------------------------------------------------- + +constexpr HRESULT E_DSTORAGE_INVALID_QUEUE_CAPACITY = static_cast(0x89240003L); +constexpr HRESULT E_DSTORAGE_END_OF_FILE = static_cast(0x89240007L); +constexpr HRESULT E_DSTORAGE_REQUEST_TOO_LARGE = static_cast(0x89240008L); +constexpr HRESULT E_DSTORAGE_ACCESS_VIOLATION = static_cast(0x89240009L); +constexpr HRESULT E_DSTORAGE_FILE_NOT_OPEN = static_cast(0x8924000BL); +constexpr HRESULT E_DSTORAGE_RESERVED_FIELDS = static_cast(0x8924000CL); +constexpr HRESULT E_DSTORAGE_INVALID_BCPACK_MODE = static_cast(0x8924000DL); +constexpr HRESULT E_DSTORAGE_INVALID_SWIZZLE_MODE = static_cast(0x8924000EL); +constexpr HRESULT E_DSTORAGE_INVALID_DESTINATION_SIZE = static_cast(0x8924000FL); +constexpr HRESULT E_DSTORAGE_QUEUE_CLOSED = static_cast(0x89240010L); +constexpr HRESULT E_DSTORAGE_INVALID_QUEUE_PRIORITY = static_cast(0x89240013L); +constexpr HRESULT E_DSTORAGE_INDEX_BOUND = static_cast(0x89240015L); +constexpr HRESULT E_DSTORAGE_INVALID_FILE_HANDLE = static_cast(0x89240017L); +constexpr HRESULT E_DSTORAGE_INVALID_FILE_OFFSET = static_cast(0x8924001AL); +constexpr HRESULT E_DSTORAGE_INVALID_SOURCE_TYPE = static_cast(0x8924001BL); +constexpr HRESULT E_DSTORAGE_INVALID_INTERMEDIATE_SIZE = static_cast(0x8924001CL); +constexpr HRESULT E_DSTORAGE_STAGING_BUFFER_LOCKED = static_cast(0x8924001FL); +constexpr HRESULT E_DSTORAGE_INVALID_STAGING_BUFFER_SIZE = static_cast(0x89240020L); +constexpr HRESULT E_DSTORAGE_INVALID_FENCE = static_cast(0x89240022L); +constexpr HRESULT E_DSTORAGE_INVALID_STATUS_ARRAY = static_cast(0x89240023L); +constexpr HRESULT E_DSTORAGE_INVALID_MEMORY_QUEUE_PRIORITY = static_cast(0x89240024L); +// The decompression failures. E_DSTORAGE_DECOMPRESSION_ERROR ("a generic error has happened during decompression") +// is on the public DirectStorage constants page; the three zlib codes are in the same header (dstorageerr.h) with no +// public description: the names and values here are those of the header-generated bindings of the `direct-storage` +// crate (docs/directstorage.md "Sources"). PARITY_FAIL is read as the Adler-32 check, the only check value a zlib +// stream has. +constexpr HRESULT E_DSTORAGE_DECOMPRESSION_ERROR = static_cast(0x89240030L); +constexpr HRESULT E_DSTORAGE_ZLIB_BAD_HEADER = static_cast(0x89240031L); +constexpr HRESULT E_DSTORAGE_ZLIB_BAD_DATA = static_cast(0x89240032L); +constexpr HRESULT E_DSTORAGE_ZLIB_PARITY_FAIL = static_cast(0x89240033L); + +// ---- Structures --------------------------------------------------------------------------------------------------- + +// DSTORAGE_REQUEST_OPTIONS as the reference declares it. The shim reads AsUINT64 through the bit positions below +// (MSVC allocates bit-fields from bit 0 up); dstorage_test checks that the two agree. +union DSTORAGE_REQUEST_OPTIONS { + struct { + uint64_t ZlibDecompress : 1; + DSTORAGE_BCPACK_MODE BcpackMode : 4; + DSTORAGE_SWIZZLE_MODE SwizzleMode : 16; + uint64_t DestinationIsPhysicalPages : 1; + DSTORAGE_REQUEST_SOURCE_TYPE SourceType : 1; + uint64_t SourceIsPhysicalPages : 1; + uint64_t Reserved : 40; + }; + uint64_t AsUINT64; +}; +static_assert(sizeof(DSTORAGE_REQUEST_OPTIONS) == 8); + +namespace options { +constexpr uint64_t kZlib = 1ull << 0; +constexpr unsigned kBcpackShift = 1; +constexpr uint64_t kBcpackMask = 0xFull << kBcpackShift; +constexpr unsigned kSwizzleShift = 5; +constexpr uint64_t kSwizzleMask = 0xFFFFull << kSwizzleShift; +constexpr uint64_t kDestinationPages = 1ull << 21; +constexpr uint64_t kSourceMemory = 1ull << 22; // SourceType == DSTORAGE_REQUEST_SOURCE_MEMORY +constexpr uint64_t kSourcePages = 1ull << 23; +constexpr uint64_t kReservedMask = ~((1ull << 24) - 1); + +constexpr bool zlib(uint64_t o) { return (o & kZlib) != 0; } +constexpr uint64_t bcpack(uint64_t o) { return (o & kBcpackMask) >> kBcpackShift; } +constexpr uint64_t swizzle(uint64_t o) { return (o & kSwizzleMask) >> kSwizzleShift; } +constexpr DSTORAGE_REQUEST_SOURCE_TYPE source_type(uint64_t o) { + return (o & kSourceMemory) ? DSTORAGE_REQUEST_SOURCE_MEMORY : DSTORAGE_REQUEST_SOURCE_FILE; +} +} // namespace options + +struct IDStorageFileX; +struct IDStorageStatusArrayX; + +struct DSTORAGE_REQUEST { + DSTORAGE_REQUEST_OPTIONS Options; + union { + void* Destination; + struct { + PULONG_PTR DestinationPageArray; + UINT16 DestinationPageOffset; + }; + }; + UINT32 DestinationSize; + union { + struct { + IDStorageFileX* File; + UINT64 FileOffset; + }; + const void* Source; + struct { + PULONG_PTR SourcePageArray; + UINT16 SourcePageOffset; + }; + }; + UINT32 SourceSize; + UINT32 IntermediateSize; + UINT64 CancellationTag; + const CHAR* Name; +}; +static_assert(offsetof(DSTORAGE_REQUEST, Destination) == 8 && offsetof(DSTORAGE_REQUEST, DestinationPageOffset) == 16); +static_assert(offsetof(DSTORAGE_REQUEST, DestinationSize) == 24 && offsetof(DSTORAGE_REQUEST, File) == 32); +static_assert(offsetof(DSTORAGE_REQUEST, FileOffset) == 40 && offsetof(DSTORAGE_REQUEST, Source) == 32); +static_assert(offsetof(DSTORAGE_REQUEST, SourcePageOffset) == 40 && offsetof(DSTORAGE_REQUEST, SourceSize) == 48); +static_assert(offsetof(DSTORAGE_REQUEST, IntermediateSize) == 52 && offsetof(DSTORAGE_REQUEST, CancellationTag) == 56); +static_assert(offsetof(DSTORAGE_REQUEST, Name) == 64 && sizeof(DSTORAGE_REQUEST) == 72); + +struct DSTORAGE_QUEUE_DESC { + DSTORAGE_REQUEST_SOURCE_TYPE SourceType; + UINT16 Capacity; + DSTORAGE_PRIORITY Priority; + const CHAR* Name; +}; +static_assert(offsetof(DSTORAGE_QUEUE_DESC, Capacity) == 8 && offsetof(DSTORAGE_QUEUE_DESC, Priority) == 10); +static_assert(offsetof(DSTORAGE_QUEUE_DESC, Name) == 16 && sizeof(DSTORAGE_QUEUE_DESC) == 24); + +union DSTORAGE_QUEUE_OPTIONS { + struct { + uint64_t AutoSubmitDisabled : 1; + uint64_t Reserved : 63; + }; + uint64_t AsUINT64; +}; +static_assert(sizeof(DSTORAGE_QUEUE_OPTIONS) == 8); + +struct DSTORAGE_QUEUE_DESC1 { + DSTORAGE_REQUEST_SOURCE_TYPE SourceType; + UINT16 Capacity; + DSTORAGE_PRIORITY Priority; + const CHAR* Name; + DSTORAGE_QUEUE_OPTIONS Options; +}; +static_assert(offsetof(DSTORAGE_QUEUE_DESC1, Options) == 24 && sizeof(DSTORAGE_QUEUE_DESC1) == 32); + +struct DSTORAGE_QUEUE_INFO { + DSTORAGE_QUEUE_DESC Desc; + UINT16 EmptySlotCount; + UINT16 RequestCountUntilAutoSubmit; +}; +static_assert(offsetof(DSTORAGE_QUEUE_INFO, EmptySlotCount) == 24 && sizeof(DSTORAGE_QUEUE_INFO) == 32); + +struct DSTORAGE_QUEUE_INFO1 { + DSTORAGE_QUEUE_DESC1 Desc; + UINT16 EmptySlotCount; + UINT16 RequestCountUntilAutoSubmit; +}; +static_assert(offsetof(DSTORAGE_QUEUE_INFO1, EmptySlotCount) == 32 && sizeof(DSTORAGE_QUEUE_INFO1) == 40); + +// The reference declares the three failure kinds as unnamed structs inside DSTORAGE_ERROR_RECORD; they are named +// here (Leonida's names) so the shim can fill them. The layout is the same. +struct DSTORAGE_ERROR_REQUEST { + DSTORAGE_REQUEST_OPTIONS Options; + void* Destination; + UINT32 DestinationSize; + WCHAR Filename[MAX_PATH]; + UINT64 FileOffset; + const void* Source; + UINT32 SourceSize; + UINT64 CancellationTag; + CHAR Name[kRequestMaxName]; +}; +struct DSTORAGE_ERROR_STATUS { + IDStorageStatusArrayX* StatusArray; + UINT32 Index; +}; +struct DSTORAGE_ERROR_SIGNAL { + ID3D12Fence* Fence; + UINT64 Value; +}; +struct DSTORAGE_ERROR_FIRST_FAILURE { + HRESULT HResult; + DSTORAGE_COMMAND_TYPE CommandType; + union { + DSTORAGE_ERROR_REQUEST Request; + DSTORAGE_ERROR_STATUS Status; + DSTORAGE_ERROR_SIGNAL Signal; + }; +}; +struct DSTORAGE_ERROR_RECORD { + UINT32 FailureCount; + DSTORAGE_ERROR_FIRST_FAILURE FirstFailure; +}; +static_assert(offsetof(DSTORAGE_ERROR_RECORD, FirstFailure) == 8); +static_assert(offsetof(DSTORAGE_ERROR_FIRST_FAILURE, Request) == 8); +static_assert(offsetof(DSTORAGE_ERROR_REQUEST, Filename) == 20 && offsetof(DSTORAGE_ERROR_REQUEST, FileOffset) == 544); +static_assert(offsetof(DSTORAGE_ERROR_REQUEST, Name) == 576 && sizeof(DSTORAGE_ERROR_REQUEST) == 640); +static_assert(sizeof(DSTORAGE_ERROR_RECORD) == 656); + +struct DSTORAGE_PRIORITY_STATS { + UINT32 CurrentQueueCount; + UINT32 MaxQueueCount; + UINT32 CumulativeQueueCount; + UINT32 TotalStatusCount; + UINT32 TotalFenceCount; + UINT32 PendingRequestCount; + UINT32 TotalRequestCount; + UINT64 TotalRequestSourceByteCount; + UINT64 TotalRequestDestinationByteCount; +}; +static_assert(sizeof(DSTORAGE_PRIORITY_STATS) == 48); + +struct DSTORAGE_STATS { + DSTORAGE_PRIORITY_STATS LowPriorityStats; + DSTORAGE_PRIORITY_STATS NormalPriorityStats; + DSTORAGE_PRIORITY_STATS HighPriorityStats; + DSTORAGE_PRIORITY_STATS RealtimePriorityStats; + UINT8 CurrentOpenVirtualDiskCount; + UINT8 MaxOpenVirtualDiskCount; + UINT32 CumulativeOpenVirtualDiskCount; + UINT32 PendingStorageRequestCount; + UINT32 TotalStorageRequestCount; + UINT32 StorageRetries; + UINT32 StorageErrors; + UINT32 PendingDecompressionRequestCount; + UINT32 TotalDecompressionRequestCount; + UINT32 DecompressionErrors; + UINT32 StagingBufferStallCount; + UINT32 CurrentOpenFileCount; + UINT32 MaxOpenFileCount; + UINT32 CumulativeOpenFileCount; + UINT32 CurrentTitleMemoryUsageBytes; + UINT32 MaxTitleMemoryUsageBytes; + UINT32 ErrorCount; +}; + +#pragma warning(pop) + +// ---- Interfaces, in the vtable order chosen above --------------------------------------------------------------- + +struct IDStorageStatusArrayX : IUnknown { + virtual bool STDMETHODCALLTYPE IsComplete(UINT32 index) = 0; + virtual HRESULT STDMETHODCALLTYPE GetHResult(UINT32 index) = 0; +}; + +struct IDStorageFileX : IUnknown { + virtual void STDMETHODCALLTYPE Close() = 0; + virtual HANDLE STDMETHODCALLTYPE GetHandle() = 0; +}; + +struct IDStorageQueueX : IUnknown { + virtual void STDMETHODCALLTYPE EnqueueRequest(const DSTORAGE_REQUEST* request) = 0; + virtual void STDMETHODCALLTYPE EnqueueStatus(IDStorageStatusArrayX* status_array, UINT32 index) = 0; + virtual void STDMETHODCALLTYPE EnqueueSignal(ID3D12Fence* fence, UINT64 value) = 0; + virtual void STDMETHODCALLTYPE Submit() = 0; + virtual void STDMETHODCALLTYPE CancelRequestsWithTag(UINT64 mask, UINT64 value) = 0; + virtual void STDMETHODCALLTYPE Close() = 0; + virtual HANDLE STDMETHODCALLTYPE GetErrorEvent() = 0; + virtual void STDMETHODCALLTYPE RetrieveErrorRecord(DSTORAGE_ERROR_RECORD* record) = 0; + virtual void STDMETHODCALLTYPE Query(DSTORAGE_QUEUE_INFO* info) = 0; +}; + +struct IDStorageQueueX1 : IDStorageQueueX { + virtual void STDMETHODCALLTYPE EnqueueSetEvent(HANDLE handle) = 0; +}; + +struct IDStorageQueueX2 : IDStorageQueueX1 { + virtual void STDMETHODCALLTYPE Query1(DSTORAGE_QUEUE_INFO1* info) = 0; +}; + +struct IDStorageFactoryX : IUnknown { + virtual HRESULT STDMETHODCALLTYPE CreateQueue(const DSTORAGE_QUEUE_DESC* desc, REFIID riid, void** ppv) = 0; + virtual HRESULT STDMETHODCALLTYPE OpenFile(const WCHAR* path, REFIID riid, void** ppv) = 0; + virtual HRESULT STDMETHODCALLTYPE CreateStatusArray(UINT32 capacity, PCSTR name, REFIID riid, void** ppv) = 0; + virtual HRESULT STDMETHODCALLTYPE SetCpuAffinity(UINT64 affinity) = 0; + virtual void STDMETHODCALLTYPE SetDebugFlags(UINT32 flags) = 0; + virtual HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT32 size) = 0; +}; + +struct IDStorageFactoryX1 : IDStorageFactoryX { + virtual void STDMETHODCALLTYPE GetStats(DSTORAGE_STATS* stats) = 0; +}; + +struct IDStorageFactoryX2 : IDStorageFactoryX1 { + virtual HRESULT STDMETHODCALLTYPE CreateQueue1(const DSTORAGE_QUEUE_DESC1* desc, REFIID riid, void** ppv) = 0; +}; + +using DStorageGetFactoryFn = HRESULT(WINAPI*)(REFIID riid, void** ppv); + +// ---- Interface ids ------------------------------------------------------------------------------------------------- + +// Accepted for a status array: IDStorageStatusArray (PC dstorage.h 1.3.0), same methods in the same order. +constexpr GUID kStatusArrayIds[] = { + {0x82397587, 0x7cd5, 0x453b, {0xa0, 0x2e, 0x31, 0x37, 0x9b, 0xd6, 0x46, 0x56}}, +}; + +// The other PC DirectStorage ids (dstorage.h 1.3.0), refused: their objects have another shape. +constexpr GUID kPcInterfaceIds[] = { + {0x6924ea0c, 0xc3cd, 0x4826, {0xb1, 0x0a, 0xf6, 0x4f, 0x4e, 0xd9, 0x27, 0xc1}}, // IDStorageFactory + {0x5de95e7b, 0x955a, 0x4868, {0xa7, 0x3c, 0x24, 0x3b, 0x29, 0xf4, 0xb8, 0xda}}, // IDStorageFile + {0xcfdbd83f, 0x9e06, 0x4fda, {0x8e, 0xa5, 0x69, 0x04, 0x21, 0x37, 0xf4, 0x9b}}, // IDStorageQueue + {0xdd2f482c, 0x5eff, 0x41e8, {0x9c, 0x9e, 0xd2, 0x37, 0x4b, 0x27, 0x81, 0x28}}, // IDStorageQueue1 + {0xb1c9d643, 0x3a49, 0x44a2, {0xb4, 0x6f, 0x65, 0x36, 0x49, 0x47, 0x0d, 0x18}}, // IDStorageQueue2 + {0xdeb54c52, 0xeca8, 0x46b3, {0x82, 0xa7, 0x03, 0x1b, 0x72, 0x26, 0x26, 0x53}}, // IDStorageQueue3 + {0x97179b2f, 0x2c21, 0x49ca, {0x82, 0x91, 0x4e, 0x1b, 0xf4, 0xa1, 0x60, 0xdf}}, // ...CustomDecompressionQueue + {0x0d47c6c9, 0xe61a, 0x4706, {0x93, 0xb4, 0x68, 0xbf, 0xe3, 0xf4, 0xaa, 0x4a}}, // ...CustomDecompressionQueue1 + {0x84ef5121, 0x9b43, 0x4d03, {0xb5, 0xc1, 0xcc, 0x34, 0x60, 0x6b, 0x26, 0x2d}}, // IDStorageCompressionCodec +}; + +} // namespace dsx diff --git a/runtime/shims/gameinput.cpp b/runtime/shims/gameinput.cpp index 47ee190e3f..402179cde8 100644 --- a/runtime/shims/gameinput.cpp +++ b/runtime/shims/gameinput.cpp @@ -2724,7 +2724,11 @@ void set_hid_backend(const HidBackend* backend) { g_hid = backend ? backend : &k } // namespace rt::gameinput +// GameInputCreate is GameInput.dll's export 1, and the retail executable imports it by that ordinal, which the loader +// looks up as "#1". Without the alias the import misses the shim and binds to the host's GameInput.dll; under Wine that +// is the builtin stub, which fails, and the title stops on the result. SHIM_TABLE(gameinput, {"gameinput.dll", "GameInputCreate", reinterpret_cast(&GameInputCreate)}, + {"gameinput.dll", "#1", reinterpret_cast(&GameInputCreate)}, {"xgameruntime.dll", "GameInputCreate", reinterpret_cast(&GameInputCreate)}, ); diff --git a/runtime/shims/library_loader.cpp b/runtime/shims/library_loader.cpp index 82dd754930..0fcd89d7e3 100644 --- a/runtime/shims/library_loader.cpp +++ b/runtime/shims/library_loader.cpp @@ -2,9 +2,10 @@ // // GDK code does not always import the console runtime. The package's libHttpClient.GDK.dll and XCurl.dll have no // import entry for xgameruntime.dll at all: their statically linked xgameruntime.lib thunks hold the wide string -// "xgameruntime.dll" and the names InitializeApiImpl, InitializeApiImplEx, InitializeApiImplEx2, QueryApiImpl and -// UninitializeApiImpl, and look them up at run time (docs/runtime_imports.md, "Run-time loaded modules"). Bound to the -// host, that LoadLibraryW would load the PC's Gaming Services runtime or fail, and never reach the offline shims. +// "xgameruntime.dll" and the names InitializeApiImpl, InitializeApiImplEx, InitializeApiImplEx2, QueryApiImpl, +// UninitializeApiImpl and XErrorReport, and look them up at run time (docs/runtime_imports.md, "Run-time loaded +// modules"). Bound to the host, that LoadLibraryW would load the PC's Gaming Services runtime or fail, and never reach +// the offline shims. // // So for a module the shim registry owns (rt::shims::owns_dll: xgameruntime.dll, d3d12_xs.dll, xmem.dll, ...), these // return a pseudo-handle, and GetProcAddress on it resolves names (and "#ordinal") through rt::shims::find. A name the diff --git a/runtime/shims/registry.cpp b/runtime/shims/registry.cpp index 9b3ea04375..c0d826e311 100644 --- a/runtime/shims/registry.cpp +++ b/runtime/shims/registry.cpp @@ -80,7 +80,10 @@ std::vector g_lookups; // xaudio2_9.dll XAudio2Create: HRESULT (learn.microsoft.com/windows/win32/api/xaudio2/ // xaudio2_9redist.dll nf-xaudio2-xaudio2create). xaudio2_9.dll is the console name (docs/d3d12_vulkan.md §7). // dstorage.dll DStorageGetFactory: HRESULT (learn.microsoft.com/windows/win32/api/dstorage/ -// dstorage_xs.dll nf-dstorage-dstoragegetfactory). dstorage_xs.dll is the console name. +// dstorage_xs.dll nf-dstorage-dstoragegetfactory, and the GDK's gaming/gdk/docs/reference/system/dstorage/ +// xcrdapi.dll functions/dstoragegetfactory). dstorage_xs.dll is the console name; xcrdapi.dll is a +// console module the title may import it from (docs/directstorage.md). dstorage.cpp serves +// it; the class is kept for a build without that shim. const char* const kNotHResult[] = { "XAsyncCancel", "XAsyncComplete", "XTaskQueueCloseHandle", "XTaskQueueDispatch", "XTaskQueueGetCurrentProcessTaskQueue", @@ -111,7 +114,7 @@ ReturnClass classify(const std::string& dll, const std::string& name) { if (name == "XAudio2Create") return ReturnClass::HResult; } else if (dll == "gameinput.dll") { if (name == "GameInputCreate") return ReturnClass::HResult; - } else if (dll == "dstorage.dll" || dll == "dstorage_xs.dll") { + } else if (dll == "dstorage.dll" || dll == "dstorage_xs.dll" || dll == "xcrdapi.dll") { if (name == "DStorageGetFactory") return ReturnClass::HResult; } else if (dll == "acphal.dll") { if (name == "AcpHalAllocateShapeContexts" || name == "AcpHalCreate" || @@ -387,6 +390,11 @@ struct BundledLoaderEntry { const BundledModuleOps* ops; }; +struct XMemHooksEntry { + const void* owner; + const XMemAllocationHooks* hooks; +}; + // Immortal: late mapped-DLL detach or atexit handlers may call GetProcAddress/FreeLibrary during process teardown. std::mutex& bundled_loader_mutex() { static auto* m = new std::mutex; @@ -398,6 +406,16 @@ std::vector& bundled_loaders() { return *v; } +std::mutex& xmem_hooks_mutex() { + static auto* m = new std::mutex; + return *m; +} + +std::vector& xmem_hooks_entries() { + static auto* v = new std::vector; + return *v; +} + std::vector snapshot_bundled_loaders() { std::lock_guard lock(bundled_loader_mutex()); return bundled_loaders(); @@ -480,6 +498,30 @@ bool owns_bundled_module_handle(void* module) { return false; } +void add_xmem_allocation_hooks(const void* owner, const XMemAllocationHooks* hooks) { + if (!owner || !hooks) return; + std::lock_guard lock(xmem_hooks_mutex()); + xmem_hooks_entries().push_back({owner, hooks}); +} + +void remove_xmem_allocation_hooks(const void* owner) { + std::lock_guard lock(xmem_hooks_mutex()); + auto& list = xmem_hooks_entries(); + for (auto it = list.begin(); it != list.end();) { + if (it->owner == owner) { + it = list.erase(it); + } else { + ++it; + } + } +} + +const XMemAllocationHooks* xmem_allocation_hooks() { + std::lock_guard lock(xmem_hooks_mutex()); + const auto& list = xmem_hooks_entries(); + return list.empty() ? nullptr : list.back().hooks; +} + Table::Table(const Entry* entries, size_t count) { for (size_t i = 0; i < count; ++i) table()[lower_ascii(entries[i].dll) + "!" + entries[i].name] = entries[i].fn; } diff --git a/runtime/shims/shims.h b/runtime/shims/shims.h index 76a7e761f8..a7fa7b9ced 100644 --- a/runtime/shims/shims.h +++ b/runtime/shims/shims.h @@ -80,6 +80,19 @@ void* load_bundled_module_w(const std::wstring& basename, uint32_t flags, bool& void* get_bundled_proc_address(void* module, const std::string& sym, bool& owns_handle); bool owns_bundled_module_handle(void* module); +// Title-exported __XMemAllocationHooks__ (GDK XMEM_ALLOCATION_HOOKS): the console runtime routes internal +// allocations (including D3D12 descriptor heaps) through these callbacks when the mapped image exports the struct. +// Registered by Loader after relocations and removed in Loader::~Loader. +using XMemAllocHookFn = void*(__stdcall*)(size_t size, uint64_t attributes); +using XMemFreeHookFn = void(__stdcall*)(void* ptr, uint64_t attributes); +struct XMemAllocationHooks { + XMemAllocHookFn alloc; + XMemFreeHookFn free; +}; +void add_xmem_allocation_hooks(const void* owner, const XMemAllocationHooks* hooks); +void remove_xmem_allocation_hooks(const void* owner); +const XMemAllocationHooks* xmem_allocation_hooks(); + // Test seam: called at the top of every unimplemented-import call with the address of rt_unimplemented's return // address slot (so a test can check stack alignment) and from inside the call (so it can walk the stack). using TestHook = void (*)(const void* return_address_slot); diff --git a/runtime/shims/startup_trace.h b/runtime/shims/startup_trace.h index 7b47d993ae..ca4a4853f6 100644 --- a/runtime/shims/startup_trace.h +++ b/runtime/shims/startup_trace.h @@ -3,14 +3,15 @@ // One JSON object per line, flushed per event so the file survives a crash. Off by default; every entry point is a // single relaxed load when it is off. Events: // {"seq":1,"t":0.000,"kind":"trace_open"} -// {"seq":2,"t":0.001,"kind":"map","module":"a.dll","base":"0x...","size":"0x2000","relocated":false} -// {"seq":3,"t":0.002,"kind":"tls_callback","module":"a.dll","at":"a.dll+0x1200","reason":1} -// {"seq":4,"t":0.002,"kind":"dllmain","module":"a.dll","result":1} -// {"seq":5,"t":0.010,"kind":"unimplemented_call","import":"x.dll!Foo","caller":"a.dll+0x3f10"} (first call only) -// {"seq":6,"t":0.011,"kind":"debug_string","text":"..."} -// {"seq":7,"t":0.020,"kind":"exception","code":"0xc0000005","at":"a.dll+0x4a00","access":"read","address":"0x0", +// {"seq":2,"t":0.001,"kind":"tls_index0","owner":"gta6rt.exe","moved_to":4} (first executable mapped, once) +// {"seq":3,"t":0.001,"kind":"map","module":"a.dll","base":"0x...","size":"0x2000","relocated":false} +// {"seq":4,"t":0.002,"kind":"tls_callback","module":"a.dll","at":"a.dll+0x1200","reason":1} +// {"seq":5,"t":0.002,"kind":"dllmain","module":"a.dll","result":1} +// {"seq":6,"t":0.010,"kind":"unimplemented_call","import":"x.dll!Foo","caller":"a.dll+0x3f10"} (first call only) +// {"seq":7,"t":0.011,"kind":"debug_string","text":"..."} +// {"seq":8,"t":0.020,"kind":"exception","code":"0xc0000005","at":"a.dll+0x4a00","access":"read","address":"0x0", // "stack":["a.dll+0x4a00","a.dll+0x2210"]} -// {"seq":8,"t":0.030,"kind":"exit","code":0} +// {"seq":9,"t":0.030,"kind":"exit","code":0} // // The exception handler is vectored, logs and returns EXCEPTION_CONTINUE_SEARCH: it never changes what the process // does (except LEONIDA_SKIP_INT3, below). diff --git a/runtime/shims/title_window.h b/runtime/shims/title_window.h new file mode 100644 index 0000000000..f2564f6563 --- /dev/null +++ b/runtime/shims/title_window.h @@ -0,0 +1,52 @@ +#pragma once + +// The window a GDKX title shows its frames in, for PresentX. +// +// On the console PresentX puts a frame on the display: it names no window. A GDKX title still makes its own top-level +// Win32 window (CreateWindowExW with its own class, a message loop on its own thread) before it presents, so on the PC +// that window is where the frames belong. Measured on a retail executable: by its first PresentX the title has one +// visible, unowned top-level window on a thread of its own; the other windows of the process at that point are hidden +// (the IME windows Windows adds, a driver's dummy window). +// +// The lookup sends no message to any window. The present thread is not the title's window thread, and that thread can +// be busy (or waiting on the present thread) when the first PresentX comes: GetWindowTextW, or any call that sends a +// message across threads, would block the present thread there. Measured: a lookup that read the window titles with +// GetWindowTextW stopped the retail title at its first PresentX. EnumWindows, GetWindowThreadProcessId, IsWindowVisible, +// GetWindow(GW_OWNER), GetWindowLongPtrW and GetClientRect read the window manager's own state and send nothing. + +#include + +namespace rt::d3d12 { + +// The visible, unowned, non-tool top-level window of `process_id` with the largest client area, `exclude` aside (the +// runtime's own fallback window); null when the process has none. Ties keep the first one in Z order (the topmost). +inline HWND find_title_window(DWORD process_id, HWND exclude = nullptr) { + struct Search { + DWORD process_id; + HWND exclude; + HWND best; + LONGLONG best_area; + } search{process_id, exclude, nullptr, -1}; + EnumWindows( + [](HWND window, LPARAM context) -> BOOL { + auto& s = *reinterpret_cast(context); + DWORD owner_process = 0; + if (window == s.exclude || !GetWindowThreadProcessId(window, &owner_process) || + owner_process != s.process_id) + return TRUE; + if (!IsWindowVisible(window) || GetWindow(window, GW_OWNER)) return TRUE; + if (GetWindowLongPtrW(window, GWL_EXSTYLE) & WS_EX_TOOLWINDOW) return TRUE; + RECT client{}; + const LONGLONG area = + GetClientRect(window, &client) ? LONGLONG(client.right - client.left) * (client.bottom - client.top) : 0; + if (area > s.best_area) { + s.best = window; + s.best_area = area; + } + return TRUE; + }, + reinterpret_cast(&search)); + return search.best; +} + +} // namespace rt::d3d12 diff --git a/runtime/shims/xbox_bvh_builder.cpp b/runtime/shims/xbox_bvh_builder.cpp new file mode 100644 index 0000000000..8c80419e2e --- /dev/null +++ b/runtime/shims/xbox_bvh_builder.cpp @@ -0,0 +1,285 @@ +// XboxBvhBuilder.dll served by the layer's own acceleration-structure builder (RT-5, boot stop 18). +// +// The package's XboxBvhBuilder.dll builds the game's ray-tracing structures with 52 console compute programs that +// its constructor creates as pipelines on the title's thread. Translated, they take 25-60 s to compile on a cold +// driver cache (31.2 s for one of them on an RTX 4080, 59.5 s for all 52 on an RX 9070 XT, measured in #7231 and +// #7049), longer than the title's startup watchdog (about 30 s), so a first boot ends at the builder. The layer +// already builds XDXR BVH4 structures itself (BuildRaytracingAccelerationStructure on the Vulkan device, D3D-178, +// src/xdxr_build.*), in the node format the game's translated traversal shaders read, and its one pipeline compiles +// in well under a second. So this file serves the DLL's exports with the layer's builder and the DLL is never +// loaded: the loader binds an import to a shim before a bundled module (pe_loader.cpp, Loader::resolve). +// +// The exports, as the executable imports them (7 of the DLL's 12, measured statically on 1.0.2.1: names and call +// counts only). Member functions: `this` comes first (rcx), then the arguments, as for a free function on x64. +// ??0 XboxBvhBuilder(ID3D12Device11*, bool) 1 call site +// ??1 ~XboxBvhBuilder() 1 +// Set64BitMortonCodes(bool) 8 +// GetRaytracingAccelerationStructurePrebuildInfo(const INPUTS*, const XDXR_STREAM_DESC*, PREBUILD_INFO*) 3 +// BuildRaytracingAccelerationStructureBatched2X(GCL6*, UINT, const BATCHED_DESC2*) 6 +// CopyRaytracingAccelerationStructure(GCL4*, UINT64 dest, UINT64 source, COPY_MODE) 2 +// RehydrateRaytracingAccelerationStructureBatched2X(GCL8*, UINT, const BUILD_DESC*, const UINT64*) -> HRESULT 4 +// The Xbox descriptions are the measured layouts of src/xdxr_descs.h (docs/xdxr.md). +// +// What differs from the console builder, on purpose: +// - No programs are created: the constructor only remembers the device. +// - The XDXR stream records (docs/xdxr.md §3) tune the console builder's own heuristics. The layer's builder has +// none of those settings, so a non-empty stream is logged once and otherwise ignored; the structure is still a +// valid BVH of the same geometry. Set64BitMortonCodes is recorded and ignored for the same reason. +// - The DLL throws its validation errors as C++ exceptions (docs/xdxr.md, "Errors are thrown, not returned"). A +// shim must not throw into the title, so an element the DLL would reject is logged and skipped instead. The one +// rule a correct title meets every time is kept: the offline-statistics postbuild type (0x10) is never written. +// - Rehydration is not implemented yet: RehydrateRaytracingAccelerationStructureBatched2X logs once and returns +// E_NOTIMPL. (Planned: rebuild each structure from the source geometry its description carries.) +// +// The builder object belongs to the title, which allocates it with a size this file doesn't know, so nothing is +// written into it: what the shim keeps (the device, the Morton option) lives in a table keyed by its address. +// +// LEONIDA_BVH_BUILDER=console turns the shim off, so the imports bind to the bundled DLL as before (for work on the +// console programs themselves, #5680 and #7318). The variable is read once, when the shim registers. +#include + +#include + +#include +#include +#include +#include +#include +#include +#include + +#include "d3d12_xs_device.h" +#include "shims.h" +#include "../src/xdxr_descs.h" + +namespace { + +namespace xdxr = leonida::xdxr; + +struct BuilderState { + ID3D12Device5* device = nullptr; // a reference held for the builder's lifetime; null if it has no DXR methods + bool morton64 = false; +}; + +std::mutex g_mutex; +std::unordered_map g_builders; + +void log_once(std::atomic& flag, const char* text) { + if (!flag.exchange(true)) std::fprintf(stderr, "[rt] XboxBvhBuilder shim: %s\n", text); +} + +// The PC device behind what the title passed: the real device behind a d3d12_xs device proxy, or the pointer +// itself when it is already a device (a test, or a backend that hands out unwrapped devices). +ID3D12Device5* device5_of(void* device) { + if (!device) return nullptr; + IUnknown* base = rt::d3d12_xs::device_proxy_real_device(device); + if (!base) base = static_cast(device); + ID3D12Device5* out = nullptr; + if (FAILED(base->QueryInterface(IID_PPV_ARGS(&out)))) return nullptr; + return out; +} + +// The command list a title passes, as the backend's own list: a d3d12_xs proxy is unwrapped first, so the PC +// interfaces below are asked of the real list and never of a console-shaped proxy (whose vtable is not the PC one; +// docs/d3d12_command_objects.md §3.5a). Lists aren't wrapped on main yet; a console list proxy joins +// proxy_real_object, which real_object_behind_proxy follows. +IUnknown* real_list(void* list) { + if (!list) return nullptr; + IUnknown* real = rt::d3d12_xs::real_object_behind_proxy(list); + return real ? real : static_cast(list); +} + +ID3D12GraphicsCommandList4* list4_of(void* list) { + IUnknown* real = real_list(list); + if (!real) return nullptr; + ID3D12GraphicsCommandList4* out = nullptr; + if (FAILED(real->QueryInterface(IID_PPV_ARGS(&out)))) return nullptr; + return out; +} + +// ??0XboxBvhBuilder@@QEAA@PEAUID3D12Device11@@_N@Z: XboxBvhBuilder(ID3D12Device11* device, bool). +// Returns `this`, as an MSVC constructor does. The bool's meaning is not measured; it is not needed here. +void* builder_construct(void* self, void* device, bool) { + ID3D12Device5* device5 = device5_of(device); + if (!device5) { + static std::atomic s_logged{false}; + log_once(s_logged, "the device has no ID3D12Device5 (DXR) interface; builds will be skipped"); + } + std::lock_guard lock(g_mutex); + BuilderState& state = g_builders[self]; + if (state.device) state.device->Release(); // the same storage constructed twice without a destructor + state = BuilderState{device5, false}; + return self; +} + +// ??1XboxBvhBuilder@@QEAA@XZ: ~XboxBvhBuilder(). +void builder_destruct(void* self) { + std::lock_guard lock(g_mutex); + auto it = g_builders.find(self); + if (it == g_builders.end()) return; + if (it->second.device) it->second.device->Release(); + g_builders.erase(it); +} + +// ?Set64BitMortonCodes@XboxBvhBuilder@@QEAAX_N@Z: a console-builder option (64-bit Morton keys for its sort). +void builder_set_64bit_morton_codes(void* self, bool enable) { + std::lock_guard lock(g_mutex); + auto it = g_builders.find(self); + if (it != g_builders.end()) it->second.morton64 = enable; +} + +// The builder's device with a reference of the caller's own, taken under the lock, so a destructor on another +// thread can't release it during the call. The caller releases it. +ID3D12Device5* builder_device(void* self) { + std::lock_guard lock(g_mutex); + auto it = g_builders.find(self); + if (it == g_builders.end() || !it->second.device) return nullptr; + it->second.device->AddRef(); + return it->second.device; +} + +void note_stream(const xdxr::StreamDesc& stream) { + if (stream.size_in_bytes == 0 || !stream.stream) return; + static std::atomic s_logged{false}; + log_once(s_logged, "XDXR stream records (console builder settings) are ignored by the layer's builder"); +} + +// ?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_ +// STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z +// The sizes the layer's own builder needs, which are the sizes the layer's build will use. +void builder_prebuild_info(void* self, const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS* inputs, + const xdxr::StreamDesc* stream, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO* info) { + if (!info) return; + *info = {}; + if (!inputs) return; + if (stream) note_stream(*stream); + ID3D12Device5* device = builder_device(self); + if (!device) { + static std::atomic s_logged{false}; + log_once(s_logged, "GetRaytracingAccelerationStructurePrebuildInfo on a builder without a DXR device; sizes are 0"); + return; + } + device->GetRaytracingAccelerationStructurePrebuildInfo(inputs, info); + device->Release(); +} + +// ?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12XBOX_ +// BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z +// Each element is a public build description followed by its postbuild descriptions and a stream (xdxr_descs.h), so +// it is one BuildRaytracingAccelerationStructure on the list. +void builder_build_batched2x(void*, void* list, UINT count, const xdxr::BatchedDesc2* descs) { + static_assert(sizeof(D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC) == 0x30, "the BATCHED_DESC2 prefix"); + static_assert(sizeof(D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC) == sizeof(xdxr::PostbuildInfoDesc), + "postbuild descriptions are the public ones"); + if (count == 0) return; + if (!descs) return; + ID3D12GraphicsCommandList4* list4 = list4_of(list); + if (!list4) { + static std::atomic s_logged{false}; + log_once(s_logged, "BuildRaytracingAccelerationStructureBatched2X: the list has no ID3D12GraphicsCommandList4"); + return; + } + for (UINT i = 0; i < count; ++i) { + const xdxr::BatchedDesc2& element = descs[i]; + note_stream(element.stream); + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC build; + std::memcpy(&build, &element, sizeof(build)); + // The postbuild descriptions, without the offline-statistics type the DLL refuses (docs/xdxr.md §4). + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_DESC kept[16]; + UINT n_kept = 0; + bool skipped_statistics = false; + const auto* post = reinterpret_cast( + element.postbuild_info_descs); + for (UINT p = 0; post && p < element.num_postbuild_info_descs; ++p) { + if (static_cast(post[p].InfoType) == xdxr::kPostbuildInfoOfflineStatistics) { + skipped_statistics = true; + continue; + } + if (n_kept == 16) { + static std::atomic s_logged{false}; + log_once(s_logged, "more than 16 postbuild descriptions in one element; the rest are dropped"); + break; + } + kept[n_kept++] = post[p]; + } + if (skipped_statistics) { + // The DLL throws E_INVALIDARG for this element before any work; the shim skips it the same way. + static std::atomic s_logged{false}; + log_once(s_logged, "an element asked for offline statistics (0x10), which the DLL refuses; element skipped"); + continue; + } + list4->BuildRaytracingAccelerationStructure(&build, n_kept, n_kept ? kept : nullptr); + } + list4->Release(); +} + +// ?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_RAYTRACING_ +// ACCELERATION_STRUCTURE_COPY_MODE@@@Z +void builder_copy(void*, void* list, UINT64 dest, UINT64 source, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE mode) { + ID3D12GraphicsCommandList4* list4 = list4_of(list); + if (!list4) { + static std::atomic s_logged{false}; + log_once(s_logged, "CopyRaytracingAccelerationStructure: the list has no ID3D12GraphicsCommandList4"); + return; + } + list4->CopyRaytracingAccelerationStructure(dest, source, mode); + list4->Release(); +} + +// ?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBUD3D12_ +// BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z -> HRESULT. Not implemented yet (see the header comment). +HRESULT builder_rehydrate_batched2x(void*, void*, UINT, const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC*, + const UINT64*) { + static std::atomic s_logged{false}; + log_once(s_logged, "RehydrateRaytracingAccelerationStructureBatched2X is not implemented yet; E_NOTIMPL"); + return E_NOTIMPL; +} + +constexpr const char kDll[] = "xboxbvhbuilder.dll"; + +const rt::shims::Entry kEntries[] = { + {kDll, "??0XboxBvhBuilder@@QEAA@PEAUID3D12Device11@@_N@Z", reinterpret_cast(&builder_construct)}, + {kDll, "??1XboxBvhBuilder@@QEAA@XZ", reinterpret_cast(&builder_destruct)}, + {kDll, "?Set64BitMortonCodes@XboxBvhBuilder@@QEAAX_N@Z", reinterpret_cast(&builder_set_64bit_morton_codes)}, + {kDll, + "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_" + "STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z", + reinterpret_cast(&builder_prebuild_info)}, + {kDll, + "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12" + "XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z", + reinterpret_cast(&builder_build_batched2x)}, + {kDll, + "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_" + "RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z", + reinterpret_cast(&builder_copy)}, + {kDll, + "?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBU" + "D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z", + reinterpret_cast(&builder_rehydrate_batched2x)}, +}; + +bool shim_enabled() { + char value[16] = {}; + size_t length = 0; + if (getenv_s(&length, value, "LEONIDA_BVH_BUILDER") != 0 || length <= 1) return true; + return _stricmp(value, "console") != 0; +} + +// Registers the table unless LEONIDA_BVH_BUILDER=console asks for the bundled DLL. +struct Registration { + Registration() { + if (!shim_enabled()) return; + static rt::shims::Table table(kEntries, sizeof(kEntries) / sizeof(kEntries[0])); + } +} g_registration; + +} // namespace + +namespace rt::shims { +// For tests: the builders constructed and not destroyed. +size_t xbox_bvh_builder_live_count() { + std::lock_guard lock(g_mutex); + return g_builders.size(); +} +} // namespace rt::shims diff --git a/runtime/shims/xbox_present.cpp b/runtime/shims/xbox_present.cpp index dd5f810cf7..6fbed007d4 100644 --- a/runtime/shims/xbox_present.cpp +++ b/runtime/shims/xbox_present.cpp @@ -1,3 +1,4 @@ +#include #include "xbox_present.h" #include "d3d12_trace.h" @@ -28,10 +29,11 @@ void log_once(bool& done, const char* text) { } // namespace -XboxPresentation::XboxPresentation(std::unique_ptr presenter, leonida::FrameClock* clock) +XboxPresentation::XboxPresentation(std::unique_ptr presenter, leonida::FrameClock* clock, + std::shared_ptr tokens) : presenter_(std::move(presenter)), own_clock_(clock ? nullptr : std::make_unique()), - pacer_(clock ? *clock : *own_clock_) { + pacer_(clock ? *clock : *own_clock_, std::move(tokens)) { // A present waiting for a swapchain image gives up once SuspendX has been called. presenter_->set_abort([this] { return pacer_.suspended(); }); // LEONIDA_SDR_EOTF=gamma22 (or 2.2, any case) decodes SDR with a pure power of 2.2 instead of piecewise sRGB; "srgb" or diff --git a/runtime/shims/xbox_present.h b/runtime/shims/xbox_present.h index 60a317beec..914d707a3d 100644 --- a/runtime/shims/xbox_present.h +++ b/runtime/shims/xbox_present.h @@ -100,7 +100,8 @@ class XboxPresentation { public: // `clock` null: real time (a steady high-resolution timer). Tests pass a leonida::ManualFrameClock, which must // outlive this object. `presenter` is what create_window_presenter returned. - explicit XboxPresentation(std::unique_ptr presenter, leonida::FrameClock* clock = nullptr); + explicit XboxPresentation(std::unique_ptr presenter, leonida::FrameClock* clock = nullptr, + std::shared_ptr tokens = nullptr); ~XboxPresentation(); XboxPresentation(const XboxPresentation&) = delete; XboxPresentation& operator=(const XboxPresentation&) = delete; diff --git a/runtime/shims/xgameruntime.cpp b/runtime/shims/xgameruntime.cpp index 2b44229be4..37ac918d59 100644 --- a/runtime/shims/xgameruntime.cpp +++ b/runtime/shims/xgameruntime.cpp @@ -62,6 +62,8 @@ std::atomic g_runtime_refs{0}; // (no caller in the shipped DLLs to measure), and the classes of the other xgameruntime_*.cpp files through their // query functions; for any other class QueryApiImpl logs the class and interface id and refuses it, so the first boot // with the executable lists the interfaces to implement next. +// +// The thunks look up a sixth name, XErrorReport (served below GetApiVersionImpl), and refuse the runtime without it. struct ApiImplOptions { // InitializeApiImplEx2's fourth argument uint32_t unknown; // documented as always 1 @@ -651,6 +653,7 @@ HRESULT WINAPI GetApiVersionImpl(uint64_t* first, uint64_t* second) { return S_OK; } + // HRESULT XGameRuntimeInitialize(). Reference counted, as in the GDK: each call needs an XGameRuntimeUninitialize. HRESULT __stdcall XGameRuntimeInitialize() { if (g_runtime_refs.fetch_add(1) == 0) std::fprintf(stderr, "[rt] xgameruntime: initialized (offline)\n"); @@ -1365,7 +1368,7 @@ SHIM_TABLE(xgameruntime, XGR(InitializeApiImplEx2), XGR(UninitializeApiImpl), XGR(QueryApiImpl), - XGR(XErrorReport), + XGR(XErrorReport), // looked up with the five above; without it the thunks refuse the runtime // the same runtime through gameplatformservices.dll, which XCurl.dll loads from System32 (GetApiVersionImpl above) {"gameplatformservices.dll", "QueryApiImpl", reinterpret_cast(&QueryApiImpl)}, {"gameplatformservices.dll", "GetApiVersionImpl", reinterpret_cast(&GetApiVersionImpl)}, diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp index 1e286d7120..e8988c0461 100644 --- a/runtime/shims/xmem.cpp +++ b/runtime/shims/xmem.cpp @@ -18,6 +18,7 @@ #include #include +#include #include #include #include @@ -35,6 +36,7 @@ #include "shims.h" #include "startup_trace.h" +#include "../src/title_va_alias.h" #include "xmem.h" namespace { @@ -67,14 +69,27 @@ void note_attributes(const char* api, uint64_t attributes, size_t size, const vo void* allocate_block(size_t size) { return _aligned_malloc(size ? size : 1, kAlign); } +// Every block and range the title gets here is recorded as the title's memory (src/title_va_alias.h): a shader +// address into it can be given a GPU copy, and an address anywhere else cannot. +void* title_block(size_t size) { + void* p = allocate_block(size); + leonida::title_va_aliases().add_title_memory(reinterpret_cast(p), size ? size : 1); + return p; +} + +void free_title_block(void* p) { + if (p) leonida::title_va_aliases().remove_title_memory(reinterpret_cast(p)); + _aligned_free(p); +} + void* __stdcall XMemAlloc(size_t size, uint64_t attributes) { note_attributes("XMemAlloc", attributes, size, _ReturnAddress()); - return allocate_block(size); + return title_block(size); } void __stdcall XMemFree(void* p, uint64_t attributes) { note_attributes("XMemFree", attributes, kNoSize, _ReturnAddress()); - _aligned_free(p); + free_title_block(p); } // XMemAllocDefault / XMemFreeDefault: the GDK's own allocator behind XMemAlloc and XMemFree, which a title that hooks @@ -83,12 +98,12 @@ void __stdcall XMemFree(void* p, uint64_t attributes) { // released by either free. void* __stdcall XMemAllocDefault(size_t size, uint64_t attributes) { note_attributes("XMemAllocDefault", attributes, size, _ReturnAddress()); - return allocate_block(size); + return title_block(size); } void __stdcall XMemFreeDefault(void* p, uint64_t attributes) { note_attributes("XMemFreeDefault", attributes, kNoSize, _ReturnAddress()); - _aligned_free(p); + free_title_block(p); } // BOOL XMemIsToolsMemAvailable(void). The measured title calls it from one helper, which six out-of-memory paths reach @@ -239,14 +254,10 @@ struct Window { struct Section { HANDLE handle; - void* scratch; - explicit Section(HANDLE h) : handle(h), scratch(MapViewOfFile(h, FILE_MAP_WRITE, 0, 0, 0)) {} + explicit Section(HANDLE h) : handle(h) {} Section(const Section&) = delete; Section& operator=(const Section&) = delete; - ~Section() { - if (scratch) UnmapViewOfFile(scratch); - CloseHandle(handle); - } + ~Section() { CloseHandle(handle); } }; struct PhysicalPage { @@ -266,28 +277,16 @@ std::map g_windows; // base -> window std::unordered_map g_pages; // page number -> backing std::vector g_free_slots; uint64_t g_next_slot = 1; -struct MappedPage { - uint64_t page; - std::shared_ptr
section; - uint64_t offset; -}; - -std::unordered_map g_mapped; -SRWLOCK g_fault_lock = SRWLOCK_INIT; - -struct FaultLockExclusive { - FaultLockExclusive() { AcquireSRWLockExclusive(&g_fault_lock); } - ~FaultLockExclusive() { ReleaseSRWLockExclusive(&g_fault_lock); } - FaultLockExclusive(const FaultLockExclusive&) = delete; - FaultLockExclusive& operator=(const FaultLockExclusive&) = delete; -}; - -struct FaultLockShared { - FaultLockShared() { AcquireSRWLockShared(&g_fault_lock); } - ~FaultLockShared() { ReleaseSRWLockShared(&g_fault_lock); } - FaultLockShared(const FaultLockShared&) = delete; - FaultLockShared& operator=(const FaultLockShared&) = delete; +// A mapped run: `count` pages of one section at consecutive offsets, mapped as one view at its base. One view per run +// rather than per page: under Wine each view costs a placeholder split and a section map whose time grows with the +// number of views, and the retail title maps about 100,000 pages in one call. +struct View { + uint64_t count; + std::shared_ptr
section; // kept for remapping part of the run after its pages are freed + uint64_t offset; // section offset of the first page + DWORD protect; }; +std::map g_views; // view base -> view // With g_phys_mutex held. A window replaces every window it overlaps: the title released those regions (with // kernel32!VirtualFree, which the shim does not see) before the host could hand the addresses out again. @@ -346,8 +345,18 @@ PVOID reserve_placeholder(void* address, SIZE_T size, SIZE_T alignment) { // XMemMapPhysicalPages. The guest page size sets the alignment and rounding of the region; the host's own pages stay // 4 KiB (host large pages need SeLockMemoryPrivilege). A 2 MiB region the host places is reserved 2 MiB-aligned through // VirtualAlloc2. +void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect); + void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect) { note_attributes("XMemVirtualAlloc", attributes, size, _ReturnAddress()); + void* result = xmem_virtual_alloc(address, size, allocation_type, attributes, protect); + // The title's memory (src/title_va_alias.h). Never forgotten: a released range is no longer committed, which + // the copy also checks. + if (result) leonida::title_va_aliases().add_title_memory(reinterpret_cast(result), size); + return result; +} + +void* xmem_virtual_alloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect) { if (size == 0) { SetLastError(ERROR_INVALID_PARAMETER); return nullptr; @@ -451,19 +460,74 @@ void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, return VirtualAlloc(address, size, host_type, host_prot); } -// With g_phys_mutex held. Unmaps the page at `address` if one is mapped there; the address becomes a placeholder again. -bool unmap_page(uintptr_t address) { - const FaultLockExclusive lock; - const auto it = g_mapped.find(address); - if (it == g_mapped.end()) return true; - if (!placeholder_api().unmap_view2(GetCurrentProcess(), reinterpret_cast(address), - MEM_PRESERVE_PLACEHOLDER)) { - return false; +// With g_phys_mutex held. Maps `view` at the 64 KiB-aligned `address`, which holds no mapped page. MEM_REPLACE_PLACEHOLDER +// needs the view to fill one placeholder exactly, and earlier partial unmaps can leave several host placeholders in one +// run, so the run is mapped as one view per placeholder it spans. Views are capped at kMaxViewPages so that unmapping a +// page inside a long run only remaps the rest of one capped view, not the whole run. +constexpr uint64_t kMaxViewPages = 1024; // 64 MiB + +bool map_view(uintptr_t address, const View& view) { + for (uint64_t mapped = 0; mapped < view.count;) { + const uintptr_t base = address + mapped * kPhysicalPageSize; + void* const target = reinterpret_cast(base); + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(target, &info, sizeof(info)) || info.State != MEM_RESERVE || + info.RegionSize < kPhysicalPageSize) { + SetLastError(ERROR_INVALID_ADDRESS); + return false; + } + const uint64_t available = info.RegionSize / kPhysicalPageSize; + const uint64_t remaining = view.count - mapped; + const uint64_t count = (std::min)({available, remaining, kMaxViewPages}); + const SIZE_T size = static_cast(count * kPhysicalPageSize); + const uint64_t offset = view.offset + mapped * kPhysicalPageSize; + if (!isolate_placeholder(target, size)) return false; + if (!placeholder_api().map_view3(view.section->handle, GetCurrentProcess(), target, offset, size, + MEM_REPLACE_PLACEHOLDER, view.protect, nullptr, 0)) { + return false; + } + g_views.emplace(base, View{count, view.section, offset, view.protect}); + mapped += count; } - g_mapped.erase(it); return true; } +// With g_phys_mutex held. Unmaps every page in [start, end); the addresses become placeholders again. A view that +// reaches outside the range is unmapped whole, and its pages outside the range are mapped again, so neighbours keep +// their pages. +bool unmap_range(uintptr_t start, uintptr_t end) { + auto it = g_views.upper_bound(start); + if (it != g_views.begin()) { + const auto prev = std::prev(it); + if (prev->first + prev->second.count * kPhysicalPageSize > start) it = prev; + } + while (it != g_views.end() && it->first < end) { + const uintptr_t base = it->first; + const View view = it->second; + const uintptr_t view_end = base + view.count * kPhysicalPageSize; + if (!placeholder_api().unmap_view2(GetCurrentProcess(), reinterpret_cast(base), + MEM_PRESERVE_PLACEHOLDER)) { + return false; + } + it = g_views.erase(it); + if (base < start) { + View left = view; + left.count = (start - base) / kPhysicalPageSize; + if (!map_view(base, left)) return false; + } + if (view_end > end) { + const uint64_t skipped = (end - base) / kPhysicalPageSize; + View right = view; + right.count = view.count - skipped; + right.offset += skipped * kPhysicalPageSize; + return map_view(end, right); // the last view the range touches + } + } + return true; +} + +bool unmap_page(uintptr_t address) { return unmap_range(address, address + kPhysicalPageSize); } + // With g_phys_mutex held. Maps physical page `page` (0: unmap) at the 64 KiB-aligned `address`, replacing what was // mapped there. The caller has found the window. bool map_page(uintptr_t address, uint64_t page, DWORD protect) { @@ -474,87 +538,18 @@ bool map_page(uintptr_t address, uint64_t page, DWORD protect) { SetLastError(ERROR_INVALID_PARAMETER); return false; } - void* const target = reinterpret_cast(address); - if (!isolate_placeholder(target, kPhysicalPageSize)) return false; - const FaultLockExclusive lock; - void* const view = placeholder_api().map_view3(it->second.section->handle, GetCurrentProcess(), target, - it->second.offset, kPhysicalPageSize, MEM_REPLACE_PLACEHOLDER, - protect, nullptr, 0); - if (!view) return false; - g_mapped[address] = MappedPage{page, it->second.section, it->second.offset}; - return true; -} - -enum class PageCommit { not_ours, committed_before, committed_now, failed }; - -PageCommit commit_mapped_page(uintptr_t address, uintptr_t accessed, DWORD& protect) { - const auto it = g_mapped.find(address); - if (it == g_mapped.end() || !it->second.section->scratch) return PageCommit::not_ours; - MEMORY_BASIC_INFORMATION info{}; - if (!VirtualQuery(reinterpret_cast(accessed), &info, sizeof(info)) || info.Type != MEM_MAPPED) { - return PageCommit::not_ours; - } - if (info.State == MEM_COMMIT) { - protect = info.Protect; - return PageCommit::committed_before; - } - void* const backing = static_cast(it->second.section->scratch) + it->second.offset; - return VirtualAlloc(backing, kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE) ? PageCommit::committed_now - : PageCommit::failed; -} - -bool access_allowed(DWORD protect, ULONG_PTR access) { - if (protect & PAGE_GUARD) return false; - switch (protect & 0xff) { - case PAGE_EXECUTE_READWRITE: - case PAGE_EXECUTE_WRITECOPY: - return true; - case PAGE_READWRITE: - case PAGE_WRITECOPY: - return access != 8; - case PAGE_EXECUTE_READ: - return access != 1; - case PAGE_READONLY: - return access == 0; - case PAGE_EXECUTE: - return access == 8; - default: - return false; - } -} - -LONG CALLBACK physical_page_fault(EXCEPTION_POINTERS* info) { - thread_local bool busy = false; - const EXCEPTION_RECORD* record = info ? info->ExceptionRecord : nullptr; - if (busy || !record || record->ExceptionCode != EXCEPTION_ACCESS_VIOLATION || record->NumberParameters < 2) { - return EXCEPTION_CONTINUE_SEARCH; - } - busy = true; - const uintptr_t accessed = static_cast(record->ExceptionInformation[1]); - const uintptr_t address = accessed & ~static_cast(kPhysicalPageSize - 1); - DWORD protect = 0; - PageCommit result; - { - const FaultLockShared lock; - result = commit_mapped_page(address, accessed, protect); - } - busy = false; - if (result == PageCommit::committed_now) return EXCEPTION_CONTINUE_EXECUTION; - if (result == PageCommit::committed_before && access_allowed(protect, record->ExceptionInformation[0])) { - return EXCEPTION_CONTINUE_EXECUTION; - } - return EXCEPTION_CONTINUE_SEARCH; -} - -bool install_physical_page_fault_handler() { - static const bool installed = AddVectoredExceptionHandler(1, &physical_page_fault) != nullptr; - return installed; + return map_view(address, View{1, it->second.section, it->second.offset, protect}); } // Two of the measured windows are reserved PAGE_NOACCESS for the CPU and the GPU alike; pages mapped there are still // GPU memory, which the D3D12 layer reads on the CPU. DWORD view_protect(const Window& window) { - return window.protect == PAGE_NOACCESS ? PAGE_READWRITE : window.protect; + // A view takes no cache modifier. Three of the measured windows carry PAGE_WRITECOMBINE (0x400) next to + // PAGE_READWRITE: Wine's MapViewOfFile3 refuses it, and PAGE_NOCACHE, with ERROR_INVALID_PARAMETER, and on Windows + // the view comes out write-combined, which an import of those pages as a GPU buffer refuses (#7218). PAGE_GUARD + // is an access alarm, not a cache modifier, so it is left as the window has it. + const DWORD protect = window.protect & ~static_cast(PAGE_WRITECOMBINE | PAGE_NOCACHE); + return protect == PAGE_NOACCESS ? PAGE_READWRITE : protect; } bool aligned_page_address(uintptr_t address) { return (address & (kPhysicalPageSize - 1)) == 0; } @@ -581,7 +576,7 @@ void note_physical_attributes(uint64_t attributes, uint64_t count, const void* c // a 32-bit BOOL. After success every caller compares the count with the one it asked for and frees the pages if they // differ, so the count is in/out. // -// Each call is backed by one pagefile-backed section of count * 64 KiB: committed (charged) on touch, given physical +// Each call is backed by one pagefile-backed section of count * 64 KiB: committed (charged) at once, given physical // memory as it is touched, zero-filled. Pages keep their contents while unmapped or mapped elsewhere, and one page can // be mapped at several addresses. ASSUMPTION: the attribute word (memory type, perhaps the page size) is not decoded; // every page is 64 KiB, which all four callers' arithmetic agrees with. @@ -600,23 +595,14 @@ BOOL WINAPI XMemAllocatePhysicalPages(uint64_t attributes, uint64_t* page_count, SetLastError(ERROR_NOT_ENOUGH_MEMORY); return FALSE; } - if (!install_physical_page_fault_handler()) { - *page_count = 0; - SetLastError(ERROR_NOT_SUPPORTED); - return FALSE; - } const uint64_t bytes = count * kPhysicalPageSize; // below 2^37: count is below 2^21 - const HANDLE handle = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_RESERVE, + const HANDLE handle = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_COMMIT, static_cast(bytes >> 32), static_cast(bytes), nullptr); if (!handle) { *page_count = 0; return FALSE; } const auto section = std::make_shared
(handle); - if (!section->scratch) { - *page_count = 0; - return FALSE; - } for (uint64_t i = 0; i < count; ++i) { uint64_t slot; if (!g_free_slots.empty()) { @@ -659,8 +645,9 @@ BOOL WINAPI XMemFreePhysicalPages(uint64_t page_count, const uint64_t* page_arra // or null to unmap that many (four calls at shutdown). Callers test the 64-bit result for zero, so it is the address on // success. A page number of 0 in the array unmaps that one page. // -// Each page is its own view (MapViewOfFile3 into a 64 KiB placeholder), so any page can be remapped or unmapped later -// without touching its neighbours. A failure part-way leaves the pages before it mapped. +// Consecutive pages of one allocation are mapped as one view (MapViewOfFile3 into a placeholder of their size); a +// page remapped or unmapped later splits its view, and its neighbours stay mapped. The range is unmapped first, so a +// page number that is not a live page fails with the pages before it mapped and the rest of the range unmapped. void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint64_t* page_array) { const uintptr_t start = reinterpret_cast(address); if (!aligned_page_address(start) || page_count > (std::numeric_limits::max)() / kPhysicalPageSize || @@ -673,20 +660,36 @@ void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint return nullptr; } const std::lock_guard lock(g_phys_mutex); - if (!page_array) { - for (uint64_t i = 0; i < page_count; ++i) { - if (!unmap_page(start + i * kPhysicalPageSize)) return nullptr; - } - return address; - } + const uintptr_t end = start + page_count * kPhysicalPageSize; + if (!page_array) return unmap_range(start, end) ? address : nullptr; const Window* const window = find_window(start, page_count * kPhysicalPageSize); if (!window) { SetLastError(ERROR_INVALID_ADDRESS); return nullptr; } const DWORD protect = view_protect(*window); - for (uint64_t i = 0; i < page_count; ++i) { - if (!map_page(start + i * kPhysicalPageSize, page_array[i], protect)) return nullptr; + if (!unmap_range(start, end)) return nullptr; + for (uint64_t i = 0; i < page_count;) { + if (page_array[i] == 0) { + ++i; + continue; + } + const auto it = g_pages.find(page_array[i]); + if (it == g_pages.end()) { + SetLastError(ERROR_INVALID_PARAMETER); + return nullptr; + } + View view{1, it->second.section, it->second.offset, protect}; + while (i + view.count < page_count) { + const auto next = g_pages.find(page_array[i + view.count]); + if (next == g_pages.end() || next->second.section != view.section || + next->second.offset != view.offset + view.count * kPhysicalPageSize) { + break; + } + ++view.count; + } + if (!map_view(start + i * kPhysicalPageSize, view)) return nullptr; + i += view.count; } return address; } @@ -792,63 +795,42 @@ constexpr DWORD kMemGraphics = 0x10000000; constexpr DWORD kMemTitle = 0x40000000; LPVOID WINAPI TitleVirtualAlloc(LPVOID address, SIZE_T size, DWORD allocation_type, DWORD protect) { - return VirtualAlloc(address, size, allocation_type & ~(kMemGraphics | kMemTitle), host_protect(protect)); + LPVOID result = VirtualAlloc(address, size, allocation_type & ~(kMemGraphics | kMemTitle), host_protect(protect)); + if (result) leonida::title_va_aliases().add_title_memory(reinterpret_cast(result), size); + return result; } } // namespace namespace rt::xmem { -bool commit_physical_range(const void* address, size_t size) { +// main's xmem commits physical pages on first touch and exposes these two for code that must see them committed +// (slot 133's import, d3d12_xmem_placed_test). Here a physical page is committed when it is allocated, so there is +// nothing to do: the range only has to be mapped, readable memory, and the page array non-null. +bool commit_physical_range(const void* address, std::size_t size) { if (size == 0) return true; - const uintptr_t start = reinterpret_cast(address); - if (start > (std::numeric_limits::max)() - (size - 1)) { - SetLastError(ERROR_INVALID_PARAMETER); - return false; - } - const uintptr_t mask = ~static_cast(kPhysicalPageSize - 1); - const uintptr_t first = start & mask; - const uintptr_t pages = (((start + (size - 1)) & mask) - first) / kPhysicalPageSize + 1; - const FaultLockShared lock; - for (uintptr_t i = 0; i < pages; ++i) { - DWORD protect = 0; - const uintptr_t page = first + i * kPhysicalPageSize; - if (commit_mapped_page(page, page, protect) == PageCommit::failed) return false; + const auto* at = static_cast(address); + const auto* const end = at + size; + while (at < end) { + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(at, &info, sizeof(info)) || info.State != MEM_COMMIT) { + SetLastError(ERROR_INVALID_ADDRESS); + return false; + } + at = static_cast(info.BaseAddress) + info.RegionSize; } return true; } -bool commit_physical_pages(const uint64_t* page_array, size_t count) { - if (count == 0) return true; - if (!page_array) { +bool commit_physical_pages(const std::uint64_t* page_array, std::size_t count) { + if (count && !page_array) { SetLastError(ERROR_INVALID_PARAMETER); return false; } - const std::lock_guard lock(g_phys_mutex); - size_t first = 0; - while (first < count) { - const auto it = g_pages.find(page_array[first]); - if (it == g_pages.end() || !it->second.section->scratch) { - SetLastError(ERROR_INVALID_PARAMETER); - return false; - } - size_t last = first + 1; - while (last < count) { - const auto next = g_pages.find(page_array[last]); - if (next == g_pages.end() || next->second.section != it->second.section || - next->second.offset != it->second.offset + (last - first) * kPhysicalPageSize) { - break; - } - ++last; - } - void* const backing = static_cast(it->second.section->scratch) + it->second.offset; - if (!VirtualAlloc(backing, (last - first) * kPhysicalPageSize, MEM_COMMIT, PAGE_READWRITE)) return false; - first = last; - } return true; } -} +} // namespace rt::xmem #define TITLE_VIRTUAL_ALLOC(dll) {dll, "VirtualAlloc", reinterpret_cast(&TitleVirtualAlloc)} diff --git a/runtime/src/command_list.h b/runtime/src/command_list.h index 7c5c09e0ac..595110f360 100644 --- a/runtime/src/command_list.h +++ b/runtime/src/command_list.h @@ -587,6 +587,9 @@ enum class IndirectKind : std::uint8_t { draw = 0, draw_indexed = 1, dispatch = 2, + // D3D12_DISPATCH_MESH_ARGUMENTS. Created on a device with mesh shaders; ExecuteIndirect with it records nothing + // yet (the replay is #3777's), so a title that only creates such a signature at startup goes on. + dispatch_mesh = 3, }; struct ExecuteIndirect { diff --git a/runtime/src/frame_pacer.h b/runtime/src/frame_pacer.h index fa9c20df1d..5de8e9b79d 100644 --- a/runtime/src/frame_pacer.h +++ b/runtime/src/frame_pacer.h @@ -37,7 +37,9 @@ #include #include #include +#include #include +#include namespace leonida { @@ -143,9 +145,19 @@ struct FrameStatistic { float percent_scanned = 0.0f; // display entries: where the scan was when the frame came up (0 at a vblank) }; +class FrameTokenSource { +public: + std::uint64_t issue() { return last_.fetch_add(1, std::memory_order_acq_rel) + 1; } + std::uint64_t issued() const { return last_.load(std::memory_order_acquire); } + +private: + std::atomic last_{0}; +}; + class FramePacer { public: - explicit FramePacer(FrameClock& clock) : clock_(clock) { + explicit FramePacer(FrameClock& clock, std::shared_ptr tokens = nullptr) + : clock_(clock), tokens_(tokens ? std::move(tokens) : std::make_shared()) { clock_.set_wake([this] { { std::lock_guard guard(mutex_); } cv_.notify_all(); @@ -263,7 +275,7 @@ class FramePacer { std::lock_guard guard(mutex_); if (issue) *issue = TokenIssue::none; if (suspended_) return pacer_hr::invalid_state; - if (token > issued_) return pacer_hr::invalid_arg; + if (token > tokens_->issued()) return pacer_hr::invalid_arg; if (issue) { if (token == 0) *issue = TokenIssue::null_token; else if (token == last_presented_) *issue = TokenIssue::repeated; @@ -357,7 +369,8 @@ class FramePacer { } bool suspended() const { std::lock_guard guard(mutex_); return suspended_; } - std::uint64_t tokens_issued() const { std::lock_guard guard(mutex_); return issued_; } + std::uint64_t tokens_issued() const { return tokens_->issued(); } + const std::shared_ptr& token_source() const { return tokens_; } std::uint32_t frames_in_flight() { std::lock_guard guard(mutex_); retire_locked(clock_.now_us()); @@ -408,7 +421,7 @@ class FramePacer { const std::uint64_t now = clock_.now_us(); retire_locked(now); if (uncapped_) { // no vblank grid and no latency throttle: a token at once, due now - *token = ++issued_; + *token = tokens_->issue(); Record record; record.token = *token; record.origin_us = now; @@ -426,7 +439,7 @@ class FramePacer { const std::int64_t newest = std::int64_t((now - first) / period_us_); const std::int64_t origin = std::max(next, newest); last_origin_ = origin; - *token = ++issued_; + *token = tokens_->issue(); Record record; record.token = *token; record.origin_us = first + std::uint64_t(origin) * period_us_; @@ -457,7 +470,7 @@ class FramePacer { std::uint32_t offset_us_ = 0; std::uint64_t epoch_us_ = 0; std::int64_t last_origin_ = 0; // origin 0 is the epoch itself, which has passed - std::uint64_t issued_ = 0; + std::shared_ptr tokens_; std::uint64_t last_presented_ = 0; std::uint64_t immediate_presents_ = 0; std::deque pending_; diff --git a/runtime/src/gfx10_descriptors.h b/runtime/src/gfx10_descriptors.h index b225cddef0..e6fc4df6d4 100644 --- a/runtime/src/gfx10_descriptors.h +++ b/runtime/src/gfx10_descriptors.h @@ -218,6 +218,7 @@ struct FormatRow { }; inline constexpr Swizzle channels_r{select_x, select_zero, select_zero, select_one}; +inline constexpr Swizzle channels_a{select_zero, select_zero, select_zero, select_x}; inline constexpr Swizzle channels_rg{select_x, select_y, select_zero, select_one}; inline constexpr Swizzle channels_rgb{select_x, select_y, select_z, select_one}; inline constexpr Swizzle channels_rgba = identity_swizzle; @@ -227,6 +228,9 @@ inline constexpr Swizzle channels_abgr{select_w, select_z, select_y, select_x}; inline constexpr FormatRow format_table[] = { {1, VK_FORMAT_R8_UNORM, channels_r}, // GFX10_FORMAT_8_UNORM +#ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME + {1, VK_FORMAT_A8_UNORM_KHR, channels_a}, // GFX10_FORMAT_8_UNORM (an A8 render target) +#endif {2, VK_FORMAT_R8_SNORM, channels_r}, // GFX10_FORMAT_8_SNORM {3, VK_FORMAT_R8_USCALED, channels_r}, // GFX10_FORMAT_8_USCALED {4, VK_FORMAT_R8_SSCALED, channels_r}, // GFX10_FORMAT_8_SSCALED diff --git a/runtime/src/main.cpp b/runtime/src/main.cpp index 098a8ee400..63bd016e8a 100644 --- a/runtime/src/main.cpp +++ b/runtime/src/main.cpp @@ -52,6 +52,16 @@ const char* binding_name(rt::Binding b) { } } +// Module TLS index 0 for the game's executable (rt::reserve_tls_index0), from the CRT's initializer table: .CRT$XCT +// runs after the C runtime is set up and before every C++ dynamic initializer of gta6rt (.CRT$XCU), so before any of +// gta6rt's code can have started a thread. The frames above it (wmainCRTStartup, __scrt_common_main_seh, _initterm) +// hold no TLS slot address. The result is read again where an image is run. +void __cdecl reserve_tls_index0_at_start() { rt::reserve_tls_index0(); } +#pragma section(".CRT$XCT", read) +extern "C" __declspec(allocate(".CRT$XCT")) void(__cdecl* const gta6rt_reserve_tls_index0)() = + reserve_tls_index0_at_start; +#pragma comment(linker, "/INCLUDE:gta6rt_reserve_tls_index0") + int usage() { std::fprintf(stderr, "usage: gta6rt --dry-run [--game-dir DIR] [--overlay DIR] [--mods DIR] [--archetype-lookup RVA[,ARG]] [--view-mode-getter RVA] [--trace FILE]\n" @@ -186,6 +196,20 @@ int wmain(int argc, wchar_t** argv) { try { rt::Loader loader(game_dir); rt::Module& main_module = loader.load(image); // maps, binds and installs TLS; runs no image code + // An executable with TLS that did not get index 0: its /GA code would read and write the TLS in slot 0, which + // is gta6rt's own (or another executable's), so no code of it may run. + const auto* main_nt = reinterpret_cast( + main_module.base + reinterpret_cast(main_module.base)->e_lfanew); + const bool main_is_exe = (main_nt->FileHeader.Characteristics & IMAGE_FILE_DLL) == 0; + if ((init || run) && main_is_exe && main_module.tls_slot != rt::kNoTlsIndex && main_module.tls_index != 0) { + std::string why; + if (rt::reserve_tls_index0(&why)) why = "another mapped executable holds it"; + std::fprintf(stderr, + "error: %s cannot have module TLS index 0 (%s); code built with /GA would read and write " + "another module's TLS through slot 0, so it is not run\n", + main_module.name.c_str(), why.c_str()); + return 1; + } // The mods' archetype swaps (docs/modding.md): hooked here, before any image code runs, when the lookup's RVA // for this executable is given. The count of redirected calls shows whether the RVA is the real lookup. if (view_mode_getter_rva) { diff --git a/runtime/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index 5e55ac1f9c..c6e62c73a2 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -126,8 +126,29 @@ IMAGE_TLS_DIRECTORY64* tls_directory(Module& m) { // reuses that index for the mapped image. When more than one manually mapped module uses static TLS at once, the loader // clones gta6rt_tls_host.dll to a per-process temporary path on demand and loads it, so the OS assigns an independent // module TLS index for each simultaneous module (up to kMaxMappedTlsModules). +// +// A mapped executable is different: MSVC code built with /GA (an EXE-only optimisation) skips _tls_index and reads +// TEB->ThreadLocalStoragePointer[0] directly (mov rax, gs:[58h]; mov rax, [rax]), because Windows always gives the +// process executable module TLS index 0. Measured with a `thread_local int v = 42;` EXE built /O2 /GA /MD: natively +// tls_index=0 value=42; mapped with a helper index (6) the code still read slot 0 and printed value=0. Index 0 +// belongs to the runtime's own EXE (gta6rt.exe: a 1398-byte template when measured, no TLS callbacks; so does each +// test EXE that links this file), and every TLS read in its disassembly goes through _tls_index (the only direct +// gs:[58h] read is module_tls_slots below, which wants the array itself). reserve_tls_index0 therefore moves the owner +// off index 0, once, at process start: it loads the home clone (make_home_clone_image), whose TLS template is a copy of +// the owner's, and on the calling thread swaps slots 0 and home and writes home into the owner's _tls_index. From then on every thread the OS +// starts has a fresh copy of the owner's template at home, which is where the owner looks, from its first instruction: +// nothing has to run on a new thread first. Slot 0 holds a block nobody reads, which the mapped executable's copy +// replaces (kMainImageSlot) exactly as a DLL's copy replaces a helper's, and the OS frees both slots at thread exit. +// It has to happen before any other thread has run the owner's code: MSVC keeps &ThreadLocalStoragePointer[_tls_index] +// across calls (zlib_inflate in shader_library.h saves it at [rbp-80h] across memset, push_back and inflate_codes, then +// reads _Init_thread_epoch through it), so a running thread cannot be moved safely, wherever it is stopped. Such a +// thread's TLS would also stay where it was, at index 0. constexpr DWORD kMaxModuleTlsSlots = 64; constexpr size_t kMaxMappedTlsModules = 16; +// The slot for a mapped executable, which reads module TLS index 0 (see above). Only one at a time; a second +// executable mapped while one is live gets an ordinary helper slot. kTlsSlotCount sizes the per-slot tables. +constexpr size_t kMainImageSlot = kMaxMappedTlsModules; +constexpr size_t kTlsSlotCount = kMaxMappedTlsModules + 1; void** module_tls_slots() { return reinterpret_cast(__readgsqword(0x58)); } void __cdecl on_host_thread_event(DWORD reason); @@ -135,6 +156,7 @@ void __cdecl on_host_thread_event(DWORD reason); struct TlsHostModule { HMODULE module = nullptr; DWORD index = TLS_OUT_OF_INDEXES; + bool hooked = false; // its DllMain reports thread events to on_host_thread_event }; std::filesystem::path tls_host_base_path() { @@ -167,20 +189,39 @@ struct TlsCloneRecord { std::mutex g_tls_alloc_mutex; std::array g_tls_hosts{}; -std::array, kMaxMappedTlsModules> g_tls_slot_owners{}; -std::array, kMaxMappedTlsModules> g_tls_slot_generations{}; +std::array, kTlsSlotCount> g_tls_slot_owners{}; +std::array, kTlsSlotCount> g_tls_slot_generations{}; std::atomic g_next_tls_generation{1}; -std::vector g_tls_clones; +// Allocated with the first clone and never destroyed: cleanup_tls_clones_at_exit runs from the atexit table, and a +// static vector's destructor (registered when its dynamic initializer ran) could run before it. Under +// g_tls_alloc_mutex, as are its records. +std::vector* g_tls_clones = nullptr; + +// The move of module TLS index 0 (see kMainImageSlot): done at most once, by reserve_tls_index0 under +// g_tls_alloc_mutex. `why` is the reason it was not done, for the executable that then maps with a helper index. +// Constant-initialized only (no std::string): gta6rt reserves from a CRT initializer that runs before the dynamic +// initializers of this file, which would otherwise reset what it wrote. +struct Index0Move { + bool moved = false; + bool traced = false; // the startup trace opens after the move; the first executable map reports it + TlsHostModule home; // the clone whose index holds the owner's TLS from now on; never freed + char owner[260] = {}; // UTF-8 file name of the image that held index 0 + char why[160] = "reserve_tls_index0 was not called at process start"; +}; +Index0Move g_index0; -// Frees every TLS helper clone this process loaded and deletes its files. load() registers the wrapper with atexit; -// the --run path in main() must also call this directly before ExitProcess, which skips the atexit table. Call it -// only when no mapped code can run again: it unmaps the helper images. +// Frees every TLS helper clone recorded for a mapped DLL's slot and deletes its files. ensure_tls_host registers the +// wrapper with atexit when it records the first clone; the --run path in main() must also call this directly before +// ExitProcess, which skips the atexit table. Call it only when no mapped code can run again: it unmaps the helper +// images. The home clone is not recorded (reserve_index0): it stays loaded, so its file outlives the process and the +// next run's sweep deletes it. void cleanup_tls_clones_internal() { - for (const auto& rec : g_tls_clones) { + if (!g_tls_clones) return; + for (const auto& rec : *g_tls_clones) { if (rec.module) FreeLibrary(rec.module); if (!rec.path.empty()) DeleteFileW(rec.path.c_str()); } - g_tls_clones.clear(); + g_tls_clones->clear(); } void cleanup_tls_clones_at_exit() { cleanup_tls_clones_internal(); } @@ -204,10 +245,14 @@ DWORD clone_owner_pid(const wchar_t* name) { bool process_alive(DWORD pid) { // PROCESS_QUERY_LIMITED_INFORMATION needs no handle rights a normal process could deny; a failure means the // process is gone. A still-mapped or still-open file is caught by the checks below even for a misjudged PID. + // OpenProcess also succeeds on a process that has ended while another process still holds a handle to it (a + // parent waiting on its exit code, as CMake's execute_process does), so the exit code decides. HANDLE p = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, FALSE, pid); if (!p) return false; + DWORD code = 0; + const bool alive = !GetExitCodeProcess(p, &code) || code == STILL_ACTIVE; CloseHandle(p); - return true; + return alive; } // Deletes clones left behind by processes that have exited. Deletion is scoped to files whose owner is gone: a @@ -262,45 +307,66 @@ TlsHostModule load_tls_host_image(const std::filesystem::path& path, bool hook_t if (hook_thread_events) { // Only the primary helper reports thread attach/detach events; on_host_thread_event iterates all active slots. using SetThreadEvent = void(__cdecl*)(void(__cdecl*)(DWORD)); - if (auto set = reinterpret_cast(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event"))) + auto set = reinterpret_cast(GetProcAddress(host.module, "gta6rt_tls_host_set_thread_event")); + if (set) { set(&on_host_thread_event); + host.hooked = true; + } } return host; } -// Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the Windows loader lock). -TlsHostModule ensure_tls_host(size_t slot) { - if (slot >= kMaxMappedTlsModules) return {}; - if (g_tls_hosts[slot].index != TLS_OUT_OF_INDEXES) return g_tls_hosts[slot]; - +// The primary helper: slot 0's index, and the only helper whose DllMain reports thread events (on_host_thread_event +// covers every slot). Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the +// Windows loader lock). +// A helper without the thread-event export is refused: no thread started later would get its copies. +bool ensure_primary_tls_host() { + if (g_tls_hosts[0].index != TLS_OUT_OF_INDEXES) return true; const std::filesystem::path primary = tls_host_base_path(); - if (primary.empty()) return {}; - - if (slot == 0) { - g_tls_hosts[0] = load_tls_host_image(primary, true); - return g_tls_hosts[0]; - } - - // Ensure slot 0 is loaded first so thread attach/detach events are hooked. - if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) { - g_tls_hosts[0] = load_tls_host_image(primary, true); - if (g_tls_hosts[0].index == TLS_OUT_OF_INDEXES) return {}; + if (primary.empty()) return false; + TlsHostModule host = load_tls_host_image(primary, true); + if (host.index != TLS_OUT_OF_INDEXES && !host.hooked) { + FreeLibrary(host.module); + return false; } + g_tls_hosts[0] = host; + return host.index != TLS_OUT_OF_INDEXES; +} +// Copies gta6rt_tls_host.dll (or writes `image`, a changed copy of it) to "leonida_tls_host__.dll" in the +// clone directory and loads it, so the OS gives the copy an index of its own. On failure the file is gone again and +// the result has no index. The caller records the clone (g_tls_clones) if it is to be freed at exit. Same locking rule +// as ensure_primary_tls_host. +TlsHostModule load_tls_host_clone(const std::wstring& tag, std::filesystem::path& clone_path, + const std::vector* image = nullptr) { + const std::filesystem::path primary = tls_host_base_path(); + if (primary.empty()) return {}; // Clone gta6rt_tls_host.dll to a distinct path using CopyFileW (Wine 9 lacks CopyFile2 used by std::filesystem). const std::filesystem::path dir = tls_host_clone_dir(); static bool swept = false; if (!swept) { swept = true; sweep_stale_tls_clones(dir); - std::atexit(&cleanup_tls_clones_at_exit); } - const std::wstring name = - L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + std::to_wstring(slot) + L".dll"; - const std::filesystem::path clone_path = dir / name; + const std::wstring name = L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_" + tag + L".dll"; + clone_path = dir / name; // The staging name must not match the sweep pattern, which only covers final clone names ending in .dll. const std::filesystem::path staging = clone_path.wstring() + L".new"; - if (!CopyFileW(primary.c_str(), staging.c_str(), FALSE)) return {}; + if (image) { + HANDLE out = + CreateFileW(staging.c_str(), GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, nullptr); + if (out == INVALID_HANDLE_VALUE) return {}; + DWORD written = 0; + const bool ok = WriteFile(out, image->data(), static_cast(image->size()), &written, nullptr) && + written == image->size(); + CloseHandle(out); + if (!ok) { + DeleteFileW(staging.c_str()); + return {}; + } + } else if (!CopyFileW(primary.c_str(), staging.c_str(), FALSE)) { + return {}; + } // Open the guard before the clone exists under its final name and hold it across LoadLibraryExW: the rename // below needs DELETE access, which the handle's FILE_SHARE_DELETE grants, and no purge can remove the clone @@ -320,18 +386,34 @@ TlsHostModule ensure_tls_host(size_t slot) { TlsHostModule loaded = load_tls_host_image(clone_path, false); CloseHandle(guard); - if (loaded.index == TLS_OUT_OF_INDEXES) { + if (loaded.index == TLS_OUT_OF_INDEXES) DeleteFileW(clone_path.c_str()); + return loaded; +} + +// Must be called with g_tls_alloc_mutex held and WITHOUT g_tls_lock held (LoadLibraryExW takes the Windows loader lock). +TlsHostModule ensure_tls_host(size_t slot) { + if (slot >= kMaxMappedTlsModules) return {}; + if (g_tls_hosts[slot].index != TLS_OUT_OF_INDEXES) return g_tls_hosts[slot]; + // Slot 0 is the primary helper; it is loaded first in any case so thread attach/detach events are hooked. + if (!ensure_primary_tls_host()) return {}; + if (slot == 0) return g_tls_hosts[0]; + + std::filesystem::path clone_path; + TlsHostModule loaded = load_tls_host_clone(std::to_wstring(slot), clone_path); + if (loaded.index == TLS_OUT_OF_INDEXES) return {}; + // Index 0 is the runtime EXE's, and after the move the home clone's index holds that EXE's TLS. + bool taken = loaded.index == 0 || loaded.index == g_index0.home.index; + for (size_t i = 0; i < kMaxMappedTlsModules; ++i) taken |= i != slot && g_tls_hosts[i].index == loaded.index; + if (taken) { + FreeLibrary(loaded.module); DeleteFileW(clone_path.c_str()); return {}; } - for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { - if (i != slot && g_tls_hosts[i].index == loaded.index) { - FreeLibrary(loaded.module); - DeleteFileW(clone_path.c_str()); - return {}; - } + if (!g_tls_clones) { + g_tls_clones = new std::vector; + std::atexit(&cleanup_tls_clones_at_exit); } - g_tls_clones.push_back({loaded.module, clone_path}); + g_tls_clones->push_back({loaded.module, clone_path}); g_tls_hosts[slot] = loaded; return g_tls_hosts[slot]; } @@ -347,7 +429,7 @@ struct ThreadTlsSlot { }; // Per-thread installation state for each reserved TLS slot. -thread_local std::array g_thread_tls_slots{}; +thread_local std::array g_thread_tls_slots{}; // Orders the TLS owners' publication, their `initialised` flags and their retirement against the thread events. Shared // in on_host_thread_event, exclusive only for those short writes (no allocation and no call that takes the Windows @@ -366,10 +448,185 @@ struct ExclusiveTlsLock { ExclusiveTlsLock& operator=(const ExclusiveTlsLock&) = delete; }; +// gta6rt_tls_host.dll's exports that the home clone's TLS directory is pointed at (tls_host.cpp): a zero array in its +// .rdata and that array's size. +constexpr char kHomeTemplateExport[] = "gta6rt_tls_home_template"; +constexpr char kHomeTemplateSizeExport[] = "gta6rt_tls_home_template_size"; + +// File offset of `len` bytes at `rva` in an image file held in memory, or SIZE_MAX when they are not all inside one +// section's raw data. +size_t file_offset(const std::vector& file, const IMAGE_NT_HEADERS64* nt, uint64_t rva, uint64_t len) { + const auto* sec = IMAGE_FIRST_SECTION(nt); + for (unsigned i = 0; i < nt->FileHeader.NumberOfSections; ++i, ++sec) { + if (reinterpret_cast(sec + 1) > file.data() + file.size()) break; + if (rva < sec->VirtualAddress || rva + len > static_cast(sec->VirtualAddress) + sec->SizeOfRawData) + continue; + const uint64_t off = sec->PointerToRawData + (rva - sec->VirtualAddress); + return off + len <= file.size() ? static_cast(off) : SIZE_MAX; + } + return SIZE_MAX; +} + +// The RVA of a named export in an image file held in memory, 0 when it has none. +uint32_t file_export(const std::vector& file, const IMAGE_NT_HEADERS64* nt, const char* wanted) { + const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_EXPORT); + const size_t ed_off = file_offset(file, nt, dir.VirtualAddress, sizeof(IMAGE_EXPORT_DIRECTORY)); + if (!dir.Size || ed_off == SIZE_MAX) return 0; + const auto* ed = reinterpret_cast(file.data() + ed_off); + const size_t names = file_offset(file, nt, ed->AddressOfNames, uint64_t{4} * ed->NumberOfNames); + const size_t ords = file_offset(file, nt, ed->AddressOfNameOrdinals, uint64_t{2} * ed->NumberOfNames); + const size_t funcs = file_offset(file, nt, ed->AddressOfFunctions, uint64_t{4} * ed->NumberOfFunctions); + if (names == SIZE_MAX || ords == SIZE_MAX || funcs == SIZE_MAX) return 0; + const size_t wanted_len = std::strlen(wanted) + 1; + for (uint32_t i = 0; i < ed->NumberOfNames; ++i) { + uint32_t name_rva, func_rva; + uint16_t ord; + std::memcpy(&name_rva, file.data() + names + 4 * i, 4); + std::memcpy(&ord, file.data() + ords + 2 * i, 2); + const size_t name = file_offset(file, nt, name_rva, wanted_len); + if (name == SIZE_MAX || std::memcmp(file.data() + name, wanted, wanted_len) != 0) continue; + if (ord >= ed->NumberOfFunctions) return 0; + std::memcpy(&func_rva, file.data() + funcs + 4 * ord, 4); + return func_rva; + } + return 0; +} + +// Turns gta6rt_tls_host.dll's bytes into the home clone: its TLS directory now covers gta6rt_tls_home_template, which +// starts with a copy of the owner's template (taken from the mapped owner, so its pointers are already relocated; the +// array itself has no relocations), and takes the owner's alignment. The OS then gives every thread, at the home +// index, a block that is a fresh copy of the owner's TLS. The zero fill goes into the covered range too: +// LdrpAllocateTls allocates and copies End - Start only (Windows 11 26300) and ignores SizeOfZeroFill. The directory's +// Start and End have base relocations, so they follow the clone wherever it loads. Empty on success, else why not. +std::string make_home_clone_image(std::vector& file, const IMAGE_TLS_DIRECTORY64& owner) { + if (file.size() < sizeof(IMAGE_DOS_HEADER)) return "gta6rt_tls_host.dll is truncated"; + const auto* dos = reinterpret_cast(file.data()); + if (dos->e_magic != IMAGE_DOS_SIGNATURE || dos->e_lfanew < 0 || + static_cast(dos->e_lfanew) + sizeof(IMAGE_NT_HEADERS64) > file.size()) + return "gta6rt_tls_host.dll has no PE header"; + auto* nt = reinterpret_cast(file.data() + dos->e_lfanew); + if (nt->Signature != IMAGE_NT_SIGNATURE || nt->OptionalHeader.Magic != IMAGE_NT_OPTIONAL_HDR64_MAGIC) + return "gta6rt_tls_host.dll is not a 64-bit image"; + const uint32_t array_rva = file_export(file, nt, kHomeTemplateExport); + const uint32_t size_rva = file_export(file, nt, kHomeTemplateSizeExport); + const size_t size_off = file_offset(file, nt, size_rva, sizeof(uint32_t)); + if (!array_rva || !size_rva || size_off == SIZE_MAX) + return "gta6rt_tls_host.dll has no gta6rt_tls_home_template"; + uint32_t capacity; + std::memcpy(&capacity, file.data() + size_off, sizeof(capacity)); + const uint64_t raw = owner.EndAddressOfRawData - owner.StartAddressOfRawData; + const uint64_t total = raw + owner.SizeOfZeroFill; + if (owner.EndAddressOfRawData < owner.StartAddressOfRawData || total > capacity) + return "the owner's TLS (" + std::to_string(total) + " bytes) does not fit gta6rt_tls_home_template (" + + std::to_string(capacity) + " bytes)"; + const size_t array_off = file_offset(file, nt, array_rva, capacity); + const auto tls_dir = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS); + const size_t tls_off = file_offset(file, nt, tls_dir.VirtualAddress, sizeof(IMAGE_TLS_DIRECTORY64)); + if (array_off == SIZE_MAX || !tls_dir.Size || tls_off == SIZE_MAX) + return "gta6rt_tls_host.dll's TLS directory or home template lies outside its file"; + std::memcpy(file.data() + array_off, reinterpret_cast(owner.StartAddressOfRawData), raw); + std::memset(file.data() + array_off + raw, 0, capacity - raw); + auto* tls = reinterpret_cast(file.data() + tls_off); + tls->StartAddressOfRawData = nt->OptionalHeader.ImageBase + array_rva; + tls->EndAddressOfRawData = tls->StartAddressOfRawData + total; + tls->SizeOfZeroFill = 0; + tls->Characteristics = + (tls->Characteristics & ~IMAGE_SCN_ALIGN_MASK) | (owner.Characteristics & IMAGE_SCN_ALIGN_MASK); + return {}; +} + +std::string module_file_name(HMODULE module) { + wchar_t path[MAX_PATH]; + const DWORD n = GetModuleFileNameW(module, path, MAX_PATH); + if (!n || n >= MAX_PATH) return "?"; + const wchar_t* name = path; + for (const wchar_t* p = path; *p; ++p) + if (*p == L'\\' || *p == L'/') name = p + 1; + const int bytes = WideCharToMultiByte(CP_UTF8, 0, name, -1, nullptr, 0, nullptr, nullptr); + if (bytes <= 1) return "?"; + std::string out(static_cast(bytes - 1), '\0'); + WideCharToMultiByte(CP_UTF8, 0, name, -1, out.data(), bytes, nullptr, nullptr); + return out; +} + +// The move on the calling thread, kept apart so that no frame of reserve_index0 holds a slot address across it. After +// it the owner's live block is at `home` and slot 0 holds the home clone's fresh copy, which nothing reads. +__declspec(noinline) void move_index0_on_this_thread(DWORD* owner_index, DWORD home) { + void** slots = module_tls_slots(); + std::swap(slots[0], slots[home]); + *owner_index = home; +} + +// See reserve_tls_index0. Empty on success, else why not; nothing has changed then. g_tls_alloc_mutex held. It reads +// no thread_local data and runs no code that does, before or after the move. +std::string reserve_index0() { + // Windows gives index 0 to the process executable when it has TLS; a DLL can only hold it in a process whose EXE + // has none, and a DLL that is still loading or was loaded without its references resolved shows 0 too. + const HMODULE exe = GetModuleHandleW(nullptr); + auto* base = reinterpret_cast(exe); + auto* nt = at(base, reinterpret_cast(base)->e_lfanew); + const auto dir = directory(nt, IMAGE_DIRECTORY_ENTRY_TLS); + if (!dir.Size || !dir.VirtualAddress) return "the process executable has no TLS, so index 0 is not its"; + const IMAGE_TLS_DIRECTORY64 owner = *at(base, dir.VirtualAddress); + auto* owner_index = reinterpret_cast(owner.AddressOfIndex); + if (!owner_index) return "the process executable's TLS directory has no index"; + if (*owner_index != 0) return "the process executable's _tls_index is " + std::to_string(*owner_index) + ", not 0"; + if (!module_tls_slots()) return "this thread has no TLS array"; + if (!ensure_primary_tls_host()) + return "gta6rt_tls_host.dll is missing, has no module TLS index or lacks gta6rt_tls_host_set_thread_event"; + + std::vector image; + try { + image = read_file(tls_host_base_path()); + } catch (const std::exception& e) { + return e.what(); + } + if (std::string why = make_home_clone_image(image, owner); !why.empty()) return why; + std::filesystem::path path; + const TlsHostModule home = load_tls_host_clone(L"home", path, &image); + if (home.index == TLS_OUT_OF_INDEXES) return "the home clone of gta6rt_tls_host.dll cannot be loaded"; + auto drop = [&](std::string why) { + FreeLibrary(home.module); // safe until the move below: nothing lives at its index yet + DeleteFileW(path.c_str()); + return why; + }; + bool taken = home.index == 0 || home.index >= kMaxModuleTlsSlots; + for (const auto& host : g_tls_hosts) taken |= host.index == home.index; + if (taken) return drop("the home clone got an unusable module TLS index"); + // The OS must have taken the changed directory: the mapped clone's template is the owner's, at full size. + auto* home_base = reinterpret_cast(home.module); + auto* home_nt = at(home_base, reinterpret_cast(home_base)->e_lfanew); + const auto* home_tls = + at(home_base, directory(home_nt, IMAGE_DIRECTORY_ENTRY_TLS).VirtualAddress); + const uint64_t raw = owner.EndAddressOfRawData - owner.StartAddressOfRawData; + if (home_tls->EndAddressOfRawData - home_tls->StartAddressOfRawData != raw + owner.SizeOfZeroFill || + std::memcmp(reinterpret_cast(home_tls->StartAddressOfRawData), + reinterpret_cast(owner.StartAddressOfRawData), raw) != 0) + return drop("the home clone's mapped TLS template is not the owner's"); + + // Everything that can throw comes first: past the move this records the result and nothing more. + const std::string name = module_file_name(exe); + // _tls_index sits in .data; made writable first in case a linker merged it into a read-only section. + DWORD old_protect = 0; + if (!VirtualProtect(owner_index, sizeof(DWORD), PAGE_READWRITE, &old_protect)) + return drop("the owner's _tls_index cannot be written"); + move_index0_on_this_thread(owner_index, home.index); + VirtualProtect(owner_index, sizeof(DWORD), old_protect, &old_protect); + + // Kept loaded for the process lifetime: FreeLibrary would make the OS free every thread's block at its index, the + // owner's from now on. Not in g_tls_clones for that reason. Its file cannot be deleted while it is mapped + // (DeleteFileW and a POSIX-semantics delete both fail with ERROR_ACCESS_DENIED on Windows 11), so it stays until + // a later run's sweep. + g_index0.home = home; + std::snprintf(g_index0.owner, sizeof(g_index0.owner), "%s", name.c_str()); + g_index0.moved = true; + return {}; +} + // Puts the helper DLL's own block back in this thread's slot and frees the copy that replaced it. Uses only this // thread's record, so it also works after the module that installed the copy is gone. void release_thread_slot(size_t slot) { - if (slot >= kMaxMappedTlsModules) return; + if (slot >= kTlsSlotCount) return; ThreadTlsSlot& entry = g_thread_tls_slots[slot]; if (!entry.module && !entry.block) return; if (entry.ga_view) { @@ -438,7 +695,7 @@ void** make_ga_view(const Module& m, void* block) { } void install_thread_block(Module& m) { - if (m.tls_slot >= kMaxMappedTlsModules) return; + if (m.tls_slot >= kTlsSlotCount) return; const size_t slot = m.tls_slot; ThreadTlsSlot& entry = g_thread_tls_slots[slot]; if (entry.module == &m && entry.generation == m.tls_generation) return; @@ -530,7 +787,7 @@ bool ga_tls_patch_enabled() { } void uninstall_thread_block(Module& m) { - if (m.tls_slot >= kMaxMappedTlsModules) return; + if (m.tls_slot >= kTlsSlotCount) return; const size_t slot = m.tls_slot; ThreadTlsSlot& entry = g_thread_tls_slots[slot]; if (entry.module != &m || entry.generation != m.tls_generation) return; @@ -697,7 +954,7 @@ constexpr size_t kMaxEndedThreads = 1024; // load(): every other running thread gets its own copy of m's template. Not fatal where it cannot be done. void install_on_existing_threads(Module& m) { const uint64_t total = static_cast(m.tls_raw_size) + m.tls_zero_fill; - if (!total || m.tls_index >= kMaxModuleTlsSlots || m.tls_slot >= kMaxMappedTlsModules) return; + if (!total || m.tls_index >= kMaxModuleTlsSlots || m.tls_slot >= kTlsSlotCount) return; // Stays ahead of the TLS lock: the first call resolves the function with GetModuleHandle and GetProcAddress, which // take the Windows loader lock, and a thread inside its attach event holds that lock while it waits for ours. if (!query_thread_fn()) return; @@ -882,7 +1139,11 @@ void release_existing_blocks_of_this_thread() { // Runs in gta6rt_tls_host.dll's DllMain for each thread the process starts or ends once the helper is loaded, under // the Windows loader lock, on that thread. A new thread gets its own copy of each active TLS owner's template; an // ending one gives each helper's block back before the Windows loader frees it. TLS callbacks get the thread events -// only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. +// only after the module's DLL_PROCESS_ATTACH (initialise()), as the Windows loader orders them. Windows allocates +// every module's block before the first DllMain of a new thread, and runs an EXE's TLS callbacks after every DllMain, +// for attach and for detach (measured on Windows 11 26300). So attach installs all copies first and then runs the +// callbacks, the DLL slots in order and the executable's last; detach runs the DLL slots in reverse and then the +// executable's slot, each releasing its copy after its callbacks. void __cdecl on_host_thread_event(DWORD reason) { SharedTlsLock lock; // The try/catch is per slot: a throw from one module's install or callbacks must not take the thread events @@ -893,14 +1154,25 @@ void __cdecl on_host_thread_event(DWORD reason) { } catch (const std::exception& e) { std::fprintf(stderr, "[rt] loader: thread attach: %s\n", e.what()); } - for (size_t slot = 0; slot < kMaxMappedTlsModules; ++slot) { + std::array installed{}; + for (size_t slot = 0; slot < kTlsSlotCount; ++slot) { Module* m = g_tls_slot_owners[slot].load(); if (!m) continue; try { install_thread_block(*m); - if (m->initialised) run_callbacks(*m, DLL_THREAD_ATTACH); + installed[slot] = m; + } catch (const std::exception& e) { + // The thread runs on without this module's TLS (and its callbacks); later slots still get theirs. + std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(), + e.what()); + } + } + for (size_t slot = 0; slot < kTlsSlotCount; ++slot) { + Module* m = installed[slot]; + if (!m || !m->initialised) continue; + try { + run_callbacks(*m, DLL_THREAD_ATTACH); } catch (const std::exception& e) { - // The thread runs on without this module's TLS; later slots still get theirs. std::fprintf(stderr, "[rt] loader: thread attach, slot %zu (%s): %s\n", slot, m->name.c_str(), e.what()); } @@ -913,7 +1185,8 @@ void __cdecl on_host_thread_event(DWORD reason) { } catch (const std::exception& e) { std::fprintf(stderr, "[rt] loader: thread detach: %s\n", e.what()); } - for (size_t i = kMaxMappedTlsModules; i-- > 0;) { + for (size_t step = 0; step < kTlsSlotCount; ++step) { + const size_t i = step < kMaxMappedTlsModules ? kMaxMappedTlsModules - 1 - step : kMainImageSlot; Module* m = g_tls_slot_owners[i].load(); if (m && g_thread_tls_slots[i].module == m && g_thread_tls_slots[i].generation == m->tls_generation) { @@ -1017,6 +1290,26 @@ void redirect_pc_to_file_header_at(const void* resolved) { // Declared in pe_loader.h; the body needs the internal clone registry above. void cleanup_tls_clones() { cleanup_tls_clones_internal(); } +bool reserve_tls_index0(std::string* why) { + std::lock_guard alloc_lock(g_tls_alloc_mutex); + static bool attempted = false; // once: a later attempt could meet threads that already run this EXE's code + if (!attempted) { + attempted = true; + // A throw (std::filesystem::temp_directory_path when GetTempPathW fails, an allocation) is a failed + // reservation like any other: gta6rt calls this before main, where an exception would end it with no message. + try { + const std::string reason = reserve_index0(); + std::snprintf(g_index0.why, sizeof(g_index0.why), "%s", reason.c_str()); + } catch (const std::exception& e) { + std::snprintf(g_index0.why, sizeof(g_index0.why), "%s", e.what()); + } catch (...) { + std::snprintf(g_index0.why, sizeof(g_index0.why), "an unknown error while reserving it"); + } + } + if (why) *why = g_index0.moved ? std::string() : std::string(g_index0.why); + return g_index0.moved; +} + namespace { bool lookup_in_loader(void* ctx, uint64_t address, std::string& module, uint32_t& rva) { return static_cast(ctx)->find_address(address, module, rva); @@ -1094,11 +1387,12 @@ Loader::~Loader() { entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored } } + shims::remove_xmem_allocation_hooks(this); shims::remove_bundled_loader(this); shims::remove_module_lookup(this); for (auto* m : order_) { // TLS state must go away before the image and its TLS block are unmapped. - if (m->tls_index != kNoTlsIndex && m->tls_slot < kMaxMappedTlsModules) { + if (m->tls_index != kNoTlsIndex && m->tls_slot < kTlsSlotCount) { // Retired first, under the lock: no thread event installs it or runs its callbacks after this, and a // thread that still holds a copy frees it when it ends (on_host_thread_event). { @@ -1498,6 +1792,12 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string& // installed here, before bind_imports can return control to the caller and before any image code can run. initialize_tls(*m); parse_exports(*m); + if (auto it = m->exports.find("__XMemAllocationHooks__"); it != m->exports.end()) { + const auto offset = static_cast(static_cast(it->second) - m->base); + if (offset <= m->size && m->size - offset >= sizeof(shims::XMemAllocationHooks)) { + shims::add_xmem_allocation_hooks(this, static_cast(it->second)); + } + } return *m; } @@ -1507,7 +1807,7 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string& // Only the OS loader can allocate that module index, so the loader reuses the index the OS assigned to // gta6rt_tls_host.dll and maps a fresh clone of the helper for every additional simultaneous TLS module, each clone // getting its own index. All kMaxMappedTlsModules slots can be live at once; a further module is rejected rather than -// silently sharing (and corrupting) a slot. +// silently sharing (and corrupting) a slot. An executable takes index 0 instead (kMainImageSlot), as on Windows. void Loader::initialize_tls(Module& m) { auto* tls = tls_directory(m); if (!tls) return; @@ -1531,26 +1831,51 @@ void Loader::initialize_tls(Module& m) { if (!module_tls_slots()) throw std::runtime_error(m.name + ": this thread has no TLS array"); - size_t slot = kMaxMappedTlsModules; + auto* nt = at(m.base, reinterpret_cast(m.base)->e_lfanew); + const bool executable = (nt->FileHeader.Characteristics & IMAGE_FILE_DLL) == 0; + + size_t slot = kTlsSlotCount; DWORD index = TLS_OUT_OF_INDEXES; { std::lock_guard alloc_lock(g_tls_alloc_mutex); - for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { - if (g_tls_slot_owners[i].load() == nullptr) { - slot = i; - break; + if (executable) { + if (g_index0.moved && g_tls_slot_owners[kMainImageSlot].load() == nullptr) { + slot = kMainImageSlot; + index = 0; + if (!g_index0.traced && startup_trace::enabled()) { + g_index0.traced = true; + startup_trace::event("tls_index0", "\"owner\":" + startup_trace::quote(g_index0.owner) + + ",\"moved_to\":" + std::to_string(g_index0.home.index)); + } + } else { + // Mapped on as a DLL is: its code that reads _tls_index works, but its /GA code would read and write + // the block in slot 0, which is the runtime's own TLS or the other executable's. gta6rt refuses to + // run such an image (main.cpp); a Loader user must not run its code either. + std::fprintf(stderr, + "[rt] loader: %s does not get module TLS index 0 (%s); its code built with /GA would use " + "another module's TLS\n", + m.name.c_str(), g_index0.moved ? "another mapped executable holds it" : g_index0.why); + } + } + if (slot == kTlsSlotCount) { + for (size_t i = 0; i < kMaxMappedTlsModules; ++i) { + if (g_tls_slot_owners[i].load() == nullptr) { + slot = i; + break; + } } + if (slot >= kMaxMappedTlsModules) + throw std::runtime_error(m.name + ": all " + std::to_string(kMaxMappedTlsModules) + + " manually mapped static TLS slots are in use"); + + // Load/clone gta6rt_tls_host.dll OUTSIDE ExclusiveTlsLock so LoadLibraryExW cannot deadlock with + // on_host_thread_event (which runs under the Windows loader lock and takes SharedTlsLock). + index = ensure_tls_host(slot).index; + if (index == TLS_OUT_OF_INDEXES) + throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index"); + if (index >= kMaxModuleTlsSlots) + throw std::runtime_error(m.name + ": reserved TLS index is out of range"); } - if (slot >= kMaxMappedTlsModules) - throw std::runtime_error(m.name + ": all " + std::to_string(kMaxMappedTlsModules) + - " manually mapped static TLS slots are in use"); - - // Load/clone gta6rt_tls_host.dll OUTSIDE ExclusiveTlsLock so LoadLibraryExW cannot deadlock with - // on_host_thread_event (which runs under the Windows loader lock and takes SharedTlsLock). - index = ensure_tls_host(slot).index; - if (index == TLS_OUT_OF_INDEXES) - throw std::runtime_error(m.name + ": gta6rt_tls_host.dll is missing or has no module TLS index"); - if (index >= kMaxModuleTlsSlots) throw std::runtime_error(m.name + ": reserved TLS index is out of range"); // The fields are complete before a thread event can see the owner. ExclusiveTlsLock lock; diff --git a/runtime/src/pe_loader.h b/runtime/src/pe_loader.h index fda9244401..f75426e416 100644 --- a/runtime/src/pe_loader.h +++ b/runtime/src/pe_loader.h @@ -54,11 +54,15 @@ struct Module { // the image's _tls_index. tls_index names TEB->ThreadLocalStoragePointer[tls_index], the array // __declspec(thread) reads; it is not a TlsAlloc slot. The loader reserves distinct indices by loading // gta6rt_tls_host.dll (and cloning it on demand for additional simultaneous TLS modules, up to 16 at a time). + // An executable gets index 0, as Windows gives the process EXE, because code built with /GA reads slot 0 without + // _tls_index. That needs reserve_tls_index0() at process start; without it, and for a second executable mapped + // while one holds index 0, the executable gets a helper index and a note on stderr, and its /GA code would use + // another module's TLS, so its code must not run (gta6rt refuses). // Every thread started after load() gets its own copy through the helper's DLL_THREAD_ATTACH, and gives it back // at DLL_THREAD_DETACH. A thread that was already running gets its copy from load() itself, as it would from // Windows for a DLL Windows loads: a block, no DLL_THREAD_ATTACH, and DLL_THREAD_DETACH when it ends. uint32_t tls_index = kNoTlsIndex; - uint32_t tls_slot = kNoTlsIndex; // index into the loader's reserved TLS-host slot pool + uint32_t tls_slot = kNoTlsIndex; // index into the loader's reserved TLS-host slot pool ; 16 is index 0, an executable's uint64_t tls_generation = 0; // unique token per TLS initialisation, distinguishing reused slots/addresses void* tls_block = nullptr; // calling thread's copy of the image's template void* tls_saved_block = nullptr; // helper DLL block replaced in that thread, restored by ~Loader @@ -182,6 +186,14 @@ class Loader { // skips the atexit table. Call it when no mapped code can run again: it unmaps the helper images. void cleanup_tls_clones(); +// Moves the runtime's own EXE off module TLS index 0, which Windows gave it, so that a mapped executable can have it +// (Module::tls_index): its TLS moves to the index of one more helper clone, whose template is a copy of the EXE's. +// Call it once at process start, before any other thread has run this EXE's code (gta6rt does it from a CRT +// initializer): MSVC code keeps the address of its TLS slot across calls, so a thread that is already running cannot +// be moved, and its TLS would stay at index 0. Returns false, with the reason in *why, when it cannot; later calls +// return the first result. +bool reserve_tls_index0(std::string* why = nullptr); + std::string lower(std::string s); } // namespace rt diff --git a/runtime/test/pipeline_cache_file.h b/runtime/src/pipeline_cache_file.h similarity index 90% rename from runtime/test/pipeline_cache_file.h rename to runtime/src/pipeline_cache_file.h index 400138ef7d..95afbd10ad 100644 --- a/runtime/test/pipeline_cache_file.h +++ b/runtime/src/pipeline_cache_file.h @@ -1,4 +1,7 @@ // Publish a checkpoint only after every byte has reached a closed, same-directory staging file. +// +// Used by vk_pipeline_check (its corpus checkpoints) and by the runtime itself, which writes the session cache on +// device teardown (pipeline_cache_store.h). A reader of the old file keeps it open until its rename completes. #pragma once #include diff --git a/runtime/src/pipeline_cache_store.h b/runtime/src/pipeline_cache_store.h new file mode 100644 index 0000000000..6d519d99b1 --- /dev/null +++ b/runtime/src/pipeline_cache_store.h @@ -0,0 +1,69 @@ +// Persisting the runtime's VkPipelineCache across launches (D3D-704). +// +// Two files sit beside gta6rt.exe, and they are not interchangeable: +// +// pipeline_cache.bin the offline corpus seed the `pipelines` build stage writes (#367). Read only. +// pipeline_cache.session.bin what the runtime compiled last time. Written on device teardown. +// +// Keeping them apart means a run can never replace the multi-GB corpus cache with the handful of pipelines it +// happened to compile. On the next launch both are loaded and merged, so the offline entries and the previous +// session's entries are available together. +// +// This header is pure stdlib on purpose (it does not include vulkan.h): pipeline_cache_store_test builds on hosts +// where CMake has no Vulkan headers. The byte layout below is VkPipelineCacheHeaderVersionOne, whose 32 bytes are +// part of Vulkan's ABI, not something a driver chooses. +#pragma once + +#include +#include +#include +#include + +#include "cached_pso.h" + +namespace leonida::pipeline_cache_store { + +// A session cache normally holds what one boot compiled (a few MB to a few hundred MB). The cap is what keeps a +// cache seeded from the multi-GB corpus file -- whose data comes back as the whole union -- from being rewritten +// at every exit. Past it the previous session file is left alone; raise the limit with +// LEONIDA_PIPELINE_CACHE_BYTES when a session really compiles that much. +inline constexpr std::size_t default_save_limit = std::size_t{256} << 20; // 256 MiB + +struct SaveLimit { + std::size_t bytes = default_save_limit; + bool valid = true; // false when the text was not a byte count; bytes then stays at the default +}; + +// LEONIDA_PIPELINE_CACHE_BYTES: a decimal byte count, 0 turning the session file off entirely. Empty or absent +// means the default; stray text, a sign or an overflow is reported by the caller and the default is used. +inline SaveLimit parse_save_limit(const char* text) { + if (!text || !*text) return {}; + std::size_t value = 0; + for (const char* p = text; *p; ++p) { + if (*p < '0' || *p > '9') return {default_save_limit, false}; + const std::size_t digit = static_cast(*p - '0'); + if (value > (std::numeric_limits::max() - digit) / 10) return {default_save_limit, false}; + value = value * 10 + digit; + } + return {value, true}; +} + +inline constexpr std::size_t header_bytes = 32; +inline constexpr std::uint32_t header_version_one = 1; + +inline std::uint32_t read_u32(const std::uint8_t* p) { + return std::uint32_t(p[0]) | (std::uint32_t(p[1]) << 8) | (std::uint32_t(p[2]) << 16) | + (std::uint32_t(p[3]) << 24); +} + +// True when the blob's header names this physical device and pipeline-cache UUID, which is what a driver requires +// before it will read the opaque payload. The header is little-endian, like the host. +inline bool header_matches(const void* data, std::size_t size, const cached_pso::Identity& identity) { + if (!data || size < header_bytes) return false; + const auto* bytes = static_cast(data); + return read_u32(bytes) == header_bytes && read_u32(bytes + 4) == header_version_one && + read_u32(bytes + 8) == identity.vendor && read_u32(bytes + 12) == identity.device && + std::memcmp(bytes + 16, identity.cache_uuid, sizeof(identity.cache_uuid)) == 0; +} + +} // namespace leonida::pipeline_cache_store diff --git a/runtime/src/present_dump.h b/runtime/src/present_dump.h new file mode 100644 index 0000000000..2e594fcb50 --- /dev/null +++ b/runtime/src/present_dump.h @@ -0,0 +1,256 @@ +#pragma once + +// LEONIDA_PRESENT_DUMP: the final swapchain texels, encoded on a worker after their frame fence signals. +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida::present_dump { + +inline unsigned texel_size(VkFormat format) { + switch (format) { + case VK_FORMAT_B8G8R8A8_UNORM: case VK_FORMAT_B8G8R8A8_SRGB: + case VK_FORMAT_R8G8B8A8_UNORM: case VK_FORMAT_R8G8B8A8_SRGB: + case VK_FORMAT_A2B10G10R10_UNORM_PACK32: case VK_FORMAT_A2R10G10B10_UNORM_PACK32: return 4; + case VK_FORMAT_R16G16B16A16_SFLOAT: return 8; + case VK_FORMAT_R32G32B32A32_SFLOAT: return 16; + default: return 0; + } +} + +inline std::uint8_t unorm8(float v) { + return v > 0 ? std::uint8_t(std::min(v, 1.0f) * 255 + 0.5f) : 0; +} + +inline std::uint8_t half_unorm8(std::uint16_t bits) { + const int exponent = bits >> 10; + const int fraction = bits & 1023; + if (bits >= 0x8000 || !exponent || (exponent == 31 && fraction)) return 0; + return unorm8(std::ldexp(float(1024 + fraction), exponent - 25)); +} + +inline void rgba_row(std::uint8_t* dst, const std::uint8_t* src, unsigned width, VkFormat format, bool pq) { + if (format == VK_FORMAT_R8G8B8A8_UNORM || format == VK_FORMAT_R8G8B8A8_SRGB) { + std::memcpy(dst, src, size_t(width) * 4); + return; + } + const unsigned stride = texel_size(format); + for (unsigned x = 0; x < width; ++x, src += stride, dst += 4) { + if (format == VK_FORMAT_B8G8R8A8_UNORM || format == VK_FORMAT_B8G8R8A8_SRGB) { + dst[0] = src[2]; dst[1] = src[1]; dst[2] = src[0]; dst[3] = src[3]; + } else if (format == VK_FORMAT_R16G16B16A16_SFLOAT) { + std::uint16_t v[4]; + std::memcpy(v, src, sizeof(v)); + std::transform(v, v + 4, dst, half_unorm8); + } else if (format == VK_FORMAT_R32G32B32A32_SFLOAT) { + float v[4]; + std::memcpy(v, src, sizeof(v)); + std::transform(v, v + 4, dst, unorm8); + } else { + // A cheap HDR10 preview: decode ST.2084 per component, clip at 203 nits and encode for SDR. + // Keep the source primaries. A 10-bit SDR swapchain just scales its code values to eight bits. + static const auto pq_to_sdr = [] { + std::array table{}; + for (unsigned i = 0; i < table.size(); ++i) { + const double p = std::pow(i / 1023.0, 1.0 / 78.84375); + const double linear = (10000.0 / 203.0) * + std::pow(std::max(0.0, p - 0.8359375) / (18.8515625 - 18.6875 * p), 1.0 / 0.1593017578125); + const double srgb = linear <= 0.0031308 ? 12.92 * linear : 1.055 * std::pow(linear, 1.0 / 2.4) - 0.055; + table[i] = unorm8(float(srgb)); + } + return table; + }(); + std::uint32_t packed; + std::memcpy(&packed, src, sizeof(packed)); + for (unsigned channel = 0; channel < 3; ++channel) { + const unsigned bits = (packed >> (10 * channel)) & 1023; + dst[channel] = pq ? pq_to_sdr[bits] : std::uint8_t((bits * 255 + 511) / 1023); + } + if (format == VK_FORMAT_A2R10G10B10_UNORM_PACK32) std::swap(dst[0], dst[2]); + dst[3] = std::uint8_t((packed >> 30) * 85); + } + } +} + +inline std::array big_endian(std::uint32_t n) { + return {std::uint8_t(n >> 24), std::uint8_t(n >> 16), std::uint8_t(n >> 8), std::uint8_t(n)}; +} + +inline bool chunk(std::FILE* file, const char (&type)[5], std::span data, + std::span prefix = {}) { + static constexpr auto crc_table = [] { + std::array table{}; + for (unsigned i = 0; i < table.size(); ++i) { + unsigned c = i; + for (int bit = 0; bit < 8; ++bit) c = (c >> 1) ^ ((c & 1) ? 0xedb88320u : 0); + table[i] = c; + } + return table; + }(); + std::uint32_t crc = ~0u; + const auto write = [&](std::span bytes) { + for (auto b : bytes) crc = crc_table[(crc ^ b) & 255] ^ (crc >> 8); + return bytes.empty() || std::fwrite(bytes.data(), 1, bytes.size(), file) == bytes.size(); + }; + return std::fwrite(big_endian(std::uint32_t(prefix.size() + data.size())).data(), 1, 4, file) == 4 && + write({reinterpret_cast(type), 4}) && write(prefix) && write(data) && + std::fwrite(big_endian(~crc).data(), 1, 4, file) == 4; +} + +inline bool write_png(std::FILE* file, VkExtent2D extent, VkFormat format, bool pq, const std::uint8_t* src) { + constexpr std::uint8_t signature[]{137, 80, 78, 71, 13, 10, 26, 10}; + std::array ihdr{}; + const auto w = big_endian(extent.width), h = big_endian(extent.height); + std::copy(w.begin(), w.end(), ihdr.begin()); + std::copy(h.begin(), h.end(), ihdr.begin() + 4); + ihdr[8] = 8; + ihdr[9] = 6; // 8-bit RGBA + constexpr std::uint8_t zlib_header[]{0x78, 0x01}; + if (std::fwrite(signature, 1, sizeof(signature), file) != sizeof(signature) || + !chunk(file, "IHDR", ihdr) || !chunk(file, "IDAT", zlib_header)) return false; + + // IDAT chunks concatenate to one zlib stream. Each scanline starts with PNG filter 0 and occupies + // one or more stored DEFLATE blocks (16-bit little-endian length and its ones' complement). + std::vector row(1 + size_t(extent.width) * 4); + std::uint32_t a = 1, b = 0; + for (unsigned y = 0; y < extent.height; ++y, src += size_t(extent.width) * texel_size(format)) { + rgba_row(row.data() + 1, src, extent.width, format, pq); + std::span rest(row); + while (!rest.empty()) { + auto block = rest.first(std::min(rest.size(), 65535)); + rest = rest.subspan(block.size()); + const auto len = std::uint16_t(block.size()); + const std::uint8_t header[]{std::uint8_t(y + 1 == extent.height && rest.empty()), + std::uint8_t(len), std::uint8_t(len >> 8), std::uint8_t(~len), std::uint8_t((len >> 8) ^ 255)}; + for (auto byte : block) { + a = (a + byte) % 65521; + b = (b + a) % 65521; + } + if (!chunk(file, "IDAT", block, header)) return false; + } + } + return chunk(file, "IDAT", big_endian((b << 16) | a)) && chunk(file, "IEND", {}); +} + +class PresentDump { +public: + PresentDump() { +#ifdef _WIN32 + wchar_t* env = nullptr; + size_t length = 0; + if (_wdupenv_s(&env, &length, L"LEONIDA_PRESENT_DUMP") != 0) { + bad_value(); + return; + } + const std::unique_ptr owned(env, &std::free); +#else + const auto* env = std::getenv("LEONIDA_PRESENT_DUMP"); +#endif + if (!env) return; + try { + auto value = std::filesystem::path(env).native(); + std::uint64_t interval = 60; + const auto comma = value.rfind(','); + if (comma != value.npos) { + const auto n = std::filesystem::path(value.substr(comma + 1)).string(); + const auto end = n.data() + n.size(); + const auto parsed = std::from_chars(n.data(), end, interval); + if (parsed.ec != std::errc{} || parsed.ptr != end || !interval) { + bad_value(); + return; + } + value.resize(comma); + } + if (value.empty()) { + bad_value(); + return; + } + dir_ = std::filesystem::absolute(value); + std::filesystem::create_directories(dir_); + interval_ = interval; + } catch (const std::exception&) { bad_value(); } + } + + bool enabled() const { return interval_ != 0; } + bool due(std::uint64_t frames_shown) const { + const auto n = interval_.load(); + return n && frames_shown % n == 0; + } + void disable(const char* why) { + if (interval_.exchange(0)) std::fprintf(stderr, "[rt] present: %s; LEONIDA_PRESENT_DUMP disabled\n", why); + } + void save(std::uint64_t frame, VkExtent2D extent, VkFormat format, bool pq, const std::uint8_t* src, size_t size) { + try { + // Bound memory to one outstanding write even at N=1. Teardown joins the final writer. + if (writer_.joinable()) writer_.join(); + if (!enabled()) return; + char name[48]; + std::snprintf(name, sizeof(name), "present_%06llu.png", static_cast(frame)); + writer_ = std::jthread([this, frame, extent, format, pq, path = dir_ / name, + bytes = std::vector(src, src + size)] { + try { + if (publish(path, extent, format, pq, bytes.data())) { + const auto utf8 = path.u8string(); + std::fprintf(stderr, "[rt] present: dumped frame %llu to %s\n", + static_cast(frame), reinterpret_cast(utf8.c_str())); + return; + } + } catch (const std::exception&) {} + disable("could not write the present dump"); + }); + } catch (const std::exception&) { disable("could not queue the present dump"); } + } + +private: + static void bad_value() { + static std::once_flag once; + std::call_once(once, [] { + std::fprintf(stderr, "[rt] present: invalid LEONIDA_PRESENT_DUMP (expected a writable dir[,N], N > 0); disabled\n"); + }); + } + static bool publish(const std::filesystem::path& path, VkExtent2D extent, VkFormat format, bool pq, + const std::uint8_t* src) { + // Never open an existing output for writing: it could be a link to a file outside the dump directory. + // Build a complete sibling exclusively, then replace the directory entry in a single rename. + auto tmp = path; + tmp += ".tmp"; +#ifdef _WIN32 + std::FILE* file = nullptr; + _wfopen_s(&file, tmp.c_str(), L"wbx"); +#else + auto* file = std::fopen(tmp.c_str(), "wbx"); +#endif + if (!file) return false; + bool ok = false; + try { ok = write_png(file, extent, format, pq, src); } catch (const std::exception&) {} + if (std::fclose(file) != 0) ok = false; + std::error_code ec; + if (ok) { + std::filesystem::rename(tmp, path, ec); + if (!ec) return true; + } + std::filesystem::remove(tmp, ec); + return false; + } + + std::filesystem::path dir_; + std::atomic interval_{0}; + std::jthread writer_; // joined before the state it uses is destroyed +}; + +} // namespace leonida::present_dump diff --git a/runtime/src/rect_list_geometry.h b/runtime/src/rect_list_geometry.h new file mode 100644 index 0000000000..0049394cf4 --- /dev/null +++ b/runtime/src/rect_list_geometry.h @@ -0,0 +1,220 @@ +#pragma once + +// Console rectangle lists on Vulkan, which has no such primitive. +// +// A rectangle is three corners (v1, v2, v3) and the hardware makes the fourth, v2 + v3 - v1, for the position and for +// every interpolant, after the vertex stage. A list topology of rectangles (D3D_PRIMITIVE_TOPOLOGY 17) and a pipeline +// whose topology type is 19 are console-only. The fact comes from xvalkyrie (GPL-3.0, commit 53af7df77c10, notes in +// its backlog); no code is taken from it. +// +// The fourth vertex depends on what the vertex stage wrote, not on what it read, so the expansion has to sit after +// the vertex stage: a pre-pass over the vertex buffers is wrong for any shader that is not linear in its inputs (and +// the translated vertex shaders fetch by V# themselves, so there is no vertex buffer to expand). The pipeline gets a +// small geometry stage instead, built here from the vertex shader's own SPIR-V: it takes the triangle (v1, v2, v3) +// the list draws and emits the parallelogram as the two triangles (v1, v2, v4) and (v1, v4, v3), with the winding of +// (v1, v2, v3). Both start at v1, so a flat input (taken from a triangle's first vertex) is v1's over the whole +// rectangle. Every Location output of the vertex stage is a vec4 float in the translator's output (rdna2spirv.py), +// and so is the stage's Position; the generated stage reads and writes exactly those. +// +// Not covered, and refused with a reason: a vertex stage that writes ClipDistance, CullDistance, Layer or +// ViewportIndex, or a Location output that is not a vec4 float. +// +// Plain word editing, standard library only. + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +// D3D_PRIMITIVE_TOPOLOGY values and the PSO topology type of the console's rectangle and quad lists. +constexpr std::uint32_t topology_rect_list = 17; +constexpr std::uint32_t topology_quad_list = 19; +constexpr std::uint32_t topology_type_rect_list = 19; +constexpr std::array quad_triangle_indices{0, 1, 2, 0, 2, 3}; + +// The geometry stage for `vertex_words`' outputs; empty, with `why` set, when the vertex stage cannot be expanded. +inline std::vector rect_list_geometry(const std::vector& vertex_words, std::string& why) { + enum : std::uint32_t { + op_entry_point = 15, op_type_void = 19, op_type_int = 21, op_type_float = 22, + op_type_vector = 23, op_type_array = 28, op_type_pointer = 32, op_type_function = 33, op_constant = 43, + op_function = 54, op_function_end = 56, op_variable = 59, op_load = 61, op_store = 62, op_access_chain = 65, + op_decorate = 71, op_fadd = 129, op_fsub = 131, op_emit_vertex = 218, op_end_primitive = 219, op_label = 248, op_return = 253, + op_capability = 17, op_memory_model = 14, op_execution_mode = 16, + deco_builtin = 11, deco_location = 30, builtin_position = 0, builtin_point_size = 1, + storage_input = 1, storage_output = 3 + }; + why.clear(); + if (vertex_words.size() < 6 || vertex_words[0] != 0x07230203u) { + why = "the vertex shader is not a SPIR-V module"; + return {}; + } + // What the vertex stage declares: types, Output variables, and the decorations that name them. + struct Type { std::uint32_t op = 0, component = 0, count = 0, width = 0; }; + std::map types; + std::map variable_type; // Output variable -> its pointer type + std::map location, builtin; // variable id -> value + std::set outputs; + for (std::size_t i = 5; i < vertex_words.size();) { + const std::uint32_t op = vertex_words[i] & 0xffffu, n = vertex_words[i] >> 16; + if (!n || i + n > vertex_words.size()) { + why = "the vertex shader's SPIR-V is cut short"; + return {}; + } + const std::uint32_t* w = &vertex_words[i]; + if (op == op_type_float && n >= 3) types[w[1]] = {op, 0, 0, w[2]}; + else if (op == op_type_vector && n >= 4) types[w[1]] = {op, w[2], w[3], 0}; + else if (op == op_type_pointer && n >= 4) types[w[1]] = {op, w[3], w[2], 0}; + else if (op == op_variable && n >= 4 && w[3] == storage_output) outputs.insert(w[2]), variable_type[w[2]] = w[1]; + else if (op == op_decorate && n >= 4 && w[2] == deco_location) location[w[1]] = w[3]; + else if (op == op_decorate && n >= 4 && w[2] == deco_builtin) builtin[w[1]] = w[3]; + i += n; + } + std::uint32_t position = 0; + std::vector params; // Location values, ascending + for (std::uint32_t id : outputs) { + const auto b = builtin.find(id); + if (b != builtin.end()) { + if (b->second == builtin_position) position = id; + else if (b->second != builtin_point_size) { + why = "the vertex shader writes ClipDistance, CullDistance, Layer or ViewportIndex"; + return {}; + } + continue; + } + const auto l = location.find(id); + if (l == location.end()) continue; + const Type& ptr = types[variable_type[id]]; + const Type& vec = types[ptr.component]; + const Type& scalar = types[vec.component]; + // Known limit: every vec4 float output gets the plain v2 + v3 - v1 corner. The translator can export an attribute + // as the register's raw bits with two packed f16 halves (only the pixel shader knows, through per_vertex in + // tools/rdna2spirv.py), and nothing on the vertex side tells those apart, so such an output would get a wrong + // fourth corner. Fixing it needs the pixel shader's words here and a per-channel marker from the translator. + if (vec.op != op_type_vector || vec.count != 4 || scalar.op != op_type_float || scalar.width != 32) { + why = "a vertex output is not a vec4 float"; + return {}; + } + params.push_back(l->second); + } + if (!position) { + why = "the vertex shader writes no Position"; + return {}; + } + std::sort(params.begin(), params.end()); + params.erase(std::unique(params.begin(), params.end()), params.end()); + + // The module: a fixed prelude, then per variable ids, then the body. Ids count up from 1. + std::uint32_t next = 1; + const auto id = [&] { return next++; }; + std::vector head, annotations, globals, body; + const auto emit = [](std::vector& to, std::uint32_t op, std::initializer_list args) { + to.push_back((std::uint32_t(args.size()) + 1) << 16 | op); + to.insert(to.end(), args.begin(), args.end()); + }; + const std::uint32_t t_void = id(), t_fn = id(), t_uint = id(), t_float = id(), t_v4 = id(), + c3 = id(), t_arr = id(), t_pin_arr = id(), t_pin_v4 = id(), + t_pout_v4 = id(), c0 = id(), c1 = id(), c2 = id(); + emit(globals, op_type_void, {t_void}); + emit(globals, op_type_function, {t_fn, t_void}); + emit(globals, op_type_int, {t_uint, 32, 0}); + emit(globals, op_type_float, {t_float, 32}); + emit(globals, op_type_vector, {t_v4, t_float, 4}); + emit(globals, op_constant, {t_uint, c3, 3}); + emit(globals, op_constant, {t_uint, c0, 0}); + emit(globals, op_constant, {t_uint, c1, 1}); + emit(globals, op_constant, {t_uint, c2, 2}); + emit(globals, op_type_array, {t_arr, t_v4, c3}); + emit(globals, op_type_pointer, {t_pin_arr, storage_input, t_arr}); + emit(globals, op_type_pointer, {t_pin_v4, storage_input, t_v4}); + emit(globals, op_type_pointer, {t_pout_v4, storage_output, t_v4}); + + struct Var { std::uint32_t in, out; bool is_position; }; + std::vector vars; + vars.push_back({id(), id(), true}); + for (std::size_t i = 0; i < params.size(); ++i) vars.push_back({id(), id(), false}); + std::vector io_vars; + emit(annotations, op_decorate, {vars[0].in, deco_builtin, builtin_position}); + emit(annotations, op_decorate, {vars[0].out, deco_builtin, builtin_position}); + for (std::size_t i = 0; i < params.size(); ++i) { + emit(annotations, op_decorate, {vars[i + 1].in, deco_location, params[i]}); + emit(annotations, op_decorate, {vars[i + 1].out, deco_location, params[i]}); + } + for (const Var& v : vars) { + emit(globals, op_variable, {t_pin_arr, v.in, storage_input}); + emit(globals, op_variable, {t_pout_v4, v.out, storage_output}); + io_vars.push_back(v.in); + io_vars.push_back(v.out); + } + + const std::uint32_t main_fn = id(), entry_label = id(); + emit(body, op_function, {t_void, main_fn, 0, t_fn}); + emit(body, op_label, {entry_label}); + // Per variable: the three corners, and the fourth, v2 + v3 - v1. + struct Corners { std::uint32_t v[4]; }; + std::vector corners; + const std::uint32_t cs[3] = {c0, c1, c2}; + for (const Var& v : vars) { + Corners c{}; + for (int k = 0; k < 3; ++k) { + const std::uint32_t ptr = id(); + c.v[k] = id(); + emit(body, op_access_chain, {t_pin_v4, ptr, v.in, cs[k]}); + emit(body, op_load, {t_v4, c.v[k], ptr}); + } + const std::uint32_t sum = id(), diff = id(); + // The fourth corner is v2 + v3 - v1, the rule d3d12_rect_list tests. OPEN QUESTION, opt-in with + // LEONIDA_RECT_FOURTH=v1v3: the retail title's full-screen rectangle draws were measured with corners + // top-left, bottom-left, bottom-right, where only v1 + v3 - v2 covers the target (see the pull request). + static const bool local_old_rule = [] { const char* e = std::getenv("LEONIDA_RECT_FOURTH"); return !(e && *e == 'v'); }(); + if (local_old_rule) { + emit(body, op_fadd, {t_v4, sum, c.v[1], c.v[2]}); + emit(body, op_fsub, {t_v4, diff, sum, c.v[0]}); + } else { + emit(body, op_fadd, {t_v4, sum, c.v[0], c.v[2]}); + emit(body, op_fsub, {t_v4, diff, sum, c.v[1]}); + } + c.v[3] = diff; + corners.push_back(c); + } + // Two triangles, (v1, v2, v4) and (v1, v4, v3): the diagonal is v1 to v4, so both start at v1 and a flat input + // (which Vulkan takes from a triangle's first vertex) is v1's over the whole rectangle. The attributes are + // affine over the parallelogram, so the split does not change any interpolated value. + static const bool local_old_split = [] { const char* e = std::getenv("LEONIDA_RECT_FOURTH"); return !(e && *e == 'v'); }(); + const int triangles_old[2][3] = {{0, 1, 3}, {0, 3, 2}}; + const int triangles_new[2][3] = {{0, 1, 2}, {0, 2, 3}}; // diagonal v1 to v3, both start at v1 + const auto& triangles = local_old_split ? triangles_old : triangles_new; + for (const auto& triangle : triangles) { + for (int k : triangle) { + for (std::size_t i = 0; i < vars.size(); ++i) emit(body, op_store, {vars[i].out, corners[i].v[k]}); + emit(body, op_emit_vertex, {}); + } + emit(body, op_end_primitive, {}); + } + emit(body, op_return, {}); + emit(body, op_function_end, {}); + + std::vector out{0x07230203u, 0x00010000u, 0, next, 0}; + emit(out, op_capability, {2}); // Geometry + emit(out, op_memory_model, {0, 1}); // Logical, GLSL450 + std::vector entry{3, main_fn, 0x6e69616du, 0}; // Geometry, %main, "main" + entry.insert(entry.end(), io_vars.begin(), io_vars.end()); + out.push_back((std::uint32_t(entry.size()) + 1) << 16 | op_entry_point); + out.insert(out.end(), entry.begin(), entry.end()); + emit(out, op_execution_mode, {main_fn, 22}); // Triangles + emit(out, op_execution_mode, {main_fn, 0, 1}); // Invocations 1 + emit(out, op_execution_mode, {main_fn, 29}); // OutputTriangleStrip + emit(out, op_execution_mode, {main_fn, 26, 6}); // OutputVertices 6 + out.insert(out.end(), annotations.begin(), annotations.end()); + out.insert(out.end(), globals.begin(), globals.end()); + out.insert(out.end(), body.begin(), body.end()); + return out; +} + +} // namespace leonida diff --git a/runtime/src/shader_library.h b/runtime/src/shader_library.h index 2fe53d4ec6..330d779327 100644 --- a/runtime/src/shader_library.h +++ b/runtime/src/shader_library.h @@ -33,6 +33,10 @@ namespace leonida { // --------------------------------------------------------------------------------------------------------------- // zlib inflate +// Why zlib_inflate failed, for a caller that reports the reason (runtime/shims/dstorage.cpp turns each into its +// E_DSTORAGE_ZLIB_* code). `limit`: the output would pass the caller's limit; the stream was not read to its end. +enum class ZlibError { none, header, data, checksum, limit }; + namespace detail { class BitReader { @@ -215,8 +219,8 @@ inline int decode(BitReader& in, const Huffman& h) { return -1; } -inline bool inflate_codes(BitReader& in, std::vector& out, const Huffman& lengths, - const Huffman& distances, std::size_t limit) { +inline ZlibError inflate_codes(BitReader& in, std::vector& out, const Huffman& lengths, + const Huffman& distances, std::size_t limit) { static constexpr std::int16_t length_base[29] = {3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258}; static constexpr std::int16_t length_extra[29] = {0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, @@ -228,20 +232,21 @@ inline bool inflate_codes(BitReader& in, std::vector& out, const H 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13}; for (;;) { int symbol = decode(in, lengths); - if (symbol < 0 || in.failed()) return false; + if (symbol < 0 || in.failed()) return ZlibError::data; if (symbol < 256) { - if (out.size() >= limit) return false; + if (out.size() >= limit) return ZlibError::limit; out.push_back(std::uint8_t(symbol)); continue; } - if (symbol == 256) return true; + if (symbol == 256) return ZlibError::none; symbol -= 257; - if (symbol >= 29) return false; + if (symbol >= 29) return ZlibError::data; const std::size_t length = std::size_t(length_base[symbol]) + in.bits(length_extra[symbol]); const int d = decode(in, distances); - if (d < 0 || d >= 30) return false; + if (d < 0 || d >= 30) return ZlibError::data; const std::size_t distance = std::size_t(distance_base[d]) + in.bits(distance_extra[d]); - if (in.failed() || distance > out.size() || out.size() + length > limit) return false; + if (in.failed() || distance > out.size()) return ZlibError::data; + if (out.size() + length > limit) return ZlibError::limit; const std::size_t from = out.size() - distance; for (std::size_t i = 0; i < length; ++i) out.push_back(out[from + i]); } @@ -250,28 +255,39 @@ inline bool inflate_codes(BitReader& in, std::vector& out, const H } // namespace detail // Inflates a zlib stream (RFC 1950: header, deflate data, Adler-32). Returns false for a malformed stream, a -// preset dictionary, a checksum mismatch, or output beyond `limit` bytes. +// preset dictionary, a checksum mismatch, or output beyond `limit` bytes, and then stores the reason in `*why` when +// it is given: `header` for the two header bytes (not deflate, a window over 32 KiB, a bad check value, a preset +// dictionary), `data` for the deflate data or a missing trailer, `checksum` for an Adler-32 mismatch, `limit` for +// output beyond `limit`. Bytes after the Adler-32 trailer are not read. inline bool zlib_inflate(std::span in, std::vector& out, - std::size_t limit = std::size_t(1) << 30) { + std::size_t limit = std::size_t(1) << 30, ZlibError* why = nullptr) { out.clear(); - if (in.size() < 6) return false; + const auto fail = [why](ZlibError reason) { + if (why) *why = reason; + return false; + }; + if (why) *why = ZlibError::none; + if (in.size() < 2) return fail(ZlibError::header); const unsigned cmf = in[0], flg = in[1]; - if ((cmf & 0x0f) != 8 || (cmf >> 4) > 7 || ((cmf << 8) | flg) % 31 != 0 || (flg & 0x20)) return false; + if ((cmf & 0x0f) != 8 || (cmf >> 4) > 7 || ((cmf << 8) | flg) % 31 != 0 || (flg & 0x20)) + return fail(ZlibError::header); + if (in.size() < 6) return fail(ZlibError::data); detail::BitReader reader(in.subspan(2)); for (bool last = false; !last;) { last = reader.bits(1) != 0; const std::uint32_t type = reader.bits(2); - if (reader.failed()) return false; + if (reader.failed()) return fail(ZlibError::data); if (type == 0) { // stored reader.align(); std::uint8_t b[4]; for (auto& x : b) - if (!reader.byte(x)) return false; + if (!reader.byte(x)) return fail(ZlibError::data); const unsigned length = b[0] | (b[1] << 8), complement = b[2] | (b[3] << 8); - if (length != (~complement & 0xffff) || out.size() + length > limit) return false; + if (length != (~complement & 0xffff)) return fail(ZlibError::data); + if (out.size() + length > limit) return fail(ZlibError::limit); for (unsigned i = 0; i < length; ++i) { std::uint8_t x; - if (!reader.byte(x)) return false; + if (!reader.byte(x)) return fail(ZlibError::data); out.push_back(x); } } else if (type == 1) { // fixed Huffman @@ -287,19 +303,21 @@ inline bool zlib_inflate(std::span in, std::vector 286 || distance_count > 30) return false; + if (literal_count > 286 || distance_count > 30) return fail(ZlibError::data); static constexpr int order[19] = {16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15}; std::int16_t lengths[320] = {}; for (int i = 0; i < code_count; ++i) lengths[order[i]] = std::int16_t(reader.bits(3)); detail::Huffman code_lengths; - if (!detail::build_huffman(code_lengths, lengths, 19)) return false; + if (!detail::build_huffman(code_lengths, lengths, 19)) return fail(ZlibError::data); for (int i = 0; i < literal_count + distance_count;) { const int symbol = detail::decode(reader, code_lengths); - if (symbol < 0) return false; + if (symbol < 0) return fail(ZlibError::data); if (symbol < 16) { lengths[i++] = std::int16_t(symbol); continue; @@ -307,7 +325,7 @@ inline bool zlib_inflate(std::span in, std::vector in, std::vector literal_count + distance_count) return false; + if (i + repeat > literal_count + distance_count) return fail(ZlibError::data); while (repeat--) lengths[i++] = value; } - if (lengths[256] == 0) return false; // no end-of-block code + if (lengths[256] == 0) return fail(ZlibError::data); // no end-of-block code detail::Huffman literal, distance; if (!detail::build_huffman(literal, lengths, literal_count) || !detail::build_huffman(distance, lengths + literal_count, distance_count)) - return false; - if (!detail::inflate_codes(reader, out, literal, distance, limit)) return false; + return fail(ZlibError::data); + if (const ZlibError e = detail::inflate_codes(reader, out, literal, distance, limit); e != ZlibError::none) + return fail(e); } else { - return false; + return fail(ZlibError::data); } - if (reader.failed()) return false; + if (reader.failed()) return fail(ZlibError::data); } // Adler-32, big-endian, after the deflate data's last whole byte. const std::size_t at = 2 + reader.position(); - if (at + 4 > in.size()) return false; + if (at + 4 > in.size()) return fail(ZlibError::data); std::uint32_t a = 1, b = 0; for (const std::uint8_t x : out) { a = (a + x) % 65521; @@ -339,7 +358,7 @@ inline bool zlib_inflate(std::span in, std::vector/index.json, then the indexes of the programs make_game.py translates from the package's DLLs, each - // when it is there: + // Reads /index.json, then the indexes of the programs make_game.py translates outside the game's shader + // entries, each when it is there: // - /fspx/index.json, the FidelityFX DLL's FSPX programs, entries named "fspx/" (docs/fspx.md); // - /bvh/index.json, XboxBvhBuilder.dll's FSSM programs, entries named "bvh/" and found by // fssm_sha256 like the game's own shaders (docs/embedded_shaders.md); // - /library/index.json, the compute programs of the pipeline library in shaders.rpf, which the executable // creates with slot 67; entries named "library/" and found by fspx_code_sha256 and fspx_state_sha256 - // like the FSPX ones (docs/shader_library.md). - // Entries with neither fssm_sha256 nor fspx_code_sha256 cannot be found by content and are skipped. Both folders - // are optional: a missing or unreadable index there leaves the main one, and the other folder's, loaded. + // like the FSPX ones (docs/shader_library.md); + // - /exe/index.json, game_scarlett_master.exe's embedded FSSM programs, entries named "exe/" and + // found by fssm_sha256 like the game's own shaders (docs/embedded_shaders.md). + // Entries with neither fssm_sha256 nor fspx_code_sha256 cannot be found by content and are skipped. The folders + // are optional: a missing or unreadable index there leaves the main one, and the other folders', loaded. bool load(const std::filesystem::path& dir, std::string* error = nullptr) { const auto fail = [&](const std::string& why) { if (error) *error = why; @@ -852,7 +873,7 @@ class ShaderLibrary { } catch (...) { return fail("index.json could not be read"); } - for (const char* sub_folder : {"fspx", "bvh", "library"}) { + for (const char* sub_folder : {"fspx", "bvh", "library", "exe"}) { try { const auto ignore = [](const std::string&) { return false; }; const std::filesystem::path sub = folder / sub_folder; @@ -875,6 +896,9 @@ class ShaderLibrary { // Entries loaded from /bvh/index.json. No RPF container reaches these either: XboxBvhBuilder.dll passes // their containers itself. std::size_t bvh_size() const { return bvh_count_; } + // Entries loaded from /exe/index.json. No RPF container reaches these either: game_scarlett_master.exe + // embeds their containers itself. + std::size_t exe_size() const { return exe_count_; } // The first entry for this program. Two containers can hold the same FSSM program with different input // signatures; `candidates` returns all of them. @@ -982,6 +1006,7 @@ class ShaderLibrary { count_ = 0; fspx_count_ = 0; bvh_count_ = 0; + exe_count_ = 0; } for (const auto& [name, meta] : root.object) { const Json* hash = meta.find("fssm_sha256"); @@ -1047,6 +1072,7 @@ class ShaderLibrary { if (by_fssm) entries_[{e.stage, e.fssm_sha256}].push_back(std::move(e)); if (by_fspx && (prefix == "fspx/" || prefix == "library/")) ++fspx_count_; if (prefix == "bvh/") ++bvh_count_; + if (prefix == "exe/") ++exe_count_; ++count_; } return true; @@ -1056,6 +1082,7 @@ class ShaderLibrary { std::size_t count_ = 0; std::size_t fspx_count_ = 0; std::size_t bvh_count_ = 0; + std::size_t exe_count_ = 0; // Entries by (stage, fssm_sha256) and by (stage, fspx_code_sha256), in index order. Entries entries_; Entries fspx_entries_; diff --git a/runtime/src/title_va_alias.h b/runtime/src/title_va_alias.h new file mode 100644 index 0000000000..829c1d8740 --- /dev/null +++ b/runtime/src/title_va_alias.h @@ -0,0 +1,250 @@ +#pragma once +// Buffer addresses in the title's own memory and the console VA a translated shader reaches them by +// (docs/d3d12_vulkan.md section 3.3, "Title-chosen addresses"). +// +// A translated shader computes heap_base + console_va, with heap_base the GPU address arena's device address. The +// layer chooses every console VA it hands out, so they all land in the arena. The title does not always use them: +// - device slot 133 places a buffer at the CPU address of the title's own pages (a user-mode Windows address, far above 4 GiB); +// - the title points V#s and root views at its own memory (a per-frame constant ring, #8862 section 3.5). +// Both are far past the arena, so heap_base + VA reads nothing the layer made. An address inside such a range is +// therefore replaced, wherever the layer can see it, by the console VA of a GPU copy of that range: its arena offset +// when the copy is an arena range (a slot-133 shadow, or a window of the title's pages copied before every +// submission), or its device address minus heap_base (mod 2^64) when it has its own memory (an imported slot-133 +// buffer). Addresses that are not in the title's memory are passed through unchanged. +// +// The table is process-wide, like the title's address space. The device behind it registers two hooks: a resolver +// that makes a GPU copy for an address in the title's memory that has none yet, and a scanner that rewrites the +// buffer V#s of a bound descriptor table before a submission. Without hooks the table only translates what was +// added to it, so it is tested without a GPU (title_va_alias_test). +#include +#include +#include +#include +#include +#include +#include +#include + +namespace leonida { + +class TitleVaAliases { +public: + // Where the layer saw the address, for the counters. + enum Kind : unsigned { root_view, created_view, table_view, vertex_view, index_view, kind_count }; + static constexpr const char* kKindNames[kind_count] = {"root view", "created view", "table V#", "vertex view", + "index view"}; + + // An address in the title's memory: true, with `shader_va` what a shader must be given (the address itself when + // no copy could be made). False: not the title's memory (an arena VA, a buffer of the layer's). + using Resolver = bool (*)(void* context, std::uint64_t va, std::uint64_t bytes, std::uint64_t& shader_va); + using TableScanner = void (*)(void* context, std::uint64_t table_va, std::uint32_t descriptors); + + // [title_va, title_va + bytes) is reached as [shader_va, shader_va + bytes). A range that overlaps a live one + // replaces it (the title has placed a new buffer over pages it released). False for an empty or wrapping range. + bool add(std::uint64_t title_va, std::uint64_t bytes, std::uint64_t shader_va) { + if (!bytes || title_va > UINT64_MAX - bytes) return false; + std::unique_lock lock(mutex_); + erase_overlapping(title_va, title_va + bytes); + ranges_[title_va] = {title_va + bytes, shader_va}; + count_.store(ranges_.size(), std::memory_order_release); + return true; + } + + // Forgets the range that starts at title_va, if it still maps to shader_va (a newer range at the same VA keeps + // its own entry). + void remove(std::uint64_t title_va, std::uint64_t shader_va) { + std::unique_lock lock(mutex_); + const auto it = ranges_.find(title_va); + if (it != ranges_.end() && it->second.shader_va == shader_va) ranges_.erase(it); + count_.store(ranges_.size(), std::memory_order_release); + } + + // The address a shader must be given for `va` from the ranges added so far: translated inside one, unchanged + // elsewhere. No copy is made here. + std::uint64_t shader_va(std::uint64_t va) const { + if (!count_.load(std::memory_order_acquire)) return va; // the common case: no title range at all + std::shared_lock lock(mutex_); + auto it = ranges_.upper_bound(va); + if (it == ranges_.begin()) return va; + --it; + if (va >= it->second.end) return va; + return it->second.shader_va + (va - it->first); + } + + // The free span around `va` (not in any range): [lo, hi). A copy made for `va` must stay inside it, so it never + // replaces a range another buffer still uses. + void gap(std::uint64_t va, std::uint64_t& lo, std::uint64_t& hi) const { + std::shared_lock lock(mutex_); + lo = 0; + hi = UINT64_MAX; + auto it = ranges_.upper_bound(va); + if (it != ranges_.end()) hi = it->first; + if (it != ranges_.begin()) lo = std::prev(it)->second.end; + } + + // shader_va, and when `va` is in the title's memory with no copy yet, a copy made by the device's resolver. + // Counted by kind: translated, or in the title's memory and left as it was. + std::uint64_t resolve(std::uint64_t va, std::uint64_t bytes, Kind kind) { + if (!va) return va; + std::uint64_t to = shader_va(va); + if (to != va) { + translated_[kind].fetch_add(1, std::memory_order_relaxed); + return to; + } + Resolver resolver; + void* context; + { + std::lock_guard lock(hook_mutex_); + resolver = resolver_; + context = hook_context_; + } + if (!resolver || !resolver(context, va, bytes, to)) return va; + (to != va ? translated_ : untranslated_)[kind].fetch_add(1, std::memory_order_relaxed); + return to; + } + + // Counts an address that the layer resolves through its buffer index instead (vertex and index views): only + // whether it is in a title range. + void note(std::uint64_t va, Kind kind) { + if (va && shader_va(va) != va) untranslated_[kind].fetch_add(1, std::memory_order_relaxed); + } + + // Before a submission: the device rewrites the buffer V#s of the `descriptors` slots the root signature declares + // for the table at `table_va` (a console VA in one of its shader-visible CBV/SRV/UAV heaps). + void scan_table(std::uint64_t table_va, std::uint32_t descriptors) { + TableScanner scanner; + void* context; + { + std::lock_guard lock(hook_mutex_); + scanner = scanner_; + context = hook_context_; + } + if (scanner) scanner(context, table_va, descriptors); + } + + // The scan's cost, per ExecuteCommandLists that had tables to scan. + void note_scan(std::uint64_t nanoseconds) { + scans_.fetch_add(1, std::memory_order_relaxed); + scan_ns_.fetch_add(nanoseconds, std::memory_order_relaxed); + std::uint64_t seen = scan_max_ns_.load(std::memory_order_relaxed); + while (nanoseconds > seen && !scan_max_ns_.compare_exchange_weak(seen, nanoseconds)) { + } + } + std::uint64_t scans() const { return scans_.load(std::memory_order_relaxed); } + std::uint64_t scan_ns() const { return scan_ns_.load(std::memory_order_relaxed); } + std::uint64_t scan_max_ns() const { return scan_max_ns_.load(std::memory_order_relaxed); } + + // The title's own memory, as the xmem shims hand it out (XMemAlloc, XMemVirtualAlloc, the title's VirtualAlloc): + // only an address in one of these ranges gets a copy. A base anywhere else (the runtime's own heap, a host DLL) + // is left as it was and counted. + void add_title_memory(std::uint64_t base, std::uint64_t bytes) { + if (!base || !bytes || base > UINT64_MAX - bytes) return; + std::uint64_t begin = base, end = base + bytes; + std::unique_lock lock(memory_mutex_); + // A commit inside a reserved range, or two that overlap, are one range. + auto it = memory_.upper_bound(begin); + if (it != memory_.begin() && std::prev(it)->second > begin) --it; + while (it != memory_.end() && it->first < end) { + begin = std::min(begin, it->first); + end = std::max(end, it->second); + it = memory_.erase(it); + } + memory_[begin] = end; + } + void remove_title_memory(std::uint64_t base) { + std::unique_lock lock(memory_mutex_); + memory_.erase(base); + } + // The title range that holds `va`: [lo, hi). False when none does. + bool title_memory(std::uint64_t va, std::uint64_t& lo, std::uint64_t& hi) const { + std::shared_lock lock(memory_mutex_); + auto it = memory_.upper_bound(va); + if (it == memory_.begin()) return false; + --it; + if (va >= it->second) return false; + lo = it->first; + hi = it->second; + return true; + } + + // A title that gives a descriptor heap its own backing memory (__XMemAllocationHooks__) writes descriptors there + // itself, while shaders read the layer's heap. The layer that keeps that mapping registers a source: before a + // bound table is scanned, it copies the slots the title wrote in its own memory over the layer's copy + // ([real, real + bytes) is the layer heap's CPU memory). Returns how many slots it copied. + using DescriptorSource = std::uint64_t (*)(void* context, std::uint8_t* real, std::size_t bytes); + void set_descriptor_source(void* context, DescriptorSource source) { + std::lock_guard lock(hook_mutex_); + source_context_ = context; + source_ = source; + } + void pull_descriptors(std::uint8_t* real, std::size_t bytes) { + DescriptorSource source; + void* context; + { + std::lock_guard lock(hook_mutex_); + source = source_; + context = source_context_; + } + if (source) pulled_.fetch_add(source(context, real, bytes), std::memory_order_relaxed); + } + std::uint64_t pulled() const { return pulled_.load(std::memory_order_relaxed); } + + // The first device to register keeps the hooks until it clears them. + void set_hooks(void* context, Resolver resolver, TableScanner scanner) { + std::lock_guard lock(hook_mutex_); + if (hook_context_) return; + hook_context_ = context; + resolver_ = resolver; + scanner_ = scanner; + } + void clear_hooks(void* context) { + std::lock_guard lock(hook_mutex_); + if (hook_context_ != context) return; + hook_context_ = nullptr; + resolver_ = nullptr; + scanner_ = nullptr; + } + + std::size_t size() const { return count_.load(std::memory_order_acquire); } + std::uint64_t translated(Kind kind) const { return translated_[kind].load(std::memory_order_relaxed); } + std::uint64_t untranslated(Kind kind) const { return untranslated_[kind].load(std::memory_order_relaxed); } + +private: + struct Range { + std::uint64_t end; // exclusive + std::uint64_t shader_va; // what the range's first byte becomes + }; + + void erase_overlapping(std::uint64_t begin, std::uint64_t end) { + auto it = ranges_.lower_bound(begin); + if (it != ranges_.begin()) { + auto previous = std::prev(it); + if (previous->second.end > begin) it = previous; + } + while (it != ranges_.end() && it->first < end) it = ranges_.erase(it); + } + + mutable std::shared_mutex mutex_; + std::map ranges_; // by title VA + std::atomic count_{0}; + std::mutex hook_mutex_; + void* hook_context_ = nullptr; + Resolver resolver_ = nullptr; + TableScanner scanner_ = nullptr; + void* source_context_ = nullptr; + DescriptorSource source_ = nullptr; + std::atomic pulled_{0}; + std::array, kind_count> translated_{}; + std::array, kind_count> untranslated_{}; + std::atomic scans_{0}, scan_ns_{0}, scan_max_ns_{0}; + mutable std::shared_mutex memory_mutex_; + std::map memory_; // the title's memory: base -> end +}; + +// The process's table: the device's title ranges and hooks, read by the command lists and descriptor writers. +inline TitleVaAliases& title_va_aliases() { + static TitleVaAliases aliases; + return aliases; +} + +} // namespace leonida diff --git a/runtime/src/tls_host.cpp b/runtime/src/tls_host.cpp index ab234cbd97..6cf5e70ae4 100644 --- a/runtime/src/tls_host.cpp +++ b/runtime/src/tls_host.cpp @@ -5,6 +5,12 @@ // __declspec(thread) access in mapped code reads a valid TEB slot. The anchor itself is never used; the loader saves // and restores the helper's own block, so the helper's CRT TLS state is not disturbed. // +// One more clone, leonida_tls_host__home.dll, is made at process start by reserve_tls_index0: its TLS directory +// is pointed at gta6rt_tls_home_template below, filled with a copy of the runtime EXE's template, and the runtime EXE +// moves its TLS from index 0 (which Windows gave it) to that clone's index, so a mapped executable can take index 0. +// That clone stays loaded until the process ends, and its slot then holds the runtime's live TLS, so nothing in this +// DLL may read or write its own TLS (gta6rt_tls_host_keep is never called). +// // The Windows loader also calls this DLL's DllMain with DLL_THREAD_ATTACH on every new thread (after it has built that // thread's TLS array) and with DLL_THREAD_DETACH when a thread exits (before it frees the array). The loader registers // a callback here so it can give each new thread its own copy of the mapped image's TLS, and put this DLL's block back @@ -26,6 +32,13 @@ void* volatile g_thread_event = nullptr; // the linker without making DllMain touch TLS during thread attach/detach. extern "C" __declspec(dllexport) void gta6rt_tls_host_keep() { g_tls_host_anchor = 1; } +// The home clone's TLS template (pe_loader.cpp, make_home_clone_image): zeros here, the runtime EXE's template in the +// clone's file. 16 KiB: gta6rt.exe's own TLS template was 1398 bytes when measured; the loader refuses the move when +// the EXE's TLS does not fit. Each thread gets a block of the EXE's size, not of this array's. Clones of this DLL for +// mapped DLLs keep the 514-byte TLS directory and do not use the array. +extern "C" __declspec(dllexport) const unsigned char gta6rt_tls_home_template[16384] = {}; +extern "C" __declspec(dllexport) const unsigned int gta6rt_tls_home_template_size = sizeof(gta6rt_tls_home_template); + // Called by the loader. `fn` runs inside DllMain (under the Windows loader lock) for DLL_THREAD_ATTACH and // DLL_THREAD_DETACH; nullptr stops the calls. extern "C" __declspec(dllexport) void gta6rt_tls_host_set_thread_event(ThreadEventFn fn) { diff --git a/runtime/src/vulkan_backend.h b/runtime/src/vulkan_backend.h index e3e4defe89..4bb6b53e36 100644 --- a/runtime/src/vulkan_backend.h +++ b/runtime/src/vulkan_backend.h @@ -104,7 +104,7 @@ struct VulkanDeviceFunctions { X(vkCmdSetPrimitiveTopology) X(vkCmdSetPrimitiveRestartEnable) X(vkCmdSetStencilReference) \ X(vkCmdSetBlendConstants) X(vkCmdDraw) \ X(vkCmdDrawIndexed) X(vkCreateGraphicsPipelines) X(vkQueueBindSparse) X(vkGetImageSparseMemoryRequirements) \ - X(vkCreatePipelineCache) X(vkDestroyPipelineCache) \ + X(vkCreatePipelineCache) X(vkDestroyPipelineCache) X(vkGetPipelineCacheData) X(vkMergePipelineCaches) \ X(vkCreateEvent) X(vkDestroyEvent) X(vkResetEvent) X(vkCmdSetEvent) X(vkCmdWaitEvents) X(vkCmdDrawMeshTasksEXT) \ X(vkCreateRenderPass2) X(vkDestroyRenderPass) X(vkCreateFramebuffer) X(vkDestroyFramebuffer) \ X(vkCmdBeginRenderPass) X(vkCmdEndRenderPass) @@ -1135,6 +1135,12 @@ class VulkanContext { std::unique_lock lock(resource_mutex_); set_resource_locked(id, binding); } + // Whether `va` is in a buffer this context knows by VA (the index buffer_at searches). + bool knows_buffer_va(std::uint64_t va) { + std::shared_lock lock(resource_mutex_); + BufferVaIndex::Hit hit{}; + return buffer_vas_.find(va, hit); + } void add_resource(ResourceId id, const ResourceBinding& binding, VkImageLayout current_layout) { std::unique_lock rlock(resource_mutex_); set_resource_locked(id, binding); @@ -1268,6 +1274,20 @@ class VulkanContext { replay_.zero_size = size; } + // LOCAL: the copy-in fallback for vertex and index views in title memory (ReplayFunctions::title_memory). + void set_title_memory(std::function copy) { + std::unique_lock lock(resource_mutex_); + replay_.title_memory = std::move(copy); + } + + // Pre-expanded 32-bit triangle indices for non-indexed quad lists (ReplayFunctions::quad_indices). + void set_quad_indices(VkBuffer buffer, VkDeviceSize offset, std::uint32_t count) { + std::unique_lock lock(resource_mutex_); + replay_.quad_indices = buffer; + replay_.quad_indices_offset = offset; + replay_.quad_index_count = count; + } + // Physical-device COLOR_ATTACHMENT format check for reinterpreted UAV clears. void set_color_attachment_format(std::function check) { std::unique_lock lock(resource_mutex_); @@ -1308,6 +1328,23 @@ class VulkanContext { return resources_.find(id) != resources_.end(); } + // The registered buffer whose VA range holds `va`, preferring one that holds [va, va + bytes) as buffer_at does: its + // ID, first VA and size in bytes. False when none does, or when `acquire(id)` returns false. `acquire` runs with + // the registry locked, so the resource cannot finish being removed under it: it takes the caller's reference + // (Resource's destructor removes its entry first, which waits for this lock). Used where a console call names a + // buffer by VA only (Xbox device slot 70). + template + bool buffer_resource_at(std::uint64_t va, std::uint64_t bytes, ResourceId& id, std::uint64_t& start, + std::uint64_t& size, Acquire&& acquire) { + std::shared_lock lock(resource_mutex_); + BufferVaIndex::Hit hit{}; + if (!buffer_vas_.find(va, hit, bytes) || !acquire(hit.id)) return false; + id = hit.id; + start = hit.start; + size = hit.size; + return true; + } + bool ray_tracing_supported() const { return ray_tracing_ && vk.vkCmdBuildAccelerationStructuresKHR != nullptr; } bool xdxr_acceleration_structures() const { return xdxr_ != nullptr; } @@ -1383,6 +1420,11 @@ class VulkanContext { // and records what the set needs first. When it fails, nothing of that call is executed. void set_transfer_only_family(std::uint32_t family) { transfer_only_family_ = family; } + // `before` is called at the start of every submission of command lists (a held batch: when it is released), + // before any lock here is taken: the device re-copies its slot-133 shadow buffers from the title's pages there. + // Set once, before the first queue exists. + void set_before_execute(std::function before) { before_execute_ = std::move(before); } + void set_bindless_prepare(std::function prepare) { std::unique_lock lock(resource_mutex_); bindless_prepare_ = std::move(prepare); @@ -1696,6 +1738,7 @@ class VulkanContext { std::map, VkRenderPass> resolve_passes_; std::map, VkFramebuffer> resolve_framebuffers_; + std::function before_execute_; std::function bindless_prepare_; std::function bindless_current_; bool bindless_upload_pending_ = false; // tracker_mutex_ @@ -2250,6 +2293,7 @@ class VulkanQueue : private QueueHolds::Holder { ReplayResult execute_now(std::span lists) { if (context_.is_device_lost() || !wait_for_room()) return ReplayResult::unsupported; + if (context_.before_execute_) context_.before_execute_(); if (kind_ != QueueKind::direct) for (const auto* list : lists) for (const auto& command : list->commands()) diff --git a/runtime/src/vulkan_present.h b/runtime/src/vulkan_present.h index 97c365b5f8..efdbd583d2 100644 --- a/runtime/src/vulkan_present.h +++ b/runtime/src/vulkan_present.h @@ -27,6 +27,7 @@ #include "vulkan_backend.h" #include "vulkan_present_compose.h" +#include "present_dump.h" // Use the original EXT spellings. They are aliases of the promoted KHR types and are available in older headers. #if defined(VK_EXT_SWAPCHAIN_MAINTENANCE_1_EXTENSION_NAME) && defined(VK_EXT_SURFACE_MAINTENANCE_1_EXTENSION_NAME) @@ -618,7 +619,15 @@ class VulkanPresenter { // Only a present the engine took counts (SUBOPTIMAL is shown too). OUT_OF_DATE was not shown: the swapchain // is recreated next time, and the caller sees VK_SUCCESS, since its work was submitted. if (result == VK_SUCCESS || result == VK_SUBOPTIMAL_KHR) { - ++presented_; + const auto shown = ++presented_; + if (dump_.due(shown - 1)) { + // Presentation is already queued and the queue/tracker locks are released. A sampled frame + // may stall here for its transfer fence and a private CPU copy. PNG and disk I/O run on a worker. + if (vkWaitForFences_(device, 1, &frame.done, VK_TRUE, UINT64_MAX) == VK_SUCCESS) + dump_.save(shown, extent_, format_, dump_pq_, capture_ptr_, size_t(capture_size_)); + else + dump_.disable("present dump fence wait failed"); + } if (planes) ++composed_; if (tearing) { last_tore_ = true; @@ -953,7 +962,7 @@ class VulkanPresenter { const VkImageSubresourceRange range{VK_IMAGE_ASPECT_COLOR_BIT, 0, 1, 0, 1}; VkImageLayout layout = VK_IMAGE_LAYOUT_TRANSFER_DST_OPTIMAL; VkAccessFlags access = VK_ACCESS_TRANSFER_WRITE_BIT; - if (capture_ && capture_buffer_) { + if (capture_buffer_ && (capture_ || dump_.due(presented_))) { // Two frames may be in flight and share `capture_buffer_`: serialize the prior frame's capture copy // before overwriting it, while moving this frame's swapchain image to TRANSFER_SRC. VkBufferMemoryBarrier capture_waw{VK_STRUCTURE_TYPE_BUFFER_MEMORY_BARRIER}; @@ -980,6 +989,10 @@ class VulkanPresenter { copy.imageExtent = {extent_.width, extent_.height, 1}; fn.copy_image_to_buffer(commands, images_[image], VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL, capture_buffer_, 1, ©); + auto to_host = capture_waw; + to_host.dstAccessMask = VK_ACCESS_HOST_READ_BIT; + fn.pipeline_barrier(commands, VK_PIPELINE_STAGE_TRANSFER_BIT, VK_PIPELINE_STAGE_HOST_BIT, 0, + 0, nullptr, 1, &to_host, 0, nullptr); layout = VK_IMAGE_LAYOUT_TRANSFER_SRC_OPTIMAL; access = VK_ACCESS_TRANSFER_READ_BIT; } @@ -992,7 +1005,7 @@ class VulkanPresenter { release_capture(); auto& vk = context_.vk; const VkDevice device = context_.device(); - capture_size_ = VkDeviceSize(extent_.width) * extent_.height * 4; + capture_size_ = VkDeviceSize(extent_.width) * extent_.height * present_dump::texel_size(format_); VkBufferCreateInfo info{VK_STRUCTURE_TYPE_BUFFER_CREATE_INFO}; info.size = capture_size_; info.usage = VK_BUFFER_USAGE_TRANSFER_DST_BIT; @@ -1180,7 +1193,9 @@ class VulkanPresenter { return true; } VkImageUsageFlags usage = VK_IMAGE_USAGE_TRANSFER_DST_BIT; - if (capture_) usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; + if (dump_.enabled() && !(caps.supportedUsageFlags & VK_IMAGE_USAGE_TRANSFER_SRC_BIT)) + dump_.disable("surface does not support swapchain readback"); + if (capture_ || dump_.enabled()) usage |= VK_IMAGE_USAGE_TRANSFER_SRC_BIT; if ((caps.supportedUsageFlags & usage) != usage) return false; // Not used by the presenter itself (it blits or copies into the images), but overlays that hook the swapchain // draw their own frame into its images through a framebuffer, which needs COLOR_ATTACHMENT: without it @@ -1324,13 +1339,14 @@ class VulkanPresenter { extent_ = extent; extent_packed_ = (std::uint64_t(extent.width) << 32) | extent.height; hdr_active_ = chose_hdr; - if (capture_) { - // A capture that cannot be made fails the recreation with the swapchain in place and stale_ still set. - const bool four_bytes = format_ == VK_FORMAT_B8G8R8A8_UNORM || format_ == VK_FORMAT_R8G8B8A8_UNORM || - format_ == VK_FORMAT_B8G8R8A8_SRGB || format_ == VK_FORMAT_R8G8B8A8_SRGB || - format_ == VK_FORMAT_A2B10G10R10_UNORM_PACK32 || - format_ == VK_FORMAT_A2R10G10B10_UNORM_PACK32; - if (!four_bytes || !make_capture_buffer()) return false; + dump_pq_ = chosen.colorSpace == VK_COLOR_SPACE_HDR10_ST2084_EXT; + if (capture_ || dump_.enabled()) { + const auto stride = present_dump::texel_size(format_); + if (capture_ && stride != 4) return false; // read_back() promises four bytes per texel + if (!stride || !make_capture_buffer()) { + dump_.disable("cannot read back this swapchain format or allocate its capture buffer"); + if (capture_) return false; + } } vsync_ = vsync; swapchain_srgb_ = srgb; @@ -1441,6 +1457,8 @@ class VulkanPresenter { std::map features_; bool warned_srgb_ = false; bool capture_ = false; + present_dump::PresentDump dump_; + bool dump_pq_ = false; VkBuffer capture_buffer_ = VK_NULL_HANDLE; VkDeviceMemory capture_memory_ = VK_NULL_HANDLE; VkDeviceSize capture_size_ = 0; diff --git a/runtime/src/vulkan_replay.h b/runtime/src/vulkan_replay.h index 889bb71f72..cdc6b5bfe8 100644 --- a/runtime/src/vulkan_replay.h +++ b/runtime/src/vulkan_replay.h @@ -1,3 +1,4 @@ +#include #pragma once #include "resource_tiling.h" @@ -32,6 +33,7 @@ #include "command_list.h" #include "depth24.h" +#include "rect_list_geometry.h" #include "uav_clear.h" #include @@ -43,6 +45,7 @@ #include #include #include +#include #include #include #include @@ -466,7 +469,11 @@ inline BlockFormat block_format(VkFormat format, VkImageAspectFlags aspect) { case VK_FORMAT_R8_UNORM: case VK_FORMAT_R8_SNORM: case VK_FORMAT_R8_UINT: - case VK_FORMAT_R8_SINT: return {1, 1}; + case VK_FORMAT_R8_SINT: +#ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME + case VK_FORMAT_A8_UNORM_KHR: // an A8_UNORM render target (VulkanDeviceInfo::a8_render_target) +#endif + return {1, 1}; case VK_FORMAT_BC1_RGBA_UNORM_BLOCK: case VK_FORMAT_BC1_RGBA_SRGB_BLOCK: case VK_FORMAT_BC4_UNORM_BLOCK: @@ -802,7 +809,6 @@ enum class ReplayResult { invalid_draw, // DispatchMesh with a pipeline that has no mesh shader, or a vertex draw with one that has unsupported }; - struct ReplayFunctions { // Set 0 for the pipelines that declare one (their own `bindless_set` is only the marker): the device's current // generation of it, which a flush may have replaced since the pipeline was made. Null: the pipeline's. @@ -862,6 +868,10 @@ struct ReplayFunctions { // cut to what the buffer holds from there: vertex and index views use what fits, WriteBufferImmediate needs all // of it. std::function buffer_at; + // A vertex or index view whose VA is the title's own CPU memory, not a registered buffer (on the console + // the GPU reads title memory directly). Copies [va, va + size) into a GPU-visible ring and names the copy; false + // when the range is not readable host memory. + std::function title_memory; // Host bytes for a whole console VA range; `not_cpu_written` when it names GPU-writable memory. For small // CPU-written inputs, such as the pointer list of an ARRAY_OF_POINTERS TLAS build. std::function host_at; @@ -869,6 +879,10 @@ struct ReplayFunctions { VkBuffer zero_buffer = VK_NULL_HANDLE; VkDeviceSize zero_offset = 0; VkDeviceSize zero_size = 0; + // 32-bit triangle indices for non-indexed quad lists: 0, 1, 2, 0, 2, 3, then the same pattern for each quad. + VkBuffer quad_indices = VK_NULL_HANDLE; + VkDeviceSize quad_indices_offset = 0; + std::uint32_t quad_index_count = 0; std::uint64_t heap_base = 0; // device address of the GPU address arena (push-constant dwords 32-33) // Resolves available binary-occlusion queries to 64-bit 0/1 values, outside conditional rendering. std::functionvertex_buffers[slot]; std::uint64_t size = view.size; - if (!vk.buffer_at(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) - return ReplayResult::unresolved_resource; + if (!vk.buffer_at(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) { + size = view.size; + if (!vk.title_memory || !vk.title_memory(view.va, size, p.vertex_buffers[slot], p.vertex_offsets[slot])) + return ReplayResult::unresolved_resource; + } p.vertex_sizes[slot] = size; p.vertex_strides[slot] = (pipeline->zero_step_slots & (1u << slot)) ? 0 : view.stride; } + // A non-indexed quad list is drawn from the shared triangle index buffer (emit). + if (!draw.indexed && !draw.mesh && draw.topology == topology_quad_list && !vk.quad_indices) + return ReplayResult::unresolved_resource; if (draw.indexed) { if (draw.index.format == 57) p.index_type = VK_INDEX_TYPE_UINT16; else if (draw.index.format == 42) p.index_type = VK_INDEX_TYPE_UINT32; @@ -2203,8 +2226,11 @@ ReplayResult prepare_draw(const Draw& draw, Resolve&& resolve, const ReplayFunct p.index_offset = vk.zero_offset; } else { std::uint64_t size = draw.index.size; - if (!vk.buffer_at(draw.index.va, size, p.index_buffer, p.index_offset)) - return ReplayResult::unresolved_resource; + if (!vk.buffer_at(draw.index.va, size, p.index_buffer, p.index_offset)) { + size = draw.index.size; + if (!vk.title_memory || !vk.title_memory(draw.index.va, size, p.index_buffer, p.index_offset)) + return ReplayResult::unresolved_resource; + } } } return ReplayResult::success; @@ -2227,6 +2253,10 @@ inline VkPrimitiveTopology vulkan_topology(std::uint32_t topology) { case 11: return VK_PRIMITIVE_TOPOLOGY_LINE_STRIP_WITH_ADJACENCY; case 12: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST_WITH_ADJACENCY; case 13: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_STRIP_WITH_ADJACENCY; + // Rectangles draw as triangle lists through a geometry stage. Indexed quads draw as separate fans; + // emit() overrides non-indexed quads to a triangle list backed by the shared indices. + case topology_rect_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; + case topology_quad_list: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN; default: return VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST; } } @@ -4190,7 +4220,8 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c // A mesh pipeline has no input assembly: its topology comes from the shader, and neither the topology // nor primitive restart is dynamic state there (VUID-VkGraphicsPipelineCreateInfo-pDynamicStates-07065). if (!draw->mesh) { - const VkPrimitiveTopology topology = detail::vulkan_topology(draw->topology); + const VkPrimitiveTopology topology = draw->topology == topology_quad_list && !draw->indexed + ? VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST : detail::vulkan_topology(draw->topology); vk.set_primitive_topology(command_buffer, topology); const bool restart = draw->indexed && detail::strip_topology(topology) && ((graphics.strip_cut == 1 && d.index_type == VK_INDEX_TYPE_UINT16) || @@ -4207,6 +4238,28 @@ inline void emit(const PreparedList& prepared, VkCommandBuffer command_buffer, c } if (draw->mesh) { vk.draw_mesh_tasks(command_buffer, draw->count, draw->instances, draw->first); + } else if (draw->topology == topology_quad_list) { + if (draw->indexed) { + // Indexed quads still read their vertices from the application's index buffer, one fan per quad. + vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); + for (std::uint32_t quad = 0; quad < draw->count / 4; ++quad) + vk.draw_indexed(command_buffer, 4, draw->instances, draw->first + 4 * quad, + draw->base_vertex, draw->first_instance); + } else { + // Both triangles start at the quad's first vertex for flat inputs. One draw also preserves + // the original instance order, and VertexIndex - BaseVertex still gives 4q + k. + constexpr std::uint32_t indices_per_quad = quad_triangle_indices.size(); + const std::uint32_t wanted = draw->count / 4; + const std::uint32_t quads = std::min(wanted, vk.quad_index_count / indices_per_quad); + if (quads < wanted) + std::fprintf(stderr, "[rt] d3d12: a non-indexed quad list of %u quads draws only the first %u\n", + wanted, quads); + if (quads) { + vk.bind_index_buffer(command_buffer, vk.quad_indices, vk.quad_indices_offset, VK_INDEX_TYPE_UINT32); + vk.draw_indexed(command_buffer, quads * indices_per_quad, draw->instances, 0, + std::int32_t(draw->first), draw->first_instance); + } + } } else if (draw->indexed) { vk.bind_index_buffer(command_buffer, d.index_buffer, d.index_offset, d.index_type); vk.draw_indexed(command_buffer, draw->count, draw->instances, draw->first, draw->base_vertex, diff --git a/runtime/test/allocator_proxy_test.cpp b/runtime/test/allocator_proxy_test.cpp index 5f89366f54..b48b224b72 100644 --- a/runtime/test/allocator_proxy_test.cpp +++ b/runtime/test/allocator_proxy_test.cpp @@ -58,11 +58,13 @@ using SlotFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std:: std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t, std::uint64_t); -// A call through slot `slot` with all words zero, the way a title calls a console method the PC interface lacks. -HRESULT call_slot(void* object, unsigned slot) { +// A call through slot `slot` with up to four explicit words (rest zero), the way a title calls a console method the PC +// interface lacks. +HRESULT call_slot(void* object, unsigned slot, std::uint64_t a1 = 0, std::uint64_t a2 = 0, std::uint64_t a3 = 0, + std::uint64_t a4 = 0) { void** vtable = *reinterpret_cast(object); return static_cast(static_cast( - reinterpret_cast(vtable[slot])(object, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))); + reinterpret_cast(vtable[slot])(object, a1, a2, a3, a4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0))); } ULONG_PTR g_fault_address = 0; @@ -182,10 +184,24 @@ int check_proxy(const Backend& b, ID3D12CommandAllocator* allocator) { back->Release(); EXPECT(SUCCEEDED(allocator->SetPrivateDataInterface(key, nullptr))); - // The refused tail: every slot past the public chain, up to the table end, is E_NOTIMPL and counted. + // Console slot 9 (SetAllocatorCallbackX): records callback/context on the proxy and returns S_OK. const unsigned table = xs::allocator_proxy_table_size(); EXPECT(table == 64); - for (unsigned slot = 9; slot < table; ++slot) { + { + EXPECT(xs::allocator_proxy_callback(allocator) == 0 && xs::allocator_proxy_callback_context(allocator) == 0); + constexpr std::uintptr_t fake_cb = 0x11223344u; + constexpr std::uintptr_t fake_ctx = 0x55667788u; + const std::uint64_t before = xs::allocator_slot_hits(9); + EXPECT(call_slot(allocator, 9, fake_cb, fake_ctx, 0, 0x99aabbccu) == S_OK); + EXPECT(xs::allocator_slot_hits(9) == before + 1 && xs::allocator_slot_first_call_seen(9)); + EXPECT(xs::allocator_proxy_callback(allocator) == fake_cb && + xs::allocator_proxy_callback_context(allocator) == fake_ctx); + EXPECT(call_slot(allocator, 9, 0, 0) == S_OK); + EXPECT(xs::allocator_proxy_callback(allocator) == 0 && xs::allocator_proxy_callback_context(allocator) == 0); + } + + // The refused tail: every slot past slot 9, up to the table end, is E_NOTIMPL and counted. + for (unsigned slot = 10; slot < table; ++slot) { const std::uint64_t before = xs::allocator_slot_hits(slot); EXPECT(call_slot(allocator, slot) == E_NOTIMPL); EXPECT(xs::allocator_slot_hits(slot) == before + 1 && xs::allocator_slot_first_call_seen(slot)); @@ -201,8 +217,9 @@ int check_proxy(const Backend& b, ID3D12CommandAllocator* allocator) { EXPECT(g_fault_address == reinterpret_cast(&vtable[slot])); EXPECT(xs::allocator_table_overruns() == before + 1); } - std::printf("%s: allocator proxy: 9 public slots forwarded, slots 9-%u refused, the guard region names a read " - "past the table; QueryInterface/GetDevice/private data keep the proxy identity\n", label, table - 1); + std::printf("%s: allocator proxy: 9 public slots forwarded, slot 9 SetAllocatorCallbackX handled, slots 10-%u " + "refused, the guard region names a read past the table; QueryInterface/GetDevice/private data keep " + "the proxy identity\n", label, table - 1); return 0; } diff --git a/runtime/test/check_pipeline_cache_seed.cmake b/runtime/test/check_pipeline_cache_seed.cmake new file mode 100644 index 0000000000..89a3c2ab6c --- /dev/null +++ b/runtime/test/check_pipeline_cache_seed.cmake @@ -0,0 +1,33 @@ +# The cache vk_pipeline_check saves must hit on the runtime's device: the checker compiles one synthetic compute +# shader into a cache, then pipeline_cache_seed_test creates the same pipeline on the runtime's device from it. +# +# The checker runs as a copy with the test program's file name: a driver can make the executable's file name part of +# the cache key (docs/pipeline_check.md, "The cache and the runtime's device"), and this test is about the device. +file(REMOVE_RECURSE "${TEST_DIR}") +file(MAKE_DIRECTORY "${TEST_DIR}/checker") +file(COPY_FILE "${SHADER}" "${TEST_DIR}/seed.spv") +file(WRITE "${TEST_DIR}/index.json" "{\"seed\":{\"stage\":\"cs\",\"bindings\":[],\"push_constant_bytes\":144," + "\"local_size\":[1,1,1],\"wave64\":false}}\n") +get_filename_component(test_name "${TEST}" NAME) +set(checker "${TEST_DIR}/checker/${test_name}") +file(COPY_FILE "${CHECKER}" "${checker}") + +execute_process(COMMAND ${RUNNER} "${checker}" "${TEST_DIR}" "${TEST_DIR}/pipeline_cache.bin" --jobs 1 + RESULT_VARIABLE code OUTPUT_VARIABLE log ERROR_VARIABLE log TIMEOUT 120) +if(NOT log MATCHES "cs pipelines: 1 ok, 0 failed, 0 skipped" OR NOT EXISTS "${TEST_DIR}/pipeline_cache.bin") + if(log MATCHES "no Vulkan physical device|vulkan-1|libvulkan|cs pipelines: 0 ok, 0 failed, 1 skipped") + message(STATUS "SKIP: vk_pipeline_check built no pipeline here\n${log}") + return() + endif() + message(FATAL_ERROR "vk_pipeline_check did not build the pipeline (${code})\n${log}") +endif() + +execute_process(COMMAND ${RUNNER} "${TEST}" "${TEST_DIR}/seed.spv" "${TEST_DIR}/pipeline_cache.bin" + RESULT_VARIABLE code OUTPUT_VARIABLE log ERROR_VARIABLE log TIMEOUT 120) +message(STATUS "${log}") +if(code STREQUAL "77") + return() # the test printed its own SKIP line +endif() +if(NOT code STREQUAL "0") + message(FATAL_ERROR "pipeline_cache_seed_test failed (${code})") +endif() diff --git a/runtime/test/check_tiny_frame.py b/runtime/test/check_tiny_frame.py index 2a734e43e4..b67e468d7c 100644 --- a/runtime/test/check_tiny_frame.py +++ b/runtime/test/check_tiny_frame.py @@ -124,7 +124,10 @@ def main(): print("SKIP: no usable Vulkan device (the probe test skipped)") return SKIP - environment = dict(os.environ, LEONIDA_D3D12="vulkan") + # The fixture is compiled against the PC headers, so it calls the command list through PC vtable + # indices; LEONIDA_D3D12_LISTS=pc asks the proxy for PC-shaped lists. The console-shaped device, + # queue, heap and fence it checks stay console-shaped. + environment = dict(os.environ, LEONIDA_D3D12="vulkan", LEONIDA_D3D12_LISTS="pc") if options.queue_test_settings: environment.update(QUEUE_TEST_SETTINGS) run = subprocess.run([*options.runner, options.loader, "--run", os.path.basename(options.guest), "--trace-d3d12"], diff --git a/runtime/test/check_tls_clone_cleanup.cmake b/runtime/test/check_tls_clone_cleanup.cmake new file mode 100644 index 0000000000..21130ce328 --- /dev/null +++ b/runtime/test/check_tls_clone_cleanup.cmake @@ -0,0 +1,40 @@ +# gta6rt --dry-run, --init and --dry-run again with tiny_tls_clones.exe, which maps three TLS modules and so makes a +# helper clone for one of its DLLs. After each run no clone file of that run's process may remain in the temporary +# folder but its home clone (leonida_tls_host__home.dll), which is mapped until the process ends and cannot be +# deleted before; the next run's sweep must delete that one. The process ID comes from the trace's first line. A gta6rt +# running beside this test may sweep the home clone first, so its absence is fine. +if(DEFINED ENV{TMP}) + set(temp "$ENV{TMP}") +else() + set(temp "$ENV{TEMP}") +endif() +file(TO_CMAKE_PATH "${temp}" temp) +set(previous "") +foreach(mode dry-run init dry-run) + set(trace "${TRACE_DIR}/tls_clone_cleanup.jsonl") + file(REMOVE "${trace}") # --trace only creates a new file + execute_process( + COMMAND ${RUNNER} "${LOADER}" --${mode} "${GUEST}" --trace "${trace}" + TIMEOUT 90 + RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE error) + if(NOT code STREQUAL "0" OR NOT output MATCHES "3 module\\(s\\) mapped") + message(FATAL_ERROR "--${mode} returned ${code}\n${output}\n${error}") + endif() + file(STRINGS "${trace}" first LIMIT_COUNT 1) + file(REMOVE "${trace}") + if(NOT first MATCHES "\"pid\":([0-9]+)") + message(FATAL_ERROR "--${mode}: no pid in the trace: ${first}") + endif() + set(pid "${CMAKE_MATCH_1}") + file(GLOB left "${temp}/leonida_tls_host_${pid}_*.dll") + if(left AND NOT left STREQUAL "${temp}/leonida_tls_host_${pid}_home.dll") + message(FATAL_ERROR "--${mode} (pid ${pid}) left clone files other than its home clone: ${left}") + endif() + if(previous) + file(GLOB swept "${temp}/leonida_tls_host_${previous}_*.dll") + if(swept) + message(FATAL_ERROR "the run after pid ${previous} did not delete its clone files: ${swept}") + endif() + endif() + set(previous "${pid}") +endforeach() diff --git a/runtime/test/check_tls_index0.cmake b/runtime/test/check_tls_index0.cmake new file mode 100644 index 0000000000..a1ca31b8ff --- /dev/null +++ b/runtime/test/check_tls_index0.cmake @@ -0,0 +1,46 @@ +# gta6rt --run and --init with tiny_tls_ga.exe, an executable built /GA whose thread_local reads go straight to +# ThreadLocalStoragePointer[0]. --run: the game thread and a second thread both read the template value 42 and +# _tls_index is 0. Both modes: the startup trace names gta6rt.exe as the image that held module TLS index 0 and the +# index its block moved to. Then, with TMP and TEMP naming a missing folder, the home clone cannot be written and the +# reservation fails before main: --run and --init refuse the image with that reason and run none of its code, and +# --dry-run maps it with the note. (A TMP longer than MAX_PATH does not get this far: GetTempPathW then skips it.) +foreach(mode run init) + set(trace "${TRACE_DIR}/tls_index0_${mode}.jsonl") + file(REMOVE "${trace}") # --trace only creates a new file + execute_process( + COMMAND ${RUNNER} "${LOADER}" --${mode} "${GUEST}" --trace "${trace}" + TIMEOUT 90 + RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE error) + if(NOT code STREQUAL "0") + message(FATAL_ERROR "--${mode} returned ${code}\n${output}\n${error}") + endif() + if(mode STREQUAL "run" AND (NOT output MATCHES "tiny_tls_ga: tls_index=0 main=42 thread=42 OK" + OR NOT output MATCHES "game exited with code 0")) + message(FATAL_ERROR "--run did not read the TLS from slot 0\n${output}\n${error}") + endif() + if(error MATCHES "does not get module TLS index 0") + message(FATAL_ERROR "--${mode}: the executable was not given index 0\n${error}") + endif() + file(READ "${trace}" lines) + if(NOT lines MATCHES "\"kind\":\"tls_index0\",\"owner\":\"gta6rt.exe\",\"moved_to\":[1-9][0-9]*}") + message(FATAL_ERROR "--${mode}: no tls_index0 event naming gta6rt.exe in the trace\n${lines}") + endif() + file(REMOVE "${trace}") +endforeach() + +set(missing "${TRACE_DIR}/leonida_no_such_temp") +file(REMOVE_RECURSE "${missing}") +foreach(mode run init dry-run) + execute_process( + COMMAND ${CMAKE_COMMAND} -E env "TMP=${missing}" "TEMP=${missing}" ${RUNNER} "${LOADER}" --${mode} "${GUEST}" + TIMEOUT 90 + RESULT_VARIABLE code OUTPUT_VARIABLE output ERROR_VARIABLE error) + set(reason "module TLS index 0 \\(the home clone of gta6rt_tls_host.dll cannot be loaded") + if(mode STREQUAL "dry-run") + if(NOT code STREQUAL "0" OR NOT error MATCHES "does not get ${reason}") + message(FATAL_ERROR "--dry-run without the reservation returned ${code}\n${output}\n${error}") + endif() + elseif(NOT code STREQUAL "1" OR NOT error MATCHES "cannot have ${reason}" OR output MATCHES "running ") + message(FATAL_ERROR "--${mode} without the reservation returned ${code}\n${output}\n${error}") + endif() +endforeach() diff --git a/runtime/test/d3d12_a8_dimensions_test.cpp b/runtime/test/d3d12_a8_dimensions_test.cpp new file mode 100644 index 0000000000..c421bed89c --- /dev/null +++ b/runtime/test/d3d12_a8_dimensions_test.cpp @@ -0,0 +1,233 @@ +// DXGI_FORMAT_A8_UNORM textures in 1D and 3D. The host makes them (a title's boot sizes a 128-texel 1D one through +// GetResourceAllocationInfo); the layer refused every A8_UNORM texture that was not 2D. They are R8_UNORM images, like +// the 2D ones, and their SRVs read (0, 0, 0, A). +// +// Exercises, for a 1D (128) and a 3D (8x8x4) texture: +// 1. CheckFeatureSupport advertises TEXTURE1D and TEXTURE3D for A8_UNORM +// 2. GetResourceAllocationInfo gives a size and CreateCommittedResource makes the texture +// 3. Bytes uploaded with CopyTextureRegion come back unchanged +// 4. The default SRV is a T# of the right image type, in R8_UNORM's GFX10 format, with the swizzle (0, 0, 0, X) +// 5. Negative controls: unordered access and depth-stencil are still refused in both dimensions +// +// Synthetic data only; no game files. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" +#include "../src/gfx10_descriptors.h" + +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +namespace g = leonida::gfx10; + +template +struct Ref { + T* p = nullptr; + ~Ref() { reset(); } + void reset() { + if (p) p->Release(); + p = nullptr; + } + T* operator->() const { return p; } +}; + +D3D12_RESOURCE_DESC a8_desc(D3D12_RESOURCE_DIMENSION dimension, UINT64 width, UINT height, UINT16 depth, + D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = dimension; + d.Width = width; + d.Height = height; + d.DepthOrArraySize = depth; + d.MipLevels = 1; + d.Format = DXGI_FORMAT_A8_UNORM; + d.SampleDesc = {1, 0}; + d.Flags = flags; + return d; +} + +D3D12_RESOURCE_DESC buf_desc(UINT64 bytes) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = bytes; + d.Height = 1; + d.DepthOrArraySize = 1; + d.MipLevels = 1; + d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + return d; +} + +D3D12_RESOURCE_BARRIER transition(ID3D12Resource* resource, D3D12_RESOURCE_STATES before, D3D12_RESOURCE_STATES after) { + D3D12_RESOURCE_BARRIER b{}; + b.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b.Transition = {resource, D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, before, after}; + return b; +} + +std::uint8_t texel(UINT x, UINT y, UINT z) { return std::uint8_t(1 + x + 7 * y + 61 * z); } + +} // namespace + +int main() { + vktest::Device d; + const auto status = d.initialize(); + if (status == vktest::DeviceStatus::unavailable) return 77; + if (status != vktest::DeviceStatus::ready) return 1; + + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.bindless = d.bindless; + info.bindless_partially_bound = d.partially_bound; + info.image_view_min_lod = d.image_view_min_lod; + info.host_image_copy = d.host_image_copy; + Ref device; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&device.p)))); + + // 1. Format support names both dimensions, as the host's does. + D3D12_FEATURE_DATA_FORMAT_SUPPORT support{DXGI_FORMAT_A8_UNORM}; + EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &support, sizeof(support)))); + EXPECT((support.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE1D) && (support.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE2D) && + (support.Support1 & D3D12_FORMAT_SUPPORT1_TEXTURE3D)); + + Ref queue; + const D3D12_COMMAND_QUEUE_DESC qd{D3D12_COMMAND_LIST_TYPE_DIRECT}; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&qd, IID_PPV_ARGS(&queue.p)))); + Ref alloc; + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&alloc.p)))); + Ref fence; + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + Ref cpu_heap; + const D3D12_DESCRIPTOR_HEAP_DESC cpu_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_NONE}; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&cpu_desc, IID_PPV_ARGS(&cpu_heap.p)))); + const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + EXPECT(step >= sizeof(g::ImageWords)); + + const D3D12_HEAP_PROPERTIES def_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_HEAP_PROPERTIES up_heap{D3D12_HEAP_TYPE_UPLOAD}; + const D3D12_HEAP_PROPERTIES rb_heap{D3D12_HEAP_TYPE_READBACK}; + const std::uint32_t r8_code = g::format_from_vulkan(VK_FORMAT_R8_UNORM); + EXPECT(r8_code != 0); + + struct Case { + const char* name; + D3D12_RESOURCE_DESC desc; + g::ImageType type; + }; + const Case cases[] = { + {"1D", a8_desc(D3D12_RESOURCE_DIMENSION_TEXTURE1D, 128, 1, 1), g::ImageType::image_1d}, + {"3D", a8_desc(D3D12_RESOURCE_DIMENSION_TEXTURE3D, 8, 8, 4), g::ImageType::image_3d}, + }; + UINT64 fence_value = 0; + for (UINT c = 0; c < 2; ++c) { + const Case& k = cases[c]; + const UINT width = UINT(k.desc.Width), height = k.desc.Height; + const UINT depth = k.desc.Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE3D ? k.desc.DepthOrArraySize : 1u; + + // 5. Negative controls first: the flags A8_UNORM never takes stay refused in this dimension. + for (auto flag : {D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS, D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL}) { + const auto refused = a8_desc(k.desc.Dimension, k.desc.Width, k.desc.Height, k.desc.DepthOrArraySize, flag); + EXPECT(device->GetResourceAllocationInfo(0, 1, &refused).SizeInBytes == UINT64_MAX); + } + + // 2. A size and a texture. + const auto alloc_info = device->GetResourceAllocationInfo(0, 1, &k.desc); + EXPECT(alloc_info.SizeInBytes != UINT64_MAX && alloc_info.SizeInBytes >= UINT64(width) * height * depth); + Ref tex; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&def_heap, D3D12_HEAP_FLAG_NONE, &k.desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&tex.p)))); + + // 3. Upload, copy back, compare. + D3D12_PLACED_SUBRESOURCE_FOOTPRINT fp{}; + UINT64 total = 0; + device->GetCopyableFootprints(&k.desc, 0, 1, 0, &fp, nullptr, nullptr, &total); + EXPECT(fp.Footprint.Format == DXGI_FORMAT_A8_UNORM && fp.Footprint.Width == width && + fp.Footprint.Height == height && fp.Footprint.Depth == depth && total != UINT64_MAX); + const auto staging_desc = buf_desc(total); + Ref upload, readback; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&up_heap, D3D12_HEAP_FLAG_NONE, &staging_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&upload.p)))); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&rb_heap, D3D12_HEAP_FLAG_NONE, &staging_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + const UINT pitch = fp.Footprint.RowPitch; + void* mapped = nullptr; + EXPECT(SUCCEEDED(upload->Map(0, nullptr, &mapped))); + std::memset(mapped, 0, size_t(total)); + for (UINT z = 0; z < depth; ++z) + for (UINT y = 0; y < height; ++y) + for (UINT x = 0; x < width; ++x) + static_cast(mapped)[size_t(z) * pitch * height + size_t(y) * pitch + x] = + texel(x, y, z); + upload->Unmap(0, nullptr); + + Ref list; + EXPECT(SUCCEEDED(alloc->Reset())); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, alloc.p, nullptr, + IID_PPV_ARGS(&list.p)))); + D3D12_TEXTURE_COPY_LOCATION placed_up{upload.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + placed_up.PlacedFootprint = fp; + D3D12_TEXTURE_COPY_LOCATION sub{tex.p, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX}; + sub.SubresourceIndex = 0; + list->CopyTextureRegion(&sub, 0, 0, 0, &placed_up, nullptr); + const auto to_src = transition(tex.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_src); + D3D12_TEXTURE_COPY_LOCATION placed_rb{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT}; + placed_rb.PlacedFootprint = fp; + list->CopyTextureRegion(&placed_rb, 0, 0, 0, &sub, nullptr); + EXPECT(SUCCEEDED(list->Close())); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence.p, ++fence_value))); + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + EXPECT(event != nullptr); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(fence_value, event))); + const DWORD waited = WaitForSingleObject(event, 10000); + CloseHandle(event); + EXPECT(waited == WAIT_OBJECT_0); + + void* back = nullptr; + const D3D12_RANGE read{0, size_t(total)}; + EXPECT(SUCCEEDED(readback->Map(0, &read, &back))); + UINT mismatches = 0; + for (UINT z = 0; z < depth; ++z) + for (UINT y = 0; y < height; ++y) + for (UINT x = 0; x < width; ++x) + mismatches += static_cast(back)[size_t(z) * pitch * height + + size_t(y) * pitch + x] != texel(x, y, z); + readback->Unmap(0, nullptr); + if (mismatches) std::fprintf(stderr, "%s: %u of %u texels differ\n", k.name, mismatches, width * height * depth); + EXPECT(mismatches == 0); + + // 4. The default SRV: the image type, R8_UNORM's format and the alpha-only swizzle. + D3D12_CPU_DESCRIPTOR_HANDLE handle = cpu_heap->GetCPUDescriptorHandleForHeapStart(); + handle.ptr += SIZE_T(c) * step; + std::memset(reinterpret_cast(handle.ptr), 0x77, step); + device->CreateShaderResourceView(tex.p, nullptr, handle); + g::ImageWords words{}; + std::memcpy(words.data(), reinterpret_cast(handle.ptr), sizeof(words)); + g::Image image{}; + EXPECT(g::is_image(words) && g::decode(words, image)); + EXPECT(image.type == k.type && image.width == width && image.format == r8_code); + EXPECT(k.type != g::ImageType::image_3d || (image.height == height && image.depth == depth)); + const g::Swizzle alpha_only{g::select_zero, g::select_zero, g::select_zero, g::select_x}; + EXPECT(image.swizzle == alpha_only); + std::printf("A8_UNORM %s: sized %llu B, %u texels round-trip, SRV reads (0, 0, 0, A)\n", k.name, + static_cast(alloc_info.SizeInBytes), width * height * depth); + } + std::printf("d3d12_a8_dimensions: PASS\n"); + return 0; +} diff --git a/runtime/test/d3d12_buffer_uav_test.cpp b/runtime/test/d3d12_buffer_uav_test.cpp index a2fa903302..c2ea4fb37a 100644 --- a/runtime/test/d3d12_buffer_uav_test.cpp +++ b/runtime/test/d3d12_buffer_uav_test.cpp @@ -161,7 +161,7 @@ int run_shaders(vktest::Device& d, const std::filesystem::path& root_dir, unsign EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE); diff --git a/runtime/test/d3d12_clear_formats_test.cpp b/runtime/test/d3d12_clear_formats_test.cpp index 33088abeec..f8b594a487 100644 --- a/runtime/test/d3d12_clear_formats_test.cpp +++ b/runtime/test/d3d12_clear_formats_test.cpp @@ -234,6 +234,7 @@ const std::vector kSint = {{-1, -2, -128, 127}, {-1.5f, -2.5f, 2.5f, 3.5f const ColorCase kColorCases[] = { {"UNORM", "R8_UNORM", DXGI_FORMAT_R8_UNORM, 1, &kUnorm}, + {"UNORM", "A8_UNORM", DXGI_FORMAT_A8_UNORM, 1, &kUnorm}, // the alpha component only {"UNORM", "R8G8_UNORM", DXGI_FORMAT_R8G8_UNORM, 2, &kUnorm}, {"UNORM", "R8G8B8A8_UNORM", DXGI_FORMAT_R8G8B8A8_UNORM, 4, &kUnorm}, {"UNORM", "B8G8R8A8_UNORM", DXGI_FORMAT_B8G8R8A8_UNORM, 4, &kUnorm}, @@ -336,6 +337,7 @@ int main() { info.device = vk.device; info.queue = vk.queue; info.queue_family = vk.family; + info.a8_render_target = vk.a8_render_target; if (FAILED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&ours.p)))) return 1; Ref factory; Ref warp; diff --git a/runtime/test/d3d12_compute_test.cpp b/runtime/test/d3d12_compute_test.cpp index 5ba3ded525..b4ed0fafe9 100644 --- a/runtime/test/d3d12_compute_test.cpp +++ b/runtime/test/d3d12_compute_test.cpp @@ -321,7 +321,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); // Root signature: [0] two constants (s4, s5), [1] a root UAV (s6:s7), [2] a one-CBV table (s8, its 32-bit VA): diff --git a/runtime/test/d3d12_debug_markers_test.cpp b/runtime/test/d3d12_debug_markers_test.cpp index a87fd030f7..b5d1a00344 100644 --- a/runtime/test/d3d12_debug_markers_test.cpp +++ b/runtime/test/d3d12_debug_markers_test.cpp @@ -100,7 +100,9 @@ HRESULT make_device(const vktest::Device& d, bool debug_utils, ID3D12Device** ou ID3D12Device* inner = nullptr; HRESULT hr = rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)); if (FAILED(hr)) return hr; - hr = rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), reinterpret_cast(out)); + // PC-shaped lists: this test calls the marker methods the console ABI does not have. + hr = rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), reinterpret_cast(out), + /*console_lists=*/false); if (FAILED(hr)) { inner->Release(); return hr; @@ -135,6 +137,9 @@ int run_markers(ID3D12Device* device) { const char ansi[] = "ansi pass and more"; const wchar_t spans[] = L"spans two lists"; const std::uint64_t blob[2] = {0x1234, 0x5678}; + // make_device passes console_lists=false, so first/second are the real PC-shaped lists — the console + // ABI has no SetMarker or BeginEvent, and its one marker slot (EndEvent at console 60) would land here + // on a shifted index. ExecuteCommandLists still unwraps the proxies below. first->SetMarker(0, frame, sizeof(frame)); first->SetMarker(0, nullptr, 0); first->BeginEvent(1, ansi, 9); // "ansi pass" diff --git a/runtime/test/d3d12_depth24_draw_test.cpp b/runtime/test/d3d12_depth24_draw_test.cpp index 436336e024..885cefa6ee 100644 --- a/runtime/test/d3d12_depth24_draw_test.cpp +++ b/runtime/test/d3d12_depth24_draw_test.cpp @@ -263,7 +263,8 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), + /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); D3D12_ROOT_PARAMETER param{}; diff --git a/runtime/test/d3d12_descriptor_test.cpp b/runtime/test/d3d12_descriptor_test.cpp index 9d4cf0fbae..2172c6311b 100644 --- a/runtime/test/d3d12_descriptor_test.cpp +++ b/runtime/test/d3d12_descriptor_test.cpp @@ -333,6 +333,7 @@ int main() { info.device = d.device; info.queue = d.queue; info.queue_family = d.family; + info.a8_render_target = d.a8_render_target; info.texture_compression_bc = d.bc; info.bindless = d.bindless; info.bindless_partially_bound = d.partially_bound; @@ -344,7 +345,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); // the proxy now owns `inner` D3D12_FEATURE_DATA_D3D12_OPTIONS8 options8{}; @@ -491,8 +492,10 @@ int main() { EXPECT((support.Support1 & D3D12_FORMAT_SUPPORT1_SHADER_SAMPLE) != 0); EXPECT((support.Support1 & D3D12_FORMAT_SUPPORT1_SHADER_GATHER) != 0); EXPECT((support.Support1 & D3D12_FORMAT_SUPPORT1_MIP) != 0); - EXPECT(!(support.Support1 & (D3D12_FORMAT_SUPPORT1_RENDER_TARGET | D3D12_FORMAT_SUPPORT1_BLENDABLE | - D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW)) && !support.Support2); + // Render targets where the device has VK_FORMAT_A8_UNORM_KHR (they are then blendable too); never UAVs. + const bool a8_render_target = (support.Support1 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET) != 0; + EXPECT(a8_render_target == ((support.Support1 & D3D12_FORMAT_SUPPORT1_BLENDABLE) != 0)); + EXPECT(!(support.Support1 & D3D12_FORMAT_SUPPORT1_TYPED_UNORDERED_ACCESS_VIEW) && !support.Support2); for (UINT count : {1u, 4u}) { D3D12_FEATURE_DATA_MULTISAMPLE_QUALITY_LEVELS quality_levels{DXGI_FORMAT_A8_UNORM, count}; EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_MULTISAMPLE_QUALITY_LEVELS, &quality_levels, @@ -504,10 +507,12 @@ int main() { auto desc = texture_desc; desc.Format = DXGI_FORMAT_A8_UNORM; desc.Flags = flag; - EXPECT(FAILED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, - D3D12_RESOURCE_STATE_COMMON, nullptr, - __uuidof(ID3D12Resource), nullptr))); - EXPECT(device->GetResourceAllocationInfo(0, 1, &desc).SizeInBytes == UINT64_MAX); + const bool allowed = flag == D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET && a8_render_target; + // With no output, a valid description is S_FALSE. + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, + __uuidof(ID3D12Resource), nullptr)) == allowed); + EXPECT((device->GetResourceAllocationInfo(0, 1, &desc).SizeInBytes == UINT64_MAX) == !allowed); } Ref byte_textures[2]; D3D12_PLACED_SUBRESOURCE_FOOTPRINT byte_placed[2]{}, a8_mip_placed{}; @@ -526,6 +531,17 @@ int main() { } EXPECT(byte_placed[0].Offset == byte_placed[1].Offset && byte_placed[0].Footprint.RowPitch == byte_placed[1].Footprint.RowPitch); + // An A8 render target (VK_FORMAT_A8_UNORM_KHR where the device has it) gets the same bytes, and its SRVs must + // read them as the R8-backed A8 texture's do. Without render-target support, slots 5 and 6 view that one. + Ref a8_target; + if (a8_render_target) { + auto desc = texture_desc; + desc.Format = DXGI_FORMAT_A8_UNORM; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&a8_target.p)))); + } for (UINT y = 0; y < size; ++y) { auto* row = static_cast(mapped) + byte_placed[0].Offset + y * byte_placed[0].Footprint.RowPitch; for (UINT x = 0; x < size; ++x) row[x] = std::uint8_t(1 + 3 * (y * size + x)); @@ -1194,7 +1210,7 @@ int main() { } } - constexpr UINT a8_mip_slot = 4, byte_view_count = a8_mip_slot + 1; + constexpr UINT a8_mip_slot = 4, a8_target_slot = 5, byte_view_count = a8_target_slot + 2; D3D12_DESCRIPTOR_HEAP_DESC byte_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, byte_view_count, D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; Ref byte_heap; @@ -1224,6 +1240,18 @@ int main() { byte_view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; byte_view.Texture2D.MostDetailedMip = 1; device->CreateShaderResourceView(byte_textures[0].p, &byte_view, byte_slot(a8_mip_slot)); + { + // The A8 render target: a default view (null description) and the remapped one of slot 1. + ID3D12Resource* const a8_source = a8_target.p ? a8_target.p : byte_textures[0].p; + device->CreateShaderResourceView(a8_source, nullptr, byte_slot(a8_target_slot)); + D3D12_SHADER_RESOURCE_VIEW_DESC remapped = byte_view; + remapped.Texture2D.MostDetailedMip = 0; + remapped.Shader4ComponentMapping = D3D12_ENCODE_SHADER_4_COMPONENT_MAPPING( + D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_3, + D3D12_SHADER_COMPONENT_MAPPING_FROM_MEMORY_COMPONENT_0, D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_1, + D3D12_SHADER_COMPONENT_MAPPING_FORCE_VALUE_0); + device->CreateShaderResourceView(a8_source, &remapped, byte_slot(a8_target_slot + 1)); + } // D3D-75: plane 1 of a depth-stencil texture is its stencil. The T# is 8_UINT at the texture's own address, // with the eight bits read as G and R, B, A as 0, 0, 1 (D3D12's X24_TYPELESS_G8_UINT / X32_..._G8X24_UINT). @@ -1487,6 +1515,18 @@ int main() { D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); list->ResourceBarrier(1, &ready); } + if (a8_target.p) { + D3D12_TEXTURE_COPY_LOCATION to{}, from{}; + to.pResource = a8_target.p; + to.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + from.pResource = upload.p; + from.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + from.PlacedFootprint = byte_placed[0]; + list->CopyTextureRegion(&to, 0, 0, 0, &from, nullptr); + const auto ready = transition(a8_target.p, D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE); + list->ResourceBarrier(1, &ready); + } EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); // Upload, then the texture into a shader-resource state. Executing the list also brings set 0 up to date. @@ -1976,12 +2016,17 @@ int main() { {value, 0, 0, 255}, {255, value, 255, 0}}; for (UINT k = 0; k < 4; ++k) EXPECT(std::memcmp(byte_results.data() + k * bytes + 4 * i, expected[k], 4) == 0); + // The A8 render target's default and remapped views read as the A8 texture's (slots 0 and 1). + EXPECT(std::memcmp(byte_results.data() + a8_target_slot * bytes + 4 * i, expected[0], 4) == 0); + EXPECT(std::memcmp(byte_results.data() + (a8_target_slot + 1) * bytes + 4 * i, expected[1], 4) == 0); const UINT mip_texel = (i / size / 2) * mip_size + (i % size) / 2; const std::uint8_t mip_expected[] = {0, 0, 0, std::uint8_t(208 + mip_texel)}; EXPECT(std::memcmp(byte_results.data() + a8_mip_slot * bytes + 4 * i, mip_expected, 4) == 0); } std::printf("A8 mip 1: %u samples matched across %u texels\n", texels, mip_size * mip_size); std::printf("A8 and R8 default and remapped views: %u texels matched each\n", texels); + std::printf("A8 render target (%s) default and remapped views: %u texels matched each\n", + a8_target.p ? "VK_FORMAT_A8_UNORM_KHR" : "not supported: the R8-backed texture", texels); // A gather across the center of each 2x2 block uses the A8 view's R-to-A swizzle. // The remapped view of the same image forces alpha to zero. @@ -2887,6 +2932,7 @@ int main() { typeless_heap.reset(); uint_texture.reset(); for (auto& resource : byte_textures) resource.reset(); + a8_target.reset(); byte_heap.reset(); ms_texture.reset(); ms_array.reset(); diff --git a/runtime/test/d3d12_draw_test.cpp b/runtime/test/d3d12_draw_test.cpp index 36e2f6e37a..b979ea42b9 100644 --- a/runtime/test/d3d12_draw_test.cpp +++ b/runtime/test/d3d12_draw_test.cpp @@ -10,6 +10,8 @@ // checks the viewport flip (D3D clip space is y-up) and the front-face winding; // - full-screen blends that read destination alpha into B8G8R8X8 and B8G8R8A8 targets cleared with alpha 0.25: // B8G8R8X8 has no alpha, so destination alpha reads 1 there, as on WARP and AMD's D3D12 driver; +// - an A8_UNORM render target where the device has VK_FORMAT_A8_UNORM_KHR: a draw and two alpha blends, also on +// one created with A8_UNORM as its castable list (an R8_UNORM list is refused); // - draws through RTVs in a format the texture's castable list names, in the other channel order (RGBA8 and BGRA8) // or across B8G8R8X8 and B8G8R8A8: the bytes land in the view's order and encoding. // The shaders are GLSL written to the translator's contract (test/glsl/vs_draw.vert, ps_draw.frag). No game data. @@ -119,6 +121,7 @@ int main() { info.device = d.device; info.queue = d.queue; info.queue_family = d.family; + info.a8_render_target = d.a8_render_target; info.buffer_device_address = true; info.subgroup = d.subgroup; info.shader_dir = library.string(); @@ -129,7 +132,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); // Root signature: [0] two constants (s0, s1: offset), [1] a root CBV (s2:s3: tint). @@ -856,6 +859,116 @@ int main() { unsigned(std::size(x8_cases))); } + // An A8_UNORM render target (VK_FORMAT_A8_UNORM_KHR, VulkanDeviceInfo::a8_render_target): the full-screen draw + // writes alpha 1, and the alpha blend reads the cleared alpha 0.25 (byte 64) as the destination. + { + D3D12_FEATURE_DATA_FORMAT_SUPPORT a8_support{DXGI_FORMAT_A8_UNORM}; + EXPECT(SUCCEEDED(device->CheckFeatureSupport(D3D12_FEATURE_FORMAT_SUPPORT, &a8_support, + sizeof(a8_support)))); + if (!(a8_support.Support1 & D3D12_FORMAT_SUPPORT1_RENDER_TARGET)) { + std::printf("A8_UNORM render target: not supported on this device (no VK_FORMAT_A8_UNORM_KHR)\n"); + } else { + struct A8Case { + const char* name; + BOOL blend; + D3D12_BLEND src_alpha, dst_alpha; + int want; + }; + constexpr A8Case a8_cases[] = { + {"no blend", FALSE, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, 255}, + {"alpha ZERO, ONE", TRUE, D3D12_BLEND_ZERO, D3D12_BLEND_ONE, 64}, + {"alpha INV_DEST_ALPHA, ZERO", TRUE, D3D12_BLEND_INV_DEST_ALPHA, D3D12_BLEND_ZERO, 191}, + }; + const D3D12_DESCRIPTOR_HEAP_DESC a8_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, + D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + Ref a8_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&a8_heap_desc, IID_PPV_ARGS(&a8_heap.p)))); + const D3D12_CPU_DESCRIPTOR_HANDLE a8_rtv{ + SIZE_T(reinterpret_cast(slot(a8_heap.p, 9))(a8_heap.p))}; + D3D12_RESOURCE_DESC a8_desc = rt_desc; + a8_desc.Width = a8_desc.Height = 4; + a8_desc.Format = DXGI_FORMAT_A8_UNORM; + Ref a8_target; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &a8_desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, + IID_PPV_ARGS(&a8_target.p)))); + // The same target through CreateCommittedResource3 with its own format as the castable list. An R8_UNORM + // list is refused: no other format can be a view format of a VK_FORMAT_A8_UNORM_KHR image. + Ref a8_inner10; + EXPECT(SUCCEEDED(inner->QueryInterface(IID_PPV_ARGS(&a8_inner10.p)))); + D3D12_RESOURCE_DESC1 a8_desc1{}; + a8_desc1.Dimension = a8_desc.Dimension; + a8_desc1.Width = a8_desc.Width; + a8_desc1.Height = a8_desc.Height; + a8_desc1.DepthOrArraySize = a8_desc.DepthOrArraySize; + a8_desc1.MipLevels = a8_desc.MipLevels; + a8_desc1.Format = a8_desc.Format; + a8_desc1.SampleDesc = a8_desc.SampleDesc; + a8_desc1.Layout = a8_desc.Layout; + a8_desc1.Flags = a8_desc.Flags; + const DXGI_FORMAT a8_own = DXGI_FORMAT_A8_UNORM, a8_r8 = DXGI_FORMAT_R8_UNORM; + Ref a8_cast_target, a8_r8_target; + EXPECT(SUCCEEDED(a8_inner10->CreateCommittedResource3(&default_heap, D3D12_HEAP_FLAG_NONE, &a8_desc1, + D3D12_BARRIER_LAYOUT_RENDER_TARGET, nullptr, nullptr, 1, &a8_own, IID_PPV_ARGS(&a8_cast_target.p)))); + EXPECT(a8_inner10->CreateCommittedResource3(&default_heap, D3D12_HEAP_FLAG_NONE, &a8_desc1, + D3D12_BARRIER_LAYOUT_RENDER_TARGET, nullptr, nullptr, 1, &a8_r8, IID_PPV_ARGS(&a8_r8_target.p)) == + E_INVALIDARG); + EXPECT(!a8_r8_target.p); + const FLOAT a8_clear[4] = {0.9f, 0.8f, 0.7f, 0.25f}; // only alpha lands + const D3D12_VIEWPORT a8_viewport{0, 0, 4, 4, 0, 1}; + const D3D12_RECT a8_scissor{0, 0, 4, 4}; + UINT64 a8_fence = 50; // after the B8G8R8X8 block's 41..50; 51..56, before the step-rate block's 61 + for (ID3D12Resource* const a8_resource : {a8_target.p, a8_cast_target.p}) + for (const A8Case& c : a8_cases) { + device->CreateRenderTargetView(a8_resource, nullptr, a8_rtv); + D3D12_GRAPHICS_PIPELINE_STATE_DESC a8_pso_desc = fullscreen_desc; + a8_pso_desc.RTVFormats[0] = DXGI_FORMAT_A8_UNORM; + a8_pso_desc.BlendState.RenderTarget[0] = { + c.blend, FALSE, D3D12_BLEND_ONE, D3D12_BLEND_ZERO, D3D12_BLEND_OP_ADD, c.src_alpha, + c.dst_alpha, D3D12_BLEND_OP_ADD, D3D12_LOGIC_OP_NOOP, D3D12_COLOR_WRITE_ENABLE_ALL}; + Ref a8_pso; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&a8_pso_desc, IID_PPV_ARGS(&a8_pso.p)))); + EXPECT(SUCCEEDED(allocator->Reset()) && SUCCEEDED(list->Reset(allocator.p, a8_pso.p))); + list->ClearRenderTargetView(a8_rtv, a8_clear, 0, nullptr); + list->SetGraphicsRootSignature(root.p); + list->IASetPrimitiveTopology(D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST); + list->RSSetViewports(1, &a8_viewport); + list->RSSetScissorRects(1, &a8_scissor); + list->OMSetRenderTargets(1, &a8_rtv, FALSE, nullptr); + list->SetGraphicsRootConstantBufferView(1, upload_va + 2048); + list->DrawInstanced(3, 1, 0, 0); + const auto a8_to_copy = transition(a8_resource, D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &a8_to_copy); + D3D12_TEXTURE_COPY_LOCATION a8_dst{readback.p, D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT, {}}; + a8_dst.PlacedFootprint = {0, {DXGI_FORMAT_A8_UNORM, 4, 4, 1, 256}}; + D3D12_TEXTURE_COPY_LOCATION a8_src{a8_resource, D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX, {}}; + list->CopyTextureRegion(&a8_dst, 0, 0, 0, &a8_src, nullptr); + const auto a8_to_target = transition(a8_resource, D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ResourceBarrier(1, &a8_to_target); + EXPECT(list->Close() == S_OK); + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + ++a8_fence; + EXPECT(SUCCEEDED(queue->Signal(fence.p, a8_fence)) && + SUCCEEDED(fence->SetEventOnCompletion(a8_fence, nullptr))); + const auto* got = static_cast(mapped); + for (UINT y = 0; y < 4; ++y) + for (UINT x = 0; x < 4; ++x) { + const int byte = got[y * 256 + x]; + if (std::abs(byte - c.want) <= 1) continue; + std::fprintf(stderr, "A8 target%s, %s: texel (%u,%u) got %d, want %d\n", + a8_resource == a8_cast_target.p ? " (castable list)" : "", c.name, x, y, + byte, c.want); + return 1; + } + } + std::printf("A8_UNORM render target: clear, draw and %u alpha blends matched, also with an A8_UNORM " + "castable list (R8_UNORM refused)\n", unsigned(std::size(a8_cases))); + } + } + // Instance step rate > 1 (VK_KHR/EXT_vertex_attribute_divisor): two per-instance colours in slot 1: // entry 0 = red, entry 1 = magenta (both preserved by the {1,0,1} tint). With step rate 2: // - Draw 1 (top-left, 2 instances from 0): instances 0 and 1 both read entry 0/2 = 0 (red). diff --git a/runtime/test/d3d12_existing_heap_test.cpp b/runtime/test/d3d12_existing_heap_test.cpp index fd827f9a1a..b781b88307 100644 --- a/runtime/test/d3d12_existing_heap_test.cpp +++ b/runtime/test/d3d12_existing_heap_test.cpp @@ -237,29 +237,89 @@ int check_title_placed(ID3D12Device* device, const char* kind, void* pages, UINT Ref placed_texture; EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, texture, 0x6u, IID_PPV_ARGS(&placed_texture.p)), S_OK); EXPECT(placed_texture.p != nullptr && placed_texture->GetDesc().Dimension == D3D12_RESOURCE_DIMENSION_TEXTURE2D); - EXPECT(placed_texture->GetGPUVirtualAddress() == reinterpret_cast(pages)); - // The layout is validated as a CreateCommittedResource state: RENDER_TARGET (2) on a texture without - // ALLOW_RENDER_TARGET is refused, and the COMMON retry still gives the title its texture. A description the - // checks refuse outright (more mips than the size has) is refused, not created. - Ref target_layout; - EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, texture, 0x2u, IID_PPV_ARGS(&target_layout.p)), S_OK); - EXPECT(target_layout.p != nullptr); - EXPECT(target_layout->GetGPUVirtualAddress() == reinterpret_cast(pages)); - D3D12_RESOURCE_DESC too_many_mips = texture; - too_many_mips.MipLevels = 12; - Ref refused_texture; - EXPECT(FAILED(rt::d3d12::create_buffer_at_host_address(device, pages, too_many_mips, 0x6u, - IID_PPV_ARGS(&refused_texture.p))) && - refused_texture.p == nullptr); - // An address off the buffer alignment can't be bound inside the import: the ordinary-buffer fallback answers. + // An address off the buffer alignment can't be bound inside the import: a shadow buffer answers, at the same VA + // (a driver whose buffer alignment is 1 imports it; the VA is the address either way). Ref fallback; + desc.Width = size - 1; EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, bytes + 1, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&fallback.p)), S_OK); - EXPECT(fallback->GetGPUVirtualAddress() != reinterpret_cast(bytes + 1)); + EXPECT(fallback->GetGPUVirtualAddress() == reinterpret_cast(bytes + 1)); std::printf("%s: %s, %llu bytes: GPU VA is the address, a GPU copy reads the CPU's writes\n", who, kind, static_cast(size)); return 0; } +std::uint8_t pattern_byte(UINT64 i, unsigned seed) { + return static_cast(i * 131u + (i >> 8) * 7u + seed); +} + +// The shadow fallback of slot 133: pages the driver does not import (write-combined, uncached, not all committed) +// still give a buffer whose GPU VA is the address. It is a copy of the pages, made again before every submission: +// a pattern written to the first `committed` bytes after the buffer exists is what a GPU copy in the next +// ExecuteCommandLists reads, and so is a second pattern in the submission after. Bytes past `committed` are not +// committed: they are never read, and the GPU sees zeros there. The same holds where the range was imported after +// all (a Wine that drops the cache modifier), so the caller need not know which path answered. +int check_title_placed_shadow(ID3D12Device* device, const char* kind, void* pages, UINT64 committed, UINT64 size) { + const char* who = "vulkan slot-133 shadow"; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = size; + desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + Ref buffer; + EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, pages, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&buffer.p)), S_OK); + EXPECT(buffer->GetGPUVirtualAddress() == reinterpret_cast(pages)); + D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref readback; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + D3D12_COMMAND_QUEUE_DESC queue_desc{D3D12_COMMAND_LIST_TYPE_DIRECT}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(list->Close())); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr); + EXPECT(done != nullptr); + auto* bytes = static_cast(pages); + UINT64 fence_value = 0; + for (const unsigned seed : {7u, 93u}) { + // Written after the buffer exists (and, the second time, after a submission read the first pattern). + for (UINT64 i = 0; i < committed; ++i) bytes[i] = pattern_byte(i, seed); + EXPECT(SUCCEEDED(allocator->Reset())); + EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); + list->CopyBufferRegion(readback.p, 0, buffer.p, 0, size); + EXPECT(SUCCEEDED(list->Close())); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(SUCCEEDED(queue->Signal(fence.p, ++fence_value))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(fence_value, done))); + EXPECT(WaitForSingleObject(done, 30000) == WAIT_OBJECT_0); + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + const auto* got = static_cast(mapped); + UINT64 wrong = size; + for (UINT64 i = 0; i < size && wrong == size; ++i) + if (got[i] != (i < committed ? pattern_byte(i, seed) : 0)) wrong = i; + readback->Unmap(0, nullptr); + if (wrong != size) + std::fprintf(stderr, "%s: %s: pattern %u: first wrong byte at %llu\n", who, kind, seed, + static_cast(wrong)); + EXPECT(wrong == size); + } + CloseHandle(done); + std::printf("%s: %s, %llu bytes (%llu committed): GPU VA is the address, each submission reads the pages' " + "latest bytes\n", + who, kind, static_cast(size), static_cast(committed)); + return 0; +} + int check_title_placed_all(ID3D12Device* device) { constexpr SIZE_T size = 4 * 0x10000; int failures = 0; @@ -277,47 +337,43 @@ int check_title_placed_all(ID3D12Device* device) { UnmapViewOfFile(view); CloseHandle(section); - // Cache-modified ranges are not imported (WC imports read wrong bytes on an RTX 5090 in review). Some Wine - // versions report a requested WC allocation as plain read-write memory; check the protection actually supplied. - // PAGE_NOCACHE also exercises the fallback on those hosts, rather than dropping the cache-protection check. + // Cache-modified ranges are not imported (WC imports read wrong bytes on an RTX 5090 in review): a shadow buffer + // answers at the same VA. Some Wine versions report a requested WC allocation as plain read-write memory; check + // the protection actually supplied. PAGE_NOCACHE also exercises the fallback on those hosts, rather than + // dropping the cache-protection check. const char* who = "vulkan slot-133 buffer"; - D3D12_RESOURCE_DESC desc{}; - desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - desc.Width = size; - desc.Height = desc.DepthOrArraySize = desc.MipLevels = 1; - desc.SampleDesc.Count = 1; - desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; for (DWORD modifier : {DWORD(PAGE_WRITECOMBINE), DWORD(PAGE_NOCACHE)}) { void* cached_pages = VirtualAlloc(nullptr, size, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE | modifier); EXPECT(cached_pages != nullptr); MEMORY_BASIC_INFORMATION region{}; EXPECT(VirtualQuery(cached_pages, ®ion, sizeof(region)) == sizeof(region)); const bool cache_modified = (region.Protect & (PAGE_WRITECOMBINE | PAGE_NOCACHE)) != 0; - { - Ref buffer; - EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, cached_pages, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&buffer.p)), S_OK); - if (cache_modified) { - EXPECT(buffer->GetGPUVirtualAddress() != reinterpret_cast(cached_pages)); - } else { - EXPECT(region.Protect == PAGE_READWRITE); - EXPECT(buffer->GetGPUVirtualAddress() == reinterpret_cast(cached_pages)); - } - } + if (!cache_modified) EXPECT(region.Protect == PAGE_READWRITE); + const int failed = check_title_placed_shadow(device, modifier == PAGE_WRITECOMBINE ? "write-combined range" + : "uncached range", + pages, size, size); std::printf("%s: cache modifier 0x%lx, reported protection 0x%lx: %s\n", who, modifier, region.Protect, - cache_modified ? "ordinary-buffer fallback verified" - : "modifier not reported; read-write import verified"); - VirtualFree(cached_pages, 0, MEM_RELEASE); + failed ? "FAILED" + : cache_modified ? "shadow buffer verified" + : "modifier not reported; read-write import verified"); + failures += failed; + VirtualFree(pages, 0, MEM_RELEASE); } - char* partial = static_cast(VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_READWRITE)); - EXPECT(partial != nullptr && VirtualAlloc(partial, size / 2, MEM_COMMIT, PAGE_READWRITE) == partial); { - // Pages not committed yet (xmem commits on first touch) are not imported either: the fallback answers. - Ref fallback; - EXPECT_HR(rt::d3d12::create_buffer_at_host_address(device, partial, desc, 0xFFFFFFFFu, IID_PPV_ARGS(&fallback.p)), S_OK); - EXPECT(fallback->GetGPUVirtualAddress() != reinterpret_cast(partial)); + // A larger write-combined range, so the per-submission copy the layer logs is measured on more than a few + // pages (retail places 182 MiB, 74 MiB of it write-combined). + constexpr SIZE_T large = 64u << 20; + void* pages = VirtualAlloc(nullptr, large, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE | PAGE_WRITECOMBINE); + EXPECT(pages != nullptr); + failures += check_title_placed_shadow(device, "64 MiB write-combined range", pages, large, large); + VirtualFree(pages, 0, MEM_RELEASE); } + char* partial = static_cast(VirtualAlloc(nullptr, size, MEM_RESERVE, PAGE_READWRITE)); + EXPECT(partial != nullptr && VirtualAlloc(partial, size / 2, MEM_COMMIT, PAGE_READWRITE) == partial); + // Pages not committed yet (xmem commits on first touch) are not imported either: the shadow copies the committed + // half and never reads the other, which a GPU copy sees as zeros. + failures += check_title_placed_shadow(device, "half-committed range", partial, size / 2, size); VirtualFree(partial, 0, MEM_RELEASE); - std::printf("%s: a partly committed range falls back to an ordinary buffer\n", who); return failures; } diff --git a/runtime/test/d3d12_f16_halves_test.cpp b/runtime/test/d3d12_f16_halves_test.cpp index c2f194e31b..bbd516e5c5 100644 --- a/runtime/test/d3d12_f16_halves_test.cpp +++ b/runtime/test/d3d12_f16_halves_test.cpp @@ -222,7 +222,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; diff --git a/runtime/test/d3d12_first_light_test.cpp b/runtime/test/d3d12_first_light_test.cpp index 8dcc2ca9c3..c5aea7fd59 100644 --- a/runtime/test/d3d12_first_light_test.cpp +++ b/runtime/test/d3d12_first_light_test.cpp @@ -134,7 +134,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); // No root parameters: the VS applies no matrix and the PS has no bindings (vk_harness pushes zeros too). diff --git a/runtime/test/d3d12_fspx_compute_test.cpp b/runtime/test/d3d12_fspx_compute_test.cpp index f07b9eea5a..fb8c3874dc 100644 --- a/runtime/test/d3d12_fspx_compute_test.cpp +++ b/runtime/test/d3d12_fspx_compute_test.cpp @@ -281,7 +281,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); if (rt::d3d12::device_push_constants_need_fallback(inner)) { std::printf("d3d12_fspx_compute_test: skipped, the PSOs need 144 push-constant bytes and this GPU has %u\n", diff --git a/runtime/test/d3d12_geometry_test.cpp b/runtime/test/d3d12_geometry_test.cpp index 6d8bb59571..1cfe035b76 100644 --- a/runtime/test/d3d12_geometry_test.cpp +++ b/runtime/test/d3d12_geometry_test.cpp @@ -91,7 +91,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); D3D12_ROOT_PARAMETER params[2] = {}; diff --git a/runtime/test/d3d12_m2_formats_test.cpp b/runtime/test/d3d12_m2_formats_test.cpp index 8730c511df..192242383d 100644 --- a/runtime/test/d3d12_m2_formats_test.cpp +++ b/runtime/test/d3d12_m2_formats_test.cpp @@ -219,7 +219,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE); diff --git a/runtime/test/d3d12_m2_textured_test.cpp b/runtime/test/d3d12_m2_textured_test.cpp index f5734e7544..cd9448c757 100644 --- a/runtime/test/d3d12_m2_textured_test.cpp +++ b/runtime/test/d3d12_m2_textured_test.cpp @@ -143,7 +143,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE); diff --git a/runtime/test/d3d12_m3_frame_test.cpp b/runtime/test/d3d12_m3_frame_test.cpp index bbf8b53178..86479017d6 100644 --- a/runtime/test/d3d12_m3_frame_test.cpp +++ b/runtime/test/d3d12_m3_frame_test.cpp @@ -176,7 +176,7 @@ int main(int argc, char** argv) { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE); diff --git a/runtime/test/d3d12_m4_compute_test.cpp b/runtime/test/d3d12_m4_compute_test.cpp index c50a63b042..bad8ed98ef 100644 --- a/runtime/test/d3d12_m4_compute_test.cpp +++ b/runtime/test/d3d12_m4_compute_test.cpp @@ -134,7 +134,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); EXPECT(rt::d3d12::bindless_set(device.p) != VK_NULL_HANDLE); diff --git a/runtime/test/d3d12_mesh_test.cpp b/runtime/test/d3d12_mesh_test.cpp index df430c11a6..590d3507b9 100644 --- a/runtime/test/d3d12_mesh_test.cpp +++ b/runtime/test/d3d12_mesh_test.cpp @@ -12,6 +12,8 @@ // bottom-left quadrant (yellow). Each pixel is read back and compared. // - A vertex draw with the mesh PSO, and DispatchMesh with the VS one, fail at execution (ReplayResult:: // invalid_draw); a mesh grid beyond D3D12's limits fails at Close; an empty grid records nothing. +// - A DISPATCH_MESH command signature is created only with the extension; ExecuteIndirect with it records nothing +// yet, so its list closes. // The shaders are GLSL written to the translator's contract (test/glsl/ms_draw.mesh, ps_draw.frag, vs_fullscreen.vert). // No game data. Set LEONIDA_VK_VALIDATION=1 to run under VK_LAYER_KHRONOS_validation. #include "vk_test_device.h" @@ -180,6 +182,11 @@ int main() { stream.add(TargetsSubobject{.inner = one_target()}); Ref pso; EXPECT(create(device.p, stream, pso) == E_NOTIMPL && !pso.p); + // A DISPATCH_MESH command signature is refused the same way. + const D3D12_INDIRECT_ARGUMENT_DESC mesh_arg{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH}; + const D3D12_COMMAND_SIGNATURE_DESC mesh_sig{12, 1, &mesh_arg, 0}; + Ref sig; + EXPECT(device->CreateCommandSignature(&mesh_sig, nullptr, IID_PPV_ARGS(&sig.p)) == E_NOTIMPL && !sig.p); root.reset(); EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); } @@ -398,6 +405,21 @@ int main() { list->RSSetViewports(1, &viewport); list6->DispatchMesh(4096, 1025, 1); EXPECT(list->Close() == E_INVALIDARG); + // A DISPATCH_MESH command signature (D3D12_DISPATCH_MESH_ARGUMENTS, 12 bytes) is created; a stride below its + // 12 bytes is refused as the PC runtime refuses it. ExecuteIndirect with it records nothing yet (#3777 replays + // it), so the list still closes. + { + const D3D12_INDIRECT_ARGUMENT_DESC mesh_arg{D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH}; + const D3D12_COMMAND_SIGNATURE_DESC mesh_sig{12, 1, &mesh_arg, 0}; + const D3D12_COMMAND_SIGNATURE_DESC short_sig{8, 1, &mesh_arg, 0}; + Ref sig, short_one; + EXPECT(SUCCEEDED(device->CreateCommandSignature(&mesh_sig, nullptr, IID_PPV_ARGS(&sig.p))) && sig.p); + EXPECT(device->CreateCommandSignature(&short_sig, nullptr, IID_PPV_ARGS(&short_one.p)) == E_INVALIDARG); + EXPECT(SUCCEEDED(list->Reset(allocator.p, mesh_pso.p))); + list->SetGraphicsRootSignature(root.p); + list->ExecuteIndirect(sig.p, 1, upload.p, 0, nullptr, 0); + EXPECT(list->Close() == S_OK); + } EXPECT(SUCCEEDED(queue->Signal(fence.p, 2)) && SUCCEEDED(fence->SetEventOnCompletion(2, nullptr))); // D3D-291: pipeline statistics around mesh draws. Query 0 holds a vertex draw, two mesh draws and another diff --git a/runtime/test/d3d12_msaa_draw_test.cpp b/runtime/test/d3d12_msaa_draw_test.cpp index 5017a01a3d..3437fe0301 100644 --- a/runtime/test/d3d12_msaa_draw_test.cpp +++ b/runtime/test/d3d12_msaa_draw_test.cpp @@ -88,7 +88,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); if (rt::d3d12::device_push_constants_need_fallback(inner)) { std::printf("d3d12_msaa_draw_test: skipped, the PSOs need 144 push-constant bytes and this GPU has %u\n", diff --git a/runtime/test/d3d12_present_test.cpp b/runtime/test/d3d12_present_test.cpp index 5c626ea80b..b94e958522 100644 --- a/runtime/test/d3d12_present_test.cpp +++ b/runtime/test/d3d12_present_test.cpp @@ -376,7 +376,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); auto presenter = rt::d3d12::create_window_presenter(inner, window); EXPECT(presenter); diff --git a/runtime/test/d3d12_rect_list_test.cpp b/runtime/test/d3d12_rect_list_test.cpp new file mode 100644 index 0000000000..05b90a81c8 --- /dev/null +++ b/runtime/test/d3d12_rect_list_test.cpp @@ -0,0 +1,341 @@ +// The console's rectangle and quad lists drawn through the D3D12-on-Vulkan layer (src/rect_list_geometry.h). +// +// Built like d3d12_translated_draw_test.cpp, from the same translated vs_m15 / ps_m15 (the VS fetches its vertices +// through a V#; the PS multiplies the colour by (0.5, 2, 1, 1) and adds the bias, 0 here), so the shaders are real +// translator output found by the SHA-256 of their FSSM programs. +// frame 1, rectangle list: PSO topology type 19, IASetPrimitiveTopology(17), DrawInstanced(3). The three corners +// v1 (-1, 1), v2 (1, 1), v3 (-1, -1) cover the top-left, top-right and bottom-left of the 64x64 target; the fourth +// corner, v2 + v3 - v1 = (1, -1) with colour c2 + c3 - c1, is made by the layer. Every pixel must carry the plane +// through the three corner colours; the bottom-right quadrant is only right when the fourth corner is. +// frame 2, quad list: PSO topology type TRIANGLE, IASetPrimitiveTopology(19), DrawInstanced(8): two quads (corners +// in order around the quad), the top-left and bottom-right quadrants, each one colour. These pixels are exact. +// Pixels are read back and compared; the other two quadrants of frame 2 stay the clear colour. LEONIDA_VK_VALIDATION=1 +// runs it under the validation layer. +#include "vk_test_device.h" +#include "d3d12_test_shaders.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/gfx10_descriptors.h" +#include "../src/shader_library.h" + +#include +#include +#include +#include +#include +#include + +#ifndef LEONIDA_TEST_M15_DIR +#error "LEONIDA_TEST_M15_DIR must name the folder build.py wrote (spirv/index.json, fssm/*.fssm)" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +using namespace d3d12test; +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX + +namespace { + +std::vector read_file(const std::filesystem::path& path) { + std::ifstream in(path, std::ios::binary); + return {std::istreambuf_iterator(in), std::istreambuf_iterator()}; +} + +struct Vertex { // 32 bytes, as vs_m15.asm reads it + float position[4]; + float color[4]; +}; + +using Pixel = std::array; +constexpr UINT target_extent = 64; +constexpr UINT pitch = target_extent * sizeof(Pixel); +constexpr D3D_PRIMITIVE_TOPOLOGY rect_list = D3D_PRIMITIVE_TOPOLOGY(17), quad_list = D3D_PRIMITIVE_TOPOLOGY(19); +const std::uint32_t rect_type_value = 19; // not an enumerator of D3D12_PRIMITIVE_TOPOLOGY_TYPE + +std::array make_vsharp(std::uint64_t base, std::uint32_t records) { + leonida::gfx10::Buffer buffer; + buffer.address = base; + buffer.stride = 32; + buffer.num_records = records; + buffer.format = 77; // GFX10_FORMAT_32_32_32_32_FLOAT + buffer.oob_select = leonida::gfx10::OobSelect::structured; + return leonida::gfx10::encode(buffer); +} + +Vertex vertex(float x, float y, const float* c) { return Vertex{{x, y, 0.0f, 1.0f}, {c[0], c[1], c[2], c[3]}}; } + +} // namespace + +int main() { + vktest::Device d; + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) return 77; // no Vulkan GPU: ctest skips + EXPECT(device_status == vktest::DeviceStatus::ready); + if (!d.enabled.geometryShader) { + std::printf("SKIP: no geometryShader on this GPU\n"); + return 77; + } + const std::filesystem::path root_dir = LEONIDA_TEST_M15_DIR; + const auto vs_program = read_file(root_dir / "fssm" / "vs_m15.fssm"); + const auto ps_program = read_file(root_dir / "fssm" / "ps_m15.fssm"); + EXPECT(vs_program.size() >= 4 && ps_program.size() == 0x110); + const auto vs_container = shader_container(vs_program), ps_container = shader_container(ps_program); + + // Frame 1: the rectangle's three corners. Vertices 0..2. Frame 2: two quads, vertices 3..10. + const float ca[4] = {0.0f, 0.0f, 0.0f, 1.0f}, cb[4] = {1.0f, 0.0f, 0.5f, 1.0f}, cc[4] = {0.0f, 0.5f, 1.0f, 1.0f}; + const float q1[4] = {0.25f, 0.5f, 0.75f, 1.0f}, q2[4] = {1.0f, 0.0f, 0.5f, 1.0f}; + const Vertex vertices[11] = {vertex(-1, 1, ca), vertex(1, 1, cb), vertex(-1, -1, cc), + vertex(-1, 1, q1), vertex(0, 1, q1), vertex(0, 0, q1), vertex(-1, 0, q1), + vertex(0, 0, q2), vertex(1, 0, q2), vertex(1, -1, q2), vertex(0, -1, q2)}; + static_assert(sizeof(Vertex) == 32 && sizeof(vertices) == 352); + + std::vector rect_pixels(target_extent * target_extent), quad_pixels(target_extent * target_extent); + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + info.features = d.enabled; // geometryShader: the rectangle stage needs it + info.shader_dir = (root_dir / "spirv").string(); + ID3D12Device* inner = nullptr; + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p)))); + rt::d3d12::set_device_outer(inner, device.p); + + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_SRV, 1, 0, 0, 0}; + D3D12_ROOT_PARAMETER params[2] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[0].DescriptorTable = {1, &range}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[1].Constants = {0, 0, 4}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {2, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto root_blob = serialize_root_signature(root_desc); + EXPECT(!root_blob.empty()); + Ref root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); + + D3D12_GRAPHICS_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.p; + pso_desc.VS = {vs_container.data(), vs_container.size()}; + pso_desc.PS = {ps_container.data(), ps_container.size()}; + pso_desc.BlendState.RenderTarget[0].RenderTargetWriteMask = D3D12_COLOR_WRITE_ENABLE_ALL; + pso_desc.SampleMask = 0xffffffff; + pso_desc.RasterizerState.FillMode = D3D12_FILL_MODE_SOLID; + pso_desc.RasterizerState.CullMode = D3D12_CULL_MODE_NONE; + pso_desc.RasterizerState.DepthClipEnable = TRUE; + pso_desc.NumRenderTargets = 1; + pso_desc.RTVFormats[0] = DXGI_FORMAT_R32G32B32A32_FLOAT; + pso_desc.SampleDesc.Count = 1; + Ref rect_pso, quad_pso; + std::memcpy(&pso_desc.PrimitiveTopologyType, &rect_type_value, sizeof(rect_type_value)); // 19: rectangles + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&rect_pso.p)))); + pso_desc.PrimitiveTopologyType = D3D12_PRIMITIVE_TOPOLOGY_TYPE_TRIANGLE; + EXPECT(SUCCEEDED(device->CreateGraphicsPipelineState(&pso_desc, IID_PPV_ARGS(&quad_pso.p)))); + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}; + const D3D12_HEAP_PROPERTIES upload_heap{D3D12_HEAP_TYPE_UPLOAD}; + const D3D12_HEAP_PROPERTIES readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref vertex_buffer, upload, readback, target; + const auto vb_desc = buffer_desc(sizeof(vertices)); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &vb_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&vertex_buffer.p)))); + const auto upload_desc = buffer_desc(1024); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&upload_heap, D3D12_HEAP_FLAG_NONE, &upload_desc, + D3D12_RESOURCE_STATE_GENERIC_READ, nullptr, + IID_PPV_ARGS(&upload.p)))); + const auto readback_desc = buffer_desc(pitch * target_extent); + EXPECT(SUCCEEDED(device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + D3D12_RESOURCE_DESC rt_desc{}; + rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rt_desc.Width = rt_desc.Height = target_extent; + rt_desc.DepthOrArraySize = 1; + rt_desc.MipLevels = 1; + rt_desc.Format = DXGI_FORMAT_R32G32B32A32_FLOAT; + rt_desc.SampleDesc.Count = 1; + rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + EXPECT(SUCCEEDED(device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &rt_desc, + D3D12_RESOURCE_STATE_COMMON, nullptr, IID_PPV_ARGS(&target.p)))); + std::uint8_t* up = nullptr; + EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&up)))); + std::memcpy(up, vertices, sizeof(vertices)); + + // Two V#s over the one vertex buffer: slot 0 the rectangle's three corners, slot 1 the eight quad corners. + const D3D12_DESCRIPTOR_HEAP_DESC srv_heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 2, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref srv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&srv_heap_desc, IID_PPV_ARGS(&srv_heap.p)))); + const std::uint64_t cpu = reinterpret_cast(slot(srv_heap.p, 9))(srv_heap.p); + const std::uint64_t gpu = reinterpret_cast(slot(srv_heap.p, 10))(srv_heap.p); + const UINT step = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + EXPECT(cpu && gpu >= 0x10000 && gpu < (1ull << 32) && step >= 16); + const std::uint64_t buffer_va = vertex_buffer->GetGPUVirtualAddress(); + EXPECT(buffer_va >= 0x10000); + const std::array vsharps[2] = {make_vsharp(buffer_va, 3), + make_vsharp(buffer_va + 3 * sizeof(Vertex), 8)}; + for (unsigned i = 0; i < 2; ++i) + std::memcpy(reinterpret_cast(cpu + std::uint64_t(i) * step), vsharps[i].data(), 16); + + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 1, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + Ref rtv_heap; + EXPECT(SUCCEEDED(device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&rtv_heap.p)))); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv{ + SIZE_T(reinterpret_cast(slot(rtv_heap.p, 9))(rtv_heap.p))}; + device->CreateRenderTargetView(target.p, nullptr, rtv); + + D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, rect_pso.p, + IID_PPV_ARGS(&list.p)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + list->CopyBufferRegion(vertex_buffer.p, 0, upload.p, 0, sizeof(vertices)); + D3D12_RESOURCE_BARRIER barriers[2] = { + transition(vertex_buffer.p, D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_STATE_NON_PIXEL_SHADER_RESOURCE), + transition(target.p, D3D12_RESOURCE_STATE_COMMON, D3D12_RESOURCE_STATE_RENDER_TARGET)}; + list->ResourceBarrier(2, barriers); + + const auto render_frame = [&](UINT64 frame, ID3D12PipelineState* pso, D3D_PRIMITIVE_TOPOLOGY topology, + unsigned vsharp_slot, UINT vertex_count, std::vector& out) -> int { + if (frame > 1) { + EXPECT(SUCCEEDED(allocator->Reset())); + EXPECT(SUCCEEDED(list->Reset(allocator.p, pso))); + auto to_target = transition(target.p, D3D12_RESOURCE_STATE_COPY_SOURCE, + D3D12_RESOURCE_STATE_RENDER_TARGET); + list->ResourceBarrier(1, &to_target); + } else { + list->SetPipelineState(pso); + } + const FLOAT clear[4] = {0.5f, 0.125f, 0.25f, 0.5f}; + list->ClearRenderTargetView(rtv, clear, 0, nullptr); + list->SetGraphicsRootSignature(root.p); + ID3D12DescriptorHeap* heaps[] = {srv_heap.p}; + list->SetDescriptorHeaps(1, heaps); + list->IASetPrimitiveTopology(topology); + const D3D12_VIEWPORT viewport{0, 0, float(target_extent), float(target_extent), 0, 1}; + const D3D12_RECT scissor{0, 0, LONG(target_extent), LONG(target_extent)}; + list->RSSetViewports(1, &viewport); + list->RSSetScissorRects(1, &scissor); + list->OMSetRenderTargets(1, &rtv, FALSE, nullptr); + const float constants[4] = {0, 0, 0, 0}; // no offset, no bias + list->SetGraphicsRootDescriptorTable(0, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + std::uint64_t(vsharp_slot) * step}); + list->SetGraphicsRoot32BitConstants(1, 4, constants, 0); + list->DrawInstanced(vertex_count, 1, 0, 0); + D3D12_RESOURCE_BARRIER to_copy = transition(target.p, D3D12_RESOURCE_STATE_RENDER_TARGET, + D3D12_RESOURCE_STATE_COPY_SOURCE); + list->ResourceBarrier(1, &to_copy); + D3D12_TEXTURE_COPY_LOCATION dst{}; + dst.pResource = readback.p; + dst.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst.PlacedFootprint = {0, {DXGI_FORMAT_R32G32B32A32_FLOAT, target_extent, target_extent, 1, pitch}}; + D3D12_TEXTURE_COPY_LOCATION src{}; + src.pResource = target.p; + src.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + list->CopyTextureRegion(&dst, 0, 0, 0, &src, nullptr); + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(queue->Signal(fence.p, frame))); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(frame, nullptr))); + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + std::memcpy(out.data(), mapped, out.size() * sizeof(Pixel)); + readback->Unmap(0, nullptr); + return 0; + }; + EXPECT(render_frame(1, rect_pso.p, rect_list, 0, 3, rect_pixels) == 0); + EXPECT(render_frame(2, quad_pso.p, quad_list, 1, 8, quad_pixels) == 0); + for (auto* r : {&vertex_buffer, &upload, &readback, &target}) r->reset(); + rect_pso.reset(); + quad_pso.reset(); + root.reset(); + srv_heap.reset(); + rtv_heap.reset(); + list.reset(); + allocator.reset(); + queue.reset(); + fence.reset(); + EXPECT(rt::d3d12_xs::device_proxy_ref_count(device.p) == 1); + } + + // Rectangle: the plane through the three corner colours, at each pixel centre, through the PS's scale. + const float scale[4] = {0.5f, 2.0f, 1.0f, 1.0f}; + unsigned covered = 0, off = 0; + float worst = 0.0f; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const float u = (float(col) + 0.5f) / target_extent, v = (float(row) + 0.5f) / target_extent; + const Pixel& got = rect_pixels[row * target_extent + col]; + bool pixel_ok = true; + for (int c = 0; c < 4; ++c) { + const float want = (ca[c] + u * (cb[c] - ca[c]) + v * (cc[c] - ca[c])) * scale[c]; + const float error = std::fabs(got[c] - want); + worst = std::fmax(worst, error); + if (!(error <= 2e-5f)) pixel_ok = false; + } + covered += pixel_ok; + if (!pixel_ok && off++ < 8) + std::fprintf(stderr, "rect pixel (%u, %u): got %g,%g,%g,%g\n", col, row, got[0], got[1], got[2], got[3]); + } + } + // The four quadrant centres on their own, so a wrong fourth corner is named by quadrant. + const char* names[4] = {"top left", "top right", "bottom left", "bottom right"}; + for (int quadrant = 0; quadrant < 4; ++quadrant) { + const UINT col = (quadrant & 1 ? 48 : 16), row = (quadrant & 2 ? 48 : 16); + const Pixel& got = rect_pixels[row * target_extent + col]; + const float u = (float(col) + 0.5f) / target_extent, v = (float(row) + 0.5f) / target_extent; + for (int c = 0; c < 4; ++c) { + const float want = (ca[c] + u * (cb[c] - ca[c]) + v * (cc[c] - ca[c])) * scale[c]; + if (!(std::fabs(got[c] - want) <= 2e-5f)) { + std::fprintf(stderr, "rect %s quadrant: channel %d got %g want %g\n", names[quadrant], c, got[c], want); + return 1; + } + } + } + EXPECT(covered == target_extent * target_extent); + + // Quad list: whole-bit comparison; two quadrants one colour each, the rest the clear colour. + const Pixel clear_color = {0.5f, 0.125f, 0.25f, 0.5f}; + const Pixel top_left = {q1[0] * scale[0], q1[1] * scale[1], q1[2], q1[3]}; + const Pixel bottom_right = {q2[0] * scale[0], q2[1] * scale[1], q2[2], q2[3]}; + unsigned quad_wrong = 0; + for (UINT row = 0; row < target_extent; ++row) { + for (UINT col = 0; col < target_extent; ++col) { + const bool top = row < target_extent / 2, left = col < target_extent / 2; + const Pixel& want = top && left ? top_left : (!top && !left ? bottom_right : clear_color); + const Pixel& got = quad_pixels[row * target_extent + col]; + if (std::memcmp(&got, &want, sizeof(Pixel)) == 0) continue; + if (quad_wrong++ < 8) + std::fprintf(stderr, "quad pixel (%u, %u): got %g,%g,%g,%g want %g,%g,%g,%g\n", col, row, got[0], got[1], + got[2], got[3], want[0], want[1], want[2], want[3]); + } + } + EXPECT(!quad_wrong); + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("rect list: %u of %u pixels on the colour plane (worst error %g), all four quadrants; quad list: " + "%u of %u pixels exact\n", + covered, target_extent * target_extent, double(worst), target_extent * target_extent - quad_wrong, + target_extent * target_extent); + return 0; +} diff --git a/runtime/test/d3d12_set0_compute_test.cpp b/runtime/test/d3d12_set0_compute_test.cpp index c2dfdfc397..a37f486d72 100644 --- a/runtime/test/d3d12_set0_compute_test.cpp +++ b/runtime/test/d3d12_set0_compute_test.cpp @@ -98,7 +98,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); if (rt::d3d12::device_push_constants_need_fallback(inner)) { std::printf("d3d12_set0_compute_test: skipped, the PSOs need 144 push-constant bytes and this GPU has %u\n", diff --git a/runtime/test/d3d12_subgroup_test.cpp b/runtime/test/d3d12_subgroup_test.cpp index ccc0d2aff9..67e5ef5e88 100644 --- a/runtime/test/d3d12_subgroup_test.cpp +++ b/runtime/test/d3d12_subgroup_test.cpp @@ -185,7 +185,7 @@ Result run(vktest::Device& d, const std::filesystem::path& library, const leonid CASE_EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; CASE_EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); // Root signature: [0] four constants (s4..s7 in the console compute layout, D3D-448), the V# the shaders store @@ -379,7 +379,7 @@ DrawResult draw(vktest::Device& d, const std::filesystem::path& library, const l CASE_EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; CASE_EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; diff --git a/runtime/test/d3d12_title_va_test.cpp b/runtime/test/d3d12_title_va_test.cpp new file mode 100644 index 0000000000..7be1e880b4 --- /dev/null +++ b/runtime/test/d3d12_title_va_test.cpp @@ -0,0 +1,554 @@ +// A buffer the title places at its own VA (Xbox device slot 133, rt::d3d12::create_buffer_at_host_address) is read +// by a shader written to the translator's address contract (heap_base + console VA, docs/d3d12_vulkan.md section +// 3.3), through the two kinds of address the layer writes for it: +// - a root view (SetComputeRootUnorderedAccessView with the title's VA): read 256 bytes past its base and written +// at its base, then copied to a READBACK buffer; +// - a buffer V# (CreateShaderResourceView of the title's buffer), the way translated vertex shaders fetch their +// vertices: read and written to an arena buffer. +// The title's VA is a VirtualAlloc address, far past the 4 GiB arena. Both page kinds are covered: read-write pages +// (imported with VK_EXT_external_memory_host where the driver takes them) and write-combined pages (refused by the +// import, so a shadow copy in the arena, the retail case on an RTX 5070 Ti). The data is written after the buffer +// exists, so the shadow's copy before the submission is what the GPU reads. +// Then the title's own memory outside any slot-133 buffer (a constant ring, #8862 section 3.5): a V# the CPU writes +// into a bound table itself, a created CBV and a root view. +// Negative controls: a second title buffer with other data must not be what the first one's V# reads; an arena +// buffer's V# keeps its VA; the title's range is forgotten when the buffer is released; a raw arena V# and a +// T#-shaped slot in a scanned table keep their bytes; a reserved, uncommitted address is left alone. The shader is test/glsl/cs_user_data.comp. No game data. LEONIDA_VK_VALIDATION=1 for the +// Khronos validation layer. +#include "shader_fixture_path.h" +#include "test_temp_dir.h" +#include "vk_test_device.h" +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../src/gfx10_descriptors.h" +#include "../src/shader_library.h" +#include "../src/title_va_alias.h" + +#include +#include +#include +#include +#include + +#ifndef LEONIDA_TEST_CS_SPV +#error "LEONIDA_TEST_CS_SPV must name the compiled test shader" +#endif + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +using XboxHeapHandleFn = std::uint64_t(WINAPI*)(void* heap); // heap slots 9/10: handle in RAX +using XboxComputePipelineFn = HRESULT(WINAPI*)(void* device, const D3D12_COMPUTE_PIPELINE_STATE_DESC*, std::uint64_t, + std::uint64_t, const IID*, void**); +using SerializeFn = HRESULT(WINAPI*)(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC*, ID3DBlob**, ID3DBlob**); + +template +struct Ref { + T* p = nullptr; + ~Ref() { reset(); } + void reset() { + if (p) p->Release(); + p = nullptr; + } + T* operator->() const { return p; } +}; + +void* slot(void* object, unsigned index) { return (*reinterpret_cast(object))[index]; } + +void put32(std::vector& out, std::uint32_t v) { + for (int i = 0; i < 4; ++i) out.push_back(std::uint8_t(v >> (8 * i))); +} + +std::vector zlib_stored(const std::vector& data) { + std::vector out = {0x78, 0x01, 0x01}; + const auto length = std::uint16_t(data.size()); + out.insert(out.end(), {std::uint8_t(length), std::uint8_t(length >> 8), std::uint8_t(~length), + std::uint8_t(~length >> 8)}); + out.insert(out.end(), data.begin(), data.end()); + std::uint32_t a = 1, b = 0; + for (const std::uint8_t x : data) { + a = (a + x) % 65521; + b = (b + a) % 65521; + } + const std::uint32_t adler = (b << 16) | a; + out.insert(out.end(), {std::uint8_t(adler >> 24), std::uint8_t(adler >> 16), std::uint8_t(adler >> 8), + std::uint8_t(adler)}); + return out; +} + +// The game's shader container shape (DXBC > DXIL > XDAT 0x0D > XBCH > zlib > FSSM), as d3d12_compute_test builds it. +std::vector shader_container(const std::vector& fssm) { + const auto stream = zlib_stored(fssm); + std::vector xbch = {'X', 'B', 'C', 'H'}; + for (const std::uint32_t v : {1u, std::uint32_t(stream.size()), 0u, std::uint32_t(fssm.size()), 0u}) put32(xbch, v); + xbch.insert(xbch.end(), stream.begin(), stream.end()); + std::vector dxil(16, 0); + dxil.insert(dxil.end(), {'X', 'D', 'A', 'T'}); + put32(dxil, 1); + put32(dxil, 12); + put32(dxil, 0x0d); + put32(dxil, 16 + 12 + 12); + put32(dxil, std::uint32_t(xbch.size())); + dxil.insert(dxil.end(), xbch.begin(), xbch.end()); + std::vector out = {'D', 'X', 'B', 'C'}; + out.resize(28, 0); + put32(out, 1); + put32(out, 36); + out.insert(out.end(), {'D', 'X', 'I', 'L'}); + put32(out, std::uint32_t(dxil.size())); + out.insert(out.end(), dxil.begin(), dxil.end()); + return out; +} + +std::vector serialize(const D3D12_VERSIONED_ROOT_SIGNATURE_DESC& desc) { + const HMODULE d3d12 = LoadLibraryExA("d3d12.dll", nullptr, LOAD_LIBRARY_SEARCH_SYSTEM32); + const auto fn = d3d12 ? reinterpret_cast( + reinterpret_cast(GetProcAddress(d3d12, "D3D12SerializeVersionedRootSignature"))) + : nullptr; + std::vector out; + ID3DBlob* blob = nullptr; + if (fn && SUCCEEDED(fn(&desc, &blob, nullptr)) && blob) { + const auto* p = static_cast(blob->GetBufferPointer()); + out.assign(p, p + blob->GetBufferSize()); + blob->Release(); + } + return out; +} + +D3D12_RESOURCE_DESC buffer_desc(UINT64 bytes, D3D12_RESOURCE_FLAGS flags = D3D12_RESOURCE_FLAG_NONE) { + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = bytes; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = flags; + return desc; +} + +// The 48-bit base address of the 16-byte GFX10 buffer V# at `cpu` (dword 0, and dword 1 bits 0-15). +std::uint64_t vsharp_base(std::uint64_t cpu) { + std::uint32_t w[2]; + std::memcpy(w, reinterpret_cast(cpu), sizeof(w)); + return std::uint64_t(w[0]) | (std::uint64_t(w[1] & 0xFFFFu) << 32); +} + +D3D12_SHADER_RESOURCE_VIEW_DESC raw_srv(UINT first_word, UINT words) { + D3D12_SHADER_RESOURCE_VIEW_DESC desc{}; + desc.Format = DXGI_FORMAT_R32_TYPELESS; + desc.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + desc.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + desc.Buffer.FirstElement = first_word; + desc.Buffer.NumElements = words; + desc.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + return desc; +} + +constexpr UINT kElements = 64, kBytes = kElements * 4; +constexpr UINT64 kPages = 64 * 1024; +constexpr UINT kSrvWord = 256; // the V# reads title words 256..319 +constexpr UINT kRootAdd = 7; // root view mode: title word i = title word 64 + i + 7 + +struct Context { + ID3D12Device* inner = nullptr; // the Vulkan device (slot 133's backend takes it) + ID3D12Device* device = nullptr; // the Xbox-ABI proxy over it + ID3D12RootSignature* root = nullptr; + ID3D12PipelineState* pso = nullptr; + ID3D12CommandQueue* queue = nullptr; + ID3D12Fence* fence = nullptr; + UINT64 fence_value = 0; + std::uint64_t arena = 0; +}; + +// One kind of title pages: `protect` is PAGE_READWRITE, or with PAGE_WRITECOMBINE. +int check_kind(Context& c, const char* kind, DWORD protect, int& checks) { + void* pages = VirtualAlloc(nullptr, kPages, MEM_RESERVE | MEM_COMMIT, protect); + void* other_pages = VirtualAlloc(nullptr, kPages, MEM_RESERVE | MEM_COMMIT, protect); + EXPECT(pages && other_pages); + const auto title_va = reinterpret_cast(pages); + EXPECT(title_va >= c.arena); // outside the arena: heap_base + title_va names nothing of the layer's + const D3D12_RESOURCE_DESC desc = buffer_desc(kPages); + Ref title, other; + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(c.inner, pages, desc, 0xFFFFFFFFu, + IID_PPV_ARGS(&title.p)))); + EXPECT(SUCCEEDED(rt::d3d12::create_buffer_at_host_address(c.inner, other_pages, desc, 0xFFFFFFFFu, + IID_PPV_ARGS(&other.p)))); + EXPECT(title->GetGPUVirtualAddress() == title_va); // the title keeps its own VA + const std::uint64_t shader_va = leonida::title_va_aliases().shader_va(title_va); + EXPECT(shader_va != title_va); + const bool arena_copy = shader_va < c.arena; + const bool vsharp_fits = (shader_va >> 48) == 0; + + // The data, written after the buffers exist. + auto* words = static_cast(pages); + auto* other_words = static_cast(other_pages); + for (UINT i = 0; i < kPages / 4; ++i) { + words[i] = 0xA0000000u + i * 3u; + other_words[i] = 0xB0000000u + i * 5u; + } + + // Descriptors: the title buffer's V# (and the other buffer's), and the negative controls. + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 8, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref heap; + EXPECT(SUCCEEDED(c.device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); + const std::uint64_t cpu = reinterpret_cast(slot(heap.p, 9))(heap.p); + const std::uint64_t gpu = reinterpret_cast(slot(heap.p, 10))(heap.p); + const UINT inc = c.device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + const D3D12_SHADER_RESOURCE_VIEW_DESC srv = raw_srv(kSrvWord, kElements); + c.device->CreateShaderResourceView(title.p, &srv, D3D12_CPU_DESCRIPTOR_HANDLE{cpu}); + c.device->CreateShaderResourceView(other.p, &srv, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + inc}); + EXPECT(vsharp_base(cpu) == ((shader_va + kSrvWord * 4) & 0xFFFFFFFFFFFFull)); + + // An arena buffer for the V# read's result, a READBACK buffer for both results. + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, readback_heap{D3D12_HEAP_TYPE_READBACK}; + Ref out, readback; + const auto uav = buffer_desc(kBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&out.p)))); + const auto readback_desc = buffer_desc(3 * kBytes); + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + // An arena buffer's V# keeps its VA: identity outside title-placed buffers. + const D3D12_CONSTANT_BUFFER_VIEW_DESC arena_cbv{out->GetGPUVirtualAddress(), 256}; + c.device->CreateConstantBufferView(&arena_cbv, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + 3 * inc}); + EXPECT(vsharp_base(cpu + 3 * inc) == out->GetGPUVirtualAddress()); + + Ref allocator; + Ref list; + EXPECT(SUCCEEDED(c.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(c.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, c.pso, + IID_PPV_ARGS(&list.p)))); + ID3D12DescriptorHeap* heaps[] = {heap.p}; + list->SetDescriptorHeaps(1, heaps); + list->SetComputeRootSignature(c.root); + // Through the V# (buffer SRV mode, s5 = 0xFFFFFFFF), into the arena buffer. Skipped when the buffer's copy is + // not within a V#'s 48 bits of heap_base (an import the driver put below the arena), which the layer logs. + if (vsharp_fits) { + list->SetComputeRoot32BitConstant(0, 0, 0); + list->SetComputeRoot32BitConstant(0, 0xFFFFFFFFu, 1); + list->SetComputeRootUnorderedAccessView(1, out->GetGPUVirtualAddress()); + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu}); + list->Dispatch(1, 1, 1); + } + // Through the root view: the title's own VA, read at +256 bytes and written at +0. + list->SetComputeRoot32BitConstant(0, kRootAdd, 0); + list->SetComputeRoot32BitConstant(0, 0xFFFFFFFEu, 1); + list->SetComputeRootUnorderedAccessView(1, title_va); + list->Dispatch(1, 1, 1); + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + list->ResourceBarrier(1, &barrier); + D3D12_RESOURCE_BARRIER to_copy{}; + to_copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + to_copy.Transition.pResource = out.p; + to_copy.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + to_copy.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + to_copy.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + list->ResourceBarrier(1, &to_copy); + list->CopyBufferRegion(readback.p, 0, out.p, 0, kBytes); + list->CopyBufferRegion(readback.p, kBytes, title.p, 0, kBytes); + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + c.queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(c.queue) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(c.queue->Signal(c.fence, ++c.fence_value))); + EXPECT(SUCCEEDED(c.fence->SetEventOnCompletion(c.fence_value, nullptr))); + + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + const auto* got = static_cast(mapped); + UINT srv_ok = 0, srv_other = 0, root_ok = 0; + for (UINT i = 0; i < kElements; ++i) { + if (got[i] == words[kSrvWord + i]) ++srv_ok; + if (got[i] == other_words[kSrvWord + i]) ++srv_other; + if (got[kElements + i] == words[64 + i] + kRootAdd) ++root_ok; + } + readback->Unmap(0, nullptr); + std::printf("%s pages: GPU copy %s (shader VA %s); V# read %s, %u/%u words matched, %u/%u read the other " + "buffer's (negative control); root view read+write %u/%u matched\n", + kind, arena_copy ? "in the arena" : "with its own device address", + arena_copy ? "an arena offset" : "device address - heap_base", + vsharp_fits ? "run" : "skipped (out of a V#'s 48 bits)", vsharp_fits ? srv_ok : 0, kElements, + vsharp_fits ? srv_other : 0, kElements, root_ok, kElements); + if (vsharp_fits) { + EXPECT(srv_ok == kElements); + EXPECT(srv_other == 0); + } + EXPECT(root_ok == kElements); + + // After release, the buffer's range is gone from the table: its old copy is not named any more. + title.reset(); + EXPECT(leonida::title_va_aliases().shader_va(title_va) == title_va); + checks += 2; + other.reset(); + heap.reset(); + VirtualFree(pages, 0, MEM_RELEASE); + VirtualFree(other_pages, 0, MEM_RELEASE); + return 0; +} + +// The title's own memory outside any slot-133 buffer: a VirtualAlloc range standing for its per-frame constant ring +// (#8862 section 3.5). Three ways a shader is given an address in it, each read back through an arena buffer: +// - a buffer V# the CPU writes into a shader-visible heap itself, as the title does (rewritten before the submission); +// - a V# made by CreateConstantBufferView (translated when written); +// - a root view (translated when set). +// Negative controls: a raw V# whose base is an arena buffer and a T#-shaped slot whose base is the ring keep their +// bytes; committed memory that is not the title's, and a title range with no committed page, are left alone. +int check_title_memory(Context& c, int& checks) { + constexpr UINT64 ring_bytes = 256 * 1024; + auto* ring = static_cast(VirtualAlloc(nullptr, ring_bytes, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + EXPECT(ring); + const auto ring_va = reinterpret_cast(ring); + EXPECT(ring_va >= c.arena); + auto& aliases = leonida::title_va_aliases(); + aliases.add_title_memory(ring_va, ring_bytes); // as the xmem shims record what they hand the title + const std::uint64_t table_before = aliases.translated(leonida::TitleVaAliases::table_view); + const std::uint64_t created_before = aliases.translated(leonida::TitleVaAliases::created_view); + const std::uint64_t root_before = aliases.translated(leonida::TitleVaAliases::root_view); + + const D3D12_HEAP_PROPERTIES default_heap{D3D12_HEAP_TYPE_DEFAULT}, readback_heap{D3D12_HEAP_TYPE_READBACK}; + const auto uav = buffer_desc(kBytes, D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + Ref out[3], readback; + for (auto& o : out) + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&default_heap, D3D12_HEAP_FLAG_NONE, &uav, + D3D12_RESOURCE_STATE_UNORDERED_ACCESS, nullptr, + IID_PPV_ARGS(&o.p)))); + const auto readback_desc = buffer_desc(3 * kBytes); + EXPECT(SUCCEEDED(c.device->CreateCommittedResource(&readback_heap, D3D12_HEAP_FLAG_NONE, &readback_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(&readback.p)))); + + const D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 8, + D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE, 0}; + Ref heap; + EXPECT(SUCCEEDED(c.device->CreateDescriptorHeap(&heap_desc, IID_PPV_ARGS(&heap.p)))); + const std::uint64_t cpu = reinterpret_cast(slot(heap.p, 9))(heap.p); + const std::uint64_t gpu = reinterpret_cast(slot(heap.p, 10))(heap.p); + const UINT inc = c.device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + const auto raw_vsharp = [](std::uint64_t address) { + leonida::gfx10::Buffer b{}; + b.address = address; + b.num_records = kBytes; + b.format = leonida::gfx10::format_from_vulkan(VK_FORMAT_R32_UINT); + b.oob_select = leonida::gfx10::OobSelect::raw; + return leonida::gfx10::encode(b); + }; + // Slot 0: a V# the CPU writes itself, its base in the ring. Slot 1: CreateConstantBufferView of the ring. + // Slot 2: a raw 64-bit VA (out[2]) for the root-view mode. Slots 3 and 4: the negative controls. + const auto v0 = raw_vsharp(ring_va + 0x1000); + std::memcpy(reinterpret_cast(cpu), v0.data(), sizeof(v0)); + const D3D12_CONSTANT_BUFFER_VIEW_DESC cbv{ring_va + 0x2000, 256}; + c.device->CreateConstantBufferView(&cbv, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + inc}); + EXPECT(vsharp_base(cpu + inc) < c.arena); // translated when written + const std::uint64_t out2 = out[2]->GetGPUVirtualAddress(); + std::memcpy(reinterpret_cast(cpu + 2 * inc), &out2, sizeof(out2)); + const auto arena_vsharp = raw_vsharp(out[0]->GetGPUVirtualAddress()); + std::memcpy(reinterpret_cast(cpu + 3 * inc), arena_vsharp.data(), sizeof(arena_vsharp)); + auto image_like = raw_vsharp(ring_va + 0x4000); + image_like[3] |= 0x8u << 28; // TYPE: an image + std::memcpy(reinterpret_cast(cpu + 4 * inc), image_like.data(), sizeof(image_like)); + std::uint8_t before3[32], before4[32]; + std::memcpy(before3, reinterpret_cast(cpu + 3 * inc), 32); + std::memcpy(before4, reinterpret_cast(cpu + 4 * inc), 32); + + // The ring's data, written before the submission (after the descriptors, as a title fills its ring per frame). + for (UINT i = 0; i < ring_bytes / 4; ++i) ring[i] = 0xC0000000u + i * 7u; + + Ref allocator; + Ref list; + EXPECT(SUCCEEDED(c.device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(&allocator.p)))); + EXPECT(SUCCEEDED(c.device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, c.pso, + IID_PPV_ARGS(&list.p)))); + ID3D12DescriptorHeap* heaps[] = {heap.p}; + list->SetDescriptorHeaps(1, heaps); + list->SetComputeRootSignature(c.root); + // The CPU-written V# (buffer SRV mode). + list->SetComputeRoot32BitConstant(0, 0, 0); + list->SetComputeRoot32BitConstant(0, 0xFFFFFFFFu, 1); + list->SetComputeRootUnorderedAccessView(1, out[0]->GetGPUVirtualAddress()); + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu}); + list->Dispatch(1, 1, 1); + // The created CBV (CBV mode). + list->SetComputeRoot32BitConstant(0, 0, 1); + list->SetComputeRootUnorderedAccessView(1, out[1]->GetGPUVirtualAddress()); + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + inc}); + list->Dispatch(1, 1, 1); + // A root view into the ring, read 256 bytes past its base, written through slot 2's raw VA. + list->SetComputeRoot32BitConstant(0, kRootAdd, 0); + list->SetComputeRoot32BitConstant(0, 0xFFFFFFFDu, 1); + list->SetComputeRootUnorderedAccessView(1, ring_va + 0x3000); + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + 2 * inc}); + list->Dispatch(1, 1, 1); + // The negative-control slots are bound too, so the scan reads them. + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + 3 * inc}); + list->SetComputeRootDescriptorTable(2, D3D12_GPU_DESCRIPTOR_HANDLE{gpu + 4 * inc}); + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + list->ResourceBarrier(1, &barrier); + for (UINT k = 0; k < 3; ++k) { + D3D12_RESOURCE_BARRIER to_copy{}; + to_copy.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + to_copy.Transition.pResource = out[k].p; + to_copy.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + to_copy.Transition.StateBefore = D3D12_RESOURCE_STATE_UNORDERED_ACCESS; + to_copy.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + list->ResourceBarrier(1, &to_copy); + list->CopyBufferRegion(readback.p, k * kBytes, out[k].p, 0, kBytes); + } + EXPECT(list->Close() == S_OK); + ID3D12CommandList* lists[] = {list.p}; + c.queue->ExecuteCommandLists(1, lists); + EXPECT(rt::d3d12::last_execute_result(c.queue) == leonida::ReplayResult::success); + EXPECT(SUCCEEDED(c.queue->Signal(c.fence, ++c.fence_value))); + EXPECT(SUCCEEDED(c.fence->SetEventOnCompletion(c.fence_value, nullptr))); + + void* mapped = nullptr; + EXPECT(SUCCEEDED(readback->Map(0, nullptr, &mapped))); + const auto* got = static_cast(mapped); + UINT raw_ok = 0, cbv_ok = 0, root_ok = 0; + for (UINT i = 0; i < kElements; ++i) { + if (got[i] == ring[0x1000 / 4 + i]) ++raw_ok; + if (got[kElements + i] == ring[0x2000 / 4 + i]) ++cbv_ok; + if (got[2 * kElements + i] == ring[0x3000 / 4 + 64 + i] + kRootAdd) ++root_ok; + } + readback->Unmap(0, nullptr); + const bool rewritten = vsharp_base(cpu) < c.arena; + const bool arena_kept = !std::memcmp(before3, reinterpret_cast(cpu + 3 * inc), 32); + const bool image_kept = !std::memcmp(before4, reinterpret_cast(cpu + 4 * inc), 32); + std::printf("title memory (a constant ring): CPU-written table V# %u/%u (rewritten before the submission: %s), " + "created CBV %u/%u, root view %u/%u; negative controls: arena V# kept %s, T#-shaped slot kept %s; " + "translated: %llu table V#, %llu created, %llu root\n", + raw_ok, kElements, rewritten ? "yes" : "no", cbv_ok, kElements, root_ok, kElements, + arena_kept ? "yes" : "no", image_kept ? "yes" : "no", + static_cast(aliases.translated(leonida::TitleVaAliases::table_view) - table_before), + static_cast(aliases.translated(leonida::TitleVaAliases::created_view) - + created_before), + static_cast(aliases.translated(leonida::TitleVaAliases::root_view) - root_before)); + EXPECT(raw_ok == kElements && cbv_ok == kElements && root_ok == kElements); + EXPECT(rewritten && arena_kept && image_kept); + // Left alone and counted: committed memory that is not the title's (the runtime's own, say), and a title range + // with no committed page. + const std::uint64_t untranslated_before = aliases.untranslated(leonida::TitleVaAliases::created_view); + void* host = VirtualAlloc(nullptr, 65536, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); + void* gone = VirtualAlloc(nullptr, 65536, MEM_RESERVE, PAGE_READWRITE); + const auto host_va = reinterpret_cast(host), gone_va = reinterpret_cast(gone); + aliases.add_title_memory(gone_va, 65536); + const D3D12_CONSTANT_BUFFER_VIEW_DESC not_title{host_va, 256}, reserved_only{gone_va, 256}; + c.device->CreateConstantBufferView(¬_title, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + 5 * inc}); + c.device->CreateConstantBufferView(&reserved_only, D3D12_CPU_DESCRIPTOR_HANDLE{cpu + 6 * inc}); + EXPECT(vsharp_base(cpu + 5 * inc) == (host_va & 0xFFFFFFFFFFFFull)); + EXPECT(vsharp_base(cpu + 6 * inc) == (gone_va & 0xFFFFFFFFFFFFull)); + EXPECT(aliases.untranslated(leonida::TitleVaAliases::created_view) - untranslated_before == 2); + aliases.remove_title_memory(gone_va); + aliases.remove_title_memory(ring_va); + VirtualFree(host, 0, MEM_RELEASE); + VirtualFree(gone, 0, MEM_RELEASE); + checks += 4; + return 0; +} + +} // namespace + +int main() { + vktest::Device d; + const auto device_status = d.initialize(); + if (device_status == vktest::DeviceStatus::unavailable) { + std::fprintf(stderr, "SKIP: no usable Vulkan 1.3 device\n"); + return 77; + } + EXPECT(device_status == vktest::DeviceStatus::ready); + + std::vector fssm = {'F', 'S', 'S', 'M'}; + put32(fssm, 6000); + for (std::uint32_t i = 0; i < 14; ++i) put32(fssm, 0xbf810000u + i); + const auto container = shader_container(fssm); + const testfiles::ScratchDir scratch("leonida_title_va_test"); + const auto& library = scratch.path(); + EXPECT(testfiles::copy_file(vktest::shader_fixture_path(LEONIDA_TEST_CS_SPV), library / "cs_user_data.spv")); + { + std::ofstream index(library / "index.json", std::ios::binary); + index << "{\"cs_user_data\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << leonida::sha256_hex(fssm) + << "\", \"bindings\": [], \"push_constant_bytes\": 144, \"local_size\": [64, 1, 1], " + "\"uses_code_base\": true, \"wave64\": false}}"; + } + + int checks = 0; + { + rt::d3d12::VulkanDeviceInfo info{}; + info.get_instance_proc = d.instance_proc; + info.instance = d.instance; + info.physical = d.physical; + info.device = d.device; + info.queue = d.queue; + info.queue_family = d.family; + info.buffer_device_address = true; + info.subgroup = d.subgroup; + info.shader_dir = library.string(); + ID3D12Device* inner = nullptr; // owned by the proxy, as in d3d12_compute_test + EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); + Ref device; + EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), + reinterpret_cast(&device.p)))); + rt::d3d12::set_device_outer(inner, device.p); + + // [0] two constants (s4, s5), [1] a root UAV (s6:s7), [2] a one-descriptor table (s8): the console compute + // layout cs_user_data.comp reads. + D3D12_DESCRIPTOR_RANGE range{D3D12_DESCRIPTOR_RANGE_TYPE_CBV, 1, 1, 0, 0}; + D3D12_ROOT_PARAMETER params[3] = {}; + params[0].ParameterType = D3D12_ROOT_PARAMETER_TYPE_32BIT_CONSTANTS; + params[0].Constants = {0, 0, 2}; + params[1].ParameterType = D3D12_ROOT_PARAMETER_TYPE_UAV; + params[1].Descriptor = {0, 0}; + params[2].ParameterType = D3D12_ROOT_PARAMETER_TYPE_DESCRIPTOR_TABLE; + params[2].DescriptorTable = {1, &range}; + D3D12_VERSIONED_ROOT_SIGNATURE_DESC root_desc{}; + root_desc.Version = D3D_ROOT_SIGNATURE_VERSION_1_0; + root_desc.Desc_1_0 = {3, params, 0, nullptr, D3D12_ROOT_SIGNATURE_FLAG_NONE}; + const auto root_blob = serialize(root_desc); + EXPECT(!root_blob.empty()); + Ref root; + EXPECT(SUCCEEDED(device->CreateRootSignature(0, root_blob.data(), root_blob.size(), IID_PPV_ARGS(&root.p)))); + D3D12_COMPUTE_PIPELINE_STATE_DESC pso_desc{}; + pso_desc.pRootSignature = root.p; + pso_desc.CS = {container.data(), container.size()}; + const IID pso_iid = __uuidof(ID3D12PipelineState); + Ref pso; + EXPECT(SUCCEEDED(reinterpret_cast(slot(device.p, 62))( + device.p, &pso_desc, 0, 0, &pso_iid, reinterpret_cast(&pso.p)))); + + const D3D12_COMMAND_QUEUE_DESC queue_desc{}; + Ref queue; + Ref fence; + EXPECT(SUCCEEDED(device->CreateCommandQueue(&queue_desc, IID_PPV_ARGS(&queue.p)))); + EXPECT(SUCCEEDED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(&fence.p)))); + + Context c; + c.inner = inner; + c.device = device.p; + c.root = root.p; + c.pso = pso.p; + c.queue = queue.p; + c.fence = fence.p; + c.arena = rt::d3d12::device_arena_size(device.p); + EXPECT(c.arena > 0); + if (check_kind(c, "read-write", PAGE_READWRITE, checks)) return 1; + if (check_kind(c, "write-combined", PAGE_READWRITE | PAGE_WRITECOMBINE, checks)) return 1; + if (check_title_memory(c, checks)) return 1; + } + if (d.validation_errors()) { + std::fprintf(stderr, "%u validation errors\n", d.validation_errors()); + return 1; + } + std::printf("title-placed buffers: a translated shader reached both page kinds through a root view and a buffer " + "V#; %d descriptor-level negative controls held\n", + checks); + return 0; +} diff --git a/runtime/test/d3d12_translated_draw_test.cpp b/runtime/test/d3d12_translated_draw_test.cpp index 62ce7b65cb..87bf185fa2 100644 --- a/runtime/test/d3d12_translated_draw_test.cpp +++ b/runtime/test/d3d12_translated_draw_test.cpp @@ -180,7 +180,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); #endif diff --git a/runtime/test/d3d12_vulkan_device_test.cpp b/runtime/test/d3d12_vulkan_device_test.cpp index 892f3a04eb..61f4aefe5c 100644 --- a/runtime/test/d3d12_vulkan_device_test.cpp +++ b/runtime/test/d3d12_vulkan_device_test.cpp @@ -5086,7 +5086,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); // the proxy now owns `inner` EXPECT(rt::d3d12_xs::is_device_proxy(device.p)); EXPECT(rt::d3d12_xs::device_proxy_slot_count(device.p) == 80); // ID3D12Device11 @@ -5414,7 +5414,7 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(fallback_info, IID_PPV_ARGS(&fallback_inner)))); Ref fallback_device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(fallback_inner, __uuidof(ID3D12Device), - reinterpret_cast(&fallback_device.p)))); + reinterpret_cast(&fallback_device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(fallback_inner, fallback_device.p); D3D12_FEATURE_DATA_D3D12_OPTIONS8 options8{TRUE}; EXPECT(fallback_device->CheckFeatureSupport(D3D12_FEATURE_D3D12_OPTIONS8, &options8, @@ -5576,7 +5576,14 @@ int main() { Ref granted_q; EXPECT(SUCCEEDED(device->CreateCommandQueue(&rt_desc, IID_PPV_ARGS(&granted_q.p))) && granted_q.p); if (granted_q.p) { - EXPECT(granted_q->GetDesc().Priority == D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME); + // PC GetDesc shares console slot 18 with the newer layout's GetTimestampFrequency; the proxy + // serves the frequency getter while the layout is undetected, so the desc is read on the real + // queue instead. + if (auto* real_q = rt::d3d12_xs::queue_proxy_real_queue(granted_q.p)) { + EXPECT(real_q->GetDesc().Priority == D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME); + } else { + EXPECT(granted_q->GetDesc().Priority == D3D12_COMMAND_QUEUE_PRIORITY_GLOBAL_REALTIME); + } } granted_q.reset(); rt::d3d12::set_global_realtime_privilege_override_for_test(-1); diff --git a/runtime/test/device_proxy_test.cpp b/runtime/test/device_proxy_test.cpp index 46a853e7c3..f02d6cd027 100644 --- a/runtime/test/device_proxy_test.cpp +++ b/runtime/test/device_proxy_test.cpp @@ -3,6 +3,7 @@ // It creates the proxy through the registered d3d12_xs!D3D12XboxCreateDevice shim, then calls the measured Xbox // slots exactly as the guest would (raw function pointers, not the C++ interface): // slot 14 CreateDescriptorHeap (returns a heap proxy) +// slot 25/26 GetResourceAllocationInfo/GetCustomHeapProperties in the title's C form (return buffer first) // heap 9/10 GetCPU/GetGPUDescriptorHandleForHeapStart (Xbox: 8-byte handle in RAX; the PC heap uses the // hidden return pointer in RDX, so slot 14 wraps it) // slot 62 CreateComputePipelineState @@ -15,6 +16,7 @@ #include #include +#include #include #include #include @@ -22,8 +24,10 @@ #include #include "d3d12_trace.h" +#include "d3d12_xs_desc_clean.h" #include "d3d12_xs_device.h" #include "shims.h" +#include "../src/frame_pacer.h" namespace { @@ -159,6 +163,9 @@ int main(int argc, char** argv) { check(rt::d3d12_xs::device_slot_overridden(14), "device slot 14 is the descriptor-heap override"); check(rt::d3d12_xs::device_slot_overridden(62), "device slot 62 is the compute-PSO override"); check(rt::d3d12_xs::device_slot_overridden(76), "device slot 76 is the resource override"); + check(rt::d3d12_xs::device_slot_overridden(86), "device slot 86 is the CreatePipelineState override"); + check(rt::d3d12_xs::device_slot_overridden(101), "device slot 101 is the CreateStateObject override"); + check(rt::d3d12_xs::device_slot_overridden(108), "device slot 108 is the GetResourceAllocationInfo2 override"); check(rt::d3d12_xs::device_slot_overridden(67), "device slot 67 is the DeserializeComputePipelineStateX override (console native-code compute pipeline, not PC CreateProtectedResourceSession1)"); @@ -199,6 +206,72 @@ int main(int argc, char** argv) { const LUID real_luid = real ? real->GetAdapterLuid() : LUID{}; check(proxy_luid.LowPart == real_luid.LowPart && proxy_luid.HighPart == real_luid.HighPart, "slot 43 forwards GetAdapterLuid (struct return)"); + // Slot 25 returns a struct wider than 8 bytes. The console title calls it with the C ABI: the hidden + // return pointer first (RCX), then the device (RDX), then the arguments, and the buffer comes back in RAX + // (measured for slot 26 on the retail executable). Call slot 25 that way through a raw function pointer and compare + // with the PC device's own answer. + check(rt::d3d12_xs::device_slot_overridden(25), "device slot 25 is the C-ABI GetResourceAllocationInfo override"); + if (real) { + using AllocInfoFn = D3D12_RESOURCE_ALLOCATION_INFO*(WINAPI*)(D3D12_RESOURCE_ALLOCATION_INFO*, void*, UINT, UINT, + const D3D12_RESOURCE_DESC*); + auto get_alloc_info = reinterpret_cast(proxy_vtbl[25]); + const D3D12_RESOURCE_DESC desc = buffer_desc(); + D3D12_RESOURCE_ALLOCATION_INFO got{~0ull, ~0ull}; + D3D12_RESOURCE_ALLOCATION_INFO* returned = get_alloc_info(&got, device.Get(), 0, 1, &desc); + // The proxy cleans the console layout word and flag bits before the PC call (stop 16), so the expected answer is + // the PC device's for the cleaned description (the raw 0x101 layout makes WARP answer UINT64_MAX). + const D3D12_RESOURCE_DESC clean = rt::d3d12_xs::pc_resource_desc(desc); + const D3D12_RESOURCE_ALLOCATION_INFO want = real->GetResourceAllocationInfo(0, 1, &clean); + check(want.SizeInBytes != UINT64_MAX, "WARP accepts the normalized slot-25 buffer description"); + check(returned == &got, "slot 25 returns the caller's buffer in RAX"); + check(got.SizeInBytes == want.SizeInBytes && got.Alignment == want.Alignment, + "slot 25 (C ABI) writes the PC device's GetResourceAllocationInfo into the caller's buffer"); + + // The runtime's own code calls the proxy through d3d12.h (PC form: this, then the return buffer). Slot 25 + // still answers that form. + const D3D12_RESOURCE_ALLOCATION_INFO pc_info = device->GetResourceAllocationInfo(0, 1, &desc); + check(pc_info.SizeInBytes == want.SizeInBytes && pc_info.Alignment == want.Alignment, + "slot 25 still answers the PC (C++) form"); + + // A console depth-stencil texture that allows unordered access too, as a title sizes one: a 2D + // R32G8X24_TYPELESS texture with ALLOW_DEPTH_STENCIL | ALLOW_UNORDERED_ACCESS and the console layout word. The + // PC device refuses the flag pair (negative control); slot 25 sizes it as the depth-stencil texture alone. + D3D12_RESOURCE_DESC ds_uav{}; + ds_uav.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + ds_uav.Width = 2560; + ds_uav.Height = 1440; + ds_uav.DepthOrArraySize = 1; + ds_uav.MipLevels = 1; + ds_uav.Format = DXGI_FORMAT_R32G8X24_TYPELESS; + ds_uav.SampleDesc.Count = 1; + ds_uav.Layout = static_cast(0x101); + ds_uav.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + D3D12_RESOURCE_DESC pc_pair = ds_uav; + pc_pair.Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + check(real->GetResourceAllocationInfo(0, 1, &pc_pair).SizeInBytes == UINT64_MAX, + "the PC device refuses a depth-stencil texture with unordered access (negative control)"); + D3D12_RESOURCE_DESC ds_only = pc_pair; + ds_only.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + const D3D12_RESOURCE_ALLOCATION_INFO ds_want = real->GetResourceAllocationInfo(0, 1, &ds_only); + check(ds_want.SizeInBytes != UINT64_MAX, "WARP sizes the depth-stencil texture without unordered access"); + const D3D12_RESOURCE_DESC ds_clean = rt::d3d12_xs::pc_resource_desc(ds_uav); + check(ds_clean.Flags == D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL, + "pc_resource_desc drops unordered access from a depth-stencil texture"); + D3D12_RESOURCE_DESC uav_buffer = buffer_desc(); + uav_buffer.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + D3D12_RESOURCE_DESC rt_uav = ds_only; + rt_uav.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + rt_uav.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + check(rt::d3d12_xs::pc_resource_desc(uav_buffer).Flags == D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS && + rt::d3d12_xs::pc_resource_desc(rt_uav).Flags == rt_uav.Flags, + "pc_resource_desc keeps unordered access on buffers and color textures"); + D3D12_RESOURCE_ALLOCATION_INFO ds_got{~0ull, ~0ull}; + get_alloc_info(&ds_got, device.Get(), 0, 1, &ds_uav); + check(ds_got.SizeInBytes != UINT64_MAX && ds_got.SizeInBytes >= ds_want.SizeInBytes && + (ds_got.SizeInBytes >> 32) == 0, + "slot 25 (C ABI) sizes a console depth-stencil texture with unordered access"); + } + D3D12_RESOURCE_DESC reserved_desc = buffer_desc(); reserved_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; ComPtr reserved; @@ -206,6 +279,41 @@ int main(int argc, char** argv) { IID_PPV_ARGS(reserved.GetAddressOf())); check(SUCCEEDED(hr) && reserved != nullptr, "slot 30 forwards CreateReservedResource (stack arguments)"); + // Slot 26 the way the retail executable calls GetCustomHeapProperties: the buffer for the struct in RCX, the + // device in RDX, for the three heap types it asks about. The answer is the PC device's own, and nothing but + // the struct is written (the buffer sits in a pattern). On main this call read the PC vtable through the buffer. + check(rt::d3d12_xs::device_slot_overridden(26), "device slot 26 takes the console's struct-return form"); + using XboxGetCustomHeapPropertiesFn = + D3D12_HEAP_PROPERTIES*(WINAPI*)(D3D12_HEAP_PROPERTIES*, void*, UINT, D3D12_HEAP_TYPE); + auto get_custom_heap = reinterpret_cast(proxy_vtbl[26]); + const D3D12_HEAP_TYPE heap_types[] = {D3D12_HEAP_TYPE_DEFAULT, D3D12_HEAP_TYPE_UPLOAD, D3D12_HEAP_TYPE_READBACK}; + bool console_returns_buffer = true, console_matches_pc = real != nullptr, console_writes_only_struct = true; + for (const D3D12_HEAP_TYPE type : heap_types) { + struct Padded { + D3D12_HEAP_PROPERTIES value; + std::uint8_t after[64]; + } padded; + std::memset(&padded, 0xA5, sizeof(padded)); + console_returns_buffer = get_custom_heap(&padded.value, device.Get(), 1, type) == &padded.value && + console_returns_buffer; + const D3D12_HEAP_PROPERTIES want = real ? real->GetCustomHeapProperties(1, type) : D3D12_HEAP_PROPERTIES{}; + console_matches_pc = console_matches_pc && std::memcmp(&padded.value, &want, sizeof(want)) == 0; + for (const std::uint8_t byte : padded.after) + console_writes_only_struct = console_writes_only_struct && byte == 0xA5; + } + check(console_returns_buffer, "slot 26 console form returns the buffer's address"); + check(console_matches_pc, "slot 26 console form writes the PC device's DEFAULT, UPLOAD and READBACK properties"); + check(console_writes_only_struct, "slot 26 console form writes nothing past the struct"); + check(rt::d3d12_xs::device_slot_hits(26) == 3, "slot 26 hit counter is 3"); + check(rt::d3d12_xs::is_device_proxy(device.Get()) && rt::d3d12_xs::device_proxy_real_device(device.Get()) == real, + "the proxy is intact after the console-form calls"); + // A PC C++ call through the proxy (the proxy in RCX, the buffer in RDX) is still forwarded. + const D3D12_HEAP_PROPERTIES pc_form = device->GetCustomHeapProperties(1, D3D12_HEAP_TYPE_UPLOAD); + const D3D12_HEAP_PROPERTIES pc_want = real ? real->GetCustomHeapProperties(1, D3D12_HEAP_TYPE_UPLOAD) + : D3D12_HEAP_PROPERTIES{}; + check(real && std::memcmp(&pc_form, &pc_want, sizeof(pc_want)) == 0 && rt::d3d12_xs::device_slot_hits(26) == 4, + "slot 26 PC form still forwards GetCustomHeapProperties"); + // Slot 14: descriptor heap through the proxy. The proxy wraps the real PC heap for the handle ABI. D3D12_DESCRIPTOR_HEAP_DESC heap_desc{}; heap_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; @@ -348,15 +456,20 @@ int main(int argc, char** argv) { check(hr == S_OK && token2 != 0 && token2 != token, "slot 80 returns a fresh token on the next wait"); hr = reinterpret_cast(proxy_vtbl[80])(device.Get(), 0, 0, nullptr, 0, nullptr); check(hr == E_POINTER, "slot 80 refuses a null token with E_POINTER"); + const auto tokens = rt::d3d12_xs::device_frame_tokens(device.Get()); + check(tokens && tokens->issued() == token2 && token2 == token + 1, + "slot 80 tokens come from the device's frame token source"); + check(!rt::d3d12_xs::device_frame_tokens(nullptr), "a non-proxy has no frame token source"); check(rt::d3d12_xs::device_slot_hits(78) == 1 && rt::d3d12_xs::device_slot_hits(79) == 1 && rt::d3d12_xs::device_slot_hits(80) == 3, "slots 78/79/80 hit counters are 1/1/3"); - D3D12_COMMAND_QUEUE_DESC xbox_queue{}; - xbox_queue.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; + // The console description is 32 bytes: the PC prefix, then four Xbox words (the proxy logs them). + struct { D3D12_COMMAND_QUEUE_DESC pc; std::uint32_t extra[4]; } xbox_queue{}; + xbox_queue.pc.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; const IID iid_queue = __uuidof(ID3D12CommandQueue); ComPtr xbox_queue_proxy; - hr = reinterpret_cast(proxy_vtbl[48])(device.Get(), &xbox_queue, &iid_queue, + hr = reinterpret_cast(proxy_vtbl[48])(device.Get(), reinterpret_cast(&xbox_queue), &iid_queue, reinterpret_cast(xbox_queue_proxy.GetAddressOf())); check(hr == S_OK && rt::d3d12_xs::is_queue_proxy(xbox_queue_proxy.Get()), "slot 48 CreateCommandQueueX returns a queue proxy"); @@ -436,6 +549,101 @@ int main(int argc, char** argv) { check(SUCCEEDED(hr) && pso67 != nullptr, "slot 67 creates a compute PSO via CreateComputePipelineState"); check(rt::d3d12_xs::device_slot_hits(67) == 1, "slot 67 hit counter is 1"); check(rt::d3d12_xs::device_slot_first_call_seen(67), "slot 67 first-call flag is set"); + + // Slot 86: CreatePipelineState(const D3D12_PIPELINE_STATE_STREAM_DESC*, REFIID, void**), forwarded to PC + // ID3D12Device2::CreatePipelineState (PC slot 47). + if (slots > 47) { + struct alignas(void*) ComputeStream { + alignas(void*) D3D12_PIPELINE_STATE_SUBOBJECT_TYPE root_type = + D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_ROOT_SIGNATURE; + ID3D12RootSignature* root_sig = nullptr; + alignas(void*) D3D12_PIPELINE_STATE_SUBOBJECT_TYPE cs_type = D3D12_PIPELINE_STATE_SUBOBJECT_TYPE_CS; + D3D12_SHADER_BYTECODE cs{}; + } stream; + stream.root_sig = root_signature.Get(); + stream.cs.pShaderBytecode = bytecode->GetBufferPointer(); + stream.cs.BytecodeLength = bytecode->GetBufferSize(); + D3D12_PIPELINE_STATE_STREAM_DESC stream_desc{sizeof(stream), &stream}; + using XboxCreatePipelineStateFn = + HRESULT(WINAPI*)(void*, const D3D12_PIPELINE_STATE_STREAM_DESC*, const IID*, void**); + auto create_stream_pso = reinterpret_cast(proxy_vtbl[86]); + ComPtr pso86; + hr = create_stream_pso(device.Get(), &stream_desc, &iid_pso, + reinterpret_cast(pso86.GetAddressOf())); + check(SUCCEEDED(hr) && pso86 != nullptr, + "slot 86 creates a PSO via PC ID3D12Device2::CreatePipelineState (slot 47)"); + check(rt::d3d12_xs::device_slot_hits(86) == 1, "slot 86 hit counter is 1"); + check(rt::d3d12_xs::device_slot_first_call_seen(86), "slot 86 first-call flag is set"); + } + } + + // Slot 101: CreateStateObject(const D3D12_STATE_OBJECT_DESC*, REFIID, void**), forwarded to PC + // ID3D12Device5::CreateStateObject (PC slot 62). + if (slots > 62) { + using XboxCreateStateObjectFn = HRESULT(WINAPI*)(void*, const D3D12_STATE_OBJECT_DESC*, const IID*, void**); + auto create_state_object = reinterpret_cast(proxy_vtbl[101]); + D3D12_STATE_OBJECT_DESC empty_so{}; + empty_so.Type = D3D12_STATE_OBJECT_TYPE_RAYTRACING_PIPELINE; + void* so_out = reinterpret_cast(0x1111); + hr = create_state_object(device.Get(), &empty_so, nullptr, &so_out); + check(hr == E_POINTER && so_out == nullptr, "slot 101 nulls its output for a null IID"); + check(rt::d3d12_xs::device_slot_hits(101) == 1, "slot 101 hit counter is 1"); + } + + // Slot 108: GetResourceAllocationInfo2(ret, this, visible_mask, count, descs, info1) with C-ABI struct return, + // 56-byte D3D12_RESOURCE_DESC entries, and Xbox layout/flag words, compared against direct PC + // ID3D12Device8::GetResourceAllocationInfo2 (PC slot 68). + if (slots > 68) { + ComPtr real_device8; + if (real && SUCCEEDED(real->QueryInterface(IID_PPV_ARGS(real_device8.GetAddressOf()))) && real_device8) { + D3D12_RESOURCE_DESC xbox_descs[2]{}; + xbox_descs[0].Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + xbox_descs[0].Width = 64; + xbox_descs[0].Height = 64; + xbox_descs[0].DepthOrArraySize = 1; + xbox_descs[0].MipLevels = 1; + xbox_descs[0].Format = DXGI_FORMAT_R8G8B8A8_UNORM; + xbox_descs[0].SampleDesc.Count = 1; + xbox_descs[0].Layout = static_cast(0x105); + xbox_descs[0].Flags = static_cast( + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | 0x300000u); + xbox_descs[1].Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + xbox_descs[1].Width = 4096; + xbox_descs[1].Height = 1; + xbox_descs[1].DepthOrArraySize = 1; + xbox_descs[1].MipLevels = 1; + xbox_descs[1].SampleDesc.Count = 1; + xbox_descs[1].Layout = static_cast(0x101); + xbox_descs[1].Flags = static_cast(0x200000u); + + D3D12_RESOURCE_DESC1 pc_descs[2]{}; + std::memcpy(&pc_descs[0], &xbox_descs[0], sizeof(D3D12_RESOURCE_DESC)); + pc_descs[0].SamplerFeedbackMipRegion = {}; + pc_descs[0].Layout = D3D12_TEXTURE_LAYOUT_UNKNOWN; + pc_descs[0].Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + std::memcpy(&pc_descs[1], &xbox_descs[1], sizeof(D3D12_RESOURCE_DESC)); + pc_descs[1].SamplerFeedbackMipRegion = {}; + pc_descs[1].Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + pc_descs[1].Flags = D3D12_RESOURCE_FLAG_NONE; + + D3D12_RESOURCE_ALLOCATION_INFO1 pc_info1[2]{}; + const D3D12_RESOURCE_ALLOCATION_INFO pc_info = + real_device8->GetResourceAllocationInfo2(1, 2, pc_descs, pc_info1); + + using XboxGetAllocInfo2CAbiFn = D3D12_RESOURCE_ALLOCATION_INFO*(WINAPI*)( + D3D12_RESOURCE_ALLOCATION_INFO*, void*, UINT, UINT, const D3D12_RESOURCE_DESC*, + D3D12_RESOURCE_ALLOCATION_INFO1*); + auto get_alloc_info2 = reinterpret_cast(proxy_vtbl[108]); + D3D12_RESOURCE_ALLOCATION_INFO xbox_info{}; + D3D12_RESOURCE_ALLOCATION_INFO1 xbox_info1[2]{}; + D3D12_RESOURCE_ALLOCATION_INFO* ret_ptr = + get_alloc_info2(&xbox_info, device.Get(), 1, 2, xbox_descs, xbox_info1); + check(ret_ptr == &xbox_info && xbox_info.SizeInBytes == pc_info.SizeInBytes && + xbox_info.Alignment == pc_info.Alignment && xbox_info1[0].SizeInBytes == pc_info1[0].SizeInBytes && + xbox_info1[1].SizeInBytes == pc_info1[1].SizeInBytes, + "slot 108 C-ABI GetResourceAllocationInfo2 with 56-byte Xbox descs matches PC Device8"); + check(rt::d3d12_xs::device_slot_hits(108) == 1, "slot 108 hit counter is 1"); + } } // _COM_Outptr_ (d3d12.h): a failed create leaves NULL in the output. WARP accepts invalid heap descriptions, @@ -497,6 +705,251 @@ int main(int argc, char** argv) { } } + // Title-exported __XMemAllocationHooks__ backing for CreateDescriptorHeap (slot 14) + CPU handle translation + // against the real WARP D3D12 runtime. + { + struct HookState { + alignas(64) std::uint8_t backing[4096]{}; + std::size_t alloc_size = 0; + std::uint64_t alloc_attr = 0; + void* freed_ptr = nullptr; + std::uint64_t freed_attr = 0; + int alloc_count = 0; + int free_count = 0; + }; + static HookState hook_state; + hook_state = {}; + struct HookCallbacks { + static void* __stdcall alloc(std::size_t size, std::uint64_t attr) { + ++hook_state.alloc_count; + hook_state.alloc_size = size; + hook_state.alloc_attr = attr; + if ((attr & 0x3FFFull) == 4 && size <= sizeof(hook_state.backing)) return hook_state.backing; + return nullptr; + } + static void __stdcall free(void* ptr, std::uint64_t attr) { + ++hook_state.free_count; + hook_state.freed_ptr = ptr; + hook_state.freed_attr = attr; + } + }; + const rt::shims::XMemAllocationHooks title_hooks{&HookCallbacks::alloc, &HookCallbacks::free}; + rt::shims::add_xmem_allocation_hooks(&title_hooks, &title_hooks); + + D3D12_DESCRIPTOR_HEAP_DESC hooked_desc{}; + hooked_desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + hooked_desc.NumDescriptors = 4; + hooked_desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; + const UINT inc = device->GetDescriptorHandleIncrementSize(hooked_desc.Type); + ComPtr hooked_heap; + hr = device->CreateDescriptorHeap(&hooked_desc, IID_PPV_ARGS(hooked_heap.GetAddressOf())); + check(SUCCEEDED(hr) && hooked_heap != nullptr, "hooked slot 14 creates a descriptor heap"); + check(hook_state.alloc_count == 1 && hook_state.alloc_size == hooked_desc.NumDescriptors * inc && + hook_state.alloc_attr == rt::d3d12_xs::kXmemDescriptorHeapAttributes, + "slot 14 invokes __XMemAllocationHooks__ with heap byte size and D3D descriptor-heap attributes"); + if (hooked_heap) { + void** hooked_vtbl = *reinterpret_cast(hooked_heap.Get()); + const auto hooked_cpu = reinterpret_cast(hooked_vtbl[9])(hooked_heap.Get()); + const auto hooked_gpu = reinterpret_cast(hooked_vtbl[10])(hooked_heap.Get()); + const auto expected_base = reinterpret_cast(hook_state.backing); + check(hooked_cpu.ptr == expected_base, + "hooked heap slot 9 returns the title-supplied CPU descriptor base"); + check(hooked_gpu.ptr != 0, "hooked heap slot 10 returns a valid GPU descriptor start"); + + // Create a CBV at slot 1 of the title-backed heap; WARP validates the translated real handle. + D3D12_CONSTANT_BUFFER_VIEW_DESC cbv{}; + cbv.BufferLocation = 0; + cbv.SizeInBytes = 256; + device->CreateConstantBufferView(&cbv, D3D12_CPU_DESCRIPTOR_HANDLE{expected_base + inc}); + check(true, "CreateConstantBufferView translates a title-backed CPU descriptor handle on WARP"); + } + hooked_heap.Reset(); + check(hook_state.free_count == 1 && hook_state.freed_ptr == hook_state.backing && + hook_state.freed_attr == rt::d3d12_xs::kXmemDescriptorHeapAttributes, + "releasing the hooked heap frees its backing through __XMemAllocationHooks__"); + + // End-to-end console command list clear + readback with title-backed RTV and DSV heaps: + // verifies CPU handle translation on console slots 50/51/52 and FLOAT Depth (XMM3) on slot 51. + { + struct DualHeapState { + alignas(64) std::uint8_t rtv_backing[1024]{}; + alignas(64) std::uint8_t dsv_backing[1024]{}; + int next_slice = 0; + }; + static DualHeapState dual_state; + dual_state = {}; + struct DualHooks { + static void* __stdcall alloc(std::size_t size, std::uint64_t attr) { + if ((attr & 0x3FFFull) != 4 || size > 1024) return nullptr; + return dual_state.next_slice++ == 0 ? dual_state.rtv_backing : dual_state.dsv_backing; + } + static void __stdcall free(void*, std::uint64_t) {} + }; + const rt::shims::XMemAllocationHooks dual_hooks{&DualHooks::alloc, &DualHooks::free}; + rt::shims::remove_xmem_allocation_hooks(&title_hooks); + rt::shims::add_xmem_allocation_hooks(&dual_hooks, &dual_hooks); + + D3D12_DESCRIPTOR_HEAP_DESC rtv_hd{D3D12_DESCRIPTOR_HEAP_TYPE_RTV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + D3D12_DESCRIPTOR_HEAP_DESC dsv_hd{D3D12_DESCRIPTOR_HEAP_TYPE_DSV, 2, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; + ComPtr rtv_heap, dsv_heap; + hr = device->CreateDescriptorHeap(&rtv_hd, IID_PPV_ARGS(rtv_heap.GetAddressOf())); + HRESULT hr_dsv = device->CreateDescriptorHeap(&dsv_hd, IID_PPV_ARGS(dsv_heap.GetAddressOf())); + check(SUCCEEDED(hr) && SUCCEEDED(hr_dsv) && rtv_heap && dsv_heap, + "hooked RTV and DSV heaps create through slot 14"); + + const D3D12_HEAP_PROPERTIES default_hp = default_heap(); + D3D12_HEAP_PROPERTIES readback_hp = default_heap(); + readback_hp.Type = D3D12_HEAP_TYPE_READBACK; + D3D12_RESOURCE_DESC rt_desc{}; + rt_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + rt_desc.Width = 4; + rt_desc.Height = 4; + rt_desc.DepthOrArraySize = 1; + rt_desc.MipLevels = 1; + rt_desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + rt_desc.SampleDesc = {1, 0}; + rt_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + + D3D12_RESOURCE_DESC ds_desc = rt_desc; + ds_desc.Format = DXGI_FORMAT_D32_FLOAT; + ds_desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_DEPTH_STENCIL; + + D3D12_RESOURCE_DESC rb_desc = buffer_desc(); + rb_desc.Width = 4096; + rb_desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + + ComPtr rt_tex, ds_tex, rb_buf; + hr = device->CreateCommittedResource(&default_hp, D3D12_HEAP_FLAG_NONE, &rt_desc, + D3D12_RESOURCE_STATE_RENDER_TARGET, nullptr, + IID_PPV_ARGS(rt_tex.GetAddressOf())); + HRESULT hr2 = device->CreateCommittedResource(&default_hp, D3D12_HEAP_FLAG_NONE, &ds_desc, + D3D12_RESOURCE_STATE_DEPTH_WRITE, nullptr, + IID_PPV_ARGS(ds_tex.GetAddressOf())); + HRESULT hr3 = device->CreateCommittedResource(&readback_hp, D3D12_HEAP_FLAG_NONE, &rb_desc, + D3D12_RESOURCE_STATE_COPY_DEST, nullptr, + IID_PPV_ARGS(rb_buf.GetAddressOf())); + check(SUCCEEDED(hr) && SUCCEEDED(hr2) && SUCCEEDED(hr3), + "RT, DS and readback resources create for console list clear test"); + + if (rtv_heap && dsv_heap && rt_tex && ds_tex && rb_buf) { + const auto rtv_cpu = reinterpret_cast( + (*reinterpret_cast(rtv_heap.Get()))[9])(rtv_heap.Get()); + const auto dsv_cpu = reinterpret_cast( + (*reinterpret_cast(dsv_heap.Get()))[9])(dsv_heap.Get()); + const UINT rtv_inc = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_RTV); + const UINT dsv_inc = device->GetDescriptorHandleIncrementSize(D3D12_DESCRIPTOR_HEAP_TYPE_DSV); + const D3D12_CPU_DESCRIPTOR_HANDLE rtv_h{rtv_cpu.ptr + rtv_inc}; + const D3D12_CPU_DESCRIPTOR_HANDLE dsv_h{dsv_cpu.ptr + dsv_inc}; + check(rtv_cpu.ptr == reinterpret_cast(dual_state.rtv_backing) && + dsv_cpu.ptr == reinterpret_cast(dual_state.dsv_backing), + "RTV and DSV heaps report their title-backed CPU descriptor bases"); + + device->CreateRenderTargetView(rt_tex.Get(), nullptr, rtv_h); + device->CreateDepthStencilView(ds_tex.Get(), nullptr, dsv_h); + + using CreateQueueXFn = HRESULT(WINAPI*)(void*, const D3D12_COMMAND_QUEUE_DESC*, const IID*, void**); + using CreateListXFn = HRESULT(WINAPI*)(void*, const void*, ID3D12CommandAllocator*, + ID3D12PipelineState*, const IID*, void**); + using CloseFn = HRESULT(WINAPI*)(void*); + using BarrierFn = void(WINAPI*)(void*, UINT, const D3D12_RESOURCE_BARRIER*); + using CopyTexFn = void(WINAPI*)(void*, const D3D12_TEXTURE_COPY_LOCATION*, UINT, UINT, UINT, + const D3D12_TEXTURE_COPY_LOCATION*, const D3D12_BOX*); + using OmSetRtFn = void(WINAPI*)(void*, UINT, const D3D12_CPU_DESCRIPTOR_HANDLE*, BOOL, + const D3D12_CPU_DESCRIPTOR_HANDLE*); + using ClearDsvFn = void(WINAPI*)(void*, D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_CLEAR_FLAGS, FLOAT, UINT8, + UINT, const D3D12_RECT*); + using ClearRtvFn = void(WINAPI*)(void*, D3D12_CPU_DESCRIPTOR_HANDLE, const FLOAT[4], UINT, + const D3D12_RECT*); + + const D3D12_COMMAND_QUEUE_DESC qd{}; + const IID iid_q = __uuidof(ID3D12CommandQueue); + const IID iid_l = __uuidof(ID3D12GraphicsCommandList); + ComPtr clear_q; + ComPtr clear_alloc; + ComPtr clear_list; + ComPtr clear_fence; + hr = reinterpret_cast(proxy_vtbl[48])( + device.Get(), &qd, &iid_q, reinterpret_cast(clear_q.GetAddressOf())); + HRESULT hra = device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, + IID_PPV_ARGS(clear_alloc.GetAddressOf())); + struct { + UINT Type; + UINT NodeMask; + } ld{D3D12_COMMAND_LIST_TYPE_DIRECT, 0}; + HRESULT hrl = SUCCEEDED(hra) ? reinterpret_cast(proxy_vtbl[73])( + device.Get(), &ld, clear_alloc.Get(), nullptr, &iid_l, + reinterpret_cast(clear_list.GetAddressOf())) + : hra; + HRESULT hrf = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(clear_fence.GetAddressOf())); + check(SUCCEEDED(hr) && SUCCEEDED(hra) && SUCCEEDED(hrl) && SUCCEEDED(hrf) && + rt::d3d12_xs::is_list_proxy(clear_list.Get()), + "console list proxy created for hooked RTV/DSV clear"); + + if (clear_q && clear_list && clear_fence) { + void** lv = *reinterpret_cast(clear_list.Get()); + const FLOAT rgba[4] = {1.0f, 0.0f, 0.5f, 1.0f}; + reinterpret_cast(lv[50])(clear_list.Get(), 1, &rtv_h, FALSE, &dsv_h); + reinterpret_cast(lv[52])(clear_list.Get(), rtv_h, rgba, 0, nullptr); + reinterpret_cast(lv[51])(clear_list.Get(), dsv_h, D3D12_CLEAR_FLAG_DEPTH, 0.25f, 0, 0, + nullptr); + + D3D12_RESOURCE_BARRIER b[2]{}; + b[0].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b[0].Transition = {rt_tex.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + D3D12_RESOURCE_STATE_RENDER_TARGET, D3D12_RESOURCE_STATE_COPY_SOURCE}; + b[1].Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + b[1].Transition = {ds_tex.Get(), D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES, + D3D12_RESOURCE_STATE_DEPTH_WRITE, D3D12_RESOURCE_STATE_COPY_SOURCE}; + reinterpret_cast(lv[26])(clear_list.Get(), 2, b); + + D3D12_TEXTURE_COPY_LOCATION dst_rt{}, src_rt{}, dst_ds{}, src_ds{}; + dst_rt.pResource = rb_buf.Get(); + dst_rt.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst_rt.PlacedFootprint = {0, {DXGI_FORMAT_R8G8B8A8_UNORM, 4, 4, 1, 256}}; + src_rt.pResource = rt_tex.Get(); + src_rt.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + dst_ds.pResource = rb_buf.Get(); + dst_ds.Type = D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT; + dst_ds.PlacedFootprint = {1536, {DXGI_FORMAT_R32_TYPELESS, 4, 4, 1, 256}}; + src_ds.pResource = ds_tex.Get(); + src_ds.Type = D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX; + reinterpret_cast(lv[16])(clear_list.Get(), &dst_rt, 0, 0, 0, &src_rt, nullptr); + reinterpret_cast(lv[16])(clear_list.Get(), &dst_ds, 0, 0, 0, &src_ds, nullptr); + + const HRESULT hr_close = reinterpret_cast(lv[9])(clear_list.Get()); + check(hr_close == S_OK, "console list Close succeeds after title-backed RTV/DSV clears"); + + ID3D12CommandList* lists[] = {clear_list.Get()}; + clear_q->ExecuteCommandLists(1, lists); + HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const bool done = ev && SUCCEEDED(clear_q->Signal(clear_fence.Get(), 1)) && + SUCCEEDED(clear_fence->SetEventOnCompletion(1, ev)) && + WaitForSingleObject(ev, 5000) == 0; + if (ev) CloseHandle(ev); + check(done, "console list clear commands complete on the GPU"); + + void* mapped = nullptr; + const D3D12_RANGE range{0, 4096}; + if (done && SUCCEEDED(rb_buf->Map(0, &range, &mapped)) && mapped) { + const auto* bytes = static_cast(mapped); + const bool rt_ok = bytes[0] == 255 && bytes[1] == 0 && (bytes[2] == 127 || bytes[2] == 128) && + bytes[3] == 255; + float depth_got = -1.0f; + std::memcpy(&depth_got, bytes + 1536, sizeof(depth_got)); + const bool ds_ok = std::fabs(depth_got - 0.25f) < 1e-6f; + check(rt_ok, "console slot 52 ClearRenderTargetView writes expected RGBA texel via hooked heap"); + check(ds_ok, "console slot 51 ClearDepthStencilView preserves FLOAT depth 0.25 via XMM3"); + const D3D12_RANGE empty{0, 0}; + rb_buf->Unmap(0, &empty); + } + } + } + rtv_heap.Reset(); + dsv_heap.Reset(); + rt::shims::remove_xmem_allocation_hooks(&dual_hooks); + } + } + // Hold a reference to the PC device so the final check can prove the proxy's Release balances its own. if (real) real->AddRef(); // Drop every device child before the proxy so the PC device is not released first. diff --git a/runtime/test/dstorage_test.cpp b/runtime/test/dstorage_test.cpp new file mode 100644 index 0000000000..1e8ea73183 --- /dev/null +++ b/runtime/test/dstorage_test.cpp @@ -0,0 +1,1260 @@ +// DirectStorage shim (runtime/shims/dstorage.cpp): DStorageGetFactory resolved through the shim registry under its +// three module names, driven the way a console title calls it, over synthetic files in %TEMP%. No game data, no GPU. +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include "dstorage_xs_abi.h" +#include "file_system.h" +#include "shims.h" + +using namespace dsx; +namespace fs = std::filesystem; + +namespace { + +int g_checks = 0; +int g_failures = 0; + +void check(bool ok, const char* what) { + ++g_checks; + if (!ok) { + ++g_failures; + std::printf("FAIL: %s\n", what); + } +} + +void check_hr(HRESULT got, HRESULT want, const char* what) { + ++g_checks; + if (got != want) { + ++g_failures; + std::printf("FAIL: %s (got 0x%08lx, want 0x%08lx)\n", what, static_cast(got), + static_cast(want)); + } +} + +// Interface ids a title might pass. The console's own ids are not public, so these are made up; the shim accepts any +// id per kind of object. +constexpr GUID kFactoryId = {0x0d5e0001, 0x1111, 0x4111, {0x81, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x01}}; +constexpr GUID kQueueId = {0x0d5e0002, 0x1111, 0x4111, {0x81, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x02}}; +constexpr GUID kFileId = {0x0d5e0003, 0x1111, 0x4111, {0x81, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x03}}; +constexpr GUID kStatusId = {0x0d5e0004, 0x1111, 0x4111, {0x81, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x04}}; +// IDStorageFactory of the PC API (dstorage.h): refused, its object has another shape. +constexpr GUID kPcFactoryId = {0x6924ea0c, 0xc3cd, 0x4826, {0xb1, 0x0a, 0xf6, 0x4f, 0x4e, 0xd9, 0x27, 0xc1}}; + +// A CPU fence with the PC ID3D12Fence vtable (the one the d3d12_xs fence proxies forward). It records the values it is +// signalled with and runs a check at each signal. +class TestFence final : public ID3D12Fence { +public: + std::function on_signal; + std::atomic value{0}; + std::atomic refs{1}; + + HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override { + if (!ppv) return E_POINTER; + *ppv = nullptr; + if (riid != __uuidof(IUnknown) && riid != __uuidof(ID3D12Fence)) return E_NOINTERFACE; + AddRef(); + *ppv = this; + return S_OK; + } + ULONG STDMETHODCALLTYPE AddRef() override { return ++refs; } + ULONG STDMETHODCALLTYPE Release() override { return --refs; } // lives on the test's stack + HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID, UINT*, void*) override { return E_NOTIMPL; } + HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID, UINT, const void*) override { return E_NOTIMPL; } + HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID, const IUnknown*) override { return E_NOTIMPL; } + HRESULT STDMETHODCALLTYPE SetName(LPCWSTR) override { return S_OK; } + HRESULT STDMETHODCALLTYPE GetDevice(REFIID, void** ppv) override { + if (ppv) *ppv = nullptr; + return E_NOTIMPL; + } + UINT64 STDMETHODCALLTYPE GetCompletedValue() override { return value.load(); } + HRESULT STDMETHODCALLTYPE SetEventOnCompletion(UINT64, HANDLE) override { return E_NOTIMPL; } + HRESULT STDMETHODCALLTYPE Signal(UINT64 v) override { + if (on_signal) on_signal(v); + value.store(v); + return S_OK; + } +}; + +std::vector pattern(size_t n, uint32_t seed) { + std::vector v(n); + uint32_t x = seed * 2654435761u + 1; + for (auto& b : v) { + x ^= x << 13; + x ^= x >> 17; + x ^= x << 5; + b = static_cast(x); + } + return v; +} + +void write_file(const fs::path& p, const std::vector& bytes) { + fs::create_directories(p.parent_path()); + FILE* f = nullptr; + if (_wfopen_s(&f, p.c_str(), L"wb") != 0 || !f) { + std::printf("FAIL: cannot write %ls\n", p.c_str()); + std::exit(1); + } + if (!bytes.empty()) std::fwrite(bytes.data(), 1, bytes.size(), f); + std::fclose(f); +} + +bool wait_complete(IDStorageStatusArrayX* s, UINT32 index, int ms = 10000) { + const auto end = std::chrono::steady_clock::now() + std::chrono::milliseconds(ms); + while (!s->IsComplete(index)) { + if (std::chrono::steady_clock::now() > end) return false; + Sleep(1); + } + return true; +} + +bool wait_until(const std::function& done, int ms = 10000) { + const auto end = std::chrono::steady_clock::now() + std::chrono::milliseconds(ms); + while (!done()) { + if (std::chrono::steady_clock::now() > end) return false; + Sleep(1); + } + return true; +} + +DSTORAGE_REQUEST file_request(IDStorageFileX* f, uint64_t offset, void* dst, uint32_t n, uint64_t tag = 0, + const char* name = nullptr) { + DSTORAGE_REQUEST r{}; + r.File = f; + r.FileOffset = offset; + r.Destination = dst; + r.DestinationSize = n; + r.SourceSize = n; + r.CancellationTag = tag; + r.Name = name; + return r; +} + +struct Env { + fs::path root, game, overlay; + IDStorageFactoryX2* factory = nullptr; + std::vector a_package, a_overlay, b, big; +}; + +IDStorageQueueX2* make_queue(Env& env, uint16_t capacity = 0x80, bool auto_submit = true, + DSTORAGE_REQUEST_SOURCE_TYPE type = DSTORAGE_REQUEST_SOURCE_FILE, + DSTORAGE_PRIORITY priority = DSTORAGE_PRIORITY_NORMAL, const char* name = "test queue") { + DSTORAGE_QUEUE_DESC1 d{}; + d.SourceType = type; + d.Capacity = capacity; + d.Priority = priority; + d.Name = name; + d.Options.AutoSubmitDisabled = auto_submit ? 0 : 1; + void* q = nullptr; + const HRESULT hr = env.factory->CreateQueue1(&d, kQueueId, &q); + check_hr(hr, S_OK, "CreateQueue1"); + return static_cast(q); +} + +IDStorageFileX* open(Env& env, const wchar_t* path) { + void* f = nullptr; + check_hr(env.factory->OpenFile(path, kFileId, &f), S_OK, "OpenFile"); + return static_cast(f); +} + +IDStorageStatusArrayX* make_status(Env& env, UINT32 capacity) { + void* s = nullptr; + check_hr(env.factory->CreateStatusArray(capacity, "test status", kStatusId, &s), S_OK, "CreateStatusArray"); + return static_cast(s); +} + +// ---- tests ---------------------------------------------------------------------------------------------------------- + +void test_layout_and_options() { + DSTORAGE_REQUEST_OPTIONS o{}; + o.ZlibDecompress = 1; + check(o.AsUINT64 == options::kZlib, "ZlibDecompress is bit 0"); + o.AsUINT64 = 0; + o.BcpackMode = DSTORAGE_BCPACK_MODE_BC7; + check(options::bcpack(o.AsUINT64) == 7 && o.AsUINT64 == (7ull << options::kBcpackShift), "BcpackMode is bits 1-4"); + o.AsUINT64 = 0; + o.SwizzleMode = DSTORAGE_SWIZZLE_MODE_4K_12K_4K_12K; + check(options::swizzle(o.AsUINT64) == 4 && o.AsUINT64 == (4ull << options::kSwizzleShift), + "SwizzleMode is bits 5-20"); + o.AsUINT64 = 0; + o.DestinationIsPhysicalPages = 1; + check(o.AsUINT64 == options::kDestinationPages, "DestinationIsPhysicalPages is bit 21"); + o.AsUINT64 = 0; + o.SourceType = DSTORAGE_REQUEST_SOURCE_MEMORY; + check(o.AsUINT64 == options::kSourceMemory, "SourceType is bit 22"); + o.AsUINT64 = 0; + o.SourceIsPhysicalPages = 1; + check(o.AsUINT64 == options::kSourcePages, "SourceIsPhysicalPages is bit 23"); + o.AsUINT64 = 0; + o.Reserved = 1; + check(o.AsUINT64 == (1ull << 24) && (o.AsUINT64 & options::kReservedMask), "Reserved starts at bit 24"); + DSTORAGE_QUEUE_OPTIONS q{}; + q.AutoSubmitDisabled = 1; + check(q.AsUINT64 == 1, "AutoSubmitDisabled is bit 0"); +} + +void test_registry(Env& env) { + const char* names[] = {"dstorage_xs.dll", "xcrdapi.dll", "dstorage.dll"}; + void* first = rt::shims::find("dstorage_xs.dll", "DStorageGetFactory"); + check(first != nullptr, "dstorage_xs.dll!DStorageGetFactory is registered"); + for (const char* n : names) { + check(rt::shims::find(n, "DStorageGetFactory") == first, "every module name serves the same function"); + check(rt::shims::owns_dll(n), "the shims own the module (LoadLibrary gets a pseudo-handle)"); + } + auto get = reinterpret_cast(first); + if (!get) std::exit(1); + + check_hr(get(kFactoryId, nullptr), E_POINTER, "DStorageGetFactory without ppv"); + void* pc = reinterpret_cast(1); + check_hr(get(kPcFactoryId, &pc), E_NOINTERFACE, "the PC IDStorageFactory id is refused"); + check(pc == nullptr, "a refused factory clears ppv"); + + void* f1 = nullptr; + void* f2 = nullptr; + check_hr(get(kFactoryId, &f1), S_OK, "DStorageGetFactory"); + check_hr(reinterpret_cast(rt::shims::find("xcrdapi.dll", "DStorageGetFactory"))( + __uuidof(IUnknown), &f2), + S_OK, "DStorageGetFactory(IUnknown) under xcrdapi.dll"); + check(f1 && f1 == f2, "the factory is one object"); + env.factory = static_cast(f1); + static_cast(f2)->Release(); + check(env.factory->Release() >= 1 && env.factory->Release() >= 1, "the factory's count does not drop below one"); + env.factory->AddRef(); + + void* again = nullptr; + check_hr(env.factory->QueryInterface(kFactoryId, &again), S_OK, "factory QueryInterface for its own id"); + if (again) static_cast(again)->Release(); +} + +void test_factory_checks(Env& env) { + // Before any queue or file exists. + check_hr(env.factory->SetStagingBufferSize(17u << 20), E_DSTORAGE_INVALID_STAGING_BUFFER_SIZE, "staging 17 MiB"); + check_hr(env.factory->SetStagingBufferSize(16u << 20), S_OK, "staging 16 MiB"); + check_hr(env.factory->SetStagingBufferSize(0), S_OK, "staging 0"); + check_hr(env.factory->SetCpuAffinity(0x3c), S_OK, "SetCpuAffinity"); + env.factory->SetDebugFlags(DSTORAGE_DEBUG_SHOW_ERRORS); + + auto create = [&](DSTORAGE_REQUEST_SOURCE_TYPE type, uint16_t cap, int prio, uint64_t opts = 0) { + DSTORAGE_QUEUE_DESC1 d{}; + d.SourceType = type; + d.Capacity = cap; + d.Priority = static_cast(prio); + d.Options.AsUINT64 = opts; + void* q = reinterpret_cast(1); + const HRESULT hr = env.factory->CreateQueue1(&d, kQueueId, &q); + if (SUCCEEDED(hr)) static_cast(q)->Release(); + else check(q == nullptr, "a failed CreateQueue1 clears ppv"); + return hr; + }; + check_hr(create(DSTORAGE_REQUEST_SOURCE_FILE, 0x7f, 0), E_DSTORAGE_INVALID_QUEUE_CAPACITY, "capacity 0x7f"); + check_hr(create(DSTORAGE_REQUEST_SOURCE_FILE, 0x2001, 0), E_DSTORAGE_INVALID_QUEUE_CAPACITY, "capacity 0x2001"); + check_hr(create(DSTORAGE_REQUEST_SOURCE_FILE, 0x80, 3), E_DSTORAGE_INVALID_QUEUE_PRIORITY, "priority 3"); + check_hr(create(DSTORAGE_REQUEST_SOURCE_FILE, 0x80, -2), E_DSTORAGE_INVALID_QUEUE_PRIORITY, "priority -2"); + check_hr(create(DSTORAGE_REQUEST_SOURCE_MEMORY, 0x80, 0), E_DSTORAGE_INVALID_MEMORY_QUEUE_PRIORITY, + "a memory queue must be realtime"); + check_hr(create(static_cast(2), 0x80, 0), E_DSTORAGE_INVALID_SOURCE_TYPE, + "source type 2"); + check_hr(create(DSTORAGE_REQUEST_SOURCE_FILE, 0x80, 0, 2), E_DSTORAGE_RESERVED_FIELDS, "queue option bit 1"); + check_hr(create(DSTORAGE_REQUEST_SOURCE_FILE, 0x2000, -1), S_OK, "capacity 0x2000, low priority"); + check_hr(create(DSTORAGE_REQUEST_SOURCE_MEMORY, 0x80, 2), S_OK, "a realtime memory queue"); + check_hr(env.factory->CreateQueue1(nullptr, kQueueId, nullptr), E_POINTER, "CreateQueue1 without ppv"); + void* q = nullptr; + check_hr(env.factory->CreateQueue(nullptr, kQueueId, &q), E_INVALIDARG, "CreateQueue without a desc"); + check_hr(env.factory->CreateQueue1(nullptr, kQueueId, &q), E_INVALIDARG, "CreateQueue1 without a desc"); + void* s = nullptr; + check_hr(env.factory->CreateStatusArray(0, nullptr, kStatusId, &s), E_INVALIDARG, "a status array of 0"); + + // The id policy: an id seen for a queue is not a factory id. + void* wrong = nullptr; + check_hr(env.factory->QueryInterface(kQueueId, &wrong), E_NOINTERFACE, "a queue id is not a factory id"); + check_hr(env.factory->CreateStatusArray(4, nullptr, kFactoryId, &s), E_NOINTERFACE, + "a factory id is not a status array id"); + + // CreateQueue (DSTORAGE_QUEUE_DESC) and Query reflect the desc. + DSTORAGE_QUEUE_DESC d{}; + d.SourceType = DSTORAGE_REQUEST_SOURCE_FILE; + d.Capacity = 0x100; + d.Priority = DSTORAGE_PRIORITY_HIGH; + d.Name = "named"; + check_hr(env.factory->CreateQueue(&d, kQueueId, &q), S_OK, "CreateQueue"); + auto* queue = static_cast(q); + DSTORAGE_QUEUE_INFO info{}; + queue->Query(&info); + check(info.Desc.Capacity == 0x100 && info.Desc.Priority == DSTORAGE_PRIORITY_HIGH && info.Desc.Name == d.Name && + info.Desc.SourceType == DSTORAGE_REQUEST_SOURCE_FILE, + "Query returns the creation desc"); + check(info.EmptySlotCount == 0xff, "an empty queue has capacity - 1 empty slots"); + check(info.RequestCountUntilAutoSubmit == 0x80, "auto-submit at half the capacity"); + DSTORAGE_QUEUE_INFO1 info1{}; + queue->Query1(&info1); + check(info1.Desc.Options.AsUINT64 == 0 && info1.EmptySlotCount == 0xff, "Query1"); + check_hr(env.factory->SetStagingBufferSize(32u << 20), E_DSTORAGE_STAGING_BUFFER_LOCKED, + "staging size is locked while a queue exists"); + void* qi = nullptr; + check_hr(queue->QueryInterface(kQueueId, &qi), S_OK, "queue QueryInterface"); + if (qi) static_cast(qi)->Release(); + check(queue->Release() == 0, "the last queue reference frees it"); + check_hr(env.factory->SetStagingBufferSize(32u << 20), S_OK, "staging size unlocked again"); +} + +void test_open_paths(Env& env) { + void* f = reinterpret_cast(1); + check_hr(env.factory->OpenFile(L"GAME:\\data\\missing.bin", kFileId, &f), HRESULT_FROM_WIN32(ERROR_FILE_NOT_FOUND), + "a missing GAME: file"); + check(f == nullptr, "a failed OpenFile clears ppv"); + check_hr(env.factory->OpenFile(L"GAME:\\..\\outside.bin", kFileId, &f), HRESULT_FROM_WIN32(ERROR_INVALID_NAME), + "a GAME: path that climbs out is refused"); + check_hr(env.factory->OpenFile(nullptr, kFileId, &f), E_INVALIDARG, "OpenFile without a path"); + check_hr(env.factory->OpenFile(L"GAME:\\data\\a.bin", kFileId, nullptr), E_POINTER, "OpenFile without ppv"); + + // The overlay copy wins over the package; a host path is passed through. + IDStorageFileX* a = open(env, L"GAME:\\data\\a.bin"); + IDStorageFileX* b = open(env, L"game:/data/b.bin"); + const std::wstring host = (env.game / L"data" / L"b.bin").wstring(); + IDStorageFileX* h = open(env, host.c_str()); + if (!a || !b || !h) std::exit(1); + + IDStorageQueueX2* q = make_queue(env); + IDStorageStatusArrayX* s = make_status(env, 4); + std::vector da(4096), db(1000), dh(1000); + DSTORAGE_REQUEST r = file_request(a, 0, da.data(), 4096); + q->EnqueueRequest(&r); + r = file_request(b, 500, db.data(), 1000); + q->EnqueueRequest(&r); + r = file_request(h, 500, dh.data(), 1000); + q->EnqueueRequest(&r); + q->EnqueueStatus(s, 0); + check_hr(s->GetHResult(0), E_PENDING, "a status entry is pending once enqueued"); + q->Submit(); + check(wait_complete(s, 0), "the reads complete"); + check_hr(s->GetHResult(0), S_OK, "the reads succeed"); + check(std::memcmp(da.data(), env.a_overlay.data(), 4096) == 0 && da != env.a_package, + "GAME: reads the overlay copy, not the package"); + + // GetHandle: a handle of its own (ReOpenFile), so its file position does not follow the shim's reads, which + // just ended at byte 4096 of this file. + HANDLE own = a->GetHandle(); + LARGE_INTEGER size{}; + check(own != INVALID_HANDLE_VALUE && GetFileSizeEx(own, &size) && size.QuadPart == 5000, + "GetHandle names the overlay copy (5000 bytes, the package has 4096)"); + std::vector via_handle(6000); + DWORD got = 0; + check(own != INVALID_HANDLE_VALUE && ReadFile(own, via_handle.data(), 6000, &got, nullptr) && got == 5000 && + std::memcmp(via_handle.data(), env.a_overlay.data(), 5000) == 0, + "a ReadFile through GetHandle's handle starts at byte 0 and reads the overlay copy"); + if (own != INVALID_HANDLE_VALUE) CloseHandle(own); + r = file_request(a, 100, da.data(), 50); + q->EnqueueRequest(&r); + q->EnqueueStatus(s, 1); + q->Submit(); + check(wait_complete(s, 1) && std::memcmp(da.data(), env.a_overlay.data() + 100, 50) == 0, + "the shim's reads do not follow a GetHandle handle's position either"); + check(std::memcmp(db.data(), env.b.data() + 500, 1000) == 0, + "a GAME: read at an offset (forward slashes, any case)"); + check(db == dh, "a host path reads the same file"); + a->Release(); + b->Release(); + h->Release(); + s->Release(); + q->Release(); +} + +void test_reads_and_errors(Env& env) { + IDStorageFileX* b = open(env, L"GAME:\\data\\b.bin"); // 10,000 bytes + IDStorageFileX* big = open(env, L"GAME:\\data\\big.bin"); + IDStorageQueueX2* q = make_queue(env, 0x80, false); + IDStorageStatusArrayX* s = make_status(env, 32); + HANDLE error_event = q->GetErrorEvent(); + check(error_event != nullptr, "GetErrorEvent returns a handle"); + + std::vector big_out(env.big.size()); + std::vector few(64, 0xAB); + std::vector zero(16, 0xCD); + struct Case { + DSTORAGE_REQUEST r; + HRESULT want; + const char* what; + }; + std::vector cases; + cases.push_back({file_request(big, 0, big_out.data(), static_cast(big_out.size())), S_OK, + "a 3 MiB read"}); + cases.push_back({file_request(b, 10000, zero.data(), 0), S_OK, "a zero-size read at the end of the file"}); + cases.push_back({file_request(b, 9990, few.data(), 11, 0x77, "past-the-end"), E_DSTORAGE_END_OF_FILE, + "a read one byte past the end"}); + cases.push_back({file_request(b, ~0ull - 4, few.data(), 8), E_DSTORAGE_END_OF_FILE, "an offset near 2^64"}); + cases.push_back({file_request(b, 0, few.data(), 8), S_OK, "a good read after failures"}); + { + DSTORAGE_REQUEST r = file_request(b, 0, few.data(), 8); + r.DestinationSize = 16; + cases.push_back({r, E_DSTORAGE_INVALID_DESTINATION_SIZE, "DestinationSize differs from SourceSize"}); + r = file_request(b, 0, few.data(), 8); + r.Options.ZlibDecompress = 1; + cases.push_back({r, E_DSTORAGE_INVALID_DESTINATION_SIZE, "zlib with DestinationSize equal to SourceSize"}); + r = file_request(b, 0, few.data(), 8); + r.Options.BcpackMode = DSTORAGE_BCPACK_MODE_BC1; + cases.push_back({r, E_NOTIMPL, "BCPack is not implemented yet"}); + r = file_request(b, 0, few.data(), 8); + r.Options.SwizzleMode = DSTORAGE_SWIZZLE_MODE_4K_4K_8K; + cases.push_back({r, E_NOTIMPL, "swizzle is not implemented yet"}); + r = file_request(b, 0, few.data(), 8); + r.Options.AsUINT64 = 8ull << options::kBcpackShift; + cases.push_back({r, E_DSTORAGE_INVALID_BCPACK_MODE, "BCPack mode 8"}); + r = file_request(b, 0, few.data(), 8); + r.Options.AsUINT64 = 5ull << options::kSwizzleShift; + cases.push_back({r, E_DSTORAGE_INVALID_SWIZZLE_MODE, "swizzle mode 5"}); + r = file_request(b, 0, few.data(), 8); + r.Options.Reserved = 1; + cases.push_back({r, E_DSTORAGE_RESERVED_FIELDS, "a reserved option bit"}); + r = file_request(b, 0, few.data(), 8); + r.Options.DestinationIsPhysicalPages = 1; + cases.push_back({r, E_NOTIMPL, "physical pages are not implemented yet"}); + r = file_request(b, 0, few.data(), 8); + r.IntermediateSize = 4; + cases.push_back({r, E_DSTORAGE_INVALID_INTERMEDIATE_SIZE, "IntermediateSize without zlib and BCPack"}); + r = file_request(b, 0, nullptr, 8); + cases.push_back({r, E_INVALIDARG, "a null destination"}); + r = file_request(nullptr, 0, few.data(), 8); + cases.push_back({r, E_INVALIDARG, "a null file"}); + r = file_request(reinterpret_cast(s), 0, few.data(), 8); + cases.push_back({r, E_DSTORAGE_INVALID_FILE_HANDLE, "a status array passed as a file"}); + r = file_request(b, 0, few.data(), 8); + r.Options.SourceType = DSTORAGE_REQUEST_SOURCE_MEMORY; + cases.push_back({r, E_DSTORAGE_INVALID_SOURCE_TYPE, "a memory request on a file queue"}); + } + cases.push_back({file_request(b, 0, nullptr, 0), E_INVALIDARG, "a zero-size read still needs a destination"}); + cases.push_back({file_request(nullptr, 0, zero.data(), 0), E_INVALIDARG, "a zero-size read still needs a file"}); + void* reserved = VirtualAlloc(nullptr, 1 << 16, MEM_RESERVE, PAGE_READWRITE); + cases.push_back({file_request(b, 0, reserved, 4096), E_DSTORAGE_ACCESS_VIOLATION, + "a destination the process cannot write"}); + check(cases.size() <= 31, "the cases fit the status array"); + + for (UINT32 i = 0; i < cases.size(); ++i) { + q->EnqueueRequest(&cases[i].r); + q->EnqueueStatus(s, i); + } + Sleep(30); + check(!s->IsComplete(0), "nothing runs before Submit when auto-submit is disabled"); + DSTORAGE_QUEUE_INFO1 info{}; + q->Query1(&info); + check(info.RequestCountUntilAutoSubmit == 0, "no auto-submit count when it is disabled"); + check(info.EmptySlotCount == 0x7f - 2 * cases.size(), "EmptySlotCount counts every entry"); + q->Submit(); + const UINT32 last = static_cast(cases.size() - 1); + check(wait_complete(s, last), "all cases complete"); + for (UINT32 i = 0; i < cases.size(); ++i) check_hr(s->GetHResult(i), cases[i].want, cases[i].what); + check(big_out == env.big, "the 3 MiB read has the file's bytes"); + check(zero == std::vector(16, 0xCD), "a zero-size read writes nothing"); + check(std::memcmp(few.data(), env.b.data(), 8) == 0, "the good read after failures"); + + check(WaitForSingleObject(error_event, 0) == WAIT_OBJECT_0, "the error event is set"); + DSTORAGE_ERROR_RECORD rec{}; + q->RetrieveErrorRecord(&rec); + size_t failures = 0; + for (const auto& c : cases) failures += FAILED(c.want) ? 1 : 0; + check(rec.FailureCount == failures, "FailureCount counts every failed request"); + check_hr(rec.FirstFailure.HResult, E_DSTORAGE_END_OF_FILE, "the first failure is recorded"); + check(rec.FirstFailure.CommandType == DSTORAGE_COMMAND_TYPE_REQUEST, "its command type is REQUEST"); + check(rec.FirstFailure.Request.FileOffset == 9990 && rec.FirstFailure.Request.SourceSize == 11 && + rec.FirstFailure.Request.CancellationTag == 0x77, + "the record has the request's offset, size and tag"); + check(std::wcscmp(rec.FirstFailure.Request.Filename, L"GAME:\\data\\b.bin") == 0, + "the record names the file as the title opened it"); + check(std::strcmp(rec.FirstFailure.Request.Name, "past-the-end") == 0, "the record has the request's name"); + check(WaitForSingleObject(error_event, 0) == WAIT_TIMEOUT, "RetrieveErrorRecord resets the event"); + q->RetrieveErrorRecord(&rec); + check(rec.FailureCount == 0 && rec.FirstFailure.CommandType == DSTORAGE_COMMAND_TYPE_NONE, + "a second RetrieveErrorRecord has nothing"); + + // Status and fence entries that fail. + q->EnqueueStatus(s, 1000); + q->EnqueueStatus(nullptr, 0); + q->EnqueueSignal(nullptr, 1); + q->EnqueueStatus(s, 31); + q->Submit(); + check(wait_complete(s, 31), "the entries after the failed notifications complete"); + check_hr(s->GetHResult(31), S_OK, "notification failures do not fail the next status entry"); + check_hr(s->GetHResult(1000), E_DSTORAGE_INDEX_BOUND, "GetHResult past the array"); + check(s->IsComplete(1000), "IsComplete past the array is not pending"); + q->RetrieveErrorRecord(&rec); + check(rec.FailureCount == 3 && rec.FirstFailure.CommandType == DSTORAGE_COMMAND_TYPE_STATUS && + rec.FirstFailure.HResult == E_DSTORAGE_INDEX_BOUND && rec.FirstFailure.Status.Index == 1000 && + rec.FirstFailure.Status.StatusArray == s, + "an index past the array is recorded as a STATUS failure"); + + VirtualFree(reserved, 0, MEM_RELEASE); + CloseHandle(error_event); + s->Release(); + q->Release(); + b->Release(); + big->Release(); +} + +void test_fence_order_and_events(Env& env) { + IDStorageFileX* b = open(env, L"GAME:\\data\\b.bin"); + IDStorageQueueX2* q = make_queue(env, 0x200); + TestFence fence; + constexpr int kReads = 100; + std::vector> outs(kReads, std::vector(100)); + std::atomic in_place{false}; + fence.on_signal = [&](UINT64 v) { + bool ok = v == 7; + for (int i = 0; i < kReads; ++i) ok = ok && std::memcmp(outs[i].data(), env.b.data() + i * 100, 100) == 0; + in_place.store(ok); + }; + for (int i = 0; i < kReads; ++i) { + DSTORAGE_REQUEST r = file_request(b, static_cast(i) * 100, outs[i].data(), 100); + q->EnqueueRequest(&r); + } + q->EnqueueSignal(&fence, 7); + check(fence.refs.load() == 2, "an enqueued signal holds a fence reference"); + HANDLE ev = CreateEventW(nullptr, FALSE, FALSE, nullptr); + q->EnqueueSetEvent(ev); + q->Submit(); + check(WaitForSingleObject(ev, 10000) == WAIT_OBJECT_0, "EnqueueSetEvent sets the event"); + check(fence.GetCompletedValue() == 7, "EnqueueSignal signals the fence with its value"); + check(in_place.load(), "the fence is signalled after every read before it is in place"); + check(wait_until([&] { return fence.refs.load() == 1; }), "the fence reference is released after the signal"); + + // A failed request before a fence: the fence still signals, and the status after the fence is clean. + IDStorageStatusArrayX* s = make_status(env, 2); + std::vector tmp(8); + DSTORAGE_REQUEST bad = file_request(b, 20000, tmp.data(), 8); + q->EnqueueRequest(&bad); + q->EnqueueSignal(&fence, 8); + q->EnqueueStatus(s, 0); + q->Submit(); + check(wait_complete(s, 0), "the status after a fence completes"); + check_hr(s->GetHResult(0), S_OK, "a failure before a fence is not reported by a status after it"); + check(fence.GetCompletedValue() == 8, "a fence after a failed read still signals"); + CloseHandle(ev); + s->Release(); + q->Release(); + b->Release(); +} + +void test_cancel(Env& env) { + IDStorageFileX* b = open(env, L"GAME:\\data\\b.bin"); + IDStorageQueueX2* q = make_queue(env, 0x80, false); + IDStorageStatusArrayX* s = make_status(env, 1); + std::vector> outs(6, std::vector(16, 0)); + const uint64_t tags[] = {0x11, 0x12, 0x21, 0x22, 0x31}; + for (int i = 0; i < 5; ++i) { + DSTORAGE_REQUEST r = file_request(b, 0, outs[i].data(), 16, tags[i]); + q->EnqueueRequest(&r); + } + q->CancelRequestsWithTag(0xF0, 0x10); // 0x11 and 0x12 + q->CancelRequestsWithTag(0xFF, 0x22); // 0x22 + DSTORAGE_REQUEST later = file_request(b, 0, outs[5].data(), 16, 0x11); // enqueued after: not cancelled + q->EnqueueRequest(&later); + q->EnqueueStatus(s, 0); + q->Submit(); + check(wait_complete(s, 0), "cancelled requests complete"); + check_hr(s->GetHResult(0), S_OK, "a cancelled request is a success"); + const std::vector zeros(16, 0); + check(outs[0] == zeros && outs[1] == zeros && outs[3] == zeros, "cancelled requests read nothing"); + check(std::memcmp(outs[2].data(), env.b.data(), 16) == 0 && std::memcmp(outs[4].data(), env.b.data(), 16) == 0, + "requests the mask did not match are read"); + check(std::memcmp(outs[5].data(), env.b.data(), 16) == 0, "a request enqueued after the cancel is read"); + s->Release(); + q->Release(); + b->Release(); +} + +void test_auto_submit_and_full_queue(Env& env) { + IDStorageFileX* b = open(env, L"GAME:\\data\\b.bin"); + IDStorageQueueX2* q = make_queue(env, 0x80, true); + std::vector> outs(64, std::vector(8, 0)); + for (int i = 0; i < 63; ++i) { + DSTORAGE_REQUEST r = file_request(b, i, outs[i].data(), 8); + q->EnqueueRequest(&r); + } + DSTORAGE_QUEUE_INFO info{}; + q->Query(&info); + check(info.RequestCountUntilAutoSubmit == 1, "one entry before the automatic submit"); + Sleep(20); + check(outs[0] == std::vector(8, 0), "below half the capacity nothing is submitted"); + DSTORAGE_REQUEST r = file_request(b, 63, outs[63].data(), 8); + q->EnqueueRequest(&r); // the 64th: half of 0x80 + check(wait_until([&] { return std::memcmp(outs[63].data(), env.b.data() + 63, 8) == 0; }), + "reaching half the capacity submits without Submit"); + bool all = true; + for (int i = 0; i < 64; ++i) all = all && std::memcmp(outs[i].data(), env.b.data() + i, 8) == 0; + check(all, "every auto-submitted read has its bytes"); + q->Release(); + + // Auto-submit disabled and full: an enqueue waits until another thread submits. + q = make_queue(env, 0x80, false); + IDStorageStatusArrayX* s = make_status(env, 1); + constexpr int kMany = 400; + std::vector sink(kMany * 4); + std::atomic done{false}; + std::thread producer([&] { + for (int i = 0; i < kMany; ++i) { + DSTORAGE_REQUEST rr = file_request(b, i, sink.data() + i * 4, 4); + q->EnqueueRequest(&rr); + } + q->EnqueueStatus(s, 0); + done.store(true); + }); + check(wait_until([&] { + DSTORAGE_QUEUE_INFO i{}; + q->Query(&i); + return i.EmptySlotCount == 0; + }), + "the queue fills to capacity - 1"); + Sleep(20); + check(!done.load(), "an enqueue into a full queue waits"); + while (!done.load()) { + q->Submit(); + Sleep(1); + } + producer.join(); + q->Submit(); + check(wait_complete(s, 0), "the producer's reads complete"); + bool same = true; + for (int i = 0; i < kMany; ++i) same = same && std::memcmp(sink.data() + i * 4, env.b.data() + i, 4) == 0; + check(same, "every read of the full-queue run has its bytes"); + s->Release(); + q->Release(); + b->Release(); +} + +void test_memory_queue(Env& env) { + IDStorageQueueX2* q = make_queue(env, 0x80, true, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME); + IDStorageStatusArrayX* s = make_status(env, 6); + std::vector buf = pattern(8192, 9); + std::vector want = buf; + std::memmove(want.data() + 1024, want.data(), 4096); + DSTORAGE_REQUEST r{}; + r.Options.SourceType = DSTORAGE_REQUEST_SOURCE_MEMORY; + r.Source = buf.data(); + r.Destination = buf.data() + 1024; + r.SourceSize = r.DestinationSize = 4096; + q->EnqueueRequest(&r); + q->EnqueueStatus(s, 0); + void* reserved = VirtualAlloc(nullptr, 1 << 16, MEM_RESERVE, PAGE_READWRITE); + DSTORAGE_REQUEST bad = r; + bad.Destination = reserved; + q->EnqueueRequest(&bad); + q->EnqueueStatus(s, 1); + DSTORAGE_REQUEST file_on_memory{}; // a file request on a memory queue + file_on_memory.Destination = buf.data(); + file_on_memory.SourceSize = file_on_memory.DestinationSize = 4; + q->EnqueueRequest(&file_on_memory); + q->EnqueueStatus(s, 2); + DSTORAGE_REQUEST huge = r; + huge.SourceSize = huge.DestinationSize = (1u << 29) + 1; // more than 1 GiB together + q->EnqueueRequest(&huge); + q->EnqueueStatus(s, 3); + // Buffers over 32 MiB need 64 KiB or 2 MiB pages (DSTORAGE_REQUEST). Reserved memory: a copy that is not refused + // faults and reports an access violation instead. + constexpr uint32_t k32MiB = 32u << 20; + void* wide = VirtualAlloc(nullptr, 2 * (k32MiB + 4096), MEM_RESERVE, PAGE_READWRITE); + check(wide != nullptr, "reserve 64 MiB for the over-limit copy"); + DSTORAGE_REQUEST over = r; + over.Source = wide; + over.Destination = static_cast(wide) + k32MiB + 4096; + over.SourceSize = over.DestinationSize = k32MiB + 1; + q->EnqueueRequest(&over); + q->EnqueueStatus(s, 4); + std::vector at_limit_source = pattern(k32MiB, 10), at_limit(k32MiB, 0); + DSTORAGE_REQUEST limit = r; + limit.Source = at_limit_source.data(); + limit.Destination = at_limit.data(); + limit.SourceSize = limit.DestinationSize = k32MiB; + q->EnqueueRequest(&limit); + q->EnqueueStatus(s, 5); + q->Submit(); + check(wait_complete(s, 5), "memory requests complete"); + check_hr(s->GetHResult(4), E_DSTORAGE_REQUEST_TOO_LARGE, "an unpaged buffer over 32 MiB is refused untouched"); + check_hr(s->GetHResult(5), S_OK, "a 32 MiB unpaged copy"); + check(at_limit == at_limit_source, "the 32 MiB copy moved every byte"); + VirtualFree(wide, 0, MEM_RELEASE); + check_hr(s->GetHResult(0), S_OK, "a memory-to-memory copy"); + check(buf == want, "an overlapping memory copy moves like memmove"); + check_hr(s->GetHResult(1), E_DSTORAGE_ACCESS_VIOLATION, "a memory copy to memory the process cannot write"); + check_hr(s->GetHResult(2), E_DSTORAGE_INVALID_SOURCE_TYPE, "a file request on a memory queue"); + check_hr(s->GetHResult(3), E_DSTORAGE_REQUEST_TOO_LARGE, "source plus destination over 1 GiB"); + VirtualFree(reserved, 0, MEM_RELEASE); + s->Release(); + q->Release(); +} + +void test_close_and_release(Env& env) { + IDStorageFileX* big = open(env, L"GAME:\\data\\big.bin"); + // Close with requests in flight: it returns after they all ran. + IDStorageQueueX2* q = make_queue(env, 0x100, true); + constexpr int kReads = 300; + constexpr uint32_t kChunk = 8192; + std::vector out(kReads * kChunk); + for (int i = 0; i < kReads; ++i) { + DSTORAGE_REQUEST r = file_request(big, static_cast(i) * kChunk, out.data() + i * kChunk, kChunk); + q->EnqueueRequest(&r); + } + q->Close(); + check(std::memcmp(out.data(), env.big.data(), out.size()) == 0, "Close returns after every enqueued read ran"); + IDStorageStatusArrayX* s = make_status(env, 1); + std::vector tmp(8, 0); + DSTORAGE_REQUEST r = file_request(big, 0, tmp.data(), 8); + q->EnqueueRequest(&r); + q->EnqueueStatus(s, 0); + q->Submit(); + q->Close(); // a second Close is harmless + Sleep(20); + check(tmp == std::vector(8, 0), "a request enqueued after Close is not run"); + DSTORAGE_ERROR_RECORD rec{}; + q->RetrieveErrorRecord(&rec); + check(rec.FailureCount == 2 && rec.FirstFailure.HResult == E_DSTORAGE_QUEUE_CLOSED, + "enqueues after Close are recorded"); + check(q->Release() == 0, "a closed queue is freed by its last Release"); + + // The last Release with requests in flight finishes them first. + q = make_queue(env, 0x100, true); + std::fill(out.begin(), out.end(), uint8_t{0}); + for (int i = 0; i < kReads; ++i) { + DSTORAGE_REQUEST rr = file_request(big, static_cast(i) * kChunk, out.data() + i * kChunk, kChunk); + q->EnqueueRequest(&rr); + } + q->Submit(); + big->Release(); // the requests hold the file + check(q->Release() == 0, "the last Release of a busy queue"); + check(std::memcmp(out.data(), env.big.data(), out.size()) == 0, "the last Release ran the reads in flight"); + + // IDStorageFileX::Close: submitted reads finish, a later one fails with E_DSTORAGE_FILE_NOT_OPEN. + IDStorageFileX* b = open(env, L"GAME:\\data\\b.bin"); + q = make_queue(env, 0x80, false); + IDStorageStatusArrayX* s2 = make_status(env, 3); + std::vector first(100, 0), second(100, 0); + DSTORAGE_REQUEST r1 = file_request(b, 0, first.data(), 100); + q->EnqueueRequest(&r1); + q->EnqueueStatus(s2, 0); + q->Submit(); + DSTORAGE_REQUEST r2 = file_request(b, 0, second.data(), 100); + q->EnqueueRequest(&r2); // not submitted yet + b->Close(); + check(std::memcmp(first.data(), env.b.data(), 100) == 0, + "IDStorageFileX::Close waits for the file's submitted reads"); + check(wait_complete(s2, 0) && s2->GetHResult(0) == S_OK, "the submitted read succeeded"); + check(b->GetHandle() == INVALID_HANDLE_VALUE, "GetHandle on a closed file"); + q->EnqueueStatus(s2, 1); + DSTORAGE_REQUEST r3 = file_request(b, 0, second.data(), 0); + q->EnqueueRequest(&r3); + q->EnqueueStatus(s2, 2); + q->Submit(); + check(wait_complete(s2, 2), "the reads after the close complete"); + check_hr(s2->GetHResult(1), E_DSTORAGE_FILE_NOT_OPEN, "a read of a closed file"); + check_hr(s2->GetHResult(2), E_DSTORAGE_FILE_NOT_OPEN, "a zero-size read of a closed file"); + check(second == std::vector(100, 0), "a read of a closed file writes nothing"); + q->Release(); + b->Release(); + s->Release(); + s2->Release(); +} + +void test_threads(Env& env) { + IDStorageFileX* big = open(env, L"GAME:\\data\\big.bin"); + IDStorageQueueX2* q = make_queue(env, 0x80, true); + constexpr int kThreads = 4, kPer = 250; + constexpr uint32_t kChunk = 512; + std::vector> outs(kThreads, std::vector(kPer * kChunk)); + std::vector arrays; + for (int t = 0; t < kThreads; ++t) arrays.push_back(make_status(env, 1)); + std::vector threads; + for (int t = 0; t < kThreads; ++t) + threads.emplace_back([&, t] { + for (int i = 0; i < kPer; ++i) { + const uint64_t offset = (static_cast(t) * kPer + i) * kChunk % (env.big.size() - kChunk); + DSTORAGE_REQUEST r = file_request(big, offset, outs[t].data() + i * kChunk, kChunk, t); + q->EnqueueRequest(&r); + } + q->EnqueueStatus(arrays[t], 0); + q->Submit(); + }); + for (auto& th : threads) th.join(); + bool ok = true; + for (int t = 0; t < kThreads; ++t) { + ok = ok && wait_complete(arrays[t], 0) && arrays[t]->GetHResult(0) == S_OK; + for (int i = 0; i < kPer; ++i) { + const uint64_t offset = (static_cast(t) * kPer + i) * kChunk % (env.big.size() - kChunk); + ok = ok && std::memcmp(outs[t].data() + i * kChunk, env.big.data() + offset, kChunk) == 0; + } + } + check(ok, "four threads enqueueing at once all read their bytes"); + for (auto* a : arrays) a->Release(); + q->Release(); + big->Release(); +} + +void test_iid_policy_events_and_cancel(Env& env) { + // Well-known system interfaces and made-up ids: QueryInterface refuses all of them. + const GUID kRandom = {0x5eed0001, 0x2222, 0x4222, {0x82, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x01}}; + const GUID kIMarshal = {0x00000003, 0x0000, 0x0000, {0xc0, 0, 0, 0, 0, 0, 0, 0x46}}; + const GUID kIAgileObject = {0x94ea2b94, 0xe9cc, 0x49e0, {0xc0, 0xff, 0xee, 0x64, 0xca, 0x8f, 0x5b, 0x90}}; + const GUID kINoMarshal = {0xecc8691b, 0xc1db, 0x4dc0, {0x85, 0x5e, 0x65, 0xf6, 0xc5, 0x51, 0xaf, 0x49}}; + const GUID kIClientSecurity = {0x0000013d, 0x0000, 0x0000, {0xc0, 0, 0, 0, 0, 0, 0, 0x46}}; + const GUID kPcStatusArrayId = {0x82397587, 0x7cd5, 0x453b, {0xa0, 0x2e, 0x31, 0x37, 0x9b, 0xd6, 0x46, 0x56}}; + const GUID kPcQueueId = {0xcfdbd83f, 0x9e06, 0x4fda, {0x8e, 0xa5, 0x69, 0x04, 0x21, 0x37, 0xf4, 0x9b}}; + const GUID kQueueId2 = {0x0d5e0012, 0x1111, 0x4111, {0x81, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x12}}; + const GUID refused[] = {kRandom, kIMarshal, kIAgileObject, kINoMarshal, kIClientSecurity}; + + IDStorageQueueX2* q = make_queue(env, 0x80, false); + IDStorageFileX* b = open(env, L"GAME:\\data\\b.bin"); + IDStorageStatusArrayX* s = make_status(env, 8); + IUnknown* objects[] = {env.factory, q, b, s}; + for (IUnknown* o : objects) + for (const GUID& g : refused) { + void* out = reinterpret_cast(1); + check_hr(o->QueryInterface(g, &out), E_NOINTERFACE, "QueryInterface refuses an unknown or system id"); + check(out == nullptr, "a refused QueryInterface clears ppv"); + } + void* out = nullptr; + check_hr(q->QueryInterface(kFileId, &out), E_NOINTERFACE, "a queue refuses a file id"); + check_hr(b->QueryInterface(kQueueId, &out), E_NOINTERFACE, "a file refuses a queue id"); + check_hr(s->QueryInterface(kFactoryId, &out), E_NOINTERFACE, "a status array refuses a factory id"); + check_hr(q->QueryInterface(__uuidof(IUnknown), &out), S_OK, "QueryInterface(IUnknown)"); + if (out) static_cast(out)->Release(); + + // Creating calls learn a new id but refuse system ones. + auto get = reinterpret_cast(rt::shims::find("dstorage_xs.dll", "DStorageGetFactory")); + check_hr(get(kIMarshal, &out), E_NOINTERFACE, "DStorageGetFactory refuses IMarshal"); + check_hr(get(kIAgileObject, &out), E_NOINTERFACE, "DStorageGetFactory refuses IAgileObject"); + DSTORAGE_QUEUE_DESC1 d{}; + d.Capacity = 0x80; + check_hr(env.factory->CreateQueue1(&d, kINoMarshal, &out), E_NOINTERFACE, "CreateQueue1 refuses INoMarshal"); + check_hr(env.factory->OpenFile(L"GAME:\\data\\b.bin", kIClientSecurity, &out), E_NOINTERFACE, + "OpenFile refuses IClientSecurity"); + check_hr(env.factory->CreateQueue1(&d, kPcQueueId, &out), E_NOINTERFACE, "CreateQueue1 refuses the PC queue id"); + check_hr(env.factory->CreateQueue1(&d, kPcStatusArrayId, &out), E_NOINTERFACE, + "the status array id is not a queue id"); + check_hr(env.factory->CreateQueue1(&d, kQueueId2, &out), S_OK, "a creating call learns a new queue id"); + if (out) static_cast(out)->Release(); + check_hr(q->QueryInterface(kQueueId2, &out), S_OK, "QueryInterface accepts an id a queue was created with"); + if (out) static_cast(out)->Release(); + + // The PC IDStorageStatusArray id has the console interface's shape and is accepted. + check_hr(env.factory->CreateStatusArray(2, nullptr, kPcStatusArrayId, &out), S_OK, + "CreateStatusArray accepts the PC IDStorageStatusArray id"); + if (out) static_cast(out)->Release(); + check_hr(s->QueryInterface(kPcStatusArrayId, &out), S_OK, "a status array answers the PC IDStorageStatusArray id"); + if (out) static_cast(out)->Release(); + + // EnqueueSetEvent duplicates the handle: closing the title's handle, even with its value reused, changes nothing. + HANDLE first = CreateEventW(nullptr, TRUE, FALSE, nullptr); + q->EnqueueSetEvent(first); + CloseHandle(first); + HANDLE second = CreateEventW(nullptr, TRUE, FALSE, nullptr); // may get the same handle value + q->EnqueueSetEvent(reinterpret_cast(static_cast(0x7ffffff0))); // not a handle + q->EnqueueSetEvent(nullptr); + q->EnqueueStatus(s, 0); + q->Submit(); + check(wait_complete(s, 0), "the event entries complete"); + check(WaitForSingleObject(second, 0) == WAIT_TIMEOUT, "a closed event's reused handle value is not set"); + DSTORAGE_ERROR_RECORD rec{}; + q->RetrieveErrorRecord(&rec); + check(rec.FailureCount == 2 && rec.FirstFailure.CommandType == kCommandTypeEvent && + FAILED(rec.FirstFailure.HResult), + "an invalid and a null event handle are recorded as EVENT failures; the closed one is not"); + CloseHandle(second); + + // A cancelled request that also had an enqueue error is still a success, and not counted as a failure. + std::vector tmp(8, 0); + DSTORAGE_REQUEST foreign = file_request(reinterpret_cast(s), 0, tmp.data(), 8, 0x99); + q->EnqueueRequest(&foreign); + DSTORAGE_REQUEST null_file = file_request(nullptr, 0, tmp.data(), 8, 0x99); + q->EnqueueRequest(&null_file); + q->CancelRequestsWithTag(~0ull, 0x99); + q->EnqueueStatus(s, 1); + q->Submit(); + check(wait_complete(s, 1), "cancelled bad requests complete"); + check_hr(s->GetHResult(1), S_OK, "a cancelled request with an enqueue error is a success"); + q->RetrieveErrorRecord(&rec); + check(rec.FailureCount == 0, "a cancelled request is not counted as a failure"); + + s->Release(); + b->Release(); + q->Release(); +} + +// Holds the queue's worker inside a copy: the copy's source is a guard page, and this handler waits on the first +// touch until the test releases it. The guard is gone after that fault, so the copy then goes on. +struct GuardHold { + uint8_t* page = nullptr; + HANDLE entered = nullptr; + HANDLE release = nullptr; +}; +GuardHold* g_hold = nullptr; + +LONG CALLBACK hold_on_guard(EXCEPTION_POINTERS* x) { + const EXCEPTION_RECORD* e = x->ExceptionRecord; + if (!g_hold || e->ExceptionCode != STATUS_GUARD_PAGE_VIOLATION || e->NumberParameters < 2) + return EXCEPTION_CONTINUE_SEARCH; + const auto* address = reinterpret_cast(e->ExceptionInformation[1]); + if (address < g_hold->page || address >= g_hold->page + 4096) return EXCEPTION_CONTINUE_SEARCH; + SetEvent(g_hold->entered); + WaitForSingleObject(g_hold->release, 10000); + return EXCEPTION_CONTINUE_EXECUTION; +} + +// DSTORAGE_PRIORITY_STATS: TotalRequestCount and the byte totals count submitted requests; PendingRequestCount counts +// requests whose processing has started and not completed. A memory queue (realtime, the only priority it may have): +// the counts are compared with the ones before. +void test_stats_timing(Env& env) { + auto realtime = [&] { + DSTORAGE_STATS st{}; + env.factory->GetStats(&st); + return st.RealtimePriorityStats; + }; + const DSTORAGE_PRIORITY_STATS before = realtime(); + IDStorageQueueX2* q = make_queue(env, 0x80, false, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME); + if (!q) return; + IDStorageStatusArrayX* s = make_status(env, 1); + GuardHold hold; + hold.page = static_cast(VirtualAlloc(nullptr, 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + hold.entered = CreateEventW(nullptr, TRUE, FALSE, nullptr); + hold.release = CreateEventW(nullptr, TRUE, FALSE, nullptr); + if (!hold.page || !hold.entered || !hold.release) { + check(false, "allocate the guard page and its events"); + return; + } + std::memset(hold.page, 0x5A, 4096); + DWORD old = 0; + VirtualProtect(hold.page, 4096, PAGE_READWRITE | PAGE_GUARD, &old); + std::vector out(4096, 0); + DSTORAGE_REQUEST r{}; + r.Options.SourceType = DSTORAGE_REQUEST_SOURCE_MEMORY; + r.Source = hold.page; + r.Destination = out.data(); + r.SourceSize = r.DestinationSize = 4096; + q->EnqueueRequest(&r); + q->EnqueueStatus(s, 0); + DSTORAGE_PRIORITY_STATS p = realtime(); + check(p.TotalRequestCount == before.TotalRequestCount && + p.TotalRequestSourceByteCount == before.TotalRequestSourceByteCount && + p.TotalRequestDestinationByteCount == before.TotalRequestDestinationByteCount, + "an enqueued request is not counted before Submit"); + + g_hold = &hold; + void* handler = AddVectoredExceptionHandler(1, hold_on_guard); + q->Submit(); + check(WaitForSingleObject(hold.entered, 10000) == WAIT_OBJECT_0, "the copy reached the guard page"); + p = realtime(); + check(p.TotalRequestCount == before.TotalRequestCount + 1 && + p.TotalRequestSourceByteCount == before.TotalRequestSourceByteCount + 4096 && + p.TotalRequestDestinationByteCount == before.TotalRequestDestinationByteCount + 4096, + "a submitted request is counted, with its sizes"); + check(p.PendingRequestCount == before.PendingRequestCount + 1, "a running request is pending"); + SetEvent(hold.release); + check(wait_complete(s, 0), "the held copy completes"); + check_hr(s->GetHResult(0), S_OK, "the held copy succeeds"); + check(out == std::vector(4096, 0x5A), "the held copy moved every byte"); + check(realtime().PendingRequestCount == before.PendingRequestCount, "a completed request is no longer pending"); + RemoveVectoredExceptionHandler(handler); + g_hold = nullptr; + CloseHandle(hold.entered); + CloseHandle(hold.release); + VirtualFree(hold.page, 0, MEM_RELEASE); + s->Release(); + q->Release(); +} + +void test_stats(Env& env) { + DSTORAGE_STATS st{}; + env.factory->GetStats(&st); + check(st.CurrentOpenFileCount == 0, "every file was released"); + check(st.NormalPriorityStats.CurrentQueueCount == 0 && st.RealtimePriorityStats.CurrentQueueCount == 0, + "every queue was released"); + check(st.NormalPriorityStats.TotalRequestCount > 1000 && st.NormalPriorityStats.TotalFenceCount >= 2 && + st.RealtimePriorityStats.TotalRequestCount == 7, + "requests and fences are counted per priority"); + check(st.CumulativeOpenFileCount >= 10 && st.MaxOpenFileCount >= 3, "files are counted"); + check(st.ErrorCount > 10, "errors are counted"); +} + + +// ---- zlib requests ------------------------------------------------------------------------------------------------ +// +// Synthetic streams only. The two Huffman streams were made with Python's zlib (3.14, zlib-ng 1.3.1 API) from the +// text zlib_text() builds, which in Python is +// text = lambda n: b"".join(b"line %04d: a zlib request for the queue, value %d\n" % (i, (i * i) % 97) +// for i in range(n)) +// kZlibDynamic = zlib.compress(text(64), 9): one final dynamic-Huffman block (BTYPE 2), 345 bytes for 3,191. +// kZlibFixed = zlib.compress(text(4), 1): one final fixed-Huffman block (BTYPE 1), 77 bytes for 196. +// Streams with stored blocks (BTYPE 0) are built here by stored_stream(); for a single block that is byte for byte +// what zlib.compress(data, 0) gives. +constexpr uint8_t kZlibDynamic[] = { + 0x78, 0xda, 0x95, 0xd4, 0x4d, 0x4e, 0x03, 0x31, 0x0c, 0x05, 0xe0, 0x3d, 0xa7, 0xc8, 0x01, 0x58, 0x4c, 0xfc, + 0x97, 0x84, 0xdb, 0x14, 0x69, 0x10, 0x95, 0x46, 0x20, 0x4a, 0xcb, 0x82, 0xd3, 0x33, 0x0b, 0xf4, 0xbc, 0x7d, + 0xee, 0x6e, 0xa4, 0x3e, 0x25, 0xce, 0x67, 0xfb, 0xb8, 0x7e, 0xec, 0x6d, 0x3b, 0x7f, 0x2f, 0xed, 0xd2, 0x7e, + 0x8f, 0xeb, 0x6b, 0xbb, 0xed, 0x5f, 0x8f, 0xfd, 0xfb, 0xde, 0xde, 0x3e, 0x6f, 0xed, 0xfe, 0xbe, 0xb7, 0xf3, + 0xeb, 0xb1, 0x3f, 0xb7, 0x9f, 0xcb, 0xf1, 0x38, 0xff, 0xf9, 0x74, 0xfc, 0x07, 0x3a, 0x17, 0xe8, 0x08, 0x08, + 0x17, 0x30, 0x04, 0x94, 0x0b, 0x2c, 0x04, 0x8c, 0xbc, 0x52, 0x20, 0xe1, 0x5c, 0x42, 0x1c, 0x89, 0xe0, 0x12, + 0x9a, 0x67, 0x0c, 0xb2, 0xee, 0xac, 0x63, 0x72, 0x89, 0xc8, 0xa7, 0x5a, 0x5c, 0x62, 0x42, 0xa3, 0x93, 0xde, + 0x8a, 0x00, 0xe9, 0x2d, 0xb8, 0x54, 0x67, 0xc1, 0x07, 0x12, 0xa4, 0xf8, 0x10, 0x24, 0x48, 0xf2, 0x0c, 0x90, + 0xe2, 0x9a, 0x2f, 0x45, 0x8a, 0x47, 0x9e, 0x41, 0x8a, 0x2f, 0x74, 0x55, 0x27, 0xc5, 0x35, 0x39, 0x48, 0xf1, + 0x81, 0x81, 0x15, 0x52, 0xbc, 0xa3, 0x0e, 0x21, 0xc9, 0x1d, 0xb7, 0x12, 0x92, 0x7c, 0x61, 0x3a, 0x84, 0x24, + 0x37, 0xb4, 0x95, 0x90, 0xe4, 0x0b, 0x82, 0x42, 0x9a, 0x5b, 0xd6, 0x41, 0x9a, 0xaf, 0xbc, 0x15, 0x69, 0xee, + 0xe9, 0x41, 0x9a, 0x4f, 0x04, 0x48, 0xf2, 0x40, 0x5b, 0x29, 0x49, 0x2e, 0x98, 0x40, 0x25, 0xc9, 0x27, 0x6e, + 0xa5, 0x24, 0xb9, 0xe3, 0xa9, 0x94, 0x24, 0x17, 0x34, 0xa2, 0x92, 0xe4, 0x13, 0x2b, 0x54, 0x49, 0xf2, 0x40, + 0x93, 0x28, 0xbb, 0xd8, 0xf3, 0x75, 0x49, 0xf2, 0x9e, 0x67, 0xb0, 0xe4, 0x18, 0x0f, 0x65, 0xcd, 0x91, 0x30, + 0xd2, 0xdc, 0x20, 0x68, 0xa4, 0xb9, 0xc2, 0xc3, 0x48, 0xf3, 0x9e, 0x67, 0x90, 0xe6, 0x59, 0x06, 0x3b, 0xe5, + 0x98, 0x59, 0x23, 0xc9, 0x27, 0x00, 0x8d, 0x24, 0x1f, 0x68, 0x2b, 0x23, 0xc9, 0x47, 0x9e, 0x41, 0x92, 0x8f, + 0xac, 0x63, 0x55, 0x13, 0xbe, 0x55, 0x6f, 0xe5, 0xbd, 0x5a, 0xb9, 0x4b, 0xf5, 0x75, 0x5d, 0xab, 0x82, 0x6e, + 0xc5, 0x26, 0x71, 0xaf, 0xf6, 0xa1, 0x47, 0xb5, 0xd7, 0x7d, 0x54, 0xe7, 0xc9, 0x67, 0x75, 0x66, 0x7d, 0x55, + 0xf7, 0x42, 0x6c, 0xd5, 0xdd, 0x13, 0xbd, 0xba, 0xdf, 0x42, 0xaa, 0x3b, 0x34, 0x94, 0xde, 0xd3, 0x7f, 0x97, + 0x8b, 0x11, 0xce, +}; +constexpr uint8_t kZlibFixed[] = { + 0x78, 0x01, 0xcb, 0xc9, 0xcc, 0x4b, 0x55, 0x30, 0x30, 0x30, 0x30, 0xb0, 0x52, 0x48, 0x54, 0xa8, 0xca, 0xc9, + 0x4c, 0x52, 0x28, 0x4a, 0x2d, 0x2c, 0x4d, 0x2d, 0x2e, 0x51, 0x48, 0xcb, 0x2f, 0x52, 0x28, 0xc9, 0x48, 0x55, + 0x28, 0x2c, 0x4d, 0x2d, 0x4d, 0xd5, 0x51, 0x28, 0x4b, 0xcc, 0x29, 0x4d, 0x55, 0x30, 0xe0, 0x82, 0x69, 0x30, + 0x24, 0x4e, 0x83, 0x21, 0x5c, 0x83, 0x11, 0x71, 0x1a, 0x4c, 0xe0, 0x1a, 0x8c, 0x89, 0xd3, 0x60, 0xc9, 0x05, + 0x00, 0xb0, 0x6e, 0x40, 0x49, +}; + +std::vector zlib_text(int lines) { + std::string t; + char line[96]; + for (int i = 0; i < lines; ++i) { + std::snprintf(line, sizeof line, "line %04d: a zlib request for the queue, value %d\n", i, (i * i) % 97); + t += line; + } + return {t.begin(), t.end()}; +} + +uint32_t adler32(const std::vector& data) { + uint32_t a = 1, b = 0; + for (const uint8_t x : data) { + a = (a + x) % 65521; + b = (b + a) % 65521; + } + return (b << 16) | a; +} + +// A zlib stream (header 78 01) whose first block stores `stored` (a final block when there is no tail), followed by +// the deflate blocks of the zlib stream `tail` (its header and Adler-32 dropped: a stored block ends on a byte +// boundary, so they follow as they are) and the Adler-32 of the whole result, `stored` then `tail_plain`. +std::vector stored_stream(const std::vector& stored, const uint8_t* tail = nullptr, + size_t tail_size = 0, const std::vector& tail_plain = {}) { + const auto n = static_cast(stored.size()); + std::vector z = {0x78, 0x01, static_cast(tail ? 0 : 1), static_cast(n), + static_cast(n >> 8), static_cast(~n), static_cast(~n >> 8)}; + z.insert(z.end(), stored.begin(), stored.end()); + if (tail) z.insert(z.end(), tail + 2, tail + tail_size - 4); + std::vector plain = stored; + plain.insert(plain.end(), tail_plain.begin(), tail_plain.end()); + const uint32_t check = adler32(plain); + for (int shift = 24; shift >= 0; shift -= 8) z.push_back(static_cast(check >> shift)); + return z; +} + +void test_zlib(Env& env) { + const std::vector dynamic(std::begin(kZlibDynamic), std::end(kZlibDynamic)); + const std::vector fixed(std::begin(kZlibFixed), std::end(kZlibFixed)); + const std::vector dynamic_plain = zlib_text(64), fixed_plain = zlib_text(4); + // The first block header is the low three bits after the two header bytes: BFINAL, then BTYPE (RFC 1951 3.2.3). + check(dynamic.size() == 345 && (dynamic[2] & 7) == (1 | 2 << 1), "kZlibDynamic is one final dynamic block"); + check(fixed.size() == 77 && (fixed[2] & 7) == (1 | 1 << 1), "kZlibFixed is one final fixed-Huffman block"); + check(dynamic_plain.size() == 3191 && fixed_plain.size() == 196, "the synthetic text has the generator's sizes"); + + const std::vector stored_part = pattern(300, 21); + const std::vector mixed = stored_stream(stored_part, kZlibDynamic, sizeof kZlibDynamic, dynamic_plain); + std::vector mixed_plain = stored_part; + mixed_plain.insert(mixed_plain.end(), dynamic_plain.begin(), dynamic_plain.end()); + check((mixed[2] & 7) == 0, "the mixed stream starts with a stored block that is not the last"); + const std::vector stored_only = stored_stream(pattern(40, 22)); // larger than what it inflates to + std::vector bad_method = dynamic, bad_type = fixed, bad_check = dynamic, preset = dynamic; + bad_method[0] ^= 1; // CM 9: not deflate + preset[1] = 0xbb; // 78 BB: a valid check value with FDICT set (a preset dictionary) + bad_type[2] |= 0x06; // BTYPE 3, reserved + bad_check.back() ^= 1; // the Adler-32 + + // One file, every stream at a 16-byte aligned offset and followed by 32 zero bytes. + std::vector file; + auto put = [&](const std::vector& z) { + const uint64_t at = file.size(); + file.insert(file.end(), z.begin(), z.end()); + file.resize((file.size() + 32 + 15) & ~size_t{15}, 0); + return at; + }; + const uint64_t at_dynamic = put(dynamic), at_fixed = put(fixed), at_mixed = put(mixed), + at_stored = put(stored_only), at_method = put(bad_method), at_preset = put(preset), + at_type = put(bad_type), at_check = put(bad_check); + write_file(env.game / L"data" / L"zlib.bin", file); + + struct Case { + uint64_t offset; + uint32_t source, destination; + HRESULT want; + const std::vector* result; // the expected bytes; null when the destination stays untouched + const char* what; + uint64_t options = 0; + uint32_t intermediate = 0; + }; + const auto z = static_cast(dynamic.size()); + std::vector cases = { + {at_dynamic, z, 3191, S_OK, &dynamic_plain, "a zlib file request: dynamic Huffman"}, + {at_fixed, 77, 196, S_OK, &fixed_plain, "a zlib file request: fixed Huffman"}, + {at_mixed, static_cast(mixed.size()), 3491, S_OK, &mixed_plain, + "a zlib file request: a stored block, then dynamic Huffman"}, + {at_dynamic, z + 16, 3191, S_OK, &dynamic_plain, "bytes after the Adler-32 are not read"}, + {at_stored, static_cast(stored_only.size()), 40, E_DSTORAGE_INVALID_DESTINATION_SIZE, nullptr, + "a zlib DestinationSize not larger than SourceSize"}, + {at_method, z, 3191, E_DSTORAGE_ZLIB_BAD_HEADER, nullptr, "a header that is not deflate"}, + {at_preset, z, 3191, E_DSTORAGE_ZLIB_BAD_HEADER, nullptr, "a header with a preset dictionary"}, + {at_type, 77, 196, E_DSTORAGE_ZLIB_BAD_DATA, nullptr, "a reserved block type"}, + {at_dynamic, z - 10, 3191, E_DSTORAGE_ZLIB_BAD_DATA, nullptr, "a truncated stream"}, + {at_check, z, 3191, E_DSTORAGE_ZLIB_PARITY_FAIL, nullptr, "an Adler-32 mismatch"}, + {at_dynamic, z, 3192, E_DSTORAGE_DECOMPRESSION_ERROR, nullptr, "a stream shorter than DestinationSize"}, + {at_dynamic, z, 3190, E_DSTORAGE_DECOMPRESSION_ERROR, nullptr, "a stream longer than DestinationSize"}, + {at_dynamic + 8, z, 3191, E_DSTORAGE_INVALID_FILE_OFFSET, nullptr, "a zlib offset not 16-byte aligned"}, + {file.size() - 16, 32, 64, E_DSTORAGE_END_OF_FILE, nullptr, "a zlib source past the end of the file"}, + {at_dynamic, z, 3191, E_DSTORAGE_INVALID_INTERMEDIATE_SIZE, nullptr, "zlib with an IntermediateSize", 0, + 16}, + {at_dynamic, z, 3191, E_NOTIMPL, nullptr, "zlib and BCPack is not implemented yet", + static_cast(DSTORAGE_BCPACK_MODE_BC1) << options::kBcpackShift, 64}, + {at_dynamic, z, 3191, E_NOTIMPL, nullptr, "zlib and swizzle is not implemented yet", + static_cast(DSTORAGE_SWIZZLE_MODE_4K_4K_8K) << options::kSwizzleShift}, + }; + + DSTORAGE_STATS before{}; + env.factory->GetStats(&before); + IDStorageFileX* f = open(env, L"GAME:\\data\\zlib.bin"); + IDStorageQueueX2* q = make_queue(env, 0x80, false); + IDStorageStatusArrayX* s = make_status(env, static_cast(cases.size())); + constexpr size_t kSlack = 64; // past DestinationSize: must stay untouched + std::vector> out(cases.size()); + for (size_t i = 0; i < cases.size(); ++i) { + const Case& c = cases[i]; + out[i].assign(c.destination + kSlack, 0xEE); + DSTORAGE_REQUEST r = file_request(f, c.offset, out[i].data(), c.destination); + r.SourceSize = c.source; + r.IntermediateSize = c.intermediate; + r.Options.AsUINT64 = options::kZlib | c.options; + q->EnqueueRequest(&r); + q->EnqueueStatus(s, static_cast(i)); + } + q->Submit(); + check(wait_complete(s, static_cast(cases.size() - 1)), "the zlib file requests complete"); + for (size_t i = 0; i < cases.size(); ++i) { + const Case& c = cases[i]; + check_hr(s->GetHResult(static_cast(i)), c.want, c.what); + const std::vector untouched(c.destination, 0xEE); + const bool head = c.result ? std::equal(c.result->begin(), c.result->end(), out[i].begin()) + : std::equal(untouched.begin(), untouched.end(), out[i].begin()); + const bool tail = std::all_of(out[i].end() - kSlack, out[i].end(), [](uint8_t x) { return x == 0xEE; }); + check(head && tail, c.result ? "the inflated bytes are the synthetic text, and nothing past them" + : "a failed zlib request leaves the destination untouched"); + } + s->Release(); + q->Release(); + f->Release(); + + // A memory source: the same stream, one inflated in place (the compressed bytes sit at the end of their own + // destination, as a title may load them), a corrupt one, a source and a destination the process cannot touch. + IDStorageQueueX2* mq = make_queue(env, 0x80, true, DSTORAGE_REQUEST_SOURCE_MEMORY, DSTORAGE_PRIORITY_REALTIME); + IDStorageStatusArrayX* ms = make_status(env, 5); + void* reserved = VirtualAlloc(nullptr, 1 << 16, MEM_RESERVE, PAGE_READWRITE); + std::vector m0(3191, 0xEE), in_place(3191, 0xEE), m2(3191, 0xEE), m3(3191, 0xEE); + std::copy(dynamic.begin(), dynamic.end(), in_place.end() - dynamic.size()); + DSTORAGE_REQUEST r{}; + r.Options.AsUINT64 = options::kZlib | options::kSourceMemory; + r.SourceSize = z; + r.DestinationSize = 3191; + r.Source = dynamic.data(); + r.Destination = m0.data(); + mq->EnqueueRequest(&r); + mq->EnqueueStatus(ms, 0); + r.Source = in_place.data() + in_place.size() - dynamic.size(); + r.Destination = in_place.data(); + mq->EnqueueRequest(&r); + mq->EnqueueStatus(ms, 1); + r.Source = bad_check.data(); + r.Destination = m2.data(); + mq->EnqueueRequest(&r); + mq->EnqueueStatus(ms, 2); + r.Source = reserved; + r.Destination = m3.data(); + mq->EnqueueRequest(&r); + mq->EnqueueStatus(ms, 3); + r.Source = dynamic.data(); + r.Destination = reserved; + mq->EnqueueRequest(&r); + mq->EnqueueStatus(ms, 4); + mq->Submit(); + check(wait_complete(ms, 4), "the zlib memory requests complete"); + check_hr(ms->GetHResult(0), S_OK, "a zlib memory request"); + check(m0 == dynamic_plain, "the zlib memory request inflates to the synthetic text"); + check_hr(ms->GetHResult(1), S_OK, "a zlib memory request whose source lies inside its destination"); + check(in_place == dynamic_plain, "inflating in place gives the synthetic text"); + check_hr(ms->GetHResult(2), E_DSTORAGE_ZLIB_PARITY_FAIL, "a zlib memory request with an Adler-32 mismatch"); + check(m2 == std::vector(3191, 0xEE), "the failed zlib memory request leaves the destination untouched"); + check_hr(ms->GetHResult(3), E_DSTORAGE_ACCESS_VIOLATION, "a zlib source the process cannot read"); + check_hr(ms->GetHResult(4), E_DSTORAGE_ACCESS_VIOLATION, "a zlib destination the process cannot write"); + VirtualFree(reserved, 0, MEM_RELEASE); + ms->Release(); + mq->Release(); + + // Counted when the inflate starts: the 11 file requests (4 good, 7 bad streams) and 4 memory requests (all but the + // unreadable source) whose checks passed and whose source was read. Failed: the 7 bad file streams and the memory + // one with an Adler-32 mismatch; a destination the process cannot write is not a decompression error. + DSTORAGE_STATS after{}; + env.factory->GetStats(&after); + check(after.TotalDecompressionRequestCount - before.TotalDecompressionRequestCount == 15, + "TotalDecompressionRequestCount counts the zlib requests that reached the inflate"); + check(after.DecompressionErrors - before.DecompressionErrors == 8, "DecompressionErrors counts the bad streams"); + check(after.PendingDecompressionRequestCount == 0, "no decompression is pending afterwards"); +} + +} // namespace + +int main() { + wchar_t temp[MAX_PATH]; + GetTempPathW(MAX_PATH, temp); + Env env; + env.root = fs::path(temp) / (L"leonida_dstorage_test_" + std::to_wstring(GetCurrentProcessId())); + env.game = env.root / L"game"; + env.overlay = env.root / L"overlay"; + std::error_code ec; + fs::remove_all(env.root, ec); + env.a_package = pattern(4096, 1); + env.a_overlay = pattern(5000, 2); // another size and other bytes than the package's copy + env.b = pattern(10000, 3); + env.big = pattern(3u << 20, 4); + write_file(env.game / L"data" / L"a.bin", env.a_package); + write_file(env.overlay / L"data" / L"a.bin", env.a_overlay); + write_file(env.game / L"data" / L"b.bin", env.b); + write_file(env.game / L"data" / L"big.bin", env.big); + rt::fs::configure(env.game, env.overlay); + + test_layout_and_options(); + test_registry(env); + test_factory_checks(env); + test_open_paths(env); + test_reads_and_errors(env); + test_fence_order_and_events(env); + test_cancel(env); + test_auto_submit_and_full_queue(env); + test_memory_queue(env); + test_close_and_release(env); + test_threads(env); + test_iid_policy_events_and_cancel(env); + test_stats_timing(env); + test_stats(env); + test_zlib(env); // after test_stats, whose request totals it would change + + fs::remove_all(env.root, ec); + std::printf("dstorage: %d checks, %d failures\n", g_checks, g_failures); + return g_failures ? 1 : 0; +} diff --git a/runtime/test/fixtures/tiny_gdk_load.cpp b/runtime/test/fixtures/tiny_gdk_load.cpp index 7a6ca6cc6c..2d1cf6af34 100644 --- a/runtime/test/fixtures/tiny_gdk_load.cpp +++ b/runtime/test/fixtures/tiny_gdk_load.cpp @@ -1,7 +1,7 @@ // A mapped program that reaches the GDK runtime the way xgameruntime.lib's thunks do: it has no import of -// xgameruntime.dll, loads it with LoadLibraryW and looks the five run-time entry points up with GetProcAddress -// (measured in the package's libHttpClient.GDK.dll and XCurl.dll, docs/runtime_imports.md "Run-time loaded -// modules"). Run under `gta6rt --run`, its own kernel32 imports are bound by the loader, so LoadLibraryW and +// xgameruntime.dll, loads it with LoadLibraryW and looks the five run-time entry points and XErrorReport up with +// GetProcAddress (measured in the package's libHttpClient.GDK.dll and XCurl.dll, docs/runtime_imports.md "Run-time +// loaded modules"). Run under `gta6rt --run`, its own kernel32 imports are bound by the loader, so LoadLibraryW and // GetProcAddress must reach runtime/shims/library_loader.cpp and the offline xgameruntime shim. Run on its own, // LoadLibraryW goes to Windows and either fails or loads the PC's Gaming Services runtime, and this never prints // PASS. Ordinary test code; no game data. @@ -23,6 +23,9 @@ struct Options { // InitializeApiImplEx2's fourth argument (xodus-gaming/ using InitEx2 = HRESULT(WINAPI*)(ULONG, ULONG, char, const Options*); using Query = HRESULT(WINAPI*)(const GUID*, REFIID, void**); using Uninit = HRESULT(WINAPI*)(); +using Report = HRESULT(WINAPI*)(HRESULT, const char*); + +HRESULT g_reported = S_OK; // what the XErrorSetCallback callback last received int fail(const char* stage, unsigned long value) { std::printf("tiny_gdk_load: FAIL %s (0x%08lx)\n", stage, value); @@ -66,8 +69,9 @@ int main() { if (GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_UNCHANGED_REFCOUNT, L"xgameruntime.dll", &host_view) && host_view == runtime) return fail("xgameruntime.dll came from the host loader, not the shims", 0); + // XErrorReport too: the thunks look it up with the five entry points and refuse the runtime when it is missing. const char* names[] = {"InitializeApiImpl", "InitializeApiImplEx", "InitializeApiImplEx2", "UninitializeApiImpl", - "QueryApiImpl"}; + "QueryApiImpl", "XErrorReport"}; for (const char* name : names) if (!GetProcAddress(runtime, name)) return fail(name, GetLastError()); SetLastError(0); @@ -98,6 +102,27 @@ int main() { reinterpret_cast(vtable[17])(obj, queue); reinterpret_cast(vtable[2])(obj); + // The XErrorReport export and XErrorImpl's slot 3 are one function: a report through the export reaches the + // callback XErrorImpl's slot 4 (XErrorSetCallback) set. + const GUID error_class = {0x8ca467f7, 0x22e8, 0x4096, {0x84, 0x56, 0xbb, 0x8a, 0xa1, 0x3f, 0x79, 0xd8}}; + void* error = nullptr; + hr = query(&error_class, error_class, &error); + if (hr != S_OK || !error) return fail("QueryApiImpl hands out XErrorImpl", static_cast(hr)); + void* const* error_vtable = *static_cast(error); + using Callback = bool(CALLBACK*)(HRESULT, const char*, void*); + using SetCallback = void(STDMETHODCALLTYPE*)(void*, Callback, void*); + const Callback on_error = [](HRESULT reported, const char*, void*) { + g_reported = reported; + return true; + }; + reinterpret_cast(error_vtable[4])(error, on_error, nullptr); + auto report = reinterpret_cast(GetProcAddress(runtime, "XErrorReport")); + hr = report(E_FAIL, "tiny_gdk_load"); + reinterpret_cast(error_vtable[4])(error, nullptr, nullptr); + reinterpret_cast(error_vtable[2])(error); + if (hr != S_OK || g_reported != E_FAIL) + return fail("the XErrorReport export reaches the XErrorSetCallback callback", static_cast(hr)); + // A class not served (an id no runtime class has, made up for this test) is refused, with the out pointer // cleared. const GUID unserved = {0x4c454f4e, 0x4944, 0x4100, {0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x01}}; diff --git a/runtime/test/fixtures/tiny_thread_hook.cpp b/runtime/test/fixtures/tiny_thread_hook.cpp new file mode 100644 index 0000000000..0187d3265e --- /dev/null +++ b/runtime/test/fixtures/tiny_thread_hook.cpp @@ -0,0 +1,16 @@ +// Tiny fixture DLL for loader_tls_index0_test (threads): calls a function of the test EXE from its +// DllMain(DLL_THREAD_ATTACH). Loaded before the runtime's TLS helper, so on a new thread this runs before the helper's +// DLL_THREAD_ATTACH, the window in which only the OS has set up the thread's TLS. Ordinary test code, no game data. +#include + +namespace { +using Hook = void(__cdecl*)(); +Hook volatile g_hook = nullptr; +} // namespace + +extern "C" __declspec(dllexport) void __cdecl tiny_thread_hook_set(Hook hook) { g_hook = hook; } + +BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID) { + if (reason == DLL_THREAD_ATTACH && g_hook) g_hook(); + return TRUE; +} diff --git a/runtime/test/fixtures/tiny_tls_clones.cpp b/runtime/test/fixtures/tiny_tls_clones.cpp new file mode 100644 index 0000000000..c3b957c4d0 --- /dev/null +++ b/runtime/test/fixtures/tiny_tls_clones.cpp @@ -0,0 +1,13 @@ +// Tiny fixture EXE for check_tls_clone_cleanup.cmake. It is ordinary test code, not game content. +// +// It imports two DLLs with static TLS, tiny_tls.dll and tiny_tls_cb_only.dll, and has TLS of its own. Mapped by gta6rt +// the EXE takes module TLS index 0, one DLL takes the primary helper's index and the other needs a helper clone +// (leonida_tls_host__1.dll in %TEMP%), whose file gta6rt has to delete when it exits. +extern "C" __declspec(dllimport) int __cdecl tiny_tls_get(); +extern "C" __declspec(dllimport) int __cdecl tiny_tls_cb_attach_count(); + +namespace { +thread_local int t_value = 3; +} + +int main() { return tiny_tls_get() == 7 && tiny_tls_cb_attach_count() >= 0 && t_value == 3 ? 0 : 1; } diff --git a/runtime/test/fixtures/tiny_tls_ga.cpp b/runtime/test/fixtures/tiny_tls_ga.cpp new file mode 100644 index 0000000000..a44d0e97d4 --- /dev/null +++ b/runtime/test/fixtures/tiny_tls_ga.cpp @@ -0,0 +1,35 @@ +// Tiny fixture EXE for module TLS index 0. It is ordinary test code, not game content. +// +// Built /GA (CMakeLists.txt), the EXE-only option that lets the compiler assume the image is the process executable +// and so has module TLS index 0: every thread_local access below reads TEB->ThreadLocalStoragePointer[0] directly +// (mov rax, gs:[58h]; mov rax, [rax]) and never loads _tls_index. Mapped with any other index, the getter reads +// whatever block sits in slot 0. loader_tls_index0_test calls the exports on threads of its own; under +// `gta6rt --run` (run_tiny_tls_ga) main() checks the value on the game thread and on a second thread and returns 0 +// only when both read the template value 42. +#include +#include + +extern "C" unsigned long _tls_index; + +namespace { +thread_local int t_value = 42; +} + +extern "C" __declspec(dllexport) __declspec(noinline) int __cdecl tiny_ga_get() { return t_value; } +extern "C" __declspec(dllexport) __declspec(noinline) void __cdecl tiny_ga_set(int value) { t_value = value; } +// Where this thread's t_value is, so the test can find its offset inside the slot-0 block. +extern "C" __declspec(dllexport) __declspec(noinline) int* __cdecl tiny_ga_address() { return &t_value; } +extern "C" __declspec(dllexport) unsigned long __cdecl tiny_ga_tls_index() { return _tls_index; } +extern "C" __declspec(dllexport) unsigned long* __cdecl tiny_ga_tls_index_address() { return &_tls_index; } + +int main() { + const int on_main = tiny_ga_get(); + tiny_ga_set(7); + int on_thread = -1; + std::thread worker([&] { on_thread = tiny_ga_get(); }); + worker.join(); + const bool ok = on_main == 42 && on_thread == 42 && tiny_ga_get() == 7; + std::printf("tiny_tls_ga: tls_index=%lu main=%d thread=%d %s\n", _tls_index, on_main, on_thread, + ok ? "OK" : "FAILED"); + return ok ? 0 : 1; +} diff --git a/runtime/test/frame_pacer_test.cpp b/runtime/test/frame_pacer_test.cpp index 8d089acdaf..e86c6f560a 100644 --- a/runtime/test/frame_pacer_test.cpp +++ b/runtime/test/frame_pacer_test.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include using namespace leonida; @@ -86,6 +87,24 @@ int main() { EXPECT(pacer.tokens_issued() == 2); } + { + ManualFrameClock clock; + auto tokens = std::make_shared(); + FramePacer pacer(clock, tokens); + EXPECT(pacer.token_source() == tokens); + const std::uint64_t outside = tokens->issue(); + EXPECT(outside == 1 && pacer.tokens_issued() == 1); + EXPECT(pacer.check_present_token(outside) == pacer_hr::ok); + EXPECT(pacer.check_present_token(outside + 1) == pacer_hr::invalid_arg); + EXPECT(setup(pacer, 1)); + clock.advance_us(period); + std::uint64_t token = 0; + EXPECT(pacer.wait_frame_event(frame_event_origin, 0, 0, &token) == pacer_hr::ok && token == outside + 1); + EXPECT(tokens->issue() == outside + 2); + EXPECT(pacer.check_present_token(outside + 2) == pacer_hr::ok); + EXPECT(pacer.check_present_token(outside + 3) == pacer_hr::invalid_arg); + } + // An offset delays the event inside the period: origin n comes at n * period + offset. { ManualFrameClock clock; diff --git a/runtime/test/gameinput_test.cpp b/runtime/test/gameinput_test.cpp index 4c48a35e61..93c48518b2 100644 --- a/runtime/test/gameinput_test.cpp +++ b/runtime/test/gameinput_test.cpp @@ -1708,6 +1708,8 @@ int main() { check(create != nullptr, "gameinput.dll!GameInputCreate is registered"); check(rt::shims::find("xgameruntime.dll", "GameInputCreate") == reinterpret_cast(create), "xgameruntime.dll!GameInputCreate is the same function"); + check(rt::shims::find("gameinput.dll", "#1") == reinterpret_cast(create), + "gameinput.dll!#1 (the ordinal import) is the same function"); if (!create) return 1; IGameInput* input = nullptr; diff --git a/runtime/test/gfx10_descriptors_test.cpp b/runtime/test/gfx10_descriptors_test.cpp index 523180ee70..e727053813 100644 --- a/runtime/test/gfx10_descriptors_test.cpp +++ b/runtime/test/gfx10_descriptors_test.cpp @@ -167,7 +167,15 @@ int main() { for (const FormatRow& row : format_table) { CHECK(row.gfx10 >= previous && row.gfx10 > 0 && row.gfx10 < 512); CHECK(seen.insert(row.vulkan).second); - CHECK(valid_swizzle(row.channels) && row.channels[0] != select_zero && row.channels[0] != select_one); + // Every format reads its first channel as red, but A8 (an A8_UNORM render target), whose only channel is alpha. +#ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME + const bool alpha_only = row.vulkan == VK_FORMAT_A8_UNORM_KHR; +#else + const bool alpha_only = false; +#endif + CHECK(valid_swizzle(row.channels) && + (alpha_only ? row.channels == channels_a + : row.channels[0] != select_zero && row.channels[0] != select_one)); CHECK(format_from_vulkan(row.vulkan) == row.gfx10); CHECK(format_swizzle(row.vulkan) == row.channels); if (row.gfx10 != previous) { @@ -176,6 +184,17 @@ int main() { } previous = row.gfx10; } +#ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME + // An A8 render target shares 8_UNORM with R8: an A8 image keeps its own view format, and the T#'s X is its alpha. + CHECK(format_from_vulkan(VK_FORMAT_A8_UNORM_KHR) == 1 && vulkan_format(1) == VK_FORMAT_R8_UNORM); + CHECK(vulkan_view_format(VK_FORMAT_A8_UNORM_KHR, 1) == VK_FORMAT_A8_UNORM_KHR); + { + const VkComponentMapping a8 = vulkan_swizzle(Swizzle{select_zero, select_zero, select_zero, select_x}, + VK_FORMAT_A8_UNORM_KHR); + CHECK(a8.r == VK_COMPONENT_SWIZZLE_ZERO && a8.g == VK_COMPONENT_SWIZZLE_ZERO && + a8.b == VK_COMPONENT_SWIZZLE_ZERO && a8.a == VK_COMPONENT_SWIZZLE_A); + } +#endif CHECK(vulkan_format(56) == VK_FORMAT_R8G8B8A8_UNORM && vulkan_format(130) == VK_FORMAT_R8G8B8A8_SRGB); CHECK(vulkan_format(22) == VK_FORMAT_R32_SFLOAT && format_from_vulkan(VK_FORMAT_D32_SFLOAT) == 22); CHECK(vulkan_format(7) == VK_FORMAT_R16_UNORM && format_from_vulkan(VK_FORMAT_D16_UNORM) == 7); diff --git a/runtime/test/glsl/cs_user_data.comp b/runtime/test/glsl/cs_user_data.comp index b285c0f3f9..07b4b7e4d4 100644 --- a/runtime/test/glsl/cs_user_data.comp +++ b/runtime/test/glsl/cs_user_data.comp @@ -37,8 +37,21 @@ Words at(uvec2 va) { void main() { const uint i = gl_GlobalInvocationID.x; - Words table = at(uvec2(pc.s[8], 0u)); Words result = at(uvec2(pc.s[6], pc.s[7])); + if (pc.s[5] == 0xFFFFFFFEu) { + // Root view read mode (d3d12_title_va_test): read through the root UAV itself, 256 bytes past its base, and + // write at the base, so the root view's address is both read and written. + result.w[i] = result.w[64u + i] + pc.s[4]; + return; + } + Words table = at(uvec2(pc.s[8], 0u)); + if (pc.s[5] == 0xFFFFFFFDu) { + // Root view read to a table pointer (d3d12_title_va_test): read through the root view, 256 bytes past its + // base, and write where the table entry's raw 64-bit VA points. + Words target = at(uvec2(table.w[0], table.w[1])); + target.w[i] = result.w[64u + i] + pc.s[4]; + return; + } if (pc.s[5] == 0u) { // CBV V# mode: table holds a 16-byte GFX10 raw buffer descriptor written by CreateConstantBufferView. const uint num_records = table.w[2]; diff --git a/runtime/test/loader_tls_index0_test.cpp b/runtime/test/loader_tls_index0_test.cpp new file mode 100644 index 0000000000..cb3aec418e --- /dev/null +++ b/runtime/test/loader_tls_index0_test.cpp @@ -0,0 +1,580 @@ +// End-to-end checks for module TLS index 0 and a mapped executable, against locally built fixtures. +// +// Windows gives the process executable module TLS index 0, and MSVC code built with /GA relies on it: it reads +// TEB->ThreadLocalStoragePointer[0] without loading _tls_index. tiny_tls_ga.exe is such an image (a thread_local int +// with the initializer 42, built /GA). rt::reserve_tls_index0 moves this test EXE's own TLS (index 0 at start) to the +// home clone's index, whose TLS template is a copy of this EXE's; the Loader then gives the executable index 0. +// +// loader_tls_index0_test runs +// Reserve at start, then: this EXE keeps its TLS on the reserving thread and every later thread finds a fresh +// copy at the home index; the executable reads 42 on the loading thread, a thread older than load() and new +// threads; its getter is /GA code; tiny_tls.dll keeps a helper index alongside; two runs in a row both get +// index 0, and a second executable mapped meanwhile gets a helper index. +// loader_tls_index0_test threads +// Threads are created all through the reservation, one waits suspended with no TLS array yet, and +// tiny_thread_hook.dll (loaded before the helper) runs this EXE's code in each new thread's DLL_THREAD_ATTACH, +// before the helper's: all of them find this EXE's TLS at the home index, the hook included. +// loader_tls_index0_test noreserve +// Without the reservation the executable maps with a helper index and this EXE keeps index 0. +// +// gta6rt_tls_host.dll must sit next to this EXE, as for loader_tls_test. No game files are needed. Every function +// that runs before the reservation, or calls it, touches no thread_local data: MSVC may keep a TLS slot address in a +// frame across calls, and the reservation has to come before any such frame exists (pe_loader.h). +#include +#include + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "pe_loader.h" + +extern "C" unsigned long _tls_index; // this EXE's module TLS index, read through its TLS directory's AddressOfIndex + +namespace { + +namespace fs = std::filesystem; + +int g_checks = 0; +int g_failures = 0; + +void check(bool condition, const char* what) { + ++g_checks; + std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); + if (!condition) ++g_failures; +} + +// This EXE's own TLS: thread_local reads here go through _tls_index, so they follow the move. +thread_local int t_host = 1234; +thread_local bool t_hooked = false; +thread_local int t_seen_in_hook = -1; + +__declspec(noinline) int host_value() { return t_host; } +__declspec(noinline) void set_host_value(int value) { t_host = value; } +__declspec(noinline) const uint8_t* host_address() { return reinterpret_cast(&t_host); } + +void** module_tls_slots() { return reinterpret_cast(__readgsqword(0x58)); } + +const IMAGE_TLS_DIRECTORY64* tls_of(HMODULE module) { + auto* base = reinterpret_cast(module); + auto* nt = + reinterpret_cast(base + reinterpret_cast(base)->e_lfanew); + const auto& dir = nt->OptionalHeader.DataDirectory[IMAGE_DIRECTORY_ENTRY_TLS]; + return dir.Size ? reinterpret_cast(base + dir.VirtualAddress) : nullptr; +} + +// This EXE's TLS template: what every fresh block of it starts as. +struct Template { + const uint8_t* data = nullptr; + size_t size = 0; +}; +Template own_template() { + const auto* tls = tls_of(GetModuleHandleW(nullptr)); + return {reinterpret_cast(tls->StartAddressOfRawData), + static_cast(tls->EndAddressOfRawData - tls->StartAddressOfRawData + tls->SizeOfZeroFill)}; +} + +// The home clone, found by its file name, and the index the OS gave it (from its own AddressOfIndex, not from +// this EXE's _tls_index). +HMODULE home_module() { + const std::wstring name = L"leonida_tls_host_" + std::to_wstring(GetCurrentProcessId()) + L"_home.dll"; + return GetModuleHandleW(name.c_str()); +} +DWORD home_index() { + const HMODULE home = home_module(); + return home ? *reinterpret_cast(tls_of(home)->AddressOfIndex) : rt::kNoTlsIndex; +} + +bool inside(const uint8_t* p, const void* block, size_t size) { + const auto* b = static_cast(block); + return b && p >= b && p + sizeof(int) <= b + size; +} + +// Where this thread finds t_host: in the block at the home index, and not in the one at slot 0. +bool host_tls_at_home() { + const DWORD home = home_index(); + const size_t size = own_template().size; + return home != rt::kNoTlsIndex && inside(host_address(), module_tls_slots()[home], size) && + !inside(host_address(), module_tls_slots()[0], size); +} + +template +Fn find_export(const rt::Module& m, const char* name) { + const auto it = m.exports.find(name); + if (it == m.exports.end()) throw std::runtime_error(std::string("missing export ") + name); + return reinterpret_cast(it->second); +} + +struct Ga { + int(__cdecl* get)(); + void(__cdecl* set)(int); + int*(__cdecl* address)(); + unsigned long(__cdecl* tls_index)(); + unsigned long*(__cdecl* tls_index_address)(); +}; + +Ga ga_exports(const rt::Module& m) { + return {find_export(m, "tiny_ga_get"), find_export(m, "tiny_ga_set"), + find_export(m, "tiny_ga_address"), + find_export(m, "tiny_ga_tls_index"), + find_export(m, "tiny_ga_tls_index_address")}; +} + +// Code bytes of a function, past an incremental-linking jump stub (Debug builds export the stub). +const uint8_t* code_of(const void* fn) { + const auto* p = static_cast(fn); + if (p[0] == 0xE9) { + int32_t rel; + std::memcpy(&rel, p + 1, 4); + p += 5 + rel; + } + return p; +} + +// The /GA shape of the getter, up to its ret: a load of gs:[58h] (65 REX.W 8B /r with a SIB of disp32 0x58) and no +// rip-relative operand that lands on the image's _tls_index. +bool reads_slot0_without_index(const void* fn, const void* tls_index) { + const uint8_t* p = code_of(fn); + bool gs58 = false, index = false; + for (size_t i = 0; i < 64 && p[i] != 0xC3; ++i) { + if (p[i] == 0x65 && (p[i + 1] & 0xF8) == 0x48 && p[i + 2] == 0x8B && (p[i + 3] & 0xC7) == 0x04 && + p[i + 4] == 0x25 && p[i + 5] == 0x58 && !p[i + 6] && !p[i + 7] && !p[i + 8]) + gs58 = true; + int32_t disp; + std::memcpy(&disp, p + i, 4); + for (int tail = 4; tail <= 5; ++tail) // the displacement ends the instruction or is followed by an imm8 + index |= p + i + tail + disp == tls_index; + } + return gs58 && !index; +} + +// Calls the getter with stand-in blocks in slot 0 (77 at the variable's offset) and in slot `other` (88), and the +// executable's _tls_index pointing at `other`: /GA code reads 77, code that loads _tls_index reads 88. Slot `other` +// is this EXE's own TLS meanwhile, so nothing here touches thread_local data. +__declspec(noinline) int read_through_stand_ins(const Ga& ga, size_t offset, DWORD other) { + alignas(64) static uint8_t zero_slot[4096], other_slot[4096]; + const int seventy_seven = 77, eighty_eight = 88; + std::memcpy(zero_slot + offset, &seventy_seven, sizeof(int)); + std::memcpy(other_slot + offset, &eighty_eight, sizeof(int)); + void** slots = module_tls_slots(); + unsigned long* index = ga.tls_index_address(); + void* const saved0 = slots[0]; + void* const saved_other = slots[other]; + const unsigned long saved_index = *index; + slots[0] = zero_slot; + slots[other] = other_slot; + *index = other; + const int seen = ga.get(); + *index = saved_index; + slots[other] = saved_other; + slots[0] = saved0; + return seen; +} + +// What a thread started after the reservation sees, without any install call. +struct NewThreadView { + bool from_template = false; // its TLS at the home index starts from this EXE's template, not from zeros + int ga = -1, ga_after_set = -1, host = -1, dll = -1; + bool host_at_home = false; + void* slot0 = nullptr; +}; + +// ga may be null: then only this EXE's own TLS is looked at. +NewThreadView run_new_thread(const Ga* ga, int(__cdecl* dll_get)() = nullptr) { + NewThreadView v; + std::thread t([&] { + // Not the whole block: the helper's DLL_THREAD_ATTACH has already written the loader's own thread_local + // state there. -1 is a template value that a zero-filled block would not have. + v.from_template = t_seen_in_hook == -1; + v.slot0 = module_tls_slots()[0]; + if (ga) { + v.ga = ga->get(); + ga->set(9); + v.ga_after_set = ga->get(); + } + v.host = host_value(); + set_host_value(4321); + v.host_at_home = host_tls_at_home(); + if (dll_get) v.dll = dll_get(); + }); + t.join(); + return v; +} + +__declspec(noinline) bool call_reserve(std::string* why) { return rt::reserve_tls_index0(why); } + +// ---- runs ---- + +// A thread started before the reservation that runs no TLS code before it. load() gives it the executable's copy +// in slot 0, as it gives an already-running thread every module's copy (#3671); install_tls_for_thread and +// uninstall_tls_for_thread are no-ops there. +struct EarlyThread { + HANDLE go = CreateEventW(nullptr, TRUE, FALSE, nullptr); + HANDLE done = CreateEventW(nullptr, TRUE, FALSE, nullptr); + HANDLE quit = CreateEventW(nullptr, TRUE, FALSE, nullptr); + HANDLE handle = nullptr; + rt::Loader* loader = nullptr; + rt::Module* module = nullptr; + Ga ga{}; + int host = -1, ga_before_install = -1, ga_installed = -1, ga_after_set = -1; + bool host_at_home = false, block_in_slot0 = false, slot0_restored = false; + void* slot0_before_install = nullptr; + + static __declspec(noinline) void checks(EarlyThread* t) { + t->host = host_value(); + t->host_at_home = host_tls_at_home(); + // load() gave this already-running thread the executable's copy, as it does for a DLL (#3671): the /GA + // getter reads the template value before any install call. + t->slot0_before_install = module_tls_slots()[0]; + t->ga_before_install = t->ga.get(); + void* before = module_tls_slots()[0]; + t->loader->install_tls_for_thread(*t->module); + t->block_in_slot0 = module_tls_slots()[0] != before; + t->ga_installed = t->ga.get(); + t->ga.set(5); + t->ga_after_set = t->ga.get(); + t->loader->uninstall_tls_for_thread(*t->module); + t->slot0_restored = module_tls_slots()[0] == before; + } + static DWORD WINAPI body(void* p) { // no TLS here: it runs from before the reservation + auto* t = static_cast(p); + WaitForSingleObject(t->go, INFINITE); + if (t->loader) checks(t); + SetEvent(t->done); + WaitForSingleObject(t->quit, INFINITE); // ends after both Loaders are gone + return 0; + } + __declspec(noinline) void start() { handle = CreateThread(nullptr, 0, &body, this, 0, nullptr); } + void finish() { + SetEvent(go); + SetEvent(quit); + if (handle) { + WaitForSingleObject(handle, INFINITE); + CloseHandle(handle); + } + for (HANDLE h : {go, done, quit}) CloseHandle(h); + } +}; + +void test_first_run(const fs::path& exe, const fs::path& dll, EarlyThread& early, void* own_block) { + std::printf("\n-- first run: %s --\n", exe.string().c_str()); + const DWORD home = home_index(); + void* block = nullptr; + void* saved = nullptr; + { + rt::Loader loader(exe.parent_path()); + rt::Module& m = loader.load(exe); + const Ga ga = ga_exports(m); + std::printf(" this EXE's _tls_index is now %lu; the executable's block=%p\n", _tls_index, m.tls_block); + + check(m.tls_index == 0, "the mapped executable gets module TLS index 0"); + check(ga.tls_index() == 0, "its AddressOfIndex (_tls_index) holds 0"); + check(m.tls_block && module_tls_slots()[0] == m.tls_block, "slot 0 of this thread holds its template copy"); + check(ga.get() == 42, "its /GA getter reads the template value 42 on the loading thread"); + check(module_tls_slots()[home] == own_block && host_value() == 555, + "this EXE's TLS on the loading thread is still the same block, now at the home index"); + check(m.tls_saved_block && m.tls_saved_block != own_block, "the block saved from slot 0 is not this EXE's"); + + const auto offset = reinterpret_cast(ga.address()) - static_cast(m.tls_block); + const bool offset_ok = offset >= 0 && static_cast(offset) + sizeof(int) <= m.tls_block_size && + static_cast(offset) + sizeof(int) <= 4096; + check(offset_ok, "the executable's thread_local lies inside its slot-0 block"); + if (offset_ok) + check(read_through_stand_ins(ga, static_cast(offset), home) == 77, + "the getter reads slot 0 even when its _tls_index names another slot (/GA code)"); +#if LEONIDA_GA_FIXTURE_IS_GA + check(reads_slot0_without_index(reinterpret_cast(ga.get), ga.tls_index_address()), + "the fixture's getter has the /GA shape: gs:[58h] and no load of _tls_index"); +#else + std::printf("SKIP the fixture's /GA code shape (this compiler may ignore /GA)\n"); +#endif + + ga.set(43); + const NewThreadView fresh = run_new_thread(&ga); + check(fresh.from_template, "a new thread's TLS at the home index starts from this EXE's template"); + check(fresh.ga == 42, "a thread started after load() reads 42 without an install call"); + check(fresh.ga_after_set == 9 && ga.get() == 43, "its write stays in its own copy"); + check(fresh.slot0 != m.tls_block, "its slot 0 is its own block, not the loading thread's"); + check(fresh.host == 1234 && fresh.host_at_home, + "this EXE's thread_local starts at 1234 there, at the home index"); + check(host_value() == 555, "this EXE's value on the loading thread is unchanged"); + + early.loader = &loader; + early.module = &m; + early.ga = ga; + SetEvent(early.go); + WaitForSingleObject(early.done, INFINITE); + check(early.host == 1234 && early.host_at_home, + "a thread that existed before the reservation finds a fresh copy of this EXE's TLS at the home index"); + check(early.ga_before_install == 42 && early.slot0_before_install != m.tls_block, + "load() gives a thread that was already running its own copy in slot 0: it reads 42 with no install " + "call"); + check(!early.block_in_slot0 && early.ga_installed == 42 && early.ga_after_set == 5, + "install_tls_for_thread is a no-op there, and the thread's writes stay in its own copy"); + check(early.slot0_restored, "uninstall_tls_for_thread leaves that thread's copy in slot 0"); + + loader.initialise(); + check(m.initialised, "initialise() runs the executable's TLS callbacks (it has none)"); + check(run_new_thread(&ga).ga == 42, "after initialise() a new thread still reads 42"); + + rt::Module& d = loader.load(dll); + const auto dll_get = find_export(d, "tiny_tls_get"); + check(d.tls_index != rt::kNoTlsIndex && d.tls_index != 0 && d.tls_index != home, + "tiny_tls.dll gets a helper index, neither 0 nor the home index"); + check(dll_get() == 7 && ga.get() == 43 && host_value() == 555, + "the DLL, the executable and this EXE each read their own value on the loading thread"); + const NewThreadView both = run_new_thread(&ga, dll_get); + check(both.dll == 7 && both.ga == 42 && both.host == 1234, + "a new thread reads the DLL's 7, the executable's 42 and this EXE's 1234"); + + block = m.tls_block; + saved = m.tls_saved_block; + } + check(module_tls_slots()[0] == saved, "~Loader puts slot 0's earlier block back"); + MEMORY_BASIC_INFORMATION info{}; + check(VirtualQuery(block, &info, sizeof(info)) == 0 || info.State == MEM_FREE, "~Loader frees the copy"); + check(_tls_index == home && host_value() == 555, "this EXE keeps the home index and its value after the run"); +} + +void test_second_run(const fs::path& exe) { + std::printf("\n-- second run, and a second executable at once --\n"); + wchar_t temp[MAX_PATH]; + GetTempPathW(MAX_PATH, temp); + const fs::path copy = + fs::path(temp) / ("leonida_tls_index0_copy_" + std::to_string(GetCurrentProcessId()) + ".exe"); + // CopyFileW, not fs::copy_file: MSVC's copy_file calls CopyFile2, which Wine 9 doesn't implement. + check(CopyFileW(exe.c_str(), copy.c_str(), FALSE) != 0, "copied the executable under a second name"); + { + rt::Loader loader(exe.parent_path()); + rt::Module& m = loader.load(exe); + const Ga ga = ga_exports(m); + loader.initialise(); + check(m.tls_index == 0 && ga.get() == 42, "a second Loader maps the executable at index 0 again, value 42"); + check(run_new_thread(&ga).ga == 42 && host_value() == 555, "new threads and this EXE's value still check out"); + + rt::Module& other = loader.load(copy); + const Ga other_ga = ga_exports(other); + check(other.tls_index != 0 && other.tls_index != rt::kNoTlsIndex && other_ga.tls_index() == other.tls_index, + "a second executable mapped meanwhile gets a helper index in its _tls_index"); + check(m.tls_index == 0 && ga.get() == 42, "the first keeps index 0 and its value"); + } + std::error_code ec; + fs::remove(copy, ec); +} + +void test_home_template() { + std::printf("\n-- the home clone --\n"); + const HMODULE home = home_module(); + check(home != nullptr, "the home clone is loaded"); + if (!home) return; + const auto* tls = tls_of(home); + const Template tmpl = own_template(); + std::printf(" this EXE's TLS is %zu bytes; the home clone's template is %llu bytes\n", tmpl.size, + static_cast(tls->EndAddressOfRawData - tls->StartAddressOfRawData)); + check(tls->EndAddressOfRawData - tls->StartAddressOfRawData == tmpl.size, + "the home template is exactly as large as this EXE's TLS (template plus zero fill)"); + check(std::memcmp(reinterpret_cast(tls->StartAddressOfRawData), tmpl.data, tmpl.size) == 0, + "the home template holds this EXE's template"); +} + +// Runs before the reservation: TLS here is fine, as no frame outlives the call. +__declspec(noinline) void* before_reservation() { + check(_tls_index == 0, "before the reservation this test EXE holds module TLS index 0 (Windows gave it)"); + set_host_value(555); + check(inside(host_address(), module_tls_slots()[0], own_template().size), "its TLS is the block in slot 0"); + return module_tls_slots()[0]; +} + +__declspec(noinline) void after_reservation(bool reserved, const std::string& why, void* own_block, EarlyThread& early, + const fs::path& exe, const fs::path& dll) { + if (!why.empty()) std::printf(" reserve_tls_index0: %s\n", why.c_str()); + check(reserved && why.empty(), "reserve_tls_index0 succeeds"); + const DWORD home = home_index(); + check(home != rt::kNoTlsIndex && home != 0 && _tls_index == home, + "this EXE's _tls_index is the home clone's own index"); + check(module_tls_slots()[home] == own_block && module_tls_slots()[0] != own_block && host_value() == 555, + "on the reserving thread this EXE's block moved, with its value, from slot 0 to the home index"); + std::string again; + check(rt::reserve_tls_index0(&again) && again.empty(), "a second call returns the first result"); + test_home_template(); + test_first_run(exe, dll, early, own_block); + test_second_run(exe); +} + +__declspec(noinline) int scenario_runs(const fs::path& exe, const fs::path& dll) { + void* own_block = before_reservation(); + EarlyThread early; + early.start(); + std::string why; + const bool reserved = call_reserve(&why); + after_reservation(reserved, why, own_block, early, exe, dll); + early.finish(); + return 0; +} + +// ---- threads ---- + +constexpr int kChurn = 64; +struct ThreadResult { + int host = -1, seen_in_hook = -1; + bool hooked = false, at_home = false, fresh = false; +}; +ThreadResult g_results[kChurn + 1]; +HANDLE g_handles[kChurn + 1]; +HANDLE g_go = nullptr; +std::atomic g_hook_active{false}; +std::atomic g_created{0}; +std::atomic g_stop_churn{false}; + +// Runs in tiny_thread_hook.dll's DllMain(DLL_THREAD_ATTACH), before the TLS helper's own DLL_THREAD_ATTACH. +void __cdecl hook_body() { + if (!g_hook_active.load()) return; // TLS only once the reservation is done + t_seen_in_hook = host_value(); + t_hooked = host_tls_at_home(); + set_host_value(4321); +} + +__declspec(noinline) void record(int i) { + g_results[i].hooked = t_hooked; + g_results[i].seen_in_hook = t_seen_in_hook; + g_results[i].host = host_value(); + g_results[i].at_home = host_tls_at_home(); +} + +DWORD WINAPI churn_body(void* p) { // no TLS before the wait: it may start before the reservation + WaitForSingleObject(g_go, INFINITE); + record(static_cast(reinterpret_cast(p))); + return 0; +} + +DWORD WINAPI churn_creator(void*) { // runs through the reservation and touches no TLS + for (int i = 1; i <= kChurn; ++i) { + void* index = reinterpret_cast(static_cast(i)); + g_handles[i] = CreateThread(nullptr, 0, &churn_body, index, 0, nullptr); + g_created.store(i); + if (i >= kChurn / 2) while (!g_stop_churn.load()) Sleep(0); // the rest after the reservation + Sleep(0); + } + return 0; +} + +using NtQueryInformationThreadFn = LONG(NTAPI*)(HANDLE, int, PVOID, ULONG, PULONG); + +// TEB->ThreadLocalStoragePointer of another thread. +void* tls_array_of(HANDLE thread) { + struct { + LONG exit_status; + PVOID teb; + PVOID ids[2]; + ULONG_PTR affinity; + LONG priority, base_priority; + } info{}; + const auto query = reinterpret_cast( + GetProcAddress(GetModuleHandleW(L"ntdll.dll"), "NtQueryInformationThread")); + if (!query || query(thread, 0, &info, sizeof(info), nullptr) < 0 || !info.teb) return reinterpret_cast(1); + return *reinterpret_cast(static_cast(info.teb) + 0x58); +} + +__declspec(noinline) void threads_after(bool reserved, HANDLE suspended, bool suspended_had_no_array) { + check(reserved, "reserve_tls_index0 succeeds while threads are being created"); + check(suspended_had_no_array, "the thread created suspended has no TLS array yet when the reservation starts"); + std::printf(" %d threads created before the reservation returned\n", g_created.load()); + g_hook_active = true; + SetEvent(g_go); + g_stop_churn = true; + ResumeThread(suspended); + HANDLE creator = g_handles[0]; + WaitForSingleObject(creator, INFINITE); + CloseHandle(creator); + WaitForSingleObject(suspended, INFINITE); + CloseHandle(suspended); + int hooked = 0, ok = 0, window_ok = 0; + for (int i = 1; i <= kChurn; ++i) { + WaitForSingleObject(g_handles[i], INFINITE); + CloseHandle(g_handles[i]); + } + for (int i = 0; i <= kChurn; ++i) { + const ThreadResult& r = g_results[i]; + ok += r.at_home && r.host == (r.hooked ? 4321 : 1234); + hooked += r.hooked; + window_ok += r.hooked && r.seen_in_hook == 1234; + } + std::printf(" %d of %d threads ran the hook in DLL_THREAD_ATTACH\n", hooked, kChurn + 1); + check(ok == kChurn + 1, "every thread created before, during or after the reservation finds this EXE's TLS at the " + "home index, with the value it should have"); + check(g_results[0].hooked && g_results[0].at_home && g_results[0].host == 4321, + "the suspended thread, resumed afterwards, gets a fresh copy and keeps the hook's write"); + check(hooked > 0 && window_ok == hooked, + "code of this EXE run before the helper's DLL_THREAD_ATTACH reads a fresh copy of its TLS (1234) there"); +} + +__declspec(noinline) int scenario_threads(const fs::path& hook_dll) { + HMODULE hook = LoadLibraryW(hook_dll.c_str()); // before the helper, so its DLL_THREAD_ATTACH comes first + using SetHook = void(__cdecl*)(void(__cdecl*)()); + auto set_hook = hook ? reinterpret_cast(GetProcAddress(hook, "tiny_thread_hook_set")) : nullptr; + check(set_hook != nullptr, "tiny_thread_hook.dll is loaded"); + if (!set_hook) return 1; + set_hook(&hook_body); + g_go = CreateEventW(nullptr, TRUE, FALSE, nullptr); + HANDLE suspended = CreateThread(nullptr, 0, &churn_body, nullptr, CREATE_SUSPENDED, nullptr); + g_handles[0] = CreateThread(nullptr, 0, &churn_creator, nullptr, 0, nullptr); + while (g_created.load() < 4) Sleep(0); + const bool no_array = tls_array_of(suspended) == nullptr; + const bool reserved = call_reserve(nullptr); + threads_after(reserved, suspended, no_array); + CloseHandle(g_go); + return 0; +} + +// ---- noreserve ---- + +__declspec(noinline) int scenario_noreserve(const fs::path& exe) { + rt::Loader loader(exe.parent_path()); + rt::Module& m = loader.load(exe); + check(m.tls_index != 0 && m.tls_index != rt::kNoTlsIndex, + "without reserve_tls_index0 the executable gets a helper index"); + check(_tls_index == 0, "and this EXE keeps module TLS index 0"); + check(ga_exports(m).tls_index() == m.tls_index, "the executable's _tls_index holds that helper index"); + return 0; +} + +void print_result() { + if (g_failures == 0) + std::printf("\nloader_tls_index0_test: OK (%d checks)\n", g_checks); + else + std::printf("\nloader_tls_index0_test: FAILED (%d checks, %d failure%s)\n", g_checks, g_failures, + g_failures == 1 ? "" : "s"); +} + +} // namespace + +int main(int argc, char** argv) { + std::setvbuf(stdout, nullptr, _IONBF, 0); + if (argc != 5) { + std::fprintf(stderr, + "usage: loader_tls_index0_test runs|threads|noreserve " + "\n"); + return 2; + } + std::printf("loader_tls_index0_test %s: module TLS index 0 for a mapped executable\n", argv[1]); + const std::string scenario = argv[1]; + const fs::path exe = argv[2], dll = argv[3], hook = argv[4]; + try { + if (!fs::exists(exe) || !fs::exists(dll) || !fs::exists(hook)) throw std::runtime_error("a fixture is missing"); + if (scenario == "runs") scenario_runs(exe, dll); + else if (scenario == "threads") scenario_threads(hook); + else if (scenario == "noreserve") scenario_noreserve(exe); + else throw std::runtime_error("unknown scenario " + scenario); + } catch (const std::exception& e) { + ++g_checks; + ++g_failures; + std::printf("FAIL unexpected exception: %s\n", e.what()); + } + print_result(); + return g_failures ? 1 : 0; +} diff --git a/runtime/test/pipeline_cache_file_test.cpp b/runtime/test/pipeline_cache_file_test.cpp index 73dad65de8..f24694a56d 100644 --- a/runtime/test/pipeline_cache_file_test.cpp +++ b/runtime/test/pipeline_cache_file_test.cpp @@ -1,5 +1,5 @@ // Exercise checkpoint replacement and real filesystem errors without a Vulkan device. -#include "pipeline_cache_file.h" +#include "../src/pipeline_cache_file.h" #include #include diff --git a/runtime/test/pipeline_cache_seed_test.cpp b/runtime/test/pipeline_cache_seed_test.cpp new file mode 100644 index 0000000000..2254257b72 --- /dev/null +++ b/runtime/test/pipeline_cache_seed_test.cpp @@ -0,0 +1,170 @@ +// The cache vk_pipeline_check saves has to hit on the runtime's device: +// pipeline_cache_seed_test +// +// Creates the runtime's own device (create_vulkan_device_standalone), seeds a VkPipelineCache from the file and +// creates the compute pipeline of the way PipelineState::create_compute does for a shader without set-0 +// bindings: no set layouts, one 144-byte compute push-constant range and the subgroup request of src/subgroup_size.h. +// It passes when the driver reports VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT for that creation. +// +// Exit 77 (skipped): no device, a cache written for another GPU or driver, or a driver that reports no hit even for +// a cache this device wrote itself a moment before. Run by test/check_pipeline_cache_seed.cmake after the checker. +#include "../shims/d3d12_com.h" +#include "../src/shader_library.h" +#include +#include +#include +#include +#include +#include + +namespace { + +std::vector read_file(const char* path) { + std::ifstream file(path, std::ios::binary); + return {std::istreambuf_iterator(file), std::istreambuf_iterator()}; +} + +struct Created { + bool ok = false; + bool hit = false; // VALID and APPLICATION_PIPELINE_CACHE_HIT +}; + +} // namespace + +int main(int argc, char** argv) { + if (argc != 3) { + std::fprintf(stderr, "usage: pipeline_cache_seed_test \n"); + return 2; + } + const std::vector code = read_file(argv[1]); + const std::vector seed = read_file(argv[2]); + if (code.empty() || code.size() % 4) { + std::fprintf(stderr, "%s: not a SPIR-V module\n", argv[1]); + return 1; + } + if (seed.size() < sizeof(VkPipelineCacheHeaderVersionOne)) { + std::fprintf(stderr, "%s: not a pipeline cache\n", argv[2]); + return 1; + } + + Microsoft::WRL::ComPtr d3d; + if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(&d3d))) || !d3d) { + std::printf("SKIP: no Vulkan device for the runtime\n"); + return 77; + } + const rt::d3d12::VulkanDeviceInfo* info = rt::d3d12::vulkan_device_info(d3d.Get()); + if (!info || !info->get_instance_proc) return 1; + const VkDevice device = info->device; + const auto device_proc = reinterpret_cast( + info->get_instance_proc(info->instance, "vkGetDeviceProcAddr")); + const auto physical_properties = reinterpret_cast( + info->get_instance_proc(info->instance, "vkGetPhysicalDeviceProperties")); + if (!device_proc || !physical_properties) return 1; +#define LOAD(name) const auto name = reinterpret_cast(device_proc(device, #name)) + LOAD(vkCreateShaderModule); + LOAD(vkDestroyShaderModule); + LOAD(vkCreatePipelineLayout); + LOAD(vkDestroyPipelineLayout); + LOAD(vkCreatePipelineCache); + LOAD(vkDestroyPipelineCache); + LOAD(vkGetPipelineCacheData); + LOAD(vkCreateComputePipelines); + LOAD(vkDestroyPipeline); +#undef LOAD + + VkPhysicalDeviceProperties properties{}; + physical_properties(info->physical, &properties); + VkPipelineCacheHeaderVersionOne header{}; + std::memcpy(&header, seed.data(), sizeof(header)); + if (header.vendorID != properties.vendorID || header.deviceID != properties.deviceID || + std::memcmp(header.pipelineCacheUUID, properties.pipelineCacheUUID, VK_UUID_SIZE) != 0) { + std::printf("SKIP: %s was written for another GPU or driver than the runtime's %s\n", argv[2], + properties.deviceName); + return 77; + } + + VkShaderModuleCreateInfo module_info{VK_STRUCTURE_TYPE_SHADER_MODULE_CREATE_INFO}; + module_info.codeSize = code.size(); + module_info.pCode = reinterpret_cast(code.data()); + VkShaderModule module = VK_NULL_HANDLE; + if (vkCreateShaderModule(device, &module_info, nullptr, &module) != VK_SUCCESS) return 1; + const VkPushConstantRange push{VK_SHADER_STAGE_COMPUTE_BIT, 0, sizeof(leonida::ShaderUserData)}; + VkPipelineLayoutCreateInfo layout_info{VK_STRUCTURE_TYPE_PIPELINE_LAYOUT_CREATE_INFO}; + layout_info.pushConstantRangeCount = 1; + layout_info.pPushConstantRanges = &push; + VkPipelineLayout layout = VK_NULL_HANDLE; + if (vkCreatePipelineLayout(device, &layout_info, nullptr, &layout) != VK_SUCCESS) return 1; + + const auto make_cache = [&](const void* data, std::size_t size) { + VkPipelineCacheCreateInfo cache_info{VK_STRUCTURE_TYPE_PIPELINE_CACHE_CREATE_INFO}; + cache_info.initialDataSize = size; + cache_info.pInitialData = data; + VkPipelineCache cache = VK_NULL_HANDLE; + if (vkCreatePipelineCache(device, &cache_info, nullptr, &cache) != VK_SUCCESS) return VkPipelineCache{}; + return cache; + }; + // The index entry check_pipeline_cache_seed.cmake writes: both programs take the subgroup request from it. + leonida::ShaderEntry entry; + entry.stage = "cs"; + entry.local_size = {1, 1, 1}; + const auto create = [&](VkPipelineCache cache) { + VkPipelineCreationFeedback feedback{}; + const VkPipelineCreationFeedbackCreateInfo feedback_info{ + VK_STRUCTURE_TYPE_PIPELINE_CREATION_FEEDBACK_CREATE_INFO, nullptr, &feedback, 0, nullptr}; + VkComputePipelineCreateInfo pipeline_info{VK_STRUCTURE_TYPE_COMPUTE_PIPELINE_CREATE_INFO, &feedback_info}; + pipeline_info.stage = {VK_STRUCTURE_TYPE_PIPELINE_SHADER_STAGE_CREATE_INFO}; + pipeline_info.stage.stage = VK_SHADER_STAGE_COMPUTE_BIT; + pipeline_info.stage.module = module; + pipeline_info.stage.pName = "main"; + VkPipelineShaderStageRequiredSubgroupSizeCreateInfo required_size{}; + leonida::apply_subgroup_request(leonida::decide_subgroup_size(entry, info->subgroup), required_size, + pipeline_info.stage); + pipeline_info.layout = layout; + VkPipeline pipeline = VK_NULL_HANDLE; + Created result; + if (vkCreateComputePipelines(device, cache, 1, &pipeline_info, nullptr, &pipeline) != VK_SUCCESS) return result; + vkDestroyPipeline(device, pipeline, nullptr); + result.ok = true; + result.hit = (feedback.flags & VK_PIPELINE_CREATION_FEEDBACK_VALID_BIT) && + (feedback.flags & VK_PIPELINE_CREATION_FEEDBACK_APPLICATION_PIPELINE_CACHE_HIT_BIT); + return result; + }; + + int code_out = 1; + const VkPipelineCache seeded = make_cache(seed.data(), seed.size()); + const Created from_seed = seeded ? create(seeded) : Created{}; + if (!from_seed.ok) { + std::fprintf(stderr, "FAIL: the pipeline was not created from the seeded cache\n"); + } else if (from_seed.hit) { + std::printf("ok: %s hits on the runtime's device (%s)\n", argv[2], properties.deviceName); + code_out = 0; + } else { + // Does this driver report a hit at all? Write a cache on this device and read it back. + const VkPipelineCache first = make_cache(nullptr, 0); + std::vector own; + std::size_t size = 0; + if (first && create(first).ok && vkGetPipelineCacheData(device, first, &size, nullptr) == VK_SUCCESS) { + own.resize(size); + if (vkGetPipelineCacheData(device, first, &size, own.data()) != VK_SUCCESS) own.clear(); + own.resize(own.empty() ? 0 : size); + } + const VkPipelineCache second = own.empty() ? VkPipelineCache{} : make_cache(own.data(), own.size()); + const bool reports_hits = second && create(second).hit; + if (first) vkDestroyPipelineCache(device, first, nullptr); + if (second) vkDestroyPipelineCache(device, second, nullptr); + if (reports_hits) { + std::fprintf(stderr, + "FAIL: %s does not hit on the runtime's device (%s), which does hit a cache it wrote itself: " + "vk_pipeline_check's device differs from the runtime's in something the driver makes part " + "of a pipeline's cache key\n", + argv[2], properties.deviceName); + } else { + std::printf("SKIP: %s reports no cache hit even for a cache it wrote itself\n", properties.deviceName); + code_out = 77; + } + } + if (seeded) vkDestroyPipelineCache(device, seeded, nullptr); + vkDestroyPipelineLayout(device, layout, nullptr); + vkDestroyShaderModule(device, module, nullptr); + return code_out; +} diff --git a/runtime/test/pipeline_cache_store_test.cpp b/runtime/test/pipeline_cache_store_test.cpp new file mode 100644 index 0000000000..dbf174768b --- /dev/null +++ b/runtime/test/pipeline_cache_store_test.cpp @@ -0,0 +1,93 @@ +// The two pure decisions behind D3D-704: how large a session cache may be (LEONIDA_PIPELINE_CACHE_BYTES) and +// whether a blob's VkPipelineCacheHeaderVersionOne names this device. No Vulkan, no GPU, no files. +#include "../src/pipeline_cache_store.h" + +#include +#include +#include +#include +#include + +#define CHECK(condition) do { \ + if (!(condition)) { \ + std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); \ + return 1; \ + } \ +} while (0) + +namespace store = leonida::pipeline_cache_store; + +static void put32(std::uint8_t* p, std::uint32_t value) { + for (int i = 0; i < 4; ++i) p[i] = static_cast(value >> (8 * i)); +} + +static int test_limit() { + using store::default_save_limit; + // Absent, empty and the default knob. + CHECK(store::parse_save_limit(nullptr).bytes == default_save_limit); + CHECK(store::parse_save_limit(nullptr).valid); + CHECK(store::parse_save_limit("").bytes == default_save_limit); + // 0 is the documented "off", not a typo, and leading zeros are still a number. + CHECK(store::parse_save_limit("0").bytes == 0); + CHECK(store::parse_save_limit("0").valid); + CHECK(store::parse_save_limit("007").bytes == 7); + CHECK(store::parse_save_limit("1048576").bytes == 1048576); + const std::string largest = std::to_string(std::numeric_limits::max()); + CHECK(store::parse_save_limit(largest.c_str()).bytes == std::numeric_limits::max()); + // Anything that is not a plain byte count falls back to the default and says the value was rejected. + for (const char* text : {"-1", "+1", " 1", "1 ", "12x", "0x10", "1.5", "99999999999999999999999999"}) { + const auto limit = store::parse_save_limit(text); + CHECK(!limit.valid); + CHECK(limit.bytes == default_save_limit); + } + return 0; +} + +static int test_header() { + leonida::cached_pso::Identity identity; + identity.vendor = 0x1002; + identity.device = 0x73ff; + identity.driver = 0x02000d0b; + + std::uint8_t header[store::header_bytes] = {}; + put32(header, store::header_bytes); + put32(header + 4, store::header_version_one); + put32(header + 8, identity.vendor); + put32(header + 12, identity.device); + for (int i = 0; i < 16; ++i) header[16 + i] = identity.cache_uuid[i] = static_cast(i + 1); + CHECK(store::header_matches(header, sizeof(header), identity)); + // Extra payload past the header does not matter: the driver reads the header and then its own data. + std::uint8_t blob[store::header_bytes + 8] = {}; + std::memcpy(blob, header, sizeof(header)); + CHECK(store::header_matches(blob, sizeof(blob), identity)); + + // Too short and null are "no cache", never a read past the end. + CHECK(!store::header_matches(header, store::header_bytes - 1, identity)); + CHECK(!store::header_matches(nullptr, store::header_bytes, identity)); + + // The four fields a driver checks before trusting a blob from another device, driver or header version. + auto differs = [&](int offset, std::uint32_t value) { + std::uint8_t changed[store::header_bytes]; + std::memcpy(changed, header, sizeof(changed)); + put32(changed + offset, value); + return !store::header_matches(changed, sizeof(changed), identity); + }; + CHECK(differs(0, store::header_bytes + 4)); + CHECK(differs(4, store::header_version_one + 1)); + CHECK(differs(8, identity.vendor + 1)); + CHECK(differs(12, identity.device + 1)); + std::uint8_t uuid[store::header_bytes]; + std::memcpy(uuid, header, sizeof(uuid)); + uuid[16] ^= 0xff; + CHECK(!store::header_matches(uuid, sizeof(uuid), identity)); + // vendorID/deviceID are u32s little-endian; the same bytes read the other way name another device. + leonida::cached_pso::Identity swapped = identity; + swapped.vendor = 0x02100000; + CHECK(!store::header_matches(header, sizeof(header), swapped)); + return 0; +} + +int main() { + if (const int failed = test_limit()) return failed; + return test_header(); +} diff --git a/runtime/test/queue_proxy_test.cpp b/runtime/test/queue_proxy_test.cpp index 3f46567f85..ece44f117e 100644 --- a/runtime/test/queue_proxy_test.cpp +++ b/runtime/test/queue_proxy_test.cpp @@ -8,8 +8,9 @@ // - heap, queue and fence proxies are unwrapped where the real runtime receives them (Signal/Wait, // SetEventOnMultipleFenceCompletion, MakeResident/Evict/SetResidencyPriority/EnqueueMakeResident, // CreateSharedHandle), and OpenSharedHandle wraps a shared fence; -// - slots past the public chain are refused (E_NOTIMPL) up to the end of the table, and a slot past the table -// faults on the vtable read in the guard region and is counted; +// - slots past the public chain answer the console contract — a queue slot returns S_OK having signalled +// nothing (frame pacing flows through those methods), a fence slot is refused with E_NOTIMPL — and a +// slot past either table faults on the vtable read in the guard region and is counted; // - calls from eight threads at once, and repeated device, queue and fence creation without leaks; // - the child-process runner of the differential check itself: large output, hangs, crashes, failed starts. // No shaders, game data or Xbox DLLs. LEONIDA_VK_VALIDATION=1 runs the Vulkan device under @@ -389,24 +390,61 @@ int check_slots(const Backend& b) { } } - // The refused tail: every slot from the end of the public chain to the end of the table. + // The console queue tail answers S_OK instead of refusing: frame pacing flows through those + // methods, the contract xs_proxy_mock checks too. The two methods the proxy models — SignalX at + // 23 and PresentX at 30 on the older layout the 16/17 calls above pinned — are checked below. + // The fence tail below is still refused — nothing console-shaped was measured past its public chain. + // Fence slot 12 (value, descriptor, flags): the address of the completed value, which follows a queue's + // signal without another call (a wait on the real fence refreshes it). + { + before = fhits(12); + const auto* completed = reinterpret_cast(raw_call(fence.p, 12, 9, 0, 0)); + EXPECT(completed && *completed == fence->GetCompletedValue() && fhits(12) == before + 1); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 9))); + bool seen = false; + for (int i = 0; i < 5000 && !seen; ++i) { + seen = *completed == 9; + if (!seen) Sleep(1); + } + EXPECT(seen); + EXPECT(raw_call(fence.p, 12, 9, 0, 0) == reinterpret_cast(completed)); + } + + // The refused tail: every slot from the end of the public chain to the end of the table, but fence slot 12. for (unsigned slot = 19; slot < xs::queue_proxy_table_size(); ++slot) { + if (slot == 23 || slot == 30) continue; before = qhits(slot); - EXPECT(as_hr(call_slot(queue.p, slot)) == E_NOTIMPL); + EXPECT(as_hr(call_slot(queue.p, slot)) == S_OK); EXPECT(qhits(slot) == before + 1 && xs::queue_slot_first_call_seen(slot)); } + // SignalX forwards to the real queue's Signal with the extra word dropped: the fence reaching 9 + // proves the call was forwarded rather than swallowed by the console-tail answer. + before = qhits(23); + EXPECT(as_hr(raw_call(queue.p, 23, reinterpret_cast(fence.p), 9)) == S_OK); + EXPECT(qhits(23) == before + 1 && xs::queue_slot_first_call_seen(23)); + if (wait_for(label, fence.p, 9)) return 1; + // PresentX is handled by the presentation front end, not refused: its status is the swapchain's + // (a black frame on the test window, or S_OK where it cannot present), so anything but E_NOTIMPL + // shows the modelled path ran. + before = qhits(30); + EXPECT(as_hr(call_slot(queue.p, 30)) != E_NOTIMPL); + EXPECT(qhits(30) == before + 1 && xs::queue_slot_first_call_seen(30)); for (unsigned slot = fence_slots; slot < xs::fence_proxy_table_size(); ++slot) { + if (slot == 12) continue; before = fhits(slot); EXPECT(as_hr(call_slot(fence.p, slot)) == E_NOTIMPL); EXPECT(fhits(slot) == before + 1 && xs::fence_slot_first_call_seen(slot)); } - // The objects still work after refused calls. + // The objects still work after the console-only calls. EXPECT(SUCCEEDED(queue->Signal(fence.p, 10))); if (wait_for(label, fence.p, 10)) return 1; EXPECT(xs::command_object_proxy_ref_count(queue.p) == 1 && xs::command_object_proxy_ref_count(fence.p) == 1); } EXPECT(xs::device_proxy_ref_count(device) == device_refs); // every queue and fence gave its reference back - std::printf("%s: every public queue and fence slot forwarded and counted; tail refused\n", label); + std::printf("%s: every public queue and fence slot forwarded and counted; queue tail S_OK, fence tail " + "refused\n", label); + std::printf("%s: every public queue and fence slot forwarded and counted; fence slot 12 follows a queue " + "signal; tail refused\n", label); return 0; } diff --git a/runtime/test/replay_quad_list_test.cpp b/runtime/test/replay_quad_list_test.cpp new file mode 100644 index 0000000000..15b0c7e781 --- /dev/null +++ b/runtime/test/replay_quad_list_test.cpp @@ -0,0 +1,110 @@ +// Quad lists without an index buffer are one triangle-list draw. A switch back to Vulkan triangle fans +// changes the provoking vertex for flat attributes and the order of overlapping blended instances. +#include "../src/vulkan_replay.h" + +#include +#include +#include + +namespace { +using namespace leonida; + +struct DrawCall { + VkPrimitiveTopology topology; + VkBuffer buffer; + VkDeviceSize offset; + VkIndexType index_type; + std::uint32_t count, instances, first_index; + std::int32_t base_vertex; + std::uint32_t first_instance; + bool operator==(const DrawCall&) const = default; +}; + +DrawCall recorded{}; +std::vector calls; + +bool check(bool condition, const char* description) { + if (!condition) std::fprintf(stderr, "FAIL: %s\n", description); + return condition; +} +} + +int main() { + using namespace leonida; + ReplayFunctions vk{}; + vk.begin_rendering = +[](VkCommandBuffer, const VkRenderingInfo*) {}; + vk.end_rendering = +[](VkCommandBuffer) {}; + vk.bind_pipeline = +[](VkCommandBuffer, VkPipelineBindPoint, VkPipeline) {}; + vk.push_constants = +[](VkCommandBuffer, VkPipelineLayout, VkShaderStageFlags, std::uint32_t, + std::uint32_t, const void*) {}; + vk.set_viewport = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkViewport*) {}; + vk.set_scissor = +[](VkCommandBuffer, std::uint32_t, std::uint32_t, const VkRect2D*) {}; + vk.set_primitive_topology = +[](VkCommandBuffer, VkPrimitiveTopology topology) { recorded.topology = topology; }; + vk.set_primitive_restart_enable = +[](VkCommandBuffer, VkBool32) {}; + vk.set_stencil_reference = +[](VkCommandBuffer, VkStencilFaceFlags, std::uint32_t) {}; + vk.set_blend_constants = +[](VkCommandBuffer, const float*) {}; + vk.bind_index_buffer = +[](VkCommandBuffer, VkBuffer buffer, VkDeviceSize offset, VkIndexType type) { + recorded.buffer = buffer; + recorded.offset = offset; + recorded.index_type = type; + }; + vk.draw_indexed = +[](VkCommandBuffer, std::uint32_t count, std::uint32_t instances, std::uint32_t first, + std::int32_t base, std::uint32_t first_instance) { + recorded.count = count; + recorded.instances = instances; + recorded.first_index = first; + recorded.base_vertex = base; + recorded.first_instance = first_instance; + calls.push_back(recorded); + }; + + vk.quad_indices = reinterpret_cast(std::uintptr_t{1}); + vk.quad_indices_offset = 64; + vk.quad_index_count = 12; + const auto app_buffer = reinterpret_cast(std::uintptr_t{2}); + + GraphicsPipeline graphics{}; + const auto collect = [&](const Draw& draw) { + calls.clear(); + CommandList list; + if (!list.draw(draw) || !list.close()) return false; + PreparedList prepared; + prepared.list = &list; + prepared.commands.resize(1); + prepared.commands[0].draw = 0; + auto& entry = prepared.draws.emplace_back(); + entry.graphics = &graphics; + entry.index_buffer = app_buffer; + entry.index_offset = 32; + emit(prepared, VK_NULL_HANDLE, vk); + return true; + }; + + Draw draw{}; + draw.pipeline = 1; + draw.topology = topology_quad_list; + draw.count = 8; + draw.instances = 2; + draw.first = 13; + draw.first_instance = 7; + + const DrawCall triangles{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_LIST, vk.quad_indices, 64, VK_INDEX_TYPE_UINT32, + 12, 2, 0, 13, 7}; + bool ok = check(collect(draw) && calls == std::vector{triangles}, + "non-indexed quads use one triangle-list draw and preserve draw bases"); + draw.count = 13; + ok &= check(collect(draw) && calls == std::vector{triangles}, + "a draw is limited to whole quads in the generated index buffer"); + draw.count = 3; + ok &= check(collect(draw) && calls.empty(), "an incomplete quad emits no draw"); + + draw.indexed = true; + draw.count = 8; + draw.first = 5; + draw.base_vertex = -2; + const DrawCall first_fan{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, app_buffer, 32, VK_INDEX_TYPE_UINT16, 4, 2, 5, -2, 7}; + const DrawCall second_fan{VK_PRIMITIVE_TOPOLOGY_TRIANGLE_FAN, app_buffer, 32, VK_INDEX_TYPE_UINT16, 4, 2, 9, -2, 7}; + ok &= check(collect(draw) && calls == std::vector{first_fan, second_fan}, + "indexed quads use the application's index buffer and base vertex"); + return ok ? 0 : 1; +} diff --git a/runtime/test/shader_library_corpus_test.cpp b/runtime/test/shader_library_corpus_test.cpp index 7fdba23743..bb0be8c72e 100644 --- a/runtime/test/shader_library_corpus_test.cpp +++ b/runtime/test/shader_library_corpus_test.cpp @@ -192,16 +192,16 @@ int main() { } if (containers == 0) fail("no .dxbc containers in", dxbc_dir); - const std::size_t rpf_entries = library.size() - library.fspx_size() - library.bvh_size(); + const std::size_t rpf_entries = library.size() - library.fspx_size() - library.bvh_size() - library.exe_size(); if (reached.size() != rpf_entries) fail(std::to_string(reached.size() > rpf_entries ? reached.size() - rpf_entries : rpf_entries - reached.size()) + " RPF index entries not matched one to one", spirv_dir); std::printf("%zu containers, %zu RPF index entries, %zu reached, %zu FSPX index entries, %zu BVH builder index " - "entries; %zu containers with more than one program; " + "entries, %zu executable index entries; %zu containers with more than one program; " "%zu not translated; %d failures\n", - containers, rpf_entries, reached.size(), library.fspx_size(), library.bvh_size(), multi, untranslated, - failures); + containers, rpf_entries, reached.size(), library.fspx_size(), library.bvh_size(), library.exe_size(), + multi, untranslated, failures); if (untranslated) std::fprintf(stderr, "%zu container(s) have no index entry: the translator left them out, so the lookup had " "nothing to find. Run the shaders stage again with a current translator.\n", diff --git a/runtime/test/shader_library_test.cpp b/runtime/test/shader_library_test.cpp index bf7ad80d10..de3dc1e4fe 100644 --- a/runtime/test/shader_library_test.cpp +++ b/runtime/test/shader_library_test.cpp @@ -571,6 +571,16 @@ int main() { CHECK(!zlib_inflate(broken, out)); CHECK(!zlib_inflate(dynamic, out, 599)); // larger than the limit CHECK(!zlib_inflate(bytes("not zlib"), out)); + // The reason a caller can ask for (dstorage.cpp reports each with its own HRESULT). + ZlibError why = ZlibError::limit; + CHECK(zlib_inflate(dynamic, out, 600, &why) && why == ZlibError::none); + CHECK(!zlib_inflate(dynamic, out, 599, &why) && why == ZlibError::limit); + CHECK(!zlib_inflate(bytes("not zlib"), out, 1 << 20, &why) && why == ZlibError::header); + broken = dynamic; + broken.back() ^= 1; + CHECK(!zlib_inflate(broken, out, 1 << 20, &why) && why == ZlibError::checksum); + broken.resize(100); + CHECK(!zlib_inflate(broken, out, 1 << 20, &why) && why == ZlibError::data); Json json; // "s" holds an escaped quote and a \u escape for U+00E9, which the reader must turn into UTF-8. @@ -760,65 +770,63 @@ int main() { std::filesystem::remove_all(dir); } - // Pipeline-library entries: the compute programs of the library in shaders.rpf, translated by make_game.py into - // /library/index.json (named "library/"), are found by the same two keys as the DLL's FSPX programs, - // next to /fspx/. The executable's slot-67 description carries kind 0 (the record's state blob) and kind 6. + // Executable embedded shaders (/exe/index.json): graphics (vs/ps) FSSM programs indexed alongside the game's + // own shaders, counted apart via exe_size(), and optional when missing or malformed. { + const auto vs_container = container({{fixed, 25}}); + const auto ps_container = container({{stored, 40}}); + const std::string vs_hash = sha256_hex(fssm_program(vs_container)); + const std::string ps_hash = sha256_hex(fssm_program(ps_container)); const auto code = fspx_code(0x5000); - const auto shared_code = fspx_code(0x7000); - std::vector state(28, 0), other_state(28, 0); - state[12] = 64; // word 3: NumThreadsX - other_state[12] = 32; - const auto n = std::uint32_t(code.size()); - const auto payload = [&](const std::vector& kind0) { - std::vector body = kind0; - body.insert(body.end(), code.begin(), code.end()); - return fspx_payload({{0, 48, 28}, {6, 48 + 28, n}}, body); + const std::uint32_t words[5] = {0x07230203, 0x00010500, 0, 1, 0}; + const auto write = [&](const std::filesystem::path& file, const std::string& text) { + std::ofstream out(file, std::ios::binary | std::ios::trunc); + out << text; }; + const std::string game = "\"cs_game\": {\"stage\": \"cs\", \"fssm_sha256\": \"" + hash + "\"}"; + const std::string vs_entry = "{\"stage\": \"vs\", \"fssm_sha256\": \"" + vs_hash + + "\", \"input_signature\": [{\"semantic\": \"POSITION\", \"semantic_index\": 0, " + "\"register\": 0, \"system_value\": 0, \"component_type\": \"float\"}]}"; + const std::string ps_entry = "{\"stage\": \"ps\", \"fssm_sha256\": \"" + ps_hash + "\"}"; std::filesystem::create_directories(dir / "fspx"); - std::filesystem::create_directories(dir / "library"); + std::filesystem::create_directories(dir / "bvh"); + std::filesystem::create_directories(dir / "exe"); + write(dir / "index.json", "{" + game + "}"); + write(dir / "fspx" / "index.json", + "{\"upscaler_00\": {\"stage\": \"cs\", \"fspx_code_sha256\": \"" + sha256_hex(code) + "\"}}"); + write(dir / "bvh" / "index.json", + "{\"BuilderProgram\": {\"stage\": \"cs\", \"fssm_sha256\": \"" + hash + "\"}}"); + write(dir / "exe" / "index.json", + "{\"container_00\": " + vs_entry + ",\n \"container_01\": " + ps_entry + + ",\n \"NoKey\": {\"error\": \"ValueError: synthetic\"}}"); { - std::ofstream index(dir / "index.json", std::ios::binary | std::ios::trunc); - index << "{\"cs_game\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << hash << "\"}}"; - std::ofstream dll(dir / "fspx" / "index.json", std::ios::binary | std::ios::trunc); - dll << "{\"upscaler_00\": {\"stage\": \"cs\", \"fspx_code_sha256\": \"" << sha256_hex(fspx_code(0x6000)) - << "\"}, \"shared_dll\": {\"stage\": \"cs\", \"fspx_code_sha256\": \"" << sha256_hex(shared_code) - << "\"}}"; - std::ofstream lib(dir / "library" / "index.json", std::ios::binary | std::ios::trunc); - lib << "{\"lib_cs_00007\": {\"stage\": \"cs\", \"fspx_code_sha256\": \"" << sha256_hex(code) - << "\", \"fspx_state_sha256\": \"" << sha256_hex(state) - << "\", \"bindings\": [], \"local_size\": [64, 1, 1]}, " - << "\"lib_cs_shared\": {\"stage\": \"cs\", \"fspx_code_sha256\": \"" << sha256_hex(shared_code) - << "\"}}"; - std::ofstream spv(dir / "library" / "lib_cs_00007.spv", std::ios::binary); - const std::uint32_t words[5] = {0x07230203, 0x00010500, 7, 1, 0}; + std::ofstream spv(dir / "exe" / "container_00.spv", std::ios::binary); spv.write(reinterpret_cast(words), sizeof(words)); + std::ofstream spv_ps(dir / "exe" / "container_01.spv", std::ios::binary); + spv_ps.write(reinterpret_cast(words), sizeof(words)); } - ShaderLibrary library; - CHECK(library.load(dir.string(), &error) && library.size() == 5 && library.fspx_size() == 4); - const auto found = library.fspx_candidates("cs", sha256_hex(code)); - CHECK(found.size() == 1 && found[0]->name == "library/lib_cs_00007" && found[0]->local_size[0] == 64 && - found[0]->fssm_sha256.empty()); - CHECK(library.spirv(*found[0]).size() == 5); // /library/lib_cs_00007.spv - // fspx/ loads before library/, so shared code keys preserve fspx/ entries ahead of library/ entries. - const auto shared = library.fspx_candidates("cs", sha256_hex(shared_code)); - CHECK(shared.size() == 2 && shared[0]->name == "fspx/shared_dll" && shared[1]->name == "library/lib_cs_shared"); - // As slot 67 passes it: kind 0 and kind 6 in one payload. The record's state finds it; another state doesn't. - bool ambiguous = true; - CHECK(library.program_candidates("cs", compute_program(payload(state)), &ambiguous) == found && !ambiguous); - CHECK(library.program_candidates("cs", compute_program(payload(other_state)), &ambiguous).empty()); - // The DLL's entries are still there, and the game's own by FSSM hash. - CHECK(library.fspx_candidates("cs", sha256_hex(fspx_code(0x6000))).at(0)->name == "fspx/upscaler_00"); - CHECK(library.find("cs", hash) && library.find("cs", hash)->name == "cs_game"); - // A broken library index leaves the others loaded; a missing one is not an error either. - { - std::ofstream lib(dir / "library" / "index.json", std::ios::binary | std::ios::trunc); - lib << "{broken"; - } - CHECK(library.load(dir.string(), &error) && library.size() == 3 && library.fspx_size() == 2 && - library.fspx_candidates("cs", sha256_hex(code)).empty()); - std::filesystem::remove(dir / "library" / "index.json"); - CHECK(library.load(dir.string(), &error) && library.size() == 3 && library.fspx_size() == 2); + ShaderLibrary exe; + CHECK(exe.load(dir.string(), &error) && exe.size() == 5 && exe.fspx_size() == 1 && exe.bvh_size() == 1 && + exe.exe_size() == 2); + const ShaderEntry* vs = exe.find("vs", vs_hash); + const ShaderEntry* ps = exe.find("ps", ps_hash); + CHECK(vs && vs->name == "exe/container_00" && vs->input_signature.size() == 1 && + vs->input_signature[0].semantic == "POSITION" && exe.spirv(*vs).size() == 5); + CHECK(ps && ps->name == "exe/container_01" && exe.spirv(*ps).size() == 5); + CHECK(exe.candidates("ps", vs_hash).empty() && exe.candidates("vs", ps_hash).empty() && + exe.fspx_candidates("vs", vs_hash).empty()); + // Same program in main index and exe/: main comes first (index order). + write(dir / "index.json", "{" + game + ",\n \"vs_same\": " + vs_entry + "}"); + CHECK(exe.load(dir.string(), &error) && exe.size() == 6 && exe.exe_size() == 2); + const auto both = exe.candidates("vs", vs_hash); + CHECK(both.size() == 2 && both[0]->name == "vs_same" && both[1]->name == "exe/container_00"); + write(dir / "index.json", "{" + game + "}"); + // Broken or missing exe/index.json leaves main, fspx, and bvh loaded and resets exe_size() to 0. + write(dir / "exe" / "index.json", "{broken"); + CHECK(exe.load(dir.string(), &error) && exe.size() == 3 && exe.exe_size() == 0 && exe.bvh_size() == 1 && + exe.fspx_size() == 1 && !exe.find("vs", vs_hash)); + std::filesystem::remove(dir / "exe" / "index.json"); + CHECK(exe.load(dir.string(), &error) && exe.size() == 3 && exe.exe_size() == 0 && exe.find("cs", hash)); std::filesystem::remove_all(dir); } @@ -889,6 +897,61 @@ int main() { std::filesystem::remove_all(dir); } + // Pipeline-library entries: the compute programs of the library in shaders.rpf, translated by make_game.py into + // /library/index.json (named "library/"), are found by the same two keys as the DLL's FSPX programs, + // next to /fspx/. The executable's slot-67 description carries kind 0 (the record's state blob) and kind 6. + { + const auto code = fspx_code(0x5000); + std::vector state(28, 0), other_state(28, 0); + state[12] = 64; // word 3: NumThreadsX + other_state[12] = 32; + const auto n = std::uint32_t(code.size()); + const auto payload = [&](const std::vector& kind0) { + std::vector body = kind0; + body.insert(body.end(), code.begin(), code.end()); + return fspx_payload({{0, 48, 28}, {6, 48 + 28, n}}, body); + }; + std::filesystem::create_directories(dir / "fspx"); + std::filesystem::create_directories(dir / "library"); + { + std::ofstream index(dir / "index.json", std::ios::binary | std::ios::trunc); + index << "{\"cs_game\": {\"stage\": \"cs\", \"fssm_sha256\": \"" << hash << "\"}}"; + std::ofstream dll(dir / "fspx" / "index.json", std::ios::binary | std::ios::trunc); + dll << "{\"upscaler_00\": {\"stage\": \"cs\", \"fspx_code_sha256\": \"" << sha256_hex(fspx_code(0x6000)) + << "\"}}"; + std::ofstream lib(dir / "library" / "index.json", std::ios::binary | std::ios::trunc); + lib << "{\"lib_cs_00007\": {\"stage\": \"cs\", \"fspx_code_sha256\": \"" << sha256_hex(code) + << "\", \"fspx_state_sha256\": \"" << sha256_hex(state) + << "\", \"bindings\": [], \"local_size\": [64, 1, 1]}}"; + std::ofstream spv(dir / "library" / "lib_cs_00007.spv", std::ios::binary); + const std::uint32_t words[5] = {0x07230203, 0x00010500, 7, 1, 0}; + spv.write(reinterpret_cast(words), sizeof(words)); + } + ShaderLibrary library; + CHECK(library.load(dir.string(), &error) && library.size() == 3 && library.fspx_size() == 2); + const auto found = library.fspx_candidates("cs", sha256_hex(code)); + CHECK(found.size() == 1 && found[0]->name == "library/lib_cs_00007" && found[0]->local_size[0] == 64 && + found[0]->fssm_sha256.empty()); + CHECK(library.spirv(*found[0]).size() == 5); // /library/lib_cs_00007.spv + // As slot 67 passes it: kind 0 and kind 6 in one payload. The record's state finds it; another state doesn't. + bool ambiguous = true; + CHECK(library.program_candidates("cs", compute_program(payload(state)), &ambiguous) == found && !ambiguous); + CHECK(library.program_candidates("cs", compute_program(payload(other_state)), &ambiguous).empty()); + // The DLL's entries are still there, and the game's own by FSSM hash. + CHECK(library.fspx_candidates("cs", sha256_hex(fspx_code(0x6000))).at(0)->name == "fspx/upscaler_00"); + CHECK(library.find("cs", hash) && library.find("cs", hash)->name == "cs_game"); + // A broken library index leaves the others loaded; a missing one is not an error either. + { + std::ofstream lib(dir / "library" / "index.json", std::ios::binary | std::ios::trunc); + lib << "{broken"; + } + CHECK(library.load(dir.string(), &error) && library.size() == 2 && library.fspx_size() == 1 && + library.fspx_candidates("cs", sha256_hex(code)).empty()); + std::filesystem::remove(dir / "library" / "index.json"); + CHECK(library.load(dir.string(), &error) && library.size() == 2 && library.fspx_size() == 1); + std::filesystem::remove_all(dir); + } + // The review case on #1911: one kind-6 program in two containers whose kind-0 entries differ (32x1x1 and // 64x1x1), translated to two different modules. A container picks its own entry by fspx_state_sha256; a bare // kind-6 program cannot tell them apart and is refused as ambiguous; with one module for the key it is accepted. diff --git a/runtime/test/title_va_alias_test.cpp b/runtime/test/title_va_alias_test.cpp new file mode 100644 index 0000000000..133f7f2e54 --- /dev/null +++ b/runtime/test/title_va_alias_test.cpp @@ -0,0 +1,68 @@ +// leonida::TitleVaAliases (src/title_va_alias.h): where an address inside a title-placed buffer (Xbox device slot +// 133) is translated to, and that everything else is left alone. No GPU. +#include "../src/title_va_alias.h" + +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +int main() { + leonida::TitleVaAliases a; + constexpr std::uint64_t title = 0x20000000000ull; // a synthetic user-mode VA far above 4 GiB + constexpr std::uint64_t size = 0x10000; + constexpr std::uint64_t arena = 0x2340000; + // Empty: identity everywhere. + EXPECT(a.size() == 0 && a.shader_va(title) == title && a.shader_va(0) == 0); + EXPECT(!a.add(title, 0, arena)); // empty range + EXPECT(!a.add(UINT64_MAX - 4, 16, arena)); // wraps + EXPECT(a.add(title, size, arena) && a.size() == 1); + // Inside: the same offset in the copy, first and last byte included. + EXPECT(a.shader_va(title) == arena); + EXPECT(a.shader_va(title + 0x123) == arena + 0x123); + EXPECT(a.shader_va(title + size - 1) == arena + size - 1); + // Negative controls: one byte before, the end itself, and an arena VA are untouched. + EXPECT(a.shader_va(title - 1) == title - 1); + EXPECT(a.shader_va(title + size) == title + size); + EXPECT(a.shader_va(arena) == arena); + // The free span around an address: between the ranges, so a window made for it never covers one. + std::uint64_t lo = 1, hi = 1; + a.gap(title + size + 5, lo, hi); + EXPECT(lo == title + size && hi == UINT64_MAX); + a.gap(title - 5, lo, hi); + EXPECT(lo == 0 && hi == title); + // Without a device's resolver, resolve only translates what was added, and counts it. + EXPECT(a.resolve(title + 4, 4, leonida::TitleVaAliases::root_view) == arena + 4); + EXPECT(a.resolve(title - 4, 4, leonida::TitleVaAliases::root_view) == title - 4); + EXPECT(a.translated(leonida::TitleVaAliases::root_view) == 1); + a.note(title + 8, leonida::TitleVaAliases::vertex_view); + a.note(title - 8, leonida::TitleVaAliases::vertex_view); + EXPECT(a.untranslated(leonida::TitleVaAliases::vertex_view) == 1); + // The title's memory: a commit inside a reservation is one range; outside every range is not the title's. + std::uint64_t mlo = 0, mhi = 0; + a.add_title_memory(0x40000000, 0x100000); + a.add_title_memory(0x40010000, 0x1000); + EXPECT(a.title_memory(0x40080000, mlo, mhi) && mlo == 0x40000000 && mhi == 0x40100000); + EXPECT(!a.title_memory(0x40100000, mlo, mhi) && !a.title_memory(0x3FFFFFFF, mlo, mhi)); + a.remove_title_memory(0x40000000); + EXPECT(!a.title_memory(0x40080000, mlo, mhi)); + // A wrapping target (an import below heap_base) is kept as is: modular arithmetic. + constexpr std::uint64_t below = 0xFFFFFFFFFFF00000ull; + EXPECT(a.add(title + 0x100000, size, below) && a.shader_va(title + 0x100010) == below + 0x10); + // A new buffer over part of a live range replaces it; the old range's removal does not touch the new one. + EXPECT(a.add(title + 0x8000, size, 0x5000000)); + EXPECT(a.shader_va(title) == title); // the replaced range is gone entirely + EXPECT(a.shader_va(title + 0x8000) == 0x5000000); + a.remove(title, arena); // stale: nothing starts there any more + EXPECT(a.shader_va(title + 0x8000) == 0x5000000); + a.remove(title + 0x8000, 0x1234); // another target: kept + EXPECT(a.shader_va(title + 0x8000) == 0x5000000); + a.remove(title + 0x8000, 0x5000000); + EXPECT(a.shader_va(title + 0x8000) == title + 0x8000); + a.remove(title + 0x100000, below); + EXPECT(a.size() == 0 && a.shader_va(title + 0x100010) == title + 0x100010); + std::printf("title_va_alias: translation inside a title-placed range, identity outside it and after release\n"); + return 0; +} diff --git a/runtime/test/title_window_test.cpp b/runtime/test/title_window_test.cpp new file mode 100644 index 0000000000..b3ea9ac825 --- /dev/null +++ b/runtime/test/title_window_test.cpp @@ -0,0 +1,104 @@ +// find_title_window (shims/title_window.h): the window PresentX shows a GDKX title's frames in. +// +// The windows belong to a thread that never pumps its messages, as the title's window thread may be busy at the first +// PresentX: the lookup must still answer at once. The negative control shows that thread really does not answer a +// sent message (WM_GETTEXT, what GetWindowTextW sends across threads, times out), so a lookup that sent one would block. + +#include "title_window.h" + +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +namespace { + +struct Windows { + HWND title = nullptr; // visible, unowned, the largest client area: the title's window + HWND small = nullptr; // visible, unowned, smaller + HWND hidden = nullptr; // never shown (like the IME windows and a driver's dummy window) + HWND owned = nullptr; // visible but owned by `title` (a dialog, not a top-level frame) + HWND tool = nullptr; // visible tool window +}; + +HWND make(const wchar_t* name, DWORD ex_style, DWORD style, int width, int height, HWND owner) { + return CreateWindowExW(ex_style | WS_EX_NOACTIVATE, L"LeonidaTitleWindowTest", name, style, 0, 0, width, height, + owner, nullptr, GetModuleHandleW(nullptr), nullptr); +} + +} // namespace + +int main() { + WNDCLASSW window_class{}; + window_class.lpfnWndProc = DefWindowProcW; + window_class.hInstance = GetModuleHandleW(nullptr); + window_class.lpszClassName = L"LeonidaTitleWindowTest"; + EXPECT(RegisterClassW(&window_class)); + + // A process with no window of its own has no title window. + EXPECT(rt::d3d12::find_title_window(GetCurrentProcessId()) == nullptr); + + Windows windows; + HANDLE made = CreateEventW(nullptr, TRUE, FALSE, nullptr); + HANDLE release = CreateEventW(nullptr, TRUE, FALSE, nullptr); + EXPECT(made && release); + std::thread window_thread([&] { + windows.hidden = make(L"hidden", 0, WS_OVERLAPPEDWINDOW, 900, 700, nullptr); + windows.small = make(L"small", 0, WS_OVERLAPPEDWINDOW | WS_VISIBLE, 160, 120, nullptr); + windows.title = make(L"title", 0, WS_OVERLAPPEDWINDOW | WS_VISIBLE, 320, 240, nullptr); + windows.owned = make(L"owned", 0, WS_OVERLAPPEDWINDOW | WS_VISIBLE, 800, 600, windows.title); + windows.tool = make(L"tool", WS_EX_TOOLWINDOW, WS_OVERLAPPEDWINDOW | WS_VISIBLE, 800, 600, nullptr); + SetEvent(made); + WaitForSingleObject(release, INFINITE); // no message loop: like a title window thread that is busy + DestroyWindow(windows.tool); + DestroyWindow(windows.owned); + DestroyWindow(windows.title); + DestroyWindow(windows.small); + DestroyWindow(windows.hidden); + }); + WaitForSingleObject(made, INFINITE); + int result = 0; + [&] { + auto check = [&](bool ok, int line, const char* what) { + if (!ok && !result) { + std::fprintf(stderr, "line %d: %s\n", line, what); + result = 1; + } + }; +#define CHECK(condition) check((condition), __LINE__, #condition) + CHECK(windows.title && windows.small && windows.hidden && windows.owned && windows.tool); + + // Negative control: the window thread does not answer a sent message. + wchar_t text[16]{}; + DWORD_PTR copied = 0; + CHECK(!SendMessageTimeoutW(windows.title, WM_GETTEXT, 16, reinterpret_cast(text), SMTO_BLOCK, 200, + &copied)); + + // The lookup answers at once anyway, and picks the visible unowned non-tool window with the largest client + // area: not the larger hidden, owned or tool windows. + const auto start = std::chrono::steady_clock::now(); + const HWND found = rt::d3d12::find_title_window(GetCurrentProcessId()); + const auto took = std::chrono::steady_clock::now() - start; + CHECK(found == windows.title); + CHECK(took < std::chrono::milliseconds(100)); + + // The runtime's own window, excluded, is never the answer. + CHECK(rt::d3d12::find_title_window(GetCurrentProcessId(), windows.title) == windows.small); + // Another process's windows are not this title's. + CHECK(rt::d3d12::find_title_window(GetCurrentProcessId() ^ 0x40000000u) == nullptr); +#undef CHECK + }(); + SetEvent(release); + window_thread.join(); + CloseHandle(made); + CloseHandle(release); + if (result) return result; + + // Gone with its windows. + EXPECT(rt::d3d12::find_title_window(GetCurrentProcessId()) == nullptr); + std::puts("title_window: ok"); + return 0; +} diff --git a/runtime/test/unimplemented_policy_test.cpp b/runtime/test/unimplemented_policy_test.cpp index 8941901296..6f893766a9 100644 --- a/runtime/test/unimplemented_policy_test.cpp +++ b/runtime/test/unimplemented_policy_test.cpp @@ -231,6 +231,8 @@ void test_classification() { check(cls("gameinput.dll", "GameInputCreate") == ReturnClass::HResult, "GameInputCreate is hresult"); check(cls("dstorage_xs.dll", "DStorageGetFactory") == ReturnClass::HResult, "the console dstorage name is hresult"); + check(cls("xcrdapi.dll", "DStorageGetFactory") == ReturnClass::HResult, "xcrdapi's DStorageGetFactory is hresult"); + check(cls("xcrdapi.dll", "XCrdLeonidaPolicyProbe") == ReturnClass::Other, "other xcrdapi imports are other"); check(cls("xg_xs.dll", "XGCreateTexture2DComputer") == ReturnClass::Other, "unmeasured xg_xs import is other"); check(cls("acphal.dll", "AcpHalCreate") == ReturnClass::HResult, "AcpHalCreate is hresult"); check(cls("acphal.dll", "ApuFree") == ReturnClass::Other, "ApuFree returns void"); diff --git a/runtime/test/vk_pipeline_check.cpp b/runtime/test/vk_pipeline_check.cpp index 7b4f8d5338..ec9a395194 100644 --- a/runtime/test/vk_pipeline_check.cpp +++ b/runtime/test/vk_pipeline_check.cpp @@ -47,7 +47,7 @@ // pipelines stage's retry. #include "vulkan_loader.h" #include "vk_device_pick.h" -#include "pipeline_cache_file.h" +#include "../src/pipeline_cache_file.h" #include "pipeline_cache_snapshot.h" #include "large_module_gate.h" #include "pipeline_summary.h" @@ -1058,11 +1058,10 @@ int main(int argc, char** argv) { return failed ? 1 : 0; } - // Scan selected shaders to request only the optional extensions they actually use. - bool want_mesh = false, want_bary = false, want_lock = false, want_m8 = false, want_fma = false, want_clock = false; + // Collect optional features requested by the selected shaders. + bool want_mesh = false, want_bary = false, want_lock = false, want_fma = false, want_clock = false; for (auto& [_, meta] : work) { if (meta->stage == "ms") want_mesh = true; - if (meta->needs_maintenance8) want_m8 = true; for (const auto& feat : meta->features) { if (feat == "meshShader") want_mesh = true; else if (feat == "fragmentShaderBarycentric") want_bary = true; @@ -1114,7 +1113,7 @@ int main(int argc, char** argv) { auto has = [&](const char* e) { for (auto& x : exts) if (!std::strcmp(x.extensionName, e)) return true; return false; }; std::vector enable; - // Query what the GPU supports for core 1.2/1.3 and any optional extensions requested by `work`. + // Query the core and optional device features used by the checker. VkPhysicalDeviceMeshShaderFeaturesEXT mesh{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_FEATURES_EXT}; VkPhysicalDeviceFragmentShaderBarycentricFeaturesKHR bary{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_BARYCENTRIC_FEATURES_KHR}; VkPhysicalDeviceFragmentShaderInterlockFeaturesEXT lock{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FRAGMENT_SHADER_INTERLOCK_FEATURES_EXT}; @@ -1141,9 +1140,9 @@ int main(int argc, char** argv) { const bool ext_bary = link(&bary, reinterpret_cast(&bary), VK_KHR_FRAGMENT_SHADER_BARYCENTRIC_EXTENSION_NAME, want_bary); const bool ext_lock = link(&lock, reinterpret_cast(&lock), VK_EXT_FRAGMENT_SHADER_INTERLOCK_EXTENSION_NAME, want_lock); #ifdef VK_KHR_MAINTENANCE_8_EXTENSION_NAME - const bool ext_m8 = link(&m8, reinterpret_cast(&m8), VK_KHR_MAINTENANCE_8_EXTENSION_NAME, want_m8); -#else - (void)want_m8; + // The runtime enables maintenance8 whenever supported. The NVIDIA driver keys cached pipelines on this + // device feature even for shaders that do not use it, so match the runtime for every batch. + const bool ext_m8 = link(&m8, reinterpret_cast(&m8), VK_KHR_MAINTENANCE_8_EXTENSION_NAME, true); #endif #ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME VkPhysicalDeviceShaderFmaFeaturesKHR fma{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_SHADER_FMA_FEATURES_KHR}; @@ -1172,6 +1171,12 @@ int main(int argc, char** argv) { VkPhysicalDeviceFeatures2 f2{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2}; f2.pNext = chain; vkGetPhysicalDeviceFeatures2(pd, &f2); // fills every linked struct with what's supported + // The runtime's device (create_vulkan_device_standalone) never enables these three, and a driver makes them part + // of a pipeline's cache key: with any of them on here, the cache this tool saves does not hit in gta6rt + // (pipeline_cache_seed_test; docs/pipeline_check.md, "The cache and the runtime's device"). + f2.features.robustBufferAccess = VK_FALSE; + f12.scalarBlockLayout = VK_FALSE; + f13.robustImageAccess = VK_FALSE; VkPhysicalDeviceMeshShaderPropertiesEXT mesh_props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MESH_SHADER_PROPERTIES_EXT}; if (ext_mesh && mesh.meshShader) { VkPhysicalDeviceProperties2 mesh_device_props{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2}; diff --git a/runtime/test/vk_present_dump_test.cpp b/runtime/test/vk_present_dump_test.cpp new file mode 100644 index 0000000000..a4497166f9 --- /dev/null +++ b/runtime/test/vk_present_dump_test.cpp @@ -0,0 +1,113 @@ +// Present a small solid texture through the window blit and the PresentX plane composer. Only the composed +// image has a black lower half. Decode the PNGs independently with the conformance tool's WIC reader. +#define VK_USE_PLATFORM_WIN32_KHR +#include +#include + +#include "test_temp_dir.h" +#include "vk_test_device.h" +#include "../src/vulkan_present.h" +#include "../../tools/conformance/native/src/png_io.h" + +#include +#include +#include +#include +#include + +#define EXPECT(condition) do { \ + if (!(condition)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #condition); return 1; } \ +} while (0) + +int main(int argc, char** argv) { + using namespace leonida; + namespace fs = std::filesystem; + vktest::Device d; + const auto status = d.initialize(true); + if (status == vktest::DeviceStatus::unavailable) return 77; + EXPECT(status == vktest::DeviceStatus::ready); + EXPECT(SUCCEEDED(CoInitializeEx(nullptr, COINIT_MULTITHREADED))); + testfiles::ScratchDir scratch("leonida_present_dump"); + const fs::path dir = scratch.path() / "frames"; + const std::string_view mode = argc == 2 ? argv[1] : ""; + EXPECT(mode.empty() || mode == "--default" || mode == "--invalid"); + const int interval = mode == "--default" ? 60 : 2; + const auto setting = dir.wstring() + (mode == "--default" ? L"" : mode == "--invalid" ? L",0" : L",2"); + EXPECT(_wputenv_s(L"LEONIDA_PRESENT_DUMP", setting.c_str()) == 0); + // An earlier dump might be a hard link outside the requested directory. Replacing it must leave that file intact. + const auto sentinel = scratch.path() / "outside"; + if (mode == "--default") { + EXPECT(fs::create_directory(dir)); + EXPECT(std::ofstream(sentinel).put('X')); + std::error_code ec; + fs::create_hard_link(sentinel, dir / "present_000001.png", ec); // optional on filesystems without links + } + + constexpr int width = 192, height = 100; + const HINSTANCE instance = GetModuleHandleW(nullptr); + HWND window = CreateWindowExW(0, L"STATIC", L"Leonida present dump test", WS_POPUP, 0, 0, width, height, + nullptr, nullptr, instance, nullptr); + EXPECT(window); + ShowWindow(window, SW_SHOWNOACTIVATE); + VulkanContext context(d.device_proc, d.device, true); + VulkanQueue queue(context, d.queue, d.family); + EXPECT(context.loaded() && queue.ok()); + ResourceBinding back{}; + back.format = VK_FORMAT_R8G8B8A8_UNORM; + back.width = back.height = 2; + back.aspects = VK_IMAGE_ASPECT_COLOR_BIT; + back.sampled = back.color_attachment = true; + back.image = d.image(back.format, 2, 2, 1, VK_IMAGE_USAGE_SAMPLED_BIT | VK_IMAGE_USAGE_COLOR_ATTACHMENT_BIT); + EXPECT(back.image); + context.add_resource(1, back, VK_IMAGE_LAYOUT_UNDEFINED); + CommandList commands; + EXPECT(commands.transition({1, 0, d3d12_state::common, d3d12_state::render_target})); + EXPECT(commands.clear_render_target({1, 0, 0, 1}, {1.0f, 0.4f, 0.0f, 1.0f})); + EXPECT(commands.transition({1, 0, d3d12_state::render_target, d3d12_state::common})); + EXPECT(commands.close()); + const CommandList* list = &commands; + EXPECT(queue.execute({&list, 1}) == ReplayResult::success); + + VkWin32SurfaceCreateInfoKHR info{VK_STRUCTURE_TYPE_WIN32_SURFACE_CREATE_INFO_KHR}; + info.hinstance = instance; + info.hwnd = window; + VkSurfaceKHR surface{}; + EXPECT(d.instance_fn("vkCreateWin32SurfaceKHR")( + d.instance, &info, nullptr, &surface) == VK_SUCCESS); + { + VulkanPresenter presenter(context, d.instance_proc, d.instance, d.physical, d.queue, d.family, surface, + false, [] { return VkExtent2D{width, height}; }); + EXPECT(presenter.ok()); + EXPECT(presenter.present(1, true) == VK_SUCCESS); + for (int i = 1; i < interval; ++i) EXPECT(presenter.present_blank(true) == VK_SUCCESS); + PresentPlanes planes; + planes.plane[0].source = 1; + planes.plane[0].dest[3] = 0.5f; + EXPECT(presenter.present_planes(planes, true) == VK_SUCCESS); + EXPECT(presenter.presented() == unsigned(interval + 1) && presenter.composed_presents() == 1); + } + DestroyWindow(window); + EXPECT(d.validation_errors() == 0); + if (mode == "--invalid") { + EXPECT(!fs::exists(dir)); + CoUninitialize(); + return 0; + } + if (mode == "--default") EXPECT(fs::file_size(sentinel) == 1 && std::ifstream(sentinel).get() == 'X'); + for (bool composed : {false, true}) { + const auto* name = !composed ? "present_000001.png" : interval == 2 ? "present_000003.png" : "present_000061.png"; + PixelSurface png; + EXPECT(ReadPngFile(dir / name, png)); + EXPECT(png.width == width && png.height == height); + for (int y = 0; y < height; ++y) { + const bool black = composed && y >= height / 2; + const std::array expected = black ? std::array{0, 0, 0, 255} + : std::array{255, 102, 0, 255}; + for (int x = 0; x < width; ++x) + EXPECT(std::equal(expected.begin(), expected.end(), png.At(x, y))); + } + } + EXPECT(std::distance(fs::directory_iterator(dir), fs::directory_iterator{}) == 2); + CoUninitialize(); + return 0; +} diff --git a/runtime/test/vk_test_device.h b/runtime/test/vk_test_device.h index 5cccd1836e..0aca467878 100644 --- a/runtime/test/vk_test_device.h +++ b/runtime/test/vk_test_device.h @@ -106,6 +106,11 @@ class Device { bool storage_buffer_8bit = false; // storageBuffer8BitAccess enabled bool conditional_rendering = false; // VK_EXT_conditional_rendering enabled, where available bool host_image_copy = false; // VK_EXT_host_image_copy and hostImageCopy enabled + // VK_KHR_maintenance5 enabled, where VK_FORMAT_A8_UNORM_KHR can be sampled and blended as a colour attachment, as + // gta6rt enables it (VulkanDeviceInfo::a8_render_target). + bool a8_render_target = false; + // VK_EXT_external_memory_host is enabled when non-zero: its minImportedHostPointerAlignment. + VkDeviceSize host_pointer_alignment = 0; // create(true) only: VK_KHR (else EXT) swapchain_maintenance1 and its feature enabled, with the surface half on the // instance, so a vsync swapchain can switch to IMMEDIATE or FIFO_RELAXED per present. bool swapchain_maintenance1 = false; @@ -123,8 +128,6 @@ class Device { leonida::SubgroupSizeCaps subgroup; bool custom_border_color = false; // VK_EXT_custom_border_color and customBorderColors enabled bool custom_border_color_without_format = false; - // VK_EXT_external_memory_host is enabled when non-zero: its minImportedHostPointerAlignment. - VkDeviceSize host_pointer_alignment = 0; Device() = default; Device(const Device&) = delete; @@ -499,6 +502,39 @@ class Device { host_copy.pNext = *v13_.next(); // after the conditional rendering features, if any *v13_.next() = &host_copy; } + // VK_EXT_external_memory_host where the device has it (OpenExistingHeapFromAddress). + for (const auto& extension : extensions) { + if (std::strcmp(extension.extensionName, VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME) != 0) continue; + VkPhysicalDeviceExternalMemoryHostPropertiesEXT host_memory{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT}; + VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &host_memory}; + instance_fn("vkGetPhysicalDeviceProperties2")(physical, &properties); + host_pointer_alignment = host_memory.minImportedHostPointerAlignment; + } + +#ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME + VkPhysicalDeviceMaintenance5FeaturesKHR maintenance5{ + VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_MAINTENANCE_5_FEATURES_KHR}; + if (std::any_of(extensions.begin(), extensions.end(), [](const auto& e) { + return std::strcmp(e.extensionName, VK_KHR_MAINTENANCE_5_EXTENSION_NAME) == 0; + })) { + VkPhysicalDeviceFeatures2 query{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_FEATURES_2, &maintenance5}; + instance_fn("vkGetPhysicalDeviceFeatures2")(physical, &query); + VkFormatProperties a8{}; + instance_fn("vkGetPhysicalDeviceFormatProperties")( + physical, VK_FORMAT_A8_UNORM_KHR, &a8); + const VkFormatFeatureFlags needed = VK_FORMAT_FEATURE_SAMPLED_IMAGE_BIT | + VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BIT | + VK_FORMAT_FEATURE_COLOR_ATTACHMENT_BLEND_BIT | + VK_FORMAT_FEATURE_TRANSFER_SRC_BIT | VK_FORMAT_FEATURE_TRANSFER_DST_BIT; + a8_render_target = + maintenance5.maintenance5 == VK_TRUE && (a8.optimalTilingFeatures & needed) == needed; + } + if (a8_render_target) { + maintenance5.pNext = *v13_.next(); + *v13_.next() = &maintenance5; + } +#endif #ifdef VK_KHR_SHADER_FMA_EXTENSION_NAME // VK_KHR_shader_fma where the device has it: translated shaders built with --fma khr use OpFmaKHR. @@ -550,16 +586,6 @@ class Device { *v13_.next() = &custom_border; } - // VK_EXT_external_memory_host where the device has it (OpenExistingHeapFromAddress). - for (const auto& extension : extensions) { - if (std::strcmp(extension.extensionName, VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME) != 0) continue; - VkPhysicalDeviceExternalMemoryHostPropertiesEXT host_memory{ - VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_EXTERNAL_MEMORY_HOST_PROPERTIES_EXT}; - VkPhysicalDeviceProperties2 properties{VK_STRUCTURE_TYPE_PHYSICAL_DEVICE_PROPERTIES_2, &host_memory}; - instance_fn("vkGetPhysicalDeviceProperties2")(physical, &properties); - host_pointer_alignment = host_memory.minImportedHostPointerAlignment; - } - VkDeviceCreateInfo device_info{VK_STRUCTURE_TYPE_DEVICE_CREATE_INFO, &enable12}; device_info.queueCreateInfoCount = std::uint32_t(queue_infos.size()); device_info.pQueueCreateInfos = queue_infos.data(); @@ -575,6 +601,9 @@ class Device { if (vertex_attribute_divisor) device_extensions.push_back(divisor_extension); if (conditional_rendering) device_extensions.push_back(conditional_extension); if (host_image_copy) device_extensions.push_back(host_image_copy_name); +#ifdef VK_KHR_MAINTENANCE_5_EXTENSION_NAME + if (a8_render_target) device_extensions.push_back(VK_KHR_MAINTENANCE_5_EXTENSION_NAME); +#endif if (host_pointer_alignment) device_extensions.push_back(VK_EXT_EXTERNAL_MEMORY_HOST_EXTENSION_NAME); const char* swapchain = "VK_KHR_swapchain"; if (presentation) device_extensions.push_back(swapchain); diff --git a/runtime/test/xbox_bvh_builder_test.cpp b/runtime/test/xbox_bvh_builder_test.cpp new file mode 100644 index 0000000000..3deb816b46 --- /dev/null +++ b/runtime/test/xbox_bvh_builder_test.cpp @@ -0,0 +1,430 @@ +// The XboxBvhBuilder.dll shim (shims/xbox_bvh_builder.cpp) on the standalone Vulkan device, called the way the +// title's imports bind: rt::shims::find("xboxbvhbuilder.dll", ), `this` first. A BLAS and a TLAS are +// built through BuildRaytracingAccelerationStructureBatched2X, the BLAS is compacted through +// CopyRaytracingAccelerationStructure, and the three are written to as .bin + .json for +// `python -I tools/xdxr_bvh.py check-build ` (ctest: xbox_bvh_builder + xbox_bvh_builder_check), which +// checks the records and traces rays against brute force. Also checked: the shim's prebuild sizes are the layer's, +// an element asking for offline statistics is skipped and leaves its destination untouched, a non-empty XDXR stream +// is accepted, rehydration answers E_NOTIMPL, and builders are released. +// +// xbox_bvh_builder_test the shim +// xbox_bvh_builder_test --console run with LEONIDA_BVH_BUILDER=console: nothing is registered +// +// Exit 77 without a Vulkan device. No game files. +#include "../shims/d3d12_com.h" +#include "../shims/d3d12_xs_device.h" +#include "../shims/shims.h" +#include "../src/xdxr_descs.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace rt::shims { +size_t xbox_bvh_builder_live_count(); +} + +namespace { + +namespace xdxr = leonida::xdxr; + +int g_checks = 0; +int g_failures = 0; + +void check(bool condition, const char* what) { + ++g_checks; + std::printf("%s %s\n", condition ? "PASS" : "FAIL", what); + if (!condition) ++g_failures; +} + +template struct Ref { + T* p = nullptr; + ~Ref() { if (p) p->Release(); } + T* operator->() const { return p; } + T** put() { return &p; } +}; + +int fail(const char* what, HRESULT hr = S_OK) { + std::fprintf(stderr, "FAIL: %s (hr 0x%08lx)\n", what, static_cast(hr)); + return 1; +} + +HRESULT buffer(ID3D12Device* device, D3D12_HEAP_TYPE heap, UINT64 size, D3D12_RESOURCE_STATES state, + D3D12_RESOURCE_FLAGS flags, ID3D12Resource** out) { + D3D12_HEAP_PROPERTIES props{}; + props.Type = heap; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + desc.Width = size ? size : 1; + desc.Height = 1; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.SampleDesc.Count = 1; + desc.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + desc.Flags = flags; + return device->CreateCommittedResource(&props, D3D12_HEAP_FLAG_NONE, &desc, state, nullptr, IID_PPV_ARGS(out)); +} + +std::string num(double x) { + char s[64]; + std::snprintf(s, sizeof s, "%.9g", x); + return s; +} + +bool write_file(const std::string& path, const void* data, std::size_t bytes) { + std::ofstream f(path, std::ios::binary); + f.write(static_cast(data), std::streamsize(bytes)); + return bool(f); +} + +// The exports, as the executable imports them. +constexpr const char kDll[] = "xboxbvhbuilder.dll"; +constexpr const char kConstruct[] = "??0XboxBvhBuilder@@QEAA@PEAUID3D12Device11@@_N@Z"; +constexpr const char kDestruct[] = "??1XboxBvhBuilder@@QEAA@XZ"; +constexpr const char kMorton[] = "?Set64BitMortonCodes@XboxBvhBuilder@@QEAAX_N@Z"; +constexpr const char kPrebuild[] = + "?GetRaytracingAccelerationStructurePrebuildInfo@XboxBvhBuilder@@QEAAXPEBUD3D12_BUILD_RAYTRACING_ACCELERATION_" + "STRUCTURE_INPUTS@@PEBUD3D12XBOX_XDXR_STREAM_DESC@@PEAUD3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO@@@Z"; +constexpr const char kBatched[] = + "?BuildRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList6@@IPEBUD3D12" + "XBOX_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_BATCHED_DESC2@@@Z"; +constexpr const char kCopy[] = + "?CopyRaytracingAccelerationStructure@XboxBvhBuilder@@QEAAXPEAUID3D12GraphicsCommandList4@@_K1W4D3D12_" + "RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE@@@Z"; +constexpr const char kRehydrate[] = + "?RehydrateRaytracingAccelerationStructureBatched2X@XboxBvhBuilder@@QEAAJPEAUID3D12GraphicsCommandList8@@IPEBU" + "D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC@@PEB_K@Z"; + +using Construct = void*(*)(void*, void*, bool); +using Destruct = void (*)(void*); +using Morton = void (*)(void*, bool); +using Prebuild = void (*)(void*, const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS*, const xdxr::StreamDesc*, + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO*); +using Batched = void (*)(void*, void*, UINT, const xdxr::BatchedDesc2*); +using Copy = void (*)(void*, void*, UINT64, UINT64, D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE); +using Rehydrate = HRESULT (*)(void*, void*, UINT, const D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC*, + const UINT64*); + +template F shim(const char* name) { return reinterpret_cast(rt::shims::find(kDll, name)); } + +} // namespace + +int main(int argc, char** argv) { + if (argc < 2) { + std::fprintf(stderr, "usage: xbox_bvh_builder_test | --console\n"); + return 2; + } + if (std::strcmp(argv[1], "--console") == 0) { + // LEONIDA_BVH_BUILDER=console: the imports must bind to the bundled DLL, so the shim registers nothing. + check(shim(kConstruct) == nullptr && shim(kBatched) == nullptr && + !rt::shims::owns_dll(kDll), + "LEONIDA_BVH_BUILDER=console registers none of the exports"); + std::printf("xbox_bvh_builder_test: %d of %d checks failed\n", g_failures, g_checks); + return g_failures ? 1 : 0; + } + const std::string dir = argv[1]; + std::error_code ec; + std::filesystem::create_directories(dir, ec); + for (const auto& entry : std::filesystem::directory_iterator(dir, ec)) { + const auto ext = entry.path().extension(); + if (ext == ".bin" || ext == ".json") std::filesystem::remove(entry.path(), ec); + } + + // ---- the seven exports are registered ---- + const auto construct = shim(kConstruct); + const auto destruct = shim(kDestruct); + const auto morton = shim(kMorton); + const auto prebuild = shim(kPrebuild); + const auto batched = shim(kBatched); + const auto copy = shim(kCopy); + const auto rehydrate = shim(kRehydrate); + check(construct && destruct && morton && prebuild && batched && copy && rehydrate && rt::shims::owns_dll(kDll), + "the seven exports the executable imports are served by the shim"); + if (!(construct && destruct && morton && prebuild && batched && copy && rehydrate)) return 1; + + char rt_as[8] = {}; + std::size_t rt_as_length = 0; + if (getenv_s(&rt_as_length, rt_as, "LEONIDA_RT_AS") == 0 && rt_as_length > 1 && std::strcmp(rt_as, "khr") == 0) { + std::puts("SKIP: LEONIDA_RT_AS=khr"); + return 77; + } + Ref device; + if (FAILED(rt::d3d12::create_vulkan_device_standalone(IID_PPV_ARGS(device.put())))) { + std::puts("SKIP: no Vulkan D3D12 device"); + return 77; + } + + // ---- the builder object: the title's storage, larger than anything the shim could write ---- + alignas(16) unsigned char builder[256]; + std::memset(builder, 0xab, sizeof builder); + check(construct(builder, device.p, true) == builder, "the constructor returns `this`"); + bool untouched = true; + for (unsigned char b : builder) untouched = untouched && b == 0xab; + check(untouched && rt::shims::xbox_bvh_builder_live_count() == 1, + "nothing is written into the title's builder object; its state is kept aside"); + morton(builder, true); + + // ---- geometry: a triangle soup ---- + std::mt19937 rng(23); + std::uniform_real_distribution spread(-4.0f, 4.0f), jitter(-0.6f, 0.6f); + const UINT tris = 400; + std::vector soup; + for (UINT t = 0; t < tris; ++t) { + const float c[3] = {spread(rng), spread(rng), spread(rng)}; + for (int k = 0; k < 9; ++k) soup.push_back(c[k % 3] + jitter(rng)); + } + const UINT64 soup_bytes = soup.size() * 4; + Ref upload; + HRESULT hr = buffer(device.p, D3D12_HEAP_TYPE_UPLOAD, 256 + soup_bytes + 3 * 64, D3D12_RESOURCE_STATE_GENERIC_READ, + D3D12_RESOURCE_FLAG_NONE, upload.put()); + if (FAILED(hr)) return fail("upload buffer", hr); + char* mapped = nullptr; + if (FAILED(upload->Map(0, nullptr, reinterpret_cast(&mapped)))) return fail("Map upload"); + std::memcpy(mapped, soup.data(), std::size_t(soup_bytes)); + const UINT64 soup_va = upload->GetGPUVirtualAddress(); + + D3D12_RAYTRACING_GEOMETRY_DESC geometry{}; + geometry.Type = D3D12_RAYTRACING_GEOMETRY_TYPE_TRIANGLES; + geometry.Flags = D3D12_RAYTRACING_GEOMETRY_FLAG_OPAQUE; + geometry.Triangles.VertexFormat = DXGI_FORMAT_R32G32B32_FLOAT; + geometry.Triangles.VertexCount = tris * 3; + geometry.Triangles.VertexBuffer = {soup_va, 12}; + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS blas_inputs{}; + blas_inputs.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_BOTTOM_LEVEL; + blas_inputs.Flags = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_PREFER_FAST_TRACE | + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_BUILD_FLAG_ALLOW_COMPACTION; + blas_inputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY; + blas_inputs.NumDescs = 1; + blas_inputs.pGeometryDescs = &geometry; + + // ---- GetRaytracingAccelerationStructurePrebuildInfo: the layer's sizes, with or without a stream ---- + const xdxr::StreamRecord2 record{2, 0, -1.0f, 0.0f}; // a type-2 record with its defaults + const xdxr::StreamDesc stream{sizeof record, &record}; + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO blas_info{}, layer_info{}; + prebuild(builder, &blas_inputs, &stream, &blas_info); + device->GetRaytracingAccelerationStructurePrebuildInfo(&blas_inputs, &layer_info); + check(blas_info.ResultDataMaxSizeInBytes == layer_info.ResultDataMaxSizeInBytes && + blas_info.ScratchDataSizeInBytes == layer_info.ScratchDataSizeInBytes, + "the shim's prebuild sizes are the layer's own"); + if (!blas_info.ResultDataMaxSizeInBytes) { + std::puts("SKIP: the device does not build XDXR acceleration structures (no bufferDeviceAddress)"); + return 77; + } + // The title's device is a d3d12_xs device proxy (D3D12XboxCreateDevice): a builder constructed on one reaches the + // real device behind it. + { + Ref proxy; + alignas(16) unsigned char proxied[64]; + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO through_proxy{}; + device->AddRef(); // create_device_proxy takes one reference to the real device on success + const bool wrapped = SUCCEEDED(rt::d3d12_xs::create_device_proxy(device.p, IID_PPV_ARGS(proxy.put()))); + if (!wrapped) device->Release(); + const bool made = wrapped && rt::d3d12_xs::device_proxy_real_device(proxy.p) != nullptr; + if (made) { + construct(proxied, proxy.p, true); + prebuild(proxied, &blas_inputs, nullptr, &through_proxy); + destruct(proxied); + } + check(made && through_proxy.ResultDataMaxSizeInBytes == layer_info.ResultDataMaxSizeInBytes && + through_proxy.ScratchDataSizeInBytes == layer_info.ScratchDataSizeInBytes, + "a builder constructed on a d3d12_xs device proxy uses the real device behind it"); + } + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_INPUTS tlas_inputs{}; + tlas_inputs.Type = D3D12_RAYTRACING_ACCELERATION_STRUCTURE_TYPE_TOP_LEVEL; + tlas_inputs.DescsLayout = D3D12_ELEMENTS_LAYOUT_ARRAY; + tlas_inputs.NumDescs = 2; + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_PREBUILD_INFO tlas_info{}; + prebuild(builder, &tlas_inputs, nullptr, &tlas_info); + if (!tlas_info.ResultDataMaxSizeInBytes) return fail("TLAS prebuild info is empty"); + + // ---- buffers ---- + const D3D12_RESOURCE_FLAGS uav = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + const D3D12_RESOURCE_STATES as_state = D3D12_RESOURCE_STATE_RAYTRACING_ACCELERATION_STRUCTURE; + Ref blas, refused, tlas, scratch, scratch2, info, blas_rb, refused_rb, tlas_rb, info_rb; + const UINT64 scratch_size = blas_info.ScratchDataSizeInBytes > tlas_info.ScratchDataSizeInBytes + ? blas_info.ScratchDataSizeInBytes : tlas_info.ScratchDataSizeInBytes; + if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav, blas.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, blas_info.ResultDataMaxSizeInBytes, as_state, uav, refused.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, tlas_info.ResultDataMaxSizeInBytes, as_state, uav, tlas.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, scratch_size, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, uav, scratch.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, scratch_size, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, uav, scratch2.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, 16, D3D12_RESOURCE_STATE_UNORDERED_ACCESS, uav, info.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, blas_info.ResultDataMaxSizeInBytes, + D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, blas_rb.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, blas_info.ResultDataMaxSizeInBytes, + D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, refused_rb.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, tlas_info.ResultDataMaxSizeInBytes, + D3D12_RESOURCE_STATE_COPY_DEST, D3D12_RESOURCE_FLAG_NONE, tlas_rb.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, 16, D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_FLAG_NONE, info_rb.put()))) + return fail("acceleration-structure buffers", hr); + + // ---- instances ---- + const float c = std::cos(0.9f), s = std::sin(0.9f); + const float xforms[2][12] = {{1, 0, 0, 0, 0, 1, 0, 0, 0, 0, 1, 0}, {c, 0, s, 10, 0, 1, 0, -2, -s, 0, c, 1}}; + D3D12_RAYTRACING_INSTANCE_DESC instances[2]{}; + for (int i = 0; i < 2; ++i) { + std::memcpy(instances[i].Transform, xforms[i], sizeof xforms[i]); + instances[i].InstanceID = 40 + i; + instances[i].InstanceMask = 0xff; + instances[i].AccelerationStructure = blas->GetGPUVirtualAddress(); + } + const UINT64 instances_at = (soup_bytes + 255) / 256 * 256; + std::memcpy(mapped + instances_at, instances, sizeof instances); + upload->Unmap(0, nullptr); + tlas_inputs.InstanceDescs = upload->GetGPUVirtualAddress() + instances_at; + + D3D12_COMMAND_QUEUE_DESC qd{}; + qd.Type = D3D12_COMMAND_LIST_TYPE_DIRECT; + Ref queue; + Ref allocator; + Ref list; + Ref fence; + if (FAILED(device->CreateCommandQueue(&qd, IID_PPV_ARGS(queue.put()))) || + FAILED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, IID_PPV_ARGS(allocator.put()))) || + FAILED(device->CreateCommandList(0, D3D12_COMMAND_LIST_TYPE_DIRECT, allocator.p, nullptr, IID_PPV_ARGS(list.put()))) || + FAILED(device->CreateFence(0, D3D12_FENCE_FLAG_NONE, IID_PPV_ARGS(fence.put())))) + return fail("queue, allocator, list or fence"); + UINT64 fence_value = 0; + auto submit = [&]() { + if (FAILED(list->Close())) return false; + ID3D12CommandList* lists[] = {list.p}; + queue->ExecuteCommandLists(1, lists); + if (FAILED(queue->Signal(fence.p, ++fence_value))) return false; + HANDLE event = CreateEventW(nullptr, FALSE, FALSE, nullptr); + const bool done = event && SUCCEEDED(fence->SetEventOnCompletion(fence_value, event)) && + WaitForSingleObject(event, 10000) == WAIT_OBJECT_0; + if (event) CloseHandle(event); + return done && SUCCEEDED(device->GetDeviceRemovedReason()); + }; + D3D12_RESOURCE_BARRIER barrier{}; + barrier.Type = D3D12_RESOURCE_BARRIER_TYPE_UAV; + + // ---- BuildRaytracingAccelerationStructureBatched2X: the BLAS (with a stream and a COMPACTED_SIZE postbuild), + // and an element asking for offline statistics, which the DLL refuses and the shim skips ---- + const xdxr::PostbuildInfoDesc compacted_post{info->GetGPUVirtualAddress(), + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_POSTBUILD_INFO_COMPACTED_SIZE, 0}; + const xdxr::PostbuildInfoDesc statistics_post{info->GetGPUVirtualAddress() + 8, + xdxr::kPostbuildInfoOfflineStatistics, 0}; + xdxr::BatchedDesc2 elements[2]{}; + for (xdxr::BatchedDesc2& e : elements) { + std::memcpy(&e.inputs, &blas_inputs, sizeof e.inputs); + e.stream = stream; + } + elements[0].dest_acceleration_structure_data = blas->GetGPUVirtualAddress(); + elements[0].scratch_acceleration_structure_data = scratch->GetGPUVirtualAddress(); + elements[0].num_postbuild_info_descs = 1; + elements[0].postbuild_info_descs = &compacted_post; + elements[1].dest_acceleration_structure_data = refused->GetGPUVirtualAddress(); + elements[1].scratch_acceleration_structure_data = scratch2->GetGPUVirtualAddress(); + elements[1].num_postbuild_info_descs = 1; + elements[1].postbuild_info_descs = &statistics_post; + batched(builder, list.p, 2, elements); + list->ResourceBarrier(1, &barrier); + xdxr::BatchedDesc2 top{}; + top.dest_acceleration_structure_data = tlas->GetGPUVirtualAddress(); + std::memcpy(&top.inputs, &tlas_inputs, sizeof top.inputs); + top.scratch_acceleration_structure_data = scratch->GetGPUVirtualAddress(); + batched(builder, list.p, 1, &top); + batched(builder, list.p, 0, nullptr); // an empty batch does nothing + list->ResourceBarrier(1, &barrier); + list->CopyBufferRegion(blas_rb.p, 0, blas.p, 0, blas_info.ResultDataMaxSizeInBytes); + list->CopyBufferRegion(refused_rb.p, 0, refused.p, 0, blas_info.ResultDataMaxSizeInBytes); + list->CopyBufferRegion(tlas_rb.p, 0, tlas.p, 0, tlas_info.ResultDataMaxSizeInBytes); + list->CopyBufferRegion(info_rb.p, 0, info.p, 0, 16); + if (!submit()) return fail("the batched builds did not complete"); + + UINT64 post[2] = {}; + { + void* p = nullptr; + if (FAILED(info_rb->Map(0, nullptr, &p))) return fail("Map postbuild"); + std::memcpy(post, p, sizeof post); + info_rb->Unmap(0, nullptr); + } + check(post[0] && post[0] % 64 == 0 && post[0] <= blas_info.ResultDataMaxSizeInBytes, + "the BLAS element's COMPACTED_SIZE postbuild is written"); + check(post[1] == 0, "the offline-statistics element is skipped: its postbuild destination is untouched"); + { + void* p = nullptr; + std::uint32_t units = 0; + if (SUCCEEDED(refused_rb->Map(0, nullptr, &p))) { + std::memcpy(&units, static_cast(p) + 4, 4); + refused_rb->Unmap(0, nullptr); + } + check(units == 0, "and no structure was built into its destination"); + } + + // ---- CopyRaytracingAccelerationStructure COMPACT into a buffer of exactly COMPACTED_SIZE ---- + Ref compacted, compacted_rb; + if (FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_DEFAULT, post[0], as_state, uav, compacted.put())) || + FAILED(hr = buffer(device.p, D3D12_HEAP_TYPE_READBACK, post[0], D3D12_RESOURCE_STATE_COPY_DEST, + D3D12_RESOURCE_FLAG_NONE, compacted_rb.put()))) + return fail("compacted buffers", hr); + if (FAILED(allocator->Reset()) || FAILED(list->Reset(allocator.p, nullptr))) return fail("Reset for compaction"); + copy(builder, list.p, compacted->GetGPUVirtualAddress(), blas->GetGPUVirtualAddress(), + D3D12_RAYTRACING_ACCELERATION_STRUCTURE_COPY_MODE_COMPACT); + list->ResourceBarrier(1, &barrier); + list->CopyBufferRegion(compacted_rb.p, 0, compacted.p, 0, post[0]); + if (!submit()) return fail("the compaction did not complete"); + + // ---- RehydrateRaytracingAccelerationStructureBatched2X: not implemented yet ---- + D3D12_BUILD_RAYTRACING_ACCELERATION_STRUCTURE_DESC rehydrate_desc{}; + const UINT64 source = blas->GetGPUVirtualAddress(); + check(rehydrate(builder, list.p, 1, &rehydrate_desc, &source) == E_NOTIMPL, + "RehydrateRaytracingAccelerationStructureBatched2X answers E_NOTIMPL (stage 2)"); + + // ---- dump for xdxr_bvh.py check-build ---- + auto dump = [&](ID3D12Resource* rb, UINT64 size, const std::string& name, const std::string& json) { + void* p = nullptr; + if (FAILED(rb->Map(0, nullptr, &p))) return false; + std::uint32_t units = 0; + std::memcpy(&units, static_cast(p) + 4, 4); // header totalSizeIn64BNodes + const UINT64 used = (UINT64(units) + 1) * 64; // the field does not count the 64-byte header + const bool ok = units && used <= size && write_file(dir + "/" + name + ".bin", p, std::size_t(used)) && + write_file(dir + "/" + name + ".json", json.data(), json.size()); + rb->Unmap(0, nullptr); + return ok; + }; + std::string triangles = "["; + for (UINT t = 0; t < tris; ++t) { + triangles += t ? ",\n [" : "\n ["; + for (int k = 0; k < 3; ++k) + triangles += (k ? ", [" : "[") + num(soup[9 * t + 3 * k]) + ", " + num(soup[9 * t + 3 * k + 1]) + ", " + + num(soup[9 * t + 3 * k + 2]) + "]"; + triangles += ", 0, " + std::to_string(t) + "]"; + } + triangles += "]"; + check(dump(blas_rb.p, blas_info.ResultDataMaxSizeInBytes, "shim_blas", + "{\"kind\": \"blas\", \"address\": " + std::to_string(blas->GetGPUVirtualAddress()) + + ", \"triangles\": " + triangles + "}\n"), + "the BLAS built through the shim is written for check-build"); + std::string inst = "["; + for (int i = 0; i < 2; ++i) { + inst += i ? ", {\"transform\": [" : "{\"transform\": ["; + for (int k = 0; k < 12; ++k) inst += (k ? ", " : "") + num(xforms[i][k]); + inst += "], \"mask\": 255, \"blas\": 0}"; + } + inst += "]"; + check(dump(tlas_rb.p, tlas_info.ResultDataMaxSizeInBytes, "shim_tlas", + "{\"kind\": \"tlas\", \"address\": " + std::to_string(tlas->GetGPUVirtualAddress()) + + ", \"bias\": 0, \"blas\": [\"shim_blas\"], \"instances\": " + inst + "}\n"), + "the TLAS built through the shim is written for check-build"); + check(dump(compacted_rb.p, post[0], "shim_blas_compacted", + "{\"kind\": \"blas\", \"address\": " + std::to_string(compacted->GetGPUVirtualAddress()) + + ", \"triangles\": " + triangles + "}\n"), + "the BLAS compacted through the shim is written for check-build"); + + // ---- the destructor releases the builder ---- + destruct(builder); + destruct(builder); // a second destruction of the same storage is ignored + check(rt::shims::xbox_bvh_builder_live_count() == 0, "the destructor releases the builder's state"); + + std::printf("xbox_bvh_builder_test: %d of %d checks failed\n", g_failures, g_checks); + return g_failures ? 1 : 0; +} diff --git a/runtime/test/xbox_present_test.cpp b/runtime/test/xbox_present_test.cpp index 1526f87a7a..ce0ff853f3 100644 --- a/runtime/test/xbox_present_test.cpp +++ b/runtime/test/xbox_present_test.cpp @@ -368,15 +368,17 @@ int main() { EXPECT(SUCCEEDED(rt::d3d12::create_vulkan_device(info, IID_PPV_ARGS(&inner)))); Ref device; EXPECT(SUCCEEDED(rt::d3d12_xs::create_device_proxy(inner, __uuidof(ID3D12Device), - reinterpret_cast(&device.p)))); + reinterpret_cast(&device.p), /*console_lists=*/false))); rt::d3d12::set_device_outer(inner, device.p); auto presenter = rt::d3d12::create_window_presenter(inner, window); EXPECT(presenter); EXPECT(presenter->enable_capture()); leonida::ManualFrameClock clock; - auto owner = std::make_unique(std::move(presenter), &clock); + auto owner = std::make_unique(std::move(presenter), &clock, + rt::d3d12_xs::device_frame_tokens(device.p)); rt::d3d12::XboxPresentation& xbox = *owner; + EXPECT(xbox.pacer().token_source() == rt::d3d12_xs::device_frame_tokens(device.p)); D3D12_COMMAND_QUEUE_DESC queue_desc{}; Ref queue; @@ -665,6 +667,22 @@ int main() { EXPECT(region_is(frame, 0, 0, width, height, {51, 153, 230})); EXPECT(xbox.presents() == presented_before + 3); + using DeviceWaitFrameEventFn = HRESULT(WINAPI*)(void*, UINT, UINT, void*, UINT, std::uint64_t*); + const auto device_wait = + reinterpret_cast((*reinterpret_cast(device.p))[80]); + std::uint64_t device_token = 0; + EXPECT(device_wait(device.p, rt::d3d12::xbox_frame_event_origin, 0, nullptr, 0, &device_token) == S_OK); + EXPECT(device_token != 0 && device_token == xbox.pacer().tokens_issued()); + plane = plane_of(second, device_token + 1); + EXPECT(xbox.PresentX(1, &plane, nullptr) == E_INVALIDARG); + EXPECT(xbox.presents() == presented_before + 3); + plane = plane_of(rgba, device_token); + EXPECT(xbox.PresentX(1, &plane, nullptr) == S_OK); + EXPECT(xbox.presents() == presented_before + 4); + EXPECT(grab(frame)); + EXPECT(region_is(frame, 0, 0, width, height, {51, 153, 230})); + std::printf("a token from device slot 80 (WaitFrameEventX) presents: ok\n"); + // Sources the GPU cannot blit are refused with DXGI_ERROR_UNSUPPORTED and present nothing: multisampled, // integer and block-compressed. The last frame stays on screen and the token is still usable afterwards. { diff --git a/runtime/test/xgameruntime_test.cpp b/runtime/test/xgameruntime_test.cpp index af67045d42..c1293c5cc8 100644 --- a/runtime/test/xgameruntime_test.cpp +++ b/runtime/test/xgameruntime_test.cpp @@ -266,8 +266,8 @@ void check_measured_classes(QueryFn query, XSystemAnalyticsInfo (*named_analytic } // xgameruntime.lib's thunks don't import the runtime: they LoadLibraryW(L"xgameruntime.dll") and GetProcAddress five -// names (measured in the package's libHttpClient.GDK.dll and XCurl.dll). Drive that path through the loader shims, -// bound by the api set XCurl.dll imports them from, as a mapped image would be. +// entry points and XErrorReport (measured in the package's libHttpClient.GDK.dll and XCurl.dll). Drive that path +// through the loader shims, bound by the api set XCurl.dll imports them from, as a mapped image would be. void check_run_time_load() { using LoadW = HMODULE(WINAPI*)(LPCWSTR); using LoadExA = HMODULE(WINAPI*)(LPCSTR, HANDLE, DWORD); @@ -294,12 +294,15 @@ void check_run_time_load() { "the same module for a bare name, a full path in any case, LoadLibraryExA and GetModuleHandleW"); const char* entry_points[] = {"InitializeApiImpl", "InitializeApiImplEx", "InitializeApiImplEx2", - "UninitializeApiImpl", "QueryApiImpl"}; + "UninitializeApiImpl", "QueryApiImpl", "XErrorReport"}; bool all = true; for (const char* n : entry_points) all = all && get_proc(rt_mod, n) && reinterpret_cast(get_proc(rt_mod, n)) == rt::shims::find("xgameruntime.dll", n); - check(all, "GetProcAddress serves the five entry points xgameruntime.lib looks up"); + check(all, "GetProcAddress serves the six names xgameruntime.lib looks up (five entry points and XErrorReport)"); + using ReportExport = HRESULT(WINAPI*)(HRESULT, const char*); + auto report_export = reinterpret_cast(get_proc(rt_mod, "XErrorReport")); + check(report_export && report_export(E_FAIL, "export") == S_OK, "the XErrorReport export answers S_OK"); SetLastError(0); check(get_proc(rt_mod, "NoSuchRuntimeFunction") == nullptr && GetLastError() == ERROR_PROC_NOT_FOUND, "an unserved name is NULL with ERROR_PROC_NOT_FOUND, as from a real module"); diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp index 3ec621b0b4..415f2c9e5d 100644 --- a/runtime/test/xmem_test.cpp +++ b/runtime/test/xmem_test.cpp @@ -11,7 +11,6 @@ #include #include -#include #include #include #include @@ -19,12 +18,9 @@ #include #include #include -#include -#include #include "shims.h" #include "startup_trace.h" -#include "xmem.h" namespace { @@ -373,10 +369,27 @@ void test_physical_pages(const PhysicalApi& api) { VirtualQuery(window, &info, sizeof(info)); check(info.State == MEM_COMMIT && info.Type == MEM_MAPPED && info.Protect == PAGE_READWRITE, "a mapped page is a read-write view with the window's protection"); + check(info.AllocationBase == window && info.RegionSize == kPages * kPage64k, + "consecutive pages of one allocation are mapped as one view"); } + // A page unmapped or remapped inside that view splits it; its neighbours keep their pages. + void* const middle = window + kPage64k; + check(api.scatter(&middle, 1, nullptr) == TRUE && reserved_only(window + kPage64k), + "a page inside a view unmaps on its own"); + check(page_holds(window, 0x1000u) && page_holds(window + 2 * kPage64k, 0x3000u) && + page_holds(window + 3 * kPage64k, 0x4000u), + "the pages around it stay mapped with their contents"); + check(api.map(middle, 1, &pages[1]) == middle && page_holds(window + kPage64k, 0x2000u), + "a page maps again into the gap"); + check(api.map(window, kPages, nullptr) == window, "XMemMapPhysicalPages with no page array unmaps"); check(reserved_only(window) && reserved_only(window + 3 * kPage64k), "unmapped pages are reserved again"); + // The split above left the range as several host placeholders; the whole run maps again over them. + check(api.map(window, kPages, pages) == window && page_holds(window, 0x1000u) && + page_holds(window + 3 * kPage64k, 0x4000u), + "a run maps again over a range an earlier partial unmap split"); + check(api.map(window, kPages, nullptr) == window && reserved_only(window), "and unmaps again"); // Remap in reverse order into the other window: each page keeps its contents. uint64_t reversed[kPages]; @@ -444,223 +457,48 @@ void test_physical_pages(const PhysicalApi& api) { // The windows were split into one placeholder per page; the process exit releases them. } -bool access_faults(volatile uint32_t* address, bool write) { - __try { - if (write) { - *address = 1; - } else { - const uint32_t value = *address; - (void)value; - } - } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER - : EXCEPTION_CONTINUE_SEARCH) { - return true; - } - return false; -} - -int64_t commit_growth(const PERFORMANCE_INFORMATION& from, const PERFORMANCE_INFORMATION& to) { - return (static_cast(to.CommitTotal) - static_cast(from.CommitTotal)) * - static_cast(to.PageSize); -} - -void test_physical_pages_commit_on_touch(const PhysicalApi& api) { - PERFORMANCE_INFORMATION before{}; - if (!GetPerformanceInfo(&before, sizeof(before))) { - check(false, "GetPerformanceInfo reads the system commit charge"); - return; - } - const uint64_t free_commit = static_cast(before.CommitLimit - before.CommitTotal) * before.PageSize; - const uint64_t count = (free_commit + (uint64_t{1} << 30)) / kPage64k; - if (count >= (uint64_t{1} << 20)) { - std::printf("SKIP physical pages past the free commit: %llu MiB of commit is free\n", - static_cast(free_commit >> 20)); - return; - } - std::vector pages(static_cast(count)); - uint64_t got = count; - check(api.allocate(0x380, &got, pages.data()) == TRUE && got == count, - "XMemAllocatePhysicalPages gives 1 GiB more pages than the system has commit free"); - if (got != count) return; - PERFORMANCE_INFORMATION allocated{}; - GetPerformanceInfo(&allocated, sizeof(allocated)); - check(commit_growth(before, allocated) < static_cast(count * kPage64k / 8), - "allocating those pages does not charge them"); - - constexpr uint64_t kMapped = 1024; - constexpr uint64_t kTouched = 512; +// The placeholder flags pass through: reserve a placeholder, carve windows and committed memory out of it. +// A run longer than one host view is mapped as capped views, so unmapping one page inside it only remaps the rest of +// that view; every other page keeps its contents. +void test_long_run(const PhysicalApi& api) { + constexpr uint64_t kPages = 1100; // more than the 1024-page view cap auto* const window = static_cast( - api.virtual_alloc(nullptr, kMapped * kPage64k, MEM_RESERVE | kXmem64kPages, 0x21, PAGE_READWRITE)); - auto* const second = static_cast( - api.virtual_alloc(nullptr, 2 * kPage64k, MEM_RESERVE | kXmem64kPages, 0x21, PAGE_READWRITE)); - check(window != nullptr && second != nullptr, "XMemVirtualAlloc reserves windows for them"); - if (!window || !second) { - api.free_pages(count, pages.data()); - return; - } - check(api.map(window, kMapped, pages.data()) == window, "1,024 of them map into one window"); - PERFORMANCE_INFORMATION mapped{}; - GetPerformanceInfo(&mapped, sizeof(mapped)); - check(commit_growth(allocated, mapped) < static_cast(kMapped * kPage64k / 2), - "mapping them does not charge them"); - - for (uint64_t i = 0; i < kTouched; ++i) { - static_cast(static_cast(window + i * kPage64k))[0] = - 0xc0de0000u | static_cast(i); - } - PERFORMANCE_INFORMATION touched{}; - GetPerformanceInfo(&touched, sizeof(touched)); - const int64_t touched_growth = commit_growth(mapped, touched); - check(touched_growth >= static_cast(kTouched * kPage64k / 2) && - touched_growth < static_cast(kMapped * kPage64k), - "writing to 512 of them charges about those 512 pages"); - bool written = true; - for (uint64_t i = 0; i < kTouched; ++i) written &= read_u32(window + i * kPage64k, 0) == (0xc0de0000u | i); - check(written, "each touched page keeps what was written to it"); - check(read_u32(window + kTouched * kPage64k, 0) == 0, "an untouched page reads as zero"); - - check(api.map(second, 2, pages.data()) == second, "two of the pages map into a second window"); - check(read_u32(second, 0) == 0xc0de0000u && read_u32(second + kPage64k, 0) == 0xc0de0001u, - "the second window sees what was written through the first"); - static_cast(static_cast(second))[1] = 0x5ca1ab1e; - check(read_u32(window, 4) == 0x5ca1ab1e, "and the first window sees what is written through the second"); - - DWORD old = 0; - check(VirtualProtect(window, kPage64k, PAGE_READONLY, &old) != FALSE && - access_faults(static_cast(static_cast(window)), true), - "a write to a committed read-only page still faults to the next handler"); - VirtualProtect(window, kPage64k, PAGE_READWRITE, &old); - check(VirtualProtect(window + 4096, 4096, PAGE_READONLY, &old) != FALSE && - access_faults(static_cast(static_cast(window + 4096)), true), - "a write to a read-only 4 KiB part of a read-write page still faults to the next handler"); - check(!access_faults(static_cast(static_cast(window + 8192)), true), - "the rest of that page stays writable"); - VirtualProtect(window + 4096, 4096, PAGE_READWRITE, &old); - void* const elsewhere = VirtualAlloc(nullptr, kPage64k, MEM_RESERVE, PAGE_READWRITE); - check(elsewhere != nullptr && access_faults(static_cast(elsewhere), false), - "a fault outside the mapped pages still reaches the next handler"); - if (elsewhere) VirtualFree(elsewhere, 0, MEM_RELEASE); - - uint8_t* const target = window + (kTouched + 1) * kPage64k; - check(rt::xmem::commit_physical_range(target, kPage64k), "commit_physical_range commits an untouched page"); - uint32_t local = 0; - check(rt::xmem::commit_physical_range(&local, sizeof(local)), "commit_physical_range skips memory it does not own"); - wchar_t directory[MAX_PATH]{}; - wchar_t path[MAX_PATH]{}; - bool read_ok = false; - if (GetTempPathW(MAX_PATH, directory) && GetTempFileNameW(directory, L"xpg", 0, path)) { - std::vector pattern(kPage64k / sizeof(uint32_t)); - for (size_t i = 0; i < pattern.size(); ++i) pattern[i] = 0x7e570000u + static_cast(i); - const HANDLE out = - CreateFileW(path, GENERIC_WRITE, 0, nullptr, CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY, nullptr); - DWORD bytes = 0; - const bool wrote = out != INVALID_HANDLE_VALUE && - WriteFile(out, pattern.data(), static_cast(kPage64k), &bytes, nullptr) && - bytes == kPage64k; - if (out != INVALID_HANDLE_VALUE) CloseHandle(out); - const HANDLE in = wrote ? CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr, OPEN_EXISTING, 0, nullptr) - : INVALID_HANDLE_VALUE; - if (in != INVALID_HANDLE_VALUE) { - read_ok = ReadFile(in, target, static_cast(kPage64k), &bytes, nullptr) && bytes == kPage64k && - std::memcmp(target, pattern.data(), kPage64k) == 0; - CloseHandle(in); - } - DeleteFileW(path); - } - check(read_ok, "ReadFile fills a page that commit_physical_range committed"); - - check(api.map(second, 2, nullptr) == second && api.map(window, kMapped, nullptr) == window, "they unmap"); - check(api.free_pages(count, pages.data()) == TRUE, "XMemFreePhysicalPages frees them"); -} - -void test_commit_physical_pages(const PhysicalApi& api) { - constexpr uint64_t kPages = 3; - uint64_t pages[kPages]{}; + api.virtual_alloc(nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE)); + std::vector pages(kPages); uint64_t count = kPages; - check(api.allocate(0x280, &count, pages) == TRUE && count == kPages, "three physical pages for commit by number"); - if (count != kPages) return; - check(rt::xmem::commit_physical_pages(pages, 0), "committing no pages succeeds"); - check(!rt::xmem::commit_physical_pages(nullptr, 1), "committing from a null page array fails"); - const uint64_t unknown = 0x1fffff0; - check(!rt::xmem::commit_physical_pages(&unknown, 1), "committing a page number that was never allocated fails"); - check(rt::xmem::commit_physical_pages(pages, 2), "commit_physical_pages commits two pages that were never mapped"); - - auto* const window = static_cast( - api.virtual_alloc(nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x21, PAGE_READWRITE)); - check(window != nullptr, "XMemVirtualAlloc reserves a window for them"); - if (window) { - check(api.map(window, kPages, pages) == window, "the three pages map"); - MEMORY_BASIC_INFORMATION info[kPages]{}; - bool queried = true; - for (uint64_t i = 0; i < kPages; ++i) - queried &= VirtualQuery(window + i * kPage64k, &info[i], sizeof(info[i])) == sizeof(info[i]); - check(queried && info[0].State == MEM_COMMIT && info[1].State == MEM_COMMIT && info[2].State == MEM_RESERVE, - "the two committed by number are committed in the window and the third is not yet"); - check(read_u32(window, 0) == 0 && read_u32(window + kPage64k, 0) == 0, - "pages committed by number read as zero"); - api.map(window, kPages, nullptr); - } - check(api.free_pages(kPages, pages) == TRUE, "XMemFreePhysicalPages frees them"); -} - -void test_first_touch_during_remap(const PhysicalApi& api) { - constexpr uint64_t kSlice = 16; - constexpr uint64_t kSlices = 256; - std::vector pages(kSlice * kSlices); - uint64_t count = pages.size(); - check(api.allocate(0x280, &count, pages.data()) == TRUE && count == pages.size(), - "4,096 physical pages for the remap race"); - if (count != pages.size()) return; - auto* const window = static_cast( - api.virtual_alloc(nullptr, kSlice * kPage64k, MEM_RESERVE | kXmem64kPages, 0x21, PAGE_READWRITE)); - check(window != nullptr, "XMemVirtualAlloc reserves a window for the remap race"); - if (!window) { - api.free_pages(count, pages.data()); - return; - } - std::atomic stop{false}; - std::atomic touches{0}; - std::atomic unmapped_faults{0}; - std::vector writers; - for (int t = 0; t < 4; ++t) { - writers.emplace_back([&, t] { - uint64_t i = static_cast(t); - while (!stop.load(std::memory_order_relaxed)) { - auto* const word = - static_cast(static_cast(window + (i % kSlice) * kPage64k)) + t; - if (access_faults(word, true)) { - unmapped_faults.fetch_add(1, std::memory_order_relaxed); - } else { - touches.fetch_add(1, std::memory_order_relaxed); - } - ++i; - } - }); - } - const ULONGLONG started = GetTickCount64(); - bool remapped = true; - for (uint64_t s = 0; s < kSlices; ++s) { - remapped &= api.map(window, kSlice, pages.data() + s * kSlice) == window; - Sleep(0); - remapped &= api.map(window, kSlice, nullptr) == window; - } - remapped &= api.map(window, kSlice, pages.data() + (kSlices - 1) * kSlice) == window; - stop.store(true); - for (auto& writer : writers) writer.join(); - const ULONGLONG elapsed = GetTickCount64() - started; - check(remapped, "256 slices map and unmap while 4 threads write into the window"); - check(elapsed < 30000, "first-touch faults during map and unmap finish without hanging"); - check(touches.load() > 0, "writes land while the pages are mapped"); - std::printf("remap race: %llu writes landed, %llu hit an unmapped page, %llu ms\n", - static_cast(touches.load()), - static_cast(unmapped_faults.load()), static_cast(elapsed)); - static_cast(static_cast(window))[8] = 0x600dcafe; - check(read_u32(window, 32) == 0x600dcafe, "the last slice is still mapped and writable"); - api.map(window, kSlice, nullptr); - check(api.free_pages(count, pages.data()) == TRUE, "XMemFreePhysicalPages frees the remap race pages"); + check(window && api.allocate(0x280, &count, pages.data()) == TRUE, "a long run's window and pages are allocated"); + if (!window || count != kPages) return; + check(api.map(window, kPages, pages.data()) == window, "a run longer than the view cap maps"); + MEMORY_BASIC_INFORMATION info{}; + VirtualQuery(window, &info, sizeof(info)); + check(info.State == MEM_COMMIT && info.RegionSize == 1024 * kPage64k, "it is mapped as views of at most 1024 pages"); + for (uint64_t i = 0; i < kPages; ++i) fill_page(window + i * kPage64k, static_cast(i + 1)); + void* const hole = window + 10 * kPage64k; + check(api.scatter(&hole, 1, nullptr) == TRUE && reserved_only(hole), "a page inside the first view unmaps"); + bool kept = true; + for (uint64_t i = 0; i < kPages; ++i) { + if (i != 10) kept &= page_holds(window + i * kPage64k, static_cast(i + 1)); + } + check(kept, "every other page of the run keeps its contents"); + // Several pages across the boundary of two capped views unmap together; the pages on both sides stay. + check(api.map(window + 1000 * kPage64k, 50, nullptr) == window + 1000 * kPage64k && + reserved_only(window + 1000 * kPage64k) && reserved_only(window + 1049 * kPage64k), + "a multi-page range across two views unmaps"); + check(page_holds(window + 999 * kPage64k, 1000u) && page_holds(window + 1050 * kPage64k, 1051u), + "the pages on both sides of it keep their contents"); + // Mapping other pages over the middle of a live run replaces just those pages. + check(api.map(window + 500 * kPage64k, 3, &pages[600]) == window + 500 * kPage64k && + page_holds(window + 500 * kPage64k, 601u) && page_holds(window + 502 * kPage64k, 603u), + "pages mapped over the middle of a live run replace it there"); + check(page_holds(window + 499 * kPage64k, 500u) && page_holds(window + 503 * kPage64k, 504u), + "and the run's pages around them keep their contents"); + check(api.map(window, kPages, nullptr) == window && reserved_only(window) && + reserved_only(window + (kPages - 1) * kPage64k), + "the whole run unmaps"); + check(api.free_pages(kPages, pages.data()) == TRUE, "the long run's pages are freed"); + check(api.map(window, 1, pages.data()) == nullptr && reserved_only(window), "a freed page does not map again"); } -// The placeholder flags pass through: reserve a placeholder, carve windows and committed memory out of it. void test_placeholders(const PhysicalApi& api) { auto* const base = static_cast( api.virtual_alloc(nullptr, 6 * kPage64k, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, 7, PAGE_NOACCESS)); @@ -694,6 +532,34 @@ void test_placeholders(const PhysicalApi& api) { check(reserved_only(base), "the rest of the placeholder is still reserved"); } +// Three of the retail executable's five physical-page windows carry 0x400 next to PAGE_READWRITE. That is +// PAGE_WRITECOMBINE on the PC, outside the PAGE_GRAPHICS_* range, and MapViewOfFile3 refuses a view with it, so the +// mapped pages take the window's protection without the cache modifier. +void test_write_combine_window(const PhysicalApi& api) { + auto* const window = static_cast( + api.virtual_alloc(nullptr, kPage64k, MEM_RESERVE | kXmem64kPages, 0x27, + PAGE_READWRITE | PAGE_WRITECOMBINE | PAGE_GRAPHICS_READWRITE)); + check(window != nullptr, "XMemVirtualAlloc reserves a window with PAGE_WRITECOMBINE in its protection"); + if (!window) return; + + uint64_t page = 0; + uint64_t count = 1; + check(api.allocate(0x280, &count, &page) == TRUE && count == 1, "allocate a page for the write-combine window"); + SetLastError(ERROR_SUCCESS); + const bool mapped = api.map(window, 1, &page) == window; + check(mapped, "a page maps into a window reserved with PAGE_WRITECOMBINE"); + if (mapped) { + MEMORY_BASIC_INFORMATION info{}; + VirtualQuery(window, &info, sizeof(info)); + check(info.State == MEM_COMMIT && info.Protect == PAGE_READWRITE, + "the page mapped there is a plain read-write view"); + fill_page(window, 0x77000000u); + check(page_holds(window, 0x77000000u), "the page in the write-combine window holds data"); + } + check(api.map(window, 1, nullptr) == window, "unmap the write-combine window"); + check(api.free_pages(1, &page) == TRUE, "free the write-combine window's page"); +} + // gta6rt --trace: one "xmem_attributes" event per distinct raw attribute word and API, none with the trace off. void test_attribute_trace(XMemAllocFn alloc, XMemFreeFn free_mem, XMemVirtualAllocFn virtual_alloc) { wchar_t temp[MAX_PATH]; @@ -938,10 +804,9 @@ int main() { if (tools_mem) check(tools_mem() == FALSE, "XMemIsToolsMemAvailable returns FALSE (no devkit tools memory)"); if (virtual_alloc && physical.allocate && physical.free_pages && physical.map && physical.scatter) { test_physical_pages(physical); - test_physical_pages_commit_on_touch(physical); - test_commit_physical_pages(physical); - test_first_touch_during_remap(physical); + test_long_run(physical); test_placeholders(physical); + test_write_combine_window(physical); } print_result(); diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 6af7ad8046..5592d5875f 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -2,11 +2,14 @@ // - devices that stop at ID3D12Device, Device1, Device3 and Device9: the slots of a missing interface (45/46, // 50, 75) are refused without reaching the device, the others get the real objects behind the proxies; // - fences with and without ID3D12Fence1: 11 or 12 public slots, QueryInterface and slot 11 to match; +// - fence slot 12: the address of a completed value that follows the real fence, from a CPU Signal through the +// proxy and from a signal the proxy never sees, up to device removal, with the descriptor's code pointer unused; // - creation that fails, that returns S_OK with no object, a null IID or output, and an interface the real object // has but the proxy does not model; // - OpenSharedHandle of a fence (as ID3D12Fence, IUnknown, Fence1), of a non-fence object, of an invalid handle, // and with a null output or IID, with the references of every object it touches; // - allocation failures in the proxy (operator new, the arrays it unwraps), injected in this executable only; +// - device slot 26 called the console's way (the struct's buffer in RCX, the device in RDX) and the PC way; // - --fail-virtualalloc / --fail-virtualprotect / --fail-veh: the guard region's setup failing, injected by // patching this executable's own import table before the first proxy table is built (one process each). // Every device, queue, fence and resource here is a mock that records the calls it gets. No game data, no Xbox DLLs. @@ -70,11 +73,15 @@ namespace xs = rt::d3d12_xs; // ---- Mocks ---- -enum class Kind { device, queue, fence, resource, allocator, command_list, heap }; +enum class Kind { device, queue, fence, resource, allocator, command_list, list, heap }; constexpr unsigned kMockSlots = 128; constexpr std::uint64_t kFenceHandle = 0x1000, kResourceHandle = 0x2000; // the handles the mock device opens constexpr std::uint64_t kCompletedValue = 7; // what a mock fence's slot 8 returns +constexpr UINT kHeapMarker = 0x26262626; // the VisibleNodeMask a mock device's slot 26 answers +constexpr SIZE_T kMockHeapCpuStart = 0x55550000ull; +constexpr UINT64 kMockHeapGpuStart = 0x66660000ull; +constexpr UINT kMockDescriptorInc = 32; // {5d1e0c4a-2b7f-4e61-9a3d-8c4b2f1e6a70}: an interface the mock queue implements that the proxy does not model. constexpr GUID kExtraIid{0x5d1e0c4a, 0x2b7f, 0x4e61, {0x9a, 0x3d, 0x8c, 0x4b, 0x2f, 0x1e, 0x6a, 0x70}}; @@ -83,21 +90,41 @@ struct Mock { Kind kind; long refs; int device_level; // device: highest ID3D12DeviceN it answers (0 = ID3D12Device only) - int list_level; // command_list: 0=base (60 slots), 7=GCL7 (81 slots), 8=GCL8 (82 slots) bool fence1; // fence: answers ID3D12Fence1; device: the fences it makes do bool allocator_tag; // allocator: answers kLeonidaCommandAllocatorTag; device: the allocators it makes do + bool full_chain_lists; // device: CreateCommandList makes a full-chain list mock (Kind::list), else command_list bool create_null; // device: creation returns create_result with no object HRESULT create_result; // device: what creation returns (S_OK makes the object) Mock* last_child; // device: the object its last creation or open made + Mock* device10_alias; // device: when set, QueryInterface(ID3D12Device10) answers this object, not itself + SRWLOCK lock; // fence: guards completed, armed_value and armed_event (zeroed = SRWLOCK_INIT) + std::uint64_t completed; // fence: what GetCompletedValue (slot 8) returns + std::uint64_t armed_value; // fence: the value SetEventOnCompletion (slot 9) waits for + HANDLE armed_event; // fence: the event it sets then, or null unsigned calls[kMockSlots]; - std::uint64_t args[kMockSlots][5]; + std::uint64_t args[kMockSlots][6]; std::uint64_t array[kMockSlots][4]; // device: the first entries of the array argument, as received + D3D12_COMMAND_QUEUE_DESC queue_desc; // device: the description of its last CreateCommandQueue (slot 8) + D3D12_SHADER_RESOURCE_VIEW_DESC srv; // device: the description CreateShaderResourceView (slot 18) last received + IUnknown* held; // ID3D12Object::SetPrivateDataInterface (slot 5): one reference, until destroyed + UINT om_rtv_count; // list slot 46 (OMSetRenderTargets): captured RTV/DSV handles + BOOL om_single_range; + SIZE_T om_rtvs[D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT]; + bool om_has_dsv; + SIZE_T om_dsv; + SIZE_T clear_dsv_handle; // list slot 47 (ClearDepthStencilView): typed float-ABI capture + D3D12_CLEAR_FLAGS clear_dsv_flags; + FLOAT clear_dsv_depth; + UINT8 clear_dsv_stencil; + UINT clear_dsv_num_rects; + const D3D12_RECT* clear_dsv_rects; }; Mock g_pool[256]; unsigned g_pool_used = 0; void** mock_vtable(); +void** mock_list_vtable(); Mock* new_mock(Kind kind) { if (g_pool_used == std::size(g_pool)) { @@ -106,11 +133,44 @@ Mock* new_mock(Kind kind) { } Mock* m = &g_pool[g_pool_used++]; std::memset(m, 0, sizeof(*m)); - m->vtable = mock_vtable(); + m->vtable = (kind == Kind::list || kind == Kind::command_list) ? mock_list_vtable() : mock_vtable(); m->kind = kind; + if (kind == Kind::fence) m->completed = kCompletedValue; return m; } +// A mock fence's completed value, read and written under its lock: the proxy's wait thread calls slots 8 and 9 while +// the test signals. Signal sets the one armed event once the value reaches it, as the PC fence does. +std::uint64_t fence_completed(Mock* m) { + AcquireSRWLockExclusive(&m->lock); + const std::uint64_t value = m->completed; + ReleaseSRWLockExclusive(&m->lock); + return value; +} + +void fence_signal(Mock* m, std::uint64_t value) { + AcquireSRWLockExclusive(&m->lock); + m->completed = value; + if (m->armed_event && value >= m->armed_value) { + SetEvent(m->armed_event); + m->armed_event = nullptr; + } + ReleaseSRWLockExclusive(&m->lock); +} + +HRESULT fence_set_event(Mock* m, std::uint64_t value, HANDLE event) { + if (!event) return S_OK; // the PC fence would block until `value`; no caller here does that + AcquireSRWLockExclusive(&m->lock); + if (m->completed >= value) { + SetEvent(event); + } else { + m->armed_value = value; + m->armed_event = event; + } + ReleaseSRWLockExclusive(&m->lock); + return S_OK; +} + bool mock_has(const Mock* m, REFIID iid) { if (IsEqualIID(iid, __uuidof(IUnknown)) || IsEqualIID(iid, __uuidof(ID3D12Object))) return true; if (m->kind == Kind::device) { @@ -144,24 +204,23 @@ bool mock_has(const Mock* m, REFIID iid) { case Kind::fence: return IsEqualIID(iid, __uuidof(ID3D12Fence)) || (m->fence1 && IsEqualIID(iid, __uuidof(ID3D12Fence1))); case Kind::resource: return IsEqualIID(iid, __uuidof(ID3D12Resource)); - case Kind::heap: return IsEqualIID(iid, __uuidof(ID3D12DescriptorHeap)); case Kind::command_list: - if (IsEqualIID(iid, __uuidof(ID3D12CommandList)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList))) return true; -#ifdef __ID3D12GraphicsCommandList7_INTERFACE_DEFINED__ - if (m->list_level >= 7 && (IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList7)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList6)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList5)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList4)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList3)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList2)) || - IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList1)))) - return true; -#endif - return false; + return IsEqualIID(iid, __uuidof(ID3D12CommandList)) || + IsEqualIID(iid, __uuidof(ID3D12GraphicsCommandList)); case Kind::allocator: return IsEqualIID(iid, __uuidof(ID3D12CommandAllocator)) || (m->allocator_tag && IsEqualIID(iid, xs::kLeonidaCommandAllocatorTag)); + case Kind::list: { + // The mock answers every graphics-command-list interface so the proxy sees the full 82-slot chain. + const IID lists[] = {__uuidof(ID3D12CommandList), __uuidof(ID3D12GraphicsCommandList), + __uuidof(ID3D12GraphicsCommandList1), __uuidof(ID3D12GraphicsCommandList2), + __uuidof(ID3D12GraphicsCommandList3), __uuidof(ID3D12GraphicsCommandList4), + __uuidof(ID3D12GraphicsCommandList5), __uuidof(ID3D12GraphicsCommandList6), + __uuidof(ID3D12GraphicsCommandList7), __uuidof(ID3D12GraphicsCommandList8)}; + for (const IID& list_iid : lists) if (IsEqualIID(iid, list_iid)) return true; + return false; + } + case Kind::heap: return IsEqualIID(iid, __uuidof(ID3D12DescriptorHeap)); default: return false; } } @@ -170,6 +229,9 @@ HRESULT mock_query(Mock* m, const IID* riid, void** out) { if (!out) return E_POINTER; *out = nullptr; if (!riid || !mock_has(m, *riid)) return E_NOINTERFACE; +#ifdef __ID3D12Device10_INTERFACE_DEFINED__ + if (m->device10_alias && IsEqualIID(*riid, __uuidof(ID3D12Device10))) m = m->device10_alias; +#endif *out = m; ++m->refs; return S_OK; @@ -194,55 +256,203 @@ void copy_array(Mock* m, unsigned slot, std::uint64_t objects, std::uint64_t cou for (std::uint32_t i = 0; in && i < static_cast(count) && i < 4; ++i) m->array[slot][i] = in[i]; } -// `words` are the call's first five words (a1..a5), copied into the thunk's own frame. +// The PC device's GetResourceAllocationInfo, as a driver that packs a surface with no tile padding answers it: a buffer +// its width, a texture width x height x slices x element bytes (4 for RGBA8, 8 for RGBA16F), each rounded up to +// 64 KiB, summed over the descriptions; a texture with no width is refused. The struct is written to the hidden return +// pointer (RDX of a C++ method call), which comes back in RAX. +D3D12_RESOURCE_DESC g_seen_descs[4]; // the first descriptions the mock device's slot 25 was given +std::uint32_t g_seen_desc_count = 0; +std::uint32_t g_seen_calls = 0; // slot 25 calls since the test cleared it; only the first is recorded + +std::uint64_t g_texture_size_bias = 0; // added to each texture's answer: a driver that pads more than the console + +std::uint64_t mock_allocation_info(std::uint64_t ret, std::uint64_t count, std::uint64_t descs_word) { + const auto* descs = reinterpret_cast(descs_word); + if (g_seen_calls++ == 0) { + g_seen_desc_count = static_cast(count); + for (std::uint32_t i = 0; descs && i < g_seen_desc_count && i < std::size(g_seen_descs); ++i) + g_seen_descs[i] = descs[i]; + } + std::uint64_t total = 0; + bool refused = false; + for (std::uint32_t i = 0; descs && i < static_cast(count); ++i) { + const D3D12_RESOURCE_DESC& d = descs[i]; + std::uint64_t bytes = d.Width; + if (d.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) + bytes = d.Width * d.Height * d.DepthOrArraySize * (d.Format == DXGI_FORMAT_R16G16B16A16_FLOAT ? 8 : 4); + refused = refused || d.Width == 0; + total += (bytes + 65535) / 65536 * 65536; + if (d.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) total += g_texture_size_bias; + } + auto* out = reinterpret_cast(ret); + *out = {refused ? UINT64_MAX : total, 65536}; + return ret; +} + +// `words` are the call's first six words (a1..a6), copied into the thunk's own frame. std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { - const std::uint64_t a1 = words[0], a2 = words[1], a3 = words[2], a4 = words[3]; + const std::uint64_t a1 = words[0], a2 = words[1], a3 = words[2], a4 = words[3], a5 = words[4], a6 = words[5]; if (m->kind == Kind::device) { + // The description lives on the caller's stack only for the call, so it is copied while the call is active. + if (slot == 18 && a2 >= 0x10000) std::memcpy(&m->srv, reinterpret_cast(a2), sizeof(m->srv)); switch (slot) { - case 8: return static_cast(mock_create(m, Kind::queue, a2, a3)); // CreateCommandQueue + case 8: // CreateCommandQueue + if (a1) std::memcpy(&m->queue_desc, reinterpret_cast(a1), sizeof(m->queue_desc)); + return static_cast(mock_create(m, Kind::queue, a2, a3)); case 9: return static_cast(mock_create(m, Kind::allocator, a2, a3)); // CreateCmdAllocator - case 14: return static_cast(mock_create(m, Kind::heap, a2, a3)); // CreateDescriptorHeap + // Slot 12 (CreateCommandList) never reaches this switch: the device vtable's slot is the dedicated + // mock_create_command_list, which needs the sixth word the generic thunk does not declare on some + // builds and which picks the list mock's chain breadth from full_chain_lists. + case 14: return static_cast(mock_create(m, Kind::heap, a2, a3)); // CreateDescriptorHeap + case 15: return kMockDescriptorInc; // GetDescriptorHandleIncrementSize + case 23: // CopyDescriptors + copy_array(m, 23, a2, a1); // dest starts + copy_array(m, 24, words[4], a4); // src starts (recorded in slot 24's array) + break; case 75: return static_cast(mock_create(m, Kind::queue, a3, a4)); // CreateCommandQueue1 case 36: return static_cast(mock_create(m, Kind::fence, a3, a4)); // CreateFence case 32: // OpenSharedHandle if (a1 == kFenceHandle) return static_cast(mock_create(m, Kind::fence, a2, a3)); if (a1 == kResourceHandle) return static_cast(mock_create(m, Kind::resource, a2, a3)); return static_cast(E_INVALIDARG); + case 25: return mock_allocation_info(a1, a3, a4); // GetResourceAllocationInfo (mask a2 is unused) case 34: case 35: case 46: copy_array(m, slot, a2, a1); break; // (count, objects, ...) case 45: copy_array(m, slot, a1, a3); break; // (fences, values, count, ...) + case 26: { // GetCustomHeapProperties, the PC method: (return buffer, node mask, heap type) + auto* out = reinterpret_cast(a1); + if (!out) break; + *out = {}; + out->Type = static_cast(static_cast(a3)); + out->CreationNodeMask = static_cast(a2); + out->VisibleNodeMask = kHeapMarker; + return a1; // a struct-returning method hands the buffer's address back in RAX + } + case 41: // CreateCommandSignature(desc, ...) + if (const auto* desc = reinterpret_cast(a1)) { + m->array[41][0] = desc->ByteStride | std::uint64_t{desc->NumArgumentDescs} << 32; + for (UINT i = 0; desc->pArgumentDescs && i < desc->NumArgumentDescs && i < 3; ++i) { + std::uint32_t type = 0; // read as its 32 bits: a console type is outside the enum's range + std::memcpy(&type, &desc->pArgumentDescs[i].Type, sizeof(type)); + m->array[41][i + 1] = type; + } + } + break; case 50: copy_array(m, slot, a3, a2); break; // (flags, count, objects, fence, value) + case 68: { // GetResourceAllocationInfo2 + auto* ret = reinterpret_cast(a1); + const auto count = static_cast(a3); + const auto* descs = reinterpret_cast(a4); + auto* info1 = reinterpret_cast(words[4]); + if (descs && count > 0) { + m->array[68][0] = static_cast(descs[0].Layout); + m->array[68][1] = static_cast(descs[0].Flags); + m->array[68][2] = descs[0].SamplerFeedbackMipRegion.Width | + descs[0].SamplerFeedbackMipRegion.Height | + descs[0].SamplerFeedbackMipRegion.Depth; + if (count > 1) { + const auto& last = descs[count - 1]; + m->array[68][3] = (static_cast(last.Layout) << 32) | + static_cast(last.Flags); + } + } + if (ret) *ret = {0x40000, 0x10000}; + if (info1 && count > 0) info1[0] = {0, 0x10000, 0x40000}; + return a1; + } default: break; } return S_OK; } - if (m->kind == Kind::fence && slot == 8) return kCompletedValue; // GetCompletedValue - if (m->kind == Kind::queue && slot == 10) copy_array(m, slot, a2, a1); // ExecuteCommandLists(count, lists) - if (m->kind == Kind::command_list && slot == 28) copy_array(m, slot, a2, a1); // SetDescriptorHeaps(count, heaps) + if (m->kind == Kind::fence) { + switch (slot) { + case 8: return fence_completed(m); // GetCompletedValue + case 9: return static_cast(fence_set_event(m, a1, reinterpret_cast(a2))); + case 10: fence_signal(m, a1); return S_OK; // Signal + default: break; + } + } + if (m->kind == Kind::queue && slot == 16 && a1) { + // GetTimestampFrequency writes a fixed value — unless a1 is a mock object, which on this slot is a + // newer-layout Signal's fence, not an out pointer. + const auto at = static_cast(a1); + const auto base = reinterpret_cast(g_pool); + const bool is_mock = at >= base && at < base + sizeof(g_pool) && (at - base) % sizeof(Mock) == 0; + if (!is_mock) *reinterpret_cast(a1) = 1000000; + } + if (m->kind == Kind::heap && slot == 9) { + if (a1) reinterpret_cast(a1)->ptr = kMockHeapCpuStart; + return kMockHeapCpuStart; + } + if (m->kind == Kind::heap && slot == 10) { + if (a1) reinterpret_cast(a1)->ptr = kMockHeapGpuStart; + return kMockHeapGpuStart; + } + if ((m->kind == Kind::list || m->kind == Kind::command_list) && slot == 46) { // OMSetRenderTargets + m->om_rtv_count = static_cast(a1); + m->om_single_range = static_cast(a3); + std::memset(m->om_rtvs, 0, sizeof(m->om_rtvs)); + const auto* rtvs = reinterpret_cast(a2); + if (rtvs && m->om_rtv_count > 0) { + const UINT n = m->om_single_range + ? 1u + : (m->om_rtv_count < D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT + ? m->om_rtv_count + : D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT); + for (UINT i = 0; i < n; ++i) m->om_rtvs[i] = rtvs[i].ptr; + } + const auto* dsv = reinterpret_cast(a4); + m->om_has_dsv = dsv != nullptr; + m->om_dsv = dsv ? dsv->ptr : 0; + } return S_OK; } template std::uint64_t WINAPI mock_slot(Mock* self, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, std::uint64_t a4, - std::uint64_t a5) { + std::uint64_t a5, std::uint64_t a6) { if constexpr (Slot == 0) { return static_cast(mock_query(self, reinterpret_cast(a1), reinterpret_cast(a2))); } else if constexpr (Slot == 1) { return static_cast(++self->refs); } else if constexpr (Slot == 2) { - return static_cast(--self->refs); + const long left = --self->refs; + if (left == 0 && self->held) { // destroyed: private data goes with it + IUnknown* const held = self->held; + self->held = nullptr; + held->Release(); + } + return static_cast(left); + } else if constexpr (Slot == 5) { // SetPrivateDataInterface(guid, object): keeps one reference + ++self->calls[5]; + auto* const object = reinterpret_cast(a2); + if (object) object->AddRef(); + if (self->held) self->held->Release(); + self->held = object; + return S_OK; } else { // A caller may pass fewer words than this thunk declares (OpenSharedHandle passes three), so its frame // has no room past the four register homes. The words are copied into this frame and passed by pointer: // forwarding them as stack arguments let MSVC tail-call mock_call and write into the caller's saved // registers (an optimized build corrupted the test's own locals that way). ++self->calls[Slot]; - const std::uint64_t words[] = {a1, a2, a3, a4, a5}; + const std::uint64_t words[] = {a1, a2, a3, a4, a5, a6}; std::memcpy(self->args[Slot], words, sizeof(words)); return mock_call(self, Slot, words); } } +void WINAPI mock_clear_depth_stencil_view(Mock* self, D3D12_CPU_DESCRIPTOR_HANDLE dsv, D3D12_CLEAR_FLAGS flags, + FLOAT depth, UINT8 stencil, UINT num_rects, const D3D12_RECT* rects) { + ++self->calls[47]; + self->clear_dsv_handle = dsv.ptr; + self->clear_dsv_flags = flags; + self->clear_dsv_depth = depth; + self->clear_dsv_stencil = stencil; + self->clear_dsv_num_rects = num_rects; + self->clear_dsv_rects = rects; +} + // PC ID3D12Device::CreateCommandList takes six words after `this`, one more than the generic mock thunk declares, so // it gets its own entry in the table: the out pointer is a6 (first stack argument on x64) and has to be written. HRESULT WINAPI mock_create_command_list(Mock* self, std::uint64_t node_mask, std::uint64_t type, @@ -257,12 +467,100 @@ HRESULT WINAPI mock_create_command_list(Mock* self, std::uint64_t node_mask, std if (!out) return S_FALSE; *out = nullptr; if (self->create_null || FAILED(self->create_result)) return self->create_result; - Mock* child = new_mock(Kind::command_list); - child->list_level = self->list_level; + Mock* child = new_mock(self->full_chain_lists ? Kind::list : Kind::command_list); self->last_child = child; return mock_query(child, riid, out); } +// PC ID3D12Device::CreateCommittedResource (slot 27) takes seven words after `this`, so it has its own entry too. It +// records what it was given (the description by value) and makes a resource mock. +struct CommittedCall { + D3D12_HEAP_PROPERTIES heap; + D3D12_HEAP_FLAGS heap_flags; + D3D12_RESOURCE_DESC desc; + D3D12_RESOURCE_STATES state; + const D3D12_CLEAR_VALUE* clear; + const IID* riid; +}; +CommittedCall g_committed{}; + +HRESULT WINAPI mock_create_committed_resource(Mock* self, const D3D12_HEAP_PROPERTIES* heap, + D3D12_HEAP_FLAGS heap_flags, const D3D12_RESOURCE_DESC* desc, + D3D12_RESOURCE_STATES state, const D3D12_CLEAR_VALUE* clear, + const IID* riid, void** out) { + // Seven words after `this`, so a device answers it from its own entry; other kinds keep the generic path. + ++self->calls[27]; + const std::uint64_t words[] = {reinterpret_cast(heap), static_cast(heap_flags), + reinterpret_cast(desc), static_cast(state), + reinterpret_cast(clear)}; + std::memcpy(self->args[27], words, sizeof(words)); + if (self->kind != Kind::device) return static_cast(mock_call(self, 27, words)); + g_committed = CommittedCall{}; + if (heap) g_committed.heap = *heap; + g_committed.heap_flags = heap_flags; + if (desc) g_committed.desc = *desc; + g_committed.state = state; + g_committed.clear = clear; + g_committed.riid = riid; + if (!out) return S_FALSE; + *out = nullptr; + if (self->create_null || FAILED(self->create_result)) return self->create_result; + Mock* child = new_mock(Kind::resource); + self->last_child = child; + return mock_query(child, riid, out); +} + +#ifdef __ID3D12Device10_INTERFACE_DEFINED__ +// PC ID3D12Device10::CreateCommittedResource3 (PC slot 76) takes ten words after `this`, so it has its own entry that +// keeps all of them: the resource description is copied because the caller's copy is a local of the proxy. Two +// records: slot 133's Device10 path (g_committed3_133) and slot 127's (g_committed3). +struct Committed3Call { + unsigned calls; + D3D12_HEAP_PROPERTIES heap; + D3D12_RESOURCE_DESC1 desc; + std::uint32_t layout; + const D3D12_CLEAR_VALUE* clear; + const void* session; + UINT castable_count; + const IID* riid; +}; +Committed3Call g_committed3_133{}; + +struct CommittedResource3Call { + unsigned calls; + const Mock* device; // the PC object the call arrived on + const D3D12_HEAP_PROPERTIES* heap; + D3D12_HEAP_FLAGS heap_flags; + D3D12_RESOURCE_DESC1 desc; + std::uint32_t layout; + const D3D12_CLEAR_VALUE* clear; + const void* session; + std::uint32_t castable_count; + const DXGI_FORMAT* castable_formats; + const IID* riid; + void** out; +}; +CommittedResource3Call g_committed3; + +HRESULT WINAPI mock_create_committed_resource3(Mock* self, const D3D12_HEAP_PROPERTIES* heap, D3D12_HEAP_FLAGS flags, + const D3D12_RESOURCE_DESC1* desc, std::uint32_t layout, + const D3D12_CLEAR_VALUE* clear, const void* session, + std::uint32_t castable_count, const DXGI_FORMAT* castable_formats, + const IID* riid, void** out) { + g_committed3 = {g_committed3.calls + 1, self, heap, flags, *desc, layout, clear, session, castable_count, + castable_formats, riid, out}; + ++g_committed3_133.calls; + if (heap) g_committed3_133.heap = *heap; + if (desc) g_committed3_133.desc = *desc; + g_committed3_133.layout = layout; + g_committed3_133.clear = clear; + g_committed3_133.session = session; + g_committed3_133.castable_count = castable_count; + g_committed3_133.riid = riid; + return mock_create(self, Kind::resource, reinterpret_cast(riid), reinterpret_cast(out)); +} +#endif + template void fill_mock_vtable(void** vtable, std::index_sequence) { ((vtable[I] = reinterpret_cast(&mock_slot(I)>)), ...); @@ -273,6 +571,21 @@ void** mock_vtable() { static const bool filled = [] { fill_mock_vtable(table, std::make_index_sequence{}); table[12] = reinterpret_cast(&mock_create_command_list); + table[27] = reinterpret_cast(&mock_create_committed_resource); +#ifdef __ID3D12Device10_INTERFACE_DEFINED__ + table[76] = reinterpret_cast(&mock_create_committed_resource3); +#endif + return true; + }(); + (void)filled; + return table; +} + +void** mock_list_vtable() { + static void* table[kMockSlots]; + static const bool filled = [] { + fill_mock_vtable(table, std::make_index_sequence{}); + table[47] = reinterpret_cast(&mock_clear_depth_stencil_view); return true; }(); (void)filled; @@ -288,10 +601,25 @@ using SlotFn = std::uint64_t(WINAPI*)(void*, std::uint64_t, std::uint64_t, std:: std::uint64_t raw(const void* object, unsigned slot, std::uint64_t a1 = 0, std::uint64_t a2 = 0, std::uint64_t a3 = 0, std::uint64_t a4 = 0, std::uint64_t a5 = 0, std::uint64_t a6 = 0) { void* const* vtable = *reinterpret_cast(object); + return reinterpret_cast(vtable[slot])(const_cast(object), a1, a2, a3, a4, a5, a6, 0, 0, 0, 0, + 0, 0, 0, 0); +} + +// The same with a sixth word, the first stack argument (slot 133's output pointer). +std::uint64_t raw6(const void* object, unsigned slot, std::uint64_t a1, std::uint64_t a2, std::uint64_t a3, + std::uint64_t a4, std::uint64_t a5, std::uint64_t a6) { + void* const* vtable = *reinterpret_cast(object); return reinterpret_cast(vtable[slot])(const_cast(object), a1, a2, a3, a4, a5, a6, 0, 0, 0, 0, 0, 0, 0, 0); } +// A call with the ten words of device slot 127 (and any other slot that takes up to ten). +std::uint64_t raw10(const void* object, unsigned slot, const std::uint64_t (&w)[10]) { + void* const* vtable = *reinterpret_cast(object); + return reinterpret_cast(vtable[slot])(const_cast(object), w[0], w[1], w[2], w[3], w[4], w[5], w[6], + w[7], w[8], w[9], 0, 0, 0, 0); +} + HRESULT hr_of(std::uint64_t value) { return static_cast(static_cast(value)); } @@ -308,16 +636,20 @@ const IID kUnknownIid = __uuidof(IUnknown); const IID kResourceIid = __uuidof(ID3D12Resource); const IID kDevice1Iid = __uuidof(ID3D12Device1); const D3D12_COMMAND_QUEUE_DESC kQueueDesc{}; +// The retail title's slot 48 desc is 32 bytes (the route logs words 4..7); type in word 0 as in kQueueDesc. +const std::uint32_t kXboxQueueDesc[8]{}; // A device proxy over a new mock device. The proxy takes the mock's one reference. -void* make_device(Mock*& mock, int level, bool fence1, bool allocator_tag = true) { +void* make_device(Mock*& mock, int level, bool fence1, bool allocator_tag = true, bool full_chain_lists = false) { mock = new_mock(Kind::device); mock->device_level = level; mock->fence1 = fence1; mock->allocator_tag = allocator_tag; + mock->full_chain_lists = full_chain_lists; mock->refs = 1; void* device = nullptr; - if (FAILED(xs::create_device_proxy(reinterpret_cast(mock), __uuidof(ID3D12Device), &device))) + if (FAILED(xs::create_device_proxy(reinterpret_cast(mock), __uuidof(ID3D12Device), &device, + /*console_lists=*/true))) return nullptr; return device; } @@ -398,109 +730,36 @@ int check_levels() { EXPECT(r75 == E_NOTIMPL && !queue1 && mock->calls[75] == 0); } - // 133: past every PC device vtable; the retail title calls it. Refused, not a jump through a missing entry. - EXPECT(hr_of(raw(device, 133)) == E_NOTIMPL && mock->calls[127] == 0); - - // 133 with a handler (CreatePlacedResourceX): the arguments in the title's positions (va, desc, state, - // clear, riid, out) reach the handler with the real device, the Xbox flag bits masked to the PC ones the host - // takes (0x20004 -> 0x4, and 0x200 dropped) and the buffer's Xbox layout word made ROW_MAJOR. - { - static void* seen_real = nullptr; - static void* seen_va = nullptr; - static D3D12_RESOURCE_DESC seen_desc{}; - static GUID seen_iid{}; - static std::uint32_t seen_layout = 0; - const xs::PlacedAtVaHandler handler = [](ID3D12Device* real_device, void* va, - const D3D12_RESOURCE_DESC& desc, std::uint32_t layout, - REFIID iid, void** out) -> HRESULT { - seen_layout = layout; - seen_real = real_device; - seen_va = va; - seen_desc = desc; - seen_iid = iid; - *out = reinterpret_cast(0x1330); - return S_OK; - }; - xs::set_placed_at_va_handler(handler); - D3D12_RESOURCE_DESC xbox_desc{}; - xbox_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - xbox_desc.Width = 0x10000; - xbox_desc.Height = xbox_desc.DepthOrArraySize = xbox_desc.MipLevels = 1; - xbox_desc.SampleDesc.Count = 1; - xbox_desc.Layout = static_cast(0x1); // the Xbox row-major word - xbox_desc.Flags = static_cast(0x20204); - const GUID resource_iid = __uuidof(ID3D12Resource); - void* placed = nullptr; - void* const va = reinterpret_cast(0x7f0000000000ull); - const HRESULT r133 = hr_of(raw(device, 133, word(va), word(&xbox_desc), 0xFFFFFFFFull, 0, - word(&resource_iid), word(&placed))); - xs::set_placed_at_va_handler(nullptr); - EXPECT(r133 == S_OK && placed == reinterpret_cast(0x1330)); - EXPECT(seen_real == xs::device_proxy_real_device(device) && seen_va == va); - EXPECT(static_cast(seen_desc.Flags) == 0x4); - EXPECT(seen_desc.Layout == D3D12_TEXTURE_LAYOUT_ROW_MAJOR && seen_desc.Width == 0x10000); - EXPECT(std::memcmp(&seen_iid, &resource_iid, sizeof(GUID)) == 0); - EXPECT(seen_layout == 0xFFFFFFFFu); // the title's third word, passed through as the barrier layout - EXPECT(xs::device_slot_overridden(133)); + // 134: past every PC device vtable and not handled by the proxy (133 is, see check_placed_resource_x). + // Refused, not a jump through a missing entry. + EXPECT(hr_of(raw(device, 134)) == E_NOTIMPL && mock->calls[127] == 0); + // 86: Xbox CreatePipelineState -> PC slot 47 (ID3D12Device2) + void* pso_out = reinterpret_cast(1); + const HRESULT r86 = hr_of(raw(device, 86, 0, word(&kUnknownIid), word(&pso_out))); + if (l.level >= 2) { + EXPECT(r86 == S_OK && mock->calls[47] == 1 && mock->calls[86] == 0); + } else { + EXPECT(r86 == E_NOTIMPL && !pso_out && mock->calls[47] == 0 && mock->calls[86] == 0); } - // 133 with a pages hook (set_placed_at_va_pages_hook): a buffer's range [va, va + width) is handed to it - // before the handler runs; a texture is not; a hook that fails still leaves the call to the handler. - { - static int order = 0; - static int hook_at = 0; - static int handler_at = 0; - static const void* hook_va = nullptr; - static std::size_t hook_bytes = 0; - static bool hook_result = true; - order = hook_at = handler_at = 0; - const xs::PlacedAtVaPagesHook hook = [](const void* va, std::size_t bytes) -> bool { - hook_at = ++order; - hook_va = va; - hook_bytes = bytes; - return hook_result; - }; - const xs::PlacedAtVaHandler handler = [](ID3D12Device*, void*, const D3D12_RESOURCE_DESC&, std::uint32_t, - REFIID, void** out) -> HRESULT { - handler_at = ++order; - *out = reinterpret_cast(0x1331); - return S_OK; - }; - xs::set_placed_at_va_handler(handler); - xs::set_placed_at_va_pages_hook(hook); - D3D12_RESOURCE_DESC xbox_desc{}; - xbox_desc.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; - xbox_desc.Width = 0xadf0000; - xbox_desc.Height = xbox_desc.DepthOrArraySize = xbox_desc.MipLevels = 1; - xbox_desc.SampleDesc.Count = 1; - xbox_desc.Layout = static_cast(0x1); - const GUID resource_iid = __uuidof(ID3D12Resource); - void* placed = nullptr; - void* const va = reinterpret_cast(0x7f0000010000ull); - auto place = [&]() { - placed = nullptr; - return hr_of(raw(device, 133, word(va), word(&xbox_desc), 0xFFFFFFFFull, 0, word(&resource_iid), - word(&placed))); - }; - const HRESULT buffer_hr = place(); - EXPECT(buffer_hr == S_OK && placed == reinterpret_cast(0x1331)); - EXPECT(hook_at == 1 && handler_at == 2 && hook_va == va && hook_bytes == 0xadf0000); - - hook_result = false; - order = hook_at = handler_at = 0; - const HRESULT refused_hr = place(); - EXPECT(refused_hr == S_OK && hook_at == 1 && handler_at == 2); - hook_result = true; - - xbox_desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; - xbox_desc.Width = 64; - xbox_desc.Height = 64; - order = hook_at = handler_at = 0; - const HRESULT texture_hr = place(); - EXPECT(texture_hr == S_OK && hook_at == 0 && handler_at == 1); - - xs::set_placed_at_va_pages_hook(nullptr); - xs::set_placed_at_va_handler(nullptr); + // 101: Xbox CreateStateObject -> PC slot 62 (ID3D12Device5) + void* so_out = reinterpret_cast(1); + const HRESULT r101 = hr_of(raw(device, 101, 0, word(&kUnknownIid), word(&so_out))); + if (l.level >= 5) { + EXPECT(r101 == S_OK && mock->calls[62] == 1 && mock->calls[101] == 0); + } else { + EXPECT(r101 == E_NOTIMPL && !so_out && mock->calls[62] == 0 && mock->calls[101] == 0); + } + + // 108: Xbox GetResourceAllocationInfo2 -> PC slot 68 (ID3D12Device8) + D3D12_RESOURCE_ALLOCATION_INFO alloc_info{1, 1}; + const std::uint64_t r108 = raw(device, 108, word(&alloc_info), 1, 0, 0, 0); + if (l.level >= 8) { + EXPECT(r108 == word(&alloc_info) && alloc_info.SizeInBytes == 0x40000 && alloc_info.Alignment == 0x10000 && + mock->calls[68] == 1 && mock->calls[108] == 0); + } else { + EXPECT(r108 == word(&alloc_info) && alloc_info.SizeInBytes == UINT64_MAX && alloc_info.Alignment == 0 && + mock->calls[68] == 0 && mock->calls[108] == 0); } Mock* const queue_mock = reinterpret_cast(real_queue); @@ -514,6 +773,30 @@ int check_levels() { return 0; } +// ---- 1b. Slot 48: the title's CreateCommandQueue with a 32-byte description ---- + +int check_slot48() { + Mock* mock = nullptr; + void* device = make_device(mock, 3, true); + EXPECT(device); + // 16-byte PC prefix, then four Xbox words; the flags carry a bit the PC does not know besides the timeout bit. + const std::uint32_t desc[8] = {D3D12_COMMAND_LIST_TYPE_COMPUTE, 100, + 0x8000u | D3D12_COMMAND_QUEUE_FLAG_DISABLE_GPU_TIMEOUT, 1, 0x11, 0x22, 0x33, 0x44}; + void* queue = reinterpret_cast(1); + EXPECT(hr_of(raw(device, 48, word(desc), word(&kQueueIid), word(&queue))) == S_OK); + EXPECT(xs::is_queue_proxy(queue) && mock->calls[8] == 1); + EXPECT(mock->queue_desc.Type == D3D12_COMMAND_LIST_TYPE_COMPUTE && mock->queue_desc.Priority == 100 && + mock->queue_desc.Flags == D3D12_COMMAND_QUEUE_FLAG_DISABLE_GPU_TIMEOUT && + mock->queue_desc.NodeMask == 1); + EXPECT(release(queue) == 0); + void* none = reinterpret_cast(1); + EXPECT(hr_of(raw(device, 48, 0, word(&kQueueIid), word(&none))) == E_INVALIDARG && !none); + EXPECT(mock->calls[8] == 1); + EXPECT(release(device) == 0); + std::printf("%s: slot 48 makes a queue proxy from a 32-byte description, PC prefix and flags only\n", g_label); + return 0; +} + // ---- 2. Fences with and without ID3D12Fence1 ---- int check_fence1() { @@ -558,6 +841,117 @@ int check_fence1() { return 0; } +// ---- Fence slot 12: the completed value at an address ---- + +std::atomic g_descriptor_calls{0}; +void WINAPI descriptor_callback() { g_descriptor_calls.fetch_add(1); } + +// True once *completed reads `value`, within five seconds (the proxy's wait thread writes it). +bool reads_within(const volatile std::uint64_t* completed, std::uint64_t value) { + for (int i = 0; i < 5000; ++i) { + if (*completed == value) return true; + Sleep(1); + } + return *completed == value; +} + +bool fence_armed_for(Mock* fence, std::uint64_t value) { + AcquireSRWLockExclusive(&fence->lock); + const bool armed = fence->armed_event && fence->armed_value == value; + ReleaseSRWLockExclusive(&fence->lock); + return armed; +} + +int check_fence_completed_value() { + for (const bool fence1 : {false, true}) { // past ID3D12Fence1 either way + Mock* mock = nullptr; + void* device = make_device(mock, 9, fence1); + EXPECT(device); + void* fence = make_fence(device); + Mock* const fence_mock = mock->last_child; + void* other = make_fence(device); + Mock* const other_mock = mock->last_child; + EXPECT(fence && other && fence_mock != other_mock); + + // The title's shape: (value, descriptor with a code pointer in its second word, flags). + const std::uint64_t descriptor[4] = {0, reinterpret_cast(&descriptor_callback), 0, 0}; + const auto* completed = + reinterpret_cast(raw(fence, 12, 9, word(descriptor), 1)); + EXPECT(completed && *completed == kCompletedValue); + EXPECT(xs::fence_slot_first_call_seen(12)); + EXPECT(raw(fence, 12, 9, word(descriptor), 1) == word(completed)); // one address per fence + const auto* other_completed = reinterpret_cast(raw(other, 12, 0, 0, 0)); + EXPECT(other_completed && other_completed != completed); + + // A CPU Signal through the proxy shows at once. + EXPECT(hr_of(raw(fence, 10, 9)) == S_OK && fence_mock->completed == 9); + EXPECT(*completed == 9 && *other_completed == kCompletedValue); + // A signal the proxy never sees (a queue's, on the GPU) shows without another call, and again after it. + fence_signal(fence_mock, 12); + EXPECT(reads_within(completed, 12)); + fence_signal(fence_mock, 40); + EXPECT(reads_within(completed, 40)); + fence_signal(other_mock, 8); + EXPECT(reads_within(other_completed, 8) && *completed == 40); + // Wait for the wait thread to arm its next threshold before rewinding. + const ULONGLONG until = GetTickCount64() + 1000; + while (!fence_armed_for(fence_mock, 41) && GetTickCount64() < until) Sleep(1); + EXPECT(fence_armed_for(fence_mock, 41)); + EXPECT(hr_of(raw(fence, 10, 3)) == S_OK && *completed == 3); + fence_signal(fence_mock, 15); + EXPECT(fence_completed(fence_mock) == 15); + if (!reads_within(completed, 15)) { + std::fprintf(stderr, "rewind: underlying fence %llu, slot 12 mirror %llu\n", + static_cast(fence_completed(fence_mock)), + static_cast(*completed)); + return 1; + } + // A rewind by a producer outside the proxy can go straight below its outstanding event. + fence_signal(fence_mock, 2); + EXPECT(reads_within(completed, 2)); + fence_signal(fence_mock, 7); + EXPECT(reads_within(completed, 7)); + // The fallback must leave the pending completion event alone. + EXPECT(fence_armed_for(fence_mock, 41)); + fence_signal(fence_mock, 45); + EXPECT(reads_within(completed, 45)); + // Device removal: the real fence reports ~0, which the title tests for, and nothing is armed after it. + fence_signal(fence_mock, ~std::uint64_t{0}); + EXPECT(reads_within(completed, ~std::uint64_t{0})); + Sleep(50); + AcquireSRWLockExclusive(&fence_mock->lock); + const bool rearmed = fence_mock->armed_event != nullptr; + ReleaseSRWLockExclusive(&fence_mock->lock); + EXPECT(!rearmed); + EXPECT(g_descriptor_calls.load() == 0); // the descriptor's code pointer is not called + + // Release waits out the wait thread; both fences and the device go back to zero references. + EXPECT(release(fence) == 0 && fence_mock->refs == 0); + EXPECT(release(other) == 0 && other_mock->refs == 0); + + // A fence whose slot 12 is never called arms nothing on the real fence. + void* quiet = make_fence(device); + Mock* const quiet_mock = mock->last_child; + EXPECT(quiet && hr_of(raw(quiet, 10, 3)) == S_OK && raw(quiet, 8) == 3 && quiet_mock->calls[9] == 0); + EXPECT(release(quiet) == 0 && quiet_mock->refs == 0); + + // Out of memory for the mirror: slot 12 returns null, and the next call works. + void* starved = make_fence(device); + EXPECT(starved); + g_fail_news = 1; + const std::uint64_t none = raw(starved, 12, 0, 0, 0); + g_fail_news = 0; + EXPECT(none == 0); + const auto* later = reinterpret_cast(raw(starved, 12, 0, 0, 0)); + EXPECT(later && *later == kCompletedValue); + EXPECT(release(starved) == 0); + EXPECT(release(device) == 0 && mock->refs == 0); + } + std::printf("%s: fence slot 12 returns one address per fence whose completed value follows CPU and unseen " + "signals up to device removal; the descriptor is not called\n", g_label); + return 0; +} + // ---- 3. Creation failures and refused interfaces ---- int check_create_failures() { @@ -747,9 +1141,21 @@ int check_allocators() { EXPECT(xs::is_allocator_proxy(allocator) && word(xs::allocator_proxy_real_allocator(allocator)) == word(real)); EXPECT(mock->args[9][0] == D3D12_COMMAND_LIST_TYPE_DIRECT && real->refs == 1); EXPECT(xs::allocator_proxy_slot_count(allocator) == 9 && xs::device_proxy_ref_count(device) == device_refs + 1); - // Reset (slot 8) reaches the real allocator; every slot past it up to the table end is refused. + // Reset (slot 8) reaches the real allocator; slot 9 (SetAllocatorCallbackX) records callback/context and + // succeeds without touching the real vtable; every slot past 9 up to the table end is refused. EXPECT(hr_of(raw(allocator, 8)) == S_OK && real->calls[8] == 1); - for (unsigned slot = 9; slot < xs::allocator_proxy_table_size(); ++slot) + EXPECT(xs::allocator_proxy_callback(allocator) == 0 && xs::allocator_proxy_callback_context(allocator) == 0); + EXPECT(xs::allocator_proxy_callback(nullptr) == 0 && xs::allocator_proxy_callback_context(device) == 0); + constexpr std::uintptr_t fake_cb = 0x12345678u; + constexpr std::uintptr_t fake_ctx = 0x9abcdef0u; + const std::uint64_t slot9_hits_before = xs::allocator_slot_hits(9); + EXPECT(hr_of(raw(allocator, 9, fake_cb, fake_ctx, 0, 0xfeedfaceu)) == S_OK && real->calls[9] == 0); + EXPECT(xs::allocator_slot_hits(9) == slot9_hits_before + 1 && xs::allocator_slot_first_call_seen(9)); + EXPECT(xs::allocator_proxy_callback(allocator) == fake_cb && + xs::allocator_proxy_callback_context(allocator) == fake_ctx); + EXPECT(hr_of(raw(allocator, 9, 0, 0)) == S_OK && real->calls[9] == 0); + EXPECT(xs::allocator_proxy_callback(allocator) == 0 && xs::allocator_proxy_callback_context(allocator) == 0); + for (unsigned slot = 10; slot < xs::allocator_proxy_table_size(); ++slot) EXPECT(hr_of(raw(allocator, slot)) == E_NOTIMPL && real->calls[slot] == 0); // The tag and the real object stay hidden: QueryInterface answers only the modelled interfaces. void* found = reinterpret_cast(1); @@ -809,7 +1215,115 @@ int check_allocators() { return 0; } +// ---- 6b. Device slot 133: a resource placed at a VA becomes a committed DEFAULT-heap resource ---- +// +// The device stops at ID3D12Device9 (76 slots), so 133 is past its table: the proxy must answer it before the +// beyond-table refusal and reach the PC CreateCommittedResource (slot 27) with a cleaned description. +int check_placed_resource_x() { + Mock* mock = nullptr; + void* device = make_device(mock, 9, true); + EXPECT(device && xs::device_slot_overridden(133)); + xs::reset_device_proxy_stats(); + constexpr std::uint64_t kVa = 0x7f0000000000ull; // any address: the stand-in does not touch it + const auto kXboxFlag = static_cast(0x20000); // not constexpr: outside the enum's range for clang // a bit above every PC flag + + // The fourth word is a D3D12_BARRIER_LAYOUT. On this device (no ID3D12Device10) it becomes the legacy state. + // A buffer with an Xbox flag bit, a non-PC layout word and the all-ones layout (UNDEFINED): PC flags only, + // ROW_MAJOR, COMMON, no clear value, DEFAULT heap, and the caller's IID. + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = 1 << 20; + buffer.Height = 1; + buffer.DepthOrArraySize = 1; + buffer.MipLevels = 1; + buffer.SampleDesc.Count = 1; + buffer.Layout = static_cast(0x101); + buffer.Flags = static_cast(D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | kXboxFlag); + const D3D12_CLEAR_VALUE clear{DXGI_FORMAT_R8G8B8A8_UNORM, {{0, 0, 0, 1}}}; + void* resource = nullptr; + EXPECT(hr_of(raw6(device, 133, kVa, word(&buffer), 0xFFFFFFFFu, word(&clear), word(&kResourceIid), + word(&resource))) == S_OK); + EXPECT(resource && reinterpret_cast(resource)->kind == Kind::resource); + EXPECT(mock->calls[27] == 1 && mock->calls[127] == 0 && xs::device_slot_hits(133) == 1); + EXPECT(g_committed.heap.Type == D3D12_HEAP_TYPE_DEFAULT && g_committed.heap_flags == D3D12_HEAP_FLAG_NONE); + EXPECT(g_committed.desc.Flags == D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS); + EXPECT(g_committed.desc.Layout == D3D12_TEXTURE_LAYOUT_ROW_MAJOR && g_committed.desc.Width == buffer.Width); + EXPECT(g_committed.state == D3D12_RESOURCE_STATE_COMMON && !g_committed.clear); + EXPECT(g_committed.riid == &kResourceIid); + EXPECT(release(resource) == 0); + + // A render-target texture in the RENDER_TARGET layout (2) gets that state and its clear value; the texture layout + // becomes UNKNOWN. + D3D12_RESOURCE_DESC target = buffer; + target.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + target.Width = 64; + target.Height = 32; + target.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + target.Flags = static_cast(D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | kXboxFlag); + EXPECT(hr_of(raw6(device, 133, kVa, word(&target), 2, word(&clear), word(&kResourceIid), word(&resource))) == S_OK); + EXPECT(mock->calls[27] == 2 && g_committed.desc.Flags == D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET); + EXPECT(g_committed.desc.Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN); + EXPECT(g_committed.state == D3D12_RESOURCE_STATE_RENDER_TARGET && g_committed.clear == &clear); + EXPECT(release(resource) == 0); + // The same texture in the all-ones layout (UNDEFINED) is created in COMMON. + EXPECT(hr_of(raw6(device, 133, kVa, word(&target), 0xFFFFFFFFu, 0, word(&kResourceIid), word(&resource))) == + S_OK); + EXPECT(mock->calls[27] == 3 && g_committed.state == D3D12_RESOURCE_STATE_COMMON); + EXPECT(release(resource) == 0); + // The SHADER_RESOURCE layout (6), which the title passes for its 1x1 targets, is the shader-resource states, not + // INDEX_BUFFER | RENDER_TARGET. + EXPECT(hr_of(raw6(device, 133, kVa, word(&target), 6, 0, word(&kResourceIid), word(&resource))) == S_OK); + EXPECT(mock->calls[27] == 4 && g_committed.state == D3D12_RESOURCE_STATE_ALL_SHADER_RESOURCE); + EXPECT(release(resource) == 0); + + // Refusals before the device is called; the output is cleared. + resource = reinterpret_cast(1); + EXPECT(hr_of(raw6(device, 133, kVa, 0, 0, 0, word(&kResourceIid), word(&resource))) == E_INVALIDARG); + EXPECT(!resource); + resource = reinterpret_cast(1); + EXPECT(hr_of(raw6(device, 133, kVa, word(&buffer), 0, 0, 0, word(&resource))) == E_POINTER && !resource); + EXPECT(hr_of(raw6(device, 133, kVa, word(&buffer), 0, 0, word(&kResourceIid), 0)) == E_POINTER); + EXPECT(mock->calls[27] == 4); + + // A failed creation is returned as it is, with no object. + mock->create_result = E_OUTOFMEMORY; + resource = reinterpret_cast(1); + EXPECT(hr_of(raw6(device, 133, kVa, word(&buffer), 0, 0, word(&kResourceIid), word(&resource))) == + E_OUTOFMEMORY); + EXPECT(!resource && mock->calls[27] == 5); + mock->create_result = S_OK; + + EXPECT(release(device) == 0 && mock->refs == 0); + +#ifdef __ID3D12Device10_INTERFACE_DEFINED__ + // A PC device with ID3D12Device10: CreateCommittedResource3 with the layout as given, never CreateCommittedResource. + Mock* mock10 = nullptr; + void* device10 = make_device(mock10, 10, true); + EXPECT(device10); + g_committed3_133 = {}; + EXPECT(hr_of(raw6(device10, 133, kVa, word(&target), 6, word(&clear), word(&kResourceIid), word(&resource))) == + S_OK); + EXPECT(resource && g_committed3_133.calls == 1 && mock10->calls[27] == 0); + EXPECT(g_committed3_133.layout == 6 && g_committed3_133.clear == &clear && !g_committed3_133.session && + g_committed3_133.castable_count == 0 && g_committed3_133.riid == &kResourceIid); + EXPECT(g_committed3_133.heap.Type == D3D12_HEAP_TYPE_DEFAULT); + EXPECT(g_committed3_133.desc.Flags == D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET && + g_committed3_133.desc.Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN && g_committed3_133.desc.Width == 64); + EXPECT(release(resource) == 0); + // A buffer goes in UNDEFINED whatever word it came with. + EXPECT(hr_of(raw6(device10, 133, kVa, word(&buffer), 2, 0, word(&kResourceIid), word(&resource))) == S_OK); + EXPECT(g_committed3_133.calls == 2 && g_committed3_133.layout == 0xFFFFFFFFu && !g_committed3_133.clear); + EXPECT(release(resource) == 0); + EXPECT(release(device10) == 0 && mock10->refs == 0); +#endif + std::printf("%s: device slot 133 places a resource as a committed DEFAULT one (PC flags, its barrier layout, " + "clear value for targets only), past a 76-slot device\n", g_label); + return 0; +} + // ---- 7. Xbox device slots from the public HLE (48, 73, 78, 79, 80) ---- +// ---- 7. Xbox device slots from the public HLE (48, 73, 78, 79, 80) and the retail title (41) ---- +// ---- 7. Xbox device slots from the public HLE (48, 73, 78, 79, 80) and the retail title (61) ---- // // A device that answers ID3D12Device11 (80 PC slots) is the Vulkan layer's shape: slots 78/79 are inside its table // (CreateReservedResource2/CreateSampler2 there) and 80 is just past it. None of the five may reach the mock's own @@ -817,7 +1331,9 @@ int check_allocators() { int check_xbox_slots() { #ifdef __ID3D12Device11_INTERFACE_DEFINED__ Mock* mock = nullptr; - void* device = make_device(mock, 11, true); + // Full-chain lists: the console IID maps to ID3D12GraphicsCommandList6, which a command_list-kind mock + // does not answer. + void* device = make_device(mock, 11, true, true, true); EXPECT(device && xs::device_proxy_slot_count(device) == 80); xs::reset_device_proxy_stats(); @@ -836,11 +1352,10 @@ int check_xbox_slots() { EXPECT(hr_of(raw(device, 80, 0, 0, 0, 0, 0)) == E_POINTER); EXPECT(mock->calls[80] == 0 && xs::device_slot_hits(80) == 3); - // 48 CreateCommandQueueX(desc, riid, out): the queue proxy, created through the PC slot 8 path. + // 48 CreateCommandQueueX(desc, riid, out): the queue proxy, created through the PC slot 8 path (filtered desc copy). void* queue = nullptr; - EXPECT(hr_of(raw(device, 48, word(&kQueueDesc), word(&kQueueIid), word(&queue))) == S_OK); + EXPECT(hr_of(raw(device, 48, word(kXboxQueueDesc), word(&kQueueIid), word(&queue))) == S_OK); EXPECT(xs::is_queue_proxy(queue) && mock->calls[48] == 0 && mock->calls[8] == 1); - EXPECT(mock->args[8][0] == word(&kQueueDesc)); // 73 CreateCommandListX(desc, allocator, initialState, riid, out): the type is desc's first word, the allocator // proxy is unwrapped, the node mask is 0 and the PC six-argument CreateCommandList (slot 12) is reached. @@ -859,13 +1374,27 @@ int check_xbox_slots() { const IID list_iid = __uuidof(ID3D12GraphicsCommandList); void* list = nullptr; EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&list_iid), word(&list))) == S_OK); - EXPECT(xs::is_command_list_proxy(list)); - EXPECT(xs::command_list_proxy_real_list(list) && - reinterpret_cast(xs::command_list_proxy_real_list(list))->kind == Kind::command_list); + // A console device answers with the console-shaped list proxy over the real list, as slot 12 does. + EXPECT(xs::is_list_proxy(list) && + reinterpret_cast(xs::list_proxy_real_list(list))->kind == Kind::list); EXPECT(mock->calls[73] == 0 && mock->calls[12] == 1 && xs::device_slot_hits(73) == 1); EXPECT(mock->args[12][0] == 0 && mock->args[12][1] == D3D12_COMMAND_LIST_TYPE_DIRECT); EXPECT(mock->args[12][2] == word(real_allocator) && mock->args[12][3] == 0); - EXPECT(mock->args[12][4] == word(&list_iid)); + // The real list is created as ID3D12GraphicsCommandList; the console IID the caller asked for is answered by + // the proxy's QueryInterface instead. + EXPECT(mock->args[12][4] == word(&__uuidof(ID3D12GraphicsCommandList))); + + // The measured console list IID (the 1.0.2.1 executable's only GUID of that form) maps to + // ID3D12GraphicsCommandList6: slot 73 answers it, and a QueryInterface for it on the proxy returns the proxy. + const IID console_list_iid = {0xc3827890, 0x4024, 0x474c, {0x98, 0xcf, 0x64, 0x5b, 0x51, 0xdc, 0x48, 0x74}}; + void* console_list = nullptr; + EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&console_list_iid), + word(&console_list))) == S_OK); + EXPECT(xs::is_list_proxy(console_list)); + EXPECT(mock->calls[12] == 2); + void* asked = nullptr; + EXPECT(hr_of(raw(console_list, 0, word(&console_list_iid), word(&asked))) == S_OK && asked == console_list); + EXPECT(release(asked) == 1 && release(console_list) == 0); // Release the list before the refusal calls below: the COM convention (and the handler) nulls the caller's // output on failure, so an invalid call would clear this pointer. @@ -876,14 +1405,141 @@ int check_xbox_slots() { EXPECT(hr_of(raw(device, 73, word(&desc), 0, 0, word(&list_iid), word(&list))) == E_INVALIDARG); EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&list_iid), 0)) == E_POINTER); + // 41 CreateCommandSignature: a console argument of type 105 reaches the PC slot 41 as DISPATCH, in a copy of the + // description (stride, count, the root argument before it and the root signature kept). A PC description is + // passed as the same pointer. + D3D12_INDIRECT_ARGUMENT_DESC console_args[2]{}; + console_args[0].Type = D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT; + console_args[0].Constant.Num32BitValuesToSet = 1; + constexpr std::uint32_t kType105 = 105; // outside the enum's range: written and read as its 32 bits + std::memcpy(&console_args[1].Type, &kType105, sizeof(kType105)); + const D3D12_COMMAND_SIGNATURE_DESC console_sig{16, 2, console_args, 0}; + const IID sig_iid = __uuidof(ID3D12CommandSignature); + void* sig = nullptr; + EXPECT(hr_of(raw(device, 41, word(&console_sig), 0x5150, word(&sig_iid), word(&sig))) == S_OK); + EXPECT(mock->calls[41] == 1 && xs::device_slot_hits(41) == 1); + EXPECT(mock->args[41][0] != word(&console_sig) && mock->args[41][1] == 0x5150); + EXPECT(mock->args[41][2] == word(&sig_iid) && mock->args[41][3] == word(&sig)); + EXPECT(mock->array[41][0] == (16 | std::uint64_t{2} << 32)); + EXPECT(mock->array[41][1] == D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT && + mock->array[41][2] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH); + std::uint32_t caller_type = 0; + std::memcpy(&caller_type, &console_args[1].Type, sizeof(caller_type)); + EXPECT(caller_type == kType105); // the caller's description is untouched + D3D12_INDIRECT_ARGUMENT_DESC pc_arg{}; + pc_arg.Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH; + const D3D12_COMMAND_SIGNATURE_DESC pc_sig{12, 1, &pc_arg, 0}; + EXPECT(hr_of(raw(device, 41, word(&pc_sig), 0, word(&sig_iid), word(&sig))) == S_OK); + EXPECT(mock->calls[41] == 2 && mock->args[41][0] == word(&pc_sig)); + EXPECT(mock->array[41][1] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH); + + // 61 CreateSamplerX(desc, dest): the PC CreateSampler (slot 22) gets the same two words, not the PC slot 61 + // (CreateMetaCommand). A null description is skipped without reaching the device. + D3D12_SAMPLER_DESC sampler{}; + sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; + sampler.AddressU = sampler.AddressV = sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP; + sampler.MaxLOD = D3D12_FLOAT32_MAX; + const std::uint64_t sampler_handle = 0x7ff012340040ull; + raw(device, 61, word(&sampler), sampler_handle); + EXPECT(mock->calls[61] == 0 && mock->calls[22] == 1 && xs::device_slot_hits(61) == 1); + EXPECT(mock->args[22][0] == word(&sampler) && mock->args[22][1] == sampler_handle); + raw(device, 61, 0, sampler_handle); + EXPECT(mock->calls[61] == 0 && mock->calls[22] == 1 && xs::device_slot_hits(61) == 2); + + EXPECT(xs::device_slot_overridden(41) && xs::device_slot_overridden(48) && xs::device_slot_overridden(61) && + xs::device_slot_overridden(73) && + xs::device_slot_overridden(78) && xs::device_slot_overridden(79) && xs::device_slot_overridden(80)); EXPECT(xs::device_slot_overridden(48) && xs::device_slot_overridden(73) && xs::device_slot_overridden(78) && - xs::device_slot_overridden(79) && xs::device_slot_overridden(80)); + xs::device_slot_overridden(79) && xs::device_slot_overridden(80) && xs::device_slot_overridden(86) && + xs::device_slot_overridden(101) && xs::device_slot_overridden(108)); + + // 86 CreatePipelineState(desc, riid, out) -> PC slot 47 (ID3D12Device2::CreatePipelineState). + D3D12_PIPELINE_STATE_STREAM_DESC stream_desc{}; + const IID pso_iid = __uuidof(ID3D12PipelineState); + void* pso_stream_out = nullptr; + EXPECT(hr_of(raw(device, 86, word(&stream_desc), word(&pso_iid), word(&pso_stream_out))) == S_OK); + EXPECT(mock->calls[86] == 0 && mock->calls[47] == 1 && xs::device_slot_hits(86) == 1); + EXPECT(mock->args[47][0] == word(&stream_desc) && mock->args[47][1] == word(&pso_iid) && + mock->args[47][2] == word(&pso_stream_out)); + pso_stream_out = reinterpret_cast(1); + EXPECT(hr_of(raw(device, 86, word(&stream_desc), 0, word(&pso_stream_out))) == E_POINTER && !pso_stream_out); + + // 101 CreateStateObject(desc, riid, out) -> PC slot 62 (ID3D12Device5::CreateStateObject). + D3D12_STATE_OBJECT_DESC state_obj_desc{}; + const IID so_iid = __uuidof(ID3D12StateObject); + void* so_out = nullptr; + EXPECT(hr_of(raw(device, 101, word(&state_obj_desc), word(&so_iid), word(&so_out))) == S_OK); + EXPECT(mock->calls[101] == 0 && mock->calls[62] == 1 && xs::device_slot_hits(101) == 1); + EXPECT(mock->args[62][0] == word(&state_obj_desc) && mock->args[62][1] == word(&so_iid) && + mock->args[62][2] == word(&so_out)); + so_out = reinterpret_cast(1); + EXPECT(hr_of(raw(device, 101, word(&state_obj_desc), 0, word(&so_out))) == E_POINTER && !so_out); + + // 108 GetResourceAllocationInfo2 -> PC slot 68 (ID3D12Device8::GetResourceAllocationInfo2), called with the + // retail executable's C-ABI struct return (return buffer in RCX, device proxy in RDX), 56-byte D3D12_RESOURCE_DESC + // entries, and an Xbox layout/flag word, as well as the PC C++ argument order. + void* const* proxy_vtable = *reinterpret_cast(device); + using CAbiSlot108Fn = D3D12_RESOURCE_ALLOCATION_INFO*(WINAPI*)( + D3D12_RESOURCE_ALLOCATION_INFO*, void*, UINT, UINT, const D3D12_RESOURCE_DESC*, + D3D12_RESOURCE_ALLOCATION_INFO1*); + const auto call_slot108_c_abi = reinterpret_cast(proxy_vtable[108]); + D3D12_RESOURCE_DESC xbox_descs[2]{}; + xbox_descs[0].Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + xbox_descs[0].Width = 3840; + xbox_descs[0].Height = 2160; + xbox_descs[0].DepthOrArraySize = 1; + xbox_descs[0].MipLevels = 1; + xbox_descs[0].Format = DXGI_FORMAT_R8G8B8A8_UNORM; + xbox_descs[0].SampleDesc.Count = 1; + xbox_descs[0].Layout = static_cast(0x105); + xbox_descs[0].Flags = static_cast( + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | 0x300000u); + xbox_descs[1].Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + xbox_descs[1].Width = 4096; + xbox_descs[1].Height = 1; + xbox_descs[1].DepthOrArraySize = 1; + xbox_descs[1].MipLevels = 1; + xbox_descs[1].SampleDesc.Count = 1; + xbox_descs[1].Layout = static_cast(0x101); + xbox_descs[1].Flags = static_cast(D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | 0x200000u); + D3D12_RESOURCE_ALLOCATION_INFO ret_info{}; + D3D12_RESOURCE_ALLOCATION_INFO1 detail_info[2]{}; + EXPECT(call_slot108_c_abi(&ret_info, device, 1, 2, xbox_descs, detail_info) == &ret_info); + EXPECT(ret_info.SizeInBytes == 0x40000 && ret_info.Alignment == 0x10000); + EXPECT(detail_info[0].SizeInBytes == 0x40000 && detail_info[0].Alignment == 0x10000); + EXPECT(mock->calls[108] == 0 && mock->calls[68] == 1 && xs::device_slot_hits(108) == 1); + EXPECT(mock->array[68][0] == static_cast(D3D12_TEXTURE_LAYOUT_UNKNOWN)); + EXPECT(mock->array[68][1] == static_cast( + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS)); + EXPECT(mock->array[68][2] == 0); + EXPECT(mock->array[68][3] == ((static_cast(D3D12_TEXTURE_LAYOUT_ROW_MAJOR) << 32) | + static_cast(D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))); + + D3D12_RESOURCE_DESC xbox_buf_desc = xbox_descs[1]; + xbox_buf_desc.Flags = static_cast(0x200000u); + D3D12_RESOURCE_ALLOCATION_INFO buf_ret{}; + EXPECT(raw(device, 108, word(&buf_ret), 1, 1, word(&xbox_buf_desc), 0) == word(&buf_ret)); + EXPECT(buf_ret.SizeInBytes == 0x40000 && mock->calls[68] == 2 && xs::device_slot_hits(108) == 2); + EXPECT(mock->array[68][0] == static_cast(D3D12_TEXTURE_LAYOUT_ROW_MAJOR)); + EXPECT(mock->array[68][1] == static_cast(D3D12_RESOURCE_FLAG_NONE)); + + D3D12_RESOURCE_DESC batch1025[1025]{}; + for (int i = 0; i < 1024; ++i) batch1025[i] = xbox_descs[0]; + batch1025[1024] = xbox_descs[1]; + D3D12_RESOURCE_ALLOCATION_INFO batch_ret{}; + EXPECT(call_slot108_c_abi(&batch_ret, device, 1, 1025, batch1025, nullptr) == &batch_ret); + EXPECT(batch_ret.SizeInBytes == 0x40000 && mock->calls[68] == 3 && xs::device_slot_hits(108) == 3); + EXPECT(mock->array[68][0] == static_cast(D3D12_TEXTURE_LAYOUT_UNKNOWN)); + EXPECT(mock->array[68][3] == ((static_cast(D3D12_TEXTURE_LAYOUT_ROW_MAJOR) << 32) | + static_cast(D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS))); EXPECT(release(allocator) == 0 && real_allocator->refs == 0); EXPECT(release(queue) == 0); EXPECT(release(device) == 0 && mock->refs == 0); std::printf("%s: device slots 48/73/78/79/80 route to a queue, a list and frame-event tokens without reaching " - "the mock's own PC slots\n", g_label); + "the mock's own PC slots; slot 41 creates argument type 105 as DISPATCH\n", g_label); + std::printf("%s: device slots 48/73/78/79/80 route to a queue, a list and frame-event tokens, and slot 61 to " + "CreateSampler, without reaching the mock's own PC slots\n", g_label); return 0; #else std::printf("%s: ID3D12Device11 is not in this SDK; Xbox slot 80's beyond-table case is not built\n", g_label); @@ -893,10 +1549,11 @@ int check_xbox_slots() { // ---- 8. Environment overrides for the Xbox device slots (one process each, read once) ---- -int run_env_slots(bool valid) { - const char* frame_interval = valid ? "96" : "2"; +// `moved_to` puts one route on a slot that has a built-in handler too: 70 (SetFrameIntervalX) or 74 (WaitFrameEventX). +int run_env_slots(bool valid, unsigned moved_to = 0) { + const char* frame_interval = moved_to == 70 ? "70" : valid ? "96" : "2"; const char* schedule_event = valid ? "97" : "2"; - const char* wait_event = valid ? "98" : "2"; + const char* wait_event = moved_to == 74 ? "74" : valid ? "98" : "2"; const char* queue_x = valid ? "99" : "2"; const char* list_x = valid ? "100" : "2"; EXPECT(SetEnvironmentVariableA("LEONIDA_XS_FRAME_INTERVAL_SLOT", frame_interval) != FALSE); @@ -910,13 +1567,23 @@ int run_env_slots(bool valid) { EXPECT(device); xs::reset_device_proxy_stats(); std::uint64_t token = 0; - if (valid) { + if (moved_to == 70) { + // SetFrameIntervalX moved onto 70, which also has a built-in handler: the override wins, so (output, interval, + // latency, flags) is a frame-interval call, never a shader-resource view whose handle is the latency. + EXPECT(hr_of(raw(device, 70, 0, 16667, 1, 0)) == S_OK && mock->calls[70] == 0 && mock->calls[18] == 0); + EXPECT(hr_of(raw(device, 78, 0, 16667, 1, 0)) == S_OK && mock->calls[78] == 1); // the old default is a PC slot now + } else if (moved_to == 74) { + // WaitFrameEventX moved onto 74, which also has a built-in handler: the override wins, so the call writes its + // wait token through the last pointer, which the stand-in never does, and reaches no PC slot. + std::uint64_t token_74 = 0; + EXPECT(hr_of(raw(device, 74, 0, 0, 0, 0, word(&token_74))) == S_OK && token_74 && mock->calls[74] == 0); + } else if (valid) { // Every route moved: the new slot is handled, the default slot is forwarded to the mock. EXPECT(hr_of(raw(device, 96, 0, 16667, 1, 0)) == S_OK && mock->calls[96] == 0); EXPECT(hr_of(raw(device, 97, 0, 0, 0, 0)) == S_OK && mock->calls[97] == 0); EXPECT(hr_of(raw(device, 98, 0, 0, 0, 0, word(&token))) == S_OK && token && mock->calls[98] == 0); void* queue = nullptr; - EXPECT(hr_of(raw(device, 99, word(&kQueueDesc), word(&kQueueIid), word(&queue))) == S_OK); + EXPECT(hr_of(raw(device, 99, word(kXboxQueueDesc), word(&kQueueIid), word(&queue))) == S_OK); EXPECT(xs::is_queue_proxy(queue) && mock->calls[99] == 0); const IID allocator_iid = __uuidof(ID3D12CommandAllocator); void* allocator = nullptr; @@ -937,7 +1604,7 @@ int run_env_slots(bool valid) { EXPECT(hr_of(raw(device, 78, 0, 16667, 1, 0)) == S_OK && mock->calls[78] == 0); EXPECT(hr_of(raw(device, 79, 0, 0, 0, 0)) == S_OK && mock->calls[79] == 0); EXPECT(hr_of(raw(device, 80, 0, 0, 0, 0, word(&token))) == S_OK && token && mock->calls[80] == 0); - EXPECT(hr_of(raw(device, 70)) == S_OK && mock->calls[70] == 1); // not an Xbox slot: forwarded + EXPECT(hr_of(raw(device, 71)) == S_OK && mock->calls[71] == 1); // not an Xbox slot: forwarded } EXPECT(release(device) == 0 && mock->refs == 0); std::printf("%s: environment slot overrides %s\n", g_label, @@ -945,6 +1612,529 @@ int run_env_slots(bool valid) { return 0; } +// ---- 9. Device slot 26, GetCustomHeapProperties, the console's way and the PC's ---- + +int check_custom_heap_properties() { + Mock* mock = nullptr; + void* device = make_device(mock, 0, true); + EXPECT(device && xs::device_slot_overridden(26)); + void* const* vtable = *reinterpret_cast(device); + + // The retail executable's call: the buffer for the struct in RCX, the device in RDX, node mask and heap type in + // R8 and R9 (their upper halves are not the callee's to read). The buffer sits inside a pattern that must stay. + struct Padded { + std::uint8_t before[16]; + D3D12_HEAP_PROPERTIES value; + std::uint8_t after[64]; + } padded; + std::memset(&padded, 0xA5, sizeof(padded)); + using ConsoleFn = std::uint64_t(WINAPI*)(void*, void*, std::uint64_t, std::uint64_t); + const std::uint64_t returned = reinterpret_cast(vtable[26])( + &padded.value, device, 0xdeadbeef00000001ull, 0xdeadbeef00000002ull); + EXPECT(returned == word(&padded.value)); + // The PC method got (buffer, node mask, heap type) once, on the device behind the proxy. + EXPECT(mock->calls[26] == 1); + EXPECT(static_cast(mock->args[26][1]) == 1 && static_cast(mock->args[26][2]) == 2); + EXPECT(padded.value.Type == D3D12_HEAP_TYPE_UPLOAD && padded.value.CreationNodeMask == 1 && + padded.value.VisibleNodeMask == kHeapMarker); + for (const std::uint8_t byte : padded.before) EXPECT(byte == 0xA5); + for (const std::uint8_t byte : padded.after) EXPECT(byte == 0xA5); + // The proxy is what it was: main's forwarder took the buffer for the proxy, and a thunk that took the proxy + // for the buffer would write the struct over it. + EXPECT(xs::is_device_proxy(device) && word(xs::device_proxy_real_device(device)) == word(mock) && + xs::device_proxy_slot_count(device) == 44 && xs::device_proxy_ref_count(device) == 1); + + // A PC C++ caller: the proxy in RCX and its buffer in RDX. That call is forwarded as it is. + D3D12_HEAP_PROPERTIES pc{}; + EXPECT(raw(device, 26, word(&pc), 1, 3) == word(&pc)); + EXPECT(mock->calls[26] == 2 && mock->args[26][0] == word(&pc)); + EXPECT(pc.Type == D3D12_HEAP_TYPE_READBACK && pc.CreationNodeMask == 1 && pc.VisibleNodeMask == kHeapMarker); + + EXPECT(release(device) == 0 && mock->refs == 0); + std::printf("%s: device slot 26 with the buffer in RCX and the device in RDX reaches the PC method and writes " + "only the struct; the PC form is forwarded unchanged\n", g_label); + return 0; +} + +// ---- 9b. Command lists (device slot 12): the console-shaped proxy and AllocateUploadMemory ---- + +int check_lists() { + const IID allocator_iid = __uuidof(ID3D12CommandAllocator); + const IID gcl_iid = __uuidof(ID3D12GraphicsCommandList); + Mock* mock = nullptr; + void* device = make_device(mock, 9, true, true, true); + EXPECT(device); + const unsigned long device_refs = xs::device_proxy_ref_count(device); + void* allocator = nullptr; + EXPECT(hr_of(raw(device, 9, 0, word(&allocator_iid), word(&allocator))) == S_OK); + Mock* const real_allocator = mock->last_child; + // CreateCommandList(node_mask, type, allocator, pso, iid, out): the allocator proxy is unwrapped on the way + // in and the list comes back console-shaped. + void* list = nullptr; + EXPECT(hr_of(raw(device, 12, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, word(allocator), 0, word(&gcl_iid), + word(&list))) == S_OK); + Mock* const real = mock->last_child; + EXPECT(real->kind == Kind::list && mock->args[12][2] == word(real_allocator)); + EXPECT(xs::is_list_proxy(list) && word(xs::list_proxy_real_list(list)) == word(real)); + EXPECT(xs::device_proxy_ref_count(device) == device_refs + 2); // allocator + list + // The console object body sits at +0x18 with the write cursor pinned at the record limits. + const auto* body = reinterpret_cast(word(list) + 0x18); + // Object offsets +0x18/+0x28/+0x30 are body[0]/body[2]/body[3]: the cursor is pinned at both record limits. + EXPECT(body[0] == body[2] && body[0] == body[3]); + // GetDevice answers with the Xbox-ABI device. + void* found = nullptr; + const IID device_iid = __uuidof(ID3D12Device); + EXPECT(hr_of(raw(list, 7, word(&device_iid), word(&found))) == S_OK && found == device); + EXPECT(release(found) >= 1); + // A forwarded console slot: Dispatch is console 14 (PC slot 14 too — order holds through 26). + EXPECT(hr_of(raw(list, 14, 1, 1, 1)) == S_OK && real->calls[14] == 1); + // Console slot 139 is the retail title's Reset(allocator, pso) (Pipodi measured it on 1.0.2.1): the allocator + // proxy unwraps and the call reaches the real list's PC slot 10. + EXPECT(hr_of(raw(list, 139, word(allocator), 0)) == S_OK && real->calls[10] == 1 && + real->args[10][0] == word(real_allocator)); + // Console-only extras (27-30) and the unmeasured tail are recorded and return 0, never forwarded. + EXPECT(raw(list, 27, 1, 2, 3, 4) == 0 && real->calls[27] == 0); + EXPECT(raw(list, 148, 0, 16) == 0); // AllocateUploadMemory(0, ...) refuses + // AllocateUploadMemory carves from the upload arena; a later root SRV gets a real address for it. + const std::uint64_t p1 = raw(list, 148, 4096, 64); + const std::uint64_t p2 = raw(list, 148, 16, 16); + EXPECT(p1 && p2 > p1 && (p1 & 63) == 0 && p2 >= p1 + 4096); + // A size that wraps the arena arithmetic is refused and moves nothing: UINT64_MAX used to return a + // pointer and corrupt the cursor so the next request re-handed the same range (daemosofchaos's + // report on #2490). A non-power-of-two alignment is unmeasured and refused rather than guessed. + EXPECT(raw(list, 148, ~0ull, 16) == 0); + EXPECT(raw(list, 148, 16, 48) == 0); + const std::uint64_t p3 = raw(list, 148, 16, 16); + EXPECT(p3 && p3 == p2 + 16); // fresh memory right after p2 — both refusals left the cursor alone + // Console 43 -> PC 39 (SetComputeRootShaderResourceView): the arena pointer crosses as a GPU VA (the mock + // device cannot map a real buffer, so the fallback arena translates to the same address). + EXPECT(hr_of(raw(list, 43, 0, p1)) == S_OK && real->calls[39] == 1 && real->args[39][1] == p1); + // The view-struct paths (IASetIndexBuffer console 47 -> PC 43, IASetVertexBuffers console 48 -> PC 44) reach + // the real list; the arena VAs inside the views are rewritten in the proxy's copies. + D3D12_INDEX_BUFFER_VIEW ib_view{}; + ib_view.BufferLocation = p1; + EXPECT(hr_of(raw(list, 47, word(&ib_view))) == S_OK && real->calls[43] == 1); + D3D12_VERTEX_BUFFER_VIEW vb_views[2]{}; + vb_views[0].BufferLocation = p1; + vb_views[1].BufferLocation = 0xDEAD0000; // a VA outside the arena passes through + EXPECT(hr_of(raw(list, 48, 0, 2, word(vb_views))) == S_OK && real->calls[44] == 1); + D3D12_STREAM_OUTPUT_BUFFER_VIEW so_view{}; + so_view.BufferLocation = p1; + so_view.BufferFilledSizeLocation = p2; + EXPECT(hr_of(raw(list, 49, 0, 1, word(&so_view))) == S_OK && real->calls[45] == 1); + // The console tail past the PC chain is refused with E_NOTIMPL only when the mapped PC slot is missing. + EXPECT(hr_of(raw(list, 146, word(list), 0)) == S_OK && real->calls[80] == 1); // enhanced Barrier -> GCL7 80 + EXPECT(release(list) == 0 && real->refs == 0); + EXPECT(release(allocator) == 0 && real_allocator->refs == 0); + EXPECT(xs::device_proxy_ref_count(device) == device_refs); + EXPECT(release(device) == 0 && mock->refs == 0); + + // A PC caller (console_lists=false — the default, what the GPU harnesses use) gets the real list back: + // slot 12 returns the mock, not a proxy, so its PC vtable indices stay valid. + Mock* pc_mock = new_mock(Kind::device); + pc_mock->device_level = 9; + pc_mock->refs = 1; + void* pc_device = nullptr; + EXPECT(SUCCEEDED(xs::create_device_proxy(reinterpret_cast(pc_mock), __uuidof(ID3D12Device), + &pc_device))); + void* pc_list = nullptr; + EXPECT(hr_of(raw(pc_device, 12, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, word(&gcl_iid), + word(&pc_list))) == S_OK); + EXPECT(pc_list && !xs::is_list_proxy(pc_list) && + reinterpret_cast(pc_list)->kind == Kind::command_list); + EXPECT(release(pc_list) == 0); + EXPECT(release(pc_device) == 0 && pc_mock->refs == 0); + std::printf("%s: lists come back console-shaped (cursor pinned, GetDevice, Dispatch forwarded, extras " + "recorded); AllocateUploadMemory hands out arena pointers a root SRV receives\n", g_label); + return 0; +} + +// ---- 10. SignalX layout detection ------------------------------------------------------------ +// A fence at queue slot 25 while the layout is still unknown is itself the newer-layout evidence: a title that +// signals only through SignalX never reaches Signal/Wait at 16/17, so an unanswered SignalX used to return +// S_OK having signalled nothing — a waiter on that fence value then hangs (shdann's report on #2490: the first +// SignalX gave hr=0 calls=0, the value was lost). + +int check_signalx_detection() { + Mock* mock = nullptr; + void* device = make_device(mock, 9, true); + EXPECT(device); + void* queue = make_queue(device); + void* fence = make_fence(device); + EXPECT(queue && fence); + Mock* const queue_mock = reinterpret_cast(xs::queue_proxy_real_queue(queue)); + const auto real_fence = word(xs::fence_proxy_real_fence(fence)); + // Undetected layout, fence at slot 25: forwarded as Signal and pins the device to the newer layout. + EXPECT(hr_of(raw(queue, 25, word(fence), 7)) == S_OK && queue_mock->calls[14] == 1 && + queue_mock->args[14][0] == real_fence && queue_mock->args[14][1] == 7); + // Now proven newer: Signal at 16 and SignalX at 25 keep forwarding. + EXPECT(hr_of(raw(queue, 16, word(fence), 8)) == S_OK && queue_mock->calls[14] == 2 && + queue_mock->args[14][1] == 8); + EXPECT(hr_of(raw(queue, 25, word(fence), 9)) == S_OK && queue_mock->calls[14] == 3 && + queue_mock->args[14][1] == 9); + // A second queue on the same device inherits the shared detection. + void* queue2 = make_queue(device); + EXPECT(queue2); + Mock* const queue2_mock = reinterpret_cast(xs::queue_proxy_real_queue(queue2)); + EXPECT(hr_of(raw(queue2, 25, word(fence), 11)) == S_OK && queue2_mock->calls[14] == 1 && + queue2_mock->args[14][1] == 11); + EXPECT(release(queue2) == 0); + EXPECT(release(queue) == 0 && release(fence) == 0 && release(device) == 0 && mock->refs == 0); + + // Proven older stays older: a non-fence at slot 16 pins the older layout (the frequency getter), and a + // fence at 25 afterwards is an unmodelled console method — S_OK with no forward, not a second detection. + Mock* mock2 = nullptr; + void* device2 = make_device(mock2, 9, true); + void* queue3 = make_queue(device2); + void* fence3 = make_fence(device2); + EXPECT(device2 && queue3 && fence3); + Mock* const queue3_mock = reinterpret_cast(xs::queue_proxy_real_queue(queue3)); + EXPECT(hr_of(raw(queue3, 16, 0, 0)) == S_OK && queue3_mock->calls[16] == 1 && + queue3_mock->calls[14] == 0); + EXPECT(hr_of(raw(queue3, 25, word(fence3), 13)) == S_OK && queue3_mock->calls[14] == 0); + // The older SignalX at slot 23 still forwards under the pinned-older layout. + EXPECT(hr_of(raw(queue3, 23, word(fence3), 15)) == S_OK && queue3_mock->calls[14] == 1 && + queue3_mock->args[14][1] == 15); + EXPECT(release(queue3) == 0 && release(fence3) == 0 && release(device2) == 0 && mock2->refs == 0); + + // A fence at the older SignalX slot while undetected forwards but does NOT pin: a newer title could reach + // an unmodelled slot-23 method with a fence argument, and a premature older pin would drop its real + // SignalX at 25. + Mock* mock3 = nullptr; + void* device3 = make_device(mock3, 9, true); + void* queue4 = make_queue(device3); + void* fence4 = make_fence(device3); + EXPECT(device3 && queue4 && fence4); + Mock* const queue4_mock = reinterpret_cast(xs::queue_proxy_real_queue(queue4)); + EXPECT(hr_of(raw(queue4, 23, word(fence4), 17)) == S_OK && queue4_mock->calls[14] == 1 && + queue4_mock->args[14][1] == 17); + EXPECT(hr_of(raw(queue4, 25, word(fence4), 19)) == S_OK && queue4_mock->calls[14] == 2 && + queue4_mock->args[14][1] == 19); + EXPECT(release(queue4) == 0 && release(fence4) == 0 && release(device3) == 0 && mock3->refs == 0); + + // Ambiguous slot 18 on an undetected queue: the older GetDesc or the newer frequency getter. It is + // served as the frequency query — a desc write is far wider than the 8 bytes a frequency caller + // passes (a title often reads the frequency before its first fence call); once a fence proves the + // layout the same call keeps reaching the getter through the shifted path. + Mock* mock4 = nullptr; + void* device4 = make_device(mock4, 9, true); + void* queue5 = make_queue(device4); + void* fence5 = make_fence(device4); + EXPECT(device4 && queue5 && fence5); + Mock* const queue5_mock = reinterpret_cast(xs::queue_proxy_real_queue(queue5)); + UINT64 hz = 0; + EXPECT(hr_of(raw(queue5, 18, word(&hz))) == S_OK && hz == 1000000 && + queue5_mock->calls[16] == 1 && queue5_mock->calls[18] == 0); + hz = 0; + EXPECT(hr_of(raw(queue5, 16, word(fence5), 8)) == S_OK); + EXPECT(hr_of(raw(queue5, 18, word(&hz))) == S_OK && hz == 1000000 && + queue5_mock->calls[16] == 2 && queue5_mock->calls[18] == 0); + EXPECT(release(queue5) == 0 && release(fence5) == 0 && release(device4) == 0 && mock4->refs == 0); + std::printf("xs_proxy_mock: SignalX on an undetected queue's slot 25 forwards as Signal and marks the " + "newer layout; proven-older stays older, a fence at 23 does not pin, and an undetected " + "slot 18 answers the frequency getter\n"); + return 0; +} + +// ---- 10b. Device slot 70: a view from raw words, never the PC CreatePlacedResource1 ---- + +// What the layer's resource provider knows: one buffer at [kBufferStart, kBufferStart + kBufferSize). +Mock* g_buffer = nullptr; +constexpr std::uint64_t kBufferStart = 0x10000, kBufferSize = 0x400; + +std::uint64_t g_asked_bytes = 0; // the byte count the proxy last asked the provider to cover + +ID3D12Resource* find_buffer(ID3D12Device*, std::uint64_t va, std::uint64_t bytes, std::uint64_t* start, + std::uint64_t* size) { + g_asked_bytes = bytes; + if (!g_buffer || va < kBufferStart || va >= kBufferStart + kBufferSize) return nullptr; + *start = kBufferStart; + *size = kBufferSize; + ++g_buffer->refs; // the provider hands out a reference; the proxy releases it + return reinterpret_cast(g_buffer); +} + +// The measured retail shape: a desktop buffer description, then a raw R32_TYPELESS view description with the VA right +// after it. +struct RawShape { + D3D12_RESOURCE_DESC resource; + struct { + D3D12_SHADER_RESOURCE_VIEW_DESC view; + D3D12_GPU_VIRTUAL_ADDRESS va; + } view; +}; + +RawShape raw_shape(std::uint64_t va, std::uint64_t width) { + RawShape shape{}; + shape.resource.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + shape.resource.Width = width; + shape.resource.Height = 1; + shape.resource.DepthOrArraySize = 1; + shape.resource.MipLevels = 1; + shape.resource.SampleDesc.Count = 1; + shape.resource.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + shape.view.view.Format = DXGI_FORMAT_R32_TYPELESS; + shape.view.view.ViewDimension = D3D12_SRV_DIMENSION_BUFFER; + shape.view.view.Shader4ComponentMapping = D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; + shape.view.view.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_RAW; + shape.view.va = va; + return shape; +} + +bool is_null_view(const Mock* mock) { + return mock->args[18][0] == 0 && mock->srv.ViewDimension == D3D12_SRV_DIMENSION_TEXTURE2D && + mock->srv.Format == DXGI_FORMAT_R8G8B8A8_UNORM && mock->srv.Texture2D.MipLevels == 1 && + mock->srv.Shader4ComponentMapping == D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING; +} + +int check_slot70() { + // Level 9 has the PC slot 70; level 0 does not (44 PC slots). Neither may reach CreatePlacedResource1. + for (const int level : {9, 0}) { + Mock* mock = nullptr; + void* device = make_device(mock, level, true); + EXPECT(device && xs::device_slot_overridden(70)); + xs::reset_device_proxy_stats(); + const std::uint32_t words[8] = {0x1000, 0, 0, 0, 0, 0, 0, 0}; + const std::uint32_t view[8] = {}; + const std::uint64_t destination = 0x7000; + raw(device, 70, word(words), word(view), destination); + EXPECT(mock->calls[70] == 0 && xs::device_slot_hits(70) == 1); + // Words that are not the measured shape: the destination gets the PC null view (CreateShaderResourceView, slot + // 18, no resource), the destination handle unchanged. + EXPECT(mock->calls[18] == 1 && mock->args[18][2] == destination && is_null_view(mock)); + // No destination, no write. + raw(device, 70, word(words), word(view), 0); + EXPECT(mock->calls[70] == 0 && mock->calls[18] == 1); + EXPECT(release(device) == 0 && mock->refs == 0); + } + return 0; +} + +// ---- 8b. Device slot 74: (pointer, u32, pointer) succeeds and touches nothing, never the PC ShaderCacheControl ---- + +int check_slot74() { + // Level 9 has the PC slot 74 (ShaderCacheControl); level 0 does not (44 PC slots). Neither may reach it. + for (const int level : {9, 0}) { + Mock* mock = nullptr; + void* device = make_device(mock, level, true); + EXPECT(device && xs::device_slot_overridden(74)); + xs::reset_device_proxy_stats(); + std::uint32_t first[4] = {0x11111111, 0x22222222, 0x33333333, 0x44444444}; + std::uint32_t second[4] = {0x55555555, 0x66666666, 0x77777777, 0x88888888}; + const std::uint32_t first_before[4] = {first[0], first[1], first[2], first[3]}; + const std::uint32_t second_before[4] = {second[0], second[1], second[2], second[3]}; + EXPECT(hr_of(raw(device, 74, word(first), 7, word(second))) == S_OK); + EXPECT(mock->calls[74] == 0 && xs::device_slot_hits(74) == 1); + EXPECT(std::memcmp(first, first_before, sizeof(first)) == 0 && std::memcmp(second, second_before, sizeof(second)) == 0); + EXPECT(release(device) == 0 && mock->refs == 0); + } + return 0; +} + +// A raw buffer view of a registered VA: the view is of that resource, from (va - start) / 4, as wide as the +// description says. Every other shape, and a VA no buffer holds, still gets the null view. +int check_slot70_raw_buffer() { + Mock* mock = nullptr; + void* device = make_device(mock, 9, true); + EXPECT(device); + g_buffer = new_mock(Kind::resource); + g_buffer->refs = 1; + EXPECT(xs::set_device_resource_provider(device, &find_buffer)); + const std::uint64_t destination = 0x7000; + + // 0x100 bytes at +0x40 of the buffer. + RawShape shape = raw_shape(kBufferStart + 0x40, 0x100); + raw(device, 70, word(&shape.resource), word(&shape.view), destination); + EXPECT(mock->calls[70] == 0 && mock->calls[18] == 1 && mock->args[18][0] == word(g_buffer) && + mock->args[18][2] == destination); + EXPECT(mock->srv.Format == DXGI_FORMAT_R32_TYPELESS && mock->srv.ViewDimension == D3D12_SRV_DIMENSION_BUFFER && + (mock->srv.Buffer.Flags & D3D12_BUFFER_SRV_FLAG_RAW) && mock->srv.Buffer.FirstElement == 0x10 && + mock->srv.Buffer.NumElements == 0x40 && mock->srv.Buffer.StructureByteStride == 0 && + mock->srv.Shader4ComponentMapping == D3D12_DEFAULT_SHADER_4_COMPONENT_MAPPING); + EXPECT(g_buffer->refs == 1); // the proxy released the reference the provider added + EXPECT(g_asked_bytes == 0x100); // it asks for a buffer that holds the whole width, so an alias that does wins + + // A width that runs past the buffer is cut at its end: (0x400 - 0x3f0) / 4 elements. + shape = raw_shape(kBufferStart + 0x3f0, 0x1000); + raw(device, 70, word(&shape.resource), word(&shape.view), destination); + EXPECT(mock->calls[18] == 2 && mock->args[18][0] == word(g_buffer) && mock->srv.Buffer.FirstElement == 0xfc && + mock->srv.Buffer.NumElements == 4); + + // A VA no buffer holds: the null view, and nothing is left referenced. + shape = raw_shape(kBufferStart + kBufferSize + 0x40, 0x100); + raw(device, 70, word(&shape.resource), word(&shape.view), destination); + EXPECT(mock->calls[18] == 3 && is_null_view(mock) && g_buffer->refs == 1); + + // A known VA but not a raw R32_TYPELESS buffer view (a typed view; a texture description): the null view. + shape = raw_shape(kBufferStart + 0x40, 0x100); + shape.view.view.Buffer.Flags = D3D12_BUFFER_SRV_FLAG_NONE; + raw(device, 70, word(&shape.resource), word(&shape.view), destination); + EXPECT(mock->calls[18] == 4 && is_null_view(mock)); + shape = raw_shape(kBufferStart + 0x40, 0x100); + shape.resource.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + raw(device, 70, word(&shape.resource), word(&shape.view), destination); + EXPECT(mock->calls[18] == 5 && is_null_view(mock) && g_buffer->refs == 1); + + // No provider: the null view as well. + EXPECT(xs::set_device_resource_provider(device, nullptr)); + shape = raw_shape(kBufferStart + 0x40, 0x100); + raw(device, 70, word(&shape.resource), word(&shape.view), destination); + EXPECT(mock->calls[18] == 6 && is_null_view(mock) && mock->calls[70] == 0); + + g_buffer = nullptr; + EXPECT(release(device) == 0 && mock->refs == 0); + return 0; +} + +// ---- 10c. Device slot 25, GetResourceAllocationInfo: a render target takes whole console tiles ---- + +D3D12_RESOURCE_DESC target_desc(std::uint64_t width, UINT height, DXGI_FORMAT format, UINT slices = 1) { + D3D12_RESOURCE_DESC d{}; + d.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + d.Width = width; + d.Height = height; + d.DepthOrArraySize = static_cast(slices); + d.MipLevels = 1; + d.Format = format; + d.SampleDesc.Count = 1; + d.Layout = static_cast(0x101); // the Xbox tiled layout word + d.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + return d; +} + +int check_render_target_sizes() { + Mock* mock = nullptr; + void* device = make_device(mock, 0, true); + EXPECT(device); + void* const* vtable = *reinterpret_cast(device); + // The retail executable's call: the buffer for the struct in RCX, the device in RDX. + using ConsoleFn = D3D12_RESOURCE_ALLOCATION_INFO*(WINAPI*)(D3D12_RESOURCE_ALLOCATION_INFO*, void*, UINT, UINT, + const D3D12_RESOURCE_DESC*); + const auto get_info = reinterpret_cast(vtable[25]); + auto ask = [&](const D3D12_RESOURCE_DESC* descs, UINT count) { + D3D12_RESOURCE_ALLOCATION_INFO info{0xDEAD, 0xBEEF}; + const bool same_buffer = get_info(&info, device, 0, count, descs) == &info; + if (!same_buffer) info.SizeInBytes = 0; + return info; + }; + + // A 1920 x 1080 RGBA8 target. A 4-byte element tile is 128 x 128 pixels: 15 tiles across, 9 down (1080 / 128 is + // 8.4), 135 x 64 KiB = 8,847,360 B. The PC device packs it as 8,294,400 B, 8,323,072 B rounded to 64 KiB. + const D3D12_RESOURCE_DESC hd = target_desc(1920, 1080, DXGI_FORMAT_R8G8B8A8_UNORM); + D3D12_RESOURCE_ALLOCATION_INFO info = ask(&hd, 1); + EXPECT(info.SizeInBytes == 8847360 && info.Alignment == 65536); + // A 3840 x 2160 RGBA16F target: an 8-byte element tile is 128 x 64, 30 across and 34 down (2160 / 64 is 33.75), + // 1020 tiles = 66,846,720 B, where the PC device says 66,387,968 B. + const D3D12_RESOURCE_DESC uhd = target_desc(3840, 2160, DXGI_FORMAT_R16G16B16A16_FLOAT); + EXPECT(ask(&uhd, 1).SizeInBytes == 66846720); + // Both in one call: the sum of the two console sizes. + const D3D12_RESOURCE_DESC both[] = {hd, uhd}; + EXPECT(ask(both, 2).SizeInBytes == 8847360 + 66846720); + // Two slices take two surfaces. + const D3D12_RESOURCE_DESC two = target_desc(1920, 1080, DXGI_FORMAT_R8G8B8A8_UNORM, 2); + EXPECT(ask(&two, 1).SizeInBytes == 2 * 8847360); + + // What is left alone: a texture that is not a render target, a buffer, a render target of a format the rule does + // not list, one the PC device refuses, and a surface that is already whole tiles (1024 x 1024 RGBA8). + D3D12_RESOURCE_DESC sampled = hd; + sampled.Flags = D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + EXPECT(ask(&sampled, 1).SizeInBytes == 8323072); + D3D12_RESOURCE_DESC buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = 100000; + buffer.Height = 1; + buffer.DepthOrArraySize = 1; + buffer.MipLevels = 1; + buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + buffer.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + EXPECT(ask(&buffer, 1).SizeInBytes == 131072); + D3D12_RESOURCE_DESC odd_format = hd; + odd_format.Format = DXGI_FORMAT_BC1_UNORM; + EXPECT(ask(&odd_format, 1).SizeInBytes == 8323072); + D3D12_RESOURCE_DESC empty = hd; + empty.Width = 0; + EXPECT(ask(&empty, 1).SizeInBytes == UINT64_MAX); + const D3D12_RESOURCE_DESC exact = target_desc(1024, 1024, DXGI_FORMAT_R8G8B8A8_UNORM); + EXPECT(ask(&exact, 1).SizeInBytes == 4194304); + // A refused description in a list refuses the list, as before. + const D3D12_RESOURCE_DESC refused[] = {hd, empty}; + EXPECT(ask(refused, 2).SizeInBytes == UINT64_MAX); + // A mip chain: 1920 x 1080 with 3 mips is mip 0 in 135 tiles, mip 1 (960 x 540) in 8 x 5 = 40 tiles and mip 2 + // (480 x 270) in 4 x 3 = 12 tiles. + D3D12_RESOURCE_DESC mips = hd; + mips.MipLevels = 3; + EXPECT(ask(&mips, 1).SizeInBytes == (135 + 40 + 12) * 65536ull); + + // The PC form (this in RCX, the buffer in RDX) answers the same sizes. + D3D12_RESOURCE_ALLOCATION_INFO pc{}; + EXPECT(raw(device, 25, word(&pc), 0, 1, word(&hd)) == word(&pc)); + EXPECT(pc.SizeInBytes == 8847360); + + EXPECT(release(device) == 0 && mock->refs == 0); + std::printf("%s: device slot 25 pads render targets to whole console tiles and leaves the other sizes as the PC " + "device gives them\n", g_label); + return 0; +} + +// ---- 10d. Device slot 25 hands the PC device clean descriptions and leaves the title's array alone ---- + +int check_allocation_descriptions_cleaned() { + constexpr std::uint32_t kXboxTiledLayout = 0x101, kXboxRowMajorLayout = 0x1, kXboxFlagBits = 0x40000 | 0x20000; + constexpr D3D12_RESOURCE_FLAGS kPcFlags = + D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS; + Mock* mock = nullptr; + void* device = make_device(mock, 0, true); + EXPECT(device); + void* const* vtable = *reinterpret_cast(device); + using ConsoleFn = D3D12_RESOURCE_ALLOCATION_INFO*(WINAPI*)(D3D12_RESOURCE_ALLOCATION_INFO*, void*, UINT, UINT, + const D3D12_RESOURCE_DESC*); + const auto get_info = reinterpret_cast(vtable[25]); + + // A texture with the Xbox tiled layout word and Xbox bits above the PC flags, and a buffer with the row-major word. + D3D12_RESOURCE_DESC titles[2] = {target_desc(1920, 1080, DXGI_FORMAT_R8G8B8A8_UNORM), {}}; + titles[0].Flags = static_cast(kPcFlags | kXboxFlagBits); + titles[0].Layout = static_cast(kXboxTiledLayout); + titles[1].Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + titles[1].Width = 100000; + titles[1].Height = 1; + titles[1].DepthOrArraySize = 1; + titles[1].MipLevels = 1; + titles[1].SampleDesc.Count = 1; + titles[1].Layout = static_cast(kXboxRowMajorLayout); + titles[1].Flags = static_cast(kXboxFlagBits); + D3D12_RESOURCE_DESC kept[2]; + std::memcpy(kept, titles, sizeof(kept)); + + D3D12_RESOURCE_ALLOCATION_INFO info{}; + g_seen_desc_count = 0; + g_seen_calls = 0; + std::memset(g_seen_descs, 0xCC, sizeof(g_seen_descs)); + EXPECT(get_info(&info, device, 0, 2, titles) == &info); + // The PC device saw both descriptions with PC flags and a PC layout, the rest of each as the title wrote it. + EXPECT(g_seen_desc_count == 2); + EXPECT(g_seen_descs[0].Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN && g_seen_descs[0].Flags == kPcFlags); + EXPECT(g_seen_descs[0].Width == 1920 && g_seen_descs[0].Height == 1080 && + g_seen_descs[0].Format == DXGI_FORMAT_R8G8B8A8_UNORM); + EXPECT(g_seen_descs[1].Layout == D3D12_TEXTURE_LAYOUT_ROW_MAJOR && g_seen_descs[1].Flags == D3D12_RESOURCE_FLAG_NONE); + EXPECT(g_seen_descs[1].Width == 100000); + // The title's array is as it was, and the size still follows the render-target flag it kept (the proxy's later + // per-target questions to the PC device are not recorded). + EXPECT(std::memcmp(kept, titles, sizeof(kept)) == 0); + EXPECT(info.SizeInBytes == 8847360 + 131072); + + // A null array with a zero count reaches the PC device as it came. + g_seen_desc_count = 99; + g_seen_calls = 0; + EXPECT(get_info(&info, device, 0, 0, nullptr) == &info && g_seen_calls == 1 && g_seen_desc_count == 0); + + EXPECT(release(device) == 0 && mock->refs == 0); + std::printf("%s: device slot 25 gives the PC device descriptions with PC flags and layout, and the title's own " + "array is not written\n", g_label); + return 0; +} + +// ---- 11. The console tail and the guard region ---- // ---- 9. The refused tail and the guard region ---- int check_tail(bool want_guarded) { @@ -959,14 +2149,360 @@ int check_tail(bool want_guarded) { // Signal (14) still reaches the real queue, with the real fence. EXPECT(hr_of(raw(queue, 14, word(fence), 5)) == S_OK && queue_mock->calls[14] == 1 && queue_mock->args[14][0] == word(xs::fence_proxy_real_fence(fence)) && queue_mock->args[14][1] == 5); + // Console-only queue methods (the tail past the PC chain, SignalX, PresentX) report S_OK instead of + // refusing: frame pacing flows through them. Nothing is forwarded — the real queue never sees them. for (unsigned slot = 19; slot < xs::queue_proxy_table_size(); ++slot) - EXPECT(hr_of(raw(queue, slot)) == E_NOTIMPL && queue_mock->calls[slot] == 0); - for (unsigned slot = 12; slot < xs::fence_proxy_table_size(); ++slot) EXPECT(hr_of(raw(fence, slot)) == E_NOTIMPL); + EXPECT(hr_of(raw(queue, slot)) == S_OK && queue_mock->calls[slot] == 0); + EXPECT(raw(fence, 12) != 0); // the completed value's address (check_fence_completed_value) + for (unsigned slot = 13; slot < xs::fence_proxy_table_size(); ++slot) EXPECT(hr_of(raw(fence, slot)) == E_NOTIMPL); EXPECT(xs::queue_table_overruns() == 0 && xs::fence_table_overruns() == 0); EXPECT(release(queue) == 0 && release(fence) == 0 && release(device) == 0 && mock->refs == 0); return 0; } +struct HeapHookState { + void* next_ptr = nullptr; + std::size_t last_alloc_size = 0; + std::uint64_t last_alloc_attr = 0; + int alloc_calls = 0; + void* last_free_ptr = nullptr; + std::uint64_t last_free_attr = 0; + int free_calls = 0; +} g_heap_hook; + +void* mock_heap_alloc(std::size_t byte_size, std::uint64_t attributes) { + ++g_heap_hook.alloc_calls; + g_heap_hook.last_alloc_size = byte_size; + g_heap_hook.last_alloc_attr = attributes; + return g_heap_hook.next_ptr; +} + +void mock_heap_free(void* ptr, std::uint64_t attributes) { + ++g_heap_hook.free_calls; + g_heap_hook.last_free_ptr = ptr; + g_heap_hook.last_free_attr = attributes; +} + +int check_descriptor_heap_hooks() { + g_heap_hook = {}; + xs::set_descriptor_heap_allocator(&mock_heap_alloc, &mock_heap_free); + + Mock* real = new_mock(Kind::device); + real->refs = 1; + real->device_level = 9; + void* device = nullptr; + EXPECT(SUCCEEDED(xs::create_device_proxy(reinterpret_cast(real), __uuidof(ID3D12Device), &device))); + + constexpr SIZE_T kCustomBase = 0x77770000ull; + g_heap_hook.next_ptr = reinterpret_cast(kCustomBase); + D3D12_DESCRIPTOR_HEAP_DESC desc{}; + desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + desc.NumDescriptors = 8; + desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; + const IID iid_heap = __uuidof(ID3D12DescriptorHeap); + void* heap = nullptr; + EXPECT(SUCCEEDED(hr_of(raw(device, 14, word(&desc), word(&iid_heap), word(&heap))))); + EXPECT(heap != nullptr && xs::is_heap_proxy(heap)); + EXPECT(g_heap_hook.alloc_calls == 1); + EXPECT(g_heap_hook.last_alloc_size == desc.NumDescriptors * kMockDescriptorInc); + EXPECT(g_heap_hook.last_alloc_attr == xs::kXmemDescriptorHeapAttributes); + + // Slot 9 returns the title-supplied base; slot 10 keeps the real GPU start so (gpu - cpu) delta stays exact. + EXPECT(raw(heap, 9) == kCustomBase); + EXPECT(raw(heap, 10) == kMockHeapGpuStart); + + // Public translator and device slots 17-24 remap handles in [kCustomBase, +256) to kMockHeapCpuStart + offset. + const SIZE_T off3 = 3 * kMockDescriptorInc; + const SIZE_T off7 = 7 * kMockDescriptorInc; + const SIZE_T outside = kCustomBase + desc.NumDescriptors * kMockDescriptorInc; + EXPECT(xs::translate_cpu_descriptor_handle(device, D3D12_CPU_DESCRIPTOR_HANDLE{kCustomBase + off3}).ptr == + kMockHeapCpuStart + off3); + EXPECT(xs::translate_cpu_descriptor_handle(device, D3D12_CPU_DESCRIPTOR_HANDLE{outside}).ptr == outside); + + raw(device, 17, 0x11, kCustomBase + off3); // CreateConstantBufferView + EXPECT(real->args[17][1] == kMockHeapCpuStart + off3); + raw(device, 18, 0x22, 0x33, kCustomBase + off3); // CreateShaderResourceView + EXPECT(real->args[18][2] == kMockHeapCpuStart + off3); + raw(device, 19, 0x22, 0x33, 0x44, kCustomBase + off7); // CreateUnorderedAccessView + EXPECT(real->args[19][3] == kMockHeapCpuStart + off7); + raw(device, 20, 0x22, 0x33, kCustomBase + off3); // CreateRenderTargetView + EXPECT(real->args[20][2] == kMockHeapCpuStart + off3); + raw(device, 21, 0x22, 0x33, kCustomBase + off7); // CreateDepthStencilView + EXPECT(real->args[21][2] == kMockHeapCpuStart + off7); + raw(device, 22, 0x55, kCustomBase + off3); // CreateSampler + EXPECT(real->args[22][1] == kMockHeapCpuStart + off3); + raw(device, 24, 1, kCustomBase + off7, kCustomBase + off3, 0); // CopyDescriptorsSimple + EXPECT(real->args[24][1] == kMockHeapCpuStart + off7); + EXPECT(real->args[24][2] == kMockHeapCpuStart + off3); + { + D3D12_CPU_DESCRIPTOR_HANDLE dsts[2] = {{kCustomBase + off3}, {outside}}; + D3D12_CPU_DESCRIPTOR_HANDLE srcs[2] = {{kCustomBase + off7}, {0x99990000ull}}; + UINT sizes[2] = {1, 1}; + static_cast(device)->CopyDescriptors(2, dsts, sizes, 2, srcs, sizes, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + EXPECT(real->array[23][0] == kMockHeapCpuStart + off3 && real->array[23][1] == outside); + EXPECT(real->array[24][0] == kMockHeapCpuStart + off7 && real->array[24][1] == 0x99990000ull); + } + + // Releasing the heap unregisters the range and invokes the free callback with the same attribute word. + EXPECT(raw(heap, 2) == 0); + EXPECT(g_heap_hook.free_calls == 1); + EXPECT(g_heap_hook.last_free_ptr == reinterpret_cast(kCustomBase)); + EXPECT(g_heap_hook.last_free_attr == xs::kXmemDescriptorHeapAttributes); + EXPECT(xs::translate_cpu_descriptor_handle(device, D3D12_CPU_DESCRIPTOR_HANDLE{kCustomBase + off3}).ptr == + kCustomBase + off3); + + // Null return from the hook falls back cleanly to the PC heap's start and never calls free. + g_heap_hook.next_ptr = nullptr; + void* plain_heap = nullptr; + EXPECT(SUCCEEDED(hr_of(raw(device, 14, word(&desc), word(&iid_heap), word(&plain_heap))))); + EXPECT(plain_heap != nullptr && raw(plain_heap, 9) == kMockHeapCpuStart); + EXPECT(raw(plain_heap, 2) == 0); + EXPECT(g_heap_hook.free_calls == 1); + + // QI failure on heap proxy creation (unsupported IID) frees the hook backing immediately. + g_heap_hook.next_ptr = reinterpret_cast(kCustomBase); + void* bad_heap = nullptr; + EXPECT(hr_of(raw(device, 14, word(&desc), word(&kExtraIid), word(&bad_heap))) == E_NOINTERFACE); + EXPECT(bad_heap == nullptr && g_heap_hook.free_calls == 2); + EXPECT(g_heap_hook.last_free_ptr == reinterpret_cast(kCustomBase)); + + // OOM on HeapProxy allocation frees the hook backing and leaves no dangling range. + g_fail_news = 1; + void* oom_heap = nullptr; + EXPECT(hr_of(raw(device, 14, word(&desc), word(&iid_heap), word(&oom_heap))) == E_OUTOFMEMORY); + EXPECT(oom_heap == nullptr && g_heap_hook.free_calls == 3); + EXPECT(xs::translate_cpu_descriptor_handle(device, D3D12_CPU_DESCRIPTOR_HANDLE{kCustomBase}).ptr == kCustomBase); + + EXPECT(raw(device, 2) == 0 && real->refs == 0); + xs::set_descriptor_heap_allocator(nullptr, nullptr); + return 0; +} + +// ---- Committed resources lease their size through the title's XMem hooks (RT-5 stop 17) ---- +// Slots 76 and 127 allocate the slot-25 size of the resource through the installed hooks with page-size field 2, the +// resource holds the lease, and the hooks' free runs once, when the resource is destroyed. +int check_committed_resource_leases() { + g_heap_hook = {}; + xs::set_descriptor_heap_allocator(&mock_heap_alloc, &mock_heap_free); + Mock* mock = nullptr; + void* device = make_device(mock, 10, true); + EXPECT(device); + constexpr std::uint64_t kLeaseAttributes = (0x80ULL << 16) | (2ULL << 14); + static std::uint8_t lease_memory[64]; + g_heap_hook.next_ptr = lease_memory; + + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = D3D12_HEAP_TYPE_DEFAULT; + D3D12_RESOURCE_DESC desc{}; + desc.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + desc.Width = 1920; + desc.Height = 1080; + desc.DepthOrArraySize = 1; + desc.MipLevels = 1; + desc.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + desc.SampleDesc.Count = 1; + desc.Flags = D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET; + + // Slot 76: the lease is the console tile size (135 tiles), not the PC one. + void* resource = nullptr; + std::uint64_t words76[10] = {word(&heap), 0, word(&desc), 0, 0, word(&kResourceIid), word(&resource), 0, 0, 0}; + EXPECT(hr_of(raw10(device, 76, words76)) == S_OK && resource); + EXPECT(g_heap_hook.alloc_calls == 1 && g_heap_hook.last_alloc_size == 8847360); + EXPECT(g_heap_hook.last_alloc_attr == kLeaseAttributes); + EXPECT(g_heap_hook.free_calls == 0 && reinterpret_cast(resource)->held); + EXPECT(release(resource) == 0); + EXPECT(g_heap_hook.free_calls == 1 && g_heap_hook.last_free_ptr == lease_memory && + g_heap_hook.last_free_attr == kLeaseAttributes); + +#ifdef __ID3D12Device10_INTERFACE_DEFINED__ + // Slot 127, a buffer: its PC size, leased the same way. + D3D12_RESOURCE_DESC1 buffer{}; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Width = 3 * 65536; + buffer.Height = 1; + buffer.DepthOrArraySize = 1; + buffer.MipLevels = 1; + buffer.SampleDesc.Count = 1; + buffer.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + resource = nullptr; + std::uint64_t words127[10] = {word(&heap), 0, word(&buffer), 0xFFFFFFFFu, 0, 0, 0, 0, word(&kResourceIid), + word(&resource)}; + EXPECT(hr_of(raw10(device, 127, words127)) == S_OK && resource); + EXPECT(g_heap_hook.alloc_calls == 2 && g_heap_hook.last_alloc_size == 3 * 65536); + EXPECT(release(resource) == 0 && g_heap_hook.free_calls == 2); +#endif + + // A driver whose PC answer is above the console tiles (AMD's Windows driver: 513 x 64 KiB for a 3840 x 2160 RGBA8 + // target, 510 tiles on the console) still leases the tiles: the title's 64 MiB range holds two of those and no more. + desc.Width = 3840; + desc.Height = 2160; + g_texture_size_bias = 6 * 65536; // the mock's 507 x 64 KiB becomes 513 x 64 KiB + resource = nullptr; + EXPECT(hr_of(raw10(device, 76, words76)) == S_OK && resource); + EXPECT(g_heap_hook.last_alloc_size == 30ull * 17 * 65536); + EXPECT(release(resource) == 0); + g_texture_size_bias = 0; + desc.Width = 1920; + desc.Height = 1080; + + // Hooks that return null: the resource is still created, and nothing is freed later. + g_heap_hook.next_ptr = nullptr; + resource = nullptr; + EXPECT(hr_of(raw10(device, 76, words76)) == S_OK && resource && !reinterpret_cast(resource)->held); + const unsigned frees = g_heap_hook.free_calls; + EXPECT(release(resource) == 0 && g_heap_hook.free_calls == frees); + + // No hooks: no lease. + xs::set_descriptor_heap_allocator(nullptr, nullptr); + const unsigned allocs = g_heap_hook.alloc_calls; + resource = nullptr; + EXPECT(hr_of(raw10(device, 76, words76)) == S_OK && resource && g_heap_hook.alloc_calls == allocs); + EXPECT(release(resource) == 0); + EXPECT(release(device) == 0 && mock->refs == 0); + std::printf("%s: committed resources lease their slot-25 size through the title's XMem hooks until destroyed\n", + g_label); + return 0; +} + +int check_list_cpu_handles() { + g_heap_hook = {}; + xs::set_descriptor_heap_allocator(&mock_heap_alloc, &mock_heap_free); + + Mock* real = nullptr; + void* device = make_device(real, 9, true, true, true); + EXPECT(device != nullptr); + + constexpr SIZE_T kCustomBase = 0x77880000ull; + g_heap_hook.next_ptr = reinterpret_cast(kCustomBase); + D3D12_DESCRIPTOR_HEAP_DESC desc{}; + desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_RTV; + desc.NumDescriptors = 8; + const IID iid_heap = __uuidof(ID3D12DescriptorHeap); + void* heap = nullptr; + EXPECT(SUCCEEDED(hr_of(raw(device, 14, word(&desc), word(&iid_heap), word(&heap))))); + EXPECT(heap != nullptr && raw(heap, 9) == kCustomBase); + + const IID iid_alloc = __uuidof(ID3D12CommandAllocator); + const IID iid_gcl = __uuidof(ID3D12GraphicsCommandList); + void* allocator = nullptr; + EXPECT(SUCCEEDED(hr_of(raw(device, 9, D3D12_COMMAND_LIST_TYPE_DIRECT, word(&iid_alloc), word(&allocator))))); + void* list = nullptr; + EXPECT(SUCCEEDED(hr_of(raw(device, 12, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, word(allocator), 0, + word(&iid_gcl), word(&list))))); + EXPECT(list != nullptr && xs::is_list_proxy(list)); + Mock* const real_list = reinterpret_cast(xs::list_proxy_real_list(list)); + EXPECT(real_list != nullptr); + + const SIZE_T off1 = 1 * kMockDescriptorInc; + const SIZE_T off4 = 4 * kMockDescriptorInc; + const SIZE_T off6 = 6 * kMockDescriptorInc; + const SIZE_T outside = kCustomBase + desc.NumDescriptors * kMockDescriptorInc; + + // Console slot 50 -> PC slot 46 (OMSetRenderTargets): multiple RTV handles + DSV handle, caller arrays untouched. + { + D3D12_CPU_DESCRIPTOR_HANDLE rtvs[2] = {{kCustomBase + off1}, {outside}}; + D3D12_CPU_DESCRIPTOR_HANDLE dsv{kCustomBase + off6}; + raw(list, 50, 2, word(rtvs), FALSE, word(&dsv)); + EXPECT(real_list->calls[46] == 1); + EXPECT(real_list->om_rtv_count == 2 && real_list->om_single_range == FALSE); + EXPECT(real_list->om_rtvs[0] == kMockHeapCpuStart + off1 && real_list->om_rtvs[1] == outside); + EXPECT(real_list->om_has_dsv && real_list->om_dsv == kMockHeapCpuStart + off6); + EXPECT(rtvs[0].ptr == kCustomBase + off1 && rtvs[1].ptr == outside && dsv.ptr == kCustomBase + off6); + } + // Single descriptor range: only rtvs[0] is read and translated even when NumRenderTargetDescriptors > 1; null DSV. + { + D3D12_CPU_DESCRIPTOR_HANDLE single_rtv{kCustomBase + off4}; + raw(list, 50, 3, word(&single_rtv), TRUE, 0); + EXPECT(real_list->calls[46] == 2); + EXPECT(real_list->om_rtv_count == 3 && real_list->om_single_range == TRUE); + EXPECT(real_list->om_rtvs[0] == kMockHeapCpuStart + off4 && !real_list->om_has_dsv); + EXPECT(single_rtv.ptr == kCustomBase + off4); + } + // Zero RTVs with a non-null DSV. + { + D3D12_CPU_DESCRIPTOR_HANDLE dsv{kCustomBase + off1}; + raw(list, 50, 0, 0, FALSE, word(&dsv)); + EXPECT(real_list->calls[46] == 3); + EXPECT(real_list->om_rtv_count == 0 && real_list->om_has_dsv && real_list->om_dsv == kMockHeapCpuStart + off1); + } + // Count beyond D3D12_SIMULTANEOUS_RENDER_TARGET_COUNT (8): forwards safely without overrunning stack scratch. + { + D3D12_CPU_DESCRIPTOR_HANDLE nine[9]{}; + for (UINT i = 0; i < 9; ++i) nine[i].ptr = outside + i * kMockDescriptorInc; + raw(list, 50, 9, word(nine), FALSE, 0); + EXPECT(real_list->calls[46] == 4 && real_list->om_rtv_count == 9); + } + + // Console slot 51 -> PC slot 47 (ClearDepthStencilView): CPU handle translated AND FLOAT Depth in XMM3 preserved. + { + using ClearDsvFn = void(WINAPI*)(void*, D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_CLEAR_FLAGS, FLOAT, UINT8, UINT, + const D3D12_RECT*); + void* const* list_vtbl = *reinterpret_cast(list); + auto clear_dsv = reinterpret_cast(list_vtbl[51]); + const D3D12_RECT rect{1, 2, 3, 4}; + clear_dsv(list, D3D12_CPU_DESCRIPTOR_HANDLE{kCustomBase + off6}, + D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL, 0.375f, 0x5Au, 1, &rect); + EXPECT(real_list->calls[47] == 1); + EXPECT(real_list->clear_dsv_handle == kMockHeapCpuStart + off6); + EXPECT(real_list->clear_dsv_flags == (D3D12_CLEAR_FLAG_DEPTH | D3D12_CLEAR_FLAG_STENCIL)); + EXPECT(real_list->clear_dsv_depth == 0.375f); + EXPECT(real_list->clear_dsv_stencil == 0x5Au); + EXPECT(real_list->clear_dsv_num_rects == 1 && real_list->clear_dsv_rects == &rect); + + // Second call (past first-call log): outside-range handle passes through and a different depth float holds. + clear_dsv(list, D3D12_CPU_DESCRIPTOR_HANDLE{outside}, D3D12_CLEAR_FLAG_DEPTH, 0.625f, 0u, 0, nullptr); + EXPECT(real_list->calls[47] == 2); + EXPECT(real_list->clear_dsv_handle == outside); + EXPECT(real_list->clear_dsv_depth == 0.625f); + EXPECT(real_list->clear_dsv_num_rects == 0 && real_list->clear_dsv_rects == nullptr); + } + + // Console slot 52 -> PC slot 48 (ClearRenderTargetView): CPU handle translated, color and rects forwarded. + { + const FLOAT color[4] = {0.25f, 0.5f, 0.75f, 1.0f}; + const D3D12_RECT rect{0, 0, 8, 8}; + raw(list, 52, kCustomBase + off1, word(color), 1, word(&rect)); + EXPECT(real_list->calls[48] == 1); + EXPECT(real_list->args[48][0] == kMockHeapCpuStart + off1); + EXPECT(real_list->args[48][1] == word(color) && real_list->args[48][2] == 1 && + real_list->args[48][3] == word(&rect)); + + raw(list, 52, outside, word(color), 0, 0); + EXPECT(real_list->calls[48] == 2 && real_list->args[48][0] == outside); + } + + // Console slots 53/54 -> PC slots 49/50 (ClearUnorderedAccessViewUint/Float): GPU handle kept, CPU handle remapped. + { + const UINT uvals[4] = {1, 2, 3, 4}; + const FLOAT fvals[4] = {1.0f, 0.5f, 0.25f, 0.0f}; + const D3D12_RECT rect{2, 2, 6, 6}; + raw(list, 53, kMockHeapGpuStart + off1, kCustomBase + off4, 0x3333ull, word(uvals), 1, word(&rect)); + EXPECT(real_list->calls[49] == 1); + EXPECT(real_list->args[49][0] == kMockHeapGpuStart + off1); + EXPECT(real_list->args[49][1] == kMockHeapCpuStart + off4); + EXPECT(real_list->args[49][2] == 0x3333ull && real_list->args[49][3] == word(uvals) && + real_list->args[49][4] == 1 && real_list->args[49][5] == word(&rect)); + + raw(list, 54, kMockHeapGpuStart + off6, kCustomBase + off6, 0x4444ull, word(fvals), 0, 0); + EXPECT(real_list->calls[50] == 1); + EXPECT(real_list->args[50][0] == kMockHeapGpuStart + off6); + EXPECT(real_list->args[50][1] == kMockHeapCpuStart + off6); + EXPECT(real_list->args[50][2] == 0x4444ull && real_list->args[50][3] == word(fvals) && + real_list->args[50][4] == 0 && real_list->args[50][5] == 0); + + raw(list, 54, kMockHeapGpuStart, outside, 0x4444ull, word(fvals), 0, 0); + EXPECT(real_list->calls[50] == 2 && real_list->args[50][1] == outside); + } + + EXPECT(raw(list, 2) == 0); + EXPECT(raw(allocator, 2) == 0); + EXPECT(raw(heap, 2) == 0); + EXPECT(raw(device, 2) == 0 && real->refs == 0); + xs::set_descriptor_heap_allocator(nullptr, nullptr); + return 0; +} + // ---- Guard-region setup failures: this executable's import table, patched before the first proxy table ---- std::atomic g_injected{0}; @@ -1040,13 +2576,176 @@ int run_fault_mode(const char* mode) { g_armed = false; if (failed) return 1; EXPECT(g_injected.load() > 0); // the proxy's own call was the one refused - std::printf("%s: %s refused %d time(s): the tables %s guarded, the proxies forward and refuse their tail as " - "before\n", m.flag, m.function, g_injected.load(), m.guarded ? "stay" : "are not"); + std::printf("%s: %s refused %d time(s): the tables %s guarded, the proxies forward and answer their " + "console tail as before\n", m.flag, m.function, g_injected.load(), + m.guarded ? "stay" : "are not"); return 0; } return 2; } +// ---- 12. List tail slot names (D3D-445) --------------------------------------------------------------------- +// From CopyTextureRegionX on, the newer layout sits two slots later than the older one (d3d12_xs_console_abi.md +// 5.3). A diagnostic name follows the device-wide layout, so slot 85 of the newer layout and slot 83 of the older +// layout are both CopyTextureRegionX, and neither number gets that name under the other layout. + +int check_list_tail_names() { + const unsigned char older = xs::kConsoleLayoutOlder, newer = xs::kConsoleLayoutNewer; + const auto same = [](const char* a, const char* b) { return a && b && std::strcmp(a, b) == 0; }; + EXPECT(same(xs::list_tail_slot_name(83, older), "CopyTextureRegionX")); + EXPECT(same(xs::list_tail_slot_name(85, newer), "CopyTextureRegionX")); + // The same numbers under the other layout are different methods. + EXPECT(!xs::list_tail_slot_name(83, newer)); // not a measured slot of the newer layout + EXPECT(xs::list_tail_slot_name(85, older) && !same(xs::list_tail_slot_name(85, older), "CopyTextureRegionX")); + // Every measured newer->older pair has one name, and the eight names differ. + const unsigned pairs[][2] = {{85, 83}, {86, 84}, {87, 85}, {90, 88}, {91, 89}, {92, 90}, {95, 93}, {96, 94}}; + for (const auto& pair : pairs) { + EXPECT(same(xs::list_tail_slot_name(pair[0], newer), xs::list_tail_slot_name(pair[1], older))); + for (const auto& other : pairs) + EXPECT(pair[1] == other[1] || + !same(xs::list_tail_slot_name(pair[1], older), xs::list_tail_slot_name(other[1], older))); + } + // Slots outside the measured set have no tail name in either layout, and no slot has one before the layout is + // known: the log then prints the slot number only, as before. + for (unsigned slot = 0; slot < 160; ++slot) { + bool older_tail = false, newer_tail = false; + for (const auto& pair : pairs) { + newer_tail = newer_tail || slot == pair[0]; + older_tail = older_tail || slot == pair[1]; + } + EXPECT((xs::list_tail_slot_name(slot, older) != nullptr) == older_tail); + EXPECT((xs::list_tail_slot_name(slot, newer) != nullptr) == newer_tail); + EXPECT(!xs::list_tail_slot_name(slot, 0)); + EXPECT(!xs::list_tail_slot_name(slot, 3)); + } + return 0; +} + +// Device slot 127 is ID3D12Device10::CreateCommittedResource3 with Xbox descriptors (RT-5 stop 15). Past the PC +// vtable it used to be refused with E_NOTIMPL; the PC device must now get the resource with the Xbox layout word and +// flag bits gone and every other word as the title passed it. +int check_committed_resource3_x() { +#ifdef __ID3D12Device10_INTERFACE_DEFINED__ + constexpr std::uint32_t kXboxLayoutTiled = 0x101, kXboxFlagBit = 0x40000, kBarrierLayoutUndefined = 0xFFFFFFFFu; + constexpr std::uint32_t kTightAlignment = 0x400, // D3D12_RESOURCE_FLAG_USE_TIGHT_ALIGNMENT, a PC bit + kHeapNotZeroed = 0x1000; // D3D12_HEAP_FLAG_CREATE_NOT_ZEROED + static const int session_sentinel = 0; + D3D12_HEAP_PROPERTIES heap{}; + heap.Type = D3D12_HEAP_TYPE_DEFAULT; + D3D12_CLEAR_VALUE clear{}; + clear.Format = DXGI_FORMAT_R8G8B8A8_UNORM; + const DXGI_FORMAT castable[2] = {DXGI_FORMAT_R8G8B8A8_UNORM, DXGI_FORMAT_R8G8B8A8_UNORM_SRGB}; + D3D12_RESOURCE_DESC1 texture{}; + texture.Dimension = D3D12_RESOURCE_DIMENSION_TEXTURE2D; + texture.Width = 1920; + texture.Height = 1080; + texture.DepthOrArraySize = 1; + texture.MipLevels = 1; + texture.Format = DXGI_FORMAT_R8G8B8A8_TYPELESS; + texture.SampleDesc.Count = 1; + texture.Layout = static_cast(kXboxLayoutTiled); + texture.Flags = static_cast(D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | + D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | kXboxFlagBit | kTightAlignment); + + // A PC device with ID3D12Device10: the render target comes back, as the console's call returns it. + Mock* mock = nullptr; + void* device = make_device(mock, 10, true); + EXPECT(device && xs::device_proxy_slot_count(device) == 79); + xs::reset_device_proxy_stats(); + g_committed3 = {}; + void* resource = nullptr; + std::uint64_t words[10] = {word(&heap), kHeapNotZeroed, word(&texture), kBarrierLayoutUndefined, + word(&clear), word(&session_sentinel), 2, word(castable), word(&kResourceIid), word(&resource)}; + EXPECT(hr_of(raw10(device, 127, words)) == S_OK); + EXPECT(resource && reinterpret_cast(resource)->kind == Kind::resource); + EXPECT(g_committed3.calls == 1 && xs::device_slot_hits(127) == 1); + EXPECT(g_committed3.heap == &heap && g_committed3.clear == &clear); + EXPECT(g_committed3.heap_flags == static_cast(kHeapNotZeroed)); // the title's heap flags + EXPECT(g_committed3.session == &session_sentinel); // and protected session + EXPECT(g_committed3.layout == kBarrierLayoutUndefined); + EXPECT(g_committed3.castable_count == 2 && g_committed3.castable_formats == castable); + EXPECT(g_committed3.riid == &kResourceIid); + EXPECT(g_committed3.desc.Layout == D3D12_TEXTURE_LAYOUT_UNKNOWN); + // The Xbox-only bit goes; every PC bit stays, tight alignment included. + EXPECT(static_cast(g_committed3.desc.Flags) == + (D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET | D3D12_RESOURCE_FLAG_ALLOW_UNORDERED_ACCESS | kTightAlignment)); + EXPECT(g_committed3.desc.Width == 1920 && g_committed3.desc.Height == 1080 && + g_committed3.desc.Format == DXGI_FORMAT_R8G8B8A8_TYPELESS && g_committed3.desc.SampleDesc.Count == 1); + EXPECT(texture.Layout == static_cast(kXboxLayoutTiled)); // the title's description is read only + EXPECT(release(resource) == 0); // the title's one reference is the only one: nothing leaked, nothing extra + + // A buffer takes the row-major layout. + D3D12_RESOURCE_DESC1 buffer = texture; + buffer.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + buffer.Height = 1; + buffer.Format = DXGI_FORMAT_UNKNOWN; + words[2] = word(&buffer); + words[6] = 0; + words[7] = 0; + resource = nullptr; + EXPECT(hr_of(raw10(device, 127, words)) == S_OK && resource); + EXPECT(g_committed3.calls == 2 && g_committed3.desc.Layout == D3D12_TEXTURE_LAYOUT_ROW_MAJOR); + EXPECT(release(resource) == 0); + + // The PC device's own refusal reaches the title with a null object. + mock->create_result = E_OUTOFMEMORY; + resource = reinterpret_cast(1); + words[9] = word(&resource); + EXPECT(hr_of(raw10(device, 127, words)) == E_OUTOFMEMORY && !resource); + mock->create_result = S_OK; + + // A null heap, description, IID or output is refused before the PC device is called. + const unsigned before = g_committed3.calls; + std::uint64_t bad[10]; + std::memcpy(bad, words, sizeof(bad)); + bad[0] = 0; + EXPECT(hr_of(raw10(device, 127, bad)) == E_POINTER); + std::memcpy(bad, words, sizeof(bad)); + bad[2] = 0; + EXPECT(hr_of(raw10(device, 127, bad)) == E_POINTER); + std::memcpy(bad, words, sizeof(bad)); + bad[8] = 0; + EXPECT(hr_of(raw10(device, 127, bad)) == E_POINTER); + std::memcpy(bad, words, sizeof(bad)); + bad[9] = 0; + EXPECT(hr_of(raw10(device, 127, bad)) == E_POINTER); + EXPECT(g_committed3.calls == before); + EXPECT(xs::device_slot_overridden(127)); + EXPECT(release(device) == 0); + + // A PC device whose ID3D12Device10 is another pointer than the device itself: the call goes to that one, and the + // reference the proxy took on it is given back. The base pointer is a trap that answers E_UNEXPECTED. + Mock* split_mock = nullptr; + void* split_device = make_device(split_mock, 10, true); + EXPECT(split_device); + Mock* alias = new_mock(Kind::device); + alias->device_level = 10; + alias->refs = 1; + split_mock->device10_alias = alias; + split_mock->create_result = E_UNEXPECTED; + resource = nullptr; + words[9] = word(&resource); + EXPECT(hr_of(raw10(split_device, 127, words)) == S_OK && resource); + EXPECT(g_committed3.device == alias); + EXPECT(alias->refs == 1); + EXPECT(release(resource) == 0); + EXPECT(release(split_device) == 0); + + // A PC device that stops at ID3D12Device9 has no CreateCommittedResource3: E_NOTIMPL, a null object, no PC call. + Mock* old_mock = nullptr; + void* old_device = make_device(old_mock, 9, true); + EXPECT(old_device && xs::device_proxy_slot_count(old_device) == 76); + resource = reinterpret_cast(1); + words[9] = word(&resource); + const unsigned old_before = g_committed3.calls; + EXPECT(hr_of(raw10(old_device, 127, words)) == E_NOTIMPL && !resource); + EXPECT(g_committed3.calls == old_before && old_mock->calls[76] == 0); + EXPECT(release(old_device) == 0); + std::printf("%s: device slot 127 creates the committed resource with the PC flags and layout\n", g_label); +#endif + return 0; +} + } // namespace // A failure ends the process with a message on stderr, never in a dialog a test run would wait on: abort() (an @@ -1062,195 +2761,26 @@ static void no_dialogs() { SetErrorMode(GetErrorMode() | SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX); } -int check_console_command_list() { - // 1. Slot mapping checks - EXPECT(xs::console_to_pc_list_slot(14) == 14); // Dispatch - EXPECT(xs::console_to_pc_list_slot(26) == 26); // ResourceBarrier - EXPECT(xs::console_to_pc_list_slot(31) == 27); // ExecuteBundle - EXPECT(xs::console_to_pc_list_slot(32) == 28); // SetDescriptorHeaps - EXPECT(xs::console_to_pc_list_slot(33) == 29); // SetComputeRootSignature - EXPECT(xs::console_to_pc_list_slot(35) == 31); // SetComputeRootDescriptorTable - EXPECT(xs::console_to_pc_list_slot(60) == 58); // EndEvent - EXPECT(xs::console_to_pc_list_slot(61) == 59); // ExecuteIndirect - EXPECT(xs::console_to_pc_list_slot(85) == 16); // CopyTextureRegion - EXPECT(xs::console_to_pc_list_slot(146) == 80); // GCL7 Barrier - EXPECT(xs::console_to_pc_list_slot(148) == xs::kListNotForwarded); // AllocateUploadMemory - - Mock* mock_device = nullptr; - void* device = make_device(mock_device, 11, true); - EXPECT(device != nullptr); - - // 2. PC Slot 12 vs Xbox Slot 73 - // PC Slot 12 returns unwrapped list directly, so PC tests like tiny_frame can call slot 48 (ClearRenderTargetView) - void* pc_list = nullptr; - const IID list_iid = __uuidof(ID3D12GraphicsCommandList); - EXPECT(hr_of(raw(device, 12, 0, D3D12_COMMAND_LIST_TYPE_DIRECT, 0, 0, word(&list_iid), word(&pc_list))) == S_OK); - EXPECT(pc_list != nullptr); - EXPECT(!xs::is_command_list_proxy(pc_list)); - Mock* real_pc_list = reinterpret_cast(pc_list); - EXPECT(real_pc_list->kind == Kind::command_list); - // In PC ABI, slot 48 is ClearRenderTargetView - raw(pc_list, 48, 0x1111, 0x2222, 0, 0); - EXPECT(real_pc_list->calls[48] == 1); - EXPECT(release(pc_list) == 0); - - // Xbox Slot 73 returns wrapped console command list proxy - void* allocator = nullptr; - const IID alloc_iid = __uuidof(ID3D12CommandAllocator); - EXPECT(hr_of(raw(device, 9, 0, word(&alloc_iid), word(&allocator))) == S_OK); - EXPECT(xs::is_allocator_proxy(allocator)); - Mock* real_allocator = reinterpret_cast(xs::allocator_proxy_real_allocator(allocator)); - - struct XboxCommandListDesc { - std::uint32_t type; - std::uint32_t node_mask; - std::uint64_t reserved[2]; - } desc{D3D12_COMMAND_LIST_TYPE_DIRECT, 0, {0, 0}}; - - void* list_proxy = nullptr; - EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&list_iid), word(&list_proxy))) == S_OK); - EXPECT(xs::is_command_list_proxy(list_proxy)); - EXPECT(xs::command_list_proxy_table_size() == 160); - - // 3. Inline cursor pinning: +0x18, +0x28, +0x30 - const auto base = reinterpret_cast(list_proxy); - std::uint64_t c18 = 0, c28 = 0, c30 = 0; - std::memcpy(&c18, reinterpret_cast(base + 0x18), sizeof(c18)); - std::memcpy(&c28, reinterpret_cast(base + 0x28), sizeof(c28)); - std::memcpy(&c30, reinterpret_cast(base + 0x30), sizeof(c30)); - const std::uint64_t expected_limit = static_cast(base + 0x18 + 0x500); - EXPECT(c18 == expected_limit); - EXPECT(c28 == expected_limit); - EXPECT(c30 == expected_limit); - - // 4. Console slot routing on ListProxy - Mock* real_list = reinterpret_cast(xs::command_list_proxy_real_list(list_proxy)); - EXPECT(real_list != nullptr && real_list->kind == Kind::command_list); - - // Console slot 32 (SetDescriptorHeaps) -> PC slot 28 - // Pass descriptor heap proxy to ensure UnwrappedArray unwrap_object works - D3D12_DESCRIPTOR_HEAP_DESC heap_desc{D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV, 16, D3D12_DESCRIPTOR_HEAP_FLAG_NONE, 0}; - void* heap_proxy = nullptr; - const IID heap_iid = __uuidof(ID3D12DescriptorHeap); - EXPECT(hr_of(raw(device, 14, word(&heap_desc), word(&heap_iid), word(&heap_proxy))) == S_OK); - EXPECT(heap_proxy != nullptr && xs::is_heap_proxy(heap_proxy)); - ID3D12DescriptorHeap* real_heap = xs::heap_proxy_real_heap(heap_proxy); - void* heap_ptrs[2] = {heap_proxy, real_heap}; - raw(list_proxy, 32, 2, word(heap_ptrs), 0, 0); - EXPECT(real_list->calls[28] == 1); - EXPECT(real_list->args[28][0] == 2); - // The heap proxy should have been unwrapped in the array passed to PC slot 28: - EXPECT(real_list->array[28][0] == word(real_heap)); - EXPECT(real_list->array[28][1] == word(real_heap)); - EXPECT(xs::list_slot_hits(32) == 1); - EXPECT(xs::list_slot_first_call_seen(32)); - - // Console slot 33 (SetComputeRootSignature) -> PC slot 29 - raw(list_proxy, 33, 0x5555, 0, 0, 0); - EXPECT(real_list->calls[29] == 1); - EXPECT(real_list->args[29][0] == 0x5555); - EXPECT(xs::list_slot_hits(33) == 1); - EXPECT(xs::list_slot_first_call_seen(33)); - - // Console slot 60 (EndEvent) -> PC slot 58 - raw(list_proxy, 60, 0, 0, 0, 0); - EXPECT(real_list->calls[58] == 1); - - // Console slot 61 (ExecuteIndirect) -> PC slot 59 - raw(list_proxy, 61, 0x10, 0x20, 0x30, 0x40); - EXPECT(real_list->calls[59] == 1); - EXPECT(real_list->args[59][0] == 0x10); - - // Console slot 148 (AllocateUploadMemory stub) -> returns 0 without faulting - EXPECT(raw(list_proxy, 148, 2048, 512, 0, 0) == 0); - EXPECT(xs::list_slot_hits(148) == 1); - EXPECT(xs::list_slot_first_call_seen(148)); - - // Console slot 146 (Barrier) on base 60-slot list returns E_NOTIMPL (PC slot 80 >= 60) - EXPECT(hr_of(raw(list_proxy, 146, 0, 0, 0, 0)) == E_NOTIMPL); - - // Console slot 10 (Reset) unwraps allocator proxy and re-pins inline cursor - std::uint64_t zero = 0; - std::memcpy(reinterpret_cast(base + 0x18), &zero, sizeof(zero)); - EXPECT(hr_of(raw(list_proxy, 10, word(allocator), 0, 0, 0)) == S_OK); - EXPECT(real_list->calls[10] == 1); - EXPECT(real_list->args[10][0] == word(real_allocator)); - std::memcpy(&c18, reinterpret_cast(base + 0x18), sizeof(c18)); - EXPECT(c18 == expected_limit); - - // Console slot 7 (GetDevice) returns device proxy - void* list_dev = nullptr; - const IID dev_iid = __uuidof(ID3D12Device); - const auto dev_refs_before = xs::device_proxy_ref_count(device); - EXPECT(hr_of(raw(list_proxy, 7, word(&dev_iid), word(&list_dev))) == S_OK); - EXPECT(list_dev == device); - EXPECT(xs::device_proxy_ref_count(device) == dev_refs_before + 1); - EXPECT(release(list_dev) == dev_refs_before); - - // Console slot 0 (QueryInterface) - void* list_qi = nullptr; - EXPECT(hr_of(raw(list_proxy, 0, word(&list_iid), word(&list_qi))) == S_OK); - EXPECT(list_qi == list_proxy); - EXPECT(release(list_qi) == 1); - - // 5. Queue slot 10 (ExecuteCommandLists) unwraps ListProxy in array - void* queue = nullptr; - D3D12_COMMAND_QUEUE_DESC qdesc{}; - const IID queue_iid = __uuidof(ID3D12CommandQueue); - EXPECT(hr_of(raw(device, 8, word(&qdesc), word(&queue_iid), word(&queue))) == S_OK); - EXPECT(xs::is_queue_proxy(queue)); - Mock* real_queue = reinterpret_cast(xs::queue_proxy_real_queue(queue)); - - Mock* unwrapped_list = new_mock(Kind::command_list); - void* lists_to_exec[2] = {unwrapped_list, list_proxy}; - raw(queue, 10, 2, word(lists_to_exec), 0, 0); - EXPECT(real_queue->calls[10] == 1); - EXPECT(real_queue->args[10][0] == 2); - EXPECT(real_queue->array[10][0] == word(unwrapped_list)); - EXPECT(real_queue->array[10][1] == word(real_list)); - - // 6. Test with list_level = 7 (supporting ID3D12GraphicsCommandList7, 81 slots) - mock_device->list_level = 7; - void* list7_proxy = nullptr; - EXPECT(hr_of(raw(device, 73, word(&desc), word(allocator), 0, word(&list_iid), word(&list7_proxy))) == S_OK); - EXPECT(xs::is_command_list_proxy(list7_proxy)); - Mock* real_list7 = reinterpret_cast(xs::command_list_proxy_real_list(list7_proxy)); - EXPECT(real_list7 != nullptr); - // Console slot 146 -> PC slot 80 (since 80 < 81 slots) - raw(list7_proxy, 146, 0x9999, 0, 0, 0); - EXPECT(real_list7->calls[80] == 1); - EXPECT(real_list7->args[80][0] == 0x9999); - EXPECT(release(list7_proxy) == 0 && real_list7->refs == 0); - - // Clean up - EXPECT(release(list_proxy) == 0 && real_list->refs == 0); - EXPECT(release(heap_proxy) == 0); - EXPECT(release(allocator) == 0 && real_allocator->refs == 0); - EXPECT(release(queue) == 0 && real_queue->refs == 0); - EXPECT(release(device) == 0 && mock_device->refs == 0); - - // 7. Verify stats reset - EXPECT(xs::list_slot_hits(32) > 0); - xs::reset_device_proxy_stats(); - EXPECT(xs::list_slot_hits(32) == 0); - EXPECT(!xs::list_slot_first_call_seen(32)); - - std::printf("%s: console command list routing, cursor pinning, queue unwrapping, and slot mapping passed\n", g_label); - return 0; -} - int main(int argc, char** argv) { no_dialogs(); std::setvbuf(stdout, nullptr, _IONBF, 0); if (argc == 2) { if (std::strcmp(argv[1], "--env-slots") == 0) return run_env_slots(true); if (std::strcmp(argv[1], "--env-slots-invalid") == 0) return run_env_slots(false); + if (std::strcmp(argv[1], "--env-slots-70") == 0) return run_env_slots(true, 70); + if (std::strcmp(argv[1], "--env-slots-74") == 0) return run_env_slots(true, 74); return run_fault_mode(argv[1]); } if (argc != 1) return 2; - if (check_tail(true) || check_levels() || check_fence1() || check_create_failures() || check_open_shared() || - check_alloc_failures() || check_allocators() || check_xbox_slots() || check_console_command_list()) + if (check_tail(true) || check_levels() || check_slot48() || check_fence1() || check_create_failures() || + check_open_shared() || check_alloc_failures() || check_allocators() || check_xbox_slots() || + check_custom_heap_properties() || check_lists() || check_signalx_detection() || check_list_tail_names() || + check_descriptor_heap_hooks() || check_slot70() || check_slot70_raw_buffer() || + check_committed_resource3_x() || check_render_target_sizes() || check_allocation_descriptions_cleaned() || + check_committed_resource_leases() || check_slot74() || check_fence_completed_value() || + check_list_cpu_handles()) return 1; + if (check_placed_resource_x()) return 1; std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); return 0; } diff --git a/scripts/build_runtime.ps1 b/scripts/build_runtime.ps1 index 010a8782d1..bf2003a7ec 100644 --- a/scripts/build_runtime.ps1 +++ b/scripts/build_runtime.ps1 @@ -81,7 +81,7 @@ $build || exit /b 1 Write-Warning "CMake and Ninja weren't found (neither VS C++ CMake tools nor native PATH tools): building with cl.exe directly, without the GameInput shim (SDL3). Install CMake + Ninja or VS's CMake tools component to get it." $xtaskqueueDir = Join-Path $root "third_party\xtaskqueue" $xtaskqueueFiles = "Source\Task\TaskQueue.cpp", "Source\Task\AsyncLib.cpp", "Source\Task\ThreadPool_win32.cpp", "Source\Task\WaitTimer_win32.cpp" | ForEach-Object { "`"$xtaskqueueDir\$_`"" } - $files = "src\main.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\xg_xs.cpp", "shims\acphal.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\com_shim.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_chad.cpp" | ForEach-Object { "`"$src\$_`"" } + $files = "src\main.cpp", "src\host_cpu.cpp", "src\pe_loader.cpp", "shims\registry.cpp", "shims\file_system.cpp", "shims\xmem.cpp", "shims\xg_xs.cpp", "shims\acphal.cpp", "shims\d3d12_xs.cpp", "shims\d3d12_xs_device.cpp", "shims\d3d12_xs_rootsig.cpp", "shims\xgameruntime.cpp", "shims\xgameruntime_user.cpp", "shims\xgameruntime_gamesave.cpp", "shims\xgameruntime_store.cpp", "shims\xgameruntime_offline.cpp", "shims\winhttp_offline.cpp", "shims\library_loader.cpp", "shims\process.cpp", "shims\com_shim.cpp", "shims\bcrypt_rng.cpp", "shims\xapu_chad.cpp" | ForEach-Object { "`", "shims\dstorage.cpp", "shims\xbox_bvh_builder.cpp"$src\$_`"" } $includes = "/I `"$src\src`" /I `"$src\shims`" /I `"$src\shims\xtaskqueue`" /I `"$xtaskqueueDir\Include`" /I `"$xtaskqueueDir\Source\Task`" /I `"$xtaskqueueDir\Source\Common`"" $opt = if ($Debug) { "/Od /MDd" } else { "/O2 /MD" } $body = @" diff --git a/tests/test_exe_shaders_stage.py b/tests/test_exe_shaders_stage.py new file mode 100644 index 0000000000..e96d0936d9 --- /dev/null +++ b/tests/test_exe_shaders_stage.py @@ -0,0 +1,385 @@ +"""make_game.py's executable shader step (exe_shaders) and the index key the runtime finds its programs by (fssm_sha256). + + python -I tests/test_exe_shaders_stage.py + +Zero game data: the "executable" is synthetic bytes around hand-built DXBC containers whose PSV0 chunk names a +graphics stage (VS/PS) and whose XBCH record is a zlib stream of a made-up FSSM blob; llvm-mc and the translator are +stood in for the way tests/test_bvh_shaders_stage.py does. The extracting, unpacking and disassembling tools are the +repository's own, run as make_game.py runs them. +""" +import hashlib +import io +import json +import os +import struct +import subprocess +import sys +import tempfile +import unittest +import zlib +from unittest import mock + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +sys.path.insert(0, ROOT) +sys.path.insert(0, os.path.join(ROOT, "tools")) +sys.path.insert(0, os.path.join(ROOT, "tests")) +import make_game # noqa: E402 +import rdna2spirv # noqa: E402 +import shader_meta # noqa: E402 +from test_pe_shader_containers import container, xdat # noqa: E402 + +TOOLS = ["pe_shader_containers.py", "fssm_unpack.py", "shader_disasm.py", "rdna2spirv.py"] +ENDPGM = b"\x00\x00\x81\xbf" +PSV0_STAGE_CODE = {"ps": 0, "vs": 1} + + +def fssm_blob(seed: int) -> bytes: + """A made-up FSSM blob shader_disasm.py accepts: the code section offset at 0xC0, code 0x28 bytes into it, a + few filler words that differ per seed and the closing s_endpgm.""" + head = bytearray(b"FSSM" + b"\x01\x01" + bytes(0xF0 - 6)) + struct.pack_into(" bytes: + """A minimal PSV0 chunk whose ShaderStage byte at payload offset 4 + 24 names `stage`.""" + payload = bytearray(struct.pack(" bytes: + """DXBC { SFI0, PSV0 = stage, DXIL = program header + XDAT { 0x12, 0x0D = XBCH + zlib(blob), 0x07 = bitcode } }: + the parts of game_scarlett_master.exe's embedded containers the tools read (no ILDN chunk; docs/embedded_shaders.md + section 2).""" + packed = zlib.compress(blob) + xbch = b"XBCH" + struct.pack(" bytes: + """Containers between unrelated bytes, as the executable holds them.""" + return b"MZ" + b"\0" * 126 + b"".join(c + b"\xcc" * 12 for c in containers) + + +def tool(name: str, *args: str) -> subprocess.CompletedProcess: + return subprocess.run([sys.executable, "-I", os.path.join(ROOT, "tools", name), *args], + capture_output=True, text=True) + + +class IndexKey(unittest.TestCase): + """Extracted PSV0 containers without ILDN unpack to FSSM and give rdna2spirv the stage (vs/ps) and fssm_sha256.""" + + def test_the_extracted_layout_gives_the_translator_the_key_and_graphics_stages(self): + programs = [("container_00", "vs", fssm_blob(1)), ("container_01", "ps", fssm_blob(2))] + with tempfile.TemporaryDirectory() as t: + exe = os.path.join(t, make_game.EXE_FILE) + with open(exe, "wb") as f: + f.write(exe_like(*(exe_container(stage, blob) for _, stage, blob in programs))) + out = os.path.join(t, "exe") + r = tool("pe_shader_containers.py", exe, "--extract", out) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + r = tool("fssm_unpack.py", out, "--carve-index", os.path.join(out, "index.json")) + self.assertEqual(r.returncode, 0, r.stdout + r.stderr) + os.makedirs(os.path.join(out, "disasm")) + rdna2spirv._STAGES = None + self.addCleanup(setattr, rdna2spirv, "_STAGES", None) + for name, stage, blob in programs: + with open(os.path.join(out, "fssm", name + ".fssm"), "rb") as f: + self.assertEqual(f.read(), blob) + listing = os.path.join(out, "disasm", name + ".s") + meta = shader_meta.collect(listing, name, [[]], [[]]) + self.assertEqual(meta.get("fssm_sha256"), hashlib.sha256(blob).hexdigest()) + self.assertNotIn("fspx_code_sha256", meta) + self.assertEqual(rdna2spirv.stage_of(name, listing), stage) + + +class ExeStage(unittest.TestCase): + """Which tools exe_shaders() runs and what it reports. Each stand-in writes what the real tool writes last.""" + + def setUp(self): + self.tmp = tempfile.TemporaryDirectory() + self.addCleanup(self.tmp.cleanup) + self.work = os.path.join(self.tmp.name, "work") + self.game = os.path.join(self.tmp.name, "game") + os.makedirs(self.game) + self.exe = os.path.join(self.game, make_game.EXE_FILE) + self.programs = { + "container_00": ("vs", fssm_blob(1)), + "container_01": ("ps", fssm_blob(2)), + "container_02": ("ps", fssm_blob(3)), + } + self.untranslated = set() + self.write_exe() + self.unpacked = os.path.join(self.work, "shaders", "exe") + self.spirv = os.path.join(self.work, "shaders", "spirv", "exe") + self.calls, self.logs = [], [] + + def write_exe(self): + with open(self.exe, "wb") as f: + f.write(exe_like(*(exe_container(stage, blob) for stage, blob in self.programs.values()))) + + def fake_translate(self, *args): + out = args[args.index("--out") + 1] + os.makedirs(out, exist_ok=True) + index = {} + for listing in sorted(os.listdir(args[0])): + name = listing[:-2] + if not listing.endswith(".s") or name in self.untranslated: + continue + with open(os.path.join(os.path.dirname(args[0]), "fssm", name + ".fssm"), "rb") as f: + stage = self.programs[name][0] + index[name] = {"stage": stage, "fssm_sha256": hashlib.sha256(f.read()).hexdigest()} + with open(os.path.join(out, name + ".spv"), "wb") as f: + f.write(b"module of " + name.encode()) + with open(os.path.join(out, "index.json"), "w", encoding="utf-8", newline="\n") as f: + json.dump(index, f) + + def fake_py(self, tool_name, *args): + self.calls.append((tool_name, args)) + if tool_name == "pe_shader_containers.py": + os.makedirs(self.unpacked, exist_ok=True) + for name in self.programs: + open(os.path.join(self.unpacked, name + ".dxbc"), "wb").close() + with open(os.path.join(self.unpacked, "index.json"), "w", encoding="utf-8", newline="\n") as f: + json.dump([{"name": n, "file": n + ".dxbc", "stage": st} for n, (st, _) in self.programs.items()], f) + elif tool_name == "fssm_unpack.py": + os.makedirs(os.path.join(self.unpacked, "fssm"), exist_ok=True) + for name, (_, blob) in self.programs.items(): + with open(os.path.join(self.unpacked, "fssm", name + ".fssm"), "wb") as f: + f.write(blob) + with open(os.path.join(self.unpacked, "fssm_index.json"), "w", encoding="utf-8", newline="\n") as f: + json.dump([{"name": n} for n in self.programs], f) + elif tool_name == "shader_disasm.py": + os.makedirs(os.path.join(self.unpacked, "disasm"), exist_ok=True) + for name in self.programs: + with open(os.path.join(self.unpacked, "disasm", name + ".s"), "w", encoding="utf-8", + newline="\n") as f: + f.write("s_endpgm\n") + elif tool_name == "rdna2spirv.py": + self.fake_translate(*args) + + def run_step(self, signature="llvm-mc 23", emulate=False, fallbacks=(), py=None): + self.calls, self.logs = [], [] + with mock.patch.object(make_game, "py", py or self.fake_py), \ + mock.patch.object(make_game, "log", self.logs.append): + make_game.exe_shaders(self.game, self.work, signature, 3, emulate=emulate, fallbacks=fallbacks) + return [name for name, _ in self.calls] + + def test_runs_once_then_only_reports(self): + self.assertEqual(self.run_step(), TOOLS) + (_, extract), (_, unpack), (_, disasm), (_, translate) = self.calls + self.assertEqual(extract, (self.exe, "--extract", self.unpacked)) + self.assertEqual(unpack, (self.unpacked, "--carve-index", os.path.join(self.unpacked, "index.json"))) + self.assertEqual(disasm, (os.path.join(self.unpacked, "fssm"), "--unpack-index", + os.path.join(self.unpacked, "fssm_index.json"), "--out", + os.path.join(self.unpacked, "disasm"), "--mcpu", "gfx1013", "--jobs", 3)) + # Graphics shaders: no --max-shared-memory compute LDS cap. + self.assertEqual(translate, (os.path.join(self.unpacked, "disasm"), "--out", self.spirv, "--no-asm")) + self.assertTrue(os.path.isfile(os.path.join(self.spirv, "exe_build.json"))) + self.assertIn(f"shaders: 3 of 3 {make_game.EXE_FILE} programs translated", self.logs) + self.assertEqual(self.run_step(), []) + self.assertEqual(self.logs, [f"shaders: 3 of 3 {make_game.EXE_FILE} programs translated"]) + + def test_the_real_tools_fill_the_folder_and_a_second_run_leaves_no_duplicates(self): + mc = os.path.join(self.tmp.name, "fake_mc.py") + with open(mc, "w", encoding="utf-8", newline="\n") as f: + f.write("print('\\ts_endpgm')\n") + + def run_tool(tool_name, *args): + self.calls.append((tool_name, args)) + if tool_name == "rdna2spirv.py": + return self.fake_translate(*args) + make_game.run([sys.executable, "-I", os.path.join(make_game.TOOLS, tool_name), *args], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + + with mock.patch.dict(os.environ, {"LLVM_MC": f'"{sys.executable}" "{mc}"'}): + for signature in ("llvm-mc 23", "llvm-mc 24"): + self.assertEqual(self.run_step(signature=signature, py=run_tool), TOOLS) + names = sorted(self.programs) + self.assertEqual(sorted(f for f in os.listdir(self.unpacked) if f.endswith(".dxbc")), + [n + ".dxbc" for n in names]) + self.assertEqual(sorted(os.listdir(os.path.join(self.unpacked, "fssm"))), + [n + ".fssm" for n in names]) + self.assertEqual(sorted(os.listdir(os.path.join(self.unpacked, "disasm"))), + [n + ".s" for n in names]) + with open(os.path.join(self.spirv, "index.json"), encoding="utf-8") as f: + index = json.load(f) + self.assertEqual({n: (index[n]["stage"], index[n]["fssm_sha256"]) for n in index}, + {n: (st, hashlib.sha256(blob).hexdigest()) for n, (st, blob) in self.programs.items()}) + self.assertIn(f"shaders: 3 of 3 {make_game.EXE_FILE} programs translated", self.logs) + self.assertEqual(self.run_step(signature="llvm-mc 24", py=run_tool), []) + + def test_no_exe_no_step(self): + os.remove(self.exe) + self.assertEqual(self.run_step(), []) + self.assertFalse(os.path.exists(self.spirv)) + self.assertFalse(os.path.exists(self.unpacked)) + + def test_an_exe_that_is_gone_takes_the_old_index_with_it(self): + self.assertEqual(self.run_step(), TOOLS) + index, settings = os.path.join(self.spirv, "index.json"), os.path.join(self.spirv, "exe_build.json") + self.assertTrue(os.path.isfile(index) and os.path.isfile(settings)) + os.remove(self.exe) + self.assertEqual(self.run_step(), []) + self.assertFalse(os.path.exists(index)) + self.assertFalse(os.path.exists(settings)) + self.assertEqual(self.logs, [f"shaders: no {make_game.EXE_FILE} in the game folder, so no executable " + "shader programs to translate"]) + self.assertEqual(self.run_step(), []) + self.write_exe() + self.assertEqual(self.run_step(), TOOLS) + self.assertTrue(os.path.isfile(index) and os.path.isfile(settings)) + + def test_each_input_change_runs_it_again(self): + self.run_step() + self.assertEqual(self.run_step(signature="llvm-mc 24"), TOOLS) + self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True), TOOLS) + self.assertIn("--wave64-emulate", self.calls[3][1]) + flags = ("--no-float-controls",) + self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True, fallbacks=flags), TOOLS) + self.assertIn("--no-float-controls", self.calls[3][1]) + self.programs["container_02"] = ("ps", fssm_blob(4)) + self.write_exe() + self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True, fallbacks=flags), TOOLS) + self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True, fallbacks=flags), []) + with mock.patch.object(make_game, "translation_sources_digest", return_value="another translator"): + self.assertEqual(self.run_step(signature="llvm-mc 24", emulate=True, fallbacks=flags), TOOLS) + + def test_an_untranslated_program_is_named_on_every_run_and_the_step_still_finishes(self): + self.untranslated = {"container_01"} + for expected in (TOOLS, [], []): + self.assertEqual(self.run_step(), expected) + self.assertIn(f"shaders: 2 of 3 {make_game.EXE_FILE} programs translated", self.logs) + named = [line for line in self.logs if "NOT translated: container_01." in line] + self.assertEqual(len(named), 1, self.logs) + self.assertNotIn("container_00", named[0]) + with open(os.path.join(self.spirv, "index.json"), encoding="utf-8") as f: + self.assertEqual(sorted(json.load(f)), ["container_00", "container_02"]) + self.assertFalse(os.path.exists(os.path.join(self.spirv, "container_01.spv"))) + + def test_nothing_translated_fails_and_keeps_no_index(self): + self.untranslated = set(self.programs) + with self.assertRaises(SystemExit), mock.patch("sys.stderr", new_callable=io.StringIO) as err: + self.run_step() + self.assertIn(f"none of the {make_game.EXE_FILE} programs translated", err.getvalue()) + self.assertFalse(os.path.exists(os.path.join(self.spirv, "index.json"))) + self.assertFalse(os.path.exists(os.path.join(self.spirv, "exe_build.json"))) + self.untranslated = set() + self.assertEqual(self.run_step(), TOOLS) + + def test_missing_cached_module_or_index_is_rebuilt(self): + self.assertEqual(self.run_step(), TOOLS) + module = os.path.join(self.spirv, "container_00.spv") + os.remove(module) + self.assertEqual(self.run_step(), TOOLS) + with open(module, "rb") as f: + self.assertEqual(f.read(), b"module of container_00") + self.assertEqual(self.run_step(), []) + os.remove(os.path.join(self.unpacked, "index.json")) + self.assertEqual(self.run_step(), TOOLS) + self.assertEqual(self.run_step(), []) + + def test_empty_cached_index_is_rebuilt(self): + """A cached index.json with no usable entries ({} or all error entries) must not be reused as finished.""" + self.assertEqual(self.run_step(), TOOLS) + for bad_index in ("{}", '{"container_00": {"error": "ValueError: synthetic"}}'): + with open(os.path.join(self.spirv, "index.json"), "w", encoding="utf-8", newline="\n") as f: + f.write(bad_index) + self.assertEqual(self.run_step(), TOOLS) + self.assertIn(f"shaders: 3 of 3 {make_game.EXE_FILE} programs translated", self.logs) + self.assertEqual(self.run_step(), []) + self.assertEqual(self.logs, [f"shaders: 3 of 3 {make_game.EXE_FILE} programs translated"]) + + +class ShadersStageWithTheExe(unittest.TestCase): + """The whole shaders() stage with both DLLs and the executable: exe_shaders() runs last and runs alone when only + the executable changes.""" + + def test_exe_runs_after_bvh_and_alone_when_only_the_exe_changes(self): + from test_bvh_shaders_stage import builder_container, dll_like as bvh_dll + from test_fspx_shaders_stage import container as fspx_container, dll_like as fspx_dll, program + with tempfile.TemporaryDirectory() as t: + work, game = os.path.join(t, "work"), os.path.join(t, "game") + os.makedirs(game) + with open(os.path.join(game, make_game.FSPX_DLL), "wb") as f: + f.write(fspx_dll(fspx_container(program()))) + with open(os.path.join(game, make_game.BVH_DLL), "wb") as f: + f.write(bvh_dll(builder_container("SortKeys", fssm_blob(1)))) + exe = os.path.join(game, make_game.EXE_FILE) + with open(exe, "wb") as f: + f.write(exe_like(exe_container("vs", fssm_blob(2)))) + ran = [] + dxbc = os.path.join(work, "shaders", "dxbc") + bvh = os.path.join(work, "shaders", "bvh") + exe_dir = os.path.join(work, "shaders", "exe") + + def write(text, *parts): + os.makedirs(os.path.dirname(os.path.join(*parts)), exist_ok=True) + with open(os.path.join(*parts), "w", encoding="utf-8", newline="\n") as f: + f.write(text) + + def fake_py(tool_name, *args): + ran.append(tool_name) + if tool_name == "shader_carve.py": + write('[{"file": "shader.dxbc"}]', dxbc, "index.json") + elif tool_name == "pe_shader_containers.py": + if args[2] == exe_dir: + write('[{"name": "container_00", "file": "container_00.dxbc", "stage": "vs"}]', + exe_dir, "index.json") + else: + write('[{"name": "SortKeys", "file": "SortKeys.dxbc", "stage": "cs"}]', bvh, "index.json") + elif tool_name == "fssm_unpack.py": + if args[0] == exe_dir: + write('[{"name": "container_00"}]', exe_dir, "fssm_index.json") + elif args[0] == bvh: + write('[{"name": "SortKeys"}]', bvh, "fssm_index.json") + else: + write('[{"name": "shader"}]', dxbc, "fssm_index.json") + elif tool_name == "shader_disasm.py": + if args[0].startswith(exe_dir): + write("s_endpgm\n", exe_dir, "disasm", "container_00.s") + elif args[0].startswith(bvh): + write("s_endpgm\n", bvh, "disasm", "SortKeys.s") + else: + write("s_endpgm\n", dxbc, "disasm", "shader.s") + elif tool_name == "rdna2spirv.py": + out = args[args.index("--out") + 1] + if args[0].startswith(exe_dir): + write('{"container_00": {"stage": "vs", "fssm_sha256": "%s"}}' % ("b" * 64), out, "index.json") + write("", out, "container_00.spv") + elif args[0].startswith(bvh): + write('{"SortKeys": {"stage": "cs", "fssm_sha256": "%s"}}' % ("a" * 64), out, "index.json") + write("", out, "SortKeys.spv") + else: + write('{"Upscale": {"stage": "cs"}}', out, "index.json") + write("", out, "Upscale.spv") + + def fake_translate(disasm, spirv, jobs, emulate=False, fallbacks=()): + ran.append("translate") + write("", spirv, "index.json") + + def stage(): + ran.clear() + with mock.patch.object(make_game, "py", fake_py), \ + mock.patch.object(make_game, "need", lambda *a: None), \ + mock.patch.object(make_game, "translate", fake_translate), \ + mock.patch.object(make_game, "llvm_mc_signature", return_value="llvm-mc 23"), \ + mock.patch.object(make_game, "log", lambda *a: None): + make_game.shaders(game, work, 2) + return list(ran) + + self.assertEqual(stage(), ["shader_carve.py", "fssm_unpack.py", "shader_disasm.py", "translate", + "fspx_unpack.py", "rdna2spirv.py", *TOOLS, *TOOLS]) + self.assertEqual(stage(), []) + with open(exe, "wb") as f: + f.write(exe_like(exe_container("vs", fssm_blob(3)))) + self.assertEqual(stage(), TOOLS) + for sub in ((), ("fspx",), ("bvh",), ("exe",)): + self.assertTrue(os.path.isfile(os.path.join(work, "shaders", "spirv", *sub, "index.json"))) + + +if __name__ == "__main__": + unittest.main()