106

The Linux specific backtrace() and backtrace_symbols() allows you to produce a call trace of the program. However, it only prints function addresses, not their names for my program. How can I make them print the function names as well ? I've tried compiling the program with -g as well as -ggdb. The test case below just prints this:


    BACKTRACE ------------
    ./a.out() [0x8048616]
    ./a.out() [0x8048623]
    /lib/libc.so.6(__libc_start_main+0xf3) [0x4a937413]
    ./a.out() [0x8048421]
    ----------------------
    

I'd want the first 2 items to also show the function names, foo and main

Code:

#include <execinfo.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <stdlib.h>

static void full_write(int fd, const char *buf, size_t len)
{
        while (len > 0) {
                ssize_t ret = write(fd, buf, len);

                if ((ret == -1) && (errno != EINTR))
                        break;

                buf += (size_t) ret;
                len -= (size_t) ret;
        }
}

void print_backtrace(void)
{
        static const char start[] = "BACKTRACE ------------\n";
        static const char end[] = "----------------------\n";

        void *bt[1024];
        int bt_size;
        char **bt_syms;
        int i;

        bt_size = backtrace(bt, 1024);
        bt_syms = backtrace_symbols(bt, bt_size);
        full_write(STDERR_FILENO, start, strlen(start));
        for (i = 1; i < bt_size; i++) {
                size_t len = strlen(bt_syms[i]);
                full_write(STDERR_FILENO, bt_syms[i], len);
                full_write(STDERR_FILENO, "\n", 1);
        }
        full_write(STDERR_FILENO, end, strlen(end));
    free(bt_syms);
}
void foo()
{
    print_backtrace();
}

int main()
{
    foo();
    return 0;
}
SamB
  • 9,039
  • 5
  • 49
  • 56
Lyke
  • 4,575
  • 6
  • 27
  • 26
  • possible duplicate of [How to get more detailed backtrace](http://stackoverflow.com/questions/5945775/how-to-get-more-detailed-backtrace) – Nemo Aug 04 '11 at 00:51
  • 2
    btw, function `backtrace_symbols_fd` performs the same operation as `backtrace_symbols()`, but the resulting strings are immediately written to the file descriptor `fd`. – nhnghia Jul 16 '18 at 10:01
  • I have tested several methods in detail at: https://stackoverflow.com/questions/3899870/print-call-stack-in-c-or-c/54365144#54365144 – Ciro Santilli OurBigBook.com Jan 25 '19 at 12:20
  • Since the second argument of backtrace() specifies the maximum number of addresses that can be stored in the buffer specified by the first (man 3 backtrace), a value of 1024 is unnecessarily generous here. A value of 20 should do fine, and printing a warning for possible truncation when bt_size == 20 is good practice. – Robert Jul 27 '21 at 13:13

5 Answers5

76

The symbols are taken from the dynamic symbol table; you need the -rdynamic option to gcc, which makes it pass a flag to the linker which ensures that all symbols are placed in the table.

(See the Link Options page of the GCC manual, and / or the Backtraces page of the glibc manual.)

Matthew Slattery
  • 45,290
  • 8
  • 103
  • 119
  • 12
    This doesn't work for static symbols, though. `libunwind` that @Nemo mentions, works for static functions. – Nathan Kidd Mar 18 '14 at 00:22
  • 1
    In a CMake project, this had mistakenly been set as `ADD_COMPILE_OPTIONS(-rdynamic)`. Instead, it needs to be `ADD_LINK_OPTIONS(-rdynamic)` or equivalent to have the desired behaviour. – Stéphane Jul 17 '20 at 19:54
  • 1
    Better yet for those using cmake: `SET (CMAKE_ENABLE_EXPORTS TRUE)`. This sets the -rdynamic linker flag. – Stéphane Jan 17 '21 at 18:55
34

Use the addr2line command to map executable addresses to source code filename+line number. Give the -f option to get function names as well.

Alternatively, try libunwind.

Nemo
  • 70,042
  • 10
  • 116
  • 153
  • 3
    addr2 line is nice because it includes file name and line number in the output, but it fails as soon as relocations are performed by the loader. – Erwan Legrand Jun 05 '14 at 14:14
  • ... and with ASLR relocations are more common than ever. – Erwan Legrand Jun 05 '14 at 14:18
  • @ErwanLegrand: Before ASLR, I thought the relocations were predictable and `addr2line` worked reliably even for addresses in shared objects (?) But yeah, on modern platforms you would need to know the actual load address of the relocatable object even to do this operation in principle. – Nemo Jun 05 '14 at 14:24
  • I can't tell for sure how well it worked before ASLR. Nowadays, it will only for for code inside "regular" executables and fail for code inside DSOs and PIEs (Position Independent Executables). Fortunately, libunwind appears to work for all of these. – Erwan Legrand Jun 05 '14 at 14:34
  • I had forgotten about this discussion. Libbacktrace, which I did not know of at the time, is a better option. (See my new answer.) – Erwan Legrand May 27 '15 at 10:15
15

The excellent Libbacktrace by Ian Lance Taylor solves this issue. It handles stack unwinding and supports both ordinary ELF symbols and DWARF debugging symbols.

Libbacktrace does not require exporting all symbols, which would be ugly, and ASLR does not break it.

Libbacktrace was originally part of the GCC distribution. Now, a standalone version can be found on Github:

https://github.com/ianlancetaylor/libbacktrace

Erwan Legrand
  • 4,148
  • 26
  • 26
2

the answer on the top has a bug if ret == -1 and errno is EINTER you should try again, but not count ret as copied (not going to make an account just for this, if you don't like it tough)

static void full_write(int fd, const char *buf, size_t len)
{
        while (len > 0) {
                ssize_t ret = write(fd, buf, len);

                if ((ret == -1) {
                        if (errno != EINTR))
                                break;
                        //else
                        continue;
                }
                buf += (size_t) ret;
                len -= (size_t) ret;
        }
}
Billg
  • 21
  • 1
2

Boost backtrace

Very convenient because it prints both:

  • unmangled C++ function names
  • line numbers

automatically for you.

Usage summary:

#define BOOST_STACKTRACE_USE_ADDR2LINE
#include <boost/stacktrace.hpp>

std::cout << boost::stacktrace::stacktrace() << std::endl;

I have provided a minimal runnable example for it and many other methods at: print call stack in C or C++

Ciro Santilli OurBigBook.com
  • 347,512
  • 102
  • 1,199
  • 985