blob: 1aa28c60e204ce317547e34979d62fcc209bb89f [file] [log] [blame]
Eli Bendersky1a516a32011-12-22 15:22:00 +02001#-------------------------------------------------------------------------------
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#-------------------------------------------------------------------------------
9from __future__ import print_function
10import sys
Eli Benderskyce5d1872011-12-22 20:03:06 +020011
Eli Benderskycc1e5572013-04-09 21:25:54 -070012# If pyelftools is not installed, the example can also run from the root or
13# examples/ dir of the source distribution.
14sys.path[0:0] = ['.', '..']
Eli Benderskyce5d1872011-12-22 20:03:06 +020015
Eli Bendersky79271e92012-01-27 10:25:47 +020016from elftools.common.py3compat import bytes2str
Eli Bendersky1a516a32011-12-22 15:22:00 +020017from elftools.elf.elffile import ELFFile
18
19
20def process_file(filename):
21 print('Processing file:', filename)
eli.bendersky3bd3ecc2012-01-11 15:56:41 +020022 with open(filename, 'rb') as f:
Eli Bendersky1a516a32011-12-22 15:22:00 +020023 elffile = ELFFile(f)
24
25 if not elffile.has_dwarf_info():
26 print(' file has no DWARF info')
27 return
28
29 # get_dwarf_info returns a DWARFInfo context object, which is the
30 # starting point for all DWARF-based processing in pyelftools.
31 dwarfinfo = elffile.get_dwarf_info()
32
33 for CU in dwarfinfo.iter_CUs():
34 # DWARFInfo allows to iterate over the compile units contained in
35 # the .debug_info section. CU is a CompileUnit object, with some
36 # computed attributes (such as its offset in the section) and
37 # a header which conforms to the DWARF standard. The access to
38 # header elements is, as usual, via item-lookup.
39 print(' Found a compile unit at offset %s, length %s' % (
40 CU.cu_offset, CU['unit_length']))
41
42 # The first DIE in each compile unit describes it.
43 top_DIE = CU.get_top_DIE()
44 print(' Top DIE with tag=%s' % top_DIE.tag)
45
46 # Each DIE holds an OrderedDict of attributes, mapping names to
47 # values. Values are represented by AttributeValue objects in
48 # elftools/dwarf/die.py
49 # We're interested in the DW_AT_name attribute. Note that its value
Eli Bendersky40545e92011-12-22 15:53:52 +020050 # is usually a string taken from the .debug_str section. This
Eli Bendersky1a516a32011-12-22 15:22:00 +020051 # is done transparently by the library, and such a value will be
52 # simply given as a string.
53 name_attr = top_DIE.attributes['DW_AT_name']
Eli Bendersky79271e92012-01-27 10:25:47 +020054 print(' name=%s' % bytes2str(name_attr.value))
Eli Bendersky1a516a32011-12-22 15:22:00 +020055
56if __name__ == '__main__':
57 for filename in sys.argv[1:]:
58 process_file(filename)
59
60
61
62
63