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:
authorcynbun <74268930+cynbun@users.noreply.github.com>2026-11-23 15:06:21 +0100
committerGitHub <noreply@github.com>2026-11-23 08:06:21 -0600
commit085fe1efd46d63ee4f4da9d700d23a40484ea6a2 (patch)
tree4ae5da04b3853dd08c0d0b60583da57e316e200a /runtime
parent7022367cbd4f7ef30ec3168189c79eb68a6dd1d3 (diff)
xmem: serve XMemTransferMemory (RT-449) (#6351)
Squash-merged after review of PR #6351 - xmem: serve XMemTransferMemory (RT-449)
Diffstat (limited to 'runtime')
-rw-r--r--runtime/shims/xmem.cpp48
-rw-r--r--runtime/test/xmem_test.cpp95
2 files changed, 143 insertions, 0 deletions
diff --git a/runtime/shims/xmem.cpp b/runtime/shims/xmem.cpp
index c7cfb76c0..e6ab2d43b 100644
--- a/runtime/shims/xmem.cpp
+++ b/runtime/shims/xmem.cpp
@@ -21,6 +21,7 @@
21#include <limits> 21#include <limits>
22#include <mutex> 22#include <mutex>
23#include <set> 23#include <set>
24#include <string>
24#include <utility> 25#include <utility>
25 26
26#include "shims.h" 27#include "shims.h"
@@ -219,6 +220,52 @@ UINT WINAPI XMemResetWriteWatch(void* base_address, SIZE_T region_size) {
219 return ResetWriteWatch(base_address, region_size); 220 return ResetWriteWatch(base_address, region_size);
220} 221}
221 222
223// BOOL XMemTransferMemory(XMEM_TRANSFER_TYPE type, SIZE_T size). Its reference page and the XMEM_TRANSFER_TYPE enum
224// page (gaming/gdk/docs/reference/system/xmem/{functions/xmemtransfermemory,enums/xmem_transfer_type}) are NDA
225// topics on Microsoft Learn, so the shape comes from public code built against the GDK's xmem.h: Microsoft's
226// XBOX-MonoGame-NetRumble sample (console/NetRumble.Bootstrap/Main.cpp) and FNA-XNA/NativeAOT-Xbox (Bootstrap/Main.cpp)
227// both call `if (!XMemTransferMemory(XMemTransferTitleToSystem, additionalKernelPoolMemory))` with a `const size_t`,
228// commented "Transfer additional memory to kernel pool" and "Must be multiples of 2MB sizes". So: two arguments, the
229// enum (32 bits) in ECX and the size in RDX, and a zero return is failure. The public XLaunchNewGame page adds that
230// "Memory transferred to the system using XMemTransferMemory (NDA topic) is persisted", and the game-save debugging
231// page suggests it for E_OUTOFMEMORY "to transfer some memory to the system partition".
232//
233// On the console it moves budget between the title's partition and the system's. A PC has one pool and no budget
234// split, so there is nothing to move: every direction and size returns TRUE and nothing is allocated or reserved. Not
235// known (the pages are NDA): the numeric XMEM_TRANSFER_TYPE values, and whether the console refuses or rounds a size
236// that is not a multiple of 2 MiB. Refusing would stop a title at startup (both samples return -1), while succeeding
237// changes nothing here. TRUE is 1 in EAX, so it also reads as true if the real return type is a one-byte bool.
238//
239// gta6rt --trace FILE: the first call for each distinct (type, size) pair goes to the startup trace as an
240// "xmem_transfer" event with the caller as module+RVA, so a run with the executable records the values it passes.
241BOOL WINAPI XMemTransferMemory(uint32_t type, SIZE_T size) {
242 static std::atomic<bool> warned{false};
243 if (!warned.exchange(true, std::memory_order_relaxed)) {
244 std::fprintf(stderr,
245 "[rt] xmem: XMemTransferMemory(type %u, %zu bytes): a PC has no title/system memory partition; "
246 "returning TRUE without moving anything (logged once)\n",
247 type, static_cast<size_t>(size));
248 }
249 if (rt::startup_trace::enabled()) {
250 static std::mutex mutex;
251 static std::set<std::pair<uint32_t, uint64_t>> seen;
252 bool first = false;
253 {
254 const std::lock_guard lock(mutex);
255 first = seen.insert({type, static_cast<uint64_t>(size)}).second;
256 }
257 if (first) {
258 rt::startup_trace::event(
259 "xmem_transfer",
260 "\"api\":\"XMemTransferMemory\",\"type\":" + std::to_string(type) +
261 ",\"size\":" + std::to_string(static_cast<uint64_t>(size)) + ",\"caller\":" +
262 rt::startup_trace::quote(
263 rt::startup_trace::where(reinterpret_cast<uint64_t>(_ReturnAddress()))));
264 }
265 }
266 return TRUE;
267}
268
222// kernel32!VirtualAlloc as a title calls it. The console's allocation type has two bits of its own, MEM_GRAPHICS 269// kernel32!VirtualAlloc as a title calls it. The console's allocation type has two bits of its own, MEM_GRAPHICS
223// (0x10000000, memory the GPU reads) and MEM_TITLE (0x40000000, the title's own heap). On a PC the host rejects both 270// (0x10000000, memory the GPU reads) and MEM_TITLE (0x40000000, the title's own heap). On a PC the host rejects both
224// with ERROR_INVALID_PARAMETER (measured on Windows 11 26200: VirtualAlloc(NULL, 64 KiB, MEM_COMMIT | MEM_RESERVE | 271// with ERROR_INVALID_PARAMETER (measured on Windows 11 26200: VirtualAlloc(NULL, 64 KiB, MEM_COMMIT | MEM_RESERVE |
@@ -258,4 +305,5 @@ SHIM_TABLE(xmem,
258 {"xmem.dll", "XMemVirtualAlloc", reinterpret_cast<void*>(&XMemVirtualAlloc)}, 305 {"xmem.dll", "XMemVirtualAlloc", reinterpret_cast<void*>(&XMemVirtualAlloc)},
259 {"xmem.dll", "XMemGetWriteWatch", reinterpret_cast<void*>(&XMemGetWriteWatch)}, 306 {"xmem.dll", "XMemGetWriteWatch", reinterpret_cast<void*>(&XMemGetWriteWatch)},
260 {"xmem.dll", "XMemResetWriteWatch", reinterpret_cast<void*>(&XMemResetWriteWatch)}, 307 {"xmem.dll", "XMemResetWriteWatch", reinterpret_cast<void*>(&XMemResetWriteWatch)},
308 {"xmem.dll", "XMemTransferMemory", reinterpret_cast<void*>(&XMemTransferMemory)},
261); 309);
diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp
index bd38cab39..aa9ba1d31 100644
--- a/runtime/test/xmem_test.cpp
+++ b/runtime/test/xmem_test.cpp
@@ -4,6 +4,8 @@
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).
7#include <windows.h> 9#include <windows.h>
8#include <psapi.h> 10#include <psapi.h>
9 11
@@ -11,6 +13,7 @@
11#include <cstdio> 13#include <cstdio>
12#include <cstring> 14#include <cstring>
13#include <fstream> 15#include <fstream>
16#include <limits>
14#include <sstream> 17#include <sstream>
15#include <string> 18#include <string>
16 19
@@ -27,6 +30,9 @@ using XMemGetWorkingSetStatisticsFn = BOOL(__stdcall*)(uint32_t, void*);
27using XMemVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD); 30using XMemVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD);
28using XMemGetWriteWatchFn = UINT(WINAPI*)(DWORD, void*, SIZE_T, void**, ULONG_PTR*, ULONG*); 31using XMemGetWriteWatchFn = UINT(WINAPI*)(DWORD, void*, SIZE_T, void**, ULONG_PTR*, ULONG*);
29using XMemResetWriteWatchFn = UINT(WINAPI*)(void*, SIZE_T); 32using XMemResetWriteWatchFn = UINT(WINAPI*)(void*, SIZE_T);
33// BOOL XMemTransferMemory(XMEM_TRANSFER_TYPE, SIZE_T): the shape Microsoft's public NetRumble and NativeAOT-Xbox
34// samples call (see runtime/shims/xmem.cpp).
35using XMemTransferMemoryFn = BOOL(WINAPI*)(uint32_t, SIZE_T);
30constexpr uint32_t kMeasuredKind = 0x20000001; 36constexpr uint32_t kMeasuredKind = 0x20000001;
31 37
32int g_checks = 0; 38int g_checks = 0;
@@ -266,6 +272,88 @@ void test_attribute_trace(XMemAllocFn alloc, XMemFreeFn free_mem) {
266 DeleteFileW(path.c_str()); 272 DeleteFileW(path.c_str());
267} 273}
268 274
275// XMemTransferMemory moves budget between the console's title and system partitions; a PC has neither, so the shim
276// succeeds for every direction and size and moves (allocates) nothing. The XMEM_TRANSFER_TYPE values are not public,
277// so the directions here are just the first few enum values and one far outside any plausible range.
278void test_transfer_memory(XMemTransferMemoryFn transfer) {
279 constexpr SIZE_T kMiB = 1024 * 1024;
280 const uint32_t types[] = {0u, 1u, 2u, 0xffffffffu};
281 // 2 MiB and 40 MiB are the sizes the samples pass ("Must be multiples of 2MB sizes"); 0, an odd size and SIZE_MAX
282 // are the boundaries.
283 const SIZE_T sizes[] = {0, 2 * kMiB, 40 * kMiB, 2 * kMiB + 1, (std::numeric_limits<SIZE_T>::max)()};
284
285 PROCESS_MEMORY_COUNTERS_EX before{};
286 const bool have_before = GetProcessMemoryInfo(GetCurrentProcess(),
287 reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&before), sizeof(before));
288 bool all_true = true;
289 bool last_error_kept = true;
290 for (const uint32_t type : types) {
291 for (const SIZE_T size : sizes) {
292 SetLastError(0x2bad);
293 const BOOL result = transfer(type, size);
294 if (result != TRUE) {
295 all_true = false;
296 std::printf(" XMemTransferMemory(%u, %zu) -> %d\n", type, static_cast<size_t>(size), result);
297 }
298 last_error_kept &= GetLastError() == 0x2bad;
299 }
300 }
301 check(all_true, "XMemTransferMemory returns TRUE (1) for every direction and size, 0 and SIZE_MAX included");
302 check(last_error_kept, "XMemTransferMemory leaves the thread's last error alone");
303
304 PROCESS_MEMORY_COUNTERS_EX after{};
305 const bool have_after = GetProcessMemoryInfo(GetCurrentProcess(),
306 reinterpret_cast<PROCESS_MEMORY_COUNTERS*>(&after), sizeof(after));
307 // 20 calls asked to move up to 40 MiB each; nothing may be committed for them. 1 MiB of slack covers the CRT's
308 // own buffers (the one-time stderr line).
309 check(have_before && have_after && after.PrivateUsage < before.PrivateUsage + kMiB,
310 "XMemTransferMemory commits no memory for the transferred sizes");
311
312 // A bool-returning declaration reads only AL: TRUE must be non-zero there as well.
313 const auto as_bool = reinterpret_cast<bool(WINAPI*)(uint32_t, SIZE_T)>(reinterpret_cast<void*>(transfer));
314 check(as_bool(0, 2 * kMiB), "XMemTransferMemory's result also reads as true through a bool return");
315
316 // The enum is 32 bits: garbage in the upper half of RCX must not change anything.
317 const auto wide = reinterpret_cast<BOOL(WINAPI*)(uint64_t, SIZE_T)>(reinterpret_cast<void*>(transfer));
318 check(wide(0xdead000000000000ull, 2 * kMiB) == TRUE, "XMemTransferMemory ignores the upper half of RCX");
319}
320
321// gta6rt --trace: one "xmem_transfer" event per distinct (type, size), none with the trace off.
322void test_transfer_trace(XMemTransferMemoryFn transfer) {
323 wchar_t temp[MAX_PATH];
324 GetTempPathW(MAX_PATH, temp);
325 const std::wstring path =
326 std::wstring(temp) + L"xmem_transfer_trace_test_" + std::to_wstring(GetCurrentProcessId()) + L".jsonl";
327 DeleteFileW(path.c_str());
328
329 check(transfer(7, 12345) == TRUE, "XMemTransferMemory with the trace off still returns TRUE");
330
331 check(rt::startup_trace::open(path.c_str()), "open the startup trace file");
332 transfer(0, 2097152);
333 transfer(0, 2097152); // same pair again: no second event
334 transfer(0, 41943040);
335 transfer(1, 2097152);
336 rt::startup_trace::close();
337
338 std::ifstream in(path);
339 std::stringstream text;
340 text << in.rdbuf();
341 const std::string log = text.str();
342 auto count = [&](const std::string& needle) {
343 int n = 0;
344 for (size_t at = log.find(needle); at != std::string::npos; at = log.find(needle, at + 1)) ++n;
345 return n;
346 };
347 check(count("\"kind\":\"xmem_transfer\"") == 3, "three xmem_transfer events: one per distinct (type, size)");
348 check(count("\"api\":\"XMemTransferMemory\",\"type\":0,\"size\":2097152") == 1,
349 "type 0 / 2 MiB is recorded once although it was called twice");
350 check(count("\"api\":\"XMemTransferMemory\",\"type\":0,\"size\":41943040") == 1, "type 0 / 40 MiB is recorded");
351 check(count("\"api\":\"XMemTransferMemory\",\"type\":1,\"size\":2097152") == 1, "type 1 / 2 MiB is recorded");
352 check(count("\"size\":12345") == 0, "nothing was recorded while the trace was off");
353 check(count("\"caller\":\"") == 3, "every transfer event names its caller");
354 DeleteFileW(path.c_str());
355}
356
269using HostVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, DWORD); 357using HostVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, DWORD);
270 358
271// RT-217: a title's kernel32!VirtualAlloc carries the console's MEM_GRAPHICS / MEM_TITLE type bits, which the host 359// RT-217: a title's kernel32!VirtualAlloc carries the console's MEM_GRAPHICS / MEM_TITLE type bits, which the host
@@ -319,6 +407,8 @@ int main() {
319 reinterpret_cast<XMemGetWriteWatchFn>(rt::shims::find("xmem.dll", "XMemGetWriteWatch")); 407 reinterpret_cast<XMemGetWriteWatchFn>(rt::shims::find("xmem.dll", "XMemGetWriteWatch"));
320 const auto reset_write_watch = 408 const auto reset_write_watch =
321 reinterpret_cast<XMemResetWriteWatchFn>(rt::shims::find("xmem.dll", "XMemResetWriteWatch")); 409 reinterpret_cast<XMemResetWriteWatchFn>(rt::shims::find("xmem.dll", "XMemResetWriteWatch"));
410 const auto transfer =
411 reinterpret_cast<XMemTransferMemoryFn>(rt::shims::find("xmem.dll", "XMemTransferMemory"));
322 412
323 check(alloc != nullptr, "registry exposes xmem.dll!XMemAlloc"); 413 check(alloc != nullptr, "registry exposes xmem.dll!XMemAlloc");
324 check(free_mem != nullptr, "registry exposes xmem.dll!XMemFree"); 414 check(free_mem != nullptr, "registry exposes xmem.dll!XMemFree");
@@ -327,6 +417,7 @@ int main() {
327 check(virtual_alloc != nullptr, "registry exposes xmem.dll!XMemVirtualAlloc"); 417 check(virtual_alloc != nullptr, "registry exposes xmem.dll!XMemVirtualAlloc");
328 check(get_write_watch != nullptr, "registry exposes xmem.dll!XMemGetWriteWatch"); 418 check(get_write_watch != nullptr, "registry exposes xmem.dll!XMemGetWriteWatch");
329 check(reset_write_watch != nullptr, "registry exposes xmem.dll!XMemResetWriteWatch"); 419 check(reset_write_watch != nullptr, "registry exposes xmem.dll!XMemResetWriteWatch");
420 check(transfer != nullptr, "registry exposes xmem.dll!XMemTransferMemory");
330 421
331 if (!alloc || !free_mem || !query || !get_stats) { 422 if (!alloc || !free_mem || !query || !get_stats) {
332 print_result(); 423 print_result();
@@ -340,6 +431,10 @@ int main() {
340 test_virtual_alloc(virtual_alloc, get_write_watch, reset_write_watch); 431 test_virtual_alloc(virtual_alloc, get_write_watch, reset_write_watch);
341 } 432 }
342 test_attribute_trace(alloc, free_mem); 433 test_attribute_trace(alloc, free_mem);
434 if (transfer) {
435 test_transfer_memory(transfer);
436 test_transfer_trace(transfer);
437 }
343 438
344 test_title_virtual_alloc(); 439 test_title_virtual_alloc();
345 440