Aug 29, 2012

Posted by | 0 Comments

Calling Convention – Part IV (__thiscall)

Make sure you have read “Calling Convention – Part I”, “Calling Convention – Part II” & “Calling Convention – Part III” of this article.

This calling convention ( __thiscall )

__thiscall is the default calling convention for calling member functions of C++ classes (except for those with a variable number of arguments).

The main characteristics of __thiscall calling convention are:

  1. Arguments are passed from right to left, and placed on the stack. this is placed in ECX.
  2. Stack cleanup is performed by the called function.

C++ Name Decoration/Mangling For thiscall

Please click Here to get detail overview of C++ Name Decoration.

The example for this calling convention had to be a little different. First, the code is compiled as C++, and not C. Second, we have a class/struct with a member function, instead of a global function.

class CSum
      int Add ( int nValue1, int nValue2)
           return nValue1+nValue2;

The assembly code for the function call looks like this:

push 3
push 2
lea ecx,[sumObj]                 ; Object of CSum (this pointer)
call [email protected]@@[email protected]         ; CSum::Add
mov DWORD PTR [nResult],eax

The function itself is given below:

; // function prolog
push ebp
mov ebp, esp
push ebx
push esi
push edi
; // return nValue1 + nValue2;
mov eax, DWORD PTR [nValue1]
add eax, DWORD PTR [nValue2]
; // function epilog
pop ebx
pop esi
pop edi
mov esp, ebp
pop ebp
;//Stack cleanup and return
ret 8

Now, what happens if we have a member function with a variable number of arguments? In that case, __cdecl is used, and this is pushed onto the stack last.


__thiscall calling convention is the default calling convention used by C++ member functions that do not use variable arguments.

Read More