Skip to content

Commit ca08655

Browse files
alloc: custom realloc
Signed-off-by: Andy-Python-Programmer <[email protected]>
1 parent f75215d commit ca08655

File tree

1 file changed

+18
-0
lines changed

1 file changed

+18
-0
lines changed

src/aero_kernel/src/mem/alloc.rs

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -321,6 +321,24 @@ unsafe impl GlobalAlloc for LockedHeap {
321321

322322
self.0.dealloc(ptr, layout)
323323
}
324+
325+
unsafe fn realloc(&self, ptr: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {
326+
// SAFETY: the caller must ensure that the `new_size` does not overflow.
327+
// `layout.align()` comes from a `Layout` and is thus guaranteed to be valid.
328+
let new_layout = Layout::from_size_align_unchecked(new_size, layout.align());
329+
// SAFETY: the caller must ensure that `new_layout` is greater than zero.
330+
let new_ptr = self.alloc(new_layout);
331+
332+
// NOTE: It is fine to pass a NULL pointer to `realloc` so, we need to check for that.
333+
if !new_ptr.is_null() && !ptr.is_null() {
334+
// SAFETY: the previously allocated block cannot overlap the newly allocated block.
335+
// The safety contract for `dealloc` must be upheld by the caller.
336+
core::ptr::copy_nonoverlapping(ptr, new_ptr, core::cmp::min(layout.size(), new_size));
337+
self.dealloc(ptr, layout);
338+
}
339+
340+
new_ptr
341+
}
324342
}
325343

326344
#[alloc_error_handler]

0 commit comments

Comments
 (0)