summaryrefslogtreecommitdiff
path: root/skullfuck.c
blob: 0f5819854980bd54e5d0484126e21cf3a208221e (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
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
/* Skullfuck -- A dead simple, non-optimizing Brainfuck compiler.

   Copyright (C) 2017 Jakob Kreuze, All Rights Reserved.

   Skullfuck is free software: you can redistribute it and/or modify it
   under the terms of the GNU General Public License as published by the
   Free Software Foundation, either version 3 of the License, or (at
   your option) any later version.

   Skullfuck is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with Skullfuck. If not, see <http://www.gnu.org/licenses/>. */

#include <sys/types.h>
#include <sys/wait.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#include <getopt.h>


#ifdef x86_64
#define INC_DATA_PTR "\tincq %rsi\n"
#define DEC_DATA_PTR "\tdecq %rsi\n"
#define INC_DATA     "\tincb (%rsi)\n"
#define DEC_DATA     "\tdecb (%rsi)\n"
#define PRINT_DATA   "\tmovq $0x01, %rax\n" \
                     "\tmovq $0x01, %rdi\n" \
                     "\tsyscall\n"
#define READ_DATA    "\tmovq $0x00, %rax\n" \
                     "\tmovq $0x00, %rdi\n" \
                     "\tsyscall\n"
#define DATA_IS_ZERO "\tmovb (%rsi), %cl\n" \
                     "\ttestb %cl, %cl\n"
#define JMP_END      "\tjz E%d\n"
#define JMP_START    "\tjnz S%d\n"

#define PRELUDE      "\t.section .bss\n" \
                     "\t.comm mem, %d\n" \
                     "\t.section .text\n" \
                     "\t.globl _start\n" \
                     "_start:\n" \
                     "\tmovq $mem, %%rsi\n" \
                     "\tmovq $0x01, %%rdx\n"

#define EXIT         "\tmovq $0x3c, %rax\n" \
                     "\tmovq $0x00, %rdi\n" \
                     "\tsyscall\n"
#endif


#ifdef i686
#define INC_DATA_PTR "\tincl %ecx\n"
#define DEC_DATA_PTR "\tdecl %ecx\n"
#define INC_DATA     "\tincb (%ecx)\n"
#define DEC_DATA     "\tdecb (%ecx)\n"
#define PRINT_DATA   "\tmovl $0x04, %eax\n" \
                     "\tmovl $0x01, %ebx\n" \
                     "\tint $0x80\n"
#define READ_DATA    "\tmovl $0x03, %eax\n" \
                     "\tmovl $0x00, %ebx\n" \
                     "\tint $0x80\n"
#define DATA_IS_ZERO "\tmovb (%ecx), %al\n" \
                     "\ttestb %al, %al\n"
#define JMP_END      "\tjz E%d\n"
#define JMP_START    "\tjnz S%d\n"

#define PRELUDE      "\t.section .bss\n" \
                     "\t.comm mem, %d\n" \
                     "\t.section .text\n" \
                     "\t.globl _start\n" \
                     "_start:\n" \
                     "\tmovl $mem, %%ecx\n" \
                     "\tmovl $0x01, %%edx\n"

#define EXIT         "\tmovl $0x01, %eax\n" \
                     "\tmovl $0x00, %ebx\n" \
                     "\tint $0x80\n"
#endif

#ifndef AS
#define AS /bin/as
#endif

#ifndef LD
#define LD /bin/ld
#endif

#define MAX_CELLS      30000
#define MAX_LOOP_DEPTH 64

#define SKULLFUCK_VERSION "0.2.0"

#define EXIT_SUCCESS 0
#define EXIT_FAILURE 1



/* Structure for storing runtime parameters. */
struct params {
    bool compile_only;
    char *in, *out, *as;
};


/* A stack data structure for storing loop depth. */
struct loop_stack {
    int _mem[MAX_LOOP_DEPTH];
    int _stack_index;
};

/* Pushes `n` onto the stack specified by `s`. */
static void push_loop_index(struct loop_stack *s, int n) {
    s->_mem[s->_stack_index] = n;
    s->_stack_index++;
}

/* Pops the top of `s` off and returns it. */
static int pop_loop_index(struct loop_stack *s) {
    s->_stack_index--;
    return s->_mem[s->_stack_index];
}


/* Converts the brainfuck instructions read from `in` to assembly
   instructions and writes them to `out`. `in` is expected to be
   null-terminated. */
static void write_instructions(FILE *out, char *in) {
    int               next_loop = 0, cur_loop = 0;
    struct loop_stack *loops = calloc(sizeof(struct loop_stack), 1);

    for (int i = 0; in[i] != '\0'; i++) {
        switch (in[i]) {
            case '>':
                fputs(INC_DATA_PTR, out);
                break;
            case '<':
                fputs(DEC_DATA_PTR, out);
                break;
            case '+':
                fputs(INC_DATA, out);
                break;
            case '-':
                fputs(DEC_DATA, out);
                break;
            case '.':
                fputs(PRINT_DATA, out);
                break;
            case ',':
                fputs(READ_DATA, out);
                break;
            case '[':
                cur_loop = next_loop;
                push_loop_index(loops, next_loop++);
                fprintf(out, "S%d:\n", cur_loop);
                fputs(DATA_IS_ZERO, out);
                fprintf(out, JMP_END, cur_loop);
                break;
            case ']':
                cur_loop = pop_loop_index(loops);
                fprintf(out, "E%d:\n", cur_loop);
                fputs(DATA_IS_ZERO, out);
                fprintf(out, JMP_START, cur_loop);
                break;
        }
    }

    fputs(EXIT, out);
    free(loops);
}


/* Prints error information and terminates with minimal cleanup. */
static void panic(char *msg) {
    perror(msg);
    fprintf(stderr, "Fatal error encountered. Terminating!\n");
    exit(EXIT_FAILURE);
}


/* Attempts to create a new file at `path`, and writes a boilerplate
   prelude to initialize memory segments and load some registers with
   constant values. A FILE pointer will be returned, or NULL if the file
   could not be created. */
static FILE *out_init(char *path) {
    FILE *fp = fopen(path, "w+");
    if (fp == NULL) return fp;
    fprintf(fp, PRELUDE, MAX_CELLS);
    return fp;
}


/* Returns a buffer containing the contents of `path`. */
static char *read_infile(char *path) {
    FILE *fp = fopen(path, "r");
    if (fp == NULL) panic(path);
    fseek(fp, 0, SEEK_END);
    size_t len = ftell(fp);
    char   *in = malloc(len);
    fseek(fp, 0, SEEK_SET);
    fread(in, len, 1, fp);
    fclose(fp);
    return in;
}


/* Assembles and links the compiled source code into a binary. */
static void create_binary(struct params p) {
    pid_t        pid;
    char  *const as_argv[] = {"as", "-o", "/tmp/skullfuck_tmp.o", p.as, NULL};
    char  *const ld_argv[] = {"ld", "-o", p.out, "/tmp/skullfuck_tmp.o", NULL};

    if ((pid = fork()) == -1) {
        panic("fork");
    } else if (pid == 0) {
        execv(AS, as_argv);
    } else {
        wait(NULL);
        if ((pid = fork()) == -1) {
            panic("fork");
        } else if (pid == 0) {
            execv(LD, ld_argv);
        } else {
            wait(NULL);
        }
    }
}


/* Parses command-line arguments into a params structure. */
static struct params parse_args(int argc, char **argv) {
    struct params p = {0};

    if (argc < 2) {
        fprintf(stderr, "USAGE: %s [options] (infile)\n", argv[0]);
        exit(EXIT_FAILURE);
    }

    int cur = 0, opt_index = 0, count = 0;
    static struct option long_opts[] = {
        {"help", no_argument, NULL, 'h'},
        {"version", no_argument, NULL, 'v'},
        {NULL, 0, NULL, 0}
    };

    do {
        count++;
        cur = getopt_long(argc, argv, "hvSo:", long_opts, &opt_index);
        switch (cur) {
            case 'h':
                printf("A dead simple, non-optimizing Brainfuck compiler.\n\n"
                       "\t-h, --help\tDisplay this help page and exit.\n"
                       "\t-v, --version\tDisplay versioning information and "
                       "exit\n\n"
                       "\t-S\t\tStop after the stage of compilation proper; "
                       "do not assemble.\n"
                       "\t-o file\t\tPlace the output in file.\n");
                exit(EXIT_SUCCESS);
            case 'v':
                printf("Skullfuck compiler for Brainfuck, version %s.\nMade "
                       "by Jakob. <http://jakob.space>\n", SKULLFUCK_VERSION);
                exit(EXIT_SUCCESS);
            case 'S':
                p.compile_only = true;
                break;
            case 'o':
                count++;
                p.out = optarg;
                break;
        }
    } while (cur >= 0);

    if (count >= argc) {
        fprintf(stderr, "Fatal error: No input files.\n");
        exit(EXIT_FAILURE);
    }

    p.in = argv[count];

    p.as  = "/tmp/skullfuck_tmp.s";
    if (p.compile_only) {
        p.out = p.out == NULL ? "./out.s" : p.out;
        p.as = p.out;
    } else if (p.out == NULL) {
        p.out = "./a.out";
    }

    return p;
}


int main(int argc, char **argv) {
    struct params p = parse_args(argc, argv);
    FILE          *fp = out_init(p.as);

    if (fp == NULL) panic(p.as);
    char *in = read_infile(p.in);
    write_instructions(fp, in);
    fclose(fp);

    if (!p.compile_only)
        create_binary(p);

    free(in);
    return EXIT_SUCCESS;
}