Skip to main content

kvmtrace/
events.rs

1//! Interrupts, exceptions and system calls: noticing them, and making sure
2//! the tracer follows the CPU into their handlers.
3//!
4//! # The problem
5//!
6//! KVM single-steps a guest by setting RFLAGS.TF. But when the CPU
7//! delivers an interrupt or exception through the IDT, it *clears* TF, and
8//! SYSCALL clears it too (through IA32_FMASK, which Linux sets to include
9//! TF). The handler therefore runs at full speed, untraced, and stepping
10//! resumes only when `iret`/`sysret` restores the old flags. Measured on
11//! this crate's test VM, plain single-stepping misses every handler: an
12//! `int 0x80`, a page fault, a SYSCALL and an external interrupt all looked
13//! like one ordinary step.
14//!
15//! # The fix
16//!
17//! We put a software breakpoint (`int3`, intercepted by KVM with
18//! `KVM_GUESTDBG_USE_SW_BP`) on the first byte of every IDT handler and of
19//! the SYSCALL/SYSENTER entry points. Entering any handler now stops the
20//! vCPU *before* the handler's first instruction. The tracer puts the
21//! original byte back, re-arms single-stepping, steps that one
22//! instruction, and puts the breakpoint back.
23//!
24//! The breakpoint table is shared by all vCPUs, because guest memory is.
25
26use std::collections::HashMap;
27
28use crate::memory::GuestMemory;
29use crate::paging::{read_linear, translate};
30use crate::record::{AccessClass, AccessKind, AccessOutcome, MemoryAccess};
31use crate::state::{CpuMode, CpuState, SegReg};
32
33/// MSR numbers of the fast-system-call entry points.
34pub mod msr {
35    /// IA32_SYSENTER_EIP.
36    pub const SYSENTER_EIP: u32 = 0x176;
37    /// IA32_LSTAR (64-bit SYSCALL target).
38    pub const LSTAR: u32 = 0xC000_0082;
39    /// IA32_CSTAR (compatibility-mode SYSCALL target).
40    pub const CSTAR: u32 = 0xC000_0083;
41}
42
43/// The guest's fast-system-call entry points.
44#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
45pub struct EntryMsrs {
46    /// IA32_LSTAR.
47    pub lstar: u64,
48    /// IA32_CSTAR.
49    pub cstar: u64,
50    /// IA32_SYSENTER_EIP.
51    pub sysenter_eip: u64,
52}
53
54/// One IDT gate.
55#[derive(Debug, Clone, Copy, PartialEq, Eq)]
56pub struct Gate {
57    /// Vector number.
58    pub vector: u8,
59    /// Linear address of the handler.
60    pub handler: u64,
61}
62
63/// Does exception `vector` push an error code (in protected/long mode)?
64pub fn has_error_code(vector: u8) -> bool {
65    matches!(vector, 8 | 10 | 11 | 12 | 13 | 14 | 17 | 21 | 29 | 30)
66}
67
68/// Is `vector` a trap-class exception (reported *after* the instruction)?
69pub fn is_trap_vector(vector: u8) -> bool {
70    matches!(vector, 1 | 3 | 4)
71}
72
73/// Size of one IDT entry in this mode.
74fn gate_size(s: &CpuState) -> u64 {
75    match s.mode() {
76        CpuMode::Real => 4,
77        _ if s.efer & crate::state::EFER_LMA != 0 => 16,
78        _ => 8,
79    }
80}
81
82/// Reads the base of the code segment `selector` from the GDT/LDT (flat
83/// segments are the norm; this handles the rest).
84fn descriptor_base(s: &CpuState, mem: &dyn GuestMemory, selector: u16) -> u64 {
85    if s.efer & crate::state::EFER_LMA != 0 || selector & 4 != 0 {
86        return 0; // 64-bit code segments have base 0; LDT not modelled
87    }
88    let mut d = [0u8; 8];
89    if read_linear(s, mem, s.gdt_base + (selector as u64 & !7), &mut d) != 8 {
90        return 0;
91    }
92    let d = u64::from_le_bytes(d);
93    ((d >> 16) & 0xff_ffff) | ((d >> 32) & 0xff00_0000)
94}
95
96/// Reads every present interrupt/trap gate of the vCPU's IDT.
97pub fn read_idt(s: &CpuState, mem: &dyn GuestMemory) -> Vec<Gate> {
98    let size = gate_size(s);
99    let count = ((s.idt_limit as u64 + 1) / size).min(256);
100    let mut out = Vec::new();
101    for v in 0..count {
102        let mut g = [0u8; 16];
103        let la = s.idt_base + v * size;
104        if read_linear(s, mem, la, &mut g[..size as usize]) != size as usize {
105            continue;
106        }
107        let lo = u64::from_le_bytes(g[..8].try_into().unwrap());
108        let handler = match size {
109            4 => {
110                let off = lo & 0xffff;
111                let seg = (lo >> 16) & 0xffff;
112                (seg << 4) + off
113            }
114            _ => {
115                let present = lo >> 47 & 1 == 1;
116                let ty = (lo >> 40) & 0xf;
117                if !present || !matches!(ty, 0x6 | 0x7 | 0xE | 0xF) {
118                    continue; // task gates and empty slots
119                }
120                let off = (lo & 0xffff) | ((lo >> 32) & 0xffff_0000);
121                let sel = ((lo >> 16) & 0xffff) as u16;
122                if size == 16 {
123                    let hi = u64::from_le_bytes(g[8..16].try_into().unwrap());
124                    off | (hi & 0xffff_ffff) << 32
125                } else {
126                    descriptor_base(s, mem, sel).wrapping_add(off) & 0xffff_ffff
127                }
128            }
129        };
130        out.push(Gate { vector: v as u8, handler });
131    }
132    out
133}
134
135#[derive(Debug, Clone, Copy)]
136struct Bp {
137    original: u8,
138    /// vCPU that has temporarily removed the breakpoint to execute the
139    /// instruction under it.
140    lifted_by: Option<u32>,
141}
142
143/// The shared table of entry-point breakpoints.
144#[derive(Debug, Default)]
145pub struct Breakpoints {
146    by_phys: HashMap<u64, Bp>,
147    /// handler linear address → vectors that use it
148    handlers: HashMap<u64, Vec<u8>>,
149    /// physical address ranges holding an IDT
150    idt_ranges: Vec<(u64, u64)>,
151    /// fast-system-call entry points (linear)
152    syscall_entries: Vec<u64>,
153    /// a guest write touched an IDT: rescan before the next step
154    pub(crate) stale: bool,
155}
156
157impl Breakpoints {
158    /// An empty table.
159    pub fn new() -> Self {
160        Self::default()
161    }
162
163    /// Number of breakpoints currently planted.
164    pub fn len(&self) -> usize {
165        self.by_phys.len()
166    }
167
168    /// No breakpoints planted.
169    pub fn is_empty(&self) -> bool {
170        self.by_phys.is_empty()
171    }
172
173    /// Scans the IDT this vCPU uses, plus the system-call MSRs, and plants
174    /// a breakpoint on every entry point that does not have one yet.
175    ///
176    /// Breakpoints are only ever *added* here; [`Breakpoints::clear`]
177    /// removes them all when tracing stops.
178    pub fn sync(&mut self, s: &CpuState, mem: &dyn GuestMemory, msrs: &EntryMsrs) -> usize {
179        let mut added = 0;
180        let gates = read_idt(s, mem);
181        let idt_end = s.idt_base + s.idt_limit as u64;
182        let mut la = s.idt_base & !0xfff;
183        while la <= idt_end {
184            if let Ok(t) = translate(s, mem, la) {
185                let r = (t.physical & !0xfff, (t.physical & !0xfff) + 0x1000);
186                if !self.idt_ranges.contains(&r) {
187                    self.idt_ranges.push(r);
188                }
189            }
190            la += 0x1000;
191        }
192        for g in &gates {
193            let v = self.handlers.entry(g.handler).or_default();
194            if !v.contains(&g.vector) {
195                v.push(g.vector);
196            }
197        }
198        let mut targets: Vec<u64> = gates.iter().map(|g| g.handler).collect();
199        for e in [msrs.lstar, msrs.cstar, msrs.sysenter_eip] {
200            if e != 0 {
201                targets.push(e);
202                if !self.syscall_entries.contains(&e) {
203                    self.syscall_entries.push(e);
204                }
205            }
206        }
207        targets.sort_unstable();
208        targets.dedup();
209        for la in targets {
210            let Ok(t) = translate(s, mem, la) else { continue };
211            if self.by_phys.contains_key(&t.physical) {
212                continue;
213            }
214            let mut b = [0u8];
215            if mem.read(t.physical, &mut b).is_err() {
216                continue;
217            }
218            if b[0] == 0xCC {
219                continue; // the guest's own int3; leave it alone
220            }
221            if mem.write(t.physical, &[0xCC]).is_ok() {
222                self.by_phys.insert(t.physical, Bp { original: b[0], lifted_by: None });
223                added += 1;
224            }
225        }
226        self.stale = false;
227        added
228    }
229
230    /// The byte the guest wrote at `phys`, if a breakpoint covers it.
231    pub fn original(&self, phys: u64) -> Option<u8> {
232        self.by_phys.get(&phys).map(|b| b.original)
233    }
234
235    /// Is there one of our breakpoints at `phys`?
236    pub fn is_ours(&self, phys: u64) -> bool {
237        self.by_phys.contains_key(&phys)
238    }
239
240    /// Temporarily restores the original byte so `vcpu` can execute it.
241    pub fn lift(&mut self, phys: u64, vcpu: u32, mem: &dyn GuestMemory) -> bool {
242        match self.by_phys.get_mut(&phys) {
243            Some(bp) => {
244                if bp.lifted_by.is_none() {
245                    let _ = mem.write(phys, &[bp.original]);
246                }
247                bp.lifted_by = Some(vcpu);
248                true
249            }
250            None => false,
251        }
252    }
253
254    /// Puts a lifted breakpoint back.
255    pub fn reinsert(&mut self, phys: u64, mem: &dyn GuestMemory) {
256        if let Some(bp) = self.by_phys.get_mut(&phys) {
257            bp.lifted_by = None;
258            let _ = mem.write(phys, &[0xCC]);
259        }
260    }
261
262    /// Called for every guest write the tracer observes. If the write lands
263    /// on a breakpoint, the new byte becomes the "original" and the
264    /// breakpoint is re-planted; if it lands on an IDT, the table is
265    /// marked stale.
266    pub fn on_guest_write(&mut self, phys: u64, size: u32, mem: &dyn GuestMemory) {
267        let end = phys + size as u64;
268        if self.idt_ranges.iter().any(|&(a, b)| phys < b && end > a) {
269            self.stale = true;
270        }
271        if self.by_phys.is_empty() {
272            return;
273        }
274        for p in phys..end.min(phys + 64) {
275            if let Some(bp) = self.by_phys.get_mut(&p) {
276                let mut b = [0u8];
277                if mem.read(p, &mut b).is_ok() && b[0] != 0xCC {
278                    bp.original = b[0];
279                    if bp.lifted_by.is_none() {
280                        let _ = mem.write(p, &[0xCC]);
281                    }
282                }
283            }
284        }
285    }
286
287    /// Vectors whose handler starts at linear address `la`.
288    pub fn vectors_at(&self, la: u64) -> &[u8] {
289        self.handlers.get(&la).map(|v| v.as_slice()).unwrap_or(&[])
290    }
291
292    /// Is `la` a SYSCALL/SYSENTER entry point?
293    pub fn is_syscall_entry(&self, la: u64) -> bool {
294        self.syscall_entries.contains(&la)
295    }
296
297    /// Removes every breakpoint, restoring the guest's bytes.
298    pub fn clear(&mut self, mem: &dyn GuestMemory) {
299        for (p, bp) in self.by_phys.drain() {
300            let _ = mem.write(p, &[bp.original]);
301        }
302        self.handlers.clear();
303        self.idt_ranges.clear();
304        self.syscall_entries.clear();
305    }
306}
307
308/// An event delivery found by inspecting the interrupt frame.
309#[derive(Debug, Clone, PartialEq, Eq)]
310pub struct EventMatch {
311    /// IDT vector.
312    pub vector: u8,
313    /// Saved RIP (where `iret` returns to).
314    pub return_rip: u64,
315    /// The CPU's own memory accesses (IDT read, frame push).
316    pub accesses: Vec<MemoryAccess>,
317}
318
319/// Checks whether `post` is the first instruction of a handler entered by
320/// an event while the vCPU was at `pre`, and if so which one.
321///
322/// The test is strict: `post` must be at a handler for some vector *v*,
323/// the frame on the new stack must hold the old CS selector, and the saved
324/// RIP must be one of `candidates` (the pre-step RIP, or a legal successor
325/// of the instruction). A plain `jmp` into handler code fails the frame
326/// test, so it is not mistaken for an interrupt.
327pub fn match_event(
328    pre: &CpuState,
329    post: &CpuState,
330    mem: &dyn GuestMemory,
331    bps: &Breakpoints,
332    candidates: &[u64],
333) -> Option<EventMatch> {
334    let la = post.linear_rip();
335    let vectors = bps.vectors_at(la);
336    if vectors.is_empty() {
337        return None;
338    }
339    let long = post.efer & crate::state::EFER_LMA != 0;
340    let ss_base = post.effective_segment_base(SegReg::Ss);
341    let sp = ss_base.wrapping_add(post.stack_pointer()) & post.linear_mask();
342    let word = if long { 8 } else { 4 };
343    let mut frame = [0u8; 24];
344    let n = read_linear(post, mem, sp, &mut frame[..3 * word]);
345    if n < 3 * word {
346        return None;
347    }
348    let at = |i: usize| -> u64 {
349        if word == 8 {
350            u64::from_le_bytes(frame[i * 8..i * 8 + 8].try_into().unwrap())
351        } else {
352            u32::from_le_bytes(frame[i * 4..i * 4 + 4].try_into().unwrap()) as u64
353        }
354    };
355    let pre_cs = pre.segment(SegReg::Cs).selector as u64;
356    for &v in vectors {
357        let skip = has_error_code(v) as usize;
358        let (rip, cs) = (at(skip), at(skip + 1) & 0xffff);
359        if cs != pre_cs || !candidates.contains(&rip) {
360            continue;
361        }
362        // Frame size: long mode always pushes SS:RSP; legacy mode only on a privilege change.
363        let words = if long || post.cpl() < pre.cpl() { 5 } else { 3 } + skip;
364        let gsize = gate_size(post);
365        let idt_la = post.idt_base + v as u64 * gsize;
366        let phys = |a: u64| translate(post, mem, a).ok().map(|t| t.physical);
367        let accesses = vec![
368            MemoryAccess {
369                linear: idt_la,
370                physical: phys(idt_la),
371                physical_end: None,
372                size: gsize as u32,
373                kind: AccessKind::Read,
374                class: AccessClass::EventDescriptor,
375                outcome: AccessOutcome::Performed,
376                conditional: false,
377            },
378            MemoryAccess {
379                linear: sp,
380                physical: phys(sp),
381                physical_end: None,
382                size: (words * word) as u32,
383                kind: AccessKind::Write,
384                class: AccessClass::EventFrame,
385                outcome: AccessOutcome::Performed,
386                conditional: false,
387            },
388        ];
389        return Some(EventMatch { vector: v, return_rip: rip, accesses });
390    }
391    None
392}