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

Open
BBareth wants to merge 1 commit from upstream-pr/3548 into main
BBareth commented 2026-11-30 22:15:07 +00:00 (Migrated from github.com)

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 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 6a442550 (on main 078358a0): 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 395405e4.
  • A retail title, 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 the title 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. The title'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 #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

<!-- greyfinch-sync:ivall/xcl:issue:5574751292 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3548). Originally posted by [BBareth](https://github.com/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 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 6a442550 (on main 078358a0): 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 395405e4. - A retail title, 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 the title 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. The title'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 #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](https://claude.com/claude-code)
thehollowedone commented 2026-12-01 02:44:37 +00:00 (Migrated from github.com)

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.

  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.

<!-- greyfinch-sync:ivall/xcl:comment:7298948927 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3548#issuecomment-7298948927). Originally posted by [thehollowedone](https://github.com/thehollowedone) on 2026-12-01T02:44:37Z. --- Source review of current head [`29be3d1d`](https://github.com/xcl-dev/xcl/commit/29be3d1d88561e7dc8ab651a7248ec03ba4d4efd): 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)`](https://github.com/xcl-dev/xcl/blob/29be3d1d88561e7dc8ab651a7248ec03ba4d4efd/crates/xcl/src/eh.rs#L452-L461) can be allocated to `rbx`. Rust's [inline-assembly reference](https://doc.rust-lang.org/reference/inline-assembly.html#asm.register-names.fp-bp-reserved) 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](https://doc.rust-lang.org/core/arch/x86_64/fn.cmpxchg16b.html) 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](https://github.com/xcl-dev/xcl/blob/29be3d1d88561e7dc8ab651a7248ec03ba4d4efd/crates/xcl/src/eh.rs#L499-L520) holds `CODE_REWRITE` across its RWX/write/restore sequence, but the existing [CLWB patch path](https://github.com/xcl-dev/xcl/blob/29be3d1d88561e7dc8ab651a7248ec03ba4d4efd/crates/xcl/src/eh.rs#L623-L631) 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](https://github.com/xcl-dev/xcl/issues/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 commented 2026-12-01 07:28:40 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by BBareth on 2026-12-01T07:28:40Z.


Thanks for the review. Head is now 3c29d4bc.

  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 #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.

<!-- greyfinch-sync:ivall/xcl:comment:7304103690 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3548#issuecomment-7304103690). Originally posted by [BBareth](https://github.com/BBareth) on 2026-12-01T07:28:40Z. --- Thanks for the review. Head is now 3c29d4bc. 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 #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.
Foniass commented 2026-12-01 08:19:19 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T08:19:19Z.


merge-check
base: 7d86c5d2b7
head: 3c29d4bcb7
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 3c29d4bc. Since 29be3d1d 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 7d86c5d2 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.

<!-- greyfinch-sync:ivall/xcl:comment:7305164496 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3548#issuecomment-7305164496). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T08:19:19Z. --- merge-check base: 7d86c5d2b7845695031eeea1327aa81b6c439323 head: 3c29d4bcb7baea22aae59b5893e8aa03b00d276f 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 3c29d4bc. Since 29be3d1d 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 7d86c5d2 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.
Foniass commented 2026-12-01 10:12:10 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T10:12:10Z.


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.

<!-- greyfinch-sync:ivall/xcl:comment:7307826366 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3548#issuecomment-7307826366). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T10:12:10Z. --- **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 commented 2026-12-02 12:44:54 +00:00 (Migrated from github.com)

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.

<!-- greyfinch-sync:ivall/xcl:review:6150963221 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3548#pullrequestreview-6150963221). Originally posted by [bmjask](https://github.com/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._
bmjask commented 2026-12-02 12:44:55 +00:00 (Migrated from github.com)

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

Code review location: crates/xcl/src/eh.rs; line 481

@@ -443,34 +443,67 @@ fn replace_code_word_from(cell: &std::sync::atomic::AtomicU64, off: usize, expec
     }
 }
 
