K
K
Koncord2016-05-14 22:11:28
C++ / C#
Koncord, 2016-05-14 22:11:28

There is a function to call functions with parameters loaded onto the stack. For x86 everything is clear, but how can I port to x86-64?

inline uintptr_t CallNative(void* func, unsigned int* data, size_t size)
{
    uintptr_t low;
    uintptr_t high;
    uintptr_t result;
#ifdef __i386__
asm(
        "MOV EDI,ESP\n"
        "SUB EDI,%3\n"
        "MOV ESI,%4\n"
        "MOV ECX,%3\n"
        "PUSH DS\n"
        "POP ES\n"
        "CLD\n"
        "REP MOVSB\n"
        "MOV ESI,ESP\n"
        "SUB ESP,%3\n"
        "CALL %2\n"
        "MOV ESP,ESI\n"
        "MOV %0,EAX\n"
        "MOV %1,EDX\n"
        : "=m"(low), "=m"(high)
        : "m"(func), "m"(size), "m"(data)
        : "eax", "edx", "ecx", "esi", "edi", "cc"
);
    *reinterpret_cast<uintptr_t*>(&result) = low;
    *reinterpret_cast<uintptr_t*>(((uintptr_t) &result) + 4) = high;
#endif
    return result;
}

Answer the question

In order to leave comments, you need to log in

2 answer(s)
N
none7, 2016-05-15
@none7

The code will be system dependent. On Linux, the first 6 arguments are passed in registers (rdi, rsi, rdx, rcx, r8, r9), the rest are the old fashioned way. On Windows, the first four are in registers (rcx, rdx, r8, r9), the rest are on the stack, BUT the place on the stack for the first 4 still needs to be allocated and it is better to save the arguments there too; for the sake of va_arg functions. The stack needs to be aligned on a 16-byte boundary because sse2 is used everywhere.
By the way, it's better to implement such a function not in the C ++ source, but in a separate .s file. After all, if the function returns double, then there are no guarantees that everything will return intact.

V
Vasily, 2016-05-15
@Foolleren

emnip inline assembler is a bit illegal for X64 for some compilers,
if yours is exactly like that, then you have to leave only

#ifdef __i386__
asm(
бла бла бла
);
#endif

return result; - not a ride - you have to put your hands in rax

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question