Skip to main content

kvmtrace/
memory.rs

1//! Reading and writing guest-physical memory.
2//!
3//! The tracer needs guest memory for three jobs: fetching instruction
4//! bytes, walking page tables, and reading interrupt frames. It never
5//! needs more than a few bytes at a time, so the interface is tiny.
6
7use std::sync::RwLock;
8
9use crate::error::{Error, Result};
10
11/// Access to guest-physical memory.
12///
13/// Implement this for whatever owns the guest RAM. The crate ships
14/// [`MappedMemory`], which covers the common case where guest RAM is
15/// mapped into the tracer's own address space (your own VMM, or QEMU via
16/// the `LD_PRELOAD` interposer).
17pub trait GuestMemory: Send + Sync {
18    /// Copies `buf.len()` bytes starting at guest-physical address `gpa`.
19    fn read(&self, gpa: u64, buf: &mut [u8]) -> Result<()>;
20    /// Copies `data` to guest-physical address `gpa`.
21    fn write(&self, gpa: u64, data: &[u8]) -> Result<()>;
22
23    /// Reads a little-endian `u64`.
24    fn read_u64(&self, gpa: u64) -> Result<u64> {
25        let mut b = [0u8; 8];
26        self.read(gpa, &mut b)?;
27        Ok(u64::from_le_bytes(b))
28    }
29    /// Reads a little-endian `u32`.
30    fn read_u32(&self, gpa: u64) -> Result<u32> {
31        let mut b = [0u8; 4];
32        self.read(gpa, &mut b)?;
33        Ok(u32::from_le_bytes(b))
34    }
35}
36
37/// One slot of guest RAM mapped into this process.
38#[derive(Debug, Clone, Copy)]
39pub struct Region {
40    /// KVM memory-slot id (as passed to `KVM_SET_USER_MEMORY_REGION`).
41    pub slot: u32,
42    /// First guest-physical address.
43    pub gpa: u64,
44    /// Size in bytes.
45    pub size: u64,
46    /// Host virtual address of the first byte.
47    pub host: usize,
48}
49
50/// Guest RAM that is mapped into the current process, described by the
51/// same slot table KVM uses.
52///
53/// # Examples
54///
55/// ```
56/// use kvmtrace::memory::{GuestMemory, MappedMemory};
57///
58/// let mut ram = vec![0u8; 4096];
59/// let mem = MappedMemory::new();
60/// // SAFETY: `ram` outlives `mem` and is not resized.
61/// unsafe { mem.set_region(0, 0x1000, ram.len() as u64, ram.as_mut_ptr() as usize) };
62/// mem.write(0x1008, &[0xAA]).unwrap();
63/// let mut b = [0u8; 1];
64/// mem.read(0x1008, &mut b).unwrap();
65/// assert_eq!(b[0], 0xAA);
66/// assert!(mem.read(0x0, &mut b).is_err()); // not RAM
67/// ```
68#[derive(Debug, Default)]
69pub struct MappedMemory {
70    regions: RwLock<Vec<Region>>,
71}
72
73impl MappedMemory {
74    /// An empty slot table.
75    pub fn new() -> Self {
76        Self::default()
77    }
78
79    /// Adds, replaces or (with `size == 0`) removes a slot, exactly like
80    /// `KVM_SET_USER_MEMORY_REGION` does.
81    ///
82    /// # Safety
83    ///
84    /// `host .. host + size` must stay mapped and readable/writable for as
85    /// long as the slot is registered.
86    pub unsafe fn set_region(&self, slot: u32, gpa: u64, size: u64, host: usize) {
87        let mut r = self.regions.write().unwrap();
88        r.retain(|x| x.slot != slot);
89        if size != 0 {
90            r.push(Region { slot, gpa, size, host });
91            r.sort_by_key(|x| x.gpa);
92        }
93    }
94
95    /// A copy of the slot table.
96    pub fn regions(&self) -> Vec<Region> {
97        self.regions.read().unwrap().clone()
98    }
99
100    fn with_host<R>(&self, gpa: u64, len: usize, f: impl FnOnce(*mut u8) -> R) -> Result<R> {
101        let r = self.regions.read().unwrap();
102        for reg in r.iter() {
103            if gpa >= reg.gpa && gpa.checked_add(len as u64).is_some_and(|e| e <= reg.gpa + reg.size) {
104                return Ok(f((reg.host + (gpa - reg.gpa) as usize) as *mut u8));
105            }
106        }
107        Err(Error::Unmapped(gpa))
108    }
109}
110
111impl GuestMemory for MappedMemory {
112    fn read(&self, gpa: u64, buf: &mut [u8]) -> Result<()> {
113        // Split at slot boundaries one byte-run at a time; accesses are tiny.
114        match self.with_host(gpa, buf.len(), |p| unsafe {
115            std::ptr::copy_nonoverlapping(p as *const u8, buf.as_mut_ptr(), buf.len())
116        }) {
117            Ok(()) => Ok(()),
118            Err(_) if buf.len() > 1 => {
119                for (i, b) in buf.iter_mut().enumerate() {
120                    let mut one = [0u8];
121                    self.with_host(gpa + i as u64, 1, |p| unsafe { one[0] = *p })?;
122                    *b = one[0];
123                }
124                Ok(())
125            }
126            Err(e) => Err(e),
127        }
128    }
129
130    fn write(&self, gpa: u64, data: &[u8]) -> Result<()> {
131        self.with_host(gpa, data.len(), |p| unsafe { std::ptr::copy_nonoverlapping(data.as_ptr(), p, data.len()) })
132    }
133}