kvmtrace/kvm.rs
1//! Driving a KVM vCPU: the glue between a `kvm_ioctls::VcpuFd` and the
2//! tracing engine.
3//!
4//! If your VMM is written in Rust on top of `kvm-ioctls`, this is the
5//! whole integration: create a [`KvmTracer`] per vCPU, call
6//! [`KvmTracer::enable`] once, and hand every `VcpuExit::Debug` to
7//! [`KvmTracer::on_debug_exit`]. Everything else your run loop already does
8//! (port I/O, MMIO, HLT) stays exactly as it was.
9//!
10//! ```no_run
11//! # use std::sync::Arc;
12//! # use kvm_ioctls::{Kvm, VcpuExit};
13//! # use kvmtrace::{Session, TraceOptions, kvm::KvmTracer, memory::MappedMemory};
14//! # fn demo(vcpu: &mut kvm_ioctls::VcpuFd, mem: Arc<MappedMemory>) -> kvmtrace::Result<()> {
15//! let session = Session::new(TraceOptions::default(), mem, Some("out".as_ref()))?;
16//! let mut tracer = KvmTracer::new(&session, 0)?;
17//! tracer.enable(vcpu)?;
18//! let mut held = None; // the token, kept while an entry breakpoint is lifted
19//! loop {
20//! let token = held.take().or_else(|| tracer.needs_token(vcpu).then(|| session.token()).flatten());
21//! let exit = vcpu.run().map_err(|e| kvmtrace::Error::Kvm { what: "KVM_RUN", source: e })?;
22//! match exit {
23//! VcpuExit::Debug(d) => {
24//! tracer.on_debug_exit(vcpu, &d, token.is_none())?;
25//! }
26//! VcpuExit::Hlt => {
27//! tracer.flush(vcpu)?; // the HLT itself: no further step will report it
28//! break;
29//! }
30//! _ => { /* your VMM's usual exit handling */ }
31//! }
32//! if tracer.holds_lifted_breakpoint() {
33//! held = token;
34//! }
35//! }
36//! tracer.finish()?;
37//! session.finish()?;
38//! # Ok(()) }
39//! ```
40
41use kvm_bindings::*;
42use kvm_ioctls::{SyncReg, VcpuFd};
43
44use crate::decode::VectorRegs;
45use crate::error::{Error, Result};
46use crate::state::CpuState;
47use crate::tracer::{Session, StopAction, StopContext, StopReason, VcpuTracer};
48
49/// Reads the vCPU state with `KVM_GET_REGS` + `KVM_GET_SREGS`.
50pub fn read_state(vcpu: &VcpuFd) -> Result<CpuState> {
51 let r = vcpu.get_regs().map_err(Error::kvm("KVM_GET_REGS"))?;
52 let s = vcpu.get_sregs().map_err(Error::kvm("KVM_GET_SREGS"))?;
53 Ok(CpuState::from_kvm(&r, &s))
54}
55
56/// Reads the vCPU state from the `kvm_run` shared page, where KVM copied
57/// it on the last exit (`KVM_CAP_SYNC_REGS`). No system call.
58pub fn read_state_synced(vcpu: &VcpuFd) -> CpuState {
59 let s = vcpu.sync_regs();
60 CpuState::from_kvm(&s.regs, &s.sregs)
61}
62
63/// The `KVM_SET_GUEST_DEBUG` control word for tracing.
64pub fn debug_control(follow_handlers: bool, block_interrupts: bool) -> u32 {
65 let mut c = KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP;
66 if follow_handlers {
67 c |= KVM_GUESTDBG_USE_SW_BP;
68 }
69 if block_interrupts {
70 c |= KVM_GUESTDBG_BLOCKIRQ;
71 }
72 c
73}
74
75/// RFLAGS.TF, the trap flag.
76const RFLAGS_TF: u64 = 1 << 8;
77/// DR6.BS: the #DB was a single-step trap.
78const DR6_BS: u64 = 1 << 14;
79
80/// Debug state of a vCPU between trace windows, with the guard on: every
81/// #DB exits to the VMM (`USE_HW_BP`, with no hardware breakpoint set),
82/// so a stale single-step trap can be caught; see [`KvmTracer::disable`].
83pub const GUARD_CONTROL: u32 = KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_HW_BP;
84
85/// Handles a `KVM_EXIT_DEBUG` that arrives while a vCPU is **not** being
86/// traced. Returns `true` if it was a stale single-step trap, now absorbed:
87/// re-enter the vCPU. `false` means it is the guest's own (or a VMM
88/// debugger's) #DB: hand the exit to the VMM as usual (QEMU passes such
89/// exceptions back to the guest).
90///
91/// # Why stale traps exist
92///
93/// While KVM single-steps a vCPU, the hardware trap flag is set. KVM hides
94/// it from register reads, but not from **copies the guest itself saves**:
95/// the RFLAGS image in every interrupt or exception frame, and every
96/// `pushf`. If the guest restores such a copy after tracing has stopped
97/// (a task preempted during the window resumes; a handler that was
98/// interrupted mid-way returns), TF comes back on and the CPU traps after
99/// the next instruction. A user program gets `SIGTRAP` and usually dies.
100///
101/// The guard absorbs that trap: it clears TF in the vCPU's RFLAGS and lets
102/// the guest go on, as if the copy had never had it.
103pub fn absorb_stale_single_step(vcpu: &VcpuFd, d: &kvm_debug_exit_arch) -> Result<bool> {
104 if d.exception != 1 || d.dr6 & DR6_BS == 0 {
105 return Ok(false);
106 }
107 let mut regs = vcpu.get_regs().map_err(Error::kvm("KVM_GET_REGS"))?;
108 if regs.rflags & RFLAGS_TF == 0 {
109 return Ok(false);
110 }
111 regs.rflags &= !RFLAGS_TF;
112 vcpu.set_regs(®s).map_err(Error::kvm("KVM_SET_REGS"))?;
113 Ok(true)
114}
115
116fn set_debug(vcpu: &VcpuFd, control: u32) -> Result<()> {
117 let dbg = kvm_guest_debug { control, pad: 0, arch: Default::default() };
118 vcpu.set_guest_debug(&dbg).map_err(Error::kvm("KVM_SET_GUEST_DEBUG"))
119}
120
121/// [`StopContext`] backed by KVM ioctls on a vCPU fd.
122pub struct KvmContext<'a> {
123 /// The vCPU.
124 pub vcpu: &'a VcpuFd,
125}
126
127impl StopContext for KvmContext<'_> {
128 fn vector_regs(&mut self) -> Option<VectorRegs> {
129 let x = self.vcpu.get_xsave().ok()?;
130 let mut v = Vec::with_capacity(x.region.len() * 4);
131 for w in x.region.iter() {
132 v.extend_from_slice(&w.to_le_bytes());
133 }
134 Some(VectorRegs { xsave: v })
135 }
136
137 fn read_msr(&mut self, index: u32) -> Option<u64> {
138 let mut m = Msrs::from_entries(&[kvm_msr_entry { index, ..Default::default() }]).ok()?;
139 match self.vcpu.get_msrs(&mut m) {
140 Ok(1) => Some(m.as_slice()[0].data),
141 _ => None,
142 }
143 }
144}
145
146/// Traces one KVM vCPU.
147pub struct KvmTracer {
148 tracer: VcpuTracer,
149 control: u32,
150 enabled: bool,
151 check_halt: bool,
152 /// Interrupt pacing: (interval, steps since the last window, window open).
153 pacing: Option<(u64, u64, bool)>,
154 /// Leave the trap-flag guard on when disabled.
155 guard: bool,
156}
157
158impl KvmTracer {
159 /// A tracer for vCPU `id` of `session`, writing to the session's output.
160 pub fn new(session: &Session, id: u32) -> Result<KvmTracer> {
161 Ok(Self::with_tracer(session, session.vcpu(id)?))
162 }
163
164 /// Wraps an engine-level tracer (for example one with a custom sink).
165 pub fn with_tracer(session: &Session, tracer: VcpuTracer) -> KvmTracer {
166 let o = session.options();
167 let pacing = o.interrupt_pacing.filter(|_| o.block_interrupts).map(|n| (n.max(1), 0, false));
168 KvmTracer { tracer, control: debug_control(o.follow_handlers, o.block_interrupts), enabled: false, check_halt: true, pacing, guard: o.trap_flag_guard }
169 }
170
171 /// Is single-step tracing on?
172 pub fn is_enabled(&self) -> bool {
173 self.enabled
174 }
175
176 /// The engine-level tracer.
177 pub fn tracer(&mut self) -> &mut VcpuTracer {
178 &mut self.tracer
179 }
180
181 /// Makes the vCPU report `int3` to us instead of to the guest, without
182 /// single-stepping yet.
183 ///
184 /// On a multi-vCPU guest, call this on **every** vCPU, and wait until
185 /// all have done so, before any of them calls [`enable`](Self::enable):
186 /// `enable` plants breakpoints in guest memory, and a vCPU without
187 /// `KVM_GUESTDBG_USE_SW_BP` that reaches one hands #BP to the guest,
188 /// which then recurses on its own breakpointed #BP handler. Likewise,
189 /// when stopping, call [`Session::remove_breakpoints`] once every
190 /// vCPU has stopped stepping, and only then [`disable`](Self::disable).
191 /// (`libkvmtrace_preload` does this rendezvous for QEMU.)
192 pub fn prearm(&mut self, vcpu: &mut VcpuFd) -> Result<()> {
193 set_debug(vcpu, KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_USE_SW_BP)
194 }
195
196 /// Switches tracing on. Must be called on the thread that runs the vCPU,
197 /// while it is not running. See [`prearm`](Self::prearm) for guests
198 /// with more than one vCPU.
199 pub fn enable(&mut self, vcpu: &mut VcpuFd) -> Result<()> {
200 vcpu.set_sync_valid_reg(SyncReg::Register);
201 vcpu.set_sync_valid_reg(SyncReg::SystemRegister);
202 set_debug(vcpu, self.control)?;
203 let st = read_state(vcpu)?;
204 let a = self.tracer.on_stop(&st, StopReason::Start, &mut KvmContext { vcpu }, false)?;
205 self.apply(vcpu, a)?;
206 self.enabled = true;
207 self.check_halt = true;
208 Ok(())
209 }
210
211 /// Switches tracing off; the guest continues at full speed.
212 ///
213 /// With [`TraceOptions::trap_flag_guard`](crate::TraceOptions::trap_flag_guard)
214 /// (the default), the vCPU is left in [`GUARD_CONTROL`] instead of
215 /// plain debugging-off: no single-stepping and no breakpoints, but a
216 /// `#DB` exits to the VMM, which must pass `KVM_EXIT_DEBUG` exits to
217 /// [`absorb_stale_single_step`] first. This costs nothing while the
218 /// guest does not trap. Two consequences, both inside the guest: its
219 /// own hardware breakpoints (DR0–DR7) do not fire while the guard is
220 /// on, and a debugger *in the guest* that single-steps with TF has its
221 /// traps absorbed. Call [`release`](Self::release) to drop the guard.
222 pub fn disable(&mut self, vcpu: &mut VcpuFd) -> Result<()> {
223 set_debug(vcpu, if self.guard { GUARD_CONTROL } else { 0 })?;
224 self.tracer.pause();
225 self.enabled = false;
226 Ok(())
227 }
228
229 /// Switches all debugging off, guard included.
230 pub fn release(&mut self, vcpu: &mut VcpuFd) -> Result<()> {
231 if self.enabled {
232 self.disable(vcpu)?;
233 }
234 set_debug(vcpu, 0)
235 }
236
237 /// Should the next `KVM_RUN` hold the session's serialization token?
238 ///
239 /// Not if the vCPU is halted or waiting for INIT/SIPI: it would block
240 /// in the kernel holding the token until an interrupt arrives, and the
241 /// vCPU that would send that interrupt could never run.
242 pub fn needs_token(&mut self, vcpu: &VcpuFd) -> bool {
243 if !self.enabled {
244 return false;
245 }
246 if self.check_halt || self.tracer_may_block() {
247 self.check_halt = false;
248 if let Ok(mp) = vcpu.get_mp_state() {
249 if mp.mp_state != KVM_MP_STATE_RUNNABLE {
250 return false;
251 }
252 }
253 }
254 true
255 }
256
257 /// Must the serialization token be kept for the next step?
258 ///
259 /// True right after the vCPU stopped on an entry breakpoint: the
260 /// breakpoint is lifted for one step, and no other vCPU may run until
261 /// it is back (see [`VcpuTracer::has_lifted_breakpoint`]). Keep the
262 /// [`Token`](crate::Token) instead of dropping it:
263 ///
264 /// ```no_run
265 /// # fn f(session: &kvmtrace::Session, tracer: &mut kvmtrace::kvm::KvmTracer, vcpu: &mut kvm_ioctls::VcpuFd) -> kvmtrace::Result<()> {
266 /// let mut held = None;
267 /// loop {
268 /// let token = held.take().or_else(|| if tracer.needs_token(vcpu) { session.token() } else { None });
269 /// let exit = vcpu.run().map_err(kvmtrace::Error::kvm("KVM_RUN"))?;
270 /// if let kvm_ioctls::VcpuExit::Debug(d) = exit {
271 /// tracer.on_debug_exit(vcpu, &d, token.is_none())?;
272 /// }
273 /// if tracer.holds_lifted_breakpoint() { held = token; }
274 /// }
275 /// # }
276 /// ```
277 pub fn holds_lifted_breakpoint(&self) -> bool {
278 self.tracer.has_lifted_breakpoint()
279 }
280
281 fn tracer_may_block(&self) -> bool {
282 self.tracer.pending_may_block()
283 }
284
285 /// Handles a `KVM_EXIT_DEBUG`. Returns what was done; if
286 /// [`StopAction::stop`] is set, the instruction budget ran out: stop
287 /// all vCPUs (see [`prearm`](Self::prearm) for the order) and call
288 /// [`disable`](Self::disable). The vCPU still reports breakpoints.
289 pub fn on_debug_exit(&mut self, vcpu: &mut VcpuFd, d: &kvm_debug_exit_arch, unserialized: bool) -> Result<StopAction> {
290 let st = read_state_synced(vcpu);
291 let reason = if d.exception == 3 { StopReason::Breakpoint } else { StopReason::Step };
292 let a = self.tracer.on_stop(&st, reason, &mut KvmContext { vcpu }, unserialized)?;
293 self.apply(vcpu, a)?;
294 if !a.stop {
295 self.pace(vcpu, a)?;
296 }
297 Ok(a)
298 }
299
300 /// The control word in force right now: without BLOCKIRQ while an
301 /// interrupt window is open.
302 fn current_control(&self) -> u32 {
303 match self.pacing {
304 Some((_, _, true)) => self.control & !KVM_GUESTDBG_BLOCKIRQ,
305 _ => self.control,
306 }
307 }
308
309 /// Opens and closes interrupt windows ([`crate::TraceOptions::interrupt_pacing`]).
310 fn pace(&mut self, vcpu: &VcpuFd, a: StopAction) -> Result<()> {
311 let Some((every, since, open)) = self.pacing.as_mut() else { return Ok(()) };
312 *since += 1;
313 let switch = if *open { *since >= crate::tracer::PACING_WINDOW } else { *since >= *every };
314 if switch {
315 *open = !*open;
316 *since = 0;
317 // Keep a breakpoint injection that apply() may just have asked for.
318 let inject = if a.inject_breakpoint { KVM_GUESTDBG_INJECT_BP } else { 0 };
319 set_debug(vcpu, self.current_control() | inject)?;
320 self.check_halt = true;
321 }
322 Ok(())
323 }
324
325 fn apply(&mut self, vcpu: &VcpuFd, a: StopAction) -> Result<()> {
326 if a.inject_breakpoint {
327 set_debug(vcpu, self.current_control() | KVM_GUESTDBG_INJECT_BP)?;
328 } else if a.rearm {
329 set_debug(vcpu, self.current_control())?;
330 }
331 if a.rearm || a.inject_breakpoint {
332 self.check_halt = true;
333 }
334 Ok(())
335 }
336
337 /// Records the vCPU's last instruction from its current state, when no
338 /// further debug exit will come for it: after the final `VcpuExit::Hlt`
339 /// of a run, or before stopping a trace. See [`VcpuTracer::flush`].
340 pub fn flush(&mut self, vcpu: &VcpuFd) -> Result<()> {
341 let st = read_state(vcpu)?;
342 self.tracer.flush(&st)
343 }
344
345 /// Flushes this vCPU's trace files.
346 pub fn finish(&mut self) -> Result<()> {
347 self.tracer.finish()
348 }
349}