如何使用c ++执行附加到可执行文件末尾的机器代码?

时间:2015-02-19 03:12:16

标签: c++ append executable binaryfiles machine-code

我有一个程序将机器代码附加到可执行文件的末尾,我想在可执行文件的开头编写一个c ++程序来运行附加的机器代码。然后,附加的代码将运行原始程序。

我的程序将在Mac上运行。

这里有一个类似的问题:Executing machine codes attached at the end of an executable 然而,问题没有得到解答,给出了替代解决方案。我不能使用链表,因为这个程序的目的是修改可能不一定安装了编译器的机器上的可执行文件的功能。

以下是一个例子:

// C++ program at the beginning of file, runs appended machine code.

// Original program, must be skipped over and run after appended machine code is run.

#include <iostream>
#include <stdio.h>
using namespace std;

int main()
{
    FILE *input,*output;
    char buffer[512];

    =fopen("a.out","rb");
    output=fopen("filename","ab");

    for(;fread(buffer,512,1,input)==1;)
        fwrite(buffer,512,1,output);
    fclose(output);
    cout << "Testing, testing, testing" << endl;

    //Run original program
}

1 个答案:

答案 0 :(得分:0)

You can make a program that creates an executable from the appended code and then executes it. Or if what you want is that the executable executes code appended to it, then you would have to call that appended code as a function or jump to that in inline assembly ("call" or "jmp").