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