pdb-bindgen-codegen 0.1.0

Build-time discovery, PDB acquisition, and binding generation for pdb-bindgen.
Documentation
use super::{
    error::{ActualIdentity, Error, HttpError},
    msf,
};
use crate::PdbIdentity;
use std::{
    fs::{self, File, OpenOptions},
    io::{Read, Write},
    path::{Path, PathBuf},
    sync::atomic::{AtomicU64, Ordering},
};

static TEMP: AtomicU64 = AtomicU64::new(0);

pub(crate) fn key(identity: &PdbIdentity) -> String {
    format!(
        "{:08X}{:04X}{:04X}{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}{:02X}{:X}",
        identity.guid().data1(),
        identity.guid().data2(),
        identity.guid().data3(),
        identity.guid().data4()[0],
        identity.guid().data4()[1],
        identity.guid().data4()[2],
        identity.guid().data4()[3],
        identity.guid().data4()[4],
        identity.guid().data4()[5],
        identity.guid().data4()[6],
        identity.guid().data4()[7],
        identity.age()
    )
}
pub(super) fn path(root: &Path, identity: &PdbIdentity) -> PathBuf {
    root.join(identity.filename())
        .join(key(identity))
        .join(identity.filename())
}

pub(super) fn validate(path: &Path, expected: &PdbIdentity) -> Result<(), Error> {
    let metadata =
        fs::symlink_metadata(path).map_err(|error| Error::io("inspect", path.into(), error))?;
    if metadata.file_type().is_symlink() || !metadata.file_type().is_file() {
        return Err(Error::Cache {
            path: path.into(),
            reason: "entry is not a regular non-symlink file",
        });
    }
    let mut file = File::open(path).map_err(|error| Error::io("open", path.into(), error))?;
    let actual = msf::validate(&mut file, metadata.len())?;
    validate_identity(actual, expected)
}

fn validate_identity(actual: ActualIdentity, expected: &PdbIdentity) -> Result<(), Error> {
    if actual.guid == expected.guid() && actual.age == expected.age() {
        Ok(())
    } else {
        Err(Error::Identity {
            expected: expected.clone(),
            actual,
        })
    }
}

fn safe_dirs(root: &Path, identity: &PdbIdentity) -> Result<PathBuf, Error> {
    fs::create_dir_all(root).map_err(|error| Error::io("create cache root", root.into(), error))?;
    let root_metadata =
        fs::metadata(root).map_err(|error| Error::io("inspect cache root", root.into(), error))?;
    if !root_metadata.is_dir() {
        return Err(Error::Cache {
            path: root.into(),
            reason: "cache root is not a directory",
        });
    }
    let mut parent = root.to_path_buf();
    for component in [identity.filename(), &key(identity)] {
        parent.push(component);
        match fs::symlink_metadata(&parent) {
            Ok(metadata) if metadata.file_type().is_dir() && !metadata.file_type().is_symlink() => {
            }
            Ok(_) => {
                return Err(Error::Cache {
                    path: parent,
                    reason: "cache directory component is a symlink or non-directory",
                });
            }
            Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
                fs::create_dir(&parent)
                    .map_err(|error| Error::io("create cache directory", parent.clone(), error))?;
            }
            Err(error) => return Err(Error::io("inspect cache directory", parent, error)),
        }
    }
    Ok(parent)
}

struct Temp {
    path: PathBuf,
    file: Option<File>,
    armed: bool,
}
impl Temp {
    fn file(&mut self) -> &mut File {
        self.file.as_mut().expect("temporary file is open")
    }

    fn close(&mut self) {
        drop(self.file.take());
    }
}
impl Drop for Temp {
    fn drop(&mut self) {
        self.close();
        if self.armed {
            let _ = fs::remove_file(&self.path);
        }
    }
}

fn create_temp(
    parent: &Path,
    filename: &str,
    candidates: impl IntoIterator<Item = u64>,
) -> Result<Temp, Error> {
    for candidate in candidates {
        let path = parent.join(format!(
            ".{filename}.pdb-bindgen-{}-{candidate}",
            std::process::id()
        ));
        match OpenOptions::new().write(true).create_new(true).open(&path) {
            Ok(file) => {
                return Ok(Temp {
                    path,
                    file: Some(file),
                    armed: true,
                });
            }
            Err(error) if error.kind() == std::io::ErrorKind::AlreadyExists => {}
            Err(error) => return Err(Error::io("create cache temporary", path, error)),
        }
    }
    Err(Error::Cache {
        path: parent.to_path_buf(),
        reason: "temporary name retries exhausted",
    })
}

