authorgravatar for squeek502@hotmail.comRyan Liptak <squeek502@hotmail.com> 2022-06-23 17:01:56-07:00
committergravatar for squeek502@hotmail.comRyan Liptak <squeek502@hotmail.com> 2022-06-23 17:01:56-07:00
log819e0e83d338a898f06d1e39c21da812ac58238b
tree22b84046196b11d1844ca1a8f0b168cedea82a63
parentca9862578903a93089e6aae71bb8641b580bc4f6

Add stack trace capturing to FailingAllocator


1 files changed, 24 insertions(+), 0 deletions(-)

lib/std/testing/failing_allocator.zig+24
......@@ -19,6 +19,8 @@ pub const FailingAllocator = struct {
1919 freed_bytes: usize,
2020 allocations: usize,
2121 deallocations: usize,
22 stack_addresses: [16]usize,
23 has_induced_failure: bool,
2224
2325 /// `fail_index` is the number of successful allocations you can
2426 /// expect from this allocator. The next allocation will fail.
......@@ -37,6 +39,8 @@ pub const FailingAllocator = struct {
3739 .freed_bytes = 0,
3840 .allocations = 0,
3941 .deallocations = 0,
42 .stack_addresses = undefined,
43 .has_induced_failure = false,
4044 };
4145 }
4246
......@@ -52,6 +56,13 @@ pub const FailingAllocator = struct {
5256 return_address: usize,
5357 ) error{OutOfMemory}![]u8 {
5458 if (self.index == self.fail_index) {
59 mem.set(usize, &self.stack_addresses, 0);
60 var stack_trace = std.builtin.StackTrace{
61 .instruction_addresses = &self.stack_addresses,
62 .index = 0,
63 };
64 std.debug.captureStackTrace(return_address, &stack_trace);
65 self.has_induced_failure = true;
5566 return error.OutOfMemory;
5667 }
5768 const result = try self.internal_allocator.rawAlloc(len, ptr_align, len_align, return_address);
......@@ -88,4 +99,17 @@ pub const FailingAllocator = struct {
8899 self.deallocations += 1;
89100 self.freed_bytes += old_mem.len;
90101 }
102
103 /// Only valid once `has_induced_failure == true`
104 pub fn getStackTrace(self: *FailingAllocator) std.builtin.StackTrace {
105 std.debug.assert(self.has_induced_failure);
106 var len: usize = 0;
107 while (len < self.stack_addresses.len and self.stack_addresses[len] != 0) {
108 len += 1;
109 }
110 return .{
111 .instruction_addresses = &self.stack_addresses,
112 .index = len,
113 };
114 }
91115};