-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmicroprocessor_simulator.py
327 lines (306 loc) · 14.2 KB
/
microprocessor_simulator.py
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
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
import re
import time
from utils import (FORMAT_1_OPCODE, FORMAT_2_OPCODE, FORMAT_3_OPCODE, OPCODE,
REGISTER, clear_registers, convert_to_hex, hex_to_binary, RAM, load_ram, is_valid_file, clear_ram)
def get_opcode_key(val):
"""
Gets the opcode for the given value
"""
for key, value in OPCODE.items():
if val == value:
return key
return None
class MicroSim:
"""Microprocessor simulator"""
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.is_ram_loaded = False
self.decoded_micro_instructions = []
self.program_counter = 0
self.is_running = False
self.prev_program_counter = -1
self.counter = 0
self.filename = ''
self.error = ''
def read_obj_file(self, filename):
"""
Reads obj file and stores content in RAM
:param filename: str
"""
is_valid, file_ext = is_valid_file(filename)
if not is_valid and file_ext != 'obj':
raise AssertionError(
f"Unsupported file '{filename}'. "
f"Microprocesor simulator files must be of type 'obj'")
self.filename = filename
file = open(filename, 'r')
lines = file.readlines()
load_ram(lines)
self.is_ram_loaded = True
lines.clear()
file.close()
def disassembled_instruction(self):
"""Disassembles executed assembly instruction"""
instruction = hex_to_binary(
f'{RAM[self.program_counter]}{RAM[self.program_counter + 1]}')
opcode = get_opcode_key(instruction[0:5])
if opcode in FORMAT_1_OPCODE:
register_a = f'R{int(instruction[5:8], 2)}'
register_b = f'R{int(instruction[8:11], 2)}'
register_c = f'R{int(instruction[11:14], 2)}'
if opcode == 'nop':
dis_instruction = f'{opcode}'
elif opcode == 'jmprind':
dis_instruction = f'{opcode} {register_a}'
elif opcode in ('loadrind', 'storerind', 'not', 'neg', 'grt', 'grteq', 'eq', 'neq'):
dis_instruction = f'{opcode} {register_a}, {register_b}'
else:
dis_instruction = f'{opcode} {register_a}, {register_b}, {register_c}'
elif opcode in FORMAT_2_OPCODE:
register_a = f'R{int(instruction[5:8], 2)}'
address_or_const = f'{int(instruction[8:], 2):02x}'
if opcode in ('pop', 'push'):
dis_instruction = f'{opcode} {register_a}'
elif opcode in ('loadim', 'addim', 'subim'):
dis_instruction = f'{opcode} {register_a}, #{address_or_const}'
elif opcode == 'store':
dis_instruction = f'{opcode} {address_or_const}, {register_a}'
else:
dis_instruction = f'{opcode} {register_a}, {address_or_const}'
elif opcode in FORMAT_3_OPCODE:
register_a = f'R{int(instruction[5:8], 2)}'
address = f'{int(instruction[5:], 2):02x}'
if opcode == 'jcondrin':
dis_instruction = f'{opcode} {register_a}'
else:
dis_instruction = f'{opcode} {address}'
else:
dis_instruction = f'{opcode}'
return dis_instruction.upper()
def run_micro_instructions(self, timeout=0):
"""
Runs assembly instructions
:param timeout: int
"""
if timeout != 0 and time.time() > timeout:
self.is_running = False
raise TimeoutError('Infinite loop detected.')
if self.program_counter % 2 != 0:
self.program_counter -= 1
raise SystemError('Invalid PC value')
REGISTER['ir'] = f'{RAM[self.program_counter]}{RAM[self.program_counter + 1]}'
binary_instruction = hex_to_binary(
f'{RAM[self.program_counter]}{RAM[self.program_counter + 1]}')
self.execute_instruction(binary_instruction)
if self.prev_program_counter == self.program_counter:
self.is_running = False
else:
self.prev_program_counter = self.program_counter
def micro_clear(self):
"""
Resets microprocessor simulator to initial conditions
"""
self.is_ram_loaded = False
self.decoded_micro_instructions = []
self.program_counter = 0
self.is_running = False
self.prev_program_counter = -1
self.counter = 0
clear_ram()
clear_registers()
def execute_instruction(self, instruction):
"""
Executes assembly instruction
:param instruction: str
"""
if re.match('^[0]+$', instruction):
self.prev_program_counter = self.program_counter
self.program_counter += 2
if self.program_counter < 4096:
REGISTER['pc'] = convert_to_hex(self.program_counter, 3)
else:
self.program_counter = self.prev_program_counter
else:
opcode = get_opcode_key(instruction[0:5])
if opcode in FORMAT_1_OPCODE:
register_a = f'r{int(instruction[5:8], 2)}'
register_b = f'r{int(instruction[8:11], 2)}'
register_c = f'r{int(instruction[11:14], 2)}'
if opcode == 'loadrind':
REGISTER[register_a] = RAM[int(REGISTER[register_b], 16)]
elif opcode == 'storerind':
RAM[int(REGISTER[register_a], 16)] = REGISTER[register_b]
elif opcode == 'grt':
_grt = int(REGISTER[register_a], 16) > int(
REGISTER[register_b], 16)
REGISTER['cond'] = convert_to_hex(_grt, 4)
elif opcode == 'add':
_add = int(REGISTER[register_b], 16) + \
int(REGISTER[register_c], 16)
REGISTER[register_a] = convert_to_hex(_add, 8)
elif opcode == 'sub':
_sub = int(REGISTER[register_b], 16) - \
int(REGISTER[register_c], 16)
REGISTER[register_a] = convert_to_hex(_sub, 8)
elif opcode == 'and':
_and = int(REGISTER[register_b], 16) & int(
REGISTER[register_c], 16)
REGISTER[register_a] = convert_to_hex(_and, 8)
elif opcode == 'or':
_or = int(REGISTER[register_b], 16) | int(REGISTER[register_c], 16)
REGISTER[register_a] = convert_to_hex(_or, 8)
elif opcode == 'xor':
_xor = int(REGISTER[register_b]) ^ int(
REGISTER[register_c])
REGISTER[register_a] = convert_to_hex(_xor, 8)
elif opcode == 'not':
_not = self.bit_not(int(REGISTER[register_b], 16)) + 1
REGISTER[register_a] = convert_to_hex(_not, 8)
elif opcode == 'neg':
_neg = self.bit_not(int(REGISTER[register_b], 16))
REGISTER[register_a] = convert_to_hex(_neg, 8)
elif opcode == 'shiftr':
_shiftr = int(REGISTER[register_b], 16) >> int(
REGISTER[register_c], 16)
REGISTER[register_a] = convert_to_hex(_shiftr, 8)
elif opcode == 'shiftl':
_shiftl = int(REGISTER[register_b], 16) << int(
REGISTER[register_c], 16)
REGISTER[register_a] = convert_to_hex(_shiftl, 8)
elif opcode == 'rotar':
_rotar = self.rotr(int(REGISTER[register_b], 16), int(
REGISTER[register_c], 16))
REGISTER[register_a] = convert_to_hex(_rotar, 8)
elif opcode == 'rotal':
_rotl = self.rotl(int(REGISTER[register_b], 16), int(
REGISTER[register_c], 16))
REGISTER[register_a] = convert_to_hex(_rotl, 8)
elif opcode == 'jmprind':
self.program_counter = int(REGISTER[register_a], 16) - 2
REGISTER['pc'] = f'{self.program_counter:03x}'
elif opcode == 'grteq':
REGISTER['cond'] = str(int(int(REGISTER[register_a], 16) >= int(
REGISTER[register_b], 16)))
elif opcode == 'eq':
REGISTER['cond'] = str(int(int(REGISTER[register_a], 16) == int(
REGISTER[register_b], 16)))
elif opcode == 'neq':
REGISTER['cond'] = str(int(int(REGISTER[register_a], 16) != int(
REGISTER[register_b], 16)))
self.program_counter += 2
REGISTER['pc'] = convert_to_hex(self.program_counter, 12)
elif opcode in FORMAT_2_OPCODE:
register_a = f'r{int(instruction[5:8], 2)}'
address_or_const = int(instruction[8:], 2)
if opcode == 'load':
REGISTER[register_a] = convert_to_hex(
int(RAM[address_or_const], 16), 8)
elif opcode == 'loadim':
REGISTER[register_a] = convert_to_hex(address_or_const, 8)
elif opcode == 'store':
RAM[address_or_const] = REGISTER[register_a]
elif opcode == 'addim':
_addim = int(REGISTER[register_a], 16) + address_or_const
REGISTER[register_a] = convert_to_hex(_addim, 8)
elif opcode == 'subim':
_subim = int(REGISTER[register_a], 16) - address_or_const
REGISTER[register_a] = convert_to_hex(_subim, 8)
elif opcode == 'pop':
stack_pointer = int(REGISTER['sp'], 16)
REGISTER[register_a] = RAM[stack_pointer]
stack_pointer += 1
if stack_pointer >= len(RAM):
stack_pointer -= len(RAM)
REGISTER['sp'] = convert_to_hex(stack_pointer, 12)
REGISTER['r7'] = convert_to_hex(int(REGISTER['sp'], 16), 8)
elif opcode == 'push':
stack_pointer = int(REGISTER['sp'], 16) - 1
if stack_pointer < 0:
stack_pointer += len(RAM)
REGISTER['sp'] = convert_to_hex(stack_pointer, 12)
REGISTER['r7'] = convert_to_hex(int(REGISTER['sp'], 16), 8)
RAM[stack_pointer] = REGISTER[register_a]
elif opcode == 'loop':
reg_ra = int(REGISTER[register_a], 16) - 1
if reg_ra < 0:
reg_ra = 0
REGISTER[register_a] = convert_to_hex(reg_ra, 8)
if reg_ra != 0:
self.program_counter = address_or_const - 2
self.prev_program_counter = self.program_counter - 2
REGISTER['pc'] = convert_to_hex(
self.program_counter, 12)
self.program_counter += 2
REGISTER['pc'] = convert_to_hex(
int(REGISTER['pc'], 16) + 2, 12)
elif opcode in FORMAT_3_OPCODE:
register_a = f'r{int(instruction[5:8], 2)}'
address = int(instruction[5:], 2)
if opcode == 'jmpaddr':
self.program_counter = address
REGISTER['pc'] = convert_to_hex(address, 12)
elif opcode == 'jcondrin':
REGISTER['pc'] = REGISTER[register_a] if int(REGISTER['cond']) else convert_to_hex(
int(REGISTER['pc'], 16) + 2,
12)
self.program_counter = int(REGISTER['pc'], 16)
elif opcode == 'jcondaddr':
REGISTER['pc'] = convert_to_hex(address, 12) if int(REGISTER['cond']) \
else convert_to_hex(int(REGISTER['pc'], 16) + 2, 12)
self.program_counter = int(REGISTER['pc'], 16)
elif opcode == 'call':
stack_pointer = int(REGISTER['sp'], 16) - 2
if stack_pointer < 0:
stack_pointer += len(RAM)
RAM[stack_pointer] = f'0{REGISTER["pc"][0]}'
RAM[stack_pointer + 1] = REGISTER["pc"][1:]
REGISTER['sp'] = convert_to_hex(stack_pointer, 12)
REGISTER['r7'] = convert_to_hex(int(REGISTER['sp'], 16), 8)
REGISTER['pc'] = convert_to_hex(address, 12)
self.program_counter = address
elif opcode == 'return':
stack_pointer = int(REGISTER['sp'], 16)
self.program_counter = int(
RAM[stack_pointer][1], 16) + int(RAM[stack_pointer + 1], 16) + 2
REGISTER['pc'] = convert_to_hex(self.program_counter, 12)
stack_pointer += 2
if stack_pointer >= len(RAM):
stack_pointer -= len(RAM)
REGISTER['sp'] = convert_to_hex(stack_pointer, 12)
REGISTER['r7'] = convert_to_hex(int(REGISTER['sp'], 16), 8)
if REGISTER['r0'] != '00':
raise SystemError('R0 cannot be modified')
REGISTER['sp'] = convert_to_hex(int(REGISTER['r7'], 16), 12)
if (int(REGISTER['r7'], 16) > 255):
REGISTER['r7'] = convert_to_hex(int(REGISTER['r7'], 16) & 255, 8)
def bit_not(self, num, bits=8):
"""
1's complementing a binary number up to the given amount of bits
:param num: int
:param bits: int
"""
return (1 << bits) - 1 - num
def rotl(self, num, bits):
"""
Rotates bits to the left
:param num: int
:param bits: int
"""
bit = num & (1 << (bits - 1))
num <<= 1
if bit:
num |= 1
num &= (2 << bits - 1)
return num
def rotr(self, num, bits):
"""
Rotates bits to the right
:param num: int
:param bits: int
"""
num &= (2 << bits - 1)
bit = num & 1
num >>= 1
if bit:
num |= (1 << (bits - 1))
return num