use std::collections::HashSet;
use super::lift;
use vlk_base::target::Isa;
use vlk_eval::eval;
use vlk_ir::ir::visit::expr_width;
use vlk_ir::ir::{Expr, FunctionIr, Stmt};
use vlk_loader::loader::{Function, Image};
#[test]
fn flag_predecessors_keep_repeated_edges_and_entry_backedges() {
use std::collections::HashMap;
use vlk_ir::ir::Block;
let blocks = vec![
Block {
start: 0,
stmts: vec![Stmt::Switch {
index: Expr::reg(0, 64),
cases: vec![(0, 8), (1, 8), (2, 99)],
default: Some(16),
at: None,
}],
},
Block {
start: 8,
stmts: vec![Stmt::BrifFlags {
cond: vlk_ir::ir::Cond::Eq,
target: 0,
at: None,
}],
},
Block {
start: 16,
stmts: vec![Stmt::BrifFlags {
cond: vlk_ir::ir::Cond::Eq,
target: 0,
at: None,
}],
},
];
let predecessors = super::flag_predecessors(&blocks);
assert_eq!(predecessors, vec![vec![1, 2], vec![0, 0], vec![0, 1]]);
let flags = super::flags::Flags::logic(Expr::reg(7, 64));
let exits: HashMap<_, _> = blocks
.iter()
.map(|block| {
(
block.start,
super::Exit {
flags: Some(flags.clone()),
touched: true,
},
)
})
.collect();
for extra in [HashSet::new(), HashSet::from([8, 16])] {
let mut carried = super::carry_flags(&blocks, &exits, &extra, &predecessors);
assert!(!carried.entry.contains_key(&0));
assert_eq!(carried.entry.contains_key(&8), !extra.contains(&8));
assert_eq!(carried.entry.contains_key(&16), !extra.contains(&16));
super::carry_zero(
Isa::X86_64,
&blocks,
&exits,
&extra,
&predecessors,
&mut carried,
);
assert!(!carried.entry.contains_key(&0));
for address in &extra {
assert!(!carried.entry.contains_key(address));
}
let mut zero = super::Carried::default();
super::carry_zero(
Isa::X86_64,
&blocks,
&exits,
&extra,
&predecessors,
&mut zero,
);
assert!(!zero.entry.contains_key(&0));
assert_eq!(zero.entry.contains_key(&8), !extra.contains(&8));
assert_eq!(zero.entry.contains_key(&16), !extra.contains(&16));
}
}
fn returns(isa: Isa, code: Vec<u8>, registers: &[(u16, u64)]) -> u64 {
returns_with(isa, code, registers, &[])
}
fn returns_with(isa: Isa, code: Vec<u8>, registers: &[(u16, u64)], memory: &[(u64, u64)]) -> u64 {
let len = code.len() as u64;
let program = vlk_program::program::Program::new(Image::from_code(isa, 0, code));
let mut ir = FunctionIr::single_block(isa, Vec::new());
ir.blocks = lift(&program, 0, len, &HashSet::new()).expect("lifts");
let setup = eval::Setup {
seed: 0,
convention: eval::Convention {
arguments: &[],
clobbered: &[],
},
registers,
memory,
step_limit: 100,
};
match eval::run(&ir, &setup) {
eval::Outcome::Return { value, .. } => value,
other => panic!("{other:?}\n{}", ir.render()),
}
}
fn words(words: &[u32]) -> Vec<u8> {
words.iter().flat_map(|word| word.to_le_bytes()).collect()
}
#[test]
fn x86_zero_extension_preserves_each_high_byte_source() {
let originals = [
(0, 0xfedcba9876543210),
(1, 0x0123456789abcdef),
(2, 0x800000007fffffff),
(3, 0x7fffffff80000000),
];
for source in 0..4u8 {
for byte in 0..=255u64 {
let mut registers = originals;
registers[usize::from(source)].1 =
(registers[usize::from(source)].1 & !0xff00) | (byte << 8);
for word_destination in [false, true] {
let mut code = if word_destination {
vec![0x66]
} else {
Vec::new()
};
code.extend([0x0f, 0xb6, 0xc4 + source, 0xc3]);
let expected = if word_destination {
(registers[0].1 & !0xffff) | byte
} else {
byte
};
assert_eq!(
returns(Isa::X86_64, code, ®isters),
expected,
"source={source}, byte={byte}, word_destination={word_destination}"
);
}
}
}
}
#[test]
fn x86_zero_extension_keeps_low_byte_word_and_rex_sources() {
let registers = [
(0, 0xfedcba9876543210),
(1, 0x0123456789abcdef),
(2, 0x800000007fffffff),
(3, 0x7fffffff80000000),
(8, 0x80000000000000a5),
];
for source in 0..4u8 {
for (opcode, bits) in [(0xb6, 8), (0xb7, 16)] {
let expected = registers[usize::from(source)].1 & ((1u64 << bits) - 1);
let code = vec![0x0f, opcode, 0xc0 + source, 0xc3];
assert_eq!(returns(Isa::X86_64, code, ®isters), expected);
}
}
assert_eq!(
returns(
Isa::X86_64,
vec![0x40, 0xb4, 0x5a, 0x40, 0x0f, 0xb6, 0xc4, 0xc3],
®isters
),
0x5a
);
assert_eq!(
returns(Isa::X86_64, vec![0x41, 0x0f, 0xb6, 0xc0, 0xc3], ®isters),
0xa5
);
assert_eq!(
returns(Isa::X86_64, vec![0x48, 0x0f, 0xb7, 0xc1, 0xc3], ®isters),
0xcdef
);
}
#[test]
fn x86_sign_extension_preserves_each_high_byte_sign() {
let originals = [
(0, 0xfedcba9876543210),
(1, 0x0123456789abcdef),
(2, 0x800000007fffffff),
(3, 0x7fffffff80000000),
];
for source in 0..4u8 {
for byte in 0..=255u64 {
let mut registers = originals;
registers[usize::from(source)].1 =
(registers[usize::from(source)].1 & !0xff00) | (byte << 8);
let extended = byte as u8 as i8 as i64 as u64;
for word_destination in [false, true] {
let mut code = if word_destination {
vec![0x66]
} else {
Vec::new()
};
code.extend([0x0f, 0xbe, 0xc4 + source, 0xc3]);
let expected = if word_destination {
(registers[0].1 & !0xffff) | (extended & 0xffff)
} else {
extended & 0xffffffff
};
assert_eq!(
returns(Isa::X86_64, code, ®isters),
expected,
"source={source}, byte={byte}, word_destination={word_destination}"
);
}
}
}
}
#[test]
fn x86_sign_extension_keeps_low_word_dword_rex_and_memory_widths() {
for input in [
0,
0x7f,
0x80,
0xff,
0x7fff,
0x8000,
0xffff,
0x7fffffff,
0x80000000,
u64::MAX,
] {
let registers = [(0, 0xfedcba9876543210), (1, input), (7, 0x100), (8, input)];
for wide in [false, true] {
for (opcode, extended) in [
(0xbe, input as u8 as i8 as i64 as u64),
(0xbf, input as u16 as i16 as i64 as u64),
] {
let mut code = if wide { vec![0x48] } else { Vec::new() };
code.extend([0x0f, opcode, 0xc1, 0xc3]);
let expected = if wide {
extended
} else {
extended & 0xffffffff
};
assert_eq!(returns(Isa::X86_64, code, ®isters), expected);
}
}
let dword = input as u32 as i32 as i64 as u64;
assert_eq!(
returns(Isa::X86_64, vec![0x48, 0x63, 0xc1, 0xc3], ®isters),
dword
);
for (code, expected) in [
(
vec![0x41, 0x0f, 0xbe, 0xc0, 0xc3],
input as u8 as i8 as u32 as u64,
),
(
vec![0x49, 0x0f, 0xbe, 0xc0, 0xc3],
input as u8 as i8 as i64 as u64,
),
] {
assert_eq!(returns(Isa::X86_64, code, ®isters), expected);
}
for (code, expected) in [
(
vec![0x0f, 0xbe, 0x07, 0xc3],
input as u8 as i8 as u32 as u64,
),
(
vec![0x48, 0x0f, 0xbe, 0x07, 0xc3],
input as u8 as i8 as i64 as u64,
),
(
vec![0x48, 0x0f, 0xbf, 0x07, 0xc3],
input as u16 as i16 as i64 as u64,
),
(vec![0x48, 0x63, 0x07, 0xc3], dword),
] {
assert_eq!(
returns_with(Isa::X86_64, code, ®isters, &[(0x100, input)]),
expected
);
}
}
assert_eq!(
returns(
Isa::X86_64,
vec![0x40, 0xb4, 0x80, 0x40, 0x0f, 0xbe, 0xc4, 0xc3],
&[]
),
0xffffff80
);
}
#[test]
fn a_branch_tests_the_operands_a_flag_setting_write_replaced() {
let code = words(&[
0x6b090108, 0x5400006c, 0x52800000, 0xd65f03c0, 0x52800020, 0xd65f03c0,
]);
assert_eq!(returns(Isa::AArch64, code, &[(8, 5), (9, 3)]), 1);
let code = vec![
0xff, 0xc9, 0x75, 0x06, 0xb8, 0, 0, 0, 0, 0xc3, 0xb8, 1, 0, 0, 0, 0xc3,
];
assert_eq!(returns(Isa::X86_64, code, &[(1, 1)]), 0);
}
#[test]
fn flags_carry_into_a_block_every_path_reaches_with_them() {
let x86 = vec![
0x39, 0xf7, 0x75, 0x05, 0xb8, 5, 0, 0, 0, 0x0f, 0x9c, 0xc0, 0x0f, 0xb6, 0xc0, 0xc3,
];
let aarch64_code = words(&[
0x6b01_001f,
0x5400_0041,
0x5280_0022,
0x1a9f_a7e0,
0xd65f_03c0,
]);
for (a, b) in [(1u64, 2u64), (2, 1), (0xffff_ffff, 1), (3, 3)] {
let less = u64::from((a as u32 as i32) < (b as u32 as i32));
assert_eq!(returns(Isa::X86_64, x86.clone(), &[(7, a), (6, b)]), less);
assert_eq!(
returns(Isa::AArch64, aarch64_code.clone(), &[(0, a), (1, b)]),
less
);
}
}
fn memory_after(
code: Vec<u8>,
registers: &[(u16, u64)],
memory: &[(u64, u64)],
) -> std::collections::BTreeMap<u64, u8> {
let len = code.len() as u64;
let program = vlk_program::program::Program::new(Image::from_code(Isa::X86_64, 0, code));
let mut ir = FunctionIr::single_block(Isa::X86_64, Vec::new());
ir.blocks = lift(&program, 0, len, &HashSet::new()).expect("lifts");
let setup = eval::Setup {
seed: 0,
convention: eval::Convention {
arguments: &[],
clobbered: &[],
},
registers,
memory,
step_limit: 1000,
};
match eval::run(&ir, &setup) {
eval::Outcome::Return { memory, .. } => memory,
other => panic!("{other:?}\n{}", ir.render()),
}
}
#[test]
fn a_repeated_string_move_copies_as_many_elements_as_the_count() {
let source = [(0x1000, 0x0807_0605_0403_0201)];
let moved = memory_after(
vec![0xf3, 0xa4, 0xc3],
&[(6, 0x1000), (7, 0x2000), (1, 3)],
&source,
);
let copied: Vec<u8> = (0x2000..0x2004)
.filter_map(|addr| moved.get(&addr).copied())
.collect();
assert_eq!(copied, vec![1, 2, 3]);
let none = memory_after(
vec![0xf3, 0xa4, 0xc3],
&[(6, 0x1000), (7, 0x2000), (1, 0)],
&source,
);
assert!(!none.keys().any(|addr| (0x2000..0x2010).contains(addr)));
let stored = memory_after(
vec![0xf3, 0x48, 0xab, 0xc3],
&[(0, 0x1122_3344_5566_7788), (7, 0x3000), (1, 2)],
&[],
);
assert_eq!(
stored
.keys()
.filter(|addr| (0x3000..0x3018).contains(*addr))
.count(),
16
);
assert_eq!(stored.get(&0x3008), Some(&0x88));
}
#[test]
fn string_instructions_cover_widths_directions_counts_and_comparisons() {
for (size, prefix) in [(1u8, vec![]), (2, vec![0x66]), (4, vec![]), (8, vec![0x48])] {
for backward in [false, true] {
for count in [0, 1, 3] {
let first = if backward { 0x1010 } else { 0x1000 };
let target = if backward { 0x2010 } else { 0x2000 };
let memory = [
(0x1000, u64::MAX),
(0x1008, u64::MAX),
(0x1010, u64::MAX),
(0x2000, u64::MAX),
(0x2008, u64::MAX),
(0x2010, u64::MAX),
];
for opcode in [0xa4, 0xaa, 0xac, 0xa6, 0xae] {
for repeat in [None, Some(0xf3), Some(0xf2)] {
let mut code = vec![if backward { 0xfd } else { 0xfc }];
code.extend([0x39, 0xc0]);
code.extend(repeat);
code.extend(&prefix);
code.push(opcode + u8::from(size != 1));
code.extend([0x48, 0x89, 0xc8, 0xc3]);
let program = vlk_program::program::Program::new(Image::from_code(
Isa::X86_64,
0,
code.clone(),
));
let mut ir = FunctionIr::single_block(Isa::X86_64, Vec::new());
ir.blocks = lift(&program, 0, code.len() as u64, &HashSet::new())
.expect("string lifts");
let registers = [(0, u64::MAX), (1, count), (6, first), (7, target)];
let setup = eval::Setup {
seed: 0,
convention: eval::Convention {
arguments: &[],
clobbered: &[],
},
registers: ®isters,
memory: &memory,
step_limit: 2000,
};
let expected = if repeat.is_none() {
count
} else if matches!(opcode, 0xa6 | 0xae) && repeat == Some(0xf2) {
count.saturating_sub(1)
} else {
0
};
match eval::run(&ir, &setup) {
eval::Outcome::Return { value, .. } => assert_eq!(
value,
expected,
"size={size} backward={backward} count={count} opcode={opcode:x} repeat={repeat:?}\n{}",
ir.render()
),
other => panic!("{other:?}\n{}", ir.render()),
}
}
}
}
}
}
}
#[test]
fn string_sources_add_segment_bases_without_changing_pointer_offsets() {
for segment in [0x64, 0x65] {
let base = if segment == 0x64 {
vlk_arch::arch::x86::FS_BASE
} else {
vlk_arch::arch::x86::GS_BASE
};
let moved = memory_after(
vec![segment, 0xf3, 0xa4, 0x48, 0x89, 0x37, 0xc3],
&[(base, 0x1000), (6, 0x10), (7, 0x2000), (1, 1)],
&[(0x1010, 0x55)],
);
assert_eq!(moved.get(&0x2000), Some(&0x55));
assert_eq!(moved.get(&0x2001), Some(&0x11));
assert_eq!(moved.get(&0x2002), Some(&0));
}
}
#[test]
fn address_override_uses_ecx_and_preserves_registers_for_zero_count() {
for count in [0u64, 1, 3] {
let code = vec![0xfc, 0x67, 0xf3, 0xaa, 0x48, 0x89, 0xc8, 0xc3];
let initial = 0xffff_ffff_0000_0000 | count;
assert_eq!(
returns(Isa::X86_64, code, &[(0, 0), (1, initial), (7, 0x2000)]),
if count == 0 { initial } else { 0 }
);
}
}
#[test]
fn repeated_comparisons_leave_the_last_flags_and_keep_flags_for_zero_count() {
for repeat in [0xf3, 0xf2] {
for opcode in [0xa6, 0xae] {
for count in [0, 1, 3] {
for unequal in [false, true] {
let code = vec![
0xfc, 0x39, 0xc0, repeat, opcode, 0x0f, 0x94, 0xc0, 0x0f, 0xb6, 0xc0, 0xc3,
];
let program = vlk_program::program::Program::new(Image::from_code(
Isa::X86_64,
0,
code.clone(),
));
let mut ir = FunctionIr::single_block(Isa::X86_64, Vec::new());
ir.blocks = lift(&program, 0, code.len() as u64, &HashSet::new())
.expect("comparison lifts");
let registers = [(0, 1), (1, count), (6, 0x1000), (7, 0x2000)];
let memory = [
(0x1000, 0x010101),
(0x2000, if unequal { 0x020202 } else { 0x010101 }),
];
let setup = eval::Setup {
seed: 0,
convention: eval::Convention {
arguments: &[],
clobbered: &[],
},
registers: ®isters,
memory: &memory,
step_limit: 2000,
};
match eval::run(&ir, &setup) {
eval::Outcome::Return { value, .. } => assert_eq!(
value,
u64::from(count == 0 || !unequal),
"repeat={repeat:x} opcode={opcode:x} count={count} unequal={unequal}\n{}",
ir.render()
),
other => panic!("{other:?}\n{}", ir.render()),
}
}
}
}
}
}
#[test]
fn flags_of_different_kinds_do_not_carry_into_a_join() {
let code = vec![0x85, 0xff, 0x74, 0x02, 0x39, 0xf7, 0x0f, 0x9c, 0xc0, 0xc3];
let len = code.len() as u64;
let program = vlk_program::program::Program::new(Image::from_code(Isa::X86_64, 0, code));
let blocks = lift(&program, 0, len, &HashSet::new()).expect("lifts");
assert!(
blocks
.iter()
.flat_map(|block| &block.stmts)
.any(|stmt| matches!(stmt, Stmt::Unsupported { .. })),
"{blocks:?}"
);
}
#[test]
fn flags_of_tst_and_cmn_test_the_result() {
let tst = words(&[
0x6a01_001f,
0x5400_0060,
0x5280_0000,
0xd65f_03c0,
0x5280_0020,
0xd65f_03c0,
]);
assert_eq!(returns(Isa::AArch64, tst, &[(0, 6), (1, 9)]), 1);
let cmn = words(&[
0x3100_201f,
0x5400_006d,
0x5280_0000,
0xd65f_03c0,
0x5280_0020,
0xd65f_03c0,
]);
assert_eq!(returns(Isa::AArch64, cmn, &[(0, 0xffff_fff8)]), 1);
}
#[test]
fn an_unsigned_test_after_sub_compares_the_operands() {
let code = vec![
0x83, 0xef, 0x09, 0x77, 0x06, 0xb8, 0, 0, 0, 0, 0xc3, 0xb8, 1, 0, 0, 0, 0xc3,
];
assert_eq!(returns(Isa::X86_64, code, &[(7, 5)]), 0);
}
#[test]
fn a_call_through_a_register_keeps_its_target() {
let program = vlk_program::program::Program::new(Image::from_code(
Isa::X86_64,
0,
vec![0xff, 0xd0, 0xc3],
));
let blocks = lift(&program, 0, 3, &HashSet::new()).expect("lifts");
assert!(
matches!(
blocks[0].stmts.first(),
Some(Stmt::Call {
target: None,
through: Some(Expr::Reg { index: 0, .. }),
..
})
),
"{blocks:?}"
);
}
#[test]
fn every_bitfield_move_matches_the_architecture() {
fn ones(count: u64) -> u64 {
if count >= 64 {
u64::MAX
} else {
(1 << count) - 1
}
}
fn rotate_right(value: u64, amount: u64, size: u64) -> u64 {
if amount == 0 {
return value;
}
((value >> amount) | (value << (size - amount))) & ones(size)
}
fn reference(opc: u32, size: u64, immr: u64, imms: u64, old: u64, source: u64) -> u64 {
let (old, source) = (old & ones(size), source & ones(size));
let wmask = rotate_right(ones(imms + 1), immr, size);
let tmask = ones((imms.wrapping_sub(immr) & (size - 1)) + 1);
let rotated = rotate_right(source, immr, size);
let (top, bottom) = match opc {
0 => (
if (source >> imms) & 1 == 1 {
ones(size)
} else {
0
},
rotated & wmask,
),
1 => (old, (old & !wmask) | (rotated & wmask)),
_ => (0, rotated & wmask),
};
((top & !tmask) | (bottom & tmask)) & ones(size)
}
let ret = 0xd65f_03c0;
let values = [
(0xa5a5_5a5a_c3c3_3c3c, 0x0123_4567_89ab_cdef),
(0x5a5a_a5a5_3c3c_c3c3, 0xfedc_ba98_7654_3210),
(0, 0x8000_0000_8000_0001),
(u64::MAX, 0x7fff_ffff_7fff_fffe),
];
for sf in [0u32, 1] {
let size = if sf == 1 { 64 } else { 32 };
for opc in 0..3u32 {
for immr in 0..size {
for imms in 0..size {
let word = sf << 31
| opc << 29
| 0b100110 << 23
| sf << 22
| (immr as u32) << 16
| (imms as u32) << 10
| 1 << 5;
for (old, source) in values {
let actual =
returns(Isa::AArch64, words(&[word, ret]), &[(0, old), (1, source)]);
let expected = reference(opc, size, immr, imms, old, source);
assert_eq!(
actual, expected,
"{word:08x} opc={opc} sf={sf} immr={immr} imms={imms} old={old:x} source={source:x}"
);
}
}
}
}
}
}
#[test]
fn bitfield_moves_extract_and_insert() {
let ret = 0xd65f_03c0;
let ubfx = words(&[0x5304_1c20, ret]);
assert_eq!(returns(Isa::AArch64, ubfx, &[(1, 0xab)]), 0xa);
let sxtw = words(&[0x9340_7c20, ret]);
assert_eq!(returns(Isa::AArch64, sxtw, &[(1, 0xffff_ffff)]), u64::MAX);
let ubfiz = words(&[0x531f_0820, ret]);
assert_eq!(returns(Isa::AArch64, ubfiz, &[(1, 0xff)]), 0xe);
}
#[test]
fn integer_division_and_unscaled_loads_lift() {
let sdiv = words(&[0x1ac1_0c00, 0xd65f_03c0]);
let quotient = returns(Isa::AArch64, sdiv, &[(0, (-7i32) as u32 as u64), (1, 2)]);
assert_eq!(quotient as u32, (-3i32) as u32);
let ldur = words(&[0xb85f_c020, 0xd65f_03c0]);
assert_eq!(
returns_with(Isa::AArch64, ldur, &[(1, 0x1004)], &[(0x1000, 0x2a)]),
0x2a
);
let div = vec![0x89, 0xf8, 0x31, 0xd2, 0xf7, 0xf6, 0xc3];
assert_eq!(returns(Isa::X86_64, div, &[(7, 7), (6, 2)]), 3);
}
#[test]
fn moves_after_one_compare_all_test_it() {
let code = vec![
0xb9, 0x09, 0x00, 0x00, 0x00, 0x39, 0xf7, 0x0f, 0x4c, 0xc1, 0x0f, 0x4c, 0xc2, 0xc3,
];
assert_eq!(returns(Isa::X86_64, code, &[(7, 1), (6, 2), (2, 4)]), 4);
}
#[test]
fn vector_moves_copy_both_halves() {
let code = vec![
0x0f, 0x10, 0x07, 0x0f, 0x11, 0x06, 0x48, 0x8b, 0x46, 0x08, 0xc3,
];
let registers = [(7, 0x100), (6, 0x200)];
assert_eq!(
returns_with(Isa::X86_64, code, ®isters, &[(0x108, 0x55)]),
0x55
);
let code = vec![0x0f, 0x57, 0xc0, 0x66, 0x48, 0x0f, 0x7e, 0xc0, 0xc3];
assert_eq!(returns(Isa::X86_64, code, &[(18, 5)]), 0);
}
#[test]
fn rotations_and_byte_reversals_lift() {
let x = 0x1122_3344_5566_7788;
let rol = vec![0x48, 0x89, 0xf8, 0x48, 0xc1, 0xc0, 0x08, 0xc3];
assert_eq!(returns(Isa::X86_64, rol, &[(7, x)]), 0x2233_4455_6677_8811);
let ror = vec![0x89, 0xf8, 0xd3, 0xc8, 0xc3];
let rotated = |count| returns(Isa::X86_64, ror.clone(), &[(7, 0x1234_5678), (1, count)]);
assert_eq!(rotated(4), 0x8123_4567);
assert_eq!(rotated(0), 0x1234_5678);
let bswap = vec![0x48, 0x89, 0xf8, 0x48, 0x0f, 0xc8, 0xc3];
assert_eq!(
returns(Isa::X86_64, bswap, &[(7, x)]),
0x8877_6655_4433_2211
);
let shrd = vec![0x48, 0x89, 0xf8, 0x48, 0x0f, 0xac, 0xf0, 0x08, 0xc3];
assert_eq!(
returns(Isa::X86_64, shrd, &[(7, x), (6, 0xaabb)]),
0xbb11_2233_4455_6677
);
let ret = 0xd65f_03c0;
let run_aarch64 =
|word: u32, registers: &[(u16, u64)]| returns(Isa::AArch64, words(&[word, ret]), registers);
assert_eq!(run_aarch64(0x93c1_2020, &[(1, x)]), 0x8811_2233_4455_6677);
assert_eq!(run_aarch64(0xaac1_23e0, &[(1, x)]), 0x8811_2233_4455_6677);
assert_eq!(
run_aarch64(0x1ac2_2c20, &[(1, 0x1234_5678), (2, 36)]),
0x8123_4567
);
assert_eq!(run_aarch64(0xdac0_0c20, &[(1, x)]), 0x8877_6655_4433_2211);
assert_eq!(run_aarch64(0x5ac0_0420, &[(1, 0x1122_3344)]), 0x2211_4433);
assert_eq!(run_aarch64(0xaa22_0020, &[(1, 0xf0), (2, !0x0f)]), 0xff);
}
#[test]
fn exchanges_return_the_old_value() {
let xchg = vec![0xb8, 0x05, 0x00, 0x00, 0x00, 0x48, 0x97, 0xc3];
assert_eq!(returns(Isa::X86_64, xchg, &[(7, 9)]), 9);
let xadd = vec![
0xb8, 0x03, 0x00, 0x00, 0x00, 0xf0, 0x48, 0x0f, 0xc1, 0x07, 0xc3,
];
assert_eq!(
returns_with(Isa::X86_64, xadd, &[(7, 0x100)], &[(0x100, 10)]),
10
);
let cmpxchg = vec![
0xb8, 0x0a, 0x00, 0x00, 0x00, 0xf0, 0x48, 0x0f, 0xb1, 0x37, 0xc3,
];
let registers = [(7, 0x100), (6, 42)];
assert_eq!(
returns_with(Isa::X86_64, cmpxchg, ®isters, &[(0x100, 7)]),
7
);
let stored = vec![
0xb8, 0x0a, 0x00, 0x00, 0x00, 0xf0, 0x48, 0x0f, 0xb1, 0x37, 0x48, 0x8b, 0x07, 0xc3,
];
assert_eq!(
returns_with(Isa::X86_64, stored, ®isters, &[(0x100, 10)]),
42
);
let bt = vec![
0x31, 0xc0, 0x48, 0x0f, 0xba, 0xe7, 0x03, 0x0f, 0x92, 0xc0, 0xc3,
];
assert_eq!(returns(Isa::X86_64, bt.clone(), &[(7, 8)]), 1);
assert_eq!(returns(Isa::X86_64, bt, &[(7, 7)]), 0);
}
#[test]
fn a_division_by_rdx_divides_by_its_value_before_the_remainder() {
let code = vec![0x89, 0xf8, 0x99, 0xf7, 0xfa, 0xc3];
assert_eq!(returns(Isa::X86_64, code, &[(7, (-5i64) as u64)]), 5);
}
#[test]
fn byte_division_uses_ax_and_writes_al_and_ah() {
let unsigned = vec![0x66, 0xb8, 0x07, 0x01, 0xb7, 0x03, 0xf6, 0xf7, 0xc3];
assert_eq!(
returns(Isa::X86_64, unsigned, &[(0, 0x1234_5678_9abc_0000)]),
0x1234_5678_9abc_0257
);
let signed = vec![0x66, 0xb8, 0xf9, 0xfe, 0xb7, 0xfd, 0xf6, 0xff, 0xc3];
assert_eq!(
returns(Isa::X86_64, signed, &[(0, 0x1234_5678_9abc_0000)]),
0x1234_5678_9abc_fe57
);
}
#[test]
fn signed_division_requires_a_matching_extension_width() {
let code = [0x99, 0x48, 0xf7, 0xf9];
for (return_code, expected) in [
(vec![0xc3], 0x7fff_ffff_8000_0000),
(vec![0x48, 0x89, 0xd0, 0xc3], 0x8000_0000),
] {
assert_eq!(
returns(
Isa::X86_64,
[code.to_vec(), return_code].concat(),
&[(0, 0x8000_0000), (1, 0x2_0000_0000)]
),
expected
);
}
let code = [0x48, 0x99, 0xf7, 0xf9];
for (return_code, expected) in [(vec![0xc3], 715_827_882), (vec![0x89, 0xd0, 0xc3], 2)] {
assert_eq!(
returns(
Isa::X86_64,
[code.to_vec(), return_code].concat(),
&[(0, 0x8000_0000), (1, 3)]
),
expected
);
}
assert_eq!(
returns(
Isa::X86_64,
vec![0x66, 0x99, 0xf6, 0xfb, 0xc3],
&[(0, 0x0107), (3, 3)]
),
0x0257
);
}
#[test]
fn unsigned_division_preserves_high_dividend_bits_after_partial_zeroing() {
for zero in [vec![0x66, 0x31, 0xd2], vec![0x30, 0xd2]] {
for (return_code, expected) in [(vec![0xc3], 0x8000_0000), (vec![0x89, 0xd0, 0xc3], 7)] {
assert_eq!(
returns(
Isa::X86_64,
[zero.clone(), vec![0xf7, 0xf1], return_code].concat(),
&[(0, 7), (1, 0x2_0000), (2, 0x1_00ff)]
),
expected
);
}
}
}
#[test]
fn pop_reads_the_slot_push_wrote() {
assert_eq!(returns(Isa::X86_64, vec![0x53, 0x58, 0xc3], &[(3, 7)]), 7);
}
#[test]
fn a_branch_target_after_padding_starts_a_block() {
let program = vlk_program::program::Program::new(Image::from_code(
Isa::X86_64,
0,
vec![0xeb, 0x01, 0x90, 0xc3],
));
let blocks = lift(&program, 0, 4, &HashSet::new()).expect("lifts");
assert!(blocks.iter().any(|block| block.start == 3), "{:?}", blocks);
}
#[test]
fn a_store_of_the_zero_register_is_kept() {
let code = words(&[0xb9000bff, 0xd65f03c0]);
let program = vlk_program::program::Program::new(Image::from_code(Isa::AArch64, 0, code));
let blocks = lift(&program, 0, 8, &HashSet::new()).expect("lifts");
assert!(
matches!(
blocks[0].stmts.first(),
Some(Stmt::Store {
value: Expr::Const(0),
width: 4,
..
})
),
"{:?}",
blocks[0]
);
}
#[test]
fn a_cbnz_target_starts_a_block() {
let code = words(&[0xaa1f03e8, 0x38686809, 0x91000508, 0x35ffffc9, 0xd65f03c0]);
let program = vlk_program::program::Program::new(Image::from_code(Isa::AArch64, 0, code));
let blocks = lift(&program, 0, 20, &HashSet::new()).expect("lifts");
assert!(blocks.iter().any(|block| block.start == 4), "{blocks:?}");
}
#[test]
fn cbz_on_a_w_register_tests_the_low_half() {
let code = words(&[0x34000040, 0xd65f03c0, 0xd65f03c0]);
let program = vlk_program::program::Program::new(Image::from_code(Isa::AArch64, 0, code));
let blocks = lift(&program, 0, 12, &HashSet::new()).expect("lifts");
let Some(Stmt::Brif { lhs, .. }) = blocks[0].stmts.last() else {
panic!("a conditional branch: {:?}", blocks[0]);
};
assert_eq!(expr_width(lhs), Some(32), "{lhs:?}");
}
#[test]
fn shared_lifts_use_the_normalized_extra_target_set() {
let program = vlk_program::program::Program::new(Image::from_code(
Isa::X86_64,
0,
vec![0x89, 0xf8, 0x01, 0xf0, 0xc3],
));
let summaries = |_| vlk_loader::loader::Summary::default();
let plain = super::lift_shared(&program, 0, 5, &summaries).expect("plain lift");
let empty = super::lift_shared_with_targets(&program, 0, 5, &HashSet::new(), &summaries)
.expect("empty targets");
assert!(std::sync::Arc::ptr_eq(&plain, &empty));
let first = super::lift_shared_with_targets(&program, 0, 5, &HashSet::from([2, 4]), &summaries)
.expect("first targets");
let reordered =
super::lift_shared_with_targets(&program, 0, 5, &HashSet::from([4, 2]), &summaries)
.expect("reordered targets");
let different =
super::lift_shared_with_targets(&program, 0, 5, &HashSet::from([4]), &summaries)
.expect("different targets");
assert!(std::sync::Arc::ptr_eq(&first, &reordered));
assert!(!std::sync::Arc::ptr_eq(&plain, &first));
assert!(!std::sync::Arc::ptr_eq(&first, &different));
assert!(first.iter().any(|block| block.start == 2));
assert!(!different.iter().any(|block| block.start == 2));
let again = super::lift_shared(&program, 0, 5, &summaries).expect("plain cached lift");
assert!(std::sync::Arc::ptr_eq(&plain, &again));
}
#[test]
fn shared_target_lifts_recheck_callees_outside_the_cache_lock() {
let program = vlk_program::program::Program::new(Image::from_code(
Isa::X86_64,
0,
vec![0xe8, 0x1b, 0, 0, 0, 0xc3],
));
let summaries = |_| {
assert!(
!program.lifts.locked(),
"summary requested outside cache lock"
);
vlk_loader::loader::Summary::default()
};
let targets = HashSet::from([5]);
let first = super::lift_shared_with_targets(&program, 0, 6, &targets, &summaries)
.expect("returning callee");
let changed = super::lift_shared_with_targets(&program, 0, 6, &targets, &|_| {
vlk_loader::loader::Summary {
noreturn: true,
..Default::default()
}
})
.expect("changed callee");
assert!(!std::sync::Arc::ptr_eq(&first, &changed));
assert!(
changed
.iter()
.flat_map(|block| &block.stmts)
.any(|stmt| matches!(stmt, Stmt::Trap { .. }))
);
let again = super::lift_shared_with_targets(&program, 0, 6, &targets, &summaries)
.expect("retained previous version");
assert!(std::sync::Arc::ptr_eq(&first, &again));
}
#[test]
fn forgetting_summarized_lifts_keeps_the_one_without_summaries() {
let code = vec![0xe8, 0x1b, 0, 0, 0, 0xc3];
let size = code.len() as u64;
let program = vlk_program::program::Program::new(Image::from_code(Isa::X86_64, 0, code));
let unknown = |_| vlk_loader::loader::Summary::default();
let summaries = |_| vlk_loader::loader::Summary {
arity: Some(2),
..Default::default()
};
let plain = super::lift_shared(&program, 0, size, &unknown).unwrap();
let summarized = super::lift_shared(&program, 0, size, &summaries).unwrap();
program.lifts.forget_summarized(0, size, &HashSet::new());
let plain_again = super::lift_shared(&program, 0, size, &unknown).unwrap();
assert!(std::sync::Arc::ptr_eq(&plain, &plain_again));
let summarized_again = super::lift_shared(&program, 0, size, &summaries).unwrap();
assert!(!std::sync::Arc::ptr_eq(&summarized, &summarized_again));
assert_eq!(format!("{summarized:?}"), format!("{summarized_again:?}"));
program.lifts.clear();
let plain_anew = super::lift_shared(&program, 0, size, &unknown).unwrap();
assert!(!std::sync::Arc::ptr_eq(&plain, &plain_anew));
assert_eq!(format!("{plain:?}"), format!("{plain_anew:?}"));
}
#[test]
fn forgetting_a_function_drops_the_lift_without_summaries_too() {
let code = vec![0xe8, 0x1b, 0, 0, 0, 0xc3];
let size = code.len() as u64;
let program = vlk_program::program::Program::new(Image::from_code(Isa::X86_64, 0, code));
let unknown = |_| vlk_loader::loader::Summary::default();
let plain = super::lift_shared(&program, 0, size, &unknown).unwrap();
program.lifts.forget(0, size + 1, &HashSet::new());
let kept = super::lift_shared(&program, 0, size, &unknown).unwrap();
assert!(std::sync::Arc::ptr_eq(&plain, &kept));
program.lifts.forget(0, size, &HashSet::new());
let anew = super::lift_shared(&program, 0, size, &unknown).unwrap();
assert!(!std::sync::Arc::ptr_eq(&plain, &anew));
assert_eq!(format!("{plain:?}"), format!("{anew:?}"));
}
#[test]
fn caller_analysis_retains_the_lift_without_callee_summaries() {
for (isa, code) in [
(Isa::X86_64, vec![0xe8, 0x1b, 0, 0, 0, 0xc3]),
(Isa::I386, vec![0xe8, 0x1b, 0, 0, 0, 0xc3]),
(Isa::AArch64, vec![0x08, 0, 0, 0x94, 0xc0, 0x03, 0x5f, 0xd6]),
(Isa::Arm32, vec![0x06, 0, 0, 0xeb, 0x1e, 0xff, 0x2f, 0xe1]),
(Isa::RiscV64, vec![0xef, 0x00, 0xc0, 0x01, 0x67, 0x80, 0, 0]),
(
Isa::Mips32,
vec![6, 0, 0x11, 0x04, 0, 0, 0, 0, 8, 0, 0xe0, 0x03, 0, 0, 0, 0],
),
] {
let size = code.len() as u64;
let program = vlk_program::program::Program::new(Image::from_code(isa, 0, code));
let unknown = |_| vlk_loader::loader::Summary::default();
let first = super::lift_shared(&program, 0, size, &unknown).unwrap();
for arity in 0..5 {
let summaries = |_| vlk_loader::loader::Summary {
arity: Some(arity),
..Default::default()
};
let cached = super::lift_shared(&program, 0, size, &summaries).unwrap();
assert!(!std::sync::Arc::ptr_eq(&first, &cached), "{isa}");
let uncached =
super::lift_with(&program, 0, size, &HashSet::new(), &summaries).unwrap();
assert_eq!(format!("{cached:?}"), format!("{uncached:?}"));
}
let again = super::lift_shared(&program, 0, size, &unknown).unwrap();
assert!(std::sync::Arc::ptr_eq(&first, &again), "{isa}");
assert!(program.lifts.most_kept() <= vlk_program::program::KEPT_LIFTS);
}
}
fn first_call(
bytes: Vec<u8>,
format: vlk_base::target::Format,
summary: vlk_loader::loader::Summary,
) -> (vlk_types::types::CallKind, Option<Vec<Expr>>) {
let len = bytes.len() as u64;
let mut program = vlk_program::program::Program::new(Image::from_code(Isa::X86_64, 0, bytes));
program.image.format = format;
program.image.functions.insert(
32,
Function {
addr: 32,
size: None,
size_estimated: false,
name: None,
aliases: Vec::new(),
library: None,
sources: Vec::new(),
},
);
let blocks = super::lift_shared(&program, 0, len, &|_| summary).unwrap();
let Some(Stmt::Call { kind, args, .. }) = blocks
.iter()
.flat_map(|block| &block.stmts)
.find(|stmt| matches!(stmt, Stmt::Call { .. }))
else {
panic!("a call");
};
(*kind, args.clone())
}
#[test]
fn x86_calls_jumps_and_syscalls_keep_their_kind() {
use vlk_types::types::CallKind;
for (bytes, expected) in [
(vec![0xe8, 0x1b, 0, 0, 0, 0xc3], CallKind::Invoke),
(vec![0xe9, 0x1b, 0, 0, 0], CallKind::Tail),
(vec![0x0f, 0x05, 0xc3], CallKind::Syscall),
] {
let (kind, _) = first_call(bytes, vlk_base::target::Format::Elf, Default::default());
assert_eq!(kind, expected);
}
}
#[test]
fn unused_integer_positions_do_not_clear_floating_inputs() {
let summary = vlk_loader::loader::Summary {
arity: Some(1),
floats: Some(2),
inputs: Some(Default::default()),
..Default::default()
};
let (_, args) = first_call(
vec![0xe8, 0x1b, 0, 0, 0, 0xc3],
vlk_base::target::Format::Elf,
summary,
);
assert_eq!(
args,
Some(vec![
Expr::constant(0),
Expr::reg(18, 64),
Expr::reg(20, 64)
])
);
}
#[test]
fn tail_call_stack_arguments_are_read_past_the_return_address() {
for (format, count, invoke_offset, tail_offset) in [
(vlk_base::target::Format::Elf, 6, 0, 8),
(vlk_base::target::Format::Pe, 4, 32, 40),
] {
for (opcode, expected) in [(0xe8, invoke_offset), (0xe9, tail_offset)] {
let summary = vlk_loader::loader::Summary {
arity: Some(count),
stack: 1,
..Default::default()
};
let (_, args) = first_call(vec![opcode, 0x1b, 0, 0, 0, 0xc3], format, summary);
let args = args.expect("known arguments");
assert_eq!(args.len(), count + 1);
let wanted = Expr::Load {
addr: Box::new(Expr::bin(
vlk_ir::ir::BinOp::Add,
Expr::reg(4, 64),
Expr::Const(expected),
)),
width: 8,
signed: false,
};
assert_eq!(args.last(), Some(&wanted), "{opcode:#x}");
}
}
}