208
|
1 import binascii
|
234
|
2 from target import Instruction, Label
|
|
3
|
208
|
4 """
|
|
5 The output stream is a stream of instructions that can be output
|
|
6 to a file or binary or hexfile.
|
|
7 """
|
|
8
|
219
|
9
|
208
|
10 class OutputStream:
|
|
11 def __init__(self):
|
|
12 self.sections = {}
|
|
13 self.currentSection = None
|
225
|
14
|
208
|
15 def emit(self, item):
|
234
|
16 assert isinstance(item, Instruction)
|
208
|
17 self.sections[self.currentSection].append(item)
|
219
|
18
|
|
19 def align(self, alignment):
|
|
20 self.emit(Alignment(alignment))
|
234
|
21
|
208
|
22 def selectSection(self, s):
|
|
23 self.currentSection = s
|
|
24 if not s in self.sections:
|
|
25 self.sections[s] = []
|
|
26
|
234
|
27 def getLabelAddress(self, l):
|
|
28 assert isinstance(l, Label)
|
|
29 for s in self.sections.values():
|
|
30 for i in s:
|
|
31 if type(i) is Label:
|
|
32 if i.name == l.name:
|
|
33 return i.address
|
|
34 return 0
|
|
35
|
208
|
36 def backpatch(self):
|
|
37 """ Fixup references to other parts in the assembler """
|
|
38 for s in self.sections:
|
|
39 # TODO parameterize this:
|
|
40 if s == 'code':
|
|
41 address = 0x08000000
|
|
42 elif s == 'data':
|
|
43 address = 0x02000000
|
|
44 else:
|
|
45 address = 0x0
|
|
46 for i in self.sections[s]:
|
|
47 i.address = address
|
234
|
48 i.resolve(self.getLabelAddress)
|
208
|
49 bts = i.encode()
|
|
50 address += len(bts)
|
|
51
|
|
52 def dump(self):
|
|
53 self.backpatch()
|
|
54 for s in sorted(self.sections.keys()):
|
|
55 self.dumpSection(s)
|
|
56
|
|
57 def dumpSection(self, s):
|
|
58 print('.section '+s)
|
|
59 for i in self.sections[s]:
|
234
|
60 addr = i.address
|
|
61 insword = i.encode()
|
|
62 assert type(insword) is bytes
|
|
63 insword = binascii.hexlify(bytes(reversed(insword))).decode('ascii')
|
|
64 asm = str(i)
|
|
65 print(' 0x{0:08x} 0x{1} {2}'.format(addr, insword, asm))
|
208
|
66
|
|
67 class TextOutputStream(OutputStream):
|
|
68 pass
|
|
69
|
|
70 class BinOutputStream(OutputStream):
|
|
71 def dump(self):
|
|
72 pass
|
|
73
|