upleb.uk

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

summaryrefslogtreecommitdiff
path: root/runtime/shims/xmem.cpp
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/shims/xmem.cpp
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/shims/xmem.cpp')
-rw-r--r--runtime/shims/xmem.cpp467
1 files changed, 437 insertions, 30 deletions
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);