Blame view

main.c 1.95 KB
Imanol-Mikel Barba Sabariego authored
1
#include <stdio.h>
2
#include <string.h>
3
#include <getopt.h>
4
5
#include "mem.h"
#include "stack.h"
6
7
#include "disasm.h"
#include "debug.h"
8
9
uint32_t load_program(const char* path)
10
11
12
13
14
15
16
{
    FILE *fp = fopen(path,"r");
    fseek(fp, 0L, SEEK_END);
    long file_size = ftell(fp);
    rewind(fp);
    fread(mem,1,(size_t)file_size,fp);
    fclose(fp);
17
    return file_size/2;
18
}
Imanol-Mikel Barba Sabariego authored
19
20
void startvm(char *program)
Imanol-Mikel Barba Sabariego authored
21
{
22
    initialize_stack();
23
24
    memset(regs,0x00,sizeof(uint16_t)*NUM_REGISTERS);
    memset(mem,0x00,sizeof(uint16_t)*MEMSIZE);
25
    load_program(program);
26
27
    start_execution();
    free_stack();
28
29
30
31
32
33
34
35
36
37
}

void disasm(char *program)
{
    disassemble_program(load_program(program));
}

void debug(char *program)
{
    initialize_stack();
38
39
    memset(regs,0x00,sizeof(uint16_t)*NUM_REGISTERS);
    memset(mem,0x00,sizeof(uint16_t)*MEMSIZE);
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
    load_program(program);
    debug_program();
    free_stack();
}

int main(int argc, char** argv)
{
    uint8_t debug_flag = 0;
    uint8_t disasm_flag = 0;
    uint8_t err = 0;
    char c;
    char *program;
    while ((c = getopt(argc, argv, "s:d:")) != -1)
    {
        switch(c)
        {
            case 'd':
                debug_flag = 1;
                program = optarg;
                break;
            case 's':
                disasm_flag = 1;
                program = optarg;
                break;
            case '?':
                err = 1;
                break;
        }
    }
    if(err)
    {
        fprintf(stderr,"Error parsing arguments\n");
        return 1;
    }
    else if(debug_flag && disasm_flag)
    {
        fprintf(stderr,"-d and -s are mutually exclusive\n");
        return 1;
    }
    else if(!(debug_flag || disasm_flag))
    {
        if(argc != 2)
        {
            fprintf(stderr,"No program specified\n");
            return 1;
        }
        startvm(argv[1]);
    }
    else if(debug_flag)
    {
        debug(program);
    }
    else if(disasm_flag)
    {
        disasm(program);
    }
Imanol-Mikel Barba Sabariego authored
96
    return 0;
97
}