Function Calls Part 1
Notes
- This is Jorgensen chapter 12
- He tells us that there are two main issues with functions
- Linkage: ie returning to the correct place after a function is called
- Argument Transmission: passing parameters.
- I would add a third
- Dealing with the local environment
- Saving/restoring temporary registers in the calling function
- saving/restoring preserved registers in the called function
- Local variables (memory) in the called function
- A discussion of variables
- Variables declared in the .data and .bss sections are global
- A recursive function at least will need local copies of these.
- In addition, we probably don't want global variables for everything anyways.
- So local variables are declared on the stack.
- He makes an argument for global as well, but...
- Call and ret
- call
- pushes the current program counter onto the stack
- Jumps the the function beginning.
- ret
- pops the stack into the pc
- This accomplishes the return to an arbitrary point in code.
- Jorgensen notes that it is important to keep the stack right, or do not corrupt the stack
- By the way, this mechanism is the root of the stack overflow security attack.
- Parameters
- rdi, rsi, rdx, rcx, r8, r9
- Then in reverse order on the stack.
- rax is used for return values
- Registers
- rbx, rbp, r12-r15 are all preserved
- IE if you use them in a function, you should
- Save the value before the function you use it
- Restore the value before the function returns.
- all others are temporary
- That means if you are using them and make a function call
- You should save them before you make the call
- You should restore them after the call returns.