-5

So, I wondered why I am not able to do memcpy for myself. This is the code that works and gets me the correct result:

unsigned int VTableAddress = FindPattern( VTABLE_PATTERN, VTABLE_MASK );

unsigned int *p_VTable = NULL;

WriteMemory( &p_VTable, ( void* ) ( VTableAddress + 2 ), 4 );

//....

void D3DX9Interface::WriteMemory( void *address, void *bytes, int byteSize )
{
    DWORD NewProtection;

    VirtualProtect( address, byteSize, PAGE_EXECUTE_READWRITE, &NewProtection );
    memcpy( address, bytes, byteSize );
    VirtualProtect( address, byteSize, NewProtection, &NewProtection );
}

So for my understanding, WriteMemory basically sets read/write protection to the memory address and then simply copies bytes into address. To understand how things are working, I've tried it myself with this code:

//Get the address of the vtable
unsigned int VTableAddress = FindPattern( VTABLE_PATTERN, VTABLE_MASK );

unsigned int *p_VTable = NULL;

CopyWithRWPrivileges( p_VTable, (unsigned int*)( VTableAddress + 2 ) );

//...

void D3DX9Interface::CopyWithRWPrivileges( unsigned int *p_Destination, unsigned int *p_Source )
{
    DWORD Protection( 0 );

    VirtualProtect( reinterpret_cast< LPVOID >( p_Destination ), 4, PAGE_EXECUTE_READWRITE, &Protection );

    p_Destination = p_Source;

    VirtualProtect( reinterpret_cast< LPVOID >( p_Destination ), 4, Protection, &Protection );
}

But for some reason the last code gives me back a NULL pointer. But why?

drescherjm
  • 10,365
  • 5
  • 44
  • 64
Haxx0r
  • 9
  • 3
  • 1
    `p_Destination = p_Source;` is not a copy operation. It reassigns the local pointer `p_Destination` (which is not visible outside of the function) – UnholySheep May 06 '18 at 13:05
  • Thanks! Ok, understood that. But when passing p_VTable like "unsigned int *&p_Destination" it still gives me not the same result as the memcpy. – Haxx0r May 06 '18 at 13:35
  • Have a look at [The Definitive C++ Book Guide and List](https://stackoverflow.com/q/388242/1889329). – IInspectable May 06 '18 at 20:15

1 Answers1

0

Ok with the help of UnholySheep I've found the solution for my problem. So first, the pointer is getting copied instead of passed as a reference-pointer. And as second, the p_Source needs to be handled as a pointer too, so with this code it's working:

void D3DX9Interface::CopyWithRWPrivileges( unsigned int *&p_Destination, unsigned int *p_Source )
{
    DWORD Protection( 0 );

    VirtualProtect( reinterpret_cast< LPVOID >( p_Destination ), 4, PAGE_EXECUTE_READWRITE, &Protection );

    p_Destination = *(unsigned int**) p_Source;

    VirtualProtect( reinterpret_cast< LPVOID >( p_Destination ), 4, Protection, &Protection );
}
Haxx0r
  • 9
  • 3