Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion HANDOFF.md
Original file line number Diff line number Diff line change
Expand Up @@ -1820,7 +1820,9 @@ right after its first `CreateShaderResourceView` (the first descriptor written i
the Zen 2 instructions such a CPU lacks – `clwb` (Intel: Ice Lake+), `clzero`, `rdpru`, `monitorx` / `mwaitx`
(AMD only), `rdpid` – and the vectored handler (`eh::emulate_console_only`) emulates them and steps over
(`clwb` / `monitorx` / `mwaitx`: nothing, the PC's memory is coherent; `clzero`: 64 zero bytes at rAX; `rdpru`:
QueryPerformanceCounter; `rdpid`: the processor number). Logged once per instruction. Any other illegal instruction
QueryPerformanceCounter; `rdpid`: the processor number). SSE4a (AMD only): `extrq` / `insertq` on the exception's
XMM registers, `movntss` / `movntsd` as a plain store of the low dword / quadword (fs / gs-relative ones are not
emulated). Logged once per instruction. Any other illegal instruction
(and `ud2`, a title's own trap) is logged with its 16 code bytes, in the first-chance handler and in the crash line.
SHA-NI is not emulated (also missing on those CPUs): add it if a title's code bytes show `0F 38 C8..CD`.

Expand Down
70 changes: 70 additions & 0 deletions crates/xcl/src/eh.rs
Original file line number Diff line number Diff line change
Expand Up @@ -370,6 +370,22 @@ unsafe fn emulate_console_only(ctx: &mut windows_sys::Win32::System::Diagnostics
d.Low = crate::insn::insertq(d.Low, s.Low, len, idx);
d.High = 0;
}
ConsoleOnly::Movnts { bytes, src, mem } => {
let regs = [
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 at = crate::insn::address(&mem, &regs, ctx.Rip + len as u64) as usize;
if !crate::gpu::shader::readable(at, bytes as usize) {
return 0; // the real store faults there too
}
let v = ctx.Anonymous.FltSave.XmmRegisters[src as usize & 15].Low;
if bytes == 8 {
(at as *mut u64).write_unaligned(v);
} else {
(at as *mut u32).write_unaligned(v as u32);
}
}
}
ctx.Rip += len as u64;
-1 // EXCEPTION_CONTINUE_EXECUTION
Expand Down Expand Up @@ -946,4 +962,58 @@ mod tests {
}
modules::unregister_mapped(code);
}

