x86 Disassembly/Functions and Stack Frame Examples

From Wikibooks, open books for an open world
Jump to: navigation, search

Example: Number of Parameters[edit]

Given the following disassembled function (in MASM syntax), how many 4-byte parameters does this function receive? How many variables are created on the stack? What does this function do?

_Question1:
  push ebp
  mov ebp, esp
  sub esp, 4
  mov eax, [ebp + 8]
  mul 2
  mov [esp + 0], eax
  mov eax, [ebp + 12]
  mov edx, [esp + 0]
  add eax, edx
  mov esp, ebp
  pop ebp
  ret

The function above takes 2 4-byte parameters, accessed by offsets +8 and +12 from ebp. The function also has 1 variable created on the stack, accessed by offset +0 from esp. The function is nearly identical to this C code:

 int Question1(int x, int y)
 {
    int z;
    z = x * 2;
    return y + z;
 }

Example: Standard Entry Sequences[edit]

Does the following function follow the Standard Entry and Exit Sequences? if not, where does it differ?

_Question2:
  call _SubQuestion2
  mul 2
  ret

The function does not follow the standard entry sequence, because it doesn't set up a proper stack frame with ebp and esp. The function basically performs the following C instructions:

 int Question2()
 {
    return SubQuestion2() * 2;
 }

Although an optimizing compiler has chosen to take a few shortcuts.