0

I'm trying to call a C function from assembly. However my assembly code uses a .bss section which is causing me some troubles linking the file.

Here is the error I am getting

/usr/bin/ld: server.o: relocation R_X86_64_32S against `.bss' can not be used when making a PIE object; recompile with -fPIC
/usr/bin/ld: final link failed: Nonrepresentable section on output
collect2: error: ld returned 1 exit status
Makefile:8: recipe for target 'all' failed
make: *** [all] Error 1

I've created a minimal example of the issue I am having just to show the problem as clear as I can.

server.s

global main
extern send_to_queue

bits 64

section .bss 
    sockfd:             resq 1

section .text
main:
    push 99
    push 1
    mov rdi, 1
    mov rsi, 2
    call send_to_queue
    add rsp, 16

    ; return 0;
    mov rax, 0

    mov byte[sockfd], 10
    mov r10, [sockfd]
    ret

func.c

#include <stdio.h>

void send_to_queue(int log, int length) {
  printf("%d, %d", log, length);
}

makefile

OBJECTS = func.o server.o
CC = gcc
CFLAGS = -std=c11 -m64 -Wall -Wextra -Werror -c
AS = nasm
ASFLAGS = -elf64

all: $(OBJECTS)
    gcc -m64 $(OBJECTS) -o server

run: all
    ./server

%.o: %.c
    $(CC) $(CFLAGS)  $< -o $@

%.o: %.s
    $(AS) $(ASFLAGS) $< -o $@

clean:
    rm -rf $(OBJECTS) server

I have tried to use the flag -fPIC as the error message suggest however it is not working for me.I have also tried to use -static flag in the cflags but that also did not help. If anyone has some insight on this issue it would be appreciated. Thanks.

Michael Petch
  • 46,082
  • 8
  • 107
  • 198
questionerofdy
  • 513
  • 3
  • 7
  • In your server.s example as of now you are calling "c_function", which is undefined. Please fix the example. – ecm Jul 25 '19 at 13:14
  • Fixed. However the same issue remains. – questionerofdy Jul 25 '19 at 15:06
  • You need to make your assembly code position independent. With the code you have the issues are at these lines `mov byte[sockfd], 10` `mov r10, [sockfd]` . To make them RIP relative you could do `mov byte[rel sockfd], 10` `mov r10, [rel sockfd]` . Even better would be to simply add the directive `default rel` at the top of your assembly code. – Michael Petch Jul 25 '19 at 15:27
  • You forgot **`default rel`**. (And BTW, for `-static` to work, that would need to be in `LDFLAGS` - it's a linking option, irrelevant for compiling .c to .o where CFLAGS is used. – Peter Cordes Jul 25 '19 at 15:40

0 Answers0