从 x86_64 程序集调用函数

Call functions from x86_64 assembly

我正在尝试创建自己的 JIT 并且到目前为止设法 运行 非常简单的汇编代码(机器代码),但无法弄清楚如何以这种方式调用函数。在 Visual Studio 中,我可以在反汇编中看到函数 window。

另一个相关问题是如何在机器代码中调用 Win32 MessageBox()?

下一个问题是如何以这种方式调用外部 DLL/LIB 函数?

另外,是否有任何书籍或教程可以进一步教我这方面的知识?我试图搜索它,但得到的结果是 .NET、JVM 和 LLVM,我认为这并不是我真正想要的。

这是我正在处理的代码的简化版本:

#include <iostream>
#include <Windows.h>

int main(int argc, char* argv[])
{
    // b8 03 00 00 00 83 c0 02 c3
    unsigned char code[] = {
        0xb8,                   // mov eax, 3
        0x03, 0x00, 0x00, 0x00, // 3 (32 bit)
        0x83,                   // add eax, 2 // 0x83 = add,
        0xc0,                   // ModR/M with immediate 8 bit value
        0x02,                   // 2 (8 bit)
        0xc3                    // ret
    };

    void* mem = VirtualAlloc(0, sizeof(code), MEM_COMMIT, PAGE_EXECUTE_READWRITE);

    memcpy(mem, code, sizeof(code));

    DWORD old;
    VirtualProtect(mem, sizeof(mem), PAGE_EXECUTE_READ, &old);

    int(*func)() = reinterpret_cast<int(*)()>(mem);

    printf("Number is %d\n", func());

    VirtualFree(mem, 0, MEM_RELEASE);

    return 0;
}

是否可以让 JIT 汇编代码调用 C++ 函数?

在这个项目之前,我用 C++ 编写了一个字节码解释器,但在将它与等效的 C# 测试程序进行比较时,我对速度并不满意。 C# 大约快 25 倍。所以我偶然发现了一种叫做 JIT 的东西来让它更快。所以我希望你们都能看到我把这个 JIT 项目带到哪里去了。也许如果可能的话让它处理 GUI。

您或许可以找到一些有关编写 compiler/linker 的教程。它可能对 implementing/calling 动态库有帮助。

我不确定调用 C++ 函数的确切含义。不管怎样,我写了下面的演示程序,你可以看看它是否有帮助。

#include <Windows.h>
#include <iostream>


using namespace std;

__int64 sub(__int64 a, __int64 b)
{
    return a - b;
}

int main(int argc, char **argv)
{
    char code[] =
    {
        0x48, 0x89, 0xC8,           // mov rax, rcx
        0xC3,                       // ret

        0x48, 0x83, 0xEC, 0x20,     // sub rsp, 0x20
        0xFF, 0xD0,                 // call rax
        0x48, 0x83, 0xC4, 0x20,     // add rsp, 0x20
        0xC3                        // ret
    };


    char *mem = static_cast<char *>(VirtualAlloc(0, sizeof(code), MEM_COMMIT, PAGE_EXECUTE_READWRITE));

    MoveMemory(mem, code, sizeof(code));

    auto setFunc = reinterpret_cast<void *(*)(void *)>(mem);
    auto callFunc = reinterpret_cast<__int64 (*)(__int64, __int64)>(mem + 4);

    setFunc(sub);
    __int64 r = callFunc(0, 1);
    cout << "r = " << r << endl;

    VirtualFree(mem, 0, MEM_RELEASE);


    cin.ignore();
    return 0;
}