aboutsummaryrefslogtreecommitdiff
path: root/tools/wasm_compile.c
blob: c45554176c3167e7a253e8cc98b4024e01e31aa2 (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
#include "wasm_compile.h"
#include "stack_machine_instruction.h"

void print_instructions(uint32_t count,
			struct translated_word memory[count])
{
	uint32_t i;
	char binary[17];
	uint16_t bits;
	int j;

	binary[16] = '\0';

	for (i = 0; i < count; i++) {
		bits = memory[i].contents;
		j = 16;

		while (j--) {
			binary[j] = (bits & 1) ? '1' : '0';
			bits >>= 1;
		}

		printf(binary);

		if (memory[i].instr) {
			printf(" // 0x%03lx %s", (long) i,
			       memory[i].instr->name);
		}

		putchar('\n');
	}
}

int main(int argc, char **argv)
{
	FILE *handle = NULL;
	struct module *module = NULL;
	struct translated_word *translated_instructions = NULL;
	char retval = -1;

	if (argc < 2) {
		PRERR("Please provide name of the file to parse on the command line\n");
		goto fail;
	}

	handle = fopen(argv[1], "r");

	if (!handle) {
		PRERR("Couldn't open '%s'\n", argv[1]);
		goto fail;
	}

	module = parse_module(handle);

	if (!module)
		goto fail;

	translated_instructions = calloc(1, CODE_TOP_ADDR *
					 sizeof(struct translated_word));

	if (!translated_instructions) {
		PRERR(MSG_ALLOC_FAIL(CODE_TOP_ADDR));
		goto fail;
	}

	if (assemble(CODE_TOP_ADDR / 2, translated_instructions, module))
		goto fail;

	print_instructions(CODE_TOP_ADDR / 2, translated_instructions);

	retval = 0;

fail:
	if (handle)
		fclose(handle);

	free_module(module);

	free(translated_instructions);

	return retval;
}