Reverse Engineering for Beginners

(avery) #1

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


mov eax, DWORD PTR [esp+20]
mov DWORD PTR [esp+4], ebx
sub eax, 12
mov DWORD PTR [esp], eax
call _ZNSs4_Rep10_M_disposeERKSaIcE
lea esp, [ebp-12]
xor eax, eax
pop ebx
pop esi
pop edi
pop ebp
ret

It can be seen that it’s not a pointer to the object that is passed to destructors, but rather an address 12 bytes (or 3 words)
before, i.e., a pointer to the real start of the structure.


std::string as a global variable


Experienced C++ programmers knows that global variables ofSTL^7 types can be defined without problems.


Yes, indeed:


#include <stdio.h>
#include


std::string s="a string";


int main()
{
printf ("%s\n", s.c_str());
};


But how and wherestd::stringconstructor will be called?


In fact, this variable is to be initialized even beforemain()start.


Listing 51.25: MSVC 2012: here is how a global variable is constructed and also its destructor is registered

??Es@@YAXXZ PROC
push 8
push OFFSET $SG39512 ; 'a string'
mov ecx, OFFSET ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A ; s
call ?assign@?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@QAEAAV12@PBDI@Z ;⤦
Ç std::basic_string<char,std::char_traits,std::allocator >::assign
push OFFSET ??
Fs@@YAXXZ ; `dynamic atexit destructor for 's''
call _atexit
pop ecx
ret 0
??__Es@@YAXXZ ENDP


Listing 51.26: MSVC 2012: here a global variable is used inmain()

$SG39512 DB 'a string', 00H
$SG39519 DB '%s', 0aH, 00H


_main PROC
cmp DWORD PTR ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A+20, 16
mov eax, OFFSET ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A ; s
cmovae eax, DWORD PTR ?s@@3V?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@A
push eax
push OFFSET $SG39519 ; '%s'
call _printf
add esp, 8
xor eax, eax
ret 0
_main ENDP


(^7) (C++) Standard Template Library:51.4 on page 538

Free download pdf