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 {...@@ -19,6 +19,8 @@ pub const FailingAllocator = struct {
19 freed_bytes: usize,19 freed_bytes: usize,
20 allocations: usize,20 allocations: usize,
21 deallocations: usize,21 deallocations: usize,
22 stack_addresses: [16]usize,
23 has_induced_failure: bool,
2224
23 /// `fail_index` is the number of successful allocations you can25 /// `fail_index` is the number of successful allocations you can
24 /// expect from this allocator. The next allocation will fail.26 /// expect from this allocator. The next allocation will fail.
...@@ -37,6 +39,8 @@ pub const FailingAllocator = struct {...@@ -37,6 +39,8 @@ pub const FailingAllocator = struct {
37 .freed_bytes = 0,39 .freed_bytes = 0,
38 .allocations = 0,40 .allocations = 0,
39 .deallocations = 0,41 .deallocations = 0,
42 .stack_addresses = undefined,
43 .has_induced_failure = false,
40 };44 };
41 }45 }
4246
...@@ -52,6 +56,13 @@ pub const FailingAllocator = struct {...@@ -52,6 +56,13 @@ pub const FailingAllocator = struct {
52 return_address: usize,56 return_address: usize,
53 ) error{OutOfMemory}![]u8 {57 ) error{OutOfMemory}![]u8 {
54 if (self.index == self.fail_index) {58 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;
55 return error.OutOfMemory;66 return error.OutOfMemory;
56 }67 }
57 const result = try self.internal_allocator.rawAlloc(len, ptr_align, len_align, return_address);68 const result = try self.internal_allocator.rawAlloc(len, ptr_align, len_align, return_address);
...@@ -88,4 +99,17 @@ pub const FailingAllocator = struct {...@@ -88,4 +99,17 @@ pub const FailingAllocator = struct {
88 self.deallocations += 1;99 self.deallocations += 1;
89 self.freed_bytes += old_mem.len;100 self.freed_bytes += old_mem.len;
90 }101 }
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 }
91};115};