feat(libc): trap guest reads for the write watch on Windows #26643

Merged
LeandroLP23 merged 3 commits from upstream-pr/26643 into main 2026-11-27 22:02:39 +00:00
LeandroLP23 commented 2026-11-24 13:12:10 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by LeandroLP23 on 2026-11-24T13:12:10Z.


What

The write watch's read traps (GuestWriteWatchTrapReads and the rest of that API) now work on Windows. Before this, every call there was a no-op on Windows. The class is a port of the Linux one from #19054: the same trap set, resolver slots, batches and holder bypass. Only the host primitives change. This PR does not change what the driver does: no library sets a trap on Windows yet. A follow-up enables the label read traps in libSceAgcDriver on top of it.

  • Trapping: a trapped range is made PAGE_NOACCESS with VirtualProtect. A vectored exception handler, added first in the chain when the first resolver is set, waits while the resolver runs on the watch's own thread, then gives the pages back read-write. It passes every other fault on, so the crash report and WindowsMappings handlers still see theirs. A thread that holds what the bypass reports (the GpuMutex holder, in the driver) opens the page unstored, as on Linux.
  • Where a trap is set: only on committed guest arena pages that VirtualQuery reports as exactly PAGE_READWRITE, and only inside resident runs of WindowsMappings. WindowsMappings::ProtectsItself refuses shared views and views demoted for an alias, since write tracking and eviction change their protection themselves.
  • Arena changes:
    • the guest arena's commit, reset, shared, zero, direct and file mappings resolve the traps over their range before changing it, and no trap can be set there while they run. The range is widened to the resident runs it touches, since a split or an eviction rewrites the whole run. libkernel's mprotect does the same over its exact range: WindowsMappings::SetProtection only updates the bookkeeping of the views in range, and its VirtualProtect covers only that range;
    • GuestArenaBeginHostWrite, which GuestArena::HostWrite uses for file reads and socket receives into guest memory, now opens the write watch's host write on Windows too, as on Linux and macOS. Before, it went to WindowsMappings alone, so a host write into a trapped page would fail or fault instead of resolving the trap first;
    • GuestArenaMapAlias drops the traps in the resident runs it demotes, without running the resolver, because a host import maps that alias under the write tracker lock the resolver takes. GuestWriteWatchUnregister drops them the same way on Windows. The drop shows in GuestWriteWatchReadTrapGeneration, so a caller can store the range again.
  • Tests: windows_read_trap_tests has 12 modes: trap, release, host, arenahost, unknown, reset, alias, trapped, generation, untrapped, holder, threads. The threads resolver does not touch the pages, as a store through a host import does not. Its readers check that none of them goes on before the resolver returns.
  • Debt fragment: what stays open. A system call that reads a trapped page fails instead of faulting. A resolver that stores with the CPU opens each page to every thread at its first store, as on Linux. A read between an alias drop and the caller's store sees the old bytes.

Tested

