mirror of
https://github.com/MacosPorters/betterxen.git
synced 2026-11-30 00:21:12 +00:00
Compare commits
5
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
b49b0d9696 | ||
|
|
84dd9e2df5 | ||
|
|
2dc58a3b25 | ||
|
|
9f6fef064c | ||
|
|
961cf7e26c |
No files matched your search
+1
-1
@@ -27,7 +27,6 @@ remains unsupported.
|
||||
- `dxbc-accc` no longer classifies `DXIL` chunks whose bitcode payload starts with the `NOBC` header-only placeholder as executable DXIL (Track D prerequisite from ADR 0008 / `docs/roadmap.md`). `inspect_dxbc` and `bx_shader_inspect` still report the container's `dxil_chunk_size`, stage, and shader model, but leave `kind` as `Unknown` (or `AcccOnly` when paired with an `ACCC` chunk) instead of `Dxil` or `DualDxilAndAccc`, and `bx_shader_prepare_for_d3dmetal` returns `BX_SHADER_ERR_UNSUPPORTED` rather than passing a bitcode-less container through. Covered by synthetic `NOBC`, mixed-chunk, and bounds-safety unit tests in `dxbc-accc`; live CrossOver execution is unchanged.
|
||||
|
||||
### Added
|
||||
- `GameInput.dll` exposes one keyboard-backed gamepad through v0 blocking enumeration and current readings. Enter or Space maps to A, Escape or Backspace to B, arrow keys to the D-pad, WASD and IJKL to the two sticks, Q/E to shoulders, Z/C to triggers, F/H to stick clicks, X/Y to the matching face buttons, and P/Tab to Menu/View. Input returns to neutral when another application owns the foreground.
|
||||
- `xgameruntime.dll` serves `XGameSaveGetContainerInfo` (slot 13) and `XGameSaveEnumerateContainerInfoByName` (slot 15) on `IXGameSaveImpl` (#667). `XGameSaveGetContainerInfo` reads container metadata without loading blob payloads and, when the named container does not exist, succeeds without invoking the callback (source rank 3 inference). `XGameSaveEnumerateContainerInfoByName` filters containers by name prefix (treating `nullptr` or empty prefix as all containers), sorts by name, and stops early when the callback returns `false`. `test_xgameruntime_saves` checks both slots through `QueryApiImpl`.
|
||||
- `xgameruntime.dll` serves `XAsyncRun`, `XTaskQueueCreateComposite`, `XTaskQueueGetPort` and `XTaskQueueDuplicateHandle` through `IXGameRuntimeCore` slots 6, 13, 14 and 15 (#666). `XAsyncRun` runs the title's work callback on the block's work port and completes the block with its result. A duplicated queue handle shares the queue, and only the last close shuts its lanes down. A composite queue forwards each port to the port it was made from, and an async block's completion returns through the queue the block named. A project-authorized target build uses these for its save-game work and exited when `XAsyncRun` was unimplemented. `test_xgameruntime` checks all four through `QueryApiImpl`.
|
||||
- `bx-cli report <log.jsonl>...` (#664, part 1): a run report per log (one log is one run) and a summary across runs. Per run: how it ended, the frames presented (a lower bound), every unimplemented call with its count, faults whose innermost frame is in a BetterXen module, and pipelines by kind. The summary counts clean runs and lists each blocker signature with the number of runs that hit it; blocker issues are titled with those signatures. `bx-cli run` now appends a `run_end` record to its log (exited with a status, timeout, signal or launch failure), which the report reads. A log without it has an unknown outcome and is never counted as clean.
|
||||
@@ -96,6 +95,7 @@ remains unsupported.
|
||||
- **`d3d12_xs.dll`: console rectangle lists are drawn.** `D3D_PRIMITIVE_TOPOLOGY_RECTLIST` (17) and the pipeline topology type `D3D12XBOX_PRIMITIVE_TOPOLOGY_TYPE_RECT` (19) are Xbox extensions (GDK `d3d12_xs.h`): three vertices per rectangle, the fourth corner `v0 + v2 - v1`. The host knew neither value, so a title's full-screen passes drew half a rectangle or nothing. A rectangle list is now drawn as triangle strips (`rect_list.cpp`): the pipeline is created with the triangle type, and a non-indexed draw builds four vertices per rectangle from the title's vertex data and the pipeline's input layout. Indexed rectangle lists and quad lists are not emulated and are logged as unimplemented. Test: `test_d3d12_rect_list` (25 checks, pixel readback).
|
||||
- **`bx_runtime_veh.dll`: a CLWB range loop completes in one exception.** A title flushes an address range with `clwb [reg]; add reg, 0x40; cmp reg, <reg64>; jbe|jb`; each CLWB trapped under Rosetta, about 94,000 exception round trips per 6 MiB buffer. CLWB changes no register, flag or memory, so the handler now advances the pointer register to the last value the loop would have used and the title's own add/cmp/jcc leaves the loop. Other forms keep the per-instruction path. Test: `test_veh_clwb_loop` (15 checks; without the fix the four loop cases take one exception per line).
|
||||
- **Committed render targets request the console's size from XMemAlloc** (#695). The console lays out a 2D render-target or unordered-access texture with one mip and one sample in 64 KB tiles (64KB_R_X for every size: 128x128 elements at 4 bytes, 128x64 at 8, 64x64 at 16, 256x128 at 2, 256x256 at 1; authorized GDK XG library), and a title that hooks XMemAlloc sizes its pool for those requests and asserts that less than 2 MB is left over. `d3d12_xs.dll` requested the host's size instead, 1920x1080 RGBA8 as 128 pages where the console takes 135, and on the Series S path the target build stopped on that assertion. The XMemAlloc request for those textures is now the tile size, computed from the title's format; every other resource keeps the host's size, and XG's render-target compression metadata after the tiles (8 KB to 96 KB in the cases measured) is not modelled. `GetResourceAllocationInfo` still answers with the host's size. Test: `test_d3d12_committed_tile_size`.
|
||||
- **XCRDAPI holds an xmem guard while accessing title memory** (#668). Replacing a mapped view on Windows or Wine can temporarily make pages in that view inaccessible. DirectStorage reads and writes that can touch title memory now hold the shared guard while xmem mapping and freeing operations hold it exclusively. A loaded xmem DLL without both guard exports produces a warning. The guard covers DirectStorage accesses through BetterXen. `test_xcrdapi_remap_guard` exercises memory-to-memory stores into a window, zlib streams inflated into it and memory requests reading out of it while it is remapped; accesses by the title's own threads are not covered.
|
||||
- **`d3d12_xs.dll`: an index or vertex binding at a title address without a host buffer no longer crashes the process.** A title binds index and vertex data by address in plain title memory, with no Direct3D resource behind it. The address reached D3DMetal unchanged and it read through a null buffer (`IASetIndexBuffer`). Such a binding is now left empty and logged as unimplemented (`IASetIndexBuffer(title memory without a host buffer)`, likewise `IASetVertexBuffers`); bindings inside resources BetterXen created are translated as before. Supplying the data is separate work. Test: `test_d3d12_unbacked_buffers` (13 checks; without the fix it dies with the same null read).
|
||||
- **`d3d12_xs.dll`: console-only DXGI formats and depth-stencil unordered-access views no longer end the process.** The Xbox Series `DXGI_FORMAT` enumeration has values the PC one lacks (116-120, 189, 190; GDK `d3d12_xs.h`). D3DMetal turns one into an invalid Metal pixel format and Metal aborts, which a target build's crash reporter then turned into either "exit status 5" or a stall with every thread stopped.
|
||||
- **Formats:** `console_formats.h` maps each to the nearest host format (a depth texture is created typeless, each view names the concrete format). The three `GetResourceAllocationInfo` forms, `CreatePlacedResource`, `CreateReservedResource`, the four view-creation methods, the committed-resource forms and the placed (X) resource and view forms translate before the host call.
|
||||
|
||||
@@ -17,3 +17,5 @@ EXPORTS
|
||||
bx_xmem_get_internal_stats
|
||||
bx_xmem_try_charge_external
|
||||
bx_xmem_release_charge_external
|
||||
bx_xmem_remap_guard_enter @18
|
||||
bx_xmem_remap_guard_leave @19
|
||||
@@ -51,6 +51,18 @@ int bx_xmem_try_charge_external(uint64_t bytes);
|
||||
* unchanged and an external_charge error is logged. */
|
||||
void bx_xmem_release_charge_external(uint64_t bytes);
|
||||
|
||||
/* The remap guard protects BetterXen reads and writes to title memory while
|
||||
* XMemMapPhysicalPages, XMemMapPhysicalPagesScatter or XMemFreePhysicalPages
|
||||
* replaces mapped views. Those operations wait for active guards and block
|
||||
* new guards until the remap completes.
|
||||
*
|
||||
* Pair each enter with one leave on the same thread. Keep the guard short,
|
||||
* avoid nesting it, and release it before calling an XMem function.
|
||||
* Consumers that resolve the helpers dynamically must resolve both or
|
||||
* call neither. */
|
||||
void bx_xmem_remap_guard_enter(void);
|
||||
void bx_xmem_remap_guard_leave(void);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -1,5 +1,4 @@
|
||||
bx_add_shim_dll(gameinput GameInput GameInput.def
|
||||
gameinput.cpp
|
||||
keyboard_gamepad.cpp
|
||||
)
|
||||
target_link_libraries(gameinput PRIVATE bx_runtime_veh kernel32 user32)
|
||||
target_link_libraries(gameinput PRIVATE bx_runtime_veh kernel32)
|
||||
@@ -7,19 +7,16 @@
|
||||
#include <unordered_map>
|
||||
|
||||
#include "bx_log.h"
|
||||
#include "keyboard_gamepad.h"
|
||||
|
||||
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*)();
|
||||
using DeviceCallback = void (WINAPI*)(uint64_t, void*, IUnknown*, uint64_t, uint32_t, uint32_t);
|
||||
|
||||
// GameInputEnumerationKind values from Microsoft's public GDK GameInput (v0) reference:
|
||||
// 0 = GameInputNoEnumeration, 1 = GameInputAsyncEnumeration, 2 = GameInputBlockingEnumeration.
|
||||
constexpr uint32_t kAsyncEnumeration = 1;
|
||||
constexpr uint32_t kBlockingEnumeration = 2;
|
||||
constexpr uint32_t kMaxEnumerationKind = 2;
|
||||
|
||||
struct SrwExclusiveLock {
|
||||
explicit SrwExclusiveLock(SRWLOCK& lock) : lock_(lock) { AcquireSRWLockExclusive(&lock_); }
|
||||
@@ -37,7 +34,7 @@ struct RegisteredDeviceCallback {
|
||||
uint32_t status_filter = 0;
|
||||
uint32_t enumeration_kind = 0;
|
||||
void* context = nullptr;
|
||||
DeviceCallback callback = nullptr;
|
||||
Callback callback = nullptr;
|
||||
bool stopped = false;
|
||||
};
|
||||
|
||||
@@ -94,15 +91,9 @@ public:
|
||||
virtual uint64_t WINAPI GetCurrentTimestamp() {
|
||||
return GetTickCount64() * 1000;
|
||||
}
|
||||
virtual HRESULT WINAPI GetCurrentReading(uint32_t kind, void* device, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (!(kind & keyboard_gamepad::input_kind)) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 4, "GetCurrentReading(non-gamepad)");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
if (device && device != keyboard_gamepad::device()) return keyboard_gamepad::device_not_found;
|
||||
return keyboard_gamepad::read(out);
|
||||
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");
|
||||
@@ -126,45 +117,25 @@ public:
|
||||
uint32_t status_filter,
|
||||
uint32_t enumeration_kind,
|
||||
void* context,
|
||||
DeviceCallback callback,
|
||||
Callback callback,
|
||||
uint64_t* out_token
|
||||
) {
|
||||
if (out_token) *out_token = 0;
|
||||
if (!callback || input_kind == 0 || status_filter == 0 || enumeration_kind > kBlockingEnumeration) {
|
||||
if (!callback || input_kind == 0 || status_filter == 0 || enumeration_kind > kMaxEnumerationKind) {
|
||||
return E_INVALIDARG;
|
||||
}
|
||||
uint64_t token;
|
||||
{
|
||||
SrwExclusiveLock guard(callback_lock_);
|
||||
token = next_token_++;
|
||||
callbacks_.emplace(token, RegisteredDeviceCallback{
|
||||
device,
|
||||
input_kind,
|
||||
status_filter,
|
||||
enumeration_kind,
|
||||
context,
|
||||
callback,
|
||||
false,
|
||||
});
|
||||
}
|
||||
SrwExclusiveLock guard(callback_lock_);
|
||||
const uint64_t token = next_token_++;
|
||||
callbacks_.emplace(token, RegisteredDeviceCallback{
|
||||
device,
|
||||
input_kind,
|
||||
status_filter,
|
||||
enumeration_kind,
|
||||
context,
|
||||
callback,
|
||||
false,
|
||||
});
|
||||
if (out_token) *out_token = token;
|
||||
|
||||
auto* pad = keyboard_gamepad::device();
|
||||
const bool matches = (!device || device == pad) &&
|
||||
(input_kind & keyboard_gamepad::input_kind) &&
|
||||
(status_filter & keyboard_gamepad::device_status);
|
||||
if (matches && enumeration_kind == kBlockingEnumeration) {
|
||||
// The title requests blocking enumeration. The callback may reenter
|
||||
// GameInput, so never call it under the registration lock.
|
||||
static std::atomic_flag reported;
|
||||
if (!reported.test_and_set(std::memory_order_relaxed)) {
|
||||
bx_log_emit(BX_LOG_INFO, "gameinput", "keyboard_gamepad_connected",
|
||||
"keyboard gamepad announced through v0 device enumeration");
|
||||
}
|
||||
callback(token, context, pad, GetCurrentTimestamp(), keyboard_gamepad::device_status, 0);
|
||||
} else if (matches && enumeration_kind == kAsyncEnumeration) {
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 9, "RegisterDeviceCallback(async gamepad enumeration)");
|
||||
}
|
||||
return S_OK;
|
||||
}
|
||||
virtual HRESULT WINAPI RegisterSystemButtonCallback(void*, uint32_t, void*, Callback, uint64_t* out) {
|
||||
@@ -195,15 +166,9 @@ public:
|
||||
BX_VTABLE_STUB_LOG("IGameInput", 15, "CreateAggregateDevice");
|
||||
return unavailable(out);
|
||||
}
|
||||
virtual HRESULT WINAPI FindDeviceFromId(const void* id, void** out) {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (!id) return E_INVALIDARG;
|
||||
if (!keyboard_gamepad::has_id(id)) return keyboard_gamepad::device_not_found;
|
||||
auto* pad = keyboard_gamepad::device();
|
||||
pad->AddRef();
|
||||
*out = pad;
|
||||
return S_OK;
|
||||
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");
|
||||
|
||||
@@ -1,306 +0,0 @@
|
||||
#include "keyboard_gamepad.h"
|
||||
|
||||
#include <array>
|
||||
#include <atomic>
|
||||
#include <cstddef>
|
||||
#include <cstring>
|
||||
#include <new>
|
||||
|
||||
#include "bx_log.h"
|
||||
|
||||
namespace keyboard_gamepad {
|
||||
namespace {
|
||||
|
||||
// Legacy GameInput v0 interface identities and Win64 data layouts.
|
||||
constexpr GUID device_iid = {0x31dd86fb, 0x4c1b, 0x408a, {0x86, 0x8f, 0x43, 0x9b, 0x3c, 0xd4, 0x71, 0x25}};
|
||||
constexpr GUID reading_iid = {0x2156947a, 0xe1fa, 0x4de0, {0xa3, 0x0b, 0xd8, 0x12, 0x93, 0x1d, 0xbd, 0x8d}};
|
||||
|
||||
struct GamepadState {
|
||||
uint32_t buttons;
|
||||
float left_trigger;
|
||||
float right_trigger;
|
||||
float left_x;
|
||||
float left_y;
|
||||
float right_x;
|
||||
float right_y;
|
||||
};
|
||||
static_assert(sizeof(GamepadState) == 28);
|
||||
|
||||
struct BatteryState {
|
||||
float rate, max_rate, remaining, capacity;
|
||||
uint32_t status;
|
||||
};
|
||||
static_assert(sizeof(BatteryState) == 20);
|
||||
|
||||
struct DeviceString {
|
||||
uint32_t bytes;
|
||||
uint32_t code_points;
|
||||
const char* text;
|
||||
};
|
||||
|
||||
using DeviceId = std::array<uint8_t, 32>;
|
||||
constexpr DeviceId device_id{{'B', 'e', 't', 't', 'e', 'r', 'X', 'e', 'n', '-', 'K', 'e', 'y', 'b', 'o', 'a', 'r', 'd'}};
|
||||
constexpr char device_name[] = "BetterXen Keyboard Gamepad";
|
||||
constexpr DeviceString display_name{
|
||||
sizeof(device_name) - 1, sizeof(device_name) - 1, device_name,
|
||||
};
|
||||
// Menu, View, A/B/X/Y, D-pad, shoulders, and stick clicks, in v0 label order.
|
||||
constexpr std::array<uint32_t, 14> gamepad_labels{{4, 5, 7, 8, 9, 10, 11, 12, 13, 14, 15, 18, 17, 20}};
|
||||
|
||||
// The virtual device supplies only fixed-format gamepad data. The arrays group
|
||||
// the zero-valued v0 metadata for raw reports, other input kinds, and motors.
|
||||
struct DeviceInfo {
|
||||
uint32_t size;
|
||||
uint16_t vendor_id, product_id, revision;
|
||||
uint8_t interface_number, collection_number;
|
||||
uint16_t usage_page, usage;
|
||||
uint16_t hardware_version[4], firmware_version[4];
|
||||
DeviceId id, root_id;
|
||||
int32_t family;
|
||||
uint32_t capabilities, supported_input, supported_rumble;
|
||||
uint32_t counts[12];
|
||||
const void* other_input_info[12];
|
||||
const uint32_t* gamepad_info;
|
||||
const void* wheel_navigation_motor_info[4];
|
||||
const DeviceString* display_name;
|
||||
const void* device_strings;
|
||||
const void* descriptor;
|
||||
};
|
||||
static_assert(sizeof(DeviceInfo) == 320);
|
||||
static_assert(offsetof(DeviceInfo, id) == 32);
|
||||
static_assert(offsetof(DeviceInfo, supported_input) == 104);
|
||||
static_assert(offsetof(DeviceInfo, gamepad_info) == 256);
|
||||
static_assert(offsetof(DeviceInfo, display_name) == 296);
|
||||
|
||||
constexpr DeviceInfo device_info{
|
||||
.size = sizeof(DeviceInfo),
|
||||
.vendor_id = 0,
|
||||
.product_id = 0,
|
||||
.revision = 0,
|
||||
.interface_number = 0,
|
||||
.collection_number = 0,
|
||||
.usage_page = 1,
|
||||
.usage = 5,
|
||||
.hardware_version = {},
|
||||
.firmware_version = {},
|
||||
.id = device_id,
|
||||
.root_id = device_id,
|
||||
.family = -1, // GameInputFamilyVirtual
|
||||
.capabilities = 0,
|
||||
.supported_input = input_kind,
|
||||
.supported_rumble = 0,
|
||||
.counts = {},
|
||||
.other_input_info = {},
|
||||
.gamepad_info = gamepad_labels.data(),
|
||||
.wheel_navigation_motor_info = {},
|
||||
.display_name = &display_name,
|
||||
.device_strings = nullptr,
|
||||
.descriptor = nullptr,
|
||||
};
|
||||
|
||||
#define DEVICE_STUB(slot, method) BX_VTABLE_STUB_LOG("IGameInputDevice", slot, method)
|
||||
#define READING_STUB(slot, method) BX_VTABLE_STUB_LOG("IGameInputReading", slot, method)
|
||||
|
||||
class Device final : public IUnknown {
|
||||
LONG refs_ = 1; // The shim owns one reference for the lifetime of the device.
|
||||
|
||||
public:
|
||||
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (iid != IID_IUnknown && iid != device_iid) return E_NOINTERFACE;
|
||||
AddRef();
|
||||
*out = this;
|
||||
return S_OK;
|
||||
}
|
||||
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs_); }
|
||||
ULONG WINAPI Release() override { return InterlockedDecrement(&refs_); }
|
||||
|
||||
virtual const DeviceInfo* WINAPI GetDeviceInfo() { return &device_info; }
|
||||
virtual uint32_t WINAPI GetDeviceStatus() { return device_status; }
|
||||
virtual void WINAPI GetBatteryState(BatteryState* out) { if (out) *out = {}; }
|
||||
virtual HRESULT WINAPI CreateForceFeedbackEffect(uint32_t, const void*, void** out) {
|
||||
DEVICE_STUB(6, "CreateForceFeedbackEffect");
|
||||
if (out) *out = nullptr;
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
virtual bool WINAPI IsForceFeedbackMotorPoweredOn(uint32_t) { return false; }
|
||||
virtual void WINAPI SetForceFeedbackMotorGain(uint32_t, float) { DEVICE_STUB(8, "SetForceFeedbackMotorGain"); }
|
||||
virtual HRESULT WINAPI SetHapticMotorState(uint32_t, const void*) {
|
||||
DEVICE_STUB(9, "SetHapticMotorState");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
virtual void WINAPI SetRumbleState(const void*) { DEVICE_STUB(10, "SetRumbleState"); }
|
||||
virtual void WINAPI SetInputSynchronizationState(bool) { DEVICE_STUB(11, "SetInputSynchronizationState"); }
|
||||
virtual void WINAPI SendInputSynchronizationHint() { DEVICE_STUB(12, "SendInputSynchronizationHint"); }
|
||||
virtual void WINAPI PowerOff() { DEVICE_STUB(13, "PowerOff"); }
|
||||
virtual HRESULT WINAPI CreateRawDeviceReport(uint32_t, uint32_t, void** out) {
|
||||
DEVICE_STUB(14, "CreateRawDeviceReport");
|
||||
if (out) *out = nullptr;
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
virtual HRESULT WINAPI GetRawDeviceFeature(uint32_t, void** out) {
|
||||
DEVICE_STUB(15, "GetRawDeviceFeature");
|
||||
if (out) *out = nullptr;
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
virtual HRESULT WINAPI SetRawDeviceFeature(void*) {
|
||||
DEVICE_STUB(16, "SetRawDeviceFeature");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
virtual HRESULT WINAPI SendRawDeviceOutput(void*) {
|
||||
DEVICE_STUB(17, "SendRawDeviceOutput");
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
virtual HRESULT WINAPI SendRawDeviceOutputWithResponse(void*, void** out) {
|
||||
DEVICE_STUB(18, "SendRawDeviceOutputWithResponse");
|
||||
if (out) *out = nullptr;
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
virtual HRESULT WINAPI ExecuteRawDeviceIoControl(uint32_t, size_t, const void*, size_t, void*, size_t* out) {
|
||||
DEVICE_STUB(19, "ExecuteRawDeviceIoControl");
|
||||
if (out) *out = 0;
|
||||
return E_NOTIMPL;
|
||||
}
|
||||
virtual bool WINAPI AcquireExclusiveRawDeviceAccess(uint64_t) {
|
||||
DEVICE_STUB(20, "AcquireExclusiveRawDeviceAccess");
|
||||
return false;
|
||||
}
|
||||
virtual void WINAPI ReleaseExclusiveRawDeviceAccess() { DEVICE_STUB(21, "ReleaseExclusiveRawDeviceAccess"); }
|
||||
};
|
||||
Device virtual_device;
|
||||
|
||||
bool pressed(int key) { return (GetAsyncKeyState(key) & 0x8000) != 0; }
|
||||
|
||||
bool owns_foreground() {
|
||||
const HWND foreground = GetForegroundWindow();
|
||||
DWORD pid = 0;
|
||||
return foreground && GetWindowThreadProcessId(foreground, &pid) && pid == GetCurrentProcessId();
|
||||
}
|
||||
|
||||
void sample_stick(int left, int right, int down, int up, float& x, float& y) {
|
||||
x = static_cast<float>(pressed(right) - pressed(left));
|
||||
y = static_cast<float>(pressed(up) - pressed(down));
|
||||
if (x != 0 && y != 0) {
|
||||
constexpr float diagonal = 0.70710678f;
|
||||
x *= diagonal;
|
||||
y *= diagonal;
|
||||
}
|
||||
}
|
||||
|
||||
GamepadState sample_keyboard() {
|
||||
GamepadState state{};
|
||||
if (!owns_foreground()) return state;
|
||||
|
||||
constexpr struct KeyBinding { int key; uint32_t button; } buttons[] = {
|
||||
{'P', 0x1}, {VK_TAB, 0x2}, {VK_RETURN, 0x4}, {VK_SPACE, 0x4},
|
||||
{VK_ESCAPE, 0x8}, {VK_BACK, 0x8}, {'X', 0x10}, {'Y', 0x20},
|
||||
{VK_UP, 0x40}, {VK_DOWN, 0x80}, {VK_LEFT, 0x100}, {VK_RIGHT, 0x200},
|
||||
{'Q', 0x400}, {'E', 0x800}, {'F', 0x1000}, {'H', 0x2000},
|
||||
};
|
||||
for (const auto& binding : buttons) {
|
||||
if (pressed(binding.key)) state.buttons |= binding.button;
|
||||
}
|
||||
state.left_trigger = pressed('Z') ? 1.0f : 0.0f;
|
||||
state.right_trigger = pressed('C') ? 1.0f : 0.0f;
|
||||
sample_stick('A', 'D', 'S', 'W', state.left_x, state.left_y);
|
||||
sample_stick('J', 'L', 'K', 'I', state.right_x, state.right_y);
|
||||
return owns_foreground() ? state : GamepadState{};
|
||||
}
|
||||
|
||||
struct Sample {
|
||||
GamepadState state{};
|
||||
uint64_t sequence = 0;
|
||||
uint64_t timestamp = 0;
|
||||
};
|
||||
|
||||
SRWLOCK sample_lock = SRWLOCK_INIT;
|
||||
Sample latest;
|
||||
|
||||
Sample sample() {
|
||||
AcquireSRWLockExclusive(&sample_lock);
|
||||
const GamepadState state = sample_keyboard();
|
||||
if (!latest.sequence || std::memcmp(&state, &latest.state, sizeof(state)) != 0) {
|
||||
latest = {state, latest.sequence + 1, GetTickCount64() * 1000};
|
||||
}
|
||||
const Sample snapshot = latest;
|
||||
ReleaseSRWLockExclusive(&sample_lock);
|
||||
return snapshot;
|
||||
}
|
||||
|
||||
class Reading final : public IUnknown {
|
||||
LONG refs_ = 1;
|
||||
const Sample sample_;
|
||||
|
||||
public:
|
||||
explicit Reading(const Sample& value) : sample_(value) {}
|
||||
HRESULT WINAPI QueryInterface(REFIID iid, void** out) override {
|
||||
if (!out) return E_POINTER;
|
||||
*out = nullptr;
|
||||
if (iid != IID_IUnknown && iid != reading_iid) return E_NOINTERFACE;
|
||||
AddRef();
|
||||
*out = this;
|
||||
return S_OK;
|
||||
}
|
||||
ULONG WINAPI AddRef() override { return InterlockedIncrement(&refs_); }
|
||||
ULONG WINAPI Release() override {
|
||||
const auto left = InterlockedDecrement(&refs_);
|
||||
if (!left) delete this;
|
||||
return left;
|
||||
}
|
||||
|
||||
virtual uint32_t WINAPI GetInputKind() { return input_kind; }
|
||||
virtual uint64_t WINAPI GetSequenceNumber(uint32_t kind) { return kind & input_kind ? sample_.sequence : 0; }
|
||||
virtual uint64_t WINAPI GetTimestamp() { return sample_.timestamp; }
|
||||
virtual void WINAPI GetDevice(void** out) {
|
||||
if (!out) return;
|
||||
virtual_device.AddRef();
|
||||
*out = &virtual_device;
|
||||
}
|
||||
virtual bool WINAPI GetRawReport(void** out) {
|
||||
if (out) *out = nullptr;
|
||||
return false;
|
||||
}
|
||||
virtual uint32_t WINAPI GetControllerAxisCount() { return 0; }
|
||||
virtual uint32_t WINAPI GetControllerAxisState(uint32_t, float*) { return 0; }
|
||||
virtual uint32_t WINAPI GetControllerButtonCount() { return 0; }
|
||||
virtual uint32_t WINAPI GetControllerButtonState(uint32_t, bool*) { return 0; }
|
||||
virtual uint32_t WINAPI GetControllerSwitchCount() { return 0; }
|
||||
virtual uint32_t WINAPI GetControllerSwitchState(uint32_t, uint32_t*) { return 0; }
|
||||
virtual uint32_t WINAPI GetKeyCount() { return 0; }
|
||||
virtual uint32_t WINAPI GetKeyState(uint32_t, void*) { return 0; }
|
||||
virtual bool WINAPI GetMouseState(void*) { READING_STUB(16, "GetMouseState"); return false; }
|
||||
virtual uint32_t WINAPI GetTouchCount() { return 0; }
|
||||
virtual uint32_t WINAPI GetTouchState(uint32_t, void*) { return 0; }
|
||||
virtual bool WINAPI GetMotionState(void*) { READING_STUB(19, "GetMotionState"); return false; }
|
||||
virtual bool WINAPI GetArcadeStickState(void*) { READING_STUB(20, "GetArcadeStickState"); return false; }
|
||||
virtual bool WINAPI GetFlightStickState(void*) { READING_STUB(21, "GetFlightStickState"); return false; }
|
||||
virtual bool WINAPI GetGamepadState(GamepadState* out) {
|
||||
if (!out) return false;
|
||||
*out = sample_.state;
|
||||
static std::atomic_flag reported;
|
||||
if ((out->buttons || out->left_trigger || out->right_trigger || out->left_x || out->left_y ||
|
||||
out->right_x || out->right_y) && !reported.test_and_set(std::memory_order_relaxed)) {
|
||||
bx_log_emit(BX_LOG_INFO, "gameinput", "keyboard_gamepad_input",
|
||||
"guest read a non-neutral keyboard gamepad state");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
virtual bool WINAPI GetRacingWheelState(void*) { READING_STUB(23, "GetRacingWheelState"); return false; }
|
||||
virtual bool WINAPI GetUiNavigationState(void*) { READING_STUB(24, "GetUiNavigationState"); return false; }
|
||||
};
|
||||
|
||||
} // namespace
|
||||
|
||||
IUnknown* device() { return &virtual_device; }
|
||||
|
||||
bool has_id(const void* id) {
|
||||
return id && std::memcmp(id, device_id.data(), device_id.size()) == 0;
|
||||
}
|
||||
|
||||
HRESULT read(void** out) {
|
||||
*out = new (std::nothrow) Reading(sample());
|
||||
return *out ? S_OK : E_OUTOFMEMORY;
|
||||
}
|
||||
|
||||
} // namespace keyboard_gamepad
|
||||
@@ -1,17 +0,0 @@
|
||||
#pragma once
|
||||
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
#include <cstdint>
|
||||
|
||||
namespace keyboard_gamepad {
|
||||
|
||||
constexpr uint32_t input_kind = 0x00040000;
|
||||
constexpr uint32_t device_status = 0x3; // connected and input enabled
|
||||
constexpr HRESULT device_not_found = static_cast<HRESULT>(0x838a0002u);
|
||||
|
||||
IUnknown* device();
|
||||
bool has_id(const void* id);
|
||||
HRESULT read(void** out);
|
||||
|
||||
} // namespace keyboard_gamepad
|
||||
@@ -212,11 +212,48 @@ void transition(ID3D12GraphicsCommandList* list, ID3D12Resource* resource,
|
||||
list->ResourceBarrier(1, &barrier);
|
||||
}
|
||||
|
||||
HRESULT read_bytes(HANDLE file, UINT64 offset, void* destination, const void* source, DWORD size) {
|
||||
// Title memory can be temporarily inaccessible while xmem replaces a mapped view. Keep reads
|
||||
// and writes out of that window. Never nest guards or hold one across an XMem call.
|
||||
class RemapGuard {
|
||||
public:
|
||||
explicit RemapGuard(bool needed = true) {
|
||||
if (!needed) return;
|
||||
const HMODULE xmem = GetModuleHandleW(L"xmem.dll");
|
||||
if (!xmem) return;
|
||||
const auto enter = resolve(xmem, "bx_xmem_remap_guard_enter");
|
||||
leave_ = resolve(xmem, "bx_xmem_remap_guard_leave");
|
||||
if (enter && leave_) {
|
||||
enter();
|
||||
} else {
|
||||
leave_ = nullptr;
|
||||
static std::atomic<bool> warned{false};
|
||||
if (!warned.exchange(true)) {
|
||||
bx_log_emit(BX_LOG_WARN, "xcrdapi", "dstorage_remap_guard",
|
||||
"loaded xmem.dll does not provide both remap guard exports");
|
||||
}
|
||||
}
|
||||
}
|
||||
~RemapGuard() {
|
||||
if (leave_) leave_();
|
||||
}
|
||||
RemapGuard(const RemapGuard&) = delete;
|
||||
RemapGuard& operator=(const RemapGuard&) = delete;
|
||||
|
||||
private:
|
||||
using Fn = void (*)();
|
||||
static Fn resolve(HMODULE module, const char* name) {
|
||||
return reinterpret_cast<Fn>(reinterpret_cast<void*>(GetProcAddress(module, name)));
|
||||
}
|
||||
Fn leave_ = nullptr;
|
||||
};
|
||||
|
||||
HRESULT read_bytes(HANDLE file, UINT64 offset, void* destination, const void* source, DWORD size,
|
||||
bool title_destination = false) {
|
||||
if (!size) return S_OK;
|
||||
if (!destination) return E_INVALIDARG;
|
||||
if (!file) {
|
||||
if (!source) return E_INVALIDARG;
|
||||
RemapGuard remap_guard;
|
||||
std::memmove(destination, source, size);
|
||||
return S_OK;
|
||||
}
|
||||
@@ -229,6 +266,7 @@ HRESULT read_bytes(HANDLE file, UINT64 offset, void* destination, const void* so
|
||||
|
||||
DWORD bytes = 0;
|
||||
HRESULT result = S_OK;
|
||||
RemapGuard remap_guard(title_destination);
|
||||
if (!ReadFile(file, destination, size, &bytes, &operation)) {
|
||||
const DWORD error = GetLastError();
|
||||
if (error != ERROR_IO_PENDING) {
|
||||
@@ -252,7 +290,7 @@ HRESULT write_mapped(HANDLE file, const Request& request) {
|
||||
return E_FAIL;
|
||||
}
|
||||
auto* destination = static_cast<unsigned char*>(mapped) + static_cast<SIZE_T>(request.resource_offset);
|
||||
const HRESULT read_hr = read_bytes(file, request.file_offset, destination, request.source, request.size);
|
||||
const HRESULT read_hr = read_bytes(file, request.file_offset, destination, request.source, request.size, true);
|
||||
D3D12_RANGE written{
|
||||
static_cast<SIZE_T>(request.resource_offset),
|
||||
static_cast<SIZE_T>(request.resource_offset + request.size)};
|
||||
@@ -424,6 +462,7 @@ HRESULT inflate_request(HANDLE file, const Request& request) {
|
||||
if (!compressed) return E_OUTOFMEMORY;
|
||||
HRESULT hr = read_bytes(file, request.file_offset, compressed, request.source, request.size);
|
||||
if (SUCCEEDED(hr)) {
|
||||
RemapGuard remap_guard;
|
||||
const BxInflateResult r = bx_zlib_inflate(compressed, request.size, static_cast<uint8_t*>(request.destination),
|
||||
request.output_size);
|
||||
if (r != BxInflateResult::ok) {
|
||||
@@ -461,7 +500,10 @@ CopyResult fulfill(HANDLE file, const Request& request) {
|
||||
if (traced.fetch_add(1) >= 20000) return result;
|
||||
const DWORD out = request.compression == compression_zlib ? request.output_size : request.size;
|
||||
uint64_t head[2] = {0, 0};
|
||||
if (SUCCEEDED(result.hr) && request.destination && out >= 16) std::memcpy(head, request.destination, 16);
|
||||
if (SUCCEEDED(result.hr) && request.destination && out >= 16) {
|
||||
RemapGuard remap_guard;
|
||||
std::memcpy(head, request.destination, 16);
|
||||
}
|
||||
char detail[220];
|
||||
std::snprintf(detail, sizeof(detail), "dst=%p..%p out=%lu src=%lu offset=0x%llx compression=%u hr=0x%08lx head=%016llx %016llx",
|
||||
request.destination, static_cast<const uint8_t*>(request.destination) + out, out, request.size,
|
||||
@@ -483,7 +525,7 @@ CopyResult fulfill_request(HANDLE file, const Request& request) {
|
||||
}
|
||||
if (!request.size) return {};
|
||||
if (!request.resource) {
|
||||
return {read_bytes(file, request.file_offset, request.destination, request.source, request.size), false};
|
||||
return {read_bytes(file, request.file_offset, request.destination, request.source, request.size, true), false};
|
||||
}
|
||||
|
||||
const D3D12_RESOURCE_DESC desc = request.resource->GetDesc();
|
||||
|
||||
@@ -97,6 +97,17 @@ struct Lock {
|
||||
~Lock() { ReleaseSRWLockExclusive(&memory_lock); }
|
||||
};
|
||||
|
||||
// Replacing part of a mapped view can leave a temporary gap across that view
|
||||
// while its remaining runs are restored. DirectStorage holds remap_lock shared
|
||||
// while accessing title memory. Mapping and freeing take it exclusively during
|
||||
// replacement. Acquire it before memory_lock to keep the lock order consistent.
|
||||
SRWLOCK remap_lock = SRWLOCK_INIT;
|
||||
|
||||
struct RemapExclusive {
|
||||
RemapExclusive() { AcquireSRWLockExclusive(&remap_lock); }
|
||||
~RemapExclusive() { ReleaseSRWLockExclusive(&remap_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,
|
||||
@@ -690,6 +701,7 @@ extern "C" BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR count, PULONG_PTR page_ar
|
||||
return FALSE;
|
||||
}
|
||||
|
||||
RemapExclusive remap;
|
||||
Lock lock;
|
||||
SIZE_T validated = 0;
|
||||
for (; validated < count; ++validated) {
|
||||
@@ -741,6 +753,7 @@ extern "C" PVOID WINAPI XMemMapPhysicalPages(PVOID address, ULONG_PTR count, PUL
|
||||
return nullptr;
|
||||
}
|
||||
if (!have_placeholder_api()) return nullptr;
|
||||
RemapExclusive remap;
|
||||
Lock lock;
|
||||
auto* base = static_cast<BYTE*>(address);
|
||||
const auto begin = reinterpret_cast<uintptr_t>(address);
|
||||
@@ -799,6 +812,7 @@ static BOOL scatter_impl(PVOID* addresses, ULONG_PTR count, PULONG_PTR page_arra
|
||||
return FALSE;
|
||||
}
|
||||
if (!have_placeholder_api()) return FALSE;
|
||||
RemapExclusive remap;
|
||||
Lock lock;
|
||||
for (ULONG_PTR i = 0; i < count; ++i) {
|
||||
const auto slot = reinterpret_cast<uintptr_t>(addresses[i]);
|
||||
@@ -838,6 +852,14 @@ static BOOL scatter_impl(PVOID* addresses, ULONG_PTR count, PULONG_PTR page_arra
|
||||
return TRUE;
|
||||
}
|
||||
|
||||
extern "C" void bx_xmem_remap_guard_enter(void) {
|
||||
AcquireSRWLockShared(&remap_lock);
|
||||
}
|
||||
|
||||
extern "C" void bx_xmem_remap_guard_leave(void) {
|
||||
ReleaseSRWLockShared(&remap_lock);
|
||||
}
|
||||
|
||||
extern "C" int bx_xmem_query_region(uint64_t va, bx_xmem_region_info_t* out_info) {
|
||||
if (!out_info) return 0;
|
||||
|
||||
|
||||
@@ -1,2 +0,0 @@
|
||||
add_executable(test_gameinput_keyboard main.cpp)
|
||||
target_link_libraries(test_gameinput_keyboard PRIVATE kernel32 user32 uuid)
|
||||
@@ -1,185 +0,0 @@
|
||||
#include <windows.h>
|
||||
#include <unknwn.h>
|
||||
|
||||
#include <array>
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr uint32_t gamepad_kind = 0x00040000;
|
||||
constexpr uint32_t keyboard_kind = 0x10;
|
||||
constexpr uint32_t connected = 1;
|
||||
constexpr uint32_t input_enabled = 2;
|
||||
constexpr GUID device_iid = {0x31dd86fb, 0x4c1b, 0x408a, {0x86, 0x8f, 0x43, 0x9b, 0x3c, 0xd4, 0x71, 0x25}};
|
||||
constexpr GUID reading_iid = {0x2156947a, 0xe1fa, 0x4de0, {0xa3, 0x0b, 0xd8, 0x12, 0x93, 0x1d, 0xbd, 0x8d}};
|
||||
struct State {
|
||||
uint32_t buttons;
|
||||
float lt, rt, lx, ly, rx, ry;
|
||||
};
|
||||
static_assert(sizeof(State) == 28);
|
||||
|
||||
template <typename Fn>
|
||||
Fn slot(IUnknown* object, unsigned index) {
|
||||
return reinterpret_cast<Fn>((*reinterpret_cast<void***>(object))[index]);
|
||||
}
|
||||
|
||||
using Create = HRESULT (WINAPI*)(void**);
|
||||
using Current = HRESULT (WINAPI*)(IUnknown*, uint32_t, IUnknown*, IUnknown**);
|
||||
using DeviceCallback = void (WINAPI*)(uint64_t, void*, IUnknown*, uint64_t, uint32_t, uint32_t);
|
||||
using Register = HRESULT (WINAPI*)(IUnknown*, IUnknown*, uint32_t, uint32_t, uint32_t, void*, DeviceCallback, uint64_t*);
|
||||
using Unregister = bool (WINAPI*)(IUnknown*, uint64_t, uint64_t);
|
||||
using StateFn = bool (WINAPI*)(IUnknown*, State*);
|
||||
using Sequence = uint64_t (WINAPI*)(IUnknown*, uint32_t);
|
||||
|
||||
struct Notification {
|
||||
unsigned count = 0;
|
||||
uint64_t token = 0;
|
||||
uint64_t timestamp = 0;
|
||||
uint32_t current = 0;
|
||||
uint32_t previous = 0;
|
||||
IUnknown* device = nullptr;
|
||||
};
|
||||
|
||||
void WINAPI note_device(uint64_t token, void* context, IUnknown* device, uint64_t timestamp,
|
||||
uint32_t current, uint32_t previous) {
|
||||
auto& result = *static_cast<Notification*>(context);
|
||||
result = {result.count + 1, token, timestamp, current, previous, device};
|
||||
}
|
||||
|
||||
void pump_messages() {
|
||||
MSG message;
|
||||
while (PeekMessageW(&message, nullptr, 0, 0, PM_REMOVE)) {
|
||||
TranslateMessage(&message);
|
||||
DispatchMessageW(&message);
|
||||
}
|
||||
}
|
||||
|
||||
bool focus_window(HWND window) {
|
||||
SetForegroundWindow(window);
|
||||
for (unsigned i = 0; i < 40; ++i) {
|
||||
pump_messages();
|
||||
if (GetForegroundWindow() == window) return true;
|
||||
Sleep(10);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
template <size_t N>
|
||||
bool keys(const std::array<WORD, N>& bindings, bool down) {
|
||||
std::array<INPUT, N> events{};
|
||||
for (size_t i = 0; i < N; ++i) {
|
||||
events[i].type = INPUT_KEYBOARD;
|
||||
events[i].ki.wVk = bindings[i];
|
||||
events[i].ki.dwFlags = down ? 0 : KEYEVENTF_KEYUP;
|
||||
}
|
||||
const bool ok = SendInput(static_cast<UINT>(N), events.data(), sizeof(INPUT)) == N;
|
||||
for (unsigned i = 0; i < 4; ++i) {
|
||||
pump_messages();
|
||||
Sleep(10);
|
||||
}
|
||||
return ok;
|
||||
}
|
||||
|
||||
uint32_t read_u32(const unsigned char* bytes, size_t offset) {
|
||||
uint32_t value;
|
||||
std::memcpy(&value, bytes + offset, sizeof(value));
|
||||
return value;
|
||||
}
|
||||
|
||||
#define REQUIRE(expr) do { if (!(expr)) { \
|
||||
std::fprintf(stderr, "FAIL: GameInput keyboard line %d: %s\n", __LINE__, #expr); return 1; \
|
||||
} } while (false)
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
HMODULE module = LoadLibraryW(L"GameInput.dll");
|
||||
REQUIRE(module);
|
||||
const auto create = reinterpret_cast<Create>(reinterpret_cast<void*>(GetProcAddress(module, MAKEINTRESOURCEA(1))));
|
||||
REQUIRE(create);
|
||||
IUnknown* game_input = nullptr;
|
||||
REQUIRE(create(reinterpret_cast<void**>(&game_input)) == S_OK && game_input);
|
||||
const auto current = slot<Current>(game_input, 4);
|
||||
const auto register_device = slot<Register>(game_input, 9);
|
||||
const auto unregister = slot<Unregister>(game_input, 13);
|
||||
|
||||
Notification pad{};
|
||||
uint64_t token = 0;
|
||||
REQUIRE(register_device(game_input, nullptr, gamepad_kind, connected, 2, &pad, note_device, &token) == S_OK);
|
||||
REQUIRE(pad.count == 1 && pad.token == token && pad.device && pad.timestamp);
|
||||
REQUIRE(pad.current == (connected | input_enabled) && pad.previous == 0);
|
||||
REQUIRE(unregister(game_input, token, 10000));
|
||||
|
||||
Notification filtered{};
|
||||
REQUIRE(register_device(game_input, nullptr, keyboard_kind, connected, 2, &filtered, note_device, &token) == S_OK);
|
||||
REQUIRE(filtered.count == 0 && unregister(game_input, token, 10000));
|
||||
REQUIRE(register_device(game_input, pad.device, gamepad_kind, connected, 0, &filtered, note_device, &token) == S_OK);
|
||||
REQUIRE(filtered.count == 0 && unregister(game_input, token, 10000));
|
||||
|
||||
void* interface_pointer = nullptr;
|
||||
REQUIRE(pad.device->QueryInterface(device_iid, &interface_pointer) == S_OK && interface_pointer == pad.device);
|
||||
static_cast<IUnknown*>(interface_pointer)->Release();
|
||||
using Info = const unsigned char* (WINAPI*)(IUnknown*);
|
||||
const auto info = slot<Info>(pad.device, 3)(pad.device);
|
||||
REQUIRE(info && read_u32(info, 0) == 320 && read_u32(info, 104) == gamepad_kind);
|
||||
using Find = HRESULT (WINAPI*)(IUnknown*, const void*, IUnknown**);
|
||||
IUnknown* found = nullptr;
|
||||
REQUIRE(slot<Find>(game_input, 16)(game_input, info + 32, &found) == S_OK && found == pad.device);
|
||||
found->Release();
|
||||
|
||||
IUnknown* resting = nullptr;
|
||||
REQUIRE(current(game_input, gamepad_kind, pad.device, &resting) == S_OK && resting);
|
||||
REQUIRE(resting->QueryInterface(reading_iid, &interface_pointer) == S_OK && interface_pointer == resting);
|
||||
static_cast<IUnknown*>(interface_pointer)->Release();
|
||||
const auto state = slot<StateFn>(resting, 22);
|
||||
const auto sequence = slot<Sequence>(resting, 4);
|
||||
using GetDevice = void (WINAPI*)(IUnknown*, IUnknown**);
|
||||
slot<GetDevice>(resting, 6)(resting, &found);
|
||||
REQUIRE(found == pad.device);
|
||||
found->Release();
|
||||
State neutral{};
|
||||
REQUIRE(state(resting, &neutral) && neutral.buttons == 0 && neutral.lx == 0 && neutral.rt == 0);
|
||||
REQUIRE(sequence(resting, gamepad_kind) != 0 && sequence(resting, keyboard_kind) == 0);
|
||||
IUnknown* invalid = resting;
|
||||
REQUIRE(current(game_input, gamepad_kind, game_input, &invalid) == static_cast<HRESULT>(0x838a0002u) && !invalid);
|
||||
|
||||
HWND window = CreateWindowExW(0, L"STATIC", L"BetterXen keyboard conformance",
|
||||
WS_VISIBLE | WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, CW_USEDEFAULT,
|
||||
300, 150, nullptr, nullptr, GetModuleHandleW(nullptr), nullptr);
|
||||
REQUIRE(window && focus_window(window));
|
||||
const std::array<WORD, 7> bindings{VK_RETURN, VK_LEFT, 'W', 'D', 'J', 'C', 'Q'};
|
||||
const bool keydown = keys(bindings, true);
|
||||
IUnknown* active = nullptr;
|
||||
const HRESULT active_result = current(game_input, gamepad_kind, pad.device, &active);
|
||||
|
||||
ShowWindow(window, SW_HIDE);
|
||||
pump_messages();
|
||||
IUnknown* unfocused = nullptr;
|
||||
const HRESULT unfocused_result = current(game_input, gamepad_kind, pad.device, &unfocused);
|
||||
const bool keyup = keys(bindings, false);
|
||||
DestroyWindow(window);
|
||||
|
||||
REQUIRE(keydown && keyup && active_result == S_OK && active);
|
||||
REQUIRE(unfocused_result == S_OK && unfocused);
|
||||
State pressed{};
|
||||
REQUIRE(state(active, &pressed));
|
||||
REQUIRE(pressed.buttons == (0x4 | 0x100 | 0x400));
|
||||
REQUIRE(pressed.lt == 0 && pressed.rt == 1);
|
||||
REQUIRE(std::fabs(pressed.lx - 0.70710678f) < 0.001f && std::fabs(pressed.ly - 0.70710678f) < 0.001f);
|
||||
REQUIRE(pressed.rx == -1 && pressed.ry == 0);
|
||||
REQUIRE(state(resting, &neutral) && neutral.buttons == 0);
|
||||
REQUIRE(state(unfocused, &neutral) && neutral.buttons == 0 && neutral.rt == 0 && neutral.lx == 0);
|
||||
REQUIRE(sequence(active, gamepad_kind) > sequence(resting, gamepad_kind));
|
||||
REQUIRE(sequence(unfocused, gamepad_kind) > sequence(active, gamepad_kind));
|
||||
|
||||
unfocused->Release();
|
||||
active->Release();
|
||||
resting->Release();
|
||||
game_input->Release();
|
||||
FreeLibrary(module);
|
||||
std::puts("PASS: GameInput v0 keyboard gamepad enumeration, state, and foreground handling");
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1,5 @@
|
||||
add_executable(test_xcrdapi_remap_guard main.cpp)
|
||||
target_compile_definitions(test_xcrdapi_remap_guard PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
|
||||
target_include_directories(test_xcrdapi_remap_guard PRIVATE "${BX_ABI_INCLUDE_DIR}"
|
||||
"${BX_ROOT_DIR}/shims/xcrdapi" "${BX_ROOT_DIR}/shims/xcrdapi/dstorage")
|
||||
target_link_libraries(test_xcrdapi_remap_guard PRIVATE xcrdapi xmem kernel32 uuid)
|
||||
@@ -0,0 +1,243 @@
|
||||
/*
|
||||
* XCRDAPI.dll stores into a title's memory on worker threads while the title remaps neighbouring
|
||||
* pages of the same XMemMapPhysicalPages window (handoff #668: an access violation in
|
||||
* XCRDAPI.dll, writing to memory that is not mapped). Windows and Wine cannot replace a mapped
|
||||
* view in one step, so XCRDAPI.dll brackets its stores with xmem.dll's remap guard
|
||||
* (bx_xmem_remap_guard_enter / _leave) and the remapping calls wait for it. Memory requests that
|
||||
* span the window are queued while the window is remapped over and over; without the guard a
|
||||
* store lands in a gap and the process dies in an access violation. Three request shapes, each
|
||||
* for about 2 s:
|
||||
* 1. memory to memory into the window (public DirectStorage interface): stores;
|
||||
* 2. a zlib stream inflated into the window for about 4 s (BetterXen's request interface):
|
||||
* stores and back-reference loads by the inflater;
|
||||
* 3. memory to memory out of the window into private memory: loads, which fault in the gap
|
||||
* like stores.
|
||||
* The zlib stream is built here by hand (RFC 1950/1951, fixed Huffman codes), so the expected
|
||||
* output does not come from the code under test.
|
||||
*/
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
#include "dstorage_mingw.h"
|
||||
#include "synthetic_storage.h"
|
||||
|
||||
extern "C" {
|
||||
PVOID WINAPI XMemVirtualAlloc(PVOID, SIZE_T, DWORD, uint64_t, DWORD);
|
||||
BOOL WINAPI XMemAllocatePhysicalPages(uint64_t, PULONG_PTR, PULONG_PTR);
|
||||
PVOID WINAPI XMemMapPhysicalPages(PVOID, ULONG_PTR, PULONG_PTR);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr SIZE_T kPage = 64 * 1024;
|
||||
constexpr UINT32 kSlots = 4; // one request spans four 64 KB slots
|
||||
constexpr UINT32 kRequestBytes = kSlots * kPage;
|
||||
constexpr DWORD kMem64KPages = 0x20400000;
|
||||
constexpr uint64_t kXMemCpu = 0x1;
|
||||
constexpr uint64_t kXMemMappable = 0x20;
|
||||
|
||||
#define CHECK(condition) \
|
||||
do { \
|
||||
if (!(condition)) { \
|
||||
std::fprintf(stderr, "xcrdapi remap guard:%d: %s (Win32 error %lu)\n", __LINE__, \
|
||||
#condition, static_cast<unsigned long>(GetLastError())); \
|
||||
return 1; \
|
||||
} \
|
||||
} while (false)
|
||||
|
||||
template <class Interface>
|
||||
struct Com {
|
||||
Interface* value = nullptr;
|
||||
~Com() {
|
||||
if (value) value->Release();
|
||||
}
|
||||
Interface* operator->() const { return value; }
|
||||
void** out() { return reinterpret_cast<void**>(&value); }
|
||||
};
|
||||
|
||||
// RFC 1950 stream for `count` copies of `byte`: one fixed-Huffman deflate block (RFC 1951
|
||||
// 3.2.6) holding the byte as a literal, then copies of distance 1 (length 258, and one shorter
|
||||
// copy for the rest), then end of block; adler-32 at the end.
|
||||
class BitWriter {
|
||||
public:
|
||||
std::vector<unsigned char> bytes;
|
||||
void bits(uint32_t value, int n) { // LSB first, as deflate packs header and extra bits
|
||||
for (int i = 0; i < n; ++i) put((value >> i) & 1u);
|
||||
}
|
||||
void code(uint32_t value, int n) { // Huffman codes are packed most significant bit first
|
||||
for (int i = n - 1; i >= 0; --i) put((value >> i) & 1u);
|
||||
}
|
||||
|
||||
private:
|
||||
void put(uint32_t bit) {
|
||||
if (used_ == 0) bytes.push_back(0);
|
||||
bytes.back() |= static_cast<unsigned char>(bit << used_);
|
||||
used_ = (used_ + 1) & 7;
|
||||
}
|
||||
int used_ = 0;
|
||||
};
|
||||
|
||||
std::vector<unsigned char> zlib_repeat(unsigned char byte, uint32_t count) {
|
||||
BitWriter w;
|
||||
w.bits(1, 1); // BFINAL
|
||||
w.bits(1, 2); // BTYPE = 01, fixed Huffman codes
|
||||
w.code(0x30u + byte, 8); // literals 0-143: 8-bit codes 00110000 + value
|
||||
uint32_t left = count - 1;
|
||||
while (left) {
|
||||
if (left >= 258) {
|
||||
w.code(0xC0u + (285 - 280), 8); // length 258: symbol 285, codes 280-287 are 11000000 + n
|
||||
left -= 258;
|
||||
} else {
|
||||
// Lengths 3..257 below 258 use symbols 257-284 with extra bits; this stream only needs
|
||||
// what is left after 258-byte copies, which the test keeps at 15 (symbol 267: lengths
|
||||
// 15-16, 1 extra bit).
|
||||
if (left != 15) return {};
|
||||
w.code(267 - 256, 7); // symbols 256-279: 7-bit codes 0000000 + (n - 256)
|
||||
w.bits(0, 1); // extra bit: 15 = base 15 + 0
|
||||
left = 0;
|
||||
}
|
||||
w.code(0, 5); // distance code 0 = distance 1, 5-bit fixed code, no extra bits
|
||||
}
|
||||
w.code(0, 7); // end of block: symbol 256
|
||||
std::vector<unsigned char> out = {0x78, 0x01};
|
||||
out.insert(out.end(), w.bytes.begin(), w.bytes.end());
|
||||
uint32_t a = 1, b = 0;
|
||||
for (uint32_t i = 0; i < count; ++i) {
|
||||
a = (a + byte) % 65521;
|
||||
b = (b + a) % 65521;
|
||||
}
|
||||
const uint32_t adler = (b << 16) | a;
|
||||
for (int shift = 24; shift >= 0; shift -= 8) out.push_back(static_cast<unsigned char>(adler >> shift));
|
||||
return out;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
// Eight pages: four in the window under test, four to swap in and out of it.
|
||||
ULONG_PTR count = 8;
|
||||
ULONG_PTR pages[8]{};
|
||||
CHECK(XMemAllocatePhysicalPages(0, &count, pages) && count == 8);
|
||||
auto* base = static_cast<BYTE*>(XMemVirtualAlloc(nullptr, kSlots * kPage, MEM_RESERVE | kMem64KPages,
|
||||
kXMemMappable | kXMemCpu, PAGE_READWRITE));
|
||||
CHECK(base);
|
||||
CHECK(XMemMapPhysicalPages(base, kSlots, pages) == base);
|
||||
|
||||
Com<IDStorageFactory> factory;
|
||||
CHECK(DStorageGetFactory(__uuidof(IDStorageFactory), factory.out()) == S_OK && factory.value);
|
||||
DSTORAGE_QUEUE_DESC desc{};
|
||||
desc.SourceType = DSTORAGE_REQUEST_SOURCE_MEMORY;
|
||||
desc.Capacity = DSTORAGE_MIN_QUEUE_CAPACITY;
|
||||
desc.Priority = DSTORAGE_PRIORITY_NORMAL;
|
||||
Com<IDStorageQueue1> queue;
|
||||
CHECK(factory->CreateQueue(&desc, __uuidof(IDStorageQueue1), queue.out()) == S_OK);
|
||||
HANDLE done = CreateEventW(nullptr, FALSE, FALSE, nullptr);
|
||||
CHECK(done);
|
||||
|
||||
std::vector<unsigned char> source(kRequestBytes, 0xA5);
|
||||
DSTORAGE_REQUEST request{};
|
||||
request.Options.SourceType = DSTORAGE_REQUEST_SOURCE_MEMORY;
|
||||
request.Options.DestinationType = DSTORAGE_REQUEST_DESTINATION_MEMORY;
|
||||
request.Source.Memory.Source = source.data();
|
||||
request.Source.Memory.Size = kRequestBytes;
|
||||
request.Destination.Memory.Buffer = base;
|
||||
request.Destination.Memory.Size = kRequestBytes;
|
||||
|
||||
// Slots 1 and 2 of the window are remapped between two page pairs; slots 0 and 3 keep theirs.
|
||||
ULONG_PTR swap_a[2] = {pages[1], pages[2]};
|
||||
ULONG_PTR swap_b[2] = {pages[5], pages[6]};
|
||||
const DWORD start = GetTickCount();
|
||||
int batches = 0;
|
||||
int remaps = 0;
|
||||
while (GetTickCount() - start < 3000) {
|
||||
for (int i = 0; i < 4; ++i) queue->EnqueueRequest(&request);
|
||||
queue->EnqueueSetEvent(done);
|
||||
queue->Submit();
|
||||
// Remap under the requests while they run: the title does this between requests.
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
CHECK(XMemMapPhysicalPages(base + kPage, 2, (remaps & 1) ? swap_b : swap_a) == base + kPage);
|
||||
++remaps;
|
||||
}
|
||||
CHECK(WaitForSingleObject(done, 10000) == WAIT_OBJECT_0);
|
||||
++batches;
|
||||
}
|
||||
CHECK(WaitForSingleObject(queue->GetErrorEvent(), 0) == WAIT_TIMEOUT);
|
||||
std::printf("stores: batches=%d remaps=%d\n", batches, remaps);
|
||||
CHECK(batches > 10 && remaps > 40);
|
||||
|
||||
// 2. zlib streams inflated into the window, through BetterXen's request interface.
|
||||
using namespace bx::storage;
|
||||
Com<Factory> synthetic;
|
||||
CHECK(DStorageGetFactory(factory_iid, synthetic.out()) == S_OK && synthetic.value);
|
||||
Com<Queue> zqueue;
|
||||
CHECK(synthetic->CreateQueue(64, queue_iid, zqueue.out()) == S_OK && zqueue.value);
|
||||
const std::vector<unsigned char> zstream = zlib_repeat(0x5A, kRequestBytes); // 1 + 1016 * 258 + 15 bytes
|
||||
CHECK(!zstream.empty() && zstream.size() < kRequestBytes);
|
||||
Request zrequest{nullptr, 0, zstream.data(), base, static_cast<DWORD>(zstream.size()), compression_zlib};
|
||||
zrequest.output_size = kRequestBytes;
|
||||
// Control: the stream inflates correctly with nothing remapped.
|
||||
zqueue->EnqueueRequest(&zrequest);
|
||||
zqueue->EnqueueSetEvent(done);
|
||||
zqueue->Submit();
|
||||
CHECK(WaitForSingleObject(done, 10000) == WAIT_OBJECT_0);
|
||||
ErrorRecord zcontrol{};
|
||||
zqueue->RetrieveErrorRecord(&zcontrol);
|
||||
std::printf("zlib control: failures=%llu hr=0x%08lx first=%02x last=%02x\n",
|
||||
static_cast<unsigned long long>(zcontrol.failure_count), static_cast<unsigned long>(zcontrol.first_error),
|
||||
base[0], base[kRequestBytes - 1]);
|
||||
CHECK(zcontrol.failure_count == 0 && base[0] == 0x5A && base[kPage + 7] == 0x5A && base[kRequestBytes - 1] == 0x5A);
|
||||
int zbatches = 0;
|
||||
const DWORD zstart = GetTickCount();
|
||||
while (GetTickCount() - zstart < 4000) {
|
||||
for (int i = 0; i < 4; ++i) zqueue->EnqueueRequest(&zrequest);
|
||||
zqueue->EnqueueSetEvent(done);
|
||||
zqueue->Submit();
|
||||
for (int i = 0; i < 8; ++i) {
|
||||
CHECK(XMemMapPhysicalPages(base + kPage, 2, (remaps & 1) ? swap_b : swap_a) == base + kPage);
|
||||
++remaps;
|
||||
}
|
||||
CHECK(WaitForSingleObject(done, 10000) == WAIT_OBJECT_0);
|
||||
++zbatches;
|
||||
}
|
||||
ErrorRecord zerr{};
|
||||
zqueue->RetrieveErrorRecord(&zerr);
|
||||
std::printf("zlib under remap: batches=%d failures=%llu\n", zbatches, static_cast<unsigned long long>(zerr.failure_count));
|
||||
if (zerr.failure_count) std::printf("zlib first error hr=0x%08lx count=%llu\n", static_cast<unsigned long>(zerr.first_error), static_cast<unsigned long long>(zerr.failure_count));
|
||||
CHECK(zerr.failure_count == 0);
|
||||
CHECK(base[0] == 0x5A && base[kRequestBytes - 1] == 0x5A); // slots 0 and 3 keep their pages
|
||||
CHECK(zbatches > 10);
|
||||
|
||||
// 3. The window as the source: loads from title memory into private memory.
|
||||
std::vector<unsigned char> sink(kRequestBytes, 0);
|
||||
DSTORAGE_REQUEST load{};
|
||||
load.Options.SourceType = DSTORAGE_REQUEST_SOURCE_MEMORY;
|
||||
load.Options.DestinationType = DSTORAGE_REQUEST_DESTINATION_MEMORY;
|
||||
load.Source.Memory.Source = base;
|
||||
load.Source.Memory.Size = kRequestBytes;
|
||||
load.Destination.Memory.Buffer = sink.data();
|
||||
load.Destination.Memory.Size = kRequestBytes;
|
||||
int lbatches = 0;
|
||||
const DWORD lstart = GetTickCount();
|
||||
while (GetTickCount() - lstart < 2000) {
|
||||
for (int i = 0; i < 4; ++i) queue->EnqueueRequest(&load);
|
||||
queue->EnqueueSetEvent(done);
|
||||
queue->Submit();
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
CHECK(XMemMapPhysicalPages(base + kPage, 2, (remaps & 1) ? swap_b : swap_a) == base + kPage);
|
||||
++remaps;
|
||||
}
|
||||
CHECK(WaitForSingleObject(done, 10000) == WAIT_OBJECT_0);
|
||||
++lbatches;
|
||||
}
|
||||
CHECK(WaitForSingleObject(queue->GetErrorEvent(), 0) == WAIT_TIMEOUT);
|
||||
CHECK(sink[0] == 0x5A); // slot 0 still holds the inflated bytes
|
||||
std::printf("loads: batches=%d remaps=%d\n", lbatches, remaps);
|
||||
CHECK(lbatches > 10);
|
||||
CloseHandle(done);
|
||||
std::puts("test_xcrdapi_remap_guard: passed");
|
||||
return 0;
|
||||
}
|
||||
@@ -3,3 +3,16 @@ add_executable(test_xcrdapi_xbox main.cpp)
|
||||
target_compile_definitions(test_xcrdapi_xbox PRIVATE WIDL_EXPLICIT_AGGREGATE_RETURNS)
|
||||
target_include_directories(test_xcrdapi_xbox PRIVATE "${BX_ABI_INCLUDE_DIR}" "${BX_ROOT_DIR}/shims/xcrdapi/dstorage")
|
||||
target_link_libraries(test_xcrdapi_xbox PRIVATE xcrdapi bx_runtime_veh kernel32)
|
||||
|
||||
# Load this observer explicitly from a test-only directory. Keep the fixture
|
||||
# DLL and its import library away from the real shim's build artifacts.
|
||||
add_library(test_xcrdapi_guard_observer SHARED guard_observer.cpp)
|
||||
set(guard_fixture_dir "${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/xcrdapi_guard_fixture")
|
||||
set_target_properties(test_xcrdapi_guard_observer PROPERTIES
|
||||
PREFIX ""
|
||||
OUTPUT_NAME xmem
|
||||
RUNTIME_OUTPUT_DIRECTORY "${guard_fixture_dir}"
|
||||
ARCHIVE_OUTPUT_DIRECTORY "${guard_fixture_dir}"
|
||||
LIBRARY_OUTPUT_DIRECTORY "${guard_fixture_dir}")
|
||||
target_link_libraries(test_xcrdapi_guard_observer PRIVATE kernel32)
|
||||
add_dependencies(test_xcrdapi_xbox test_xcrdapi_guard_observer)
|
||||
@@ -0,0 +1,22 @@
|
||||
// Test-only XMem provider. Records guard calls on stable buffers without remapping memory.
|
||||
#include <windows.h>
|
||||
#include <cstdint>
|
||||
|
||||
namespace {
|
||||
volatile LONG enters = 0;
|
||||
volatile LONG leaves = 0;
|
||||
}
|
||||
|
||||
extern "C" __declspec(dllexport) void bx_xmem_remap_guard_enter() {
|
||||
InterlockedIncrement(&enters);
|
||||
}
|
||||
|
||||
extern "C" __declspec(dllexport) void bx_xmem_remap_guard_leave() {
|
||||
InterlockedIncrement(&leaves);
|
||||
}
|
||||
|
||||
extern "C" __declspec(dllexport) uint64_t bx_test_guard_counts() {
|
||||
const auto enter_count = static_cast<uint32_t>(InterlockedCompareExchange(&enters, 0, 0));
|
||||
const auto leave_count = static_cast<uint32_t>(InterlockedCompareExchange(&leaves, 0, 0));
|
||||
return (static_cast<uint64_t>(enter_count) << 32) | leave_count;
|
||||
}
|
||||
@@ -100,6 +100,40 @@ bool wait_complete(IXboxDStorageStatusArray* status, UINT32 index) {
|
||||
return false;
|
||||
}
|
||||
|
||||
using GuardCounts = uint64_t (*)();
|
||||
|
||||
struct GuardObserver {
|
||||
HMODULE module = nullptr;
|
||||
GuardCounts counts = nullptr;
|
||||
|
||||
bool load() {
|
||||
wchar_t executable[MAX_PATH]{};
|
||||
const DWORD length = GetModuleFileNameW(nullptr, executable, MAX_PATH);
|
||||
if (!length || length >= MAX_PATH || GetModuleHandleW(L"xmem.dll")) return false;
|
||||
const std::wstring path(executable, length);
|
||||
const size_t separator = path.find_last_of(L"\\/");
|
||||
if (separator == std::wstring::npos) return false;
|
||||
const std::wstring library = path.substr(0, separator + 1) + L"xcrdapi_guard_fixture\\xmem.dll";
|
||||
module = LoadLibraryExW(library.c_str(), nullptr,
|
||||
LOAD_LIBRARY_SEARCH_DLL_LOAD_DIR | LOAD_LIBRARY_SEARCH_SYSTEM32);
|
||||
if (!module) return false;
|
||||
counts = reinterpret_cast<GuardCounts>(reinterpret_cast<void*>(GetProcAddress(module, "bx_test_guard_counts")));
|
||||
return counts != nullptr;
|
||||
}
|
||||
|
||||
~GuardObserver() {
|
||||
if (module) FreeLibrary(module);
|
||||
}
|
||||
|
||||
void expect(uint64_t before, uint32_t expected, const char* operation) const {
|
||||
const uint64_t after = counts();
|
||||
const auto entered = static_cast<uint32_t>((after >> 32) - (before >> 32));
|
||||
const auto left = static_cast<uint32_t>(after) - static_cast<uint32_t>(before);
|
||||
check(entered == expected && left == expected, "%s guard count: enter=%u leave=%u expected=%u",
|
||||
operation, entered, left, expected);
|
||||
}
|
||||
};
|
||||
|
||||
/* Reads only what this run appended: bx-cli run appends to a supplied BX_LOG_FILE,
|
||||
* so records from an earlier run must not satisfy these checks. */
|
||||
long g_log_start = 0;
|
||||
@@ -162,6 +196,12 @@ int main() {
|
||||
}
|
||||
g_log_start = log_size(log_path);
|
||||
|
||||
GuardObserver guard;
|
||||
if (!guard.load() || !SetEnvironmentVariableW(L"BX_DSTORAGE_TRACE", L"1")) {
|
||||
std::fprintf(stderr, "FAIL: unable to initialize the DirectStorage guard observer\n");
|
||||
return 1;
|
||||
}
|
||||
|
||||
IXboxDStorageFactory* factory = nullptr;
|
||||
HRESULT hr = DStorageGetFactory(kXboxFactoryIid, reinterpret_cast<void**>(&factory));
|
||||
check(hr == S_OK && factory != nullptr, "DStorageGetFactory(Xbox) must succeed (hr=0x%08lx)",
|
||||
@@ -247,6 +287,7 @@ int main() {
|
||||
req.source_ptr = file;
|
||||
req.file_offset = 64;
|
||||
req.source_size = sizeof(dest);
|
||||
const uint64_t file_read_guards = guard.counts();
|
||||
file_q->EnqueueRequest(&req);
|
||||
file_q->EnqueueStatus(status, 0);
|
||||
file_q->Submit();
|
||||
@@ -254,6 +295,7 @@ int main() {
|
||||
check(status->GetHResult(0) == S_OK, "file read status must be S_OK (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(status->GetHResult(0)));
|
||||
check(std::memcmp(dest, payload + 64, sizeof(dest)) == 0, "file read bytes must match payload[64..192]");
|
||||
guard.expect(file_read_guards, 2, "file read and destination trace");
|
||||
|
||||
/* DSTORAGE_REQUEST_OPTIONS.BcpackMode (bits 1-4) has no decoder: E_NOTIMPL and a stub log. */
|
||||
XboxRequest bcpack_req = req;
|
||||
@@ -308,6 +350,7 @@ int main() {
|
||||
fz.source_ptr = zfile;
|
||||
fz.file_offset = 100;
|
||||
fz.source_size = sizeof(kZlibStream);
|
||||
const uint64_t file_inflate_guards = guard.counts();
|
||||
file_q->EnqueueRequest(&fz);
|
||||
file_q->EnqueueStatus(status, 1);
|
||||
file_q->Submit();
|
||||
@@ -315,6 +358,7 @@ int main() {
|
||||
"file-source zlib request must succeed (hr=0x%08lx)", static_cast<unsigned long>(status->GetHResult(1)));
|
||||
check(std::memcmp(file_inflated, expected_text, kZlibPlainSize) == 0,
|
||||
"file-source zlib request must inflate to the expected text");
|
||||
guard.expect(file_inflate_guards, 2, "file-source inflate and destination trace");
|
||||
zfile->Close();
|
||||
zfile->Release();
|
||||
}
|
||||
@@ -372,12 +416,14 @@ int main() {
|
||||
zreq.destination_size = kZlibPlainSize;
|
||||
zreq.source_ptr = const_cast<uint8_t*>(kZlibStream);
|
||||
zreq.source_size = sizeof(kZlibStream);
|
||||
const uint64_t mem_inflate_guards = guard.counts();
|
||||
mem_q->EnqueueRequest(&zreq);
|
||||
mem_q->EnqueueStatus(status, 1);
|
||||
mem_q->Submit();
|
||||
check(wait_complete(status, 1) && status->GetHResult(1) == S_OK, "zlib request must succeed (hr=0x%08lx)",
|
||||
static_cast<unsigned long>(status->GetHResult(1)));
|
||||
check(std::memcmp(inflated, expected, kZlibPlainSize) == 0, "zlib request must inflate to the expected text");
|
||||
guard.expect(mem_inflate_guards, 3, "compressed memory read, inflate, and destination trace");
|
||||
|
||||
/* DSTORAGE_QUEUE_OPTIONS.AutoSubmitDisabled (flags bit 0, authorized GDK documentation):
|
||||
* enqueued work waits for Submit. Without it the queue submits by itself once half full
|
||||
|
||||
@@ -0,0 +1,3 @@
|
||||
add_executable(test_xmem_remap_guard main.cpp)
|
||||
target_include_directories(test_xmem_remap_guard PRIVATE "${BX_ABI_INCLUDE_DIR}")
|
||||
target_link_libraries(test_xmem_remap_guard PRIVATE xmem kernel32)
|
||||
@@ -0,0 +1,169 @@
|
||||
/*
|
||||
* The remap guard (bx_xmem_remap_guard_enter / _leave): Windows and Wine cannot replace a mapped
|
||||
* view in one step, so remapping a range leaves its pages unmapped for a moment and a store from
|
||||
* another thread into that window faults. A writer that brackets its stores with the guard must
|
||||
* never see that gap, and XMemMapPhysicalPages, XMemMapPhysicalPagesScatter and
|
||||
* XMemFreePhysicalPages must wait for it. Observed on the target build (handoff #668): worker
|
||||
* threads of XCRDAPI.dll storing into a window the title was remapping.
|
||||
*/
|
||||
#include <windows.h>
|
||||
|
||||
#include <cstdint>
|
||||
#include <cstdio>
|
||||
|
||||
#include "bx_xmem_internal.h"
|
||||
|
||||
extern "C" {
|
||||
PVOID WINAPI XMemVirtualAlloc(PVOID, SIZE_T, DWORD, uint64_t, DWORD);
|
||||
BOOL WINAPI XMemAllocatePhysicalPages(uint64_t, PULONG_PTR, PULONG_PTR);
|
||||
BOOL WINAPI XMemFreePhysicalPages(ULONG_PTR, PULONG_PTR);
|
||||
PVOID WINAPI XMemMapPhysicalPages(PVOID, ULONG_PTR, PULONG_PTR);
|
||||
BOOL WINAPI XMemMapPhysicalPagesScatter(PVOID*, ULONG_PTR, PULONG_PTR);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
constexpr SIZE_T kPage = 64 * 1024;
|
||||
constexpr DWORD kMem64KPages = 0x20400000;
|
||||
constexpr uint64_t kXMemCpu = 0x1;
|
||||
constexpr uint64_t kXMemMappable = 0x20;
|
||||
|
||||
#define CHECK(condition) \
|
||||
do { \
|
||||
if (!(condition)) { \
|
||||
std::fprintf(stderr, "xmem remap guard:%d: %s (Win32 error %lu)\n", __LINE__, \
|
||||
#condition, static_cast<unsigned long>(GetLastError())); \
|
||||
return false; \
|
||||
} \
|
||||
} while (false)
|
||||
|
||||
struct Holder {
|
||||
HANDLE entered;
|
||||
HANDLE release;
|
||||
};
|
||||
|
||||
DWORD WINAPI hold_guard(void* arg) {
|
||||
auto* holder = static_cast<Holder*>(arg);
|
||||
bx_xmem_remap_guard_enter();
|
||||
SetEvent(holder->entered);
|
||||
WaitForSingleObject(holder->release, 10000);
|
||||
bx_xmem_remap_guard_leave();
|
||||
return 0;
|
||||
}
|
||||
|
||||
enum class Call { map, scatter, free_pages };
|
||||
|
||||
struct Remap {
|
||||
Call call;
|
||||
BYTE* base;
|
||||
ULONG_PTR* pages;
|
||||
bool ok;
|
||||
};
|
||||
|
||||
DWORD WINAPI do_remap(void* arg) {
|
||||
auto* remap = static_cast<Remap*>(arg);
|
||||
switch (remap->call) {
|
||||
case Call::map:
|
||||
remap->ok = XMemMapPhysicalPages(remap->base, 2, remap->pages) == remap->base;
|
||||
break;
|
||||
case Call::scatter: {
|
||||
PVOID slots[2] = {remap->base, remap->base + kPage};
|
||||
remap->ok = XMemMapPhysicalPagesScatter(slots, 2, remap->pages) != FALSE;
|
||||
break;
|
||||
}
|
||||
case Call::free_pages:
|
||||
remap->ok = XMemFreePhysicalPages(2, remap->pages) != FALSE;
|
||||
break;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// While one thread holds the guard, the call must not finish; once released, it must.
|
||||
bool blocks_until_released(Call call, BYTE* base, ULONG_PTR* pages) {
|
||||
Holder holder{CreateEventW(nullptr, TRUE, FALSE, nullptr), CreateEventW(nullptr, TRUE, FALSE, nullptr)};
|
||||
CHECK(holder.entered && holder.release);
|
||||
HANDLE guard_thread = CreateThread(nullptr, 0, hold_guard, &holder, 0, nullptr);
|
||||
CHECK(guard_thread);
|
||||
CHECK(WaitForSingleObject(holder.entered, 5000) == WAIT_OBJECT_0);
|
||||
|
||||
Remap remap{call, base, pages, false};
|
||||
HANDLE remap_thread = CreateThread(nullptr, 0, do_remap, &remap, 0, nullptr);
|
||||
CHECK(remap_thread);
|
||||
CHECK(WaitForSingleObject(remap_thread, 300) == WAIT_TIMEOUT); // waits for the open guard
|
||||
|
||||
SetEvent(holder.release);
|
||||
CHECK(WaitForSingleObject(remap_thread, 5000) == WAIT_OBJECT_0); // and goes on once it is gone
|
||||
CHECK(remap.ok);
|
||||
WaitForSingleObject(guard_thread, 5000);
|
||||
CloseHandle(remap_thread);
|
||||
CloseHandle(guard_thread);
|
||||
CloseHandle(holder.entered);
|
||||
CloseHandle(holder.release);
|
||||
return true;
|
||||
}
|
||||
|
||||
struct Writer {
|
||||
BYTE* stable; // a slot that keeps its page
|
||||
BYTE* neighbour; // a slot that is remapped all the time
|
||||
volatile LONG stop;
|
||||
volatile LONG stores;
|
||||
};
|
||||
|
||||
DWORD WINAPI write_under_guard(void* arg) {
|
||||
auto* writer = static_cast<Writer*>(arg);
|
||||
while (!writer->stop) {
|
||||
bx_xmem_remap_guard_enter();
|
||||
for (int i = 0; i < 64; ++i) {
|
||||
writer->stable[i * 8] = static_cast<BYTE>(i);
|
||||
writer->neighbour[i * 8] = static_cast<BYTE>(i);
|
||||
}
|
||||
bx_xmem_remap_guard_leave();
|
||||
InterlockedIncrement(&writer->stores);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool check_remap_guard() {
|
||||
ULONG_PTR count = 8;
|
||||
ULONG_PTR pages[8]{};
|
||||
CHECK(XMemAllocatePhysicalPages(0, &count, pages) && count == 8);
|
||||
auto* base = static_cast<BYTE*>(XMemVirtualAlloc(nullptr, 8 * kPage, MEM_RESERVE | kMem64KPages,
|
||||
kXMemMappable | kXMemCpu, PAGE_READWRITE));
|
||||
CHECK(base);
|
||||
CHECK(XMemMapPhysicalPages(base, 4, pages) == base);
|
||||
|
||||
// 1. Each call that unmaps or maps views waits for an open guard.
|
||||
ULONG_PTR other[2] = {pages[5], pages[6]};
|
||||
CHECK(blocks_until_released(Call::map, base + 2 * kPage, other));
|
||||
CHECK(blocks_until_released(Call::scatter, base + 2 * kPage, pages + 2));
|
||||
CHECK(blocks_until_released(Call::free_pages, base, pages + 6));
|
||||
|
||||
// 2. A writer that brackets its stores never faults while its neighbours are remapped as
|
||||
// often (without the guard the process dies in an access violation).
|
||||
CHECK(XMemMapPhysicalPages(base, 4, pages) == base);
|
||||
Writer writer{base, base + kPage, 0, 0};
|
||||
HANDLE thread = CreateThread(nullptr, 0, write_under_guard, &writer, 0, nullptr);
|
||||
CHECK(thread);
|
||||
ULONG_PTR a[2] = {pages[1], pages[2]};
|
||||
ULONG_PTR b[2] = {pages[2], pages[1]};
|
||||
const DWORD start = GetTickCount();
|
||||
int remaps = 0;
|
||||
while (GetTickCount() - start < 1500) {
|
||||
CHECK(XMemMapPhysicalPages(base + kPage, 2, (remaps & 1) ? b : a) == base + kPage);
|
||||
++remaps;
|
||||
Sleep(1); // a title remaps between requests; SRW locks are not fair to a loop with no gap
|
||||
}
|
||||
InterlockedExchange(&writer.stop, 1);
|
||||
CHECK(WaitForSingleObject(thread, 5000) == WAIT_OBJECT_0);
|
||||
CloseHandle(thread);
|
||||
std::printf("remaps=%d guarded writer batches=%ld\n", remaps, static_cast<long>(writer.stores));
|
||||
CHECK(remaps > 10 && writer.stores > 10);
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
int main() {
|
||||
if (!check_remap_guard()) return 1;
|
||||
std::puts("test_xmem_remap_guard: passed");
|
||||
}
|
||||
Reference in new issue
Block a user