-
-
Save zid/b1328d44ec9b975cd3f34440adbfdff7 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
static const char bf[] = ">++[<+++++++++++++>-]<[[>+>+<<-]>[<+>-]++++++++" | |
"[>++++++++<-]>.[-]<<>++++++++++[>++++++++++[>++" | |
"++++++++[>++++++++++[>++++++++++[>++++++++++[>+" | |
"+++++++++[-]<-]<-]<-]<-]<-]<-]<-]++++++++++."; | |
static void tputs(const char *str) | |
{ | |
putchar('\t'); | |
puts(str); | |
} | |
int main(void) | |
{ | |
size_t i, len = sizeof(bf) - 1; | |
int stack[512]; | |
int labels = 0, sp = 0; | |
puts("default rel"); | |
puts("global main"); | |
puts("extern printf"); | |
puts("section .text"); | |
puts("main:"); | |
tputs("sub rsp, 4096"); | |
tputs("mov rdi, rsp"); | |
tputs("mov rcx, 4096"); | |
tputs("xor rax, rax"); | |
tputs("rep stosb"); | |
tputs("mov rdi, rsp"); | |
for(i = 0; i < len; i++) | |
{ | |
int n; | |
switch(bf[i]) | |
{ | |
case '<': | |
tputs("dec rdi"); | |
break; | |
case '>': | |
tputs("inc rdi"); | |
break; | |
case '+': | |
n = 0; | |
while(bf[i++] == '+') | |
{ | |
n++; | |
} | |
i -= 2; | |
if(n == 1) tputs("inc byte [rdi]"); | |
else printf("\tadd byte [rdi], %d\n", n); | |
break; | |
case '-': | |
tputs("dec byte [rdi]"); | |
break; | |
case '.': | |
tputs("call put"); | |
break; | |
case ',': | |
tputs("call get"); | |
break; | |
case '[': | |
if(bf[i+1] == '-' && bf[i+2] == ']') | |
{ | |
i += 2; | |
tputs("mov byte [rdi], 0"); | |
break; | |
} | |
stack[sp++] = labels; | |
printf("L%d:\n", labels++); | |
break; | |
case ']': | |
tputs("movzx rax, byte [rdi]"); | |
tputs("test rax, rax"); | |
printf("\tjnz L%d\n", stack[--sp]); | |
break; | |
} | |
} | |
tputs("mov rax, 60"); | |
tputs("syscall"); | |
puts("put:"); | |
tputs("push rdi"); | |
tputs("xor rax, rax"); | |
tputs("movzx rsi, byte [rdi]"); | |
tputs("lea rdi, [fmt]"); | |
tputs("call printf wrt ..plt"); | |
tputs("pop rdi"); | |
tputs("ret"); | |
puts("get:"); | |
tputs("ret"); | |
puts("section .rodata"); | |
tputs("fmt db \"%c\", 0"); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment