tags:

views:

208

answers:

3

hi.... i used stack in assembly but i didn't got idea about push ebp and pop ebp.

.intel_syntax noprefix

.include "console.i"

.text

askl:   .asciz  "Enter length: "
askb:   .asciz  "Enter breadth: "
ans:    .asciz  "Perimeter = "

_entry:

    push    ebp     # establishing stack-frame
    mov ebp, esp
    sub esp, 12

    Prompt  askl
    GetInt  [ebp-4]     # length
    Prompt  askb
    GetInt  [ebp-8]     # breadth

    mov eax, [ebp-4]    # eax = l
    add eax, [ebp-8]    # eax = l + b
    add eax, eax    # eax = 2 * (l + b)
    mov [ebp-12], eax

    Prompt  ans
    PutInt  [ebp-12]
    PutEoL

    mov esp, ebp
    pop ebp     # unwinding stack-frame
    ret

.global _entry

.end
+1  A: 

ebp is known as the base pointer or the frame pointer. On entry to your function, you push it (to save the value for the calling function). Then, you copy esp, the stack pointer, into ebp, so that ebp now points to your function's stack frame. At the end of your function, you then pop ebp so that the calling function's value is restored.

For some clarification on exactly what is going on - the push instruction puts the value from the specified register (ebp in this case), onto the stack, and decrements the stack pointer by the appropriate amount. The pop operation is the opposite - it increments the stack pointer and takes a value from the stack and puts it in the specified register.

Carl Norum
+1  A: 

I'm not sure if this is your doubt, but maybe you're wondering about this:

push    ebp
mov ebp, esp
sub esp, 12

The first 2 lines are know as prolog assembly function. It stores the previous base pointer (ebp) and set the base pointer as it was the top of the stack. This means that all the stack contents is saved down the stack, so the function can push/pop in the stack.

The sub esp,12 line is saving space for local variables in the function.

At the end you have:

mov esp, ebp
pop ebp
ret

This is the inverse the prolog does, so the previous context can be restored.

Is this your doubt? :)

jyzuz
A: 

Functions and Stack Frames

Kev