0

I am trying to compile the following 64-bit code in Linux (Ubuntu 18.04 LTS):

global start

extern scanf, printf, exit

section .data
    read_name db '%255s', 0
    msg db 'Hello, %s', 0Ah, 0

section .text
start:
    sub rsp, 256
    mov rsi, rsp
    mov rdi, read_name
    call scanf
    mov rsi, rsp
    mov rdi, msg
    call printf
    add rsp, 256
    xor rdi, rdi
    call exit

This is how I compile my code:

nasm -f elf64 hello64.asm
gcc -nostartfiles -m64 -o hello64 hello64.o -Wl,--entry="start"

The code compiles without errors, but when I run it I get this segmentation fault:

./hello64: Symbol `scanf' causes overflow in R_X86_64_PC32 relocation
./hello64: Symbol `printf' causes overflow in R_X86_64_PC32 relocation
./hello64: Symbol `exit' causes overflow in R_X86_64_PC32 relocation
Segmentation fault (core dumped)

Not sure what is happening. Since this is 64-bit code, I would assume that the C functions use the System V AMD64 ABI, so I am calling them accordingly (first parameters in RDI, RSI, RDX, RCX, R8, R9). Can anybody help me understand what's wrong?

DarkAtom
  • 2,589
  • 1
  • 11
  • 27
  • It works with 32-bit code. I am using dynamic linking specifically because shared libraries run the startup code when they are loaded. – DarkAtom Apr 25 '20 at 22:46
  • 2
    You're building a PIE executable so the linker doesn't automatically generate a PLT for `call printf`. Use `-no-pie` or see the linked duplicate for the NASM syntax for a PLT or `-fno-plt` style of call to dynamically linked libc. Also, if you call your entry point `_start`, that's the default name that `ld` looks for so you don't need `-Wl,--entry=` – Peter Cordes Apr 25 '20 at 22:58

0 Answers0