Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why gcc does so when creating assembler code?

Tags:

gcc

assembly

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?

  1. When calling function sets arguments for a called one it uses mov to esp instead push. What is the advantage not using push?

  2. 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 see esp - offset which is more understandable. What is the reason to use ebp as fundamental point everywhere? I know these ones are equal but anyway?

  3. What is this magic for in the beginning of main? Why esp must be initialized in this way only?

    and    esp,0xfffffff0
    

Thanks,

like image 741
zweibaranov Avatar asked Jun 24 '12 06:06

zweibaranov


1 Answers

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 push instruction 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 from esp and them mov the 8-byte quadword into [esp].

Question 2

ebp is 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 consider

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

Now if you only accessed the stack frame contents with esp, then a is at [esp], the return address would be at [esp+4] and x would be at [esp+8]. Now let's generate code to call g. We have to first push 5 then push x. But after pushing 5, the offset of x from esp has changed! This is why ebp is used. Normally on entry to functions we push the old value of ebp to save it, then copy esp to ebp. Now ebp can be used to access stack frame contents. It won't move when we are in the middle of passing arguments.

Question 3

This and instruction zeros out the last 4 bits of esp, aligning it to a 16-byte boundary. Since the stack grows downward, this is nice and safe.

like image 90
Ray Toal Avatar answered Sep 22 '22 11:09

Ray Toal