/// MOVNTSS / MOVNTSD in a title image: on a CPU without SSE4a (any Intel) they raise
/// STATUS_ILLEGAL_INSTRUCTION and the handler does the store; on an AMD CPU they run
/// natively. Either way the memory holds the same values.
#[test]
fn sse4a_streaming_stores_run_in_a_title_image() {
use windows_sys::Win32::System::Memory::{VirtualAlloc, VirtualFree, MEM_COMMIT, MEM_RELEASE, MEM_RESERVE, PAGE_EXECUTE_READWRITE};
// s(p, v): movq xmm0, rdx; movntsd [rcx], xmm0; ret
// t(p, v): movq xmm1, rdx; movntss [rcx+4], xmm1 (a SIB without an index); ret
// u(p, v): movq xmm2, rdx; movntsd [rip+disp32], xmm2 (into the page's last 8 bytes); ret
let s_code: &[u8] = &[0x66, 0x48, 0x0F, 0x6E, 0xC2, 0xF2, 0x0F, 0x2B, 0x01, 0xC3];
let t_code: &[u8] = &[0x66, 0x48, 0x0F, 0x6E, 0xCA, 0xF3, 0x0F, 0x2B, 0x4C, 0x21, 0x04, 0xC3];
unsafe {
let page = VirtualAlloc(std::ptr::null(), 4096, MEM_COMMIT | MEM_RESERVE, PAGE_EXECUTE_READWRITE) as *mut u8;
assert!(!page.is_null());
std::ptr::write_bytes(page, 0xCC, 4096);
std::ptr::copy_nonoverlapping(s_code.as_ptr(), page, s_code.len());
std::ptr::copy_nonoverlapping(t_code.as_ptr(), page.add(32), t_code.len());
// u at 64: the store's disp32 is relative to the end of the movntsd (64 + 5 + 8)
let disp = (4096 - 8 - (64 + 5 + 8)) as u32;
let mut u_code = vec![0x66, 0x48, 0x0F, 0x6E, 0xD2, 0xF2, 0x0F, 0x2B, 0x15];
u_code.extend_from_slice(&disp.to_le_bytes());
u_code.push(0xC3);
std::ptr::copy_nonoverlapping(u_code.as_ptr(), page.add(64), u_code.len());
modules::register_mapped(std::sync::Arc::new(modules::MappedModule {
name: "sse4a_test.exe".into(),
path: "sse4a_test.exe".into(),
base: page as usize,
size: 4096,
entry_rva: 0,
is_dll: false,
exports: Default::default(),
tls_callbacks: Default::default(),
no_thread_calls: Default::default(),
initialized: Default::default(),
stack_reserve: 0,
}));
let veh = windows_sys::Win32::System::Diagnostics::Debug::AddVectoredExceptionHandler(1, Some(cpp_exception_logger));
let s: extern "system" fn(*mut u64, u64) = std::mem::transmute(page);
let t: extern "system" fn(*mut u32, u64) = std::mem::transmute(page.add(32));
let u: extern "system" fn(*mut u64, u64) = std::mem::transmute(page.add(64));
let mut out = [0u64; 2];
s(out.as_mut_ptr(), 0x0123_4567_89AB_CDEF);
assert_eq!(out[0], 0x0123_4567_89AB_CDEF, "movntsd stores the low quadword");
let mut words = [0u32; 3];
t(words.as_mut_ptr(), 0xFFFF_FFFF_DEAD_BEEF);
assert_eq!(words, [0, 0xDEAD_BEEF, 0], "movntss stores the low dword at [rcx+4] and nothing else");
u(std::ptr::null_mut(), 0x1122_3344_5566_7788);
assert_eq!((page.add(4096 - 8) as *const u64).read_unaligned(), 0x1122_3344_5566_7788, "rip-relative movntsd");
windows_sys::Win32::System::Diagnostics::Debug::RemoveVectoredExceptionHandler(veh);
modules::unregister_mapped(page as usize);
VirtualFree(page as _, 0, MEM_RELEASE);
}
}
}
131 changes: 127 additions & 4 deletions crates/xcl/src/insn.rs
Original file line number Diff line number Diff line change
@@ -1,8 +1,22 @@
//! 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.
//! SHA) or on any Intel CPU (CLZERO, RDPRU, MONITORX / MWAITX and SSE4a's EXTRQ / INSERTQ /
//! MOVNTSS / MOVNTSD, which are AMD's). The exception handler (`eh`) emulates the ones decoded
//! here and steps over them.

/// A memory operand (ModRM with its SIB and displacement): `base + index * scale + disp`, or
/// with `rip` the address of the next instruction + disp; with `a32` (an 0x67 prefix) the
/// address is 32 bits. Registers in CONTEXT order (rax, rcx, rdx, rbx, rsp, rbp, rsi, rdi,
/// r8..r15).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Mem {
pub base: Option<u8>,
pub index: Option<u8>,
pub scale: u8,
pub disp: i32,
pub rip: bool,
pub a32: bool,
}

/// A console-only instruction at the faulting address.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
Expand All @@ -29,6 +43,9 @@ pub enum ConsoleOnly {
/// 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 },
/// SSE4a `movntss m32, xmm` (F3 0F 2B /r, `bytes` 4) / `movntsd m64, xmm` (F2 0F 2B /r,
/// `bytes` 8): the low dword / quadword of XMM `src` stored without the cache
Movnts { bytes: u8, src: u8, mem: Mem },
/// `ud2`: the title's own trap (not emulated)
Ud2,
}
Expand Down Expand Up @@ -61,6 +78,52 @@ pub fn insertq(dst: u64, src: u64, len: u8, idx: u8) -> u64 {
(dst & !mask) | ((src & ones).checked_shl(idx).unwrap_or(0) & mask)
}

/// The address of a memory operand: `regs` in CONTEXT order, `next` the address of the
/// instruction after it (for a rip-relative operand).
pub fn address(m: &Mem, regs: &[u64; 16], next: u64) -> u64 {
let base = if m.rip { next } else { m.base.map_or(0, |r| regs[r as usize & 15]) };
let index = m.index.map_or(0, |r| regs[r as usize & 15].wrapping_mul(m.scale as u64));
let a = base.wrapping_add(index).wrapping_add(m.disp as i64 as u64);
if m.a32 {
a & 0xFFFF_FFFF
} else {
a
}
}

