main.c
1.93 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
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
96
97
98
99
100
#include <stdio.h>
#include <string.h>
#include <getopt.h>
#include "mem.h"
#include "stack.h"
#include "disasm.h"
uint32_t load_program(const char* path)
{
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);
return (uint32_t)file_size/2;
}
void initializevm(char *program)
{
initialize_stack();
memset(regs,0x00,sizeof(uint16_t)*NUM_REGISTERS);
memset(mem,0x00,sizeof(uint16_t)*MEMSIZE);
load_program(program);
}
void startvm(char *program)
{
initializevm(program);
start_execution();
free_stack();
}
void disasm(char *program)
{
stderr = stdout;
disassemble_program(load_program(program));
}
void debug(char *program)
{
initializevm(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 = NULL;
while ((c = (char)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 '?':
default:
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);
}
return 0;
}