What’s the point of saving the old base pointer on the stack at the beginning of a function? I’m new to working with functions in assembly, but so far I have yet to see the point of doing this. It just gets pushed onto the stack and then popped off at the end, it doesn’t do anything. For example the following code works just fine without doing this:
.section .data
.section .text
.globl _start
.type add, @function
add:
mov %rsp, %rbp
mov 8(%rbp), %rax
mov 16(%rbp), %rdi
add %rax, %rdi
mov %rbp, %rsp
ret
_start:
push $45
push $36
call add
add $16, %rsp
mov $60, %rax
syscall
I know that you could have simplified this even further by just using the stack pointer in this example, but I can see how that’s bad practice.
Every function using
xBPto locate its parameters or local variables needs to setxBPtoxSPat the very beginning.By doing so, it destroys the previous value of
xBPfrom the calling function and so, naturally, it should save and restore it by e.g. usingpushandpop.If
xBPisn’t used at all, it doesn’t need to be saved and restored.Many compilers have an option to use
xSPto locate function parameters and local variables. If that option is enabled,xBPmay not need to be preserved (unless the calling convention requires its preservation).