Reverse Engineering for Beginners

(avery) #1

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


add esp, 12
ret 0
?dump@sphere@@QAEXXZ ENDP ; sphere::dump


So, here is the memory layout:


(base classobject)


offset description
+0x0 int color

(inherited classes)


box:


offset description
+0x0 int color
+0x4 int width
+0x8 int height
+0xC int depth

sphere:


offset description
+0x0 int color
+0x4 int radius

Let’s seemain()function body:


Listing 51.11: Optimizing MSVC 2008 /Ob0

PUBLIC _main
_TEXT SEGMENT
_s$ = -24 ; size = 8
_b$ = -16 ; size = 16
_main PROC
sub esp, 24
push 30
push 20
push 10
push 1
lea ecx, DWORD PTR _b$[esp+40]
call ??0box@@QAE@HHHH@Z ; box::box
push 40
push 2
lea ecx, DWORD PTR _s$[esp+32]
call ??0sphere@@QAE@HH@Z ; sphere::sphere
lea ecx, DWORD PTR _b$[esp+24]
call ?print_color@object@@QAEXXZ ; object::print_color
lea ecx, DWORD PTR _s$[esp+24]
call ?print_color@object@@QAEXXZ ; object::print_color
lea ecx, DWORD PTR _b$[esp+24]
call ?dump@box@@QAEXXZ ; box::dump
lea ecx, DWORD PTR _s$[esp+24]
call ?dump@sphere@@QAEXXZ ; sphere::dump
xor eax, eax
add esp, 24
ret 0
_main ENDP


The inherited classes must always add their fields after the base classes’ fields, to make it possible for the base class methods
to work with their own fields.


When theobject::print_color()method is called, a pointers to both theboxandsphereobjects are passed asthis,
and it can work with these objects easily since thecolorfield in these objects is always at the pinned address (at offset+0x0).


It can be said that theobject::print_color()method is agnostic in relation to the input object type as long as the
fields arepinnedat the same addresses, and this condition is always true.


And if you create inherited class of theboxclass, the compiler will add the new fields after thedepthfield, leaving thebox
class fields at the pinned addresses.


Thus, thebox::dump()method will work fine for accessing thecolor/width/height/depthsfields, which are always pinned
at known addresses.

Free download pdf