Skip to content

Console CPU instructions: serialize CLWB hot-patching and flush icache (#278) - #321

Open
TG0000 wants to merge 2 commits into
xcl-dev:mainfrom
TG0000:fix/clwb-hotpatch-race
Open

TG0000 wants to merge 2 commits into
xcl-dev:mainfrom
TG0000:fix/clwb-hotpatch-race

Conversation

@TG0000

@TG0000 TG0000 commented Nov 23, 2026 •

Copy link
Copy Markdown
Contributor

Part of #278 (item 4: the CLWB hot-patch race). Items 1 and 2 (the CLZERO loop) are in #295 and #290; item 3 (is_writable) is not in this PR.

A CLWB was hot-patched like this: make its bytes writable, fill them with 0x90 one byte at a time, put the protection back. Nothing was shared between threads, which caused four problems:

  • Protection race. Two threads patching on one page could restore each other's protection. The page could stay PAGE_EXECUTE_READWRITE, or become read-only again while the other thread was still writing.
  • Torn instruction. Another thread could run half-written bytes. 90 0F AE 30 is a nop followed by xsaveopt [rax].
  • Late faulter. A thread that faulted on the CLWB just before another thread patched it read the NOPs. NOPs don't decode, so its fault went on to the title's handlers.
  • No flush. FlushInstructionCache was never called.

What is in it

  • One lock covers all CLWB patching: making the page writable, the write, restoring the old protection and FlushInstructionCache. The lock also guards the set of addresses already patched. Everything is in crates/xcl/src/eh.rs.
  • Only the first two bytes change. They become a short jump over the instruction (EB, len - 2), written by a single lock cmpxchg, so another thread runs either the whole CLWB or the whole jump. The bytes after the jump are left as they were.
  • A fault on an address that is already patched resumes at the jump. This covers a thread that faulted before the patch and reads the bytes after it.
  • A CLWB whose first two bytes cross a cache line is not patched, because no single store there is atomic. It is stepped over on every fault, as before the hot-patch existed.

Tested

  • Hardware: AMD Ryzen 9 5900X, Windows 11 Pro. No GPU is involved in these tests.
  • Toolchain: Rust 1.100.0 stable-x86_64-pc-windows-gnu with llvm-mingw, debug build.
  • The 5900X runs CLWB natively, so it never raises the fault. The tests call the exception handler's emulation (emulate_console_only) directly on code pages registered as a title module and set to PAGE_EXECUTE_READ. The patched code is then actually executed.
  • New tests in eh::tests, all passing:
    • clwb_patch_is_a_short_jump_over_the_instruction: the jump bytes for lengths 4 to 15; no patch when the bytes cross a cache line or a page, or for an invalid length.
    • clwb_is_patched_into_a_jump_and_the_page_keeps_its_protection: clwb [rax], clwb [rsp+8] at an odd address, and clwb [r8]. Only two bytes change, the page is PAGE_EXECUTE_READ afterwards, a second (late) fault resumes at the jump, and the code runs.
    • clwb_across_a_cache_line_is_stepped_over
    • clwb_patching_from_many_threads_at_once: 8 threads fault on 64 CLWBs on one page at once, in different orders, some twice. A watcher thread checks that each CLWB's first two bytes are only ever the old bytes or the jump. Every fault is handled, every CLWB is patched, the page ends PAGE_EXECUTE_READ, and all the patched code runs. Passed 5 of 5 runs.
  • cargo test --workspace --exclude testgame-mw --no-fail-fast -- --test-threads=4: xcl lib 614 passed, 1 failed, 20 ignored. All other targets passed apart from the e2e target, which had 1 failure. Neither failure involves this change:
    • pe::tests::parses_own_test_binary_tls expects the test binary to have a PE TLS directory. A windows-gnu binary doesn't have one; the MSVC target does.
    • e2e::test_title_runs_and_game_folder_is_untouched needs testgame_mw.dll, and testgame-mw was excluded because it doesn't build with this local toolchain.
  • No new warnings. The one warning in the build, the fetch_update deprecation in hle/xgameruntime/mod.rs, was already there (see XGameRuntime: try_update instead of the deprecated fetch_update #251).

Regression run
Windows 11, Ryzen 9 5900X, AMD Radeon RX 6800, Rust stable x86_64-pc-windows-msvc (VS 2022 Build Tools, link.exe), cargo build --release -p xcl, scripts/smoke.ps1 -Seconds 45, one run at a time under a RAM watchdog.

main (a6f5f7a, current origin/main, this PR's base):

xcl-smoke v1
commit: a6f5f7a74cc620c1f88a9e3669a633d10c3c8212
gpu: AMD Radeon RX 6800
title: retail-title-1.0.2.1
seconds: 45
exit: 0x0
frames shown: 828 (PresentX 828)
presents per 2 s (last 3): 59 60 60
device removals: 0
crashes: 0
peak commit: 15144 MB

PR (head commit, no local changes):

xcl-smoke v1
commit: 6c42ec75a2984c945fd009f8c694edcbbee047d5
gpu: AMD Radeon RX 6800
title: retail-title-1.0.2.1
seconds: 45
exit: 0x0
frames shown: 790 (PresentX 790)
presents per 2 s (last 3): 60 60 55
device removals: 0
crashes: 0
peak commit: 15155 MB

No regression: 790 frames against 828 on its base, no device removals or crashes, peak commit 15155 MB against 15144 MB. The 5900X has CLWB natively, so this run doesn't reach the hot-patching path; it only shows nothing else changed. Frame counts move by about 10 % between runs of the same commit on this machine (earlier runs of main gave 843, 709 and 828), and more when other builds are running: a first run of this head, made while other builds were compiling on the machine, gave 524 frames, so I reran it once the machine was idle and give that run above.

Rebased onto current main (a6f5f7a): the one conflict, in eh.rs, is resolved by keeping main's tests (cmp_eflags_matches_x86_64_sub_flags, the CLZERO loop test, code_bytes_on_the_instructions_page_are_not_asked_about) next to the CLWB ones. On the rebased head, built with stable-x86_64-pc-windows-msvc, cargo test -p xcl --lib eh passes: 11 passed, 0 failed, including the four clwb_* tests.

Not tested

  • A real CLWB fault (an Intel CPU before Ice Lake).
  • Other code in XCL that changes the protection of title pages (for example hook_gs_failure) doesn't take this lock. Those patches run at load time, not from the exception handler.

AI use

  • Claude Opus 5.5 (Claude Code) wrote the change and the tests and ran them. The author reviewed the result.

🤖 Generated with Claude Code

@mastrr9

mastrr9 commented Nov 23, 2026

Copy link
Copy Markdown

Static code audit of 7d5f5f0 (not tested on Windows / pre-Ice Lake CPU; no game files):

Overall this is a very clean fix for the CLWB hot-patch race in #278:

  • Lock ordering for late faulters: Holding CLWB_PATCHES across VirtualProtect(RWX) -> cas_u16 -> VirtualProtect(old) -> FlushInstructionCache -> patches.insert(rip) ensures any concurrent thread that reads [0xEB, len - 2] after cas_u16 and enters clwb_patched(rip) blocks until rip is inserted, so it never leaks to the title's exception handler.
  • Atomicity & inline asm: Guarding rip % 64 == 63 keeps the 2-byte lock cmpxchg within one cache line, and cas_u16 correctly omits preserves_flags since cmpxchg clobbers EFLAGS.
  • No VEH deadlock: CLWB_PATCHES is only acquired on the ILLEGAL_INSTRUCTION VEH path (emulate_console_only).

One small hardening suggestion

  • DLL unload / address reuse (eh.rs:360): Currently if clwb_patched(rip) { return -1; } unconditionally resumes at rip. If a DLL containing a patched CLWB is ever unloaded and another module/code is later mapped at the same address and hits a genuine #UD at rip, returning -1 without checking the bytes would spin indefinitely. Checking code.first() == Some(&0xEB) && clwb_patched(rip) (and/or pruning CLWB_PATCHES if a module is unregistered) prevents that cleanly.
  • (Tiny test comment nit: in clwb_patching_from_many_threads_at_once, k * 0x20 + 2 * (k % 4) for k % 4 == 3 puts the 2-byte load at offset +6..+8, which is aligned inside the qword rather than crossing a qword boundary — harmless, just slightly different from the comment.)

AI use: static code audit of 7d5f5f0 with Antigravity (Gemini 4 Neon).

@ghost

ghost commented Nov 24, 2026

Copy link
Copy Markdown

MSVC run, since Not tested lists the MSVC toolchain. This PR's head 7d5f5f0 builds and passes with x86_64-pc-windows-msvc. It no longer merges cleanly with main a6f5f7a, which changed eh.rs (#306's is_writable window check), so I ran the head as it is, not merged.

Tested

  • Ryzen 7 5800X3D (runs CLWB natively, so like your 5900X it only exercises the emulation path the tests call directly); Windows 11 Pro 26200; Rust 1.100.0 stable-x86_64-pc-windows-msvc; debug build.
  • cargo test -p xcl --lib clwb: all 4 pass (clwb_patch_is_a_short_jump_over_the_instruction, clwb_is_patched_into_a_jump_and_the_page_keeps_its_protection, clwb_across_a_cache_line_is_stepped_over, clwb_patching_from_many_threads_at_once).
  • clwb_patching_from_many_threads_at_once repeated 20 times: 20 of 20 pass.
  • cargo test -p xcl --lib on the head: 615 passed, 0 failed, 20 ignored.

Not tested

  • A real CLWB fault (needs a pre-Ice Lake Intel CPU); the merge with current main (conflict in eh.rs).

AI use

  • Claude Code (Claude Opus 5.5) ran the commands and wrote this report from the logs; I checked it before posting.

ivall#278)

A CLWB was hot-patched by making its bytes writable, filling them with
0x90 one byte at a time and restoring the protection, with nothing shared
between threads:

- two threads patching on one page could restore each other's protection,
  leaving the page PAGE_EXECUTE_READWRITE or making it read-only while the
  other still wrote;
- another thread could run the half-written bytes (90 0F AE 30 is a nop and
  then xsaveopt [rax]);
- a thread that faulted on the CLWB just before another patched it read
  NOPs, which do not decode, and its fault went on to the title's handlers;
- the instruction cache was not flushed.

Now the patching runs under one lock, which also keeps the set of patched
addresses. Only the first two bytes change, to a short jump over the
instruction (EB, len - 2), written by a single lock cmpxchg so another
thread runs either the whole CLWB or the whole jump. The old protection is
put back and FlushInstructionCache is called. A fault on an address already
patched resumes at the jump. A CLWB whose first two bytes cross a cache line,
where no single store is atomic, is stepped over on each fault instead.

Tests: the jump bytes; three CLWB lengths (one at an odd address) patched,
the page PAGE_EXECUTE_READ afterwards, a late fault resumed, and the code
run; a cache-line crossing stepped over; eight threads faulting on 64 CLWBs
of one page at once while a watcher checks that each CLWB's first two bytes
are only ever the old ones or the jump.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@H0UNDZER0

Copy link
Copy Markdown

Tested on an RTX 5080, release build: pass at the current head dfa332a, 680 passed, 0 failed. This adds a run of the current head to the MSVC run of the earlier head 7d5f5f0 above.

  • Commit dfa332a5a4217d8a90fdeac1f8a049cfd808c699, this PR's head as is (on its base a6f5f7a), release build.
  • NVIDIA GeForce RTX 5080 16 GB, driver 621.24 (32.0.16.2124), 32-lane waves; Ryzen 7 9700X; Windows 11 Pro 24H2 (26100.9711); Rust 1.100.0 MSVC; DXC 1.9.2602.17 (Windows SDK 10.0.26100.0). No XCL_* variables set.
  • cargo build --release --workspace --locked: OK, the same single fetch_update warning as main.
  • cargo test --workspace --release --no-fail-fast --locked -- --test-threads=4, run twice (the second with --show-output): 680 passed, 0 failed, 41 ignored both times. main 2997c9a, which differs from a6f5f7a only in README.md, gives 676 / 0 / 41 on this PC: the difference is the 4 new clwb_* tests, which pass.
  • SKIPPED: the usual 2, gpu_geometry_wave32_prefix_count_over_a_mask and gpu_wave32_program_in_wave64_hardware (no wave64).
  • The 4 tests alone, cargo test --release --locked -p xcl --lib eh::tests::clwb, 3 runs: 4 passed each time, clwb_patching_from_many_threads_at_once included.

Not tested

  • A CPU without CLWB, where a title's CLWB really faults: the new tests drive the handler directly.
  • This PR merged onto a newer main. When this was written that was dd2ae9a; git merge-tree showed no conflict.
  • Debug build, retail titles, scripts/smoke.ps1.

AI use: Claude Code (Claude Opus 5.5, Claude Fable 5.2)

@MesshM

MesshM commented Nov 24, 2026

Copy link
Copy Markdown

Test run of dfa332a5a4217d8a90fdeac1f8a049cfd808c699 on AMD RDNA4. I merged it onto current main 64b3f35 locally (clean merge) and tested that tree.

Tested

  • AMD Radeon RX 9060 XT 16 GB (RDNA4), driver 32.0.32029.2010; Ryzen 7 5700X, 64 GB RAM, Windows 11 Pro build 26200, Rust 1.100.0 stable-x86_64-pc-windows-msvc, debug
  • cargo build --workspace + cargo test --workspace -- --test-threads=4 on the merge: 705 passed, 0 failed, 41 ignored, exit code 0; xcl lib tests 664 passed, 0 failed, 21 ignored
  • 0 SKIPPED; the clwb tests in eh pass, including clwb_patching_from_many_threads_at_once.

Review: Hot-patching is serialized and the patched range's instruction cache is flushed, so a thread that faults on a CLWB while another patches the same site sees either the old bytes or the whole jump. I did not trace every interaction with the CLZERO loop handling (#278, #295).

Not tested: no retail title or regression run (I have no unpacked game), no XCL_SAMPLE_* tests, release build; the PR's head on its old base was not run, only its merge onto main.

Run and review by Claude Code (Claude Opus 5.5) on this machine; the review points were checked against the code.

@bunbeans2-arch

Copy link
Copy Markdown

Test report for dfa332a5a4217d8a90fdeac1f8a049cfd808c699 on an Intel CPU that lacks CLWB (i9-9900K, Coffee Lake), so the instruction raises a real STATUS_ILLEGAL_INSTRUCTION and eh's handler gets a real fault, not a made-up CONTEXT. The other reports here ran on Ryzen CPUs, which run CLWB natively.

Tested

  • Intel Core i9-9900K (CPUID: no CLWB, CLZERO, RDPRU, RDPID, MONITORX, SSE4a), AMD Radeon RX 9070 XT 16 GB (Adrenalin driver 32.0.32015.7029), 32 GB RAM, Windows 11 Pro 23H2 build 22631.6199, Rust 1.100.0 stable-x86_64-pc-windows-msvc, debug.
  • This PR's head as is (base a6f5f7a): cargo build --workspace + cargo test --workspace -- --test-threads=4: 680 passed, 0 failed, 41 ignored, 0 SKIPPED (D3D12 backend on the RX 9070 XT). Control, main f4ce27c: 701 passed, 0 failed, 41 ignored.
  • Real-fault test (a temporary test module appended to eh.rs, not part of this PR; source below). It ran on main f4ce27c and on this PR's head merged onto f4ce27c (clean merge), each built in its own target dir:
    • 8 threads, the same 64 CLWB sites at once: 8 threads call 64 clwb [rcx]; ret functions on one PAGE_EXECUTE_READ page registered as a title module, 4 passes each in their own order, while a watcher thread reads each CLWB's first two bytes. One new process per run, 100 runs each:
      • this PR: 100 of 100 passed; every run: 0 of the 64 sites left as a CLWB (the first site read eb 02 ae 31 after each run), the watcher saw 0 two-byte states other than 66 0f, eb 02 or 90 90, 0 bytes written into the threads' buffers, the page ends PAGE_EXECUTE_READ; 73 to 92 illegal-instruction faults a run.
      • main f4ce27c: 0 of 100 passed. Exit status as Git Bash reports it: 139 in 83 runs, 132 in 16, 3 in 1; cargo's line for the first run of each build named 0xc0000005 STATUS_ACCESS_VIOLATION (one build) and 0xc000001d STATUS_ILLEGAL_INSTRUCTION (the other). XCL's own log printed 47 lines illegal instruction in real_clwb_threads.exe+...: code bytes 90 90 90 90 over the 100 runs: my reading is that a thread faulted on the CLWB and its handler found the bytes already NOPed by another thread, so it passed the fault on (item 4 of Console CPU emulation: ClzeroLoop decoder/semantics, is_writable guards, and CLWB hot-patch race #278).
    • One thread, three forms, each called 3 times: this PR: clwb [rcx] becomes eb 02 ae 31 and clwb [rcx+8] becomes eb 03 ae 71 08 (faults per call 1, 0, 0); a clwb [rcx] whose first two bytes cross a cache line is stepped over each call (1, 1, 1) and left as 66 0f ae 31; the page stays PAGE_EXECUTE_READ. On main all three become NOPs (1, 0, 0) and this part passes too.
    • Control for the buffer check: the bytes of a half-patched CLWB, 90 0f ae 31 (nop; xsaveopt [rcx]), run once, write 7 non-zero bytes into the buffer, so the check can see a torn patch.

Not tested

  • A retail title or a scripts/smoke.ps1 run (no game files were used), XCL_SAMPLE_* tests, a release build.
  • This PR on a newer main than f4ce27c (the real-fault test ran on the merge onto f4ce27c, the suite on the head as is), other Intel generations, an AMD CPU (where CLWB never faults).

AI use

  • Claude Code. The real-fault test, the runs and this report: Claude Fable 5.2, then Claude Opus 5.5 (the session's model was switched partway). All numbers come from the runs above on this machine.
The real-fault test module (appended to the end of crates/xcl/src/eh.rs; run with cargo test -p xcl --lib real_fault_tests -- --nocapture --test-threads=1, then real_d_clwb_faults_from_many_threads alone, one process a run)
// TEMPORARY, local only: appended to crates/xcl/src/eh.rs for a hardware test run. Not part of any
// pull request. It runs the console-only instructions for real, so a CPU without them raises the
// real STATUS_ILLEGAL_INSTRUCTION and XCL's own handler (`cpp_exception_logger`) gets it. The
// tests in `eh::tests` hand the handler a made-up CONTEXT instead.
#[cfg(test)]
mod real_fault_tests {
    use super::*;
    use std::sync::atomic::{AtomicBool, AtomicU16, AtomicUsize, Ordering};
    use std::sync::{Arc, Barrier};
    use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualProtect, VirtualQuery, MEMORY_BASIC_INFORMATION, MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READ, PAGE_READWRITE};

    /// Illegal-instruction exceptions seen by `counting_handler`.
    static UD: AtomicUsize = AtomicUsize::new(0);

    /// mov eax, 7; xor edx, edx: if a half-patched CLWB (`90 0F AE 31`) ran as `nop; xsaveopt [rcx]`,
    /// it would save x87, SSE and AVX state into the buffer at rcx, which a CLWB never writes.
    const PRE: [u8; 7] = [0xB8, 7, 0, 0, 0, 0x31, 0xD2];
    const CLWB_RCX: [u8; 4] = [0x66, 0x0F, 0xAE, 0x31];

    unsafe extern "system" fn counting_handler(info: *mut EXCEPTION_POINTERS) -> i32 {
        unsafe {
            if !info.is_null() && !(*info).ExceptionRecord.is_null() && (*(*info).ExceptionRecord).ExceptionCode as u32 == ILLEGAL_INSTRUCTION {
                UD.fetch_add(1, Ordering::SeqCst);
                return cpp_exception_logger(info);
            }
        }
        0
    }

    fn install() {
        static ONCE: std::sync::Once = std::sync::Once::new();
        ONCE.call_once(|| unsafe {
            use windows_sys::Win32::System::Diagnostics::Debug::{AddVectoredExceptionHandler, SetErrorMode};
            // no crash dialog if a run dies: SEM_FAILCRITICALERRORS | SEM_NOGPFAULTERRORBOX
            SetErrorMode(0x0001 | 0x0002);
            AddVectoredExceptionHandler(1, Some(counting_handler));
        });
    }

    fn serial() -> std::sync::MutexGuard<'static, ()> {
        static M: std::sync::Mutex<()> = std::sync::Mutex::new(());
        M.lock().unwrap_or_else(|e| e.into_inner())
    }

    struct Cpu {
        brand: String,
        clwb: bool,
        clzero: bool,
        rdpru: bool,
        rdpid: bool,
        monitorx: bool,
        sse4a: bool,
        xsaveopt: bool,
    }

    #[allow(unused_unsafe)]
    fn cpu() -> Cpu {
        use std::arch::x86_64::{__cpuid, __cpuid_count};
        unsafe {
            let max_ext = __cpuid(0x8000_0000).eax;
            let l7 = __cpuid_count(7, 0);
            let e1 = if max_ext >= 0x8000_0001 { __cpuid(0x8000_0001).ecx } else { 0 };
            let e8 = if max_ext >= 0x8000_0008 { __cpuid(0x8000_0008).ebx } else { 0 };
            let mut brand = Vec::new();
            if max_ext >= 0x8000_0004 {
                for leaf in 0x8000_0002u32..=0x8000_0004 {
                    let r = __cpuid(leaf);
                    for v in [r.eax, r.ebx, r.ecx, r.edx] {
                        brand.extend_from_slice(&v.to_le_bytes());
                    }
                }
            }
            Cpu {
                brand: String::from_utf8_lossy(&brand).trim_matches(|c: char| c == '\0' || c == ' ').to_string(),
                clwb: ((l7.ebx >> 24) & 1) == 1,
                clzero: (e8 & 1) == 1,
                rdpru: ((e8 >> 4) & 1) == 1,
                rdpid: ((l7.ecx >> 22) & 1) == 1,
                monitorx: ((e1 >> 29) & 1) == 1,
                sse4a: ((e1 >> 6) & 1) == 1,
                xsaveopt: (__cpuid_count(0xD, 1).eax & 1) == 1,
            }
        }
    }

    /// 64 KiB of code registered as a title module, filled while writable, then PAGE_EXECUTE_READ.
    fn code_page(name: &str, fill: impl FnOnce(&mut [u8])) -> usize {
        unsafe {
            let code = VirtualAlloc(std::ptr::null(), 0x1_0000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) as usize;
            assert_ne!(code, 0);
            fill(std::slice::from_raw_parts_mut(code as *mut u8, 0x1_0000));
            let mut old = 0;
            assert_ne!(VirtualProtect(code as *const _, 0x1_0000, PAGE_EXECUTE_READ, &mut old), 0);
            modules::register_mapped(Arc::new(modules::MappedModule {
                name: name.into(), path: name.into(), base: code, size: 0x1_0000, entry_rva: 0, is_dll: false,
                exports: Default::default(), tls_callbacks: Mutex::new(Vec::new()), no_thread_calls: AtomicBool::new(false),
                initialized: AtomicBool::new(true), stack_reserve: 0,
            }));
            code
        }
    }

    /// Zeroed read-write memory, 64 KiB aligned.
    fn rw(len: usize) -> usize {
        let p = unsafe { VirtualAlloc(std::ptr::null(), len, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE) } as usize;
        assert_ne!(p, 0);
        p
    }

    fn protection(va: usize) -> u32 {
        let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
        assert_ne!(unsafe { VirtualQuery(va as *const _, &mut m, std::mem::size_of_val(&m)) }, 0);
        m.Protect
    }

    fn bytes(at: usize, n: usize) -> Vec<u8> {
        unsafe { std::slice::from_raw_parts(at as *const u8, n) }.to_vec()
    }

    fn nonzero(at: usize, n: usize) -> usize {
        bytes(at, n).iter().filter(|&&b| b != 0).count()
    }

    /// Illegal-instruction exceptions raised while `f` ran.
    fn faults(f: impl FnOnce()) -> usize {
        let before = UD.load(Ordering::SeqCst);
        f();
        UD.load(Ordering::SeqCst) - before
    }

    fn report(insn: &str, native: bool, n: usize, ok: bool, bad: &mut Vec<String>) {
        eprintln!("REALFAULT insn={insn} cpu_has_it={native} faults={n} result_ok={ok}");
        if !ok || (native && n != 0) || (!native && n == 0) {
            bad.push(format!("{insn}: cpu_has_it {native} faults {n} result_ok {ok}"));
        }
    }

    #[test]
    fn real_a_cpu_report() {
        let c = cpu();
        eprintln!(
            "REALFAULT cpu brand=\"{}\" clwb={} clzero={} rdpru={} rdpid={} monitorx={} sse4a={} xsaveopt={}",
            c.brand, c.clwb, c.clzero, c.rdpru, c.rdpid, c.monitorx, c.sse4a, c.xsaveopt
        );
    }

    /// Each emulated instruction run once for real.
    #[test]
    fn real_b_single_instructions() {
        let _g = serial();
        install();
        let c = cpu();
        let mut bad = Vec::new();
        let code = code_page("real_single.exe", |m| {
            m.fill(0xCC);
            let mut put = |at: usize, b: &[u8]| m[at..at + b.len()].copy_from_slice(b);
            // mov rax, rcx; clzero; ret
            put(0x000, &[0x48, 0x89, 0xC8, 0x0F, 0x01, 0xFC, 0xC3]);
            // mov rax, rcx; clzero; add rax, 0x40; cmp rax, rdx; jb -12; ret
            put(0x040, &[0x48, 0x89, 0xC8, 0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4, 0xC3]);
            // xor ecx, ecx; rdpru; shl rdx, 32; or rax, rdx; ret
            put(0x080, &[0x31, 0xC9, 0x0F, 0x01, 0xFD, 0x48, 0xC1, 0xE2, 0x20, 0x48, 0x09, 0xD0, 0xC3]);
            // rdpid rax; ret
            put(0x0C0, &[0xF3, 0x0F, 0xC7, 0xF8, 0xC3]);
            // mov rax, rcx; xor ecx, ecx; xor edx, edx; monitorx; ret
            put(0x100, &[0x48, 0x89, 0xC8, 0x31, 0xC9, 0x31, 0xD2, 0x0F, 0x01, 0xFA, 0xC3]);
            // push rbx; xor eax, eax; mov ecx, 2 (timer on); mov ebx, 10000; mwaitx; pop rbx; ret
            put(0x140, &[0x53, 0x31, 0xC0, 0xB9, 2, 0, 0, 0, 0xBB, 0x10, 0x27, 0, 0, 0x0F, 0x01, 0xFB, 0x5B, 0xC3]);
            // extrq xmm0, 8, 8; ret
            put(0x180, &[0x66, 0x0F, 0x78, 0xC0, 0x08, 0x08, 0xC3]);
            // insertq xmm0, xmm1, 8, 8; ret
            put(0x1C0, &[0xF2, 0x0F, 0x78, 0xC1, 0x08, 0x08, 0xC3]);
        });

        let clzero: extern "system" fn(usize) = unsafe { std::mem::transmute(code) };
        let buf = rw(0x1000);
        unsafe { std::ptr::write_bytes(buf as *mut u8, 0xA5, 0x1000) };
        let n = faults(|| clzero(buf + 0x47));
        let b = bytes(buf, 0x100);
        let ok = b[0x40..0x80].iter().all(|&x| x == 0) && b[..0x40].iter().chain(&b[0x80..]).all(|&x| x == 0xA5);
        report("clzero", c.clzero, n, ok, &mut bad);

        let clzero_loop: extern "system" fn(usize, usize) = unsafe { std::mem::transmute(code + 0x040) };
        let buf = rw(0x1000);
        unsafe { std::ptr::write_bytes(buf as *mut u8, 0xA5, 0x1000) };
        let n = faults(|| clzero_loop(buf, buf + 0x400));
        let b = bytes(buf, 0x1000);
        let ok = b[..0x400].iter().all(|&x| x == 0) && b[0x400..].iter().all(|&x| x == 0xA5);
        report("clzero_loop", c.clzero, n, ok, &mut bad);

        let rdpru: extern "system" fn() -> u64 = unsafe { std::mem::transmute(code + 0x080) };
        let mut v = 0;
        let n = faults(|| v = rdpru());
        report("rdpru", c.rdpru, n, c.rdpru || v != 0, &mut bad);

        let rdpid: extern "system" fn() -> u64 = unsafe { std::mem::transmute(code + 0x0C0) };
        let mut v = u64::MAX;
        let n = faults(|| v = rdpid());
        report("rdpid", c.rdpid, n, v < 4096, &mut bad);

        let monitorx: extern "system" fn(usize) = unsafe { std::mem::transmute(code + 0x100) };
        let n = faults(|| monitorx(buf));
        report("monitorx", c.monitorx, n, true, &mut bad);

        let mwaitx: extern "system" fn() = unsafe { std::mem::transmute(code + 0x140) };
        let n = faults(|| mwaitx());
        report("mwaitx", c.monitorx, n, true, &mut bad);

        let (a, s) = (0x4022_3344_5566_7788u64, 0x4011_0000_0000_00ABu64);
        let extrq: extern "system" fn(f64) -> f64 = unsafe { std::mem::transmute(code + 0x180) };
        let mut r = 0;
        let n = faults(|| r = extrq(f64::from_bits(a)).to_bits());
        report("extrq", c.sse4a, n, r == crate::insn::extrq(a, 8, 8), &mut bad);

        let insertq: extern "system" fn(f64, f64) -> f64 = unsafe { std::mem::transmute(code + 0x1C0) };
        let mut r = 0;
        let n = faults(|| r = insertq(f64::from_bits(a), f64::from_bits(s)).to_bits());
        report("insertq", c.sse4a, n, r == crate::insn::insertq(a, s, 8, 8), &mut bad);

        assert!(bad.is_empty(), "{bad:?}");
    }

    /// CLWBs called three times each on one thread: clwb [rcx], clwb [rcx+8], and a clwb [rcx]
    /// whose first two bytes cross a cache line.
    #[test]
    fn real_c_clwb_on_one_thread() {
        let _g = serial();
        install();
        let c = cpu();
        let mut bad = Vec::new();
        let sites: [(usize, &[u8]); 3] = [(0x100, &CLWB_RCX), (0x140, &[0x66, 0x0F, 0xAE, 0x71, 0x08]), (0x238, &CLWB_RCX)];
        let code = code_page("real_clwb.exe", |m| {
            m.fill(0xCC);
            for (at, b) in sites {
                m[at..at + 7].copy_from_slice(&PRE);
                m[at + 7..at + 7 + b.len()].copy_from_slice(b);
                m[at + 7 + b.len()] = 0xC3;
            }
        });
        let buf = rw(0x1_0000);
        for (at, b) in sites {
            let f: extern "system" fn(usize) = unsafe { std::mem::transmute(code + at) };
            let per_call: Vec<usize> = (0..3).map(|_| faults(|| f(buf))).collect();
            let rip = code + at + 7;
            let (now, prot, dirty) = (bytes(rip, b.len()), protection(rip), nonzero(buf, 0x1_0000));
            eprintln!(
                "REALFAULT clwb offset_in_cache_line={} len={} faults_per_call={:?} bytes_before=\"{}\" bytes_after=\"{}\" protection={:#x} buffer_nonzero={}",
                rip & 63, b.len(), per_call, crate::insn::hex(b), crate::insn::hex(&now), prot, dirty
            );
            if !c.clwb && per_call[0] == 0 {
                bad.push(format!("{at:#x}: no fault on a CPU without CLWB"));
            }
            if c.clwb && per_call.iter().sum::<usize>() != 0 {
                bad.push(format!("{at:#x}: faults on a CPU with CLWB"));
            }
            if prot != PAGE_EXECUTE_READ {
                bad.push(format!("{at:#x}: protection {prot:#x}"));
            }
            if dirty != 0 {
                bad.push(format!("{at:#x}: {dirty} buffer bytes written"));
            }
        }
        assert!(bad.is_empty(), "{bad:?}");
    }

    /// Eight threads call the same 64 CLWB functions of one page at once, each in its own order,
    /// four passes, while another thread watches each CLWB's first two bytes.
    #[test]
    fn real_d_clwb_faults_from_many_threads() {
        let _g = serial();
        install();
        let c = cpu();
        let mut bad = Vec::new();
        const THREADS: usize = 8;
        const PASSES: usize = 4;
        // function starts at odd addresses, so each CLWB (7 bytes in) is at an even one
        let starts: Vec<usize> = (0..64).map(|k| k * 0x20 + 2 * (k % 4) + 1).collect();
        let code = code_page("real_clwb_threads.exe", |m| {
            m.fill(0xCC);
            for &at in &starts {
                m[at..at + 7].copy_from_slice(&PRE);
                m[at + 7..at + 11].copy_from_slice(&CLWB_RCX);
                m[at + 11] = 0xC3;
            }
        });
        let fns: Arc<Vec<usize>> = Arc::new(starts.iter().map(|&at| code + at).collect());
        let whole = [u16::from_le_bytes([0x66, 0x0F]), u16::from_le_bytes([0xEB, 0x02]), u16::from_le_bytes([0x90, 0x90])];
        let start = Arc::new(Barrier::new(THREADS + 2));
        let done = Arc::new(AtomicBool::new(false));
        let before = UD.load(Ordering::SeqCst);
        let watcher = {
            let (fns, start, done) = (fns.clone(), start.clone(), done.clone());
            std::thread::spawn(move || {
                start.wait();
                let (mut odd, mut first_odd) = (0usize, 0u16);
                while !done.load(Ordering::Acquire) {
                    for &f in fns.iter() {
                        let v = unsafe { &*((f + 7) as *const AtomicU16) }.load(Ordering::Relaxed);
                        if !whole.contains(&v) {
                            if odd == 0 {
                                first_odd = v;
                            }
                            odd += 1;
                        }
                    }
                }
                (odd, first_odd)
            })
        };
        let workers: Vec<_> = (0..THREADS)
            .map(|t| {
                let (fns, start) = (fns.clone(), start.clone());
                std::thread::spawn(move || {
                    let buf = rw(0x1_0000);
                    let order: Vec<usize> = (0..fns.len()).map(|i| (i * 7 + t * 13) % fns.len()).collect();
                    start.wait();
                    for _ in 0..PASSES {
                        for &i in &order {
                            let f: extern "system" fn(usize) = unsafe { std::mem::transmute(fns[i]) };
                            f(buf);
                        }
                    }
                    nonzero(buf, 0x1_0000)
                })
            })
            .collect();
        start.wait();
        let dirty: usize = workers.into_iter().map(|w| w.join().expect("a worker")).sum();
        done.store(true, Ordering::Release);
        let (odd, first_odd) = watcher.join().expect("the watcher");
        let n = UD.load(Ordering::SeqCst) - before;
        let unpatched = fns.iter().filter(|&&f| bytes(f + 7, 2) == [0x66, 0x0F]).count();
        let prot = protection(code);
        eprintln!(
            "REALFAULT clwb_threads threads={THREADS} sites={} passes={PASSES} faults={n} unpatched_sites={unpatched} odd_two_byte_states={odd} first_odd={first_odd:#06x} buffers_nonzero_bytes={dirty} protection={prot:#x} first_site_bytes=\"{}\"",
            fns.len(), crate::insn::hex(&bytes(fns[0] + 7, 4))
        );
        if c.clwb {
            if n != 0 {
                bad.push(format!("{n} faults on a CPU with CLWB"));
            }
        } else {
            if n < fns.len() {
                bad.push(format!("{n} faults for {} sites", fns.len()));
            }
            if unpatched != 0 {
                bad.push(format!("{unpatched} sites still a CLWB"));
            }
        }
        if odd != 0 {
            bad.push(format!("{odd} two-byte states that are neither the CLWB nor a whole patch, first {first_odd:#06x}"));
        }
        if dirty != 0 {
            bad.push(format!("{dirty} buffer bytes written"));
        }
        if prot != PAGE_EXECUTE_READ {
            bad.push(format!("the page ends with protection {prot:#x}"));
        }
        assert!(bad.is_empty(), "{bad:?}");
    }

    /// The known positive for the buffer check: the bytes a half-patched CLWB would be
    /// (`90 0F AE 31`: nop; xsaveopt [rcx]) do write into the buffer.
    #[test]
    fn real_e_torn_clwb_detector_control() {
        let c = cpu();
        if !c.xsaveopt {
            eprintln!("REALFAULT control NOT RUN (no xsaveopt)");
            return;
        }
        let code = code_page("real_control.exe", |m| {
            m.fill(0xCC);
            m[..7].copy_from_slice(&PRE);
            m[7..12].copy_from_slice(&[0x90, 0x0F, 0xAE, 0x31, 0xC3]);
        });
        let buf = rw(0x1_0000);
        let f: extern "system" fn(usize) = unsafe { std::mem::transmute(code) };
        f(buf);
        let n = nonzero(buf, 0x1_0000);
        eprintln!("REALFAULT control torn_clwb_bytes=\"90 0f ae 31\" buffer_nonzero={n}");
        assert!(n > 0, "the buffer check would not see a half-patched CLWB");
    }
}

…CLWB

Guard the late-fault resume path with code.first() == Some(&0xEB) so a
stale CLWB_PATCHES entry after DLL unload and address reuse cannot spin
on a genuine #UD at the same RIP. Add a regression check in
clwb_is_patched_into_a_jump_and_the_page_keeps_its_protection and fix a
minor offset comment in clwb_patching_from_many_threads_at_once.

Co-Authored-By: Gemini 4 Neon <noreply@google.com>
@TG0000

TG0000 commented Nov 24, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @mastrr9 for the hardening note — pushed $sha\ checking \code.first() == Some(&0xEB) && clwb_patched(rip)\ so a stale \CLWB_PATCHES\ entry after a DLL unload / address reuse cannot spin on a genuine #UD, with a regression assertion in \clwb_is_patched_into_a_jump_and_the_page_keeps_its_protection\ (and fixed the offset comment nit).

Verified \cargo test -p xcl --lib eh::tests::clwb -- --test-threads=1: 4 passed, 0 failed.

Also huge thanks to @bunbeans2-arch for the real-fault i9-9900K verification (100/100), and @MesshM / @H0UNDZER0 / @nullmarsh for the independent MSVC + AMD/NVIDIA runs!

(Note: \scripts/smoke.ps1\ will need a quick refresh on $sha\ to update the \PR description\ check.)

(AI-assisted)

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants