Skip to content

PE loader: rewrite console waits that cross an 8-byte word - #3548

Open
BBareth wants to merge 1 commit into
xcl-dev:mainfrom
BBareth:console-cpu/rewrite-waits-across-words
Open

BBareth wants to merge 1 commit into
xcl-dev:mainfrom
BBareth:console-cpu/rewrite-waits-across-words

Conversation

@BBareth

@BBareth BBareth commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

On a CPU without monitorx / mwaitx (Intel), the first fault rewrites a console wait in place, but only when the instruction fits in one aligned 8-byte word. GTA 6 has a monitorx at an address ending in 7, so its 3 bytes cross two words. rewrite_code refused it, and every poll of that spin loop raised #UD and was emulated. Part of #505.

Such a wait now becomes a form that differs from the original in one word only. A thread running it therefore fetches either the old or the new instruction, never half of each:

  • Two bytes or more in the first word: those bytes become a short jump over the rest (0F 01 FA → EB 01 FA).
  • One byte in the first word (a plain 3-byte wait): its last two bytes, both in the second word, become 1F C0, which makes the whole instruction 0F 1F C0 (nop eax).
  • A prefixed wait with one byte in the first word stays emulated.

Neither cross-word form has room for the pause an mwaitx gets inside one word, so a spin loop around such an mwaitx runs without one once rewritten.

rewrite_code now changes only the bytes that differ, inside their word, with the same compare-and-retry, lock and page protection as before.

The first version of this PR wrote the whole 16-byte block with cmpxchg16b. Review pointed out that nothing promises another core fetches such a write whole. A thread could then decode a mix, for example 90 01 FA (add edx, edi). That path is gone.

What is in it

  • crates/xcl/src/eh.rs:
    • rewrite_code finds the range of bytes that differ and rewrites it only when it lies in one aligned word;
    • wait_replacement picks the form above for a monitorx / mwaitx site;
    • the two wait arms now share it.
  • Test a_wait_across_two_words_changes_in_one_word, which replaces a_rewrite_crossing_an_atomic_word_stays_emulated:
    • sites at word offset 6 (0x16, 0x26), two bytes in the first word, take the jump;
    • plain waits at word offset 7 (0x37, 0x47), one byte in the first word, take 0F 1F C0;
    • a prefixed one (0x57) stays emulated;
    • the bytes around each site are untouched.
    • It fails on main.
  • Test the_one_word_wait_forms_run_as_no_ops: both forms are executed on this CPU between mov eax, 42 and ret, and the function returns 42.

Tested

  • RTX 5070 Ti, driver 32.0.16.2124; i7-12700K (no monitorx, so these rewrites happen on this CPU); 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 6a44255 (on main 078358a): 3007 passed, 0 failed, 52 ignored.
  • SKIPPED on this adapter, 28 in all:
    • 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)
  • Still merges cleanly into main 395405e.
  • GTA 6 (Xbox 1.0.2.1), with the first (16-byte) version on an earlier local tree with other open PRs, 10 s WPR CPU trace at 700 s in the world:
    • before, the render thread's samples were 49 % kernel, about 2,359 of them in the exception path from that monitorx;
    • after, the site was gone from the kernel callers;
    • the frame rate did not change (2–5 presents per 2 s): this saves CPU time, it is not what limits GTA 6 there.

Regression run

xcl-smoke v1
commit: 078358a058f7ba5d16690dba8dc4e55d2c88ae0a
gpu: NVIDIA GeForce RTX 5070 Ti
title: 9cc6a39e
seconds: 120
exit: 0x0
frames shown: 3046 (PresentX 3046)
presents per 2 s (last 3): 15 27 19
device removals: 0
crashes: 0
peak commit: 32465 MB
xcl-smoke v1
commit: 6a442550b8c0e41014b232d43e12ca1d8bc68ada
gpu: NVIDIA GeForce RTX 5070 Ti
title: 9cc6a39e
seconds: 120
exit: 0x0
frames shown: 3072 (PresentX 3072)
presents per 2 s (last 3): 24 24 26
device removals: 0
crashes: 0
peak commit: 32465 MB

