我编写了下面的汇编代码,它可以直接构建 pass by as 和 ld。
as cpuid.s -o cpuid.o
ld cpuid.o -o cpuid
但是当我使用 gcc 来完成整个过程时。我遇到以下错误。
$ gcc cpuid.s -o cpuid
/tmp/cctNMsIU.o: In function `_start':
(.text+0x0): multiple definition of `_start'
/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/Scrt1.o:(.text+0x0): first defined here
/usr/bin/ld: /tmp/cctNMsIU.o: relocation R_X86_64_32 against `.data' can not be used when making a shared object; recompile with -fPIC
/usr/lib/gcc/x86_64-linux-gnu/7/../../../x86_64-linux-gnu/Scrt1.o: In function `_start':
(.text+0x20): undefined reference to `main'
/usr/bin/ld: final link failed: Invalid operation
collect2: error: ld returned 1 exit status
然后我_start修改为 main,并将 -fPIC 添加到 gcc 参数。但它不能解决我的 ld 错误。错误消息更改为下面。
$ gcc cpuid.s -o cpuid
/usr/bin/ld: /tmp/ccYCG80T.o: relocation R_X86_64_32 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
我不明白这是什么意思,因为我不做一个共享对象。我只想制作一个可执行的二进制文件。
.section .data
output:
.ascii "The processor Vendor ID is 'xxxxxxxxxxxx'n"
.section .text
.global _start
_start:
movl $0, %eax
cpuid
movl $output, %edi
movl %ebx, 28(%edi)
movl %edx, 32(%edi)
movl %ecx, 36(%edi)
movl $4, %eax
movl $1, %ebx
movl $output, %ecx
movl $42, %edx
int $0x80
movl $1, %eax
movl $0, %ebx
int $0x80
如果我将上面的代码修改为下面,它是否正确或对 64 位 asm 编程有一些副作用?
.section .data
output:
.ascii "The processor Vendor ID is 'xxxxxxxxxxxx'n"
.section .text
.global main
main:
movq $0, %rax
cpuid
lea output(%rip), %rdi
movl %ebx, 28(%rdi)
movl %edx, 32(%rdi)
movl %ecx, 36(%rdi)
movq %rdi, %r10
movq $1, %rax
movq $1, %rdi
movq %r10, %rsi
movq $42, %rdx
syscall
正如评论所指出的,您可以通过将程序链接为非 PIE 来解决此问题,但最好将您的 asm 修复为与位置无关。如果是 32 位 x86 代码,那就有点难看了。本说明:
movl $output, %edi
将变成:
call 1f
1: pop %edi
add $output-1b, %edi
对于 64 位,它要干净得多。而不是:
movq $output, %rdi
你会写:
lea output(%rip), %rdi
使用 NASM,我通过在源文件中放置"DEFAULT REL"行来解决此问题(检查 nasmdoc.pdf第 76 页(。