use std::sync::Arc;
use std::sync::atomic::{AtomicUsize, Ordering};
use vlk_base::target::Isa;
use vlk_loader::loader::{Function, Image, Summary};
#[test]
fn dependent_parts_run_once_after_all_their_callees() {
let pool = rayon::ThreadPoolBuilder::new()
.num_threads(4)
.build()
.unwrap();
let callees = [vec![], vec![], vec![0, 1], vec![0], vec![2, 3], vec![4]];
let finished: Vec<AtomicUsize> = (0..callees.len()).map(|_| AtomicUsize::new(0)).collect();
let pending = super::PendingParts {
waiting: callees
.iter()
.map(|calls| AtomicUsize::new(calls.len()))
.collect(),
dependents: vec![vec![2, 3], vec![2], vec![4], vec![4], vec![5], vec![]],
work: |index: usize| {
for &callee in &callees[index] {
assert_eq!(finished[callee].load(Ordering::Acquire), 1);
}
assert_eq!(finished[index].fetch_add(1, Ordering::Release), 0);
},
};
pool.scope(|scope| {
scope.spawn(|scope| pending.run(scope, 0));
scope.spawn(|scope| pending.run(scope, 1));
});
for count in finished {
assert_eq!(count.into_inner(), 1);
}
}
fn image(words: &[u32]) -> Image {
let code: Vec<_> = words.iter().flat_map(|word| word.to_le_bytes()).collect();
let size = code.len() as u64;
let mut image = Image::from_code(Isa::AArch64, 0, code);
image.functions.insert(
0,
Function {
addr: 0,
size: Some(size),
size_estimated: false,
name: Some("exception_test".to_owned()),
aliases: Vec::new(),
library: None,
sources: Vec::new(),
},
);
image
}
#[test]
fn summary_body_splits_exception_boundaries_and_agrees_with_main_stack_recovery() {
let mut program = vlk_program::program::Program::new(image(&[
0x94000010, 0xf90003ff, 0x14000002, 0xd503201f, 0xf94003e0, 0xd65f03c0,
]));
program.image.set_landing_pad(12, vec![(0, 4)]);
let summaries = |_| Summary::default();
let blocks = super::body(&program, 0, &summaries).expect("summary body");
for start in [4, 12, 16] {
assert!(
blocks.iter().any(|block| block.start == start),
"{blocks:?}"
);
}
let first = &blocks[0];
assert!(matches!(
first.stmts.last(),
Some(vlk_ir::ir::Stmt::Call { .. })
));
let (summary, seen) = super::compute(&program, 0, &summaries, None, false);
let seen = seen.expect("recovered summary");
let signature = &seen.signature;
let repeated = super::body(&program, 0, &summaries).expect("cached exception body");
assert!(Arc::ptr_eq(&blocks, &repeated));
let (_, repeated_seen) = super::compute(&program, 0, &summaries, Some(&seen), false);
assert!(Arc::ptr_eq(
signature,
&repeated_seen.expect("cached signature").signature
));
assert_eq!(signature.stack, vec![0]);
assert_eq!(summary.stack, 1);
let main =
super::super::lift_function(&program, &program.image.functions[&0]).expect("main lift");
assert_eq!(
main.ir
.stack_params
.iter()
.map(|param| param.offset)
.collect::<Vec<_>>(),
signature.stack
);
program.image.set_landing_pad(12, vec![(0, 8)]);
let changed = super::body(&program, 0, &summaries).expect("different exception boundaries");
assert!(!Arc::ptr_eq(&blocks, &changed));
assert!(changed.iter().any(|block| block.start == 8));
}
#[test]
fn summary_body_without_exceptions_keeps_the_shared_lift() {
let program = vlk_program::program::Program::new(image(&[0xd65f03c0]));
let summaries = |_| Summary::default();
let first = super::body(&program, 0, &summaries).expect("first body");
let second = super::body(&program, 0, &summaries).expect("second body");
assert!(Arc::ptr_eq(&first, &second));
}
#[test]
fn summaries_prepared_together_are_those_asked_for_one_by_one() {
for fixture in ["cpp_virtual_x64.elf", "calls_a64.elf", "go_probe"] {
let path = std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../.."))
.join("tests/fixtures")
.join(fixture);
let one_by_one = vlk::service::Binary::open(&path).expect("fixture");
for &addr in one_by_one.image().functions.keys() {
super::summary(one_by_one.program(), addr);
}
let summaries = |binary: &vlk::service::Binary| {
let summaries = binary.program().summaries.read().expect("summaries lock");
summaries
.iter()
.map(|(addr, summary)| (*addr, *summary))
.collect::<std::collections::BTreeMap<_, _>>()
};
for bodies in [super::Bodies::Kept, super::Bodies::Dropped] {
let together = vlk::service::Binary::open(&path).expect("fixture");
super::prepare(together.program(), None, bodies).expect("no deadline");
assert!(!summaries(&together).is_empty(), "{fixture}");
assert_eq!(summaries(&together), summaries(&one_by_one), "{fixture}");
}
}
}
#[test]
fn landing_pads_of_an_extent_are_those_a_scan_of_all_finds() {
let mut image = image(&[0xd65f03c0]);
let pads: [(u64, &[(u64, u64)]); 6] = [
(0x10, &[(0, 4), (40, 44)]),
(0x18, &[(8, 8)]),
(0x30, &[(0, 100)]),
(0x50, &[(20, 24), (24, 28)]),
(0x90, &[(60, 64)]),
(0x200, &[(30, 20)]),
];
for (pad, sites) in pads {
image.set_landing_pad(pad, sites.to_vec());
}
for start in (0..0x220).step_by(4) {
for length in [0, 4, 8, 40, 0x100] {
let extent = start..start + length;
let scanned: Vec<_> = image
.landing_pads
.iter()
.filter(|(pad, sites)| {
extent.contains(*pad)
|| sites
.iter()
.any(|(from, to)| from < to && extent.start < *to && *from < extent.end)
})
.map(|(&pad, sites)| (pad, sites.clone()))
.collect();
assert_eq!(image.landing_pads_of(extent.clone()), scanned, "{extent:?}");
}
}
}
#[test]
fn main_and_summary_keep_metadata_for_an_outside_landing_pad() {
let mut program = vlk_program::program::Program::new(image(&[
0x94000010, 0xf90003ff, 0x14000002, 0xd503201f, 0xf94003e0, 0xd65f03c0,
]));
program.image.set_landing_pad(0x100, vec![(0, 4)]);
let pads = program.image.landing_pads_of(0..24);
assert_eq!(pads, vec![(0x100, vec![(0, 4)])]);
assert_eq!(
super::super::exceptions::exception_starts(&pads, 0..24),
std::collections::HashSet::from([4])
);
let (_, seen) = super::compute(&program, 0, &|_| Summary::default(), None, false);
let signature = seen.expect("summary with missing pad").signature;
assert_eq!(signature.stack, vec![0]);
let main = super::super::lift_function(&program, &program.image.functions[&0])
.expect("main with missing pad");
assert_eq!(
main.ir
.stack_params
.iter()
.map(|param| param.offset)
.collect::<Vec<_>>(),
signature.stack
);
}
#[test]
fn summary_signature_cache_checks_ranges_even_when_lift_targets_are_unchanged() {
let mut program = vlk_program::program::Program::new(image(&[
0x94000020, 0xf90003ff, 0x14000001, 0x9400001d, 0x14000003, 0xd503201f, 0x14000001,
0xf94003e0, 0xd65f03c0,
]));
program.image.set_landing_pad(20, vec![(12, 16)]);
let summaries = |_| Summary::default();
let (_, before) = super::compute(&program, 0, &summaries, None, false);
let before = before.expect("late-call range");
assert!(before.signature.stack.is_empty());
program.image.set_landing_pad(20, vec![(0, 16)]);
let (_, after) = super::compute(&program, 0, &summaries, Some(&before), false);
let after = after.expect("expanded protected range");
assert!(Arc::ptr_eq(&before.blocks, &after.blocks));
assert!(!Arc::ptr_eq(&before.signature, &after.signature));
assert_eq!(after.signature.stack, vec![0]);
}
#[test]
fn raw_stack_summary_agrees_with_callee_and_caller_inputs() {
use vlk_ir::ir::{BinOp, Expr, Stmt};
use vlk_types::types::Convention;
let fixture = std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../.."))
.join("tests/fixtures/go_probe");
let mut binary = vlk::service::Binary::open(&fixture).expect("fixture");
let callee = 0x461c80;
let caller = 0x403b40;
{
let program = binary.program();
assert_eq!(
crate::lift::convention_of(&program.image, callee),
Convention::GoAbi0
);
let summary = super::summary(program, callee);
assert_eq!(summary.stack, 1);
assert_eq!(summary.stack_widths[0], 0);
let lookup = |target| super::summary(program, target);
let raw = super::body(program, callee, &lookup).expect("raw callee");
assert!(
raw.iter()
.any(|block| matches!(block.stmts.last(), Some(Stmt::BrIndirect { .. })))
);
let raw = super::body(program, caller, &lookup).expect("raw caller");
let arguments = raw
.iter()
.flat_map(|block| &block.stmts)
.find_map(|stmt| match stmt {
Stmt::Call {
target: Some(target),
args: Some(args),
..
} if *target == callee => Some(args),
_ => None,
})
.expect("call arguments");
assert_eq!(
arguments,
&vec![Expr::Load {
addr: Box::new(Expr::bin(BinOp::Add, Expr::reg(4, 64), Expr::Const(0))),
width: 8,
signed: false,
}]
);
}
let full = binary.analysis(callee, None).expect("callee analysis");
assert_eq!(full.ir.stack_params.len(), 1);
assert_eq!(full.ir.stack_params[0].offset, 8);
assert_eq!(full.ir.stack_params[0].size, 8);
assert_eq!(super::summary(binary.program(), callee).stack, 1);
let caller = binary.analysis(caller, None).expect("caller analysis");
let arguments = caller
.ir
.blocks
.iter()
.flat_map(|block| &block.stmts)
.find_map(|stmt| match stmt {
Stmt::Call {
target: Some(target),
args: Some(args),
..
} if *target == callee => Some(args),
_ => None,
})
.expect("analyzed call arguments");
assert_eq!(
arguments.as_slice(),
&[Expr::bin(
BinOp::Add,
Expr::reg(4, 64),
Expr::Const((-24_i64) as u64),
)]
);
}
#[test]
fn known_no_return_runtime_summary_stops_call_graph_walk() {
let fixture = std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../.."))
.join("tests/fixtures/go_probe");
let program = vlk_program::program::Program::new(crate::lift::load(&fixture).expect("fixture"));
let divmod = program
.image
.functions
.iter()
.find_map(|(&addr, function)| {
(function.name.as_deref() == Some("main.divmod")).then_some(addr)
})
.expect("main.divmod");
let summary = super::summary(&program, divmod);
assert_eq!(summary.arity, Some(2));
assert_eq!(summary.floats, Some(0));
assert_eq!(summary.stack, 0);
assert_eq!(summary.clobbers.map(|registers| registers.0), Some(13));
assert!(!summary.noreturn);
assert_eq!(program.summaries.read().expect("summaries lock").len(), 2);
}
#[test]
fn known_print_helper_summary_uses_the_go_register_clobbers() {
let fixture = std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../.."))
.join("tests/fixtures/go_probe");
let program = vlk_program::program::Program::new(crate::lift::load(&fixture).expect("fixture"));
let printlock = program
.image
.functions
.iter()
.find_map(|(&addr, function)| {
(function.name.as_deref() == Some("runtime.printlock")).then_some(addr)
})
.expect("runtime.printlock");
let summary = super::summary(&program, printlock);
let clobbers: vlk_types::types::Registers =
crate::lift::convention_of(&program.image, printlock)
.clobbered()
.iter()
.copied()
.collect();
assert_eq!(summary.arity, Some(0));
assert_eq!(summary.floats, Some(0));
assert_eq!(summary.clobbers, Some(clobbers));
assert_eq!(program.summaries.read().expect("summaries lock").len(), 1);
}
#[test]
fn morestack_summary_uses_its_known_stack_argument() {
let fixture = std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../.."))
.join("tests/fixtures/go_probe");
let program = vlk_program::program::Program::new(crate::lift::load(&fixture).expect("fixture"));
let morestack = program
.image
.functions
.iter()
.find_map(|(&addr, function)| {
(function.name.as_deref() == Some("runtime.morestack_noctxt")).then_some(addr)
})
.expect("runtime.morestack_noctxt");
assert!(program.image.go_argument_sizes.get().is_some());
let summary = super::summary(&program, morestack);
assert_eq!(summary.arity, Some(0));
assert_eq!(summary.floats, Some(0));
assert_eq!(summary.stack, 1);
assert_eq!(
summary.clobbers.map(|registers| registers.0),
Some(1u128 << vlk_arch::arch::x86::RDX)
);
assert!(summary.noreturn);
assert_eq!(program.summaries.read().expect("summaries lock").len(), 1);
}
#[test]
fn known_unlock_summary_keeps_signature_and_clobbers_separate() {
let fixture = std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../.."))
.join("tests/fixtures/go_probe");
let program = vlk_program::program::Program::new(crate::lift::load(&fixture).expect("fixture"));
let unlock = program
.image
.functions
.iter()
.find_map(|(&addr, function)| {
(function.name.as_deref() == Some("runtime.unlock2")).then_some(addr)
})
.expect("runtime.unlock2");
let summary = super::summary(&program, unlock);
let prototype = vlk_prototypes::prototypes::runtime("runtime.unlock2").expect("prototype");
let clobbers: vlk_types::types::Registers = crate::lift::convention_of(&program.image, unlock)
.clobbered()
.iter()
.copied()
.collect();
assert_eq!(summary.arity, Some(1));
assert_eq!(summary.pointers, 0);
assert_eq!(prototype.pointers(), 1);
assert_eq!(summary.clobbers, Some(clobbers));
assert_eq!(program.summaries.read().expect("summaries lock").len(), 1);
}
#[test]
fn mcall_summary_uses_the_runtime_function_argument() {
let fixture = std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../.."))
.join("tests/fixtures/go_probe");
let program = vlk_program::program::Program::new(crate::lift::load(&fixture).expect("fixture"));
let mcall = program
.image
.functions
.iter()
.find_map(|(&addr, function)| {
(function.name.as_deref() == Some("runtime.mcall")).then_some(addr)
})
.expect("runtime.mcall");
let summary = super::summary(&program, mcall);
let prototype = vlk_prototypes::prototypes::runtime("runtime.mcall").expect("prototype");
let clobbers: vlk_types::types::Registers = crate::lift::convention_of(&program.image, mcall)
.clobbered()
.iter()
.copied()
.collect();
assert_eq!(summary.arity, Some(1));
assert_eq!(summary.pointers, 0);
assert_eq!(prototype.pointers(), 1);
assert_eq!(summary.clobbers, Some(clobbers));
assert!(!summary.noreturn);
assert!(!summary.narrow_return);
}
#[test]
fn runtime_summaries_are_shared_between_requests() {
let fixture = std::path::Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../.."))
.join("tests/fixtures/go_probe");
let program = vlk_program::program::Program::new(crate::lift::load(&fixture).expect("fixture"));
let main = program
.image
.functions
.iter()
.find_map(|(&addr, function)| {
(function.name.as_deref() == Some("main.main")).then_some(addr)
})
.expect("main.main");
let first = super::summary(&program, main);
let cached = program.summaries.read().expect("summaries lock").clone();
assert!(cached.contains_key(&main));
assert!(!cached.is_empty());
assert_eq!(super::summary(&program, main), first);
let summaries = program.summaries.read().expect("summaries lock");
assert_eq!(*summaries, cached);
}