使用 GCC 进行组装会导致关于 .data 的奇怪的重定位错误

Assembling with GCC causes weird relocation error with regards to .data

这是一个以前从未发生过的问题。我非常确信这可能是我的软件包存储库的问题(我最近重新安装了我的 Arch 系统,这才刚刚开始发生)。

我在x86_64写了一个小hello world:

.data
str:    .asciz  "Test"

.text
.globl main
main:
    sub , %rsp
    mov $str, %rdi
    call puts
    add , %rsp
    ret

然后我尝试使用 GCC 进行组装和 link - 就像我过去做过很多次一样 - 只需:

gcc test.s -o test

然后输出这个错误:

/usr/bin/ld: /tmp/ccAKVV4D.o: relocation R_X86_64_32S against `.data' can not be used when making a shared object; recompile with -fPIC /usr/bin/ld: final link failed: Nonrepresentable section on output collect2: error: ld returned 1 exit status

这个错误我从来没有发生过。我试图通过谷歌搜索相同的错误消息来解决这个问题,但它提出了非常具体的事情,而我认为这是一个普遍的问题。我试过重新安装 base-devel 和整个 GCC 工具链。我不知道我还能做什么(请不要建议使用nasm,那是异端)。

我想我遗漏了一些明显的东西,但我已经使用 GCC 来满足我的组装需求很长时间了。

解决此错误的方法是生成一个 no-pie(非位置独立可执行文件)可执行文件:

gcc -no-pie test.s -o test

此行为的原因如@Ped7g 所解释:

Debian 在 64 位模式下切换到 PIC/PIE 二进制文件,在你的情况下 GCC 试图 link 你的对象作为 PIC,但它会在 mov $str, %rdi.

中遇到绝对地址