Skip to content

Commit

Permalink
Zero freed memory in trace mode.
Browse files Browse the repository at this point in the history
  • Loading branch information
fubark committed Aug 26, 2024
1 parent 91bf62d commit baf8875
Showing 1 changed file with 41 additions and 1 deletion.
42 changes: 41 additions & 1 deletion src/heap.zig
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ var gpa: std.heap.GeneralPurposeAllocator(.{
.stack_trace_frames = if (builtin.mode == .Debug) 12 else 0,
}) = .{};
var miAlloc: mi.Allocator = undefined;
var trace_allocator: TraceAllocator = undefined;
var initedAllocator = false;

fn initAllocator() void {
Expand Down Expand Up @@ -57,7 +58,12 @@ pub fn getAllocator() std.mem.Allocator {
},
.zig => {
if (builtin.is_test) {
return t.alloc;
if (cy.Trace) {
trace_allocator.alloc = t.alloc;
return trace_allocator.allocator();
} else {
return t.alloc;
}
}
if (cy.isWasm) {
return std.heap.wasm_allocator;
Expand Down Expand Up @@ -88,6 +94,40 @@ pub fn deinitAllocator() void {
}
}

// Uses a backing allocator and zeros the freed memory to surface UB more consistently.
pub const TraceAllocator = struct {
alloc: std.mem.Allocator,

const vtable = std.mem.Allocator.VTable{
.alloc = alloc,
.resize = resize,
.free = free,
};

pub fn allocator(self: *TraceAllocator) std.mem.Allocator {
return std.mem.Allocator{
.ptr = self,
.vtable = &vtable,
};
}

fn alloc(ptr: *anyopaque, len: usize, log2_align: u8, ret_addr: usize) ?[*]u8 {
const self: *TraceAllocator = @ptrCast(@alignCast(ptr));
return self.alloc.rawAlloc(len, log2_align, ret_addr);
}

fn resize(ptr: *anyopaque, buf: []u8, log2_align: u8, new_len: usize, ret_addr: usize) bool {
const self: *TraceAllocator = @ptrCast(@alignCast(ptr));
return self.alloc.rawResize(buf, log2_align, new_len, ret_addr);
}

fn free(ptr: *anyopaque, buf: []u8, log2_align: u8, ret_addr: usize) void {
const self: *TraceAllocator = @ptrCast(@alignCast(ptr));
@memset(buf, 0);
return self.alloc.rawFree(buf, log2_align, ret_addr);
}
};

// Keep it just under 4kb page.
pub const HeapPage = struct {
objects: [102]HeapObject,
Expand Down

0 comments on commit baf8875

Please sign in to comment.