Stack is Last-In/First-Out construct where 'top' is tracked by ESP. On x86 stack 'grows' top down, meaning that it is initialized to certain value and pointer to 'top' of the stack goes down (lower value) when things are added to stack.
As an example, in the beginning your Stack could be the following:
+----+
FFFF | 00 | <--- ESP
FFFE | 00 |
FFFD | 00 |
FFFC | 00 |
FFFB | 00 |
FFFA | 00 |
+----+
If you use SUB ESP, 2
you will basically reserve space from the stack to be used for local variables:
+----+
FFFF | xx |
FFFE | xx |
FFFD | 00 | <--- ESP
FFFC | 00 |
FFFB | 00 |
FFFA | 00 |
+----+
At this point addresses FFFF and FFFE are available for use as local variables. Of course these need to be removed from the stack when you are done. This can be done either using ADD ESP,2
or as part of the return RET 2
.
As ESP is always relative to 'top' of the stack, you need to keep track of the local variables using some other register, like EBP
.
See here for more information on stack.
Update:
In case example above doesn't highlight it clearly, ADD
and SUB
work on the ESP
register itself, therefore after:
MOV ESP,1000h
SUB ESP,10h
ESP will have value 0FF0h.