0

I've been trying to hook a function using Detours 1.5, but when DetourFunction() is called, it throws access violation.

This is the original function:

int greeter(char *name) {
    printf_s("%s, %s!\n", greetings[rand() % ((int) sizeof(greetings) / (int) sizeof(greet_t))], name);
    int rerun = strcmp("Gabriel", name);
    if (!rerun) printf_s("Have a nice day!\n");
    return rerun;
}

With the program compiled and running properly, I used IDA Pro to see the trace and found my function beginning on address 0x004010B0. Then I set the variable DWORD orig_greeter = 0x4010B0. And wrote the following code:

#include "sky.h"

int myGreeter(char* name);
int (__cdecl* origGreeter)(char*);

bool __stdcall DllMain(HINSTANCE hInst, DWORD dwReason, LPVOID pvReserved) {
    if (dwReason == DLL_PROCESS_ATTACH) {
        // Start Hook Sub-Routine
        origGreeter = (int (__cdecl*)(char*))DetourFunction((PBYTE)orig_greeter, (PBYTE)myGreeter);
        origGreeter("sir");
    }   
    return true;
}

int myGreeter(char* name) {
    printf_s("You've been hooked, %s!", name);
    return 0;
}

Once DetourFunction tries to access the given offset it throws Access Violation and the function is not hooked. What am I missing?

[Edits removed. No relevant for the question]

1

The problem is that I was considering the base address given by IDA Pro instead of process actual base address.

The IDA Base was 0x400000, thus the offset really was 0x10B0. Once I updated orig_greeter to this value, I call it as follows.

HMODULE hModule = GetModuleHandle(NULL);
origGreeter = (int (__cdecl*)(char*))DetourFunction((PBYTE)hModule+orig_greeter, (PBYTE)myGreeter);

The code itself still doesn't behave as expected, but it detours properly. The callstack showed it called myGreeter when it was supposed to. Therfore, I consider this question answered.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.