pdb-bindgen-codegen 0.1.0

Build-time discovery, PDB acquisition, and binding generation for pdb-bindgen.
Documentation
use pdb_bindgen_macro_support::{
    FragmentId, ManifestError, encode_manifest, logical_fragment_path, manifest_entries,
    manifest_path, parse_manifest, relative_fragment_path_from_logical,
};
use std::collections::BTreeMap;
use std::error::Error;
use std::fmt;
use std::fs::{self, OpenOptions};
use std::io::{ErrorKind, Write};
use std::path::{Path, PathBuf};

const TEMP_ATTEMPTS: u32 = 16;

#[derive(Default)]
pub(crate) struct GenerationSet {
    fragments: BTreeMap<String, Vec<u8>>,
}

impl GenerationSet {
    pub(crate) fn insert(&mut self, id: FragmentId<'_>, bytes: Vec<u8>) -> Result<(), OutputError> {
        let path = logical_fragment_path(id);
        match self.fragments.entry(path.clone()) {
            std::collections::btree_map::Entry::Vacant(entry) => {
                entry.insert(bytes);
                Ok(())
            }
            std::collections::btree_map::Entry::Occupied(_) => Err(OutputError::Duplicate(path)),
        }
    }

    #[cfg(test)]
    pub(crate) fn fragments_for_test(&self) -> &BTreeMap<String, Vec<u8>> {
        &self.fragments
    }

    pub(crate) fn publish(&self, out_dir: &Path) -> Result<(), OutputError> {
        require_directory(out_dir, "inspect output directory")?;
        let desired: Vec<_> = self
            .fragments
            .iter()
            .map(|(path, bytes)| (path.as_str(), bytes.as_slice()))
            .collect();
        let manifest_bytes =
            encode_manifest(&manifest_entries(desired).map_err(OutputError::Manifest)?)
                .map_err(OutputError::Manifest)?;
        let manifest = manifest_path(out_dir);
        verify_parents(
            out_dir,
            manifest
                .parent()
                .ok_or_else(|| OutputError::UnsafeTarget(manifest.clone()))?,
        )?;
        inspect_existing_regular(&manifest, "inspect manifest")?;
        let previous = match fs::read(&manifest) {
            Ok(bytes) => parse_manifest(&bytes).map_err(OutputError::Manifest)?,
            Err(error) if error.kind() == ErrorKind::NotFound => Vec::new(),
            Err(source) => return Err(OutputError::io("read manifest", manifest.clone(), source)),
        };

        for entry in &previous {
            let target = checked_target(out_dir, &entry.path, false)?;
            inspect_existing_regular(&target, "inspect previous fragment")?;
        }
        let mut changes = Vec::new();
        for (logical, bytes) in &self.fragments {
            let target = checked_target(out_dir, logical, false)?;
            match fs::symlink_metadata(&target) {
                Ok(metadata) if metadata.file_type().is_file() => {
                    let existing = fs::read(&target).map_err(|source| {
                        OutputError::io("read fragment", target.clone(), source)
                    })?;
                    if existing != *bytes {
                        changes.push((target, bytes.as_slice()));
                    }
                }
                Ok(_) => return Err(OutputError::UnsafeTarget(target)),
                Err(error) if error.kind() == ErrorKind::NotFound => {
                    changes.push((target, bytes.as_slice()))
                }
                Err(source) => return Err(OutputError::io("inspect fragment", target, source)),
            }
        }

        let manifest_changed = match fs::read(&manifest) {
            Ok(existing) => existing != manifest_bytes,
            Err(error) if error.kind() == ErrorKind::NotFound => true,
            Err(source) => return Err(OutputError::io("read manifest", manifest.clone(), source)),
        };
        let mut staged = Staged::default();
        for (target, bytes) in &changes {
            let parent = target
                .parent()
                .ok_or_else(|| OutputError::UnsafeTarget(target.clone()))?;
            ensure_parents(out_dir, parent)?;
            let temp = stage(parent, "fragment", bytes, staged.next)?;
            staged.next += 1;
            staged.files.push((temp, target.clone()));
        }
        if manifest_changed {
            let parent = manifest
                .parent()
                .ok_or_else(|| OutputError::UnsafeTarget(manifest.clone()))?;
            ensure_parents(out_dir, parent)?;
            let temp = stage(parent, "manifest", &manifest_bytes, staged.next)?;
            staged.files.push((temp, manifest.clone()));
        }
        let manifest_index = if manifest_changed {
            Some(staged.files.len() - 1)
        } else {
            None
        };
        let fragment_count = staged.files.len() - usize::from(manifest_changed);
        for (temp, target) in &staged.files[..fragment_count] {
            fs::rename(temp, target)
                .map_err(|source| OutputError::io("publish fragment", target.clone(), source))?;
        }
        for entry in previous {
            if !self.fragments.contains_key(&entry.path) {
                let target = checked_target(out_dir, &entry.path, false)?;
                match fs::remove_file(&target) {
                    Ok(()) => clean_empty_ancestors(out_dir, target.parent().unwrap())?,
                    Err(error) if error.kind() == ErrorKind::NotFound => {
                        clean_empty_ancestors(out_dir, target.parent().unwrap())?
                    }
                    Err(source) => {
                        return Err(OutputError::io("remove stale fragment", target, source));
                    }
                }
            }
        }
        if let Some(index) = manifest_index {
            let (temp, target) = &staged.files[index];
            fs::rename(temp, target)
                .map_err(|source| OutputError::io("publish manifest", target.clone(), source))?;
        }
        staged.files.clear();
        Ok(())
    }
}

