208
|
1 import binascii
|
346
|
2 from ppci.target import Instruction, Alignment
|
335
|
3 from ppci.objectfile import ObjectFile
|
234
|
4
|
208
|
5 """
|
|
6 The output stream is a stream of instructions that can be output
|
|
7 to a file or binary or hexfile.
|
|
8 """
|
|
9
|
219
|
10
|
335
|
11 class OutputStream:
|
237
|
12 def emit(self, item):
|
335
|
13 raise NotImplementedError('Abstract base class')
|
219
|
14
|
250
|
15 def selectSection(self, sname):
|
335
|
16 raise NotImplementedError('Abstract base class')
|
234
|
17
|
208
|
18
|
316
|
19 class OutputStreamWriter:
|
|
20 def __init__(self, extra_indent=''):
|
|
21 self.extra_indent = extra_indent
|
208
|
22
|
316
|
23 def dump(self, stream, f):
|
|
24 for s in sorted(stream.sections.keys()):
|
|
25 # print('.section '+ s)
|
|
26 self.dumpSection(stream.sections[s], f)
|
|
27
|
|
28 def dumpSection(self, s, f):
|
|
29 for i in s.instructions:
|
234
|
30 addr = i.address
|
|
31 insword = i.encode()
|
|
32 assert type(insword) is bytes
|
|
33 insword = binascii.hexlify(bytes(reversed(insword))).decode('ascii')
|
|
34 asm = str(i)
|
235
|
35 if len(insword) == 0:
|
316
|
36 print(' {}'.format(asm), file=f)
|
235
|
37 else:
|
316
|
38 print(' 0x{0:08x} 0x{1} {2}'.format(addr, insword, asm), file=f)
|
208
|
39
|
296
|
40
|
335
|
41 class BinaryOutputStream(OutputStream):
|
|
42 """ Output stream that writes to object file """
|
|
43 def __init__(self, obj_file):
|
|
44 super().__init__()
|
|
45 self.obj_file = obj_file
|
208
|
46
|
335
|
47 def emit(self, item):
|
|
48 """ Encode instruction and add symbol and relocation information """
|
341
|
49 assert isinstance(item, Instruction), str(item) + str(type(item))
|
335
|
50 assert self.currentSection
|
|
51 section = self.currentSection
|
|
52 address = self.currentSection.Size
|
|
53 b = item.encode()
|
|
54 syms = item.symbols()
|
|
55 relocs = item.relocations()
|
|
56 section.add_data(b)
|
|
57 for sym in syms:
|
|
58 self.obj_file.add_symbol(sym, address, section.name)
|
|
59 for sym, typ in relocs:
|
|
60 self.obj_file.add_relocation(sym, address, typ, section.name)
|
|
61 # Special case for align, TODO do this different?
|
|
62 if type(item) is Alignment:
|
|
63 while section.Size % item.align != 0:
|
|
64 section.add_data(bytes([0]))
|
236
|
65
|
335
|
66 def selectSection(self, sname):
|
|
67 self.currentSection = self.obj_file.get_section(sname)
|
337
|
68
|
|
69
|
|
70 class DummyOutputStream(OutputStream):
|
|
71 def emit(self, item):
|
|
72 pass
|
|
73
|
|
74 def selectSection(self, sname):
|
|
75 pass
|