Search code examples
functionmemoryvirtualbyte

Function in BYTE array straight to memory?


Is it possible to allocate virtual memory for a byte array containing a function, write the array in the memory and then somehow execute the function in virtual memory?


Solution

  • You have to be sure that the bytes you are going to execute are indeed a valid sequence of CPU instructions, or otherwise the "function" would definitely crash, such as causing exceptions "illegal instruction", "access violation" etc.

    Next thing to do is to make sure that the bytes in question are located in memory that has a execution privilege. VirtualProtect with PAGE_EXECUTE get you that.

    Then you are to actually pass control to your function. This can be assembly code, e.g. push <address>; ret; or C++ style call of static function with address in variable.