This is amaaaaaaaazing piece of code, i really don't know how to thank you for your continuous support, i have studied your code, tried some things here and there and this is my code now. I commented out some questions that i hope you get the time to take a look at.
Code:
#include <iostream>
#include <string>
#include <Windows.h>
using namespace std;
void RealFunction()
{
MessageBox(NULL, "RealFunction()", "Trace", MB_OK);
}
DWORD jmpBackAddr = 0x000000;
__declspec(naked) void CodeCave()
{
__asm {
pushad;
pushfd;
}
MessageBox(NULL, "CodeCave()", "Trace", MB_OK);
__asm{
popfd;
popad;
jmp [jmpBackAddr];
}
}
template<typename T>
DWORD protectMemory(DWORD address, DWORD prot)
{
DWORD oldProt;
VirtualProtect((LPVOID)address, sizeof(T), prot, &oldProt);
return oldProt;
}
template<typename T>
void writeMemory(DWORD address, T value)
{
*((T*)address) = value;
}
DWORD hookWithJump(DWORD hookAt, DWORD newFunc, int size){
if (size > 12) // shouldn't ever have to replace 12+ bytes
return 0;
protectMemory<DWORD/*[3] >> Why ?*/>(hookAt, PAGE_EXECUTE_READWRITE); //If the current page is always 0x20 [PAGE_EXECUTE_READ] why we need to save the old value ?
writeMemory<BYTE>(hookAt, 0xE9);
writeMemory<DWORD>(hookAt + 1, (newFunc - hookAt - 5)); //As i understand we use -5 because the size of JMP instruction is 5, and now we are writing write after the JMP so we need to move past it, (like a little bit to the right :D) ?
//Also what happens if the stack was going down instead of up or vice versa, would that newFunc - hookAt be the reverse in that situation ?
//for (unsigned int i = 5; i < size; i++) //I think this code will never be excuted since we are passing 5, and `i` starts with 5. Wouldn't be more
// writeMemory<BYTE>(hookAt + i, 0x90); //If we somehow dynamically determined the target instruction's size, placed our jump then noped out the rest ?
protectMemory<DWORD/*[3] >> Why ?*/>(hookAt + 1, 0x20);
return hookAt + 5; //But Hook at is already overwritten right ? i think that will cause an infinite loop to the code cave ?, it gives me memory access violation btw but this is what i think will happen ?
}
void main()
{
jmpBackAddr = hookWithJump((DWORD)RealFunction, (DWORD)CodeCave, 5);
while (true)
{
cin.get();
RealFunction();
}
}