Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 903
Gordon Gustafson Avatar asked Oct 18 '09 15:10

Gordon Gustafson


People also ask

What happens when you call a function in assembly?

Calling a function The call instruction does two things: First it pushes the address of the next instruction, which is the return address, onto the stack. Then, it modifies the instruction pointer %eip to point to the start of the function.

What happens when you call a function?

Series of operations when we call a function:Stack Frame is pushed into stack. Sub-routine instructions are executed. Stack Frame is popped from the stack. Now Program Counter is holding the return address.

What instruction will call execute a function Assembly?

To call an external function, such as NetRun's "print_int", or a standard C library function like "exit", you need to tell the assembler the function is "extern". "extern" isn't actually an instruction--it doesn't show up in the disassembly--it's just a message to the assembler, often called a pseudoinstruction.

How a method function calls is implemented with stack?

When a function call is made, function's arguments are PUSHed on stack. These arguments are further referenced by base pointer. When the function returns to its caller, the arguments of the returning function are POPed from the stack using LIFO method.


1 Answers

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

like image 45
Isak Savo Avatar answered Oct 21 '22 13:10

Isak Savo