[PATCH v2] rust: alloc: add smoke test for zero-size realloc code path

Hsiu Che Yu posted 1 patch 1 month, 3 weeks ago
rust/kernel/alloc/allocator.rs | 25 +++++++++++++++++++++++++
1 file changed, 25 insertions(+)
[PATCH v2] rust: alloc: add smoke test for zero-size realloc code path
Posted by Hsiu Che Yu 1 month, 3 weeks ago
The `Allocator` trait documents that reallocating with a target size of
zero must be equivalent to freeing the memory:
    "If the requested size is zero, `realloc` behaves equivalent
    to `free`."
Add a smoke test to verify that `Kmalloc`, `Vmalloc`, and `KVmalloc`
do not error or panic when reallocating with a zero target size.
Note that the actual deallocation performed by the underlying C
functions is not verified here.

Link: https://lore.kernel.org/all/20260424052936.250238-1-yu.whisper.personal@gmail.com
Signed-off-by: Hsiu Che Yu <yu.whisper.personal@gmail.com>
---
v2: clarify that this is a smoke test and does not verify actual
        deallocation

 rust/kernel/alloc/allocator.rs | 25 +++++++++++++++++++++++++
 1 file changed, 25 insertions(+)

diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs
index 63bfb91b3671..85606c30dab6 100644
--- a/rust/kernel/alloc/allocator.rs
+++ b/rust/kernel/alloc/allocator.rs
@@ -305,4 +305,29 @@ fn is_aligned_to(&self, align: usize) -> bool {
 
         Ok(())
     }
+
+    #[test]
+    fn test_realloc_zero_size_does_not_error() -> Result {
+        // Note: this test only verifies that zero-size realloc completes without
+        // error. The actual deallocation is performed by the underlying C functions
+        // and is not verified here.
+        const INIT_SIZE: usize = 64;
+
+        let old = Layout::from_size_align(INIT_SIZE, 1).unwrap();
+        let new = Layout::from_size_align(0, 1).unwrap();
+
+        let existing = unsafe { Kmalloc::realloc(None, old, old, GFP_KERNEL, NumaNode::NO_NODE)? };
+        let existing_ptr = existing.cast::<u8>();
+        unsafe { Kmalloc::realloc(Some(existing_ptr), new, old, GFP_KERNEL, NumaNode::NO_NODE)? };
+
+        let existing = unsafe { Vmalloc::realloc(None, old, old, GFP_KERNEL, NumaNode::NO_NODE)? };
+        let existing_ptr = existing.cast::<u8>();
+        unsafe { Vmalloc::realloc(Some(existing_ptr), new, old, GFP_KERNEL, NumaNode::NO_NODE)? };
+
+        let existing = unsafe { KVmalloc::realloc(None, old, old, GFP_KERNEL, NumaNode::NO_NODE)? };
+        let existing_ptr = existing.cast::<u8>();
+        unsafe { KVmalloc::realloc(Some(existing_ptr), new, old, GFP_KERNEL, NumaNode::NO_NODE)? };
+
+        Ok(())
+    }
 }
-- 
2.43.0