Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions rust/kernel/alloc/allocator.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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::<u8>().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::<u8>().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::<u8>().as_ptr() as usize & (align - 1), 0);
KVmalloc::free(kvm.cast(), layout);
}
}

let empty: KVec<u64> = KVec::new();
drop(empty);
let empty_cap: KVec<u64> = KVec::with_capacity(0, GFP_KERNEL)?;
drop(empty_cap);

Ok(())
}
}
Loading