some more header descriptions added
[pyelftools.git] / scripts / readelf.py
1 #-------------------------------------------------------------------------------
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 #-------------------------------------------------------------------------------
9 import sys
10 from 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 #
15 try:
16 import elftools
17 except ImportError:
18 sys.path.extend(['.', '..'])
19
20 from elftools.common.exceptions import ELFError
21 from elftools.elf.elffile import ELFFile
22 from elftools.elf.descriptions import (
23 describe_ei_class, describe_ei_data, describe_ei_version,
24 describe_ei_osabi, describe_e_type, describe_e_machine,
25 describe_e_version_numeric,
26 )
27
28
29 class ReadElf(object):
30 """ display_* methods are used to emit output into the output stream
31 """
32 def __init__(self, file, output):
33 """ file:
34 stream object with the ELF file to read
35
36 output:
37 output stream to write to
38 """
39 self.elffile = ELFFile(file)
40 self.output = output
41
42 def display_file_header(self):
43 """ Display the ELF file header
44 """
45 self._emitline('ELF Header:')
46 self._emit(' Magic: ')
47 self._emitline(' '.join('%2.2x' % ord(b)
48 for b in self.elffile.e_ident_raw))
49 header = self.elffile.header
50 e_ident = header['e_ident']
51 self._emitline(' Class: %s' %
52 describe_ei_class(e_ident['EI_CLASS']))
53 self._emitline(' Data: %s' %
54 describe_ei_data(e_ident['EI_DATA']))
55 self._emitline(' Version: %s' %
56 describe_ei_version(e_ident['EI_VERSION']))
57 self._emitline(' OS/ABI: %s' %
58 describe_ei_osabi(e_ident['EI_OSABI']))
59 self._emitline(' ABI Version: %d' %
60 e_ident['EI_ABIVERSION'])
61 self._emitline(' Type: %s' %
62 describe_e_type(header['e_type']))
63 self._emitline(' Machine: %s' %
64 describe_e_machine(header['e_machine']))
65 self._emitline(' Version: %s' %
66 describe_e_version_numeric(header['e_version']))
67
68 def _emit(self, s):
69 """ Emit an object to output
70 """
71 self.output.write(str(s))
72
73 def _emitline(self, s):
74 """ Emit an object to output, followed by a newline
75 """
76 self.output.write(str(s) + '\n')
77
78
79 def main():
80 optparser = OptionParser()
81 options, args = optparser.parse_args()
82
83 with open(args[0], 'rb') as file:
84 try:
85 readelf = ReadElf(file, sys.stdout)
86 readelf.display_file_header()
87 except ELFError as ex:
88 sys.stderr.write('ELF read error: %s\n' % ex)
89 sys.exit(1)
90
91
92 #-------------------------------------------------------------------------------
93 if __name__ == '__main__':
94 main()
95