tags:

views:

155

answers:

1

I'm using Detours to hook into an executable's message function, but I need to run my own code and then call the original code. From what I've seen in the Detours docs, it definitely sounds like that should happen automatically. The original function prints a message to the screen, but as soon as I attach a detour it starts running my code and stops printing.

The original function code is roughly:

void CGuiObject::AppendMsgToBuffer(classA, unsigned long, unsigned long, int, classB);

My function is:

void CGuiObject_AppendMsgToBuffer( [same params, with names] );

I know the memory position the original function resides in, so using:

DWORD OrigPos = 0x0040592C;
DetourAttach( (void*)OrigPos, CGuiObject_AppendMsgToBuffer);

gets me into the function. This code works almost perfectly: my function is called with the proper parameters. However, execution leaves my function and the original code is not called. I've tried jmping back in, but that crashes the program (I'm assuming the code Detours moved to fit the hook is responsible for the crash).

Edit: I've managed to fix the first issue, with no returning to program execution. By calling the OrigPos value as a function, I'm able to go to the "trampoline" function and from there on to the original code. However, somewhere along the lines the registers are changing and that is causing the program to crash with a segfault as soon as I get back into the original code.

Edit2: Final working code:

class CGuiObject
{
 public:
    void MyFunc( [params] );
};

DWORD TrueAddr = 0x0040592C;

CGuiObject::MyFunc( [params] )
{
    _asm { pushad }
    // process
    _asm {
        popad
        leave
        jmp TrueAddr
    }
}

and using TrueAddr for the first param in DetourAttach.

+1  A: 

Given that you are trying to intercept a C++ method call, you probably have a calling convention issue when you call the original function.

I've not tried to do this personally with detours, but this post points to something that might help you.C++ — Detours (Win32 API Hijacking) — Hijack Class Methods See the link in the second answer.

Paul Arnold
This worked, in a round-about way. In the end, I created a skeleton class which works perfectly. It can even call itself to insert messages into the queue or skip the final parts to prevent a message. Thanks for the link! :)
peachykeen