pub(crate) mod msvc;
use std::collections::{BTreeMap, BTreeSet};
use binbun_ast::types::{Signature, Type, TypeId, Types};
use binbun_decompile::prototype::{Open, Prototype};
use binbun_demangle::itanium::{
self, Builtin, Component, NameKind, PrefixId, Symbol, Type as Mangled, TypeId as MangledId,
};
use binbun_loader::{Format, Image, Machine, SymbolKind};
use binbun_semantics::ir::Format as FloatFormat;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Abi {
Aapcs64,
SysV,
MicrosoftX64,
}
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct Manglings {
abi: Option<Abi>,
defined: BTreeMap<u64, BTreeSet<String>>,
}
impl Manglings {
pub fn new(image: &Image<'_>) -> Self {
let abi = match (image.format, image.machine) {
(Format::Elf | Format::MachO, Machine::Aarch64) => Some(Abi::Aapcs64),
(Format::Elf | Format::MachO, Machine::X86_64) => Some(Abi::SysV),
(Format::Pe, Machine::X86_64) => Some(Abi::MicrosoftX64),
(Format::Elf | Format::MachO, Machine::X86 | Machine::Arm | Machine::Other)
| (Format::Pe, Machine::X86 | Machine::Aarch64 | Machine::Arm | Machine::Other) => None,
};
let mut defined: BTreeMap<u64, BTreeSet<String>> = BTreeMap::new();
for symbol in &image.symbols {
if symbol.kind == SymbolKind::Function {
defined
.entry(symbol.address)
.or_default()
.insert(symbol.name.clone());
}
}
Self { abi, defined }
}
pub fn import(&self, name: &str, types: &mut Types) -> Option<Prototype> {
self.prototype(name, false, types)
}
pub fn defined(&self, entry: u64, types: &mut Types) -> Option<Prototype> {
let names = self.defined.get(&entry)?;
let aliased = |kind: NameKind| {
names.iter().any(|name| {
itanium::parse(name)
.ok()
.and_then(|symbol| symbol.last_name().map(|last| last.kind.clone()))
== Some(kind.clone())
})
};
let complete = aliased(NameKind::Constructor(1)) || aliased(NameKind::Destructor(1));
let mut found: Option<Prototype> = None;
for name in names {
let prototype = self.prototype(name, complete, types)?;
match &found {
Some(first)
if first.signature != prototype.signature
|| first.returns_stated != prototype.returns_stated
|| first.open != prototype.open =>
{
return None;
}
Some(_) => {}
None => found = Some(prototype),
}
}
found
}
fn prototype(&self, name: &str, complete: bool, types: &mut Types) -> Option<Prototype> {
let given = match self.abi? {
Abi::MicrosoftX64 if name.starts_with('?') => msvc::signature(name, types)?,
abi @ (Abi::Aapcs64 | Abi::SysV) if name.starts_with("_Z") => {
let symbol = itanium::parse(name).ok()?;
if symbol.suffix.is_some() {
return None;
}
let mut convert = Convert {
symbol: &symbol,
abi,
types,
};
convert.signature(complete)?
}
Abi::MicrosoftX64 | Abi::Aapcs64 | Abi::SysV => return None,
};
Some(Prototype {
name: Some(name.to_owned()),
signature: types.intern(Type::Code(given.signature)),
returns_stated: given.returns_stated,
own: false,
open: given.open,
noreturn: false,
format: None,
format_arg: Vec::new(),
alloc_size: None,
wide_result: None,
})
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
struct Given {
signature: Signature,
returns_stated: bool,
open: Open,
}
pub(crate) fn scope(symbol: &Symbol) -> Option<PrefixId> {
let mut node = symbol.prefix(symbol.name()?.path)?;
loop {
match &node.component {
Component::Arguments(_) => node = symbol.prefix(node.parent?)?,
Component::Name(_) => return node.parent,
Component::Std | Component::Abbreviation(_) => return None,
}
}
}
struct Convert<'s, 't> {
symbol: &'s Symbol,
abi: Abi,
types: &'t mut Types,
}
impl Convert<'_, '_> {
fn signature(&mut self, complete: bool) -> Option<Given> {
let symbol = self.symbol;
let name = symbol.name()?;
let function = symbol.function()?;
let kind = &symbol.last_name()?.kind;
let structor = match kind {
NameKind::Constructor(1) | NameKind::Destructor(0 | 1) => true,
NameKind::Constructor(2) | NameKind::Destructor(2) => {
if !complete {
return None;
}
true
}
NameKind::Constructor(_) | NameKind::Destructor(_) => return None,
NameKind::Source(_) | NameKind::Operator(_) => false,
};
let scope = scope(symbol);
let in_std = scope
.and_then(|scope| symbol.prefix(scope))
.is_some_and(|node| node.component == Component::Std);
let allocation = matches!(
kind,
NameKind::Operator(" new" | " new[]" | " delete" | " delete[]")
);
let member = !allocation && (structor || !name.cv.is_empty() || name.reference.is_some());
if !member && !allocation && scope.is_some() && !in_std {
return None;
}
let (returns, returns_stated, open_returns) = if structor {
(None, true, false)
} else {
self.returns(function.returns)?
};
let mut parameters = Vec::new();
let mut open = Open {
parameters: Vec::new(),
returns: open_returns,
};
if member {
open.parameters.push(parameters.len());
parameters.push(self.types.intern(Type::Pointer(None)));
}
let mut variadic = false;
for (index, ¶meter) in function.parameters.iter().enumerate() {
let resolved = symbol.resolve(parameter)?;
if symbol.ty(resolved)? == &Mangled::Builtin(Builtin::Ellipsis) {
if index + 1 != function.parameters.len() {
return None;
}
variadic = true;
} else {
let (ty, pointer) = self.value(parameter)?;
if pointer {
open.parameters.push(parameters.len());
}
parameters.push(ty);
}
}
Some(Given {
signature: Signature {
parameters,
returns,
variadic,
},
returns_stated,
open,
})
}
fn returns(&mut self, stated: Option<MangledId>) -> Option<(Option<TypeId>, bool, bool)> {
let unstated = |convert: &mut Self| match convert.abi {
Abi::Aapcs64 => Some((Some(convert.types.intern(Type::Bits(64))), false, false)),
Abi::SysV | Abi::MicrosoftX64 => None,
};
let Some(stated) = stated else {
return unstated(self);
};
let resolved = self.symbol.resolve(stated)?;
match self.symbol.ty(resolved)? {
Mangled::Builtin(Builtin::Void) => Some((None, true, false)),
Mangled::Qualified(_, inner)
if self.symbol.ty(self.symbol.resolve(*inner)?)?
== &Mangled::Builtin(Builtin::Void) =>
{
Some((None, true, false))
}
Mangled::Named { .. } => unstated(self),
Mangled::Builtin(_)
| Mangled::Qualified(..)
| Mangled::Pointer(_)
| Mangled::LvalueReference(_)
| Mangled::RvalueReference(_)
| Mangled::Function(_)
| Mangled::TemplateParam(_) => {
let (ty, pointer) = self.value(stated)?;
Some((Some(ty), true, pointer))
}
}
}
fn value(&mut self, id: MangledId) -> Option<(TypeId, bool)> {
let symbol = self.symbol;
let resolved = symbol.resolve(id)?;
match symbol.ty(resolved)? {
&Mangled::Builtin(builtin) => {
let ty = self.builtin(builtin)?;
Some((self.types.intern(ty), false))
}
&Mangled::Qualified(_, inner) => self.value(inner),
&(Mangled::Pointer(target)
| Mangled::LvalueReference(target)
| Mangled::RvalueReference(target)) => Some(match self.pointer_to(target, 0) {
Some(pointer) => (pointer, false),
None => (self.types.intern(Type::Pointer(None)), true),
}),
Mangled::Named { .. } | Mangled::Function(_) | Mangled::TemplateParam(_) => None,
}
}
fn pointer_to(&mut self, id: MangledId, depth: usize) -> Option<TypeId> {
let symbol = self.symbol;
if depth > symbol.types.len() {
return None;
}
let target = match symbol.ty(symbol.resolve(id)?)? {
Mangled::Builtin(Builtin::Void) => None,
&Mangled::Builtin(builtin) => {
let ty = self.builtin(builtin)?;
Some(self.types.intern(ty))
}
&Mangled::Qualified(_, inner) => return self.pointer_to(inner, depth + 1),
&(Mangled::Pointer(target)
| Mangled::LvalueReference(target)
| Mangled::RvalueReference(target)) => Some(self.pointer_to(target, depth + 1)?),
Mangled::Named { .. } | Mangled::Function(_) | Mangled::TemplateParam(_) => {
return None;
}
};
Some(self.types.intern(Type::Pointer(target)))
}
fn builtin(&self, builtin: Builtin) -> Option<Type> {
let aarch64 = self.abi == Abi::Aapcs64;
Some(match builtin {
Builtin::Bool => Type::Bool(8),
Builtin::Char => Type::Char { signed: !aarch64 },
Builtin::SignedChar => Type::Int(8),
Builtin::UnsignedChar | Builtin::Char8 => Type::UInt(8),
Builtin::Short => Type::Int(16),
Builtin::UnsignedShort | Builtin::Char16 => Type::UInt(16),
Builtin::Int => Type::Int(32),
Builtin::Wchar if !aarch64 => Type::Int(32),
Builtin::UnsignedInt | Builtin::Char32 | Builtin::Wchar => Type::UInt(32),
Builtin::Long | Builtin::LongLong => Type::Int(64),
Builtin::UnsignedLong | Builtin::UnsignedLongLong => Type::UInt(64),
Builtin::Float => Type::Float(FloatFormat::Single),
Builtin::Double => Type::Float(FloatFormat::Double),
Builtin::Nullptr => Type::Pointer(None),
Builtin::Void
| Builtin::Ellipsis
| Builtin::Int128
| Builtin::UnsignedInt128
| Builtin::LongDouble
| Builtin::Float128 => return None,
})
}
}