there is stack figuration which is
Parameter #N
...
...
Parameter 2
Parameter 1
Return Address
Old %ebp
Local Variable 1
Local Variable 2
I have no idea what `"Old %ebp"` for.
if %ebp
is used for accessing return address and parameters, then why don't %ebp
point just
return address rather than "Old %ebp"
?
is it for future uses?
my question are
- Q1. what is "Old %ebp" for and what is it?
- Q2. why %ebp point Old %ebp not just return address?
The
ebp
register (base pointer) is often used in handling stack frames (different "levels" of the stack). While the stack pointer can change based on what you push and pop, the base pointer stays the same while you're at the same stack level.That way, you can get at all the local variables on one side of
ebp
(e.g.,mov ax,[ebp-8]
) and all the passed parameters on the other side (e.g.,mov ax,[ebp+12]
), along with any other locations that are relative toebp
, such as the return code in some cases.The reason you have the previous contents of the base pointer pushed on the stack is so that it is easy to recover the value when you move up to the previous stack frame. You just pop that value into
ebp
and it's restored, meaning you can access locals and passed parameters for the next level up.This article provides a graphical overview of how it can work, something I usually find invaluable:
The way it works is that you push the parameters for the function, then you simply call that function. The prolog code at the start of the function is something like:
which saves the old
ebp
and sets up a new one, pointing to the variables pushed by the calling code. The subtraction from the stack pointer is to allocate space for locals.As stated, this means passed parameters can be gotten at with
[ebp+N]
and locals with[ebp-N]
.The epilog code is the reverse operation:
after which
ebp
is now set to its previous value.%ebp
is base pointer, all the parameters and local variables are accessed as offset from base pointer. Current ebp will be pointing to stack havingold %ebp
eg
Local Variable 1 is stored at %ebp-4
,parameter 1 is stored at %ebp+8
."Old %ebp"
is base pointer of caller function, when calle returns base pointer old caller to restored.To answer you second question it can do that but this been the convention. Part of the which does this is.
PS: I mostly use nasm syntax so might be