blob: c8405adeffb0697b0d04fbe4e0a4116e27b4e883 [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 Bendersky1a516a32011-12-22 15:22:00 +020020from elftools.elf.elffile import ELFFile
21from elftools.elf.relocation import RelocationSection
22
23
24def process_file(filename):
25 print('Processing file:', filename)
eli.bendersky3bd3ecc2012-01-11 15:56:41 +020026 with open(filename, 'rb') as f:
Eli Bendersky1a516a32011-12-22 15:22:00 +020027 elffile = ELFFile(f)
28
29 # Read the .rela.dyn section from the file, by explicitly asking
30 # ELFFile for this section
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 # Use the Relocation's object ability to pretty-print itself to a
42 # string to examine it
43 print(' ', reloc)
44
45 # Relocation entry attributes are available through item lookup
46 print(' offset = %s' % reloc['r_offset'])
47
48
49if __name__ == '__main__':
50 for filename in sys.argv[1:]:
51 process_file(filename)
52