1use crate::ConfigError;
2use std::error::Error;
3use std::fmt;
4use std::str::FromStr;
5
6#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
13pub struct PdbGuid {
14 data1: u32,
15 data2: u16,
16 data3: u16,
17 data4: [u8; 8],
18}
19
20impl PdbGuid {
21 #[must_use]
23 pub const fn from_fields(data1: u32, data2: u16, data3: u16, data4: [u8; 8]) -> Self {
24 Self {
25 data1,
26 data2,
27 data3,
28 data4,
29 }
30 }
31
32 #[must_use]
34 pub const fn data1(self) -> u32 {
35 self.data1
36 }
37
38 #[must_use]
40 pub const fn data2(self) -> u16 {
41 self.data2
42 }
43
44 #[must_use]
46 pub const fn data3(self) -> u16 {
47 self.data3
48 }
49
50 #[must_use]
52 pub const fn data4(self) -> [u8; 8] {
53 self.data4
54 }
55}
56
57impl fmt::Display for PdbGuid {
58 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
59 write!(
60 formatter,
61 "{:08x}-{:04x}-{:04x}-{:02x}{:02x}-{:02x}{:02x}{:02x}{:02x}{:02x}{:02x}",
62 self.data1,
63 self.data2,
64 self.data3,
65 self.data4[0],
66 self.data4[1],
67 self.data4[2],
68 self.data4[3],
69 self.data4[4],
70 self.data4[5],
71 self.data4[6],
72 self.data4[7]
73 )
74 }
75}
76
77impl FromStr for PdbGuid {
78 type Err = ParsePdbGuidError;
79
80 fn from_str(input: &str) -> Result<Self, Self::Err> {
81 parse_guid(input)
82 }
83}
84
85#[derive(Clone, Copy, Debug, Eq, PartialEq)]
87#[non_exhaustive]
88pub enum GuidErrorKind {
89 InvalidLength,
91 InvalidSeparator,
93 InvalidHexDigit,
95}
96
97impl fmt::Display for GuidErrorKind {
98 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
99 formatter.write_str(match self {
100 Self::InvalidLength => "expected exactly 36 bytes",
101 Self::InvalidSeparator => "expected hyphens in 8-4-4-4-12 positions",
102 Self::InvalidHexDigit => "expected only hexadecimal digits between hyphens",
103 })
104 }
105}
106
107#[derive(Clone, Debug, Eq, PartialEq)]
109pub struct ParsePdbGuidError {
110 kind: GuidErrorKind,
111}
112
113impl ParsePdbGuidError {
114 #[must_use]
116 pub const fn kind(&self) -> GuidErrorKind {
117 self.kind
118 }
119}
120
121impl fmt::Display for ParsePdbGuidError {
122 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
123 write!(formatter, "invalid PDB GUID: {}", self.kind)
124 }
125}
126
127impl Error for ParsePdbGuidError {}
128
129#[derive(Clone, Debug, Eq, PartialEq)]
136pub struct PdbIdentity {
137 filename: String,
138 guid: PdbGuid,
139 age: u32,
140}
141
142impl PdbIdentity {
143 pub fn new(filename: impl Into<String>, guid: PdbGuid, age: u32) -> Result<Self, ConfigError> {
150 let filename = filename.into();
151 validate_pdb_filename(&filename)?;
152 Ok(Self {
153 filename,
154 guid,
155 age,
156 })
157 }
158
159 #[must_use]
161 pub fn filename(&self) -> &str {
162 &self.filename
163 }
164
165 #[must_use]
167 pub const fn guid(&self) -> PdbGuid {
168 self.guid
169 }
170
171 #[must_use]
173 pub const fn age(&self) -> u32 {
174 self.age
175 }
176}
177#[derive(Clone, Copy, Debug, Eq, PartialEq)]
179#[non_exhaustive]
180pub enum PdbFilenameErrorKind {
181 Empty,
183 Separator,
185 NotFileName,
187 Nul,
189}
190
191impl fmt::Display for PdbFilenameErrorKind {
192 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
193 formatter.write_str(match self {
194 Self::Empty => "filename must not be empty",
195 Self::Separator => "filename must not contain path separators",
196 Self::NotFileName => "expected a filename, not `.` or `..`",
197 Self::Nul => "filename must not contain NUL",
198 })
199 }
200}
201fn parse_guid(input: &str) -> Result<PdbGuid, ParsePdbGuidError> {
202 let bytes = input.as_bytes();
203 if bytes.len() != 36 {
204 return Err(ParsePdbGuidError {
205 kind: GuidErrorKind::InvalidLength,
206 });
207 }
208 if [8, 13, 18, 23]
209 .into_iter()
210 .any(|index| bytes[index] != b'-')
211 {
212 return Err(ParsePdbGuidError {
213 kind: GuidErrorKind::InvalidSeparator,
214 });
215 }
216
217 let data1 = parse_hex_u32(&bytes[0..8])?;
218 let data2 = parse_hex_u16(&bytes[9..13])?;
219 let data3 = parse_hex_u16(&bytes[14..18])?;
220 let mut data4 = [0_u8; 8];
221 data4[0] = parse_hex_byte(&bytes[19..21])?;
222 data4[1] = parse_hex_byte(&bytes[21..23])?;
223 for (slot, index) in data4[2..].iter_mut().zip((24..36).step_by(2)) {
224 *slot = parse_hex_byte(&bytes[index..index + 2])?;
225 }
226 Ok(PdbGuid::from_fields(data1, data2, data3, data4))
227}
228
229fn parse_hex_u32(bytes: &[u8]) -> Result<u32, ParsePdbGuidError> {
230 bytes.iter().try_fold(0_u32, |value, byte| {
231 hex_value(*byte)
232 .map(|digit| (value << 4) | u32::from(digit))
233 .ok_or(ParsePdbGuidError {
234 kind: GuidErrorKind::InvalidHexDigit,
235 })
236 })
237}
238
239fn parse_hex_u16(bytes: &[u8]) -> Result<u16, ParsePdbGuidError> {
240 parse_hex_u32(bytes).map(|value| value as u16)
241}
242
243fn parse_hex_byte(bytes: &[u8]) -> Result<u8, ParsePdbGuidError> {
244 parse_hex_u32(bytes).map(|value| value as u8)
245}
246
247const fn hex_value(byte: u8) -> Option<u8> {
248 match byte {
249 b'0'..=b'9' => Some(byte - b'0'),
250 b'a'..=b'f' => Some(byte - b'a' + 10),
251 b'A'..=b'F' => Some(byte - b'A' + 10),
252 _ => None,
253 }
254}
255
256fn validate_pdb_filename(filename: &str) -> Result<(), ConfigError> {
257 let reason = if filename.is_empty() {
258 Some(PdbFilenameErrorKind::Empty)
259 } else if filename.contains(['/', '\\']) {
260 Some(PdbFilenameErrorKind::Separator)
261 } else if filename == "." || filename == ".." {
262 Some(PdbFilenameErrorKind::NotFileName)
263 } else if filename.contains('\0') {
264 Some(PdbFilenameErrorKind::Nul)
265 } else {
266 None
267 };
268
269 match reason {
270 Some(reason) => Err(ConfigError::InvalidPdbFilename {
271 filename: filename.to_owned(),
272 reason,
273 }),
274 None => Ok(()),
275 }
276}
277
278#[cfg(test)]
279mod tests {
280 use super::*;
281
282 const GUID_TEXT: &str = "12345678-9abc-def0-1234-56789abcdef0";
283
284 #[test]
285 fn guid_round_trips_with_conventional_field_semantics() {
286 let guid: PdbGuid = "12345678-9ABC-DEF0-1234-56789ABCDEF0"
287 .parse()
288 .expect("valid uppercase GUID");
289
290 assert_eq!(guid.data1(), 0x1234_5678);
291 assert_eq!(guid.data2(), 0x9abc);
292 assert_eq!(guid.data3(), 0xdef0);
293 assert_eq!(
294 guid.data4(),
295 [0x12, 0x34, 0x56, 0x78, 0x9a, 0xbc, 0xde, 0xf0]
296 );
297 assert_eq!(guid.to_string(), GUID_TEXT);
298 assert_eq!(guid.to_string().parse::<PdbGuid>(), Ok(guid));
299 }
300
301 #[test]
302 fn guid_boundaries_round_trip() {
303 for guid in [
304 PdbGuid::from_fields(0, 0, 0, [0; 8]),
305 PdbGuid::from_fields(u32::MAX, u16::MAX, u16::MAX, [u8::MAX; 8]),
306 ] {
307 assert_eq!(guid.to_string().parse::<PdbGuid>(), Ok(guid));
308 }
309 }
310
311 #[test]
312 fn malformed_guids_report_precise_categories() {
313 let cases = [
314 ("", GuidErrorKind::InvalidLength),
315 (
316 "123456789abc-def0-1234-56789abcdef0",
317 GuidErrorKind::InvalidLength,
318 ),
319 (
320 "12345678-9abc-def0-1234-56789abcdeg0",
321 GuidErrorKind::InvalidHexDigit,
322 ),
323 (
324 "12345678-9abc-def0-1234-56789abcdef00",
325 GuidErrorKind::InvalidLength,
326 ),
327 (
328 "12345678_9abc-def0-1234-56789abcdef0",
329 GuidErrorKind::InvalidSeparator,
330 ),
331 ];
332 for (text, expected) in cases {
333 let error = text.parse::<PdbGuid>().expect_err("GUID must fail");
334 assert_eq!(error.kind(), expected, "input {text:?}");
335 assert!(Error::source(&error).is_none());
336 }
337 }
338
339 #[test]
340 fn identity_accepts_age_zero_and_exposes_authoritative_fields() {
341 let guid = GUID_TEXT.parse().expect("valid GUID");
342 let identity = PdbIdentity::new("ntkrnlmp.pdb", guid, 0).expect("valid identity");
343
344 assert_eq!(identity.filename(), "ntkrnlmp.pdb");
345 assert_eq!(identity.guid(), guid);
346 assert_eq!(identity.age(), 0);
347 }
348
349 #[test]
350 fn identity_rejects_non_filename_forms_without_requiring_pdb_extension() {
351 assert!(PdbIdentity::new("kernel.debug", GUID_TEXT.parse().unwrap(), 1).is_ok());
352 let cases = [
353 ("", PdbFilenameErrorKind::Empty),
354 ("dir/file.pdb", PdbFilenameErrorKind::Separator),
355 (r"dir\file.pdb", PdbFilenameErrorKind::Separator),
356 (".", PdbFilenameErrorKind::NotFileName),
357 ("..", PdbFilenameErrorKind::NotFileName),
358 ("bad\0name", PdbFilenameErrorKind::Nul),
359 ];
360 for (filename, expected) in cases {
361 let error = PdbIdentity::new(filename, GUID_TEXT.parse().unwrap(), 1)
362 .expect_err("filename must fail");
363 assert_eq!(
364 error,
365 ConfigError::InvalidPdbFilename {
366 filename: filename.to_owned(),
367 reason: expected,
368 }
369 );
370 assert!(error.to_string().contains(&expected.to_string()));
371 assert!(Error::source(&error).is_none());
372 }
373 }
374}