函数指针可以用于运行“数据"吗? [英] Can function pointers be used to run "data"?

查看:65
本文介绍了函数指针可以用于运行“数据"吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这不是大多数人可能会使用的东西,但是它浮现在脑海,烦扰了我.

This is not something most people would probably use, but it just came to mind and was bugging me.

是否可以在c字符串中包含一些机器代码,然后将其地址转换为函数指针,然后使用它来运行该机器代码?

Is it possible to have some machine code in say, a c-string, and then cast its address to a function pointer and then use it to run that machine code?

推荐答案

从理论上讲,根据卡尔·诺鲁姆(Carl Norum)的说法,您可以.这称为自我修改代码".

In theory you can, per Carl Norum. This is called "self-modifying code."

在实践中,通常会阻止您运行的是操作系统.大多数主要的现代操作系统都旨在区分可读",可读写"和可执行"内存.当这种OS内核加载程序时,会将代码放入一个特殊的可执行"页面,该页面标记为只读,因此用户应用程序无法对其进行修改.同时,尝试转到不在可执行"页面中的地址也将导致错误异常.这是出于安全目的,因为许多种类的恶意软件和病毒以及其他黑客攻击都依赖于使程序跳入修改后的内存中.例如,黑客可能会馈送应用程序数据,从而导致某些功能将恶意代码写入堆栈,然后运行它.

In practice what will usually stop you is the operating system. Most of the major modern operating systems are designed to make a distinction between "readable", "readwriteable", and "executable" memory. When this kind of OS kernel loads a program, it puts the code into a special "executable" page which is marked read-only, so that a user application cannot modify it; at the same time, trying to GOTO an address that is not in an "executable" page will also cause a fault exception. This is for security purposes, because many kinds of malware and viruses and other hacks depend upon making the program jump into modified memory. For example, a hacker might feed an app data that causes some function to write malicious code into the stack, and then run it.

但是,从本质上讲,操作系统本身加载程序所要做的正是您所描述的-它将代码加载到内存中,将内存标记为可执行文件,然后跳转到其中.

But at heart, what the operating system itself does to load a program is exactly what you describe -- it loads code into memory, flags the memory as executable, and jumps into it.

在嵌入式硬件世界中,可能没有适合您的操作系统,因此某些平台经常使用此操作系统.在PlayStation 2上,我一直都这样做-如果有一些特定于例如沙漠级别的代码,并且在其他地方都没有使用过,那么我就不会一直将其保留在内存中-而是我将其与沙漠级别一起加载,并修复指向正确的可执行文件的函数指针.当用户离开该级别时,我将从内存中转储该代码,将所有这些函数指针设置为异常处理程序,然后将下一个级别的代码加载到同一空间中.

In the embedded hardware world, there may not be an OS to get in your way, and so some platforms use this pretty regularly. On the PlayStation 2 I used to do this all the time -- if there was some code that was specific to, say, the desert level, and used nowhere else, I wouldn't keep it in memory all the time -- instead I'd load it along with the desert level, and fix up my function pointers to the right executable. When the user left the level, I'd dump that code from memory, set all those function pointers to an exception handler, and load the code for the next level into the same space.

这篇关于函数指针可以用于运行“数据"吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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