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

From
Peder Bergan via B4 Relay <devnull+peder.bergan.gmail.com@kernel.org>
Date
2026-11-17 17:57:07
Also in
b4-sent, lkml, stable
Reply to
Peder Bergan via B4 Relay, 2026-11-17
From: Peder Bergan <redacted>

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]`.")
Cc: <redacted>
Reported-by: Georgios Androutsopoulos <redacted>
Closes: https://github.com/Rust-for-Linux/linux/issues/1261
Signed-off-by: Peder Bergan <redacted>
---
 rust/kernel/str.rs | 4 ++--
 1 file changed, 2 insertions(+), 2 deletions(-)
diff --git a/rust/kernel/str.rs b/rust/kernel/str.rs
index 644b4279a..e5fe84eeb 100644
--- a/rust/kernel/str.rs
+++ b/rust/kernel/str.rs
@@ -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()) }
-- 
2.56.1

Thread (9 messages) 9 messages, 5 authors, last reply 8d ago
Keyboard shortcuts
hback out one level
jnext message in thread / next series-diff position
kprevious message in thread / previous series-diff position
ldrill in
Escclose help / fold thread tree
?toggle this help