Skip to content

Commit

Permalink
Merge pull request #37 from SFBdragon/main
Browse files Browse the repository at this point in the history
Validate user allocation size to resolve #32
  • Loading branch information
alexcrichton committed Jan 30, 2024
2 parents 621d530 + d303d1c commit 7b43912
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 1 deletion.
15 changes: 15 additions & 0 deletions src/dlmalloc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -1168,6 +1168,21 @@ 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) {
let max_overhead =
min_overhead + self.min_chunk_size() * 2 + mem::align_of::<usize>() - 1;

assert!(psize <= size + max_overhead);
}
}

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 7b43912

Please sign in to comment.