Skip to content

Commit

Permalink
validate user allocation size
Browse files Browse the repository at this point in the history
  • Loading branch information
SFBdragon committed Jan 28, 2024
1 parent 621d530 commit 74fbdb5
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 1 deletion.
12 changes: 12 additions & 0 deletions src/dlmalloc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1168,6 +1168,18 @@ impl<A: Allocator> Dlmalloc<A> {
}
}

pub unsafe fn validate_size(&mut self, ptr: *mut u8, size: usize) {
let p = Chunk::from_mem(ptr);
let psize = Chunk::size(p);

let min_overhead = self.overhead_for(p);
assert!(psize >= size + min_overhead);

if !Chunk::mmapped(p) {
assert!(psize <= size + min_overhead + self.min_chunk_size() * 2 + mem::align_of::<usize>() - 1);
}
}

pub unsafe fn free(&mut self, mem: *mut u8) {
self.check_malloc_state();

Expand Down
5 changes: 4 additions & 1 deletion src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,8 @@ impl<A: Allocator> Dlmalloc<A> {
/// method contracts.
#[inline]
pub unsafe fn free(&mut self, ptr: *mut u8, size: usize, align: usize) {
let _ = (size, align);
let _ = align;
self.0.validate_size(ptr, size);
self.0.free(ptr)
}

Expand All @@ -162,6 +163,8 @@ impl<A: Allocator> Dlmalloc<A> {
old_align: usize,
new_size: usize,
) -> *mut u8 {
self.0.validate_size(ptr, old_size);

if old_align <= self.0.malloc_alignment() {
self.0.realloc(ptr, new_size)
} else {
Expand Down

0 comments on commit 74fbdb5

Please sign in to comment.