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