Question

What does this mean?

sub esp, 20h

I especially do not get it when I think about how the stack grows downwards. Does this mean if my stack pointer has a value of 10000h it will move my stack pointer to 10020h ?

ps: if the stack grows downwards, does it mean that the more it grows the larger the addresses?

EDIT: I know that the stack grows downwards, my question is if the ESP is pointing at 10000h and if it is subtracted by 50 does it become 99950h or 10050h?

UPDATE: The osdev wiki Stack article suggested by @vhu was helpful.

Was it helpful?

Solution

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.

OTHER TIPS

esp is just a register (which points usually to the stack). It is not the stack. So sub does here the same as elsewhere. In your example esp becomes 0FFE0h.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top