Each run follows one warm-up run of the same build; the A button is pressed once at 70 s. An earlier run of this head (2259 frames, no removal, no crash) overlapped a release build of another tree on this machine and is left out. The run after it is shown, and a third one had 3061 frames.

Not tested

  • The WPR trace was not repeated with this form. GTA 6's site is a plain monitorx at word offset 7 (one byte in the first word), so it takes 0F 1F C0, as at 0x37 in the test.
  • Cross-modifying code on real cores while they run the site: the form is chosen so that only one word changes, but no test runs the site on another core during the write.
  • With open PE loader: patch a CLWB with one atomic jump under the rewrite lock #3588 (the CLWB patch through rewrite_code): both change rewrite_code; whichever lands second needs a rebase.
  • AMD CPUs: they run monitorx / mwaitx natively and never take this path.
  • The 120 s smoke does not show the CPU saving: XCL logs no count of emulated waits.

AI use

  • Claude Code, Claude Opus 5.5: found the cause in a WPR trace, wrote the first fix and the trace runs, then rewrote it to the one-word form after review, wrote both tests, ran the suite and the regression runs above, and wrote this description.
  • Claude Code, Claude Fable 5.2: rebased the first version and replaced its inline assembly with the intrinsic after an earlier review.

🤖 Generated with Claude Code

@github-actions github-actions Bot added the area:hle kernelx, XGameRuntime, XAudio2, VFS, PE loader, TLS, EH label Nov 30, 2026
@thehollowedone

Copy link
Copy Markdown
Contributor

Source review of current head 29be3d1d: two issues need resolution before the 16-byte rewrite path is safe to use.

  1. The new cmpxchg16b assembly may lose its address. cell = in(reg) can be allocated to rbx. Rust's inline-assembly reference explicitly allows reg operands to use LLVM-reserved base registers. xchg {new_lo}, rbx then replaces the address in rbx with replacement bytes before cmpxchg16b [{cell}], so a cross-word wait can fault in the exception handler. The stable cmpxchg16b intrinsic avoids this register-allocation hazard; it returns the prior 128-bit value needed by the retry loop. Please test both successful exchange and failed comparison, including preservation of the surrounding bytes.

  2. CLWB can change the same page's protection concurrently. The new wait path holds CODE_REWRITE across its RWX/write/restore sequence, but the existing CLWB patch path does not. If CLWB first saves RX, then the wait saves RWX, CLWB can restore RX before the wait's write. That can fault inside the handler; another ordering can leave the page RWX. This underlying CLWB race is tracked in #278. Serialize CLWB's full protection/write/restore sequence with CODE_REWRITE, and add a controlled same-page CLWB plus offset-7 wait regression that checks the final protection is RX. The existing concurrent test covers two waits, so it misses this interleaving.

These are source-level findings. I did not run a build, GPU test, or title on this PR. AI use: Codex (GPT-6.2 Sol) reviewed the integration and existing tracker; Codex (GPT-6.2 Astra) traced the assembly and concurrency paths.

@BBareth
BBareth force-pushed the console-cpu/rewrite-waits-across-words branch from 29be3d1 to 3c29d4b Compare December 1, 2026 07:28
@BBareth

BBareth commented Dec 1, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the review. Head is now 3c29d4b.

  1. Confirmed. cell = in(reg) could be given rbx, and the xchg would then replace the address. compare_exchange_16 now calls std::arch::x86_64::cmpxchg16b instead of asm!. The new test compare_exchange_16_stores_on_a_match_and_reports_a_mismatch covers a matching exchange, a failed comparison (nothing stored, the value found is returned) and the blocks on either side.
  2. Confirmed from the source, but it is not from this PR: on main the CLWB path already patches without CODE_REWRITE while the 8-byte wait rewrite holds it, so the same interleaving exists there. It is tracked in Console CPU emulation: ClzeroLoop decoder/semantics, is_writable guards, and CLWB hot-patch race #278. I left it out of this PR to keep it to one change, and listed it under Not tested.

Suite on 3c29d4b: 2890 passed, 0 failed, 51 ignored, 28 SKIPPED lines (as before). The smoke blocks in the description are rerun on this head.

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

@github-actions github-actions Bot added the needs-pr-check Failing the PR description check (CONTRIBUTING.md) label Dec 1, 2026
@Foniass

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