pub(super) fn publish<R: Read>(
    root: &Path,
    expected: &PdbIdentity,
    mut input: R,
) -> Result<PathBuf, Error> {
    let parent = safe_dirs(root, expected)?;
    let destination = parent.join(expected.filename());
    match fs::symlink_metadata(&destination) {
        Ok(metadata) if metadata.file_type().is_symlink() || !metadata.file_type().is_file() => {
            return Err(Error::Cache {
                path: destination,
                reason: "destination is not a regular non-symlink file",
            });
        }
        Ok(_) => {}
        Err(error) if error.kind() == std::io::ErrorKind::NotFound => {}
        Err(error) => {
            return Err(Error::io("inspect cache destination", destination, error));
        }
    }
    let candidates = (0..64).map(|_| TEMP.fetch_add(1, Ordering::Relaxed));
    let mut temp = create_temp(&parent, expected.filename(), candidates)?;
    let mut superblock = [0; msf::SUPERBLOCK_LEN];
    input
        .read_exact(&mut superblock)
        .map_err(|_| Error::Http(HttpError::BodyLength))?;
    let parsed = msf::parse_superblock(&superblock)?;
    let total = parsed.total()?;
    temp.file()
        .write_all(&superblock)
        .map_err(|error| Error::io("write cache temporary", temp.path.clone(), error))?;
    let mut remaining = total
        .checked_sub(msf::SUPERBLOCK_LEN as u64)
        .ok_or(Error::Http(HttpError::BodyLength))?;
    let mut buffer = [0; 8192];
    while remaining != 0 {
        let take = remaining.min(buffer.len() as u64) as usize;
        let read = input
            .read(&mut buffer[..take])
            .map_err(|error| Error::io("read HTTP body", temp.path.clone(), error))?;
        if read == 0 {
            return Err(Error::Http(HttpError::BodyLength));
        }
        temp.file()
            .write_all(&buffer[..read])
            .map_err(|error| Error::io("write cache temporary", temp.path.clone(), error))?;
        remaining -= read as u64;
    }
    if input
        .read(&mut buffer[..1])
        .map_err(|error| Error::io("read HTTP body", temp.path.clone(), error))?
        != 0
    {
        return Err(Error::Http(HttpError::BodyLength));
    }
    temp.file()
        .flush()
        .map_err(|error| Error::io("flush cache temporary", temp.path.clone(), error))?;
    temp.close();
    validate(&temp.path, expected)?;
    match fs::rename(&temp.path, &destination) {
        Ok(()) => {
            temp.armed = false;
            Ok(destination)
        }
        Err(error) => {
            if validate(&destination, expected).is_ok() {
                return Ok(destination);
            }
            Err(Error::io("publish cache", destination, error))
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn temporary_collisions_never_truncate_sentinels() {
        let root = std::env::temp_dir().join(format!(
            "pdb-bindgen-cache-collision-{}",
            std::process::id()
        ));
        let _ = fs::remove_dir_all(&root);
        fs::create_dir(&root).expect("create collision directory");
        let filename = "fixture.pdb";
        let path = |candidate| {
            root.join(format!(
                ".{filename}.pdb-bindgen-{}-{candidate}",
                std::process::id()
            ))
        };
        fs::write(path(10), b"first").expect("first sentinel");
        fs::write(path(11), b"second").expect("second sentinel");

        let temp = create_temp(&root, filename, 10..13).expect("third candidate succeeds");
        assert_eq!(fs::read(path(10)).expect("first sentinel"), b"first");
        assert_eq!(fs::read(path(11)).expect("second sentinel"), b"second");
        assert_eq!(temp.path, path(12));
        drop(temp);
        assert!(!path(12).exists());

        let Err(error) = create_temp(&root, filename, 10..12) else {
            panic!("all candidates must collide");
        };
        assert!(error.to_string().contains("retries exhausted"));
        assert_eq!(fs::read(path(10)).expect("first sentinel"), b"first");
        assert_eq!(fs::read(path(11)).expect("second sentinel"), b"second");
        fs::remove_dir_all(root).expect("remove collision directory");
    }
}