[ox/std] Improve stacktrace clarity

This commit is contained in:
Gary Talent 2021-05-07 06:45:10 -05:00
parent 462f5b580b
commit 1c509ca20d
2 changed files with 46 additions and 10 deletions

View File

@ -7,23 +7,59 @@
*/
#if defined(OX_USE_STDLIB) && __has_include(<unistd.h>)
#include <array>
#include <execinfo.h>
#include <iostream>
#include <execinfo.h>
#include <dlfcn.h>
#include <unistd.h>
#if __has_include(<cxxabi.h>)
#include <cxxabi.h>
#endif
#endif
#include "stacktrace.hpp"
#include "error.hpp"
#include "string.hpp"
#include "trace.hpp"
#include "units.hpp"
#include "utility.hpp"
#include "vector.hpp"
namespace ox {
void printStackTrace([[maybe_unused]]int shave) noexcept {
#if defined(OX_USE_STDLIB) && __has_include(<unistd.h>)
std::array<void*, 100> frames;
auto size = static_cast<int>(backtrace(frames.data(), frames.size()));
if (size > shave) {
std::cout << "\nStacktrace:\n";
backtrace_symbols_fd(frames.data() + shave, size - shave, STDERR_FILENO);
[[nodiscard]]
static String symbolicate([[maybe_unused]]const char **frames, [[maybe_unused]]std::size_t symbolsLen, [[maybe_unused]]const char *linePrefix) {
#if __has_include(<cxxabi.h>)
String out;
for (auto i = 0u; i < symbolsLen; ++i) {
Dl_info info;
if (dladdr(frames[i], &info) && info.dli_sname) {
int status = -1;
const auto name = abi::__cxa_demangle(info.dli_sname, nullptr, 0, &status);
if (status == 0) {
out += sfmt("\t{}: {}\n", i, name);
continue;
}
}
out += sfmt("\t{}\n", frames[i]);
}
return move(out);
#else // __has_include(<cxxabi.h>)
return {};
#endif // __has_include(<cxxabi.h>)
}
#endif // defined(OX_USE_STDLIB) && __has_include(<unistd.h>)
void printStackTrace([[maybe_unused]]unsigned shave) noexcept {
#if defined(OX_USE_STDLIB) && __has_include(<unistd.h>)
Vector<void*> frames(1000);
frames.resize(static_cast<std::size_t>(backtrace(frames.data(), frames.size())));
if (frames.size() > shave) {
const auto symbols = backtrace_symbols(frames.data() + shave, frames.size() - shave);
const auto symbolicatedStacktrace = symbolicate(bit_cast<const char**>(frames.data()), frames.size() - shave, "\t");
free(symbols);
oxErrf("Stacktrace:\n{}", symbolicatedStacktrace);
}
#endif
}

View File

@ -15,6 +15,6 @@ namespace ox {
*
* @param shave number of call levels to shave off the top
*/
void printStackTrace(int shave = 1) noexcept;
void printStackTrace(unsigned shave = 1) noexcept;
}