-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.c
71 lines (55 loc) · 1.48 KB
/
main.c
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
#include <stdlib.h>
#include <stdio.h>
#include <sys/stat.h>
#include <string.h>
#include "vm.h"
#include "exe.h"
int main(int argc, char** argv) {
// Check for the filename
if (argc <= 1) {
fprintf(stderr, "Missing filename\n");
return 1;
}
FILE* fp;
fp = fopen(argv[1], "r");
if (fp == NULL) {
fprintf(stderr, "Could not open file: %s\n", argv[1]);
return 1;
}
struct stat inputStat;
if (fstat(fileno(fp), &inputStat) < 0) {
fprintf(stderr, "Could not stat file: %s\n", argv[1]);
return 1;
}
uint8_t* buffer = malloc(inputStat.st_size);
if (buffer == NULL) {
fprintf(stderr, "Could not allocate space for executable\n");
return 1;
}
fread(buffer, inputStat.st_size, 1, fp);
Executable* exe;
ExecutableError err = exe_create(&exe, buffer, inputStat.st_size);
if (err != exe_err_success) {
fprintf(stderr, "Could not parse executable: %s\n", exe_err(err));
return 1;
}
VM* vm;
VMError create_result = vm_create(&vm);
if (create_result != vm_err_regular_exit) {
fprintf(stderr, "Could not initialize vm\n");
fprintf(stderr, "Reason: %s\n", vm_err(create_result));
return 1;
}
VMError flash_result = vm_flash(vm, exe);
if (flash_result != vm_err_regular_exit) {
fprintf(stderr, "Could not load executable\n");
fprintf(stderr, "Reason: %s\n", vm_err(flash_result));
return 1;
}
int exit_code;
vm_run(vm, &exit_code);
vm_clean(vm);
exe_clean(exe);
fclose(fp);
return exit_code;
}