Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

x86 Assembly: Why Do I Need Stack Frames?

Tags:

x86

assembly

nasm

On most x86 Assembly (NASM especifically) code samples I see around (even on the ones generated by GCC) I see what's called "setup of stack frame". 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:

  1. If my code doesn't touch the stack then setting/removing the stack frame as above is completely useless, right?

  2. Even if my code uses the stack, as long as pop everything I push (leaving the stack as it was essentially) then again setting up a stack frame is completely useless, right?

  3. As I see it the only purpose of this would be to save the value of ESP so that I can play around with it on my code without worrying about messing things up, and once I am done I simply restore its original value. Is this the purpose of the stack frame setup or am I missing something?

Thanks

like image 425
Daniel Scocco Avatar asked Jun 21 '13 16:06

Daniel Scocco


1 Answers

Well, in fact, you don't need stack frames.

Stack frames are convenient when you save registers and store local variables in stack - to make writing and debugging easier: you just set ebp to a fixed point in stack and address all stack data using ebp. And it's easier to restores esp at the end.

Also, debuggers often expect stack frames to be present, otherwise you can get inaccurate stack call for example.

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

like image 124
nullptr Avatar answered Nov 13 '22 03:11

nullptr