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
|
#include "all.h"
#include <stdbool.h>
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main(int argc, char *argv[]) {
bool dump_c = false;
bool dump_ast = false;
for (int i = 1; i < argc; i++) {
if (strcmp("-cd", argv[i]) == 0) {
dump_c = true;
}
if (strcmp("-ad", argv[i]) == 0) {
dump_ast = true;
}
}
str input = {0};
str_append_fread(&input, stdin);
// Run the parser and turn tokens into an AST representation
ast_node_t *ast = parse(input.data);
ast = optimize_ast(ast);
if (dump_ast)
ast_dump(ast, 0);
str c_code = gen_code(ast);
if (dump_c)
fprintf(stderr, "%s\n", c_code.data);
// Run gcc
int fd[2];
pipe(fd);
if (fork() == 0) {
dup2(fd[0], STDIN_FILENO);
close(fd[0]);
close(fd[1]);
char *argv[] = {"gcc",
"-Os",
"-flto",
"-fuse-linker-plugin",
"-DNDEBUG",
"-fomit-frame-pointer",
"-nostdlib",
"-nostartfiles",
"-ffreestanding",
"-no-pie",
"-fno-stack-protector",
"-o",
"/proc/self/fd/1",
"-x",
"c",
"-",
NULL};
execvp("gcc", argv);
perror("execvp");
_exit(1);
}
// Cleanup
close(fd[0]);
write(fd[1], c_code.data, strlen(c_code.data));
close(fd[1]);
int status;
wait(&status);
if (WIFEXITED(status)) {
int code = WEXITSTATUS(status);
if (code != 0) {
fprintf(stderr, "GCC failed with exit code %d\n", code);
fprintf(stderr, "Dumping C code:\n%s\n", c_code.data);
}
} else if (WIFSIGNALED(status)) {
fprintf(stderr, "GCC killed by signal %d\n", WTERMSIG(status));
} else {
fprintf(stderr, "GCC died in an unknown and mysterious way\n");
}
ast_free(ast);
free_str(&input);
return 0;
}
|