aboutsummaryrefslogtreecommitdiff
path: root/vm/main.c
blob: cb2c3fb12c9e87319294130e3a241b27f513e949 (plain)
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
/* Copyright (C) 2023 Aryadev Chavali

 * You may distribute and modify this code under the terms of the
 * GPLv2 license.  You should have received a copy of the GPLv2
 * license with this file.  If not, please write to:
 * aryadev@aryadevchavali.com.

 * Created: 2023-10-15
 * Author: Aryadev Chavali
 * Description: Entrypoint to program
 */

#include <assert.h>
#include <stdio.h>
#include <string.h>

#include "./runtime.h"
#include <lib/inst.h>

void usage(const char *program_name, FILE *out)
{
  fprintf(out,
          "Usage: %s [OPTIONS] FILE\n"
          "\t FILE: Bytecode file to execute\n"
          "\tOptions:\n"
          "\t\t To be developed...\n",
          program_name);
}

int main(int argc, char *argv[])
{
  if (argc == 1)
  {
    usage(argv[0], stderr);
    return 1;
  }
  const char *filename = argv[1];

#if VERBOSE >= 1
  printf("[%sINTERPRETER%s]: Interpreting `%s`\n", TERM_YELLOW, TERM_RESET,
         filename);
#endif

  FILE *fp             = fopen(filename, "rb");
  size_t number        = 0;
  inst_t *instructions = insts_read_bytecode_file(fp, &number);
  fclose(fp);

#if VERBOSE >= 1
  printf("\t[%sBYTECODE-READER%s]: Read %lu instructions\n", TERM_GREEN,
         TERM_RESET, number);
#endif

  size_t stack_size     = 256;
  byte *stack           = calloc(stack_size, 1);
  registers_t registers = {0};
  darr_init(&registers, 8 * WORD_SIZE);
  heap_t heap = {0};
  heap_create(&heap);

  vm_t vm = {0};
  vm_load_stack(&vm, stack, stack_size);
  vm_load_program(&vm, instructions, number);
  vm_load_registers(&vm, registers);
  vm_load_heap(&vm, heap);

#if VERBOSE >= 1
  printf("\t[%sVM-SETUP%s]: Loaded stack and program into VM\n", TERM_GREEN,
         TERM_RESET);
#endif
  err_t err = vm_execute_all(&vm);

  int ret = 0;
  if (err)
  {
    const char *error_str = err_as_cstr(err);
    fprintf(stderr, "[ERROR]: %s\n", error_str);
    vm_print_all(&vm, stderr);
    ret = 255 - err;
  }
  vm_stop(&vm);

#if VERBOSE >= 1
  printf("[%sINTERPRETER%s]: Finished execution\n", TERM_GREEN, TERM_RESET);
#endif
  return ret;
}