Repository navigation
runtime: add XMem virtual memory and write-watch exports - #2199
Conversation
Expose XMemVirtualAlloc and the write-watch queries through the xmem shim. Map ordinary and 64 KiB allocations to host virtual memory, and reject unsupported page modes instead of silently using the wrong alignment.
Do not report a successful virtual allocation when nonzero XMem attributes have no host mapping yet.
|
Tested 7c2fbe1 on an NVIDIA GeForce RTX 3050 Laptop GPU, driver 32.0.16.2101, Windows 11, native MSVC (VS 2022 Build Tools, Ninja, RelWithDebInfo), with
AI-assisted (Claude Code). |
|
Built and tested No test exercises the three new exports yet, so this only shows they build and don't break anything else. A small case in the existing shim tests (an AI-assisted (Claude Code). |
|
Update at 84f86c5: rebuilt the permanent xmem_test with MSVC 19.44.35230 / SDK NuGet 10.0.26100.9457. Independent Windows verification at Environment: Windows 11 Pro 26300, MSVC 19.44.35230, CMake 4.2.1/Ninja 1.13.1, Microsoft.Windows.SDK.CPP and CPP.x64 10.0.26100.9457 (their include/lib directory is named
The runner covers:
The Windows reference is the native API, with separate allocations for host/shim comparisons. For failed Negative controls, compiled from private scratch copies only:
I found no failure in this tested subset. This does not establish the Xbox calling convention from a real call site, nonzero-attribute semantics, 2 MiB/physical-page support, or write-watch suspend/resume; those remain outside the stated implementation. It also does not exercise game boot. One useful follow-up in this PR would be permanent coverage of the three new exports: the existing 19-check Standalone synthetic differential runner (compile from the repository root)Save as cl /nologo /std:c++20 /EHsc /W4 /permissive- /utf-8 /DWIN32_LEAN_AND_MEAN /DNOMINMAX /I runtime/shims xmem_virtual_review.cpp runtime/shims/xmem.cpp runtime/shims/registry.cpp /Fe:xmem_virtual_review.exe /link /OPT:NOREF psapi.lib
.\xmem_virtual_review.exe// Independent synthetic Windows differential review of PR #2199. AI-assisted.
// Uses the real registry.cpp/xmem.cpp, not copied allocation code. No game files.
#include <windows.h>
#include <algorithm>
#include <array>
#include <cstdint>
#include <cstdio>
#include <limits>
#include <string>
#include <vector>
#include "shims.h"
using AllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD);
using WatchFn = UINT(WINAPI*)(DWORD, void*, SIZE_T, void**, ULONG_PTR*, ULONG*);
using ResetFn = UINT(WINAPI*)(void*, SIZE_T);
AllocFn guest_alloc;
WatchFn guest_watch;
ResetFn guest_reset;
int checks = 0, failures = 0, scenarios = 0;
DWORD page_bytes;
constexpr DWORD guest64k = 0x20400000;
void check(bool ok, const char* label) {
++checks;
if (!ok) { ++failures; std::printf("FAIL: %s\n", label); }
}
struct Region {
void* base{};
Region() = default;
explicit Region(void* p) : base(p) {}
Region(const Region&) = delete;
Region& operator=(const Region&) = delete;
~Region() { if (base) VirtualFree(base, 0, MEM_RELEASE); }
void* at(SIZE_T offset) const { return static_cast<unsigned char*>(base) + offset; }
};
void* allocate(bool shim, void* address, SIZE_T size, DWORD type, DWORD protect) {
return shim ? guest_alloc(address, size, type, 0, protect) : VirtualAlloc(address, size, type, protect);
}
bool query(void* address, MEMORY_BASIC_INFORMATION& info) {
return VirtualQuery(address, &info, sizeof(info)) == sizeof(info);
}
void compare_null_alloc(SIZE_T size, DWORD type, DWORD protect) {
++scenarios;
SetLastError(0xdead);
Region native(allocate(false, nullptr, size, type, protect));
const DWORD native_error = GetLastError();
SetLastError(0xdead);
Region shim(allocate(true, nullptr, size, type, protect));
const DWORD shim_error = GetLastError();
const bool same_success = (native.base != nullptr) == (shim.base != nullptr);
check(same_success, "ordinary VirtualAlloc success matches host");
if (!same_success) std::printf(" size=%zu type=%08lx protect=%08lx native=%d/%lu shim=%d/%lu\n",
size, type, protect, native.base != nullptr, native_error, shim.base != nullptr, shim_error);
if (!native.base || !shim.base) {
if (!native.base && !shim.base) check(native_error == shim_error, "ordinary allocation failure code matches host");
return;
}
MEMORY_BASIC_INFORMATION a{}, b{};
check(query(native.base, a) && query(shim.base, b), "query ordinary allocations");
check(a.RegionSize == b.RegionSize && a.State == b.State && a.Protect == b.Protect &&
a.AllocationProtect == b.AllocationProtect && a.Type == b.Type,
"ordinary allocation extent/state/protection matches host");
if (a.State == MEM_COMMIT && (a.Protect & 0xff) == PAGE_READWRITE && !(a.Protect & PAGE_GUARD)) {
auto* bytes = static_cast<volatile unsigned char*>(shim.base);
bool zero = true;
for (SIZE_T offset = 0; offset < size; offset += page_bytes) zero &= bytes[offset] == 0;
check(zero && bytes[size - 1] == 0, "new committed memory is zero initialized");
bytes[0] = 0x35; bytes[size - 1] = 0x79;
check(bytes[size - 1] == 0x79, "first and last requested bytes writable");
}
}
void compare_commit(SIZE_T offset, SIZE_T size) {
++scenarios;
constexpr SIZE_T extent = 0x40000;
Region native(VirtualAlloc(nullptr, extent, MEM_RESERVE, PAGE_NOACCESS));
Region shim(VirtualAlloc(nullptr, extent, MEM_RESERVE, PAGE_NOACCESS));
check(native.base && shim.base, "reserve independent arenas for commit comparison");
if (!native.base || !shim.base) return;
void* a = allocate(false, native.at(offset), size, MEM_COMMIT, PAGE_READWRITE);
void* b = allocate(true, shim.at(offset), size, MEM_COMMIT, PAGE_READWRITE);
check(a && b, "commit unaligned requested range succeeds on host and shim");
if (!a || !b) return;
check(static_cast<unsigned char*>(a) - static_cast<unsigned char*>(native.base) ==
static_cast<unsigned char*>(b) - static_cast<unsigned char*>(shim.base), "commit returned offset matches host");
bool same = true;
for (SIZE_T at = 0; at < extent; at += page_bytes) {
MEMORY_BASIC_INFORMATION x{}, y{};
same &= query(native.at(at), x) && query(shim.at(at), y) && x.State == y.State && x.Protect == y.Protect;
}
check(same, "every page's commit state/protection matches host");
}
void test_guest64k() {
for (SIZE_T requested : {SIZE_T(1), SIZE_T(0xffff), SIZE_T(0x10000), SIZE_T(0x10001)}) {
++scenarios;
const SIZE_T expected = requested <= 0x10000 ? 0x10000 : 0x20000;
Region shim(guest_alloc(nullptr, requested, guest64k | MEM_RESERVE | MEM_COMMIT, 0, PAGE_READWRITE));
check(shim.base != nullptr, "guest 64K allocation succeeds");
if (!shim.base) continue;
MEMORY_BASIC_INFORMATION info{};
check((reinterpret_cast<uintptr_t>(shim.base) & 0xffff) == 0, "guest 64K allocation aligned");
const bool whole_extent = query(shim.base, info) && info.State == MEM_COMMIT && info.RegionSize == expected;
check(whole_extent, "guest 64K commitment rounds to complete 64K blocks");
if (!whole_extent) continue; // fail the mutation without touching an uncommitted tail
auto* bytes = static_cast<volatile unsigned char*>(shim.base);
bytes[0] = 0x12; bytes[expected - 1] = 0x34;
check(bytes[0] == 0x12 && bytes[expected - 1] == 0x34, "whole guest 64K committed extent writable");
}
++scenarios;
Region arena(guest_alloc(nullptr, 0x40000, guest64k | MEM_RESERVE, 0, PAGE_NOACCESS));
check(arena.base != nullptr, "guest 64K reserve-only arena");
if (!arena.base) return;
// Two bytes cross a 64K boundary: precisely blocks 1 and 2 should commit.
void* result = guest_alloc(arena.at(0x1ffff), 2, guest64k | MEM_COMMIT, 0, PAGE_READWRITE);
check(result == arena.at(0x10000), "guest 64K unaligned commit returns rounded base");
bool exact = true;
for (SIZE_T i = 0; i < 0x40000; i += page_bytes) {
MEMORY_BASIC_INFORMATION info{};
const DWORD expected = i >= 0x10000 && i < 0x30000 ? MEM_COMMIT : MEM_RESERVE;
exact &= query(arena.at(i), info) && info.State == expected;
}
check(exact, "64K boundary crossing commits exactly two guest blocks, preserves neighbors");
}
struct WatchResult {
UINT status{};
ULONG_PTR count{};
ULONG granularity{};
std::vector<SIZE_T> offsets;
bool sentinels{};
};
WatchResult watch(bool shim, DWORD flags, const Region& region, SIZE_T offset, SIZE_T bytes, ULONG_PTR capacity = 32) {
std::array<void*, 34> output{};
std::fill(output.begin(), output.end(), reinterpret_cast<void*>(uintptr_t(0xcafef00d)));
struct Count { ULONG_PTR value; std::uint64_t sentinel; } count{capacity, 0x123456789abcdef0};
struct Gran { ULONG value; ULONG sentinel; } gran{0xdeadbeef, 0x89abcdef};
const UINT status = shim ? guest_watch(flags, region.at(offset), bytes, output.data(), &count.value, &gran.value)
: GetWriteWatch(flags, region.at(offset), bytes, output.data(), &count.value, &gran.value);
WatchResult result{status, count.value, gran.value, {}, true};
for (ULONG_PTR i = 0; i < (std::min)(count.value, capacity); ++i)
result.offsets.push_back(reinterpret_cast<uintptr_t>(output[i]) - reinterpret_cast<uintptr_t>(region.base));
std::sort(result.offsets.begin(), result.offsets.end());
for (SIZE_T i = capacity; i < output.size(); ++i)
result.sentinels &= output[i] == reinterpret_cast<void*>(uintptr_t(0xcafef00d));
result.sentinels &= count.sentinel == 0x123456789abcdef0 && gran.sentinel == 0x89abcdef;
return result;
}
void compare_watch(const WatchResult& a, const WatchResult& b, const char* label) {
++scenarios;
check(a.status == b.status, label);
// GetWriteWatch only documents the returned addresses/count/granularity on success.
// Error output is not an oracle (untouched address sentinels are not relative pointers).
if (a.status == 0 && b.status == 0)
check(a.count == b.count && a.granularity == b.granularity && a.offsets == b.offsets,
"write-watch count/granularity/relative addresses match host");
check(a.sentinels && b.sentinels, "write-watch respects array capacity and out-parameter widths");
}
void dirty(const Region& region) {
auto* bytes = static_cast<volatile unsigned char*>(region.base);
bytes[1] = 1; bytes[2 * page_bytes + 17] = 2; bytes[7 * page_bytes + page_bytes - 1] = 3;
}
void test_write_watch(DWORD mode) {
const SIZE_T extent = 0x20000;
Region native(VirtualAlloc(nullptr, extent, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, PAGE_READWRITE));
Region shim(guest_alloc(nullptr, extent, mode | MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, 0, PAGE_READWRITE));
check(native.base && shim.base, "create independent write-watch arenas");
if (!native.base || !shim.base) return;
compare_watch(watch(false, 0, native, 0, extent), watch(true, 0, shim, 0, extent), "initial write-watch status matches");
dirty(native); dirty(shim);
auto a = watch(false, 0, native, 0, extent), b = watch(true, 0, shim, 0, extent);
compare_watch(a, b, "three dirty pages match host");
check(b.status == 0 && b.offsets == std::vector<SIZE_T>{0, 2 * page_bytes, 7 * page_bytes} && b.granularity == page_bytes,
"write-watch finds exact dirty pages with host page granularity");
// Non-reset observation must retain dirty state. Also compare small capacities and invalid flags.
compare_watch(watch(false, 0, native, 0, extent), watch(true, 0, shim, 0, extent), "observation does not reset");
compare_watch(watch(false, 0, native, 0, extent, 1), watch(true, 0, shim, 0, extent, 1), "capacity-one behavior matches host");
compare_watch(watch(false, 2, native, 0, extent), watch(true, 2, shim, 0, extent), "invalid write-watch flag matches host");
compare_watch(watch(false, 0, native, page_bytes, 3 * page_bytes),
watch(true, 0, shim, page_bytes, 3 * page_bytes), "subrange dirty pages match host");
UINT ar = ResetWriteWatch(native.at(2 * page_bytes), page_bytes);
UINT br = guest_reset(shim.at(2 * page_bytes), page_bytes);
++scenarios; check(ar == br && br == 0, "subrange ResetWriteWatch succeeds like host");
a = watch(false, 0, native, 0, extent); b = watch(true, 0, shim, 0, extent);
compare_watch(a, b, "subrange reset preserves dirty pages outside subrange");
check(b.offsets == std::vector<SIZE_T>{0, 7 * page_bytes}, "reset clears exactly its dirty page");
compare_watch(watch(false, WRITE_WATCH_FLAG_RESET, native, 0, extent),
watch(true, WRITE_WATCH_FLAG_RESET, shim, 0, extent), "query-and-reset returns remaining dirty pages");
a = watch(false, 0, native, 0, extent); b = watch(true, 0, shim, 0, extent);
compare_watch(a, b, "query-and-reset clears subsequent observation");
check(b.status == 0 && b.count == 0, "no pages remain dirty after query-and-reset");
dirty(native); dirty(shim);
ar = ResetWriteWatch(native.base, extent); br = guest_reset(shim.base, extent);
++scenarios; check(ar == br && br == 0, "full ResetWriteWatch succeeds like host");
b = watch(true, 0, shim, 0, extent);
check(b.status == 0 && b.count == 0, "full reset clears all dirty pages");
}
void test_rejections() {
struct Bad { void* address; SIZE_T size; DWORD flags; ULONGLONG attributes; DWORD error; };
const SIZE_T max = (std::numeric_limits<SIZE_T>::max)();
const Bad cases[] = {
{nullptr, 0, MEM_RESERVE | MEM_COMMIT, 0, ERROR_INVALID_PARAMETER},
{nullptr, 1, MEM_RESERVE | MEM_COMMIT, 1, ERROR_NOT_SUPPORTED},
{nullptr, 1, 0x20000000 | MEM_RESERVE | MEM_COMMIT, 0, ERROR_NOT_SUPPORTED},
{nullptr, 1, 0x00400000 | MEM_RESERVE | MEM_COMMIT, 0, ERROR_INVALID_PARAMETER},
{nullptr, 1, 0x80000000 | MEM_RESERVE | MEM_COMMIT, 0, ERROR_INVALID_PARAMETER},
{nullptr, max, guest64k | MEM_RESERVE | MEM_COMMIT, 0, ERROR_INVALID_PARAMETER},
{reinterpret_cast<void*>(max - 1), 4, MEM_COMMIT, 0, ERROR_INVALID_PARAMETER},
{reinterpret_cast<void*>(max - 2), 1, guest64k | MEM_COMMIT, 0, ERROR_INVALID_PARAMETER},
};
for (const auto& bad : cases) {
++scenarios;
SetLastError(0xdead);
Region result(guest_alloc(bad.address, bad.size, bad.flags, bad.attributes, PAGE_READWRITE));
const DWORD error = GetLastError();
check(!result.base && error == bad.error, "documented rejected/overflow case returns deterministic error");
}
Region native(VirtualAlloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE));
Region shim(guest_alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT, 0, PAGE_READWRITE));
if (native.base && shim.base) {
compare_watch(watch(false, 0, native, 0, 0x10000), watch(true, 0, shim, 0, 0x10000),
"write-watch on untracked allocation matches host failure");
++scenarios;
const UINT a = ResetWriteWatch(native.base, 0x10000), b = guest_reset(shim.base, 0x10000);
check(a == b && b != 0, "reset on untracked allocation matches host failure");
}
}
int main() {
guest_alloc = reinterpret_cast<AllocFn>(rt::shims::find("xmem.dll", "XMemVirtualAlloc"));
guest_watch = reinterpret_cast<WatchFn>(rt::shims::find("xmem.dll", "XMemGetWriteWatch"));
guest_reset = reinterpret_cast<ResetFn>(rt::shims::find("xmem.dll", "XMemResetWriteWatch"));
check(guest_alloc && guest_watch && guest_reset, "all three new exports resolve through real shim registry");
if (!guest_alloc || !guest_watch || !guest_reset) return 1;
SYSTEM_INFO sys{}; GetSystemInfo(&sys); page_bytes = sys.dwPageSize;
std::printf("host page=%lu allocation granularity=%lu; registered PR exports\n", page_bytes, sys.dwAllocationGranularity);
const SIZE_T sizes[] = {1, 0xfff, 0x1000, 0x1001, 0xffff, 0x10000, 0x10001};
const DWORD types[] = {MEM_RESERVE, MEM_COMMIT, MEM_RESERVE | MEM_COMMIT,
MEM_RESERVE | MEM_COMMIT | MEM_TOP_DOWN, MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH};
const DWORD protections[] = {PAGE_READWRITE, PAGE_READONLY, PAGE_NOACCESS};
for (SIZE_T size : sizes) for (DWORD type : types) for (DWORD protect : protections)
compare_null_alloc(size, type, protect);
// Host rejection behavior for bad protection values is also observable without touching memory.
compare_null_alloc(0x1000, MEM_RESERVE | MEM_COMMIT, 0);
compare_null_alloc(0x1000, MEM_WRITE_WATCH, PAGE_READWRITE);
for (SIZE_T offset : {SIZE_T(1), SIZE_T(0xfff), SIZE_T(0x1001), SIZE_T(0xffff), SIZE_T(0x10001)})
for (SIZE_T size : {SIZE_T(1), SIZE_T(2), SIZE_T(0x1001)}) compare_commit(offset, size);
test_guest64k();
test_write_watch(0);
test_write_watch(guest64k);
test_rejections();
std::printf("xmem virtual review: %d scenarios, %d checks, %d failures\n", scenarios, checks, failures);
return failures ? 1 : 0;
} |
|
Tested 7c2fbe1 (merged onto main 4947579) on NVIDIA GeForce RTX 4060 Ti, driver 610.88 (32.0.16.1088), Windows 11 26200, MSVC 14.51.36231 (VS 2026), Vulkan SDK 1.4.363.0: pass
Suggestion: those checks would fit as a small AI-assisted (Claude). |
|
Added permanent synthetic coverage in commit 84f86c5: xmem_test now exercises write-watch dirty-page reporting, query-only preservation, reset/re-arm, and rejection of unsupported large pages/nonzero attributes. Built with MSVC 19.51; 35/35 checks pass. No game files or generated shader data used. AI-assisted contribution by @edupode with assistance from ChatGPT 6.2 Astra (Ultra Thinking). |
|
Tested 7c2fbe1 on Tiger Lake (Xe-LP) iGPU 0x9a78 (Intel(R) UHD Graphics, driver 32.0.101.7088), Windows 11, MSVC 14.44: pass Built the runtime test suite with MSVC 14.44 and Vulkan SDK 1.4.363.0 (RelWithDebInfo). Same coverage note as my other Intel runs here: the translated-shader GPU tests and d3d12_subgroup_test are not built on this machine (no llvm-mc with the AMDGPU target), gameinput disabled (no SDL3). Full ctest: 93/95 pass; the 2 failures are the same pre-existing The PR's own area, run separately ( AI-assisted (GLM, operated by the account owner). |
Summary
XMemVirtualAlloc,XMemGetWriteWatch, andXMemResetWriteWatchin the XMem shim.VirtualAllocwith checked range rounding.Scope
Physical-page allocation/mapping, 2 MiB alignment, write-watch suspend/resume, and nonzero XMem attributes remain unsupported. Existing
XMemAlloc/XMemFreebehavior is unchanged. The API coverage was informed by xbox-emulator's XMem virtual-memory module; this implementation is independent and copies no code.Win32 contracts: VirtualAlloc, GetWriteWatch, ResetWriteWatch.
Verification
git diff --checkpassed.AI-assisted contribution by @edupode with assistance from ChatGPT 6.2 Astra (Ultra Thinking).