-
Notifications
You must be signed in to change notification settings - Fork 1
/
example.c
104 lines (79 loc) · 2.21 KB
/
example.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
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 <stdio.h>
#include <string.h>
#include <assert.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include "back/amd64.h"
#include "front/brainfuck.h"
// TODO: Add an example with mremap
int main(int argc, const char **argv) {
bool debug = false;
// Check arguments
assert(argc > 1 && "Missing arguments");
const char *path = argv[1];
if (argc == 3) {
assert(!strcmp(argv[1], "--debug"));
debug = true;
path = argv[2];
}
FILE *file = stdin;
if (strcmp(path, "-")) {
file = fopen(argv[1], "rb");
assert(file != NULL && "Failed to open file");
}
// Open input file
In_Channel in;
in_init_file(&in, file);
// Init IR instruction pool
const size_t instrs_len = 4096;
Bfir_Instr instrs[instrs_len];
Bfir_Pool pool;
bfir_pool_init(&pool, instrs, instrs_len, NULL);
Bfir_Entry entry;
bfir_entry_init(&entry, "", &pool);
// Parse input to IR
brainfuck_front.parse_f(&in, &entry, NULL);
if (file != stdin) fclose(file);
// Init x86_64 backend
const size_t labels_len = 1024;
Label_Id labels[labels_len];
Label_Stack stack1;
label_stack_init(&stack1, labels, labels_len / 2);
Label_Stack stack2;
label_stack_init(&stack2, labels + labels_len / 2, labels_len / 2);
uint8_t cells[10000];
Amd64_Layout mem = {
.cells = (uint64_t)cells,
.getchar = (uint64_t)getchar,
.putchar = (uint64_t)putchar,
};
Amd64_Aux aux;
amd64_aux_init(&aux, &stack1, &stack2, &mem, AMD64_RELATIVE_CALL);
// Memory map buffer
const size_t mem_len = 4096;
void *mem_ptr = mmap(NULL, mem_len, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
if (mem_ptr == MAP_FAILED || mem_ptr == NULL) {
perror("mmap");
return 1;
}
Byte_Buffer buffer;
byte_buffer_init(&buffer, mem_ptr, mem_len);
Out_Channel out;
out_init_buffer(&out, &buffer);
// Emit x86_64 machine code
amd64_back.emit_f(&out, &entry, (void *)&aux);
if (debug) {
printf("Program compiled, %zu bytes emitted\n", buffer.len);
for (size_t i = 0; i < buffer.len; ++i) printf("%02x ", buffer.bytes[i]);
printf("\n\n");
}
// Execute compiled machine code
void (*func)() = mem_ptr;
func();
// Clean up buffer
munmap(mem_ptr, mem_len);
return 0;
}