#[derive(Default)]
struct Staged {
    files: Vec<(PathBuf, PathBuf)>,
    next: u32,
}
impl Drop for Staged {
    fn drop(&mut self) {
        for (temp, _) in &self.files {
            let _ = fs::remove_file(temp);
        }
    }
}

struct TempFile(Option<PathBuf>);
impl TempFile {
    fn path(&self) -> &Path {
        self.0.as_deref().expect("staged temporary path is present")
    }

    fn disarm(mut self) -> PathBuf {
        self.0.take().expect("staged temporary path is present")
    }
}
impl Drop for TempFile {
    fn drop(&mut self) {
        if let Some(path) = &self.0 {
            let _ = fs::remove_file(path);
        }
    }
}

fn stage(parent: &Path, label: &str, bytes: &[u8], sequence: u32) -> Result<PathBuf, OutputError> {
    for attempt in 0..TEMP_ATTEMPTS {
        let path = parent.join(format!(
            ".pdb-bindgen-{label}-{}-{sequence}-{attempt}.tmp",
            std::process::id()
        ));
        match OpenOptions::new().write(true).create_new(true).open(&path) {
            Ok(mut file) => {
                let temp = TempFile(Some(path));
                let result = file.write_all(bytes).and_then(|()| file.flush());
                drop(file);
                result.map_err(|source| {
                    OutputError::io("stage output", temp.path().to_path_buf(), source)
                })?;
                return Ok(temp.disarm());
            }
            Err(error) if error.kind() == ErrorKind::AlreadyExists => continue,
            Err(source) => return Err(OutputError::io("create staged output", path, source)),
        }
    }
    Err(OutputError::StageExhausted(parent.to_path_buf()))
}

fn inspect_existing_regular(path: &Path, operation: &'static str) -> Result<(), OutputError> {
    match fs::symlink_metadata(path) {
        Ok(metadata) if metadata.file_type().is_file() => Ok(()),
        Ok(_) => Err(OutputError::UnsafeTarget(path.to_path_buf())),
        Err(error) if error.kind() == ErrorKind::NotFound => Ok(()),
        Err(source) => Err(OutputError::io(operation, path.to_path_buf(), source)),
    }
}

