I want to make a simple just-in-time compiler with c on Linux.
How can I allocate memory such that I can write out raw x86 code to it and execute it as any other fun
See mprotect(). Once you have filled a (n-)page-sized memory region (allocated with mmap()) with code, change its permissions to disallow writes and allow execution.
In addition to using mprotect
correctly to provide first write and then execute permission, on some OS/hardware operations you may need to flush the I-cache. At this moment (mid-2010), all recent x86 processors have separate level 1 caches for instructions and data, and somebody has to make sure that if you write new instructions into memory (which will update the D-cache), you don't then try to execute stale bits from the I-cache. Exactly how to flush the I-cache from userspace will depend on both your hardware and the OS. My advice would be to read Intel's documentation on "self-modifying code" for their IA-32 multiprocessors. This should be enough to get you through.