pdb-bindgen-codegen 0.1.0

Build-time discovery, PDB acquisition, and binding generation for pdb-bindgen.
Documentation
use crate::ConfigError;
use std::error::Error;
use std::fmt;
use std::str::FromStr;

/// A PDB GUID represented by its conventional GUID fields.
///
/// The numeric fields preserve GUID semantics and avoid the byte-order ambiguity
/// of a bare 16-byte array. [`Display`](fmt::Display) and [`FromStr`] use the
/// canonical hyphenated `8-4-4-4-12` form. Parsing is case-insensitive and
/// formatting always uses lowercase hexadecimal.
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct PdbGuid {
    data1: u32,
    data2: u16,
    data3: u16,
    data4: [u8; 8],
}

impl PdbGuid {
    /// Creates a GUID from its conventional fields.
    #[must_use]
    pub const fn from_fields(data1: u32, data2: u16, data3: u16, data4: [u8; 8]) -> Self {
        Self {
            data1,
            data2,
            data3,
            data4,
        }
    }

    /// Returns the first 32-bit GUID field.
    #[must_use]
    pub const fn data1(self) -> u32 {
        self.data1
    }

    /// Returns the second 16-bit GUID field.
    #[must_use]
    pub const fn data2(self) -> u16 {
        self.data2
    }

    /// Returns the third 16-bit GUID field.
    #[must_use]
    pub const fn data3(self) -> u16 {
        self.data3
    }

    /// Returns the final eight GUID bytes in display order.
    #[must_use]
    pub const fn data4(self) -> [u8; 8] {
        self.data4
    }
}

impl fmt::Display for PdbGuid {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(
            formatter,
            "{:08x}-{:04x}-{:04x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
            self.data1,
            self.data2,
            self.data3,
            self.data4[0],
            self.data4[1],
            self.data4[2],
            self.data4[3],
            self.data4[4],
            self.data4[5],
            self.data4[6],
            self.data4[7]
        )
    }
}

impl FromStr for PdbGuid {
    type Err = ParsePdbGuidError;

    fn from_str(input: &str) -> Result<Self, Self::Err> {
        parse_guid(input)
    }
}

/// Describes why canonical PDB GUID text could not be parsed.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GuidErrorKind {
    /// The text is not exactly 36 bytes long.
    InvalidLength,
    /// A canonical group separator is absent or misplaced.
    InvalidSeparator,
    /// A field contains a non-hexadecimal character.
    InvalidHexDigit,
}

impl fmt::Display for GuidErrorKind {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::InvalidLength => "expected exactly 36 bytes",
            Self::InvalidSeparator => "expected hyphens in 8-4-4-4-12 positions",
            Self::InvalidHexDigit => "expected only hexadecimal digits between hyphens",
        })
    }
}

/// An error returned when canonical PDB GUID text is malformed.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParsePdbGuidError {
    kind: GuidErrorKind,
}

impl ParsePdbGuidError {
    /// Returns the malformed-text category.
    #[must_use]
    pub const fn kind(&self) -> GuidErrorKind {
        self.kind
    }
}

impl fmt::Display for ParsePdbGuidError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "invalid PDB GUID: {}", self.kind)
    }
}

impl Error for ParsePdbGuidError {}

/// An explicit Symbol Server PDB identity.
///
/// `filename` is a logical filename used in Symbol Server addressing, not a
/// filesystem path. Age zero is accepted because the CodeView identity stores
/// age as an unrestricted 32-bit value; this configuration layer preserves the
/// authoritative identity supplied by the user.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PdbIdentity {
    filename: String,
    guid: PdbGuid,
    age: u32,
}

