Detailed description of function call Methods

Source: Internet
Author: User
Tags microsoft c

In C, suppose we have a function like this:

Int function (int A, int B)

You can use this function by using result = function. However, when a high-level language is compiled into a machine code that can be recognized by a computer, a problem arises: In the CPU, the computer cannot know how many or what parameters are required for a function call, and there is no hardware to save these parameters. That is to say, the computer does not know how to pass parameters to this function. The operation of passing parameters must be coordinated by the function caller and the function itself. Therefore, the computer provides a data structure called Stack to support parameter transmission.

Stack is an advanced post-release data structure with a storage zone and a stack top pointer. The stack top Pointer Points to the first available data item (called the stack top) in the stack ). You can add data to the stack at the top of the stack. This operation is called the push operation. After the stack is pressed, the top of the stack automatically becomes the position of the newly added data item, the stack top pointer is also modified. You can also remove the top stack from the stack, which is called pop. After the stack pops up, an element at the top of the stack changes to the top of the stack, and the top pointer of the stack changes accordingly.

When a function is called, the caller pushes the parameter to the stack in sequence and then calls the function. After the function is called, the caller obtains data in the stack for calculation. After function compute is completed, the caller or the function modifies the stack to restore the original stack.

Two important issues in parameter passing must be clarified:

  • When there are more than one parameter, in what order will the parameter be pushed into the stack?
  • Who will restore the original stack after the function is called?

In advanced languages, the two problems are described through the function call convention. Common call conventions include:

  • Stdcall
  • Cdecl
  • Fastcall
  • Thiscall
  • Naked call
Stdcall call conventions

Stdcall is often referred to as Pascal's call convention, because Pascal is a very common programming language for teaching in the early days, and its syntax is rigorous. The function call Convention used is stdcall. In Microsoft C ++ C/C ++ compilers, Pascal macro is often used to declare this call Convention. Similar macros include winapi and callback.

The syntax of the stdcall call Convention Declaration is (the previous function is used as an example ):

Int __StdcallFunction (int A, int B)

The call Convention of stdcall means: 1) the parameter is pushed from right to left into the stack, 2) the function modifies the stack itself. 3) the function name is automatically followed by a leading underline followed by a @ symbol, followed by the parameter size

The preceding function is used as an example. parameter B is first pushed to the stack, and parameter A is followed. The function call function (1, 2) is translated into an assembly language:

 
 
Push 2 the second parameter to push 1 the first parameter to call the call function of the stack. Note that CS: EIP is automatically put into the stack.

For the function itself, you can translate it:

 
 
Push EBP to save the EBP register, which will be used to save the top pointer of the stack. mov EBP can be restored when the function exits. ESP saves the stack pointer mov eax, [EBP + 8 h] EBP is stored in sequence with EBP, CS: EIP, A, B, EBP + 8 pointing to aadd eax, [EBP + 0ch] bmov ESP is saved at EBP + 12 in the stack, and EBP restores esppop ebpret 8

During compilation, the function name is translated into _ FUNCTION @ 8.

Note that different compilers insert their own compilation code to provide compilation versatility, but the general code is as follows. The ESP is reserved to EBP at the beginning of the function, and the restoration at the end of the function is a common method used by the compiler.

