-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgassembler
executable file
·261 lines (216 loc) · 7.5 KB
/
gassembler
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
#!/usr/bin/env python3
import sys, os, argparse
info = """Description:
EE560 GPU ISA Assembler (derived from MIPS32)
Author: Chang Xu ([email protected])
Date: 01/10/2020
"""
InputParser = argparse.ArgumentParser(description=info, formatter_class=argparse.RawDescriptionHelpFormatter)
InputParser.add_argument("inputfile", help= "path of the input assembly file", type=str)
InputParser.add_argument("-v", "--verbose", help="verbose", action="store_true")
InputParser.add_argument("-x", help="output in bin(default)/hex", action="store_true")
InputParser.add_argument("-o", metavar='outfile', help="path of the output binary file", type=str)
options = InputParser.parse_args()
def errorExit(msg:str, errno:int):
print("Error: " + msg)
exit(errno)
def vprint(msg:str):
global options
if options.verbose:
print(msg)
instList: list = []
labelDict: dict = {}
InstDict = {
# R-type: (type, opcode, funct)
"ADD": (0, 0b000000, 0b100000),
"SUB": (0, 0b000000, 0b100010),
"MULT": (0, 0b000000, 0b011000),
"AND": (0, 0b000000, 0b100100),
"OR": (0, 0b000000, 0b100101),
"XOR": (0, 0b000000, 0b100110),
"SHR": (0, 0b000000, 0b000010),
"SHL": (0, 0b000000, 0b000000),
# "DIV": (0, 0b000000, 0b011010),
# I-type: (type, opcode)
"ADDI": (1, 0b001000),
"ANDI": (1, 0b001100),
"ORI": (1, 0b001101),
"XORI": (1, 0b001110),
# LW/ST
"LW": (2, 0b100011),
"LWS": (2, 0b100111),
"SW": (2, 0b101011),
"SWS": (2, 0b101111),
# BEQ/BLT
"BEQ": (3, 0b000100),
"BLT": (3, 0b000111),
# Jump/CALL
"J": (4, 0b000010),
"CALL": (4, 0b000011),
# RET
"RET": (5, 0b000110),
"NOOP": (5, 0b000001),
"EXIT": (5, 0b100001)
# TODO: NOOP same funct
}
def rTypeParser(raw_instruction: str)-> (bool, int):
op, _, operands = raw_instruction.partition(' ')
ret = InstDict[op.partition('.')[0]][2] # funct
operands = operands.partition('$')[2]
reg = operands.partition(',')[0].strip()
if not reg:
return False, 0
ret += int(reg) << 11
vprint("rd: " + reg)
operands = operands.partition('$')[2]
reg = operands.partition(',')[0].strip()
if not reg:
return False, 0
ret += int(reg) << 21
vprint("rs: " + reg)
reg = operands.partition('$')[2].strip()
if not reg:
return False, 0
ret += int(reg) << 16
vprint("rt: " + reg)
return True, ret
def iTypeParser(raw_instruction: str)-> (bool, int):
operands = raw_instruction.partition('$')[2]
reg = operands.partition(',')[0].strip()
if not reg:
return False, 0
ret = int(reg) << 16
vprint("rt: " + reg)
operands = operands.partition('$')[2]
reg = operands.partition(',')[0].strip()
if not reg:
return False, 0
ret += int(reg) << 21
vprint("rs: " + reg)
imme = operands.partition(',')[2].strip()
if not operands:
return False, 0
ret += int(imme) & 0xFFFF
vprint("imme: " + imme)
return True, ret
def lsParser(raw_instruction: str)-> (bool, int):
operands = raw_instruction.partition('$')[2]
reg = operands.partition(',')[0].strip()
if not reg:
return False, 0
ret = int(reg) << 16
vprint("rt: " + reg)
imme = operands.partition(',')[2].partition('(')[0].strip()
if not imme:
return False, 0
ret += int(imme) & 0xFFFF
vprint("imme: " + imme)
reg = operands.partition('$')[2].partition(')')[0].strip()
if not reg:
return False, 0
ret += int(reg) << 21
vprint("rs: " + reg)
return True, ret
def brParser(raw_instruction: str)-> (bool, int):
operands = raw_instruction.partition('$')[2]
reg = operands.partition(',')[0].strip()
if not reg:
return False, 0
ret = int(reg) << 21
vprint("rs: " + reg)
operands = operands.partition('$')[2]
reg = operands.partition(',')[0].strip()
if not reg:
return False, 0
ret += int(reg) << 16
vprint("rt: " + reg)
label = operands.partition(',')[2].strip()
if label not in labelDict:
errorExit('label ' + label + ' is invalid', -2)
return False, 0
ret += labelDict[label] & 0xFFFF
vprint("Label: " + label)
return True, ret
def jParser(raw_instruction: str)-> (bool, int):
tokens = raw_instruction.split()
if not len(tokens) == 2:
return False, 0
if not tokens[1] in labelDict:
errorExit('label ' + tokens[1] + ' is invalid', -2)
return False, 0
ret = labelDict[tokens[1]]
vprint("Label: " + tokens[1])
return True, ret
def retParser(raw_instruction: str)-> (bool, int):
ret = 0b000000 #basically do nothing
return True, ret
ParserList = [
rTypeParser,
iTypeParser,
lsParser,
brParser,
jParser,
retParser
]
def parseSingleInst(raw_instruction: str)-> str:
global options
vprint(raw_instruction)
OP = raw_instruction.partition(' ')[0]
# dotS support
OP, dotS, operands= OP.partition('.')
if OP not in InstDict:
errorExit("Invalid instruction: " + raw_instruction, -2)
ind, opcode = InstDict[OP][0:2]
ret, inst = ParserList[ind](raw_instruction)
if not ret:
errorExit("Invalid instruction: " + raw_instruction, -2)
inst += opcode << 26
if dotS:
if operands[0] != 'S' and operands[0] != 's':
errorExit("Invalid instruction: " + raw_instruction, -2)
inst += (1 << 30)
instParsed = '{:08x}'.format(inst) if options.x else '{:032b}'.format(inst)
print(instParsed)
return instParsed
def main():
# processing args
global instList, labelDict, options
filename = options.inputfile
if not os.path.isfile(filename):
errorExit(filename + " is not a valid file!", -1)
# read input
with open(filename, "r") as fileobj:
for line in fileobj.read().splitlines():
head = line.partition(';')[0]
head = head.strip()
if not head:
continue
if ':' not in head:
instList.append(head)
else:
label, _, inst = head.partition(':')
assert label and (label not in labelDict) and "Duplicate Labels!"
labelDict[label] = len(instList)
inst = inst.strip()
if inst:
instList.append(inst)
# verbose informations
if options.verbose:
print("\n------------ Recognized Instructions: ------------\n")
for i,inst in enumerate(instList):
print('{:>3x}'.format(i) + ' : {:>3d}'.format(i) + " " + inst)
print("\n--------------- Recognized Labels: ---------------\n")
for key,value in labelDict.items():
print('{:>3x}'.format(value) + ' : {:>3d}'.format(value) + " " + key + ": " + instList[value])
# parsing
vprint("\n-------------- Parsing Instructions --------------\n")
if options.o:
with open(options.o, "w") as outfileobj:
for inst in instList:
outfileobj.write(parseSingleInst(inst) + "\n")
else:
for inst in instList:
parseSingleInst(inst)
vprint("\n---------------- Parsing Finished ----------------\n")
if __name__ == "__main__":
main()