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

Open
BBareth wants to merge 1 commit from upstream-pr/3588 into main
BBareth commented 2026-12-01 17:18:08 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by BBareth on 2026-12-01T17:18:08Z.


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

What could go wrong on main:

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

The patch now goes through rewrite_code, like the waits:

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

A site whose first two bytes cross an aligned 8-byte word cannot take the jump in one write. Only its second opcode byte changes, AE to 1F: 0F 1F /6 is a reserved NOP of the same length. A one-byte write cannot be seen half done by another core. Changing the ModRM byte as well, as the previous head did, could let a core fetch the old opcode with the new ModRM (0F AE /0, FXSAVE). The opcode is found past the prefixes of one copy of the bytes, so the scan cannot match 0F AE inside the displacement of a site another thread patched in the meantime.

What is in it

  • crates/xcl/src/eh.rs, the ConsoleOnly::Clwb arm of emulate_console_only:
    • it calls rewrite_code(rip, first two bytes, [EB, len - 2]) instead of its own protect / fill / restore;
    • a site crossing a word changes one byte through rewrite_code_within, which records the site with its unchanged prefix so a stale fault is retried there too;
    • clwb_opcode_at finds the opcode past the prefix bytes;
    • a visit with TF set still leaves the code alone (#571).
  • Test clwb_and_a_wait_patched_at_once_on_one_page_keep_its_protection: 32 threads fault at once on a CLWB and on a monitorx in one page. Every fault is handled, both sites are patched whole, and the page is read-execute afterwards.
  • Test clwb_across_an_atomic_word_becomes_a_nop_with_its_operand: a CLWB at word offset 7, with and without a REX prefix, becomes 66 0F 1F 30 / 66 41 0F 1F 74 24 08. The bytes around it stay, and a second fault at the site is retried there.
  • Test clwb_opcode_is_found_past_the_prefixes_only: a displacement that holds 0F AE is not taken for the opcode.
  • Test clwb_single_step_keeps_code_and_normal_faults_still_patch (changed): expects the jump and the untouched tail, and checks that a second fault at the patched address is retried there.

Tested

  • RTX 5070 Ti, driver 32.0.16.2124; i7-12700K; Windows 11 Pro 26200; rustc 1.95.0; debug suite, release smoke.
  • cargo build --workspace, then cargo test --workspace --no-fail-fast -- --test-threads=4 on f2179fc0 (on main 078358a0): 3009 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)
  • On the earlier head, with the old patching code put back, the three original CLWB tests failed in 3 of 3 runs: the concurrent test logged illegal instruction ... code bytes 90 90 90 90 90 90 (the late faulter), and one run ended in STATUS_ACCESS_VIOLATION (the protection race).
  • 66 0F 1F /6 with a null operand register was run on this CPU: it is a NOP and touches no memory.

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: f2179fc05d964c03e769ece3254d0e3a06dbf6fc
gpu: NVIDIA GeForce RTX 5070 Ti
title: 9cc6a39e
seconds: 120
exit: 0x0
frames shown: 3061 (PresentX 3061)
presents per 2 s (last 3): 37 16 24
device removals: 0
crashes: 0
peak commit: 32342 MB

Each run follows one warm-up run of the same build; the A button is pressed once at 70 s. This CPU executes CLWB, so the changed code did not run in them.

Not tested

  • A real CLWB fault: this CPU (i7-12700K) runs CLWB natively, so the changed path is reached only by the unit tests, which call the handler with a made-up CONTEXT. The smoke runs are a regression check only.
  • Cross-modifying code on real cores while they run the site: the one-byte write is chosen so that a core can only see the old or the new byte, but no test runs the site on another core during the write.
  • With open #1829: it adds clwb_patches_instruction_bytes_to_nop_and_advances_rip, which expects NOP bytes at an ordinary site; whichever of the two lands second has to adjust that test.
  • With open #3548: both change rewrite_code; whichever lands second needs a rebase. #3548 no longer widens the write to 16 bytes, so the word rule here stays the same.
  • AMD CPUs run CLWB natively and never take this path.

AI use

  • Claude Code, Claude Fable 5.2: wrote the change, the first tests and the first description, and ran the suite and earlier regression runs.
  • Claude Code, Claude Opus 5.5: made the one-byte form and the prefix scan after review, ran the suite and the regression runs above, and updated this description.

🤖 Generated with Claude Code

