I am playing around with gcc -S to understand how memory and stack works. During these plays I found several things unclear to me. Could you please help me to understand the reasons?
-
When calling function sets arguments for a called one it uses
movtoespinsteadpush. What is the advantage not usingpush? -
Function which works with its stack located arguments points to them as
ebp + (N + offset)(where N is a size reserved for return address). I expect to seeesp - offsetwhich is more understandable. What is the reason to useebpas fundamental point everywhere? I know these ones are equal but anyway? -
What is this magic for in the beginning of
main? Whyespmust be initialized in this way only?and esp,0xfffffff0
Thanks,
I will assume you are working under a 32-bit environment because in a 64-bit environment arguments are passed in registers.
Question 1
Perhaps you are passing a floating point argument here. You cannot push these directly, as the
pushinstruction in a 32-bit runtime pushes 4 bytes at a time so you would have to break up the value. It is sometimes easier to subtract 8 fromespand them mov the 8-byte quadword into[esp].Question 2
ebpis frequently used to index the parameters and locals in stack frames in 32-bit code. This allows the offsets within frames to be fixed even as the stack pointer moves. For example considerNow if you only accessed the stack frame contents with
esp, thenais at[esp], the return address would be at[esp+4]andxwould be at[esp+8]. Now let’s generate code to callg. We have to first push 5 then pushx. But after pushing 5, the offset ofxfromesphas changed! This is whyebpis used. Normally on entry to functions we push the old value ofebpto save it, then copyesptoebp. Nowebpcan be used to access stack frame contents. It won’t move when we are in the middle of passing arguments.Question 3
This
andinstruction zeros out the last 4 bits ofesp, aligning it to a 16-byte boundary. Since the stack grows downward, this is nice and safe.