Functions with call and ret

A function call is a push and a jump; a return is a pop and a jump. Building one by hand shows exactly that.

What you'll learn
  • Describe exactly what call and ret do to esp and eip
  • Write a function prologue and epilogue with ebp
  • Use the stack for a function's local bytes

A function has to know where to come back to. call func solves this in two moves: it pushes the address of the next instruction onto the stack, then jumps to func. 07_function.asm makes the return explicit instead of using ret:

_start:
    call func
    mov eax, 1
    int 0x80

func:
    mov ebx, 42
    pop eax         ; the return address, pushed by call
    jmp eax         ; go back to it

The program exits with 42. pop eax takes the return address off the stack, and jmp eax goes there — which is precisely what ret does, except that ret leaves eax alone. That difference matters in real code, where eax carries the return value.

07_function.asm. call pushes the address of the next instruction (0x08049005) and jumps; pop eax and jmp eax take it back off and return there by hand.

Prologue and epilogue

08_function1.asm writes a proper function, with the two standard bookends:

func:
    push ebp        ; prologue: save the caller's ebp
    mov ebp, esp    ;           anchor this frame
    sub esp, 2      ;           two bytes of local space
    mov [esp], byte 'H'
    mov [esp+1], byte 'i'
    ; ... sys_write(1, esp, 2) prints "Hi"
    mov esp, ebp    ; epilogue: drop the locals
    pop ebp         ;           restore the caller's ebp
    ret

ebp is a fixed point for the whole function: esp moves as things are pushed and popped, but ebp stays put, so arguments and locals are always at the same offset from it. mov esp, ebp frees every local at once, however many there were, and pop ebp hands the caller its base pointer back unchanged.

08_function1.asm. Follow the purple ebp marker and the orange esp marker: the prologue saves ebp and anchors it, sub esp, 2 opens two bytes, and the epilogue puts both back exactly as they were before ret.

One detail: sub esp, 2 leaves esp at an address that is not a multiple of

  1. Nothing here cares, because the function only makes system calls. Code that calls C functions must keep the stack aligned — lesson 7 shows how GCC does it.

Try it yourself. Replace pop eax / jmp eax in 07_function.asm with ret and check the exit status is unchanged. Then, in 08_function1.asm, delete mov esp, ebp from the epilogue. Step through by hand: what does pop ebp load, and where does ret jump to?

View source on GitHub →