Search code examples
assemblyx86callstackbacktracestack-frame

Stack / base pointers in assembly


I know this topic has been covered ad nauseam here, and other places on the internet - but hopefully the question is a simple one as I try to get my head around assembly...

So if i understand correctly the ebp (base pointer) will point to the top of the stack, and the esp (stack pointer) will point to the bottom -- since the stack grows downward. esp therefore points to the 'current location'. So on a function call, once you've saved the ebp on the stack you insert a new stack frame - for the function. So in the case of the image below, if you started from N-3 you would go to N-2 with a function call. But when you are at N-2 - is your ebp == 25 and the esp == 24 (at least initially, before any data is placed on the stack)?

Is this correct or am I off on a tangent here?

Thanks!

http://upload.wikimedia.org/wikipedia/en/a/a7/ProgramCallStack2.png
(source: wikimedia.org)


Solution

  • This actually depends upon not only the hardware architecture and the compiler, but also the calling convention, which is simply an agreed-upon way in which functions work with the stack to call one another. In other words, there are different orders in which a function can push things onto the stack, depending on your compiler settings (and peculiar #pragma options, etc, etc).

    It looks like you are talking about the cdecl calling convention on the x86 architecture. In that case, the caller's ebp is usually pushed onto the stack immediately after the return address. So, in your example's N-2, location 25 will contain a pointer back to the calling function N-3 (ie, it will contain the address of the instruction immediately after the call that got you into N-2) and location 24 will contain the old ebp, and your esp will = 23 immediately after the call, before any locals have been pushed onto stack. (Except some compilers will make space on the stack immediately after the call, and so ESP will be 20 instead of moving up and down inside function N-2.)

    However be aware that on the x86 there is a particular optimization the compiler can sometimes do called frame pointer omission, which avoids pushing the old ebp onto the stack altogether under certain conditions.