1

Hey I have to call a function of glibc in assembly for an exercise. So I found this code to call printf.

section .rodata
    format: db 'Hello %s', 10
    name:   db 'Conrad'

section .text
        global main
        extern printf
    main:
        ; printf(format, name)
        mov rdi, format
        mov rsi, name
        call printf
        ; return 0
        mov rax, 0
        ret

But i get the error:

Symbol `printf' causes overflow in R_X86_64_PC32 relocation

Compiled it with:

nasm -f elf64 -o test.o test.asm

gcc -o test test.o

The error occurs after doing

./test

Jan Wolfram
  • 145
  • 8

2 Answers2

3

Change call printf to call printf@PLT. The former only works if the actual definition of printf is withing ±2GB of the call instruction, which can't be known if the definition is in a shared library (it would work if you static link, though). "Overflow" is telling you that the relative address, which would need to be up to 64-bit, overflows in a 32-bit call instruction offset.

By using printf@PLT, you'll instead get a relative address that resolves statically at link time to a thunk in the PLT, which loads and jumps to the address of the function definition, resolved at dynamic-linking time.

As Maxime B. noted, the loads of the addresses of format and name are also not correct for position-independent code. They should be loaded with "rip-relative" form, but it looks like you're using the weird "Intel syntax" for asm and I'm not sure how to write it in that syntax. You could, as Maxime B. suggested, build with -fno-pie, but better would be figuring out the way to fix your code so it doesn't depend on being linked for a particular fixed address.

R.. GitHub STOP HELPING ICE
  • 208,859
  • 35
  • 376
  • 711
2

You should compile your with -no-pie

This error is explained here. Quoting the original post:

Debian switched to PIC/PIE binaries in 64-bits mode & GCC in your case is trying to link your object as PIC, but it will encounter absolute address in mov $str, %rdi.

Federico klez Culloca
  • 26,308
  • 17
  • 56
  • 95
Maxime B.
  • 1,116
  • 8
  • 21