Skip to main content

kvmtrace_preload/
lib.rs

1//! `libkvmtrace_preload.so`: trace an unmodified QEMU (or any VMM that
2//! calls `ioctl(2)` through libc) by loading this library with `LD_PRELOAD`.
3//!
4//! ```text
5//! KVMTRACE_OUT=trace-dir LD_PRELOAD=libkvmtrace_preload.so qemu-system-x86_64 -accel kvm ...
6//! ```
7//!
8//! The library wraps `ioctl`. It watches the VMM create the VM, its vCPUs
9//! and its memory slots, and it takes over `KVM_RUN`: while tracing, every
10//! single-step exit is handled here and the vCPU is re-entered at once, so
11//! the VMM only ever sees the exits it would have seen anyway (I/O, MMIO,
12//! shutdown, signals).
13//!
14//! Configuration is through environment variables; see the crate README
15//! or `kvmtrace::book::ch07_tracing_qemu`.
16
17use std::collections::HashMap;
18use std::ffi::{c_int, c_ulong, c_void};
19use std::os::fd::RawFd;
20use std::path::PathBuf;
21use std::sync::atomic::{AtomicBool, AtomicI32, AtomicU32, AtomicU64, Ordering as AtOrd};
22use std::sync::{Arc, Condvar, Mutex, OnceLock};
23use std::time::{Duration, Instant};
24
25use kvm_bindings::*;
26use kvm_ioctls::{Kvm, VcpuFd, VmFd};
27use kvmtrace::kvm::KvmTracer;
28use kvmtrace::memory::MappedMemory;
29use kvmtrace::{Ordering, Session, TraceOptions};
30
31// ioctl request numbers (x86-64).
32const KVM_CREATE_VM: c_ulong = 0xAE01;
33const KVM_CREATE_VCPU: c_ulong = 0xAE41;
34const KVM_SET_USER_MEMORY_REGION: c_ulong = 0x4020_AE46;
35const KVM_SET_USER_MEMORY_REGION2: c_ulong = 0x40A0_AE49;
36const KVM_RUN: c_ulong = 0xAE80;
37const KVM_SET_REGS: c_ulong = 0x4090_AE82;
38const KVM_SET_SREGS: c_ulong = 0x4138_AE84;
39const KVM_SET_GUEST_DEBUG: c_ulong = 0x4048_AE9B;
40const KVM_SET_CPUID2: c_ulong = 0x4008_AE90;
41
42/// "KVMK", the start of the hypervisor signature in CPUID 0x4000_0x00.EBX.
43const KVM_SIGNATURE_EBX: u32 = 0x4b4d_564b;
44/// KVM_FEATURE_STEAL_TIME in CPUID 0x4000_0x01.EAX.
45const KVM_FEATURE_STEAL_TIME: u32 = 1 << 5;
46
47type IoctlFn = unsafe extern "C" fn(c_int, c_ulong, *mut c_void) -> c_int;
48
49fn real_ioctl() -> IoctlFn {
50    static REAL: OnceLock<usize> = OnceLock::new();
51    let p = *REAL.get_or_init(|| {
52        // SAFETY: dlsym with a valid NUL-terminated name.
53        let p = unsafe { libc::dlsym(libc::RTLD_NEXT, c"ioctl".as_ptr()) };
54        assert!(!p.is_null(), "kvmtrace: cannot find the real ioctl");
55        p as usize
56    });
57    // SAFETY: the symbol is libc's ioctl, ABI-compatible with IoctlFn on x86-64.
58    unsafe { std::mem::transmute::<usize, IoctlFn>(p) }
59}
60
61thread_local! {
62    /// Set while this thread is inside our hook: ioctls made by the
63    /// tracer itself go straight to the kernel.
64    static IN_HOOK: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
65}
66
67/// When the first window opens.
68#[derive(Clone, Copy, Debug, PartialEq)]
69enum Start {
70    /// When the guest writes START to the marker port (or on a control command).
71    Marker,
72    /// From the first instruction.
73    Now,
74    /// This long after the guest first runs.
75    After(Duration),
76}
77
78struct Config {
79    out: PathBuf,
80    start: Start,
81    /// Close each window after this much wall-clock time.
82    duration: Option<Duration>,
83    /// Open a new window this long after the previous one opened.
84    every: Option<Duration>,
85    /// At most this many windows (None: unlimited).
86    max_windows: Option<u64>,
87    /// Unix socket accepting `start [SECS]`, `stop`, `status`.
88    control: Option<PathBuf>,
89    port: u16,
90    opts: TraceOptions,
91    verbose: bool,
92    keep_steal_time: bool,
93}
94
95fn env_flag(name: &str, default: bool) -> bool {
96    match std::env::var(name) {
97        Ok(v) => matches!(v.as_str(), "1" | "yes" | "true" | "on"),
98        Err(_) => default,
99    }
100}
101
102impl Config {
103    fn from_env() -> Config {
104        let num = |name: &str| -> Option<u64> {
105            std::env::var(name).ok().and_then(|v| {
106                let v = v.trim();
107                if let Some(h) = v.strip_prefix("0x") { u64::from_str_radix(h, 16).ok() } else { v.parse().ok() }
108            })
109        };
110        let opts = TraceOptions {
111            instruction_fetches: env_flag("KVMTRACE_FETCH", true),
112            physical_addresses: env_flag("KVMTRACE_PHYS", true),
113            ordering: match std::env::var("KVMTRACE_ORDER").as_deref() {
114                Ok("concurrent") => Ordering::Concurrent,
115                _ => Ordering::Serialized,
116            },
117            follow_handlers: env_flag("KVMTRACE_FOLLOW_HANDLERS", true),
118            block_interrupts: env_flag("KVMTRACE_BLOCKIRQ", true),
119            interrupt_pacing: match num("KVMTRACE_IRQ_EVERY") {
120                Some(0) => None,
121                Some(n) => Some(n),
122                None => Some(50_000),
123            },
124            macsim: env_flag("KVMTRACE_MACSIM", true),
125            macsim_sideband: env_flag("KVMTRACE_SIDE", true),
126            extended: env_flag("KVMTRACE_KVT", true),
127            max_instructions: num("KVMTRACE_MAX"),
128            trap_flag_guard: env_flag("KVMTRACE_TF_GUARD", true),
129            ..TraceOptions::default()
130        };
131        let secs = |name: &str| -> Option<Duration> {
132            let v = std::env::var(name).ok()?;
133            match parse_secs(&v) {
134                Some(d) => Some(d),
135                None => {
136                    eprintln!("kvmtrace: ignoring {name}={v}: expected seconds, e.g. 2.5");
137                    None
138                }
139            }
140        };
141        let start = match std::env::var("KVMTRACE_START").as_deref() {
142            Ok("now") => Start::Now,
143            Ok(v) if v.starts_with("after:") => match parse_secs(&v[6..]) {
144                Some(d) => Start::After(d),
145                None => {
146                    eprintln!("kvmtrace: ignoring KVMTRACE_START={v}: expected after:SECONDS");
147                    Start::Marker
148                }
149            },
150            _ => Start::Marker,
151        };
152        let every = secs("KVMTRACE_EVERY");
153        let control = std::env::var_os("KVMTRACE_CONTROL").map(PathBuf::from);
154        // One window unless the run is set up to have several.
155        let max_windows = match num("KVMTRACE_WINDOWS") {
156            Some(0) => None,
157            Some(n) => Some(n),
158            None if every.is_some() || control.is_some() => None,
159            None => Some(1),
160        };
161        Config {
162            out: std::env::var_os("KVMTRACE_OUT").map(PathBuf::from).unwrap_or_else(|| "kvmtrace-out".into()),
163            start,
164            duration: secs("KVMTRACE_DURATION"),
165            every,
166            max_windows,
167            control,
168            port: num("KVMTRACE_PORT").unwrap_or(0x278) as u16,
169            opts,
170            verbose: env_flag("KVMTRACE_VERBOSE", false),
171            keep_steal_time: env_flag("KVMTRACE_KEEP_STEAL_TIME", false),
172        }
173    }
174}
175
176/// Parses "2", "2.5", "500ms", "2s", "1m".
177fn parse_secs(v: &str) -> Option<Duration> {
178    let v = v.trim();
179    let (n, scale) = if let Some(x) = v.strip_suffix("ms") {
180        (x, 1e-3)
181    } else if let Some(x) = v.strip_suffix('s') {
182        (x, 1.0)
183    } else if let Some(x) = v.strip_suffix('m') {
184        (x, 60.0)
185    } else {
186        (v, 1.0)
187    };
188    let f: f64 = n.trim().parse().ok()?;
189    (f.is_finite() && f >= 0.0).then(|| Duration::from_secs_f64(f * scale))
190}
191
192impl Config {
193    /// Several windows are possible: each gets its own directory.
194    fn multi_window(&self) -> bool {
195        self.max_windows != Some(1)
196    }
197
198    fn window_dir(&self, n: u64) -> PathBuf {
199        if self.multi_window() { self.out.join(format!("window-{n:03}")) } else { self.out.clone() }
200    }
201}
202
203/// Marker values the guest writes to the marker port.
204mod marker {
205    pub const START: u32 = 1;
206    pub const STOP: u32 = 2;
207}
208
209struct Slot {
210    id: u32,
211    vcpu: VcpuFd,
212    tracer: Option<KvmTracer>,
213    /// The VMM changed registers or debug state behind our back.
214    resync: bool,
215    done: bool,
216    /// This vCPU has `KVM_GUESTDBG_USE_SW_BP` on (see [`Gate`]).
217    prearmed: bool,
218    /// This vCPU has arrived at the stop rendezvous.
219    stopping: bool,
220    /// The serialization token, kept while an entry breakpoint is lifted.
221    held: Option<kvmtrace::Token>,
222    /// This vCPU wrote STOP: close the window after its next step, so the
223    /// STOP `out` itself (which KVM completes on re-entry) is recorded.
224    stop_after_step: bool,
225    /// The window this slot's per-window state belongs to.
226    window: u64,
227}
228
229/// The rendezvous that keeps entry breakpoints safe on SMP guests.
230///
231/// The tracer plants `int3` bytes on interrupt, exception and system-call
232/// entry points. A vCPU that runs with `KVM_GUESTDBG_USE_SW_BP` turns
233/// them into exits to us; a vCPU that runs *without* it delivers #BP to
234/// the guest instead, and since the #BP handler's own first byte is a
235/// breakpoint too, the guest recurses until it overflows its stack and
236/// panics. So the invariant is:
237///
238/// > while any breakpoint is in guest memory, every vCPU that can run
239/// > guest code has `USE_SW_BP` enabled.
240///
241/// Starting: each vCPU switches `USE_SW_BP` on ("prearms") and waits
242/// until all have; only then does tracing (and planting) begin. Stopping:
243/// each traced vCPU waits until all have arrived, one of them removes the
244/// breakpoints, and only then does any vCPU switch its debug state off.
245/// Waits are bounded: on timeout the hook returns `EINTR`, which QEMU
246/// treats like a kick, so cross-vCPU work in QEMU (`run_on_cpu`) is
247/// never deadlocked; the vCPU re-enters the hook and keeps waiting
248/// without running guest code.
249#[derive(Default)]
250struct Gate {
251    prearmed: u32,
252    stopping: u32,
253    removed: bool,
254}
255
256const GATE_WAIT: Duration = Duration::from_millis(100);
257
258struct Global {
259    cfg: Config,
260    mem: Arc<MappedMemory>,
261    kvm: Kvm,
262    vm: Mutex<Option<VmFd>>,
263    vcpus: Mutex<HashMap<RawFd, Arc<Mutex<Slot>>>>,
264    tids: Mutex<HashMap<u32, libc::pid_t>>,
265    session: Mutex<Option<Session>>,
266    /// Desired state: true while the trace window is open.
267    tracing: AtomicBool,
268    /// A window is open or still closing (from START until its files are written).
269    active: AtomicBool,
270    /// START arrived while the previous window was still closing.
271    pending_start: AtomicBool,
272    /// The current (or next) window's number; bumped when a window finishes.
273    window: AtomicU64,
274    /// Windows opened so far.
275    windows_opened: AtomicU64,
276    /// Serializes opening and closing windows.
277    ctl: Mutex<()>,
278    /// Instructions recorded in finished windows.
279    total_instructions: AtomicU64,
280    /// Stale single-step traps absorbed between windows.
281    stale_traps: AtomicU64,
282    finished_vcpus: AtomicU32,
283    traced_vcpus: AtomicU32,
284    steps: AtomicU64,
285    vm_fd: AtomicI32,
286    gate: Mutex<Gate>,
287    gate_cv: Condvar,
288    finished: AtomicBool,
289    /// When the trace window opened (for the rate in the final message).
290    started: Mutex<Option<std::time::Instant>>,
291}
292
293fn global() -> &'static Global {
294    static G: OnceLock<Global> = OnceLock::new();
295    G.get_or_init(|| {
296        let cfg = Config::from_env();
297        let g = Global {
298            mem: Arc::new(MappedMemory::new()),
299            kvm: Kvm::new().expect("kvmtrace: open /dev/kvm"),
300            vm: Mutex::new(None),
301            vcpus: Mutex::new(HashMap::new()),
302            tids: Mutex::new(HashMap::new()),
303            session: Mutex::new(None),
304            tracing: AtomicBool::new(false),
305            active: AtomicBool::new(false),
306            pending_start: AtomicBool::new(false),
307            window: AtomicU64::new(0),
308            windows_opened: AtomicU64::new(0),
309            ctl: Mutex::new(()),
310            total_instructions: AtomicU64::new(0),
311            stale_traps: AtomicU64::new(0),
312            finished_vcpus: AtomicU32::new(0),
313            traced_vcpus: AtomicU32::new(0),
314            steps: AtomicU64::new(0),
315            vm_fd: AtomicI32::new(-1),
316            gate: Mutex::new(Gate::default()),
317            gate_cv: Condvar::new(),
318            finished: AtomicBool::new(false),
319            started: Mutex::new(None),
320            cfg,
321        };
322        if g.cfg.verbose {
323            eprintln!(
324                "kvmtrace: loaded; out={} start={:?} duration={:?} every={:?} windows={:?} control={:?} port={:#x} order={:?}",
325                g.cfg.out.display(),
326                g.cfg.start,
327                g.cfg.duration,
328                g.cfg.every,
329                g.cfg.max_windows,
330                g.cfg.control,
331                g.cfg.port,
332                g.cfg.opts.ordering
333            );
334        }
335        // SAFETY: registering a plain extern "C" fn.
336        unsafe { libc::atexit(at_exit) };
337        g
338    })
339}
340
341/// Opens a window (from a marker, the schedule or the control socket).
342/// Returns false if it cannot: the window limit is reached.
343fn request_start(g: &Global, from: u32) -> bool {
344    let _l = g.ctl.lock().unwrap();
345    if g.tracing.load(AtOrd::SeqCst) {
346        return true; // already open
347    }
348    if g.active.load(AtOrd::SeqCst) {
349        // The previous window is still being closed: open right after.
350        g.pending_start.store(true, AtOrd::SeqCst);
351        return true;
352    }
353    let n = g.windows_opened.load(AtOrd::SeqCst);
354    if g.cfg.max_windows.is_some_and(|m| n >= m) {
355        if g.cfg.verbose || n == 1 {
356            eprintln!("kvmtrace: window limit ({n}) reached; ignoring START (set KVMTRACE_WINDOWS for more)");
357        }
358        return false;
359    }
360    g.windows_opened.store(n + 1, AtOrd::SeqCst);
361    g.active.store(true, AtOrd::SeqCst);
362    g.tracing.store(true, AtOrd::SeqCst);
363    if g.cfg.verbose {
364        eprintln!("kvmtrace: window {} opening -> {}", g.window.load(AtOrd::SeqCst), g.cfg.window_dir(g.window.load(AtOrd::SeqCst)).display());
365    }
366    drop(_l);
367    kick_all(g, from);
368    true
369}
370
371/// Closes the current window; `only` restricts it to that window number
372/// (a timer must not close a later window).
373fn request_stop(g: &Global, from: u32, only: Option<u64>) {
374    let l = g.ctl.lock().unwrap();
375    if only.is_some_and(|w| w != g.window.load(AtOrd::SeqCst)) {
376        return;
377    }
378    g.pending_start.store(false, AtOrd::SeqCst);
379    if !g.tracing.swap(false, AtOrd::SeqCst) {
380        return;
381    }
382    if g.traced_vcpus.load(AtOrd::SeqCst) == 0 {
383        // No vCPU got as far as tracing: nothing to write.
384        drop(l);
385        finish_session(g);
386        return;
387    }
388    drop(l);
389    kick_all(g, from);
390}
391
392/// Once a window's files are written: reset for the next window.
393fn reset_window(g: &Global) {
394    {
395        let _l = g.ctl.lock().unwrap();
396        *g.session.lock().unwrap() = None;
397        *g.gate.lock().unwrap() = Gate::default();
398        g.finished_vcpus.store(0, AtOrd::SeqCst);
399        g.traced_vcpus.store(0, AtOrd::SeqCst);
400        *g.started.lock().unwrap() = None;
401        g.window.fetch_add(1, AtOrd::SeqCst);
402        g.finished.store(false, AtOrd::SeqCst);
403        g.active.store(false, AtOrd::SeqCst);
404    }
405    if g.pending_start.swap(false, AtOrd::SeqCst) {
406        request_start(g, u32::MAX);
407    }
408}
409
410/// Opens and closes windows on the configured schedule. Runs on its own
411/// thread from the guest's first instruction.
412fn scheduler(g: &'static Global) {
413    let t0 = Instant::now();
414    let mut next = match g.cfg.start {
415        Start::Now => None, // opened before the guest's first instruction
416        Start::After(d) => Some(t0 + d),
417        Start::Marker => None, // markers or the control socket open windows
418    };
419    loop {
420        // Open the next scheduled window, if there is one.
421        if let Some(at) = next {
422            if let Some(w) = at.checked_duration_since(Instant::now()) {
423                std::thread::sleep(w);
424            }
425            // Wait for a previous window to finish closing.
426            while g.active.load(AtOrd::SeqCst) {
427                std::thread::sleep(Duration::from_millis(5));
428            }
429            if !request_start(g, u32::MAX) {
430                return;
431            }
432            next = g.cfg.every.map(|e| at + e);
433        } else {
434            // Wait for a window opened by a marker or the control socket.
435            while !g.active.load(AtOrd::SeqCst) {
436                std::thread::sleep(Duration::from_millis(5));
437            }
438            // Repeat from here, if asked to.
439            next = g.cfg.every.map(|e| Instant::now() + e);
440        }
441        let w = g.window.load(AtOrd::SeqCst);
442        if let Some(d) = g.cfg.duration {
443            std::thread::sleep(d);
444            request_stop(g, u32::MAX, Some(w));
445        }
446        // Next round: after this window is fully written.
447        while g.window.load(AtOrd::SeqCst) == w && g.active.load(AtOrd::SeqCst) {
448            std::thread::sleep(Duration::from_millis(5));
449        }
450        if next.is_none() && g.cfg.duration.is_none() {
451            return; // nothing left to time
452        }
453        if g.cfg.max_windows.is_some_and(|m| g.windows_opened.load(AtOrd::SeqCst) >= m) {
454            return;
455        }
456    }
457}
458
459/// Serves the control socket: one command per line.
460///
461/// ```text
462/// start [SECONDS]   open a window (closing it after SECONDS, if given)
463/// stop              close the current window
464/// status            "tracing window N, I instructions so far" or "idle ..."
465/// ```
466fn control_server(g: &'static Global, path: PathBuf) {
467    use std::io::{BufRead, BufReader, Write};
468    let _ = std::fs::remove_file(&path);
469    let listener = match std::os::unix::net::UnixListener::bind(&path) {
470        Ok(l) => l,
471        Err(e) => {
472            eprintln!("kvmtrace: control socket {}: {e}", path.display());
473            return;
474        }
475    };
476    if g.cfg.verbose {
477        eprintln!("kvmtrace: control socket at {}", path.display());
478    }
479    for conn in listener.incoming().flatten() {
480        let mut w = match conn.try_clone() {
481            Ok(w) => w,
482            Err(_) => continue,
483        };
484        for line in BufReader::new(conn).lines() {
485            let Ok(line) = line else { break };
486            let mut it = line.split_whitespace();
487            let reply = match (it.next(), it.next()) {
488                (Some("start"), secs) => {
489                    let d = secs.and_then(parse_secs);
490                    if secs.is_some() && d.is_none() {
491                        "error: expected start [SECONDS]".to_string()
492                    } else if request_start(g, u32::MAX) {
493                        let wnum = g.window.load(AtOrd::SeqCst);
494                        if let Some(d) = d {
495                            std::thread::spawn(move || {
496                                std::thread::sleep(d);
497                                request_stop(g, u32::MAX, Some(wnum));
498                            });
499                        }
500                        format!("ok: window {wnum} -> {}", g.cfg.window_dir(wnum).display())
501                    } else {
502                        "error: window limit reached".to_string()
503                    }
504                }
505                (Some("stop"), None) => {
506                    let wnum = g.window.load(AtOrd::SeqCst);
507                    let was = g.tracing.load(AtOrd::SeqCst);
508                    request_stop(g, u32::MAX, None);
509                    if was { format!("ok: window {wnum} closing") } else { "ok: not tracing".to_string() }
510                }
511                (Some("status"), None) => status(g),
512                _ => "error: commands are: start [SECONDS] | stop | status".to_string(),
513            };
514            if writeln!(w, "{reply}").is_err() {
515                break;
516            }
517        }
518    }
519}
520
521fn status(g: &Global) -> String {
522    let wnum = g.window.load(AtOrd::SeqCst);
523    let done = g.total_instructions.load(AtOrd::SeqCst);
524    if g.tracing.load(AtOrd::SeqCst) {
525        let secs = g.started.lock().unwrap().map(|t| t.elapsed().as_secs_f64()).unwrap_or(0.0);
526        format!("tracing window {wnum} for {secs:.1} s; {} steps so far in all windows", g.steps.load(AtOrd::Relaxed))
527    } else if g.active.load(AtOrd::SeqCst) {
528        format!("closing window {wnum}")
529    } else {
530        format!(
531            "idle; {} windows written, {done} instructions; {} stale traps absorbed",
532            g.windows_opened.load(AtOrd::SeqCst),
533            g.stale_traps.load(AtOrd::Relaxed)
534        )
535    }
536}
537
538/// Starts the scheduler and the control socket on the guest's first run.
539fn start_background(g: &'static Global) {
540    static ONCE: OnceLock<()> = OnceLock::new();
541    ONCE.get_or_init(|| {
542        if g.cfg.start == Start::Now {
543            request_start(g, u32::MAX);
544        }
545        if g.cfg.start != Start::Marker || g.cfg.every.is_some() || g.cfg.duration.is_some() {
546            std::thread::Builder::new().name("kvmtrace-sched".into()).spawn(move || scheduler(g)).ok();
547        }
548        if let Some(p) = g.cfg.control.clone() {
549            std::thread::Builder::new().name("kvmtrace-ctl".into()).spawn(move || control_server(g, p)).ok();
550        }
551    });
552}
553
554fn session(g: &Global) -> Option<Session> {
555    let mut s = g.session.lock().unwrap();
556    if s.is_none() {
557        let dir = g.cfg.window_dir(g.window.load(AtOrd::SeqCst));
558        match Session::new(g.cfg.opts.clone(), g.mem.clone(), Some(&dir)) {
559            Ok(x) => *s = Some(x),
560            Err(e) => {
561                eprintln!("kvmtrace: cannot start session: {e}");
562                return None;
563            }
564        }
565    }
566    s.clone()
567}
568
569/// Kicks every other vCPU out of KVM_RUN so it notices a state change.
570fn kick_all(g: &Global, except: u32) {
571    // SAFETY: getpid has no preconditions.
572    let pid = unsafe { libc::getpid() };
573    for (&id, &tid) in g.tids.lock().unwrap().iter() {
574        if id != except {
575            // SAFETY: tgkill to a thread of our own process; QEMU's SIG_IPI (SIGUSR1)
576            // handler is installed and only makes KVM_RUN return -EINTR.
577            unsafe { libc::syscall(libc::SYS_tgkill, pid, tid, libc::SIGUSR1) };
578        }
579    }
580}
581
582fn on_create_vm(g: &Global, fd: c_int) {
583    g.vm_fd.store(fd, AtOrd::SeqCst);
584    // SAFETY: dup of a valid fd; the wrapper owns the duplicate.
585    let dup = unsafe { libc::dup(fd) };
586    // SAFETY: `dup` is a fresh fd for the VM.
587    match unsafe { g.kvm.create_vmfd_from_rawfd(dup) } {
588        Ok(vm) => *g.vm.lock().unwrap() = Some(vm),
589        Err(e) => eprintln!("kvmtrace: cannot wrap VM fd: {e}"),
590    }
591}
592
593fn on_create_vcpu(g: &Global, id: u32, fd: c_int) {
594    let vm = g.vm.lock().unwrap();
595    let Some(vm) = vm.as_ref() else { return };
596    // SAFETY: dup of a valid fd.
597    let dup = unsafe { libc::dup(fd) };
598    // SAFETY: `dup` is a fresh fd for a vCPU of `vm`.
599    match unsafe { vm.create_vcpu_from_rawfd(dup) } {
600        Ok(vcpu) => {
601            g.vcpus.lock().unwrap().insert(fd, Arc::new(Mutex::new(Slot { id, vcpu, tracer: None, resync: false, done: false, prearmed: false, stopping: false, held: None, stop_after_step: false, window: 0 })));
602        }
603        Err(e) => eprintln!("kvmtrace: cannot wrap vCPU {id}: {e}"),
604    }
605}
606
607fn on_memory_region(g: &Global, arg: *mut c_void) {
608    // kvm_userspace_memory_region and ..._region2 share their first 32 bytes.
609    // SAFETY: the VMM passed a valid pointer to at least this prefix.
610    let r = unsafe { &*(arg as *const kvm_userspace_memory_region) };
611    let as_id = r.slot >> 16;
612    if as_id != 0 {
613        return; // SMM address space
614    }
615    // SAFETY: the VMM keeps guest RAM mapped while the slot exists.
616    unsafe { g.mem.set_region(r.slot, r.guest_phys_addr, r.memory_size, r.userspace_addr as usize) };
617}
618
619/// Forwards KVM_SET_CPUID2 with the paravirtual steal-time feature hidden.
620///
621/// The guest reads its steal-time record in a retry loop that gives up only
622/// when the record's version number is the same before and after the read.
623/// KVM rewrites the record, bumping the version, every time a vCPU is
624/// loaded, which means on every `KVM_RUN` ioctl. Single-stepping issues one
625/// `KVM_RUN` per instruction, so the two reads never agree and the guest
626/// spins forever inside `kvm_steal_clock`. Hiding the feature from CPUID
627/// (as `-cpu host,-kvm-steal-time` would) avoids it.
628fn set_cpuid_without_steal_time(fd: c_int, arg: *mut c_void, verbose: bool) -> c_int {
629    let real = real_ioctl();
630    // struct kvm_cpuid2 { u32 nent; u32 padding; struct kvm_cpuid_entry2 entries[]; }
631    // struct kvm_cpuid_entry2 { u32 function, index, flags, eax, ebx, ecx, edx, padding[3]; }
632    const ENTRY_WORDS: usize = 10;
633    // SAFETY: the VMM passed a valid kvm_cpuid2; we read nent, then copy it whole.
634    let nent = unsafe { *(arg as *const u32) } as usize;
635    let words = 2 + nent * ENTRY_WORDS;
636    let mut copy = vec![0u32; words];
637    // SAFETY: `words` u32s are valid behind `arg` (header plus nent entries).
638    unsafe { std::ptr::copy_nonoverlapping(arg as *const u32, copy.as_mut_ptr(), words) };
639    let entry = |k: usize| 2 + k * ENTRY_WORDS;
640    let bases: Vec<u32> = (0..nent)
641        .filter(|&k| {
642            let f = copy[entry(k)];
643            (0x4000_0000..0x4001_0000).contains(&f) && f & 0xff == 0 && copy[entry(k) + 4] == KVM_SIGNATURE_EBX
644        })
645        .map(|k| copy[entry(k)])
646        .collect();
647    for k in 0..nent {
648        if bases.contains(&copy[entry(k)].wrapping_sub(1)) && copy[entry(k) + 3] & KVM_FEATURE_STEAL_TIME != 0 {
649            copy[entry(k) + 3] &= !KVM_FEATURE_STEAL_TIME;
650            if verbose {
651                eprintln!("kvmtrace: hiding KVM steal time from the guest (CPUID {:#x})", copy[entry(k)]);
652            }
653        }
654    }
655    // SAFETY: KVM_SET_CPUID2 with our well-formed copy.
656    unsafe { real(fd, KVM_SET_CPUID2, copy.as_mut_ptr() as *mut c_void) }
657}
658
659/// Waits (bounded) until `ready` holds. False on timeout.
660fn wait_gate(g: &Global, ready: impl Fn(&Gate) -> bool) -> bool {
661    let guard = g.gate.lock().unwrap();
662    let (guard, _) = g.gate_cv.wait_timeout_while(guard, GATE_WAIT, |x| !ready(x)).unwrap();
663    ready(&guard)
664}
665
666/// What a kicked `KVM_RUN` returns: -1 with errno EINTR.
667fn eintr() -> c_int {
668    // SAFETY: errno is thread-local and always valid.
669    unsafe { *libc::__errno_location() = libc::EINTR };
670    -1
671}
672
673/// Handles KVM_RUN for a vCPU we know about.
674fn run_vcpu(g: &'static Global, fd: c_int, slot: &Arc<Mutex<Slot>>) -> c_int {
675    let real = real_ioctl();
676    let mut s = slot.lock().unwrap();
677    {
678        let mut t = g.tids.lock().unwrap();
679        // SAFETY: gettid has no preconditions.
680        t.entry(s.id).or_insert_with(|| unsafe { libc::gettid() });
681    }
682    start_background(g);
683    loop {
684        // A new window: forget the last one's per-vCPU state.
685        let current = g.window.load(AtOrd::SeqCst);
686        if s.window != current && (s.done || s.tracer.is_none()) {
687            s.window = current;
688            s.tracer = None;
689            s.done = false;
690            s.prearmed = false;
691            s.stopping = false;
692            s.held = None;
693            s.stop_after_step = false;
694        }
695        let want = g.tracing.load(AtOrd::SeqCst);
696        // Apply the desired state on this (the vCPU's own) thread.
697        if want && !s.done && s.tracer.as_ref().is_none_or(|t| !t.is_enabled()) {
698            if let Some(sess) = session(g) {
699                if s.tracer.is_none() {
700                    // Under `ctl`, so a concurrent stop sees the count.
701                    let _l = g.ctl.lock().unwrap();
702                    if !g.tracing.load(AtOrd::SeqCst) || g.window.load(AtOrd::SeqCst) != s.window {
703                        continue;
704                    }
705                    match KvmTracer::new(&sess, s.id) {
706                        Ok(t) => {
707                            s.tracer = Some(t);
708                            g.traced_vcpus.fetch_add(1, AtOrd::SeqCst);
709                        }
710                        Err(e) => eprintln!("kvmtrace: vCPU {}: {e}", s.id),
711                    }
712                }
713                // Phase 1: USE_SW_BP on, then wait for every vCPU to do the same.
714                if !s.prearmed {
715                    let Slot { vcpu, tracer, .. } = &mut *s;
716                    if let Some(t) = tracer {
717                        if let Err(e) = t.prearm(vcpu) {
718                            eprintln!("kvmtrace: prearm vCPU {}: {e}", s.id);
719                        } else {
720                            s.prearmed = true;
721                            g.gate.lock().unwrap().prearmed += 1;
722                            g.gate_cv.notify_all();
723                        }
724                    }
725                }
726                let n = g.vcpus.lock().unwrap().len() as u32;
727                if s.prearmed && !wait_gate(g, |x| x.prearmed >= n) {
728                    return eintr();
729                }
730                // Phase 2: everyone is protected; start stepping (this plants breakpoints).
731                g.started.lock().unwrap().get_or_insert_with(std::time::Instant::now);
732                let Slot { vcpu, tracer, .. } = &mut *s;
733                if let Some(t) = tracer {
734                    if let Err(e) = t.enable(vcpu) {
735                        eprintln!("kvmtrace: enable vCPU {}: {e}", s.id);
736                    } else if g.cfg.verbose {
737                        eprintln!("kvmtrace: vCPU {} tracing", s.id);
738                    }
739                }
740            }
741        } else if !want && s.tracer.is_some() && !s.done {
742            // Stop rendezvous: stay protected until the breakpoints are gone.
743            // Give up a held token first, or a vCPU waiting for it could never
744            // get here (its lifted step will not be recorded anyway).
745            s.held = None;
746            if !s.stopping {
747                s.stopping = true;
748                g.gate.lock().unwrap().stopping += 1;
749                g.gate_cv.notify_all();
750            }
751            if !wait_gate(g, |x| x.stopping >= x.prearmed) {
752                return eintr();
753            }
754            {
755                let mut gate = g.gate.lock().unwrap();
756                if !gate.removed {
757                    if let Some(sess) = g.session.lock().unwrap().as_ref() {
758                        sess.remove_breakpoints();
759                    }
760                    gate.removed = true;
761                }
762            }
763            stop_vcpu(g, &mut s);
764        } else if s.resync && s.tracer.as_ref().is_some_and(|t| t.is_enabled()) {
765            // Registers were rewritten by the VMM: forget the pending step and restart.
766            let Slot { vcpu, tracer, .. } = &mut *s;
767            let t = tracer.as_mut().unwrap();
768            let _ = t.disable(vcpu);
769            let _ = t.enable(vcpu);
770        }
771        s.resync = false;
772
773        let enabled = s.tracer.as_ref().is_some_and(|t| t.is_enabled());
774        let sess = if enabled { g.session.lock().unwrap().clone() } else { None };
775        let held = s.held.take();
776        let token = match (&sess, enabled) {
777            (_, true) if held.is_some() => held,
778            (Some(sess), true) => {
779                let Slot { vcpu, tracer, .. } = &mut *s;
780                if tracer.as_mut().unwrap().needs_token(vcpu) { sess.token() } else { None }
781            }
782            _ => None,
783        };
784        // SAFETY: KVM_RUN on the VMM's own vCPU fd.
785        let r = unsafe { real(fd, KVM_RUN, std::ptr::null_mut()) };
786        let lifted = s.tracer.as_ref().is_some_and(|t| t.holds_lifted_breakpoint());
787        if r < 0 {
788            // Kicked (EINTR) mid-way: keep the token if a breakpoint is lifted.
789            if lifted {
790                s.held = token;
791            }
792            return r;
793        }
794        let run = s.vcpu.get_kvm_run();
795        let reason = run.exit_reason;
796        if reason == KVM_EXIT_IO {
797            // SAFETY: exit_reason says the io member is active.
798            let io = unsafe { run.__bindgen_anon_1.io };
799            if io.port == g.cfg.port {
800                let data = (run as *mut kvm_run as *mut u8).wrapping_add(io.data_offset as usize);
801                if io.direction == KVM_EXIT_IO_OUT as u8 {
802                    let mut v = [0u8; 4];
803                    let n = (io.size as usize).min(4);
804                    // SAFETY: KVM placed `size` bytes at data_offset inside the run page.
805                    unsafe { std::ptr::copy_nonoverlapping(data, v.as_mut_ptr(), n) };
806                    let v = u32::from_le_bytes(v);
807                    drop(token);
808                    if v == marker::STOP && s.tracer.as_ref().is_some_and(|t| t.is_enabled()) {
809                        if g.cfg.verbose {
810                            eprintln!("kvmtrace: STOP from vCPU {}", s.id);
811                        }
812                        s.stop_after_step = true;
813                    } else {
814                        handle_marker(g, s.id, v);
815                    }
816                } else {
817                    // `in` from the port answers 'K': the tracer is present.
818                    // SAFETY: as above, for writing.
819                    unsafe { std::ptr::write_bytes(data, b'K', io.size as usize * io.count as usize) };
820                    drop(token);
821                }
822                continue; // re-enter to complete the instruction
823            }
824        }
825        if reason == KVM_EXIT_DEBUG && enabled {
826            // SAFETY: exit_reason says the debug member is active.
827            let d = unsafe { run.__bindgen_anon_1.debug.arch };
828            let unserialized = token.is_none() && g.cfg.opts.ordering == Ordering::Serialized;
829            let Slot { vcpu, tracer, .. } = &mut *s;
830            let t = tracer.as_mut().unwrap();
831            match t.on_debug_exit(vcpu, &d, unserialized) {
832                Ok(a) => {
833                    if a.stop {
834                        // Budget used up: close the window for everyone (the
835                        // stop rendezvous at the top of the loop does the rest).
836                        drop(token);
837                        request_stop(g, s.id, None);
838                        continue;
839                    }
840                }
841                Err(e) => {
842                    eprintln!("kvmtrace: vCPU {}: {e}; stopping", s.id);
843                    drop(token);
844                    request_stop(g, s.id, None);
845                    continue;
846                }
847            }
848            if s.tracer.as_ref().is_some_and(|t| t.holds_lifted_breakpoint()) {
849                s.held = token; // no other vCPU may run until the breakpoint is back
850            } else {
851                drop(token);
852            }
853            if std::mem::take(&mut s.stop_after_step) {
854                // The STOP `out` has now been recorded: close the window.
855                handle_marker(g, s.id, marker::STOP);
856            }
857            g.steps.fetch_add(1, AtOrd::Relaxed);
858            continue;
859        }
860        if reason == KVM_EXIT_DEBUG && !enabled {
861            // Between windows: a trap flag the guest restored from a copy
862            // saved while it was being stepped (see absorb_stale_single_step).
863            // SAFETY: exit_reason says the debug member is active.
864            let d = unsafe { run.__bindgen_anon_1.debug.arch };
865            match kvmtrace::kvm::absorb_stale_single_step(&s.vcpu, &d) {
866                Ok(true) => {
867                    let n = g.stale_traps.fetch_add(1, AtOrd::Relaxed) + 1;
868                    if g.cfg.verbose {
869                        eprintln!("kvmtrace: vCPU {}: absorbed stale single-step trap #{n} at {:#x}", s.id, d.pc);
870                    }
871                    continue;
872                }
873                Ok(false) => {}
874                Err(e) => eprintln!("kvmtrace: vCPU {}: {e}", s.id),
875            }
876        }
877        // An exit for QEMU (I/O, MMIO, ...). The instruction under a lifted
878        // breakpoint may not have completed yet: keep the token if so.
879        if s.tracer.as_ref().is_some_and(|t| t.holds_lifted_breakpoint()) {
880            s.held = token;
881        }
882        return r;
883    }
884}
885
886fn handle_marker(g: &Global, from: u32, v: u32) {
887    match v {
888        marker::START => {
889            if g.cfg.verbose {
890                eprintln!("kvmtrace: START from vCPU {from}");
891            }
892            request_start(g, from);
893        }
894        marker::STOP => {
895            if g.cfg.verbose {
896                eprintln!("kvmtrace: STOP from vCPU {from}");
897            }
898            request_stop(g, from, None);
899        }
900        _ => {}
901    }
902}
903
904fn stop_vcpu(g: &Global, s: &mut Slot) {
905    let Slot { vcpu, tracer, done, id, .. } = s;
906    if let Some(t) = tracer {
907        // The vCPU that wrote STOP has completed that `out`: record it.
908        if let Err(e) = t.flush(vcpu) {
909            eprintln!("kvmtrace: vCPU {id}: {e}");
910        }
911        let _ = t.disable(vcpu);
912        if let Err(e) = t.finish() {
913            eprintln!("kvmtrace: vCPU {id}: finishing trace files: {e}");
914        }
915    }
916    if !*done {
917        *done = true;
918        let n = g.finished_vcpus.fetch_add(1, AtOrd::SeqCst) + 1;
919        if g.cfg.verbose {
920            eprintln!("kvmtrace: vCPU {id} stopped ({n}/{} traced vCPUs)", g.traced_vcpus.load(AtOrd::SeqCst));
921        }
922        if n == g.traced_vcpus.load(AtOrd::SeqCst) {
923            finish_session(g);
924        }
925    }
926}
927
928fn finish_session(g: &Global) {
929    if g.finished.swap(true, AtOrd::SeqCst) {
930        return;
931    }
932    let wnum = g.window.load(AtOrd::SeqCst);
933    let sess = g.session.lock().unwrap().clone();
934    if let Some(sess) = sess {
935        match sess.finish() {
936            Ok(st) => {
937                g.total_instructions.fetch_add(st.instructions, AtOrd::SeqCst);
938                let secs = g.started.lock().unwrap().map(|t| t.elapsed().as_secs_f64()).unwrap_or(0.0);
939                eprintln!(
940                    "kvmtrace: trace written to {} ({} instructions, {} events, {} gaps; {:.2} s, {:.0} instructions/s)",
941                    g.cfg.window_dir(wnum).display(),
942                    st.instructions,
943                    st.events,
944                    st.gaps,
945                    secs,
946                    st.instructions as f64 / secs.max(1e-9)
947                )
948            }
949            Err(e) => eprintln!("kvmtrace: finishing session: {e}"),
950        }
951    }
952    reset_window(g);
953}
954
955extern "C" fn at_exit() {
956    let g = global();
957    if g.traced_vcpus.load(AtOrd::SeqCst) == 0 {
958        return;
959    }
960    IN_HOOK.with(|f| f.set(true));
961    g.pending_start.store(false, AtOrd::SeqCst);
962    g.tracing.store(false, AtOrd::SeqCst);
963    // The process is exiting: take the breakpoints out of guest RAM first.
964    if let Some(sess) = g.session.lock().unwrap().as_ref() {
965        sess.remove_breakpoints();
966    }
967    // Best effort: finish vCPUs whose threads are idle; skip any that are busy.
968    let slots: Vec<_> = g.vcpus.lock().unwrap().values().cloned().collect();
969    for sl in slots {
970        if let Ok(mut s) = sl.try_lock() {
971            if !s.done && s.tracer.is_some() {
972                stop_vcpu(g, &mut s);
973            }
974        }
975    }
976    finish_session(g);
977}
978
979/// The `ioctl` every caller in the process gets instead of libc's.
980///
981/// # Safety
982///
983/// Same contract as `ioctl(2)`. On x86-64 a variadic call with one
984/// pointer-sized argument is ABI-compatible with this signature.
985#[unsafe(no_mangle)]
986pub unsafe extern "C" fn ioctl(fd: c_int, request: c_ulong, arg: *mut c_void) -> c_int {
987    let real = real_ioctl();
988    // Fast path: only a handful of KVM requests interest us.
989    let interesting = matches!(
990        request,
991        KVM_RUN | KVM_CREATE_VM | KVM_CREATE_VCPU | KVM_SET_USER_MEMORY_REGION | KVM_SET_USER_MEMORY_REGION2 | KVM_SET_REGS | KVM_SET_SREGS | KVM_SET_GUEST_DEBUG | KVM_SET_CPUID2
992    );
993    if !interesting || IN_HOOK.with(|f| f.get()) {
994        // SAFETY: forwarding the caller's arguments unchanged.
995        return unsafe { real(fd, request, arg) };
996    }
997    IN_HOOK.with(|f| f.set(true));
998    let g = global();
999    let r = match request {
1000        KVM_RUN => {
1001            let slot = g.vcpus.lock().unwrap().get(&fd).cloned();
1002            match slot {
1003                Some(slot) => run_vcpu(g, fd, &slot),
1004                // SAFETY: forwarding.
1005                None => unsafe { real(fd, request, arg) },
1006            }
1007        }
1008        KVM_SET_CPUID2 if !g.cfg.keep_steal_time => set_cpuid_without_steal_time(fd, arg, g.cfg.verbose),
1009        _ => {
1010            // SAFETY: forwarding.
1011            let r = unsafe { real(fd, request, arg) };
1012            if r >= 0 {
1013                match request {
1014                    KVM_CREATE_VM => on_create_vm(g, r),
1015                    KVM_CREATE_VCPU => on_create_vcpu(g, arg as usize as u32, r),
1016                    KVM_SET_USER_MEMORY_REGION | KVM_SET_USER_MEMORY_REGION2 => on_memory_region(g, arg),
1017                    KVM_SET_REGS | KVM_SET_SREGS | KVM_SET_GUEST_DEBUG => {
1018                        if let Some(sl) = g.vcpus.lock().unwrap().get(&fd) {
1019                            if let Ok(mut s) = sl.try_lock() {
1020                                s.resync = true;
1021                            }
1022                        }
1023                    }
1024                    _ => {}
1025                }
1026            }
1027            r
1028        }
1029    };
1030    IN_HOOK.with(|f| f.set(false));
1031    r
1032}
1033