C++ Logo


Advanced search

Re: Adding stacktrace to std::exception

From: Antony Polukhin <antoshkka_at_[hidden]>
Date: Thu, 12 Nov 2020 17:14:52 +0300
ср, 11 нояб. 2020 г. в 20:32, Kilian Henneberger via Std-Proposals
> Hello everyone,
> if I am informed correctly, P0881 (https://wg21.link/P0881) has been
> approved for C++23.
> And I assume this is no new idea (also not to C++), but what do you
> think about adding a stacktrace to std::exception?

This is a very good idea that was not discussed, because this seemed
to be an ABI breaking change.

However, probably there's a way to not break ABI. Here are some draft ideas:

I. With heavy patching of C++ runtime, like
libstdc++-v3/libsupc++/unwind-cxx.h for GCC (not sure if that does not
count as an ABI break, but the programs either link the runtime
dynamically or are hermetic and are not affected)
1) add std::stacktrace into __cxxabiv1::__cxa_exception and init the
trace in __cxa_allocate_exception (see note 1)
2) Propose a Standard Library `stacktrace
get_stacktrace_from_exception(const E& e);` function that extracts
stacktrace from __cxxabiv1::__cxa_exception

This could be prototyped quite easily ^, but make sure that it does
not count as an ABI break

II . Without breaking the ABI with older c++ runtimes
1) Implement __cxa_allocate_exception2 that allocates (see note 0)
additional space (see note 1) to store the stacktrace AND puts a mark
(see note 2) into the allocated memory, that this is an exception with
a stacktrace
2) Add some __cxa_get_trace(void* ) function that returns you a
stacktrace if the mark is set
3) Force the compiler to use __cxa_allocate_exception2 instead of
4) Propose a Standard Library `stacktrace
get_stacktrace_from_exception(const E& e);` function that calls
`__cxa_get_trace` on `e` and returns a stacktrace

Note 0: it must be a single allocation with the main exception
internals allocation, so that the __cxa_free_exception could do the
cleanup properly without any adjustments
Note 1: No idea if it is implementable on Windows or any other non-ItaniumABIs
Note 2: The mark should not change the layout of the exception
internals. You have to find an unused but zeroed out bit (no idea
where to find such).

If everything is done right, exceptions thrown by old
__cxa_allocate_exception could be processed by new runtime. Old
__cxa_free_exception and __cxa_throw could work with new exceptions by
just not touching the stacktrace machinery.

Note that those ideas require prototyping!

Best regards,
Antony Polukhin

Received on 2020-11-12 08:15:12