/// The memory operand of the ModRM byte at `b[0]` (with its SIB and displacement) and its
/// length; None for a register operand or when the bytes run out. REX.B extends the base, REX.X
/// the index.
fn mem_operand(b: &[u8], rex: u8, a32: bool) -> Option<(Mem, usize)> {
let len = modrm_len(b)?;
let (md, rm) = (b[0] >> 6, b[0] & 7);
if md == 3 {
return None;
}
let (rex_b, rex_x) = ((rex & 1) << 3, (rex & 2) << 2);
let mut m = Mem { base: Some(rm | rex_b), index: None, scale: 1, disp: 0, rip: false, a32 };
let mut at = 1;
if rm == 4 {
let sib = b[1];
let (index, base) = (((sib >> 3) & 7) | rex_x, sib & 7);
m.scale = 1 << (sib >> 6);
// index 100 is no index (with REX.X it is r12)
m.index = (index != 4).then_some(index);
// base 101 with mod 00 is no base and a disp32 (r13 takes mod 01)
m.base = (md != 0 || base != 5).then_some(base | rex_b);
at = 2;
} else if md == 0 && rm == 5 {
m.base = None;
m.rip = true;
}
m.disp = match len - at {
0 => 0,
1 => b[at] as i8 as i32,
_ => i32::from_le_bytes([b[at], b[at + 1], b[at + 2], b[at + 3]]),
};
Some((m, len))
}

