I read that when a function call is made by a program, the called function must know how to return to its caller.
My question is: How does the called function know how to return to its caller? Is there a mechanism working behind the scenes through the compiler?
The compiler obeys a particular "calling convention", defined as part of the ABI you're targeting. That calling convention will include a way for the system to know what address to return to. The calling convention usually takes advantage of the hardware's support for procedure calls. On Intel, for example, the return address is pushed to the stack:
...the processor pushes the value of the
EIP
register (which contains the offset of the instruction following theCALL
instruction) on the stack (for use later as a return-instruction pointer).
Returning from a function is done via the ret
instruction:
... the processor pops the return instruction pointer (offset) from the top of the stack into the
EIP
register and begins program execution at the new instruction pointer.
To contrast, on ARM, the return address is put in the link register:
The
BL
andBLX
instructions copy the address of the next instruction intolr
(r14
, the link register).
Returns are commonly done by executing movs pc, lr
to copy the address from the link register back into the program counter register.
References:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With