How is calling of function implemented in machine code level?
- User
How is calling of function implemented in machine code level?
- Assistant
The implementation of function calling at the machine code level involves several steps and depends on the processor architecture (e.g., x86, ARM) and the calling convention used (e.g., cdecl, stdcall on x86). However, the fundamental process shares common principles across various systems. Here's an overview of how it works in a generalized manner:
1. Preparation
Before calling a function, the caller prepares the environment in accordance with the calling convention, which dictates how arguments are passed, how the call is made, and how control is transferred back to the caller.
2. Passing Arguments
- Registers: Some calling conventions pass the first few arguments through registers. Which registers are used can depend on the type of argument (integer, floating point, etc.).
- Stack: Arguments can also be passed on the stack. The caller places arguments onto the stack in a defined order, often right to left (so the first argument is on top), but this can vary.
3. Call Instruction
- The caller then executes a call instruction, which does a couple of things:
- It pushes the return address (the instruction immediately after the call) onto the stack or stores it in a specific register. The return address indicates where to return control after the function completes.
- It jumps to the start of the function being called by changing the instruction pointer (IP) or program counter (PC) to the address of the callee function.
4. Prologue of the Callee
- Upon entering the function, a function prologue is usually executed. This consists of instructions that prepare the function's stack frame. It typically includes saving the base pointer of the caller (for stack-based architectures), adjusting the stack pointer to make room for local variables, and possibly saving registers that will be used within the function.
5. Execution
- The function performs its intended operations, accessing passed arguments either from registers or from the stack, depending on the calling convention and how they were passed.
6. Function Epilogue
- Before returning, the function epilogue is executed. This reverses the actions of the prologue: it restores saved registers, restores the caller's base pointer, and adjusts the stack pointer back to its original position (before the call was made).
7. Return
- Finally, control is transferred back to the caller. This is often achieved with an instruction like
reton x86, which pops the return address off the stack and jumps to that address, resuming execution right after where the function was called.
8. Cleanup
- After the function has returned, the caller may need to perform cleanup, especially if arguments were passed on the stack. The caller adjusts the stack pointer to remove arguments (for calling conventions where the caller is responsible for cleaning the stack).
This description simplifies some aspects and omits the variety that exists due to different architectures and calling conventions. The precise behavior can vary significantly, especially with modern optimizations and variations like leaf function optimizations, where not all steps are necessary if the function is simple enough.
- User
so %rbp is saved during calling to track the frame boundary of each function. and return address of each function is pushed to stack so that after a function returns, CPU knows where to return.
- Assistant
Yes, that's correct. In the context of x86_64 and other similar architectures,
%rbp(base pointer register) and the return address play critical roles in managing function calls and returns at the machine code level. Here's a bit more detail on each of their roles:%rbp (Base Pointer)
- The
%rbpregister, often referred to as the frame pointer, is used to mark the boundary of each function's frame (or context) on the stack. When a function is called, its prologue often includes instructions to save the previous function's%rbpvalue onto the stack and then set%rbpto the current stack pointer's value (%rsp). This action effectively creates a new stack frame for the called function. - Throughout the function's execution, the
%rbpregister is used as a stable point of reference for accessing function parameters, local variables, and for restoring the stack's state upon exiting the function. - Using
%rbpto establish a frame boundary helps in debugging and generating stack traces since each stack frame links to the previous one through the saved%rbpvalues, making it easier to unwind the stack.
Return Address
- The return address is pushed onto the stack when a function call is made, typically by the
callinstruction in x86_64 and similar instruction sets. Thecallinstruction automatically saves the address of the next instruction (the instruction that follows thecall) onto the stack. This address is where the program counter (%ripin x86_64) should return to after the called function completes its execution. - When the called function has completed its task, it typically executes a
retinstruction as part of its epilogue. Theretinstruction pops the return address off the stack and jumps execution back to that address. This mechanism ensures that, no matter how deep function calls are nested or how complex the call hierarchy is, the CPU always knows where to return after a function completes.
Together, the use of the
%rbpto track frame boundaries and the pushing of return addresses onto the stack are foundational mechanisms that underpin function call semantics in many conventional architectures. They provide a structured way to handle nested function calls, manage variable scoping and lifetimes, and ensure that program execution continues correctly after a function has finished its execution. - The
- User
when a function returns and we don't care about its frame, we can simply use "mov rbp rsp" to move the stack head to frame boundary, effectively throw away current frame, right?
- Assistant
In principle, yes, you could adjust the stack pointer (
%rspin x86_64 architecture) to effectively discard the current function's stack frame if you're done with it and don't need to preserve the function's local environment or return values located on the stack. However, the operation you described:mov rbp, rspThis instruction would move the value of the stack pointer (
rsp) into the base pointer register (rbp), not the other way around. This operation updates the base pointer to point to the current top of the stack, which is not typically how you would discard a frame.If the intention is to discard the current function's frame and reset the stack pointer to its position at the beginning of the function call (effectively "throwing away" the current frame), you would generally do the opposite by setting
rspto the value ofrbp:mov rsp, rbpAfter this, to fully restore the caller's stack frame environment, you would typically also need to:
-
Pop the old
rbpvalue: Restore the previous function's frame pointer.pop rbpThis restores
rbpto its previous value by popping the value that was stored on the stack at the beginning of the function. This step is important for correctly unwinding the stack frame and ensuring that following function calls or returns operate on the correct stack context. -
Return: If you're finishing execution of the current function and returning to the caller, a
retinstruction should be issued:retThe
retinstruction pops the return address off the stack and jumps execution to that address, effectively returning to the caller.
In summary, to "throw away" the current stack frame and return to the caller, you would adjust the stack pointer
rsp(not always as simple as a directmovoperation fromrbpbecause local variables might alterrspduring function execution), restore therbpto its previous value, and then issue aret. The standard procedure for cleaning up the stack frame and returning from a function typically includes these steps, encoded in the function's epilogue.Remember that these operations are sensitive to the calling convention and the specific function prologue/epilogue patterns employed by the compiler or assembly programmer. Direct manipulation of
rspandrbpshould be done with a clear understanding of the current stack layout and calling convention in use. -