#![allow(
clippy::unwrap_used,
clippy::indexing_slicing,
reason = "test helpers fail loudly"
)]
use std::collections::BTreeSet;
use std::fmt::Write;
use binbun::Database;
use binbun::analysis::Seeds;
use binbun::decompile::{Decompiled, Options};
use binbun_ast::ir::{Block, CatchType, Function as Ast, HandlerKind, SehFilter, Stmt};
use binbun_ast::types::Type;
use binbun_loader::Image;
fn fixture(name: &str) -> Vec<u8> {
let path = format!("{}/../../tests/fixtures/{name}", env!("CARGO_MANIFEST_DIR"));
std::fs::read(&path).unwrap_or_else(|e| panic!("{path}: {e}"))
}
fn decompile(name: &str, functions: &[&str]) -> Vec<(String, Decompiled)> {
let data = fixture(name);
let image = Image::parse(&data).unwrap();
let database = Database::new(&image, Seeds::ALL).unwrap();
let options = Options {
style: Some("kr".to_owned()),
..Options::default()
};
functions
.iter()
.map(|&function| {
let id = database.find_function(function).unwrap();
let output = database.decompile(id, &options);
let decompiled = output
.result
.unwrap_or_else(|e| panic!("{name} {function}: {e}"));
(function.to_owned(), decompiled)
})
.collect()
}
fn catch_type(ty: &CatchType) -> String {
ty.name
.clone()
.or_else(|| ty.symbol.clone())
.unwrap_or_else(|| "?".to_owned())
}
fn shape(f: &Ast, block: &Block) -> String {
let mut out = String::new();
for stmt in block.iter().filter_map(|&id| f.stmt(id)) {
match stmt {
Stmt::Try { body, handlers } => {
let _ = write!(out, "try{{{}}}", shape(f, body));
for handler in handlers {
let head = match &handler.kind {
HandlerKind::Landing(_) => "landing".to_owned(),
HandlerKind::Catch(ty) => format!("catch({})", catch_type(ty)),
HandlerKind::CatchAll => "catch(...)".to_owned(),
HandlerKind::Cleanup => "cleanup".to_owned(),
HandlerKind::Unexpected(types) => {
let names: Vec<String> = types.iter().map(catch_type).collect();
format!("unexpected({})", names.join(","))
}
HandlerKind::Except(SehFilter::Constant(value)) => {
format!("except({value})")
}
HandlerKind::Except(SehFilter::Funclet(funclet)) => {
format!("except({funclet:#x})")
}
HandlerKind::Finally => "finally".to_owned(),
};
let _ = write!(out, "{head}{{{}}}", shape(f, &handler.body));
}
}
Stmt::While { .. } | Stmt::DoWhile { .. } | Stmt::For { .. } => {
let inner: String = stmt.blocks().map(|block| shape(f, block)).collect();
if !inner.is_empty() {
let _ = write!(out, "loop{{{inner}}}");
}
}
Stmt::If { .. }
| Stmt::Switch { .. }
| Stmt::VaStart { .. }
| Stmt::Assign { .. }
| Stmt::Call { .. }
| Stmt::Intrinsic { .. }
| Stmt::Expr(_)
| Stmt::Break(_)
| Stmt::Continue(_)
| Stmt::Label(_)
| Stmt::Goto(_)
| Stmt::Return(_)
| Stmt::Trap(_)
| Stmt::Unreachable
| Stmt::Escape { .. } => out.extend(stmt.blocks().map(|block| shape(f, block))),
}
}
out
}
const HANDLERS: [(&str, Option<&str>, Option<&str>); 7] = [
(
"by_type",
Some("try{}catch(Error){}"),
Some("try{}catch(Error){}"),
),
(
"several",
Some("try{}catch(Error){}catch(std::exception){try{}cleanup{}}catch(int){}"),
Some("try{}catch(Error){}catch(std::exception){}catch(int){}"),
),
("any", Some("try{}catch(...){}"), Some("try{}catch(...){}")),
(
"rethrow",
Some("try{}catch(Error){try{}cleanup{}}"),
Some("try{}catch(Error){try{}cleanup{try{}catch(...){}}}"),
),
(
"nested",
None,
Some("try{try{}catch(Error){}}catch(std::exception){}"),
),
("cleanup", Some("try{}cleanup{}"), Some("try{}cleanup{}")),
(
"loop",
Some("loop{try{}catch(Error){}}"),
Some("loop{try{}catch(Error){}}"),
),
];
fn check_clean(fixture: &str, function: &str, decompiled: &Decompiled) {
assert_eq!(
decompiled.stats.structure, None,
"{fixture} {function}: structure"
);
let c = decompiled.c.as_ref().unwrap();
assert!(
!c.text.contains("binbun_foreign_jump"),
"{fixture} {function}:\n{}",
c.text
);
}
#[test]
fn handlers_read_as_the_source() {
let mut wrong = Vec::new();
for (index, compiler) in ["gcc", "clang"].into_iter().enumerate() {
let name = format!("handlers-{compiler}-x86_64.elf");
let functions: Vec<&str> = HANDLERS.iter().map(|&(function, ..)| function).collect();
for ((function, decompiled), &(_, gcc, clang)) in
decompile(&name, &functions).into_iter().zip(&HANDLERS)
{
check_clean(&name, &function, &decompiled);
let l2 = &decompiled.l2;
let got = shape(l2, &l2.body);
let Some(want) = [gcc, clang][index] else {
continue;
};
if got != want {
wrong.push(format!("{name} {function}: {got}, not {want}"));
}
}
}
assert!(wrong.is_empty(), "{wrong:#?}");
}
#[test]
fn excepts_read_as_the_source() {
let name = "seh-x86_64.exe";
let want = [
("0x140001080", "try{}except(0x1400026f0){}"),
(
"0x1400011f0",
"try{}finally{try{}except(1){}}try{}except(1){}",
),
("0x1400010f0", "try{}except(1){}try{}except(1){}"),
("0x1400010b0", "try{}finally{}"),
];
let functions: Vec<&str> = want.iter().map(|&(function, _)| function).collect();
for ((function, decompiled), (_, want)) in decompile(name, &functions).into_iter().zip(want) {
check_clean(name, &function, &decompiled);
let l2 = &decompiled.l2;
assert_eq!(shape(l2, &l2.body), want, "{function}");
let c = &decompiled.c.as_ref().unwrap().text;
assert!(c.contains("BINBUN_SEH_TRY"), "{c}");
if function == "0x1400010f0" {
assert_eq!(c.matches("binbun_exception_code()").count(), 2, "{c}");
}
if function == "0x1400010b0" {
assert!(c.contains("BINBUN_FINALLY"), "{c}");
assert!(c.contains("binbun_abnormal_termination()"), "{c}");
}
}
}
#[test]
fn catches_read_as_the_source() {
let shapes = [
"try{}catch(Error){}",
"try{}catch(Error){}catch(std::exception){}catch(int){}",
"try{}catch(...){}",
"try{}catch(Error){}",
"loop{try{}catch(Error){}}",
];
for (name, functions, cleanup) in [
(
"eh-x86_64.exe",
[
"0x1400012a0",
"0x140001550",
"0x140001280",
"0x140001540",
"0x140001310",
],
("0x1400012c0", ""),
),
(
"eh-fh3-x86_64.exe",
[
"0x1400012f0",
"0x1400015e0",
"0x1400012d0",
"0x1400015c0",
"0x140001360",
],
("0x140001310", "try{}cleanup{}"),
),
] {
let mut all: Vec<&str> = functions.to_vec();
all.push(cleanup.0);
let want = shapes.iter().copied().chain([cleanup.1]);
for ((function, decompiled), want) in decompile(name, &all).into_iter().zip(want) {
check_clean(name, &function, &decompiled);
let l2 = &decompiled.l2;
assert_eq!(shape(l2, &l2.body), want, "{name} {function}");
}
}
}
#[test]
fn built_in_funclets_are_not_functions_of_their_own() {
for (name, built_in, apart) in [
(
"seh-x86_64.exe",
&[0x1_4000_2720, 0x1_4000_2760][..],
0x1_4000_26f0,
),
(
"eh-x86_64.exe",
&[0x1_4000_2c90, 0x1_4000_2cc0, 0x1_4000_2d00][..],
0x1_4000_1550,
),
] {
let data = fixture(name);
let image = Image::parse(&data).unwrap();
let database = Database::new(&image, Seeds::ALL).unwrap();
let options = Options {
style: None,
..Options::default()
};
let mut entries = BTreeSet::new();
database.decompile_all_on(
&options,
1,
|output| output.entry,
|entry| {
entries.insert(entry);
},
);
for &funclet in built_in {
assert!(!entries.contains(&funclet), "{name} {funclet:#x}");
}
assert!(entries.contains(&apart), "{name} {apart:#x}");
}
}
#[test]
fn funclets_are_joined_to_their_functions() {
for (name, function, funclets) in [
("seh-x86_64.exe", 0x1_4000_1080, &[0x1_4000_26f0][..]),
("seh-x86_64.exe", 0x1_4000_11f0, &[0x1_4000_2760][..]),
(
"eh-x86_64.exe",
0x1_4000_1550,
&[0x1_4000_2c90, 0x1_4000_2cc0, 0x1_4000_2d00][..],
),
("eh-fh3-x86_64.exe", 0x1_4000_1310, &[0x1_4000_2ba0][..]),
] {
let data = fixture(name);
let image = Image::parse(&data).unwrap();
let database = Database::new(&image, Seeds::ALL).unwrap();
let owner = database
.function(database.function_at(function).unwrap())
.unwrap();
assert_eq!(owner.funclets, funclets, "{name} {function:#x}");
for &funclet in funclets {
let part = database
.function(database.function_at(funclet).unwrap())
.unwrap();
assert_eq!(part.part_of, Some(function), "{name} {funclet:#x}");
}
}
}
#[test]
fn guarded_catches_std_exception() {
let name = "exceptions-x86_64.elf";
for (function, decompiled) in decompile(name, &["_Z7guardedi"]) {
check_clean(name, &function, &decompiled);
let l2 = &decompiled.l2;
assert_eq!(
shape(l2, &l2.body),
"try{}catch(std::exception){try{}cleanup{}}"
);
let text = &decompiled.c.as_ref().unwrap().text;
assert!(text.contains("BINBUN_CATCH(std::exception)"), "{text}");
assert!(!text.contains("_Unwind_Resume"), "{text}");
}
}
#[test]
fn each_callee_and_type_is_declared_once() {
let mut checked = 0;
for (name, functions) in [
("exceptions-x86_64.elf", &["_Z7guardedi", "main"][..]),
(
"handlers-gcc-x86_64.elf",
&["several", "rethrow", "nested", "cleanup", "loop"][..],
),
(
"handlers-clang-x86_64.elf",
&["several", "rethrow", "nested", "cleanup", "loop"][..],
),
] {
for (function, decompiled) in decompile(name, functions) {
let text = &decompiled.c.as_ref().unwrap().text;
let mut addresses = BTreeSet::new();
for line in text.lines().filter(|line| line.contains("); /* 0x")) {
let address = line.split("/* ").nth(1).unwrap().split(' ').next().unwrap();
assert!(
addresses.insert(address.to_owned()),
"{name} {function}: {address} declared twice:\n{text}"
);
checked += 1;
}
let mut names = BTreeSet::new();
for (_, ty) in decompiled.l2.types.iter() {
if let Type::Struct(aggregate) | Type::Union(aggregate) = ty
&& let Some(tag) = &aggregate.name
{
assert!(names.insert(tag.clone()), "{name} {function}: two {tag}");
}
}
}
}
assert!(checked > 20, "only {checked} declarations");
}