merge-check
base: 7d86c5d
head: 3c29d4b
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2897 passed, 0 failed, 51 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 main); failing: none
review: re-reviewed at 3c29d4b. Since 29be3d1 the hand-written assembly is replaced by the stable std::arch::x86_64::cmpxchg16b intrinsic (eh.rs ~450), with a new single-threaded test of the exchange. Only CPUs without monitorx / mwaitx (Intel) change; this run is on a Ryzen 7 7800X3D, which has monitorx, so the smoke run doesn't reach the new path. Findings: (1) replace_code_block (~457) still reads the block with a plain volatile read and returns early when it already shows the replacement; sound only while rewrites of a site are serialized by CODE_REWRITE, while the CLWB patch (~614) writes code bytes without that lock (formally a data race; #278, the same on main, now noted in the PR). (2) No concurrent test of two rewrites in one 16-byte block, unlike the 8-byte path (~1465). Fine: the intrinsic removes the old rbx juggling, the failure ordering (Acquire) is allowed, the new test checks a stored match, a reported mismatch and that neighbouring blocks are untouched, the 16-byte-aligned block stays within one page and cache line, lengths still come from insn::decode with a same-length replacement, and the earlier test fails without the change.
performance: 60 s smoke of a retail title, main 7d86c5d vs this merge (a21b7f0d): 1663 -> 1680 frames shown (101 %; last presents per 2 s: 60 60 60), peak commit 17153 -> 17475 MB, 0 device removals, 0 crashes.
verdict: safe to merge (on this AMD CPU the changed path isn't reached; an Intel run is what exercises it)
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.

@github-actions github-actions Bot added needs-2nd-check Has 1 safe merge-check; needs second independent check (#3041) and removed needs-pr-check Failing the PR description check (CONTRIBUTING.md) labels Dec 1, 2026
@Foniass

Foniass commented Dec 1, 2026

Copy link
Copy Markdown
Collaborator

Triage (#1607) – head 3c29d4b

No open or merged PR makes the same change. #2618 (open) adds an older 8-byte-only rewrite_code. Main already has its own form of that, and this PR extends main's form to an aligned 16-byte block with cmpxchg16b.
No problems found in the diff. A 16-byte aligned block never crosses a page, the compare-and-retry reloads atomically after a torn first read, and the test covers offsets 6, 7 and 14 plus the bytes around them.
Recommendation: keep open.

AI review: Claude Code (Claude Opus 5.5), diffs read only, not built or run; not checked by a human.

@bmjask bmjask left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Review of 3c29d4bc: 2 finding(s). 2 are 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.

Comment thread crates/xcl/src/eh.rs Outdated
use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READWRITE};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
let word = at & !7;
let width = if (at & 7) + new.len() <= 8 { 8 } else { 16 };

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This drops the guard that kept rewrites inside one aligned 8-byte word, and the test that checked it. A thread running the code during the patch can now decode a mix of old and new bytes when the instruction spans the two halves of the 16-byte block. Data reads of a locked cmpxchg16b are atomic, but the x86 manuals don't promise that for instruction fetch or for code already decoded on another core, since cross-modifying code needs serialization. Take monitorx 0F 01 FA at block offset 7 (the GTA 6 site) rewritten to 90 90 90 while another thread runs it. New-low/old-high decodes as 90 then 01 FA = add edx, edi, which silently corrupts EDX. Old-low/new-high decodes 0F 90 90 .. = seto byte [rax+disp32], a write to a random address. For mwaitx (F3 90 90) the mix is F3 01 FB = rep add ebx, edi. The 8-byte path never mixes bytes because the whole instruction is in one word. Patching that's safe across halves needs the int3 method (CC first byte, flush, write the tail, write the first byte), which the stale-exception lookup could treat as retry; that works at any alignment.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Agreed, and the 16-byte path is gone in 005df98. The word guard is back: rewrite_code rewrites only when the bytes that differ lie in one aligned 8-byte word. A wait across two words now gets a form that differs from it in one word only:

  • with two or more bytes in the first word, those bytes become a jump over the rest (0F 01 FA → EB 01 FA, so only the first byte changes);
  • with one byte in the first word, the GTA 6 case, the two bytes in the second word become 1F C0, making 0F 1F C0.
    A core sees either the old instruction or the new one, and no mix like 90 01 FA can occur. A prefixed wait with one byte in the first word stays emulated. The test a_wait_across_two_words_changes_in_one_word checks which bytes change at each offset, and the_one_word_wait_forms_run_as_no_ops executes both forms.

Comment thread crates/xcl/src/eh.rs Outdated

/// `replace_code_word` for an instruction across two words of an aligned 16-byte block.
unsafe fn replace_code_block(cell: *mut u128, off: usize, expected: &[u8], new: &[u8]) -> bool {
// a torn read only fails the first compare, which then reloads the block atomically

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The comment says a torn first read is retried with an atomic reload, but if that read doesn't show expected the function returns false right away without reaching cmpxchg16b. The first read is a plain ptr::read_volatile (~457), which is a non-atomic read of memory other threads may write: a data race in Rust, and one the compiler may split into two 8-byte loads. If the CLWB path (which fills NOPs without holding CODE_REWRITE, #278) writes the block during that read, the mixed value doesn't match expected at off.., the second if returns false, and the site stays emulated for the rest of the run. Taking the first value from compare_exchange_16(cell, 0, 0), as the 8-byte path does with its atomic load, would fix both.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Moot in 005df98: replace_code_block and its plain 16-byte read are removed. The remaining path is the 8-byte one, which takes its first value with an atomic load.

@bmjask

bmjask commented Dec 2, 2026

Copy link
Copy Markdown
Contributor

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

@BBareth
BBareth force-pushed the console-cpu/rewrite-waits-across-words branch from 3c29d4b to 005df98 Compare December 3, 2026 02:55
@BBareth

BBareth commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

Reworked to 005df98 (on main 078358a; still merges cleanly into 395405e) after @bmjask's review. There's no cmpxchg16b any more: a wait across two words gets a form that differs from it in one aligned word only, so another core sees the old instruction or the new one, never a mix. Details are in the threads and the description.

@Foniass, @thehollowedone: your points were on the 16-byte path, which is removed. The CLWB protection race (#278) is handled in #3588, which moves the CLWB patch under CODE_REWRITE.

Suite on 005df98: 3007 passed, 0 failed, 52 ignored, 28 SKIPPED. Smoke blocks in the description were rerun on this head. On this Intel CPU (no monitorx), both new forms are executed by a test.

AI use: Claude Code (Claude Opus 5.5) made the change, ran the suite and the runs, and wrote these replies.

@Foniass

Foniass commented Dec 3, 2026

Copy link
Copy Markdown
Collaborator

Follow-up review of 005df987, since 3c29d4b (code reading only, not a merge-check) · 2 nits

In short: Since the triage of 3c29d4b, the PR was reworked after review: the cmpxchg16b 16-byte write is gone. A wait that crosses two aligned 8-byte words now becomes a form that differs from it in one word only:

  • with two bytes or more in the first word, a short jump over the rest;
  • with one, a plain wait becomes 0F 1F C0 (nop eax), its last two bytes in the second word;
  • a prefixed wait with one byte in the first word stays emulated.

rewrite_code now writes only the bytes that differ, inside their word. The approach is sound and both forms are run as code in a test. One small cost, one overlap.

Nit

  1. An mwaitx that crosses a word loses its pause. Inside one word, an mwaitx becomes F3 90 .. (pause then NOPs). Across a word (wait_replacement, eh.rs ~489), it becomes the jump or nop eax, so the console's spin loop runs with no pause in it once rewritten. That matters only for the spin loop's power and hyper-thread sibling. Say so in the doc comment, or fit a pause where the bytes allow.
  2. Overlaps PE loader: patch a CLWB with one atomic jump under the rewrite lock #3588 in rewrite_code. PE loader: patch a CLWB with one atomic jump under the rewrite lock #3588 moves the body of rewrite_code into rewrite_code_within, and this PR changes the same body to find the differing range. Whichever lands second needs a rebase. Both descriptions mention the other.
Checked and fine
  • rewrite_code takes the first and last differing byte and refuses when that range does not fit in one aligned word. It hands only that slice to replace_code_word, with the same lock, compare-and-retry, page protection and cache flush as before.
  • Jump case: EB (len - 2) over the first two bytes. For a plain 3-byte wait the second byte stays 01, so only byte 0 changes. For a prefixed one (66 0F 01 FA) bytes 0-1 change, both in the first word since low >= 2.
  • One-byte case: only bytes 1-2 change (01 FA → 1F C0), both in the second word. A thread fetching the instruction sees either 0F 01 FA or 0F 1F C0, never a mix.
  • The form inside one word is the same NOPs as on main, with pause first for an mwaitx.
  • a_wait_across_two_words_changes_in_one_word covers word offsets 6 and 7, plain and prefixed, the bytes around each site, and the retry of a fault on the old bytes. It fails on main. the_one_word_wait_forms_run_as_no_ops executes both forms between mov eax, 42 and ret.
  • 108+/-25 in eh.rs only.

Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.

@github-actions github-actions Bot removed the needs-2nd-check Has 1 safe merge-check; needs second independent check (#3041) label Dec 3, 2026
On a CPU without monitorx / mwaitx (Intel), the first fault rewrites a
console wait in place, but only when the instruction fits in one aligned
8-byte word. GTA 6 has a monitorx at an address ending in 7, so its 3
bytes cross two words: rewrite_code refused it and every poll of that
spin loop raised #UD and was emulated (about 2,359 samples of the render
thread's kernel time in a 10 s WPR trace).

Such a wait now becomes a form that differs from it in one word only, so
a thread running it fetches either the old or the new instruction, never
half of each:
- two bytes or more in the first word: they become a short jump over
  the rest (0F 01 FA -> EB 01 FA);
- one byte in the first word (a plain 3-byte wait): its last two bytes,
  in the second word, become 1F C0 (0F 1F C0, nop eax).
A prefixed wait with one byte in the first word stays emulated.
rewrite_code changes only the bytes that differ, in their word, with
the same compare-and-retry, lock and page protection as before.

The first version of this change wrote the whole 16-byte block with
cmpxchg16b; review pointed out that nothing promises another core
fetches such a write whole.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@BBareth
BBareth force-pushed the console-cpu/rewrite-waits-across-words branch from 005df98 to 6a44255 Compare December 3, 2026 03:33
@BBareth

BBareth commented Dec 3, 2026

Copy link
Copy Markdown
Contributor Author

On the follow-up review of 005df98, pushed 6a44255 (a doc line only):

  1. mwaitx across a word loses its pause: noted in wait_replacement's doc comment and in the description. No cross-word form can hold a pause. With one or two bytes in the first word, F3 90 would leave the wait's remaining bytes to decode as a live instruction (FB is sti), or need one that clobbers flags.
  2. Overlap with PE loader: patch a CLWB with one atomic jump under the rewrite lock #3588 in rewrite_code: both descriptions say so already. Whichever lands second gets rebased.

The previous CI run failed with the lib test process exiting 0xc0000005 while gpu::agility tests ran. The same exit shows in 12 of the last 40 failed CI runs on unrelated branches. This push reruns CI.

Suite and smoke blocks are updated for 6a44255: 3007 passed, 0 failed, 52 ignored, 28 SKIPPED; 3072 frames, no removal, no crash.

AI use: Claude Code, Claude Opus 5.5 wrote this comment.

@Foniass

Foniass commented Dec 3, 2026

Copy link
Copy Markdown
Collaborator

Follow-up review of 6a442550, since 005df987 (code reading only, not a merge-check) · 1 nit

In short: This push answers the pause nit from my last review: the doc comment of wait_replacement now says that neither cross-word form has room for a pause, so a spin loop around such an mwaitx runs without one. Nothing else changed (git range-diff), and nothing blocks it.

Nit

  1. Overlaps PE loader: patch a CLWB with one atomic jump under the rewrite lock #3588 in rewrite_code (still open). PE loader: patch a CLWB with one atomic jump under the rewrite lock #3588 moves the body of rewrite_code into rewrite_code_within, and this PR changes the same body. Whichever lands second needs a rebase. Both descriptions say so.
Checked and fine
  • Earlier nit answered: the missing pause for an mwaitx that crosses a word is now written down where the forms are chosen.
  • The code is the same as at 005df987, which the last review found sound.

Written by Claude Code (Claude Opus 5.5) and 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.

4 participants