blob: fd65541954c70119a2621a11f3bf244d61ea5e1b [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
13# If elftools is not installed, maybe we're running from the root or examples
14# dir of the source distribution
15try:
16 import elftools
17except ImportError:
18 sys.path.extend(['.', '..'])
19
Eli Bendersky79271e92012-01-27 10:25:47 +020020from elftools.common.py3compat import bytes2str
Eli Bendersky1a516a32011-12-22 15:22:00 +020021from elftools.elf.elffile import ELFFile
22from elftools.elf.relocation import RelocationSection
23
24
25def process_file(filename):
26 print('Processing file:', filename)
eli.bendersky3bd3ecc2012-01-11 15:56:41 +020027 with open(filename, 'rb') as f:
Eli Bendersky1a516a32011-12-22 15:22:00 +020028 elffile = ELFFile(f)
29
30 # Read the .rela.dyn section from the file, by explicitly asking
31 # ELFFile for this section
Eli Bendersky79271e92012-01-27 10:25:47 +020032 # Recall that section names are bytes objects
33 reladyn_name = b'.rela.dyn'
Eli Bendersky1a516a32011-12-22 15:22:00 +020034 reladyn = elffile.get_section_by_name(reladyn_name)
35
36 if not isinstance(reladyn, RelocationSection):
Eli Bendersky79271e92012-01-27 10:25:47 +020037 print(' The file has no %s section' % bytes2str(reladyn_name))
Eli Bendersky1a516a32011-12-22 15:22:00 +020038
39 print(' %s section with %s relocations' % (
Eli Bendersky79271e92012-01-27 10:25:47 +020040 bytes2str(reladyn_name), reladyn.num_relocations()))
Eli Bendersky1a516a32011-12-22 15:22:00 +020041
42 for reloc in reladyn.iter_relocations():
Eli Benderskybd1a09f2012-01-26 06:49:19 +020043 print(' Relocation (%s)' % 'RELA' if reloc.is_RELA() else 'REL')
Eli Bendersky1a516a32011-12-22 15:22:00 +020044 # Relocation entry attributes are available through item lookup
Eli Benderskybd1a09f2012-01-26 06:49:19 +020045 print(' offset = %s' % reloc['r_offset'])
Eli Bendersky1a516a32011-12-22 15:22:00 +020046
47
48if __name__ == '__main__':
49 for filename in sys.argv[1:]:
50 process_file(filename)
51