how does push and pop work in assembly

GamefanA picture GamefanA · Sep 24, 2014 · Viewed 40.5k times · Source

I'm getting confused on what does pop actually do in assembly. Does pop move the value PUSHed onto the stack last (meaning it doesn't apply if we MOV a value after the the last element PUSHed) or does it just pop whatever value that's last on the stack (thus, applying to both MOV and PUSH), or does it pop what ever value pointed to by the stack pointer? Consider the following code:

push $4
mov $5, -4(%esp)
add $4, %esp (esp pointing to an unknown value)
pop %ebp

So in this code will the value poped into ebp be 4, 5, or the unknown value pointed to by esp?

Answer

500 - Internal Server Error picture 500 - Internal Server Error · Sep 24, 2014

The latter

POP EBP

is equivalent to

MOV EBP, [ESP]
ADD ESP, 4           ; but without modifying flags, like  LEA ESP, [ESP+4]

(in Intel syntax - target on the left, source on the right)