Snippets for writing bytes to specified memory address
WriteMemory - write an byte-array to memory-address.
WriteJump - both arguments are addresses, where to jump from and where to jump to.
WriteNop - address and how many to write.
#ifndef MEMUTILS_H
#define MEMUTILS_H
BOOL WriteMemory( DWORD dwAddress, const void* cpvPatch, DWORD dwSize )
{
DWORD dwProtect;
if( VirtualProtect( (void*)dwAddress, dwSize, PAGE_READWRITE, &dwProtect ) ) //Unprotect the memory
memcpy( (void*)dwAddress, cpvPatch, dwSize ); //Write our patch
else
return false; //Failed to unprotect, so return false..
return VirtualProtect( (void*)dwAddress, dwSize, dwProtect, new DWORD ); //Reprotect the memory
}
BOOL WriteJump( DWORD From, DWORD To )
{
if( To < From + 128 && To > From - 128 ) //Short jump
{
BYTE bpJump[2] = { 0xEB, ( To - From ) - 2 }; //Calculate opcode
return WriteMemory( From, bpJump, 2 );
}
else //Far jump
{
BYTE bpJump[5] = { 0xE9, 0x00, 0x00, 0x00, 0x00 };
*(DWORD*)&bpJump[1] = ( To - From ) - 5; //Calculate jump
return WriteMemory( From, bpJump, 5 );
}
return false; //If we end up here, something went horribly wrong
}
BOOL WriteNop( DWORD dwAddress, DWORD dwAmount )
{
BYTE bpNops[100]; //100 just incase I wanna do some gigantic NOPing
memset( bpNops, 0x90, 100 ); //Fill byte-array with NOPs
return WriteMemory( dwAddress, bpNops, dwAmount );
}
#endif