R. Hahnemann
R. Hahnemann

Reputation: 189

What's happening in this simple x86 assembly function call code snippet from Wikibooks?

The Code

The following simple x86 assembly code is listed on Wikibooks for the CDECL calling convention:

Function Definition:

_MyFunction1:
  push ebp
  mov ebp, esp
  mov eax, [ebp + 8]
  mov edx, [ebp + 12]
  add eax, edx
  pop ebp
  ret

Calling Function:

push 3
push 2
call _MyFunction1
add esp, 8

It is what would be generated from the following C code:

_cdecl int MyFunction1(int a, int b)
{
  return a + b;
}

And this function call:

 x = MyFunction1(2, 3);

The issue

Unfortunately, I can't fully wrap my head around what is happening here. Here's a list of the events as I understand them, starting from the calling function:

Upvotes: 0

Views: 187

Answers (1)

prl
prl

Reputation: 12455

  • The instructions with ebp and esp are a standard way of setting up a stack frame. You’re right, there’s no real need to do it, and many compilers don’t. One reason for it is to help a debugger trace the stack frames.
  • It knows to read 4 bytes from [ebp+8] and [ebp+12] because eax and edx are 4-byte registers. That size is encoded in the instructions.
  • x86 addresses are always in bytes. So the 8 and 12 offsets added to ebp are in bytes.
  • when 8 is added to esp, that is just a number, no units. But when esp is used to access memory, it is treated as holding a byte address. So, effectively, the 8 means 8 bytes.
  • The stack grows down. Push decrements the stack pointer. So adding to esp removes things from the stack. The values 2 and 3 are still there in memory, but since they’re below the stack pointer, they’re effectively gone. (And might actually be gone in some rare circumstances, like a debugger evaluating a function call using your stack, or a Windows SEH exception handler, or on non-Windows, a signal handler.)

Upvotes: 3

Related Questions