Add loading capability to interpreter
authorbylex <mbilek06@gmail.com>
Wed, 9 Oct 2024 12:33:11 +0000 (14:33 +0200)
committerbylex <mbilek06@gmail.com>
Wed, 9 Oct 2024 12:33:11 +0000 (14:33 +0200)
also change order in which instructions are loaded

interpreter.c

index a71abaca0d856c1d2c84d47603fb7f98392ae447..bbc27a2a27fc1aa4b11ff8ad41559cd929b3e621 100644 (file)
@@ -1,4 +1,6 @@
 #include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
 #include <stdint.h>
 
 #include "opcodes.h"
@@ -17,32 +19,39 @@ uint64_t instruction_counter = 0;
 
 
 
-void load_mem()
+void load_mem(char* file_name)
 {
-       mem[0] = (uint16_t)4 << 8 | 0;
-       mem[1] = 1234;
-
-       mem[2] = (uint16_t)4 << 8 | 1;
-       mem[3] = 1000;
-
-       mem[6] = (uint16_t)1 << 8 | 0;
-       mem[7] = (uint16_t)0 << 8 | 1;
-       
-       mem[8] = (uint16_t)9 << 8 | 0;
-       mem[9] = 0;
+       uint16_t current_addr = 0;
+       uint8_t* line_buffer = malloc(5);
+       FILE* input_file = fopen(file_name, "rb");
+       if(!input_file)
+       {
+               perror("Error opening input file");
+               exit(1);
+       }
+       while(fgets(line_buffer, 5, input_file))
+       {
+               memcpy(&(mem[current_addr]), line_buffer, 4);
+               current_addr = current_addr + 2;
+       }
 }
 
 
 
 int main(int argc, char *argv[])
 {
-       load_mem();
+       if(argc == 1)
+       {
+               fprintf(stderr, "No memory file!\n");
+               exit(1);
+       }
+       load_mem(argv[1]);
        while(!halted)
        {
-               uint8_t arg1 = (uint8_t)mem[current_instruction];
-               uint8_t instruction = (uint8_t)(mem[current_instruction] >> 8);
-               uint8_t arg3 = (uint8_t)mem[current_instruction + 1];
-               uint8_t arg2 = (uint8_t)(mem[current_instruction + 1] >> 8);
+               uint8_t instruction = (uint8_t)mem[current_instruction];
+               uint8_t arg1 = (uint8_t)(mem[current_instruction] >> 8);
+               uint8_t arg2 = (uint8_t)mem[current_instruction + 1];
+               uint8_t arg3 = (uint8_t)(mem[current_instruction + 1] >> 8);
                printf("Executing at 0x%04x; Instruction number %ld\r", current_instruction, instruction_counter);
                fflush(stdout);
                (*opcodes[instruction]) (arg1, arg2, arg3);