completed descriptions of --debug-info=frames. readelf tests run
[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
28 from elftools.elf.relocation import RelocationSection
29 from elftools.elf.descriptions import (
30 describe_ei_class, describe_ei_data, describe_ei_version,
31 describe_ei_osabi, describe_e_type, describe_e_machine,
32 describe_e_version_numeric, describe_p_type, describe_p_flags,
33 describe_sh_type, describe_sh_flags,
34 describe_symbol_type, describe_symbol_bind, describe_symbol_visibility,
35 describe_symbol_shndx, describe_reloc_type,
36 )
37 from elftools.dwarf.dwarfinfo import DWARFInfo
38 from elftools.dwarf.descriptions import (
39 describe_attr_value, set_global_machine_arch, describe_CFI_instructions)
40 from elftools.dwarf.constants import (
41 DW_LNS_copy, DW_LNS_set_file, DW_LNE_define_file)
42 from elftools.dwarf.callframe import CIE, FDE
43
44
45 class ReadElf(object):
46 """ display_* methods are used to emit output into the output stream
47 """
48 def __init__(self, file, output):
49 """ file:
50 stream object with the ELF file to read
51
52 output:
53 output stream to write to
54 """
55 self.elffile = ELFFile(file)
56 self.output = output
57
58 # Lazily initialized if a debug dump is requested
59 self._dwarfinfo = None
60
61 def display_file_header(self):
62 """ Display the ELF file header
63 """
64 self._emitline('ELF Header:')
65 self._emit(' Magic: ')
66 self._emitline(' '.join('%2.2x' % ord(b)
67 for b in self.elffile.e_ident_raw))
68 header = self.elffile.header
69 e_ident = header['e_ident']
70 self._emitline(' Class: %s' %
71 describe_ei_class(e_ident['EI_CLASS']))
72 self._emitline(' Data: %s' %
73 describe_ei_data(e_ident['EI_DATA']))
74 self._emitline(' Version: %s' %
75 describe_ei_version(e_ident['EI_VERSION']))
76 self._emitline(' OS/ABI: %s' %
77 describe_ei_osabi(e_ident['EI_OSABI']))
78 self._emitline(' ABI Version: %d' %
79 e_ident['EI_ABIVERSION'])
80 self._emitline(' Type: %s' %
81 describe_e_type(header['e_type']))
82 self._emitline(' Machine: %s' %
83 describe_e_machine(header['e_machine']))
84 self._emitline(' Version: %s' %
85 describe_e_version_numeric(header['e_version']))
86 self._emitline(' Entry point address: %s' %
87 self._format_hex(header['e_entry']))
88 self._emit(' Start of program headers: %s' %
89 header['e_phoff'])
90 self._emitline(' (bytes into file)')
91 self._emit(' Start of section headers: %s' %
92 header['e_shoff'])
93 self._emitline(' (bytes into file)')
94 self._emitline(' Flags: %s' %
95 self._format_hex(header['e_flags']))
96 self._emitline(' Size of this header: %s (bytes)' %
97 header['e_ehsize'])
98 self._emitline(' Size of program headers: %s (bytes)' %
99 header['e_phentsize'])
100 self._emitline(' Number of program headers: %s' %
101 header['e_phnum'])
102 self._emitline(' Size of section headers: %s (bytes)' %
103 header['e_shentsize'])
104 self._emitline(' Number of section headers: %s' %
105 header['e_shnum'])
106 self._emitline(' Section header string table index: %s' %
107 header['e_shstrndx'])
108
109 def display_program_headers(self, show_heading=True):
110 """ Display the ELF program headers.
111 If show_heading is True, displays the heading for this information
112 (Elf file type is...)
113 """
114 self._emitline()
115 if self.elffile.num_segments() == 0:
116 self._emitline('There are no program headers in this file.')
117 return
118
119 elfheader = self.elffile.header
120 if show_heading:
121 self._emitline('Elf file type is %s' %
122 describe_e_type(elfheader['e_type']))
123 self._emitline('Entry point is %s' %
124 self._format_hex(elfheader['e_entry']))
125 # readelf weirness - why isn't e_phoff printed as hex? (for section
126 # headers, it is...)
127 self._emitline('There are %s program headers, starting at offset %s' % (
128 elfheader['e_phnum'], elfheader['e_phoff']))
129 self._emitline()
130
131 self._emitline('Program Headers:')
132
133 # Now comes the table of program headers with their attributes. Note
134 # that due to different formatting constraints of 32-bit and 64-bit
135 # addresses, there are some conditions on elfclass here.
136 #
137 # First comes the table heading
138 #
139 if self.elffile.elfclass == 32:
140 self._emitline(' Type Offset VirtAddr PhysAddr FileSiz MemSiz Flg Align')
141 else:
142 self._emitline(' Type Offset VirtAddr PhysAddr')
143 self._emitline(' FileSiz MemSiz Flags Align')
144
145 # Now the entries
146 #
147 for segment in self.elffile.iter_segments():
148 self._emit(' %-14s ' % describe_p_type(segment['p_type']))
149
150 if self.elffile.elfclass == 32:
151 self._emitline('%s %s %s %s %s %-3s %s' % (
152 self._format_hex(segment['p_offset'], fieldsize=6),
153 self._format_hex(segment['p_vaddr'], fullhex=True),
154 self._format_hex(segment['p_paddr'], fullhex=True),
155 self._format_hex(segment['p_filesz'], fieldsize=5),
156 self._format_hex(segment['p_memsz'], fieldsize=5),
157 describe_p_flags(segment['p_flags']),
158 self._format_hex(segment['p_align'])))
159 else: # 64
160 self._emitline('%s %s %s' % (
161 self._format_hex(segment['p_offset'], fullhex=True),
162 self._format_hex(segment['p_vaddr'], fullhex=True),
163 self._format_hex(segment['p_paddr'], fullhex=True)))
164 self._emitline(' %s %s %-3s %s' % (
165 self._format_hex(segment['p_filesz'], fullhex=True),
166 self._format_hex(segment['p_memsz'], fullhex=True),
167 describe_p_flags(segment['p_flags']),
168 # lead0x set to False for p_align, to mimic readelf.
169 # No idea why the difference from 32-bit mode :-|
170 self._format_hex(segment['p_align'], lead0x=False)))
171
172 if isinstance(segment, InterpSegment):
173 self._emitline(' [Requesting program interpreter: %s]' %
174 segment.get_interp_name())
175
176 # Sections to segments mapping
177 #
178 if self.elffile.num_sections() == 0:
179 # No sections? We're done
180 return
181
182 self._emitline('\n Section to Segment mapping:')
183 self._emitline(' Segment Sections...')
184
185 for nseg, segment in enumerate(self.elffile.iter_segments()):
186 self._emit(' %2.2d ' % nseg)
187
188 for section in self.elffile.iter_sections():
189 if ( not section.is_null() and
190 segment.section_in_segment(section)):
191 self._emit('%s ' % section.name)
192
193 self._emitline('')
194
195 def display_section_headers(self, show_heading=True):
196 """ Display the ELF section headers
197 """
198 elfheader = self.elffile.header
199 if show_heading:
200 self._emitline('There are %s section headers, starting at offset %s' % (
201 elfheader['e_shnum'], self._format_hex(elfheader['e_shoff'])))
202
203 self._emitline('\nSection Header%s:' % (
204 's' if elfheader['e_shnum'] > 1 else ''))
205
206 # Different formatting constraints of 32-bit and 64-bit addresses
207 #
208 if self.elffile.elfclass == 32:
209 self._emitline(' [Nr] Name Type Addr Off Size ES Flg Lk Inf Al')
210 else:
211 self._emitline(' [Nr] Name Type Address Offset')
212 self._emitline(' Size EntSize Flags Link Info Align')
213
214 # Now the entries
215 #
216 for nsec, section in enumerate(self.elffile.iter_sections()):
217 self._emit(' [%2u] %-17.17s %-15.15s ' % (
218 nsec, section.name, describe_sh_type(section['sh_type'])))
219
220 if self.elffile.elfclass == 32:
221 self._emitline('%s %s %s %s %3s %2s %3s %2s' % (
222 self._format_hex(section['sh_addr'], fieldsize=8, lead0x=False),
223 self._format_hex(section['sh_offset'], fieldsize=6, lead0x=False),
224 self._format_hex(section['sh_size'], fieldsize=6, lead0x=False),
225 self._format_hex(section['sh_entsize'], fieldsize=2, lead0x=False),
226 describe_sh_flags(section['sh_flags']),
227 section['sh_link'], section['sh_info'],
228 section['sh_addralign']))
229 else: # 64
230 self._emitline(' %s %s' % (
231 self._format_hex(section['sh_addr'], fullhex=True, lead0x=False),
232 self._format_hex(section['sh_offset'],
233 fieldsize=16 if section['sh_offset'] > 0xffffffff else 8,
234 lead0x=False)))
235 self._emitline(' %s %s %3s %2s %3s %s' % (
236 self._format_hex(section['sh_size'], fullhex=True, lead0x=False),
237 self._format_hex(section['sh_entsize'], fullhex=True, lead0x=False),
238 describe_sh_flags(section['sh_flags']),
239 section['sh_link'], section['sh_info'],
240 section['sh_addralign']))
241
242 self._emitline('Key to Flags:')
243 self._emit(' W (write), A (alloc), X (execute), M (merge), S (strings)')
244 if self.elffile['e_machine'] in ('EM_X86_64', 'EM_L10M'):
245 self._emitline(', l (large)')
246 else:
247 self._emitline()
248 self._emitline(' I (info), L (link order), G (group), T (TLS), E (exclude), x (unknown)')
249 self._emitline(' O (extra OS processing required) o (OS specific), p (processor specific)')
250
251 def display_symbol_tables(self):
252 """ Display the symbol tables contained in the file
253 """
254 for section in self.elffile.iter_sections():
255 if not isinstance(section, SymbolTableSection):
256 continue
257
258 if section['sh_entsize'] == 0:
259 self._emitline("\nSymbol table '%s' has a sh_entsize of zero!" % (
260 section.name))
261 continue
262
263 self._emitline("\nSymbol table '%s' contains %s entries:" % (
264 section.name, section.num_symbols()))
265
266 if self.elffile.elfclass == 32:
267 self._emitline(' Num: Value Size Type Bind Vis Ndx Name')
268 else: # 64
269 self._emitline(' Num: Value Size Type Bind Vis Ndx Name')
270
271 for nsym, symbol in enumerate(section.iter_symbols()):
272 # symbol names are truncated to 25 chars, similarly to readelf
273 self._emitline('%6d: %s %5d %-7s %-6s %-7s %4s %.25s' % (
274 nsym,
275 self._format_hex(symbol['st_value'], fullhex=True, lead0x=False),
276 symbol['st_size'],
277 describe_symbol_type(symbol['st_info']['type']),
278 describe_symbol_bind(symbol['st_info']['bind']),
279 describe_symbol_visibility(symbol['st_other']['visibility']),
280 describe_symbol_shndx(symbol['st_shndx']),
281 symbol.name))
282
283 def display_relocations(self):
284 """ Display the relocations contained in the file
285 """
286 has_relocation_sections = False
287 for section in self.elffile.iter_sections():
288 if not isinstance(section, RelocationSection):
289 continue
290
291 has_relocation_sections = True
292 self._emitline("\nRelocation section '%s' at offset %s contains %s entries:" % (
293 section.name,
294 self._format_hex(section['sh_offset']),
295 section.num_relocations()))
296 if section.is_RELA():
297 self._emitline(" Offset Info Type Sym. Value Sym. Name + Addend")
298 else:
299 self._emitline(" Offset Info Type Sym.Value Sym. Name")
300
301 # The symbol table section pointed to in sh_link
302 symtable = self.elffile.get_section(section['sh_link'])
303
304 for rel in section.iter_relocations():
305 hexwidth = 8 if self.elffile.elfclass == 32 else 12
306 self._emit('%s %s %-17.17s' % (
307 self._format_hex(rel['r_offset'],
308 fieldsize=hexwidth, lead0x=False),
309 self._format_hex(rel['r_info'],
310 fieldsize=hexwidth, lead0x=False),
311 describe_reloc_type(
312 rel['r_info_type'], self.elffile)))
313
314 if rel['r_info_sym'] == 0:
315 self._emitline()
316 continue
317
318 symbol = symtable.get_symbol(rel['r_info_sym'])
319 # Some symbols have zero 'st_name', so instead what's used is
320 # the name of the section they point at
321 if symbol['st_name'] == 0:
322 symsec = self.elffile.get_section(symbol['st_shndx'])
323 symbol_name = symsec.name
324 else:
325 symbol_name = symbol.name
326 self._emit(' %s %s%22.22s' % (
327 self._format_hex(
328 symbol['st_value'],
329 fullhex=True, lead0x=False),
330 ' ' if self.elffile.elfclass == 32 else '',
331 symbol_name))
332 if section.is_RELA():
333 self._emit(' %s %x' % (
334 '+' if rel['r_addend'] >= 0 else '-',
335 abs(rel['r_addend'])))
336 self._emitline()
337
338 if not has_relocation_sections:
339 self._emitline('\nThere are no relocations in this file.')
340
341 def display_hex_dump(self, section_spec):
342 """ Display a hex dump of a section. section_spec is either a section
343 number or a name.
344 """
345 section = self._section_from_spec(section_spec)
346 if section is None:
347 self._emitline("Section '%s' does not exist in the file!" % (
348 section_spec))
349 return
350
351 self._emitline("\nHex dump of section '%s':" % section.name)
352 self._note_relocs_for_section(section)
353 addr = section['sh_addr']
354 data = section.data()
355 dataptr = 0
356
357 while dataptr < len(data):
358 bytesleft = len(data) - dataptr
359 # chunks of 16 bytes per line
360 linebytes = 16 if bytesleft > 16 else bytesleft
361
362 self._emit(' %s ' % self._format_hex(addr, fieldsize=8))
363 for i in range(16):
364 if i < linebytes:
365 self._emit('%2.2x' % ord(data[dataptr + i]))
366 else:
367 self._emit(' ')
368 if i % 4 == 3:
369 self._emit(' ')
370
371 for i in range(linebytes):
372 c = data[dataptr + i]
373 if c >= ' ' and ord(c) < 0x7f:
374 self._emit(c)
375 else:
376 self._emit('.')
377
378 self._emitline()
379 addr += linebytes
380 dataptr += linebytes
381
382 self._emitline()
383
384 def display_string_dump(self, section_spec):
385 """ Display a strings dump of a section. section_spec is either a
386 section number or a name.
387 """
388 section = self._section_from_spec(section_spec)
389 if section is None:
390 self._emitline("Section '%s' does not exist in the file!" % (
391 section_spec))
392 return
393
394 printables = set(string.printable)
395 self._emitline("\nString dump of section '%s':" % section.name)
396
397 found = False
398 data = section.data()
399 dataptr = 0
400
401 while dataptr < len(data):
402 while dataptr < len(data) and data[dataptr] not in printables:
403 dataptr += 1
404
405 if dataptr >= len(data):
406 break
407
408 endptr = dataptr
409 while endptr < len(data) and data[endptr] != '\x00':
410 endptr += 1
411
412 found = True
413 self._emitline(' [%6x] %s' % (
414 dataptr, data[dataptr:endptr]))
415
416 dataptr = endptr
417
418 if not found:
419 self._emitline(' No strings found in this section.')
420 else:
421 self._emitline()
422
423 def display_debug_dump(self, dump_what):
424 """ Dump a DWARF section
425 """
426 self._init_dwarfinfo()
427 if self._dwarfinfo is None:
428 return
429
430 set_global_machine_arch(self.elffile.get_machine_arch())
431
432 if dump_what == 'info':
433 self._dump_debug_info()
434 elif dump_what == 'decodedline':
435 self._dump_debug_line_programs()
436 elif dump_what == 'frames':
437 self._dump_debug_frames()
438 else:
439 self._emitline('debug dump not yet supported for "%s"' % dump_what)
440
441 def _format_hex(self, addr, fieldsize=None, fullhex=False, lead0x=True):
442 """ Format an address into a hexadecimal string.
443
444 fieldsize:
445 Size of the hexadecimal field (with leading zeros to fit the
446 address into. For example with fieldsize=8, the format will
447 be %08x
448 If None, the minimal required field size will be used.
449
450 fullhex:
451 If True, override fieldsize to set it to the maximal size
452 needed for the elfclass
453
454 lead0x:
455 If True, leading 0x is added
456 """
457 s = '0x' if lead0x else ''
458 if fullhex:
459 fieldsize = 8 if self.elffile.elfclass == 32 else 16
460 if fieldsize is None:
461 field = '%x'
462 else:
463 field = '%' + '0%sx' % fieldsize
464 return s + field % addr
465
466 def _section_from_spec(self, spec):
467 """ Retrieve a section given a "spec" (either number or name).
468 Return None if no such section exists in the file.
469 """
470 try:
471 num = int(spec)
472 if num < self.elffile.num_sections():
473 return self.elffile.get_section(num)
474 else:
475 return None
476 except ValueError:
477 # Not a number. Must be a name then
478 return self.elffile.get_section_by_name(spec)
479
480 def _note_relocs_for_section(self, section):
481 """ If there are relocation sections pointing to the givne section,
482 emit a note about it.
483 """
484 for relsec in self.elffile.iter_sections():
485 if isinstance(relsec, RelocationSection):
486 info_idx = relsec['sh_info']
487 if self.elffile.get_section(info_idx) == section:
488 self._emitline(' Note: This section has relocations against it, but these have NOT been applied to this dump.')
489 return
490
491 def _init_dwarfinfo(self):
492 """ Initialize the DWARF info contained in the file and assign it to
493 self._dwarfinfo.
494 Leave self._dwarfinfo at None if no DWARF info was found in the file
495 """
496 if self._dwarfinfo is not None:
497 return
498
499 if self.elffile.has_dwarf_info():
500 self._dwarfinfo = self.elffile.get_dwarf_info()
501 else:
502 self._dwarfinfo = None
503
504 def _dump_debug_info(self):
505 """ Dump the debugging info section.
506 """
507 self._emitline('Contents of the .debug_info section:\n')
508
509 # Offset of the .debug_info section in the stream
510 section_offset = self._dwarfinfo.debug_info_sec.global_offset
511
512 for cu in self._dwarfinfo.iter_CUs():
513 self._emitline(' Compilation Unit @ offset %s:' %
514 self._format_hex(cu.cu_offset))
515 self._emitline(' Length: %s (%s)' % (
516 self._format_hex(cu['unit_length']),
517 '%s-bit' % cu.dwarf_format()))
518 self._emitline(' Version: %s' % cu['version']),
519 self._emitline(' Abbrev Offset: %s' % cu['debug_abbrev_offset']),
520 self._emitline(' Pointer Size: %s' % cu['address_size'])
521
522 # The nesting depth of each DIE within the tree of DIEs must be
523 # displayed. To implement this, a counter is incremented each time
524 # the current DIE has children, and decremented when a null die is
525 # encountered. Due to the way the DIE tree is serialized, this will
526 # correctly reflect the nesting depth
527 #
528 die_depth = 0
529 for die in cu.iter_DIEs():
530 if die.is_null():
531 die_depth -= 1
532 continue
533 self._emitline(' <%s><%x>: Abbrev Number: %s (%s)' % (
534 die_depth,
535 die.offset,
536 die.abbrev_code,
537 die.tag))
538
539 for attr in die.attributes.itervalues():
540 self._emitline(' <%2x> %-18s: %s' % (
541 attr.offset,
542 attr.name,
543 describe_attr_value(
544 attr, die, section_offset)))
545
546 if die.has_children:
547 die_depth += 1
548
549 self._emitline()
550
551 def _dump_debug_line_programs(self):
552 """ Dump the (decoded) line programs from .debug_line
553 The programs are dumped in the order of the CUs they belong to.
554 """
555 self._emitline('Decoded dump of debug contents of section .debug_line:\n')
556
557 for cu in self._dwarfinfo.iter_CUs():
558 lineprogram = self._dwarfinfo.line_program_for_CU(cu)
559
560 cu_filename = ''
561 if len(lineprogram['include_directory']) > 0:
562 cu_filename = '%s/%s' % (
563 lineprogram['include_directory'][0],
564 lineprogram['file_entry'][0].name)
565 else:
566 cu_filename = lineprogram['file_entry'][0].name
567
568 self._emitline('CU: %s:' % cu_filename)
569 self._emitline('File name Line number Starting address')
570
571 # Print each state's file, line and address information. For some
572 # instructions other output is needed to be compatible with
573 # readelf.
574 for entry in lineprogram.get_entries():
575 state = entry.state
576 if state is None:
577 # Special handling for commands that don't set a new state
578 if entry.command == DW_LNS_set_file:
579 file_entry = lineprogram['file_entry'][entry.args[0] - 1]
580 if file_entry.dir_index == 0:
581 # current directory
582 self._emitline('\n./%s:[++]' % (
583 file_entry.name))
584 else:
585 self._emitline('\n%s/%s:' % (
586 lineprogram['include_directory'][file_entry.dir_index - 1],
587 file_entry.name))
588 elif entry.command == DW_LNE_define_file:
589 self._emitline('%s:' % (
590 lineprogram['include_directory'][entry.args[0].dir_index]))
591 elif not state.end_sequence:
592 # readelf doesn't print the state after end_sequence
593 # instructions. I think it's a bug but to be compatible
594 # I don't print them too.
595 self._emitline('%-35s %11d %18s' % (
596 lineprogram['file_entry'][state.file - 1].name,
597 state.line,
598 '0' if state.address == 0 else
599 self._format_hex(state.address)))
600 if entry.command == DW_LNS_copy:
601 # Another readelf oddity...
602 self._emitline()
603
604 def _dump_debug_frames(self):
605 """ Dump the raw frame information from .debug_frame
606 """
607 if not self._dwarfinfo.has_CFI():
608 return
609 self._emitline('Contents of the .debug_frame section:')
610
611 for entry in self._dwarfinfo.CFI_entries():
612 if isinstance(entry, CIE):
613 self._emitline('\n%08x %08x %08x CIE' % (
614 entry.offset, entry['length'], entry['CIE_id']))
615 self._emitline(' Version: %d' % entry['version'])
616 self._emitline(' Augmentation: "%s"' % entry['augmentation'])
617 self._emitline(' Code alignment factor: %u' % entry['code_alignment_factor'])
618 self._emitline(' Data alignment factor: %d' % entry['data_alignment_factor'])
619 self._emitline(' Return address column: %d' % entry['return_address_register'])
620 self._emitline()
621 else: # FDE
622 self._emitline('\n%08x %08x %08x FDE cie=%08x pc=%08x..%08x' % (
623 entry.offset,
624 entry['length'],
625 entry['CIE_pointer'],
626 entry.cie.offset,
627 entry['initial_location'],
628 entry['initial_location'] + entry['address_range']))
629
630 self._emit(describe_CFI_instructions(entry))
631 self._emitline()
632
633 def _emit(self, s=''):
634 """ Emit an object to output
635 """
636 self.output.write(str(s))
637
638 def _emitline(self, s=''):
639 """ Emit an object to output, followed by a newline
640 """
641 self.output.write(str(s) + '\n')
642
643
644 SCRIPT_DESCRIPTION = 'Display information about the contents of ELF format files'
645 VERSION_STRING = '%%prog: based on pyelftools %s' % __version__
646
647
648 def main(stream=None):
649 # parse the command-line arguments and invoke ReadElf
650 optparser = OptionParser(
651 usage='usage: %prog [options] <elf-file>',
652 description=SCRIPT_DESCRIPTION,
653 add_help_option=False, # -h is a real option of readelf
654 prog='readelf.py',
655 version=VERSION_STRING)
656 optparser.add_option('-H', '--help',
657 action='store_true', dest='help',
658 help='Display this information')
659 optparser.add_option('-h', '--file-header',
660 action='store_true', dest='show_file_header',
661 help='Display the ELF file header')
662 optparser.add_option('-l', '--program-headers', '--segments',
663 action='store_true', dest='show_program_header',
664 help='Display the program headers')
665 optparser.add_option('-S', '--section-headers', '--sections',
666 action='store_true', dest='show_section_header',
667 help="Display the sections' headers")
668 optparser.add_option('-e', '--headers',
669 action='store_true', dest='show_all_headers',
670 help='Equivalent to: -h -l -S')
671 optparser.add_option('-s', '--symbols', '--syms',
672 action='store_true', dest='show_symbols',
673 help='Display the symbol table')
674 optparser.add_option('-r', '--relocs',
675 action='store_true', dest='show_relocs',
676 help='Display the relocations (if present)')
677 optparser.add_option('-x', '--hex-dump',
678 action='store', dest='show_hex_dump', metavar='<number|name>',
679 help='Dump the contents of section <number|name> as bytes')
680 optparser.add_option('-p', '--string-dump',
681 action='store', dest='show_string_dump', metavar='<number|name>',
682 help='Dump the contents of section <number|name> as strings')
683 optparser.add_option('--debug-dump',
684 action='store', dest='debug_dump_what', metavar='<section>',
685 help='Display the contents of DWARF debug sections')
686
687 options, args = optparser.parse_args()
688
689 if options.help or len(args) == 0:
690 optparser.print_help()
691 sys.exit(0)
692
693 if options.show_all_headers:
694 do_file_header = do_section_header = do_program_header = True
695 else:
696 do_file_header = options.show_file_header
697 do_section_header = options.show_section_header
698 do_program_header = options.show_program_header
699
700 with open(args[0], 'rb') as file:
701 try:
702 readelf = ReadElf(file, stream or sys.stdout)
703 if do_file_header:
704 readelf.display_file_header()
705 if do_section_header:
706 readelf.display_section_headers(
707 show_heading=not do_file_header)
708 if do_program_header:
709 readelf.display_program_headers(
710 show_heading=not do_file_header)
711 if options.show_symbols:
712 readelf.display_symbol_tables()
713 if options.show_relocs:
714 readelf.display_relocations()
715 if options.show_hex_dump:
716 readelf.display_hex_dump(options.show_hex_dump)
717 if options.show_string_dump:
718 readelf.display_string_dump(options.show_string_dump)
719 if options.debug_dump_what:
720 readelf.display_debug_dump(options.debug_dump_what)
721 except ELFError as ex:
722 sys.stderr.write('ELF error: %s\n' % ex)
723 sys.exit(1)
724
725
726 def profile_main():
727 # Run 'main' redirecting its output to readelfout.txt
728 # Saves profiling information in readelf.profile
729 PROFFILE = 'readelf.profile'
730 import cProfile
731 cProfile.run('main(open("readelfout.txt", "w"))', PROFFILE)
732
733 # Dig in some profiling stats
734 import pstats
735 p = pstats.Stats(PROFFILE)
736 p.sort_stats('cumulative').print_stats(25)
737
738
739 #-------------------------------------------------------------------------------
740 if __name__ == '__main__':
741 main()
742 #profile_main()
743
744