kvmtrace/record.rs
1//! The trace records: what one executed instruction (or one interrupt)
2//! looks like after the tracer has finished with it.
3//!
4//! These types are the tracer's *intermediate representation*. They hold
5//! more than MacSim can use (guest-physical addresses, CR3, privilege
6//! level, faults, interrupts), and are written in full to the extended
7//! `.kvt` trace. The [`macsim`](crate::macsim) module turns them into the
8//! narrower MacSim format.
9
10use crate::state::CpuMode;
11
12/// A tiny stand-in for the `bitflags` crate, so the public API has no
13/// third-party types in it.
14macro_rules! bitflags_lite {
15 ($(#[$m:meta])* pub struct $name:ident: $t:ty { $($(#[$fm:meta])* const $f:ident = $v:expr;)* }) => {
16 $(#[$m])*
17 #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
18 pub struct $name(pub $t);
19 impl $name {
20 $($(#[$fm])* pub const $f: $name = $name($v);)*
21 /// No flags.
22 pub const fn empty() -> Self { $name(0) }
23 /// Are all bits of `other` set?
24 pub const fn contains(self, other: Self) -> bool { self.0 & other.0 == other.0 }
25 /// Sets the bits of `other`.
26 pub fn insert(&mut self, other: Self) { self.0 |= other.0 }
27 /// The raw bits.
28 pub const fn bits(self) -> $t { self.0 }
29 }
30 impl std::ops::BitOr for $name {
31 type Output = Self;
32 fn bitor(self, o: Self) -> Self { $name(self.0 | o.0) }
33 }
34 };
35}
36
37
38/// Where a record sits in the trace orderings.
39#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
40pub struct Sequence {
41 /// Position in this vCPU's own stream, starting at 0. Always exact.
42 pub local: u64,
43 /// Position in the global stream across all vCPUs.
44 ///
45 /// In [`Ordering::Serialized`](crate::Ordering::Serialized) mode only
46 /// one vCPU executes at a time, so this is the exact execution order.
47 /// In [`Ordering::Concurrent`](crate::Ordering::Concurrent) mode it is
48 /// the order in which the tracer *observed* the steps, which is
49 /// close to, but not guaranteed to be, the execution order.
50 pub global: u64,
51 /// Host time stamp counter when the step was observed.
52 pub host_tsc: u64,
53}
54
55/// The kind of a memory access.
56#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
57pub enum AccessKind {
58 /// Data read.
59 Read,
60 /// Data write.
61 Write,
62 /// A read and a write of the same location by one instruction
63 /// (`add [rax], 1`, `xchg`, `lock cmpxchg`).
64 ReadWrite,
65 /// Instruction fetch.
66 Fetch,
67}
68
69/// Why the access happened.
70#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
71pub enum AccessClass {
72 /// An explicit memory operand of the instruction.
73 Operand,
74 /// An implicit access by the instruction: the stack in `push`/`call`,
75 /// string-instruction operands, and so on.
76 Implicit,
77 /// A software prefetch hint.
78 Prefetch,
79 /// Fetching the instruction's own bytes.
80 InstructionFetch,
81 /// The CPU reading an IDT gate while delivering an event.
82 EventDescriptor,
83 /// The CPU pushing an interrupt frame while delivering an event.
84 EventFrame,
85}
86
87/// Whether the access happened.
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
89pub enum AccessOutcome {
90 /// The access was performed.
91 Performed,
92 /// The access was attempted and caused the fault that stopped the
93 /// instruction (for a page fault: CR2 is inside this access).
94 Faulted,
95 /// The instruction faulted, so this access was attempted but not
96 /// committed (x86 does not define which of an instruction's accesses
97 /// happen before a fault, so every one is reported).
98 Aborted,
99 /// A conditional access (masked vector element, `cmov` whose
100 /// condition was false, …) that the hardware skipped.
101 Suppressed,
102}
103
104/// One memory access by one instruction or event.
105#[derive(Debug, Clone, Copy, PartialEq, Eq)]
106pub struct MemoryAccess {
107 /// Linear (virtual) address: segment base + effective address.
108 pub linear: u64,
109 /// Guest-physical address of the first byte, if the page is mapped.
110 /// For an access that crosses a page boundary this is the first
111 /// page's address; [`MemoryAccess::physical_end`] gives the second.
112 pub physical: Option<u64>,
113 /// Guest-physical address of the last byte, when it lies on a
114 /// different page than the first.
115 pub physical_end: Option<u64>,
116 /// Size in bytes.
117 pub size: u32,
118 /// Read, write, both, or fetch.
119 pub kind: AccessKind,
120 /// Why the access happened.
121 pub class: AccessClass,
122 /// Did it happen?
123 pub outcome: AccessOutcome,
124 /// The access is conditional on a mask or a condition code.
125 pub conditional: bool,
126}
127
128/// What happened to the instruction.
129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
130pub enum InstructionOutcome {
131 /// The instruction completed (retired).
132 Retired,
133 /// One iteration of a `REP`-prefixed string instruction completed.
134 /// The instruction will appear again for the next iteration, exactly
135 /// as Pin reports it.
136 RepIteration,
137 /// The instruction raised exception `vector` and did not complete.
138 Faulted {
139 /// The exception vector (13 = #GP, 14 = #PF, …).
140 vector: u8,
141 },
142}
143
144bitflags_lite! {
145 /// Extra facts about a record.
146 pub struct RecordFlags: u16 {
147 /// The successor RIP could not be checked against a prediction
148 /// (the instruction's target depends on state we did not read).
149 const SUCCESSOR_UNCHECKED = 1 << 0;
150 /// The successor RIP did *not* match the prediction and no event
151 /// explains it: some instructions may have run untraced.
152 const GAP_AFTER = 1 << 1;
153 /// The step ran without holding the global token (the vCPU was
154 /// halted and woke up), so its global order is approximate even in
155 /// serialized mode.
156 const UNSERIALIZED = 1 << 2;
157 /// This was the first instruction after an entry breakpoint
158 /// (a handler, or a SYSCALL/SYSENTER entry point).
159 const AT_ENTRY_POINT = 1 << 3;
160 /// More memory accesses than MacSim can represent (2 loads + 1
161 /// store); the MacSim record holds only the first ones.
162 const MACSIM_TRUNCATED = 1 << 4;
163 /// This instruction followed a MOV SS / POP SS, which suppresses
164 /// the single-step trap for one instruction. It was decoded and
165 /// its accesses planned from the exactly known state between the
166 /// two, rather than observed by a trap of its own.
167 const SHADOWED = 1 << 5;
168 }
169}
170
171/// One executed (or attempted) instruction.
172#[derive(Debug, Clone, PartialEq, Eq)]
173pub struct InstructionRecord {
174 /// Ordering information.
175 pub seq: Sequence,
176 /// The vCPU that executed it.
177 pub vcpu: u32,
178 /// RIP (offset inside CS).
179 pub rip: u64,
180 /// Linear address of the first byte (CS.base + RIP).
181 pub linear_rip: u64,
182 /// Guest-physical address of the first byte.
183 pub physical_rip: Option<u64>,
184 /// The raw instruction bytes (only the first `len` are meaningful).
185 pub bytes: [u8; 15],
186 /// Instruction length in bytes.
187 pub len: u8,
188 /// CS selector.
189 pub cs: u16,
190 /// Current privilege level (0–3).
191 pub cpl: u8,
192 /// CPU mode.
193 pub mode: CpuMode,
194 /// CR3, including PCID bits.
195 pub cr3: u64,
196 /// RIP of the next instruction this vCPU executed (or of the handler
197 /// it was diverted to).
198 pub next_rip: u64,
199 /// For a control-flow instruction: was the branch taken?
200 pub branch_taken: bool,
201 /// What happened to the instruction.
202 pub outcome: InstructionOutcome,
203 /// Memory accesses, in a fixed order: instruction fetch(es) first,
204 /// then reads, then read-modify-writes, then writes. Within each group,
205 /// the order iced-x86 reports operands in.
206 pub accesses: Vec<MemoryAccess>,
207 /// Extra facts.
208 pub flags: RecordFlags,
209}
210
211impl InstructionRecord {
212 /// The instruction bytes as a slice.
213 pub fn bytes(&self) -> &[u8] {
214 &self.bytes[..self.len as usize]
215 }
216
217 /// Data accesses only (no instruction fetches).
218 pub fn data_accesses(&self) -> impl Iterator<Item = &MemoryAccess> {
219 self.accesses.iter().filter(|a| a.kind != AccessKind::Fetch)
220 }
221}
222
223/// How an event was delivered.
224#[derive(Debug, Clone, Copy, PartialEq, Eq)]
225pub enum EventKind {
226 /// A fault or abort raised by the instruction that was executing
227 /// (`#PF`, `#GP`, `#UD`, …). The instruction did not complete.
228 Exception,
229 /// A trap raised after an instruction completed (`int n`, `int3`, `into`,
230 /// a data breakpoint), or an exception the instruction raised on purpose.
231 Software,
232 /// An external interrupt or NMI, taken at an instruction boundary.
233 Interrupt,
234}
235
236/// A hardware event: the CPU stopped the normal instruction flow and
237/// entered a handler through the IDT.
238#[derive(Debug, Clone, PartialEq, Eq)]
239pub struct EventRecord {
240 /// Ordering information.
241 pub seq: Sequence,
242 /// The vCPU.
243 pub vcpu: u32,
244 /// IDT vector.
245 pub vector: u8,
246 /// How it was delivered.
247 pub kind: EventKind,
248 /// The instruction pointer saved in the interrupt frame (where `iret`
249 /// will return to).
250 pub return_rip: u64,
251 /// The handler's first instruction.
252 pub handler_rip: u64,
253 /// CR3 at delivery.
254 pub cr3: u64,
255 /// The CPU's own accesses: the IDT gate read and the frame push.
256 pub accesses: Vec<MemoryAccess>,
257}
258
259/// One item of a per-vCPU trace stream.
260#[derive(Debug, Clone, PartialEq, Eq)]
261pub enum TraceItem {
262 /// An instruction.
263 Instruction(InstructionRecord),
264 /// An event.
265 Event(EventRecord),
266}
267
268impl TraceItem {
269 /// The item's ordering information.
270 pub fn seq(&self) -> &Sequence {
271 match self {
272 TraceItem::Instruction(i) => &i.seq,
273 TraceItem::Event(e) => &e.seq,
274 }
275 }
276 /// The vCPU that produced it.
277 pub fn vcpu(&self) -> u32 {
278 match self {
279 TraceItem::Instruction(i) => i.vcpu,
280 TraceItem::Event(e) => e.vcpu,
281 }
282 }
283}
284