Setup sys.path properly this time (I'll update the hacking guide to
[pyelftools.git] / examples / elfclass_address_size.py
1 #-------------------------------------------------------------------------------
2 # elftools example: elfclass_address_size.py
3 #
4 # This example explores the ELF class (32 or 64-bit) and address size in each
5 # of the CUs in the DWARF information.
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 elftools is not installed, maybe we're running from the root or examples
14 # dir of the source distribution
15 try:
16 import elftools
17 except ImportError:
18 sys.path[0:0] = ['.', '..']
19
20 from elftools.elf.elffile import ELFFile
21
22
23 def process_file(filename):
24 with open(filename, 'rb') as f:
25 elffile = ELFFile(f)
26 # elfclass is a public attribute of ELFFile, read from its header
27 print('%s: elfclass is %s' % (filename, elffile.elfclass))
28
29 if elffile.has_dwarf_info():
30 dwarfinfo = elffile.get_dwarf_info()
31 for CU in dwarfinfo.iter_CUs():
32 # cu_offset is a public attribute of CU
33 # address_size is part of the CU header
34 print(' CU at offset 0x%x. address_size is %s' % (
35 CU.cu_offset, CU['address_size']))
36
37
38 if __name__ == '__main__':
39 for filename in sys.argv[1:]:
40 process_file(filename)
41