1 // SPDX-License-Identifier: GPL-2.0 2 3 //! String representations. 4 5 use crate::alloc::{flags::*, vec_ext::VecExt}; 6 use alloc::alloc::AllocError; 7 use alloc::vec::Vec; 8 use core::fmt::{self, Write}; 9 use core::ops::{self, Deref, DerefMut, Index}; 10 11 use crate::{ 12 bindings, 13 error::{code::*, Error}, 14 }; 15 16 /// Byte string without UTF-8 validity guarantee. 17 #[repr(transparent)] 18 pub struct BStr([u8]); 19 20 impl BStr { 21 /// Returns the length of this string. 22 #[inline] 23 pub const fn len(&self) -> usize { 24 self.0.len() 25 } 26 27 /// Returns `true` if the string is empty. 28 #[inline] 29 pub const fn is_empty(&self) -> bool { 30 self.len() == 0 31 } 32 33 /// Creates a [`BStr`] from a `[u8]`. 34 #[inline] 35 pub const fn from_bytes(bytes: &[u8]) -> &Self { 36 // SAFETY: `BStr` is transparent to `[u8]`. 37 unsafe { &*(bytes as *const [u8] as *const BStr) } 38 } 39 } 40 41 impl fmt::Display for BStr { 42 /// Formats printable ASCII characters, escaping the rest. 43 /// 44 /// ``` 45 /// # use kernel::{fmt, b_str, str::{BStr, CString}}; 46 /// let ascii = b_str!("Hello, BStr!"); 47 /// let s = CString::try_from_fmt(fmt!("{}", ascii)).unwrap(); 48 /// assert_eq!(s.as_bytes(), "Hello, BStr!".as_bytes()); 49 /// 50 /// let non_ascii = b_str!(""); 51 /// let s = CString::try_from_fmt(fmt!("{}", non_ascii)).unwrap(); 52 /// assert_eq!(s.as_bytes(), "\\xf0\\x9f\\xa6\\x80".as_bytes()); 53 /// ``` 54 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 55 for &b in &self.0 { 56 match b { 57 // Common escape codes. 58 b'\t' => f.write_str("\\t")?, 59 b'\n' => f.write_str("\\n")?, 60 b'\r' => f.write_str("\\r")?, 61 // Printable characters. 62 0x20..=0x7e => f.write_char(b as char)?, 63 _ => write!(f, "\\x{:02x}", b)?, 64 } 65 } 66 Ok(()) 67 } 68 } 69 70 impl fmt::Debug for BStr { 71 /// Formats printable ASCII characters with a double quote on either end, 72 /// escaping the rest. 73 /// 74 /// ``` 75 /// # use kernel::{fmt, b_str, str::{BStr, CString}}; 76 /// // Embedded double quotes are escaped. 77 /// let ascii = b_str!("Hello, \"BStr\"!"); 78 /// let s = CString::try_from_fmt(fmt!("{:?}", ascii)).unwrap(); 79 /// assert_eq!(s.as_bytes(), "\"Hello, \\\"BStr\\\"!\"".as_bytes()); 80 /// 81 /// let non_ascii = b_str!(""); 82 /// let s = CString::try_from_fmt(fmt!("{:?}", non_ascii)).unwrap(); 83 /// assert_eq!(s.as_bytes(), "\"\\xf0\\x9f\\x98\\xba\"".as_bytes()); 84 /// ``` 85 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 86 f.write_char('"')?; 87 for &b in &self.0 { 88 match b { 89 // Common escape codes. 90 b'\t' => f.write_str("\\t")?, 91 b'\n' => f.write_str("\\n")?, 92 b'\r' => f.write_str("\\r")?, 93 // String escape characters. 94 b'\"' => f.write_str("\\\"")?, 95 b'\\' => f.write_str("\\\\")?, 96 // Printable characters. 97 0x20..=0x7e => f.write_char(b as char)?, 98 _ => write!(f, "\\x{:02x}", b)?, 99 } 100 } 101 f.write_char('"') 102 } 103 } 104 105 impl Deref for BStr { 106 type Target = [u8]; 107 108 #[inline] 109 fn deref(&self) -> &Self::Target { 110 &self.0 111 } 112 } 113 114 /// Creates a new [`BStr`] from a string literal. 115 /// 116 /// `b_str!` converts the supplied string literal to byte string, so non-ASCII 117 /// characters can be included. 118 /// 119 /// # Examples 120 /// 121 /// ``` 122 /// # use kernel::b_str; 123 /// # use kernel::str::BStr; 124 /// const MY_BSTR: &BStr = b_str!("My awesome BStr!"); 125 /// ``` 126 #[macro_export] 127 macro_rules! b_str { 128 ($str:literal) => {{ 129 const S: &'static str = $str; 130 const C: &'static $crate::str::BStr = $crate::str::BStr::from_bytes(S.as_bytes()); 131 C 132 }}; 133 } 134 135 /// Possible errors when using conversion functions in [`CStr`]. 136 #[derive(Debug, Clone, Copy)] 137 pub enum CStrConvertError { 138 /// Supplied bytes contain an interior `NUL`. 139 InteriorNul, 140 141 /// Supplied bytes are not terminated by `NUL`. 142 NotNulTerminated, 143 } 144 145 impl From<CStrConvertError> for Error { 146 #[inline] 147 fn from(_: CStrConvertError) -> Error { 148 EINVAL 149 } 150 } 151 152 /// A string that is guaranteed to have exactly one `NUL` byte, which is at the 153 /// end. 154 /// 155 /// Used for interoperability with kernel APIs that take C strings. 156 #[repr(transparent)] 157 pub struct CStr([u8]); 158 159 impl CStr { 160 /// Returns the length of this string excluding `NUL`. 161 #[inline] 162 pub const fn len(&self) -> usize { 163 self.len_with_nul() - 1 164 } 165 166 /// Returns the length of this string with `NUL`. 167 #[inline] 168 pub const fn len_with_nul(&self) -> usize { 169 // SAFETY: This is one of the invariant of `CStr`. 170 // We add a `unreachable_unchecked` here to hint the optimizer that 171 // the value returned from this function is non-zero. 172 if self.0.is_empty() { 173 unsafe { core::hint::unreachable_unchecked() }; 174 } 175 self.0.len() 176 } 177 178 /// Returns `true` if the string only includes `NUL`. 179 #[inline] 180 pub const fn is_empty(&self) -> bool { 181 self.len() == 0 182 } 183 184 /// Wraps a raw C string pointer. 185 /// 186 /// # Safety 187 /// 188 /// `ptr` must be a valid pointer to a `NUL`-terminated C string, and it must 189 /// last at least `'a`. When `CStr` is alive, the memory pointed by `ptr` 190 /// must not be mutated. 191 #[inline] 192 pub unsafe fn from_char_ptr<'a>(ptr: *const core::ffi::c_char) -> &'a Self { 193 // SAFETY: The safety precondition guarantees `ptr` is a valid pointer 194 // to a `NUL`-terminated C string. 195 let len = unsafe { bindings::strlen(ptr) } + 1; 196 // SAFETY: Lifetime guaranteed by the safety precondition. 197 let bytes = unsafe { core::slice::from_raw_parts(ptr as _, len as _) }; 198 // SAFETY: As `len` is returned by `strlen`, `bytes` does not contain interior `NUL`. 199 // As we have added 1 to `len`, the last byte is known to be `NUL`. 200 unsafe { Self::from_bytes_with_nul_unchecked(bytes) } 201 } 202 203 /// Creates a [`CStr`] from a `[u8]`. 204 /// 205 /// The provided slice must be `NUL`-terminated, does not contain any 206 /// interior `NUL` bytes. 207 pub const fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, CStrConvertError> { 208 if bytes.is_empty() { 209 return Err(CStrConvertError::NotNulTerminated); 210 } 211 if bytes[bytes.len() - 1] != 0 { 212 return Err(CStrConvertError::NotNulTerminated); 213 } 214 let mut i = 0; 215 // `i + 1 < bytes.len()` allows LLVM to optimize away bounds checking, 216 // while it couldn't optimize away bounds checks for `i < bytes.len() - 1`. 217 while i + 1 < bytes.len() { 218 if bytes[i] == 0 { 219 return Err(CStrConvertError::InteriorNul); 220 } 221 i += 1; 222 } 223 // SAFETY: We just checked that all properties hold. 224 Ok(unsafe { Self::from_bytes_with_nul_unchecked(bytes) }) 225 } 226 227 /// Creates a [`CStr`] from a `[u8]` without performing any additional 228 /// checks. 229 /// 230 /// # Safety 231 /// 232 /// `bytes` *must* end with a `NUL` byte, and should only have a single 233 /// `NUL` byte (or the string will be truncated). 234 #[inline] 235 pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr { 236 // SAFETY: Properties of `bytes` guaranteed by the safety precondition. 237 unsafe { core::mem::transmute(bytes) } 238 } 239 240 /// Creates a mutable [`CStr`] from a `[u8]` without performing any 241 /// additional checks. 242 /// 243 /// # Safety 244 /// 245 /// `bytes` *must* end with a `NUL` byte, and should only have a single 246 /// `NUL` byte (or the string will be truncated). 247 #[inline] 248 pub unsafe fn from_bytes_with_nul_unchecked_mut(bytes: &mut [u8]) -> &mut CStr { 249 // SAFETY: Properties of `bytes` guaranteed by the safety precondition. 250 unsafe { &mut *(bytes as *mut [u8] as *mut CStr) } 251 } 252 253 /// Returns a C pointer to the string. 254 #[inline] 255 pub const fn as_char_ptr(&self) -> *const core::ffi::c_char { 256 self.0.as_ptr() as _ 257 } 258 259 /// Convert the string to a byte slice without the trailing `NUL` byte. 260 #[inline] 261 pub fn as_bytes(&self) -> &[u8] { 262 &self.0[..self.len()] 263 } 264 265 /// Convert the string to a byte slice containing the trailing `NUL` byte. 266 #[inline] 267 pub const fn as_bytes_with_nul(&self) -> &[u8] { 268 &self.0 269 } 270 271 /// Yields a [`&str`] slice if the [`CStr`] contains valid UTF-8. 272 /// 273 /// If the contents of the [`CStr`] are valid UTF-8 data, this 274 /// function will return the corresponding [`&str`] slice. Otherwise, 275 /// it will return an error with details of where UTF-8 validation failed. 276 /// 277 /// # Examples 278 /// 279 /// ``` 280 /// # use kernel::str::CStr; 281 /// let cstr = CStr::from_bytes_with_nul(b"foo\0").unwrap(); 282 /// assert_eq!(cstr.to_str(), Ok("foo")); 283 /// ``` 284 #[inline] 285 pub fn to_str(&self) -> Result<&str, core::str::Utf8Error> { 286 core::str::from_utf8(self.as_bytes()) 287 } 288 289 /// Unsafely convert this [`CStr`] into a [`&str`], without checking for 290 /// valid UTF-8. 291 /// 292 /// # Safety 293 /// 294 /// The contents must be valid UTF-8. 295 /// 296 /// # Examples 297 /// 298 /// ``` 299 /// # use kernel::c_str; 300 /// # use kernel::str::CStr; 301 /// let bar = c_str!("ツ"); 302 /// // SAFETY: String literals are guaranteed to be valid UTF-8 303 /// // by the Rust compiler. 304 /// assert_eq!(unsafe { bar.as_str_unchecked() }, "ツ"); 305 /// ``` 306 #[inline] 307 pub unsafe fn as_str_unchecked(&self) -> &str { 308 unsafe { core::str::from_utf8_unchecked(self.as_bytes()) } 309 } 310 311 /// Convert this [`CStr`] into a [`CString`] by allocating memory and 312 /// copying over the string data. 313 pub fn to_cstring(&self) -> Result<CString, AllocError> { 314 CString::try_from(self) 315 } 316 317 /// Converts this [`CStr`] to its ASCII lower case equivalent in-place. 318 /// 319 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z', 320 /// but non-ASCII letters are unchanged. 321 /// 322 /// To return a new lowercased value without modifying the existing one, use 323 /// [`to_ascii_lowercase()`]. 324 /// 325 /// [`to_ascii_lowercase()`]: #method.to_ascii_lowercase 326 pub fn make_ascii_lowercase(&mut self) { 327 // INVARIANT: This doesn't introduce or remove NUL bytes in the C 328 // string. 329 self.0.make_ascii_lowercase(); 330 } 331 332 /// Converts this [`CStr`] to its ASCII upper case equivalent in-place. 333 /// 334 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z', 335 /// but non-ASCII letters are unchanged. 336 /// 337 /// To return a new uppercased value without modifying the existing one, use 338 /// [`to_ascii_uppercase()`]. 339 /// 340 /// [`to_ascii_uppercase()`]: #method.to_ascii_uppercase 341 pub fn make_ascii_uppercase(&mut self) { 342 // INVARIANT: This doesn't introduce or remove NUL bytes in the C 343 // string. 344 self.0.make_ascii_uppercase(); 345 } 346 347 /// Returns a copy of this [`CString`] where each character is mapped to its 348 /// ASCII lower case equivalent. 349 /// 350 /// ASCII letters 'A' to 'Z' are mapped to 'a' to 'z', 351 /// but non-ASCII letters are unchanged. 352 /// 353 /// To lowercase the value in-place, use [`make_ascii_lowercase`]. 354 /// 355 /// [`make_ascii_lowercase`]: str::make_ascii_lowercase 356 pub fn to_ascii_lowercase(&self) -> Result<CString, AllocError> { 357 let mut s = self.to_cstring()?; 358 359 s.make_ascii_lowercase(); 360 361 Ok(s) 362 } 363 364 /// Returns a copy of this [`CString`] where each character is mapped to its 365 /// ASCII upper case equivalent. 366 /// 367 /// ASCII letters 'a' to 'z' are mapped to 'A' to 'Z', 368 /// but non-ASCII letters are unchanged. 369 /// 370 /// To uppercase the value in-place, use [`make_ascii_uppercase`]. 371 /// 372 /// [`make_ascii_uppercase`]: str::make_ascii_uppercase 373 pub fn to_ascii_uppercase(&self) -> Result<CString, AllocError> { 374 let mut s = self.to_cstring()?; 375 376 s.make_ascii_uppercase(); 377 378 Ok(s) 379 } 380 } 381 382 impl fmt::Display for CStr { 383 /// Formats printable ASCII characters, escaping the rest. 384 /// 385 /// ``` 386 /// # use kernel::c_str; 387 /// # use kernel::fmt; 388 /// # use kernel::str::CStr; 389 /// # use kernel::str::CString; 390 /// let penguin = c_str!(""); 391 /// let s = CString::try_from_fmt(fmt!("{}", penguin)).unwrap(); 392 /// assert_eq!(s.as_bytes_with_nul(), "\\xf0\\x9f\\x90\\xa7\0".as_bytes()); 393 /// 394 /// let ascii = c_str!("so \"cool\""); 395 /// let s = CString::try_from_fmt(fmt!("{}", ascii)).unwrap(); 396 /// assert_eq!(s.as_bytes_with_nul(), "so \"cool\"\0".as_bytes()); 397 /// ``` 398 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 399 for &c in self.as_bytes() { 400 if (0x20..0x7f).contains(&c) { 401 // Printable character. 402 f.write_char(c as char)?; 403 } else { 404 write!(f, "\\x{:02x}", c)?; 405 } 406 } 407 Ok(()) 408 } 409 } 410 411 impl fmt::Debug for CStr { 412 /// Formats printable ASCII characters with a double quote on either end, escaping the rest. 413 /// 414 /// ``` 415 /// # use kernel::c_str; 416 /// # use kernel::fmt; 417 /// # use kernel::str::CStr; 418 /// # use kernel::str::CString; 419 /// let penguin = c_str!(""); 420 /// let s = CString::try_from_fmt(fmt!("{:?}", penguin)).unwrap(); 421 /// assert_eq!(s.as_bytes_with_nul(), "\"\\xf0\\x9f\\x90\\xa7\"\0".as_bytes()); 422 /// 423 /// // Embedded double quotes are escaped. 424 /// let ascii = c_str!("so \"cool\""); 425 /// let s = CString::try_from_fmt(fmt!("{:?}", ascii)).unwrap(); 426 /// assert_eq!(s.as_bytes_with_nul(), "\"so \\\"cool\\\"\"\0".as_bytes()); 427 /// ``` 428 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 429 f.write_str("\"")?; 430 for &c in self.as_bytes() { 431 match c { 432 // Printable characters. 433 b'\"' => f.write_str("\\\"")?, 434 0x20..=0x7e => f.write_char(c as char)?, 435 _ => write!(f, "\\x{:02x}", c)?, 436 } 437 } 438 f.write_str("\"") 439 } 440 } 441 442 impl AsRef<BStr> for CStr { 443 #[inline] 444 fn as_ref(&self) -> &BStr { 445 BStr::from_bytes(self.as_bytes()) 446 } 447 } 448 449 impl Deref for CStr { 450 type Target = BStr; 451 452 #[inline] 453 fn deref(&self) -> &Self::Target { 454 self.as_ref() 455 } 456 } 457 458 impl Index<ops::RangeFrom<usize>> for CStr { 459 type Output = CStr; 460 461 #[inline] 462 fn index(&self, index: ops::RangeFrom<usize>) -> &Self::Output { 463 // Delegate bounds checking to slice. 464 // Assign to _ to mute clippy's unnecessary operation warning. 465 let _ = &self.as_bytes()[index.start..]; 466 // SAFETY: We just checked the bounds. 467 unsafe { Self::from_bytes_with_nul_unchecked(&self.0[index.start..]) } 468 } 469 } 470 471 impl Index<ops::RangeFull> for CStr { 472 type Output = CStr; 473 474 #[inline] 475 fn index(&self, _index: ops::RangeFull) -> &Self::Output { 476 self 477 } 478 } 479 480 mod private { 481 use core::ops; 482 483 // Marker trait for index types that can be forward to `BStr`. 484 pub trait CStrIndex {} 485 486 impl CStrIndex for usize {} 487 impl CStrIndex for ops::Range<usize> {} 488 impl CStrIndex for ops::RangeInclusive<usize> {} 489 impl CStrIndex for ops::RangeToInclusive<usize> {} 490 } 491 492 impl<Idx> Index<Idx> for CStr 493 where 494 Idx: private::CStrIndex, 495 BStr: Index<Idx>, 496 { 497 type Output = <BStr as Index<Idx>>::Output; 498 499 #[inline] 500 fn index(&self, index: Idx) -> &Self::Output { 501 &self.as_ref()[index] 502 } 503 } 504 505 /// Creates a new [`CStr`] from a string literal. 506 /// 507 /// The string literal should not contain any `NUL` bytes. 508 /// 509 /// # Examples 510 /// 511 /// ``` 512 /// # use kernel::c_str; 513 /// # use kernel::str::CStr; 514 /// const MY_CSTR: &CStr = c_str!("My awesome CStr!"); 515 /// ``` 516 #[macro_export] 517 macro_rules! c_str { 518 ($str:expr) => {{ 519 const S: &str = concat!($str, "\0"); 520 const C: &$crate::str::CStr = match $crate::str::CStr::from_bytes_with_nul(S.as_bytes()) { 521 Ok(v) => v, 522 Err(_) => panic!("string contains interior NUL"), 523 }; 524 C 525 }}; 526 } 527 528 #[cfg(test)] 529 mod tests { 530 use super::*; 531 use alloc::format; 532 533 const ALL_ASCII_CHARS: &'static str = 534 "\\x01\\x02\\x03\\x04\\x05\\x06\\x07\\x08\\x09\\x0a\\x0b\\x0c\\x0d\\x0e\\x0f\ 535 \\x10\\x11\\x12\\x13\\x14\\x15\\x16\\x17\\x18\\x19\\x1a\\x1b\\x1c\\x1d\\x1e\\x1f \ 536 !\"#$%&'()*+,-./0123456789:;<=>?@\ 537 ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~\\x7f\ 538 \\x80\\x81\\x82\\x83\\x84\\x85\\x86\\x87\\x88\\x89\\x8a\\x8b\\x8c\\x8d\\x8e\\x8f\ 539 \\x90\\x91\\x92\\x93\\x94\\x95\\x96\\x97\\x98\\x99\\x9a\\x9b\\x9c\\x9d\\x9e\\x9f\ 540 \\xa0\\xa1\\xa2\\xa3\\xa4\\xa5\\xa6\\xa7\\xa8\\xa9\\xaa\\xab\\xac\\xad\\xae\\xaf\ 541 \\xb0\\xb1\\xb2\\xb3\\xb4\\xb5\\xb6\\xb7\\xb8\\xb9\\xba\\xbb\\xbc\\xbd\\xbe\\xbf\ 542 \\xc0\\xc1\\xc2\\xc3\\xc4\\xc5\\xc6\\xc7\\xc8\\xc9\\xca\\xcb\\xcc\\xcd\\xce\\xcf\ 543 \\xd0\\xd1\\xd2\\xd3\\xd4\\xd5\\xd6\\xd7\\xd8\\xd9\\xda\\xdb\\xdc\\xdd\\xde\\xdf\ 544 \\xe0\\xe1\\xe2\\xe3\\xe4\\xe5\\xe6\\xe7\\xe8\\xe9\\xea\\xeb\\xec\\xed\\xee\\xef\ 545 \\xf0\\xf1\\xf2\\xf3\\xf4\\xf5\\xf6\\xf7\\xf8\\xf9\\xfa\\xfb\\xfc\\xfd\\xfe\\xff"; 546 547 #[test] 548 fn test_cstr_to_str() { 549 let good_bytes = b"\xf0\x9f\xa6\x80\0"; 550 let checked_cstr = CStr::from_bytes_with_nul(good_bytes).unwrap(); 551 let checked_str = checked_cstr.to_str().unwrap(); 552 assert_eq!(checked_str, ""); 553 } 554 555 #[test] 556 #[should_panic] 557 fn test_cstr_to_str_panic() { 558 let bad_bytes = b"\xc3\x28\0"; 559 let checked_cstr = CStr::from_bytes_with_nul(bad_bytes).unwrap(); 560 checked_cstr.to_str().unwrap(); 561 } 562 563 #[test] 564 fn test_cstr_as_str_unchecked() { 565 let good_bytes = b"\xf0\x9f\x90\xA7\0"; 566 let checked_cstr = CStr::from_bytes_with_nul(good_bytes).unwrap(); 567 let unchecked_str = unsafe { checked_cstr.as_str_unchecked() }; 568 assert_eq!(unchecked_str, ""); 569 } 570 571 #[test] 572 fn test_cstr_display() { 573 let hello_world = CStr::from_bytes_with_nul(b"hello, world!\0").unwrap(); 574 assert_eq!(format!("{}", hello_world), "hello, world!"); 575 let non_printables = CStr::from_bytes_with_nul(b"\x01\x09\x0a\0").unwrap(); 576 assert_eq!(format!("{}", non_printables), "\\x01\\x09\\x0a"); 577 let non_ascii = CStr::from_bytes_with_nul(b"d\xe9j\xe0 vu\0").unwrap(); 578 assert_eq!(format!("{}", non_ascii), "d\\xe9j\\xe0 vu"); 579 let good_bytes = CStr::from_bytes_with_nul(b"\xf0\x9f\xa6\x80\0").unwrap(); 580 assert_eq!(format!("{}", good_bytes), "\\xf0\\x9f\\xa6\\x80"); 581 } 582 583 #[test] 584 fn test_cstr_display_all_bytes() { 585 let mut bytes: [u8; 256] = [0; 256]; 586 // fill `bytes` with [1..=255] + [0] 587 for i in u8::MIN..=u8::MAX { 588 bytes[i as usize] = i.wrapping_add(1); 589 } 590 let cstr = CStr::from_bytes_with_nul(&bytes).unwrap(); 591 assert_eq!(format!("{}", cstr), ALL_ASCII_CHARS); 592 } 593 594 #[test] 595 fn test_cstr_debug() { 596 let hello_world = CStr::from_bytes_with_nul(b"hello, world!\0").unwrap(); 597 assert_eq!(format!("{:?}", hello_world), "\"hello, world!\""); 598 let non_printables = CStr::from_bytes_with_nul(b"\x01\x09\x0a\0").unwrap(); 599 assert_eq!(format!("{:?}", non_printables), "\"\\x01\\x09\\x0a\""); 600 let non_ascii = CStr::from_bytes_with_nul(b"d\xe9j\xe0 vu\0").unwrap(); 601 assert_eq!(format!("{:?}", non_ascii), "\"d\\xe9j\\xe0 vu\""); 602 let good_bytes = CStr::from_bytes_with_nul(b"\xf0\x9f\xa6\x80\0").unwrap(); 603 assert_eq!(format!("{:?}", good_bytes), "\"\\xf0\\x9f\\xa6\\x80\""); 604 } 605 606 #[test] 607 fn test_bstr_display() { 608 let hello_world = BStr::from_bytes(b"hello, world!"); 609 assert_eq!(format!("{}", hello_world), "hello, world!"); 610 let escapes = BStr::from_bytes(b"_\t_\n_\r_\\_\'_\"_"); 611 assert_eq!(format!("{}", escapes), "_\\t_\\n_\\r_\\_'_\"_"); 612 let others = BStr::from_bytes(b"\x01"); 613 assert_eq!(format!("{}", others), "\\x01"); 614 let non_ascii = BStr::from_bytes(b"d\xe9j\xe0 vu"); 615 assert_eq!(format!("{}", non_ascii), "d\\xe9j\\xe0 vu"); 616 let good_bytes = BStr::from_bytes(b"\xf0\x9f\xa6\x80"); 617 assert_eq!(format!("{}", good_bytes), "\\xf0\\x9f\\xa6\\x80"); 618 } 619 620 #[test] 621 fn test_bstr_debug() { 622 let hello_world = BStr::from_bytes(b"hello, world!"); 623 assert_eq!(format!("{:?}", hello_world), "\"hello, world!\""); 624 let escapes = BStr::from_bytes(b"_\t_\n_\r_\\_\'_\"_"); 625 assert_eq!(format!("{:?}", escapes), "\"_\\t_\\n_\\r_\\\\_'_\\\"_\""); 626 let others = BStr::from_bytes(b"\x01"); 627 assert_eq!(format!("{:?}", others), "\"\\x01\""); 628 let non_ascii = BStr::from_bytes(b"d\xe9j\xe0 vu"); 629 assert_eq!(format!("{:?}", non_ascii), "\"d\\xe9j\\xe0 vu\""); 630 let good_bytes = BStr::from_bytes(b"\xf0\x9f\xa6\x80"); 631 assert_eq!(format!("{:?}", good_bytes), "\"\\xf0\\x9f\\xa6\\x80\""); 632 } 633 } 634 635 /// Allows formatting of [`fmt::Arguments`] into a raw buffer. 636 /// 637 /// It does not fail if callers write past the end of the buffer so that they can calculate the 638 /// size required to fit everything. 639 /// 640 /// # Invariants 641 /// 642 /// The memory region between `pos` (inclusive) and `end` (exclusive) is valid for writes if `pos` 643 /// is less than `end`. 644 pub(crate) struct RawFormatter { 645 // Use `usize` to use `saturating_*` functions. 646 beg: usize, 647 pos: usize, 648 end: usize, 649 } 650 651 impl RawFormatter { 652 /// Creates a new instance of [`RawFormatter`] with an empty buffer. 653 fn new() -> Self { 654 // INVARIANT: The buffer is empty, so the region that needs to be writable is empty. 655 Self { 656 beg: 0, 657 pos: 0, 658 end: 0, 659 } 660 } 661 662 /// Creates a new instance of [`RawFormatter`] with the given buffer pointers. 663 /// 664 /// # Safety 665 /// 666 /// If `pos` is less than `end`, then the region between `pos` (inclusive) and `end` 667 /// (exclusive) must be valid for writes for the lifetime of the returned [`RawFormatter`]. 668 pub(crate) unsafe fn from_ptrs(pos: *mut u8, end: *mut u8) -> Self { 669 // INVARIANT: The safety requirements guarantee the type invariants. 670 Self { 671 beg: pos as _, 672 pos: pos as _, 673 end: end as _, 674 } 675 } 676 677 /// Creates a new instance of [`RawFormatter`] with the given buffer. 678 /// 679 /// # Safety 680 /// 681 /// The memory region starting at `buf` and extending for `len` bytes must be valid for writes 682 /// for the lifetime of the returned [`RawFormatter`]. 683 pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self { 684 let pos = buf as usize; 685 // INVARIANT: We ensure that `end` is never less then `buf`, and the safety requirements 686 // guarantees that the memory region is valid for writes. 687 Self { 688 pos, 689 beg: pos, 690 end: pos.saturating_add(len), 691 } 692 } 693 694 /// Returns the current insert position. 695 /// 696 /// N.B. It may point to invalid memory. 697 pub(crate) fn pos(&self) -> *mut u8 { 698 self.pos as _ 699 } 700 701 /// Returns the number of bytes written to the formatter. 702 pub(crate) fn bytes_written(&self) -> usize { 703 self.pos - self.beg 704 } 705 } 706 707 impl fmt::Write for RawFormatter { 708 fn write_str(&mut self, s: &str) -> fmt::Result { 709 // `pos` value after writing `len` bytes. This does not have to be bounded by `end`, but we 710 // don't want it to wrap around to 0. 711 let pos_new = self.pos.saturating_add(s.len()); 712 713 // Amount that we can copy. `saturating_sub` ensures we get 0 if `pos` goes past `end`. 714 let len_to_copy = core::cmp::min(pos_new, self.end).saturating_sub(self.pos); 715 716 if len_to_copy > 0 { 717 // SAFETY: If `len_to_copy` is non-zero, then we know `pos` has not gone past `end` 718 // yet, so it is valid for write per the type invariants. 719 unsafe { 720 core::ptr::copy_nonoverlapping( 721 s.as_bytes().as_ptr(), 722 self.pos as *mut u8, 723 len_to_copy, 724 ) 725 }; 726 } 727 728 self.pos = pos_new; 729 Ok(()) 730 } 731 } 732 733 /// Allows formatting of [`fmt::Arguments`] into a raw buffer. 734 /// 735 /// Fails if callers attempt to write more than will fit in the buffer. 736 pub(crate) struct Formatter(RawFormatter); 737 738 impl Formatter { 739 /// Creates a new instance of [`Formatter`] with the given buffer. 740 /// 741 /// # Safety 742 /// 743 /// The memory region starting at `buf` and extending for `len` bytes must be valid for writes 744 /// for the lifetime of the returned [`Formatter`]. 745 pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self { 746 // SAFETY: The safety requirements of this function satisfy those of the callee. 747 Self(unsafe { RawFormatter::from_buffer(buf, len) }) 748 } 749 } 750 751 impl Deref for Formatter { 752 type Target = RawFormatter; 753 754 fn deref(&self) -> &Self::Target { 755 &self.0 756 } 757 } 758 759 impl fmt::Write for Formatter { 760 fn write_str(&mut self, s: &str) -> fmt::Result { 761 self.0.write_str(s)?; 762 763 // Fail the request if we go past the end of the buffer. 764 if self.0.pos > self.0.end { 765 Err(fmt::Error) 766 } else { 767 Ok(()) 768 } 769 } 770 } 771 772 /// An owned string that is guaranteed to have exactly one `NUL` byte, which is at the end. 773 /// 774 /// Used for interoperability with kernel APIs that take C strings. 775 /// 776 /// # Invariants 777 /// 778 /// The string is always `NUL`-terminated and contains no other `NUL` bytes. 779 /// 780 /// # Examples 781 /// 782 /// ``` 783 /// use kernel::{str::CString, fmt}; 784 /// 785 /// let s = CString::try_from_fmt(fmt!("{}{}{}", "abc", 10, 20)).unwrap(); 786 /// assert_eq!(s.as_bytes_with_nul(), "abc1020\0".as_bytes()); 787 /// 788 /// let tmp = "testing"; 789 /// let s = CString::try_from_fmt(fmt!("{tmp}{}", 123)).unwrap(); 790 /// assert_eq!(s.as_bytes_with_nul(), "testing123\0".as_bytes()); 791 /// 792 /// // This fails because it has an embedded `NUL` byte. 793 /// let s = CString::try_from_fmt(fmt!("a\0b{}", 123)); 794 /// assert_eq!(s.is_ok(), false); 795 /// ``` 796 pub struct CString { 797 buf: Vec<u8>, 798 } 799 800 impl CString { 801 /// Creates an instance of [`CString`] from the given formatted arguments. 802 pub fn try_from_fmt(args: fmt::Arguments<'_>) -> Result<Self, Error> { 803 // Calculate the size needed (formatted string plus `NUL` terminator). 804 let mut f = RawFormatter::new(); 805 f.write_fmt(args)?; 806 f.write_str("\0")?; 807 let size = f.bytes_written(); 808 809 // Allocate a vector with the required number of bytes, and write to it. 810 let mut buf = <Vec<_> as VecExt<_>>::with_capacity(size, GFP_KERNEL)?; 811 // SAFETY: The buffer stored in `buf` is at least of size `size` and is valid for writes. 812 let mut f = unsafe { Formatter::from_buffer(buf.as_mut_ptr(), size) }; 813 f.write_fmt(args)?; 814 f.write_str("\0")?; 815 816 // SAFETY: The number of bytes that can be written to `f` is bounded by `size`, which is 817 // `buf`'s capacity. The contents of the buffer have been initialised by writes to `f`. 818 unsafe { buf.set_len(f.bytes_written()) }; 819 820 // Check that there are no `NUL` bytes before the end. 821 // SAFETY: The buffer is valid for read because `f.bytes_written()` is bounded by `size` 822 // (which the minimum buffer size) and is non-zero (we wrote at least the `NUL` terminator) 823 // so `f.bytes_written() - 1` doesn't underflow. 824 let ptr = unsafe { bindings::memchr(buf.as_ptr().cast(), 0, (f.bytes_written() - 1) as _) }; 825 if !ptr.is_null() { 826 return Err(EINVAL); 827 } 828 829 // INVARIANT: We wrote the `NUL` terminator and checked above that no other `NUL` bytes 830 // exist in the buffer. 831 Ok(Self { buf }) 832 } 833 } 834 835 impl Deref for CString { 836 type Target = CStr; 837 838 fn deref(&self) -> &Self::Target { 839 // SAFETY: The type invariants guarantee that the string is `NUL`-terminated and that no 840 // other `NUL` bytes exist. 841 unsafe { CStr::from_bytes_with_nul_unchecked(self.buf.as_slice()) } 842 } 843 } 844 845 impl DerefMut for CString { 846 fn deref_mut(&mut self) -> &mut Self::Target { 847 // SAFETY: A `CString` is always NUL-terminated and contains no other 848 // NUL bytes. 849 unsafe { CStr::from_bytes_with_nul_unchecked_mut(self.buf.as_mut_slice()) } 850 } 851 } 852 853 impl<'a> TryFrom<&'a CStr> for CString { 854 type Error = AllocError; 855 856 fn try_from(cstr: &'a CStr) -> Result<CString, AllocError> { 857 let mut buf = Vec::new(); 858 859 <Vec<_> as VecExt<_>>::extend_from_slice(&mut buf, cstr.as_bytes_with_nul(), GFP_KERNEL) 860 .map_err(|_| AllocError)?; 861 862 // INVARIANT: The `CStr` and `CString` types have the same invariants for 863 // the string data, and we copied it over without changes. 864 Ok(CString { buf }) 865 } 866 } 867 868 impl fmt::Debug for CString { 869 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { 870 fmt::Debug::fmt(&**self, f) 871 } 872 } 873 874 /// A convenience alias for [`core::format_args`]. 875 #[macro_export] 876 macro_rules! fmt { 877 ($($f:tt)*) => ( core::format_args!($($f)*) ) 878 } 879