Reverse Engineering for Beginners

(avery) #1

CHAPTER 51. C++ CHAPTER 51. C++


ret 8
??0c@@QAE@HH@Z ENDP ; c::c


?dump@c@@QAEXXZ PROC ; c::dump, COMDAT
; _this$ = ecx
mov eax, DWORD PTR [ecx+4]
mov ecx, DWORD PTR [ecx]
push eax
push ecx
push OFFSET ??_C@_07NJBDCIEC@?$CFd?$DL?5?$CFd?6?$AA@
call _printf
add esp, 12
ret 0
?dump@c@@QAEXXZ ENDP ; c::dump


That’s all. The other thing we need to note is that thestack pointerwas not corrected withadd esp, Xafter the constructor
was called. At the same time, the constructor hasret 8instead ofRETat the end.


This is all because the thiscall (51.1.1 on page 522) calling convention is used here, which together with the stdcall (64.2
on page 648) method offers thecalleeto correct the stack instead of thecaller. Theret xinstruction addsXto the value
inESP, then passes the control to thecallerfunction.


See also the section about calling conventions (64 on page 648).


It also has to be noted that the compiler decides when to call the constructor and destructor—but we already know that from
the C++ language basics.


MSVC—x86-64


As we already know, the first 4 function arguments in x86-64 are passed inRCX,RDX,R8andR9registers, all the rest—via
the stack. Nevertheless, thethispointer to the object is passed inRCX, the first argument of the method inRDX,etc. We can
see this in thec(int a, int b)method internals:


Listing 51.5: Optimizing MSVC 2012 x64

; void dump()


?dump@c@@QEAAXXZ PROC ; c::dump
mov r8d, DWORD PTR [rcx+4]
mov edx, DWORD PTR [rcx]
lea rcx, OFFSET FLAT:??_C@_07NJBDCIEC@?$CFd?$DL?5?$CFd?6?$AA@ ; '%d; %d'
jmp printf
?dump@c@@QEAAXXZ ENDP ; c::dump


; c(int a, int b)


??0c@@QEAA@HH@Z PROC ; c::c
mov DWORD PTR [rcx], edx ; 1st argument: a
mov DWORD PTR [rcx+4], r8d ; 2nd argument: b
mov rax, rcx
ret 0
??0c@@QEAA@HH@Z ENDP ; c::c


; default ctor


??0c@@QEAA@XZ PROC ; c::c
mov DWORD PTR [rcx], 667
mov DWORD PTR [rcx+4], 999
mov rax, rcx
ret 0
??0c@@QEAA@XZ ENDP ; c::c


Theintdata type is still 32-bit in x64^2 , so that is why 32-bit register parts are used here.


We also seeJMP printfinstead ofRETin thedump()method, thathackwe already saw earlier:13.1.1 on page 143.


(^2) Apparently, for easier porting of 32-bit C/C++ code to x64

Free download pdf