[PATCH] rust/alloc: mention layout in Box::from_raw()
From: David Rheinsberg
Date: Wed Apr 01 2026 - 07:17:08 EST
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@xxxxxxxxxx>
Signed-off-by: David Rheinsberg <david@xxxxxxxxxxxx>
---
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