| 1 |
#include "utils/microfmt.hpp" |
| 2 |
#ifdef CPPTRACE_DEMANGLE_WITH_CXXABI |
| 3 |
|
| 4 |
#include "demangle/demangle.hpp" |
| 5 |
|
| 6 |
#include "utils/utils.hpp" |
| 7 |
|
| 8 |
#include <cxxabi.h> |
| 9 |
|
| 10 |
#include <cstdlib> |
| 11 |
#include <functional> |
| 12 |
#include <string> |
| 13 |
|
| 14 |
CPPTRACE_BEGIN_NAMESPACE |
| 15 |
namespace detail { |
| 16 |
std::string demangle(const std::string& name, bool check_prefix) { |
| 17 |
// https://itanium-cxx-abi.github.io/cxx-abi/abi.html#demangler |
| 18 |
// Check both _Z and __Z, apple prefixes all symbols with an underscore |
| 19 |
if(check_prefix && !(starts_with(name, "_Z") || starts_with(name, "__Z"))) { |
| 20 |
return name; |
| 21 |
} |
| 22 |
// Apple clang demangles __Z just fine but gcc doesn't, so just offset the leading underscore |
| 23 |
std::size_t offset = 0; |
| 24 |
if(starts_with(name, "__Z")) { |
| 25 |
offset = 1; |
| 26 |
} |
| 27 |
// Mangled names don't have spaces, we might add a space and some extra info somewhere but we still want it to |
| 28 |
// be demanglable. Look for a space, if there is one swap it with a null terminator briefly. |
| 29 |
auto end = name.find(' '); |
| 30 |
std::string name_copy; |
| 31 |
std::reference_wrapper<const std::string> to_demangle = name; |
| 32 |
std::string rest; |
| 33 |
if(end != std::string::npos) { |
| 34 |
name_copy = name.substr(0, end); |
| 35 |
rest = name.substr(end); |
| 36 |
to_demangle = name_copy; |
| 37 |
} |
| 38 |
// presumably thread-safe |
| 39 |
// it appears safe to pass nullptr for status however the docs don't explicitly say it's safe so I don't |
| 40 |
// want to rely on it |
| 41 |
int status; |
| 42 |
auto demangled = raii_wrap( |
| 43 |
abi::__cxa_demangle(to_demangle.get().c_str() + offset, nullptr, nullptr, &status), |
| 44 |
[] (char* str) { std::free(str); } |
| 45 |
); |
| 46 |
// demangled will always be nullptr on non-zero status, and if __cxa_demangle ever fails for any reason |
| 47 |
// we'll just quietly return the mangled name |
| 48 |
if(demangled.get()) { |
| 49 |
std::string str = demangled.get(); |
| 50 |
if(!rest.empty()) { |
| 51 |
str += rest; |
| 52 |
} |
| 53 |
return str; |
| 54 |
} else { |
| 55 |
return name; |
| 56 |
} |
| 57 |
} |
| 58 |
} |
| 59 |
CPPTRACE_END_NAMESPACE |
| 60 |
|
| 61 |
#endif |