0

i try to use printf in my asm code but i get Segmentation fault(core dumped)

This is my code :

section .data
    msg db "current char is %d", 0x0a, 0x00

section .text
    global main
    extern printf


main:

    push rbp
    mov rbp, rsp

    push 123 
    push msg
    xor rax,rax
    call printf

    mov rsp, rbp
    pop rbp


    mov rax, 1
    mov rbx, 0
    int 0x80

BTW i use :

nasm elf64 file.asm

Then

gcc file.o

i would love any help or suggestions. thanks.

Jester
  • 56,577
  • 4
  • 81
  • 125
  • 4
    64 bit calling convention does not use the stack for passing arguments. PS: general tips: do not use `int 0x80` in 64 bit mode and do not mix syscalls with libc. – Jester Jun 11 '18 at 13:39
  • Relevant: [What happens if you use the 32-bit int 0x80 Linux ABI in 64-bit code?](https://stackoverflow.com/q/46087730/417501) – fuz Jun 11 '18 at 13:40
  • It's not clear what you are asking about (the code you posted should definitely segfault, i.e. it works as expected). Any help+suggestion: write working code? Learning first how assembly works, and how your target platform works helps a lot (assembly is not "guessable", like half of it makes quite some sense, but rest has many quirky details which are not guessable by common sense, so you need good resource to check for details and good debugger). – Ped7g Jun 11 '18 at 13:42
  • 2
    Amending @Jesters comment: See https://en.wikipedia.org/wiki/X86_calling_conventions#List_of_x86_calling_conventions for calling conventions on x86-64. – andreee Jun 11 '18 at 13:45
  • 2
    Which tutorial taught you to push function arguments on the stack and do system calls with `int 0x80` on amd64? These are such common mistakes to make that I start to wonder whether there is a tutorial that systematically teaches this mistake. – fuz Jun 11 '18 at 13:48
  • OK i get that i'm an idiot. the calling conventions on x86-64 was very helpful thank you andreee – omer tiko Jun 11 '18 at 14:09
  • 2
    @omertiko No, you are not an idiot! You have just been taught wrong. That happens. Don't feel bad about it. With assembly, never expect two platforms to work the same way, even if they are very similar. Only believe what you see written down in a manual or specification document. – fuz Jun 11 '18 at 15:11
  • exact duplicate of [Assembly NASM printf segmentation fault error](https://stackoverflow.com/q/50304517), which itself is closed as a dup of the system / function call Q&A. – Peter Cordes Jun 11 '18 at 17:25
  • @omertiko just stop guessing and use the information, which for this particular platform is available. It's not like you could have known magically, my comment was about that, you can't guess the correct way, don't even try. Search for documentation/specification, read through it, use it (or ask on stack overflow about particular part, if it's confusing). – Ped7g Jun 11 '18 at 17:28

0 Answers0