/*8==================================D~~~~* * BrainFuck Interpreter * * v0.5 * /\ *8==================================D~~~~* /4/ * Written by poutine/DALnet * /1/ * 2008-02-05 * /./ *8==================================D~~~~* /5/ .*. /$/ |*| \/ |*|/ |*| / * \ >+++++++++++[<+++++>-]<+++.[-]> /_/.\_\ >++++++++++[<++++>-]<+.[-] / . . \ +++++[<++>-]<.[-] |. . | |_______| |Sea | NOTES: |Monkeys| * Can do 30K slots or more | ____ | |/o~~ \ | || o~~| | ||o~~ | | |\____/ | |_______| (_______) */ #include #include #include void parse_brainfuck_file(FILE *bf) { unsigned char *bfprogram = NULL; unsigned char *eip = NULL; unsigned char *slots = NULL; unsigned char *ptr = NULL; size_t slotsize = 0; size_t slotindex = 0; size_t ret = 0; size_t i = 0; if ((bfprogram = malloc(1024)) == NULL) { printf("Could not allocate memory for brainfuck code, barfing.\n"); exit(EXIT_FAILURE); } for(i=0;(ret = fread(&bfprogram[(i) ? (i*1024)-1 : 0],1,1024,bf)) == 1024;i++) { if ((bfprogram = realloc(bfprogram,(i*1024)+1024+1024)) == NULL) { printf("Could not allocate memory for brainfuck code, barfing.\n"); exit(EXIT_FAILURE); } } if (!feof(bf)) { printf("Error during file read\n"); exit(EXIT_FAILURE); } bfprogram[(i*1024)+ret+1] = '\0'; /* Put the first char as eip of parent's code structure */ eip = bfprogram; /* Allocate slots */ if ((slots = malloc(sizeof(char) * (1024))) == NULL) { printf("Could not allocate memory for internal slots, barfing\n"); exit(EXIT_FAILURE); } memset(slots,0,1024); slotindex = 0; slotsize = 1024; ptr = slots; while (*eip) { switch (*eip) { case '>': if (slotindex == slotsize) { if ((slots = realloc(slots,(sizeof(char) * 1024) * slotsize+1024)) == NULL) { printf("Could not resize slots array\n"); exit(EXIT_FAILURE); } memset(&slots[slotindex+1],0,1024); slotsize += 1024; } ptr++; slotindex++; break; case '<': if (slotindex == 0) { printf("Tried going below slot 0, quitting\n"); exit(EXIT_FAILURE); } ptr--; slotindex--; break; case '+': (*ptr)++; break; case '-': (*ptr)--; break; case ',': (*ptr) = getchar(); break; case '.': putchar(*ptr); break; case ']': if (*ptr) while (*eip--) if (*eip == '[') break; break; } eip++; } free(bfprogram); free(slots); return; } int main(int argc, char *argv[]) { FILE *bf; if (argc != 2) { printf("Syntax Error: ./bf4 \n"); return EXIT_FAILURE; } if ((bf = fopen(argv[1],"r")) == NULL) { printf("Error, could not open '%s'\n" "Syntax: ./bf5 \n",argv[1]); return EXIT_FAILURE; } parse_brainfuck_file(bf); fclose(bf); return EXIT_SUCCESS; }