From 522faa2ee4ad77b00d11057543497f9e31c3ff05 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 1/9] 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 c29a288a91..cc4ae88aab 100644 --- a/runtime/src/pe_loader.cpp +++ b/runtime/src/pe_loader.cpp @@ -1094,6 +1094,7 @@ Loader::~Loader() { entry(m.base, DLL_PROCESS_DETACH, nullptr); // explicit unload; the return value is ignored } } + shims::remove_xmem_allocation_hooks(this); shims::remove_bundled_loader(this); shims::remove_module_lookup(this); for (auto* m : order_) { @@ -1498,6 +1499,12 @@ Module& Loader::map_image(const std::filesystem::path& path, const std::string& // installed here, before bind_imports can return control to the caller and before any image code can run. initialize_tls(*m); parse_exports(*m); + if (auto it = m->exports.find("__XMemAllocationHooks__"); it != m->exports.end()) { + const auto offset = static_cast(static_cast(it->second) - m->base); + if (offset <= m->size && m->size - offset >= sizeof(shims::XMemAllocationHooks)) { + shims::add_xmem_allocation_hooks(this, static_cast(it->second)); + } + } return *m; } diff --git a/runtime/test/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 f59167ef9ce47c3861a2c3f4092c6d4ccdb623e5 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 16:52:16 +0100 Subject: [PATCH 2/9] 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 6b75cbafbc9e909747c7576dc7123f4d78b4123f Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 16:56:52 +0100 Subject: [PATCH 3/9] 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 8eaccded7f8ea0292046f097d934f73015e3c670 Mon Sep 17 00:00:00 2001 From: tedin7 Date: Mon, 23 Nov 2026 17:26:57 +0100 Subject: [PATCH 4/9] 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 e090be908ded3ebe84a04702e6690bd98d2cefe7 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 5/9] 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 24914e72982aff3da606199eb1bb783fbaa18457 Mon Sep 17 00:00:00 2001 From: Johan John Joji <83926918+TripleJ160@users.noreply.github.com> Date: Mon, 23 Nov 2026 11:37:29 -0500 Subject: [PATCH 6/9] d3d12: preserve PC descriptor validation in slot 25 (cherry picked from commit b4d1ba179436a73989b7c33dfcdd1eda473575f4) --- docs/d3d12_vulkan.md | 5 +- runtime/shims/d3d12_xs_desc_clean.h | 11 ++- runtime/shims/d3d12_xs_device.cpp | 14 ++-- runtime/test/device_proxy_test.cpp | 6 +- runtime/test/xs_proxy_mock_test.cpp | 126 +++++++++++++++------------- 5 files changed, 93 insertions(+), 69 deletions(-) diff --git a/docs/d3d12_vulkan.md b/docs/d3d12_vulkan.md index b39a558923..5979e22f56 100644 --- a/docs/d3d12_vulkan.md +++ b/docs/d3d12_vulkan.md @@ -2261,8 +2261,9 @@ The trace will enumerate them. 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). + ones). For console-form calls or descriptors explicitly using layout `0x101`, the proxy strips Xbox-only flags and + translates layout `0x101` to ROW_MAJOR for buffers or UNKNOWN for textures. Other PC-form descriptors reach the host + unchanged for validation (`d3d12_xs_desc_clean.h`; #6982 section 3.7). A committed resource made through slots 76 and 127 also allocates that size through the title's `__XMemAllocationHooks__`, as the console runtime's `XMemAlloc` for the resource does, and frees it when the resource is destroyed (a lease kept with `SetPrivateDataInterface`; the bytes are not used). The retail title diff --git a/runtime/shims/d3d12_xs_desc_clean.h b/runtime/shims/d3d12_xs_desc_clean.h index 61f49eb8b2..1782b7d880 100644 --- a/runtime/shims/d3d12_xs_desc_clean.h +++ b/runtime/shims/d3d12_xs_desc_clean.h @@ -21,12 +21,15 @@ constexpr std::uint32_t kPcResourceFlagsMask = 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). +constexpr auto kXboxTiledResourceLayout = static_cast(0x101); + +// Strip Xbox-only flags and translate the Xbox tiled layout. Preserve all other layouts so the host can validate them. inline D3D12_RESOURCE_DESC pc_resource_desc(const D3D12_RESOURCE_DESC& xbox) { D3D12_RESOURCE_DESC pc = xbox; - pc.Layout = xbox.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? D3D12_TEXTURE_LAYOUT_ROW_MAJOR - : D3D12_TEXTURE_LAYOUT_UNKNOWN; + if (pc.Layout == kXboxTiledResourceLayout) { + pc.Layout = pc.Dimension == D3D12_RESOURCE_DIMENSION_BUFFER ? D3D12_TEXTURE_LAYOUT_ROW_MAJOR + : D3D12_TEXTURE_LAYOUT_UNKNOWN; + } pc.Flags = static_cast(static_cast(xbox.Flags) & kPcResourceFlagsMask); return pc; } diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 4662577459..48c111a136 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -2483,13 +2483,14 @@ void** get_vtable(); struct StructReturnCall { DeviceProxy* self; void* ret; + bool console_abi; }; StructReturnCall struct_return_call(std::uint64_t a0, std::uint64_t a1) { void** const vtable = get_vtable(); if (a0 && *reinterpret_cast(a0) == vtable) // PC form: this, return buffer - return {reinterpret_cast(a0), reinterpret_cast(a1)}; - return {reinterpret_cast(a1), reinterpret_cast(a0)}; // C form: return buffer, this + return {reinterpret_cast(a0), reinterpret_cast(a1), false}; + return {reinterpret_cast(a1), reinterpret_cast(a0), true}; // C form: return buffer, this } // The console size of a list of descriptions (d3d12_xs_alloc_size.h): the PC device's answer with every console render @@ -2516,8 +2517,8 @@ 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. + // Normalize console descriptors in a copy. PC calls can also pass the Xbox tiled layout explicitly. Otherwise + // their flags and layout reach the host unchanged so the host can validate them. const UINT desc_count = static_cast(count); std::unique_ptr clean; if (descs && desc_count) { @@ -2526,7 +2527,10 @@ void* WINAPI proxy_get_resource_allocation_info(std::uint64_t a0, std::uint64_t *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]); + for (UINT i = 0; i < desc_count; ++i) { + const auto& desc = descs[i]; + clean[i] = call.console_abi || desc.Layout == kXboxTiledResourceLayout ? pc_resource_desc(desc) : desc; + } descs = clean.get(); } const UINT mask = static_cast(visible_mask); diff --git a/runtime/test/device_proxy_test.cpp b/runtime/test/device_proxy_test.cpp index 6b91a7a1f8..05655200f9 100644 --- a/runtime/test/device_proxy_test.cpp +++ b/runtime/test/device_proxy_test.cpp @@ -225,7 +225,11 @@ int main(int argc, char** argv) { const D3D12_RESOURCE_DESC desc = buffer_desc(); D3D12_RESOURCE_ALLOCATION_INFO got{~0ull, ~0ull}; D3D12_RESOURCE_ALLOCATION_INFO* returned = get_alloc_info(&got, device.Get(), 0, 1, &desc); - const D3D12_RESOURCE_ALLOCATION_INFO want = real->GetResourceAllocationInfo(0, 1, &desc); + // The proxy cleans the console layout word and flag bits before the PC call (stop 16), so the expected answer is + // the PC device's for the cleaned description (the raw 0x101 layout makes WARP answer UINT64_MAX). + const D3D12_RESOURCE_DESC clean = rt::d3d12_xs::pc_resource_desc(desc); + const D3D12_RESOURCE_ALLOCATION_INFO want = real->GetResourceAllocationInfo(0, 1, &clean); + check(want.SizeInBytes != UINT64_MAX, "WARP accepts the normalized slot-25 buffer description"); check(returned == &got, "slot 25 returns the caller's buffer in RAX"); check(got.SizeInBytes == want.SizeInBytes && got.Alignment == want.Alignment, "slot 25 (C ABI) writes the PC device's GetResourceAllocationInfo into the caller's buffer"); diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 45055b888b..8acfb67ea7 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -1332,6 +1332,75 @@ 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); + + // PC calls must keep their layout and flags so the host can reject an invalid descriptor. + using PcFn = D3D12_RESOURCE_ALLOCATION_INFO*(WINAPI*)(void*, D3D12_RESOURCE_ALLOCATION_INFO*, UINT, UINT, + const D3D12_RESOURCE_DESC*); + const auto get_pc_info = reinterpret_cast(vtable[25]); + D3D12_RESOURCE_DESC pc_buffer = titles[1]; + pc_buffer.Layout = D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE; + pc_buffer.Flags = static_cast(0x1000); + g_seen_calls = 0; + EXPECT(get_pc_info(device, &info, 0, 1, &pc_buffer) == &info); + EXPECT(g_seen_desc_count == 1 && g_seen_descs[0].Layout == D3D12_TEXTURE_LAYOUT_64KB_UNDEFINED_SWIZZLE); + EXPECT(g_seen_descs[0].Flags == pc_buffer.Flags); + + // A null array with a zero count reaches the PC device as it came. + g_seen_desc_count = 99; + g_seen_calls = 0; + EXPECT(get_info(&info, device, 0, 0, nullptr) == &info && g_seen_calls == 1 && g_seen_desc_count == 0); + + EXPECT(release(device) == 0 && mock->refs == 0); + std::printf("%s: device slot 25 gives the PC device descriptions with PC flags and layout, and the title's own " + "array is not written\n", g_label); + return 0; +} + // ---- 11. Console render target layout: alignment, per-description offsets, mips, formats, overflow ---- int check_render_target_layout() { @@ -1433,63 +1502,6 @@ int check_render_target_layout() { } -// ---- 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) { From 4056d185e7e30c90df32a095cf0d30d93b20d507 Mon Sep 17 00:00:00 2001 From: ASTROWwwW Date: Mon, 23 Nov 2026 19:51:21 +0100 Subject: [PATCH 7/9] ladder: kXboxTiledResourceLayout is inline const, not constexpr (clang-cl rejects 0x101 for the unfixed enum) Reported by YaBulochka and sovljanskii on #7154; #7110's current head has the same form. Co-Authored-By: Claude Opus 5.5 (cherry picked from commit bee47186f68c995b196a5215ccdc5abcf80660e7) --- runtime/shims/d3d12_xs_desc_clean.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/runtime/shims/d3d12_xs_desc_clean.h b/runtime/shims/d3d12_xs_desc_clean.h index 1782b7d880..ba51184a4d 100644 --- a/runtime/shims/d3d12_xs_desc_clean.h +++ b/runtime/shims/d3d12_xs_desc_clean.h @@ -21,7 +21,8 @@ constexpr std::uint32_t kPcResourceFlagsMask = D3D12_RESOURCE_FLAG_VIDEO_DECODE_REFERENCE_ONLY | D3D12_RESOURCE_FLAG_VIDEO_ENCODE_REFERENCE_ONLY | D3D12_RESOURCE_FLAG_RAYTRACING_ACCELERATION_STRUCTURE; -constexpr auto kXboxTiledResourceLayout = static_cast(0x101); +// Not constexpr: 0x101 is outside the unfixed enum's value range, which clang-cl rejects in a constant expression. +inline const auto kXboxTiledResourceLayout = static_cast(0x101); // Strip Xbox-only flags and translate the Xbox tiled layout. Preserve all other layouts so the host can validate them. inline D3D12_RESOURCE_DESC pc_resource_desc(const D3D12_RESOURCE_DESC& xbox) { From c108c5389467128dffc1414e112c8b699e724894 Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:49:26 -0600 Subject: [PATCH 8/9] d3d12_xs: the console render-target sizes of slots 25 and 56 are for console-form calls only With the console tile sizes applied to every caller, a PC-form call through the proxy no longer answered what the PC device answers, and the code that compares the two failed on Windows: device_proxy_test's two slot 25 checks and d3d12_vulkan_device_test's allocation_mismatches (reported on #375 from MSVC builds on AMD and NVIDIA, the first bad commit being the one that cleans the descriptions). Together with b4d1ba179, which scopes the cleaning the same way, a PC-form caller now gets the PC device's own answer for its own description; the title's call, which comes in the console form, gets the cleaned description and the console sizes as before. xs_proxy_mock_test: the PC-form slot 25 case expects the mock device's size (it expected the console size), and the mixed slot 56 case is asked in the console form. device_proxy_test includes d3d12_xs_desc_clean.h for the cleaned description b4d1ba179's check compares with. Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HxBQf4pXH8PWpC5oZsM4bt --- runtime/shims/d3d12_xs_device.cpp | 9 ++++++--- runtime/test/device_proxy_test.cpp | 1 + runtime/test/xs_proxy_mock_test.cpp | 9 +++++---- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index 48c111a136..b0698e153a 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -2535,8 +2535,11 @@ void* WINAPI proxy_get_resource_allocation_info(std::uint64_t a0, std::uint64_t } 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); + // The console tile sizes are the title's: a call in the console form gets them. A PC-form caller (the runtime's + // own code and tests, which compare with the PC device) gets the PC device's answer unchanged. + if (call.console_abi) + apply_console_placement(descs, desc_count, info, nullptr, + [&](UINT i) { return real->GetResourceAllocationInfo(mask, 1, &descs[i]); }, 25); *static_cast(call.ret) = info; return call.ret; } @@ -2557,7 +2560,7 @@ void* WINAPI proxy_get_resource_allocation_info1(std::uint64_t a0, std::uint64_t 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) { + if (each && call.console_abi) { // console sizes for the console form only, as slot 25 auto& info = *static_cast(call.ret); apply_console_placement(descs, n, info, each, [&](UINT i) { return D3D12_RESOURCE_ALLOCATION_INFO{each[i].SizeInBytes, each[i].Alignment}; diff --git a/runtime/test/device_proxy_test.cpp b/runtime/test/device_proxy_test.cpp index 05655200f9..6242d1b526 100644 --- a/runtime/test/device_proxy_test.cpp +++ b/runtime/test/device_proxy_test.cpp @@ -23,6 +23,7 @@ #include #include "d3d12_trace.h" +#include "d3d12_xs_desc_clean.h" #include "d3d12_xs_device.h" #include "shims.h" diff --git a/runtime/test/xs_proxy_mock_test.cpp b/runtime/test/xs_proxy_mock_test.cpp index 8acfb67ea7..fa5f6812af 100644 --- a/runtime/test/xs_proxy_mock_test.cpp +++ b/runtime/test/xs_proxy_mock_test.cpp @@ -1321,10 +1321,11 @@ int check_render_target_sizes() { 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. + // The PC form (this in RCX, the buffer in RDX) is not the title's call: it gets the PC device's own size, 127 + // units of 64 KiB for the mock, so code that compares the proxy with the PC device still agrees. D3D12_RESOURCE_ALLOCATION_INFO pc{}; EXPECT(raw(device, 25, word(&pc), 0, 1, word(&hd)) == word(&pc)); - EXPECT(pc.SizeInBytes == 8847360); + EXPECT(pc.SizeInBytes == 8323072); EXPECT(release(device) == 0 && mock->refs == 0); std::printf("%s: device slot 25 pads render targets to whole console tiles and leaves the other sizes as the PC " @@ -1442,7 +1443,7 @@ int check_render_target_layout() { 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. + // GetResourceAllocationInfo1: the offsets follow the padded sizes, in the console form. const D3D12_RESOURCE_DESC two[] = {hd, hd}; D3D12_RESOURCE_ALLOCATION_INFO1 each[2]{}; D3D12_RESOURCE_ALLOCATION_INFO total{}; @@ -1452,7 +1453,7 @@ int check_render_target_layout() { 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(get_info1(&pc, device, 0, 2, msaa_first, mixed) == &pc); EXPECT(pc.SizeInBytes == 16777216 && pc.Alignment == 4194304); EXPECT(mixed[0].Offset == 0 && mixed[0].SizeInBytes == 4194304 && mixed[0].Alignment == 4194304); EXPECT(mixed[1].Offset == 4194304 && mixed[1].SizeInBytes == 8847360 && mixed[1].Alignment == 65536); From 0c5a14659502a32d84c830880bc2c20aa1562c11 Mon Sep 17 00:00:00 2001 From: Mumogg <104529023+Mumogg@users.noreply.github.com> Date: Tue, 24 Nov 2026 03:49:45 -0600 Subject: [PATCH 9/9] d3d12_xs: the hook-backed descriptor address is not applied to a console-extended heap A heap that main's console-extended handler created already sits at the address the title named, so proxy_create_descriptor_heap asks the title's XMem hooks for a backing address only when the heap came from a plain PC description (follow-up asked for in review on #375). Co-Authored-By: Claude Fable 5.2 Claude-Session: https://claude.ai/code/session_01HxBQf4pXH8PWpC5oZsM4bt --- runtime/shims/d3d12_xs_device.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/runtime/shims/d3d12_xs_device.cpp b/runtime/shims/d3d12_xs_device.cpp index b0698e153a..b66175ac87 100644 --- a/runtime/shims/d3d12_xs_device.cpp +++ b/runtime/shims/d3d12_xs_device.cpp @@ -1800,7 +1800,9 @@ HRESULT proxy_create_descriptor_heap(DeviceProxy* self, const D3D12_DESCRIPTOR_H alloc_fn = g_heap_alloc; free_fn = g_heap_free; } - if (alloc_fn && desc && desc->NumDescriptors > 0) { + // A heap the console-extended handler made already sits at the address the title named: the hook-backed address + // is for a heap made from a plain PC description only. + if (!console_extended && alloc_fn && desc && desc->NumDescriptors > 0) { const UINT inc = self->real->GetDescriptorHandleIncrementSize(desc->Type); if (inc > 0 && desc->NumDescriptors <= (std::numeric_limits::max)() / inc) { const SIZE_T byte_size = static_cast(desc->NumDescriptors) * static_cast(inc);