从数据部分执行一段代码 [英] Execute a piece of code from the data-section

查看:203
本文介绍了从数据部分执行一段代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想取一段代码,将其复制到全局数组中并从中执行。



换句话说,我试图复制



在这里,代码段中的一组指令被放入数据段,然后设置程序计数器从数据段继续执行程序。是我的代码:

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

typedef void(* func)();

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

#define CODE_SIZE 73
//在反汇编的code_section_func中验证了这个大小

静态长整型数据[(CODE_SIZE- 1)/ sizeof(long long)+1];
//我使用'long long'来获得最大对齐

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

我可能是天真的认为它可以工作,



例如,在将程序加载到内存后,MMU是否将指令限制到内存中的特定区域进程的地址空间(即程序的代码段)?



对于协议,我已经通过64位操作系统的VS2013编译器测试过了,

解决方案

感谢您使用基于x64的处理器。



<许多其他现代操作系统)默认情况下将数据部分设置为读/写/无执行,因此尝试调用数据对象将失败。



VirtualAlloc 一块内存与 PAGE_EXECUTE_READWRITE 保护。请注意,可能需要使用 FlushInstructionCache ,以确保执行新复制的代码。


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

解决方案

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.

这篇关于从数据部分执行一段代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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