victory-gta6: this fork's changes on top of VIctory main (ffe310e)
World rendering, lighting, frame-rate and memory work for Grand Theft Auto VI (Xbox Series X profile) on one Windows PC with an NVIDIA RTX 4070. The README describes the state, the changes and the credits. Based on VIctory by Marvisak and contributors (GPL-3.0-or-later); XCL by ivall and contributors was used as a reference. No game files are included. Co-Authored-By: Claude Fable 5.2 <[email protected]>
This commit is contained in:
1 parent
ffe310eb20
commit
578d459c34
61 files changed
+32259
-1274
No files matched your search
@@ -0,0 +1,249 @@
|
||||
//! Instructions the console's CPU (Zen 2) has and an Intel PC's lacks, emulated: the title's
|
||||
//! code raises STATUS_ILLEGAL_INSTRUCTION on them (GTA VI zeroes memory with a `clzero` loop at
|
||||
//! its first frames), and the vectored handler steps over them here.
|
||||
//!
|
||||
//! Ported from XCL (github.com/ivall/xcl, GPL-2.0-only): `insn.rs` (decoder, as
|
||||
//! `console_insn_decode.rs`, unchanged) and `eh.rs` `emulate_console_only`.
|
||||
|
||||
#[path = "console_insn_decode.rs"]
|
||||
mod decode;
|
||||
|
||||
use decode::ConsoleOnly;
|
||||
use std::cell::Cell;
|
||||
use std::sync::atomic::{AtomicU64, Ordering::Relaxed};
|
||||
use windows_sys::Win32::System::Diagnostics::Debug::CONTEXT;
|
||||
|
||||
const CONTINUE_EXECUTION: i32 = -1;
|
||||
|
||||
/// Whether what Windows said about memory is remembered per thread (the regions it found
|
||||
/// writable, the code bytes it found readable) and not asked again at every emulated
|
||||
/// instruction. A query walks the pages of the region it answers for: asked from outside, it
|
||||
/// took 2-9 ms in the title's heaps of 0.6-2.2 GB and 89 ms in its 6.2 GB page pool (run 30),
|
||||
/// and the title zeroes blocks of them with `clzero` loops all through a frame: six of its
|
||||
/// threads spent 25-78 % of their time inside that query (runs 29 and 30), about 27 s of
|
||||
/// processor time in Windows per 9 s frame. On by default; `VICTORY_CLZERO_ASK=1` asks every
|
||||
/// time, as before.
|
||||
fn remembers() -> bool {
|
||||
static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
|
||||
*ON.get_or_init(|| std::env::var_os("VICTORY_CLZERO_ASK").is_none_or(|v| v != "1"))
|
||||
}
|
||||
|
||||
/// Answers a remembered region gives before Windows is asked about it again: one freed or
|
||||
/// protected meanwhile is forgotten then.
|
||||
const ANSWERS: u32 = 4096;
|
||||
|
||||
thread_local! {
|
||||
/// The regions Windows last said are committed and writable (start, end), newest first,
|
||||
/// and the answers they gave since they were emptied.
|
||||
static WRITABLE: Cell<([(usize, usize); 4], u32)> = const { Cell::new(([(0, 0); 4], 0)) };
|
||||
/// Faulting addresses and the code bytes found readable there, newest first.
|
||||
static CODE: Cell<[(usize, usize); 8]> = const { Cell::new([(0, 0); 8]) };
|
||||
}
|
||||
|
||||
/// Instructions emulated, the times Windows was asked about memory for them, and the bytes
|
||||
/// `clzero` loops zeroed, since the start.
|
||||
static EMULATED: AtomicU64 = AtomicU64::new(0);
|
||||
static ASKED: AtomicU64 = AtomicU64::new(0);
|
||||
static ZEROED: AtomicU64 = AtomicU64::new(0);
|
||||
|
||||
fn readable(va: usize, bytes: usize) -> bool {
|
||||
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_GUARD, PAGE_NOACCESS, VirtualQuery};
|
||||
// SAFETY: plain data filled in by the query.
|
||||
let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
|
||||
// SAFETY: a valid out pointer of the right size.
|
||||
let found = unsafe { VirtualQuery(va as *const _, &mut m, size_of_val(&m)) } != 0;
|
||||
ASKED.fetch_add(1, Relaxed);
|
||||
found && m.State == MEM_COMMIT && m.Protect & (PAGE_NOACCESS | PAGE_GUARD) == 0 && m.BaseAddress as usize + m.RegionSize >= va + bytes
|
||||
}
|
||||
|
||||
fn writable(va: usize, bytes: usize) -> bool {
|
||||
writable_to(va, va + bytes) == Some(va + bytes)
|
||||
}
|
||||
|
||||
/// Where the committed, writable memory that `va` lies in ends, at most `end`; None if `va`
|
||||
/// is not in such memory. A region found is remembered ([`remembers`]).
|
||||
/// shortcut: a remembered region that was freed or protected since is written all the same
|
||||
/// for up to [`ANSWERS`] answers: the write then faults inside the handler, which the guard
|
||||
/// on view memory opens as it does any write, and which is a crash otherwise (as the
|
||||
/// unchecked single-line emulation behind this one already is).
|
||||
fn writable_to(va: usize, end: usize) -> Option<usize> {
|
||||
use windows_sys::Win32::System::Memory::{MEM_COMMIT, MEMORY_BASIC_INFORMATION, PAGE_EXECUTE_READWRITE, PAGE_READWRITE, VirtualQuery};
|
||||
let remember = remembers();
|
||||
if remember {
|
||||
let (regions, answers) = WRITABLE.with(Cell::get);
|
||||
if let Some(&(_, to)) = regions.iter().find(|&&(from, to)| from <= va && va < to) {
|
||||
let next = if answers >= ANSWERS { ([(0, 0); 4], 0) } else { (regions, answers + 1) };
|
||||
WRITABLE.with(|w| w.set(next));
|
||||
return Some(to.min(end));
|
||||
}
|
||||
}
|
||||
// SAFETY: plain data filled in by the query.
|
||||
let mut m: MEMORY_BASIC_INFORMATION = unsafe { std::mem::zeroed() };
|
||||
// SAFETY: a valid out pointer of the right size.
|
||||
let found = unsafe { VirtualQuery(va as *const _, &mut m, size_of_val(&m)) } != 0;
|
||||
ASKED.fetch_add(1, Relaxed);
|
||||
if !found || m.State != MEM_COMMIT || m.Protect & (PAGE_READWRITE | PAGE_EXECUTE_READWRITE) == 0 {
|
||||
return None;
|
||||
}
|
||||
let (from, to) = (m.BaseAddress as usize, m.BaseAddress as usize + m.RegionSize);
|
||||
if remember {
|
||||
WRITABLE.with(|w| {
|
||||
let (mut regions, answers) = w.get();
|
||||
regions.rotate_right(1);
|
||||
regions[0] = (from, to);
|
||||
w.set((regions, answers));
|
||||
});
|
||||
}
|
||||
Some(to.min(end))
|
||||
}
|
||||
|
||||
/// An illegal instruction at `ctx.Rip`: a console-only one is emulated and stepped over
|
||||
/// (`CONTINUE_EXECUTION`); anything else returns 0 (the crash report and the title's handlers
|
||||
/// see it).
|
||||
///
|
||||
/// # Safety
|
||||
/// `ctx` is the faulting thread's context, from the exception being dispatched.
|
||||
pub(crate) unsafe fn emulate(ctx: &mut CONTEXT) -> i32 {
|
||||
let rip = ctx.Rip as usize;
|
||||
// The same few instructions fault again and again: their bytes are asked about once.
|
||||
let known = if remembers() { CODE.with(Cell::get) } else { [(0, 0); 8] };
|
||||
let n = match known.iter().find(|&&(at, n)| at == rip && n > 0) {
|
||||
Some(&(_, n)) => n,
|
||||
None => {
|
||||
if !readable(rip, 1) {
|
||||
return 0;
|
||||
}
|
||||
let n = (1..=16).rev().find(|&n| readable(rip, n)).unwrap_or(0);
|
||||
if remembers() {
|
||||
let mut known = known;
|
||||
known.rotate_right(1);
|
||||
known[0] = (rip, n);
|
||||
CODE.with(|c| c.set(known));
|
||||
}
|
||||
n
|
||||
}
|
||||
};
|
||||
// SAFETY: `n` bytes at `rip` are readable.
|
||||
let code = unsafe { std::slice::from_raw_parts(rip as *const u8, n) };
|
||||
let Some((what, len)) = decode::decode(code) else { return 0 };
|
||||
static SEEN: std::sync::Mutex<Vec<std::mem::Discriminant<ConsoleOnly>>> = std::sync::Mutex::new(Vec::new());
|
||||
if let Ok(mut seen) = SEEN.lock()
|
||||
&& !seen.contains(&std::mem::discriminant(&what))
|
||||
{
|
||||
seen.push(std::mem::discriminant(&what));
|
||||
if what != ConsoleOnly::Ud2 {
|
||||
tracing::warn!(instruction = ?what, at = format_args!("{rip:#x}"), "a console CPU instruction this CPU lacks: emulated (logged once)");
|
||||
}
|
||||
}
|
||||
match what {
|
||||
ConsoleOnly::Ud2 => return 0,
|
||||
ConsoleOnly::Clwb => {
|
||||
// nothing to write back on the PC: patched to NOPs, no exception next time
|
||||
use windows_sys::Win32::System::Memory::{PAGE_EXECUTE_READWRITE, VirtualProtect};
|
||||
let mut old = 0u32;
|
||||
// SAFETY: the instruction's own bytes, made writable for the patch and restored.
|
||||
unsafe {
|
||||
if VirtualProtect(rip as *const _, len, PAGE_EXECUTE_READWRITE, &mut old) != 0 {
|
||||
std::slice::from_raw_parts_mut(rip as *mut u8, len).fill(0x90);
|
||||
VirtualProtect(rip as *const _, len, old, &mut old);
|
||||
}
|
||||
}
|
||||
}
|
||||
ConsoleOnly::Monitorx => {}
|
||||
ConsoleOnly::Mwaitx => std::hint::spin_loop(),
|
||||
ConsoleOnly::Clzero => {
|
||||
// with an address-size prefix (0x67) the line is at EAX, zero-extended
|
||||
let a32 = code[..len - 3].contains(&0x67);
|
||||
let line = (if a32 { ctx.Rax & 0xFFFF_FFFF } else { ctx.Rax } as usize) & !63;
|
||||
if !writable(line, 64) {
|
||||
return 0; // the real instruction faults there too
|
||||
}
|
||||
// SAFETY: the 64-byte line is committed and writable.
|
||||
unsafe { std::ptr::write_bytes(line as *mut u8, 0, 64) };
|
||||
}
|
||||
ConsoleOnly::ClzeroLoop { end_reg } => {
|
||||
// the whole `clzero; add rax,40h; cmp rax,end; jb` loop at once
|
||||
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,
|
||||
];
|
||||
let end = regs[end_reg as usize & 15] as usize;
|
||||
let start = ctx.Rax as usize;
|
||||
if end > start && end - start < 2 << 30 {
|
||||
// Region by region: a block may lie across several (the title's pages are
|
||||
// mapped one view each), and one answer for all of it was a refusal, after
|
||||
// which every 64-byte line took an exception of its own.
|
||||
let mut at = start;
|
||||
while at < end {
|
||||
let Some(to) = writable_to(at, end) else { break };
|
||||
// SAFETY: committed and writable from `at` to `to`.
|
||||
unsafe { std::ptr::write_bytes(at as *mut u8, 0, to - at) };
|
||||
at = to;
|
||||
}
|
||||
if at == start {
|
||||
return 0;
|
||||
}
|
||||
ZEROED.fetch_add((at - start) as u64, Relaxed);
|
||||
if at < end {
|
||||
// What follows is not writable: the loop goes on there (the same
|
||||
// instruction again), where the real one faults too.
|
||||
ctx.Rax = at as u64;
|
||||
return CONTINUE_EXECUTION;
|
||||
}
|
||||
}
|
||||
ctx.Rax = end as u64;
|
||||
}
|
||||
ConsoleOnly::Rdpru => {
|
||||
let mut v = 0i64;
|
||||
// SAFETY: a valid out pointer.
|
||||
unsafe { windows_sys::Win32::System::Performance::QueryPerformanceCounter(&mut v) };
|
||||
let v = if ctx.Rcx as u32 <= 1 { v as u64 } else { 0 };
|
||||
ctx.Rax = v & 0xFFFF_FFFF;
|
||||
ctx.Rdx = v >> 32;
|
||||
}
|
||||
ConsoleOnly::Rdpid(r) => {
|
||||
// SAFETY: no preconditions.
|
||||
let cpu = unsafe { windows_sys::Win32::System::Threading::GetCurrentProcessorNumber() } as u64;
|
||||
let regs: [&mut u64; 16] = [
|
||||
&mut ctx.Rax, &mut ctx.Rcx, &mut ctx.Rdx, &mut ctx.Rbx, &mut ctx.Rsp, &mut ctx.Rbp, &mut ctx.Rsi, &mut ctx.Rdi, &mut ctx.R8, &mut ctx.R9, &mut ctx.R10, &mut ctx.R11, &mut ctx.R12, &mut ctx.R13,
|
||||
&mut ctx.R14, &mut ctx.R15,
|
||||
];
|
||||
*regs[r as usize & 15] = cpu;
|
||||
}
|
||||
// the low quadword changes; the high one is zeroed, as a Zen 5 does
|
||||
ConsoleOnly::Extrq { dst, src, len, idx } => {
|
||||
// SAFETY: the context's XMM registers (CONTEXT_FLOATING_POINT is captured for exceptions).
|
||||
let x = unsafe { &mut ctx.Anonymous.FltSave.XmmRegisters };
|
||||
let (len, idx) = match src {
|
||||
Some(s) => {
|
||||
let c = x[s as usize & 15].Low;
|
||||
(c as u8, (c >> 8) as u8)
|
||||
}
|
||||
None => (len, idx),
|
||||
};
|
||||
let d = &mut x[dst as usize & 15];
|
||||
d.Low = decode::extrq(d.Low, len, idx);
|
||||
d.High = 0;
|
||||
}
|
||||
ConsoleOnly::Insertq { dst, src, reg, len, idx } => {
|
||||
// SAFETY: as above.
|
||||
let x = unsafe { &mut ctx.Anonymous.FltSave.XmmRegisters };
|
||||
let s = x[src as usize & 15];
|
||||
let (len, idx) = if reg { (s.High as u8, (s.High >> 8) as u8) } else { (len, idx) };
|
||||
let d = &mut x[dst as usize & 15];
|
||||
d.Low = decode::insertq(d.Low, s.Low, len, idx);
|
||||
d.High = 0;
|
||||
}
|
||||
}
|
||||
ctx.Rip += len as u64;
|
||||
// How often this runs at all (each one is an exception: a trip into Windows and back).
|
||||
let emulated = EMULATED.fetch_add(1, Relaxed) + 1;
|
||||
if emulated >= 1 << 16 && emulated.is_power_of_two() {
|
||||
tracing::info!(
|
||||
emulated,
|
||||
asked = ASKED.load(Relaxed),
|
||||
zeroed_mb = ZEROED.load(Relaxed) >> 20,
|
||||
"console CPU instructions emulated so far, the times Windows was asked about memory for them, and what clzero loops zeroed"
|
||||
);
|
||||
}
|
||||
CONTINUE_EXECUTION
|
||||
}
|
||||
@@ -0,0 +1,237 @@
|
||||
//! Instructions the console's CPU (Zen 2) has and a PC's may lack – a title raises
|
||||
//! STATUS_ILLEGAL_INSTRUCTION on them on an Intel CPU before Ice Lake / Alder Lake (CLWB,
|
||||
//! SHA) or on any Intel CPU (CLZERO, RDPRU, MONITORX / MWAITX and SSE4a's EXTRQ / INSERTQ,
|
||||
//! which are AMD's). The exception handler (`eh`) emulates the ones decoded here and steps over
|
||||
//! them.
|
||||
|
||||
/// A console-only instruction at the faulting address.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum ConsoleOnly {
|
||||
/// `clwb m8`: write a cache line back – nothing to do, the PC's memory is coherent
|
||||
Clwb,
|
||||
/// `clzero`: zero the 64-byte cache line at rAX
|
||||
Clzero,
|
||||
/// `clzero` loop: `clzero; add rax, 0x40; cmp rax, <reg>; jb -12` – zero `[rax..reg)`
|
||||
ClzeroLoop { end_reg: u8 },
|
||||
/// `rdpru`: ecx = 0 MPERF / 1 APERF → edx:eax (a counter)
|
||||
Rdpru,
|
||||
/// `monitorx` / `mwaitx`: a wait the emulation skips
|
||||
Monitorx,
|
||||
Mwaitx,
|
||||
/// `rdpid r64`: TSC_AUX (the processor number) into the register (CONTEXT order: rax, rcx,
|
||||
/// rdx, rbx, rsp, rbp, rsi, rdi, r8..r15)
|
||||
Rdpid(u8),
|
||||
/// SSE4a `extrq xmm, imm8 (length), imm8 (index)` / `extrq xmm1, xmm2` (`src` Some: the
|
||||
/// length and index in xmm2's bits 5:0 and 13:8): a bit field of the low quadword, moved
|
||||
/// down and zero-extended (the high quadword zeroed). Registers are XMM numbers 0..15.
|
||||
Extrq { dst: u8, src: Option<u8>, len: u8, idx: u8 },
|
||||
/// SSE4a `insertq xmm1, xmm2, imm8 (length), imm8 (index)` / `insertq xmm1, xmm2` (`reg`:
|
||||
/// the length and index in xmm2's bits 69:64 and 77:72): the low bits of xmm2 put into a
|
||||
/// bit field of xmm1's low quadword.
|
||||
Insertq { dst: u8, src: u8, reg: bool, len: u8, idx: u8 },
|
||||
/// `ud2`: the title's own trap (not emulated)
|
||||
Ud2,
|
||||
}
|
||||
|
||||
/// A field length of SSE4a's six bits: 0 is 64.
|
||||
fn field_len(len: u8) -> u32 {
|
||||
match len & 63 {
|
||||
0 => 64,
|
||||
n => n as u32,
|
||||
}
|
||||
}
|
||||
|
||||
/// EXTRQ on a low quadword: `len` bits from bit `idx`, zero-extended (a field past bit 63 is
|
||||
/// undefined on the console; here it is what a shift gives).
|
||||
pub fn extrq(v: u64, len: u8, idx: u8) -> u64 {
|
||||
let (len, idx) = (field_len(len), (idx & 63) as u32);
|
||||
let field = v.checked_shr(idx).unwrap_or(0);
|
||||
if len >= 64 {
|
||||
field
|
||||
} else {
|
||||
field & ((1u64 << len) - 1)
|
||||
}
|
||||
}
|
||||
|
||||
/// INSERTQ on a low quadword: the low `len` bits of `src` put at bit `idx` of `dst`.
|
||||
pub fn insertq(dst: u64, src: u64, len: u8, idx: u8) -> u64 {
|
||||
let (len, idx) = (field_len(len), (idx & 63) as u32);
|
||||
let ones = if len >= 64 { u64::MAX } else { (1u64 << len) - 1 };
|
||||
let mask = ones.checked_shl(idx).unwrap_or(0);
|
||||
(dst & !mask) | ((src & ones).checked_shl(idx).unwrap_or(0) & mask)
|
||||
}
|
||||
|
||||
/// The length of a ModRM-encoded operand (ModRM, SIB and displacement) at `b[0]`, None when the
|
||||
/// bytes run out.
|
||||
fn modrm_len(b: &[u8]) -> Option<usize> {
|
||||
let modrm = *b.first()?;
|
||||
let (md, rm) = (modrm >> 6, modrm & 7);
|
||||
if md == 3 {
|
||||
return Some(1);
|
||||
}
|
||||
let mut len = 1;
|
||||
let mut base = rm;
|
||||
if rm == 4 {
|
||||
base = *b.get(1)? & 7;
|
||||
len += 1;
|
||||
}
|
||||
len += match md {
|
||||
0 if base == 5 => 4, // disp32 (rip-relative, or a SIB without a base)
|
||||
0 => 0,
|
||||
1 => 1,
|
||||
_ => 4,
|
||||
};
|
||||
(b.len() >= len).then_some(len)
|
||||
}
|
||||
|
||||
/// The console-only instruction at the start of `code` and its length.
|
||||
pub fn decode(code: &[u8]) -> Option<(ConsoleOnly, usize)> {
|
||||
let mut i = 0;
|
||||
// `rep`: the last of F2 / F3, which decides between them (and over 66) for SSE4a
|
||||
let (mut p66, mut pf3, mut rep, mut rex) = (false, false, 0u8, 0u8);
|
||||
while let Some(&b) = code.get(i) {
|
||||
match b {
|
||||
0x66 => p66 = true,
|
||||
0xF2 => rep = 0xF2,
|
||||
0xF3 => {
|
||||
pf3 = true;
|
||||
rep = 0xF3;
|
||||
}
|
||||
0x2E | 0x3E | 0x26 | 0x36 | 0x64 | 0x65 | 0x67 => {}
|
||||
// REX counts only right before the opcode: one before a legacy prefix is ignored
|
||||
0x40..=0x4F => {
|
||||
rex = b;
|
||||
i += 1;
|
||||
continue;
|
||||
}
|
||||
_ => break,
|
||||
}
|
||||
rex = 0;
|
||||
i += 1;
|
||||
}
|
||||
if *code.get(i)? != 0x0F {
|
||||
return None;
|
||||
}
|
||||
match (*code.get(i + 1)?, code.get(i + 2).copied()) {
|
||||
(0x01, Some(0xFC)) => {
|
||||
// clzero (0F 01 FC); add rax, 0x40 (48 83 C0 40); cmp rax, <reg> ([48|4C] 39 modrm); jb -12 (72 F4)
|
||||
// (not after an 0x67: that CLZERO is at EAX, and the jb goes back to the 0F, past the
|
||||
// prefix – it is stepped alone, the loop is taken from the next one)
|
||||
if code.len() >= i + 12
|
||||
&& !code[..i].contains(&0x67)
|
||||
&& code[i + 3..i + 7] == [0x48, 0x83, 0xC0, 0x40]
|
||||
&& (code[i + 7] == 0x48 || code[i + 7] == 0x4C)
|
||||
&& code[i + 8] == 0x39
|
||||
&& code[i + 10..i + 12] == [0x72, 0xF4]
|
||||
{
|
||||
let rex_r = code[i + 7] == 0x4C;
|
||||
let modrm = code[i + 9];
|
||||
let reg_idx = ((modrm >> 3) & 7) | if rex_r { 8 } else { 0 };
|
||||
Some((ConsoleOnly::ClzeroLoop { end_reg: reg_idx }, i + 12))
|
||||
} else {
|
||||
Some((ConsoleOnly::Clzero, i + 3))
|
||||
}
|
||||
}
|
||||
(0x01, Some(0xFD)) => Some((ConsoleOnly::Rdpru, i + 3)),
|
||||
(0x01, Some(0xFA)) => Some((ConsoleOnly::Monitorx, i + 3)),
|
||||
(0x01, Some(0xFB)) => Some((ConsoleOnly::Mwaitx, i + 3)),
|
||||
(0x0B, _) => Some((ConsoleOnly::Ud2, i + 2)),
|
||||
// SSE4a: register operands only (ModRM mod 3); REX.R extends reg, REX.B rm
|
||||
// (the last of F2 / F3 decides: F2 INSERTQ, F3 #UD; neither with 66: EXTRQ)
|
||||
(0x78 | 0x79, Some(m)) if (rep == 0xF2 || (rep == 0 && p66)) && m >> 6 == 3 => {
|
||||
let reg = ((m >> 3) & 7) | (rex & 4) << 1;
|
||||
let rm = (m & 7) | (rex & 1) << 3;
|
||||
let imm = |k: usize| code.get(i + 3 + k).copied();
|
||||
match (code[i + 1], rep == 0xF2) {
|
||||
// extrq xmm(rm), imm8, imm8 – the ModRM reg field is /0
|
||||
(0x78, false) if (m >> 3) & 7 == 0 => Some((ConsoleOnly::Extrq { dst: rm, src: None, len: imm(0)?, idx: imm(1)? }, i + 5)),
|
||||
(0x79, false) => Some((ConsoleOnly::Extrq { dst: reg, src: Some(rm), len: 0, idx: 0 }, i + 3)),
|
||||
(0x78, true) => Some((ConsoleOnly::Insertq { dst: reg, src: rm, reg: false, len: imm(0)?, idx: imm(1)? }, i + 5)),
|
||||
(0x79, true) => Some((ConsoleOnly::Insertq { dst: reg, src: rm, reg: true, len: 0, idx: 0 }, i + 3)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
// 66 0F AE /6 with a memory operand (without 66 it is xsaveopt)
|
||||
(0xAE, Some(m)) if p66 && (m >> 3) & 7 == 6 && m >> 6 != 3 => Some((ConsoleOnly::Clwb, i + 2 + modrm_len(&code[i + 2..])?)),
|
||||
// F3 0F C7 /7 with a register operand
|
||||
(0xC7, Some(m)) if pf3 && (m >> 3) & 7 == 7 && m >> 6 == 3 => Some((ConsoleOnly::Rdpid((m & 7) | (rex & 1) << 3), i + 3)),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// `code` as hex, for a log line.
|
||||
pub fn hex(code: &[u8]) -> String {
|
||||
code.iter().map(|b| format!("{b:02x}")).collect::<Vec<_>>().join(" ")
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// EXTRQ / INSERTQ as AMD's manual gives them: a length of 0 is 64.
|
||||
#[test]
|
||||
fn sse4a_bit_fields() {
|
||||
assert_eq!(extrq(0x1234_5678_9ABC_DEF0, 8, 16), 0xBC);
|
||||
assert_eq!(extrq(0x1234_5678_9ABC_DEF0, 0, 0), 0x1234_5678_9ABC_DEF0);
|
||||
assert_eq!(extrq(0x8000_0000_0000_0000, 1, 63), 1);
|
||||
assert_eq!(insertq(0xFFFF_FFFF_FFFF_FFFF, 0xAB, 8, 8), 0xFFFF_FFFF_FFFF_ABFF);
|
||||
assert_eq!(insertq(0, 0x1FF, 4, 60), 0xF000_0000_0000_0000);
|
||||
assert_eq!(insertq(0x1111, 0xDEAD_BEEF_0000_0000, 0, 0), 0xDEAD_BEEF_0000_0000);
|
||||
for (v, len, idx) in [(0x0123_4567_89AB_CDEFu64, 12u8, 20u8), (u64::MAX, 63, 1), (0x55, 3, 0)] {
|
||||
assert_eq!(extrq(insertq(0, v, len, idx), len, idx), extrq(v, len, 0));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn decodes_the_console_only_instructions() {
|
||||
assert_eq!(decode(&[0x0F, 0x01, 0xFC]), Some((ConsoleOnly::Clzero, 3)));
|
||||
// clzero loop against r10 (4C 39 D0 = cmp rax, r10)
|
||||
assert_eq!(
|
||||
decode(&[0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x4C, 0x39, 0xD0, 0x72, 0xF4]),
|
||||
Some((ConsoleOnly::ClzeroLoop { end_reg: 10 }, 12))
|
||||
);
|
||||
// clzero loop against rdx (48 39 D0 = cmp rax, rdx)
|
||||
assert_eq!(
|
||||
decode(&[0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4]),
|
||||
Some((ConsoleOnly::ClzeroLoop { end_reg: 2 }, 12))
|
||||
);
|
||||
// the same loop after an address-size prefix: that one CLZERO alone
|
||||
assert_eq!(decode(&[0x67, 0x0F, 0x01, 0xFC, 0x48, 0x83, 0xC0, 0x40, 0x48, 0x39, 0xD0, 0x72, 0xF4]), Some((ConsoleOnly::Clzero, 4)));
|
||||
assert_eq!(decode(&[0x0F, 0x01, 0xFD]), Some((ConsoleOnly::Rdpru, 3)));
|
||||
assert_eq!(decode(&[0x0F, 0x01, 0xFA]), Some((ConsoleOnly::Monitorx, 3)));
|
||||
assert_eq!(decode(&[0x0F, 0x01, 0xFB]), Some((ConsoleOnly::Mwaitx, 3)));
|
||||
assert_eq!(decode(&[0x0F, 0x0B]), Some((ConsoleOnly::Ud2, 2)));
|
||||
// clwb [rax]; clwb [rcx+0x40]; clwb [rsp+8]; clwb [rip+disp32]; clwb [r8]
|
||||
assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x30]), Some((ConsoleOnly::Clwb, 4)));
|
||||
assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x71, 0x40]), Some((ConsoleOnly::Clwb, 5)));
|
||||
assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x74, 0x24, 0x08]), Some((ConsoleOnly::Clwb, 6)));
|
||||
assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x35, 1, 2, 3, 4]), Some((ConsoleOnly::Clwb, 8)));
|
||||
assert_eq!(decode(&[0x66, 0x41, 0x0F, 0xAE, 0x30]), Some((ConsoleOnly::Clwb, 5)));
|
||||
// rdpid rax; rdpid r9
|
||||
assert_eq!(decode(&[0xF3, 0x0F, 0xC7, 0xF8]), Some((ConsoleOnly::Rdpid(0), 4)));
|
||||
assert_eq!(decode(&[0xF3, 0x41, 0x0F, 0xC7, 0xF9]), Some((ConsoleOnly::Rdpid(9), 5)));
|
||||
// not console-only: clflushopt (/7), xsaveopt (no 66), a plain mov, truncated bytes
|
||||
// SSE4a, as a retail game has it (#216: insertq xmm0, xmm1 with length / index bytes)
|
||||
assert_eq!(decode(&[0xF2, 0x0F, 0x78, 0xC1, 0x08, 0x10]), Some((ConsoleOnly::Insertq { dst: 0, src: 1, reg: false, len: 8, idx: 16 }, 6)));
|
||||
assert_eq!(decode(&[0xF2, 0x45, 0x0F, 0x79, 0xC1]), Some((ConsoleOnly::Insertq { dst: 8, src: 9, reg: true, len: 0, idx: 0 }, 5)));
|
||||
assert_eq!(decode(&[0x66, 0x0F, 0x78, 0xC2, 0x04, 0x08]), Some((ConsoleOnly::Extrq { dst: 2, src: None, len: 4, idx: 8 }, 6)));
|
||||
assert_eq!(decode(&[0x66, 0x0F, 0x79, 0xCA]), Some((ConsoleOnly::Extrq { dst: 1, src: Some(2), len: 0, idx: 0 }, 4)));
|
||||
assert_eq!(decode(&[0xF2, 0x0F, 0x78, 0xC1, 0x08]), None, "an immediate missing");
|
||||
assert_eq!(decode(&[0x0F, 0x78, 0xC1, 0x08, 0x10]), None, "VMREAD without a prefix is not SSE4a");
|
||||
// prefixes as a Zen 5 runs them (Kalmarv on #209): the last of F2 / F3 decides, 66 next
|
||||
// to them does not; 0x67 and a REX before a legacy prefix are ignored
|
||||
let insertq = Some((ConsoleOnly::Insertq { dst: 0, src: 1, reg: false, len: 16, idx: 16 }, 7));
|
||||
for code in [[0x66, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0xF2, 0x66, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0xF3, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0x67, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0x41, 0xF2, 0x0F, 0x78, 0xC1, 0x10, 0x10]] {
|
||||
assert_eq!(decode(&code), insertq, "{code:02x?}");
|
||||
}
|
||||
for code in [[0xF2, 0xF3, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0xF3, 0x66, 0x0F, 0x78, 0xC1, 0x10, 0x10], [0x66, 0xF3, 0x0F, 0x78, 0xC0, 0x10, 0x10]] {
|
||||
assert_eq!(decode(&code), None, "#UD on the CPU: {code:02x?}");
|
||||
}
|
||||
assert_eq!(decode(&[0x67, 0x0F, 0x01, 0xFC]), Some((ConsoleOnly::Clzero, 4)));
|
||||
assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x38]), None);
|
||||
assert_eq!(decode(&[0x0F, 0xAE, 0x30]), None);
|
||||
assert_eq!(decode(&[0x48, 0x8B, 0x01]), None);
|
||||
assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x74, 0x24]), None);
|
||||
assert_eq!(decode(&[0x0F]), None);
|
||||
}
|
||||
}
|
||||
@@ -357,6 +357,15 @@ unsafe fn sse4a(code: *const u8, xmm: &mut [M128A; 16]) -> Option<usize> {
|
||||
}
|
||||
|
||||
unsafe extern "system" fn handler(info: *mut EXCEPTION_POINTERS) -> i32 {
|
||||
// an instruction of the console's CPU this one lacks: emulated, the title goes on
|
||||
// SAFETY: the system passes valid exception pointers.
|
||||
if unsafe { (*(*info).ExceptionRecord).ExceptionCode } == EXCEPTION_ILLEGAL_INSTRUCTION {
|
||||
// SAFETY: the faulting thread's context, for the exception being dispatched.
|
||||
let r = unsafe { crate::console_insn::emulate(&mut *(*info).ContextRecord) };
|
||||
if r != 0 {
|
||||
return r;
|
||||
}
|
||||
}
|
||||
// SAFETY: the system passes valid exception pointers.
|
||||
if unsafe { emulate_amd_only(info) } {
|
||||
return -1; // EXCEPTION_CONTINUE_EXECUTION
|
||||
|
||||
@@ -22,6 +22,7 @@
|
||||
//! on, pass every thread start and end on to the attached images.
|
||||
|
||||
#[cfg(windows)]
|
||||
mod console_insn;
|
||||
mod crash;
|
||||
pub mod prepare;
|
||||
pub mod resolve;
|
||||
|
||||
Reference in new issue
Block a user