Skip to main content

kvmtrace/
tracer.rs

1//! The tracing engine: a session shared by all vCPUs, and one
2//! [`VcpuTracer`] per vCPU.
3//!
4//! The engine does not run the guest. Whoever owns the vCPU (your Rust
5//! VMM through [`crate::kvm::KvmTracer`], or QEMU through the interposer)
6//! runs it one step at a time and calls [`VcpuTracer::on_stop`] each time
7//! it stops. `on_stop` receives the state *after* the previous step,
8//! which is also the state *before* the next one, so a single register
9//! read per step is enough:
10//!
11//! ```text
12//!   stop k-1          step k            stop k
13//!  ───●────────────[ instruction ]────────●──────▶
14//!     │ pre-state of k                    │ post-state of k
15//!     │ decode, plan accesses,            │ = pre-state of k+1
16//!     │ predict successor                 │ classify step k, emit records
17//! ```
18
19use std::collections::HashMap;
20use std::path::{Path, PathBuf};
21use std::sync::atomic::{AtomicBool, AtomicU64, Ordering as AtOrd};
22use std::sync::{Arc, Condvar, Mutex};
23
24use iced_x86::{FlowControl, InstructionInfoFactory, Mnemonic, OpKind, Register};
25
26use crate::decode::{self, Decoded, PlannedAccess, Successors, VectorRegs};
27use crate::error::Result;
28use crate::events::{self, Breakpoints, EntryMsrs, msr};
29use crate::kvt::KvtWriter;
30use crate::macsim::{self, MacsimRecord, MacsimWriter};
31use crate::memory::GuestMemory;
32use crate::paging::translate;
33use crate::record::*;
34use crate::state::{CpuState, gpr};
35
36/// How steps of different vCPUs are ordered against each other.
37#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum Ordering {
39    /// Only one vCPU executes at a time; every step takes a global token.
40    /// The global sequence numbers are then the *exact* execution order,
41    /// at the cost of losing all parallelism while tracing.
42    Serialized,
43    /// vCPUs step in parallel. Each vCPU's own order is exact; the global
44    /// sequence is the order steps were *observed*, with a host TSC stamp
45    /// for each.
46    Concurrent,
47}
48
49/// Everything you can switch on and off.
50#[derive(Debug, Clone)]
51pub struct TraceOptions {
52    /// Record instruction-fetch accesses in the extended trace.
53    pub instruction_fetches: bool,
54    /// Translate every access to a guest-physical address.
55    pub physical_addresses: bool,
56    /// How vCPUs are ordered against each other.
57    pub ordering: Ordering,
58    /// Plant breakpoints on interrupt, exception and system-call entry
59    /// points so that handlers are traced too (see [`crate::events`]).
60    /// Without this, every handler runs untraced.
61    pub follow_handlers: bool,
62    /// Ask KVM not to inject interrupts while tracing
63    /// (`KVM_GUESTDBG_BLOCKIRQ`, Linux ≥ 5.15). Interrupts are held
64    /// pending, not lost: they are delivered when tracing stops, or in the
65    /// windows opened by [`interrupt_pacing`](Self::interrupt_pacing).
66    pub block_interrupts: bool,
67    /// With [`block_interrupts`](Self::block_interrupts): every this many
68    /// instructions, let pending interrupts in for
69    /// [`PACING_WINDOW`] instructions. The handlers they start are traced
70    /// like any other code.
71    ///
72    /// Why: a traced guest runs one to two orders of magnitude slower than
73    /// normal, but its timers still run on host time. Delivered as they
74    /// fall due, timer interrupts arrive faster than the slowed guest can
75    /// service them and an OS kernel livelocks in its interrupt handlers.
76    /// Pacing bounds the interrupt rate in *guest instructions*.
77    pub interrupt_pacing: Option<u64>,
78    /// Write MacSim `.raw` files.
79    pub macsim: bool,
80    /// Also write instructions that faulted to the MacSim stream (Pin
81    /// reports them too, since it instruments *before* execution).
82    pub macsim_include_faulted: bool,
83    /// With [`macsim`](Self::macsim): also write the sideband
84    /// `trace_<vcpu>.side` ([`crate::side`]): CS, CPL, CR3, physical
85    /// addresses, instruction bytes and every access, one entry per
86    /// MacSim record.
87    pub macsim_sideband: bool,
88    /// Write extended `.kvt` files.
89    pub extended: bool,
90    /// gzip level for MacSim files (1 = fastest).
91    pub gzip_level: u32,
92    /// zstd level for `.kvt` files.
93    pub zstd_level: i32,
94    /// Stop after this many instructions in total.
95    pub max_instructions: Option<u64>,
96    /// After tracing stops, keep catching stale single-step traps (see
97    /// [`KvmTracer::disable`](crate::kvm::KvmTracer::disable)).
98    pub trap_flag_guard: bool,
99}
100
101impl Default for TraceOptions {
102    fn default() -> Self {
103        TraceOptions {
104            instruction_fetches: true,
105            physical_addresses: true,
106            ordering: Ordering::Serialized,
107            follow_handlers: true,
108            block_interrupts: false,
109            interrupt_pacing: None,
110            macsim: true,
111            macsim_include_faulted: true,
112            macsim_sideband: true,
113            extended: true,
114            gzip_level: 1,
115            zstd_level: 3,
116            trap_flag_guard: true,
117            max_instructions: None,
118        }
119    }
120}
121
122/// How many instructions an interrupt window (see
123/// [`TraceOptions::interrupt_pacing`]) stays open. A few, so that an
124/// interrupt pending while the guest briefly has IF = 0 still gets in.
125pub const PACING_WINDOW: u64 = 32;
126
127/// Counters kept by a session.
128#[derive(Debug, Default)]
129struct Counters {
130    instructions: AtomicU64,
131    rep_iterations: AtomicU64,
132    faulted: AtomicU64,
133    events: AtomicU64,
134    interrupts_before: AtomicU64,
135    gaps: AtomicU64,
136    unchecked: AtomicU64,
137    entry_hits: AtomicU64,
138    undecodable: AtomicU64,
139    macsim_truncated: AtomicU64,
140    heuristic_opcodes: AtomicU64,
141    pc_aliases: AtomicU64,
142    guest_breakpoints: AtomicU64,
143    shadowed: AtomicU64,
144}
145
146/// A snapshot of a session's counters.
147#[derive(Debug, Clone, Default, PartialEq, Eq)]
148pub struct Stats {
149    /// Instruction records written (including REP iterations and faulted ones).
150    pub instructions: u64,
151    /// Of those, REP iterations.
152    pub rep_iterations: u64,
153    /// Of those, instructions that faulted.
154    pub faulted: u64,
155    /// Event records written.
156    pub events: u64,
157    /// Interrupts taken before an instruction started.
158    pub interrupts_before: u64,
159    /// Steps whose successor did not match the prediction (possible
160    /// untraced code). Zero on a correct trace.
161    pub gaps: u64,
162    /// Steps whose successor could not be predicted.
163    pub unchecked: u64,
164    /// Times an entry-point breakpoint stopped a vCPU.
165    pub entry_hits: u64,
166    /// Steps whose instruction bytes could not be fetched or decoded.
167    pub undecodable: u64,
168    /// Instructions with more accesses than a MacSim record holds.
169    pub macsim_truncated: u64,
170    /// Instructions whose MacSim opcode came from the fallback heuristic.
171    pub heuristic_opcodes: u64,
172    /// Times one PC held two different instructions (MacSim caches decode by PC).
173    pub pc_aliases: u64,
174    /// The guest's own `int3`s, passed back to the guest.
175    pub guest_breakpoints: u64,
176    /// Instructions executed in a MOV SS / POP SS shadow, reconstructed
177    /// from the states around them (flagged [`RecordFlags::SHADOWED`]).
178    pub shadowed: u64,
179}
180
181impl Counters {
182    fn snapshot(&self) -> Stats {
183        let g = |a: &AtomicU64| a.load(AtOrd::Relaxed);
184        Stats {
185            instructions: g(&self.instructions),
186            rep_iterations: g(&self.rep_iterations),
187            faulted: g(&self.faulted),
188            events: g(&self.events),
189            interrupts_before: g(&self.interrupts_before),
190            gaps: g(&self.gaps),
191            unchecked: g(&self.unchecked),
192            entry_hits: g(&self.entry_hits),
193            undecodable: g(&self.undecodable),
194            macsim_truncated: g(&self.macsim_truncated),
195            heuristic_opcodes: g(&self.heuristic_opcodes),
196            pc_aliases: g(&self.pc_aliases),
197            guest_breakpoints: g(&self.guest_breakpoints),
198            shadowed: g(&self.shadowed),
199        }
200    }
201}
202
203struct Shared {
204    opts: TraceOptions,
205    mem: Arc<dyn GuestMemory>,
206    out: Option<PathBuf>,
207    bps: Mutex<Breakpoints>,
208    msrs: Mutex<Option<EntryMsrs>>,
209    global: AtomicU64,
210    token: Arc<TicketLock>,
211    counters: Counters,
212    threads: Mutex<Vec<u32>>,
213    finished: AtomicBool,
214}
215
216/// A tracing session: options, output directory, and the state all vCPUs
217/// share (breakpoints, global sequence, statistics).
218///
219/// `Session` is cheap to clone; clones refer to the same session.
220#[derive(Clone)]
221pub struct Session {
222    shared: Arc<Shared>,
223}
224
225impl Session {
226    /// Starts a session writing into directory `out` (created if needed).
227    /// Pass `None` to keep records in memory only (use
228    /// [`Session::vcpu_with_sink`]).
229    pub fn new(opts: TraceOptions, mem: Arc<dyn GuestMemory>, out: Option<&Path>) -> Result<Session> {
230        if let Some(d) = out {
231            std::fs::create_dir_all(d)?;
232        }
233        Ok(Session {
234            shared: Arc::new(Shared {
235                opts,
236                mem,
237                out: out.map(Path::to_path_buf),
238                bps: Mutex::new(Breakpoints::new()),
239                msrs: Mutex::new(None),
240                global: AtomicU64::new(0),
241                token: Arc::new(TicketLock::default()),
242                counters: Counters::default(),
243                threads: Mutex::new(Vec::new()),
244                finished: AtomicBool::new(false),
245            }),
246        })
247    }
248
249    /// The options.
250    pub fn options(&self) -> &TraceOptions {
251        &self.shared.opts
252    }
253
254    /// Guest memory.
255    pub fn memory(&self) -> &Arc<dyn GuestMemory> {
256        &self.shared.mem
257    }
258
259    /// A tracer for vCPU `id`, writing to the session's output directory.
260    pub fn vcpu(&self, id: u32) -> Result<VcpuTracer> {
261        let sink: Box<dyn TraceSink> = match &self.shared.out {
262            Some(dir) => Box::new(FileSink::create(dir, id, &self.shared.opts)?),
263            None => Box::new(NullSink),
264        };
265        Ok(self.vcpu_with_sink(id, sink))
266    }
267
268    /// A tracer for vCPU `id` that hands its records to `sink`.
269    pub fn vcpu_with_sink(&self, id: u32, sink: Box<dyn TraceSink>) -> VcpuTracer {
270        {
271            let mut t = self.shared.threads.lock().unwrap();
272            if !t.contains(&id) {
273                t.push(id);
274            }
275        }
276        VcpuTracer {
277            id,
278            shared: self.shared.clone(),
279            sink,
280            info: InstructionInfoFactory::new(),
281            pending: None,
282            lifted: None,
283            local: 0,
284            static_cache: HashMap::new(),
285            synced: false,
286            last_blocking: false,
287        }
288    }
289
290    /// In [`Ordering::Serialized`] mode, the token a vCPU must hold while
291    /// it executes a step. `None` in concurrent mode.
292    ///
293    /// The token is handed out first-come, first-served (a ticket lock), so
294    /// runnable vCPUs take turns one instruction at a time. An unfair lock
295    /// would let one vCPU run thousands of instructions while the others
296    /// wait, which is a correct order but a badly distorted one.
297    pub fn token(&self) -> Option<Token> {
298        match self.shared.opts.ordering {
299            Ordering::Serialized => Some(TicketLock::acquire(&self.shared.token)),
300            Ordering::Concurrent => None,
301        }
302    }
303
304    /// Current counters.
305    pub fn stats(&self) -> Stats {
306        self.shared.counters.snapshot()
307    }
308
309    /// Has the instruction budget run out?
310    pub fn budget_exhausted(&self) -> bool {
311        self.shared
312            .opts
313            .max_instructions
314            .is_some_and(|m| self.shared.counters.instructions.load(AtOrd::Relaxed) >= m)
315    }
316
317    /// Removes all breakpoints from guest memory and writes the MacSim
318    /// header and a summary. Call once, after every vCPU tracer has been
319    /// [finished](VcpuTracer::finish).
320    pub fn finish(&self) -> Result<Stats> {
321        self.remove_breakpoints();
322        let stats = self.stats();
323        if self.shared.finished.swap(true, AtOrd::SeqCst) {
324            return Ok(stats);
325        }
326        if let Some(dir) = &self.shared.out {
327            let mut ids = self.shared.threads.lock().unwrap().clone();
328            ids.sort_unstable();
329            if self.shared.opts.macsim {
330                let threads: Vec<(u32, u64)> = ids.iter().map(|&i| (i, 0)).collect();
331                macsim::write_config(&dir.join("trace"), &threads)?;
332            }
333            let mut s = String::new();
334            use std::fmt::Write as _;
335            let _ = writeln!(s, "kvmtrace {}", env!("CARGO_PKG_VERSION"));
336            let _ = writeln!(s, "vcpus {}", ids.iter().map(|i| i.to_string()).collect::<Vec<_>>().join(","));
337            let _ = writeln!(s, "options {:?}", self.shared.opts);
338            let _ = writeln!(s, "{stats:#?}");
339            std::fs::write(dir.join("summary.txt"), s)?;
340        }
341        Ok(stats)
342    }
343
344    /// Removes the entry-point breakpoints (also done by [`Session::finish`]).
345    pub fn remove_breakpoints(&self) {
346        self.shared.bps.lock().unwrap().clear(&*self.shared.mem);
347    }
348
349    /// Is `state` stopped on one of the session's entry breakpoints?
350    pub fn is_entry_breakpoint(&self, state: &CpuState) -> bool {
351        match translate(state, &*self.shared.mem, state.linear_rip()) {
352            Ok(t) => self.shared.bps.lock().unwrap().is_ours(t.physical),
353            Err(_) => false,
354        }
355    }
356}
357
358/// A fair (FIFO) lock: tickets are served in the order they were taken.
359#[derive(Default)]
360struct TicketLock {
361    next: AtomicU64,
362    serving: Mutex<u64>,
363    turn: Condvar,
364}
365
366impl TicketLock {
367    fn acquire(this: &Arc<TicketLock>) -> Token {
368        let me = this.next.fetch_add(1, AtOrd::SeqCst);
369        let mut s = this.serving.lock().unwrap_or_else(|e| e.into_inner());
370        while *s != me {
371            s = this.turn.wait(s).unwrap_or_else(|e| e.into_inner());
372        }
373        drop(s);
374        Token { lock: this.clone() }
375    }
376}
377
378/// Proof that this vCPU holds the serialization token; dropping it passes
379/// the token to the next waiting vCPU.
380///
381/// It owns a reference to the lock, so a VMM can keep it across loop
382/// iterations, which it must do while
383/// [`KvmTracer::holds_lifted_breakpoint`](crate::kvm::KvmTracer::holds_lifted_breakpoint)
384/// is true.
385pub struct Token {
386    lock: Arc<TicketLock>,
387}
388
389impl Drop for Token {
390    fn drop(&mut self) {
391        let mut s = self.lock.serving.lock().unwrap_or_else(|e| e.into_inner());
392        *s += 1;
393        self.lock.turn.notify_all();
394    }
395}
396
397/// Services the tracer needs from whoever owns the vCPU, at a stop.
398pub trait StopContext {
399    /// The SIMD register file (`KVM_GET_XSAVE`). Called only for gathers
400    /// and scatters.
401    fn vector_regs(&mut self) -> Option<VectorRegs>;
402    /// Reads an MSR (`KVM_GET_MSRS`). Called when tracing starts and after
403    /// the guest writes one of the system-call MSRs.
404    fn read_msr(&mut self, index: u32) -> Option<u64>;
405}
406
407/// Why the vCPU stopped.
408#[derive(Debug, Clone, Copy, PartialEq, Eq)]
409pub enum StopReason {
410    /// Tracing is starting (no step has been taken yet).
411    Start,
412    /// A single-step trap (`#DB`).
413    Step,
414    /// A breakpoint trap (`#BP`): either an entry breakpoint, or the
415    /// guest's own `int3`.
416    Breakpoint,
417}
418
419/// What the owner of the vCPU must do before running it again.
420#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
421pub struct StopAction {
422    /// Call `KVM_SET_GUEST_DEBUG` again: RFLAGS.TF was (or may have been)
423    /// cleared by the guest or by event delivery.
424    pub rearm: bool,
425    /// The stop was the guest's own `int3`: inject `#BP` into the guest
426    /// (`KVM_GUESTDBG_INJECT_BP`).
427    pub inject_breakpoint: bool,
428    /// The instruction budget is used up: stop tracing.
429    pub stop: bool,
430}
431
432struct Pending {
433    pre: CpuState,
434    d: Decoded,
435    plan: Vec<PlannedAccess>,
436    succ: Successors,
437    at_entry: bool,
438    unserialized: bool,
439    macsim: Option<MacsimRecord>,
440    /// Executed in the shadow of a MOV SS / POP SS (see `split_shadow`).
441    shadow: bool,
442}
443
444/// The tracer for one vCPU.
445pub struct VcpuTracer {
446    id: u32,
447    shared: Arc<Shared>,
448    sink: Box<dyn TraceSink>,
449    info: InstructionInfoFactory,
450    pending: Option<Pending>,
451    lifted: Option<u64>,
452    local: u64,
453    static_cache: HashMap<u64, ([u8; 15], u8, MacsimRecord)>,
454    synced: bool,
455    last_blocking: bool,
456}
457
458fn rdtsc() -> u64 {
459    #[cfg(target_arch = "x86_64")]
460    // SAFETY: RDTSC has no preconditions.
461    unsafe {
462        core::arch::x86_64::_rdtsc()
463    }
464    #[cfg(not(target_arch = "x86_64"))]
465    0
466}
467
468impl VcpuTracer {
469    /// The vCPU id.
470    pub fn id(&self) -> u32 {
471        self.id
472    }
473
474    /// Handles one stop of the vCPU.
475    ///
476    /// `state` is the vCPU's state now. `unserialized` says the step that
477    /// just ended ran without the global token (see [`Ordering`]).
478    pub fn on_stop(
479        &mut self,
480        state: &CpuState,
481        reason: StopReason,
482        ctx: &mut dyn StopContext,
483        unserialized: bool,
484    ) -> Result<StopAction> {
485        let shared = self.shared.clone();
486        let mem = &*shared.mem;
487        let mut action = StopAction::default();
488
489        // The instruction under a lifted breakpoint has executed: put it back.
490        if let Some(p) = self.lifted.take() {
491            shared.bps.lock().unwrap().reinsert(p, mem);
492        }
493
494        let here = translate(state, mem, state.linear_rip()).ok().map(|t| t.physical);
495        let ours = here.is_some_and(|p| shared.bps.lock().unwrap().is_ours(p));
496
497        // The guest's own int3: the step did not happen; hand #BP to the guest.
498        if reason == StopReason::Breakpoint && !ours {
499            shared.counters.guest_breakpoints.fetch_add(1, AtOrd::Relaxed);
500            action.inject_breakpoint = true;
501            return Ok(action);
502        }
503
504        if shared.opts.follow_handlers {
505            let stale = shared.bps.lock().unwrap().stale;
506            if !self.synced || stale {
507                self.sync_entry_points(state, ctx);
508            }
509        }
510
511        if let Some(p) = self.pending.take() {
512            let rearm = decode::may_clear_tf(&p.d.instr);
513            self.last_blocking = matches!(p.d.instr.mnemonic(), Mnemonic::Hlt | Mnemonic::Mwait | Mnemonic::Mwaitx);
514            self.finish_step(p, state, unserialized)?;
515            action.rearm |= rearm;
516        }
517
518        // Prepare the next step.
519        let mut at_entry = false;
520        if ours {
521            let p = here.unwrap();
522            shared.bps.lock().unwrap().lift(p, self.id, mem);
523            self.lifted = Some(p);
524            shared.counters.entry_hits.fetch_add(1, AtOrd::Relaxed);
525            action.rearm = true;
526            at_entry = true;
527        }
528        if reason == StopReason::Start {
529            action.rearm = true;
530        }
531        match self.prepare(state, at_entry, &mut |d, info| {
532            if decode::needs_vector_regs(d, info) { ctx.vector_regs() } else { None }
533        }) {
534            Some(p) => self.pending = Some(p),
535            None => {
536                shared.counters.undecodable.fetch_add(1, AtOrd::Relaxed);
537            }
538        }
539        if let Some(p) = &mut self.pending {
540            p.unserialized = unserialized;
541        }
542        action.stop = self
543            .shared
544            .opts
545            .max_instructions
546            .is_some_and(|m| shared.counters.instructions.load(AtOrd::Relaxed) >= m);
547        Ok(action)
548    }
549
550    fn sync_entry_points(&mut self, state: &CpuState, ctx: &mut dyn StopContext) {
551        let shared = &self.shared;
552        let msrs = {
553            let mut g = shared.msrs.lock().unwrap();
554            if g.is_none() || !self.synced {
555                *g = Some(EntryMsrs {
556                    lstar: ctx.read_msr(msr::LSTAR).unwrap_or(0),
557                    cstar: ctx.read_msr(msr::CSTAR).unwrap_or(0),
558                    sysenter_eip: ctx.read_msr(msr::SYSENTER_EIP).unwrap_or(0),
559                });
560            }
561            g.unwrap()
562        };
563        shared.bps.lock().unwrap().sync(state, &*shared.mem, &msrs);
564        self.synced = true;
565    }
566
567    fn macsim_template(&mut self, d: &Decoded) -> MacsimRecord {
568        if let Some((b, len, t)) = self.static_cache.get(&d.linear_rip) {
569            if *len == d.len && b[..*len as usize] == d.bytes[..d.len as usize] {
570                return *t;
571            }
572            self.shared.counters.pc_aliases.fetch_add(1, AtOrd::Relaxed);
573        }
574        let si = macsim::static_info(d, &mut self.info);
575        if si.category == macsim::CategorySource::Heuristic {
576            self.shared.counters.heuristic_opcodes.fetch_add(1, AtOrd::Relaxed);
577        }
578        self.static_cache.insert(d.linear_rip, (d.bytes, d.len, si.template));
579        si.template
580    }
581
582    fn next_seq(&mut self) -> Sequence {
583        let s = Sequence { local: self.local, global: self.shared.global.fetch_add(1, AtOrd::SeqCst), host_tsc: rdtsc() };
584        self.local += 1;
585        s
586    }
587
588    /// Decodes the instruction at `state` and plans what it will do.
589    fn prepare(
590        &mut self,
591        state: &CpuState,
592        at_entry: bool,
593        vregs: &mut dyn FnMut(&decode::Decoded, &mut InstructionInfoFactory) -> Option<decode::VectorRegs>,
594    ) -> Option<Pending> {
595        let shared = self.shared.clone();
596        let mem = &*shared.mem;
597        let d = {
598            let bps = shared.bps.lock().unwrap();
599            decode::fetch(state, mem, &|pa| bps.original(pa))
600        }?;
601        let vregs = vregs(&d, &mut self.info);
602        let mut plan = decode::io_permission_accesses(state, &d, mem);
603        plan.extend(decode::plan_accesses(state, &d, &mut self.info, vregs.as_ref()));
604        let lstar = shared.msrs.lock().unwrap().map(|m| m.lstar);
605        let succ = decode::predict_successors(state, mem, &d, lstar);
606        let macsim = shared.opts.macsim.then(|| self.macsim_template(&d));
607        Some(Pending { pre: *state, d, plan, succ, at_entry, unserialized: false, macsim, shadow: false })
608    }
609
610    /// MOV SS and POP SS block interrupts *and debug traps* until the next
611    /// instruction has completed (the "SS shadow", which lets `mov ss` +
612    /// `mov rsp` switch stacks atomically). So a single step over them
613    /// executes two instructions, and the trap arrives after the second.
614    ///
615    /// When that happens we split the step. The state between the two is
616    /// known exactly: it is the state before, with the new SS (and, for
617    /// POP SS, the popped stack pointer) — nothing else is changed by
618    /// these instructions. From it we decode and plan the second
619    /// instruction, and finish the two steps one after the other. The
620    /// second record carries [`RecordFlags::SHADOWED`].
621    fn split_shadow(&mut self, p: Pending, post: &CpuState, unserialized: bool) -> Result<()> {
622        let i = &p.d.instr;
623        let mut mid = p.pre;
624        mid.rip = i.next_ip();
625        mid.seg[crate::state::SegReg::Ss as usize] = post.seg[crate::state::SegReg::Ss as usize];
626        if i.mnemonic() == Mnemonic::Pop {
627            let size = match p.pre.mode() {
628                crate::state::CpuMode::Long64 => 8,
629                _ => i.stack_pointer_increment().unsigned_abs() as u64,
630            };
631            let sp = &mut mid.gpr[gpr::RSP];
632            *sp = if p.pre.segment(crate::state::SegReg::Ss).db || p.pre.mode() == crate::state::CpuMode::Long64 {
633                sp.wrapping_add(size)
634            } else {
635                (*sp & !0xffff) | (sp.wrapping_add(size) & 0xffff)
636            };
637        }
638        let second = self.prepare(&mid, false, &mut |_, _| None);
639        self.finish_step_inner(p, &mid, unserialized)?;
640        match second {
641            Some(mut q) => {
642                q.shadow = true;
643                self.finish_step_inner(q, post, unserialized)
644            }
645            None => {
646                self.shared.counters.undecodable.fetch_add(1, AtOrd::Relaxed);
647                Ok(())
648            }
649        }
650    }
651
652    fn finish_step(&mut self, p: Pending, post: &CpuState, unserialized: bool) -> Result<()> {
653        let i = &p.d.instr;
654        let loads_ss = match i.mnemonic() {
655            Mnemonic::Mov => i.op0_kind() == OpKind::Register && i.op0_register() == Register::SS,
656            Mnemonic::Pop => i.op0_kind() == OpKind::Register && i.op0_register() == Register::SS,
657            _ => false,
658        };
659        // A completed MOV SS lands past the *next* instruction. (If it
660        // faulted, or an event came before it, RIP would be at or before it.)
661        if loads_ss && post.rip != i.next_ip() && post.rip != p.pre.rip {
662            // Unless an event frame says the MOV SS itself faulted or never started.
663            let own_event = {
664                let bps = self.shared.bps.lock().unwrap();
665                !bps.is_empty() && events::match_event(&p.pre, post, &*self.shared.mem, &bps, &[p.pre.rip]).is_some()
666            };
667            if !own_event {
668                return self.split_shadow(p, post, unserialized);
669            }
670        }
671        self.finish_step_inner(p, post, unserialized)
672    }
673
674    fn finish_step_inner(&mut self, p: Pending, post: &CpuState, unserialized: bool) -> Result<()> {
675        let shared = self.shared.clone();
676        let mem = &*shared.mem;
677        let i = &p.d.instr;
678        let next = i.next_ip();
679        let rep = decode::is_rep_string(i);
680        let count_changed = rep && decode::rep_count(&p.pre, i) != decode::rep_count(post, i);
681
682        let mut candidates = vec![p.pre.rip, next];
683        if let Successors::Exactly(v) = &p.succ {
684            candidates.extend_from_slice(v);
685        }
686        let ev = {
687            let bps = shared.bps.lock().unwrap();
688            if bps.is_empty() { None } else { events::match_event(&p.pre, post, mem, &bps, &candidates) }
689        };
690
691        let mut flags = RecordFlags::empty();
692        if p.at_entry {
693            flags.insert(RecordFlags::AT_ENTRY_POINT);
694        }
695        if p.shadow {
696            flags.insert(RecordFlags::SHADOWED);
697            shared.counters.shadowed.fetch_add(1, AtOrd::Relaxed);
698        }
699        if p.unserialized || unserialized {
700            flags.insert(RecordFlags::UNSERIALIZED);
701        }
702
703        // 1. What happened to the instruction?
704        enum Fate {
705            Completed { next_rip: u64 },
706            Faulted(u8),
707            NotStarted,
708        }
709        let fate = match &ev {
710            Some(e) if e.return_rip == p.pre.rip && !count_changed => {
711                if e.vector < 32 && e.vector != 2 && !events::is_trap_vector(e.vector) {
712                    Fate::Faulted(e.vector)
713                } else {
714                    Fate::NotStarted
715                }
716            }
717            Some(e) => Fate::Completed { next_rip: e.return_rip },
718            None => {
719                if !(rep && post.rip == p.pre.rip) {
720                    match p.succ.admits(post.rip) {
721                        Some(true) => {}
722                        Some(false) => {
723                            // A SYSCALL lands on LSTAR, an int3-style entry on a handler:
724                            // anything else is unexplained.
725                            flags.insert(RecordFlags::GAP_AFTER);
726                            shared.counters.gaps.fetch_add(1, AtOrd::Relaxed);
727                        }
728                        None => {
729                            flags.insert(RecordFlags::SUCCESSOR_UNCHECKED);
730                            shared.counters.unchecked.fetch_add(1, AtOrd::Relaxed);
731                        }
732                    }
733                }
734                Fate::Completed { next_rip: post.rip }
735            }
736        };
737
738        // 2. The instruction record.
739        let mut record_macsim = None;
740        if !matches!(fate, Fate::NotStarted) {
741            let faulted = match fate {
742                Fate::Faulted(v) => Some(v),
743                _ => None,
744            };
745            let next_rip = match fate {
746                Fate::Completed { next_rip } => next_rip,
747                _ => post.rip,
748            };
749            let outcome = match fate {
750                Fate::Faulted(vector) => InstructionOutcome::Faulted { vector },
751                _ if rep && next_rip == p.pre.rip => InstructionOutcome::RepIteration,
752                _ => InstructionOutcome::Retired,
753            };
754            let mut accesses = Vec::with_capacity(p.plan.len() + 2);
755            let fault_addr = (faulted == Some(14)).then_some(post.cr2);
756            let within = |la: u64, size: u32| fault_addr.is_some_and(|c| c >= la && c < la.wrapping_add(size as u64));
757            if shared.opts.instruction_fetches {
758                for &(la, pa, size) in &p.d.fetches {
759                    accesses.push(MemoryAccess {
760                        linear: la,
761                        physical: if shared.opts.physical_addresses { pa } else { None },
762                        physical_end: None,
763                        size,
764                        kind: AccessKind::Fetch,
765                        class: AccessClass::InstructionFetch,
766                        outcome: if within(la, size) { AccessOutcome::Faulted } else { AccessOutcome::Performed },
767                        conditional: false,
768                    });
769                }
770            }
771            // Note: CMOVcc *always* reads its memory source (and can fault)
772            // even when the condition is false, so it is never suppressed.
773            for a in &p.plan {
774                let (physical, physical_end) = if shared.opts.physical_addresses {
775                    let first = translate(&p.pre, mem, a.linear).ok().map(|t| t.physical);
776                    let last_la = a.linear.wrapping_add(a.size.max(1) as u64 - 1);
777                    let end = if last_la >> 12 != a.linear >> 12 {
778                        translate(&p.pre, mem, last_la).ok().map(|t| t.physical)
779                    } else {
780                        None
781                    };
782                    (first, end)
783                } else {
784                    (None, None)
785                };
786                let outcome = if faulted.is_some() {
787                    if within(a.linear, a.size) { AccessOutcome::Faulted } else { AccessOutcome::Aborted }
788                } else {
789                    AccessOutcome::Performed
790                };
791                accesses.push(MemoryAccess {
792                    linear: a.linear,
793                    physical,
794                    physical_end,
795                    size: a.size,
796                    kind: a.kind,
797                    class: a.class,
798                    outcome,
799                    conditional: a.conditional,
800                });
801            }
802            // Keep the breakpoint table honest about guest writes.
803            if faulted.is_none() && shared.opts.follow_handlers {
804                let mut bps = shared.bps.lock().unwrap();
805                for a in &accesses {
806                    if matches!(a.kind, AccessKind::Write | AccessKind::ReadWrite) && a.outcome == AccessOutcome::Performed {
807                        let pa = a.physical.or_else(|| translate(&p.pre, mem, a.linear).ok().map(|t| t.physical));
808                        if let Some(pa) = pa {
809                            bps.on_guest_write(pa, a.size, mem);
810                        }
811                    }
812                }
813                match i.mnemonic() {
814                    Mnemonic::Lidt => bps.stale = true,
815                    Mnemonic::Wrmsr => {
816                        let ecx = p.pre.gpr[gpr::RCX] as u32;
817                        if [msr::LSTAR, msr::CSTAR, msr::SYSENTER_EIP].contains(&ecx) {
818                            *shared.msrs.lock().unwrap() = None;
819                            self.synced = false;
820                            bps.stale = true;
821                        }
822                    }
823                    _ => {}
824                }
825            }
826            let cf = i.flow_control();
827            let branch_taken = match cf {
828                FlowControl::Next | FlowControl::Exception => false,
829                FlowControl::ConditionalBranch => faulted.is_none() && next_rip != next,
830                _ => faulted.is_none(),
831            };
832            let branch_target = match cf {
833                FlowControl::ConditionalBranch => i.near_branch_target(),
834                FlowControl::Next | FlowControl::Exception => 0,
835                _ => next_rip,
836            };
837            let rec = InstructionRecord {
838                seq: self.next_seq(),
839                vcpu: self.id,
840                rip: p.pre.rip,
841                linear_rip: p.d.linear_rip,
842                physical_rip: if shared.opts.physical_addresses { p.d.physical_rip } else { None },
843                bytes: p.d.bytes,
844                len: p.d.len,
845                cs: p.pre.segment(crate::state::SegReg::Cs).selector,
846                cpl: p.pre.cpl(),
847                mode: p.pre.mode(),
848                cr3: p.pre.cr3,
849                next_rip,
850                branch_taken,
851                outcome,
852                accesses,
853                flags,
854            };
855            let mut rec = rec;
856            if let Some(mut t) = p.macsim {
857                if faulted.is_none() || shared.opts.macsim_include_faulted {
858                    if macsim::fill_dynamic(&mut t, &rec, p.pre.rflags, branch_target) {
859                        rec.flags.insert(RecordFlags::MACSIM_TRUNCATED);
860                        shared.counters.macsim_truncated.fetch_add(1, AtOrd::Relaxed);
861                    }
862                    record_macsim = Some(t);
863                }
864            }
865            let c = &shared.counters;
866            c.instructions.fetch_add(1, AtOrd::Relaxed);
867            match outcome {
868                InstructionOutcome::RepIteration => {
869                    c.rep_iterations.fetch_add(1, AtOrd::Relaxed);
870                }
871                InstructionOutcome::Faulted { .. } => {
872                    c.faulted.fetch_add(1, AtOrd::Relaxed);
873                }
874                _ => {}
875            }
876            self.sink.record(&TraceItem::Instruction(rec), record_macsim.as_ref())?;
877        }
878
879        // 3. The event record.
880        if let Some(e) = ev {
881            let kind = match fate {
882                Fate::Faulted(_) => EventKind::Exception,
883                Fate::NotStarted => {
884                    shared.counters.interrupts_before.fetch_add(1, AtOrd::Relaxed);
885                    EventKind::Interrupt
886                }
887                Fate::Completed { .. } => {
888                    if i.flow_control() == FlowControl::Interrupt || e.vector < 32 {
889                        EventKind::Software
890                    } else {
891                        EventKind::Interrupt
892                    }
893                }
894            };
895            shared.counters.events.fetch_add(1, AtOrd::Relaxed);
896            let rec = EventRecord {
897                seq: self.next_seq(),
898                vcpu: self.id,
899                vector: e.vector,
900                kind,
901                return_rip: e.return_rip,
902                handler_rip: post.rip,
903                cr3: post.cr3,
904                accesses: e.accesses,
905            };
906            self.sink.record(&TraceItem::Event(rec), None)?;
907        }
908        Ok(())
909    }
910
911    /// Did the last traced instruction (HLT, MWAIT) put the vCPU to sleep,
912    /// so that the next `KVM_RUN` may block until an interrupt arrives?
913    pub fn pending_may_block(&self) -> bool {
914        self.last_blocking
915    }
916
917    /// Drops the pending (not yet executed) step, puts back a lifted
918    /// breakpoint, and flushes the output files.
919    pub fn finish(&mut self) -> Result<()> {
920        self.pending = None;
921        if let Some(p) = self.lifted.take() {
922            self.shared.bps.lock().unwrap().reinsert(p, &*self.shared.mem);
923        }
924        self.sink.finish()
925    }
926
927    /// Records the last instruction now, from `state`, because no further
928    /// stop is coming: the vCPU halted for good, or tracing is about to be
929    /// switched off.
930    ///
931    /// A step is normally written when the *next* stop arrives, since only
932    /// then is its outcome known. If `state.rip` has moved past the pending
933    /// instruction (HLT, and port I/O that KVM completed before exiting,
934    /// both do this), the instruction retired and is written. If not, it
935    /// has not executed and is dropped.
936    pub fn flush(&mut self, state: &CpuState) -> Result<()> {
937        if let Some(p) = self.pending.take() {
938            if state.rip != p.pre.rip {
939                self.finish_step(p, state, false)?;
940            }
941        }
942        Ok(())
943    }
944
945    /// Is one of the session's entry breakpoints lifted (its original byte
946    /// back in place) for this vCPU's next step?
947    ///
948    /// While it is, another vCPU entering the same handler would not stop
949    /// there, and since event delivery clears TF its handler would run
950    /// untraced. In serialized mode the vCPU therefore keeps the token
951    /// until the breakpoint is back.
952    pub fn has_lifted_breakpoint(&self) -> bool {
953        self.lifted.is_some()
954    }
955
956    /// Forgets the pending step without writing it (used when tracing is
957    /// switched off in the middle of a run).
958    pub fn pause(&mut self) {
959        self.pending = None;
960        if let Some(p) = self.lifted.take() {
961            self.shared.bps.lock().unwrap().reinsert(p, &*self.shared.mem);
962        }
963    }
964}
965
966/// Where a vCPU's records go.
967pub trait TraceSink: Send {
968    /// One item, plus its MacSim record when there is one.
969    fn record(&mut self, item: &TraceItem, macsim: Option<&MacsimRecord>) -> Result<()>;
970    /// Flushes and closes.
971    fn finish(&mut self) -> Result<()>;
972}
973
974/// Discards everything.
975pub struct NullSink;
976
977impl TraceSink for NullSink {
978    fn record(&mut self, _: &TraceItem, _: Option<&MacsimRecord>) -> Result<()> {
979        Ok(())
980    }
981    fn finish(&mut self) -> Result<()> {
982        Ok(())
983    }
984}
985
986/// Keeps every record in memory, behind a shared handle; handy in tests.
987#[derive(Clone, Default)]
988pub struct MemorySink {
989    /// The items and their MacSim records, in order.
990    pub items: Arc<Mutex<Vec<(TraceItem, Option<MacsimRecord>)>>>,
991}
992
993impl TraceSink for MemorySink {
994    fn record(&mut self, item: &TraceItem, macsim: Option<&MacsimRecord>) -> Result<()> {
995        self.items.lock().unwrap().push((item.clone(), macsim.copied()));
996        Ok(())
997    }
998    fn finish(&mut self) -> Result<()> {
999        Ok(())
1000    }
1001}
1002
1003/// Writes `trace_<vcpu>.raw` (MacSim) and `vcpu<vcpu>.kvt` (extended)
1004/// into a directory.
1005pub struct FileSink {
1006    macsim: Option<MacsimWriter>,
1007    side: Option<crate::side::SideWriter>,
1008    kvt: Option<KvtWriter>,
1009}
1010
1011impl FileSink {
1012    /// Creates the files for one vCPU.
1013    pub fn create(dir: &Path, vcpu: u32, opts: &TraceOptions) -> Result<FileSink> {
1014        Ok(FileSink {
1015            macsim: if opts.macsim { Some(MacsimWriter::create(&dir.join("trace"), vcpu, opts.gzip_level)?) } else { None },
1016            side: if opts.macsim && opts.macsim_sideband {
1017                Some(crate::side::SideWriter::create(&dir.join("trace"), vcpu, opts.gzip_level)?)
1018            } else {
1019                None
1020            },
1021            kvt: if opts.extended {
1022                Some(KvtWriter::create(&dir.join(format!("vcpu{vcpu}.kvt")), vcpu, opts.zstd_level)?)
1023            } else {
1024                None
1025            },
1026        })
1027    }
1028}
1029
1030impl TraceSink for FileSink {
1031    fn record(&mut self, item: &TraceItem, macsim: Option<&MacsimRecord>) -> Result<()> {
1032        if let (Some(w), Some(r)) = (&mut self.macsim, macsim) {
1033            if let (Some(sw), TraceItem::Instruction(rec)) = (&mut self.side, item) {
1034                let (mut used, store, _) = macsim::selected_accesses(r, rec);
1035                used.extend(store);
1036                sw.write(&crate::side::SideEntry::from_record(rec, w.count(), &used))?;
1037            }
1038            w.write(r)?;
1039        }
1040        if let Some(w) = &mut self.kvt {
1041            w.write(item)?;
1042        }
1043        Ok(())
1044    }
1045    fn finish(&mut self) -> Result<()> {
1046        if let Some(w) = self.macsim.take() {
1047            w.finish()?;
1048        }
1049        if let Some(w) = self.side.take() {
1050            w.finish()?;
1051        }
1052        if let Some(w) = self.kvt.take() {
1053            w.finish()?;
1054        }
1055        Ok(())
1056    }
1057}