Reputation: 395
I am triying to create a code emmiter in c++ in order to learn how to make an emulator, but im having a hard time making dynamic assembler work:
unsigned char program[] = {0x90, 0x90, 0xC3 }; //nop; nop; ret
void (*p)(void) = (void(*)()) &program;
p();
always return access violation .....
im working with visual studio 2012 C++ win32 console application
Thanks.
Upvotes: 5
Views: 177
Reputation:
After some research I found this: you have to allocate the memory and change the read/write/execution permissions to: Allow Read, Disallow Write, Allow Execution.
See this question for a "how to do it".
On Windows the function is VirtualProtect, you'll want to pass in PAGE_EXECUTE_READWRITE to get execute permission.
By default Windows does not allow memory execution. It's called Data Execute Prevention (DEP).
And for linux:
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.
another fix for your issue on windows is just add your program to DEP whitelist... (You probbly didn't notice, but your crash is probably of type BEX
, BEX
crashes are in 99% cases related to DEP)
P.S. When you create a working code emitter.. mind giving me a copy? xD
Upvotes: 7