/// 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> {
Expand Down Expand Up @@ -89,6 +152,8 @@ 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);
// for a memory operand: an fs / gs override (its base is not in the context), 0x67
let (mut fs_gs, mut a32) = (false, false);
while let Some(&b) = code.get(i) {
match b {
0x66 => p66 = true,
Expand All @@ -97,7 +162,9 @@ pub fn decode(code: &[u8]) -> Option<(ConsoleOnly, usize)> {
pf3 = true;
rep = 0xF3;
}
0x2E | 0x3E | 0x26 | 0x36 | 0x64 | 0x65 | 0x67 => {}
0x64 | 0x65 => fs_gs = true,
0x67 => a32 = true,
0x2E | 0x3E | 0x26 | 0x36 => {}
// REX counts only right before the opcode: one before a legacy prefix is ignored
0x40..=0x4F => {
rex = b;
Expand Down Expand Up @@ -151,6 +218,14 @@ pub fn decode(code: &[u8]) -> Option<(ConsoleOnly, usize)> {
_ => None,
}
}
// SSE4a scalar streaming stores, memory operands only: F3 0F 2B movntss, F2 0F 2B
// movntsd (the last of F2 / F3 decides; without them it is movntps, with 66 alone
// movntpd). One through fs / gs is left to fault.
(0x2B, Some(m)) if rep != 0 && m >> 6 != 3 && !fs_gs => {
let (mem, len) = mem_operand(&code[i + 2..], rex, a32)?;
let src = ((m >> 3) & 7) | (rex & 4) << 1;
Some((ConsoleOnly::Movnts { bytes: if rep == 0xF2 { 8 } else { 4 }, src, mem }, i + 2 + len))
}
// 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
Expand Down Expand Up @@ -234,4 +309,52 @@ mod tests {
assert_eq!(decode(&[0x66, 0x0F, 0xAE, 0x74, 0x24]), None);
assert_eq!(decode(&[0x0F]), None);
}

#[test]
fn decodes_the_sse4a_streaming_stores() {
let m = |base: Option<u8>, index: Option<u8>, scale: u8, disp: i32| Mem { base, index, scale, disp, rip: false, a32: false };
// movntsd [rax], xmm0; movntss [rsp+8], xmm1; movntsd [rip+0x10], xmm2
assert_eq!(decode(&[0xF2, 0x0F, 0x2B, 0x00]), Some((ConsoleOnly::Movnts { bytes: 8, src: 0, mem: m(Some(0), None, 1, 0) }, 4)));
assert_eq!(decode(&[0xF3, 0x0F, 0x2B, 0x4C, 0x24, 0x08]), Some((ConsoleOnly::Movnts { bytes: 4, src: 1, mem: m(Some(4), None, 1, 8) }, 6)));
assert_eq!(
decode(&[0xF2, 0x0F, 0x2B, 0x15, 0x10, 0, 0, 0]),
Some((ConsoleOnly::Movnts { bytes: 8, src: 2, mem: Mem { rip: true, ..m(None, None, 1, 0x10) } }, 8))
);
// movntsd [r8+r12*4-4], xmm9 (REX.RXB); movntsd [r13+0], xmm0; movntsd [0x1000], xmm0 (a SIB
// without base or index); movntss [rbp+rsi*8+0x12345678], xmm3
assert_eq!(decode(&[0xF2, 0x47, 0x0F, 0x2B, 0x4C, 0xA0, 0xFC]), Some((ConsoleOnly::Movnts { bytes: 8, src: 9, mem: m(Some(8), Some(12), 4, -4) }, 7)));
assert_eq!(decode(&[0xF2, 0x41, 0x0F, 0x2B, 0x45, 0x00]), Some((ConsoleOnly::Movnts { bytes: 8, src: 0, mem: m(Some(13), None, 1, 0) }, 6)));
assert_eq!(decode(&[0xF2, 0x0F, 0x2B, 0x04, 0x25, 0, 0x10, 0, 0]), Some((ConsoleOnly::Movnts { bytes: 8, src: 0, mem: m(None, None, 1, 0x1000) }, 9)));
assert_eq!(
decode(&[0xF3, 0x0F, 0x2B, 0x9C, 0xF5, 0x78, 0x56, 0x34, 0x12]),
Some((ConsoleOnly::Movnts { bytes: 4, src: 3, mem: m(Some(5), Some(6), 8, 0x1234_5678) }, 9))
);
// the last of F2 / F3 decides, 66 next to them does not; 0x67 makes the address 32 bits
assert_eq!(decode(&[0xF2, 0xF3, 0x0F, 0x2B, 0x00]).map(|(c, _)| c), Some(ConsoleOnly::Movnts { bytes: 4, src: 0, mem: m(Some(0), None, 1, 0) }));
assert_eq!(decode(&[0x66, 0xF2, 0x0F, 0x2B, 0x00]).map(|(c, _)| c), Some(ConsoleOnly::Movnts { bytes: 8, src: 0, mem: m(Some(0), None, 1, 0) }));
assert_eq!(decode(&[0x67, 0xF2, 0x0F, 0x2B, 0x00]), Some((ConsoleOnly::Movnts { bytes: 8, src: 0, mem: Mem { a32: true, ..m(Some(0), None, 1, 0) } }, 5)));
// not these: movntps (no prefix), movntpd (66), a register operand, through gs, cut short
assert_eq!(decode(&[0x0F, 0x2B, 0x00]), None);
assert_eq!(decode(&[0x66, 0x0F, 0x2B, 0x00]), None);
assert_eq!(decode(&[0xF2, 0x0F, 0x2B, 0xC0]), None);
assert_eq!(decode(&[0x65, 0xF2, 0x0F, 0x2B, 0x04, 0x25, 0, 0x10, 0, 0]), None);
assert_eq!(decode(&[0xF2, 0x0F, 0x2B, 0x44]), None);
assert_eq!(decode(&[0xF2, 0x0F, 0x2B, 0x80, 1, 2, 3]), None);
}

#[test]
fn memory_operand_addresses() {
let mut regs = [0u64; 16];
regs[4] = 0x1000; // rsp
regs[8] = 0x2000; // r8
regs[12] = 3; // r12
regs[0] = 0x1_FFFF_FFF0; // rax
let m = Mem { base: Some(8), index: Some(12), scale: 4, disp: -4, rip: false, a32: false };
assert_eq!(address(&m, &regs, 0), 0x2000 + 12 - 4);
assert_eq!(address(&Mem { base: Some(4), index: None, scale: 1, disp: 8, ..m }, &regs, 0), 0x1008);
assert_eq!(address(&Mem { base: None, index: None, disp: -0x10, rip: true, ..m }, &regs, 0x5000), 0x4FF0);
assert_eq!(address(&Mem { base: None, index: None, disp: 0x1000, ..m }, &regs, 0x5000), 0x1000);
// a 32-bit address wraps at 4 GiB
assert_eq!(address(&Mem { base: Some(0), index: None, disp: 0x20, a32: true, ..m }, &regs, 0), 0x10);
}
}