#![allow(
clippy::unwrap_used,
clippy::indexing_slicing,
reason = "test helpers fail loudly"
)]
use std::path::PathBuf;
use binbun_ast::types::{Type as L2Type, Types};
use binbun_debuginfo::info::DebugModel;
use binbun_debuginfo::info::model::{Composite, Type as PdbType};
use binbun_typedb::types::Record;
use binbun_typedb::{Type, TypeId, TypeLibrary, embedded};
const STRUCTURES: [&str; 9] = [
"_TEB",
"_PEB",
"_NT_TIB",
"_CLIENT_ID",
"_PEB_LDR_DATA",
"_LDR_DATA_TABLE_ENTRY",
"_RTL_USER_PROCESS_PARAMETERS",
"_UNICODE_STRING",
"_LIST_ENTRY",
];
const DIFFERENCES: [(&str, &str); 4] = [
("_PEB", "size Some(2008) vs Some(2000)"),
("_PEB+0x7d0", "Win32ClientProcInfo (8 bytes) not in phnt"),
(
"_RTL_USER_PROCESS_PARAMETERS",
"size Some(1104) vs Some(1096)",
),
(
"_RTL_USER_PROCESS_PARAMETERS+0x448",
"AttributeList (8 bytes) not in phnt",
),
];
fn pdb(variable: &str, file: &str) -> Option<Vec<u8>> {
let path = std::env::var_os(variable).map_or_else(
|| {
std::env::home_dir()?
.join(".cache/binbun-model-data/pdb")
.join(file)
.into()
},
|path| Some(PathBuf::from(path)),
)?;
std::fs::read(path).ok()
}
fn native(arch: &str) -> TypeLibrary {
let (_, database) = embedded(arch, "windows")
.into_iter()
.find(|(_, database)| {
database
.header
.inputs
.iter()
.any(|input| input.starts_with("phnt@"))
})
.unwrap();
let mut library = TypeLibrary::new();
library.add(database).unwrap();
library
}
fn record<'a>(library: &'a TypeLibrary, key: &str) -> &'a Record<TypeId> {
library
.types()
.find_map(|(_, ty)| {
let Type::Record(record) = ty else {
return None;
};
(record.key == key).then_some(record)
})
.unwrap_or_else(|| panic!("no {key} in the native database"))
}
fn database_fields(
library: &TypeLibrary,
record: &Record<TypeId>,
base: u64,
out: &mut Vec<(u64, u64, String)>,
) {
for field in record.fields.iter().flatten() {
if field.bit_width.is_some() {
continue;
}
let offset = base + field.bit_offset.unwrap() / 8;
match (&field.name, library.ty(field.ty)) {
(None, Some(Type::Record(inner))) => database_fields(library, inner, offset, out),
(name, _) => out.push((
offset,
library.size_of(field.ty).unwrap_or(0),
name.clone().unwrap_or_default(),
)),
}
}
}
fn pdb_fields(
model: &DebugModel,
composite: &Composite,
base: u64,
out: &mut Vec<(u64, u64, String)>,
) {
for field in &composite.fields {
let padding = field.name.as_deref().is_some_and(|name| {
name.strip_prefix("Padding")
.is_some_and(|digits| digits.bytes().all(|byte| byte.is_ascii_digit()))
});
if field.bits.is_some() || padding {
continue;
}
let offset = base + field.offset;
let resolved = model.resolve(field.ty);
match (&field.name, model.ty(resolved)) {
(None, PdbType::Composite(inner)) => pdb_fields(model, inner, offset, out),
(name, _) => out.push((
offset,
model.size(field.ty).unwrap_or(0),
name.clone().unwrap_or_default(),
)),
}
}
}
fn differences(arch: &str, data: &[u8]) -> Vec<String> {
let (model, ids) = binbun_debuginfo::info::pdb::named(data, &STRUCTURES).unwrap();
let library = native(arch);
let mut differences = Vec::new();
let mut renamed = Vec::new();
for (name, id) in STRUCTURES.iter().zip(ids) {
let id = id.unwrap_or_else(|| panic!("ntdll.pdb defines no {name}"));
let PdbType::Composite(composite) = model.ty(model.resolve(id)) else {
panic!("{name} is no composite in ntdll.pdb");
};
let ours = record(&library, &format!("struct {name}"));
if composite.size != ours.size {
differences.push(format!(
"{name}: size {:?} vs {:?}",
composite.size, ours.size
));
}
let (mut theirs, mut mine) = (Vec::new(), Vec::new());
pdb_fields(&model, composite, 0, &mut theirs);
database_fields(&library, ours, 0, &mut mine);
for (offset, size, field) in &theirs {
let there: Vec<_> = mine.iter().filter(|(at, _, _)| at == offset).collect();
let same = there
.iter()
.filter(|(_, ours_size, _)| ours_size == size)
.min_by_key(|(_, _, ours_name)| ours_name != field);
match (same, there.first()) {
(Some((_, _, ours_name)), _) => {
if ours_name != field {
renamed.push(format!("{name}+{offset:#x}: {field} is phnt's {ours_name}"));
}
}
(None, Some((_, ours_size, ours_name))) => differences.push(format!(
"{name}+{offset:#x}: {field} ({size} bytes) vs {ours_name} ({ours_size} bytes)"
)),
(None, None) => differences.push(format!(
"{name}+{offset:#x}: {field} ({size} bytes) not in phnt"
)),
}
}
}
eprintln!(
"{arch}: renamed ({}):\n{}",
renamed.len(),
renamed.join("\n")
);
eprintln!(
"{arch}: differences ({}):\n{}",
differences.len(),
differences.join("\n")
);
differences
}
#[test]
fn native_structures_match_ntdll_pdb() {
let expected: Vec<String> = DIFFERENCES
.iter()
.map(|(at, what)| format!("{at}: {what}"))
.collect();
for (arch, variable, file) in [
("x86_64", "BINBUN_NTDLL_PDB", "ntdll.pdb"),
("aarch64", "BINBUN_NTDLL_ARM64_PDB", "ntdll-arm64.pdb"),
] {
let Some(data) = pdb(variable, file) else {
eprintln!("{arch}: skipped: no {file}");
continue;
};
assert_eq!(differences(arch, &data), expected, "{arch}");
}
}
#[test]
fn glibc_tcb_matches_glibc_debug_information() {
let Some(path) = std::env::home_dir().map(|home| {
home.join(".cache/binbun-model-data/glibc-r50/root/usr/lib/debug/usr/lib/libc.so.6.debug")
}) else {
return;
};
let Ok(data) = std::fs::read(&path) else {
eprintln!("skipped: no {}", path.display());
return;
};
let model = binbun_debuginfo::info::dwarf::read(&data).unwrap();
let composite = model
.types
.iter()
.find_map(|ty| {
let PdbType::Typedef { name, target } = ty else {
return None;
};
let PdbType::Composite(composite) = model.ty(model.resolve(*target)) else {
return None;
};
(name == "tcbhead_t").then_some(composite)
})
.expect("no tcbhead_t in glibc's debug information");
let mut types = Types::new(64);
let id = binbun::prototypes::glibc_tcb(&mut types);
let Some(L2Type::Struct(ours)) = types.get(id) else {
panic!("not a struct");
};
for field in &ours.fields {
let name = field.name.as_deref().unwrap();
let theirs = composite
.fields
.iter()
.find(|theirs| theirs.name.as_deref() == Some(name))
.unwrap_or_else(|| panic!("glibc's tcbhead_t has no {name}"));
assert_eq!(theirs.offset, field.offset, "{name}");
assert_eq!(
model.size(theirs.ty),
types.width(field.ty).map(|bits| bits / 8),
"{name}"
);
}
}