用气体(-fPIC)生成与位置无关的代码 [英] Generating position independent code with gas (-fPIC)

查看:153
本文介绍了用气体(-fPIC)生成与位置无关的代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我尝试在x86-64上创建共享库,但是失败.问题归结为以下代码(请不要介意,这没有任何意义):

I try to create a shared library on x86-64 but fail. The problem boils down to the following code (please don't mind, that it does not make a lot of sense):

.section .data
newline:
    .ascii "\n"

.section .text
.globl write_newline
    .type write_newline, @function
write_newline: 
    mov  $newline, %rax    
    ret

构建如下:

as minimal.s -o minimal.o
ld -shared minimal.o -o libmin.so

导致以下错误:

ld: minimal.o: relocation R_X86_64_32 against `.data' can not be used when making a shared object; recompile with -fPIC
minimal.o: error adding symbols: Bad value

但是gas不知道选项-fPIC,所以我不能用它重新编译:

But gas doesn't know option -fPIC, so I cannot recompile with it:

as -fPIC minimal.s -o minimal.o
as: unrecognized option '-PIC'

该怎么办呢?

推荐答案

正如Marc B在评论中所说,错误消息假定您正在使用GCC或其他某种编译器.由于您已经用汇编语言编写了代码,因此您有责任确保代码与位置无关.

As Marc B said in the comments, the error message assumes you were using GCC or so some other compiler. Since you've written the code in assembly its your responsibility to ensure that your code is position independent.

在x86-64目标上,您可以使用RIP相对寻址解决此错误:

On x86-64 targets you can resolve this error using RIP relative addressing:

        .section .data
newline:
    .ascii "\n"

.section .text
.globl write_newline
    .type write_newline, @function
write_newline:
    lea  newline(%rip), %rax
    ret

请注意,由于newline是本地符号,因此您无需在此处使用GOT.如果它是全局的,并且您希望在代码中对newline的引用能够在其他某些运行时组件中引用newline的其他定义,那么您将需要使用@GOTPCREL重定位.这将允许动态链接程序更改GOT中的条目以指向newline的不同定义.

Note that you don't need to use the GOT here because newline is a local symbol. If it were global, and you wanted the reference to newline in your code to able to refer to some other definition of newline in some other runtime component, then you would need to use an @GOTPCREL relocation. That would allow the dynamic linker to change the entry in the GOT to point to a different definition of newline.

这篇关于用气体(-fPIC)生成与位置无关的代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