Skip to content

Commit 7b43912

Browse files
authored
Merge pull request #37 from SFBdragon/main
Validate user allocation size to resolve #32
2 parents 621d530 + d303d1c commit 7b43912

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed

src/dlmalloc.rs

+15
Original file line numberDiff line numberDiff line change
@@ -1168,6 +1168,21 @@ impl<A: Allocator> Dlmalloc<A> {
11681168
}
11691169
}
11701170

1171+
pub unsafe fn validate_size(&mut self, ptr: *mut u8, size: usize) {
1172+
let p = Chunk::from_mem(ptr);
1173+
let psize = Chunk::size(p);
1174+
1175+
let min_overhead = self.overhead_for(p);
1176+
assert!(psize >= size + min_overhead);
1177+
1178+
if !Chunk::mmapped(p) {
1179+
let max_overhead =
1180+
min_overhead + self.min_chunk_size() * 2 + mem::align_of::<usize>() - 1;
1181+
1182+
assert!(psize <= size + max_overhead);
1183+
}
1184+
}
1185+
11711186
pub unsafe fn free(&mut self, mem: *mut u8) {
11721187
self.check_malloc_state();
11731188

src/lib.rs

+4-1
Original file line numberDiff line numberDiff line change
@@ -141,7 +141,8 @@ impl<A: Allocator> Dlmalloc<A> {
141141
/// method contracts.
142142
#[inline]
143143
pub unsafe fn free(&mut self, ptr: *mut u8, size: usize, align: usize) {
144-
let _ = (size, align);
144+
let _ = align;
145+
self.0.validate_size(ptr, size);
145146
self.0.free(ptr)
146147
}
147148

@@ -162,6 +163,8 @@ impl<A: Allocator> Dlmalloc<A> {
162163
old_align: usize,
163164
new_size: usize,
164165
) -> *mut u8 {
166+
self.0.validate_size(ptr, old_size);
167+
165168
if old_align <= self.0.malloc_alignment() {
166169
self.0.realloc(ptr, new_size)
167170
} else {

0 commit comments

Comments
 (0)