-
Notifications
You must be signed in to change notification settings - Fork 0
/
computer.py
322 lines (207 loc) · 7 KB
/
computer.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
# ========================================================================================
#
# Description:
#
# Computer for the Intel 8080 Emulator
#
# Supports debugging (step and breakpoint)
#
# Attribution:
#
# Code by www.jk-quantized.com
#
# Redistribution and use of this code in source and binary forms must retain
# the above attribution notice and this condition.
#
# ========================================================================================
from cpu_8080 import *
from memory import *
from terminal import *
from assembler import compile_
from disassembler import instructionLookup, instructionsWithData
from time import sleep
import sys
from shutil import copyfile
class Computer ():
def __init__ ( self, memorySize ):
self.memory = [ 0 ] * memorySize
self.CPU = CPU( self.memory )
self.terminal = Terminal()
self.CPU.ioDevices.append( self.terminal )
# Debug helpers ---
self.printHowTo = True
self.dumpFolderPath = None
self.breakpoint = None
self.breakpointReached = False
self.prevInstruction = None
self.prevPC = None
self.nextInstruction = None
self.nextPC = None
self.curStep = 0
self.nStepsSaved = - 1
self.stackBase = None
def loadProgram ( self, programPath, isAssembly=True ):
if isAssembly:
compile_( programPath, self.memory )
else:
with open( programPath, 'rb' ) as file:
idx = 0
byte = file.read( 1 )
while byte:
# print( byte )
self.memory[ idx ] = int.from_bytes( byte, byteorder='big' )
idx += 1
byte = file.read( 1 )
def run ( self, step=False ):
cpuThreadTarget = self.CPU.run
if step: cpuThreadTarget = self.run_debugMode
tkThread = threading.Thread(
target = self.terminal.setupTkinter,
name = 'tk_thread'
)
cpuThread = threading.Thread(
# target = self.CPU.run,
target = cpuThreadTarget,
name = 'cpu_thread',
daemon = True # so that closing tk also closes cpu
)
tkThread.start()
sleep( 0.1 ) # wait for tk to setup
cpuThread.start()
tkThread.join() # wait for tk to be closed
self.onStop()
def onStop ( self ):
print( 'See you later!' )
# self.dumpStatus() # debug
def printDebuggerHelp ( self ):
print( '\n---' )
print( 'The debugger dumps the status of the CPU and memory' )
print( 'following execution of an instruction.' )
print( 'The dump of the current instruction can be found' )
print( 'at dumpFolderPath/tmp. Ideally you will have this' )
print( 'file open as you step through the program to view' )
print( 'the current status.' )
print()
print( 'To step through the program, type:' )
print( ' n -> next' )
print( ' p -> previous' )
print( ' quit -> quit' )
print( ' help -> help' )
print()
def run_debugMode ( self ):
self.dumpStatusToFiles()
while True:
if ( self.breakpoint and ( not self.breakpointReached ) ):
# Auto step ---
self.curStep += 1
if self.curStep > self.nStepsSaved:
self.CPU.step()
self.dumpStatusToFiles()
print( self.curStep )
if ( self.nextPC == self.breakpoint ) or self.CPU.halt:
self.breakpointReached = True
else:
# Manual step ---
if self.printHowTo:
self.printDebuggerHelp()
self.printHowTo = False
uinput = input( '> ' )
if uinput == 'n':
self.curStep += 1
if self.curStep > self.nStepsSaved:
self.CPU.step()
self.dumpStatusToFiles()
print( self.curStep )
elif uinput == 'p':
self.curStep -= 1
if self.curStep < 0: self.curStep = 0
self.dumpStatusToFiles()
print( self.curStep )
elif uinput == '?' or uinput == 'help':
self.printDebuggerHelp()
elif uinput == 'quit':
break
def dumpStatusToFiles ( self ):
if self.curStep > self.nStepsSaved:
# print( 'creating new file' )
#
self.nextPC = self.CPU.register_PC.read()
self.nextInstruction = instructionLookup[ self.CPU.read_M( self.nextPC ) ]
# display
filePath = self.dumpFolderPath + 'tmp'
self.dumpStatusToFile( filePath )
# store
filePath = self.dumpFolderPath + str( self.curStep )
self.dumpStatusToFile( filePath )
self.nStepsSaved += 1
#
self.prevPC = self.nextPC
self.prevInstruction = self.nextInstruction
else:
# print( 'reading old file' )
# display stored
src = self.dumpFolderPath + str( self.curStep )
dst = self.dumpFolderPath + 'tmp'
copyfile( src, dst )
def dumpStatusToFile ( self, filePath ):
sys.stdout = open( filePath, 'w' ) # redirect stdout
self.dumpStatus()
sys.stdout = sys.__stdout__ # restore stdout
def dumpStatus ( self ):
print( '\nMemory ---' )
self.dumpMemory()
if self.stackBase:
print( '\nStack ---' )
self.dumpMemory( self.CPU.register_SP.read(), self.stackBase )
elif self.CPU.register_SP.read() > 0:
self.stackBase = self.CPU.register_SP.read()
print( '\nRegisters ---' )
print( 'A :', self.CPU.register_AF.readUpperByte() )
print( 'B :', self.CPU.register_BC.readUpperByte() )
print( 'C :', self.CPU.register_BC.readLowerByte() )
print( 'BC :', self.CPU.register_BC.read() )
print( 'D :', self.CPU.register_DE.readUpperByte() )
print( 'E :', self.CPU.register_DE.readLowerByte() )
print( 'DE :', self.CPU.register_DE.read() )
print( 'H :', self.CPU.register_HL.readUpperByte() )
print( 'L :', self.CPU.register_HL.readLowerByte() )
print( 'HL :', self.CPU.register_HL.read() )
print( 'SP :', self.CPU.register_SP.read() )
print( '\nFlags ---' )
f = self.CPU.register_AF.readLowerByte()
f = bin( f )[ 2 : ].zfill( 8 )
f = f[ : : - 1 ]
print( 'carry :', self.CPU.flagALU_carry , f[ 0 ] )
print( 'parity :', self.CPU.flagALU_parity, f[ 2 ] )
print( 'zero :', self.CPU.flagALU_zero , f[ 6 ] )
print( 'sign :', self.CPU.flagALU_sign , f[ 7 ] )
print( '\nInstruction ---' )
if self.prevInstruction in instructionsWithData:
print( 'instruction :', self.prevInstruction )
nBytes = instructionsWithData[ self.prevInstruction ]
for i in range( nBytes ):
print( 'data :', self.CPU.read_M( self.prevPC + 1 + i ) )
else:
print( 'instruction :', instructionLookup[ self.CPU.instruction ] ) # disassemble
# self.nextPC = self.CPU.register_PC.read()
# self.nextInstruction = instructionLookup[ self.CPU.read_M( self.nextPC ) ]
print( 'PC_next :', self.nextPC )
print( 'instruction_next :', self.nextInstruction )
# self.prevPC = self.nextPC
# self.prevInstruction = self.nextInstruction
def dumpMemory ( self, start=None, end=None ):
if start and end:
range_ = range( start, end + 1 )
else:
range_ = range( len( self.memory ) )
for i in range_:
r = self.memory[ i ]
b = bin( r )[ 2 : ].zfill( 8 )
# b = '{:08b}'.format( r )
if r < 0:
raise Exception( 'wtf', i, r ) # should never happen
elif r > 0:
c = None
if r < 128: c = chr( r )
# print( '{:4x} {:5} | {:08b} {:5} {}'.format( i, i, r, r, c ) )
print( '{:4x} {:5} | {:08b} {:5} {}'.format( i, i, r, r, str( c ).encode( 'utf-8' ) ) )