Skip to main content

kvmtrace/
minivm.rs

1//! A tiny 64-bit virtual machine, for tests and for learning.
2//!
3//! Real guests are big. To see exactly what the tracer does, it helps to
4//! have a guest small enough to read in full: a few hundred bytes of
5//! machine code, no firmware, no devices. `MiniVm` creates such a guest
6//! directly in 64-bit long mode:
7//!
8//! | guest-physical | contents                                        |
9//! |----------------|-------------------------------------------------|
10//! | `0x0500`       | GDT: null, 64-bit code (`0x08`), data (`0x10`)  |
11//! | `0x1000`       | PML4                                            |
12//! | `0x2000`       | PDPT                                            |
13//! | `0x3000`       | page directory: 2 MiB pages, except the second  |
14//! | `0x4000`       | page table for `0x20_0000..0x40_0000` (4 KiB pages) |
15//! | `0x6000`       | IDT (256 × 16 bytes)                            |
16//! | `0x1_0000`     | [`MiniVm::CODE`]: where your program goes       |
17//! | `0x8_0000`     | top of vCPU 0's stack (each vCPU gets 64 KiB)   |
18//!
19//! Linear addresses equal physical addresses (identity mapping), and the
20//! second 2 MiB is mapped with 4 KiB pages so tests can unmap single
21//! pages and provoke page faults.
22
23use std::sync::Arc;
24
25use kvm_bindings::*;
26use kvm_ioctls::{Kvm, VcpuFd, VmFd};
27
28use crate::error::{Error, Result};
29use crate::memory::{GuestMemory, MappedMemory};
30
31/// A minimal long-mode VM.
32pub struct MiniVm {
33    /// The `/dev/kvm` handle.
34    pub kvm: Kvm,
35    /// The VM.
36    pub vm: VmFd,
37    /// Guest RAM.
38    pub mem: Arc<MappedMemory>,
39    /// The vCPUs.
40    pub vcpus: Vec<VcpuFd>,
41    host: *mut u8,
42    size: usize,
43}
44
45// SAFETY: the raw pointer is only used to unmap the RAM on drop.
46unsafe impl Send for MiniVm {}
47
48impl MiniVm {
49    /// Where programs are loaded.
50    pub const CODE: u64 = 0x1_0000;
51    /// GDT.
52    pub const GDT: u64 = 0x500;
53    /// PML4.
54    pub const PML4: u64 = 0x1000;
55    /// The 4 KiB page table covering `0x20_0000..0x40_0000`.
56    pub const PT: u64 = 0x4000;
57    /// IDT.
58    pub const IDT: u64 = 0x6000;
59    /// Top of vCPU 0's stack.
60    pub const STACK_TOP: u64 = 0x8_0000;
61
62    /// Creates a VM with `mem_mib` MiB of RAM and `vcpus` vCPUs, all in
63    /// 64-bit mode at [`MiniVm::CODE`] with interrupts disabled.
64    pub fn new(mem_mib: usize, vcpus: u32) -> Result<MiniVm> {
65        let kvm = Kvm::new().map_err(Error::kvm("open /dev/kvm"))?;
66        let vm = kvm.create_vm().map_err(Error::kvm("KVM_CREATE_VM"))?;
67        let size = mem_mib << 20;
68        // SAFETY: anonymous private mapping; checked below.
69        let host = unsafe {
70            libc::mmap(
71                std::ptr::null_mut(),
72                size,
73                libc::PROT_READ | libc::PROT_WRITE,
74                libc::MAP_PRIVATE | libc::MAP_ANONYMOUS | libc::MAP_NORESERVE,
75                -1,
76                0,
77            )
78        };
79        if host == libc::MAP_FAILED {
80            return Err(Error::Io(std::io::Error::last_os_error()));
81        }
82        let host = host as *mut u8;
83        let region = kvm_userspace_memory_region {
84            slot: 0,
85            guest_phys_addr: 0,
86            memory_size: size as u64,
87            userspace_addr: host as u64,
88            flags: 0,
89        };
90        // SAFETY: the mapping lives as long as the VM (unmapped in Drop).
91        unsafe { vm.set_user_memory_region(region) }.map_err(Error::kvm("KVM_SET_USER_MEMORY_REGION"))?;
92        let mem = Arc::new(MappedMemory::new());
93        // SAFETY: same mapping, same lifetime.
94        unsafe { mem.set_region(0, 0, size as u64, host as usize) };
95
96        let mut me = MiniVm { kvm, vm, mem, vcpus: Vec::new(), host, size };
97        me.build_tables()?;
98        let cpuid = me.kvm.get_supported_cpuid(KVM_MAX_CPUID_ENTRIES).map_err(Error::kvm("KVM_GET_SUPPORTED_CPUID"))?;
99        for id in 0..vcpus {
100            let v = me.vm.create_vcpu(id as u64).map_err(Error::kvm("KVM_CREATE_VCPU"))?;
101            v.set_cpuid2(&cpuid).map_err(Error::kvm("KVM_SET_CPUID2"))?;
102            me.vcpus.push(v);
103            me.reset_vcpu(id as usize, Self::CODE, Self::STACK_TOP - id as u64 * 0x1_0000)?;
104        }
105        Ok(me)
106    }
107
108    fn w64(&self, gpa: u64, v: u64) {
109        self.mem.write(gpa, &v.to_le_bytes()).expect("MiniVm table write");
110    }
111
112    fn build_tables(&mut self) -> Result<()> {
113        self.w64(Self::PML4, 0x2000 | 3);
114        self.w64(0x2000, 0x3000 | 3);
115        for i in 0..512u64 {
116            self.w64(0x3000 + i * 8, (i << 21) | 0x83);
117        }
118        self.w64(0x3000 + 8, Self::PT | 3);
119        for i in 0..512u64 {
120            self.w64(Self::PT + i * 8, (0x20_0000 + (i << 12)) | 3);
121        }
122        self.w64(Self::GDT, 0);
123        self.w64(Self::GDT + 8, 0x00af_9a00_0000_ffff);
124        self.w64(Self::GDT + 16, 0x00cf_9200_0000_ffff);
125        Ok(())
126    }
127
128    /// Puts vCPU `idx` in 64-bit mode at `rip` with stack `rsp`.
129    pub fn reset_vcpu(&mut self, idx: usize, rip: u64, rsp: u64) -> Result<()> {
130        let v = &self.vcpus[idx];
131        let mut s = v.get_sregs().map_err(Error::kvm("KVM_GET_SREGS"))?;
132        let code = kvm_segment {
133            base: 0,
134            limit: 0xffff_ffff,
135            selector: 0x08,
136            type_: 11,
137            present: 1,
138            dpl: 0,
139            db: 0,
140            s: 1,
141            l: 1,
142            g: 1,
143            avl: 0,
144            unusable: 0,
145            padding: 0,
146        };
147        let data = kvm_segment { selector: 0x10, type_: 3, l: 0, db: 1, ..code };
148        s.cs = code;
149        s.ds = data;
150        s.es = data;
151        s.ss = data;
152        s.fs = data;
153        s.gs = data;
154        s.gdt = kvm_dtable { base: Self::GDT, limit: 23, padding: [0; 3] };
155        s.idt = kvm_dtable { base: Self::IDT, limit: 4095, padding: [0; 3] };
156        s.cr3 = Self::PML4;
157        s.cr4 = 1 << 5 | 1 << 9 | 1 << 10 | 1 << 18; // PAE, OSFXSR, OSXMMEXCPT, OSXSAVE
158        s.cr0 = 0x8000_0033; // PG, NE, ET, MP, PE
159        s.efer = 0x500 | 1 | 1 << 11; // LME, LMA, SCE, NXE
160        v.set_sregs(&s).map_err(Error::kvm("KVM_SET_SREGS"))?;
161        let r = kvm_regs { rip, rsp, rflags: 2, ..Default::default() };
162        v.set_regs(&r).map_err(Error::kvm("KVM_SET_REGS"))?;
163        // Enable x87/SSE/AVX state so AVX2 gathers can run.
164        let xcr = kvm_xcrs { nr_xcrs: 1, flags: 0, xcrs: [kvm_xcr { xcr: 0, reserved: 0, value: 7 }; 16], padding: [0; 16] };
165        let _ = v.set_xcrs(&xcr);
166        Ok(())
167    }
168
169    /// Copies `bytes` to guest-physical address `gpa`.
170    pub fn load(&self, gpa: u64, bytes: &[u8]) {
171        self.mem.write(gpa, bytes).expect("MiniVm::load outside RAM");
172    }
173
174    /// Points IDT vector `vector` at `handler` (a 64-bit interrupt gate).
175    pub fn set_gate(&self, vector: u8, handler: u64) {
176        let lo = (handler & 0xffff) | (0x08 << 16) | (0x8e00u64 << 32) | (((handler >> 16) & 0xffff) << 48);
177        self.w64(Self::IDT + vector as u64 * 16, lo);
178        self.w64(Self::IDT + vector as u64 * 16 + 8, handler >> 32);
179    }
180
181    /// Marks the 4 KiB page at `la` (which must be in `0x20_0000..0x40_0000`)
182    /// not present.
183    pub fn unmap_page(&self, la: u64) {
184        assert!((0x20_0000..0x40_0000).contains(&la));
185        self.w64(Self::PT + ((la - 0x20_0000) >> 12) * 8, 0);
186    }
187
188    /// Sets MSRs on every vCPU (for example `LSTAR` for SYSCALL).
189    pub fn set_msrs(&self, entries: &[(u32, u64)]) -> Result<()> {
190        let e: Vec<kvm_msr_entry> = entries.iter().map(|&(index, data)| kvm_msr_entry { index, data, ..Default::default() }).collect();
191        let m = Msrs::from_entries(&e).map_err(|_| Error::Format("too many MSRs".into()))?;
192        for v in &self.vcpus {
193            v.set_msrs(&m).map_err(Error::kvm("KVM_SET_MSRS"))?;
194        }
195        Ok(())
196    }
197
198    /// Guest RAM as a shareable [`GuestMemory`].
199    pub fn memory(&self) -> Arc<dyn GuestMemory> {
200        self.mem.clone()
201    }
202}
203
204impl Drop for MiniVm {
205    fn drop(&mut self) {
206        self.vcpus.clear();
207        // SAFETY: we created this mapping in `new` and nothing else refers to it now.
208        unsafe { libc::munmap(self.host as *mut _, self.size) };
209    }
210}