Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get list of source files (and locations) from binary

I'm working in a linux distro. I'm writing a C/C++ program that requires a list of source files that a binary (executable) was compiled with. I compiled the binary using GCC with the -g flag, of course. Using gdb I found out the format of the binary is DWARF2:

(gdb) info source
Current source file is src/main.cpp
Compilation directory is /path/to/source
Located in /path/to/source/src/main.cpp 
Contains 43 lines.
Source language is c++.
Compiled with DWARF 2 debugging format.
Does not include preprocessor macro info.

Using objdump or elfread I see the information that I need:

bash> objdump -W binary
...
The File Name Table:
  Entry Dir Time    Size    Name
  1 1   0   0   main.cpp
  2 2   0   0   curses.h
  3 3   0   0   tprint.h
  4 3   0   0   twindow.h
  5 4   0   0   locale.h
...

Using dwarfdump I see that the variables of interest are: DW_AT_comp_dir and DW_AT_decl_file. Using a simple bash script (a few grep and sed calls) I was able to get the source list. What I would like to do, is get this source list from within a C/C++ program. For this purpose I have installed libdwarf, but with lack of any usage examples I'm unable to easily implement what I want.

My questions are: 1) Could someone provide a C/C++ example that reads debug information from a binary? It does not have to be with libdwarf if there are other libraries that can do this. 2) Can gdb provide a source list? Eventually I would like to build my own interface to gdb and scroll though available source files.

Regards

like image 264
gospes Avatar asked Dec 04 '13 16:12

gospes


People also ask

How can I get the source code from a binary file?

It's possible using decompilers and also assembly source can be get by objdump. There are few decompilers (to c language and assembly language) around. Use Wikipedia and web search to find them. It's illegal in some place but legal in others and also depends on license terms of the binary.

How do you check if a file is binary or Ascii in Linux?

You can use file --mime-encoding | grep binary to detect if a file is a binary file.

What is Linux binary?

Binary Files in Linux A binary package is an application package that contains (pre-built) executables, build from source code, and are not reversible. The most important advantage of binary is the ability to hide source code and prevent future modifications.


1 Answers

Can gdb provide a source list?

Yes: info sources

like image 169
Employed Russian Avatar answered Oct 01 '22 22:10

Employed Russian