C++ to ASM: Behind the scene!

Yeah, a weekend of fully reading about the way in that C++ is compiled to assembly. It's greatz and of course, my girl friend is not really happy without any weekend dating :D

  • ECX register
I've just know about this two day ago :| in one of my previous post (ref from other). This register is usually used as the this pointer.  And it's often assigned a value just before a function is about to be called. I wrote a small application to test it. Its function is just to print the address of my object and call the method. 
  1. class A { public:    void func() { cout << "class A"; } };
  2.  
  3. void main()
  4. {
  5.     A obj;
  6.     cout << &obj << endl;
  7.     obj.func();
  8.     return;
  9. }
And here the output:
0012FF63
class A
I load it into OllyDbg and after carrying out several steps over, I reach to the target:


The value in ECX which is assigned right before the call is the same as the address of obj.

 Of course, everything will be worse if there's the virtual thing. In this case, we must determine the actual address of virtual table.
  • Calling Convention
There're four calling convention supported in C++. They are:


Keyword Stack cleanup Parameter passing
__cdecl Caller Pushes parameters on the stack, in reverse order (right to left)
__stdcall Callee Pushes parameters on the stack, in reverse order (right to left)
__fastcall Callee Stored in registers, then pushed on stack
thiscall
(not a keyword)
Callee Pushed on stack; this pointer stored in ECX

Take a look at this following code:

void    calltype MyFunc( char c, short s, int i, double f );
.
.
.
void    MyFunc( char c, short s, int i, double f )
    {
    .
    .
    .
    }
.
.
.
MyFunc ('x', 12, 8192, 2.7183);

Here the results of calling examples:
    • __cdecl
The C decorated function name is "_MyFunc." 

    • _stdcall and thiscall
The C decorated name (__stdcall) is "_MyFunc@20." The C++ decorated name is proprietary.

    • __fastcall
The C decorated name (__fastcall) is "@MyFunc@20." The C++ decorated name is proprietary.


 Reference: Calling Conventions