Skip to main content

Module ch02_your_first_trace

Module ch02_your_first_trace 

Source
Expand description

§Your First Trace

The best way to understand a tracer is to trace something small enough that you can check every line by hand. So in this chapter we build a virtual machine with exactly one page of code, run it under kvmtrace, and look at what comes out.

§A guest you can read

kvmtrace comes with MiniVm, a minimal virtual machine that is already in 64-bit mode with paging on, so we can skip the boot process entirely. Our guest program adds the numbers 1 to 3 into memory and halts:

mov  ecx, 3            ; B9 03 00 00 00
loop:
add  [0x20000], rcx    ; 48 01 0C 25 00 00 02 00
dec  rcx               ; 48 FF C9
jnz  loop              ; 75 F3
hlt                    ; F4

§The program

Create a new binary crate and replace src/main.rs with Listing 2-1.

Listing 2-1: Tracing a three-iteration loop

use kvm_ioctls::VcpuExit;
use kvmtrace::kvm::KvmTracer;
use kvmtrace::minivm::MiniVm;
use kvmtrace::{Session, TraceOptions};

fn main() -> kvmtrace::Result<()> {
    // 1. A VM with 8 MiB of RAM and one vCPU, and our program in it.
    let mut vm = MiniVm::new(8, 1)?;
    let code = [
        0xB9, 0x03, 0x00, 0x00, 0x00,                   // mov ecx, 3
        0x48, 0x01, 0x0C, 0x25, 0x00, 0x00, 0x02, 0x00, // add [0x20000], rcx
        0x48, 0xFF, 0xC9,                               // dec rcx
        0x75, 0xF3,                                     // jnz -13
        0xF4,                                           // hlt
    ];
    vm.load(MiniVm::CODE, &code);

    // 2. A tracing session that writes its files to ./trace-out.
    let session = Session::new(TraceOptions::default(), vm.memory(), Some("trace-out".as_ref()))?;
    let mut tracer = KvmTracer::new(&session, 0)?;

    // 3. The run loop: every single-step comes back as a Debug exit.
    let vcpu = &mut vm.vcpus[0];
    tracer.enable(vcpu)?;
    loop {
        match vcpu.run().map_err(kvmtrace::Error::kvm("KVM_RUN"))? {
            VcpuExit::Debug(d) => {
                tracer.on_debug_exit(vcpu, &d, false)?;
            }
            VcpuExit::Hlt => {
                // The HLT has retired, but no further step will report it.
                tracer.flush(vcpu)?;
                break;
            }
            other => panic!("unexpected exit: {other:?}"),
        }
    }

    // 4. Flush the files and print the counters.
    tracer.finish()?;
    let stats = session.finish()?;
    println!("{} instructions, {} gaps", stats.instructions, stats.gaps);
    Ok(())
}

Let’s walk through it.

Step 1 builds the machine. MiniVm::load copies our bytes into guest RAM at MiniVm::CODE, which is where the vCPU’s RIP points after reset.

Step 2 creates a Session. A session owns everything shared by the vCPUs of one trace: the options, a handle to guest memory (the tracer reads the guest’s page tables and instruction bytes through it), the global sequence counter, and the output directory. Then we ask the session for a KvmTracer for vCPU 0.

Step 3 is the part that will look familiar if you have written a KVM program before: a loop around vcpu.run(). After enable, KVM stops the vCPU after every instruction and reports a VcpuExit::Debug. We hand each one to on_debug_exit, which records the instruction that just ran and sets up the next step. Every other exit is none of the tracer’s business: your VMM handles I/O, MMIO and so on exactly as before.

Step 4 flushes the trace files and returns the session’s Stats.

§Running it

$ cargo run --release
11 instructions, 0 gaps
$ ls trace-out
summary.txt  trace_0.raw  trace.txt  vcpu0.kvt

Eleven instructions: the mov, three trips around the loop (add, dec, jnz), and the hlt. Notice the tracer.flush(vcpu) before break. A step is written when the next stop arrives, because only then do we know how it ended (did it fault? was an interrupt taken?). After the final HLT there is no next stop, so we tell the tracer to finish the last instruction from the vCPU’s current state.

The other number, gaps, is the one to watch: it counts places where the CPU went somewhere the tracer could not explain, so instructions may have run untraced. Zero is the only acceptable value, and chapter 5 explains how the tracer keeps it there.

§A tracer is a good debugger

The first draft of Listing 2-1 had the jump written as 75 F4, which is one byte off: it lands in the middle of the add, and the CPU decodes 01 0C 25 …, a 32-bit add [0x20000], ecx. The trace showed exactly that, add [20000h],ecx with a 4-byte access, on the second and third iterations. Single-stepping records what the CPU did, not what you meant.

The four files are:

FileContents
trace.txtMacSim’s index file: format version, thread count, thread ids
trace_0.rawMacSim records for vCPU 0 (gzip)
vcpu0.kvtthe extended trace: everything, including physical addresses and events (zstd)
summary.txtoptions and counters, for humans