blob: 9650f309d68e5fccc77e0b05d003851ab97e17d2 [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
Eli Benderskyce5d1872011-12-22 20:03:06 +020012
13# If elftools is not installed, maybe we're running from the root or examples
14# dir of the source distribution
15try:
16 import elftools
17except ImportError:
18 sys.path.extend(['.', '..'])
19
Eli Bendersky1a516a32011-12-22 15:22:00 +020020from elftools.elf.elffile import ELFFile
21
22
23def process_file(filename):
24 print('Processing file:', filename)
eli.bendersky3bd3ecc2012-01-11 15:56:41 +020025 with open(filename, 'rb') as f:
Eli Bendersky1a516a32011-12-22 15:22:00 +020026 elffile = ELFFile(f)
27
28 if not elffile.has_dwarf_info():
29 print(' file has no DWARF info')
30 return
31
32 # get_dwarf_info returns a DWARFInfo context object, which is the
33 # starting point for all DWARF-based processing in pyelftools.
34 dwarfinfo = elffile.get_dwarf_info()
35
36 for CU in dwarfinfo.iter_CUs():
37 # DWARFInfo allows to iterate over the compile units contained in
38 # the .debug_info section. CU is a CompileUnit object, with some
39 # computed attributes (such as its offset in the section) and
40 # a header which conforms to the DWARF standard. The access to
41 # header elements is, as usual, via item-lookup.
42 print(' Found a compile unit at offset %s, length %s' % (
43 CU.cu_offset, CU['unit_length']))
44
45 # Start with the top DIE, the root for this CU's DIE tree
46 top_DIE = CU.get_top_DIE()
47 print(' Top DIE with tag=%s' % top_DIE.tag)
48
49 # Each DIE holds an OrderedDict of attributes, mapping names to
50 # values. Values are represented by AttributeValue objects in
51 # elftools/dwarf/die.py
52 # We're interested in the DW_AT_name attribute. Note that its value
53 # is usually a string taken from the .debug_string section. This
54 # is done transparently by the library, and such a value will be
55 # simply given as a string.
56 name_attr = top_DIE.attributes['DW_AT_name']
57 print(' name=%s' % name_attr.value)
58
59 # Display DIEs recursively starting with top_DIE
60 die_info_rec(top_DIE)
61
62
63def die_info_rec(die, indent_level=' '):
64 """ A recursive function for showing information about a DIE and its
65 children.
66 """
67 print(indent_level + 'DIE tag=%s' % die.tag)
68 child_indent = indent_level + ' '
69 for child in die.iter_children():
70 die_info_rec(child, child_indent)
71
72
73if __name__ == '__main__':
74 for filename in sys.argv[1:]:
75 process_file(filename)
76
77
78
79
80
81