I have been learning AT&T assembly for a few months now and I find it really difficult to wrap my head around on some of the recurring instructions in my .s file. In particular,
main:
pushq %rbp
movq %rsp, %rbp
From the book that I'm using, I came to conclude that pushq
pushes the 64-bit address of the calling function to the call stack, or saves it; while movq
copies the value (I suppose its the address) in the %rsp register to the %rbp register. That is, both of them contains the address of the base of the stack.
Also, other sources (thanks Govind) also explained this question pretty well: What is the purpose of the RBP register in x86_64 assembler?
I get it, I already know that pushq %rbp saves caller's frame pointer or saves address of previous stack frame, but if this is the only function I'm calling in my C program, what was the "previous stack frame" then? Like, what was stored in %rbp before my main function call?
For example, if my main function calls a function called foo(), then the asm code in my .S file would be something like this:
foo:
pushq %rbp
movq %rsp, %rbp
#whatever instruction
ret
In this case, I know what was pushed into %rbp (the address of the call instruction in main). Then it makes sense to save it because we will need to return to the main function (w/ ret
). But, why do we have to do it in main if main was the only function in C?