5

given an object file and address addr2line tool can relate it to a file and line number in the source code.

I'd like to have the opposite. Given a line number and an object file I want to get a list of instruction addresses which correspond to a given line in the source code.

I know that I can use objdump -DS and seek for a line, but that inconvenient, and requires manual effort to filter out the addresses. Do you know any tool which can do what I want if I give it a list of lines?

UPD.

I give an example of what I want.

I have a set of file lines:

src/a.c:14
src/a.c:28
src/b.c:44

I pass this list to a tool:

cat lines | line2addr -e lib.so

And it reports me instruction addresses for these lines:

0x442: src/a.c:14
0x444: src/a.c:14
0x44a: src/a.c:14
0x584: src/a.c:28
0x588: src/a.c:28
...
mcsim
  • 1,647
  • 2
  • 16
  • 35
  • 1
    The `gdb` debugger can do this with the executable (not individual object files). And of course, you'll need to compile with debug information .. – Basile Starynkevitch Nov 27 '15 at 09:47
  • http://gcc.godbolt.org/ does a nice job for small functions of mapping lines to asm. It even has color-coding. e.g. http://goo.gl/aLPTts – Peter Cordes Nov 27 '15 at 09:52
  • @BasileStarynkevitch I can compile with debugging information. But I did not completely understand how can I get the addresses in gdb. I found out that I can set up a breakpoint, but it only shows me one address, although there can be several instructions for the same line. – mcsim Nov 27 '15 at 10:05

2 Answers2

6

The way to do it in a utility manner is with the following GDB cmd-line:

gdb ../main.o -ex "info line main.c:39" --batch 
Line 39 of "main.c" starts at address 0x36 <main+54> and ends at 0x5e <main+94>.

The GDB accepts either an object or an executable file compiled with debug info (-g). Use GDB 7.6 and higher. Earlier versions crashed on Windows while loading object files.

Multiple lines can be translated by applying the -ex switch multiple times:

gdb ../main.o -ex "info line main.c:39" -ex "info line main.c:41" --batch
Line 39 of "main.c" starts at address 0x36 <main+54> and ends at 0x5e <main+94>.
Line 41 of "main.c" starts at address 0x5e <main+94> and ends at 0x70 <main+112>.
AlexF
  • 399
  • 4
  • 9
0

Read carefully the documentation of GDB. If your executable has been built with debug information (all code compiled with -g), you could use stack related commands, machine code related commands, etc.

I'm not sure to understand your wish, but I guess that dis and x commands could be helpful

In addition, recent GDB is scriptable in Python and Guile.

Basile Starynkevitch
  • 223,805
  • 18
  • 296
  • 547