How to make backtrace()/backtrace_symbols() print the function names?

后端 未结 5 1779
别那么骄傲
别那么骄傲 2020-11-29 16:57

The Linux specific backtrace() and backtrace_symbols() allows you to produce a call trace of the program. However, it only prints function addresse

相关标签:
5条回答
  • 2020-11-29 17:09

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

    0 讨论(0)
  • 2020-11-29 17:13

    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.

    0 讨论(0)
  • 2020-11-29 17:19

    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;
            }
    }
    
    0 讨论(0)
  • 2020-11-29 17:20

    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

    0 讨论(0)
  • 2020-11-29 17:22

    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++

    0 讨论(0)
提交回复
热议问题