Search code examples
linuxdebuggingaddr2line

How addr2line can locate the source file and the line of code?


addr2line translates addresses into file names and line numbers. I am still beginner in debugging, and have some questions about addr2line.

  1. If am debugging a certain .so (binary) file, how the tool can locate its source code file (from where can get it!), what if the source doesn't exist?

  2. What is the relation between the address in a binary and the line number in its source, so addr2line can do this kind of mapping?


Solution

  • In general, addr2line works best on ELF executables or shared libraries with debug information. That debug information is emitted by the compiler when you pass -g (or -g2, etc...) to GCC. It notably provides a mapping between source code location (name of source file, line number, column number) and functions, variable names, call stack frame organization, etc etc... The debug information is today in DWARF format (and is also processed by the gdb debugger, the libbacktrace library, etc etc...). Notice that the debug information contains source file paths (not the source file itself).

    In practice, you can (and often should) pass the -g (or -g2) debugging option to GCC even with optimization flags like -O2. In that case, the debug information is slightly less precise but still practically usable. In some cases, stack frames may disappear (inlined function calls, tail call optimizations, ....).

    You could use the strip(1) utility to remove debug information (and other symbol tables, etc) from some ELF executable.