-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathemulator.c
80 lines (63 loc) · 1.68 KB
/
emulator.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
72
73
74
75
76
77
78
79
80
#include "instructions_info.h"
#include "virtual_machine.h"
#include <string.h>
#define MAX_BUFFER_SIZE 30
int PROGRAM_SIZE;
int LOAD_ADDRESS;
int loadProgram(char *fileName){
char line[MAX_BUFFER_SIZE];
FILE *file = fopen(fileName, "r");
if(file == NULL){
printf("arquivo nao encontrado\n");
return 0;
}
if(fgets(line, MAX_BUFFER_SIZE, file) == NULL){
printf("erro ao ler arquivo\n");
return 0;
}
line[strlen(line) - 1] = '\0';
if(strcmp(line, "MV-EXE") != 0){
printf("formato nao executavel\n");
return 0;
}
fscanf(file, "%d %d %d %d", &PROGRAM_SIZE, &LOAD_ADDRESS, &AP, &PC);
// carregar programa para memoria
int i, currentAddress;
currentAddress = LOAD_ADDRESS;
while(currentAddress - LOAD_ADDRESS < PROGRAM_SIZE && !feof(file)){
fscanf(file, "%d", &i);
MEMORY[currentAddress] = i;
currentAddress ++;
}
fclose(file);
return 1;
}
int main(int argc, char *argv[]){
char *fileName;
int instruction;
int *operands;
DEBUG_MODE = 0;
if(argc == 2){
fileName = argv[1];
}
else if(argc == 3){
if(strcmp(argv[1], "-v") == 0){
DEBUG_MODE = 1;
fileName = argv[2];
}
else if(strcmp(argv[2], "-v") == 0){
DEBUG_MODE = 1;
fileName = argv[1];
}
}
if(!loadProgram(fileName)){
return 1;
}
while(PC <= LOAD_ADDRESS + PROGRAM_SIZE){
instruction = MEMORY[PC];
operands = &MEMORY[PC + 1];
PC += INSTRUCTION_NUMBER_OF_OPERANDS[instruction] + 1;
execute(instruction, operands);
}
return 0;
}