compiler, vm - Corrected ASCII, UNICODE format issues
[hwframework.git] / hwvm.c
blob6f4d71197ce05a1ca9a5fc270112911576de50b0
1 #include "vm.h"
3 #include <stdarg.h>
4 #include <stdio.h>
5 #include <stdlib.h>
7 static void start_vm(FILE *, const HwHeader *);
8 static void execute_opcode(uint8_t);
9 static void vm_error(const char *, ...);
11 int
12 main(int argc, char **argv)
14 FILE *file;
15 HwHeader head;
17 if (argc == 1)
18 vm_error("No executable file!\n");
20 file = fopen(argv[1], "rt");
21 if (file == NULL)
22 vm_error("Cannot read file %s\n", argv[1]);
24 fread(&head, sizeof(HwHeader), 1, file);
26 if (head.hw_magic != HW_HEADER_MAGIC)
27 vm_error("File is corrupted or not a valid application!\n");
29 start_vm(file, &head);
30 return 0;
33 static void
34 start_vm(FILE *file, const HwHeader *head)
36 uint8_t *text_segment;
37 int i;
38 text_segment = (uint8_t *)malloc(sizeof(uint8_t) * head->hw_instr_count);
40 if (text_segment == NULL)
41 vm_error("Cannot allocate text segment\n");
43 fread(text_segment, sizeof(uint8_t), head->hw_instr_count, file);
45 for (i = 0; i < head->hw_instr_count; i++) {
46 execute_opcode(text_segment[i]);
50 static void
51 execute_opcode(uint8_t opcode)
53 HwInstruction *inst;
54 int i;
56 for (i = 0; i < LAST_INSTRUCTION; i++) {
57 inst = &instructions[i];
58 if (opcode == inst->i_opcode) {
59 printf("%s", inst->i_data);
64 static void
65 vm_error(const char *fmt, ...)
67 va_list ap;
68 va_start(ap, fmt);
69 fprintf(stderr, "HW Virtual Machine - (C) Akos Kovacs\n\nError: ");
70 vfprintf(stderr, fmt, ap);
71 va_end(ap);
72 exit(1);