xref: /openbmc/linux/rust/kernel/str.rs (revision f77d1a49)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 //! String representations.
4 
5 use alloc::alloc::AllocError;
6 use alloc::vec::Vec;
7 use core::fmt::{self, Write};
8 use core::ops::{self, Deref, Index};
9 
10 use crate::{
11     bindings,
12     error::{code::*, Error},
13 };
14 
15 /// Byte string without UTF-8 validity guarantee.
16 ///
17 /// `BStr` is simply an alias to `[u8]`, but has a more evident semantical meaning.
18 pub type BStr = [u8];
19 
20 /// Creates a new [`BStr`] from a string literal.
21 ///
22 /// `b_str!` converts the supplied string literal to byte string, so non-ASCII
23 /// characters can be included.
24 ///
25 /// # Examples
26 ///
27 /// ```
28 /// # use kernel::b_str;
29 /// # use kernel::str::BStr;
30 /// const MY_BSTR: &BStr = b_str!("My awesome BStr!");
31 /// ```
32 #[macro_export]
33 macro_rules! b_str {
34     ($str:literal) => {{
35         const S: &'static str = $str;
36         const C: &'static $crate::str::BStr = S.as_bytes();
37         C
38     }};
39 }
40 
41 /// Possible errors when using conversion functions in [`CStr`].
42 #[derive(Debug, Clone, Copy)]
43 pub enum CStrConvertError {
44     /// Supplied bytes contain an interior `NUL`.
45     InteriorNul,
46 
47     /// Supplied bytes are not terminated by `NUL`.
48     NotNulTerminated,
49 }
50 
51 impl From<CStrConvertError> for Error {
52     #[inline]
53     fn from(_: CStrConvertError) -> Error {
54         EINVAL
55     }
56 }
57 
58 /// A string that is guaranteed to have exactly one `NUL` byte, which is at the
59 /// end.
60 ///
61 /// Used for interoperability with kernel APIs that take C strings.
62 #[repr(transparent)]
63 pub struct CStr([u8]);
64 
65 impl CStr {
66     /// Returns the length of this string excluding `NUL`.
67     #[inline]
68     pub const fn len(&self) -> usize {
69         self.len_with_nul() - 1
70     }
71 
72     /// Returns the length of this string with `NUL`.
73     #[inline]
74     pub const fn len_with_nul(&self) -> usize {
75         // SAFETY: This is one of the invariant of `CStr`.
76         // We add a `unreachable_unchecked` here to hint the optimizer that
77         // the value returned from this function is non-zero.
78         if self.0.is_empty() {
79             unsafe { core::hint::unreachable_unchecked() };
80         }
81         self.0.len()
82     }
83 
84     /// Returns `true` if the string only includes `NUL`.
85     #[inline]
86     pub const fn is_empty(&self) -> bool {
87         self.len() == 0
88     }
89 
90     /// Wraps a raw C string pointer.
91     ///
92     /// # Safety
93     ///
94     /// `ptr` must be a valid pointer to a `NUL`-terminated C string, and it must
95     /// last at least `'a`. When `CStr` is alive, the memory pointed by `ptr`
96     /// must not be mutated.
97     #[inline]
98     pub unsafe fn from_char_ptr<'a>(ptr: *const core::ffi::c_char) -> &'a Self {
99         // SAFETY: The safety precondition guarantees `ptr` is a valid pointer
100         // to a `NUL`-terminated C string.
101         let len = unsafe { bindings::strlen(ptr) } + 1;
102         // SAFETY: Lifetime guaranteed by the safety precondition.
103         let bytes = unsafe { core::slice::from_raw_parts(ptr as _, len as _) };
104         // SAFETY: As `len` is returned by `strlen`, `bytes` does not contain interior `NUL`.
105         // As we have added 1 to `len`, the last byte is known to be `NUL`.
106         unsafe { Self::from_bytes_with_nul_unchecked(bytes) }
107     }
108 
109     /// Creates a [`CStr`] from a `[u8]`.
110     ///
111     /// The provided slice must be `NUL`-terminated, does not contain any
112     /// interior `NUL` bytes.
113     pub const fn from_bytes_with_nul(bytes: &[u8]) -> Result<&Self, CStrConvertError> {
114         if bytes.is_empty() {
115             return Err(CStrConvertError::NotNulTerminated);
116         }
117         if bytes[bytes.len() - 1] != 0 {
118             return Err(CStrConvertError::NotNulTerminated);
119         }
120         let mut i = 0;
121         // `i + 1 < bytes.len()` allows LLVM to optimize away bounds checking,
122         // while it couldn't optimize away bounds checks for `i < bytes.len() - 1`.
123         while i + 1 < bytes.len() {
124             if bytes[i] == 0 {
125                 return Err(CStrConvertError::InteriorNul);
126             }
127             i += 1;
128         }
129         // SAFETY: We just checked that all properties hold.
130         Ok(unsafe { Self::from_bytes_with_nul_unchecked(bytes) })
131     }
132 
133     /// Creates a [`CStr`] from a `[u8]` without performing any additional
134     /// checks.
135     ///
136     /// # Safety
137     ///
138     /// `bytes` *must* end with a `NUL` byte, and should only have a single
139     /// `NUL` byte (or the string will be truncated).
140     #[inline]
141     pub const unsafe fn from_bytes_with_nul_unchecked(bytes: &[u8]) -> &CStr {
142         // SAFETY: Properties of `bytes` guaranteed by the safety precondition.
143         unsafe { core::mem::transmute(bytes) }
144     }
145 
146     /// Returns a C pointer to the string.
147     #[inline]
148     pub const fn as_char_ptr(&self) -> *const core::ffi::c_char {
149         self.0.as_ptr() as _
150     }
151 
152     /// Convert the string to a byte slice without the trailing 0 byte.
153     #[inline]
154     pub fn as_bytes(&self) -> &[u8] {
155         &self.0[..self.len()]
156     }
157 
158     /// Convert the string to a byte slice containing the trailing 0 byte.
159     #[inline]
160     pub const fn as_bytes_with_nul(&self) -> &[u8] {
161         &self.0
162     }
163 
164     /// Yields a [`&str`] slice if the [`CStr`] contains valid UTF-8.
165     ///
166     /// If the contents of the [`CStr`] are valid UTF-8 data, this
167     /// function will return the corresponding [`&str`] slice. Otherwise,
168     /// it will return an error with details of where UTF-8 validation failed.
169     ///
170     /// # Examples
171     ///
172     /// ```
173     /// # use kernel::str::CStr;
174     /// let cstr = CStr::from_bytes_with_nul(b"foo\0").unwrap();
175     /// assert_eq!(cstr.to_str(), Ok("foo"));
176     /// ```
177     #[inline]
178     pub fn to_str(&self) -> Result<&str, core::str::Utf8Error> {
179         core::str::from_utf8(self.as_bytes())
180     }
181 
182     /// Unsafely convert this [`CStr`] into a [`&str`], without checking for
183     /// valid UTF-8.
184     ///
185     /// # Safety
186     ///
187     /// The contents must be valid UTF-8.
188     ///
189     /// # Examples
190     ///
191     /// ```
192     /// # use kernel::c_str;
193     /// # use kernel::str::CStr;
194     /// // SAFETY: String literals are guaranteed to be valid UTF-8
195     /// // by the Rust compiler.
196     /// let bar = c_str!("ツ");
197     /// assert_eq!(unsafe { bar.as_str_unchecked() }, "ツ");
198     /// ```
199     #[inline]
200     pub unsafe fn as_str_unchecked(&self) -> &str {
201         unsafe { core::str::from_utf8_unchecked(self.as_bytes()) }
202     }
203 
204     /// Convert this [`CStr`] into a [`CString`] by allocating memory and
205     /// copying over the string data.
206     pub fn to_cstring(&self) -> Result<CString, AllocError> {
207         CString::try_from(self)
208     }
209 }
210 
211 impl fmt::Display for CStr {
212     /// Formats printable ASCII characters, escaping the rest.
213     ///
214     /// ```
215     /// # use kernel::c_str;
216     /// # use kernel::str::CStr;
217     /// # use kernel::str::CString;
218     /// let penguin = c_str!("��");
219     /// let s = CString::try_from_fmt(fmt!("{}", penguin)).unwrap();
220     /// assert_eq!(s.as_bytes_with_nul(), "\\xf0\\x9f\\x90\\xa7\0".as_bytes());
221     ///
222     /// let ascii = c_str!("so \"cool\"");
223     /// let s = CString::try_from_fmt(fmt!("{}", ascii)).unwrap();
224     /// assert_eq!(s.as_bytes_with_nul(), "so \"cool\"\0".as_bytes());
225     /// ```
226     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
227         for &c in self.as_bytes() {
228             if (0x20..0x7f).contains(&c) {
229                 // Printable character.
230                 f.write_char(c as char)?;
231             } else {
232                 write!(f, "\\x{:02x}", c)?;
233             }
234         }
235         Ok(())
236     }
237 }
238 
239 impl fmt::Debug for CStr {
240     /// Formats printable ASCII characters with a double quote on either end, escaping the rest.
241     ///
242     /// ```
243     /// # use kernel::c_str;
244     /// # use kernel::str::CStr;
245     /// # use kernel::str::CString;
246     /// let penguin = c_str!("��");
247     /// let s = CString::try_from_fmt(fmt!("{:?}", penguin)).unwrap();
248     /// assert_eq!(s.as_bytes_with_nul(), "\"\\xf0\\x9f\\x90\\xa7\"\0".as_bytes());
249     ///
250     /// // Embedded double quotes are escaped.
251     /// let ascii = c_str!("so \"cool\"");
252     /// let s = CString::try_from_fmt(fmt!("{:?}", ascii)).unwrap();
253     /// assert_eq!(s.as_bytes_with_nul(), "\"so \\\"cool\\\"\"\0".as_bytes());
254     /// ```
255     fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
256         f.write_str("\"")?;
257         for &c in self.as_bytes() {
258             match c {
259                 // Printable characters.
260                 b'\"' => f.write_str("\\\"")?,
261                 0x20..=0x7e => f.write_char(c as char)?,
262                 _ => write!(f, "\\x{:02x}", c)?,
263             }
264         }
265         f.write_str("\"")
266     }
267 }
268 
269 impl AsRef<BStr> for CStr {
270     #[inline]
271     fn as_ref(&self) -> &BStr {
272         self.as_bytes()
273     }
274 }
275 
276 impl Deref for CStr {
277     type Target = BStr;
278 
279     #[inline]
280     fn deref(&self) -> &Self::Target {
281         self.as_bytes()
282     }
283 }
284 
285 impl Index<ops::RangeFrom<usize>> for CStr {
286     type Output = CStr;
287 
288     #[inline]
289     fn index(&self, index: ops::RangeFrom<usize>) -> &Self::Output {
290         // Delegate bounds checking to slice.
291         // Assign to _ to mute clippy's unnecessary operation warning.
292         let _ = &self.as_bytes()[index.start..];
293         // SAFETY: We just checked the bounds.
294         unsafe { Self::from_bytes_with_nul_unchecked(&self.0[index.start..]) }
295     }
296 }
297 
298 impl Index<ops::RangeFull> for CStr {
299     type Output = CStr;
300 
301     #[inline]
302     fn index(&self, _index: ops::RangeFull) -> &Self::Output {
303         self
304     }
305 }
306 
307 mod private {
308     use core::ops;
309 
310     // Marker trait for index types that can be forward to `BStr`.
311     pub trait CStrIndex {}
312 
313     impl CStrIndex for usize {}
314     impl CStrIndex for ops::Range<usize> {}
315     impl CStrIndex for ops::RangeInclusive<usize> {}
316     impl CStrIndex for ops::RangeToInclusive<usize> {}
317 }
318 
319 impl<Idx> Index<Idx> for CStr
320 where
321     Idx: private::CStrIndex,
322     BStr: Index<Idx>,
323 {
324     type Output = <BStr as Index<Idx>>::Output;
325 
326     #[inline]
327     fn index(&self, index: Idx) -> &Self::Output {
328         &self.as_bytes()[index]
329     }
330 }
331 
332 /// Creates a new [`CStr`] from a string literal.
333 ///
334 /// The string literal should not contain any `NUL` bytes.
335 ///
336 /// # Examples
337 ///
338 /// ```
339 /// # use kernel::c_str;
340 /// # use kernel::str::CStr;
341 /// const MY_CSTR: &CStr = c_str!("My awesome CStr!");
342 /// ```
343 #[macro_export]
344 macro_rules! c_str {
345     ($str:expr) => {{
346         const S: &str = concat!($str, "\0");
347         const C: &$crate::str::CStr = match $crate::str::CStr::from_bytes_with_nul(S.as_bytes()) {
348             Ok(v) => v,
349             Err(_) => panic!("string contains interior NUL"),
350         };
351         C
352     }};
353 }
354 
355 #[cfg(test)]
356 mod tests {
357     use super::*;
358 
359     #[test]
360     fn test_cstr_to_str() {
361         let good_bytes = b"\xf0\x9f\xa6\x80\0";
362         let checked_cstr = CStr::from_bytes_with_nul(good_bytes).unwrap();
363         let checked_str = checked_cstr.to_str().unwrap();
364         assert_eq!(checked_str, "��");
365     }
366 
367     #[test]
368     #[should_panic]
369     fn test_cstr_to_str_panic() {
370         let bad_bytes = b"\xc3\x28\0";
371         let checked_cstr = CStr::from_bytes_with_nul(bad_bytes).unwrap();
372         checked_cstr.to_str().unwrap();
373     }
374 
375     #[test]
376     fn test_cstr_as_str_unchecked() {
377         let good_bytes = b"\xf0\x9f\x90\xA7\0";
378         let checked_cstr = CStr::from_bytes_with_nul(good_bytes).unwrap();
379         let unchecked_str = unsafe { checked_cstr.as_str_unchecked() };
380         assert_eq!(unchecked_str, "��");
381     }
382 }
383 
384 /// Allows formatting of [`fmt::Arguments`] into a raw buffer.
385 ///
386 /// It does not fail if callers write past the end of the buffer so that they can calculate the
387 /// size required to fit everything.
388 ///
389 /// # Invariants
390 ///
391 /// The memory region between `pos` (inclusive) and `end` (exclusive) is valid for writes if `pos`
392 /// is less than `end`.
393 pub(crate) struct RawFormatter {
394     // Use `usize` to use `saturating_*` functions.
395     beg: usize,
396     pos: usize,
397     end: usize,
398 }
399 
400 impl RawFormatter {
401     /// Creates a new instance of [`RawFormatter`] with an empty buffer.
402     fn new() -> Self {
403         // INVARIANT: The buffer is empty, so the region that needs to be writable is empty.
404         Self {
405             beg: 0,
406             pos: 0,
407             end: 0,
408         }
409     }
410 
411     /// Creates a new instance of [`RawFormatter`] with the given buffer pointers.
412     ///
413     /// # Safety
414     ///
415     /// If `pos` is less than `end`, then the region between `pos` (inclusive) and `end`
416     /// (exclusive) must be valid for writes for the lifetime of the returned [`RawFormatter`].
417     pub(crate) unsafe fn from_ptrs(pos: *mut u8, end: *mut u8) -> Self {
418         // INVARIANT: The safety requirements guarantee the type invariants.
419         Self {
420             beg: pos as _,
421             pos: pos as _,
422             end: end as _,
423         }
424     }
425 
426     /// Creates a new instance of [`RawFormatter`] with the given buffer.
427     ///
428     /// # Safety
429     ///
430     /// The memory region starting at `buf` and extending for `len` bytes must be valid for writes
431     /// for the lifetime of the returned [`RawFormatter`].
432     pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self {
433         let pos = buf as usize;
434         // INVARIANT: We ensure that `end` is never less then `buf`, and the safety requirements
435         // guarantees that the memory region is valid for writes.
436         Self {
437             pos,
438             beg: pos,
439             end: pos.saturating_add(len),
440         }
441     }
442 
443     /// Returns the current insert position.
444     ///
445     /// N.B. It may point to invalid memory.
446     pub(crate) fn pos(&self) -> *mut u8 {
447         self.pos as _
448     }
449 
450     /// Return the number of bytes written to the formatter.
451     pub(crate) fn bytes_written(&self) -> usize {
452         self.pos - self.beg
453     }
454 }
455 
456 impl fmt::Write for RawFormatter {
457     fn write_str(&mut self, s: &str) -> fmt::Result {
458         // `pos` value after writing `len` bytes. This does not have to be bounded by `end`, but we
459         // don't want it to wrap around to 0.
460         let pos_new = self.pos.saturating_add(s.len());
461 
462         // Amount that we can copy. `saturating_sub` ensures we get 0 if `pos` goes past `end`.
463         let len_to_copy = core::cmp::min(pos_new, self.end).saturating_sub(self.pos);
464 
465         if len_to_copy > 0 {
466             // SAFETY: If `len_to_copy` is non-zero, then we know `pos` has not gone past `end`
467             // yet, so it is valid for write per the type invariants.
468             unsafe {
469                 core::ptr::copy_nonoverlapping(
470                     s.as_bytes().as_ptr(),
471                     self.pos as *mut u8,
472                     len_to_copy,
473                 )
474             };
475         }
476 
477         self.pos = pos_new;
478         Ok(())
479     }
480 }
481 
482 /// Allows formatting of [`fmt::Arguments`] into a raw buffer.
483 ///
484 /// Fails if callers attempt to write more than will fit in the buffer.
485 pub(crate) struct Formatter(RawFormatter);
486 
487 impl Formatter {
488     /// Creates a new instance of [`Formatter`] with the given buffer.
489     ///
490     /// # Safety
491     ///
492     /// The memory region starting at `buf` and extending for `len` bytes must be valid for writes
493     /// for the lifetime of the returned [`Formatter`].
494     pub(crate) unsafe fn from_buffer(buf: *mut u8, len: usize) -> Self {
495         // SAFETY: The safety requirements of this function satisfy those of the callee.
496         Self(unsafe { RawFormatter::from_buffer(buf, len) })
497     }
498 }
499 
500 impl Deref for Formatter {
501     type Target = RawFormatter;
502 
503     fn deref(&self) -> &Self::Target {
504         &self.0
505     }
506 }
507 
508 impl fmt::Write for Formatter {
509     fn write_str(&mut self, s: &str) -> fmt::Result {
510         self.0.write_str(s)?;
511 
512         // Fail the request if we go past the end of the buffer.
513         if self.0.pos > self.0.end {
514             Err(fmt::Error)
515         } else {
516             Ok(())
517         }
518     }
519 }
520 
521 /// An owned string that is guaranteed to have exactly one `NUL` byte, which is at the end.
522 ///
523 /// Used for interoperability with kernel APIs that take C strings.
524 ///
525 /// # Invariants
526 ///
527 /// The string is always `NUL`-terminated and contains no other `NUL` bytes.
528 ///
529 /// # Examples
530 ///
531 /// ```
532 /// use kernel::str::CString;
533 ///
534 /// let s = CString::try_from_fmt(fmt!("{}{}{}", "abc", 10, 20)).unwrap();
535 /// assert_eq!(s.as_bytes_with_nul(), "abc1020\0".as_bytes());
536 ///
537 /// let tmp = "testing";
538 /// let s = CString::try_from_fmt(fmt!("{tmp}{}", 123)).unwrap();
539 /// assert_eq!(s.as_bytes_with_nul(), "testing123\0".as_bytes());
540 ///
541 /// // This fails because it has an embedded `NUL` byte.
542 /// let s = CString::try_from_fmt(fmt!("a\0b{}", 123));
543 /// assert_eq!(s.is_ok(), false);
544 /// ```
545 pub struct CString {
546     buf: Vec<u8>,
547 }
548 
549 impl CString {
550     /// Creates an instance of [`CString`] from the given formatted arguments.
551     pub fn try_from_fmt(args: fmt::Arguments<'_>) -> Result<Self, Error> {
552         // Calculate the size needed (formatted string plus `NUL` terminator).
553         let mut f = RawFormatter::new();
554         f.write_fmt(args)?;
555         f.write_str("\0")?;
556         let size = f.bytes_written();
557 
558         // Allocate a vector with the required number of bytes, and write to it.
559         let mut buf = Vec::try_with_capacity(size)?;
560         // SAFETY: The buffer stored in `buf` is at least of size `size` and is valid for writes.
561         let mut f = unsafe { Formatter::from_buffer(buf.as_mut_ptr(), size) };
562         f.write_fmt(args)?;
563         f.write_str("\0")?;
564 
565         // SAFETY: The number of bytes that can be written to `f` is bounded by `size`, which is
566         // `buf`'s capacity. The contents of the buffer have been initialised by writes to `f`.
567         unsafe { buf.set_len(f.bytes_written()) };
568 
569         // Check that there are no `NUL` bytes before the end.
570         // SAFETY: The buffer is valid for read because `f.bytes_written()` is bounded by `size`
571         // (which the minimum buffer size) and is non-zero (we wrote at least the `NUL` terminator)
572         // so `f.bytes_written() - 1` doesn't underflow.
573         let ptr = unsafe { bindings::memchr(buf.as_ptr().cast(), 0, (f.bytes_written() - 1) as _) };
574         if !ptr.is_null() {
575             return Err(EINVAL);
576         }
577 
578         // INVARIANT: We wrote the `NUL` terminator and checked above that no other `NUL` bytes
579         // exist in the buffer.
580         Ok(Self { buf })
581     }
582 }
583 
584 impl Deref for CString {
585     type Target = CStr;
586 
587     fn deref(&self) -> &Self::Target {
588         // SAFETY: The type invariants guarantee that the string is `NUL`-terminated and that no
589         // other `NUL` bytes exist.
590         unsafe { CStr::from_bytes_with_nul_unchecked(self.buf.as_slice()) }
591     }
592 }
593 
594 impl<'a> TryFrom<&'a CStr> for CString {
595     type Error = AllocError;
596 
597     fn try_from(cstr: &'a CStr) -> Result<CString, AllocError> {
598         let mut buf = Vec::new();
599 
600         buf.try_extend_from_slice(cstr.as_bytes_with_nul())
601             .map_err(|_| AllocError)?;
602 
603         // INVARIANT: The `CStr` and `CString` types have the same invariants for
604         // the string data, and we copied it over without changes.
605         Ok(CString { buf })
606     }
607 }
608 
609 /// A convenience alias for [`core::format_args`].
610 #[macro_export]
611 macro_rules! fmt {
612     ($($f:tt)*) => ( core::format_args!($($f)*) )
613 }
614