1mod 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
57pub const RECORD_SIZE: usize = 80;
59pub const MAX_SRC: usize = 9;
61pub const MAX_DST: usize = 6;
63pub const GENERATOR_VERSION: &str = "1.3";
65
66#[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#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
85pub struct MacsimRecord {
86 pub num_read_regs: u8,
88 pub num_dest_regs: u8,
90 pub src: [u8; MAX_SRC],
92 pub dst: [u8; MAX_DST],
94 pub cf_type: u8,
96 pub has_immediate: bool,
98 pub opcode: u8,
100 pub has_st: bool,
102 pub is_fp: bool,
104 pub write_flg: bool,
106 pub num_ld: u8,
108 pub size: u8,
110 pub ld_vaddr1: u64,
112 pub ld_vaddr2: u64,
114 pub st_vaddr: u64,
116 pub instruction_addr: u64,
118 pub branch_target: u64,
120 pub mem_read_size: u8,
122 pub mem_write_size: u8,
124 pub rep_dir: bool,
126 pub actually_taken: bool,
128}
129
130impl MacsimRecord {
131 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 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 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 pub fn opcode_name(&self) -> &'static str {
189 OPCODE_NAMES.get(self.opcode as usize).copied().unwrap_or("?")
190 }
191}
192
193pub 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
212fn 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
257fn 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 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
294fn 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
315pub enum CategorySource {
316 Xed,
318 Heuristic,
320}
321
322pub 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 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 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
357pub fn pin_reg(r: Register) -> Option<u8> {
360 if r.is_gpr() {
361 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#[derive(Debug, Clone, Copy)]
388pub struct StaticInfo {
389 pub template: MacsimRecord,
391 pub category: CategorySource,
393}
394
395pub 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 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 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 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
478pub 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
509pub 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 extra
533}
534
535pub struct MacsimWriter {
537 out: GzEncoder<BufWriter<File>>,
538 count: u64,
539}
540
541impl MacsimWriter {
542 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 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 pub fn count(&self) -> u64 {
558 self.count
559 }
560
561 pub fn finish(self) -> Result<u64> {
563 self.out.finish()?.flush()?;
564 Ok(self.count)
565 }
566}
567
568pub 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
575pub 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
592pub struct MacsimReader {
594 inp: MultiGzDecoder<std::io::BufReader<File>>,
595}
596
597impl MacsimReader {
598 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); 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}