Compare commits

...
Author SHA1 Message Date
Ateş f7194d0255 Merge pull request #431 from MacosPorters/track-a/410-win32-bridge
[M1-A3] Cover Win32 bridges and track offline PSM registrations
2026-11-26 18:20:03 +03:00
ates 7ea4f1f6ca Merge main and address PR #431 review findings
- Replace std::mutex/std::unordered_set + -fexceptions in psm_appnotify.cpp with a Win32 SRWLOCK and HeapAlloc open-addressed token set, keeping -fno-exceptions and reducing both PSM DLLs from ~2.4 MB back to 118 KB.
- Tag state (PSM1) and constrained (PSM2) tokens so cross-family unregisters log foreign_token while duplicate, null, or arbitrary invalid tokens log unknown_token.
- Fix load_bridge to call FreeLibrary on path mismatch or path-query failure without leaking the module handle or reporting a stale GetLastError().
- Verify exact per-(event, detail) JSONL counts inside test_win32_bridge (both with caller-provided BX_LOG_FILE and a self-managed temp log).
- Resolve CHANGELOG.md conflict with origin/main.

Signed-off-by: ates <ahmetrizaates@hotmail.com>
2026-11-26 18:19:30 +03:00
Ateş bd8edd8f70 Merge pull request #429 from MacosPorters/track-e/419-audio-input
Implement bounded audio queues and GameInput ordinal 1 COM stub
2026-11-26 18:09:00 +03:00
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
ates cee636193a Cover Win32 bridges and track offline PSM registrations
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
11 changed files with 1130 additions and 84 deletions

No files matched your search

+2
View File
@@ -10,6 +10,8 @@ Guest execution uses original, purpose-built test programs. Commercial Xbox game
remains unsupported.
### Added
- 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).
+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;
}
+229 -17
View File
@@ -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"
@@ -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");
}
@@ -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(&notification_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;
}