forked from vonsim/vonsim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
595 lines (548 loc) · 20 KB
/
index.ts
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
import { MemoryAddress } from "@vonsim/common/address";
import { AnyByte, Byte } from "@vonsim/common/byte";
import { Component, ComponentInit } from "../component";
import { SimulatorError } from "../error";
import type { EventGenerator } from "../events";
import { InstructionType, statementToInstruction } from "./instructions";
import { getSyscallNumber, handleSyscall } from "./syscalls";
import type {
ByteRegister,
Flag,
MARRegister,
PartialFlags,
PhysicalRegister,
Register,
RegistersMap,
WordRegister,
} from "./types";
import { parseRegister } from "./utils";
/**
* The CPU.
* @see {@link https://vonsim.github.io/en/computer/cpu}
*
* It has internal registers, a memory address buffer (MAR) and a
* memory buffer register (MBR).
*
* It also stores the instructions of the program. This is done to avoid
* having to read the program from memory every time an instruction is executed,
* which would be very inefficient.
*
* The function that executes the instructions is {@link CPU.run}.
*
* ---
* This class is: MUTABLE
*/
export class CPU extends Component {
#instructions: Map<number, InstructionType>;
#registers: RegistersMap;
#MAR: Byte<16>;
#MBR: Byte<8>;
constructor(options: ComponentInit) {
super(options);
if (options.data === "unchanged") {
this.#registers = options.previous.cpu.#registers;
this.#MAR = options.previous.cpu.#MAR;
this.#MBR = options.previous.cpu.#MBR;
} else if (options.data === "randomize") {
this.#registers = {
AX: Byte.random(16),
BX: Byte.random(16),
CX: Byte.random(16),
DX: Byte.random(16),
SP: Byte.random(16),
IP: Byte.random(16),
IR: Byte.random(8),
ri: Byte.random(16),
id: Byte.random(16),
left: Byte.random(16),
right: Byte.random(16),
result: Byte.random(16),
FLAGS: Byte.random(16),
};
this.#MAR = Byte.random(16);
this.#MBR = Byte.random(8);
} else {
this.#registers = {
AX: Byte.zero(16),
BX: Byte.zero(16),
CX: Byte.zero(16),
DX: Byte.zero(16),
SP: Byte.zero(16),
IP: Byte.zero(16),
IR: Byte.zero(8),
ri: Byte.zero(16),
id: Byte.zero(16),
left: Byte.zero(16),
right: Byte.zero(16),
result: Byte.zero(16),
FLAGS: Byte.zero(16),
};
this.#MAR = Byte.zero(16);
this.#MBR = Byte.zero(8);
}
// Stack pointer starts at the "bottom" of the memory
this.#registers.SP = Byte.fromUnsigned(MemoryAddress.MAX_ADDRESS + 1, 16);
// The initial address of the program is 0x2000
this.#registers.IP = Byte.fromUnsigned(0x2000, 16);
// Interrupts always enabled at the start
this.#setFlag("IF", true);
this.#instructions = new Map();
for (const statement of options.program.instructions) {
const instruction = statementToInstruction(statement);
this.#instructions.set(instruction.start.value, instruction);
}
}
/**
* CPU runner.
* Executes one instruction at a time, yielding the micro-operations that it will execute.
*
* ---
* Called by the Computer.
*/
*run(): EventGenerator {
// Infinite loop until computer halts
while (true) {
// Gets the instruction at the current IP from `this.#instructions`
const IP = this.#registers.IP;
const syscallNumber = getSyscallNumber(IP);
if (syscallNumber !== null) {
// Syscall
const continueExecuting = yield* handleSyscall(this.computer, syscallNumber);
if (!continueExecuting) return;
} else {
const instruction = this.#instructions.get(IP.unsigned);
if (!instruction) {
yield {
type: "cpu:error",
error: new SimulatorError("no-instruction", this.#registers.IP),
};
return;
}
// Execute the instruction, and checks if the instruction returned `false` (halt)
const continueExecuting = yield* instruction.execute(this.computer);
if (!continueExecuting) return;
}
// Check for interrupts
if (this.getFlag("IF") && this.computer.io.pic?.isINTRActive()) {
// Start interrupt phase
yield { type: "cpu:cycle.interrupt" };
const intn = yield* this.computer.io.pic.handleINTR();
yield* this.getMBR("ri.l");
yield* this.updateByteRegister("ri.h", Byte.zero(8));
yield* this.startInterrupt(intn);
}
// End cycle and repeat
yield { type: "cpu:cycle.end" };
}
}
/**
* Starts an interrupt routine.
* The interrupt number should have been previously written to the ri register.
*
* This function will push the FLAGS and IP registers to the stack, and set the IF flag to false.
* Then, will get the interrupt routine address from the interrupt vector table, and set the IP register to that address.
*
* @see {@link https://vonsim.github.io/en/computer/cpu#interrupts}
*
* @param number The interrupt number (0-255).
* @returns Whether the operation was successful.
*
* ---
* Called by the CPU ({@link CPU.run}).
*/
*startInterrupt(number: Byte<8>): EventGenerator<boolean> {
// Save machine state
yield* this.copyWordRegister("FLAGS", "id");
if (!(yield* this.pushToStack())) return false; // Stack overflow
yield* this.updateFLAGS({ IF: false });
yield* this.copyWordRegister("IP", "id");
if (!(yield* this.pushToStack())) return false; // Stack overflow
// Get interrupt routine address low
let vector = Byte.fromUnsigned(number.unsigned * 4, 16);
yield* this.updateWordRegister("ri", vector);
yield* this.setMAR("ri");
if (!(yield* this.useBus("mem-read"))) return false; // Error reading memory
yield* this.getMBR("id.l");
// Get interrupt routine address high
vector = vector.add(1);
yield* this.updateWordRegister("ri", vector);
yield* this.setMAR("ri");
if (!(yield* this.useBus("mem-read"))) return false; // Error reading memory
yield* this.getMBR("id.h");
// Update IP
yield* this.copyWordRegister("id", "IP");
return true;
}
toJSON() {
const registers = Object.entries(this.#registers).reduce(
(acc, [reg, value]) => ({ ...acc, [reg]: value.toJSON() }),
{} as { [key in PhysicalRegister]: number },
);
return {
...registers,
MAR: this.#MAR.toJSON(),
MBR: this.#MBR.toJSON(),
};
}
// #=========================================================================#
// # Register methods #
// #=========================================================================#
/**
* Gets the value of the specified register.
* @param register Either a full register or a partial register (like AL for the low part of AX).
* @returns The value of the register.
*/
getRegister(register: ByteRegister): Byte<8>;
getRegister(register: WordRegister): Byte<16>;
getRegister(register: Register): AnyByte {
const [reg, part] = parseRegister(register);
if (part === "low") return this.#registers[reg].low;
else if (part === "high") return this.#registers[reg].high;
else return this.#registers[reg];
}
/**
* Sets the value of the specified register.
* If the value size is different from the register size, an error is thrown.
* @internal
* @param register Either a full register or a partial register (like AL for the low part of AX).
* @param value The value to set.
*/
#setRegister(register: ByteRegister, value: Byte<8>): void;
#setRegister(register: WordRegister, value: Byte<16>): void;
#setRegister(register: Register, value: AnyByte): void {
const [reg, part] = parseRegister(register);
if (part === null) {
if (this.#registers[reg].size !== value.size) {
throw new TypeError(
`Cannot set register ${register} with value ${value} of different size`,
);
}
(this.#registers[reg] as AnyByte) = value;
} else {
if (!value.is8bits()) {
throw new TypeError(
`Cannot set register ${register} with value ${value} of different size`,
);
}
if (part === "low") (this.#registers[reg] as AnyByte) = this.#registers[reg].withLow(value);
else (this.#registers[reg] as AnyByte) = this.#registers[reg].withHigh(value);
}
}
/**
* Copies the value of a byte register to another byte register.
*
* ---
* Called by the instructions ({@link InstructionType.execute}) and the CPU.
*/
*copyByteRegister(src: ByteRegister, dest: ByteRegister): EventGenerator {
const value = this.getRegister(src);
this.#setRegister(dest, value);
yield { type: "cpu:register.copy", size: 8, src, dest };
}
/**
* Copies the value of a word register to another word register.
*
* ---
* Called by the instructions ({@link InstructionType.execute}) and the CPU.
*/
*copyWordRegister(src: WordRegister, dest: WordRegister): EventGenerator {
const value = this.getRegister(src);
this.#setRegister(dest, value);
yield { type: "cpu:register.copy", size: 16, src, dest };
}
/**
* Updates the value of a byte register.
*
* ---
* Called by the instructions ({@link InstructionType.execute}) and the CPU.
*/
*updateByteRegister(
register: ByteRegister,
value: Byte<8> | ((prev: Byte<8>) => Byte<8>),
): EventGenerator {
value = typeof value === "function" ? value(this.getRegister(register)) : value;
this.#setRegister(register, value);
yield { type: "cpu:register.update", size: 8, register, value };
}
/**
* Updates the value of a word register.
*
* ---
* Called by the instructions ({@link InstructionType.execute}) and the CPU.
*/
*updateWordRegister(
register: WordRegister,
value: Byte<16> | ((prev: Byte<16>) => Byte<16>),
): EventGenerator {
value = typeof value === "function" ? value(this.getRegister(register)) : value;
this.#setRegister(register, value);
yield { type: "cpu:register.update", size: 16, register, value };
}
// #=========================================================================#
// # Flags methods #
// #=========================================================================#
/**
* Returns the value of the specified flag.
* @see {@link https://vonsim.github.io/en/computer/cpu#flags}
*/
getFlag(flag: Flag): boolean {
switch (flag) {
case "CF":
return this.#registers.FLAGS.bit(0);
case "ZF":
return this.#registers.FLAGS.bit(6);
case "SF":
return this.#registers.FLAGS.bit(7);
case "IF":
return this.#registers.FLAGS.bit(9);
case "OF":
return this.#registers.FLAGS.bit(11);
default:
throw new TypeError(`Invalid flag ${flag}`);
}
}
/**
* Sets the value of the specified flag.
* @internal
* @see {@link https://vonsim.github.io/en/computer/cpu#flags}
*/
#setFlag(flag: Flag, value: boolean): void {
switch (flag) {
case "CF":
this.#registers.FLAGS = this.#registers.FLAGS.withBit(0, value);
return;
case "ZF":
this.#registers.FLAGS = this.#registers.FLAGS.withBit(6, value);
return;
case "SF":
this.#registers.FLAGS = this.#registers.FLAGS.withBit(7, value);
return;
case "IF":
this.#registers.FLAGS = this.#registers.FLAGS.withBit(9, value);
return;
case "OF":
this.#registers.FLAGS = this.#registers.FLAGS.withBit(11, value);
return;
default:
throw new TypeError(`Invalid flag ${flag}`);
}
}
/**
* Updates the FLAGS register.
* @param flags The flags to update. If a flag is not specified, it will not be updated.
*
* ---
* Called by the instructions ({@link InstructionType.execute}) and the CPU.
*/
*updateFLAGS(flags: PartialFlags): EventGenerator {
if (typeof flags.CF === "boolean") this.#setFlag("CF", flags.CF);
if (typeof flags.ZF === "boolean") this.#setFlag("ZF", flags.ZF);
if (typeof flags.SF === "boolean") this.#setFlag("SF", flags.SF);
if (typeof flags.IF === "boolean") this.#setFlag("IF", flags.IF);
if (typeof flags.OF === "boolean") this.#setFlag("OF", flags.OF);
yield {
type: "cpu:register.update",
size: 16,
register: "FLAGS",
value: this.#registers.FLAGS,
};
}
/**
* Updates the FLAGS register.
* @param flags The flags to update. If a flag is not specified, it will not be updated.
*
* ---
* Called by the instructions ({@link InstructionType.execute}) and the CPU.
*/
*aluExecute(operation: string, result: AnyByte, flags: PartialFlags): EventGenerator {
this.#registers.result = result.is8bits() ? this.#registers.result.withLow(result) : result;
if (typeof flags.CF === "boolean") this.#setFlag("CF", flags.CF);
if (typeof flags.ZF === "boolean") this.#setFlag("ZF", flags.ZF);
if (typeof flags.SF === "boolean") this.#setFlag("SF", flags.SF);
if (typeof flags.IF === "boolean") this.#setFlag("IF", flags.IF);
if (typeof flags.OF === "boolean") this.#setFlag("OF", flags.OF);
yield {
type: "cpu:alu.execute",
operation,
size: result.size,
result: this.#registers.result,
flags: this.#registers.FLAGS,
};
}
// #=========================================================================#
// # Bus methods #
// #=========================================================================#
/**
* Sets the value of the MAR.
*
* ---
* Called by the instructions ({@link InstructionType.execute}) and the CPU.
*/
*setMAR(register: MARRegister): EventGenerator {
const value = this.getRegister(register);
this.#MAR = value;
yield { type: "cpu:mar.set", register };
}
/**
* Copies the value of the MBR to another register.
*
* ---
* Called by the instructions ({@link InstructionType.execute}) and the CPU.
*/
*getMBR(register: ByteRegister): EventGenerator {
this.#setRegister(register, this.#MBR);
yield { type: "cpu:mbr.get", register };
}
/**
* Sets the value of the MBR.
*
* ---
* Called by the instructions ({@link InstructionType.execute}) and the CPU.
*/
*setMBR(register: ByteRegister): EventGenerator {
const value = this.getRegister(register);
this.#MBR = value;
yield { type: "cpu:mbr.set", register };
}
/**
* Uses the bus. Analogous to set the control lines of the bus.
*
* @param mode
* - `mem-read`: Read from memory.
* The address should have been previously written to the MAR register.
* The value will be written to the MBR register.
* - `mem-write`: Write to memory.
* The address should have been previously written to the MAR register.
* The value will be read from the MBR register.
* - `io-read`: Read from I/O memory.
* The address should have been previously written to the low part of the MAR register.
* The value will be written to the MBR register.
* - `io-write`: Read from memory.
* The address should have been previously written to the low part of the MAR register.
* The value will be written to the MBR register.
* - `intr-read`: Read the interrupt number from the PIC.
* The value will be written to the MBR register.
*
* @returns Whether the operation was successful.
*
* ---
* Called by the instructions ({@link InstructionType.execute}) and the CPU.
*/
*useBus(mode: `${"mem" | "io"}-${"read" | "write"}` | "intr-read"): EventGenerator<boolean> {
switch (mode) {
case "mem-read": {
yield { type: "cpu:rd.on" };
const value = yield* this.computer.memory.read(this.#MAR);
if (!value) return false; // Error reading from memory
this.#MBR = value;
yield { type: "bus:reset" };
return true;
}
case "mem-write": {
yield { type: "cpu:wr.on" };
const success = yield* this.computer.memory.write(this.#MAR, this.#MBR);
if (!success) return false; // Error writing to memory
yield { type: "bus:reset" };
return true;
}
case "io-read": {
yield { type: "cpu:iom.on" };
const register = yield* this.computer.io.chipSelect(this.#MAR.low);
if (!register) return false; // Error selecting i/o register
yield { type: "cpu:rd.on" };
const value = yield* this.computer.io.read(register);
if (!value) return false; // Error reading from i/o
this.#MBR = value;
yield { type: "bus:reset" };
return true;
}
case "io-write": {
yield { type: "cpu:iom.on" };
const register = yield* this.computer.io.chipSelect(this.#MAR.low);
if (!register) return false; // Error selecting i/o register
yield { type: "cpu:wr.on" };
const success = yield* this.computer.io.write(register, this.#MBR);
if (!success) return false; // Error writing to i/o
yield { type: "bus:reset" };
return true;
}
case "intr-read": {
if (!this.computer.io.pic) return false; // Error reading from pic (no pic)
const intn = yield* this.computer.io.pic.handleINTR();
this.#MBR = intn;
yield { type: "bus:reset" };
return true;
}
default: {
const _exhaustiveCheck: never = mode;
return _exhaustiveCheck;
}
}
}
// #=========================================================================#
// # Stack methods #
// #=========================================================================#
/**
* Pushes a value to the stack, and updates the SP register.
* This value should have been previously written to the id register.
* @see {@link https://vonsim.github.io/en/computer/cpu#stack}
* @param value The value to push to the stack.
* @returns Whether the operation was successful.
*
* ---
* Called by the instructions ({@link InstructionType.execute}).
*/
*pushToStack(): EventGenerator<boolean> {
let SP = this.getRegister("SP");
if (!MemoryAddress.inRange(SP.unsigned - 1)) {
yield { type: "cpu:error", error: new SimulatorError("stack-overflow") };
return false;
}
SP = SP.add(-1);
yield* this.updateWordRegister("SP", SP);
yield* this.setMAR("SP");
yield* this.setMBR("id.h");
if (!(yield* this.useBus("mem-write"))) return false; // Error writing to memory
if (!MemoryAddress.inRange(SP.unsigned - 1)) {
yield { type: "cpu:error", error: new SimulatorError("stack-overflow") };
return false;
}
SP = SP.add(-1);
yield* this.updateWordRegister("SP", SP);
yield* this.setMAR("SP");
yield* this.setMBR("id.l");
if (!(yield* this.useBus("mem-write"))) return false; // Error writing to memory
return true;
}
/**
* Pops a value from the stack, and updates the SP register.
* This value will be written to the id register.
* @see {@link https://vonsim.github.io/en/computer/cpu#stack}
* @returns Whether the operation was successful.
*
* ---
* Called by the instructions ({@link InstructionType.execute}).
*/
*popFromStack(): EventGenerator<boolean> {
let SP = this.getRegister("SP");
if (!MemoryAddress.inRange(SP)) {
yield { type: "cpu:error", error: new SimulatorError("stack-underflow") };
return false;
}
yield* this.setMAR("SP");
if (!(yield* this.useBus("mem-read"))) return false; // Error reading memory
yield* this.getMBR("id.l");
SP = SP.add(1);
yield* this.updateWordRegister("SP", SP);
if (!MemoryAddress.inRange(SP)) {
yield { type: "cpu:error", error: new SimulatorError("stack-underflow") };
return true;
}
yield* this.setMAR("SP");
if (!(yield* this.useBus("mem-read"))) return false; // Error reading memory
yield* this.getMBR("id.h");
SP = SP.add(1);
yield* this.updateWordRegister("SP", SP);
return true;
}
}