geting stack trace from signal handlers

nazriel spam at dzfl.pl
Thu Jun 6 08:44:00 PDT 2013


On Wednesday, 5 June 2013 at 21:05:53 UTC, Timothee Cour wrote:
> how do i get a stacktrace inside handleTermination?
>
> If not currently possible, could we have a compile flag that 
> would enable
> this kind of feature? (making code slower would be OK, its an 
> opt in
> feature)
> Ideally we'd also be able to walk up or down the stack trace 
> (kind of what
> gdb would do, but I'd like to be able to do that without 
> resorting to gdb,
> using a language/library solution)
>
> ----
>
> import core.sys.posix.signal;
> import std.c.stdlib;
> import std.stdio;
>
> void main(string[] args)
> {
>         bsd_signal(SIGINT, &handleTermination);
>
>         while (true)
>         {
>
>         }
> }
>
> extern(C) void handleTermination(int signal)
> {
>         writefln("Caught signal: %s", signal);
>         exit(signal);
> }
>
> -----

You mean call stack?
Maybe something like this:
http://dpaste.dzfl.pl/99f217be

---
import core.sys.posix.signal;
import std.c.stdlib;
import std.stdio;
import std.conv;

void main(string[] args)
{
        bsd_signal(SIGINT, &handleTermination);

        while (true)
        {

        }
}

extern(C) void handleTermination(int signal)
{
        writefln("Caught signal: %s", signal);
        getTrace();
        exit(signal);
}

extern (C) void* thread_stackBottom();
extern (C) char** backtrace_symbols(void**, int size);

void getTrace() {
     void*[10] callstack;
     void** stackTop;
     void** stackBottom = cast(void**) thread_stackBottom();

     asm {
         mov [stackTop], RBP;
     }

     auto curr = stackTop;

     size_t i;
     for (i = 0; stackTop <= curr &&
         curr < stackBottom && i < 10;)
     {
         callstack[i++] = *(curr+1);
         curr = cast(void**) *curr;
     }

     auto ret = backtrace_symbols(callstack.ptr, cast(int) i);
     for (; i > 0; i--) {
         writeln((*ret).to!string());
         ret++;
     }
}
---


More information about the Digitalmars-d-learn mailing list