Why does gcc do this when creating assembler code?

I play with gcc -S to understand how memory and stack work. During these plays I discovered a few strange things to me. Could you help me understand the reasons?

  • When calling arguments to function sets for the callee, mov to esp instead of push . What is the advantage of using push ?

  • A function that works with stack arguments points to them as ebp + (N + offset) (where N is the size reserved for the return address). I expect to see esp - offset , which is more clear. What is the reason for using ebp as a fundamental point everywhere? I know that they are equal, but anyway?

  • What is this magic at the beginning of main ? Why should esp be initialized this way only?

     and esp,0xfffffff0 

Thanks,

+8
assembly gcc
source share
1 answer

I assume that you work in a 32-bit environment, because in a 64-bit environment, arguments are passed to registers.

Question 1

Perhaps you are passing a floating point argument. You cannot directly push them, because the push command in a 32-bit runtime pushes 4 bytes at a time, so you have to break the value. Sometimes it's easier to subtract 8 from esp and they will move the 8-byte quad word into [esp] .

Question 2

ebp often used to index parameters and locales in stack frames in 32-bit code. This allows you to capture offsets within frames, even when the stack pointer moves. For example, consider

 void f(int x) { int a; g(x, 5); } 

Now, if you just accessed the contents of the stack frame using esp , then a is in [esp] , the return address will be in [esp+4] , and x in [esp+8] . Now let me generate the code to call g . First you need to press 5, then press x . But after pressing 5, the offset x from esp has changed! This is why ebp used. Usually, when entering functions, we press the old ebp value to save it, then copy esp to ebp . Now ebp can be used to access the contents of the stack frame. It will not move when we are in the middle of the arguments passed.

Question 3

This and command completes the last 4 bits of esp , aligning it with a 16-byte boundary. As the stack grows down, it is good and safe.

+7
source share

All Articles