Skip to content

Commit

Permalink
fix: prevent buffer overrun in aligned allocations
Browse files Browse the repository at this point in the history
  • Loading branch information
dweiller committed Sep 20, 2023
1 parent 7abfe9e commit e70b99d
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 6 deletions.
24 changes: 18 additions & 6 deletions src/Heap.zig
Original file line number Diff line number Diff line change
Expand Up @@ -170,12 +170,7 @@ pub fn allocate(self: *Heap, len: usize, log2_align: u8, ret_addr: usize) ?Alloc

const class = sizeClass(slot_size_min);

if (self.allocateSizeClass(class, log2_align)) |allocation| {
@memset(allocation.ptr[0..indexToSize(class)], undefined);
return allocation;
}

return null;
return self.allocateSizeClass(class, log2_align);
}

pub fn canResizeInPlace(self: *Heap, buf: []u8, log2_align: u8, new_len: usize, ret_addr: usize) bool {
Expand Down Expand Up @@ -460,6 +455,23 @@ test "slot alignment" {
}
}

test "allocate with larger alignment" {
var heap = Heap.init();
defer heap.deinit();

for (0..size_class_count) |class| {
const size = (3 * indexToSize(class)) / 2;
const slot_log2_align = @ctz(indexToSize(class));
const log2_align = slot_log2_align + 1;
const allocation = heap.allocate(size, log2_align, 0) orelse {
log.err("failed to allocate size class {d}", .{class});
return error.BadSizeClass;
};
const actual_log2_align: std.math.Log2Int(usize) = @intCast(@ctz(@intFromPtr(allocation.ptr)));
try std.testing.expect(@ctz(indexToSize(class)) <= actual_log2_align);
}
}

test "huge allocation alignment - allocateHuge" {
var heap = Heap.init();
defer heap.deinit();
Expand Down
1 change: 1 addition & 0 deletions src/Page.zig
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,7 @@ pub fn allocSlotFast(self: *Page) ?Slot {
const node_ptr = self.alloc_free_list.popFirst() orelse return null;
const casted_ptr: [*]align(constants.min_slot_alignment) u8 = @ptrCast(node_ptr);
self.used_count += 1;
@memset(casted_ptr[0..self.slot_size], undefined);
return @ptrCast(casted_ptr[0..self.slot_size]);
}

Expand Down

0 comments on commit e70b99d

Please sign in to comment.