str.rs 29 KB

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