Exceuting a simple assembly code in C++ without it being in a function

馋奶兔 提交于 2019-12-13 21:01:17

问题


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.


回答1:


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
    }
}


来源:https://stackoverflow.com/questions/24277471/exceuting-a-simple-assembly-code-in-c-without-it-being-in-a-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!