PUSH and POP with stack
This is the second tutorial of our stack tutorial set. Hear we are going to talk about some two basic operations we frequently do with the stack. Those are PUSH and POP.
The instruction PUSH means that we are pushing something onto top of the stack. It is clear that, if we push something on to the stack frame the stack should grow more. As you know stack grows into lower memory addresses. So ESP (or RSP) will reduced. Think that we are pushing an integer to the stack. An integer is four bytes long. So ESP will reduce by 4 bytes. Let's understand this situation with image. Hear we have a graphic layout of the stack before we push our integer value.Note that there is a stack frame already on the stack. ESP is pointing to the top of the stack.
Let's use PUSH instruction and put our integer value.
You can see the space allocated for the integer in a yellow box.
Now we want to see the syntax of assembly push instruction. It requires one operand (Or we can call it as a argument). Think that we want to push the value five to the stack. Then we use the command push 0x4.
Also we can push the value of a register . Let's see how we can push the value of ebp. push ebp
Now we are going to see about the POP instruction. What this instruction do is removing what ever found at the top of the stack and place it on another register. So after this process the length of the stack should be reduced. So ESP will go higher. Think that we want to remove the value at the top of stack and place it on ebp. We can just use the command pop ebp.
So guys we can summarize all of above content in to following.
The stack starts from high memory and grows into low memory.
Stack pointer is always pointing to the top of stack ( This can be esp or rsp). If we push something (using PUSH instruction)stack grow more into lower addresses so esp will reduced.
We can pop off the stack and copy what ever found on top of the stack into a register. After that stack length will reduced and esp go higher.
Hear we have an example also.
[push ebp] esp ---> esp-4 : value of ebp pushed onto the stack. [pop ebp] esp ---> esp+4 : remove value of top stack and copy it to ebp.
I hope you learned something from this document. Just leave a comment if anything is unclear. Thanks for reading.