Skip to contentSkip to conversation

rust: alloc: add smoke test for zero-size realloc code path

PATCH New Hsiu Che Yu 1 participant 1 message Apr 24

Subsystems (2)
lore
Share & tools
lore
#0 lore raw

PATCH v2 1/1 rust: alloc: add smoke test for zero-size realloc code path

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.

---
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(+)
rust/kernel/alloc/allocator.rs +25 -0
index 63bfb91b3671..85606c30dab6 100644
@@ -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(())
+    }
 }
Signature · 1 line
2.43.0