-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathkernel.py
More file actions
59 lines (49 loc) · 2.04 KB
/
kernel.py
File metadata and controls
59 lines (49 loc) · 2.04 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
from process import Process
class Kernel:
CPU_CODES = {
0x00: "Halt code",
0xAA: "Protection error",
0xBB: "Invalid register",
0xCC: "Unknown opcode",
0xDD: "Unknown syscall",
0xD0: "Awaiting syscall",
0xFF: "Success code"
}
def __init__(self, mmu, cpu):
self.processes:Process = []
self.current = 0
self.CPU = cpu
self.MMU = mmu
def create_process(self, program:Process, base_addr:int=0x00000, stack_top:int=0xFFFFF):
process = Process(len(self.processes)) # len of processes -> pid
bytes_used = 0
for i, byte in enumerate(program):
self.MMU.write_uint8(process, base_addr + i, byte)
bytes_used += 1
print(f"Loaded {bytes_used} bytes to memory")
process.registers["sp"] = stack_top # top of virtual memory, grows downward
process.registers["pc"] = base_addr # bottom of virtual memory, grows upward
self.processes.append(process)
return process
def get_current_process(self):
return self.processes[self.current]
def schedule_next(self):
self.current = (self.current + 1) % len(self.processes)
def context_switch(self):
current_process = self.get_current_process()
current_process.registers = self.CPU.registers.copy()
self.schedule_next()
next_process = self.get_current_process()
self.CPU.registers = next_process.registers.copy()
def handle_syscall(self, process:Process):
reg_index = process.registers["c0"] - 0xD0 # = r0...7
syscall_code = process.registers[f"r{reg_index}"]
match syscall_code:
case 0x00:
process.exit_code = process.registers["r1"]
process.registers["c0"] = 0x00 # signal halt
print(f"pid {process.pid} safe kernel exit")
case 0xA0:
print(f"pid {process.pid} console out: {process.registers["r1"]}")
case _:
print(f"pid {process.pid} unknown syscall")