KernelX, D3D12.X, DirectStorage: opt-in XCL_GUEST_WRITE_GUARD for XCL-protected title pages #3597

Open
iggyvilla wants to merge 1 commit from upstream-pr/3597 into amd-dev
iggyvilla commented 2026-12-01 17:45:42 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by iggyvilla on 2026-12-01T17:45:42Z.


Adds opt-in XCL_GUEST_WRITE_GUARD=1 (off by default: zero behavior change) to bracket kernel and XCL writes into title pages that XCL itself has made read-only or no-access (guards::watch views today, and registered protector ranges for stacked #3601 / #3639).

TL;DR — Before vs After

Metric Before (origin/amd-dev 41aa60ce) After (07d529ea, XCL_GUEST_WRITE_GUARD unset)
60 s smoke frames / peak commit 1,654 / 15,902 MB (0 crashes) 1,643 / 15,913 MB (0 crashes)
XCL / kernel write to protected page (unit tests, switch on) Pre-checks skip or NtWriteVirtualMemory fails writable() accepts XCL-protected pages; open() / kernel_write() pin, touch, and retry cleanly
Concurrent protector VirtualProtect vs open() Racy is_pinned check Race-free while_unpinned() + FREEZE_LOCK wait in open_with()

Scope note: This PR provides the core guest_write mechanism, race-free while_unpinned / meets_guarded_view protector protocol, and XCL / DirectStorage / ReadFile call-site brackets. No runtime caller calls guest_write::register in this PR yet (the first callers are stacked #3601 and #3639); with XCL_GUEST_WRITE_GUARD=1 alone, only guards::watch views are recognized as XCL-protected. Socket recv/recvfrom hooks and the standalone OS probe were removed to keep this PR single-purpose (~420 runtime lines + ~200 test lines, down from 997).

What is in it

  • crates/xcl/src/hle/kernelx/guest_write.rs: XCL_GUEST_WRITE_GUARD=1 switch, registered range map (register/unregister), xcl_protected, writable (covers), open / Bracket (with keep_until_done for overlapped reads), kernel_write (pin + touch + single retry), and race-free protector serialization (while_unpinned, meets_guarded_view, FREEZE_LOCK wait in open_with). Includes 7 unit tests covering range merge/split, covers, NtWriteVirtualMemory into RO/NA pages, overlapped pins, concurrent while_unpinned ↔ open_with serialization, and a real guards::watch view exercised through enabled() (writable + kernel_write).
  • crates/xcl/src/hle/kernelx.rs, crates/xcl/src/hle/kernelx/guards.rs: exposes guest_write, guards::is_view, and guards::still_pending.
  • crates/xcl/src/eh.rs, crates/xcl/src/hle/d3d12x/cpu_writes.rs, crates/xcl/src/hle/d3d12x/frame.rs, crates/xcl/src/hle/dstorage.rs, crates/xcl/src/hle/dstorage/parallel.rs, crates/xcl/src/vfs_hooks.rs: route writability pre-checks through guest_write::writable, DirectStorage writes through guest_write::kernel_write, and hk_read_file through guest_write::open / keep_until_done (all no-ops when off).

Tested

  • Hardware: AMD Radeon RX 6650 XT 8 GB (RDNA2, driver 32.0.21045.29003), AMD Ryzen 7 5700X, Windows 11 x64, rustc 1.100.0 (0ef1bc386 2026-11-09), debug tests + release smoke.
  • cargo build --workspace && cargo test --workspace --no-fail-fast -- --test-threads=4: 2,965 passed, 13 failed, 49 ignored. All 13 failures reproduce identically on clean origin/amd-dev 41aa60ce (2,954 passed, 17 failed, 49 ignored: 3 pre-existing RDNA2 f32/NaN tests, 6 parallel sparse/title_textures shared-global contention tests, test_title_runs_and_game_folder_is_untouched, and two_pass_driver_cache_e2e). SKIPPED (7): 4× f16_programs_on_the_gpu, 2× heap-window tests, 1× pso_measurement_compiles_an_exact_synthetic_record (Developer Mode off).
  • cargo test -p xcl --lib -- hle::kernelx::guest_write::tests --test-threads=1: 7 passed, 0 failed, 0 ignored, 0 skipped.

Regression run
Base (main, required by pr_check.py):

xcl-smoke v1
commit: d8bd9a38204667f3ca7dd9eeffcc2f1c937b07b0
gpu: AMD Radeon RX 6650 XT
title: 1778c2d9
seconds: 60
exit: 0x0
frames shown: 1618 (PresentX 1618)
presents per 2 s (last 3): 61 60 60
device removals: 0
crashes: 0
peak commit: 15479 MB

Base (origin/amd-dev merge base):

xcl-smoke v1
commit: 41aa60ce842060a597b7e8724896f7bf6a031af5
gpu: AMD Radeon RX 6650 XT
title: 1778c2d9
seconds: 60
exit: 0x0
frames shown: 1654 (PresentX 1654)
presents per 2 s (last 3): 60 61 60
device removals: 0
crashes: 0
peak commit: 15902 MB

PR head (07d529ea, XCL_GUEST_WRITE_GUARD unset):

xcl-smoke v1
commit: 07d529ea9478b48cb9443b2e7aa9a830a48327e0
gpu: AMD Radeon RX 6650 XT
title: 1778c2d9
seconds: 60
exit: 0x0
frames shown: 1643 (PresentX 1643)
presents per 2 s (last 3): 60 60 60
device removals: 0
crashes: 0
peak commit: 15913 MB

Not tested

  • No live title run with a registered protector in this PR (tested in stacked #3601 and #3639).
  • NVIDIA and Intel GPUs, and Wine.

AI use

  • Antigravity (Gemini 4 Neon High) trimmed the PR per review (removed the OS probe and socket hooks, moved while_unpinned / meets_guarded_view here, added real guards::watch and concurrency tests), ran the workspace GPU test suite and 60 s smoke, and updated this description.
<!-- greyfinch-sync:ivall/xcl:issue:5591204415 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3597). Originally posted by [iggyvilla](https://github.com/iggyvilla) on 2026-12-01T17:45:42Z. --- Adds opt-in `XCL_GUEST_WRITE_GUARD=1` (off by default: zero behavior change) to bracket kernel and XCL writes into title pages that XCL itself has made read-only or no-access (`guards::watch` views today, and registered protector ranges for stacked #3601 / #3639). ### TL;DR — Before vs After | Metric | Before (`origin/amd-dev` `41aa60ce`) | After (`07d529ea`, `XCL_GUEST_WRITE_GUARD` unset) | |---|---|---| | **60 s smoke frames / peak commit** | `1,654` / `15,902 MB` (`0` crashes) | `1,643` / `15,913 MB` (`0` crashes) | | **XCL / kernel write to protected page (unit tests, switch on)** | Pre-checks skip or `NtWriteVirtualMemory` fails | `writable()` accepts XCL-protected pages; `open()` / `kernel_write()` pin, touch, and retry cleanly | | **Concurrent protector `VirtualProtect` vs `open()`** | Racy `is_pinned` check | Race-free `while_unpinned()` + `FREEZE_LOCK` wait in `open_with()` | **Scope note:** This PR provides the core `guest_write` mechanism, race-free `while_unpinned` / `meets_guarded_view` protector protocol, and XCL / DirectStorage / `ReadFile` call-site brackets. No runtime caller calls `guest_write::register` in this PR yet (the first callers are stacked #3601 and #3639); with `XCL_GUEST_WRITE_GUARD=1` alone, only `guards::watch` views are recognized as XCL-protected. Socket `recv`/`recvfrom` hooks and the standalone OS probe were removed to keep this PR single-purpose (~420 runtime lines + ~200 test lines, down from 997). **What is in it** - `crates/xcl/src/hle/kernelx/guest_write.rs`: `XCL_GUEST_WRITE_GUARD=1` switch, registered range map (`register`/`unregister`), `xcl_protected`, `writable` (`covers`), `open` / `Bracket` (with `keep_until_done` for overlapped reads), `kernel_write` (pin + touch + single retry), and race-free protector serialization (`while_unpinned`, `meets_guarded_view`, `FREEZE_LOCK` wait in `open_with`). Includes 7 unit tests covering range merge/split, `covers`, `NtWriteVirtualMemory` into RO/NA pages, overlapped pins, concurrent `while_unpinned` ↔ `open_with` serialization, and a real `guards::watch` view exercised through `enabled()` (`writable` + `kernel_write`). - `crates/xcl/src/hle/kernelx.rs`, `crates/xcl/src/hle/kernelx/guards.rs`: exposes `guest_write`, `guards::is_view`, and `guards::still_pending`. - `crates/xcl/src/eh.rs`, `crates/xcl/src/hle/d3d12x/cpu_writes.rs`, `crates/xcl/src/hle/d3d12x/frame.rs`, `crates/xcl/src/hle/dstorage.rs`, `crates/xcl/src/hle/dstorage/parallel.rs`, `crates/xcl/src/vfs_hooks.rs`: route writability pre-checks through `guest_write::writable`, DirectStorage writes through `guest_write::kernel_write`, and `hk_read_file` through `guest_write::open` / `keep_until_done` (all no-ops when off). **Tested** - Hardware: AMD Radeon RX 6650 XT 8 GB (RDNA2, driver `32.0.21045.29003`), AMD Ryzen 7 5700X, Windows 11 x64, `rustc 1.100.0 (0ef1bc386 2026-11-09)`, debug tests + release smoke. - `cargo build --workspace && cargo test --workspace --no-fail-fast -- --test-threads=4`: **2,965 passed, 13 failed, 49 ignored**. All 13 failures reproduce identically on clean `origin/amd-dev` `41aa60ce` (`2,954 passed, 17 failed, 49 ignored`: 3 pre-existing RDNA2 f32/NaN tests, 6 parallel `sparse`/`title_textures` shared-global contention tests, `test_title_runs_and_game_folder_is_untouched`, and `two_pass_driver_cache_e2e`). `SKIPPED` (7): 4× `f16_programs_on_the_gpu`, 2× heap-window tests, 1× `pso_measurement_compiles_an_exact_synthetic_record` (Developer Mode off). - `cargo test -p xcl --lib -- hle::kernelx::guest_write::tests --test-threads=1`: **7 passed, 0 failed, 0 ignored, 0 skipped**. **Regression run** Base (`main`, required by `pr_check.py`): ``` xcl-smoke v1 commit: d8bd9a38204667f3ca7dd9eeffcc2f1c937b07b0 gpu: AMD Radeon RX 6650 XT title: 1778c2d9 seconds: 60 exit: 0x0 frames shown: 1618 (PresentX 1618) presents per 2 s (last 3): 61 60 60 device removals: 0 crashes: 0 peak commit: 15479 MB ``` Base (`origin/amd-dev` merge base): ``` xcl-smoke v1 commit: 41aa60ce842060a597b7e8724896f7bf6a031af5 gpu: AMD Radeon RX 6650 XT title: 1778c2d9 seconds: 60 exit: 0x0 frames shown: 1654 (PresentX 1654) presents per 2 s (last 3): 60 61 60 device removals: 0 crashes: 0 peak commit: 15902 MB ``` PR head (`07d529ea`, `XCL_GUEST_WRITE_GUARD` unset): ``` xcl-smoke v1 commit: 07d529ea9478b48cb9443b2e7aa9a830a48327e0 gpu: AMD Radeon RX 6650 XT title: 1778c2d9 seconds: 60 exit: 0x0 frames shown: 1643 (PresentX 1643) presents per 2 s (last 3): 60 60 60 device removals: 0 crashes: 0 peak commit: 15913 MB ``` **Not tested** - No live title run with a registered protector in this PR (tested in stacked #3601 and #3639). - NVIDIA and Intel GPUs, and Wine. **AI use** - Antigravity (Gemini 4 Neon High) trimmed the PR per review (removed the OS probe and socket hooks, moved `while_unpinned` / `meets_guarded_view` here, added real `guards::watch` and concurrency tests), ran the workspace GPU test suite and 60 s smoke, and updated this description.
Foniass commented 2026-12-01 20:33:13 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T20:33:13Z.


Review (head 1b6f6748, diff read, not a merge-check):

  • Nothing in this PR registers a range. guest_write::register (guest_write.rs ~55) is only called from tests, so with the switch on ANY stays false and open, the pins, touch and the kernel_write retry do nothing. The only XCL-protected pages this PR can meet are guards views, which lazy::ensure already opens for hk_read_file and DirectStorage on the base. So the "kernel write into XCL-protected RO/NA page lands cleanly" row and the switch-on smoke do not exercise a new kernel-write path; the first caller of register is #3601.
  • recv into write-watched memory is still untracked. bounce_with (~319) bounces only when a page is xcl_protected (a registered range or a guarded view, ~99-101). Plain MEM_WRITE_WATCH title memory is neither, so a TCP recv there still goes straight to the kernel and the write watch misses it, while the description's "safe + tracked" row says this case is handled.
  • The documented pin protocol is racy. A protector is told to check is_pinned (~104) and then protect, with the lock released in between; open_with pins (~269) and then touches (~276). A protector can read "not pinned", the writer then pins and touches an already-writable page, and the protector protects it before the kernel call, so ReadFile fails with ERROR_NOACCESS with no retry, against the comment at ~275. #3601 adds while_unpinned for this, which suggests it belongs here.
  • The probe test barely asserts anything. crates/xcl/tests/guest_write_probe.rs calls no XCL code; its only assertions are on the read-write control rows (~301), and the read-only, no-access and write-watch outcomes cited as evidence are only printed. The GPU case is #[ignore]d (~309) instead of using skip_test, and asserts nothing.
  • The call-site changes are untested. enabled() reads the env var once through a OnceLock, so no test runs writable with the switch on, and the changes in cpu_writes.rs, frame.rs, eh.rs and dstorage.rs are never exercised; the unit tests use only a stand-in protector, never a real guards::watch view.
  • Size and scope. 997 changed lines, over ~800 with no reason given, mixing four separable parts: a registry for a protector that is not in this PR, the pre-check changes for guarded views, the recv/recvfrom hooks, and a 407-line OS probe. The registry belongs with its first user.

Fine: with the switch off the default path is unchanged (writable is false, open is lazy::ensure, kernel_write calls the write directly, no hooks installed), and the range merge and split logic is correct.

AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7324883007 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3597#issuecomment-7324883007). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T20:33:13Z. --- Review (head 1b6f6748, diff read, not a merge-check): - **Nothing in this PR registers a range.** `guest_write::register` (`guest_write.rs` ~55) is only called from tests, so with the switch on `ANY` stays false and `open`, the pins, `touch` and the `kernel_write` retry do nothing. The only XCL-protected pages this PR can meet are `guards` views, which `lazy::ensure` already opens for `hk_read_file` and DirectStorage on the base. So the "kernel write into XCL-protected RO/NA page lands cleanly" row and the switch-on smoke do not exercise a new kernel-write path; the first caller of `register` is #3601. - **`recv` into write-watched memory is still untracked.** `bounce_with` (~319) bounces only when a page is `xcl_protected` (a registered range or a guarded view, ~99-101). Plain `MEM_WRITE_WATCH` title memory is neither, so a TCP `recv` there still goes straight to the kernel and the write watch misses it, while the description's "safe + tracked" row says this case is handled. - **The documented pin protocol is racy.** A protector is told to check `is_pinned` (~104) and then protect, with the lock released in between; `open_with` pins (~269) and then touches (~276). A protector can read "not pinned", the writer then pins and touches an already-writable page, and the protector protects it before the kernel call, so `ReadFile` fails with `ERROR_NOACCESS` with no retry, against the comment at ~275. #3601 adds `while_unpinned` for this, which suggests it belongs here. - **The probe test barely asserts anything.** `crates/xcl/tests/guest_write_probe.rs` calls no XCL code; its only assertions are on the read-write control rows (~301), and the read-only, no-access and write-watch outcomes cited as evidence are only printed. The GPU case is `#[ignore]`d (~309) instead of using `skip_test`, and asserts nothing. - **The call-site changes are untested.** `enabled()` reads the env var once through a `OnceLock`, so no test runs `writable` with the switch on, and the changes in `cpu_writes.rs`, `frame.rs`, `eh.rs` and `dstorage.rs` are never exercised; the unit tests use only a stand-in protector, never a real `guards::watch` view. - **Size and scope.** 997 changed lines, over ~800 with no reason given, mixing four separable parts: a registry for a protector that is not in this PR, the pre-check changes for guarded views, the `recv`/`recvfrom` hooks, and a 407-line OS probe. The registry belongs with its first user. Fine: with the switch off the default path is unchanged (`writable` is false, `open` is `lazy::ensure`, `kernel_write` calls the write directly, no hooks installed), and the range merge and split logic is correct. AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.
iggyvilla commented 2026-12-02 06:23:25 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by iggyvilla on 2026-12-02T06:23:25Z.


Updated to 07d529ea addressing @Foniass's review:\n- Size & scope: removed the 407-line guest_write_probe.rs OS probe and the ws2_32 recv/recvfrom hooks (which did not track plain MEM_WRITE_WATCH memory), shrinking the diff from 997 to 624 lines (~420 runtime + ~200 tests).\n- Race-free pin protocol: moved FREEZE_LOCK, while_unpinned, meets_guarded_view, and the open_with wait directly into this PR (and removed public is_pinned), with a multi-threaded serialization test (while_unpinned_serializes_concurrent_protect_and_open).\n- Real guards::watch & enabled() coverage: added real_guarded_view_counts_as_writable_and_opens_on_kernel_write exercising a real read-only guards::watch view through writable() and kernel_write().\n- Honest scope & testing: noted explicitly that no runtime caller calls register yet (stacked #3601 and #3639 are the first callers), and added whole-workspace GPU test counts + 41aa60ce merge-base smoke.

<!-- greyfinch-sync:ivall/xcl:comment:7336959281 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3597#issuecomment-7336959281). Originally posted by [iggyvilla](https://github.com/iggyvilla) on 2026-12-02T06:23:25Z. --- Updated to `07d529ea` addressing @Foniass's review:\n- **Size & scope**: removed the 407-line `guest_write_probe.rs` OS probe and the `ws2_32` `recv`/`recvfrom` hooks (which did not track plain `MEM_WRITE_WATCH` memory), shrinking the diff from 997 to 624 lines (~420 runtime + ~200 tests).\n- **Race-free pin protocol**: moved `FREEZE_LOCK`, `while_unpinned`, `meets_guarded_view`, and the `open_with` wait directly into this PR (and removed public `is_pinned`), with a multi-threaded serialization test (`while_unpinned_serializes_concurrent_protect_and_open`).\n- **Real `guards::watch` & `enabled()` coverage**: added `real_guarded_view_counts_as_writable_and_opens_on_kernel_write` exercising a real read-only `guards::watch` view through `writable()` and `kernel_write()`.\n- **Honest scope & testing**: noted explicitly that no runtime caller calls `register` yet (stacked #3601 and #3639 are the first callers), and added whole-workspace GPU test counts + `41aa60ce` merge-base smoke.
Foniass commented 2026-12-02 06:25:52 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-02T06:25:52Z.


Follow-up review (head 07d529ea, since 1b6f6748, diff read, not a merge-check):

  • recv into write-watched memory untracked: fixed; the recv / recvfrom hooks and their install in host.rs are gone, and the description no longer claims it.
  • The probe test asserts little: fixed; guest_write_probe.rs is gone, and the failing kernel write is asserted in a_kernel_write_into_a_protected_page_lands_once_bracketed (guest_write.rs ~482).
  • Racy pin protocol: partly fixed. while_unpinned now checks the pins and publishes FREEZE_AT / FREEZE_END under PINS, and open_with waits on an overlapping freeze; the new wait has a lost wakeup (below).
  • Call-site changes untested: partly fixed. real_guarded_view_counts_as_writable_and_opens_on_kernel_write (~557) drives writable and kernel_write on a real guards::watch view, but no test reaches the changed call sites (eh.rs ~536, cpu_writes.rs ~149 / ~189 / ~230, frame.rs ~381, dstorage.rs ~896 / ~941, parallel.rs ~491, vfs_hooks.rs ~537).
  • No caller of register: still open, now stated in the description. With the switch on ANY stays false, so the pins, touch, the freeze wait and the kernel_write retry never run.
  • Size and scope: partly fixed; 645 changed lines (about 440 runtime), still over ~400, with the registry and freeze protocol here without their first user.

New:

  • open_with can spin forever after a freeze ends. It reads FREEZE_END (~330) and then FREEZES_DONE (~332), but Done::drop (~144-145) clears FREEZE_END and bumps FREEZES_DONE without taking PINS, so it can run between the two loads; the writer then waits (~336) for a count that has already moved, until some later while_unpinned succeeds, and one that overlaps the writer's pinned pages returns at ~135 without bumping it. A ReadFile or DirectStorage write over those pages can hang. Reading FREEZES_DONE before FREEZE_END, or bumping it under PINS, closes this; the description's "race-free while_unpinned()" does not hold as is.
  • The stacked PRs no longer apply. #3601 and #3639 are on the old commit 1b6f6748; #3601 adds its own while_unpinned and meets_guarded_view, which this head now defines, so it conflicts.

Fine: with the switch off the default path is unchanged; the range merge / split and covers logic is correct; the new tests assert real outcomes.

AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7337005484 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3597#issuecomment-7337005484). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T06:25:52Z. --- Follow-up review (head 07d529ea, since 1b6f6748, diff read, not a merge-check): - **`recv` into write-watched memory untracked:** fixed; the `recv` / `recvfrom` hooks and their install in `host.rs` are gone, and the description no longer claims it. - **The probe test asserts little:** fixed; `guest_write_probe.rs` is gone, and the failing kernel write is asserted in `a_kernel_write_into_a_protected_page_lands_once_bracketed` (`guest_write.rs` ~482). - **Racy pin protocol:** partly fixed. `while_unpinned` now checks the pins and publishes `FREEZE_AT` / `FREEZE_END` under `PINS`, and `open_with` waits on an overlapping freeze; the new wait has a lost wakeup (below). - **Call-site changes untested:** partly fixed. `real_guarded_view_counts_as_writable_and_opens_on_kernel_write` (~557) drives `writable` and `kernel_write` on a real `guards::watch` view, but no test reaches the changed call sites (`eh.rs` ~536, `cpu_writes.rs` ~149 / ~189 / ~230, `frame.rs` ~381, `dstorage.rs` ~896 / ~941, `parallel.rs` ~491, `vfs_hooks.rs` ~537). - **No caller of `register`:** still open, now stated in the description. With the switch on `ANY` stays false, so the pins, `touch`, the freeze wait and the `kernel_write` retry never run. - **Size and scope:** partly fixed; 645 changed lines (about 440 runtime), still over ~400, with the registry and freeze protocol here without their first user. New: - **`open_with` can spin forever after a freeze ends.** It reads `FREEZE_END` (~330) and then `FREEZES_DONE` (~332), but `Done::drop` (~144-145) clears `FREEZE_END` and bumps `FREEZES_DONE` without taking `PINS`, so it can run between the two loads; the writer then waits (~336) for a count that has already moved, until some later `while_unpinned` succeeds, and one that overlaps the writer's pinned pages returns at ~135 without bumping it. A `ReadFile` or DirectStorage write over those pages can hang. Reading `FREEZES_DONE` before `FREEZE_END`, or bumping it under `PINS`, closes this; the description's "race-free `while_unpinned()`" does not hold as is. - **The stacked PRs no longer apply.** #3601 and #3639 are on the old commit `1b6f6748`; #3601 adds its own `while_unpinned` and `meets_guarded_view`, which this head now defines, so it conflicts. Fine: with the switch off the default path is unchanged; the range merge / split and `covers` logic is correct; the new tests assert real outcomes. AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.
Foniass commented 2026-12-02 13:05:17 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-02T13:05:17Z.


merge-check
base: 41aa60ce84
head: 07d529ea94
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2968 passed, 9 failed, 49 ignored; SKIPPED: 28 (20 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 1 no heap windows, 1 cannot disable the driver cache, 3 others; the same set as on amd-dev); failing: gpu::recomp::lower_dxil::tests::f32_programs_on_the_gpu, gpu::recomp::tests::gpu_fract_f32_edges, hle::d3d12x::sparse::tests::private_physical_pages_reach_the_gpu_on_mapping, hle::d3d12x::title_textures::tests::placed_title_textures_share_vram_and_preserve_pixels, hle::d3d12x::title_textures::tests::remapped_pages_are_compared_with_what_they_held, hle::d3d12x::title_textures::tests::stream_recheck_keeps_the_whole_upload_baseline_over_partial_uploads, hle::d3d12x::title_textures::tests::stream_recheck_partial_upload_without_an_entry_queues_a_whole_upload, hle::d3d12x::title_textures::tests::stream_recheck_schedule_catches_late_writes_and_resets_milestones (the same tests fail on amd-dev 41aa60ce alone on this card, so none is from this PR)
review: read by one reviewer at this same head; the review is at https://github.com/xcl-dev/xcl/pull/3597#issuecomment-7337005484 and its findings stand. Most serious: a lost wakeup: Done::drop (guest_write.rs ~144) clears FREEZE_END and bumps FREEZES_DONE without taking PINS, so open_with (~330-336) can spin forever once #3639 / #3601 call it; it is also over 400 lines and adds the protocol without its first user.
performance: 60 s smoke of a retail title, amd-dev 41aa60ce vs this merge (07d529ea): 1671 -> 1687 frames shown (100 %; last presents per 2 s: 60 60 60), peak commit 16722 -> 16817 MB, 0 device removals, 0 crashes.
verdict: not yet: a lost wakeup: Done::drop (guest_write.rs ~144) clears FREEZE_END and bumps FREEZES_DONE without taking PINS, so open_with (~330-336) can spin forever once #3639 / #3601 call it; it is also over 400 lines and adds the protocol without its first user (see the review)
hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5

AI-written and posted by Foniass without a human check of each point.

<!-- greyfinch-sync:ivall/xcl:comment:7346330286 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3597#issuecomment-7346330286). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-02T13:05:17Z. --- merge-check base: 41aa60ce842060a597b7e8724896f7bf6a031af5 head: 07d529ea9478b48cb9443b2e7aa9a830a48327e0 merge: clean build: cargo build --workspace -> ok tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2968 passed, 9 failed, 49 ignored; SKIPPED: 28 (20 no wave64, 2 no d3d12SDKLayers.dll, 1 no D3D12 debug layer, 1 no heap windows, 1 cannot disable the driver cache, 3 others; the same set as on amd-dev); failing: gpu::recomp::lower_dxil::tests::f32_programs_on_the_gpu, gpu::recomp::tests::gpu_fract_f32_edges, hle::d3d12x::sparse::tests::private_physical_pages_reach_the_gpu_on_mapping, hle::d3d12x::title_textures::tests::placed_title_textures_share_vram_and_preserve_pixels, hle::d3d12x::title_textures::tests::remapped_pages_are_compared_with_what_they_held, hle::d3d12x::title_textures::tests::stream_recheck_keeps_the_whole_upload_baseline_over_partial_uploads, hle::d3d12x::title_textures::tests::stream_recheck_partial_upload_without_an_entry_queues_a_whole_upload, hle::d3d12x::title_textures::tests::stream_recheck_schedule_catches_late_writes_and_resets_milestones (the same tests fail on amd-dev 41aa60ce alone on this card, so none is from this PR) review: read by one reviewer at this same head; the review is at https://github.com/xcl-dev/xcl/pull/3597#issuecomment-7337005484 and its findings stand. Most serious: a lost wakeup: `Done::drop` (`guest_write.rs` ~144) clears `FREEZE_END` and bumps `FREEZES_DONE` without taking `PINS`, so `open_with` (~330-336) can spin forever once #3639 / #3601 call it; it is also over 400 lines and adds the protocol without its first user. performance: 60 s smoke of a retail title, amd-dev 41aa60ce vs this merge (07d529ea): 1671 -> 1687 frames shown (100 %; last presents per 2 s: 60 60 60), peak commit 16722 -> 16817 MB, 0 device removals, 0 crashes. verdict: not yet: a lost wakeup: `Done::drop` (`guest_write.rs` ~144) clears `FREEZE_END` and bumps `FREEZES_DONE` without taking `PINS`, so `open_with` (~330-336) can spin forever once #3639 / #3601 call it; it is also over 400 lines and adds the protocol without its first user (see the review) hardware / tool and model: RTX 5070 Ti (driver 621.14), Ryzen 7 7800X3D, Windows 11 26300 / Claude Code with Claude Opus 5.5 AI-written and posted by Foniass without a human check of each point.
bmjask commented 2026-12-02 15:33:51 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T15:33:51Z.

Code review location: crates/xcl/src/hle/kernelx/guest_write.rs; line 330

@@ -0,0 +1,582 @@
+//! Writes into the title's memory by XCL or by a kernel call, where XCL itself may have made the
+//! pages read-only or no-access (`XCL_GUEST_WRITE_GUARD=1`; default off).
+//!
+//! XCL protects title pages to learn about CPU writes (`guards`, `XCL_PAGE_ALIAS=1`) and may do
+//! so for more memory (read-only cold blocks, no-access GPU-written pages). A user-mode store
+//! there faults and the protector's handler opens the page. A kernel call does not fault: on a
+//! read-only or no-access page `ReadFile` (buffered, NO_BUFFERING, overlapped) and
+//! `WriteProcessMemory` fail with ERROR_NOACCESS, `NtReadFile` with STATUS_ACCESS_VIOLATION,
+//! and `NtWriteVirtualMemory` with STATUS_PARTIAL_COPY; nothing lands and no handler runs. So,
+//! behind the switch:
+//!
+//! - `writable` answers "can XCL write here" for the pre-checks that asked `VirtualQuery` for a
+//!   writable protection: a page XCL protected counts as writable (a store faults and is opened);
+//! - `open` brackets a kernel call's (or XCL's) write: lazy pages are committed and guarded views
+//!   opened (`lazy::ensure`, as without the switch), and pages of ranges a protector registered
+//!   are pinned (the protector must not protect them again) and touched by a no-op atomic RMW,
+//!   so the protector's fault handler runs before the kernel writes;
+//! - `kernel_write` is `open` around a write that returns a status, with one retry.
+//!
+//! A protector calls `register` / `unregister` for the ranges whose pages it may protect,
+//! serializes `VirtualProtect` against active writes via `while_unpinned`, and makes a page
+//! writable from its vectored handler on a write fault (access 1) there. Off, every function
+//! here does what the code did before: `writable` is false, `open` is `lazy::ensure`.
+
+use std::collections::{BTreeMap, HashMap};
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering};
+use std::sync::{Mutex, OnceLock, RwLock};
+
+use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_GUARD, PAGE_NOACCESS, PAGE_READONLY, PAGE_READWRITE};
+
+/// the protection granule (`VirtualProtect` works on 4 KiB pages)
+pub const STEP: usize = 0x1000;
+
+#[cfg(test)]
+static FORCE_TEST: AtomicBool = AtomicBool::new(false);
+
+/// `XCL_GUEST_WRITE_GUARD=1` turns the guest-write guard on (default: off).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    if FORCE_TEST.load(Ordering::Acquire) {
+        return true;
+    }
+    static ON: OnceLock<bool> = OnceLock::new();
+    *ON.get_or_init(|| std::env::var("XCL_GUEST_WRITE_GUARD").is_ok_and(|v| v.trim() == "1"))
+}
+
+/// ranges a protector registered: start → end
+static RANGES: RwLock<BTreeMap<usize, usize>> = RwLock::new(BTreeMap::new());
+/// Whether any range was ever registered: `open` takes no lock before then.
+static ANY: AtomicBool = AtomicBool::new(false);
+/// 4 KiB pages pinned writable by a write going on → how many writes
+static PINS: Mutex<Option<HashMap<usize, usize>>> = Mutex::new(None);
+/// overlapped reads into registered ranges: (the OVERLAPPED, its pins), released when done
+static PENDING: Mutex<Vec<(usize, Vec<usize>)>> = Mutex::new(Vec::new());
+/// calls a retry repaired, and calls that still failed (logged, a few each)
+static REPAIRED: AtomicUsize = AtomicUsize::new(0);
+static FAILED: AtomicUsize = AtomicUsize::new(0);
+
+/// `[p, p + len)` may hold pages a protector makes read-only or no-access.
+pub fn register(p: usize, len: usize) {
+    if len == 0 {
+        return;
+    }
+    ANY.store(true, Ordering::Release);
+    let mut g = RANGES.write().unwrap_or_else(|e| e.into_inner());
+    insert_range(&mut g, p, p.saturating_add(len));
+}
+
+/// `[p, p + len)` is no longer protected (call it before the memory is freed or decommitted).
+pub fn unregister(p: usize, len: usize) {
+    let mut g = RANGES.write().unwrap_or_else(|e| e.into_inner());
+    remove_range(&mut g, p, p.saturating_add(len));
+}
+
+fn insert_range(m: &mut BTreeMap<usize, usize>, mut lo: usize, mut hi: usize) {
+    // merge with every range that touches [lo, hi)
+    let touching: Vec<(usize, usize)> = m.range(..=hi).rev().take_while(|&(_, &e)| e >= lo).map(|(&s, &e)| (s, e)).collect();
+    for (s, e) in touching {
+        m.remove(&s);
+        lo = lo.min(s);
+        hi = hi.max(e);
+    }
+    m.insert(lo, hi);
+}
+
+fn remove_range(m: &mut BTreeMap<usize, usize>, lo: usize, hi: usize) {
+    let hit: Vec<(usize, usize)> = m.range(..hi).rev().take_while(|&(_, &e)| e > lo).map(|(&s, &e)| (s, e)).collect();
+    for (s, e) in hit {
+        m.remove(&s);
+        if s < lo {
+            m.insert(s, lo);
+        }
+        if e > hi {
+            m.insert(hi, e);
+        }
+    }
+}
+
+fn in_ranges(m: &BTreeMap<usize, usize>, at: usize) -> bool {
+    m.range(..=at).next_back().is_some_and(|(_, &e)| at < e)
+}
+
+/// Whether XCL may have protected the page at `at` (a registered range or a guarded view).
+pub fn xcl_protected(at: usize) -> bool {
+    (ANY.load(Ordering::Acquire) && in_ranges(&RANGES.read().unwrap_or_else(|e| e.into_inner()), at)) || super::guards::is_view(at)
+}
+
+/// Range a protector is currently transitioning (`FREEZE_END == 0`: none), published under `PINS`
+/// so a concurrent `open_with` that pins an overlapping page waits until `protect` completes
+/// before touching it. `FREEZE_LOCK` serializes concurrent protectors without holding `PINS`
+/// across `VirtualProtect`.
+static FREEZE_LOCK: Mutex<()> = Mutex::new(());
+static FREEZE_AT: AtomicUsize = AtomicUsize::new(0);
+static FREEZE_END: AtomicUsize = AtomicUsize::new(0);
+static FREEZES_DONE: AtomicUsize = AtomicUsize::new(0);
+
+/// Run `protect` on `[p, p + n)` only if no 4 KiB page in it is currently pinned by a kernel
+/// write. The pin check and active-range mark happen under `PINS`; `protect` itself runs after
+/// `PINS` is released, and any concurrent `open` that pins an overlapping page waits until
+/// `protect` finishes before touching the page. Returns `false` if any page was pinned.
+pub fn while_unpinned(p: usize, n: usize, protect: impl FnOnce() -> bool) -> bool {
+    let _serial = FREEZE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+    release_done();
+    let (lo, hi) = (p & !(STEP - 1), p.saturating_add(n));
+    {
+        let g = PINS.lock().unwrap_or_else(|e| e.into_inner());
+        if let Some(m) = g.as_ref().filter(|m| !m.is_empty()) {
+            let pinned = if m.len() < n / STEP {
+                m.keys().any(|&k| k >= lo && k < hi)
+            } else {
+                (lo..hi).step_by(STEP).any(|k| m.contains_key(&k))
+            };
+            if pinned {
+                return false;
+            }
+        }
+        FREEZE_AT.store(lo, Ordering::Release);
+        FREEZE_END.store(hi, Ordering::Release);
+    }
+    struct Done;
+    impl Drop for Done {
+        fn drop(&mut self) {
+            FREEZE_END.store(0, Ordering::Release);
+            FREEZES_DONE.fetch_add(1, Ordering::AcqRel);
+        }
+    }
+    let _done = Done;
+    protect()
+}
+
+/// Whether `[p, p + n)` intersects a guarded view (`XCL_PAGE_ALIAS`): another protector owns it.
+pub fn meets_guarded_view(p: usize, n: usize) -> bool {
+    const VIEW: usize = 0x10000;
+    (p & !(VIEW - 1)..p.saturating_add(n)).step_by(VIEW).any(super::guards::is_view)
+}
+
+#[cfg(test)]
+fn is_pinned(at: usize) -> bool {
+    release_done();
+    PINS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| m.contains_key(&(at & !(STEP - 1))))
+}
+
+/// One region `VirtualQuery` describes: [base, end), committed?, protection.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub(crate) struct Region {
+    pub base: usize,
+    pub end: usize,
+    pub committed: bool,
+    pub protect: u32,
+}
+
+fn query(at: usize) -> Option<Region> {
+    let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
+    // SAFETY: VirtualQuery only reads the address space description.
+    if unsafe { VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) } == 0 {
+        return None;
+    }
+    let base = m.BaseAddress as usize;
+    Some(Region { base, end: base.saturating_add(m.RegionSize), committed: m.State == MEM_COMMIT, protect: m.Protect })
+}
+
+const WRITES: u32 = PAGE_READWRITE | PAGE_EXECUTE_READWRITE | 0x08 | 0x80; // + WRITECOPY, EXECUTE_WRITECOPY
+const PROTECTED: u32 = PAGE_READONLY | PAGE_NOACCESS | PAGE_EXECUTE_READ;
+
+/// Whether every byte of `[p, p + n)` is committed and either writable now or on a page XCL
+/// protected (`xcl`). `query` describes the region at an address.
+pub(crate) fn covers(p: usize, n: usize, mut query: impl FnMut(usize) -> Option<Region>, xcl: impl Fn(usize) -> bool) -> bool {
+    let Some(end) = p.checked_add(n) else { return false };
+    let mut at = p;
+    while at < end {
+        let Some(r) = query(at) else { return false };
+        if !r.committed || r.protect & PAGE_GUARD != 0 || r.end <= at {
+            return false;
+        }
+        let stop = r.end.min(end);
+        if r.protect & WRITES == 0 {
+            if r.protect & PROTECTED == 0 {
+                return false;
+            }
+            let mut page = at & !(STEP - 1);
+            while page < stop {
+                if !xcl(page) {
+                    return false;
+                }
+                let Some(next) = page.checked_add(STEP) else { break };
+                page = next;
+            }
+        }
+        at = stop;
+    }
+    true
+}
+
+/// With the switch on: whether XCL may write `[p, p + n)` – committed, and writable or protected
+/// by XCL (a store there faults and is opened; a kernel call goes through `open`). Off: false, so
+/// a pre-check `old || writable(..)` is the old one.
+pub fn writable(p: usize, n: usize) -> bool {
+    enabled() && n > 0 && covers(p, n, query, xcl_protected)
+}
+
+/// A write to `[p, p + n)` going on: lazy pages committed and guarded views open (`lazy::ensure`),
+/// pins on pages of registered ranges. Dropped when the write is over.
+#[must_use = "the pages stay open only while this lives"]
+pub struct Bracket {
+    opened: Option<super::guards::Opened>,
+    pins: Vec<usize>,
+}
+
+impl Drop for Bracket {
+    fn drop(&mut self) {
+        unpin(std::mem::take(&mut self.pins));
+    }
+}
+
+impl Bracket {
+    /// An overlapped read (`ov`) writes after its call returned: the pages stay open until done.
+    pub fn keep_until_done(mut self, ov: usize) {
+        if let Some(o) = self.opened.take() {
+            super::guards::open_until_done(o, ov);
+        }
+        let pins = std::mem::take(&mut self.pins);
+        if !pins.is_empty() {
+            PENDING.lock().unwrap_or_else(|e| e.into_inner()).push((ov, pins));
+        }
+    }
+
+    /// pages of registered ranges this write holds open
+    pub fn pinned(&self) -> usize {
+        self.pins.len()
+    }
+}
+
+fn unpin(pins: Vec<usize>) {
+    if pins.is_empty() {
+        return;
+    }
+    let mut g = PINS.lock().unwrap_or_else(|e| e.into_inner());
+    let m = g.get_or_insert_with(HashMap::new);
+    for p in pins {
+        if let Some(c) = m.get_mut(&p) {
+            *c -= 1;
+            if *c == 0 {
+                m.remove(&p);
+            }
+        }
+    }
+}
+
+fn release_done() {
+    let done: Vec<Vec<usize>> = {
+        let mut g = PENDING.lock().unwrap_or_else(|e| e.into_inner());
+        if g.is_empty() {
+            return;
+        }
+        let (done, pending): (Vec<_>, Vec<_>) = std::mem::take(&mut *g).into_iter().partition(|&(ov, _)| !super::guards::still_pending(ov));
+        *g = pending;
+        done.into_iter().map(|(_, p)| p).collect()
+    };
+    for p in done {
+        unpin(p);
+    }
+}
+
+/// Make each committed 4 KiB page of `[p, p + n)` that is not writable now and lies in `pins`
+/// take a write fault in user mode: a no-op atomic RMW, so the protector's handler opens it.
+unsafe fn touch(p: usize, n: usize, pins: &[usize]) {
+    for &page in pins {
+        let Some(r) = query(page) else { continue };
+        if r.committed && r.protect & WRITES == 0 && r.protect & PROTECTED != 0 {
+            let at = page.max(p);
+            debug_assert!(at < p + n);
+            (*(at as *const AtomicU8)).fetch_add(0, Ordering::Relaxed);
+        }
+    }
+}
+
+/// `[p, p + n)` is about to be written by a kernel call or by XCL (see the module's comment).
+pub fn open(p: usize, n: usize) -> Bracket {
+    open_with(enabled(), p, n)
+}
+
+pub(crate) fn open_with(on: bool, p: usize, n: usize) -> Bracket {
+    let opened = Some(super::lazy::ensure(p, n));
+    if !on || n == 0 || !ANY.load(Ordering::Acquire) {
+        return Bracket { opened, pins: Vec::new() };
+    }
+    release_done();
+    let end = p.saturating_add(n);
+    let pins: Vec<usize> = {
+        let g = RANGES.read().unwrap_or_else(|e| e.into_inner());
+        let mut v = Vec::new();
+        let mut page = p & !(STEP - 1);
+        while page < end {
+            if in_ranges(&g, page) {
+                v.push(page);
+            }
+            let Some(next) = page.checked_add(STEP) else { break };
+            page = next;
+        }
+        v
+    };
+    let mut wait_for = None;
+    if !pins.is_empty() {
+        let mut g = PINS.lock().unwrap_or_else(|e| e.into_inner());
+        let m = g.get_or_insert_with(HashMap::new);
+        for &page in &pins {
+            *m.entry(page).or_default() += 1;
+        }
+        let (fa, fe) = (FREEZE_AT.load(Ordering::Acquire), FREEZE_END.load(Ordering::Acquire));

Critical: open_with reads FREEZE_END and then FREEZES_DONE, and while_unpinned's Done::drop clears FREEZE_END and bumps FREEZES_DONE without holding PINS, so the snapshot can be taken after the protector has already finished, and the spin-wait waits for a completion that never comes. Thread A (hk_read_file or a DirectStorage kernel_write) pins pages under PINS and loads fe != 0 while protector B is in protect(). B returns, Done::drop sets FREEZE_END=0 and FREEZES_DONE=k+1, and A then loads FREEZES_DONE=k+1 as wait_for and spins in while FREEZES_DONE == k+1 { yield_now() } until some other while_unpinned completes. If none does, the title's ReadFile or the DirectStorage worker hangs at 100% CPU. Loading FREEZES_DONE before FREEZE_END, or publishing a generation under PINS, would fix it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4772035665 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3597#discussion_r4772035665). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:33:51Z. **Code review location:** `crates/xcl/src/hle/kernelx/guest_write.rs`; line 330 ~~~~diff @@ -0,0 +1,582 @@ +//! Writes into the title's memory by XCL or by a kernel call, where XCL itself may have made the +//! pages read-only or no-access (`XCL_GUEST_WRITE_GUARD=1`; default off). +//! +//! XCL protects title pages to learn about CPU writes (`guards`, `XCL_PAGE_ALIAS=1`) and may do +//! so for more memory (read-only cold blocks, no-access GPU-written pages). A user-mode store +//! there faults and the protector's handler opens the page. A kernel call does not fault: on a +//! read-only or no-access page `ReadFile` (buffered, NO_BUFFERING, overlapped) and +//! `WriteProcessMemory` fail with ERROR_NOACCESS, `NtReadFile` with STATUS_ACCESS_VIOLATION, +//! and `NtWriteVirtualMemory` with STATUS_PARTIAL_COPY; nothing lands and no handler runs. So, +//! behind the switch: +//! +//! - `writable` answers "can XCL write here" for the pre-checks that asked `VirtualQuery` for a +//! writable protection: a page XCL protected counts as writable (a store faults and is opened); +//! - `open` brackets a kernel call's (or XCL's) write: lazy pages are committed and guarded views +//! opened (`lazy::ensure`, as without the switch), and pages of ranges a protector registered +//! are pinned (the protector must not protect them again) and touched by a no-op atomic RMW, +//! so the protector's fault handler runs before the kernel writes; +//! - `kernel_write` is `open` around a write that returns a status, with one retry. +//! +//! A protector calls `register` / `unregister` for the ranges whose pages it may protect, +//! serializes `VirtualProtect` against active writes via `while_unpinned`, and makes a page +//! writable from its vectored handler on a write fault (access 1) there. Off, every function +//! here does what the code did before: `writable` is false, `open` is `lazy::ensure`. + +use std::collections::{BTreeMap, HashMap}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering}; +use std::sync::{Mutex, OnceLock, RwLock}; + +use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_GUARD, PAGE_NOACCESS, PAGE_READONLY, PAGE_READWRITE}; + +/// the protection granule (`VirtualProtect` works on 4 KiB pages) +pub const STEP: usize = 0x1000; + +#[cfg(test)] +static FORCE_TEST: AtomicBool = AtomicBool::new(false); + +/// `XCL_GUEST_WRITE_GUARD=1` turns the guest-write guard on (default: off). +pub fn enabled() -> bool { + #[cfg(test)] + if FORCE_TEST.load(Ordering::Acquire) { + return true; + } + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_GUEST_WRITE_GUARD").is_ok_and(|v| v.trim() == "1")) +} + +/// ranges a protector registered: start → end +static RANGES: RwLock<BTreeMap<usize, usize>> = RwLock::new(BTreeMap::new()); +/// Whether any range was ever registered: `open` takes no lock before then. +static ANY: AtomicBool = AtomicBool::new(false); +/// 4 KiB pages pinned writable by a write going on → how many writes +static PINS: Mutex<Option<HashMap<usize, usize>>> = Mutex::new(None); +/// overlapped reads into registered ranges: (the OVERLAPPED, its pins), released when done +static PENDING: Mutex<Vec<(usize, Vec<usize>)>> = Mutex::new(Vec::new()); +/// calls a retry repaired, and calls that still failed (logged, a few each) +static REPAIRED: AtomicUsize = AtomicUsize::new(0); +static FAILED: AtomicUsize = AtomicUsize::new(0); + +/// `[p, p + len)` may hold pages a protector makes read-only or no-access. +pub fn register(p: usize, len: usize) { + if len == 0 { + return; + } + ANY.store(true, Ordering::Release); + let mut g = RANGES.write().unwrap_or_else(|e| e.into_inner()); + insert_range(&mut g, p, p.saturating_add(len)); +} + +/// `[p, p + len)` is no longer protected (call it before the memory is freed or decommitted). +pub fn unregister(p: usize, len: usize) { + let mut g = RANGES.write().unwrap_or_else(|e| e.into_inner()); + remove_range(&mut g, p, p.saturating_add(len)); +} + +fn insert_range(m: &mut BTreeMap<usize, usize>, mut lo: usize, mut hi: usize) { + // merge with every range that touches [lo, hi) + let touching: Vec<(usize, usize)> = m.range(..=hi).rev().take_while(|&(_, &e)| e >= lo).map(|(&s, &e)| (s, e)).collect(); + for (s, e) in touching { + m.remove(&s); + lo = lo.min(s); + hi = hi.max(e); + } + m.insert(lo, hi); +} + +fn remove_range(m: &mut BTreeMap<usize, usize>, lo: usize, hi: usize) { + let hit: Vec<(usize, usize)> = m.range(..hi).rev().take_while(|&(_, &e)| e > lo).map(|(&s, &e)| (s, e)).collect(); + for (s, e) in hit { + m.remove(&s); + if s < lo { + m.insert(s, lo); + } + if e > hi { + m.insert(hi, e); + } + } +} + +fn in_ranges(m: &BTreeMap<usize, usize>, at: usize) -> bool { + m.range(..=at).next_back().is_some_and(|(_, &e)| at < e) +} + +/// Whether XCL may have protected the page at `at` (a registered range or a guarded view). +pub fn xcl_protected(at: usize) -> bool { + (ANY.load(Ordering::Acquire) && in_ranges(&RANGES.read().unwrap_or_else(|e| e.into_inner()), at)) || super::guards::is_view(at) +} + +/// Range a protector is currently transitioning (`FREEZE_END == 0`: none), published under `PINS` +/// so a concurrent `open_with` that pins an overlapping page waits until `protect` completes +/// before touching it. `FREEZE_LOCK` serializes concurrent protectors without holding `PINS` +/// across `VirtualProtect`. +static FREEZE_LOCK: Mutex<()> = Mutex::new(()); +static FREEZE_AT: AtomicUsize = AtomicUsize::new(0); +static FREEZE_END: AtomicUsize = AtomicUsize::new(0); +static FREEZES_DONE: AtomicUsize = AtomicUsize::new(0); + +/// Run `protect` on `[p, p + n)` only if no 4 KiB page in it is currently pinned by a kernel +/// write. The pin check and active-range mark happen under `PINS`; `protect` itself runs after +/// `PINS` is released, and any concurrent `open` that pins an overlapping page waits until +/// `protect` finishes before touching the page. Returns `false` if any page was pinned. +pub fn while_unpinned(p: usize, n: usize, protect: impl FnOnce() -> bool) -> bool { + let _serial = FREEZE_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + release_done(); + let (lo, hi) = (p & !(STEP - 1), p.saturating_add(n)); + { + let g = PINS.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(m) = g.as_ref().filter(|m| !m.is_empty()) { + let pinned = if m.len() < n / STEP { + m.keys().any(|&k| k >= lo && k < hi) + } else { + (lo..hi).step_by(STEP).any(|k| m.contains_key(&k)) + }; + if pinned { + return false; + } + } + FREEZE_AT.store(lo, Ordering::Release); + FREEZE_END.store(hi, Ordering::Release); + } + struct Done; + impl Drop for Done { + fn drop(&mut self) { + FREEZE_END.store(0, Ordering::Release); + FREEZES_DONE.fetch_add(1, Ordering::AcqRel); + } + } + let _done = Done; + protect() +} + +/// Whether `[p, p + n)` intersects a guarded view (`XCL_PAGE_ALIAS`): another protector owns it. +pub fn meets_guarded_view(p: usize, n: usize) -> bool { + const VIEW: usize = 0x10000; + (p & !(VIEW - 1)..p.saturating_add(n)).step_by(VIEW).any(super::guards::is_view) +} + +#[cfg(test)] +fn is_pinned(at: usize) -> bool { + release_done(); + PINS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| m.contains_key(&(at & !(STEP - 1)))) +} + +/// One region `VirtualQuery` describes: [base, end), committed?, protection. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Region { + pub base: usize, + pub end: usize, + pub committed: bool, + pub protect: u32, +} + +fn query(at: usize) -> Option<Region> { + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: VirtualQuery only reads the address space description. + if unsafe { VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) } == 0 { + return None; + } + let base = m.BaseAddress as usize; + Some(Region { base, end: base.saturating_add(m.RegionSize), committed: m.State == MEM_COMMIT, protect: m.Protect }) +} + +const WRITES: u32 = PAGE_READWRITE | PAGE_EXECUTE_READWRITE | 0x08 | 0x80; // + WRITECOPY, EXECUTE_WRITECOPY +const PROTECTED: u32 = PAGE_READONLY | PAGE_NOACCESS | PAGE_EXECUTE_READ; + +/// Whether every byte of `[p, p + n)` is committed and either writable now or on a page XCL +/// protected (`xcl`). `query` describes the region at an address. +pub(crate) fn covers(p: usize, n: usize, mut query: impl FnMut(usize) -> Option<Region>, xcl: impl Fn(usize) -> bool) -> bool { + let Some(end) = p.checked_add(n) else { return false }; + let mut at = p; + while at < end { + let Some(r) = query(at) else { return false }; + if !r.committed || r.protect & PAGE_GUARD != 0 || r.end <= at { + return false; + } + let stop = r.end.min(end); + if r.protect & WRITES == 0 { + if r.protect & PROTECTED == 0 { + return false; + } + let mut page = at & !(STEP - 1); + while page < stop { + if !xcl(page) { + return false; + } + let Some(next) = page.checked_add(STEP) else { break }; + page = next; + } + } + at = stop; + } + true +} + +/// With the switch on: whether XCL may write `[p, p + n)` – committed, and writable or protected +/// by XCL (a store there faults and is opened; a kernel call goes through `open`). Off: false, so +/// a pre-check `old || writable(..)` is the old one. +pub fn writable(p: usize, n: usize) -> bool { + enabled() && n > 0 && covers(p, n, query, xcl_protected) +} + +/// A write to `[p, p + n)` going on: lazy pages committed and guarded views open (`lazy::ensure`), +/// pins on pages of registered ranges. Dropped when the write is over. +#[must_use = "the pages stay open only while this lives"] +pub struct Bracket { + opened: Option<super::guards::Opened>, + pins: Vec<usize>, +} + +impl Drop for Bracket { + fn drop(&mut self) { + unpin(std::mem::take(&mut self.pins)); + } +} + +impl Bracket { + /// An overlapped read (`ov`) writes after its call returned: the pages stay open until done. + pub fn keep_until_done(mut self, ov: usize) { + if let Some(o) = self.opened.take() { + super::guards::open_until_done(o, ov); + } + let pins = std::mem::take(&mut self.pins); + if !pins.is_empty() { + PENDING.lock().unwrap_or_else(|e| e.into_inner()).push((ov, pins)); + } + } + + /// pages of registered ranges this write holds open + pub fn pinned(&self) -> usize { + self.pins.len() + } +} + +fn unpin(pins: Vec<usize>) { + if pins.is_empty() { + return; + } + let mut g = PINS.lock().unwrap_or_else(|e| e.into_inner()); + let m = g.get_or_insert_with(HashMap::new); + for p in pins { + if let Some(c) = m.get_mut(&p) { + *c -= 1; + if *c == 0 { + m.remove(&p); + } + } + } +} + +fn release_done() { + let done: Vec<Vec<usize>> = { + let mut g = PENDING.lock().unwrap_or_else(|e| e.into_inner()); + if g.is_empty() { + return; + } + let (done, pending): (Vec<_>, Vec<_>) = std::mem::take(&mut *g).into_iter().partition(|&(ov, _)| !super::guards::still_pending(ov)); + *g = pending; + done.into_iter().map(|(_, p)| p).collect() + }; + for p in done { + unpin(p); + } +} + +/// Make each committed 4 KiB page of `[p, p + n)` that is not writable now and lies in `pins` +/// take a write fault in user mode: a no-op atomic RMW, so the protector's handler opens it. +unsafe fn touch(p: usize, n: usize, pins: &[usize]) { + for &page in pins { + let Some(r) = query(page) else { continue }; + if r.committed && r.protect & WRITES == 0 && r.protect & PROTECTED != 0 { + let at = page.max(p); + debug_assert!(at < p + n); + (*(at as *const AtomicU8)).fetch_add(0, Ordering::Relaxed); + } + } +} + +/// `[p, p + n)` is about to be written by a kernel call or by XCL (see the module's comment). +pub fn open(p: usize, n: usize) -> Bracket { + open_with(enabled(), p, n) +} + +pub(crate) fn open_with(on: bool, p: usize, n: usize) -> Bracket { + let opened = Some(super::lazy::ensure(p, n)); + if !on || n == 0 || !ANY.load(Ordering::Acquire) { + return Bracket { opened, pins: Vec::new() }; + } + release_done(); + let end = p.saturating_add(n); + let pins: Vec<usize> = { + let g = RANGES.read().unwrap_or_else(|e| e.into_inner()); + let mut v = Vec::new(); + let mut page = p & !(STEP - 1); + while page < end { + if in_ranges(&g, page) { + v.push(page); + } + let Some(next) = page.checked_add(STEP) else { break }; + page = next; + } + v + }; + let mut wait_for = None; + if !pins.is_empty() { + let mut g = PINS.lock().unwrap_or_else(|e| e.into_inner()); + let m = g.get_or_insert_with(HashMap::new); + for &page in &pins { + *m.entry(page).or_default() += 1; + } + let (fa, fe) = (FREEZE_AT.load(Ordering::Acquire), FREEZE_END.load(Ordering::Acquire)); ~~~~ --- **Critical**: `open_with` reads FREEZE_END and then FREEZES_DONE, and `while_unpinned`'s `Done::drop` clears FREEZE_END and bumps FREEZES_DONE without holding PINS, so the snapshot can be taken after the protector has already finished, and the spin-wait waits for a completion that never comes. Thread A (`hk_read_file` or a DirectStorage `kernel_write`) pins pages under PINS and loads fe != 0 while protector B is in `protect()`. B returns, `Done::drop` sets FREEZE_END=0 and FREEZES_DONE=k+1, and A then loads FREEZES_DONE=k+1 as `wait_for` and spins in `while FREEZES_DONE == k+1 { yield_now() }` until some other `while_unpinned` completes. If none does, the title's ReadFile or the DirectStorage worker hangs at 100% CPU. Loading FREEZES_DONE before FREEZE_END, or publishing a generation under PINS, would fix it.
bmjask commented 2026-12-02 15:33:51 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T15:33:51Z.

Code review location: crates/xcl/src/hle/kernelx/guest_write.rs; line 290

@@ -0,0 +1,582 @@
+//! Writes into the title's memory by XCL or by a kernel call, where XCL itself may have made the
+//! pages read-only or no-access (`XCL_GUEST_WRITE_GUARD=1`; default off).
+//!
+//! XCL protects title pages to learn about CPU writes (`guards`, `XCL_PAGE_ALIAS=1`) and may do
+//! so for more memory (read-only cold blocks, no-access GPU-written pages). A user-mode store
+//! there faults and the protector's handler opens the page. A kernel call does not fault: on a
+//! read-only or no-access page `ReadFile` (buffered, NO_BUFFERING, overlapped) and
+//! `WriteProcessMemory` fail with ERROR_NOACCESS, `NtReadFile` with STATUS_ACCESS_VIOLATION,
+//! and `NtWriteVirtualMemory` with STATUS_PARTIAL_COPY; nothing lands and no handler runs. So,
+//! behind the switch:
+//!
+//! - `writable` answers "can XCL write here" for the pre-checks that asked `VirtualQuery` for a
+//!   writable protection: a page XCL protected counts as writable (a store faults and is opened);
+//! - `open` brackets a kernel call's (or XCL's) write: lazy pages are committed and guarded views
+//!   opened (`lazy::ensure`, as without the switch), and pages of ranges a protector registered
+//!   are pinned (the protector must not protect them again) and touched by a no-op atomic RMW,
+//!   so the protector's fault handler runs before the kernel writes;
+//! - `kernel_write` is `open` around a write that returns a status, with one retry.
+//!
+//! A protector calls `register` / `unregister` for the ranges whose pages it may protect,
+//! serializes `VirtualProtect` against active writes via `while_unpinned`, and makes a page
+//! writable from its vectored handler on a write fault (access 1) there. Off, every function
+//! here does what the code did before: `writable` is false, `open` is `lazy::ensure`.
+
+use std::collections::{BTreeMap, HashMap};
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering};
+use std::sync::{Mutex, OnceLock, RwLock};
+
+use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_GUARD, PAGE_NOACCESS, PAGE_READONLY, PAGE_READWRITE};
+
+/// the protection granule (`VirtualProtect` works on 4 KiB pages)
+pub const STEP: usize = 0x1000;
+
+#[cfg(test)]
+static FORCE_TEST: AtomicBool = AtomicBool::new(false);
+
+/// `XCL_GUEST_WRITE_GUARD=1` turns the guest-write guard on (default: off).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    if FORCE_TEST.load(Ordering::Acquire) {
+        return true;
+    }
+    static ON: OnceLock<bool> = OnceLock::new();
+    *ON.get_or_init(|| std::env::var("XCL_GUEST_WRITE_GUARD").is_ok_and(|v| v.trim() == "1"))
+}
+
+/// ranges a protector registered: start → end
+static RANGES: RwLock<BTreeMap<usize, usize>> = RwLock::new(BTreeMap::new());
+/// Whether any range was ever registered: `open` takes no lock before then.
+static ANY: AtomicBool = AtomicBool::new(false);
+/// 4 KiB pages pinned writable by a write going on → how many writes
+static PINS: Mutex<Option<HashMap<usize, usize>>> = Mutex::new(None);
+/// overlapped reads into registered ranges: (the OVERLAPPED, its pins), released when done
+static PENDING: Mutex<Vec<(usize, Vec<usize>)>> = Mutex::new(Vec::new());
+/// calls a retry repaired, and calls that still failed (logged, a few each)
+static REPAIRED: AtomicUsize = AtomicUsize::new(0);
+static FAILED: AtomicUsize = AtomicUsize::new(0);
+
+/// `[p, p + len)` may hold pages a protector makes read-only or no-access.
+pub fn register(p: usize, len: usize) {
+    if len == 0 {
+        return;
+    }
+    ANY.store(true, Ordering::Release);
+    let mut g = RANGES.write().unwrap_or_else(|e| e.into_inner());
+    insert_range(&mut g, p, p.saturating_add(len));
+}
+
+/// `[p, p + len)` is no longer protected (call it before the memory is freed or decommitted).
+pub fn unregister(p: usize, len: usize) {
+    let mut g = RANGES.write().unwrap_or_else(|e| e.into_inner());
+    remove_range(&mut g, p, p.saturating_add(len));
+}
+
+fn insert_range(m: &mut BTreeMap<usize, usize>, mut lo: usize, mut hi: usize) {
+    // merge with every range that touches [lo, hi)
+    let touching: Vec<(usize, usize)> = m.range(..=hi).rev().take_while(|&(_, &e)| e >= lo).map(|(&s, &e)| (s, e)).collect();
+    for (s, e) in touching {
+        m.remove(&s);
+        lo = lo.min(s);
+        hi = hi.max(e);
+    }
+    m.insert(lo, hi);
+}
+
+fn remove_range(m: &mut BTreeMap<usize, usize>, lo: usize, hi: usize) {
+    let hit: Vec<(usize, usize)> = m.range(..hi).rev().take_while(|&(_, &e)| e > lo).map(|(&s, &e)| (s, e)).collect();
+    for (s, e) in hit {
+        m.remove(&s);
+        if s < lo {
+            m.insert(s, lo);
+        }
+        if e > hi {
+            m.insert(hi, e);
+        }
+    }
+}
+
+fn in_ranges(m: &BTreeMap<usize, usize>, at: usize) -> bool {
+    m.range(..=at).next_back().is_some_and(|(_, &e)| at < e)
+}
+
+/// Whether XCL may have protected the page at `at` (a registered range or a guarded view).
+pub fn xcl_protected(at: usize) -> bool {
+    (ANY.load(Ordering::Acquire) && in_ranges(&RANGES.read().unwrap_or_else(|e| e.into_inner()), at)) || super::guards::is_view(at)
+}
+
+/// Range a protector is currently transitioning (`FREEZE_END == 0`: none), published under `PINS`
+/// so a concurrent `open_with` that pins an overlapping page waits until `protect` completes
+/// before touching it. `FREEZE_LOCK` serializes concurrent protectors without holding `PINS`
+/// across `VirtualProtect`.
+static FREEZE_LOCK: Mutex<()> = Mutex::new(());
+static FREEZE_AT: AtomicUsize = AtomicUsize::new(0);
+static FREEZE_END: AtomicUsize = AtomicUsize::new(0);
+static FREEZES_DONE: AtomicUsize = AtomicUsize::new(0);
+
+/// Run `protect` on `[p, p + n)` only if no 4 KiB page in it is currently pinned by a kernel
+/// write. The pin check and active-range mark happen under `PINS`; `protect` itself runs after
+/// `PINS` is released, and any concurrent `open` that pins an overlapping page waits until
+/// `protect` finishes before touching the page. Returns `false` if any page was pinned.
+pub fn while_unpinned(p: usize, n: usize, protect: impl FnOnce() -> bool) -> bool {
+    let _serial = FREEZE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+    release_done();
+    let (lo, hi) = (p & !(STEP - 1), p.saturating_add(n));
+    {
+        let g = PINS.lock().unwrap_or_else(|e| e.into_inner());
+        if let Some(m) = g.as_ref().filter(|m| !m.is_empty()) {
+            let pinned = if m.len() < n / STEP {
+                m.keys().any(|&k| k >= lo && k < hi)
+            } else {
+                (lo..hi).step_by(STEP).any(|k| m.contains_key(&k))
+            };
+            if pinned {
+                return false;
+            }
+        }
+        FREEZE_AT.store(lo, Ordering::Release);
+        FREEZE_END.store(hi, Ordering::Release);
+    }
+    struct Done;
+    impl Drop for Done {
+        fn drop(&mut self) {
+            FREEZE_END.store(0, Ordering::Release);
+            FREEZES_DONE.fetch_add(1, Ordering::AcqRel);
+        }
+    }
+    let _done = Done;
+    protect()
+}
+
+/// Whether `[p, p + n)` intersects a guarded view (`XCL_PAGE_ALIAS`): another protector owns it.
+pub fn meets_guarded_view(p: usize, n: usize) -> bool {
+    const VIEW: usize = 0x10000;
+    (p & !(VIEW - 1)..p.saturating_add(n)).step_by(VIEW).any(super::guards::is_view)
+}
+
+#[cfg(test)]
+fn is_pinned(at: usize) -> bool {
+    release_done();
+    PINS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| m.contains_key(&(at & !(STEP - 1))))
+}
+
+/// One region `VirtualQuery` describes: [base, end), committed?, protection.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub(crate) struct Region {
+    pub base: usize,
+    pub end: usize,
+    pub committed: bool,
+    pub protect: u32,
+}
+
+fn query(at: usize) -> Option<Region> {
+    let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
+    // SAFETY: VirtualQuery only reads the address space description.
+    if unsafe { VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) } == 0 {
+        return None;
+    }
+    let base = m.BaseAddress as usize;
+    Some(Region { base, end: base.saturating_add(m.RegionSize), committed: m.State == MEM_COMMIT, protect: m.Protect })
+}
+
+const WRITES: u32 = PAGE_READWRITE | PAGE_EXECUTE_READWRITE | 0x08 | 0x80; // + WRITECOPY, EXECUTE_WRITECOPY
+const PROTECTED: u32 = PAGE_READONLY | PAGE_NOACCESS | PAGE_EXECUTE_READ;
+
+/// Whether every byte of `[p, p + n)` is committed and either writable now or on a page XCL
+/// protected (`xcl`). `query` describes the region at an address.
+pub(crate) fn covers(p: usize, n: usize, mut query: impl FnMut(usize) -> Option<Region>, xcl: impl Fn(usize) -> bool) -> bool {
+    let Some(end) = p.checked_add(n) else { return false };
+    let mut at = p;
+    while at < end {
+        let Some(r) = query(at) else { return false };
+        if !r.committed || r.protect & PAGE_GUARD != 0 || r.end <= at {
+            return false;
+        }
+        let stop = r.end.min(end);
+        if r.protect & WRITES == 0 {
+            if r.protect & PROTECTED == 0 {
+                return false;
+            }
+            let mut page = at & !(STEP - 1);
+            while page < stop {
+                if !xcl(page) {
+                    return false;
+                }
+                let Some(next) = page.checked_add(STEP) else { break };
+                page = next;
+            }
+        }
+        at = stop;
+    }
+    true
+}
+
+/// With the switch on: whether XCL may write `[p, p + n)` – committed, and writable or protected
+/// by XCL (a store there faults and is opened; a kernel call goes through `open`). Off: false, so
+/// a pre-check `old || writable(..)` is the old one.
+pub fn writable(p: usize, n: usize) -> bool {
+    enabled() && n > 0 && covers(p, n, query, xcl_protected)
+}
+
+/// A write to `[p, p + n)` going on: lazy pages committed and guarded views open (`lazy::ensure`),
+/// pins on pages of registered ranges. Dropped when the write is over.
+#[must_use = "the pages stay open only while this lives"]
+pub struct Bracket {
+    opened: Option<super::guards::Opened>,
+    pins: Vec<usize>,
+}
+
+impl Drop for Bracket {
+    fn drop(&mut self) {
+        unpin(std::mem::take(&mut self.pins));
+    }
+}
+
+impl Bracket {
+    /// An overlapped read (`ov`) writes after its call returned: the pages stay open until done.
+    pub fn keep_until_done(mut self, ov: usize) {
+        if let Some(o) = self.opened.take() {
+            super::guards::open_until_done(o, ov);
+        }
+        let pins = std::mem::take(&mut self.pins);
+        if !pins.is_empty() {
+            PENDING.lock().unwrap_or_else(|e| e.into_inner()).push((ov, pins));
+        }
+    }
+
+    /// pages of registered ranges this write holds open
+    pub fn pinned(&self) -> usize {
+        self.pins.len()
+    }
+}
+
+fn unpin(pins: Vec<usize>) {
+    if pins.is_empty() {
+        return;
+    }
+    let mut g = PINS.lock().unwrap_or_else(|e| e.into_inner());
+    let m = g.get_or_insert_with(HashMap::new);
+    for p in pins {
+        if let Some(c) = m.get_mut(&p) {
+            *c -= 1;
+            if *c == 0 {
+                m.remove(&p);
+            }
+        }
+    }
+}
+
+fn release_done() {
+    let done: Vec<Vec<usize>> = {
+        let mut g = PENDING.lock().unwrap_or_else(|e| e.into_inner());
+        if g.is_empty() {
+            return;
+        }
+        let (done, pending): (Vec<_>, Vec<_>) = std::mem::take(&mut *g).into_iter().partition(|&(ov, _)| !super::guards::still_pending(ov));
+        *g = pending;
+        done.into_iter().map(|(_, p)| p).collect()
+    };
+    for p in done {
+        unpin(p);
+    }
+}
+
+/// Make each committed 4 KiB page of `[p, p + n)` that is not writable now and lies in `pins`
+/// take a write fault in user mode: a no-op atomic RMW, so the protector's handler opens it.
+unsafe fn touch(p: usize, n: usize, pins: &[usize]) {
+    for &page in pins {
+        let Some(r) = query(page) else { continue };
+        if r.committed && r.protect & WRITES == 0 && r.protect & PROTECTED != 0 {

Critical: touch() doesn't exclude PAGE_GUARD pages (covers() does), so a pinned page with PAGE_READONLY|PAGE_GUARD gets a locked RMW that raises STATUS_GUARD_PAGE_VIOLATION, which no protector handles, and it consumes the title's one-shot guard. If a registered range contains a title guard page (e.g. a stack-growth guard in a pool XCL registered), a ReadFile or DirectStorage write over it calls open_with -> touch(), and fetch_add(0) on that page raises a guard-page exception. The protector's handler only claims EXCEPTION_ACCESS_VIOLATION, so it's unhandled inside hk_read_file or the worker (a crash), or the guard is silently removed. Skipping r.protect & PAGE_GUARD != 0 in touch would fix it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4772035683 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3597#discussion_r4772035683). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:33:51Z. **Code review location:** `crates/xcl/src/hle/kernelx/guest_write.rs`; line 290 ~~~~diff @@ -0,0 +1,582 @@ +//! Writes into the title's memory by XCL or by a kernel call, where XCL itself may have made the +//! pages read-only or no-access (`XCL_GUEST_WRITE_GUARD=1`; default off). +//! +//! XCL protects title pages to learn about CPU writes (`guards`, `XCL_PAGE_ALIAS=1`) and may do +//! so for more memory (read-only cold blocks, no-access GPU-written pages). A user-mode store +//! there faults and the protector's handler opens the page. A kernel call does not fault: on a +//! read-only or no-access page `ReadFile` (buffered, NO_BUFFERING, overlapped) and +//! `WriteProcessMemory` fail with ERROR_NOACCESS, `NtReadFile` with STATUS_ACCESS_VIOLATION, +//! and `NtWriteVirtualMemory` with STATUS_PARTIAL_COPY; nothing lands and no handler runs. So, +//! behind the switch: +//! +//! - `writable` answers "can XCL write here" for the pre-checks that asked `VirtualQuery` for a +//! writable protection: a page XCL protected counts as writable (a store faults and is opened); +//! - `open` brackets a kernel call's (or XCL's) write: lazy pages are committed and guarded views +//! opened (`lazy::ensure`, as without the switch), and pages of ranges a protector registered +//! are pinned (the protector must not protect them again) and touched by a no-op atomic RMW, +//! so the protector's fault handler runs before the kernel writes; +//! - `kernel_write` is `open` around a write that returns a status, with one retry. +//! +//! A protector calls `register` / `unregister` for the ranges whose pages it may protect, +//! serializes `VirtualProtect` against active writes via `while_unpinned`, and makes a page +//! writable from its vectored handler on a write fault (access 1) there. Off, every function +//! here does what the code did before: `writable` is false, `open` is `lazy::ensure`. + +use std::collections::{BTreeMap, HashMap}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering}; +use std::sync::{Mutex, OnceLock, RwLock}; + +use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_GUARD, PAGE_NOACCESS, PAGE_READONLY, PAGE_READWRITE}; + +/// the protection granule (`VirtualProtect` works on 4 KiB pages) +pub const STEP: usize = 0x1000; + +#[cfg(test)] +static FORCE_TEST: AtomicBool = AtomicBool::new(false); + +/// `XCL_GUEST_WRITE_GUARD=1` turns the guest-write guard on (default: off). +pub fn enabled() -> bool { + #[cfg(test)] + if FORCE_TEST.load(Ordering::Acquire) { + return true; + } + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_GUEST_WRITE_GUARD").is_ok_and(|v| v.trim() == "1")) +} + +/// ranges a protector registered: start → end +static RANGES: RwLock<BTreeMap<usize, usize>> = RwLock::new(BTreeMap::new()); +/// Whether any range was ever registered: `open` takes no lock before then. +static ANY: AtomicBool = AtomicBool::new(false); +/// 4 KiB pages pinned writable by a write going on → how many writes +static PINS: Mutex<Option<HashMap<usize, usize>>> = Mutex::new(None); +/// overlapped reads into registered ranges: (the OVERLAPPED, its pins), released when done +static PENDING: Mutex<Vec<(usize, Vec<usize>)>> = Mutex::new(Vec::new()); +/// calls a retry repaired, and calls that still failed (logged, a few each) +static REPAIRED: AtomicUsize = AtomicUsize::new(0); +static FAILED: AtomicUsize = AtomicUsize::new(0); + +/// `[p, p + len)` may hold pages a protector makes read-only or no-access. +pub fn register(p: usize, len: usize) { + if len == 0 { + return; + } + ANY.store(true, Ordering::Release); + let mut g = RANGES.write().unwrap_or_else(|e| e.into_inner()); + insert_range(&mut g, p, p.saturating_add(len)); +} + +/// `[p, p + len)` is no longer protected (call it before the memory is freed or decommitted). +pub fn unregister(p: usize, len: usize) { + let mut g = RANGES.write().unwrap_or_else(|e| e.into_inner()); + remove_range(&mut g, p, p.saturating_add(len)); +} + +fn insert_range(m: &mut BTreeMap<usize, usize>, mut lo: usize, mut hi: usize) { + // merge with every range that touches [lo, hi) + let touching: Vec<(usize, usize)> = m.range(..=hi).rev().take_while(|&(_, &e)| e >= lo).map(|(&s, &e)| (s, e)).collect(); + for (s, e) in touching { + m.remove(&s); + lo = lo.min(s); + hi = hi.max(e); + } + m.insert(lo, hi); +} + +fn remove_range(m: &mut BTreeMap<usize, usize>, lo: usize, hi: usize) { + let hit: Vec<(usize, usize)> = m.range(..hi).rev().take_while(|&(_, &e)| e > lo).map(|(&s, &e)| (s, e)).collect(); + for (s, e) in hit { + m.remove(&s); + if s < lo { + m.insert(s, lo); + } + if e > hi { + m.insert(hi, e); + } + } +} + +fn in_ranges(m: &BTreeMap<usize, usize>, at: usize) -> bool { + m.range(..=at).next_back().is_some_and(|(_, &e)| at < e) +} + +/// Whether XCL may have protected the page at `at` (a registered range or a guarded view). +pub fn xcl_protected(at: usize) -> bool { + (ANY.load(Ordering::Acquire) && in_ranges(&RANGES.read().unwrap_or_else(|e| e.into_inner()), at)) || super::guards::is_view(at) +} + +/// Range a protector is currently transitioning (`FREEZE_END == 0`: none), published under `PINS` +/// so a concurrent `open_with` that pins an overlapping page waits until `protect` completes +/// before touching it. `FREEZE_LOCK` serializes concurrent protectors without holding `PINS` +/// across `VirtualProtect`. +static FREEZE_LOCK: Mutex<()> = Mutex::new(()); +static FREEZE_AT: AtomicUsize = AtomicUsize::new(0); +static FREEZE_END: AtomicUsize = AtomicUsize::new(0); +static FREEZES_DONE: AtomicUsize = AtomicUsize::new(0); + +/// Run `protect` on `[p, p + n)` only if no 4 KiB page in it is currently pinned by a kernel +/// write. The pin check and active-range mark happen under `PINS`; `protect` itself runs after +/// `PINS` is released, and any concurrent `open` that pins an overlapping page waits until +/// `protect` finishes before touching the page. Returns `false` if any page was pinned. +pub fn while_unpinned(p: usize, n: usize, protect: impl FnOnce() -> bool) -> bool { + let _serial = FREEZE_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + release_done(); + let (lo, hi) = (p & !(STEP - 1), p.saturating_add(n)); + { + let g = PINS.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(m) = g.as_ref().filter(|m| !m.is_empty()) { + let pinned = if m.len() < n / STEP { + m.keys().any(|&k| k >= lo && k < hi) + } else { + (lo..hi).step_by(STEP).any(|k| m.contains_key(&k)) + }; + if pinned { + return false; + } + } + FREEZE_AT.store(lo, Ordering::Release); + FREEZE_END.store(hi, Ordering::Release); + } + struct Done; + impl Drop for Done { + fn drop(&mut self) { + FREEZE_END.store(0, Ordering::Release); + FREEZES_DONE.fetch_add(1, Ordering::AcqRel); + } + } + let _done = Done; + protect() +} + +/// Whether `[p, p + n)` intersects a guarded view (`XCL_PAGE_ALIAS`): another protector owns it. +pub fn meets_guarded_view(p: usize, n: usize) -> bool { + const VIEW: usize = 0x10000; + (p & !(VIEW - 1)..p.saturating_add(n)).step_by(VIEW).any(super::guards::is_view) +} + +#[cfg(test)] +fn is_pinned(at: usize) -> bool { + release_done(); + PINS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| m.contains_key(&(at & !(STEP - 1)))) +} + +/// One region `VirtualQuery` describes: [base, end), committed?, protection. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Region { + pub base: usize, + pub end: usize, + pub committed: bool, + pub protect: u32, +} + +fn query(at: usize) -> Option<Region> { + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: VirtualQuery only reads the address space description. + if unsafe { VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) } == 0 { + return None; + } + let base = m.BaseAddress as usize; + Some(Region { base, end: base.saturating_add(m.RegionSize), committed: m.State == MEM_COMMIT, protect: m.Protect }) +} + +const WRITES: u32 = PAGE_READWRITE | PAGE_EXECUTE_READWRITE | 0x08 | 0x80; // + WRITECOPY, EXECUTE_WRITECOPY +const PROTECTED: u32 = PAGE_READONLY | PAGE_NOACCESS | PAGE_EXECUTE_READ; + +/// Whether every byte of `[p, p + n)` is committed and either writable now or on a page XCL +/// protected (`xcl`). `query` describes the region at an address. +pub(crate) fn covers(p: usize, n: usize, mut query: impl FnMut(usize) -> Option<Region>, xcl: impl Fn(usize) -> bool) -> bool { + let Some(end) = p.checked_add(n) else { return false }; + let mut at = p; + while at < end { + let Some(r) = query(at) else { return false }; + if !r.committed || r.protect & PAGE_GUARD != 0 || r.end <= at { + return false; + } + let stop = r.end.min(end); + if r.protect & WRITES == 0 { + if r.protect & PROTECTED == 0 { + return false; + } + let mut page = at & !(STEP - 1); + while page < stop { + if !xcl(page) { + return false; + } + let Some(next) = page.checked_add(STEP) else { break }; + page = next; + } + } + at = stop; + } + true +} + +/// With the switch on: whether XCL may write `[p, p + n)` – committed, and writable or protected +/// by XCL (a store there faults and is opened; a kernel call goes through `open`). Off: false, so +/// a pre-check `old || writable(..)` is the old one. +pub fn writable(p: usize, n: usize) -> bool { + enabled() && n > 0 && covers(p, n, query, xcl_protected) +} + +/// A write to `[p, p + n)` going on: lazy pages committed and guarded views open (`lazy::ensure`), +/// pins on pages of registered ranges. Dropped when the write is over. +#[must_use = "the pages stay open only while this lives"] +pub struct Bracket { + opened: Option<super::guards::Opened>, + pins: Vec<usize>, +} + +impl Drop for Bracket { + fn drop(&mut self) { + unpin(std::mem::take(&mut self.pins)); + } +} + +impl Bracket { + /// An overlapped read (`ov`) writes after its call returned: the pages stay open until done. + pub fn keep_until_done(mut self, ov: usize) { + if let Some(o) = self.opened.take() { + super::guards::open_until_done(o, ov); + } + let pins = std::mem::take(&mut self.pins); + if !pins.is_empty() { + PENDING.lock().unwrap_or_else(|e| e.into_inner()).push((ov, pins)); + } + } + + /// pages of registered ranges this write holds open + pub fn pinned(&self) -> usize { + self.pins.len() + } +} + +fn unpin(pins: Vec<usize>) { + if pins.is_empty() { + return; + } + let mut g = PINS.lock().unwrap_or_else(|e| e.into_inner()); + let m = g.get_or_insert_with(HashMap::new); + for p in pins { + if let Some(c) = m.get_mut(&p) { + *c -= 1; + if *c == 0 { + m.remove(&p); + } + } + } +} + +fn release_done() { + let done: Vec<Vec<usize>> = { + let mut g = PENDING.lock().unwrap_or_else(|e| e.into_inner()); + if g.is_empty() { + return; + } + let (done, pending): (Vec<_>, Vec<_>) = std::mem::take(&mut *g).into_iter().partition(|&(ov, _)| !super::guards::still_pending(ov)); + *g = pending; + done.into_iter().map(|(_, p)| p).collect() + }; + for p in done { + unpin(p); + } +} + +/// Make each committed 4 KiB page of `[p, p + n)` that is not writable now and lies in `pins` +/// take a write fault in user mode: a no-op atomic RMW, so the protector's handler opens it. +unsafe fn touch(p: usize, n: usize, pins: &[usize]) { + for &page in pins { + let Some(r) = query(page) else { continue }; + if r.committed && r.protect & WRITES == 0 && r.protect & PROTECTED != 0 { ~~~~ --- **Critical**: `touch()` doesn't exclude PAGE_GUARD pages (`covers()` does), so a pinned page with PAGE_READONLY|PAGE_GUARD gets a locked RMW that raises STATUS_GUARD_PAGE_VIOLATION, which no protector handles, and it consumes the title's one-shot guard. If a registered range contains a title guard page (e.g. a stack-growth guard in a pool XCL registered), a ReadFile or DirectStorage write over it calls `open_with` -> `touch()`, and `fetch_add(0)` on that page raises a guard-page exception. The protector's handler only claims EXCEPTION_ACCESS_VIOLATION, so it's unhandled inside `hk_read_file` or the worker (a crash), or the guard is silently removed. Skipping `r.protect & PAGE_GUARD != 0` in `touch` would fix it.
bmjask commented 2026-12-02 15:33:51 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T15:33:51Z.

Code review location: crates/xcl/src/hle/kernelx/guest_write.rs; line 106

@@ -0,0 +1,582 @@
+//! Writes into the title's memory by XCL or by a kernel call, where XCL itself may have made the
+//! pages read-only or no-access (`XCL_GUEST_WRITE_GUARD=1`; default off).
+//!
+//! XCL protects title pages to learn about CPU writes (`guards`, `XCL_PAGE_ALIAS=1`) and may do
+//! so for more memory (read-only cold blocks, no-access GPU-written pages). A user-mode store
+//! there faults and the protector's handler opens the page. A kernel call does not fault: on a
+//! read-only or no-access page `ReadFile` (buffered, NO_BUFFERING, overlapped) and
+//! `WriteProcessMemory` fail with ERROR_NOACCESS, `NtReadFile` with STATUS_ACCESS_VIOLATION,
+//! and `NtWriteVirtualMemory` with STATUS_PARTIAL_COPY; nothing lands and no handler runs. So,
+//! behind the switch:
+//!
+//! - `writable` answers "can XCL write here" for the pre-checks that asked `VirtualQuery` for a
+//!   writable protection: a page XCL protected counts as writable (a store faults and is opened);
+//! - `open` brackets a kernel call's (or XCL's) write: lazy pages are committed and guarded views
+//!   opened (`lazy::ensure`, as without the switch), and pages of ranges a protector registered
+//!   are pinned (the protector must not protect them again) and touched by a no-op atomic RMW,
+//!   so the protector's fault handler runs before the kernel writes;
+//! - `kernel_write` is `open` around a write that returns a status, with one retry.
+//!
+//! A protector calls `register` / `unregister` for the ranges whose pages it may protect,
+//! serializes `VirtualProtect` against active writes via `while_unpinned`, and makes a page
+//! writable from its vectored handler on a write fault (access 1) there. Off, every function
+//! here does what the code did before: `writable` is false, `open` is `lazy::ensure`.
+
+use std::collections::{BTreeMap, HashMap};
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering};
+use std::sync::{Mutex, OnceLock, RwLock};
+
+use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_GUARD, PAGE_NOACCESS, PAGE_READONLY, PAGE_READWRITE};
+
+/// the protection granule (`VirtualProtect` works on 4 KiB pages)
+pub const STEP: usize = 0x1000;
+
+#[cfg(test)]
+static FORCE_TEST: AtomicBool = AtomicBool::new(false);
+
+/// `XCL_GUEST_WRITE_GUARD=1` turns the guest-write guard on (default: off).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    if FORCE_TEST.load(Ordering::Acquire) {
+        return true;
+    }
+    static ON: OnceLock<bool> = OnceLock::new();
+    *ON.get_or_init(|| std::env::var("XCL_GUEST_WRITE_GUARD").is_ok_and(|v| v.trim() == "1"))
+}
+
+/// ranges a protector registered: start → end
+static RANGES: RwLock<BTreeMap<usize, usize>> = RwLock::new(BTreeMap::new());
+/// Whether any range was ever registered: `open` takes no lock before then.
+static ANY: AtomicBool = AtomicBool::new(false);
+/// 4 KiB pages pinned writable by a write going on → how many writes
+static PINS: Mutex<Option<HashMap<usize, usize>>> = Mutex::new(None);
+/// overlapped reads into registered ranges: (the OVERLAPPED, its pins), released when done
+static PENDING: Mutex<Vec<(usize, Vec<usize>)>> = Mutex::new(Vec::new());
+/// calls a retry repaired, and calls that still failed (logged, a few each)
+static REPAIRED: AtomicUsize = AtomicUsize::new(0);
+static FAILED: AtomicUsize = AtomicUsize::new(0);
+
+/// `[p, p + len)` may hold pages a protector makes read-only or no-access.
+pub fn register(p: usize, len: usize) {
+    if len == 0 {
+        return;
+    }
+    ANY.store(true, Ordering::Release);
+    let mut g = RANGES.write().unwrap_or_else(|e| e.into_inner());
+    insert_range(&mut g, p, p.saturating_add(len));
+}
+
+/// `[p, p + len)` is no longer protected (call it before the memory is freed or decommitted).
+pub fn unregister(p: usize, len: usize) {
+    let mut g = RANGES.write().unwrap_or_else(|e| e.into_inner());
+    remove_range(&mut g, p, p.saturating_add(len));
+}
+
+fn insert_range(m: &mut BTreeMap<usize, usize>, mut lo: usize, mut hi: usize) {
+    // merge with every range that touches [lo, hi)
+    let touching: Vec<(usize, usize)> = m.range(..=hi).rev().take_while(|&(_, &e)| e >= lo).map(|(&s, &e)| (s, e)).collect();
+    for (s, e) in touching {
+        m.remove(&s);
+        lo = lo.min(s);
+        hi = hi.max(e);
+    }
+    m.insert(lo, hi);
+}
+
+fn remove_range(m: &mut BTreeMap<usize, usize>, lo: usize, hi: usize) {
+    let hit: Vec<(usize, usize)> = m.range(..hi).rev().take_while(|&(_, &e)| e > lo).map(|(&s, &e)| (s, e)).collect();
+    for (s, e) in hit {
+        m.remove(&s);
+        if s < lo {
+            m.insert(s, lo);
+        }
+        if e > hi {
+            m.insert(hi, e);
+        }
+    }
+}
+
+fn in_ranges(m: &BTreeMap<usize, usize>, at: usize) -> bool {
+    m.range(..=at).next_back().is_some_and(|(_, &e)| at < e)
+}
+
+/// Whether XCL may have protected the page at `at` (a registered range or a guarded view).
+pub fn xcl_protected(at: usize) -> bool {
+    (ANY.load(Ordering::Acquire) && in_ranges(&RANGES.read().unwrap_or_else(|e| e.into_inner()), at)) || super::guards::is_view(at)

Critical: xcl_protected answers "XCL may have protected this page" (any page in a registered range or a guarded view), not "XCL protected it now", so writable()/covers() report pages the title itself made read-only or no-access as writable, and every pre-check that used to skip safely now does a user-mode store there. With XCL_GUEST_WRITE_GUARD=1, if the title VirtualProtects part of a registered range (or a guarded view) to PAGE_READONLY/PAGE_NOACCESS, or the range holds PAGE_EXECUTE_READ code, the cpu_writes worker (write_now_in / write_u64_now), frame.rs note_signaled, the eh.rs CLZERO emulation, or the DirectStorage copy now stores there. If the protector's handler doesn't claim the fault, the result is an unhandled access violation that crashes the process, where before the write was skipped. On a guarded view, the guards handler also silently overrides the title's own protection with RW. Tracking which pages XCL actually protected (and when) would fix it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4772035696 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3597#discussion_r4772035696). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:33:51Z. **Code review location:** `crates/xcl/src/hle/kernelx/guest_write.rs`; line 106 ~~~~diff @@ -0,0 +1,582 @@ +//! Writes into the title's memory by XCL or by a kernel call, where XCL itself may have made the +//! pages read-only or no-access (`XCL_GUEST_WRITE_GUARD=1`; default off). +//! +//! XCL protects title pages to learn about CPU writes (`guards`, `XCL_PAGE_ALIAS=1`) and may do +//! so for more memory (read-only cold blocks, no-access GPU-written pages). A user-mode store +//! there faults and the protector's handler opens the page. A kernel call does not fault: on a +//! read-only or no-access page `ReadFile` (buffered, NO_BUFFERING, overlapped) and +//! `WriteProcessMemory` fail with ERROR_NOACCESS, `NtReadFile` with STATUS_ACCESS_VIOLATION, +//! and `NtWriteVirtualMemory` with STATUS_PARTIAL_COPY; nothing lands and no handler runs. So, +//! behind the switch: +//! +//! - `writable` answers "can XCL write here" for the pre-checks that asked `VirtualQuery` for a +//! writable protection: a page XCL protected counts as writable (a store faults and is opened); +//! - `open` brackets a kernel call's (or XCL's) write: lazy pages are committed and guarded views +//! opened (`lazy::ensure`, as without the switch), and pages of ranges a protector registered +//! are pinned (the protector must not protect them again) and touched by a no-op atomic RMW, +//! so the protector's fault handler runs before the kernel writes; +//! - `kernel_write` is `open` around a write that returns a status, with one retry. +//! +//! A protector calls `register` / `unregister` for the ranges whose pages it may protect, +//! serializes `VirtualProtect` against active writes via `while_unpinned`, and makes a page +//! writable from its vectored handler on a write fault (access 1) there. Off, every function +//! here does what the code did before: `writable` is false, `open` is `lazy::ensure`. + +use std::collections::{BTreeMap, HashMap}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering}; +use std::sync::{Mutex, OnceLock, RwLock}; + +use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_GUARD, PAGE_NOACCESS, PAGE_READONLY, PAGE_READWRITE}; + +/// the protection granule (`VirtualProtect` works on 4 KiB pages) +pub const STEP: usize = 0x1000; + +#[cfg(test)] +static FORCE_TEST: AtomicBool = AtomicBool::new(false); + +/// `XCL_GUEST_WRITE_GUARD=1` turns the guest-write guard on (default: off). +pub fn enabled() -> bool { + #[cfg(test)] + if FORCE_TEST.load(Ordering::Acquire) { + return true; + } + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_GUEST_WRITE_GUARD").is_ok_and(|v| v.trim() == "1")) +} + +/// ranges a protector registered: start → end +static RANGES: RwLock<BTreeMap<usize, usize>> = RwLock::new(BTreeMap::new()); +/// Whether any range was ever registered: `open` takes no lock before then. +static ANY: AtomicBool = AtomicBool::new(false); +/// 4 KiB pages pinned writable by a write going on → how many writes +static PINS: Mutex<Option<HashMap<usize, usize>>> = Mutex::new(None); +/// overlapped reads into registered ranges: (the OVERLAPPED, its pins), released when done +static PENDING: Mutex<Vec<(usize, Vec<usize>)>> = Mutex::new(Vec::new()); +/// calls a retry repaired, and calls that still failed (logged, a few each) +static REPAIRED: AtomicUsize = AtomicUsize::new(0); +static FAILED: AtomicUsize = AtomicUsize::new(0); + +/// `[p, p + len)` may hold pages a protector makes read-only or no-access. +pub fn register(p: usize, len: usize) { + if len == 0 { + return; + } + ANY.store(true, Ordering::Release); + let mut g = RANGES.write().unwrap_or_else(|e| e.into_inner()); + insert_range(&mut g, p, p.saturating_add(len)); +} + +/// `[p, p + len)` is no longer protected (call it before the memory is freed or decommitted). +pub fn unregister(p: usize, len: usize) { + let mut g = RANGES.write().unwrap_or_else(|e| e.into_inner()); + remove_range(&mut g, p, p.saturating_add(len)); +} + +fn insert_range(m: &mut BTreeMap<usize, usize>, mut lo: usize, mut hi: usize) { + // merge with every range that touches [lo, hi) + let touching: Vec<(usize, usize)> = m.range(..=hi).rev().take_while(|&(_, &e)| e >= lo).map(|(&s, &e)| (s, e)).collect(); + for (s, e) in touching { + m.remove(&s); + lo = lo.min(s); + hi = hi.max(e); + } + m.insert(lo, hi); +} + +fn remove_range(m: &mut BTreeMap<usize, usize>, lo: usize, hi: usize) { + let hit: Vec<(usize, usize)> = m.range(..hi).rev().take_while(|&(_, &e)| e > lo).map(|(&s, &e)| (s, e)).collect(); + for (s, e) in hit { + m.remove(&s); + if s < lo { + m.insert(s, lo); + } + if e > hi { + m.insert(hi, e); + } + } +} + +fn in_ranges(m: &BTreeMap<usize, usize>, at: usize) -> bool { + m.range(..=at).next_back().is_some_and(|(_, &e)| at < e) +} + +/// Whether XCL may have protected the page at `at` (a registered range or a guarded view). +pub fn xcl_protected(at: usize) -> bool { + (ANY.load(Ordering::Acquire) && in_ranges(&RANGES.read().unwrap_or_else(|e| e.into_inner()), at)) || super::guards::is_view(at) ~~~~ --- **Critical**: `xcl_protected` answers "XCL may have protected this page" (any page in a registered range or a guarded view), not "XCL protected it now", so `writable()`/`covers()` report pages the title itself made read-only or no-access as writable, and every pre-check that used to skip safely now does a user-mode store there. With XCL_GUEST_WRITE_GUARD=1, if the title VirtualProtects part of a registered range (or a guarded view) to PAGE_READONLY/PAGE_NOACCESS, or the range holds PAGE_EXECUTE_READ code, the cpu_writes worker (`write_now_in` / `write_u64_now`), frame.rs `note_signaled`, the eh.rs CLZERO emulation, or the DirectStorage copy now stores there. If the protector's handler doesn't claim the fault, the result is an unhandled access violation that crashes the process, where before the write was skipped. On a guarded view, the guards handler also silently overrides the title's own protection with RW. Tracking which pages XCL actually protected (and when) would fix it.
bmjask commented 2026-12-02 15:33:51 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T15:33:51Z.

Code review location: crates/xcl/src/hle/kernelx/guest_write.rs; line 331

@@ -0,0 +1,582 @@
+//! Writes into the title's memory by XCL or by a kernel call, where XCL itself may have made the
+//! pages read-only or no-access (`XCL_GUEST_WRITE_GUARD=1`; default off).
+//!
+//! XCL protects title pages to learn about CPU writes (`guards`, `XCL_PAGE_ALIAS=1`) and may do
+//! so for more memory (read-only cold blocks, no-access GPU-written pages). A user-mode store
+//! there faults and the protector's handler opens the page. A kernel call does not fault: on a
+//! read-only or no-access page `ReadFile` (buffered, NO_BUFFERING, overlapped) and
+//! `WriteProcessMemory` fail with ERROR_NOACCESS, `NtReadFile` with STATUS_ACCESS_VIOLATION,
+//! and `NtWriteVirtualMemory` with STATUS_PARTIAL_COPY; nothing lands and no handler runs. So,
+//! behind the switch:
+//!
+//! - `writable` answers "can XCL write here" for the pre-checks that asked `VirtualQuery` for a
+//!   writable protection: a page XCL protected counts as writable (a store faults and is opened);
+//! - `open` brackets a kernel call's (or XCL's) write: lazy pages are committed and guarded views
+//!   opened (`lazy::ensure`, as without the switch), and pages of ranges a protector registered
+//!   are pinned (the protector must not protect them again) and touched by a no-op atomic RMW,
+//!   so the protector's fault handler runs before the kernel writes;
+//! - `kernel_write` is `open` around a write that returns a status, with one retry.
+//!
+//! A protector calls `register` / `unregister` for the ranges whose pages it may protect,
+//! serializes `VirtualProtect` against active writes via `while_unpinned`, and makes a page
+//! writable from its vectored handler on a write fault (access 1) there. Off, every function
+//! here does what the code did before: `writable` is false, `open` is `lazy::ensure`.
+
+use std::collections::{BTreeMap, HashMap};
+use std::ffi::c_void;
+use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering};
+use std::sync::{Mutex, OnceLock, RwLock};
+
+use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_GUARD, PAGE_NOACCESS, PAGE_READONLY, PAGE_READWRITE};
+
+/// the protection granule (`VirtualProtect` works on 4 KiB pages)
+pub const STEP: usize = 0x1000;
+
+#[cfg(test)]
+static FORCE_TEST: AtomicBool = AtomicBool::new(false);
+
+/// `XCL_GUEST_WRITE_GUARD=1` turns the guest-write guard on (default: off).
+pub fn enabled() -> bool {
+    #[cfg(test)]
+    if FORCE_TEST.load(Ordering::Acquire) {
+        return true;
+    }
+    static ON: OnceLock<bool> = OnceLock::new();
+    *ON.get_or_init(|| std::env::var("XCL_GUEST_WRITE_GUARD").is_ok_and(|v| v.trim() == "1"))
+}
+
+/// ranges a protector registered: start → end
+static RANGES: RwLock<BTreeMap<usize, usize>> = RwLock::new(BTreeMap::new());
+/// Whether any range was ever registered: `open` takes no lock before then.
+static ANY: AtomicBool = AtomicBool::new(false);
+/// 4 KiB pages pinned writable by a write going on → how many writes
+static PINS: Mutex<Option<HashMap<usize, usize>>> = Mutex::new(None);
+/// overlapped reads into registered ranges: (the OVERLAPPED, its pins), released when done
+static PENDING: Mutex<Vec<(usize, Vec<usize>)>> = Mutex::new(Vec::new());
+/// calls a retry repaired, and calls that still failed (logged, a few each)
+static REPAIRED: AtomicUsize = AtomicUsize::new(0);
+static FAILED: AtomicUsize = AtomicUsize::new(0);
+
+/// `[p, p + len)` may hold pages a protector makes read-only or no-access.
+pub fn register(p: usize, len: usize) {
+    if len == 0 {
+        return;
+    }
+    ANY.store(true, Ordering::Release);
+    let mut g = RANGES.write().unwrap_or_else(|e| e.into_inner());
+    insert_range(&mut g, p, p.saturating_add(len));
+}
+
+/// `[p, p + len)` is no longer protected (call it before the memory is freed or decommitted).
+pub fn unregister(p: usize, len: usize) {
+    let mut g = RANGES.write().unwrap_or_else(|e| e.into_inner());
+    remove_range(&mut g, p, p.saturating_add(len));
+}
+
+fn insert_range(m: &mut BTreeMap<usize, usize>, mut lo: usize, mut hi: usize) {
+    // merge with every range that touches [lo, hi)
+    let touching: Vec<(usize, usize)> = m.range(..=hi).rev().take_while(|&(_, &e)| e >= lo).map(|(&s, &e)| (s, e)).collect();
+    for (s, e) in touching {
+        m.remove(&s);
+        lo = lo.min(s);
+        hi = hi.max(e);
+    }
+    m.insert(lo, hi);
+}
+
+fn remove_range(m: &mut BTreeMap<usize, usize>, lo: usize, hi: usize) {
+    let hit: Vec<(usize, usize)> = m.range(..hi).rev().take_while(|&(_, &e)| e > lo).map(|(&s, &e)| (s, e)).collect();
+    for (s, e) in hit {
+        m.remove(&s);
+        if s < lo {
+            m.insert(s, lo);
+        }
+        if e > hi {
+            m.insert(hi, e);
+        }
+    }
+}
+
+fn in_ranges(m: &BTreeMap<usize, usize>, at: usize) -> bool {
+    m.range(..=at).next_back().is_some_and(|(_, &e)| at < e)
+}
+
+/// Whether XCL may have protected the page at `at` (a registered range or a guarded view).
+pub fn xcl_protected(at: usize) -> bool {
+    (ANY.load(Ordering::Acquire) && in_ranges(&RANGES.read().unwrap_or_else(|e| e.into_inner()), at)) || super::guards::is_view(at)
+}
+
+/// Range a protector is currently transitioning (`FREEZE_END == 0`: none), published under `PINS`
+/// so a concurrent `open_with` that pins an overlapping page waits until `protect` completes
+/// before touching it. `FREEZE_LOCK` serializes concurrent protectors without holding `PINS`
+/// across `VirtualProtect`.
+static FREEZE_LOCK: Mutex<()> = Mutex::new(());
+static FREEZE_AT: AtomicUsize = AtomicUsize::new(0);
+static FREEZE_END: AtomicUsize = AtomicUsize::new(0);
+static FREEZES_DONE: AtomicUsize = AtomicUsize::new(0);
+
+/// Run `protect` on `[p, p + n)` only if no 4 KiB page in it is currently pinned by a kernel
+/// write. The pin check and active-range mark happen under `PINS`; `protect` itself runs after
+/// `PINS` is released, and any concurrent `open` that pins an overlapping page waits until
+/// `protect` finishes before touching the page. Returns `false` if any page was pinned.
+pub fn while_unpinned(p: usize, n: usize, protect: impl FnOnce() -> bool) -> bool {
+    let _serial = FREEZE_LOCK.lock().unwrap_or_else(|e| e.into_inner());
+    release_done();
+    let (lo, hi) = (p & !(STEP - 1), p.saturating_add(n));
+    {
+        let g = PINS.lock().unwrap_or_else(|e| e.into_inner());
+        if let Some(m) = g.as_ref().filter(|m| !m.is_empty()) {
+            let pinned = if m.len() < n / STEP {
+                m.keys().any(|&k| k >= lo && k < hi)
+            } else {
+                (lo..hi).step_by(STEP).any(|k| m.contains_key(&k))
+            };
+            if pinned {
+                return false;
+            }
+        }
+        FREEZE_AT.store(lo, Ordering::Release);
+        FREEZE_END.store(hi, Ordering::Release);
+    }
+    struct Done;
+    impl Drop for Done {
+        fn drop(&mut self) {
+            FREEZE_END.store(0, Ordering::Release);
+            FREEZES_DONE.fetch_add(1, Ordering::AcqRel);
+        }
+    }
+    let _done = Done;
+    protect()
+}
+
+/// Whether `[p, p + n)` intersects a guarded view (`XCL_PAGE_ALIAS`): another protector owns it.
+pub fn meets_guarded_view(p: usize, n: usize) -> bool {
+    const VIEW: usize = 0x10000;
+    (p & !(VIEW - 1)..p.saturating_add(n)).step_by(VIEW).any(super::guards::is_view)
+}
+
+#[cfg(test)]
+fn is_pinned(at: usize) -> bool {
+    release_done();
+    PINS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| m.contains_key(&(at & !(STEP - 1))))
+}
+
+/// One region `VirtualQuery` describes: [base, end), committed?, protection.
+#[derive(Clone, Copy, Debug, PartialEq)]
+pub(crate) struct Region {
+    pub base: usize,
+    pub end: usize,
+    pub committed: bool,
+    pub protect: u32,
+}
+
+fn query(at: usize) -> Option<Region> {
+    let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
+    // SAFETY: VirtualQuery only reads the address space description.
+    if unsafe { VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) } == 0 {
+        return None;
+    }
+    let base = m.BaseAddress as usize;
+    Some(Region { base, end: base.saturating_add(m.RegionSize), committed: m.State == MEM_COMMIT, protect: m.Protect })
+}
+
+const WRITES: u32 = PAGE_READWRITE | PAGE_EXECUTE_READWRITE | 0x08 | 0x80; // + WRITECOPY, EXECUTE_WRITECOPY
+const PROTECTED: u32 = PAGE_READONLY | PAGE_NOACCESS | PAGE_EXECUTE_READ;
+
+/// Whether every byte of `[p, p + n)` is committed and either writable now or on a page XCL
+/// protected (`xcl`). `query` describes the region at an address.
+pub(crate) fn covers(p: usize, n: usize, mut query: impl FnMut(usize) -> Option<Region>, xcl: impl Fn(usize) -> bool) -> bool {
+    let Some(end) = p.checked_add(n) else { return false };
+    let mut at = p;
+    while at < end {
+        let Some(r) = query(at) else { return false };
+        if !r.committed || r.protect & PAGE_GUARD != 0 || r.end <= at {
+            return false;
+        }
+        let stop = r.end.min(end);
+        if r.protect & WRITES == 0 {
+            if r.protect & PROTECTED == 0 {
+                return false;
+            }
+            let mut page = at & !(STEP - 1);
+            while page < stop {
+                if !xcl(page) {
+                    return false;
+                }
+                let Some(next) = page.checked_add(STEP) else { break };
+                page = next;
+            }
+        }
+        at = stop;
+    }
+    true
+}
+
+/// With the switch on: whether XCL may write `[p, p + n)` – committed, and writable or protected
+/// by XCL (a store there faults and is opened; a kernel call goes through `open`). Off: false, so
+/// a pre-check `old || writable(..)` is the old one.
+pub fn writable(p: usize, n: usize) -> bool {
+    enabled() && n > 0 && covers(p, n, query, xcl_protected)
+}
+
+/// A write to `[p, p + n)` going on: lazy pages committed and guarded views open (`lazy::ensure`),
+/// pins on pages of registered ranges. Dropped when the write is over.
+#[must_use = "the pages stay open only while this lives"]
+pub struct Bracket {
+    opened: Option<super::guards::Opened>,
+    pins: Vec<usize>,
+}
+
+impl Drop for Bracket {
+    fn drop(&mut self) {
+        unpin(std::mem::take(&mut self.pins));
+    }
+}
+
+impl Bracket {
+    /// An overlapped read (`ov`) writes after its call returned: the pages stay open until done.
+    pub fn keep_until_done(mut self, ov: usize) {
+        if let Some(o) = self.opened.take() {
+            super::guards::open_until_done(o, ov);
+        }
+        let pins = std::mem::take(&mut self.pins);
+        if !pins.is_empty() {
+            PENDING.lock().unwrap_or_else(|e| e.into_inner()).push((ov, pins));
+        }
+    }
+
+    /// pages of registered ranges this write holds open
+    pub fn pinned(&self) -> usize {
+        self.pins.len()
+    }
+}
+
+fn unpin(pins: Vec<usize>) {
+    if pins.is_empty() {
+        return;
+    }
+    let mut g = PINS.lock().unwrap_or_else(|e| e.into_inner());
+    let m = g.get_or_insert_with(HashMap::new);
+    for p in pins {
+        if let Some(c) = m.get_mut(&p) {
+            *c -= 1;
+            if *c == 0 {
+                m.remove(&p);
+            }
+        }
+    }
+}
+
+fn release_done() {
+    let done: Vec<Vec<usize>> = {
+        let mut g = PENDING.lock().unwrap_or_else(|e| e.into_inner());
+        if g.is_empty() {
+            return;
+        }
+        let (done, pending): (Vec<_>, Vec<_>) = std::mem::take(&mut *g).into_iter().partition(|&(ov, _)| !super::guards::still_pending(ov));
+        *g = pending;
+        done.into_iter().map(|(_, p)| p).collect()
+    };
+    for p in done {
+        unpin(p);
+    }
+}
+
+/// Make each committed 4 KiB page of `[p, p + n)` that is not writable now and lies in `pins`
+/// take a write fault in user mode: a no-op atomic RMW, so the protector's handler opens it.
+unsafe fn touch(p: usize, n: usize, pins: &[usize]) {
+    for &page in pins {
+        let Some(r) = query(page) else { continue };
+        if r.committed && r.protect & WRITES == 0 && r.protect & PROTECTED != 0 {
+            let at = page.max(p);
+            debug_assert!(at < p + n);
+            (*(at as *const AtomicU8)).fetch_add(0, Ordering::Relaxed);
+        }
+    }
+}
+
+/// `[p, p + n)` is about to be written by a kernel call or by XCL (see the module's comment).
+pub fn open(p: usize, n: usize) -> Bracket {
+    open_with(enabled(), p, n)
+}
+
+pub(crate) fn open_with(on: bool, p: usize, n: usize) -> Bracket {
+    let opened = Some(super::lazy::ensure(p, n));
+    if !on || n == 0 || !ANY.load(Ordering::Acquire) {
+        return Bracket { opened, pins: Vec::new() };
+    }
+    release_done();
+    let end = p.saturating_add(n);
+    let pins: Vec<usize> = {
+        let g = RANGES.read().unwrap_or_else(|e| e.into_inner());
+        let mut v = Vec::new();
+        let mut page = p & !(STEP - 1);
+        while page < end {
+            if in_ranges(&g, page) {
+                v.push(page);
+            }
+            let Some(next) = page.checked_add(STEP) else { break };
+            page = next;
+        }
+        v
+    };
+    let mut wait_for = None;
+    if !pins.is_empty() {
+        let mut g = PINS.lock().unwrap_or_else(|e| e.into_inner());
+        let m = g.get_or_insert_with(HashMap::new);
+        for &page in &pins {
+            *m.entry(page).or_default() += 1;
+        }
+        let (fa, fe) = (FREEZE_AT.load(Ordering::Acquire), FREEZE_END.load(Ordering::Acquire));
+        if fe != 0 && fa < end && p < fe {

High: The freeze overlap test fa < end && p < fe compares the unaligned p against the unaligned fe = p'+n', but VirtualProtect, the pins and the while_unpinned pin check all work on whole 4 KiB pages, so an open on the same page just past fe skips the wait. If the protector calls while_unpinned(0x10000, 0x1800) (fe=0x11800, so VirtualProtect makes 0x10000-0x11fff read-only) and open(0x11900, 0x100) runs concurrently, it pins page 0x11000, sees p >= fe and doesn't wait. touch skips the page because it's still read-write, protect() then makes it read-only, and the kernel ReadFile into 0x11900 fails with ERROR_NOACCESS. hk_read_file has no retry, so the title gets a failed read. Rounding fe up to STEP would fix it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4772035707 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3597#discussion_r4772035707). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:33:51Z. **Code review location:** `crates/xcl/src/hle/kernelx/guest_write.rs`; line 331 ~~~~diff @@ -0,0 +1,582 @@ +//! Writes into the title's memory by XCL or by a kernel call, where XCL itself may have made the +//! pages read-only or no-access (`XCL_GUEST_WRITE_GUARD=1`; default off). +//! +//! XCL protects title pages to learn about CPU writes (`guards`, `XCL_PAGE_ALIAS=1`) and may do +//! so for more memory (read-only cold blocks, no-access GPU-written pages). A user-mode store +//! there faults and the protector's handler opens the page. A kernel call does not fault: on a +//! read-only or no-access page `ReadFile` (buffered, NO_BUFFERING, overlapped) and +//! `WriteProcessMemory` fail with ERROR_NOACCESS, `NtReadFile` with STATUS_ACCESS_VIOLATION, +//! and `NtWriteVirtualMemory` with STATUS_PARTIAL_COPY; nothing lands and no handler runs. So, +//! behind the switch: +//! +//! - `writable` answers "can XCL write here" for the pre-checks that asked `VirtualQuery` for a +//! writable protection: a page XCL protected counts as writable (a store faults and is opened); +//! - `open` brackets a kernel call's (or XCL's) write: lazy pages are committed and guarded views +//! opened (`lazy::ensure`, as without the switch), and pages of ranges a protector registered +//! are pinned (the protector must not protect them again) and touched by a no-op atomic RMW, +//! so the protector's fault handler runs before the kernel writes; +//! - `kernel_write` is `open` around a write that returns a status, with one retry. +//! +//! A protector calls `register` / `unregister` for the ranges whose pages it may protect, +//! serializes `VirtualProtect` against active writes via `while_unpinned`, and makes a page +//! writable from its vectored handler on a write fault (access 1) there. Off, every function +//! here does what the code did before: `writable` is false, `open` is `lazy::ensure`. + +use std::collections::{BTreeMap, HashMap}; +use std::ffi::c_void; +use std::sync::atomic::{AtomicBool, AtomicU8, AtomicUsize, Ordering}; +use std::sync::{Mutex, OnceLock, RwLock}; + +use windows_sys::Win32::System::Memory::{VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, PAGE_EXECUTE_READ, PAGE_EXECUTE_READWRITE, PAGE_GUARD, PAGE_NOACCESS, PAGE_READONLY, PAGE_READWRITE}; + +/// the protection granule (`VirtualProtect` works on 4 KiB pages) +pub const STEP: usize = 0x1000; + +#[cfg(test)] +static FORCE_TEST: AtomicBool = AtomicBool::new(false); + +/// `XCL_GUEST_WRITE_GUARD=1` turns the guest-write guard on (default: off). +pub fn enabled() -> bool { + #[cfg(test)] + if FORCE_TEST.load(Ordering::Acquire) { + return true; + } + static ON: OnceLock<bool> = OnceLock::new(); + *ON.get_or_init(|| std::env::var("XCL_GUEST_WRITE_GUARD").is_ok_and(|v| v.trim() == "1")) +} + +/// ranges a protector registered: start → end +static RANGES: RwLock<BTreeMap<usize, usize>> = RwLock::new(BTreeMap::new()); +/// Whether any range was ever registered: `open` takes no lock before then. +static ANY: AtomicBool = AtomicBool::new(false); +/// 4 KiB pages pinned writable by a write going on → how many writes +static PINS: Mutex<Option<HashMap<usize, usize>>> = Mutex::new(None); +/// overlapped reads into registered ranges: (the OVERLAPPED, its pins), released when done +static PENDING: Mutex<Vec<(usize, Vec<usize>)>> = Mutex::new(Vec::new()); +/// calls a retry repaired, and calls that still failed (logged, a few each) +static REPAIRED: AtomicUsize = AtomicUsize::new(0); +static FAILED: AtomicUsize = AtomicUsize::new(0); + +/// `[p, p + len)` may hold pages a protector makes read-only or no-access. +pub fn register(p: usize, len: usize) { + if len == 0 { + return; + } + ANY.store(true, Ordering::Release); + let mut g = RANGES.write().unwrap_or_else(|e| e.into_inner()); + insert_range(&mut g, p, p.saturating_add(len)); +} + +/// `[p, p + len)` is no longer protected (call it before the memory is freed or decommitted). +pub fn unregister(p: usize, len: usize) { + let mut g = RANGES.write().unwrap_or_else(|e| e.into_inner()); + remove_range(&mut g, p, p.saturating_add(len)); +} + +fn insert_range(m: &mut BTreeMap<usize, usize>, mut lo: usize, mut hi: usize) { + // merge with every range that touches [lo, hi) + let touching: Vec<(usize, usize)> = m.range(..=hi).rev().take_while(|&(_, &e)| e >= lo).map(|(&s, &e)| (s, e)).collect(); + for (s, e) in touching { + m.remove(&s); + lo = lo.min(s); + hi = hi.max(e); + } + m.insert(lo, hi); +} + +fn remove_range(m: &mut BTreeMap<usize, usize>, lo: usize, hi: usize) { + let hit: Vec<(usize, usize)> = m.range(..hi).rev().take_while(|&(_, &e)| e > lo).map(|(&s, &e)| (s, e)).collect(); + for (s, e) in hit { + m.remove(&s); + if s < lo { + m.insert(s, lo); + } + if e > hi { + m.insert(hi, e); + } + } +} + +fn in_ranges(m: &BTreeMap<usize, usize>, at: usize) -> bool { + m.range(..=at).next_back().is_some_and(|(_, &e)| at < e) +} + +/// Whether XCL may have protected the page at `at` (a registered range or a guarded view). +pub fn xcl_protected(at: usize) -> bool { + (ANY.load(Ordering::Acquire) && in_ranges(&RANGES.read().unwrap_or_else(|e| e.into_inner()), at)) || super::guards::is_view(at) +} + +/// Range a protector is currently transitioning (`FREEZE_END == 0`: none), published under `PINS` +/// so a concurrent `open_with` that pins an overlapping page waits until `protect` completes +/// before touching it. `FREEZE_LOCK` serializes concurrent protectors without holding `PINS` +/// across `VirtualProtect`. +static FREEZE_LOCK: Mutex<()> = Mutex::new(()); +static FREEZE_AT: AtomicUsize = AtomicUsize::new(0); +static FREEZE_END: AtomicUsize = AtomicUsize::new(0); +static FREEZES_DONE: AtomicUsize = AtomicUsize::new(0); + +/// Run `protect` on `[p, p + n)` only if no 4 KiB page in it is currently pinned by a kernel +/// write. The pin check and active-range mark happen under `PINS`; `protect` itself runs after +/// `PINS` is released, and any concurrent `open` that pins an overlapping page waits until +/// `protect` finishes before touching the page. Returns `false` if any page was pinned. +pub fn while_unpinned(p: usize, n: usize, protect: impl FnOnce() -> bool) -> bool { + let _serial = FREEZE_LOCK.lock().unwrap_or_else(|e| e.into_inner()); + release_done(); + let (lo, hi) = (p & !(STEP - 1), p.saturating_add(n)); + { + let g = PINS.lock().unwrap_or_else(|e| e.into_inner()); + if let Some(m) = g.as_ref().filter(|m| !m.is_empty()) { + let pinned = if m.len() < n / STEP { + m.keys().any(|&k| k >= lo && k < hi) + } else { + (lo..hi).step_by(STEP).any(|k| m.contains_key(&k)) + }; + if pinned { + return false; + } + } + FREEZE_AT.store(lo, Ordering::Release); + FREEZE_END.store(hi, Ordering::Release); + } + struct Done; + impl Drop for Done { + fn drop(&mut self) { + FREEZE_END.store(0, Ordering::Release); + FREEZES_DONE.fetch_add(1, Ordering::AcqRel); + } + } + let _done = Done; + protect() +} + +/// Whether `[p, p + n)` intersects a guarded view (`XCL_PAGE_ALIAS`): another protector owns it. +pub fn meets_guarded_view(p: usize, n: usize) -> bool { + const VIEW: usize = 0x10000; + (p & !(VIEW - 1)..p.saturating_add(n)).step_by(VIEW).any(super::guards::is_view) +} + +#[cfg(test)] +fn is_pinned(at: usize) -> bool { + release_done(); + PINS.lock().unwrap_or_else(|e| e.into_inner()).as_ref().is_some_and(|m| m.contains_key(&(at & !(STEP - 1)))) +} + +/// One region `VirtualQuery` describes: [base, end), committed?, protection. +#[derive(Clone, Copy, Debug, PartialEq)] +pub(crate) struct Region { + pub base: usize, + pub end: usize, + pub committed: bool, + pub protect: u32, +} + +fn query(at: usize) -> Option<Region> { + let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() }; + // SAFETY: VirtualQuery only reads the address space description. + if unsafe { VirtualQuery(at as *const c_void, &mut m, std::mem::size_of_val(&m)) } == 0 { + return None; + } + let base = m.BaseAddress as usize; + Some(Region { base, end: base.saturating_add(m.RegionSize), committed: m.State == MEM_COMMIT, protect: m.Protect }) +} + +const WRITES: u32 = PAGE_READWRITE | PAGE_EXECUTE_READWRITE | 0x08 | 0x80; // + WRITECOPY, EXECUTE_WRITECOPY +const PROTECTED: u32 = PAGE_READONLY | PAGE_NOACCESS | PAGE_EXECUTE_READ; + +/// Whether every byte of `[p, p + n)` is committed and either writable now or on a page XCL +/// protected (`xcl`). `query` describes the region at an address. +pub(crate) fn covers(p: usize, n: usize, mut query: impl FnMut(usize) -> Option<Region>, xcl: impl Fn(usize) -> bool) -> bool { + let Some(end) = p.checked_add(n) else { return false }; + let mut at = p; + while at < end { + let Some(r) = query(at) else { return false }; + if !r.committed || r.protect & PAGE_GUARD != 0 || r.end <= at { + return false; + } + let stop = r.end.min(end); + if r.protect & WRITES == 0 { + if r.protect & PROTECTED == 0 { + return false; + } + let mut page = at & !(STEP - 1); + while page < stop { + if !xcl(page) { + return false; + } + let Some(next) = page.checked_add(STEP) else { break }; + page = next; + } + } + at = stop; + } + true +} + +/// With the switch on: whether XCL may write `[p, p + n)` – committed, and writable or protected +/// by XCL (a store there faults and is opened; a kernel call goes through `open`). Off: false, so +/// a pre-check `old || writable(..)` is the old one. +pub fn writable(p: usize, n: usize) -> bool { + enabled() && n > 0 && covers(p, n, query, xcl_protected) +} + +/// A write to `[p, p + n)` going on: lazy pages committed and guarded views open (`lazy::ensure`), +/// pins on pages of registered ranges. Dropped when the write is over. +#[must_use = "the pages stay open only while this lives"] +pub struct Bracket { + opened: Option<super::guards::Opened>, + pins: Vec<usize>, +} + +impl Drop for Bracket { + fn drop(&mut self) { + unpin(std::mem::take(&mut self.pins)); + } +} + +impl Bracket { + /// An overlapped read (`ov`) writes after its call returned: the pages stay open until done. + pub fn keep_until_done(mut self, ov: usize) { + if let Some(o) = self.opened.take() { + super::guards::open_until_done(o, ov); + } + let pins = std::mem::take(&mut self.pins); + if !pins.is_empty() { + PENDING.lock().unwrap_or_else(|e| e.into_inner()).push((ov, pins)); + } + } + + /// pages of registered ranges this write holds open + pub fn pinned(&self) -> usize { + self.pins.len() + } +} + +fn unpin(pins: Vec<usize>) { + if pins.is_empty() { + return; + } + let mut g = PINS.lock().unwrap_or_else(|e| e.into_inner()); + let m = g.get_or_insert_with(HashMap::new); + for p in pins { + if let Some(c) = m.get_mut(&p) { + *c -= 1; + if *c == 0 { + m.remove(&p); + } + } + } +} + +fn release_done() { + let done: Vec<Vec<usize>> = { + let mut g = PENDING.lock().unwrap_or_else(|e| e.into_inner()); + if g.is_empty() { + return; + } + let (done, pending): (Vec<_>, Vec<_>) = std::mem::take(&mut *g).into_iter().partition(|&(ov, _)| !super::guards::still_pending(ov)); + *g = pending; + done.into_iter().map(|(_, p)| p).collect() + }; + for p in done { + unpin(p); + } +} + +/// Make each committed 4 KiB page of `[p, p + n)` that is not writable now and lies in `pins` +/// take a write fault in user mode: a no-op atomic RMW, so the protector's handler opens it. +unsafe fn touch(p: usize, n: usize, pins: &[usize]) { + for &page in pins { + let Some(r) = query(page) else { continue }; + if r.committed && r.protect & WRITES == 0 && r.protect & PROTECTED != 0 { + let at = page.max(p); + debug_assert!(at < p + n); + (*(at as *const AtomicU8)).fetch_add(0, Ordering::Relaxed); + } + } +} + +/// `[p, p + n)` is about to be written by a kernel call or by XCL (see the module's comment). +pub fn open(p: usize, n: usize) -> Bracket { + open_with(enabled(), p, n) +} + +pub(crate) fn open_with(on: bool, p: usize, n: usize) -> Bracket { + let opened = Some(super::lazy::ensure(p, n)); + if !on || n == 0 || !ANY.load(Ordering::Acquire) { + return Bracket { opened, pins: Vec::new() }; + } + release_done(); + let end = p.saturating_add(n); + let pins: Vec<usize> = { + let g = RANGES.read().unwrap_or_else(|e| e.into_inner()); + let mut v = Vec::new(); + let mut page = p & !(STEP - 1); + while page < end { + if in_ranges(&g, page) { + v.push(page); + } + let Some(next) = page.checked_add(STEP) else { break }; + page = next; + } + v + }; + let mut wait_for = None; + if !pins.is_empty() { + let mut g = PINS.lock().unwrap_or_else(|e| e.into_inner()); + let m = g.get_or_insert_with(HashMap::new); + for &page in &pins { + *m.entry(page).or_default() += 1; + } + let (fa, fe) = (FREEZE_AT.load(Ordering::Acquire), FREEZE_END.load(Ordering::Acquire)); + if fe != 0 && fa < end && p < fe { ~~~~ --- **High**: The freeze overlap test `fa < end && p < fe` compares the unaligned p against the unaligned fe = p'+n', but VirtualProtect, the pins and the `while_unpinned` pin check all work on whole 4 KiB pages, so an open on the same page just past fe skips the wait. If the protector calls `while_unpinned(0x10000, 0x1800)` (fe=0x11800, so VirtualProtect makes 0x10000-0x11fff read-only) and `open(0x11900, 0x100)` runs concurrently, it pins page 0x11000, sees p >= fe and doesn't wait. `touch` skips the page because it's still read-write, `protect()` then makes it read-only, and the kernel ReadFile into 0x11900 fails with ERROR_NOACCESS. `hk_read_file` has no retry, so the title gets a failed read. Rounding fe up to STEP would fix it.
bmjask commented 2026-12-02 15:33:51 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T15:33:51Z.

Review: COMMENTED


Review of 07d529ea: 4 finding(s) (3 critical, 1 high), most severe first.

  1. Critical crates/xcl/src/hle/kernelx/guest_write.rs:330: open_with reads FREEZE_END and then FREEZES_DONE, and while_unpinned's Done::drop clears FREEZE_END and bumps FREEZES_DONE without holding PINS, so the snapshot can be taken after the protector has already finished, and the spin-wa.... (inline)
  2. Critical crates/xcl/src/hle/kernelx/guest_write.rs:290: touch() doesn't exclude PAGE_GUARD pages (covers() does), so a pinned page with PAGE_READONLY|PAGE_GUARD gets a locked RMW that raises STATUS_GUARD_PAGE_VIOLATION, which no protector handles, and it consumes the title's one-shot guard. (inline)
  3. Critical crates/xcl/src/hle/kernelx/guest_write.rs:106: xcl_protected answers "XCL may have protected this page" (any page in a registered range or a guarded view), not "XCL protected it now", so writable()/covers() report pages the title itself made read-only or no-access as writable, .... (inline)
  4. High crates/xcl/src/hle/kernelx/guest_write.rs:331: The freeze overlap test fa < end && p < fe compares the unaligned p against the unaligned fe = p'+n', but VirtualProtect, the pins and the while_unpinned pin check all work on whole 4 KiB pages, so an open on the same page just past .... (inline)

These findings come from an AI-assisted review (Claude Code) and focus on correctness. Each is a candidate; please check it before acting on it.

<!-- greyfinch-sync:ivall/xcl:review:6153969716 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3597#pullrequestreview-6153969716). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:33:51Z. **Review:** COMMENTED --- Review of `07d529ea`: 4 finding(s) (3 critical, 1 high), most severe first. 1. **Critical** `crates/xcl/src/hle/kernelx/guest_write.rs:330`: `open_with` reads FREEZE_END and then FREEZES_DONE, and `while_unpinned`'s `Done::drop` clears FREEZE_END and bumps FREEZES_DONE without holding PINS, so the snapshot can be taken after the protector has already finished, and the spin-wa.... (inline) 2. **Critical** `crates/xcl/src/hle/kernelx/guest_write.rs:290`: `touch()` doesn't exclude PAGE_GUARD pages (`covers()` does), so a pinned page with PAGE_READONLY|PAGE_GUARD gets a locked RMW that raises STATUS_GUARD_PAGE_VIOLATION, which no protector handles, and it consumes the title's one-shot guard. (inline) 3. **Critical** `crates/xcl/src/hle/kernelx/guest_write.rs:106`: `xcl_protected` answers "XCL may have protected this page" (any page in a registered range or a guarded view), not "XCL protected it now", so `writable()`/`covers()` report pages the title itself made read-only or no-access as writable, .... (inline) 4. **High** `crates/xcl/src/hle/kernelx/guest_write.rs:331`: The freeze overlap test `fa < end && p < fe` compares the unaligned p against the unaligned fe = p'+n', but VirtualProtect, the pins and the `while_unpinned` pin check all work on whole 4 KiB pages, so an open on the same page just past .... (inline) --- _These findings come from an AI-assisted review (Claude Code) and focus on correctness. Each is a candidate; please check it before acting on it._
bmjask commented 2026-12-02 15:33:55 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T15:33:55Z.


@Prime1997 could you take a look at this one for review and merge? My automated review notes are above, if any.

<!-- greyfinch-sync:ivall/xcl:comment:7350540478 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3597#issuecomment-7350540478). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:33:55Z. --- @Prime1997 could you take a look at this one for review and merge? My automated review notes are above, if any.
This pull request cannot be merged automatically due to conflicts.
Merge manually to resolve the conflicts.
View command line instructions

Checkout

From your project repository, check out a new branch and test the changes.
git fetch -u origin 'upstream-pr/3597:upstream-pr/3597'
git switch 'upstream-pr/3597'

Merge

Merge the changes and update on Forgejo.

Warning: The "Autodetect manual merge" setting is not enabled for this repository, you will have to mark this pull request as manually merged afterwards.

git switch 'amd-dev'
git merge --no-ff 'upstream-pr/3597'
git switch 'upstream-pr/3597'
git rebase 'amd-dev'
git switch 'amd-dev'
git merge --ff-only 'upstream-pr/3597'
git switch 'upstream-pr/3597'
git rebase 'amd-dev'
git switch 'amd-dev'
git merge --no-ff 'upstream-pr/3597'
git switch 'amd-dev'
git merge --squash 'upstream-pr/3597'
git switch 'amd-dev'
git merge --ff-only 'upstream-pr/3597'
git switch 'amd-dev'
git merge 'upstream-pr/3597'
git push origin 'amd-dev'
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
xcl-dev/xcl!3597
No description provided.