Relocation error when compiling NASM code in 64-bit mode

岁酱吖の 提交于 2019-12-13 00:34:04

问题


I have written a simple assembly code which I am trying to compile in 64-bit mode. Here is the code:

extern printf

section .rodata
readinfo db `%d\n`, 0

section .text
global main
main:
mov rbp, rsp ; for correct debugging

mov rax, 5
push rax
push readinfo
call printf
add rsp, 8

xor rax, rax
mov rsp, rbp
ret

And here are the instructions I give to nasm and gcc (as I have read on other posts, gcc automatically links the object file with the default c libraries):

nasm -f elf64 -o test.o test.asm -D UNIX
gcc -o test test.o

However, I get the following relocation error:

/usr/bin/x86_64-linux-gnu-ld: test.o: relocation R_X86_64_32S against `.rodata' can not be used when making a PIE object; recompile with -fPIC

/usr/bin/x86_64-linux-gnu-ld: final link failed: Nonrepresentable section on output

collect2: error: ld returned 1 exit status

When I compile with the '-no-pic' option to disable positionally-independent code, it compiles without errors, but after execution I get a segfault with no output. When I recompile the code in 32-bit (replacing 64-bit registers with 32-bit), I get no error. The commands are:

nasm -f elf32 -o test.o test.asm -D UNIX
gcc -o test test.o -m32

My question is: why can't I compile the code with PIC in 64bit mode?

PS: This is not a duplicate of Can't link a shared library from an x86-64 object from assembly because of PIC , since the error is different and the solution found in that post has nothing in relation with my problem. I have edited the error output to specify.


回答1:


The mistake was that I was using the wrong calling convention. In architecture x86_64 the first two arguments are passed in rdi and rsi, respectively, without using the stack. Also, I needed to add "wrt ..plt" to the call. The following code works:

extern printf

section .rodata
readinfo db `%d\n`, 0

section .text
global main
main:
mov rbp, rsp ; for correct debugging

mov rsi, 5
mov rdi, readinfo
xor rax, rax
call printf wrt ..plt

xor rax, rax
mov rsp, rbp
ret

The commands for nasm and gcc haven't changed.



来源:https://stackoverflow.com/questions/51407270/relocation-error-when-compiling-nasm-code-in-64-bit-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!