如何从 ELF 二进制文件中删除程序头
我想编写一个实用程序来从 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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
?当然:程序头在
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
段“覆盖”。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
toPT_NULL
is another (and simpler) approach. But such entries are generally not expected to be present, and you may find some systems wherePT_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 entirePhdr
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 anyPT_LOAD
segment.GNU 二进制文件描述符库 (libbfd) 可能会有所帮助。
The GNU Binary File Descriptor library (libbfd) may be helpful.