Through a piece of assembly, We can deepen our understanding of register ESP and EBP.

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.