Eli Bendersky | 1a516a3 | 2011-12-22 15:22:00 +0200 | [diff] [blame] | 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 |
Eli Bendersky | ce5d187 | 2011-12-22 20:03:06 +0200 | [diff] [blame] | 12 | |
| 13 | # If elftools is not installed, maybe we're running from the root or examples |
| 14 | # dir of the source distribution |
| 15 | try: |
| 16 | import elftools |
| 17 | except ImportError: |
| 18 | sys.path.extend(['.', '..']) |
| 19 | |
Eli Bendersky | 1a516a3 | 2011-12-22 15:22:00 +0200 | [diff] [blame] | 20 | from elftools.elf.elffile import ELFFile |
| 21 | from elftools.elf.relocation import RelocationSection |
| 22 | |
| 23 | |
| 24 | def process_file(filename): |
| 25 | print('Processing file:', filename) |
eli.bendersky | 3bd3ecc | 2012-01-11 15:56:41 +0200 | [diff] [blame] | 26 | with open(filename, 'rb') as f: |
Eli Bendersky | 1a516a3 | 2011-12-22 15:22:00 +0200 | [diff] [blame] | 27 | 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 | |
| 49 | if __name__ == '__main__': |
| 50 | for filename in sys.argv[1:]: |
| 51 | process_file(filename) |
| 52 | |