upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/test/xmem_test.cpp
diff options
context:
space:
mode:
authorRafael <rafaelalvesp2005@gmail.com>2026-11-23 15:36:26 -0300
committerRafael <rafaelalvesp2005@gmail.com>2026-11-23 15:36:26 -0300
commit63f0e0dea3a9d44201db408c4e2c3f2f5b2b94d6 (patch)
tree86f0dcad8070e2a3a693ef4897aa83950cfeb224 /runtime/test/xmem_test.cpp
parentf78f7d6a2a9364cb128c03ac539fe540d5c70df1 (diff)
parent6dda0630bd6fc0514baadb94fb98e36bd7d64c0b (diff)
Merge main into fix/walk-bink_names
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Diffstat (limited to 'runtime/test/xmem_test.cpp')
-rw-r--r--runtime/test/xmem_test.cpp400
1 files changed, 389 insertions, 11 deletions
diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp
index bd38cab39..eed030c12 100644
--- a/runtime/test/xmem_test.cpp
+++ b/runtime/test/xmem_test.cpp
@@ -4,6 +4,10 @@
4// convention the runtime installs for xmem.dll imports instead of a private copy of the implementation. The checks 4// convention the runtime installs for xmem.dll imports instead of a private copy of the implementation. The checks
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
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.
7#include <windows.h> 11#include <windows.h>
8#include <psapi.h> 12#include <psapi.h>
9 13
@@ -11,6 +15,7 @@
11#include <cstdio> 15#include <cstdio>
12#include <cstring> 16#include <cstring>
13#include <fstream> 17#include <fstream>
18#include <limits>
14#include <sstream> 19#include <sstream>
15#include <string> 20#include <string>
16 21
@@ -27,7 +32,20 @@ using XMemGetWorkingSetStatisticsFn = BOOL(__stdcall*)(uint32_t, void*);
27using XMemVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD); 32using XMemVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD);
28using XMemGetWriteWatchFn = UINT(WINAPI*)(DWORD, void*, SIZE_T, void**, ULONG_PTR*, ULONG*); 33using XMemGetWriteWatchFn = UINT(WINAPI*)(DWORD, void*, SIZE_T, void**, ULONG_PTR*, ULONG*);
29using XMemResetWriteWatchFn = UINT(WINAPI*)(void*, SIZE_T); 34using XMemResetWriteWatchFn = UINT(WINAPI*)(void*, SIZE_T);
35// BOOL XMemTransferMemory(XMEM_TRANSFER_TYPE, SIZE_T): the shape Microsoft's public NetRumble and NativeAOT-Xbox
36// samples call (see runtime/shims/xmem.cpp).
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*);
30constexpr 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;
31 49
32int g_checks = 0; 50int g_checks = 0;
33int g_failures = 0; 51int g_failures = 0;
@@ -212,20 +230,252 @@ void test_virtual_alloc(XMemVirtualAllocFn virtual_alloc, XMemGetWriteWatchFn ge
212 230
213 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");
214 232
233 // 2 MiB guest pages: the region is 2 MiB-aligned, rounded up to whole 2 MiB pages and committed.
234 void* const large_page = virtual_alloc(nullptr, kPage2m + page_size, MEM_RESERVE | MEM_COMMIT | kXmemLargePages,
235 0x183, PAGE_READWRITE | PAGE_GRAPHICS_READWRITE | PAGE_GRAPHICS_COHERENT);
236 check(large_page != nullptr, "XMemVirtualAlloc commits 2 MiB guest pages");
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 }
260
261 // The retail executable's GPU pools: the attribute word is recorded, and the PAGE_GRAPHICS_* bits are dropped.
262 MEMORY_BASIC_INFORMATION mbi{};
263 void* const pool = virtual_alloc(nullptr, SIZE_T{8} << 30, MEM_RESERVE | 0x20400000, 0x21, PAGE_READWRITE);
264 check(pool != nullptr, "attributes 0x21 with 64 KiB pages reserves 8 GiB");
265 if (pool) {
266 check(VirtualQuery(pool, &mbi, sizeof mbi) && mbi.State == MEM_RESERVE, "the 8 GiB pool is reserve-only");
267 check(VirtualFree(pool, 0, MEM_RELEASE), "release the 8 GiB pool");
268 }
269
270 void* const noaccess = virtual_alloc(nullptr, 0x10000, MEM_RESERVE | 0x20400000, 0x3, 0x801);
271 check(noaccess != nullptr, "attributes 0x3 with protect PAGE_GRAPHICS_NOACCESS|PAGE_NOACCESS succeeds");
272 if (noaccess) {
273 check(VirtualQuery(noaccess, &mbi, sizeof mbi) && mbi.AllocationProtect == PAGE_NOACCESS,
274 "protect 0x801 becomes PAGE_NOACCESS");
275 check(VirtualFree(noaccess, 0, MEM_RELEASE), "release the PAGE_NOACCESS pool");
276 }
277
278 void* const gpu = virtual_alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT, 0x183, 0x22004);
279 check(gpu != nullptr, "attributes 0x183 with protect 0x22004 succeeds");
280 if (gpu) {
281 check(VirtualQuery(gpu, &mbi, sizeof mbi) && mbi.Protect == PAGE_READWRITE, "protect 0x22004 becomes PAGE_READWRITE");
282 static_cast<volatile uint8_t*>(gpu)[0] = 0x5a;
283 check(static_cast<volatile uint8_t*>(gpu)[0] == 0x5a, "the 0x183 allocation is writable");
284 check(VirtualFree(gpu, 0, MEM_RELEASE), "release the 0x183 allocation");
285 }
286
215 SetLastError(ERROR_SUCCESS); 287 SetLastError(ERROR_SUCCESS);
216 void* const large_page = virtual_alloc(nullptr, page_size, MEM_RESERVE | MEM_COMMIT | 0x20000000, 0, 288 void* const replace_without_address =
217 PAGE_READWRITE); 289 virtual_alloc(nullptr, kPage64k, MEM_RESERVE | MEM_REPLACE_PLACEHOLDER | kXmem64kPages, 0, PAGE_READWRITE);
218 check(large_page == nullptr && GetLastError() == ERROR_NOT_SUPPORTED, 290 check(replace_without_address == nullptr && GetLastError() == ERROR_INVALID_PARAMETER,
219 "unsupported large-page allocation is rejected before host allocation"); 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}
220 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;
221 SetLastError(ERROR_SUCCESS); 409 SetLastError(ERROR_SUCCESS);
222 void* const attributed = virtual_alloc(nullptr, page_size, MEM_RESERVE | MEM_COMMIT, 1, PAGE_READWRITE); 410 check(api.map(reinterpret_cast<void*>((reinterpret_cast<uintptr_t>(&outside) + 0xffff) & ~uintptr_t{0xffff}), 1,
223 check(attributed == nullptr && GetLastError() == ERROR_NOT_SUPPORTED, 411 pages) == nullptr,
224 "nonzero XMem allocation attributes are rejected before host allocation"); 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");
225} 475}
226 476
227// 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.
228void test_attribute_trace(XMemAllocFn alloc, XMemFreeFn free_mem) { 478void test_attribute_trace(XMemAllocFn alloc, XMemFreeFn free_mem, XMemVirtualAllocFn virtual_alloc) {
229 wchar_t temp[MAX_PATH]; 479 wchar_t temp[MAX_PATH];
230 GetTempPathW(MAX_PATH, temp); 480 GetTempPathW(MAX_PATH, temp);
231 const std::wstring path = 481 const std::wstring path =
@@ -244,6 +494,9 @@ void test_attribute_trace(XMemAllocFn alloc, XMemFreeFn free_mem) {
244 free_mem(b, 0x5e50000); // same word again: no second event 494 free_mem(b, 0x5e50000); // same word again: no second event
245 free_mem(c, 0x99); 495 free_mem(c, 0x99);
246 free_mem(nullptr, 0x77); // a free-only word is recorded too 496 free_mem(nullptr, 0x77); // a free-only word is recorded too
497 void* const v = virtual_alloc ? virtual_alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT, 0x183, PAGE_READWRITE)
498 : nullptr;
499 if (v) VirtualFree(v, 0, MEM_RELEASE);
247 rt::startup_trace::close(); 500 rt::startup_trace::close();
248 501
249 std::ifstream in(path); 502 std::ifstream in(path);
@@ -255,14 +508,98 @@ void test_attribute_trace(XMemAllocFn alloc, XMemFreeFn free_mem) {
255 for (size_t at = log.find(needle); at != std::string::npos; at = log.find(needle, at + 1)) ++n; 508 for (size_t at = log.find(needle); at != std::string::npos; at = log.find(needle, at + 1)) ++n;
256 return n; 509 return n;
257 }; 510 };
258 check(count("\"kind\":\"xmem_attributes\"") == 5, "five events: two XMemAlloc words and three XMemFree words"); 511 check(count("\"kind\":\"xmem_attributes\"") == 6, "six events: two XMemAlloc words, three XMemFree words and one XMemVirtualAlloc word");
512 check(count("\"api\":\"XMemVirtualAlloc\",\"attributes\":\"0x183\",\"size\":65536") == 1,
513 "XMemVirtualAlloc 0x183 is recorded once, with its size");
259 check(count("\"api\":\"XMemAlloc\",\"attributes\":\"0x5e50000\",\"size\":4096") == 1, 514 check(count("\"api\":\"XMemAlloc\",\"attributes\":\"0x5e50000\",\"size\":4096") == 1,
260 "XMemAlloc 0x5e50000 is recorded once, with the size of the first call"); 515 "XMemAlloc 0x5e50000 is recorded once, with the size of the first call");
261 check(count("\"api\":\"XMemAlloc\",\"attributes\":\"0x99\",\"size\":16") == 1, "XMemAlloc 0x99 is recorded once"); 516 check(count("\"api\":\"XMemAlloc\",\"attributes\":\"0x99\",\"size\":16") == 1, "XMemAlloc 0x99 is recorded once");
262 check(count("\"api\":\"XMemFree\",\"attributes\":\"0x5e50000\"") == 1, "XMemFree 0x5e50000 is recorded once"); 517 check(count("\"api\":\"XMemFree\",\"attributes\":\"0x5e50000\"") == 1, "XMemFree 0x5e50000 is recorded once");
263 check(count("\"api\":\"XMemFree\",\"attributes\":\"0x77\"") == 1, "XMemFree 0x77 is recorded"); 518 check(count("\"api\":\"XMemFree\",\"attributes\":\"0x77\"") == 1, "XMemFree 0x77 is recorded");
264 check(count("\"attributes\":\"0x1111\"") == 0, "nothing was recorded while the trace was off"); 519 check(count("\"attributes\":\"0x1111\"") == 0, "nothing was recorded while the trace was off");
265 check(count("\"caller\":\"") == 5, "every event names its caller"); 520 check(count("\"caller\":\"") == 6, "every event names its caller");
521 DeleteFileW(path.c_str());
522}
523
524// XMemTransferMemory moves budget between the console's title and system partitions; a PC has neither, so the shim
525// succeeds for every direction and size and moves (allocates) nothing. The XMEM_TRANSFER_TYPE values are not public,
526// so the directions here are just the first few enum values and one far outside any plausible range.
527void test_transfer_memory(XMemTransferMemoryFn transfer) {
528 constexpr SIZE_T kMiB = 1024 * 1024;
529 const uint32_t types[] = {0u, 1u, 2u, 0xffffffffu};
530 // 2 MiB and 40 MiB are the sizes the samples pass ("Must be multiples of 2MB sizes"); 0, an odd size and SIZE_MAX
531 // are the boundaries.
532 const SIZE_T sizes[] = {0, 2 * kMiB, 40 * kMiB, 2 * kMiB + 1, (std::numeric_limits<SIZE_T>::max)()};
533
534 PROCESS_MEMORY_COUNTERS_EX before{};
535 const bool have_before = GetProcessMemoryInfo(GetCurrentProcess(),
536 reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&before), sizeof(before));
537 bool all_true = true;
538 bool last_error_kept = true;
539 for (const uint32_t type : types) {
540 for (const SIZE_T size : sizes) {
541 SetLastError(0x2bad);
542 const BOOL result = transfer(type, size);
543 if (result != TRUE) {
544 all_true = false;
545 std::printf(" XMemTransferMemory(%u, %zu) -> %d\n", type, static_cast<size_t>(size), result);
546 }
547 last_error_kept &= GetLastError() == 0x2bad;
548 }
549 }
550 check(all_true, "XMemTransferMemory returns TRUE (1) for every direction and size, 0 and SIZE_MAX included");
551 check(last_error_kept, "XMemTransferMemory leaves the thread's last error alone");
552
553 PROCESS_MEMORY_COUNTERS_EX after{};
554 const bool have_after = GetProcessMemoryInfo(GetCurrentProcess(),
555 reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&after), sizeof(after));
556 // 20 calls asked to move up to 40 MiB each; nothing may be committed for them. 1 MiB of slack covers the CRT's
557 // own buffers (the one-time stderr line).
558 check(have_before && have_after && after.PrivateUsage < before.PrivateUsage + kMiB,
559 "XMemTransferMemory commits no memory for the transferred sizes");
560
561 // A bool-returning declaration reads only AL: TRUE must be non-zero there as well.
562 const auto as_bool = reinterpret_cast<bool(WINAPI*)(uint32_t, SIZE_T)>(reinterpret_cast<void*>(transfer));
563 check(as_bool(0, 2 * kMiB), "XMemTransferMemory's result also reads as true through a bool return");
564
565 // The enum is 32 bits: garbage in the upper half of RCX must not change anything.
566 const auto wide = reinterpret_cast<BOOL(WINAPI*)(uint64_t, SIZE_T)>(reinterpret_cast<void*>(transfer));
567 check(wide(0xdead000000000000ull, 2 * kMiB) == TRUE, "XMemTransferMemory ignores the upper half of RCX");
568}
569
570// gta6rt --trace: one "xmem_transfer" event per distinct (type, size), none with the trace off.
571void test_transfer_trace(XMemTransferMemoryFn transfer) {
572 wchar_t temp[MAX_PATH];
573 GetTempPathW(MAX_PATH, temp);
574 const std::wstring path =
575 std::wstring(temp) + L"xmem_transfer_trace_test_" + std::to_wstring(GetCurrentProcessId()) + L".jsonl";
576 DeleteFileW(path.c_str());
577
578 check(transfer(7, 12345) == TRUE, "XMemTransferMemory with the trace off still returns TRUE");
579
580 check(rt::startup_trace::open(path.c_str()), "open the startup trace file");
581 transfer(0, 2097152);
582 transfer(0, 2097152); // same pair again: no second event
583 transfer(0, 41943040);
584 transfer(1, 2097152);
585 rt::startup_trace::close();
586
587 std::ifstream in(path);
588 std::stringstream text;
589 text << in.rdbuf();
590 const std::string log = text.str();
591 auto count = [&](const std::string& needle) {
592 int n = 0;
593 for (size_t at = log.find(needle); at != std::string::npos; at = log.find(needle, at + 1)) ++n;
594 return n;
595 };
596 check(count("\"kind\":\"xmem_transfer\"") == 3, "three xmem_transfer events: one per distinct (type, size)");
597 check(count("\"api\":\"XMemTransferMemory\",\"type\":0,\"size\":2097152") == 1,
598 "type 0 / 2 MiB is recorded once although it was called twice");
599 check(count("\"api\":\"XMemTransferMemory\",\"type\":0,\"size\":41943040") == 1, "type 0 / 40 MiB is recorded");
600 check(count("\"api\":\"XMemTransferMemory\",\"type\":1,\"size\":2097152") == 1, "type 1 / 2 MiB is recorded");
601 check(count("\"size\":12345") == 0, "nothing was recorded while the trace was off");
602 check(count("\"caller\":\"") == 3, "every transfer event names its caller");
266 DeleteFileW(path.c_str()); 603 DeleteFileW(path.c_str());
267} 604}
268 605
@@ -281,6 +618,14 @@ void test_title_virtual_alloc() {
281 check(alloc != nullptr, what); 618 check(alloc != nullptr, what);
282 if (!alloc) continue; 619 if (!alloc) continue;
283 620
621 void* const gfx = alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT, 0x2004); // PAGE_GRAPHICS_READWRITE
622 check(gfx != nullptr, "title VirtualAlloc with protect 0x2004 succeeds");
623 if (gfx) {
624 MEMORY_BASIC_INFORMATION mbi{};
625 check(VirtualQuery(gfx, &mbi, sizeof mbi) && mbi.Protect == PAGE_READWRITE,
626 "protect 0x2004 commits PAGE_READWRITE");
627 VirtualFree(gfx, 0, MEM_RELEASE);
628 }
284 for (const DWORD bits : {kMemGraphics, kMemTitle, kMemGraphics | kMemTitle, DWORD{0}}) { 629 for (const DWORD bits : {kMemGraphics, kMemTitle, kMemGraphics | kMemTitle, DWORD{0}}) {
285 void* const p = alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT | bits, PAGE_READWRITE); 630 void* const p = alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT | bits, PAGE_READWRITE);
286 std::snprintf(what, sizeof what, "%s!VirtualAlloc with type bits %#lx returns memory", dll, 631 std::snprintf(what, sizeof what, "%s!VirtualAlloc with type bits %#lx returns memory", dll,
@@ -319,6 +664,8 @@ int main() {
319 reinterpret_cast<XMemGetWriteWatchFn>(rt::shims::find("xmem.dll", "XMemGetWriteWatch")); 664 reinterpret_cast<XMemGetWriteWatchFn>(rt::shims::find("xmem.dll", "XMemGetWriteWatch"));
320 const auto reset_write_watch = 665 const auto reset_write_watch =
321 reinterpret_cast<XMemResetWriteWatchFn>(rt::shims::find("xmem.dll", "XMemResetWriteWatch")); 666 reinterpret_cast<XMemResetWriteWatchFn>(rt::shims::find("xmem.dll", "XMemResetWriteWatch"));
667 const auto transfer =
668 reinterpret_cast<XMemTransferMemoryFn>(rt::shims::find("xmem.dll", "XMemTransferMemory"));
322 669
323 check(alloc != nullptr, "registry exposes xmem.dll!XMemAlloc"); 670 check(alloc != nullptr, "registry exposes xmem.dll!XMemAlloc");
324 check(free_mem != nullptr, "registry exposes xmem.dll!XMemFree"); 671 check(free_mem != nullptr, "registry exposes xmem.dll!XMemFree");
@@ -327,6 +674,26 @@ int main() {
327 check(virtual_alloc != nullptr, "registry exposes xmem.dll!XMemVirtualAlloc"); 674 check(virtual_alloc != nullptr, "registry exposes xmem.dll!XMemVirtualAlloc");
328 check(get_write_watch != nullptr, "registry exposes xmem.dll!XMemGetWriteWatch"); 675 check(get_write_watch != nullptr, "registry exposes xmem.dll!XMemGetWriteWatch");
329 check(reset_write_watch != nullptr, "registry exposes xmem.dll!XMemResetWriteWatch"); 676 check(reset_write_watch != nullptr, "registry exposes xmem.dll!XMemResetWriteWatch");
677 check(transfer != nullptr, "registry exposes xmem.dll!XMemTransferMemory");
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");
330 697
331 if (!alloc || !free_mem || !query || !get_stats) { 698 if (!alloc || !free_mem || !query || !get_stats) {
332 print_result(); 699 print_result();
@@ -339,10 +706,21 @@ int main() {
339 if (virtual_alloc && get_write_watch && reset_write_watch) { 706 if (virtual_alloc && get_write_watch && reset_write_watch) {
340 test_virtual_alloc(virtual_alloc, get_write_watch, reset_write_watch); 707 test_virtual_alloc(virtual_alloc, get_write_watch, reset_write_watch);
341 } 708 }
342 test_attribute_trace(alloc, free_mem); 709 test_attribute_trace(alloc, free_mem, virtual_alloc);
710 if (transfer) {
711 test_transfer_memory(transfer);
712 test_transfer_trace(transfer);
713 }
343 714
344 test_title_virtual_alloc(); 715 test_title_virtual_alloc();
345 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
346 print_result(); 724 print_result();
347 return g_failures ? 1 : 0; 725 return g_failures ? 1 : 0;
348} 726}