November 29, 2017

Changes of stack when exiting a function

※ You can refer the memory stack structure here(LINK)


1. Initial state
┌─────────────────────┐ → ESP / Low address
│
│Local variables of new function
│
├─────────────────────  → EBP
│SFP
├─────────────────────
│RET
├─────────────────────
│Parameters of new function
├─────────────────────
│
│Local variables
│
├─────────────────────
│SFP
├─────────────────────
│RET
├─────────────────────
│Parameters
└─────────────────────┘→ High address




2. MOV ESP,EBP
┌─────────────────────┐
│
│Local variables of new function
│
├─────────────────────  → ESP / EBP
│SFP
├─────────────────────
│RET
├─────────────────────
│Parameters of new function
├─────────────────────
│
│Local variables
│
├─────────────────────
│SFP
├─────────────────────
│RET
├─────────────────────
│Parameters
└─────────────────────┘




3. POP EBP
┌─────────────────────┐
│
│Local variables of new function
│
├─────────────────────
│SFP
├─────────────────────  → ESP
│RET
├─────────────────────
│Parameters of new function
├─────────────────────
│
│Local variables
│
├─────────────────────  → EBP
│SFP
├─────────────────────
│RET
├─────────────────────
│Parameters
└─────────────────────┘
LEAVE operation is same as (MOV ESP,EBP) + (POP EBP).




4. RET
┌─────────────────────┐
│
│Local variables of new function
│
├─────────────────────
│SFP
├───────────────────── 
│RET
├─────────────────────  → ESP
│Parameters of new function
├─────────────────────
│
│Local variables
│
├─────────────────────  → EBP
│SFP
├─────────────────────
│RET
├─────────────────────
│Parameters
└─────────────────────┘
※ RET includes POP EIP. It stores RET value to EIP.




5. ADD ESP,0x~
┌─────────────────────┐
│
│Local variables of new function
│
├─────────────────────
│SFP
├───────────────────── 
│RET
├─────────────────────
│Parameters of new function
├─────────────────────  → ESP
│
│Local variables
│
├─────────────────────  → EBP
│SFP
├─────────────────────
│RET
├─────────────────────
│Parameters
└─────────────────────┘



And Here is the post that is changes of stack when calling a function(Link).