5

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.

Jens Björnhager
  • 5,632
  • 3
  • 27
  • 47
elios264
  • 385
  • 2
  • 16
  • Are you trying to cast a char[] to a pointer to a function?? why? I think i don't understand what are you trying to do... – DGomez Jun 17 '13 at 23:41
  • 2
    Does the memory which holds `program` permit execution? – Kaz Jun 17 '13 at 23:42
  • woah I want to know the answer too. –  Jun 17 '13 at 23:43
  • 2
    this is an example, but the char array is a buffer where all the instructions are going to be stored and then processed by the cpu: http://www.multigesture.net/wp-content/uploads/mirror/zenogais/Dynamic%20Recompiler.html – elios264 Jun 17 '13 at 23:43
  • Does windows allow these kinds of shenanigans? – Carl Norum Jun 17 '13 at 23:47
  • 2
    @CarlNorum: Certainly. How else can a JITter work? – SLaks Jun 17 '13 at 23:47
  • 1
    Sure; I meant without a further dance to allow execution (ala @GamErix's answer). – Carl Norum Jun 17 '13 at 23:49
  • 3
    @CarlNorum: before DEP (which depended on the support of the NX bit in the processor) memory was executable by default. Also, DEP has been disabled by default for anything but system services for several Windows releases to avoid breaking applications that relied on this kind of stuff. – Matteo Italia Jun 17 '13 at 23:50

1 Answers1

7

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

Community
  • 1
  • 1