[PATCH] rust: alloc: check the length precondition in Vec::from_raw_parts
From: Peder Bergan via B4 Relay
Date: Mon Nov 16 2026 - 07:53:42 EST
From: Peder Bergan <peder.bergan@xxxxxxxxx>
Vec::from_raw_parts() requires length to be no greater than capacity for
nonzero-sized elements. Check this precondition with
unsafe_precondition_assert!() before constructing the vector so debug
builds diagnose invalid raw parts at this boundary.
Keep the check in the nonzero-sized branch because zero-sized vectors
ignore the capacity argument. Add a KUnit test for reconstructing a
nonempty zero-sized vector with a zero capacity argument.
Suggested-by: Miguel Ojeda <ojeda@xxxxxxxxxx>
Link: https://github.com/Rust-for-Linux/linux/issues/1232
Signed-off-by: Peder Bergan <peder.bergan@xxxxxxxxx>
---
Based on alloc-next.
My validation used the x86_64 rust_kvec KUnit suite under QEMU with
CLIPPY=1 and debug assertions enabled and disabled. All six tests passed
in both configurations. A temporary invalid-length probe triggered the
expected precondition diagnostic. The baseline has an unrelated unused
function warning in io/resource.rs, also present after this change.
OpenAI Codex assisted with coding and testing.
---
rust/kernel/alloc/kvec.rs | 17 ++++++++++++++++-
1 file changed, 16 insertions(+), 1 deletion(-)
diff --git a/rust/kernel/alloc/kvec.rs b/rust/kernel/alloc/kvec.rs
index cd0c57a9a..b8f4c1692 100644
--- a/rust/kernel/alloc/kvec.rs
+++ b/rust/kernel/alloc/kvec.rs
@@ -23,7 +23,8 @@ use crate::{
page::{
AsPageIter,
PAGE_SIZE, //
- }, //
+ },
+ unsafe_precondition_assert, //
};
use core::{
@@ -685,6 +686,8 @@ where
let layout = if Self::is_zst() {
ArrayLayout::empty()
} else {
+ unsafe_precondition_assert!(length <= capacity);
+
// SAFETY: By the safety requirements of this function, `capacity * size_of::<T>()` is
// smaller than `isize::MAX`.
unsafe { ArrayLayout::new_unchecked(capacity) }
@@ -1623,6 +1626,18 @@ mod tests {
use super::*;
use crate::prelude::*;
+ #[test]
+ fn test_kvec_from_raw_parts_zst() {
+ let ptr = NonNull::<()>::dangling().as_ptr();
+
+ // SAFETY: For a zero-sized type, `ptr` only needs to be dangling and well aligned.
+ // The capacity argument is ignored.
+ let v = unsafe { KVec::from_raw_parts(ptr, 3, 0) };
+
+ assert_eq!(v.len(), 3);
+ assert_eq!(v.capacity(), usize::MAX);
+ }
+
#[test]
fn test_kvec_retain() {
/// Verify correctness for one specific function.
---
base-commit: a2a82cbb73342d605078cb85763472f40156af1f
change-id: 20261116-vec-raw-parts-precondition-b540ab5ccceb
Best regards,
--
Peder Bergan <peder.bergan@xxxxxxxxx>