Fix for mixed version loclists, tests (#521)
[pyelftools.git] / examples / elf_relocations.py
1 #-------------------------------------------------------------------------------
2 # elftools example: elf_relocations.py
3 #
4 # An example of obtaining a relocation section from an ELF file and examining
5 # the relocation entries it contains.
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.elf.elffile import ELFFile
18 from elftools.elf.relocation import RelocationSection
19
20
21 def process_file(filename):
22 print('Processing file:', filename)
23 with open(filename, 'rb') as f:
24 elffile = ELFFile(f)
25
26 # Read the .rela.dyn section from the file, by explicitly asking
27 # ELFFile for this section
28 # The section names are strings
29 reladyn_name = '.rela.dyn'
30 reladyn = elffile.get_section_by_name(reladyn_name)
31
32 if not isinstance(reladyn, RelocationSection):
33 print(' The file has no %s section' % reladyn_name)
34
35 print(' %s section with %s relocations' % (
36 reladyn_name, reladyn.num_relocations()))
37
38 for reloc in reladyn.iter_relocations():
39 print(' Relocation (%s)' % 'RELA' if reloc.is_RELA() else 'REL')
40 # Relocation entry attributes are available through item lookup
41 print(' offset = %s' % reloc['r_offset'])
42
43
44 if __name__ == '__main__':
45 if sys.argv[1] == '--test':
46 for filename in sys.argv[2:]:
47 process_file(filename)