blob: 5633d594f42e58755ab1607650843f9488342590 [file] [log] [blame]
Eli Bendersky1a516a32011-12-22 15:22:00 +02001#-------------------------------------------------------------------------------
2# elftools example: dwarf_die_tree.py
3#
4# In the .debug_info section, Dwarf Information Entries (DIEs) form a tree.
5# pyelftools provides easy access to this tree, as demonstrated here.
6#
7# Eli Bendersky (eliben@gmail.com)
8# This code is in the public domain
9#-------------------------------------------------------------------------------
10from __future__ import print_function
11import sys
12from elftools.elf.elffile import ELFFile
13
14
15def process_file(filename):
16 print('Processing file:', filename)
17 with open(filename) as f:
18 elffile = ELFFile(f)
19
20 if not elffile.has_dwarf_info():
21 print(' file has no DWARF info')
22 return
23
24 # get_dwarf_info returns a DWARFInfo context object, which is the
25 # starting point for all DWARF-based processing in pyelftools.
26 dwarfinfo = elffile.get_dwarf_info()
27
28 for CU in dwarfinfo.iter_CUs():
29 # DWARFInfo allows to iterate over the compile units contained in
30 # the .debug_info section. CU is a CompileUnit object, with some
31 # computed attributes (such as its offset in the section) and
32 # a header which conforms to the DWARF standard. The access to
33 # header elements is, as usual, via item-lookup.
34 print(' Found a compile unit at offset %s, length %s' % (
35 CU.cu_offset, CU['unit_length']))
36
37 # Start with the top DIE, the root for this CU's DIE tree
38 top_DIE = CU.get_top_DIE()
39 print(' Top DIE with tag=%s' % top_DIE.tag)
40
41 # Each DIE holds an OrderedDict of attributes, mapping names to
42 # values. Values are represented by AttributeValue objects in
43 # elftools/dwarf/die.py
44 # We're interested in the DW_AT_name attribute. Note that its value
45 # is usually a string taken from the .debug_string section. This
46 # is done transparently by the library, and such a value will be
47 # simply given as a string.
48 name_attr = top_DIE.attributes['DW_AT_name']
49 print(' name=%s' % name_attr.value)
50
51 # Display DIEs recursively starting with top_DIE
52 die_info_rec(top_DIE)
53
54
55def die_info_rec(die, indent_level=' '):
56 """ A recursive function for showing information about a DIE and its
57 children.
58 """
59 print(indent_level + 'DIE tag=%s' % die.tag)
60 child_indent = indent_level + ' '
61 for child in die.iter_children():
62 die_info_rec(child, child_indent)
63
64
65if __name__ == '__main__':
66 for filename in sys.argv[1:]:
67 process_file(filename)
68
69
70
71
72
73