diff --git a/rust/kernel/alloc/allocator.rs b/rust/kernel/alloc/allocator.rs index 349a4f665fc4e..9107ac8e9aeff 100644 --- a/rust/kernel/alloc/allocator.rs +++ b/rust/kernel/alloc/allocator.rs @@ -114,6 +114,13 @@ impl ReallocFunc { None => ptr::null(), }; + if size == 0 && ptr.is_null() { + return Ok(NonNull::slice_from_raw_parts( + crate::alloc::dangling_from_layout(layout), + 0, + )); + } + // SAFETY: // - `self.0` is one of `krealloc`, `vrealloc`, `kvrealloc` and thus only requires that // `ptr` is NULL or valid. @@ -322,4 +329,35 @@ mod tests { Ok(()) } + + #[test] + fn test_zero_size() -> Result { + for align in [1, 8, 64, 4096] { + let layout = Layout::from_size_align(0, align).map_err(|_| EINVAL)?; + // SAFETY: Zero-size alloc and free are always valid for all kernel allocators. + unsafe { + let km = Kmalloc::realloc(None, layout, Layout::new::<()>(), GFP_KERNEL, NumaNode::NO_NODE)?; + assert_eq!(km.len(), 0); + assert_eq!(km.cast::().as_ptr() as usize & (align - 1), 0); + Kmalloc::free(km.cast(), layout); + + let vm = Vmalloc::realloc(None, layout, Layout::new::<()>(), GFP_KERNEL, NumaNode::NO_NODE)?; + assert_eq!(vm.len(), 0); + assert_eq!(vm.cast::().as_ptr() as usize & (align - 1), 0); + Vmalloc::free(vm.cast(), layout); + + let kvm = KVmalloc::realloc(None, layout, Layout::new::<()>(), GFP_KERNEL, NumaNode::NO_NODE)?; + assert_eq!(kvm.len(), 0); + assert_eq!(kvm.cast::().as_ptr() as usize & (align - 1), 0); + KVmalloc::free(kvm.cast(), layout); + } + } + + let empty: KVec = KVec::new(); + drop(empty); + let empty_cap: KVec = KVec::with_capacity(0, GFP_KERNEL)?; + drop(empty_cap); + + Ok(()) + } }