fn require_directory(path: &Path, operation: &'static str) -> Result<(), OutputError> {
    match fs::symlink_metadata(path) {
        Ok(metadata) if metadata.file_type().is_dir() => Ok(()),
        Ok(_) => Err(OutputError::UnsafeTarget(path.to_path_buf())),
        Err(source) => Err(OutputError::io(operation, path.to_path_buf(), source)),
    }
}
fn ensure_parents(out_dir: &Path, parent: &Path) -> Result<(), OutputError> {
    let relative = parent
        .strip_prefix(out_dir)
        .map_err(|_| OutputError::UnsafeTarget(parent.to_path_buf()))?;
    let mut current = out_dir.to_path_buf();
    for component in relative.components() {
        current.push(component.as_os_str());
        match fs::symlink_metadata(&current) {
            Ok(metadata) if metadata.file_type().is_dir() => {}
            Ok(_) => return Err(OutputError::UnsafeTarget(current)),
            Err(error) if error.kind() == ErrorKind::NotFound => {
                fs::create_dir(&current).map_err(|source| {
                    OutputError::io("create output directory", current.clone(), source)
                })?
            }
            Err(source) => {
                return Err(OutputError::io("inspect output directory", current, source));
            }
        }
    }
    Ok(())
}
fn verify_parents(out_dir: &Path, parent: &Path) -> Result<(), OutputError> {
    let relative = parent
        .strip_prefix(out_dir)
        .map_err(|_| OutputError::UnsafeTarget(parent.to_path_buf()))?;
    let mut current = out_dir.to_path_buf();
    for component in relative.components() {
        current.push(component.as_os_str());
        match fs::symlink_metadata(&current) {
            Ok(metadata) if metadata.file_type().is_dir() => {}
            Ok(_) => return Err(OutputError::UnsafeTarget(current)),
            Err(error) if error.kind() == ErrorKind::NotFound => break,
            Err(source) => {
                return Err(OutputError::io("inspect output directory", current, source));
            }
        }
    }
    Ok(())
}
fn checked_target(
    out_dir: &Path,
    logical: &str,
    create_parent: bool,
) -> Result<PathBuf, OutputError> {
    let relative = relative_fragment_path_from_logical(logical).map_err(OutputError::Manifest)?;
    let target = out_dir.join(relative);
    if let Some(parent) = target.parent() {
        if create_parent {
            ensure_parents(out_dir, parent)?;
        } else {
            verify_parents(out_dir, parent)?;
        }
    }
    let generated = out_dir.join("pdb-bindgen/generated");
    if !target.starts_with(&generated) {
        return Err(OutputError::UnsafeTarget(target));
    }
    Ok(target)
}
fn clean_empty_ancestors(out_dir: &Path, start: &Path) -> Result<(), OutputError> {
    let stop = out_dir.join("pdb-bindgen/generated");
    let mut current = start.to_path_buf();
    while current.starts_with(&stop) && current != stop {
        match fs::remove_dir(&current) {
            Ok(()) => {}
            Err(error) if error.kind() == ErrorKind::DirectoryNotEmpty => break,
            Err(error) if error.kind() == ErrorKind::NotFound => {}
            Err(source) => {
                return Err(OutputError::io(
                    "clean generated directory",
                    current,
                    source,
                ));
            }
        }
        let Some(parent) = current.parent() else {
            break;
        };
        current = parent.to_path_buf();
    }
    Ok(())
}

#[derive(Debug)]
pub(crate) enum OutputError {
    Duplicate(String),
    UnsafeTarget(PathBuf),
    StageExhausted(PathBuf),
    Manifest(ManifestError),
    Io {
        operation: &'static str,
        path: PathBuf,
        source: std::io::Error,
    },
}
impl OutputError {
    fn io(operation: &'static str, path: PathBuf, source: std::io::Error) -> Self {
        Self::Io {
            operation,
            path,
            source,
        }
    }
}
impl fmt::Display for OutputError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::Duplicate(path) => write!(f, "duplicate generated fragment: {path}"),
            Self::UnsafeTarget(path) => {
                write!(f, "unsafe generated output target: {}", path.display())
            }
            Self::StageExhausted(path) => {
                write!(f, "could not allocate staged output in {}", path.display())
            }
            Self::Manifest(error) => error.fmt(f),
            Self::Io {
                operation, path, ..
            } => write!(f, "{operation}: {}", path.display()),
        }
    }
}
impl Error for OutputError {
    fn source(&self) -> Option<&(dyn Error + 'static)> {
        match self {
            Self::Manifest(error) => Some(error),
            Self::Io { source, .. } => Some(source),
            _ => None,
        }
    }
}