diff options
| author | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-24 20:09:14 -0500 |
|---|---|---|
| committer | Jan Trencansky <jan.trencansky@protonmail.com> | 2026-11-24 20:09:14 -0500 |
| commit | 6fdeadfe509f37203317a967bf28e57fc75676b2 (patch) | |
| tree | c4d837eca0be726489f24e01fbbe14c6d5d420f4 /runtime/test/xmem_test.cpp | |
| parent | f2268abeadb9c57f675c43805a622d5e43628739 (diff) | |
| parent | 1d89b20c5f26f1078b50fef7e2c9cd5fbe2372d6 (diff) | |
Merge main with #984 into RT-QUEUE31 (#968)
Merges the local m984-on-main (1d89b20c5f26f1078b50fef7e2c9cd5fbe2372d6), main with #984
merged, into #968's head f2268abea.
Conflicts and their resolutions:
- runtime/shims/xmem.h: both sides appended to the end of rt::xmem. Kept
geometry_aliases and transfer_physical from #984 and appended #968's
CopyPageMappingsFn typedef and the inline copy_page_mappings_fn after them.
- runtime/shims/xmem.cpp: copy_page_mappings and the self-registering
g_copy_page_mappings_set stay right after XMemMapPhysicalPagesScatter,
followed by #984's shadows_write_watch. One-line port: #984's g_mapped stores
the page number itself (HostUnorderedMap<uintptr_t, uint64_t>), so
`it->second.page` becomes `it->second`.
- runtime/shims/d3d12_xs_device.cpp:
- includes: #968's "xmem.h" beside "d3d12_trace.h", then #984's includes;
- constants: #984's block kept, kQueueCopyPageMappingsBatchX = 31 added after
kQueueExecuteCommandListsX and its static_assert;
- the slot-31 section (ConsolePageRange/Batch, copy_console_page_range,
queue_copy_page_mappings) goes after #984's queue_execute_command_lists and
before the "PresentX is at queue slot 30" comment;
- child_slot: #984's queue block kept; the slot-31 dispatch (beyond the PC
table and with xmem's hook set) goes just before the qroutes lookup, ahead
of the presentation routes and the console-only S_OK tail. Newer-layout
PresentX is 32, so 31 does not clash.
- runtime/test/xs_proxy_mock_test.cpp:
- includes: "../shims/xmem.h" beside #984's d3d12_xs_frame_events.h;
- #984's descriptor-heap and later checks kept, check_queue_copy_page_mappings
after them. Without xmem the merged proxy answers slot 31 with the
console-only S_OK, so that check's `== E_NOTIMPL` becomes `== S_OK` (and its
summary line says so);
- main: `|| check_queue_copy_page_mappings()` appended after
check_presentation_wiring().
runtime/test/xmem_test.cpp merged without conflict: test_copy_page_mappings runs
after test_physical_pages.
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.cpp | 543 |
1 files changed, 539 insertions, 4 deletions
diff --git a/runtime/test/xmem_test.cpp b/runtime/test/xmem_test.cpp index f116b5f3c..96924e185 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. | ||
| 40 | namespace { | ||
| 41 | SRWLOCK g_heap_gate = SRWLOCK_INIT; | ||
| 42 | std::atomic<bool> g_heap_gate_on{false}; | ||
| 43 | struct 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 | |||
| 54 | void* 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 | } | ||
| 59 | void operator delete(void* p) noexcept { | ||
| 60 | HeapGate gate; | ||
| 61 | std::free(p); | ||
| 62 | } | ||
| 63 | void operator delete(void* p, std::size_t) noexcept { operator delete(p); } | ||
| 28 | 64 | ||
| 29 | namespace { | 65 | namespace { |
| 30 | 66 | ||
| @@ -98,6 +134,10 @@ void test_alloc(XMemAllocFn alloc, XMemFreeFn free_mem) { | |||
| 98 | } | 134 | } |
| 99 | 135 | ||
| 100 | void test_working_set(XMemGetWorkingSetStatisticsFn get_stats) { | 136 | void test_working_set(XMemGetWorkingSetStatisticsFn get_stats) { |
| 137 | char saved_env[64]{}; | ||
| 138 | const DWORD saved_n = GetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", saved_env, sizeof(saved_env)); | ||
| 139 | SetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", nullptr); | ||
| 140 | |||
| 101 | alignas(64) uint8_t stats[64]; | 141 | alignas(64) uint8_t stats[64]; |
| 102 | std::memset(stats, 0xa5, sizeof(stats)); | 142 | std::memset(stats, 0xa5, sizeof(stats)); |
| 103 | // The pointer is the second argument: the first (0x20000001 here, as the FSR DLL passes it) must never be written | 143 | // The pointer is the second argument: the first (0x20000001 here, as the FSR DLL passes it) must never be written |
| @@ -134,6 +174,31 @@ void test_working_set(XMemGetWorkingSetStatisticsFn get_stats) { | |||
| 134 | } | 174 | } |
| 135 | check(ok != FALSE && tail_untouched, "XMemGetWorkingSetStatistics leaves bytes 16..63 untouched"); | 175 | check(ok != FALSE && tail_untouched, "XMemGetWorkingSetStatistics leaves bytes 16..63 untouched"); |
| 136 | 176 | ||
| 177 | // LEONIDA_TITLE_MEMORY_MB override and clamping (matches XSystemGetAppMemoryUsageLimit). | ||
| 178 | auto query_total = [&]() -> uint64_t { | ||
| 179 | alignas(64) uint8_t buf[64]{}; | ||
| 180 | if (!get_stats(kMeasuredKind, buf)) return 0; | ||
| 181 | uint64_t out = 0; | ||
| 182 | std::memcpy(&out, buf, sizeof(out)); | ||
| 183 | return out; | ||
| 184 | }; | ||
| 185 | SetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", "6144"); | ||
| 186 | check(query_total() == 6144ULL * 1024ULL * 1024ULL, | ||
| 187 | "XMemGetWorkingSetStatistics honors LEONIDA_TITLE_MEMORY_MB=6144"); | ||
| 188 | SetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", "512"); | ||
| 189 | check(query_total() == 2048ULL * 1024ULL * 1024ULL, | ||
| 190 | "XMemGetWorkingSetStatistics clamps LEONIDA_TITLE_MEMORY_MB below 2048 MiB"); | ||
| 191 | SetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", "131072"); | ||
| 192 | check(query_total() == 65536ULL * 1024ULL * 1024ULL, | ||
| 193 | "XMemGetWorkingSetStatistics clamps LEONIDA_TITLE_MEMORY_MB above 65536 MiB"); | ||
| 194 | SetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", "invalid"); | ||
| 195 | check(query_total() == total_memory, | ||
| 196 | "XMemGetWorkingSetStatistics ignores invalid LEONIDA_TITLE_MEMORY_MB"); | ||
| 197 | SetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", "-4096"); | ||
| 198 | check(query_total() == total_memory, | ||
| 199 | "XMemGetWorkingSetStatistics ignores negative LEONIDA_TITLE_MEMORY_MB"); | ||
| 200 | SetEnvironmentVariableA("LEONIDA_TITLE_MEMORY_MB", (saved_n > 0 && saved_n < sizeof(saved_env)) ? saved_env : nullptr); | ||
| 201 | |||
| 137 | check(get_stats(kMeasuredKind, nullptr) == FALSE, | 202 | check(get_stats(kMeasuredKind, nullptr) == FALSE, |
| 138 | "XMemGetWorkingSetStatistics(kind, nullptr) returns FALSE without crashing"); | 203 | "XMemGetWorkingSetStatistics(kind, nullptr) returns FALSE without crashing"); |
| 139 | } | 204 | } |
| @@ -366,17 +431,38 @@ void test_physical_pages(const PhysicalApi& api) { | |||
| 366 | } | 431 | } |
| 367 | check(numbers_ok, "page numbers are distinct non-zero multiples of 16 below 2^25"); | 432 | check(numbers_ok, "page numbers are distinct non-zero multiples of 16 below 2^25"); |
| 368 | 433 | ||
| 434 | auto generation = leonida::title_memory_map::generation(); | ||
| 369 | check(api.map(window, kPages, pages) == window, "XMemMapPhysicalPages returns the address it mapped"); | 435 | check(api.map(window, kPages, pages) == window, "XMemMapPhysicalPages returns the address it mapped"); |
| 436 | check(leonida::title_memory_map::generation() != generation, "mapping physical pages invalidates shadows"); | ||
| 370 | for (uint64_t i = 0; i < kPages; ++i) fill_page(window + i * kPage64k, 0x1000u * static_cast<uint32_t>(i + 1)); | 437 | for (uint64_t i = 0; i < kPages; ++i) fill_page(window + i * kPage64k, 0x1000u * static_cast<uint32_t>(i + 1)); |
| 371 | { | 438 | { |
| 372 | MEMORY_BASIC_INFORMATION info{}; | 439 | MEMORY_BASIC_INFORMATION info{}; |
| 373 | VirtualQuery(window, &info, sizeof(info)); | 440 | VirtualQuery(window, &info, sizeof(info)); |
| 374 | check(info.State == MEM_COMMIT && info.Type == MEM_MAPPED && info.Protect == PAGE_READWRITE, | 441 | check(info.State == MEM_COMMIT && info.Type == MEM_MAPPED && info.Protect == PAGE_READWRITE, |
| 375 | "a mapped page is a read-write view with the window's protection"); | 442 | "a mapped page is a read-write view with the window's protection"); |
| 443 | check(info.AllocationBase == window && info.RegionSize == kPages * kPage64k, | ||
| 444 | "consecutive pages of one allocation are mapped as one view"); | ||
| 376 | } | 445 | } |
| 377 | 446 | ||
| 447 | // A page unmapped or remapped inside that view splits it; its neighbours keep their pages. | ||
| 448 | void* const middle = window + kPage64k; | ||
| 449 | generation = leonida::title_memory_map::generation(); | ||
| 450 | check(api.scatter(&middle, 1, nullptr) == TRUE && reserved_only(window + kPage64k), | ||
| 451 | "a page inside a view unmaps on its own"); | ||
| 452 | check(page_holds(window, 0x1000u) && page_holds(window + 2 * kPage64k, 0x3000u) && | ||
| 453 | page_holds(window + 3 * kPage64k, 0x4000u), | ||
| 454 | "the pages around it stay mapped with their contents"); | ||
| 455 | check(leonida::title_memory_map::generation() != generation, "scatter unmapping invalidates shadows"); | ||
| 456 | check(api.map(middle, 1, &pages[1]) == middle && page_holds(window + kPage64k, 0x2000u), | ||
| 457 | "a page maps again into the gap"); | ||
| 458 | |||
| 378 | check(api.map(window, kPages, nullptr) == window, "XMemMapPhysicalPages with no page array unmaps"); | 459 | check(api.map(window, kPages, nullptr) == window, "XMemMapPhysicalPages with no page array unmaps"); |
| 379 | check(reserved_only(window) && reserved_only(window + 3 * kPage64k), "unmapped pages are reserved again"); | 460 | check(reserved_only(window) && reserved_only(window + 3 * kPage64k), "unmapped pages are reserved again"); |
| 461 | // The split above left the range as several host placeholders; the whole run maps again over them. | ||
| 462 | check(api.map(window, kPages, pages) == window && page_holds(window, 0x1000u) && | ||
| 463 | page_holds(window + 3 * kPage64k, 0x4000u), | ||
| 464 | "a run maps again over a range an earlier partial unmap split"); | ||
| 465 | check(api.map(window, kPages, nullptr) == window && reserved_only(window), "and unmaps again"); | ||
| 380 | 466 | ||
| 381 | // Remap in reverse order into the other window: each page keeps its contents. | 467 | // Remap in reverse order into the other window: each page keeps its contents. |
| 382 | uint64_t reversed[kPages]; | 468 | uint64_t reversed[kPages]; |
| @@ -681,9 +767,11 @@ void test_first_touch_during_remap(const PhysicalApi& api) { | |||
| 681 | std::atomic<bool> stop{false}; | 767 | std::atomic<bool> stop{false}; |
| 682 | std::atomic<uint64_t> touches{0}; | 768 | std::atomic<uint64_t> touches{0}; |
| 683 | std::atomic<uint64_t> unmapped_faults{0}; | 769 | std::atomic<uint64_t> unmapped_faults{0}; |
| 770 | std::atomic<int> started_writers{0}; | ||
| 684 | std::vector<std::thread> writers; | 771 | std::vector<std::thread> writers; |
| 685 | for (int t = 0; t < 4; ++t) { | 772 | for (int t = 0; t < 4; ++t) { |
| 686 | writers.emplace_back([&, t] { | 773 | writers.emplace_back([&, t] { |
| 774 | started_writers.fetch_add(1); | ||
| 687 | uint64_t i = static_cast<uint64_t>(t); | 775 | uint64_t i = static_cast<uint64_t>(t); |
| 688 | while (!stop.load(std::memory_order_relaxed)) { | 776 | while (!stop.load(std::memory_order_relaxed)) { |
| 689 | auto* const word = | 777 | auto* const word = |
| @@ -697,6 +785,8 @@ void test_first_touch_during_remap(const PhysicalApi& api) { | |||
| 697 | } | 785 | } |
| 698 | }); | 786 | }); |
| 699 | } | 787 | } |
| 788 | // The remaps can finish before a writer is scheduled on a fast host, so wait for all four to run first. | ||
| 789 | while (started_writers.load() < 4) Sleep(0); | ||
| 700 | const ULONGLONG started = GetTickCount64(); | 790 | const ULONGLONG started = GetTickCount64(); |
| 701 | bool remapped = true; | 791 | bool remapped = true; |
| 702 | for (uint64_t s = 0; s < kSlices; ++s) { | 792 | for (uint64_t s = 0; s < kSlices; ++s) { |
| @@ -705,6 +795,8 @@ void test_first_touch_during_remap(const PhysicalApi& api) { | |||
| 705 | remapped &= api.map(window, kSlice, nullptr) == window; | 795 | remapped &= api.map(window, kSlice, nullptr) == window; |
| 706 | } | 796 | } |
| 707 | remapped &= api.map(window, kSlice, pages.data() + (kSlices - 1) * kSlice) == window; | 797 | remapped &= api.map(window, kSlice, pages.data() + (kSlices - 1) * kSlice) == window; |
| 798 | // The last slice stays mapped: give the writers up to a second to land a write in it before stopping them. | ||
| 799 | for (const ULONGLONG until = GetTickCount64() + 1000; touches.load() == 0 && GetTickCount64() < until;) Sleep(1); | ||
| 708 | stop.store(true); | 800 | stop.store(true); |
| 709 | for (auto& writer : writers) writer.join(); | 801 | for (auto& writer : writers) writer.join(); |
| 710 | const ULONGLONG elapsed = GetTickCount64() - started; | 802 | const ULONGLONG elapsed = GetTickCount64() - started; |
| @@ -720,6 +812,102 @@ void test_first_touch_during_remap(const PhysicalApi& api) { | |||
| 720 | check(api.free_pages(count, pages.data()) == TRUE, "XMemFreePhysicalPages frees the remap race pages"); | 812 | check(api.free_pages(count, pages.data()) == TRUE, "XMemFreePhysicalPages frees the remap race pages"); |
| 721 | } | 813 | } |
| 722 | 814 | ||
| 815 | // Splitting a view briefly unmaps the view's other pages; a thread reading one of them meanwhile must not fault. | ||
| 816 | // Unmapping page k of the view [k, end) splits it every time, and the last page of each view is the one being read. | ||
| 817 | void test_split_under_reader(const PhysicalApi& api) { | ||
| 818 | constexpr uint64_t kPages = 2048; // two capped views | ||
| 819 | auto* const window = static_cast<uint8_t*>( | ||
| 820 | api.virtual_alloc(nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE)); | ||
| 821 | std::vector<uint64_t> pages(kPages); | ||
| 822 | uint64_t count = kPages; | ||
| 823 | check(window && api.allocate(0x280, &count, pages.data()) == TRUE && count == kPages && | ||
| 824 | api.map(window, kPages, pages.data()) == window, | ||
| 825 | "a 2,048-page run maps for the split test"); | ||
| 826 | if (!window || count != kPages) return; | ||
| 827 | uint8_t* const read_pages[2] = {window + 1023 * kPage64k, window + 2047 * kPage64k}; | ||
| 828 | fill_page(read_pages[0], 0x11000u); | ||
| 829 | fill_page(read_pages[1], 0x11000u); | ||
| 830 | std::atomic<bool> done{false}; | ||
| 831 | std::atomic<uint64_t> reads{0}, wrong{0}; | ||
| 832 | std::thread reader([&] { | ||
| 833 | for (uint64_t i = 0; !done.load(std::memory_order_relaxed); ++i) { | ||
| 834 | wrong += read_u32(read_pages[i & 1], 0) != 0x11000u; | ||
| 835 | ++reads; | ||
| 836 | } | ||
| 837 | }); | ||
| 838 | bool unmapped = true; | ||
| 839 | for (uint64_t k = 0; k < kPages - 1; ++k) { | ||
| 840 | if (k == 1023) continue; | ||
| 841 | void* const page = window + k * kPage64k; | ||
| 842 | unmapped &= api.scatter(&page, 1, nullptr) == TRUE; | ||
| 843 | } | ||
| 844 | done = true; | ||
| 845 | reader.join(); | ||
| 846 | check(unmapped, "2,046 pages unmap one at a time, each splitting the view a reader is in"); | ||
| 847 | check(reads.load() > 0 && wrong.load() == 0, "the reader of the views' last pages never faults or misreads"); | ||
| 848 | // The last split was of [2046, 2048): a fault there is retried, one on another mapped page is not. | ||
| 849 | api.map(window, kPages, nullptr); | ||
| 850 | api.free_pages(kPages, pages.data()); | ||
| 851 | } | ||
| 852 | |||
| 853 | // A run longer than one host view is mapped as capped views, so unmapping one page inside it only remaps the rest of | ||
| 854 | // that view; every other page keeps its contents. | ||
| 855 | void test_long_run(const PhysicalApi& api) { | ||
| 856 | constexpr uint64_t kPages = 1100; // more than the 1024-page view cap | ||
| 857 | auto* const window = static_cast<uint8_t*>( | ||
| 858 | api.virtual_alloc(nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE)); | ||
| 859 | std::vector<uint64_t> pages(kPages); | ||
| 860 | uint64_t count = kPages; | ||
| 861 | check(window && api.allocate(0x280, &count, pages.data()) == TRUE, "a long run's window and pages are allocated"); | ||
| 862 | if (!window || count != kPages) return; | ||
| 863 | check(api.map(window, kPages, pages.data()) == window, "a run longer than the view cap maps"); | ||
| 864 | // The pages are committed on first touch, so an untouched view reads MEM_RESERVE on Windows (Wine reports | ||
| 865 | // MEM_COMMIT); either way the first region is one mapped view of exactly the cap. | ||
| 866 | MEMORY_BASIC_INFORMATION info{}; | ||
| 867 | VirtualQuery(window, &info, sizeof(info)); | ||
| 868 | check(info.Type == MEM_MAPPED && (info.State == MEM_COMMIT || info.State == MEM_RESERVE) && | ||
| 869 | info.RegionSize == 1024 * kPage64k, | ||
| 870 | "it is mapped as views of at most 1024 pages"); | ||
| 871 | for (uint64_t i = 0; i < kPages; ++i) fill_page(window + i * kPage64k, static_cast<uint32_t>(i + 1)); | ||
| 872 | void* const hole = window + 10 * kPage64k; | ||
| 873 | check(api.scatter(&hole, 1, nullptr) == TRUE && reserved_only(hole), "a page inside the first view unmaps"); | ||
| 874 | bool kept = true; | ||
| 875 | for (uint64_t i = 0; i < kPages; ++i) { | ||
| 876 | if (i != 10) kept &= page_holds(window + i * kPage64k, static_cast<uint32_t>(i + 1)); | ||
| 877 | } | ||
| 878 | check(kept, "every other page of the run keeps its contents"); | ||
| 879 | // Several pages across the boundary of two capped views unmap together; the pages on both sides stay. | ||
| 880 | check(api.map(window + 1000 * kPage64k, 50, nullptr) == window + 1000 * kPage64k && | ||
| 881 | reserved_only(window + 1000 * kPage64k) && reserved_only(window + 1049 * kPage64k), | ||
| 882 | "a multi-page range across two views unmaps"); | ||
| 883 | check(page_holds(window + 999 * kPage64k, 1000u) && page_holds(window + 1050 * kPage64k, 1051u), | ||
| 884 | "the pages on both sides of it keep their contents"); | ||
| 885 | // Mapping other pages over the middle of a live run replaces just those pages. | ||
| 886 | check(api.map(window + 500 * kPage64k, 3, &pages[600]) == window + 500 * kPage64k && | ||
| 887 | page_holds(window + 500 * kPage64k, 601u) && page_holds(window + 502 * kPage64k, 603u), | ||
| 888 | "pages mapped over the middle of a live run replace it there"); | ||
| 889 | check(page_holds(window + 499 * kPage64k, 500u) && page_holds(window + 503 * kPage64k, 504u), | ||
| 890 | "and the run's pages around them keep their contents"); | ||
| 891 | check(api.map(window, kPages, nullptr) == window && reserved_only(window) && | ||
| 892 | reserved_only(window + (kPages - 1) * kPage64k), | ||
| 893 | "the whole run unmaps"); | ||
| 894 | check(api.free_pages(kPages, pages.data()) == TRUE, "the long run's pages are freed"); | ||
| 895 | check(api.map(window, 1, pages.data()) == nullptr && reserved_only(window), "a freed page does not map again"); | ||
| 896 | // Pages freed while still mapped keep their memory, and splitting their view later still maps the rest again. | ||
| 897 | count = 4; | ||
| 898 | check(api.allocate(0x280, &count, pages.data()) == TRUE && count == 4 && api.map(window, 4, pages.data()) == window, | ||
| 899 | "four pages map as one view"); | ||
| 900 | if (count != 4) return; | ||
| 901 | for (uint64_t i = 0; i < 4; ++i) fill_page(window + i * kPage64k, static_cast<uint32_t>(i + 1)); | ||
| 902 | check(api.free_pages(4, pages.data()) == TRUE, "they are freed while mapped"); | ||
| 903 | void* const second = window + kPage64k; | ||
| 904 | check(api.scatter(&second, 1, nullptr) == TRUE && !reserved_only(window) && | ||
| 905 | !reserved_only(window + 2 * kPage64k) && page_holds(window, 1u) && | ||
| 906 | page_holds(window + 2 * kPage64k, 3u) && page_holds(window + 3 * kPage64k, 4u), | ||
| 907 | "unmapping one of them afterwards keeps the others' memory"); | ||
| 908 | api.map(window, 4, nullptr); | ||
| 909 | } | ||
| 910 | |||
| 723 | // The placeholder flags pass through: reserve a placeholder, carve windows and committed memory out of it. | 911 | // The placeholder flags pass through: reserve a placeholder, carve windows and committed memory out of it. |
| 724 | void test_placeholders(const PhysicalApi& api) { | 912 | void test_placeholders(const PhysicalApi& api) { |
| 725 | auto* const base = static_cast<uint8_t*>( | 913 | auto* const base = static_cast<uint8_t*>( |
| @@ -784,6 +972,168 @@ void test_write_combine_window(const PhysicalApi& api) { | |||
| 784 | check(api.free_pages(1, &page) == TRUE, "free the write-combine window's page"); | 972 | check(api.free_pages(1, &page) == TRUE, "free the write-combine window's page"); |
| 785 | } | 973 | } |
| 786 | 974 | ||
| 975 | // Counts the access violations in [g_counted_begin, g_counted_end). Added after xmem's handler with First = 1, so it | ||
| 976 | // runs before it and sees every fault there, the ones xmem then commits included. | ||
| 977 | std::atomic<uintptr_t> g_counted_begin{0}, g_counted_end{0}; | ||
| 978 | std::atomic<uint64_t> g_counted_faults{0}; | ||
| 979 | |||
| 980 | LONG CALLBACK count_window_faults(EXCEPTION_POINTERS* info) { | ||
| 981 | const EXCEPTION_RECORD* record = info ? info->ExceptionRecord : nullptr; | ||
| 982 | if (record && record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && record->NumberParameters >= 2) { | ||
| 983 | const auto at = static_cast<uintptr_t>(record->ExceptionInformation[1]); | ||
| 984 | if (at >= g_counted_begin.load(std::memory_order_relaxed) && at < g_counted_end.load(std::memory_order_relaxed)) | ||
| 985 | g_counted_faults.fetch_add(1, std::memory_order_relaxed); | ||
| 986 | } | ||
| 987 | return EXCEPTION_CONTINUE_SEARCH; | ||
| 988 | } | ||
| 989 | |||
| 990 | // About `us` microseconds of spinning, without a call that could allocate. | ||
| 991 | void spin_for(LONGLONG us) { | ||
| 992 | LARGE_INTEGER now{}, frequency{}; | ||
| 993 | QueryPerformanceFrequency(&frequency); | ||
| 994 | QueryPerformanceCounter(&now); | ||
| 995 | const LONGLONG until = now.QuadPart + frequency.QuadPart * us / 1000000; | ||
| 996 | while (QueryPerformanceCounter(&now) && now.QuadPart < until) YieldProcessor(); | ||
| 997 | } | ||
| 998 | |||
| 999 | // Title threads take access violations while they hold the process heap's lock: XMemAlloc is _aligned_malloc, so | ||
| 1000 | // HeapAlloc and HeapFree write block headers on title pages, which may be physical pages waiting for their first touch | ||
| 1001 | // or pages the D3D12 layer's shadows guard. xmem's handler waits for g_fault_lock (shared) at every access violation, | ||
| 1002 | // its own or not, so whoever holds that lock exclusively (a map or an unmap of physical pages) must never wait for the | ||
| 1003 | // process heap meanwhile: it would wait for the faulting thread, which waits for it. While | ||
| 1004 | // - threads take the process heap's lock (HeapLock, as HeapAlloc does inside, and the heap gate above) and, holding | ||
| 1005 | // it, _aligned_malloc and _aligned_free and write a word into every page of a window whose pages are mapped fresh | ||
| 1006 | // all the time (a first-touch commit, or a fault on a page that is being unmapped) and into a read-only page (a | ||
| 1007 | // fault that isn't xmem's, as on a guarded shadow page); | ||
| 1008 | // - threads allocate physical pages, map them into their part of the window (as a run, or page by page through the | ||
| 1009 | // scatter call), and unmap and free them, some freed while still mapped so that the unmap drops the last | ||
| 1010 | // reference to their section; | ||
| 1011 | // a watchdog ends the process (exit code 3) when nothing got anywhere for 30 s: a deadlock. | ||
| 1012 | void test_heap_lock_faults(const PhysicalApi& api) { | ||
| 1013 | if (const HMODULE ntdll = GetModuleHandleW(L"ntdll.dll"); ntdll && GetProcAddress(ntdll, "wine_get_version")) { | ||
| 1014 | // Under Wine a holder of the fault lock still reaches the process heap through the host's own view calls (or | ||
| 1015 | // Wine's fault dispatch needs it): the test deadlocks there with the fix in. The Wine side is an open item. | ||
| 1016 | std::printf("SKIP heap-lock faults under Wine: a fault-lock holder still waits for the process heap there\n"); | ||
| 1017 | return; | ||
| 1018 | } | ||
| 1019 | constexpr uint64_t kMappers = 2, kSlice = 4, kPages = kMappers * kSlice; | ||
| 1020 | constexpr unsigned kTouchers = 3; | ||
| 1021 | auto* const window = static_cast<uint8_t*>( | ||
| 1022 | api.virtual_alloc(nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x21, PAGE_READWRITE)); | ||
| 1023 | auto* const read_only = static_cast<uint8_t*>(VirtualAlloc(nullptr, 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_READONLY)); | ||
| 1024 | check(window != nullptr && read_only != nullptr, "a window and a read-only page for the heap-lock faults"); | ||
| 1025 | if (!window || !read_only) return; | ||
| 1026 | g_counted_begin = reinterpret_cast<uintptr_t>(window); | ||
| 1027 | g_counted_end = reinterpret_cast<uintptr_t>(window) + kPages * kPage64k; | ||
| 1028 | g_counted_faults = 0; | ||
| 1029 | // xmem's handler is in by now (the first XMemAllocatePhysicalPages put it in), so this one runs first. | ||
| 1030 | void* const counter = AddVectoredExceptionHandler(1, &count_window_faults); | ||
| 1031 | check(counter != nullptr, "a fault counter in front of xmem's handler"); | ||
| 1032 | if (!counter) return; | ||
| 1033 | |||
| 1034 | std::atomic<uint64_t> progress{0}; // bumped by every round of every thread | ||
| 1035 | std::atomic<bool> stop{false}, finished{false}, failed{false}; | ||
| 1036 | std::thread watchdog([&] { | ||
| 1037 | uint64_t seen = progress.load(); | ||
| 1038 | ULONGLONG since = GetTickCount64(); | ||
| 1039 | while (!finished.load()) { | ||
| 1040 | Sleep(100); | ||
| 1041 | const uint64_t now = progress.load(); | ||
| 1042 | if (now != seen) { | ||
| 1043 | seen = now; | ||
| 1044 | since = GetTickCount64(); | ||
| 1045 | } else if (GetTickCount64() - since > 30000) { | ||
| 1046 | // No heap here: the process heap may be what is stuck. | ||
| 1047 | static const char message[] = | ||
| 1048 | "xmem heap-lock faults: no progress for 30 s: deadlock (a holder of the lock xmem's fault handler " | ||
| 1049 | "waits for is waiting for the process heap)\n"; | ||
| 1050 | DWORD wrote = 0; | ||
| 1051 | WriteFile(GetStdHandle(STD_ERROR_HANDLE), message, DWORD(sizeof(message) - 1), &wrote, nullptr); | ||
| 1052 | TerminateProcess(GetCurrentProcess(), 3); | ||
| 1053 | } | ||
| 1054 | } | ||
| 1055 | }); | ||
| 1056 | std::atomic<uint64_t> rounds{0}, missed{0}, read_only_faults{0}, maps{0}; | ||
| 1057 | std::vector<std::thread> threads; | ||
| 1058 | threads.reserve(kTouchers + kMappers); | ||
| 1059 | g_heap_gate_on = true; | ||
| 1060 | for (unsigned t = 0; t < kTouchers; ++t) | ||
| 1061 | threads.emplace_back([&, t] { | ||
| 1062 | const HANDLE heap = GetProcessHeap(); | ||
| 1063 | for (unsigned round = 0; !stop.load(std::memory_order_relaxed); ++round) { | ||
| 1064 | uint64_t round_missed = 0; | ||
| 1065 | bool round_read_only = false; | ||
| 1066 | AcquireSRWLockExclusive(&g_heap_gate); | ||
| 1067 | HeapLock(heap); | ||
| 1068 | void* block = _aligned_malloc(64 + (round % 32) * 160, 16); | ||
| 1069 | for (uint64_t p = 0; p < kPages; ++p) { | ||
| 1070 | auto* const word = | ||
| 1071 | static_cast<volatile uint32_t*>(static_cast<void*>(window + p * kPage64k)) + t; | ||
| 1072 | round_missed += access_faults(word, true); | ||
| 1073 | } | ||
| 1074 | round_read_only = access_faults(static_cast<volatile uint32_t*>(static_cast<void*>(read_only)), true); | ||
| 1075 | _aligned_free(block); | ||
| 1076 | HeapUnlock(heap); | ||
| 1077 | ReleaseSRWLockExclusive(&g_heap_gate); | ||
| 1078 | missed.fetch_add(round_missed, std::memory_order_relaxed); | ||
| 1079 | read_only_faults.fetch_add(round_read_only, std::memory_order_relaxed); | ||
| 1080 | rounds.fetch_add(1, std::memory_order_relaxed); | ||
| 1081 | progress.fetch_add(1, std::memory_order_relaxed); | ||
| 1082 | spin_for(50); // the other threads get to allocate | ||
| 1083 | } | ||
| 1084 | }); | ||
| 1085 | for (uint64_t m = 0; m < kMappers; ++m) | ||
| 1086 | threads.emplace_back([&, m] { | ||
| 1087 | uint8_t* const slice = window + m * kSlice * kPage64k; | ||
| 1088 | uint64_t pages[kSlice]{}; | ||
| 1089 | void* addresses[kSlice]{}; | ||
| 1090 | for (uint64_t k = 0; k < kSlice; ++k) addresses[k] = slice + k * kPage64k; | ||
| 1091 | for (uint64_t round = 0; !stop.load(std::memory_order_relaxed); ++round) { | ||
| 1092 | uint64_t count = kSlice; | ||
| 1093 | if (api.allocate(0x280, &count, pages) != TRUE || count != kSlice) { | ||
| 1094 | failed = true; | ||
| 1095 | break; | ||
| 1096 | } | ||
| 1097 | bool ok = round % 2 == 0 ? api.map(slice, kSlice, pages) == slice | ||
| 1098 | : api.scatter(addresses, static_cast<uint32_t>(kSlice), pages) == TRUE; | ||
| 1099 | spin_for(100); // the touchers get to fault the fresh pages in | ||
| 1100 | // Freed while mapped: the unmap then drops the last reference to the section. | ||
| 1101 | const bool free_first = round % 3 == 0; | ||
| 1102 | if (free_first) ok &= api.free_pages(kSlice, pages) == TRUE; | ||
| 1103 | ok &= api.map(slice, kSlice, nullptr) == slice; | ||
| 1104 | if (!free_first) ok &= api.free_pages(kSlice, pages) == TRUE; | ||
| 1105 | if (!ok) { | ||
| 1106 | failed = true; | ||
| 1107 | break; | ||
| 1108 | } | ||
| 1109 | maps.fetch_add(1, std::memory_order_relaxed); | ||
| 1110 | progress.fetch_add(1, std::memory_order_relaxed); | ||
| 1111 | } | ||
| 1112 | }); | ||
| 1113 | for (const ULONGLONG until = GetTickCount64() + 3000; !failed.load() && GetTickCount64() < until;) Sleep(10); | ||
| 1114 | stop = true; | ||
| 1115 | for (std::thread& thread : threads) thread.join(); | ||
| 1116 | g_heap_gate_on = false; | ||
| 1117 | finished = true; | ||
| 1118 | watchdog.join(); | ||
| 1119 | RemoveVectoredExceptionHandler(counter); | ||
| 1120 | g_counted_end = 0; | ||
| 1121 | |||
| 1122 | const uint64_t window_faults = g_counted_faults.load(); | ||
| 1123 | // A fault in the window that the toucher's own handler didn't catch is one xmem's handler resolved: a first touch | ||
| 1124 | // (or a retry of one another toucher committed meanwhile). | ||
| 1125 | const uint64_t committed = window_faults > missed.load() ? window_faults - missed.load() : 0; | ||
| 1126 | check(!failed.load(), "physical pages allocate, map (run and scatter), unmap and free while faults hold the heap"); | ||
| 1127 | check(maps.load() > 0 && rounds.load() > 0, "the mappers and the faulting threads both made progress"); | ||
| 1128 | check(committed > 0, "threads holding the process heap's lock took first-touch faults xmem committed"); | ||
| 1129 | check(read_only_faults.load() == rounds.load(), "every write to the read-only page faulted through xmem's handler"); | ||
| 1130 | std::printf("heap-lock faults: %llu mappings, %llu rounds holding the process heap's lock, %llu first touches " | ||
| 1131 | "committed, %llu faults on unmapped pages: no deadlock\n", | ||
| 1132 | static_cast<unsigned long long>(maps.load()), static_cast<unsigned long long>(rounds.load()), | ||
| 1133 | static_cast<unsigned long long>(committed), static_cast<unsigned long long>(missed.load())); | ||
| 1134 | VirtualFree(read_only, 0, MEM_RELEASE); | ||
| 1135 | } | ||
| 1136 | |||
| 787 | // gta6rt --trace: one "xmem_attributes" event per distinct raw attribute word and API, none with the trace off. | 1137 | // gta6rt --trace: one "xmem_attributes" event per distinct raw attribute word and API, none with the trace off. |
| 788 | void test_attribute_trace(XMemAllocFn alloc, XMemFreeFn free_mem, XMemVirtualAllocFn virtual_alloc) { | 1138 | void test_attribute_trace(XMemAllocFn alloc, XMemFreeFn free_mem, XMemVirtualAllocFn virtual_alloc) { |
| 789 | wchar_t temp[MAX_PATH]; | 1139 | wchar_t temp[MAX_PATH]; |
| @@ -914,6 +1264,8 @@ void test_transfer_trace(XMemTransferMemoryFn transfer) { | |||
| 914 | } | 1264 | } |
| 915 | 1265 | ||
| 916 | using HostVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, DWORD); | 1266 | using HostVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, DWORD); |
| 1267 | using HostVirtualFreeFn = BOOL(WINAPI*)(void*, SIZE_T, DWORD); | ||
| 1268 | using HostVirtualProtectFn = BOOL(WINAPI*)(void*, SIZE_T, DWORD, PDWORD); | ||
| 917 | 1269 | ||
| 918 | // RT-217: a title's kernel32!VirtualAlloc carries the console's MEM_GRAPHICS / MEM_TITLE type bits, which the host | 1270 | // RT-217: a title's kernel32!VirtualAlloc carries the console's MEM_GRAPHICS / MEM_TITLE type bits, which the host |
| 919 | // rejects. The registered shim has to drop them and still allocate. | 1271 | // rejects. The registered shim has to drop them and still allocate. |
| @@ -923,18 +1275,30 @@ void test_title_virtual_alloc() { | |||
| 923 | const char* const dlls[] = {"kernel32.dll", "kernelbase.dll", "api-ms-win-core-memory-l1-1-0.dll"}; | 1275 | const char* const dlls[] = {"kernel32.dll", "kernelbase.dll", "api-ms-win-core-memory-l1-1-0.dll"}; |
| 924 | for (const char* dll : dlls) { | 1276 | for (const char* dll : dlls) { |
| 925 | const auto alloc = reinterpret_cast<HostVirtualAllocFn>(rt::shims::find(dll, "VirtualAlloc")); | 1277 | const auto alloc = reinterpret_cast<HostVirtualAllocFn>(rt::shims::find(dll, "VirtualAlloc")); |
| 1278 | const auto free = reinterpret_cast<HostVirtualFreeFn>(rt::shims::find(dll, "VirtualFree")); | ||
| 1279 | const auto protect = reinterpret_cast<HostVirtualProtectFn>(rt::shims::find(dll, "VirtualProtect")); | ||
| 926 | char what[160]; | 1280 | char what[160]; |
| 927 | std::snprintf(what, sizeof what, "registry exposes %s!VirtualAlloc", dll); | 1281 | std::snprintf(what, sizeof what, "registry exposes %s's virtual memory shims", dll); |
| 928 | check(alloc != nullptr, what); | 1282 | check(alloc && free && protect, what); |
| 929 | if (!alloc) continue; | 1283 | if (!alloc || !free || !protect) continue; |
| 930 | 1284 | ||
| 1285 | auto generation = leonida::title_memory_map::generation(); | ||
| 931 | void* const gfx = alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT, 0x2004); // PAGE_GRAPHICS_READWRITE | 1286 | void* const gfx = alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT, 0x2004); // PAGE_GRAPHICS_READWRITE |
| 932 | check(gfx != nullptr, "title VirtualAlloc with protect 0x2004 succeeds"); | 1287 | check(gfx != nullptr, "title VirtualAlloc with protect 0x2004 succeeds"); |
| 933 | if (gfx) { | 1288 | if (gfx) { |
| 1289 | check(leonida::title_memory_map::generation() != generation, "title VirtualAlloc invalidates shadows"); | ||
| 934 | MEMORY_BASIC_INFORMATION mbi{}; | 1290 | MEMORY_BASIC_INFORMATION mbi{}; |
| 935 | check(VirtualQuery(gfx, &mbi, sizeof mbi) && mbi.Protect == PAGE_READWRITE, | 1291 | check(VirtualQuery(gfx, &mbi, sizeof mbi) && mbi.Protect == PAGE_READWRITE, |
| 936 | "protect 0x2004 commits PAGE_READWRITE"); | 1292 | "protect 0x2004 commits PAGE_READWRITE"); |
| 937 | VirtualFree(gfx, 0, MEM_RELEASE); | 1293 | DWORD old = 0; |
| 1294 | generation = leonida::title_memory_map::generation(); | ||
| 1295 | check(protect(gfx, 0x1000, PAGE_READONLY, &old) && old == PAGE_READWRITE, | ||
| 1296 | "title VirtualProtect changes protection and returns the previous protection"); | ||
| 1297 | check(leonida::title_memory_map::generation() != generation, "title VirtualProtect invalidates shadows"); | ||
| 1298 | generation = leonida::title_memory_map::generation(); | ||
| 1299 | check(free(gfx, 0x1000, MEM_DECOMMIT), "title VirtualFree decommits a page"); | ||
| 1300 | check(leonida::title_memory_map::generation() != generation, "title VirtualFree invalidates shadows"); | ||
| 1301 | check(free(gfx, 0, MEM_RELEASE), "release the graphics allocation"); | ||
| 938 | } | 1302 | } |
| 939 | for (const DWORD bits : {kMemGraphics, kMemTitle, kMemGraphics | kMemTitle, DWORD{0}}) { | 1303 | for (const DWORD bits : {kMemGraphics, kMemTitle, kMemGraphics | kMemTitle, DWORD{0}}) { |
| 940 | void* const p = alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT | bits, PAGE_READWRITE); | 1304 | void* const p = alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT | bits, PAGE_READWRITE); |
| @@ -949,6 +1313,171 @@ void test_title_virtual_alloc() { | |||
| 949 | } | 1313 | } |
| 950 | } | 1314 | } |
| 951 | 1315 | ||
| 1316 | // The title's ordinary reservations are write-watched for the D3D12 layer's shadows (leonida::title_write_watch): | ||
| 1317 | // XMemVirtualAlloc's plain, 2 MiB and 64 KiB committed regions and kernel32!VirtualAlloc's reservations, each recorded | ||
| 1318 | // until the title releases it. Placeholders and physical-page windows are not (a section view can't be), nor is a | ||
| 1319 | // region the title asked to be write-watched itself (its bits are the title's). With LEONIDA_WRITE_WATCH=0 (the | ||
| 1320 | // xmem_no_write_watch test) nothing is. | ||
| 1321 | void test_write_watched_reservations(XMemVirtualAllocFn virtual_alloc) { | ||
| 1322 | const bool on = leonida::title_write_watch::enabled(); | ||
| 1323 | std::printf("xmem_test: write watching %s\n", on ? "on" : "off (LEONIDA_WRITE_WATCH=0)"); | ||
| 1324 | const auto kernel_watching = [](void* base, SIZE_T size) { | ||
| 1325 | void* found[16]{}; | ||
| 1326 | ULONG_PTR count = 16; | ||
| 1327 | ULONG granularity = 0; | ||
| 1328 | return GetWriteWatch(0, base, size, found, &count, &granularity) == 0; | ||
| 1329 | }; | ||
| 1330 | const auto title_free = reinterpret_cast<HostVirtualFreeFn>(rt::shims::find("kernel32.dll", "VirtualFree")); | ||
| 1331 | const auto title_alloc = reinterpret_cast<HostVirtualAllocFn>(rt::shims::find("kernel32.dll", "VirtualAlloc")); | ||
| 1332 | check(title_free && title_alloc, "registry exposes kernel32.dll's VirtualAlloc and VirtualFree shims"); | ||
| 1333 | if (!title_free || !title_alloc) return; | ||
| 1334 | struct Case { | ||
| 1335 | const char* what; | ||
| 1336 | DWORD type; | ||
| 1337 | SIZE_T size; | ||
| 1338 | bool watched; | ||
| 1339 | }; | ||
| 1340 | const Case cases[] = { | ||
| 1341 | {"plain reserve+commit", MEM_RESERVE | MEM_COMMIT, 0x3000, true}, | ||
| 1342 | {"commit at no address", MEM_COMMIT, 0x3000, true}, | ||
| 1343 | {"reserve only", MEM_RESERVE, 0x20000, true}, | ||
| 1344 | {"2 MiB pages", kXmemLargePages | MEM_RESERVE | MEM_COMMIT, kPage2m, true}, | ||
| 1345 | {"64 KiB pages committed", kXmem64kPages | MEM_RESERVE | MEM_COMMIT, kPage64k * 2, true}, | ||
| 1346 | {"64 KiB physical-page window", kXmem64kPages | MEM_RESERVE, kPage64k * 2, false}, | ||
| 1347 | {"placeholder", MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, kPage64k * 2, false}, | ||
| 1348 | {"the title's own write watch", MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, 0x3000, false}, | ||
| 1349 | }; | ||
| 1350 | for (const Case& c : cases) { | ||
| 1351 | void* const base = virtual_alloc(nullptr, c.size, c.type, 0, PAGE_READWRITE); | ||
| 1352 | char what[192]; | ||
| 1353 | std::snprintf(what, sizeof what, "XMemVirtualAlloc %s succeeds", c.what); | ||
| 1354 | check(base != nullptr, what); | ||
| 1355 | if (!base) continue; | ||
| 1356 | const auto at = reinterpret_cast<uintptr_t>(base); | ||
| 1357 | const bool want = on && c.watched; | ||
| 1358 | std::snprintf(what, sizeof what, "XMemVirtualAlloc %s: %s for the shadows", c.what, | ||
| 1359 | want ? "recorded write-watched" : "not recorded"); | ||
| 1360 | check(leonida::title_write_watch::contains(at) == want && | ||
| 1361 | leonida::title_write_watch::contains(at + c.size - 1) == want, | ||
| 1362 | what); | ||
| 1363 | if (want) { | ||
| 1364 | std::snprintf(what, sizeof what, "XMemVirtualAlloc %s: the kernel write-watches it", c.what); | ||
| 1365 | check(kernel_watching(base, c.size), what); | ||
| 1366 | } | ||
| 1367 | if ((c.type & MEM_RESERVE_PLACEHOLDER) || ((c.type & kXmem64kPages) == kXmem64kPages && !(c.type & MEM_COMMIT))) { | ||
| 1368 | VirtualFree(base, 0, MEM_RELEASE); | ||
| 1369 | continue; | ||
| 1370 | } | ||
| 1371 | std::snprintf(what, sizeof what, "title VirtualFree releases the region (%s) and forgets it", c.what); | ||
| 1372 | check(title_free(base, 0, MEM_RELEASE) && !leonida::title_write_watch::contains(at), what); | ||
| 1373 | } | ||
| 1374 | // kernel32!VirtualAlloc as the title calls it: a reservation is recorded, a commit inside it adds nothing. | ||
| 1375 | void* const reserved = title_alloc(nullptr, 0x40000, MEM_RESERVE, PAGE_READWRITE); | ||
| 1376 | check(reserved != nullptr, "title VirtualAlloc reserves"); | ||
| 1377 | if (!reserved) return; | ||
| 1378 | const auto at = reinterpret_cast<uintptr_t>(reserved); | ||
| 1379 | const auto generation = leonida::title_write_watch::generation(); | ||
| 1380 | check(title_alloc(reserved, 0x1000, MEM_COMMIT, PAGE_READWRITE) == reserved, "title VirtualAlloc commits in it"); | ||
| 1381 | check(leonida::title_write_watch::generation() == generation, "a commit inside a reservation records nothing new"); | ||
| 1382 | check(leonida::title_write_watch::contains(at + 0x3ffff) == on, | ||
| 1383 | on ? "title VirtualAlloc's reservation is recorded write-watched" : "title VirtualAlloc's is not recorded"); | ||
| 1384 | if (on) { | ||
| 1385 | check(kernel_watching(reserved, 0x40000), "the kernel write-watches title VirtualAlloc's reservation"); | ||
| 1386 | static_cast<volatile uint8_t*>(reserved)[0x10] = 1; | ||
| 1387 | void* found[4]{}; | ||
| 1388 | ULONG_PTR count = 4; | ||
| 1389 | ULONG granularity = 0; | ||
| 1390 | check(GetWriteWatch(0, reserved, 0x40000, found, &count, &granularity) == 0 && count == 1 && | ||
| 1391 | found[0] == reserved, | ||
| 1392 | "a write to it is in the kernel's answer"); | ||
| 1393 | } else { | ||
| 1394 | check(!kernel_watching(reserved, 0x40000), "LEONIDA_WRITE_WATCH=0: the kernel does not write-watch it"); | ||
| 1395 | } | ||
| 1396 | check(title_free(reserved, 0, MEM_RELEASE) && !leonida::title_write_watch::contains(at), | ||
| 1397 | "title VirtualFree releases it and forgets it"); | ||
| 1398 | } | ||
| 1399 | |||
| 1400 | // A reservation the title releases and reserves again at the same address is a new one to the shadows' journal | ||
| 1401 | // (leonida::title_write_watch::ask): a reader that asked over the old one is told all of the new one's pages as | ||
| 1402 | // written, though nothing wrote them (a new reservation's kernel bits are clear, and a MEM_RESERVE | MEM_COMMIT in one | ||
| 1403 | // call marks nothing). Through kernel32!VirtualAlloc and XMemVirtualAlloc; a page decommitted and committed again | ||
| 1404 | // inside a reservation is told as written too. And the title's XMemGetWriteWatch and XMemResetWriteWatch refuse a | ||
| 1405 | // reservation write-watched for the shadows (on the console it is not write-watched, and a reset would clear the bits | ||
| 1406 | // the shadows ask about): the journal still sees the write. | ||
| 1407 | void test_write_watch_rereserve(XMemVirtualAllocFn virtual_alloc, XMemGetWriteWatchFn get_write_watch, | ||
| 1408 | XMemResetWriteWatchFn reset_write_watch) { | ||
| 1409 | if (!leonida::title_write_watch::enabled()) return; | ||
| 1410 | namespace ww = leonida::title_write_watch; | ||
| 1411 | const auto title_free = reinterpret_cast<HostVirtualFreeFn>(rt::shims::find("kernel32.dll", "VirtualFree")); | ||
| 1412 | const auto title_alloc = reinterpret_cast<HostVirtualAllocFn>(rt::shims::find("kernel32.dll", "VirtualAlloc")); | ||
| 1413 | if (!title_free || !title_alloc) return; | ||
| 1414 | constexpr SIZE_T kSize = 0x10000; | ||
| 1415 | // The pages of [base, base + kSize) the reader is told were written. | ||
| 1416 | const auto told = [](std::uint64_t reader, void* base) { | ||
| 1417 | const auto from = reinterpret_cast<uintptr_t>(base); | ||
| 1418 | const std::vector<std::pair<uintptr_t, uintptr_t>> runs{{from, from + kSize}}; | ||
| 1419 | size_t pages = 0; | ||
| 1420 | ww::ask( | ||
| 1421 | reader, runs, [&](uintptr_t a, uintptr_t b) { pages += (b - a) / ww::kPage; }, [](uintptr_t, uintptr_t) {}); | ||
| 1422 | return pages; | ||
| 1423 | }; | ||
| 1424 | struct Way { | ||
| 1425 | const char* what; | ||
| 1426 | std::function<void*(void*)> reserve; // MEM_RESERVE | MEM_COMMIT at the address (null: anywhere) | ||
| 1427 | }; | ||
| 1428 | const Way ways[] = { | ||
| 1429 | {"kernel32!VirtualAlloc", | ||
| 1430 | [&](void* at) { return title_alloc(at, kSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); }}, | ||
| 1431 | {"XMemVirtualAlloc", [&](void* at) { return virtual_alloc(at, kSize, MEM_RESERVE | MEM_COMMIT, 0, PAGE_READWRITE); }}, | ||
| 1432 | }; | ||
| 1433 | char what[192]; | ||
| 1434 | for (const Way& way : ways) { | ||
| 1435 | void* base = nullptr; | ||
| 1436 | std::uint64_t reader = 0; | ||
| 1437 | bool told_once = true, same_address = false; | ||
| 1438 | // Another thread may take the range between the release and the new reservation: tried again elsewhere. | ||
| 1439 | for (int attempt = 0; attempt < 8 && !same_address; ++attempt) { | ||
| 1440 | base = way.reserve(nullptr); | ||
| 1441 | if (!base) break; | ||
| 1442 | reader = ww::open_reader(); | ||
| 1443 | static_cast<volatile uint8_t*>(base)[0x10] = 1; | ||
| 1444 | told_once = told_once && told(reader, base) == 1 && told(reader, base) == 0; | ||
| 1445 | void* const again = title_free(base, 0, MEM_RELEASE) ? way.reserve(base) : nullptr; | ||
| 1446 | same_address = again == base; | ||
| 1447 | if (!same_address) { | ||
| 1448 | ww::close_reader(reader); | ||
| 1449 | if (again) title_free(again, 0, MEM_RELEASE); | ||
| 1450 | } | ||
| 1451 | } | ||
| 1452 | std::snprintf(what, sizeof what, "%s: a write to a new reservation is told once", way.what); | ||
| 1453 | check(told_once, what); | ||
| 1454 | std::snprintf(what, sizeof what, "%s: released and reserved again at the same address", way.what); | ||
| 1455 | check(same_address, what); | ||
| 1456 | if (!same_address) continue; | ||
| 1457 | std::snprintf(what, sizeof what, "%s: the new reservation's pages are all told as written", way.what); | ||
| 1458 | check(told(reader, base) == kSize / ww::kPage, what); | ||
| 1459 | check(told(reader, base) == 0, "and only once"); | ||
| 1460 | std::snprintf(what, sizeof what, "%s: a page decommitted and committed again is told as written", way.what); | ||
| 1461 | check(title_free(static_cast<uint8_t*>(base) + 0x3000, 0x1000, MEM_DECOMMIT) && | ||
| 1462 | title_alloc(static_cast<uint8_t*>(base) + 0x3000, 0x1000, MEM_COMMIT, PAGE_READWRITE) && | ||
| 1463 | told(reader, base) == 1, | ||
| 1464 | what); | ||
| 1465 | // The title's own write-watch calls leave the shadows' bits alone. | ||
| 1466 | static_cast<volatile uint8_t*>(base)[0x5010] = 1; | ||
| 1467 | void* found[16]{}; | ||
| 1468 | ULONG_PTR count = 16; | ||
| 1469 | ULONG granularity = 0; | ||
| 1470 | std::snprintf(what, sizeof what, "%s: XMemResetWriteWatch and XMemGetWriteWatch refuse the shadows' reservation", | ||
| 1471 | way.what); | ||
| 1472 | check(reset_write_watch(base, kSize) != 0 && | ||
| 1473 | get_write_watch(WRITE_WATCH_FLAG_RESET, base, kSize, found, &count, &granularity) != 0, | ||
| 1474 | what); | ||
| 1475 | check(told(reader, base) == 1, "the write is still told to the shadows"); | ||
| 1476 | ww::close_reader(reader); | ||
| 1477 | title_free(base, 0, MEM_RELEASE); | ||
| 1478 | } | ||
| 1479 | } | ||
| 1480 | |||
| 952 | void print_result() { | 1481 | void print_result() { |
| 953 | if (g_failures == 0) { | 1482 | if (g_failures == 0) { |
| 954 | std::printf("xmem_test: OK (%d checks)\n", g_checks); | 1483 | std::printf("xmem_test: OK (%d checks)\n", g_checks); |
| @@ -1023,6 +1552,9 @@ int main() { | |||
| 1023 | } | 1552 | } |
| 1024 | 1553 | ||
| 1025 | test_title_virtual_alloc(); | 1554 | test_title_virtual_alloc(); |
| 1555 | if (virtual_alloc) test_write_watched_reservations(virtual_alloc); | ||
| 1556 | if (virtual_alloc && get_write_watch && reset_write_watch) | ||
| 1557 | test_write_watch_rereserve(virtual_alloc, get_write_watch, reset_write_watch); | ||
| 1026 | 1558 | ||
| 1027 | if (alloc_default && free_default) test_default_alloc(alloc, free_mem, alloc_default, free_default); | 1559 | if (alloc_default && free_default) test_default_alloc(alloc, free_mem, alloc_default, free_default); |
| 1028 | if (tools_mem) check(tools_mem() == FALSE, "XMemIsToolsMemAvailable returns FALSE (no devkit tools memory)"); | 1560 | if (tools_mem) check(tools_mem() == FALSE, "XMemIsToolsMemAvailable returns FALSE (no devkit tools memory)"); |
| @@ -1032,8 +1564,11 @@ int main() { | |||
| 1032 | test_physical_pages_commit_on_touch(physical); | 1564 | test_physical_pages_commit_on_touch(physical); |
| 1033 | test_commit_physical_pages(physical); | 1565 | test_commit_physical_pages(physical); |
| 1034 | test_first_touch_during_remap(physical); | 1566 | test_first_touch_during_remap(physical); |
| 1567 | test_long_run(physical); | ||
| 1568 | test_split_under_reader(physical); | ||
| 1035 | test_placeholders(physical); | 1569 | test_placeholders(physical); |
| 1036 | test_write_combine_window(physical); | 1570 | test_write_combine_window(physical); |
| 1571 | test_heap_lock_faults(physical); | ||
| 1037 | } | 1572 | } |
| 1038 | 1573 | ||
| 1039 | print_result(); | 1574 | print_result(); |