blob: 008626619f53b5eb2548698adc60804df9d9f548 [file] [log] [blame]
Eli Bendersky1a516a32011-12-22 15:22:00 +02001#-------------------------------------------------------------------------------
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#-------------------------------------------------------------------------------
10from __future__ import print_function
11import sys
Eli Benderskyce5d1872011-12-22 20:03:06 +020012
Eli Benderskycc1e5572013-04-09 21:25:54 -070013# If pyelftools is not installed, the example can also run from the root or
14# examples/ dir of the source distribution.
15sys.path[0:0] = ['.', '..']
16
Eli Benderskyce5d1872011-12-22 20:03:06 +020017
Eli Bendersky79271e92012-01-27 10:25:47 +020018from elftools.common.py3compat import bytes2str
Eli Bendersky1a516a32011-12-22 15:22:00 +020019from elftools.elf.elffile import ELFFile
20from elftools.elf.relocation import RelocationSection
21
22
23def process_file(filename):
24 print('Processing file:', filename)
eli.bendersky3bd3ecc2012-01-11 15:56:41 +020025 with open(filename, 'rb') as f:
Eli Bendersky1a516a32011-12-22 15:22:00 +020026 elffile = ELFFile(f)
27
28 # Read the .rela.dyn section from the file, by explicitly asking
29 # ELFFile for this section
Eli Bendersky79271e92012-01-27 10:25:47 +020030 # Recall that section names are bytes objects
31 reladyn_name = b'.rela.dyn'
Eli Bendersky1a516a32011-12-22 15:22:00 +020032 reladyn = elffile.get_section_by_name(reladyn_name)
33
34 if not isinstance(reladyn, RelocationSection):
Eli Bendersky79271e92012-01-27 10:25:47 +020035 print(' The file has no %s section' % bytes2str(reladyn_name))
Eli Bendersky1a516a32011-12-22 15:22:00 +020036
37 print(' %s section with %s relocations' % (
Eli Bendersky79271e92012-01-27 10:25:47 +020038 bytes2str(reladyn_name), reladyn.num_relocations()))
Eli Bendersky1a516a32011-12-22 15:22:00 +020039
40 for reloc in reladyn.iter_relocations():
Eli Benderskybd1a09f2012-01-26 06:49:19 +020041 print(' Relocation (%s)' % 'RELA' if reloc.is_RELA() else 'REL')
Eli Bendersky1a516a32011-12-22 15:22:00 +020042 # Relocation entry attributes are available through item lookup
Eli Benderskybd1a09f2012-01-26 06:49:19 +020043 print(' offset = %s' % reloc['r_offset'])
Eli Bendersky1a516a32011-12-22 15:22:00 +020044
45
46if __name__ == '__main__':
47 for filename in sys.argv[1:]:
48 process_file(filename)
49