当前位置:网站首页>Creation and destruction of function stack frame
Creation and destruction of function stack frame
2022-07-03 02:53:00 【Holy cat】
Introduction to this issue
This paper mainly introduces : stay C The whole process of function call in language .
List of articles
- One 、 Preface
- Two 、 Types and functions of registers
- 3、 ... and 、 Common assembly instructions
- Four 、 Function stack frames are created in the whole process of destruction
- 1.main() Function to open up stack frame
- 2. stay main() Create a local variable in the function
- 3. call Add() Preparation before function
- 4. by Add() Function to open up stack frame
- 5.Add() The definition and description part of the function and the execution statement part
- 6.Add() Destruction of function stack frames
- 7.Add() Return after function call
- 5、 ... and 、 summary
One 、 Preface
I think everyone is learning C The process of language will more or less produce the following problems :
1. How local variables are stored in memory ? Can you just choose an unoccupied space ?
2. Why do local variables automatically attach random values when they are not initialized ?
3. How functions pass parameters ? What is the order of transferring parameters ?
4. It is said that a formal parameter is a temporary copy of an argument , Then why do you say that ?
5. What about the whole process of function call ?
Before the formal detailed explanation, let me briefly explain some knowledge points . First of all, we should know , Stack is the extension from high address to low address , That is to say, in the stack area, the high address will be used first, and then the low address . secondly , Every function call will open up a space in the stack , And this space is called the Function stack frame , All kinds of required information are maintained in this stack frame : The parameters of the function 、 local variable 、 The address to jump after the call is over, and so on . Finally, there are two registers , Respectively esp and ebp( among esp It stores the top address of the current stack frame ,ebp It stores the bottom address of the current stack frame ), The stack frame of function is maintained by these two registers . Be careful :esp and ebp What must be maintained is the function stack frame of the function currently being called .
Two 、 Types and functions of registers
register | function |
---|---|
eax | Accumulation register , Relative to other registers , More commonly used in Computing . |
ebx | Base address register , Store base address in memory addressing . |
ecx | Count register , For cyclic operation , Such as repeated character storage operations or numerical statistics . |
edx | As eax Overflow register , It is always used to store the remainder of integer division . |
esi | Source index register , It is mainly used to store the offset of the storage unit in the segment , Usually used in memory operation instructions as “ Source address pointer ” Use |
edi | Destination address register , It is mainly used to store the offset of the storage unit in the segment . |
eip | Control register , Storage CPU The address of the instruction to be executed next time ( Store instruction offset address ). |
esp | Top pointer of stack , The pointer always points to the top of the stack frame . |
ebp | Pointer at the bottom of the stack , The pointer always points to the bottom of the top stack frame . |
3、 ... and 、 Common assembly instructions
push Instructions
: Stack pressing operation . It first reduces esp Value , Then copy the source operand to the stack address , stay 32 A platform ,esp Every time reduce 4 byte .pop Instructions
: The stack, . It first put esp The contents of the stack element pointed to are copied into the operand , add esp Value . stay 32 A platform ,esp Each time 4 byte .mov Instructions
: Used to transfer data from a source address to a destination address , The contents of the source operation address remain unchanged .sub Instructions
: Minus operation instruction , Subtract... From a register <shifter_operand> Represents the value of , And save the result in the target register .lea Instructions
: yes “load effective address” Abbreviation , To put it simply ,lea Instruction can be used to assign a memory address directly to the destination operand .rep Instructions
: Repeat prefix instruction , English abbreviation repeat. Can cause subsequent string instructions to be repeated .stos Instructions
: String store instruction , English abbreviation store string.rep Instructions
Repeat the instructions above ,ecx The value of is the number of repetitions , Every time ,ecx reduce 1, until ecx Be reduced to 0.stos Instructions
take eax Copy the value in to es:[edi] Address to .
dword Two words It's four bytes .
ptrpointer abbreviation I.e. pointer
[ ] The data in is an address value , This address points to a double font data
Copy double words at one time (4 Bytes ) Data to the destination address .
es:[edi] Point to the destination string
explain : Together, it means , Remove the stack from ebp-0E4h Starting position , Assign a value to the memory in the high address direction 0CCCCCCCCh, repeat 39h Time , Each assignment is doubleword ( Four bytes of space ).
call Instructions
: The position of the next instruction in the program IP Push into the stack , And transfer to the calling subroutine .jmp Instructions
: An unconditional jump order .add Instructions
: Used to add two operators , And write the result to the first operator .ret Instructions
: Used to terminate the execution of the current function , Return the operation right to the upper function . That is to say , The frame of the current function will be recycled .
Four 、 Function stack frames are created in the whole process of destruction
First , Let me introduce the code to be demonstrated next :
#include<stdio.h>
int Add(int x, int y)
{
int z = 0;
z = x + y;
return z;
}
int main()
{
int a = 10;
int b = 20;
int c = 0;
c = Add(a, b);
printf("%d\n", c);
}
We know that the code in the function will not be executed until the function needs to be called , Have you ever thought about main() Who called the function ? Want to confirm , Just press F10( Step by step commissioning ) Open the call stack , Until debugging to return 0 The next step . As shown in the figure below ,main()
The function is to be __tmainCRTStartup()
Function called , And if we continue to debug step by step, we will find __tmainCRTStartup()
The function is to be mainCRTStartup()
Function called .
1.main() Function to open up stack frame
First, you want to observe every step of the function when it is called , We need to do it after the implementation of the mode Go to disassembly operation , Thus, it can be executed step by step C Language assembly code . As shown in the figure below :
The space opened up by the function stack frame will be initialized to random values 0cccccccch, This is also why when not initialized , Random values will be placed in local variables .
2. stay main() Create a local variable in the function
From this we can see , Local variables are not stored randomly in the stack , Instead, a space is opened in the function stack frame corresponding to the function it is maintaining . Besides , If the local variable is not initialized, the corresponding assembly code is shown in the following figure . therefore , This explains why without initialization , The value stored in the local variable is a random value 0cccccccch.
3. call Add() Preparation before function
It can be seen that the function will perform a series of stack pressing operations before being officially called , Will Parameters to be transferred and call Instruction the address of the next instruction Pressure into the stack , Prepare for the operation of the next function .
4. by Add() Function to open up stack frame
This step is the same as before main() The function stack frame of the function is basically the same. There is nothing to say .
5.Add() The definition and description part of the function and the execution statement part
It can be seen from this that when a function passes parameters , It will not open up another space for formal parameters , Instead, the effect is achieved by accessing the parameters previously pushed into the stack . And the order of pressing into the stack is from right to left , Like here Add(a,b) First pass b Retransmission a Of , So we can think that the function passes parameters from right to left . It also verifies what I said before : A formal parameter is a temporary copy of an argument , Because the formal parameter is the parameter pushed or passed into the stack before calling the function . So changing the formal parameters doesn't matter at all , The actual parameters will not change with it .
6.Add() Destruction of function stack frames
So this is why in the calling and process , You need to press the bottom address of the previous function stack frame into the stack , In order to make the pointer at the bottom of the stack ebp Point to this position accurately , Thus, the last called function can be maintained immediately after the end of the call .
7.Add() Return after function call
5、 ... and 、 summary
边栏推荐
- Counter统计数量后,如何返回有序的key
- 【翻译】后台项目加入了CNCF孵化器
- ASP. Net core 6 framework unveiling example demonstration [02]: application development based on routing, MVC and grpc
- Three. JS local environment setup
- [fluent] JSON model conversion (JSON serialization tool | JSON manual serialization | writing dart model classes according to JSON | online automatic conversion of dart classes according to JSON)
- [flutter] example of asynchronous programming code between future and futurebuilder (futurebuilder constructor setting | handling flutter Chinese garbled | complete code example)
- I2C subsystem (II): I3C spec
- [principles of multithreading and high concurrency: 1_cpu multi-level cache model]
- I2C 子系统(四):I2C debug
- Process the dataset and use labelencoder to convert all IDs to start from 0
猜你喜欢
Summary of interview project technology stack
函数栈帧的创建与销毁
Linear rectification function relu and its variants in deep learning activation function
Add automatic model generation function to hade
C语言初阶-指针详解-庖丁解牛篇
Super easy to use logzero
Can netstat still play like this?
Deep Reinforcement Learning for Intelligent Transportation Systems: A Survey 论文阅读笔记
Build a private cloud disk cloudrev
从C到Capable-----利用指针作为函数参数求字符串是否为回文字符
随机推荐
Hcip137-147 title + analysis
[shutter] bottom navigation bar page frame (bottomnavigationbar bottom navigation bar | pageview sliding page | bottom navigation and sliding page associated operation)
Notifydatasetchanged not applicable to recyclerview - notifydatasetchanged not working on recyclerview
The base value is too large (the error is marked as "08") [duplicate] - value too great for base (error token is'08') [duplicate]
Choose it when you decide
tensorflow转pytorch笔记;tf.gather_nd(x,y)转pytorch
HTB-Devel
Add automatic model generation function to hade
JMeter performance test JDBC request (query database to obtain database data) use "suggestions collection"
Change cell color in Excel using C - cell color changing in Excel using C
Privatization lightweight continuous integration deployment scheme -- 01 environment configuration (Part 2)
Build a private cloud disk cloudrev
TCP 三次握手和四次挥手机制,TCP为什么要三次握手和四次挥手,TCP 连接建立失败处理机制
Deep Reinforcement Learning for Intelligent Transportation Systems: A Survey 论文阅读笔记
Three. JS local environment setup
SQL statement
Cancer biopsy instruments and kits - market status and future development trends
Update and return document in mongodb - update and return document in mongodb
Counter统计数量后,如何返回有序的key
Serious security vulnerabilities reported by moxa mxview network management software