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?
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.
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.
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.
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.
In general, this is what happens:
call
instruction or through a normal jmp
or br
instruction (jump/branch)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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With