Compare commits

...
Author SHA1 Message Date
atharvranjan b096424f33 d3d12_xs: fix presentation timeout semantics and strengthen the frame test
Present now waits for the current buffer before calling the host, so
ERROR_TIMEOUT means nothing was presented. A timeout after the host
Present returns BX_PRESENT_E_NEXT_BUFFER_BUSY. WaitForIdle counts lock
acquisition against its timeout, and same-thread re-entry is refused. The
leak-on-timeout path now returns the queue proxy reference.

The fixture checks host buffer identity, per-frame present counts, both
timeout results, the leak path, rejection log records and the swapchain
release count against a host-only control. run_controls.sh checks each
negative control's failing stage.

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 14:33:13 -06:00
atharvranjan f2af367da6 [M2-C2] d3d12_xs: add a swapchain presentation bridge and frame conformance test
The proxied command queue answers a BetterXen-defined IID with a tear-off
that creates a flip-model swapchain on a Win32 window over the host's
IDXGISwapChain3. This is not the console's PresentX and claims no binary
compatibility with it. No export or abi/ file changes.

The bridge waits (bounded) for the next back buffer, waits for the GPU
before releasing, and refuses presents that D3DMetal 3.0 was observed to
accept with S_OK (sync interval above 4, any flag, destroyed window).

test_d3d12_presentx renders and presents 12 frames, checks every read-back
pixel against CPU-computed values, and compares swapchain lifetime with a
host-DXGI control.

Refs #465

Signed-off-by: Arths17 <Atharvranjan8@gmail.com>
2026-11-26 12:46:56 -06:00
8 changed files with 1663 additions and 0 deletions

No files matched your search

