Fix for mixed version loclists, tests (#521)
[pyelftools.git] / examples / dwarf_die_tree.py
1 #-------------------------------------------------------------------------------
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 #-------------------------------------------------------------------------------
10 from __future__ import print_function
11 from pathlib import Path
12 import sys
13
14 # If pyelftools is not installed, the example can also run from the root or
15 # examples/ dir of the source distribution.
16 sys.path[0:0] = ['.', '..']
17
18 from elftools.elf.elffile import ELFFile
19
20
21 def process_file(filename):
22 print('Processing file:', filename)
23 with open(filename, 'rb') as f:
24 elffile = ELFFile(f)
25
26 if not elffile.has_dwarf_info():
27 print(' file has no DWARF info')
28 return
29
30 # get_dwarf_info returns a DWARFInfo context object, which is the
31 # starting point for all DWARF-based processing in pyelftools.
32 dwarfinfo = elffile.get_dwarf_info()
33
34 for CU in dwarfinfo.iter_CUs():
35 # DWARFInfo allows to iterate over the compile units contained in
36 # the .debug_info section. CU is a CompileUnit object, with some
37 # computed attributes (such as its offset in the section) and
38 # a header which conforms to the DWARF standard. The access to
39 # header elements is, as usual, via item-lookup.
40 print(' Found a compile unit at offset %s, length %s' % (
41 CU.cu_offset, CU['unit_length']))
42
43 # Start with the top DIE, the root for this CU's DIE tree
44 top_DIE = CU.get_top_DIE()
45 print(' Top DIE with tag=%s' % top_DIE.tag)
46
47 # We're interested in the filename...
48 print(' name=%s' % Path(top_DIE.get_full_path()).as_posix())
49
50 # Display DIEs recursively starting with top_DIE
51 die_info_rec(top_DIE)
52
53
54 def die_info_rec(die, indent_level=' '):
55 """ A recursive function for showing information about a DIE and its
56 children.
57 """
58 print(indent_level + 'DIE tag=%s' % die.tag)
59 child_indent = indent_level + ' '
60 for child in die.iter_children():
61 die_info_rec(child, child_indent)
62
63
64 if __name__ == '__main__':
65 if sys.argv[1] == '--test':
66 for filename in sys.argv[2:]:
67 process_file(filename)