解引用C中的函数指针以访问CODE存储器 [英] Dereferencing function pointers in C to access CODE memory

查看:109
本文介绍了解引用C中的函数指针以访问CODE存储器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在这里处理C.我只是有这个想法,想知道是否有可能访问存储函数的内存中的点,例如foo,然后将函数的内容复制到内存中的另一点.具体来说,我正在尝试以下工作:

We are dealing with C here. I'm just had this idea, wondering if it is possible to access the point in memory where a function is stored, say foo and copying the contents of the function to another point in memory. Specifically, I'm trying to get the following to work:

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

void foo(){
    printf("Hello World");
}

int main(){

    void (*bar)(void) = malloc(sizeof foo);
    memcpy(&bar, &foo, sizeof foo);


    bar();
    return 0;
}

但是运行它会产生总线错误:Bus error: 10.我试图将功能foo的内容复制到内存bar的空间中,然后执行新创建的功能bar.

But running it gives a bus error: Bus error: 10. I'm trying to copy over the contents of function foo into a space of memory bar and then executing the newly created function bar.

除了查看这种事情是否可行,揭示C语言的复杂性外,这没有其他原因.我没有考虑这有什么实际用途.

This is for no other reason than to see if such a thing is possible, to reveal the intricacies of the C language. I'm not thinking about what practical uses this has.

我正在寻找使此功能正常运行的指南,或者出于某种原因而被告知的原因

EDIT 查看一些答案,并了解 read write executable 内存,我刚刚意识到,可以通过写入可执行内存在C语言中动态创建函数.

EDIT Looking at some of the answers and learning about read, write, and executable memory, it just dawned upon me that it would be possible to create functions on the fly in C by writing to executable memory.

推荐答案

使用标准C,您尝试执行的是实现定义的行为,并且无法移植.在给定的平台上,您也许可以完成这项工作.

With standard C, what you try to do is implementation defined behaviour and won't work portably. On a given platform, you might be able to make this work.

malloc给您的内存通常是不可执行的.跳到那里会导致总线错误(SIGBUS).假设您使用的是类似POSIX的系统,请使用mmap和使内存区域可执行的标志为函数分配内存,或者使用mprotect将区域标记为可执行.

The memory malloc gives you is typically not executable. Jumping there causes a bus error (SIGBUS). Assuming you are on a POSIX-like system, either allocate the memory for the function with mmap and flags that cause the memory region to be executable or use mprotect to mark the region as executable.

您还需要更加小心地提供您所提供的内存,您不能简单地考虑一个函数的大小并期望它是函数的长度,sizeof并非旨在提供这种功能.您需要使用其他方法找出函数长度.

You also need to be more careful with the amount of memory you provide, you cannot simply take the size of a function and expect that to be the length of the function, sizeof is not designed to provide this kind of functionality. You need to find out the function length using some other approach.

这篇关于解引用C中的函数指针以访问CODE存储器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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