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.
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.
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
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.