gpt4 book ai didi

linux - 为什么 gcc 为 x64 共享库强制 PIC?

转载 作者:IT王子 更新时间:2023-10-29 00:03:18 26 4
gpt4 key购买 nike

尝试使用 gcc 将非 PIC 代码编译到 x64 上的共享库会导致错误,类似于:

/usr/bin/ld: /tmp/ccQ2ttcT.o: relocation R_X86_64_32 against `a local symbol' can not be used when making a shared object; recompile with -fPIC

这个问题是关于为什么会这样。我知道 x64 具有 RIP 相对寻址,旨在提高 PIC 代码的效率。然而,这并不意味着加载时重定位不能(理论上)应用于此类代码。

一些在线资源,包括 this one (在这个问题上被广泛引用)声称在共享库中存在一些禁止非 PIC 代码的固有限制,因为 RIP 相对寻址。我不明白为什么这是真的。

考虑“旧 x86”- call 指令也有一个 IP 相关操作数。然而,其中包含 call 的 x86 代码可以很好地编译成没有 PIC 的共享库,但使用 load-time relocation R_386_PC32。不能对 x64 中的数据 RIP 相对寻址做同样的事情吗?

请注意,我完全理解 PIC 代码的好处,RIP 相对寻址的性能损失有助于缓解。尽管如此,我还是很好奇不允许使用非 PIC 代码的原因。它背后是否有真正的技术原因,或者只是为了鼓励编写 PIC 代码?

最佳答案

这是我从 a post on comp.unix.programmer 读到的最好的解释:

Shared libs need PIC on x86-64, or more accurately, relocatable code has to be PIC. This is because a 32-bit immediate address operand used in the code might need more than 32 bits after relocation. If this happens, there is nowhere to write the new value.

关于linux - 为什么 gcc 为 x64 共享库强制 PIC?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7865059/

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