The concepts of register ESP and EBP are always confused. View and define esp as the stack top pointer, and EBP as the access Stack pointer. Still cannot be fully understood. Later I used a piece of assembly code to have a clear understanding of the two.
The following is the assembly code for calling the test (INT P1, int P2) function according to the call Convention _ stdcall.
Suppose that the pre-function Stack pointer ESP is NN
Push P2; parameter 2 into the stack, ESP-= 4 h, esp = nn-4 h
Push P1; parameter 1 into the stack, ESP-= 4 h, esp = nn-8 h
Call test; push-in return address ESP-= 4 h, esp = nn-0ch
; // Enter the Function
Push EBP to protect the previous EBP pointer, EBP into the stack, ESP-= 4 h, esp = nn-10 h
MoV EBP, esp; Set EBP pointer to stack top NN-10h
MoV eax, dword ptr [EBP + 0ch]; EBP + 0ch for the NN-4h, that is, the location of parameter 2
MoV EBX, dword ptr [EBP + 08 h]; EBP + 08h is the NN-8h, that is, the position of parameter 1
Sub ESP, 8; space occupied by local variables ESP-= 8, esp = NN-18h
Add ESP, 8; release local variables, esp + = 8, esp = NN-10h
Pop EBP; out stack, recovery EBP, esp + = 4, esp = NN-0Ch
RET 8; RET return, pop-up return address, esp + = 4, esp = NN-08h, followed by the operand 8 for the balanced stack, esp + = 8, esp = nn, restores the stack before the function.
After reading the compilation, let's look at the definitions of EBP and ESP,
Previously, esp was the pointer that always points to the top of the stack, while EBP only accesses the top pointer of the stack at a certain time point to facilitate stack operations, such as obtaining function parameters and local variables.