diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 3ae29163e5..23245b8251 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2247,6 +2247,30 @@ 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 that 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). 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. @@ -2263,8 +2287,9 @@ The trace will enumerate them. 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`). Slots 25 and 43 return structs too; the - executable has not been seen calling them yet, so the proxy still forwards them in the PC form. + (`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. @@ -3506,6 +3531,10 @@ 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, for a caller in an image the guest loader mapped; the PC slot 61 is `CreateMetaCommand`, which any other caller (a host test driving the device through the proxy) still gets. The layout of the description beyond the PC fields is **Open**. | +| Device slot 74 | The retail title's boot under `gta6rt --run`: called as `(pointer, u32, pointer)` | **Stand-in.** `d3d12_xs_device.cpp` answers `S_OK` and does nothing, for a caller in an image the guest loader mapped; the PC slot 74 is `ShaderCacheControl`, which the call does not fit and which any other caller still gets. What the console method is, and what it should do, is **Open**. | +| Command-allocator slot 9 | The retail title's boot under `gta6rt --run`: called past the 9-slot PC allocator, as `(function pointer, context, ...)`; `SetAllocatorCallbackX` is the name the commit that added it uses | **Stand-in.** The allocator proxy records the callback and its context (`allocator_proxy_callback`, `allocator_proxy_callback_context`) and answers `S_OK`. **Nothing calls the callback**: the Vulkan layer backs command buffers itself. Whether the title depends on being called back 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. | diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index 64e346f40a..e922f067c9 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1025,6 +1025,7 @@ 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_74 COMMAND xs_proxy_mock_test --env-slots-74) endif() if(TARGET root_sig_test) add_test(NAME root_sig COMMAND root_sig_test) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 4f4904e965..cf02df5193 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -842,11 +842,21 @@ class GraphicsCommandList final kind == leonida::IndirectKind::draw ? sizeof(D3D12_DRAW_ARGUMENTS) : kind == leonida::IndirectKind::draw_indexed ? sizeof(D3D12_DRAW_INDEXED_ARGUMENTS) : kind == leonida::IndirectKind::dispatch ? sizeof(D3D12_DISPATCH_ARGUMENTS) + : kind == leonida::IndirectKind::dispatch_mesh ? sizeof(D3D12_DISPATCH_MESH_ARGUMENTS) : 0; if (!record_size || stride < record_size || stride % 4 != 0) return check(false); if (argument_buffer_offset > arg_desc.Width || UINT64(max_command_count) > (arg_desc.Width - argument_buffer_offset) / stride) 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; + } leonida::ExecuteIndirect cmd{}; cmd.kind = kind; cmd.stride = stride; diff --git a/runtime/shims/d3d12_vulkan_device.cpp b/runtime/shims/d3d12_vulkan_device.cpp index 0273f9339b..6cc357c87e 100644 --- a/runtime/shims/d3d12_vulkan_device.cpp +++ b/runtime/shims/d3d12_vulkan_device.cpp @@ -5833,6 +5833,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()); diff --git a/runtime/shims/d3d12_xs.cpp b/runtime/shims/d3d12_xs.cpp index 8e54c3fd56..173106f1cd 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); @@ -155,6 +166,12 @@ HRESULT WINAPI D3D12XboxCreateDevice(IUnknown* adapter, const void* params, cons std::fprintf(stderr, "[rt] d3d12_xs: D3D12XboxCreateDevice: wrapping the PC ID3D12Device in the Xbox-ABI proxy " "(slot 62 -> CreateComputePipelineState, slot 76 -> CreateCommittedResource).\n"); + // A console method whose slot is another PC method (61) is served only to the title: a caller in an image + // this loader mapped. + rt::d3d12_xs::set_console_caller([](std::uint64_t address) { + std::uint64_t base = 0; + return rt::shims::mapped_image_base(address, base); + }); } #ifdef LEONIDA_VULKAN_DEVICE 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_desc_clean.h b/runtime/shims/d3d12_xs_desc_clean.h new file mode 100644 index 0000000000..ba51184a4d --- /dev/null +++ b/runtime/shims/d3d12_xs_desc_clean.h @@ -0,0 +1,38 @@ +// 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); + +// 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(static_cast(xbox.Flags) & kPcResourceFlagsMask); + return pc; +} + +} // namespace rt::d3d12_xs diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 7f7040fdd9..2f0b547d8b 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -25,12 +25,23 @@ // behind the device before a presenter exists, so WaitFrameEventX returns at once with a fresh non-zero token. #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 slot lands on the Xbox presentation core, which needs the Vulkan layer's +// WindowPresenter. Other builds of this file (the mock and COM tests) have no presenter and answer S_OK. +#include "xbox_present.h" +#endif + #include #include +#include // _ReturnAddress: slot 61 serves a console caller differently from a host one #include +#include #include #include #include @@ -38,9 +49,12 @@ #include #include #include -#include +#include #include +#include +#include #include +#include namespace rt::d3d12_xs { namespace { @@ -75,9 +89,14 @@ 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(); + // The PresentX state (window, presenter, XboxPresentation) the first queue PresentX builds on this device, + // destroyed with the proxy. Opaque here: PresentState is defined with the queue proxy. + void* present_state = nullptr; }; +void destroy_present_state(void* present_state); + constexpr unsigned kHeapSlots = 11; // IUnknown + ID3D12Object + DeviceChild + Pageable + GetDesc + 2 handles struct HeapProxy { @@ -86,8 +105,85 @@ 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; +} + std::atomic g_hits[kMaxSlots]; std::atomic g_first[kMaxSlots]; std::atomic g_beyond_warned[kMaxSlots]; @@ -134,6 +230,14 @@ const char* slot_name(unsigned slot) { case 11: return "CreateComputePipelineState (PC slot 11)"; case 14: return "CreateDescriptorHeap"; case 16: return "CreateRootSignature"; + 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"; case 27: return "CreateCommittedResource (PC slot 27)"; @@ -142,15 +246,19 @@ const char* slot_name(unsigned slot) { 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 50: return "EnqueueMakeResident (proxies unwrapped)"; + case 56: return "GetResourceAllocationInfo1 (C or PC form)"; + case 61: return "Xbox CreateSamplerX -> PC CreateSampler (a host caller gets PC CreateMetaCommand)"; 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 76: return "Xbox resource creation"; case 127: return "Xbox CreateCommittedResource3"; @@ -283,6 +391,7 @@ unsigned long proxy_release(DeviceProxy* self) { const unsigned long refs = self->refs.fetch_sub(1, std::memory_order_acq_rel) - 1; if (refs == 0) { ID3D12Device* real = self->real; + destroy_present_state(self->present_state); // the presenter goes before the device it draws with delete self; if (real) real->Release(); } @@ -494,11 +603,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; } @@ -533,17 +646,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); @@ -599,7 +716,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; @@ -611,11 +730,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; @@ -685,7 +816,13 @@ 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 kQueueGetTimestampFrequency = 16, kQueueGetDesc = 18; // the PC slots +bool is_console_caller(const void* address); // defined with the device proxy +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 @@ -694,6 +831,9 @@ struct ChildProxy { void** real_vtable; unsigned slot_count; // public slots the real object implements; the rest of the table is refused std::atomic refs; + // Allocators only: callback and context recorded by console slot 9 (SetAllocatorCallbackX). + std::atomic allocator_callback{0}; + std::atomic allocator_callback_context{0}; }; template @@ -726,10 +866,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; } @@ -898,6 +1040,11 @@ bool is_child_proxy(const void* object) { constexpr unsigned kListSlots = 160; 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 kConsoleBarrier = 146; struct ListProxy { @@ -1094,14 +1241,54 @@ std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t std::uint64_t, std::uint64_t); auto** const real_vtable = *reinterpret_cast(self->real); UnwrappedArray heaps; - if constexpr (Slot == 10) { + if constexpr (pc == 10) { + // Reset(allocator, pso): console slot 10, and slot 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 the same way). a1 = unwrap_object(a1); + a2 = unwrap_object(a2); 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(); + } else if constexpr (Slot == kConsoleOMSetRenderTargets) { + // OMSetRenderTargets(count, render target handles, single range, depth-stencil handle): the handles + // may be in the title's own descriptor range (__XMemAllocationHooks__), which only this proxy can + // translate. Copies are translated; the caller's arrays are not written. + 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(view, colour, rect count, rects): the view handle is translated. + 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(GPU handle, CPU handle, resource, values, rect count, rects): + // the CPU handle is translated, the GPU handle is kept. + 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); @@ -1109,9 +1296,37 @@ std::uint64_t WINAPI list_slot(ListProxy* self, std::uint64_t a1, std::uint64_t } } +// ClearDepthStencilView (console slot 51 -> PC slot 47) takes FLOAT Depth as its fourth argument, in XMM3 on the +// Windows x64 ABI. The all-integer list_slot thunk reads R9 there and loses the depth, so this slot has a typed +// thunk that keeps it and translates a 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); + 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() { @@ -1194,6 +1409,100 @@ 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 } +// ---- PresentX (console queue slot 32) ---- +// +// The retail title presents through command-queue slot 32, past the PC queue's 19 slots: PresentX(plane count, +// planes, parameters), the call the Xbox presentation core (xbox_present.h) implements. The first call on a device +// builds a window and the Vulkan layer's presenter for it, once; a device that cannot present (no presenter, no +// window) answers S_OK and shows nothing, so the title's frame loop keeps running either way. +// ASSUMPTION: the window is one this layer creates. The title has a window of its own; presenting into that one is +// a separate piece of work (old PR 8591). +constexpr unsigned kQueuePresentX = 32; + +#ifdef LEONIDA_VULKAN_DEVICE + +struct PresentState { + ~PresentState() { + xbox.reset(); + if (window) DestroyWindow(window); + } + HWND window = nullptr; + std::unique_ptr xbox; +}; + +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); +} + +// Builds the window, presenter and XboxPresentation once per device. Returns the state even when `xbox` stays null: +// the failure is logged once and not retried. +PresentState* present_state_for(DeviceProxy* device) { + static std::mutex mutex; + const std::lock_guard lock(mutex); + if (auto* state = static_cast(device->present_state)) return state; + auto* state = new (std::nothrow) PresentState; + if (!state) return nullptr; + device->present_state = state; + 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; + } + ShowWindow(state->window, SW_SHOWNOACTIVATE); + auto presenter = rt::d3d12::create_window_presenter(device->real, state->window); + if (!presenter) { + std::fprintf(stderr, "[rt] d3d12_xs: no window presenter on this device; PresentX shows nothing\n"); + return state; + } + state->xbox = std::make_unique(std::move(presenter), nullptr, device->frame_tokens); + // The device's token source: the title takes its frame tokens from device slot 80 and presents them here. + 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); // the 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 (the 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 + +std::uint64_t queue_execute_command_lists(ChildProxy* self, std::uint64_t count_word, std::uint64_t lists_word) { + // The array holds what the title got from the proxy: list proxies are replaced by the real lists in a copy, as + // for every other array of objects the real device or queue reads. + UnwrappedArray unwrapped_lists; + if (!unwrapped_lists.fill(lists_word, static_cast(count_word))) return hr_to_u64(E_OUTOFMEMORY); + if (unwrapped_lists.data()) lists_word = unwrapped_lists.data(); + // Pass zero-extended UINT in 64-bit RDX so both 32-bit PC implementations and 64-bit mock thunks see clean count. + using ExecuteFn = void(WINAPI*)(void*, std::uint64_t, ID3D12CommandList* const*); + reinterpret_cast(self->real_vtable[kQueueExecuteCommandLists])( + self->real, static_cast(static_cast(count_word)), + reinterpret_cast(lists_word)); + 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, @@ -1213,6 +1522,31 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ reinterpret_cast(a2))); } 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 && Slot == kQueuePresentX) { + return queue_present_x(self, a1, a2, a3); // XboxPresentation::PresentX writes the trace line + } + 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, @@ -1228,6 +1562,22 @@ 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 == kQueueGetDesc) { + // Queue slot 18 is GetDesc on the PC: a struct return, 16 bytes written through the hidden pointer. The + // retail title calls slot 18 with one pointer to 8 bytes, the shape of GetTimestampFrequency(UINT64*), + // which the console layout with two methods inserted at 14/15 has there (PC slot 16). Forwarded as + // GetDesc it wrote a whole description over the title's 8 bytes and what follows them. The title's call + // therefore goes to the frequency getter, the only reading that cannot overrun its argument; a host + // caller (set_console_caller, as device slots 61 and 74) keeps the PC GetDesc. + if (is_console_caller(_ReturnAddress())) { + using Fn = HRESULT(WINAPI*)(void*, UINT64*); + return hr_to_u64(reinterpret_cast(self->real_vtable[kQueueGetTimestampFrequency])( + self->real, reinterpret_cast(a1))); + } + } if constexpr (K == ChildKind::queue && (Slot == kQueueSignal || Slot == kQueueWait)) a1 = unwrap_object(a1); UnwrappedArray unwrapped_lists; if constexpr (K == ChildKind::queue && Slot == 10) { @@ -1407,9 +1757,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; } @@ -1676,11 +2024,131 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H 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(); + 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; + } + // A heap the console-extended handler made already sits at the address the title named: the hook-backed address + // is for a heap made from a plain PC description only. + if (!console_extended && 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); + } + } + } + } + + 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)); +} + +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)); +} + +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)); +} + +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)); +} + +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); +} + +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); +} + // 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. @@ -1699,6 +2167,90 @@ 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. +// The same proxy also serves host callers (the runtime's own tests drive the Vulkan device through it), for whom slot +// 61 is the PC ID3D12Device5::CreateMetaCommand. So the slot is CreateSamplerX only for a caller in an image the +// guest loader mapped (set_console_caller); any other caller, or every caller when no check is installed, gets the PC +// method. Without the check d3d12_vulkan_device_test's CreateMetaCommand call reached this handler (#7115). +std::atomic g_console_caller{nullptr}; + +bool is_console_caller(const void* address) { + const ConsoleCaller classify = g_console_caller.load(std::memory_order_acquire); + return classify && classify(reinterpret_cast(address)); +} + +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{}; + // A destination in the title's own descriptor range is translated to the real heap's, as device slots 17 to 24 do. + handle = translate_cpu_handle(self, D3D12_CPU_DESCRIPTOR_HANDLE{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): @@ -1781,6 +2333,97 @@ 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 one slot 25 answers for the same description +// (lease_size), the figure the title budgets with. +// 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, @@ -1805,8 +2448,10 @@ 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; } // Device slot 133 is the console's CreatePlacedResourceX: (va, desc, state, clear, riid, out), measured on the retail @@ -1932,13 +2577,81 @@ HRESULT proxy_create_committed_resource3_x(DeviceProxy* self, std::uint64_t heap const D3D12_RESOURCE_DESC1*, std::uint32_t, const D3D12_CLEAR_VALUE*, ID3D12ProtectedResourceSession*, std::uint32_t, const DXGI_FORMAT*, const IID*, void**); - const auto create = reinterpret_cast(self->real_vtable[kPcCreateCommittedResource3]); - return create(self->real, 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); + // 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; +} + +// The Xbox routes at their configured indices. Returns false when `slot` is none of them. Built-in handlers (slot 74) ask +// too, because an override that moves a route onto their slot must win over the built-in 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. Only for the title's calls (set_console_caller, as +// slot 61): a host caller of ID3D12Device9::ShaderCacheControl through the proxy gets the PC method. +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); } template @@ -1979,6 +2692,20 @@ 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) { + 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 + note_slot(Slot); + if (is_console_caller(_ReturnAddress())) return proxy_slot74(a1, a2, a3); + // A host caller: the PC slot 74 (ID3D12Device9::ShaderCacheControl), forwarded like any other PC method, as + // slot 61 does. With no classifier installed every caller is a host one. + if (Slot >= self->slot_count) return hr_to_u64(refuse_beyond_device(Slot, self->slot_count)); + 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]); + return fn(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); } else if constexpr (Slot == 75) { return hr_to_u64(proxy_create_command_queue1(self, a1, a2, reinterpret_cast(a3), reinterpret_cast(a4))); @@ -1986,10 +2713,69 @@ 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) { + if (is_console_caller(_ReturnAddress())) { + proxy_create_sampler_x(self, reinterpret_cast(a1), a2); + return 0; + } + // A host caller: the PC slot 61 (ID3D12Device5::CreateMetaCommand), forwarded like any other PC method. + note_slot(Slot); + if (Slot >= self->slot_count) return hr_to_u64(refuse_beyond_device(Slot, self->slot_count)); + 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]); + return fn(self->real, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14); } else if constexpr (Slot == 67) { return hr_to_u64(proxy_create_compute_pipeline_from_native_code( self, reinterpret_cast(a1), reinterpret_cast(a2), @@ -2025,30 +2811,8 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 // 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_xbox(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 @@ -2093,29 +2857,98 @@ 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)}; - return {reinterpret_cast(a1), reinterpret_cast(a0)}; // C form: return buffer, this + 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); - *static_cast(call.ret) = call.self->real->GetResourceAllocationInfo( - static_cast(visible_mask), static_cast(count), descs); + 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; + } + descs = clean.get(); + } + const UINT mask = static_cast(visible_mask); + D3D12_RESOURCE_ALLOCATION_INFO info = real->GetResourceAllocationInfo(mask, desc_count, descs); + // The console tile sizes are the title's: a call in the console form gets them. A PC-form caller (the runtime's + // own code and tests, which compare with the PC device) gets the PC device's answer unchanged. + if (call.console_abi) + 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); + void* const returned = reinterpret_cast(self->real_vtable[56])( + self->real, call.ret, static_cast(visible_mask), n, descs, each); + if (each && call.console_abi) { // console sizes for the console form only, as slot 25 + 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; @@ -2229,6 +3062,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; @@ -2251,9 +3103,14 @@ 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 == 25 || slot == 26 || slot == 31 || slot == 32 || slot == 34 || slot == 35 || - slot == 36 || slot == 45 || slot == 46 || slot == 50 || slot == 62 || slot == 67 || + if (slot <= 2 || slot == 8 || slot == 9 || slot == 14 || (slot >= 17 && slot <= 24) || slot == 25 || slot == 26 || slot == 31 || slot == 32 || slot == 34 || slot == 35 || + slot == 36 || slot == 41 || slot == 45 || slot == 46 || slot == 50 || slot == 56 || slot == 61 || slot == 74 || slot == 62 || slot == 67 || slot == 70 || slot == 75 || slot == 76 || slot == 133 || slot == kCreateCommittedResource3X) return true; const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes(); @@ -2290,11 +3147,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 || slot == kQueuePresentX; +} 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); @@ -2358,6 +3232,10 @@ bool heap_slot_overridden(unsigned slot) { return slot <= 2 || slot == 7 || slot == 9 || slot == 10; } +void set_console_caller(ConsoleCaller classify) { + g_console_caller.store(classify, std::memory_order_release); +} + std::uint64_t device_slot_hits(unsigned slot) { start_hit_counts(); return slot < kMaxSlots ? g_hits[slot].load(std::memory_order_relaxed) : 0; diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 7ee8809397..6ae5200341 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -6,6 +6,10 @@ // 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; no call of them by // the executable has been seen yet, so they are forwarded in the PC form. +// 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 @@ -15,6 +19,8 @@ // and a GPU address, with no resource (retail boot chain stop 14). The PC slot 70 is CreatePlacedResource1. // The words are not measured, so the destination gets the PC null view (PC 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 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 @@ -50,11 +56,12 @@ // // 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 -// 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 +// in PC order. Queue slot 35 is the console ExecuteCommandLists(count, lists) variant and forwards to PC slot 10; +// every other slot past the public chain, 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 +// reserved, never-committed region, and the fault is logged with the slot. PresentX, SuspendX and ResumeX slots past +// the public chain remain refused until measured and implemented, 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 @@ -66,6 +73,11 @@ #include #include +#include + +namespace leonida { +class FrameTokenSource; +} namespace rt::d3d12_xs { @@ -99,6 +111,20 @@ 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); @@ -132,14 +158,23 @@ using ConsoleDescriptorHeapHandler = HRESULT (*)(ID3D12Device* real, const D3D12 REFIID riid, void** out); void set_console_descriptor_heap_handler(ConsoleDescriptorHeapHandler handler); +std::shared_ptr device_frame_tokens(const void* device); + // True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue -// proxies), 9 (allocator proxies), 14, 26 (the console's struct-return form), +// 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 +// 78/79/80 (the Xbox slots above, at their configured indices), 62, 67, 70, 74, 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. bool device_slot_overridden(unsigned slot); +// Whether a return address is in an image the guest loader mapped, i.e. the call comes from the title. Device slot 61 +// is CreateSamplerX for such a caller and the PC ID3D12Device5::CreateMetaCommand for any other; with no check +// installed every caller is a host one. D3D12XboxCreateDevice installs rt::shims::mapped_image_base. +using ConsoleCaller = bool (*)(std::uint64_t address); +void set_console_caller(ConsoleCaller classify); + // Queue and fence proxies created by device slots 8/75 and 36. The real_* accessors return the wrapped object // (no reference added), or null when the pointer is not such a proxy. bool is_queue_proxy(const void* queue); @@ -151,6 +186,9 @@ unsigned queue_proxy_slot_count(const void* queue); unsigned fence_proxy_slot_count(const void* fence); unsigned queue_proxy_table_size(); unsigned fence_proxy_table_size(); +// True for queue slots handled by the proxy instead of forwarded verbatim past IUnknown: 0-2 (IUnknown), +// 7 (GetDevice), 14/15 (Signal/Wait unwrap fences), and 35 (Xbox ExecuteCommandLists variant -> PC slot 10). +bool queue_slot_overridden(unsigned slot); // Live references on a queue, fence or allocator proxy (0 for anything else). Test helper. unsigned long command_object_proxy_ref_count(const void* object); // Per-slot call counters and first-call flags, shared by all queue proxies and all fence proxies. @@ -165,10 +203,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. @@ -180,6 +219,9 @@ bool is_allocator_proxy(const void* allocator); 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(); @@ -202,6 +244,7 @@ inline constexpr unsigned console_to_pc_list_slot(unsigned slot) { if (slot == 60) return 58; // EndEvent (no console SetMarker/BeginEvent) if (slot == 61) return 59; // ExecuteIndirect (Package) if (slot == 85) return 16; // CopyTextureRegionX -> CopyTextureRegion + if (slot == 139) return 10; // Reset(allocator, pso), as the retail title calls it (measured, Pipodi) if (slot == 146) return 80; // D3D12_BARRIER_GROUP (Package; PC GCL7) return kListNotForwarded; } diff --git a/runtime/shims/registry.cpp b/runtime/shims/registry.cpp index 6ec36e31cc..c0d826e311 100644 --- a/runtime/shims/registry.cpp +++ b/runtime/shims/registry.cpp @@ -390,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; @@ -401,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(); @@ -483,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/xbox_present.cpp b/runtime/shims/xbox_present.cpp index dd5f810cf7..f41f2c4680 100644 --- a/runtime/shims/xbox_present.cpp +++ b/runtime/shims/xbox_present.cpp @@ -28,10 +28,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/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/pe_loader.cpp b/runtime/src/pe_loader.cpp index c29a288a91..cc4ae88aab 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -1094,6 +1094,7 @@ 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_) { @@ -1498,6 +1499,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; } 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/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/device_proxy_test.cpp b/runtime/test/device_proxy_test.cpp index b3b3f0fc3e..933674952f 100644 --- a/runtime/test/device_proxy_test.cpp +++ b/runtime/test/device_proxy_test.cpp @@ -23,8 +23,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 { @@ -225,7 +227,11 @@ int main(int argc, char** argv) { 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); - const D3D12_RESOURCE_ALLOCATION_INFO want = real->GetResourceAllocationInfo(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"); @@ -428,6 +434,10 @@ 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"); @@ -577,6 +587,71 @@ 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__"); + rt::shims::remove_xmem_allocation_hooks(&title_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/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/queue_proxy_test.cpp b/runtime/test/queue_proxy_test.cpp index 3f46567f85..674a8cf2ed 100644 --- a/runtime/test/queue_proxy_test.cpp +++ b/runtime/test/queue_proxy_test.cpp @@ -257,7 +257,9 @@ int check_slots(const Backend& b) { } } - // 10: ExecuteCommandLists passes the (real, not wrapped) command lists through. + // 10 and console slot 35: ExecuteCommandLists passes the (real, not wrapped) command lists through. + EXPECT(xs::queue_slot_overridden(35) && xs::queue_slot_overridden(14) && xs::queue_slot_overridden(15)); + EXPECT(!xs::queue_slot_overridden(10) && !xs::queue_slot_overridden(34)); { Ref allocator; EXPECT(SUCCEEDED(device->CreateCommandAllocator(D3D12_COMMAND_LIST_TYPE_DIRECT, @@ -272,6 +274,17 @@ int check_slots(const Backend& b) { EXPECT(qhits(10) == before + 1); EXPECT(SUCCEEDED(queue->Signal(fence.p, 6))); if (wait_for(label, fence.p, 6)) return 1; + const std::uint64_t before35 = qhits(35); + EXPECT(raw_call(queue.p, 35, 1, reinterpret_cast(lists)) == 0); + EXPECT(qhits(35) == before35 + 1 && xs::queue_slot_first_call_seen(35)); + // Console slot 32, PresentX. This test's build of the proxy has no presenter (the wiring is in gta6rt's, + // LEONIDA_VULKAN_DEVICE), so the slot answers S_OK and reaches no PC slot; it is counted like any other. + EXPECT(xs::queue_slot_overridden(32)); + const std::uint64_t before32 = qhits(32); + EXPECT(static_cast(raw_call(queue.p, 32, 0, 0, 0)) == static_cast(S_OK)); + EXPECT(qhits(32) == before32 + 1); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 7))); + if (wait_for(label, fence.p, 7)) return 1; if (b.vulkan) { // The layer's own helpers find their queue behind the proxy. EXPECT(rt::d3d12::last_execute_result(queue.p) == leonida::ReplayResult::success); @@ -293,17 +306,17 @@ int check_slots(const Backend& b) { // 14/15: Signal and Wait take fence proxies; the real queue gets the real fences. before = qhits(14); - EXPECT(SUCCEEDED(queue->Signal(fence.p, 7))); + EXPECT(SUCCEEDED(queue->Signal(fence.p, 8))); EXPECT(qhits(14) == before + 1); - if (wait_for(label, fence.p, 7)) return 1; + if (wait_for(label, fence.p, 8)) return 1; before = qhits(15); - EXPECT(SUCCEEDED(queue->Wait(fence.p, 8))); // the queue waits until the CPU signals 8 + EXPECT(SUCCEEDED(queue->Wait(fence.p, 9))); // the queue waits until the CPU signals 9 EXPECT(qhits(15) == before + 1); EXPECT(SUCCEEDED(queue->Signal(second.p, 1))); Sleep(50); EXPECT(second->GetCompletedValue() == 0); // still held by the Wait before = fhits(10); - EXPECT(SUCCEEDED(fence->Signal(8))); // fence 10, from the CPU + EXPECT(SUCCEEDED(fence->Signal(9))); // fence 10, from the CPU EXPECT(fhits(10) == before + 1); if (wait_for(label, second.p, 1)) return 1; @@ -359,12 +372,12 @@ int check_slots(const Backend& b) { EXPECT(fhits(7) == before + 1); } before = fhits(8); - EXPECT(fence->GetCompletedValue() == 8); + EXPECT(fence->GetCompletedValue() == 9); EXPECT(fhits(8) == before + 1); { Event done; before = fhits(9); - EXPECT(SUCCEEDED(fence->SetEventOnCompletion(8, done.h)) && done.set_within(5000)); + EXPECT(SUCCEEDED(fence->SetEventOnCompletion(9, done.h)) && done.set_within(5000)); EXPECT(fhits(9) == before + 1); } if (fence_slots == 12) { @@ -389,8 +402,9 @@ 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 refused tail: every unmodelled slot from the end of the public chain to the end of the table. for (unsigned slot = 19; slot < xs::queue_proxy_table_size(); ++slot) { + if (xs::queue_slot_overridden(slot)) continue; before = qhits(slot); EXPECT(as_hr(call_slot(queue.p, slot)) == E_NOTIMPL); EXPECT(qhits(slot) == before + 1 && xs::queue_slot_first_call_seen(slot)); @@ -1460,18 +1474,56 @@ int check_xbox_client(const Backend& b) { EXPECT(same); // the GPU really ran the list the queue proxy submitted } - // Device slot 50: EnqueueMakeResident with the objects and a fence proxy to signal. - EXPECT(SUCCEEDED(as_hr(raw(device, 50, D3D12_RESIDENCY_FLAG_NONE, 4, word(pageables), word(fence.p), 2)))); + // Second copy with fresh bytes, submitted through console ExecuteCommandLists slot 35. + { + std::uint8_t* bytes = nullptr; + EXPECT(SUCCEEDED(upload->Map(0, nullptr, reinterpret_cast(&bytes)))); + for (UINT64 i = 0; i < kBytes; ++i) bytes[i] = static_cast(i * 11 + 5); + upload->Unmap(0, nullptr); + } + EXPECT(SUCCEEDED(allocator->Reset())); + EXPECT(SUCCEEDED(list->Reset(allocator.p, nullptr))); + D3D12_RESOURCE_BARRIER to_dest{}; + to_dest.Type = D3D12_RESOURCE_BARRIER_TYPE_TRANSITION; + to_dest.Transition.pResource = gpu.p; + to_dest.Transition.Subresource = D3D12_RESOURCE_BARRIER_ALL_SUBRESOURCES; + to_dest.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_SOURCE; + to_dest.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_DEST; + list->ResourceBarrier(1, &to_dest); + list->CopyBufferRegion(gpu.p, 0, upload.p, 0, kBytes); + D3D12_RESOURCE_BARRIER to_source = to_dest; + to_source.Transition.StateBefore = D3D12_RESOURCE_STATE_COPY_DEST; + to_source.Transition.StateAfter = D3D12_RESOURCE_STATE_COPY_SOURCE; + list->ResourceBarrier(1, &to_source); + list->CopyBufferRegion(readback.p, 0, gpu.p, 0, kBytes); + EXPECT(SUCCEEDED(list->Close())); + EXPECT(raw(queue.p, 35, 1, word(lists)) == 0); + EXPECT(SUCCEEDED(as_hr(raw(queue.p, 14, word(fence.p), 2)))); EXPECT(SUCCEEDED(as_hr(raw(fence.p, 9, 2, word(done.h)))) && done.set_within(5000)); + EXPECT(raw(fence.p, 8) >= 2); + { + std::uint8_t* bytes = nullptr; + const D3D12_RANGE read_range{0, kBytes}; + EXPECT(SUCCEEDED(readback->Map(0, &read_range, reinterpret_cast(&bytes)))); + bool same = true; + for (UINT64 i = 0; i < kBytes; ++i) same = same && bytes[i] == static_cast(i * 11 + 5); + const D3D12_RANGE nothing{0, 0}; + readback->Unmap(0, ¬hing); + EXPECT(same); // the GPU really ran the list submitted via queue slot 35 + } + + // Device slot 50: EnqueueMakeResident with the objects and a fence proxy to signal. + EXPECT(SUCCEEDED(as_hr(raw(device, 50, D3D12_RESIDENCY_FLAG_NONE, 4, word(pageables), word(fence.p), 3)))); + EXPECT(SUCCEEDED(as_hr(raw(fence.p, 9, 3, word(done.h)))) && done.set_within(5000)); // Queue slot 15 holds the queue until the CPU (fence slot 10) signals; device slot 45 then sees both fences. - EXPECT(SUCCEEDED(as_hr(raw(queue.p, 15, word(fence.p), 3)))); + EXPECT(SUCCEEDED(as_hr(raw(queue.p, 15, word(fence.p), 4)))); EXPECT(SUCCEEDED(as_hr(raw(queue.p, 14, word(second.p), 1)))); Sleep(50); EXPECT(raw(second.p, 8) == 0); - EXPECT(SUCCEEDED(as_hr(raw(fence.p, 10, 3)))); + EXPECT(SUCCEEDED(as_hr(raw(fence.p, 10, 4)))); ID3D12Fence* both[] = {fence.p, second.p}; - const UINT64 values[] = {3, 1}; + const UINT64 values[] = {4, 1}; EXPECT(SUCCEEDED(as_hr(raw(device, 45, word(both), word(values), 2, D3D12_MULTIPLE_FENCE_WAIT_FLAG_ALL, word(done.h)))) && done.set_within(5000)); diff --git a/runtime/test/xbox_present_test.cpp b/runtime/test/xbox_present_test.cpp index 1526f87a7a..adbb75e6a5 100644 --- a/runtime/test/xbox_present_test.cpp +++ b/runtime/test/xbox_present_test.cpp @@ -375,8 +375,10 @@ int main() { 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/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 224030247c..3f447a2236 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -16,6 +16,8 @@ #include #include +#include + #include #include @@ -77,7 +79,9 @@ 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 UINT64 kAllocationMarker = 0x2525252500000000ull; // in the SizeInBytes a mock device's slot 25 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}}; @@ -96,6 +100,7 @@ struct Mock { std::uint64_t args[kMockSlots][5]; 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) + IUnknown* held; // ID3D12Object::SetPrivateDataInterface (slot 5): one reference, until destroyed }; Mock g_pool[256]; @@ -198,6 +203,58 @@ 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]; } +// GetResourceAllocationInfo as a PC driver without console tile padding answers it. A buffer is its width, a texture +// width x height x slices x element bytes (2 for B5G5R5A1, 4 for RGBA8, 8 for RGBA16F, 16 for RGBA32F; mips are not +// counted, and one resource is at most 4 GiB, the way a driver caps an allocation), each rounded up to the +// resource's alignment: 64 KiB, or 4 MiB with more than one sample. A texture with no width is refused. Resources are +// laid out one after another, each at its own alignment, and the total is rounded up to the largest alignment, as the +// Vulkan layer's place() does. The struct is written to the hidden return pointer (RDX of a C++ method call), which +// comes back in RAX. `each` (slot 56) gets every resource's offset, alignment and size. +std::uint64_t mock_align(std::uint64_t value, std::uint64_t to) { + return value > UINT64_MAX - (to - 1) ? UINT64_MAX / to * to : (value + to - 1) / to * to; +} + +D3D12_RESOURCE_ALLOCATION_INFO mock_one_allocation(const D3D12_RESOURCE_DESC& d) { + if (d.Width == 0) return {UINT64_MAX, 65536}; + if (d.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER) return {mock_align(d.Width, 65536), 65536}; + std::uint64_t element = 4; + if (d.Format == DXGI_FORMAT_B5G5R5A1_UNORM) element = 2; + if (d.Format == DXGI_FORMAT_R16G16B16A16_FLOAT) element = 8; + if (d.Format == DXGI_FORMAT_R32G32B32A32_FLOAT) element = 16; + const std::uint64_t samples = d.SampleDesc.Count ? d.SampleDesc.Count : 1; + const std::uint64_t alignment = samples > 1 ? 4194304 : 65536; + const std::uint64_t bytes = std::min( + d.Width * d.Height * d.DepthOrArraySize * element * samples, std::uint64_t{4} << 30); + return {mock_align(bytes, alignment), alignment}; +} + +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 mock_allocation_info(std::uint64_t ret, std::uint64_t count, std::uint64_t descs_word, + D3D12_RESOURCE_ALLOCATION_INFO1* each = nullptr) { + 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]; + } + D3D12_RESOURCE_ALLOCATION_INFO total{0, 1}; + bool refused = false; + for (std::uint32_t i = 0; descs && i < static_cast(count); ++i) { + const D3D12_RESOURCE_ALLOCATION_INFO one = mock_one_allocation(descs[i]); + refused = refused || one.SizeInBytes == UINT64_MAX; + const std::uint64_t offset = mock_align(total.SizeInBytes, one.Alignment); + if (each) each[i] = {offset, one.Alignment, one.SizeInBytes}; + total.SizeInBytes = one.SizeInBytes > UINT64_MAX - offset ? UINT64_MAX : offset + one.SizeInBytes; + total.Alignment = std::max(total.Alignment, one.Alignment); + } + auto* out = reinterpret_cast(ret); + *out = {refused ? UINT64_MAX : mock_align(total.SizeInBytes, total.Alignment), total.Alignment}; + return ret; +} + // `words` are the call's first five words (a1..a5), 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]; @@ -207,22 +264,23 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { 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 + 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 56: // GetResourceAllocationInfo1: (return buffer, mask, count, descs, per-description array) + return mock_allocation_info(a1, a3, a4, reinterpret_cast(words[4])); 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 25: { // GetResourceAllocationInfo, the PC method: (return buffer, visible mask, count, descs) - auto* out = reinterpret_cast(a1); - if (!out) break; - out->SizeInBytes = kAllocationMarker + a3; // the count, so the test sees the arguments arrive - out->Alignment = static_cast(a2); // the visible mask - return a1; - } case 26: { // GetCustomHeapProperties, the PC method: (return buffer, node mask, heap type) auto* out = reinterpret_cast(a1); if (!out) break; @@ -232,6 +290,16 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { 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) default: break; } @@ -240,6 +308,15 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { 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::command_list && slot == 46) copy_array(m, slot, a2, a1); // OMSetRenderTargets(count, handles) + 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; + } return S_OK; } @@ -252,7 +329,20 @@ std::uint64_t WINAPI mock_slot(Mock* self, std::uint64_t a1, std::uint64_t a2, s } 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: @@ -319,11 +409,23 @@ void fill_mock_vtable(void** vtable, std::index_sequence) { ((vtable[I] = reinterpret_cast(&mock_slot(I)>)), ...); } +// PC ID3D12Device::CreateCommittedResource(heap, flags, desc, state, clear, riid, out) takes seven words after `this`, +// so a device answers it from its own entry; other kinds keep the generic path for slot 27. +HRESULT WINAPI mock_create_committed_resource(Mock* self, std::uint64_t heap, std::uint64_t flags, std::uint64_t desc, + std::uint64_t state, std::uint64_t clear, const IID* riid, void** out) { + ++self->calls[27]; + const std::uint64_t words[] = {heap, flags, desc, state, clear}; + std::memcpy(self->args[27], words, sizeof(words)); + if (self->kind != Kind::device) return mock_call(self, 27, words); + return mock_create(self, Kind::resource, reinterpret_cast(riid), reinterpret_cast(out)); +} + void** mock_vtable() { static void* table[kMockSlots]; 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 @@ -834,9 +936,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); @@ -896,7 +1010,9 @@ int check_allocators() { 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) ---- // // 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 @@ -964,14 +1080,67 @@ 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); - 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)); + // 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 is CreateSamplerX(desc, dest) for the title and the PC CreateMetaCommand for a host caller. With no + // console-caller check installed (a host program like this one), the call is the PC slot 61. + 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] == 1 && mock->calls[22] == 0 && xs::device_slot_hits(61) == 1); + // A caller the check calls the title's (here every one): the PC CreateSampler (slot 22) gets the same two words, + // not the PC slot 61. A null description is skipped without reaching the device. + xs::set_console_caller([](std::uint64_t) { return true; }); + raw(device, 61, word(&sampler), sampler_handle); + EXPECT(mock->calls[61] == 1 && mock->calls[22] == 1 && xs::device_slot_hits(61) == 2); + EXPECT(mock->args[22][0] == word(&sampler) && mock->args[22][1] == sampler_handle); + raw(device, 61, 0, sampler_handle); + EXPECT(mock->calls[61] == 1 && mock->calls[22] == 1 && xs::device_slot_hits(61) == 3); + // A caller outside the title's images is a host one again. + xs::set_console_caller([](std::uint64_t) { return false; }); + raw(device, 61, word(&sampler), sampler_handle); + EXPECT(mock->calls[61] == 2 && mock->calls[22] == 1); + xs::set_console_caller(nullptr); + + 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(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); + 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; slot 41 creates argument type 105 as DISPATCH\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); @@ -979,10 +1148,62 @@ int check_xbox_slots() { #endif } +// ---- 7b. Xbox queue ExecuteCommandLists variant (queue slot 35 -> PC slot 10) ---- + +int check_xbox_queue_slots() { + Mock* mock = nullptr; + void* device = make_device(mock, 9, true); + EXPECT(device); + void* queue = make_queue(device); + EXPECT(queue); + Mock* const queue_mock = reinterpret_cast(xs::queue_proxy_real_queue(queue)); + xs::reset_device_proxy_stats(); + + EXPECT(xs::queue_slot_overridden(35) && xs::queue_slot_overridden(14) && xs::queue_slot_overridden(15)); + EXPECT(!xs::queue_slot_overridden(10) && !xs::queue_slot_overridden(34) && !xs::queue_slot_overridden(36)); + + // Real objects, not numbers: the array is read to replace list proxies by their real lists, as slot 10's is. + Mock* const list_a = new_mock(Kind::command_list); + Mock* const list_b = new_mock(Kind::command_list); + void* lists[2] = {list_a, list_b}; + EXPECT(raw(queue, 35, (0xdeadbeefull << 32) | 2ull, word(lists)) == 0); + EXPECT(xs::queue_slot_hits(35) == 1 && xs::queue_slot_first_call_seen(35)); + EXPECT(xs::queue_slot_hits(10) == 0); + EXPECT(queue_mock->calls[35] == 0 && queue_mock->calls[10] == 1); + EXPECT(queue_mock->args[10][0] == 2); + EXPECT(queue_mock->array[10][0] == word(list_a) && queue_mock->array[10][1] == word(list_b)); + EXPECT(lists[0] == list_a && lists[1] == list_b); // the caller's array is not written + + EXPECT(raw(queue, 35, 0, 0) == 0); + EXPECT(xs::queue_slot_hits(35) == 2 && queue_mock->calls[35] == 0 && queue_mock->calls[10] == 2); + EXPECT(queue_mock->args[10][0] == 0 && queue_mock->args[10][1] == 0); + + // Queue slot 18. The title's call (one pointer to 8 bytes) is the frequency getter, PC slot 16, and never the + // PC slot 18 (GetDesc), which would write a 16-byte description through that pointer. A host caller, under a + // classifier and with none installed, keeps the PC slot 18. + std::uint64_t frequency[3] = {0xA5A5A5A5A5A5A5A5ull, 0xA5A5A5A5A5A5A5A5ull, 0xA5A5A5A5A5A5A5A5ull}; + xs::set_console_caller([](std::uint64_t) { return true; }); + raw(queue, 18, word(&frequency[1])); + EXPECT(queue_mock->calls[16] == 1 && queue_mock->calls[18] == 0 && queue_mock->args[16][0] == word(&frequency[1])); + EXPECT(frequency[0] == 0xA5A5A5A5A5A5A5A5ull && frequency[2] == 0xA5A5A5A5A5A5A5A5ull); + xs::set_console_caller([](std::uint64_t) { return false; }); + D3D12_COMMAND_QUEUE_DESC host_desc{}; + raw(queue, 18, word(&host_desc)); + EXPECT(queue_mock->calls[16] == 1 && queue_mock->calls[18] == 1 && queue_mock->args[18][0] == word(&host_desc)); + xs::set_console_caller(nullptr); + raw(queue, 18, word(&host_desc)); + EXPECT(queue_mock->calls[16] == 1 && queue_mock->calls[18] == 2); + + EXPECT(release(queue) == 0 && release(device) == 0 && mock->refs == 0); + std::printf("%s: queue slot 35 routes ExecuteCommandLists(count, lists) to PC slot 10 with UINT count masking\n", + g_label); + return 0; +} + // ---- 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"; +int run_env_slots(bool valid, bool on_slot74 = false) { + const char* frame_interval = on_slot74 ? "74" : valid ? "96" : "2"; const char* schedule_event = valid ? "97" : "2"; const char* wait_event = valid ? "98" : "2"; const char* queue_x = valid ? "99" : "2"; @@ -998,7 +1219,12 @@ int run_env_slots(bool valid) { EXPECT(device); xs::reset_device_proxy_stats(); std::uint64_t token = 0; - if (valid) { + if (on_slot74) { + // SetFrameIntervalX moved onto 74, which also has a built-in handler: the override wins, so (output, interval, + // latency, flags) is a frame-interval call that reaches no PC slot, not the stand-in that ignores its words. + EXPECT(hr_of(raw(device, 74, 0, 16667, 1, 0)) == S_OK && mock->calls[74] == 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 (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); @@ -1084,7 +1310,14 @@ int check_resource_allocation_info() { void* device = make_device(mock, 0, true); EXPECT(device && xs::device_slot_overridden(25)); void* const* vtable = *reinterpret_cast(device); - const D3D12_RESOURCE_DESC descs[2] = {}; + D3D12_RESOURCE_DESC descs[2] = {}; // two one-byte buffers: the mock sizes each as one 64 KiB unit + for (D3D12_RESOURCE_DESC& d : descs) { + d.Dimension = D3D12_RESOURCE_DIMENSION_BUFFER; + d.Width = 1; + d.Height = d.DepthOrArraySize = d.MipLevels = 1; + d.SampleDesc.Count = 1; + d.Layout = D3D12_TEXTURE_LAYOUT_ROW_MAJOR; + } // The console form: the buffer for the struct in RCX, the device in RDX, then the mask, the count and the // descriptions. The buffer sits inside a pattern that must stay. @@ -1099,8 +1332,8 @@ int check_resource_allocation_info() { reinterpret_cast(vtable[25])(&padded.value, device, 1, 2, word(descs)); EXPECT(returned == word(&padded.value)); // The PC method got (a return buffer, mask, count, descriptions) once, on the device behind the proxy. - EXPECT(mock->calls[25] == 1 && mock->args[25][1] == 1 && mock->args[25][2] == 2 && mock->args[25][3] == word(descs)); - EXPECT(padded.value.SizeInBytes == kAllocationMarker + 2 && padded.value.Alignment == 1); + EXPECT(mock->calls[25] == 1 && mock->args[25][1] == 1 && mock->args[25][2] == 2); + EXPECT(padded.value.SizeInBytes == 2 * 65536 && padded.value.Alignment == 65536); for (const std::uint8_t byte : padded.before) EXPECT(byte == 0xA5); for (const std::uint8_t byte : padded.after) EXPECT(byte == 0xA5); EXPECT(xs::is_device_proxy(device) && word(xs::device_proxy_real_device(device)) == word(mock)); @@ -1108,8 +1341,8 @@ int check_resource_allocation_info() { // A PC C++ caller: the proxy in RCX and its buffer in RDX. D3D12_RESOURCE_ALLOCATION_INFO pc{}; EXPECT(raw(device, 25, word(&pc), 1, 1, word(descs)) == word(&pc)); - EXPECT(mock->calls[25] == 2 && mock->args[25][2] == 1 && mock->args[25][3] == word(descs)); - EXPECT(pc.SizeInBytes == kAllocationMarker + 1 && pc.Alignment == 1); + EXPECT(mock->calls[25] == 2 && mock->args[25][2] == 1); + EXPECT(pc.SizeInBytes == 65536 && pc.Alignment == 65536); EXPECT(release(device) == 0 && mock->refs == 0); std::printf("%s: device slot 25 with the buffer in RCX and the device in RDX reaches the PC method and writes " @@ -1143,6 +1376,309 @@ int check_slot70() { 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]}; + // The title's call (a caller the classifier takes for a guest image): the stand-in. + xs::set_console_caller([](std::uint64_t) { return true; }); + 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); + // A host caller, under a classifier and with none installed: the PC slot 74 (ShaderCacheControl) with the + // same words where the PC device has it, and the refusal past its table where it does not (found on Windows + // in the review of this change: the stand-in used to take a host's ShaderCacheControl too). + for (const bool installed : {true, false}) { + if (installed) + xs::set_console_caller([](std::uint64_t) { return false; }); + else + xs::set_console_caller(nullptr); + const std::uint64_t before = mock->calls[74]; + const HRESULT hr = hr_of(raw(device, 74, 0x1, 0x2)); + if (level >= 9) { + EXPECT(hr == S_OK && mock->calls[74] == before + 1); + EXPECT(mock->args[74][0] == 0x1 && mock->args[74][1] == 0x2); + } else { + EXPECT(hr == E_NOTIMPL && mock->calls[74] == before); + } + } + xs::set_console_caller(nullptr); + EXPECT(release(device) == 0 && mock->refs == 0); + } + return 0; +} + +// ---- 7. 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) is not the title's call: it gets the PC device's own size, 127 + // units of 64 KiB for the mock, so code that compares the proxy with the PC device still agrees. + D3D12_RESOURCE_ALLOCATION_INFO pc{}; + EXPECT(raw(device, 25, word(&pc), 0, 1, word(&hd)) == word(&pc)); + EXPECT(pc.SizeInBytes == 8323072); + + 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; +} + +// ---- 7b. 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); + + // PC calls must keep their layout and flags so the host can reject an invalid descriptor. + using PcFn = D3D12_RESOURCE_ALLOCATION_INFO*(WINAPI*)(void*, D3D12_RESOURCE_ALLOCATION_INFO*, UINT, UINT, + const D3D12_RESOURCE_DESC*); + const auto get_pc_info = reinterpret_cast(vtable[25]); + D3D12_RESOURCE_DESC pc_buffer = titles[1]; + pc_buffer.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE; + pc_buffer.Flags = static_cast(0x1000); + g_seen_calls = 0; + EXPECT(get_pc_info(device, &info, 0, 1, &pc_buffer) == &info); + EXPECT(g_seen_desc_count == 1 && g_seen_descs[0].Layout == D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE); + EXPECT(g_seen_descs[0].Flags == pc_buffer.Flags); + + // 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. Console render target layout: alignment, per-description offsets, mips, formats, overflow ---- + +int check_render_target_layout() { + Mock* mock = nullptr; + void* device = make_device(mock, 9, true); + EXPECT(device); + void* const* vtable = *reinterpret_cast(device); + // The retail executable's calls: the buffer for the struct in RCX, the device in RDX. + using InfoFn = D3D12_RESOURCE_ALLOCATION_INFO*(WINAPI*)(D3D12_RESOURCE_ALLOCATION_INFO*, void*, UINT, UINT, + const D3D12_RESOURCE_DESC*); + using Info1Fn = D3D12_RESOURCE_ALLOCATION_INFO*(WINAPI*)(D3D12_RESOURCE_ALLOCATION_INFO*, void*, UINT, UINT, + const D3D12_RESOURCE_DESC*, + D3D12_RESOURCE_ALLOCATION_INFO1*); + const auto get_info = reinterpret_cast(vtable[25]); + const auto get_info1 = reinterpret_cast(vtable[56]); + auto ask = [&](const D3D12_RESOURCE_DESC* descs, UINT count) { + D3D12_RESOURCE_ALLOCATION_INFO info{0xDEAD, 0xBEEF}; + if (get_info(&info, device, 0, count, descs) != &info) info = {0, 0}; + return info; + }; + auto ask_one = [&](const D3D12_RESOURCE_DESC& d) { return ask(&d, 1); }; + auto target = [](std::uint64_t w, UINT h, DXGI_FORMAT f, UINT slices, UINT mips) { + D3D12_RESOURCE_DESC d = target_desc(w, h, f, slices); + d.MipLevels = static_cast(mips); + return d; + }; + + // A four-sample 1 x 1 target is 4 MiB at 4 MiB alignment. Next to a 1080p target that grows to 8,847,360 B, the + // two need 4 MiB + 8,847,360 B = 13,041,664 B placed, and the total is a whole number of 4 MiB: 16 MiB, in + // either order. (The PC device says 12 MiB for them; adding the 512 KiB the padding takes would say 12.5 MiB.) + const D3D12_RESOURCE_DESC hd = target_desc(1920, 1080, DXGI_FORMAT_R8G8B8A8_UNORM); + D3D12_RESOURCE_DESC msaa = target_desc(1, 1, DXGI_FORMAT_R8G8B8A8_UNORM); + msaa.SampleDesc.Count = 4; + const D3D12_RESOURCE_DESC msaa_first[] = {msaa, hd}; + const D3D12_RESOURCE_DESC msaa_last[] = {hd, msaa}; + D3D12_RESOURCE_ALLOCATION_INFO info = ask(msaa_first, 2); + EXPECT(info.SizeInBytes == 16777216 && info.Alignment == 4194304); + info = ask(msaa_last, 2); + EXPECT(info.SizeInBytes == 16777216 && info.Alignment == 4194304); + EXPECT(ask(&msaa, 1).SizeInBytes == 4194304); // multisampled targets are left as the PC device sizes them + + // GetResourceAllocationInfo1: the offsets follow the padded sizes, in the console form. + const D3D12_RESOURCE_DESC two[] = {hd, hd}; + D3D12_RESOURCE_ALLOCATION_INFO1 each[2]{}; + D3D12_RESOURCE_ALLOCATION_INFO total{}; + EXPECT(get_info1(&total, device, 0, 2, two, each) == &total); + EXPECT(total.SizeInBytes == 17694720 && total.Alignment == 65536); + EXPECT(each[0].Offset == 0 && each[0].SizeInBytes == 8847360 && each[0].Alignment == 65536); + EXPECT(each[1].Offset == 8847360 && each[1].SizeInBytes == 8847360 && each[1].Alignment == 65536); + D3D12_RESOURCE_ALLOCATION_INFO1 mixed[2]{}; + D3D12_RESOURCE_ALLOCATION_INFO pc{}; + EXPECT(get_info1(&pc, device, 0, 2, msaa_first, mixed) == &pc); + EXPECT(pc.SizeInBytes == 16777216 && pc.Alignment == 4194304); + EXPECT(mixed[0].Offset == 0 && mixed[0].SizeInBytes == 4194304 && mixed[0].Alignment == 4194304); + EXPECT(mixed[1].Offset == 4194304 && mixed[1].SizeInBytes == 8847360 && mixed[1].Alignment == 65536); + // Nothing to pad: the PC device's answer stands, per-description array included. + 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; + const D3D12_RESOURCE_DESC buffers[] = {buffer, buffer}; + D3D12_RESOURCE_ALLOCATION_INFO1 plain[2]{}; + EXPECT(get_info1(&total, device, 0, 2, buffers, plain) == &total); + EXPECT(total.SizeInBytes == 262144 && plain[1].Offset == 131072 && plain[1].SizeInBytes == 131072); + + // Mips: 0 is the full chain. 256 x 128 RGBA8 takes two tiles for mip 0, one for mip 1 (128 x 64 is wider than half a + // tile) and one tail tile for the rest. + EXPECT(ask_one(target(256, 128, DXGI_FORMAT_R8G8B8A8_UNORM, 1, 0)).SizeInBytes == + 4 * 65536ull); + // 128 x 32 with two mips and two slices: mip 0 is a whole tile, mip 1 (64 x 16) is the tail tile, per slice. + EXPECT(ask_one(target(128, 32, DXGI_FORMAT_R8G8B8A8_UNORM, 2, 2)).SizeInBytes == + 4 * 65536ull); + // 257 x 32 with two mips: mip 0 is 3 tiles across, mip 1 is 129 x 16 (an odd extent rounds up): 2 tiles. + EXPECT(ask_one(target(257, 32, DXGI_FORMAT_R8G8B8A8_UNORM, 1, 2)).SizeInBytes == + 5 * 65536ull); + // 2-byte B5G5R5A1 is a 256 x 128 tile: 257 x 64 takes two. + EXPECT(ask_one(target(257, 64, DXGI_FORMAT_B5G5R5A1_UNORM, 1, 1)).SizeInBytes == + 2 * 65536ull); + // 16-byte RGBA32F is a 64 x 64 tile: 65 x 32 takes two. + EXPECT(ask_one(target(65, 32, DXGI_FORMAT_R32G32B32A32_FLOAT, 1, 1)).SizeInBytes == + 2 * 65536ull); + + // Sums saturate where the PC device's do. A 2^26 x 2^26 RGBA32F target of 200 slices is 200 x 2^56 B (the PC mock + // caps it at 4 GiB); two of them are past 2^64. + const D3D12_RESOURCE_DESC huge = target(1ull << 26, 1u << 26, DXGI_FORMAT_R32G32B32A32_FLOAT, 200, 1); + EXPECT(ask(&huge, 1).SizeInBytes == 200ull << 56); + const D3D12_RESOURCE_DESC huge_two[] = {huge, huge}; + info = ask(huge_two, 2); + EXPECT(info.SizeInBytes == 0xFFFFFFFFFFFF0000ull && info.Alignment == 65536); + + EXPECT(release(device) == 0 && mock->refs == 0); + std::printf("%s: render targets are laid out at their own alignments, with per-description offsets, mip chains " + "and saturating sums\n", g_label); + return 0; +} + + // ---- 9. The refused tail and the guard region ---- int check_tail(bool want_guarded) { @@ -1157,14 +1693,256 @@ 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); - for (unsigned slot = 19; slot < xs::queue_proxy_table_size(); ++slot) + for (unsigned slot = 19; slot < xs::queue_proxy_table_size(); ++slot) { + if (xs::queue_slot_overridden(slot)) continue; 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(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); + } + + // The command-list methods that take CPU descriptor handles translate the same range: console slots 50 + // (OMSetRenderTargets), 51 (ClearDepthStencilView), 52 (ClearRenderTargetView), 53 and 54 (the two + // ClearUnorderedAccessView). A handle outside the range is passed as it is, and the caller's arrays are not written. + { + const IID alloc_iid = __uuidof(ID3D12CommandAllocator); + const IID list_iid = __uuidof(ID3D12GraphicsCommandList); + void* allocator = nullptr; + EXPECT(hr_of(raw(device, 9, 0, word(&alloc_iid), word(&allocator))) == S_OK); + struct { + std::uint32_t type, node_mask; + std::uint64_t reserved[2]; + } list_desc{static_cast(D3D12_COMMAND_LIST_TYPE_DIRECT), 0, {0, 0}}; + void* list = nullptr; + EXPECT(hr_of(raw(device, 73, word(&list_desc), word(allocator), 0, word(&list_iid), word(&list))) == S_OK); + EXPECT(xs::is_command_list_proxy(list)); + Mock* const real_list = reinterpret_cast(xs::command_list_proxy_real_list(list)); + + raw(list, 52, kCustomBase + off3, 0x1234, 0, 0); // ClearRenderTargetView + EXPECT(real_list->calls[48] == 1 && real_list->args[48][0] == kMockHeapCpuStart + off3); + raw(list, 52, outside, 0x1234, 0, 0); + EXPECT(real_list->calls[48] == 2 && real_list->args[48][0] == outside); + raw(list, 53, kMockHeapGpuStart + off7, kCustomBase + off7, 0x55, 0x66, 0, 0); // ClearUnorderedAccessViewUint + EXPECT(real_list->args[49][0] == kMockHeapGpuStart + off7 && real_list->args[49][1] == kMockHeapCpuStart + off7); + raw(list, 54, kMockHeapGpuStart + off3, kCustomBase + off3, 0x55, 0x66, 0, 0); // ClearUnorderedAccessViewFloat + EXPECT(real_list->args[50][0] == kMockHeapGpuStart + off3 && real_list->args[50][1] == kMockHeapCpuStart + off3); + + D3D12_CPU_DESCRIPTOR_HANDLE targets[2] = {{kCustomBase + off3}, {outside}}; + D3D12_CPU_DESCRIPTOR_HANDLE depth{kCustomBase + off7}; + raw(list, 50, 2, word(targets), 0, word(&depth)); // OMSetRenderTargets + EXPECT(real_list->calls[46] == 1 && real_list->args[46][0] == 2); + EXPECT(real_list->args[46][1] != word(targets) && real_list->args[46][3] != word(&depth)); + EXPECT(real_list->array[46][0] == kMockHeapCpuStart + off3 && real_list->array[46][1] == outside); + EXPECT(targets[0].ptr == kCustomBase + off3 && targets[1].ptr == outside && depth.ptr == kCustomBase + off7); + + // Slot 51 has a typed thunk, because its depth is a FLOAT in XMM3. The mock's integer prototype cannot see + // the float; what it can see is that the call arrives at PC slot 47 with the translated handle and flags. + using ClearDsvFn = void(WINAPI*)(void*, D3D12_CPU_DESCRIPTOR_HANDLE, D3D12_CLEAR_FLAGS, FLOAT, UINT8, UINT, + const D3D12_RECT*); + void* const* list_vtable = *reinterpret_cast(list); + reinterpret_cast(list_vtable[51])(list, D3D12_CPU_DESCRIPTOR_HANDLE{kCustomBase + off7}, + D3D12_CLEAR_FLAG_DEPTH, 0.5f, 3, 0, nullptr); + EXPECT(real_list->calls[47] == 1 && real_list->args[47][0] == kMockHeapCpuStart + off7 && + static_cast(real_list->args[47][1]) == D3D12_CLEAR_FLAG_DEPTH); + + EXPECT(release(list) == 0); + EXPECT(release(allocator) == 0); + } + + // 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-tiled size slot 25 answers (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 + + // 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; +} + // ---- Guard-region setup failures: this executable's import table, patched before the first proxy table ---- std::atomic g_injected{0}; @@ -1368,6 +2146,7 @@ int check_console_command_list() { 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(139) == 10); // Reset, as the retail title calls it EXPECT(xs::console_to_pc_list_slot(146) == 80); // GCL7 Barrier EXPECT(xs::console_to_pc_list_slot(148) == xs::kListNotForwarded); // AllocateUploadMemory @@ -1473,6 +2252,15 @@ int check_console_command_list() { std::memcpy(&c18, reinterpret_cast(base + 0x18), sizeof(c18)); EXPECT(c18 == expected_limit); + // Console slot 139 is Reset as the retail title calls it: the same PC slot 10, allocator unwrapped, cursor + // re-pinned, and the list's own slot 139 never reached. + std::memcpy(reinterpret_cast(base + 0x18), &zero, sizeof(zero)); + EXPECT(hr_of(raw(list_proxy, 139, word(allocator), 0, 0, 0)) == S_OK); + EXPECT(real_list->calls[10] == 2 && real_list->calls[139] == 0); + EXPECT(real_list->args[10][0] == word(real_allocator) && real_list->args[10][1] == 0); + 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); @@ -1540,13 +2328,21 @@ int main(int argc, char** argv) { 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-74") == 0) return run_env_slots(true, true); return run_fault_mode(argv[1]); } if (argc != 1) return 2; 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_console_command_list() || check_custom_heap_properties() || - check_resource_allocation_info() || check_slot70() || check_committed_resource3_x()) + check_resource_allocation_info() || check_slot70() || check_committed_resource3_x() || + check_descriptor_heap_hooks() || + check_render_target_sizes() || + check_allocation_descriptions_cleaned() || + check_render_target_layout() || + check_committed_resource_leases() || + check_slot74() || + check_xbox_queue_slots()) return 1; std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); return 0;