Skip to content

PE loader: patch a CLWB with one atomic jump under the rewrite lock - #3588

Open
BBareth wants to merge 1 commit into
xcl-dev:mainfrom
BBareth:console-cpu/clwb-patch-atomic
Open

BBareth wants to merge 1 commit into
xcl-dev:mainfrom
BBareth:console-cpu/clwb-patch-atomic

Conversation

@BBareth

@BBareth BBareth commented Dec 1, 2026 •

Copy link
Copy Markdown
Contributor

On a CPU without CLWB (older Intel), XCL patches the instruction out at its first fault. The patch made the bytes writable, filled them with NOPs one at a time and restored the protection, with nothing shared between threads. This is item 4 of #278, the part #321 addressed before it was closed with conflicts; #571 fixed only the single-step case. Part of #278.

What could go wrong on main:

  • Two threads patching on one page could restore each other's protection, also against the wait rewrite, which already holds CODE_REWRITE. The page could stay writable, or turn read-only while the other thread still wrote.
  • Another thread could run the half-written bytes (90 0F AE 30 is a nop followed by xsaveopt [rax]).
  • A thread that faulted on the CLWB just before the patch found NOPs, which do not decode, so its fault went on to the title's handlers.
  • The instruction cache was never flushed.

The patch now goes through rewrite_code, like the waits: the first two bytes become a short jump over the instruction (EB, len - 2) in one atomic word write under CODE_REWRITE, the protection is restored, the cache is flushed, and a thread that faulted on the old bytes is retried at the jump. The bytes after the jump stay as they were.

A site whose first two bytes cross an aligned 8-byte word (one address in eight) cannot take the jump in one write. Its opcode and ModRM bytes, which are both in the second word, become those of the NOP with the same operand (0F AE /6 to 0F 1F /0, e.g. 66 0F AE 30 to 66 0F 1F 00): prefixes and operand bytes stay, the length is the same, and the site is patched once like the others (review on 9ac6998).

