Skip to main content

anvil/
cpu.rs

1use std::fmt;
2use std::ops::Deref;
3
4use crate::sys::AnvilCpuContext;
5
6/// The registers at a mid hook or block replacement, as SafetyHook saves
7/// them (`AnvilCpuContext`, 408 bytes). Reading is safe through `Deref`
8/// (`cpu.rcx`); writing is [`regs_mut`](Cpu::regs_mut). Valid only during the
9/// callback.
10#[repr(transparent)]
11pub struct Cpu(AnvilCpuContext);
12
13impl Cpu {
14    /// The context of a callback.
15    ///
16    /// # Safety
17    /// `raw` is the context Anvil passed to the callback that is running.
18    pub(crate) unsafe fn from_raw<'a>(raw: *mut AnvilCpuContext) -> Option<&'a mut Cpu> {
19        // SAFETY: Cpu is a transparent AnvilCpuContext; the caller's contract.
20        unsafe { raw.cast::<Cpu>().as_mut() }
21    }
22
23    /// The registers, writable: the game continues with what the callback
24    /// leaves in them. In a mid hook a changed `rip` ends the chain there.
25    ///
26    /// # Safety
27    /// The game's code at the site must work with the values written: a
28    /// pointer it dereferences, a stack it returns through. `rsp` and
29    /// `reserved` must not change.
30    pub unsafe fn regs_mut(&mut self) -> &mut AnvilCpuContext {
31        &mut self.0
32    }
33
34    /// XMM register `index` (0-15) as bytes.
35    pub fn xmm_bytes(&self, index: usize) -> [u8; 16] {
36        // SAFETY: every bit pattern is a valid [u8; 16].
37        unsafe { self.0.xmm[index].u8_ }
38    }
39
40    /// XMM register `index` (0-15) as four `f32`.
41    pub fn xmm_f32(&self, index: usize) -> [f32; 4] {
42        // SAFETY: every bit pattern is a valid f32.
43        unsafe { self.0.xmm[index].f32_ }
44    }
45
46    /// XMM register `index` (0-15) as two `f64` (`xmm0` holds a `double`
47    /// argument or result in the low one).
48    pub fn xmm_f64(&self, index: usize) -> [f64; 2] {
49        // SAFETY: every bit pattern is a valid f64.
50        unsafe { self.0.xmm[index].f64_ }
51    }
52}
53
54impl Deref for Cpu {
55    type Target = AnvilCpuContext;
56
57    fn deref(&self) -> &AnvilCpuContext {
58        &self.0
59    }
60}
61
62impl fmt::Debug for Cpu {
63    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
64        let c = &self.0;
65        f.debug_struct("Cpu")
66            .field("rax", &format_args!("{:#x}", c.rax))
67            .field("rcx", &format_args!("{:#x}", c.rcx))
68            .field("rdx", &format_args!("{:#x}", c.rdx))
69            .field("r8", &format_args!("{:#x}", c.r8))
70            .field("r9", &format_args!("{:#x}", c.r9))
71            .field("rsp", &format_args!("{:#x}", c.rsp))
72            .field("rip", &format_args!("{:#x}", c.rip))
73            .finish_non_exhaustive()
74    }
75}