Merge pull request #76 from JaySon-Huang/strings
[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
18 from elftools.common.py3compat import bytes2str
19 from elftools.elf.elffile import ELFFile
20 from elftools.elf.relocation import RelocationSection
21
22
23 def process_file(filename):
24 print('Processing file:', filename)
25 with open(filename, 'rb') as f:
26 elffile = ELFFile(f)
27
28 # Read the .rela.dyn section from the file, by explicitly asking
29 # ELFFile for this section
30 # The section names are strings
31 reladyn_name = '.rela.dyn'
32 reladyn = elffile.get_section_by_name(reladyn_name)
33
34 if not isinstance(reladyn, RelocationSection):
35 print(' The file has no %s section' % reladyn_name)
36
37 print(' %s section with %s relocations' % (
38 reladyn_name, reladyn.num_relocations()))
39
40 for reloc in reladyn.iter_relocations():
41 print(' Relocation (%s)' % 'RELA' if reloc.is_RELA() else 'REL')
42 # Relocation entry attributes are available through item lookup
43 print(' offset = %s' % reloc['r_offset'])
44
45
46 if __name__ == '__main__':
47 for filename in sys.argv[1:]:
48 process_file(filename)
49