Skip to content

Commit 101b25c

Browse files
author
Clark Gaebel
committed
[liballoc] Adds checks for UB during allocation.
They're only enabled in debug builds, but a panic is usually more welcome than UB in debug builds.
1 parent dc630d0 commit 101b25c

File tree

1 file changed

+12
-0
lines changed

1 file changed

+12
-0
lines changed

src/liballoc/heap.rs

+12
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,15 @@
88
// option. This file may not be copied, modified, or distributed
99
// except according to those terms.
1010

11+
use core::{isize, usize};
12+
13+
#[inline(always)]
14+
fn check_size_and_alignment(size: usize, align: usize) {
15+
debug_assert!(size != 0);
16+
debug_assert!(size <= isize::MAX as usize, "Tried to allocate too much: {} bytes", size);
17+
debug_assert!(usize::is_power_of_two(align), "Invalid alignment of allocation: {}", align);
18+
}
19+
1120
// FIXME: #13996: mark the `allocate` and `reallocate` return value as `noalias`
1221

1322
/// Return a pointer to `size` bytes of memory aligned to `align`.
@@ -19,6 +28,7 @@
1928
/// size on the platform.
2029
#[inline]
2130
pub unsafe fn allocate(size: usize, align: usize) -> *mut u8 {
31+
check_size_and_alignment(size, align);
2232
imp::allocate(size, align)
2333
}
2434

@@ -38,6 +48,7 @@ pub unsafe fn allocate(size: usize, align: usize) -> *mut u8 {
3848
/// any value in range_inclusive(requested_size, usable_size).
3949
#[inline]
4050
pub unsafe fn reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usize) -> *mut u8 {
51+
check_size_and_alignment(size, align);
4152
imp::reallocate(ptr, old_size, size, align)
4253
}
4354

@@ -56,6 +67,7 @@ pub unsafe fn reallocate(ptr: *mut u8, old_size: usize, size: usize, align: usiz
5667
#[inline]
5768
pub unsafe fn reallocate_inplace(ptr: *mut u8, old_size: usize, size: usize,
5869
align: usize) -> usize {
70+
check_size_and_alignment(size, align);
5971
imp::reallocate_inplace(ptr, old_size, size, align)
6072
}
6173

0 commit comments

Comments
 (0)