从机器代码调用 C++ 中的简单方法会导致分段错误

问题描述 投票:0回答:0

所以我想写一个简单的程序,用 C++ 从机器代码调用一个简单的方法,目标平台是 Windows x86-64。这是可重现的代码:

#include <windows.h>
#include <iostream>
#include <cstring>

void test(long long int val) {
    std::cout << "Calling test function:" << val << std::endl;
}

int main() {

    unsigned char code[] = {
            // Load the address of the target into RAX register.
            0x48, 0xB8, 0, 0, 0, 0, 0, 0, 0, 0, // mov rax, imm64
            0x48, 0xB9, 0, 0, 0, 0, 0, 0, 0, 0, // mov rcx, imm64
            0xFF, 0xD0, // call rax
            0xC3 // ret
    };

    // Simulation of test(12345);

    *((void **) &code[2]) = (void *) &test; // Pass the address of the function.
    *((long long int *) &code[12]) = 12345L; // Pass the argument.

    // Preparation
    SYSTEM_INFO sys_info;
    GetSystemInfo(&sys_info);
    auto const page_size = sys_info.dwPageSize;
    auto const code_buffer = VirtualAlloc(nullptr, page_size, MEM_COMMIT, PAGE_EXECUTE_READWRITE);
    ::memcpy(code_buffer, code, sizeof(code));

    using func_ptr_t = void (*)();
    auto const func_ptr = reinterpret_cast<func_ptr_t>(code_buffer);
    func_ptr();
    VirtualFree(code_buffer, 0, MEM_RELEASE);

    return 0;
}

所以这只是打印我们的字符串“调用测试函数:12345”,但我在函数调用期间遇到了分段错误

void test(long long int)
.

调试器证明函数调用成功,

val
的值也正确传递,但是在这行之后出现segmentation fault

有谁知道它的原因以及如何解决它?

非常感谢!

c++ assembly machine-code
© www.soinside.com 2019 - 2024. All rights reserved.