-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathComputerSimulator.py
More file actions
1172 lines (1088 loc) · 47.2 KB
/
ComputerSimulator.py
File metadata and controls
1172 lines (1088 loc) · 47.2 KB
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
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
# ComputerSimulator.py
# By: Shawn Silva (ssilva at jatgam dot com)
# Jatgam Computer Simulator
#
# Simulates the CPU, Memory, Disk, and OS of a computer allowing you to create
# and run simple assembly programs.
# -----------------------------------------------------------------------------
#
# REQUIREMENTS:
# Python 3.7.x
#
# Copyright (C) 2012-2019 Jatgam Technical Solutions
# ----------------------------------------------
# This file is part of Jatgam Computer Simulator.
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
import argparse
import logging
import os
from pathlib import Path
import sys
import math
from tkinter import filedialog
from tkinter import Tk
from computersimulator.hardware.SimulatedCPU import SimulatedCPU
import computersimulator.utils.listutils as listutils
import computersimulator.constants as constants
CONST = constants.Constants
class ComputerSimulator:
osFreeList = CONST.EOL # OS Free Mem List
userFreeList = CONST.EOL # User Free Mem List
pid = 0 # Process ID
RQptr = CONST.EOL # Ready Queue Pointer
WQptr = CONST.EOL # waiting queue pointer
RunningPCBptr = CONST.EOL # Whats currently Running
memoryLists = {"osFreeList": {"start": 7000, "size": 3000},
"userFreeList": {"start": 3000, "size": 4000}}
def __init__(self):
self.logger = logging.getLogger(self.__class__.__name__)
self.scpu = SimulatedCPU()
def initializeSystem(self):
"""Sets all hardware variables to zero. Initializes the user and OS
free lists."""
self.scpu.sp = 0
self.scpu.pc = 0
self.scpu.ir = 0
self.scpu.psr = CONST.OSMODE
self.scpu.clock = 0
for curgpr in range(len(self.scpu.gpr)):
self.scpu.gpr[curgpr] = 0
for mempos in range(len(self.scpu.sram.ram)):
self.scpu.sram.ram[mempos] = 0
self._checkDisk()
# Initialize Memory Lists
for key, value in self.memoryLists.items():
vars(self)[key] = value["start"]
self.scpu.sram.ram[value["start"]] = CONST.EOL
self.scpu.sram.ram[value["start"] + 1] = value["size"]
def _checkDisk(self):
if (self.scpu.sdisk.disk[0] == [0]*self.scpu.sdisk.sectorSize):
#Disk Not Formatted!
print("Disk not formatted, proceeding with format.")
self._formatDisk()
elif (listutils.numJoin(self.scpu.sdisk.disk[0][0:2]) != CONST.PARTITION_TYPE):
print("Unsupported File System! Quitting!")
sys.exit()
else:
return True
def _formatDisk(self):
"""
Writes the MBR and creates a partition on disk.
Also, loads the OS boot code. In this case, and Idle process.
"""
idle = [0x0, 0x60000, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, 0x0, -1]
part1size = self.scpu.sdisk.numSectors-1
part1fatStart = int(part1size/2)
part1bitmapsize = math.ceil(part1size/self.scpu.sdisk.sectorSize)
#Creating the MBR
self.scpu.sdisk.disk[0][0:2] = listutils.numSplit(CONST.PARTITION_TYPE)
self.scpu.sdisk.disk[0][2:8] = listutils.numSplit(format(1, "06d"))
self.scpu.sdisk.disk[0][8:14] = listutils.numSplit(
format(part1size, "06d"))
#Creating First Sector of Partition
self.scpu.sdisk.disk[1][0:6] = listutils.numSplit(
format(part1fatStart, "06d"))
self.scpu.sdisk.disk[1][6:12] = listutils.numSplit(
format(CONST.FAT_SIZE, "06d"))
self.scpu.sdisk.disk[1][12:18] = listutils.numSplit(format(2, "06d"))
self.scpu.sdisk.disk[1][18:24] = listutils.numSplit(
format(part1bitmapsize, "06d"))
self.scpu.sdisk.disk[1][110:128] = list(idle)
#Initializing Sector Bitmap
slack = self.scpu.sdisk.sectorSize - \
(part1size % self.scpu.sdisk.sectorSize)
self.partBitmapUpdate(2, 8, part1size+1, slack, CONST.BTMP_INV)
self.partBitmapUpdate(2, 8, 1, 1, CONST.BTMP_SYS)
self.partBitmapUpdate(2, 8, 2, 8, CONST.BTMP_SYS)
self.partBitmapUpdate(2, 8, part1fatStart,
CONST.FAT_SIZE, CONST.BTMP_SYS)
def partBitmapUpdate(self, bitstart, bitsize, start, size, op):
"""Updates the bitmap and either marks free, used, or system."""
bstartsec = math.ceil(start/self.scpu.sdisk.sectorSize)-1
bendsec = math.ceil((start+size)/self.scpu.sdisk.sectorSize)-1
if (start <= self.scpu.sdisk.sectorSize):
if (bstartsec == bendsec):
if (start-1 == 0):
self.scpu.sdisk.disk[bitstart
+ bstartsec][start-1:size] = [op]*size
else:
self.scpu.sdisk.disk[bitstart
+ bstartsec][start-1:size+1] = [op]*size
else:
offset = start
newstart = self.scpu.sdisk.sectorSize+1
while (offset <= self.scpu.sdisk.sectorSize):
self.scpu.sdisk.disk[bitstart+bstartsec][offset-1] = op
offset += 1
size -= 1
self.partBitmapUpdate(bitstart, bitsize, newstart, size, op)
else:
offset = start % self.scpu.sdisk.sectorSize
if (bstartsec == bendsec):
if (offset-1 == 0):
self.scpu.sdisk.disk[bitstart
+ bstartsec][offset-1:size] = [op]*size
else:
self.scpu.sdisk.disk[bitstart
+ bstartsec][offset-1:size+1] = [op]*size
else:
newstart = (start+size)-((start+size) %
self.scpu.sdisk.sectorSize)+1
while (offset <= self.scpu.sdisk.sectorSize):
self.scpu.sdisk.disk[bitstart+bstartsec][offset-1] = op
offset += 1
size -= 1
self.partBitmapUpdate(bitstart, bitsize, newstart, size, op)
def systemCall(self, sysCallID):
"""
Takes the supplied sysCallID and performs the correct system call.
Prints out messages for what system call is performed and what process
asked for it.
"""
status = 0
self.scpu.psr = CONST.OSMODE
if (sysCallID == CONST.TASK_CREATE):
self.taskCreate()
print("-------------------------------")
print("System Call Recieved: task_create")
print("PID that issued: {}".format(self.scpu.sram.ram[self.RunningPCBptr+3]))
print("Input: Address of first Instruction: {}".format(self.scpu.gpr[3]))
print("Output: PID of Child: {}, Status: {}".format(self.scpu.gpr[2], self.scpu.gpr[0]))
print("-------------------------------")
elif (sysCallID == CONST.TASK_DELETE):
status = self.taskDelete()
print("-------------------------------")
print("System Call Recieved: task_delete")
print("PID that issued: {}".format(self.scpu.sram.ram[self.RunningPCBptr+3]))
print("Input: PID to delete: {}".format(self.scpu.gpr[1]))
print("Output: Status: {}".format(self.scpu.gpr[0]))
print("-------------------------------")
if (status == CONST.HALT):
self.scpu.psr = CONST.USERMODE
return CONST.HALT
elif (sysCallID == CONST.TASK_INQUIRY):
self.taskInquiry()
print("-------------------------------")
print("System Call Recieved: task_inquiry")
print("PID that issued: {}".format(self.scpu.sram.ram[self.RunningPCBptr+3]))
print("Output: PID: {}, Priority: {}, State: {}".format(self.scpu.gpr[1], self.scpu.gpr[2], self.scpu.gpr[3]))
print("-------------------------------")
elif (sysCallID == CONST.MEM_ALLOC): # Mem Alloc System Call
status = self.mem_alloc(self.scpu.gpr[2]) # Allocate memory with size GPR2
print("-------------------------------")
print("System Call Recieved: mem_alloc")
print("PID that issued: {}".format(self.scpu.sram.ram[self.RunningPCBptr+3]))
print("Input: Size: {}".format(self.scpu.gpr[2]))
print("Output: Start Address: {}".format(self.scpu.gpr[1]))
print("-------------------------------")
elif (sysCallID == CONST.MEM_FREE): # Mem Free System Call
status = self.mem_free(self.scpu.gpr[1], self.scpu.gpr[2])
print("-------------------------------")
print("System Call Recieved: mem_free")
print("PID that issued: {}".format(self.scpu.sram.ram[self.RunningPCBptr+3]))
print("Input: Size: {}, Start: {}".format(self.scpu.gpr[2], self.scpu.gpr[1]))
print("-------------------------------")
elif (sysCallID == CONST.MSG_QSEND):
status = self.msgQsend()
if (status == CONST.ER_TID):
print("-------------------------------")
print("System Call Recieved: msg_qsend")
print("PID that issued: {}".format(self.scpu.sram.ram[self.RunningPCBptr+3]))
print("Output: PID Invalid")
print("-------------------------------")
else:
print("-------------------------------")
print("System Call Recieved: msg_qsend")
print("PID that issued: {}".format(self.scpu.sram.ram[self.RunningPCBptr+3]))
print("Output: Message Sent")
print("-------------------------------")
elif (sysCallID == CONST.MSG_QRECIEVE):
ptr = self.RunningPCBptr
status = self.msgQRecieve()
if (status == CONST.WAITING):
print("-------------------------------")
print("System Call Recieved: msg_qrecieve")
print("PID that issued: {}".format(self.scpu.sram.ram[ptr+3]))
print("Output: Waiting for message")
print("-------------------------------")
self.scpu.psr = CONST.USERMODE
return CONST.WAITING
else:
print("-------------------------------")
print("System Call Recieved: msg_qrecieve")
print("PID that issued: {}".format(self.scpu.sram.ram[ptr+3]))
print("Output: Got Message")
print("-------------------------------")
elif (sysCallID == CONST.IO_GETC):
self.scpu.sram.ram[self.RunningPCBptr+4] = CONST.WAITINGGET
self.scpu.sram.ram[self.RunningPCBptr+1] = CONST.WAITING
print("-------------------------------")
print("System Call Recieved: io_getc")
print("PID that issued: {}".format(self.scpu.sram.ram[self.RunningPCBptr+3]))
print("Output: Waiting for Input Completion")
print("-------------------------------")
self.scpu.psr = CONST.USERMODE
return CONST.WAITING
elif (sysCallID == CONST.IO_PUTC):
self.scpu.sram.ram[self.RunningPCBptr+4] = CONST.WAITINGPUT
self.scpu.sram.ram[self.RunningPCBptr+1] = CONST.WAITING
print("-------------------------------")
print("System Call Recieved: io_putc")
print("PID that issued: {}".format(self.scpu.sram.ram[self.RunningPCBptr+3]))
print("Output: Waiting for Output Completion")
print("-------------------------------")
self.scpu.psr = CONST.USERMODE
return CONST.WAITING
elif (sysCallID == CONST.TIME_GET):
self.scpu.gpr[1] = self.scpu.clock
print("-------------------------------")
print("System Call Recieved: time_get")
print("PID that issued: {}".format(self.scpu.sram.ram[self.RunningPCBptr+3]))
print("Output: Time: {}".format(self.scpu.gpr[1]))
print("-------------------------------")
elif (sysCallID == CONST.TIME_SET):
self.scpu.clock = self.scpu.gpr[1]
print("-------------------------------")
print("System Call Recieved: time_set")
print("PID that issued: {}".format(self.scpu.sram.ram[self.RunningPCBptr+3]))
print("Input: Time: {}".format(self.scpu.gpr[1]))
print("-------------------------------")
else:
self.scpu.psr = CONST.USERMODE
return CONST.ER_ISC
self.scpu.psr = CONST.USERMODE
return status
def mem_alloc(self, size):
"""
System Call,Takes supplied size of memory allocation and tries to
allocate the memory. Returns the status and teh start of the address
to GPRs 0 and 1
Parameters:
size size of the memory to be allocated
Returns:
status status of the memory allocation
"""
status = self.allocateMemory(size, "userFreeList")
if (status >= 0):
self.scpu.gpr[1] = status # GPR1 Gets pointer to memory
self.scpu.gpr[0] = CONST.OK # GPR0 Gets OK Status
else:
self.scpu.gpr[0] = status # GPR0 gets error status
return status
def mem_free(self, start, size):
"""
System Call, Take the supplied start address and size of memory to free
and tries to free it. Returns the status.
Parameters:
start start address of memory
size size of memory to be freed
Returns:
status status of the system call
"""
status = self.freeMemory(start, size, "userFreeList")
return status
def allocateMemory(self, size, freeList):
"""
Takes the supplied size of memory and attempts to allocate it. Searches
through the userFreeList looking for a block.
Parameters:
size size of memory to be allocated
freeList The list (OS/User) to work with
Returns:
ptr Pointer to the start of mem location
ER_MEM No Memory available.
"""
if freeList not in self.memoryLists.keys():
raise ValueError("Invalid memory list. Expected one of: %s" % self.memoryLists.keys())
ptr = vars(self)[freeList]
previousPtr = CONST.EOL
while (ptr != CONST.EOL):
if (self.scpu.sram.ram[ptr+1] >= size):
break # Found Free Block
else:
previousPtr = ptr
ptr = self.scpu.sram.ram[ptr]
# Check Various Cases
if (ptr == CONST.EOL):
return CONST.ER_MEM # No Memory Available
if (self.scpu.sram.ram[ptr+1] == size):
# Found equal size block, check for first block
if (ptr == vars(self)[freeList]):
# First block equal size
vars(self)[freeList] = self.scpu.sram.ram[ptr]
self.scpu.sram.ram[ptr] = CONST.EOL
return ptr
else:
# Middle Block Equal Size
self.scpu.sram.ram[previousPtr] = self.scpu.sram.ram[ptr]
self.scpu.sram.ram[ptr] = CONST.EOL
return ptr
else: # Found bigger block, check for first block
if (ptr == vars(self)[freeList]): # First Block
# First block bigger, modify size userFreeList
vars(self)[freeList] = ptr + size
self.scpu.sram.ram[ptr+size] = self.scpu.sram.ram[ptr]
self.scpu.sram.ram[ptr+size+1] = self.scpu.sram.ram[ptr+1] - size
self.scpu.sram.ram[ptr] = CONST.EOL
return ptr
else: # Not first block
# Middle block larger size
self.scpu.sram.ram[ptr+size] = self.scpu.sram.ram[ptr]
self.scpu.sram.ram[ptr+size+1] = self.scpu.sram.ram[ptr+1] - size
self.scpu.sram.ram[previousPtr] = self.scpu.sram.ram[ptr+size]
self.scpu.sram.ram[ptr] = CONST.EOL
return ptr
def freeMemory(self, start, size, freeList):
"""
Takes the supplied start address and size of memory block and frees it
from the userFreeList. Adds to correct location in the freeList.
Parameters:
start Start of address of memory
size size of memory to free
freeList The list (OS/User) to work with
Returns:
status
"""
if freeList not in self.memoryLists.keys():
raise ValueError("Invalid memory list. Expected one of: %s" % self.memoryLists.keys())
status = 0
ptr = vars(self)[freeList]
previousPtr = CONST.EOL
if (ptr == CONST.EOL): # All Memory Used
vars(self)[freeList] = start
self.scpu.sram.ram[start] = CONST.EOL
self.scpu.sram.ram[start+1] = size
else:
if (ptr-(start+size) == 0): # Blocks next to each other at beinning
self.scpu.sram.ram[start] = self.scpu.sram.ram[ptr]
self.scpu.sram.ram[start+1] = size + self.scpu.sram.ram[ptr+1]
vars(self)[freeList] = start
self.scpu.sram.ram[ptr] = 0
self.scpu.sram.ram[ptr+1] = 0
return CONST.OK
else:
while (ptr != CONST.EOL):
previousPtr = ptr
ptr = self.scpu.sram.ram[ptr]
if (ptr-(start+size) == 0):
# Blocks Next to each other in middle
if (start-(previousPtr+self.scpu.sram.ram[previousPtr+1]) == 0):
# Between two blocks
self.scpu.sram.ram[previousPtr+1] = size + self.scpu.sram.ram[ptr+1] + self.scpu.sram.ram[previousPtr+1]
self.scpu.sram.ram[previousPtr] = self.scpu.sram.ram[ptr]
self.scpu.sram.ram[ptr] = 0
self.scpu.sram.ram[ptr+1] = 0
return CONST.OK
else:
# Next to block
self.scpu.sram.ram[start] = self.scpu.sram.ram[ptr]
self.scpu.sram.ram[start+1] = size + self.scpu.sram.ram[ptr+1]
self.scpu.sram.ram[previousPtr] = start
self.scpu.sram.ram[ptr] = 0
self.scpu.sram.ram[ptr+1] = 0
return CONST.OK
# Block at end of list
if (start-(previousPtr+self.scpu.sram.ram[previousPtr+1]) == 0):
self.scpu.sram.ram[previousPtr+1] = size + self.scpu.sram.ram[previousPtr+1]
return CONST.OK
else:
self.scpu.sram.ram[start] = CONST.EOL
self.scpu.sram.ram[start+1] = size
self.scpu.sram.ram[previousPtr] = start
return CONST.OK
return status
def absoluteLoader(self, filename):
"""
Passed in filename is opened, parsed line by line, and stored in RAM.
Values are checked to make sure they are valid. Returns the value of
the program counter.
Parameters:
filename name of executable file
Returns:
0 to 9999 successful load, PC value
ER_FILEOPEN unable to open file
ER_INVALIDADDR invalid memory address
ER_NOENDOFPROG missing end of program indicator
"""
try:
programFile = open(filename, "r")
except:
return CONST.ER_FILEOPEN
for programLine in programFile.readlines():
temp = programLine.split(" ")
addr = int(temp[0])
content = int(temp[1], 16)
if (addr >= 0) and (addr <= 9999):
self.scpu.sram.ram[addr] = content
elif (addr == CONST.ENDPROG):
programFile.close()
return content
else:
programFile.close()
return CONST.ER_INVALIDADDR
programFile.close()
return CONST.ER_NOENDOFPROG
def createProcess(self, filename, priority):
"""
Takes a file and tries to laod the program. Allocates necessary user
and OS memory for the program and creates the PCB. Inserts PCB in RQ.
Parameters:
filename name of the file that contains the program
priority priority of the process being created
Returns:
OK successfully created process
ER_MEM no memory available
"""
# Allocate Memory for PCB
pcbptr = self.allocateMemory(CONST.PCBSIZE, "osFreeList")
if (pcbptr < 0):
return CONST.ER_MEM
status = self.absoluteLoader(filename)
if (status < 0):
return status
# Set PC in PCB
self.scpu.sram.ram[pcbptr+14] = status
# Allocate Message Queue
msgqid = self.allocateMemory(10, "osFreeList")
# Allocate stack from user free list
ptr = self.allocateMemory(CONST.USER_STACK_SIZE, "userFreeList")
if (ptr < 0):
return CONST.ER_MEM
else:
self.scpu.sram.ram[pcbptr+15] = ptr
self.scpu.sram.ram[pcbptr+16] = CONST.USER_STACK_SIZE
self.scpu.sram.ram[pcbptr+13] = ptr - 1 # Empty Stack
# Initialize GPR0-7 to 0 in PCB
for i in range(8):
self.scpu.sram.ram[pcbptr+5+i] = 0
# Set State to ready
self.scpu.sram.ram[pcbptr+1] = CONST.READY
# Set Priority
self.scpu.sram.ram[pcbptr+2] = priority
# Set PID
self.scpu.sram.ram[pcbptr+3] = self.pid
self.pid += 1
# Reason for waiting
self.scpu.sram.ram[pcbptr+4] = 0
# Set msgqueue start address
self.scpu.sram.ram[pcbptr+17] = msgqid
# Set message queue size
self.scpu.sram.ram[pcbptr+18] = 10
# set number of messages in queue
self.scpu.sram.ram[pcbptr+19] = 0
# Insert into RQ
self.insertRQ(pcbptr)
print("--------------------------")
print("|Process Created PCB Dump|")
print("--------------------------")
self.printPCB(pcbptr)
print("------------------------------")
print("|End Process Created PCB Dump|")
print("------------------------------")
return status
def taskCreate(self):
"""
System call, creates a child process of a program already loaded.
Returns:
OK successfully created process
ER_MEM no memory available
"""
# Allocate memory for pcb
pcbptr = self.allocateMemory(CONST.PCBSIZE, "osFreeList")
# Set PC in PCB
self.scpu.sram.ram[pcbptr+14] = self.scpu.gpr[3]
# Allocate message queue
msgqid = self.allocateMemory(10, "osFreeList")
# Allocate stack from user free list
ptr = self.allocateMemory(CONST.USER_STACK_SIZE, "userFreeList")
if (ptr < 0):
return CONST.ER_MEM
else:
self.scpu.sram.ram[pcbptr+15] = ptr
self.scpu.sram.ram[pcbptr+16] = CONST.USER_STACK_SIZE
self.scpu.sram.ram[pcbptr+13] = ptr - 1 # Empty Stack
# Initialize GPR0-7 to 0 in PCB
for i in range(8):
self.scpu.sram.ram[pcbptr+5+i] = 0
# Set State to ready
self.scpu.sram.ram[pcbptr+1] = CONST.READY
# Set Priority
self.scpu.sram.ram[pcbptr+2] = CONST.DFLT_USR_PRTY
# Set PID
self.scpu.sram.ram[pcbptr+3] = self.pid
self.pid += 1
# Reason for waiting
self.scpu.sram.ram[pcbptr+4] = 0
# Set msgqueue start address
self.scpu.sram.ram[pcbptr+17] = msgqid
# Set message queue size
self.scpu.sram.ram[pcbptr+18] = 10
# set number of messages in queue
self.scpu.sram.ram[pcbptr+19] = 0
# Insert into RQ
self.insertRQ(pcbptr)
self.scpu.gpr[2] = self.scpu.sram.ram[pcbptr+3]
self.scpu.gpr[0] = CONST.OK
print("--------------------------")
print("| Task Created PCB Dump |")
print("--------------------------")
self.printPCB(pcbptr)
print("------------------------------")
print("| End Task Created PCB Dump |")
print("------------------------------")
return CONST.OK
def taskDelete(self):
"""
System Call, deletes a child process
Returns:
status
"""
if (self.scpu.gpr[1] == 0):
return CONST.HALT
if (self.scpu.gpr[1] > 0):
# Search WQ
pcbptr = self.searchRemoveWQ(self.scpu.gpr[1])
if (pcbptr == CONST.EOL):
pcbptr = self.searchRemoveRQ(self.scpu.gpr[1])
if (pcbptr == CONST.EOL):
if (self.scpu.sram.ram[self.RunningPCBptr+3] == self.scpu.gpr[1]):
return CONST.HALT
else:
self.scpu.gpr[0] = CONST.ER_TID
return CONST.OK
else: # Found in RQ
self.terminateProcess(pcbptr)
self.scpu.gpr[0] = CONST.OK
return CONST.OK
else: # Found in WQ
self.terminateProcess(pcbptr)
self.scpu.gpr[0] = CONST.OK
return CONST.OK
else: # PID < 0
self.scpu.gpr[0] = CONST.ER_TID
return CONST.OK
def terminateProcess(self, pcbptr):
"""
Free the memory of the supplied process using the pointer
Parameters:
pcbptr Pointer to the process to terminate
"""
self.freeMemory(self.scpu.sram.ram[pcbptr+15], self.scpu.sram.ram[pcbptr+16], "userFreeList")
self.freeMemory(pcbptr, CONST.PCBSIZE, "osFreeList")
def selectProcess(self):
"""
Selects a process from the Ready Queue. Removes that process from the
RQ and returns the ptr to the selected process.
Returns:
pcbptr ptr to chosen process
"""
pcbptr = self.RQptr
self.removeFromRQ()
return pcbptr
def saveCPUContext(self, pcbptr):
"""
Saves the current register status into the PCB for the running process
Parameters:
pcbptr pointer to pcb
"""
self.scpu.sram.ram[pcbptr+5] = self.scpu.gpr[0]
self.scpu.sram.ram[pcbptr+6] = self.scpu.gpr[1]
self.scpu.sram.ram[pcbptr+7] = self.scpu.gpr[2]
self.scpu.sram.ram[pcbptr+8] = self.scpu.gpr[3]
self.scpu.sram.ram[pcbptr+9] = self.scpu.gpr[4]
self.scpu.sram.ram[pcbptr+10] = self.scpu.gpr[5]
self.scpu.sram.ram[pcbptr+11] = self.scpu.gpr[6]
self.scpu.sram.ram[pcbptr+12] = self.scpu.gpr[7]
self.scpu.sram.ram[pcbptr+13] = self.scpu.sp
self.scpu.sram.ram[pcbptr+14] = self.scpu.pc
def dispatcher(self, pcbptr):
"""
Sets the registers from the PCB supplied
Parameters:
pcbptr pointer to pcb
"""
self.scpu.gpr[0] = self.scpu.sram.ram[pcbptr+5]
self.scpu.gpr[1] = self.scpu.sram.ram[pcbptr+6]
self.scpu.gpr[2] = self.scpu.sram.ram[pcbptr+7]
self.scpu.gpr[3] = self.scpu.sram.ram[pcbptr+8]
self.scpu.gpr[4] = self.scpu.sram.ram[pcbptr+9]
self.scpu.gpr[5] = self.scpu.sram.ram[pcbptr+10]
self.scpu.gpr[6] = self.scpu.sram.ram[pcbptr+11]
self.scpu.gpr[7] = self.scpu.sram.ram[pcbptr+12]
self.scpu.sp = self.scpu.sram.ram[pcbptr+13]
self.scpu.pc = self.scpu.sram.ram[pcbptr+14]
self.scpu.psr = CONST.USERMODE
def processInterrupts(self):
"""Display a list of valid interrupts, waits for user input. Performs
the requested interrupt.
Returns:
0 No Interrupts/Successful Process
ER_INT Invalid Interrupt
ER_FILEOPEN file not found
"""
print("------------------------")
print("Processing Interrupts: ")
print("0: No interrupt")
print("1: Read Character")
print("2: Output Character")
print("3: Run Program")
print("4: Shutdown")
interruptId = input("Interrupt ID: ")
try:
interruptId = int(interruptId)
except:
return CONST.ER_INT
if (interruptId == CONST.NO_INT): # No Interrupt
print("0: No Interrupt!")
return CONST.OK
elif (interruptId == CONST.INPUT_INT): # Read Char
print("1: Read Input!")
self.inputCompletionInterrupt()
return CONST.OK
elif (interruptId == CONST.OUTPUT_INT): # Output Char
print("2: Output Character!")
self.outputCompletionInterrupt()
return CONST.OK
elif (interruptId == CONST.RUN_INT): # Run Program
root = Tk()
root.withdraw()
fileToOpen = filedialog.askopenfilename(initialdir=Path(sys.path[0]+"/programs/machinecode"), title="Select Program", filetypes=(("Programs","*.txt"),("all files","*.*")))
root.destroy()
if (os.path.isfile(fileToOpen)):
print("3: Run Program!")
status = self.createProcess(fileToOpen, CONST.DFLT_USR_PRTY)
self.dumpMemory("Program Area after Process Creation Memory Dump", 0, 130)
return status
else:
return CONST.ER_FILEOPEN
elif ( interruptId == CONST.SHUTDOWN_INT): # Shutdown
while (self.RQptr != CONST.EOL): # Terminate Ready Processes
ptr = self.scpu.sram.ram[self.RQptr]
self.terminateProcess(self.RQptr)
self.RQptr = ptr
while (self.WQptr != CONST.EOL): # Terminate Waiting Processes
ptr = self.scpu.sram.ram[self.WQptr]
self.terminateProcess(self.WQptr)
self.WQptr = ptr
print("4: System Shutting Down!")
self.logger.info("System Shutting Down")
sys.exit(0)
else: # Invalid Interrupt
return CONST.ER_INT
def inputCompletionInterrupt(self):
"""
Simulates interrupt to read from the keyboard. Takes PID out of WQ,
reads a character and puts in GPR2. Puts process in RQ.
Returns:
0 Successful Read
"""
inputPid = input("Enter PID of Process needing Input: ")
try:
inputPid = int(inputPid)
except:
return CONST.ER_TID
pcbptr = self.searchRemoveWQ(inputPid)
if (pcbptr == CONST.EOL):
return CONST.ER_TID
print(inputPid)
inputChar = input("Type a character: ")
self.scpu.sram.ram[pcbptr+6] = ord(inputChar[0])
self.scpu.sram.ram[pcbptr+5] = CONST.OK
self.scpu.sram.ram[pcbptr+1] = CONST.READY
self.insertRQ(pcbptr)
return CONST.OK
def outputCompletionInterrupt(self):
"""
Simulates interrupt to read from keyboard. Takes PID out of WQ, reads
a character and puts in GPR2. Puts process in RQ.
Returns:
0 successful output
"""
outputPid = input("Enter PID of Process needing Output: ")
try:
outputPid = int(outputPid)
except:
return CONST.ER_TID
pcbptr = self.searchRemoveWQ(outputPid)
if (pcbptr == CONST.EOL):
return CONST.ER_TID
print(outputPid)
outputChar = chr(self.scpu.sram.ram[pcbptr+6])
print("Output: {}".format(outputChar))
self.scpu.sram.ram[pcbptr+5] = CONST.OK
self.scpu.sram.ram[pcbptr+1] = CONST.READY
self.insertRQ(pcbptr)
return CONST.OK
def searchRemoveWQ(self, findpid):
"""
Takes a given PID, searches for it in the WQ, if found removes it and
returns the PCB ptr. Otherwise returns not found
Parameters:
findpid pid of process to find
Returns:
EOL Pid not found
ptr ptr to pid in pcb
"""
ptr = self.WQptr
previousPtr = CONST.EOL
if (ptr == CONST.EOL): # Queue empty, not found
return CONST.EOL
else:
while (ptr != CONST.EOL):
if (self.scpu.sram.ram[ptr+3] == findpid): # Pid Found
if (previousPtr == CONST.EOL):
self.WQptr = self.scpu.sram.ram[ptr]
self.scpu.sram.ram[ptr] = CONST.EOL
return ptr
else:
self.scpu.sram.ram[previousPtr] = self.scpu.sram.ram[ptr]
self.scpu.sram.ram[ptr] = CONST.EOL
return ptr
else:
previousPtr = ptr
ptr = self.scpu.sram.ram[ptr]
return CONST.EOL
def searchRemoveRQ(self, findpid):
"""
Takes a given PID, searches for it in the RQ, if found removes it and
returns the PCB ptr. Otherwise returns not found
Parameters:
findpid pid of process to find
Returns:
EOL Pid not found
ptr ptr to pid in pcb
"""
ptr = self.RQptr
previousPtr = CONST.EOL
if (ptr == CONST.EOL): # Queue empty, not found
return CONST.EOL
else:
while (ptr != CONST.EOL):
if (self.scpu.sram.ram[ptr+3] == findpid): # Pid Found
if (previousPtr == CONST.EOL):
self.RQptr = self.scpu.sram.ram[ptr]
self.scpu.sram.ram[ptr] = CONST.EOL
return ptr
else:
self.scpu.sram.ram[previousPtr] = self.scpu.sram.ram[ptr]
self.scpu.sram.ram[ptr] = CONST.EOL
return ptr
else:
previousPtr = ptr
ptr = self.scpu.sram.ram[ptr]
return CONST.EOL
def insertRQ(self, pcbptr):
"""
Takes a pcbptr and puts in the correct place in RQ using Priority
Round Robin.
Parameters:
pcbptr pointer to pcb to put in RQ
"""
ptr = self.RQptr
previousPtr = CONST.EOL
if (pcbptr >= 7000) and (pcbptr <= 9974): # Valid pcbptr
if (self.RQptr == CONST.EOL): # Rq Empty
self.RQptr = pcbptr
return
else: # RQ has entries, search through and insert correctly
while (ptr != CONST.EOL):
if (self.scpu.sram.ram[pcbptr+2] <= self.scpu.sram.ram[ptr+2]):
previousPtr = ptr
ptr = self.scpu.sram.ram[ptr]
else: # Found place to insert
# Insert between previous ptr and ptr
# 1, the beginning
if (ptr == self.RQptr):
self.scpu.sram.ram[pcbptr] = self.RQptr
self.RQptr = pcbptr
return
else:
# Insert in middle
self.scpu.sram.ram[pcbptr] = ptr
self.scpu.sram.ram[previousPtr] = pcbptr
return
# Insert at end of RQ
self.scpu.sram.ram[previousPtr] = pcbptr
return
else: # Invalid pcbptr
return
def insertWQ(self, pcbptr):
"""
Takes a pcbptr and puts in the correct place in WQ using Priority
Round Robin.
Parameters:
pcbptr pointer to pcb to put in RQ
"""
ptr = self.WQptr
previousPtr = CONST.EOL
if (pcbptr >= 7000) and (pcbptr <= 9974): # Valid pcbptr
if (self.WQptr == CONST.EOL): # Rq Empty
self.WQptr = pcbptr
return
else: # RQ has entries, search through and insert correctly
while (ptr != CONST.EOL):
if (self.scpu.sram.ram[pcbptr+2] <= self.scpu.sram.ram[ptr+2]):
previousPtr = ptr
ptr = self.scpu.sram.ram[ptr]
else: # Found place to insert
# Insert between previous ptr and ptr
# 1, the beginning
if (ptr == self.WQptr):
self.scpu.sram.ram[pcbptr] = self.WQptr
self.WQptr = pcbptr
return
else:
# Insert in middle
self.scpu.sram.ram[pcbptr] = ptr
self.scpu.sram.ram[previousPtr] = pcbptr
return
# Insert at end of RQ
self.scpu.sram.ram[previousPtr] = pcbptr
return
else: # Invalid pcbptr
return
def removeFromRQ(self):
"""
Takes the first entry from the RQ and removes from the list.
"""
pcbptr = self.RQptr
self.RQptr = self.scpu.sram.ram[pcbptr]
self.scpu.sram.ram[pcbptr] = CONST.EOL
def removeFromWQ(self):
"""
Takes the first entry from the WQ and removes from the list.
"""
pcbptr = self.WQptr
self.WQptr = self.scpu.sram.ram[pcbptr]
self.scpu.sram.ram[pcbptr] = CONST.EOL
def searchPID(self, pid):
"""
Search through the WQ and RQ for a PID
Parameters:
pid pid of process to find
Returns:
pcbptr ptr to pid
EOL pid not found
"""
ptr = self.WQptr
while (ptr != CONST.EOL):
if (self.scpu.sram.ram[ptr+3] == pid):
return ptr
else:
ptr = self.scpu.sram.ram[ptr]
ptr = self.RQptr
while (ptr != CONST.EOL):
if (self.scpu.sram.ram[ptr+3] == pid):
return ptr
else:
ptr = self.scpu.sram.ram[ptr]
return CONST.EOL
def msgQsend(self):
"""
System call, Sends a message with a start address of GPR2 to PID in
GPR1
"""
# GPR1 has process PID
# GPR2 has start address of message
# Set GPR0 to status when done
self.logger.debug("msgQsend pid: %s, start addr: %s", self.scpu.gpr[1], self.scpu.gpr[2])
pctptr = self.searchPID(self.scpu.gpr[1]) # Search WQ and RQ for pid
if (pctptr == CONST.EOL): # Invalid PID
self.scpu.gpr[0] = CONST.ER_TID # Error, invalid PID
return CONST.ER_TID
msgaddr = self.scpu.sram.ram[pctptr+17]
msgcount = self.scpu.sram.ram[pctptr+19]
self.scpu.sram.ram[msgaddr+msgcount] = self.scpu.gpr[2]
self.scpu.sram.ram[pctptr+19] += 1
self.scpu.sram.ram[pctptr+7] = self.scpu.gpr[2]
self.scpu.gpr[0] = CONST.OK
return CONST.OK
def msgQRecieve(self):
"""
System Call, tries to retrieve message, if none, waits until one
arrives
"""
if (self.scpu.sram.ram[self.RunningPCBptr+19] == 0): # No message in queue
self.scpu.sram.ram[self.RunningPCBptr+4] = CONST.WAITINGMSG # Waiting for msg
self.scpu.sram.ram[self.RunningPCBptr+1] = CONST.WAITING # Set state to waiting
return CONST.WAITING
# There is a message in the queue
msgqaddr = self.scpu.sram.ram[self.RunningPCBptr+17]
self.scpu.gpr[2] = self.scpu.sram.ram[msgqaddr] # Copy msg start addr to gpr2
self.scpu.gpr[0] = CONST.OK
return CONST.OK
def taskInquiry(self):
"""
Sets the GPRs to contain information about the running process.
PID, priority, and state.
"""
self.scpu.gpr[0] = CONST.OK
self.scpu.gpr[1] = self.scpu.sram.ram[self.RunningPCBptr+3] # PID
self.scpu.gpr[2] = self.scpu.sram.ram[self.RunningPCBptr+2] # Priority
self.scpu.gpr[3] = self.scpu.sram.ram[self.RunningPCBptr+1] # State
def dumpMemory(self, title, start, end):
"""