I am testing an assembler I am writing which generates X86 instructions. I would like to do something like this to test whether the instructions work or not.
#include<stdio.h>
unsigned char code[2] = {0xc9, 0xc3};
int main() {
void (*foo)();
foo = &code;
foo();
return 0;
}
However it seems that OS X is preventing this due to DEP. Is there a way to either (a) disable DEP for this program or (b) enter the bytes in another format such that I can jump to them.
If you just need to test, try this instead, it’s magic…
The
constkeyword causes the compiler to place it in theconstsection (warning! this is an implementation detail!), which is in the same segment as thetextsection. The entire segment should be executable. It is probably more portable to do it this way:And you can always do it in an assembly file,
However: If you want to change the code at runtime, you need to use
mprotect. By default, there are no mappings in memory with both write and execute permissions.Here is an example:
The
mprotectspecification states that its behavior is undefined if the memory was not originally mapped withmmap, but you’re testing, not shipping, so just know that it works just fine on OS X because the OS Xmallocusesmmapbehind the scenes (exclusively, I think).