impl PdbIdentity {
    /// Creates and validates an explicit PDB identity.
    ///
    /// # Errors
    ///
    /// Returns [`ConfigError::InvalidPdbFilename`] when `filename` is empty,
    /// contains a path separator or NUL, or names `.` or `..`.
    pub fn new(filename: impl Into<String>, guid: PdbGuid, age: u32) -> Result<Self, ConfigError> {
        let filename = filename.into();
        validate_pdb_filename(&filename)?;
        Ok(Self {
            filename,
            guid,
            age,
        })
    }

    /// Returns the logical PDB filename.
    #[must_use]
    pub fn filename(&self) -> &str {
        &self.filename
    }

    /// Returns the authoritative PDB GUID.
    #[must_use]
    pub const fn guid(&self) -> PdbGuid {
        self.guid
    }

    /// Returns the authoritative PDB age.
    #[must_use]
    pub const fn age(&self) -> u32 {
        self.age
    }
}
/// Describes why a logical PDB filename is invalid.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum PdbFilenameErrorKind {
    /// The filename is empty.
    Empty,
    /// The filename contains `/` or `\\`.
    Separator,
    /// The filename is `.` or `..`.
    NotFileName,
    /// The filename contains NUL.
    Nul,
}

impl fmt::Display for PdbFilenameErrorKind {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        formatter.write_str(match self {
            Self::Empty => "filename must not be empty",
            Self::Separator => "filename must not contain path separators",
            Self::NotFileName => "expected a filename, not `.` or `..`",
            Self::Nul => "filename must not contain NUL",
        })
    }
}
fn parse_guid(input: &str) -> Result<PdbGuid, ParsePdbGuidError> {
    let bytes = input.as_bytes();
    if bytes.len() != 36 {
        return Err(ParsePdbGuidError {
            kind: GuidErrorKind::InvalidLength,
        });
    }
    if [8, 13, 18, 23]
        .into_iter()
        .any(|index| bytes[index] != b'-')
    {
        return Err(ParsePdbGuidError {
            kind: GuidErrorKind::InvalidSeparator,
        });
    }

    let data1 = parse_hex_u32(&bytes[0..8])?;
    let data2 = parse_hex_u16(&bytes[9..13])?;
    let data3 = parse_hex_u16(&bytes[14..18])?;
    let mut data4 = [0_u8; 8];
    data4[0] = parse_hex_byte(&bytes[19..21])?;
    data4[1] = parse_hex_byte(&bytes[21..23])?;
    for (slot, index) in data4[2..].iter_mut().zip((24..36).step_by(2)) {
        *slot = parse_hex_byte(&bytes[index..index + 2])?;
    }
    Ok(PdbGuid::from_fields(data1, data2, data3, data4))
}

fn parse_hex_u32(bytes: &[u8]) -> Result<u32, ParsePdbGuidError> {
    bytes.iter().try_fold(0_u32, |value, byte| {
        hex_value(*byte)
            .map(|digit| (value << 4) | u32::from(digit))
            .ok_or(ParsePdbGuidError {
                kind: GuidErrorKind::InvalidHexDigit,
            })
    })
}

fn parse_hex_u16(bytes: &[u8]) -> Result<u16, ParsePdbGuidError> {
    parse_hex_u32(bytes).map(|value| value as u16)
}

fn parse_hex_byte(bytes: &[u8]) -> Result<u8, ParsePdbGuidError> {
    parse_hex_u32(bytes).map(|value| value as u8)
}

const fn hex_value(byte: u8) -> Option<u8> {
    match byte {
        b'0'..=b'9' => Some(byte - b'0'),
        b'a'..=b'f' => Some(byte - b'a' + 10),
        b'A'..=b'F' => Some(byte - b'A' + 10),
        _ => None,
    }
}

