Reverse Engineering for Beginners

(avery) #1

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


f(f(std::cout, "Hello, "), "world!");


GCC generates almost the same code as MSVC.


51.3 References.


In C++, references are pointers (10 on page 100) as well, but they are calledsafe, because it is harder to make a mistake
while dealing with them [ISO13, p. 8.3.2]. For example, reference must always be pointing to an object of the corresponding
type and cannot be NULL [Cli, p. 8.6]. Even more than that, references cannot be changed, it is impossible to point them to
another object (reseat) [Cli, p. 8.5].


If we are going to try to change the example with pointers (10 on page 100) to use references instead ...


void f2 (int x, int y, int & sum, int & product)
{
sum=x+y;
product=x*y;
};


...then we can see that the compiled code is just the same as in the pointers example (10 on page 100):


Listing 51.20: Optimizing MSVC 2010

_x$ = 8 ; size = 4
_y$ = 12 ; size = 4
_sum$ = 16 ; size = 4
_product$ = 20 ; size = 4
?f2@@YAXHHAAH0@Z PROC ; f2
mov ecx, DWORD PTR _y$[esp-4]
mov eax, DWORD PTR _x$[esp-4]
lea edx, DWORD PTR [eax+ecx]
imul eax, ecx
mov ecx, DWORD PTR _product$[esp-4]
push esi
mov esi, DWORD PTR _sum$[esp]
mov DWORD PTR [esi], edx
mov DWORD PTR [ecx], eax
pop esi
ret 0
?f2@@YAXHHAAH0@Z ENDP ; f2


( The reason why C++ functions has such strange names is explained here:51.1.1 on page 522.)


Hence, C++ references are as much efficient as usual pointers.


51.4 STL


N.B.: all examples here were checked only in 32-bit environment. x64 wasn’t checked.


51.4.1 std::string.


Internals


Many string libraries [Yur13, p. 2.2] implement a structure that contains a pointer to a string buffer, a variable that always
contains the current string length (which is very convenient for many functions: [Yur13, p. 2.2.1]) and a variable containing
the current buffer size. The string in the buffer is usually terminated with zero, in order to be able to pass a pointer to the
buffer into the functions that take usual CASCIIZstrings.


It is not specified in the C++ standard [ISO13] how std::string has to be implemented, however, it is usually implemented as
explained above.


The C++ string is not a class (as QString in Qt, for instance) but a template (basic_string), this is done in order to support
various character types: at leastcharandwchar_t.


So, std::string is a class withcharas its base type. And std::wstring is a class withwchar_tas its base type.

Free download pdf