执行这样的函数调用是否正确?

时间:2014-04-20 15:32:15

标签: c assembly virtual-machine inline-assembly vm-implementation

我有一个32位值的数组(nativeParameters长度为nativeParameterCount)和一个指向函数的指针(void*到cdecl函数,这里是method->nativeFunction)被称为。现在我正在尝试这样做:

// Push parameters for call
if (nativeParameterCount != 0) {
    uint32_t count = 0;
pushParameter:
    uint32_t value = nativeParameters[nativeParameterCount - count - 1];
            asm("push %0" : : "r"(value));
    if (++count < nativeParameterCount) goto pushParameter;
}

// Call method
asm("call *%0" : : "r"(method->nativeFunction));

// Return value
uint32_t eax;
uint32_t edx;
asm("push %eax");
asm("push %edx");
asm("pop %0" : "=r"(edx));
asm("pop %0" : "=r"(eax));
uint64_t returnValue = eax;

// If the typesize of the methods return type is >4 bytes, or with EDX
Type returnType = method->returnType.type;
if (TYPE_SIZES[returnType] > 4) {
    returnValue |= (((uint64_t) edx) << 32);
}

// Clean stack
asm("add %%esp, %0" : : "r"(parameterByteSize));

此方法是否适合执行本机调用(假设所有目标函数仅接受32位值作为参数)?我可以确定它不会破坏堆栈或乱用寄存器,或者以某种方式影响正常流量吗?还有其他方法吗?

1 个答案:

答案 0 :(得分:2)

您可能不想自己手动执行此操作,而是可以使用dyncall libary来完成所有这些操作。