
In x86 systems, stack is growing to the bottom (shrinking to the top), while heap is in opposite direction.
But today I will just focus on stack. What is stack?
QUOTE
Stack is just a memory with pointer.
When we add parameters onto stack, the stack pointer decrements. We call it "push" operation.
But when we "pop" it off the stack, the stack pointer increments.
Stack is LIFO, also known as "last in first out"
Let take an example, in 32-bit, each parameter is 4 bytes.
CODE
push val1;esp - 4
push val2;esp - 8
add esp, 8
The above push 2 DWORD parameters onto stack, then adjust the stack pointer to make it balanced.
Actually the above is the same like below:
CODE
push val1;esp - 4
push val2;esp - 8
pop eax;contains val2
pop ebx;contains val1
After adding the "val1" and "val2" paramters onto stack, it is restored back to ebx and eax registers respectively, and the stack pointer is automatically adjusted if you use "push" and "pop", no need to increment or decrement stack pointer manually.
Look now, the last parameter, "val2" is restored back off stack first; meanwhile the first parameter, "val1" is restored back off stack the last, this is because it follows LIFO order, not FIFO (first in first out).
As a bonus, I will show how to do an alternative of "push" operation.
CODE
sub esp, 4
mov dword [esp], val1
mov dword [esp], val1
Now it reserves stack space of 4 bytes first, then store the "val1" parameter onto it.
Sometimes a program may reserves stack space of 32 bytes (multiple of 16) by doing like this:
CODE
sub esp, 32
Then it can do whatever it wants with the allocated stack.
To point to any of the 8 parameters ( 32/ 4 bytes = 8), it can then use ebp (points to the value of esp before allocating 32-byte stack space), or by referencing to esp directly:
CODE
mov eax, dword [esp + 28]
This will copy first parameter pushed to stack (remember stack grows downward) to eax register.
I hope you enjoy this lesson, as what I learned in the past two years.
Disclaimer: Information herein is made accurate at the time of posting, however, corrections are welcomed, this article is written by me for LYN forum and my personal blog.
Unless otherwise stated, all content and picture are my own.
This post has been edited by MatQuasar: Jul 15 2023, 07:01 AM
Jul 11 2023, 08:33 PM, updated 3y ago
Quote




0.0167sec
1.71
5 queries
GZIP Disabled