X86 Build: Why Stack Frames?

In most instances of x86 Assembly code (NASM especifically) that I see around (even those generated by GCC), I see what is called "stack frame tuning." Like this:

main: /*setting the stack frame*/ push ebp mov ebp,esp ... code goes here ... /*removing the stack frame*/ mov esp, ebp pop ebp 

I have 3 questions about this practice:

  • If my code doesn’t touch the stack, then installing / removing the stack frame as above is completely useless, right?

  • Even if my code uses the stack, until everything I click pops (leaving the stack, as it was essentially), then again creating a stack frame is completely useless, right?

  • As I see it, the sole purpose of this would be to keep the ESP value so that I can play with it in my code without worrying about ruining everything, and as soon as I finish, I just restore its original value. Is this the purpose of setting the stack frame, or am I missing something?

thanks

+4
source share
3 answers

Well, you really don't need stack frames.

Stack frames are convenient when you save registers and save local variables on the stack β€” to simplify writing and debugging: just set ebp to a fixed point on the stack and specify all the stack data using ebp . And it is easier to restore esp at the end.

In addition, debuggers often expect stack frames to be present, otherwise you might get an inaccurate stack call, for example.

So, the answer to 1 is yes, the answer to 2 and 3 above.

+5
source

You are essentially right.

Stack frames have certain advantages, although even if you don't need a fixed stack link to access options and locals. In particular, their presence allows you to accurately move the stacks to generate stack traces for debugging purposes.

+2
source

This is done by agreement. C functions use stack frames to access parameters that are sent to functions and to configure dynamic local variables. That's why they do it in the sample code you are looking at. Of course, if you want to do it your own way, you can, but you cannot call your code from C, etc.

EDIT: I am also sure that there are compilers that implement various calling conventions that optimize this and possibly don't create a frame at all. So basically, you're right. Stack frames are not needed.

+2
source

Source: https://habr.com/ru/post/1487509/


All Articles