1use iced_x86::{
15 Code, Decoder, DecoderOptions, FlowControl, InstructionInfoFactory, Mnemonic, OpAccess, OpKind, Register,
16};
17
18use crate::memory::GuestMemory;
19use crate::paging::{read_linear, translate};
20use crate::record::{AccessClass, AccessKind};
21use crate::state::{CpuMode, CpuState, SegReg, gpr};
22
23#[derive(Debug, Clone)]
25pub struct Decoded {
26 pub instr: iced_x86::Instruction,
28 pub bytes: [u8; 15],
30 pub len: u8,
32 pub linear_rip: u64,
34 pub physical_rip: Option<u64>,
36 pub fetches: Vec<(u64, Option<u64>, u32)>,
39}
40
41pub fn fetch(
47 state: &CpuState,
48 mem: &dyn GuestMemory,
49 original_byte: &dyn Fn(u64) -> Option<u8>,
50) -> Option<Decoded> {
51 let la = state.linear_rip();
52 let mut bytes = [0u8; 15];
53 let mut fetches = Vec::with_capacity(2);
54 let mut got = 0usize;
55 let mut physical_rip = None;
56 while got < 15 {
57 let a = la.wrapping_add(got as u64) & state.linear_mask();
58 let Ok(t) = translate(state, mem, a) else { break };
59 let n = ((4096 - (a & 0xfff)) as usize).min(15 - got);
60 if mem.read(t.physical, &mut bytes[got..got + n]).is_err() {
61 break;
62 }
63 for i in 0..n {
64 if let Some(b) = original_byte(t.physical + i as u64) {
65 bytes[got + i] = b;
66 }
67 }
68 if got == 0 {
69 physical_rip = Some(t.physical);
70 }
71 fetches.push((a, Some(t.physical), n as u32));
72 got += n;
73 }
74 if got == 0 {
75 return None;
76 }
77 let mut dec = Decoder::with_ip(state.mode().bitness(), &bytes[..got], state.rip, DecoderOptions::NONE);
78 let instr = dec.decode();
79 if instr.is_invalid() {
80 return None;
81 }
82 let len = instr.len() as u8;
83 let mut left = len as u32;
85 fetches.retain_mut(|f| {
86 if left == 0 {
87 return false;
88 }
89 f.2 = f.2.min(left);
90 left -= f.2;
91 true
92 });
93 Some(Decoded { instr, bytes, len, linear_rip: la, physical_rip, fetches })
94}
95
96#[derive(Clone)]
101pub struct VectorRegs {
102 pub xsave: Vec<u8>,
104}
105
106impl std::fmt::Debug for VectorRegs {
107 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
108 f.write_str("VectorRegs { .. }")
109 }
110}
111
112impl VectorRegs {
113 fn get(&self, off: usize, len: usize) -> Option<&[u8]> {
114 self.xsave.get(off..off + len)
115 }
116
117 fn vector_bytes(&self, n: usize, out: &mut [u8; 64]) -> Option<()> {
119 if n < 16 {
122 out[..16].copy_from_slice(self.get(160 + 16 * n, 16)?);
123 if let Some(h) = self.get(576 + 16 * n, 16) {
124 out[16..32].copy_from_slice(h);
125 }
126 if let Some(h) = self.get(1152 + 32 * n, 32) {
127 out[32..64].copy_from_slice(h);
128 }
129 } else {
130 out.copy_from_slice(self.get(1664 + 64 * (n - 16), 64)?);
131 }
132 Some(())
133 }
134
135 pub fn element(&self, reg: Register, index: usize, size: usize) -> Option<u64> {
137 let n = reg.number();
138 let mut b = [0u8; 64];
139 self.vector_bytes(n, &mut b)?;
140 let off = index * size;
141 let s = b.get(off..off + size)?;
142 Some(if size == 4 { u32::from_le_bytes(s.try_into().ok()?) as u64 } else { u64::from_le_bytes(s.try_into().ok()?) })
143 }
144
145 pub fn opmask(&self, k: usize) -> Option<u64> {
147 Some(u64::from_le_bytes(self.get(1088 + 8 * k, 8)?.try_into().ok()?))
148 }
149}
150
151pub fn gpr_value(state: &CpuState, reg: Register) -> Option<u64> {
153 if !reg.is_gpr() {
154 return None;
155 }
156 let full = reg.full_register();
157 let idx = (full as usize).checked_sub(Register::RAX as usize)?;
158 let v = *state.gpr.get(idx)?;
159 Some(match reg {
160 Register::AH | Register::CH | Register::DH | Register::BH => (v >> 8) & 0xff,
161 _ => match reg.size() {
162 1 => v & 0xff,
163 2 => v & 0xffff,
164 4 => v & 0xffff_ffff,
165 _ => v,
166 },
167 })
168}
169
170fn seg_of(reg: Register) -> Option<SegReg> {
171 Some(match reg {
172 Register::ES => SegReg::Es,
173 Register::CS => SegReg::Cs,
174 Register::SS => SegReg::Ss,
175 Register::DS => SegReg::Ds,
176 Register::FS => SegReg::Fs,
177 Register::GS => SegReg::Gs,
178 _ => return None,
179 })
180}
181
182#[derive(Debug, Clone, Copy, PartialEq, Eq)]
184pub struct PlannedAccess {
185 pub linear: u64,
187 pub size: u32,
189 pub kind: AccessKind,
191 pub class: AccessClass,
193 pub conditional: bool,
195 pub element: Option<u16>,
197}
198
199pub fn io_permission_accesses(state: &CpuState, d: &Decoded, mem: &dyn GuestMemory) -> Vec<PlannedAccess> {
212 let i = &d.instr;
213 if !matches!(i.mnemonic(), Mnemonic::In | Mnemonic::Out | Mnemonic::Insb | Mnemonic::Insw | Mnemonic::Insd | Mnemonic::Outsb | Mnemonic::Outsw | Mnemonic::Outsd) {
214 return Vec::new();
215 }
216 let mode = state.mode();
217 let checked = match mode {
218 CpuMode::Real => false,
219 CpuMode::Virtual8086 => true,
220 _ => state.cpl() > state.iopl(),
221 };
222 if !checked {
223 return Vec::new();
224 }
225 let port = (0..i.op_count())
226 .find_map(|n| match i.op_kind(n) {
227 OpKind::Immediate8 => Some(i.immediate8() as u64),
228 OpKind::Register if i.op_register(n) == Register::DX => Some(state.gpr[gpr::RDX] & 0xffff),
229 _ => None,
230 })
231 .unwrap_or(state.gpr[gpr::RDX] & 0xffff);
232 let tss = state.tr.base;
233 let read = |linear: u64| PlannedAccess {
234 linear,
235 size: 2,
236 kind: AccessKind::Read,
237 class: AccessClass::Implicit,
238 conditional: false,
239 element: None,
240 };
241 let mut out = Vec::new();
242 if (state.tr.limit as u64) < 0x67 {
243 return out; }
245 out.push(read(tss + 0x66));
246 let mut b = [0u8; 2];
247 if read_linear(state, mem, tss + 0x66, &mut b) == 2 {
248 let off = u16::from_le_bytes(b) as u64 + port / 8;
249 if off + 1 <= state.tr.limit as u64 {
250 out.push(read(tss + off));
251 }
252 }
253 out
254}
255
256pub fn needs_vector_regs(d: &Decoded, info: &mut InstructionInfoFactory) -> bool {
258 info.info(&d.instr).used_memory().iter().any(|m| m.vsib_size() != 0)
259}
260
261pub fn is_rep_string(i: &iced_x86::Instruction) -> bool {
263 (i.has_rep_prefix() || i.has_repe_prefix() || i.has_repne_prefix()) && i.is_string_instruction()
264}
265
266pub fn rep_count(state: &CpuState, i: &iced_x86::Instruction) -> u64 {
268 let rcx = state.gpr[gpr::RCX];
269 match rep_address_size(state, i) {
270 2 => rcx & 0xffff,
271 4 => rcx & 0xffff_ffff,
272 _ => rcx,
273 }
274}
275
276fn rep_address_size(state: &CpuState, i: &iced_x86::Instruction) -> u32 {
277 let def = match state.mode().bitness() {
279 64 => 8,
280 32 => 4,
281 _ => 2,
282 };
283 for op in 0..i.op_count() {
285 match i.op_kind(op) {
286 OpKind::MemorySegRSI | OpKind::MemorySegRDI | OpKind::MemoryESRDI => return 8,
287 OpKind::MemorySegESI | OpKind::MemorySegEDI | OpKind::MemoryESEDI => return 4,
288 OpKind::MemorySegSI | OpKind::MemorySegDI | OpKind::MemoryESDI => return 2,
289 _ => {}
290 }
291 }
292 def
293}
294
295fn is_prefetch(m: Mnemonic) -> bool {
296 matches!(
297 m,
298 Mnemonic::Prefetchnta
299 | Mnemonic::Prefetcht0
300 | Mnemonic::Prefetcht1
301 | Mnemonic::Prefetcht2
302 | Mnemonic::Prefetchw
303 | Mnemonic::Prefetchwt1
304 | Mnemonic::Prefetch
305 | Mnemonic::Prefetchit0
306 | Mnemonic::Prefetchit1
307 )
308}
309
310pub fn plan_accesses(
315 state: &CpuState,
316 d: &Decoded,
317 info: &mut InstructionInfoFactory,
318 vregs: Option<&VectorRegs>,
319) -> Vec<PlannedAccess> {
320 let i = &d.instr;
321 let mut out = Vec::new();
322 if is_rep_string(i) && rep_count(state, i) == 0 {
324 return out;
325 }
326 let long = state.mode() == CpuMode::Long64;
327 let mut value = |reg: Register, elem: usize, esize: usize| -> Option<u64> {
328 if let Some(s) = seg_of(reg) {
329 return Some(state.effective_segment_base(s));
330 }
331 if reg.is_gpr() {
332 return gpr_value(state, reg);
333 }
334 match reg {
335 Register::RIP | Register::EIP => Some(i.next_ip()),
336 r if r.is_xmm() || r.is_ymm() || r.is_zmm() => vregs?.element(r, elem, esize),
337 _ => None,
338 }
339 };
340 let explicit_mem = (0..i.op_count()).any(|n| i.op_kind(n) == OpKind::Memory);
341 let prefetch = is_prefetch(i.mnemonic());
342 let info = info.info(i);
343 for um in info.used_memory() {
344 let (kind, conditional) = match um.access() {
345 OpAccess::Read => (AccessKind::Read, false),
346 OpAccess::CondRead => (AccessKind::Read, true),
347 OpAccess::Write => (AccessKind::Write, false),
348 OpAccess::CondWrite => (AccessKind::Write, true),
349 OpAccess::ReadWrite => (AccessKind::ReadWrite, false),
350 OpAccess::ReadCondWrite => (AccessKind::ReadWrite, false),
353 OpAccess::NoMemAccess if prefetch => (AccessKind::Read, false),
354 _ => continue,
355 };
356 let class = if prefetch {
357 AccessClass::Prefetch
358 } else if explicit_mem && um.index() == i.memory_index() && (um.base() == i.memory_base() || i.is_ip_rel_memory_operand()) {
359 AccessClass::Operand
360 } else {
361 AccessClass::Implicit
362 };
363 let size = um.memory_size().size() as u32;
364 let size = if size == 0 { 1 } else { size };
365 let seg_mask = if long { u64::MAX } else { 0xffff_ffff };
366 if um.vsib_size() != 0 {
367 let esize = um.vsib_size() as usize;
369 let index_bytes = um.index().size();
370 let data_elem = um.memory_size().element_size().max(1);
371 let dest_bytes = if i.op_count() > 0 && i.op_kind(0) == OpKind::Register {
372 i.op0_register().size()
373 } else {
374 i.op_register(i.op_count() - 1).size()
376 };
377 let n = (index_bytes / esize).min(dest_bytes / data_elem);
378 for e in 0..n {
379 let active = match vregs {
380 None => None,
381 Some(v) => {
382 if i.op_mask() != Register::None {
383 let k = i.op_mask().number();
384 v.opmask(k).map(|m| m >> e & 1 == 1)
385 } else if i.op_count() >= 3 && i.op_kind(2) == OpKind::Register {
386 let mreg = i.op2_register();
388 v.element(mreg, e, data_elem).map(|m| m >> (data_elem * 8 - 1) & 1 == 1)
389 } else {
390 Some(true)
391 }
392 }
393 };
394 if active != Some(true) {
395 continue;
396 }
397 if let Some(ea) = um.virtual_address(e, &mut value) {
398 out.push(PlannedAccess {
399 linear: ea & seg_mask,
400 size: data_elem as u32,
401 kind,
402 class,
403 conditional: true,
404 element: Some(e as u16),
405 });
406 }
407 }
408 continue;
409 }
410 if let Some(ea) = um.virtual_address(0, &mut value) {
411 out.push(PlannedAccess { linear: ea & seg_mask, size, kind, class, conditional, element: None });
412 }
413 }
414 out.sort_by_key(|a| match a.kind {
416 AccessKind::Read => 0,
417 AccessKind::ReadWrite => 1,
418 _ => 2,
419 });
420 out
421}
422
423#[derive(Debug, Clone, PartialEq, Eq)]
425pub enum Successors {
426 Exactly(Vec<u64>),
428 Unknown,
431}
432
433impl Successors {
434 pub fn admits(&self, rip: u64) -> Option<bool> {
436 match self {
437 Successors::Exactly(v) => Some(v.contains(&rip)),
438 Successors::Unknown => None,
439 }
440 }
441}
442
443pub fn predict_successors(state: &CpuState, mem: &dyn GuestMemory, d: &Decoded, lstar: Option<u64>) -> Successors {
447 let i = &d.instr;
448 let next = i.next_ip();
449 let rip_mask = match state.mode().bitness() {
450 64 => u64::MAX,
451 32 => 0xffff_ffff,
452 _ => 0xffff,
453 };
454 let read_stack = |off: u64, size: usize| -> Option<u64> {
455 let sp = state.stack_pointer();
456 let ss = state.effective_segment_base(SegReg::Ss);
457 let mut b = [0u8; 8];
458 let la = ss.wrapping_add(sp.wrapping_add(off)) & state.linear_mask();
459 (read_linear(state, mem, la, &mut b[..size]) == size).then(|| u64::from_le_bytes(b))
460 };
461 match i.mnemonic() {
462 Mnemonic::Syscall => return lstar.map_or(Successors::Unknown, |l| Successors::Exactly(vec![l])),
463 Mnemonic::Hlt => return Successors::Exactly(vec![next]),
464 _ => {}
465 }
466 match i.flow_control() {
467 FlowControl::Next => {
468 let mut v = vec![next & rip_mask];
469 if is_rep_string(i) {
470 v.push(state.rip);
471 }
472 Successors::Exactly(v)
473 }
474 FlowControl::UnconditionalBranch | FlowControl::Call => {
475 if matches!(i.op0_kind(), OpKind::NearBranch16 | OpKind::NearBranch32 | OpKind::NearBranch64) {
476 Successors::Exactly(vec![i.near_branch_target()])
477 } else {
478 Successors::Unknown
479 }
480 }
481 FlowControl::ConditionalBranch => {
482 if matches!(i.op0_kind(), OpKind::NearBranch16 | OpKind::NearBranch32 | OpKind::NearBranch64) {
483 Successors::Exactly(vec![i.near_branch_target(), next & rip_mask])
484 } else {
485 Successors::Unknown
486 }
487 }
488 FlowControl::IndirectBranch | FlowControl::IndirectCall => {
489 if matches!(i.code(), Code::Jmp_m1632 | Code::Jmp_m1664 | Code::Jmp_m1616 | Code::Call_m1632 | Code::Call_m1664 | Code::Call_m1616) {
490 return Successors::Unknown; }
492 let size = i.memory_size().size();
493 match i.op0_kind() {
494 OpKind::Register => gpr_value(state, i.op0_register())
495 .map_or(Successors::Unknown, |v| Successors::Exactly(vec![v & rip_mask])),
496 OpKind::Memory => {
497 let mut f = InstructionInfoFactory::new();
498 let plan = plan_accesses(state, d, &mut f, None);
499 let Some(a) = plan.iter().find(|a| a.class == AccessClass::Operand) else {
500 return Successors::Unknown;
501 };
502 let mut b = [0u8; 8];
503 let n = size.clamp(1, 8);
504 if read_linear(state, mem, a.linear, &mut b[..n]) == n {
505 Successors::Exactly(vec![u64::from_le_bytes(b) & rip_mask])
506 } else {
507 Successors::Unknown
508 }
509 }
510 _ => Successors::Unknown,
511 }
512 }
513 FlowControl::Return => match i.mnemonic() {
514 Mnemonic::Ret => {
515 let size = match (state.mode().bitness(), i.code()) {
516 (64, Code::Retnw | Code::Retnw_imm16) => 2,
517 (64, _) => 8,
518 (_, Code::Retnd | Code::Retnd_imm16) => 4,
519 (_, Code::Retnw | Code::Retnw_imm16) => 2,
520 (32, _) => 4,
521 _ => 2,
522 };
523 read_stack(0, size).map_or(Successors::Unknown, |v| Successors::Exactly(vec![v & rip_mask]))
524 }
525 _ => Successors::Unknown,
526 },
527 _ => Successors::Unknown,
528 }
529}
530
531pub fn may_clear_tf(i: &iced_x86::Instruction) -> bool {
535 matches!(
536 i.mnemonic(),
537 Mnemonic::Popf
538 | Mnemonic::Popfd
539 | Mnemonic::Popfq
540 | Mnemonic::Iret
541 | Mnemonic::Iretd
542 | Mnemonic::Iretq
543 | Mnemonic::Sysret
544 | Mnemonic::Sysretq
545 | Mnemonic::Sysexit
546 | Mnemonic::Sysexitq
547 | Mnemonic::Syscall
548 | Mnemonic::Sysenter
549 | Mnemonic::Rsm
550 | Mnemonic::Int
551 | Mnemonic::Int1
552 | Mnemonic::Int3
553 | Mnemonic::Into
554 | Mnemonic::Eretu
555 | Mnemonic::Erets
556 )
557}