fn validate_pdb_filename(filename: &str) -> Result<(), ConfigError> {
    let reason = if filename.is_empty() {
        Some(PdbFilenameErrorKind::Empty)
    } else if filename.contains(['/', '\\']) {
        Some(PdbFilenameErrorKind::Separator)
    } else if filename == "." || filename == ".." {
        Some(PdbFilenameErrorKind::NotFileName)
    } else if filename.contains('\0') {
        Some(PdbFilenameErrorKind::Nul)
    } else {
        None
    };

    match reason {
        Some(reason) => Err(ConfigError::InvalidPdbFilename {
            filename: filename.to_owned(),
            reason,
        }),
        None => Ok(()),
    }
}

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

    const GUID_TEXT: &str = "12345678-9abc-def0-1234-56789abcdef0";

    #[test]
    fn guid_round_trips_with_conventional_field_semantics() {
        let guid: PdbGuid = "12345678-9ABC-DEF0-1234-56789ABCDEF0"
            .parse()
            .expect("valid uppercase GUID");

        assert_eq!(guid.data1(), 0x1234_5678);
        assert_eq!(guid.data2(), 0x9abc);
        assert_eq!(guid.data3(), 0xdef0);
        assert_eq!(
            guid.data4(),
            [0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0]
        );
        assert_eq!(guid.to_string(), GUID_TEXT);
        assert_eq!(guid.to_string().parse::<PdbGuid>(), Ok(guid));
    }

    #[test]
    fn guid_boundaries_round_trip() {
        for guid in [
            PdbGuid::from_fields(0, 0, 0, [0; 8]),
            PdbGuid::from_fields(u32::MAX, u16::MAX, u16::MAX, [u8::MAX; 8]),
        ] {
            assert_eq!(guid.to_string().parse::<PdbGuid>(), Ok(guid));
        }
    }

    #[test]
    fn malformed_guids_report_precise_categories() {
        let cases = [
            ("", GuidErrorKind::InvalidLength),
            (
                "123456789abc-def0-1234-56789abcdef0",
                GuidErrorKind::InvalidLength,
            ),
            (
                "12345678-9abc-def0-1234-56789abcdeg0",
                GuidErrorKind::InvalidHexDigit,
            ),
            (
                "12345678-9abc-def0-1234-56789abcdef00",
                GuidErrorKind::InvalidLength,
            ),
            (
                "12345678_9abc-def0-1234-56789abcdef0",
                GuidErrorKind::InvalidSeparator,
            ),
        ];
        for (text, expected) in cases {
            let error = text.parse::<PdbGuid>().expect_err("GUID must fail");
            assert_eq!(error.kind(), expected, "input {text:?}");
            assert!(Error::source(&error).is_none());
        }
    }

    #[test]
    fn identity_accepts_age_zero_and_exposes_authoritative_fields() {
        let guid = GUID_TEXT.parse().expect("valid GUID");
        let identity = PdbIdentity::new("ntkrnlmp.pdb", guid, 0).expect("valid identity");

        assert_eq!(identity.filename(), "ntkrnlmp.pdb");
        assert_eq!(identity.guid(), guid);
        assert_eq!(identity.age(), 0);
    }

    #[test]
    fn identity_rejects_non_filename_forms_without_requiring_pdb_extension() {
        assert!(PdbIdentity::new("kernel.debug", GUID_TEXT.parse().unwrap(), 1).is_ok());
        let cases = [
            ("", PdbFilenameErrorKind::Empty),
            ("dir/file.pdb", PdbFilenameErrorKind::Separator),
            (r"dir\file.pdb", PdbFilenameErrorKind::Separator),
            (".", PdbFilenameErrorKind::NotFileName),
            ("..", PdbFilenameErrorKind::NotFileName),
            ("bad\0name", PdbFilenameErrorKind::Nul),
        ];
        for (filename, expected) in cases {
            let error = PdbIdentity::new(filename, GUID_TEXT.parse().unwrap(), 1)
                .expect_err("filename must fail");
            assert_eq!(
                error,
                ConfigError::InvalidPdbFilename {
                    filename: filename.to_owned(),
                    reason: expected,
                }
            );
            assert!(error.to_string().contains(&expected.to_string()));
            assert!(Error::source(&error).is_none());
        }
    }
}