Merge branch 'night/cpu' into local/next

This commit is contained in:
local committed 2026-11-25 07:21:55 -06:00
commit ba837eeff9
9 files changed
+325 -41

No files matched your search

+98
View File
@@ -0,0 +1,98 @@
//! Which processors our own threads run on, where a processor has two kinds
//! of cores. `cpu_sets` and `keep_on_fast_cores` are fxceless/victory-fork's
//! (`framelog.rs`, commit 0b0074e0, GPL-3.0-or-later, as this).
/// The system's processor sets of group 0: each one's id and its efficiency
/// class (higher is faster).
fn cpu_sets() -> Vec<(u32, u8)> {
use windows_sys::Win32::System::SystemInformation::{GetSystemCpuSetInformation, SYSTEM_CPU_SET_INFORMATION};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
let mut bytes = 0u32;
// SAFETY: a size query, then the call into a buffer of that size.
unsafe { GetSystemCpuSetInformation(std::ptr::null_mut(), 0, &mut bytes, GetCurrentProcess(), 0) };
let mut buffer = vec![0u64; (bytes as usize).div_ceil(8).max(1)];
// SAFETY: as above; the buffer holds `bytes` bytes, aligned for the records.
let ok = unsafe { GetSystemCpuSetInformation(buffer.as_mut_ptr().cast(), bytes, &mut bytes, GetCurrentProcess(), 0) };
let mut sets = Vec::new();
let mut at = 0usize;
while ok != 0 && at + size_of::<SYSTEM_CPU_SET_INFORMATION>() <= bytes as usize {
// SAFETY: a record inside the buffer; each says its own size.
let info = unsafe { &*(buffer.as_ptr().cast::<u8>().add(at).cast::<SYSTEM_CPU_SET_INFORMATION>()) };
if info.Size == 0 {
break;
}
// SAFETY: the record's type is CpuSet (the only one there is).
let set = unsafe { &info.Anonymous.CpuSet };
if set.Group == 0 {
sets.push((set.Id, set.EfficiencyClass));
}
at += info.Size as usize;
}
sets
}
/// The sets of the fastest class, if there are slower ones too.
fn fast_of(sets: &[(u32, u8)]) -> Vec<u32> {
let best = sets.iter().map(|c| c.1).max().unwrap_or(0);
let fast: Vec<u32> = sets.iter().filter(|c| c.1 == best).map(|c| c.0).collect();
if fast.len() == sets.len() { Vec::new() } else { fast }
}
/// `VICTORY_FAST_CORES`: 0: no thread asks; 1: the threads a frame waits for
/// one by one; 2 (the default): the threads they share their work with too.
fn stage() -> u32 {
static STAGE: std::sync::OnceLock<u32> = std::sync::OnceLock::new();
*STAGE.get_or_init(|| std::env::var("VICTORY_FAST_CORES").ok().and_then(|v| v.trim().parse().ok()).unwrap_or(2))
}
/// Asks the system to run the calling thread, which a frame waits for, on
/// the fast cores only, where the processor has two kinds. That fork's submit
/// thread was found on a slow one in 1,529 looks of 24,021. (A selection of
/// processors is a preference the scheduler keeps unless nothing of it is
/// free.) The title's threads are not asked for.
pub(crate) fn keep_on_fast_cores(what: &str) {
ask(what, 1);
}
/// [`keep_on_fast_cores`] for one of the threads a submission's preparing or
/// a landing shares its work with.
pub(crate) fn keep_helper_on_fast_cores(what: &str) {
ask(what, 2);
}
fn ask(what: &str, from: u32) {
use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadSelectedCpuSets};
if stage() < from {
return;
}
static FAST: std::sync::OnceLock<(Vec<u32>, usize)> = std::sync::OnceLock::new();
let (fast, of) = FAST.get_or_init(|| {
let sets = cpu_sets();
(fast_of(&sets), sets.len())
});
// All alike (or nothing known): nothing to ask for.
if fast.is_empty() {
return;
}
// SAFETY: our own thread and a list of the system's own set ids.
let ok = unsafe { SetThreadSelectedCpuSets(GetCurrentThread(), fast.as_ptr(), fast.len() as u32) };
if ok == 0 {
tracing::warn!(what, error = %std::io::Error::last_os_error(), "the thread could not be kept on the fast cores");
} else {
tracing::info!(what, fast = fast.len(), of, "the thread is kept on the fast cores (VICTORY_FAST_CORES=0: not)");
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_fast_cores_are_those_of_the_best_class_if_there_is_a_worse_one() {
assert_eq!(fast_of(&[(256, 1), (257, 1), (258, 0)]), [256, 257]);
assert!(fast_of(&[(256, 0), (257, 0)]).is_empty());
assert!(fast_of(&[]).is_empty());
assert!(!cpu_sets().is_empty());
std::thread::spawn(|| keep_on_fast_cores("test")).join().unwrap();
}
}
+1
View File
@@ -216,6 +216,7 @@ pub(crate) fn begin_sync_heaps() -> SyncedHeaps {
static THREAD: std::sync::atomic::AtomicBool = std::sync::atomic::AtomicBool::new(false);
STARTED.call_once(|| {
let made = std::thread::Builder::new().name("victory-heap-sync".into()).spawn(|| {
crate::cores::keep_on_fast_cores("victory-heap-sync");
let rounds = || SYNC_ROUNDS.0.lock().unwrap_or_else(|e| e.into_inner());
/// A round is over, however it ends.
struct Over;
+2
View File
@@ -2869,6 +2869,7 @@ fn land() {
/// value while the submitting thread waits for that thread would never
/// see it.
fn late_helper() {
crate::cores::keep_on_fast_cores("victory-late-wait");
let Some(host) = host() else {
return;
};
@@ -2999,6 +3000,7 @@ struct RelayFetch {
/// anything a caller of [`Host::settle`] may hold: resetting the landed
/// lists and looking at what queues hold are left to [`late_helper`].
fn relay_worker() {
crate::cores::keep_on_fast_cores("victory-relay");
let Some(host) = host() else {
return;
};
+4 -1
View File
@@ -63,7 +63,10 @@ pub(crate) fn begin(work: impl FnOnce() -> Vec<Refresh> + Send + 'static) -> std
let (send, jobs) = std::sync::mpsc::channel::<Job>();
std::thread::Builder::new()
.name("victory-aside".into())
.spawn(move || jobs.into_iter().for_each(|job| job()))
.spawn(move || {
crate::cores::keep_on_fast_cores("victory-aside");
jobs.into_iter().for_each(|job| job())
})
.ok()
.map(|_| Mutex::new(send))
});
+4 -1
View File
@@ -237,7 +237,10 @@ impl Pool {
}));
for i in 1..threads {
// (A helper that is not there is only missed.)
let _ = std::thread::Builder::new().name(format!("victory-land-{i}")).spawn(move || pool.help());
let _ = std::thread::Builder::new().name(format!("victory-land-{i}")).spawn(move || {
crate::cores::keep_helper_on_fast_cores("victory-land");
pool.help()
});
}
pool
}
+2
View File
@@ -20,6 +20,8 @@ mod capture;
pub mod console;
#[cfg(all(windows, feature = "diagnostics"))]
mod copystat;
#[cfg(windows)]
mod cores;
pub mod descriptor;
pub mod device;
#[cfg(windows)]
+1
View File
@@ -439,6 +439,7 @@ pub(super) fn on() -> bool {
use windows_sys::Win32::System::Threading::{GetCurrentThread, SetThreadPriority, THREAD_PRIORITY_ABOVE_NORMAL};
// SAFETY: this thread's own priority.
unsafe { SetThreadPriority(GetCurrentThread(), THREAD_PRIORITY_ABOVE_NORMAL) };
crate::cores::keep_on_fast_cores("victory-submit");
OURS.set(true);
let ended = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| LANE.serve()));
if ended.is_err() {
+1
View File
@@ -1453,6 +1453,7 @@ fn workers() -> &'static Workers {
STARTED.call_once(|| {
for i in 0..wide_threads() {
let _ = std::thread::Builder::new().name(format!("victory-wide-{i}")).spawn(move || {
crate::cores::keep_helper_on_fast_cores("victory-wide");
let workers = WORKERS.get().expect("made above");
loop {
let job = {
+212 -39
View File
@@ -66,52 +66,157 @@ fn wait_patch(what: ConsoleOnly) -> Option<[u8; 3]> {
}
}
/// The aligned 8 bytes `word` around address `at` with the 3 bytes at `at` replaced; `None`
/// where they do not all lie in those 8.
fn with_patch(word: u64, at: usize, patch: [u8; 3]) -> Option<u64> {
let offset = at & 7;
if offset + patch.len() > 8 {
/// Whether a `clzero` loop ([`ConsoleOnly::ClzeroLoop`]) is replaced the first time it faults
/// by a jump to the same loop with plain stores ([`clzero_stub`]). Run cpu-5 (the dorm): 25,000
/// exceptions a second, 2,100 a frame, at five such loops of one function of the title, for
/// some kilobytes each; ten times what the wait instructions raised. On by default;
/// `VICTORY_PATCH_CLZERO=0` emulates each time, as before.
fn patches_clzero() -> bool {
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
*ON.get_or_init(|| std::env::var_os("VICTORY_PATCH_CLZERO").is_none_or(|v| v != "0"))
}
/// `jmp rel32` at `at` to `to`, if it reaches.
fn jump(at: usize, to: usize) -> Option<[u8; 5]> {
let rel = i32::try_from(to as i64 - (at as i64 + 5)).ok()?;
let [a, b, c, d] = rel.to_le_bytes();
Some([0xe9, a, b, c, d])
}
/// The `clzero` loop of 12 bytes at `at` with plain stores, as code at `stub`: every register
/// and the flags come out as the loop leaves them. `cmp` is its `cmp rax, reg` (3 bytes, the
/// register not `rax`), `None` for another form. (The scratch register is saved on the stack
/// and back before the compare, whose register it may be.)
fn clzero_stub(at: usize, stub: usize, cmp: [u8; 3]) -> Option<Vec<u8>> {
if !matches!(cmp[0], 0x48 | 0x4c) || cmp[1] != 0x39 || cmp[2] & 0xc7 != 0xc0 || (cmp[0] == 0x48 && cmp[2] == 0xc0) {
return None;
}
let mut code = vec![
0x51, // push rcx
0x48, 0x89, 0xc1, // mov rcx, rax
0x48, 0x83, 0xe1, 0xc0, // and rcx, -64
];
for k in 0..8 {
code.extend([0x48, 0xc7, 0x41, k * 8, 0, 0, 0, 0]); // mov qword [rcx + 8k], 0
}
code.push(0x59); // pop rcx
code.extend([0x48, 0x83, 0xc0, 0x40]); // add rax, 0x40
code.extend(cmp);
let back = -(code.len() as i64 + 2);
code.extend([0x72, i8::try_from(back).ok()? as u8]); // jb the start
let end = stub + code.len();
code.extend(jump(end, at + 12)?);
Some(code)
}
/// Room for [`clzero_stub`]s near the title's code: where it is and the bytes used.
static STUBS: std::sync::Mutex<Option<(usize, usize)>> = std::sync::Mutex::new(None);
const STUBS_LEN: usize = 64 << 10;
/// Memory for code within reach of a `jmp rel32` at `at`.
fn near(at: usize) -> Option<usize> {
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RESERVE, PAGE_EXECUTE_READWRITE, VirtualAlloc};
let at = at & !0xffff;
(0x10_0000..0x7000_0000).step_by(0x10_0000).flat_map(|d| [at.checked_sub(d), at.checked_add(d)]).flatten().find_map(|place| {
// SAFETY: reserves free memory at that address or fails.
let got = unsafe { VirtualAlloc(place as *const _, STUBS_LEN, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) } as usize;
(got != 0).then_some(got)
})
}
/// Replaces the `clzero` loop at `at`, whose 12 bytes are `code`: whether it did.
///
/// No thread is ever inside the loop's other instructions (the emulation does the whole loop
/// in one), so the five bytes of the jump may take the place of two of them.
///
/// # Safety
/// `at` is in the title's code, which stays mapped.
unsafe fn patch_clzero(at: usize, code: &[u8]) -> bool {
let &[a, b, c, d, e, _, _, x, y, z, 0x72, 0xf4] = code else {
return false;
};
let mut stubs = STUBS.lock().unwrap_or_else(|e| e.into_inner());
if stubs.is_none() {
*stubs = near(at).map(|place| (place, 0));
}
let Some((place, used)) = stubs.as_mut() else {
return false;
};
let stub = *place + *used;
let (Some(body), Some(jump)) = (clzero_stub(at, stub, [x, y, z]), jump(at, stub)) else {
return false;
};
if *used + body.len() > STUBS_LEN || (at & 15) + 5 > 16 {
return false;
}
// SAFETY: inside the memory made for it, which nothing runs yet; then the title's code.
unsafe {
std::ptr::copy_nonoverlapping(body.as_ptr(), stub as *mut u8, body.len());
*used += body.len().next_multiple_of(16);
patch(at, [a, b, c, d, e], jump)
}
}
/// The aligned 16 bytes `word` around address `at` with the bytes at `at` replaced; `None`
/// where they do not all lie in those 16. (16 and not 8: the title's busiest one lies over the
/// end of its 8 and took 28,000 exceptions a second, run cpu-6.)
fn with_patch(word: u128, at: usize, patch: &[u8]) -> Option<u128> {
let offset = at & 15;
if offset + patch.len() > 16 {
return None;
}
let mut bytes = word.to_le_bytes();
bytes[offset..offset + patch.len()].copy_from_slice(&patch);
Some(u64::from_le_bytes(bytes))
bytes[offset..offset + patch.len()].copy_from_slice(patch);
Some(u128::from_le_bytes(bytes))
}
/// One thread at a time changes code: a second one would take the first one's loosened
/// protection for the page's own.
static PATCHING: std::sync::Mutex<()> = std::sync::Mutex::new(());
/// Replaces the 3 bytes at `at`, which are `was`, by `patch`, in one store that other threads
/// see whole: whether they are replaced now (not where they cross 8 aligned bytes, or the page
/// Replaces the bytes at `at`, which are `was`, by `patch`, in one store that other threads
/// see whole: whether they are replaced now (not where they cross 16 aligned bytes, or the page
/// cannot be written).
///
/// # Safety
/// `at` is in code that stays mapped, and `patch` does for it what `was` does.
unsafe fn patch(at: usize, was: [u8; 3], patch: [u8; 3]) -> bool {
unsafe fn patch<const N: usize>(at: usize, was: [u8; N], patch: [u8; N]) -> bool {
use std::sync::atomic::Ordering::SeqCst;
use windows_sys::Win32::System::Diagnostics::Debug::FlushInstructionCache;
use windows_sys::Win32::System::Memory::{PAGE_EXECUTE_READWRITE, VirtualProtect};
use windows_sys::Win32::System::Threading::GetCurrentProcess;
if (at & 7) + 3 > 8 {
if (at & 15) + N > 16 || !std::is_x86_feature_detected!("cmpxchg16b") {
return false;
}
let _one = PATCHING.lock().unwrap_or_else(|e| e.into_inner());
let word = (at & !7) as *mut u64;
let here = (at & 7)..(at & 7) + 3;
let word = (at & !15) as *mut u128;
let here = (at & 15)..(at & 15) + N;
let mut old = 0u32;
// SAFETY: the aligned 8 bytes around the instruction lie in one page of mapped code, made
// writable for the store and put back.
// SAFETY: the aligned 16 bytes around the instruction lie in one page of mapped code, made
// writable for the store and put back; the processor has the instruction (asked above).
unsafe {
if VirtualProtect(word.cast(), 8, PAGE_EXECUTE_READWRITE, &mut old) == 0 {
if VirtualProtect(word.cast(), 16, PAGE_EXECUTE_READWRITE, &mut old) == 0 {
return false;
}
let done = AtomicU64::from_ptr(word)
.fetch_update(SeqCst, SeqCst, |now| if now.to_le_bytes()[here.clone()] == was { with_patch(now, at, patch) } else { None })
// (Another thread's fault at the same place: done already.)
.map_or_else(|now| now.to_le_bytes()[here.clone()] == patch, |_| true);
VirtualProtect(word.cast(), 8, old, &mut old);
FlushInstructionCache(GetCurrentProcess(), word.cast(), 8);
// What is there (zeros are replaced by zeros).
let mut now = std::arch::x86_64::cmpxchg16b(word, 0, 0, SeqCst, SeqCst);
let done = loop {
let bytes = &now.to_le_bytes()[here.clone()];
if bytes == patch {
// (Another thread's fault at the same place: done already.)
break true;
}
let Some(new) = (bytes == was).then(|| with_patch(now, at, &patch)).flatten() else {
break false;
};
let there = std::arch::x86_64::cmpxchg16b(word, now, new, SeqCst, SeqCst);
if there == now {
break true;
}
now = there;
};
VirtualProtect(word.cast(), 16, old, &mut old);
FlushInstructionCache(GetCurrentProcess(), word.cast(), 16);
done
}
}
@@ -186,7 +291,7 @@ mod sites {
let top: Vec<String> =
all.iter().take(8).map(|s| format!("{:#x} {} {:.0}", s.1, NAMES[s.2], s.0 as f64 / seconds)).collect();
tracing::info!(
"console CPU instructions that fault, a second: {}; wait instructions replaced in place so far: {}; the busiest places: {}",
"console CPU instructions that fault, a second: {}; places replaced so far: {}; the busiest places: {}",
kinds.join(", "),
PATCHED.load(Relaxed),
top.join(", ")
@@ -328,6 +433,15 @@ pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 {
}
ConsoleOnly::ClzeroLoop { end_reg } => {
// the whole `clzero; add rax,40h; cmp rax,end; jb` loop at once
// (and not again: the next time it is plain stores)
if len == 12
&& patches_clzero()
// SAFETY: the title's code, where the loop's first instruction just faulted.
&& unsafe { patch_clzero(rip, &code[..12]) }
{
#[cfg(feature = "diagnostics")]
sites::patched();
}
let regs: [u64; 16] = [
ctx.Rax, ctx.Rcx, ctx.Rdx, ctx.Rbx, ctx.Rsp, ctx.Rbp, ctx.Rsi, ctx.Rdi, ctx.R8, ctx.R9, ctx.R10, ctx.R11, ctx.R12, ctx.R13, ctx.R14, ctx.R15,
];
@@ -426,12 +540,12 @@ mod tests {
use super::*;
#[test]
fn wait_instructions_are_replaced_inside_eight_aligned_bytes() {
let word = u64::from_le_bytes([1, 2, 0x0f, 0x01, 0xfb, 6, 7, 8]);
let new = with_patch(word, 0x1002, [0xf3, 0x90, 0x90]).unwrap();
assert_eq!(new.to_le_bytes(), [1, 2, 0xf3, 0x90, 0x90, 6, 7, 8]);
assert!(with_patch(word, 0x1005, [0; 3]).is_some());
assert!(with_patch(word, 0x1006, [0; 3]).is_none(), "crosses into the next eight");
fn wait_instructions_are_replaced_inside_sixteen_aligned_bytes() {
let word = u128::from_le_bytes([1, 2, 3, 4, 5, 6, 7, 0x0f, 0x01, 0xfb, 11, 12, 13, 14, 15, 16]);
let new = with_patch(word, 0x1007, &[0xf3, 0x90, 0x90]).unwrap();
assert_eq!(new.to_le_bytes(), [1, 2, 3, 4, 5, 6, 7, 0xf3, 0x90, 0x90, 11, 12, 13, 14, 15, 16]);
assert!(with_patch(word, 0x100d, &[0; 3]).is_some());
assert!(with_patch(word, 0x100e, &[0; 3]).is_none(), "crosses into the next sixteen");
}
/// `monitorx; mwaitx; ret` in a page of its own: each is replaced at its first fault,
@@ -447,34 +561,93 @@ mod tests {
let page = VirtualAlloc(std::ptr::null(), 4096, MEM_COMMIT | MEM_RESERVE, PAGE_READWRITE).cast::<u8>();
assert!(!page.is_null());
let code = [0x0f, 0x01, 0xfa, 0x0f, 0x01, 0xfb, 0xc3];
// Both within the aligned eight bytes at 8; and one over the end of its eight
// (at 22), which is left alone.
std::ptr::copy_nonoverlapping(code.as_ptr(), page.add(8), code.len());
std::ptr::copy_nonoverlapping(code.as_ptr(), page.add(22), code.len());
// The first over the end of its aligned eight bytes, as the title's is; and one
// over the end of its sixteen (at 46), which is left alone.
std::ptr::copy_nonoverlapping(code.as_ptr(), page.add(6), code.len());
std::ptr::copy_nonoverlapping(code.as_ptr(), page.add(46), code.len());
let mut old = 0;
assert_ne!(VirtualProtect(page.cast(), 4096, PAGE_EXECUTE_READ, &mut old), 0);
let at = page as usize;
let mut context: CONTEXT = std::mem::zeroed();
for rip in [at + 8, at + 11, at + 22] {
for rip in [at + 6, at + 9, at + 46] {
context.Rip = rip as u64;
assert_eq!(emulate(&mut context), CONTINUE_EXECUTION);
assert_eq!(context.Rip, rip as u64 + 3);
}
if patches_waits() {
let now = std::slice::from_raw_parts(page.add(8), 7);
let now = std::slice::from_raw_parts(page.add(6), 7);
assert_eq!(now, [0x0f, 0x1f, 0x00, 0xf3, 0x90, 0x90, 0xc3]);
// They run now.
let run: extern "system" fn() = std::mem::transmute(page.add(8));
let run: extern "system" fn() = std::mem::transmute(page.add(6));
run();
// A second thread that faulted at the same place meanwhile.
assert!(patch(at + 8, [0x0f, 0x01, 0xfa], [0x0f, 0x1f, 0x00]));
assert!(!patch(at + 22, [0x0f, 0x01, 0xfa], [0x0f, 0x1f, 0x00]), "crosses its eight bytes");
assert!(patch(at + 6, [0x0f, 0x01, 0xfa], [0x0f, 0x1f, 0x00]));
assert!(!patch(at + 46, [0x0f, 0x01, 0xfa], [0x0f, 0x1f, 0x00]), "crosses its sixteen bytes");
}
assert_eq!(std::slice::from_raw_parts(page.add(22), 3), [0x0f, 0x01, 0xfa]);
assert_eq!(std::slice::from_raw_parts(page.add(46), 3), [0x0f, 0x01, 0xfa]);
let mut m: MEMORY_BASIC_INFORMATION = std::mem::zeroed();
VirtualQuery(page.cast(), &mut m, size_of_val(&m));
assert_eq!(m.Protect, PAGE_EXECUTE_READ);
VirtualFree(page.cast(), 0, MEM_RELEASE);
}
}
/// `clzero` loops run as plain stores: the lines they name are zero and no other byte,
/// and the pointer, the scratch register and the flags come out as from the loop.
#[test]
fn a_clzero_loop_becomes_plain_stores() {
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READWRITE, VirtualAlloc, VirtualFree};
// Against rdx (rm rax, reg rdx) and against rcx, the scratch register.
for (cmp, by) in [([0x48, 0x39, 0xd0], 2), ([0x48, 0x39, 0xc8], 1), ([0x4c, 0x39, 0xc0], 8)] {
// SAFETY: memory of our own, written and run inside it.
unsafe {
let page = VirtualAlloc(std::ptr::null(), 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) as usize;
assert_ne!(page, 0);
// A function of (start, end): the start in rax, the end in its register, the
// loop at 16, and what rax became.
let mut head = vec![0x48, 0x89, 0xc8]; // mov rax, rcx
match by {
1 => head.extend([0x48, 0x89, 0xd1]), // mov rcx, rdx
8 => head.extend([0x49, 0x89, 0xd0]), // mov r8, rdx
_ => {}
}
head.resize(16, 0x90);
let mut code = head;
code.extend([0x0f, 0x01, 0xfc, 0x48, 0x83, 0xc0, 0x40]);
code.extend(cmp);
code.extend([0x72, 0xf4]);
code.push(0xc3);
std::ptr::copy_nonoverlapping(code.as_ptr(), page as *mut u8, code.len());
let mut context: CONTEXT = std::mem::zeroed();
let mut block = vec![0xaau8; 64 * 8 + 64];
let base = block.as_mut_ptr() as usize;
let first = base.next_multiple_of(64);
// The fault itself: emulated whole, and replaced.
context.Rip = page as u64 + 16;
context.Rax = first as u64;
context.Rdx = first as u64 + 128;
context.Rcx = context.Rdx;
context.R8 = context.Rdx;
assert_eq!(emulate(&mut context), CONTINUE_EXECUTION);
assert_eq!((context.Rip, context.Rax), (page as u64 + 28, first as u64 + 128));
if patches_clzero() {
assert_eq!(*((page + 16) as *const u8), 0xe9, "a jump");
block.fill(0xaa);
let run: extern "system" fn(usize, usize) -> usize = std::mem::transmute(page);
// From inside a line to inside the third: whole lines, one past the end.
assert_eq!(run(first + 8, first + 130), first + 8 + 128);
let at = first - base;
assert!(block[at..at + 128].iter().all(|&b| b == 0));
assert!(block[..at].iter().chain(&block[at + 128..]).all(|&b| b == 0xaa));
// An end at the start: one line.
block.fill(0xaa);
assert_eq!(run(first, first), first + 64);
assert!(block[at..at + 64].iter().all(|&b| b == 0) && block[at + 64] == 0xaa);
}
VirtualFree(page as *mut _, 0, MEM_RELEASE);
}
}
assert!(clzero_stub(0x1000, 0x2000, [0x48, 0x39, 0xc0]).is_none(), "against rax itself");
assert!(jump(0x1000, 0x9000_0000_0000).is_none(), "out of reach");
}
}