0

I have encountered a problem with printf spitting out segfaults whenever there is only one element in the stack. Here, what I want the script to do is print 5, only then do the add operation, but segmentation fault happens.

Interestingly, if I push 6 right after I push 5 and then print, it works. Thus, I suppose the problem occurs when there is only one element in the stack.

Any ideas?

Thank you in advance!

.fmt:
    .asciz "%d\n"
.text

.globl _start

_start: 
    push $5

    pop %rdx
    mov %rdx, %rsi
    push %rdx
    mov $.fmt, %rdi
    call printf
    xor %rax, %rax

    push $6

    pop %rdx
    pop %rcx
    add %rdx, %rcx
    push %rcx

    mov $60, %rax
    pop %rdi
    syscall
Michael Petch
  • 46,082
  • 8
  • 107
  • 198
  • 1
    The AMD64 ABI requires the stack be aligned (16 bytes by default) before calling a ABI compliant function like `printf`. Likely it fails because of the stack being improperly aligned. – Michael Petch Dec 17 '22 at 12:43
  • 1
    Also the `xor %rax, %rax` should be before the `printf` to indicate no SSE registers used. Furthermore if you intend to use C library you should in general use `main` entry point and do not use syscalls directly. – Jester Dec 17 '22 at 12:44
  • Since you need to zero `AL` before printf with `xor %eax,%eax`, you can `lea 5(%rax), %edx` instead of push/pop. Still 3 bytes without any `0` bytes. – Peter Cordes Dec 17 '22 at 20:14

0 Answers0