1
section .text
extern printf
global main
main:
    push 10 ; Parameter
    push mymsg ; Adresse
    call printf
    ;add rsp, 8
    mov rax, 1 ; sys_exit
    mov rbx, 0 ; return 0 (success)
    int 80h
section .data
    mymsg db 'Hello World %d!', 0xa

Compiling it @Linux64Bit

nasm -f elf64 printf.asm
gcc printf.o -o printf
./printf

--> Error: Segmentation fault (code dumped)

Whats wrong with that code?

  • 2
    You are pushing arguments for `printf` into stack, but that's not the correct calling convetion for Linux 64b ABI. (would you add tags [x86] and [x86-64], I would be like two clicks away from finding the "info" tab on tag, and search for link for the ABI docs). – Ped7g May 12 '18 at 09:06
  • added tag, thanks :-) –  May 12 '18 at 09:07
  • Hint "The first six integer arguments (from the left) are passed in `RDI, RSI, RDX, RCX, R8, and R9`, *in that order*, all additional arguments are pushed onto the stack in reverse order." – David C. Rankin May 12 '18 at 09:10
  • added possible duplicate with long answer, where you should be able to find also x86-64 calling functions explained.. Or you have other option to cross check this, in case of some confusion, create small C/C++ source with a function call which you want to use (even online in godbolt, just pick correct platform options), and see yourself how the C compiler does call the function. Make sure in asm you keep track of `rsp` alignment. – Ped7g May 12 '18 at 09:10
  • 1
    And about tags.... I meant mostly [x86] info page: https://stackoverflow.com/tags/x86/info ... where you can find many many resources (links). Plus of course when you have segfault, you can use debugger to verify first that you prepared stack as you did want, and then you can report the `call` did segfault. And you shouldn't use `int 80h` in 64b target either: [What happens if you use the 32-bit int 0x80 Linux ABI in 64-bit code?](https://stackoverflow.com/q/46087730/4271923) – Ped7g May 12 '18 at 09:12
  • ok thanks. My code is running now! –  May 12 '18 at 09:18

0 Answers0