upleb.uk

Public git repos — served from a NIP-34 GRASP relay at git.upleb.uk

summaryrefslogtreecommitdiff
path: root/runtime
diff options
context:
space:
mode:
authorNiiRoZz <simonin.remi25@gmail.com>2026-11-23 17:40:07 +0100
committerGitHub <noreply@github.com>2026-11-23 10:40:07 -0600
commit042c5f37836dc2c8d5913c2fc5a88e99bdee083b (patch)
treebb8d8953a0de3d611e356808773f7a7636ccc2c2 /runtime
parentb2801e26e672f76ffc89d52e2038677bcca9de1f (diff)
xmem: physical pages, default allocators, XMemIsToolsMemAvailable; XMemVirtualAlloc takes 2 MiB pages and placeholders (#6919)
Squash-merged after diff review of PR #6919
Diffstat (limited to 'runtime')
-rw-r--r--runtime/README.md10
-rw-r--r--runtime/shims/xmem.cpp467
-rw-r--r--runtime/test/xmem_test.cpp261
3 files changed, 700 insertions, 38 deletions
diff --git a/runtime/README.md b/runtime/README.md
index fef8a3bcb..44391fc07 100644
--- a/runtime/README.md
+++ b/runtime/README.md
@@ -161,7 +161,12 @@ Current limits, by design:
161 measured three-argument 161 measured three-argument
162 `XMemVirtualQuery(process, address, out)`. Allocations are 64-byte aligned; the working-set and 162 `XMemVirtualQuery(process, address, out)`. Allocations are 64-byte aligned; the working-set and
163 virtual-query outputs fill the observed 64-byte structures and return `FALSE`/`0` on a null or bad 163 virtual-query outputs fill the observed 64-byte structures and return `FALSE`/`0` on a null or bad
164 address. 164 address. `XMemAllocDefault`/`XMemFreeDefault` share that heap. `XMemVirtualAlloc` accepts the attribute word,
165 drops the console's `PAGE_GRAPHICS_*` protection bits, commits 2 MiB guest pages 2 MiB-aligned,
166 and passes `MEM_RESERVE_PLACEHOLDER`/`MEM_REPLACE_PLACEHOLDER` through. Physical pages
167 (`XMemAllocatePhysicalPages`, `XMemFreePhysicalPages`, `XMemMapPhysicalPages`, `XMemMapPhysicalPagesScatter`) are
168 64 KiB pages of pagefile-backed sections, mapped one view per page into the placeholder that a reserve-only
169 64 KiB-page `XMemVirtualAlloc` becomes, with that reservation's protection. `XMemIsToolsMemAvailable` is `FALSE`.
165- The `kernel32.dll` file API — `CreateFileA/W`, `FindFirstFileA/W`/`FindNextFileA/W`/`FindClose`, 170- The `kernel32.dll` file API — `CreateFileA/W`, `FindFirstFileA/W`/`FindNextFileA/W`/`FindClose`,
166 `GetFileAttributesA/W`, `GetFileAttributesExA/W` and `DeleteFileA/W`: a `GAME:` path maps under `--game-dir`, an 171 `GetFileAttributesA/W`, `GetFileAttributesExA/W` and `DeleteFileA/W`: a `GAME:` path maps under `--game-dir`, an
167 open that can write and a delete go to `--overlay DIR` (default `<game-dir>\overlay`), which reads prefer, and a path 172 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.
351| `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` | 356| `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` |
352| `dllmain` | after `DllMain(DLL_PROCESS_ATTACH)` returns | `module`, `result` | 357| `dllmain` | after `DllMain(DLL_PROCESS_ATTACH)` returns | `module`, `result` |
353| `unimplemented_call` | first call of each unimplemented import | `import` (`dll!name`), `caller` (module+RVA) | 358| `unimplemented_call` | first call of each unimplemented import | `import` (`dll!name`), `caller` (module+RVA) |
354| `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) | 359| `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) |
360| `xmem_physical_pages` | the first `XMemAllocatePhysicalPages` for each distinct attribute word | `api`, `attributes`, `pages`, `caller` |
355| `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) | 361| `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) |
356| `int3_skipped` | with `LEONIDA_SKIP_INT3` set: first int3 at each address, which is then stepped over | `at` (module+RVA) | 362| `int3_skipped` | with `LEONIDA_SKIP_INT3` set: first int3 at each address, which is then stepped over | `at` (module+RVA) |
357| `debug_string` | `OutputDebugStringA/W` with no debugger attached | `text` | 363| `debug_string` | `OutputDebugStringA/W` with no debugger attached | `text` |
diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp
index a1061af21..37f29459f 100644
--- a/runtime/shims/xmem.cpp
+++ b/runtime/shims/xmem.cpp
@@ -9,6 +9,10 @@
9// ASSUMPTION: the attribute word is not decoded by the measured call sites (one passes 0x5e50000). Until a call 9// ASSUMPTION: the attribute word is not decoded by the measured call sites (one passes 0x5e50000). Until a call
10// site shows the alignment/type fields, every block is 64-byte aligned (covers cache lines and SIMD) and a size of 10// site shows the alignment/type fields, every block is 64-byte aligned (covers cache lines and SIMD) and a size of
11// zero is rounded up to one byte so the result is a stable, non-null pointer that XMemFree can release. 11// zero is rounded up to one byte so the result is a stable, non-null pointer that XMemFree can release.
12//
13// The default allocators, the physical-page functions and XMemIsToolsMemAvailable follow argument shapes measured
14// locally at a title's call sites (each function says which). The page functions are built on the Windows placeholder
15// APIs (VirtualAlloc2, MapViewOfFile3), whose flags the title's own XMemVirtualAlloc calls already use.
12#include <windows.h> 16#include <windows.h>
13#include <intrin.h> 17#include <intrin.h>
14#include <malloc.h> 18#include <malloc.h>
@@ -18,11 +22,16 @@
18#include <cstdint> 22#include <cstdint>
19#include <cstdio> 23#include <cstdio>
20#include <cstring> 24#include <cstring>
25#include <iterator>
21#include <limits> 26#include <limits>
27#include <map>
28#include <memory>
22#include <mutex> 29#include <mutex>
23#include <set> 30#include <set>
24#include <string> 31#include <string>
32#include <unordered_map>
25#include <utility> 33#include <utility>
34#include <vector>
26 35
27#include "shims.h" 36#include "shims.h"
28#include "startup_trace.h" 37#include "startup_trace.h"
@@ -32,10 +41,14 @@ namespace {
32constexpr size_t kAlign = 64; 41constexpr size_t kAlign = 64;
33constexpr size_t kNoSize = static_cast<size_t>(-1); // XMemFree has no size field 42constexpr size_t kNoSize = static_cast<size_t>(-1); // XMemFree has no size field
34 43
35// gta6rt --trace FILE: the first XMemAlloc, XMemFree and XMemVirtualAlloc call for each distinct raw attribute word go to the 44std::string caller_field(const void* caller) {
36// startup trace as an "xmem_attributes" event (api, the word, the size for an allocation, the caller as module+RVA). The 45 return ",\"caller\":" + rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast<uint64_t>(caller)));
37// bits of the attribute word are not known yet; this records them from a real run without logging every allocation, 46}
38// which would fill the file. Off: one relaxed load per call. 47
48// gta6rt --trace FILE: the first XMemAlloc, XMemFree, XMemAllocDefault, XMemFreeDefault and XMemVirtualAlloc call for
49// each distinct raw attribute word go to the startup trace as an "xmem_attributes" event (api, the word, the size for an
50// allocation, the caller as module+RVA). The bits of the attribute word are not known yet; this records them from a
51// real run without logging every allocation, which would fill the file. Off: one relaxed load per call.
39void note_attributes(const char* api, uint64_t attributes, size_t size, const void* caller) { 52void note_attributes(const char* api, uint64_t attributes, size_t size, const void* caller) {
40 if (!rt::startup_trace::enabled()) return; 53 if (!rt::startup_trace::enabled()) return;
41 static std::mutex mutex; 54 static std::mutex mutex;
@@ -47,14 +60,15 @@ void note_attributes(const char* api, uint64_t attributes, size_t size, const vo
47 std::string fields = std::string("\"api\":\"") + api + 60 std::string fields = std::string("\"api\":\"") + api +
48 "\",\"attributes\":" + rt::startup_trace::quote(rt::startup_trace::hex(attributes)); 61 "\",\"attributes\":" + rt::startup_trace::quote(rt::startup_trace::hex(attributes));
49 if (size != kNoSize) fields += ",\"size\":" + std::to_string(size); 62 if (size != kNoSize) fields += ",\"size\":" + std::to_string(size);
50 fields += ",\"caller\":" + 63 fields += caller_field(caller);
51 rt::startup_trace::quote(rt::startup_trace::where(reinterpret_cast<uint64_t>(caller)));
52 rt::startup_trace::event("xmem_attributes", fields); 64 rt::startup_trace::event("xmem_attributes", fields);
53} 65}
54 66
67void* allocate_block(size_t size) { return _aligned_malloc(size ? size : 1, kAlign); }
68
55void* __stdcall XMemAlloc(size_t size, uint64_t attributes) { 69void* __stdcall XMemAlloc(size_t size, uint64_t attributes) {
56 note_attributes("XMemAlloc", attributes, size, _ReturnAddress()); 70 note_attributes("XMemAlloc", attributes, size, _ReturnAddress());
57 return _aligned_malloc(size ? size : 1, kAlign); 71 return allocate_block(size);
58} 72}
59 73
60void __stdcall XMemFree(void* p, uint64_t attributes) { 74void __stdcall XMemFree(void* p, uint64_t attributes) {
@@ -62,6 +76,32 @@ void __stdcall XMemFree(void* p, uint64_t attributes) {
62 _aligned_free(p); 76 _aligned_free(p);
63} 77}
64 78
79// XMemAllocDefault / XMemFreeDefault: the GDK's own allocator behind XMemAlloc and XMemFree, which a title that hooks
80// XMemAlloc forwards to. The measured title reaches each through one wrapper that is a bare tail jump to the import,
81// so they take exactly XMemAlloc's and XMemFree's arguments. They share the heap: a block from either allocator may be
82// released by either free.
83void* __stdcall XMemAllocDefault(size_t size, uint64_t attributes) {
84 note_attributes("XMemAllocDefault", attributes, size, _ReturnAddress());
85 return allocate_block(size);
86}
87
88void __stdcall XMemFreeDefault(void* p, uint64_t attributes) {
89 note_attributes("XMemFreeDefault", attributes, kNoSize, _ReturnAddress());
90 _aligned_free(p);
91}
92
93// BOOL XMemIsToolsMemAvailable(void). The measured title calls it from one helper, which six out-of-memory paths reach
94// only after an allocation has failed; the helper breaks into the debugger when the result is zero. Tools memory is
95// the extra memory of a development kit. A PC has none, so the answer is FALSE, and the title's own breakpoint marks
96// where it ran out of memory.
97BOOL WINAPI XMemIsToolsMemAvailable() {
98 static std::atomic<bool> warned{false};
99 if (!warned.exchange(true, std::memory_order_relaxed)) {
100 std::fprintf(stderr, "[rt] xmem: XMemIsToolsMemAvailable -> FALSE (no devkit tools memory; logged once)\n");
101 }
102 return FALSE;
103}
104
65// Measured call sites pass a zeroed 64-byte structure. Only the MEMORY_BASIC_INFORMATION-compatible prefix is 105// Measured call sites pass a zeroed 64-byte structure. Only the MEMORY_BASIC_INFORMATION-compatible prefix is
66// known: callers read at least the base and size fields. Fill that prefix from VirtualQueryEx and zero the rest. 106// known: callers read at least the base and size fields. Fill that prefix from VirtualQueryEx and zero the rest.
67constexpr size_t kVirtualQueryOutSize = 64; 107constexpr size_t kVirtualQueryOutSize = 64;
@@ -127,13 +167,43 @@ BOOL __stdcall XMemGetWorkingSetStatistics(uint32_t /*kind*/, void* stats) {
127 return TRUE; 167 return TRUE;
128} 168}
129 169
170// The placeholder APIs (Windows 10 1803 and later) come from kernelbase.dll at run time, so neither gta6rt nor the
171// tests link onecore.lib. A host without them fails the calls that need them with ERROR_NOT_SUPPORTED.
172using VirtualAlloc2Fn = PVOID(WINAPI*)(HANDLE, PVOID, SIZE_T, ULONG, ULONG, MEM_EXTENDED_PARAMETER*, ULONG);
173using MapViewOfFile3Fn = PVOID(WINAPI*)(HANDLE, HANDLE, PVOID, ULONG64, SIZE_T, ULONG, ULONG, MEM_EXTENDED_PARAMETER*,
174 ULONG);
175using UnmapViewOfFile2Fn = BOOL(WINAPI*)(HANDLE, PVOID, ULONG);
176
177struct PlaceholderApi {
178 VirtualAlloc2Fn virtual_alloc2 = nullptr;
179 MapViewOfFile3Fn map_view3 = nullptr;
180 UnmapViewOfFile2Fn unmap_view2 = nullptr;
181 bool available() const { return virtual_alloc2 && map_view3 && unmap_view2; }
182};
183
184const PlaceholderApi& placeholder_api() {
185 static const PlaceholderApi api = [] {
186 PlaceholderApi resolved;
187 if (const HMODULE kernelbase = GetModuleHandleW(L"kernelbase.dll")) {
188 resolved.virtual_alloc2 = reinterpret_cast<VirtualAlloc2Fn>(GetProcAddress(kernelbase, "VirtualAlloc2"));
189 resolved.map_view3 = reinterpret_cast<MapViewOfFile3Fn>(GetProcAddress(kernelbase, "MapViewOfFile3"));
190 resolved.unmap_view2 =
191 reinterpret_cast<UnmapViewOfFile2Fn>(GetProcAddress(kernelbase, "UnmapViewOfFile2"));
192 }
193 return resolved;
194 }();
195 return api;
196}
197
130// XMem allocation-type page bits select the guest page granularity and must not be forwarded as Win32 flags. 198// XMem allocation-type page bits select the guest page granularity and must not be forwarded as Win32 flags.
131constexpr DWORD kXmemLargePages = 0x20000000; 199constexpr DWORD kXmemLargePages = 0x20000000; // 2 MiB pages
132constexpr DWORD kXmem64kPages = 0x20400000; 200constexpr DWORD kXmem64kPages = 0x20400000; // 64 KiB pages
133constexpr DWORD kXmemPageModeMask = kXmem64kPages; 201constexpr DWORD kXmemPageModeMask = kXmem64kPages;
134constexpr SIZE_T kXmemPageSize64k = 0x10000; 202constexpr SIZE_T kXmemPageSize64k = 0x10000;
135constexpr DWORD kXmemHostAllocationTypeMask = 203constexpr SIZE_T kXmemPageSize2m = 0x200000;
136 MEM_COMMIT | MEM_RESERVE | MEM_RESET | MEM_TOP_DOWN | MEM_WRITE_WATCH | 0x01000000; 204constexpr DWORD kXmemHostAllocationTypeMask = MEM_COMMIT | MEM_RESERVE | MEM_REPLACE_PLACEHOLDER |
205 MEM_RESERVE_PLACEHOLDER | MEM_RESET | MEM_TOP_DOWN | MEM_WRITE_WATCH |
206 MEM_RESET_UNDO;
137 207
138bool round_up_size(SIZE_T value, SIZE_T alignment, SIZE_T& rounded) { 208bool round_up_size(SIZE_T value, SIZE_T alignment, SIZE_T& rounded) {
139 const SIZE_T max = (std::numeric_limits<SIZE_T>::max)(); 209 const SIZE_T max = (std::numeric_limits<SIZE_T>::max)();
@@ -152,14 +222,105 @@ DWORD host_protect(DWORD p) {
152 return cpu ? cpu : PAGE_NOACCESS; 222 return cpu ? cpu : PAGE_NOACCESS;
153} 223}
154 224
225// Physical pages and the windows they are mapped into. One mutex covers both tables and every map and unmap.
226//
227// A physical-page window is a reserve-only XMemVirtualAlloc in a guest page mode, or a reserve-only replacement of
228// part of a placeholder. On the host it is a placeholder, the only kind of reservation a section view can later
229// replace, and its protection is kept here: the map calls take none, so a mapped page gets its window's protection, as
230// AWE's MapUserPhysicalPages does.
231//
232// ASSUMPTION: a title does not commit memory inside such a window with kernel32!VirtualAlloc. A placeholder refuses a
233// plain commit; the measured windows are only ever passed to the map calls.
234struct Window {
235 SIZE_T size;
236 DWORD protect;
237};
238
239struct Section {
240 HANDLE handle;
241 explicit Section(HANDLE h) : handle(h) {}
242 Section(const Section&) = delete;
243 Section& operator=(const Section&) = delete;
244 ~Section() { CloseHandle(handle); }
245};
246
247struct PhysicalPage {
248 std::shared_ptr<Section> section; // a mapped view holds its own reference to the section
249 uint64_t offset;
250};
251
252constexpr uint64_t kPhysicalPageSize = 0x10000;
253// Page numbers are 4 KiB frame numbers of 64 KiB pages: the measured title stores them packed and assumes each is a
254// 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
255// [1, 2^21), and freed slots are reused so a long run never runs out.
256constexpr uint64_t kFramesPerPage = kPhysicalPageSize / 0x1000;
257constexpr uint64_t kPageSlotLimit = uint64_t{1} << 21;
258
259std::mutex g_phys_mutex;
260std::map<uintptr_t, Window> g_windows; // base -> window
261std::unordered_map<uint64_t, PhysicalPage> g_pages; // page number -> backing
262std::vector<uint64_t> g_free_slots;
263uint64_t g_next_slot = 1;
264std::unordered_map<uintptr_t, uint64_t> g_mapped; // mapped 64 KiB address -> page number
265
266// With g_phys_mutex held. A window replaces every window it overlaps: the title released those regions (with
267// kernel32!VirtualFree, which the shim does not see) before the host could hand the addresses out again.
268void record_window(void* base, SIZE_T size, DWORD protect) {
269 const uintptr_t start = reinterpret_cast<uintptr_t>(base);
270 const uintptr_t end = start + size;
271 auto it = g_windows.lower_bound(start);
272 if (it != g_windows.begin()) {
273 const auto prev = std::prev(it);
274 if (prev->first + prev->second.size > start) it = prev;
275 }
276 while (it != g_windows.end() && it->first < end) it = g_windows.erase(it);
277 g_windows[start] = Window{size, protect};
278}
279
280// With g_phys_mutex held: the window holding [address, address + bytes), if one does.
281const Window* find_window(uintptr_t address, uint64_t bytes) {
282 auto it = g_windows.upper_bound(address);
283 if (it == g_windows.begin()) return nullptr;
284 --it;
285 const uint64_t offset = address - it->first;
286 if (offset >= it->second.size || bytes > it->second.size - offset) return nullptr;
287 return &it->second;
288}
289
290// [address, address + size) as one placeholder of its own: split it out of the placeholder that holds it. Fails when
291// the range is not inside one placeholder.
292bool isolate_placeholder(void* address, SIZE_T size) {
293 MEMORY_BASIC_INFORMATION info{};
294 if (!VirtualQuery(address, &info, sizeof(info)) || info.State != MEM_RESERVE) {
295 SetLastError(ERROR_INVALID_ADDRESS);
296 return false;
297 }
298 if (info.AllocationBase == address && info.RegionSize == size) return true;
299 return VirtualFree(address, size, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER) != FALSE;
300}
301
302PVOID reserve_placeholder(void* address, SIZE_T size, SIZE_T alignment) {
303 MEM_ADDRESS_REQUIREMENTS requirements{};
304 MEM_EXTENDED_PARAMETER parameter{};
305 ULONG parameter_count = 0;
306 if (!address && alignment > kXmemPageSize64k) {
307 requirements.Alignment = alignment;
308 parameter.Type = MemExtendedParameterAddressRequirements;
309 parameter.Pointer = &requirements;
310 parameter_count = 1;
311 }
312 return placeholder_api().virtual_alloc2(GetCurrentProcess(), address, size, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER,
313 PAGE_NOACCESS, parameter_count ? &parameter : nullptr, parameter_count);
314}
315
316// PVOID XMemVirtualAlloc(address, size, allocationType, attributes, protect). All 23 calls of the measured title pass a
317// nonzero attribute word; its bits are not decoded and nothing on the host depends on them, so it is accepted and only
318// recorded (xmem_attributes). Its types cover committed 2 MiB and 64 KiB pages, reserve-only 64 KiB windows for physical pages, one
319// MEM_RESERVE_PLACEHOLDER reservation and five MEM_REPLACE_PLACEHOLDER windows carved out of it, each then filled with
320// XMemMapPhysicalPages. The guest page size sets the alignment and rounding of the region; the host's own pages stay
321// 4 KiB (host large pages need SeLockMemoryPrivilege). A 2 MiB region the host places is reserved 2 MiB-aligned through
322// VirtualAlloc2.
155void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect) { 323void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type, ULONGLONG attributes, DWORD protect) {
156 // Host-backed support covers ordinary and 64 KiB guest reservations. The 2 MiB guest mode needs an aligned
157 // reservation strategy that this shim does not provide, so fail explicitly instead of returning a misaligned
158 // region.
159 //
160 // The attribute word is recorded, not applied, as for XMemAlloc: the host has no allocator ids or memory types.
161 // The retail executable passes 0x21, 0x3, 0x183, 0x283 and 0x181 and stops at an int3 when a reservation
162 // returns NULL, so refusing a nonzero word is not an option.
163 note_attributes("XMemVirtualAlloc", attributes, size, _ReturnAddress()); 324 note_attributes("XMemVirtualAlloc", attributes, size, _ReturnAddress());
164 if (size == 0) { 325 if (size == 0) {
165 SetLastError(ERROR_INVALID_PARAMETER); 326 SetLastError(ERROR_INVALID_PARAMETER);
@@ -167,11 +328,7 @@ void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type,
167 } 328 }
168 329
169 const DWORD page_mode = allocation_type & kXmemPageModeMask; 330 const DWORD page_mode = allocation_type & kXmemPageModeMask;
170 if (page_mode == kXmemLargePages) { 331 if (page_mode != 0 && page_mode != kXmem64kPages && page_mode != kXmemLargePages) {
171 SetLastError(ERROR_NOT_SUPPORTED);
172 return nullptr;
173 }
174 if (page_mode != 0 && page_mode != kXmem64kPages) {
175 SetLastError(ERROR_INVALID_PARAMETER); 332 SetLastError(ERROR_INVALID_PARAMETER);
176 return nullptr; 333 return nullptr;
177 } 334 }
@@ -184,14 +341,28 @@ void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type,
184 341
185 DWORD host_type = allocation_type & kXmemHostAllocationTypeMask; 342 DWORD host_type = allocation_type & kXmemHostAllocationTypeMask;
186 if (host_type == 0) host_type = MEM_RESERVE | MEM_COMMIT; 343 if (host_type == 0) host_type = MEM_RESERVE | MEM_COMMIT;
344 const DWORD host_prot = host_protect(protect);
345
346 const bool commit = (host_type & MEM_COMMIT) != 0;
347 const bool new_placeholder = (host_type & MEM_RESERVE_PLACEHOLDER) != 0;
348 const bool replace = (host_type & MEM_REPLACE_PLACEHOLDER) != 0;
349 const bool window = page_mode != 0 && !commit && !new_placeholder;
350 if ((new_placeholder || replace || window || page_mode == kXmemLargePages) && !placeholder_api().available()) {
351 SetLastError(ERROR_NOT_SUPPORTED);
352 return nullptr;
353 }
187 354
188 SYSTEM_INFO system_info{}; 355 SYSTEM_INFO system_info{};
189 GetSystemInfo(&system_info); 356 GetSystemInfo(&system_info);
190 const SIZE_T page_granularity = page_mode == kXmem64kPages ? kXmemPageSize64k : system_info.dwPageSize; 357 SIZE_T page_granularity = system_info.dwPageSize;
191 const SIZE_T base_granularity = 358 SIZE_T base_granularity = (host_type & MEM_RESERVE) ? system_info.dwAllocationGranularity : system_info.dwPageSize;
192 page_mode == kXmem64kPages 359 if (page_mode == kXmem64kPages) page_granularity = base_granularity = kXmemPageSize64k;
193 ? kXmemPageSize64k 360 if (page_mode == kXmemLargePages) page_granularity = base_granularity = kXmemPageSize2m;
194 : ((host_type & MEM_RESERVE) ? system_info.dwAllocationGranularity : system_info.dwPageSize); 361 if (new_placeholder || replace) {
362 // Placeholders are split and replaced on allocation-granularity boundaries only.
363 if (page_granularity < system_info.dwAllocationGranularity) page_granularity = system_info.dwAllocationGranularity;
364 if (base_granularity < system_info.dwAllocationGranularity) base_granularity = system_info.dwAllocationGranularity;
365 }
195 if (page_granularity == 0 || (page_granularity & (page_granularity - 1)) != 0 || base_granularity == 0 || 366 if (page_granularity == 0 || (page_granularity & (page_granularity - 1)) != 0 || base_granularity == 0 ||
196 (base_granularity & (base_granularity - 1)) != 0) { 367 (base_granularity & (base_granularity - 1)) != 0) {
197 SetLastError(ERROR_INVALID_PARAMETER); 368 SetLastError(ERROR_INVALID_PARAMETER);
@@ -215,12 +386,241 @@ void* WINAPI XMemVirtualAlloc(void* address, SIZE_T size, DWORD allocation_type,
215 ~(static_cast<uintptr_t>(page_granularity) - 1); 386 ~(static_cast<uintptr_t>(page_granularity) - 1);
216 address = reinterpret_cast<void*>(base); 387 address = reinterpret_cast<void*>(base);
217 size = static_cast<SIZE_T>(end - base); 388 size = static_cast<SIZE_T>(end - base);
218 } else if (page_mode == kXmem64kPages && !round_up_size(size, page_granularity, size)) { 389 } else if (replace) {
390 SetLastError(ERROR_INVALID_PARAMETER); // a replacement names the placeholder it replaces
391 return nullptr;
392 } else if (page_granularity > system_info.dwPageSize && !round_up_size(size, page_granularity, size)) {
219 SetLastError(ERROR_INVALID_PARAMETER); 393 SetLastError(ERROR_INVALID_PARAMETER);
220 return nullptr; 394 return nullptr;
221 } 395 }
222 396
223 return VirtualAlloc(address, size, host_type, host_protect(protect)); 397 if (replace) {
398 const std::lock_guard lock(g_phys_mutex);
399 if (!isolate_placeholder(address, size)) return nullptr;
400 if (window) {
401 // A reserve-only replacement stays a placeholder: the physical pages are mapped into it.
402 record_window(address, size, host_prot);
403 return address;
404 }
405 return placeholder_api().virtual_alloc2(GetCurrentProcess(), address, size, host_type | MEM_RESERVE, host_prot,
406 nullptr, 0);
407 }
408 if (new_placeholder || window) {
409 void* const result = reserve_placeholder(address, size, base_granularity);
410 if (result && window) {
411 const std::lock_guard lock(g_phys_mutex);
412 record_window(result, size, host_prot);
413 }
414 return result;
415 }
416 if (page_mode == kXmemLargePages && address == nullptr) {
417 MEM_ADDRESS_REQUIREMENTS requirements{};
418 requirements.Alignment = kXmemPageSize2m;
419 MEM_EXTENDED_PARAMETER parameter{};
420 parameter.Type = MemExtendedParameterAddressRequirements;
421 parameter.Pointer = &requirements;
422 return placeholder_api().virtual_alloc2(GetCurrentProcess(), nullptr, size, host_type | MEM_RESERVE, host_prot,
423 &parameter, 1);
424 }
425 return VirtualAlloc(address, size, host_type, host_prot);
426}
427
428// With g_phys_mutex held. Unmaps the page at `address` if one is mapped there; the address becomes a placeholder again.
429bool unmap_page(uintptr_t address) {
430 const auto it = g_mapped.find(address);
431 if (it == g_mapped.end()) return true;
432 if (!placeholder_api().unmap_view2(GetCurrentProcess(), reinterpret_cast<void*>(address),
433 MEM_PRESERVE_PLACEHOLDER)) {
434 return false;
435 }
436 g_mapped.erase(it);
437 return true;
438}
439
440// With g_phys_mutex held. Maps physical page `page` (0: unmap) at the 64 KiB-aligned `address`, replacing what was
441// mapped there. The caller has found the window.
442bool map_page(uintptr_t address, uint64_t page, DWORD protect) {
443 if (!unmap_page(address)) return false;
444 if (page == 0) return true;
445 const auto it = g_pages.find(page);
446 if (it == g_pages.end()) {
447 SetLastError(ERROR_INVALID_PARAMETER);
448 return false;
449 }
450 void* const target = reinterpret_cast<void*>(address);
451 if (!isolate_placeholder(target, kPhysicalPageSize)) return false;
452 void* const view = placeholder_api().map_view3(it->second.section->handle, GetCurrentProcess(), target,
453 it->second.offset, kPhysicalPageSize, MEM_REPLACE_PLACEHOLDER,
454 protect, nullptr, 0);
455 if (!view) return false;
456 g_mapped[address] = page;
457 return true;
458}
459
460// Two of the measured windows are reserved PAGE_NOACCESS for the CPU and the GPU alike; pages mapped there are still
461// GPU memory, which the D3D12 layer reads on the CPU.
462DWORD view_protect(const Window& window) {
463 return window.protect == PAGE_NOACCESS ? PAGE_READWRITE : window.protect;
464}
465
466bool aligned_page_address(uintptr_t address) { return (address & (kPhysicalPageSize - 1)) == 0; }
467
468// gta6rt --trace FILE: the first XMemAllocatePhysicalPages for each distinct attribute word goes to the startup trace
469// as an "xmem_physical_pages" event with the page count and the caller.
470void note_physical_attributes(uint64_t attributes, uint64_t count, const void* caller) {
471 if (!rt::startup_trace::enabled()) return;
472 static std::mutex mutex;
473 static std::set<uint64_t> seen;
474 {
475 const std::lock_guard lock(mutex);
476 if (!seen.insert(attributes).second) return;
477 }
478 rt::startup_trace::event("xmem_physical_pages",
479 "\"api\":\"XMemAllocatePhysicalPages\",\"attributes\":" +
480 rt::startup_trace::quote(rt::startup_trace::hex(attributes)) +
481 ",\"pages\":" + std::to_string(count) + caller_field(caller));
482}
483
484// BOOL XMemAllocatePhysicalPages(attributes, UINT64* pageCount, UINT64* pageArray). Measured at four call sites: RCX is
485// a constant attribute word, RDX points at the number of 64 KiB pages (every caller computes it as the byte size
486// rounded up and shifted right by 16), R8 at an array that receives one page number per page. The result is tested as
487// a 32-bit BOOL. After success every caller compares the count with the one it asked for and frees the pages if they
488// differ, so the count is in/out.
489//
490// Each call is backed by one pagefile-backed section of count * 64 KiB: committed (charged) at once, given physical
491// memory as it is touched, zero-filled. Pages keep their contents while unmapped or mapped elsewhere, and one page can
492// be mapped at several addresses. ASSUMPTION: the attribute word (memory type, perhaps the page size) is not decoded;
493// every page is 64 KiB, which all four callers' arithmetic agrees with.
494BOOL WINAPI XMemAllocatePhysicalPages(uint64_t attributes, uint64_t* page_count, uint64_t* page_array) {
495 note_physical_attributes(attributes, page_count ? *page_count : 0, _ReturnAddress());
496 if (!page_count || (*page_count && !page_array)) {
497 SetLastError(ERROR_INVALID_PARAMETER);
498 return FALSE;
499 }
500 const uint64_t count = *page_count;
501 if (count == 0) return TRUE;
502
503 const std::lock_guard lock(g_phys_mutex);
504 if (count > g_free_slots.size() + (kPageSlotLimit - g_next_slot)) {
505 *page_count = 0;
506 SetLastError(ERROR_NOT_ENOUGH_MEMORY);
507 return FALSE;
508 }
509 const uint64_t bytes = count * kPhysicalPageSize; // below 2^37: count is below 2^21
510 const HANDLE handle = CreateFileMappingW(INVALID_HANDLE_VALUE, nullptr, PAGE_READWRITE | SEC_COMMIT,
511 static_cast<DWORD>(bytes >> 32), static_cast<DWORD>(bytes), nullptr);
512 if (!handle) {
513 *page_count = 0;
514 return FALSE;
515 }
516 const auto section = std::make_shared<Section>(handle);
517 for (uint64_t i = 0; i < count; ++i) {
518 uint64_t slot;
519 if (!g_free_slots.empty()) {
520 slot = g_free_slots.back();
521 g_free_slots.pop_back();
522 } else {
523 slot = g_next_slot++;
524 }
525 const uint64_t page = slot * kFramesPerPage;
526 g_pages[page] = PhysicalPage{section, i * kPhysicalPageSize};
527 page_array[i] = page;
528 }
529 return TRUE;
530}
531
532// BOOL XMemFreePhysicalPages(UINT64 pageCount, UINT64* pageArray). Measured at three call sites: RCX is the count (the
533// one XMemAllocatePhysicalPages returned, or the sum of several allocations), RDX the array. The callers unmap the
534// pages first; a page that is still mapped keeps its memory until it is unmapped. FALSE, with the entries before it
535// freed, for a number that is not a live page.
536BOOL WINAPI XMemFreePhysicalPages(uint64_t page_count, const uint64_t* page_array) {
537 if (page_count && !page_array) {
538 SetLastError(ERROR_INVALID_PARAMETER);
539 return FALSE;
540 }
541 const std::lock_guard lock(g_phys_mutex);
542 for (uint64_t i = 0; i < page_count; ++i) {
543 const auto it = g_pages.find(page_array[i]);
544 if (it == g_pages.end()) {
545 SetLastError(ERROR_INVALID_PARAMETER);
546 return FALSE;
547 }
548 g_pages.erase(it);
549 g_free_slots.push_back(page_array[i] / kFramesPerPage);
550 }
551 return TRUE;
552}
553
554// PVOID XMemMapPhysicalPages(PVOID address, UINT64 pageCount, UINT64* pageArray). Measured at twelve call sites: RCX
555// is an address in a window XMemVirtualAlloc reserved, RDX a 64-bit count, R8 the pages to map there one after another,
556// or null to unmap that many (four calls at shutdown). Callers test the 64-bit result for zero, so it is the address on
557// success. A page number of 0 in the array unmaps that one page.
558//
559// Each page is its own view (MapViewOfFile3 into a 64 KiB placeholder), so any page can be remapped or unmapped later
560// without touching its neighbours. A failure part-way leaves the pages before it mapped.
561void* WINAPI XMemMapPhysicalPages(void* address, uint64_t page_count, const uint64_t* page_array) {
562 const uintptr_t start = reinterpret_cast<uintptr_t>(address);
563 if (!aligned_page_address(start) || page_count > (std::numeric_limits<uintptr_t>::max)() / kPhysicalPageSize ||
564 start > (std::numeric_limits<uintptr_t>::max)() - page_count * kPhysicalPageSize) {
565 SetLastError(ERROR_INVALID_PARAMETER);
566 return nullptr;
567 }
568 if (!placeholder_api().available()) {
569 SetLastError(ERROR_NOT_SUPPORTED);
570 return nullptr;
571 }
572 const std::lock_guard lock(g_phys_mutex);
573 if (!page_array) {
574 for (uint64_t i = 0; i < page_count; ++i) {
575 if (!unmap_page(start + i * kPhysicalPageSize)) return nullptr;
576 }
577 return address;
578 }
579 const Window* const window = find_window(start, page_count * kPhysicalPageSize);
580 if (!window) {
581 SetLastError(ERROR_INVALID_ADDRESS);
582 return nullptr;
583 }
584 const DWORD protect = view_protect(*window);
585 for (uint64_t i = 0; i < page_count; ++i) {
586 if (!map_page(start + i * kPhysicalPageSize, page_array[i], protect)) return nullptr;
587 }
588 return address;
589}
590
591// BOOL XMemMapPhysicalPagesScatter(PVOID* addresses, UINT32 pageCount, UINT64* pageArray). Measured at two call sites:
592// 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,
593// unmaps). The result is tested as a 32-bit BOOL. Like MapUserPhysicalPagesScatter: entry i maps pageArray[i] at
594// addresses[i].
595BOOL WINAPI XMemMapPhysicalPagesScatter(void* const* addresses, uint32_t page_count, const uint64_t* page_array) {
596 if (page_count && !addresses) {
597 SetLastError(ERROR_INVALID_PARAMETER);
598 return FALSE;
599 }
600 if (!placeholder_api().available()) {
601 SetLastError(ERROR_NOT_SUPPORTED);
602 return FALSE;
603 }
604 const std::lock_guard lock(g_phys_mutex);
605 for (uint32_t i = 0; i < page_count; ++i) {
606 const uintptr_t address = reinterpret_cast<uintptr_t>(addresses[i]);
607 if (!aligned_page_address(address)) {
608 SetLastError(ERROR_INVALID_PARAMETER);
609 return FALSE;
610 }
611 const uint64_t page = page_array ? page_array[i] : 0;
612 if (page == 0) {
613 if (!unmap_page(address)) return FALSE;
614 continue;
615 }
616 const Window* const window = find_window(address, kPhysicalPageSize);
617 if (!window) {
618 SetLastError(ERROR_INVALID_ADDRESS);
619 return FALSE;
620 }
621 if (!map_page(address, page, view_protect(*window))) return FALSE;
622 }
623 return TRUE;
224} 624}
225 625
226UINT WINAPI XMemGetWriteWatch(DWORD flags, void* base_address, SIZE_T region_size, void** addresses, ULONG_PTR* count, 626UINT WINAPI XMemGetWriteWatch(DWORD flags, void* base_address, SIZE_T region_size, void** addresses, ULONG_PTR* count,
@@ -318,4 +718,11 @@ SHIM_TABLE(xmem,
318 {"xmem.dll", "XMemGetWriteWatch", reinterpret_cast<void*>(&XMemGetWriteWatch)}, 718 {"xmem.dll", "XMemGetWriteWatch", reinterpret_cast<void*>(&XMemGetWriteWatch)},
319 {"xmem.dll", "XMemResetWriteWatch", reinterpret_cast<void*>(&XMemResetWriteWatch)}, 719 {"xmem.dll", "XMemResetWriteWatch", reinterpret_cast<void*>(&XMemResetWriteWatch)},
320 {"xmem.dll", "XMemTransferMemory", reinterpret_cast<void*>(&XMemTransferMemory)}, 720 {"xmem.dll", "XMemTransferMemory", reinterpret_cast<void*>(&XMemTransferMemory)},
721 {"xmem.dll", "XMemAllocDefault", reinterpret_cast<void*>(&XMemAllocDefault)},
722 {"xmem.dll", "XMemFreeDefault", reinterpret_cast<void*>(&XMemFreeDefault)},
723 {"xmem.dll", "XMemIsToolsMemAvailable", reinterpret_cast<void*>(&XMemIsToolsMemAvailable)},
724 {"xmem.dll", "XMemAllocatePhysicalPages", reinterpret_cast<void*>(&XMemAllocatePhysicalPages)},
725 {"xmem.dll", "XMemFreePhysicalPages", reinterpret_cast<void*>(&XMemFreePhysicalPages)},
726 {"xmem.dll", "XMemMapPhysicalPages", reinterpret_cast<void*>(&XMemMapPhysicalPages)},
727 {"xmem.dll", "XMemMapPhysicalPagesScatter", reinterpret_cast<void*>(&XMemMapPhysicalPagesScatter)},
321); 728);
diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp
index edc5fd33c..eed030c12 100644
--- a/runtime/test/xmem_test.cpp
+++ b/runtime/test/xmem_test.cpp
@@ -5,7 +5,9 @@
5// cover what the measured call sites use: 64-byte-aligned allocations, XMemFree, working-set statistics with the 5// cover what the measured call sites use: 64-byte-aligned allocations, XMemFree, working-set statistics with the
6// size at +8, and XMemVirtualQuery's MEMORY_BASIC_INFORMATION prefix inside a zeroed 64-byte output. 6// size at +8, and XMemVirtualQuery's MEMORY_BASIC_INFORMATION prefix inside a zeroed 64-byte output.
7// XMemTransferMemory follows the call shape in Microsoft's public samples: TRUE for any direction and size, with 7// XMemTransferMemory follows the call shape in Microsoft's public samples: TRUE for any direction and size, with
8// nothing committed, and one trace event per distinct (type, size). 8// nothing committed, and one trace event per distinct (type, size). XMemVirtualAlloc accepts attribute words and console
9// graphics protection bits and commits 2 MiB guest pages; the placeholder flags pass through; physical pages keep their
10// contents across unmap and remap, alias when mapped twice, and scatter-map per address.
9#include <windows.h> 11#include <windows.h>
10#include <psapi.h> 12#include <psapi.h>
11 13
@@ -33,7 +35,17 @@ using XMemResetWriteWatchFn = UINT(WINAPI*)(void*, SIZE_T);
33// BOOL XMemTransferMemory(XMEM_TRANSFER_TYPE, SIZE_T): the shape Microsoft's public NetRumble and NativeAOT-Xbox 35// BOOL XMemTransferMemory(XMEM_TRANSFER_TYPE, SIZE_T): the shape Microsoft's public NetRumble and NativeAOT-Xbox
34// samples call (see runtime/shims/xmem.cpp). 36// samples call (see runtime/shims/xmem.cpp).
35using XMemTransferMemoryFn = BOOL(WINAPI*)(uint32_t, SIZE_T); 37using XMemTransferMemoryFn = BOOL(WINAPI*)(uint32_t, SIZE_T);
38// The shapes measured at a title's call sites (see runtime/shims/xmem.cpp).
39using XMemIsToolsMemAvailableFn = BOOL(WINAPI*)();
40using XMemAllocatePhysicalPagesFn = BOOL(WINAPI*)(uint64_t, uint64_t*, uint64_t*);
41using XMemFreePhysicalPagesFn = BOOL(WINAPI*)(uint64_t, const uint64_t*);
42using XMemMapPhysicalPagesFn = void*(WINAPI*)(void*, uint64_t, const uint64_t*);
43using XMemMapPhysicalPagesScatterFn = BOOL(WINAPI*)(void* const*, uint32_t, const uint64_t*);
36constexpr uint32_t kMeasuredKind = 0x20000001; 44constexpr uint32_t kMeasuredKind = 0x20000001;
45constexpr DWORD kXmemLargePages = 0x20000000;
46constexpr DWORD kXmem64kPages = 0x20400000;
47constexpr SIZE_T kPage64k = 0x10000;
48constexpr SIZE_T kPage2m = 0x200000;
37 49
38int g_checks = 0; 50int g_checks = 0;
39int g_failures = 0; 51int g_failures = 0;
@@ -218,11 +230,33 @@ void test_virtual_alloc(XMemVirtualAllocFn virtual_alloc, XMemGetWriteWatchFn ge
218 230
219 check(VirtualFree(base, 0, MEM_RELEASE), "release the synthetic write-watch region"); 231 check(VirtualFree(base, 0, MEM_RELEASE), "release the synthetic write-watch region");
220 232
221 SetLastError(ERROR_SUCCESS); 233 // 2 MiB guest pages: the region is 2 MiB-aligned, rounded up to whole 2 MiB pages and committed.
222 void* const large_page = virtual_alloc(nullptr, page_size, MEM_RESERVE | MEM_COMMIT | 0x20000000, 0, 234 void* const large_page = virtual_alloc(nullptr, kPage2m + page_size, MEM_RESERVE | MEM_COMMIT | kXmemLargePages,
223 PAGE_READWRITE); 235 0x183, PAGE_READWRITE | PAGE_GRAPHICS_READWRITE | PAGE_GRAPHICS_COHERENT);
224 check(large_page == nullptr && GetLastError() == ERROR_NOT_SUPPORTED, 236 check(large_page != nullptr, "XMemVirtualAlloc commits 2 MiB guest pages");
225 "unsupported large-page allocation is rejected before host allocation"); 237 if (large_page) {
238 check((reinterpret_cast<uintptr_t>(large_page) & (kPage2m - 1)) == 0, "a 2 MiB-page region is 2 MiB-aligned");
239 MEMORY_BASIC_INFORMATION info{};
240 VirtualQuery(large_page, &info, sizeof(info));
241 check(info.State == MEM_COMMIT && info.RegionSize >= 2 * kPage2m && info.Protect == PAGE_READWRITE,
242 "a 2 MiB-page region is rounded up to whole pages, committed read-write without the graphics bits");
243 static_cast<volatile uint8_t*>(large_page)[2 * kPage2m - 1] = 0x77;
244 check(VirtualFree(large_page, 0, MEM_RELEASE), "release the 2 MiB-page region");
245 }
246
247 // The attribute word is accepted (every measured call passes a nonzero one) and the protection loses its graphics
248 // bits, in the 64 KiB page mode as well.
249 void* const attributed = virtual_alloc(nullptr, kPage64k, MEM_RESERVE | MEM_COMMIT | kXmem64kPages, 0x181,
250 PAGE_READWRITE | PAGE_GRAPHICS_READWRITE);
251 check(attributed != nullptr, "XMemVirtualAlloc accepts a nonzero attribute word and console protection bits");
252 if (attributed) {
253 MEMORY_BASIC_INFORMATION info{};
254 VirtualQuery(attributed, &info, sizeof(info));
255 check(info.State == MEM_COMMIT && info.Protect == PAGE_READWRITE,
256 "the region is committed PAGE_READWRITE (graphics bits dropped)");
257 static_cast<volatile uint8_t*>(attributed)[0] = 0x42;
258 check(VirtualFree(attributed, 0, MEM_RELEASE), "release the attributed region");
259 }
226 260
227 // The retail executable's GPU pools: the attribute word is recorded, and the PAGE_GRAPHICS_* bits are dropped. 261 // The retail executable's GPU pools: the attribute word is recorded, and the PAGE_GRAPHICS_* bits are dropped.
228 MEMORY_BASIC_INFORMATION mbi{}; 262 MEMORY_BASIC_INFORMATION mbi{};
@@ -249,6 +283,195 @@ void test_virtual_alloc(XMemVirtualAllocFn virtual_alloc, XMemGetWriteWatchFn ge
249 check(static_cast<volatile uint8_t*>(gpu)[0] == 0x5a, "the 0x183 allocation is writable"); 283 check(static_cast<volatile uint8_t*>(gpu)[0] == 0x5a, "the 0x183 allocation is writable");
250 check(VirtualFree(gpu, 0, MEM_RELEASE), "release the 0x183 allocation"); 284 check(VirtualFree(gpu, 0, MEM_RELEASE), "release the 0x183 allocation");
251 } 285 }
286
287 SetLastError(ERROR_SUCCESS);
288 void* const replace_without_address =
289 virtual_alloc(nullptr, kPage64k, MEM_RESERVE | MEM_REPLACE_PLACEHOLDER | kXmem64kPages, 0, PAGE_READWRITE);
290 check(replace_without_address == nullptr && GetLastError() == ERROR_INVALID_PARAMETER,
291 "MEM_REPLACE_PLACEHOLDER without an address is rejected");
292}
293
294// XMemAllocDefault / XMemFreeDefault share XMemAlloc's heap: a block from either is freed by either.
295void test_default_alloc(XMemAllocFn alloc, XMemFreeFn free_mem, XMemAllocFn alloc_default,
296 XMemFreeFn free_default) {
297 void* const a = alloc_default(100, 0x5e50000);
298 check(aligned_64(a), "XMemAllocDefault returns a 64-byte aligned block");
299 void* const zero = alloc_default(0, 0);
300 check(zero != nullptr, "XMemAllocDefault(0) returns non-null");
301 void* const b = alloc(100, 0);
302 if (a) std::memset(a, 0x11, 100);
303 if (b) std::memset(b, 0x22, 100);
304 free_mem(a, 0x5e50000);
305 free_default(b, 0);
306 free_default(zero, 0);
307 check(true, "XMemFree releases an XMemAllocDefault block and XMemFreeDefault an XMemAlloc block");
308}
309
310uint32_t read_u32(const void* base, size_t offset) {
311 uint32_t value = 0;
312 std::memcpy(&value, static_cast<const uint8_t*>(base) + offset, sizeof(value));
313 return value;
314}
315
316void fill_page(void* page, uint32_t tag) {
317 auto* words = static_cast<uint32_t*>(page);
318 for (size_t i = 0; i < kPage64k / sizeof(uint32_t); i += 1024) words[i] = tag + static_cast<uint32_t>(i);
319}
320
321bool page_holds(const void* page, uint32_t tag) {
322 for (size_t i = 0; i < kPage64k / sizeof(uint32_t); i += 1024) {
323 if (read_u32(page, i * sizeof(uint32_t)) != tag + static_cast<uint32_t>(i)) return false;
324 }
325 return true;
326}
327
328bool reserved_only(const void* address) {
329 MEMORY_BASIC_INFORMATION info{};
330 return VirtualQuery(address, &info, sizeof(info)) && info.State == MEM_RESERVE;
331}
332
333struct PhysicalApi {
334 XMemVirtualAllocFn virtual_alloc;
335 XMemAllocatePhysicalPagesFn allocate;
336 XMemFreePhysicalPagesFn free_pages;
337 XMemMapPhysicalPagesFn map;
338 XMemMapPhysicalPagesScatterFn scatter;
339};
340
341// Physical pages in a 64 KiB-page window, as the measured callers use them: reserve a window, allocate pages, map them,
342// remap them elsewhere and in another order, unmap, free.
343void test_physical_pages(const PhysicalApi& api) {
344 constexpr uint64_t kPages = 4;
345 auto* const window = static_cast<uint8_t*>(api.virtual_alloc(
346 nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE | PAGE_GRAPHICS_READWRITE));
347 check(window != nullptr, "XMemVirtualAlloc reserves a 64 KiB-page window");
348 auto* const second = static_cast<uint8_t*>(api.virtual_alloc(
349 nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x21, PAGE_READWRITE));
350 check(second != nullptr, "XMemVirtualAlloc reserves a second window");
351 if (!window || !second) return;
352 check(reserved_only(window), "the window is reserved, not committed");
353
354 uint64_t pages[kPages]{};
355 uint64_t count = kPages;
356 check(api.allocate(0x280, &count, pages) == TRUE && count == kPages,
357 "XMemAllocatePhysicalPages allocates every page asked for and keeps the count");
358 bool numbers_ok = true;
359 for (uint64_t i = 0; i < kPages; ++i) {
360 numbers_ok &= pages[i] != 0 && pages[i] % 16 == 0 && pages[i] < (uint64_t{1} << 25);
361 for (uint64_t j = 0; j < i; ++j) numbers_ok &= pages[i] != pages[j];
362 }
363 check(numbers_ok, "page numbers are distinct non-zero multiples of 16 below 2^25");
364
365 check(api.map(window, kPages, pages) == window, "XMemMapPhysicalPages returns the address it mapped");
366 for (uint64_t i = 0; i < kPages; ++i) fill_page(window + i * kPage64k, 0x1000u * static_cast<uint32_t>(i + 1));
367 {
368 MEMORY_BASIC_INFORMATION info{};
369 VirtualQuery(window, &info, sizeof(info));
370 check(info.State == MEM_COMMIT && info.Type == MEM_MAPPED && info.Protect == PAGE_READWRITE,
371 "a mapped page is a read-write view with the window's protection");
372 }
373
374 check(api.map(window, kPages, nullptr) == window, "XMemMapPhysicalPages with no page array unmaps");
375 check(reserved_only(window) && reserved_only(window + 3 * kPage64k), "unmapped pages are reserved again");
376
377 // Remap in reverse order into the other window: each page keeps its contents.
378 uint64_t reversed[kPages];
379 for (uint64_t i = 0; i < kPages; ++i) reversed[i] = pages[kPages - 1 - i];
380 check(api.map(second, kPages, reversed) == second, "the pages map into another window");
381 bool kept = true;
382 for (uint64_t i = 0; i < kPages; ++i) {
383 kept &= page_holds(second + i * kPage64k, 0x1000u * static_cast<uint32_t>(kPages - i));
384 }
385 check(kept, "a physical page keeps its contents across unmap and remap");
386
387 // One page mapped at two addresses is one memory.
388 check(api.map(window, 1, &pages[0]) == window, "a page already mapped elsewhere maps again");
389 static_cast<volatile uint32_t*>(static_cast<void*>(window))[1] = 0xfeedf00d;
390 check(read_u32(second + 3 * kPage64k, 4) == 0xfeedf00d, "both mappings of a page see the same memory");
391
392 // Mapping over a mapped page replaces it; a 0 entry unmaps one page.
393 const uint64_t replace[2] = {pages[1], 0};
394 check(api.map(window, 2, replace) == window, "mapping over mapped pages replaces them");
395 check(page_holds(window, 0x2000u) && reserved_only(window + kPage64k),
396 "the first page now shows page 1 and a 0 entry left the second unmapped");
397
398 // Scatter: entry i maps page i at address i, out of order; 0 unmaps.
399 void* const addresses[3] = {window + 3 * kPage64k, window + 2 * kPage64k, window};
400 const uint64_t scattered[3] = {pages[2], pages[3], 0};
401 check(api.scatter(addresses, 3, scattered) == TRUE, "XMemMapPhysicalPagesScatter maps each page at its address");
402 check(page_holds(window + 3 * kPage64k, 0x3000u) && page_holds(window + 2 * kPage64k, 0x4000u) &&
403 reserved_only(window),
404 "scattered pages land at their own addresses and a 0 entry unmaps");
405 check(api.scatter(addresses, 3, nullptr) == TRUE && reserved_only(window + 3 * kPage64k),
406 "XMemMapPhysicalPagesScatter with no page array unmaps");
407
408 uint8_t outside = 0;
409 SetLastError(ERROR_SUCCESS);
410 check(api.map(reinterpret_cast<void*>((reinterpret_cast<uintptr_t>(&outside) + 0xffff) & ~uintptr_t{0xffff}), 1,
411 pages) == nullptr,
412 "mapping outside any window fails");
413 check(api.map(window + 1, 1, pages) == nullptr && GetLastError() == ERROR_INVALID_PARAMETER,
414 "mapping at an address that is not 64 KiB-aligned fails");
415 const uint64_t bogus = 0x1fffff0; // the highest page number, far above the few this test allocates
416 check(api.map(window, 1, &bogus) == nullptr, "mapping a page number that was never allocated fails");
417
418 check(api.map(second, kPages, nullptr) == second, "unmap the second window");
419 check(api.free_pages(kPages, pages) == TRUE, "XMemFreePhysicalPages frees the pages");
420 check(api.free_pages(1, pages) == FALSE, "freeing a page twice fails");
421
422 // Freed numbers are reused.
423 uint64_t again[kPages]{};
424 count = kPages;
425 check(api.allocate(0x180, &count, again) == TRUE && count == kPages, "pages can be allocated again");
426 bool reused = true;
427 for (uint64_t i = 0; i < kPages; ++i) {
428 bool found = false;
429 for (uint64_t j = 0; j < kPages; ++j) found |= again[i] == pages[j];
430 reused &= found;
431 }
432 check(reused, "freed page numbers are reused");
433 check(api.map(window, 1, again) == window && read_u32(window, 0) == 0, "a fresh page maps and reads as zero");
434 api.map(window, 1, nullptr);
435 api.free_pages(kPages, again);
436
437 uint64_t zero_count = 0;
438 check(api.allocate(0x280, &zero_count, nullptr) == TRUE, "allocating zero pages succeeds");
439 check(api.allocate(0x280, nullptr, pages) == FALSE, "a null count fails");
440 // The windows were split into one placeholder per page; the process exit releases them.
441}
442
443// The placeholder flags pass through: reserve a placeholder, carve windows and committed memory out of it.
444void test_placeholders(const PhysicalApi& api) {
445 auto* const base = static_cast<uint8_t*>(
446 api.virtual_alloc(nullptr, 6 * kPage64k, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, 7, PAGE_NOACCESS));
447 check(base != nullptr, "XMemVirtualAlloc reserves a MEM_RESERVE_PLACEHOLDER region");
448 if (!base) return;
449
450 void* const window = api.virtual_alloc(base + kPage64k, 2 * kPage64k,
451 MEM_RESERVE | MEM_REPLACE_PLACEHOLDER | kXmem64kPages, 0x27,
452 PAGE_READWRITE | PAGE_GRAPHICS_READONLY);
453 check(window == base + kPage64k, "a reserve-only MEM_REPLACE_PLACEHOLDER returns the address it replaced");
454
455 auto* const committed = static_cast<uint8_t*>(
456 api.virtual_alloc(base + 4 * kPage64k, kPage64k,
457 MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER | kXmem64kPages, 0x27, PAGE_READWRITE));
458 check(committed == base + 4 * kPage64k, "a committing MEM_REPLACE_PLACEHOLDER returns the address it replaced");
459 if (committed) {
460 committed[0] = 0x5a;
461 check(committed[0] == 0x5a, "the committed replacement is writable");
462 }
463
464 uint64_t pages[2]{};
465 uint64_t count = 2;
466 check(api.allocate(0x380, &count, pages) == TRUE && count == 2, "allocate two pages for the carved window");
467 check(api.map(window, 2, pages) == window, "pages map into a window carved out of a placeholder");
468 if (window) {
469 fill_page(static_cast<uint8_t*>(window) + kPage64k, 0xabc0000u);
470 check(page_holds(static_cast<uint8_t*>(window) + kPage64k, 0xabc0000u), "the carved window holds data");
471 }
472 check(api.map(window, 2, nullptr) == window, "unmap the carved window");
473 check(api.free_pages(2, pages) == TRUE, "free the carved window's pages");
474 check(reserved_only(base), "the rest of the placeholder is still reserved");
252} 475}
253 476
254// gta6rt --trace: one "xmem_attributes" event per distinct raw attribute word and API, none with the trace off. 477// gta6rt --trace: one "xmem_attributes" event per distinct raw attribute word and API, none with the trace off.
@@ -453,6 +676,25 @@ int main() {
453 check(reset_write_watch != nullptr, "registry exposes xmem.dll!XMemResetWriteWatch"); 676 check(reset_write_watch != nullptr, "registry exposes xmem.dll!XMemResetWriteWatch");
454 check(transfer != nullptr, "registry exposes xmem.dll!XMemTransferMemory"); 677 check(transfer != nullptr, "registry exposes xmem.dll!XMemTransferMemory");
455 678
679 const auto alloc_default = reinterpret_cast<XMemAllocFn>(rt::shims::find("xmem.dll", "XMemAllocDefault"));
680 const auto free_default = reinterpret_cast<XMemFreeFn>(rt::shims::find("xmem.dll", "XMemFreeDefault"));
681 const auto tools_mem =
682 reinterpret_cast<XMemIsToolsMemAvailableFn>(rt::shims::find("xmem.dll", "XMemIsToolsMemAvailable"));
683 const PhysicalApi physical{
684 virtual_alloc,
685 reinterpret_cast<XMemAllocatePhysicalPagesFn>(rt::shims::find("xmem.dll", "XMemAllocatePhysicalPages")),
686 reinterpret_cast<XMemFreePhysicalPagesFn>(rt::shims::find("xmem.dll", "XMemFreePhysicalPages")),
687 reinterpret_cast<XMemMapPhysicalPagesFn>(rt::shims::find("xmem.dll", "XMemMapPhysicalPages")),
688 reinterpret_cast<XMemMapPhysicalPagesScatterFn>(rt::shims::find("xmem.dll", "XMemMapPhysicalPagesScatter")),
689 };
690 check(alloc_default != nullptr, "registry exposes xmem.dll!XMemAllocDefault");
691 check(free_default != nullptr, "registry exposes xmem.dll!XMemFreeDefault");
692 check(tools_mem != nullptr, "registry exposes xmem.dll!XMemIsToolsMemAvailable");
693 check(physical.allocate != nullptr, "registry exposes xmem.dll!XMemAllocatePhysicalPages");
694 check(physical.free_pages != nullptr, "registry exposes xmem.dll!XMemFreePhysicalPages");
695 check(physical.map != nullptr, "registry exposes xmem.dll!XMemMapPhysicalPages");
696 check(physical.scatter != nullptr, "registry exposes xmem.dll!XMemMapPhysicalPagesScatter");
697
456 if (!alloc || !free_mem || !query || !get_stats) { 698 if (!alloc || !free_mem || !query || !get_stats) {
457 print_result(); 699 print_result();
458 return 1; 700 return 1;
@@ -472,6 +714,13 @@ int main() {
472 714
473 test_title_virtual_alloc(); 715 test_title_virtual_alloc();
474 716
717 if (alloc_default && free_default) test_default_alloc(alloc, free_mem, alloc_default, free_default);
718 if (tools_mem) check(tools_mem() == FALSE, "XMemIsToolsMemAvailable returns FALSE (no devkit tools memory)");
719 if (virtual_alloc && physical.allocate && physical.free_pages && physical.map && physical.scatter) {
720 test_physical_pages(physical);
721 test_placeholders(physical);
722 }
723
475 print_result(); 724 print_result();
476 return g_failures ? 1 : 0; 725 return g_failures ? 1 : 0;
477} 726}