简体   繁体   中英

Passing integer to x86 ASM in C++

I am trying to do some script hooking in C++, and have setup a simple test function for this case.

   void __declspec(naked) testFunct()
{
    int myInt;
    myInt = 2000;
    __asm{
        mov eax, myInt
        jmp [jmp_back_address]
    }
}

when using this to pass in the integer, the function fails when it is called and the project crashes. However, when using this instead, without an integer value, it successfully passes through.

   void __declspec(naked) testFunct()
{
    __asm{
        mov eax, 2000
        jmp [jmp_back_address]
    }
} 

How can I successfully pass the integer?

The assembler doesn't know what "myInt" means. Most compilers support inline assembly with the possibility to pass values. For instance, with GCC, you may try to define a macro like

#define MY_ASM_MACRO(myInt) ({ asm volatile("mov eax,%0\n\t \
          jmp [jmp_back_address]" : : "r"(myInt) : ); })

And use it like

void __declspec(naked) testFunct()
{
   int myInt;
   myInt = 2000;
   MY_ASM_MACRO(myInt)
}

The correct solution for my situation was to simply do everything within the ourFunct() through ASM instead, as mixing both C++ and ASM for passing variables was creating buggy assembly code. Example with a function call that works:

int CalculateTotalScore()
{
    return (int)*Game::current_speed_score;
}

DWORD jmpBackAddress;
void __declspec(naked) ourFunct()
{
    __asm{
        call CalculateTotalScore
        jmp [jmpBackAddress]
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM