开发者

What do the first lines of a code in assembly mean?

pushl %ebp      
movl %esp, %ebp

This is my understanding:

  1. Moves to the top of the stack. However, I'm not sure what is in %ebp or what gets stored in %ebp register.

  2. If I use the basic understanding of this %esp is Sourche and %ebp is destination. So I'm moving what's in register %esp into register %ebp. Wha开发者_StackOverflow社区t is in register %esp?


By convention, esp is the stack pointer and ebp is the frame pointer. See Intel x86 Function-call Conventions - Assembly View.

So, by this convention, when a call is made, the current frame pointer (ebp, the frame pointer of the caller) is preserved (so that it can be restored when returning to the caller - so from the caller's perspective its frame pointer never changes). Then the current stack pointer (esp) is stored in ebp, making it the frame pointer for the called code.


%esp is the current stackpointer, ie. the top of it. %ebp represents the base pointer of the current function. It is needed so the function knows where its stack begins. You need to save the previous function's %ebp (pushl %ebp) to the stack to be able to assign your own.

Later, when going up the stack again, each function will have its base pointer restored to be able continue working.


    pushl %ebp      
    movl %esp, %ebp
  • save ebp register on the stack
  • move (copy) the content of register esp into the register ebp

The "style" of the piece of code is so that source is the first argument and destination the second; in the intel style you would see something like

    push ebp
    mov  ebp, esp

This is the plain explanation of those lines of code. The meaning depends. Usually it is a common prolog for functions generated by a high level language (e.g. C), respecting some calling convention. The epilog should look like

    movl %ebp, %esp
    popl %ebp
    ret

Room for local variables can be "created" on stack by decrementing esp, and using ebp to access the data, preserving the normal usage of esp e.g. for another call to another function (return address is pushed on stack), and avoiding overwriting of the local variables: the memory between the decremented esp and the base ebp is something like a "reserved area" on stack that the current function can use.

Since each entered function preserve both ebp and esp, recursive function call (until the stack limit is reached) are rather natural in this calling convention mechanism, and nested function can be called ad libitum (until the stack ends!).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