diff --git a/CMakeLists.txt b/CMakeLists.txt index de8c359067..b25238ec53 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -356,6 +356,65 @@ set_tests_properties(xmem_lazy_imports PROPERTIES TIMEOUT 60) add_test(NAME xmem_lazy_handler_failure COMMAND xmem_lazy_imports_check "$" handler-failure) set_tests_properties(xmem_lazy_handler_failure PROPERTIES TIMEOUT 60) +# Readers that do not fault, inside a run break held open by the test-controls build: x2w_xmem_stable_call, +# XMemVirtualQuery, the VirtualQueryEx import wrapper and the stand-in readers that go through +# x2w_local::outside_run_breaks must answer after the break. Control: a copy of local_log.h that asks xmem.dll for +# a missing export, so the stand-in readers run directly and answer inside the window. +foreach(variant check control) + add_executable(xmem_run_break_readers_${variant} tests/xmem_run_break_readers_check.cpp) + target_compile_features(xmem_run_break_readers_${variant} PRIVATE cxx_std_17) + add_dependencies(xmem_run_break_readers_${variant} xmem_shim_test_controls) +endforeach() +target_include_directories(xmem_run_break_readers_check PRIVATE src) +file(READ "${CMAKE_CURRENT_SOURCE_DIR}/src/startup_stubs/local_log.h" local_log_text) +string(REPLACE "\"x2w_xmem_stable_call\"" "\"x2w_xmem_stable_call_control\"" local_log_control_text "${local_log_text}") +if(local_log_control_text STREQUAL local_log_text) + message(FATAL_ERROR "local_log.h lost the anchor used by xmem_run_break_readers_control") +endif() +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/run_break_readers_control/startup_stubs/local_log.h" "${local_log_control_text}") +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS src/startup_stubs/local_log.h) +target_include_directories(xmem_run_break_readers_control BEFORE PRIVATE "${CMAKE_CURRENT_BINARY_DIR}/run_break_readers_control") +target_include_directories(xmem_run_break_readers_control PRIVATE src) +add_test(NAME xmem_run_break_readers COMMAND xmem_run_break_readers_check "$") +add_test(NAME xmem_run_break_readers_control COMMAND xmem_run_break_readers_control + "$" control) +add_test(NAME xmem_run_break_readers_next_break_control COMMAND xmem_run_break_readers_check + "$" next-break-control) +# Default mode (no X2W_XMEM_SHARED_VIEWS): readers that overlap an unmap answer inside it, as before. Lazy commit: +# the readers' output buffer in a mapped slot not yet committed. +add_test(NAME xmem_run_break_readers_default COMMAND xmem_run_break_readers_check "$" default) +add_test(NAME xmem_run_break_readers_lazy COMMAND xmem_run_break_readers_check "$" lazy) +# A fault handler that reads the breaks after a later break on another run has begun: a second unmap on a disjoint +# run, and one permissive call that joins the CPU run and then its GPU mirror run (X2W_XMEM_GPU_MIRROR). +# ring-edge: a held fault whose break has 63 later breaks is retried; with 64 its break is no longer recorded +# (RemapWindow::kept) and the fault is passed on. +add_test(NAME xmem_run_break_readers_two_runs COMMAND xmem_run_break_readers_check "$" two-runs) +add_test(NAME xmem_run_break_readers_mirror COMMAND xmem_run_break_readers_check "$" mirror) +add_test(NAME xmem_run_break_readers_ring_edge COMMAND xmem_run_break_readers_check "$" ring-edge) +set_tests_properties(xmem_run_break_readers xmem_run_break_readers_control xmem_run_break_readers_next_break_control + xmem_run_break_readers_default xmem_run_break_readers_lazy xmem_run_break_readers_two_runs + xmem_run_break_readers_mirror xmem_run_break_readers_ring_edge PROPERTIES TIMEOUT 60) +set_tests_properties(xmem_run_break_readers_default PROPERTIES + PASS_REGULAR_EXPRESSION "default mode: readers answer inside an unmap" FAIL_REGULAR_EXPRESSION "check_failed") +# Cross-call merge of shared views (merge_with_previous): single-page calls on consecutive slots join one view, and +# the steps around it (an unmap inside, slots out of order, a reader inside the held window, refused steps, two +# reservations). The control keeps one view per call (X2W_XMEM_TEST_NO_MERGE=1, test build only); the deployed shim +# ignores that switch; without X2W_XMEM_SHARED_VIEWS every page keeps a view of its own. +add_executable(xmem_cross_call_merge_check tests/xmem_cross_call_merge_check.cpp) +target_compile_features(xmem_cross_call_merge_check PRIVATE cxx_std_17) +add_dependencies(xmem_cross_call_merge_check xmem_shim xmem_shim_test_controls) +add_test(NAME xmem_cross_call_merge COMMAND xmem_cross_call_merge_check "$" check) +add_test(NAME xmem_cross_call_merge_control COMMAND xmem_cross_call_merge_check "$" control) +add_test(NAME xmem_cross_call_merge_deployed COMMAND xmem_cross_call_merge_check "$" deployed) +add_test(NAME xmem_cross_call_merge_default COMMAND xmem_cross_call_merge_check "$" default) +set_tests_properties(xmem_cross_call_merge xmem_cross_call_merge_control xmem_cross_call_merge_deployed + xmem_cross_call_merge_default PROPERTIES TIMEOUT 60) +set_tests_properties(xmem_cross_call_merge_control PROPERTIES ENVIRONMENT "X2W_XMEM_TEST_NO_MERGE=1" + PASS_REGULAR_EXPRESSION "no-merge control: 32 views" FAIL_REGULAR_EXPRESSION "check_failed") +set_tests_properties(xmem_cross_call_merge_deployed PROPERTIES ENVIRONMENT "X2W_XMEM_TEST_NO_MERGE=1" + PASS_REGULAR_EXPRESSION "merge: 1 view of 32 pages" FAIL_REGULAR_EXPRESSION "check_failed") +set_tests_properties(xmem_cross_call_merge_default PROPERTIES + PASS_REGULAR_EXPRESSION "no-merge control: 32 views" FAIL_REGULAR_EXPRESSION "check_failed") add_executable(xmem_section_lease_check tests/xmem_section_lease_check.cpp tests/desktop_gpu.cpp) target_include_directories(xmem_section_lease_check PRIVATE src) target_compile_features(xmem_section_lease_check PRIVATE cxx_std_17) @@ -371,6 +430,32 @@ foreach(adapter warp hardware) add_test(NAME xmem_section_lease_vertex_${adapter} COMMAND xmem_section_lease_check ${adapter} "$" vertex) set_tests_properties(xmem_section_lease_vertex_${adapter} xmem_section_lease_mesh_${adapter} PROPERTIES SKIP_RETURN_CODE 77 TIMEOUT 60) endforeach() +# Slot 31 placeholder split inside an XMem reservation. The control disables the fallback used where the OS does +# not report placeholders (Wine), so the split fails there; where the OS reports them, the control skips (77). +add_executable(xmem_placeholder_split_check tests/xmem_placeholder_split_check.cpp) +target_include_directories(xmem_placeholder_split_check PRIVATE src) +target_compile_features(xmem_placeholder_split_check PRIVATE cxx_std_17) +target_link_libraries(xmem_placeholder_split_check PRIVATE OneCore) +add_dependencies(xmem_placeholder_split_check xmem_shim) +set(xmem_placeholder_env "X2W_XMEM_PERMISSIVE=1;X2W_XMEM_GPU_MIRROR=0;X2W_XMEM_LAZY_COMMIT=0;X2W_XMEM_SHARED_VIEWS=0") +add_test(NAME xmem_placeholder_split COMMAND xmem_placeholder_split_check "$") +set_tests_properties(xmem_placeholder_split PROPERTIES TIMEOUT 60 ENVIRONMENT "${xmem_placeholder_env}") +# The control passes only when the split itself fails, not on an earlier setup failure. +add_test(NAME xmem_placeholder_split_control COMMAND xmem_placeholder_split_check "$" control) +set_tests_properties(xmem_placeholder_split_control PROPERTIES + ENVIRONMENT "${xmem_placeholder_env};X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1" + PASS_REGULAR_EXPRESSION "FAIL: map two pool pages into the middle of the reservation" SKIP_RETURN_CODE 77 TIMEOUT 60) +add_executable(xmem_map_split_first_check tests/xmem_map_split_first_check.cpp) +target_include_directories(xmem_map_split_first_check PRIVATE src) +target_compile_features(xmem_map_split_first_check PRIVATE cxx_std_17) +add_dependencies(xmem_map_split_first_check xmem_shim) +add_test(NAME xmem_map_split_first COMMAND xmem_map_split_first_check "$") +add_test(NAME xmem_map_split_first_control COMMAND xmem_map_split_first_check "$" control) +set_tests_properties(xmem_map_split_first PROPERTIES TIMEOUT 60 ENVIRONMENT "${xmem_placeholder_env}") +# The control passes only when the map-first order is measured (2 maps per page), not on a setup failure. +set_tests_properties(xmem_map_split_first_control PROPERTIES + ENVIRONMENT "${xmem_placeholder_env};X2W_XMEM_TEST_MAP_FIRST=1" + PASS_REGULAR_EXPRESSION "map-first control: maps=2N" TIMEOUT 60) add_executable(xmem_startup_below_40_check tests/xmem_startup_below_40_check.cpp) target_link_libraries(xmem_startup_below_40_check PRIVATE OneCore) target_compile_features(xmem_startup_below_40_check PRIVATE cxx_std_17) @@ -975,6 +1060,39 @@ target_compile_features(startup_dstorage_destination_check PRIVATE cxx_std_17) add_dependencies(startup_dstorage_destination_check startup_stub_xcrdapi) add_test(NAME startup_dstorage_destination COMMAND startup_dstorage_destination_check "$") set_tests_properties(startup_dstorage_destination PROPERTIES TIMEOUT 60) +# A request whose destination page an XMem run break holds unmapped (the xmem test-controls build's +# X2W_XMEM_TEST_HOLD_WINDOW) must not complete within the 1000 ms hold, then land after the release. +# Control: XCRDAPI without the x2w_xmem_copy_to_destination lookup judges the destination with its own VirtualQuery +# inside the window and refuses it. +add_executable(startup_dstorage_break_window_check tests/startup_dstorage_break_window_check.cpp) +target_compile_features(startup_dstorage_break_window_check PRIVATE cxx_std_17) +add_dependencies(startup_dstorage_break_window_check startup_stub_xcrdapi xmem_shim_test_controls) +add_test(NAME startup_dstorage_break_window COMMAND startup_dstorage_break_window_check + "$" "$") +set_tests_properties(startup_dstorage_break_window PROPERTIES TIMEOUT 60) +set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS src/startup_stubs/xcrdapi.cpp) +file(READ "${CMAKE_CURRENT_SOURCE_DIR}/src/startup_stubs/xcrdapi.cpp" xcrdapi_text) +string(REPLACE "\"x2w_xmem_copy_to_destination\"" "\"x2w_xmem_copy_to_destination_control\"" xcrdapi_control_text + "${xcrdapi_text}") +if(xcrdapi_control_text STREQUAL xcrdapi_text) + message(FATAL_ERROR "xcrdapi.cpp lost the anchor used by startup_dstorage_break_window_control") +endif() +set(xcrdapi_control "${CMAKE_CURRENT_BINARY_DIR}/xcrdapi_break_window_control/xcrdapi.cpp") +file(WRITE "${xcrdapi_control}" "${xcrdapi_control_text}") +add_library(startup_stub_xcrdapi_break_window_control SHARED "${xcrdapi_control}" src/startup_stubs/xcrdapi.def) +set_target_properties(startup_stub_xcrdapi_break_window_control PROPERTIES OUTPUT_NAME XCRDAPI + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/xcrdapi-break-window-control" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/xcrdapi-break-window-control" + ARCHIVE_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/xcrdapi-break-window-control" + MSVC_RUNTIME_LIBRARY "MultiThreaded$<$:Debug>") +target_include_directories(startup_stub_xcrdapi_break_window_control PRIVATE src) +target_compile_features(startup_stub_xcrdapi_break_window_control PRIVATE cxx_std_17) +target_link_libraries(startup_stub_xcrdapi_break_window_control PRIVATE psapi) +add_dependencies(startup_dstorage_break_window_check startup_stub_xcrdapi_break_window_control) +add_test(NAME startup_dstorage_break_window_control COMMAND startup_dstorage_break_window_check + "$" "$") +set_tests_properties(startup_dstorage_break_window_control PROPERTIES TIMEOUT 60 + PASS_REGULAR_EXPRESSION "FAIL break window: refused while the run was broken") add_executable(startup_storage_worker_start tests/startup_storage_worker_start.cpp) target_compile_features(startup_storage_worker_start PRIVATE cxx_std_17) target_include_directories(startup_storage_worker_start PRIVATE src) diff --git a/README.md b/README.md index 9b94df39ff..fc23d1a64f 100644 --- a/README.md +++ b/README.md @@ -109,7 +109,7 @@ After the full [Windows build](#first-build), run one comparison from the reposi | PE 32/64-bit base fixups against Windows | `ctest --preset dev --no-tests=error -R '^cpu_native_highlow$' -V` ยท [scope and controls](docs/experiments.md#highlow-and-mixed-width-base-relocations) | | [CPU counted cache-line zero loops](docs/experiments.md#counted-cache-line-zero-loops) | `ctest --preset release --no-tests=error -R '^cpu_counted_clzero$' -V` | | [Experimental startup stand-ins and debugger (trap-by-default DLLs)](docs/startup-runtime.md) | `ctest --preset release --no-tests=error -R '^startup_stubs$' -V` | -| [Remap XMem pool pages through queue slot 31](docs/experiments.md#queue-page-batches-on-xmem-sections) | `ctest --preset release --no-tests=error -R 'queue_page_batch|xmem_page_batch_inflight' -V` | +| [Remap XMem pool pages through queue slot 31](docs/experiments.md#queue-page-batches-on-xmem-sections) | `ctest --preset release --no-tests=error -R 'queue_page_batch|xmem_page_batch_inflight|xmem_placeholder_split' -V` | | [Sample a texture by address in a translated draw](docs/startup-runtime.md#textures-published-by-address-device-slot-70) | `ctest --preset release --no-tests=error -R '^startup_address_console_' -V` | | [Desktop audio render sink and its three-case fixture (WASAPI)](docs/experiments.md#desktop-audio-render-sink) | `ctest --preset release --no-tests=error -R '^startup_audio_output$' -V` | diff --git a/docs/experiments.md b/docs/experiments.md index 2bba0fe771..65f7d42f95 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -10541,6 +10541,8 @@ Command queue slot 31 resolves 64 KiB pool pages against the views XMem currentl The `xmem_page_batch_inflight_{warp,hardware}` fixture holds a submitted GPU read behind an unsignaled fence, remaps the same virtual address, then releases the fence. The held read must see the old pattern. A second read binds the new section, writes a different pattern through its CPU pool after recording, and checks every byte across a 64 KiB boundary. Run `ctest --preset release --no-tests=error -R '^xmem_page_batch_inflight_' -V`. +`xmem_placeholder_split` maps two pool pages into the middle of an XMem reservation through `X2WMapPageBatch`, which needs a placeholder split. Before splitting, xmem checks that the target is a placeholder, because on Windows `VirtualFree(MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)` can release a reservation that is not one. The check reads bit 0x100 of the `MemoryRegionInfo` flags. Wine (Proton Experimental, November 2026) leaves that bit 0 for placeholders but refuses the same release on a plain reservation with `ERROR_INVALID_ADDRESS` and keeps it whole. xmem measures both once. Where the bit is missing and the plain release is refused, it offers any reserved region to the split, and a plain one fails the split instead. Where the bit is reported, nothing changes. Without this, every slot 31 batch whose destination was not exactly one placeholder failed with `ERROR_INVALID_ADDRESS` under Wine. The fixture also maps onto a committed page in the same reservation, which must fail and keep its bytes (Windows returns `ERROR_INVALID_ADDRESS`, Wine `ERROR_INVALID_PARAMETER`). `xmem_placeholder_split_control` runs the same checks with `X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1` and must fail. It skips (77) where the OS reports the bit. Run `ctest --preset dev --no-tests=error -R '^xmem_placeholder_split' -V`. + `vm_page_provenance_warp` and `vm_page_provenance_hardware` test the source side independently. Two pagefile sections hold distinct data and are mapped into adjacent CPU addresses in reverse creation order. D3D12 reopens those same sections as heaps. The test copies a 4 KiB span centered on the page boundary into a GPU buffer using the logical page order, then compares its readback with the two expected token patterns. It writes new data through the CPU aliases and reads the GPU buffer again before uploading, which must still return the old data. A second upload must produce all the updated words. The tests skip (77) if the requested adapter or section-backed D3D12 buffers are unavailable. [Opening a D3D12 heap from a file mapping](https://learn.microsoft.com/en-us/windows/win32/api/d3d12/nf-d3d12-id3d12device3-openexistingheapfromfilemapping) Run `ctest --preset dev --no-tests=error -R '^vm_page_provenance_' -V`. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index 2563133bb5..a81f3e9b69 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -3160,21 +3160,57 @@ view (`src/xmem_mapped_pages.cpp`). Before, every page had a section and a view slow for a start-up batch of about 100,000 pages (measured under Wine: 42.9 s for 100,000 pages, 82 ms with shared sections and views). +Start-up maps nearly every page with a call of its own, and under Wine each map costs more the +more views the process has. So a mapping call whose pages all continue the view that ends at its +address, on the next slots of the same section and inside the same reservation of the shim, joins +that view: the view is unmapped, its placeholder is joined with the new pages' placeholder, and one +view is mapped over both. It is taken apart the same way as in an unmap (below), and if a step is +refused the view is mapped again as it was and the new pages get a view of their own. A joined +view stops at 64 pages (`max_merged_run_pages`): a page that would make it longer starts a view of +its own, which the next pages join. Every later unmap inside a joined view takes the whole view +apart, so the cap bounds that work too. Only joined views are capped: a view mapped by one call +covers as many of its pages as follow each other in address and in their section, and an unmap inside it maps the surviving pages again +with one view per contiguous stretch, as long as before the cap. Measured under Wine with every byte of the view written +(`xmem_cross_call_merge_check timing`): an unmap inside a view of 64 pages took 0.28 ms, of 512 +pages 2.1 ms and of 4096 pages 13 ms; joining a page to a view of 63 took 1.5 ms, about what a page +mapped on its own costs (1.4 ms). + Unmapping a page inside a shared view unmaps that view and maps its other pages again. A thread that touches one of those pages in between takes an access violation. A vectored handler retries -it only when the address is inside a view that the unmap in progress, or the last finished one, -took apart, the page is recorded and covered by a view once that unmap is over, and the thread -has not already retried that page for that unmap. Any other fault is passed on, after at most one -retry. +it only when the address is inside a view that one of the last 64 unmaps or joins (the one in +progress included) took apart, the page is recorded and covered by a view once that one is over, +and the thread has not already retried that page for the newest such unmap or join. A handler that +runs late, after a later unmap or join of another view has begun (one call joins a CPU view and +then its GPU mirror), still finds the one its fault came from. Any other fault is passed on, after +at most one retry for each unmap or join. Shared views are opt-in. The caller chooses before the first mapping call by setting -`X2W_XMEM_SHARED_VIEWS=1` in the process environment; the shim reads it once, on that call. +`X2W_XMEM_SHARED_VIEWS=1` in the process environment; the shim reads it once, on that call. It also +reads it once when `xmem.dll` loads: with it set then, the main module's `VirtualQueryEx`, +`ReadFile` and `WriteFile` imports are wrapped (see below), and the module is pinned at load when +one is. + +A region query or a kernel copy does not fault, so inside an unmap it would see the pages of the +view being taken apart as reserved. With shared views such readers run through the export +`x2w_xmem_stable_call`: the reader runs once, and runs again after the unmap if one began or ended +around it. `XMemVirtualQuery`, the main module's `VirtualQueryEx` imports and the shim's own +`VirtualQuery` and `ReadProcessMemory` readers (`src/startup_stubs/local_log.h`, slot 133, +the sampler snapshot) use it. Without shared views every page has a view of its own and readers +run once, as before. + +Inside an unmap a kernel copy into or out of a page of that view fails at once. Measured under +Wine: `ReadFile` fails with `ERROR_NOACCESS` and leaves the file position as it was, `WriteFile` +with `ERROR_INVALID_USER_BUFFER`. The main module's `ReadFile` and `WriteFile` imports therefore +run again, up to 4 times in all, when a synchronous call fails with one of those errors while an +unmap or join was in progress or began or ended around it, and its buffer lies in a view of a +run; they wait for that one to end first. Overlapped I/O (the copy happens at completion), a call +cut short after part of the copy, and I/O from other modules are not covered. | | Default | `X2W_XMEM_SHARED_VIEWS=1` | |---|---|---| | Views | one per page | one per run of adjacent pages | | Fault handler | none | registered by the first mapping call, never removed | -| `FreeLibrary` | unloads `xmem.dll` | module is pinned and stays until the process ends | +| `FreeLibrary` | unloads `xmem.dll` | module is pinned and stays until the process ends (at load when the main module imports `VirtualQueryEx`, `ReadFile` or `WriteFile`, else at the first mapping call) | The handler is process-wide, and Windows has no removal that also waits for a dispatch already under way, so the opt-in keeps the module, the handler and the shim's state in place for the life diff --git a/src/startup_stubs/local_log.h b/src/startup_stubs/local_log.h index bea306fde9..64f7d95f71 100644 --- a/src/startup_stubs/local_log.h +++ b/src/startup_stubs/local_log.h @@ -6,6 +6,7 @@ #include #include +#include namespace x2w_local { @@ -107,6 +108,27 @@ inline void commit_lazy_block(const void* pointer) noexcept if (commit_block) commit_block(pointer); } +// Runs f() outside xmem's run breaks (x2w_xmem_stable_call, X2W_XMEM_SHARED_VIEWS): inside a break the pages of +// the run being taken apart read as reserved to a VirtualQuery and make ReadProcessMemory fail, although a touch of +// them would be retried. f must be a query, or a copy into the caller's memory, that can run again; it may run +// twice. Without xmem.dll, or with one that lacks the export, f runs once, directly. +using StableCall = BOOL(WINAPI*)(void (*)(void*), void*); +inline StableCall stable_call_export() noexcept +{ + static const StableCall stable_call = [] { + const HMODULE xmem = GetModuleHandleW(L"xmem.dll"); + return xmem ? reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_stable_call")) : nullptr; + }(); + return stable_call; +} +template +inline void outside_run_breaks(F&& f) noexcept +{ + const StableCall stable_call = stable_call_export(); + using Call = std::remove_reference_t; + if (!stable_call || !stable_call([](void* context) { (*static_cast(context))(); }, &f)) f(); +} + // Readability by probing (see probe_readable); writability by one VirtualQuery (rare callers). inline bool accessible(const void* pointer, std::size_t bytes, bool write) noexcept { @@ -115,7 +137,9 @@ inline bool accessible(const void* pointer, std::size_t bytes, bool write) noexc if (!write) return probe_readable(start, bytes) == bytes; commit_lazy(pointer, bytes); MEMORY_BASIC_INFORMATION info{}; - if (!VirtualQuery(pointer, &info, sizeof(info)) || info.State != MEM_COMMIT) return false; + SIZE_T queried = 0; + outside_run_breaks([&] { queried = VirtualQuery(pointer, &info, sizeof(info)); }); + if (!queried || info.State != MEM_COMMIT) return false; const DWORD protect = info.Protect & 0xFF; if ((info.Protect & PAGE_GUARD) || protect == PAGE_NOACCESS || protect == 0) return false; const bool writable = protect == PAGE_READWRITE || protect == PAGE_EXECUTE_READWRITE || protect == PAGE_WRITECOPY || @@ -129,4 +153,30 @@ inline bool accessible(const void* pointer, std::size_t bytes, bool write) noexc inline bool readable(const void* pointer, std::size_t bytes) noexcept { return accessible(pointer, bytes, false); } inline bool writable(const void* pointer, std::size_t bytes) noexcept { return accessible(pointer, bytes, true); } +// True when every byte of [pointer, pointer + bytes) is committed and writable, with no guard or no-access page +// in between. Walks the regions one VirtualQuery at a time, so a range that spans regions of different +// protection is judged page by page. Nothing is written, touched or committed (see commit_lazy), so it is safe +// under xmem's mapping lock. An empty range is writable; a null or wrapping one is not. +inline bool committed_writable(const void* pointer, std::size_t bytes) noexcept +{ + if (bytes == 0) return true; + std::uintptr_t cursor = reinterpret_cast(pointer); + if (!pointer || bytes > ~std::uintptr_t{0} - cursor) return false; + const std::uintptr_t end = cursor + bytes; + while (cursor < end) { + MEMORY_BASIC_INFORMATION info{}; + if (!VirtualQuery(reinterpret_cast(cursor), &info, sizeof(info)) || info.State != MEM_COMMIT) + return false; + if (info.Protect & (PAGE_GUARD | PAGE_NOACCESS)) return false; + const DWORD protect = info.Protect & 0xFF; + if (protect != PAGE_READWRITE && protect != PAGE_WRITECOPY && protect != PAGE_EXECUTE_READWRITE && + protect != PAGE_EXECUTE_WRITECOPY) + return false; + const std::uintptr_t region_end = reinterpret_cast(info.BaseAddress) + info.RegionSize; + if (region_end <= cursor) return false; + cursor = region_end; + } + return true; +} + } // namespace x2w_local diff --git a/src/startup_stubs/placed_buffer_range.h b/src/startup_stubs/placed_buffer_range.h index 115983e174..27d6400788 100644 --- a/src/startup_stubs/placed_buffer_range.h +++ b/src/startup_stubs/placed_buffer_range.h @@ -22,6 +22,8 @@ #include #include +#include "startup_stubs/local_log.h" + namespace x2w_startup { struct PlacedBufferRange { @@ -70,11 +72,9 @@ inline std::uint64_t allocation_bytes(const void* address) return info.RegionSize; } -// False when the address is not committed (slot 133 returns E_INVALIDARG). Otherwise covered is -// exactly "offset <= committed bytes from base && width <= committed bytes - offset" for the run the -// full walk measures. -inline bool measure_placed_buffer(const void* address, std::uint64_t width, PlacedBufferRange& out, - PlacedProof proof = PlacedProof::exact) +namespace placed_detail { +// One pass of measure_placed_buffer; out is reset first, so a second pass replaces the first. +inline bool measure_once(const void* address, std::uint64_t width, PlacedBufferRange& out, PlacedProof proof) { out = PlacedBufferRange{}; if (!address) return false; @@ -118,6 +118,24 @@ inline bool measure_placed_buffer(const void* address, std::uint64_t width, Plac out.covered = true; return true; } +} // namespace placed_detail + +// False when the address is not committed (slot 133 returns E_INVALIDARG). Otherwise covered is +// exactly "offset <= committed bytes from base && width <= committed bytes - offset" for the run the +// full walk measures. The queries run outside xmem's run breaks (x2w_local::outside_run_breaks): inside +// one, pages of a shared-view run read as reserved, and the buffer would be refused although it is mapped. +inline bool measure_placed_buffer(const void* address, std::uint64_t width, PlacedBufferRange& out, + PlacedProof proof = PlacedProof::exact) +{ + bool committed = false; + unsigned queries = 0; // over every pass: a pass run again after a break replaces out + x2w_local::outside_run_breaks([&] { + committed = placed_detail::measure_once(address, width, out, proof); + queries += out.queries; + }); + out.queries = queries; + return committed; +} // True when an uncovered buffer at [address, address + width) lies inside a MEM_PRIVATE // reservation at a 64 KiB-aligned offset, fits within its whole allocation size (nonzero and at diff --git a/src/startup_stubs/translated_sampler_bindings.h b/src/startup_stubs/translated_sampler_bindings.h index 10149b3c1d..21720a3595 100644 --- a/src/startup_stubs/translated_sampler_bindings.h +++ b/src/startup_stubs/translated_sampler_bindings.h @@ -3,6 +3,8 @@ #include #include +#include "startup_stubs/local_log.h" + #include #include #include @@ -178,10 +180,15 @@ inline SamplerSnapshot snapshot_samplers(SamplerSource source, bool reserved_fal const UINT room = static_cast((page_size - address % page_size) / title_sampler_stride); const UINT available = snapshot.count - i; const UINT run = room ? (room < available ? room : available) : 1; - SIZE_T copied = 0; const SIZE_T bytes = SIZE_T{run} * title_sampler_stride; - if (ReadProcessMemory(GetCurrentProcess(), reinterpret_cast(address), &snapshot.words[i], bytes, &copied) && - copied == bytes) { + // Outside xmem's run breaks, where a mapped page of the title's heap would read as missing. + bool whole = false; + x2w_local::outside_run_breaks([&] { + SIZE_T copied = 0; + whole = ReadProcessMemory(GetCurrentProcess(), reinterpret_cast(address), &snapshot.words[i], bytes, + &copied) && copied == bytes; + }); + if (whole) { for (UINT j = i; j < i + run; ++j) snapshot.readable.set(j); } else { // ReadProcessMemory can copy part of a record on failure. diff --git a/src/startup_stubs/xcrdapi.cpp b/src/startup_stubs/xcrdapi.cpp index a711551975..ac6df58902 100644 --- a/src/startup_stubs/xcrdapi.cpp +++ b/src/startup_stubs/xcrdapi.cpp @@ -200,30 +200,36 @@ static bool resident_read_write(std::uintptr_t start, std::uintptr_t end) // True when every byte of [destination, destination + bytes) is committed and writable, with no guard or // no-access page in between. Nothing is written or touched. Resident read-write pages are accepted from // their working-set attributes; any other page (not resident, copy-on-write, guard, no access) sends the -// destination to the VirtualQuery walk, which judges it region by region. That walk is slow on the title's -// large regions: each query scans to the end of the region (#2684). +// destination to the region walk (x2w_local::committed_writable), which judges it region by region. That walk +// is slow on the title's large regions: each query scans to the end of the region (#2684). Lazily mapped +// physical pages (X2W_XMEM_LAZY_COMMIT) are committed first. static bool destination_writable(const void* destination, std::size_t bytes) { if (bytes == 0) return true; - std::uintptr_t cursor = reinterpret_cast(destination); - if (!destination || bytes > UINTPTR_MAX - cursor) return false; - x2w_local::commit_lazy(destination, bytes); // lazily mapped physical pages (X2W_XMEM_LAZY_COMMIT) - const std::uintptr_t end = cursor + bytes; - if (resident_read_write(cursor, end)) return true; - while (cursor < end) { - MEMORY_BASIC_INFORMATION info{}; - if (!VirtualQuery(reinterpret_cast(cursor), &info, sizeof(info)) || info.State != MEM_COMMIT) - return false; - if (info.Protect & (PAGE_GUARD | PAGE_NOACCESS)) return false; - const DWORD protect = info.Protect & 0xFF; - if (protect != PAGE_READWRITE && protect != PAGE_WRITECOPY && protect != PAGE_EXECUTE_READWRITE && - protect != PAGE_EXECUTE_WRITECOPY) - return false; - const std::uintptr_t region_end = reinterpret_cast(info.BaseAddress) + info.RegionSize; - if (region_end <= cursor) return false; - cursor = region_end; - } - return true; + const auto start = reinterpret_cast(destination); + if (!destination || bytes > UINTPTR_MAX - start) return false; + x2w_local::commit_lazy(destination, bytes); + if (resident_read_write(start, start + bytes)) return true; + return x2w_local::committed_writable(destination, bytes); +} + +// Copies bytes of data into a plain-memory destination whose whole declared capacity must be writable. With +// xmem.dll loaded, x2w_xmem_copy_to_destination makes the check and the copy under XMem's mapping mutex, so an +// XMem run break (the pages of a shared view unmapped and mapped again) can neither make a mapped destination +// look reserved nor take it away during the copy. Without xmem.dll the check and the copy run here. +// ERROR_SUCCESS; ERROR_NOACCESS when the destination is not writable (nothing written); another error when the +// copy faulted. +static DWORD copy_to_destination(void* destination, std::size_t capacity, const void* data, std::size_t bytes) +{ + using CopyToDestination = BOOL(WINAPI*)(void*, SIZE_T, const void*, SIZE_T); + static const CopyToDestination copy = [] { + const HMODULE xmem = GetModuleHandleW(L"xmem.dll"); + return xmem ? reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_copy_to_destination")) : nullptr; + }(); + if (copy) return copy(destination, capacity, data, bytes) ? ERROR_SUCCESS : GetLastError(); + if (!destination_writable(destination, capacity)) return ERROR_NOACCESS; + std::memcpy(destination, data, bytes); + return ERROR_SUCCESS; } // Return the exact queued requests that continue this stream in this submission, in queue order. @@ -943,11 +949,10 @@ void execute_request(Object* self, const unsigned char* request, const ULONG_PTR // The title's destination can be smaller in memory than its declared capacity (#870: // a write fault inside this copy). Judge the whole declared capacity before the first // byte is written, so a refusal leaves every page untouched. - if (destination_writable(destination, destination_capacity)) { - std::memcpy(destination, data, decode_length); - } else { - outcome = "destination not writable"; - failure = StorageFailure::destination_not_writable; + const DWORD copied = copy_to_destination(destination, destination_capacity, data, decode_length); + if (copied != ERROR_SUCCESS) { + outcome = copied == ERROR_NOACCESS ? "destination not writable" : "copy faulted (source not readable)"; + failure = copied == ERROR_NOACCESS ? StorageFailure::destination_not_writable : StorageFailure::other; data = nullptr; written = false; } diff --git a/src/xmem_mapped_pages.cpp b/src/xmem_mapped_pages.cpp index c212772964..15364200aa 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -262,6 +262,10 @@ const Backing* lease_backing(UINT version, ULONG_PTR page) return backing && backing->committed ? backing : nullptr; } +// Set while this thread holds memory.mutex to change mappings or to copy into mapped pages (MappingThread). The +// fault handlers pass such a thread's faults on: waiting for memory.mutex there would never return. +thread_local bool mapping_thread = false; + LONG CALLBACK lazy_commit_fault(EXCEPTION_POINTERS* e) { const EXCEPTION_RECORD* record = e->ExceptionRecord; @@ -296,6 +300,7 @@ LONG CALLBACK lazy_commit_fault(EXCEPTION_POINTERS* e) // A thread that raced another one to the same slot finds it committed: retry once, then pass the fault on. thread_local ULONG_PTR retried = 0; const ULONG_PTR page = address & ~(ULONG_PTR{page_bytes} - 1); + if (mapping_thread) return EXCEPTION_CONTINUE_SEARCH; const std::lock_guard guard(memory.mutex); Backing* backing = backing_at(address); if (!backing) return EXCEPTION_CONTINUE_SEARCH; @@ -365,18 +370,50 @@ auto owned_reservation(ULONG_PTR address) return address - it->first < it->second ? it : memory.reservations.end(); } +// MapViewOfFile3 and placeholder-split attempts made by map_split (x2w_xmem_map_counts). +volatile LONG64 map_attempts, split_attempts; + +// True when [target, target + bytes) is a whole reserved region of its own: a placeholder that +// MEM_REPLACE_PLACEHOLDER can take as it is, so no split is needed first. +bool exact_placeholder(void* target, SIZE_T bytes) +{ + MEMORY_BASIC_INFORMATION info{}; + return VirtualQuery(target, &info, sizeof(info)) == sizeof(info) && info.State == MEM_RESERVE && + info.AllocationBase == target && info.BaseAddress == target && info.RegionSize == bytes; +} + // Only split a reservation owned by the shim. Caller-owned placeholders must already match the view. +// Inside an owned reservation the split comes first when the target is not already an exact placeholder: +// a map into the middle of a larger placeholder always fails, and under Wine every failed map is another +// server round trip whose cost grows with the number of views (one 64 KiB page per call at startup). +// The query and the split are not atomic, so if the split or the map after it fails, the map-first +// path below runs as before. X2W_XMEM_TEST_MAP_FIRST=1 skips the split-first step (tests only). // Once a split succeeds, report the retry's result even if it fails for a different reason. template bool map_split(void* target, SIZE_T bytes, Map map) { - if (map()) return true; - const DWORD error = GetLastError(); + static const bool map_first = x2w_local::env_on("X2W_XMEM_TEST_MAP_FIRST"); const auto address = reinterpret_cast(target); const auto reservation = owned_reservation(address); - if (reservation != memory.reservations.end() && bytes <= reservation->second - (address - reservation->first) && - VirtualFree(target, bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) - return map(); + const bool owned = reservation != memory.reservations.end() && + bytes <= reservation->second - (address - reservation->first); + if (owned && !map_first && !exact_placeholder(target, bytes)) { + InterlockedIncrement64(&split_attempts); + if (VirtualFree(target, bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) { + InterlockedIncrement64(&map_attempts); + if (map()) return true; + } + } + InterlockedIncrement64(&map_attempts); + if (map()) return true; + const DWORD error = GetLastError(); + if (owned) { + InterlockedIncrement64(&split_attempts); + if (VirtualFree(target, bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) { + InterlockedIncrement64(&map_attempts); + return map(); + } + } SetLastError(error); return false; } @@ -444,22 +481,51 @@ void coalesce_unused(const Pages& batch) } } -// Unmapping a page inside a run unmaps the whole run and maps its other pages again (map_pages). -// A thread that touches one of those pages in between faults. The break records the address -// ranges of the runs it takes apart and a generation that is odd while it is in progress. +// Unmapping a page inside a run unmaps the whole run and maps its other pages again (map_pages), and so does a +// cross-call merge (merge_with_previous) for the run it joins. A thread that touches one of those pages in between +// faults. Each break records the address ranges of the runs it takes apart, and a generation that is odd while it +// is in progress; the break's id is that odd value. The last `kept` breaks stay recorded, so that a fault handler +// that runs late, after later breaks on other runs have begun (a merge of the CPU view and then of its GPU mirror +// in one call, or the next call's merge), still finds the break its fault came from. struct RemapWindow { + static constexpr std::size_t kept = 64; + struct Break { + ULONG64 id = 0; // 0: no break recorded in this slot yet + std::vector> ranges; + }; SRWLOCK lock = SRWLOCK_INIT; - std::vector> ranges; // the runs of the break in progress, or of the last one + Break recent[kept]; // break id i in recent[(i / 2) % kept] ULONG64 generation = 0; + + // The newest recorded break whose ranges hold address, or 0. Caller holds lock (shared). + ULONG64 newest_holding(ULONG_PTR address) const + { + ULONG64 found = 0; + for (const Break& b : recent) { + if (b.id <= found) continue; + for (const auto& [base, size] : b.ranges) + if (address - base < size) { + found = b.id; + break; + } + } + return found; + } }; RemapWindow remap_window; +// Set once shared views are on (FaultRetry::ready). Breaks also begin without them (every unmap counts in the +// generation), but then a page has a view of its own and no break takes a neighbour away, so x2w_xmem_stable_call +// does not wait for them. +std::atomic shared_views_on{false}; void begin_break(const std::map& broken) { std::vector> ranges(broken.begin(), broken.end()); AcquireSRWLockExclusive(&remap_window.lock); - remap_window.ranges.swap(ranges); - ++remap_window.generation; + const ULONG64 id = ++remap_window.generation; + auto& slot = remap_window.recent[(id / 2) % RemapWindow::kept]; + slot.id = id; + slot.ranges.swap(ranges); // the old slot's ranges are freed after the lock ReleaseSRWLockExclusive(&remap_window.lock); } void end_break() @@ -471,12 +537,35 @@ void end_break() struct EndBreak { ~EndBreak() { end_break(); } }; -// Retries an access violation only when all of this holds: the address is inside a run that the -// break in progress, or the last finished one, took apart; after that break has finished (the -// mutex) the page is recorded and covered by a view; and this thread has not already retried this -// page for this break. Everything else is passed on, so a fault that is not the transient one is -// reported after at most one retry. -thread_local bool mapping_thread = false; +// Test build only: X2W_XMEM_TEST_HOLD_RETRY= holds the fault handler before it reads the break: it sets +// ".faulted", then waits up to five seconds for ".go", so that a test can end the break first. +#ifdef X2W_XMEM_TEST_CONTROLS +void hold_retry() +{ + char name[96]; + const DWORD length = GetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", name, sizeof(name) - 16); + if (!length || length >= sizeof(name) - 16) return; + char event_name[128]; + std::snprintf(event_name, sizeof(event_name), "%s.faulted", name); + HANDLE faulted = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.go", name); + HANDLE go = CreateEventA(nullptr, TRUE, FALSE, event_name); + if (faulted && go) { + SetEvent(faulted); + WaitForSingleObject(go, 5000); + } + if (faulted) CloseHandle(faulted); + if (go) CloseHandle(go); +} +#else +void hold_retry() {} +#endif + +// Retries an access violation only when all of this holds: the address is inside a run that one of the recorded +// breaks (the one in progress or the last RemapWindow::kept) took apart; after that break has finished (the mutex) +// the page is recorded and covered by a view; and this thread has not already retried this page for the newest +// such break. Everything else is passed on, so a fault that is not the transient one is reported after at most one +// retry per break. LONG CALLBACK retry_remapped_page(EXCEPTION_POINTERS* e) { const EXCEPTION_RECORD* record = e->ExceptionRecord; @@ -484,14 +573,13 @@ LONG CALLBACK retry_remapped_page(EXCEPTION_POINTERS* e) return EXCEPTION_CONTINUE_SEARCH; const ULONG_PTR address = record->ExceptionInformation[1]; const ULONG_PTR page = address & ~(ULONG_PTR{page_bytes} - 1); - bool inside = false; + hold_retry(); AcquireSRWLockShared(&remap_window.lock); - const ULONG64 seen = remap_window.generation; - for (const auto& [base, size] : remap_window.ranges) - inside |= address - base < size; + // The newest break that took the page apart, in progress or finished; a later break on another run does not + // hide it. A fault in a later break of the same page names that break, so it is retried again. + const ULONG64 break_id = remap_window.newest_holding(address); ReleaseSRWLockShared(&remap_window.lock); - if (!inside || seen == 0) return EXCEPTION_CONTINUE_SEARCH; - const ULONG64 break_id = seen | 1; // the break in progress, or the one that just finished + if (!break_id) return EXCEPTION_CONTINUE_SEARCH; thread_local ULONG_PTR retried_page = 0; thread_local ULONG64 retried_break = 0; if (retried_page == page && retried_break == break_id) return EXCEPTION_CONTINUE_SEARCH; @@ -513,7 +601,9 @@ struct MappingThread { // Shared views are opt-in: X2W_XMEM_SHARED_VIEWS=1, read once by the first mapping call. Without // it every page has a view of its own, as before: unmapping a page never takes a neighbour away, -// no handler is registered, and the module unloads like any DLL. +// no handler is registered, and the module unloads like any DLL. The switch is also read once when +// xmem.dll loads (virtual_query_ex_wrapped): with it set then, the main module's VirtualQueryEx imports +// are wrapped, and the module is pinned at load when one is. // // With it, the first mapping call registers the handler and pins the module. The handler is // process-wide and Windows offers no way to remove one that also waits for every dispatch already @@ -551,6 +641,7 @@ struct FaultRetry { x2w_local::logf("x2w-xmem shared views are off: the fault handler could not be set up (error %lu)", GetLastError()); } const bool result = guaranteed; + if (result) shared_views_on.store(true, std::memory_order_release); ReleaseSRWLockExclusive(&lock); return result; } @@ -560,13 +651,15 @@ FaultRetry fault_retry; // Test build only (X2W_XMEM_TEST_CONTROLS; tests/xmem_page_runs_check.py): X2W_XMEM_TEST_FAULT=: makes one step of // the next unmap fail as if Windows had refused it, after skipping such steps. Stage 1 is // unmapping a run, stage 2 mapping surviving pages again, stage 3 both the unmap and the restore. +// Stages 4 and 5 are steps of a cross-call merge (merge_with_previous): 4 the map of the joined view, +// 5 joining the two placeholders. #ifdef X2W_XMEM_TEST_CONTROLS struct TestFault { unsigned stage = 0, skip = 0; TestFault() { char text[32]; - if (GetEnvironmentVariableA("X2W_XMEM_TEST_FAULT", text, sizeof(text)) && text[0] >= '1' && text[0] <= '3' && text[1] == ':') { + if (GetEnvironmentVariableA("X2W_XMEM_TEST_FAULT", text, sizeof(text)) && text[0] >= '1' && text[0] <= '5' && text[1] == ':') { stage = static_cast(text[0] - '0'); skip = static_cast(std::strtoul(text + 2, nullptr, 10)); } @@ -590,8 +683,8 @@ struct TestFault { }; #endif -// Test build only: X2W_XMEM_TEST_HOLD_WINDOW= keeps an unmap in the window where the run is -// unmapped and not yet mapped again. It sets the event ".unmapped", then waits up to +// Test build only: X2W_XMEM_TEST_HOLD_WINDOW= keeps an unmap, or a cross-call merge (merge_with_previous), in the +// window where the run is unmapped and not yet mapped again. It sets the event ".unmapped", then waits up to // five seconds for ".release", so that a reader thread can reach the window every time. #ifdef X2W_XMEM_TEST_CONTROLS void hold_window() @@ -692,6 +785,82 @@ ULONG_PTR map_recorded(ULONG_PTR base, SIZE_T size, bool fail, MapFailure* failu return lost; } +// Shared views only. Startup maps nearly every page with a call of its own, and under Wine each map +// costs more the more views the process has. A run mapped by a call of its own therefore joins the +// recorded run R that ends at its address, when its first page is the next slot of the section behind +// R's last page and R and the new pages lie in one reservation of the shim: the new pages' range is +// split to a placeholder of its own, R is unmapped, the two placeholders are joined and one view is +// mapped over both. R is taken apart as in an unmap (begin_break), so a thread that touches R in +// between is retried and x2w_xmem_stable_call readers wait. On a refused step before R is unmapped +// nothing changed; after it, R is mapped again as it was (map_recorded). Both return separate, and +// the caller maps the new pages on their own. lost: R could not be mapped again; the pages that have +// no view are forgotten, as in an unmap. X2W_XMEM_TEST_NO_MERGE=1 turns the merge off (tests only). +// A joined run stops at max_merged_run_pages: a page that would make R longer starts a run of its own, which the +// next pages join. The cap bounds the runs that joining builds: the work of each join, and of a later break of such a +// run (an unmap inside a run takes the whole run apart and maps its other pages again). A run mapped by one call +// (map_run in map_pages_locked) is not capped, and neither are the survivors map_recorded maps again after an unmap +// inside such a run; both are as long as they were before the cap. +enum class Merge { joined, separate, lost }; + +constexpr SIZE_T max_merged_run_pages = 64; + +// Test build only: X2W_XMEM_TEST_MERGE_CAP= replaces the cap (xmem_cross_call_merge_check's timing mode). +SIZE_T merged_run_cap() +{ +#ifdef X2W_XMEM_TEST_CONTROLS + char text[24]; + if (GetEnvironmentVariableA("X2W_XMEM_TEST_MERGE_CAP", text, sizeof(text))) + if (const auto pages = std::strtoull(text, nullptr, 10)) return static_cast(pages); +#endif + return max_merged_run_pages; +} + +Merge merge_with_previous(ULONG_PTR address, const Backing& head, SIZE_T bytes, MapFailure* failure) +{ +#ifdef X2W_XMEM_TEST_CONTROLS + if (x2w_local::env_on("X2W_XMEM_TEST_NO_MERGE")) return Merge::separate; +#endif + const auto next = memory.runs.lower_bound(address); + if (next == memory.runs.begin()) return Merge::separate; + const auto [base, size] = *std::prev(next); + if (base + size != address) return Merge::separate; + if ((size + bytes) / page_bytes > merged_run_cap()) return Merge::separate; + const auto tail = memory.views.find(address - page_bytes); + if (tail == memory.views.end()) return Merge::separate; + const Backing& previous = memory.backings.at(tail->second); + if (previous.section != head.section || previous.offset + page_bytes != head.offset) return Merge::separate; + const auto reservation = owned_reservation(base); + if (reservation == memory.reservations.end() || address + bytes > reservation->first + reservation->second) + return Merge::separate; + const Backing start = memory.backings.at(memory.views.at(base)); + auto* const target = reinterpret_cast(address); + if (!exact_placeholder(target, bytes)) { + InterlockedIncrement64(&split_attempts); + if (!VirtualFree(target, bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER)) return Merge::separate; + } + TestFault test; + begin_break({{base, size}}); + const EndBreak end; + if (!unmap_view(base)) return Merge::separate; + memory.runs.erase(base); + hold_window(); + auto* const whole = reinterpret_cast(base); + if (!test.hit(5) && VirtualFree(whole, size + bytes, MEM_RELEASE | MEM_COALESCE_PLACEHOLDERS)) { + InterlockedIncrement64(&map_attempts); + if (!test.hit(4) && MapViewOfFile3(start.section, GetCurrentProcess(), whole, start.offset, size + bytes, + MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0)) { + memory.runs[base] = size + bytes; + return Merge::joined; + } + } + // map_recorded splits the joined placeholder back to R's size (map_split: the reservation is the shim's). + const ULONG_PTR lost = map_recorded(base, size, false, failure); + if (!lost) return Merge::separate; + x2w_local::logf("x2w-xmem merge of a run with the next mapping call failed: %llu page(s) of the run could not be " + "mapped again and were forgotten", static_cast(lost)); + return Merge::lost; +} + // Destinations must be caller-owned, page-sized Windows placeholders. Live views // are owned by this shim until it unmaps them. The caller must not replace them. template @@ -736,8 +905,18 @@ BOOL map_pages_locked(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& const Backing& b = memory.backings.at(last->second); if (last->first != first->first + bytes || b.section != head.section || b.offset != head.offset + bytes) break; } + // Only a run that is the whole batch joins an earlier one: a later run of the batch that + // fails unmaps everything in made, which a joined run is not. + const Merge merge = share_views && first == batch.begin() && last == batch.end() + ? merge_with_previous(first->first, head, bytes, failure) + : Merge::separate; + if (merge == Merge::lost) { + coalesce_unused(batch); + SetLastError(ERROR_NOT_ENOUGH_MEMORY); + return FALSE; + } ULONG_PTR failed_address; - if (!map_run(first->first, head, bytes, made, failed_address)) { + if (merge == Merge::separate && !map_run(first->first, head, bytes, made, failed_address)) { const DWORD error = GetLastError(); if (failure) failure->record("map-view", failed_address, batch.at(failed_address), error); for (const auto& [base, size] : made) { @@ -1131,19 +1310,61 @@ struct AliasEdit { using AliasPlan = std::map; using ViewRuns = std::map; +// The region query exposes the placeholder reservation flag in Flags even though the SDK does not name that bit. +constexpr ULONG placeholder_reservation = 0x100; + +// Measured once: whether the region query reports placeholder_reservation for a fresh placeholder, and, when it does +// not, whether VirtualFree(MEM_PRESERVE_PLACEHOLDER) refuses a plain reservation and leaves it whole. Windows reports +// the bit. Wine (Proton Experimental, 2026-11) leaves Flags 0 for placeholders but refuses the plain case with +// ERROR_INVALID_ADDRESS. X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1 skips the second probe (tests only). +bool placeholder_fallback() +{ + static const bool fallback = [] { + bool bit_reported = false, refuses_plain = false; + if (void* probe = VirtualAlloc2(GetCurrentProcess(), nullptr, 2 * page_bytes, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, nullptr, 0)) { + WIN32_MEMORY_REGION_INFORMATION info{}; + bit_reported = QueryVirtualMemoryInformation(GetCurrentProcess(), probe, MemoryRegionInfo, &info, + sizeof(info), nullptr) && + (info.Flags & placeholder_reservation); + VirtualFree(probe, 0, MEM_RELEASE); + } + if (!bit_reported && !x2w_local::env_on("X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK")) { + if (auto* plain = static_cast(VirtualAlloc(nullptr, 2 * page_bytes, MEM_RESERVE, PAGE_NOACCESS))) { + MEMORY_BASIC_INFORMATION after{}; + refuses_plain = !VirtualFree(plain + page_bytes, page_bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER) && + VirtualQuery(plain, &after, sizeof(after)) == sizeof(after) && + after.State == MEM_RESERVE && after.AllocationBase == plain && + after.RegionSize == 2 * page_bytes; + VirtualFree(plain, 0, MEM_RELEASE); + } + } + x2w_local::logf("x2w-xmem placeholder bit reported=%d, plain reservation kept by a placeholder release=%d", + bit_reported, refuses_plain); + return !bit_reported && refuses_plain; + }(); + return fallback; +} + bool alias_placeholders(ULONG_PTR address, SIZE_T bytes) { - // The region query exposes the placeholder reservation flag in Flags even though the - // SDK does not name that bit. VirtualQuery alone cannot distinguish a reserved private - // allocation from a placeholder. PRESERVE_PLACEHOLDER can silently release that allocation. - constexpr ULONG placeholder_reservation = 0x100; + // VirtualQuery alone cannot distinguish a reserved private allocation from a placeholder, and on Windows + // PRESERVE_PLACEHOLDER can silently release that allocation. Where the region query does not report the bit + // and the OS refuses that release (placeholder_fallback), any reserved region may be offered: a plain one + // fails the split instead of being released. + const bool fallback = placeholder_fallback(); const auto end = address + bytes; while (address < end) { WIN32_MEMORY_REGION_INFORMATION info{}; if (!QueryVirtualMemoryInformation(GetCurrentProcess(), reinterpret_cast(address), - MemoryRegionInfo, &info, sizeof(info), nullptr) || - !(info.Flags & placeholder_reservation)) + MemoryRegionInfo, &info, sizeof(info), nullptr)) return false; + if (!(info.Flags & placeholder_reservation)) { + MEMORY_BASIC_INFORMATION region{}; + if (!fallback || VirtualQuery(reinterpret_cast(address), ®ion, sizeof(region)) != sizeof(region) || + region.State != MEM_RESERVE) + return false; + } const auto base = reinterpret_cast(info.AllocationBase); if (address - base >= info.RegionSize) return false; address += info.RegionSize - (address - base); @@ -1503,9 +1724,55 @@ extern "C" BOOL WINAPI x2w_xmem_page_stats(ULONGLONG* live_sections) return TRUE; } +// Runs fn(context) so that its answer does not come from inside a run break: the moment, under memory.mutex, +// when a run of shared views is unmapped and its surviving pages are mapped again (map_pages_locked, +// remap_alias_pages). A thread that touches such a page faults and retry_remapped_page retries it, but a region +// query (VirtualQuery) or a kernel copy (ReadProcessMemory) does not fault: inside the break it reports the pages +// as reserved, or fails. fn must be a query, or a copy into the caller's memory, that can simply run again, and +// must not take memory.mutex or call the mapping exports. +// Without shared views (X2W_XMEM_SHARED_VIEWS unset, or no mapping call yet) fn runs once, directly: every page has +// a view of its own, so no break takes a page away from a reader. With them fn runs once when no break begins or +// ends around it (the break generation is even before and unchanged after), which is nearly every call; otherwise +// it runs again under memory.mutex, so after the break. A thread that holds memory.mutex runs it directly. +extern "C" BOOL WINAPI x2w_xmem_stable_call(void (*fn)(void*), void* context) +{ + if (!fn) { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + if (mapping_thread || !shared_views_on.load(std::memory_order_acquire)) { + fn(context); + return TRUE; + } + const auto generation = [] { + AcquireSRWLockShared(&remap_window.lock); + const ULONG64 value = remap_window.generation; + ReleaseSRWLockShared(&remap_window.lock); + return value; + }; + const ULONG64 before = generation(); + if (!(before & 1)) { + fn(context); + if (generation() == before) return TRUE; + } + const MappingThread marker; + const std::lock_guard guard(memory.mutex); + fn(context); + return TRUE; +} + // Experimental export: the slab accounting behind those pages (#1199): slabs open, slots in use and slots free // in the open slabs. A slab is reserved when it is created, its slots are committed on first use, and empty slabs // are closed when all of their slots are freed and unpinned. +// Test export: MapViewOfFile3 and placeholder-split attempts made by the physical-page map path so far. +extern "C" BOOL WINAPI x2w_xmem_map_counts(ULONGLONG* maps, ULONGLONG* splits) +{ + if (!maps || !splits) return FALSE; + *maps = static_cast(map_attempts); + *splits = static_cast(split_attempts); + return TRUE; +} + extern "C" BOOL WINAPI x2w_xmem_slab_stats(ULONGLONG* slabs, ULONGLONG* slots_in_use, ULONGLONG* slots_free) { if (!slabs || !slots_in_use || !slots_free) return FALSE; @@ -1549,6 +1816,76 @@ extern "C" BOOL WINAPI x2w_xmem_commit_range(const void* address, SIZE_T bytes) return TRUE; } +namespace { +// Keep the guarded copy out of functions that need unwinding (as read_alias_record). +bool copy_guarded(void* destination, const void* data, SIZE_T bytes) noexcept +{ + __try { + std::memcpy(destination, data, bytes); + return true; + } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION || + GetExceptionCode() == EXCEPTION_IN_PAGE_ERROR ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + return false; + } +} + +// The longest hold of memory.mutex by a destination copy, and the largest copy, so far (under memory.mutex). +double copy_hold_max_ms = 0; +SIZE_T copy_bytes_max = 0; +} // namespace + +// The DirectStorage stand-in's copy into a plain-memory destination (XCRDAPI). The check that all of +// [destination, destination + capacity) is committed and writable and the copy of bytes from data both run under +// memory.mutex. Unmapping a page of a shared run takes the whole run away until its other pages are mapped again +// (map_pages_locked, remap_alias_pages), all under that mutex, so neither the check nor the copy can fall into that +// window, and no such window can open while the copy runs. Lazily mapped pages of both ranges are committed first, +// before the mutex is taken: a fault under it is passed on (mapping_thread), not served. +// TRUE when the bytes were copied. FALSE with ERROR_NOACCESS when the destination is not writable (nothing is +// written), ERROR_INVALID_ADDRESS when the copy faulted (a source page not readable; part of the destination may be +// written), or ERROR_INVALID_PARAMETER for more bytes than capacity or null data. +extern "C" BOOL WINAPI x2w_xmem_copy_to_destination(void* destination, SIZE_T capacity, const void* data, SIZE_T bytes) +{ + if (bytes > capacity || (bytes && !data)) { + SetLastError(ERROR_INVALID_PARAMETER); + return FALSE; + } + const auto start = reinterpret_cast(destination); + if (capacity && destination && capacity <= ~ULONG_PTR{0} - start) x2w_xmem_commit_range(destination, capacity); + if (bytes) x2w_xmem_commit_range(data, bytes); + DWORD error = ERROR_SUCCESS; + double held_ms = 0; + bool longest = false, largest = false; + { + const MappingThread marker; + const std::lock_guard guard(memory.mutex); + LARGE_INTEGER frequency{}, begin{}, end{}; + QueryPerformanceFrequency(&frequency); + QueryPerformanceCounter(&begin); + if (!x2w_local::committed_writable(destination, capacity)) + error = ERROR_NOACCESS; + else if (bytes && !copy_guarded(destination, data, bytes)) + error = ERROR_INVALID_ADDRESS; + QueryPerformanceCounter(&end); + held_ms = frequency.QuadPart ? 1000.0 * static_cast(end.QuadPart - begin.QuadPart) / frequency.QuadPart : 0; + if (held_ms > copy_hold_max_ms) { + copy_hold_max_ms = held_ms; + longest = true; + } + if (!error && bytes > copy_bytes_max) { + copy_bytes_max = bytes; + largest = true; + } + } + // A line per new maximum (about the logarithm of the number of copies), logged after the mutex is released. + static volatile LONG lines; + if ((longest || largest) && x2w_local::first_calls(lines, 64)) + x2w_local::logf("x2w-xmem destination copy: %s%s%.3f ms under the mapping mutex for 0x%llx bytes (capacity 0x%llx)", + longest ? "longest hold so far, " : "", largest ? "largest copy so far, " : "", held_ms, + static_cast(bytes), static_cast(capacity)); + SetLastError(error); + return error == ERROR_SUCCESS; +} + // Experimental export (X2W_XMEM_LAZY_STARTUP): commits the whole lazy startup block holding address and stops // committing it lazily. A GPU heap opened on the block covers the committed run from its base and is reused for // later resources in the block, so the block is committed whole before the first one is placed. TRUE without the @@ -1656,6 +1993,139 @@ const bool lazy_commit_installed = [] { } return true; }(); + +// With X2W_XMEM_SHARED_VIEWS=1 the main module's VirtualQueryEx imports answer outside run breaks +// (x2w_xmem_stable_call): inside one, a page of the run being taken apart reads as reserved. A query of another +// process runs the same way; it only costs the retry. The module is pinned once an import points into it (a main +// module without the import leaves it unloadable, as before); if the pin is refused, the imports are restored. +using VirtualQueryExFn = SIZE_T(WINAPI*)(HANDLE, LPCVOID, PMEMORY_BASIC_INFORMATION, SIZE_T); +VirtualQueryExFn real_virtual_query_ex; + +// The answer goes to a local buffer and is copied to the caller's after x2w_xmem_stable_call: on its mutex path the +// lazy-commit handler passes faults on (MappingThread), so a write into an uncommitted mapped slot would not be +// committed there. +SIZE_T WINAPI virtual_query_ex_stable(HANDLE process, LPCVOID address, PMEMORY_BASIC_INFORMATION info, SIZE_T bytes) +{ + if (!info || bytes < sizeof(MEMORY_BASIC_INFORMATION)) return real_virtual_query_ex(process, address, info, bytes); + struct Query { + HANDLE process; + LPCVOID address; + MEMORY_BASIC_INFORMATION info; + SIZE_T result; + DWORD error; + } query{process, address, {}, 0, ERROR_SUCCESS}; + x2w_xmem_stable_call([](void* context) { + auto& q = *static_cast(context); + q.result = real_virtual_query_ex(q.process, q.address, &q.info, sizeof(q.info)); + q.error = GetLastError(); + }, &query); + if (query.result) std::memcpy(info, &query.info, query.result); + SetLastError(query.error); + return query.result; +} + +const int virtual_query_ex_wrapped = [] { + if (!x2w_local::env_on("X2W_XMEM_SHARED_VIEWS")) return 0; + real_virtual_query_ex = reinterpret_cast(GetProcAddress(GetModuleHandleW(L"kernel32.dll"), "VirtualQueryEx")); + if (!real_virtual_query_ex) return 0; + int queries = patch_main_import("VirtualQueryEx", reinterpret_cast(&virtual_query_ex_stable)); + HMODULE self = nullptr; + if (queries && !GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, + reinterpret_cast(&virtual_query_ex_stable), &self)) { + const DWORD error = GetLastError(); + const int restored = patch_main_import("VirtualQueryEx", reinterpret_cast(real_virtual_query_ex)); + x2w_local::logf("x2w-xmem shared views (X2W_XMEM_SHARED_VIEWS): xmem.dll could not be pinned (error %lu); " + "%d of %d VirtualQueryEx import(s) restored", static_cast(error), restored, queries); + queries = 0; + } + x2w_local::logf("x2w-xmem shared views (X2W_XMEM_SHARED_VIEWS): %d VirtualQueryEx import(s) answer outside run breaks", + queries); + return queries; +}(); + +// With X2W_XMEM_SHARED_VIEWS=1 the main module's ReadFile and WriteFile imports also go around run breaks. Inside one, +// a kernel copy into or out of a page of the run being taken apart fails at once, with no fault to retry. Measured +// under Wine (tests/xmem_run_break_readers_check.cpp, ReadFile_import and WriteFile_import): ReadFile fails with +// ERROR_NOACCESS and leaves the file position where it was, WriteFile with ERROR_INVALID_USER_BUFFER. A synchronous +// call (no OVERLAPPED) that fails with one of those while a break was in progress, or began or ended around it, and +// whose buffer lies in a run, waits for memory.mutex (the end of the break) and runs again, at most io_attempts times +// in all. A call that fails that way with no break around it, or outside the runs, fails at once as before. +// Not covered: overlapped I/O (the copy happens at completion, after the call has returned), a call that a break +// cuts short after part of the copy (a short count), and I/O from other modules or through GetProcAddress. +using WriteFileFn = BOOL(WINAPI*)(HANDLE, LPCVOID, DWORD, LPDWORD, LPOVERLAPPED); +ReadFileFn next_read_file; // read_file_committed with lazy commit, kernel32's ReadFile without +WriteFileFn kernel_write_file; +constexpr int io_attempts = 4; + +ULONG64 break_generation() +{ + AcquireSRWLockShared(&remap_window.lock); + const ULONG64 value = remap_window.generation; + ReleaseSRWLockShared(&remap_window.lock); + return value; +} + +// Whether [buffer, buffer + bytes) holds a page of a run. Takes memory.mutex, so it returns after the break in progress. +bool in_a_run(const void* buffer, DWORD bytes) +{ + const auto first = reinterpret_cast(buffer); + const std::lock_guard guard(memory.mutex); + const auto run = memory.runs.upper_bound(first); + if (run != memory.runs.begin() && first - std::prev(run)->first < std::prev(run)->second) return true; + return run != memory.runs.end() && run->first - first < bytes; +} + +template +BOOL io_outside_breaks(const void* buffer, DWORD bytes, LPOVERLAPPED overlapped, const Call& call) +{ + if (overlapped || !buffer || !bytes || mapping_thread || !shared_views_on.load(std::memory_order_acquire)) return call(); + for (int attempt = 1;; ++attempt) { + const ULONG64 before = break_generation(); + if (call()) return TRUE; + const DWORD error = GetLastError(); + const bool broken = (before & 1) || break_generation() != before; + if ((error != ERROR_NOACCESS && error != ERROR_INVALID_USER_BUFFER) || !broken || attempt == io_attempts || + !in_a_run(buffer, bytes)) { + SetLastError(error); + return FALSE; + } + } +} + +BOOL WINAPI read_file_stable(HANDLE file, LPVOID buffer, DWORD bytes, LPDWORD read, LPOVERLAPPED overlapped) +{ + return io_outside_breaks(buffer, bytes, overlapped, [&] { return next_read_file(file, buffer, bytes, read, overlapped); }); +} + +BOOL WINAPI write_file_stable(HANDLE file, LPCVOID buffer, DWORD bytes, LPDWORD written, LPOVERLAPPED overlapped) +{ + return io_outside_breaks(buffer, bytes, overlapped, [&] { return kernel_write_file(file, buffer, bytes, written, overlapped); }); +} + +const int file_io_wrapped = [] { + if (!x2w_local::env_on("X2W_XMEM_SHARED_VIEWS")) return 0; + const HMODULE kernel32 = GetModuleHandleW(L"kernel32.dll"); + const auto kernel_read_file = reinterpret_cast(GetProcAddress(kernel32, "ReadFile")); + kernel_write_file = reinterpret_cast(GetProcAddress(kernel32, "WriteFile")); + if (!kernel_read_file || !kernel_write_file) return 0; + // With lazy commit the ReadFile imports already point at read_file_committed, which stays the inner call. + next_read_file = lazy_commit_installed && real_read_file ? &read_file_committed : kernel_read_file; + int wrapped = patch_main_import("ReadFile", reinterpret_cast(&read_file_stable)); + wrapped += patch_main_import("WriteFile", reinterpret_cast(&write_file_stable)); + HMODULE self = nullptr; + if (wrapped && !GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS | GET_MODULE_HANDLE_EX_FLAG_PIN, + reinterpret_cast(&read_file_stable), &self)) { + const DWORD error = GetLastError(); + const int restored = patch_main_import("ReadFile", reinterpret_cast(next_read_file)) + + patch_main_import("WriteFile", reinterpret_cast(kernel_write_file)); + x2w_local::logf("x2w-xmem shared views (X2W_XMEM_SHARED_VIEWS): xmem.dll could not be pinned (error %lu); " + "%d of %d ReadFile/WriteFile import(s) restored", static_cast(error), restored, wrapped); + wrapped = 0; + } + x2w_local::logf("x2w-xmem shared views (X2W_XMEM_SHARED_VIEWS): %d ReadFile/WriteFile import(s) run again after a run " + "break that refused their buffer", wrapped); + return wrapped; +}(); } // namespace // Experimental export: writes bytes into physical pages named by the title's diff --git a/src/xmem_shim.cpp b/src/xmem_shim.cpp index 50272449cc..61f64e716f 100644 --- a/src/xmem_shim.cpp +++ b/src/xmem_shim.cpp @@ -104,9 +104,28 @@ extern "C" void XMemFree(void* allocation, ULONGLONG attributes) era_heap::release_with_attributes(allocation, attributes); } +extern "C" BOOL WINAPI x2w_xmem_stable_call(void (*fn)(void*), void* context); + +// The answer for a page of a shared-view run is taken outside a run break (x2w_xmem_stable_call): inside one the +// page would read as reserved. era_query writes a local buffer, and on success its tail_offset + 1 bytes (the MBI and +// the tail byte, all that era_query writes) go to the caller's after the call: on stable_call's mutex path the +// lazy-commit handler passes faults on, so an uncommitted mapped slot is not written there. The caller's buffer is +// not read, and nothing is written to it on failure. extern "C" BOOL XMemVirtualQuery(HANDLE process, LPCVOID address, void* buffer) { - return era_query::query(process, address, buffer, query_buffer_bytes) != 0; + struct Query { + HANDLE process; + LPCVOID address; + unsigned char* buffer; + unsigned char copy[query_buffer_bytes]; + std::size_t result; + } query{process, address, static_cast(buffer), {}, 0}; + x2w_xmem_stable_call([](void* context) { + auto& q = *static_cast(context); + q.result = era_query::query(q.process, q.address, q.buffer ? q.copy : nullptr, query_buffer_bytes); + }, &query); + if (query.buffer && query.result) std::memcpy(query.buffer, query.copy, era_query::tail_offset + 1); + return query.result != 0; } // Desktop policy (docs/experiments.md): writes only +8, with this process's GPU memory in bytes; diff --git a/src/xmem_shim.def b/src/xmem_shim.def index 3776c7529f..06c581eb0c 100644 --- a/src/xmem_shim.def +++ b/src/xmem_shim.def @@ -22,3 +22,6 @@ EXPORTS x2w_xmem_release_section @20 x2w_xmem_match_section @21 X2WMapPageBatch @22 + x2w_xmem_copy_to_destination @23 + x2w_xmem_map_counts @25 + x2w_xmem_stable_call @26 diff --git a/tests/linear_buffer_backing_check.cpp b/tests/linear_buffer_backing_check.cpp index a735c1ef8d..98ceaf1681 100644 --- a/tests/linear_buffer_backing_check.cpp +++ b/tests/linear_buffer_backing_check.cpp @@ -345,7 +345,7 @@ struct Pool { write(previous.cpu, 0, D, alloc_pages * page / 4); return release(previous); } - bool map(Memory& out, unsigned pages) + bool map(Memory& out, unsigned pages, bool split_last_page = false) { out.cpu = base + cursor; if (cursor + pages * page > bytes) return false; @@ -353,8 +353,13 @@ struct Pool { if (!xmem) return true; out.tokens.assign(pages, 0); ULONG_PTR got = pages; - return XMemAllocatePhysicalPages(0x20400000, &got, out.tokens.data()) && got == pages && - XMemMapPhysicalPages(out.cpu, pages, out.tokens.data()) == out.cpu; + if (!XMemAllocatePhysicalPages(0x20400000, &got, out.tokens.data()) || got != pages) return false; + if (!split_last_page) return XMemMapPhysicalPages(out.cpu, pages, out.tokens.data()) == out.cpu; + + // Map the upper page first so neither call can join across the boundary inside the buffer. + auto* const last_page = out.cpu + (pages - 1) * page; + return XMemMapPhysicalPages(last_page, 1, &out.tokens.back()) == last_page && + XMemMapPhysicalPages(out.cpu, pages - 1, out.tokens.data()) == out.cpu; } // One allocation in the case layout: neighbour pages, then the buffer filled with `fill`. bool allocate(Memory& out, Tag fill, bool* zero = nullptr) @@ -370,11 +375,7 @@ struct Pool { // Two pages of the buffer in two mapping calls (two views): the buffer crosses a view boundary. bool allocate_split(Memory& out, Tag fill) { - Memory first, second; - if (!xmem || !map(first, alloc_pages - 1) || !map(second, 1)) return false; - out.cpu = first.cpu; - out.tokens = first.tokens; - out.tokens.insert(out.tokens.end(), second.tokens.begin(), second.tokens.end()); + if (!xmem || !map(out, alloc_pages, true)) return false; write(out.cpu, 0, neighbour, buffer_offset / 4); write(out.buffer(), 0, fill, buffer_bytes / 4); return true; diff --git a/tests/startup_dstorage_break_window_check.cpp b/tests/startup_dstorage_break_window_check.cpp new file mode 100644 index 0000000000..d04d329bac --- /dev/null +++ b/tests/startup_dstorage_break_window_check.cpp @@ -0,0 +1,240 @@ +// A DirectStorage request whose destination lies in an XMem run that is being taken apart must wait for the break +// and then land, not be refused. +// +// With shared views (X2W_XMEM_SHARED_VIEWS=1) adjacent pages of one batch share a view, and unmapping one page of +// such a run unmaps the whole run and maps its other pages again, under xmem's mapping mutex. For that moment a +// surviving page reads as reserved. The xmem build with its test controls holds an unmap in that window +// (X2W_XMEM_TEST_HOLD_WINDOW=: it sets ".unmapped" and waits up to five seconds for ".release"). +// +// usage: startup_dstorage_break_window_check +// Cases, each against the real stand-in's queue with a memory source: +// - no break: a request into a mapped page of the run lands; +// - read-only destination: refused, nothing written (the writability check also runs on the xmem path); +// - break held: while an unmap holds page 2's run apart (page 2 reads MEM_RESERVE), a request into page 2 must not +// complete for the whole hold window (1000 ms, polled every 10 ms); after the release it completes with S_OK and +// every byte landed. An XCRDAPI that judges the destination with its own VirtualQuery instead refuses inside the +// window: "FAIL break window: refused while the run was broken" (the negative control in CMakeLists.txt). +#ifndef WIN32_LEAN_AND_MEAN +#define WIN32_LEAN_AND_MEAN +#endif +#ifndef NOMINMAX +#define NOMINMAX +#endif +#include + +#include +#include +#include + +namespace { +using u64 = std::uint64_t; +struct Object { void** vtable; }; +using GetFactoryFn = long(__stdcall*)(const void*, void**); +using CreateStatusArrayFn = long(__stdcall*)(void*, unsigned, const char*, const void*, void**); +using CreateQueueFn = long(__stdcall*)(void*, const void*, const void*, void**); +using EnqueueRequestFn = void(__stdcall*)(void*, const void*); +using EnqueueStatusFn = void(__stdcall*)(void*, void*, unsigned); +using SubmitFn = void(__stdcall*)(void*); +using IsCompleteFn = bool(__stdcall*)(void*, unsigned); +using GetHResultFn = long(__stdcall*)(void*, unsigned); +using VirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD); +using AllocatePagesFn = BOOL(WINAPI*)(ULONG_PTR, PULONG_PTR, PULONG_PTR); +using MapPagesFn = void*(WINAPI*)(void*, ULONG_PTR, const ULONG_PTR*); +using ScatterFn = BOOL(WINAPI*)(void* const*, ULONG_PTR, const ULONG_PTR*); + +constexpr SIZE_T page = 65536; +constexpr unsigned run_pages = 8; +constexpr unsigned bytes = 4096; +constexpr DWORD hold_ms = 1000; // the window in which a request into the broken run must not complete +constexpr DWORD poll_ms = 10; +unsigned char source[bytes]; +int failures; + +Object* status; +Object* queue; +unsigned next_index; + +void fail(const char* name, const char* what) +{ + std::printf("FAIL %s: %s\n", name, what); + ++failures; +} + +// Enqueues one uncompressed memory-source request and submits it; returns its status index. +unsigned submit(unsigned char* destination, unsigned capacity, unsigned size) +{ + unsigned char request[0x48] = {}; + *reinterpret_cast(request + 0x00) = 0x400000; + *reinterpret_cast(request + 0x08) = destination; + *reinterpret_cast(request + 0x18) = capacity; + *reinterpret_cast(request + 0x20) = source; + *reinterpret_cast(request + 0x30) = size; + const unsigned index = next_index++; + reinterpret_cast(queue->vtable[3])(queue, request); + reinterpret_cast(queue->vtable[4])(queue, status, index); + reinterpret_cast(queue->vtable[6])(queue); + return index; +} + +// Polls the status entry for up to milliseconds; true with its HRESULT when it completed. +bool completed_within(unsigned index, DWORD milliseconds, long& hr) +{ + for (DWORD waited = 0;; waited += poll_ms) { + if (reinterpret_cast(status->vtable[3])(status, index)) { + hr = reinterpret_cast(status->vtable[4])(status, index); + return true; + } + if (waited >= milliseconds) return false; + Sleep(poll_ms); + } +} + +bool filled(const unsigned char* at, unsigned char value, unsigned count) +{ + for (unsigned i = 0; i < count; ++i) + if (at[i] != value) return false; + return true; +} + +DWORD query_state(const void* address) +{ + MEMORY_BASIC_INFORMATION info{}; + return VirtualQuery(address, &info, sizeof(info)) ? info.State : 0; +} + +struct Unmap { + ScatterFn scatter; + void* address; + BOOL result; +}; + +DWORD WINAPI unmap_one(void* context) +{ + auto* unmap = static_cast(context); + unmap->result = unmap->scatter(&unmap->address, 1, nullptr); // no pages: unmap + return 0; +} +} // namespace + +int main(int argc, char** argv) +{ + if (argc != 3) { + std::printf("usage: startup_dstorage_break_window_check \n"); + return 2; + } + char hold_name[64]; + std::snprintf(hold_name, sizeof(hold_name), "x2w-dstorage-break-window-%lu", GetCurrentProcessId()); + SetEnvironmentVariableA("X2W_XMEM_SHARED_VIEWS", "1"); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", hold_name); + + // xmem first: XCRDAPI finds it by module name (GetModuleHandleW(L"xmem.dll")). + HMODULE xmem = LoadLibraryA(argv[1]); + if (!xmem || GetModuleHandleW(L"xmem.dll") != xmem) { + std::printf("FAIL setup: %s is not loaded as xmem.dll\n", argv[1]); + return 1; + } + const auto virtual_alloc = reinterpret_cast(GetProcAddress(xmem, "XMemVirtualAlloc")); + const auto allocate = reinterpret_cast(GetProcAddress(xmem, "XMemAllocatePhysicalPages")); + const auto map = reinterpret_cast(GetProcAddress(xmem, "XMemMapPhysicalPages")); + const auto scatter = reinterpret_cast(GetProcAddress(xmem, "XMemMapPhysicalPagesScatter")); + HMODULE library = LoadLibraryA(argv[2]); + auto* get_factory = library ? reinterpret_cast(GetProcAddress(library, "DStorageGetFactory")) : nullptr; + if (!virtual_alloc || !allocate || !map || !scatter || !get_factory) { + std::printf("FAIL setup: missing export\n"); + return 1; + } + void* factory_pointer = nullptr; + if (get_factory(nullptr, &factory_pointer) != 0 || !factory_pointer) return 1; + auto* factory = static_cast(factory_pointer); + void* status_pointer = nullptr; + void* queue_pointer = nullptr; + unsigned char description[0x28] = {}; + *reinterpret_cast(description + 8) = 16; + if (reinterpret_cast(factory->vtable[5])(factory, 8, "Status", nullptr, &status_pointer) != 0 || + reinterpret_cast(factory->vtable[10])(factory, description, nullptr, &queue_pointer) != 0) + return 1; + status = static_cast(status_pointer); + queue = static_cast(queue_pointer); + for (unsigned i = 0; i < bytes; ++i) source[i] = static_cast(i % 251 + 1); + + // Eight physical pages mapped as one run at the start of a startup reservation (as xmem_page_runs_check.py). + auto* whole = static_cast(virtual_alloc(nullptr, SIZE_T{16} << 30, 0x20402000, 0x21, PAGE_READWRITE)); + ULONG_PTR count = run_pages, tokens[run_pages] = {}; + unsigned char* base = whole ? whole + page : nullptr; + if (!base || !allocate(0x20400000, &count, tokens) || count != run_pages || map(base, run_pages, tokens) != base) { + std::printf("FAIL setup: could not map %u pages (err %lu)\n", run_pages, GetLastError()); + return 1; + } + MEMORY_BASIC_INFORMATION run{}; + if (!VirtualQuery(base, &run, sizeof(run)) || run.Type != MEM_MAPPED || run.RegionSize < run_pages * page) { + std::printf("FAIL setup: the %u pages are not one view (region 0x%zx), so no unmap takes a run apart\n", run_pages, + static_cast(run.RegionSize)); + return 1; + } + unsigned char* target = base + 2 * page; + + // No break: the request lands. + std::memset(target, 0xAA, bytes); + long hr = -1; + if (!completed_within(submit(target, bytes, bytes), 5000, hr)) fail("no break", "no completion"); + else if (hr != 0) fail("no break", "request failed"); + else if (std::memcmp(target, source, bytes) != 0) fail("no break", "bytes differ"); + else std::printf("ok: no break: the request into page 2 of the run landed\n"); + + // Read-only destination: refused before any write, on the xmem path too. + auto* plain = static_cast(VirtualAlloc(nullptr, 2 * bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + DWORD old = 0; + if (!plain) { + fail("read-only destination", "VirtualAlloc"); + } else { + std::memset(plain, 0xAA, 2 * bytes); + if (!VirtualProtect(plain + bytes, bytes, PAGE_READONLY, &old)) fail("read-only destination", "VirtualProtect"); + else if (!completed_within(submit(plain, 2 * bytes, bytes), 5000, hr)) fail("read-only destination", "no completion"); + else if (hr == 0) fail("read-only destination", "request succeeded"); + else if (!filled(plain, 0xAA, 2 * bytes)) fail("read-only destination", "bytes were written"); + else std::printf("ok: read-only destination: refused, nothing written\n"); + VirtualFree(plain, 0, MEM_RELEASE); + } + + // Break held: an unmap of page 5 takes the run apart and holds it there until released. + char event_name[96]; + std::snprintf(event_name, sizeof(event_name), "%s.unmapped", hold_name); + HANDLE unmapped = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.release", hold_name); + HANDLE release = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::memset(target, 0xAA, bytes); + Unmap unmap{scatter, base + 5 * page, FALSE}; + HANDLE thread = unmapped && release ? CreateThread(nullptr, 0, unmap_one, &unmap, 0, nullptr) : nullptr; + if (!thread || WaitForSingleObject(unmapped, 10000) != WAIT_OBJECT_0) { + std::printf("FAIL break window: the unmap never held the run apart (hook missing or timed out)\n"); + if (release) SetEvent(release); + return 1; + } + if (query_state(target) != MEM_RESERVE) { + std::printf("FAIL break window: page 2 is not reserved while the run is apart (state 0x%lx)\n", query_state(target)); + SetEvent(release); + return 1; + } + std::printf("ok: break held: page 2 reads MEM_RESERVE while the run is apart\n"); + const unsigned index = submit(target, bytes, bytes); + const bool early = completed_within(index, hold_ms, hr); + const long early_hr = hr; + SetEvent(release); + const bool joined = WaitForSingleObject(thread, 10000) == WAIT_OBJECT_0; + if (early) { + if (early_hr != 0) fail("break window", "refused while the run was broken"); + else fail("break window", "completed while the run was broken"); + } else { + std::printf("ok: break held: no completion within %lu ms\n", hold_ms); + if (!completed_within(index, 5000, hr)) fail("break window", "no completion after the release"); + else if (hr != 0) fail("break window", "request failed after the release"); + else if (std::memcmp(target, source, bytes) != 0) fail("break window", "bytes differ after the release"); + else std::printf("ok: break released: the request completed with S_OK and every byte landed\n"); + } + if (!joined || !unmap.result) fail("break window", "the unmap of page 5 did not finish"); + CloseHandle(thread); + + if (failures) return 1; + std::printf("dstorage break window: the request waited for the break and landed\n"); + return 0; +} diff --git a/tests/xmem_cross_call_merge_check.cpp b/tests/xmem_cross_call_merge_check.cpp new file mode 100644 index 0000000000..3d0aa09cf2 --- /dev/null +++ b/tests/xmem_cross_call_merge_check.cpp @@ -0,0 +1,464 @@ +// Cross-call merge of shared views (X2W_XMEM_SHARED_VIEWS=1, src/xmem_mapped_pages.cpp, merge_with_previous). A run +// mapped by a call of its own joins the recorded run that ends at its address when its first page is the next slot of +// the section behind that run's last page and both lie in one reservation of the shim. What a view is, is measured +// with VirtualQuery: inside a view AllocationBase is the view's base and RegionSize the bytes to the view's end. +// +// Modes: +// check (test-controls xmem.dll) every case below. +// control (test-controls xmem.dll, X2W_XMEM_TEST_NO_MERGE=1) single-page calls keep a view each: the layout +// before the merge. Prints "no-merge control: 32 views". +// deployed (deployed xmem.dll, X2W_XMEM_TEST_NO_MERGE=1) the deployed shim ignores the test switch and merges. +// default (deployed xmem.dll, X2W_XMEM_SHARED_VIEWS unset) every page keeps a view of its own. +// timing (test-controls xmem.dll; not a ctest case) ms of a join, of a break and of an own-view map against the +// run length R (X2W_XMEM_TEST_MERGE_CAP), for the cap's table in the review notes. +// The pass line of control, deployed and default is printed at the end of main, only when no check failed. +// +// Cases of `check`: +// joined 32 single-page calls on consecutive slots: one view of 32 pages; each page keeps the mark written +// right after its own call. +// middle unmapping page 10 of that view leaves views [0, 10) and [11, 32) with their marks. +// reversed 32 single-page calls on slots in reverse order (adjacent addresses, not adjacent slots): 32 views, +// page i shows slot 31 - i. +// window X2W_XMEM_TEST_HOLD_WINDOW holds the merge while the earlier run is unmapped: a raw query of one +// of its pages is not committed; a thread that reads the page and an x2w_xmem_stable_call query both +// wait, then read the mark and MEM_COMMIT; the result is one view of 9 pages. +// refused-4/5 X2W_XMEM_TEST_FAULT=4:0 (the joined map refused) and 5:0 (joining the placeholders refused): the call +// succeeds, the earlier run is a view of 8 pages again, the new page a view of its own, marks kept, +// the pages unmap and release, and the live page count returns to where it was. +// two-reservations a caller placeholder split in two pieces, each recorded with XMemVirtualAlloc (permissive +// replace-placeholder call): a page at the start of the second piece does not join the first's run. +// capped 192 single-page calls make three runs of 64 pages (max_merged_run_pages); an unmap held in its window +// inside the middle run takes apart at most 64 pages, and the outer runs stay mapped. +// +// Usage: xmem_cross_call_merge_check check|control|deployed|default|timing +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include + +#include +#include +#include +#include +#include +#include +#include + +namespace { +using XMemVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD); +using XMemAllocatePhysicalPagesFn = BOOL(WINAPI*)(SIZE_T, SIZE_T*, SIZE_T*); +using XMemMapPhysicalPagesFn = void*(WINAPI*)(void*, SIZE_T, SIZE_T*); +using XMemFreePhysicalPagesFn = BOOL(WINAPI*)(SIZE_T, SIZE_T*); +using StableCallFn = BOOL(WINAPI*)(void (*)(void*), void*); +using PageStatsFn = BOOL(WINAPI*)(ULONGLONG*); +using VirtualAlloc2Fn = PVOID(WINAPI*)(HANDLE, PVOID, SIZE_T, ULONG, ULONG, MEM_EXTENDED_PARAMETER*, ULONG); + +constexpr SIZE_T page = SIZE_T{64} << 10; +constexpr SIZE_T count = 32; + +int failures = 0; +const char* token = nullptr; // the mode's pass line; main prints it at its end, and only with no failure + +bool check(bool ok, const char* name, const char* detail = "") +{ + std::printf("%s: %s%s%s\n", ok ? "ok" : "check_failed", name, *detail ? " " : "", detail); + if (!ok) ++failures; + return ok; +} + +struct Region { + ULONG_PTR allocation_base = 0; + SIZE_T size = 0; + DWORD state = 0; +}; + +Region region(const unsigned char* address) +{ + MEMORY_BASIC_INFORMATION info{}; + if (VirtualQuery(address, &info, sizeof(info)) != sizeof(info)) return {}; + return {reinterpret_cast(info.AllocationBase), info.RegionSize, info.State}; +} + +// The view that holds address starts at first and ends at end (exclusive). +bool view_is(const unsigned char* address, const unsigned char* first, const unsigned char* end) +{ + const Region r = region(address); + return r.state == MEM_COMMIT && r.allocation_base == reinterpret_cast(first) && + r.size == static_cast(end - address); +} + +std::uint32_t& word(unsigned char* address) { return *reinterpret_cast(address); } + +struct Shim { + XMemVirtualAllocFn virtual_alloc; + XMemAllocatePhysicalPagesFn allocate; + XMemMapPhysicalPagesFn map; + XMemFreePhysicalPagesFn release; + StableCallFn stable_call; + PageStatsFn page_stats; + + std::vector pages(SIZE_T n) const + { + std::vector tokens(n); + SIZE_T got = n; + if (!allocate(0x20400000, &got, tokens.data()) || got != n) tokens.clear(); + return tokens; + } + ULONGLONG live() const + { + ULONGLONG value = ~0ull; + page_stats(&value); + return value; + } +}; + +// Maps tokens[order(i)] at base + i pages, one call each, and marks each page right after its call, before the next +// call merges it. Returns false when a call fails. +template +bool map_one_by_one(const Shim& shim, unsigned char* base, std::vector& tokens, std::uint32_t tag, Order order) +{ + for (SIZE_T i = 0; i < tokens.size(); ++i) { + unsigned char* const at = base + i * page; + if (shim.map(at, 1, &tokens[order(i)]) != at) return false; + word(at) = tag + static_cast(i); + word(at + page - 4) = static_cast(order(i)); + } + return true; +} + +bool marked(unsigned char* base, SIZE_T n, std::uint32_t tag, SIZE_T skip = SIZE_T(-1)) +{ + for (SIZE_T i = 0; i < n; ++i) { + if (i == skip) continue; + if (region(base + i * page).state != MEM_COMMIT || word(base + i * page) != tag + i) return false; + } + return true; +} + +// joined (merging modes) or the per-page layout (control, default); then middle in `check`. +void single_page_calls(const Shim& shim, unsigned char* base, bool merges, bool middle) +{ + auto tokens = shim.pages(count); + if (!check(tokens.size() == count, "allocate 32 pages")) return; + if (!check(map_one_by_one(shim, base, tokens, 0x61000000u, [](SIZE_T i) { return i; }), "32 single-page calls")) return; + if (merges) { + if (check(view_is(base, base, base + count * page) && view_is(base + (count - 1) * page, base, base + count * page), + "joined: one view of 32 pages")) + token = "merge: 1 view of 32 pages"; + } else { + bool each = true; + for (SIZE_T i = 0; i < count; ++i) each &= view_is(base + i * page, base + i * page, base + (i + 1) * page); + if (check(each, "one view per call")) token = "no-merge control: 32 views"; + } + check(marked(base, count, 0x61000000u), "joined: marks kept"); + if (middle) { + check(shim.map(base + 10 * page, 1, nullptr) == base + 10 * page, "middle: unmap page 10"); + check(view_is(base, base, base + 10 * page) && view_is(base + 9 * page, base, base + 10 * page), "middle: view [0, 10)"); + check(view_is(base + 11 * page, base + 11 * page, base + count * page), "middle: view [11, 32)"); + check(region(base + 10 * page).state == MEM_RESERVE, "middle: page 10 reserved"); + check(marked(base, count, 0x61000000u, 10), "middle: neighbours keep their marks"); + check(shim.map(base, 10, nullptr) == base && shim.map(base + 11 * page, count - 11, nullptr) == base + 11 * page, + "middle: unmap the rest"); + } else { + check(shim.map(base, count, nullptr) == base, "unmap 32 pages"); + } + check(shim.release(count, tokens.data()) != FALSE, "release 32 pages"); +} + +void reversed(const Shim& shim, unsigned char* base, unsigned char* scratch) +{ + auto tokens = shim.pages(count); + if (!check(tokens.size() == count, "reversed: allocate")) return; + // Mark every slot through one view first: slot k holds 0x62000000 + k. + if (!check(shim.map(scratch, count, tokens.data()) == scratch, "reversed: map the slots in order")) return; + for (SIZE_T k = 0; k < count; ++k) word(scratch + k * page) = 0x62000000u + static_cast(k); + check(shim.map(scratch, count, nullptr) == scratch, "reversed: unmap the slots"); + bool mapped = true; + for (SIZE_T i = 0; i < count && mapped; ++i) + mapped = shim.map(base + i * page, 1, &tokens[count - 1 - i]) == base + i * page; + if (!check(mapped, "reversed: 32 single-page calls")) return; + bool each = true, data = true; + for (SIZE_T i = 0; i < count; ++i) { + each &= view_is(base + i * page, base + i * page, base + (i + 1) * page); + data &= region(base + i * page).state == MEM_COMMIT && word(base + i * page) == 0x62000000u + (count - 1 - i); + } + check(each, "reversed: 32 views"); + check(data, "reversed: page i shows slot 31 - i"); + check(shim.map(base, count, nullptr) == base && shim.release(count, tokens.data()), "reversed: unmap and release"); +} + +void window(const Shim& shim, unsigned char* base) +{ + auto tokens = shim.pages(9); + if (!check(tokens.size() == 9 && shim.map(base, 8, tokens.data()) == base, "window: map a run of 8 pages")) return; + for (SIZE_T i = 0; i < 8; ++i) word(base + i * page) = 0x63000000u + static_cast(i); + char hold[64], event_name[96]; + std::snprintf(hold, sizeof(hold), "x2w-cross-call-merge-%lu", GetCurrentProcessId()); + std::snprintf(event_name, sizeof(event_name), "%s.unmapped", hold); + HANDLE unmapped = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.release", hold); + HANDLE release = CreateEventA(nullptr, TRUE, FALSE, event_name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", hold); + bool joined_call = false; + std::thread mapper([&] { joined_call = shim.map(base + 8 * page, 1, &tokens[8]) == base + 8 * page; }); + const bool opened = WaitForSingleObject(unmapped, 10000) == WAIT_OBJECT_0; + check(opened, "window: the merge held the window"); + unsigned char* const target = base + 2 * page; + if (opened) check(region(target).state != MEM_COMMIT, "window: raw query inside the window not committed"); + std::atomic read_done{false}, query_done{false}; + std::uint32_t value = 0; + DWORD state = 0; + std::thread reader([&] { + value = word(target); // faults inside the window; retried by the shim after it + read_done = true; + }); + std::thread querier([&] { + struct Query { unsigned char* target; DWORD state; } query{target, 0}; + shim.stable_call([](void* context) { + auto& q = *static_cast(context); + q.state = region(q.target).state; + }, &query); + state = query.state; + query_done = true; + }); + Sleep(300); + check(!read_done.load(), "window: the reader waits for the merge"); + check(!query_done.load(), "window: x2w_xmem_stable_call waits for the merge"); + SetEvent(release); + reader.join(); + querier.join(); + mapper.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + check(joined_call, "window: the mapping call succeeded"); + check(value == 0x63000002u, "window: the reader read the mark"); + check(state == MEM_COMMIT, "window: x2w_xmem_stable_call answered committed"); + check(view_is(base, base, base + 9 * page), "window: one view of 9 pages"); + check(marked(base, 8, 0x63000000u), "window: marks kept"); + check(shim.map(base, 9, nullptr) == base && shim.release(9, tokens.data()), "window: unmap and release"); + CloseHandle(unmapped); + CloseHandle(release); +} + +void refused(const Shim& shim, unsigned char* base, const char* stage, const char* name) +{ + const ULONGLONG live_before = shim.live(); + auto tokens = shim.pages(9); + if (!check(tokens.size() == 9 && shim.map(base, 8, tokens.data()) == base, name, "map a run of 8 pages")) return; + for (SIZE_T i = 0; i < 8; ++i) word(base + i * page) = 0x64000000u + static_cast(i); + SetEnvironmentVariableA("X2W_XMEM_TEST_FAULT", stage); + const bool mapped = shim.map(base + 8 * page, 1, &tokens[8]) == base + 8 * page; + SetEnvironmentVariableA("X2W_XMEM_TEST_FAULT", nullptr); + check(mapped, name, "the mapping call succeeded"); + // State first: a page without a view is not touched. + bool committed = true; + for (SIZE_T i = 0; i < 9; ++i) committed &= region(base + i * page).state == MEM_COMMIT; + if (!check(committed, name, "all 9 pages committed")) return; + check(view_is(base, base, base + 8 * page) && view_is(base + 7 * page, base, base + 8 * page), name, + "the run is a view of 8 pages again"); + check(view_is(base + 8 * page, base + 8 * page, base + 9 * page), name, "the new page has a view of its own"); + check(marked(base, 8, 0x64000000u), name, "marks kept"); + word(base + 8 * page) = 0x64000008u; + check(marked(base, 9, 0x64000000u), name, "the new page holds its write"); + check(shim.map(base, 9, nullptr) == base, name, "unmap 9 pages"); + check(shim.release(9, tokens.data()) != FALSE, name, "release 9 pages"); + check(shim.live() == live_before, name, "live page count back where it was"); +} + +// Named events for X2W_XMEM_TEST_HOLD_WINDOW: ".unmapped" (set by the held call) and ".release". +struct Hold { + char name[64]; + HANDLE unmapped, release; + explicit Hold(const char* stem) + { + std::snprintf(name, sizeof(name), "x2w-cross-call-merge-%s-%lu", stem, GetCurrentProcessId()); + char event_name[96]; + std::snprintf(event_name, sizeof(event_name), "%s.unmapped", name); + unmapped = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.release", name); + release = CreateEventA(nullptr, TRUE, FALSE, event_name); + } + ~Hold() + { + CloseHandle(unmapped); + CloseHandle(release); + } +}; + +// capped: 3 * cap single-page calls make three runs of cap pages (the cap of the shim, 64), not one. The unmap of a +// page in the middle run is held in its window: the pages that read as not committed there are the pages the break +// took apart, at most one run of cap pages; the runs before and after it stay mapped. +void capped(const Shim& shim, unsigned char* base) +{ + constexpr SIZE_T cap = 64, n = 3 * cap, hole = cap + cap / 2; + auto tokens = shim.pages(n); + if (!check(tokens.size() == n, "capped: allocate 192 pages")) return; + if (!check(map_one_by_one(shim, base, tokens, 0x65000000u, [](SIZE_T i) { return i; }), "capped: 192 single-page calls")) + return; + bool runs = true; + for (SIZE_T r = 0; r < 3; ++r) + runs &= view_is(base + r * cap * page, base + r * cap * page, base + (r + 1) * cap * page) && + view_is(base + ((r + 1) * cap - 1) * page, base + r * cap * page, base + (r + 1) * cap * page); + check(runs, "capped: three views of 64 pages"); + Hold hold("capped"); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", hold.name); + bool unmapped_call = false; + std::thread unmapper([&] { unmapped_call = shim.map(base + hole * page, 1, nullptr) == base + hole * page; }); + const bool opened = WaitForSingleObject(hold.unmapped, 10000) == WAIT_OBJECT_0; + SIZE_T taken_apart = 0; + bool outer_mapped = true; + for (SIZE_T i = 0; opened && i < n; ++i) { + const bool committed = region(base + i * page).state == MEM_COMMIT; + taken_apart += !committed; + if (i < cap || i >= 2 * cap) outer_mapped &= committed; + } + SetEvent(hold.release); + unmapper.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + char detail[64]; + std::snprintf(detail, sizeof(detail), "(%zu pages)", static_cast(taken_apart)); + check(opened, "capped: the unmap held the window"); + check(opened && taken_apart <= cap, "capped: the break took apart at most 64 pages", detail); + check(opened && outer_mapped, "capped: the runs before and after stay mapped in the window"); + check(unmapped_call, "capped: the unmap succeeded"); + check(view_is(base + cap * page, base + cap * page, base + hole * page) && + view_is(base + (hole + 1) * page, base + (hole + 1) * page, base + 2 * cap * page), "capped: views [64, 96) and [97, 128)"); + check(marked(base, n, 0x65000000u, hole), "capped: marks kept"); + check(shim.map(base, hole, nullptr) == base && shim.map(base + (hole + 1) * page, n - hole - 1, nullptr) == base + (hole + 1) * page && + shim.release(n, tokens.data()), "capped: unmap and release"); +} + +// timing (not a ctest case; ready.md's table): for a run of R pages, the ms of the call that joins page R to a run of +// R - 1 (X2W_XMEM_TEST_MERGE_CAP=R), of the unmap of page R/2 (one break of the whole run) and, for comparison, of a +// single-page call that maps a view of its own (X2W_XMEM_TEST_NO_MERGE=1). Every byte of the run is written before +// the join and before the break, as a title's use of the pages would (a run that is mostly untouched unmaps much +// faster). Median of 5 (3 from 1024 pages). This process has a few +// views; a title process has tens of thousands, and under Wine each map costs more the more views there are. +double ms_since(const LARGE_INTEGER& from) +{ + LARGE_INTEGER now, frequency; + QueryPerformanceCounter(&now); + QueryPerformanceFrequency(&frequency); + return 1000.0 * static_cast(now.QuadPart - from.QuadPart) / static_cast(frequency.QuadPart); +} + +double median(std::vector v) +{ + std::sort(v.begin(), v.end()); + return v.empty() ? 0.0 : v[v.size() / 2]; +} + +void timing(const Shim& shim, unsigned char* base) +{ + std::printf("timing: R pages | join ms | break ms | own-view map ms (median of 5)\n"); + for (const SIZE_T r : {SIZE_T{16}, SIZE_T{32}, SIZE_T{64}, SIZE_T{128}, SIZE_T{256}, SIZE_T{512}, SIZE_T{1024}, + SIZE_T{2048}, SIZE_T{4096}}) { + std::vector join, unmap, own; + char cap[24]; + std::snprintf(cap, sizeof(cap), "%zu", static_cast(r)); + for (int rep = 0; rep < (r >= 1024 ? 3 : 5); ++rep) { + auto tokens = shim.pages(r + 1); + if (!check(tokens.size() == r + 1 && shim.map(base, r - 1, tokens.data()) == base, "timing: map R - 1 pages")) return; + std::memset(base, 0x5a, (r - 1) * page); + SetEnvironmentVariableA("X2W_XMEM_TEST_MERGE_CAP", cap); + LARGE_INTEGER t; + QueryPerformanceCounter(&t); + const bool joined = shim.map(base + (r - 1) * page, 1, &tokens[r - 1]) == base + (r - 1) * page; + join.push_back(ms_since(t)); + SetEnvironmentVariableA("X2W_XMEM_TEST_MERGE_CAP", nullptr); + check(joined && view_is(base, base, base + r * page), "timing: joined run of R pages"); + std::memset(base, 0x5b, r * page); + QueryPerformanceCounter(&t); + check(shim.map(base + (r / 2) * page, 1, nullptr) == base + (r / 2) * page, "timing: unmap page R/2"); + unmap.push_back(ms_since(t)); + SetEnvironmentVariableA("X2W_XMEM_TEST_NO_MERGE", "1"); + QueryPerformanceCounter(&t); + const bool alone = shim.map(base + r * page, 1, &tokens[r]) == base + r * page; + own.push_back(ms_since(t)); + SetEnvironmentVariableA("X2W_XMEM_TEST_NO_MERGE", nullptr); + check(alone && view_is(base + r * page, base + r * page, base + (r + 1) * page), "timing: own view"); + check(shim.map(base, r / 2, nullptr) == base && shim.map(base + (r / 2 + 1) * page, r / 2, nullptr) && + shim.release(r + 1, tokens.data()), "timing: unmap and release"); + } + std::printf("timing: %4zu | %7.3f | %7.3f | %7.3f\n", static_cast(r), median(join), median(unmap), median(own)); + } +} + +void two_reservations(const Shim& shim) +{ + const auto virtual_alloc2 = reinterpret_cast( + GetProcAddress(GetModuleHandleA("kernelbase.dll"), "VirtualAlloc2")); + if (!check(virtual_alloc2 != nullptr, "two-reservations: VirtualAlloc2")) return; + auto* const piece = static_cast(virtual_alloc2(GetCurrentProcess(), nullptr, 8 * page, + MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, PAGE_NOACCESS, nullptr, 0)); + if (!check(piece && VirtualFree(piece, 4 * page, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER), "two-reservations: split a placeholder")) + return; + SetEnvironmentVariableA("X2W_XMEM_PERMISSIVE", "1"); + const bool recorded = shim.virtual_alloc(piece, 4 * page, 0x20406000, 0x21, PAGE_READWRITE) == piece && + shim.virtual_alloc(piece + 4 * page, 4 * page, 0x20406000, 0x21, PAGE_READWRITE) == piece + 4 * page; + SetEnvironmentVariableA("X2W_XMEM_PERMISSIVE", nullptr); + if (!check(recorded, "two-reservations: record both pieces")) return; + auto tokens = shim.pages(5); + if (!check(tokens.size() == 5 && shim.map(piece, 4, tokens.data()) == piece && + shim.map(piece + 4 * page, 1, &tokens[4]) == piece + 4 * page, "two-reservations: map 4 + 1 pages")) + return; + check(view_is(piece, piece, piece + 4 * page), "two-reservations: the first piece's run stays 4 pages"); + check(view_is(piece + 4 * page, piece + 4 * page, piece + 5 * page), "two-reservations: the page has a view of its own"); + check(shim.map(piece, 4, nullptr) == piece && shim.map(piece + 4 * page, 1, nullptr) == piece + 4 * page && + shim.release(5, tokens.data()), "two-reservations: unmap and release"); + VirtualFree(piece, 0, MEM_RELEASE); + VirtualFree(piece + 4 * page, 0, MEM_RELEASE); +} +} // namespace + +int main(int argc, char** argv) +{ + const char* const mode = argc == 3 ? argv[2] : ""; + const bool all = std::strcmp(mode, "check") == 0, control = std::strcmp(mode, "control") == 0, + deployed = std::strcmp(mode, "deployed") == 0, plain = std::strcmp(mode, "default") == 0, + timed = std::strcmp(mode, "timing") == 0; + if (!all && !control && !deployed && !plain && !timed) { + std::printf("usage: xmem_cross_call_merge_check check|control|deployed|default|timing\n"); + return 2; + } + // The mode is read by the first mapping call. + SetEnvironmentVariableA("X2W_XMEM_SHARED_VIEWS", plain ? nullptr : "1"); + const HMODULE xmem = LoadLibraryA(argv[1]); + if (!xmem) { + std::printf("check_failed: load (error %lu)\n", GetLastError()); + return 1; + } + const Shim shim{reinterpret_cast(GetProcAddress(xmem, "XMemVirtualAlloc")), + reinterpret_cast(GetProcAddress(xmem, "XMemAllocatePhysicalPages")), + reinterpret_cast(GetProcAddress(xmem, "XMemMapPhysicalPages")), + reinterpret_cast(GetProcAddress(xmem, "XMemFreePhysicalPages")), + reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_stable_call")), + reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_page_stats"))}; + if (!shim.virtual_alloc || !shim.allocate || !shim.map || !shim.release || !shim.stable_call || !shim.page_stats) { + std::printf("check_failed: exports\n"); + return 1; + } + auto* const whole = static_cast(shim.virtual_alloc(nullptr, SIZE_T{16} << 30, 0x20402000, 0x21, PAGE_READWRITE)); + if (!whole) { + std::printf("check_failed: startup reservation (error %lu)\n", GetLastError()); + return 1; + } + unsigned char* const base = whole + page; + if (timed) { + timing(shim, base); + VirtualFree(whole, 0, MEM_RELEASE); + std::printf(failures ? "FAIL (%d)\n" : "PASS\n", failures); + return failures ? 1 : 0; + } + single_page_calls(shim, base, all || deployed, all); + if (all) { + reversed(shim, base + 64 * page, base + 128 * page); + window(shim, base + 192 * page); + refused(shim, base + 256 * page, "4:0", "refused-4"); + refused(shim, base + 320 * page, "5:0", "refused-5"); + two_reservations(shim); + capped(shim, base + 512 * page); + } + VirtualFree(whole, 0, MEM_RELEASE); + if (!failures && token) std::printf("%s\n", token); + std::printf(failures ? "FAIL (%d)\n" : "PASS\n", failures); + return failures ? 1 : 0; +} diff --git a/tests/xmem_map_split_first_check.cpp b/tests/xmem_map_split_first_check.cpp new file mode 100644 index 0000000000..4514fc6f3b --- /dev/null +++ b/tests/xmem_map_split_first_check.cpp @@ -0,0 +1,93 @@ +// XMemMapPhysicalPages into an owned XMem reservation: when the target is in the middle of a larger placeholder, xmem +// splits first and maps once (one MapViewOfFile3 per page). Under Wine each failed map is a server round trip whose +// cost grows with the number of views, and the title maps one 64 KiB page per call at startup. +// xmem_map_split_first_check N single-page maps take N map attempts; an exact placeholder +// (left by an unmap) is mapped without a split +// xmem_map_split_first_check control run by CTest with X2W_XMEM_TEST_MAP_FIRST=1: the old order takes +// 2N map attempts and prints "map-first control: maps=2N" +#include +#include +#include + +namespace { +constexpr SIZE_T page_bytes = 65536; +constexpr ULONG_PTR pages = 8; +using Reserve = void* (WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD); +using AllocPages = BOOL (WINAPI*)(ULONG_PTR, ULONG_PTR*, ULONG_PTR*); +using MapPages = void* (WINAPI*)(void*, ULONG_PTR, const ULONG_PTR*); +using MapCounts = BOOL (WINAPI*)(ULONGLONG*, ULONGLONG*); + +bool require(bool ok, const char* step) +{ + if (!ok) std::printf("FAIL: %s (last error %lu)\n", step, GetLastError()); + return ok; +} +} // namespace + +int wmain(int argc, wchar_t** argv) +{ + const bool control = argc == 3 && std::wcscmp(argv[2], L"control") == 0; + if (argc != 2 && !control) return 2; + const HMODULE xmem = LoadLibraryW(argv[1]); + if (!require(xmem != nullptr, "load xmem.dll")) return 1; + const auto reserve = reinterpret_cast(GetProcAddress(xmem, "XMemVirtualAlloc")); + const auto alloc = reinterpret_cast(GetProcAddress(xmem, "XMemAllocatePhysicalPages")); + const auto map = reinterpret_cast(GetProcAddress(xmem, "XMemMapPhysicalPages")); + const auto counts = reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_map_counts")); + if (!require(reserve && alloc && map && counts, "find the xmem exports")) return 1; + auto* const pool = static_cast(reserve(nullptr, SIZE_T{16} << 30, 0x20402000, 0x21, PAGE_READWRITE)); + if (!require(pool != nullptr, "reserve XMem addresses")) return 1; + ULONG_PTR grants[pages]{}, count = pages; + if (!require(alloc(0x280, &count, grants) && count == pages, "allocate the pages")) return 1; + + // N single-page maps, each into the middle of the reservation's placeholder (every other page, so no two + // targets are neighbours). + ULONGLONG maps0 = 0, splits0 = 0, maps1 = 0, splits1 = 0; + if (!require(counts(&maps0, &splits0), "read the map counts")) return 1; + for (ULONG_PTR i = 0; i < pages; ++i) { + BYTE* const target = pool + (16 + 2 * i) * page_bytes; + if (!require(map(target, 1, &grants[i]) == target, "map one page into the reservation")) return 1; + target[0] = static_cast(0x40 + i); + target[page_bytes - 1] = static_cast(0x40 + i); + } + if (!require(counts(&maps1, &splits1), "read the map counts")) return 1; + const ULONGLONG maps = maps1 - maps0, splits = splits1 - splits0; + std::printf("%llu single-page maps: map attempts %llu, split attempts %llu\n", static_cast(pages), + maps, splits); + for (ULONG_PTR i = 0; i < pages; ++i) { + const BYTE* const target = pool + (16 + 2 * i) * page_bytes; + if (!require(target[0] == 0x40 + i && target[page_bytes - 1] == 0x40 + i, "each mapped page keeps its bytes")) + return 1; + } + MEMORY_BASIC_INFORMATION gap{}; + VirtualQuery(pool + 17 * page_bytes, &gap, sizeof(gap)); + if (!require(gap.State == MEM_RESERVE, "the page between two targets stays reserved")) return 1; + if (control) { + if (maps == 2 * pages && splits == pages) { + std::puts("map-first control: maps=2N"); + return 1; // CTest passes the control on the line above, not on the exit code + } + std::printf("FAIL: map-first control measured %llu maps for %llu pages\n", maps, + static_cast(pages)); + return 1; + } + if (!require(maps == pages && splits == pages, "split-first: one map attempt and one split per page")) return 1; + + // An exact placeholder: unmap the first page (the placeholder is kept), then map a page there again. No split. + BYTE* const first = pool + 16 * page_bytes; + if (!require(map(first, 1, nullptr) == first, "unmap the first page")) return 1; + MEMORY_BASIC_INFORMATION hole{}; + VirtualQuery(first, &hole, sizeof(hole)); + std::printf("after unmap: state 0x%lx base %p allocation %p size 0x%llx\n", hole.State, hole.BaseAddress, + hole.AllocationBase, static_cast(hole.RegionSize)); + if (!require(counts(&maps0, &splits0), "read the map counts") || + !require(map(first, 1, &grants[0]) == first, "map a page into the exact placeholder") || + !require(counts(&maps1, &splits1), "read the map counts")) + return 1; + std::printf("exact placeholder: map attempts %llu, split attempts %llu\n", maps1 - maps0, splits1 - splits0); + if (!require(maps1 - maps0 == 1 && splits1 - splits0 == 0, "an exact placeholder is mapped without a split") || + !require(first[0] == 0x40, "the remapped page reads its bytes")) + return 1; + std::puts("split-first: maps=N; exact placeholder mapped without a split"); + return 0; +} diff --git a/tests/xmem_page_runs_check.py b/tests/xmem_page_runs_check.py index afb878d74f..b9bf799cd8 100644 --- a/tests/xmem_page_runs_check.py +++ b/tests/xmem_page_runs_check.py @@ -153,9 +153,11 @@ def view(page, first, last): assert view(i, 4, 7), f"upper piece, page {i}: {shim.query(base + i * PAGE)}" hole = shim.query(base + 3 * PAGE) assert hole[1] == base + 3 * PAGE and hole[2] == PAGE and hole[3] == MEM_RESERVE, hole - # Mapping the page again does not join the pieces: three views. + # Mapping the page again on its own call joins the lower piece, which ends at it on the slot before + # (merge_with_previous): two views. It never joins the upper piece. One view per call without the merge is + # asserted by xmem_cross_call_merge_control (tests/xmem_cross_call_merge_check.cpp). assert shim.contiguous(base + 3 * PAGE, 1, C.byref(shim.number(tokens[3]))) == base + 3 * PAGE - assert view(3, 3, 3) and view(2, 0, 2) and view(4, 4, 7) + assert view(3, 0, 3) and view(2, 0, 3) and view(4, 4, 7), (shim.query(base + 3 * PAGE), shim.query(base + 4 * PAGE)) assert shim.contiguous(base, 8, None) == base and shim.release(8, tokens) diff --git a/tests/xmem_page_runs_device_check.cpp b/tests/xmem_page_runs_device_check.cpp index e89264236e..c1f1ec807a 100644 --- a/tests/xmem_page_runs_device_check.cpp +++ b/tests/xmem_page_runs_device_check.cpp @@ -88,11 +88,14 @@ int main(int argc, char** argv) if (!whole) return 1; unsigned char* const first = whole + page; - // Two mapping calls next to each other: two views that meet at first + 8 pages. + // Two mapping calls next to each other: two views that meet at first + 8 pages. The upper one is mapped first: a + // call joins only a view that ends at its address (merge_with_previous), never one that starts after it. const auto a = pages(8), b = pages(8); - if (a.empty() || b.empty() || XMemMapPhysicalPages(first, 8, a.data()) != first || - XMemMapPhysicalPages(first + 8 * page, 8, b.data()) != first + 8 * page) + if (a.empty() || b.empty() || XMemMapPhysicalPages(first + 8 * page, 8, b.data()) != first + 8 * page || + XMemMapPhysicalPages(first, 8, a.data()) != first) { + std::printf("check_failed: allocate or map the two 8-page calls (error %lu)\n", GetLastError()); return 1; + } place("inside one view", wrapper.Get(), first + 4 * page, 1); place("across two mapping calls", wrapper.Get(), first + 8 * page, 2); @@ -107,12 +110,19 @@ int main(int argc, char** argv) } place("across two backing sections", wrapper.Get(), second + info.RegionSize, 2); - // Pages mapped one call at a time get a view each: the layout every page had before views were shared. + // Map the single pages from high to low addresses. Each call then has no adjacent view below it to join, + // regardless of the order in which the allocator assigned the backing slots. unsigned char* const third = second + 8192 * page; const auto single = pages(8); - if (single.empty()) return 1; - for (int i = 0; i < 8; ++i) - if (XMemMapPhysicalPages(third + i * page, 1, &single[i]) != third + i * page) return 1; + if (single.empty()) { + std::printf("check_failed: allocate 8 single pages (error %lu)\n", GetLastError()); + return 1; + } + for (int i = 7; i >= 0; --i) + if (XMemMapPhysicalPages(third + i * page, 1, &single[7 - i]) != third + i * page) { + std::printf("check_failed: single-page call %d (error %lu)\n", i, GetLastError()); + return 1; + } place("across two single-page views", wrapper.Get(), third + 4 * page, 2); if (failures) { diff --git a/tests/xmem_placeholder_split_check.cpp b/tests/xmem_placeholder_split_check.cpp new file mode 100644 index 0000000000..767c3a6579 --- /dev/null +++ b/tests/xmem_placeholder_split_check.cpp @@ -0,0 +1,109 @@ +// Queue slot 31 (X2WMapPageBatch) into the middle of an XMem reservation needs a placeholder split. Where the region +// query does not report placeholders (Wine), xmem probes whether a placeholder release refuses a plain reservation +// and then offers reserved regions to the split (xmem placeholder_fallback). +// xmem_placeholder_split_check split succeeds; a committed target still fails and stays intact +// xmem_placeholder_split_check control the same checks, run with X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1 +// by CTest, which expects the split step to fail; exits 77 where +// the OS reports the bit, because there the fallback is never used +#include +#include "xmem_page_batch.h" +#include +#include +#include + +namespace { +constexpr SIZE_T page_bytes = 65536; +constexpr UINT pool_pages = 4; +using Reserve = void* (WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD); +using AllocPages = BOOL (WINAPI*)(ULONG_PTR, ULONG_PTR*, ULONG_PTR*); +using Scatter = BOOL (WINAPI*)(void* const*, ULONG_PTR, const ULONG_PTR*); + +bool require(bool ok, const char* step) +{ + if (!ok) std::printf("FAIL: %s (last error %lu)\n", step, GetLastError()); + return ok; +} + +bool os_reports_placeholder_bit() +{ + void* probe = VirtualAlloc2(GetCurrentProcess(), nullptr, 2 * page_bytes, MEM_RESERVE | MEM_RESERVE_PLACEHOLDER, + PAGE_NOACCESS, nullptr, 0); + if (!probe) return false; + WIN32_MEMORY_REGION_INFORMATION info{}; + const bool bit = QueryVirtualMemoryInformation(GetCurrentProcess(), probe, MemoryRegionInfo, &info, sizeof(info), + nullptr) && (info.Flags & 0x100); + VirtualFree(probe, 0, MEM_RELEASE); + return bit; +} + +MEMORY_BASIC_INFORMATION query(const BYTE* pointer) +{ + MEMORY_BASIC_INFORMATION info{}; + VirtualQuery(pointer, &info, sizeof(info)); + return info; +} +} // namespace + +int wmain(int argc, wchar_t** argv) +{ + const bool control = argc == 3 && std::wcscmp(argv[2], L"control") == 0; + if (argc != 2 && !control) return 2; + const bool bit = os_reports_placeholder_bit(); + std::printf("placeholder bit reported=%d\n", bit); + if (control && bit) { + std::puts("SKIP: the OS reports the placeholder bit, so the fallback is never used"); + return 77; + } + const HMODULE xmem = LoadLibraryW(argv[1]); + if (!require(xmem != nullptr, "load xmem.dll")) return 1; + const auto reserve = reinterpret_cast(GetProcAddress(xmem, "XMemVirtualAlloc")); + const auto alloc = reinterpret_cast(GetProcAddress(xmem, "XMemAllocatePhysicalPages")); + const auto scatter = reinterpret_cast(GetProcAddress(xmem, "XMemMapPhysicalPagesScatter")); + const auto batch_map = reinterpret_cast(GetProcAddress(xmem, "X2WMapPageBatch")); + if (!require(reserve && alloc && scatter && batch_map, "find the xmem exports")) return 1; + + auto* const pool = static_cast(reserve(nullptr, SIZE_T{16} << 30, 0x20402000, 0x21, PAGE_READWRITE)); + if (!require(pool != nullptr, "reserve XMem addresses")) return 1; + ULONG_PTR grants[pool_pages]{}, count = pool_pages; + void* addresses[pool_pages]{}; + for (UINT i = 0; i < pool_pages; ++i) addresses[i] = pool + i * page_bytes; + if (!require(alloc(0x280, &count, grants) && count == pool_pages, "allocate the pool") || + !require(scatter(addresses, pool_pages, grants), "map the pool")) + return 1; + for (UINT i = 0; i < pool_pages; ++i) std::memset(addresses[i], 0x51 + i, page_bytes); + + // Negative control: a committed page inside the reservation is not a placeholder. The batch must fail and leave + // the page committed with its bytes. + BYTE* const committed = pool + 64 * page_bytes; + if (!require(VirtualFree(committed, page_bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER), "split out a page") || + !require(VirtualAlloc2(GetCurrentProcess(), committed, page_bytes, MEM_RESERVE | MEM_COMMIT | MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, nullptr, 0) == committed, "commit that page")) + return 1; + std::memset(committed, 0x77, page_bytes); + const X2WPageRange one{0, 0, 1}; + const X2WPageBatch onto_committed{reinterpret_cast(committed), 1, &one}; + const HRESULT refused = batch_map(1, &onto_committed, reinterpret_cast(pool), pool_pages, 0, nullptr); + std::printf("batch onto a committed page -> 0x%08lx\n", static_cast(refused)); + // The code is the OS's map failure: Windows 487, Wine 87 (measured 2026-11-26). + if (!require(FAILED(refused), "a committed target is refused") || + !require(query(committed).State == MEM_COMMIT && committed[0] == 0x77 && committed[page_bytes - 1] == 0x77, + "the committed target keeps its bytes")) + return 1; + + // The split: pool pages 1 and 2 into the middle of an untouched part of the reservation. + BYTE* const window = pool + 128 * page_bytes; + const X2WPageRange two{0, 1, 2}; + const X2WPageBatch split{reinterpret_cast(window + page_bytes), 1, &two}; + const HRESULT hr = batch_map(1, &split, reinterpret_cast(pool), pool_pages, 0, nullptr); + std::printf("batch into the middle of the reservation -> 0x%08lx\n", static_cast(hr)); + if (!require(SUCCEEDED(hr), "map two pool pages into the middle of the reservation") || + !require(window[page_bytes] == 0x52 && window[2 * page_bytes] == 0x53 && window[3 * page_bytes - 1] == 0x53, + "the destination reads the pool pages") || + !require(query(window).State == MEM_RESERVE && query(window + 3 * page_bytes).State == MEM_RESERVE, + "the neighbours stay reserved")) + return 1; + window[page_bytes] = 0x60; + if (!require(pool[page_bytes] == 0x60, "a write through the destination reaches the pool page")) return 1; + std::puts("slot31 split inside an XMem reservation matched; a committed target was refused and kept"); + return 0; +} diff --git a/tests/xmem_run_break_readers_check.cpp b/tests/xmem_run_break_readers_check.cpp new file mode 100644 index 0000000000..f4c78ce9cc --- /dev/null +++ b/tests/xmem_run_break_readers_check.cpp @@ -0,0 +1,803 @@ +// Readers that do not fault, inside a run break of the shared-view mode (X2W_XMEM_SHARED_VIEWS=1). Unmapping one +// page of a run unmaps the whole run, then maps its other pages again (src/xmem_mapped_pages.cpp, map_pages_locked). +// A thread that touches one of those pages in between faults and is retried; a region query or a kernel copy does +// not fault, so it reads the pages as reserved or fails. Each case below opens that window with the test-controls +// build's X2W_XMEM_TEST_HOLD_WINDOW, proves it is open with a raw VirtualQuery of a neighbour page (not committed), +// starts the reader under test on another thread, checks that it has not answered 300 ms later, releases the window +// and then checks the reader's answer: the neighbour page is committed, mapped and holds its data. +// +// Cases (one window each): x2w_xmem_stable_call, XMemVirtualQuery, this program's VirtualQueryEx import (wrapped by +// xmem.dll when it loads with the switch), this program's ReadFile and WriteFile imports (synchronous, into and out +// of the page; wrapped the same way), x2w_local::writable, x2w_startup::measure_placed_buffer and +// x2w_startup::snapshot_samplers. Then io_outside_runs: a ReadFile into a reserved page in no run fails at once. +// +// With `control` (the build whose local_log.h asks xmem.dll for a missing export, so the header readers run +// directly) the three header readers answer inside the window: the check expects that, and fails if they wait. +// +// Then a page that faults in two breaks in a row (retry_remapped_page): a thread faults on a page of a run taken +// apart by break A, and the test build's X2W_XMEM_TEST_HOLD_RETRY holds the handler until break A has ended, so the +// handler reads the generation after it; the thread is retried and reads its page. Break B then takes the same page +// apart, and the thread faults on it again: that fault must be retried as well (a different break). With +// `next-break-control` the handler is not held, so it reads break A while A is open: that order passes even when +// the handler names the breaks wrongly, which shows the hold is what this case depends on. +// +// A fault whose handler reads the breaks only after a later break on another run has begun (two_runs: break B on a +// disjoint run; mirror: one permissive XMemMapPhysicalPages call that joins the CPU run and then its GPU mirror run) +// must be retried as well: the handler keeps the ranges of the recent breaks, not only of the last one. +// +// The ring's edge (ring_edge): a held fault in break A whose handler reads the breaks after 63 later breaks is retried; +// after 64 later breaks, A is no longer recorded and the fault is passed on (the reader's own __except catches it). +// +// A break that begins while x2w_xmem_stable_call's fn runs (break_during_fn): fn itself starts the unmap, waits until +// the window is open and queries a page of the run (reserved). stable_call must see the generation change and run fn +// again under memory.mutex: 2 calls, the last one committed. +// +// `default` (X2W_XMEM_SHARED_VIEWS unset): every page has a view of its own, and readers that overlap an unmap +// answer inside it, without waiting for memory.mutex, as before x2w_xmem_stable_call. +// `lazy` (X2W_XMEM_SHARED_VIEWS=1, X2W_XMEM_LAZY_COMMIT=1): XMemVirtualQuery and VirtualQueryEx wait for a break +// with their output buffer in a mapped slot that is not committed yet; the answer reaches it after the break. Then a +// ReadFile into another such slot, with no break: the lazy-commit ReadFile wrapper still runs inside the run-break one. +// +// `two-runs` and `mirror` run those two cases alone (an access violation there ends the process); `ring-edge` runs +// ring_edge with 63 and then 64 later breaks. +// +// Usage: xmem_run_break_readers_check +// [control|next-break-control|default|lazy|two-runs|mirror|ring-edge] +#define WIN32_LEAN_AND_MEAN +#define NOMINMAX +#include + +#include + +#include "startup_stubs/local_log.h" +#include "startup_stubs/placed_buffer_range.h" +#include "startup_stubs/translated_sampler_bindings.h" + +#include +#include +#include +#include +#include + +namespace { +using XMemVirtualAllocFn = void*(WINAPI*)(void*, SIZE_T, DWORD, ULONGLONG, DWORD); +using XMemAllocatePhysicalPagesFn = BOOL(WINAPI*)(SIZE_T, SIZE_T*, SIZE_T*); +using XMemMapPhysicalPagesFn = void*(WINAPI*)(void*, SIZE_T, SIZE_T*); +using XMemFreePhysicalPagesFn = BOOL(WINAPI*)(SIZE_T, SIZE_T*); +using XMemVirtualQueryFn = BOOL(WINAPI*)(HANDLE, LPCVOID, void*); +using StableCallFn = BOOL(WINAPI*)(void (*)(void*), void*); + +constexpr SIZE_T page = SIZE_T{64} << 10; +constexpr SIZE_T pages = 8; +constexpr SIZE_T broken_page = 5; // the page unmapped; its run [0, 8) is taken apart +constexpr SIZE_T neighbour = 2; // a surviving page of that run, unmapped while the window is held + +int failures = 0; + +bool check(bool ok, const char* name, const char* reader) +{ + std::printf("%s: %s %s\n", ok ? "ok" : "check_failed", reader, name); + if (!ok) ++failures; + return ok; +} + +DWORD raw_state(const void* address) +{ + MEMORY_BASIC_INFORMATION info{}; + return VirtualQuery(address, &info, sizeof(info)) ? info.State : 0; +} + +struct Shim { + XMemVirtualAllocFn virtual_alloc; + XMemAllocatePhysicalPagesFn allocate; + XMemMapPhysicalPagesFn map; + XMemFreePhysicalPagesFn release; + XMemVirtualQueryFn query; + StableCallFn stable_call; +}; + +// One window: maps a fresh run of eight pages at base, marks every page, unmaps broken_page on a thread of its own +// with the hold set, and runs reader on another thread once the window is open. reader returns whether its answer +// says the neighbour page is committed and readable. waits: the reader must not answer before the release. +void window_case(const Shim& shim, unsigned char* base, int index, const char* name, bool waits, + const std::function& reader) +{ + SIZE_T count = pages, tokens[pages] = {}; + if (!shim.allocate(0x20400000, &count, tokens) || count != pages || shim.map(base, pages, tokens) != base) { + check(false, "map_run", name); + return; + } + for (SIZE_T i = 0; i < pages; ++i) *reinterpret_cast(base + i * page) = 0x51000000u + static_cast(i); + char hold[64], event_name[96]; + std::snprintf(hold, sizeof(hold), "x2w-run-break-readers-%lu-%d", GetCurrentProcessId(), index); + std::snprintf(event_name, sizeof(event_name), "%s.unmapped", hold); + HANDLE unmapped = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.release", hold); + HANDLE release = CreateEventA(nullptr, TRUE, FALSE, event_name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", hold); + unsigned char* const broken = base + broken_page * page; + std::thread unmapper([&] { shim.map(broken, 1, nullptr); }); + const bool opened = WaitForSingleObject(unmapped, 10000) == WAIT_OBJECT_0; + check(opened, "window_reached", name); + unsigned char* const target = base + neighbour * page; + if (opened) check(raw_state(target) != MEM_COMMIT, "window_open_raw_query_not_committed", name); + std::atomic started{false}, answered{false}; + bool answer = false; + std::thread reading([&] { + started = true; + answer = reader(target); + answered = true; + }); + for (int i = 0; i < 10000 && !started.load(); ++i) Sleep(1); // the 300 ms count from the reader's start + Sleep(300); + const bool early = answered.load(); + check(waits ? !early : early, waits ? "reader_waits_for_the_break" : "reader_answers_inside_the_window", name); + SetEvent(release); + reading.join(); + unmapper.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + check(waits ? answer : !answer, waits ? "answer_after_the_break_committed" : "answer_inside_the_window_not_committed", name); + check(*reinterpret_cast(target) == 0x51000000u + neighbour, "neighbour_data_kept", name); + shim.map(base, broken_page, nullptr); + shim.map(base + (broken_page + 1) * page, pages - broken_page - 1, nullptr); + shim.release(pages, tokens); + CloseHandle(unmapped); + CloseHandle(release); +} +// fn starts the unmap and waits for the window inside x2w_xmem_stable_call. +void break_during_fn(const Shim& shim, unsigned char* base) +{ + const char* const name = "break_during_fn"; + SIZE_T count = pages, tokens[pages] = {}; + if (!shim.allocate(0x20400000, &count, tokens) || count != pages || shim.map(base, pages, tokens) != base) { + check(false, "map_run", name); + return; + } + struct Context { + const Shim* shim; + unsigned char* base; + char hold[64]; + HANDLE unmapped, release; + std::thread unmapper, releaser; + int calls = 0; + DWORD first = 0, last = 0; + bool opened = false; + } c{&shim, base, {}, nullptr, nullptr}; + std::snprintf(c.hold, sizeof(c.hold), "x2w-run-break-during-fn-%lu", GetCurrentProcessId()); + char event_name[96]; + std::snprintf(event_name, sizeof(event_name), "%s.unmapped", c.hold); + c.unmapped = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.release", c.hold); + c.release = CreateEventA(nullptr, TRUE, FALSE, event_name); + shim.stable_call([](void* context) { + auto& c = *static_cast(context); + if (++c.calls == 1) { + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", c.hold); + c.unmapper = std::thread([&c] { c.shim->map(c.base + broken_page * page, 1, nullptr); }); + c.opened = WaitForSingleObject(c.unmapped, 10000) == WAIT_OBJECT_0; + c.first = raw_state(c.base + neighbour * page); + c.releaser = std::thread([&c] { // stable_call waits for memory.mutex until the window is released + Sleep(100); + SetEvent(c.release); + }); + } + c.last = raw_state(c.base + neighbour * page); + }, &c); + c.unmapper.join(); + c.releaser.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + check(c.opened, "window_reached", name); + check(c.first != MEM_COMMIT, "first_call_inside_the_window_not_committed", name); + check(c.calls == 2, "fn_ran_again_after_the_break", name); + check(c.last == MEM_COMMIT, "answer_after_the_break_committed", name); + shim.map(base, broken_page, nullptr); + shim.map(base + (broken_page + 1) * page, pages - broken_page - 1, nullptr); + shim.release(pages, tokens); + CloseHandle(c.unmapped); + CloseHandle(c.release); +} + +// Kernel I/O into or out of a page of the run: this program's ReadFile and WriteFile imports (wrapped by xmem.dll +// when it loads with the switch). Synchronous calls on a file opened without FILE_FLAG_OVERLAPPED. +constexpr DWORD io_bytes = 4096; + +struct TempFile { + char path[MAX_PATH] = {}; + explicit TempFile(const char* stem) + { + char dir[MAX_PATH]; + GetTempPathA(sizeof(dir), dir); + std::snprintf(path, sizeof(path), "%sx2w-run-break-%s-%lu.bin", dir, stem, GetCurrentProcessId()); + } + ~TempFile() { DeleteFileA(path); } + HANDLE open(DWORD access, DWORD disposition) const + { + return CreateFileA(path, access, 0, nullptr, disposition, FILE_ATTRIBUTE_NORMAL, nullptr); + } +}; + +// The file's bytes: the neighbour page's mark, then 0xa5. +void io_pattern(unsigned char* out) +{ + std::memset(out, 0xa5, io_bytes); + const std::uint32_t mark = 0x51000000u + neighbour; + std::memcpy(out, &mark, sizeof(mark)); +} + +bool read_file_into(unsigned char* target) +{ + TempFile file("read"); + unsigned char data[io_bytes]; + io_pattern(data); + HANDLE h = file.open(GENERIC_WRITE, CREATE_ALWAYS); + DWORD done = 0; + const bool written = h != INVALID_HANDLE_VALUE && WriteFile(h, data, io_bytes, &done, nullptr) && done == io_bytes; + if (h != INVALID_HANDLE_VALUE) CloseHandle(h); + if (!written) return false; + h = file.open(GENERIC_READ, OPEN_EXISTING); + if (h == INVALID_HANDLE_VALUE) return false; + done = 0; + const BOOL ok = ReadFile(h, target, io_bytes, &done, nullptr); + const DWORD error = ok ? 0 : GetLastError(); + LARGE_INTEGER position{}; + SetFilePointerEx(h, LARGE_INTEGER{}, &position, FILE_CURRENT); + CloseHandle(h); + std::printf("ReadFile into the run: ok=%d bytes=%lu error=%lu position=%lld\n", ok, done, error, position.QuadPart); + return ok && done == io_bytes && std::memcmp(target, data, io_bytes) == 0; +} + +bool write_file_from(unsigned char* target) +{ + TempFile file("write"); + HANDLE h = file.open(GENERIC_WRITE, CREATE_ALWAYS); + if (h == INVALID_HANDLE_VALUE) return false; + DWORD done = 0; + const BOOL ok = WriteFile(h, target, io_bytes, &done, nullptr); + const DWORD error = ok ? 0 : GetLastError(); + CloseHandle(h); + std::printf("WriteFile from the run: ok=%d bytes=%lu error=%lu\n", ok, done, error); + if (!ok || done != io_bytes) return false; + unsigned char data[io_bytes]; + h = file.open(GENERIC_READ, OPEN_EXISTING); + const bool read = h != INVALID_HANDLE_VALUE && ReadFile(h, data, io_bytes, &done, nullptr) && done == io_bytes; + if (h != INVALID_HANDLE_VALUE) CloseHandle(h); + return read && std::memcmp(data, target, io_bytes) == 0; +} + +// A read into a reserved page that is in no run fails at once, as without the wrapper: nothing waits for it. +void io_outside_runs() +{ + const char* const name = "io_outside_runs"; + auto* const reserved = static_cast(VirtualAlloc(nullptr, page, MEM_RESERVE, PAGE_NOACCESS)); + if (!check(reserved != nullptr, "reserve", name)) return; + TempFile file("outside"); + unsigned char data[io_bytes]; + io_pattern(data); + HANDLE h = file.open(GENERIC_WRITE | GENERIC_READ, CREATE_ALWAYS); + DWORD done = 0; + if (!check(h != INVALID_HANDLE_VALUE && WriteFile(h, data, io_bytes, &done, nullptr) && + SetFilePointer(h, 0, nullptr, FILE_BEGIN) == 0, "temp_file", name)) { + if (h != INVALID_HANDLE_VALUE) CloseHandle(h); + VirtualFree(reserved, 0, MEM_RELEASE); + return; + } + const ULONGLONG from = GetTickCount64(); + const BOOL ok = ReadFile(h, reserved, io_bytes, &done, nullptr); + const DWORD error = GetLastError(); + const ULONGLONG took = GetTickCount64() - from; + CloseHandle(h); + VirtualFree(reserved, 0, MEM_RELEASE); + std::printf("ReadFile into a reserved page outside the runs: ok=%d error=%lu %llu ms\n", ok, error, took); + check(!ok && error == ERROR_NOACCESS, "read_into_reserved_page_fails_with_ERROR_NOACCESS", name); + check(took < 1000, "read_into_reserved_page_fails_at_once", name); +} + +// Default mode: eight single-page views; the unmap of page 5 is held open while readers query page 2. +void default_case(const Shim& shim, unsigned char* base) +{ + const char* const name = "default"; + SIZE_T count = pages, tokens[pages] = {}; + if (!shim.allocate(0x20400000, &count, tokens) || count != pages || shim.map(base, pages, tokens) != base) { + check(false, "map", name); + return; + } + unsigned char* const target = base + neighbour * page; + MEMORY_BASIC_INFORMATION info{}; + check(VirtualQuery(target, &info, sizeof(info)) && info.RegionSize == page, "one_view_per_page", name); + char hold[64], event_name[96]; + std::snprintf(hold, sizeof(hold), "x2w-run-break-default-%lu", GetCurrentProcessId()); + std::snprintf(event_name, sizeof(event_name), "%s.unmapped", hold); + HANDLE unmapped = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.release", hold); + HANDLE release = CreateEventA(nullptr, TRUE, FALSE, event_name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", hold); + std::thread unmapper([&] { shim.map(base + broken_page * page, 1, nullptr); }); + check(WaitForSingleObject(unmapped, 10000) == WAIT_OBJECT_0, "window_reached", name); + std::atomic answered{0}; + DWORD stable = 0, xmem = 0; + bool writable = false; + std::thread reading([&] { + struct Query { unsigned char* target; DWORD state; } query{target, 0}; + shim.stable_call([](void* context) { + auto& q = *static_cast(context); + q.state = raw_state(q.target); + }, &query); + stable = query.state; + unsigned char buffer[64] = {}; + if (shim.query(GetCurrentProcess(), target, buffer)) std::memcpy(&xmem, buffer + 0x20, sizeof(xmem)); + writable = x2w_local::writable(target, 64); + answered = 1; + }); + for (int i = 0; i < 300 && !answered.load(); ++i) Sleep(10); + check(answered.load() == 1, "readers_answer_inside_the_unmap", name); + check(stable == MEM_COMMIT && xmem == MEM_COMMIT && writable, "answers_committed", name); + SetEvent(release); + reading.join(); + unmapper.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + shim.map(base, broken_page, nullptr); + shim.map(base + (broken_page + 1) * page, pages - broken_page - 1, nullptr); + shim.release(pages, tokens); + CloseHandle(unmapped); + CloseHandle(release); +} + +// Lazy commit: the output buffers lie in a mapped page whose slot is not committed until it is touched. +void lazy_case(const Shim& shim, unsigned char* base) +{ + const char* const name = "lazy"; + SIZE_T count = pages, tokens[pages] = {}, out_count = 1, out_token = 0; + unsigned char* const out = base + 32 * page; + if (!shim.allocate(0x20400000, &count, tokens) || count != pages || shim.map(base, pages, tokens) != base || + !shim.allocate(0x20400000, &out_count, &out_token) || shim.map(out, 1, &out_token) != out) { + check(false, "map", name); + return; + } + for (SIZE_T i = 0; i < pages; ++i) *reinterpret_cast(base + i * page) = 0x53000000u + static_cast(i); + if (!check(raw_state(out) != MEM_COMMIT, "output_slot_not_committed_yet", name)) return; + char hold[64], event_name[96]; + std::snprintf(hold, sizeof(hold), "x2w-run-break-lazy-%lu", GetCurrentProcessId()); + std::snprintf(event_name, sizeof(event_name), "%s.unmapped", hold); + HANDLE unmapped = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.release", hold); + HANDLE release = CreateEventA(nullptr, TRUE, FALSE, event_name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", hold); + std::thread unmapper([&] { shim.map(base + broken_page * page, 1, nullptr); }); + check(WaitForSingleObject(unmapped, 10000) == WAIT_OBJECT_0, "window_reached", name); + unsigned char* const target = base + neighbour * page; + BOOL xmem_ok = FALSE; + SIZE_T ex_bytes = 0; + auto* const ex_info = reinterpret_cast(out + 0x100); + std::atomic answered{0}; + std::thread xmem_reader([&] { + xmem_ok = shim.query(GetCurrentProcess(), target, out); + ++answered; + }); + std::thread ex_reader([&] { + ex_bytes = VirtualQueryEx(GetCurrentProcess(), target, ex_info, sizeof(*ex_info)); + ++answered; + }); + Sleep(300); + check(answered.load() == 0, "readers_wait_for_the_break", name); + SetEvent(release); + xmem_reader.join(); + ex_reader.join(); + unmapper.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + // The answers are the state after the break, read back from the slot they were written to. Measured under Wine: a + // slot committed lazily (through the slab) still reads as reserved in the title's view, and so does a page of the + // view mapped again after the break (its bytes are kept), so compare with a raw query taken now. + const DWORD after = raw_state(target); + DWORD xmem_state = 0; + std::memcpy(&xmem_state, out + 0x20, sizeof(xmem_state)); + std::printf("lazy: target 0x%lx after the break; XMemVirtualQuery %d 0x%lx; VirtualQueryEx %zu 0x%lx\n", + static_cast(after), xmem_ok, static_cast(xmem_state), + static_cast(ex_bytes), static_cast(ex_info->State)); + check(xmem_ok && xmem_state == after, "XMemVirtualQuery_answer_after_the_break_in_the_lazy_slot", name); + check(ex_bytes == sizeof(*ex_info) && ex_info->State == after, "VirtualQueryEx_answer_after_the_break_in_the_lazy_slot", name); + check(*reinterpret_cast(target) == 0x53000000u + neighbour, "neighbour_data_kept", name); + shim.map(out, 1, nullptr); + shim.release(1, &out_token); + shim.map(base, broken_page, nullptr); + shim.map(base + (broken_page + 1) * page, pages - broken_page - 1, nullptr); + shim.release(pages, tokens); + CloseHandle(unmapped); + CloseHandle(release); +} + +// Lazy commit and shared views: the ReadFile import goes through both wrappers. A read into a mapped slot that is not +// committed yet (no break around it) commits the slot first and succeeds, as with lazy commit alone. +void lazy_read_file(const Shim& shim, unsigned char* at) +{ + const char* const name = "lazy_read_file"; + SIZE_T count = 1, token = 0; + if (!check(shim.allocate(0x20400000, &count, &token) && shim.map(at, 1, &token) == at, "map", name)) return; + if (check(raw_state(at) != MEM_COMMIT, "slot_not_committed_yet", name)) { + TempFile file("lazy"); + unsigned char data[io_bytes]; + io_pattern(data); + HANDLE h = file.open(GENERIC_WRITE | GENERIC_READ, CREATE_ALWAYS); + DWORD done = 0; + const bool ready = h != INVALID_HANDLE_VALUE && WriteFile(h, data, io_bytes, &done, nullptr) && + SetFilePointer(h, 0, nullptr, FILE_BEGIN) == 0; + const BOOL ok = ready && ReadFile(h, at, io_bytes, &done, nullptr); + const DWORD error = ok ? 0 : GetLastError(); + if (h != INVALID_HANDLE_VALUE) CloseHandle(h); + std::printf("lazy: ReadFile into an uncommitted mapped slot: ok=%d error=%lu\n", ok, error); + check(ok && done == io_bytes && std::memcmp(at, data, io_bytes) == 0, "read_into_the_slot", name); + } + shim.map(at, 1, nullptr); + shim.release(1, &token); +} + +struct Events { + char name[64]; + HANDLE first, second; + Events(const char* stem, const char* a, const char* b) + { + std::snprintf(name, sizeof(name), "x2w-run-break-%s-%lu", stem, GetCurrentProcessId()); + char event_name[96]; + std::snprintf(event_name, sizeof(event_name), "%s.%s", name, a); + first = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.%s", name, b); + second = CreateEventA(nullptr, TRUE, FALSE, event_name); + } + ~Events() + { + CloseHandle(first); + CloseHandle(second); + } +}; + +// Break A: unmap page 7 of a run of eight; break B: unmap page 6 of what is left, [0, 7). The reader's page 2 is in +// both. hold_retry: the handler for the fault in break A reads the break only after A has ended. +void next_break_case(const Shim& shim, unsigned char* base, bool hold_retry) +{ + const char* const name = hold_retry ? "next_break" : "next_break_control"; + SIZE_T count = pages, tokens[pages] = {}; + if (!shim.allocate(0x20400000, &count, tokens) || count != pages || shim.map(base, pages, tokens) != base) { + check(false, "map_run", name); + return; + } + for (SIZE_T i = 0; i < pages; ++i) *reinterpret_cast(base + i * page) = 0x52000000u + static_cast(i); + unsigned char* const target = base + 2 * page; + Events window_a("a", "unmapped", "release"), window_b("b", "unmapped", "release"), retry("retry", "faulted", "go"); + HANDLE second_read = CreateEventA(nullptr, TRUE, FALSE, nullptr); + std::atomic reads{0}; + std::uint32_t first_value = 0, second_value = 0; + + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", window_a.name); + std::thread unmap_a([&] { shim.map(base + 7 * page, 1, nullptr); }); + const bool a_open = WaitForSingleObject(window_a.first, 10000) == WAIT_OBJECT_0; + check(a_open, "break_a_held", name); + if (hold_retry) SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", retry.name); + std::thread reader([&] { + first_value = *reinterpret_cast(target); // faults in break A + ++reads; + WaitForSingleObject(second_read, 10000); + second_value = *reinterpret_cast(target); // faults in break B + ++reads; + }); + if (hold_retry) { + check(WaitForSingleObject(retry.first, 10000) == WAIT_OBJECT_0, "handler_held_before_reading_the_break", name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", nullptr); + } else { + Sleep(100); // the handler reads break A while it is open, then waits for it + } + SetEvent(window_a.second); + unmap_a.join(); + check(raw_state(target) == MEM_COMMIT, "break_a_ended", name); + if (hold_retry) SetEvent(retry.second); // the handler now reads the generation after break A + for (int i = 0; i < 200 && reads.load() < 1; ++i) Sleep(10); + check(reads.load() == 1 && first_value == 0x52000002u, "first_fault_retried", name); + + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", window_b.name); + std::thread unmap_b([&] { shim.map(base + 6 * page, 1, nullptr); }); + const bool b_open = WaitForSingleObject(window_b.first, 10000) == WAIT_OBJECT_0; + check(b_open && raw_state(target) != MEM_COMMIT, "break_b_held_page_not_committed", name); + SetEvent(second_read); + Sleep(300); + check(reads.load() == 1, "second_fault_waits_for_break_b", name); + SetEvent(window_b.second); + unmap_b.join(); + reader.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + check(reads.load() == 2 && second_value == 0x52000002u, "second_fault_retried", name); + shim.map(base, 6, nullptr); + shim.release(pages, tokens); + CloseHandle(second_read); + if (!hold_retry) std::printf("next-break control: the handler read break A while it was open\n"); +} +// Break A takes apart run 1, break B (begun after A ended) run 2, a disjoint run. The handler for a fault in A is held +// (X2W_XMEM_TEST_HOLD_RETRY) until B is held open, so it reads the breaks while B is in progress: it must still find +// A and retry the fault. A handler that knew only the last break's ranges passes the fault on, and the process ends +// with an access violation. +void two_runs_case(const Shim& shim, unsigned char* base) +{ + const char* const name = "two_runs"; + unsigned char* const run1 = base; + unsigned char* const run2 = base + 16 * page; + SIZE_T count = 2 * pages, tokens[2 * pages] = {}; + if (!shim.allocate(0x20400000, &count, tokens) || count != 2 * pages || shim.map(run1, pages, tokens) != run1 || + shim.map(run2, pages, tokens + pages) != run2) { + check(false, "map_runs", name); + return; + } + for (SIZE_T i = 0; i < pages; ++i) { + *reinterpret_cast(run1 + i * page) = 0x54000000u + static_cast(i); + *reinterpret_cast(run2 + i * page) = 0x54100000u + static_cast(i); + } + unsigned char* const target = run1 + 2 * page; + Events window_a("two-a", "unmapped", "release"), window_b("two-b", "unmapped", "release"), retry("two-retry", "faulted", "go"); + std::atomic reads{0}; + std::uint32_t value = 0; + + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", window_a.name); + std::thread unmap_a([&] { shim.map(run1 + 7 * page, 1, nullptr); }); + check(WaitForSingleObject(window_a.first, 10000) == WAIT_OBJECT_0 && raw_state(target) != MEM_COMMIT, + "break_a_held_on_run_1", name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", retry.name); + std::thread reader([&] { + value = *reinterpret_cast(target); // faults in break A + ++reads; + }); + check(WaitForSingleObject(retry.first, 10000) == WAIT_OBJECT_0, "handler_held_before_reading_the_breaks", name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", nullptr); + SetEvent(window_a.second); + unmap_a.join(); + check(raw_state(target) == MEM_COMMIT, "break_a_ended", name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", window_b.name); + std::thread unmap_b([&] { shim.map(run2 + 7 * page, 1, nullptr); }); + check(WaitForSingleObject(window_b.first, 10000) == WAIT_OBJECT_0 && raw_state(run2 + 2 * page) != MEM_COMMIT, + "break_b_held_on_run_2", name); + SetEvent(retry.second); // the handler reads the breaks now, with B in progress + Sleep(100); + SetEvent(window_b.second); + unmap_b.join(); + reader.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + check(reads.load() == 1 && value == 0x54000002u, "fault_in_break_a_retried_during_break_b", name); + check(*reinterpret_cast(run2 + 2 * page) == 0x54100002u, "run_2_data_kept", name); + shim.map(run1, 7, nullptr); + shim.map(run2, 7, nullptr); + shim.release(2 * pages, tokens); +} + +// The owner's configuration (X2W_XMEM_PERMISSIVE=1, X2W_XMEM_GPU_MIRROR=1): one XMemMapPhysicalPages call joins the +// CPU run, then the same pages' GPU mirror run, under one memory.mutex hold; the two breaks follow each other at once. +// A fault on the CPU run in the first break, whose handler is held until the GPU break is held open, must be retried. +// The release event is auto-reset, so each of the call's two holds waits for a release of its own. +void mirror_case(const Shim& shim, unsigned char* cpu) +{ + const char* const name = "mirror"; + SetEnvironmentVariableA("X2W_XMEM_PERMISSIVE", "1"); + SetEnvironmentVariableA("X2W_XMEM_GPU_MIRROR", "1"); + auto* const gpu_view = static_cast(shim.virtual_alloc(nullptr, SIZE_T{16} << 30, 0x20402000, 3, 0x800 | PAGE_NOACCESS)); + SetEnvironmentVariableA("X2W_XMEM_GPU_MIRROR", nullptr); + unsigned char* const at = cpu + page; + SIZE_T count = pages + 1, tokens[pages + 1] = {}; + if (!check(gpu_view != nullptr, "gpu_reservation", name) || + !check(shim.allocate(0x280, &count, tokens) && count == pages + 1 && shim.map(at, pages, tokens) == at, "map_run", name)) { + SetEnvironmentVariableA("X2W_XMEM_PERMISSIVE", nullptr); + if (gpu_view) VirtualFree(gpu_view, 0, MEM_RELEASE); + return; + } + unsigned char* const twin = at - cpu + gpu_view; + for (SIZE_T i = 0; i < pages; ++i) *reinterpret_cast(at + i * page) = 0x55000000u + static_cast(i); + check(*reinterpret_cast(twin + 2 * page) == 0x55000002u, "gpu_twin_shows_the_cpu_page", name); + unsigned char* const target = at + 2 * page; + char hold[64], event_name[96]; + std::snprintf(hold, sizeof(hold), "x2w-run-break-mirror-%lu", GetCurrentProcessId()); + std::snprintf(event_name, sizeof(event_name), "%s.unmapped", hold); + HANDLE unmapped = CreateEventA(nullptr, TRUE, FALSE, event_name); + std::snprintf(event_name, sizeof(event_name), "%s.release", hold); + HANDLE release = CreateEventA(nullptr, FALSE, FALSE, event_name); + Events retry("mirror-retry", "faulted", "go"); + std::atomic reads{0}; + std::uint32_t value = 0; + bool mapped = false; + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", hold); + std::thread mapper([&] { mapped = shim.map(at + pages * page, 1, &tokens[pages]) == at + pages * page; }); + check(WaitForSingleObject(unmapped, 10000) == WAIT_OBJECT_0 && raw_state(target) != MEM_COMMIT, "cpu_merge_held", name); + ResetEvent(unmapped); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", retry.name); + std::thread reader([&] { + value = *reinterpret_cast(target); // faults in the CPU merge's break + ++reads; + }); + check(WaitForSingleObject(retry.first, 10000) == WAIT_OBJECT_0, "handler_held_before_reading_the_breaks", name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", nullptr); + SetEvent(release); // the CPU merge ends; the GPU merge begins and holds + check(WaitForSingleObject(unmapped, 10000) == WAIT_OBJECT_0 && raw_state(twin + 2 * page) != MEM_COMMIT && + raw_state(target) == MEM_COMMIT, "gpu_merge_held_after_the_cpu_merge", name); + SetEvent(retry.second); // the handler reads the breaks now, with the GPU merge in progress + Sleep(100); + SetEvent(release); + mapper.join(); + reader.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + check(mapped, "mapping_call_succeeded", name); + check(reads.load() == 1 && value == 0x55000002u, "fault_in_the_cpu_merge_retried_during_the_gpu_merge", name); + MEMORY_BASIC_INFORMATION info{}; + check(VirtualQuery(at, &info, sizeof(info)) && info.RegionSize == (pages + 1) * page && + VirtualQuery(twin, &info, sizeof(info)) && info.RegionSize == (pages + 1) * page, "both_views_joined", name); + shim.map(at, pages + 1, nullptr); + shim.release(pages + 1, tokens); + SetEnvironmentVariableA("X2W_XMEM_PERMISSIVE", nullptr); + VirtualFree(gpu_view, 0, MEM_RELEASE); + CloseHandle(unmapped); + CloseHandle(release); +} + +// Reads *address into value; false when the access violation reaches this frame (the handler passed it on). No C++ +// objects in the __try frame, and not inlined: inlined into the reader's lambda (clang-cl, under Wine), the code after +// the __except wrote through a null pointer. +__declspec(noinline) bool guarded_read(const volatile std::uint32_t* address, std::uint32_t* value) +{ + __try { + *value = *address; + return true; + } __except (GetExceptionCode() == EXCEPTION_ACCESS_VIOLATION ? EXCEPTION_EXECUTE_HANDLER : EXCEPTION_CONTINUE_SEARCH) { + return false; + } +} + +// The edge of the ring of recorded breaks (RemapWindow::kept, 64). Break A takes apart run 1; a fault in it is held +// before its handler reads the breaks (X2W_XMEM_TEST_HOLD_RETRY). A ends, then `later` breaks follow, each the unmap +// of a lone page mapped by a call of its own (one break per unmap call; the lone page joins no run). The k-th break +// after A is recorded in A's slot when k is a multiple of 64. With 63 later breaks A is still recorded and the fault +// is retried (the reader reads its page); with 64, A's slot holds the newest break, no recorded break holds the +// address, and the handler passes the fault on, which the reader's own __except catches. +void ring_edge_case(const Shim& shim, unsigned char* run1, SIZE_T later, bool retried) +{ + char name[32], stem[32]; + std::snprintf(name, sizeof(name), "ring_edge_%zu", later); + std::snprintf(stem, sizeof(stem), "ring-%zu", later); + unsigned char* const lone = run1 + 32 * page; + SIZE_T count = pages + 1, tokens[pages + 1] = {}; + if (!shim.allocate(0x20400000, &count, tokens) || count != pages + 1 || shim.map(run1, pages, tokens) != run1) { + check(false, "map_run", name); + return; + } + for (SIZE_T i = 0; i < pages; ++i) *reinterpret_cast(run1 + i * page) = 0x56000000u + static_cast(i); + unsigned char* const target = run1 + 2 * page; + Events window(stem, "unmapped", "release"), retry(stem, "faulted", "go"); + std::atomic outcome{0}; // 0: the reader has not finished; 1: it read its page; 2: the fault was passed on + std::uint32_t value = 0; + + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", window.name); + std::thread unmap_a([&] { shim.map(run1 + 7 * page, 1, nullptr); }); + check(WaitForSingleObject(window.first, 10000) == WAIT_OBJECT_0 && raw_state(target) != MEM_COMMIT, "break_a_held", name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", retry.name); + std::thread reader([&] { outcome = guarded_read(reinterpret_cast(target), &value) ? 1 : 2; }); + check(WaitForSingleObject(retry.first, 10000) == WAIT_OBJECT_0, "handler_held_before_reading_the_breaks", name); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_RETRY", nullptr); + SetEvent(window.second); + unmap_a.join(); + SetEnvironmentVariableA("X2W_XMEM_TEST_HOLD_WINDOW", nullptr); + check(raw_state(target) == MEM_COMMIT, "break_a_ended", name); + // The handler waits at most five seconds for "go" (hold_retry): the later breaks must all end inside that wait. + const ULONGLONG started = GetTickCount64(); + SIZE_T made = 0; + for (SIZE_T k = 0; k < later; ++k) { + if (shim.map(lone, 1, &tokens[pages]) != lone || raw_state(lone) != MEM_COMMIT) break; + if (shim.map(lone, 1, nullptr) != lone || raw_state(lone) == MEM_COMMIT) break; + ++made; + } + check(made == later, "later_breaks_made", name); + check(outcome.load() == 0 && GetTickCount64() - started < 4000, "handler_still_held_after_the_later_breaks", name); + SetEvent(retry.second); // the handler reads the breaks now + reader.join(); + if (retried) + check(outcome.load() == 1 && value == 0x56000002u, "fault_retried_with_break_a_still_recorded", name); + else + check(outcome.load() == 2, "fault_passed_on_with_break_a_evicted", name); + shim.map(run1, 7, nullptr); + shim.release(pages + 1, tokens); +} +} // namespace + +int main(int argc, char** argv) +{ + std::setvbuf(stdout, nullptr, _IONBF, 0); // a case that ends the process with an access violation keeps its lines + const bool control = argc > 2 && std::strcmp(argv[2], "control") == 0; + const bool next_break_control = argc > 2 && std::strcmp(argv[2], "next-break-control") == 0; + const bool default_mode = argc > 2 && std::strcmp(argv[2], "default") == 0; + const bool lazy = argc > 2 && std::strcmp(argv[2], "lazy") == 0; + const bool two_runs = argc > 2 && std::strcmp(argv[2], "two-runs") == 0; + const bool mirror = argc > 2 && std::strcmp(argv[2], "mirror") == 0; + const bool ring_edge = argc > 2 && std::strcmp(argv[2], "ring-edge") == 0; + if (argc < 2 || (argc > 2 && !control && !next_break_control && !default_mode && !lazy && !two_runs && !mirror && + !ring_edge)) { + std::printf("usage: xmem_run_break_readers_check " + "[control|next-break-control|default|lazy|two-runs|mirror|ring-edge]\n"); + return 2; + } + // The mode is read by the first mapping call; the VirtualQueryEx import is wrapped when xmem.dll loads. + SetEnvironmentVariableA("X2W_XMEM_SHARED_VIEWS", default_mode ? nullptr : "1"); + if (lazy) SetEnvironmentVariableA("X2W_XMEM_LAZY_COMMIT", "1"); + const HMODULE xmem = LoadLibraryA(argv[1]); + if (!xmem) { + std::printf("check_failed: load (error %lu)\n", GetLastError()); + return 1; + } + Shim shim{reinterpret_cast(GetProcAddress(xmem, "XMemVirtualAlloc")), + reinterpret_cast(GetProcAddress(xmem, "XMemAllocatePhysicalPages")), + reinterpret_cast(GetProcAddress(xmem, "XMemMapPhysicalPages")), + reinterpret_cast(GetProcAddress(xmem, "XMemFreePhysicalPages")), + reinterpret_cast(GetProcAddress(xmem, "XMemVirtualQuery")), + reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_stable_call"))}; + if (!shim.virtual_alloc || !shim.allocate || !shim.map || !shim.release || !shim.query || !shim.stable_call) { + std::printf("check_failed: exports\n"); + return 1; + } + auto* const base = static_cast(shim.virtual_alloc(nullptr, SIZE_T{16} << 30, 0x20402000, 0x21, PAGE_READWRITE)); + if (!base) { + std::printf("check_failed: startup reservation (error %lu)\n", GetLastError()); + return 1; + } + unsigned char* const at = base + page; + if (next_break_control || default_mode || lazy || two_runs || mirror || ring_edge) { + if (next_break_control) next_break_case(shim, at, false); + if (default_mode) default_case(shim, at); + if (lazy) { + lazy_case(shim, at); + lazy_read_file(shim, at + 40 * page); + } + if (two_runs) two_runs_case(shim, at); + if (mirror) mirror_case(shim, base); + if (ring_edge) { + ring_edge_case(shim, at, 63, true); + ring_edge_case(shim, at + 64 * page, 64, false); + } + VirtualFree(base, 0, MEM_RELEASE); + // The default mode's pass line, at the end and only with no failed check (ctest matches it). + if (default_mode && !failures) std::printf("default mode: readers answer inside an unmap\n"); + std::printf(failures ? "FAIL (%d)\n" : "PASS\n", failures); + return failures ? 1 : 0; + } + int index = 0; + if (!control) { + window_case(shim, at, index++, "x2w_xmem_stable_call", true, [&](unsigned char* target) { + struct Query { unsigned char* target; DWORD state; } query{target, 0}; + shim.stable_call([](void* context) { + auto& q = *static_cast(context); + q.state = raw_state(q.target); + }, &query); + return query.state == MEM_COMMIT; + }); + window_case(shim, at, index++, "XMemVirtualQuery", true, [&](unsigned char* target) { + unsigned char buffer[64] = {}; + DWORD state = 0; + if (shim.query(GetCurrentProcess(), target, buffer)) std::memcpy(&state, buffer + 0x20, sizeof(state)); + return state == MEM_COMMIT; + }); + window_case(shim, at, index++, "VirtualQueryEx_import", true, [&](unsigned char* target) { + MEMORY_BASIC_INFORMATION info{}; + return VirtualQueryEx(GetCurrentProcess(), target, &info, sizeof(info)) == sizeof(info) && info.State == MEM_COMMIT; + }); + window_case(shim, at, index++, "ReadFile_import", true, read_file_into); + window_case(shim, at, index++, "WriteFile_import", true, write_file_from); + io_outside_runs(); + } + // The header readers: waiting with the export, answering inside the window without it (control). + const bool waits = !control; + window_case(shim, at, index++, "x2w_local::writable", waits, [&](unsigned char* target) { + return x2w_local::writable(target, 64); + }); + window_case(shim, at, index++, "measure_placed_buffer", waits, [&](unsigned char* target) { + x2w_startup::PlacedBufferRange range; + return x2w_startup::measure_placed_buffer(target, 4096, range) && range.type == MEM_MAPPED && range.covered; + }); + window_case(shim, at, index++, "snapshot_samplers", waits, [&](unsigned char* target) { + const auto snapshot = x2w_startup::snapshot_samplers({reinterpret_cast(target), 4}, false); + return snapshot.count == 4 && snapshot.readable.count() == 4 && snapshot.words[0][0] == 0x51000000u + neighbour; + }); + if (!control) { + next_break_case(shim, at, true); + break_during_fn(shim, at); + } + VirtualFree(base, 0, MEM_RELEASE); + std::printf(failures ? "FAIL (%d)\n" : "PASS\n", failures); + return failures ? 1 : 0; +}