Skip to contentSkip to conversation

rust: str: tie Formatter to its backing buffer

PATCH New Peder Bergan 1 participant 3 messages Nov 17

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

v2 cover rust: str: tie Formatter to its backing buffer

Split the lifetime fix and its documentation into separate patches as requested by Gary.

I compiled the fix-only first patch with Clippy and ran the string tests and kernel doctests under x86_64 QEMU. The final source tree is unchanged from v1, including the previously tested example.

OpenAI Codex assisted with coding and testing.

---
Changes in v2:
- Split the documentation and example into a second patch, as requested by Gary.
- Link to v1: https://lore.kernel.org/rust-for-linux/[email protected]/

---
Peder Bergan (2):
rust: str: tie Formatter to its backing buffer
rust: str: add an example for Formatter::new

 rust/kernel/str.rs | 20 ++++++++++++++++++--
 1 file changed, 18 insertions(+), 2 deletions(-)

---
base-commit: aebb7274476403040d582c61478df8f4a7bf9cd3
change-id: 20261117-formatter-lifetime-48391ed7affd

Best regards,

Signature · 1 line
Peder Bergan <[email protected]>
#1 lore raw

PATCH v2 1/2 rust: str: tie Formatter to its backing buffer

Formatter::new() returns a Formatter whose lifetime is independent of the borrow of its backing buffer. Safe code can therefore drop the buffer and then write through the formatter, causing a use-after-free.

Tie the buffer borrow to the formatter's lifetime so that the borrow checker rejects such callers and prevents overlapping mutable access.

Fixes 87482d6d9104 ("rust: str: allow `str::Formatter` to format into `&mut [u8]`.")
---
 rust/kernel/str.rs | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
rust/kernel/str.rs +2 -2
index 644b4279a..e5fe84eeb 100644
@@ -645,7 +645,7 @@ impl fmt::Write for RawFormatter {
 /// Fails if callers attempt to write more than will fit in the buffer.
 pub struct Formatter<'a>(RawFormatter, PhantomData<&'a mut ()>);
 
-impl Formatter<'_> {
+impl<'a> Formatter<'a> {
     /// Creates a new instance of [`Formatter`] with the given buffer.
     ///
     /// # Safety
@@ -658,7 +658,7 @@ impl Formatter<'_> {
     }
 
     /// Create a new [`Self`] instance.
-    pub fn new(buffer: &mut [u8]) -> Self {
+    pub fn new(buffer: &'a mut [u8]) -> Self {
         // SAFETY: `buffer` is valid for writes for the entire length for
         // the lifetime of `Self`.
         unsafe { Formatter::from_buffer(buffer.as_mut_ptr(), buffer.len()) }
Signature · 1 line
2.56.1
#2 lore raw

PATCH v2 2/2 rust: str: add an example for Formatter::new

In reply to Peder Bergan

Document the exclusive buffer borrow held by Formatter::new() and show formatting into a live buffer. Check the number of bytes written and the resulting buffer contents.

---
 rust/kernel/str.rs | 16 ++++++++++++++++
 1 file changed, 16 insertions(+)
rust/kernel/str.rs +16 -0
index e5fe84eeb..6222faacf 100644
@@ -658,6 +658,22 @@ impl<'a> Formatter<'a> {
     }
 
     /// Create a new [`Self`] instance.
+    ///
+    /// The formatter exclusively borrows `buffer` for its lifetime.
+    ///
+    /// # Examples
+    ///
+    /// ```
+    /// use kernel::fmt::Write as _;
+    /// use kernel::str::Formatter;
+    ///
+    /// let mut buffer = [0; 4];
+    /// let mut formatter = Formatter::new(&mut buffer);
+    /// formatter.write_str("test")?;
+    /// assert_eq!(formatter.bytes_written(), 4);
+    /// assert_eq!(&buffer, b"test");
+    /// # Ok::<(), kernel::error::Error>(())
+    /// ```
     pub fn new(buffer: &'a mut [u8]) -> Self {
         // SAFETY: `buffer` is valid for writes for the entire length for
         // the lifetime of `Self`.
Signature · 1 line
2.56.1