Skip to content

Console CPU instructions: serialize CLWB hot-patching and flush icache (#278) - #321

Open
TG0000 wants to merge 1 commit into
ivall:mainfrom
TG0000:fix/clwb-hotpatch-race
Open

TG0000 wants to merge 1 commit into
ivall:mainfrom
TG0000:fix/clwb-hotpatch-race

Conversation

@TG0000

@TG0000 TG0000 commented Nov 23, 2026 •

Copy link
Copy Markdown

Part of #278 (item 4: the CLWB hot-patch race). Items 1 and 2 (the CLZERO loop) are in #295 and #290; item 3 (is_writable) is not in this PR.

A CLWB was hot-patched like this: make its bytes writable, fill them with 0x90 one byte at a time, put the protection back. Nothing was shared between threads, which caused four problems:

  • Protection race. Two threads patching on one page could restore each other's protection. The page could stay PAGE_EXECUTE_READWRITE, or become read-only again while the other thread was still writing.
  • Torn instruction. Another thread could run half-written bytes. 90 0F AE 30 is a nop followed by xsaveopt [rax].
  • Late faulter. A thread that faulted on the CLWB just before another thread patched it read the NOPs. NOPs don't decode, so its fault went on to the title's handlers.
  • No flush. FlushInstructionCache was never called.

What is in it

  • One lock covers all CLWB patching: making the page writable, the write, restoring the old protection and FlushInstructionCache. The lock also guards the set of addresses already patched. Everything is in crates/xcl/src/eh.rs.
  • Only the first two bytes change. They become a short jump over the instruction (EB, len - 2), written by a single lock cmpxchg, so another thread runs either the whole CLWB or the whole jump. The bytes after the jump are left as they were.
  • A fault on an address that is already patched resumes at the jump. This covers a thread that faulted before the patch and reads the bytes after it.
  • A CLWB whose first two bytes cross a cache line is not patched, because no single store there is atomic. It is stepped over on every fault, as before the hot-patch existed.

Tested

  • Hardware: AMD Ryzen 9 5900X, Windows 11 Pro. No GPU is involved in these tests.
  • Toolchain: Rust 1.100.0 stable-x86_64-pc-windows-gnu with llvm-mingw, debug build.
  • The 5900X runs CLWB natively, so it never raises the fault. The tests call the exception handler's emulation (emulate_console_only) directly on code pages registered as a title module and set to PAGE_EXECUTE_READ. The patched code is then actually executed.
  • New tests in eh::tests, all passing:
    • clwb_patch_is_a_short_jump_over_the_instruction: the jump bytes for lengths 4 to 15; no patch when the bytes cross a cache line or a page, or for an invalid length.
    • clwb_is_patched_into_a_jump_and_the_page_keeps_its_protection: clwb [rax], clwb [rsp+8] at an odd address, and clwb [r8]. Only two bytes change, the page is PAGE_EXECUTE_READ afterwards, a second (late) fault resumes at the jump, and the code runs.
    • clwb_across_a_cache_line_is_stepped_over
    • clwb_patching_from_many_threads_at_once: 8 threads fault on 64 CLWBs on one page at once, in different orders, some twice. A watcher thread checks that each CLWB's first two bytes are only ever the old bytes or the jump. Every fault is handled, every CLWB is patched, the page ends PAGE_EXECUTE_READ, and all the patched code runs. Passed 5 of 5 runs.
  • cargo test --workspace --exclude testgame-mw --no-fail-fast -- --test-threads=4: xcl lib 614 passed, 1 failed, 20 ignored. All other targets passed apart from the e2e target, which had 1 failure. Neither failure involves this change:
    • pe::tests::parses_own_test_binary_tls expects the test binary to have a PE TLS directory. A windows-gnu binary doesn't have one; the MSVC target does.
    • e2e::test_title_runs_and_game_folder_is_untouched needs testgame_mw.dll, and testgame-mw was excluded because it doesn't build with this local toolchain.
  • No new warnings. The one warning in the build, the fetch_update deprecation in hle/xgameruntime/mod.rs, was already there (see XGameRuntime: try_update instead of the deprecated fetch_update #251).

Regression run
Windows 11, Ryzen 9 5900X, AMD Radeon RX 6800, Rust stable x86_64-pc-windows-msvc (VS 2022 Build Tools, link.exe), cargo build --release -p xcl, scripts/smoke.ps1 -Seconds 45, one run at a time under a RAM watchdog.

main (a6f5f7a, current origin/main, this PR's base):

xcl-smoke v1
commit: a6f5f7a74cc620c1f88a9e3669a633d10c3c8212
gpu: AMD Radeon RX 6800
title: retail-title-1.0.2.1
seconds: 45
exit: 0x0
frames shown: 828 (PresentX 828)
presents per 2 s (last 3): 59 60 60
device removals: 0
crashes: 0
peak commit: 15144 MB

PR (head commit, no local changes):

xcl-smoke v1
commit: dfa332a5a4217d8a90fdeac1f8a049cfd808c699
gpu: AMD Radeon RX 6800
title: retail-title-1.0.2.1
seconds: 45
exit: 0x0
frames shown: 848 (PresentX 849)
presents per 2 s (last 3): 44 48 54
device removals: 0
crashes: 0
peak commit: 15149 MB

No regression: 848 frames against 828 on its base, no device removals or crashes, peak commit 15149 MB against 15144 MB. The 5900X has CLWB natively, so this run doesn't reach the hot-patching path; it only shows nothing else changed. Frame counts move by about 10 % between runs of the same commit on this machine (earlier runs of main gave 843, 709 and 828).

Rebased onto current main (a6f5f7a): the one conflict, in eh.rs, is resolved by keeping main's tests (cmp_eflags_matches_x86_64_sub_flags, the CLZERO loop test, code_bytes_on_the_instructions_page_are_not_asked_about) next to the CLWB ones. On the rebased head, built with stable-x86_64-pc-windows-msvc, cargo test -p xcl --lib eh passes: 11 passed, 0 failed, including the four clwb_* tests.

Not tested

  • A real CLWB fault (an Intel CPU before Ice Lake).
  • Other code in XCL that changes the protection of title pages (for example hook_gs_failure) doesn't take this lock. Those patches run at load time, not from the exception handler.

AI use

  • Claude Opus 5.5 (Claude Code) wrote the change and the tests and ran them. The author reviewed the result.

🤖 Generated with Claude Code

@ethandepstein-del

Copy link
Copy Markdown

Static code audit of 7d5f5f0 (not tested on Windows / pre-Ice Lake CPU; no game files):

Overall this is a very clean fix for the CLWB hot-patch race in #278:

  • Lock ordering for late faulters: Holding CLWB_PATCHES across VirtualProtect(RWX) -> cas_u16 -> VirtualProtect(old) -> FlushInstructionCache -> patches.insert(rip) ensures any concurrent thread that reads [0xEB, len - 2] after cas_u16 and enters clwb_patched(rip) blocks until rip is inserted, so it never leaks to the title's exception handler.
  • Atomicity & inline asm: Guarding rip % 64 == 63 keeps the 2-byte lock cmpxchg within one cache line, and cas_u16 correctly omits preserves_flags since cmpxchg clobbers EFLAGS.
  • No VEH deadlock: CLWB_PATCHES is only acquired on the ILLEGAL_INSTRUCTION VEH path (emulate_console_only).

One small hardening suggestion

  • DLL unload / address reuse (eh.rs:360): Currently if clwb_patched(rip) { return -1; } unconditionally resumes at rip. If a DLL containing a patched CLWB is ever unloaded and another module/code is later mapped at the same address and hits a genuine #UD at rip, returning -1 without checking the bytes would spin indefinitely. Checking code.first() == Some(&0xEB) && clwb_patched(rip) (and/or pruning CLWB_PATCHES if a module is unregistered) prevents that cleanly.
  • (Tiny test comment nit: in clwb_patching_from_many_threads_at_once, k * 0x20 + 2 * (k % 4) for k % 4 == 3 puts the 2-byte load at offset +6..+8, which is aligned inside the qword rather than crossing a qword boundary — harmless, just slightly different from the comment.)

AI use: static code audit of 7d5f5f0 with Antigravity (Gemini 4 Neon).

@nullmarsh

Copy link
Copy Markdown

MSVC run, since Not tested lists the MSVC toolchain. This PR's head 7d5f5f0 builds and passes with x86_64-pc-windows-msvc. It no longer merges cleanly with main a6f5f7a, which changed eh.rs (#306's is_writable window check), so I ran the head as it is, not merged.

Tested

  • Ryzen 7 5800X3D (runs CLWB natively, so like your 5900X it only exercises the emulation path the tests call directly); Windows 11 Pro 26200; Rust 1.100.0 stable-x86_64-pc-windows-msvc; debug build.
  • cargo test -p xcl --lib clwb: all 4 pass (clwb_patch_is_a_short_jump_over_the_instruction, clwb_is_patched_into_a_jump_and_the_page_keeps_its_protection, clwb_across_a_cache_line_is_stepped_over, clwb_patching_from_many_threads_at_once).
  • clwb_patching_from_many_threads_at_once repeated 20 times: 20 of 20 pass.
  • cargo test -p xcl --lib on the head: 615 passed, 0 failed, 20 ignored.

Not tested

  • A real CLWB fault (needs a pre-Ice Lake Intel CPU); the merge with current main (conflict in eh.rs).

AI use

  • Claude Code (Claude Opus 5.5) ran the commands and wrote this report from the logs; I checked it before posting.

ivall#278)

A CLWB was hot-patched by making its bytes writable, filling them with
0x90 one byte at a time and restoring the protection, with nothing shared
between threads:

- two threads patching on one page could restore each other's protection,
  leaving the page PAGE_EXECUTE_READWRITE or making it read-only while the
  other still wrote;
- another thread could run the half-written bytes (90 0F AE 30 is a nop and
  then xsaveopt [rax]);
- a thread that faulted on the CLWB just before another patched it read
  NOPs, which do not decode, and its fault went on to the title's handlers;
- the instruction cache was not flushed.

Now the patching runs under one lock, which also keeps the set of patched
addresses. Only the first two bytes change, to a short jump over the
instruction (EB, len - 2), written by a single lock cmpxchg so another
thread runs either the whole CLWB or the whole jump. The old protection is
put back and FlushInstructionCache is called. A fault on an address already
patched resumes at the jump. A CLWB whose first two bytes cross a cache line,
where no single store is atomic, is stepped over on each fault instead.

Tests: the jump bytes; three CLWB lengths (one at an odd address) patched,
the page PAGE_EXECUTE_READ afterwards, a late fault resumed, and the code
run; a cache-line crossing stepped over; eight threads faulting on 64 CLWBs
of one page at once while a watcher checks that each CLWB's first two bytes
are only ever the old ones or the jump.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@TG0000
TG0000 force-pushed the fix/clwb-hotpatch-race branch from 7d5f5f0 to dfa332a Compare November 24, 2026 00:22
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants