I’m working on application (written in C++), which generate some machine code at runtime (Linux, x86-64 now, but I plan to migrate on ARM). Next it store generated code in memory and execute it by jumping to memory location. For a long time I had a problem with allocating executable memory, but I finally solved it using:
uint8_t *memory = mmap (NULL, length, PROT_READ | PROT_WRITE | PROT_EXEC, MAP_PRIVATE | MAP_ANONYMOUS, -1, 0);
So far it works, but I’m not sure if it’s elegant way to do such things. I wonder how executable loader do this?
This is essentially how executable loaders do things; in their case they perform a
mmapof a file, not an anonymous mapping, but apart from that it’s essentially the same.Note that it’s a good idea not to have both write and execute access at the same time, as it makes certain types of security exploits easier. You can use
mprotectto adjust the protection flags after the initial mapping.