What is in it

  • crates/xcl/src/eh.rs, the ConsoleOnly::Clwb arm of emulate_console_only: calls rewrite_code(rip, first two bytes, [EB, len - 2]) instead of its own protect / fill / restore. A visit with TF set still leaves the code alone (Console CPU instructions: leave CLWB intact while single stepping #571). A site whose first two bytes cross an aligned 8-byte word takes the NOP form through rewrite_code_within, which writes inside the instruction and records the site with its unchanged prefix, so a stale fault is retried there too.
  • Test clwb_and_a_wait_patched_at_once_on_one_page_keep_its_protection: 32 threads fault at once on a CLWB and on a monitorx in one page; every fault is handled, both sites are patched whole and the page is read-execute afterwards.
  • Test clwb_across_an_atomic_word_becomes_a_nop_with_its_operand: a CLWB at word offset 7, with and without a REX prefix, becomes the NOP of the same length, the bytes around it stay, and a second fault at the site is retried there.
  • Test clwb_single_step_keeps_code_and_normal_faults_still_patch (changed): expects the jump and the untouched tail, and checks that a second fault at the patched address is retried there.

Tested

  • RTX 5070 Ti, driver 32.0.16.2124; i7-12700K; Windows 11 Pro 26200; rustc 1.95.0; debug suite, release smoke.
  • cargo build --workspace, then cargo test --workspace --no-fail-fast -- --test-threads=4 on 81ad460 (on main 6bfb5c5): 2906 passed, 0 failed, 51 ignored.
  • SKIPPED on this adapter: 28: 22 no wave64; 2 no heap windows; 2 no d3d12SDKLayers.dll; 1 no D3D12 debug layer; 1 cannot disable the driver cache (no Developer Mode).
  • With the old patching code put back, the three CLWB tests fail in 3 of 3 runs: the concurrent test logs illegal instruction ... code bytes 90 90 90 90 90 90 (the late faulter) and one run ended in STATUS_ACCESS_VIOLATION (the protection race).

Regression run

xcl-smoke v1
commit: 6bfb5c5153ccc23517daf30aa1071ddb0fadb53c
gpu: NVIDIA GeForce RTX 5070 Ti
title: 9cc6a39e
seconds: 120
exit: 0x0
frames shown: 3099 (PresentX 3099)
presents per 2 s (last 3): 60 16 27
device removals: 0
crashes: 0
peak commit: 32491 MB
xcl-smoke v1
commit: 81ad460d7f5eb2f9d662c7a056fd8cfb5da4ab28
gpu: NVIDIA GeForce RTX 5070 Ti
title: 9cc6a39e
seconds: 120
exit: 0x0
frames shown: 3082 (PresentX 3082)
presents per 2 s (last 3): 53 11 23
device removals: 0
crashes: 0
peak commit: 33381 MB

Each run follows one warm-up run of the same build; the A button is pressed once at 70 s. Earlier in this session the title lost the D3D12 device (0x887a0006, DRED state 7, no breadcrumbs) between 118 s and 123 s in 2 of 4 runs of main 6bfb5c5 and in 2 of 4 runs of the previous head, interleaved; the two runs of this head (warm-up and the block above) had none. The log has no CLWB patch line in any run (this CPU executes CLWB), so the changed code did not run in them.

Not tested

  • A real CLWB fault: this CPU (i7-12700K) runs CLWB natively, so the changed path is reached only by the unit tests, which call the handler with a made-up CONTEXT. The smoke runs are a regression check only.
  • The NOP form of a site that crosses a word (66 [REX] 0F 1F /0 with the site's operand bytes) was not executed: the test checks the patched bytes, the bytes around them and the retry of a stale fault.
  • With open Tests: cover CLWB, MONITORX, MWAITX, and faulting CLZERO in eh #1829: it adds clwb_patches_instruction_bytes_to_nop_and_advances_rip, which expects NOP bytes at an ordinary site; whichever of the two lands second has to adjust that test.
  • AMD CPUs run CLWB natively and never take this path.

AI use

  • Claude Code, Claude Fable 5.2: wrote the change, the tests and this description, and ran the suite and the regression runs.

🤖 Generated with Claude Code

@github-actions github-actions Bot added the area:hle kernelx, XGameRuntime, XAudio2, VFS, PE loader, TLS, EH label Dec 1, 2026
@fromthemoonx

fromthemoonx commented Dec 1, 2026 •

Copy link
Copy Markdown

Rerun on the new head (81ad460d, the cross-word fix after Foniass's review). The earlier report, on 9ac69984, is below.

merge-check
base: f07e426
head: 81ad460
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2906 passed, 0 failed, 51 ignored (base: 2904 passed, 0 failed, 51 ignored); SKIPPED: 25 (22 no wave64, 2 no heap windows, 1 no GPU_UPLOAD heaps), the same set as base; failing: none
review: read the change since 9ac69984 (eh.rs). No correctness problem found.

  • A CLWB whose first two bytes cross an aligned word (rip & 7 == 7) now gets 0F 1F with the same ModRM (modrm & 0xC7 clears the /6 reg field), SIB and displacement, through rewrite_code_within. That is a NOP of the same length, and the prefixes before and the operand after stay.
  • At offset 7 the two bytes changed (AE, ModRM) are always inside the next aligned word, so one CAS covers them, and the first word is untouched.
  • The site is recorded with its first skip bytes, so a thread that faulted on the old bytes finds 0F 1F (not a console instruction), matches rewritten_wait, and is retried. The test checks that.
  • Each 30 of 30 alone: eh::tests::clwb_across_an_atomic_word_becomes_a_nop_with_its_operand, clwb_and_a_wait_patched_at_once_on_one_page_keep_its_protection, clwb_single_step_keeps_code_and_normal_faults_still_patch.
  • eh::tests:: at --test-threads=8: 30 of 30 ok.
  • Mutation: the cross-word branch removed (main's step-over only) fails clwb_across_an_atomic_word_becomes_a_nop_with_its_operand. Good.
  • This Ryzen 7 5700X has CLWB, so a real CLWB fault does not happen here. Tests: cover CLWB, MONITORX, MWAITX, and faulting CLZERO in eh #1829's test (NOP bytes at the site) still clashes, as Foniass said.
    performance: none on CPUs with CLWB. Without it, every site, including those crossing a word, is patched once.
    verdict: safe to merge
    hardware / tool and model: RTX 3060 12 GB (610.88), Ryzen 7 5700X, Windows 11 Pro 26300 / Claude Code (Claude Opus 5.5)
Earlier report on 9ac6998 (base 6bfb5c5)
merge-check
base: 6bfb5c5153ccc23517daf30aa1071ddb0fadb53c
head: 9ac69984280edd2d47b7606bef5cc1d1f1fc7ffe
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2906 passed, 0 failed, 51 ignored (base: 2904 passed, 0 failed, 51 ignored); SKIPPED: 25 (22 no wave64, 2 no heap windows, 1 no GPU_UPLOAD heaps), the same set as base; failing: none
review: read the whole diff (`eh.rs`, +102 -9). No correctness problem found.
- The CLWB arm now goes through `rewrite_code`:
  - It is serialized on `CODE_REWRITE` with the wait rewrites.
  - It writes the `EB, len - 2` jump in one atomic word write and restores the protection.
  - It records the site in `REWRITTEN_WAITS`. A thread that faulted on the old bytes then finds the jump: `decode` returns `None`, `rewritten_wait` matches, and the thread is retried at the jump.
  - A site whose first two bytes cross an aligned 8-byte word is refused by `rewrite_code` (`off + 2 > 8`) and stepped over each time. The TF case leaves the code alone as before (#571).
- The three tests touched, 30 of 30 alone each:
  - `eh::tests::clwb_and_a_wait_patched_at_once_on_one_page_keep_its_protection`
  - `eh::tests::clwb_across_an_atomic_word_stays_emulated`
  - `eh::tests::clwb_single_step_keeps_code_and_normal_faults_still_patch`
- `eh::tests::` at `--test-threads=8`: 30 of 30 ok.
- Mutation: the same two jump bytes written with `VirtualProtect` + byte stores instead of `rewrite_code` (no lock, no record of the site). 10 runs of each test:
  - the concurrent test failed 10 of 10: some runs with "a concurrent patch must not leave the page writable", some with a segmentation fault;
  - `clwb_across_an_atomic_word_stays_emulated` failed 10 of 10 (the bytes were patched);
  - `clwb_single_step_keeps_code_and_normal_faults_still_patch` failed 10 of 10 (the stale fault returned 0 instead of -1).
  Good.
- This Ryzen 7 5700X has CLWB, so a real CLWB fault does not happen here. The tests call `emulate_console_only` directly. No title with CLWB was run on a CPU without it.
performance: none on CPUs with CLWB. On CPUs without it, each site is patched once as before; the jump replaces the NOPs.
verdict: safe to merge
hardware / tool and model: RTX 3060 12 GB (610.88), Ryzen 7 5700X, Windows 11 Pro 26300 / Claude Code (Claude Opus 5.5)

@github-actions github-actions Bot added needs-1st-check Passes gates; needs first independent merge-check (#3041) needs-2nd-check Has 1 safe merge-check; needs second independent check (#3041) and removed needs-1st-check Passes gates; needs first independent merge-check (#3041) labels Dec 1, 2026
@Foniass

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Review (head 9ac6998, diff read, not a merge-check):

  • One CLWB site in eight now faults at every visit. rewrite_code (eh.rs ~454) returns false when the instruction's first two bytes start at offset 7 of an aligned 8-byte word, and the CLWB arm (~585) ignores that and only steps RIP, so the site is never patched and every execution goes through the vectored handler again. On main such a site was patched to NOPs once, which b25582a added precisely to avoid repeated exceptions in tight loops. On a CPU without CLWB this is a default-path cost the PR does not measure; these sites need a fallback that still patches them once.
  • Clashes with open Tests: cover CLWB, MONITORX, MWAITX, and faulting CLZERO in eh #1829. Tests: cover CLWB, MONITORX, MWAITX, and faulting CLZERO in eh #1829 (test-only) adds clwb_patches_instruction_bytes_to_nop_and_advances_rip, which expects NOP bytes at the site. Whichever of the two lands second breaks that test.

Fine: the patch now takes CODE_REWRITE, so it cannot restore page protection over another rewrite on the same page; the two-byte EB len-2 jump goes in with one CAS and leaves no half-written instruction; a thread that faulted on the old bytes is retried through rewritten_wait (EB does not decode, so it reaches that path); the tests check the jump bytes, the untouched tail, the stale-fault retry and the page protection.

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

A CLWB on a CPU without it is patched out at its first fault. The patch
made the bytes writable, filled them with NOPs one at a time and put
the protection back, with nothing shared between threads (xcl-dev#278, item 4):

- two threads patching on one page could restore each other's
  protection (also against the wait rewrite, which holds CODE_REWRITE);
- another thread could run the half-written bytes (90 0F AE 30 is a
  nop and xsaveopt [rax]);
- a thread that faulted on the CLWB just before the patch found NOPs,
  which do not decode, and its fault went on to the title's handlers;
- the instruction cache was never flushed.

The patch now goes through rewrite_code, like the waits: the first two
bytes become a short jump over the instruction in one atomic word
write under CODE_REWRITE, the protection is restored, the cache is
flushed, and a thread that faulted on the old bytes is retried at the
jump. The bytes after the jump stay as they were.

A site whose first two bytes cross an aligned 8-byte word cannot take
the jump in one write. Its opcode and ModRM bytes, which are both in
the second word, become those of the NOP with the same operand
(0F AE /6 -> 0F 1F /0): the prefixes and the operand bytes stay, so the
length is the same and the site is patched once like the others
(rewrite_code_within records the site with its unchanged prefix).
A visit with TF set still leaves the code alone (xcl-dev#571).

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
@BBareth
BBareth force-pushed the console-cpu/clwb-patch-atomic branch from 9ac6998 to 81ad460 Compare December 1, 2026 21:49
@BBareth

BBareth commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

On the review of 9ac6998: both points checked against the source; the first is fixed in 81ad460.

One CLWB site in eight faulted at every visit: right. rewrite_code refuses a rewrite that crosses an aligned word, and the arm only stepped RIP then, so a site at word offset 7 was never patched, where main patched it once. Such a site now gets a second form instead of the jump: its opcode and ModRM bytes, which are both in the second word, become those of the NOP with the same operand (0F AE /6 to 0F 1F /0, e.g. 66 0F AE 30 to 66 0F 1F 00). Prefixes and operand bytes stay, the length is the same, it is one atomic write under CODE_REWRITE, and the site is recorded with its unchanged prefix (rewrite_code_within), so a thread that faulted on the old bytes is retried there as for the jump. Every site is patched once again. The test is now clwb_across_an_atomic_word_becomes_a_nop_with_its_operand (offset 7, with and without a REX prefix: the patched bytes, the bytes around them, the retry of a stale fault).

Clash with #1829: yes, its clwb_patches_instruction_bytes_to_nop_and_advances_rip expects NOP bytes at an ordinary site and this PR writes EB, len - 2 there. Whichever lands second has to adjust that test; I added it to Not tested and will rebase if #1829 goes first.

Suite on 81ad460: 2906 passed, 0 failed, 51 ignored, 28 SKIPPED lines. The smoke block in the description is rerun on this head (3082 frames, no device removal, no crash). Not done: the NOP form was not executed on a CPU, the test checks bytes.

AI use: Claude Code, Claude Fable 5.2 checked the points against the source, wrote the change and this comment and ran the tests.

@github-actions github-actions Bot removed the needs-2nd-check Has 1 safe merge-check; needs second independent check (#3041) label Dec 1, 2026
@Foniass

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Contributor

Follow-up review (head 81ad460, since 9ac6998, diff read, not a merge-check):

  • One CLWB site in eight faulted at every visit: fixed. When the first two bytes cross an aligned word, the CLWB arm (eh.rs ~597-601) now writes a NOP with the same operand (0F AE /6 to 0F 1F /0, prefixes and operand bytes kept, same length) with one CAS through rewrite_code_within (~454), which records the site with its prefix bytes so a stale fault is retried through rewritten_wait. clwb_across_an_atomic_word_becomes_a_nop_with_its_operand (~1718) checks both encodings, the surrounding bytes and the retry.
  • Clashes with open Tests: cover CLWB, MONITORX, MWAITX, and faulting CLZERO in eh #1829: still open. Tests: cover CLWB, MONITORX, MWAITX, and faulting CLZERO in eh #1829's clwb_patches_instruction_bytes_to_nop_and_advances_rip still expects NOP bytes where this PR writes EB, len - 2; the description now lists it, so whichever lands second adjusts that test.

New:

Fine: only the opcode and ModRM bytes change, both in one aligned word; 0F is never a prefix byte so the first 0F AE found is the opcode; modrm & 0xC7 keeps mod/rm, so SIB, displacement and length stay valid; the jump path, lock, protection restore and TF case are unchanged.

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

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

Labels

area:hle kernelx, XGameRuntime, XAudio2, VFS, PE loader, TLS, EH

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants