(x86) Is the value of ESP relative to EBP, or not?

537 views Asked by At

I always used to think that SP was relative to BP, meaning that pushing and popping stuff on the stack would use the address BP - SP, with BP being the start of the stack, and SP being the current item on the top of the stack. However, after looking at the CDECL calling convention, that would not make sense, as SP is assigned to the value of BP. So, if I change BP, does that even affect SP? Is BP even used for push/pop instructions? Or does push/pop just work with SP? Is BP even needed?

2

There are 2 answers

0
Michael On BEST ANSWER

So, if I change BP, does that even effect SP? Is BP even used for push/pop instructions?

No, and no.

BP/EBP/RBP is often used to hold the address of the current stack frame of a function. That is, an address relative to the function's arguments and local variables that will stay the same throughout the function (whereas the stack pointer might change temporarily).
Instructions like PUSH / POP or CALL / RET will change SP/ESP/RSP but not BP/EBP/RBP.

0
Kerrek SB On

None of the general registers in x86 have "spurious action at a distance", changing one does not touch any of the others. BP is just an ordinary register. It's used by convention to store the base of the current stack frame, but that's it (and that's not even done some most of the time when optimizing, because it is rarely necessary). SP is also an ordinary register, but it is special in the sense that it is modified implicitly by certain instructions, namely push, pop, call, ret, etc., and it must maintain proper stack discipline or function calls (or rather, returns) will break.