Skip to main content

kvmtrace/macsim/
mod.rs

1//! Writing (and reading) traces in MacSim's x86 format.
2//!
3//! [MacSim](https://github.com/gthparch/macsim) reads x86 traces produced
4//! by its Pin tool (`tools/x86_trace_generator`). A trace is a directory
5//! entry made of
6//!
7//! * a text file `NAME.txt`:
8//!   ```text
9//!   x86 1.3
10//!   <thread count>
11//!   <thread id> <start instruction count>
12//!   ...
13//!   ```
14//! * one gzip-compressed file `NAME_<tid>.raw` per thread, holding a flat
15//!   array of 80-byte records: MacSim's `trace_info_cpu_s` without its last
16//!   field (`m_instruction_next_addr`, which the reader fills in itself).
17//!
18//! This module produces exactly that, one MacSim *thread* per guest vCPU,
19//! so a trace from this crate drops into MacSim where a Pin trace would.
20//! [`MacsimRecord`] mirrors the C struct field by field; the layout is
21//! checked against MacSim's own header by a test.
22//!
23//! # How an instruction becomes a record
24//!
25//! The static fields (opcode category, registers, branch type) are filled
26//! in exactly the way the Pin tool fills them, using the same rules:
27//!
28//! * `m_opcode` is the instruction's XED category (MacSim's
29//!   `CPU_OPCODE_ENUM`), except that names containing `NOP`, `MUL`, `DIV`
30//!   and the four `PREFETCH` hints get MacSim's special values, just as the
31//!   Pin tool does. Categories come from a table generated from Intel XED's
32//!   own ISA files (see `tools/gen_xed_categories.py`).
33//! * Registers use Pin 3.13's `REG` numbering of the *full* register
34//!   (`eax` → `rax` = 10), sorted and de-duplicated, as Pin's `std::set`
35//!   does. All widths of vector register *n* map to `zmm`*n*, so a write to
36//!   `ymm3` and a read of `xmm3` are seen as dependent.
37//! * At most two loads and one store fit in a record. Instructions with
38//!   more (gathers, some string and stack instructions) keep the first ones,
39//!   like the Pin tool, and are flagged in the extended trace.
40
41mod xed_categories;
42
43use std::fs::File;
44use std::io::{BufWriter, Read, Write};
45use std::path::{Path, PathBuf};
46
47use flate2::Compression;
48use flate2::read::MultiGzDecoder;
49use flate2::write::GzEncoder;
50use iced_x86::{EncodingKind, FlowControl, InstructionInfoFactory, Mnemonic, OpAccess, OpKind, Register};
51
52use crate::decode::Decoded;
53use crate::error::{Error, Result};
54use crate::record::{AccessKind, AccessOutcome, InstructionRecord};
55use crate::state::RFLAGS_DF;
56
57/// Size of one record in a `.raw` file (MacSim's `CPU_TRACE_SIZE`).
58pub const RECORD_SIZE: usize = 80;
59/// Most source registers a record holds (`MAX_SRC_NUM`).
60pub const MAX_SRC: usize = 9;
61/// Most destination registers a record holds (`MAX_DST_NUM`).
62pub const MAX_DST: usize = 6;
63/// The trace-generator version MacSim's reader expects (`t_gen_ver`).
64pub const GENERATOR_VERSION: &str = "1.3";
65
66/// MacSim's control-flow types (`CF_TYPE` in `trace_read.h`).
67#[allow(missing_docs)]
68#[derive(Debug, Clone, Copy, PartialEq, Eq)]
69#[repr(u8)]
70pub enum CfType {
71    NotCf = 0,
72    Br = 1,
73    Cbr = 2,
74    Call = 3,
75    Ibr = 4,
76    ICall = 5,
77    Ico = 6,
78    Ret = 7,
79    Sys = 8,
80    Icbr = 9,
81}
82
83/// One MacSim x86 trace record (`trace_info_cpu_s` minus the last field).
84#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
85pub struct MacsimRecord {
86    /// Number of source registers.
87    pub num_read_regs: u8,
88    /// Number of destination registers.
89    pub num_dest_regs: u8,
90    /// Source register ids (Pin 3.13 `REG`).
91    pub src: [u8; MAX_SRC],
92    /// Destination register ids.
93    pub dst: [u8; MAX_DST],
94    /// Control-flow type ([`CfType`]).
95    pub cf_type: u8,
96    /// Has an immediate (never set by the Pin tool; kept 0).
97    pub has_immediate: bool,
98    /// Opcode: a `CPU_OPCODE_ENUM` value.
99    pub opcode: u8,
100    /// Has a store.
101    pub has_st: bool,
102    /// Uses floating-point registers.
103    pub is_fp: bool,
104    /// Writes RFLAGS.
105    pub write_flg: bool,
106    /// Number of loads (0, 1 or 2).
107    pub num_ld: u8,
108    /// Instruction size in bytes.
109    pub size: u8,
110    /// First load address.
111    pub ld_vaddr1: u64,
112    /// Second load address.
113    pub ld_vaddr2: u64,
114    /// Store address.
115    pub st_vaddr: u64,
116    /// Instruction address (PC).
117    pub instruction_addr: u64,
118    /// Branch target.
119    pub branch_target: u64,
120    /// Load size in bytes.
121    pub mem_read_size: u8,
122    /// Store size in bytes.
123    pub mem_write_size: u8,
124    /// Direction flag (for string instructions).
125    pub rep_dir: bool,
126    /// Branch taken.
127    pub actually_taken: bool,
128}
129
130impl MacsimRecord {
131    /// Serializes to the 80-byte on-disk layout (x86-64 C ABI, with padding zeroed).
132    pub fn to_bytes(&self) -> [u8; RECORD_SIZE] {
133        let mut b = [0u8; RECORD_SIZE];
134        b[0] = self.num_read_regs;
135        b[1] = self.num_dest_regs;
136        b[2..11].copy_from_slice(&self.src);
137        b[11..17].copy_from_slice(&self.dst);
138        b[17] = self.cf_type;
139        b[18] = self.has_immediate as u8;
140        b[19] = self.opcode;
141        b[20] = self.has_st as u8;
142        b[21] = self.is_fp as u8;
143        b[22] = self.write_flg as u8;
144        b[23] = self.num_ld;
145        b[24] = self.size;
146        // 25..32: padding before the first u64
147        b[32..40].copy_from_slice(&self.ld_vaddr1.to_le_bytes());
148        b[40..48].copy_from_slice(&self.ld_vaddr2.to_le_bytes());
149        b[48..56].copy_from_slice(&self.st_vaddr.to_le_bytes());
150        b[56..64].copy_from_slice(&self.instruction_addr.to_le_bytes());
151        b[64..72].copy_from_slice(&self.branch_target.to_le_bytes());
152        b[72] = self.mem_read_size;
153        b[73] = self.mem_write_size;
154        b[74] = self.rep_dir as u8;
155        b[75] = self.actually_taken as u8;
156        b
157    }
158
159    /// Parses the 80-byte on-disk layout.
160    pub fn from_bytes(b: &[u8; RECORD_SIZE]) -> MacsimRecord {
161        let u = |o: usize| u64::from_le_bytes(b[o..o + 8].try_into().unwrap());
162        MacsimRecord {
163            num_read_regs: b[0],
164            num_dest_regs: b[1],
165            src: b[2..11].try_into().unwrap(),
166            dst: b[11..17].try_into().unwrap(),
167            cf_type: b[17],
168            has_immediate: b[18] != 0,
169            opcode: b[19],
170            has_st: b[20] != 0,
171            is_fp: b[21] != 0,
172            write_flg: b[22] != 0,
173            num_ld: b[23],
174            size: b[24],
175            ld_vaddr1: u(32),
176            ld_vaddr2: u(40),
177            st_vaddr: u(48),
178            instruction_addr: u(56),
179            branch_target: u(64),
180            mem_read_size: b[72],
181            mem_write_size: b[73],
182            rep_dir: b[74] != 0,
183            actually_taken: b[75] != 0,
184        }
185    }
186
187    /// Name of the opcode, as MacSim prints it.
188    pub fn opcode_name(&self) -> &'static str {
189        OPCODE_NAMES.get(self.opcode as usize).copied().unwrap_or("?")
190    }
191}
192
193/// MacSim's `CPU_OPCODE_ENUM`, in order (from `src/trace_read.h`).
194pub const OPCODE_NAMES: &[&str] = &[
195    "INVALID", "3DNOW", "ADOX_ADCX", "AES", "AVX", "AVX2", "AVX2GATHER", "AVX512", "AVX512_4FMAPS",
196    "AVX512_4VNNIW", "AVX512_BITALG", "AVX512_VBMI", "AVX512_VP2INTERSECT", "BINARY", "BITBYTE", "BLEND",
197    "BMI1", "BMI2", "BROADCAST", "CALL", "CET", "CLDEMOTE", "CLFLUSHOPT", "CLWB", "CLZERO", "CMOV",
198    "COMPRESS", "COND_BR", "CONFLICT", "CONVERT", "DATAXFER", "DECIMAL", "ENQCMD", "EXPAND", "FCMOV",
199    "FLAGOP", "FMA4", "GATHER", "GFNI", "IFMA", "INTERRUPT", "IO", "IOSTRINGOP", "KMASK", "LOGICAL",
200    "LOGICAL_FP", "LZCNT", "MISC", "MMX", "MOVDIR", "MPX", "NOP", "PCLMULQDQ", "PCONFIG", "PKU", "POP",
201    "PREFETCH", "PREFETCHWT1", "PT", "PUSH", "RDPID", "RDPRU", "RDRAND", "RDSEED", "RDWRFSGS", "RET",
202    "ROTATE", "SCATTER", "SEGOP", "SEMAPHORE", "SETCC", "SGX", "SHA", "SHIFT", "SMAP", "SSE", "STRINGOP",
203    "STTNI", "SYSCALL", "SYSRET", "SYSTEM", "TBM", "UNCOND_BR", "VAES", "VBMI2", "VFMA", "VIA_PADLOCK",
204    "VPCLMULQDQ", "VTX", "WAITPKG", "WIDENOP", "X87_ALU", "XOP", "XSAVE", "XSAVEOPT", "TR_MUL", "TR_DIV",
205    "TR_FMUL", "TR_FDIV", "TR_NOP", "PREFETCH_NTA", "PREFETCH_T0", "PREFETCH_T1", "PREFETCH_T2", "GPU_EN",
206];
207
208fn opcode_id(name: &str) -> Option<u8> {
209    OPCODE_NAMES.iter().position(|n| *n == name).map(|p| p as u8)
210}
211
212/// XED iclass name for an iced mnemonic (they agree except for condition
213/// codes and a few control-transfer names).
214fn xed_iclass(i: &iced_x86::Instruction) -> String {
215    let m = format!("{:?}", i.mnemonic()).to_ascii_uppercase();
216    let cc = |s: &str| -> String {
217        match s {
218            "E" => "Z",
219            "NE" => "NZ",
220            "AE" => "NB",
221            "A" => "NBE",
222            "GE" => "NL",
223            "G" => "NLE",
224            o => o,
225        }
226        .to_string()
227    };
228    for p in ["CMOV", "SET", "J"] {
229        if let Some(rest) = m.strip_prefix(p) {
230            let is_cc = matches!(
231                rest,
232                "O" | "NO" | "B" | "AE" | "E" | "NE" | "BE" | "A" | "S" | "NS" | "P" | "NP" | "L" | "GE" | "LE" | "G"
233            );
234            if is_cc {
235                return format!("{p}{}", cc(rest));
236            }
237        }
238    }
239    match i.mnemonic() {
240        Mnemonic::Ret => "RET_NEAR".into(),
241        Mnemonic::Retf => "RET_FAR".into(),
242        Mnemonic::Call if i.is_call_far() || i.is_call_far_indirect() => "CALL_FAR".into(),
243        Mnemonic::Call => "CALL_NEAR".into(),
244        Mnemonic::Jmp if i.is_jmp_far() || i.is_jmp_far_indirect() => "JMP_FAR".into(),
245        Mnemonic::Xlatb => "XLAT".into(),
246        Mnemonic::Movsd if i.is_string_instruction() => "MOVSD".into(),
247        Mnemonic::Movsd => "MOVSD_XMM".into(),
248        Mnemonic::Cmpsd if !i.is_string_instruction() => "CMPSD_XMM".into(),
249        _ => m,
250    }
251}
252
253fn uses_reg(i: &iced_x86::Instruction, pred: impl Fn(Register) -> bool) -> bool {
254    (0..i.op_count()).any(|n| i.op_kind(n) == OpKind::Register && pred(i.op_register(n)))
255}
256
257/// Picks the XED category among the candidates for this encoding.
258fn resolve_category(i: &iced_x86::Instruction, cands: &[&'static str]) -> &'static str {
259    if cands.len() == 1 {
260        return cands[0];
261    }
262    let has = |c: &str| cands.contains(&c);
263    if i.mnemonic() == Mnemonic::Nop && has("NOP") && has("WIDENOP") {
264        // 0x90 is NOP; the multi-byte 0F 1F/0F 0D forms are WIDENOP.
265        return if i.op_count() == 0 { "NOP" } else { "WIDENOP" };
266    }
267    match i.encoding() {
268        EncodingKind::EVEX | EncodingKind::MVEX => cands[0],
269        EncodingKind::VEX | EncodingKind::XOP => {
270            if has("AVX2GATHER") {
271                return "AVX2GATHER";
272            }
273            let ymm = uses_reg(i, |r| r.is_ymm());
274            if has("AES") && has("VAES") {
275                return if ymm { "VAES" } else { "AES" };
276            }
277            if has("AVX2") && ymm {
278                return "AVX2";
279            }
280            if has("AVX") {
281                return "AVX";
282            }
283            cands.iter().copied().find(|c| *c != "AVX512").unwrap_or(cands[0])
284        }
285        _ => {
286            if has("MMX") && has("SSE") {
287                return if uses_reg(i, |r| r.is_mm()) { "MMX" } else { "SSE" };
288            }
289            cands[0]
290        }
291    }
292}
293
294/// Heuristic category for instructions XED's table does not name.
295fn fallback_category(i: &iced_x86::Instruction) -> &'static str {
296    match i.flow_control() {
297        FlowControl::Call | FlowControl::IndirectCall => return "CALL",
298        FlowControl::Return => return "RET",
299        FlowControl::ConditionalBranch => return "COND_BR",
300        FlowControl::UnconditionalBranch | FlowControl::IndirectBranch => return "UNCOND_BR",
301        FlowControl::Interrupt => return "INTERRUPT",
302        _ => {}
303    }
304    match i.encoding() {
305        EncodingKind::EVEX | EncodingKind::MVEX => "AVX512",
306        EncodingKind::VEX => "AVX",
307        EncodingKind::XOP => "XOP",
308        EncodingKind::D3NOW => "3DNOW",
309        _ => "MISC",
310    }
311}
312
313/// How the opcode of an instruction was determined (for coverage statistics).
314#[derive(Debug, Clone, Copy, PartialEq, Eq)]
315pub enum CategorySource {
316    /// From the XED-generated table.
317    Xed,
318    /// From the fallback heuristic.
319    Heuristic,
320}
321
322/// The MacSim opcode for an instruction, following the Pin tool's rules.
323pub fn opcode_for(i: &iced_x86::Instruction) -> (u8, CategorySource) {
324    let name = format!("{:?}", i.mnemonic()).to_ascii_uppercase();
325    let tr = |n: &str| (opcode_id(n).unwrap(), CategorySource::Xed);
326    // The Pin tool's substring rules come first (trace_generator.cpp).
327    if name.contains("NOP") {
328        return tr("TR_NOP");
329    }
330    if name.contains("MUL") {
331        return tr(if matches!(i.mnemonic(), Mnemonic::Mul | Mnemonic::Imul) { "TR_MUL" } else { "TR_FMUL" });
332    }
333    if name.contains("DIV") {
334        return tr(if matches!(i.mnemonic(), Mnemonic::Div | Mnemonic::Idiv) { "TR_DIV" } else { "TR_FDIV" });
335    }
336    match i.mnemonic() {
337        Mnemonic::Prefetchnta => return tr("PREFETCH_NTA"),
338        Mnemonic::Prefetcht0 => return tr("PREFETCH_T0"),
339        Mnemonic::Prefetcht1 => return tr("PREFETCH_T1"),
340        Mnemonic::Prefetcht2 => return tr("PREFETCH_T2"),
341        _ => {}
342    }
343    let iclass = xed_iclass(i);
344    let table = xed_categories::XED_ICLASS_CATEGORY;
345    if let Ok(k) = table.binary_search_by(|(n, _)| (*n).cmp(iclass.as_str())) {
346        let cat = resolve_category(i, table[k].1);
347        if let Some(id) = opcode_id(cat) {
348            return (id, CategorySource::Xed);
349        }
350        // A category newer than MacSim's enum: nearest family.
351        let near = if cat.starts_with("AVX512") || cat.starts_with("AVX10") || cat == "APX" { "AVX512" } else { "MISC" };
352        return (opcode_id(near).unwrap(), CategorySource::Heuristic);
353    }
354    (opcode_id(fallback_category(i)).unwrap(), CategorySource::Heuristic)
355}
356
357/// Pin 3.13 `REG` id of the full register containing `r`, or `None` for
358/// registers Pin's MacSim tool never reports.
359pub fn pin_reg(r: Register) -> Option<u8> {
360    if r.is_gpr() {
361        // rdi rsi rbp rsp rbx rdx rcx rax r8..r15 = 3..18
362        let n = r.full_register().number();
363        const ORDER: [u8; 16] = [10, 9, 8, 7, 6, 5, 4, 3, 11, 12, 13, 14, 15, 16, 17, 18];
364        return Some(ORDER[n]);
365    }
366    Some(match r {
367        Register::CS => 19,
368        Register::SS => 20,
369        Register::DS => 21,
370        Register::ES => 22,
371        Register::FS => 23,
372        Register::GS => 24,
373        Register::RIP | Register::EIP => 26,
374        r if r.is_mm() => 83 + r.number() as u8,
375        r if r.is_xmm() || r.is_ymm() || r.is_zmm() => 155 + r.number() as u8,
376        r if r.is_k() => 187 + r.number() as u8,
377        r if r.is_st() => 207 + r.number() as u8,
378        r if r.is_cr() => 223 + r.number().min(4) as u8,
379        r if r.is_dr() => 215 + r.number().min(7) as u8,
380        _ => return None,
381    })
382}
383
384const PIN_RFLAGS: u8 = 25;
385
386/// The static half of a record, computed once per instruction.
387#[derive(Debug, Clone, Copy)]
388pub struct StaticInfo {
389    /// Registers, opcode, cf type, … (dynamic fields zero).
390    pub template: MacsimRecord,
391    /// Where the opcode came from.
392    pub category: CategorySource,
393}
394
395/// Computes the static fields of a MacSim record for an instruction.
396pub fn static_info(d: &Decoded, info: &mut InstructionInfoFactory) -> StaticInfo {
397    let i = &d.instr;
398    let mut t = MacsimRecord::default();
399    let ii = info.info(i);
400    let mut src: Vec<u8> = Vec::new();
401    let mut dst: Vec<u8> = Vec::new();
402    let mut fp = false;
403    for ur in ii.used_registers() {
404        let r = ur.register();
405        // Pin reports segment registers only as explicit FS/GS overrides in 64-bit code.
406        if r.is_segment_register() && !matches!(r, Register::FS | Register::GS) {
407            continue;
408        }
409        let Some(id) = pin_reg(r) else { continue };
410        if r.is_st() || r.is_xmm() || r.is_ymm() || r.is_zmm() {
411            fp = true;
412        }
413        match ur.access() {
414            OpAccess::Read | OpAccess::CondRead => src.push(id),
415            OpAccess::Write | OpAccess::CondWrite => dst.push(id),
416            OpAccess::ReadWrite | OpAccess::ReadCondWrite => {
417                src.push(id);
418                dst.push(id);
419            }
420            _ => {}
421        }
422    }
423    if i.rflags_read() != 0 {
424        src.push(PIN_RFLAGS);
425    }
426    if i.rflags_modified() != 0 {
427        dst.push(PIN_RFLAGS);
428        t.write_flg = true;
429    }
430    src.sort_unstable();
431    src.dedup();
432    dst.sort_unstable();
433    dst.dedup();
434    src.truncate(MAX_SRC - 1);
435    dst.truncate(MAX_DST - 1);
436    t.num_read_regs = src.len() as u8;
437    t.num_dest_regs = dst.len() as u8;
438    t.src[..src.len()].copy_from_slice(&src);
439    t.dst[..dst.len()].copy_from_slice(&dst);
440    t.is_fp = fp;
441    t.size = d.len;
442    let (op, cat) = opcode_for(i);
443    t.opcode = op;
444    t.cf_type = match i.flow_control() {
445        FlowControl::UnconditionalBranch => CfType::Br,
446        FlowControl::ConditionalBranch => CfType::Cbr,
447        FlowControl::Call => CfType::Call,
448        FlowControl::IndirectBranch => CfType::Ibr,
449        FlowControl::IndirectCall => CfType::ICall,
450        FlowControl::Return => CfType::Ret,
451        FlowControl::Interrupt => CfType::Ico,
452        _ => CfType::NotCf,
453    } as u8;
454    // Far direct jumps/calls are "direct" in Pin too.
455    if matches!(i.op0_kind(), OpKind::FarBranch16 | OpKind::FarBranch32) {
456        t.cf_type = if i.flow_control() == FlowControl::Call { CfType::Call } else { CfType::Br } as u8;
457    }
458    // num_ld / has_st are static in Pin (INS_IsMemoryRead / HasMemoryRead2 / IsMemoryWrite).
459    let mut reads = 0u8;
460    let mut writes = false;
461    for um in ii.used_memory() {
462        match um.access() {
463            OpAccess::Read | OpAccess::CondRead => reads += 1,
464            OpAccess::Write | OpAccess::CondWrite => writes = true,
465            OpAccess::ReadWrite | OpAccess::ReadCondWrite => {
466                reads += 1;
467                writes = true
468            }
469            OpAccess::NoMemAccess if matches!(i.mnemonic(), Mnemonic::Prefetchnta | Mnemonic::Prefetcht0 | Mnemonic::Prefetcht1 | Mnemonic::Prefetcht2 | Mnemonic::Prefetchw) => reads += 1,
470            _ => {}
471        }
472    }
473    t.num_ld = reads.min(2);
474    t.has_st = writes;
475    StaticInfo { template: t, category: cat }
476}
477
478/// Which of `rec.accesses` a MacSim record with this template holds: the
479/// first `num_ld` reads (`ld_vaddr1`, `ld_vaddr2`) and, if `has_st`, the
480/// first write (`st_vaddr`), in that order. Instruction fetches and
481/// suppressed accesses are never in a record. The second value is true if
482/// some data access did not fit.
483pub fn selected_accesses(t: &MacsimRecord, rec: &InstructionRecord) -> (Vec<usize>, Option<usize>, bool) {
484    let mut loads = Vec::with_capacity(2);
485    let mut store = None;
486    let mut extra = false;
487    for (k, a) in rec.accesses.iter().enumerate() {
488        if a.kind == AccessKind::Fetch || a.outcome == AccessOutcome::Suppressed {
489            continue;
490        }
491        if matches!(a.kind, AccessKind::Read | AccessKind::ReadWrite) {
492            if loads.len() < t.num_ld as usize {
493                loads.push(k);
494            } else {
495                extra = true;
496            }
497        }
498        if matches!(a.kind, AccessKind::Write | AccessKind::ReadWrite) {
499            if store.is_none() && t.has_st {
500                store = Some(k);
501            } else {
502                extra = true;
503            }
504        }
505    }
506    (loads, store, extra)
507}
508
509/// Fills the dynamic fields of a record whose static fields came from
510/// [`static_info`]: addresses, sizes, direction, branch outcome. Returns
511/// true if the instruction had more accesses than the record can hold.
512pub fn fill_dynamic(t: &mut MacsimRecord, rec: &InstructionRecord, rflags: u64, branch_target: u64) -> bool {
513    t.instruction_addr = rec.linear_rip;
514    t.rep_dir = rflags & RFLAGS_DF != 0;
515    t.actually_taken = rec.branch_taken;
516    t.branch_target = branch_target;
517    let (loads, store, extra) = selected_accesses(t, rec);
518    if let Some(&k) = loads.first() {
519        t.ld_vaddr1 = rec.accesses[k].linear;
520        t.mem_read_size = rec.accesses[k].size.min(255) as u8;
521    }
522    if let Some(&k) = loads.get(1) {
523        t.ld_vaddr2 = rec.accesses[k].linear;
524    }
525    if let Some(k) = store {
526        t.st_vaddr = rec.accesses[k].linear;
527        t.mem_write_size = rec.accesses[k].size.min(255) as u8;
528    }
529    // A REP string instruction whose count was zero touches nothing: the
530    // static load/store counts stay (MacSim keys its decode cache by PC)
531    // but the sizes stay zero, which MacSim's STRINGOP path treats as a no-op.
532    extra
533}
534
535/// Writes one vCPU's MacSim `.raw` stream.
536pub struct MacsimWriter {
537    out: GzEncoder<BufWriter<File>>,
538    count: u64,
539}
540
541impl MacsimWriter {
542    /// Creates `<base>_<tid>.raw`.
543    pub fn create(base: &Path, tid: u32, level: u32) -> Result<MacsimWriter> {
544        let path = raw_path(base, tid);
545        let f = File::create(&path)?;
546        Ok(MacsimWriter { out: GzEncoder::new(BufWriter::with_capacity(1 << 20, f), Compression::new(level)), count: 0 })
547    }
548
549    /// Appends one record.
550    pub fn write(&mut self, r: &MacsimRecord) -> Result<()> {
551        self.out.write_all(&r.to_bytes())?;
552        self.count += 1;
553        Ok(())
554    }
555
556    /// Records written so far.
557    pub fn count(&self) -> u64 {
558        self.count
559    }
560
561    /// Finishes the gzip stream.
562    pub fn finish(self) -> Result<u64> {
563        self.out.finish()?.flush()?;
564        Ok(self.count)
565    }
566}
567
568/// Path of thread `tid`'s raw file for trace base name `base`.
569pub fn raw_path(base: &Path, tid: u32) -> PathBuf {
570    let mut s = base.as_os_str().to_owned();
571    s.push(format!("_{tid}.raw"));
572    PathBuf::from(s)
573}
574
575/// Writes the `<base>.txt` header MacSim opens first.
576///
577/// `threads` lists `(thread id, start instruction count)`; for a trace in
578/// which all vCPUs start together the start count is 0.
579pub fn write_config(base: &Path, threads: &[(u32, u64)]) -> Result<PathBuf> {
580    let mut p = base.as_os_str().to_owned();
581    p.push(".txt");
582    let p = PathBuf::from(p);
583    let mut f = File::create(&p)?;
584    writeln!(f, "x86 {GENERATOR_VERSION}")?;
585    writeln!(f, "{}", threads.len())?;
586    for (tid, start) in threads {
587        writeln!(f, "{tid} {start}")?;
588    }
589    Ok(p)
590}
591
592/// Reads records back from a `.raw` file (for checking and for the CLI).
593pub struct MacsimReader {
594    inp: MultiGzDecoder<std::io::BufReader<File>>,
595}
596
597impl MacsimReader {
598    /// Opens a `.raw` file.
599    pub fn open(path: &Path) -> Result<MacsimReader> {
600        Ok(MacsimReader { inp: MultiGzDecoder::new(std::io::BufReader::new(File::open(path)?)) })
601    }
602}
603
604impl Iterator for MacsimReader {
605    type Item = Result<MacsimRecord>;
606    fn next(&mut self) -> Option<Self::Item> {
607        let mut b = [0u8; RECORD_SIZE];
608        let mut got = 0;
609        while got < RECORD_SIZE {
610            match self.inp.read(&mut b[got..]) {
611                Ok(0) if got == 0 => return None,
612                Ok(0) => return Some(Err(Error::Format("truncated MacSim record".into()))),
613                Ok(n) => got += n,
614                Err(e) => return Some(Err(e.into())),
615            }
616        }
617        Some(Ok(MacsimRecord::from_bytes(&b)))
618    }
619}
620
621#[cfg(test)]
622mod tests {
623    use super::*;
624
625    #[test]
626    fn record_roundtrip() {
627        let r = MacsimRecord {
628            num_read_regs: 2,
629            src: [10, 25, 0, 0, 0, 0, 0, 0, 0],
630            opcode: 13,
631            ld_vaddr1: 0x1234,
632            instruction_addr: 0xffff_ffff_8100_0000,
633            mem_read_size: 8,
634            actually_taken: true,
635            ..Default::default()
636        };
637        assert_eq!(MacsimRecord::from_bytes(&r.to_bytes()), r);
638    }
639
640    #[test]
641    fn opcode_table_matches_macsim_enum_order() {
642        assert_eq!(opcode_id("INVALID"), Some(0));
643        assert_eq!(opcode_id("XSAVEOPT"), Some(94));
644        assert_eq!(OPCODE_NAMES.len(), 105); // CPU_OPCODE_LAST in trace_read.h
645        assert_eq!(opcode_id("TR_MUL"), Some(95));
646        assert_eq!(opcode_id("GPU_EN"), Some(104));
647    }
648
649    #[test]
650    fn xed_table_is_sorted() {
651        let t = xed_categories::XED_ICLASS_CATEGORY;
652        assert!(t.windows(2).all(|w| w[0].0 < w[1].0));
653    }
654}