What happens in assembly language when you call a method/function?

16,571

Solution 1

In general, this is what happens:

  1. Arguments to the function are stored on the stack. In platform specific order.
  2. Location for return value is "allocated" on the stack
  3. The return address for the function is also stored in the stack or in a special purpose CPU register.
  4. The function (or actually, the address of the function) is called, either through a CPU specific call instruction or through a normal jmp or br instruction (jump/branch)
  5. The function reads the arguments (if any) from the stack and the runs the function code
  6. Return value from function is stored in the specified location (stack or special purpose CPU register)
  7. Execution jumps back to the caller and the stack is cleared (by restoring the stack pointer to its initial value).

The details of the above vary from platform to platform and even from compiler to compiler (see e.g. STDCALL vs CDECL calling conventions). For instance, in some cases, CPU registers are used instead of storing stuff on the stack. The general idea is the same though

Solution 2

What happens in the assembly?

A brief explanation: The current stack state is saved, a new stack is created and the code for the function to be executed is loaded and run. This involves inconveniencing a few registers of your microprocessor, some frantic to and fro read/writes to the memory and once done, the calling function's stack state is restored.

Solution 3

What happens? In x86, the first line of your main function might look something like:

call foo

The call instruction will push the return address on the stack and then jmp to the location of foo.

Solution 4

Arguments are pushed in stack and "call" instruction is made

Call is a simple "jmp" with pushing an address of instruction into stack ("ret" in the end of a method popping it and jumping on it)

Solution 5

I think you want to take a look at call stack to get a better idea what happens during a function call: http://en.wikipedia.org/wiki/Call_stack

Share:
16,571
Gordon Gustafson
Author by

Gordon Gustafson

ML Platform Engineer at Motional. Experience in devops, backend development, and ML.

Updated on June 12, 2022

Comments

  • Gordon Gustafson
    Gordon Gustafson about 2 years

    If I have a program in C++/C that (language doesn't matter much, just needed to illustrate a concept):

    #include <iostream>    
    
    void foo() {
        printf("in foo");
    }
    
    int main() {
        foo();
        return 0;
    }
    

    What happens in the assembly? I'm not actually looking for assembly code as I haven't gotten that far in it yet, but what's the basic principle?