A simple C language code is used as an example to analyze the function call process.
Code:
1 #include <stdio.h> 2 3 int func(int param1 ,int param2,int param3) 4 { 5 int var1 = param1; 6 int var2 = param2; 7 int var3 = param3; 8 9 printf("var1=%d,var2=%d,var3=%d",var1,var2,var3);10 return var1;11 }12 13 int main(int argc, char* argv[])14 {15 int result = func(1,2,3);16 17 return 0; 18 }
First, it is explained that in the stack, the variable distribution is from high address to low address distribution, and EBP is the pointer to the bottom of the stack, which remains unchanged in the process call, also known as the frame pointer. ESP points to the top of the stack, moves during program execution, ESP reduces the allocation space, ESP increases the release space, ESP is also called a stack pointer.
Next, we will analyze the function call process step by step.
1. The main function is executed. The parameters of main are gradually pushed to the stack from right to left, and finally to the return address.
2. Execute row 15th. The three parameters are pushed to the stack from left to right, and from param3 to param1. the distribution in the stack is as follows:
3. then return the address to the stack: the distribution in the stack is as follows:
4. When calling a 3rd-line function, after the jump command enters the function, the function address goes into the stack, the EBP goes into the stack, and then the current ESP value is given to the EBP, corresponding to the Assembly command:
push ebpmov ebp esp
In this case, the top and bottom of the stack point to the same position. The distribution in the stack is as follows:
5. Execute the statement starting from row 3. int var1 = param1; int var2 = param2; int var3 = param3; store the statements in sequence.. Corresponding Compilation:
mov 0x8(%ebp),%eaxmov %eax,-0x4(%ebp)
The content in the [EBP + 0x8] address is assigned to EAX, that is, the param value is assigned to EAX, and then the value in EAX is placed in the address of [EBP-4, that is, the EAX value is assigned to var1, and the c code int var1 = param1 is completed. Other variables are the same.
9th rows, output results, and 10th rows to execute the corresponding assembly code:
mov -0x4(%ebp),%eax
Finally, the returned values of the function are saved through the eax register;
7. after the function is called, the local variables var3, var2, and var1 exit the stack once. EBP restores the original value, returns the address to exit the stack, and finds the original execution address, param1, param2, and param3, the function call is completed. Figure omitted