This repository has been archived by the owner on Jan 18, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
trace.rs
740 lines (649 loc) · 25.7 KB
/
trace.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
use anyhow::{anyhow, Context, Result};
use iced_x86::{
Code, Decoder, DecoderOptions, Instruction, InstructionInfoFactory, InstructionInfoOptions,
MemorySize, Mnemonic, OpAccess, Register,
};
use nix::sys::personality::{self, Persona};
use nix::sys::ptrace;
use nix::sys::signal;
use nix::sys::uio;
use nix::sys::wait;
use nix::unistd::Pid;
use serde::Serialize;
use spawn_ptrace::CommandPtraceSpawn;
use std::convert::{TryFrom, TryInto};
use std::io;
use std::os::unix::process::CommandExt;
use std::process::Command;
const MAX_INSTR_LEN: usize = 15;
pub trait CommandPersonality {
fn personality(&mut self, persona: Persona);
}
impl CommandPersonality for Command {
fn personality(&mut self, persona: Persona) {
unsafe {
self.pre_exec(move || match personality::set(persona) {
Ok(_) => Ok(()),
Err(nix::Error::Sys(e)) => Err(io::Error::from_raw_os_error(e as i32)),
Err(_) => Err(io::Error::new(
io::ErrorKind::Other,
"unknown personality error",
)),
})
};
}
}
/// Represents the width of a concrete memory operation.
///
/// All `mttn` memory operations are 1, 2, 4, or 8 bytes.
/// Larger operations are either modeled as multiple individual operations
/// (if caused by a `REP` prefix), ignored (if configured), or cause a fatal error.
#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
pub enum MemoryMask {
Byte = 1,
Word = 2,
DWord = 4,
QWord = 8,
}
impl TryFrom<u64> for MemoryMask {
type Error = anyhow::Error;
fn try_from(size: u64) -> Result<Self> {
Ok(match size {
1 => MemoryMask::Byte,
2 => MemoryMask::Word,
4 => MemoryMask::DWord,
8 => MemoryMask::QWord,
_ => return Err(anyhow!("size {} doesn't have a supported mask", size)),
})
}
}
impl TryFrom<Register> for MemoryMask {
type Error = anyhow::Error;
fn try_from(reg: Register) -> Result<Self> {
(reg.info().size() as u64).try_into()
}
}
/// The access disposition of a concrete memory operation.
///
/// All `mttn` operations are either `Read` or `Write`. Instructions that
/// perform a read-and-update are modeled with two separate operations.
/// Instructions that perform conditional reads or writes are modeled only
/// if the conditional memory operation actually took place during the trace.
#[derive(Clone, Copy, Debug, PartialEq, Serialize)]
pub enum MemoryOp {
Read,
Write,
}
/// Represents an entire traced memory operation, including its kind (`MemoryOp`),
/// size (`MemoryMask`), concrete address, and actual read or written data.
#[derive(Debug, PartialEq, Serialize)]
pub struct MemoryHint {
address: u64,
operation: MemoryOp,
mask: MemoryMask,
data: Vec<u8>,
}
/// Represents an individual step in the trace, including the raw instruction bytes,
/// the register file state before execution, and any memory operations that result
/// from execution.
#[derive(Debug, PartialEq, Serialize)]
pub struct Step {
instr: Vec<u8>,
regs: RegisterFile,
hints: Vec<MemoryHint>,
}
/// Represents the (usermode) register file.
///
/// Only the standard addressable registers, plus `RFLAGS`, are tracked.
/// `mttn` assumes that all segment base addresses are `0` and therefore doesn't
/// track them.
#[derive(Clone, Copy, Debug, Default, PartialEq, Serialize)]
pub struct RegisterFile {
rax: u64,
rbx: u64,
rcx: u64,
rdx: u64,
rsi: u64,
rdi: u64,
rsp: u64,
rbp: u64,
r8: u64,
r9: u64,
r10: u64,
r11: u64,
r12: u64,
r13: u64,
r14: u64,
r15: u64,
rip: u64,
rflags: u64,
fs_base: u64,
gs_base: u64,
}
impl RegisterFile {
/// Given a symbolic iced-x86 register, concretize it against the register file.
/// Narrows the result, as appropriate.
///
/// Untracked registers result in an `Err` result.
fn value(&self, reg: Register) -> Result<u64> {
match reg {
// 8 bit regs.
Register::AL => Ok((self.rax as u8).into()),
Register::BL => Ok((self.rbx as u8).into()),
Register::CL => Ok((self.rcx as u8).into()),
Register::DL => Ok((self.rdx as u8).into()),
Register::AH => Ok(((self.rax >> 8) as u8).into()),
Register::BH => Ok(((self.rbx >> 8) as u8).into()),
Register::CH => Ok(((self.rcx >> 8) as u8).into()),
Register::DH => Ok(((self.rdx >> 8) as u8).into()),
Register::R8L => Ok((self.r8 as u8).into()),
Register::R9L => Ok((self.r9 as u8).into()),
Register::R10L => Ok((self.r10 as u8).into()),
Register::R11L => Ok((self.r11 as u8).into()),
Register::R12L => Ok((self.r12 as u8).into()),
Register::R13L => Ok((self.r13 as u8).into()),
Register::R14L => Ok((self.r14 as u8).into()),
Register::R15L => Ok((self.r15 as u8).into()),
// 16 bit regs.
Register::AX => Ok((self.rax as u16).into()),
Register::BX => Ok((self.rbx as u16).into()),
Register::CX => Ok((self.rcx as u16).into()),
Register::DX => Ok((self.rdx as u16).into()),
Register::SI => Ok((self.rsi as u16).into()),
Register::DI => Ok((self.rdi as u16).into()),
Register::SP => Ok((self.rsp as u16).into()),
Register::BP => Ok((self.rbp as u16).into()),
Register::R8W => Ok((self.r8 as u16).into()),
Register::R9W => Ok((self.r9 as u16).into()),
Register::R10W => Ok((self.r10 as u16).into()),
Register::R11W => Ok((self.r11 as u16).into()),
Register::R12W => Ok((self.r12 as u16).into()),
Register::R13W => Ok((self.r13 as u16).into()),
Register::R14W => Ok((self.r14 as u16).into()),
Register::R15W => Ok((self.r15 as u16).into()),
// 32 bit regs.
Register::EAX => Ok((self.rax as u32).into()),
Register::EBX => Ok((self.rbx as u32).into()),
Register::ECX => Ok((self.rcx as u32).into()),
Register::EDX => Ok((self.rdx as u32).into()),
Register::ESI => Ok((self.rsi as u32).into()),
Register::EDI => Ok((self.rdi as u32).into()),
Register::ESP => Ok((self.rsp as u32).into()),
Register::EBP => Ok((self.rbp as u32).into()),
Register::R8D => Ok((self.r8 as u32).into()),
Register::R9D => Ok((self.r9 as u32).into()),
Register::R10D => Ok((self.r10 as u32).into()),
Register::R11D => Ok((self.r11 as u32).into()),
Register::R12D => Ok((self.r12 as u32).into()),
Register::R13D => Ok((self.r13 as u32).into()),
Register::R14D => Ok((self.r14 as u32).into()),
Register::R15D => Ok((self.r15 as u32).into()),
Register::EIP => Ok((self.rip as u32).into()),
// 64 bit regs.
Register::RAX => Ok(self.rax),
Register::RBX => Ok(self.rbx),
Register::RCX => Ok(self.rcx),
Register::RDX => Ok(self.rdx),
Register::RSI => Ok(self.rsi),
Register::RDI => Ok(self.rdi),
Register::RSP => Ok(self.rsp),
Register::RBP => Ok(self.rbp),
Register::R8 => Ok(self.r8),
Register::R9 => Ok(self.r9),
Register::R10 => Ok(self.r10),
Register::R11 => Ok(self.r11),
Register::R12 => Ok(self.r12),
Register::R13 => Ok(self.r13),
Register::R14 => Ok(self.r14),
Register::R15 => Ok(self.r15),
Register::RIP => Ok(self.rip),
// FS and GS: We support these because Linux uses them for TLS.
// We return the FSBASE and GSBASE values here, since we're returning by address
// and not by descriptor value.
Register::FS => Ok(self.fs_base),
Register::GS => Ok(self.gs_base),
// All other segment registers are treated as 0, per the Tiny86 model.
Register::SS | Register::CS | Register::DS | Register::ES => Ok(0),
// Everything else (vector regs, control regs, debug regs, etc) is unsupported.
// NOTE(ww): We track rflags in this struct, but iced-x86 doesn't have a Register
// variant for it (presumably because it's unaddressable).
_ => Err(anyhow!("untracked register requested: {:?}", reg)),
}
}
}
impl From<libc::user_regs_struct> for RegisterFile {
fn from(user_regs: libc::user_regs_struct) -> Self {
Self {
rax: user_regs.rax,
rbx: user_regs.rbx,
rcx: user_regs.rcx,
rdx: user_regs.rdx,
rsi: user_regs.rsi,
rdi: user_regs.rdi,
rsp: user_regs.rsp,
rbp: user_regs.rbp,
r8: user_regs.r8,
r9: user_regs.r9,
r10: user_regs.r10,
r11: user_regs.r11,
r12: user_regs.r12,
r13: user_regs.r13,
r14: user_regs.r14,
r15: user_regs.r15,
rip: user_regs.rip,
rflags: user_regs.eflags,
fs_base: user_regs.fs_base,
gs_base: user_regs.gs_base,
}
}
}
/// Represents a valid target for a `Tracer`.
///
/// The currently valid targets are `Program`s (which haven't been spawned yet)
/// and already-spawned `Process`es.
#[derive(Debug)]
pub enum Target {
Program(String, Vec<String>),
Process(Pid),
}
/// Represents an actively traced program, in some indeterminate state.
///
/// Tracees are associated with their parent `Tracer`.
pub struct Tracee<'a> {
terminated: bool,
tracee_pid: Pid,
tracer: &'a Tracer,
info_factory: InstructionInfoFactory,
register_file: RegisterFile,
}
impl<'a> Tracee<'a> {
/// Create a new `Tracee` from the given PID (presumably either spawned with `PTRACE_TRACEME`
/// or recently attached to) and `Tracer`.
fn new(tracee_pid: Pid, tracer: &'a Tracer) -> Self {
#[allow(clippy::redundant_field_names)]
Self {
terminated: false,
tracee_pid: tracee_pid,
tracer: &tracer,
info_factory: InstructionInfoFactory::new(),
register_file: Default::default(),
}
}
/// Step the tracee forwards by one instruction, returning the trace `Step` or
/// an `Err` if an internal tracing step fails.
fn step(&mut self) -> Result<Step> {
self.tracee_regs()?;
let (instr, instr_bytes) = self.tracee_instr()?;
// TODO(ww): Check `instr` here and perform one of two cases:
// 1. If `instr` is an instruction that benefits from modeling/emulation
// (e.g. `MOVS`), then emulate it and generate its memory hints
// from the emulation.
// 2. Otherwise, generate the hints as normal (do phase 1, single-step,
// then phase 2).
// Hints are generated in two phases: we build a complete list of
// expected hints (including all Read hints) in stage 1...
let mut hints = self.tracee_hints_stage1(&instr)?;
ptrace::step(self.tracee_pid, None)?;
// ...then, after we've stepped the program, we fill in the data
// associated with each Write hint in stage 2.
self.tracee_hints_stage2(&mut hints)?;
match wait::waitpid(self.tracee_pid, None)? {
wait::WaitStatus::Exited(_, status) => {
log::debug!("exited with {}", status);
self.terminated = true;
}
wait::WaitStatus::Signaled(_, _, _) => {
log::debug!("signaled");
}
wait::WaitStatus::Stopped(_, signal) => {
log::debug!("stopped with {:?}", signal);
}
wait::WaitStatus::StillAlive => {
log::debug!("still alive");
}
s => {
log::debug!("{:?}", s);
self.terminated = true;
}
}
#[allow(clippy::redundant_field_names)]
Ok(Step {
instr: instr_bytes,
regs: self.register_file,
hints: hints,
})
}
/// Loads the our register file from the tracee's user register state.
fn tracee_regs(&mut self) -> Result<()> {
self.register_file = RegisterFile::from(ptrace::getregs(self.tracee_pid)?);
Ok(())
}
/// Returns the iced-x86 `Instruction` and raw instruction bytes at the tracee's
/// current instruction pointer.
fn tracee_instr(&self) -> Result<(Instruction, Vec<u8>)> {
let mut bytes = vec![0u8; MAX_INSTR_LEN];
let remote_iov = uio::RemoteIoVec {
base: self.register_file.rip as usize,
len: MAX_INSTR_LEN,
};
// TODO(ww): Check the length here.
uio::process_vm_readv(
self.tracee_pid,
&[uio::IoVec::from_mut_slice(&mut bytes)],
&[remote_iov],
)?;
log::debug!("fetched instruction bytes: {:?}", bytes);
let mut decoder = Decoder::new(self.tracer.bitness, &bytes, DecoderOptions::NONE);
decoder.set_ip(self.register_file.rip);
let instr = decoder.decode();
log::debug!("instr: {:?}", instr.code());
match instr.code() {
Code::INVALID => Err(anyhow!("invalid instruction")),
_ => {
bytes.truncate(instr.len());
Ok((instr, bytes))
}
}
}
/// Reads a piece of the tracee's memory, starting at `addr`.
fn tracee_data(&self, addr: u64, mask: MemoryMask) -> Result<Vec<u8>> {
log::debug!("attempting to read tracee @ 0x{:x} ({:?})", addr, mask);
// NOTE(ww): Could probably use ptrace::read() here since we're always <= 64 bits,
// but I find process_vm_readv a little more readable.
let mut bytes = vec![0u8; mask as usize];
let remote_iov = uio::RemoteIoVec {
base: addr as usize,
len: mask as usize,
};
// NOTE(ww): A failure here indicates a bug in the tracer, not the tracee.
// In particular it indicates that we either (1) calculated the effective
// address incorrectly, or (2) calculated the mask incorrectly.
if let Err(e) = uio::process_vm_readv(
self.tracee_pid,
&[uio::IoVec::from_mut_slice(&mut bytes)],
&[remote_iov],
) {
if self.tracer.debug_on_fault {
log::error!(
"Suspending the tracee ({}), detaching and exiting",
self.tracee_pid
);
ptrace::detach(self.tracee_pid, Some(signal::Signal::SIGSTOP))?;
}
return Err(e).with_context(|| format!("Fault: size: {:?}, address: {:x}", mask, addr));
} else {
log::debug!("fetched data bytes: {:?}", bytes);
}
Ok(bytes)
}
/// Given a string instruction (e.g., `MOVS`, `LODS`) variant, return its
/// expected memory mask (i.e., the size in bytes that one execution
/// reads and/or writes).
fn mask_from_str_instr(&self, instr: &Instruction) -> Result<MemoryMask> {
Ok(match instr.mnemonic() {
Mnemonic::Lodsb
| Mnemonic::Stosb
| Mnemonic::Movsb
| Mnemonic::Cmpsb
| Mnemonic::Scasb => MemoryMask::Byte,
Mnemonic::Lodsw
| Mnemonic::Stosw
| Mnemonic::Movsw
| Mnemonic::Cmpsw
| Mnemonic::Scasw => MemoryMask::Word,
Mnemonic::Lodsd
| Mnemonic::Stosd
| Mnemonic::Movsd
| Mnemonic::Cmpsd
| Mnemonic::Scasd => MemoryMask::DWord,
Mnemonic::Lodsq
| Mnemonic::Stosq
| Mnemonic::Movsq
| Mnemonic::Cmpsq
| Mnemonic::Scasq => MemoryMask::QWord,
_ => return Err(anyhow!("unknown mask for instruction: {:?}", instr.code())),
})
}
fn tracee_hints_stage1(&mut self, instr: &Instruction) -> Result<Vec<MemoryHint>> {
log::debug!("memory hints stage 1");
let mut hints = vec![];
let info = self
.info_factory
.info_options(&instr, InstructionInfoOptions::NO_REGISTER_USAGE)
.clone();
for used_mem in info.used_memory() {
// We model writebacks as two separate memory ops, so split them up here.
// Also: all conditional reads and writes are in fact real reads and writes,
// since we're single-stepping through REP'd instructions.
let ops: &[MemoryOp] = match used_mem.access() {
OpAccess::Read => &[MemoryOp::Read],
OpAccess::CondRead => &[MemoryOp::Read],
OpAccess::Write => &[MemoryOp::Write],
OpAccess::CondWrite => &[MemoryOp::Write],
OpAccess::ReadWrite => &[MemoryOp::Read, MemoryOp::Write],
OpAccess::ReadCondWrite => &[MemoryOp::Read, MemoryOp::Write],
op => return Err(anyhow!("unsupported memop: {:?}", op)),
};
let mask = match used_mem.memory_size() {
MemorySize::UInt8 | MemorySize::Int8 => MemoryMask::Byte,
MemorySize::UInt16 | MemorySize::Int16 => MemoryMask::Word,
MemorySize::UInt32 | MemorySize::Int32 => MemoryMask::DWord,
MemorySize::UInt64 | MemorySize::Int64 => MemoryMask::QWord,
MemorySize::Unknown => self.mask_from_str_instr(&instr)?,
size => {
if self.tracer.ignore_unsupported_memops {
log::warn!(
"unsupported memop size: {:?}: not generating a memory hint",
size
);
continue;
} else {
return Err(anyhow!("unsupported memsize: {:?}", size));
}
}
};
let addr = used_mem
.try_virtual_address(0, |reg, _, _| self.register_file.value(reg).ok())
.ok_or_else(|| anyhow!("effective address calculation failed"))?;
log::debug!("effective virtual addr: {:x}", addr);
for op in ops {
let data = match op {
MemoryOp::Read => self.tracee_data(addr, mask)?,
MemoryOp::Write => Vec::new(),
};
#[allow(clippy::redundant_field_names)]
hints.push(MemoryHint {
address: addr,
operation: *op,
mask: mask,
data: data,
});
}
log::debug!("{:?}", used_mem);
}
Ok(hints)
}
fn tracee_hints_stage2(&self, hints: &mut Vec<MemoryHint>) -> Result<()> {
log::debug!("memory hints stage 2");
// NOTE(ww): By default, recent-ish x86 CPUs execute MOVS and STOS
// in "fast string operation" mode. This can cause stores to not appear
// when we expect them to, since they can be executed out-of-order.
// The "correct" fix for this is probably to toggle the
// fast-string-enable bit (0b) in the IA32_MISC_ENABLE MSR, but we just sleep
// for a bit to give the CPU a chance to catch up.
// TODO(ww): Longer term, we should just model REP'd instructions outright.
std::thread::sleep(std::time::Duration::from_millis(2));
for hint in hints.iter_mut() {
if hint.operation != MemoryOp::Write {
continue;
}
let data = self.tracee_data(hint.address, hint.mask)?;
hint.data = data;
}
Ok(())
}
}
impl Iterator for Tracee<'_> {
type Item = Result<Step>;
fn next(&mut self) -> Option<Self::Item> {
if self.terminated {
None
} else {
Some(self.step())
}
}
}
#[derive(Debug)]
pub struct Tracer {
pub ignore_unsupported_memops: bool,
pub debug_on_fault: bool,
pub disable_aslr: bool,
pub bitness: u32,
pub target: Target,
}
impl From<clap::ArgMatches<'_>> for Tracer {
fn from(matches: clap::ArgMatches) -> Self {
let target = if let Some(pid) = matches.value_of("tracee-pid") {
Target::Process(Pid::from_raw(pid.parse().unwrap()))
} else {
Target::Program(
matches.value_of("tracee-name").map(Into::into).unwrap(),
matches
.values_of("tracee-args")
.map(|v| v.map(|a| a.to_string()).collect())
.unwrap_or_else(Vec::new),
)
};
#[allow(clippy::redundant_field_names)]
Self {
ignore_unsupported_memops: matches.is_present("ignore-unsupported-memops"),
debug_on_fault: matches.is_present("debug-on-fault"),
disable_aslr: matches.is_present("disable-aslr"),
bitness: matches.value_of("mode").unwrap().parse().unwrap(),
target: target,
}
}
}
impl Tracer {
pub fn trace(&self) -> Result<Tracee> {
let tracee_pid = match &self.target {
Target::Program(name, args) => {
let child = {
let mut cmd = Command::new(name);
cmd.args(args);
if self.disable_aslr {
cmd.personality(Persona::ADDR_NO_RANDOMIZE);
}
cmd.spawn_ptrace()?
};
log::debug!("spawned {} for tracing as child {}", name, child.id());
Pid::from_raw(child.id() as i32)
}
Target::Process(pid) => {
ptrace::attach(*pid)?;
*pid
}
};
// Our tracee is now live and ready to be traced, but in a stopped state.
// We set PTRACE_O_TRACEEXIT on it to make sure it stops right before
// finally exiting, giving us one last chance to do some inspection.
ptrace::setoptions(tracee_pid, ptrace::Options::PTRACE_O_TRACEEXIT)?;
Ok(Tracee::new(tracee_pid, &self))
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::path::PathBuf;
fn dummy_regs() -> RegisterFile {
RegisterFile {
rax: 0x9900aabbccddeeff,
rdi: 0x00000000feedface,
..Default::default()
}
}
fn build_test_program(program: &str) -> String {
let mut buf = {
let mut buf = PathBuf::from(env!("CARGO_MANIFEST_DIR"));
buf.push("test");
buf
};
let status = Command::new("make")
.arg("-C")
.arg(&buf)
.arg(program)
.status()
.expect(&format!("build failed: {}", program));
if !status.success() {
panic!("build failed: {}", program);
}
buf.push(program);
buf.into_os_string().into_string().unwrap()
}
fn test_program_tracer(program: &str) -> Tracer {
let target = Target::Program(program.into(), vec![]);
Tracer {
ignore_unsupported_memops: false,
debug_on_fault: false,
disable_aslr: true,
bitness: 32,
target: target,
}
}
#[test]
fn test_register_file_value() {
let regs = dummy_regs();
// Addressable registers always return their correctly masked values.
assert_eq!(regs.value(Register::AL).unwrap(), 0xff);
assert_eq!(regs.value(Register::AH).unwrap(), 0xee);
assert_eq!(regs.value(Register::AX).unwrap(), 0xeeff);
assert_eq!(regs.value(Register::EAX).unwrap(), 0xccddeeff);
assert_eq!(regs.value(Register::RAX).unwrap(), 0x9900aabbccddeeff);
// Segment registers always return a base address of 0.
assert_eq!(regs.value(Register::AL).unwrap(), 0xff);
assert_eq!(regs.value(Register::AH).unwrap(), 0xee);
assert_eq!(regs.value(Register::AX).unwrap(), 0xeeff);
assert_eq!(regs.value(Register::EAX).unwrap(), 0xccddeeff);
assert_eq!(regs.value(Register::RAX).unwrap(), 0x9900aabbccddeeff);
assert_eq!(regs.value(Register::SS).unwrap(), 0);
assert_eq!(regs.value(Register::CS).unwrap(), 0);
assert_eq!(regs.value(Register::DS).unwrap(), 0);
assert_eq!(regs.value(Register::ES).unwrap(), 0);
assert_eq!(regs.value(Register::FS).unwrap(), 0);
assert_eq!(regs.value(Register::GS).unwrap(), 0);
// Unaddressable and unsupported registers return an Err.
assert!(regs.value(Register::ST0).is_err());
}
macro_rules! trace_consistency_tests {
($($name:ident,)*) => {
$(
#[test]
fn $name() {
let program = build_test_program(concat!(stringify!($name), ".elf"));
let tracer = test_program_tracer(&program);
// TODO(ww): Don't collect these.
let trace1 = tracer
.trace()
.expect("spawn failed")
.collect::<Result<Vec<Step>>>()
.expect("trace failed");
let trace2 = tracer
.trace()
.expect("spawn failed")
.collect::<Result<Vec<Step>>>()
.expect("trace failed");
assert_eq!(trace1.len(), trace2.len());
for (step1, step2) in trace1.iter().zip(trace2.iter()) {
assert_eq!(step1, step2);
}
}
)*
}
}
trace_consistency_tests! {
memops,
stosb,
stosw,
stosd,
}
}