coderodde
coderodde

Reputation: 977

Hello world code for machine instruction generation at run time?

I sit on Intel MacOSX 10.6 and using GCC 4.2.1 under the hood. What I am attempting to do is to allocate a buffer, populate it with machine instructions, and run it. All in a single program.

For instance,

typedef unsigned char byte_t;

int main(int argc, char** argv) {
    byte_t* code = new byte_t[3];
    code[0] = 0x90; // NOP
    code[1] = 0xC9; // LEAVE - tried also without this.
    code[2] = 0xCB; // RET far - tried also 0xC3, the near return.
    ((void (*)(void)) code)();
    return 0;
}

fails with the message Bus error. What am I doing wrong here?

Upvotes: 1

Views: 214

Answers (1)

unwind
unwind

Reputation: 399823

The memory is not considered "safe" for code execution, so the operating system prevents it.

Look into using mmap() to allocate the memory, and use the PROT_EXEC to ask for the memory to be made executable.

Upvotes: 5

Related Questions