1 #-------------------------------------------------------------------------------
2 # elftools example: dwarf_range_lists.py
4 # Examine DIE entries which have range list values, and decode these range
7 # Eli Bendersky (eliben@gmail.com)
8 # This code is in the public domain
9 #-------------------------------------------------------------------------------
10 from __future__
import print_function
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] = ['.', '..']
17 from elftools
.elf
.elffile
import ELFFile
18 from elftools
.dwarf
.descriptions
import (
19 describe_DWARF_expr
, set_global_machine_arch
)
20 from elftools
.dwarf
.ranges
import RangeEntry
23 def process_file(filename
):
24 print('Processing file:', filename
)
25 with
open(filename
, 'rb') as f
:
28 if not elffile
.has_dwarf_info():
29 print(' file has no DWARF info')
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()
36 # The range lists are extracted by DWARFInfo from the .debug_ranges
37 # section, and returned here as a RangeLists object.
38 range_lists
= dwarfinfo
.range_lists()
39 if range_lists
is None:
40 print(' file has no .debug_ranges section')
43 for CU
in dwarfinfo
.iter_CUs():
44 # DWARFInfo allows to iterate over the compile units contained in
45 # the .debug_info section. CU is a CompileUnit object, with some
46 # computed attributes (such as its offset in the section) and
47 # a header which conforms to the DWARF standard. The access to
48 # header elements is, as usual, via item-lookup.
49 print(' Found a compile unit at offset %s, length %s' % (
50 CU
.cu_offset
, CU
['unit_length']))
52 # A CU provides a simple API to iterate over all the DIEs in it.
53 for DIE
in CU
.iter_DIEs():
54 # Go over all attributes of the DIE. Each attribute is an
55 # AttributeValue object (from elftools.dwarf.die), which we
57 for attr
in DIE
.attributes
.values():
58 if attribute_has_range_list(attr
):
59 # This is a range list. Its value is an offset into
60 # the .debug_ranges section, so we can use the range
61 # lists object to decode it.
62 rangelist
= range_lists
.get_range_list_at_offset(
65 print(' DIE %s. attr %s.\n%s' % (
71 def attribute_has_range_list(attr
):
72 """ Only some attributes can have range list values, if they have the
73 required DW_FORM (rangelistptr "class" in DWARF spec v3)
75 if attr
.name
== 'DW_AT_ranges':
76 if attr
.form
in ('DW_FORM_data4', 'DW_FORM_data8'):
81 if __name__
== '__main__':
82 if sys
.argv
[1] == '--test':
83 for filename
in sys
.argv
[2:]:
84 process_file(filename
)