| 1 | // { dg-options "-funwind-tables -lstdc++exp" } |
| 2 | // { dg-do run { target c++23 } } |
| 3 | // { dg-require-cpp-feature-test __cpp_lib_stacktrace } |
| 4 | |
| 5 | #include <stacktrace> |
| 6 | #include <memory> |
| 7 | #include <new> |
| 8 | #include "testsuite_hooks.h" |
| 9 | |
| 10 | template<typename T> |
| 11 | struct Allocator |
| 12 | { |
| 13 | using value_type = T; |
| 14 | using propagate_on_container_move_assignment = std::true_type; |
| 15 | |
| 16 | explicit |
| 17 | Allocator(unsigned max = -1u) : max_size(max) { } |
| 18 | |
| 19 | template<typename U> |
| 20 | Allocator(const Allocator<U>& a) : max_size(a.max_size) { } |
| 21 | |
| 22 | T* |
| 23 | allocate(std::size_t n) |
| 24 | { |
| 25 | if (n > max_size) |
| 26 | throw std::bad_alloc(); |
| 27 | |
| 28 | return std::allocator<T>().allocate(n); |
| 29 | } |
| 30 | |
| 31 | void |
| 32 | deallocate(T* p, std::size_t n) noexcept |
| 33 | { |
| 34 | std::allocator<T>().deallocate(p, n); |
| 35 | } |
| 36 | |
| 37 | bool operator==(const Allocator&) const = default; |
| 38 | |
| 39 | private: |
| 40 | unsigned max_size; |
| 41 | }; |
| 42 | |
| 43 | [[gnu::optimize("O0")]] |
| 44 | void |
| 45 | test_max_depth() |
| 46 | { |
| 47 | using Stacktrace = std::basic_stacktrace<Allocator<std::stacktrace_entry>>; |
| 48 | using Alloc = typename Stacktrace::allocator_type; |
| 49 | |
| 50 | [] { [] { [] { [] { [] { [] { [] { [] { |
| 51 | auto t = Stacktrace::current(); |
| 52 | VERIFY( ! t.empty() ); |
| 53 | const auto n = t.size(); // total number of frames |
| 54 | t = Stacktrace::current(8); |
| 55 | VERIFY( t.size() == (n - 8) ); |
| 56 | t = Stacktrace::current(n); |
| 57 | VERIFY( t.empty() ); |
| 58 | t = Stacktrace::current(n - 2); |
| 59 | VERIFY( t.size() == 2 ); |
| 60 | t = Stacktrace::current(2, 6); |
| 61 | VERIFY( t.size() == 6 ); |
| 62 | t = Stacktrace::current(n - 2, 6); |
| 63 | VERIFY( t.size() == 2 ); |
| 64 | |
| 65 | t = Stacktrace::current(Alloc(3)); |
| 66 | // Full stacktrace is larger than 3 frames, so allocation fails: |
| 67 | VERIFY( t.empty() ); |
| 68 | t = Stacktrace::current(3, Alloc(2)); |
| 69 | // Stacktrace still too large after skipping 3 frames, so allocation fails: |
| 70 | VERIFY( t.empty() ); |
| 71 | t = Stacktrace::current(0, 3, Alloc(3)); |
| 72 | // Capacity for exactly 3 frames is allocated: |
| 73 | VERIFY( t.size() == 3 ); |
| 74 | t = Stacktrace::current(2, 4, Alloc(4)); |
| 75 | // Capacity for exactly 4 frames is allocated: |
| 76 | VERIFY( t.size() == 4 ); |
| 77 | t = Stacktrace::current(0, 4, Alloc(3)); |
| 78 | // Capacity for exactly 4 frames is requested, but allocation fails: |
| 79 | VERIFY( t.empty() ); |
| 80 | }(); }(); }(); }(); }(); }(); }(); }(); |
| 81 | } |
| 82 | |
| 83 | int main() |
| 84 | { |
| 85 | test_max_depth(); |
| 86 | } |