208
|
1 import binascii
|
249
|
2 from target import Instruction, Label, DebugInfo
|
234
|
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
|
237
|
10 class Section:
|
|
11 def __init__(self):
|
250
|
12 self.address = 0
|
237
|
13 self.instructions = []
|
|
14
|
|
15 def emit(self, item):
|
|
16 assert isinstance(item, Instruction)
|
|
17 self.instructions.append(item)
|
|
18
|
|
19 def to_bytes(self):
|
|
20 d = bytearray()
|
|
21 for i in self.instructions:
|
|
22 addr = i.address
|
|
23 insword = i.encode()
|
|
24 assert type(insword) is bytes
|
|
25 d.extend(insword)
|
|
26 return bytes(d)
|
|
27
|
249
|
28 def debugInfos(self):
|
|
29 di = [i for i in self.instructions if isinstance(i, DebugInfo)]
|
|
30 return di
|
|
31
|
208
|
32 class OutputStream:
|
|
33 def __init__(self):
|
|
34 self.sections = {}
|
|
35 self.currentSection = None
|
225
|
36
|
208
|
37 def emit(self, item):
|
237
|
38 assert self.currentSection
|
250
|
39 self.currentSection.emit(item)
|
219
|
40
|
250
|
41 def selectSection(self, sname):
|
|
42 self.currentSection = self.getSection(sname)
|
208
|
43
|
235
|
44 def getLabelAddress(self, lname):
|
|
45 assert isinstance(lname, str)
|
234
|
46 for s in self.sections.values():
|
237
|
47 for i in s.instructions:
|
234
|
48 if type(i) is Label:
|
235
|
49 if i.name == lname:
|
234
|
50 return i.address
|
|
51 return 0
|
|
52
|
249
|
53 def getSection(self, name):
|
|
54 if not name in self.sections:
|
|
55 self.sections[name] = Section()
|
|
56 return self.sections[name]
|
|
57
|
208
|
58 def backpatch(self):
|
|
59 """ Fixup references to other parts in the assembler """
|
250
|
60 for s in self.sections.values():
|
|
61 address = s.address
|
|
62 for i in s.instructions:
|
208
|
63 i.address = address
|
234
|
64 i.resolve(self.getLabelAddress)
|
208
|
65 bts = i.encode()
|
|
66 address += len(bts)
|
|
67
|
|
68 def dump(self):
|
|
69 self.backpatch()
|
236
|
70 self.backpatch()
|
208
|
71 for s in sorted(self.sections.keys()):
|
|
72 self.dumpSection(s)
|
|
73
|
|
74 def dumpSection(self, s):
|
237
|
75 print('.section '+ s)
|
|
76 for i in self.sections[s].instructions:
|
234
|
77 addr = i.address
|
|
78 insword = i.encode()
|
|
79 assert type(insword) is bytes
|
|
80 insword = binascii.hexlify(bytes(reversed(insword))).decode('ascii')
|
|
81 asm = str(i)
|
235
|
82 if len(insword) == 0:
|
|
83 print(' {}'.format(asm))
|
|
84 else:
|
|
85 print(' 0x{0:08x} 0x{1} {2}'.format(addr, insword, asm))
|
208
|
86
|
|
87 class TextOutputStream(OutputStream):
|
|
88 pass
|
|
89
|
|
90 class BinOutputStream(OutputStream):
|
|
91
|
236
|
92 @property
|
|
93 def Data(self):
|
|
94 d = self.dump()
|
|
95 return bytes(d)
|
|
96
|
|
97 def dump(self):
|
|
98 self.backpatch()
|
|
99 self.backpatch()
|
237
|
100 section = self.sections[list(self.sections.keys())[0]]
|
|
101 return section.to_bytes()
|
236
|
102
|
|
103
|