pdb-bindgen-codegen 0.1.0

Build-time discovery, PDB acquisition, and binding generation for pdb-bindgen.
Documentation
mod symbols;
mod types;

use super::error::Error;
use super::ir::Database;
use std::path::Path;

pub(crate) use symbols::{normalize_global_data, normalize_symbols};
pub(crate) use types::{normalize_types, validate_references};

#[cfg(test)]
pub(crate) use symbols::rva;
#[cfg(test)]
pub(crate) use types::primitive;

const AMD64_MACHINE: u16 = 0x8664;

pub(crate) fn read(path: &Path) -> Result<Database, Error> {
    let pdb = ms_pdb::Pdb::open(path).map_err(|source| Error::Open {
        path: path.to_path_buf(),
        source: source.into(),
    })?;
    validate_machine(pdb.machine().0)?;
    let sections = pdb
        .section_headers()
        .map_err(parse("read section headers"))?;
    if sections.is_empty() {
        return Err(Error::Parse {
            operation: "read section headers",
            detail: "missing section headers".into(),
        });
    }
    let stream = pdb.read_type_stream().map_err(parse("read TPI"))?;
    let mut database = normalize_types(&stream)?;
    for module in pdb.modules().map_err(parse("read modules"))?.iter() {
        if let Some(module_stream) = pdb
            .read_module_stream(&module)
            .map_err(parse("read module stream"))?
        {
            normalize_symbols(module_stream.iter_syms(), sections, &mut database)?;
        }
    }
    let gss = pdb.gss().map_err(parse("read global symbol stream"))?;
    normalize_global_data(gss.iter_syms(), sections, &mut database)?;
    validate_references(&stream, &mut database)?;
    database.finish();
    Ok(database)
}

fn parse<E: std::fmt::Display>(operation: &'static str) -> impl FnOnce(E) -> Error {
    move |source| Error::Parse {
        operation,
        detail: source.to_string(),
    }
}

fn utf8(value: &ms_pdb::BStr, operation: &'static str) -> Result<String, Error> {
    String::from_utf8(value.to_vec()).map_err(|_| Error::InvalidUtf8 { operation })
}

pub(crate) fn validate_machine(machine: u16) -> Result<(), Error> {
    if machine == AMD64_MACHINE {
        Ok(())
    } else {
        Err(Error::UnsupportedMachine { machine })
    }
}