348
|
1 import logging
|
208
|
2 import binascii
|
366
|
3 from .target import Instruction, Alignment
|
|
4 from .objectfile import ObjectFile
|
234
|
5
|
208
|
6 """
|
|
7 The output stream is a stream of instructions that can be output
|
|
8 to a file or binary or hexfile.
|
|
9 """
|
|
10
|
219
|
11
|
335
|
12 class OutputStream:
|
366
|
13 """ Interface to generator code with. """
|
237
|
14 def emit(self, item):
|
335
|
15 raise NotImplementedError('Abstract base class')
|
219
|
16
|
348
|
17 def select_section(self, sname):
|
335
|
18 raise NotImplementedError('Abstract base class')
|
234
|
19
|
208
|
20
|
335
|
21 class BinaryOutputStream(OutputStream):
|
|
22 """ Output stream that writes to object file """
|
|
23 def __init__(self, obj_file):
|
|
24 super().__init__()
|
|
25 self.obj_file = obj_file
|
208
|
26
|
335
|
27 def emit(self, item):
|
|
28 """ Encode instruction and add symbol and relocation information """
|
341
|
29 assert isinstance(item, Instruction), str(item) + str(type(item))
|
335
|
30 assert self.currentSection
|
|
31 section = self.currentSection
|
|
32 address = self.currentSection.Size
|
|
33 b = item.encode()
|
|
34 syms = item.symbols()
|
|
35 relocs = item.relocations()
|
|
36 section.add_data(b)
|
|
37 for sym in syms:
|
|
38 self.obj_file.add_symbol(sym, address, section.name)
|
|
39 for sym, typ in relocs:
|
|
40 self.obj_file.add_relocation(sym, address, typ, section.name)
|
|
41 # Special case for align, TODO do this different?
|
|
42 if type(item) is Alignment:
|
|
43 while section.Size % item.align != 0:
|
|
44 section.add_data(bytes([0]))
|
236
|
45
|
348
|
46 def select_section(self, sname):
|
335
|
47 self.currentSection = self.obj_file.get_section(sname)
|
337
|
48
|
|
49
|
|
50 class DummyOutputStream(OutputStream):
|
348
|
51 """ Stream that implements the bare minimum and does nothing """
|
337
|
52 def emit(self, item):
|
|
53 pass
|
|
54
|
348
|
55 def select_section(self, sname):
|
337
|
56 pass
|
348
|
57
|
|
58
|
|
59 class LoggerOutputStream(OutputStream):
|
|
60 """ Stream that emits instructions as text in the log """
|
|
61 def __init__(self):
|
|
62 self.logger = logging.getLogger('LoggerOutputStream')
|
|
63
|
|
64 def emit(self, item):
|
|
65 self.logger.debug(str(item))
|
|
66
|
|
67 def select_section(self, sname):
|
|
68 self.logger.debug('.section {}'.format(sname))
|
|
69
|
|
70
|
|
71 class MasterOutputStream(OutputStream):
|
|
72 """ Stream that emits to multiple sub streams """
|
366
|
73 def __init__(self, substreams=[]):
|
|
74 self.substreams = list(substreams) # Use copy constructor!!!
|
348
|
75
|
|
76 def add_substream(self, output_stream):
|
|
77 self.substreams.append(output_stream)
|
|
78
|
|
79 def emit(self, item):
|
|
80 for output_stream in self.substreams:
|
|
81 output_stream.emit(item)
|
|
82
|
|
83 def select_section(self, sname):
|
|
84 for output_stream in self.substreams:
|
|
85 output_stream.select_section(sname)
|