Fix Container's __pretty_str__ to use str instead of repr. This provides more consist...
[pyelftools.git] / scripts / readelf.py
index 01c4d1f3e2493919a8fb61dce89558bc41cb03be..6ecac7bd8a68f4db92cf5ac976ceeced8f70eda5 100755 (executable)
@@ -9,12 +9,11 @@
 #-------------------------------------------------------------------------------
 import os, sys
 from optparse import OptionParser
+from itertools import ifilter
 import string
 
-
 # If elftools is not installed, maybe we're running from the root or scripts
 # dir of the source distribution
-#
 try:
     import elftools
 except ImportError:
@@ -36,7 +35,10 @@ from elftools.elf.descriptions import (
     )
 from elftools.dwarf.dwarfinfo import DWARFInfo
 from elftools.dwarf.descriptions import (
-    describe_attr_value, set_global_machine_arch, describe_CFI_instruction)
+    describe_reg_name, describe_attr_value, set_global_machine_arch,
+    describe_CFI_instructions, describe_CFI_register_rule,
+    describe_CFI_CFA_rule,
+    )
 from elftools.dwarf.constants import (
     DW_LNS_copy, DW_LNS_set_file, DW_LNE_define_file)
 from elftools.dwarf.callframe import CIE, FDE
@@ -435,6 +437,8 @@ class ReadElf(object):
             self._dump_debug_line_programs()
         elif dump_what == 'frames':
             self._dump_debug_frames()
+        elif dump_what == 'frames-interp':
+            self._dump_debug_frames_interp()
         else:
             self._emitline('debug dump not yet supported for "%s"' % dump_what)
 
@@ -537,9 +541,13 @@ class ReadElf(object):
                     die.tag))
                 
                 for attr in die.attributes.itervalues():
+                    name = attr.name
+                    # Unknown attribute values are passed-through as integers
+                    if isinstance(name, int):
+                        name = 'Unknown AT value: %x' % name
                     self._emitline('    <%2x>   %-18s: %s' % (
                         attr.offset,
-                        attr.name,
+                        name,
                         describe_attr_value(
                             attr, die, section_offset)))
                 
@@ -604,6 +612,8 @@ class ReadElf(object):
     def _dump_debug_frames(self):
         """ Dump the raw frame information from .debug_frame
         """
+        if not self._dwarfinfo.has_CFI():
+            return
         self._emitline('Contents of the .debug_frame section:')
 
         for entry in self._dwarfinfo.CFI_entries():
@@ -615,6 +625,7 @@ class ReadElf(object):
                 self._emitline('  Code alignment factor: %u' % entry['code_alignment_factor'])
                 self._emitline('  Data alignment factor: %d' % entry['data_alignment_factor'])
                 self._emitline('  Return address column: %d' % entry['return_address_register'])
+                self._emitline()
             else: # FDE
                 self._emitline('\n%08x %08x %08x FDE cie=%08x pc=%08x..%08x' % (
                     entry.offset,
@@ -624,10 +635,73 @@ class ReadElf(object):
                     entry['initial_location'],
                     entry['initial_location'] + entry['address_range']))
 
-            if len(entry.instructions) > 0:
-                self._emitline('')
-                for instr in entry.instructions:
-                    self._emitline(describe_CFI_instruction(instr, entry))
+            self._emit(describe_CFI_instructions(entry))
+        self._emitline()
+
+    def _dump_debug_frames_interp(self):
+        """ Dump the interpreted (decoded) frame information from .debug_frame
+        """
+        if not self._dwarfinfo.has_CFI():
+            return
+
+        self._emitline('Contents of the .debug_frame section:')
+
+        for entry in self._dwarfinfo.CFI_entries():
+            if isinstance(entry, CIE):
+                self._emitline('\n%08x %08x %08x CIE "%s" cf=%d df=%d ra=%d' % (
+                    entry.offset,
+                    entry['length'],
+                    entry['CIE_id'],
+                    entry['augmentation'],
+                    entry['code_alignment_factor'],
+                    entry['data_alignment_factor'],
+                    entry['return_address_register']))
+                ra_regnum = entry['return_address_register']
+            else: # FDE
+                self._emitline('\n%08x %08x %08x FDE cie=%08x pc=%08x..%08x' % (
+                    entry.offset,
+                    entry['length'],
+                    entry['CIE_pointer'],
+                    entry.cie.offset,
+                    entry['initial_location'],
+                    entry['initial_location'] + entry['address_range']))
+                ra_regnum = entry.cie['return_address_register']
+
+            # Print the heading row for the decoded table
+            self._emit('   LOC')
+            self._emit('  ' if entry.structs.address_size == 4 else '          ')
+            self._emit(' CFA      ')
+
+            # Decode the table nad look at the registers it describes.
+            # We build reg_order here to match readelf's order. In particular,
+            # registers are sorted by their number, and the register matching
+            # ra_regnum is always listed last with a special heading.
+            decoded_table = entry.get_decoded()
+            reg_order = sorted(ifilter(
+                lambda r: r != ra_regnum, 
+                decoded_table.reg_order))
+
+            # Headings for the registers
+            for regnum in reg_order:
+                self._emit('%-6s' % describe_reg_name(regnum))
+            self._emitline('ra      ')
+            
+            # Now include ra_regnum in reg_order to print its values similarly
+            # to the other registers.
+            reg_order.append(ra_regnum)
+            for line in decoded_table.table:
+                self._emit(self._format_hex(
+                    line['pc'], fullhex=True, lead0x=False))
+                self._emit(' %-9s' % describe_CFI_CFA_rule(line['cfa']))
+
+                for regnum in reg_order:
+                    if regnum in line:
+                        s = describe_CFI_register_rule(line[regnum])
+                    else:
+                        s = 'u'
+                    self._emit('%-6s' % s)
+                self._emitline()
+        self._emitline()
 
     def _emit(self, s=''):
         """ Emit an object to output
@@ -680,8 +754,10 @@ def main(stream=None):
             action='store', dest='show_string_dump', metavar='<number|name>',
             help='Dump the contents of section <number|name> as strings')
     optparser.add_option('--debug-dump',
-            action='store', dest='debug_dump_what', metavar='<section>',
-            help='Display the contents of DWARF debug sections')
+            action='store', dest='debug_dump_what', metavar='<what>',
+            help=(
+                'Display the contents of DWARF debug sections. <what> can ' +
+                'one of {info,decodedline,frames,frames-interp}'))
 
     options, args = optparser.parse_args()