1

Im trying to understand how a program makes a function call (using C semantics) with assembly x86 code. Any help would be greatly appreciated.

I could not find any sources to specifically answer this question.

Nancy Raon
  • 23
  • 1
  • 3
  • 4
    By far the easiest way to understand this is to write a C program and compile it using your favorite compiler with the option to have an output listing generated, or - failing that - by running the application under the debugger. – 500 - Internal Server Error Sep 30 '14 at 19:59
  • Any answer that will be useful to you will depend on the ABI you're targeting. What machine/environment/toolchain are you working with? – Carl Norum Sep 30 '14 at 20:05
  • Are you looking for understand some calling convention? – Jack Sep 30 '14 at 20:06
  • Thousands of hits with a Google of "assembly x86 code function call" - the first one is quite nice. – TimSPQR Oct 01 '14 at 00:15

2 Answers2

4

In x86, there are the instructions called call and ret to do this. call store the current address on stack and jmp to a label passed as argument. And the instruction called ret pop this address and jump to it after add one byte to that address.

Code example:

C

int sum(int a, int b)
{
  return a + b;
}

void f(void)
{
  sum(2, 2);
  g();
}

A compiler might generate(x86-assembly-like example):

f:
  push 2
  push 2
  call sum
  call g
  ret

sum:
   pop eax
   pop ebx
   add eax, ebx
   ret

I hope it helps

Jack
  • 16,276
  • 55
  • 159
  • 284
0

I've had good luck with the following resources in the past.

If you're looking for how function calls are translated to assembly, look for the __cdecl calling convention in the links above. Basically, different calling conventions specify different (and not always standardized) ways to pass parameters by manipulating the stack, and __cdecl is just one of the ways - the "C" calling convention.

If you're wondering how to call a C function from assembly code, the last two links are pretty good.

One other word of advice I can give is that if you have an assembly function that you want to call from C, specify the calling convention in the function declaration in C. For example, I once wrote assembly code following the __stdcall calling convention instead of __cdecl, so in the function signature I explicitly specified the __stdcall convention.

Community
  • 1
  • 1