blob: 606441233f368837c97fd43ac375a0131bd37191 [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
12# If elftools is not installed, maybe we're running from the root or examples
13# dir of the source distribution
14try:
15 import elftools
16except ImportError:
17 sys.path.extend(['.', '..'])
18
Eli Bendersky1a516a32011-12-22 15:22:00 +020019from elftools.elf.elffile import ELFFile
20
21
22def process_file(filename):
23 print('Processing file:', filename)
24 with open(filename) as f:
25 elffile = ELFFile(f)
26
27 if not elffile.has_dwarf_info():
28 print(' file has no DWARF info')
29 return
30
31 # get_dwarf_info returns a DWARFInfo context object, which is the
32 # starting point for all DWARF-based processing in pyelftools.
33 dwarfinfo = elffile.get_dwarf_info()
34
35 for CU in dwarfinfo.iter_CUs():
36 # DWARFInfo allows to iterate over the compile units contained in
37 # the .debug_info section. CU is a CompileUnit object, with some
38 # computed attributes (such as its offset in the section) and
39 # a header which conforms to the DWARF standard. The access to
40 # header elements is, as usual, via item-lookup.
41 print(' Found a compile unit at offset %s, length %s' % (
42 CU.cu_offset, CU['unit_length']))
43
44 # The first DIE in each compile unit describes it.
45 top_DIE = CU.get_top_DIE()
46 print(' Top DIE with tag=%s' % top_DIE.tag)
47
48 # Each DIE holds an OrderedDict of attributes, mapping names to
49 # values. Values are represented by AttributeValue objects in
50 # elftools/dwarf/die.py
51 # We're interested in the DW_AT_name attribute. Note that its value
Eli Bendersky40545e92011-12-22 15:53:52 +020052 # is usually a string taken from the .debug_str section. This
Eli Bendersky1a516a32011-12-22 15:22:00 +020053 # is done transparently by the library, and such a value will be
54 # simply given as a string.
55 name_attr = top_DIE.attributes['DW_AT_name']
56 print(' name=%s' % name_attr.value)
57
58if __name__ == '__main__':
59 for filename in sys.argv[1:]:
60 process_file(filename)
61
62
63
64
65