public inbox for rust-for-linux@vger.kernel.org
 help / color / mirror / Atom feed
* [PATCH] rust/alloc: mention layout in Box::from_raw()
@ 2026-04-01 10:58 David Rheinsberg
  2026-04-01 11:13 ` Danilo Krummrich
  0 siblings, 1 reply; 2+ messages in thread
From: David Rheinsberg @ 2026-04-01 10:58 UTC (permalink / raw)
  To: rust-for-linux
  Cc: David Rheinsberg, Danilo Krummrich, Lorenzo Stoakes,
	Vlastimil Babka, Liam R. Howlett, Uladzislau Rezki, Boqun Feng,
	Gary Guo, Björn Roy Baron, Benno Lossin, Andreas Hindborg,
	Alice Ryhl, Trevor Gross, linux-kernel

Extend the safety requirements of `Box::from_raw()` to mention that the
layout of the allocation must match exactly. Even though the underlying
allocators maintain allocation layout information to some degree, the
Rust abstraction strictly requires the layout to match exactly.

Suggested-by: Danilo Krummrich <dakr@kernel.org>
Signed-off-by: David Rheinsberg <david@readahead.eu>
---
 rust/kernel/alloc/kbox.rs | 9 +++++----
 1 file changed, 5 insertions(+), 4 deletions(-)

diff --git a/rust/kernel/alloc/kbox.rs b/rust/kernel/alloc/kbox.rs
index 622b3529edfc..1b30c51f87ab 100644
--- a/rust/kernel/alloc/kbox.rs
+++ b/rust/kernel/alloc/kbox.rs
@@ -170,15 +170,16 @@ impl<T, A> Box<T, A>
     ///
     /// # Safety
     ///
-    /// For non-ZSTs, `raw` must point at an allocation allocated with `A` that is sufficiently
-    /// aligned for and holds a valid `T`. The caller passes ownership of the allocation to the
-    /// `Box`.
+    /// For non-ZSTs, `raw` must point at an allocation allocated with `A` with a layout
+    /// of `Layout::for_value::<T>()`. The caller passes ownership of the allocation
+    /// to the `Box`.
     ///
     /// For ZSTs, `raw` must be a dangling, well aligned pointer.
     #[inline]
     pub const unsafe fn from_raw(raw: *mut T) -> Self {
         // INVARIANT: Validity of `raw` is guaranteed by the safety preconditions of this function.
-        // SAFETY: By the safety preconditions of this function, `raw` is not a NULL pointer.
+        // SAFETY: By the safety preconditions of this function, `raw` is not a NULL pointer and
+        // was allocated via `A` for `Layout::for_value::<T>()`.
         Self(unsafe { NonNull::new_unchecked(raw) }, PhantomData)
     }
 
-- 
2.53.0


^ permalink raw reply related	[flat|nested] 2+ messages in thread

end of thread, other threads:[~2026-04-01 11:13 UTC | newest]

Thread overview: 2+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
2026-04-01 10:58 [PATCH] rust/alloc: mention layout in Box::from_raw() David Rheinsberg
2026-04-01 11:13 ` Danilo Krummrich

This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox