Search code examples
cassemblycallfunction-callsfunction-call

Function Calls and Assembly


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.


Solution

  • 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