0

I have the following function that stores a number on the stack (and modifies that number) and then at the end it cleans things up:

.rodata
number: .long   127     # need to keep original value

_start:

    # set up stack, align on 16 for syscalls
    push %rbp
    mov %rsp, %rbp
    push number

    ...

  exit:
    pop ???
    mov %rbp, %rsp
    pop %rbp
    mov $SYS_EXIT,      %eax
    syscall

What should I be doing with the pop to get rid of the number (i.e., re-align the stack before exiting) ?

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
carl.hiass
  • 1,526
  • 1
  • 6
  • 26
  • 1
    You can call "SYS_EXIT" without cleaning up the stack, which means that you can delete the "pop ???" and the 2 instructions after it and it won't matter. – Brendan Sep 18 '20 at 22:01
  • 1
    `push number` loads 8 bytes from the absolute address `number`, but you only allocated 4 bytes of static data with `.long`. Did you maybe mean `push $number` to push the address as an immediate, instead of loading from it? Because if you did want to load, `push number(%rip)` is the more efficient way to address static storage. – Peter Cordes Sep 18 '20 at 22:02

1 Answers1

4

You can either use add $8, %rsp or simply pop into a register whose value you don't care about, like pop %rcx.

The latter is slightly preferable on recent systems due to the shorter code size and quirks of the "stack engine" (explicit use of RSP can make Intel CPUs insert as stack-sync uop), but the former is not too bad either.

Some compilers (especially clang) do use dummy push/pop by default when they need to move RSP by exactly 8: Why does this function push RAX to the stack as the first operation?


Also note that your pop is redundant with mov %rbp, %rsp since you're using RBP as a frame pointer anyway. And that an _exit system call doesn't care where RSP is pointing.

Peter Cordes
  • 328,167
  • 45
  • 605
  • 847
fuz
  • 88,405
  • 25
  • 200
  • 352