-/// Rewrite one console-only instruction in place when it fits in an aligned 8-byte word. Threads
-/// executing it observe either the complete old instruction or the complete replacement.
+/// `lock cmpxchg16b` on the aligned 16 bytes at `cell`: Err carries the value found instead.
+unsafe fn compare_exchange_16(cell: *mut u128, was: u128, new: u128) -> Result<(), u128> {
+    // (the intrinsic and not `asm!`: the instruction takes rbx, which LLVM reserves and may
+    // still hand to a `reg` operand; every x64 CPU Windows 10 runs on has the instruction)
+    let found = std::arch::x86_64::cmpxchg16b(cell, was, new, Ordering::AcqRel, Ordering::Acquire);
+    if found == was { Ok(()) } else { Err(found) }
+}
+
+/// `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
+    let mut was = std::ptr::read_volatile(cell);
+    loop {
+        let mut bytes = was.to_le_bytes();
+        if bytes[off..off + new.len()] == *new {
+            return true;
+        }
+        if bytes[off..off + expected.len()] != *expected {
+            return false;
+        }
+        bytes[off..off + new.len()].copy_from_slice(new);
+        match compare_exchange_16(cell, was, u128::from_le_bytes(bytes)) {
+            Ok(()) => return true,
+            Err(now) => was = now,
+        }
+    }
+}
+
+/// Rewrite one console-only instruction in place when it fits in an aligned 8-byte word, or else
+/// in an aligned 16-byte block. Threads executing it observe either the complete old instruction
+/// or the complete replacement.
 fn rewrite_code(at: usize, expected: &[u8], new: &[u8]) -> bool {
     use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache;
     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 };

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4769697100 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3548#discussion_r4769697100). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T12:44:55Z. **Code review location:** `crates/xcl/src/eh.rs`; line 481 ~~~~diff @@ -443,34 +443,67 @@ fn replace_code_word_from(cell: &std::sync::atomic::AtomicU64, off: usize, expec } } -/// Rewrite one console-only instruction in place when it fits in an aligned 8-byte word. Threads -/// executing it observe either the complete old instruction or the complete replacement. +/// `lock cmpxchg16b` on the aligned 16 bytes at `cell`: Err carries the value found instead. +unsafe fn compare_exchange_16(cell: *mut u128, was: u128, new: u128) -> Result<(), u128> { + // (the intrinsic and not `asm!`: the instruction takes rbx, which LLVM reserves and may + // still hand to a `reg` operand; every x64 CPU Windows 10 runs on has the instruction) + let found = std::arch::x86_64::cmpxchg16b(cell, was, new, Ordering::AcqRel, Ordering::Acquire); + if found == was { Ok(()) } else { Err(found) } +} + +/// `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 + let mut was = std::ptr::read_volatile(cell); + loop { + let mut bytes = was.to_le_bytes(); + if bytes[off..off + new.len()] == *new { + return true; + } + if bytes[off..off + expected.len()] != *expected { + return false; + } + bytes[off..off + new.len()].copy_from_slice(new); + match compare_exchange_16(cell, was, u128::from_le_bytes(bytes)) { + Ok(()) => return true, + Err(now) => was = now, + } + } +} + +/// Rewrite one console-only instruction in place when it fits in an aligned 8-byte word, or else +/// in an aligned 16-byte block. Threads executing it observe either the complete old instruction +/// or the complete replacement. fn rewrite_code(at: usize, expected: &[u8], new: &[u8]) -> bool { use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache; 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 }; ~~~~ --- 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.
bmjask commented 2026-12-02 12:44:55 +00:00 (Migrated from github.com)

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

Code review location: crates/xcl/src/eh.rs; line 456

@@ -443,34 +443,67 @@ fn replace_code_word_from(cell: &std::sync::atomic::AtomicU64, off: usize, expec
     }
 }
 
-/// Rewrite one console-only instruction in place when it fits in an aligned 8-byte word. Threads
-/// executing it observe either the complete old instruction or the complete replacement.
+/// `lock cmpxchg16b` on the aligned 16 bytes at `cell`: Err carries the value found instead.
+unsafe fn compare_exchange_16(cell: *mut u128, was: u128, new: u128) -> Result<(), u128> {
+    // (the intrinsic and not `asm!`: the instruction takes rbx, which LLVM reserves and may
+    // still hand to a `reg` operand; every x64 CPU Windows 10 runs on has the instruction)
+    let found = std::arch::x86_64::cmpxchg16b(cell, was, new, Ordering::AcqRel, Ordering::Acquire);
+    if found == was { Ok(()) } else { Err(found) }
+}
+
+/// `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

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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4769697110 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3548#discussion_r4769697110). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T12:44:55Z. **Code review location:** `crates/xcl/src/eh.rs`; line 456 ~~~~diff @@ -443,34 +443,67 @@ fn replace_code_word_from(cell: &std::sync::atomic::AtomicU64, off: usize, expec } } -/// Rewrite one console-only instruction in place when it fits in an aligned 8-byte word. Threads -/// executing it observe either the complete old instruction or the complete replacement. +/// `lock cmpxchg16b` on the aligned 16 bytes at `cell`: Err carries the value found instead. +unsafe fn compare_exchange_16(cell: *mut u128, was: u128, new: u128) -> Result<(), u128> { + // (the intrinsic and not `asm!`: the instruction takes rbx, which LLVM reserves and may + // still hand to a `reg` operand; every x64 CPU Windows 10 runs on has the instruction) + let found = std::arch::x86_64::cmpxchg16b(cell, was, new, Ordering::AcqRel, Ordering::Acquire); + if found == was { Ok(()) } else { Err(found) } +} + +/// `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 ~~~~ --- 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.
bmjask commented 2026-12-02 14:11:32 +00:00 (Migrated from github.com)

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.

