Skip to content

Instantly share code, notes, and snippets.

@0xbb
Last active August 29, 2015 14:20
Show Gist options
  • Save 0xbb/4bd111a9962b2fd38046 to your computer and use it in GitHub Desktop.
Save 0xbb/4bd111a9962b2fd38046 to your computer and use it in GitHub Desktop.
Brainfuck compiler in Python for x86_64 Linux
#!/usr/bin/env python
# Usage: ./bfc.py source.bf > out.S && as out.S -o out.o && ld out.o
import sys
print("""
.intel_syntax noprefix
.global values
.data
cells:
.rept 10000
.byte 0
.endr
.global _start
.text
_start:
lea r15, cells""")
def increment_dp():
print('inc r15')
def decrement_dp():
print('dec r15')
def increment():
print('incb [r15]')
def decrement():
print('decb [r15]')
def bf_output():
print("""
mov rax,1 # write syscall (x86_64)
mov rdi,1 # fd = stdout
mov rsi, r15 # *buf = Hello
mov rdx,1 # count
syscall""")
def bf_input():
print("""
mov rax,0 # read syscall (x86_64)
mov rdi,0 # fd = stdin
mov rsi, r15 # *buf
mov rdx,1 # count
syscall""")
label_stack = []
label_count = 0
def while_open():
global label_count
label_stack.append(label_count)
print("l" + str(label_count) + ":")
print("""
cmpb [r15], 0
je l""" + str(label_count + 1))
label_count += 2
def while_close():
l = label_stack.pop()
print("jmp l" + str(l))
print("l" + str(l + 1) + ":")
commands = {
'>': increment_dp,
'<': decrement_dp,
'+': increment,
'-': decrement,
'.': bf_output,
',': bf_input,
'[': while_open,
']': while_close,
}
with open(sys.argv[1], "rt") as in_file:
for c in in_file.read():
buf = ""
if c in commands:
commands[c]()
print("""
mov rax, 60 # system call 60 is exit
xor rdi, rdi # we want return code 0
syscall""")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment