动态重定位代码部分 [英] Dynamic relocation of code section

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

问题描述

只是出于好奇,我想知道是否有可能在此期间重新定位一段代码 程序的执行.例如,我有一个函数,这个函数应该 每次执行后都将其替换在内存中.一个想法浮现在我们的脑海 是使用自我修改的代码来做到这一点.根据一些在线资源,自我修改 代码可以在Linux上执行,但是我仍然不确定是否可以进行这样的动态重定位.有人有经验吗?

Just out of curiosity I wonder if it is possible to relocate a piece of code during the execution of a program. For instance, I have a function and this function should be replaced in memory each time after it has been executed. One idea that came up our mind is to use self-modifying code to do that. According to some online resources, self-modifying code can be executed on Linux, but still I am not sure if such a dynamic relocation is possible. Has anyone experience with that?

推荐答案

是的,动态重定位肯定是可能的.但是,您必须确保代码完全独立,或通过绝对引用访问全局变量/外部函数.如果您的代码可以完全独立于位置,这意味着它所做的唯一引用是相对于其自身的,那么您就设置了.否则,您将需要在加载时自行进行修复.

Yes dynamic relocation is definitely possible. However, you have to make sure that the code is completely self-contained, or that it accesses globals/external functions by absolute references. If your code can be completely position independent, meaning the only references it makes are relative to itself, you're set. Otherwise you will need to do the fixups yourself at loading time.

对于GCC,您可以使用-fpic生成与位置无关的代码.将-q--emit-relocs传递给链接器将使其发出重定位信息. ELF规范(PDF链接)包含有关如何使用该重定位信息的信息.如果您不使用ELF,则必须找到适合您格式的文档.

With GCC, you can use -fpic to generate position independent code. Passing -q or --emit-relocs to the linker will make it emit relocation information. The ELF specification (PDF link) has information about how to use that relocation information; if you're not using ELF, you'll have to find the appropriate documentation for your format.

这篇关于动态重定位代码部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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