<!-- greyfinch-sync:ivall/xcl:comment:7348137819 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3548#issuecomment-7348137819). Originally posted by [bmjask](https://github.com/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.
BBareth commented 2026-12-03 02:55:48 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by BBareth on 2026-12-03T02:55:48Z.

Code review location: crates/xcl/src/eh.rs; line 481

@@ -443,34 +443,67 @@ fn replace_code_word_from(cell: &std::sync::atomic::AtomicU64, off: usize, expec
     }
 }
 
-/// Rewrite one console-only instruction in place when it fits in an aligned 8-byte word. Threads
-/// executing it observe either the complete old instruction or the complete replacement.
+/// `lock cmpxchg16b` on the aligned 16 bytes at `cell`: Err carries the value found instead.
+unsafe fn compare_exchange_16(cell: *mut u128, was: u128, new: u128) -> Result<(), u128> {
+    // (the intrinsic and not `asm!`: the instruction takes rbx, which LLVM reserves and may
+    // still hand to a `reg` operand; every x64 CPU Windows 10 runs on has the instruction)
+    let found = std::arch::x86_64::cmpxchg16b(cell, was, new, Ordering::AcqRel, Ordering::Acquire);
+    if found == was { Ok(()) } else { Err(found) }
+}
+
+/// `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
+    let mut was = std::ptr::read_volatile(cell);
+    loop {
+        let mut bytes = was.to_le_bytes();
+        if bytes[off..off + new.len()] == *new {
+            return true;
+        }
+        if bytes[off..off + expected.len()] != *expected {
+            return false;
+        }
+        bytes[off..off + new.len()].copy_from_slice(new);
+        match compare_exchange_16(cell, was, u128::from_le_bytes(bytes)) {
+            Ok(()) => return true,
+            Err(now) => was = now,
+        }
+    }
+}
+
+/// Rewrite one console-only instruction in place when it fits in an aligned 8-byte word, or else
+/// in an aligned 16-byte block. Threads executing it observe either the complete old instruction
+/// or the complete replacement.
 fn rewrite_code(at: usize, expected: &[u8], new: &[u8]) -> bool {
     use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache;
     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 };

Agreed, and the 16-byte path is gone in 005df987. 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.
<!-- greyfinch-sync:ivall/xcl:review-comment:4779286060 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3548#discussion_r4779286060). Originally posted by [BBareth](https://github.com/BBareth) on 2026-12-03T02:55:48Z. **Code review location:** `crates/xcl/src/eh.rs`; line 481 ~~~~diff @@ -443,34 +443,67 @@ fn replace_code_word_from(cell: &std::sync::atomic::AtomicU64, off: usize, expec } } -/// Rewrite one console-only instruction in place when it fits in an aligned 8-byte word. Threads -/// executing it observe either the complete old instruction or the complete replacement. +/// `lock cmpxchg16b` on the aligned 16 bytes at `cell`: Err carries the value found instead. +unsafe fn compare_exchange_16(cell: *mut u128, was: u128, new: u128) -> Result<(), u128> { + // (the intrinsic and not `asm!`: the instruction takes rbx, which LLVM reserves and may + // still hand to a `reg` operand; every x64 CPU Windows 10 runs on has the instruction) + let found = std::arch::x86_64::cmpxchg16b(cell, was, new, Ordering::AcqRel, Ordering::Acquire); + if found == was { Ok(()) } else { Err(found) } +} + +/// `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 + let mut was = std::ptr::read_volatile(cell); + loop { + let mut bytes = was.to_le_bytes(); + if bytes[off..off + new.len()] == *new { + return true; + } + if bytes[off..off + expected.len()] != *expected { + return false; + } + bytes[off..off + new.len()].copy_from_slice(new); + match compare_exchange_16(cell, was, u128::from_le_bytes(bytes)) { + Ok(()) => return true, + Err(now) => was = now, + } + } +} + +/// Rewrite one console-only instruction in place when it fits in an aligned 8-byte word, or else +/// in an aligned 16-byte block. Threads executing it observe either the complete old instruction +/// or the complete replacement. fn rewrite_code(at: usize, expected: &[u8], new: &[u8]) -> bool { use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache; 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 }; ~~~~ --- Agreed, and the 16-byte path is gone in 005df987. 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.
BBareth commented 2026-12-03 02:55:50 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by BBareth on 2026-12-03T02:55:50Z.

