* added new test file - an object compiled from C++, on x64
[pyelftools.git] / scripts / readelf.py
1 #!/usr/bin/env python
2 #-------------------------------------------------------------------------------
3 # scripts/readelf.py
4 #
5 # A clone of 'readelf' in Python, based on the pyelftools library
6 #
7 # Eli Bendersky (eliben@gmail.com)
8 # This code is in the public domain
9 #-------------------------------------------------------------------------------
10 import os, sys
11 from optparse import OptionParser
12 import string
13
14
15 # If elftools is not installed, maybe we're running from the root or scripts
16 # dir of the source distribution
17 #
18 try:
19 import elftools
20 except ImportError:
21 sys.path.extend(['.', '..'])
22
23 from elftools import __version__
24 from elftools.common.exceptions import ELFError
25 from elftools.elf.elffile import ELFFile
26 from elftools.elf.segments import InterpSegment
27 from elftools.elf.sections import SymbolTableSection, RelocationSection
28 from elftools.elf.descriptions import (
29 describe_ei_class, describe_ei_data, describe_ei_version,
30 describe_ei_osabi, describe_e_type, describe_e_machine,
31 describe_e_version_numeric, describe_p_type, describe_p_flags,
32 describe_sh_type, describe_sh_flags,
33 describe_symbol_type, describe_symbol_bind, describe_symbol_visibility,
34 describe_symbol_shndx, describe_reloc_type,
35 )
36
37
38 class ReadElf(object):
39 """ display_* methods are used to emit output into the output stream
40 """
41 def __init__(self, file, output):
42 """ file:
43 stream object with the ELF file to read
44
45 output:
46 output stream to write to
47 """
48 self.elffile = ELFFile(file)
49 self.output = output
50
51 def display_file_header(self):
52 """ Display the ELF file header
53 """
54 self._emitline('ELF Header:')
55 self._emit(' Magic: ')
56 self._emitline(' '.join('%2.2x' % ord(b)
57 for b in self.elffile.e_ident_raw))
58 header = self.elffile.header
59 e_ident = header['e_ident']
60 self._emitline(' Class: %s' %
61 describe_ei_class(e_ident['EI_CLASS']))
62 self._emitline(' Data: %s' %
63 describe_ei_data(e_ident['EI_DATA']))
64 self._emitline(' Version: %s' %
65 describe_ei_version(e_ident['EI_VERSION']))
66 self._emitline(' OS/ABI: %s' %
67 describe_ei_osabi(e_ident['EI_OSABI']))
68 self._emitline(' ABI Version: %d' %
69 e_ident['EI_ABIVERSION'])
70 self._emitline(' Type: %s' %
71 describe_e_type(header['e_type']))
72 self._emitline(' Machine: %s' %
73 describe_e_machine(header['e_machine']))
74 self._emitline(' Version: %s' %
75 describe_e_version_numeric(header['e_version']))
76 self._emitline(' Entry point address: %s' %
77 self._format_hex(header['e_entry']))
78 self._emit(' Start of program headers: %s' %
79 header['e_phoff'])
80 self._emitline(' (bytes into file)')
81 self._emit(' Start of section headers: %s' %
82 header['e_shoff'])
83 self._emitline(' (bytes into file)')
84 self._emitline(' Flags: %s' %
85 self._format_hex(header['e_flags']))
86 self._emitline(' Size of this header: %s (bytes)' %
87 header['e_ehsize'])
88 self._emitline(' Size of program headers: %s (bytes)' %
89 header['e_phentsize'])
90 self._emitline(' Number of program headers: %s' %
91 header['e_phnum'])
92 self._emitline(' Size of section headers: %s (bytes)' %
93 header['e_shentsize'])
94 self._emitline(' Number of section headers: %s' %
95 header['e_shnum'])
96 self._emitline(' Section header string table index: %s' %
97 header['e_shstrndx'])
98
99 def display_program_headers(self, show_heading=True):
100 """ Display the ELF program headers.
101 If show_heading is True, displays the heading for this information
102 (Elf file type is...)
103 """
104 self._emitline()
105 if self.elffile.num_segments() == 0:
106 self._emitline('There are no program headers in this file.')
107 return
108
109 elfheader = self.elffile.header
110 if show_heading:
111 self._emitline('Elf file type is %s' %
112 describe_e_type(elfheader['e_type']))
113 self._emitline('Entry point is %s' %
114 self._format_hex(elfheader['e_entry']))
115 # readelf weirness - why isn't e_phoff printed as hex? (for section
116 # headers, it is...)
117 self._emitline('There are %s program headers, starting at offset %s' % (
118 elfheader['e_phnum'], elfheader['e_phoff']))
119 self._emitline()
120
121 self._emitline('Program Headers:')
122
123 # Now comes the table of program headers with their attributes. Note
124 # that due to different formatting constraints of 32-bit and 64-bit
125 # addresses, there are some conditions on elfclass here.
126 #
127 # First comes the table heading
128 #
129 if self.elffile.elfclass == 32:
130 self._emitline(' Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align')
131 else:
132 self._emitline(' Type Offset VirtAddr PhysAddr')
133 self._emitline(' FileSiz MemSiz Flags Align')
134
135 # Now the entries
136 #
137 for segment in self.elffile.iter_segments():
138 self._emit(' %-14s ' % describe_p_type(segment['p_type']))
139
140 if self.elffile.elfclass == 32:
141 self._emitline('%s %s %s %s %s %-3s %s' % (
142 self._format_hex(segment['p_offset'], fieldsize=6),
143 self._format_hex(segment['p_vaddr'], fullhex=True),
144 self._format_hex(segment['p_paddr'], fullhex=True),
145 self._format_hex(segment['p_filesz'], fieldsize=5),
146 self._format_hex(segment['p_memsz'], fieldsize=5),
147 describe_p_flags(segment['p_flags']),
148 self._format_hex(segment['p_align'])))
149 else: # 64
150 self._emitline('%s %s %s' % (
151 self._format_hex(segment['p_offset'], fullhex=True),
152 self._format_hex(segment['p_vaddr'], fullhex=True),
153 self._format_hex(segment['p_paddr'], fullhex=True)))
154 self._emitline(' %s %s %-3s %s' % (
155 self._format_hex(segment['p_filesz'], fullhex=True),
156 self._format_hex(segment['p_memsz'], fullhex=True),
157 describe_p_flags(segment['p_flags']),
158 # lead0x set to False for p_align, to mimic readelf.
159 # No idea why the difference from 32-bit mode :-|
160 self._format_hex(segment['p_align'], lead0x=False)))
161
162 if isinstance(segment, InterpSegment):
163 self._emitline(' [Requesting program interpreter: %s]' %
164 segment.get_interp_name())
165
166 # Sections to segments mapping
167 #
168 if self.elffile.num_sections() == 0:
169 # No sections? We're done
170 return
171
172 self._emitline('\n Section to Segment mapping:')
173 self._emitline(' Segment Sections...')
174
175 for nseg, segment in enumerate(self.elffile.iter_segments()):
176 self._emit(' %2.2d ' % nseg)
177
178 for section in self.elffile.iter_sections():
179 if ( not section.is_null() and
180 segment.section_in_segment(section)):
181 self._emit('%s ' % section.name)
182
183 self._emitline('')
184
185 def display_section_headers(self, show_heading=True):
186 """ Display the ELF section headers
187 """
188 elfheader = self.elffile.header
189 if show_heading:
190 self._emitline('There are %s section headers, starting at offset %s' % (
191 elfheader['e_shnum'], self._format_hex(elfheader['e_shoff'])))
192
193 self._emitline('\nSection Header%s:' % (
194 's' if elfheader['e_shnum'] > 1 else ''))
195
196 # Different formatting constraints of 32-bit and 64-bit addresses
197 #
198 if self.elffile.elfclass == 32:
199 self._emitline(' [Nr] Name Type Addr Off Size ES Flg Lk Inf Al')
200 else:
201 self._emitline(' [Nr] Name Type Address Offset')
202 self._emitline(' Size EntSize Flags Link Info Align')
203
204 # Now the entries
205 #
206 for nsec, section in enumerate(self.elffile.iter_sections()):
207 self._emit(' [%2u] %-17.17s %-15.15s ' % (
208 nsec, section.name, describe_sh_type(section['sh_type'])))
209
210 if self.elffile.elfclass == 32:
211 self._emitline('%s %s %s %s %3s %2s %3s %2s' % (
212 self._format_hex(section['sh_addr'], fieldsize=8, lead0x=False),
213 self._format_hex(section['sh_offset'], fieldsize=6, lead0x=False),
214 self._format_hex(section['sh_size'], fieldsize=6, lead0x=False),
215 self._format_hex(section['sh_entsize'], fieldsize=2, lead0x=False),
216 describe_sh_flags(section['sh_flags']),
217 section['sh_link'], section['sh_info'],
218 section['sh_addralign']))
219 else: # 64
220 self._emitline(' %s %s' % (
221 self._format_hex(section['sh_addr'], fullhex=True, lead0x=False),
222 self._format_hex(section['sh_offset'],
223 fieldsize=16 if section['sh_offset'] > 0xffffffff else 8,
224 lead0x=False)))
225 self._emitline(' %s %s %3s %2s %3s %s' % (
226 self._format_hex(section['sh_size'], fullhex=True, lead0x=False),
227 self._format_hex(section['sh_entsize'], fullhex=True, lead0x=False),
228 describe_sh_flags(section['sh_flags']),
229 section['sh_link'], section['sh_info'],
230 section['sh_addralign']))
231
232 self._emitline('Key to Flags:')
233 self._emitline(' W (write), A (alloc), X (execute), M (merge), S (strings)')
234 self._emitline(' I (info), L (link order), G (group), x (unknown)')
235 self._emitline(' O (extra OS processing required) o (OS specific), p (processor specific)')
236
237 def display_symbol_tables(self):
238 """ Display the symbol tables contained in the file
239 """
240 for section in self.elffile.iter_sections():
241 if not isinstance(section, SymbolTableSection):
242 continue
243
244 if section['sh_entsize'] == 0:
245 self._emitline("\nSymbol table '%s' has a sh_entsize of zero!" % (
246 section.name))
247 continue
248
249 self._emitline("\nSymbol table '%s' contains %s entries:" % (
250 section.name, section.num_symbols()))
251
252 if self.elffile.elfclass == 32:
253 self._emitline(' Num: Value Size Type Bind Vis Ndx Name')
254 else: # 64
255 self._emitline(' Num: Value Size Type Bind Vis Ndx Name')
256
257 for nsym, symbol in enumerate(section.iter_symbols()):
258 # symbol names are truncated to 25 chars, similarly to readelf
259 self._emitline('%6d: %s %5d %-7s %-6s %-7s %4s %.25s' % (
260 nsym,
261 self._format_hex(symbol['st_value'], fullhex=True, lead0x=False),
262 symbol['st_size'],
263 describe_symbol_type(symbol['st_info']['type']),
264 describe_symbol_bind(symbol['st_info']['bind']),
265 describe_symbol_visibility(symbol['st_other']['visibility']),
266 describe_symbol_shndx(symbol['st_shndx']),
267 symbol.name))
268
269 def display_relocations(self):
270 """ Display the relocations contained in the file
271 """
272 has_relocation_sections = False
273 for section in self.elffile.iter_sections():
274 if not isinstance(section, RelocationSection):
275 continue
276
277 has_relocation_sections = True
278 self._emitline("\nRelocation section '%s' at offset %s contains %s entries:" % (
279 section.name,
280 self._format_hex(section['sh_offset']),
281 section.num_relocations()))
282 if section.is_RELA():
283 self._emitline(" Offset Info Type Sym. Value Sym. Name + Addend")
284 else:
285 self._emitline(" Offset Info Type Sym.Value Sym. Name")
286
287 # The symbol table section pointed to in sh_link
288 symtable = self.elffile.get_section(section['sh_link'])
289
290 for rel in section.iter_relocations():
291 hexwidth = 8 if self.elffile.elfclass == 32 else 12
292 self._emit('%s %s %-17.17s' % (
293 self._format_hex(rel['r_offset'],
294 fieldsize=hexwidth, lead0x=False),
295 self._format_hex(rel['r_info'],
296 fieldsize=hexwidth, lead0x=False),
297 describe_reloc_type(
298 rel['r_info_type'], self.elffile['e_machine'])))
299
300 if rel['r_info_sym'] == 0:
301 self._emitline()
302 continue
303
304 symbol = symtable.get_symbol(rel['r_info_sym'])
305 # Some symbols have zero 'st_name', so instead what's used is
306 # the name of the section they point at
307 if symbol['st_name'] == 0:
308 symsec = self.elffile.get_section(symbol['st_shndx'])
309 symbol_name = symsec.name
310 else:
311 symbol_name = symbol.name
312 self._emit(' %s %s%22.22s' % (
313 self._format_hex(
314 symbol['st_value'],
315 fullhex=True, lead0x=False),
316 ' ' if self.elffile.elfclass == 32 else '',
317 symbol_name))
318 if section.is_RELA():
319 self._emit(' %s %x' % (
320 '+' if rel['r_addend'] >= 0 else '-',
321 abs(rel['r_addend'])))
322 self._emitline()
323
324 if not has_relocation_sections:
325 self._emitline('\nThere are no relocations in this file.')
326
327 def display_hex_dump(self, section_spec):
328 """ Display a hex dump of a section. section_spec is either a section
329 number or a name.
330 """
331 section = self._section_from_spec(section_spec)
332 if section is None:
333 self._emitline("Section '%s' does not exist in the file!" % (
334 section_spec))
335 return
336
337 self._emitline("\nHex dump of section '%s':" % section.name)
338 self._note_relocs_for_section(section)
339 addr = section['sh_addr']
340 data = section.data()
341 dataptr = 0
342
343 while dataptr < len(data):
344 bytesleft = len(data) - dataptr
345 # chunks of 16 bytes per line
346 linebytes = 16 if bytesleft > 16 else bytesleft
347
348 self._emit(' %s ' % self._format_hex(addr, fieldsize=8))
349 for i in range(16):
350 if i < linebytes:
351 self._emit('%2.2x' % ord(data[dataptr + i]))
352 else:
353 self._emit(' ')
354 if i % 4 == 3:
355 self._emit(' ')
356
357 for i in range(linebytes):
358 c = data[dataptr + i]
359 if c >= ' ' and ord(c) < 0x7f:
360 self._emit(c)
361 else:
362 self._emit('.')
363
364 self._emitline()
365 addr += linebytes
366 dataptr += linebytes
367
368 self._emitline()
369
370 def display_string_dump(self, section_spec):
371 """ Display a strings dump of a section. section_spec is either a
372 section number or a name.
373 """
374 section = self._section_from_spec(section_spec)
375 if section is None:
376 self._emitline("Section '%s' does not exist in the file!" % (
377 section_spec))
378 return
379
380 printables = set(string.printable)
381 self._emitline("\nString dump of section '%s':" % section.name)
382
383 found = False
384 data = section.data()
385 dataptr = 0
386
387 while dataptr < len(data):
388 while dataptr < len(data) and data[dataptr] not in printables:
389 dataptr += 1
390
391 if dataptr >= len(data):
392 break
393
394 endptr = dataptr
395 while endptr < len(data) and data[endptr] != '\x00':
396 endptr += 1
397
398 found = True
399 self._emitline(' [%6x] %s' % (
400 dataptr, data[dataptr:endptr]))
401
402 dataptr = endptr
403
404 if not found:
405 self._emitline(' No strings found in this section.')
406 else:
407 self._emitline()
408
409 def _format_hex(self, addr, fieldsize=None, fullhex=False, lead0x=True):
410 """ Format an address into a hexadecimal string.
411
412 fieldsize:
413 Size of the hexadecimal field (with leading zeros to fit the
414 address into. For example with fieldsize=8, the format will
415 be %08x
416 If None, the minimal required field size will be used.
417
418 fullhex:
419 If True, override fieldsize to set it to the maximal size
420 needed for the elfclass
421
422 lead0x:
423 If True, leading 0x is added
424 """
425 s = '0x' if lead0x else ''
426 if fullhex:
427 fieldsize = 8 if self.elffile.elfclass == 32 else 16
428 if fieldsize is None:
429 field = '%x'
430 else:
431 field = '%' + '0%sx' % fieldsize
432 return s + field % addr
433
434 def _section_from_spec(self, spec):
435 """ Retrieve a section given a "spec" (either number or name).
436 Return None if no such section exists in the file.
437 """
438 try:
439 num = int(spec)
440 if num < self.elffile.num_sections():
441 return self.elffile.get_section(num)
442 else:
443 return None
444 except ValueError:
445 # Not a number. Must be a name then
446 return self.elffile.get_section_by_name(spec)
447
448 def _note_relocs_for_section(self, section):
449 """ If there are relocation sections pointing to the givne section,
450 emit a note about it.
451 """
452 for relsec in self.elffile.iter_sections():
453 if isinstance(relsec, RelocationSection):
454 info_idx = relsec['sh_info']
455 if self.elffile.get_section(info_idx) == section:
456 self._emitline(' Note: This section has relocations against it, but these have NOT been applied to this dump.')
457 return
458
459 def _emit(self, s=''):
460 """ Emit an object to output
461 """
462 self.output.write(str(s))
463
464 def _emitline(self, s=''):
465 """ Emit an object to output, followed by a newline
466 """
467 self.output.write(str(s) + '\n')
468
469
470 SCRIPT_DESCRIPTION = 'Display information about the contents of ELF format files'
471 VERSION_STRING = '%%prog: based on pyelftools %s' % __version__
472
473
474 def main():
475 # parse the command-line arguments and invoke ReadElf
476 optparser = OptionParser(
477 usage='usage: %prog [options] <elf-file>',
478 description=SCRIPT_DESCRIPTION,
479 add_help_option=False, # -h is a real option of readelf
480 prog='readelf.py',
481 version=VERSION_STRING)
482 optparser.add_option('-H', '--help',
483 action='store_true', dest='help',
484 help='Display this information')
485 optparser.add_option('-h', '--file-header',
486 action='store_true', dest='show_file_header',
487 help='Display the ELF file header')
488 optparser.add_option('-l', '--program-headers', '--segments',
489 action='store_true', dest='show_program_header',
490 help='Display the program headers')
491 optparser.add_option('-S', '--section-headers', '--sections',
492 action='store_true', dest='show_section_header',
493 help="Display the sections' headers")
494 optparser.add_option('-e', '--headers',
495 action='store_true', dest='show_all_headers',
496 help='Equivalent to: -h -l -S')
497 optparser.add_option('-s', '--symbols', '--syms',
498 action='store_true', dest='show_symbols',
499 help='Display the symbol table')
500 optparser.add_option('-r', '--relocs',
501 action='store_true', dest='show_relocs',
502 help='Display the relocations (if present)')
503 optparser.add_option('-x', '--hex-dump',
504 action='store', dest='show_hex_dump', metavar='<number|name>',
505 help='Dump the contents of section <number|name> as bytes')
506 optparser.add_option('-p', '--string-dump',
507 action='store', dest='show_string_dump', metavar='<number|name>',
508 help='Dump the contents of section <number|name> as strings')
509
510 options, args = optparser.parse_args()
511
512 if options.help or len(args) == 0:
513 optparser.print_help()
514 sys.exit(0)
515
516 if options.show_all_headers:
517 do_file_header = do_section_header = do_program_header = True
518 else:
519 do_file_header = options.show_file_header
520 do_section_header = options.show_section_header
521 do_program_header = options.show_program_header
522
523 with open(args[0], 'rb') as file:
524 try:
525 readelf = ReadElf(file, sys.stdout)
526 if do_file_header:
527 readelf.display_file_header()
528 if do_section_header:
529 readelf.display_section_headers(
530 show_heading=not do_file_header)
531 if do_program_header:
532 readelf.display_program_headers(
533 show_heading=not do_file_header)
534 if options.show_symbols:
535 readelf.display_symbol_tables()
536 if options.show_relocs:
537 readelf.display_relocations()
538 if options.show_hex_dump:
539 readelf.display_hex_dump(options.show_hex_dump)
540 if options.show_string_dump:
541 readelf.display_string_dump(options.show_string_dump)
542 except ELFError as ex:
543 sys.stderr.write('ELF error: %s\n' % ex)
544 sys.exit(1)
545
546
547 #-------------------------------------------------------------------------------
548 if __name__ == '__main__':
549 main()
550