i want to learn more about stack. Especially, what happens when a function with parameter are called. For this, i write the following code:
#include <stdio.h>
int sum(int d, int e, int f){
int result = d + e + f;
return result;
}
int main(void){
int a = 5;
int b = 4;
int c = 2;
int erg = sum(a,b,c);
printf("Result is: %d", erg);
}
and I get the following Assembly-Code(I will only add the part of the main
function, because first I want to understand this section):
push ebp,
mov ebp, esp
and esp, -16
sub esp, 32
mov DWORD PTR[esp+28], 5
mov DWORD PTR[esp+24], 4
mov DWORD PTR[esp+20], 2
mov eax, DWORD PTR[esp+20]
mov DWORD PTR[esp+8], eax
mov eax, DWORD PTR[esp+24]
mov DWORTD PTR[esp+4], eax
mov eax, DWORD PTR[esp+28]
mov DWORD PTR[esp], eax
call sum
........
........
So, for this part I draw a little sketch to for myself. Please take a look :)
My question : Where is at that point my ebp
? Because of line 2 of my assembler code, it must be at the same place like [esp]
, right ?
Now, the part of sum function which follows to my second question.
so here is the assembly-code of that:
push ebp
mov ebp, esp
sub esp, 16
mov eax, DWORD PTR[ebp+12]
mov edx, DWORD PTR[ebp+8]
mov edx, eax
------------
so, I had learned that we can find our parameters always in [eb+12]
and [ebp+8]
.
(I skipped the third parameter because I want to keep it simple)
So my question is now:
If I assume that esp
=ebp
and I look at my sketch, then I see that there is nothing in [esp+12]
or now [ebp+12]
. But nevertheless, it is used.
How can I imagine that?
Can someone help me? I've read so many papers, but nobody seems to sketch these things. Because of that, it is very hard to understand that.
Thank you!
Here is my sketch:
During the first function execution
esp
andebp
have the same value only immediately after the instructionmov ebp, esp
. After thatand esp, -16
zeroes the lowest 4 bits (the lowest nibble) ofesp
, andesp
andebp
diverge, unless the lowest bits ofesp
were zeroes already. Thensub esp, 32
subtracts 32 fromesp
and hereesp
andebp
diverge for sure.Then regarding your second question:
Don't assume
esp
==ebp
. In this second function tooesp
andebp
diverge upon execution of the instructionsub esp,16
. Learn to use a debugger, for example GDB and single-step through the code and follow the values of registers (especiallyesp
) and memory after each instruction. You can also debug the code in your head as I did above, but if you are a beginner in assembly, using a debugger is usually a lot easier and a lot less error-prone.The following has fairly decent explanation of what is going on with the stack, stack frame, ebp and esp when calling a routine with parameters. I hope it is helpful. What is stack frame in assembly?