Remove unused import
[pyelftools.git] / examples / dwarf_range_lists.py
1 #-------------------------------------------------------------------------------
2 # elftools example: dwarf_range_lists.py
3 #
4 # Examine DIE entries which have range list values, and decode these range
5 # lists.
6 #
7 # Eli Bendersky (eliben@gmail.com)
8 # This code is in the public domain
9 #-------------------------------------------------------------------------------
10 from __future__ import print_function
11 import sys
12
13 # If pyelftools is not installed, the example can also run from the root or
14 # examples/ dir of the source distribution.
15 sys.path[0:0] = ['.', '..']
16
17 from elftools.common.py3compat import itervalues
18 from elftools.elf.elffile import ELFFile
19 from elftools.dwarf.descriptions import (
20 describe_DWARF_expr, set_global_machine_arch)
21 from elftools.dwarf.ranges import RangeEntry
22
23
24 def process_file(filename):
25 print('Processing file:', filename)
26 with open(filename, 'rb') as f:
27 elffile = ELFFile(f)
28
29 if not elffile.has_dwarf_info():
30 print(' file has no DWARF info')
31 return
32
33 # get_dwarf_info returns a DWARFInfo context object, which is the
34 # starting point for all DWARF-based processing in pyelftools.
35 dwarfinfo = elffile.get_dwarf_info()
36
37 # The range lists are extracted by DWARFInfo from the .debug_ranges
38 # section, and returned here as a RangeLists object.
39 range_lists = dwarfinfo.range_lists()
40
41 for CU in dwarfinfo.iter_CUs():
42 # DWARFInfo allows to iterate over the compile units contained in
43 # the .debug_info section. CU is a CompileUnit object, with some
44 # computed attributes (such as its offset in the section) and
45 # a header which conforms to the DWARF standard. The access to
46 # header elements is, as usual, via item-lookup.
47 print(' Found a compile unit at offset %s, length %s' % (
48 CU.cu_offset, CU['unit_length']))
49
50 # A CU provides a simple API to iterate over all the DIEs in it.
51 for DIE in CU.iter_DIEs():
52 # Go over all attributes of the DIE. Each attribute is an
53 # AttributeValue object (from elftools.dwarf.die), which we
54 # can examine.
55 for attr in itervalues(DIE.attributes):
56 if attribute_has_range_list(attr):
57 # This is a range list. Its value is an offset into
58 # the .debug_ranges section, so we can use the range
59 # lists object to decode it.
60 rangelist = range_lists.get_range_list_at_offset(
61 attr.value)
62
63 print(' DIE %s. attr %s.\n%s' % (
64 DIE.tag,
65 attr.name,
66 rangelist))
67
68
69 def attribute_has_range_list(attr):
70 """ Only some attributes can have range list values, if they have the
71 required DW_FORM (rangelistptr "class" in DWARF spec v3)
72 """
73 if attr.name == 'DW_AT_ranges':
74 if attr.form in ('DW_FORM_data4', 'DW_FORM_data8'):
75 return True
76 return False
77
78
79 if __name__ == '__main__':
80 for filename in sys.argv[1:]:
81 process_file(filename)
82
83
84
85
86
87
88