Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is my compiler reserving more space than required for a function stack frame?

Tags:

stack

assembly

I have a function:

void func(int a)
{
    int x = a+2;
}

In the assembly code, in function prolog:

push %ebp
mov %esp, %ebp
sub $0x10, %esp

The code only needs to reserve space for x i.e. 4 bytes. But it is reserving 16 bytes. Why is that ? I have always seen it to reserve more space than required.

My guess: it tends to store in 16 bytes. i.e. if I needed say 20 bytes, it will reserve 32 bytes, no matter what.

like image 273
Rash Avatar asked Oct 21 '13 04:10

Rash


1 Answers

This highly depends on your architecture and compiler flags, so it is impossible to point to a single thing and say "this must be it" here. However, I can give you some pointers you may find helpful.

First, consider the stack boundary. You may have heard of the -mpreferred-stack-boundary=X flag to GCC. If not, it basically tells your compiler to prefer your values on the stack to be 2^X bytes each. Your compiler will then try to optimize your program so that these values fit on the stack as best as possible. On the other hand, GCC modifier such as __packed__ will make the compiler try to fit the data in the stack as tightly as possible.

There's also the stack protector. Basically, GCC places dummy values on the stack that make sure buffer overflows can't any harm other than segfaulting your program (which isn't fun, but better than an attacker tacking control of the instruction pointer). You can easily try this out: take any recent version of GCC and let the user overflow a buffer. You'll note that the program exits with a message along the lines of 'stack smashing detected, terminated'. Try compiling your program with -fno-stack-protector, and the allocated local memory on the stack will probably be smaller.

like image 158
Anonymous Avatar answered Nov 16 '22 03:11

Anonymous