+5
View File
@@ -12,6 +12,11 @@ remains unsupported.
### Added
- Updated `README.md` and `docs/roadmap.md` to record Milestone M0 and Milestone M1 (`#17`, 16/16 issues) as verified complete on synthetic workloads and activate Milestone M2 (`#18`, First Rendered Frame & Shader Format Gate).
- Implemented clean-room COM `IUnknown` vtable dispatch in `xgameruntime.dll!QueryApiImpl` for the core public Microsoft PC GDK (`Microsoft.GDK.Windows 2610.0.9661`) interface families (`XAsync`/`XTaskQueue`/`XThread`, `XGameRuntimeIsFeatureAvailable`, `XSystem`, `XError`, `XPersistentLocalStorage`, `XUser`, `XStore`, `XGameUi`, `XNetworking`, `XGame`), with auto-logging `BX_VTABLE_STUB_LOG` fallback on unimplemented slots. Validated live on CrossOver 26.3 with an independently authored caller linked against Microsoft's public `xgameruntime.lib` (#456).
- `d3d12_xs.dll` can present rendered frames through a swapchain (#465, M2-C2). A caller asks the proxied command queue for a BetterXen-defined interface (`IBxPresentQueue`, in `shims/d3d12_xs/presentx.h`) and creates a flip-model swapchain on a Win32 window over the host's `IDXGISwapChain3`. This is not the console's `PresentX`: its signature is not defined in `abi/`, and no binary compatibility is claimed. No export or `abi/` file changed.
- **Behaviour:** `Present` signals a fence and waits, for at most 5 s, until the next back buffer is idle; if that wait expires it returns `BX_PRESENT_E_NEXT_BUFFER_BUSY`, meaning the frame was presented and must not be presented again. `ERROR_TIMEOUT` from `Present` means nothing was presented. `WaitForIdle` takes a finite timeout that includes waiting behind another thread's `Present`, and re-entering either call on one thread is refused. The final `Release` waits for the GPU and, if it cannot confirm completion, logs and leaks what pending GPU work may still touch, while releasing its queue proxy reference. Resizing and fullscreen are not implemented, and the caller records its own resource transitions.
- **Stricter than the host:** D3DMetal 3.0 returned `S_OK` for sync intervals 5 and 100, unsupported flags and a destroyed window, so the bridge itself refuses a sync interval above 4, any present flag and a destroyed window with `DXGI_ERROR_INVALID_CALL`.
- **Test:** `tests/conformance/test_d3d12_presentx/` renders and presents 12 frames (a clear plus a scissored shader draw) and compares all 72,000 read-back pixels with values computed on the CPU. It also checks that the bridge's buffers and index are the host swapchain's, that each present advances the host count by one, argument rejection and its log records, bounded waits and the leak path with the queue deliberately blocked, and reference lifetime against a swapchain made with host DXGI alone. `run_controls.sh` checks the failing stage of each negative control. It reads the back buffer before presentation; it does not capture the window.
- **Local result:** on one Apple M4 (macOS 27.0, CrossOver 26.3.0.39832, D3DMetal 3.0), `bx-cli run --bottle … --backend d3dmetal --timeout 30` passed 296 checks with 0 skipped. D3DMetal kept all 4 of 4 swapchains referenced after release, both through the bridge and in the host-only control, which matches the earlier recorded observation. On the `wined3d` (vkd3d) setting the pixels were also correct, but some runs of the first version stalled inside the host swapchain's final `Release`; this revision was not rerun on it. Not independently reproduced, and not an Xbox hardware result.
- `bx-cli run` now stages the shims a guest loads by system-directory search into the prefix's or bottle's `drive_c/windows/system32` before launch (#457). GDK titles load `xgameruntime.dll` with `LoadLibraryExW(..., LOAD_LIBRARY_SEARCH_SYSTEM32)`, which never searches `WINEPATH`. The bootstrap therefore reported `E_GAMERUNTIME_DLL_NOT_FOUND` before the #441 loader exports could be reached.
- **What is staged:** `xgameruntime.dll` and, found through `bx-probe`, every BetterXen shim it imports (today `bx_runtime_veh.dll`). The same restricted search applies to a DLL's own imports, so staging the runtime alone fails unless the guest happened to load the logger first.
- **How:** copies are idempotent: an identical file is left alone, a different one is replaced through a rename. `bx-cli` prints what it staged.
+1
View File
@@ -1,5 +1,6 @@
bx_add_shim_dll(d3d12_xs d3d12_xs d3d12_xs.def
d3d12_xs.cpp
presentx.cpp
proxy.cpp
proxy_generated.cpp
)
+489
View File
@@ -0,0 +1,489 @@
#include "presentx.h"
#include <atomic>
#include <cstdio>
#include <new>
#include "proxy.h"
/*
* Track C (M2-C2, #465). See presentx.h for the contract and for what this is not.
* Host DXGI is loaded on demand, like the host d3d12.dll in d3d12_xs.cpp.
*/
namespace {
constexpr HRESULT kWaitTimedOut = static_cast<HRESULT>(0x800705B4u); /* HRESULT_FROM_WIN32(ERROR_TIMEOUT) */
void log_hr(bx_log_level_t level, const char* event, const char* what, HRESULT hr) {
char detail[160];
std::snprintf(detail, sizeof(detail), "%s hr=0x%08lx", what, static_cast<unsigned long>(hr));
bx_log_emit(level, "d3d12_xs", event, detail);
}
/* Releases an already acquired lock and records its owner, so re-entry can be refused. */
class SrwOwner {
public:
SrwOwner(SRWLOCK& lock, std::atomic<DWORD>& owner) : lock_(lock), owner_(owner) { owner_ = GetCurrentThreadId(); }
~SrwOwner() {
owner_ = 0;
ReleaseSRWLockExclusive(&lock_);
}
SrwOwner(const SrwOwner&) = delete;
SrwOwner& operator=(const SrwOwner&) = delete;
private:
SRWLOCK& lock_;
std::atomic<DWORD>& owner_;
};
class BxPresentSwapChain final : public IBxPresentSwapChain {
public:
/* `queue_proxy` is referenced for the lifetime of the chain; `host_queue` is its host object. */
static HRESULT create(ID3D12CommandQueue* queue_proxy, ID3D12CommandQueue* host_queue, HWND window,
const BxPresentDesc& desc, IBxPresentSwapChain** out);
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override;
ULONG STDMETHODCALLTYPE AddRef() override;
ULONG STDMETHODCALLTYPE Release() override;
HRESULT STDMETHODCALLTYPE GetBuffer(UINT index, REFIID riid, void** ppv) override;
UINT STDMETHODCALLTYPE GetCurrentBackBufferIndex() override;
HRESULT STDMETHODCALLTYPE Present(UINT sync_interval, UINT flags) override;
HRESULT STDMETHODCALLTYPE WaitForIdle(DWORD timeout_ms) override;
HRESULT STDMETHODCALLTYPE GetHostSwapChain(REFIID riid, void** ppv) override;
private:
BxPresentSwapChain() = default;
~BxPresentSwapChain() = default;
HRESULT init(HWND window, const BxPresentDesc& desc);
HRESULT signal_locked(UINT64* value);
HRESULT wait_locked(UINT64 value, DWORD timeout_ms);
HRESULT idle_locked(DWORD timeout_ms);
HRESULT removed_reason();
void destroy();
std::atomic<ULONG> refs_{1};
SRWLOCK lock_ = SRWLOCK_INIT; /* guards the fence counter, the event and Present */
ID3D12CommandQueue* queue_proxy_ = nullptr;
ID3D12CommandQueue* host_queue_ = nullptr;
HWND window_ = nullptr;
IDXGISwapChain3* swap_ = nullptr;
ID3D12Fence* fence_ = nullptr;
HANDLE event_ = nullptr;
std::atomic<DWORD> owner_{0}; /* thread holding lock_ */
UINT64 last_signaled_ = 0;
UINT64 presented_ = 0;
UINT64 buffer_value_[DXGI_MAX_SWAP_CHAIN_BUFFERS] = {};
};
HRESULT BxPresentSwapChain::create(ID3D12CommandQueue* queue_proxy, ID3D12CommandQueue* host_queue, HWND window,
const BxPresentDesc& desc, IBxPresentSwapChain** out) {
auto* self = new (std::nothrow) BxPresentSwapChain();
if (!self) {
return E_OUTOFMEMORY;
}
queue_proxy->AddRef();
self->queue_proxy_ = queue_proxy;
host_queue->AddRef();
self->host_queue_ = host_queue;
self->window_ = window;
HRESULT hr = self->init(window, desc);
if (FAILED(hr)) {
self->destroy(); /* nothing was submitted, so every partially created object can go */
return hr;
}
*out = self;
return S_OK;
}
HRESULT BxPresentSwapChain::init(HWND window, const BxPresentDesc& desc) {
static HMODULE dxgi = LoadLibraryA("dxgi.dll");
using CreateFactoryFn = HRESULT(WINAPI*)(REFIID, void**);
auto create_factory = dxgi
? reinterpret_cast<CreateFactoryFn>(reinterpret_cast<void*>(GetProcAddress(dxgi, "CreateDXGIFactory1")))
: nullptr;
if (!create_factory) {
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_dxgi_missing", "dxgi.dll!CreateDXGIFactory1 not available");
return DXGI_ERROR_UNSUPPORTED;
}
IDXGIFactory4* factory = nullptr;
HRESULT hr = create_factory(__uuidof(IDXGIFactory4), reinterpret_cast<void**>(&factory));
if (FAILED(hr)) {
log_hr(BX_LOG_ERROR, "present_create_failed", "CreateDXGIFactory1", hr);
return hr;
}
DXGI_SWAP_CHAIN_DESC1 sd = {};
sd.Width = desc.width;
sd.Height = desc.height;
sd.Format = desc.format;
sd.SampleDesc.Count = 1;
sd.BufferUsage = DXGI_USAGE_RENDER_TARGET_OUTPUT;
sd.BufferCount = desc.buffer_count;
sd.SwapEffect = DXGI_SWAP_EFFECT_FLIP_DISCARD;
IDXGISwapChain1* swap1 = nullptr;
/* For D3D12 the "device" argument of CreateSwapChainForHwnd is the command queue. */
hr = factory->CreateSwapChainForHwnd(host_queue_, window, &sd, nullptr, nullptr, &swap1);
if (SUCCEEDED(hr)) {
/* Alt+Enter would require ResizeBuffers handling that the bridge does not have. */
HRESULT assoc = factory->MakeWindowAssociation(window, DXGI_MWA_NO_ALT_ENTER);
if (FAILED(assoc)) {
log_hr(BX_LOG_WARN, "present_window_association", "MakeWindowAssociation", assoc);
}
}
factory->Release();
if (FAILED(hr)) {
log_hr(BX_LOG_ERROR, "present_create_failed", "CreateSwapChainForHwnd", hr);
return hr;
}
hr = swap1->QueryInterface(__uuidof(IDXGISwapChain3), reinterpret_cast<void**>(&swap_));
swap1->Release();
if (FAILED(hr)) {
log_hr(BX_LOG_ERROR, "present_create_failed", "QueryInterface(IDXGISwapChain3)", hr);
return hr;
}
ID3D12Device* device = nullptr;
hr = host_queue_->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
if (SUCCEEDED(hr)) {
hr = device->CreateFence(0, D3D12_FENCE_FLAG_NONE, __uuidof(ID3D12Fence), reinterpret_cast<void**>(&fence_));
device->Release();
}
if (FAILED(hr)) {
log_hr(BX_LOG_ERROR, "present_create_failed", "CreateFence", hr);
return hr;
}
event_ = CreateEventA(nullptr, FALSE, FALSE, nullptr);
if (!event_) {
hr = HRESULT_FROM_WIN32(GetLastError());
log_hr(BX_LOG_ERROR, "present_create_failed", "CreateEvent", hr);
return hr;
}
char detail[128];
std::snprintf(detail, sizeof(detail), "width=%u height=%u format=%d buffers=%u",
desc.width, desc.height, static_cast<int>(desc.format), desc.buffer_count);
bx_log_emit(BX_LOG_INFO, "d3d12_xs", "present_chain_created", detail);
return S_OK;
}
HRESULT BxPresentSwapChain::removed_reason() {
ID3D12Device* device = nullptr;
HRESULT hr = host_queue_->GetDevice(__uuidof(ID3D12Device), reinterpret_cast<void**>(&device));
if (FAILED(hr)) {
return hr;
}
hr = device->GetDeviceRemovedReason();
device->Release();
return hr;
}
HRESULT BxPresentSwapChain::signal_locked(UINT64* value) {
const UINT64 next = last_signaled_ + 1;
HRESULT hr = host_queue_->Signal(fence_, next);
if (FAILED(hr)) {
log_hr(BX_LOG_ERROR, "present_signal_failed", "ID3D12CommandQueue::Signal", hr);
return hr;
}
last_signaled_ = next;
*value = next;
return S_OK;
}
HRESULT BxPresentSwapChain::wait_locked(UINT64 value, DWORD timeout_ms) {
const ULONGLONG start = GetTickCount64();
for (;;) {
const UINT64 completed = fence_->GetCompletedValue();
if (completed == UINT64_MAX) { /* the documented value after device removal */
HRESULT reason = removed_reason();
log_hr(BX_LOG_ERROR, "present_device_removed", "fence", reason);
return FAILED(reason) ? reason : DXGI_ERROR_DEVICE_REMOVED;
}
if (completed >= value) {
return S_OK;
}
const ULONGLONG elapsed = GetTickCount64() - start;
if (elapsed >= timeout_ms) {
break;
}
HRESULT hr = fence_->SetEventOnCompletion(value, event_);
if (FAILED(hr)) {
log_hr(BX_LOG_ERROR, "present_wait_failed", "SetEventOnCompletion", hr);
return hr;
}
/* The event can be left over from an earlier timed-out wait, so the loop re-reads the fence. */
DWORD waited = WaitForSingleObject(event_, static_cast<DWORD>(timeout_ms - elapsed));
if (waited == WAIT_FAILED) {
hr = HRESULT_FROM_WIN32(GetLastError());
log_hr(BX_LOG_ERROR, "present_wait_failed", "WaitForSingleObject", hr);
return hr;
}
}
char detail[128];
std::snprintf(detail, sizeof(detail), "timeout_ms=%lu wanted=%llu completed=%llu", static_cast<unsigned long>(timeout_ms),
static_cast<unsigned long long>(value), static_cast<unsigned long long>(fence_->GetCompletedValue()));
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_wait_timeout", detail);
return kWaitTimedOut;
}
HRESULT BxPresentSwapChain::idle_locked(DWORD timeout_ms) {
UINT64 value = 0;
HRESULT hr = signal_locked(&value);
return FAILED(hr) ? hr : wait_locked(value, timeout_ms);
}
void BxPresentSwapChain::destroy() {
if (swap_ && fence_ && event_) {
HRESULT idle = idle_locked(BX_PRESENT_WAIT_MS);
if (FAILED(idle) && SUCCEEDED(removed_reason())) {
/* The device is alive and the GPU may still be using the back buffers. */
log_hr(BX_LOG_ERROR, "present_chain_leaked", "queue not idle; GPU-visible objects deliberately not released", idle);
/*
* swap_, fence_, event_ and host_queue_ stay: pending work may touch them. The proxy
* is only BetterXen's wrapper; host_queue_ keeps the host queue alive without it.
*/
ID3D12CommandQueue* proxy = queue_proxy_;
delete this;
proxy->Release();
return;
}
}
const bool had_swap = swap_ != nullptr;
ULONG swap_refs = 0;
if (swap_) swap_refs = swap_->Release();
if (fence_) fence_->Release();
if (event_) CloseHandle(event_);
if (had_swap) {
/*
* The count the host's Release returned. Non-zero means something else still references
* the swapchain: back buffers or host pointers the caller holds, or the host itself
* (see docs/research/d3dmetal-swapchain-references.md). It is reported, never "fixed up"
* by releasing references this object does not own.
*/
char detail[96];
std::snprintf(detail, sizeof(detail), "presented=%llu swapchain_release_returned=%lu",
static_cast<unsigned long long>(presented_), static_cast<unsigned long>(swap_refs));
bx_log_emit(swap_refs ? BX_LOG_WARN : BX_LOG_INFO, "d3d12_xs", "present_chain_destroyed", detail);
}
ID3D12CommandQueue* host_queue = host_queue_;
ID3D12CommandQueue* queue_proxy = queue_proxy_;
delete this;
if (host_queue) host_queue->Release();
if (queue_proxy) queue_proxy->Release();
}
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::QueryInterface(REFIID riid, void** ppv) {
if (!ppv) {
return E_POINTER;
}
if (IsEqualGUID(riid, __uuidof(IUnknown)) || IsEqualGUID(riid, IID_IBxPresentSwapChain)) {
AddRef();
*ppv = static_cast<IBxPresentSwapChain*>(this);
return S_OK;
}
*ppv = nullptr;
return E_NOINTERFACE;
}
ULONG STDMETHODCALLTYPE BxPresentSwapChain::AddRef() {
return refs_.fetch_add(1, std::memory_order_relaxed) + 1;
}
ULONG STDMETHODCALLTYPE BxPresentSwapChain::Release() {
ULONG left = refs_.fetch_sub(1, std::memory_order_acq_rel) - 1;
if (left == 0) {
destroy();
}
return left;
}
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::GetBuffer(UINT index, REFIID riid, void** ppv) {
if (!ppv) {
return E_POINTER;
}
*ppv = nullptr;
HRESULT hr = swap_->GetBuffer(index, riid, ppv);
if (FAILED(hr)) {
log_hr(BX_LOG_WARN, "present_get_buffer_failed", "IDXGISwapChain::GetBuffer", hr);
}
return hr;
}
UINT STDMETHODCALLTYPE BxPresentSwapChain::GetCurrentBackBufferIndex() {
return swap_->GetCurrentBackBufferIndex();
}
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::Present(UINT sync_interval, UINT flags) {
BX_D3D_TRACE("IBxPresentSwapChain", "Present");
if (sync_interval > 4 || flags != 0 || !IsWindow(window_)) {
char detail[96];
std::snprintf(detail, sizeof(detail), "sync=%u flags=0x%x window_alive=%d", sync_interval, flags,
IsWindow(window_) ? 1 : 0);
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "present_rejected", detail);
return DXGI_ERROR_INVALID_CALL;
}
if (owner_ == GetCurrentThreadId()) {
bx_log_emit(BX_LOG_WARN, "d3d12_xs", "present_rejected", "re-entered on the same thread");
return DXGI_ERROR_INVALID_CALL;
}
AcquireSRWLockExclusive(&lock_);
SrwOwner guard(lock_, owner_);
const UINT presented_index = swap_->GetCurrentBackBufferIndex();
if (presented_index < DXGI_MAX_SWAP_CHAIN_BUFFERS) {
/* Busy only after an earlier BX_PRESENT_E_NEXT_BUFFER_BUSY. Nothing is presented then. */
const HRESULT ready = wait_locked(buffer_value_[presented_index], BX_PRESENT_WAIT_MS);
if (FAILED(ready)) {
return ready;
}
}
HRESULT hr = swap_->Present(sync_interval, flags);
if (FAILED(hr)) {
char detail[128];
std::snprintf(detail, sizeof(detail), "sync=%u flags=0x%x hr=0x%08lx device_removed_reason=0x%08lx", sync_interval,
flags, static_cast<unsigned long>(hr), static_cast<unsigned long>(removed_reason()));
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_failed", detail);
return hr;
}
++presented_;
UINT64 value = 0;
HRESULT sync_hr = signal_locked(&value);
if (FAILED(sync_hr)) {
return sync_hr;
}
if (presented_index < DXGI_MAX_SWAP_CHAIN_BUFFERS) {
buffer_value_[presented_index] = value;
}
const UINT next = swap_->GetCurrentBackBufferIndex();
if (next < DXGI_MAX_SWAP_CHAIN_BUFFERS) {
sync_hr = wait_locked(buffer_value_[next], BX_PRESENT_WAIT_MS);
if (FAILED(sync_hr)) {
return sync_hr == kWaitTimedOut ? BX_PRESENT_E_NEXT_BUFFER_BUSY : sync_hr;
}
}
return hr;
}
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::WaitForIdle(DWORD timeout_ms) {
if (timeout_ms == INFINITE) {
return E_INVALIDARG;
}
if (owner_ == GetCurrentThreadId()) {
return DXGI_ERROR_INVALID_CALL;
}
const ULONGLONG start = GetTickCount64();
while (!TryAcquireSRWLockExclusive(&lock_)) {
if (GetTickCount64() - start >= timeout_ms) {
bx_log_emit(BX_LOG_ERROR, "d3d12_xs", "present_wait_timeout", "swapchain busy in another call");
return kWaitTimedOut;
}
Sleep(1);
}
SrwOwner guard(lock_, owner_);
const ULONGLONG spent = GetTickCount64() - start;
return idle_locked(spent < timeout_ms ? static_cast<DWORD>(timeout_ms - spent) : 0);
}
HRESULT STDMETHODCALLTYPE BxPresentSwapChain::GetHostSwapChain(REFIID riid, void** ppv) {
if (!ppv) {
return E_POINTER;
}
*ppv = nullptr;
return swap_->QueryInterface(riid, ppv);
}
bool desc_is_valid(const BxPresentDesc& d) {
const bool format_ok = d.format == DXGI_FORMAT_R8G8B8A8_UNORM || d.format == DXGI_FORMAT_B8G8R8A8_UNORM ||
d.format == DXGI_FORMAT_R10G10B10A2_UNORM || d.format == DXGI_FORMAT_R16G16B16A16_FLOAT;
return format_ok && d.width >= 1 && d.width <= D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION && d.height >= 1 &&
d.height <= D3D12_REQ_TEXTURE2D_U_OR_V_DIMENSION && d.buffer_count >= 2 &&
d.buffer_count <= DXGI_MAX_SWAP_CHAIN_BUFFERS;
}
/* COM tear-off: its own reference count, one reference on the queue, and the queue's identity. */
class BxPresentQueue final : public IBxPresentQueue {
public:
explicit BxPresentQueue(ID3D12CommandQueue* queue_proxy) : queue_(queue_proxy) { queue_->AddRef(); }
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** ppv) override {
if (!ppv) {
return E_POINTER;
}
if (IsEqualGUID(riid, IID_IBxPresentQueue)) {
AddRef();
*ppv = static_cast<IBxPresentQueue*>(this);
return S_OK;
}
return queue_->QueryInterface(riid, ppv);
}
ULONG STDMETHODCALLTYPE AddRef() override { return refs_.fetch_add(1, std::memory_order_relaxed) + 1; }
ULONG STDMETHODCALLTYPE Release() override {
ULONG left = refs_.fetch_sub(1, std::memory_order_acq_rel) - 1;
if (left == 0) {
ID3D12CommandQueue* queue = queue_;
delete this;
queue->Release();
}
return left;
}
HRESULT STDMETHODCALLTYPE CreateSwapChain(HWND window, const BxPresentDesc* desc, IBxPresentSwapChain** out) override {
if (!out) {
return E_POINTER;
}
*out = nullptr;
if (!desc) {
return E_POINTER;
}
if (!window || !IsWindow(window) || !desc_is_valid(*desc)) {
log_hr(BX_LOG_WARN, "present_create_rejected", "invalid window or description", DXGI_ERROR_INVALID_CALL);
return DXGI_ERROR_INVALID_CALL;
}
ID3D12CommandQueue* host = nullptr;
HRESULT hr = static_cast<IUnknown*>(bx_unwrap_raw(queue_))
->QueryInterface(__uuidof(ID3D12CommandQueue), reinterpret_cast<void**>(&host));
if (FAILED(hr)) {
log_hr(BX_LOG_ERROR, "present_create_failed", "host command queue", hr);
return hr;
}
D3D12_COMMAND_QUEUE_DESC queue_desc = {};
host->GetDesc(&queue_desc);
if (queue_desc.Type != D3D12_COMMAND_LIST_TYPE_DIRECT) {
log_hr(BX_LOG_WARN, "present_create_rejected", "queue is not a DIRECT queue", DXGI_ERROR_INVALID_CALL);
hr = DXGI_ERROR_INVALID_CALL;
} else {
hr = BxPresentSwapChain::create(queue_, host, window, *desc, out);
}
host->Release();
return hr;
}
private:
~BxPresentQueue() = default;
std::atomic<ULONG> refs_{1};
ID3D12CommandQueue* queue_;
};
} // namespace
HRESULT bx_present_query_queue(ID3D12CommandQueue* queue_proxy, void** ppv) {
if (!ppv) {
return E_POINTER;
}
auto* bridge = new (std::nothrow) BxPresentQueue(queue_proxy);
if (!bridge) {
*ppv = nullptr;
return E_OUTOFMEMORY;
}
*ppv = static_cast<IBxPresentQueue*>(bridge);
return S_OK;
}
+101
View File
@@ -0,0 +1,101 @@
#ifndef BETTERXEN_D3D12_XS_PRESENTX_H
#define BETTERXEN_D3D12_XS_PRESENTX_H
/*
* Track C (M2-C2, #465): the PresentX presentation bridge over host DXGI.
*
* THESE INTERFACES ARE DEFINED BY BETTERXEN. They are not the console's PresentX, whose
* signature and structures are not defined in abi/, and no binary compatibility with any Xbox
* interface is claimed. A guest that calls a console-only command queue slot still lands on the
* proxy's logged stub.
*
* Use: QueryInterface the command queue returned by a D3D12XboxCreateDevice device for
* IID_IBxPresentQueue, then create a swapchain on a Win32 window. No new DLL export is involved.
*
* This is a subset of the public DXGI flip model, not all of it: the caller records its own
* resource transitions and every back buffer must be in D3D12_RESOURCE_STATE_PRESENT when it is
* presented. D3D12 offers no way to query a resource's state, so the bridge cannot check this.
* ResizeBuffers and fullscreen are not implemented.
*/
#ifndef WIDL_EXPLICIT_AGGREGATE_RETURNS
#define WIDL_EXPLICIT_AGGREGATE_RETURNS
#endif
#include <windows.h>
#include <unknwn.h>
#include <d3d12.h>
#include <dxgi1_4.h>
/* {34127279-2D93-4642-88A6-97B834217B8A} */
inline const GUID IID_IBxPresentQueue = {0x34127279, 0x2d93, 0x4642, {0x88, 0xa6, 0x97, 0xb8, 0x34, 0x21, 0x7b, 0x8a}};
/* {DEC9F73E-DE84-4F87-9167-26203B3A1152} */
inline const GUID IID_IBxPresentSwapChain = {0xdec9f73e, 0xde84, 0x4f87, {0x91, 0x67, 0x26, 0x20, 0x3b, 0x3a, 0x11, 0x52}};
/* Longest single GPU wait Present() performs, and the destructor's wait for the GPU. */
inline constexpr DWORD BX_PRESENT_WAIT_MS = 5000;
/*
* Present() result: the frame WAS handed to the host, but the next back buffer is still busy.
* Do not present that frame again. Call WaitForIdle until it returns S_OK before reusing a buffer.
*/
inline constexpr HRESULT BX_PRESENT_E_NEXT_BUFFER_BUSY = static_cast<HRESULT>(0x80040201u);
struct BxPresentDesc {
UINT width; /* 1..16384; 0 ("use the window size") is not accepted */
UINT height; /* 1..16384 */
DXGI_FORMAT format; /* R8G8B8A8_UNORM, B8G8R8A8_UNORM, R10G10B10A2_UNORM or R16G16B16A16_FLOAT */
UINT buffer_count; /* 2..DXGI_MAX_SWAP_CHAIN_BUFFERS */
};
/*
* One swapchain. Holds a reference on the command queue it was created from.
* The final Release waits (bounded) for the queue to go idle. If that fails and the device
* reports it has not been removed, it logs and deliberately leaks what pending GPU work may
* still touch (swapchain, fence, event, host queue) and releases its queue proxy reference.
* After device removal everything is released. Time spent inside the host's own Release is not bounded: on the
* wined3d/vkd3d path (not D3DMetal) an intermittent stall in it was observed.
*/
struct IBxPresentSwapChain : public IUnknown {
/* Same rules as IDXGISwapChain::GetBuffer. The caller owns the returned reference. */
virtual HRESULT STDMETHODCALLTYPE GetBuffer(UINT index, REFIID riid, void** ppv) = 0;
virtual UINT STDMETHODCALLTYPE GetCurrentBackBufferIndex() = 0;
/*
* Waits (bounded) until the current back buffer is idle, calls IDXGISwapChain::Present,
* signals a fence on the queue, then waits until the next back buffer is idle. Results:
* - a DXGI success code, including DXGI_STATUS_OCCLUDED: presented, next buffer idle;
* - HRESULT_FROM_WIN32(ERROR_TIMEOUT): NOT presented (the current buffer is still busy);
* - BX_PRESENT_E_NEXT_BUFFER_BUSY: presented, see its definition;
* - another failure: the host's Present failure, or a fence or device failure. A fence
* or device failure can follow a successful host Present.
* The bounds cover BetterXen's own waits, not time spent inside the host's Present.
*
* The bridge itself returns DXGI_ERROR_INVALID_CALL, without calling the host, for a
* sync_interval above 4, for any flag (none is supported, including DXGI_PRESENT_TEST),
* once the window is destroyed, and when Present or WaitForIdle is re-entered on a thread
* already inside one of them. D3DMetal 3.0 was observed to answer S_OK to the first three.
*/
virtual HRESULT STDMETHODCALLTYPE Present(UINT sync_interval, UINT flags) = 0;
/*
* Waits until everything submitted to the queue before this call has finished.
* INFINITE is rejected with E_INVALIDARG; a timeout returns HRESULT_FROM_WIN32(ERROR_TIMEOUT).
* timeout_ms includes any time spent waiting for a Present on another thread.
*/
virtual HRESULT STDMETHODCALLTYPE WaitForIdle(DWORD timeout_ms) = 0;
/*
* The host DXGI swapchain, for diagnostics and tests. The caller owns the reference and must
* not call Present or ResizeBuffers on it: the bridge's buffer tracking would not follow.
*/
virtual HRESULT STDMETHODCALLTYPE GetHostSwapChain(REFIID riid, void** ppv) = 0;
};
/* Tear-off on the command queue proxy; QueryInterface for any other IID returns the queue's answer. */
struct IBxPresentQueue : public IUnknown {
/*
* The queue must be a DIRECT queue and `window` an existing window. Argument errors return
* E_POINTER or DXGI_ERROR_INVALID_CALL; host failures are returned unchanged and logged.
*/
virtual HRESULT STDMETHODCALLTYPE CreateSwapChain(HWND window, const BxPresentDesc* desc, IBxPresentSwapChain** out) = 0;
};
/* Internal to d3d12_xs.dll: the command queue proxy answers IID_IBxPresentQueue with this. */
HRESULT bx_present_query_queue(ID3D12CommandQueue* queue_proxy, void** ppv);
#endif /* BETTERXEN_D3D12_XS_PRESENTX_H */
+8
View File
@@ -3,6 +3,9 @@
#include <cstdio>
#include <cstring>
#include <new>
#include <type_traits>
#include "presentx.h"
/* {6B1D5C0E-2F4A-4E0B-9A57-3C0E5D7B1A42}: private to this DLL, never handed to a host object. */
const GUID IID_BxProxyHost = {0x6b1d5c0e, 0x2f4a, 0x4e0b, {0x9a, 0x57, 0x3c, 0x0e, 0x5d, 0x7b, 0x1a, 0x42}};
@@ -458,6 +461,11 @@ HRESULT STDMETHODCALLTYPE BxChildProxy<Gen>::QueryInterface(REFIID riid, void**
*ppv = static_cast<Gen*>(this);
return S_OK;
}
if constexpr (std::is_same_v<Gen, BxCommandQueueProxyImpl>) {
if (IsEqualGUID(riid, IID_IBxPresentQueue)) {
return bx_present_query_queue(this, ppv); /* BetterXen's presentation bridge, presentx.h */
}
}
return query_host_unproxied(host_identity_, Gen::kLeafName, riid, ppv);
}
@@ -0,0 +1,4 @@
# M2-C2 (#465): rendered frames through d3d12_xs.dll's presentation bridge, verified by readback.
add_executable(test_d3d12_presentx main.cpp)
target_include_directories(test_d3d12_presentx PRIVATE "${BX_ABI_INCLUDE_DIR}" "${BX_ROOT_DIR}/shims/d3d12_xs")
target_link_libraries(test_d3d12_presentx PRIVATE d3d12_xs bx_runtime_veh user32 kernel32)
File diff suppressed because it is too large. Load diff
+52
View File
@@ -0,0 +1,52 @@
#!/bin/sh
# SPDX-License-Identifier: GPL-3.0-or-later
#
# Runs test_d3d12_presentx once normally and once per negative control, and checks that each
# control fails in its own stage with its own evidence. Needs build-shims/ and bx-cli built.
# Usage (from the repository root): tests/conformance/test_d3d12_presentx/run_controls.sh <bottle>
set -u
bottle=${1:?usage: run_controls.sh <d3dmetal_bottle>}
dir=$(mktemp -d) || exit 1
bad=0
run() { # name injection
BX_PRESENTX_INJECT=$2 target/debug/bx-cli run --inherit-env --bottle "$bottle" --backend d3dmetal \
--shims build-shims/bin --log "$dir/$1.jsonl" --timeout 90 \
--exe build-shims/bin/test_d3d12_presentx.exe >"$dir/$1.out" 2>&1
status=$?
}
expect() { # name file pattern
grep -aq -- "$3" "$dir/$1.$2" || { echo "$1: missing in $2: $3"; bad=1; }
}
must_fail() { # name stage
[ "$status" -ne 0 ] || { echo "$1: exited 0"; bad=1; }
expect "$1" out "first failing stage: $2)"
}
run normal ""
[ "$status" -eq 0 ] || { echo "normal: exit $status"; bad=1; }
expect normal out "^PASS: test_d3d12_presentx (.* 0 skipped)"
run bad-window bad-window
must_fail bad-window create
expect bad-window out "FAIL \[create\]: CreateSwapChain hr=0x887a0001"
# The contract stage logs seven argument rejections; the injected window must add the eighth.
n=$(grep -ac '"event":"present_create_rejected".*invalid window or description' "$dir/bad-window.jsonl")
[ "$n" -eq 8 ] || { echo "bad-window: $n argument rejections logged, expected 8"; bad=1; }
run skip-draw skip-draw
must_fail skip-draw pixels
expect skip-draw out "frame 5: 2432 of 6000 pixels differ"
expect skip-draw out "pixels_wrong=2432 "
run wrong-expectation wrong-expectation
must_fail wrong-expectation pixels
expect wrong-expectation out "pixels_wrong=29184 "
if [ "$bad" -ne 0 ]; then
echo "FAIL: run_controls (output kept in $dir)"
exit 1
fi
rm -rf "$dir"
echo "PASS: run_controls (1 normal run, 3 negative controls)"