I have been trying to write to a process's memory with this code (to create a cheat code):
#include
int main()
{
HWND hWnd = FindWindow(0, "xyz");
if(hWnd == 0)
{
MessageBox(0, "Error cannot find window.", "Error", MB_OK|MB_ICONERROR);
}
else
{
DWORD proccess_ID;
GetWindowThreadProcessId(hWnd, &proccess_ID);
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, proccess_ID);
if(!hProcess)
{
MessageBox(0, "Could not open the process!", "Error!", MB_OK|MB_ICONERROR);
}
else
{
int newdata = 500;
DWORD newdatasize = sizeof(newdata);
if(WriteProcessMemory(hProcess, (LPVOID)0x57C2A4, &newdata, newdatasize, NULL))
{
MessageBox(NULL, "WriteProcessMemory worked.", "Success", MB_OK + MB_ICONINFORMATION);
}
else
{
MessageBox(NULL, "Error cannot WriteProcessMemory!", "Error", MB_OK + MB_ICONERROR);
}
CloseHandle(hProcess);
}
}
return 0;
}
When I overwrite for example a jnz with jz it works fine, because both have the same size. But when I try to overwrite for example a pop with jmp I get an error because these commands have different size.
I read here that WriteProcessMemory performs a verification to check the available size at the specified address.
What I want to do is to write to a memory address without size check, so the program simply overwrite as many bytes is needed to the code.
With Cheat Engine I was able to do this, because it offered me to overwrite the necessary bytes.
So my question is how to do in C++ the same as with Cheat Engine?
I don’t know the answer to your precise question “how to do in C++ the same as with Cheat Engine?” because I have no idea how Cheat Engine works for your case. It might be doing something much more complex than just overwriting a single instruction.
WriteProcessMemory doesn’t verify what you think it verifies.
It takes a sequence of bytes from the address space of the calling process, writes those bytes to another process. It doesn’t decode any x86 instructions from those bytes, nor from the bytes being overwritten. And it can’t, because it doesn’t even know for sure whether you’re writing code or data.
If you know what you’re doing, you can surely replace shorter instructions with longer instructions. Just write the new longer code. There’s a side effect, you’ll also overwrite (maybe partially) some instruction[s] that were after the old short one. This may break the code directly after your patch.
Replacing longer instruction with shorter one is easier and should be free from side effects, just pad the new instruction with 0x90 bytes = NOP instructions.