Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c - Execute a piece of code from the data-section

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...