Eli Bendersky | 1a516a3 | 2011-12-22 15:22:00 +0200 | [diff] [blame] | 1 | #------------------------------------------------------------------------------- |
| 2 | # elftools example: examine_dwarf_info.py |
| 3 | # |
| 4 | # An example of examining information in the .debug_info section of an ELF file. |
| 5 | # |
| 6 | # Eli Bendersky (eliben@gmail.com) |
| 7 | # This code is in the public domain |
| 8 | #------------------------------------------------------------------------------- |
| 9 | from __future__ import print_function |
| 10 | import sys |
Eli Bendersky | ce5d187 | 2011-12-22 20:03:06 +0200 | [diff] [blame] | 11 | |
Eli Bendersky | cc1e557 | 2013-04-09 21:25:54 -0700 | [diff] [blame] | 12 | # If pyelftools is not installed, the example can also run from the root or |
| 13 | # examples/ dir of the source distribution. |
| 14 | sys.path[0:0] = ['.', '..'] |
Eli Bendersky | ce5d187 | 2011-12-22 20:03:06 +0200 | [diff] [blame] | 15 | |
Eli Bendersky | 1a516a3 | 2011-12-22 15:22:00 +0200 | [diff] [blame] | 16 | from elftools.elf.elffile import ELFFile |
| 17 | |
| 18 | |
| 19 | def process_file(filename): |
| 20 | print('Processing file:', filename) |
eli.bendersky | 3bd3ecc | 2012-01-11 15:56:41 +0200 | [diff] [blame] | 21 | with open(filename, 'rb') as f: |
Eli Bendersky | 1a516a3 | 2011-12-22 15:22:00 +0200 | [diff] [blame] | 22 | elffile = ELFFile(f) |
| 23 | |
| 24 | if not elffile.has_dwarf_info(): |
| 25 | print(' file has no DWARF info') |
| 26 | return |
| 27 | |
| 28 | # get_dwarf_info returns a DWARFInfo context object, which is the |
| 29 | # starting point for all DWARF-based processing in pyelftools. |
| 30 | dwarfinfo = elffile.get_dwarf_info() |
| 31 | |
| 32 | for CU in dwarfinfo.iter_CUs(): |
| 33 | # DWARFInfo allows to iterate over the compile units contained in |
| 34 | # the .debug_info section. CU is a CompileUnit object, with some |
| 35 | # computed attributes (such as its offset in the section) and |
| 36 | # a header which conforms to the DWARF standard. The access to |
| 37 | # header elements is, as usual, via item-lookup. |
| 38 | print(' Found a compile unit at offset %s, length %s' % ( |
| 39 | CU.cu_offset, CU['unit_length'])) |
| 40 | |
| 41 | # The first DIE in each compile unit describes it. |
| 42 | top_DIE = CU.get_top_DIE() |
| 43 | print(' Top DIE with tag=%s' % top_DIE.tag) |
| 44 | |
Shaheed Haque | 7d8885f | 2013-12-27 12:36:34 +0000 | [diff] [blame] | 45 | # We're interested in the filename... |
| 46 | print(' name=%s' % top_DIE.get_filename()) |
Eli Bendersky | 1a516a3 | 2011-12-22 15:22:00 +0200 | [diff] [blame] | 47 | |
| 48 | if __name__ == '__main__': |
| 49 | for filename in sys.argv[1:]: |
| 50 | process_file(filename) |
| 51 | |
| 52 | |
| 53 | |
| 54 | |
| 55 | |