Skip to main content

kvmtrace/
state.rs

1//! A snapshot of the architectural state of one virtual CPU.
2//!
3//! KVM hands us registers in two structures, `kvm_regs` and `kvm_sregs`.
4//! [`CpuState`] merges them into one value that is cheap to copy and easy
5//! to ask questions of: *which mode is the CPU in?*, *what is the current
6//! privilege level?*, *what is the base of the FS segment?*
7
8use kvm_bindings::{kvm_regs, kvm_segment, kvm_sregs};
9
10/// One segment register, as the CPU sees it (selector plus the hidden,
11/// cached descriptor).
12#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
13pub struct Segment {
14    /// The visible 16-bit selector.
15    pub selector: u16,
16    /// The cached base address.
17    pub base: u64,
18    /// The cached limit, already scaled by the granularity bit.
19    pub limit: u32,
20    /// Descriptor type field (4 bits).
21    pub type_: u8,
22    /// Descriptor privilege level.
23    pub dpl: u8,
24    /// Present bit.
25    pub present: bool,
26    /// Default operation size (D/B bit): 32-bit when set.
27    pub db: bool,
28    /// Long-mode code segment (L bit).
29    pub l: bool,
30    /// The segment register holds no usable descriptor.
31    pub unusable: bool,
32}
33
34impl From<&kvm_segment> for Segment {
35    fn from(s: &kvm_segment) -> Self {
36        Segment {
37            selector: s.selector,
38            base: s.base,
39            limit: s.limit,
40            type_: s.type_,
41            dpl: s.dpl,
42            present: s.present != 0,
43            db: s.db != 0,
44            l: s.l != 0,
45            unusable: s.unusable != 0,
46        }
47    }
48}
49
50/// The execution mode the CPU is in, which decides how instructions are
51/// decoded and how addresses are formed.
52#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
53pub enum CpuMode {
54    /// Real-address mode (CR0.PE = 0).
55    Real,
56    /// Virtual-8086 mode (EFLAGS.VM = 1).
57    Virtual8086,
58    /// Protected mode with a 16-bit code segment.
59    Protected16,
60    /// Protected mode with a 32-bit code segment.
61    Protected32,
62    /// IA-32e compatibility mode, 16-bit code segment.
63    Compat16,
64    /// IA-32e compatibility mode, 32-bit code segment.
65    Compat32,
66    /// 64-bit mode.
67    Long64,
68}
69
70impl CpuMode {
71    /// Instruction-stream bitness for the decoder: 16, 32 or 64.
72    pub fn bitness(self) -> u32 {
73        match self {
74            CpuMode::Real | CpuMode::Virtual8086 | CpuMode::Protected16 | CpuMode::Compat16 => 16,
75            CpuMode::Protected32 | CpuMode::Compat32 => 32,
76            CpuMode::Long64 => 64,
77        }
78    }
79
80    /// A stable small integer used by the on-disk formats.
81    pub fn as_u8(self) -> u8 {
82        self as u8
83    }
84
85    /// Inverse of [`CpuMode::as_u8`].
86    pub fn from_u8(v: u8) -> Option<CpuMode> {
87        use CpuMode::*;
88        [Real, Virtual8086, Protected16, Protected32, Compat16, Compat32, Long64].get(v as usize).copied()
89    }
90}
91
92/// Index of a segment register inside [`CpuState::seg`].
93#[derive(Debug, Clone, Copy, PartialEq, Eq)]
94#[repr(usize)]
95pub enum SegReg {
96    /// ES
97    Es = 0,
98    /// CS
99    Cs = 1,
100    /// SS
101    Ss = 2,
102    /// DS
103    Ds = 3,
104    /// FS
105    Fs = 4,
106    /// GS
107    Gs = 5,
108}
109
110/// Architectural state of one vCPU at an instruction boundary.
111///
112/// General-purpose registers are stored in the hardware encoding order
113/// (`rax, rcx, rdx, rbx, rsp, rbp, rsi, rdi, r8 … r15`), so that
114/// `gpr[n]` is register number `n` in a ModRM byte.
115#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
116pub struct CpuState {
117    /// General-purpose registers in encoding order.
118    pub gpr: [u64; 16],
119    /// Instruction pointer (an offset inside CS).
120    pub rip: u64,
121    /// RFLAGS as the guest sees it. KVM hides the TF bit it sets for
122    /// single-stepping, so this is the guest's own view.
123    pub rflags: u64,
124    /// Segment registers, indexed by [`SegReg`].
125    pub seg: [Segment; 6],
126    /// CR0.
127    pub cr0: u64,
128    /// CR2 (last page-fault linear address).
129    pub cr2: u64,
130    /// CR3 (page-table root, plus PCID in the low 12 bits when CR4.PCIDE is set).
131    pub cr3: u64,
132    /// CR4.
133    pub cr4: u64,
134    /// CR8 (task priority).
135    pub cr8: u64,
136    /// IA32_EFER.
137    pub efer: u64,
138    /// GDTR base.
139    pub gdt_base: u64,
140    /// GDTR limit.
141    pub gdt_limit: u16,
142    /// IDTR base.
143    pub idt_base: u64,
144    /// IDTR limit.
145    pub idt_limit: u16,
146    /// The task register (its base locates the TSS, which holds the I/O
147    /// permission bitmap).
148    pub tr: Segment,
149}
150
151/// Encoding-order indices of the general-purpose registers.
152#[allow(missing_docs)]
153pub mod gpr {
154    pub const RAX: usize = 0;
155    pub const RCX: usize = 1;
156    pub const RDX: usize = 2;
157    pub const RBX: usize = 3;
158    pub const RSP: usize = 4;
159    pub const RBP: usize = 5;
160    pub const RSI: usize = 6;
161    pub const RDI: usize = 7;
162}
163
164pub(crate) const CR0_PE: u64 = 1;
165pub(crate) const CR0_WP: u64 = 1 << 16;
166pub(crate) const CR0_PG: u64 = 1 << 31;
167pub(crate) const CR4_PSE: u64 = 1 << 4;
168pub(crate) const CR4_PAE: u64 = 1 << 5;
169pub(crate) const CR4_PCIDE: u64 = 1 << 17;
170pub(crate) const CR4_LA57: u64 = 1 << 12;
171pub(crate) const CR4_SMEP: u64 = 1 << 20;
172pub(crate) const CR4_SMAP: u64 = 1 << 21;
173pub(crate) const EFER_LMA: u64 = 1 << 10;
174pub(crate) const EFER_NXE: u64 = 1 << 11;
175pub(crate) const RFLAGS_DF: u64 = 1 << 10;
176pub(crate) const RFLAGS_VM: u64 = 1 << 17;
177pub(crate) const RFLAGS_AC: u64 = 1 << 18;
178
179impl CpuState {
180    /// Builds a snapshot from the two structures KVM returns.
181    pub fn from_kvm(r: &kvm_regs, s: &kvm_sregs) -> CpuState {
182        CpuState {
183            gpr: [
184                r.rax, r.rcx, r.rdx, r.rbx, r.rsp, r.rbp, r.rsi, r.rdi, r.r8, r.r9, r.r10, r.r11, r.r12, r.r13, r.r14,
185                r.r15,
186            ],
187            rip: r.rip,
188            rflags: r.rflags,
189            seg: [
190                (&s.es).into(),
191                (&s.cs).into(),
192                (&s.ss).into(),
193                (&s.ds).into(),
194                (&s.fs).into(),
195                (&s.gs).into(),
196            ],
197            cr0: s.cr0,
198            cr2: s.cr2,
199            cr3: s.cr3,
200            cr4: s.cr4,
201            cr8: s.cr8,
202            efer: s.efer,
203            gdt_base: s.gdt.base,
204            gdt_limit: s.gdt.limit,
205            idt_base: s.idt.base,
206            idt_limit: s.idt.limit,
207            tr: (&s.tr).into(),
208        }
209    }
210
211    /// A segment register.
212    pub fn segment(&self, r: SegReg) -> &Segment {
213        &self.seg[r as usize]
214    }
215
216    /// The CPU mode, worked out from CR0, EFER, RFLAGS and the CS descriptor.
217    pub fn mode(&self) -> CpuMode {
218        let cs = self.segment(SegReg::Cs);
219        if self.cr0 & CR0_PE == 0 {
220            CpuMode::Real
221        } else if self.efer & EFER_LMA != 0 {
222            if cs.l {
223                CpuMode::Long64
224            } else if cs.db {
225                CpuMode::Compat32
226            } else {
227                CpuMode::Compat16
228            }
229        } else if self.rflags & RFLAGS_VM != 0 {
230            CpuMode::Virtual8086
231        } else if cs.db {
232            CpuMode::Protected32
233        } else {
234            CpuMode::Protected16
235        }
236    }
237
238    /// RFLAGS.IOPL, the privilege level needed for port I/O.
239    pub fn iopl(&self) -> u8 {
240        ((self.rflags >> 12) & 3) as u8
241    }
242
243    /// Current privilege level (0 = most privileged, 3 = user).
244    ///
245    /// The CPL is the DPL of the SS descriptor, which is what KVM itself
246    /// uses. In real mode it is 0; in virtual-8086 mode it is 3.
247    pub fn cpl(&self) -> u8 {
248        match self.mode() {
249            CpuMode::Real => 0,
250            CpuMode::Virtual8086 => 3,
251            _ => self.segment(SegReg::Ss).dpl & 3,
252        }
253    }
254
255    /// The page-table root without the PCID / flag bits.
256    pub fn page_table_root(&self) -> u64 {
257        if self.cr4 & CR4_PCIDE != 0 || self.efer & EFER_LMA != 0 {
258            self.cr3 & 0x000f_ffff_ffff_f000
259        } else if self.cr4 & CR4_PAE != 0 {
260            self.cr3 & 0xffff_ffe0
261        } else {
262            self.cr3 & 0xffff_f000
263        }
264    }
265
266    /// Process-context identifier, when CR4.PCIDE is set.
267    pub fn pcid(&self) -> Option<u16> {
268        (self.cr4 & CR4_PCIDE != 0).then_some((self.cr3 & 0xfff) as u16)
269    }
270
271    /// Linear address of the current instruction (CS.base + RIP,
272    /// truncated to the address width of the mode).
273    pub fn linear_rip(&self) -> u64 {
274        match self.mode() {
275            CpuMode::Long64 => self.rip,
276            CpuMode::Real | CpuMode::Virtual8086 => (self.segment(SegReg::Cs).base + (self.rip & 0xffff)) & 0xf_ffff_ffff,
277            _ => (self.segment(SegReg::Cs).base.wrapping_add(self.rip)) & 0xffff_ffff,
278        }
279    }
280
281    /// Segment base as used by address generation: in 64-bit mode only FS
282    /// and GS have a non-zero base.
283    pub fn effective_segment_base(&self, r: SegReg) -> u64 {
284        if self.mode() == CpuMode::Long64 && !matches!(r, SegReg::Fs | SegReg::Gs) {
285            0
286        } else {
287            self.segment(r).base
288        }
289    }
290
291    /// Width of a linear address in this mode, as a mask.
292    pub fn linear_mask(&self) -> u64 {
293        match self.mode() {
294            CpuMode::Long64 => u64::MAX,
295            _ => 0xffff_ffff,
296        }
297    }
298
299    /// The stack pointer, sized for the current stack segment.
300    pub fn stack_pointer(&self) -> u64 {
301        self.gpr[gpr::RSP]
302    }
303}