Skip to content

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

Open
LeandroLP23 wants to merge 3 commits into
boykopovar:mainfrom
LeandroLP23:feat/libc-windows-read-traps
Open

LeandroLP23 wants to merge 3 commits into
boykopovar:mainfrom
LeandroLP23:feat/libc-windows-read-traps

Conversation

@LeandroLP23

@LeandroLP23 LeandroLP23 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

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.

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

LeandroLP23 and others added 2 commits November 24, 2026 14:11
Port the Linux read traps of GuestWriteWatch to Windows: a trapped
range is made PAGE_NOACCESS and a vectored exception handler added with
the first resolver runs the resolver on its own thread. Traps are set
only on read-write resident guest arena pages that WindowsMappings does
not protect itself. The arena's commit, reset and mappings and
libkernel's mprotect resolve traps over their range first, and an alias
of a resident run drops the traps in it.

No library sets traps on Windows yet.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
GuestArenaBeginHostWrite went to WindowsMappings alone on Windows, so a
host write through GuestArena::HostWrite (file reads, socket receives)
into a trapped page would fail or fault instead of resolving the trap
first, as it does on Linux and macOS. Open the write watch's host write
around the WindowsMappings one.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@github-actions

Copy link
Copy Markdown

Other open pull requests touch the same code. Merging one will break the other, or both implement the same thing. If this one builds on them, list them in Depends on.

Pull request Conflicting files (lines on main) Same exports Same new files
PR 18300 core/libs/prx/libc/src/GuestArena.cpp L779

Some comparisons could not be completed because a pull request conflicts with the base branch. Review these shared files manually before concluding that there is no overlap.

Pull request Shared files not compared
PR 1835 core/libs/prx/libc/src/GuestArena.cpp
PR 7149 core/libs/prx/libkernel/DirectMemory/DirectMemory.cpp
PR 12792 core/libs/prx/libc/src/GuestWriteWatch.cpp
PR 20315 core/libs/prx/libc/include/WindowsMappings.hpp
core/libs/prx/libc/src/GuestArena.cpp
PR 20580 core/libs/prx/libc/src/GuestWriteWatch.cpp

@kripotker

Copy link
Copy Markdown
Contributor

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 b0085f0. 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).

@kripotker kripotker left a comment •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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 b0085f0. 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).

Only the guest arena operations widen the fenced range to the resident
runs they touch; libkernel's mprotect changes and fences exactly the
range it is given.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@LeandroLP23

Copy link
Copy Markdown
Contributor Author

@kripotker thanks for the review and the stress run. You are right about mprotect. Its fence covers exactly [addr, addr + len), and that is the intent: WindowsMappings::SetProtection only updates the bookkeeping of the views in range, and the VirtualProtect that follows touches only that range, so a trap elsewhere in the run stays as it is. Only the arena operations can split or evict a whole resident run, which is why they widen. 574b9a1b0f rewords the debt fragment, and the description says the same now.

AI-assisted: yes (Claude Code)

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants