c++linuxgccdemangler

c++ : convert symbols to code line numbers programmatically


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.


Solution

  • 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).