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