Question

I am trying to compile and run code snippet bellow, which work in Windows x86 or WOW64 but in Windows x64 he crash with error Access Violation.

Compile with both, gcc and Microsoft C/C++ compilers.

/*Microsoft (R) C/C++ Optimizing Compiler Version 15.00.30729.01 for x64
 (x64)cl -W3 -Zi tx.c -Fetx64
 (x86)cl -W3 -Zi tx.c -Fetx32

 gcc (tdm64-1) 4.7.1
 (x64)gcc -m64 -Wall -O2 -o tx64 tx.c
 (x86)gcc -m32 -Wall -O2 -o tx32 tx.c
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

typedef int (*fpPUTS)( const char *str ); /*function pointer that takes an const char * as an argument and returns int*/                                          
typedef void (*fpMEMEXEC)( fpPUTS pPuts, char *str ) ;/*function pointer on which first argument is pointer to above function*/

void toMem( fpPUTS pPuts, char *str )
{
    pPuts( str );
}   

int main(int argc, char* argv[])
{
    fpMEMEXEC   pMemexec;
    pMemexec = (fpMEMEXEC) malloc(4*1024);/* Allocate 4 KB memory space to the function pointer */
    memcpy( pMemexec, toMem, 4*1024);    /*  Copy the content of toMem into newly allocated memory */
    pMemexec( puts, "Hello word !!\n"); /* execute it in memory */
    return 0;
}

My question is, why this code does not work properly 64-bit environment ?
What rules are not met but should be in order to work properly this code ?

Was it helpful?

Solution

Your system probably has DEP - Data Execution Prevention. This means that every page can be either writable or executable, but not both.

On 32bit systems, You will need to use SetProcessDEPPolicy in order to disable it for the current process.

On 64bit systems, you should allocate using PAGE_EXECUTE_READWRITE - something like

pMemexec = VirtualAlloc(0, 4*1024, MEM_COMMIT, PAGE_EXECUTE_READWRITE);

You probably want to see this and this questions, and this example.


As has been pointed out, this does not guarantee it will work.

  1. As far as I am aware, the C programming language make no guarantee that such copying will make a sensibly callable function.
  2. If the function is not page-aligned (which is probable) and the next page is not allocated, you find yourself trying to read from an unallocated memory. So you will have to find exactly how long the function is, somehow.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top