Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an application programmatically generate its own stacktrace?

Tags:

c

stack-trace

I have a program written in C that runs on Linux, MacOS and Windows. Is there a way I can call a function and generate a stack trace? This would be super-useful for me. Ideally I'd like to do it on all three platforms, but Linux is the most important. (Windows is being compiled via mingw.)

Thanks.

like image 647
vy32 Avatar asked Nov 07 '11 01:11

vy32


People also ask

How do you get a Stacktrace?

You can obtain a stack trace from a thread – by calling the getStackTrace method on that Thread instance. This invocation returns an array of StackTraceElement, from which details about stack frames of the thread can be extracted.

How can I print stack trace without exception?

Just use new Throwable(). printStackTrace() method and it will print complete stack trace from where a method is called, into the console.


2 Answers

For example, in GCC and the GNU libc C library, you can use backtrace().

As @slugonamission suggests, Windows offers CaptureStackBackTrace() - thanks!

Other platforms may offer similar features.

(This is obviously a platform-dependent question.)

(On a related note, there also exist self-disassembly libraries.)

like image 179
Kerrek SB Avatar answered Oct 04 '22 04:10

Kerrek SB


I'm using this code to generate debug stack traces. It uses libunwind to get the stacktrace and libdwfl to read debug information.

It produces nice Java-like stack traces, with function names and source locations. eg.:

at c(stack_trace.c:95)
at b(stack_trace.c:100)
at a(stack_trace.c:105)
at main(stack_trace.c:110)

libunwind should work on Windows and Mac, but libdwfl is Linux and ELF specific.

like image 28
Piotr Praszmo Avatar answered Oct 04 '22 02:10

Piotr Praszmo