The stack structure of the function call process was previously known until Tuesday, when a colleague from the technical salon made a different point of view and was unable to answer it.
The test code is as follows:
intAddintAintb) { inti = A +b; returni;}intFuncintAintb) { returnAdd (3, 5); }intMain () {intA = func (3,5); return 0;}
Linux generates the assembly code as follows:
Add:.LFB0:. Cfi_startproc PUSHL%ebp; save Ebp. Cfi_def_cfa_offset8. Cfi_offset5, -8movl%esp,%EBP; esp points to the bottom of the stack. Cfi_def_cfa_register5Subl $ -,%esp; reserved stack space movl A(%EBP),%eax movl8(%EBP),%edx addl%edx,%eax movl%eax,-4(%EBP) MOVL-4(%EBP),%eaxleave; see Assembly instruction explanation. Cfi_restore5. CFI_DEF_CFA4,4 retSee assembly instruction explanation. Cfi_endproc.LFE0:. SizeAdd, .-Add. globl func. Type func, @functionfunc:.LFB1:. Cfi_startproc PUSHL%ebp; ebp into the stack. Cfi_def_cfa_offset8. Cfi_offset5, -8movl%esp,%EBP; esp points to the bottom of the stack. Cfi_def_cfa_register5Subl $8,%esp MOVL $5,4(%ESP) MOVL $3, (%ESP)Pager Add, return the address into the stack and jump to add Leave. Cfi_restore5. CFI_DEF_CFA4,4 ret. Cfi_endproc.LFE1:. Size func,.-func. GLOBL Main. Type Main, @function
A compilation of several instructions explains:
Call
Push EIP
jmp
Leave
MOV ESP,EBP
Pop EBP
Ret:
Pop EIP
Add esp,4
Pop EIP:
mov EIP, [ESP]
Add esp,4
Stack structure diagram:
————————————
Ebp
Local variable
5; Func Stack Frames
3
return address
————————————
EBP; Save the func ebp
Local variable
————————————
The stack structure of function call