C Virtual machine Command with same opcode

161 views Asked by At

Im attempting to put together a basic C Virtual machine that will read a binary file from an assembler program and use that file to execute commands based on the binary data in that file. Im at the point where i need to decode values into its hex format and then use these to determine opcode and execution operations. This is the part im confused on how to work around this? I have the registers and instructions defined but im wondering how i am to use the Fetch function to read the "instruction bytes" from memory and then decode to populate OP1 and/or OP2 in order to determine what command is to be done, what has me confused is with a command like pop push and return for within this example they all have the same starting opcode of 7 and differ only in the latter 2 bytes of push being 40 pop being 80 and return being 00. How can i pass all the 4-8 bytes of a command into fetch and be able to determine the command to be executed?

MAIN.C

#include <stdio.h>
#include <stdbool.h>
#include <stdlib.h>

unsigned char memory[1028];

typedef enum{
    halt,
    add,
    and,
    divide,
    mult,
    sub,
    or,
    popushret,
    interrupt,
    addimmediate,
    branchifequal,
    branchifless,
    jump,
    call,
    load,
    store
} Instructions;

typedef enum{
    R1, R2, R3, R4, R5, R6, R7, R8, R9, R10, R11, R12, R13, R14, R15, R16,
    PC,
    OP1, OP2,
    Result,
    CIP,
} Registers;

void decode( ) { // Read only from the array of bytes from fetch. Populate the OP1 and OP2 registers if appropriate. Fetch any additional memory needed to complete the instruction.

}

void fetch(int memory){ // Read instruction bytes from memory. 
    printf("%02x\n", memory);

}
int loads(char *filename){
     FILE *file = fopen(filename, "rb");
     ssize_t read;
     if(file == NULL){
         exit(-1);
     }

     while(fread(&memory, sizeof(unsigned char), 1, file) == 1){
        fetch(*memory);
     }
    fclose(file);
    exit(0);
}

int main(int argc, char** argv){
    if (argc <= 1){
        printf("No file found\n");
        return -1;
    }

    char *filename = argv[1];

    loads(filename);
}

INPUT.txt

74
40
77
40
11
23

OUTPUT.TXT

Desired output from the above is to push 4 to stack, push 7 to stack, pop 7 into R2 and 4 into R1 and the and add both into R3 and store in result
0

There are 0 answers