Skip to content

Commit c0e6878

Browse files
Manciukicbchalios
authored andcommitted
fix(pci): do not panic on invalid BDF during deserialization
Correctly handle invalid Bdf by returning an error to the deserializer. This bug was caught by the fuzzer. Signed-off-by: Riccardo Mancini <[email protected]> Signed-off-by: Babis Chalios <[email protected]>
1 parent 2c3c03d commit c0e6878

File tree

1 file changed

+17
-10
lines changed

1 file changed

+17
-10
lines changed

src/pci/src/lib.rs

Lines changed: 17 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ impl Visitor<'_> for PciBdfVisitor {
7171
where
7272
E: serde::de::Error,
7373
{
74-
Ok(v.into())
74+
PciBdf::from_str(v).map_err(serde::de::Error::custom)
7575
}
7676
}
7777

@@ -176,24 +176,31 @@ impl Display for PciBdf {
176176
}
177177
}
178178

179+
/// Errors associated with parsing a BDF string.
180+
#[derive(Debug, thiserror::Error, displaydoc::Display)]
181+
pub enum PciBdfParseError {
182+
/// Unable to parse bus/device/function number hex: {0}
183+
InvalidHex(#[from] ParseIntError),
184+
/// Invalid format: {0} (expected format: 0000:00:00.0)
185+
InvalidFormat(String),
186+
}
187+
179188
impl FromStr for PciBdf {
180-
type Err = ParseIntError;
189+
type Err = PciBdfParseError;
181190

182191
fn from_str(s: &str) -> Result<Self, Self::Err> {
183192
let items: Vec<&str> = s.split('.').collect();
184-
assert_eq!(items.len(), 2);
193+
if items.len() != 2 {
194+
return Err(PciBdfParseError::InvalidFormat(s.to_string()));
195+
}
185196
let function = u8::from_str_radix(items[1], 16)?;
186197
let items: Vec<&str> = items[0].split(':').collect();
187-
assert_eq!(items.len(), 3);
198+
if items.len() != 3 {
199+
return Err(PciBdfParseError::InvalidFormat(s.to_string()));
200+
}
188201
let segment = u16::from_str_radix(items[0], 16)?;
189202
let bus = u8::from_str_radix(items[1], 16)?;
190203
let device = u8::from_str_radix(items[2], 16)?;
191204
Ok(PciBdf::new(segment, bus, device, function))
192205
}
193206
}
194-
195-
impl From<&str> for PciBdf {
196-
fn from(bdf: &str) -> Self {
197-
Self::from_str(bdf).unwrap()
198-
}
199-
}

0 commit comments

Comments
 (0)