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
|
use std::fmt::Write;
use yaxpeax_arch::{AddressBase, LengthedInstruction};
use yaxpeax_arch::annotation::FieldDescription;
use yaxpeax_x86::long_mode::Opcode;
use yaxpeax_x86::long_mode::RegSpec;
use yaxpeax_x86::long_mode::InstDecoder;
use yaxpeax_x86::long_mode::Instruction;
use yaxpeax_x86::long_mode::InnerDescription;
use yaxpeax_arch::annotation::AnnotatingDecoder;
fn test_annotations(data: &[u8], expected: &'static str, checks: &[AnnotationCheck]) {
test_annotations_under(&InstDecoder::default(), data, expected, checks);
}
// pair up field descriptions and the check that matched them. we'll use this for
// reporting errors if checks don't match up.
#[derive(PartialEq, Eq, Copy, Clone)]
enum CheckResult {
Matched,
Failed,
Ignored,
}
impl CheckResult {
fn consumed_check(&self) -> bool {
*self != CheckResult::Ignored
}
}
struct MatchResult {
check: AnnotationCheck,
result: CheckResult,
}
#[derive(Clone)]
enum AnnotationCheck {
// does not match any description; intended to assert that there should be no extra annotations
// after the last check.
NoExtra,
Exact {
// check the reported annotation matches this description
desc: InnerDescription,
start_bit: u32,
end_bit: u32,
},
Approximate {
check: fn(&InnerDescription) -> bool,
start_bit: u32,
end_bit: u32,
}
}
impl std::fmt::Display for AnnotationCheck {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
match self {
AnnotationCheck::NoExtra => {
write!(f, "no further field descriptions expected")
}
AnnotationCheck::Exact { desc, start_bit, end_bit } => {
write!(f, "bit {}:{}; {}", start_bit, end_bit, desc)
}
AnnotationCheck::Approximate {
start_bit, end_bit, ..
} => {
write!(f, "bit {}:{}; (fn-based match)", start_bit, end_bit)
}
}
}
}
impl AnnotationCheck {
fn exact(start: u32, end: u32, desc: InnerDescription) -> AnnotationCheck {
AnnotationCheck::Exact {
desc,
start_bit: start,
end_bit: end,
}
}
fn approximate(start: u32, end: u32, check: fn(&InnerDescription) -> bool) -> AnnotationCheck {
AnnotationCheck::Approximate {
check,
start_bit: start,
end_bit: end,
}
}
fn no_extra() -> AnnotationCheck {
AnnotationCheck::NoExtra
}
fn matches(&self, actual_start: u32, actual_end: u32, actual_desc: InnerDescription) -> CheckResult {
match self {
AnnotationCheck::NoExtra => {
CheckResult::Failed
},
AnnotationCheck::Exact { start_bit, end_bit, desc } => {
let bits_match = *start_bit == actual_start && *end_bit == actual_end;
let desc_match = desc == &actual_desc;
let fail_anyway = match (desc, &actual_desc) {
// expect that there's only one `Number` field with a given name, so if the
// bits are wrong or the value is wrong, that's a guaranteed fail.
(InnerDescription::Number(expected_name, _), InnerDescription::Number(actual_name, _)) => {
if expected_name == actual_name {
true
} else {
false
}
}
// expect that there's only one opcode field. there won't be a second one that
// we might match on later.
(InnerDescription::Opcode(_), InnerDescription::Opcode(_)) => {
true
}
(_expected, _actual) => false
};
if (!bits_match && !desc_match) && !fail_anyway {
return CheckResult::Ignored;
}
if bits_match && desc_match {
CheckResult::Matched
} else {
CheckResult::Failed
}
},
AnnotationCheck::Approximate { start_bit, end_bit, check } => {
let bits_match = *start_bit == actual_start && *end_bit == actual_end;
let desc_match = check(&actual_desc);
if !bits_match && !desc_match {
return CheckResult::Ignored;
}
if bits_match && desc_match {
CheckResult::Matched
} else {
CheckResult::Failed
}
}
}
}
}
impl std::fmt::Display for CheckResult {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
let s = match self {
CheckResult::Matched => "\x1b[32mmatched\x1b[0m ",
CheckResult::Failed => "\x1b[31mfailed\x1b[0m ",
CheckResult::Ignored => "\x1b[33mignored\x1b[0m",
};
f.write_str(s)
}
}
fn test_annotations_under(decoder: &InstDecoder, data: &[u8], expected: &'static str, checks: &[AnnotationCheck]) {
let mut hex = String::new();
for b in data {
write!(hex, "{:02x}", b).unwrap();
}
let mut reader = yaxpeax_arch::U8Reader::new(data);
let mut sink = yaxpeax_arch::annotation::VecSink::new();
let mut inst = Instruction::default();
match decoder.decode_with_annotation(&mut inst, &mut reader, &mut sink) {
Ok(()) => {
#[cfg(feature = "fmt")]
let text = format!("{}", inst);
#[cfg(feature = "fmt")]
assert!(
text == expected,
"display error for {}:\n decoded: {:?} under decoder {}\n displayed: {}\n expected: {}\n",
hex,
inst,
decoder,
text,
expected
);
let mut matches: Vec<((u32, u32, InnerDescription), Option<MatchResult>)> = Vec::new();
let mut extra_checks: Vec<AnnotationCheck> = Vec::new();
sink.records.sort_by_key(|x| x.2.id());
let mut rec_iter = sink.records.iter();
let mut check_iter = checks.iter();
let mut check = check_iter.next();
let mut failed = false;
while let Some((bit_start, bit_end, desc)) = rec_iter.next().cloned() {
if let Some(curr_check) = check {
if let AnnotationCheck::NoExtra = curr_check {
failed = true;
}
let check_result = curr_check.matches(bit_start, bit_end, desc.desc().clone());
if check_result == CheckResult::Failed {
failed = true;
}
matches.push(((bit_start, bit_end, desc.desc().clone()), Some(MatchResult {
check: curr_check.clone(),
result: check_result
})));
if check_result.consumed_check() {
check = check_iter.next();
}
} else {
// no more checks, so we'll have passed the test at least. continue scooping up
// field descriptions into `matches` with no checks.
matches.push(((bit_start, bit_end, desc.desc().clone()), None));
}
}
while let Some(missed_check) = check {
check = check_iter.next();
if let AnnotationCheck::NoExtra = missed_check {
// "no extra" will be "missed" in that nothing matches it above. in the success
// case, it's a leftover check, and should be the only one remaining if the
// test is written correctly. so skip it here, and see if we've exhausted the
// list of checks..
continue;
}
extra_checks.push(missed_check.clone());
}
if extra_checks.len() > 0 {
failed = true;
}
if failed {
#[cfg(not(feature = "fmt"))]
eprintln!("[!] annotation check failed, enable the fmt feature for more info");
#[cfg(feature = "fmt")]
eprintln!("[!] annotation check for {}, `{}`, failed:", hex, inst);
#[cfg(feature = "fmt")]
for ((bit_start, bit_end, desc), check) in matches {
let mut desc = format!("bit {}:{}; {}", bit_start, bit_end, desc);
while desc.len() < 60 {
desc.push(' ');
}
desc.push(' ');
let comment = match check {
None => {
"\x1b[34mno check\x1b[0m".to_owned()
}
Some(MatchResult {
result,
check
}) => {
if result == CheckResult::Ignored {
result.to_string()
} else {
format!("{}{}", result, check)
}
}
};
eprintln!(" - {}{}", desc, comment);
}
#[cfg(feature = "fmt")]
for check in extra_checks {
eprintln!(" ! \x1b[31mextra check\x1b[0m: {}", check);
}
}
assert!(!failed);
// while we're at it, test that the instruction is as long, and no longer, than its
// input
assert_eq!((0u64.wrapping_offset(inst.len()).to_linear()) as usize, data.len(), "instruction length is incorrect, wanted instruction {}", expected);
},
Err(e) => {
cfg_if::cfg_if! {
if #[cfg(feature="fmt")] {
assert!(false, "decode error ({}) for {} under decoder {}:\n expected: {}\n", e, hex, decoder, expected);
} else {
// avoid the unused `e` warning
let _ = e;
assert!(false, "decode error (<non-fmt build>) for {} under decoder <non-fmt build>:\n expected: {}\n", hex, expected);
}
}
}
}
}
#[test]
#[cfg(feature = "fmt")]
fn test_modrm_decode() {
test_annotations(&[0xff, 0xc0], "inc eax", &[
AnnotationCheck::exact(11, 13, InnerDescription::Opcode(Opcode::INC)),
AnnotationCheck::approximate(0, 7, |desc| { desc.to_string().contains("ModRM_0xff_Ev") }),
AnnotationCheck::approximate(14, 15, |desc| {
desc.to_string().contains("mmm") &&
desc.to_string().contains("register number") &&
desc.to_string().contains("mod bits: 11")
}),
AnnotationCheck::exact(8, 10, InnerDescription::RegisterNumber("mmm", 0, RegSpec::eax())),
AnnotationCheck::no_extra(),
]);
test_annotations(&[0xc1, 0xe0, 0x03], "shl eax, 0x3", &[
AnnotationCheck::exact(11, 13, InnerDescription::Opcode(Opcode::SHL)),
AnnotationCheck::exact(16, 23, InnerDescription::Number("imm", 3)),
AnnotationCheck::approximate(0, 7, |desc| { desc.to_string().contains("ModRM_0xc1_Ev_Ib") }),
AnnotationCheck::approximate(14, 15, |desc| {
desc.to_string().contains("mmm") &&
desc.to_string().contains("register number") &&
desc.to_string().contains("mod bits: 11")
}),
AnnotationCheck::exact(8, 10, InnerDescription::RegisterNumber("mmm", 0, RegSpec::eax())),
AnnotationCheck::no_extra(),
]);
test_annotations(&[0x33, 0x08], "xor ecx, dword [rax]", &[
AnnotationCheck::exact(0, 7, InnerDescription::Opcode(Opcode::XOR)),
AnnotationCheck::approximate(0, 7, |desc| { desc.to_string() == "operand code `Gv_Ev`" }),
AnnotationCheck::approximate(7, 7, |desc| { desc.to_string().contains("operands begin") }),
AnnotationCheck::approximate(14, 15, |desc| {
desc.to_string().contains("memory operand is [reg]") &&
desc.to_string().contains("mod bits: 00")
}),
AnnotationCheck::exact(8, 10, InnerDescription::RegisterNumber("mmm", 0, RegSpec::rax())),
AnnotationCheck::exact(11, 13, InnerDescription::RegisterNumber("rrr", 1, RegSpec::ecx())),
AnnotationCheck::no_extra(),
]);
test_annotations(&[0x66, 0x0f, 0x38, 0x00, 0xc1], "pshufb xmm0, xmm1", &[
AnnotationCheck::exact(0, 7, InnerDescription::Misc("operand size override (to 16 bits)")),
AnnotationCheck::approximate(38, 39, |desc| {
desc.to_string().contains("mmm") &&
desc.to_string().contains("register number") &&
desc.to_string().contains("mod bits: 11")
}),
AnnotationCheck::exact(32, 34, InnerDescription::RegisterNumber("mmm", 1, RegSpec::ecx())),
AnnotationCheck::exact(35, 37, InnerDescription::RegisterNumber("rrr", 0, RegSpec::eax())),
AnnotationCheck::no_extra(),
]);
// modrm + rex.w
test_annotations(&[0x48, 0x33, 0x08], "xor rcx, qword [rax]", &[]);
test_annotations(&[0x48, 0x33, 0x20], "xor rsp, qword [rax]", &[]);
test_annotations(&[0x48, 0x33, 0x05, 0x78, 0x56, 0x34, 0x12], "xor rax, qword [rip + 0x12345678]", &[]);
// specifically sib with base == 0b101
// mod bits 00
test_annotations(&[0x42, 0x33, 0x34, 0x25, 0x20, 0x30, 0x40, 0x50], "xor esi, dword [r12 * 1 + 0x50403020]", &[]);
test_annotations(&[0x43, 0x33, 0x34, 0x25, 0x20, 0x30, 0x40, 0x50], "xor esi, dword [r12 * 1 + 0x50403020]", &[]);
// mod bits 01
test_annotations(&[0x42, 0x33, 0x74, 0x25, 0x20], "xor esi, dword [rbp + r12 * 1 + 0x20]", &[]);
test_annotations(&[0x43, 0x33, 0x74, 0x25, 0x20], "xor esi, dword [r13 + r12 * 1 + 0x20]", &[]);
// mod bits 10
test_annotations(&[0x42, 0x33, 0xb4, 0x25, 0x20, 0x30, 0x40, 0x50], "xor esi, dword [rbp + r12 * 1 + 0x50403020]", &[]);
test_annotations(&[0x43, 0x33, 0xb4, 0x25, 0x20, 0x30, 0x40, 0x50], "xor esi, dword [r13 + r12 * 1 + 0x50403020]", &[]);
}
|