3

I'm trying to pass a function pointer in a template, to then use it in asm code:

template <auto T>
_declspec(naked) void Test()
{
    __asm
    {
        lea eax, T
        jmp [eax]
    }
}

int main()
{
    Test<MessageBoxA>();
    Test<Sleep>();
}

I know the naked function will crash when executed but I've simplified the code to show only what I'm trying to achieve.

The problem with this code is that once compiled, if you look at the assembly code in a disassembler, it will look like this:

lea eax, 0
jmp [eax]

It is storing 0 in eax. Instead, it should store the MessageBoxA address (and Sleep in another function) in eax.

I don't know if I'm doing something wrong or the compiler is failing.

8
  • &MessageBoxA ? Commented Apr 14, 2022 at 6:00
  • @Aganju same output. Commented Apr 14, 2022 at 6:01
  • You tagged this [compiler-errors], but you're saying it actually does compile, just not to the asm you want. If there actually is an error message, edit your question. Commented Apr 14, 2022 at 6:08
  • 2
    Unfortunately templates and inline assembly don't mix well. Commented Apr 14, 2022 at 10:35
  • 1
    I am siding with @oisyn . A couple of years ago there was another MSVC related question about inline and templates and pretty sure the conclusion was that there were problems with the combination. After searching I can't find it though. Commented Apr 15, 2022 at 0:43

1 Answer 1

1

I'm not an assembly expert, but creating a static constexpr void* set to the non-type template parameter value seems to do the trick:

template <auto T>
__declspec(naked) void Test()
{
    static constexpr void* fptr = T;
    
    __asm 
    {
        lea eax, fptr
        jmp [eax]
    }
}

const void sleep()
{
}

int main()
{
    Test<(&sleep)>();
    return 0;
}

generates

lea     eax, OFFSET void * `void Test<&void sleep(void)>(void)'::`2'::fptr
jmp     SHORT DWORD PTR [eax]

The example can be played with on compiler explorer: https://godbolt.org/z/f1d7daa49

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.