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.
push readinfo
is not position independent. You could dolea rax, [rel readinfo]
push rax
. But forget that. In 64-bit Linux code the first parameters are passed in registers.(not on the stack). You'd also need to changecall printf
tocall printf wrt ..plt
– Michael Petchxor eax, eax
lea rdi, [rel readinfo]
mov esi, 5
call printf wrt ..plt
. Register AL has to be set to the number of vector registers use which in this case is 0. So I use XOR EAX, EAX to zero RAX. First integer class parameter is in RDI, second in RSI – Michael Petchprintf
is a variadic function (not a fixed number of arguments) and variadic functions are also covered in the ABI. – Michael Petch