<!-- greyfinch-sync:ivall/xcl:issue:5590757655 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3588). Originally posted by [BBareth](https://github.com/BBareth) on 2026-12-01T17:18:08Z. --- On a CPU without CLWB (older Intel), XCL patches the instruction out at its first fault. The patch made the bytes writable, filled them with NOPs one at a time and restored the protection, with nothing shared between threads. This is item 4 of #278, the part #321 addressed before it was closed with conflicts; #571 fixed only the single-step case. Part of #278. What could go wrong on `main`: - Two threads patching on one page could restore each other's protection, also against the wait rewrite, which already holds `CODE_REWRITE`. The page could stay writable, or turn read-only while the other thread still wrote. - Another thread could run the half-written bytes (`90 0F AE 30` is a nop followed by `xsaveopt [rax]`). - A thread that faulted on the CLWB just before the patch found NOPs, which do not decode, so its fault went on to the title's handlers. - The instruction cache was never flushed. The patch now goes through `rewrite_code`, like the waits: - The first two bytes become a short jump over the instruction (`EB, len - 2`), in one atomic word write under `CODE_REWRITE`. - The protection is restored and the cache is flushed. - A thread that faulted on the old bytes is retried at the jump. - The bytes after the jump stay as they were. A site whose first two bytes cross an aligned 8-byte word cannot take the jump in one write. Only its second opcode byte changes, `AE` to `1F`: `0F 1F /6` is a reserved NOP of the same length. A one-byte write cannot be seen half done by another core. Changing the ModRM byte as well, as the previous head did, could let a core fetch the old opcode with the new ModRM (`0F AE /0`, FXSAVE). The opcode is found past the prefixes of one copy of the bytes, so the scan cannot match `0F AE` inside the displacement of a site another thread patched in the meantime. **What is in it** - `crates/xcl/src/eh.rs`, the `ConsoleOnly::Clwb` arm of `emulate_console_only`: - it calls `rewrite_code(rip, first two bytes, [EB, len - 2])` instead of its own protect / fill / restore; - a site crossing a word changes one byte through `rewrite_code_within`, which records the site with its unchanged prefix so a stale fault is retried there too; - `clwb_opcode_at` finds the opcode past the prefix bytes; - a visit with TF set still leaves the code alone (#571). - Test `clwb_and_a_wait_patched_at_once_on_one_page_keep_its_protection`: 32 threads fault at once on a CLWB and on a `monitorx` in one page. Every fault is handled, both sites are patched whole, and the page is read-execute afterwards. - Test `clwb_across_an_atomic_word_becomes_a_nop_with_its_operand`: a CLWB at word offset 7, with and without a REX prefix, becomes `66 0F 1F 30` / `66 41 0F 1F 74 24 08`. The bytes around it stay, and a second fault at the site is retried there. - Test `clwb_opcode_is_found_past_the_prefixes_only`: a displacement that holds `0F AE` is not taken for the opcode. - Test `clwb_single_step_keeps_code_and_normal_faults_still_patch` (changed): expects the jump and the untouched tail, and checks that a second fault at the patched address is retried there. **Tested** - RTX 5070 Ti, driver 32.0.16.2124; i7-12700K; Windows 11 Pro 26200; rustc 1.95.0; debug suite, release smoke. - `cargo build --workspace`, then `cargo test --workspace --no-fail-fast -- --test-threads=4` on f2179fc0 (on main 078358a0): 3009 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) - On the earlier head, with the old patching code put back, the three original CLWB tests failed in 3 of 3 runs: the concurrent test logged `illegal instruction ... code bytes 90 90 90 90 90 90` (the late faulter), and one run ended in `STATUS_ACCESS_VIOLATION` (the protection race). - `66 0F 1F /6` with a null operand register was run on this CPU: it is a NOP and touches no memory. **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: f2179fc05d964c03e769ece3254d0e3a06dbf6fc gpu: NVIDIA GeForce RTX 5070 Ti title: 9cc6a39e seconds: 120 exit: 0x0 frames shown: 3061 (PresentX 3061) presents per 2 s (last 3): 37 16 24 device removals: 0 crashes: 0 peak commit: 32342 MB ``` Each run follows one warm-up run of the same build; the A button is pressed once at 70 s. This CPU executes CLWB, so the changed code did not run in them. **Not tested** - A real CLWB fault: this CPU (i7-12700K) runs CLWB natively, so the changed path is reached only by the unit tests, which call the handler with a made-up `CONTEXT`. The smoke runs are a regression check only. - Cross-modifying code on real cores while they run the site: the one-byte write is chosen so that a core can only see the old or the new byte, but no test runs the site on another core during the write. - With open #1829: it adds `clwb_patches_instruction_bytes_to_nop_and_advances_rip`, which expects NOP bytes at an ordinary site; whichever of the two lands second has to adjust that test. - With open #3548: both change `rewrite_code`; whichever lands second needs a rebase. #3548 no longer widens the write to 16 bytes, so the word rule here stays the same. - AMD CPUs run CLWB natively and never take this path. **AI use** - Claude Code, Claude Fable 5.2: wrote the change, the first tests and the first description, and ran the suite and earlier regression runs. - Claude Code, Claude Opus 5.5: made the one-byte form and the prefix scan after review, ran the suite and the regression runs above, and updated this description. 🤖 Generated with [Claude Code](https://claude.com/claude-code)
fromthemoonx commented 2026-12-01 17:59:15 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by fromthemoonx on 2026-12-01T17:59:15Z.


merge-check
base: 078358a058
head: f2179fc05d
merge: clean (one commit, directly on that base)
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 3009 passed, 0 failed, 52 ignored (base: 3006 passed, 0 failed, 52 ignored); SKIPPED: 25 (22 no wave64, 2 no heap windows, 1 no GPU_UPLOAD heaps), the same set as base; failing: none
review: rerun on the new head; read the whole diff (eh.rs, +144 -10). No correctness problem found. My report on 81ad460d passed the two-byte form that bmjask then objected to; this head no longer has it.

  • clwb_opcode_at skips the same prefix bytes as insn::decode, so it finds the opcode of every CLWB decode accepts.
  • The four CLWB tests: 30 of 30 alone each. eh::tests:: at --test-threads=8: 30 of 30.
  • Mutations: searching for 0F AE anywhere in the instruction fails clwb_opcode_is_found_past_the_prefixes_only; writing the ModRM byte as well fails clwb_across_an_atomic_word_becomes_a_nop_with_its_operand.
  • From Not tested, patching a site while other cores run it: this CPU has CLWB, so the old and the new bytes both run here. In a scratch test (not pushed) 8 threads called the sites in a loop while another thread patched them through emulate_console_only. 3 runs, each 12,000 sites at word offset 7 and 12,000 that take the jump: no crash, and the operand's memory was not written. The previous two-byte form passed the same test 3 of 3, so this shows that the new form works, not that the old one failed.
  • Nit, not blocking: clwb_opcode_at was put between rewrite_code_within and its doc comment, so the two lines starting "rewrite_code for bytes skip into the instruction" now document the wrong function.
  • Not tested: a real CLWB fault (needs a CPU without it), Intel, and a retail title (none on this machine).
    performance: none on CPUs with CLWB. Without it, each site is patched once, as on base (reasoned, not measured).
    verdict: safe to merge
    hardware / tool and model: RTX 3060 12 GB (610.88), Ryzen 7 5700X, Windows 11 Pro 26300 / Claude Code (Claude Opus 5.5)
Earlier reports (81ad460d, 9ac69984)

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

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

  • A CLWB whose first two bytes cross an aligned word (rip & 7 == 7) now gets 0F 1F with the same ModRM (modrm & 0xC7 clears the /6 reg field), SIB and displacement, through rewrite_code_within. That is a NOP of the same length, and the prefixes before and the operand after stay.
  • At offset 7 the two bytes changed (AE, ModRM) are always inside the next aligned word, so one CAS covers them, and the first word is untouched.
  • The site is recorded with its first skip bytes, so a thread that faulted on the old bytes finds 0F 1F (not a console instruction), matches rewritten_wait, and is retried. The test checks that.
  • Each 30 of 30 alone: eh::tests::clwb_across_an_atomic_word_becomes_a_nop_with_its_operand, clwb_and_a_wait_patched_at_once_on_one_page_keep_its_protection, clwb_single_step_keeps_code_and_normal_faults_still_patch.
  • eh::tests:: at --test-threads=8: 30 of 30 ok.
  • Mutation: the cross-word branch removed (main's step-over only) fails clwb_across_an_atomic_word_becomes_a_nop_with_its_operand. Good.
  • This Ryzen 7 5700X has CLWB, so a real CLWB fault does not happen here. #1829's test (NOP bytes at the site) still clashes, as Foniass said.
    performance: none on CPUs with CLWB. Without it, every site, including those crossing a word, is patched once.
    verdict: safe to merge
    hardware / tool and model: RTX 3060 12 GB (610.88), Ryzen 7 5700X, Windows 11 Pro 26300 / Claude Code (Claude Opus 5.5)
Earlier report on 9ac69984 (base 6bfb5c51)
merge-check
base: 6bfb5c5153ccc23517daf30aa1071ddb0fadb53c
head: 9ac69984280edd2d47b7606bef5cc1d1f1fc7ffe
merge: clean
build: cargo build --workspace -> ok
tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2906 passed, 0 failed, 51 ignored (base: 2904 passed, 0 failed, 51 ignored); SKIPPED: 25 (22 no wave64, 2 no heap windows, 1 no GPU_UPLOAD heaps), the same set as base; failing: none
review: read the whole diff (`eh.rs`, +102 -9). No correctness problem found.
- The CLWB arm now goes through `rewrite_code`:
  - It is serialized on `CODE_REWRITE` with the wait rewrites.
  - It writes the `EB, len - 2` jump in one atomic word write and restores the protection.
  - It records the site in `REWRITTEN_WAITS`. A thread that faulted on the old bytes then finds the jump: `decode` returns `None`, `rewritten_wait` matches, and the thread is retried at the jump.
  - A site whose first two bytes cross an aligned 8-byte word is refused by `rewrite_code` (`off + 2 > 8`) and stepped over each time. The TF case leaves the code alone as before (#571).
- The three tests touched, 30 of 30 alone each:
  - `eh::tests::clwb_and_a_wait_patched_at_once_on_one_page_keep_its_protection`
  - `eh::tests::clwb_across_an_atomic_word_stays_emulated`
  - `eh::tests::clwb_single_step_keeps_code_and_normal_faults_still_patch`
- `eh::tests::` at `--test-threads=8`: 30 of 30 ok.
- Mutation: the same two jump bytes written with `VirtualProtect` + byte stores instead of `rewrite_code` (no lock, no record of the site). 10 runs of each test:
  - the concurrent test failed 10 of 10: some runs with "a concurrent patch must not leave the page writable", some with a segmentation fault;
  - `clwb_across_an_atomic_word_stays_emulated` failed 10 of 10 (the bytes were patched);
  - `clwb_single_step_keeps_code_and_normal_faults_still_patch` failed 10 of 10 (the stale fault returned 0 instead of -1).
  Good.
- This Ryzen 7 5700X has CLWB, so a real CLWB fault does not happen here. The tests call `emulate_console_only` directly. No title with CLWB was run on a CPU without it.
performance: none on CPUs with CLWB. On CPUs without it, each site is patched once as before; the jump replaces the NOPs.
verdict: safe to merge
hardware / tool and model: RTX 3060 12 GB (610.88), Ryzen 7 5700X, Windows 11 Pro 26300 / Claude Code (Claude Opus 5.5)
<!-- greyfinch-sync:ivall/xcl:comment:7320197917 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3588#issuecomment-7320197917). Originally posted by [fromthemoonx](https://github.com/fromthemoonx) on 2026-12-01T17:59:15Z. --- merge-check base: 078358a058f7ba5d16690dba8dc4e55d2c88ae0a head: f2179fc05d964c03e769ece3254d0e3a06dbf6fc merge: clean (one commit, directly on that base) build: cargo build --workspace -> ok tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 3009 passed, 0 failed, 52 ignored (base: 3006 passed, 0 failed, 52 ignored); SKIPPED: 25 (22 no wave64, 2 no heap windows, 1 no GPU_UPLOAD heaps), the same set as base; failing: none review: rerun on the new head; read the whole diff (`eh.rs`, +144 -10). No correctness problem found. My report on `81ad460d` passed the two-byte form that bmjask then objected to; this head no longer has it. - `clwb_opcode_at` skips the same prefix bytes as `insn::decode`, so it finds the opcode of every CLWB `decode` accepts. - The four CLWB tests: 30 of 30 alone each. `eh::tests::` at `--test-threads=8`: 30 of 30. - Mutations: searching for `0F AE` anywhere in the instruction fails `clwb_opcode_is_found_past_the_prefixes_only`; writing the ModRM byte as well fails `clwb_across_an_atomic_word_becomes_a_nop_with_its_operand`. - From **Not tested**, patching a site while other cores run it: this CPU has CLWB, so the old and the new bytes both run here. In a scratch test (not pushed) 8 threads called the sites in a loop while another thread patched them through `emulate_console_only`. 3 runs, each 12,000 sites at word offset 7 and 12,000 that take the jump: no crash, and the operand's memory was not written. The previous two-byte form passed the same test 3 of 3, so this shows that the new form works, not that the old one failed. - Nit, not blocking: `clwb_opcode_at` was put between `rewrite_code_within` and its doc comment, so the two lines starting "`rewrite_code` for bytes `skip` into the instruction" now document the wrong function. - Not tested: a real CLWB fault (needs a CPU without it), Intel, and a retail title (none on this machine). performance: none on CPUs with CLWB. Without it, each site is patched once, as on base (reasoned, not measured). verdict: safe to merge hardware / tool and model: RTX 3060 12 GB (610.88), Ryzen 7 5700X, Windows 11 Pro 26300 / Claude Code (Claude Opus 5.5) <details><summary>Earlier reports (81ad460d, 9ac69984)</summary> Rerun on the new head (`81ad460d`, the cross-word fix after Foniass's review). The earlier report, on `9ac69984`, is below. merge-check base: f07e426dade72aa7112cf6bfe08ca6f6ff5a9d5c head: 81ad460d7f5eb2f9d662c7a056fd8cfb5da4ab28 merge: clean build: cargo build --workspace -> ok tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2906 passed, 0 failed, 51 ignored (base: 2904 passed, 0 failed, 51 ignored); SKIPPED: 25 (22 no wave64, 2 no heap windows, 1 no GPU_UPLOAD heaps), the same set as base; failing: none review: read the change since `9ac69984` (`eh.rs`). No correctness problem found. - A CLWB whose first two bytes cross an aligned word (`rip & 7 == 7`) now gets `0F 1F` with the same ModRM (`modrm & 0xC7` clears the `/6` reg field), SIB and displacement, through `rewrite_code_within`. That is a NOP of the same length, and the prefixes before and the operand after stay. - At offset 7 the two bytes changed (`AE`, ModRM) are always inside the next aligned word, so one CAS covers them, and the first word is untouched. - The site is recorded with its first `skip` bytes, so a thread that faulted on the old bytes finds `0F 1F` (not a console instruction), matches `rewritten_wait`, and is retried. The test checks that. - Each 30 of 30 alone: `eh::tests::clwb_across_an_atomic_word_becomes_a_nop_with_its_operand`, `clwb_and_a_wait_patched_at_once_on_one_page_keep_its_protection`, `clwb_single_step_keeps_code_and_normal_faults_still_patch`. - `eh::tests::` at `--test-threads=8`: 30 of 30 ok. - Mutation: the cross-word branch removed (main's step-over only) fails `clwb_across_an_atomic_word_becomes_a_nop_with_its_operand`. Good. - This Ryzen 7 5700X has CLWB, so a real CLWB fault does not happen here. #1829's test (NOP bytes at the site) still clashes, as Foniass said. performance: none on CPUs with CLWB. Without it, every site, including those crossing a word, is patched once. verdict: safe to merge hardware / tool and model: RTX 3060 12 GB (610.88), Ryzen 7 5700X, Windows 11 Pro 26300 / Claude Code (Claude Opus 5.5) <details><summary>Earlier report on 9ac69984 (base 6bfb5c51)</summary> ```text merge-check base: 6bfb5c5153ccc23517daf30aa1071ddb0fadb53c head: 9ac69984280edd2d47b7606bef5cc1d1f1fc7ffe merge: clean build: cargo build --workspace -> ok tests: cargo test --workspace --no-fail-fast -- --test-threads=4 -> 2906 passed, 0 failed, 51 ignored (base: 2904 passed, 0 failed, 51 ignored); SKIPPED: 25 (22 no wave64, 2 no heap windows, 1 no GPU_UPLOAD heaps), the same set as base; failing: none review: read the whole diff (`eh.rs`, +102 -9). No correctness problem found. - The CLWB arm now goes through `rewrite_code`: - It is serialized on `CODE_REWRITE` with the wait rewrites. - It writes the `EB, len - 2` jump in one atomic word write and restores the protection. - It records the site in `REWRITTEN_WAITS`. A thread that faulted on the old bytes then finds the jump: `decode` returns `None`, `rewritten_wait` matches, and the thread is retried at the jump. - A site whose first two bytes cross an aligned 8-byte word is refused by `rewrite_code` (`off + 2 > 8`) and stepped over each time. The TF case leaves the code alone as before (#571). - The three tests touched, 30 of 30 alone each: - `eh::tests::clwb_and_a_wait_patched_at_once_on_one_page_keep_its_protection` - `eh::tests::clwb_across_an_atomic_word_stays_emulated` - `eh::tests::clwb_single_step_keeps_code_and_normal_faults_still_patch` - `eh::tests::` at `--test-threads=8`: 30 of 30 ok. - Mutation: the same two jump bytes written with `VirtualProtect` + byte stores instead of `rewrite_code` (no lock, no record of the site). 10 runs of each test: - the concurrent test failed 10 of 10: some runs with "a concurrent patch must not leave the page writable", some with a segmentation fault; - `clwb_across_an_atomic_word_stays_emulated` failed 10 of 10 (the bytes were patched); - `clwb_single_step_keeps_code_and_normal_faults_still_patch` failed 10 of 10 (the stale fault returned 0 instead of -1). Good. - This Ryzen 7 5700X has CLWB, so a real CLWB fault does not happen here. The tests call `emulate_console_only` directly. No title with CLWB was run on a CPU without it. performance: none on CPUs with CLWB. On CPUs without it, each site is patched once as before; the jump replaces the NOPs. verdict: safe to merge hardware / tool and model: RTX 3060 12 GB (610.88), Ryzen 7 5700X, Windows 11 Pro 26300 / Claude Code (Claude Opus 5.5) ``` </details> </details>
Foniass commented 2026-12-01 20:27:56 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T20:27:56Z.


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

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

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

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

<!-- greyfinch-sync:ivall/xcl:comment:7324731709 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3588#issuecomment-7324731709). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T20:27:56Z. --- Review (head 9ac69984, diff read, not a merge-check): - **One CLWB site in eight now faults at every visit.** `rewrite_code` (`eh.rs` ~454) returns false when the instruction's first two bytes start at offset 7 of an aligned 8-byte word, and the CLWB arm (~585) ignores that and only steps RIP, so the site is never patched and every execution goes through the vectored handler again. On `main` such a site was patched to NOPs once, which b25582a39 added precisely to avoid repeated exceptions in tight loops. On a CPU without CLWB this is a default-path cost the PR does not measure; these sites need a fallback that still patches them once. - **Clashes with open #1829.** #1829 (test-only) adds `clwb_patches_instruction_bytes_to_nop_and_advances_rip`, which expects NOP bytes at the site. Whichever of the two lands second breaks that test. Fine: the patch now takes `CODE_REWRITE`, so it cannot restore page protection over another rewrite on the same page; the two-byte `EB len-2` jump goes in with one CAS and leaves no half-written instruction; a thread that faulted on the old bytes is retried through `rewritten_wait` (`EB` does not decode, so it reaches that path); the tests check the jump bytes, the untouched tail, the stale-fault retry and the page protection. AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.
BBareth commented 2026-12-01 21:49:29 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by BBareth on 2026-12-01T21:49:29Z.


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

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

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

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

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

<!-- greyfinch-sync:ivall/xcl:comment:7326841810 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3588#issuecomment-7326841810). Originally posted by [BBareth](https://github.com/BBareth) on 2026-12-01T21:49:29Z. --- On the review of 9ac69984: both points checked against the source; the first is fixed in 81ad460d. **One CLWB site in eight faulted at every visit**: right. `rewrite_code` refuses a rewrite that crosses an aligned word, and the arm only stepped RIP then, so a site at word offset 7 was never patched, where `main` patched it once. Such a site now gets a second form instead of the jump: its opcode and ModRM bytes, which are both in the second word, become those of the NOP with the same operand (`0F AE /6` to `0F 1F /0`, e.g. `66 0F AE 30` to `66 0F 1F 00`). Prefixes and operand bytes stay, the length is the same, it is one atomic write under `CODE_REWRITE`, and the site is recorded with its unchanged prefix (`rewrite_code_within`), so a thread that faulted on the old bytes is retried there as for the jump. Every site is patched once again. The test is now `clwb_across_an_atomic_word_becomes_a_nop_with_its_operand` (offset 7, with and without a REX prefix: the patched bytes, the bytes around them, the retry of a stale fault). **Clash with #1829**: yes, its `clwb_patches_instruction_bytes_to_nop_and_advances_rip` expects NOP bytes at an ordinary site and this PR writes `EB, len - 2` there. Whichever lands second has to adjust that test; I added it to **Not tested** and will rebase if #1829 goes first. Suite on 81ad460d: 2906 passed, 0 failed, 51 ignored, 28 SKIPPED lines. The smoke block in the description is rerun on this head (3082 frames, no device removal, no crash). Not done: the NOP form was not executed on a CPU, the test checks bytes. AI use: Claude Code, Claude Fable 5.2 checked the points against the source, wrote the change and this comment and ran the tests.
Foniass commented 2026-12-01 21:53:24 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-01T21:53:24Z.


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

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

New:

  • Overlaps open #3548 in rewrite_code. #3548 rewrites the body of rewrite_code (16-byte cmpxchg16b path, remember_rewritten_wait(at, new)), which this PR moves into rewrite_code_within (~454) and changes (~476), so whichever lands second needs a rebase. With #3548, an offset-7 CLWB could take the jump inside its 16-byte block and the NOP fallback would only be needed at offset 15; neither description mentions the other.

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

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

<!-- greyfinch-sync:ivall/xcl:comment:7326964874 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3588#issuecomment-7326964874). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-01T21:53:24Z. --- Follow-up review (head 81ad460d, since 9ac69984, diff read, not a merge-check): - **One CLWB site in eight faulted at every visit:** fixed. When the first two bytes cross an aligned word, the CLWB arm (`eh.rs` ~597-601) now writes a NOP with the same operand (`0F AE /6` to `0F 1F /0`, prefixes and operand bytes kept, same length) with one CAS through `rewrite_code_within` (~454), which records the site with its prefix bytes so a stale fault is retried through `rewritten_wait`. `clwb_across_an_atomic_word_becomes_a_nop_with_its_operand` (~1718) checks both encodings, the surrounding bytes and the retry. - **Clashes with open #1829:** still open. #1829's `clwb_patches_instruction_bytes_to_nop_and_advances_rip` still expects NOP bytes where this PR writes `EB, len - 2`; the description now lists it, so whichever lands second adjusts that test. New: - **Overlaps open #3548 in `rewrite_code`.** #3548 rewrites the body of `rewrite_code` (16-byte `cmpxchg16b` path, `remember_rewritten_wait(at, new)`), which this PR moves into `rewrite_code_within` (~454) and changes (~476), so whichever lands second needs a rebase. With #3548, an offset-7 CLWB could take the jump inside its 16-byte block and the NOP fallback would only be needed at offset 15; neither description mentions the other. Fine: only the opcode and ModRM bytes change, both in one aligned word; `0F` is never a prefix byte so the first `0F AE` found is the opcode; `modrm & 0xC7` keeps `mod`/`rm`, so SIB, displacement and length stay valid; the jump path, lock, protection restore and TF case are unchanged. AI review: Claude Code (Claude Opus 5.5), posted by Foniass without a human check of each point.
bmjask commented 2026-12-02 15:18:58 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T15:18:58Z.

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

@@ -575,13 +584,22 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics
     match what {
         ConsoleOnly::Ud2 => return 0,
         ConsoleOnly::Clwb => {
-            use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READWRITE};
-            let mut old = 0u32;
-            // TF requests single-instruction stepping: preserve its boundary on later visits.
-            if ctx.EFlags & 0x100 == 0 && unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, PAGE_EXECUTE_READWRITE, &mut old) } != 0 {
-                let code = unsafe { std::slice::from_raw_parts_mut(rip as *mut u8, len) };
-                code.fill(0x90);
-                unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, old, &mut old) };
+            // Nothing to emulate. Later visits skip the fault: the first two bytes become a short
+            // jump over the instruction, through `rewrite_code` like the waits (one atomic word
+            // write under CODE_REWRITE, the page protection restored, the instruction cache
+            // flushed, and a thread that faulted on the old bytes retried: `rewritten_wait`). The
+            // bytes after the jump stay, so no thread can run a half-written instruction. A site
+            // whose first two bytes cross an aligned word cannot take the jump in one write: its
+            // opcode and ModRM bytes, which are in the second word, become those of the NOP with
+            // the same operand (`0F 1F /0`), the prefixes before them and the operand after stay.
+            // TF requests single-instruction stepping: such a visit leaves the code alone.
+            if ctx.EFlags & 0x100 == 0 && (2..=129).contains(&len) {
+                if (rip & 7) + 2 <= 8 {
+                    rewrite_code(rip, &code[..2], &[0xEB, (len - 2) as u8]);
+                } else if let Some(i) = (0..len.saturating_sub(2)).find(|&i| code[i] == 0x0F && code[i + 1] == 0xAE) {
+                    let modrm = code[i + 2];
+                    rewrite_code_within(rip, i + 1, &[0xAE, modrm], &[0x1F, modrm & 0xC7]);

Critical: Not certain about this one, because it depends on how the CPU handles code modified on another core without serialization: the NOP form rewrites the ModRM reg field (/6 to /0) as well as the opcode, in the middle of a live instruction, with no other core serialized first. A core that fetches a mix of old and new bytes can decode 66 0F AE /0, which is FXSAVE, not a NOP. For site 66 0F AE 30 at word offset 7, thread B writes [1F 00] over [AE 30] while core A is fetching it. Intel only guarantees stale-or-new for the first byte, so if core A combines the old opcode AE with the new ModRM 00, it runs fxsave [rax] and writes 512 bytes at rax, corrupting title memory. Changing only the 0xAE byte (to 0F 1F /6, also a reserved NOP of the same length) is a single-byte write, so it can never be seen half-done and works at every word offset.

<!-- greyfinch-sync:ivall/xcl:review-comment:4771821015 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3588#discussion_r4771821015). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:18:58Z. **Code review location:** `crates/xcl/src/eh.rs`; line 601 ~~~~diff @@ -575,13 +584,22 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics match what { ConsoleOnly::Ud2 => return 0, ConsoleOnly::Clwb => { - use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READWRITE}; - let mut old = 0u32; - // TF requests single-instruction stepping: preserve its boundary on later visits. - if ctx.EFlags & 0x100 == 0 && unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, PAGE_EXECUTE_READWRITE, &mut old) } != 0 { - let code = unsafe { std::slice::from_raw_parts_mut(rip as *mut u8, len) }; - code.fill(0x90); - unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, old, &mut old) }; + // Nothing to emulate. Later visits skip the fault: the first two bytes become a short + // jump over the instruction, through `rewrite_code` like the waits (one atomic word + // write under CODE_REWRITE, the page protection restored, the instruction cache + // flushed, and a thread that faulted on the old bytes retried: `rewritten_wait`). The + // bytes after the jump stay, so no thread can run a half-written instruction. A site + // whose first two bytes cross an aligned word cannot take the jump in one write: its + // opcode and ModRM bytes, which are in the second word, become those of the NOP with + // the same operand (`0F 1F /0`), the prefixes before them and the operand after stay. + // TF requests single-instruction stepping: such a visit leaves the code alone. + if ctx.EFlags & 0x100 == 0 && (2..=129).contains(&len) { + if (rip & 7) + 2 <= 8 { + rewrite_code(rip, &code[..2], &[0xEB, (len - 2) as u8]); + } else if let Some(i) = (0..len.saturating_sub(2)).find(|&i| code[i] == 0x0F && code[i + 1] == 0xAE) { + let modrm = code[i + 2]; + rewrite_code_within(rip, i + 1, &[0xAE, modrm], &[0x1F, modrm & 0xC7]); ~~~~ --- **Critical**: Not certain about this one, because it depends on how the CPU handles code modified on another core without serialization: the NOP form rewrites the ModRM reg field (/6 to /0) as well as the opcode, in the middle of a live instruction, with no other core serialized first. A core that fetches a mix of old and new bytes can decode `66 0F AE /0`, which is FXSAVE, not a NOP. For site `66 0F AE 30` at word offset 7, thread B writes `[1F 00]` over `[AE 30]` while core A is fetching it. Intel only guarantees stale-or-new for the first byte, so if core A combines the old opcode `AE` with the new ModRM `00`, it runs `fxsave [rax]` and writes 512 bytes at rax, corrupting title memory. Changing only the 0xAE byte (to `0F 1F /6`, also a reserved NOP of the same length) is a single-byte write, so it can never be seen half-done and works at every word offset.
bmjask commented 2026-12-02 15:18:58 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T15:18:58Z.

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

@@ -575,13 +584,22 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics
     match what {
         ConsoleOnly::Ud2 => return 0,
         ConsoleOnly::Clwb => {
-            use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READWRITE};
-            let mut old = 0u32;
-            // TF requests single-instruction stepping: preserve its boundary on later visits.
-            if ctx.EFlags & 0x100 == 0 && unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, PAGE_EXECUTE_READWRITE, &mut old) } != 0 {
-                let code = unsafe { std::slice::from_raw_parts_mut(rip as *mut u8, len) };
-                code.fill(0x90);
-                unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, old, &mut old) };
+            // Nothing to emulate. Later visits skip the fault: the first two bytes become a short
+            // jump over the instruction, through `rewrite_code` like the waits (one atomic word
+            // write under CODE_REWRITE, the page protection restored, the instruction cache
+            // flushed, and a thread that faulted on the old bytes retried: `rewritten_wait`). The
+            // bytes after the jump stay, so no thread can run a half-written instruction. A site
+            // whose first two bytes cross an aligned word cannot take the jump in one write: its
+            // opcode and ModRM bytes, which are in the second word, become those of the NOP with
+            // the same operand (`0F 1F /0`), the prefixes before them and the operand after stay.
+            // TF requests single-instruction stepping: such a visit leaves the code alone.
+            if ctx.EFlags & 0x100 == 0 && (2..=129).contains(&len) {
+                if (rip & 7) + 2 <= 8 {
+                    rewrite_code(rip, &code[..2], &[0xEB, (len - 2) as u8]);
+                } else if let Some(i) = (0..len.saturating_sub(2)).find(|&i| code[i] == 0x0F && code[i + 1] == 0xAE) {

Medium: The search for 0F AE reads live code memory after decode has run, so a concurrent patch can make it skip the real opcode (now 0F 1F) and match 0F AE bytes inside the displacement. It then rewrites displacement bytes and replaces the registry entry with a different byte string. For 66 0F AE 35 0F AE xx xx (rip-relative, disp32 starting 0F AE) at rip&7 == 7 with two threads faulting at once, B patches the opcode, then A finds i=4 and CASes the displacement [AE, xx] to [1F, xx&C7], so the site's bytes change a second time and remember_rewritten_wait stores a longer prefix. Taking the opcode offset from the decoded prefix length, not a scan of mutable memory, would avoid it.

<!-- greyfinch-sync:ivall/xcl:review-comment:4771821024 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3588#discussion_r4771821024). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:18:58Z. **Code review location:** `crates/xcl/src/eh.rs`; line 599 ~~~~diff @@ -575,13 +584,22 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics match what { ConsoleOnly::Ud2 => return 0, ConsoleOnly::Clwb => { - use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READWRITE}; - let mut old = 0u32; - // TF requests single-instruction stepping: preserve its boundary on later visits. - if ctx.EFlags & 0x100 == 0 && unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, PAGE_EXECUTE_READWRITE, &mut old) } != 0 { - let code = unsafe { std::slice::from_raw_parts_mut(rip as *mut u8, len) }; - code.fill(0x90); - unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, old, &mut old) }; + // Nothing to emulate. Later visits skip the fault: the first two bytes become a short + // jump over the instruction, through `rewrite_code` like the waits (one atomic word + // write under CODE_REWRITE, the page protection restored, the instruction cache + // flushed, and a thread that faulted on the old bytes retried: `rewritten_wait`). The + // bytes after the jump stay, so no thread can run a half-written instruction. A site + // whose first two bytes cross an aligned word cannot take the jump in one write: its + // opcode and ModRM bytes, which are in the second word, become those of the NOP with + // the same operand (`0F 1F /0`), the prefixes before them and the operand after stay. + // TF requests single-instruction stepping: such a visit leaves the code alone. + if ctx.EFlags & 0x100 == 0 && (2..=129).contains(&len) { + if (rip & 7) + 2 <= 8 { + rewrite_code(rip, &code[..2], &[0xEB, (len - 2) as u8]); + } else if let Some(i) = (0..len.saturating_sub(2)).find(|&i| code[i] == 0x0F && code[i + 1] == 0xAE) { ~~~~ --- **Medium**: The search for `0F AE` reads live code memory after `decode` has run, so a concurrent patch can make it skip the real opcode (now `0F 1F`) and match `0F AE` bytes inside the displacement. It then rewrites displacement bytes and replaces the registry entry with a different byte string. For `66 0F AE 35 0F AE xx xx` (rip-relative, disp32 starting `0F AE`) at rip&7 == 7 with two threads faulting at once, B patches the opcode, then A finds i=4 and CASes the displacement `[AE, xx]` to `[1F, xx&C7]`, so the site's bytes change a second time and `remember_rewritten_wait` stores a longer prefix. Taking the opcode offset from the decoded prefix length, not a scan of mutable memory, would avoid it.
bmjask commented 2026-12-02 15:18:58 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T15:18:58Z.

Review: COMMENTED


Review of 81ad460d: 2 finding(s) (1 critical, 1 medium), most severe first.

  1. Critical crates/xcl/src/eh.rs:601: Not certain about this one, because it depends on how the CPU handles code modified on another core without serialization: the NOP form rewrites the ModRM reg field (/6 to /0) as well as the opcode, in the middle of a live instruction, w.... (inline)
  2. Medium crates/xcl/src/eh.rs:599: The search for 0F AE reads live code memory after decode has run, so a concurrent patch can make it skip the real opcode (now 0F 1F) and match 0F AE bytes inside the displacement. (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:6153703125 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3588#pullrequestreview-6153703125). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:18:58Z. **Review:** COMMENTED --- Review of `81ad460d`: 2 finding(s) (1 critical, 1 medium), most severe first. 1. **Critical** `crates/xcl/src/eh.rs:601`: Not certain about this one, because it depends on how the CPU handles code modified on another core without serialization: the NOP form rewrites the ModRM reg field (/6 to /0) as well as the opcode, in the middle of a live instruction, w.... (inline) 2. **Medium** `crates/xcl/src/eh.rs:599`: The search for `0F AE` reads live code memory after `decode` has run, so a concurrent patch can make it skip the real opcode (now `0F 1F`) and match `0F AE` bytes inside the displacement. (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 15:19:04 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by bmjask on 2026-12-02T15:19:04Z.


@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:7350118069 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3588#issuecomment-7350118069). Originally posted by [bmjask](https://github.com/bmjask) on 2026-12-02T15:19:04Z. --- @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 01:37:11 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by BBareth on 2026-12-03T01:37:11Z.

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

@@ -575,13 +584,22 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics
     match what {
         ConsoleOnly::Ud2 => return 0,
         ConsoleOnly::Clwb => {
-            use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READWRITE};
-            let mut old = 0u32;
-            // TF requests single-instruction stepping: preserve its boundary on later visits.
-            if ctx.EFlags & 0x100 == 0 && unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, PAGE_EXECUTE_READWRITE, &mut old) } != 0 {
-                let code = unsafe { std::slice::from_raw_parts_mut(rip as *mut u8, len) };
-                code.fill(0x90);
-                unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, old, &mut old) };
+            // Nothing to emulate. Later visits skip the fault: the first two bytes become a short
+            // jump over the instruction, through `rewrite_code` like the waits (one atomic word
+            // write under CODE_REWRITE, the page protection restored, the instruction cache
+            // flushed, and a thread that faulted on the old bytes retried: `rewritten_wait`). The
+            // bytes after the jump stay, so no thread can run a half-written instruction. A site
+            // whose first two bytes cross an aligned word cannot take the jump in one write: its
+            // opcode and ModRM bytes, which are in the second word, become those of the NOP with
+            // the same operand (`0F 1F /0`), the prefixes before them and the operand after stay.
+            // TF requests single-instruction stepping: such a visit leaves the code alone.
+            if ctx.EFlags & 0x100 == 0 && (2..=129).contains(&len) {
+                if (rip & 7) + 2 <= 8 {
+                    rewrite_code(rip, &code[..2], &[0xEB, (len - 2) as u8]);
+                } else if let Some(i) = (0..len.saturating_sub(2)).find(|&i| code[i] == 0x0F && code[i + 1] == 0xAE) {
+                    let modrm = code[i + 2];
+                    rewrite_code_within(rip, i + 1, &[0xAE, modrm], &[0x1F, modrm & 0xC7]);

Agreed, fixed in f2179fc0. The cross-word form now changes only the second opcode byte, AE to 1F, and leaves the ModRM byte as it is: 0F 1F /6 is a reserved NOP of the same length. A one-byte write can only be seen as the old or the new byte, so a core can no longer combine the old opcode with a new ModRM (0F AE /0, FXSAVE). The test now expects 66 0F 1F 30 and 66 41 0F 1F 74 24 08.

<!-- greyfinch-sync:ivall/xcl:review-comment:4778680612 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3588#discussion_r4778680612). Originally posted by [BBareth](https://github.com/BBareth) on 2026-12-03T01:37:11Z. **Code review location:** `crates/xcl/src/eh.rs`; line 601 ~~~~diff @@ -575,13 +584,22 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics match what { ConsoleOnly::Ud2 => return 0, ConsoleOnly::Clwb => { - use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READWRITE}; - let mut old = 0u32; - // TF requests single-instruction stepping: preserve its boundary on later visits. - if ctx.EFlags & 0x100 == 0 && unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, PAGE_EXECUTE_READWRITE, &mut old) } != 0 { - let code = unsafe { std::slice::from_raw_parts_mut(rip as *mut u8, len) }; - code.fill(0x90); - unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, old, &mut old) }; + // Nothing to emulate. Later visits skip the fault: the first two bytes become a short + // jump over the instruction, through `rewrite_code` like the waits (one atomic word + // write under CODE_REWRITE, the page protection restored, the instruction cache + // flushed, and a thread that faulted on the old bytes retried: `rewritten_wait`). The + // bytes after the jump stay, so no thread can run a half-written instruction. A site + // whose first two bytes cross an aligned word cannot take the jump in one write: its + // opcode and ModRM bytes, which are in the second word, become those of the NOP with + // the same operand (`0F 1F /0`), the prefixes before them and the operand after stay. + // TF requests single-instruction stepping: such a visit leaves the code alone. + if ctx.EFlags & 0x100 == 0 && (2..=129).contains(&len) { + if (rip & 7) + 2 <= 8 { + rewrite_code(rip, &code[..2], &[0xEB, (len - 2) as u8]); + } else if let Some(i) = (0..len.saturating_sub(2)).find(|&i| code[i] == 0x0F && code[i + 1] == 0xAE) { + let modrm = code[i + 2]; + rewrite_code_within(rip, i + 1, &[0xAE, modrm], &[0x1F, modrm & 0xC7]); ~~~~ --- Agreed, fixed in f2179fc0. The cross-word form now changes only the second opcode byte, `AE` to `1F`, and leaves the ModRM byte as it is: `0F 1F /6` is a reserved NOP of the same length. A one-byte write can only be seen as the old or the new byte, so a core can no longer combine the old opcode with a new ModRM (`0F AE /0`, FXSAVE). The test now expects `66 0F 1F 30` and `66 41 0F 1F 74 24 08`.
BBareth commented 2026-12-03 01:37:12 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by BBareth on 2026-12-03T01:37:12Z.

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

@@ -575,13 +584,22 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics
     match what {
         ConsoleOnly::Ud2 => return 0,
         ConsoleOnly::Clwb => {
-            use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READWRITE};
-            let mut old = 0u32;
-            // TF requests single-instruction stepping: preserve its boundary on later visits.
-            if ctx.EFlags & 0x100 == 0 && unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, PAGE_EXECUTE_READWRITE, &mut old) } != 0 {
-                let code = unsafe { std::slice::from_raw_parts_mut(rip as *mut u8, len) };
-                code.fill(0x90);
-                unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, old, &mut old) };
+            // Nothing to emulate. Later visits skip the fault: the first two bytes become a short
+            // jump over the instruction, through `rewrite_code` like the waits (one atomic word
+            // write under CODE_REWRITE, the page protection restored, the instruction cache
+            // flushed, and a thread that faulted on the old bytes retried: `rewritten_wait`). The
+            // bytes after the jump stay, so no thread can run a half-written instruction. A site
+            // whose first two bytes cross an aligned word cannot take the jump in one write: its
+            // opcode and ModRM bytes, which are in the second word, become those of the NOP with
+            // the same operand (`0F 1F /0`), the prefixes before them and the operand after stay.
+            // TF requests single-instruction stepping: such a visit leaves the code alone.
+            if ctx.EFlags & 0x100 == 0 && (2..=129).contains(&len) {
+                if (rip & 7) + 2 <= 8 {
+                    rewrite_code(rip, &code[..2], &[0xEB, (len - 2) as u8]);
+                } else if let Some(i) = (0..len.saturating_sub(2)).find(|&i| code[i] == 0x0F && code[i + 1] == 0xAE) {

Fixed in f2179fc0. The scan now takes one copy of the bytes and looks for 0F AE only right after the prefix bytes (clwb_opcode_at: legacy prefixes and REX, then the opcode must follow). A site another thread patched to 0F 1F in the meantime no longer matches, and nothing inside the displacement is ever taken for the opcode. Test: clwb_opcode_is_found_past_the_prefixes_only.

<!-- greyfinch-sync:ivall/xcl:review-comment:4778680848 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3588#discussion_r4778680848). Originally posted by [BBareth](https://github.com/BBareth) on 2026-12-03T01:37:12Z. **Code review location:** `crates/xcl/src/eh.rs`; line 599 ~~~~diff @@ -575,13 +584,22 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics match what { ConsoleOnly::Ud2 => return 0, ConsoleOnly::Clwb => { - use windows_sys::Win32::System::Memory::{VirtualProtect, PAGE_EXECUTE_READWRITE}; - let mut old = 0u32; - // TF requests single-instruction stepping: preserve its boundary on later visits. - if ctx.EFlags & 0x100 == 0 && unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, PAGE_EXECUTE_READWRITE, &mut old) } != 0 { - let code = unsafe { std::slice::from_raw_parts_mut(rip as *mut u8, len) }; - code.fill(0x90); - unsafe { VirtualProtect(rip as *const std::ffi::c_void, len, old, &mut old) }; + // Nothing to emulate. Later visits skip the fault: the first two bytes become a short + // jump over the instruction, through `rewrite_code` like the waits (one atomic word + // write under CODE_REWRITE, the page protection restored, the instruction cache + // flushed, and a thread that faulted on the old bytes retried: `rewritten_wait`). The + // bytes after the jump stay, so no thread can run a half-written instruction. A site + // whose first two bytes cross an aligned word cannot take the jump in one write: its + // opcode and ModRM bytes, which are in the second word, become those of the NOP with + // the same operand (`0F 1F /0`), the prefixes before them and the operand after stay. + // TF requests single-instruction stepping: such a visit leaves the code alone. + if ctx.EFlags & 0x100 == 0 && (2..=129).contains(&len) { + if (rip & 7) + 2 <= 8 { + rewrite_code(rip, &code[..2], &[0xEB, (len - 2) as u8]); + } else if let Some(i) = (0..len.saturating_sub(2)).find(|&i| code[i] == 0x0F && code[i + 1] == 0xAE) { ~~~~ --- Fixed in f2179fc0. The scan now takes one copy of the bytes and looks for `0F AE` only right after the prefix bytes (`clwb_opcode_at`: legacy prefixes and REX, then the opcode must follow). A site another thread patched to `0F 1F` in the meantime no longer matches, and nothing inside the displacement is ever taken for the opcode. Test: `clwb_opcode_is_found_past_the_prefixes_only`.
BBareth commented 2026-12-03 01:37:15 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by BBareth on 2026-12-03T01:37:15Z.


Updated to f2179fc0 (rebased on main 078358a0) after @bmjask's review of 81ad460d. Both points are fixed; replies are in the threads:

  • The cross-word form changes one byte only (AE to 1F; 0F 1F /6 is a NOP of the same length), so no core can fetch a half-changed instruction.
  • The opcode is found right after the prefixes, not by scanning live bytes.

@Foniass, on #3548: I've reworked that PR so it no longer has the 16-byte cmpxchg16b path. It changes only bytes inside one aligned word, like this one, so the CLWB fallback is still needed at offset 7. The two PRs still both touch rewrite_code, and whichever lands second gets rebased.

Suite on f2179fc0: 3009 passed, 0 failed, 52 ignored, 28 SKIPPED. Smoke blocks in the description were rerun on this head. Still not done: a real CLWB fault (this CPU has CLWB).

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

<!-- greyfinch-sync:ivall/xcl:comment:7364548222 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3588#issuecomment-7364548222). Originally posted by [BBareth](https://github.com/BBareth) on 2026-12-03T01:37:15Z. --- Updated to f2179fc0 (rebased on main 078358a0) after @bmjask's review of 81ad460d. Both points are fixed; replies are in the threads: - The cross-word form changes one byte only (`AE` to `1F`; `0F 1F /6` is a NOP of the same length), so no core can fetch a half-changed instruction. - The opcode is found right after the prefixes, not by scanning live bytes. @Foniass, on #3548: I've reworked that PR so it no longer has the 16-byte `cmpxchg16b` path. It changes only bytes inside one aligned word, like this one, so the CLWB fallback is still needed at offset 7. The two PRs still both touch `rewrite_code`, and whichever lands second gets rebased. Suite on f2179fc0: 3009 passed, 0 failed, 52 ignored, 28 SKIPPED. Smoke blocks in the description were rerun on this head. Still not done: a real CLWB fault (this CPU has CLWB). AI use: Claude Code (Claude Opus 5.5) made the fixes, ran the suite and the smoke runs, and wrote these replies.
Foniass commented 2026-12-03 01:39:50 +00:00 (Migrated from github.com)

Imported from ivall/xcl. Originally posted by Foniass on 2026-12-03T01:39:50Z.


Follow-up review of f2179fc0, since 81ad460d (code reading only, not a merge-check) · no new findings

In short: This push changes how a CLWB whose first two bytes cross an aligned word is patched. Only its second opcode byte is now rewritten, AE → 1F. 66 0F 1F /6 is a reserved NOP of the same length, and a one-byte write can never be seen half done by another core, which before could fetch the old opcode with a new ModRM byte (66 0F AE /0, FXSAVE). The opcode is now found past the prefixes of one copy of the bytes, so a site another thread already patched is not matched inside its displacement. Both have tests. The two overlaps are now in the description, and nothing blocks it.

Checked and fine
  • 0F 1F with any ModRM reg is in the hint-NOP space and runs as a NOP. Keeping /6 and the operand keeps the length and the SIB / displacement bytes valid, as the test expectations show.
  • clwb_opcode_at (eh.rs) skips the legacy and REX prefixes (66 67 F2 F3 2E 3E 26 36 64 65 40-4F) and requires 0F AE right after them. A copy patched since decode read it (0F 1F with 0F AE in its displacement) returns None. clwb_opcode_is_found_past_the_prefixes_only covers both encodings and that case.
  • rewrite_code_within(rip, i + 1, &[0xAE], &[0x1F]) writes one byte through the same CAS, records the site, and keeps the retry through rewritten_wait.
  • Earlier points: the clash with #1829's test and the overlap with #3548 in rewrite_code are both stated in the description now. #3548 no longer widens the write to 16 bytes.
  • The jump path, the lock, the protection restore and the TF case are unchanged.

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

<!-- greyfinch-sync:ivall/xcl:comment:7364595223 --> Imported from [ivall/xcl](https://github.com/xcl-dev/xcl/pull/3588#issuecomment-7364595223). Originally posted by [Foniass](https://github.com/Foniass) on 2026-12-03T01:39:50Z. --- **Follow-up review** of `f2179fc0`, since `81ad460d` (code reading only, not a merge-check) · no new findings **In short:** This push changes how a CLWB whose first two bytes cross an aligned word is patched. Only its second opcode byte is now rewritten, `AE` → `1F`. `66 0F 1F /6` is a reserved NOP of the same length, and a one-byte write can never be seen half done by another core, which before could fetch the old opcode with a new ModRM byte (`66 0F AE /0`, FXSAVE). The opcode is now found past the prefixes of one copy of the bytes, so a site another thread already patched is not matched inside its displacement. Both have tests. The two overlaps are now in the description, and nothing blocks it. <details><summary>Checked and fine</summary> - `0F 1F` with any ModRM `reg` is in the hint-NOP space and runs as a NOP. Keeping `/6` and the operand keeps the length and the SIB / displacement bytes valid, as the test expectations show. - `clwb_opcode_at` (`eh.rs`) skips the legacy and REX prefixes (`66 67 F2 F3 2E 3E 26 36 64 65 40-4F`) and requires `0F AE` right after them. A copy patched since `decode` read it (`0F 1F` with `0F AE` in its displacement) returns `None`. `clwb_opcode_is_found_past_the_prefixes_only` covers both encodings and that case. - `rewrite_code_within(rip, i + 1, &[0xAE], &[0x1F])` writes one byte through the same CAS, records the site, and keeps the retry through `rewritten_wait`. - Earlier points: the clash with #1829's test and the overlap with #3548 in `rewrite_code` are both stated in the description now. #3548 no longer widens the write to 16 bytes. - The jump path, the lock, the protection restore and the TF case are unchanged. </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/3588:upstream-pr/3588'
git switch 'upstream-pr/3588'

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