1#include <c10/util/Type.h>
2
3#include <cstdlib>
4#include <functional>
5#include <memory>
6
7#if HAS_DEMANGLE
8
9#include <cxxabi.h>
10#include <execinfo.h>
11
12namespace c10 {
13
14std::string demangle(const char* name) {
15 int status = -1;
16
17 // This function will demangle the mangled function name into a more human
18 // readable format, e.g. _Z1gv -> g().
19 // More information:
20 // https://github.com/gcc-mirror/gcc/blob/master/libstdc%2B%2B-v3/libsupc%2B%2B/cxxabi.h
21 // NOTE: `__cxa_demangle` returns a malloc'd string that we have to free
22 // ourselves.
23 std::unique_ptr<char, std::function<void(char*)>> demangled(
24 abi::__cxa_demangle(
25 name,
26 /*__output_buffer=*/nullptr,
27 /*__length=*/nullptr,
28 &status),
29 /*deleter=*/free);
30
31 // Demangling may fail, for example when the name does not follow the
32 // standard C++ (Itanium ABI) mangling scheme. This is the case for `main`
33 // or `clone` for example, so the mangled name is a fine default.
34 if (status == 0) {
35 return demangled.get();
36 } else {
37 return name;
38 }
39}
40
41} // namespace c10
42
43#endif
44