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