use crate::ConfigError;
use std::error::Error;
use std::fmt;
use std::str::FromStr;
#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
pub struct PdbGuid {
data1: u32,
data2: u16,
data3: u16,
data4: [u8; 8],
}
impl PdbGuid {
#[must_use]
pub const fn from_fields(data1: u32, data2: u16, data3: u16, data4: [u8; 8]) -> Self {
Self {
data1,
data2,
data3,
data4,
}
}
#[must_use]
pub const fn data1(self) -> u32 {
self.data1
}
#[must_use]
pub const fn data2(self) -> u16 {
self.data2
}
#[must_use]
pub const fn data3(self) -> u16 {
self.data3
}
#[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)
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum GuidErrorKind {
InvalidLength,
InvalidSeparator,
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",
})
}
}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct ParsePdbGuidError {
kind: GuidErrorKind,
}
impl ParsePdbGuidError {
#[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 {}
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct PdbIdentity {
filename: String,
guid: PdbGuid,
age: u32,
}
impl PdbIdentity {
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,
})
}
#[must_use]
pub fn filename(&self) -> &str {
&self.filename
}
#[must_use]
pub const fn guid(&self) -> PdbGuid {
self.guid
}
#[must_use]
pub const fn age(&self) -> u32 {
self.age
}
}
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
#[non_exhaustive]
pub enum PdbFilenameErrorKind {
Empty,
Separator,
NotFileName,
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());
}
}
}