mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-27 01:30:44 +00:00
Compare commits
12
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
486f7b197f | ||
|
|
390e85fc8d | ||
|
|
bfa80dee8b | ||
|
|
02b8924de7 | ||
|
|
925311e852 | ||
|
|
f7194d0255 | ||
|
|
7ea4f1f6ca | ||
|
|
bd8edd8f70 | ||
|
|
058bc981dc | ||
|
|
cee636193a | ||
|
|
43f32acb82 | ||
|
|
ab696f1f07 |
No files matched your search
@@ -10,6 +10,9 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
|
||||
remains unsupported.
|
||||
|
||||
### Added
|
||||
- Added file-mapping-backed 64 KiB and 2 MiB physical pages, contiguous and scatter aliases (including intra-span duplicate-tag aliasing), exact-span unmap validation, physical region queries (`bx_xmem_query_region`), and shared working-set accounting / combined title memory budget enforcement across heap, virtual, and physical allocations in `xmem.dll`. Synthetic `XMemAllocatePhysicalPages` / `XMemFreePhysicalPages` signatures follow Win32 AWE (`memoryapi.h`) pending a public console flag encoding (#412).
|
||||
- Added Win32 bridge conformance coverage for a hidden window, message dispatch, concurrent PSM registrations, and per-event JSONL log verification. Offline PSM registration tokens are tracked without C++ exceptions using disjoint family tags so cross-family unregisters log `foreign_token` and retired or invalid tokens log `unknown_token` (#410).
|
||||
- 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).
|
||||
@@ -68,6 +71,7 @@ remains unsupported.
|
||||
- Extended the read-only RDNA2 planning CLI (`python3 -m qa rdna2`) with family/status filters, compact summaries, Codex-ready manifests under `artifacts/`, active-claim exclusion (family claims exclude those families; path-only claims block overlapping permitted files), coverage reconcile against `semantic_coverage` without inflating counts, and inventory diffs. Covered by `tests/qa/test_rdna2_plan.py`; planning only, no GPU production edits.
|
||||
|
||||
### Fixed
|
||||
- `test_integration_boot.exe` now creates a real texture address computer, checks a two-mip layout against hand-computed values and requires the final `Release` to return 0, instead of reporting that stage as pending after a null-descriptor probe (#446).
|
||||
- `bx-cli trace` reports the highest sampled CLWB total as a lower bound, labels counterless CLWB records as samples, and lists unhandled exceptions with their code, module base, RVA, and RIP (#438).
|
||||
- Fixed the app's executable inspector so a late result from an earlier selection can no longer replace a newer one (#251). Each selection from the file picker, drag and drop or Finder Open With now takes a request number, and only the latest request may publish its report and status or clear the busy state. The previous report is cleared when a new file is chosen, and a failed inspection of the latest file is shown in red above its report. The read itself is unchanged: size checked before reading, balanced security-scoped access, nothing executed. `BetterXen --smoke-inspection-order`, run by `scripts/build-app.sh`, drives the model with an injected reader that blocks until the check releases each file, so the check (not timing) decides which read finishes first; it checks a stale success, a stale failure and a busy state held for the newer request, and all four checks fail without the change. Checked locally on Apple Silicon; not yet independently reviewed.
|
||||
- Startup reports now reject existing destinations before guest execution, surface journal write failures, and preserve late errors alongside signal termination.
|
||||
|
||||
+108
-24
@@ -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
@@ -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;
|
||||
}
|
||||
}
|
||||
@@ -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
@@ -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"
|
||||
@@ -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;
|
||||
}
|
||||
@@ -1,37 +1,249 @@
|
||||
#include <windows.h>
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstdint>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
namespace {
|
||||
std::atomic<uintptr_t> g_next_token{1};
|
||||
|
||||
static_assert(sizeof(uintptr_t) == 8, "BetterXen Win32 shims target x86-64");
|
||||
|
||||
constexpr uintptr_t kPrefixMask = 0xFFFFFFFF00000000ULL;
|
||||
constexpr uintptr_t kSequenceMask = 0x00000000FFFFFFFFULL;
|
||||
constexpr uintptr_t kStatePrefix = 0x50534D3100000000ULL; // "PSM1"
|
||||
constexpr uintptr_t kConstrainedPrefix = 0x50534D3200000000ULL; // "PSM2"
|
||||
constexpr uintptr_t kEmptySlot = 0;
|
||||
constexpr uintptr_t kTombstoneSlot = ~uintptr_t{0};
|
||||
|
||||
struct SrwLockGuard {
|
||||
SRWLOCK& lock;
|
||||
explicit SrwLockGuard(SRWLOCK& l) : lock(l) { AcquireSRWLockExclusive(&lock); }
|
||||
~SrwLockGuard() { ReleaseSRWLockExclusive(&lock); }
|
||||
SrwLockGuard(const SrwLockGuard&) = delete;
|
||||
SrwLockGuard& operator=(const SrwLockGuard&) = delete;
|
||||
};
|
||||
|
||||
// Exception-free open-addressed hash set backed by the Win32 process heap so
|
||||
// both PSM DLLs stay on -fno-exceptions and map OOM to ERROR_NOT_ENOUGH_MEMORY.
|
||||
struct TokenSet {
|
||||
uintptr_t* slots = nullptr;
|
||||
size_t capacity = 0;
|
||||
size_t count = 0;
|
||||
size_t used = 0; // active entries + tombstones
|
||||
|
||||
static size_t hash(uintptr_t value) {
|
||||
uint64_t x = static_cast<uint64_t>(value);
|
||||
x ^= x >> 30;
|
||||
x *= 0xbf58476d1ce4e5b9ULL;
|
||||
x ^= x >> 27;
|
||||
x *= 0x94d049bb133111ebULL;
|
||||
x ^= x >> 31;
|
||||
return static_cast<size_t>(x);
|
||||
}
|
||||
|
||||
bool rehash(size_t new_capacity) {
|
||||
if (new_capacity == 0 || new_capacity > SIZE_MAX / sizeof(uintptr_t)) {
|
||||
return false;
|
||||
}
|
||||
HANDLE heap = GetProcessHeap();
|
||||
if (!heap) {
|
||||
return false;
|
||||
}
|
||||
auto* fresh = static_cast<uintptr_t*>(
|
||||
HeapAlloc(heap, HEAP_ZERO_MEMORY, new_capacity * sizeof(uintptr_t)));
|
||||
if (!fresh) {
|
||||
return false;
|
||||
}
|
||||
const size_t mask = new_capacity - 1;
|
||||
for (size_t i = 0; i < capacity; ++i) {
|
||||
const uintptr_t entry = slots[i];
|
||||
if (entry != kEmptySlot && entry != kTombstoneSlot) {
|
||||
size_t idx = hash(entry) & mask;
|
||||
while (fresh[idx] != kEmptySlot) {
|
||||
idx = (idx + 1) & mask;
|
||||
}
|
||||
fresh[idx] = entry;
|
||||
}
|
||||
}
|
||||
if (slots) {
|
||||
HeapFree(heap, 0, slots);
|
||||
}
|
||||
slots = fresh;
|
||||
capacity = new_capacity;
|
||||
used = count;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool insert(uintptr_t token) {
|
||||
if (capacity == 0 || (used + 1) * 4 >= capacity * 3) {
|
||||
size_t next_capacity = 64;
|
||||
if (capacity != 0) {
|
||||
if (count * 2 >= capacity) {
|
||||
if (capacity > (SIZE_MAX / sizeof(uintptr_t)) / 2) {
|
||||
return false;
|
||||
}
|
||||
next_capacity = capacity * 2;
|
||||
} else {
|
||||
// Compact tombstones in place without growing the table.
|
||||
next_capacity = capacity;
|
||||
}
|
||||
}
|
||||
if (!rehash(next_capacity)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
const size_t mask = capacity - 1;
|
||||
size_t idx = hash(token) & mask;
|
||||
size_t first_tombstone = capacity;
|
||||
while (true) {
|
||||
const uintptr_t entry = slots[idx];
|
||||
if (entry == token) {
|
||||
return true;
|
||||
}
|
||||
if (entry == kEmptySlot) {
|
||||
if (first_tombstone != capacity) {
|
||||
slots[first_tombstone] = token;
|
||||
} else {
|
||||
slots[idx] = token;
|
||||
++used;
|
||||
}
|
||||
++count;
|
||||
return true;
|
||||
}
|
||||
if (entry == kTombstoneSlot && first_tombstone == capacity) {
|
||||
first_tombstone = idx;
|
||||
}
|
||||
idx = (idx + 1) & mask;
|
||||
}
|
||||
}
|
||||
|
||||
bool erase(uintptr_t token) {
|
||||
if (capacity == 0 || count == 0 || token == kEmptySlot || token == kTombstoneSlot) {
|
||||
return false;
|
||||
}
|
||||
const size_t mask = capacity - 1;
|
||||
size_t idx = hash(token) & mask;
|
||||
for (size_t probed = 0; probed < capacity; ++probed) {
|
||||
const uintptr_t entry = slots[idx];
|
||||
if (entry == kEmptySlot) {
|
||||
return false;
|
||||
}
|
||||
if (entry == token) {
|
||||
slots[idx] = kTombstoneSlot;
|
||||
--count;
|
||||
return true;
|
||||
}
|
||||
idx = (idx + 1) & mask;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
void reset() {
|
||||
if (slots) {
|
||||
HANDLE heap = GetProcessHeap();
|
||||
if (heap) {
|
||||
HeapFree(heap, 0, slots);
|
||||
}
|
||||
slots = nullptr;
|
||||
}
|
||||
capacity = 0;
|
||||
count = 0;
|
||||
used = 0;
|
||||
}
|
||||
};
|
||||
|
||||
struct Registrations {
|
||||
SRWLOCK lock;
|
||||
TokenSet active;
|
||||
uintptr_t own_prefix;
|
||||
uintptr_t foreign_prefix;
|
||||
uint64_t next_seq;
|
||||
};
|
||||
|
||||
// Each DLL exposes one family. Disjoint tagged token spaces prevent an
|
||||
// unregister call on the wrong DLL from removing another registration and let
|
||||
// logs distinguish foreign-family tokens from retired or invalid ones.
|
||||
Registrations g_state{SRWLOCK_INIT, {}, kStatePrefix, kConstrainedPrefix, 1};
|
||||
Registrations g_constrained{SRWLOCK_INIT, {}, kConstrainedPrefix, kStatePrefix, 1};
|
||||
|
||||
ULONG register_notification(Registrations& registrations, PVOID callback,
|
||||
PVOID* out_reg, const char* event) {
|
||||
if (!out_reg) {
|
||||
return ERROR_INVALID_PARAMETER;
|
||||
}
|
||||
*out_reg = nullptr;
|
||||
if (!callback) {
|
||||
return ERROR_INVALID_PARAMETER;
|
||||
}
|
||||
|
||||
uintptr_t token = 0;
|
||||
{
|
||||
const SrwLockGuard guard(registrations.lock);
|
||||
// Never recycle a token that a caller may still retain.
|
||||
if (registrations.next_seq > kSequenceMask) {
|
||||
return ERROR_NOT_ENOUGH_MEMORY;
|
||||
}
|
||||
token = registrations.own_prefix | static_cast<uintptr_t>(registrations.next_seq);
|
||||
if (!registrations.active.insert(token)) {
|
||||
return ERROR_NOT_ENOUGH_MEMORY;
|
||||
}
|
||||
++registrations.next_seq;
|
||||
}
|
||||
|
||||
*out_reg = reinterpret_cast<PVOID>(token);
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", event, "registered_offline");
|
||||
return ERROR_SUCCESS;
|
||||
}
|
||||
|
||||
void unregister_notification(Registrations& registrations, PVOID reg, const char* event) {
|
||||
const uintptr_t token = reinterpret_cast<uintptr_t>(reg);
|
||||
bool removed = false;
|
||||
{
|
||||
const SrwLockGuard guard(registrations.lock);
|
||||
removed = registrations.active.erase(token);
|
||||
}
|
||||
const char* detail = "unknown_token";
|
||||
if (removed) {
|
||||
detail = "unregistered";
|
||||
} else if ((token & kPrefixMask) == registrations.foreign_prefix &&
|
||||
(token & kSequenceMask) != 0) {
|
||||
detail = "foreign_token";
|
||||
}
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", event, detail);
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
extern "C" {
|
||||
|
||||
ULONG WINAPI RegisterAppStateChangeNotification(PVOID /*callback*/, PVOID /*context*/, PVOID* out_reg) {
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", "RegisterAppStateChangeNotification", "noop_ok");
|
||||
if (out_reg) {
|
||||
*out_reg = reinterpret_cast<PVOID>(g_next_token.fetch_add(1));
|
||||
BOOL WINAPI DllMain(HINSTANCE, DWORD reason, LPVOID reserved) {
|
||||
if (reason == DLL_PROCESS_DETACH && reserved == nullptr) {
|
||||
{
|
||||
const SrwLockGuard guard(g_state.lock);
|
||||
g_state.active.reset();
|
||||
}
|
||||
{
|
||||
const SrwLockGuard guard(g_constrained.lock);
|
||||
g_constrained.active.reset();
|
||||
}
|
||||
}
|
||||
return ERROR_SUCCESS;
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
VOID WINAPI UnregisterAppStateChangeNotification(PVOID /*reg*/) {
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", "UnregisterAppStateChangeNotification", "noop_ok");
|
||||
ULONG WINAPI RegisterAppStateChangeNotification(PVOID callback, PVOID /*context*/, PVOID* out_reg) {
|
||||
return register_notification(g_state, callback, out_reg, "RegisterAppStateChangeNotification");
|
||||
}
|
||||
|
||||
ULONG WINAPI RegisterAppConstrainedChangeNotification(PVOID /*callback*/, PVOID /*context*/, PVOID* out_reg) {
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", "RegisterAppConstrainedChangeNotification", "noop_ok");
|
||||
if (out_reg) {
|
||||
*out_reg = reinterpret_cast<PVOID>(g_next_token.fetch_add(1));
|
||||
}
|
||||
return ERROR_SUCCESS;
|
||||
VOID WINAPI UnregisterAppStateChangeNotification(PVOID reg) {
|
||||
unregister_notification(g_state, reg, "UnregisterAppStateChangeNotification");
|
||||
}
|
||||
|
||||
VOID WINAPI UnregisterAppConstrainedChangeNotification(PVOID /*reg*/) {
|
||||
bx_log_emit(BX_LOG_INFO, "win32_bridge", "UnregisterAppConstrainedChangeNotification", "noop_ok");
|
||||
ULONG WINAPI RegisterAppConstrainedChangeNotification(PVOID callback, PVOID /*context*/, PVOID* out_reg) {
|
||||
return register_notification(g_constrained, callback, out_reg, "RegisterAppConstrainedChangeNotification");
|
||||
}
|
||||
|
||||
VOID WINAPI UnregisterAppConstrainedChangeNotification(PVOID reg) {
|
||||
unregister_notification(g_constrained, reg, "UnregisterAppConstrainedChangeNotification");
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
@@ -1,4 +1,5 @@
|
||||
bx_add_shim_dll(xmem xmem xmem.def
|
||||
xmem.cpp
|
||||
physical_pages.cpp
|
||||
)
|
||||
target_link_libraries(xmem PRIVATE bx_runtime_veh kernel32)
|
||||
@@ -0,0 +1,385 @@
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <limits>
|
||||
#include <new>
|
||||
|
||||
#include "bx_log.h"
|
||||
#include "bx_xmem_internal.h"
|
||||
#include "xmem_accounting.h"
|
||||
|
||||
namespace {
|
||||
constexpr SIZE_T small_page = 64 * 1024;
|
||||
constexpr SIZE_T large_page = 2 * 1024 * 1024;
|
||||
|
||||
struct PageBlock;
|
||||
|
||||
struct Page {
|
||||
PageBlock* block;
|
||||
HANDLE section;
|
||||
bool releasing;
|
||||
};
|
||||
|
||||
struct PageBlock {
|
||||
ULONG_PTR first_tag;
|
||||
SIZE_T count;
|
||||
SIZE_T size;
|
||||
SIZE_T live;
|
||||
Page* entries;
|
||||
PageBlock* next;
|
||||
};
|
||||
|
||||
struct View {
|
||||
Page* page;
|
||||
BYTE* address;
|
||||
View* next;
|
||||
};
|
||||
|
||||
SRWLOCK memory_lock = SRWLOCK_INIT;
|
||||
PageBlock* blocks = nullptr;
|
||||
View* views = nullptr;
|
||||
ULONG_PTR next_tag = 1;
|
||||
|
||||
struct Lock {
|
||||
Lock() { AcquireSRWLockExclusive(&memory_lock); }
|
||||
~Lock() { ReleaseSRWLockExclusive(&memory_lock); }
|
||||
};
|
||||
|
||||
using ReservePlaceholder = PVOID (WINAPI*)(HANDLE, PVOID, SIZE_T, ULONG, ULONG,
|
||||
MEM_EXTENDED_PARAMETER*, ULONG);
|
||||
using ReplacePlaceholder = PVOID (WINAPI*)(HANDLE, HANDLE, PVOID, ULONG64, SIZE_T, ULONG,
|
||||
ULONG, MEM_EXTENDED_PARAMETER*, ULONG);
|
||||
|
||||
struct PlaceholderApi {
|
||||
HMODULE kernel = GetModuleHandleW(L"kernelbase.dll");
|
||||
ReservePlaceholder reserve = resolve<ReservePlaceholder>("VirtualAlloc2");
|
||||
ReplacePlaceholder replace = resolve<ReplacePlaceholder>("MapViewOfFile3");
|
||||
|
||||
template<class Function>
|
||||
Function resolve(const char* name) const {
|
||||
return reinterpret_cast<Function>(reinterpret_cast<void*>(GetProcAddress(kernel, name)));
|
||||
}
|
||||
};
|
||||
|
||||
// The public backlog defines the supported sizes. The flags accepted here
|
||||
// belong to BetterXen's synthetic fixtures, pending a public console flags ABI.
|
||||
SIZE_T page_size(uint64_t flags) {
|
||||
switch (flags) {
|
||||
case 0:
|
||||
case small_page: return small_page;
|
||||
case large_page: return large_page;
|
||||
default: return 0;
|
||||
}
|
||||
}
|
||||
|
||||
Page* find_page(ULONG_PTR tag) {
|
||||
for (PageBlock* block = blocks; block; block = block->next) {
|
||||
if (tag >= block->first_tag && tag - block->first_tag < block->count) {
|
||||
Page* page = &block->entries[tag - block->first_tag];
|
||||
return page->section ? page : nullptr;
|
||||
}
|
||||
}
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
ULONG_PTR page_tag(const Page* page) {
|
||||
return page->block->first_tag + (page - page->block->entries);
|
||||
}
|
||||
|
||||
void delete_block(PageBlock* block) {
|
||||
for (SIZE_T i = 0; i < block->count; ++i) {
|
||||
if (block->entries[i].section) CloseHandle(block->entries[i].section);
|
||||
}
|
||||
delete[] block->entries;
|
||||
delete block;
|
||||
}
|
||||
|
||||
void destroy_views(View* first) {
|
||||
while (first) {
|
||||
View* next = first->next;
|
||||
delete first;
|
||||
first = next;
|
||||
}
|
||||
}
|
||||
|
||||
bool valid_span(PVOID base, SIZE_T count, SIZE_T size) {
|
||||
const auto address = reinterpret_cast<uintptr_t>(base);
|
||||
return size && count && address % size == 0
|
||||
&& count <= (std::numeric_limits<uintptr_t>::max() - address) / size;
|
||||
}
|
||||
|
||||
bool remove_view(View** link) {
|
||||
View* view = *link;
|
||||
if (!UnmapViewOfFile(view->address)) return false;
|
||||
*link = view->next;
|
||||
delete view;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Require every page slot in [base, base + count * size) to be actively mapped
|
||||
// with matching page size before unmapping; empty or partial spans fail without
|
||||
// modifying any existing views.
|
||||
PVOID unmap_span(BYTE* base, SIZE_T count, SIZE_T size) {
|
||||
if (!base) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
const auto begin = reinterpret_cast<uintptr_t>(base);
|
||||
const auto end = begin + count * size;
|
||||
|
||||
SIZE_T matched = 0;
|
||||
for (const View* view = views; view; view = view->next) {
|
||||
const auto address = reinterpret_cast<uintptr_t>(view->address);
|
||||
if (address >= begin && address < end && view->page->block->size == size) {
|
||||
++matched;
|
||||
}
|
||||
}
|
||||
if (matched != count) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
for (View** link = &views; *link;) {
|
||||
View* view = *link;
|
||||
const auto address = reinterpret_cast<uintptr_t>(view->address);
|
||||
if (address >= begin && address < end && view->page->block->size == size) {
|
||||
if (!remove_view(link)) return nullptr;
|
||||
} else {
|
||||
link = &view->next;
|
||||
}
|
||||
}
|
||||
return base;
|
||||
}
|
||||
|
||||
// Duplicate tags in `tags` are intentionally permitted so a single virtual span
|
||||
// can alias one physical page at multiple offsets (e.g. ring buffers / tiles).
|
||||
PVOID map_pages(PVOID address, SIZE_T count, uint64_t flags, const ULONG_PTR* tags) {
|
||||
const SIZE_T size = page_size(flags);
|
||||
if (!valid_span(address, count, size)) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
Lock lock;
|
||||
if (!tags) return unmap_span(static_cast<BYTE*>(address), count, size);
|
||||
|
||||
static const PlaceholderApi api;
|
||||
if (!api.reserve || !api.replace) {
|
||||
BX_STUB_LOG("xmem.dll", "MapViewOfFile3");
|
||||
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
View* pending = nullptr;
|
||||
for (SIZE_T i = count; i > 0; --i) {
|
||||
Page* page = find_page(tags[i - 1]);
|
||||
if (!page || page->block->size != size) {
|
||||
destroy_views(pending);
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return nullptr;
|
||||
}
|
||||
auto* view = new (std::nothrow) View{page, nullptr, pending};
|
||||
if (!view) {
|
||||
destroy_views(pending);
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return nullptr;
|
||||
}
|
||||
pending = view;
|
||||
}
|
||||
|
||||
MEM_ADDRESS_REQUIREMENTS requirements{};
|
||||
requirements.Alignment = size;
|
||||
MEM_EXTENDED_PARAMETER alignment{};
|
||||
alignment.Type = MemExtendedParameterAddressRequirements;
|
||||
alignment.Pointer = &requirements;
|
||||
auto* base = static_cast<BYTE*>(api.reserve(nullptr, address, count * size,
|
||||
MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS,
|
||||
address ? nullptr : &alignment, address ? 0 : 1));
|
||||
if (!base) {
|
||||
const DWORD error = GetLastError();
|
||||
destroy_views(pending);
|
||||
SetLastError(error);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
BYTE* cursor = base;
|
||||
SIZE_T remaining = count;
|
||||
View* view = pending;
|
||||
for (; view; view = view->next, cursor += size, --remaining) {
|
||||
const bool split = remaining > 1;
|
||||
if (split && !VirtualFree(cursor, size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) break;
|
||||
if (!api.replace(view->page->section, nullptr, cursor, 0, size,
|
||||
MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0)) {
|
||||
const DWORD error = GetLastError();
|
||||
if (split) VirtualFree(cursor + size, 0, MEM_RELEASE);
|
||||
SetLastError(error);
|
||||
break;
|
||||
}
|
||||
view->address = cursor;
|
||||
}
|
||||
|
||||
if (view) {
|
||||
const DWORD error = GetLastError();
|
||||
VirtualFree(cursor, 0, MEM_RELEASE);
|
||||
for (View* completed = pending; completed != view; completed = completed->next) {
|
||||
UnmapViewOfFile(completed->address);
|
||||
}
|
||||
destroy_views(pending);
|
||||
SetLastError(error);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
while (pending) {
|
||||
View* next = pending->next;
|
||||
pending->next = views;
|
||||
views = pending;
|
||||
pending = next;
|
||||
}
|
||||
return base;
|
||||
}
|
||||
} // namespace
|
||||
|
||||
// Clean-room synthetic signatures modeled after public Win32 AWE
|
||||
// AllocateUserPhysicalPages / FreeUserPhysicalPages (memoryapi.h, [in, out]
|
||||
// page count pointer), pending a public console flags/signature ABI.
|
||||
extern "C" BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T* num_pages, PULONG_PTR page_array,
|
||||
uint64_t flags) {
|
||||
const SIZE_T size = page_size(flags);
|
||||
if (!num_pages || !page_array || !valid_span(nullptr, *num_pages, size)) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
Lock lock;
|
||||
const SIZE_T count = *num_pages;
|
||||
if (count > std::numeric_limits<ULONG_PTR>::max() - next_tag
|
||||
|| count > std::numeric_limits<SIZE_T>::max() / sizeof(Page)
|
||||
|| count > std::numeric_limits<uint64_t>::max() / size) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
}
|
||||
const uint64_t total_bytes = static_cast<uint64_t>(count) * size;
|
||||
if (!bx_xmem::try_reserve_physical(total_bytes)) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
auto* entries = new (std::nothrow) Page[count]{};
|
||||
if (!entries) {
|
||||
bx_xmem::release_physical(total_bytes);
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
}
|
||||
auto* block = new (std::nothrow) PageBlock{next_tag, count, size, count, entries, blocks};
|
||||
if (!block) {
|
||||
delete[] entries;
|
||||
bx_xmem::release_physical(total_bytes);
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
for (SIZE_T i = 0; i < count; ++i) {
|
||||
HANDLE section = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE,
|
||||
0, static_cast<DWORD>(size), nullptr);
|
||||
if (!section) {
|
||||
const DWORD error = GetLastError();
|
||||
delete_block(block);
|
||||
bx_xmem::release_physical(total_bytes);
|
||||
SetLastError(error);
|
||||
return FALSE;
|
||||
}
|
||||
entries[i] = {block, section, false};
|
||||
}
|
||||
|
||||
blocks = block;
|
||||
for (SIZE_T i = 0; i < count; ++i) page_array[i] = next_tag + i;
|
||||
next_tag += count;
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
// Rejects unknown, wrong-size, or duplicate tags in `page_array` with
|
||||
// ERROR_INVALID_PARAMETER without mutating `page_array` or live views.
|
||||
extern "C" BOOL WINAPI XMemFreePhysicalPages(SIZE_T* num_pages, PULONG_PTR page_array,
|
||||
uint64_t flags) {
|
||||
const SIZE_T size = page_size(flags);
|
||||
if (!num_pages || !page_array || !valid_span(nullptr, *num_pages, size)) {
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
Lock lock;
|
||||
const SIZE_T count = *num_pages;
|
||||
SIZE_T validated = 0;
|
||||
for (; validated < count; ++validated) {
|
||||
Page* page = find_page(page_array[validated]);
|
||||
if (!page || page->block->size != size || page->releasing) break;
|
||||
page->releasing = true;
|
||||
}
|
||||
if (validated != count) {
|
||||
for (SIZE_T i = 0; i < validated; ++i) find_page(page_array[i])->releasing = false;
|
||||
SetLastError(ERROR_INVALID_PARAMETER);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
for (View** link = &views; *link;) {
|
||||
if ((*link)->page->releasing) {
|
||||
if (!remove_view(link)) {
|
||||
const DWORD error = GetLastError();
|
||||
for (SIZE_T i = 0; i < count; ++i) find_page(page_array[i])->releasing = false;
|
||||
SetLastError(error);
|
||||
return FALSE;
|
||||
}
|
||||
} else {
|
||||
link = &(*link)->next;
|
||||
}
|
||||
}
|
||||
|
||||
for (SIZE_T i = 0; i < count; ++i) {
|
||||
Page* page = find_page(page_array[i]);
|
||||
CloseHandle(page->section);
|
||||
page->section = nullptr;
|
||||
--page->block->live;
|
||||
page_array[i] = 0;
|
||||
}
|
||||
for (PageBlock** link = &blocks; *link;) {
|
||||
PageBlock* block = *link;
|
||||
if (block->live) {
|
||||
link = &block->next;
|
||||
} else {
|
||||
*link = block->next;
|
||||
delete_block(block);
|
||||
}
|
||||
}
|
||||
bx_xmem::release_physical(static_cast<uint64_t>(count) * size);
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
extern "C" PVOID WINAPI XMemMapPhysicalPages(PVOID base, SIZE_T count, uint64_t flags,
|
||||
PULONG_PTR page_array) {
|
||||
return map_pages(base, count, flags, page_array);
|
||||
}
|
||||
|
||||
extern "C" PVOID WINAPI XMemMapPhysicalPagesScatter(PVOID base, SIZE_T count, uint64_t flags,
|
||||
PULONG_PTR page_array) {
|
||||
return map_pages(base, count, flags, page_array);
|
||||
}
|
||||
|
||||
extern "C" int bx_xmem_query_region(uint64_t va, bx_xmem_region_info_t* out_info) {
|
||||
if (!out_info) return 0;
|
||||
|
||||
Lock lock;
|
||||
for (const View* view = views; view; view = view->next) {
|
||||
const auto base = reinterpret_cast<uintptr_t>(view->address);
|
||||
const SIZE_T size = view->page->block->size;
|
||||
if (va >= base && va - base < size) {
|
||||
MEMORY_BASIC_INFORMATION region{};
|
||||
if (!VirtualQuery(view->address, ®ion, sizeof(region))
|
||||
|| region.AllocationBase != view->address || region.Type != MEM_MAPPED) {
|
||||
return 0;
|
||||
}
|
||||
*out_info = {base, size, size, region.Protect, region.Type, page_tag(view->page)};
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
+25
-31
@@ -10,6 +10,7 @@
|
||||
|
||||
#include "bx_log.h"
|
||||
#include "bx_xmem_internal.h"
|
||||
#include "xmem_accounting.h"
|
||||
|
||||
namespace {
|
||||
constexpr SIZE_T heap_alignment = 64;
|
||||
@@ -61,6 +62,7 @@ std::mutex usage_lock;
|
||||
CommitTable virtual_commits;
|
||||
uint64_t heap_bytes = 0;
|
||||
uint64_t virtual_bytes = 0;
|
||||
uint64_t physical_bytes = 0;
|
||||
uint64_t peak_bytes = 0;
|
||||
|
||||
uint64_t title_limit() {
|
||||
@@ -70,12 +72,12 @@ uint64_t title_limit() {
|
||||
|
||||
bool can_commit(uint64_t bytes) {
|
||||
const uint64_t limit = title_limit();
|
||||
const uint64_t used = heap_bytes + virtual_bytes;
|
||||
const uint64_t used = heap_bytes + virtual_bytes + physical_bytes;
|
||||
return used <= limit && bytes <= limit - used;
|
||||
}
|
||||
|
||||
void update_peak() {
|
||||
peak_bytes = std::max(peak_bytes, heap_bytes + virtual_bytes);
|
||||
peak_bytes = std::max(peak_bytes, heap_bytes + virtual_bytes + physical_bytes);
|
||||
}
|
||||
|
||||
uintptr_t region_end(const MEMORY_BASIC_INFORMATION& region) {
|
||||
@@ -268,29 +270,6 @@ SIZE_T WINAPI XMemVirtualQuery(LPCVOID address, PMEMORY_BASIC_INFORMATION buf, S
|
||||
return VirtualQuery(address, buf, len);
|
||||
}
|
||||
|
||||
BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T* /*num_pages*/, PULONG_PTR /*page_array*/, uint64_t /*flags*/) {
|
||||
BX_STUB_LOG("xmem.dll", "XMemAllocatePhysicalPages");
|
||||
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
BOOL WINAPI XMemFreePhysicalPages(SIZE_T /*num_pages*/, PULONG_PTR /*page_array*/, uint64_t /*flags*/) {
|
||||
BX_STUB_LOG("xmem.dll", "XMemFreePhysicalPages");
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
PVOID WINAPI XMemMapPhysicalPages(PVOID /*base*/, SIZE_T /*num_pages*/, uint64_t /*flags*/, PULONG_PTR /*page_array*/) {
|
||||
BX_STUB_LOG("xmem.dll", "XMemMapPhysicalPages");
|
||||
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
PVOID WINAPI XMemMapPhysicalPagesScatter(PVOID /*base*/, SIZE_T /*num_pages*/, uint64_t /*flags*/, PULONG_PTR /*page_array*/) {
|
||||
BX_STUB_LOG("xmem.dll", "XMemMapPhysicalPagesScatter");
|
||||
SetLastError(ERROR_CALL_NOT_IMPLEMENTED);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
BOOL WINAPI XMemTransferMemory(PVOID dst, LPCVOID src, SIZE_T bytes, uint64_t /*flags*/) {
|
||||
if (bytes == 0) return TRUE;
|
||||
if (!dst || !src) {
|
||||
@@ -311,7 +290,7 @@ BOOL WINAPI XMemGetWorkingSetStatistics(PVOID out_stats, SIZE_T stats_size) {
|
||||
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
|
||||
return FALSE;
|
||||
}
|
||||
const bx_xmem_stats_t stats{title_limit(), heap_bytes + virtual_bytes, 0, peak_bytes};
|
||||
const bx_xmem_stats_t stats{title_limit(), heap_bytes + virtual_bytes, physical_bytes, peak_bytes};
|
||||
std::memset(out_stats, 0, stats_size);
|
||||
std::memcpy(out_stats, &stats, sizeof(stats));
|
||||
return TRUE;
|
||||
@@ -321,18 +300,33 @@ BOOL WINAPI XMemIsToolsMemAvailable(void) {
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
int bx_xmem_query_region(uint64_t /*va*/, bx_xmem_region_info_t* /*out_info*/) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
void bx_xmem_get_internal_stats(bx_xmem_stats_t* out_stats) {
|
||||
if (!out_stats) return;
|
||||
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};
|
||||
*out_stats = {title_limit(), heap_bytes + virtual_bytes, physical_bytes, peak_bytes};
|
||||
}
|
||||
}
|
||||
|
||||
} // extern "C"
|
||||
|
||||
namespace bx_xmem {
|
||||
|
||||
bool try_reserve_physical(uint64_t bytes) {
|
||||
std::lock_guard guard(usage_lock);
|
||||
if (!can_commit(bytes) && (!refresh_virtual_commits() || !can_commit(bytes))) {
|
||||
return false;
|
||||
}
|
||||
physical_bytes += bytes;
|
||||
update_peak();
|
||||
return true;
|
||||
}
|
||||
|
||||
void release_physical(uint64_t bytes) {
|
||||
std::lock_guard guard(usage_lock);
|
||||
physical_bytes = physical_bytes >= bytes ? physical_bytes - bytes : 0;
|
||||
}
|
||||
|
||||
} // namespace bx_xmem
|
||||
@@ -0,0 +1,15 @@
|
||||
#ifndef BETTERXEN_SHIMS_XMEM_ACCOUNTING_H
|
||||
#define BETTERXEN_SHIMS_XMEM_ACCOUNTING_H
|
||||
|
||||
#include <cstdint>
|
||||
|
||||
namespace bx_xmem {
|
||||
|
||||
// Reserve or release physical-page bytes against the shared xmem title memory
|
||||
// cap and working-set statistics (heap + virtual + physical <= title limit).
|
||||
bool try_reserve_physical(uint64_t bytes);
|
||||
void release_physical(uint64_t bytes);
|
||||
|
||||
} // namespace bx_xmem
|
||||
|
||||
#endif // BETTERXEN_SHIMS_XMEM_ACCOUNTING_H
|
||||
@@ -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)
|
||||
@@ -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");
|
||||
}
|
||||
@@ -6,7 +6,9 @@
|
||||
# CreateWindowExA & co. bind to the ext-ms-win-rtcore-ntuser-* shims instead of
|
||||
# the toolchain's default user32 import library.
|
||||
add_executable(test_integration_boot main.cpp)
|
||||
target_include_directories(test_integration_boot PRIVATE "${BX_ABI_INCLUDE_DIR}")
|
||||
target_include_directories(test_integration_boot PRIVATE
|
||||
"${BX_ABI_INCLUDE_DIR}"
|
||||
"${CMAKE_CURRENT_SOURCE_DIR}/../../../shims/xg_xs")
|
||||
target_link_libraries(test_integration_boot PRIVATE
|
||||
ntuser_win_ansi_1_0
|
||||
ntuser_win_1_0
|
||||
|
||||
@@ -24,7 +24,8 @@
|
||||
* or an error-severity exception.
|
||||
*
|
||||
* Function prototypes below mirror the in-tree shim sources and abi/defs; this
|
||||
* fixture deliberately invents no console structure layouts.
|
||||
* fixture deliberately invents no console structure layouts. The xg_xs
|
||||
* descriptor and vtable are BetterXen's own, from shims/xg_xs/xg_texture.h.
|
||||
*/
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
@@ -40,6 +41,7 @@
|
||||
#include "bx_config.h"
|
||||
#include "bx_log.h"
|
||||
#include "bx_xmem_internal.h"
|
||||
#include "xg_texture.h"
|
||||
|
||||
#define BX_IMPORT __declspec(dllimport)
|
||||
|
||||
@@ -94,11 +96,7 @@ BX_IMPORT HRESULT WINAPI XDspDisconnect(void* handle);
|
||||
/* GameInput.dll (ordinal 1) */
|
||||
BX_IMPORT HRESULT WINAPI GameInputCreate(void** out_game_input);
|
||||
|
||||
/* xg_xs.dll */
|
||||
BX_IMPORT HRESULT WINAPI XGCreateTextureComputer(const void* desc, void** out_computer);
|
||||
BX_IMPORT uint32_t WINAPI XGSuggestSwizzleMode(uint32_t resource_type, uint32_t format, uint32_t width,
|
||||
uint32_t height, uint32_t depth, uint32_t mip_levels,
|
||||
uint32_t sample_count, uint32_t flags);
|
||||
/* xg_xs.dll is declared by "xg_texture.h". */
|
||||
|
||||
/* d3d12_xs.dll (D3D12SerializeVersionedRootSignature is declared by <d3d12.h>) */
|
||||
BX_IMPORT HRESULT WINAPI D3D12XboxCreateDevice(PVOID params, REFIID riid, void** ppv);
|
||||
@@ -651,27 +649,71 @@ void stage_acphal_heap() {
|
||||
|
||||
/* ---- Stage 13: xg_xs ---------------------------------------------------------------------- */
|
||||
|
||||
/*
|
||||
* 100x50 R8G8B8A8 with two mips, so both public D3D12 alignments matter. By hand:
|
||||
* mip 0: 100 * 4 = 400 bytes per row, pitch 512 (256-byte pitch alignment);
|
||||
* ends at 49 * 512 + 400 = 25488.
|
||||
* mip 1: starts at the next 512 boundary, 25600; 50 * 4 = 200 bytes per row,
|
||||
* pitch 256; ends at 25600 + 24 * 256 + 200 = 31944.
|
||||
* total: 31944 rounded up to 512 = 32256.
|
||||
*/
|
||||
void* stage_xg_texture_computer() {
|
||||
begin_stage("xg_xs_texture_computer");
|
||||
bx_xg_resource_desc desc = {};
|
||||
desc.dimension = BX_XG_DIMENSION_TEXTURE2D;
|
||||
desc.width = 100;
|
||||
desc.height = 50;
|
||||
desc.depth_or_array_size = 1;
|
||||
desc.mip_levels = 2;
|
||||
desc.format = DXGI_FORMAT_R8G8B8A8_UNORM;
|
||||
desc.sample_desc.count = 1;
|
||||
desc.layout = BX_XG_LAYOUT_LINEAR;
|
||||
|
||||
void* object = reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD));
|
||||
HRESULT hr = XGCreateTextureComputer(&desc, &object);
|
||||
if (hr != S_OK || !object || object == reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD))) {
|
||||
checkpoint("xg_xs_texture_computer", Status::Fail, "XGCreateTextureComputer hr=0x%08lx object=%p",
|
||||
static_cast<unsigned long>(hr), object);
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
auto* computer = static_cast<bx_xg_texture_computer*>(object);
|
||||
bx_xg_placed_footprint mips[2] = {};
|
||||
uint32_t rows[2] = {};
|
||||
uint64_t row_bytes[2] = {};
|
||||
uint64_t total = 0;
|
||||
hr = computer->lpVtbl->GetResourceLayout(computer, 0, 2, 0, mips, rows, row_bytes, &total);
|
||||
auto shape_is = [](const bx_xg_subresource_footprint& f, uint32_t width, uint32_t height, uint32_t pitch) {
|
||||
return f.format == DXGI_FORMAT_R8G8B8A8_UNORM && f.width == width && f.height == height && f.depth == 1 &&
|
||||
f.row_pitch == pitch;
|
||||
};
|
||||
const bool mip0 = mips[0].offset == 0 && shape_is(mips[0].footprint, 100, 50, 512) && mips[0].copy_end == 25488 &&
|
||||
rows[0] == 50 && row_bytes[0] == 400;
|
||||
const bool mip1 = mips[1].offset == 25600 && shape_is(mips[1].footprint, 50, 25, 256) && mips[1].copy_end == 31944 &&
|
||||
rows[1] == 25 && row_bytes[1] == 200;
|
||||
if (hr == S_OK && mip0 && mip1 && total == 32256) {
|
||||
checkpoint("xg_xs_texture_computer", Status::Pass,
|
||||
"100x50 RGBA8 two-mip linear footprints and 32256 total bytes match hand-computed values");
|
||||
} else {
|
||||
checkpoint("xg_xs_texture_computer", Status::Fail,
|
||||
"GetResourceLayout hr=0x%08lx mip0_ok=%d mip1_ok=%d total=%llu",
|
||||
static_cast<unsigned long>(hr), mip0, mip1, static_cast<unsigned long long>(total));
|
||||
}
|
||||
return object;
|
||||
}
|
||||
|
||||
void* stage_xg_xs() {
|
||||
begin_stage("xg_xs_swizzle_mode");
|
||||
/* D3D12_RESOURCE_DIMENSION_TEXTURE2D / DXGI_FORMAT_R8G8B8A8_UNORM, 256x256, 1 mip, 1 sample. */
|
||||
uint32_t mode_a = XGSuggestSwizzleMode(D3D12_RESOURCE_DIMENSION_TEXTURE2D, DXGI_FORMAT_R8G8B8A8_UNORM, 256, 256, 1, 1, 1, 0);
|
||||
uint32_t mode_b = XGSuggestSwizzleMode(D3D12_RESOURCE_DIMENSION_TEXTURE2D, DXGI_FORMAT_R8G8B8A8_UNORM, 256, 256, 1, 1, 1, 0);
|
||||
if (mode_a == mode_b) {
|
||||
checkpoint("xg_xs_swizzle_mode", Status::Pass, "XGSuggestSwizzleMode is deterministic for identical inputs (mode=%u)", mode_a);
|
||||
if (mode_a == BX_XG_LAYOUT_LINEAR && mode_b == mode_a) {
|
||||
checkpoint("xg_xs_swizzle_mode", Status::Pass, "XGSuggestSwizzleMode suggests linear and is deterministic (mode=%u)", mode_a);
|
||||
} else {
|
||||
checkpoint("xg_xs_swizzle_mode", Status::Fail, "XGSuggestSwizzleMode returned %u then %u for identical inputs", mode_a, mode_b);
|
||||
checkpoint("xg_xs_swizzle_mode", Status::Fail, "XGSuggestSwizzleMode returned %u then %u, expected linear", mode_a, mode_b);
|
||||
}
|
||||
|
||||
begin_stage("xg_xs_texture_computer");
|
||||
void* computer = reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD));
|
||||
HRESULT hr = XGCreateTextureComputer(nullptr, &computer);
|
||||
if (computer == reinterpret_cast<void*>(static_cast<uintptr_t>(0xDEAD))) {
|
||||
checkpoint("xg_xs_texture_computer", Status::Fail, "XGCreateTextureComputer left the out pointer unwritten (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(hr));
|
||||
return nullptr;
|
||||
}
|
||||
report_create("xg_xs_texture_computer", "XGCreateTextureComputer", hr, computer, true);
|
||||
return hr == S_OK ? computer : nullptr;
|
||||
return stage_xg_texture_computer();
|
||||
}
|
||||
|
||||
/* ---- Stage 14: d3d12_xs ------------------------------------------------------------------- */
|
||||
@@ -825,7 +867,12 @@ int main(int argc, char** argv) {
|
||||
/* --- Shutdown (reverse order) ----------------------------------------- */
|
||||
begin_stage("shutdown");
|
||||
release_com(device);
|
||||
release_com(texture_computer);
|
||||
/* The fixture holds the only reference, so this Release must return 0. */
|
||||
ULONG texture_refs = 0;
|
||||
if (texture_computer) {
|
||||
auto* computer = static_cast<bx_xg_texture_computer*>(texture_computer);
|
||||
texture_refs = computer->lpVtbl->Release(computer);
|
||||
}
|
||||
release_com(game_input);
|
||||
bool dsp_closed = true;
|
||||
if (dsp) {
|
||||
@@ -841,10 +888,11 @@ int main(int argc, char** argv) {
|
||||
if (runtime_initialized) XGameRuntimeUninitialize();
|
||||
|
||||
LONG faults = InterlockedCompareExchange(&g_error_exceptions, 0, 0);
|
||||
if (dsp_closed && apu_closed && faults == 0) {
|
||||
if (dsp_closed && apu_closed && texture_refs == 0 && faults == 0) {
|
||||
checkpoint("shutdown", Status::Pass, "reverse-order teardown completed with 0 error-severity exceptions");
|
||||
} else {
|
||||
checkpoint("shutdown", Status::Fail, "dsp_closed=%d apu_closed=%d error_exceptions=%ld", dsp_closed, apu_closed, faults);
|
||||
checkpoint("shutdown", Status::Fail, "dsp_closed=%d apu_closed=%d texture_refs=%lu error_exceptions=%ld",
|
||||
dsp_closed, apu_closed, texture_refs, faults);
|
||||
}
|
||||
if (fault_handle) RemoveVectoredExceptionHandler(fault_handle);
|
||||
SetUnhandledExceptionFilter(g_prev_unhandled_filter);
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
add_executable(test_win32_bridge main.cpp)
|
||||
target_link_libraries(test_win32_bridge PRIVATE kernel32 user32)
|
||||
add_dependencies(test_win32_bridge
|
||||
psm_appnotify_1_0 psm_appnotify_1_1
|
||||
ntuser_msg_1_0 ntuser_msg_ansi_1_0 ntuser_win_1_0 ntuser_win_ansi_1_0
|
||||
)
|
||||
@@ -0,0 +1,372 @@
|
||||
#include <windows.h>
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <bit>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <thread>
|
||||
#include <unordered_set>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr UINT kMessage = WM_APP + 1;
|
||||
constexpr WPARAM kPayload = 42;
|
||||
decltype(&DefWindowProcA) g_def_window_proc;
|
||||
bool g_received_message = false;
|
||||
std::atomic<bool> g_callback_called{false};
|
||||
|
||||
struct ScopedModule {
|
||||
HMODULE handle = nullptr;
|
||||
ScopedModule() = default;
|
||||
explicit ScopedModule(HMODULE h) : handle(h) {}
|
||||
~ScopedModule() {
|
||||
if (handle) {
|
||||
FreeLibrary(handle);
|
||||
}
|
||||
}
|
||||
ScopedModule(const ScopedModule&) = delete;
|
||||
ScopedModule& operator=(const ScopedModule&) = delete;
|
||||
explicit operator bool() const { return handle != nullptr; }
|
||||
HMODULE get() const { return handle; }
|
||||
};
|
||||
|
||||
LRESULT CALLBACK window_proc(HWND window, UINT message, WPARAM wparam, LPARAM lparam) {
|
||||
if (message == kMessage) {
|
||||
g_received_message = wparam == kPayload;
|
||||
return 0;
|
||||
}
|
||||
return g_def_window_proc(window, message, wparam, lparam);
|
||||
}
|
||||
|
||||
void CALLBACK notification_callback(BOOLEAN, PVOID) {
|
||||
g_callback_called.store(true);
|
||||
}
|
||||
|
||||
HMODULE load_bridge(const wchar_t* dll) {
|
||||
wchar_t executable[MAX_PATH];
|
||||
const DWORD length = GetModuleFileNameW(nullptr, executable, MAX_PATH);
|
||||
if (!length || length == MAX_PATH) {
|
||||
return nullptr;
|
||||
}
|
||||
const std::wstring path(executable, length);
|
||||
const auto expected = path.substr(0, path.find_last_of(L"\\/") + 1) + dll;
|
||||
HMODULE module = LoadLibraryW(expected.c_str());
|
||||
if (!module) {
|
||||
std::fwprintf(stderr, L"FAIL: could not load built bridge %ls (error %lu)\n",
|
||||
expected.c_str(), GetLastError());
|
||||
return nullptr;
|
||||
}
|
||||
wchar_t actual[MAX_PATH];
|
||||
const DWORD actual_length = GetModuleFileNameW(module, actual, MAX_PATH);
|
||||
if (!actual_length || actual_length == MAX_PATH) {
|
||||
const DWORD err = GetLastError();
|
||||
FreeLibrary(module);
|
||||
std::fwprintf(stderr, L"FAIL: could not query path for bridge %ls (error %lu)\n",
|
||||
expected.c_str(), err);
|
||||
return nullptr;
|
||||
}
|
||||
if (CompareStringOrdinal(expected.c_str(), -1, actual, -1, TRUE) != CSTR_EQUAL) {
|
||||
FreeLibrary(module);
|
||||
std::fwprintf(stderr, L"FAIL: bridge %ls resolved to unexpected path %ls\n",
|
||||
expected.c_str(), actual);
|
||||
return nullptr;
|
||||
}
|
||||
return module;
|
||||
}
|
||||
|
||||
template<typename Function>
|
||||
Function lookup(HMODULE module, const char* name) {
|
||||
return std::bit_cast<Function>(GetProcAddress(module, name));
|
||||
}
|
||||
|
||||
bool test_window() {
|
||||
const ScopedModule window(load_bridge(L"ext-ms-win-rtcore-ntuser-window-l1-1-0.dll"));
|
||||
const ScopedModule window_ansi(load_bridge(L"ext-ms-win-rtcore-ntuser-window-ansi-l1-1-0.dll"));
|
||||
const ScopedModule message(load_bridge(L"ext-ms-win-rtcore-ntuser-message-l1-1-0.dll"));
|
||||
const ScopedModule message_ansi(load_bridge(L"ext-ms-win-rtcore-ntuser-message-ansi-l1-1-0.dll"));
|
||||
if (!window || !window_ansi || !message || !message_ansi) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const auto show = lookup<decltype(&ShowWindow)>(window.get(), "ShowWindow");
|
||||
const auto create = lookup<decltype(&CreateWindowExA)>(window_ansi.get(), "CreateWindowExA");
|
||||
const auto register_class = lookup<decltype(&RegisterClassExA)>(window_ansi.get(), "RegisterClassExA");
|
||||
g_def_window_proc = lookup<decltype(&DefWindowProcA)>(window_ansi.get(), "DefWindowProcA");
|
||||
const auto translate = lookup<decltype(&TranslateMessage)>(message.get(), "TranslateMessage");
|
||||
const auto peek = lookup<decltype(&PeekMessageA)>(message_ansi.get(), "PeekMessageA");
|
||||
const auto dispatch = lookup<decltype(&DispatchMessageA)>(message_ansi.get(), "DispatchMessageA");
|
||||
if (!show || !create || !register_class || !g_def_window_proc || !translate || !peek || !dispatch) {
|
||||
return false;
|
||||
}
|
||||
|
||||
WNDCLASSEXA cls{};
|
||||
cls.cbSize = sizeof(cls);
|
||||
cls.lpfnWndProc = window_proc;
|
||||
cls.hInstance = GetModuleHandleW(nullptr);
|
||||
cls.lpszClassName = "BetterXenBridgeConformance";
|
||||
if (!register_class(&cls)) {
|
||||
return false;
|
||||
}
|
||||
const HWND hwnd = create(0, cls.lpszClassName, "BetterXen Win32 Bridge", WS_OVERLAPPEDWINDOW,
|
||||
0, 0, 100, 100, nullptr, nullptr, cls.hInstance, nullptr);
|
||||
if (hwnd) {
|
||||
show(hwnd, SW_HIDE);
|
||||
if (!IsWindowVisible(hwnd) && PostMessageA(hwnd, kMessage, kPayload, 0)) {
|
||||
MSG msg{};
|
||||
while (!g_received_message && peek(&msg, hwnd, 0, 0, PM_REMOVE)) {
|
||||
translate(&msg);
|
||||
dispatch(&msg);
|
||||
}
|
||||
}
|
||||
}
|
||||
const bool destroyed = hwnd && DestroyWindow(hwnd);
|
||||
const bool unregistered = UnregisterClassA(cls.lpszClassName, cls.hInstance);
|
||||
return g_received_message && destroyed && unregistered;
|
||||
}
|
||||
|
||||
using RegisterNotification = ULONG (WINAPI*)(decltype(¬ification_callback), PVOID, PVOID*);
|
||||
using UnregisterNotification = VOID (WINAPI*)(PVOID);
|
||||
|
||||
struct PsmLogCounts {
|
||||
size_t state_registered = 0;
|
||||
size_t constrained_registered = 0;
|
||||
size_t state_unregistered = 0;
|
||||
size_t state_foreign = 0;
|
||||
size_t state_unknown = 0;
|
||||
size_t constrained_unregistered = 0;
|
||||
size_t constrained_foreign = 0;
|
||||
size_t constrained_unknown = 0;
|
||||
};
|
||||
|
||||
int64_t query_file_size(const char* path) {
|
||||
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
|
||||
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (f == INVALID_HANDLE_VALUE) {
|
||||
return 0;
|
||||
}
|
||||
LARGE_INTEGER size{};
|
||||
const bool ok = GetFileSizeEx(f, &size) != 0;
|
||||
CloseHandle(f);
|
||||
return ok && size.QuadPart > 0 ? size.QuadPart : 0;
|
||||
}
|
||||
|
||||
bool count_psm_log_events(const char* path, int64_t start_offset, PsmLogCounts& out) {
|
||||
HANDLE f = CreateFileA(path, GENERIC_READ, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr,
|
||||
OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, nullptr);
|
||||
if (f == INVALID_HANDLE_VALUE) {
|
||||
std::fprintf(stderr, "FAIL: could not open PSM log %s (error %lu)\n", path, GetLastError());
|
||||
return false;
|
||||
}
|
||||
LARGE_INTEGER size{};
|
||||
if (!GetFileSizeEx(f, &size) || size.QuadPart < start_offset) {
|
||||
CloseHandle(f);
|
||||
std::fprintf(stderr, "FAIL: invalid PSM log size for %s\n", path);
|
||||
return false;
|
||||
}
|
||||
const int64_t delta = size.QuadPart - start_offset;
|
||||
if (delta <= 0 || delta > (64LL << 20)) {
|
||||
CloseHandle(f);
|
||||
std::fprintf(stderr, "FAIL: unexpected PSM log delta (%lld bytes)\n",
|
||||
static_cast<long long>(delta));
|
||||
return false;
|
||||
}
|
||||
LARGE_INTEGER seek{};
|
||||
seek.QuadPart = start_offset;
|
||||
if (!SetFilePointerEx(f, seek, nullptr, FILE_BEGIN)) {
|
||||
CloseHandle(f);
|
||||
return false;
|
||||
}
|
||||
std::string data(static_cast<size_t>(delta), '\0');
|
||||
size_t total_read = 0;
|
||||
while (total_read < data.size()) {
|
||||
DWORD chunk = 0;
|
||||
const DWORD want = static_cast<DWORD>(data.size() - total_read);
|
||||
if (!ReadFile(f, data.data() + total_read, want, &chunk, nullptr) || chunk == 0) {
|
||||
break;
|
||||
}
|
||||
total_read += chunk;
|
||||
}
|
||||
CloseHandle(f);
|
||||
data.resize(total_read);
|
||||
|
||||
size_t pos = 0;
|
||||
while (pos < data.size()) {
|
||||
size_t nl = data.find('\n', pos);
|
||||
if (nl == std::string::npos) {
|
||||
nl = data.size();
|
||||
}
|
||||
const std::string line = data.substr(pos, nl - pos);
|
||||
pos = nl + 1;
|
||||
|
||||
if (line.find("\"sub\":\"win32_bridge\"") == std::string::npos) {
|
||||
continue;
|
||||
}
|
||||
if (line.find("\"event\":\"RegisterAppStateChangeNotification\"") != std::string::npos &&
|
||||
line.find("\"detail\":\"registered_offline\"") != std::string::npos) {
|
||||
++out.state_registered;
|
||||
} else if (line.find("\"event\":\"RegisterAppConstrainedChangeNotification\"") != std::string::npos &&
|
||||
line.find("\"detail\":\"registered_offline\"") != std::string::npos) {
|
||||
++out.constrained_registered;
|
||||
} else if (line.find("\"event\":\"UnregisterAppStateChangeNotification\"") != std::string::npos) {
|
||||
if (line.find("\"detail\":\"unregistered\"") != std::string::npos) {
|
||||
++out.state_unregistered;
|
||||
} else if (line.find("\"detail\":\"foreign_token\"") != std::string::npos) {
|
||||
++out.state_foreign;
|
||||
} else if (line.find("\"detail\":\"unknown_token\"") != std::string::npos) {
|
||||
++out.state_unknown;
|
||||
}
|
||||
} else if (line.find("\"event\":\"UnregisterAppConstrainedChangeNotification\"") != std::string::npos) {
|
||||
if (line.find("\"detail\":\"unregistered\"") != std::string::npos) {
|
||||
++out.constrained_unregistered;
|
||||
} else if (line.find("\"detail\":\"foreign_token\"") != std::string::npos) {
|
||||
++out.constrained_foreign;
|
||||
} else if (line.find("\"detail\":\"unknown_token\"") != std::string::npos) {
|
||||
++out.constrained_unknown;
|
||||
}
|
||||
}
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool test_psm() {
|
||||
char log_path[MAX_PATH]{};
|
||||
bool created_temp_log = false;
|
||||
const DWORD existing_len = GetEnvironmentVariableA("BX_LOG_FILE", log_path, sizeof(log_path));
|
||||
if (existing_len == 0 || existing_len >= sizeof(log_path)) {
|
||||
char temp_dir[MAX_PATH]{};
|
||||
const DWORD dir_len = GetTempPathA(sizeof(temp_dir), temp_dir);
|
||||
if (dir_len == 0 || dir_len >= sizeof(temp_dir) ||
|
||||
GetTempFileNameA(temp_dir, "bxp", 0, log_path) == 0) {
|
||||
std::fprintf(stderr, "FAIL: could not create temporary PSM log file\n");
|
||||
return false;
|
||||
}
|
||||
if (!SetEnvironmentVariableA("BX_LOG_FILE", log_path)) {
|
||||
DeleteFileA(log_path);
|
||||
return false;
|
||||
}
|
||||
created_temp_log = true;
|
||||
}
|
||||
const int64_t log_start_offset = query_file_size(log_path);
|
||||
|
||||
bool ok = false;
|
||||
{
|
||||
const ScopedModule state_dll(load_bridge(L"api-ms-win-core-psm-appnotify-l1-1-0.dll"));
|
||||
const ScopedModule constrained_dll(load_bridge(L"api-ms-win-core-psm-appnotify-l1-1-1.dll"));
|
||||
if (state_dll && constrained_dll) {
|
||||
const auto register_state = lookup<RegisterNotification>(
|
||||
state_dll.get(), "RegisterAppStateChangeNotification");
|
||||
const auto unregister_state = lookup<UnregisterNotification>(
|
||||
state_dll.get(), "UnregisterAppStateChangeNotification");
|
||||
const auto register_constrained = lookup<RegisterNotification>(
|
||||
constrained_dll.get(), "RegisterAppConstrainedChangeNotification");
|
||||
const auto unregister_constrained = lookup<UnregisterNotification>(
|
||||
constrained_dll.get(), "UnregisterAppConstrainedChangeNotification");
|
||||
if (register_state && unregister_state && register_constrained && unregister_constrained) {
|
||||
PVOID token = reinterpret_cast<PVOID>(1);
|
||||
PVOID token2 = reinterpret_cast<PVOID>(1);
|
||||
const bool args_ok =
|
||||
register_state(nullptr, nullptr, &token) == ERROR_INVALID_PARAMETER && !token &&
|
||||
register_state(notification_callback, nullptr, nullptr) == ERROR_INVALID_PARAMETER &&
|
||||
register_constrained(nullptr, nullptr, &token2) == ERROR_INVALID_PARAMETER && !token2 &&
|
||||
register_constrained(notification_callback, nullptr, nullptr) == ERROR_INVALID_PARAMETER;
|
||||
|
||||
constexpr size_t kThreads = 4;
|
||||
constexpr size_t kRegistrationsPerThread = 16;
|
||||
constexpr size_t kPerFamily = kThreads * kRegistrationsPerThread;
|
||||
struct Tokens {
|
||||
PVOID state{};
|
||||
PVOID constrained{};
|
||||
};
|
||||
std::array<std::array<Tokens, kRegistrationsPerThread>, kThreads> tokens{};
|
||||
std::array<std::thread, kThreads> workers;
|
||||
std::atomic<bool> success{args_ok};
|
||||
for (size_t i = 0; i < workers.size(); ++i) {
|
||||
workers[i] = std::thread([&, i] {
|
||||
for (auto& entry : tokens[i]) {
|
||||
const auto state_status =
|
||||
register_state(notification_callback, &entry, &entry.state);
|
||||
const auto constrained_status =
|
||||
register_constrained(notification_callback, &entry, &entry.constrained);
|
||||
if (state_status != ERROR_SUCCESS || constrained_status != ERROR_SUCCESS ||
|
||||
!entry.state || !entry.constrained) {
|
||||
success.store(false);
|
||||
}
|
||||
// Cross-family unregister calls must log foreign_token and leave live tokens intact.
|
||||
unregister_constrained(entry.state);
|
||||
unregister_state(entry.constrained);
|
||||
// Valid unregister followed by duplicate unregister on each family.
|
||||
unregister_state(entry.state);
|
||||
unregister_state(entry.state);
|
||||
unregister_constrained(entry.constrained);
|
||||
unregister_constrained(entry.constrained);
|
||||
}
|
||||
});
|
||||
}
|
||||
for (auto& worker : workers) {
|
||||
worker.join();
|
||||
}
|
||||
|
||||
// Null and arbitrary invalid tokens must classify as unknown_token, not foreign_token.
|
||||
unregister_state(nullptr);
|
||||
unregister_constrained(reinterpret_cast<PVOID>(0x1234));
|
||||
|
||||
std::unordered_set<PVOID> seen;
|
||||
bool unique_ok = true;
|
||||
for (const auto& entries : tokens) {
|
||||
for (const auto& entry : entries) {
|
||||
if (!seen.insert(entry.state).second ||
|
||||
!seen.insert(entry.constrained).second) {
|
||||
unique_ok = false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
PsmLogCounts counts{};
|
||||
const bool log_read_ok = count_psm_log_events(log_path, log_start_offset, counts);
|
||||
const bool counts_ok = log_read_ok &&
|
||||
counts.state_registered == kPerFamily &&
|
||||
counts.constrained_registered == kPerFamily &&
|
||||
counts.state_unregistered == kPerFamily &&
|
||||
counts.state_foreign == kPerFamily &&
|
||||
counts.state_unknown == kPerFamily + 1 &&
|
||||
counts.constrained_unregistered == kPerFamily &&
|
||||
counts.constrained_foreign == kPerFamily &&
|
||||
counts.constrained_unknown == kPerFamily + 1;
|
||||
if (log_read_ok && !counts_ok) {
|
||||
std::fprintf(
|
||||
stderr,
|
||||
"FAIL: PSM log count mismatch: state(reg=%zu unreg=%zu foreign=%zu unknown=%zu) "
|
||||
"constrained(reg=%zu unreg=%zu foreign=%zu unknown=%zu)\n",
|
||||
counts.state_registered, counts.state_unregistered,
|
||||
counts.state_foreign, counts.state_unknown,
|
||||
counts.constrained_registered, counts.constrained_unregistered,
|
||||
counts.constrained_foreign, counts.constrained_unknown);
|
||||
}
|
||||
|
||||
ok = success.load() && unique_ok && !g_callback_called.load() && counts_ok;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (created_temp_log) {
|
||||
DeleteFileA(log_path);
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
if (!test_window()) {
|
||||
std::fprintf(stderr, "FAIL: Win32 bridge window or message pump (error %lu)\n", GetLastError());
|
||||
return 1;
|
||||
}
|
||||
if (!test_psm()) {
|
||||
std::fprintf(stderr, "FAIL: PSM bridge registration lifecycle\n");
|
||||
return 2;
|
||||
}
|
||||
std::puts("PASS: test_win32_bridge (hidden window, message pump, 128 PSM registrations, per-event log verified)");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
add_executable(test_xmem_physical main.cpp)
|
||||
target_include_directories(test_xmem_physical PRIVATE "${BX_ABI_INCLUDE_DIR}")
|
||||
target_link_libraries(test_xmem_physical PRIVATE xmem kernel32)
|
||||
@@ -0,0 +1,148 @@
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
|
||||
#include "bx_xmem_internal.h"
|
||||
|
||||
extern "C" {
|
||||
PVOID WINAPI XMemAllocDefault(SIZE_T, uint64_t);
|
||||
VOID WINAPI XMemFreeDefault(PVOID, uint64_t);
|
||||
BOOL WINAPI XMemAllocatePhysicalPages(SIZE_T*, PULONG_PTR, uint64_t);
|
||||
BOOL WINAPI XMemFreePhysicalPages(SIZE_T*, PULONG_PTR, uint64_t);
|
||||
PVOID WINAPI XMemMapPhysicalPages(PVOID, SIZE_T, uint64_t, PULONG_PTR);
|
||||
PVOID WINAPI XMemMapPhysicalPagesScatter(PVOID, SIZE_T, uint64_t, PULONG_PTR);
|
||||
BOOL WINAPI XMemGetWorkingSetStatistics(PVOID, SIZE_T);
|
||||
}
|
||||
|
||||
#define CHECK(condition) \
|
||||
do { \
|
||||
if (!(condition)) { \
|
||||
std::fprintf(stderr, "xmem physical:%d: %s (Win32 error %lu)\n", \
|
||||
__LINE__, #condition, static_cast<unsigned long>(GetLastError())); \
|
||||
return false; \
|
||||
} \
|
||||
} while (false)
|
||||
|
||||
bool check_aliases(SIZE_T page_size, uint64_t flags) {
|
||||
bx_xmem_stats_t stats{};
|
||||
CHECK(XMemGetWorkingSetStatistics(&stats, sizeof(stats)));
|
||||
CHECK(stats.allocated_physical_bytes == 0);
|
||||
|
||||
SIZE_T count = 2;
|
||||
ULONG_PTR pages[2]{};
|
||||
// Invalid flags must be rejected cleanly before touching stats or tags.
|
||||
CHECK(!XMemAllocatePhysicalPages(&count, pages, 0x12345));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
|
||||
CHECK(XMemAllocatePhysicalPages(&count, pages, flags));
|
||||
CHECK(count == 2 && pages[0] && pages[1] && pages[0] != pages[1]);
|
||||
|
||||
// Working-set statistics and internal stats must both reflect physical pages.
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
CHECK(stats.allocated_physical_bytes == count * page_size);
|
||||
CHECK(stats.peak_committed_bytes >= count * page_size);
|
||||
bx_xmem_stats_t ws_stats{};
|
||||
CHECK(XMemGetWorkingSetStatistics(&ws_stats, sizeof(ws_stats)));
|
||||
CHECK(ws_stats.allocated_physical_bytes == count * page_size);
|
||||
|
||||
// Shared title budget cap: existing physical pages must block both full-cap
|
||||
// physical and full-cap heap allocations without allocating gigabytes.
|
||||
SIZE_T cap_pages = static_cast<SIZE_T>(stats.title_limit_bytes / page_size);
|
||||
CHECK(!XMemAllocatePhysicalPages(&cap_pages, pages, flags));
|
||||
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
|
||||
CHECK(!XMemAllocDefault(static_cast<SIZE_T>(stats.title_limit_bytes), 0));
|
||||
CHECK(GetLastError() == ERROR_NOT_ENOUGH_MEMORY);
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
CHECK(stats.allocated_physical_bytes == count * page_size);
|
||||
|
||||
CHECK(!XMemMapPhysicalPages(nullptr, count, 0x12345, pages));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
|
||||
auto* linear = static_cast<BYTE*>(XMemMapPhysicalPages(nullptr, count, flags, pages));
|
||||
CHECK(linear && reinterpret_cast<uintptr_t>(linear) % page_size == 0);
|
||||
ULONG_PTR reversed[] = {pages[1], pages[0]};
|
||||
auto* scatter = static_cast<BYTE*>(
|
||||
XMemMapPhysicalPagesScatter(nullptr, count, flags, reversed));
|
||||
CHECK(scatter && scatter != linear && reinterpret_cast<uintptr_t>(scatter) % page_size == 0);
|
||||
|
||||
linear[7] = 0x41;
|
||||
linear[page_size + 7] = 0x73;
|
||||
CHECK(scatter[7] == 0x73 && scatter[page_size + 7] == 0x41);
|
||||
scatter[page_size + 30] = 0xf2;
|
||||
CHECK(linear[30] == 0xf2);
|
||||
|
||||
// Duplicate tags are valid when mapping (intra-span ring-buffer/tile aliasing).
|
||||
ULONG_PTR dup_map[] = {pages[0], pages[0]};
|
||||
auto* dup_view = static_cast<BYTE*>(
|
||||
XMemMapPhysicalPagesScatter(nullptr, count, flags, dup_map));
|
||||
CHECK(dup_view && reinterpret_cast<uintptr_t>(dup_view) % page_size == 0);
|
||||
dup_view[13] = 0x9b;
|
||||
CHECK(dup_view[page_size + 13] == 0x9b && linear[13] == 0x9b);
|
||||
bx_xmem_region_info_t dup0{};
|
||||
bx_xmem_region_info_t dup1{};
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(dup_view), &dup0));
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(dup_view + page_size), &dup1));
|
||||
CHECK(dup0.physical_tag == pages[0] && dup1.physical_tag == pages[0]);
|
||||
CHECK(XMemMapPhysicalPagesScatter(dup_view, count, flags, nullptr) == dup_view);
|
||||
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(dup_view), &dup0));
|
||||
|
||||
bx_xmem_region_info_t first{};
|
||||
bx_xmem_region_info_t alias{};
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(linear + 7), &first));
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter + page_size + 7), &alias));
|
||||
CHECK(first.base_va == reinterpret_cast<uintptr_t>(linear));
|
||||
CHECK(alias.base_va == reinterpret_cast<uintptr_t>(scatter + page_size));
|
||||
CHECK(alias.physical_tag == first.physical_tag && first.physical_tag == pages[0]);
|
||||
CHECK(first.size_bytes == page_size && alias.page_size_bytes == page_size);
|
||||
CHECK(first.protect_flags == PAGE_READWRITE && first.mem_type_flags == MEM_MAPPED);
|
||||
|
||||
// Rejected frees (stale or duplicate tags) must fail without modifying
|
||||
// page_array or disturbing live mappings.
|
||||
ULONG_PTR stale[] = {pages[0], 0};
|
||||
CHECK(!XMemFreePhysicalPages(&count, stale, flags));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER && stale[0] == pages[0] && stale[1] == 0);
|
||||
CHECK(linear[7] == 0x41);
|
||||
ULONG_PTR dup_free[] = {pages[0], pages[0]};
|
||||
CHECK(!XMemFreePhysicalPages(&count, dup_free, flags));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER
|
||||
&& dup_free[0] == pages[0] && dup_free[1] == pages[0]);
|
||||
CHECK(linear[7] == 0x41 && scatter[7] == 0x73);
|
||||
|
||||
CHECK(!XMemMapPhysicalPagesScatter(nullptr, count, flags, stale));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
CHECK(!XMemMapPhysicalPages(linear, count, flags, pages));
|
||||
CHECK(linear[7] == 0x41 && scatter[7] == 0x73);
|
||||
|
||||
// Partial/over-wide unmap must fail cleanly and leave mapped pages intact.
|
||||
CHECK(!XMemMapPhysicalPagesScatter(scatter, count + 1, flags, nullptr));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
CHECK(bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter), &alias));
|
||||
CHECK(scatter[7] == 0x73 && scatter[page_size + 7] == 0x41);
|
||||
|
||||
// Exact unmap succeeds; repeating unmap on the now-empty span must fail.
|
||||
CHECK(XMemMapPhysicalPagesScatter(scatter, count, flags, nullptr) == scatter);
|
||||
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter), &alias));
|
||||
CHECK(!XMemMapPhysicalPagesScatter(scatter, count, flags, nullptr));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
|
||||
CHECK(XMemMapPhysicalPagesScatter(scatter, count, flags, reversed) == scatter);
|
||||
CHECK(scatter[7] == 0x73 && scatter[page_size + 7] == 0x41);
|
||||
CHECK(XMemFreePhysicalPages(&count, pages, flags));
|
||||
CHECK(!pages[0] && !pages[1]);
|
||||
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(linear), &first));
|
||||
CHECK(!bx_xmem_query_region(reinterpret_cast<uintptr_t>(scatter), &alias));
|
||||
CHECK(!XMemMapPhysicalPages(nullptr, count, flags, reversed));
|
||||
CHECK(GetLastError() == ERROR_INVALID_PARAMETER);
|
||||
|
||||
bx_xmem_get_internal_stats(&stats);
|
||||
CHECK(stats.allocated_physical_bytes == 0);
|
||||
return true;
|
||||
}
|
||||
|
||||
int main() {
|
||||
if (!check_aliases(64 * 1024, 0) || !check_aliases(2 * 1024 * 1024, 2 * 1024 * 1024)) {
|
||||
return 1;
|
||||
}
|
||||
std::puts("test_xmem_physical: passed");
|
||||
}
|
||||
Reference in new issue
Block a user