Reputation: 3867
I'm trying to write a trampoline hook to some win32 api function, when I write the JMP instruction to the start of the original function I want it to jump to a codecave instead of calling a function.
The original function start looks like this in OllyDBG:
PUSH 14
MOV EAX, 12345678
...
And I patch it to:
JMP 87654321
NOP
NOP
The address of the following function:
int HookFunc(int param)
{
DoStuff(param);
return ExecuteOriginal(param);
}
ExceuteOriginal looks like this:
unsigned long address = AddressOfOriginalFunction + 7;
int ExceuteOriginal(int param)
{
__asm
{
PUSH 0x14
MOV EAX, 0x12345678
JMP address
}
}
Which executes the overridden code and jumps to the original function right after the patched code. The problem is that since it's a function, it'll mess up the stack because the caller should clean it up and the function instead of return, jumps to another function's code. And I guess that's why the program crashes.
Is there a way using Visual C++ compiler to place the assembly code in the code section of the program without having it being inside a function? That way I can jump there, execute whatever, and return back without the risk of messing up the stack.
Upvotes: 0
Views: 1325
Reputation: 137398
Solution: __declspec(naked)
For functions declared with the naked attribute, the compiler generates code without prolog and epilog code. You can use this feature to write your own prolog/epilog code sequences using inline assembler code.
Example:
__declspec( naked ) int ExceuteOriginal(int param)
{
__asm
{
PUSH 14
MOV EAX, 0x12345678
JMP address
}
}
Upvotes: 6