blob: be53a2200fe23b7789fd6ea0a8f1ac8bf3cc3e6a (
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
|
#include "drain.h"
#include "ops.h"
#include <stdio.h>
#include <stdint.h>
#define MEM_SIZE 0xffff
static uint16_t *stack = NULL;
static size_t stack_ptr = 0;
static uint16_t
get_short(const unsigned char *s)
{
return s[0] | (s[1] * 0x0100);
}
static void
push(uint16_t v)
{
stack[stack_ptr] = v;
stack_ptr += 1;
if (stack_ptr >= MEM_SIZE) {
fprintf(stderr, "stack overflow\n");
return;
}
}
static uint16_t
pop(void)
{
if (stack_ptr == 0) {
fprintf(stderr, "stack underflow\n");
return 0;
}
stack_ptr -= 1;
return stack[stack_ptr];
}
static void
exec_data(uint16_t *mem)
{
for (long pc = 0; pc < MEM_SIZE; pc++) {
switch (mem[pc]) {
case OP_NOP:
break;
case OP_LIT:
push(mem[pc + 1]);
pc += 1;
break;
case OP_WRT:
putchar(pop());
break;
case OP_RET:
return;
default:
fprintf(stderr, "unhandled opcode %04x\n", mem[pc]);
return;
}
}
}
int
main(int argc, char **argv)
{
if (argc != 2) {
fprintf(stderr, "usage: %s <rom>\n", argv[0]);
return 1;
}
FILE *file = fopen(argv[1], "rb");
if (file == NULL) {
perror(argv[1]);
return 1;
}
long size;
unsigned char *const data = (unsigned char*)drain(file, &size);
fclose(file);
if (data == NULL)
return 1;
uint16_t *mem = calloc(MEM_SIZE, sizeof(uint16_t));
if (mem == NULL) {
perror("main:calloc");
free(data);
return 1;
}
for (long i = 0; i < size; i += 2)
mem[i / 2] = get_short(data + i);
free(data);
stack = calloc(MEM_SIZE, sizeof(uint16_t));
if (stack == NULL) {
perror("main:calloc");
free(mem);
return 1;
}
exec_data(mem);
free(mem);
free(stack);
return 0;
}
|