use super::*;
use vlk_eval::eval;
use vlk_ir::ir::FunctionIr;
fn run(code: Vec<u8>, thumb: bool, registers: &[(u16, u64)], memory: &[(u64, u64)]) -> u64 {
let size = code.len() as u64;
let mut program = vlk_program::program::Program::new(Image::from_code(Isa::Arm32, 0, code));
program
.image
.arm_modes
.insert(0, if thumb { ArmMode::Thumb } else { ArmMode::Arm });
let mut ir = FunctionIr::single_block(Isa::Arm32, Vec::new());
ir.blocks = super::lift(
&program,
0,
program.image.read_vaddr(0, size).unwrap(),
&HashSet::new(),
&|_| Default::default(),
)
.unwrap();
let setup = eval::Setup {
seed: 0,
convention: eval::Convention {
arguments: &[0, 1, 2, 3],
clobbered: &[0, 1, 2, 3, 12, 14],
},
registers,
memory,
step_limit: 200,
};
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()
}
fn halves(words: &[u16]) -> Vec<u8> {
words.iter().flat_map(|word| word.to_le_bytes()).collect()
}
#[test]
fn the_high_word_of_a_signed_product_is_kept_with_and_without_rounding() {
for (left, right) in [
(0u32, 0u32),
(7, 0x9249_2493),
(0xffff_fff9, 0x9249_2493),
(0x7fff_ffff, 0x7fff_ffff),
(0x8000_0000, 0x8000_0000),
(0x8000_0000, 0x7fff_ffff),
(0xffff_ffff, 1),
(0x1234_5678, 0x8000_0001),
] {
let product = i64::from(left as i32) * i64::from(right as i32);
for (word, expected) in [
(0xe750_f110, (product >> 32) as u32),
(
0xe750_f130,
(product.wrapping_add(0x8000_0000) >> 32) as u32,
),
] {
let value = run(
words(&[word, 0xe12f_ff1e]),
false,
&[(0, u64::from(left)), (1, u64::from(right))],
&[],
);
assert_eq!(value, u64::from(expected), "{word:#x} {left:#x} {right:#x}");
}
}
}
#[test]
fn adr_uses_the_aligned_pc_and_encoded_direction() {
for (code, thumb, expected) in [
(words(&[0xe28f0010, 0xe12fff1e]), false, 24),
(words(&[0xe24f0010, 0xe12fff1e]), false, 0xffff_fff8),
(halves(&[0xbf00, 0xa000, 0x4770]), true, 4),
] {
assert_eq!(run(code.clone(), thumb, &[], &[]), expected);
let mut program =
vlk_program::program::Program::new(Image::from_code(Isa::Arm32, 0, code.clone()));
program
.image
.arm_modes
.insert(0, if thumb { ArmMode::Thumb } else { ArmMode::Arm });
let mut ir = FunctionIr::single_block(Isa::Arm32, Vec::new());
ir.blocks =
super::lift(&program, 0, &code, &HashSet::new(), &|_| Default::default()).unwrap();
crate::passes::simplify::simplify(&mut ir);
ir.name = Some("address_value".into());
let printed =
vlk_render::render::render(&ir, &[], &vlk_render::render::Symbols::default(), &[]);
crate::lift::atomic_tests::compile_run(
&format!(
"#include <stdint.h>\n{printed}\nint main(void) {{ return address_value() != {expected}ULL; }}"
),
&format!("arm32_adr_{expected}"),
);
}
}
#[test]
fn carry_arithmetic_sets_all_condition_flags() {
use std::fmt::Write as _;
let mut printed = String::from("#include <stdint.h>\n#include <stdbool.h>\n");
let mut checks = String::new();
for subtract in [false, true] {
for condition in 0..14u32 {
let name = format!("carry_flags_{}_{}", u8::from(subtract), condition);
let code = words(&[
0xe3530001,
if subtract { 0xe0d02001 } else { 0xe0b02001 },
0xe3a00000,
condition << 28 | 0x03a00001,
0xe12fff1e,
]);
let program =
vlk_program::program::Program::new(Image::from_code(Isa::Arm32, 0, code.clone()));
let mut ir = FunctionIr::single_block(Isa::Arm32, Vec::new());
ir.blocks =
super::lift(&program, 0, &code, &HashSet::new(), &|_| Default::default()).unwrap();
ir.name = Some(name.clone());
ir.params = [(0, "a"), (1, "b"), (3, "carry")]
.iter()
.map(|(index, name)| vlk_types::types::Param {
index: *index,
name: (*name).into(),
ty: vlk_types::types::CType::U32,
})
.collect();
crate::passes::simplify::simplify(&mut ir);
printed.push_str(&vlk_render::render::render(
&ir,
&[],
&vlk_render::render::Symbols::default(),
&[],
));
for a in [0u32, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX] {
for b in [0u32, 1, 0x7fff_ffff, 0x8000_0000, u32::MAX] {
for carry in [0u64, 1] {
let exact = if subtract {
i64::from(a as i32) - i64::from(b as i32) - (1 - carry as i64)
} else {
i64::from(a as i32) + i64::from(b as i32) + carry as i64
};
let result = exact as u32;
let negative = result >> 31 != 0;
let zero = result == 0;
let carried = if subtract {
u64::from(a) >= u64::from(b) + 1 - carry
} else {
u64::from(a) + u64::from(b) + carry > u64::from(u32::MAX)
};
let overflow = exact < i64::from(i32::MIN) || exact > i64::from(i32::MAX);
let expected = match condition {
0 => zero,
1 => !zero,
2 => carried,
3 => !carried,
4 => negative,
5 => !negative,
6 => overflow,
7 => !overflow,
8 => carried && !zero,
9 => !carried || zero,
10 => negative == overflow,
11 => negative != overflow,
12 => !zero && negative == overflow,
_ => zero || negative != overflow,
};
assert_eq!(
run(
code.clone(),
false,
&[(0, u64::from(a)), (1, u64::from(b)), (3, carry)],
&[]
),
u64::from(expected),
"{name}({a}, {b}, {carry})"
);
writeln!(
checks,
"if ({name}({a}u, {b}u, {carry}u) != {}) return 1;",
u8::from(expected)
)
.unwrap();
}
}
}
}
}
writeln!(printed, "int main(void) {{ {checks} return 0; }}").unwrap();
crate::lift::atomic_tests::compile_run(
&vlk_render::render::combine(&printed),
"arm32_carry_flags",
);
}
#[test]
fn arm_arithmetic_wraps_at_32_bits() {
for value in [0, 1, 0x7fff_ffff, 0xffff_ffff, u64::MAX] {
assert_eq!(
run(
words(&[0xe2800001, 0xe12fff1e]),
false,
&[(0, value)],
&[]
),
u64::from((value as u32).wrapping_add(1))
);
}
}
#[test]
fn predicated_writes_and_returns_use_the_comparison() {
for (a, b) in [(1, 3), (3, 1), (0x8000_0000, 1), (0xffff_ffff, 0)] {
assert_eq!(
run(
words(&[0xe1500001, 0xb1a00001, 0xe12fff1e]),
false,
&[(0, a), (1, b)],
&[]
),
if (a as i32) < (b as i32) { b } else { a }
);
}
for a in [0, 1, 0xffff_ffff] {
assert_eq!(
run(
words(&[0xe3500000, 0x012fff1e, 0xe2800001, 0xe12fff1e]),
false,
&[(0, a)],
&[]
),
if a == 0 {
0
} else {
u64::from((a as u32).wrapping_add(1))
}
);
}
let image = Image::from_code(Isa::Arm32, 0, words(&[0xb1a00001]));
let lines = super::disassembly(&image, image.read_vaddr(0, 4).unwrap(), 0, 1);
assert!(lines[0].text.contains("movlt"), "{lines:?}");
}
#[test]
fn conditional_moves_keep_addition_carry_and_overflow() {
for (a, b) in [
(0u32, 0u32),
(1, 2),
(u32::MAX, 1),
(0x7fff_ffff, 1),
(0x8000_0000, 0x8000_0000),
] {
let registers = [(0, u64::from(a)), (1, u64::from(b))];
let sum = a.wrapping_add(b);
let carry = u64::from(u64::from(a) + u64::from(b) > u64::from(u32::MAX));
let overflow = u64::from((a ^ sum) & (b ^ sum) & 0x8000_0000 != 0);
assert_eq!(
run(
words(&[0xe0902001, 0x23a00001, 0x33a00000, 0xe12fff1e]),
false,
®isters,
&[]
),
carry
);
assert_eq!(
run(
words(&[0xe0902001, 0x63a00001, 0x73a00000, 0xe12fff1e]),
false,
®isters,
&[]
),
overflow
);
}
}
#[test]
fn immediate_flag_results_test_bit_31() {
for (instruction, expected) in [(0xe3b00102, 1), (0xe3b0007f, 0), (0xe3b00000, 0)] {
let code = words(&[instruction, 0x43a00001, 0x53a00000, 0xe12fff1e]);
assert_eq!(run(code.clone(), false, &[], &[]), expected);
let program = vlk_program::program::Program::new(Image::from_code(Isa::Arm32, 0, code));
let mut ir = FunctionIr::single_block(Isa::Arm32, Vec::new());
ir.blocks = super::lift(
&program,
0,
program.image.read_vaddr(0, 16).unwrap(),
&HashSet::new(),
&|_| Default::default(),
)
.unwrap();
ir.name = Some("flag_sign".into());
let printed =
vlk_render::render::render(&ir, &[], &vlk_render::render::Symbols::default(), &[]);
crate::lift::atomic_tests::compile_run(
&format!(
"#include <stdint.h>\n{printed}\nint main(void) {{ return flag_sign() != {expected}; }}"
),
&format!("arm32_flag_sign_{instruction:x}"),
);
}
}
#[test]
fn thumb_register_shifts_use_eight_bit_counts_and_saturate() {
for amount in [0u32, 1, 31, 32, 33, 63, 64, 255, 256] {
let count = amount & 255;
let registers = [(0, 0x8000_0001), (1, u64::from(amount))];
let left = if count >= 32 {
0
} else {
0x8000_0001u32 << count
};
let right = (0x8000_0001u32 as i32 >> count.min(31)) as u32;
assert_eq!(
run(
halves(&[0x4088, 0x4770]),
true,
®isters,
&[]
),
u64::from(left)
);
assert_eq!(
run(
halves(&[0x4108, 0x4770]),
true,
®isters,
&[]
),
u64::from(right)
);
}
}
#[test]
fn thumb_it_and_branches_use_physical_addresses() {
for (a, b) in [(1, 3), (3, 1), (0xffff_ffff, 0)] {
assert_eq!(
run(
halves(&[0x4288, 0xbfb8, 0x4608, 0x4770]),
true,
&[(0, a), (1, b)],
&[]
),
if (a as i32) < (b as i32) { b } else { a }
);
}
assert_eq!(
run(
halves(&[0xe000, 0x2009, 0x2007, 0x4770]),
true,
&[],
&[]
),
7
);
}
#[test]
fn stack_saves_and_stack_arguments_are_four_bytes() {
assert_eq!(
run(
words(&[0xe92d4010, 0xe59d0008, 0xe8bd8010]),
false,
&[(13, 0x1000), (4, 7), (14, 0x2001)],
&[(eval::stack_top(Isa::Arm32), 0x12345678)]
),
0x12345678
);
assert_eq!(
run(
halves(&[0xb510, 0x9802, 0xbd10]),
true,
&[(13, 0x1000), (4, 7), (14, 0x2001)],
&[(eval::stack_top(Isa::Arm32), 0x12345678)]
),
0x12345678
);
}
#[test]
fn halfword_post_indexed_transfers_update_the_base() {
for instruction in [0xe0d100b2, 0xe0c100b2] {
assert_eq!(
run(
words(&[instruction, 0xe1a00001, 0xe12fff1e]),
false,
&[(0, 7), (1, 0x1000)],
&[(0x1000, 0x1234)]
),
0x1002
);
}
assert_eq!(
run(
words(&[0xe09100b2, 0xe1a00001, 0xe12fff1e]),
false,
&[(1, 0x1000), (2, 4)],
&[(0x1000, 0x1234)]
),
0x1004
);
for (instruction, expected) in [
(0xe0d100b2, 0x2236),
(0xe09100b2, 0x2238),
(0xe5b10004, 0x667c),
] {
assert_eq!(
run(
words(&[instruction, 0xe0800001, 0xe12fff1e]),
false,
&[(1, 0x1000), (2, 4)],
&[(0x1000, 0x0000_5678_0000_1234)]
),
expected
);
}
}
#[test]
fn calls_define_the_link_and_use_word_stack_slots() {
for thumb in [false, true] {
let code = if thumb {
halves(&[0xf000, 0xf800, 0x4770])
} else {
words(&[0xeb000000, 0xe12fff1e])
};
let mut program = vlk_program::program::Program::new(Image::from_code(Isa::Arm32, 0, code));
program
.image
.arm_modes
.insert(0, if thumb { ArmMode::Thumb } else { ArmMode::Arm });
let summary = |_| vlk_loader::loader::Summary {
arity: Some(4),
stack: 2,
..Default::default()
};
let bytes = program
.image
.read_vaddr(0, if thumb { 6 } else { 8 })
.unwrap();
let blocks = super::lift(&program, 0, bytes, &HashSet::new(), &summary).unwrap();
let statements: Vec<_> = blocks.iter().flat_map(|block| &block.stmts).collect();
assert!(statements.iter().any(|stmt| matches!(stmt, Stmt::Assign { dest, value: Expr::Const(value), .. } if dest.index == 14 && *value == if thumb { 5 } else { 4 })));
let args = statements
.iter()
.find_map(|stmt| match stmt {
Stmt::Call { args, .. } => args.as_ref(),
_ => None,
})
.unwrap();
assert_eq!(args.len(), 6);
for arg in &args[..4] {
assert!(matches!(arg, Expr::Reg { width: 32, .. }));
}
let stack_args = args[4..].iter().enumerate();
for (slot, arg) in stack_args {
let Expr::Load { addr, width: 4, .. } = arg else {
panic!("{arg:?}");
};
assert_eq!(
addr.as_ref(),
&Expr::bin(
BinOp::Add,
Expr::reg(13, 64),
Expr::constant(slot as u64 * 4)
)
);
}
}
}
#[test]
fn blx_reads_the_old_link_register_before_defining_the_return_address() {
for thumb in [false, true] {
let code = if thumb {
halves(&[0x47f0])
} else {
words(&[0xe12fff3e])
};
let size = code.len() as u64;
let mut program = vlk_program::program::Program::new(Image::from_code(Isa::Arm32, 0, code));
program
.image
.arm_modes
.insert(0, if thumb { ArmMode::Thumb } else { ArmMode::Arm });
let mut ir = FunctionIr::single_block(Isa::Arm32, Vec::new());
ir.blocks = super::lift(
&program,
0,
program.image.read_vaddr(0, size).unwrap(),
&HashSet::new(),
&|_| Default::default(),
)
.unwrap();
let setup = eval::Setup {
seed: 0,
convention: eval::Convention {
arguments: &[],
clobbered: &[],
},
registers: &[(14, 0x2001)],
memory: &[],
step_limit: 20,
};
let outcome = eval::run(&ir, &setup);
let eval::Outcome::Trap { calls, .. } = outcome else {
panic!("{outcome:?}");
};
assert_eq!(calls.len(), 1);
assert_eq!(calls[0].target, Some(0x2000));
assert!(
calls[0]
.arguments
.iter()
.all(|value| *value <= u64::from(u32::MAX))
);
}
}
#[test]
fn register_exchange_reaches_thumb_code_in_the_same_function() {
let mut program = vlk_program::program::Program::new(Image::from_code(
Isa::Arm32,
0,
words(&[0xe3a03009, 0xe12fff13, 0x47702007]),
));
program
.image
.arm_modes
.extend([(0, ArmMode::Arm), (8, ArmMode::Thumb)]);
let bytes = program.image.read_vaddr(0, 12).unwrap();
let mut ir = FunctionIr::single_block(Isa::Arm32, Vec::new());
ir.blocks = super::lift(&program, 0, bytes, &HashSet::new(), &|_| Default::default()).unwrap();
let setup = eval::Setup {
seed: 0,
convention: eval::Convention {
arguments: &[],
clobbered: &[],
},
registers: &[],
memory: &[],
step_limit: 20,
};
assert!(matches!(
eval::run(&ir, &setup),
eval::Outcome::Return { value: 7, .. }
));
crate::passes::simplify::simplify(&mut ir);
assert!(
!ir.blocks
.iter()
.flat_map(|block| &block.stmts)
.any(|stmt| matches!(stmt, Stmt::BrIndirect { .. }))
);
ir.name = Some("exchange".into());
let code = vlk_render::render::render(&ir, &[], &vlk_render::render::Symbols::default(), &[]);
assert!(code.contains("return 7;"), "{code}");
crate::lift::atomic_tests::compile_run(
&format!("#include <stdint.h>\n{code}\nint main(void) {{ return exchange() != 7; }}"),
"arm32_exchange",
);
}
#[test]
fn mapping_symbols_skip_data_and_switch_instruction_sets() {
let mut image = Image::from_code(Isa::Arm32, 0, words(&[0xea000000, 0xffff_ffff, 0x47702007]));
image
.arm_modes
.extend([(0, ArmMode::Arm), (4, ArmMode::Data), (8, ArmMode::Thumb)]);
let bytes = image.read_vaddr(0, 12).unwrap();
let (decoded, stop) = decode(&image, bytes, 0);
assert!(stop.is_none());
assert_eq!(decoded.iter().map(|d| d.pc).collect::<Vec<_>>(), [0, 8, 10]);
assert_eq!(image.arm_mode(1), ArmMode::Thumb);
}