Compare commits

..
Author SHA1 Message Date
ates 058bc981dc Merge main and address PR #429 review findings
- Reject ApuAlloc before ApuCreateHeap is called and reset used=0 explicitly on heap creation
- Validate max_streams > 0 and record it on DSP connections in XDspConnectWithMaximumStreamLimit
- Expand test_audio_input to cover pre-heap ApuAlloc failure, single-output ApuAlloc, zero max_streams rejection, and GameInput v0 QueryInterface/method dispatch
- Resolve CHANGELOG.md merge conflict with main

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 18:08:53 +03:00
Ateş d8b83818c1 Merge pull request #430 from MacosPorters/track-a/409-veh-clwb-crash-log
[M1-A2] Cover CLWB addressing and log unhandled guest exceptions
2026-11-26 18:01:49 +03:00
ates 0a2544cd51 Merge main and address review feedback on REX decoding, crash write isolation, and marker constant
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 18:01:41 +03:00
Ateş 0082d16b1e Merge pull request #424 from MacosPorters/track-b/411-xmem-core
[M1-B1] Enforce xmem title memory budgets
2026-11-26 17:19:59 +03:00
ates 4c7f1c5aff Merge main, sanitize console memory attributes in XMemVirtualAlloc, and zero larger stats tail
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 17:19:52 +03:00
Ateş d72350c854 Merge pull request #426 from MacosPorters/track-b/413-xcrdapi-dstorage
[M1-B3] Exercise asynchronous storage through XCRDAPI
2026-11-26 17:17:27 +03:00
ates 035c93e4d6 Merge main, guard closed handle in GetFileInformation, reject ambiguous requests, and expand tests
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 17:17:19 +03:00
Ateş b93fecf20a Merge pull request #422 from MacosPorters/track-e/418-offline-gdk-runtime
[M1-E1] Implement offline xgameruntime task queues and services
2026-11-26 17:13:59 +03:00
ates 134eee3a28 Cover CLWB addressing and log unhandled guest exceptions
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 10:13:12 +03:00
ates 43f32acb82 Implement bounded audio queues and GameInput COM stub
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 10:06:36 +03:00
ates 0b0e23e10a Exercise asynchronous storage through XCRDAPI
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 09:49:04 +03:00
ates 19c240edd5 Enforce xmem title memory budgets
Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 09:38:59 +03:00
20 changed files with 1741 additions and 178 deletions

No files matched your search

