如何调用存储在char数组中的机器代码? [英] How to call machine code stored in char array?

查看:195
本文介绍了如何调用存储在char数组中的机器代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试调用本机机器语言代码。这是我到目前为止(它得到一个总线错误):

I'm trying to call native machine-language code. Here's what I have so far (it gets a bus error):

char prog[] = {'\xc3'}; // x86 ret instruction

int main()
{
    typedef double (*dfunc)();

    dfunc d = (dfunc)(&prog[0]);
    (*d)();
    return 0;
}

它正确地调用该函数,并获取到ret指令。但是当它试图执行ret指令时,它有一个SIGBUS错误。是因为我在一个不能执行的页面上执行代码或类似的东西?

It does correctly call the function and it gets to the ret instruction. But when it tries to execute the ret instruction, it has a SIGBUS error. Is it because I'm executing code on a page that is not cleared for execution or something like that?

那么我在这里做错了什么?

So what am I doing wrong here?

推荐答案

第一个问题可能是存储了prog数据的位置不可执行。

One first problem might be that the location where the prog data is stored is not executable.

至少在Linux上,生成的二进制文件会将全局变量的内容放在datasegment 此处,它不能在最常见的情况

On Linux at least, the resulting binary will place the contents of global variables in the "data" segment or here, which is not executable in most normal cases.

第二个问题可能是你调用的代码在某种程度上是无效的。有一个特定的过程来调用C中的方法,称为调用约定(您可能使用的是cdecl例如)。这可能不足以使被调用的函数只是ret。它可能还需要做一些堆栈清理等,否则程序会表现异常。这可能会在您遇到第一个问题后出现问题。

The second problem might be that the code you are invoking is invalid in some way. There's a certain procedure to calling a method in C, called the calling convention (you might be using the "cdecl" one, for example). It might not be enough for the called function to just "ret". It might also need to do some stack cleanup etc. otherwise the program will behave unexpectedly. This might prove an issue once you get past the first problem.

这篇关于如何调用存储在char数组中的机器代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