Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allocate executable ram in c on linux

Tags:

c

linux

malloc

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 function?

like image 464
pklall Avatar asked Jun 26 '10 22:06

pklall


2 Answers

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.

like image 195
ninjalj Avatar answered Oct 20 '22 09:10

ninjalj


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.

like image 8
Norman Ramsey Avatar answered Oct 20 '22 09:10

Norman Ramsey