Windows 11 (10.0.26300), WinLibs GCC 15.2.0 r7, Release.

  • Laptop, Ryzen AI 7 350 with Radeon 860M:
    • windows_read_trap_tests: all 12 modes pass in 20 of 20 rounds.
    • Negative controls: without the wait in HandleFault, trapped and holder fail and threads times out; without the write watch's host write in GuestArenaBeginHostWrite, arenahost fails (an arena host write over a trapped page did not resolve it first).
    • Full ctest -j8 with ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1, before the alias drop was added: 2 failures, agc_driver_linear_target_import_creation (private gate: a color target's import of direct memory under the settle floor was made where it would be compared) and agc_driver_store_over_untracked (a pending storage result was stored over bytes the CPU wrote to untracked memory). Both fail with the same messages, 3 of 3 runs, on the base 4c9e324231 without this change.
    • With both commits, the 61 tests matching windows_read_trap|guest_arena|arena|write_watch|windows_mappings|direct_memory|guest_copy|guest_memory|host_write|mprotect pass (1 skipped), with and without VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation VK_LOADER_DEBUG=layer. With the layer, the log shows 12 Insert instance layer "VK_LAYER_KHRONOS_validation" lines, no was not found and no VUID-.
  • Desktop, i5-10600K with RTX 5060 Ti, on a tree with #10442, #24445, #25280, #24869 and #26606 under the first commit:
    • windows_read_trap_tests: all 11 modes it had then pass in 20 of 20 rounds.
    • Negative control: without the drop in GuestArenaMapAlias, alias fails (an alias that demotes a resident run kept the generation of the trap in it).
  • tools/check_conventions.py and tools/debt_fold.py --check pass.
  • Overlap: tools/pr_overlap.py --branch reports a textual conflict with #18300 in GuestArena.cpp near GuestArenaCommit, where both PRs add lines. #20580 and #26221 change the same files for the macOS and Linux traps and add no Windows code. #1835, #7149, #12792 and #20315 also share files, but each already conflicts with main.

Not run: Linux, macOS (the shared code there is unchanged).

Checklist

  • Based on current main; no other open PR implements the same functions
  • One topic per PR; follow-ups go in a new PR
  • No comments in code except technical debt and the licence notice of code adapted from upstream (see AGENTS.md)
  • Unimplemented paths throw (NotImplemented_nid_no_patch); silent stubs are listed under Silent stubs in their library's technical debt file
  • No notes, investigation .md files or images added to the repository (attach them to this PR)
  • New third-party code is a submodule built from source
  • Generic behaviour, not specific to one title
  • Depends on: none
  • Fixes: none
  • Unblocks: none
  • GPUs tested: n/a (libc and libkernel only; no GPU path changes)
  • AI-assisted: yes
<!-- greyfinch-sync:boykopovar/AnyPS5:issue:5472805986 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/26643). Originally posted by [LeandroLP23](https://github.com/LeandroLP23) on 2026-11-24T13:12:10Z. --- ### What The write watch's read traps (`GuestWriteWatchTrapReads` and the rest of that API) now work on Windows. Before this, every call there was a no-op on Windows. The class is a port of the Linux one from #19054: the same trap set, resolver slots, batches and holder bypass. Only the host primitives change. This PR does not change what the driver does: no library sets a trap on Windows yet. A follow-up enables the label read traps in libSceAgcDriver on top of it. - **Trapping:** a trapped range is made `PAGE_NOACCESS` with `VirtualProtect`. A vectored exception handler, added first in the chain when the first resolver is set, waits while the resolver runs on the watch's own thread, then gives the pages back read-write. It passes every other fault on, so the crash report and `WindowsMappings` handlers still see theirs. A thread that holds what the bypass reports (the `GpuMutex` holder, in the driver) opens the page unstored, as on Linux. - **Where a trap is set:** only on committed guest arena pages that `VirtualQuery` reports as exactly `PAGE_READWRITE`, and only inside resident runs of `WindowsMappings`. `WindowsMappings::ProtectsItself` refuses shared views and views demoted for an alias, since write tracking and eviction change their protection themselves. - **Arena changes:** - the guest arena's commit, reset, shared, zero, direct and file mappings resolve the traps over their range before changing it, and no trap can be set there while they run. The range is widened to the resident runs it touches, since a split or an eviction rewrites the whole run. libkernel's `mprotect` does the same over its exact range: `WindowsMappings::SetProtection` only updates the bookkeeping of the views in range, and its `VirtualProtect` covers only that range; - `GuestArenaBeginHostWrite`, which `GuestArena::HostWrite` uses for file reads and socket receives into guest memory, now opens the write watch's host write on Windows too, as on Linux and macOS. Before, it went to `WindowsMappings` alone, so a host write into a trapped page would fail or fault instead of resolving the trap first; - `GuestArenaMapAlias` drops the traps in the resident runs it demotes, without running the resolver, because a host import maps that alias under the write tracker lock the resolver takes. `GuestWriteWatchUnregister` drops them the same way on Windows. The drop shows in `GuestWriteWatchReadTrapGeneration`, so a caller can store the range again. - **Tests:** `windows_read_trap_tests` has 12 modes: trap, release, host, arenahost, unknown, reset, alias, trapped, generation, untrapped, holder, threads. The `threads` resolver does not touch the pages, as a store through a host import does not. Its readers check that none of them goes on before the resolver returns. - **Debt fragment:** what stays open. A system call that reads a trapped page fails instead of faulting. A resolver that stores with the CPU opens each page to every thread at its first store, as on Linux. A read between an alias drop and the caller's store sees the old bytes. ### Tested Windows 11 (10.0.26300), WinLibs GCC 15.2.0 r7, Release. - Laptop, Ryzen AI 7 350 with Radeon 860M: - `windows_read_trap_tests`: all 12 modes pass in 20 of 20 rounds. - Negative controls: without the wait in `HandleFault`, `trapped` and `holder` fail and `threads` times out; without the write watch's host write in `GuestArenaBeginHostWrite`, `arenahost` fails (`an arena host write over a trapped page did not resolve it first`). - Full `ctest -j8` with `ANYPS5_REQUIRE_VULKAN=1 ANYPS5_NO_SHADER_CACHE=1`, before the alias drop was added: 2 failures, `agc_driver_linear_target_import_creation` (`private gate: a color target's import of direct memory under the settle floor was made where it would be compared`) and `agc_driver_store_over_untracked` (`a pending storage result was stored over bytes the CPU wrote to untracked memory`). Both fail with the same messages, 3 of 3 runs, on the base `4c9e324231` without this change. - With both commits, the 61 tests matching `windows_read_trap|guest_arena|arena|write_watch|windows_mappings|direct_memory|guest_copy|guest_memory|host_write|mprotect` pass (1 skipped), with and without `VK_INSTANCE_LAYERS=VK_LAYER_KHRONOS_validation VK_LOADER_DEBUG=layer`. With the layer, the log shows 12 `Insert instance layer "VK_LAYER_KHRONOS_validation"` lines, no `was not found` and no `VUID-`. - Desktop, i5-10600K with RTX 5060 Ti, on a tree with #10442, #24445, #25280, #24869 and #26606 under the first commit: - `windows_read_trap_tests`: all 11 modes it had then pass in 20 of 20 rounds. - Negative control: without the drop in `GuestArenaMapAlias`, `alias` fails (`an alias that demotes a resident run kept the generation of the trap in it`). - `tools/check_conventions.py` and `tools/debt_fold.py --check` pass. - **Overlap:** `tools/pr_overlap.py --branch` reports a textual conflict with #18300 in `GuestArena.cpp` near `GuestArenaCommit`, where both PRs add lines. #20580 and #26221 change the same files for the macOS and Linux traps and add no Windows code. #1835, #7149, #12792 and #20315 also share files, but each already conflicts with `main`. Not run: Linux, macOS (the shared code there is unchanged). ### Checklist <!-- Rules behind each item: https://github.com/boykopovar/AnyPS5/blob/main/CONTRIBUTING.md --> - [x] Based on current `main`; no other open PR implements the same functions - [x] One topic per PR; follow-ups go in a new PR - [x] No comments in code except [technical debt](https://github.com/boykopovar/AnyPS5/blob/main/docs/dev/CONVENTIONS.md) and the licence notice of code adapted from upstream (see AGENTS.md) - [x] Unimplemented paths throw (`NotImplemented_nid_no_patch`); silent stubs are listed under Silent stubs in their library's [technical debt](https://github.com/boykopovar/AnyPS5/tree/main/docs/dev/debt) file - [x] No notes, investigation `.md` files or images added to the repository (attach them to this PR) - [x] New third-party code is a submodule built from source - [x] Generic behaviour, not specific to one title - [x] Depends on: none - [x] Fixes: none - [x] Unblocks: none - [x] GPUs tested: n/a (libc and libkernel only; no GPU path changes) - [x] AI-assisted: yes
kripotker commented 2026-11-24 18:46:30 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by kripotker on 2026-11-24T18:46:30Z.

Review: APPROVED


Review: feat(libc): trap guest reads for the write watch on Windows

Recommendation: merge. All tests pass on a second Windows machine, a 200× stress run of all 12 modes is clean, and the 33 existing arena and host-write tests pass. One wording mismatch is noted below.

What I checked

  • ReadTraps (Windows) against the Linux class on main. The trap set, resolver slots, batches, holder bypass and retryOpen counters match. Only the host primitives differ: VirtualProtect/VirtualQuery, a vectored handler, semaphores and thread IDs.
  • The vectored handler (ReadTraps::fault):
    • it acts only on EXCEPTION_ACCESS_VIOLATION, and claims a fault only when the page is in its own trap list or a page it just reopened (retryOpen, bounded at 16 retries per generation);
    • every other fault returns EXCEPTION_CONTINUE_SEARCH, so the crash handler and the WindowsMappings handlers still see their faults;
    • under _lock nothing reads guest memory, so a fault can't re-enter the spin lock.
  • TrapReads sets a trap only after readWrite() (MEM_COMMIT + exactly PAGE_READWRITE) and ProtectsItself(), and refuses ranges in _hostWrites, all under the same lock. A failed PAGE_NOACCESS gives the range back read-write.
  • GuestArenaBeginHostWrite now opens the write-watch host write first on Windows, and closes it again when WindowsMappings::BeginHostWrite refuses. GuestArenaEndHostWrite closes both. The open and close are balanced on every path.
  • Sabotage check: the PR only touches the write watch, the arena, mprotect, one test and one debt fragment. The handler has no file, network or process side effects.

What I ran

Windows 11 (desktop: Ryzen 7 7700, 32 GB), MSYS2 UCRT64 GCC 16.2.0 (Rev6), Ninja, Release, PR head b0085f0d98. This is a different machine and toolchain from the PR's WinLibs 15.2 laptop run.

cmake --build build --target windows_read_trap_tests
ctest --test-dir build -R "^windows_read_trap_"
ctest --test-dir build -R "^windows_read_trap_" -j 16 --repeat until-fail:200
ctest --test-dir build -j 16 -R "^(windows_write_watch.*|windows_mappings_.*|guest_copy_.*|guest_socket_host_write_.*|savedata_memory_host_write|guest_stream_buffer_host_write|guest_np_trophy_host_write|guest_direct_memory_for_app|guest_named_shm_windows_mapping|guest_mprotect_unmapped|guest_kernel_mprotect_prot_none)$"
python3 tools/check_conventions.py
  • windows_read_trap_*: 12/12 passed.
  • The stress run (each mode repeated up to 200 times, 16 at a time, so threads runs under load) ended with 100% tests passed out of 12.
  • Existing arena / mapping / host-write / mprotect tests: 33/33 passed. The guest_socket_host_write_* group goes through the changed GuestArenaBeginHostWrite.
  • check_conventions.py: All conventions checks passed.
  • No new warnings in the changed files.

Note: the mprotect fence isn't widened, but the text says it is

The description and the debt fragment both say libkernel's mprotect resolves traps "widened to the resident runs it touches". But the TrapFence in core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp:171-176 fences exactly [addr, addr + len). Only the arena operations in GuestArena.cpp use WithResidentRuns.

As far as I can read, the code is fine as it is: WindowsMappings::SetProtection only updates bookkeeping for the views in range, and the VirtualProtect in mprotect covers just [addr, addr + len), so a trap elsewhere in the run is left alone. If that is the intent, please reword the debt fragment so it doesn't promise widening for mprotect. If widening is intended, the fence needs WithResidentRuns (or an exported equivalent).

AI-assisted: yes (Claude Code).

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6045293502 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/26643#pullrequestreview-6045293502). Originally posted by [kripotker](https://github.com/kripotker) on 2026-11-24T18:46:30Z. **Review:** APPROVED --- ## Review: feat(libc): trap guest reads for the write watch on Windows **Recommendation: merge.** All tests pass on a second Windows machine, a 200× stress run of all 12 modes is clean, and the 33 existing arena and host-write tests pass. One wording mismatch is noted below. ### What I checked - `ReadTraps` (Windows) against the Linux class on `main`. The trap set, resolver slots, batches, holder bypass and `retryOpen` counters match. Only the host primitives differ: `VirtualProtect`/`VirtualQuery`, a vectored handler, semaphores and thread IDs. - The vectored handler (`ReadTraps::fault`): - it acts only on `EXCEPTION_ACCESS_VIOLATION`, and claims a fault only when the page is in its own trap list or a page it just reopened (`retryOpen`, bounded at 16 retries per generation); - every other fault returns `EXCEPTION_CONTINUE_SEARCH`, so the crash handler and the `WindowsMappings` handlers still see their faults; - under `_lock` nothing reads guest memory, so a fault can't re-enter the spin lock. - `TrapReads` sets a trap only after `readWrite()` (`MEM_COMMIT` + exactly `PAGE_READWRITE`) and `ProtectsItself()`, and refuses ranges in `_hostWrites`, all under the same lock. A failed `PAGE_NOACCESS` gives the range back read-write. - `GuestArenaBeginHostWrite` now opens the write-watch host write first on Windows, and closes it again when `WindowsMappings::BeginHostWrite` refuses. `GuestArenaEndHostWrite` closes both. The open and close are balanced on every path. - **Sabotage check:** the PR only touches the write watch, the arena, `mprotect`, one test and one debt fragment. The handler has no file, network or process side effects. ### What I ran Windows 11 (desktop: Ryzen 7 7700, 32 GB), MSYS2 UCRT64 GCC 16.2.0 (Rev6), Ninja, Release, PR head b0085f0d98. This is a different machine and toolchain from the PR's WinLibs 15.2 laptop run. ``` cmake --build build --target windows_read_trap_tests ctest --test-dir build -R "^windows_read_trap_" ctest --test-dir build -R "^windows_read_trap_" -j 16 --repeat until-fail:200 ctest --test-dir build -j 16 -R "^(windows_write_watch.*|windows_mappings_.*|guest_copy_.*|guest_socket_host_write_.*|savedata_memory_host_write|guest_stream_buffer_host_write|guest_np_trophy_host_write|guest_direct_memory_for_app|guest_named_shm_windows_mapping|guest_mprotect_unmapped|guest_kernel_mprotect_prot_none)$" python3 tools/check_conventions.py ``` - `windows_read_trap_*`: 12/12 passed. - The stress run (each mode repeated up to 200 times, 16 at a time, so `threads` runs under load) ended with `100% tests passed out of 12`. - Existing arena / mapping / host-write / `mprotect` tests: **33/33 passed**. The `guest_socket_host_write_*` group goes through the changed `GuestArenaBeginHostWrite`. - `check_conventions.py`: `All conventions checks passed.` - No new warnings in the changed files. ### Note: the `mprotect` fence isn't widened, but the text says it is The description and the debt fragment both say libkernel's `mprotect` resolves traps "widened to the resident runs it touches". But the `TrapFence` in `core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp:171-176` fences exactly `[addr, addr + len)`. Only the arena operations in `GuestArena.cpp` use `WithResidentRuns`. As far as I can read, the code is fine as it is: `WindowsMappings::SetProtection` only updates bookkeeping for the views in range, and the `VirtualProtect` in `mprotect` covers just `[addr, addr + len)`, so a trap elsewhere in the run is left alone. If that is the intent, please reword the debt fragment so it doesn't promise widening for `mprotect`. If widening is intended, the fence needs `WithResidentRuns` (or an exported equivalent). AI-assisted: yes (Claude Code).
MarcZX10 commented 2026-11-25 16:36:33 +00:00 (Migrated from github.com)

Imported from boykopovar/AnyPS5. Originally posted by MarcZX10 on 2026-11-25T16:36:33Z.

Review: COMMENTED


Reviewed — comments

The Windows read trap implementation has a concrete failure path that can strand trapped pages when resolution fails.

What I ran

  • Reviewed head 574b9a1b0fbab4d6401407a3aa5aaf93d55c62bd; no merged-preview check was run.
  • Read the prepared description, commits, diff, manifest, and all seven changed files. Used repo_read.py to inspect targeted source ranges. No tests were run by me; Windows test results in the description are author-reported.

Results

Check Result Note
Source review passed Changed paths inspected
Test execution not run Author reports Windows results
Negative control not run No independent control run

Findings

Blocking

None verified.

Non-blocking

  • GuestWriteWatch.cpp:2065 calls the user resolver without containing exceptions or restoring the traps if it fails. The resolver runs on the dedicated resolver thread; an exception escaping its thread entry terminates the process, while a non-local failure would leave traps owned and waiters blocked. Consider defining and enforcing a non-throwing resolver contract, or adding a failure path that releases waiters and restores a safe page state.

Not verified

  • I did not run the Windows tests or the reported CTest suite, and did not verify Linux or macOS behavior.
  • No changed files were excluded; all seven changed files listed in the prepared manifest were read.

To get this to a good state

Nothing is required. The resolver failure handling is optional feedback.

<!-- greyfinch-sync:boykopovar/AnyPS5:review:6061290654 --> Imported from [boykopovar/AnyPS5](https://github.com/boykopovar/AnyPS5/pull/26643#pullrequestreview-6061290654). Originally posted by [MarcZX10](https://github.com/MarcZX10) on 2026-11-25T16:36:33Z. **Review:** COMMENTED --- # Reviewed — comments The Windows read trap implementation has a concrete failure path that can strand trapped pages when resolution fails. ## What I ran - Reviewed head `574b9a1b0fbab4d6401407a3aa5aaf93d55c62bd`; no merged-preview check was run. - Read the prepared description, commits, diff, manifest, and all seven changed files. Used `repo_read.py` to inspect targeted source ranges. No tests were run by me; Windows test results in the description are author-reported. ## Results | Check | Result | Note | |---|---|---| | Source review | passed | Changed paths inspected | | Test execution | not run | Author reports Windows results | | Negative control | not run | No independent control run | ## Findings ### Blocking None verified. ### Non-blocking - `GuestWriteWatch.cpp:2065` calls the user resolver without containing exceptions or restoring the traps if it fails. The resolver runs on the dedicated resolver thread; an exception escaping its thread entry terminates the process, while a non-local failure would leave traps owned and waiters blocked. Consider defining and enforcing a non-throwing resolver contract, or adding a failure path that releases waiters and restores a safe page state. ## Not verified - I did not run the Windows tests or the reported CTest suite, and did not verify Linux or macOS behavior. - No changed files were excluded; all seven changed files listed in the prepared manifest were read. ## To get this to a good state Nothing is required. The resolver failure handling is optional feedback.
Sign in to join this conversation.
No reviewers
No labels
No milestone
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Reference
boykopovar/AnyPS5!26643
No description provided.