Blame view

main.c 1.93 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
#include "disasm.h"
7
8
uint32_t load_program(const char* path)
9
10
11
12
13
14
15
{
    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);
16
    return (uint32_t)file_size/2;
17
}
Imanol-Mikel Barba Sabariego authored
18
19
void initializevm(char *program)
Imanol-Mikel Barba Sabariego authored
20
{
21
    initialize_stack();
22
23
    memset(regs,0x00,sizeof(uint16_t)*NUM_REGISTERS);
    memset(mem,0x00,sizeof(uint16_t)*MEMSIZE);
24
    load_program(program);
25
26
27
28
29
}

void startvm(char *program)
{
    initializevm(program);
30
31
    start_execution();
    free_stack();
32
33
34
35
}

void disasm(char *program)
{
36
    stderr = stdout;
37
38
39
40
41
    disassemble_program(load_program(program));
}

void debug(char *program)
{
42
    initializevm(program);
43
44
45
46
47
48
49
50
51
52
    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;
53
54
    char *program = NULL;
    while ((c = (char)getopt(argc, argv, "s:d:")) != -1)
55
56
57
58
59
60
61
62
63
64
65
66
    {
        switch(c)
        {
            case 'd':
                debug_flag = 1;
                program = optarg;
                break;
            case 's':
                disasm_flag = 1;
                program = optarg;
                break;
            case '?':
67
            default:
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
                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
99
    return 0;
100
}