Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/aienux/blob/main/vendor/uefi/src/proto/hii/config_str.rs # aienux Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately. Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `main` Branches Tags History `aienux / vendor / uefi / src / proto / hii / config_str.rs` 443 lines ยท 17886 bytes Raw Blame History 1 // SPDX-License-Identifier: MIT OR Apache-2.0 2 3 //! UEFI Configuration String parsing according to Spec 35.2.1 4 5 use alloc::boxed::Box; 6 use alloc::string::{String, ToString}; 7 use alloc::vec::Vec; 8 use core::iter::Peekable; 9 use core::slice; 10 use core::str::{self, FromStr}; 11 use uguid::Guid; 12 13 use crate::mem::AlignedBuffer; 14 use crate::proto::device_path::DevicePath; 15 use crate::{CStr16, Char16}; 16 17 /// A helper struct to split and parse a UEFI Configuration String. 18 /// 19 /// Configuration strings consist of key-value pairs separated by `&`. Keys 20 /// and values are separated by `=`. This struct provides an iterator for 21 /// easy traversal of the key-value pairs. 22 /// 23 /// For reasons of developer sanity, this is operating on &str instead of &CStr16. 24 #[derive(Debug)] 25 pub struct ConfigurationStringIter<'a> { 26 bfr: &'a str, 27 } 28 29 impl<'a> ConfigurationStringIter<'a> { 30 /// Creates a new splitter instance for a given configuration string. 31 #[must_use] 32 pub const fn new(bfr: &'a str) -> Self { 33 Self { bfr } 34 } 35 } 36 37 impl<'a> Iterator for ConfigurationStringIter<'a> { 38 type Item = (&'a str, Option<&'a str>); 39 40 fn next(&mut self) -> Option { 41 if self.bfr.is_empty() { 42 return None; 43 } 44 let (keyval, remainder) = self 45 .bfr 46 .split_once('&') 47 .unwrap_or_else(|| (self.bfr, &self.bfr[0..0])); 48 self.bfr = remainder; 49 let (key, value) = keyval 50 .split_once('=') 51 .map(|(key, value)| (key, Some(value))) 52 .unwrap_or((keyval, None)); 53 Some((key, value)) 54 } 55 } 56 57 /// Enum representing different sections of a UEFI Configuration Header. 58 /// 59 /// These sections include GUID, Name, and Path elements, which provide 60 /// routing and identification information for UEFI components. 61 #[derive(Debug, PartialEq, Eq)] 62 pub enum ConfigHdrSection { 63 /// UEFI ConfigurationString {GuidHdr} element 64 Guid, 65 /// UEFI ConfigurationString {NameHdr} element 66 Name, 67 /// UEFI ConfigurationString {PathHdr} element 68 Path, 69 /// UEFI ConfigurationString {DescHdr} element 70 DescHdr, 71 } 72 73 /// Enum representing possible parsing errors encountered when processing 74 /// UEFI Configuration Strings. 75 #[derive(Debug)] 76 pub enum ParseError { 77 /// Error while parsing the UEFI {ConfigHdr} configuration string section. 78 ConfigHdr(ConfigHdrSection), 79 /// Error while parsing the UEFI {BlockName} configuration string section. 80 BlockName, 81 /// Error while parsing the UEFI {BlockConfig} configuration string section. 82 BlockConfig, 83 } 84 85 /// Represents an individual element within a UEFI Configuration String. 86 /// 87 /// Each element contains an offset, width, and value, defining the data 88 /// stored at specific memory locations within the configuration. 89 #[derive(Debug, Default)] 90 pub struct ConfigurationStringElement { 91 /// Byte offset in the configuration block 92 pub offset: u64, 93 /// Length of the value starting at offset 94 pub width: u64, 95 /// Value bytes 96 pub value: Vec, 97 // TODO 98 // nvconfig: HashMap>, 99 } 100 101 /// Internal module with known keys found in uefi configuration strings. 102 mod keys { 103 pub const ALTCFG: &str = "ALTCFG"; 104 pub const GUID: &str = "GUID"; 105 pub const NAME: &str = "NAME"; 106 pub const OFFSET: &str = "OFFSET"; 107 pub const VALUE: &str = "VALUE"; 108 pub const WIDTH: &str = "WIDTH"; 109 } 110 111 /// A full UEFI Configuration String representation. 112 /// 113 /// This structure contains routing information such as GUID and device path, 114 /// along with the parsed configuration elements. 115 #[derive(Debug)] 116 pub struct ConfigurationString { 117 /// GUID used for identifying the configuration 118 pub guid: Guid, 119 /// Name field (optional identifier) 120 pub name: String, 121 /// Associated UEFI device path 122 pub device_path: Box, 123 /// Identifier of a configuration declared in the corresponding IFR. 124 pub alt_cfg_id: Option, 125 /// Parsed UEFI {ConfigElement} sections 126 pub elements: Vec, 127 } 128 129 impl ConfigurationString { 130 fn try_parse_with Option>( 131 err: ParseError, 132 parse_fn: F, 133 ) -> Result { 134 parse_fn().ok_or(err) 135 } 136 137 /// Parses a hexadecimal string into an iterator of bytes. 138 /// 139 /// # Arguments 140 /// 141 /// * `hex` - The hexadecimal string representing binary data. 142 /// 143 /// # Returns 144 /// 145 /// An iterator over bytes. 146 #[must_use = "iterators are lazy and do nothing unless consumed"] 147 pub fn parse_bytes_from_hex(hex: &str) -> impl DoubleEndedIterator { 148 hex.as_bytes().chunks(2).map(|chunk| { 149 let chunk = str::from_utf8(chunk).unwrap_or_default(); 150 u8::from_str_radix(chunk, 16).unwrap_or_default() 151 }) 152 } 153 154 /// Converts a hexadecimal string representation into a numeric value. 155 /// 156 /// # Arguments 157 /// 158 /// * `data` - The hexadecimal string to convert. 159 /// 160 /// # Returns 161 /// 162 /// An `Option` representing the parsed number. 163 #[must_use] 164 pub fn parse_number_from_hex(data: &str) -> Option { 165 let data: Vec<_> = Self::parse_bytes_from_hex(data).collect(); 166 match data.len() { 167 8 => Some(u64::from_be_bytes(data.try_into().unwrap())), 168 4 => Some(u32::from_be_bytes(data.try_into().unwrap()) as u64), 169 2 => Some(u16::from_be_bytes(data.try_into().unwrap()) as u64), 170 1 => Some(u8::from_be_bytes(data.try_into().unwrap()) as u64), 171 _ => None, 172 } 173 } 174 175 /// Converts a hexadecimal string into a UTF-16 string. 176 /// 177 /// # Arguments 178 /// 179 /// * `data` - The hexadecimal representation of a string. 180 /// 181 /// # Returns 182 /// 183 /// An `Option` containing the parsed string. 184 #[must_use] 185 pub fn parse_string_from_hex(data: &str) -> Option { 186 if !data.len().is_multiple_of(2) { 187 return None; 188 } 189 let size_bytes = data.len() / 2 + 2; // includes \0 terminator 190 let size_chars = size_bytes / 2; 191 let mut bfr = AlignedBuffer::from_size_align(size_bytes, 2).ok()?; 192 bfr.copy_from_iter(Self::parse_bytes_from_hex(data).chain([0, 0])); 193 #[expect(clippy::chunks_exact_to_as_chunks)] 194 bfr.as_slice_mut() 195 .chunks_exact_mut(2) 196 .for_each(|c| c.swap(0, 1)); 197 let data: &[Char16] = 198 // SAFETY: The pointer is valid for the requested slice length. 199 unsafe { slice::from_raw_parts(bfr.as_slice().as_ptr().cast(), size_chars) }; 200 Some(CStr16::from_char16_with_nul(data).ok()?.to_string()) 201 } 202 203 /// Parses a hexadecimal string into a UEFI GUID. 204 /// 205 /// # Arguments 206 /// 207 /// * `data` - The hexadecimal GUID representation. 208 /// 209 /// # Returns 210 /// 211 /// An `Option` containing the parsed GUID. 212 #[must_use] 213 pub fn parse_guid_from_hex(data: &str) -> Option { 214 let v: Vec<_> = Self::parse_bytes_from_hex(data).collect(); 215 Some(Guid::from_bytes(v.try_into().ok()?)) 216 } 217 218 /// Parse an instance of `Peekable` from the given kv-pair iterator. 219 fn parse_from( 220 splitter: &mut Peekable>, 221 ) -> Result { 222 let guid = Self::try_parse_with(ParseError::ConfigHdr(ConfigHdrSection::Guid), || { 223 let v = splitter.next()?; 224 let v = (v.0 == keys::GUID).then_some(v.1).flatten()?; 225 Self::parse_guid_from_hex(v) 226 })?; 227 let name = Self::try_parse_with(ParseError::ConfigHdr(ConfigHdrSection::Name), || { 228 let v = splitter.next()?; 229 let v = (v.0 == keys::NAME).then_some(v.1).flatten()?; 230 Self::parse_string_from_hex(v) 231 })?; 232 let device_path = 233 Self::try_parse_with(ParseError::ConfigHdr(ConfigHdrSection::Path), || { 234 let v = splitter.next()?.1?; 235 let v: Vec<_> = Self::parse_bytes_from_hex(v).collect(); 236 let v = <&DevicePath>::try_from(v.as_slice()).ok()?; 237 Some(v.to_boxed()) 238 })?; 239 let alt_cfg_id = match splitter.peek() { 240 Some((keys::ALTCFG, _)) => Some(Self::try_parse_with( 241 ParseError::ConfigHdr(ConfigHdrSection::DescHdr), 242 || { 243 let v = splitter.next()?.1?; 244 Self::parse_number_from_hex(v).map(|v| v as u16) 245 }, 246 )?), 247 _ => None, 248 }; 249 250 let mut elements = Vec::new(); 251 loop { 252 let offset = match splitter.next() { 253 Some((keys::OFFSET, Some(data))) => { 254 Self::parse_number_from_hex(data).ok_or(ParseError::BlockName)? 255 } 256 None => break, 257 _ => return Err(ParseError::BlockName), 258 }; 259 let width = match splitter.next() { 260 Some((keys::WIDTH, Some(data))) => { 261 Self::parse_number_from_hex(data).ok_or(ParseError::BlockName)? 262 } 263 _ => return Err(ParseError::BlockName), 264 }; 265 // The uefi specification declares `VALUE` as being a "number" of arbitrary length. 266 // And numbers have to be endianness-corrected. Thus, the bytes represented by a value's 267 // hex string of arbitrary length have to be reversed to account for that weird encoding. 268 let value = match splitter.next() { 269 Some((keys::VALUE, Some(data))) => Self::parse_bytes_from_hex(data).rev().collect(), 270 _ => return Err(ParseError::BlockConfig), 271 }; 272 273 while let Some(next) = splitter.peek() { 274 if next.0 == keys::OFFSET || next.0 == keys::GUID { 275 break; 276 } 277 let _ = splitter.next(); // drop nvconfig entries for now 278 } 279 280 elements.push(ConfigurationStringElement { 281 offset, 282 width, 283 value, 284 }); 285 // Found start of a new [ConfigurationString] 286 if let Some((keys::GUID, _)) = splitter.peek() { 287 break; 288 } 289 } 290 291 Ok(Self { 292 guid, 293 name, 294 device_path, 295 alt_cfg_id, 296 elements, 297 }) 298 } 299 } 300 301 impl FromStr for ConfigurationString { 302 type Err = ParseError; 303 304 fn from_str(bfr: &str) -> Result { 305 Self::parse_from(&mut ConfigurationStringIter::new(bfr).peekable()) 306 } 307 } 308 309 /// Iterator over [ConfigurationString]'s in a multi configuration string. 310 #[derive(Debug)] 311 pub struct MultiConfigurationStringIter<'a> { 312 splitter: Peekable>, 313 } 314 impl<'a> MultiConfigurationStringIter<'a> { 315 /// Creates a new iterator instance for a given configuration string. 316 #[must_use] 317 pub fn new(bfr: &'a str) -> Self { 318 let splitter = ConfigurationStringIter::new(bfr).peekable(); 319 Self { splitter } 320 } 321 } 322 impl<'a> Iterator for MultiConfigurationStringIter<'a> { 323 type Item = Result; 324 325 fn next(&mut self) -> Option { 326 self.splitter.peek()?; // end of iterator? 327 // try parsing the next full [ConfigurationString] from the splitter 328 Some(ConfigurationString::parse_from(&mut self.splitter)) 329 } 330 } 331 332 #[cfg(test)] 333 mod tests { 334 use crate::proto::hii::config_str::{ConfigurationString, MultiConfigurationStringIter}; 335 use alloc::vec::Vec; 336 use core::str::FromStr; 337 338 #[test] 339 fn parse_single() { 340 // exemplary (shortened / manually constructed) UEFI configuration string 341 let input = "GUID=`16d6474bd6a852459d44ccad2e0f4cf9`&NAME=`00490053004300530049005f0043004f004e004600490047005f004900460052005f004e00560044004100540041`&PATH=`0104140016d6474bd6a852459d44ccad2e0f4cf97fff0400`&OFFSET=01d8&WIDTH=0002&VALUE=0011&OFFSET=01d9&WIDTH=0001&VALUE=00&OFFSET=01da&WIDTH=0001&VALUE=00&OFFSET=01dc&WIDTH=0002&VALUE=03e8&OFFSET=01de&WIDTH=0001&VALUE=00&OFFSET=01df&WIDTH=0001&VALUE=00&OFFSET=05fe&WIDTH=0002&VALUE=0000&OFFSET=062a&WIDTH=0001&VALUE=00&OFFSET=062b&WIDTH=0001&VALUE=01&OFFSET=0fd4&WIDTH=0001&VALUE=00&OFFSET=0fd5&WIDTH=0001&VALUE=00"; 342 let parsed = ConfigurationString::from_str(input).unwrap(); 343 assert_eq!(parsed.guid, guid!("`4b47d616`-a8d6-4552-9d44-`ccad2e0f4cf9`")); 344 assert_eq!(parsed.name, "ISCSI_CONFIG_IFR_NVDATA"); 345 assert_eq!(parsed.alt_cfg_id, None); 346 assert_eq!(parsed.elements.len(), 11); 347 assert_eq!(parsed.elements[0].offset, 0x01d8); 348 assert_eq!(parsed.elements[0].width, 2); 349 assert_eq!(&parsed.elements[0].value, &[0x11, 0x00]); 350 assert_eq!(parsed.elements[10].offset, 0x0fd5); 351 assert_eq!(parsed.elements[10].width, 1); 352 assert_eq!(&parsed.elements[10].value, &[0x00]); 353 } 354 355 #[test] 356 fn parse_multiple() { 357 // exemplary (shortened / manually constructed) UEFI configuration string 358 let input = "GUID=`16d6474bd6a852459d44ccad2e0f4cf9`&NAME=`00490053004300530049005f0043004f004e004600490047005f004900460052005f004e00560044004100540041`&PATH=`0104140016d6474bd6a852459d44ccad2e0f4cf97fff0400`&OFFSET=01d8&WIDTH=0001&VALUE=00&GUID=`16d6474bd6a852459d44ccad2e0f4cf9`&NAME=`00490053004300530049005f0043004f004e004600490047005f004900460052005f004e00560044004100540041`&PATH=`0104140016d6474bd6a852459d44ccad2e0f4cf97fff0400`&OFFSET=01d8&WIDTH=0001&VALUE=00&OFFSET=1337&WIDTH=0005&VALUE=`1122334455`"; 359 let parsed: Vec<_> = MultiConfigurationStringIter::new(input) 360 .collect::>() 361 .unwrap(); 362 363 assert_eq!(parsed.len(), 2); 364 365 assert_eq!( 366 parsed[0].guid, 367 guid!("`4b47d616`-a8d6-4552-9d44-`ccad2e0f4cf9`") 368 ); 369 assert_eq!(parsed[0].name, "ISCSI_CONFIG_IFR_NVDATA"); 370 assert_eq!(parsed[0].alt_cfg_id, None); 371 assert_eq!(parsed[0].elements.len(), 1); 372 assert_eq!(parsed[0].elements[0].offset, 0x01d8); 373 assert_eq!(parsed[0].elements[0].width, 1); 374 assert_eq!(&parsed[0].elements[0].value, &[0x00]); 375 376 assert_eq!( 377 parsed[1].guid, 378 guid!("`4b47d616`-a8d6-4552-9d44-`ccad2e0f4cf9`") 379 ); 380 assert_eq!(parsed[1].name, "ISCSI_CONFIG_IFR_NVDATA"); 381 assert_eq!(parsed[1].alt_cfg_id, None); 382 assert_eq!(parsed[1].elements.len(), 2); 383 assert_eq!(parsed[1].elements[1].offset, 0x1337); 384 assert_eq!(parsed[1].elements[1].width, 5); 385 assert_eq!( 386 &parsed[1].elements[1].value, 387 &[0x55, 0x44, 0x33, 0x22, 0x11] 388 ); 389 } 390 391 #[test] 392 fn parse_single_altcfg() { 393 // exemplary (shortened / manually constructed) UEFI configuration string 394 let input = "GUID=`16d6474bd6a852459d44ccad2e0f4cf9`&NAME=`00490053004300530049005f0043004f004e004600490047005f004900460052005f004e00560044004100540041`&PATH=`0104140016d6474bd6a852459d44ccad2e0f4cf97fff0400`&ALTCFG=0001&OFFSET=01d8&WIDTH=0001&VALUE=00&OFFSET=01d9&WIDTH=0001&VALUE=00&OFFSET=01da&WIDTH=0001&VALUE=00&OFFSET=01dc&WIDTH=0002&VALUE=03e8&OFFSET=01de&WIDTH=0001&VALUE=00&OFFSET=01df&WIDTH=0001&VALUE=00&OFFSET=05fe&WIDTH=0002&VALUE=0000&OFFSET=062a&WIDTH=0001&VALUE=00&OFFSET=062b&WIDTH=0001&VALUE=01&OFFSET=0fd4&WIDTH=0001&VALUE=00&OFFSET=0fd5&WIDTH=0001&VALUE=00"; 395 let parsed = ConfigurationString::from_str(input).unwrap(); 396 assert_eq!(parsed.guid, guid!("`4b47d616`-a8d6-4552-9d44-`ccad2e0f4cf9`")); 397 assert_eq!(parsed.name, "ISCSI_CONFIG_IFR_NVDATA"); 398 assert_eq!(parsed.alt_cfg_id, Some(1)); 399 assert_eq!(parsed.elements.len(), 11); 400 assert_eq!(parsed.elements[0].offset, 0x01d8); 401 assert_eq!(parsed.elements[0].width, 1); 402 assert_eq!(&parsed.elements[0].value, &[0x00]); 403 assert_eq!(parsed.elements[10].offset, 0x0fd5); 404 assert_eq!(parsed.elements[10].width, 1); 405 assert_eq!(&parsed.elements[10].value, &[0x00]); 406 } 407 408 #[test] 409 fn parse_multiple_altcfg() { 410 // exemplary (shortened / manually constructed) UEFI configuration string 411 let input = "GUID=`16d6474bd6a852459d44ccad2e0f4cf9`&NAME=`00490053004300530049005f0043004f004e004600490047005f004900460052005f004e00560044004100540041`&PATH=`0104140016d6474bd6a852459d44ccad2e0f4cf97fff0400`&ALTCFG=0002&OFFSET=01d8&WIDTH=0001&VALUE=00&GUID=`16d6474bd6a852459d44ccad2e0f4cf9`&NAME=`00490053004300530049005f0043004f004e004600490047005f004900460052005f004e00560044004100540041`&PATH=`0104140016d6474bd6a852459d44ccad2e0f4cf97fff0400`&ALTCFG=0001&OFFSET=01d8&WIDTH=0001&VALUE=00&OFFSET=1337&WIDTH=0005&VALUE=`1122334455`"; 412 let parsed: Vec<_> = MultiConfigurationStringIter::new(input) 413 .collect::>() 414 .unwrap(); 415 416 assert_eq!(parsed.len(), 2); 417 418 assert_eq!( 419 parsed[0].guid, 420 guid!("`4b47d616`-a8d6-4552-9d44-`ccad2e0f4cf9`") 421 ); 422 assert_eq!(parsed[0].name, "ISCSI_CONFIG_IFR_NVDATA"); 423 assert_eq!(parsed[0].alt_cfg_id, Some(2)); 424 assert_eq!(parsed[0].elements.len(), 1); 425 assert_eq!(parsed[0].elements[0].offset, 0x01d8); 426 assert_eq!(parsed[0].elements[0].width, 1); 427 assert_eq!(&parsed[0].elements[0].value, &[0x00]); 428 429 assert_eq!( 430 parsed[1].guid, 431 guid!("`4b47d616`-a8d6-4552-9d44-`ccad2e0f4cf9`") 432 ); 433 assert_eq!(parsed[1].name, "ISCSI_CONFIG_IFR_NVDATA"); 434 assert_eq!(parsed[1].alt_cfg_id, Some(1)); 435 assert_eq!(parsed[1].elements.len(), 2); 436 assert_eq!(parsed[1].elements[1].offset, 0x1337); 437 assert_eq!(parsed[1].elements[1].width, 5); 438 assert_eq!( 439 &parsed[1].elements[1].value, 440 &[0x55, 0x44, 0x33, 0x22, 0x11] 441 ); 442 } 443 }