0

I need to print the last element of the stack and I try to call printf but I don't know why I am getting a segmentation fault.

I am working with intel x86_64 architecture and mac os.

    .text
    .globl _main
    .p2align    4, 0x90
_main:
    push $12

    pop     %rdi
    callq   _dot

    mov         $0x02000001,    %rax
    mov         $0,             %rdi
    syscall

    .globl  _dot                            ## -- Begin function dot
    .p2align    4, 0x90

_dot:                                   ## @dot
## %bb.0:
    pushq   %rbp
    movq    %rsp, %rbp
    subq    $16, %rsp
    movl    %edi, -4(%rbp)
    movl    -4(%rbp), %esi
    leaq    format(%rip), %rdi
    movb    $0, %al
    callq   _printf
    addq    $16, %rsp
    popq    %rbp
    retq

format:                                 ## @.str
    .asciz  "%ld"

Another thing that I tried and failed is this ``` .text .globl _main _main: push $12

pop %rdi
leaq    format(%rip), %rdi
movb    $0, %al
callq   _printf
retq

Update:

I fixed the first one for some cases The code below works fine when in the stack there is an odd number of elements otherwise I again get a segmentation fault. If I for example push a second number to the stack it crashes, three is okay and so on.

    .text
    .globl _main
    .p2align    4, 0x90
_main:
    push        $12

    # .
    pop     %rdi
    pushq   %rbp
    movq    %rsp, %rbp
    callq   _dot
    xorl    %eax, %eax
    popq    %rbp

    mov         $0x02000001,    %rax
    mov         $0,             %rdi
    syscall

    .globl  _dot
_dot:
    pushq   %rbp
    movq    %rsp, %rbp
    subq    $16, %rsp
    movl    %edi, -4(%rbp)
    movl    -4(%rbp), %esi
    leaq    format(%rip), %rdi
    movb    $0, %al
    callq   _printf
    addq    $16, %rsp
    popq    %rbp
    retq

format:
    .asciz  "%d\n"
VardanMelkonyan
  • 486
  • 1
  • 4
  • 11
  • Probably a stack alignment issue. Where does it crash? Have you tried using a debugger? – fuz Dec 19 '21 at 14:58
  • Or that stdout is line-buffered and the format string doesn't include a newline, and a raw `_exit` syscall doesn't trigger atexit libc functions like flushing stdout. This is why it's not recommended to mix printf with raw system calls unless you know what you're doing. – Peter Cordes Dec 19 '21 at 15:15
  • Oh, oops, yeah a segfault is likely stack alignment; register args look right at the point of the call. [Using printf in assembly leads to empty output when piping, but works on the terminal](https://stackoverflow.com/q/38379553) would only explain empty output after you fix that. This is MacOS, but the actual bug in stack alignment is the same as in [glibc scanf Segmentation faults when called from a function that doesn't align RSP](https://stackoverflow.com/q/51070716), assuming `_main` is a normal function that's entered with RSP%16 = 8. (And that you could just `ret` from...) – Peter Cordes Dec 19 '21 at 15:21

0 Answers0