+4
View File
@@ -10,6 +10,10 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Added
- Implemented synthetic APU heap mappings, per-connection APU and DSP queues, and the GameInput ordinal 1 COM stub. Added an audio/input conformance executable covering all four shim DLLs (#419).
- Added structured unhandled exception logging with module-relative addresses and x64 registers, and expanded the CLWB conformance test to require six traps across ModRM, SIB, REX and RIP-relative operands (#409).
- Enforced the configured title memory cap for default heap allocations and virtual commits in `xmem.dll`. Added working-set accounting and a synthetic fixture for alignment, commit overlap, decommit, release, and memory transfer (#411).
- Added a BetterXen-only DirectStorage conformance interface for asynchronous uncompressed file and memory transfers, status arrays, and completion events in `XCRDAPI.dll` (#413).
- Implemented offline `xgameruntime.dll` task queues and async completion, local user handles, synthetic game-license queries, console identity, and bottle-local storage (#418). Added a synthetic conformance executable for Lockhart and Anaconda launches. Only the marked conformance title receives an active synthetic SKU. The build also produces an unmarked control with the same executable name. Queue shutdown delivers accepted callbacks, and bottle-local storage is keyed by executable path.
- `xg_xs.dll` computes linear 2D layouts for `R8G8B8A8` and BC1 through BC7 (`XGCreateTextureComputer`, `XGSuggestSwizzleMode`, and COM `IXGTextureAddressComputer`). Row pitch uses the public D3D12 256-byte alignment and each subresource is placed on the public 512-byte alignment. `GetResourceLayout` reports that aligned allocation span in `total_bytes` (512 for a 1x1 RGBA8 texture) and a separate D3D12-style `copy_end` on each footprint (4 for that same texture). Sizes are overflow-checked, null pointers return `E_POINTER`, and copies stay inside the caller buffers. `SW_64KB_S`, `SW_64KB_D`, and `SW_64KB_R` return `E_NOTIMPL` and write no address. Synthetic `test_xg_xs.exe` checks hand-computed mip offsets, alignment, refcounts, and a byte-identical copy round trip. This is not an Xbox hardware result (#415).
- `d3dmetal-harness` (`bx-d3dmetal-harness`) is an opt-in harness that runs a user-supplied `D3DMetal.framework` outside CrossOver/Wine through `utmapp/d3dmetal-native` (MIT, `af1ee17`), so D3D12 faults can be attributed to D3DMetal or to Wine. D3DMetal is x86_64-only, so an x86_64 probe (`probe/`, built separately with `build-probe.sh`) hosts it under Rosetta 2. The arm64 harness finds the framework (`--framework`, then `$D3DMETAL_FRAMEWORK_PATH`, then CrossOver's copy) and checks both binaries' Mach-O architectures. It runs the probe with a cleared environment and a timeout, then judges the readback against values it computes itself. It reports SKIP (exit 77) only when no framework exists. An explicit path that does not resolve, a framework that fails to initialize, device removal, and probe output held open past the timeout are failures. The probe runs an original SM 6.6 compute kernel compiled with DXC 1.9.2609 and fills the output buffer with a sentinel first, so "kernel did not run" is told apart from "wrong values". On one Apple M5 Pro (macOS 27.2.1) with CrossOver 26.3's D3DMetal 3.0, all 16 D3D12 steps succeeded and 256/256 words matched. This is a local implementer run, not independently reproduced. The live test is `#[ignore]`d and fails when its prerequisites are missing. d3dmetal-native, directx-native and DXC are recorded per file in the upstream registry and reuse matrix. d3dmetal-native's D3DMetal binary patcher is not used (#417).
+108 -24
View File
@@ -1,20 +1,53 @@
#include <windows.h>
#include <unknwn.h>
#include <cstdint>
#include <cstdlib>
#include <mutex>
#include <new>
#include "bx_log.h"
/* Track E (M1-E2 / M5): AcpHal.dll SHAPE Audio Coprocessor HAL shim. */
namespace {
class AcpHal final : public IUnknown {
LONG refs = 1;
public:
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
if (!out) return E_POINTER;
*out = nullptr;
if (iid != IID_IUnknown) return E_NOINTERFACE;
AddRef();
*out = this;
return S_OK;
}
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs); }
ULONG WINAPI Release() override {
ULONG left = InterlockedDecrement(&refs);
if (!left) delete this;
return left;
}
};
// Sorted synthetic address ranges. Zero is reserved for failed lookups.
struct Allocation {
uintptr_t va;
uint32_t base, size;
Allocation* next;
};
Allocation* allocations;
std::mutex heap_lock;
uint64_t capacity = 0;
uint64_t used = 0;
bool heap_created = false;
}
extern "C" {
HRESULT WINAPI AcpHalCreate(void** out_hal) {
BX_STUB_LOG("AcpHal.dll", "AcpHalCreate");
if (out_hal) *out_hal = nullptr;
return E_NOTIMPL;
HRESULT WINAPI AcpHalCreate(void** out) {
if (!out) return E_POINTER;
*out = new (std::nothrow) AcpHal;
return *out ? S_OK : E_OUTOFMEMORY;
}
HRESULT WINAPI AcpHalAllocateShapeContexts(void* /*desc*/) {
HRESULT WINAPI AcpHalAllocateShapeContexts(void*) {
BX_STUB_LOG("AcpHal.dll", "AcpHalAllocateShapeContexts");
return S_OK;
}
@@ -24,35 +57,86 @@ HRESULT WINAPI AcpHalReleaseShapeContexts(void) {
return S_OK;
}
HRESULT WINAPI ApuCreateHeap(uint32_t /*cached_size*/, uint32_t /*non_cached_size*/) {
BX_STUB_LOG("AcpHal.dll", "ApuCreateHeap");
HRESULT WINAPI ApuCreateHeap(uint32_t cached, uint32_t non_cached) {
std::lock_guard guard(heap_lock);
if (allocations) return HRESULT_FROM_WIN32(ERROR_BUSY);
// Invariant: allocations == nullptr implies used == 0; reset explicitly.
used = 0;
capacity = uint64_t(cached) + non_cached;
heap_created = true;
return S_OK;
}
HRESULT WINAPI ApuAlloc(void** out_va, uint32_t* out_apu_addr, uint32_t size, uint32_t alignment) {
HRESULT WINAPI ApuAlloc(void** va, uint32_t* apu, uint32_t size, uint32_t alignment) {
if (va) *va = nullptr;
if (apu) *apu = 0;
if (!va && !apu) return E_POINTER;
if (alignment && (alignment & (alignment - 1))) return E_INVALIDARG;
if (alignment < 64) alignment = 64;
void* p = _aligned_malloc(size ? size : 64, alignment);
if (out_va) *out_va = p;
if (out_apu_addr) *out_apu_addr = static_cast<uint32_t>(reinterpret_cast<uintptr_t>(p) & 0xFFFFFFFFu);
return p ? S_OK : E_OUTOFMEMORY;
if (!size) size = 64;
std::lock_guard guard(heap_lock);
if (!heap_created || size > capacity - used) return E_OUTOFMEMORY;
uint64_t base = alignment;
Allocation** link = &allocations;
while (*link && base + size > (*link)->base) {
const uint64_t end = uint64_t((*link)->base) + (*link)->size;
base = (end + alignment - 1) & ~(uint64_t(alignment) - 1);
link = &(*link)->next;
}
if (base + size > (uint64_t{1} << 32)) return E_OUTOFMEMORY;
void* ptr = _aligned_malloc(size, alignment);
if (!ptr) return E_OUTOFMEMORY;
auto* entry = new (std::nothrow) Allocation{reinterpret_cast<uintptr_t>(ptr),
static_cast<uint32_t>(base), size, *link};
if (!entry) {
_aligned_free(ptr);
return E_OUTOFMEMORY;
}
*link = entry;
used += size;
if (va) *va = ptr;
if (apu) *apu = entry->base;
return S_OK;
}
HRESULT WINAPI ApuFree(void* va) {
if (va) _aligned_free(va);
return S_OK;
if (!va) return S_OK;
std::lock_guard guard(heap_lock);
for (auto** link = &allocations; *link; link = &(*link)->next) {
auto* entry = *link;
if (entry->va != reinterpret_cast<uintptr_t>(va)) continue;
*link = entry->next;
used -= entry->size;
_aligned_free(va);
delete entry;
return S_OK;
}
return E_INVALIDARG;
}
BOOL WINAPI ApuIsVirtualAddressValid(const void* va, uint32_t /*size*/) {
return va != nullptr;
static uint32_t lookup_va(const void* va, uint32_t size) {
const auto address = reinterpret_cast<uintptr_t>(va);
std::lock_guard guard(heap_lock);
for (auto* entry = allocations; entry; entry = entry->next) {
const auto offset = address - entry->va;
if (offset < entry->size && size <= entry->size - offset)
return entry->base + static_cast<uint32_t>(offset);
}
return 0;
}
void* WINAPI ApuMapApuAddress(uint32_t /*apu_addr*/) {
BX_STUB_LOG("AcpHal.dll", "ApuMapApuAddress");
BOOL WINAPI ApuIsVirtualAddressValid(const void* va, uint32_t size) {
return lookup_va(va, size) != 0;
}
void* WINAPI ApuMapApuAddress(uint32_t address) {
std::lock_guard guard(heap_lock);
for (auto* entry = allocations; entry && entry->base <= address; entry = entry->next) {
const auto offset = address - entry->base;
if (offset < entry->size) return reinterpret_cast<void*>(entry->va + offset);
}
return nullptr;
}
uint32_t WINAPI ApuMapVirtualAddress(const void* va) {
return static_cast<uint32_t>(reinterpret_cast<uintptr_t>(va) & 0xFFFFFFFFu);
uint32_t WINAPI ApuMapVirtualAddress(const void* va) { return lookup_va(va, 1); }
}
} // extern "C"
+34 -14
View File
@@ -1,21 +1,41 @@
#include <windows.h>
#include <cstdint>
#include "bx_log.h"
/* Track E (M1-E2 / M5): chad.dll Xbox DSP command shim. */
#define BX_DSP_CONNECTIONS
#include "command_ring.h"
extern "C" {
// Validate and record the caller's stream limit; the synthetic command ring
// holds a fixed 32-packet backlog independent of stream count.
HRESULT WINAPI XDspConnectWithMaximumStreamLimit(uint32_t max_streams, void** out) {
if (!out) return E_POINTER;
*out = nullptr;
if (!max_streams) return E_INVALIDARG;
return connect(out, max_streams);
}
HRESULT WINAPI XDspDisconnect(void* handle) { return disconnect(handle); }
HRESULT WINAPI XDspConnectWithMaximumStreamLimit(uint32_t /*max_streams*/, void** out_handle) {
BX_STUB_LOG("chad.dll", "XDspConnectWithMaximumStreamLimit");
if (out_handle) *out_handle = reinterpret_cast<void*>(0x5001);
HRESULT WINAPI XDspActivate(void* handle) {
std::lock_guard guard(connections_lock);
auto* c = lookup(handle);
if (!c) return E_HANDLE;
c->active = true;
// chad has no result export. Active DSP commands complete synchronously.
while (c->queue.count) c->queue.pop();
return S_OK;
}
HRESULT WINAPI XDspDisconnect(void* /*handle*/) { return S_OK; }
HRESULT WINAPI XDspActivate(void* /*handle*/) { return S_OK; }
HRESULT WINAPI XDspDeactivate(void* /*handle*/) { return S_OK; }
HRESULT WINAPI XDspSubmitCommand(void* /*handle*/, const void* /*cmd*/, uint32_t /*size*/) { return S_OK; }
HRESULT WINAPI XDspDeactivate(void* handle) {
std::lock_guard guard(connections_lock);
auto* c = lookup(handle);
if (!c) return E_HANDLE;
c->active = false;
return S_OK;
}
} // extern "C"
HRESULT WINAPI XDspSubmitCommand(void* handle, const void* cmd, uint32_t size) {
std::lock_guard guard(connections_lock);
auto* c = lookup(handle);
if (!c) return E_HANDLE;
const HRESULT hr = c->queue.push(cmd, size);
if (SUCCEEDED(hr) && c->active) c->queue.pop();
return hr;
}
}
+96
View File
@@ -0,0 +1,96 @@
#pragma once
#include <windows.h>
#include <array>
#include <cstdint>
#include <cstring>
#include <mutex>
#include <new>
namespace {
// A synthetic command completes by returning its opaque bytes unchanged.
struct CommandRing {
struct Packet {
uint32_t size;
unsigned char bytes[1024];
};
std::array<Packet, 32> packets;
unsigned head = 0, count = 0;
HRESULT push(const void* data, uint32_t size) {
if (!data || !size || size > sizeof(Packet::bytes)) return E_INVALIDARG;
if (count == packets.size()) return HRESULT_FROM_WIN32(ERROR_BUSY);
auto& packet = packets[(head + count) % packets.size()];
packet.size = size;
std::memcpy(packet.bytes, data, size);
++count;
return S_OK;
}
void pop() {
head = (head + 1) % packets.size();
--count;
}
HRESULT read(void* data, uint32_t size) {
if (!data) return E_POINTER;
if (!count) return S_FALSE;
const auto& packet = packets[head];
if (size < packet.size) return HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER);
std::memcpy(data, packet.bytes, packet.size);
pop();
return S_OK;
}
};
struct Connection {
uintptr_t id;
Connection* next;
CommandRing queue;
uint32_t max_streams = 0;
bool active = false;
};
// Each DLL owns its registry. An ID stays invalid after disconnect, including
// when the allocator subsequently reuses the same Connection address.
std::mutex connections_lock;
Connection* connections;
#ifdef BX_DSP_CONNECTIONS
uintptr_t next_id = 2;
#else
uintptr_t next_id = 1;
#endif
HRESULT connect(void** out, uint32_t max_streams = 0) {
if (!out) return E_POINTER;
*out = nullptr;
std::lock_guard guard(connections_lock);
if (next_id > UINTPTR_MAX - 2) return E_OUTOFMEMORY;
auto* c = new (std::nothrow) Connection;
if (!c) return E_OUTOFMEMORY;
c->id = next_id;
c->max_streams = max_streams;
next_id += 2;
c->next = connections;
connections = c;
*out = reinterpret_cast<void*>(c->id);
return S_OK;
}
// Caller holds connections_lock through the operation.
Connection* lookup(void* handle) {
for (auto* c = connections; c; c = c->next)
if (c->id == reinterpret_cast<uintptr_t>(handle)) return c;
return nullptr;
}
HRESULT disconnect(void* handle) {
std::lock_guard guard(connections_lock);
for (auto** link = &connections; *link; link = &(*link)->next) {
auto* c = *link;
if (c->id != reinterpret_cast<uintptr_t>(handle)) continue;
*link = c->next;
delete c;
return S_OK;
}
return E_HANDLE;
}
}
+15 -23
View File
@@ -1,32 +1,24 @@
#include <windows.h>
#include <cstdint>
#include "bx_log.h"
/* Track E (M1-E2 / M5): xapu.dll APU command queue shim. */
#include "command_ring.h"
extern "C" {
HRESULT WINAPI XApuConnect(void** out) { return connect(out); }
HRESULT WINAPI XApuDisconnect(void* conn) { return disconnect(conn); }
HRESULT WINAPI XApuConnect(void** out_conn) {
BX_STUB_LOG("xapu.dll", "XApuConnect");
if (out_conn) *out_conn = reinterpret_cast<void*>(0x4001);
return S_OK;
HRESULT WINAPI XApuEnqueueCommand(void* conn, const void* cmd, uint32_t size) {
std::lock_guard guard(connections_lock);
auto* c = lookup(conn);
return c ? c->queue.push(cmd, size) : E_HANDLE;
}
HRESULT WINAPI XApuDisconnect(void* /*conn*/) {
return S_OK;
HRESULT WINAPI XApuDequeueResult(void* conn, void* result, uint32_t size) {
std::lock_guard guard(connections_lock);
auto* c = lookup(conn);
return c ? c->queue.read(result, size) : E_HANDLE;
}
HRESULT WINAPI XApuEnqueueCommand(void* /*conn*/, const void* /*cmd*/, uint32_t /*size*/) {
return S_OK;
uint32_t WINAPI XApuGetResultCount(void* conn) {
std::lock_guard guard(connections_lock);
auto* c = lookup(conn);
return c ? c->queue.count : 0;
}
HRESULT WINAPI XApuDequeueResult(void* /*conn*/, void* /*out_res*/, uint32_t /*size*/) {
return S_FALSE;
}
uint32_t WINAPI XApuGetResultCount(void* /*conn*/) {
return 0u;
}
} // extern "C"
+110 -6
View File
@@ -1,13 +1,117 @@
#include <windows.h>
#include <unknwn.h>
#include <cstdint>
#include "bx_log.h"
/* Track E (M1-E2): GameInput.dll ordinal 1 (GameInputCreate) shim. */
namespace {
// GameInputCreate @1 exposes the legacy v0 COM layout.
constexpr GUID game_input_v0 = {0x11be2a7e, 0x4254, 0x445a,
{0x9c, 0x09, 0xff, 0xc4, 0x0f, 0x00, 0x69, 0x18}};
using Callback = void (WINAPI*)();
extern "C" HRESULT WINAPI GameInputCreate(void** out_game_input) {
BX_STUB_LOG("GameInput.dll", "GameInputCreate@1");
if (out_game_input) {
*out_game_input = nullptr;
}
template<class T>
HRESULT unavailable(T* out) {
if (!out) return E_POINTER;
*out = {};
return E_NOTIMPL;
}
class GameInput final : public IUnknown {
LONG refs = 0;
public:
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
if (!out) return E_POINTER;
*out = nullptr;
if (iid != IID_IUnknown && iid != game_input_v0) return E_NOINTERFACE;
AddRef();
*out = this;
return S_OK;
}
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs); }
ULONG WINAPI Release() override { return InterlockedDecrement(&refs); }
virtual uint64_t WINAPI GetCurrentTimestamp() {
return GetTickCount64() * 1000;
}
virtual HRESULT WINAPI GetCurrentReading(uint32_t, void*, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 4, "GetCurrentReading");
return unavailable(out);
}
virtual HRESULT WINAPI GetNextReading(void*, uint32_t, void*, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 5, "GetNextReading");
return unavailable(out);
}
virtual HRESULT WINAPI GetPreviousReading(void*, uint32_t, void*, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 6, "GetPreviousReading");
return unavailable(out);
}
virtual HRESULT WINAPI GetTemporalReading(uint64_t, void*, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 7, "GetTemporalReading");
return unavailable(out);
}
virtual HRESULT WINAPI RegisterReadingCallback(void*, uint32_t, float, void*, Callback, uint64_t* out) {
BX_VTABLE_STUB_LOG("IGameInput", 8, "RegisterReadingCallback");
return unavailable(out);
}
virtual HRESULT WINAPI RegisterDeviceCallback(void*, uint32_t, uint32_t, uint32_t, void*, Callback, uint64_t* out) {
BX_VTABLE_STUB_LOG("IGameInput", 9, "RegisterDeviceCallback");
return unavailable(out);
}
virtual HRESULT WINAPI RegisterSystemButtonCallback(void*, uint32_t, void*, Callback, uint64_t* out) {
BX_VTABLE_STUB_LOG("IGameInput", 10, "RegisterSystemButtonCallback");
return unavailable(out);
}
virtual HRESULT WINAPI RegisterKeyboardLayoutCallback(void*, void*, Callback, uint64_t* out) {
BX_VTABLE_STUB_LOG("IGameInput", 11, "RegisterKeyboardLayoutCallback");
return unavailable(out);
}
virtual void WINAPI StopCallback(uint64_t) {
BX_VTABLE_STUB_LOG("IGameInput", 12, "StopCallback");
}
virtual bool WINAPI UnregisterCallback(uint64_t, uint64_t) {
BX_VTABLE_STUB_LOG("IGameInput", 13, "UnregisterCallback");
return false;
}
virtual HRESULT WINAPI CreateDispatcher(void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 14, "CreateDispatcher");
return unavailable(out);
}
virtual HRESULT WINAPI CreateAggregateDevice(uint32_t, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 15, "CreateAggregateDevice");
return unavailable(out);
}
virtual HRESULT WINAPI FindDeviceFromId(const void*, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 16, "FindDeviceFromId");
return unavailable(out);
}
virtual HRESULT WINAPI FindDeviceFromObject(IUnknown*, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 17, "FindDeviceFromObject");
return unavailable(out);
}
virtual HRESULT WINAPI FindDeviceFromPlatformHandle(HANDLE, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 18, "FindDeviceFromPlatformHandle");
return unavailable(out);
}
virtual HRESULT WINAPI FindDeviceFromPlatformString(const wchar_t*, void** out) {
BX_VTABLE_STUB_LOG("IGameInput", 19, "FindDeviceFromPlatformString");
return unavailable(out);
}
virtual HRESULT WINAPI EnableOemDeviceSupport(uint16_t, uint16_t, uint8_t, uint8_t) {
BX_VTABLE_STUB_LOG("IGameInput", 20, "EnableOemDeviceSupport");
return E_NOTIMPL;
}
virtual void WINAPI SetFocusPolicy(uint32_t) {
BX_VTABLE_STUB_LOG("IGameInput", 21, "SetFocusPolicy");
}
};
GameInput singleton;
}
extern "C" HRESULT WINAPI GameInputCreate(void** out) {
if (!out) return E_POINTER;
singleton.AddRef();
*out = &singleton;
return S_OK;
}
+122 -59
View File
@@ -13,6 +13,9 @@ CRITICAL_SECTION g_log_lock;
bool g_log_lock_ready = false;
HANDLE g_log_handle = INVALID_HANDLE_VALUE;
PVOID g_veh_handle = nullptr;
LPTOP_LEVEL_EXCEPTION_FILTER g_previous_filter = nullptr;
std::atomic_flag g_crash_logged{};
std::atomic<bool> g_crash_in_flight{false};
std::atomic<uint64_t> g_clwb_traps{0};
bx_runtime_config_t g_config = {
BX_ABI_VERSION,
@@ -26,6 +29,11 @@ bx_runtime_config_t g_config = {
};
void write_log_line(const char* line, size_t len) {
// Pause regular logging while a terminal crash record is being emitted so
// background threads cannot interleave with the unlocked crash WriteFile.
if (g_crash_in_flight.load(std::memory_order_acquire)) {
return;
}
if (g_log_lock_ready) {
EnterCriticalSection(&g_log_lock);
}
@@ -45,90 +53,135 @@ void write_log_line(const char* line, size_t len) {
}
}
/*
* Decode an x86-64 `clwb m8` instruction at `ip`.
* Encoding: [legacy prefixes] 0x66 [REX 0x40..0x4F] 0x0F 0xAE /6 (mod != 3).
* Returns total instruction length in bytes, or 0 if `ip` is not `clwb`.
*/
size_t decode_clwb_length(const uint8_t* ip) {
constexpr size_t kMaxInstructionLength = 15;
size_t read_instruction(uint64_t rip, uint8_t (&bytes)[kMaxInstructionLength]) {
HANDLE process = GetCurrentProcess();
if (ReadProcessMemory(process, reinterpret_cast<LPCVOID>(rip),
bytes, sizeof(bytes), nullptr)) {
return sizeof(bytes);
}
// A short instruction can end immediately before an inaccessible page.
size_t size = 0;
while (size < sizeof(bytes) &&
ReadProcessMemory(process, reinterpret_cast<LPCVOID>(rip + size),
&bytes[size], 1, nullptr)) {
++size;
}
return size;
}
// CLWB is 66 0F AE /6 with a memory operand. The address-size override
// selects 32-bit addressing but leaves the ModRM/SIB displacement lengths intact.
size_t decode_clwb_length(const uint8_t* ip, size_t size) {
size_t idx = 0;
bool has_66 = false;
bool has_addr_override = false;
while (idx < 6) {
uint8_t b = ip[idx];
if (b == 0x66) {
while (idx < size) {
const uint8_t byte = ip[idx];
if (byte == 0x66) {
has_66 = true;
idx++;
} else if (b == 0x67) {
has_addr_override = true;
idx++;
} else if (b == 0x26 || b == 0x2E || b == 0x36 || b == 0x3E || b == 0x64 || b == 0x65) {
idx++;
} else {
} else if (byte != 0x67 && byte != 0x26 && byte != 0x2E &&
byte != 0x36 && byte != 0x3E && byte != 0x64 && byte != 0x65) {
break;
}
}
(void)has_addr_override;
if (!has_66) {
return 0;
++idx;
}
if ((ip[idx] & 0xF0) == 0x40) {
idx++; /* Optional REX prefix */
// x86-64 allows at most one REX prefix immediately before the opcode.
if (idx < size && (ip[idx] & 0xF0) == 0x40) {
++idx;
}
if (ip[idx] != 0x0F || ip[idx + 1] != 0xAE) {
if (!has_66 || size - idx < 3 || ip[idx] != 0x0F || ip[idx + 1] != 0xAE) {
return 0;
}
idx += 2;
uint8_t modrm = ip[idx++];
uint8_t mod = (modrm >> 6) & 0x3;
uint8_t reg = (modrm >> 3) & 0x7;
uint8_t rm = modrm & 0x7;
/* `clwb` requires memory operand (mod != 3) and opcode extension /6. */
const uint8_t modrm = ip[idx++];
const uint8_t mod = modrm >> 6;
const uint8_t reg = (modrm >> 3) & 7;
const uint8_t rm = modrm & 7;
if (mod == 3 || reg != 6) {
return 0;
}
uint8_t base = rm;
if (rm == 4) {
uint8_t sib = ip[idx++];
if (mod == 0 && (sib & 0x7) == 5) {
idx += 4; /* disp32 with no base */
if (idx == size) {
return 0;
}
} else if (mod == 0 && rm == 5) {
idx += 4; /* RIP-relative disp32 */
base = ip[idx++] & 7;
}
if (mod == 1) {
idx += 1; /* disp8 */
} else if (mod == 2) {
idx += 4; /* disp32 */
idx += 1;
} else if (mod == 2 || (mod == 0 && base == 5)) {
idx += 4;
}
return idx;
return idx <= size ? idx : 0;
}
bool is_adx_opcode(const uint8_t* ip) {
bool is_adx_opcode(const uint8_t* ip, size_t size) {
size_t idx = 0;
bool has_66_or_f3 = false;
while (idx < 4) {
if (ip[idx] == 0x66 || ip[idx] == 0xF3) {
has_66_or_f3 = true;
idx++;
} else {
break;
}
while (idx < size && (ip[idx] == 0x66 || ip[idx] == 0xF3)) {
++idx;
}
if (!has_66_or_f3) {
if (idx == 0) {
return false;
}
if ((ip[idx] & 0xF0) == 0x40) {
idx++;
if (idx < size && (ip[idx] & 0xF0) == 0x40) {
++idx;
}
return ip[idx] == 0x0F && ip[idx + 1] == 0x38 && ip[idx + 2] == 0xF6;
// Require the 3-byte ADCX/ADOX opcode (0F 38 F6) plus at least 1 ModRM byte.
return size - idx >= 4 && ip[idx] == 0x0F && ip[idx + 1] == 0x38 && ip[idx + 2] == 0xF6;
}
LONG WINAPI log_unhandled_exception(PEXCEPTION_POINTERS ep) {
// Wine can invoke the top-level filter again for the same terminal fault.
if (ep && ep->ExceptionRecord && ep->ContextRecord &&
!g_crash_logged.test_and_set(std::memory_order_relaxed)) {
g_crash_in_flight.store(true, std::memory_order_release);
const CONTEXT& ctx = *ep->ContextRecord;
MEMORY_BASIC_INFORMATION region{};
unsigned long long module_base = 0;
if (VirtualQuery(reinterpret_cast<LPCVOID>(ctx.Rip), &region, sizeof(region)) &&
region.Type == MEM_IMAGE) {
module_base = reinterpret_cast<uintptr_t>(region.AllocationBase);
}
char line[1024];
int length = std::snprintf(
line, sizeof(line),
"{\"ts_ms\":%llu,\"tid\":%lu,\"level\":\"ERROR\",\"sub\":\"runtime_veh\","
"\"event\":\"unhandled_exception\",\"exception_code\":\"0x%08lx\","
"\"module_base\":\"0x%016llx\",\"rva\":\"0x%016llx\","
"\"rip\":\"0x%016llx\",\"rsp\":\"0x%016llx\","
"\"registers\":{\"rax\":\"0x%016llx\",\"rbx\":\"0x%016llx\","
"\"rcx\":\"0x%016llx\",\"rdx\":\"0x%016llx\",\"rsi\":\"0x%016llx\","
"\"rdi\":\"0x%016llx\",\"rbp\":\"0x%016llx\",\"r8\":\"0x%016llx\","
"\"r9\":\"0x%016llx\",\"r10\":\"0x%016llx\",\"r11\":\"0x%016llx\","
"\"r12\":\"0x%016llx\",\"r13\":\"0x%016llx\",\"r14\":\"0x%016llx\","
"\"r15\":\"0x%016llx\"}}\n",
static_cast<unsigned long long>(GetTickCount64()), GetCurrentThreadId(),
ep->ExceptionRecord->ExceptionCode, module_base,
module_base ? ctx.Rip - module_base : 0ULL, ctx.Rip, ctx.Rsp,
ctx.Rax, ctx.Rbx, ctx.Rcx, ctx.Rdx, ctx.Rsi, ctx.Rdi, ctx.Rbp,
ctx.R8, ctx.R9, ctx.R10, ctx.R11, ctx.R12, ctx.R13, ctx.R14, ctx.R15);
// A crashed thread may already own the regular logger's lock.
HANDLE output = g_log_handle != INVALID_HANDLE_VALUE
? g_log_handle : GetStdHandle(STD_ERROR_HANDLE);
if (length > 0 && length < static_cast<int>(sizeof(line)) &&
output && output != INVALID_HANDLE_VALUE) {
DWORD written = 0;
WriteFile(output, line, static_cast<DWORD>(length), &written, nullptr);
}
}
const LONG disposition = g_previous_filter ? g_previous_filter(ep) : EXCEPTION_CONTINUE_SEARCH;
if (disposition == EXCEPTION_CONTINUE_EXECUTION) {
g_crash_in_flight.store(false, std::memory_order_release);
g_crash_logged.clear(std::memory_order_relaxed);
}
return disposition;
}
LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
@@ -139,9 +192,10 @@ LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
return EXCEPTION_CONTINUE_SEARCH;
}
auto* ip = reinterpret_cast<const uint8_t*>(ep->ContextRecord->Rip);
uint8_t ip[kMaxInstructionLength]{};
const size_t size = read_instruction(ep->ContextRecord->Rip, ip);
if (g_config.enable_clwb_veh) {
size_t len = decode_clwb_length(ip);
size_t len = decode_clwb_length(ip, size);
if (len > 0) {
uint64_t count = g_clwb_traps.fetch_add(1, std::memory_order_relaxed) + 1;
if (count == 1 || (count & (count - 1)) == 0) {
@@ -158,7 +212,7 @@ LONG CALLBACK bx_veh_handler(PEXCEPTION_POINTERS ep) {
}
}
if (g_config.enable_adx_tripwire && is_adx_opcode(ip)) {
if (g_config.enable_adx_tripwire && is_adx_opcode(ip, size)) {
char msg[160];
std::snprintf(msg, sizeof(msg),
"rip=0x%016llx bytes=%02x %02x %02x %02x %02x",
@@ -262,9 +316,18 @@ BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID) {
if (reason == DLL_PROCESS_ATTACH) {
init_config_and_logging();
bx_veh_install();
g_previous_filter = SetUnhandledExceptionFilter(log_unhandled_exception);
bx_log_emit(BX_LOG_INFO, "runtime_veh", "attached",
g_config.profile == BX_PROFILE_ANACONDA ? "profile=anaconda" : "profile=lockhart");
} else if (reason == DLL_PROCESS_DETACH) {
// Restore g_previous_filter only when our filter is still the active
// top-level filter; if the guest installed its own filter after attach,
// put the guest filter back unchanged. (The frozen .def has no separate
// uninstall export, so detach performs this bounded pointer swap.)
const auto current_filter = SetUnhandledExceptionFilter(g_previous_filter);
if (current_filter != log_unhandled_exception) {
SetUnhandledExceptionFilter(current_filter);
}
if (g_veh_handle) {
RemoveVectoredExceptionHandler(g_veh_handle);
g_veh_handle = nullptr;
+1 -1
View File
@@ -1,4 +1,4 @@
bx_add_shim_dll(xcrdapi XCRDAPI XCRDAPI.def
xcrdapi.cpp
)
target_link_libraries(xcrdapi PRIVATE bx_runtime_veh kernel32)
target_link_libraries(xcrdapi PRIVATE bx_runtime_veh kernel32 uuid)
+73
View File
@@ -0,0 +1,73 @@
#ifndef BETTERXEN_SYNTHETIC_STORAGE_H
#define BETTERXEN_SYNTHETIC_STORAGE_H
#include <windows.h>
#include <d3d12.h>
#include <unknwn.h>
// BetterXen-only COM contract for original conformance guests. The Xbox
// DirectStorage interface IDs and binary layouts are independent of these types.
namespace bx::storage {
inline constexpr IID factory_iid{0xaad71506, 0x7beb, 0x49fc, {0x94, 0x1d, 0x46, 0x58, 0x75, 0xed, 0x35, 0x00}};
inline constexpr IID file_iid{0x723738ce, 0x6772, 0x47dc, {0x95, 0x47, 0x27, 0x7d, 0x67, 0x22, 0xb0, 0xc7}};
inline constexpr IID queue_iid{0xd895469a, 0xd810, 0x4dea, {0xb4, 0x48, 0xf4, 0x42, 0x5e, 0x52, 0x9e, 0x69}};
inline constexpr IID status_iid{0xfb214629, 0xa3ae, 0x4a81, {0x9c, 0xe3, 0xe8, 0x42, 0x6b, 0x08, 0x62, 0xd7}};
struct File : IUnknown {
virtual HRESULT STDMETHODCALLTYPE Close() = 0;
virtual HRESULT STDMETHODCALLTYPE GetFileInformation(BY_HANDLE_FILE_INFORMATION*) = 0;
virtual HRESULT STDMETHODCALLTYPE GetHandle(HANDLE*) = 0;
};
// Status entries are queue-position scoped: each slot reports the first error
// among entries submitted before it since the previous status entry, and is
// not bound to a specific request handle.
struct Status : IUnknown {
virtual HRESULT STDMETHODCALLTYPE GetResult(UINT index) = 0;
};
// Requests keep source and destination buffers borrowed until completion.
// File requests retain a duplicate of the file handle when enqueued.
// Exactly one of `file` or `source` may be non-null; setting both returns E_INVALIDARG.
struct Request {
File* file;
UINT64 file_offset;
const void* source;
void* destination;
DWORD size;
UINT compression;
};
struct ErrorRecord {
HRESULT first_error;
UINT64 failure_count;
};
struct QueueInfo {
UINT capacity;
UINT available;
};
struct Queue : IUnknown {
virtual HRESULT STDMETHODCALLTYPE EnqueueRequest(const Request*) = 0;
virtual HRESULT STDMETHODCALLTYPE EnqueueStatus(Status*, UINT index) = 0;
virtual HRESULT STDMETHODCALLTYPE EnqueueSignal(ID3D12Fence*, UINT64 value) = 0;
virtual HRESULT STDMETHODCALLTYPE EnqueueSetEvent(HANDLE) = 0;
virtual HRESULT STDMETHODCALLTYPE Submit() = 0;
virtual HRESULT STDMETHODCALLTYPE RetrieveErrorRecord(ErrorRecord*) = 0;
virtual HRESULT STDMETHODCALLTYPE Query(QueueInfo*) = 0;
virtual HRESULT STDMETHODCALLTYPE Close() = 0;
};
struct Factory : IUnknown {
virtual HRESULT STDMETHODCALLTYPE OpenFile(PCWSTR, REFIID, void**) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateQueue(UINT capacity, REFIID, void**) = 0;
virtual HRESULT STDMETHODCALLTYPE CreateStatusArray(UINT count, REFIID, void**) = 0;
// 0 succeeds as a no-op; non-zero sizes log and return E_NOTIMPL.
virtual HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT size) = 0;
};
} // namespace bx::storage
extern "C" HRESULT WINAPI DStorageGetFactory(REFIID, void**);
#endif
+432 -7
View File
@@ -1,13 +1,438 @@
#include <windows.h>
#include "synthetic_storage.h"
#include <cstring>
#include <limits>
#include <new>
#include "bx_log.h"
/* Track B (M1-B3): DirectStorage factory & async I/O queue shim. */
namespace {
using namespace bx::storage;
extern "C" HRESULT WINAPI DStorageGetFactory(REFIID /*riid*/, void** ppv) {
BX_STUB_LOG("XCRDAPI.dll", "DStorageGetFactory");
if (ppv) {
*ppv = nullptr;
HRESULT win32_error() { return HRESULT_FROM_WIN32(GetLastError()); }
class Lock {
public:
explicit Lock(SRWLOCK& mutex) : mutex_(mutex) { AcquireSRWLockExclusive(&mutex_); }
~Lock() { ReleaseSRWLockExclusive(&mutex_); }
private:
SRWLOCK& mutex_;
};
template<class Interface, const IID& interface_id>
class Object : public Interface {
public:
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID riid, void** result) override {
if (!result) return E_POINTER;
*result = nullptr;
if (!IsEqualIID(riid, interface_id) && !IsEqualIID(riid, IID_IUnknown)) {
return E_NOINTERFACE;
}
*result = static_cast<Interface*>(this);
AddRef();
return S_OK;
}
return E_NOTIMPL;
ULONG STDMETHODCALLTYPE AddRef() override { return InterlockedIncrement(&references_); }
ULONG STDMETHODCALLTYPE Release() override {
const ULONG references = InterlockedDecrement(&references_);
if (!references) delete this;
return references;
}
protected:
virtual ~Object() = default;
private:
LONG references_ = 1;
};
template<class Interface>
HRESULT publish(Interface* object, REFIID iid, void** result) {
const HRESULT status = object->QueryInterface(iid, result);
object->Release();
return status;
}
HRESULT duplicate_handle(HANDLE handle, HANDLE* copy) {
const HANDLE process = GetCurrentProcess();
return DuplicateHandle(process, handle, process, copy, 0, FALSE, DUPLICATE_SAME_ACCESS)
? S_OK : win32_error();
}
class StorageFile final : public Object<File, file_iid> {
public:
explicit StorageFile(HANDLE handle) : handle_(handle) {}
HRESULT STDMETHODCALLTYPE Close() override {
Lock lock(mutex_);
if (handle_ == INVALID_HANDLE_VALUE) return S_OK;
if (!CloseHandle(handle_)) return win32_error();
handle_ = INVALID_HANDLE_VALUE;
return S_OK;
}
HRESULT STDMETHODCALLTYPE GetFileInformation(BY_HANDLE_FILE_INFORMATION* info) override {
if (!info) return E_POINTER;
Lock lock(mutex_);
if (handle_ == INVALID_HANDLE_VALUE) return HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE);
return GetFileInformationByHandle(handle_, info) ? S_OK : win32_error();
}
HRESULT STDMETHODCALLTYPE GetHandle(HANDLE* copy) override {
if (!copy) return E_POINTER;
*copy = nullptr;
Lock lock(mutex_);
if (handle_ == INVALID_HANDLE_VALUE) return HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE);
return duplicate_handle(handle_, copy);
}
private:
~StorageFile() override { Close(); }
SRWLOCK mutex_ = SRWLOCK_INIT;
HANDLE handle_;
};
class StatusArray final : public Object<Status, status_iid> {
public:
struct Slot {
HRESULT result = E_PENDING;
bool busy = false;
};
StatusArray(Slot* slots, UINT count) : slots_(slots), count_(count) {}
HRESULT STDMETHODCALLTYPE GetResult(UINT index) override {
if (index >= count_) return E_INVALIDARG;
Lock lock(mutex_);
return slots_[index].result;
}
HRESULT begin(UINT index) {
if (index >= count_) return E_INVALIDARG;
Lock lock(mutex_);
if (slots_[index].busy) return HRESULT_FROM_WIN32(ERROR_BUSY);
slots_[index] = {E_PENDING, true};
return S_OK;
}
void complete(UINT index, HRESULT result) {
Lock lock(mutex_);
slots_[index] = {result, false};
}
private:
~StatusArray() override { delete[] slots_; }
SRWLOCK mutex_ = SRWLOCK_INIT;
Slot* slots_;
UINT count_;
};
enum class Kind { request, status, signal, event };
struct Entry {
Kind kind;
Request request{};
HANDLE handle = nullptr;
StatusArray* status = nullptr;
UINT index = 0;
ID3D12Fence* fence = nullptr;
UINT64 value = 0;
};
HRESULT read_request(HANDLE file, const Request& request) {
if (!request.size) return S_OK;
if (!file) {
std::memmove(request.destination, request.source, request.size);
return S_OK;
}
OVERLAPPED operation{};
operation.Offset = static_cast<DWORD>(request.file_offset);
operation.OffsetHigh = static_cast<DWORD>(request.file_offset >> 32);
operation.hEvent = CreateEventW(nullptr, TRUE, FALSE, nullptr);
if (!operation.hEvent) return win32_error();
DWORD bytes = 0;
HRESULT result = S_OK;
if (!ReadFile(file, request.destination, request.size, &bytes, &operation)) {
const DWORD error = GetLastError();
if (error != ERROR_IO_PENDING) {
result = HRESULT_FROM_WIN32(error);
} else if (!GetOverlappedResult(file, &operation, &bytes, TRUE)) {
result = win32_error();
}
}
CloseHandle(operation.hEvent);
if (SUCCEEDED(result) && bytes != request.size) return HRESULT_FROM_WIN32(ERROR_HANDLE_EOF);
return result;
}
// Each queue is drained serially, in FIFO order, by a single threadpool work item.
class WorkQueue final : public Object<Queue, queue_iid> {
public:
WorkQueue(Entry* entries, UINT capacity) : entries_(entries), capacity_(capacity) {}
bool create_work() {
work_ = CreateThreadpoolWork(run, this, nullptr);
return work_ != nullptr;
}
HRESULT STDMETHODCALLTYPE EnqueueRequest(const Request* request) override {
constexpr UINT64 max_file_offset = std::numeric_limits<LONGLONG>::max();
if (!request || (request->file && request->source)
|| (request->size && (!request->destination || (!request->source && !request->file)))
|| (request->file && (request->file_offset > max_file_offset - request->size))) {
return E_INVALIDARG;
}
Entry entry{Kind::request, *request};
if (request->file && !request->compression) {
const HRESULT result = request->file->GetHandle(&entry.handle);
if (FAILED(result)) return result;
}
const HRESULT result = enqueue(entry);
if (FAILED(result) && entry.handle) CloseHandle(entry.handle);
return result;
}
HRESULT STDMETHODCALLTYPE EnqueueStatus(Status* status, UINT index) override {
auto* array = dynamic_cast<StatusArray*>(status);
if (!array) return E_INVALIDARG;
Lock lock(mutex_);
const HRESULT available = check_available();
if (FAILED(available)) return available;
const HRESULT result = array->begin(index);
if (FAILED(result)) return result;
array->AddRef();
Entry entry{Kind::status};
entry.status = array;
entry.index = index;
append(entry);
return S_OK;
}
HRESULT STDMETHODCALLTYPE EnqueueSignal(ID3D12Fence* fence, UINT64 value) override {
if (!fence) return E_POINTER;
Entry entry{Kind::signal};
entry.fence = fence;
entry.value = value;
fence->AddRef();
const HRESULT result = enqueue(entry);
if (FAILED(result)) fence->Release();
return result;
}
HRESULT STDMETHODCALLTYPE EnqueueSetEvent(HANDLE event) override {
if (!event || event == INVALID_HANDLE_VALUE) return E_INVALIDARG;
Entry entry{Kind::event};
const HRESULT duplicated = duplicate_handle(event, &entry.handle);
if (FAILED(duplicated)) return duplicated;
const HRESULT result = enqueue(entry);
if (FAILED(result)) CloseHandle(entry.handle);
return result;
}
HRESULT STDMETHODCALLTYPE Submit() override {
Lock lock(mutex_);
if (closed_) return HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE);
submit();
return S_OK;
}
HRESULT STDMETHODCALLTYPE RetrieveErrorRecord(ErrorRecord* out) override {
if (!out) return E_POINTER;
Lock lock(mutex_);
*out = errors_;
errors_ = {};
return S_OK;
}
HRESULT STDMETHODCALLTYPE Query(QueueInfo* info) override {
if (!info) return E_POINTER;
Lock lock(mutex_);
*info = {capacity_, capacity_ - size_};
return S_OK;
}
HRESULT STDMETHODCALLTYPE Close() override {
{
Lock lock(mutex_);
closed_ = true;
submit();
}
if (work_) WaitForThreadpoolWorkCallbacks(work_, FALSE);
return S_OK;
}
private:
~WorkQueue() override {
Close();
if (work_) CloseThreadpoolWork(work_);
delete[] entries_;
}
HRESULT check_available() const {
if (closed_) return HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE);
return size_ == capacity_ ? HRESULT_FROM_WIN32(ERROR_BUSY) : S_OK;
}
void append(const Entry& entry) {
entries_[(head_ + size_) % capacity_] = entry;
++size_;
}
HRESULT enqueue(const Entry& entry) {
Lock lock(mutex_);
const HRESULT result = check_available();
if (FAILED(result)) return result;
append(entry);
return S_OK;
}
void submit() {
submitted_ = size_;
if (submitted_ && !active_) {
active_ = true;
SubmitThreadpoolWork(work_);
}
}
static void CALLBACK run(PTP_CALLBACK_INSTANCE, void* context, PTP_WORK) {
static_cast<WorkQueue*>(context)->drain();
}
void drain() {
for (;;) {
Entry entry{};
{
Lock lock(mutex_);
if (!submitted_) {
active_ = false;
return;
}
entry = entries_[head_];
}
HRESULT result = S_OK;
switch (entry.kind) {
case Kind::request:
if (entry.request.compression) {
BX_STUB_LOG("XCRDAPI.dll", "compression");
result = E_NOTIMPL;
} else {
result = read_request(entry.handle, entry.request);
}
if (entry.handle) CloseHandle(entry.handle);
break;
case Kind::status:
entry.status->complete(entry.index, status_error_);
entry.status->Release();
status_error_ = S_OK;
break;
case Kind::signal:
result = entry.fence->Signal(entry.value);
entry.fence->Release();
break;
case Kind::event:
if (!SetEvent(entry.handle)) result = win32_error();
CloseHandle(entry.handle);
break;
}
Lock lock(mutex_);
if (FAILED(result)) {
if (SUCCEEDED(status_error_)) status_error_ = result;
if (!errors_.failure_count) errors_.first_error = result;
++errors_.failure_count;
}
head_ = (head_ + 1) % capacity_;
--size_;
--submitted_;
}
}
SRWLOCK mutex_ = SRWLOCK_INIT;
Entry* entries_;
UINT capacity_;
UINT head_ = 0;
UINT size_ = 0;
UINT submitted_ = 0;
bool active_ = false;
bool closed_ = false;
PTP_WORK work_ = nullptr;
HRESULT status_error_ = S_OK;
ErrorRecord errors_{};
};
class StorageFactory final : public Object<Factory, factory_iid> {
public:
HRESULT STDMETHODCALLTYPE OpenFile(PCWSTR path, REFIID iid, void** out) override {
if (!out) return E_POINTER;
*out = nullptr;
if (!path || !*path) return E_INVALIDARG;
HANDLE handle = CreateFileW(path, GENERIC_READ, FILE_SHARE_READ, nullptr,
OPEN_EXISTING, FILE_FLAG_OVERLAPPED, nullptr);
if (handle == INVALID_HANDLE_VALUE) return win32_error();
auto* file = new (std::nothrow) StorageFile(handle);
if (!file) {
CloseHandle(handle);
return E_OUTOFMEMORY;
}
return publish(file, iid, out);
}
HRESULT STDMETHODCALLTYPE CreateQueue(UINT capacity, REFIID iid, void** out) override {
if (!out) return E_POINTER;
*out = nullptr;
if (!capacity || capacity > 65535) return E_INVALIDARG;
auto* entries = new (std::nothrow) Entry[capacity];
if (!entries) return E_OUTOFMEMORY;
auto* queue = new (std::nothrow) WorkQueue(entries, capacity);
if (!queue) {
delete[] entries;
return E_OUTOFMEMORY;
}
if (!queue->create_work()) {
const HRESULT error = win32_error();
queue->Release();
return error;
}
return publish(queue, iid, out);
}
HRESULT STDMETHODCALLTYPE CreateStatusArray(UINT count, REFIID iid, void** out) override {
if (!out) return E_POINTER;
*out = nullptr;
if (!count || count > 65535) return E_INVALIDARG;
auto* slots = new (std::nothrow) StatusArray::Slot[count];
if (!slots) return E_OUTOFMEMORY;
auto* array = new (std::nothrow) StatusArray(slots, count);
if (!array) {
delete[] slots;
return E_OUTOFMEMORY;
}
return publish(array, iid, out);
}
HRESULT STDMETHODCALLTYPE SetStagingBufferSize(UINT size) override {
if (!size) return S_OK;
BX_STUB_LOG("XCRDAPI.dll", "SetStagingBufferSize");
return E_NOTIMPL;
}
};
} // namespace
extern "C" HRESULT WINAPI DStorageGetFactory(REFIID riid, void** ppv) {
if (!ppv) return E_POINTER;
*ppv = nullptr;
if (!IsEqualIID(riid, factory_iid) && !IsEqualIID(riid, IID_IUnknown)) {
BX_STUB_LOG("XCRDAPI.dll", "DStorageGetFactory");
return E_NOINTERFACE;
}
auto* factory = new (std::nothrow) StorageFactory;
return factory ? publish(factory, riid, ppv) : E_OUTOFMEMORY;
}
+252 -35
View File
@@ -1,30 +1,130 @@
#include <windows.h>
#include <atomic>
#include <algorithm>
#include <cstddef>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <limits>
#include <mutex>
#include <utility>
#include "bx_config.h"
#include "bx_log.h"
#include "bx_xmem_internal.h"
/*
* Track B (M1-B1 / M1-B2): Starter implementation of xmem.dll.
* Provides working default heap & virtual allocations so dependent DLLs can link
* and load immediately; Track B issues expand physical/scatter page mapping,
* __XMemAllocationHooks__ dispatch, and Lockhart working-set enforcement.
*/
namespace {
std::atomic<uint64_t> g_committed_virtual{0};
std::atomic<uint64_t> g_allocated_physical{0};
std::atomic<uint64_t> g_peak_committed{0};
constexpr SIZE_T heap_alignment = 64;
void record_alloc(uint64_t bytes) {
uint64_t cur = g_committed_virtual.fetch_add(bytes) + bytes;
uint64_t peak = g_peak_committed.load();
while (cur > peak && !g_peak_committed.compare_exchange_weak(peak, cur)) {}
struct VirtualCommit {
uintptr_t begin;
uintptr_t end;
PVOID allocation_base;
};
// The shim build disables exceptions. Grow the table before committing pages
// so a bookkeeping allocation failure leaves the Win32 allocation untouched.
struct CommitTable {
VirtualCommit* entries = nullptr;
size_t count = 0;
size_t capacity = 0;
CommitTable() = default;
CommitTable(const CommitTable&) = delete;
CommitTable& operator=(const CommitTable&) = delete;
~CommitTable() { std::free(entries); }
VirtualCommit* begin() const { return entries; }
VirtualCommit* end() const { return count ? entries + count : entries; }
bool append(VirtualCommit commit) {
if (count == capacity) {
const size_t max_entries = std::numeric_limits<size_t>::max() / sizeof(commit);
if (capacity > max_entries / 2) return false;
const size_t next_capacity = capacity ? capacity * 2 : 8;
auto* next = static_cast<VirtualCommit*>(
std::realloc(entries, next_capacity * sizeof(commit)));
if (!next) return false;
entries = next;
capacity = next_capacity;
}
entries[count++] = commit;
return true;
}
void swap(CommitTable& other) {
std::swap(entries, other.entries);
std::swap(count, other.count);
std::swap(capacity, other.capacity);
}
};
std::mutex usage_lock;
CommitTable virtual_commits;
uint64_t heap_bytes = 0;
uint64_t virtual_bytes = 0;
uint64_t peak_bytes = 0;
uint64_t title_limit() {
const auto* config = bx_get_runtime_config();
return config ? config->title_memory_limit_bytes : (8ULL << 30);
}
bool can_commit(uint64_t bytes) {
const uint64_t limit = title_limit();
const uint64_t used = heap_bytes + virtual_bytes;
return used <= limit && bytes <= limit - used;
}
void update_peak() {
peak_bytes = std::max(peak_bytes, heap_bytes + virtual_bytes);
}
uintptr_t region_end(const MEMORY_BASIC_INFORMATION& region) {
return reinterpret_cast<uintptr_t>(region.BaseAddress) + region.RegionSize;
}
// The export table has no XMemVirtualFree. Reconcile tracked ranges with
// Win32 when the guest releases or decommits pages using VirtualFree.
bool refresh_virtual_commits() {
CommitTable live;
uint64_t bytes = 0;
for (const auto& commit : virtual_commits) {
uintptr_t cursor = commit.begin;
while (cursor < commit.end) {
MEMORY_BASIC_INFORMATION region{};
if (!VirtualQuery(reinterpret_cast<PVOID>(cursor), &region, sizeof(region))) {
break;
}
const uintptr_t end = std::min(commit.end, region_end(region));
if (end <= cursor) break;
if (region.State == MEM_COMMIT && region.AllocationBase == commit.allocation_base) {
if (!live.append({cursor, end, commit.allocation_base})) return false;
bytes += end - cursor;
}
cursor = end;
}
}
virtual_commits.swap(live);
virtual_bytes = bytes;
return true;
}
void report_unsupported_host_hooks() {
static const bool reported = [] {
if (GetProcAddress(GetModuleHandleW(nullptr), "__XMemAllocationHooks__")) {
BX_STUB_LOG("xmem.dll", "__XMemAllocationHooks__");
}
return true;
}();
(void)reported;
}
SIZE_T page_size() {
static const SIZE_T size = [] {
SYSTEM_INFO info{};
GetSystemInfo(&info);
return info.dwPageSize;
}();
return size;
}
} // namespace
@@ -32,20 +132,46 @@ extern "C" {
PVOID WINAPI XMemAllocDefault(SIZE_T size, uint64_t /*attributes*/) {
if (size == 0) size = 16;
void* p = _aligned_malloc(size, 64);
if (p) record_alloc(size);
return p;
if (size > std::numeric_limits<SIZE_T>::max() - heap_alignment) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
std::lock_guard guard(usage_lock);
if (!can_commit(size) && (!refresh_virtual_commits() || !can_commit(size))) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
auto* allocation = static_cast<unsigned char*>(_aligned_malloc(size + heap_alignment, heap_alignment));
if (!allocation) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
std::memcpy(allocation, &size, sizeof(size));
heap_bytes += size;
update_peak();
return allocation + heap_alignment;
}
VOID WINAPI XMemFreeDefault(PVOID address, uint64_t /*attributes*/) {
if (address) _aligned_free(address);
if (!address) return;
auto* allocation = static_cast<unsigned char*>(address) - heap_alignment;
SIZE_T size;
std::memcpy(&size, allocation, sizeof(size));
std::lock_guard guard(usage_lock);
_aligned_free(allocation);
heap_bytes -= size;
}
PVOID WINAPI XMemAlloc(SIZE_T size, uint64_t attributes) {
report_unsupported_host_hooks();
return XMemAllocDefault(size, attributes);
}
VOID WINAPI XMemFree(PVOID address, uint64_t attributes) {
report_unsupported_host_hooks();
XMemFreeDefault(address, attributes);
}
@@ -53,11 +179,89 @@ PVOID WINAPI XMemVirtualAlloc(PVOID address, SIZE_T size, DWORD alloc_type, DWOR
/* Strip console-only high bits before forwarding to standard Win32 VirtualAlloc. */
DWORD win_alloc = alloc_type & (MEM_COMMIT | MEM_RESERVE | MEM_RESET | MEM_TOP_DOWN);
if (win_alloc == 0) win_alloc = MEM_COMMIT | MEM_RESERVE;
DWORD win_prot = protect & 0xFFu;
if (win_prot == 0) win_prot = PAGE_READWRITE;
void* p = VirtualAlloc(address, size, win_alloc, win_prot);
if (p && (win_alloc & MEM_COMMIT)) record_alloc(size);
return p;
/* Console callers may pass multi-bit Xbox memory attributes (e.g. 0x21) in arg 4;
* valid Win32 base page protections are a single power-of-two bit in 0x01..0x80. */
DWORD low_prot = protect & 0xFFu;
DWORD win_prot = (low_prot != 0 && (low_prot & (low_prot - 1)) == 0)
? (protect & (0xFFu | PAGE_GUARD | PAGE_NOCACHE | PAGE_WRITECOMBINE))
: PAGE_READWRITE;
/* MEM_RESET combined with MEM_COMMIT is rejected by Win32 VirtualAlloc, so returning
* early here cannot commit pages outside the working-set budget. */
if (!(win_alloc & MEM_COMMIT) || (win_alloc & MEM_RESET)) {
return VirtualAlloc(address, size, win_alloc, win_prot);
}
const uintptr_t requested = reinterpret_cast<uintptr_t>(address);
const SIZE_T page = page_size();
// Explicit reservations round down to allocation granularity.
SIZE_T alignment = page;
if (win_alloc & MEM_RESERVE) {
SYSTEM_INFO info{};
GetSystemInfo(&info);
alignment = info.dwAllocationGranularity;
}
const uintptr_t begin = requested - requested % alignment;
constexpr uintptr_t max_address = std::numeric_limits<uintptr_t>::max();
if (!size || requested > max_address - (page - 1)
|| size > max_address - requested - (page - 1)) {
SetLastError(ERROR_INVALID_PARAMETER);
return nullptr;
}
const uintptr_t end = (requested + size + page - 1) & ~(page - 1);
std::lock_guard guard(usage_lock);
if (!refresh_virtual_commits()) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
CommitTable next;
for (const auto& commit : virtual_commits) {
if (!next.append(commit)) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
}
uint64_t charge = end - begin;
uintptr_t cursor = begin;
if (address && !(win_alloc & MEM_RESERVE)) {
for (const auto& commit : virtual_commits) {
if (commit.end <= cursor) continue;
if (commit.begin >= end) break;
if (cursor < commit.begin && !next.append({cursor, commit.begin, nullptr})) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
const uintptr_t overlap_end = std::min(end, commit.end);
charge -= overlap_end - std::max(cursor, commit.begin);
cursor = overlap_end;
}
}
if ((cursor < end && !next.append({cursor, end, nullptr})) || !can_commit(charge)) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return nullptr;
}
PVOID allocation = VirtualAlloc(address, size, win_alloc, win_prot);
if (!allocation || next.count == virtual_commits.count) return allocation;
MEMORY_BASIC_INFORMATION region{};
// A successful commit establishes a region containing the returned address.
VirtualQuery(allocation, &region, sizeof(region));
const uintptr_t relocation = address ? 0 : reinterpret_cast<uintptr_t>(allocation);
for (size_t i = virtual_commits.count; i < next.count; ++i) {
next.entries[i].begin += relocation;
next.entries[i].end += relocation;
next.entries[i].allocation_base = region.AllocationBase;
}
std::sort(next.begin(), next.end(), [](const auto& lhs, const auto& rhs) {
return lhs.begin < rhs.begin;
});
virtual_commits.swap(next);
virtual_bytes += charge;
update_peak();
return allocation;
}
SIZE_T WINAPI XMemVirtualQuery(LPCVOID address, PMEMORY_BASIC_INFORMATION buf, SIZE_T len) {
@@ -88,16 +292,28 @@ PVOID WINAPI XMemMapPhysicalPagesScatter(PVOID /*base*/, SIZE_T /*num_pages*/, u
}
BOOL WINAPI XMemTransferMemory(PVOID dst, LPCVOID src, SIZE_T bytes, uint64_t /*flags*/) {
if (!dst || !src) return FALSE;
std::memcpy(dst, src, bytes);
if (bytes == 0) return TRUE;
if (!dst || !src) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
std::memmove(dst, src, bytes);
return TRUE;
}
BOOL WINAPI XMemGetWorkingSetStatistics(PVOID out_stats, SIZE_T stats_size) {
BX_STUB_LOG("xmem.dll", "XMemGetWorkingSetStatistics");
if (out_stats && stats_size > 0) {
std::memset(out_stats, 0, stats_size);
if (!out_stats || stats_size < sizeof(bx_xmem_stats_t)) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
std::lock_guard guard(usage_lock);
if (!refresh_virtual_commits()) {
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return FALSE;
}
const bx_xmem_stats_t stats{title_limit(), heap_bytes + virtual_bytes, 0, peak_bytes};
std::memset(out_stats, 0, stats_size);
std::memcpy(out_stats, &stats, sizeof(stats));
return TRUE;
}
@@ -111,11 +327,12 @@ int bx_xmem_query_region(uint64_t /*va*/, bx_xmem_region_info_t* /*out_info*/) {
void bx_xmem_get_internal_stats(bx_xmem_stats_t* out_stats) {
if (!out_stats) return;
const bx_runtime_config_t* cfg = bx_get_runtime_config();
out_stats->title_limit_bytes = cfg ? cfg->title_memory_limit_bytes : (8ULL << 30);
out_stats->committed_virtual_bytes = g_committed_virtual.load();
out_stats->allocated_physical_bytes = g_allocated_physical.load();
out_stats->peak_committed_bytes = g_peak_committed.load();
if (!XMemGetWorkingSetStatistics(out_stats, sizeof(*out_stats))) {
// The internal ABI has no error return. Preserve the most recent
// accounting snapshot if refreshing it runs out of bookkeeping memory.
std::lock_guard guard(usage_lock);
*out_stats = {title_limit(), heap_bytes + virtual_bytes, 0, peak_bytes};
}
}
} // extern "C"
@@ -0,0 +1,3 @@
add_executable(test_audio_input main.cpp)
target_link_libraries(test_audio_input PRIVATE acphal xapu chad kernel32)
add_dependencies(test_audio_input gameinput)
+155
View File
@@ -0,0 +1,155 @@
#include <windows.h>
#include <unknwn.h>
#include <atomic>
#include <cstdint>
#include <cstdio>
#include <thread>
extern "C" {
HRESULT WINAPI AcpHalCreate(void**);
HRESULT WINAPI ApuCreateHeap(uint32_t, uint32_t);
HRESULT WINAPI ApuAlloc(void**, uint32_t*, uint32_t, uint32_t);
HRESULT WINAPI ApuFree(void*);
BOOL WINAPI ApuIsVirtualAddressValid(const void*, uint32_t);
void* WINAPI ApuMapApuAddress(uint32_t);
uint32_t WINAPI ApuMapVirtualAddress(const void*);
HRESULT WINAPI XApuConnect(void**);
HRESULT WINAPI XApuDisconnect(void*);
HRESULT WINAPI XApuEnqueueCommand(void*, const void*, uint32_t);
HRESULT WINAPI XApuDequeueResult(void*, void*, uint32_t);
uint32_t WINAPI XApuGetResultCount(void*);
HRESULT WINAPI XDspConnectWithMaximumStreamLimit(uint32_t, void**);
HRESULT WINAPI XDspActivate(void*);
HRESULT WINAPI XDspDeactivate(void*);
HRESULT WINAPI XDspSubmitCommand(void*, const void*, uint32_t);
HRESULT WINAPI XDspDisconnect(void*);
}
#define CHECK(expr) do { if (!(expr)) { std::fprintf(stderr, "line %d: %s\n", __LINE__, #expr); return 1; } } while (0)
int main() {
void* object = nullptr;
CHECK(AcpHalCreate(&object) == S_OK && object);
auto* hal = static_cast<IUnknown*>(object);
CHECK(hal->QueryInterface(IID_IUnknown, &object) == S_OK && object == hal);
CHECK(hal->Release() == 1);
void *va = nullptr, *second = nullptr;
uint32_t base = 0, other = 0;
CHECK(ApuAlloc(&va, &base, 64, 64) == E_OUTOFMEMORY && !va && !base);
CHECK(ApuCreateHeap(64, 64) == S_OK);
CHECK(ApuAlloc(&va, nullptr, 64, 64) == S_OK && va);
CHECK(ApuFree(va) == S_OK);
va = nullptr;
CHECK(ApuAlloc(nullptr, &base, 64, 64) == S_OK && base);
va = ApuMapApuAddress(base);
CHECK(va && ApuFree(va) == S_OK);
va = nullptr;
base = 0;
CHECK(ApuAlloc(&va, &base, 64, 256) == S_OK && va && base);
CHECK(reinterpret_cast<uintptr_t>(va) % 256 == 0 && base % 256 == 0);
CHECK(ApuAlloc(&second, &other, 64, 64) == S_OK && other != base);
CHECK(ApuCreateHeap(0, 0) == HRESULT_FROM_WIN32(ERROR_BUSY));
void* excess = nullptr;
CHECK(ApuAlloc(&excess, nullptr, 1, 64) == E_OUTOFMEMORY);
auto* tail = static_cast<unsigned char*>(va) + 63;
CHECK(ApuMapApuAddress(base + 63) == tail && ApuMapVirtualAddress(tail) == base + 63);
CHECK(ApuIsVirtualAddressValid(tail, 1) && !ApuIsVirtualAddressValid(tail, 2));
CHECK(ApuFree(tail) == E_INVALIDARG);
CHECK(ApuFree(va) == S_OK && !ApuMapApuAddress(base) && !ApuMapVirtualAddress(va));
CHECK(ApuFree(va) == E_INVALIDARG && ApuMapApuAddress(other) == second);
CHECK(ApuFree(second) == S_OK && hal->Release() == 0);
void *apu = nullptr, *peer = nullptr, *dsp = nullptr;
CHECK(XApuConnect(&apu) == S_OK && XApuConnect(&peer) == S_OK && peer != apu);
unsigned result = 0;
CHECK(XApuDequeueResult(apu, &result, sizeof(result)) == S_FALSE);
for (unsigned cycle = 0; cycle < 3; ++cycle) {
HRESULT status = S_OK;
unsigned accepted = 0;
std::thread producer([&] {
for (; accepted < 1024; ++accepted) {
unsigned command = cycle * 1024 + accepted;
status = XApuEnqueueCommand(apu, &command, sizeof(command));
if (status != S_OK) break;
}
});
producer.join();
CHECK(accepted && status == HRESULT_FROM_WIN32(ERROR_BUSY));
CHECK(XApuGetResultCount(apu) == accepted && XApuGetResultCount(peer) == 0);
CHECK(XApuDequeueResult(apu, &result, 1) == HRESULT_FROM_WIN32(ERROR_INSUFFICIENT_BUFFER));
for (unsigned i = 0; i < accepted; ++i) {
CHECK(XApuDequeueResult(apu, &result, sizeof(result)) == S_OK);
CHECK(result == cycle * 1024 + i);
}
CHECK(XApuGetResultCount(apu) == 0);
}
// A stalled peer must fail this test rather than wait forever.
constexpr unsigned messages = 4096;
const auto deadline = GetTickCount64() + 10000;
std::atomic<bool> failed{false};
std::thread worker([&] {
for (unsigned i = 0; i < messages && !failed;) {
const auto hr = XApuEnqueueCommand(apu, &i, sizeof(i));
if (hr == S_OK) ++i;
else if (hr != HRESULT_FROM_WIN32(ERROR_BUSY) || GetTickCount64() >= deadline)
failed = true;
else std::this_thread::yield();
}
});
for (unsigned i = 0; i < messages && !failed;) {
const auto hr = XApuDequeueResult(apu, &result, sizeof(result));
if (hr == S_OK && result == i) ++i;
else if (hr != S_FALSE || GetTickCount64() >= deadline) failed = true;
else std::this_thread::yield();
}
worker.join();
CHECK(!failed && XApuGetResultCount(apu) == 0);
CHECK(XApuDisconnect(apu) == S_OK && XApuDisconnect(peer) == S_OK);
CHECK(XApuEnqueueCommand(apu, &result, sizeof(result)) == E_HANDLE);
CHECK(XDspConnectWithMaximumStreamLimit(0, &dsp) == E_INVALIDARG && !dsp);
CHECK(XDspConnectWithMaximumStreamLimit(2, &dsp) == S_OK && dsp);
for (unsigned cycle = 0; cycle < 2; ++cycle) {
unsigned queued = 0;
HRESULT hr = S_OK;
while (queued < 1024 && (hr = XDspSubmitCommand(dsp, &result, sizeof(result))) == S_OK)
++queued;
CHECK(queued && hr == HRESULT_FROM_WIN32(ERROR_BUSY));
CHECK(XDspActivate(dsp) == S_OK);
for (unsigned i = 0; i <= queued; ++i)
CHECK(XDspSubmitCommand(dsp, &result, sizeof(result)) == S_OK);
CHECK(XDspDeactivate(dsp) == S_OK);
}
CHECK(XDspDisconnect(dsp) == S_OK && XDspActivate(dsp) == E_HANDLE);
HMODULE dll = LoadLibraryW(L"GameInput.dll");
CHECK(dll);
auto proc = GetProcAddress(dll, MAKEINTRESOURCEA(1));
CHECK(proc && proc == GetProcAddress(dll, "GameInputCreate"));
using Factory = HRESULT (WINAPI*)(void**);
auto create = reinterpret_cast<Factory>(reinterpret_cast<void*>(proc));
CHECK(create(&object) == S_OK && object);
auto* input = static_cast<IUnknown*>(object);
CHECK(create(&object) == S_OK && object == input && input->Release() == 1);
CHECK(input->QueryInterface(IID_IUnknown, &object) == S_OK && object == input);
CHECK(input->Release() == 1);
constexpr GUID kGameInputV0 = {0x11be2a7e, 0x4254, 0x445a,
{0x9c, 0x09, 0xff, 0xc4, 0x0f, 0x00, 0x69, 0x18}};
constexpr GUID kUnknownIid = {0x00000001, 0x0002, 0x0003,
{0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x0a, 0x0b}};
void* unknown = reinterpret_cast<void*>(uintptr_t{1});
CHECK(input->QueryInterface(kUnknownIid, &unknown) == E_NOINTERFACE && !unknown);
void* v0_obj = nullptr;
CHECK(input->QueryInterface(kGameInputV0, &v0_obj) == S_OK && v0_obj == input);
auto* v0 = static_cast<IUnknown*>(v0_obj);
auto** table = *reinterpret_cast<void***>(v0);
using Timestamp = uint64_t (WINAPI*)(IUnknown*);
CHECK(reinterpret_cast<Timestamp>(table[3])(v0) > 0);
using Reading = HRESULT (WINAPI*)(IUnknown*, uint32_t, void*, void**);
void* reading = reinterpret_cast<void*>(uintptr_t{1});
CHECK(reinterpret_cast<Reading>(table[4])(v0, 0, nullptr, &reading) == E_NOTIMPL && !reading);
CHECK(v0->Release() == 1);
CHECK(input->Release() == 0);
FreeLibrary(dll);
std::puts("PASS: audio mappings, APU and DSP queues, GameInput ordinal 1");
}
@@ -2,3 +2,6 @@ add_executable(test_veh_clwb main.cpp)
target_include_directories(test_veh_clwb PRIVATE "${BX_ABI_INCLUDE_DIR}")
target_compile_options(test_veh_clwb PRIVATE -mavx2 -mfma)
target_link_libraries(test_veh_clwb PRIVATE bx_runtime_veh xmem kernel32)
add_executable(test_veh_unhandled main_unhandled.cpp)
target_link_libraries(test_veh_unhandled PRIVATE bx_runtime_veh kernel32)
+19 -9
View File
@@ -29,15 +29,25 @@ int main() {
}
}
/* 2. Verify clwb trapping via bx_runtime_veh.dll (both legacy and REX forms) */
alignas(64) uint8_t buf[128] = {0x42};
uint64_t before = bx_veh_get_clwb_trap_count();
__asm__ volatile("clwb (%0)" :: "r"(buf) : "memory");
__asm__ volatile("clwb 64(%0)" :: "r"(buf) : "memory");
uint64_t after = bx_veh_get_clwb_trap_count();
std::printf("clwb traps observed: %llu -> %llu\n",
static_cast<unsigned long long>(before),
static_cast<unsigned long long>(after));
// Fixed registers ensure the assembler emits the intended ModRM/REX forms.
alignas(64) uint8_t buf[512] = {0x42};
const uint64_t before = bx_veh_get_clwb_trap_count();
__asm__ volatile(
"clwb (%%rax)\n\t"
"clwb 64(%%rax)\n\t"
"clwb 256(%%rax)\n\t"
"mov %%rax, %%r8\n\t"
"clwb (%%r8)\n\t"
"clwb 64(%%rax,%%rcx,4)\n\t"
"clwb (%%rip)"
:: "a"(buf), "c"(8) : "r8", "memory");
const uint64_t delta = bx_veh_get_clwb_trap_count() - before;
if (delta != 6) {
std::fprintf(stderr, "FAIL: expected 6 CLWB traps, observed %llu\n",
static_cast<unsigned long long>(delta));
return 4;
}
std::printf("CLWB traps observed: %llu\n", static_cast<unsigned long long>(delta));
/* 3. Verify basic XMem allocation + transfer + stats contract */
void* src = XMemAlloc(4096, 0);
@@ -0,0 +1,16 @@
#include <windows.h>
#include <cstdint>
extern "C" uint64_t bx_veh_get_clwb_trap_count(void);
// Run in its own process. The launcher should report failure and the trace
// should contain a single unhandled_exception with RAX set to the marker.
int main() {
SetErrorMode(SEM_NOGPFAULTERRORBOX);
// Keep a static import on bx_runtime_veh.dll so its DLL_PROCESS_ATTACH filter is installed.
volatile uint64_t attached_traps = bx_veh_get_clwb_trap_count();
(void)attached_traps;
constexpr uint64_t marker = 0x123456789abcdef0ULL;
__asm__ volatile("ud2" :: "a"(marker) : "memory");
return 1;
}
@@ -0,0 +1,3 @@
add_executable(test_xcrdapi main.cpp)
target_include_directories(test_xcrdapi PRIVATE "${BX_ROOT_DIR}/shims/xcrdapi")
target_link_libraries(test_xcrdapi PRIVATE xcrdapi kernel32 uuid)
+178
View File
@@ -0,0 +1,178 @@
#include "synthetic_storage.h"
#include <array>
#include <cstdio>
#include <cstring>
#include <limits>
using namespace bx::storage;
#define CHECK(condition) \
do { \
if (!(condition)) { \
std::fprintf(stderr, "xcrdapi:%d: %s (Win32 error %lu)\n", \
__LINE__, #condition, static_cast<unsigned long>(GetLastError())); \
return 1; \
} \
} while (false)
template<class Interface>
struct Com {
Interface* value = nullptr;
~Com() { if (value) value->Release(); }
Interface* operator->() const { return value; }
void** out() { return reinterpret_cast<void**>(&value); }
};
struct TemporaryFile {
WCHAR name[MAX_PATH]{};
~TemporaryFile() { if (*name) DeleteFileW(name); }
};
struct Event {
HANDLE handle = CreateEventW(nullptr, FALSE, FALSE, nullptr);
~Event() { if (handle) CloseHandle(handle); }
};
struct ForeignStatus final : Status {
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, void**) override { return E_NOINTERFACE; }
ULONG STDMETHODCALLTYPE AddRef() override { return 1; }
ULONG STDMETHODCALLTYPE Release() override { return 1; }
HRESULT STDMETHODCALLTYPE GetResult(UINT) override { return E_NOTIMPL; }
};
struct MockFence final : ID3D12Fence {
LONG refs = 1;
UINT64 value = 0;
HRESULT STDMETHODCALLTYPE QueryInterface(REFIID, void**) override { return E_NOINTERFACE; }
ULONG STDMETHODCALLTYPE AddRef() override { return InterlockedIncrement(&refs); }
ULONG STDMETHODCALLTYPE Release() override { return InterlockedDecrement(&refs); }
HRESULT STDMETHODCALLTYPE GetPrivateData(REFGUID, UINT*, void*) override { return E_NOTIMPL; }
HRESULT STDMETHODCALLTYPE SetPrivateData(REFGUID, UINT, const void*) override { return E_NOTIMPL; }
HRESULT STDMETHODCALLTYPE SetPrivateDataInterface(REFGUID, const IUnknown*) override { return E_NOTIMPL; }
HRESULT STDMETHODCALLTYPE SetName(LPCWSTR) override { return E_NOTIMPL; }
HRESULT STDMETHODCALLTYPE GetDevice(REFIID, void**) override { return E_NOTIMPL; }
UINT64 STDMETHODCALLTYPE GetCompletedValue() override { return value; }
HRESULT STDMETHODCALLTYPE SetEventOnCompletion(UINT64, HANDLE) override { return E_NOTIMPL; }
HRESULT STDMETHODCALLTYPE Signal(UINT64 v) override {
value = v;
return S_OK;
}
};
int main() {
void* unsupported = nullptr;
CHECK(DStorageGetFactory(file_iid, &unsupported) == E_NOINTERFACE && !unsupported);
CHECK(DStorageGetFactory(factory_iid, nullptr) == E_POINTER);
Com<Factory> factory;
CHECK(DStorageGetFactory(factory_iid, factory.out()) == S_OK);
Com<IUnknown> identity;
CHECK(factory->QueryInterface(IID_IUnknown, identity.out()) == S_OK);
CHECK(identity.value == factory.value);
CHECK(factory->SetStagingBufferSize(0) == S_OK);
TemporaryFile temporary;
WCHAR directory[MAX_PATH];
const DWORD directory_len = GetTempPathW(MAX_PATH, directory);
CHECK(directory_len && directory_len < MAX_PATH);
CHECK(GetTempFileNameW(directory, L"bxs", 0, temporary.name));
const HANDLE writer = CreateFileW(temporary.name, GENERIC_WRITE, 0, nullptr,
TRUNCATE_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
CHECK(writer != INVALID_HANDLE_VALUE);
constexpr char contents[] = "ABCDEF0123456789";
DWORD written = 0;
const BOOL wrote = WriteFile(writer, contents, sizeof(contents), &written, nullptr);
CloseHandle(writer);
CHECK(wrote && written == sizeof(contents));
Com<File> file;
CHECK(factory->OpenFile(temporary.name, file_iid, file.out()) == S_OK);
BY_HANDLE_FILE_INFORMATION file_info{};
CHECK(file->GetFileInformation(&file_info) == S_OK);
CHECK(file_info.nFileSizeHigh == 0 && file_info.nFileSizeLow == sizeof(contents));
Com<Status> status;
CHECK(factory->CreateStatusArray(2, status_iid, status.out()) == S_OK);
Event event;
CHECK(event.handle);
std::array<char, 5> first{}, second{}, copied{};
Com<Queue> queue;
CHECK(factory->CreateQueue(5, queue_iid, queue.out()) == S_OK);
Request read1{file.value, 2, nullptr, first.data(), 4, 0};
Request read2{file.value, 10, nullptr, second.data(), 4, 0};
Request copy{nullptr, 0, first.data(), copied.data(), 4, 0};
CHECK(queue->EnqueueRequest(&read1) == S_OK);
CHECK(queue->EnqueueRequest(&read2) == S_OK);
CHECK(queue->EnqueueRequest(&copy) == S_OK);
CHECK(queue->EnqueueStatus(status.value, 0) == S_OK);
CHECK(queue->EnqueueSetEvent(event.handle) == S_OK);
CHECK(queue->EnqueueRequest(&copy) == HRESULT_FROM_WIN32(ERROR_BUSY));
CHECK(status->GetResult(0) == E_PENDING);
CHECK(WaitForSingleObject(event.handle, 0) == WAIT_TIMEOUT);
CHECK(first[0] == 0 && second[0] == 0 && copied[0] == 0);
CHECK(queue->Submit() == S_OK);
CHECK(WaitForSingleObject(event.handle, 5000) == WAIT_OBJECT_0);
CHECK(status->GetResult(0) == S_OK);
CHECK(std::strcmp(first.data(), "CDEF") == 0);
CHECK(std::strcmp(second.data(), "4567") == 0);
CHECK(std::strcmp(copied.data(), "CDEF") == 0);
ErrorRecord error{};
CHECK(queue->RetrieveErrorRecord(&error) == S_OK && error.failure_count == 0);
Request past_end{file.value, sizeof(contents), nullptr, first.data(), 1, 0};
Request compressed{nullptr, 0, first.data(), copied.data(), 4, 1};
CHECK(queue->EnqueueRequest(&past_end) == S_OK);
CHECK(queue->EnqueueRequest(&compressed) == S_OK);
CHECK(queue->EnqueueStatus(status.value, 0) == S_OK);
CHECK(queue->EnqueueStatus(status.value, 1) == S_OK);
CHECK(queue->Submit() == S_OK);
CHECK(file->Close() == S_OK);
CHECK(file->GetFileInformation(&file_info) == HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE));
CHECK(queue->Close() == S_OK);
CHECK(status->GetResult(0) == HRESULT_FROM_WIN32(ERROR_HANDLE_EOF));
CHECK(status->GetResult(1) == S_OK);
CHECK(queue->RetrieveErrorRecord(&error) == S_OK);
CHECK(error.failure_count == 2 && error.first_error == HRESULT_FROM_WIN32(ERROR_HANDLE_EOF));
CHECK(queue->RetrieveErrorRecord(&error) == S_OK && error.failure_count == 0);
CHECK(queue->EnqueueRequest(&copy) == HRESULT_FROM_WIN32(ERROR_INVALID_HANDLE));
QueueInfo info{};
CHECK(queue->Query(&info) == S_OK && info.capacity == 5 && info.available == 5);
// Validation edge cases and Close()-without-Submit() drain coverage.
Com<Queue> edge_queue;
CHECK(factory->CreateQueue(4, queue_iid, edge_queue.out()) == S_OK);
CHECK(edge_queue->EnqueueRequest(nullptr) == E_INVALIDARG);
Request overflow{file.value, static_cast<UINT64>(std::numeric_limits<LONGLONG>::max()), nullptr, first.data(), 1, 0};
CHECK(edge_queue->EnqueueRequest(&overflow) == E_INVALIDARG);
Request ambiguous{file.value, 0, first.data(), copied.data(), 4, 0};
CHECK(edge_queue->EnqueueRequest(&ambiguous) == E_INVALIDARG);
ForeignStatus foreign_status;
CHECK(edge_queue->EnqueueStatus(&foreign_status, 0) == E_INVALIDARG);
CHECK(edge_queue->EnqueueStatus(status.value, 2) == E_INVALIDARG);
CHECK(edge_queue->EnqueueSignal(nullptr, 1) == E_POINTER);
std::array<char, 5> src_close{"WXYZ"};
std::array<char, 5> dst_close{};
Request close_copy{nullptr, 0, src_close.data(), dst_close.data(), 4, 0};
MockFence mock_fence;
Event close_event;
CHECK(close_event.handle);
CHECK(edge_queue->EnqueueRequest(&close_copy) == S_OK);
CHECK(edge_queue->EnqueueSignal(&mock_fence, 42) == S_OK);
CHECK(edge_queue->EnqueueStatus(status.value, 0) == S_OK);
CHECK(edge_queue->EnqueueStatus(status.value, 0) == HRESULT_FROM_WIN32(ERROR_BUSY));
CHECK(edge_queue->EnqueueSetEvent(close_event.handle) == S_OK);
CHECK(edge_queue->Close() == S_OK);
CHECK(std::strcmp(dst_close.data(), "WXYZ") == 0);
CHECK(mock_fence.value == 42 && mock_fence.refs == 1);
CHECK(status->GetResult(0) == S_OK);
CHECK(WaitForSingleObject(close_event.handle, 0) == WAIT_OBJECT_0);
std::puts("test_xcrdapi: passed");
}
@@ -0,0 +1,3 @@
add_executable(test_xmem main.cpp)
target_include_directories(test_xmem PRIVATE "${BX_ABI_INCLUDE_DIR}")
target_link_libraries(test_xmem PRIVATE xmem bx_runtime_veh kernel32)
+114
View File
@@ -0,0 +1,114 @@
#include <windows.h>
#include <cstdint>
#include <cstdio>
#include <cstring>
#include "bx_log.h"
#include "bx_xmem_internal.h"
extern "C" {
PVOID WINAPI XMemAlloc(SIZE_T, uint64_t);
PVOID WINAPI XMemAllocDefault(SIZE_T, uint64_t);
VOID WINAPI XMemFree(PVOID, uint64_t);
VOID WINAPI XMemFreeDefault(PVOID, uint64_t);
PVOID WINAPI XMemVirtualAlloc(PVOID, SIZE_T, DWORD, DWORD);
SIZE_T WINAPI XMemVirtualQuery(LPCVOID, PMEMORY_BASIC_INFORMATION, SIZE_T);
BOOL WINAPI XMemTransferMemory(PVOID, LPCVOID, SIZE_T, uint64_t);
BOOL WINAPI XMemGetWorkingSetStatistics(PVOID, SIZE_T);
BOOL WINAPI XMemIsToolsMemAvailable();
}
#define CHECK(condition) \
do { \
if (!(condition)) { \
std::fprintf(stderr, "xmem:%d: %s (Win32 error %lu)\n", __LINE__, \
#condition, static_cast<unsigned long>(GetLastError())); \
return 1; \
} \
} while (false)
int main() {
SYSTEM_INFO sys{};
GetSystemInfo(&sys);
const SIZE_T page = sys.dwPageSize;
const auto* config = bx_get_runtime_config();
bx_xmem_stats_t stats{};
CHECK(config && XMemGetWorkingSetStatistics(&stats, sizeof(stats)));
char profile[16]{};
GetEnvironmentVariableA("BX_PROFILE", profile, sizeof(profile));
const uint64_t expected_limit = std::strcmp(profile, "anaconda") == 0
? 13500ULL * 1024 * 1024
: 8ULL * 1024 * 1024 * 1024;
CHECK(stats.title_limit_bytes == expected_limit);
CHECK(stats.title_limit_bytes == config->title_memory_limit_bytes);
CHECK(stats.committed_virtual_bytes == 0 && stats.allocated_physical_bytes == 0);
CHECK(!XMemIsToolsMemAvailable());
CHECK(!XMemGetWorkingSetStatistics(&stats, sizeof(stats) - 1));
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
unsigned char large_stats[sizeof(bx_xmem_stats_t) + 16];
std::memset(large_stats, 0xCC, sizeof(large_stats));
CHECK(XMemGetWorkingSetStatistics(large_stats, sizeof(large_stats)));
for (size_t i = sizeof(bx_xmem_stats_t); i < sizeof(large_stats); ++i) {
CHECK(large_stats[i] == 0);
}
auto* ordinary = XMemAlloc(73, 0);
auto* empty = XMemAllocDefault(0, 0);
CHECK(ordinary && empty);
CHECK(reinterpret_cast<uintptr_t>(ordinary) % 64 == 0);
CHECK(reinterpret_cast<uintptr_t>(empty) % 64 == 0);
bx_xmem_get_internal_stats(&stats);
CHECK(stats.committed_virtual_bytes == 89);
// The existing heap charge should reject requests at the full cap
// without allocating gigabytes on the test host.
CHECK(!XMemAllocDefault(stats.title_limit_bytes, 0));
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
CHECK(!XMemVirtualAlloc(nullptr, stats.title_limit_bytes,
MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE));
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
XMemFreeDefault(empty, 0);
XMemFree(ordinary, 0);
auto* reserved = static_cast<unsigned char*>(
XMemVirtualAlloc(nullptr, page * 3, MEM_RESERVE, PAGE_READWRITE));
CHECK(reserved && reinterpret_cast<uintptr_t>(reserved) % page == 0);
CHECK(XMemVirtualAlloc(reserved, page * 2, MEM_COMMIT, PAGE_READWRITE) == reserved);
CHECK(XMemVirtualAlloc(reserved + page + 1, page * 2 - 1, MEM_COMMIT, PAGE_READWRITE)
== reserved + page);
MEMORY_BASIC_INFORMATION region{};
CHECK(XMemVirtualQuery(reserved + page, &region, sizeof(region)) == sizeof(region));
CHECK(region.AllocationBase == reserved && region.State == MEM_COMMIT);
CHECK(region.Protect == PAGE_READWRITE && region.RegionSize == page * 2);
constexpr char sample[] = "betterxen";
CHECK(XMemTransferMemory(reserved, sample, sizeof(sample), 0));
CHECK(XMemTransferMemory(reserved + 1, reserved, sizeof(sample), 0));
CHECK(std::memcmp(reserved + 1, sample, sizeof(sample)) == 0);
bx_xmem_get_internal_stats(&stats);
CHECK(stats.committed_virtual_bytes == page * 3 && stats.peak_committed_bytes == page * 3);
CHECK(VirtualFree(reserved + page, page, MEM_DECOMMIT));
bx_xmem_get_internal_stats(&stats);
CHECK(stats.committed_virtual_bytes == page * 2 && stats.peak_committed_bytes == page * 3);
CHECK(VirtualFree(reserved, 0, MEM_RELEASE));
bx_xmem_get_internal_stats(&stats);
CHECK(stats.committed_virtual_bytes == 0 && stats.peak_committed_bytes == page * 3);
// Console callers pass multi-bit attributes (e.g. 0x21) in arg 4 and high bits in alloc_type.
auto* console_res = static_cast<unsigned char*>(
XMemVirtualAlloc(nullptr, page * 2, MEM_RESERVE | 0x20400000u, 0x21u));
CHECK(console_res != nullptr);
CHECK(XMemVirtualAlloc(console_res, page, MEM_COMMIT, 0x21u) == console_res);
console_res[0] = 0x5Au;
CHECK(console_res[0] == 0x5Au);
CHECK(VirtualFree(console_res, 0, MEM_RELEASE));
bx_xmem_get_internal_stats(&stats);
CHECK(stats.committed_virtual_bytes == 0);
std::puts("test_xmem: passed");
}