aienux
Aienux, the AienOS kernel: boot, scheduling, IPC and capability boundaries. Pre-alpha; host, emulator and physical evidence are labelled separately.
Brought by drakestapleton
aienux / vendor / uefi / src / proto / string / unicode_collation.rs
| 1 | // SPDX-License-Identifier: MIT OR Apache-2.0 |
| 2 | |
| 3 | //! The Unicode Collation Protocol. |
| 4 | //! |
| 5 | //! This protocol is used in the boot services environment to perform |
| 6 | //! lexical comparison functions on Unicode strings for given languages. |
| 7 | |
| 8 | use crate::data_types::{CStr8, CStr16}; |
| 9 | use crate::proto::unsafe_protocol; |
| 10 | use core::cmp::Ordering; |
| 11 | use core::fmt::{self, Display, Formatter}; |
| 12 | use core::{error, slice}; |
| 13 | use uefi_raw::protocol::string::UnicodeCollationProtocol; |
| 14 | |
| 15 | /// Unicode Collation [`Protocol`]. |
| 16 | /// |
| 17 | /// Used to perform case-insensitive comparisons of strings. |
| 18 | /// |
| 19 | /// [`Protocol`]: uefi::proto::Protocol |
| 20 | #[derive(Debug)] |
| 21 | #[repr(transparent)] |
| 22 | #[unsafe_protocol(UnicodeCollationProtocol::GUID)] |
| 23 | pub struct UnicodeCollation(UnicodeCollationProtocol); |
| 24 | |
| 25 | impl UnicodeCollation { |
| 26 | /// Performs a case insensitive comparison of two |
| 27 | /// null-terminated strings. |
| 28 | #[must_use] |
| 29 | pub fn stri_coll(&self, s1: &CStr16, s2: &CStr16) -> Ordering { |
| 30 | // SAFETY: The memory is valid. |
| 31 | let order = unsafe { (self.0.stri_coll)(&self.0, s1.as_ptr().cast(), s2.as_ptr().cast()) }; |
| 32 | order.cmp(&0) |
| 33 | } |
| 34 | |
| 35 | /// Performs a case insensitive comparison between a null terminated |
| 36 | /// pattern string and a null terminated string. |
| 37 | /// |
| 38 | /// This function checks if character pattern described in `pattern` |
| 39 | /// is found in `string`. If the pattern match succeeds, true is returned. |
| 40 | /// Otherwise, false is returned. |
| 41 | /// |
| 42 | /// The following syntax can be used to build the string `pattern`: |
| 43 | /// |
| 44 | /// |Pattern Character |Meaning | |
| 45 | /// |-------------------------------|--------------------------------------------------| |
| 46 | /// |* | Match 0 or more characters | |
| 47 | /// |? | Match any one character | |
| 48 | /// |``[`char1` `char2`...`charN`]``| Match any character in the set | |
| 49 | /// |``[`char1`-`char2`]`` | Match any character between `char1` and `char2`| |
| 50 | /// |`char` | Match the character `char` | |
| 51 | /// |
| 52 | /// For example, the pattern "*.Fw" will match all strings that end |
| 53 | /// in ".FW", ".fw", ".Fw" or ".fW". The pattern "[a-z]" will match any |
| 54 | /// letter in the alphabet. The pattern "z" will match the letter "z". |
| 55 | /// The pattern "d?.*" will match the character "D" or "d" followed by |
| 56 | /// any single character followed by a "." followed by any string. |
| 57 | #[must_use] |
| 58 | pub fn metai_match(&self, s: &CStr16, pattern: &CStr16) -> bool { |
| 59 | // SAFETY: The memory is valid. |
| 60 | unsafe { (self.0.metai_match)(&self.0, s.as_ptr().cast(), pattern.as_ptr().cast()) }.into() |
| 61 | } |
| 62 | |
| 63 | /// Converts the characters in `s` to lower case characters. |
| 64 | pub fn str_lwr<'a>( |
| 65 | &self, |
| 66 | s: &CStr16, |
| 67 | buf: &'a mut [u16], |
| 68 | ) -> Result<&'a CStr16, StrConversionError> { |
| 69 | let buf = copy_with_nul(s, buf)?; |
| 70 | |
| 71 | // SAFETY: The memory is valid. |
| 72 | unsafe { (self.0.str_lwr)(&self.0, buf.as_mut_ptr()) }; |
| 73 | |
| 74 | // SAFETY: `buf` holds exactly the NUL-terminated copy of `s`, which |
| 75 | // the case conversion changes in place. |
| 76 | Ok(unsafe { CStr16::from_u16_with_nul_unchecked(buf) }) |
| 77 | } |
| 78 | |
| 79 | /// Converts the characters in `s` to upper case characters. |
| 80 | pub fn str_upr<'a>( |
| 81 | &self, |
| 82 | s: &CStr16, |
| 83 | buf: &'a mut [u16], |
| 84 | ) -> Result<&'a CStr16, StrConversionError> { |
| 85 | let buf = copy_with_nul(s, buf)?; |
| 86 | |
| 87 | // SAFETY: The memory is valid. |
| 88 | unsafe { (self.0.str_upr)(&self.0, buf.as_mut_ptr()) }; |
| 89 | |
| 90 | // SAFETY: `buf` holds exactly the NUL-terminated copy of `s`, which |
| 91 | // the case conversion changes in place. |
| 92 | Ok(unsafe { CStr16::from_u16_with_nul_unchecked(buf) }) |
| 93 | } |
| 94 | |
| 95 | /// Converts the 8.3 FAT file name `fat` to a null terminated string. |
| 96 | pub fn fat_to_str<'a>( |
| 97 | &self, |
| 98 | fat: &CStr8, |
| 99 | buf: &'a mut [u16], |
| 100 | ) -> Result<&'a CStr16, StrConversionError> { |
| 101 | // The conversion writes one character per FAT character plus the |
| 102 | // NUL terminator, so the output is at most as long as `fat` with |
| 103 | // its NUL. |
| 104 | let fat_len = fat.as_bytes().len(); |
| 105 | let buf = buf |
| 106 | .get_mut(..fat_len) |
| 107 | .ok_or(StrConversionError::BufferTooSmall)?; |
| 108 | // SAFETY: The memory is valid. |
| 109 | unsafe { (self.0.fat_to_str)(&self.0, fat_len, fat.as_ptr().cast(), buf.as_mut_ptr()) }; |
| 110 | // The firmware wrote the output, so validate it instead of trusting |
| 111 | // it blindly. |
| 112 | CStr16::from_u16_until_nul(buf).map_err(|_| StrConversionError::ConversionFailed) |
| 113 | } |
| 114 | |
| 115 | /// Converts the null terminated string `s` to legal characters in a FAT file name. |
| 116 | pub fn str_to_fat<'a>( |
| 117 | &self, |
| 118 | s: &CStr16, |
| 119 | buf: &'a mut [u8], |
| 120 | ) -> Result<&'a CStr8, StrConversionError> { |
| 121 | if s.as_slice_with_nul().len() > buf.len() { |
| 122 | return Err(StrConversionError::BufferTooSmall); |
| 123 | } |
| 124 | // The protocol only writes the converted characters and no NUL |
| 125 | // terminator; the remaining buffer keeps its previous content. |
| 126 | // Pre-zero the buffer so the result is NUL-terminated. |
| 127 | buf.fill(0); |
| 128 | // SAFETY: The memory is valid. |
| 129 | let failed = unsafe { |
| 130 | (self.0.str_to_fat)( |
| 131 | &self.0, |
| 132 | s.as_ptr().cast(), |
| 133 | s.as_slice_with_nul().len(), |
| 134 | buf.as_mut_ptr(), |
| 135 | ) |
| 136 | }; |
| 137 | if bool::from(failed) { |
| 138 | Err(StrConversionError::ConversionFailed) |
| 139 | } else { |
| 140 | // The conversion writes at most one byte per input character |
| 141 | // and never a NUL, so the first NUL terminates the result. |
| 142 | let end = buf |
| 143 | .iter() |
| 144 | .position(|&b| b == 0) |
| 145 | .expect("conversion should leave the pre-zeroed NUL of the input intact"); |
| 146 | // SAFETY: The pointer is valid for the requested slice length. |
| 147 | let buf = unsafe { slice::from_raw_parts(buf.as_ptr(), end + 1) }; |
| 148 | // SAFETY: The slice ends with the first NUL, so there are no interior NULs. |
| 149 | Ok(unsafe { CStr8::from_bytes_with_nul_unchecked(buf) }) |
| 150 | } |
| 151 | } |
| 152 | } |
| 153 | |
| 154 | /// Copies `s` including its NUL terminator to the start of `buf` and returns |
| 155 | /// the written part. |
| 156 | fn copy_with_nul<'a>(s: &CStr16, buf: &'a mut [u16]) -> Result<&'a mut [u16], StrConversionError> { |
| 157 | let src = s.to_u16_slice_with_nul(); |
| 158 | let dst = buf |
| 159 | .get_mut(..src.len()) |
| 160 | .ok_or(StrConversionError::BufferTooSmall)?; |
| 161 | dst.copy_from_slice(src); |
| 162 | Ok(dst) |
| 163 | } |
| 164 | |
| 165 | /// Errors returned by [`UnicodeCollation::str_lwr`] and [`UnicodeCollation::str_upr`]. |
| 166 | #[derive(Clone, Copy, Debug, PartialEq, Eq)] |
| 167 | pub enum StrConversionError { |
| 168 | /// The conversion failed. |
| 169 | ConversionFailed, |
| 170 | /// The buffer given is too small to hold the string. |
| 171 | BufferTooSmall, |
| 172 | } |
| 173 | |
| 174 | impl Display for StrConversionError { |
| 175 | fn fmt(&self, f: &mut Formatter<'_>) -> fmt::Result { |
| 176 | write!( |
| 177 | f, |
| 178 | "{}", |
| 179 | match self { |
| 180 | Self::ConversionFailed => "conversion failed", |
| 181 | Self::BufferTooSmall => "buffer too small", |
| 182 | } |
| 183 | ) |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | impl error::Error for StrConversionError {} |
| 188 | |
| 189 | #[cfg(test)] |
| 190 | mod tests { |
| 191 | use super::*; |
| 192 | use crate::{cstr8, cstr16}; |
| 193 | use core::ptr; |
| 194 | use uefi_raw::{Boolean, Char8, Char16}; |
| 195 | |
| 196 | /// Mock of `UnicodeCollationProtocol::str_lwr` for ASCII strings. |
| 197 | /// |
| 198 | /// # Safety |
| 199 | /// `s` must point to a NUL-terminated string. |
| 200 | unsafe extern "efiapi" fn mock_str_lwr(_: *const UnicodeCollationProtocol, s: *mut Char16) { |
| 201 | let mut p = s.cast::<u16>(); |
| 202 | // SAFETY: Guaranteed by the caller. |
| 203 | unsafe { |
| 204 | while *p != 0 { |
| 205 | *p = u16::from((*p as u8).to_ascii_lowercase()); |
| 206 | p = p.add(1); |
| 207 | } |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | /// Mock of `UnicodeCollationProtocol::fat_to_str` with EDK2 semantics: |
| 212 | /// copy until NUL or `fat_size` is exhausted, then write a NUL. |
| 213 | /// |
| 214 | /// # Safety |
| 215 | /// `fat` must be valid for reading and `s` for writing `fat_size` items |
| 216 | /// plus one. |
| 217 | unsafe extern "efiapi" fn mock_fat_to_str( |
| 218 | _: *const UnicodeCollationProtocol, |
| 219 | fat_size: usize, |
| 220 | fat: *const Char8, |
| 221 | s: *mut Char16, |
| 222 | ) { |
| 223 | // SAFETY: Guaranteed by the caller. |
| 224 | let fat = unsafe { core::slice::from_raw_parts(fat.cast::<u8>(), fat_size) }; |
| 225 | let len = fat.iter().position(|&b| b == 0).unwrap_or(fat_size); |
| 226 | for (i, &b) in fat[..len].iter().enumerate() { |
| 227 | // SAFETY: Guaranteed by the caller. |
| 228 | unsafe { s.cast::<u16>().add(i).write(u16::from(b)) }; |
| 229 | } |
| 230 | // SAFETY: Guaranteed by the caller. |
| 231 | unsafe { s.cast::<u16>().add(len).write(0) }; |
| 232 | } |
| 233 | |
| 234 | // Stubs for the operations the tests do not exercise. |
| 235 | |
| 236 | extern "efiapi" fn stub_stri_coll( |
| 237 | _: *const UnicodeCollationProtocol, |
| 238 | _: *const Char16, |
| 239 | _: *const Char16, |
| 240 | ) -> isize { |
| 241 | unimplemented!() |
| 242 | } |
| 243 | |
| 244 | extern "efiapi" fn stub_metai_match( |
| 245 | _: *const UnicodeCollationProtocol, |
| 246 | _: *const Char16, |
| 247 | _: *const Char16, |
| 248 | ) -> Boolean { |
| 249 | unimplemented!() |
| 250 | } |
| 251 | |
| 252 | extern "efiapi" fn stub_str_upr(_: *const UnicodeCollationProtocol, _: *mut Char16) { |
| 253 | unimplemented!() |
| 254 | } |
| 255 | |
| 256 | extern "efiapi" fn stub_str_to_fat( |
| 257 | _: *const UnicodeCollationProtocol, |
| 258 | _: *const Char16, |
| 259 | _: usize, |
| 260 | _: *mut Char8, |
| 261 | ) -> Boolean { |
| 262 | unimplemented!() |
| 263 | } |
| 264 | |
| 265 | const MOCK: UnicodeCollationProtocol = UnicodeCollationProtocol { |
| 266 | stri_coll: stub_stri_coll, |
| 267 | metai_match: stub_metai_match, |
| 268 | str_lwr: mock_str_lwr, |
| 269 | str_upr: stub_str_upr, |
| 270 | fat_to_str: mock_fat_to_str, |
| 271 | str_to_fat: stub_str_to_fat, |
| 272 | supported_languages: ptr::null(), |
| 273 | }; |
| 274 | |
| 275 | fn mock() -> &'static UnicodeCollation { |
| 276 | // SAFETY: `UnicodeCollation` is a transparent wrapper. |
| 277 | unsafe { &*ptr::from_ref(&MOCK).cast::<UnicodeCollation>() } |
| 278 | } |
| 279 | |
| 280 | #[test] |
| 281 | fn test_str_lwr_oversized_buffer() { |
| 282 | let mut buf = [0x41; 8]; |
| 283 | let s = mock().str_lwr(cstr16!("AbC"), &mut buf).unwrap(); |
| 284 | assert_eq!(s.num_chars(), 3); |
| 285 | assert_eq!(s, cstr16!("abc")); |
| 286 | |
| 287 | let mut buf = [0x41; 2]; |
| 288 | let s = mock().str_lwr(cstr16!(""), &mut buf).unwrap(); |
| 289 | assert_eq!(s.num_chars(), 0); |
| 290 | |
| 291 | let mut buf = [0x41; 3]; |
| 292 | assert_eq!( |
| 293 | mock().str_lwr(cstr16!("AbC"), &mut buf).unwrap_err(), |
| 294 | StrConversionError::BufferTooSmall |
| 295 | ); |
| 296 | } |
| 297 | |
| 298 | #[test] |
| 299 | fn test_fat_to_str_oversized_buffer() { |
| 300 | let mut buf = [0x41; 16]; |
| 301 | let s = mock().fat_to_str(cstr8!("AB"), &mut buf).unwrap(); |
| 302 | assert_eq!(s.num_chars(), 2); |
| 303 | assert_eq!(s, cstr16!("AB")); |
| 304 | |
| 305 | let mut buf = [0x41; 2]; |
| 306 | assert_eq!( |
| 307 | mock().fat_to_str(cstr8!("AB"), &mut buf).unwrap_err(), |
| 308 | StrConversionError::BufferTooSmall |
| 309 | ); |
| 310 | } |
| 311 | } |