Tuesday, July 10, 2007
Calling conventions for functions.
I have been wanting to write this blog about calling conventions for functions, ever since I have been hit by it. Around one year back, we faced a very peculiar problem wherein calling a certain function caused a GPF [general protection fault]. Painful analysis of the problem (spread over more than a couple of days) revealed that the issue was related to incorrect function calling convention.
I will talk about calling conventions with primary focus on Windows platform and MS VC++ compiler. Function calling convention determines the following:
Now let us take a look at the common calling conventions:
I will talk about calling conventions with primary focus on Windows platform and MS VC++ compiler. Function calling convention determines the following:
- the order in which function arguments are pushed on the stack
- who is responsible for clearing the call stack (i.e. removing arguments) at the end of the call.
- any name-decoration that the compiler uses
Now let us take a look at the common calling conventions:
- cdecl [C calling convention]- Arguments are pushed on the stack from right to left. Thus, the first argument to the function is placed on top of the stack. This allows for passing variable number of arguments on the stack. Stack is cleaned up by the caller. This implies large executables, since each function call includes code to clean the stack. Underscore "_" character is prefixed to the function name.
- stdcall [Standard calling convention] - Typically used to for Win32 API functions. Arguments are pushed on the stack from right to left. The callee is responsible for stack cleanup. An underscore "_" character is prefixed to the function name, followed by "@" which is followed by number of bytes (in decimal) in the argument list.
- fastcall [ Fast calling convention] - Arguments are passed using registers and stack as well. The called functions is responsible to clean the stack. An "@" sign is prefixed to the function name and the "@" sign is followed by the number of bytes (in decimal) in the parameter list.
Labels: programming