Skip to content

Instantly share code, notes, and snippets.

@fmela
Last active September 22, 2023 10:58
Show Gist options
  • Save fmela/591333 to your computer and use it in GitHub Desktop.
Save fmela/591333 to your computer and use it in GitHub Desktop.
A C++ function that produces a stack backtrace with demangled function & method names.
#include <execinfo.h> // for backtrace
#include <dlfcn.h> // for dladdr
#include <cxxabi.h> // for __cxa_demangle
#include <string>
#include <sstream>
// This function produces a stack backtrace with demangled function & method names.
std::string Backtrace(int skip = 1)
{
void *callstack[128];
const int nMaxFrames = sizeof(callstack) / sizeof(callstack[0]);
char buf[1024];
int nFrames = backtrace(callstack, nMaxFrames);
char **symbols = backtrace_symbols(callstack, nFrames);
std::ostringstream trace_buf;
for (int i = skip; i < nFrames; i++) {
Dl_info info;
if (dladdr(callstack[i], &info)) {
char *demangled = NULL;
int status;
demangled = abi::__cxa_demangle(info.dli_sname, NULL, 0, &status);
snprintf(buf, sizeof(buf), "%-3d %*0p %s + %zd\n",
i, 2 + sizeof(void*) * 2, callstack[i],
status == 0 ? demangled : info.dli_sname,
(char *)callstack[i] - (char *)info.dli_saddr);
free(demangled);
} else {
snprintf(buf, sizeof(buf), "%-3d %*0p\n",
i, 2 + sizeof(void*) * 2, callstack[i]);
}
trace_buf << buf;
snprintf(buf, sizeof(buf), "%s\n", symbols[i]);
trace_buf << buf;
}
free(symbols);
if (nFrames == nMaxFrames)
trace_buf << "[truncated]\n";
return trace_buf.str();
}
@fmela
Copy link
Author

fmela commented Sep 22, 2010

A C++ function that will produce a stack trace with demangled function and method names.

@Qwlouse
Copy link

Qwlouse commented Mar 12, 2013

Awesome! YMMD ^^

@fmela
Copy link
Author

fmela commented Apr 22, 2013

Glad you found it useful. :)

@dholm
Copy link

dholm commented May 21, 2013

Thanks for this very useful gist!
If you are linking your binary using GNU ld you need to add --export-dynamic or most of your symbols will just be resolved to the name of the binary.

@fmela
Copy link
Author

fmela commented Oct 28, 2013

Good point @dholm, thank you.

@dgotwisner
Copy link

I'm wanting to use a modification of this in some commercial software (saves a bit of re-inventing). What copyright and license is this released with?

@fmela
Copy link
Author

fmela commented Jul 8, 2017

@dgotwisner In the past I've favored the BSD 2-clause license, so I've updated the gist to reflect this. I hope this works for you!

@pabitrad
Copy link

I am not getting correct function names of a C++ program.

funcname

@pthalamy
Copy link

@pabitrad, this is probably due the missing -export-dynamic GCC flag.
Trying rebuilding with : g++ -g -fpic -std=c++14 -export-dynamic Main.cpp -ldl -o Main.

That did it for me. It works like a charm, thanks @fmela! 😉

@drhongo
Copy link

drhongo commented Feb 26, 2019

pabitrad's problem is due to an error in the code: In snprintf format string replace '%*0p' by '%0*p'. That will fix it.

@franku
Copy link

franku commented Jun 18, 2019

Thanks for this useful piece of code! We changed it a little to return a std::vector instead of a string buffer.
https://github.com/bareos/bareos

@xiaozhuai
Copy link

Awesome! It would be better if it supported pretty print c++ method name.

__ZN4wuta12WTFaceModule14rendererUpdateENS_11RenderSceneENS_10RenderModeERNS_10InputFrameEiiii

wuta::WTFaceModule::rendererUpdate(wuta::RenderScene, wuta::RenderMode, wuta::InputFrame&, int, int, int, int)

Like what c++filt do

@fmela
Copy link
Author

fmela commented Aug 13, 2020

@xiaozhuai, it should be de-mangling the names. Would you share your compiler, compiler flags, and linker flags here?

@xiaozhuai
Copy link

@fmela Android NDK 15 with clang.

-D__ANDROID_API__=21 -g -DANDROID -ffunction-sections -funwind-tables -fstack-protector-strong -no-canonical-prefixes  -mfloat-abi=softfp -mfpu=vfpv3-d16 -fno-integrated-as -mthumb -mfpu=neon -Wa,--noexecstack -Wformat -Werror=format-security -std=c++11  -O3

@fmela
Copy link
Author

fmela commented Aug 18, 2020

Sorry @xiaozhuai, I'm not familiar with compilation on Android. I did notice that --export-dynamic is not present in your flags. Did you try that?

@xiaozhuai
Copy link

@fmela I use clang, there is no --export-dynamic supported : (

@xiaozhuai
Copy link

xiaozhuai commented Aug 19, 2020

1   14_framebuffer                      0x00000001024de654 _Z11initProgramv + 52
2   14_framebuffer                      0x00000001024e47f6 main + 1206
3   libdyld.dylib                       0x00007fff6ce713d5 start + 1

I also try it on my mac. It seems abi::__cxa_demangle not working.

Apple LLVM version 10.0.1 (clang-1001.0.46.4)
Target: x86_64-apple-darwin18.7.0
Thread model: posix
InstalledDir: /Library/Developer/CommandLineTools/usr/bin

@fmela
Copy link
Author

fmela commented Aug 19, 2020

@xiaozhuai Sorry, I should have mentioned that that is a linker flag, not a compiler flag. You might need to try -Wl,--export-dynamic.

@xiaozhuai
Copy link

@fmela It works now, it should be -Wl,-export-dynamic. Thank you very much!

@N1coc4colA
Copy link

As this code work just... perfectly, can I add it to a library addon that have to make C++ development easier with a this library?

@zwimer
Copy link

zwimer commented Jun 28, 2021

Would it be possible to add an open source license to this so other projects can more freely use it? If you don't know which you prefer, this is a really simple guide to help: https://choosealicense.com/

@haseeb-heaven
Copy link

It doesn't work in Windows , you should state it only work in Linux

@f18m
Copy link

f18m commented Nov 22, 2021

This solution is nice but it's lacking the source code file and line number... I found backward-cpp (https://github.com/bombela/backward-cpp) to be better fitting my needs.,

@cppcooper
Copy link

This solution is nice but it's lacking the source code file and line number... I found backward-cpp (https://github.com/bombela/backward-cpp) to be better fitting my needs.,

nice, thanks for updating the thread here!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment