use std::collections::{BTreeMap, BTreeSet};
use std::sync::Arc;
use binbun_ast::types::{Aggregate, Enumeration, Field, Signature, Type, TypeId, Types};
use binbun_decompile::format::Family;
use binbun_decompile::prototype::{
AllocSize, DebugStated, Format as FormatString, Open, Prototype, Prototypes, SystemCall,
};
use binbun_loader::{Image, SymbolKind};
use binbun_semantics::Declarations;
use binbun_semantics::ir::Format;
use binbun_ssa::Terminator;
use binbun_ssa::ir::{Definition, Function, Op, Value};
use binbun_typedb::database::Format as LibFormat;
use binbun_typedb::types::{Enum as LibEnum, FloatFormat, Signature as LibSignature};
use binbun_typedb::{Type as LibType, TypeId as LibId, TypeLibrary};
use crate::cfg::{Destination, Exit, FunctionId, Program};
use crate::debug::DebugInfo;
use crate::lift::{ImageEnvironment, lift_function, lift_function_leaving};
use crate::manglings::Manglings;
use crate::summary::Summaries;
use crate::target::{convention, handed_on};
use crate::user::UserTypes;
const DRIVER_INITIALIZE: &str = "Windows.Wdk.Foundation.DRIVER_INITIALIZE";
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Imports {
thunks: BTreeMap<u64, (Option<String>, String)>,
slots: BTreeMap<u64, (Option<String>, String)>,
own: BTreeMap<u64, u64>,
exports: BTreeMap<u64, BTreeSet<String>>,
driver_entries: BTreeSet<u64>,
}
impl Imports {
pub fn new(image: &Image<'_>, program: &Program) -> Self {
let mut slots: BTreeMap<u64, (Option<String>, String)> = image
.imports
.iter()
.map(|import| (import.slot, (import.library.clone(), import.name.clone())))
.collect();
for resolved in &image.resolved {
let name = resolved
.names
.iter()
.find(|name| !name.starts_with('_'))
.or_else(|| resolved.names.first());
if let Some(name) = name {
slots
.entry(resolved.at)
.or_insert_with(|| (None, name.clone()));
}
}
let thunks = program
.functions
.iter()
.filter_map(|(id, function)| {
let [only] = function.blocks.as_slice() else {
return None;
};
let Exit::Jump(Destination::Import(slot) | Destination::Pointer(slot)) =
program.blocks.get(*only)?.exit
else {
return None;
};
let import = slots.get(&slot)?.clone();
pure_thunk(image, program, id).then_some((function.entry, import))
})
.collect();
let named: BTreeSet<u64> = image
.symbols
.iter()
.filter(|symbol| symbol.kind == SymbolKind::Function)
.map(|symbol| symbol.address)
.collect();
let own = program
.functions
.iter()
.filter_map(|(id, function)| {
let [only] = function.blocks.as_slice() else {
return None;
};
let block = program.blocks.get(*only)?;
let Exit::Jump(Destination::Address(target)) = block.exit else {
return None;
};
(target != function.entry
&& block.instructions <= STUB
&& !named.contains(&function.entry)
&& program.function_at(target).is_some()
&& pure_thunk(image, program, id))
.then_some((function.entry, target))
})
.collect();
let mut exports: BTreeMap<u64, BTreeSet<String>> = BTreeMap::new();
for symbol in &image.symbols {
if symbol.interposes && symbol.kind == SymbolKind::Function {
exports
.entry(symbol.address)
.or_default()
.insert(symbol.name.clone());
}
}
Self {
thunks,
slots,
own,
exports,
driver_entries: driver_entries(image, program),
}
}
pub fn is_driver_entry(&self, address: u64) -> bool {
self.driver_entries.contains(&address)
}
pub fn thunk_names(&self) -> impl Iterator<Item = (u64, &str)> {
self.thunks
.iter()
.map(|(&entry, (_, name))| (entry, name.as_str()))
}
pub fn own_thunks(&self) -> impl Iterator<Item = (u64, u64)> {
self.own.iter().map(|(&entry, &target)| (entry, target))
}
pub fn stands_for(&self, address: u64) -> u64 {
let mut at = address;
for _ in 0..THUNKS {
match self.own.get(&at) {
Some(&target) => at = target,
None => break,
}
}
at
}
pub fn prototypes<'a>(
&'a self,
library: &'a TypeLibrary,
manglings: &'a Manglings,
debug: Option<&'a DebugInfo>,
) -> LibraryPrototypes<'a> {
LibraryPrototypes {
library,
imports: self,
manglings,
debug,
user: None,
}
}
pub fn nothrow<'a>(&'a self, library: &'a TypeLibrary) -> impl Iterator<Item = u64> + 'a {
self.thunks
.iter()
.filter(|(_, (module, name))| {
library
.function(module.as_deref(), name)
.and_then(|declaration| declaration.no_throw)
.is_some_and(|fact| fact.value)
})
.map(|(&entry, _)| entry)
}
}
#[derive(Clone, Debug)]
pub struct LibraryPrototypes<'a> {
library: &'a TypeLibrary,
imports: &'a Imports,
manglings: &'a Manglings,
debug: Option<&'a DebugInfo>,
user: Option<Arc<UserTypes>>,
}
const THUNKS: usize = 4;
const STUB: u32 = 2;
pub fn pure_thunk(image: &Image<'_>, program: &Program, id: FunctionId) -> bool {
let (Ok(l1), Ok(handed), Ok(environment)) = (
lift_function_leaving(image, program, id, &Summaries::new()),
handed_on(image),
ImageEnvironment::new(image, &[]),
) else {
return false;
};
let declarations = environment.declarations();
let Some(entry) = l1.blocks.first() else {
return false;
};
let memory = entry.parameters.last().copied();
let leaves: Vec<_> = l1
.blocks
.iter()
.filter_map(|block| match &block.terminator {
Terminator::Leave { state, .. } => Some(state),
Terminator::IndirectJump { .. }
| Terminator::Jump(_)
| Terminator::Branch { .. }
| Terminator::Invoke { .. }
| Terminator::Return { .. }
| Terminator::Trap(_)
| Terminator::Stop
| Terminator::Open => None,
})
.collect();
!leaves.is_empty()
&& leaves.iter().all(|state| {
Some(before_hashes(&l1, declarations, state.memory)) == memory
&& handed.iter().all(|register| {
let index = usize::from(register.0);
state.registers.get(index) == entry.parameters.get(index)
})
})
}
fn driver_entries(image: &Image<'_>, program: &Program) -> BTreeSet<u64> {
let mut entries = BTreeSet::new();
let Some((entry, id)) = image
.entry
.filter(|_| image.kernel)
.and_then(|entry| Some((entry, program.function_at(entry)?)))
else {
return entries;
};
entries.insert(entry);
let (Ok(l1), Ok(environment)) = (
lift_function(image, program, id, &Summaries::new()),
ImageEnvironment::new(image, &[]),
) else {
return entries;
};
let convention = convention(image, environment.declarations());
let (Some(arguments), Some(&result), Some(parameters)) = (
convention.arguments.get(..2),
convention.results.first(),
l1.blocks.first().map(|block| &block.parameters),
) else {
return entries;
};
let handed = |registers: &[Value]| {
arguments.iter().all(|register| {
let index = usize::from(register.0);
registers.get(index) == parameters.get(index)
})
};
let callee = |address: u64| {
let exit = program.blocks.get(program.block_containing(address)?)?.exit;
let (Exit::Jump(Destination::Address(target))
| Exit::Call {
callee: Destination::Address(target),
..
}) = exit
else {
return None;
};
program.function_at(target).map(|_| target)
};
let mut returned = l1.blocks.iter().filter_map(|block| {
let Terminator::Return { state, .. } = &block.terminator else {
return None;
};
Some(state.registers.get(usize::from(result.0)))
});
let returned = returned
.next()
.flatten()
.filter(|&first| returned.all(|other| other == Some(first)));
for block in &l1.blocks {
if let Terminator::Leave { state, .. } = &block.terminator
&& handed(&state.registers)
&& let Some(target) = callee(block.end)
{
entries.insert(target);
}
for inst in block.insts.iter().filter_map(|&id| l1.inst(id)) {
let Op::Call {
registers, changes, ..
} = &inst.op
else {
continue;
};
let value = changes
.iter()
.position(|®ister| register == result)
.and_then(|position| inst.results.get(position + 1));
if value.is_some()
&& value == returned
&& handed(registers)
&& let Some(target) = callee(inst.address)
{
entries.insert(target);
}
}
}
entries
}
fn before_hashes(l1: &Function, declarations: &Declarations, mut memory: Value) -> Value {
while let Some(Definition::Result { inst, .. }) = l1.value(memory).map(|v| v.definition)
&& let Some(&Op::Intrinsic {
intrinsic,
memory: before,
..
}) = l1.inst(inst).map(|i| &i.op)
&& declarations
.intrinsic(intrinsic)
.is_some_and(|info| !info.escapes)
{
memory = before;
}
memory
}
impl LibraryPrototypes<'_> {
pub(crate) fn stands_for(&self, address: u64) -> u64 {
self.imports.stands_for(address)
}
#[must_use]
pub fn defined_by(self, user: Arc<UserTypes>) -> Self {
Self {
user: Some(user),
..self
}
}
fn convert<'s, 't>(&'s self, types: &'t mut Types) -> Convert<'s, 't> {
Convert::new(self.library, types).replacing(self.user.as_deref())
}
fn driver_initialize(&self) -> Option<&LibSignature<LibId>> {
let LibType::Typedef(typedef) =
self.library.ty(self.library.named(DRIVER_INITIALIZE)?)?
else {
return None;
};
let &LibType::Pointer(target) = self.library.ty(typedef.target)? else {
return None;
};
let LibType::Function(signature) = self.library.ty(target)? else {
return None;
};
Some(signature)
}
fn driver_entry(&self, types: &mut Types) -> Option<Prototype> {
let signature = self.convert(types).signature(self.driver_initialize()?)?;
Some(Prototype {
name: None,
signature: types.intern(Type::Code(signature)),
returns_stated: true,
own: false,
open: Open::default(),
noreturn: false,
format: None,
format_arg: Vec::new(),
alloc_size: None,
wide_result: None,
})
}
fn declared_names(&self, module: Option<&str>, name: &str) -> Vec<Option<String>> {
let mut types = Types::new(64);
let Some(prototype) = self.import(module, name, &mut types) else {
return Vec::new();
};
let by_value = prototype.wide_result.is_some()
|| types
.signature(prototype.signature)
.is_some_and(|signature| {
signature
.parameters
.iter()
.any(|&ty| matches!(types.get(ty), Some(Type::Struct(_) | Type::Union(_))))
});
if by_value {
return Vec::new();
}
let Some(declared) = self
.library
.function(module, name)
.and_then(|declaration| declaration.prototype.as_ref())
else {
return Vec::new();
};
let names: Vec<Option<String>> = declared
.value
.params
.iter()
.map(|param| param.name.clone())
.collect();
let arity = types
.signature(prototype.signature)
.map(|signature| signature.parameters.len());
if arity == Some(names.len()) {
names
} else {
Vec::new()
}
}
fn import(&self, module: Option<&str>, name: &str, types: &mut Types) -> Option<Prototype> {
let declaration = self.library.function(module, name);
let noreturn = declaration
.and_then(|declaration| declaration.no_return)
.is_some_and(|fact| fact.value);
let Some((declaration, prototype)) = declaration.and_then(|declaration| {
let prototype = &declaration.prototype.as_ref()?.value;
Some((declaration, prototype))
}) else {
let prototype = self.manglings.import(name, types)?;
return Some(Prototype {
noreturn,
..prototype
});
};
let mut convert = self.convert(types);
let (signature, wide_result) = convert.declared(prototype)?;
let format = declaration
.format
.as_ref()
.and_then(|fact| format(&fact.value, &signature));
let format_arg = declaration
.format_arg
.as_ref()
.map(|fact| format_arg(&fact.value, &signature))
.unwrap_or_default();
let alloc_size = declaration
.alloc_size
.as_ref()
.and_then(|fact| alloc_size(&fact.value, &signature));
Some(Prototype {
name: Some(name.to_owned()),
signature: types.intern(Type::Code(signature)),
returns_stated: true,
own: false,
open: Open::default(),
noreturn,
format,
format_arg,
alloc_size,
wide_result,
})
}
}
fn format_arg(indices: &[u32], signature: &Signature) -> Vec<usize> {
let parameters: Option<Vec<usize>> = indices
.iter()
.map(|&index| {
let index = usize::try_from(index.checked_sub(1)?).ok()?;
(index < signature.parameters.len()).then_some(index)
})
.collect();
parameters.unwrap_or_default()
}
fn alloc_size(indices: &[u32], signature: &Signature) -> Option<AllocSize> {
let parameter = |index: u32| {
let index = usize::try_from(index.checked_sub(1)?).ok()?;
(index < signature.parameters.len()).then_some(index)
};
match *indices {
[size] => Some(AllocSize {
size: parameter(size)?,
count: None,
}),
[count, size] => Some(AllocSize {
size: parameter(size)?,
count: Some(parameter(count)?),
}),
_ => None,
}
}
impl Prototypes for LibraryPrototypes<'_> {
fn of(&self, address: u64, types: &mut Types) -> Option<Prototype> {
let address = self.imports.stands_for(address);
if let Some((module, name)) = self.imports.thunks.get(&address) {
return self.import(module.as_deref(), name, types);
}
if let Some(mut prototype) = self.debug.and_then(|debug| debug.prototype(address, types)) {
let arity = |types: &Types, prototype: &Prototype| {
types
.signature(prototype.signature)
.map(|signature| signature.parameters.len())
};
if let Some(declared) = self.interposed(address, types)
&& arity(types, &declared) == arity(types, &prototype)
{
prototype.noreturn |= declared.noreturn;
prototype.format = declared.format;
prototype.format_arg = declared.format_arg;
prototype.alloc_size = declared.alloc_size;
}
return Some(prototype);
}
if self.imports.is_driver_entry(address) {
return self.driver_entry(types);
}
self.interposed(address, types)
.or_else(|| self.manglings.defined(address, types))
}
fn through(&self, slot: u64, types: &mut Types) -> Option<Prototype> {
let (module, name) = self.imports.slots.get(&slot)?;
self.import(module.as_deref(), name, types)
}
fn parameter_names(&self, address: u64) -> Vec<Option<String>> {
let address = self.imports.stands_for(address);
if let Some((module, name)) = self.imports.thunks.get(&address) {
return self.declared_names(module.as_deref(), name);
}
if let Some(debug) = self.debug {
let mut types = Types::new(64);
if debug.prototype(address, &mut types).is_some() {
return debug
.facts(address, &mut types)
.map(|facts| facts.parameters)
.unwrap_or_default();
}
}
if self.imports.is_driver_entry(address) {
return self
.driver_initialize()
.map(|signature| {
signature
.params
.iter()
.map(|param| param.name.clone())
.collect()
})
.unwrap_or_default();
}
self.imports
.exports
.get(&address)
.and_then(|names| {
names
.iter()
.map(|name| self.declared_names(None, name))
.find(|names| !names.is_empty())
})
.unwrap_or_default()
}
fn parameter_names_through(&self, slot: u64) -> Vec<Option<String>> {
self.imports
.slots
.get(&slot)
.map(|(module, name)| self.declared_names(module.as_deref(), name))
.unwrap_or_default()
}
fn system_call(&self, number: u64) -> Option<SystemCall> {
let (name, declaration) = self.library.syscall_number(number)?;
Some(SystemCall {
name: name.to_owned(),
arguments: declaration.prototype.as_ref()?.value.params.len(),
})
}
fn debug(&self, address: u64, types: &mut Types) -> Option<DebugStated> {
self.debug?.facts(address, types)
}
fn global(&self, address: u64, types: &mut Types) -> Option<TypeId> {
self.debug?.global(address, types)
}
fn thread_pointer(&self, types: &mut Types) -> Option<TypeId> {
let target = self.library.target()?;
let structure = match (target.arch.as_str(), target.os.as_str()) {
("x86_64" | "aarch64", "windows") => {
let teb = self.library.types().find_map(|(id, ty)| {
let LibType::Record(record) = ty else {
return None;
};
(record.key == "struct _TEB" && record.fields.is_some()).then_some(id)
})?;
self.convert(types).record(teb)?
}
("x86_64", "linux") => glibc_tcb(types),
_ => return None,
};
Some(types.intern(Type::Pointer(Some(structure))))
}
}
pub fn glibc_tcb(types: &mut Types) -> TypeId {
let pointer = types.intern(Type::Pointer(None));
let word = types.intern(Type::UInt(64));
let field = |offset: u64, ty: TypeId, name: &str| Field {
offset,
ty,
name: Some(name.to_owned()),
};
types.intern(Type::Struct(Aggregate {
name: Some("tcbhead_t".to_owned()),
size: 0x30,
fields: vec![
field(0, pointer, "tcb"),
field(0x10, pointer, "self"),
field(0x28, word, "stack_guard"),
],
}))
}
impl LibraryPrototypes<'_> {
fn interposed(&self, address: u64, types: &mut Types) -> Option<Prototype> {
self.imports.exports.get(&address).and_then(|names| {
names
.iter()
.filter(|name| {
self.library
.function(None, name)
.is_some_and(|declaration| declaration.prototype.is_some())
})
.find_map(|name| self.import(None, name, types))
})
}
}
pub(crate) struct Convert<'l, 't> {
library: &'l TypeLibrary,
types: &'t mut Types,
seen: BTreeMap<LibId, TypeId>,
incomplete: bool,
user: Option<&'l UserTypes>,
}
impl<'l> Convert<'l, '_> {
pub(crate) fn new<'a, 't>(library: &'a TypeLibrary, types: &'t mut Types) -> Convert<'a, 't> {
Convert {
library,
types,
seen: BTreeMap::new(),
incomplete: false,
user: None,
}
}
pub(crate) const fn naming_incomplete(mut self) -> Self {
self.incomplete = true;
self
}
pub(crate) const fn replacing(mut self, user: Option<&'l UserTypes>) -> Self {
self.user = user;
self
}
pub(crate) fn signature(&mut self, signature: &LibSignature<LibId>) -> Option<Signature> {
self.declared(signature)
.and_then(|(signature, wide)| wide.is_none().then_some(signature))
}
pub(crate) fn declared(
&mut self,
signature: &LibSignature<LibId>,
) -> Option<(Signature, Option<TypeId>)> {
if signature.convention.is_some() {
return None;
}
let (returns, wide) = if self.void(signature.ret)? {
(None, None)
} else {
let ty = self.passed(signature.ret)?;
if self.types.value_width(ty).is_some() {
(Some(ty), None)
} else {
(None, Some(ty))
}
};
let parameters = signature
.params
.iter()
.map(|param| self.parameter(param.ty))
.collect::<Option<Vec<_>>>()?;
if parameters
.iter()
.any(|&ty| self.types.value_width(ty).is_none())
{
return None;
}
Some((
Signature {
parameters,
returns,
variadic: signature.variadic,
},
wide,
))
}
fn void(&self, id: LibId) -> Option<bool> {
match self.library.ty(id)? {
LibType::Void => Some(true),
LibType::Typedef(typedef) => self.void(typedef.target),
LibType::Bool
| LibType::Char { .. }
| LibType::Int { .. }
| LibType::Float(_)
| LibType::Pointer(_)
| LibType::Array { .. }
| LibType::Function(_)
| LibType::Record(_)
| LibType::Enum(_)
| LibType::Opaque(_) => Some(false),
}
}
pub(crate) fn value(&mut self, id: LibId) -> Option<TypeId> {
match self.library.ty(id)? {
LibType::Typedef(typedef) => self.value(typedef.target),
LibType::Void
| LibType::Record(_)
| LibType::Array { .. }
| LibType::Function(_)
| LibType::Opaque(_) => None,
LibType::Bool
| LibType::Char { .. }
| LibType::Int { .. }
| LibType::Float(_)
| LibType::Pointer(_)
| LibType::Enum(_) => self.any(id),
}
}
fn passed(&mut self, id: LibId) -> Option<TypeId> {
match self.library.ty(id)? {
LibType::Typedef(typedef) => self.passed(typedef.target),
LibType::Record(_) => self.record(id),
LibType::Void
| LibType::Bool
| LibType::Char { .. }
| LibType::Int { .. }
| LibType::Float(_)
| LibType::Pointer(_)
| LibType::Array { .. }
| LibType::Function(_)
| LibType::Enum(_)
| LibType::Opaque(_) => self.value(id),
}
}
fn parameter(&mut self, id: LibId) -> Option<TypeId> {
match self.library.ty(id)? {
LibType::Typedef(typedef) => self.parameter(typedef.target),
&LibType::Array { element, .. } => {
let pointer = self.pointer(element);
Some(self.types.intern(pointer))
}
LibType::Void
| LibType::Bool
| LibType::Char { .. }
| LibType::Int { .. }
| LibType::Float(_)
| LibType::Pointer(_)
| LibType::Function(_)
| LibType::Record(_)
| LibType::Enum(_)
| LibType::Opaque(_) => self.passed(id),
}
}
pub(crate) fn any(&mut self, id: LibId) -> Option<TypeId> {
let ty = match self.library.ty(id)? {
LibType::Bool => Type::Bool(8),
&LibType::Char { signed } => Type::Char { signed },
&LibType::Int { signed, size } => integer(signed, u16::from(size) * 8),
LibType::Enum(definition) => enumeration(definition).map_or_else(
|| Type::Int(u16::from(definition.size.unwrap_or(4)) * 8),
|enumeration| {
Type::Enum(Enumeration {
macros: self.library.macro_constants(id),
..enumeration
})
},
),
&LibType::Float(format) => Type::Float(float(format)?),
&LibType::Pointer(target) => self.pointer(target),
&LibType::Array { element, count } => Type::Array {
element: self.any(element)?,
length: count,
},
LibType::Typedef(typedef) => return self.any(typedef.target),
LibType::Record(_) => return self.record(id),
LibType::Void | LibType::Function(_) | LibType::Opaque(_) => return None,
};
Some(self.types.intern(ty))
}
fn pointer(&mut self, target: LibId) -> Type {
match self.library.ty(target) {
Some(LibType::Function(signature)) => {
let signature = signature.clone();
self.signature(&signature)
.map_or(Type::Pointer(None), Type::Code)
}
_ => Type::Pointer(self.any(target).or_else(|| self.named(target))),
}
}
fn named(&mut self, id: LibId) -> Option<TypeId> {
if !self.incomplete {
return None;
}
let Some(LibType::Record(record)) = self.library.ty(id) else {
return None;
};
if record.fields.is_some() {
return None;
}
let shell = Aggregate {
name: Some(record.name.clone()?),
size: 0,
fields: Vec::new(),
};
Some(self.types.intern(if record.union {
Type::Union(shell)
} else {
Type::Struct(shell)
}))
}
fn record(&mut self, id: LibId) -> Option<TypeId> {
if let Some(&seen) = self.seen.get(&id) {
return Some(seen);
}
let Some(LibType::Record(record)) = self.library.ty(id) else {
return None;
};
if let Some(user) = self.user
&& let Some(replaced) = user.record(&record.key)
{
let mut convert = Convert::new(user.types(), self.types);
convert.incomplete = self.incomplete;
let converted = convert.record(replaced)?;
self.seen.insert(id, converted);
return Some(converted);
}
let (size, fields) = (record.size?, record.fields.as_ref()?);
let union = record.union;
if let Some(name) = &record.name
&& let Some(existing) = self.types.iter().find_map(|(existing, ty)| {
let (Type::Struct(aggregate) | Type::Union(aggregate)) = ty else {
return None;
};
let same = aggregate.name.as_ref() == Some(name)
&& aggregate.size == size
&& matches!(ty, Type::Union(_)) == union;
same.then_some(existing)
})
{
self.seen.insert(id, existing);
return Some(existing);
}
let shell = Aggregate {
name: record.name.clone(),
size,
fields: Vec::new(),
};
let converted = self.types.intern(if union {
Type::Union(shell)
} else {
Type::Struct(shell)
});
self.seen.insert(id, converted);
let declared = fields;
let fields: Vec<Field> = declared
.clone()
.into_iter()
.filter(|field| field.bit_width.is_none())
.filter_map(|field| {
let bits = field.bit_offset?;
(bits % 8 == 0).then_some(())?;
let ty = self.any(field.ty)?;
let width = self.types.width(ty)?;
if self.replaced(field.ty) {
let next = declared
.iter()
.filter_map(|field| field.bit_offset)
.filter(|&offset| !union && offset > bits)
.min()
.unwrap_or(size * 8);
(bits + width <= next).then_some(())?;
}
Some(Field {
offset: bits / 8,
ty,
name: field.name,
})
})
.collect();
if let Some(aggregate) = self.types.aggregate_mut(converted) {
aggregate.fields = fields;
}
Some(converted)
}
fn replaced(&self, id: LibId) -> bool {
let Some(user) = self.user else {
return false;
};
let mut id = id;
for _ in 0..64 {
match self.library.ty(id) {
Some(LibType::Typedef(typedef)) => id = typedef.target,
Some(&LibType::Array { element, .. }) => id = element,
Some(LibType::Record(record)) => return user.record(&record.key).is_some(),
Some(
LibType::Void
| LibType::Bool
| LibType::Char { .. }
| LibType::Int { .. }
| LibType::Float(_)
| LibType::Pointer(_)
| LibType::Function(_)
| LibType::Enum(_)
| LibType::Opaque(_),
)
| None => return false,
}
}
false
}
}
pub fn enumeration(definition: &LibEnum) -> Option<Enumeration> {
let width = u16::from(definition.size.unwrap_or(4)) * 8;
if !matches!(width, 8 | 16 | 32 | 64) {
return None;
}
let values = || definition.variants.iter().filter_map(|v| v.value);
let top = 1i128 << (width - 1);
let signed = values().any(|v| v < 0) || values().all(|v| v < top);
let (low, high) = if signed { (-top, top) } else { (0, top * 2) };
let mask = u128::MAX >> (128 - u32::from(width));
let mut constants: Vec<(String, u128)> = Vec::new();
for variant in &definition.variants {
let Some(value) = variant.value.filter(|v| (low..high).contains(v)) else {
continue;
};
if constants.iter().all(|(name, _)| *name != variant.name) {
constants.push((variant.name.clone(), value.cast_unsigned() & mask));
}
}
Some(Enumeration {
name: definition.name.clone(),
width,
signed,
flags: definition.flags,
macros: false,
constants,
})
}
fn integer(signed: bool, bits: u16) -> Type {
if signed {
Type::Int(bits)
} else {
Type::UInt(bits)
}
}
fn float(format: FloatFormat) -> Option<Format> {
match format {
FloatFormat::Half => Some(Format::Half),
FloatFormat::Single => Some(Format::Single),
FloatFormat::Double => Some(Format::Double),
FloatFormat::X87 => Some(Format::Extended),
FloatFormat::Quad => None,
}
}
fn format(format: &LibFormat, signature: &Signature) -> Option<FormatString> {
let family = match format.archetype.as_str() {
"printf" | "gnu_printf" => Family::Printf,
"scanf" | "gnu_scanf" => Family::Scanf,
_ => return None,
};
let string = usize::try_from(format.string).ok()?.checked_sub(1)?;
let first = usize::try_from(format.first).ok()?;
let count = signature.parameters.len();
let list = first == 0 && !signature.variadic && string.checked_add(2) == Some(count);
let variadic = signature.variadic && string < count && first == count + 1;
(list || variadic).then_some(FormatString {
family,
string,
list,
})
}