pdb-bindgen-codegen 0.1.0

Build-time discovery, PDB acquisition, and binding generation for pdb-bindgen.
Documentation
use std::collections::BTreeMap;

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub(crate) struct TypeId(pub(crate) u32);

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub(crate) struct Rva(pub(crate) u32);

#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub(crate) enum Alignment {
    Known(u64),
    Unavailable,
}

#[derive(Clone, Copy, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub(crate) enum RecordKind {
    Class,
    Interface,
    Struct,
    Union,
}

#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub(crate) struct Record {
    pub(crate) id: TypeId,
    pub(crate) name: String,
    pub(crate) unique_name: Option<String>,
    pub(crate) kind: RecordKind,
    pub(crate) size: u64,
    pub(crate) alignment: Alignment,
    pub(crate) packed: bool,
    pub(crate) fields: Vec<Field>,
}
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub(crate) struct Field {
    pub(crate) name: String,
    pub(crate) ty: TypeId,
    pub(crate) offset: u64,
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum PrimitiveKind {
    Signed,
    Unsigned,
    Boolean,
    Float,
    Character,
}

#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) enum Type {
    /// `T_NOTYPE`: absence of a type, including the variadic argument-list sentinel.
    Absent,
    /// `T_VOID`: a valid pointer target, but not a sized scalar.
    Void,
    Primitive {
        kind: PrimitiveKind,
        size: u64,
        alignment: Alignment,
    },
    Pointer {
        target: TypeId,
        size: u64,
        alignment: Alignment,
        kind: PointerKind,
        is_const: bool,
        is_volatile: bool,
        is_unaligned: bool,
        is_restrict: bool,
    },
    Modifier {
        target: TypeId,
        is_const: bool,
        is_volatile: bool,
        is_unaligned: bool,
    },
    Array {
        element: TypeId,
        index: TypeId,
        size: u64,
    },
    Bitfield {
        storage: TypeId,
        position: u8,
        length: u8,
    },
    Procedure(Signature),
    MemberFunction {
        signature: Signature,
        class: TypeId,
        this: TypeId,
        this_adjust: u32,
    },
    Record(TypeId),
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum PointerKind {
    Pointer,
    LValueReference,
    RValueReference,
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub(crate) struct Signature {
    pub(crate) return_type: TypeId,
    pub(crate) arguments: Vec<TypeId>,
    pub(crate) calling_convention: CallingConvention,
    pub(crate) variadic: bool,
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub(crate) enum CallingConvention {
    NearC,
    FarC,
    NearPascal,
    NearFast,
    NearStd,
    NearSys,
    ThisCall,
    ClrCall,
    Unknown(u8),
}
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub(crate) struct Function {
    pub(crate) name: String,
    pub(crate) signature: TypeId,
    pub(crate) rva: Rva,
}
#[derive(Clone, Debug, Eq, Ord, PartialEq, PartialOrd)]
pub(crate) struct Global {
    pub(crate) name: String,
    pub(crate) ty: TypeId,
    pub(crate) rva: Rva,
}

#[derive(Default, Debug)]
pub(crate) struct Database {
    pub(crate) records: BTreeMap<String, Vec<Record>>,
    pub(crate) types: BTreeMap<TypeId, Type>,
    pub(crate) functions: BTreeMap<String, Vec<Function>>,
    pub(crate) globals: BTreeMap<String, Vec<Global>>,
}
impl Database {
    pub(crate) fn add_record(&mut self, value: Record) {
        if let Some(unique_name) = &value.unique_name
            && unique_name != &value.name
        {
            self.records
                .entry(unique_name.clone())
                .or_default()
                .push(value.clone());
        }
        self.records
            .entry(value.name.clone())
            .or_default()
            .push(value);
    }
    pub(crate) fn add_type(&mut self, id: TypeId, value: Type) {
        self.types.insert(id, value);
    }
    pub(crate) fn add_function(&mut self, value: Function) {
        self.functions
            .entry(value.name.clone())
            .or_default()
            .push(value);
    }
    pub(crate) fn add_global(&mut self, value: Global) {
        self.globals
            .entry(value.name.clone())
            .or_default()
            .push(value);
    }
    pub(crate) fn finish(&mut self) {
        deduplicate_records(&mut self.records, &mut self.types);
        deduplicate(&mut self.functions);
        deduplicate(&mut self.globals);
    }
    pub(crate) fn record(&self, name: &str) -> Result<&Record, super::error::Error> {
        one(&self.records, "record", name)
    }
    pub(crate) fn record_by_id(&self, id: TypeId) -> Option<&Record> {
        self.records
            .values()
            .flatten()
            .find(|record| record.id == id)
    }
    pub(crate) fn function(&self, name: &str) -> Result<&Function, super::error::Error> {
        one(&self.functions, "function", name)
    }
    pub(crate) fn global(&self, name: &str) -> Result<&Global, super::error::Error> {
        one(&self.globals, "global", name)
    }
}
fn deduplicate_records(
    records: &mut BTreeMap<String, Vec<Record>>,
    types: &mut BTreeMap<TypeId, Type>,
) {
    for candidates in records.values_mut() {
        candidates.sort_by(|left, right| {
            left.unique_name
                .cmp(&right.unique_name)
                .then_with(|| left.kind.cmp(&right.kind))
                .then_with(|| left.size.cmp(&right.size))
                .then_with(|| left.alignment.cmp(&right.alignment))
                .then_with(|| left.packed.cmp(&right.packed))
                .then_with(|| left.fields.cmp(&right.fields))
                .then_with(|| left.id.cmp(&right.id))
        });
        let mut unique: Vec<Record> = Vec::with_capacity(candidates.len());
        for candidate in candidates.drain(..) {
            if let Some(existing) = unique.last()
                && same_record(existing, &candidate)
            {
                types.insert(candidate.id, Type::Record(existing.id));
            } else {
                unique.push(candidate);
            }
        }
        *candidates = unique;
    }
}
pub(super) fn same_record(left: &Record, right: &Record) -> bool {
    left.name == right.name
        && left.unique_name == right.unique_name
        && left.kind == right.kind
        && left.size == right.size
        && left.alignment == right.alignment
        && left.packed == right.packed
        && left.fields == right.fields
}
fn deduplicate<T: Ord>(map: &mut BTreeMap<String, Vec<T>>) {
    for candidates in map.values_mut() {
        candidates.sort();
        candidates.dedup();
    }
}
fn one<'a, T>(
    map: &'a BTreeMap<String, Vec<T>>,
    kind: &'static str,
    name: &str,
) -> Result<&'a T, super::error::Error> {
    match map.get(name) {
        None => Err(super::error::Error::Missing {
            kind,
            name: name.into(),
        }),
        Some(values) if values.len() == 1 => Ok(&values[0]),
        Some(values) => Err(super::error::Error::Ambiguous {
            kind,
            name: name.into(),
            candidates: values.len(),
        }),
    }
}