1 #-------------------------------------------------------------------------------
2 # elftools example: elf_relocations.py
4 # An example of obtaining a relocation section from an ELF file and examining
5 # the relocation entries it contains.
7 # Eli Bendersky (eliben@gmail.com)
8 # This code is in the public domain
9 #-------------------------------------------------------------------------------
10 from __future__
import print_function
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] = ['.', '..']
17 from elftools
.elf
.elffile
import ELFFile
18 from elftools
.elf
.relocation
import RelocationSection
21 def process_file(filename
):
22 print('Processing file:', filename
)
23 with
open(filename
, 'rb') as f
:
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
)
32 if not isinstance(reladyn
, RelocationSection
):
33 print(' The file has no %s section' % reladyn_name
)
35 print(' %s section with %s relocations' % (
36 reladyn_name
, reladyn
.num_relocations()))
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'])
44 if __name__
== '__main__':
45 if sys
.argv
[1] == '--test':
46 for filename
in sys
.argv
[2:]:
47 process_file(filename
)