Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

"relocation R_X86_64_32S against `.bss' can not be used when making a shared object”

I'm absolutely green in this but during classes, teacher gave us file he wrote just for us to run it and it worked fine then, but when I try to do it at home (I use Linux on VirtualBox) and use:

nasm -f elf64 hello.asm -o hello.o
gcc hello.o -o hello

I get an error "relocation R_X86_64_32S against `.bss' can not be used when making a shared object; recompile with -fPIC”. Can someone please explain what to do to make it work?

global main
extern printf

section .data
napis:      db ' Hello world! - po raz %ld',10,0

liczba_iteracji: equ 5

section .bss
licznik: resb 1

section .text

main:

push    rbp
mov rbp,rsp

mov byte [licznik],0

petla:              ;naiwna!

inc byte [licznik]

mov rdi, qword napis
mov rsi, qword [licznik]
mov rax, 0
call    printf

cmp byte [licznik],liczba_iteracji
jnz petla

mov rsp,rbp
pop rbp

mov rax,1           ;SYS_EXIT
mov rbx,0
int 80h
like image 238
overflow Avatar asked Oct 18 '22 21:10

overflow


2 Answers

You need to make certain you're writing position independent code. The idea of PIC is that to make code truly position-independent, you need at least one level of indirection. That level of indirection is IP-relative addressing, and when that is not enough, you will need a second layer, the Global Offset Table or GOT.

In NASM, you will find the DEFAULT REL directive(s) useful.

like image 198
Michael Foukarakis Avatar answered Oct 21 '22 05:10

Michael Foukarakis


I had the same issue. The reason GCC gives this error is because it assumes (version 6.3.0 here) you are building a shared object (when, clearly, you are not), therefore presence of .bss makes it crazy. So you can either fix this by passing -static option: gcc hello.o -static -o hello (worked in my case), or using Clang as a linker: clang hello.o -o hello. No complaints from the latter.

like image 34
AlexDarkVoid Avatar answered Oct 21 '22 05:10

AlexDarkVoid