How do I access the `addr2line` functionality within my C++ program?
Asked Answered
D

2

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.

Dramatist answered 19/7, 2012 at 7:58 Comment(6)
libdwarf is what youre looking forUtta
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...Dramatist
bfd is the en.wikipedia.org/wiki/Binary_File_Descriptor_library (although originally it stood for the other meaning of BFD :)Primaveras
You can see the can see the calls addr2line makes with ltrace, but you might not want to link against bfd directly yourself: lists.debian.org/debian-devel/2005/05/msg01086.htmlOffhand
doh! So my only way is to call popen("addr2line","r") and parse the output!Dramatist
Here you have a working implementation. github.com/albfan/bindutils-gdb/issues/1. Now is a system call, but its goal is to create a addr2line library. Seems pretty easy!Sounder
C
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.

Clarhe answered 19/7, 2012 at 8:23 Comment(3)
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.Dramatist
In addition to these, there is also the libunwind library: nongnu.org/libunwindThermopylae
@ArtoBendiken libunwind doesn't have an addr2line-like functionality. It only provides the offsetNogood
C
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

Chapin answered 28/2, 2013 at 7:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.