Skip to content
Open
Show file tree
Hide file tree
Changes from 5 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
44 changes: 42 additions & 2 deletions ls8/cpu.c
Original file line number Diff line number Diff line change
@@ -1,7 +1,18 @@
#include "cpu.h"

#include <stdio.h>
#include <string.h>
#define DATA_LEN 6

unsigned char cpu_ram_read(struct cpu *cpu, unsigned char address)
{
return cpu->ram[address];
}

void cpu_ram_write(struct cpu *cpu, unsigned char address, unsigned char value)
{
cpu->ram[address] = value;
}

/**
* Load the binary bytes from a .ls8 source file into a RAM array
*/
Expand Down Expand Up @@ -50,9 +61,36 @@ void cpu_run(struct cpu *cpu)
while (running) {
// TODO
// 1. Get the value of the current instruction (in address PC).
unsigned char ir = cpu_ram_read(cpu, cpu->PC);
// 2. Figure out how many operands this next instruction requires
// 3. Get the appropriate value(s) of the operands following this instruction
unsigned char operandA = cpu_ram_read(cpu, cpu->PC + 1);
unsigned char operandB = cpu_ram_read(cpu, cpu->PC + 2);
// 4. switch() over it to decide on a course of action.
switch (ir)
{
case LDI:
{
cpu->registers[operandA] = operandB;
cpu->PC += 3;
break;
}
case PRN:
{
printf("%d\n", cpu->registers[operandA]);
cpu->PC += 2;
break;
}
case HLT:
{
running = 0;
break;
}
default:
{
break;
}
}
// 5. Do whatever the instruction should do according to the spec.
// 6. Move the PC to the next instruction.
}
Expand All @@ -63,5 +101,7 @@ void cpu_run(struct cpu *cpu)
*/
void cpu_init(struct cpu *cpu)
{
// TODO: Initialize the PC and other special registers
cpu->PC = 0;
memset(cpu->ram, 0, 8 * sizeof(unsigned char));
memset(cpu->registers, 0, 256 * sizeof(unsigned char));
}
3 changes: 3 additions & 0 deletions ls8/cpu.h
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,11 @@
struct cpu {
// TODO
// PC
unsigned char PC;
// registers (array)
unsigned char registers[8];
// ram (array)
unsigned char ram[256];
};

// ALU operations
Expand Down