Cleanup coff-dump.py
[oota-llvm.git] / test / Scripts / macho-dump
1 #!/usr/bin/env python
2
3 import struct
4 import sys
5 import StringIO
6
7 import common_dump
8
9 class Reader:
10    def __init__(self, path):
11       if path == '-':
12          # Snarf all the data so we can seek.
13          self.file = StringIO.StringIO(sys.stdin.read())
14       else:
15          self.file = open(path,'rb')
16       self.isLSB = None
17       self.is64Bit = None
18
19       self.string_table = None
20
21    def tell(self):
22       return self.file.tell()
23
24    def seek(self, pos):
25       self.file.seek(pos)
26
27    def read(self, N):
28       data = self.file.read(N)
29       if len(data) != N:
30          raise ValueError,"Out of data!"
31       return data
32
33    def read8(self):
34       return ord(self.read(1))
35
36    def read16(self):
37       return struct.unpack('><'[self.isLSB] + 'H', self.read(2))[0]
38
39    def read32(self):
40       # Force to 32-bit, if possible; otherwise these might be long ints on a
41       # big-endian platform. FIXME: Why???
42       Value = struct.unpack('><'[self.isLSB] + 'I', self.read(4))[0]
43       return int(Value)
44
45    def read64(self):
46       return struct.unpack('><'[self.isLSB] + 'Q', self.read(8))[0]
47
48    def registerStringTable(self, strings):
49       if self.string_table is not None:
50          raise ValueError,"%s: warning: multiple string tables" % sys.argv[0]
51
52       self.string_table = strings
53
54    def getString(self, index):
55       if self.string_table is None:
56          raise ValueError,"%s: warning: no string table registered" % sys.argv[0]
57       
58       end = self.string_table.index('\x00', index)
59       return self.string_table[index:end]
60
61 def dumpmacho(path, opts):
62    f = Reader(path)
63
64    magic = f.read(4)
65    if magic == '\xFE\xED\xFA\xCE':
66       f.isLSB, f.is64Bit = False, False
67    elif magic == '\xCE\xFA\xED\xFE':
68       f.isLSB, f.is64Bit = True, False
69    elif magic == '\xFE\xED\xFA\xCF':
70       f.isLSB, f.is64Bit = False, True
71    elif magic == '\xCF\xFA\xED\xFE':
72       f.isLSB, f.is64Bit = True, True
73    else:
74       raise ValueError,"Not a Mach-O object file: %r (bad magic)" % path
75
76    print "('cputype', %r)" % f.read32()
77    print "('cpusubtype', %r)" % f.read32()
78    filetype = f.read32()
79    print "('filetype', %r)" % filetype
80    
81    numLoadCommands = f.read32()
82    print "('num_load_commands', %r)" % filetype
83
84    loadCommandsSize = f.read32()
85    print "('load_commands_size', %r)" % loadCommandsSize
86
87    print "('flag', %r)" % f.read32()
88
89    if f.is64Bit:
90       print "('reserved', %r)" % f.read32()
91
92    start = f.tell()
93
94    print "('load_commands', ["
95    for i in range(numLoadCommands):
96       dumpLoadCommand(f, i, opts)
97    print "])"
98
99    if f.tell() - start != loadCommandsSize:
100       raise ValueError,"%s: warning: invalid load commands size: %r" % (
101          sys.argv[0], loadCommandsSize)
102
103 def dumpLoadCommand(f, i, opts):
104    start = f.tell()
105
106    print "  # Load Command %r" % i
107    cmd = f.read32()
108    print " (('command', %r)" % cmd
109    cmdSize = f.read32()
110    print "  ('size', %r)" % cmdSize
111
112    if cmd == 1:
113       dumpSegmentLoadCommand(f, opts, False)
114    elif cmd == 2:
115       dumpSymtabCommand(f, opts)
116    elif cmd == 11:
117       dumpDysymtabCommand(f, opts)
118    elif cmd == 25:
119       dumpSegmentLoadCommand(f, opts, True)
120    elif cmd == 27:
121       import uuid
122       print "  ('uuid', %s)" % uuid.UUID(bytes=f.read(16))
123    else:
124       print >>sys.stderr,"%s: warning: unknown load command: %r" % (
125          sys.argv[0], cmd)
126       f.read(cmdSize - 8)
127    print " ),"
128
129    if f.tell() - start != cmdSize:
130       raise ValueError,"%s: warning: invalid load command size: %r" % (
131          sys.argv[0], cmdSize)
132
133 def dumpSegmentLoadCommand(f, opts, is64Bit):
134    print "  ('segment_name', %r)" % f.read(16) 
135    if is64Bit:
136       print "  ('vm_addr', %r)" % f.read64()
137       print "  ('vm_size', %r)" % f.read64()
138       print "  ('file_offset', %r)" % f.read64()
139       print "  ('file_size', %r)" % f.read64()
140    else:
141       print "  ('vm_addr', %r)" % f.read32()
142       print "  ('vm_size', %r)" % f.read32()
143       print "  ('file_offset', %r)" % f.read32()
144       print "  ('file_size', %r)" % f.read32()
145    print "  ('maxprot', %r)" % f.read32()
146    print "  ('initprot', %r)" % f.read32()
147    numSections = f.read32()
148    print "  ('num_sections', %r)" % numSections
149    print "  ('flags', %r)" % f.read32()
150
151    print "  ('sections', ["
152    for i in range(numSections):
153       dumpSection(f, i, opts, is64Bit)
154    print "  ])"
155
156 def dumpSymtabCommand(f, opts):
157    symoff = f.read32()
158    print "  ('symoff', %r)" % symoff
159    nsyms = f.read32()
160    print "  ('nsyms', %r)" % nsyms
161    stroff = f.read32()
162    print "  ('stroff', %r)" % stroff
163    strsize = f.read32()
164    print "  ('strsize', %r)" % strsize
165
166    prev_pos = f.tell()
167
168    f.seek(stroff)
169    string_data = f.read(strsize)
170    print "  ('_string_data', %r)" % string_data
171
172    f.registerStringTable(string_data)
173
174    f.seek(symoff)
175    print "  ('_symbols', ["
176    for i in range(nsyms):
177       dumpNlist32(f, i, opts)
178    print "  ])"
179       
180    f.seek(prev_pos)
181
182 def dumpNlist32(f, i, opts):
183    print "    # Symbol %r" % i
184    n_strx = f.read32()
185    print "   (('n_strx', %r)" % n_strx
186    n_type = f.read8()
187    print "    ('n_type', %#x)" % n_type
188    n_sect = f.read8()
189    print "    ('n_sect', %r)" % n_sect
190    n_desc = f.read16()
191    print "    ('n_desc', %r)" % n_desc
192    if f.is64Bit:
193       n_value = f.read64()
194       print "    ('n_value', %r)" % n_value
195    else:
196       n_value = f.read32()
197       print "    ('n_value', %r)" % n_value
198    print "    ('_string', %r)" % f.getString(n_strx)
199    print "   ),"
200
201 def dumpDysymtabCommand(f, opts):   
202    print "  ('ilocalsym', %r)" % f.read32()
203    print "  ('nlocalsym', %r)" % f.read32()
204    print "  ('iextdefsym', %r)" % f.read32()
205    print "  ('nextdefsym', %r)" % f.read32()
206    print "  ('iundefsym', %r)" % f.read32()
207    print "  ('nundefsym', %r)" % f.read32()
208    print "  ('tocoff', %r)" % f.read32()
209    print "  ('ntoc', %r)" % f.read32()
210    print "  ('modtaboff', %r)" % f.read32()
211    print "  ('nmodtab', %r)" % f.read32()
212    print "  ('extrefsymoff', %r)" % f.read32()
213    print "  ('nextrefsyms', %r)" % f.read32()
214    indirectsymoff = f.read32()
215    print "  ('indirectsymoff', %r)" % indirectsymoff
216    nindirectsyms = f.read32()
217    print "  ('nindirectsyms', %r)" % nindirectsyms
218    print "  ('extreloff', %r)" % f.read32()
219    print "  ('nextrel', %r)" % f.read32()
220    print "  ('locreloff', %r)" % f.read32()
221    print "  ('nlocrel', %r)" % f.read32()
222
223    prev_pos = f.tell()
224
225    f.seek(indirectsymoff)
226    print "  ('_indirect_symbols', ["
227    for i in range(nindirectsyms):
228       print "    # Indirect Symbol %r" % i
229       print "    (('symbol_index', %#x),)," % f.read32()
230    print "  ])"
231       
232    f.seek(prev_pos)
233
234 def dumpSection(f, i, opts, is64Bit):
235    print "    # Section %r" % i
236    print "   (('section_name', %r)" % f.read(16)
237    print "    ('segment_name', %r)" % f.read(16)
238    if is64Bit:
239       print "    ('address', %r)" % f.read64()
240       size = f.read64()
241       print "    ('size', %r)" % size
242    else:
243       print "    ('address', %r)" % f.read32()
244       size = f.read32()
245       print "    ('size', %r)" % size
246    offset = f.read32()
247    print "    ('offset', %r)" % offset
248    print "    ('alignment', %r)" % f.read32()   
249    reloc_offset = f.read32()
250    print "    ('reloc_offset', %r)" % reloc_offset
251    num_reloc = f.read32()
252    print "    ('num_reloc', %r)" % num_reloc
253    print "    ('flags', %#x)" % f.read32()
254    print "    ('reserved1', %r)" % f.read32()
255    print "    ('reserved2', %r)" % f.read32()
256    if is64Bit:
257       print "    ('reserved3', %r)" % f.read32()
258    print "   ),"
259
260    prev_pos = f.tell()
261
262    f.seek(reloc_offset)
263    print "  ('_relocations', ["
264    for i in range(num_reloc):
265       print "    # Relocation %r" % i
266       print "    (('word-0', %#x)," % f.read32()
267       print "     ('word-1', %#x))," % f.read32()
268    print "  ])"
269
270    if opts.dumpSectionData:
271       f.seek(offset)
272       print "  ('_section_data', '%s')" % common_dump.dataToHex(f.read(size))
273       
274    f.seek(prev_pos)
275    
276 def main():
277     from optparse import OptionParser, OptionGroup
278     parser = OptionParser("usage: %prog [options] {files}")
279     parser.add_option("", "--dump-section-data", dest="dumpSectionData",
280                       help="Dump the contents of sections",
281                       action="store_true", default=False)    
282     (opts, args) = parser.parse_args()
283
284     if not args:
285        args.append('-')
286
287     for arg in args:
288        dumpmacho(arg, opts)
289
290 if __name__ == '__main__':
291    main()