diff options
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 01e27d32e..638100414 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]; |
| @@ -621,9 +707,11 @@ void test_first_touch_during_remap(const PhysicalApi& api) { | |||
| 621 | std::atomic<bool> stop{false}; | 707 | std::atomic<bool> stop{false}; |
| 622 | std::atomic<uint64_t> touches{0}; | 708 | std::atomic<uint64_t> touches{0}; |
| 623 | std::atomic<uint64_t> unmapped_faults{0}; | 709 | std::atomic<uint64_t> unmapped_faults{0}; |
| 710 | std::atomic<int> started_writers{0}; | ||
| 624 | std::vector<std::thread> writers; | 711 | std::vector<std::thread> writers; |
| 625 | for (int t = 0; t < 4; ++t) { | 712 | for (int t = 0; t < 4; ++t) { |
| 626 | writers.emplace_back([&, t] { | 713 | writers.emplace_back([&, t] { |
| 714 | started_writers.fetch_add(1); | ||
| 627 | uint64_t i = static_cast<uint64_t>(t); | 715 | uint64_t i = static_cast<uint64_t>(t); |
| 628 | while (!stop.load(std::memory_order_relaxed)) { | 716 | while (!stop.load(std::memory_order_relaxed)) { |
| 629 | auto* const word = | 717 | auto* const word = |
| @@ -637,6 +725,8 @@ void test_first_touch_during_remap(const PhysicalApi& api) { | |||
| 637 | } | 725 | } |
| 638 | }); | 726 | }); |
| 639 | } | 727 | } |
| 728 | // The remaps can finish before a writer is scheduled on a fast host, so wait for all four to run first. | ||
| 729 | while (started_writers.load() < 4) Sleep(0); | ||
| 640 | const ULONGLONG started = GetTickCount64(); | 730 | const ULONGLONG started = GetTickCount64(); |
| 641 | bool remapped = true; | 731 | bool remapped = true; |
| 642 | for (uint64_t s = 0; s < kSlices; ++s) { | 732 | for (uint64_t s = 0; s < kSlices; ++s) { |
| @@ -645,6 +735,8 @@ void test_first_touch_during_remap(const PhysicalApi& api) { | |||
| 645 | remapped &= api.map(window, kSlice, nullptr) == window; | 735 | remapped &= api.map(window, kSlice, nullptr) == window; |
| 646 | } | 736 | } |
| 647 | remapped &= api.map(window, kSlice, pages.data() + (kSlices - 1) * kSlice) == window; | 737 | remapped &= api.map(window, kSlice, pages.data() + (kSlices - 1) * kSlice) == window; |
| 738 | // The last slice stays mapped: give the writers up to a second to land a write in it before stopping them. | ||
| 739 | for (const ULONGLONG until = GetTickCount64() + 1000; touches.load() == 0 && GetTickCount64() < until;) Sleep(1); | ||
| 648 | stop.store(true); | 740 | stop.store(true); |
| 649 | for (auto& writer : writers) writer.join(); | 741 | for (auto& writer : writers) writer.join(); |
| 650 | const ULONGLONG elapsed = GetTickCount64() - started; | 742 | const ULONGLONG elapsed = GetTickCount64() - started; |
| @@ -660,6 +752,102 @@ void test_first_touch_during_remap(const PhysicalApi& api) { | |||
| 660 | check(api.free_pages(count, pages.data()) == TRUE, "XMemFreePhysicalPages frees the remap race pages"); | 752 | check(api.free_pages(count, pages.data()) == TRUE, "XMemFreePhysicalPages frees the remap race pages"); |
| 661 | } | 753 | } |
| 662 | 754 | ||
| 755 | // Splitting a view briefly unmaps the view's other pages; a thread reading one of them meanwhile must not fault. | ||
| 756 | // Unmapping page k of the view [k, end) splits it every time, and the last page of each view is the one being read. | ||
| 757 | void test_split_under_reader(const PhysicalApi& api) { | ||
| 758 | constexpr uint64_t kPages = 2048; // two capped views | ||
| 759 | auto* const window = static_cast<uint8_t*>( | ||
| 760 | api.virtual_alloc(nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE)); | ||
| 761 | std::vector<uint64_t> pages(kPages); | ||
| 762 | uint64_t count = kPages; | ||
| 763 | check(window && api.allocate(0x280, &count, pages.data()) == TRUE && count == kPages && | ||
| 764 | api.map(window, kPages, pages.data()) == window, | ||
| 765 | "a 2,048-page run maps for the split test"); | ||
| 766 | if (!window || count != kPages) return; | ||
| 767 | uint8_t* const read_pages[2] = {window + 1023 * kPage64k, window + 2047 * kPage64k}; | ||
| 768 | fill_page(read_pages[0], 0x11000u); | ||
| 769 | fill_page(read_pages[1], 0x11000u); | ||
| 770 | std::atomic<bool> done{false}; | ||
| 771 | std::atomic<uint64_t> reads{0}, wrong{0}; | ||
| 772 | std::thread reader([&] { | ||
| 773 | for (uint64_t i = 0; !done.load(std::memory_order_relaxed); ++i) { | ||
| 774 | wrong += read_u32(read_pages[i & 1], 0) != 0x11000u; | ||
| 775 | ++reads; | ||
| 776 | } | ||
| 777 | }); | ||
| 778 | bool unmapped = true; | ||
| 779 | for (uint64_t k = 0; k < kPages - 1; ++k) { | ||
| 780 | if (k == 1023) continue; | ||
| 781 | void* const page = window + k * kPage64k; | ||
| 782 | unmapped &= api.scatter(&page, 1, nullptr) == TRUE; | ||
| 783 | } | ||
| 784 | done = true; | ||
| 785 | reader.join(); | ||
| 786 | check(unmapped, "2,046 pages unmap one at a time, each splitting the view a reader is in"); | ||
| 787 | check(reads.load() > 0 && wrong.load() == 0, "the reader of the views' last pages never faults or misreads"); | ||
| 788 | // The last split was of [2046, 2048): a fault there is retried, one on another mapped page is not. | ||
| 789 | api.map(window, kPages, nullptr); | ||
| 790 | api.free_pages(kPages, pages.data()); | ||
| 791 | } | ||
| 792 | |||
| 793 | // A run longer than one host view is mapped as capped views, so unmapping one page inside it only remaps the rest of | ||
| 794 | // that view; every other page keeps its contents. | ||
| 795 | void test_long_run(const PhysicalApi& api) { | ||
| 796 | constexpr uint64_t kPages = 1100; // more than the 1024-page view cap | ||
| 797 | auto* const window = static_cast<uint8_t*>( | ||
| 798 | api.virtual_alloc(nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x23, PAGE_READWRITE)); | ||
| 799 | std::vector<uint64_t> pages(kPages); | ||
| 800 | uint64_t count = kPages; | ||
| 801 | check(window && api.allocate(0x280, &count, pages.data()) == TRUE, "a long run's window and pages are allocated"); | ||
| 802 | if (!window || count != kPages) return; | ||
| 803 | check(api.map(window, kPages, pages.data()) == window, "a run longer than the view cap maps"); | ||
| 804 | // The pages are committed on first touch, so an untouched view reads MEM_RESERVE on Windows (Wine reports | ||
| 805 | // MEM_COMMIT); either way the first region is one mapped view of exactly the cap. | ||
| 806 | MEMORY_BASIC_INFORMATION info{}; | ||
| 807 | VirtualQuery(window, &info, sizeof(info)); | ||
| 808 | check(info.Type == MEM_MAPPED && (info.State == MEM_COMMIT || info.State == MEM_RESERVE) && | ||
| 809 | info.RegionSize == 1024 * kPage64k, | ||
| 810 | "it is mapped as views of at most 1024 pages"); | ||
| 811 | for (uint64_t i = 0; i < kPages; ++i) fill_page(window + i * kPage64k, static_cast<uint32_t>(i + 1)); | ||
| 812 | void* const hole = window + 10 * kPage64k; | ||
| 813 | check(api.scatter(&hole, 1, nullptr) == TRUE && reserved_only(hole), "a page inside the first view unmaps"); | ||
| 814 | bool kept = true; | ||
| 815 | for (uint64_t i = 0; i < kPages; ++i) { | ||
| 816 | if (i != 10) kept &= page_holds(window + i * kPage64k, static_cast<uint32_t>(i + 1)); | ||
| 817 | } | ||
| 818 | check(kept, "every other page of the run keeps its contents"); | ||
| 819 | // Several pages across the boundary of two capped views unmap together; the pages on both sides stay. | ||
| 820 | check(api.map(window + 1000 * kPage64k, 50, nullptr) == window + 1000 * kPage64k && | ||
| 821 | reserved_only(window + 1000 * kPage64k) && reserved_only(window + 1049 * kPage64k), | ||
| 822 | "a multi-page range across two views unmaps"); | ||
| 823 | check(page_holds(window + 999 * kPage64k, 1000u) && page_holds(window + 1050 * kPage64k, 1051u), | ||
| 824 | "the pages on both sides of it keep their contents"); | ||
| 825 | // Mapping other pages over the middle of a live run replaces just those pages. | ||
| 826 | check(api.map(window + 500 * kPage64k, 3, &pages[600]) == window + 500 * kPage64k && | ||
| 827 | page_holds(window + 500 * kPage64k, 601u) && page_holds(window + 502 * kPage64k, 603u), | ||
| 828 | "pages mapped over the middle of a live run replace it there"); | ||
| 829 | check(page_holds(window + 499 * kPage64k, 500u) && page_holds(window + 503 * kPage64k, 504u), | ||
| 830 | "and the run's pages around them keep their contents"); | ||
| 831 | check(api.map(window, kPages, nullptr) == window && reserved_only(window) && | ||
| 832 | reserved_only(window + (kPages - 1) * kPage64k), | ||
| 833 | "the whole run unmaps"); | ||
| 834 | check(api.free_pages(kPages, pages.data()) == TRUE, "the long run's pages are freed"); | ||
| 835 | check(api.map(window, 1, pages.data()) == nullptr && reserved_only(window), "a freed page does not map again"); | ||
| 836 | // Pages freed while still mapped keep their memory, and splitting their view later still maps the rest again. | ||
| 837 | count = 4; | ||
| 838 | check(api.allocate(0x280, &count, pages.data()) == TRUE && count == 4 && api.map(window, 4, pages.data()) == window, | ||
| 839 | "four pages map as one view"); | ||
| 840 | if (count != 4) return; | ||
| 841 | for (uint64_t i = 0; i < 4; ++i) fill_page(window + i * kPage64k, static_cast<uint32_t>(i + 1)); | ||
| 842 | check(api.free_pages(4, pages.data()) == TRUE, "they are freed while mapped"); | ||
| 843 | void* const second = window + kPage64k; | ||
| 844 | check(api.scatter(&second, 1, nullptr) == TRUE && !reserved_only(window) && | ||
| 845 | !reserved_only(window + 2 * kPage64k) && page_holds(window, 1u) && | ||
| 846 | page_holds(window + 2 * kPage64k, 3u) && page_holds(window + 3 * kPage64k, 4u), | ||
| 847 | "unmapping one of them afterwards keeps the others' memory"); | ||
| 848 | api.map(window, 4, nullptr); | ||
| 849 | } | ||
| 850 | |||
| 663 | // The placeholder flags pass through: reserve a placeholder, carve windows and committed memory out of it. | 851 | // The placeholder flags pass through: reserve a placeholder, carve windows and committed memory out of it. |
| 664 | void test_placeholders(const PhysicalApi& api) { | 852 | void test_placeholders(const PhysicalApi& api) { |
| 665 | auto* const base = static_cast<uint8_t*>( | 853 | auto* const base = static_cast<uint8_t*>( |
| @@ -724,6 +912,168 @@ void test_write_combine_window(const PhysicalApi& api) { | |||
| 724 | check(api.free_pages(1, &page) == TRUE, "free the write-combine window's page"); | 912 | check(api.free_pages(1, &page) == TRUE, "free the write-combine window's page"); |
| 725 | } | 913 | } |
| 726 | 914 | ||
| 915 | // Counts the access violations in [g_counted_begin, g_counted_end). Added after xmem's handler with First = 1, so it | ||
| 916 | // runs before it and sees every fault there, the ones xmem then commits included. | ||
| 917 | std::atomic<uintptr_t> g_counted_begin{0}, g_counted_end{0}; | ||
| 918 | std::atomic<uint64_t> g_counted_faults{0}; | ||
| 919 | |||
| 920 | LONG CALLBACK count_window_faults(EXCEPTION_POINTERS* info) { | ||
| 921 | const EXCEPTION_RECORD* record = info ? info->ExceptionRecord : nullptr; | ||
| 922 | if (record && record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && record->NumberParameters >= 2) { | ||
| 923 | const auto at = static_cast<uintptr_t>(record->ExceptionInformation[1]); | ||
| 924 | if (at >= g_counted_begin.load(std::memory_order_relaxed) && at < g_counted_end.load(std::memory_order_relaxed)) | ||
| 925 | g_counted_faults.fetch_add(1, std::memory_order_relaxed); | ||
| 926 | } | ||
| 927 | return EXCEPTION_CONTINUE_SEARCH; | ||
| 928 | } | ||
| 929 | |||
| 930 | // About `us` microseconds of spinning, without a call that could allocate. | ||
| 931 | void spin_for(LONGLONG us) { | ||
| 932 | LARGE_INTEGER now{}, frequency{}; | ||
| 933 | QueryPerformanceFrequency(&frequency); | ||
| 934 | QueryPerformanceCounter(&now); | ||
| 935 | const LONGLONG until = now.QuadPart + frequency.QuadPart * us / 1000000; | ||
| 936 | while (QueryPerformanceCounter(&now) && now.QuadPart < until) YieldProcessor(); | ||
| 937 | } | ||
| 938 | |||
| 939 | // Title threads take access violations while they hold the process heap's lock: XMemAlloc is _aligned_malloc, so | ||
| 940 | // HeapAlloc and HeapFree write block headers on title pages, which may be physical pages waiting for their first touch | ||
| 941 | // or pages the D3D12 layer's shadows guard. xmem's handler waits for g_fault_lock (shared) at every access violation, | ||
| 942 | // its own or not, so whoever holds that lock exclusively (a map or an unmap of physical pages) must never wait for the | ||
| 943 | // process heap meanwhile: it would wait for the faulting thread, which waits for it. While | ||
| 944 | // - threads take the process heap's lock (HeapLock, as HeapAlloc does inside, and the heap gate above) and, holding | ||
| 945 | // it, _aligned_malloc and _aligned_free and write a word into every page of a window whose pages are mapped fresh | ||
| 946 | // all the time (a first-touch commit, or a fault on a page that is being unmapped) and into a read-only page (a | ||
| 947 | // fault that isn't xmem's, as on a guarded shadow page); | ||
| 948 | // - threads allocate physical pages, map them into their part of the window (as a run, or page by page through the | ||
| 949 | // scatter call), and unmap and free them, some freed while still mapped so that the unmap drops the last | ||
| 950 | // reference to their section; | ||
| 951 | // a watchdog ends the process (exit code 3) when nothing got anywhere for 30 s: a deadlock. | ||
| 952 | void test_heap_lock_faults(const PhysicalApi& api) { | ||
| 953 | if (const HMODULE ntdll = GetModuleHandleW(L"ntdll.dll"); ntdll && GetProcAddress(ntdll, "wine_get_version")) { | ||
| 954 | // Under Wine a holder of the fault lock still reaches the process heap through the host's own view calls (or | ||
| 955 | // Wine's fault dispatch needs it): the test deadlocks there with the fix in. The Wine side is an open item. | ||
| 956 | std::printf("SKIP heap-lock faults under Wine: a fault-lock holder still waits for the process heap there\n"); | ||
| 957 | return; | ||
| 958 | } | ||
| 959 | constexpr uint64_t kMappers = 2, kSlice = 4, kPages = kMappers * kSlice; | ||
| 960 | constexpr unsigned kTouchers = 3; | ||
| 961 | auto* const window = static_cast<uint8_t*>( | ||
| 962 | api.virtual_alloc(nullptr, kPages * kPage64k, MEM_RESERVE | kXmem64kPages, 0x21, PAGE_READWRITE)); | ||
| 963 | auto* const read_only = static_cast<uint8_t*>(VirtualAlloc(nullptr, 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_READONLY)); | ||
| 964 | check(window != nullptr && read_only != nullptr, "a window and a read-only page for the heap-lock faults"); | ||
| 965 | if (!window || !read_only) return; | ||
| 966 | g_counted_begin = reinterpret_cast<uintptr_t>(window); | ||
| 967 | g_counted_end = reinterpret_cast<uintptr_t>(window) + kPages * kPage64k; | ||
| 968 | g_counted_faults = 0; | ||
| 969 | // xmem's handler is in by now (the first XMemAllocatePhysicalPages put it in), so this one runs first. | ||
| 970 | void* const counter = AddVectoredExceptionHandler(1, &count_window_faults); | ||
| 971 | check(counter != nullptr, "a fault counter in front of xmem's handler"); | ||
| 972 | if (!counter) return; | ||
| 973 | |||
| 974 | std::atomic<uint64_t> progress{0}; // bumped by every round of every thread | ||
| 975 | std::atomic<bool> stop{false}, finished{false}, failed{false}; | ||
| 976 | std::thread watchdog([&] { | ||
| 977 | uint64_t seen = progress.load(); | ||
| 978 | ULONGLONG since = GetTickCount64(); | ||
| 979 | while (!finished.load()) { | ||
| 980 | Sleep(100); | ||
| 981 | const uint64_t now = progress.load(); | ||
| 982 | if (now != seen) { | ||
| 983 | seen = now; | ||
| 984 | since = GetTickCount64(); | ||
| 985 | } else if (GetTickCount64() - since > 30000) { | ||
| 986 | // No heap here: the process heap may be what is stuck. | ||
| 987 | static const char message[] = | ||
| 988 | "xmem heap-lock faults: no progress for 30 s: deadlock (a holder of the lock xmem's fault handler " | ||
| 989 | "waits for is waiting for the process heap)\n"; | ||
| 990 | DWORD wrote = 0; | ||
| 991 | WriteFile(GetStdHandle(STD_ERROR_HANDLE), message, DWORD(sizeof(message) - 1), &wrote, nullptr); | ||
| 992 | TerminateProcess(GetCurrentProcess(), 3); | ||
| 993 | } | ||
| 994 | } | ||
| 995 | }); | ||
| 996 | std::atomic<uint64_t> rounds{0}, missed{0}, read_only_faults{0}, maps{0}; | ||
| 997 | std::vector<std::thread> threads; | ||
| 998 | threads.reserve(kTouchers + kMappers); | ||
| 999 | g_heap_gate_on = true; | ||
| 1000 | for (unsigned t = 0; t < kTouchers; ++t) | ||
| 1001 | threads.emplace_back([&, t] { | ||
| 1002 | const HANDLE heap = GetProcessHeap(); | ||
| 1003 | for (unsigned round = 0; !stop.load(std::memory_order_relaxed); ++round) { | ||
| 1004 | uint64_t round_missed = 0; | ||
| 1005 | bool round_read_only = false; | ||
| 1006 | AcquireSRWLockExclusive(&g_heap_gate); | ||
| 1007 | HeapLock(heap); | ||
| 1008 | void* block = _aligned_malloc(64 + (round % 32) * 160, 16); | ||
| 1009 | for (uint64_t p = 0; p < kPages; ++p) { | ||
| 1010 | auto* const word = | ||
| 1011 | static_cast<volatile uint32_t*>(static_cast<void*>(window + p * kPage64k)) + t; | ||
| 1012 | round_missed += access_faults(word, true); | ||
| 1013 | } | ||
| 1014 | round_read_only = access_faults(static_cast<volatile uint32_t*>(static_cast<void*>(read_only)), true); | ||
| 1015 | _aligned_free(block); | ||
| 1016 | HeapUnlock(heap); | ||
| 1017 | ReleaseSRWLockExclusive(&g_heap_gate); | ||
| 1018 | missed.fetch_add(round_missed, std::memory_order_relaxed); | ||
| 1019 | read_only_faults.fetch_add(round_read_only, std::memory_order_relaxed); | ||
| 1020 | rounds.fetch_add(1, std::memory_order_relaxed); | ||
| 1021 | progress.fetch_add(1, std::memory_order_relaxed); | ||
| 1022 | spin_for(50); // the other threads get to allocate | ||
| 1023 | } | ||
| 1024 | }); | ||
| 1025 | for (uint64_t m = 0; m < kMappers; ++m) | ||
| 1026 | threads.emplace_back([&, m] { | ||
| 1027 | uint8_t* const slice = window + m * kSlice * kPage64k; | ||
| 1028 | uint64_t pages[kSlice]{}; | ||
| 1029 | void* addresses[kSlice]{}; | ||
| 1030 | for (uint64_t k = 0; k < kSlice; ++k) addresses[k] = slice + k * kPage64k; | ||
| 1031 | for (uint64_t round = 0; !stop.load(std::memory_order_relaxed); ++round) { | ||
| 1032 | uint64_t count = kSlice; | ||
| 1033 | if (api.allocate(0x280, &count, pages) != TRUE || count != kSlice) { | ||
| 1034 | failed = true; | ||
| 1035 | break; | ||
| 1036 | } | ||
| 1037 | bool ok = round % 2 == 0 ? api.map(slice, kSlice, pages) == slice | ||
| 1038 | : api.scatter(addresses, static_cast<uint32_t>(kSlice), pages) == TRUE; | ||
| 1039 | spin_for(100); // the touchers get to fault the fresh pages in | ||
| 1040 | // Freed while mapped: the unmap then drops the last reference to the section. | ||
| 1041 | const bool free_first = round % 3 == 0; | ||
| 1042 | if (free_first) ok &= api.free_pages(kSlice, pages) == TRUE; | ||
| 1043 | ok &= api.map(slice, kSlice, nullptr) == slice; | ||
| 1044 | if (!free_first) ok &= api.free_pages(kSlice, pages) == TRUE; | ||
| 1045 | if (!ok) { | ||
| 1046 | failed = true; | ||
| 1047 | break; | ||
| 1048 | } | ||
| 1049 | maps.fetch_add(1, std::memory_order_relaxed); | ||
| 1050 | progress.fetch_add(1, std::memory_order_relaxed); | ||
| 1051 | } | ||
| 1052 | }); | ||
| 1053 | for (const ULONGLONG until = GetTickCount64() + 3000; !failed.load() && GetTickCount64() < until;) Sleep(10); | ||
| 1054 | stop = true; | ||
| 1055 | for (std::thread& thread : threads) thread.join(); | ||
| 1056 | g_heap_gate_on = false; | ||
| 1057 | finished = true; | ||
| 1058 | watchdog.join(); | ||
| 1059 | RemoveVectoredExceptionHandler(counter); | ||
| 1060 | g_counted_end = 0; | ||
| 1061 | |||
| 1062 | const uint64_t window_faults = g_counted_faults.load(); | ||
| 1063 | // A fault in the window that the toucher's own handler didn't catch is one xmem's handler resolved: a first touch | ||
| 1064 | // (or a retry of one another toucher committed meanwhile). | ||
| 1065 | const uint64_t committed = window_faults > missed.load() ? window_faults - missed.load() : 0; | ||
| 1066 | check(!failed.load(), "physical pages allocate, map (run and scatter), unmap and free while faults hold the heap"); | ||
| 1067 | check(maps.load() > 0 && rounds.load() > 0, "the mappers and the faulting threads both made progress"); | ||
| 1068 | check(committed > 0, "threads holding the process heap's lock took first-touch faults xmem committed"); | ||
| 1069 | check(read_only_faults.load() == rounds.load(), "every write to the read-only page faulted through xmem's handler"); | ||
| 1070 | std::printf("heap-lock faults: %llu mappings, %llu rounds holding the process heap's lock, %llu first touches " | ||
| 1071 | "committed, %llu faults on unmapped pages: no deadlock\n", | ||
| 1072 | static_cast<unsigned long long>(maps.load()), static_cast<unsigned long long>(rounds.load()), | ||
| 1073 | static_cast<unsigned long long>(committed), static_cast<unsigned long long>(missed.load())); | ||
| 1074 | VirtualFree(read_only, 0, MEM_RELEASE); | ||
| 1075 | } | ||
| 1076 | |||
| 727 | // gta6rt --trace: one "xmem_attributes" event per distinct raw attribute word and API, none with the trace off. | 1077 | // gta6rt --trace: one "xmem_attributes" event per distinct raw attribute word and API, none with the trace off. |
| 728 | void test_attribute_trace(XMemAllocFn alloc, XMemFreeFn free_mem, XMemVirtualAllocFn virtual_alloc) { | 1078 | void test_attribute_trace(XMemAllocFn alloc, XMemFreeFn free_mem, XMemVirtualAllocFn virtual_alloc) { |
| 729 | wchar_t temp[MAX_PATH]; | 1079 | wchar_t temp[MAX_PATH]; |
| @@ -854,6 +1204,8 @@ void test_transfer_trace(XMemTransferMemoryFn transfer) { | |||
| 854 | } | 1204 | } |
| 855 | 1205 | ||
| 856 | using HostVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, DWORD); | 1206 | using HostVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, DWORD); |
| 1207 | using HostVirtualFreeFn = BOOL(WINAPI*)(void*, SIZE_T, DWORD); | ||
| 1208 | using HostVirtualProtectFn = BOOL(WINAPI*)(void*, SIZE_T, DWORD, PDWORD); | ||
| 857 | 1209 | ||
| 858 | // RT-217: a title's kernel32!VirtualAlloc carries the console's MEM_GRAPHICS / MEM_TITLE type bits, which the host | 1210 | // RT-217: a title's kernel32!VirtualAlloc carries the console's MEM_GRAPHICS / MEM_TITLE type bits, which the host |
| 859 | // rejects. The registered shim has to drop them and still allocate. | 1211 | // rejects. The registered shim has to drop them and still allocate. |
| @@ -863,18 +1215,30 @@ void test_title_virtual_alloc() { | |||
| 863 | const char* const dlls[] = {"kernel32.dll", "kernelbase.dll", "api-ms-win-core-memory-l1-1-0.dll"}; | 1215 | const char* const dlls[] = {"kernel32.dll", "kernelbase.dll", "api-ms-win-core-memory-l1-1-0.dll"}; |
| 864 | for (const char* dll : dlls) { | 1216 | for (const char* dll : dlls) { |
| 865 | const auto alloc = reinterpret_cast<HostVirtualAllocFn>(rt::shims::find(dll, "VirtualAlloc")); | 1217 | const auto alloc = reinterpret_cast<HostVirtualAllocFn>(rt::shims::find(dll, "VirtualAlloc")); |
| 1218 | const auto free = reinterpret_cast<HostVirtualFreeFn>(rt::shims::find(dll, "VirtualFree")); | ||
| 1219 | const auto protect = reinterpret_cast<HostVirtualProtectFn>(rt::shims::find(dll, "VirtualProtect")); | ||
| 866 | char what[160]; | 1220 | char what[160]; |
| 867 | std::snprintf(what, sizeof what, "registry exposes %s!VirtualAlloc", dll); | 1221 | std::snprintf(what, sizeof what, "registry exposes %s's virtual memory shims", dll); |
| 868 | check(alloc != nullptr, what); | 1222 | check(alloc && free && protect, what); |
| 869 | if (!alloc) continue; | 1223 | if (!alloc || !free || !protect) continue; |
| 870 | 1224 | ||
| 1225 | auto generation = leonida::title_memory_map::generation(); | ||
| 871 | void* const gfx = alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT, 0x2004); // PAGE_GRAPHICS_READWRITE | 1226 | void* const gfx = alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT, 0x2004); // PAGE_GRAPHICS_READWRITE |
| 872 | check(gfx != nullptr, "title VirtualAlloc with protect 0x2004 succeeds"); | 1227 | check(gfx != nullptr, "title VirtualAlloc with protect 0x2004 succeeds"); |
| 873 | if (gfx) { | 1228 | if (gfx) { |
| 1229 | check(leonida::title_memory_map::generation() != generation, "title VirtualAlloc invalidates shadows"); | ||
| 874 | MEMORY_BASIC_INFORMATION mbi{}; | 1230 | MEMORY_BASIC_INFORMATION mbi{}; |
| 875 | check(VirtualQuery(gfx, &mbi, sizeof mbi) && mbi.Protect == PAGE_READWRITE, | 1231 | check(VirtualQuery(gfx, &mbi, sizeof mbi) && mbi.Protect == PAGE_READWRITE, |
| 876 | "protect 0x2004 commits PAGE_READWRITE"); | 1232 | "protect 0x2004 commits PAGE_READWRITE"); |
| 877 | VirtualFree(gfx, 0, MEM_RELEASE); | 1233 | DWORD old = 0; |
| 1234 | generation = leonida::title_memory_map::generation(); | ||
| 1235 | check(protect(gfx, 0x1000, PAGE_READONLY, &old) && old == PAGE_READWRITE, | ||
| 1236 | "title VirtualProtect changes protection and returns the previous protection"); | ||
| 1237 | check(leonida::title_memory_map::generation() != generation, "title VirtualProtect invalidates shadows"); | ||
| 1238 | generation = leonida::title_memory_map::generation(); | ||
| 1239 | check(free(gfx, 0x1000, MEM_DECOMMIT), "title VirtualFree decommits a page"); | ||
| 1240 | check(leonida::title_memory_map::generation() != generation, "title VirtualFree invalidates shadows"); | ||
| 1241 | check(free(gfx, 0, MEM_RELEASE), "release the graphics allocation"); | ||
| 878 | } | 1242 | } |
| 879 | for (const DWORD bits : {kMemGraphics, kMemTitle, kMemGraphics | kMemTitle, DWORD{0}}) { | 1243 | for (const DWORD bits : {kMemGraphics, kMemTitle, kMemGraphics | kMemTitle, DWORD{0}}) { |
| 880 | void* const p = alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT | bits, PAGE_READWRITE); | 1244 | void* const p = alloc(nullptr, 0x10000, MEM_RESERVE | MEM_COMMIT | bits, PAGE_READWRITE); |
| @@ -889,6 +1253,171 @@ void test_title_virtual_alloc() { | |||
| 889 | } | 1253 | } |
| 890 | } | 1254 | } |
| 891 | 1255 | ||
| 1256 | // The title's ordinary reservations are write-watched for the D3D12 layer's shadows (leonida::title_write_watch): | ||
| 1257 | // XMemVirtualAlloc's plain, 2 MiB and 64 KiB committed regions and kernel32!VirtualAlloc's reservations, each recorded | ||
| 1258 | // until the title releases it. Placeholders and physical-page windows are not (a section view can't be), nor is a | ||
| 1259 | // region the title asked to be write-watched itself (its bits are the title's). With LEONIDA_WRITE_WATCH=0 (the | ||
| 1260 | // xmem_no_write_watch test) nothing is. | ||
| 1261 | void test_write_watched_reservations(XMemVirtualAllocFn virtual_alloc) { | ||
| 1262 | const bool on = leonida::title_write_watch::enabled(); | ||
| 1263 | std::printf("xmem_test: write watching %s\n", on ? "on" : "off (LEONIDA_WRITE_WATCH=0)"); | ||
| 1264 | const auto kernel_watching = [](void* base, SIZE_T size) { | ||
| 1265 | void* found[16]{}; | ||
| 1266 | ULONG_PTR count = 16; | ||
| 1267 | ULONG granularity = 0; | ||
| 1268 | return GetWriteWatch(0, base, size, found, &count, &granularity) == 0; | ||
| 1269 | }; | ||
| 1270 | const auto title_free = reinterpret_cast<HostVirtualFreeFn>(rt::shims::find("kernel32.dll", "VirtualFree")); | ||
| 1271 | const auto title_alloc = reinterpret_cast<HostVirtualAllocFn>(rt::shims::find("kernel32.dll", "VirtualAlloc")); | ||
| 1272 | check(title_free && title_alloc, "registry exposes kernel32.dll's VirtualAlloc and VirtualFree shims"); | ||
| 1273 | if (!title_free || !title_alloc) return; | ||
| 1274 | struct Case { | ||
| 1275 | const char* what; | ||
| 1276 | DWORD type; | ||
| 1277 | SIZE_T size; | ||
| 1278 | bool watched; | ||
| 1279 | }; | ||
| 1280 | const Case cases[] = { | ||
| 1281 | {"plain reserve+commit", MEM_RESERVE | MEM_COMMIT, 0x3000, true}, | ||
| 1282 | {"commit at no address", MEM_COMMIT, 0x3000, true}, | ||
| 1283 | {"reserve only", MEM_RESERVE, 0x20000, true}, | ||
| 1284 | {"2 MiB pages", kXmemLargePages | MEM_RESERVE | MEM_COMMIT, kPage2m, true}, | ||
| 1285 | {"64 KiB pages committed", kXmem64kPages | MEM_RESERVE | MEM_COMMIT, kPage64k * 2, true}, | ||
| 1286 | {"64 KiB physical-page window", kXmem64kPages | MEM_RESERVE, kPage64k * 2, false}, | ||
| 1287 | {"placeholder", MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, kPage64k * 2, false}, | ||
| 1288 | {"the title's own write watch", MEM_RESERVE | MEM_COMMIT | MEM_WRITE_WATCH, 0x3000, false}, | ||
| 1289 | }; | ||
| 1290 | for (const Case& c : cases) { | ||
| 1291 | void* const base = virtual_alloc(nullptr, c.size, c.type, 0, PAGE_READWRITE); | ||
| 1292 | char what[192]; | ||
| 1293 | std::snprintf(what, sizeof what, "XMemVirtualAlloc %s succeeds", c.what); | ||
| 1294 | check(base != nullptr, what); | ||
| 1295 | if (!base) continue; | ||
| 1296 | const auto at = reinterpret_cast<uintptr_t>(base); | ||
| 1297 | const bool want = on && c.watched; | ||
| 1298 | std::snprintf(what, sizeof what, "XMemVirtualAlloc %s: %s for the shadows", c.what, | ||
| 1299 | want ? "recorded write-watched" : "not recorded"); | ||
| 1300 | check(leonida::title_write_watch::contains(at) == want && | ||
| 1301 | leonida::title_write_watch::contains(at + c.size - 1) == want, | ||
| 1302 | what); | ||
| 1303 | if (want) { | ||
| 1304 | std::snprintf(what, sizeof what, "XMemVirtualAlloc %s: the kernel write-watches it", c.what); | ||
| 1305 | check(kernel_watching(base, c.size), what); | ||
| 1306 | } | ||
| 1307 | if ((c.type & MEM_RESERVE_PLACEHOLDER) || ((c.type & kXmem64kPages) == kXmem64kPages && !(c.type & MEM_COMMIT))) { | ||
| 1308 | VirtualFree(base, 0, MEM_RELEASE); | ||
| 1309 | continue; | ||
| 1310 | } | ||
| 1311 | std::snprintf(what, sizeof what, "title VirtualFree releases the region (%s) and forgets it", c.what); | ||
| 1312 | check(title_free(base, 0, MEM_RELEASE) && !leonida::title_write_watch::contains(at), what); | ||
| 1313 | } | ||
| 1314 | // kernel32!VirtualAlloc as the title calls it: a reservation is recorded, a commit inside it adds nothing. | ||
| 1315 | void* const reserved = title_alloc(nullptr, 0x40000, MEM_RESERVE, PAGE_READWRITE); | ||
| 1316 | check(reserved != nullptr, "title VirtualAlloc reserves"); | ||
| 1317 | if (!reserved) return; | ||
| 1318 | const auto at = reinterpret_cast<uintptr_t>(reserved); | ||
| 1319 | const auto generation = leonida::title_write_watch::generation(); | ||
| 1320 | check(title_alloc(reserved, 0x1000, MEM_COMMIT, PAGE_READWRITE) == reserved, "title VirtualAlloc commits in it"); | ||
| 1321 | check(leonida::title_write_watch::generation() == generation, "a commit inside a reservation records nothing new"); | ||
| 1322 | check(leonida::title_write_watch::contains(at + 0x3ffff) == on, | ||
| 1323 | on ? "title VirtualAlloc's reservation is recorded write-watched" : "title VirtualAlloc's is not recorded"); | ||
| 1324 | if (on) { | ||
| 1325 | check(kernel_watching(reserved, 0x40000), "the kernel write-watches title VirtualAlloc's reservation"); | ||
| 1326 | static_cast<volatile uint8_t*>(reserved)[0x10] = 1; | ||
| 1327 | void* found[4]{}; | ||
| 1328 | ULONG_PTR count = 4; | ||
| 1329 | ULONG granularity = 0; | ||
| 1330 | check(GetWriteWatch(0, reserved, 0x40000, found, &count, &granularity) == 0 && count == 1 && | ||
| 1331 | found[0] == reserved, | ||
| 1332 | "a write to it is in the kernel's answer"); | ||
| 1333 | } else { | ||
| 1334 | check(!kernel_watching(reserved, 0x40000), "LEONIDA_WRITE_WATCH=0: the kernel does not write-watch it"); | ||
| 1335 | } | ||
| 1336 | check(title_free(reserved, 0, MEM_RELEASE) && !leonida::title_write_watch::contains(at), | ||
| 1337 | "title VirtualFree releases it and forgets it"); | ||
| 1338 | } | ||
| 1339 | |||
| 1340 | // A reservation the title releases and reserves again at the same address is a new one to the shadows' journal | ||
| 1341 | // (leonida::title_write_watch::ask): a reader that asked over the old one is told all of the new one's pages as | ||
| 1342 | // written, though nothing wrote them (a new reservation's kernel bits are clear, and a MEM_RESERVE | MEM_COMMIT in one | ||
| 1343 | // call marks nothing). Through kernel32!VirtualAlloc and XMemVirtualAlloc; a page decommitted and committed again | ||
| 1344 | // inside a reservation is told as written too. And the title's XMemGetWriteWatch and XMemResetWriteWatch refuse a | ||
| 1345 | // reservation write-watched for the shadows (on the console it is not write-watched, and a reset would clear the bits | ||
| 1346 | // the shadows ask about): the journal still sees the write. | ||
| 1347 | void test_write_watch_rereserve(XMemVirtualAllocFn virtual_alloc, XMemGetWriteWatchFn get_write_watch, | ||
| 1348 | XMemResetWriteWatchFn reset_write_watch) { | ||
| 1349 | if (!leonida::title_write_watch::enabled()) return; | ||
| 1350 | namespace ww = leonida::title_write_watch; | ||
| 1351 | const auto title_free = reinterpret_cast<HostVirtualFreeFn>(rt::shims::find("kernel32.dll", "VirtualFree")); | ||
| 1352 | const auto title_alloc = reinterpret_cast<HostVirtualAllocFn>(rt::shims::find("kernel32.dll", "VirtualAlloc")); | ||
| 1353 | if (!title_free || !title_alloc) return; | ||
| 1354 | constexpr SIZE_T kSize = 0x10000; | ||
| 1355 | // The pages of [base, base + kSize) the reader is told were written. | ||
| 1356 | const auto told = [](std::uint64_t reader, void* base) { | ||
| 1357 | const auto from = reinterpret_cast<uintptr_t>(base); | ||
| 1358 | const std::vector<std::pair<uintptr_t, uintptr_t>> runs{{from, from + kSize}}; | ||
| 1359 | size_t pages = 0; | ||
| 1360 | ww::ask( | ||
| 1361 | reader, runs, [&](uintptr_t a, uintptr_t b) { pages += (b - a) / ww::kPage; }, [](uintptr_t, uintptr_t) {}); | ||
| 1362 | return pages; | ||
| 1363 | }; | ||
| 1364 | struct Way { | ||
| 1365 | const char* what; | ||
| 1366 | std::function<void*(void*)> reserve; // MEM_RESERVE | MEM_COMMIT at the address (null: anywhere) | ||
| 1367 | }; | ||
| 1368 | const Way ways[] = { | ||
| 1369 | {"kernel32!VirtualAlloc", | ||
| 1370 | [&](void* at) { return title_alloc(at, kSize, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE); }}, | ||
| 1371 | {"XMemVirtualAlloc", [&](void* at) { return virtual_alloc(at, kSize, MEM_RESERVE | MEM_COMMIT, 0, PAGE_READWRITE); }}, | ||
| 1372 | }; | ||
| 1373 | char what[192]; | ||
| 1374 | for (const Way& way : ways) { | ||
| 1375 | void* base = nullptr; | ||
| 1376 | std::uint64_t reader = 0; | ||
| 1377 | bool told_once = true, same_address = false; | ||
| 1378 | // Another thread may take the range between the release and the new reservation: tried again elsewhere. | ||
| 1379 | for (int attempt = 0; attempt < 8 && !same_address; ++attempt) { | ||
| 1380 | base = way.reserve(nullptr); | ||
| 1381 | if (!base) break; | ||
| 1382 | reader = ww::open_reader(); | ||
| 1383 | static_cast<volatile uint8_t*>(base)[0x10] = 1; | ||
| 1384 | told_once = told_once && told(reader, base) == 1 && told(reader, base) == 0; | ||
| 1385 | void* const again = title_free(base, 0, MEM_RELEASE) ? way.reserve(base) : nullptr; | ||
| 1386 | same_address = again == base; | ||
| 1387 | if (!same_address) { | ||
| 1388 | ww::close_reader(reader); | ||
| 1389 | if (again) title_free(again, 0, MEM_RELEASE); | ||
| 1390 | } | ||
| 1391 | } | ||
| 1392 | std::snprintf(what, sizeof what, "%s: a write to a new reservation is told once", way.what); | ||
| 1393 | check(told_once, what); | ||
| 1394 | std::snprintf(what, sizeof what, "%s: released and reserved again at the same address", way.what); | ||
| 1395 | check(same_address, what); | ||
| 1396 | if (!same_address) continue; | ||
| 1397 | std::snprintf(what, sizeof what, "%s: the new reservation's pages are all told as written", way.what); | ||
| 1398 | check(told(reader, base) == kSize / ww::kPage, what); | ||
| 1399 | check(told(reader, base) == 0, "and only once"); | ||
| 1400 | std::snprintf(what, sizeof what, "%s: a page decommitted and committed again is told as written", way.what); | ||
| 1401 | check(title_free(static_cast<uint8_t*>(base) + 0x3000, 0x1000, MEM_DECOMMIT) && | ||
| 1402 | title_alloc(static_cast<uint8_t*>(base) + 0x3000, 0x1000, MEM_COMMIT, PAGE_READWRITE) && | ||
| 1403 | told(reader, base) == 1, | ||
| 1404 | what); | ||
| 1405 | // The title's own write-watch calls leave the shadows' bits alone. | ||
| 1406 | static_cast<volatile uint8_t*>(base)[0x5010] = 1; | ||
| 1407 | void* found[16]{}; | ||
| 1408 | ULONG_PTR count = 16; | ||
| 1409 | ULONG granularity = 0; | ||
| 1410 | std::snprintf(what, sizeof what, "%s: XMemResetWriteWatch and XMemGetWriteWatch refuse the shadows' reservation", | ||
| 1411 | way.what); | ||
| 1412 | check(reset_write_watch(base, kSize) != 0 && | ||
| 1413 | get_write_watch(WRITE_WATCH_FLAG_RESET, base, kSize, found, &count, &granularity) != 0, | ||
| 1414 | what); | ||
| 1415 | check(told(reader, base) == 1, "the write is still told to the shadows"); | ||
| 1416 | ww::close_reader(reader); | ||
| 1417 | title_free(base, 0, MEM_RELEASE); | ||
| 1418 | } | ||
| 1419 | } | ||
| 1420 | |||
| 892 | void print_result() { | 1421 | void print_result() { |
| 893 | if (g_failures == 0) { | 1422 | if (g_failures == 0) { |
| 894 | std::printf("xmem_test: OK (%d checks)\n", g_checks); | 1423 | std::printf("xmem_test: OK (%d checks)\n", g_checks); |
| @@ -963,6 +1492,9 @@ int main(int argc, char** argv) { | |||
| 963 | } | 1492 | } |
| 964 | 1493 | ||
| 965 | test_title_virtual_alloc(); | 1494 | test_title_virtual_alloc(); |
| 1495 | if (virtual_alloc) test_write_watched_reservations(virtual_alloc); | ||
| 1496 | if (virtual_alloc && get_write_watch && reset_write_watch) | ||
| 1497 | test_write_watch_rereserve(virtual_alloc, get_write_watch, reset_write_watch); | ||
| 966 | 1498 | ||
| 967 | if (alloc_default && free_default) test_default_alloc(alloc, free_mem, alloc_default, free_default); | 1499 | if (alloc_default && free_default) test_default_alloc(alloc, free_mem, alloc_default, free_default); |
| 968 | if (tools_mem) check(tools_mem() == FALSE, "XMemIsToolsMemAvailable returns FALSE (no devkit tools memory)"); | 1500 | if (tools_mem) check(tools_mem() == FALSE, "XMemIsToolsMemAvailable returns FALSE (no devkit tools memory)"); |
| @@ -976,8 +1508,11 @@ int main(int argc, char** argv) { | |||
| 976 | test_physical_pages_commit_on_touch(physical); | 1508 | test_physical_pages_commit_on_touch(physical); |
| 977 | test_commit_physical_pages(physical); | 1509 | test_commit_physical_pages(physical); |
| 978 | test_first_touch_during_remap(physical); | 1510 | test_first_touch_during_remap(physical); |
| 1511 | test_long_run(physical); | ||
| 1512 | test_split_under_reader(physical); | ||
| 979 | test_placeholders(physical); | 1513 | test_placeholders(physical); |
| 980 | test_write_combine_window(physical); | 1514 | test_write_combine_window(physical); |
| 1515 | test_heap_lock_faults(physical); | ||
| 981 | } | 1516 | } |
| 982 | 1517 | ||
| 983 | print_result(); | 1518 | print_result(); |