如何从 ELF 二进制文件中删除程序头

发布于 2024-11-05 02:23:50 字数 192 浏览 1 评论 0原文

我想编写一个实用程序来从 ELF 二进制文件中删除程序头。例如,当我运行 readelf -l /my/elf 时,我会得到所有程序头的列表:PHDR INTERP ... GNU_STACK GNU_RELRO。当我运行我的实用程序时,我希望以相同的顺序返回所有相同的程序头,减去我删除的程序头。有没有比从头开始重新创建整个 ELF 并跳过不需要的标头更简单的方法呢?

I want to write a utility to remove a program header from an ELF binary. For example, when I run readelf -l /my/elf I get a listing of all the program headers: PHDR INTERP ... GNU_STACK GNU_RELRO. When I run my utility, I would like to get all the same program headers back in the same order, minus the one I deleted. Is there any easier way to do this than recreated the entire ELF from scratch, skipping the unwanted header?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

坏尐絯 2024-11-12 02:23:50

有没有比从头开始重新创建整个 ELF 更简单的方法

?当然:程序头在 ehdr.e_phoff 给定的偏移量处形成一个固定记录表,其中包含 .e_phnum .e_phentsize 字节的条目。

要删除一个条目,只需将其余条目复制到其上,然后递减 .e_phnum 即可。这就是全部内容了。

请注意:删除某些条目可能会导致动态加载器崩溃。 GNU_STACK 是唯一可以删除而不会造成太大损害的标头(我能想到的)。

更新:

是的,将 .p_type 设置为 PT_NULL 是另一种(也是更简单的)方法。但是这样的条目通常不会出现,并且您可能会发现某些系统中 PT_NULL 将在加载程序(或其他程序)中触发断言。

最后,添加新的 Phdr 可能会很棘手。通常没有空间来扩展表格(因为它后面紧跟着一些其他数据,例如.text)。您可以将表重新定位到文件末尾,并设置.e_phoff.e_phnum以对应于新表,但许多程序期望整个Phdr 表要在运行时加载并可用,这并不容易安排,因为文件末尾的新位置不会被任何 PT_LOAD 段“覆盖”。

Is there any easier way to do this than recreated the entire ELF from scratch

Sure: program headers form a fixed-record table at an offset given by ehdr.e_phoff, containing .e_phnum entries of .e_phentsize bytes.

To delete one entry, simply copy the rest of entries over it, and decrement .e_phnum. That's all there is to it.

Beware: deleting some entries will likely cause the dynamic loader to crash. GNU_STACK is about the only header that can be deleted without too much harm (that I can think of).

Update:

Yes, setting .p_type to PT_NULL is another (and simpler) approach. But such entries are generally not expected to be present, and you may find some systems where PT_NULL will trigger an assertion in the loader (or in some other program).

Finally, adding a new Phdr might be tricky. Usually there is no space to expand the table (as it is immediately followed by some other data, e.g. .text). You can relocate the table to the end of the file, and set .e_phoff and .e_phnum to correspond to the new table, but many programs expect the entire Phdr table to be loaded and available at runtime, and that is not easy to arrange, as the new location at the end of the file will not be "covered" by any PT_LOAD segment.

得不到的就毁灭 2024-11-12 02:23:50

GNU 二进制文件描述符库 (libbfd) 可能会有所帮助。

The GNU Binary File Descriptor library (libbfd) may be helpful.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文