From 0a714544d64974ad43ad26b6de533bc3b15d2c0d Mon Sep 17 00:00:00 2001 From: Khuraie <83483964+Khuraie@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:42:39 +0800 Subject: [PATCH 01/20] d3d12_xs: honour __XMemAllocationHooks__ for descriptor heaps and translate CPU handles (cherry picked from commit 355201c51e6aba95c582e2df344782b22e97bb31) --- runtime/shims/d3d12_xs.cpp | 11 + runtime/shims/d3d12_xs_device.cpp | 306 +++++++++++++++++++++++++++- runtime/shims/d3d12_xs_device.h | 17 +- runtime/shims/registry.cpp | 39 ++++ runtime/shims/shims.h | 13 ++ runtime/src/pe_loader.cpp | 7 + runtime/test/device_proxy_test.cpp | 65 ++++++ runtime/test/xs_proxy_mock_test.cpp | 140 ++++++++++++- 8 files changed, 586 insertions(+), 12 deletions(-) diff --git a/runtime/shims/d3d12_xs.cpp b/runtime/shims/d3d12_xs.cpp index 8e54c3fd56..67ac93dd0d 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); diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 7f7040fdd9..91e8fcf055 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -38,9 +38,12 @@ #include #include #include -#include +#include #include +#include +#include #include +#include namespace rt::d3d12_xs { namespace { @@ -86,8 +89,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 +214,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)"; @@ -494,11 +582,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 +625,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 +695,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 +709,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; @@ -1676,11 +1786,129 @@ 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; + } + if (alloc_fn && desc && desc->NumDescriptors > 0) { + const UINT inc = self->real->GetDescriptorHandleIncrementSize(desc->Type); + if (inc > 0 && desc->NumDescriptors <= (std::numeric_limits::max)() / inc) { + const SIZE_T byte_size = static_cast(desc->NumDescriptors) * static_cast(inc); + void* backing = alloc_fn(byte_size, kXmemDescriptorHeapAttributes); + if (backing) { + const auto addr = reinterpret_cast(backing); + if (addr <= (std::numeric_limits::max)() - byte_size) { + custom_cpu_start = addr; + custom_byte_size = byte_size; + real_cpu_start = raw_heap_get_cpu_handle(heap, *reinterpret_cast(heap)).ptr; + } else if (free_fn) { + free_fn(backing, kXmemDescriptorHeapAttributes); + } + } + } + } + + 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. @@ -1986,6 +2214,47 @@ 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, @@ -2229,6 +2498,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; @@ -2252,7 +2540,7 @@ ID3D12Device* device_proxy_real_device(const void* device) { } 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 || + 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 == 45 || slot == 46 || slot == 50 || slot == 62 || slot == 67 || slot == 70 || slot == 75 || slot == 76 || slot == 133 || slot == kCreateCommittedResource3X) return true; diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 7ee8809397..8d474dd1d5 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -99,6 +99,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); @@ -133,7 +147,8 @@ using ConsoleDescriptorHeapHandler = HRESULT (*)(ID3D12Device* real, const D3D12 void set_console_descriptor_heap_handler(ConsoleDescriptorHeapHandler handler); // True for slots the proxy handles itself rather than forwarding verbatim: IUnknown (0-2), 8 and 75 (queue -// proxies), 9 (allocator proxies), 14, 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 // measured 9/10 handle conversion is on the heap proxy, and device slot 9 is CreateCommandAllocator, which the proxy 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/src/pe_loader.cpp b/runtime/src/pe_loader.cpp index ff0693a153..bf44cea79d 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/device_proxy_test.cpp b/runtime/test/device_proxy_test.cpp index b3b3f0fc3e..6b91a7a1f8 100644 --- a/runtime/test/device_proxy_test.cpp +++ b/runtime/test/device_proxy_test.cpp @@ -577,6 +577,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/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 224030247c..8991a2114b 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -78,6 +78,9 @@ constexpr std::uint64_t kFenceHandle = 0x1000, kResourceHandle = 0x2000; // the 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}}; @@ -207,7 +210,12 @@ 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 @@ -240,6 +248,14 @@ 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::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; } @@ -1165,6 +1181,125 @@ int check_tail(bool want_guarded) { return 0; } +struct HeapHookState { + void* next_ptr = nullptr; + std::size_t last_alloc_size = 0; + std::uint64_t last_alloc_attr = 0; + int alloc_calls = 0; + void* last_free_ptr = nullptr; + std::uint64_t last_free_attr = 0; + int free_calls = 0; +} g_heap_hook; + +void* mock_heap_alloc(std::size_t byte_size, std::uint64_t attributes) { + ++g_heap_hook.alloc_calls; + g_heap_hook.last_alloc_size = byte_size; + g_heap_hook.last_alloc_attr = attributes; + return g_heap_hook.next_ptr; +} + +void mock_heap_free(void* ptr, std::uint64_t attributes) { + ++g_heap_hook.free_calls; + g_heap_hook.last_free_ptr = ptr; + g_heap_hook.last_free_attr = attributes; +} + +int check_descriptor_heap_hooks() { + g_heap_hook = {}; + xs::set_descriptor_heap_allocator(&mock_heap_alloc, &mock_heap_free); + + Mock* real = new_mock(Kind::device); + real->refs = 1; + real->device_level = 9; + void* device = nullptr; + EXPECT(SUCCEEDED(xs::create_device_proxy(reinterpret_cast(real), __uuidof(ID3D12Device), &device))); + + constexpr SIZE_T kCustomBase = 0x77770000ull; + g_heap_hook.next_ptr = reinterpret_cast(kCustomBase); + D3D12_DESCRIPTOR_HEAP_DESC desc{}; + desc.Type = D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV; + desc.NumDescriptors = 8; + desc.Flags = D3D12_DESCRIPTOR_HEAP_FLAG_SHADER_VISIBLE; + const IID iid_heap = __uuidof(ID3D12DescriptorHeap); + void* heap = nullptr; + EXPECT(SUCCEEDED(hr_of(raw(device, 14, word(&desc), word(&iid_heap), word(&heap))))); + EXPECT(heap != nullptr && xs::is_heap_proxy(heap)); + EXPECT(g_heap_hook.alloc_calls == 1); + EXPECT(g_heap_hook.last_alloc_size == desc.NumDescriptors * kMockDescriptorInc); + EXPECT(g_heap_hook.last_alloc_attr == xs::kXmemDescriptorHeapAttributes); + + // Slot 9 returns the title-supplied base; slot 10 keeps the real GPU start so (gpu - cpu) delta stays exact. + EXPECT(raw(heap, 9) == kCustomBase); + EXPECT(raw(heap, 10) == kMockHeapGpuStart); + + // Public translator and device slots 17-24 remap handles in [kCustomBase, +256) to kMockHeapCpuStart + offset. + const SIZE_T off3 = 3 * kMockDescriptorInc; + const SIZE_T off7 = 7 * kMockDescriptorInc; + const SIZE_T outside = kCustomBase + desc.NumDescriptors * kMockDescriptorInc; + EXPECT(xs::translate_cpu_descriptor_handle(device, D3D12_CPU_DESCRIPTOR_HANDLE{kCustomBase + off3}).ptr == + kMockHeapCpuStart + off3); + EXPECT(xs::translate_cpu_descriptor_handle(device, D3D12_CPU_DESCRIPTOR_HANDLE{outside}).ptr == outside); + + raw(device, 17, 0x11, kCustomBase + off3); // CreateConstantBufferView + EXPECT(real->args[17][1] == kMockHeapCpuStart + off3); + raw(device, 18, 0x22, 0x33, kCustomBase + off3); // CreateShaderResourceView + EXPECT(real->args[18][2] == kMockHeapCpuStart + off3); + raw(device, 19, 0x22, 0x33, 0x44, kCustomBase + off7); // CreateUnorderedAccessView + EXPECT(real->args[19][3] == kMockHeapCpuStart + off7); + raw(device, 20, 0x22, 0x33, kCustomBase + off3); // CreateRenderTargetView + EXPECT(real->args[20][2] == kMockHeapCpuStart + off3); + raw(device, 21, 0x22, 0x33, kCustomBase + off7); // CreateDepthStencilView + EXPECT(real->args[21][2] == kMockHeapCpuStart + off7); + raw(device, 22, 0x55, kCustomBase + off3); // CreateSampler + EXPECT(real->args[22][1] == kMockHeapCpuStart + off3); + raw(device, 24, 1, kCustomBase + off7, kCustomBase + off3, 0); // CopyDescriptorsSimple + EXPECT(real->args[24][1] == kMockHeapCpuStart + off7); + EXPECT(real->args[24][2] == kMockHeapCpuStart + off3); + { + D3D12_CPU_DESCRIPTOR_HANDLE dsts[2] = {{kCustomBase + off3}, {outside}}; + D3D12_CPU_DESCRIPTOR_HANDLE srcs[2] = {{kCustomBase + off7}, {0x99990000ull}}; + UINT sizes[2] = {1, 1}; + static_cast(device)->CopyDescriptors(2, dsts, sizes, 2, srcs, sizes, + D3D12_DESCRIPTOR_HEAP_TYPE_CBV_SRV_UAV); + EXPECT(real->array[23][0] == kMockHeapCpuStart + off3 && real->array[23][1] == outside); + EXPECT(real->array[24][0] == kMockHeapCpuStart + off7 && real->array[24][1] == 0x99990000ull); + } + + // Releasing the heap unregisters the range and invokes the free callback with the same attribute word. + EXPECT(raw(heap, 2) == 0); + EXPECT(g_heap_hook.free_calls == 1); + EXPECT(g_heap_hook.last_free_ptr == reinterpret_cast(kCustomBase)); + EXPECT(g_heap_hook.last_free_attr == xs::kXmemDescriptorHeapAttributes); + EXPECT(xs::translate_cpu_descriptor_handle(device, D3D12_CPU_DESCRIPTOR_HANDLE{kCustomBase + off3}).ptr == + kCustomBase + off3); + + // Null return from the hook falls back cleanly to the PC heap's start and never calls free. + g_heap_hook.next_ptr = nullptr; + void* plain_heap = nullptr; + EXPECT(SUCCEEDED(hr_of(raw(device, 14, word(&desc), word(&iid_heap), word(&plain_heap))))); + EXPECT(plain_heap != nullptr && raw(plain_heap, 9) == kMockHeapCpuStart); + EXPECT(raw(plain_heap, 2) == 0); + EXPECT(g_heap_hook.free_calls == 1); + + // QI failure on heap proxy creation (unsupported IID) frees the hook backing immediately. + g_heap_hook.next_ptr = reinterpret_cast(kCustomBase); + void* bad_heap = nullptr; + EXPECT(hr_of(raw(device, 14, word(&desc), word(&kExtraIid), word(&bad_heap))) == E_NOINTERFACE); + EXPECT(bad_heap == nullptr && g_heap_hook.free_calls == 2); + EXPECT(g_heap_hook.last_free_ptr == reinterpret_cast(kCustomBase)); + + // OOM on HeapProxy allocation frees the hook backing and leaves no dangling range. + g_fail_news = 1; + void* oom_heap = nullptr; + EXPECT(hr_of(raw(device, 14, word(&desc), word(&iid_heap), word(&oom_heap))) == E_OUTOFMEMORY); + EXPECT(oom_heap == nullptr && g_heap_hook.free_calls == 3); + EXPECT(xs::translate_cpu_descriptor_handle(device, D3D12_CPU_DESCRIPTOR_HANDLE{kCustomBase}).ptr == kCustomBase); + + EXPECT(raw(device, 2) == 0 && real->refs == 0); + xs::set_descriptor_heap_allocator(nullptr, nullptr); + return 0; +} + // ---- Guard-region setup failures: this executable's import table, patched before the first proxy table ---- std::atomic g_injected{0}; @@ -1546,7 +1681,8 @@ int main(int argc, char** argv) { 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()) return 1; std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); return 0; From 856334399de47b6f6f951a61333425dc3524585b Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 16:52:16 +0100 Subject: [PATCH 02/20] d3d12_xs: device slot 25 pads a render target to whole console tiles (RT-5 stop 17) The retail title asserts when its first full-screen render targets leave more than 2 MiB of a fixed budget unused (docs/retail_boot_chain.md, #6982). The PC size is about width x height x element bytes; the console takes whole RDNA2 SW_64KB tiles. Slot 25 adds the difference per render target description and never lowers a size. Depends on #6973. (cherry picked from commit 88978553998b51e0e43733606fd67bb253c587ab) --- docs/d3d12_vulkan.md | 8 ++ runtime/shims/d3d12_xs_alloc_size.h | 117 +++++++++++++++++++++++ runtime/shims/d3d12_xs_device.cpp | 27 +++++- runtime/test/xs_proxy_mock_test.cpp | 141 +++++++++++++++++++++++++--- 4 files changed, 277 insertions(+), 16 deletions(-) create mode 100644 runtime/shims/d3d12_xs_alloc_size.h diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 3ae29163e5..6f378aebb8 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2247,6 +2247,14 @@ 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 slot 25) 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, each mip rounded up to the RDNA2 SW_64KB_D tile shape + (`runtime/src/gfx10_tiling.h`: 128 x 128 pixels for 4-byte elements, 128 x 64 for 8-byte ones), with the mips that + fit in one tile 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 adds the difference per description to the PC total when the console + size is larger and never lowers a size (`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. - `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. diff --git a/runtime/shims/d3d12_xs_alloc_size.h b/runtime/shims/d3d12_xs_alloc_size.h new file mode 100644 index 0000000000..8caead8d70 --- /dev/null +++ b/runtime/shims/d3d12_xs_alloc_size.h @@ -0,0 +1,117 @@ +// Console allocation sizes for render targets, for the Xbox-ABI device proxy's slot 25 (GetResourceAllocationInfo). +// +// 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. +#pragma once + +#include "../src/gfx10_tiling.h" + +#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: + 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). +// Mips whose extent fits in one tile share the tail tile; every other mip is padded to whole tiles. 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 mips = desc.MipLevels ? desc.MipLevels : 1; + UINT64 slice = 0; + bool tail = false; + for (UINT mip = 0; mip < mips && mip < 32; ++mip) { + const UINT64 width = std::max(desc.Width >> mip, 1); + const UINT64 height = std::max(desc.Height >> 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() && 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; +} + +// What GetResourceAllocationInfo adds to the PC device's answer: for every description with a console size larger than +// the PC device's size for it alone, the difference. pc_size_of(i) is the PC device's size for description i alone. +// A description the PC device refuses (UINT64_MAX) or the rule does not cover adds nothing. +template +UINT64 console_render_target_extra(const D3D12_RESOURCE_DESC* descs, UINT count, PcSizeOf pc_size_of) { + UINT64 extra = 0; + for (UINT i = 0; descs && i < count; ++i) { + const UINT64 console = console_render_target_size(descs[i]); + if (!console) continue; + const UINT64 pc = pc_size_of(i); + if (pc == UINT64_MAX || pc >= console) continue; + extra += console - pc; + } + return extra; +} + +} // namespace rt::d3d12_xs diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 91e8fcf055..b6263491cc 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -25,6 +25,7 @@ // 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 "../src/shader_library.h" // leonida::fspx_payload_from_parts for slot 67 #include @@ -2371,12 +2372,34 @@ StructReturnCall struct_return_call(std::uint64_t a0, std::uint64_t a1) { return {reinterpret_cast(a1), reinterpret_cast(a0)}; // C form: return buffer, this } +// The size the PC device saturates a total at (docs/d3d12_vulkan.md, GetResourceAllocationInfo). +constexpr UINT64 kSizeSaturated = 0xFFFFFFFFFFFF0000ull; + 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; + D3D12_RESOURCE_ALLOCATION_INFO info = + real->GetResourceAllocationInfo(static_cast(visible_mask), static_cast(count), descs); + // A render target takes whole console tiles, which the PC device's size does not (d3d12_xs_alloc_size.h). The + // total grows by what each render target lacks on its own, so the placement of the others stays as the PC lays it. + if (info.SizeInBytes != UINT64_MAX) { + const UINT64 extra = console_render_target_extra(descs, static_cast(count), [&](UINT i) { + return real->GetResourceAllocationInfo(static_cast(visible_mask), 1, &descs[i]).SizeInBytes; + }); + if (extra) { + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, + "[rt] d3d12_xs: slot 25: render target sizes padded to console tiles, +%llu B on " + "%llu B for %u description(s)\n", + static_cast(extra), + static_cast(info.SizeInBytes), static_cast(count)); + info.SizeInBytes = extra > kSizeSaturated - info.SizeInBytes ? kSizeSaturated : info.SizeInBytes + extra; + } + } + *static_cast(call.ret) = info; return call.ret; } diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 8991a2114b..b291e4beda 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -77,7 +77,6 @@ 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; @@ -201,6 +200,27 @@ 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]; } +// The PC device's GetResourceAllocationInfo, as a driver that packs a surface with no tile padding answers it: a buffer +// its width, a texture width x height x slices x element bytes (4 for RGBA8, 8 for RGBA16F), each rounded up to +// 64 KiB, summed over the descriptions; a texture with no width is refused. The struct is written to the hidden return +// pointer (RDX of a C++ method call), which comes back in RAX. +std::uint64_t mock_allocation_info(std::uint64_t ret, std::uint64_t count, std::uint64_t descs_word) { + const auto* descs = reinterpret_cast(descs_word); + std::uint64_t total = 0; + bool refused = false; + for (std::uint32_t i = 0; descs && i < static_cast(count); ++i) { + const D3D12_RESOURCE_DESC& d = descs[i]; + std::uint64_t bytes = d.Width; + if (d.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) + bytes = d.Width * d.Height * d.DepthOrArraySize * (d.Format == DXGI_FORMAT_R16G16B16A16_FLOAT ? 8 : 4); + refused = refused || d.Width == 0; + total += (bytes + 65535) / 65536 * 65536; + } + auto* out = reinterpret_cast(ret); + *out = {refused ? UINT64_MAX : total, 65536}; + 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]; @@ -222,15 +242,9 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { if (a1 == kFenceHandle) return static_cast(mock_create(m, Kind::fence, a2, a3)); if (a1 == kResourceHandle) return static_cast(mock_create(m, Kind::resource, a2, a3)); return static_cast(E_INVALIDARG); + case 25: return mock_allocation_info(a1, a3, a4); // GetResourceAllocationInfo (mask a2 is unused) case 34: case 35: case 46: copy_array(m, slot, a2, a1); break; // (count, objects, ...) case 45: copy_array(m, slot, a1, a3); break; // (fences, values, count, ...) - case 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; @@ -1100,7 +1114,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. @@ -1115,8 +1136,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)); @@ -1124,8 +1145,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 " @@ -1159,6 +1180,97 @@ int check_slot70() { 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) answers the same sizes. + D3D12_RESOURCE_ALLOCATION_INFO pc{}; + EXPECT(raw(device, 25, word(&pc), 0, 1, word(&hd)) == word(&pc)); + EXPECT(pc.SizeInBytes == 8847360); + + EXPECT(release(device) == 0 && mock->refs == 0); + std::printf("%s: device slot 25 pads render targets to whole console tiles and leaves the other sizes as the PC " + "device gives them\n", g_label); + return 0; +} + // ---- 9. The refused tail and the guard region ---- int check_tail(bool want_guarded) { @@ -1682,7 +1794,8 @@ int main(int argc, char** argv) { 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_descriptor_heap_hooks()) + check_descriptor_heap_hooks() || + check_render_target_sizes()) return 1; std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); return 0; From 584ef36fa82ca00e19a4a03104b1b0d6ce295bd4 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 16:56:52 +0100 Subject: [PATCH 03/20] d3d12_xs: device slot 25 gives the PC device clean resource descriptions (RT-5 stop 16) The title's descriptions carry the Xbox layout word and flag bits above the PC ones. Slot 25 now passes a copy with PC flags and a PC layout; the title's array is not written. Depends on #7078. (cherry picked from commit c7ca0f2d1c3d1aaa1dca7c01740dac076c523154) --- docs/d3d12_vulkan.md | 3 ++ runtime/shims/d3d12_xs_desc_clean.h | 34 ++++++++++++++ runtime/shims/d3d12_xs_device.cpp | 16 ++++++- runtime/test/xs_proxy_mock_test.cpp | 70 ++++++++++++++++++++++++++++- 4 files changed, 121 insertions(+), 2 deletions(-) create mode 100644 runtime/shims/d3d12_xs_desc_clean.h diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 6f378aebb8..b8c519a210 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2255,6 +2255,9 @@ The trace will enumerate them. size is larger and never lowers a size (`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). The proxy gives the PC device a copy with the PC flags only and ROW_MAJOR (buffer) or UNKNOWN (texture); the + title's array is never written (`d3d12_xs_desc_clean.h`, the same cleaning as slot 76; #6982 section 3.7). - `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. diff --git a/runtime/shims/d3d12_xs_desc_clean.h b/runtime/shims/d3d12_xs_desc_clean.h new file mode 100644 index 0000000000..61f49eb8b2 --- /dev/null +++ b/runtime/shims/d3d12_xs_desc_clean.h @@ -0,0 +1,34 @@ +// 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; + +// A copy of the title's description with the PC flags only and a PC layout: ROW_MAJOR for a buffer, UNKNOWN for a +// texture (the layout the PC device picks itself). +inline D3D12_RESOURCE_DESC pc_resource_desc(const D3D12_RESOURCE_DESC& xbox) { + D3D12_RESOURCE_DESC pc = xbox; + pc.Layout = xbox.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 b6263491cc..43cbaf7b13 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -26,6 +26,7 @@ #include "d3d12_xs_device.h" #include "d3d12_trace.h" #include "d3d12_xs_alloc_size.h" +#include "d3d12_xs_desc_clean.h" #include "../src/shader_library.h" // leonida::fspx_payload_from_parts for slot 67 #include @@ -2380,8 +2381,21 @@ void* WINAPI proxy_get_resource_allocation_info(std::uint64_t a0, std::uint64_t note_slot(25); const StructReturnCall call = struct_return_call(a0, a1); ID3D12Device* const real = call.self->real; + // The descriptions are the console's. The PC device gets a copy with PC flags and layout; the title's array is + // read only. A copy that cannot be made answers as an invalid description. + 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) clean[i] = pc_resource_desc(descs[i]); + descs = clean.get(); + } D3D12_RESOURCE_ALLOCATION_INFO info = - real->GetResourceAllocationInfo(static_cast(visible_mask), static_cast(count), descs); + real->GetResourceAllocationInfo(static_cast(visible_mask), desc_count, descs); // A render target takes whole console tiles, which the PC device's size does not (d3d12_xs_alloc_size.h). The // total grows by what each render target lacks on its own, so the placement of the others stays as the PC lays it. if (info.SizeInBytes != UINT64_MAX) { diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index b291e4beda..d0e837ef07 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -204,8 +204,17 @@ void copy_array(Mock* m, unsigned slot, std::uint64_t objects, std::uint64_t cou // its width, a texture width x height x slices x element bytes (4 for RGBA8, 8 for RGBA16F), each rounded up to // 64 KiB, summed over the descriptions; a texture with no width is refused. The struct is written to the hidden return // pointer (RDX of a C++ method call), which comes back in RAX. +D3D12_RESOURCE_DESC g_seen_descs[4]; // the first descriptions the mock device's slot 25 was given +std::uint32_t g_seen_desc_count = 0; +std::uint32_t g_seen_calls = 0; // slot 25 calls since the test cleared it; only the first is recorded + std::uint64_t mock_allocation_info(std::uint64_t ret, std::uint64_t count, std::uint64_t descs_word) { const auto* descs = reinterpret_cast(descs_word); + if (g_seen_calls++ == 0) { + g_seen_desc_count = static_cast(count); + for (std::uint32_t i = 0; descs && i < g_seen_desc_count && i < std::size(g_seen_descs); ++i) + g_seen_descs[i] = descs[i]; + } std::uint64_t total = 0; bool refused = false; for (std::uint32_t i = 0; descs && i < static_cast(count); ++i) { @@ -1271,6 +1280,64 @@ int check_render_target_sizes() { 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); + + // 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; +} + // ---- 9. The refused tail and the guard region ---- int check_tail(bool want_guarded) { @@ -1795,7 +1862,8 @@ int main(int argc, char** argv) { check_custom_heap_properties() || check_resource_allocation_info() || check_slot70() || check_committed_resource3_x() || check_descriptor_heap_hooks() || - check_render_target_sizes()) + check_render_target_sizes() || + check_allocation_descriptions_cleaned()) return 1; std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); return 0; From f1a68eeffbf280b2e2c86f439ebd674da026d82e Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 17:26:57 +0100 Subject: [PATCH 04/20] d3d12_xs: console render target sizes follow each resource's alignment, slot 56 offsets, full mip chains, rounded-up mip extents, B5G5R5A1, saturating sums (cherry picked from commit 359390833f62378a5d1d2c0f9a6cea48fccbcb53) --- docs/d3d12_vulkan.md | 22 ++-- runtime/shims/d3d12_xs_alloc_size.h | 81 +++++++++++---- runtime/shims/d3d12_xs_device.cpp | 73 +++++++++---- runtime/test/xs_proxy_mock_test.cpp | 155 +++++++++++++++++++++++++--- 4 files changed, 266 insertions(+), 65 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index b8c519a210..0e8e947aac 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2247,12 +2247,17 @@ 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 slot 25) 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, each mip rounded up to the RDNA2 SW_64KB_D tile shape - (`runtime/src/gfx10_tiling.h`: 128 x 128 pixels for 4-byte elements, 128 x 64 for 8-byte ones), with the mips that - fit in one tile 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 adds the difference per description to the PC total when the console - size is larger and never lowers a size (`d3d12_xs_alloc_size.h`; `xs_proxy_mock_test`). **Assumption**: the + 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 @@ -2274,8 +2279,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. diff --git a/runtime/shims/d3d12_xs_alloc_size.h b/runtime/shims/d3d12_xs_alloc_size.h index 8caead8d70..3321c4ec88 100644 --- a/runtime/shims/d3d12_xs_alloc_size.h +++ b/runtime/shims/d3d12_xs_alloc_size.h @@ -1,4 +1,4 @@ -// Console allocation sizes for render targets, for the Xbox-ABI device proxy's slot 25 (GetResourceAllocationInfo). +// 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 @@ -10,7 +10,9 @@ // 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. +// 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" @@ -19,6 +21,7 @@ #include #include +#include #include #include @@ -36,6 +39,7 @@ inline std::size_t render_target_element_bytes(DXGI_FORMAT format) { 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: @@ -66,7 +70,9 @@ inline std::size_t render_target_element_bytes(DXGI_FORMAT format) { // 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). -// Mips whose extent fits in one tile share the tail tile; every other mip is padded to whole tiles. Slices add up. +// 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; @@ -74,19 +80,20 @@ inline UINT64 console_render_target_size(const D3D12_RESOURCE_DESC& desc) { 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 mips = desc.MipLevels ? desc.MipLevels : 1; + 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 < 32; ++mip) { - const UINT64 width = std::max(desc.Width >> mip, 1); - const UINT64 height = std::max(desc.Height >> mip, 1); + 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() && height <= surface.tile_height()) { + if (width <= surface.tile_width() / 2 && height <= surface.tile_height()) { tail = true; break; } @@ -98,20 +105,52 @@ inline UINT64 console_render_target_size(const D3D12_RESOURCE_DESC& desc) { return slice * slices; } -// What GetResourceAllocationInfo adds to the PC device's answer: for every description with a console size larger than -// the PC device's size for it alone, the difference. pc_size_of(i) is the PC device's size for description i alone. -// A description the PC device refuses (UINT64_MAX) or the rule does not cover adds nothing. -template -UINT64 console_render_target_extra(const D3D12_RESOURCE_DESC* descs, UINT count, PcSizeOf pc_size_of) { - UINT64 extra = 0; - for (UINT i = 0; descs && i < count; ++i) { - const UINT64 console = console_render_target_size(descs[i]); - if (!console) continue; - const UINT64 pc = pc_size_of(i); - if (pc == UINT64_MAX || pc >= console) continue; - extra += console - pc; +// 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 extra; + return true; } } // namespace rt::d3d12_xs diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 43cbaf7b13..cd3953fa61 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -33,6 +33,7 @@ #include #include +#include #include #include #include @@ -237,6 +238,7 @@ const char* slot_name(unsigned slot) { 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 62: return "Xbox CreateComputePipelineState"; case 67: return "Xbox DeserializeComputePipelineStateX"; case 70: return "Xbox shader-resource view from raw words"; @@ -2373,8 +2375,24 @@ StructReturnCall struct_return_call(std::uint64_t a0, std::uint64_t a1) { return {reinterpret_cast(a1), reinterpret_cast(a0)}; // C form: return buffer, this } -// The size the PC device saturates a total at (docs/d3d12_vulkan.md, GetResourceAllocationInfo). -constexpr UINT64 kSizeSaturated = 0xFFFFFFFFFFFF0000ull; +// 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) { @@ -2394,34 +2412,45 @@ void* WINAPI proxy_get_resource_allocation_info(std::uint64_t a0, std::uint64_t for (UINT i = 0; i < desc_count; ++i) clean[i] = pc_resource_desc(descs[i]); descs = clean.get(); } - D3D12_RESOURCE_ALLOCATION_INFO info = - real->GetResourceAllocationInfo(static_cast(visible_mask), desc_count, descs); - // A render target takes whole console tiles, which the PC device's size does not (d3d12_xs_alloc_size.h). The - // total grows by what each render target lacks on its own, so the placement of the others stays as the PC lays it. - if (info.SizeInBytes != UINT64_MAX) { - const UINT64 extra = console_render_target_extra(descs, static_cast(count), [&](UINT i) { - return real->GetResourceAllocationInfo(static_cast(visible_mask), 1, &descs[i]).SizeInBytes; - }); - if (extra) { - static std::atomic logged{false}; - if (!logged.exchange(true, std::memory_order_relaxed)) - std::fprintf(stderr, - "[rt] d3d12_xs: slot 25: render target sizes padded to console tiles, +%llu B on " - "%llu B for %u description(s)\n", - static_cast(extra), - static_cast(info.SizeInBytes), static_cast(count)); - info.SizeInBytes = extra > kSizeSaturated - info.SizeInBytes ? kSizeSaturated : info.SizeInBytes + extra; - } - } + const UINT mask = static_cast(visible_mask); + D3D12_RESOURCE_ALLOCATION_INFO info = real->GetResourceAllocationInfo(mask, desc_count, descs); + apply_console_placement(descs, desc_count, info, nullptr, + [&](UINT i) { return real->GetResourceAllocationInfo(mask, 1, &descs[i]); }, 25); *static_cast(call.ret) = info; return call.ret; } +// Slot 56, ID3D12Device4::GetResourceAllocationInfo1: the same answer, and the per-description offsets follow the +// padded sizes, so a title that places its resources at those offsets does not overlap them. The call is forwarded +// as it came; the console layout then replaces the total and the offsets. +void* WINAPI proxy_get_resource_allocation_info1(std::uint64_t a0, std::uint64_t a1, std::uint64_t visible_mask, + std::uint64_t count, const D3D12_RESOURCE_DESC* descs, + D3D12_RESOURCE_ALLOCATION_INFO1* each) { + const StructReturnCall call = struct_return_call(a0, a1); + DeviceProxy* const self = call.self; + note_slot(56); + if (56 >= self->slot_count) { + return reinterpret_cast(hr_to_u64(refuse_beyond_device(56, self->slot_count))); + } + using Fn = void*(WINAPI*)(void*, void*, UINT, UINT, const D3D12_RESOURCE_DESC*, D3D12_RESOURCE_ALLOCATION_INFO1*); + const UINT n = static_cast(count); + void* const returned = reinterpret_cast(self->real_vtable[56])( + self->real, call.ret, static_cast(visible_mask), n, descs, each); + if (each) { + auto& info = *static_cast(call.ret); + apply_console_placement(descs, n, info, each, [&](UINT i) { + return D3D12_RESOURCE_ALLOCATION_INFO{each[i].SizeInBytes, each[i].Alignment}; + }, 56); + } + return returned; +} + void** get_vtable() { static void** vtable = [] { static void* storage[kMaxSlots]; fill_vtable(storage, std::make_index_sequence{}); storage[25] = reinterpret_cast(&proxy_get_resource_allocation_info); + storage[56] = reinterpret_cast(&proxy_get_resource_allocation_info1); return storage; }(); return vtable; @@ -2578,7 +2607,7 @@ ID3D12Device* device_proxy_real_device(const void* device) { bool device_slot_overridden(unsigned slot) { 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 == 45 || slot == 46 || slot == 50 || slot == 62 || slot == 67 || + slot == 36 || slot == 45 || slot == 46 || slot == 50 || slot == 56 || slot == 62 || slot == 67 || slot == 70 || slot == 75 || slot == 76 || slot == 133 || slot == kCreateCommittedResource3X) return true; const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes(); diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index d0e837ef07..6bae19ac75 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 @@ -200,33 +202,55 @@ 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]; } -// The PC device's GetResourceAllocationInfo, as a driver that packs a surface with no tile padding answers it: a buffer -// its width, a texture width x height x slices x element bytes (4 for RGBA8, 8 for RGBA16F), each rounded up to -// 64 KiB, summed over the descriptions; a texture with no width is refused. The struct is written to the hidden return -// pointer (RDX of a C++ method call), which comes back in RAX. +// 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) { +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]; } - std::uint64_t total = 0; + 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_DESC& d = descs[i]; - std::uint64_t bytes = d.Width; - if (d.Dimension != D3D12_RESOURCE_DIMENSION_BUFFER) - bytes = d.Width * d.Height * d.DepthOrArraySize * (d.Format == DXGI_FORMAT_R16G16B16A16_FLOAT ? 8 : 4); - refused = refused || d.Width == 0; - total += (bytes + 65535) / 65536 * 65536; + 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 : total, 65536}; + *out = {refused ? UINT64_MAX : mock_align(total.SizeInBytes, total.Alignment), total.Alignment}; return ret; } @@ -252,6 +276,8 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { 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 26: { // GetCustomHeapProperties, the PC method: (return buffer, node mask, heap type) @@ -1280,6 +1306,106 @@ int check_render_target_sizes() { 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 and the PC 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(raw(device, 56, word(&pc), 0, 2, word(msaa_first), word(mixed)) == word(&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; +} + // ---- 7b. Device slot 25 hands the PC device clean descriptions and leaves the title's array alone ---- @@ -1863,7 +1989,8 @@ int main(int argc, char** argv) { check_resource_allocation_info() || check_slot70() || check_committed_resource3_x() || check_descriptor_heap_hooks() || check_render_target_sizes() || - check_allocation_descriptions_cleaned()) + check_allocation_descriptions_cleaned() || + check_render_target_layout()) return 1; std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); return 0; From 35e687f2ac1eeca764deffc307c6a076c9a44230 Mon Sep 17 00:00:00 2001 From: Jackson <37029272+NinJackson@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:16:28 -0500 Subject: [PATCH 05/20] d3d12_xs: committed resources lease their size through the title's XMem hooks (RT-5 stop 17) On the console a committed resource's memory is allocated with XMemAlloc, so it goes through the title's __XMemAllocationHooks__. The retail title budgets its first full-screen render targets with a per-thread hook that bump-allocates out of a range it reserved and asserts that less than 2 MiB is left; PC resources never allocated through the hooks, so the assert always fired. Slots 76 and 127 now allocate the slot-25 size of each resource through the hooks, held by the resource with SetPrivateDataInterface and freed when it is destroyed. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit ae322dafc560f07f839be457e3ba6b68bcbf83c8) Adapted to main by Mumogg: the lease size is the later form of this series (d61755d4d, a render target's console tile size, else the PC size), since console_render_target_extra is gone after 359390833. --- docs/d3d12_vulkan.md | 7 ++ runtime/shims/d3d12_xs_device.cpp | 135 ++++++++++++++++++++++++++-- runtime/test/xs_proxy_mock_test.cpp | 104 ++++++++++++++++++++- 3 files changed, 235 insertions(+), 11 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 0e8e947aac..b39a558923 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2263,6 +2263,13 @@ The trace will enumerate them. The descriptions the title passes to slot 25 carry console values (layout word `0x101`/`0x1`, flag bits above the PC ones). The proxy gives the PC device a copy with the PC flags only and ROW_MAJOR (buffer) or UNKNOWN (texture); the title's array is never written (`d3d12_xs_desc_clean.h`, the same cleaning as slot 76; #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. diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index cd3953fa61..4662577459 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -2013,6 +2013,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, @@ -2037,8 +2128,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 @@ -2164,13 +2257,37 @@ 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; } template diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 6bae19ac75..45055b888b 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -100,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]; @@ -317,7 +318,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: @@ -384,11 +398,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 @@ -1605,6 +1631,79 @@ int check_descriptor_heap_hooks() { 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}; @@ -1990,7 +2089,8 @@ int main(int argc, char** argv) { check_descriptor_heap_hooks() || check_render_target_sizes() || check_allocation_descriptions_cleaned() || - check_render_target_layout()) + check_render_target_layout() || + check_committed_resource_leases()) return 1; std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); return 0; From 20936e84537a25441aa7d8e84fd7fd7073afba82 Mon Sep 17 00:00:00 2001 From: mrp1no <137657338+mrp1no@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:05:11 +0100 Subject: [PATCH 06/20] d3d12_xs: a console indirect argument of type 105 is created as DISPATCH (slot 41) The retail title creates five one-argument command signatures with no root signature at startup (device slot 41, CreateCommandSignature at its PC position). One has the console argument type 105 and a 12-byte stride, next to a DISPATCH and a DISPATCH_MESH of 12 bytes. The PC layer refuses the unknown type, which is stop 19 of the RT-5 boot measurements. Read statically from the title's call sites (shapes only): the two ExecuteIndirect sites of that signature pass MaxCommandCount 1 and an offset into the same argument buffer as the DISPATCH sites. Right before, they set the same compute state as the DISPATCH path (pipeline, compute root signature, tables, constants, SRV and UAV); they record on a second command list of the title's context. So the argument is taken as a D3D12_DISPATCH_ARGUMENTS. Slot 41 now has its own handler. A description that holds type 105 is copied with that type replaced by DISPATCH (logged once). Any other description is forwarded as the same pointer. What the console does differently for type 105 is left open in docs/d3d12_vulkan.md (section 4.9). xs_proxy_mock_test: a two-argument description (a root constant, then type 105) reaches the PC slot 41 as a copy with DISPATCH, the same stride, count, root signature, IID and output, and the caller's description is untouched; a PC description is passed through unchanged. With main's d3d12_xs_device.cpp the new check fails. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 4c04c0f4e36476a6bbf309e2f0f4d6cfcbe9f045) --- docs/d3d12_vulkan.md | 1 + runtime/shims/d3d12_xs_device.cpp | 49 ++++++++++++++++++++++++++++- runtime/shims/d3d12_xs_device.h | 2 ++ runtime/test/xs_proxy_mock_test.cpp | 40 ++++++++++++++++++++--- 4 files changed, 87 insertions(+), 5 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index b39a558923..379a2724d4 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -3530,6 +3530,7 @@ 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**. | | 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/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 4662577459..9cdb9439d7 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -233,6 +233,7 @@ 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)"; @@ -1931,6 +1932,48 @@ 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. +constexpr D3D12_INDIRECT_ARGUMENT_TYPE kXboxIndirectArgumentDispatch105 = static_cast(105); + +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 = desc->pArgumentDescs[i].Type == 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 (args[i].Type == 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 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): @@ -2380,6 +2423,10 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 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 == 67) { return hr_to_u64(proxy_create_compute_pipeline_from_native_code( self, reinterpret_cast(a1), reinterpret_cast(a2), @@ -2724,7 +2771,7 @@ ID3D12Device* device_proxy_real_device(const void* device) { bool device_slot_overridden(unsigned slot) { 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 == 45 || slot == 46 || slot == 50 || slot == 56 || slot == 62 || slot == 67 || + slot == 36 || slot == 41 || slot == 45 || slot == 46 || slot == 50 || slot == 56 || slot == 62 || slot == 67 || slot == 70 || slot == 75 || slot == 76 || slot == 133 || slot == kCreateCommittedResource3X) return true; const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes(); diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 8d474dd1d5..5841656967 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -6,6 +6,8 @@ // 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 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 diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 45055b888b..36eb07a15b 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -290,6 +290,13 @@ 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) + m->array[41][i + 1] = static_cast(desc->pArgumentDescs[i].Type); + } + break; case 50: copy_array(m, slot, a3, a2); break; // (flags, count, objects, fence, value) default: break; } @@ -987,7 +994,7 @@ 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 @@ -1055,14 +1062,39 @@ 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; + console_args[1].Type = static_cast(105); + 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); + EXPECT(console_args[1].Type == static_cast(105)); // the caller's copy 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); + + EXPECT(xs::device_slot_overridden(41) && 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)); EXPECT(release(allocator) == 0 && real_allocator->refs == 0); EXPECT(release(queue) == 0); EXPECT(release(device) == 0 && mock->refs == 0); std::printf("%s: device slots 48/73/78/79/80 route to a queue, a list and frame-event tokens without reaching " - "the mock's own PC slots\n", g_label); + "the mock's own PC slots; slot 41 creates argument type 105 as DISPATCH\n", g_label); 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); From 58ce13c12d541c32dfbcbb199112d31bf712cb0a Mon Sep 17 00:00:00 2001 From: mrp1no <137657338+mrp1no@users.noreply.github.com> Date: Mon, 23 Nov 2026 17:17:22 +0100 Subject: [PATCH 07/20] d3d12_xs: read the console argument type as its 32 bits (clang-cl) 105 is outside D3D12_INDIRECT_ARGUMENT_TYPE's range [0, 15], so clang-cl rejects a constant expression that casts it to the enum (reported by umnitus on #7163). The handler now reads each argument's Type field as a uint32_t through memcpy and compares it with 105; the test writes and reads the raw value the same way, and the mock records it the same way. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 084c8c60e7e839d0caefaaeccf41a6348b062cf1) --- runtime/shims/d3d12_xs_device.cpp | 15 ++++++++++++--- runtime/test/xs_proxy_mock_test.cpp | 14 ++++++++++---- 2 files changed, 22 insertions(+), 7 deletions(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 9cdb9439d7..ea8bed3ca4 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -1941,7 +1941,15 @@ HRESULT proxy_create_compute_pipeline_state(DeviceProxy* self, const D3D12_COMPU // 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. -constexpr D3D12_INDIRECT_ARGUMENT_TYPE kXboxIndirectArgumentDispatch105 = static_cast(105); +// 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) { @@ -1952,7 +1960,7 @@ HRESULT proxy_create_command_signature(DeviceProxy* self, const D3D12_COMMAND_SI bool console = false; if (desc && desc->pArgumentDescs) for (UINT i = 0; i < desc->NumArgumentDescs && !console; ++i) - console = desc->pArgumentDescs[i].Type == kXboxIndirectArgumentDispatch105; + 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) @@ -1963,7 +1971,8 @@ HRESULT proxy_create_command_signature(DeviceProxy* self, const D3D12_COMMAND_SI } for (UINT i = 0; i < desc->NumArgumentDescs; ++i) { args[i] = desc->pArgumentDescs[i]; - if (args[i].Type == kXboxIndirectArgumentDispatch105) args[i].Type = D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH; + 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)) diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 36eb07a15b..ac2bf2ed7d 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -293,8 +293,11 @@ std::uint64_t mock_call(Mock* m, unsigned slot, const std::uint64_t* words) { 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) - m->array[41][i + 1] = static_cast(desc->pArgumentDescs[i].Type); + 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) @@ -1068,7 +1071,8 @@ int check_xbox_slots() { D3D12_INDIRECT_ARGUMENT_DESC console_args[2]{}; console_args[0].Type = D3D12_INDIRECT_ARGUMENT_TYPE_CONSTANT; console_args[0].Constant.Num32BitValuesToSet = 1; - console_args[1].Type = static_cast(105); + 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; @@ -1079,7 +1083,9 @@ int check_xbox_slots() { 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); - EXPECT(console_args[1].Type == static_cast(105)); // the caller's copy is untouched + 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}; From 3b86f5fb3cfa97d2aa8b500768ac72cad7a4dbfa Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Mon, 23 Nov 2026 17:29:49 +0100 Subject: [PATCH 08/20] d3d12: CreateCommandSignature creates a DISPATCH_MESH signature on a device with mesh shaders The Vulkan layer created signatures for draw, draw-indexed and dispatch only and answered E_NOTIMPL for DISPATCH_MESH, which the PC runtime creates on any mesh-shader tier 1 device. A title that creates such a signature at startup and asserts on the result stopped there. The signature is created when the device has VK_EXT_mesh_shader (MeshShaderTier 1), as a new IndirectKind::dispatch_mesh (the name and value #3777 uses, so the two merge). ExecuteIndirect with it records nothing yet and says so once; #3777 replays it as vkCmdDrawMeshTasksIndirectEXT. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit efc347830b9ccf1461baf9a764ac9e5e911de8f6) --- runtime/shims/d3d12_com.cpp | 22 +++++++++------------- runtime/shims/d3d12_vulkan_device.cpp | 5 +++++ runtime/src/command_list.h | 3 +++ runtime/test/d3d12_mesh_test.cpp | 22 ++++++++++++++++++++++ 4 files changed, 39 insertions(+), 13 deletions(-) diff --git a/runtime/shims/d3d12_com.cpp b/runtime/shims/d3d12_com.cpp index 4f4904e965..55fea20c91 100644 --- a/runtime/shims/d3d12_com.cpp +++ b/runtime/shims/d3d12_com.cpp @@ -834,19 +834,15 @@ class GraphicsCommandList final } else if (count_buffer_offset != 0) { return check(false); } - // The record size is checked for every call: D3D12 rejects a signature whose stride cannot hold a record - // even when no command runs. The argument span is what the signature can walk, max_command_count * stride: - // the host refuses a range that ends past the buffer (`240` with stride `20` in a `256`-byte buffer), and - // it checks the offset itself when max_command_count is 0, where the required bytes are none. - const UINT64 record_size = - 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) - : 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/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/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 From f54cf315b434cc5980c0bc30499e1837291c5b8f Mon Sep 17 00:00:00 2001 From: mrp1no <137657338+mrp1no@users.noreply.github.com> Date: Mon, 23 Nov 2026 16:57:30 +0100 Subject: [PATCH 09/20] d3d12_xs: Xbox device slot 61 is CreateSamplerX, routed to the PC CreateSampler The retail title calls device slot 61 as CreateSamplerX(desc, dest handle), once per sampler, after its descriptor heaps exist (stop 20 of the RT-5 boot measurements in the coordination issue). The generic thunk forwarded it to the PC slot 61, which is CreateMetaCommand, so the sampler was never written. Slot 61 now has its own handler, like 62 and 67. It passes the description's PC D3D12_SAMPLER_DESC prefix and the handle to the PC CreateSampler (slot 22). That was enough to get the title past this call under Wine. Whatever follows the prefix in the console description is not known and is not read. A null description is skipped and logged once. A handle in the title's own heap range is #7021's translation. xs_proxy_mock_test: slot 61 reaches the mock's slot 22 with the same two words and never its slot 61; a null description reaches nothing. With main's d3d12_xs_device.cpp the new check fails. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit e22994464b17517624c898ed34b3e03c06ce2261) --- docs/d3d12_vulkan.md | 1 + runtime/shims/d3d12_xs_device.cpp | 27 ++++++++++++++++++++++++++- runtime/shims/d3d12_xs_device.h | 2 ++ runtime/test/xs_proxy_mock_test.cpp | 23 ++++++++++++++++++++--- 4 files changed, 49 insertions(+), 4 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 379a2724d4..48e2990554 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -3531,6 +3531,7 @@ to be recovered from call sites (or the NDA GDK headers, if a developer has acce | PresentX / present planes / frame events | Public GDK samples (MIT/zlib), §4.5 | Likely the only present path of a GDKX title. Presenter + vblank-timed frame events; 1-2 planes composed into the Vulkan swapchain (placement, filter, alpha overlay, HDR10 conversions). Call shapes known; slots/layouts **Open**. | | Device slots 48/73/78/79/80 | Public HLE `Freminet`/`ScarlettX` (third-party, not Microsoft documentation) | `d3d12_xs_device.cpp` routes `CreateCommandQueueX` (48), `CreateCommandListX` (73), `SetFrameIntervalX` (78), `ScheduleFrameEventX` (79) and `WaitFrameEventX` (80) before it indexes the PC vtable. Queue and list creation use the existing create paths. The frame-event calls are a per-device token counter: `WaitFrameEventX` returns at once with a fresh non-zero token, because there is no vblank source before a presenter exists. The five indices can be moved with `LEONIDA_XS_QUEUE_X_SLOT`, `LEONIDA_XS_LIST_X_SLOT`, `LEONIDA_XS_FRAME_INTERVAL_SLOT`, `LEONIDA_XS_SCHEDULE_EVENT_SLOT` and `LEONIDA_XS_WAIT_EVENT_SLOT` (3..127; a value that names a slot the proxy already handles keeps that slot's handler); a trace that disagrees wins. | | Indirect argument type 105 | The retail title's startup creates five one-argument command signatures (device slot 41) with no root signature; one has type 105 and a 12-byte stride. Its two `ExecuteIndirect` sites, read statically, set the compute state first, as the `DISPATCH` sites do, and pass one command from the same argument buffer, on a second command list | `d3d12_xs_device.cpp` creates it as `DISPATCH` (`D3D12_DISPATCH_ARGUMENTS`). What the console does differently for it is **Open**. | +| Device slot 61 | The retail title's boot under `gta6rt --run` (stop 20 of the RT-5 measurements in #6910): called as `(desc, dest handle)` once per sampler | `d3d12_xs_device.cpp` routes it to the PC `CreateSampler` (slot 22) with the description's PC `D3D12_SAMPLER_DESC` prefix; the PC slot 61 is `CreateMetaCommand`. The layout of the description beyond the PC fields is **Open**. | | VRS | Public `D3D12_SHADING_RATE` / `D3D12_AXIS_SHADING_RATE` | `VK_KHR_fragment_shading_rate`; `RSSetShadingRate`/image-based rate map to `vkCmdSetFragmentShadingRateKHR`. | | Mesh shader tier | Public `D3D12_MESH_SHADER_TIER` | `VK_EXT_mesh_shader`; the 9,282 translated mesh shaders make this a hard requirement for any content that uses them. | | Wave MMA | Public `D3D12_WAVE_MMA_TIER` | Not used: no shader sets `WAVE_MMA` in SFI0 and none contains `v_mfma`/`v_wmma` (all 26,503, `tools/feature_scan.py`). Answer the tier query truthfully; no cooperative-matrix mapping is needed. | diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index ea8bed3ca4..d8c92bd0f5 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -240,6 +240,7 @@ const char* slot_name(unsigned slot) { 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"; case 62: return "Xbox CreateComputePipelineState"; case 67: return "Xbox DeserializeComputePipelineStateX"; case 70: return "Xbox shader-resource view from raw words"; @@ -1983,6 +1984,27 @@ HRESULT proxy_create_command_signature(DeviceProxy* self, const D3D12_COMMAND_SI return forward(self->real, &pc, root_signature, riid, out); } +// The Xbox slot 61 is CreateSamplerX(desc, dest): a sampler written to a CPU descriptor handle, with the PC +// CreateSampler's two arguments. Measured on the retail title's boot (stop 20 in #6910's RT-5 measurements): the +// title calls it once per sampler after its descriptor heaps exist, and it goes on when the call is served by the PC +// CreateSampler. The PC slot 61 is CreateMetaCommand, which would take these words as (CommandId, NodeMask, ...). +// HYPOTHESIS: the console description begins with the PC D3D12_SAMPLER_DESC (52 bytes), which is what got the title +// past this call; whatever follows it is not known and not read. The title was not seen testing a result, so a null +// description is skipped rather than reported. The handle is passed as given: a handle in the title's own heap range +// is #7021's translation. +void proxy_create_sampler_x(DeviceProxy* self, const D3D12_SAMPLER_DESC* desc, std::uint64_t dest) { + note_slot(61); + if (!desc) { + static std::atomic logged{false}; + if (!logged.exchange(true, std::memory_order_relaxed)) + std::fprintf(stderr, "[rt] d3d12_xs: slot 61 CreateSamplerX without a description (skipped)\n"); + return; + } + D3D12_CPU_DESCRIPTOR_HANDLE handle{}; + handle.ptr = static_cast(dest); + self->real->CreateSampler(desc, handle); +} + // The Xbox slot 67 creates a compute pipeline from native GPU code: (desc, riid, out), named // DeserializeComputePipelineStateX in amd_fidelityfx_upscaler_xbox.dll's messages (call at RVA 0x56d9). The desc // passes the root signature at +0x00, followed by pointer/size pairs for the shader's FSPX entries (docs/fspx.md): @@ -2436,6 +2458,9 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 return hr_to_u64(proxy_create_command_signature( self, reinterpret_cast(a1), a2, reinterpret_cast(a3), reinterpret_cast(a4))); + } else if constexpr (Slot == 61) { + proxy_create_sampler_x(self, reinterpret_cast(a1), a2); + return 0; } else if constexpr (Slot == 67) { return hr_to_u64(proxy_create_compute_pipeline_from_native_code( self, reinterpret_cast(a1), reinterpret_cast(a2), @@ -2780,7 +2805,7 @@ ID3D12Device* device_proxy_real_device(const void* device) { bool device_slot_overridden(unsigned slot) { 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 == 62 || slot == 67 || + slot == 36 || slot == 41 || slot == 45 || slot == 46 || slot == 50 || slot == 56 || slot == 61 || slot == 62 || slot == 67 || slot == 70 || slot == 75 || slot == 76 || slot == 133 || slot == kCreateCommittedResource3X) return true; const XboxDeviceSlotRoutes& routes = xbox_device_slot_routes(); diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 5841656967..3b2c576d17 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -8,6 +8,8 @@ // 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 diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index ac2bf2ed7d..b26a860692 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -997,6 +997,8 @@ int check_allocators() { return 0; } + + // ---- 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 @@ -1093,14 +1095,29 @@ int check_xbox_slots() { EXPECT(mock->calls[41] == 2 && mock->args[41][0] == word(&pc_sig)); EXPECT(mock->array[41][1] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH); - EXPECT(xs::device_slot_overridden(41) && xs::device_slot_overridden(48) && xs::device_slot_overridden(73) && + // 61 CreateSamplerX(desc, dest): the PC CreateSampler (slot 22) gets the same two words, not the PC slot 61 + // (CreateMetaCommand). A null description is skipped without reaching the device. + D3D12_SAMPLER_DESC sampler{}; + sampler.Filter = D3D12_FILTER_MIN_MAG_MIP_LINEAR; + sampler.AddressU = sampler.AddressV = sampler.AddressW = D3D12_TEXTURE_ADDRESS_MODE_WRAP; + sampler.MaxLOD = D3D12_FLOAT32_MAX; + const std::uint64_t sampler_handle = 0x7ff012340040ull; + raw(device, 61, word(&sampler), sampler_handle); + EXPECT(mock->calls[61] == 0 && mock->calls[22] == 1 && xs::device_slot_hits(61) == 1); + EXPECT(mock->args[22][0] == word(&sampler) && mock->args[22][1] == sampler_handle); + raw(device, 61, 0, sampler_handle); + EXPECT(mock->calls[61] == 0 && mock->calls[22] == 1 && xs::device_slot_hits(61) == 2); + + EXPECT(xs::device_slot_overridden(41) && xs::device_slot_overridden(48) && xs::device_slot_overridden(61) && + xs::device_slot_overridden(73) && xs::device_slot_overridden(78) && xs::device_slot_overridden(79) && xs::device_slot_overridden(80)); EXPECT(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; slot 41 creates argument type 105 as DISPATCH\n", g_label); + std::printf("%s: device slots 48/73/78/79/80 route to a queue, a list and frame-event tokens, and slot 61 to " + "CreateSampler, without reaching the mock's own PC slots; 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); From 6d4cf2ceb705b4d1bf2fdc0611e6431d91718320 Mon Sep 17 00:00:00 2001 From: mrp1no <137657338+mrp1no@users.noreply.github.com> Date: Mon, 23 Nov 2026 20:44:08 +0100 Subject: [PATCH 10/20] d3d12_xs: slot 61 is CreateSamplerX only for the title's calls; a host caller gets PC CreateMetaCommand The proxy also serves host callers: d3d12_vulkan_device_test drives the Vulkan device through it, and its ID3D12Device5::CreateMetaCommand call (PC slot 61) landed in proxy_create_sampler_x (found by nullmarsh on #7115: the test stopped at line 5763 instead of main's known line 6574). Slot 61 now checks the caller's return address with a classifier the runtime installs (set_console_caller, the name #7490 uses): D3D12XboxCreateDevice installs rt::shims::mapped_image_base, so only a caller in an image the guest loader mapped gets CreateSamplerX. Any other caller, and every caller when no classifier is installed, is forwarded to the PC slot 61. xs_proxy_mock_test checks all three cases: no classifier (PC slot 61), a guest caller (PC CreateSampler with the same words; a null description skipped) and a host caller under an installed classifier (PC slot 61). d3d12_vulkan_device_test again stops at line 6574, as on main. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit 8f756ebe048af042638ce51a61490f35f4f44ee3) (cherry picked from commit c915e1da45e17d46c90c32be9809e4f043a77fd3) --- docs/d3d12_vulkan.md | 2 +- runtime/shims/d3d12_xs.cpp | 6 ++++++ runtime/shims/d3d12_xs_device.cpp | 33 ++++++++++++++++++++++++++--- runtime/shims/d3d12_xs_device.h | 6 ++++++ runtime/test/xs_proxy_mock_test.cpp | 18 ++++++++++++---- 5 files changed, 57 insertions(+), 8 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index 48e2990554..77f60c3ebd 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -3531,7 +3531,7 @@ to be recovered from call sites (or the NDA GDK headers, if a developer has acce | PresentX / present planes / frame events | Public GDK samples (MIT/zlib), §4.5 | Likely the only present path of a GDKX title. Presenter + vblank-timed frame events; 1-2 planes composed into the Vulkan swapchain (placement, filter, alpha overlay, HDR10 conversions). Call shapes known; slots/layouts **Open**. | | Device slots 48/73/78/79/80 | Public HLE `Freminet`/`ScarlettX` (third-party, not Microsoft documentation) | `d3d12_xs_device.cpp` routes `CreateCommandQueueX` (48), `CreateCommandListX` (73), `SetFrameIntervalX` (78), `ScheduleFrameEventX` (79) and `WaitFrameEventX` (80) before it indexes the PC vtable. Queue and list creation use the existing create paths. The frame-event calls are a per-device token counter: `WaitFrameEventX` returns at once with a fresh non-zero token, because there is no vblank source before a presenter exists. The five indices can be moved with `LEONIDA_XS_QUEUE_X_SLOT`, `LEONIDA_XS_LIST_X_SLOT`, `LEONIDA_XS_FRAME_INTERVAL_SLOT`, `LEONIDA_XS_SCHEDULE_EVENT_SLOT` and `LEONIDA_XS_WAIT_EVENT_SLOT` (3..127; a value that names a slot the proxy already handles keeps that slot's handler); a trace that disagrees wins. | | Indirect argument type 105 | The retail title's startup creates five one-argument command signatures (device slot 41) with no root signature; one has type 105 and a 12-byte stride. Its two `ExecuteIndirect` sites, read statically, set the compute state first, as the `DISPATCH` sites do, and pass one command from the same argument buffer, on a second command list | `d3d12_xs_device.cpp` creates it as `DISPATCH` (`D3D12_DISPATCH_ARGUMENTS`). What the console does differently for it is **Open**. | -| Device slot 61 | The retail title's boot under `gta6rt --run` (stop 20 of the RT-5 measurements in #6910): called as `(desc, dest handle)` once per sampler | `d3d12_xs_device.cpp` routes it to the PC `CreateSampler` (slot 22) with the description's PC `D3D12_SAMPLER_DESC` prefix; the PC slot 61 is `CreateMetaCommand`. The layout of the description beyond the PC fields is **Open**. | +| 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**. | | 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/shims/d3d12_xs.cpp b/runtime/shims/d3d12_xs.cpp index 67ac93dd0d..173106f1cd 100644 --- a/runtime/shims/d3d12_xs.cpp +++ b/runtime/shims/d3d12_xs.cpp @@ -166,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_device.cpp b/runtime/shims/d3d12_xs_device.cpp index d8c92bd0f5..45fdf3e2e6 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -31,6 +31,7 @@ #include #include +#include // _ReturnAddress: slot 61 serves a console caller differently from a host one #include #include @@ -240,7 +241,7 @@ const char* slot_name(unsigned slot) { 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"; + 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"; @@ -1992,6 +1993,17 @@ HRESULT proxy_create_command_signature(DeviceProxy* self, const D3D12_COMMAND_SI // 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) { @@ -2459,8 +2471,19 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 self, reinterpret_cast(a1), a2, reinterpret_cast(a3), reinterpret_cast(a4))); } else if constexpr (Slot == 61) { - proxy_create_sampler_x(self, reinterpret_cast(a1), a2); - return 0; + 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), @@ -2910,6 +2933,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 3b2c576d17..da7990cb4e 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -159,6 +159,12 @@ void set_console_descriptor_heap_handler(ConsoleDescriptorHeapHandler handler); // 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); diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index b26a860692..9aa1b1614d 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -1095,18 +1095,28 @@ int check_xbox_slots() { EXPECT(mock->calls[41] == 2 && mock->args[41][0] == word(&pc_sig)); EXPECT(mock->array[41][1] == D3D12_INDIRECT_ARGUMENT_TYPE_DISPATCH_MESH); - // 61 CreateSamplerX(desc, dest): the PC CreateSampler (slot 22) gets the same two words, not the PC slot 61 - // (CreateMetaCommand). A null description is skipped without reaching the device. + // 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] == 0 && mock->calls[22] == 1 && xs::device_slot_hits(61) == 1); + 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] == 0 && mock->calls[22] == 1 && xs::device_slot_hits(61) == 2); + 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) && From 25826cddddd1cc590f0a321d356de6fe2dfcdbc1 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 17:28:57 +0100 Subject: [PATCH 11/20] d3d12_xs: device slot 74 (pointer, u32, pointer) returns S_OK instead of reaching PC ShaderCacheControl (#7231) The retail title calls slot 74 once; the PC slot 74 reads the first pointer as kinds and returns E_INVALIDARG, so the title hits an int3. The proxy handler does not call the PC device, writes nothing, logs the three words once, and yields to an env slot override that moves a route onto 74. (cherry picked from commit cdeee35aa80471ab2e1b7f946da1f1cdbf395451) Adapted to main by Mumogg: the queue route inside route_xbox_device_slot calls proxy_create_command_queue_xbox (the 32-byte description of 0cde63d61), as the inline route did before this commit moved the routes into a function. --- runtime/CMakeLists.txt | 1 + runtime/shims/d3d12_xs_device.cpp | 77 +++++++++++++++++++---------- runtime/shims/d3d12_xs_device.h | 4 +- runtime/test/xs_proxy_mock_test.cpp | 36 ++++++++++++-- 4 files changed, 88 insertions(+), 30 deletions(-) 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_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 45fdf3e2e6..42f23b1d07 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -246,6 +246,7 @@ const char* slot_name(unsigned slot) { 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"; @@ -2376,6 +2377,49 @@ HRESULT proxy_create_committed_resource3_x(DeviceProxy* self, std::uint64_t heap 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. +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 std::uint64_t WINAPI proxy_slot(DeviceProxy* 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, @@ -2414,6 +2458,11 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 reinterpret_cast(a3))); } else if constexpr (Slot == 31 || Slot == 34 || Slot == 35 || Slot == 45 || Slot == 46 || Slot == 50) { return hr_to_u64(proxy_unwrapping_call(self, a1, a2, a3, a4, a5)); + } else if constexpr (Slot == 74) { + 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); + return proxy_slot74(a1, a2, a3); } else if constexpr (Slot == 75) { return hr_to_u64(proxy_create_command_queue1(self, a1, a2, reinterpret_cast(a3), reinterpret_cast(a4))); @@ -2519,30 +2568,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 @@ -2828,7 +2855,7 @@ ID3D12Device* device_proxy_real_device(const void* device) { bool device_slot_overridden(unsigned slot) { 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 == 62 || slot == 67 || + 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(); diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index da7990cb4e..ecd39db7bf 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -19,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 @@ -154,7 +156,7 @@ void set_console_descriptor_heap_handler(ConsoleDescriptorHeapHandler handler); // 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); diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 9aa1b1614d..9eca96c9d6 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -1137,8 +1137,8 @@ int check_xbox_slots() { // ---- 8. Environment overrides for the Xbox device slots (one process each, read once) ---- -int run_env_slots(bool valid) { - const char* frame_interval = valid ? "96" : "2"; +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"; @@ -1154,7 +1154,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); @@ -1306,6 +1311,27 @@ 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]}; + EXPECT(hr_of(raw(device, 74, word(first), 7, word(second))) == S_OK); + EXPECT(mock->calls[74] == 0 && xs::device_slot_hits(74) == 1); + EXPECT(std::memcmp(first, first_before, sizeof(first)) == 0 && std::memcmp(second, second_before, sizeof(second)) == 0); + EXPECT(release(device) == 0 && mock->refs == 0); + } + return 0; +} + // ---- 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) { @@ -2144,6 +2170,7 @@ 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; @@ -2155,7 +2182,8 @@ int main(int argc, char** argv) { check_render_target_sizes() || check_allocation_descriptions_cleaned() || check_render_target_layout() || - check_committed_resource_leases()) + check_committed_resource_leases() || + check_slot74()) return 1; std::printf("xs_proxy_mock_test: PASS (%d allocations refused on purpose)\n", g_failed_news); return 0; From 6a9edfe37f6d44a114e07d599aa875381f681d0a Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:36:22 -0600 Subject: [PATCH 12/20] d3d12_xs: slot 74's stand-in is for the title's calls; a host caller gets PC ShaderCacheControl The stand-in also took a host's ID3D12Device9::ShaderCacheControl call through the proxy and answered S_OK without reaching the device (found on native Windows by BadgersMC in the review of this change). Slot 74 now asks the caller classifier slot 61 uses (set_console_caller): a caller in an image the guest loader mapped gets the stand-in, any other caller, and every caller when no classifier is installed, is forwarded to the PC slot 74 or refused past the PC device's table. xs_proxy_mock_test: the guest case under a classifier, and the host case with a classifier and with none, on a device that has ShaderCacheControl and on one that does not. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HxBQf4pXH8PWpC5oZsM4bt --- runtime/shims/d3d12_xs_device.cpp | 14 ++++++++++++-- runtime/test/xs_proxy_mock_test.cpp | 20 ++++++++++++++++++++ 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 42f23b1d07..da6f392c19 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -2409,7 +2409,8 @@ bool route_xbox_device_slot(DeviceProxy* self, unsigned slot, std::uint64_t a1, // 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. +// 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; @@ -2462,7 +2463,16 @@ std::uint64_t WINAPI proxy_slot(DeviceProxy* self, std::uint64_t a1, std::uint64 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); - return proxy_slot74(a1, a2, a3); + 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))); diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 9eca96c9d6..7e0d2da479 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -1324,9 +1324,29 @@ int check_slot74() { 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; From 5d5afdeb4c02962f0bf33d2ccb69998ecebe93d6 Mon Sep 17 00:00:00 2001 From: Vadson159 Date: Mon, 23 Nov 2026 17:24:09 +0100 Subject: [PATCH 13/20] d3d12_xs: route command queue slot 35 to ExecuteCommandLists (cherry picked from commit e925b634551ed96d1ed097dfe17d7dfca0cdbe4d) Adapted to main by Mumogg: main has command-list proxies, so the shared execute function replaces them by their real lists in a copy of the array (UnwrappedArray), for the console slot 35 as for the PC slot 10, whose test failed otherwise. The slot 35 mock case passes two mock lists instead of two numbers and checks that they arrive and that the caller's array is not written. --- runtime/shims/d3d12_xs_device.cpp | 31 +++++++++++++ runtime/shims/d3d12_xs_device.h | 14 ++++-- runtime/test/queue_proxy_test.cpp | 72 +++++++++++++++++++++++------ runtime/test/xs_proxy_mock_test.cpp | 43 ++++++++++++++++- 4 files changed, 140 insertions(+), 20 deletions(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index da6f392c19..ef0ae77815 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -803,7 +803,11 @@ 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 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 @@ -844,6 +848,7 @@ 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 { @@ -1312,6 +1317,20 @@ 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 } +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, @@ -1331,6 +1350,10 @@ 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 (Slot >= self->slot_count) { bool expected = false; if (ChildStats::beyond_warned[Slot].compare_exchange_strong(expected, true, @@ -1346,6 +1369,9 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ return hr_to_u64(E_NOTIMPL); } d3d12_trace::record(child_trace_name(Slot)); // "called": the real object's result is not inspected + if constexpr (K == ChildKind::queue && Slot == kQueueExecuteCommandLists) { + return queue_execute_command_lists(self, a1, a2); + } if constexpr (K == ChildKind::queue && (Slot == kQueueSignal || Slot == kQueueWait)) a1 = unwrap_object(a1); UnwrappedArray unwrapped_lists; if constexpr (K == ChildKind::queue && Slot == 10) { @@ -2902,6 +2928,11 @@ unsigned fence_proxy_slot_count(const void* fence) { unsigned queue_proxy_table_size() { return kQueueSlots; } unsigned fence_proxy_table_size() { return kFenceSlots; } + +bool queue_slot_overridden(unsigned slot) { + return slot <= 2 || slot == 7 || slot == kQueueSignal || slot == kQueueWait || + slot == kQueueExecuteCommandListsX; +} unsigned allocator_proxy_table_size() { return kAllocatorSlots; } unsigned allocator_proxy_slot_count(const void* allocator) { return is_allocator_proxy(allocator) ? static_cast(allocator)->slot_count : 0; diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index ecd39db7bf..9f72820258 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -56,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 @@ -178,6 +179,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. diff --git a/runtime/test/queue_proxy_test.cpp b/runtime/test/queue_proxy_test.cpp index 3f46567f85..967313d53a 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,11 @@ 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)); + 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 +300,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 +366,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 +396,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 +1468,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/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 7e0d2da479..b4bdc97a01 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -1135,6 +1135,42 @@ 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); + + 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, bool on_slot74 = false) { @@ -1615,8 +1651,10 @@ 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); @@ -2203,7 +2241,8 @@ int main(int argc, char** argv) { check_allocation_descriptions_cleaned() || check_render_target_layout() || check_committed_resource_leases() || - check_slot74()) + 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; From 6d5b2d4c2f0782e583b2094719b5292218de6594 Mon Sep 17 00:00:00 2001 From: DevilNine <102010568+DevilNine@users.noreply.github.com> Date: Mon, 23 Nov 2026 14:46:12 -0300 Subject: [PATCH 14/20] d3d12_xs: handle ID3D12CommandAllocator slot 9 (SetAllocatorCallbackX) on allocator proxy (cherry picked from commit e29e9899809347a730fd57a14532a22fe0ee7231) --- runtime/shims/d3d12_xs_device.cpp | 34 +++++++++++++++++++++++++++ runtime/shims/d3d12_xs_device.h | 12 ++++++---- runtime/test/allocator_proxy_test.cpp | 31 ++++++++++++++++++------ runtime/test/xs_proxy_mock_test.cpp | 16 +++++++++++-- 4 files changed, 80 insertions(+), 13 deletions(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index ef0ae77815..2665dd4aff 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -816,6 +816,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 @@ -853,6 +856,7 @@ const char* child_public_name(unsigned slot) { if (slot < kFence1PublicSlots) return fence[slot - 8]; } else { if (slot == 8) return "Reset"; + if (slot == 9) return "SetAllocatorCallbackX"; } return nullptr; } @@ -1354,6 +1358,24 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ d3d12_trace::record(child_trace_name(Slot)); return queue_execute_command_lists(self, a1, a2); } + 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, @@ -2938,6 +2960,18 @@ 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); diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 9f72820258..652b6047c3 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -196,10 +196,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. @@ -211,6 +212,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(); 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/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index b4bdc97a01..469796cd46 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -935,9 +935,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); From 7d58fa5790ed1764cad6258e9730080437ab5f7e Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:30:28 -0600 Subject: [PATCH 15/20] d3d12_xs: console list slot 139 is Reset, routed to the PC slot 10 The retail title resets its command lists through list slot 139, with (allocator proxy, pipeline state). main's slot map had no entry for it, so the call was recorded and dropped and the list stayed closed. The map sends it to the PC slot 10, and the unwrap keys on the PC slot, so console slot 10 and console slot 139 both hand the real list its real allocator (and a wrapped pipeline state the same way) and re-pin the inline cursor. The mapping and the unwrap rule are those of ef9d0759d (Nolan Cotter; measured by Pipodi), written again for main's list proxy, where that commit does not apply. xs_proxy_mock_test checks the map entry and a slot 139 call. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HxBQf4pXH8PWpC5oZsM4bt --- runtime/shims/d3d12_xs_device.cpp | 5 ++++- runtime/shims/d3d12_xs_device.h | 1 + runtime/test/xs_proxy_mock_test.cpp | 10 ++++++++++ 3 files changed, 15 insertions(+), 1 deletion(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 2665dd4aff..1d3350a7ac 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -1221,8 +1221,11 @@ 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); diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index 652b6047c3..b9062ff202 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -237,6 +237,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/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 469796cd46..1ea064c559 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -2068,6 +2068,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 @@ -2173,6 +2174,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); From e7044cb9bb1c0a5a1d075405ad916a48a8ec5e0b Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:42:00 -0600 Subject: [PATCH 16/20] d3d12_xs: the title's queue slot 18 is the frequency getter, not PC GetDesc Queue slot 18 is ID3D12CommandQueue::GetDesc on the PC: a struct return that writes a 16-byte description through the hidden pointer. The retail title calls slot 18 with one pointer to 8 bytes, the shape of GetTimestampFrequency(UINT64*), which the console queue has there (two methods are inserted at 14/15, so the PC slots 16 to 18 sit two later). Forwarded as GetDesc, the call wrote a description over the title's 8 bytes and what follows them; the title then went wrong a little later, after its first submission. The title's call (set_console_caller, as device slots 61 and 74) now goes to the PC slot 16. A host caller, and every caller when no classifier is installed, keeps the PC GetDesc. The reading of slot 18 is that of the console queue work in old PR 2490 (Nolan Cotter), which answers an undetected slot 18 as the frequency getter because it is the only reading that cannot overrun its argument. That work's layout detection does not apply to main's queue proxy; this is the one rule the boot needs, written for it. xs_proxy_mock_test: the guest call reaches the mock queue's slot 16 with its pointer and leaves the words around it; a host call, with a classifier and with none, reaches slot 18. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HxBQf4pXH8PWpC5oZsM4bt --- runtime/shims/d3d12_xs_device.cpp | 15 +++++++++++++++ runtime/test/xs_proxy_mock_test.cpp | 16 ++++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 1d3350a7ac..0acfa0d752 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -805,6 +805,8 @@ static_assert(kQueueSlots * sizeof(void*) <= 4096 && kFenceSlots * sizeof(void*) 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"); @@ -1397,6 +1399,19 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ 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) { diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 1ea064c559..9f6dd50461 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -1177,6 +1177,22 @@ int check_xbox_queue_slots() { 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); From 06196160febe3416020a1899da1c4381b56097ae Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 22:45:09 -0600 Subject: [PATCH 17/20] d3d12_xs: the queue's console slot 32 is PresentX, wired to the presentation core The retail title presents through command-queue slot 32, past the PC queue's 19 slots, so main refused it with E_NOTIMPL and nothing could be shown. The slot now calls XboxPresentation::PresentX (xbox_present.h) with the title's plane count, planes and parameters. The first call on a device builds a window and the Vulkan layer's presenter for it, once; a device that cannot present answers S_OK and shows nothing, so the title's frame loop runs either way. The mock and COM builds of this file have no presenter and answer S_OK. The wiring follows old PR 2490's (Nolan Cotter, 2be25cee2), written again for main's queue proxy, where that commit does not apply. Not carried over: the queue layout detection (the older layout has PresentX at slot 30) and presenting into the title's own window (old PR 8591); the window here is one this layer creates. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HxBQf4pXH8PWpC5oZsM4bt --- runtime/shims/d3d12_xs_device.cpp | 96 ++++++++++++++++++++++++++++++- 1 file changed, 95 insertions(+), 1 deletion(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 0acfa0d752..63e834beea 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -29,6 +29,12 @@ #include "d3d12_xs_desc_clean.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 @@ -83,8 +89,13 @@ struct DeviceProxy { std::atomic frame_latency{1}; std::atomic frame_event_scheduled{false}; std::atomic frame_next_token{1}; + // 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 { @@ -379,6 +390,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(); } @@ -1326,6 +1338,85 @@ 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)); + 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. @@ -1363,6 +1454,9 @@ std::uint64_t WINAPI child_slot(ChildProxy* self, std::uint64_t a1, std::uint64_ 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). @@ -2971,7 +3065,7 @@ 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 == kQueueExecuteCommandListsX || slot == kQueuePresentX; } unsigned allocator_proxy_table_size() { return kAllocatorSlots; } unsigned allocator_proxy_slot_count(const void* allocator) { From 21a6c617bc6e5706debde9a6320c9f785e55cf2b Mon Sep 17 00:00:00 2001 From: Logan Date: Mon, 23 Nov 2026 12:16:11 -0500 Subject: [PATCH 18/20] PresentX: device-side WaitFrameEventX and the frame pacer share one token source Device slot 80 (WaitFrameEventX, from #6935) numbered its tokens with a counter of its own, while XboxPresentation's pacer refuses any token above the ones it issued itself. A title that waits through the device and presents through the device's XboxPresentation therefore had every PresentX refused with E_INVALIDARG once its tokens ran ahead of the pacer's. leonida::FrameTokenSource is now the counter both use: a pacer takes an optional shared source (a standalone pacer still owns its own and numbers as before), the device proxy owns one and exposes it through rt::d3d12_xs::device_frame_tokens, and XboxPresentation passes a given source to its pacer. A token that was never issued is still refused. Reported by rafaelpssz in #7496. (cherry picked from commit afb14d56c6a1683fae4345702c874a62d9234e71) Adapted to main by Mumogg: main's uncapped pacer path issues its token from the shared source too, the device proxy keeps the PresentX state next to the token source, and the queue's PresentX hands the device's source to its XboxPresentation, which is what makes the title's tokens valid there. --- runtime/shims/d3d12_xs_device.cpp | 15 ++++++++++----- runtime/shims/d3d12_xs_device.h | 7 +++++++ runtime/shims/xbox_present.cpp | 5 +++-- runtime/shims/xbox_present.h | 3 ++- runtime/src/frame_pacer.h | 25 +++++++++++++++++++------ runtime/test/device_proxy_test.cpp | 5 +++++ runtime/test/frame_pacer_test.cpp | 19 +++++++++++++++++++ runtime/test/xbox_present_test.cpp | 20 +++++++++++++++++++- 8 files changed, 84 insertions(+), 15 deletions(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 63e834beea..e53d96d564 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -27,6 +27,7 @@ #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 @@ -88,7 +89,7 @@ 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; @@ -1395,7 +1396,8 @@ PresentState* present_state_for(DeviceProxy* device) { 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)); + 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; } @@ -1685,9 +1687,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; } @@ -3023,6 +3023,11 @@ 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 >= 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 || diff --git a/runtime/shims/d3d12_xs_device.h b/runtime/shims/d3d12_xs_device.h index b9062ff202..6ae5200341 100644 --- a/runtime/shims/d3d12_xs_device.h +++ b/runtime/shims/d3d12_xs_device.h @@ -73,6 +73,11 @@ #include #include +#include + +namespace leonida { +class FrameTokenSource; +} namespace rt::d3d12_xs { @@ -153,6 +158,8 @@ 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 (descriptor heap proxy), 17-24 (CPU descriptor handle translation), 26 (the // console's struct-return form), 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/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/test/device_proxy_test.cpp b/runtime/test/device_proxy_test.cpp index 6b91a7a1f8..3653556f3f 100644 --- a/runtime/test/device_proxy_test.cpp +++ b/runtime/test/device_proxy_test.cpp @@ -25,6 +25,7 @@ #include "d3d12_trace.h" #include "d3d12_xs_device.h" #include "shims.h" +#include "../src/frame_pacer.h" namespace { @@ -428,6 +429,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"); 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/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. { From 11d44eee9f00c2c1273240ad2220ddf14c5a8a1d Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Mon, 23 Nov 2026 23:03:47 -0600 Subject: [PATCH 19/20] queue_proxy_test: the PresentX slot is called and counted The coverage gate asks for every queue slot to have been called, and skips the overridden ones in its sweep of the refused tail. Slot 32 is overridden since the PresentX wiring, so nothing called it and the gate failed ("queue slot 32 never called"). The test now calls it where it calls the console ExecuteCommandLists slot: this build of the proxy has no presenter, so the answer is S_OK. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HxBQf4pXH8PWpC5oZsM4bt --- runtime/test/queue_proxy_test.cpp | 6 ++++++ 1 file changed, 6 insertions(+) diff --git a/runtime/test/queue_proxy_test.cpp b/runtime/test/queue_proxy_test.cpp index 967313d53a..674a8cf2ed 100644 --- a/runtime/test/queue_proxy_test.cpp +++ b/runtime/test/queue_proxy_test.cpp @@ -277,6 +277,12 @@ int check_slots(const Backend& b) { 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) { From ce3e5153f1150f90b9291eff5aa133941d06124e Mon Sep 17 00:00:00 2001 From: Rain156 <1954786975@qq.com> Date: Tue, 24 Nov 2026 14:53:10 +0800 Subject: [PATCH 20/20] d3d12_xs: keep the fallback PresentX window responsive during rendering Create and dispatch the Win32 window on its own thread. Shut that thread down after the presenter has released the surface and test window messages and closure independently of the submitting thread. --- runtime/CMakeLists.txt | 7 +++ runtime/shims/d3d12_xs_device.cpp | 33 ++++--------- runtime/shims/present_window.h | 72 ++++++++++++++++++++++++++++ runtime/test/present_window_test.cpp | 35 ++++++++++++++ 4 files changed, 123 insertions(+), 24 deletions(-) create mode 100644 runtime/shims/present_window.h create mode 100644 runtime/test/present_window_test.cpp diff --git a/runtime/CMakeLists.txt b/runtime/CMakeLists.txt index e922f067c9..e1b3aee816 100644 --- a/runtime/CMakeLists.txt +++ b/runtime/CMakeLists.txt @@ -1006,6 +1006,13 @@ if(BUILD_TESTING) add_test(NAME startup_trace COMMAND startup_trace_test) endif() + if(WIN32) + add_executable(present_window_test test/present_window_test.cpp) + target_link_libraries(present_window_test PRIVATE user32) + add_test(NAME present_window COMMAND present_window_test) + set_tests_properties(present_window PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 15) + endif() + if(TARGET device_proxy_test) add_test(NAME device_proxy COMMAND device_proxy_test) set_tests_properties(device_proxy PROPERTIES SKIP_RETURN_CODE 77) # no WARP adapter (Wine) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index e53d96d564..7a47e76a2f 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -24,6 +24,9 @@ // for a trace that disagrees. The frame-event calls answer from a per-device token counter: there is no vblank source // behind the device before a presenter exists, so WaitFrameEventX returns at once with a fresh non-zero token. #include "d3d12_xs_device.h" +#ifdef LEONIDA_VULKAN_DEVICE +#include "present_window.h" +#endif #include "d3d12_trace.h" #include "d3d12_xs_alloc_size.h" #include "d3d12_xs_desc_clean.h" @@ -1352,20 +1355,12 @@ constexpr unsigned kQueuePresentX = 32; #ifdef LEONIDA_VULKAN_DEVICE struct PresentState { - ~PresentState() { - xbox.reset(); - if (window) DestroyWindow(window); - } - HWND window = nullptr; + PresentWindow window; // The presenter is destroyed before its surface window. 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) { @@ -1375,30 +1370,20 @@ PresentState* present_state_for(DeviceProxy* device) { 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) { + HWND window = state->window.create(); + if (!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); + ShowWindowAsync(window, SW_SHOWNOACTIVATE); + auto presenter = rt::d3d12::create_window_presenter(device->real, 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)); + std::fprintf(stderr, "[rt] d3d12_xs: PresentX ready (window %p)\n", static_cast(window)); return state; } diff --git a/runtime/shims/present_window.h b/runtime/shims/present_window.h new file mode 100644 index 0000000000..1f03f58fcc --- /dev/null +++ b/runtime/shims/present_window.h @@ -0,0 +1,72 @@ +#pragma once + +#include +#include +#include +#include + +// The thread that owns an HWND must continue dispatching window messages while another +// thread creates pipelines or waits for the GPU. A stop event also wakes an idle window. +namespace rt::d3d12_xs { +class PresentWindow { +public: + PresentWindow() = default; + PresentWindow(const PresentWindow&) = delete; + PresentWindow& operator=(const PresentWindow&) = delete; + ~PresentWindow() { + if (stop_) SetEvent(stop_); + if (owner_.joinable()) owner_.join(); + if (stop_) CloseHandle(stop_); + } + + HWND create() { + if (stop_) return nullptr; + stop_ = CreateEventW(nullptr, TRUE, FALSE, nullptr); + if (!stop_) return nullptr; + try { + std::promise> ready; + auto result = ready.get_future(); + owner_ = std::thread([stop = stop_, ready = std::move(ready)]() mutable { + WNDCLASSW cls{}; + cls.lpfnWndProc = &procedure; + cls.hInstance = GetModuleHandleW(nullptr); + cls.lpszClassName = L"LeonidaPresentX"; + HWND window = nullptr; + if (RegisterClassW(&cls) || GetLastError() == ERROR_CLASS_ALREADY_EXISTS) + window = CreateWindowExW(0, cls.lpszClassName, L"Leonida", WS_OVERLAPPEDWINDOW, + CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, CW_USEDEFAULT, + nullptr, nullptr, cls.hInstance, nullptr); + ready.set_value({window, window ? ERROR_SUCCESS : GetLastError()}); + if (!window) return; + while (MsgWaitForMultipleObjectsEx(1, &stop, INFINITE, QS_ALLINPUT, MWMO_INPUTAVAILABLE) == + WAIT_OBJECT_0 + 1) { + MSG msg; + while (WaitForSingleObject(stop, 0) == WAIT_TIMEOUT && PeekMessageW(&msg, nullptr, 0, 0, PM_REMOVE)) { + if (msg.message == WM_QUIT) return; + TranslateMessage(&msg); + DispatchMessageW(&msg); + } + } + if (IsWindow(window)) DestroyWindow(window); + }); + const auto [window, error] = result.get(); + if (!window) SetLastError(error); + return window; + } catch (const std::exception&) { + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return nullptr; + } + } + +private: + static LRESULT CALLBACK procedure(HWND window, UINT message, WPARAM wparam, LPARAM lparam) { + if (message == WM_DESTROY) { + PostQuitMessage(0); + return 0; + } + return DefWindowProcW(window, message, wparam, lparam); + } + HANDLE stop_ = nullptr; + std::thread owner_; +}; +} // namespace rt::d3d12_xs diff --git a/runtime/test/present_window_test.cpp b/runtime/test/present_window_test.cpp new file mode 100644 index 0000000000..9488563c95 --- /dev/null +++ b/runtime/test/present_window_test.cpp @@ -0,0 +1,35 @@ +// The submitting thread does no message dispatch. Each hidden presentation window must still +// process messages, close on its owner thread and allow the other window to keep running. +#include "../shims/present_window.h" + +#include +#include + +namespace { +bool send(HWND window, UINT message) { + DWORD_PTR result = 0; + return SendMessageTimeoutW(window, message, 0, 0, SMTO_ABORTIFHUNG | SMTO_BLOCK, 2000, &result) != 0; +} +} + +int main() { + HWND control = CreateWindowExW(0, L"STATIC", L"", WS_POPUP, 0, 0, 1, 1, nullptr, nullptr, + GetModuleHandleW(nullptr), nullptr); + if (!control) { + std::fprintf(stderr, "no Win32 desktop available (error %lu)\n", GetLastError()); + return 77; + } + DestroyWindow(control); + + rt::d3d12_xs::PresentWindow first; + auto second = std::make_unique(); + const HWND a = first.create(), b = second->create(); + if (!a || !b || a == b || GetWindowThreadProcessId(a, nullptr) == GetCurrentThreadId() || + !send(a, WM_NULL) || !send(b, WM_NULL)) return 1; + if (!send(a, WM_CLOSE) || IsWindow(a) || !send(b, WM_NULL)) return 1; + + std::thread release([window = std::move(second)]() mutable { window.reset(); }); + release.join(); + if (IsWindow(b)) return 1; + return 0; +}