documentation fixes + new examples
[pyelftools.git] / examples / examine_dwarf_info.py
1 #-------------------------------------------------------------------------------
2 # elftools example: examine_dwarf_info.py
3 #
4 # An example of examining information in the .debug_info section of an ELF file.
5 #
6 # Eli Bendersky (eliben@gmail.com)
7 # This code is in the public domain
8 #-------------------------------------------------------------------------------
9 from __future__ import print_function
10 import sys
11 from elftools.elf.elffile import ELFFile
12
13
14 def process_file(filename):
15 print('Processing file:', filename)
16 with open(filename) as f:
17 elffile = ELFFile(f)
18
19 if not elffile.has_dwarf_info():
20 print(' file has no DWARF info')
21 return
22
23 # get_dwarf_info returns a DWARFInfo context object, which is the
24 # starting point for all DWARF-based processing in pyelftools.
25 dwarfinfo = elffile.get_dwarf_info()
26
27 for CU in dwarfinfo.iter_CUs():
28 # DWARFInfo allows to iterate over the compile units contained in
29 # the .debug_info section. CU is a CompileUnit object, with some
30 # computed attributes (such as its offset in the section) and
31 # a header which conforms to the DWARF standard. The access to
32 # header elements is, as usual, via item-lookup.
33 print(' Found a compile unit at offset %s, length %s' % (
34 CU.cu_offset, CU['unit_length']))
35
36 # The first DIE in each compile unit describes it.
37 top_DIE = CU.get_top_DIE()
38 print(' Top DIE with tag=%s' % top_DIE.tag)
39
40 # Each DIE holds an OrderedDict of attributes, mapping names to
41 # values. Values are represented by AttributeValue objects in
42 # elftools/dwarf/die.py
43 # We're interested in the DW_AT_name attribute. Note that its value
44 # is usually a string taken from the .debug_string section. This
45 # is done transparently by the library, and such a value will be
46 # simply given as a string.
47 name_attr = top_DIE.attributes['DW_AT_name']
48 print(' name=%s' % name_attr.value)
49
50 if __name__ == '__main__':
51 for filename in sys.argv[1:]:
52 process_file(filename)
53
54
55
56
57