3

I'm developing under Linux/gcc

I currently use the following to get a stack trace on custom thrown exceptions. Demangled functions names and line numbers are as expected, but I would like to avoid the use of addr2line to have a full control on the formatting of the output strings.

static void posix_print_stack_trace()
{
    int i, trace_size = 0;
    char **messages = (char **)NULL;

    trace_size = backtrace(stack_traces, MAX_STACK_FRAMES);
    messages = backtrace_symbols(stack_traces, trace_size);

    for (i = 0; i < trace_size; ++i)
    {
        if (addr2line(program_invocation_name, stack_traces[i]) != 0)
        {
            printf("  error determining line # for: %s\n", messages[i]);
        }
    }
    if (messages) { free(messages); }
}

static int addr2line(char const * const program_name, void const * const addr)
{
    char addr2line_cmd[512] = {0}; 
    sprintf(addr2line_cmd,"addr2line -C -f -p -i -e %.256s %p", program_name, addr);
    return system(addr2line_cmd);
}

Note : The use of -f for displaying the functions names in play in the stack trace and -C to display them demangled.

Q : Does anyone could point me on a programmatic solution ? (And if possibly give me some advices on how to get it working as well with MinGW/gcc).

NB : Or may be simply using gdb in some way could help in getting more customized output ?

Thanks for the help.

EDIT : It looks like for the windows part, it is doable that way : https://stackoverflow.com/a/6207030/1715716

EDIT : The above points to a Microsoft Visual only solution, so is finally useless to me.

Community
  • 1
  • 1
Gauthier Boaglio
  • 10,054
  • 5
  • 48
  • 85

1 Answers1

3

You probably could use or adapt (at least on Linux, and systems using ELF and DWARF) the libbacktrace by Ian Taylor, which is currently inside GCC source tree. See here; in principle it should be usable independently of GCC (provided you obey its BSD-like license).

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547
  • I don't have any problem with the license, since my own program will be shared under a BSD-like one too. Thanks for the pointer. I'll go into it. – Gauthier Boaglio May 28 '13 at 13:43
  • As you said, I was able to build `libbacktrace` independently from gcc (note that this feature is only part of the early gcc 4.8). I haven't tested building it using MinGW. Hope this is doable, since the pointer given in the EDIT part of my question is Visual only stuff (haven't seen that in the first time)... – Gauthier Boaglio May 29 '13 at 04:26