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