-
Notifications
You must be signed in to change notification settings - Fork 0
/
brainfuck.c
executable file
·346 lines (303 loc) · 7.76 KB
/
brainfuck.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
char *read(char *filename) {
FILE *fp;
int len;
char *code;
fp = fopen(filename, "r");
if(fp == NULL) goto error;
if(fseek(fp, 0, SEEK_END) == -1) goto error;
len = ftell(fp);
if(len == -1) goto error;
if(fseek(fp, 0, SEEK_SET) == -1) goto error;
code = malloc(len * sizeof(char) + 1);
if(code == NULL) goto error;
code[len] = '\0';
if(fread(code, len, 1, fp) == 0 && len != 0) goto error;
if(fclose(fp) == EOF) goto error;
return code;
error:
fprintf(stderr, "error: could not read %s: ", filename);
perror(NULL);
exit(1);
}
/* validates that all '[' have matching ']' and vice versa. */
void validate(char *code) {
/* the error reporting strategy is to report as early as
possible. */
int bracketDepth = 0;
int currentLine = 1;
int currentColumn = 1;
int uppermostLeftBracketLine = -1;
int uppermostLeftBracketColumn = -1;
int codeIndex = 0;
for(; code[codeIndex] != '\0';) {
switch(code[codeIndex]) {
case '[':
if(bracketDepth == 0) {
uppermostLeftBracketLine = currentLine;
uppermostLeftBracketColumn = currentColumn;
}
bracketDepth++;
break;
case ']':
if(bracketDepth == 0) {
fprintf(stderr, "error: %d. char in %d. line is an unmatched ']'\n", currentColumn, currentLine);
exit(1);
}
bracketDepth--;
break;
case '\n':
currentLine++;
currentColumn = 0;
break;
}
codeIndex++;
currentColumn++;
}
if(bracketDepth != 0) {
fprintf(stderr, "error: %d. char in %d. line is an unmatched '['\n", uppermostLeftBracketColumn, uppermostLeftBracketLine);
exit(1);
}
}
void compile_to_x64(char *code, char *target_filename) {
FILE *fp;
/* adhoc stack solution since it only works for 1024 elements, oh well.*/
int leftBracketIdStack[1024];
int topLeftBracketIdIndex = -1;
int nextLeftBracketId = 0;
int codeIndex = 0;
fp = fopen(target_filename,"w");
if(fp == NULL) goto error;
if(fputs(
"section .bss\n"
"\tbuffer: resb 30000\n"
"global _start\n"
"section .text\n"
"_start:\n"
"\tmov r15, buffer\n"
,fp) == EOF) goto error;
for(; code[codeIndex] != '\0'; codeIndex++) {
switch(code[codeIndex]) {
case '>':
if(fputs("\tinc r15\n", fp) == EOF) goto error;
break;
case '<':
if(fputs("\tdec r15\n", fp) == EOF) goto error;
break;
case '+':
if(fputs("\tinc byte [r15]\n", fp) == EOF) goto error;
break;
case '-':
if(fputs("\tdec byte [r15]\n", fp) == EOF) goto error;
break;
case '.':
if(fputs(
"\tmov rax, 1\n"
"\tmov rdi, 1\n"
"\tmov rsi, r15\n"
"\tmov rdx, 1\n"
"\tsyscall\n"
, fp) == EOF) goto error;
break;
case ',':
if(fputs(
"\tmov rax, 0\n"
"\tmov rdi, 0\n"
"\tmov rsi, r15\n"
"\tmov rdx, 1\n"
"\tsyscall\n"
, fp) == EOF) goto error;
break;
case '[':
if(0 > fprintf(fp,
"\tcmp byte [r15], 0\n"
"\tje .rightbracket%d\n"
"\t.leftbracket%d:\n"
, nextLeftBracketId, nextLeftBracketId)) goto error;
topLeftBracketIdIndex++;
leftBracketIdStack[topLeftBracketIdIndex] = nextLeftBracketId;
nextLeftBracketId++;
break;
case ']':
if(0 > fprintf(fp,
"\tcmp byte [r15], 0\n"
"\tjne .leftbracket%d\n"
"\t.rightbracket%d:\n"
, leftBracketIdStack[topLeftBracketIdIndex], leftBracketIdStack[topLeftBracketIdIndex])) goto error;
topLeftBracketIdIndex--;
break;
}
}
if(fputs(
"\tmov rax, 60\n"
"\tmov rdi, 0\n"
"\tsyscall\n"
, fp) == EOF) goto error;
if(fclose(fp) == EOF) goto error;
return;
error:
fprintf(stderr, "error: could not write to %s: ", target_filename);
perror(NULL);
exit(1);
}
void compile_to_c89(char *code, char *target_filename) {
FILE *fp;
/* adhoc stack solution since it only works for 1024 elements, oh well.*/
int leftBracketIdStack[1024];
int topLeftBracketIdIndex = -1;
int nextLeftBracketId = 0;
int codeIndex = 0;
fp = fopen(target_filename,"w");
if(fp == NULL) goto error;
if(fputs(
"#include <stdio.h>\n"
"\n"
"char buf[30000];\n" /* since this is a global variable we don't need to manually set all elements to 0 */
"int i = 0;\n"
"\n"
"int main() {\n"
,fp) == EOF) goto error;
for(; code[codeIndex] != '\0'; codeIndex++) {
switch(code[codeIndex]) {
case '>':
if(fputs("\ti++;\n", fp) == EOF) goto error;
break;
case '<':
if(fputs("\ti--;\n", fp) == EOF) goto error;
break;
case '+':
if(fputs("\tbuf[i]++;\n", fp) == EOF) goto error;
break;
case '-':
if(fputs("\tbuf[i]--;\n", fp) == EOF) goto error;
break;
case '.':
if(fputs("\tputchar(buf[i]);\n", fp) == EOF) goto error;
break;
case ',':
if(fputs("\tbuf[i] = getchar();\n", fp) == EOF) goto error;
break;
case '[':
if(0 > fprintf(fp,
"\tif(buf[i] == 0) goto right%d;\n"
"\tleft%d:\n"
, nextLeftBracketId, nextLeftBracketId)) goto error;
topLeftBracketIdIndex++;
leftBracketIdStack[topLeftBracketIdIndex] = nextLeftBracketId;
nextLeftBracketId++;
break;
case ']':
if(0 > fprintf(fp,
"\tif(buf[i] != 0) goto left%d;\n"
"\tright%d:\n"
, leftBracketIdStack[topLeftBracketIdIndex], leftBracketIdStack[topLeftBracketIdIndex])) goto error;
topLeftBracketIdIndex--;
break;
}
}
if(fputs(
"\treturn 0;\n" /* return is required as otherwise we risk having a label at the end of main. (which is illegal) */
"}\n"
, fp) == EOF) goto error;
if(fclose(fp) == EOF) goto error;
return;
error:
fprintf(stderr, "error: could not write to %s: ", target_filename);
perror(NULL);
exit(1);
}
void interpret(char *code) {
char memory[30000];
char *p;
int bracketDepth;
for(p = memory; p < memory + 30000; p++) *p = 0;
p = memory;
/* bracketDepth is equal to n - m where n is the number of '[' read
and m is the number of ']' read. */
bracketDepth = 0;
for(code++; *code != '\0'; code++) {
switch(*code) {
case '>':
p++;
break;
case '<':
p--;
break;
case '+':
(*p)++;
break;
case '-':
/* BUG: this line segfaults when ran with
http://brainfuck.org/400quine.b. The segfault only occurs
when the program is ran outside of gdb or inside of gdb with
`set disable-randomization off`. If it is ran inside of gdb
without setting disable-randomization it works fine. */
(*p)--;
break;
case '.':
putchar(*p);
break;
case ',':
*p = getchar();
break;
case '[': {
int originalBracketDepth = bracketDepth;
bracketDepth++;
if(*p == 0) {
code++;
for(;;) {
if(*code == '[') bracketDepth++;
else if(*code == ']') bracketDepth--;
if(bracketDepth == originalBracketDepth) break;
code++;
}
}
break;
}
case ']': {
int originalBracketDepth = bracketDepth;
bracketDepth--;
if(*p != 0) {
code--;
for(;;) {
if(*code == '[') bracketDepth++;
else if(*code == ']') bracketDepth--;
if(bracketDepth == originalBracketDepth) break;
code--;
}
}
}
}
}
}
void exit_with_usage() {
fputs("usage: brainfuck interpret source\n"
" brainfuck c89 source target\n"
" brainfuck x64 source target\n"
, stderr);
exit(1);
}
int main(int argc, char** argv) {
char *code;
void (*compile)(char *, char *);
if(argc == 3 && strcmp(argv[1], "interpret") == 0) {
code = read(argv[2]);
validate(code);
interpret(code);
return 0;
}
if(argc != 4) exit_with_usage();
if(strcmp(argv[1], "x64") == 0) {
compile = compile_to_x64;
} else if(strcmp(argv[1], "c89") == 0) {
compile = compile_to_c89;
} else {
exit_with_usage();
}
code = read(argv[2]);
validate(code);
compile(code, argv[3]);
return 0;
}