Execute a piece of code from the data-section

一个人想着一个人 提交于 2019-12-11 03:45:11

问题


I want to take a piece of code, copy it into a global array and execute it from there.

In other words, I am trying to to copy a bunch of instructions from the code-section into the data-section, and then set the program-counter to continue the execution of the program from the data-section.

Here is my code:

#include <stdio.h>
#include <string.h>

typedef void(*func)();

static void code_section_func()
{
    printf("hello");
}

#define CODE_SIZE 73
// I verified this size in the disassembly of 'code_section_func'

static long long data[(CODE_SIZE-1)/sizeof(long long)+1];
// I am using 'long long' in order to obtain the maximum alignment

int main()
{
    func data_section_func = (func)data;
    memcpy((void*)data_section_func,(void*)code_section_func,CODE_SIZE);
    data_section_func();
    return 0;
}

I might have been naive thinking it could work, so I'd be happy to get an explanation why it didn't.

For example, after a program is loaded into memory, does the MMU restrict instruction-fetching to a specific area within the memory address space of the process (i.e., the code-section of the program)?

For the protocol, I have tested this with VS2013 compiler over a 64-bit OS and an x64-based processor.

Thanks


回答1:


Windows (and many other modern OSes) by default sets the data section as read/write/no-execute, so attempting to "call" a data object will fail.

Instead, you should VirtualAlloc a chunk of memory with the PAGE_EXECUTE_READWRITE protection. Note, it may be necessary to use FlushInstructionCache to ensure the newly-copied code is executed.



来源:https://stackoverflow.com/questions/25311861/execute-a-piece-of-code-from-the-data-section

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!