24

I need to get the information provided by addr2line (source file and line from backtracing a function call) from within a C++ program.

I know I can call addr2line directly as a subprocess and I know that I can copy the source code of addr2line into my program (which is also GPL licensed). But the code looks complicated and I don't feel comfortable using it directly. What does bfd mean, anyway? I would prefer to use some function in the C++ STL library, because that would be cleaner.

I am working in a Linux environment.

user7610
  • 25,267
  • 15
  • 124
  • 150
steffen
  • 8,572
  • 11
  • 52
  • 90
  • libdwarf is what youre looking for – Johannes Schaub - litb Jul 19 '12 at 08:23
  • Thankd for the suggestion. I tried dwarfdump and it only prints where functions are declared, not where they are called. I couldn't find a decent documentation though... – steffen Jul 19 '12 at 09:46
  • 2
    `bfd` is the http://en.wikipedia.org/wiki/Binary_File_Descriptor_library (although originally it stood for the other meaning of BFD :) – ecatmur Jul 20 '12 at 12:09
  • 1
    You can see the can see the calls addr2line makes with `ltrace`, but you might not want to link against bfd directly yourself: http://lists.debian.org/debian-devel/2005/05/msg01086.html – Flexo Jul 20 '12 at 12:24
  • doh! So my only way is to call popen("addr2line","r") and parse the output! – steffen Jul 20 '12 at 12:39
  • 1
    Here you have a working implementation. https://github.com/albfan/bindutils-gdb/issues/1. Now is a system call, but its goal is to create a addr2line library. Seems pretty easy! – albfan Oct 08 '16 at 10:13

2 Answers2

7

You can try the function dladdr(). It uses the dynamic symbols of the program, not the debugging information (compile the program with gcc -rdynamic).

Also, you can check the backtrace library, or the higher level stacktrace library.
Not exactly what you are asking, but they may prove useful.

rodrigo
  • 94,151
  • 12
  • 143
  • 190
  • 1
    Thank you for the tipps. With `dladdr()` I get information only for dynamically linked code and only the filename, not the line, if I understand the manpage right. I am already using backtrace to get the address. What I need now is something to get the file and line out of the address. stacktrace is a mere wrapper for backtrace. – steffen Jul 19 '12 at 09:10
  • 1
    In addition to these, there is also the `libunwind` library: http://www.nongnu.org/libunwind/ – Arto Bendiken Jul 03 '15 at 22:24
  • @ArtoBendiken libunwind doesn't have an addr2line-like functionality. It only provides the offset – tjysdsg Jul 25 '21 at 10:36
6

Check the source code of bsd implementation of addr2line, it has only about 400 lines code. Change the source to a library function should be very easy. http://sourceforge.net/p/elftoolchain/code/HEAD/tree/trunk/addr2line/addr2line.c

m7913d
  • 10,244
  • 7
  • 28
  • 56
user416983
  • 974
  • 3
  • 18
  • 28