Expand description
§How Single-Stepping Works
So far we have used the tracer as a black box. In this chapter we open it. The idea fits in one sentence (stop the CPU after every instruction and look at it), but the details decide whether the trace is exhaustive or just mostly right. We’ll build up the method the way it was built: start with the obvious approach, watch it fail, and fix it.
§The problem
A cache or core simulator needs to see every instruction the guest executes and every byte it touches, in order. Under KVM the guest runs on the real CPU at full speed, and the hypervisor normally sees nothing but the occasional exit for I/O. We need a way to make the CPU stop after each instruction and hand control to us.
§The idea: the trap flag
x86 has had a mechanism for this since the 8086: the trap flag (TF,
bit 8 of RFLAGS). When TF is set, the CPU raises a debug exception (#DB)
after each instruction. KVM exposes it through the KVM_SET_GUEST_DEBUG
ioctl:
let dbg = kvm_guest_debug {
control: KVM_GUESTDBG_ENABLE | KVM_GUESTDBG_SINGLESTEP,
..Default::default()
};
vcpu.set_guest_debug(&dbg).unwrap();
// From now on, every KVM_RUN returns VcpuExit::Debug after one instruction.KVM sets TF in the guest’s RFLAGS behind the guest’s back, intercepts
the resulting #DB, and turns it into a KVM_EXIT_DEBUG for us. It also
hides TF from the guest: pushf shows the guest’s own value, and the
CpuState::rflags we read is the guest’s view.
At each stop the tracer has the complete CPU state after the instruction. It already had the state before it (from the previous stop), so it can:
- decode the instruction from guest memory, at the old RIP
(
decode::fetch), translating the address through the guest’s own page tables (paging::translate); - plan its memory accesses from the operands and the before register
values (
decode::plan_accesses): base + index × scale + displacement + segment base, one entry per gather lane, the stack slots ofpush/call, the string pointers ofmovs, and so on; - check that the new RIP is one the instruction could have produced
(
decode::predict_successors): the next instruction, a branch target, a return address read from the stack, the same RIP for aREPiteration.
That last step is what makes the tracer honest. If the CPU ends up
anywhere else, something ran that we did not see, and the record is
flagged GAP_AFTER and counted in
Stats::gaps.
§Where the obvious approach fails
Here is the result of an experiment you can run yourself
(cargo run --example tf_probe). A tiny guest executes a syscall, and
we inject a hardware interrupt at a known point. Each line is one debug
exit:
8 DEBUG exc=1 pc=0x10039 <- the syscall instruction
9 DEBUG exc=1 pc=0x1003b <- ...and we are already back from it
...
11 DEBUG exc=1 pc=0x1003d
(injected IRQ 0x20 before running from 0x1003d)
12 DEBUG exc=1 pc=0x1003e <- the handler ran, unseen
...
19 HLTThe system-call handler (four instructions) and the interrupt handler
(three) ran without a single stop. The reason is architectural, not
a KVM bug: delivering an interrupt or exception clears TF (the CPU saves
RFLAGS in the interrupt frame and starts the handler with TF = 0), and
SYSCALL clears it through the IA32_FMASK MSR. When the handler returns
with iret or sysret, the saved RFLAGS (TF and all) comes back, and
stepping resumes as if nothing had happened.
On a real operating system this is not a corner case. Page faults, timer interrupts and system calls are a large share of what a kernel does. A tracer built on TF alone silently loses all of them, and its successor check cannot even notice, because the handler returns exactly where the check expects the next instruction. Chapter 5 is about the fix; here is its effect on the same experiment:
21 DEBUG exc=3 pc=0x10080 <syscall entry>
22 DEBUG exc=1 pc=0x10081
23 DEBUG exc=1 pc=0x1008b
24 DEBUG exc=1 pc=0x1008d
25 DEBUG exc=1 pc=0x1008e
26 DEBUG exc=1 pc=0x1003b
...
(injected IRQ 0x20 before running from 0x1003d)
29 DEBUG exc=3 pc=0x10073 <IRQ handler entry>
30 DEBUG exc=1 pc=0x10074
31 DEBUG exc=1 pc=0x1007e
32 DEBUG exc=1 pc=0x1003d
...
40 HLT40 stops instead of 19: every handler instruction is there.
§Three more things the CPU does behind your back
REP string instructions are interruptible between iterations, and
TF traps after each iteration. rep stosq with RCX = 3 produces three
stops at the same RIP. The tracer writes one record per iteration
(InstructionOutcome::RepIteration
for all but the last), each with that iteration’s addresses, which is what
Pin-based tracers do too.
MOV SS and POP SS block interrupts and debug traps until the
following instruction completes, so that mov ss, ax; mov rsp, rbx
switches stacks atomically. One step therefore executes two instructions.
The tracer notices (RIP is past the second one), reconstructs the
in-between state exactly (it differs from the state before only in SS,
and in RSP for pop ss), and records both; the second carries
RecordFlags::SHADOWED. The Linux kernel
does this in its NMI and IRET paths; it was the source of every gap we
saw on a Linux guest before this was handled.
Instructions that reload RFLAGS (popf, iret, sysret, …) can clear
TF themselves. After each one the tracer re-arms single-stepping with
KVM_SET_GUEST_DEBUG (decode::may_clear_tf).
§What “before” and “after” buy us
Because the tracer sees the state on both sides of each instruction, it can say more than “this instruction accessed these addresses”:
- Faults. If the instruction faulted, the CPU is now at a handler with
an interrupt frame on the stack whose return RIP is the faulting
instruction itself. The record says
Faulted { vector }, marks the access that matches CR2 asFaultedand the ones after it asAborted, and the instruction appears again when the handler restarts it. - Branches. Taken or not is simply “is the new RIP the fall-through?”.
- Physical addresses. The page walk uses the before CR3, so a
mov cr3is attributed correctly.
§Speed
One instruction costs one exit to the host kernel, a return to user space, and a few microseconds of decoding and bookkeeping. On the laptop used for this book that is about 90 000 instructions per second per vCPU, roughly three to four orders of magnitude slower than native. That is the price of exhaustiveness on hardware without a trace unit; chapter 10 compares it with the alternatives.