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:
authoraslan2142 <jan.trencansky@protonmail.com>2026-11-25 02:37:19 +0100
committerGitHub <noreply@github.com>2026-11-25 02:37:19 +0100
commit18a22c1aefa227fd2eda047bab3385147d569f9d (patch)
tree74ad707a670f980da61b5b9e0bc9241dfd6ef181 /runtime/test/xmem_test.cpp
parent5a5df8e0b6bff458814c934e18f4216e69c40d36 (diff)
parent71a783e56fb6eb591849b5c9fb6618ed3af3f595 (diff)
Merge pull request #984 from Moriz82/integration/proton-story-load
[integration] Linux/Proton and native Windows: boot through the story load (RT-PROTON-STORY-LOAD)
Diffstat (limited to 'runtime/test/xmem_test.cpp')
-rw-r--r--runtime/test/xmem_test.cpp552
1 files changed, 544 insertions, 8 deletions
diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp
index 0c151bb9c..f7d766d4e 100644
--- a/runtime/test/xmem_test.cpp
+++ b/runtime/test/xmem_test.cpp
@@ -9,14 +9,18 @@
9// graphics protection bits and commits 2 MiB guest pages; the placeholder flags pass through; physical pages keep their 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. 10// contents across unmap and remap, alias when mapped twice, and scatter-map per address.
11#include <windows.h> 11#include <windows.h>
12#include <malloc.h>
12#include <psapi.h> 13#include <psapi.h>
13 14
14#include <atomic> 15#include <atomic>
15#include <cstdint> 16#include <cstdint>
16#include <cstdio> 17#include <cstdio>
18#include <cstdlib>
17#include <cstring> 19#include <cstring>
18#include <fstream> 20#include <fstream>
21#include <functional>
19#include <limits> 22#include <limits>
23#include <new>
20#include <sstream> 24#include <sstream>
21#include <string> 25#include <string>
22#include <thread> 26#include <thread>
@@ -25,6 +29,38 @@
25#include "shims.h" 29#include "shims.h"
26#include "startup_trace.h" 30#include "startup_trace.h"
27#include "xmem.h" 31#include "xmem.h"
32#include "../src/title_page_watch.h"
33
34// The process heap as test_heap_lock_faults needs it (the same gate as d3d12_existing_heap_test's): an allocation that
35// waits while a thread holds the heap's lock. The NT heap's low-fragmentation front end serves most small sizes
36// without that lock, so a real deadlock waits for an allocation its back end serves, which a short test can't count
37// on. Here, while the gate is on, every operator new and delete of the program (xmem.cpp's included) takes
38// g_heap_gate shared, and the test's "title" threads that hold the heap's lock hold the gate exclusively: any
39// allocation xmem makes while it holds a lock its fault handler waits for then deadlocks at once.
40namespace {
41SRWLOCK g_heap_gate = SRWLOCK_INIT;
42std::atomic<bool> g_heap_gate_on{false};
43struct HeapGate {
44 const bool on = g_heap_gate_on.load(std::memory_order_acquire);
45 HeapGate() {
46 if (on) AcquireSRWLockShared(&g_heap_gate);
47 }
48 ~HeapGate() {
49 if (on) ReleaseSRWLockShared(&g_heap_gate);
50 }
51};
52} // namespace
53
54void* operator new(std::size_t bytes) {
55 HeapGate gate;
56 if (void* p = std::malloc(bytes ? bytes : 1)) return p;
57 throw std::bad_alloc();
58}
59void operator delete(void* p) noexcept {
60 HeapGate gate;
61 std::free(p);
62}
63void operator delete(void* p, std::size_t) noexcept { operator delete(p); }
28 64
29namespace { 65namespace {
30 66
@@ -363,6 +399,24 @@ bool reserved_only(const void* address) {
363 return VirtualQuery(address, &info, sizeof(info)) && info.State == MEM_RESERVE; 399 return VirtualQuery(address, &info, sizeof(info)) && info.State == MEM_RESERVE;
364} 400}
365 401
402// The address is inside a section view (whatever state the host reports for its pages), not a bare reservation.
403bool in_view(const void* address) {
404 MEMORY_BASIC_INFORMATION info{};
405 return VirtualQuery(address, &info, sizeof(info)) && info.Type == MEM_MAPPED;
406}
407
408// Physical pages are views of a reserved section and are committed on first touch. Windows then reports the page as
409// MEM_COMMIT with its protection. Wine's VirtualQuery keeps reporting MEM_RESERVE and no protection for a view page
410// that has been written and reads back, so a check of the reported state and protection has nothing to look at
411// there. True for exactly that answer on that host; the caller says what it skips.
412bool touched_view_reported_reserved(const MEMORY_BASIC_INFORMATION& info) {
413 static const bool wine = [] {
414 const HMODULE ntdll = GetModuleHandleW(L"ntdll.dll");
415 return ntdll && GetProcAddress(ntdll, "wine_get_version") != nullptr;
416 }();
417 return wine && info.Type == MEM_MAPPED && info.State == MEM_RESERVE && info.Protect == 0;
418}
419
366struct PhysicalApi { 420struct PhysicalApi {
367 XMemVirtualAllocFn virtual_alloc; 421 XMemVirtualAllocFn virtual_alloc;
368 XMemAllocatePhysicalPagesFn allocate; 422 XMemAllocatePhysicalPagesFn allocate;
@@ -395,17 +449,46 @@ void test_physical_pages(const PhysicalApi& api) {
395 } 449 }
396 check(numbers_ok, "page numbers are distinct non-zero multiples of 16 below 2^25"); 450 check(numbers_ok, "page numbers are distinct non-zero multiples of 16 below 2^25");
397 451
452 auto generation = leonida::title_memory_map::generation();
398 check(api.map(window, kPages, pages) == window, "XMemMapPhysicalPages returns the address it mapped"); 453 check(api.map(window, kPages, pages) == window, "XMemMapPhysicalPages returns the address it mapped");
454 check(leonida::title_memory_map::generation() != generation, "mapping physical pages invalidates shadows");
399 for (uint64_t i = 0; i < kPages; ++i) fill_page(window + i * kPage64k, 0x1000u * static_cast<uint32_t>(i + 1)); 455 for (uint64_t i = 0; i < kPages; ++i) fill_page(window + i * kPage64k, 0x1000u * static_cast<uint32_t>(i + 1));
400 { 456 {
401 MEMORY_BASIC_INFORMATION info{}; 457 MEMORY_BASIC_INFORMATION info{};
402 VirtualQuery(window, &info, sizeof(info)); 458 VirtualQuery(window, &info, sizeof(info));
403 check(info.State == MEM_COMMIT && info.Type == MEM_MAPPED && info.Protect == PAGE_READWRITE, 459 if (touched_view_reported_reserved(info)) {
404 "a mapped page is a read-write view with the window's protection"); 460 std::printf("SKIP the mapped page's reported state and protection: this host's VirtualQuery shows a "
461 "written view page as reserved (Wine)\n");
462 check(info.Type == MEM_MAPPED && info.AllocationProtect == PAGE_READWRITE &&
463 page_holds(window, 0x1000u),
464 "a mapped page is a read-write view that holds what was written");
465 } else {
466 check(info.State == MEM_COMMIT && info.Type == MEM_MAPPED && info.Protect == PAGE_READWRITE,
467 "a mapped page is a read-write view with the window's protection");
468 }
469 check(info.AllocationBase == window && info.RegionSize == kPages * kPage64k,
470 "consecutive pages of one allocation are mapped as one view");
405 } 471 }
406 472
473 // A page unmapped or remapped inside that view splits it; its neighbours keep their pages.
474 void* const middle = window + kPage64k;
475 generation = leonida::title_memory_map::generation();
476 check(api.scatter(&middle, 1, nullptr) == TRUE && reserved_only(window + kPage64k),
477 "a page inside a view unmaps on its own");
478 check(page_holds(window, 0x1000u) && page_holds(window + 2 * kPage64k, 0x3000u) &&
479 page_holds(window + 3 * kPage64k, 0x4000u),
480 "the pages around it stay mapped with their contents");
481 check(leonida::title_memory_map::generation() != generation, "scatter unmapping invalidates shadows");
482 check(api.map(middle, 1, &pages[1]) == middle && page_holds(window + kPage64k, 0x2000u),
483 "a page maps again into the gap");
484
407 check(api.map(window, kPages, nullptr) == window, "XMemMapPhysicalPages with no page array unmaps"); 485 check(api.map(window, kPages, nullptr) == window, "XMemMapPhysicalPages with no page array unmaps");
408 check(reserved_only(window) && reserved_only(window + 3 * kPage64k), "unmapped pages are reserved again"); 486 check(reserved_only(window) && reserved_only(window + 3 * kPage64k), "unmapped pages are reserved again");
487 // The split above left the range as several host placeholders; the whole run maps again over them.
488 check(api.map(window, kPages, pages) == window && page_holds(window, 0x1000u) &&
489 page_holds(window + 3 * kPage64k, 0x4000u),
490 "a run maps again over a range an earlier partial unmap split");
491 check(api.map(window, kPages, nullptr) == window && reserved_only(window), "and unmaps again");
409 492
410 // Remap in reverse order into the other window: each page keeps its contents. 493 // Remap in reverse order into the other window: each page keeps its contents.
411 uint64_t reversed[kPages]; 494 uint64_t reversed[kPages];
@@ -650,9 +733,11 @@ void test_first_touch_during_remap(const PhysicalApi& api) {
650 std::atomic<bool> stop{false}; 733 std::atomic<bool> stop{false};
651 std::atomic<uint64_t> touches{0}; 734 std::atomic<uint64_t> touches{0};
652 std::atomic<uint64_t> unmapped_faults{0}; 735 std::atomic<uint64_t> unmapped_faults{0};
736 std::atomic<int> started_writers{0};
653 std::vector<std::thread> writers; 737 std::vector<std::thread> writers;
654 for (int t = 0; t < 4; ++t) { 738 for (int t = 0; t < 4; ++t) {
655 writers.emplace_back([&, t] { 739 writers.emplace_back([&, t] {
740 started_writers.fetch_add(1);
656 uint64_t i = static_cast<uint64_t>(t); 741 uint64_t i = static_cast<uint64_t>(t);
657 while (!stop.load(std::memory_order_relaxed)) { 742 while (!stop.load(std::memory_order_relaxed)) {
658 auto* const word = 743 auto* const word =
@@ -666,6 +751,8 @@ void test_first_touch_during_remap(const PhysicalApi& api) {
666 } 751 }
667 }); 752 });
668 } 753 }
754 // The remaps can finish before a writer is scheduled on a fast host, so wait for all four to run first.
755 while (started_writers.load() < 4) Sleep(0);
669 const ULONGLONG started = GetTickCount64(); 756 const ULONGLONG started = GetTickCount64();
670 bool remapped = true; 757 bool remapped = true;
671 for (uint64_t s = 0; s < kSlices; ++s) { 758 for (uint64_t s = 0; s < kSlices; ++s) {
@@ -674,6 +761,8 @@ void test_first_touch_during_remap(const PhysicalApi& api) {
674 remapped &= api.map(window, kSlice, nullptr) == window; 761 remapped &= api.map(window, kSlice, nullptr) == window;
675 } 762 }
676 remapped &= api.map(window, kSlice, pages.data() + (kSlices - 1) * kSlice) == window; 763 remapped &= api.map(window, kSlice, pages.data() + (kSlices - 1) * kSlice) == window;
764 // The last slice stays mapped: give the writers up to a second to land a write in it before stopping them.
765 for (const ULONGLONG until = GetTickCount64() + 1000; touches.load() == 0 && GetTickCount64() < until;) Sleep(1);
677 stop.store(true); 766 stop.store(true);
678 for (auto& writer : writers) writer.join(); 767 for (auto& writer : writers) writer.join();
679 const ULONGLONG elapsed = GetTickCount64() - started; 768 const ULONGLONG elapsed = GetTickCount64() - started;
@@ -689,6 +778,102 @@ void test_first_touch_during_remap(const PhysicalApi& api) {
689 check(api.free_pages(count, pages.data()) == TRUE, "XMemFreePhysicalPages frees the remap race pages"); 778 check(api.free_pages(count, pages.data()) == TRUE, "XMemFreePhysicalPages frees the remap race pages");
690} 779}
691 780
781// Splitting a view briefly unmaps the view's other pages; a thread reading one of them meanwhile must not fault.
782// Unmapping page k of the view [k, end) splits it every time, and the last page of each view is the one being read.
783void test_split_under_reader(const PhysicalApi& api) {
784 constexpr uint64_t kPages = 2048; // two capped views
785 auto* const window = static_cast<uint8_t*>(
786 api.virtual_alloc(nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE));
787 std::vector<uint64_t> pages(kPages);
788 uint64_t count = kPages;
789 check(window && api.allocate(0x280, &count, pages.data()) == TRUE && count == kPages &&
790 api.map(window, kPages, pages.data()) == window,
791 "a 2,048-page run maps for the split test");
792 if (!window || count != kPages) return;
793 uint8_t* const read_pages[2] = {window + 1023 * kPage64k, window + 2047 * kPage64k};
794 fill_page(read_pages[0], 0x11000u);
795 fill_page(read_pages[1], 0x11000u);
796 std::atomic<bool> done{false};
797 std::atomic<uint64_t> reads{0}, wrong{0};
798 std::thread reader([&] {
799 for (uint64_t i = 0; !done.load(std::memory_order_relaxed); ++i) {
800 wrong += read_u32(read_pages[i & 1], 0) != 0x11000u;
801 ++reads;
802 }
803 });
804 bool unmapped = true;
805 for (uint64_t k = 0; k < kPages - 1; ++k) {
806 if (k == 1023) continue;
807 void* const page = window + k * kPage64k;
808 unmapped &= api.scatter(&page, 1, nullptr) == TRUE;
809 }
810 done = true;
811 reader.join();
812 check(unmapped, "2,046 pages unmap one at a time, each splitting the view a reader is in");
813 check(reads.load() > 0 && wrong.load() == 0, "the reader of the views' last pages never faults or misreads");
814 // The last split was of [2046, 2048): a fault there is retried, one on another mapped page is not.
815 api.map(window, kPages, nullptr);
816 api.free_pages(kPages, pages.data());
817}
818
819// A run longer than one host view is mapped as capped views, so unmapping one page inside it only remaps the rest of
820// that view; every other page keeps its contents.
821void test_long_run(const PhysicalApi& api) {
822 constexpr uint64_t kPages = 1100; // more than the 1024-page view cap
823 auto* const window = static_cast<uint8_t*>(
824 api.virtual_alloc(nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE));
825 std::vector<uint64_t> pages(kPages);
826 uint64_t count = kPages;
827 check(window && api.allocate(0x280, &count, pages.data()) == TRUE, "a long run's window and pages are allocated");
828 if (!window || count != kPages) return;
829 check(api.map(window, kPages, pages.data()) == window, "a run longer than the view cap maps");
830 // The pages are committed on first touch, so an untouched view reads MEM_RESERVE on Windows (Wine reports
831 // MEM_COMMIT); either way the first region is one mapped view of exactly the cap.
832 MEMORY_BASIC_INFORMATION info{};
833 VirtualQuery(window, &info, sizeof(info));
834 check(info.Type == MEM_MAPPED && (info.State == MEM_COMMIT || info.State == MEM_RESERVE) &&
835 info.RegionSize == 1024 * kPage64k,
836 "it is mapped as views of at most 1024 pages");
837 for (uint64_t i = 0; i < kPages; ++i) fill_page(window + i * kPage64k, static_cast<uint32_t>(i + 1));
838 void* const hole = window + 10 * kPage64k;
839 check(api.scatter(&hole, 1, nullptr) == TRUE && reserved_only(hole), "a page inside the first view unmaps");
840 bool kept = true;
841 for (uint64_t i = 0; i < kPages; ++i) {
842 if (i != 10) kept &= page_holds(window + i * kPage64k, static_cast<uint32_t>(i + 1));
843 }
844 check(kept, "every other page of the run keeps its contents");
845 // Several pages across the boundary of two capped views unmap together; the pages on both sides stay.
846 check(api.map(window + 1000 * kPage64k, 50, nullptr) == window + 1000 * kPage64k &&
847 reserved_only(window + 1000 * kPage64k) && reserved_only(window + 1049 * kPage64k),
848 "a multi-page range across two views unmaps");
849 check(page_holds(window + 999 * kPage64k, 1000u) && page_holds(window + 1050 * kPage64k, 1051u),
850 "the pages on both sides of it keep their contents");
851 // Mapping other pages over the middle of a live run replaces just those pages.
852 check(api.map(window + 500 * kPage64k, 3, &pages[600]) == window + 500 * kPage64k &&
853 page_holds(window + 500 * kPage64k, 601u) && page_holds(window + 502 * kPage64k, 603u),
854 "pages mapped over the middle of a live run replace it there");
855 check(page_holds(window + 499 * kPage64k, 500u) && page_holds(window + 503 * kPage64k, 504u),
856 "and the run's pages around them keep their contents");
857 check(api.map(window, kPages, nullptr) == window && reserved_only(window) &&
858 reserved_only(window + (kPages - 1) * kPage64k),
859 "the whole run unmaps");
860 check(api.free_pages(kPages, pages.data()) == TRUE, "the long run's pages are freed");
861 check(api.map(window, 1, pages.data()) == nullptr && reserved_only(window), "a freed page does not map again");
862 // Pages freed while still mapped keep their memory, and splitting their view later still maps the rest again.
863 count = 4;
864 check(api.allocate(0x280, &count, pages.data()) == TRUE && count == 4 && api.map(window, 4, pages.data()) == window,
865 "four pages map as one view");
866 if (count != 4) return;
867 for (uint64_t i = 0; i < 4; ++i) fill_page(window + i * kPage64k, static_cast<uint32_t>(i + 1));
868 check(api.free_pages(4, pages.data()) == TRUE, "they are freed while mapped");
869 void* const second = window + kPage64k;
870 check(api.scatter(&second, 1, nullptr) == TRUE && in_view(window) && !in_view(second) &&
871 in_view(window + 2 * kPage64k) && page_holds(window, 1u) &&
872 page_holds(window + 2 * kPage64k, 3u) && page_holds(window + 3 * kPage64k, 4u),
873 "unmapping one of them afterwards keeps the others' memory");
874 api.map(window, 4, nullptr);
875}
876
692// The placeholder flags pass through: reserve a placeholder, carve windows and committed memory out of it. 877// The placeholder flags pass through: reserve a placeholder, carve windows and committed memory out of it.
693void test_placeholders(const PhysicalApi& api) { 878void test_placeholders(const PhysicalApi& api) {
694 auto* const base = static_cast<uint8_t*>( 879 auto* const base = static_cast<uint8_t*>(
@@ -744,8 +929,12 @@ void test_write_combine_window(const PhysicalApi& api) {
744 *static_cast<volatile unsigned char*>(window) = 1; 929 *static_cast<volatile unsigned char*>(window) = 1;
745 MEMORY_BASIC_INFORMATION info{}; 930 MEMORY_BASIC_INFORMATION info{};
746 VirtualQuery(window, &info, sizeof(info)); 931 VirtualQuery(window, &info, sizeof(info));
747 check(info.State == MEM_COMMIT && info.Protect == PAGE_READWRITE, 932 if (touched_view_reported_reserved(info))
748 "the page mapped there is a plain read-write view"); 933 std::printf("SKIP the write-combine window page's reported state and protection: this host's "
934 "VirtualQuery shows a written view page as reserved (Wine)\n");
935 else
936 check(info.State == MEM_COMMIT && info.Protect == PAGE_READWRITE,
937 "the page mapped there is a plain read-write view");
749 fill_page(window, 0x77000000u); 938 fill_page(window, 0x77000000u);
750 check(page_holds(window, 0x77000000u), "the page in the write-combine window holds data"); 939 check(page_holds(window, 0x77000000u), "the page in the write-combine window holds data");
751 } 940 }
@@ -753,6 +942,168 @@ void test_write_combine_window(const PhysicalApi& api) {
753 check(api.free_pages(1, &page) == TRUE, "free the write-combine window's page"); 942 check(api.free_pages(1, &page) == TRUE, "free the write-combine window's page");
754} 943}
755 944
945// Counts the access violations in [g_counted_begin, g_counted_end). Added after xmem's handler with First = 1, so it
946// runs before it and sees every fault there, the ones xmem then commits included.
947std::atomic<uintptr_t> g_counted_begin{0}, g_counted_end{0};
948std::atomic<uint64_t> g_counted_faults{0};
949
950LONG CALLBACK count_window_faults(EXCEPTION_POINTERS* info) {
951 const EXCEPTION_RECORD* record = info ? info->ExceptionRecord : nullptr;
952 if (record && record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && record->NumberParameters >= 2) {
953 const auto at = static_cast<uintptr_t>(record->ExceptionInformation[1]);
954 if (at >= g_counted_begin.load(std::memory_order_relaxed) && at < g_counted_end.load(std::memory_order_relaxed))
955 g_counted_faults.fetch_add(1, std::memory_order_relaxed);
956 }
957 return EXCEPTION_CONTINUE_SEARCH;
958}
959
960// About `us` microseconds of spinning, without a call that could allocate.
961void spin_for(LONGLONG us) {
962 LARGE_INTEGER now{}, frequency{};
963 QueryPerformanceFrequency(&frequency);
964 QueryPerformanceCounter(&now);
965 const LONGLONG until = now.QuadPart + frequency.QuadPart * us / 1000000;
966 while (QueryPerformanceCounter(&now) && now.QuadPart < until) YieldProcessor();
967}
968
969// Title threads take access violations while they hold the process heap's lock: XMemAlloc is _aligned_malloc, so
970// HeapAlloc and HeapFree write block headers on title pages, which may be physical pages waiting for their first touch
971// or pages the D3D12 layer's shadows guard. xmem's handler waits for g_fault_lock (shared) at every access violation,
972// its own or not, so whoever holds that lock exclusively (a map or an unmap of physical pages) must never wait for the
973// process heap meanwhile: it would wait for the faulting thread, which waits for it. While
974// - threads take the process heap's lock (HeapLock, as HeapAlloc does inside, and the heap gate above) and, holding
975// it, _aligned_malloc and _aligned_free and write a word into every page of a window whose pages are mapped fresh
976// all the time (a first-touch commit, or a fault on a page that is being unmapped) and into a read-only page (a
977// fault that isn't xmem's, as on a guarded shadow page);
978// - threads allocate physical pages, map them into their part of the window (as a run, or page by page through the
979// scatter call), and unmap and free them, some freed while still mapped so that the unmap drops the last
980// reference to their section;
981// a watchdog ends the process (exit code 3) when nothing got anywhere for 30 s: a deadlock.
982void test_heap_lock_faults(const PhysicalApi& api) {
983 if (const HMODULE ntdll = GetModuleHandleW(L"ntdll.dll"); ntdll && GetProcAddress(ntdll, "wine_get_version")) {
984 // Under Wine a holder of the fault lock still reaches the process heap through the host's own view calls (or
985 // Wine's fault dispatch needs it): the test deadlocks there with the fix in. The Wine side is an open item.
986 std::printf("SKIP heap-lock faults under Wine: a fault-lock holder still waits for the process heap there\n");
987 return;
988 }
989 constexpr uint64_t kMappers = 2, kSlice = 4, kPages = kMappers * kSlice;
990 constexpr unsigned kTouchers = 3;
991 auto* const window = static_cast<uint8_t*>(
992 api.virtual_alloc(nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x21, PAGE_READWRITE));
993 auto* const read_only = static_cast<uint8_t*>(VirtualAlloc(nullptr, 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_READONLY));
994 check(window != nullptr && read_only != nullptr, "a window and a read-only page for the heap-lock faults");
995 if (!window || !read_only) return;
996 g_counted_begin = reinterpret_cast<uintptr_t>(window);
997 g_counted_end = reinterpret_cast<uintptr_t>(window) + kPages * kPage64k;
998 g_counted_faults = 0;
999 // xmem's handler is in by now (the first XMemAllocatePhysicalPages put it in), so this one runs first.
1000 void* const counter = AddVectoredExceptionHandler(1, &count_window_faults);
1001 check(counter != nullptr, "a fault counter in front of xmem's handler");
1002 if (!counter) return;
1003
1004 std::atomic<uint64_t> progress{0}; // bumped by every round of every thread
1005 std::atomic<bool> stop{false}, finished{false}, failed{false};
1006 std::thread watchdog([&] {
1007 uint64_t seen = progress.load();
1008 ULONGLONG since = GetTickCount64();
1009 while (!finished.load()) {
1010 Sleep(100);
1011 const uint64_t now = progress.load();
1012 if (now != seen) {
1013 seen = now;
1014 since = GetTickCount64();
1015 } else if (GetTickCount64() - since > 30000) {
1016 // No heap here: the process heap may be what is stuck.
1017 static const char message[] =
1018 "xmem heap-lock faults: no progress for 30 s: deadlock (a holder of the lock xmem's fault handler "
1019 "waits for is waiting for the process heap)\n";
1020 DWORD wrote = 0;
1021 WriteFile(GetStdHandle(STD_ERROR_HANDLE), message, DWORD(sizeof(message) - 1), &wrote, nullptr);
1022 TerminateProcess(GetCurrentProcess(), 3);
1023 }
1024 }
1025 });
1026 std::atomic<uint64_t> rounds{0}, missed{0}, read_only_faults{0}, maps{0};
1027 std::vector<std::thread> threads;
1028 threads.reserve(kTouchers + kMappers);
1029 g_heap_gate_on = true;
1030 for (unsigned t = 0; t < kTouchers; ++t)
1031 threads.emplace_back([&, t] {
1032 const HANDLE heap = GetProcessHeap();
1033 for (unsigned round = 0; !stop.load(std::memory_order_relaxed); ++round) {
1034 uint64_t round_missed = 0;
1035 bool round_read_only = false;
1036 AcquireSRWLockExclusive(&g_heap_gate);
1037 HeapLock(heap);
1038 void* block = _aligned_malloc(64 + (round % 32) * 160, 16);
1039 for (uint64_t p = 0; p < kPages; ++p) {
1040 auto* const word =
1041 static_cast<volatile uint32_t*>(static_cast<void*>(window + p * kPage64k)) + t;
1042 round_missed += access_faults(word, true);
1043 }
1044 round_read_only = access_faults(static_cast<volatile uint32_t*>(static_cast<void*>(read_only)), true);
1045 _aligned_free(block);
1046 HeapUnlock(heap);
1047 ReleaseSRWLockExclusive(&g_heap_gate);
1048 missed.fetch_add(round_missed, std::memory_order_relaxed);
1049 read_only_faults.fetch_add(round_read_only, std::memory_order_relaxed);
1050 rounds.fetch_add(1, std::memory_order_relaxed);
1051 progress.fetch_add(1, std::memory_order_relaxed);
1052 spin_for(50); // the other threads get to allocate
1053 }
1054 });
1055 for (uint64_t m = 0; m < kMappers; ++m)
1056 threads.emplace_back([&, m] {
1057 uint8_t* const slice = window + m * kSlice * kPage64k;
1058 uint64_t pages[kSlice]{};
1059 void* addresses[kSlice]{};
1060 for (uint64_t k = 0; k < kSlice; ++k) addresses[k] = slice + k * kPage64k;
1061 for (uint64_t round = 0; !stop.load(std::memory_order_relaxed); ++round) {
1062 uint64_t count = kSlice;
1063 if (api.allocate(0x280, &count, pages) != TRUE || count != kSlice) {
1064 failed = true;
1065 break;
1066 }
1067 bool ok = round % 2 == 0 ? api.map(slice, kSlice, pages) == slice
1068 : api.scatter(addresses, static_cast<uint32_t>(kSlice), pages) == TRUE;
1069 spin_for(100); // the touchers get to fault the fresh pages in
1070 // Freed while mapped: the unmap then drops the last reference to the section.
1071 const bool free_first = round % 3 == 0;
1072 if (free_first) ok &= api.free_pages(kSlice, pages) == TRUE;
1073 ok &= api.map(slice, kSlice, nullptr) == slice;
1074 if (!free_first) ok &= api.free_pages(kSlice, pages) == TRUE;
1075 if (!ok) {
1076 failed = true;
1077 break;
1078 }
1079 maps.fetch_add(1, std::memory_order_relaxed);
1080 progress.fetch_add(1, std::memory_order_relaxed);
1081 }
1082 });
1083 for (const ULONGLONG until = GetTickCount64() + 3000; !failed.load() && GetTickCount64() < until;) Sleep(10);
1084 stop = true;
1085 for (std::thread& thread : threads) thread.join();
1086 g_heap_gate_on = false;
1087 finished = true;
1088 watchdog.join();
1089 RemoveVectoredExceptionHandler(counter);
1090 g_counted_end = 0;
1091
1092 const uint64_t window_faults = g_counted_faults.load();
1093 // A fault in the window that the toucher's own handler didn't catch is one xmem's handler resolved: a first touch
1094 // (or a retry of one another toucher committed meanwhile).
1095 const uint64_t committed = window_faults > missed.load() ? window_faults - missed.load() : 0;
1096 check(!failed.load(), "physical pages allocate, map (run and scatter), unmap and free while faults hold the heap");
1097 check(maps.load() > 0 && rounds.load() > 0, "the mappers and the faulting threads both made progress");
1098 check(committed > 0, "threads holding the process heap's lock took first-touch faults xmem committed");
1099 check(read_only_faults.load() == rounds.load(), "every write to the read-only page faulted through xmem's handler");
1100 std::printf("heap-lock faults: %llu mappings, %llu rounds holding the process heap's lock, %llu first touches "
1101 "committed, %llu faults on unmapped pages: no deadlock\n",
1102 static_cast<unsigned long long>(maps.load()), static_cast<unsigned long long>(rounds.load()),
1103 static_cast<unsigned long long>(committed), static_cast<unsigned long long>(missed.load()));
1104 VirtualFree(read_only, 0, MEM_RELEASE);
1105}
1106
756// gta6rt --trace: one "xmem_attributes" event per distinct raw attribute word and API, none with the trace off. 1107// gta6rt --trace: one "xmem_attributes" event per distinct raw attribute word and API, none with the trace off.
757void test_attribute_trace(XMemAllocFn alloc, XMemFreeFn free_mem, XMemVirtualAllocFn virtual_alloc) { 1108void test_attribute_trace(XMemAllocFn alloc, XMemFreeFn free_mem, XMemVirtualAllocFn virtual_alloc) {
758 wchar_t temp[MAX_PATH]; 1109 wchar_t temp[MAX_PATH];
@@ -883,6 +1234,8 @@ void test_transfer_trace(XMemTransferMemoryFn transfer) {
883} 1234}
884 1235
885using HostVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, DWORD); 1236using HostVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, DWORD);
1237using HostVirtualFreeFn = BOOL(WINAPI*)(void*, SIZE_T, DWORD);
1238using HostVirtualProtectFn = BOOL(WINAPI*)(void*, SIZE_T, DWORD, PDWORD);
886 1239
887// RT-217: a title's kernel32!VirtualAlloc carries the console's MEM_GRAPHICS / MEM_TITLE type bits, which the host 1240// RT-217: a title's kernel32!VirtualAlloc carries the console's MEM_GRAPHICS / MEM_TITLE type bits, which the host
888// rejects. The registered shim has to drop them and still allocate. 1241// rejects. The registered shim has to drop them and still allocate.
@@ -892,18 +1245,30 @@ void test_title_virtual_alloc() {
892 const char* const dlls[] = {"kernel32.dll", "kernelbase.dll", "api-ms-win-core-memory-l1-1-0.dll"}; 1245 const char* const dlls[] = {"kernel32.dll", "kernelbase.dll", "api-ms-win-core-memory-l1-1-0.dll"};
893 for (const char* dll : dlls) { 1246 for (const char* dll : dlls) {
894 const auto alloc = reinterpret_cast<HostVirtualAllocFn>(rt::shims::find(dll, "VirtualAlloc")); 1247 const auto alloc = reinterpret_cast<HostVirtualAllocFn>(rt::shims::find(dll, "VirtualAlloc"));
1248 const auto free = reinterpret_cast<HostVirtualFreeFn>(rt::shims::find(dll, "VirtualFree"));
1249 const auto protect = reinterpret_cast<HostVirtualProtectFn>(rt::shims::find(dll, "VirtualProtect"));
895 char what[160]; 1250 char what[160];
896 std::snprintf(what, sizeof what, "registry exposes %s!VirtualAlloc", dll); 1251 std::snprintf(what, sizeof what, "registry exposes %s's virtual memory shims", dll);
897 check(alloc != nullptr, what); 1252 check(alloc && free && protect, what);
898 if (!alloc) continue; 1253 if (!alloc || !free || !protect) continue;
899 1254
1255 auto generation = leonida::title_memory_map::generation();
900 void* const gfx = alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT, 0x2004); // PAGE_GRAPHICS_READWRITE 1256 void* const gfx = alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT, 0x2004); // PAGE_GRAPHICS_READWRITE
901 check(gfx != nullptr, "title VirtualAlloc with protect 0x2004 succeeds"); 1257 check(gfx != nullptr, "title VirtualAlloc with protect 0x2004 succeeds");
902 if (gfx) { 1258 if (gfx) {
1259 check(leonida::title_memory_map::generation() != generation, "title VirtualAlloc invalidates shadows");
903 MEMORY_BASIC_INFORMATION mbi{}; 1260 MEMORY_BASIC_INFORMATION mbi{};
904 check(VirtualQuery(gfx, &mbi, sizeof mbi) && mbi.Protect == PAGE_READWRITE, 1261 check(VirtualQuery(gfx, &mbi, sizeof mbi) && mbi.Protect == PAGE_READWRITE,
905 "protect 0x2004 commits PAGE_READWRITE"); 1262 "protect 0x2004 commits PAGE_READWRITE");
906 VirtualFree(gfx, 0, MEM_RELEASE); 1263 DWORD old = 0;
1264 generation = leonida::title_memory_map::generation();
1265 check(protect(gfx, 0x1000, PAGE_READONLY, &old) && old == PAGE_READWRITE,
1266 "title VirtualProtect changes protection and returns the previous protection");
1267 check(leonida::title_memory_map::generation() != generation, "title VirtualProtect invalidates shadows");
1268 generation = leonida::title_memory_map::generation();
1269 check(free(gfx, 0x1000, MEM_DECOMMIT), "title VirtualFree decommits a page");
1270 check(leonida::title_memory_map::generation() != generation, "title VirtualFree invalidates shadows");
1271 check(free(gfx, 0, MEM_RELEASE), "release the graphics allocation");
907 } 1272 }
908 for (const DWORD bits : {kMemGraphics, kMemTitle, kMemGraphics | kMemTitle, DWORD{0}}) { 1273 for (const DWORD bits : {kMemGraphics, kMemTitle, kMemGraphics | kMemTitle, DWORD{0}}) {
909 void* const p = alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT | bits, PAGE_READWRITE); 1274 void* const p = alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT | bits, PAGE_READWRITE);
@@ -918,6 +1283,171 @@ void test_title_virtual_alloc() {
918 } 1283 }
919} 1284}
920 1285
1286// The title's ordinary reservations are write-watched for the D3D12 layer's shadows (leonida::title_write_watch):
1287// XMemVirtualAlloc's plain, 2 MiB and 64 KiB committed regions and kernel32!VirtualAlloc's reservations, each recorded
1288// until the title releases it. Placeholders and physical-page windows are not (a section view can't be), nor is a
1289// region the title asked to be write-watched itself (its bits are the title's). With LEONIDA_WRITE_WATCH=0 (the
1290// xmem_no_write_watch test) nothing is.
1291void test_write_watched_reservations(XMemVirtualAllocFn virtual_alloc) {
1292 const bool on = leonida::title_write_watch::enabled();
1293 std::printf("xmem_test: write watching %s\n", on ? "on" : "off (LEONIDA_WRITE_WATCH=0)");
1294 const auto kernel_watching = [](void* base, SIZE_T size) {
1295 void* found[16]{};
1296 ULONG_PTR count = 16;
1297 ULONG granularity = 0;
1298 return GetWriteWatch(0, base, size, found, &count, &granularity) == 0;
1299 };
1300 const auto title_free = reinterpret_cast<HostVirtualFreeFn>(rt::shims::find("kernel32.dll", "VirtualFree"));
1301 const auto title_alloc = reinterpret_cast<HostVirtualAllocFn>(rt::shims::find("kernel32.dll", "VirtualAlloc"));
1302 check(title_free && title_alloc, "registry exposes kernel32.dll's VirtualAlloc and VirtualFree shims");
1303 if (!title_free || !title_alloc) return;
1304 struct Case {
1305 const char* what;
1306 DWORD type;
1307 SIZE_T size;
1308 bool watched;
1309 };
1310 const Case cases[] = {
1311 {"plain reserve+commit", MEM_RESERVE | MEM_COMMIT, 0x3000, true},
1312 {"commit at no address", MEM_COMMIT, 0x3000, true},
1313 {"reserve only", MEM_RESERVE, 0x20000, true},
1314 {"2 MiB pages", kXmemLargePages | MEM_RESERVE | MEM_COMMIT, kPage2m, true},
1315 {"64 KiB pages committed", kXmem64kPages | MEM_RESERVE | MEM_COMMIT, kPage64k * 2, true},
1316 {"64 KiB physical-page window", kXmem64kPages | MEM_RESERVE, kPage64k * 2, false},
1317 {"placeholder", MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, kPage64k * 2, false},
1318 {"the title's own write watch", MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, 0x3000, false},
1319 };
1320 for (const Case& c : cases) {
1321 void* const base = virtual_alloc(nullptr, c.size, c.type, 0, PAGE_READWRITE);
1322 char what[192];
1323 std::snprintf(what, sizeof what, "XMemVirtualAlloc %s succeeds", c.what);
1324 check(base != nullptr, what);
1325 if (!base) continue;
1326 const auto at = reinterpret_cast<uintptr_t>(base);
1327 const bool want = on && c.watched;
1328 std::snprintf(what, sizeof what, "XMemVirtualAlloc %s: %s for the shadows", c.what,
1329 want ? "recorded write-watched" : "not recorded");
1330 check(leonida::title_write_watch::contains(at) == want &&
1331 leonida::title_write_watch::contains(at + c.size - 1) == want,
1332 what);
1333 if (want) {
1334 std::snprintf(what, sizeof what, "XMemVirtualAlloc %s: the kernel write-watches it", c.what);
1335 check(kernel_watching(base, c.size), what);
1336 }
1337 if ((c.type & MEM_RESERVE_PLACEHOLDER) || ((c.type & kXmem64kPages) == kXmem64kPages && !(c.type & MEM_COMMIT))) {
1338 VirtualFree(base, 0, MEM_RELEASE);
1339 continue;
1340 }
1341 std::snprintf(what, sizeof what, "title VirtualFree releases the region (%s) and forgets it", c.what);
1342 check(title_free(base, 0, MEM_RELEASE) && !leonida::title_write_watch::contains(at), what);
1343 }
1344 // kernel32!VirtualAlloc as the title calls it: a reservation is recorded, a commit inside it adds nothing.
1345 void* const reserved = title_alloc(nullptr, 0x40000, MEM_RESERVE, PAGE_READWRITE);
1346 check(reserved != nullptr, "title VirtualAlloc reserves");
1347 if (!reserved) return;
1348 const auto at = reinterpret_cast<uintptr_t>(reserved);
1349 const auto generation = leonida::title_write_watch::generation();
1350 check(title_alloc(reserved, 0x1000, MEM_COMMIT, PAGE_READWRITE) == reserved, "title VirtualAlloc commits in it");
1351 check(leonida::title_write_watch::generation() == generation, "a commit inside a reservation records nothing new");
1352 check(leonida::title_write_watch::contains(at + 0x3ffff) == on,
1353 on ? "title VirtualAlloc's reservation is recorded write-watched" : "title VirtualAlloc's is not recorded");
1354 if (on) {
1355 check(kernel_watching(reserved, 0x40000), "the kernel write-watches title VirtualAlloc's reservation");
1356 static_cast<volatile uint8_t*>(reserved)[0x10] = 1;
1357 void* found[4]{};
1358 ULONG_PTR count = 4;
1359 ULONG granularity = 0;
1360 check(GetWriteWatch(0, reserved, 0x40000, found, &count, &granularity) == 0 && count == 1 &&
1361 found[0] == reserved,
1362 "a write to it is in the kernel's answer");
1363 } else {
1364 check(!kernel_watching(reserved, 0x40000), "LEONIDA_WRITE_WATCH=0: the kernel does not write-watch it");
1365 }
1366 check(title_free(reserved, 0, MEM_RELEASE) && !leonida::title_write_watch::contains(at),
1367 "title VirtualFree releases it and forgets it");
1368}
1369
1370// A reservation the title releases and reserves again at the same address is a new one to the shadows' journal
1371// (leonida::title_write_watch::ask): a reader that asked over the old one is told all of the new one's pages as
1372// written, though nothing wrote them (a new reservation's kernel bits are clear, and a MEM_RESERVE | MEM_COMMIT in one
1373// call marks nothing). Through kernel32!VirtualAlloc and XMemVirtualAlloc; a page decommitted and committed again
1374// inside a reservation is told as written too. And the title's XMemGetWriteWatch and XMemResetWriteWatch refuse a
1375// reservation write-watched for the shadows (on the console it is not write-watched, and a reset would clear the bits
1376// the shadows ask about): the journal still sees the write.
1377void test_write_watch_rereserve(XMemVirtualAllocFn virtual_alloc, XMemGetWriteWatchFn get_write_watch,
1378 XMemResetWriteWatchFn reset_write_watch) {
1379 if (!leonida::title_write_watch::enabled()) return;
1380 namespace ww = leonida::title_write_watch;
1381 const auto title_free = reinterpret_cast<HostVirtualFreeFn>(rt::shims::find("kernel32.dll", "VirtualFree"));
1382 const auto title_alloc = reinterpret_cast<HostVirtualAllocFn>(rt::shims::find("kernel32.dll", "VirtualAlloc"));
1383 if (!title_free || !title_alloc) return;
1384 constexpr SIZE_T kSize = 0x10000;
1385 // The pages of [base, base + kSize) the reader is told were written.
1386 const auto told = [](std::uint64_t reader, void* base) {
1387 const auto from = reinterpret_cast<uintptr_t>(base);
1388 const std::vector<std::pair<uintptr_t, uintptr_t>> runs{{from, from + kSize}};
1389 size_t pages = 0;
1390 ww::ask(
1391 reader, runs, [&](uintptr_t a, uintptr_t b) { pages += (b - a) / ww::kPage; }, [](uintptr_t, uintptr_t) {});
1392 return pages;
1393 };
1394 struct Way {
1395 const char* what;
1396 std::function<void*(void*)> reserve; // MEM_RESERVE | MEM_COMMIT at the address (null: anywhere)
1397 };
1398 const Way ways[] = {
1399 {"kernel32!VirtualAlloc",
1400 [&](void* at) { return title_alloc(at, kSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); }},
1401 {"XMemVirtualAlloc", [&](void* at) { return virtual_alloc(at, kSize, MEM_RESERVE | MEM_COMMIT, 0, PAGE_READWRITE); }},
1402 };
1403 char what[192];
1404 for (const Way& way : ways) {
1405 void* base = nullptr;
1406 std::uint64_t reader = 0;
1407 bool told_once = true, same_address = false;
1408 // Another thread may take the range between the release and the new reservation: tried again elsewhere.
1409 for (int attempt = 0; attempt < 8 && !same_address; ++attempt) {
1410 base = way.reserve(nullptr);
1411 if (!base) break;
1412 reader = ww::open_reader();
1413 static_cast<volatile uint8_t*>(base)[0x10] = 1;
1414 told_once = told_once && told(reader, base) == 1 && told(reader, base) == 0;
1415 void* const again = title_free(base, 0, MEM_RELEASE) ? way.reserve(base) : nullptr;
1416 same_address = again == base;
1417 if (!same_address) {
1418 ww::close_reader(reader);
1419 if (again) title_free(again, 0, MEM_RELEASE);
1420 }
1421 }
1422 std::snprintf(what, sizeof what, "%s: a write to a new reservation is told once", way.what);
1423 check(told_once, what);
1424 std::snprintf(what, sizeof what, "%s: released and reserved again at the same address", way.what);
1425 check(same_address, what);
1426 if (!same_address) continue;
1427 std::snprintf(what, sizeof what, "%s: the new reservation's pages are all told as written", way.what);
1428 check(told(reader, base) == kSize / ww::kPage, what);
1429 check(told(reader, base) == 0, "and only once");
1430 std::snprintf(what, sizeof what, "%s: a page decommitted and committed again is told as written", way.what);
1431 check(title_free(static_cast<uint8_t*>(base) + 0x3000, 0x1000, MEM_DECOMMIT) &&
1432 title_alloc(static_cast<uint8_t*>(base) + 0x3000, 0x1000, MEM_COMMIT, PAGE_READWRITE) &&
1433 told(reader, base) == 1,
1434 what);
1435 // The title's own write-watch calls leave the shadows' bits alone.
1436 static_cast<volatile uint8_t*>(base)[0x5010] = 1;
1437 void* found[16]{};
1438 ULONG_PTR count = 16;
1439 ULONG granularity = 0;
1440 std::snprintf(what, sizeof what, "%s: XMemResetWriteWatch and XMemGetWriteWatch refuse the shadows' reservation",
1441 way.what);
1442 check(reset_write_watch(base, kSize) != 0 &&
1443 get_write_watch(WRITE_WATCH_FLAG_RESET, base, kSize, found, &count, &granularity) != 0,
1444 what);
1445 check(told(reader, base) == 1, "the write is still told to the shadows");
1446 ww::close_reader(reader);
1447 title_free(base, 0, MEM_RELEASE);
1448 }
1449}
1450
921void print_result() { 1451void print_result() {
922 if (g_failures == 0) { 1452 if (g_failures == 0) {
923 std::printf("xmem_test: OK (%d checks)\n", g_checks); 1453 std::printf("xmem_test: OK (%d checks)\n", g_checks);
@@ -992,6 +1522,9 @@ int main() {
992 } 1522 }
993 1523
994 test_title_virtual_alloc(); 1524 test_title_virtual_alloc();
1525 if (virtual_alloc) test_write_watched_reservations(virtual_alloc);
1526 if (virtual_alloc && get_write_watch && reset_write_watch)
1527 test_write_watch_rereserve(virtual_alloc, get_write_watch, reset_write_watch);
995 1528
996 if (alloc_default && free_default) test_default_alloc(alloc, free_mem, alloc_default, free_default); 1529 if (alloc_default && free_default) test_default_alloc(alloc, free_mem, alloc_default, free_default);
997 if (tools_mem) check(tools_mem() == FALSE, "XMemIsToolsMemAvailable returns FALSE (no devkit tools memory)"); 1530 if (tools_mem) check(tools_mem() == FALSE, "XMemIsToolsMemAvailable returns FALSE (no devkit tools memory)");
@@ -1000,8 +1533,11 @@ int main() {
1000 test_physical_pages_commit_on_touch(physical); 1533 test_physical_pages_commit_on_touch(physical);
1001 test_commit_physical_pages(physical); 1534 test_commit_physical_pages(physical);
1002 test_first_touch_during_remap(physical); 1535 test_first_touch_during_remap(physical);
1536 test_long_run(physical);
1537 test_split_under_reader(physical);
1003 test_placeholders(physical); 1538 test_placeholders(physical);
1004 test_write_combine_window(physical); 1539 test_write_combine_window(physical);
1540 test_heap_lock_faults(physical);
1005 } 1541 }
1006 1542
1007 print_result(); 1543 print_result();