Issue #2: made all examples run (and test/run_examples_test.py pass) on Windows.
[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
12 # If elftools is not installed, maybe we're running from the root or examples
13 # dir of the source distribution
14 try:
15 import elftools
16 except ImportError:
17 sys.path.extend(['.', '..'])
18
19 from elftools.elf.elffile import ELFFile
20
21
22 def process_file(filename):
23 print('Processing file:', filename)
24 with open(filename, 'rb') as f:
25 elffile = ELFFile(f)
26
27 if not elffile.has_dwarf_info():
28 print(' file has no DWARF info')
29 return
30
31 # get_dwarf_info returns a DWARFInfo context object, which is the
32 # starting point for all DWARF-based processing in pyelftools.
33 dwarfinfo = elffile.get_dwarf_info()
34
35 for CU in dwarfinfo.iter_CUs():
36 # DWARFInfo allows to iterate over the compile units contained in
37 # the .debug_info section. CU is a CompileUnit object, with some
38 # computed attributes (such as its offset in the section) and
39 # a header which conforms to the DWARF standard. The access to
40 # header elements is, as usual, via item-lookup.
41 print(' Found a compile unit at offset %s, length %s' % (
42 CU.cu_offset, CU['unit_length']))
43
44 # The first DIE in each compile unit describes it.
45 top_DIE = CU.get_top_DIE()
46 print(' Top DIE with tag=%s' % top_DIE.tag)
47
48 # Each DIE holds an OrderedDict of attributes, mapping names to
49 # values. Values are represented by AttributeValue objects in
50 # elftools/dwarf/die.py
51 # We're interested in the DW_AT_name attribute. Note that its value
52 # is usually a string taken from the .debug_str section. This
53 # is done transparently by the library, and such a value will be
54 # simply given as a string.
55 name_attr = top_DIE.attributes['DW_AT_name']
56 print(' name=%s' % name_attr.value)
57
58 if __name__ == '__main__':
59 for filename in sys.argv[1:]:
60 process_file(filename)
61
62
63
64
65