gpt4 book ai didi

linux - 链接器如何将程序头添加到可重定位文件?

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:03:54 26 4
gpt4 key购买 nike

所以我们知道 linker(在我的例子中是 ld)将 Program Headers 添加到 Relocatable file在创建实际的 Executable 时。

然后这些 header 用于在运行时将程序加载到内存中。

  • 首先,ld 是如何计算这些 header 并将其添加到文件中的?

  • 如果 Program Headers 仅用于将程序加载到内存中(如果我错了请纠正我),为什么不同的可执行文件具有不同数量的 Program header ?

例如,一个用汇编语言编写的简单 helloworld 有2 个程序头:

readelf -h helloworld
...
Number of program headers: 2
...

但是 bash11 个程序头:

readelf -h /bin/bash
...
Number of program headers: 11
...

最佳答案

First of all how ld calculates and adds these headers to the file?

这个问题太笼统了,不好回答。您不妨阅读this series解释链接器工作原理的博文。

And then if the Program Headers are used only to load the program into memory (correct me if I'm wrong), how come different executables have different number of Program Headers?

可执行文件有不同数量的程序头,因为它们有不同的需求。

例如,一个完全静态的可执行文件不需要与动态链接器进行任何交互,因此不需要 PT_DYNAMIC 段(以及描述该段的程序头)。

常见的动态链接可执行文件将至少有两个 PT_LOAD 段(数据和代码),PT_INTERP(告诉使用哪个运行时加载器),PT_DYNAMIC(告知要使用哪些共享库,以及 ld.so 的其他信息)、PT_NOTE(用于链接器构建 ID)和 PT_PHDR。其中每一个都有自己的程序头。

关于linux - 链接器如何将程序头添加到可重定位文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51966583/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com