I'm developing a loader|linker for ELF-format object files. I use mmap() for mapping the code section to the process. The idea is to load and modify the relocations in the code section. But I encountered a problem of instability when using mmap() in PROT_EXEC|PROT_READ|PROT_WRITE mode.
The simple program is bx lr
. The code is for .arm 1e ff 2f e1
. If I load and execute it from file (four bytes - 1e ff 2f e1), everything is fine.
int fd = open("bx.cod", 0, 0);
char *p = mmap(0, len, PROT_EXEC, MAP_SHARED, fd, 0);
close(fd);
proce = (System_RBProc)p;
(*proce)();
But if I allocate and modify memory (writing the same code - 1e ff 2f e1
), I sometimes get Illegal instruction
char *p = mmap(0, len, PROT_EXEC|PROT_READ|PROT_WRITE,
MAP_PRIVATE|MAP_ANONYMOUS, 0, 0);
memcpy(p, "\x1e\xff\x2f\xe1", 4);
rc = mprotect(p, len, PROT_EXEC);
proce = (System_RBProc)p;
(*proce)();
Unstability means that Illegal instruction
is a rare occasion in the last case. But ...