Skip to main content

kvmtrace/
side.rs

1//! The MacSim **sideband**: everything a MacSim `.raw` record has no room
2//! for, one entry per record, in the same order.
3//!
4//! MacSim's x86 record (80 bytes, [`crate::macsim`]) was designed for one
5//! user process traced by Pin. A full-system trace needs more per
6//! instruction, and changing the record would break MacSim's reader. So
7//! next to `trace_<vcpu>.raw` the tracer writes `trace_<vcpu>.side`:
8//!
9//! | Field | Why |
10//! |---|---|
11//! | `cs`, `cpl` | the privilege level: CS bits 1:0 (= CPL in a stable state) |
12//! | `cr3` | which page table (process) the instruction ran under |
13//! | `physical_pc`, and per access `physical` / `physical_end` | guest-physical addresses |
14//! | `bytes`, `len` | the exact instruction (opcode and operands), not just MacSim's opcode category |
15//! | `vcpu`, `global_seq`, `local_seq` | which core, and the per-core and global order |
16//! | every access, with `in_macsim` | the `.raw` record holds at most 2 loads + 1 store; this list holds all of them, marking the ones the record has |
17//!
18//! Entry *k* of `trace_<v>.side` describes record *k* of `trace_<v>.raw`
19//! (`raw_index` = *k*, checked by the readers). The layout is fixed and
20//! little-endian; `macsim/kvmtrace_side.h` gives the same structs in C for
21//! use inside MacSim, and a test checks the C offsets against this module.
22//!
23//! ```text
24//! file   = "KVTSIDE\0" u32:version(=1) u32:vcpu u32:entry_size(=72) u32:access_size(=32)  entry*
25//! entry  = raw_index:u64 global_seq:u64 local_seq:u64 cr3:u64 physical_pc:u64
26//!          cs:u16 flags:u16 cpl:u8 mode:u8 outcome:u8 vector:u8 len:u8 bytes:[u8;15]
27//!          vcpu:u32 n_access:u16 reserved:u16                                  (72 bytes)
28//!          access*n_access
29//! access = linear:u64 physical:u64 physical_end:u64 size:u32 kind:u8 class:u8 outcome:u8 flags:u8   (32 bytes)
30//! ```
31//!
32//! Unknown physical addresses are `u64::MAX`.
33
34use std::fs::File;
35use std::io::{BufReader, BufWriter, Read, Write};
36use std::path::{Path, PathBuf};
37
38use flate2::Compression;
39use flate2::read::MultiGzDecoder;
40use flate2::write::GzEncoder;
41
42use crate::error::{Error, Result};
43use crate::record::{AccessClass, AccessKind, AccessOutcome, InstructionOutcome, InstructionRecord};
44
45/// File magic.
46pub const MAGIC: &[u8; 8] = b"KVTSIDE\0";
47/// Format version.
48pub const VERSION: u32 = 1;
49/// Bytes in an entry header.
50pub const ENTRY_SIZE: usize = 72;
51/// Bytes per access.
52pub const ACCESS_SIZE: usize = 32;
53/// "Unknown" physical address.
54pub const NO_PHYS: u64 = u64::MAX;
55
56/// Access flag: the access depends on a condition or mask.
57pub const ACCESS_CONDITIONAL: u8 = 1;
58/// Access flag: the access is one of those in the `.raw` record
59/// (`ld_vaddr1`, `ld_vaddr2` or `st_vaddr`).
60pub const ACCESS_IN_MACSIM: u8 = 2;
61
62/// One access in a sideband entry.
63#[derive(Debug, Clone, Copy, PartialEq, Eq)]
64pub struct SideAccess {
65    /// Linear (virtual) address.
66    pub linear: u64,
67    /// Guest-physical address of the first byte, or [`NO_PHYS`].
68    pub physical: u64,
69    /// Guest-physical address of the last byte if the access crosses a
70    /// page, else [`NO_PHYS`].
71    pub physical_end: u64,
72    /// Size in bytes.
73    pub size: u32,
74    /// 0 read, 1 write, 2 read-modify-write, 3 instruction fetch.
75    pub kind: u8,
76    /// 0 operand, 1 implicit, 2 prefetch, 3 instruction fetch, 4 event descriptor, 5 event frame.
77    pub class: u8,
78    /// 0 performed, 1 faulted, 2 aborted, 3 suppressed.
79    pub outcome: u8,
80    /// [`ACCESS_CONDITIONAL`] | [`ACCESS_IN_MACSIM`].
81    pub flags: u8,
82}
83
84/// One sideband entry: the extra facts about one MacSim record.
85#[derive(Debug, Clone, PartialEq, Eq)]
86pub struct SideEntry {
87    /// Index of the matching record in the `.raw` file.
88    pub raw_index: u64,
89    /// Global sequence number ([`crate::Sequence::global`]).
90    pub global_seq: u64,
91    /// Per-vCPU sequence number ([`crate::Sequence::local`]).
92    pub local_seq: u64,
93    /// CR3 when the instruction ran.
94    pub cr3: u64,
95    /// Guest-physical address of the instruction, or [`NO_PHYS`].
96    pub physical_pc: u64,
97    /// CS selector. Bits 1:0 are the requested privilege level, which
98    /// equals the CPL whenever the CPU is not part-way through a
99    /// privilege change.
100    pub cs: u16,
101    /// [`crate::RecordFlags`] bits.
102    pub flags: u16,
103    /// Current privilege level (SS.DPL, as KVM reports it).
104    pub cpl: u8,
105    /// [`crate::CpuMode`] as a number ([`crate::CpuMode::as_u8`]).
106    pub mode: u8,
107    /// 0 retired, 1 REP iteration, 2 faulted.
108    pub outcome: u8,
109    /// Exception vector if `outcome` is 2.
110    pub vector: u8,
111    /// Instruction length.
112    pub len: u8,
113    /// Instruction bytes (first `len` are valid).
114    pub bytes: [u8; 15],
115    /// vCPU (core) number.
116    pub vcpu: u32,
117    /// Every memory access of the instruction, in order.
118    pub accesses: Vec<SideAccess>,
119}
120
121fn kind_code(k: AccessKind) -> u8 {
122    match k {
123        AccessKind::Read => 0,
124        AccessKind::Write => 1,
125        AccessKind::ReadWrite => 2,
126        AccessKind::Fetch => 3,
127    }
128}
129
130fn class_code(c: AccessClass) -> u8 {
131    match c {
132        AccessClass::Operand => 0,
133        AccessClass::Implicit => 1,
134        AccessClass::Prefetch => 2,
135        AccessClass::InstructionFetch => 3,
136        AccessClass::EventDescriptor => 4,
137        AccessClass::EventFrame => 5,
138    }
139}
140
141fn outcome_code(o: AccessOutcome) -> u8 {
142    match o {
143        AccessOutcome::Performed => 0,
144        AccessOutcome::Faulted => 1,
145        AccessOutcome::Aborted => 2,
146        AccessOutcome::Suppressed => 3,
147    }
148}
149
150impl SideEntry {
151    /// Builds the entry for `rec`, whose MacSim record is number
152    /// `raw_index`; `in_macsim` lists the indices into `rec.accesses` that
153    /// the MacSim record holds ([`crate::macsim::selected_accesses`]).
154    pub fn from_record(rec: &InstructionRecord, raw_index: u64, in_macsim: &[usize]) -> SideEntry {
155        let (outcome, vector) = match rec.outcome {
156            InstructionOutcome::Retired => (0, 0),
157            InstructionOutcome::RepIteration => (1, 0),
158            InstructionOutcome::Faulted { vector } => (2, vector),
159        };
160        SideEntry {
161            raw_index,
162            global_seq: rec.seq.global,
163            local_seq: rec.seq.local,
164            cr3: rec.cr3,
165            physical_pc: rec.physical_rip.unwrap_or(NO_PHYS),
166            cs: rec.cs,
167            flags: rec.flags.bits(),
168            cpl: rec.cpl,
169            mode: rec.mode.as_u8(),
170            outcome,
171            vector,
172            len: rec.len,
173            bytes: rec.bytes,
174            vcpu: rec.vcpu,
175            accesses: rec
176                .accesses
177                .iter()
178                .enumerate()
179                .map(|(k, a)| SideAccess {
180                    linear: a.linear,
181                    physical: a.physical.unwrap_or(NO_PHYS),
182                    physical_end: a.physical_end.unwrap_or(NO_PHYS),
183                    size: a.size,
184                    kind: kind_code(a.kind),
185                    class: class_code(a.class),
186                    outcome: outcome_code(a.outcome),
187                    flags: (if a.conditional { ACCESS_CONDITIONAL } else { 0 })
188                        | (if in_macsim.contains(&k) { ACCESS_IN_MACSIM } else { 0 }),
189                })
190                .collect(),
191        }
192    }
193
194    /// The privilege level encoded in the CS selector (bits 1:0).
195    pub fn cs_rpl(&self) -> u8 {
196        (self.cs & 3) as u8
197    }
198
199    fn header_bytes(&self) -> [u8; ENTRY_SIZE] {
200        let mut b = [0u8; ENTRY_SIZE];
201        b[0..8].copy_from_slice(&self.raw_index.to_le_bytes());
202        b[8..16].copy_from_slice(&self.global_seq.to_le_bytes());
203        b[16..24].copy_from_slice(&self.local_seq.to_le_bytes());
204        b[24..32].copy_from_slice(&self.cr3.to_le_bytes());
205        b[32..40].copy_from_slice(&self.physical_pc.to_le_bytes());
206        b[40..42].copy_from_slice(&self.cs.to_le_bytes());
207        b[42..44].copy_from_slice(&self.flags.to_le_bytes());
208        b[44] = self.cpl;
209        b[45] = self.mode;
210        b[46] = self.outcome;
211        b[47] = self.vector;
212        b[48] = self.len;
213        b[49..64].copy_from_slice(&self.bytes);
214        b[64..68].copy_from_slice(&self.vcpu.to_le_bytes());
215        b[68..70].copy_from_slice(&(self.accesses.len().min(u16::MAX as usize) as u16).to_le_bytes());
216        b
217    }
218}
219
220impl SideAccess {
221    fn to_bytes(self) -> [u8; ACCESS_SIZE] {
222        let mut b = [0u8; ACCESS_SIZE];
223        b[0..8].copy_from_slice(&self.linear.to_le_bytes());
224        b[8..16].copy_from_slice(&self.physical.to_le_bytes());
225        b[16..24].copy_from_slice(&self.physical_end.to_le_bytes());
226        b[24..28].copy_from_slice(&self.size.to_le_bytes());
227        b[28] = self.kind;
228        b[29] = self.class;
229        b[30] = self.outcome;
230        b[31] = self.flags;
231        b
232    }
233
234    fn from_bytes(b: &[u8; ACCESS_SIZE]) -> SideAccess {
235        let u64_at = |o: usize| u64::from_le_bytes(b[o..o + 8].try_into().unwrap());
236        SideAccess {
237            linear: u64_at(0),
238            physical: u64_at(8),
239            physical_end: u64_at(16),
240            size: u32::from_le_bytes(b[24..28].try_into().unwrap()),
241            kind: b[28],
242            class: b[29],
243            outcome: b[30],
244            flags: b[31],
245        }
246    }
247}
248
249/// Path of vCPU `tid`'s sideband file for trace base name `base`.
250pub fn side_path(base: &Path, tid: u32) -> PathBuf {
251    let mut s = base.as_os_str().to_owned();
252    s.push(format!("_{tid}.side"));
253    PathBuf::from(s)
254}
255
256/// Writes one vCPU's sideband.
257pub struct SideWriter {
258    out: GzEncoder<BufWriter<File>>,
259}
260
261impl SideWriter {
262    /// Creates `<base>_<tid>.side`.
263    pub fn create(base: &Path, tid: u32, level: u32) -> Result<SideWriter> {
264        let f = File::create(side_path(base, tid))?;
265        let mut out = GzEncoder::new(BufWriter::with_capacity(1 << 20, f), Compression::new(level));
266        out.write_all(MAGIC)?;
267        for v in [VERSION, tid, ENTRY_SIZE as u32, ACCESS_SIZE as u32] {
268            out.write_all(&v.to_le_bytes())?;
269        }
270        Ok(SideWriter { out })
271    }
272
273    /// Appends one entry.
274    pub fn write(&mut self, e: &SideEntry) -> Result<()> {
275        self.out.write_all(&e.header_bytes())?;
276        for a in e.accesses.iter().take(u16::MAX as usize) {
277            self.out.write_all(&a.to_bytes())?;
278        }
279        Ok(())
280    }
281
282    /// Finishes the gzip stream.
283    pub fn finish(self) -> Result<()> {
284        self.out.finish()?.flush()?;
285        Ok(())
286    }
287}
288
289/// Reads a sideband file.
290pub struct SideReader {
291    inp: MultiGzDecoder<BufReader<File>>,
292    vcpu: u32,
293}
294
295impl SideReader {
296    /// Opens a `.side` file and checks its header.
297    pub fn open(path: &Path) -> Result<SideReader> {
298        let mut inp = MultiGzDecoder::new(BufReader::new(File::open(path)?));
299        let mut h = [0u8; 24];
300        inp.read_exact(&mut h)?;
301        let word = |k: usize| u32::from_le_bytes(h[8 + 4 * k..12 + 4 * k].try_into().unwrap());
302        if &h[..8] != MAGIC || word(0) != VERSION || word(2) as usize != ENTRY_SIZE || word(3) as usize != ACCESS_SIZE {
303            return Err(Error::Format(format!("{}: not a version-{VERSION} sideband file", path.display())));
304        }
305        Ok(SideReader { inp, vcpu: word(1) })
306    }
307
308    /// The vCPU this file belongs to.
309    pub fn vcpu(&self) -> u32 {
310        self.vcpu
311    }
312}
313
314impl Iterator for SideReader {
315    type Item = Result<SideEntry>;
316    fn next(&mut self) -> Option<Result<SideEntry>> {
317        let mut b = [0u8; ENTRY_SIZE];
318        match self.inp.read_exact(&mut b) {
319            Ok(()) => {}
320            Err(e) if e.kind() == std::io::ErrorKind::UnexpectedEof => return None,
321            Err(e) => return Some(Err(e.into())),
322        }
323        let u64_at = |o: usize| u64::from_le_bytes(b[o..o + 8].try_into().unwrap());
324        let n = u16::from_le_bytes([b[68], b[69]]) as usize;
325        let mut accesses = Vec::with_capacity(n);
326        for _ in 0..n {
327            let mut a = [0u8; ACCESS_SIZE];
328            if let Err(e) = self.inp.read_exact(&mut a) {
329                return Some(Err(e.into()));
330            }
331            accesses.push(SideAccess::from_bytes(&a));
332        }
333        Some(Ok(SideEntry {
334            raw_index: u64_at(0),
335            global_seq: u64_at(8),
336            local_seq: u64_at(16),
337            cr3: u64_at(24),
338            physical_pc: u64_at(32),
339            cs: u16::from_le_bytes([b[40], b[41]]),
340            flags: u16::from_le_bytes([b[42], b[43]]),
341            cpl: b[44],
342            mode: b[45],
343            outcome: b[46],
344            vector: b[47],
345            len: b[48],
346            bytes: b[49..64].try_into().unwrap(),
347            vcpu: u32::from_le_bytes(b[64..68].try_into().unwrap()),
348            accesses,
349        }))
350    }
351}