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