Reverse Engineering for Beginners

(avery) #1

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


The code generated by GCC is almost the same, with the sole exception of passing thethispointer (as it was explained
above, it is passed as the first argument instead of using theECXregister.


51.1.3 Encapsulation.


Encapsulation is hiding the data in theprivatesections of the class, e.g. to allow access to them only from this class methods.


However, are there any marks in code the about the fact that some field is private and some other—not?


No, there are no such marks.


Let’s try this simple example:


#include <stdio.h>


class box
{
private:
int color, width, height, depth;
public:
box(int color, int width, int height, int depth)
{
this->color=color;
this->width=width;
this->height=height;
this->depth=depth;
};
void dump()
{
printf ("this is box. color=%d, width=%d, height=%d, depth=%d\n", color, width,⤦
Çheight, depth);
};
};


Let’s compile it again in MSVC 2008 with/Oxand/Ob0options and see thebox::dump()method code:


?dump@box@@QAEXXZ PROC ; box::dump, COMDAT
; _this$ = ecx
mov eax, DWORD PTR [ecx+12]
mov edx, DWORD PTR [ecx+8]
push eax
mov eax, DWORD PTR [ecx+4]
mov ecx, DWORD PTR [ecx]
push edx
push eax
push ecx
; 'this is box. color=%d, width=%d, height=%d, depth=%d', 0aH, 00H
push OFFSET ??_C@_0DG@NCNGAADL@this?5is?5box?4?5color?$DN?$CFd?0?5width?$DN?$CFd?0@
call _printf
add esp, 20
ret 0
?dump@box@@QAEXXZ ENDP ; box::dump


Here is a memory layout of the class:


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

All fields are private and not allowed to be accessed from any other function, but knowing this layout, can we create code
that modifies these fields?


To do this we’ll add thehack_oop_encapsulation()function, which is not going to compile if it looked like this:


void hack_oop_encapsulation(class box * o)
{
o->width=1; // that code cant be compiled':
// "error C2248: 'box::width' : cannot access private member declared in class⤦
Ç'box'"

Free download pdf