PE loader: rewrite console waits that cross an 8-byte word #3548
Loading…
Reference in a new issue
No description provided.
Delete branch "upstream-pr/3548"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Imported from ivall/xcl. Originally posted by BBareth on 2026-11-30T22:15:07Z.
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. A retail title has amonitorxat an address ending in 7, so its 3 bytes cross two words.rewrite_coderefused 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:
0F 01 FA→EB 01 FA).1F C0, which makes the whole instruction0F 1F C0(nop eax).Neither cross-word form has room for the
pausean mwaitx gets inside one word, so a spin loop around such an mwaitx runs without one once rewritten.rewrite_codenow 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 example90 01 FA(add edx, edi). That path is gone.What is in it
crates/xcl/src/eh.rs:rewrite_codefinds the range of bytes that differ and rewrites it only when it lies in one aligned word;wait_replacementpicks the form above for amonitorx/mwaitxsite;a_wait_across_two_words_changes_in_one_word, which replacesa_rewrite_crossing_an_atomic_word_stays_emulated:0x16,0x26), two bytes in the first word, take the jump;0x37,0x47), one byte in the first word, take0F 1F C0;0x57) stays emulated;main.the_one_word_wait_forms_run_as_no_ops: both forms are executed on this CPU betweenmov eax, 42andret, and the function returns 42.Tested
monitorx, so these rewrites happen on this CPU); Windows 11 Pro 26200; rustc 1.95.0; debug suite, release smoke.cargo build --workspace, thencargo test --workspace --no-fail-fast -- --test-threads=4on6a442550(on main078358a0): 3007 passed, 0 failed, 52 ignored.SKIPPEDon this adapter, 28 in all:no wave64no heap windowsno d3d12SDKLayers.dllno D3D12 debug layer395405e4.monitorx;Regression run
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
monitorxat word offset 7 (one byte in the first word), so it takes0F 1F C0, as at0x37in the test.rewrite_code): both changerewrite_code; whichever lands second needs a rebase.monitorx/mwaitxnatively and never take this path.AI use
🤖 Generated with Claude Code
Imported from ivall/xcl. Originally posted by thehollowedone on 2026-12-01T02:44:37Z.
Source review of current head
29be3d1d: two issues need resolution before the 16-byte rewrite path is safe to use.The new
cmpxchg16bassembly may lose its address.cell = in(reg)can be allocated torbx. Rust's inline-assembly reference explicitly allowsregoperands to use LLVM-reserved base registers.xchg {new_lo}, rbxthen replaces the address inrbxwith replacement bytes beforecmpxchg16b [{cell}], so a cross-word wait can fault in the exception handler. The stablecmpxchg16bintrinsic 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.CLWB can change the same page's protection concurrently. The new wait path holds
CODE_REWRITEacross 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 withCODE_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.
Imported from ivall/xcl. Originally posted by BBareth on 2026-12-01T07:28:40Z.
Thanks for the review. Head is now
3c29d4bc.cell = in(reg)could be givenrbx, and thexchgwould then replace the address.compare_exchange_16now callsstd::arch::x86_64::cmpxchg16binstead ofasm!. The new testcompare_exchange_16_stores_on_a_match_and_reports_a_mismatchcovers a matching exchange, a failed comparison (nothing stored, the value found is returned) and the blocks on either side.mainthe CLWB path already patches withoutCODE_REWRITEwhile the 8-byte wait rewrite holds it, so the same interleaving exists there. It is tracked in #278. I left it out of this PR to keep it to one change, and listed it under Not tested.Suite on
3c29d4bc: 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.
Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T08:19:19Z.
merge-check
base:
7d86c5d2b7head:
3c29d4bcb7merge: 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
3c29d4bc. Since29be3d1dthe hand-written assembly is replaced by the stablestd::arch::x86_64::cmpxchg16bintrinsic (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 byCODE_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 frominsn::decodewith a same-length replacement, and the earlier test fails without the change.performance: 60 s smoke of a retail title, main
7d86c5d2vs 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.
Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T10:12:10Z.
Triage (#1607) – head
3c29d4bNo 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 withcmpxchg16b.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.
Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T12:44:54Z.
Review: COMMENTED
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.
Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T12:44:55Z.
Code review location:
crates/xcl/src/eh.rs; line 481This 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 FAat block offset 7 (the GTA 6 site) rewritten to90 90 90while another thread runs it. New-low/old-high decodes as90then01 FA=add edx, edi, which silently corrupts EDX. Old-low/new-high decodes0F 90 90 ..=seto byte [rax+disp32], a write to a random address. For mwaitx (F3 90 90) the mix isF3 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 (CCfirst byte, flush, write the tail, write the first byte), which the stale-exception lookup could treat as retry; that works at any alignment.Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T12:44:55Z.
Code review location:
crates/xcl/src/eh.rs; line 456The comment says a torn first read is retried with an atomic reload, but if that read doesn't show
expectedthe function returns false right away without reaching cmpxchg16b. The first read is a plainptr::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 matchexpectedatoff.., the secondifreturns false, and the site stays emulated for the rest of the run. Taking the first value fromcompare_exchange_16(cell, 0, 0), as the 8-byte path does with its atomic load, would fix both.Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T14:11:32Z.
@Prime1997 could you take a look at this one for review and merge? My automated review notes are above, if any.
Imported from ivall/xcl. Originally posted by BBareth on 2026-12-03T02:55:48Z.
Code review location:
crates/xcl/src/eh.rs; line 481Agreed, and the 16-byte path is gone in
005df987. The word guard is back:rewrite_coderewrites 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:0F 01 FA→EB 01 FA, so only the first byte changes);1F C0, making0F 1F C0.A core sees either the old instruction or the new one, and no mix like
90 01 FAcan occur. A prefixed wait with one byte in the first word stays emulated. The testa_wait_across_two_words_changes_in_one_wordchecks which bytes change at each offset, andthe_one_word_wait_forms_run_as_no_opsexecutes both forms.Imported from ivall/xcl. Originally posted by BBareth on 2026-12-03T02:55:50Z.
Code review location:
crates/xcl/src/eh.rs; line 456Moot in
005df987:replace_code_blockand its plain 16-byte read are removed. The remaining path is the 8-byte one, which takes its first value with an atomic load.Imported from ivall/xcl. Originally posted by BBareth on 2026-12-03T02:55:52Z.
Reworked to
005df987(on main078358a0; still merges cleanly into395405e4) after @bmjask's review. There's nocmpxchg16bany 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
005df987: 3007 passed, 0 failed, 52 ignored, 28 SKIPPED. Smoke blocks in the description were rerun on this head. On this Intel CPU (nomonitorx), 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.
Imported from ivall/xcl. Originally posted by Foniass on 2026-12-03T02:57:31Z.
Follow-up review of
005df987, since3c29d4b(code reading only, not a merge-check) · 2 nitsIn short: Since the triage of
3c29d4b, the PR was reworked after review: thecmpxchg16b16-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:0F 1F C0(nop eax), its last two bytes in the second word;rewrite_codenow 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
pause. Inside one word, an mwaitx becomesF3 90 ..(pausethen NOPs). Across a word (wait_replacement,eh.rs~489), it becomes the jump ornop 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 apausewhere the bytes allow.rewrite_code. #3588 moves the body ofrewrite_codeintorewrite_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_codetakes the first and last differing byte and refuses when that range does not fit in one aligned word. It hands only that slice toreplace_code_word, with the same lock, compare-and-retry, page protection and cache flush as before.EB (len - 2)over the first two bytes. For a plain 3-byte wait the second byte stays01, so only byte 0 changes. For a prefixed one (66 0F 01 FA) bytes 0-1 change, both in the first word sincelow >= 2.01 FA→1F C0), both in the second word. A thread fetching the instruction sees either0F 01 FAor0F 1F C0, never a mix.main, withpausefirst for an mwaitx.a_wait_across_two_words_changes_in_one_wordcovers 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 onmain.the_one_word_wait_forms_run_as_no_opsexecutes both forms betweenmov eax, 42andret.eh.rsonly.Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.
Imported from ivall/xcl. Originally posted by BBareth on 2026-12-03T03:33:24Z.
On the follow-up review of
005df987, pushed6a442550(a doc line only):pause: noted inwait_replacement's doc comment and in the description. No cross-word form can hold apause. With one or two bytes in the first word,F3 90would leave the wait's remaining bytes to decode as a live instruction (FBissti), or need one that clobbers flags.rewrite_code: both descriptions say so already. Whichever lands second gets rebased.The previous CI run failed with the lib test process exiting
0xc0000005whilegpu::agilitytests 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
6a442550: 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.
Imported from ivall/xcl. Originally posted by Foniass on 2026-12-03T03:35:38Z.
Follow-up review of
6a442550, since005df987(code reading only, not a merge-check) · 1 nitIn short: This push answers the
pausenit from my last review: the doc comment ofwait_replacementnow says that neither cross-word form has room for apause, so a spin loop around such an mwaitx runs without one. Nothing else changed (git range-diff), and nothing blocks it.Nit
rewrite_code(still open). #3588 moves the body ofrewrite_codeintorewrite_code_within, and this PR changes the same body. Whichever lands second needs a rebase. Both descriptions say so.Checked and fine
pausefor an mwaitx that crosses a word is now written down where the forms are chosen.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.
View command line instructions
Checkout
From your project repository, check out a new branch and test the changes.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.