xmem: physical pages, default allocators, XMemIsToolsMemAvailable; XMemVirtualAlloc takes 2 MiB pages and placeholders (#6919)

Squash-merged after diff review of PR #6919
This commit is contained in:
NiiRoZz
2026-11-23 17:40:07 +01:00
committed by GitHub
parent b2801e26e6
commit 042c5f3783
4 changed files with 723 additions and 38 deletions

View File

@ -103,6 +103,27 @@ bootstrap call it as `if (!XMemTransferMemory(XMemTransferTitleToSystem, size))`
returns `TRUE` for every direction and size and allocates nothing; with `--trace` it records each distinct direction
and size as an `xmem_transfer` event, because the enum values are not public. `xmem_test` covers it.
Seven more `xmem.dll` imports follow argument shapes measured locally at a title's call sites (the comments in
`runtime/shims/xmem.cpp` give each shape):
- `XMemAllocDefault` and `XMemFreeDefault` take `XMemAlloc`'s and `XMemFree`'s arguments and share their heap.
- `XMemAllocatePhysicalPages(attributes, UINT64* count, UINT64* pages)` returns a `BOOL` and the count it allocated.
Each call is one pagefile-backed section of `count` 64 KiB pages. A page number is a 4 KiB frame number: a
non-zero multiple of 16 below 2^25, which is what the measured title assumes when it packs them. `0` means "unmap".
- `XMemMapPhysicalPages(address, UINT64 count, pages)` returns the address. A null page array unmaps.
`XMemMapPhysicalPagesScatter(addresses, UINT32 count, pages)` returns a `BOOL`, and a `0` entry unmaps.
`XMemFreePhysicalPages(UINT64 count, pages)` returns a `BOOL`. Every page is its own view, mapped with
`MapViewOfFile3` into a 64 KiB placeholder, so a page keeps its contents across remaps and can be mapped twice.
- The windows are reserve-only 64 KiB-page `XMemVirtualAlloc` regions. The shim reserves them as placeholders and
keeps their protection, which mapped pages get (AWE's rule). The measured title also reserves a placeholder with
`MEM_RESERVE_PLACEHOLDER` and carves windows out of it with `MEM_REPLACE_PLACEHOLDER`, and the shim passes both
through. **ASSUMPTION:** nothing commits into a window with `kernel32!VirtualAlloc`, which a placeholder refuses.
- `XMemVirtualAlloc` used to refuse 2 MiB pages, and five of the 23 measured calls commit them. They are now
committed 2 MiB-aligned through `VirtualAlloc2`. The attribute word is recorded (`xmem_attributes`) and the
console's `PAGE_GRAPHICS_*` bits are dropped from the protection, as before.
- `XMemIsToolsMemAvailable()` is `FALSE`: a PC has no development-kit tools memory. The measured title asks only
on an out-of-memory path, after an allocation has already failed.
## The retail executable (RT-5)
`game_scarlett_master.exe` (120,181,760 bytes on disk, SHA-256
@ -144,6 +165,8 @@ Only two of these DLLs have a shim in the repository (`xmem.dll` and `d3d12_xs.d
they hold 8 of the 30 unimplemented imports. The other 22 are in five DLLs (`xg_xs.dll`, `XCRDAPI.dll`, `chad.dll`,
`xapu.dll`, `AcpHal.dll`) with no shim at all.
The seven `xmem.dll` imports are served now (see the `xmem.dll` notes above), so the same dry run lists 23.
`--init` on the same files also exits 0 with nothing on stderr. Its `--trace` file has 15 lines: the four package DLLs'
`DllMain(DLL_PROCESS_ATTACH)` each return 1, the executable's two TLS callbacks run at process attach (reason 1) and
again at detach (reason 0), and there is no `exception`, `error` or `unimplemented_call` event. So none of the 30

View File

@ -161,7 +161,12 @@ Current limits, by design:
measured three-argument
`XMemVirtualQuery(process, address, out)`. Allocations are 64-byte aligned; the working-set and
virtual-query outputs fill the observed 64-byte structures and return `FALSE`/`0` on a null or bad
address.
address. `XMemAllocDefault`/`XMemFreeDefault` share that heap. `XMemVirtualAlloc` accepts the attribute word,
drops the console's `PAGE_GRAPHICS_*` protection bits, commits 2 MiB guest pages 2 MiB-aligned,
and passes `MEM_RESERVE_PLACEHOLDER`/`MEM_REPLACE_PLACEHOLDER` through. Physical pages
(`XMemAllocatePhysicalPages`, `XMemFreePhysicalPages`, `XMemMapPhysicalPages`, `XMemMapPhysicalPagesScatter`) are
64 KiB pages of pagefile-backed sections, mapped one view per page into the placeholder that a reserve-only
64 KiB-page `XMemVirtualAlloc` becomes, with that reservation's protection. `XMemIsToolsMemAvailable` is `FALSE`.
- The `kernel32.dll` file API — `CreateFileA/W`, `FindFirstFileA/W`/`FindNextFileA/W`/`FindClose`,
`GetFileAttributesA/W`, `GetFileAttributesExA/W` and `DeleteFileA/W`: a `GAME:` path maps under `--game-dir`, an
open that can write and a delete go to `--overlay DIR` (default `<game-dir>\overlay`), which reads prefer, and a path
@ -351,7 +356,8 @@ from the ANSI code page.
| `tls_callback` | before each TLS callback the Loader runs (process attach and detach; thread events run under the Windows loader lock and are not traced) | `module`, `at` (module+RVA), `reason` |
| `dllmain` | after `DllMain(DLL_PROCESS_ATTACH)` returns | `module`, `result` |
| `unimplemented_call` | first call of each unimplemented import | `import` (`dll!name`), `caller` (module+RVA) |
| `xmem_attributes` | the first `XMemAlloc` and the first `XMemFree` for each distinct raw attribute word (not every allocation) | `api`, `attributes`, `size` (`XMemAlloc` only), `caller` (module+RVA) |
| `xmem_attributes` | the first `XMemAlloc`, `XMemFree`, `XMemAllocDefault`, `XMemFreeDefault` and `XMemVirtualAlloc` for each distinct raw attribute word (not every allocation) | `api`, `attributes`, `size` (not for the frees), `caller` (module+RVA) |
| `xmem_physical_pages` | the first `XMemAllocatePhysicalPages` for each distinct attribute word | `api`, `attributes`, `pages`, `caller` |
| `file_open_failed` | a guest `CreateFileW`/`CreateFile2` that fails (at most 256 events) | `api`, `path` (as the title passed it), `error` (Win32), `caller` (module+RVA) |
| `int3_skipped` | with `LEONIDA_SKIP_INT3` set: first int3 at each address, which is then stepped over | `at` (module+RVA) |
| `debug_string` | `OutputDebugStringA/W` with no debugger attached | `text` |

View File

@ -9,6 +9,10 @@
// ASSUMPTION: the attribute word is not decoded by the measured call sites (one passes 0x5e50000). Until a call
// site shows the alignment/type fields, every block is 64-byte aligned (covers cache lines and SIMD) and a size of
// zero is rounded up to one byte so the result is a stable, non-null pointer that XMemFree can release.
//
// The default allocators, the physical-page functions and XMemIsToolsMemAvailable follow argument shapes measured
// locally at a title's call sites (each function says which). The page functions are built on the Windows placeholder
// APIs (VirtualAlloc2, MapViewOfFile3), whose flags the title's own XMemVirtualAlloc calls already use.
#include <windows.h>
#include <intrin.h>
#include <malloc.h>
@ -18,11 +22,16 @@
#include <cstdint>
#include <cstdio>
#include <cstring>
#include <iterator>
#include <limits>
#include <map>
#include <memory>
#include <mutex>
#include <set>
#include <string>
#include <unordered_map>
#include <utility>
#include <vector>
#include "shims.h"
#include "startup_trace.h"
@ -32,10 +41,14 @@ namespace {
constexpr size_t kAlign = 64;
constexpr size_t kNoSize = static_cast<size_t>(-1); // XMemFree has no size field
// gta6rt --trace FILE: the first XMemAlloc, XMemFree and XMemVirtualAlloc call for each distinct raw attribute word go to the
// startup trace as an "xmem_attributes" event (api, the word, the size for an allocation, the caller as module+RVA). The
// bits of the attribute word are not known yet; this records them from a real run without logging every allocation,
// which would fill the file. Off: one relaxed load per call.
std::string caller_field(const void* caller) {
return ",\"caller\":" + rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast<uint64_t>(caller)));
}
// gta6rt --trace FILE: the first XMemAlloc, XMemFree, XMemAllocDefault, XMemFreeDefault and XMemVirtualAlloc call for
// each distinct raw attribute word go to the startup trace as an "xmem_attributes" event (api, the word, the size for an
// allocation, the caller as module+RVA). The bits of the attribute word are not known yet; this records them from a
// real run without logging every allocation, which would fill the file. Off: one relaxed load per call.
void note_attributes(const char* api, uint64_t attributes, size_t size, const void* caller) {
if (!rt::startup_trace::enabled()) return;
static std::mutex mutex;
@ -47,14 +60,15 @@ void note_attributes(const char* api, uint64_t attributes, size_t size, const vo
std::string fields = std::string("\"api\":\"") + api +
"\",\"attributes\":" + rt::startup_trace::quote(rt::startup_trace::hex(attributes));
if (size != kNoSize) fields += ",\"size\":" + std::to_string(size);
fields += ",\"caller\":" +
rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast<uint64_t>(caller)));
fields += caller_field(caller);
rt::startup_trace::event("xmem_attributes", fields);
}
void* allocate_block(size_t size) { return _aligned_malloc(size ? size : 1, kAlign); }
void* __stdcall XMemAlloc(size_t size, uint64_t attributes) {
note_attributes("XMemAlloc", attributes, size, _ReturnAddress());
return _aligned_malloc(size ? size : 1, kAlign);
return allocate_block(size);
}
void __stdcall XMemFree(void* p, uint64_t attributes) {
@ -62,6 +76,32 @@ void __stdcall XMemFree(void* p, uint64_t attributes) {
_aligned_free(p);
}
// XMemAllocDefault / XMemFreeDefault: the GDK's own allocator behind XMemAlloc and XMemFree, which a title that hooks
// XMemAlloc forwards to. The measured title reaches each through one wrapper that is a bare tail jump to the import,
// so they take exactly XMemAlloc's and XMemFree's arguments. They share the heap: a block from either allocator may be
// released by either free.
void* __stdcall XMemAllocDefault(size_t size, uint64_t attributes) {
note_attributes("XMemAllocDefault", attributes, size, _ReturnAddress());
return allocate_block(size);
}
void __stdcall XMemFreeDefault(void* p, uint64_t attributes) {
note_attributes("XMemFreeDefault", attributes, kNoSize, _ReturnAddress());
_aligned_free(p);
}
// BOOL XMemIsToolsMemAvailable(void). The measured title calls it from one helper, which six out-of-memory paths reach
// only after an allocation has failed; the helper breaks into the debugger when the result is zero. Tools memory is
// the extra memory of a development kit. A PC has none, so the answer is FALSE, and the title's own breakpoint marks
// where it ran out of memory.
BOOL WINAPI XMemIsToolsMemAvailable() {
static std::atomic<bool> warned{false};
if (!warned.exchange(true, std::memory_order_relaxed)) {
std::fprintf(stderr, "[rt] xmem: XMemIsToolsMemAvailable -> FALSE (no devkit tools memory; logged once)\n");
}
return FALSE;
}
// Measured call sites pass a zeroed 64-byte structure. Only the MEMORY_BASIC_INFORMATION-compatible prefix is
// known: callers read at least the base and size fields. Fill that prefix from VirtualQueryEx and zero the rest.
constexpr size_t kVirtualQueryOutSize = 64;
@ -127,13 +167,43 @@ BOOL __stdcall XMemGetWorkingSetStatistics(uint32_t /*kind*/, void* stats) {
return TRUE;
}
// The placeholder APIs (Windows 10 1803 and later) come from kernelbase.dll at run time, so neither gta6rt nor the
// tests link onecore.lib. A host without them fails the calls that need them with ERROR_NOT_SUPPORTED.
using VirtualAlloc2Fn = PVOID(WINAPI*)(HANDLE, PVOID, SIZE_T, ULONG, ULONG, MEM_EXTENDED_PARAMETER*, ULONG);
using MapViewOfFile3Fn = PVOID(WINAPI*)(HANDLE, HANDLE, PVOID, ULONG64, SIZE_T, ULONG, ULONG, MEM_EXTENDED_PARAMETER*,
ULONG);
using UnmapViewOfFile2Fn = BOOL(WINAPI*)(HANDLE, PVOID, ULONG);
struct PlaceholderApi {
VirtualAlloc2Fn virtual_alloc2 = nullptr;
MapViewOfFile3Fn map_view3 = nullptr;
UnmapViewOfFile2Fn unmap_view2 = nullptr;
bool available() const { return virtual_alloc2 && map_view3 && unmap_view2; }
};
const PlaceholderApi& placeholder_api() {
static const PlaceholderApi api = [] {
PlaceholderApi resolved;
if (const HMODULE kernelbase = GetModuleHandleW(L"kernelbase.dll")) {
resolved.virtual_alloc2 = reinterpret_cast<VirtualAlloc2Fn>(GetProcAddress(kernelbase, "VirtualAlloc2"));
resolved.map_view3 = reinterpret_cast<MapViewOfFile3Fn>(GetProcAddress(kernelbase, "MapViewOfFile3"));
resolved.unmap_view2 =
reinterpret_cast<UnmapViewOfFile2Fn>(GetProcAddress(kernelbase, "UnmapViewOfFile2"));
}
return resolved;
}();
return api;
}
// XMem allocation-type page bits select the guest page granularity and must not be forwarded as Win32 flags.
constexpr DWORD kXmemLargePages = 0x20000000;
constexpr DWORD kXmem64kPages = 0x20400000;
constexpr DWORD kXmemLargePages = 0x20000000; // 2 MiB pages
constexpr DWORD kXmem64kPages = 0x20400000; // 64 KiB pages
constexpr DWORD kXmemPageModeMask = kXmem64kPages;
constexpr SIZE_T kXmemPageSize64k = 0x10000;
constexpr DWORD kXmemHostAllocationTypeMask =
MEM_COMMIT | MEM_RESERVE | MEM_RESET | MEM_TOP_DOWN | MEM_WRITE_WATCH | 0x01000000;
constexpr SIZE_T kXmemPageSize2m = 0x200000;
constexpr DWORD kXmemHostAllocationTypeMask = MEM_COMMIT | MEM_RESERVE | MEM_REPLACE_PLACEHOLDER |
MEM_RESERVE_PLACEHOLDER | MEM_RESET | MEM_TOP_DOWN | MEM_WRITE_WATCH |
MEM_RESET_UNDO;
bool round_up_size(SIZE_T value, SIZE_T alignment, SIZE_T& rounded) {
const SIZE_T max = (std::numeric_limits<SIZE_T>::max)();
@ -152,14 +222,105 @@ DWORD host_protect(DWORD p) {
return cpu ? cpu : PAGE_NOACCESS;
}
// Physical pages and the windows they are mapped into. One mutex covers both tables and every map and unmap.
//
// A physical-page window is a reserve-only XMemVirtualAlloc in a guest page mode, or a reserve-only replacement of
// part of a placeholder. On the host it is a placeholder, the only kind of reservation a section view can later
// replace, and its protection is kept here: the map calls take none, so a mapped page gets its window's protection, as
// AWE's MapUserPhysicalPages does.
//
// ASSUMPTION: a title does not commit memory inside such a window with kernel32!VirtualAlloc. A placeholder refuses a
// plain commit; the measured windows are only ever passed to the map calls.
struct Window {
SIZE_T size;
DWORD protect;
};
struct Section {
HANDLE handle;
explicit Section(HANDLE h) : handle(h) {}
Section(const Section&) = delete;
Section& operator=(const Section&) = delete;
~Section() { CloseHandle(handle); }
};
struct PhysicalPage {
std::shared_ptr<Section> section; // a mapped view holds its own reference to the section
uint64_t offset;
};
constexpr uint64_t kPhysicalPageSize = 0x10000;
// Page numbers are 4 KiB frame numbers of 64 KiB pages: the measured title stores them packed and assumes each is a
// non-zero multiple of 16 below 2^25, with 0 for an entry it unmaps. So a page number is slot * 16 with slot in
// [1, 2^21), and freed slots are reused so a long run never runs out.
constexpr uint64_t kFramesPerPage = kPhysicalPageSize / 0x1000;
constexpr uint64_t kPageSlotLimit = uint64_t{1} << 21;
std::mutex g_phys_mutex;
std::map<uintptr_t, Window> g_windows; // base -> window
std::unordered_map<uint64_t, PhysicalPage> g_pages; // page number -> backing
std::vector<uint64_t> g_free_slots;
uint64_t g_next_slot = 1;
std::unordered_map<uintptr_t, uint64_t> g_mapped; // mapped 64 KiB address -> page number
// With g_phys_mutex held. A window replaces every window it overlaps: the title released those regions (with
// kernel32!VirtualFree, which the shim does not see) before the host could hand the addresses out again.
void record_window(void* base, SIZE_T size, DWORD protect) {
const uintptr_t start = reinterpret_cast<uintptr_t>(base);
const uintptr_t end = start + size;
auto it = g_windows.lower_bound(start);
if (it != g_windows.begin()) {
const auto prev = std::prev(it);
if (prev->first + prev->second.size > start) it = prev;
}
while (it != g_windows.end() && it->first < end) it = g_windows.erase(it);
g_windows[start] = Window{size, protect};
}
// With g_phys_mutex held: the window holding [address, address + bytes), if one does.
const Window* find_window(uintptr_t address, uint64_t bytes) {
auto it = g_windows.upper_bound(address);
if (it == g_windows.begin()) return nullptr;
--it;
const uint64_t offset = address - it->first;
if (offset >= it->second.size || bytes > it->second.size - offset) return nullptr;
return &it->second;
}
// [address, address + size) as one placeholder of its own: split it out of the placeholder that holds it. Fails when
// the range is not inside one placeholder.
bool isolate_placeholder(void* address, SIZE_T size) {
MEMORY_BASIC_INFORMATION info{};
if (!VirtualQuery(address, &info, sizeof(info)) || info.State != MEM_RESERVE) {
SetLastError(ERROR_INVALID_ADDRESS);
return false;
}
if (info.AllocationBase == address && info.RegionSize == size) return true;
return VirtualFree(address, size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER) != FALSE;
}
PVOID reserve_placeholder(void* address, SIZE_T size, SIZE_T alignment) {
MEM_ADDRESS_REQUIREMENTS requirements{};
MEM_EXTENDED_PARAMETER parameter{};
ULONG parameter_count = 0;
if (!address && alignment > kXmemPageSize64k) {
requirements.Alignment = alignment;
parameter.Type = MemExtendedParameterAddressRequirements;
parameter.Pointer = &requirements;
parameter_count = 1;
}
return placeholder_api().virtual_alloc2(GetCurrentProcess(), address, size, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
PAGE_NOACCESS, parameter_count ? &parameter : nullptr, parameter_count);
}
// PVOID XMemVirtualAlloc(address, size, allocationType, attributes, protect). All 23 calls of the measured title pass a
// nonzero attribute word; its bits are not decoded and nothing on the host depends on them, so it is accepted and only
// recorded (xmem_attributes). Its types cover committed 2 MiB and 64 KiB pages, reserve-only 64 KiB windows for physical pages, one
// MEM_RESERVE_PLACEHOLDER reservation and five MEM_REPLACE_PLACEHOLDER windows carved out of it, each then filled with
// XMemMapPhysicalPages. The guest page size sets the alignment and rounding of the region; the host's own pages stay
// 4 KiB (host large pages need SeLockMemoryPrivilege). A 2 MiB region the host places is reserved 2 MiB-aligned through
// VirtualAlloc2.
void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect) {
// Host-backed support covers ordinary and 64 KiB guest reservations. The 2 MiB guest mode needs an aligned
// reservation strategy that this shim does not provide, so fail explicitly instead of returning a misaligned
// region.
//
// The attribute word is recorded, not applied, as for XMemAlloc: the host has no allocator ids or memory types.
// The retail executable passes 0x21, 0x3, 0x183, 0x283 and 0x181 and stops at an int3 when a reservation
// returns NULL, so refusing a nonzero word is not an option.
note_attributes("XMemVirtualAlloc", attributes, size, _ReturnAddress());
if (size == 0) {
SetLastError(ERROR_INVALID_PARAMETER);
@ -167,11 +328,7 @@ void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type,
}
const DWORD page_mode = allocation_type & kXmemPageModeMask;
if (page_mode == kXmemLargePages) {
SetLastError(ERROR_NOT_SUPPORTED);
return nullptr;
}
if (page_mode != 0 && page_mode != kXmem64kPages) {
if (page_mode != 0 && page_mode != kXmem64kPages && page_mode != kXmemLargePages) {
SetLastError(ERROR_INVALID_PARAMETER);
return nullptr;
}
@ -184,14 +341,28 @@ void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type,
DWORD host_type = allocation_type & kXmemHostAllocationTypeMask;
if (host_type == 0) host_type = MEM_RESERVE | MEM_COMMIT;
const DWORD host_prot = host_protect(protect);
const bool commit = (host_type & MEM_COMMIT) != 0;
const bool new_placeholder = (host_type & MEM_RESERVE_PLACEHOLDER) != 0;
const bool replace = (host_type & MEM_REPLACE_PLACEHOLDER) != 0;
const bool window = page_mode != 0 && !commit && !new_placeholder;
if ((new_placeholder || replace || window || page_mode == kXmemLargePages) && !placeholder_api().available()) {
SetLastError(ERROR_NOT_SUPPORTED);
return nullptr;
}
SYSTEM_INFO system_info{};
GetSystemInfo(&system_info);
const SIZE_T page_granularity = page_mode == kXmem64kPages ? kXmemPageSize64k : system_info.dwPageSize;
const SIZE_T base_granularity =
page_mode == kXmem64kPages
? kXmemPageSize64k
: ((host_type & MEM_RESERVE) ? system_info.dwAllocationGranularity : system_info.dwPageSize);
SIZE_T page_granularity = system_info.dwPageSize;
SIZE_T base_granularity = (host_type & MEM_RESERVE) ? system_info.dwAllocationGranularity : system_info.dwPageSize;
if (page_mode == kXmem64kPages) page_granularity = base_granularity = kXmemPageSize64k;
if (page_mode == kXmemLargePages) page_granularity = base_granularity = kXmemPageSize2m;
if (new_placeholder || replace) {
// Placeholders are split and replaced on allocation-granularity boundaries only.
if (page_granularity < system_info.dwAllocationGranularity) page_granularity = system_info.dwAllocationGranularity;
if (base_granularity < system_info.dwAllocationGranularity) base_granularity = system_info.dwAllocationGranularity;
}
if (page_granularity == 0 || (page_granularity & (page_granularity - 1)) != 0 || base_granularity == 0 ||
(base_granularity & (base_granularity - 1)) != 0) {
SetLastError(ERROR_INVALID_PARAMETER);
@ -215,12 +386,241 @@ void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type,
~(static_cast<uintptr_t>(page_granularity) - 1);
address = reinterpret_cast<void*>(base);
size = static_cast<SIZE_T>(end - base);
} else if (page_mode == kXmem64kPages && !round_up_size(size, page_granularity, size)) {
} else if (replace) {
SetLastError(ERROR_INVALID_PARAMETER); // a replacement names the placeholder it replaces
return nullptr;
} else if (page_granularity > system_info.dwPageSize && !round_up_size(size, page_granularity, size)) {
SetLastError(ERROR_INVALID_PARAMETER);
return nullptr;
}
return VirtualAlloc(address, size, host_type, host_protect(protect));
if (replace) {
const std::lock_guard lock(g_phys_mutex);
if (!isolate_placeholder(address, size)) return nullptr;
if (window) {
// A reserve-only replacement stays a placeholder: the physical pages are mapped into it.
record_window(address, size, host_prot);
return address;
}
return placeholder_api().virtual_alloc2(GetCurrentProcess(), address, size, host_type | MEM_RESERVE, host_prot,
nullptr, 0);
}
if (new_placeholder || window) {
void* const result = reserve_placeholder(address, size, base_granularity);
if (result && window) {
const std::lock_guard lock(g_phys_mutex);
record_window(result, size, host_prot);
}
return result;
}
if (page_mode == kXmemLargePages && address == nullptr) {
MEM_ADDRESS_REQUIREMENTS requirements{};
requirements.Alignment = kXmemPageSize2m;
MEM_EXTENDED_PARAMETER parameter{};
parameter.Type = MemExtendedParameterAddressRequirements;
parameter.Pointer = &requirements;
return placeholder_api().virtual_alloc2(GetCurrentProcess(), nullptr, size, host_type | MEM_RESERVE, host_prot,
&parameter, 1);
}
return VirtualAlloc(address, size, host_type, host_prot);
}
// With g_phys_mutex held. Unmaps the page at `address` if one is mapped there; the address becomes a placeholder again.
bool unmap_page(uintptr_t address) {
const auto it = g_mapped.find(address);
if (it == g_mapped.end()) return true;
if (!placeholder_api().unmap_view2(GetCurrentProcess(), reinterpret_cast<void*>(address),
MEM_PRESERVE_PLACEHOLDER)) {
return false;
}
g_mapped.erase(it);
return true;
}
// With g_phys_mutex held. Maps physical page `page` (0: unmap) at the 64 KiB-aligned `address`, replacing what was
// mapped there. The caller has found the window.
bool map_page(uintptr_t address, uint64_t page, DWORD protect) {
if (!unmap_page(address)) return false;
if (page == 0) return true;
const auto it = g_pages.find(page);
if (it == g_pages.end()) {
SetLastError(ERROR_INVALID_PARAMETER);
return false;
}
void* const target = reinterpret_cast<void*>(address);
if (!isolate_placeholder(target, kPhysicalPageSize)) return false;
void* const view = placeholder_api().map_view3(it->second.section->handle, GetCurrentProcess(), target,
it->second.offset, kPhysicalPageSize, MEM_REPLACE_PLACEHOLDER,
protect, nullptr, 0);
if (!view) return false;
g_mapped[address] = page;
return true;
}
// Two of the measured windows are reserved PAGE_NOACCESS for the CPU and the GPU alike; pages mapped there are still
// GPU memory, which the D3D12 layer reads on the CPU.
DWORD view_protect(const Window& window) {
return window.protect == PAGE_NOACCESS ? PAGE_READWRITE : window.protect;
}
bool aligned_page_address(uintptr_t address) { return (address & (kPhysicalPageSize - 1)) == 0; }
// gta6rt --trace FILE: the first XMemAllocatePhysicalPages for each distinct attribute word goes to the startup trace
// as an "xmem_physical_pages" event with the page count and the caller.
void note_physical_attributes(uint64_t attributes, uint64_t count, const void* caller) {
if (!rt::startup_trace::enabled()) return;
static std::mutex mutex;
static std::set<uint64_t> seen;
{
const std::lock_guard lock(mutex);
if (!seen.insert(attributes).second) return;
}
rt::startup_trace::event("xmem_physical_pages",
"\"api\":\"XMemAllocatePhysicalPages\",\"attributes\":" +
rt::startup_trace::quote(rt::startup_trace::hex(attributes)) +
",\"pages\":" + std::to_string(count) + caller_field(caller));
}
// BOOL XMemAllocatePhysicalPages(attributes, UINT64* pageCount, UINT64* pageArray). Measured at four call sites: RCX is
// a constant attribute word, RDX points at the number of 64 KiB pages (every caller computes it as the byte size
// rounded up and shifted right by 16), R8 at an array that receives one page number per page. The result is tested as
// a 32-bit BOOL. After success every caller compares the count with the one it asked for and frees the pages if they
// differ, so the count is in/out.
//
// Each call is backed by one pagefile-backed section of count * 64 KiB: committed (charged) at once, given physical
// memory as it is touched, zero-filled. Pages keep their contents while unmapped or mapped elsewhere, and one page can
// be mapped at several addresses. ASSUMPTION: the attribute word (memory type, perhaps the page size) is not decoded;
// every page is 64 KiB, which all four callers' arithmetic agrees with.
BOOL WINAPI XMemAllocatePhysicalPages(uint64_t attributes, uint64_t* page_count, uint64_t* page_array) {
note_physical_attributes(attributes, page_count ? *page_count : 0, _ReturnAddress());
if (!page_count || (*page_count && !page_array)) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
const uint64_t count = *page_count;
if (count == 0) return TRUE;
const std::lock_guard lock(g_phys_mutex);
if (count > g_free_slots.size() + (kPageSlotLimit - g_next_slot)) {
*page_count = 0;
SetLastError(ERROR_NOT_ENOUGH_MEMORY);
return FALSE;
}
const uint64_t bytes = count * kPhysicalPageSize; // below 2^37: count is below 2^21
const HANDLE handle = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_COMMIT,
static_cast<DWORD>(bytes >> 32), static_cast<DWORD>(bytes), nullptr);
if (!handle) {
*page_count = 0;
return FALSE;
}
const auto section = std::make_shared<Section>(handle);
for (uint64_t i = 0; i < count; ++i) {
uint64_t slot;
if (!g_free_slots.empty()) {
slot = g_free_slots.back();
g_free_slots.pop_back();
} else {
slot = g_next_slot++;
}
const uint64_t page = slot * kFramesPerPage;
g_pages[page] = PhysicalPage{section, i * kPhysicalPageSize};
page_array[i] = page;
}
return TRUE;
}
// BOOL XMemFreePhysicalPages(UINT64 pageCount, UINT64* pageArray). Measured at three call sites: RCX is the count (the
// one XMemAllocatePhysicalPages returned, or the sum of several allocations), RDX the array. The callers unmap the
// pages first; a page that is still mapped keeps its memory until it is unmapped. FALSE, with the entries before it
// freed, for a number that is not a live page.
BOOL WINAPI XMemFreePhysicalPages(uint64_t page_count, const uint64_t* page_array) {
if (page_count && !page_array) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
const std::lock_guard lock(g_phys_mutex);
for (uint64_t i = 0; i < page_count; ++i) {
const auto it = g_pages.find(page_array[i]);
if (it == g_pages.end()) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
g_pages.erase(it);
g_free_slots.push_back(page_array[i] / kFramesPerPage);
}
return TRUE;
}
// PVOID XMemMapPhysicalPages(PVOID address, UINT64 pageCount, UINT64* pageArray). Measured at twelve call sites: RCX
// is an address in a window XMemVirtualAlloc reserved, RDX a 64-bit count, R8 the pages to map there one after another,
// or null to unmap that many (four calls at shutdown). Callers test the 64-bit result for zero, so it is the address on
// success. A page number of 0 in the array unmaps that one page.
//
// Each page is its own view (MapViewOfFile3 into a 64 KiB placeholder), so any page can be remapped or unmapped later
// without touching its neighbours. A failure part-way leaves the pages before it mapped.
void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint64_t* page_array) {
const uintptr_t start = reinterpret_cast<uintptr_t>(address);
if (!aligned_page_address(start) || page_count > (std::numeric_limits<uintptr_t>::max)() / kPhysicalPageSize ||
start > (std::numeric_limits<uintptr_t>::max)() - page_count * kPhysicalPageSize) {
SetLastError(ERROR_INVALID_PARAMETER);
return nullptr;
}
if (!placeholder_api().available()) {
SetLastError(ERROR_NOT_SUPPORTED);
return nullptr;
}
const std::lock_guard lock(g_phys_mutex);
if (!page_array) {
for (uint64_t i = 0; i < page_count; ++i) {
if (!unmap_page(start + i * kPhysicalPageSize)) return nullptr;
}
return address;
}
const Window* const window = find_window(start, page_count * kPhysicalPageSize);
if (!window) {
SetLastError(ERROR_INVALID_ADDRESS);
return nullptr;
}
const DWORD protect = view_protect(*window);
for (uint64_t i = 0; i < page_count; ++i) {
if (!map_page(start + i * kPhysicalPageSize, page_array[i], protect)) return nullptr;
}
return address;
}
// BOOL XMemMapPhysicalPagesScatter(PVOID* addresses, UINT32 pageCount, UINT64* pageArray). Measured at two call sites:
// RCX is an array of addresses, EDX a 32-bit count, R8 the page for each address (an entry of 0, or a null array,
// unmaps). The result is tested as a 32-bit BOOL. Like MapUserPhysicalPagesScatter: entry i maps pageArray[i] at
// addresses[i].
BOOL WINAPI XMemMapPhysicalPagesScatter(void* const* addresses, uint32_t page_count, const uint64_t* page_array) {
if (page_count && !addresses) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
if (!placeholder_api().available()) {
SetLastError(ERROR_NOT_SUPPORTED);
return FALSE;
}
const std::lock_guard lock(g_phys_mutex);
for (uint32_t i = 0; i < page_count; ++i) {
const uintptr_t address = reinterpret_cast<uintptr_t>(addresses[i]);
if (!aligned_page_address(address)) {
SetLastError(ERROR_INVALID_PARAMETER);
return FALSE;
}
const uint64_t page = page_array ? page_array[i] : 0;
if (page == 0) {
if (!unmap_page(address)) return FALSE;
continue;
}
const Window* const window = find_window(address, kPhysicalPageSize);
if (!window) {
SetLastError(ERROR_INVALID_ADDRESS);
return FALSE;
}
if (!map_page(address, page, view_protect(*window))) return FALSE;
}
return TRUE;
}
UINT WINAPI XMemGetWriteWatch(DWORD flags, void* base_address, SIZE_T region_size, void** addresses, ULONG_PTR* count,
@ -318,4 +718,11 @@ SHIM_TABLE(xmem,
{"xmem.dll", "XMemGetWriteWatch", reinterpret_cast<void*>(&XMemGetWriteWatch)},
{"xmem.dll", "XMemResetWriteWatch", reinterpret_cast<void*>(&XMemResetWriteWatch)},
{"xmem.dll", "XMemTransferMemory", reinterpret_cast<void*>(&XMemTransferMemory)},
{"xmem.dll", "XMemAllocDefault", reinterpret_cast<void*>(&XMemAllocDefault)},
{"xmem.dll", "XMemFreeDefault", reinterpret_cast<void*>(&XMemFreeDefault)},
{"xmem.dll", "XMemIsToolsMemAvailable", reinterpret_cast<void*>(&XMemIsToolsMemAvailable)},
{"xmem.dll", "XMemAllocatePhysicalPages", reinterpret_cast<void*>(&XMemAllocatePhysicalPages)},
{"xmem.dll", "XMemFreePhysicalPages", reinterpret_cast<void*>(&XMemFreePhysicalPages)},
{"xmem.dll", "XMemMapPhysicalPages", reinterpret_cast<void*>(&XMemMapPhysicalPages)},
{"xmem.dll", "XMemMapPhysicalPagesScatter", reinterpret_cast<void*>(&XMemMapPhysicalPagesScatter)},
);

View File

@ -5,7 +5,9 @@
// cover what the measured call sites use: 64-byte-aligned allocations, XMemFree, working-set statistics with the
// size at +8, and XMemVirtualQuery's MEMORY_BASIC_INFORMATION prefix inside a zeroed 64-byte output.
// XMemTransferMemory follows the call shape in Microsoft's public samples: TRUE for any direction and size, with
// nothing committed, and one trace event per distinct (type, size).
// nothing committed, and one trace event per distinct (type, size). XMemVirtualAlloc accepts attribute words and console
// graphics protection bits and commits 2 MiB guest pages; the placeholder flags pass through; physical pages keep their
// contents across unmap and remap, alias when mapped twice, and scatter-map per address.
#include <windows.h>
#include <psapi.h>
@ -33,7 +35,17 @@ using XMemResetWriteWatchFn = UINT(WINAPI*)(void*, SIZE_T);
// BOOL XMemTransferMemory(XMEM_TRANSFER_TYPE, SIZE_T): the shape Microsoft's public NetRumble and NativeAOT-Xbox
// samples call (see runtime/shims/xmem.cpp).
using XMemTransferMemoryFn = BOOL(WINAPI*)(uint32_t, SIZE_T);
// The shapes measured at a title's call sites (see runtime/shims/xmem.cpp).
using XMemIsToolsMemAvailableFn = BOOL(WINAPI*)();
using XMemAllocatePhysicalPagesFn = BOOL(WINAPI*)(uint64_t, uint64_t*, uint64_t*);
using XMemFreePhysicalPagesFn = BOOL(WINAPI*)(uint64_t, const uint64_t*);
using XMemMapPhysicalPagesFn = void*(WINAPI*)(void*, uint64_t, const uint64_t*);
using XMemMapPhysicalPagesScatterFn = BOOL(WINAPI*)(void* const*, uint32_t, const uint64_t*);
constexpr uint32_t kMeasuredKind = 0x20000001;
constexpr DWORD kXmemLargePages = 0x20000000;
constexpr DWORD kXmem64kPages = 0x20400000;
constexpr SIZE_T kPage64k = 0x10000;
constexpr SIZE_T kPage2m = 0x200000;
int g_checks = 0;
int g_failures = 0;
@ -218,11 +230,33 @@ void test_virtual_alloc(XMemVirtualAllocFn virtual_alloc, XMemGetWriteWatchFn ge
check(VirtualFree(base, 0, MEM_RELEASE), "release the synthetic write-watch region");
SetLastError(ERROR_SUCCESS);
void* const large_page = virtual_alloc(nullptr, page_size, MEM_RESERVE | MEM_COMMIT | 0x20000000, 0,
PAGE_READWRITE);
check(large_page == nullptr && GetLastError() == ERROR_NOT_SUPPORTED,
"unsupported large-page allocation is rejected before host allocation");
// 2 MiB guest pages: the region is 2 MiB-aligned, rounded up to whole 2 MiB pages and committed.
void* const large_page = virtual_alloc(nullptr, kPage2m + page_size, MEM_RESERVE | MEM_COMMIT | kXmemLargePages,
0x183, PAGE_READWRITE | PAGE_GRAPHICS_READWRITE | PAGE_GRAPHICS_COHERENT);
check(large_page != nullptr, "XMemVirtualAlloc commits 2 MiB guest pages");
if (large_page) {
check((reinterpret_cast<uintptr_t>(large_page) & (kPage2m - 1)) == 0, "a 2 MiB-page region is 2 MiB-aligned");
MEMORY_BASIC_INFORMATION info{};
VirtualQuery(large_page, &info, sizeof(info));
check(info.State == MEM_COMMIT && info.RegionSize >= 2 * kPage2m && info.Protect == PAGE_READWRITE,
"a 2 MiB-page region is rounded up to whole pages, committed read-write without the graphics bits");
static_cast<volatile uint8_t*>(large_page)[2 * kPage2m - 1] = 0x77;
check(VirtualFree(large_page, 0, MEM_RELEASE), "release the 2 MiB-page region");
}
// The attribute word is accepted (every measured call passes a nonzero one) and the protection loses its graphics
// bits, in the 64 KiB page mode as well.
void* const attributed = virtual_alloc(nullptr, kPage64k, MEM_RESERVE | MEM_COMMIT | kXmem64kPages, 0x181,
PAGE_READWRITE | PAGE_GRAPHICS_READWRITE);
check(attributed != nullptr, "XMemVirtualAlloc accepts a nonzero attribute word and console protection bits");
if (attributed) {
MEMORY_BASIC_INFORMATION info{};
VirtualQuery(attributed, &info, sizeof(info));
check(info.State == MEM_COMMIT && info.Protect == PAGE_READWRITE,
"the region is committed PAGE_READWRITE (graphics bits dropped)");
static_cast<volatile uint8_t*>(attributed)[0] = 0x42;
check(VirtualFree(attributed, 0, MEM_RELEASE), "release the attributed region");
}
// The retail executable's GPU pools: the attribute word is recorded, and the PAGE_GRAPHICS_* bits are dropped.
MEMORY_BASIC_INFORMATION mbi{};
@ -249,6 +283,195 @@ void test_virtual_alloc(XMemVirtualAllocFn virtual_alloc, XMemGetWriteWatchFn ge
check(static_cast<volatile uint8_t*>(gpu)[0] == 0x5a, "the 0x183 allocation is writable");
check(VirtualFree(gpu, 0, MEM_RELEASE), "release the 0x183 allocation");
}
SetLastError(ERROR_SUCCESS);
void* const replace_without_address =
virtual_alloc(nullptr, kPage64k, MEM_RESERVE | MEM_REPLACE_PLACEHOLDER | kXmem64kPages, 0, PAGE_READWRITE);
check(replace_without_address == nullptr && GetLastError() == ERROR_INVALID_PARAMETER,
"MEM_REPLACE_PLACEHOLDER without an address is rejected");
}
// XMemAllocDefault / XMemFreeDefault share XMemAlloc's heap: a block from either is freed by either.
void test_default_alloc(XMemAllocFn alloc, XMemFreeFn free_mem, XMemAllocFn alloc_default,
XMemFreeFn free_default) {
void* const a = alloc_default(100, 0x5e50000);
check(aligned_64(a), "XMemAllocDefault returns a 64-byte aligned block");
void* const zero = alloc_default(0, 0);
check(zero != nullptr, "XMemAllocDefault(0) returns non-null");
void* const b = alloc(100, 0);
if (a) std::memset(a, 0x11, 100);
if (b) std::memset(b, 0x22, 100);
free_mem(a, 0x5e50000);
free_default(b, 0);
free_default(zero, 0);
check(true, "XMemFree releases an XMemAllocDefault block and XMemFreeDefault an XMemAlloc block");
}
uint32_t read_u32(const void* base, size_t offset) {
uint32_t value = 0;
std::memcpy(&value, static_cast<const uint8_t*>(base) + offset, sizeof(value));
return value;
}
void fill_page(void* page, uint32_t tag) {
auto* words = static_cast<uint32_t*>(page);
for (size_t i = 0; i < kPage64k / sizeof(uint32_t); i += 1024) words[i] = tag + static_cast<uint32_t>(i);
}
bool page_holds(const void* page, uint32_t tag) {
for (size_t i = 0; i < kPage64k / sizeof(uint32_t); i += 1024) {
if (read_u32(page, i * sizeof(uint32_t)) != tag + static_cast<uint32_t>(i)) return false;
}
return true;
}
bool reserved_only(const void* address) {
MEMORY_BASIC_INFORMATION info{};
return VirtualQuery(address, &info, sizeof(info)) && info.State == MEM_RESERVE;
}
struct PhysicalApi {
XMemVirtualAllocFn virtual_alloc;
XMemAllocatePhysicalPagesFn allocate;
XMemFreePhysicalPagesFn free_pages;
XMemMapPhysicalPagesFn map;
XMemMapPhysicalPagesScatterFn scatter;
};
// Physical pages in a 64 KiB-page window, as the measured callers use them: reserve a window, allocate pages, map them,
// remap them elsewhere and in another order, unmap, free.
void test_physical_pages(const PhysicalApi& api) {
constexpr uint64_t kPages = 4;
auto* const window = static_cast<uint8_t*>(api.virtual_alloc(
nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE | PAGE_GRAPHICS_READWRITE));
check(window != nullptr, "XMemVirtualAlloc reserves a 64 KiB-page window");
auto* const second = static_cast<uint8_t*>(api.virtual_alloc(
nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x21, PAGE_READWRITE));
check(second != nullptr, "XMemVirtualAlloc reserves a second window");
if (!window || !second) return;
check(reserved_only(window), "the window is reserved, not committed");
uint64_t pages[kPages]{};
uint64_t count = kPages;
check(api.allocate(0x280, &count, pages) == TRUE && count == kPages,
"XMemAllocatePhysicalPages allocates every page asked for and keeps the count");
bool numbers_ok = true;
for (uint64_t i = 0; i < kPages; ++i) {
numbers_ok &= pages[i] != 0 && pages[i] % 16 == 0 && pages[i] < (uint64_t{1} << 25);
for (uint64_t j = 0; j < i; ++j) numbers_ok &= pages[i] != pages[j];
}
check(numbers_ok, "page numbers are distinct non-zero multiples of 16 below 2^25");
check(api.map(window, kPages, pages) == window, "XMemMapPhysicalPages returns the address it mapped");
for (uint64_t i = 0; i < kPages; ++i) fill_page(window + i * kPage64k, 0x1000u * static_cast<uint32_t>(i + 1));
{
MEMORY_BASIC_INFORMATION info{};
VirtualQuery(window, &info, sizeof(info));
check(info.State == MEM_COMMIT && info.Type == MEM_MAPPED && info.Protect == PAGE_READWRITE,
"a mapped page is a read-write view with the window's protection");
}
check(api.map(window, kPages, nullptr) == window, "XMemMapPhysicalPages with no page array unmaps");
check(reserved_only(window) && reserved_only(window + 3 * kPage64k), "unmapped pages are reserved again");
// Remap in reverse order into the other window: each page keeps its contents.
uint64_t reversed[kPages];
for (uint64_t i = 0; i < kPages; ++i) reversed[i] = pages[kPages - 1 - i];
check(api.map(second, kPages, reversed) == second, "the pages map into another window");
bool kept = true;
for (uint64_t i = 0; i < kPages; ++i) {
kept &= page_holds(second + i * kPage64k, 0x1000u * static_cast<uint32_t>(kPages - i));
}
check(kept, "a physical page keeps its contents across unmap and remap");
// One page mapped at two addresses is one memory.
check(api.map(window, 1, &pages[0]) == window, "a page already mapped elsewhere maps again");
static_cast<volatile uint32_t*>(static_cast<void*>(window))[1] = 0xfeedf00d;
check(read_u32(second + 3 * kPage64k, 4) == 0xfeedf00d, "both mappings of a page see the same memory");
// Mapping over a mapped page replaces it; a 0 entry unmaps one page.
const uint64_t replace[2] = {pages[1], 0};
check(api.map(window, 2, replace) == window, "mapping over mapped pages replaces them");
check(page_holds(window, 0x2000u) && reserved_only(window + kPage64k),
"the first page now shows page 1 and a 0 entry left the second unmapped");
// Scatter: entry i maps page i at address i, out of order; 0 unmaps.
void* const addresses[3] = {window + 3 * kPage64k, window + 2 * kPage64k, window};
const uint64_t scattered[3] = {pages[2], pages[3], 0};
check(api.scatter(addresses, 3, scattered) == TRUE, "XMemMapPhysicalPagesScatter maps each page at its address");
check(page_holds(window + 3 * kPage64k, 0x3000u) && page_holds(window + 2 * kPage64k, 0x4000u) &&
reserved_only(window),
"scattered pages land at their own addresses and a 0 entry unmaps");
check(api.scatter(addresses, 3, nullptr) == TRUE && reserved_only(window + 3 * kPage64k),
"XMemMapPhysicalPagesScatter with no page array unmaps");
uint8_t outside = 0;
SetLastError(ERROR_SUCCESS);
check(api.map(reinterpret_cast<void*>((reinterpret_cast<uintptr_t>(&outside) + 0xffff) & ~uintptr_t{0xffff}), 1,
pages) == nullptr,
"mapping outside any window fails");
check(api.map(window + 1, 1, pages) == nullptr && GetLastError() == ERROR_INVALID_PARAMETER,
"mapping at an address that is not 64 KiB-aligned fails");
const uint64_t bogus = 0x1fffff0; // the highest page number, far above the few this test allocates
check(api.map(window, 1, &bogus) == nullptr, "mapping a page number that was never allocated fails");
check(api.map(second, kPages, nullptr) == second, "unmap the second window");
check(api.free_pages(kPages, pages) == TRUE, "XMemFreePhysicalPages frees the pages");
check(api.free_pages(1, pages) == FALSE, "freeing a page twice fails");
// Freed numbers are reused.
uint64_t again[kPages]{};
count = kPages;
check(api.allocate(0x180, &count, again) == TRUE && count == kPages, "pages can be allocated again");
bool reused = true;
for (uint64_t i = 0; i < kPages; ++i) {
bool found = false;
for (uint64_t j = 0; j < kPages; ++j) found |= again[i] == pages[j];
reused &= found;
}
check(reused, "freed page numbers are reused");
check(api.map(window, 1, again) == window && read_u32(window, 0) == 0, "a fresh page maps and reads as zero");
api.map(window, 1, nullptr);
api.free_pages(kPages, again);
uint64_t zero_count = 0;
check(api.allocate(0x280, &zero_count, nullptr) == TRUE, "allocating zero pages succeeds");
check(api.allocate(0x280, nullptr, pages) == FALSE, "a null count fails");
// The windows were split into one placeholder per page; the process exit releases them.
}
// The placeholder flags pass through: reserve a placeholder, carve windows and committed memory out of it.
void test_placeholders(const PhysicalApi& api) {
auto* const base = static_cast<uint8_t*>(
api.virtual_alloc(nullptr, 6 * kPage64k, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, 7, PAGE_NOACCESS));
check(base != nullptr, "XMemVirtualAlloc reserves a MEM_RESERVE_PLACEHOLDER region");
if (!base) return;
void* const window = api.virtual_alloc(base + kPage64k, 2 * kPage64k,
MEM_RESERVE | MEM_REPLACE_PLACEHOLDER | kXmem64kPages, 0x27,
PAGE_READWRITE | PAGE_GRAPHICS_READONLY);
check(window == base + kPage64k, "a reserve-only MEM_REPLACE_PLACEHOLDER returns the address it replaced");
auto* const committed = static_cast<uint8_t*>(
api.virtual_alloc(base + 4 * kPage64k, kPage64k,
MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER | kXmem64kPages, 0x27, PAGE_READWRITE));
check(committed == base + 4 * kPage64k, "a committing MEM_REPLACE_PLACEHOLDER returns the address it replaced");
if (committed) {
committed[0] = 0x5a;
check(committed[0] == 0x5a, "the committed replacement is writable");
}
uint64_t pages[2]{};
uint64_t count = 2;
check(api.allocate(0x380, &count, pages) == TRUE && count == 2, "allocate two pages for the carved window");
check(api.map(window, 2, pages) == window, "pages map into a window carved out of a placeholder");
if (window) {
fill_page(static_cast<uint8_t*>(window) + kPage64k, 0xabc0000u);
check(page_holds(static_cast<uint8_t*>(window) + kPage64k, 0xabc0000u), "the carved window holds data");
}
check(api.map(window, 2, nullptr) == window, "unmap the carved window");
check(api.free_pages(2, pages) == TRUE, "free the carved window's pages");
check(reserved_only(base), "the rest of the placeholder is still reserved");
}
// gta6rt --trace: one "xmem_attributes" event per distinct raw attribute word and API, none with the trace off.
@ -453,6 +676,25 @@ int main() {
check(reset_write_watch != nullptr, "registry exposes xmem.dll!XMemResetWriteWatch");
check(transfer != nullptr, "registry exposes xmem.dll!XMemTransferMemory");
const auto alloc_default = reinterpret_cast<XMemAllocFn>(rt::shims::find("xmem.dll", "XMemAllocDefault"));
const auto free_default = reinterpret_cast<XMemFreeFn>(rt::shims::find("xmem.dll", "XMemFreeDefault"));
const auto tools_mem =
reinterpret_cast<XMemIsToolsMemAvailableFn>(rt::shims::find("xmem.dll", "XMemIsToolsMemAvailable"));
const PhysicalApi physical{
virtual_alloc,
reinterpret_cast<XMemAllocatePhysicalPagesFn>(rt::shims::find("xmem.dll", "XMemAllocatePhysicalPages")),
reinterpret_cast<XMemFreePhysicalPagesFn>(rt::shims::find("xmem.dll", "XMemFreePhysicalPages")),
reinterpret_cast<XMemMapPhysicalPagesFn>(rt::shims::find("xmem.dll", "XMemMapPhysicalPages")),
reinterpret_cast<XMemMapPhysicalPagesScatterFn>(rt::shims::find("xmem.dll", "XMemMapPhysicalPagesScatter")),
};
check(alloc_default != nullptr, "registry exposes xmem.dll!XMemAllocDefault");
check(free_default != nullptr, "registry exposes xmem.dll!XMemFreeDefault");
check(tools_mem != nullptr, "registry exposes xmem.dll!XMemIsToolsMemAvailable");
check(physical.allocate != nullptr, "registry exposes xmem.dll!XMemAllocatePhysicalPages");
check(physical.free_pages != nullptr, "registry exposes xmem.dll!XMemFreePhysicalPages");
check(physical.map != nullptr, "registry exposes xmem.dll!XMemMapPhysicalPages");
check(physical.scatter != nullptr, "registry exposes xmem.dll!XMemMapPhysicalPagesScatter");
if (!alloc || !free_mem || !query || !get_stats) {
print_result();
return 1;
@ -472,6 +714,13 @@ int main() {
test_title_virtual_alloc();
if (alloc_default && free_default) test_default_alloc(alloc, free_mem, alloc_default, free_default);
if (tools_mem) check(tools_mem() == FALSE, "XMemIsToolsMemAvailable returns FALSE (no devkit tools memory)");
if (virtual_alloc && physical.allocate && physical.free_pages && physical.map && physical.scatter) {
test_physical_pages(physical);
test_placeholders(physical);
}
print_result();
return g_failures ? 1 : 0;
}