1 #-------------------------------------------------------------------------------
4 # A clone of 'readelf' in Python, based on the pyelftools library
6 # Eli Bendersky (eliben@gmail.com)
7 # This code is in the public domain
8 #-------------------------------------------------------------------------------
10 from optparse
import OptionParser
12 # If elftools is not installed, maybe we're running from the root or scripts
13 # dir of the source distribution
18 sys
.path
.extend(['.', '..'])
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
,
29 class ReadElf(object):
30 """ display_* methods are used to emit output into the output stream
32 def __init__(self
, file, output
):
34 stream object with the ELF file to read
37 output stream to write to
39 self
.elffile
= ELFFile(file)
42 def display_file_header(self
):
43 """ Display the ELF file header
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']))
69 """ Emit an object to output
71 self
.output
.write(str(s
))
73 def _emitline(self
, s
):
74 """ Emit an object to output, followed by a newline
76 self
.output
.write(str(s
) + '\n')
80 optparser
= OptionParser()
81 options
, args
= optparser
.parse_args()
83 with
open(args
[0], 'rb') as file:
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
)
92 #-------------------------------------------------------------------------------
93 if __name__
== '__main__':