Search code examples
assemblyatt

Segmentation fault basic assembly


   .text
.global main
// code for main
main:
   push %r13
   push %r14
   push %r15
   pushq  $2
   call  show
   pop %r15
   pop %r14
   pop %r13
   mov $0,%rax
   ret
// code for show
show:
    popq   x
    pushq x
    popq    gen
    lea genfmt_(%rip),%rdi
    movq gen(%rip),%rsi
    .extern printf
    call printf
    ret
.data
 gen:    .quad 0
 genfmt_: .byte '%','u',10,0
 x:   .quad 0

The title pretty much sums it up. I have no idea why this is generating a segmentation fault error. From my understanding the stack pointer is aligned when I push r15,r14,r13 I then keep it aligned before calling print f. I'm new to assembly so any help is appreciated!


Solution

  • show:
        popq   x
    

    is an obvious bug. The first thing on the stack on entry to a function is a return address. You're going to have a problem when you try to ret since you've clobbered the return address.

    Also, the standard calling convention / ABI for 64bit code passes args in registers, so you're not passing sensible args to printf. (You can pass args between your own asm functions however you like, as long as you don't want to call them from C.)

    See the tag wiki for more docs on calling conventions. Also for info on using a debugger, which would have let you ask a better question (by showing which instruction generated the segfault, and what address it was trying to access.)