Code review location: crates/xcl/src/eh.rs; line 456

@@ -443,34 +443,67 @@ fn replace_code_word_from(cell: &std::sync::atomic::AtomicU64, off: usize, expec
     }
 }
 
-/// Rewrite one console-only instruction in place when it fits in an aligned 8-byte word. Threads
-/// executing it observe either the complete old instruction or the complete replacement.
+/// `lock cmpxchg16b` on the aligned 16 bytes at `cell`: Err carries the value found instead.
+unsafe fn compare_exchange_16(cell: *mut u128, was: u128, new: u128) -> Result<(), u128> {
+    // (the intrinsic and not `asm!`: the instruction takes rbx, which LLVM reserves and may
+    // still hand to a `reg` operand; every x64 CPU Windows 10 runs on has the instruction)
+    let found = std::arch::x86_64::cmpxchg16b(cell, was, new, Ordering::AcqRel, Ordering::Acquire);
+    if found == was { Ok(()) } else { Err(found) }
+}
+
+/// `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

Moot in 005df987: 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.

<!-- greyfinch-sync:ivall/xcl:review-comment:4779286221 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3548#discussion_r4779286221). Originally posted by [BBareth](https://github.com/BBareth) on 2026-12-03T02:55:50Z. **Code review location:** `crates/xcl/src/eh.rs`; line 456 ~~~~diff @@ -443,34 +443,67 @@ fn replace_code_word_from(cell: &std::sync::atomic::AtomicU64, off: usize, expec } } -/// Rewrite one console-only instruction in place when it fits in an aligned 8-byte word. Threads -/// executing it observe either the complete old instruction or the complete replacement. +/// `lock cmpxchg16b` on the aligned 16 bytes at `cell`: Err carries the value found instead. +unsafe fn compare_exchange_16(cell: *mut u128, was: u128, new: u128) -> Result<(), u128> { + // (the intrinsic and not `asm!`: the instruction takes rbx, which LLVM reserves and may + // still hand to a `reg` operand; every x64 CPU Windows 10 runs on has the instruction) + let found = std::arch::x86_64::cmpxchg16b(cell, was, new, Ordering::AcqRel, Ordering::Acquire); + if found == was { Ok(()) } else { Err(found) } +} + +/// `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 ~~~~ --- Moot in 005df987: `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.
BBareth commented 2026-12-03 02:55:52 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by BBareth on 2026-12-03T02:55:52Z.


Reworked to 005df987 (on main 078358a0; still merges cleanly into 395405e4) 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 005df987: 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.

<!-- greyfinch-sync:ivall/xcl:comment:7366014867 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3548#issuecomment-7366014867). Originally posted by [BBareth](https://github.com/BBareth) on 2026-12-03T02:55:52Z. --- Reworked to 005df987 (on main 078358a0; still merges cleanly into 395405e4) 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 005df987: 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 commented 2026-12-03 02:57:31 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-03T02:57:31Z.


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 #3588 in rewrite_code. #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.

<!-- greyfinch-sync:ivall/xcl:comment:7366043895 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3548#issuecomment-7366043895). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-03T02:57:31Z. --- **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 #3588 in `rewrite_code`.** #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. <details><summary>Checked and fine</summary> - `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. </details> <sub>Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.</sub>
BBareth commented 2026-12-03 03:33:24 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by BBareth on 2026-12-03T03:33:24Z.


On the follow-up review of 005df987, pushed 6a442550 (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 #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 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.

<!-- greyfinch-sync:ivall/xcl:comment:7366691628 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3548#issuecomment-7366691628). Originally posted by [BBareth](https://github.com/BBareth) on 2026-12-03T03:33:24Z. --- On the follow-up review of 005df987, pushed 6a442550 (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 #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 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.
Foniass commented 2026-12-03 03:35:38 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-03T03:35:38Z.


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 #3588 in rewrite_code (still open). #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.

<!-- greyfinch-sync:ivall/xcl:comment:7366730404 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3548#issuecomment-7366730404). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-03T03:35:38Z. --- **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 #3588 in `rewrite_code` (still open).** #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. <details><summary>Checked and fine</summary> - 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. </details> <sub>Written by Claude Code (Claude Opus 5.5) and posted by Foniass without a human check of each point.</sub>
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/3548:upstream-pr/3548'
git switch 'upstream-pr/3548'

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