Using the Microsoft Detours library, I've written the following simple code:
#include <Windows.h>
#include <detours.h>
#include <stdio.h>
void RealFunc(int num) {
printf("RealFunc %d\n", num);
}
void(*RealFuncPtr)(int) = &RealFunc;
void HookedFunc(int num) {
printf("HookedFunc %d\n", num + 100);
// RealFunc(num); // This starts an infinite loop because it calls HookedFunc which calls RealFunc which calls HookedFunc etc...
(*RealFuncPtr)(num); // This doesn't start an infinite loop and only calls RealFunc without calling HookedFunc. Why is this?
}
int main() {
RealFunc(100);
DetourTransactionBegin();
DetourUpdateThread(GetCurrentThread());
DetourAttach((PVOID*) &RealFuncPtr, &HookedFunc); //redirect RealFunc to HookedFunc
if (DetourTransactionCommit() != NO_ERROR) {
return 0;
}
printf("Hook successful!\n");
RealFunc(100);
getchar(); // Pause console
return 0;
}
Here is the output:
RealFunc 100
Hook successful!
HookedFunc 200
RealFunc 100
As you can see, because of the (*RealFuncPtr)(num);
line, the real function is called at the end of the hooked function call. However, if I comment out (*RealFuncPtr)(num);
and uncomment RealFunc(num);
, it seems to start an infinite loop. Why does the loop only occur when I use RealFunc(num);
?
Also, for some reason, when I set the project to release mode, here is the output:
RealFunc 100
Hook successful!
RealFunc 100
The hook seems to not work during release mode. Is it my Visual Studio configuration or something wrong with my code?