[ox/std] Make stacktrace code more readable

This commit is contained in:
Gary Talent 2023-06-02 20:29:58 -05:00
parent 68b6942606
commit 25954d5503

View File

@ -1,5 +1,5 @@
/*
* Copyright 2015 - 2022 gary@drinkingtea.net
* Copyright 2015 - 2023 gary@drinkingtea.net
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
@ -7,7 +7,6 @@
*/
#if defined(OX_USE_STDLIB) && __has_include(<unistd.h>)
#include <iostream>
#if __has_include(<execinfo.h>)
#include <execinfo.h>
@ -27,13 +26,14 @@ namespace ox {
#if defined(OX_USE_STDLIB) && __has_include(<unistd.h>)
[[nodiscard]]
static auto symbolicate([[maybe_unused]]char **frames,
[[maybe_unused]]std::size_t symbolsLen,
static auto symbolicate([[maybe_unused]]void **frames,
[[maybe_unused]]std::size_t frameCnt,
[[maybe_unused]]const char *linePrefix) {
using StrT = BasicString<100>;
Vector<StrT, 30> out;
#if __has_include(<cxxabi.h>) && __has_include(<execinfo.h>)
for (auto i = 0u; i < symbolsLen; ++i) {
const auto mangledSymbols = backtrace_symbols(frames, static_cast<int>(frameCnt));
for (auto i = 0u; i < frameCnt; ++i) {
Dl_info info;
if (dladdr(frames[i], &info) && info.dli_sname) {
int status = -1;
@ -43,8 +43,9 @@ static auto symbolicate([[maybe_unused]]char **frames,
continue;
}
}
out.emplace_back(sfmt<StrT>("{}", frames[i]));
out.emplace_back(sfmt<StrT>("{}: {}", i, mangledSymbols[i]));
}
free(mangledSymbols);
#endif // __has_include(<cxxabi.h>)
return out;
}
@ -56,9 +57,7 @@ void printStackTrace([[maybe_unused]]unsigned shave) noexcept {
Vector<void*, FrameCnt> frames(FrameCnt);
frames.resize(static_cast<std::size_t>(backtrace(frames.data(), static_cast<int>(frames.size()))));
if (frames.size() - shave > 2) {
const auto symbols = backtrace_symbols(frames.data() + shave, static_cast<int>(frames.size() - shave));
const auto symbolicatedStacktrace = symbolicate(reinterpret_cast<char**>(frames.data() + shave), frames.size() - shave, "\t");
free(symbols);
const auto symbolicatedStacktrace = symbolicate(frames.data() + shave, frames.size() - shave, "\t");
oxErr("Stacktrace:\n");
for (const auto &s : symbolicatedStacktrace) {
oxErrf("\t{}\n", s);