LOGBOOK

HELP

← again tap: answer good → ↑ swipe up at the end: next

1 / 9 Part 1 of 2
Other keys: show • Space: good • 1-4: rate • 0: skip • 5: flag

Question

What do push and pop actually do internally?

Answer

push subtracts 8 from %rsp then writes the value there; pop reads from %rsp then adds 8 back.

push decrements rsp by 8 then writes the value; pop reads the value then adds 8 back; the stack grows downward toward lower addresses

* push = rsp minus 8 then store; pop = load then rsp plus 8, because the stack grows toward lower addresses. *

push %rbx

is equivalent to:

sub $8, %rsp
mov %rbx, (%rsp)
pop %rbx

is equivalent to:

mov (%rsp), %rbx
add $8, %rsp

Key detail: The stack grows downward (toward lower addresses). So push subtracts and pop adds.

On x86_64, push/pop always move 8 bytes. On 32-bit x86, they move 4 bytes.

Go deeper:

Call stack layout for upward-growing stacks after the DrawSquare subroutine (shown in blue) called DrawLine (shown in green), which is the currently executing routine
Call stack layout for upward-growing stacks after the DrawSquare subroutine (shown in blue) called DrawLine (shown in green), which is the currently executing routine
R. S. Shaw · Public domain · Wikimedia Commons
or press any other key

Question

What does call and ret actually do internally?

Answer

call pushes the address of the next instruction onto the stack and jumps to the target; ret pops that address and jumps back to it.

call pushes the return address (address of the next instruction) onto the stack and jumps to the target; ret pops that address into %rip and jumps back, restoring %rsp.

* call ≡ push return-addr ; jmp target (%rsp −= 8). ret ≡ pop → %rip ; %rsp += 8. The value at (%rsp) on entry to a callee is its return address. *

call <function>

is equivalent to:

push %rip
jmp  <function>

(Pushes the address of the instruction after call, then jumps)

ret

is equivalent to:

pop %rip

(Pops the return address from the stack into the program counter)

Key consequence: After call, %rsp is 8 bytes lower. The value at (%rsp) inside the called function is the return address.

Note: This is why functions that call other functions must keep the stack 16-byte aligned — call pushes 8 bytes, so the function prologue often does sub $8, %rsp or push %rbx to re-align.

Go deeper:

Call stack layout for upward-growing stacks after the DrawSquare subroutine (shown in blue) called DrawLine (shown in green), which is the currently executing routine
Call stack layout for upward-growing stacks after the DrawSquare subroutine (shown in blue) called DrawLine (shown in green), which is the currently executing routine
R. S. Shaw · Public domain · Wikimedia Commons
or press any other key