Search code examples
c++celfbrainfuck

Making an executable by running an executable


I wanted to write a brainfuck compiler, but when I went to write one I was stuck at this problem

I want to create an ELF executable (using C/C++) that reads a brainfuck code from a file and generates an executable. Just like GCC/clang

I can read and parse the code, but I don't know how to write an executable that can run on the same system (say x86)?

I want this behavior: my_bf_compiler ./source.bf -o bin.out ./bin.out

EDIT: I do not want to know how to write a compiler. Read this, compiler part was just for context as to where I will use it

I want to create a binary executable (say maker.out) which when ran creates a executable file (say foo.out). For simplicity let's keep foo.out very simple, when executed it returns 7; So, this is what is expected:

./maker.out # Creates the foo.out executable
./foo.out && echo $ # Runs the executable and prints return value, in this case 7;

So how do I write maker.cpp?


Solution

  • Your initial message was about creating a an executable from a brainfuck code, so this is what this answer focuses on. Your current question is way too broad.

    As you have linked in one of your previous posts there is already an implementation that does this here: https://github.com/skeeto/bf-x86/blob/master/bf-x86.c

    It basically does 3 steps:

    1) Parse the BF code into a intermediate representation (which is here https://github.com/skeeto/bf-x86/blob/master/bf-x86.c#L55)

    2) Compile this intermediate representation into machine code (which can be found here https://github.com/skeeto/bf-x86/blob/master/bf-x86.c#L496)

    3) Compose the ELF binary according to the specification. The example program does this here. https://github.com/skeeto/bf-x86/blob/master/bf-x86.c#L622 .

    Steps 1 and 2 are up to you to find a good implementation, for step 3 the simplest way is to write the ELF header and program header in such a way, that it only has the programs machine code as content and point the entrypoint of the program to the machine code generated in step 2.

    The full specification for the ELF format can be found here: https://refspecs.linuxfoundation.org/elf/elf.pdf