From the perspective of function calls, 2 and 1 are pushed into the stack sequentially, and in the function, they access parameters through the offset relative to EBP (that is, the stack pointer when the function is just introduced. After the function is completed, RET 8 indicates that the 8-byte stack is cleared and the function restores the stack.

Cdecl call conventions

The cdecl call Convention, also known as the C call Convention, is the default call Convention of C language. Its definition syntax is:

 
 
Int function (int A, int B) // The C call Convention int _ cdecl function (int A, int B) // explicitly specifies the C call Convention

When I wrote this article, I was surprised to find that the parameter pressure stack sequence in cdecl call conventions is the same as that in stdcall. The parameter is first pushed to the stack from the left. The difference is that the function itself does not clean up the stack, and the caller is responsible for clearing the stack. Due to this change, the number of parameters allowed by the C call convention is not fixed, which is also a major feature of C language. For the previous function, the assembly code after cdecl is changed:

 
 
Call ProcessPush 1 Push 2 call functionadd ESP, 8 Note: here the caller is at function _ function called to restore the stack.Push EBP to save the EBP register, which will be used to save the top pointer of the stack. mov EBP can be restored when the function exits. ESP saves the stack pointer mov eax, [EBP + 8 h] EBP is stored in sequence with EBP, CS: EIP, A, B, EBP + 8 pointing to aadd eax, [EBP + 0ch] bmov ESP is saved at EBP + 12 in the stack, and EBP restores esppop ebpret Note: The stack is not modified here.

According to msdn, this modifier is automatically prefixed with a leading underline before the function name. Therefore, the function name is recorded as _ function in the symbol table, but this change does not appear to me during compilation.

Because the parameters are pressed from the right to the left, the initial parameter is at the position closest to the top of the stack. Therefore, when an indefinite number of parameters are used, the position of the first parameter in the stack must be known. As long as the number of parameters is determined based on the explicit parameters of the first and later, the parameter can be used, for example, the sprintf function in CRT is defined:

Int sprintf (char * buffer, const char * format ,...)

Since all the indefinite parameters can be determined through format, it is no problem to use the indefinite number of parameters.

Fastcall

The fastcall call Convention is similar to stdcall, which means:

  • The first and second DWORD parameters (or smaller ones) of the function are passed through ECx and EDX, and other parameters are pushed from right to left
  • Call function to clear the stack
  • Function Name modification rules are the same as stdcall

Statement Syntax: int fastcall function (int A, int B)

Thiscall

Thiscall is the only function modifier that cannot be explicitly specified, because thiscall is not a keyword. It is the default call Convention for C ++ class member functions. Because the member function call has a this pointer, special processing is required. thiscall means:

  • Parameter from right to left into Stack
  • If the number of parameters is determined, this pointer is passed to the caller through ECx; if the number of parameters is not determined, this pointer is pushed to the stack after all parameter pressure stacks.
  • If the number of parameters is not fixed, the caller clears the stack. Otherwise, the function clears the stack by itself.

To illustrate this call Convention, define the following classes and use code:

class A{public:      int function1(int a,int b);      int function2(int a,...);};int A::function1 (int a,int b){      return a+b;}#include int A::function2(int a,...){      va_list ap;      va_start(ap,a);      int i;      int result = 0;      for(i = 0 ; i < a ; i ++)      {         result += va_arg(ap,int);      }      return result;}void callee(){      A a;      a.function1 (1,2);      a.function2(3,1,2,3);}

After the callee function is translated into an assembly, it becomes:

 
 
// Function function1 call 0401c1d push 200401c1f push 100401c21 Lea ECx, [ebp-8] 00401c24 call function1 note, this is not being written into the stack // function function2 call 00401c29 push 300401c2b push 200401c2d push 100401c2f push 300401c31 Lea eax, [ebp-8] Here introducing this pointer 00401c34 Push Pull call limit add ESP, 14 h

It can be seen that, when the number of parameters is fixed, it is similar to stdcall. If it is not scheduled, it is similar to cdecl.

Naked call

This is a rare call Convention. Generally, it is recommended that you do not use it. The compiler does not add initialization and cleanup code for such functions. More specifically, you cannot use return to return values. You can only use insert assembly to return results. This is generally used for real-Mode Driver Design. Suppose we define a sum addition program, which can be defined:

__declspec(naked) int  add(int a,int b){   __asm mov eax,a   __asm add eax,b   __asm ret }

Note: This function does not return an explicit return value. The returned result is implemented by modifying the eax register, and the RET commands that exit the function must be explicitly inserted. The code above is translated into an assembly and then changed:

 
 
mov eax,[ebp+8]add eax,[ebp+12]ret 8

Note that this modifier is used in combination with _ stdcall and cdecl. The code used in combination with cdecl is mentioned earlier. For the code combined with stdcall, it becomes:

_ Declspec (naked) int _ stdcall function (int A, int B) {_ ASM mov eax, A _ ASM add eax, B _ ASM RET 8 // note the following 8}

This function is called in the same way as the common cdecl and stdcall call functions.

Common problems caused by function call conventions

If the defined and used conventions are inconsistent, the stack will be damaged, leading to serious problems. The following are two common problems:

  1. The function prototype declaration and function body definition are inconsistent.
  2. Different function conventions are defined during DLL Function Import.

For example, if we declare a function in dll:

_ Declspec (dllexport) int func (int A, int B); // note that stdcall is not found here and cdecl is used.

The time code used is:

Typedef int (* winapi dllfunc) func (int A, int B); hlib = loadlibrary (...); dllfunc func = (dllfunc) getprocaddress (...) // The call Convention result = func () is modified here; // cause an error

This modifier is added because the caller does not understand the meaning of winapi. The code above will inevitably cause the stack to be destroyed. The checkesp function inserted during MFC compilation will tell you that the stack is damaged.

This article from the Network: http://hi.baidu.com/lihao102/blog/item/29ca491ed9011ffd1bd5764f.html reprint please note.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.