Skip to content

Loader: clzero loops in one exception; rdpru (#34 rebased, with a fix) - #214

Merged
Marvisak merged 3 commits into
Marvisak:mainfrom
Makto94:fix/clzero-loops
Nov 25, 2026
Merged

Marvisak merged 3 commits into
Marvisak:mainfrom
Makto94:fix/clzero-loops

Conversation

@Makto94

@Makto94 Makto94 commented Nov 24, 2026 •

Copy link
Copy Markdown
Contributor

This is #34 by @ka1qux rebased over #45, with a fix and tests added. #34 conflicts with main since #45 added the same flag and register helpers for clwb loops; the duplicates are merged into gpr / cmp_flags / CMP_FLAGS.

From #34

  • clzero: the two loops compilers build around it are done whole in one exception, leaving registers and flags as the last pass would. ka1qux measured one 28 KiB clear at 448 exceptions / 0.40 ms on main vs 1 exception / 4 µs with this (i5-13600KF, see Loader: clzero loops in one exception; rdpru #34).
  • rdpru: the time-stamp counter for MPERF and APERF, 0 for other counters.

Added here

  • Loop 1 rejects cmp rax, rax. It was taken for the loop and left ZF=0 where the CPU leaves ZF=1. Now it is one line, as with any other neighbours.
  • Tests through the emulation on any CPU. On an AMD host the native tests in Loader: clzero loops in one exception; rdpru #34 never enter the handler. The new tests give the loop bytes to emulate_amd_only with a synthetic context: both loop shapes, the rax-rax and wrong-neighbour fallbacks, and rdpru with flags all set and all clear.

On the #34 review (rdpru and CF)

The review asked for rdpru to set CF on success and clear the other status flags. Measured natively in user mode on a Ryzen 7 5800X3D (Zen 3), rdpru changes no flags, from starts of 0x202, 0x8d5 and 0xad7, for ecx 0, 1, 2 and 0x40 (counts for 0 and 1, zero for 2 and 0x40). So the emulation leaves the flags alone, and a test pins that. This is one CPU, not the console's Zen 2, and I did not check the AMD manual's RDPRU entry.

Testing

  • cargo test -p victory-loader on Windows 11 with the pinned 1.98.1 toolchain: 22 passed, 0 failed; clippy clean.
  • An independent adversarial pass ran the real loop bytes natively on the Zen 3 and through the emulation, then compared registers, full EFLAGS, Rip and the zeroed lines: 1,008 cases for loop 1 and 14,112 for loop 2 (r8–r15 included, limits reached on entry or below the start, unaligned starts), plus wrong neighbours and code at page edges between no-access pages. All pass on this version; it found the cmp rax, rax case above, whose test fails before the fix.
  • Not tested: the real handler on an Intel CPU, the title itself, wrap-around near u64::MAX, rsp as an operand.

🤖 Generated with Claude Code

Update: main merged in (ffe310e) so CI runs; the patch itself is unchanged.

Update: three tests added for the loop edge cases (limit on a line boundary, r9-r15 with REX.R/REX.B, rax as the limit); the handler is unchanged.

Based on Marvisak#34 by ka1qux (commit faa0a9a), rebased over Marvisak#45, which added the
same flag and register helpers for clwb loops; the duplicates are merged
into gpr/cmp_flags/CMP_FLAGS.

clzero: the two loops compilers build around it are done whole in one
exception, leaving registers and flags as the last pass would. Anything else
around it is one line and the next instruction.

rdpru: returns the time-stamp counter for MPERF and APERF, 0 for other
counters, and leaves the flags as they are: a Ryzen 7 5800X3D running it
natively in user mode changes none, for known counters or not.

Added over Marvisak#34:
- loop 1 rejects cmp rax, rax (it fell into the loop and left wrong flags);
- tests that go through the emulation on any CPU (both loop shapes, the
  rax-rax and wrong-neighbour fallbacks, rdpru with both flag states), since
  on an AMD host the native tests never enter the handler.
@SkippySteve

Copy link
Copy Markdown

Ran cargo test -p victory-loader for x86_64-pc-windows-msvc under Wine on Linux to compare this PR with main.

Setup: Arch-based Linux, toolchain 1.98.1 (pinned), built with cargo xwin test, tests run by UMU-Proton 11.0 (wine-11.0) in a new prefix.

Host CPU: AMD Ryzen 5 5600 (Zen 3). clzero and rdpru are both in /proc/cpuinfo, so the native clzero_loops_end_like_their_last_pass test runs the instructions directly and never reaches the handler. That makes this a second Zen 3 result, not the Intel check the PR lists as untested. The emulated_* tests feed the bytes to emulate_amd_only directly, so they are a real check of the emulation on any CPU.

main (d2a4bae) PR head (9de712f)
lib unit tests 18 passed, 0 failed 22 passed, 0 failed
tests/load_probe.rs 1 passed, 1 failed 1 passed, 1 failed

The 4 new tests pass under Wine: compare_sets_flags_like_the_cpu, clzero_loops_end_like_their_last_pass, emulated_clzero_loops_end_like_their_last_pass and emulated_rdpru_reads_known_counters_and_keeps_flags. All 18 existing tests also pass.

load_probe::loads_binds_and_calls_probe fails the same way on main and on the PR: it spawns host cargo from inside the Wine process (running cargo: ... Invalid handle, then a mixed \..\..\ fixture path). That is a problem with how this setup runs the test, not with the PR.

Other checks:

Not tested: an Intel or non-AMD host where the handler really runs, and the title.

@wwwwwwww3333333

Copy link
Copy Markdown

Intel result for this PR's own code, through the real handler. i5-13400F (Raptor Lake, no clzero: CPUID 8000_0008 EBX[0] = 0), Windows 11, Rust 1.98.1 MSVC, this PR (9de712f) merged onto d2a4bae:

  • cargo test -p victory-loader --lib -- --test-threads=1: 22 passed, 0 failed. That includes clzero_loops_end_like_their_last_pass and clzero_zeroes_its_line_on_any_cpu, which on this CPU fault for real and go through emulate_amd_only, so they cover the handler path the description lists as untested on Intel.

  • Timing, with a local ignored test that is not part of this PR (below). It runs the title's loop from Crash on Intel CPU (i5-14400F): 0xc000001d (STATUS_ILLEGAL_INSTRUCTION) at +0x4e8aa70 #7 (0f 01 fc 48 83 c0 40 4c 39 d0 72 f4) over 16 MiB, release build, best of 3, and checks every byte is zero afterwards:

    • d2a4bae: 484.6 ms (33 MiB/s; 262,144 faults, about 1.85 µs each)
    • this PR: 1.38 ms (11,620 MiB/s; one fault)

    That is about 350× on this CPU, consistent with ka1qux's 0.40 ms → 4 µs for 28 KiB on an i5-13600KF.

Not runtime-tested with game files.

The timing test (in crash.rs's mod tests; run with cargo test --release -p victory-loader --lib clzero_loop_speed -- --ignored --nocapture)
#[test]
#[ignore = "benchmark"]
fn clzero_loop_speed() {
    report_crashes();
    const BYTES: u64 = 16 << 20;
    let native = std::arch::x86_64::__cpuid(0x8000_0008).ebx & 1 == 1;
    let mut buf = vec![0xffu8; BYTES as usize + 64];
    let start = (buf.as_mut_ptr() as u64 + 63) & !63;
    let mut best = std::time::Duration::MAX;
    for _ in 0..3 {
        // SAFETY: `buf` covers the lines.
        unsafe { std::ptr::write_bytes(start as *mut u8, 0xff, BYTES as usize) };
        let began = std::time::Instant::now();
        // SAFETY: zeroes BYTES from `start`, inside `buf`.
        unsafe {
            std::arch::asm!(
                ".byte 0x0f, 0x01, 0xfc, 0x48, 0x83, 0xc0, 0x40, 0x4c, 0x39, 0xd0, 0x72, 0xf4",
                inout("rax") start => _, in("r10") start + BYTES)
        };
        best = best.min(began.elapsed());
        // SAFETY: inside `buf`.
        let lines = unsafe { std::slice::from_raw_parts(start as *const u8, BYTES as usize) };
        assert!(lines.iter().all(|&b| b == 0), "not every line was zeroed");
    }
    let mib = (BYTES >> 20) as f64;
    eprintln!(
        "clzero loop: {mib} MiB in {:.3} ms (best of 3), {:.0} MiB/s; native clzero: {native}",
        best.as_secs_f64() * 1e3,
        mib / best.as_secs_f64()
    );
}

AI-assisted (Claude wrote the timing test and did the analysis; I ran it on my machine).

yourmomsbasement pushed a commit to yourmomsbasement/VIctory_Dev that referenced this pull request Nov 24, 2026
Merges Marvisak#188 Marvisak#213 Marvisak#214 Marvisak#219 Marvisak#221 Marvisak#311 Marvisak#324 Marvisak#363 Marvisak#406 Marvisak#454 Marvisak#529 Marvisak#560 Marvisak#708 Marvisak#937
Marvisak#941 Marvisak#963 Marvisak#1111 Marvisak#1159 Marvisak#1304 Marvisak#1306 onto main (ffe310e), each head unchanged,
no conflicts.

One change of mine: the long-format import descriptor code Marvisak#963 adds nests
`if size == 0` in an `if let`, which clippy::collapsible_if rejects under
-D warnings; it is now one `if let ... && size == 0` (clippy --fix, no
change of behaviour).

cargo clippy --workspace --all-targets --locked -- -D warnings, with and
without --all-features, is clean and cargo test --workspace --locked passes
(388 passed, 7 ignored; main has 342 passed, 6 ignored).

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
github-actions Bot added a commit to KevinPratap/VIctory that referenced this pull request Nov 24, 2026
github-actions Bot added a commit to KevinPratap/VIctory that referenced this pull request Nov 24, 2026
github-actions Bot added a commit to KevinPratap/VIctory that referenced this pull request Nov 24, 2026
@Marvisak
Marvisak merged commit 15de8f9 into Marvisak:main Nov 25, 2026
1 check passed
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.

4 participants