blob: a0eb79b5e6c4f21c96d4c504b9d10e448d268c1d [file] [log] [blame]
Eli Bendersky933f6992011-09-09 08:11:06 +03001#-------------------------------------------------------------------------------
2# readelf.py
3#
4# A clone of 'readelf' in Python, based on the pyelftools library
5#
6# Eli Bendersky (eliben@gmail.com)
7# This code is in the public domain
8#-------------------------------------------------------------------------------
9import sys
10from optparse import OptionParser
11
12# If elftools is not installed, maybe we're running from the root or scripts
13# dir of the source distribution
14#
15try:
16 import elftools
17except ImportError:
18 sys.path.extend(['.', '..'])
19
20from elftools.common.exceptions import ELFError
21from elftools.elf.elffile import ELFFile
22from elftools.elf.descriptions import (
23 describe_ei_class, describe_ei_data, describe_ei_version,
24 describe_ei_osabi, describe_e_type,
25 )
26
27
28class ReadElf(object):
29 """ display_* methods are used to emit output into the output stream
30 """
31 def __init__(self, file, output):
32 """ file:
33 stream object with the ELF file to read
34
35 output:
36 output stream to write to
37 """
38 self.elffile = ELFFile(file)
39 self.output = output
40
41 def display_file_header(self):
42 """ Display the ELF file header
43 """
44 self._emitline('ELF Header:')
45 self._emit(' Magic: ')
46 self._emitline(' '.join('%2.2x' % ord(b)
47 for b in self.elffile.e_ident_raw))
48 header = self.elffile.header
49 e_ident = header['e_ident']
50 self._emitline(' Class: %s' %
51 describe_ei_class(e_ident['EI_CLASS']))
52 self._emitline(' Data: %s' %
53 describe_ei_data(e_ident['EI_DATA']))
54 self._emitline(' Version: %s' %
55 describe_ei_version(e_ident['EI_VERSION']))
56 self._emitline(' OS/ABI: %s' %
57 describe_ei_osabi(e_ident['EI_OSABI']))
58 self._emitline(' ABI Version: %d' %
59 e_ident['EI_ABIVERSION'])
60 self._emitline(' Type: %s' %
61 describe_e_type(header['e_type']))
62
63 def _emit(self, s):
64 """ Emit an object to output
65 """
66 self.output.write(str(s))
67
68 def _emitline(self, s):
69 """ Emit an object to output, followed by a newline
70 """
71 self.output.write(str(s) + '\n')
72
73
74def main():
75 optparser = OptionParser()
76 options, args = optparser.parse_args()
77
78 with open(args[0], 'rb') as file:
79 try:
80 readelf = ReadElf(file, sys.stdout)
81 readelf.display_file_header()
82 except ELFError as ex:
83 sys.stderr.write('ELF read error: %s\n' % ex)
84 sys.exit(1)
85
86
87#-------------------------------------------------------------------------------
88if __name__ == '__main__':
89 main()
90