diff --git a/CMakePresets.json b/CMakePresets.json index 0008441a2a..a502c855a0 100644 --- a/CMakePresets.json +++ b/CMakePresets.json @@ -29,7 +29,11 @@ "d3d12_sdk_check", "era_heap_check", "xmem_shim", "offscreen_check", "cpu_fuzz_lifted", "cpu_fuzz_lifted_o2", "pe_map", "intake_candidate", "archive_gpu_reader", "archive_codec_gpu", "archive_texture_gpu_lifted", "startup_launch_probe", - "startup_indirect_dispatch", "startup_indirect_draw_indexed", "startup_present_readback_check" + "startup_indirect_dispatch", "startup_indirect_draw_indexed", "startup_present_readback_check", + "xmem_shim_test_controls", "startup_stub_xcrdapi", "startup_stub_xcrdapi_break_window_control", + "xmem_run_break_readers_check", "xmem_run_break_readers_control", "xmem_cross_call_merge_check", + "xmem_placeholder_split_check", "xmem_map_split_first_check", "startup_dstorage_break_window_check", + "xmem_page_runs_device_check", "linear_buffer_backing_check" ] }, { "name": "release", "configurePreset": "release" } @@ -42,7 +46,7 @@ "displayName": "Windows pull request smoke tests", "filter": { "include": { - "name": "^(desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key|startup_present_readback)$" + "name": "^(desktop_root_signature|era_heap_(allocation|failure)|xmem_shim_mapped_pages|cpu_aot_fuzz_smoke|cpu_archive_texture_gpu_warp|dual_uav_warp|spirv_.*_warp|static_exe_intake|descriptor_heap_paging(_swapped)?_warp|startup_launch|startup_tools_lint|startup_gfx2hlsl_cvt_off_f32_i4_controls|startup_gfx2hlsl_sad_hi_msad_controls|startup_indirect_(dispatch|count_split|draw(_indexed)?|mesh(_xmem_arguments(_skip_wait)?)?|counts_control)_warp|startup_indirect_mesh_lease_warp_dual(-trace(-disabled)?)?|startup_shader_cache_key|startup_present_readback|xmem_(run_break_readers|cross_call_merge|placeholder_split|map_split_first)(_[a-z_]+)?|startup_dstorage_break_window(_[a-z_]+)?|xmem_page_runs_device(_join)?_warp|linear_buffer_backing_share_warp)$" } } }, diff --git a/README.md b/README.md index c0b5dd147d..7a4cabdac6 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) · [page runs](docs/experiments/xmem-page-runs.md) | `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/xmem-page-runs.md b/docs/experiments/xmem-page-runs.md new file mode 100644 index 0000000000..148b3fb9b2 --- /dev/null +++ b/docs/experiments/xmem-page-runs.md @@ -0,0 +1,63 @@ +# XMem page runs: placeholder splits, joins and run breaks + +Refs [#2911](https://github.com/R0Y00/Xbox2Windows/pull/2911). The fixtures below cover the shim's mapping of +physical pages into XMem reservations with shared views (`X2W_XMEM_SHARED_VIEWS=1`). The results quoted here were +measured under Wine (Proton Experimental, November 2026) on Linux x64, with a clang-cl cross build and each CTest +entry's command run through Wine in one prefix. They are not Windows results. The D3D12 fixtures at the end have no +result there. + +## Placeholder split for queue slot 31 + +`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 in the test-controls build (`xmem_shim_test_controls`) with `X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1` and must fail. `xmem_placeholder_split_deployed` sets the same switch for the deployed `xmem_shim`, which ignores it, and must pass. `xmem_placeholder_split_partial` (test-controls build, shared views) maps a two-page view over a private allocation whose first page is reserved and whose second page is committed. The fallback checks every region the view covers, so it refuses the view and the committed page keeps its bytes. A check of the first region alone accepted the view, and Wine then released the allocation and the view replaced the committed page. Limit: the fallback cannot tell a reserved page of a private allocation made with `VirtualAlloc2(MEM_REPLACE_PLACEHOLDER)` from a placeholder, because Wine does not refuse the release for that kind of allocation. After the refused view, the batch retries each page on its own and releases the reserved first page, which cuts it out of the caller's allocation: under Wine the committed page's allocation then starts one page later. The fixture prints where that allocation starts and asserts only that the first page is still one reserved page at its own address. Where the OS reports the bit, the fallback is not used. The control, `xmem_placeholder_split_deployed` and `xmem_placeholder_split_partial` skip (77) where the OS reports the bit. Run `ctest --preset dev --no-tests=error -R '^xmem_placeholder_split' -V`. + +## Split before map + +`xmem_map_split_first` maps eight single pages with `XMemMapPhysicalPages`, each into the middle of the +reservation's placeholder. xmem splits first and maps once, so the eight pages take eight `MapViewOfFile3` attempts +and eight splits, and an exact placeholder left by an unmap is mapped without a split. `xmem_map_split_first_control` +runs the old map-first order in the test-controls build (`X2W_XMEM_TEST_MAP_FIRST=1`) and must measure 16 attempts. +`xmem_map_split_first_deployed` sets the same switch for the deployed `xmem_shim`, which ignores it, and must measure +8. Measured under Wine: 8, 16 and 8. Run `ctest --preset dev --no-tests=error -R '^xmem_map_split_first' -V`. + +## Joins across mapping calls + +With shared views, the pages of one call that are adjacent slots of one section share a view. A call joins the run +that ends at its address only with `X2W_XMEM_JOIN_CALLS=1`, which counts only with shared views on. It is off by +default; `tools/startup/run.sh` sets it, and `tools/startup/run.ps1 -LazyMemory` does not. `xmem_cross_call_merge` +checks the joined layout (32 single-page calls on consecutive slots give one view of 32 pages) and the cases around +it. `xmem_cross_call_merge_no_join` checks that the deployed shim with shared views and no join switch keeps a view +per call (32 views). `xmem_cross_call_merge_control` turns the merge off in the test-controls build +(`X2W_XMEM_TEST_NO_MERGE=1`) and must also show 32 views; `xmem_cross_call_merge_deployed` sets that switch for the +deployed shim, which ignores it and joins. All passed under Wine. Run +`ctest --preset dev --no-tests=error -R '^xmem_cross_call_merge' -V`. + +## Run breaks and the fault handler + +Unmapping a page of a shared view unmaps the whole view and maps its other pages again; a join and a slot 31 batch do +the same for the runs they change. `xmem_run_break_readers` holds that window open (the test-controls build's +`X2W_XMEM_TEST_HOLD_WINDOW`) and checks that each reader either waits for it or, for a pipe `ReadFile`, fails inside +it without being run again (under Wine with `ERROR_NOACCESS`, both queued messages kept). The access-violation +handler retries a fault on a page whose view was mapped inside a break, once per break and thread. +`xmem_run_break_readers_stamps` holds a fault's handler while 63, 64 and 200 later breaks run on another page; each +fault is retried (under Wine the later breaks took 3, 4 and 10 ms). In the same mode, a page made no-access faults +once on a run no break has mapped (passed on at once) and twice after a break mapped it (one retry), counted by a +first-chance handler of the test. Run `ctest --preset dev --no-tests=error -R '^xmem_run_break_readers' -V`. + +## DirectStorage copies into runs + +`startup_dstorage_break_window` submits a memory-source request into a page of a run while an unmap holds the run +apart: the request must not complete during the 1000 ms hold, then lands; its control, an XCRDAPI that judges the +destination with its own query, refuses inside the window. The copy takes xmem's mapping mutex only when the +destination or source overlaps a run: `startup_dstorage_break_window_plain` measures a `VirtualAlloc` destination +copied without it and a run destination with it, and `startup_dstorage_break_window_views_off` an XMem page +destination copied without it when shared views are off (`x2w_xmem_copy_counts`, test-controls build). +`startup_dstorage_break_window_outcomes` forces each copy error (`X2W_XMEM_TEST_COPY_ERROR`) and checks the outcome +XCRDAPI logs for it. All passed under Wine. Run +`ctest --preset dev --no-tests=error -R '^startup_dstorage_break_window' -V`. + +## D3D12 fixtures (not run here) + +`xmem_page_runs_device_warp`, `xmem_page_runs_device_join_warp` and `linear_buffer_backing_share_warp` check view +boundaries through D3D12 placed resources. They need D3D12 with WARP, which the Wine prefix above does not provide: +they fail there (`linear_buffer_backing_share_warp`: "WARP device not created"), so this note has no result for +them. diff --git a/docs/startup-runtime.md b/docs/startup-runtime.md index a1d62b6195..b8ceed83a6 100644 --- a/docs/startup-runtime.md +++ b/docs/startup-runtime.md @@ -1492,6 +1492,7 @@ ctest --preset dev --no-tests=error -R '^startup_trap_header(_prefix_control|_pr | `X2W_XMEM_STARTUP_BELOW_40=1` (`run.ps1 -StartupBelow40`) | startup compatibility configuration ([#1758](https://github.com/R0Y00/Xbox2Windows/issues/1758)): the large-page startup blocks with attribute `0x283` (null address, type `0x20003000`, protection `0x2004` or `0x2404`) are placed so that the whole block, last byte included, lies below 2^40. A block that does not fit there returns NULL with the Windows error and logs `x2w-xmem startup block below 2^40 refused:`; nothing is truncated or placed higher. Other shapes and explicit addresses keep their placement. See [Startup blocks below 2^40](experiments.md#startup-blocks-below-240) | | `X2W_XMEM_LAZY_COMMIT=1` | experimental ([#1199](https://github.com/R0Y00/Xbox2Windows/issues/1199)): a fresh physical-page slot is committed on its first CPU access instead of when its page is mapped. A vectored exception handler commits the slot. Writers that cannot fault one in (the main module's `ReadFile`, slot 133 placement, stand-in writes behind a commit check) call `x2w_xmem_commit_range` first. See [Mapped pages committed on first touch](experiments.md#mapped-pages-committed-on-first-touch) | | `X2W_XMEM_LAZY_STARTUP=1` (`run.ps1 -LazyMemory`, which also sets `X2W_XMEM_LAZY_COMMIT=1` and `X2W_XMEM_SHARED_VIEWS=1`) | experimental, with `X2W_XMEM_LAZY_COMMIT=1` ([#1199](https://github.com/R0Y00/Xbox2Windows/issues/1199)): the [startup commit profile](experiments.md#reserve-and-commit-startup-blocks) only reserves blocks of 32 MiB and up, and the same handler commits them 256 KiB at a time on first touch. Slot 133 commits a whole block (`x2w_xmem_commit_block`) before a GPU resource is placed in it. The main module's `VirtualFree` import drops released blocks. Blocks of 32 MiB and up placed below 2^40 by `X2W_XMEM_STARTUP_BELOW_40` are also reserved lazily. See [Startup blocks committed on first touch](experiments.md#startup-blocks-committed-on-first-touch) | +| `X2W_XMEM_JOIN_CALLS=1` (with `X2W_XMEM_SHARED_VIEWS=1`; `tools/startup/run.sh` sets both, `run.ps1 -LazyMemory` only `X2W_XMEM_SHARED_VIEWS`) | experimental: a mapping call whose pages continue the shared view that ends at its address joins that view instead of mapping a view of its own ([Physical pages in shared sections](#physical-pages-in-shared-sections)). Read once, with `X2W_XMEM_SHARED_VIEWS`, by the first mapping call; without shared views it does nothing | | `X2W_XMEM_GPU_MIRROR=1` | pairs a no-access graphics reservation with the read-write reservation of the same size made just before it, and maps every physical page into both (same section) | | `X2W_D3D12_PERMISSIVE=1` | wraps the device: recording command lists, console present, view tracking; on a runtime without shader model 6.6 (in-box Windows 10), root signatures with the heap-indexing flags (`0xC00`) are serialized again without them, and the copy kept for shader translation gets that call's bits back when `CreateRootSignature` receives the returned blob's own buffer (a copy of the bytes keeps the desktop flags; `d3d12_xs_shim_heap_indexing`). The retry runs only on runtimes that refuse the flags (before shader model 6.6); where the runtime accepts them, `d3d12_xs_shim_heap_indexing` reports a capability skip (77) | | `X2W_D3D12_RENDER=1` | draws through translated pipelines from `X2W_SHADER_CACHE` and forwards [single-record indirect Dispatch](experiments.md#gpu-written-indirect-dispatch-arguments), [DrawIndexed](experiments.md#gpu-written-indirect-indexed-draw-arguments), [Draw](experiments.md#gpu-written-indirect-draw-arguments), and [DispatchMesh](experiments.md#gpu-written-indirect-mesh-dispatch-arguments) for supported desktop pipelines and tracked placed buffers | @@ -3208,21 +3209,64 @@ 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. With `X2W_XMEM_JOIN_CALLS=1` as well (off by default; `tools/startup/run.sh` +sets it, `run.ps1 -LazyMemory` does not), 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. +that touches one of those pages in between takes an access violation. Each view mapped inside an +unmap, a join or a page batch keeps that one's id. A vectored handler retries the fault only when, +once the one in progress (if any) is over, the page is recorded, covered by a view, and that view +carries such an id, and the thread has not already retried that page for that id. A handler that +runs late, after any number of later unmaps or joins of other views (one call joins a CPU view and +then its GPU mirror), still finds the one that mapped the page again. Any other fault is passed on, +after at most one retry for each unmap or join that mapped the page's view. A fault with none in +progress or beginning or ending around a region query of the page, and no mapped view there, is +passed on without waiting for the mapping lock. 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 on a disk file 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. A call on a pipe, socket or console is not +run again. Under Wine an anonymous pipe read inside an unmap fails with `ERROR_NOACCESS` and leaves +its data queued (measured). Whether Windows consumes or sends any data in a call that fails this way +is unmeasured, and if it does, running the call again would lose or repeat that data. +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 | +| Views | one per page | one per run of adjacent pages of one call; with `X2W_XMEM_JOIN_CALLS=1` a call can also join the view that ends at its address | | 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/docs/wine.md b/docs/wine.md index 3864e71290..d7bf05c84f 100644 --- a/docs/wine.md +++ b/docs/wine.md @@ -57,6 +57,7 @@ set yourself stays, except `XDG_RUNTIME_DIR`, which it always unsets: |---|---| | The `run.ps1` set: `X2W_AUDIO_PERMISSIVE`, `X2W_D3D12_DEVICE_NOOP`, `X2W_D3D12_LIST_NOOP`, `X2W_D3D12_PERMISSIVE`, `X2W_XMEM_PERMISSIVE`, `X2W_RUNTIME_PROXY` (all `=1`) | The same stand-in behaviour as a Windows run. `run.sh` sets the variables behind `--render`, `--fake-user`, `--gpu-mirror` and `--host-cpu` as [Switches](startup-runtime.md#switches) lists them | | `X2W_XMEM_SHARED_VIEWS=1` | With one section and view per page, a start-up batch of about 100,000 pages took 42.9 s under Wine. With shared views it took 82 ms ([Physical pages in shared sections](startup-runtime.md#physical-pages-in-shared-sections)). Without it, the measured runs did not get past start-up | +| `X2W_XMEM_JOIN_CALLS=1` | Start-up maps nearly every page with a call of its own. With it, such a call joins the shared view that ends at its address instead of adding a view, and under Wine each map costs more the more views the process has ([Behaviour seen only under Wine](#behaviour-seen-only-under-wine)). It needs `X2W_XMEM_SHARED_VIEWS=1` | | `XDG_RUNTIME_DIR` unset | Wine then backs sections in `/tmp`, not on a small tmpfs ([Startup debugger under Wine](non-windows-hosts.md#startup-debugger-under-wine)). This also breaks audio; see the next section | | `PULSE_SERVER=unix:/run/user/$(id -u)/pulse/native` | Restores audio while `XDG_RUNTIME_DIR` stays unset. `run.sh` sets it only when that socket exists | | `WINEDLLOVERRIDES=d3d12,d3d12core,dxgi,d3d11=n`, `WINEFSYNC=1` | Wine's built-in D3D12 is not enough; the prefix holds vkd3d-proton and DXVK | 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/resident_pages.h b/src/startup_stubs/resident_pages.h new file mode 100644 index 0000000000..6cae74c59e --- /dev/null +++ b/src/startup_stubs/resident_pages.h @@ -0,0 +1,31 @@ +#pragma once +// Shared by XCRDAPI's destination check (src/startup_stubs/xcrdapi.cpp) and xmem's copy into a destination +// (x2w_xmem_copy_to_destination, src/xmem_mapped_pages.cpp). +#include +#include + +#include + +namespace x2w_local { +// True when every page of [start, end) is resident and plain read-write: valid in the working set, PAGE_READWRITE +// or PAGE_EXECUTE_READWRITE, no guard bit. One QueryWorkingSetEx per 512 pages, so the cost follows the +// destination's size, not the region's. Reads attributes only; no page is touched. +inline bool resident_read_write(std::uintptr_t start, std::uintptr_t end) noexcept +{ + PSAPI_WORKING_SET_EX_INFORMATION pages[512]; + std::uintptr_t page = start & ~std::uintptr_t{0xFFF}; + while (page < end) { + DWORD count = 0; + for (; count < 512 && page < end; ++count, page += 0x1000) pages[count].VirtualAddress = reinterpret_cast(page); + if (!QueryWorkingSetEx(GetCurrentProcess(), pages, count * sizeof(pages[0]))) return false; + for (DWORD i = 0; i < count; ++i) { + const auto& page_info = pages[i].VirtualAttributes; + const DWORD protect = static_cast(page_info.Win32Protection); + if (!page_info.Valid || page_info.Bad || (protect & PAGE_GUARD) || + ((protect & 0xFF) != PAGE_READWRITE && (protect & 0xFF) != PAGE_EXECUTE_READWRITE)) + return false; + } + } + return true; +} +} // namespace x2w_local 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..74c33c8061 100644 --- a/src/startup_stubs/xcrdapi.cpp +++ b/src/startup_stubs/xcrdapi.cpp @@ -10,6 +10,7 @@ #include "startup_stubs/trap.h" #include "startup_stubs/profile_zone.h" #include "startup_stubs/local_log.h" +#include "startup_stubs/resident_pages.h" #include "startup_stubs/inflate.h" #include "startup_stubs/dstorage_error_record.h" #include "startup_stubs/dstorage_file_read.h" @@ -175,55 +176,53 @@ static bool has_zlib_header(const unsigned char* bytes, std::size_t size) return true; } -// True when every page of [start, end) is resident and plain read-write: valid in the working set, PAGE_READWRITE -// or PAGE_EXECUTE_READWRITE, no guard bit. One QueryWorkingSetEx per 512 pages, so the cost follows the -// destination's size, not the region's. Reads attributes only; no page is touched. -static bool resident_read_write(std::uintptr_t start, std::uintptr_t end) -{ - PSAPI_WORKING_SET_EX_INFORMATION pages[512]; - std::uintptr_t page = start & ~std::uintptr_t{0xFFF}; - while (page < end) { - DWORD count = 0; - for (; count < 512 && page < end; ++count, page += 0x1000) pages[count].VirtualAddress = reinterpret_cast(page); - if (!QueryWorkingSetEx(GetCurrentProcess(), pages, count * sizeof(pages[0]))) return false; - for (DWORD i = 0; i < count; ++i) { - const auto& page_info = pages[i].VirtualAttributes; - const DWORD protect = static_cast(page_info.Win32Protection); - if (!page_info.Valid || page_info.Bad || (protect & PAGE_GUARD) || - ((protect & 0xFF) != PAGE_READWRITE && (protect & 0xFF) != PAGE_EXECUTE_READWRITE)) - return false; - } - } - return true; -} - // 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; + const auto start = reinterpret_cast(destination); + if (!destination || bytes > UINTPTR_MAX - start) return false; + x2w_local::commit_lazy(destination, bytes); + if (x2w_local::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 when +// either range overlaps one of its runs, 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); ERROR_INVALID_ADDRESS when +// the copy faulted (part of the destination may be written); ERROR_INVALID_PARAMETER for an invalid request. +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; +} + +// The outcome logged for a copy that copy_to_destination did not complete, by its error. text holds the last case. +static const char* copy_outcome(DWORD error, char (&text)[40]) +{ + switch (error) { + case ERROR_NOACCESS: return "destination not writable"; + case ERROR_INVALID_ADDRESS: return "copy faulted (part of the destination may be written)"; + case ERROR_INVALID_PARAMETER: return "invalid copy request"; + default: + std::snprintf(text, sizeof(text), "copy failed (error %lu)", static_cast(error)); + return text; } - return true; } // Return the exact queued requests that continue this stream in this submission, in queue order. @@ -756,6 +755,7 @@ void execute_request(Object* self, const unsigned char* request, const ULONG_PTR const unsigned page_offset = static_cast(*reinterpret_cast(request + 0x10) & 0xFFFF); const u64 known = 1 | (0xFull << 1) | (1ull << 21) | 0x400000; const char* outcome = "done"; + char copy_failure[40]; // copy_outcome's text for an error it does not name StorageFailure failure = StorageFailure::other; // the heartbeat's cause, if the request fails std::vector packed, output; const unsigned char* input = nullptr; @@ -943,11 +943,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 = copy_outcome(copied, copy_failure); + 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..de4dee155d 100644 --- a/src/xmem_mapped_pages.cpp +++ b/src/xmem_mapped_pages.cpp @@ -11,6 +11,7 @@ #include #include #include "startup_stubs/local_log.h" +#include "startup_stubs/resident_pages.h" #include "startup_stubs/profile_zone.h" #include @@ -57,7 +58,13 @@ struct PhysicalMemory { ULONG_PTR mirror_cpu = 0, mirror_gpu = 0; SIZE_T mirror_bytes = 0; std::set explicit_mirror_pages; - std::map runs; // OS views: base -> bytes + // OS views: base -> bytes, and the id of the run break inside which the view was mapped (0: mapped outside any + // break). retry_remapped_page reads the id; it never expires while the view lasts. + struct Run { + SIZE_T bytes = 0; + ULONG64 stamp = 0; + }; + std::map runs; // The slabs and their 64 KiB slots; released slots are reused lowest first, so that pages reused together // are adjacent slots again. x2w_xmem::SlabSlots slots{era_physical::page_bytes}; @@ -262,6 +269,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 +307,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 +377,60 @@ 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; +#ifdef X2W_XMEM_TEST_CONTROLS +// Test build only (x2w_xmem_alias_counts): views install_alias_view could not map in place inside an owned +// reservation, split by whether alias_placeholders refused the range or a placeholder release was tried. +volatile LONG64 alias_refusals, alias_splits; +#endif + +// 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. Test build only (X2W_XMEM_TEST_CONTROLS): X2W_XMEM_TEST_MAP_FIRST=1 skips the +// split-first step; the deployed build ignores it. // 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(); +#ifdef X2W_XMEM_TEST_CONTROLS + static const bool map_first = x2w_local::env_on("X2W_XMEM_TEST_MAP_FIRST"); +#else + constexpr bool map_first = false; +#endif 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; } @@ -394,8 +448,8 @@ bool map_view(ULONG_PTR address, const Backing& backing) } // Maps bytes of one section at address as a single view; falls back to one view per page when the -// range is not inside a single placeholder. -bool map_run(ULONG_PTR address, const Backing& backing, SIZE_T bytes, +// range is not inside a single placeholder. stamp: the run break in progress, or 0 (PhysicalMemory::Run). +bool map_run(ULONG_PTR address, const Backing& backing, SIZE_T bytes, ULONG64 stamp, std::vector>& made, ULONG_PTR& failed_address) { auto* target = reinterpret_cast(address); @@ -404,7 +458,7 @@ bool map_run(ULONG_PTR address, const Backing& backing, SIZE_T bytes, MEM_REPLACE_PLACEHOLDER, PAGE_READWRITE, nullptr, 0) != nullptr; }; if (map_split(target, bytes, map)) { - memory.runs[address] = bytes; + memory.runs[address] = {bytes, stamp}; made.emplace_back(address, bytes); return true; } @@ -417,7 +471,7 @@ bool map_run(ULONG_PTR address, const Backing& backing, SIZE_T bytes, failed_address = address + done; return false; } - memory.runs[address + done] = page_bytes; + memory.runs[address + done] = {page_bytes, stamp}; made.emplace_back(address + done, page_bytes); } return true; @@ -444,23 +498,33 @@ 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 do a +// cross-call merge (merge_with_previous) for the run it joins and a page batch (remap_alias_pages) for the runs it +// changes. A thread that touches one of those pages in between faults. Such a run break has a generation that is odd +// while it is in progress; the break's id is that odd value. Every view mapped inside a break records the id +// (PhysicalMemory::Run::stamp, under memory.mutex), so a fault handler that runs late, after any number of later +// breaks on other runs (a merge of the CPU view and then of its GPU mirror in one call, or the next calls), still +// finds the break that mapped the page again. struct RemapWindow { SRWLOCK lock = SRWLOCK_INIT; - std::vector> ranges; // the runs of the break in progress, or of the last one ULONG64 generation = 0; }; 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}; +// Set once, with shared views, when X2W_XMEM_JOIN_CALLS=1 is set as well (FaultRetry::ready): only then does a run +// mapped by a call of its own join the recorded run that ends at its address (merge_with_previous). +std::atomic joins_on{false}; -void begin_break(const std::map& broken) +// Caller holds memory.mutex. Returns the break's id, the stamp of the views mapped until end_break. +ULONG64 begin_break() { - 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; ReleaseSRWLockExclusive(&remap_window.lock); + return id; } void end_break() { @@ -471,12 +535,47 @@ 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; +ULONG64 break_generation() +{ + AcquireSRWLockShared(&remap_window.lock); + const ULONG64 value = remap_window.generation; + ReleaseSRWLockShared(&remap_window.lock); + return value; +} + +// 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: after the break in progress, if any, has finished (the +// mutex), the page is recorded, covered by a view, and in a run mapped inside a break (a nonzero Run::stamp); and +// this thread has not already retried this page for that stamp. Everything else is passed on, so a fault that is not +// the transient one is reported after at most one retry per break that mapped the page again. +// Faults that cannot be the transient one do not wait for memory.mutex, which a mapping call holds for all of its +// work: when no break is in progress or begins or ends around a region query of the page (the generation is even +// before and unchanged after) and the query shows no mapped view there, the fault is passed on at once. Outside +// breaks only a break takes away a view mapped inside one, so the check below would pass it on as well. Faults on +// lazily committed memory and other faults outside the runs take that path. LONG CALLBACK retry_remapped_page(EXCEPTION_POINTERS* e) { const EXCEPTION_RECORD* record = e->ExceptionRecord; @@ -484,26 +583,28 @@ 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; - AcquireSRWLockShared(&remap_window.lock); - const ULONG64 seen = remap_window.generation; - for (const auto& [base, size] : remap_window.ranges) - inside |= address - base < size; - 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 - 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; - bool mapped = false; + hold_retry(); + const ULONG64 before = break_generation(); + MEMORY_BASIC_INFORMATION info{}; + const bool mapped_now = VirtualQuery(reinterpret_cast(page), &info, sizeof(info)) == sizeof(info) && + info.State == MEM_COMMIT && info.Type == MEM_MAPPED; + if (!(before & 1) && break_generation() == before && !mapped_now) return EXCEPTION_CONTINUE_SEARCH; + // The break that last mapped the page's run, however many breaks on other runs came after it. A later break of + // the same run stamps it again, so a fault in that break is retried again. + ULONG64 stamp = 0; { const std::lock_guard guard(memory.mutex); // held by the mapping thread until its break is over - auto run = memory.runs.upper_bound(page); - mapped = memory.views.count(page) && run != memory.runs.begin() && page - std::prev(run)->first < std::prev(run)->second; + const auto run = memory.runs.upper_bound(page); + if (memory.views.count(page) && run != memory.runs.begin() && + page - std::prev(run)->first < std::prev(run)->second.bytes) + stamp = std::prev(run)->second.stamp; } - if (!mapped) return EXCEPTION_CONTINUE_SEARCH; + if (!stamp) return EXCEPTION_CONTINUE_SEARCH; + thread_local ULONG_PTR retried_page = 0; + thread_local ULONG64 retried_stamp = 0; + if (retried_page == page && retried_stamp == stamp) return EXCEPTION_CONTINUE_SEARCH; retried_page = page; - retried_break = break_id; + retried_stamp = stamp; return EXCEPTION_CONTINUE_EXECUTION; } struct MappingThread { @@ -513,7 +614,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 @@ -521,6 +624,9 @@ struct MappingThread { // place until the process ends, also across a host's FreeLibrary and LoadLibrary. Nothing is // waited for or torn down at DLL detach. If the handler cannot be registered or the module cannot // be pinned, the opt-in is refused and pages get a view each. +// +// X2W_XMEM_JOIN_CALLS=1 is read at the same time and only counts with shared views on: a mapping call may then join +// the run that ends at its address (merge_with_previous). Without it every call maps views of its own. struct FaultRetry { SRWLOCK lock = SRWLOCK_INIT; bool tried = false; @@ -535,6 +641,7 @@ struct FaultRetry { // Test build only: shared views without the handler, to show that a reader then faults. if (x2w_local::env_on("X2W_XMEM_NO_FAULT_RETRY")) { guaranteed = true; + joins_on.store(x2w_local::env_on("X2W_XMEM_JOIN_CALLS"), std::memory_order_release); ReleaseSRWLockExclusive(&lock); return true; } @@ -547,10 +654,15 @@ struct FaultRetry { AddVectoredExceptionHandler(1, retry_remapped_page)) { guaranteed = true; x2w_local::logf("x2w-xmem shared views are on (X2W_XMEM_SHARED_VIEWS): xmem.dll stays loaded until the process ends"); + if (x2w_local::env_on("X2W_XMEM_JOIN_CALLS")) { + joins_on.store(true, std::memory_order_release); + x2w_local::logf("x2w-xmem joins across mapping calls are on (X2W_XMEM_JOIN_CALLS)"); + } } else 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 +672,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 +704,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() @@ -628,7 +742,7 @@ void forget_page(ULONG_PTR address) // Maps every recorded page of [base, base + size) that has no view: neighbours on adjacent slots // together, one page at a time when a group is refused. A page that cannot be mapped is forgotten -// and counted. fail is true when the test control refuses this range. +// and counted. fail is true when the test control refuses this range. stamp: the break in progress. struct MapFailure { const char* stage = nullptr; ULONG_PTR address = 0; @@ -650,7 +764,7 @@ struct MapFailure { } }; -ULONG_PTR map_recorded(ULONG_PTR base, SIZE_T size, bool fail, MapFailure* failure) +ULONG_PTR map_recorded(ULONG_PTR base, SIZE_T size, ULONG64 stamp, bool fail, MapFailure* failure) { ULONG_PTR lost = 0; ULONG_PTR at = base; @@ -670,14 +784,14 @@ ULONG_PTR map_recorded(ULONG_PTR base, SIZE_T size, bool fail, MapFailure* failu } std::vector> made; ULONG_PTR failed_address; - if (fail || !map_run(at, head, bytes, made, failed_address)) { + if (fail || !map_run(at, head, bytes, stamp, made, failed_address)) { // map_run may have mapped some pages one at a time before it stopped; keep those. for (SIZE_T done = 0; done < bytes; done += page_bytes) { if (memory.runs.count(at + done)) continue; Backing one = head; one.offset += done; if (!fail && map_view(at + done, one)) { - memory.runs[at + done] = page_bytes; + memory.runs[at + done] = {page_bytes, stamp}; } else { if (failure) failure->record("restore-view", at + done, memory.views.at(at + done), @@ -692,6 +806,83 @@ ULONG_PTR map_recorded(ULONG_PTR base, SIZE_T size, bool fail, MapFailure* failu return lost; } +// Shared views with X2W_XMEM_JOIN_CALLS=1 only (joins_on). Startup maps nearly every page with a call of its own, +// and under Wine each map costs more the more views the process has. With the switch, 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 ULONG_PTR base = std::prev(next)->first; + const SIZE_T size = std::prev(next)->second.bytes; + 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; + const ULONG64 stamp = begin_break(); + 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, stamp}; + 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, stamp, 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 +927,19 @@ 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 with X2W_XMEM_JOIN_CALLS, and 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 bool whole_batch = first == batch.begin() && last == batch.end(); + const Merge merge = share_views && joins_on.load(std::memory_order_acquire) && whole_batch + ? 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, 0, 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) { @@ -765,10 +967,10 @@ BOOL map_pages_locked(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& auto run = memory.runs.upper_bound(address); if (run == memory.runs.begin()) continue; --run; - if (address - run->first < run->second) broken.insert(*run); + if (address - run->first < run->second.bytes) broken.emplace(run->first, run->second.bytes); } TestFault test; - begin_break(broken); + const ULONG64 stamp = begin_break(); const EndBreak end; DWORD error = ERROR_SUCCESS; std::vector> unmapped; @@ -792,7 +994,7 @@ BOOL map_pages_locked(ULONG_PTR count, const ULONG_PTR* tokens, const AddressAt& if (!refused && !unmapped.empty()) hold_window(); ULONG_PTR lost = 0; for (const auto& [base, size] : unmapped) - lost += map_recorded(base, size, refused ? test.stage == 3 && test.hit(3) : test.hit(2), failure); + lost += map_recorded(base, size, stamp, refused ? test.stage == 3 && test.hit(3) : test.hit(2), failure); if (!refused) coalesce_unused(batch); if (refused || lost) { x2w_local::logf("x2w-xmem unmap of %llu page(s) failed (error %lu): %s; %llu surviving page(s) could not be mapped " @@ -1129,31 +1331,91 @@ struct AliasEdit { }; using AliasPlan = std::map; -using ViewRuns = 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. Test build only (X2W_XMEM_TEST_CONTROLS): X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1 skips the +// second probe; the deployed build ignores it. +bool placeholder_fallback() +{ + static const bool fallback = [] { +#ifdef X2W_XMEM_TEST_CONTROLS + const bool skip_probe = x2w_local::env_on("X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK"); +#else + constexpr bool skip_probe = false; +#endif + 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 && !skip_probe) { + 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 for a reservation made by VirtualAlloc (placeholder_fallback), reserved + // regions may be offered. Every region the view covers must be reserved, not only the first one of each + // allocation: Wine (Proton Experimental, 2026-11) released a private allocation made in place of a placeholder + // (VirtualAlloc2 MEM_REPLACE_PLACEHOLDER) together with its committed second page, and the view then replaced + // that page (xmem_placeholder_split_partial). Limit: Wine does not refuse the release for that kind of + // allocation either, so its reserved pages are still offered, and releasing one cuts it out of the caller's + // allocation. + 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; const auto base = reinterpret_cast(info.AllocationBase); if (address - base >= info.RegionSize) return false; - address += info.RegionSize - (address - base); + const auto allocation_end = base + info.RegionSize; + if (!(info.Flags & placeholder_reservation)) { + if (!fallback) return false; + const auto stop = end < allocation_end ? end : allocation_end; + for (auto at = address; at < stop;) { + MEMORY_BASIC_INFORMATION region{}; + if (VirtualQuery(reinterpret_cast(at), ®ion, sizeof(region)) != sizeof(region) || + region.State != MEM_RESERVE || !region.RegionSize) + return false; + at = reinterpret_cast(region.BaseAddress) + region.RegionSize; + } + } + address = allocation_end; } return true; } // Both maps have the same node type. The node for each possible run base was reserved before // unmapping anything, so recording a successful OS call cannot fail for lack of C++ heap memory. -bool install_alias_view(ULONG_PTR address, const Backing& backing, SIZE_T bytes, +// stamp: the page batch's break (PhysicalMemory::Run). +bool install_alias_view(ULONG_PTR address, const Backing& backing, SIZE_T bytes, ULONG64 stamp, ViewRuns& nodes, X2WPageBatchStats& stats) { auto* target = reinterpret_cast(address); @@ -1164,8 +1426,13 @@ bool install_alias_view(ULONG_PTR address, const Backing& backing, SIZE_T bytes, if (!map()) { const DWORD original_error = GetLastError(); const auto reservation = owned_reservation(address); - if (reservation == memory.reservations.end() || - bytes > reservation->second - (address - reservation->first) || !alias_placeholders(address, bytes)) { + const bool inside = reservation != memory.reservations.end() && + bytes <= reservation->second - (address - reservation->first); + const bool accepted = inside && alias_placeholders(address, bytes); +#ifdef X2W_XMEM_TEST_CONTROLS + if (inside) InterlockedIncrement64(accepted ? &alias_splits : &alias_refusals); +#endif + if (!accepted) { SetLastError(original_error); return false; } @@ -1179,13 +1446,13 @@ bool install_alias_view(ULONG_PTR address, const Backing& backing, SIZE_T bytes, if (!map()) return false; } auto node = nodes.extract(address); - node.mapped() = bytes; + node.mapped() = {bytes, stamp}; memory.runs.insert(std::move(node)); ++stats.mapCalls; return true; } -DWORD install_alias_plan(AliasPlan& plan, ViewRuns& nodes, bool share_views, bool restoring, +DWORD install_alias_plan(AliasPlan& plan, ViewRuns& nodes, bool share_views, bool restoring, ULONG64 stamp, std::vector& made, X2WPageBatchStats& stats) { DWORD error = ERROR_SUCCESS; @@ -1205,7 +1472,7 @@ DWORD install_alias_plan(AliasPlan& plan, ViewRuns& nodes, bool share_views, boo const auto& next = memory.backings.at(token(end->second)); if (next.section != head.section || next.offset != head.offset + bytes) break; } - if (install_alias_view(address, head, bytes, nodes, stats)) { + if (install_alias_view(address, head, bytes, stamp, nodes, stats)) { made.push_back(address); for (auto page = it; page != end; ++page) page->second.actual = token(page->second); @@ -1216,7 +1483,7 @@ DWORD install_alias_plan(AliasPlan& plan, ViewRuns& nodes, bool share_views, boo // A grouped view may cross placeholder boundaries. Retry each page once. for (auto page = it; page != end; ++page) { if (install_alias_view(page->first, memory.backings.at(token(page->second)), - page_bytes, nodes, stats)) { + page_bytes, stamp, nodes, stats)) { made.push_back(page->first); page->second.actual = token(page->second); } else { @@ -1232,13 +1499,13 @@ DWORD install_alias_plan(AliasPlan& plan, ViewRuns& nodes, bool share_views, boo HRESULT remap_alias_pages(AliasPlan& plan, bool share_views, X2WPageBatchStats& stats) { - ViewRuns broken; + std::map broken; for (const auto& [address, edit] : plan) { if (!edit.old) continue; const auto run = memory.runs.upper_bound(address); - if (run == memory.runs.begin() || address - std::prev(run)->first >= std::prev(run)->second) + if (run == memory.runs.begin() || address - std::prev(run)->first >= std::prev(run)->second.bytes) return E_UNEXPECTED; - broken.insert(*std::prev(run)); + broken.emplace(std::prev(run)->first, std::prev(run)->second.bytes); } for (const auto& [base, size] : broken) { // Surviving neighbours of a shared view are part of the transaction as well. @@ -1254,7 +1521,7 @@ HRESULT remap_alias_pages(AliasPlan& plan, bool share_views, X2WPageBatchStats& std::vector made; made.reserve(plan.size()); for (const auto& [address, edit] : plan) { - run_nodes.emplace(address, page_bytes); + run_nodes.emplace(address, PhysicalMemory::Run{page_bytes, 0}); view_nodes.emplace(address, 0); } auto clear_run = [&](ULONG_PTR address, SIZE_T size) { @@ -1263,7 +1530,7 @@ HRESULT remap_alias_pages(AliasPlan& plan, bool share_views, X2WPageBatchStats& it->second.actual = 0; }; - begin_break(broken); + const ULONG64 stamp = begin_break(); const EndBreak end; DWORD error = ERROR_SUCCESS; for (const auto& [base, size] : broken) { @@ -1275,7 +1542,7 @@ HRESULT remap_alias_pages(AliasPlan& plan, bool share_views, X2WPageBatchStats& clear_run(base, size); } if (!error) - error = install_alias_plan(plan, run_nodes, share_views, false, made, stats); + error = install_alias_plan(plan, run_nodes, share_views, false, stamp, made, stats); bool restore_failed = false; if (error) { for (const auto address : made) { @@ -1284,11 +1551,11 @@ HRESULT remap_alias_pages(AliasPlan& plan, bool share_views, X2WPageBatchStats& continue; } auto run = memory.runs.extract(address); - clear_run(address, run.mapped()); + clear_run(address, run.mapped().bytes); run_nodes.insert(std::move(run)); } made.clear(); - if (install_alias_plan(plan, run_nodes, share_views, true, made, stats)) + if (install_alias_plan(plan, run_nodes, share_views, true, stamp, made, stats)) restore_failed = true; } // Publish the OS state, including any views left over if Windows refused rollback. @@ -1503,6 +1770,70 @@ 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; +} + +// 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; +} + +// Test export, counted in the test-controls build only: views X2WMapPageBatch could not map in place inside an +// owned reservation whose range alias_placeholders refused, and those for which it tried a placeholder release. +// The deployed build returns FALSE with ERROR_NOT_SUPPORTED. +extern "C" BOOL WINAPI x2w_xmem_alias_counts(ULONGLONG* refusals, ULONGLONG* splits) +{ +#ifdef X2W_XMEM_TEST_CONTROLS + if (!refusals || !splits) return FALSE; + *refusals = static_cast(alias_refusals); + *splits = static_cast(alias_splits); + return TRUE; +#else + (void)refusals; + (void)splits; + SetLastError(ERROR_NOT_SUPPORTED); + return FALSE; +#endif +} + // 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. @@ -1549,6 +1880,152 @@ 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; +#ifdef X2W_XMEM_TEST_CONTROLS +// Test build only (x2w_xmem_copy_counts): destination copies made under memory.mutex and without it. +volatile LONG64 locked_copies, unlocked_copies; +#endif + +// Whether [address, address + bytes) overlaps a recorded run. Caller holds memory.mutex. +bool overlaps_run(ULONG_PTR address, SIZE_T bytes) +{ + if (!bytes) return false; + const auto run = memory.runs.upper_bound(address); + if (run != memory.runs.begin() && address - std::prev(run)->first < std::prev(run)->second.bytes) return true; + return run != memory.runs.end() && run->first - address < bytes; +} + +// [destination, destination + capacity) committed and writable: resident read-write pages from their working-set +// attributes, any other page through the region walk (as XCRDAPI's destination check without xmem.dll). +bool destination_writable(void* destination, SIZE_T capacity) +{ + const auto start = reinterpret_cast(destination); + if (capacity && destination && capacity <= ~ULONG_PTR{0} - start && + x2w_local::resident_read_write(start, start + capacity)) + return true; + return x2w_local::committed_writable(destination, capacity); +} +} // 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, then the copy of bytes from data. 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, merge_with_previous), all under memory.mutex. With shared views on (shared_views_on), a short +// hold of that mutex first looks up whether either range overlaps a recorded run. If one does, the check and the +// copy run under the mutex, so neither can fall into that window and no such window can open while the copy runs. +// Otherwise, and always with shared views off (every page then has a view of its own, and no unmap takes a +// neighbour away), both run without the mutex, as in XCRDAPI without xmem.dll. A run can then appear over either +// range only through a mapping call on those addresses during the copy, which is the caller's race. Lazily mapped +// pages of both ranges are committed first, before any mutex: 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, or a destination page that +// stopped being writable during the copy; part of the destination may be written), or ERROR_INVALID_PARAMETER for +// more bytes than capacity or null data. +// Test build only: X2W_XMEM_TEST_COPY_ERROR= fails every copy with that error before anything is written +// (startup_dstorage_break_window_check outcomes: XCRDAPI's logged outcome per error). +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; + } +#ifdef X2W_XMEM_TEST_CONTROLS + char forced[16]; + if (GetEnvironmentVariableA("X2W_XMEM_TEST_COPY_ERROR", forced, sizeof(forced)) && forced[0]) { + SetLastError(static_cast(std::strtoul(forced, nullptr, 10))); + return FALSE; + } +#endif + 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; + bool in_runs = false; + if (shared_views_on.load(std::memory_order_acquire)) { + const std::lock_guard guard(memory.mutex); + in_runs = overlaps_run(start, capacity) || overlaps_run(reinterpret_cast(data), bytes); + } + if (!in_runs) { +#ifdef X2W_XMEM_TEST_CONTROLS + InterlockedIncrement64(&unlocked_copies); +#endif + if (!destination_writable(destination, capacity)) + error = ERROR_NOACCESS; + else if (bytes && !copy_guarded(destination, data, bytes)) + error = ERROR_INVALID_ADDRESS; + SetLastError(error); + return error == ERROR_SUCCESS; + } + double held_ms = 0; + bool longest = false, largest = false; + { + const MappingThread marker; + const std::lock_guard guard(memory.mutex); +#ifdef X2W_XMEM_TEST_CONTROLS + InterlockedIncrement64(&locked_copies); +#endif + LARGE_INTEGER frequency{}, begin{}, end{}; + QueryPerformanceFrequency(&frequency); + QueryPerformanceCounter(&begin); + if (!destination_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; +} + +// Test export, counted in the test-controls build only: destination copies (x2w_xmem_copy_to_destination) made under +// memory.mutex because a range overlapped a run, and those made without it. The deployed build returns FALSE with +// ERROR_NOT_SUPPORTED. +extern "C" BOOL WINAPI x2w_xmem_copy_counts(ULONGLONG* locked, ULONGLONG* unlocked) +{ +#ifdef X2W_XMEM_TEST_CONTROLS + if (!locked || !unlocked) return FALSE; + *locked = static_cast(locked_copies); + *unlocked = static_cast(unlocked_copies); + return TRUE; +#else + (void)locked; + (void)unlocked; + SetLastError(ERROR_NOT_SUPPORTED); + return FALSE; +#endif +} + // 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 +2133,131 @@ 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) on a disk file 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, outside the runs, or on a handle that +// is not a disk file, fails at once as before: a pipe, socket or console may have consumed or sent data in the failed +// call, so running it again could lose or repeat that data. Under Wine a pipe read that fails this way leaves its data +// queued; whether Windows consumes it is unmeasured. GetFileType is asked only on that failure path. +// 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; + +// 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 std::lock_guard guard(memory.mutex); + return overlaps_run(reinterpret_cast(buffer), bytes); +} + +template +BOOL io_outside_breaks(HANDLE file, 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 || + GetFileType(file) != FILE_TYPE_DISK || !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(file, 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(file, 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..5ff7b8500d 100644 --- a/src/xmem_shim.def +++ b/src/xmem_shim.def @@ -22,3 +22,8 @@ EXPORTS x2w_xmem_release_section @20 x2w_xmem_match_section @21 X2WMapPageBatch @22 + x2w_xmem_copy_to_destination @23 + x2w_xmem_copy_counts @24 + x2w_xmem_map_counts @25 + x2w_xmem_stable_call @26 + x2w_xmem_alias_counts @27 diff --git a/tests/cmake/xmem_page_runs.cmake b/tests/cmake/xmem_page_runs.cmake new file mode 100644 index 0000000000..fe8e94aa56 --- /dev/null +++ b/tests/cmake/xmem_page_runs.cmake @@ -0,0 +1,166 @@ +# XMem page-run fixtures (#2911): readers inside a run break, the cross-call merge of shared views, the slot 31 +# placeholder split, split-before-map inside a placeholder, and a DirectStorage destination inside a run break. +# 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 looks the page up 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; the program +# sets X2W_XMEM_JOIN_CALLS=1 for `mirror` only). +# stamps: a held fault whose break is followed by 63, 64 or 200 later breaks on another page is retried each time +# (the run keeps the stamp of the break that mapped it again); a fault that stays is passed on at once on a run no +# break mapped, and after one retry on a run a break mapped. +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_stamps COMMAND xmem_run_break_readers_check "$" stamps) +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_stamps 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, X2W_XMEM_JOIN_CALLS=1 set by the program): 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. no_join: the deployed shim with shared views and without X2W_XMEM_JOIN_CALLS keeps a view per call. +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) +add_test(NAME xmem_cross_call_merge_no_join COMMAND xmem_cross_call_merge_check "$" no-join) +set_tests_properties(xmem_cross_call_merge xmem_cross_call_merge_control xmem_cross_call_merge_deployed + xmem_cross_call_merge_default xmem_cross_call_merge_no_join 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") +set_tests_properties(xmem_cross_call_merge_no_join PROPERTIES + PASS_REGULAR_EXPRESSION "no-join: 32 views" FAIL_REGULAR_EXPRESSION "check_failed") +# Placed buffers at view boundaries (tests/xmem_page_runs_device_check.cpp, registered in CMakeLists.txt) with joins +# across mapping calls on: the order of the mapping calls keeps every boundary. +add_test(NAME xmem_page_runs_device_join_warp COMMAND xmem_page_runs_device_check warp join) +set_tests_properties(xmem_page_runs_device_join_warp PROPERTIES TIMEOUT 120) +# tests/xmem_page_runs_check.py expects one view per mapping call: an X2W_XMEM_JOIN_CALLS=1 inherited from the +# caller's environment must not reach it. +if(TEST xmem_shim_page_runs) + set_property(TEST xmem_shim_page_runs APPEND PROPERTY ENVIRONMENT "X2W_XMEM_JOIN_CALLS=") +endif() + +# Slot 31 placeholder split inside an XMem reservation. The control (test-controls build) 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). The check program sets each mode's test switch itself. +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 xmem_shim_test_controls) +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}" + PASS_REGULAR_EXPRESSION "FAIL: map two pool pages into the middle of the reservation" SKIP_RETURN_CODE 77 TIMEOUT 60) +# The deployed shim with X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1: the switch is ignored and the split succeeds. +add_test(NAME xmem_placeholder_split_deployed COMMAND xmem_placeholder_split_check "$" deployed) +set_tests_properties(xmem_placeholder_split_deployed PROPERTIES + ENVIRONMENT "${xmem_placeholder_env}" SKIP_RETURN_CODE 77 TIMEOUT 60) +# A two-page view over a reserved page and a committed page of one private allocation: the fallback checks every +# region of the view and refuses it (test-controls build: x2w_xmem_alias_counts), and the committed page keeps its +# bytes. The program turns shared views on for this mode. +add_test(NAME xmem_placeholder_split_partial COMMAND xmem_placeholder_split_check + "$" partial) +set_tests_properties(xmem_placeholder_split_partial PROPERTIES + ENVIRONMENT "${xmem_placeholder_env}" 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 xmem_shim_test_controls) +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 (test-controls build, X2W_XMEM_TEST_MAP_FIRST=1) 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}" + PASS_REGULAR_EXPRESSION "map-first control: maps=2N" TIMEOUT 60) +# The deployed shim with X2W_XMEM_TEST_MAP_FIRST=1: the switch is ignored, so the split-first counts hold. +add_test(NAME xmem_map_split_first_deployed COMMAND xmem_map_split_first_check "$" deployed) +set_tests_properties(xmem_map_split_first_deployed PROPERTIES TIMEOUT 60 ENVIRONMENT "${xmem_placeholder_env}") + +# 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) +# Which copies take xmem's mapping mutex (x2w_xmem_copy_counts): with shared views, a VirtualAlloc destination copies +# without it and one in a run with it (plain); with shared views off, an XMem page destination copies without it. +add_test(NAME startup_dstorage_break_window_plain COMMAND startup_dstorage_break_window_check + "$" "$" plain) +add_test(NAME startup_dstorage_break_window_views_off COMMAND startup_dstorage_break_window_check + "$" "$" views-off) +# XCRDAPI's logged outcome for each copy error, forced by the test-controls build (X2W_XMEM_TEST_COPY_ERROR). +add_test(NAME startup_dstorage_break_window_outcomes COMMAND startup_dstorage_break_window_check + "$" "$" outcomes) +set_tests_properties(startup_dstorage_break_window_plain startup_dstorage_break_window_views_off + startup_dstorage_break_window_outcomes 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") diff --git a/tests/linear_buffer_backing_check.cpp b/tests/linear_buffer_backing_check.cpp index a735c1ef8d..cadc63aace 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,14 @@ 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 that, with X2W_XMEM_JOIN_CALLS=1, 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 +376,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; @@ -1766,6 +1768,7 @@ int main(int argc, char** argv) SetEnvironmentVariableW(L"X2W_D3D12_LIST_NOOP", L"1"); SetEnvironmentVariableW(L"X2W_D3D12_RENDER", L"1"); SetEnvironmentVariableW(L"X2W_XMEM_SHARED_VIEWS", L"1"); + SetEnvironmentVariableW(L"X2W_XMEM_JOIN_CALLS", nullptr); // no joins across mapping calls (the default) SetEnvironmentVariableW(L"X2W_D3D12_LINEAR_BUFFERS", path == Path::default_backing ? nullptr : path == Path::copy || path == Path::untracked || path == Path::stale || path == Path::contention || path == Path::lease ? L"copy" : L"1"); diff --git a/tests/startup_dstorage_break_window_check.cpp b/tests/startup_dstorage_break_window_check.cpp new file mode 100644 index 0000000000..9fc6467d43 --- /dev/null +++ b/tests/startup_dstorage_break_window_check.cpp @@ -0,0 +1,358 @@ +// 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 +// [plain|views-off|outcomes] +// 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 +// tests/cmake/xmem_page_runs.cmake). +// `plain` and `views-off` instead check which copies take xmem's mapping mutex (x2w_xmem_copy_counts): with shared +// views, a request into a VirtualAlloc destination copies without it and one into the run with it; with +// X2W_XMEM_SHARED_VIEWS unset (`views-off`), a request into an XMem page copies without it as well. +// `outcomes` forces each copy error in turn (the test-controls build's X2W_XMEM_TEST_COPY_ERROR) and checks the +// outcome XCRDAPI logs for the request: the DLLs log to the standard error handle, which this mode points at a +// temporary file. +#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*); +using CopyCountsFn = BOOL(WINAPI*)(ULONGLONG*, ULONGLONG*); + +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; +} + +// One request per row; the change of xmem's copy counts across it names the path the copy took. +int copy_rows(HMODULE xmem, unsigned char* run_page, bool views_off) +{ + const auto counts = reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_copy_counts")); + ULONGLONG locked = 0, unlocked = 0; + if (!counts || !counts(&locked, &unlocked)) { + std::printf("FAIL setup: x2w_xmem_copy_counts (needs the test-controls build)\n"); + return 1; + } + const auto row = [&](const char* name, unsigned char* destination, ULONGLONG want_locked, ULONGLONG want_unlocked) { + ULONGLONG locked0 = 0, unlocked0 = 0, locked1 = 0, unlocked1 = 0; + counts(&locked0, &unlocked0); + std::memset(destination, 0xAA, bytes); + long hr = -1; + const bool done = completed_within(submit(destination, bytes, bytes), 5000, hr); + counts(&locked1, &unlocked1); + std::printf("%s: completed %d hr 0x%08lx; copies under the mapping mutex %llu, without it %llu\n", name, done, + static_cast(hr), locked1 - locked0, unlocked1 - unlocked0); + if (!done || hr != 0 || std::memcmp(destination, source, bytes) != 0) fail(name, "the request did not land"); + else if (locked1 - locked0 != want_locked || unlocked1 - unlocked0 != want_unlocked) fail(name, "wrong copy path"); + else std::printf("ok: %s\n", name); + }; + if (views_off) { + row("views off, XMem page destination", run_page, 0, 1); + } else { + auto* plain = static_cast(VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (!plain) { + fail("plain destination", "VirtualAlloc"); + } else { + row("plain destination", plain, 0, 1); + VirtualFree(plain, 0, MEM_RELEASE); + } + row("run destination", run_page, 1, 0); + } + if (failures) return 1; + std::printf("dstorage copy paths: %s\n", views_off ? "views off: no mutex" : "the mutex only for the run"); + return 0; +} + +// Waits up to two seconds for text to appear in the log file (the request's line follows its completion). +bool logged(HANDLE log, const char* text) +{ + static char all[1 << 16]; + for (int waited = 0; waited <= 2000; waited += 20) { + DWORD size = 0; + SetFilePointer(log, 0, nullptr, FILE_BEGIN); + if (ReadFile(log, all, sizeof(all) - 1, &size, nullptr)) { + all[size] = 0; + if (std::strstr(all, text)) return true; + } + Sleep(20); + } + return false; +} + +int outcome_rows() +{ + char dir[MAX_PATH], path[MAX_PATH]; + GetTempPathA(sizeof(dir), dir); + std::snprintf(path, sizeof(path), "%sx2w-dstorage-outcomes-%lu.log", dir, GetCurrentProcessId()); + const HANDLE log = CreateFileA(path, GENERIC_READ | GENERIC_WRITE, FILE_SHARE_READ | FILE_SHARE_WRITE, nullptr, + CREATE_ALWAYS, FILE_ATTRIBUTE_TEMPORARY | FILE_FLAG_DELETE_ON_CLOSE, nullptr); + auto* plain = static_cast(VirtualAlloc(nullptr, bytes, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE)); + if (log == INVALID_HANDLE_VALUE || !plain) { + std::printf("FAIL setup: log file or destination\n"); + return 1; + } + const HANDLE saved = GetStdHandle(STD_ERROR_HANDLE); + SetStdHandle(STD_ERROR_HANDLE, log); + const struct { + DWORD error; + const char* text; + } rows[] = { + {ERROR_NOACCESS, "-> destination not writable"}, + {ERROR_INVALID_ADDRESS, "-> copy faulted (part of the destination may be written)"}, + {ERROR_INVALID_PARAMETER, "-> invalid copy request"}, + {ERROR_GEN_FAILURE, "-> copy failed (error 31)"}, + }; + for (const auto& row : rows) { + char code[16]; + std::snprintf(code, sizeof(code), "%lu", row.error); + SetEnvironmentVariableA("X2W_XMEM_TEST_COPY_ERROR", code); + std::memset(plain, 0xAA, bytes); + long hr = 0; + const bool done = completed_within(submit(plain, bytes, bytes), 5000, hr); + SetEnvironmentVariableA("X2W_XMEM_TEST_COPY_ERROR", nullptr); + const bool found = logged(log, row.text); + std::printf("error %lu: completed %d hr 0x%08lx, logged \"%s\" %d\n", row.error, done, + static_cast(hr), row.text, found); + if (!done || hr == 0) fail(row.text, "the request did not fail"); + else if (!filled(plain, 0xAA, bytes)) fail(row.text, "bytes were written"); + else if (!found) fail(row.text, "outcome not logged"); + else std::printf("ok: error %lu logged %s\n", row.error, row.text); + } + SetStdHandle(STD_ERROR_HANDLE, saved); + CloseHandle(log); + VirtualFree(plain, 0, MEM_RELEASE); + if (failures) return 1; + std::printf("dstorage outcomes: one text per copy error\n"); + return 0; +} +} // namespace + +int main(int argc, char** argv) +{ + const bool plain_mode = argc == 4 && std::strcmp(argv[3], "plain") == 0; + const bool views_off = argc == 4 && std::strcmp(argv[3], "views-off") == 0; + const bool outcomes = argc == 4 && std::strcmp(argv[3], "outcomes") == 0; + if (argc != 3 && !plain_mode && !views_off && !outcomes) { + std::printf("usage: startup_dstorage_break_window_check " + "[plain|views-off|outcomes]\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", views_off ? nullptr : "1"); + SetEnvironmentVariableA("X2W_XMEM_JOIN_CALLS", nullptr); // the run is mapped by one call; no join is needed + 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); + if (outcomes) return outcome_rows(); + + // 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; + } + if (plain_mode || views_off) return copy_rows(xmem, base + 2 * page, views_off); + 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/startup_run_sh_check.py b/tests/startup_run_sh_check.py index beab30d418..b7a0b8e0f9 100644 --- a/tests/startup_run_sh_check.py +++ b/tests/startup_run_sh_check.py @@ -28,8 +28,8 @@ CHECKED = PERMISSIVE + [ "X2W_FAKE_USER", "X2W_XMEM_GPU_MIRROR", "X2W_HOST_CPU", "X2W_XMEM_STARTUP_BELOW_40", "X2W_HIDE_TITLE_WINDOW", "X2W_D3D12_RENDER", "X2W_DRAW_NULL_IDENTITY", "X2W_SHADER_CACHE", "X2W_TITLE_ID", "X2W_STORAGE_MB", - "X2W_STORAGE_PATH", "X2W_INPUT_SCRIPT", "X2W_XMEM_SHARED_VIEWS", "WINEDLLOVERRIDES", "WINEFSYNC", "WINEDEBUG", - "WINEPREFIX", "XDG_RUNTIME_DIR", "PULSE_SERVER", "X2W_FXC"] + "X2W_STORAGE_PATH", "X2W_INPUT_SCRIPT", "X2W_XMEM_SHARED_VIEWS", "X2W_XMEM_JOIN_CALLS", "WINEDLLOVERRIDES", + "WINEFSYNC", "WINEDEBUG", "WINEPREFIX", "XDG_RUNTIME_DIR", "PULSE_SERVER", "X2W_FXC"] GAME_OVERRIDES = "d3d12,d3d12core,dxgi,d3d11=n" # docs/wine.md FAKE_USER_WARNING = ("WARNING: Without --fake-user, user API calls go to the host gaming runtime " "(docs/startup-runtime.md).") @@ -272,7 +272,7 @@ def run_case(script, code, work, switches=(), passed=(), env_extra=None, drive_d found.append(f"{label}: the debugger received {got}, expected {want}") seen = read_json(startup / "env.json") or {} expected = {name: "1" for name in PERMISSIVE} - expected.update(X2W_XMEM_SHARED_VIEWS="1", X2W_TITLE_ID="X2WTEST", X2W_STORAGE_MB="123", + expected.update(X2W_XMEM_SHARED_VIEWS="1", X2W_XMEM_JOIN_CALLS="1", X2W_TITLE_ID="X2WTEST", X2W_STORAGE_MB="123", WINEDLLOVERRIDES=GAME_OVERRIDES, WINEFSYNC="1", WINEDEBUG="-all", WINEPREFIX=str(prefix)) if translate: expected.update(X2W_D3D12_RENDER="1", X2W_DRAW_NULL_IDENTITY="1", X2W_SHADER_CACHE=win(root / "cache"), @@ -384,6 +384,7 @@ def mutants_of(script): "no FakeUser warning": replace(script, ' echo "WARNING: Without --fake-user', ' : "WARNING: Without --fake-user'), "short DLL list": replace(script, " xg_xs GameInput; do", " xg_xs; do"), "no shared views": drop_line(script, "export X2W_XMEM_SHARED_VIEWS="), + "no join calls": drop_line(script, "export X2W_XMEM_JOIN_CALLS="), "watcher without --render": replace(script, 'if [ -n "$translate" ] && [ -n "$render" ]; then', 'if [ -n "$translate" ]; then'), "config not read": replace(script, 'if [ -f "$config" ]; then', "if false; then"), diff --git a/tests/xmem_cross_call_merge_check.cpp b/tests/xmem_cross_call_merge_check.cpp new file mode 100644 index 0000000000..981608bb05 --- /dev/null +++ b/tests/xmem_cross_call_merge_check.cpp @@ -0,0 +1,470 @@ +// Cross-call merge of shared views (X2W_XMEM_SHARED_VIEWS=1 and X2W_XMEM_JOIN_CALLS=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 (each sets X2W_XMEM_SHARED_VIEWS and X2W_XMEM_JOIN_CALLS itself; JOIN_CALLS=1 in every mode but no-join): +// 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; the join +// switch alone does nothing. +// no-join (deployed xmem.dll, X2W_XMEM_JOIN_CALLS unset) single-page calls keep a view each: joins are opt-in. +// Prints "no-join: 32 views". +// 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): a table of "timing:" lines, one row per R from 16 to 4096. +// The pass line of control, deployed, default and no-join 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|no-join|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; one row per R): 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, no_join = std::strcmp(mode, "no-join") == 0; + if (!all && !control && !deployed && !plain && !timed && !no_join) { + std::printf("usage: xmem_cross_call_merge_check check|control|deployed|default|no-join|timing\n"); + return 2; + } + // The mode is read by the first mapping call. + SetEnvironmentVariableA("X2W_XMEM_SHARED_VIEWS", plain ? nullptr : "1"); + SetEnvironmentVariableA("X2W_XMEM_JOIN_CALLS", no_join ? 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 (no_join && token) token = "no-join: 32 views"; + 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..f2c6e56ec3 --- /dev/null +++ b/tests/xmem_map_split_first_check.cpp @@ -0,0 +1,101 @@ +// 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 test-controls build (X2W_XMEM_TEST_CONTROLS) with +// X2W_XMEM_TEST_MAP_FIRST=1: the old order takes 2N map attempts and +// prints "map-first control: maps=2N" +// xmem_map_split_first_check deployed deployed build with X2W_XMEM_TEST_MAP_FIRST=1: the build ignores +// the switch, so the checks of the first mode pass +// Each mode sets or clears X2W_XMEM_TEST_MAP_FIRST itself, so an inherited value cannot change the result. +#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; + const bool deployed = argc == 3 && std::wcscmp(argv[2], L"deployed") == 0; + if (argc != 2 && !control && !deployed) return 2; + // xmem reads the switch on first use and keeps the value; set it before any map. + SetEnvironmentVariableW(L"X2W_XMEM_TEST_MAP_FIRST", control || deployed ? L"1" : nullptr); + 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"); + if (deployed) std::puts("deployed build: X2W_XMEM_TEST_MAP_FIRST=1 was ignored"); + return 0; +} diff --git a/tests/xmem_page_runs_device_check.cpp b/tests/xmem_page_runs_device_check.cpp index e89264236e..16071992de 100644 --- a/tests/xmem_page_runs_device_check.cpp +++ b/tests/xmem_page_runs_device_check.cpp @@ -2,8 +2,10 @@ // Adjacent pages of one mapping call share a view, so a buffer can lie inside one view or across // two: two mapping calls next to each other, the boundary between two backing sections inside one // call, or pages that each have a view of their own. The device wrapper's placed-resource entry -// (slot 133) must accept all of them alike and leave the memory as it was. -// usage: xmem_page_runs_device_check warp|hardware +// (slot 133) must accept all of them alike and leave the memory as it was. With `join`, X2W_XMEM_JOIN_CALLS=1 as +// well: a mapping call may then join the view that ends at its address, and the mapping order below keeps every +// boundary in place all the same. Without it the switch is cleared. +// usage: xmem_page_runs_device_check warp|hardware [join] #include "xmem_test_device.h" #include @@ -76,11 +78,13 @@ void place(const char* name, ID3D12Device* wrapper, unsigned char* boundary, int int main(int argc, char** argv) { - if (argc != 2) return 1; + if (argc != 2 && !(argc == 3 && std::strcmp(argv[2], "join") == 0)) return 1; const bool warp = std::strcmp(argv[1], "warp") == 0; + const bool join = argc == 3; bool unmatched = false; SetEnvironmentVariableW(L"X2W_D3D12_PERMISSIVE", L"1"); SetEnvironmentVariableW(L"X2W_XMEM_SHARED_VIEWS", L"1"); // the mode under test; read by the first mapping call + SetEnvironmentVariableW(L"X2W_XMEM_JOIN_CALLS", join ? L"1" : nullptr); auto wrapper = create_device(warp, unmatched, create_wrapper); if (!wrapper) return warp || unmatched ? 1 : 77; @@ -88,11 +92,15 @@ 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: with + // X2W_XMEM_JOIN_CALLS=1 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 +115,20 @@ 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. + // Pages mapped one call at a time get a view each. They are mapped from high to low addresses: with + // X2W_XMEM_JOIN_CALLS=1 no call then has an 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..e1ce8d7dae --- /dev/null +++ b/tests/xmem_placeholder_split_check.cpp @@ -0,0 +1,189 @@ +// 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 in the test-controls build (X2W_XMEM_TEST_CONTROLS) +// with X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1; CTest expects the +// split step to fail +// xmem_placeholder_split_check deployed the same checks in the deployed build with the same switch, which +// that build ignores, so they pass +// xmem_placeholder_split_check partial test-controls build with shared views: a two-page view over a +// private reservation whose second page is committed is refused +// by the region walk (x2w_xmem_alias_counts), and the committed +// page keeps its bytes; prints where its allocation starts after +// the batch (the limit in alias_placeholders) +// control, deployed and partial exit 77 where the OS reports the bit, because there the fallback is never used. Each +// mode sets or clears X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK itself, so an inherited value cannot change the result. +#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*); +using AliasCounts = 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; +} + +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; +} + +// Where the region's allocation starts, in pages from `at` (negative: before it). +long long base_pages(const MEMORY_BASIC_INFORMATION& info, const BYTE* at) +{ + return (static_cast(info.AllocationBase) - at) / static_cast(page_bytes); +} + +// partial: two pages of the reservation become a private reservation whose second page is committed and tagged. Its +// first region is reserved, so a check of that region alone would accept the whole two-page view. +int partial_case(HMODULE xmem, BYTE* pool, decltype(&X2WMapPageBatch) batch_map) +{ + const auto counts = reinterpret_cast(GetProcAddress(xmem, "x2w_xmem_alias_counts")); + ULONGLONG refusals0 = 0, splits0 = 0, refusals1 = 0, splits1 = 0; + if (!require(counts && counts(&refusals0, &splits0), "read the alias counts (test-controls build)")) return 1; + BYTE* const piece = pool + 192 * page_bytes; + if (!require(VirtualFree(piece, 2 * page_bytes, MEM_RELEASE | MEM_PRESERVE_PLACEHOLDER), "split out two pages") || + !require(VirtualAlloc2(GetCurrentProcess(), piece, 2 * page_bytes, MEM_RESERVE | MEM_REPLACE_PLACEHOLDER, + PAGE_READWRITE, nullptr, 0) == piece, "reserve the two pages privately") || + !require(VirtualAlloc(piece + page_bytes, page_bytes, MEM_COMMIT, PAGE_READWRITE) == piece + page_bytes, + "commit the second page")) + return 1; + std::memset(piece + page_bytes, 0x7a, page_bytes); + const MEMORY_BASIC_INFORMATION before = query(piece + page_bytes); + if (!require(before.AllocationBase == piece, "the two pages are one allocation")) return 1; + const X2WPageRange two{0, 1, 2}; + const X2WPageBatch onto_partial{reinterpret_cast(piece), 1, &two}; + const HRESULT hr = batch_map(1, &onto_partial, reinterpret_cast(pool), pool_pages, 0, nullptr); + if (!require(counts(&refusals1, &splits1), "read the alias counts")) return 1; + const MEMORY_BASIC_INFORMATION first = query(piece), second = query(piece + page_bytes); + std::printf("batch onto a reserved page and a committed one -> 0x%08lx; alias refusals %llu, placeholder " + "releases tried %llu; after: state 0x%lx type 0x%lx, then state 0x%lx type 0x%lx byte 0x%02x\n", + static_cast(hr), refusals1 - refusals0, splits1 - splits0, first.State, first.Type, + second.State, second.Type, second.State == MEM_COMMIT ? piece[page_bytes] : 0u); + std::printf("allocation base in pages from the first page: first page %+lld (region %llu pages); committed page " + "%+lld before the batch, %+lld after\n", + base_pages(first, piece), static_cast(first.RegionSize / page_bytes), + base_pages(before, piece), base_pages(second, piece)); + // The walk refuses the two-page view. The batch then retries each page on its own (install_alias_plan): the + // reserved page alone is accepted, released and mapped, and the rollback unmaps it again; the committed page alone + // is refused. A walk that checks only the first region of each allocation accepts the view, and under Wine the + // release then succeeds and the view replaces the committed page (measured 2026-11-27 before the fix). + // Limit: the fallback cannot tell a reserved page of a private allocation made in place of a placeholder + // (MEM_REPLACE_PLACEHOLDER) from a placeholder. Under Wine the per-page release cuts that page out of the caller's + // allocation: afterwards the committed page's allocation starts one page later (measured 2026-11-27). The row + // asserts only that the first page is still one reserved page with its own address as its allocation base, and + // prints where the committed page's allocation starts. + if (!require(refusals1 - refusals0 >= 1, "the region walk refuses the two-page view") || + !require(FAILED(hr), "the partly committed target is refused") || + !require(first.State == MEM_RESERVE && first.AllocationBase == piece && first.RegionSize == page_bytes && + second.State == MEM_COMMIT && second.Type == MEM_PRIVATE && piece[page_bytes] == 0x7a && + piece[2 * page_bytes - 1] == 0x7a, + "the committed page keeps its bytes and the first page stays one reserved page at its address")) + return 1; + if (second.AllocationBase != piece) + std::puts("limit: the per-page retry cut the reserved page out of the caller's allocation " + "(docs/experiments/xmem-page-runs.md)"); + std::puts("partial: a view over a reserved and a committed page was refused; the committed page kept its bytes"); + return 0; +} +} // namespace + +int wmain(int argc, wchar_t** argv) +{ + const bool control = argc == 3 && std::wcscmp(argv[2], L"control") == 0; + const bool deployed = argc == 3 && std::wcscmp(argv[2], L"deployed") == 0; + const bool partial = argc == 3 && std::wcscmp(argv[2], L"partial") == 0; + if (argc != 2 && !control && !deployed && !partial) return 2; + // xmem reads the switch once, in its first placeholder probe; set it before loading xmem.dll. + SetEnvironmentVariableW(L"X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK", control || deployed ? L"1" : nullptr); + if (partial) { + // A two-page view needs shared views (one view per run of pool pages); joins across calls stay off. + SetEnvironmentVariableW(L"X2W_XMEM_SHARED_VIEWS", L"1"); + SetEnvironmentVariableW(L"X2W_XMEM_JOIN_CALLS", nullptr); + } + const bool bit = os_reports_placeholder_bit(); + std::printf("placeholder bit reported=%d\n", bit); + if ((control || deployed || partial) && 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); + if (partial) return partial_case(xmem, pool, batch_map); + + // 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"); + if (deployed) std::puts("deployed build: X2W_XMEM_TEST_NO_PLACEHOLDER_FALLBACK=1 was ignored"); + 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..3f1767ab66 --- /dev/null +++ b/tests/xmem_run_break_readers_check.cpp @@ -0,0 +1,897 @@ +// 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), a ReadFile from an anonymous pipe into the page (not run again: it fails inside +// the window), 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 finds the page mapped again and looks up the stamp break A left on the run; the thread is retried and reads +// its page. Break B then takes the same page apart and stamps the run again, and the thread faults on it again: that +// fault must be retried as well (a different stamp). With `next-break-control` the handler is not held, so it sees +// break A in progress and waits for memory.mutex before the lookup: that order passes even when the handler's check +// of a fault after its break has ended is wrong, which shows the hold is what this case depends on. +// +// A fault whose handler looks the page up 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 page's run keeps the stamp of the break that mapped it again, whatever breaks follow on +// other runs. Joins across calls need X2W_XMEM_JOIN_CALLS=1: main sets it for `mirror` and clears it for every other +// mode. +// +// Many later breaks (later_breaks): a held fault in break A whose handler runs after 63, 64 or 200 later breaks on +// another page is retried each time (the reader's own __except would catch a fault passed on). A fault that stays +// (persistent_fault, a page of a run made no-access): passed on at once when no break mapped the run, and after one +// retry when one did; a first-chance handler of the test counts the faults. +// +// 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); `stamps` runs +// later_breaks with 63, 64 and 200 later breaks, then persistent_fault. +// +// Usage: xmem_run_break_readers_check +// [control|next-break-control|default|lazy|two-runs|mirror|stamps] +#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; +} + +// An anonymous pipe with two 4096-byte messages queued, read into the page inside the window. The wrapper runs a +// failed call again only on a disk file, so this one fails inside the window instead of waiting for the break. Its +// error must be one the wrapper retries on a disk file, or answering at once would show nothing. Measured under Wine +// (Proton Experimental, 2026-11): ERROR_NOACCESS inside the window, both messages still queued. A pipe read into a +// mapped page of a run fails there even outside a break (ERROR_INVALID_USER_BUFFER), while one into a VirtualAlloc +// buffer reads the first message, so a retry after the break would not have read it either. +struct PipeRead { + BOOL ok = FALSE; + DWORD bytes = 0, error = 0, queued_before = 0, queued_after = 0; + bool second_message = false; // the bytes read are the second message's +} pipe_read; + +bool read_pipe_into(unsigned char* target) +{ + HANDLE r = nullptr, w = nullptr; + if (!CreatePipe(&r, &w, nullptr, 16 * io_bytes)) return false; + unsigned char first[io_bytes], second[io_bytes]; + io_pattern(first); + std::memset(second, 0x5a, io_bytes); + DWORD done = 0; + const bool queued = WriteFile(w, first, io_bytes, &done, nullptr) && done == io_bytes && + WriteFile(w, second, io_bytes, &done, nullptr) && done == io_bytes; + PipeRead& p = pipe_read; + PeekNamedPipe(r, nullptr, 0, nullptr, &p.queued_before, nullptr); + p.ok = queued && ReadFile(r, target, io_bytes, &p.bytes, nullptr); + p.error = p.ok ? 0 : GetLastError(); + PeekNamedPipe(r, nullptr, 0, nullptr, &p.queued_after, nullptr); + p.second_message = p.ok && std::memcmp(target, second, io_bytes) == 0; + CloseHandle(r); + CloseHandle(w); + std::printf("ReadFile from a pipe into the run: ok=%d bytes=%lu error=%lu queued before %lu after %lu, second " + "message %d\n", p.ok, p.bytes, p.error, p.queued_before, p.queued_after, p.second_message); + return p.ok && p.bytes == io_bytes && std::memcmp(target, first, 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 looks the page up 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 sees break A in progress and waits for memory.mutex + } + 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 looks the page up 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 ran while break A 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 looks the page up while B is in progress: it must still find +// the stamp of A on run 1 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 looks the page up 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, X2W_XMEM_JOIN_CALLS=1 from main): 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 looks the page up 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; + } +} + +// Break A takes apart run 1; a fault in it is held before its handler looks the page up (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). Run 1's views keep the stamp of break A, which mapped them again, however many +// breaks follow, so the fault is retried and the reader reads its page. A fault passed on would reach the reader's +// own __except. +void later_breaks_case(const Shim& shim, unsigned char* run1, SIZE_T later) +{ + char name[32], stem[32]; + std::snprintf(name, sizeof(name), "later_breaks_%zu", later); + std::snprintf(stem, sizeof(stem), "later-%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; + } + const ULONGLONG elapsed = GetTickCount64() - started; + std::printf("%s: %zu later breaks in %llu ms\n", name, made, static_cast(elapsed)); + check(made == later, "later_breaks_made", name); + check(outcome.load() == 0 && elapsed < 4000, "handler_still_held_after_the_later_breaks", name); + SetEvent(retry.second); // the handler looks the page up now + reader.join(); + check(outcome.load() == 1 && value == 0x56000002u, "fault_retried_after_the_later_breaks", name); + shim.map(run1, 7, nullptr); + shim.release(pages + 1, tokens); +} + +std::atomic first_chance_faults{0}; +ULONG_PTR counted_page = 0; + +// Added after xmem's handler with FirstHandler=1, so it sees each access violation first, also one xmem retries. +LONG CALLBACK count_fault(EXCEPTION_POINTERS* e) +{ + const EXCEPTION_RECORD* record = e->ExceptionRecord; + if (record->ExceptionCode == EXCEPTION_ACCESS_VIOLATION && record->NumberParameters >= 2 && + (record->ExceptionInformation[1] & ~(ULONG_PTR{page} - 1)) == counted_page) + ++first_chance_faults; + return EXCEPTION_CONTINUE_SEARCH; +} + +// A fault that stays: page 2 of a run made no-access, read once by a new thread. On a run no break has mapped (stamp +// 0) the handler passes the fault on at once: one fault. After a break maps the run again (the unmap of page 7), it +// retries once and then passes it on: two faults. Both reach the reader's __except. +void persistent_fault_case(const Shim& shim, unsigned char* run1) +{ + const char* const name = "persistent_fault"; + SIZE_T count = pages, tokens[pages] = {}; + if (!shim.allocate(0x20400000, &count, tokens) || count != pages || shim.map(run1, pages, tokens) != run1) { + check(false, "map_run", name); + return; + } + unsigned char* const target = run1 + 2 * page; + const auto faults = [&](const char* step) { + DWORD old = 0; + if (!check(VirtualProtect(target, page, PAGE_NOACCESS, &old) != FALSE, step, name)) return -1; + counted_page = reinterpret_cast(target); + first_chance_faults = 0; + void* const counter = AddVectoredExceptionHandler(1, count_fault); + std::uint32_t value = 0; + bool read = true; + std::thread reader([&] { read = guarded_read(reinterpret_cast(target), &value); }); + reader.join(); + if (counter) RemoveVectoredExceptionHandler(counter); + VirtualProtect(target, page, PAGE_READWRITE, &old); + const int counted = first_chance_faults.load(); + std::printf("%s: %s -> read %d, first-chance faults %d\n", name, step, read, counted); + return counter && !read ? counted : -1; + }; + check(faults("no_break_mapped_the_run") == 1, "passed_on_at_once_without_a_stamp", name); + check(shim.map(run1 + 7 * page, 1, nullptr) == run1 + 7 * page, "unmap_page_7", name); + check(faults("a_break_mapped_the_run") == 2, "retried_once_with_a_stamp", name); + shim.map(run1, 7, nullptr); + shim.release(pages, 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 stamps = argc > 2 && std::strcmp(argv[2], "stamps") == 0; + if (argc < 2 || (argc > 2 && !control && !next_break_control && !default_mode && !lazy && !two_runs && !mirror && + !stamps)) { + std::printf("usage: xmem_run_break_readers_check " + "[control|next-break-control|default|lazy|two-runs|mirror|stamps]\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"); + SetEnvironmentVariableA("X2W_XMEM_JOIN_CALLS", mirror ? "1" : nullptr); // only `mirror` joins across calls + 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 || stamps) { + 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 (stamps) { + later_breaks_case(shim, at, 63); + later_breaks_case(shim, at + 64 * page, 64); + later_breaks_case(shim, at + 128 * page, 200); + persistent_fault_case(shim, at + 192 * page); + } + 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); + window_case(shim, at, index++, "ReadFile_pipe", false, read_pipe_into); + check(!pipe_read.ok && (pipe_read.error == ERROR_NOACCESS || pipe_read.error == ERROR_INVALID_USER_BUFFER), + "fails_with_an_error_the_wrapper_retries_for_disk_files", "ReadFile_pipe"); + 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; +} diff --git a/tools/startup/run.sh b/tools/startup/run.sh index 01a32d4872..802e12c9c5 100755 --- a/tools/startup/run.sh +++ b/tools/startup/run.sh @@ -100,6 +100,9 @@ export X2W_AUDIO_PERMISSIVE=1 X2W_D3D12_DEVICE_NOOP=1 X2W_D3D12_LIST_NOOP=1 export X2W_D3D12_PERMISSIVE=1 X2W_XMEM_PERMISSIVE=1 X2W_RUNTIME_PROXY=1 # Under Wine, one section and view per page did not get past start-up (docs/wine.md). export X2W_XMEM_SHARED_VIEWS=${X2W_XMEM_SHARED_VIEWS:-1} +# Mapping calls join the shared view that ends at their address: fewer views, and under Wine each map costs more +# the more views there are (docs/wine.md). +export X2W_XMEM_JOIN_CALLS=${X2W_XMEM_JOIN_CALLS:-1} export WINEDEBUG=${WINEDEBUG:--all} WINEFSYNC=${WINEFSYNC:-1} # Wine's built-in D3D12 is not enough (docs/wine.md); the prefix holds vkd3d-proton and DXVK. export WINEDLLOVERRIDES=${WINEDLLOVERRIDES:-d3d12,d3d12core,dxgi,d3d11=n}