forked from nillerusr/source-engine
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmemdbg.cpp
1967 lines (1600 loc) · 52.7 KB
/
memdbg.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//========= Copyright Valve Corporation, All rights reserved. ============//
//
// Purpose: Memory allocation!
//
// $NoKeywords: $
//=============================================================================//
#include "pch_tier0.h"
#if !defined(STEAM) && !defined(NO_MALLOC_OVERRIDE)
#ifdef OSX
#include <malloc/malloc.h>
#else
#include <malloc.h>
#endif
#include <string.h>
#include "tier0/dbg.h"
#include "tier0/memalloc.h"
#include "mem_helpers.h"
#ifdef _WIN32
#include <crtdbg.h>
#endif
#ifdef OSX
#include <malloc/malloc.h>
#include <mach/mach.h>
#include <stdlib.h>
#endif
#include <map>
#include <set>
#include <limits.h>
#include "tier0/threadtools.h"
#ifdef _X360
#include "xbox/xbox_console.h"
#endif
#if ( !defined(_DEBUG) && defined(USE_MEM_DEBUG) )
#pragma message ("USE_MEM_DEBUG is enabled in a release build. Don't check this in!")
#endif
#if (defined(_DEBUG) || defined(USE_MEM_DEBUG))
#if defined(_WIN32) && ( !defined(_X360) && !defined(_WIN64) )
// #define USE_STACK_WALK
// or:
// #define USE_STACK_WALK_DETAILED
#endif
//-----------------------------------------------------------------------------
#ifndef _X360
#define DebugAlloc malloc
#define DebugFree free
#else
#define DebugAlloc DmAllocatePool
#define DebugFree DmFreePool
#endif
#ifdef WIN32
int g_DefaultHeapFlags = _CrtSetDbgFlag( _CrtSetDbgFlag(_CRTDBG_REPORT_FLAG) | _CRTDBG_ALLOC_MEM_DF );
#endif
#if defined( _MEMTEST )
static char s_szStatsMapName[32];
static char s_szStatsComment[256];
#endif
//-----------------------------------------------------------------------------
#if defined( USE_STACK_WALK ) || defined( USE_STACK_WALK_DETAILED )
#include <dbghelp.h>
#pragma comment(lib, "Dbghelp.lib" )
#pragma auto_inline(off)
__declspec(naked) DWORD GetEIP()
{
__asm
{
mov eax, [ebp + 4]
ret
}
}
int WalkStack( void **ppAddresses, int nMaxAddresses, int nSkip = 0 )
{
HANDLE hProcess = GetCurrentProcess();
HANDLE hThread = GetCurrentThread();
STACKFRAME64 frame;
memset(&frame, 0, sizeof(frame));
DWORD valEsp, valEbp;
__asm
{
mov [valEsp], esp;
mov [valEbp], ebp
}
frame.AddrPC.Offset = GetEIP();
frame.AddrStack.Offset = valEsp;
frame.AddrFrame.Offset = valEbp;
frame.AddrPC.Mode = AddrModeFlat;
frame.AddrStack.Mode = AddrModeFlat;
frame.AddrFrame.Mode = AddrModeFlat;
// Walk the stack.
int nWalked = 0;
nSkip++;
while ( nMaxAddresses - nWalked > 0 )
{
if ( !StackWalk64(IMAGE_FILE_MACHINE_I386, hProcess, hThread, &frame, NULL, NULL, SymFunctionTableAccess64, SymGetModuleBase64, NULL ) )
{
break;
}
if ( nSkip == 0 )
{
if (frame.AddrFrame.Offset == 0)
{
// End of stack.
break;
}
*ppAddresses++ = (void *)frame.AddrPC.Offset;
nWalked++;
if (frame.AddrPC.Offset == frame.AddrReturn.Offset)
{
// Catching a stack loop
break;
}
}
else
{
nSkip--;
}
}
if ( nMaxAddresses )
{
memset( ppAddresses, 0, ( nMaxAddresses - nWalked ) * sizeof(*ppAddresses) );
}
return nWalked;
}
bool GetModuleFromAddress( void *address, char *pResult )
{
IMAGEHLP_MODULE moduleInfo;
moduleInfo.SizeOfStruct = sizeof(moduleInfo);
if ( SymGetModuleInfo( GetCurrentProcess(), (DWORD)address, &moduleInfo ) )
{
strcpy( pResult, moduleInfo.ModuleName );
return true;
}
return false;
}
bool GetCallerModule( char *pDest )
{
static bool bInit;
if ( !bInit )
{
PSTR psUserSearchPath = NULL;
psUserSearchPath = "u:\\data\\game\\bin\\;u:\\data\\game\\episodic\\bin\\;u:\\data\\game\\hl2\\bin\\;\\\\perforce\\symbols";
SymInitialize( GetCurrentProcess(), psUserSearchPath, true );
bInit = true;
}
void *pCaller;
WalkStack( &pCaller, 1, 2 );
return ( pCaller != 0 && GetModuleFromAddress( pCaller, pDest ) );
}
#if defined( USE_STACK_WALK_DETAILED )
//
// Note: StackDescribe function is non-reentrant:
// Reason: Stack description is stored in a static buffer.
// Solution: Passing caller-allocated buffers would allow the
// function to become reentrant, however the current only client (FindOrCreateFilename)
// is synchronized with a heap mutex, after retrieving stack description the
// heap memory will be allocated to copy the text.
//
char * StackDescribe( void **ppAddresses, int nMaxAddresses )
{
static char s_chStackDescription[ 32 * 1024 ];
static char s_chSymbolBuffer[ sizeof( IMAGEHLP_SYMBOL64 ) + 1024 ];
IMAGEHLP_SYMBOL64 &hlpSymbol = * ( IMAGEHLP_SYMBOL64 * ) s_chSymbolBuffer;
hlpSymbol.SizeOfStruct = sizeof( IMAGEHLP_SYMBOL64 );
hlpSymbol.MaxNameLength = 1024;
DWORD64 hlpSymbolOffset = 0;
IMAGEHLP_LINE64 hlpLine;
hlpLine.SizeOfStruct = sizeof( IMAGEHLP_LINE64 );
DWORD hlpLineOffset = 0;
s_chStackDescription[ 0 ] = 0;
char *pchBuffer = s_chStackDescription;
for ( int k = 0; k < nMaxAddresses; ++ k )
{
if ( !ppAddresses[k] )
break;
pchBuffer += strlen( pchBuffer );
if ( SymGetLineFromAddr64( GetCurrentProcess(), ( DWORD64 ) ppAddresses[k], &hlpLineOffset, &hlpLine ) )
{
char const *pchFileName = hlpLine.FileName ? hlpLine.FileName + strlen( hlpLine.FileName ) : NULL;
for ( size_t numSlashesAllowed = 2; pchFileName > hlpLine.FileName; -- pchFileName )
{
if ( *pchFileName == '\\' )
{
if ( numSlashesAllowed -- )
continue;
else
break;
}
}
sprintf( pchBuffer, hlpLineOffset ? "%s:%d+0x%I32X" : "%s:%d", pchFileName, hlpLine.LineNumber, hlpLineOffset );
}
else if ( SymGetSymFromAddr64( GetCurrentProcess(), ( DWORD64 ) ppAddresses[k], &hlpSymbolOffset, &hlpSymbol ) )
{
sprintf( pchBuffer, ( hlpSymbolOffset > 0 && !( hlpSymbolOffset >> 63 ) ) ? "%s+0x%I64X" : "%s", hlpSymbol.Name, hlpSymbolOffset );
}
else
{
sprintf( pchBuffer, "#0x%08p", ppAddresses[k] );
}
pchBuffer += strlen( pchBuffer );
sprintf( pchBuffer, "<--" );
}
*pchBuffer = 0;
return s_chStackDescription;
}
#endif // #if defined( USE_STACK_WALK_DETAILED )
#else
inline int WalkStack( void **ppAddresses, int nMaxAddresses, int nSkip = 0 )
{
memset( ppAddresses, 0, nMaxAddresses * sizeof(*ppAddresses) );
return 0;
}
#define GetModuleFromAddress( address, pResult ) ( ( *pResult = 0 ), 0)
#define GetCallerModule( pDest ) false
#endif
//-----------------------------------------------------------------------------
// NOTE: This exactly mirrors the dbg header in the MSDEV crt
// eventually when we write our own allocator, we can kill this
struct CrtDbgMemHeader_t
{
unsigned char m_Reserved[8];
const char *m_pFileName;
int m_nLineNumber;
unsigned char m_Reserved2[16];
};
struct DbgMemHeader_t
#if !defined( _DEBUG ) || defined( POSIX )
: CrtDbgMemHeader_t
#endif
{
size_t nLogicalSize;
byte reserved[12]; // MS allocator always returns mem aligned on 16 bytes, which some of our code depends on
};
//-----------------------------------------------------------------------------
#if defined( _DEBUG ) && !defined( POSIX )
#define GetCrtDbgMemHeader( pMem ) ((CrtDbgMemHeader_t*)((DbgMemHeader_t*)pMem - 1) - 1)
#elif defined( OSX )
DbgMemHeader_t *GetCrtDbgMemHeader( void *pMem );
#else
#define GetCrtDbgMemHeader( pMem ) ((DbgMemHeader_t*)pMem - 1)
#endif
#ifdef OSX
DbgMemHeader_t *GetCrtDbgMemHeader( void *pMem )
{
size_t msize = malloc_size( pMem );
return (DbgMemHeader_t *)( (char *)pMem + msize - sizeof(DbgMemHeader_t) );
}
#endif
inline void *InternalMalloc( size_t nSize, const char *pFileName, int nLine )
{
#ifdef OSX
void *pAllocedMem = malloc_zone_malloc( malloc_default_zone(), nSize + sizeof(DbgMemHeader_t) );
if (!pAllocedMem)
{
return NULL;
}
DbgMemHeader_t *pInternalMem = GetCrtDbgMemHeader( pAllocedMem );
pInternalMem->m_pFileName = pFileName;
pInternalMem->m_nLineNumber = nLine;
pInternalMem->nLogicalSize = nSize;
*((int*)pInternalMem->m_Reserved) = 0xf00df00d;
return pAllocedMem;
#else // LINUX || WIN32
DbgMemHeader_t *pInternalMem;
#if defined( POSIX ) || !defined( _DEBUG )
pInternalMem = (DbgMemHeader_t *)malloc( nSize + sizeof(DbgMemHeader_t) );
if (!pInternalMem)
{
return NULL;
}
pInternalMem->m_pFileName = pFileName;
pInternalMem->m_nLineNumber = nLine;
*((int*)pInternalMem->m_Reserved) = 0xf00df00d;
#else
pInternalMem = (DbgMemHeader_t *)_malloc_dbg( nSize + sizeof(DbgMemHeader_t), _NORMAL_BLOCK, pFileName, nLine );
#endif // defined( POSIX ) || !defined( _DEBUG )
pInternalMem->nLogicalSize = nSize;
return pInternalMem + 1;
#endif // LINUX || WIN32
}
inline void *InternalRealloc( void *pMem, size_t nNewSize, const char *pFileName, int nLine )
{
if ( !pMem )
return InternalMalloc( nNewSize, pFileName, nLine );
#ifdef OSX
void *pNewAllocedMem = NULL;
pNewAllocedMem = (void *)malloc_zone_realloc( malloc_default_zone(), pMem, nNewSize + sizeof(DbgMemHeader_t) );
DbgMemHeader_t *pInternalMem = GetCrtDbgMemHeader( pNewAllocedMem );
pInternalMem->m_pFileName = pFileName;
pInternalMem->m_nLineNumber = nLine;
pInternalMem->nLogicalSize = static_cast<unsigned int>( nNewSize );
*((int*)pInternalMem->m_Reserved) = 0xf00df00d;
return pNewAllocedMem;
#else // LINUX || WIN32
DbgMemHeader_t *pInternalMem = (DbgMemHeader_t *)pMem - 1;
#if defined( POSIX ) || !defined( _DEBUG )
pInternalMem = (DbgMemHeader_t *)realloc( pInternalMem, nNewSize + sizeof(DbgMemHeader_t) );
pInternalMem->m_pFileName = pFileName;
pInternalMem->m_nLineNumber = nLine;
#else
pInternalMem = (DbgMemHeader_t *)_realloc_dbg( pInternalMem, nNewSize + sizeof(DbgMemHeader_t), _NORMAL_BLOCK, pFileName, nLine );
#endif
pInternalMem->nLogicalSize = nNewSize;
return pInternalMem + 1;
#endif // LINUX || WIN32
}
inline void InternalFree( void *pMem )
{
if ( !pMem )
return;
DbgMemHeader_t *pInternalMem = (DbgMemHeader_t *)pMem - 1;
#if !defined( _DEBUG ) || defined( POSIX )
#ifdef OSX
malloc_zone_free( malloc_default_zone(), pMem );
#elif LINUX
free( pInternalMem );
#else
free( pInternalMem );
#endif
#else
_free_dbg( pInternalMem, _NORMAL_BLOCK );
#endif
}
inline size_t InternalMSize( void *pMem )
{
//$ TODO. For Linux, we could use 'int size = malloc_usable_size( pMem )'...
#if defined(POSIX)
DbgMemHeader_t *pInternalMem = GetCrtDbgMemHeader( pMem );
return pInternalMem->nLogicalSize;
#elif !defined(_DEBUG)
DbgMemHeader_t *pInternalMem = GetCrtDbgMemHeader( pMem );
return _msize( pInternalMem ) - sizeof(DbgMemHeader_t);
#else
DbgMemHeader_t *pInternalMem = (DbgMemHeader_t *)pMem - 1;
return _msize_dbg( pInternalMem, _NORMAL_BLOCK ) - sizeof(DbgMemHeader_t);
#endif
}
inline size_t InternalLogicalSize( void *pMem )
{
#if defined(POSIX)
DbgMemHeader_t *pInternalMem = GetCrtDbgMemHeader( pMem );
#elif !defined(_DEBUG)
DbgMemHeader_t *pInternalMem = (DbgMemHeader_t *)pMem - 1;
#else
DbgMemHeader_t *pInternalMem = (DbgMemHeader_t *)pMem - 1;
#endif
return pInternalMem->nLogicalSize;
}
#ifndef _DEBUG
#define _CrtDbgReport( nRptType, szFile, nLine, szModule, pMsg ) 0
#endif
//-----------------------------------------------------------------------------
// Custom allocator protects this module from recursing on operator new
template <class T>
class CNoRecurseAllocator
{
public:
// type definitions
typedef T value_type;
typedef T* pointer;
typedef const T* const_pointer;
typedef T& reference;
typedef const T& const_reference;
typedef std::size_t size_type;
typedef std::ptrdiff_t difference_type;
CNoRecurseAllocator() {}
CNoRecurseAllocator(const CNoRecurseAllocator&) {}
template <class U> CNoRecurseAllocator(const CNoRecurseAllocator<U>&) {}
~CNoRecurseAllocator(){}
// rebind allocator to type U
template <class U > struct rebind { typedef CNoRecurseAllocator<U> other; };
// return address of values
pointer address (reference value) const { return &value; }
const_pointer address (const_reference value) const { return &value;}
size_type max_size() const { return INT_MAX; }
pointer allocate(size_type num, const void* = 0) { return (pointer)DebugAlloc(num * sizeof(T)); }
void deallocate (pointer p, size_type num) { DebugFree(p); }
void construct(pointer p, const T& value) { new((void*)p)T(value); }
void destroy (pointer p) { p->~T(); }
};
template <class T1, class T2>
bool operator==(const CNoRecurseAllocator<T1>&, const CNoRecurseAllocator<T2>&)
{
return true;
}
template <class T1, class T2>
bool operator!=(const CNoRecurseAllocator<T1>&, const CNoRecurseAllocator<T2>&)
{
return false;
}
class CStringLess
{
public:
bool operator()(const char *pszLeft, const char *pszRight ) const
{
return ( stricmp( pszLeft, pszRight ) < 0 );
}
};
//-----------------------------------------------------------------------------
#pragma warning( disable:4074 ) // warning C4074: initializers put in compiler reserved initialization area
#pragma init_seg( compiler )
//-----------------------------------------------------------------------------
// NOTE! This should never be called directly from leaf code
// Just use new,delete,malloc,free etc. They will call into this eventually
//-----------------------------------------------------------------------------
class CDbgMemAlloc : public IMemAlloc
{
public:
CDbgMemAlloc();
virtual ~CDbgMemAlloc();
// Release versions
virtual void *Alloc( size_t nSize );
virtual void *Realloc( void *pMem, size_t nSize );
virtual void Free( void *pMem );
virtual void *Expand_NoLongerSupported( void *pMem, size_t nSize );
// Debug versions
virtual void *Alloc( size_t nSize, const char *pFileName, int nLine );
virtual void *Realloc( void *pMem, size_t nSize, const char *pFileName, int nLine );
virtual void Free( void *pMem, const char *pFileName, int nLine );
virtual void *Expand_NoLongerSupported( void *pMem, size_t nSize, const char *pFileName, int nLine );
// Returns size of a particular allocation
virtual size_t GetSize( void *pMem );
// Force file + line information for an allocation
virtual void PushAllocDbgInfo( const char *pFileName, int nLine );
virtual void PopAllocDbgInfo();
virtual long CrtSetBreakAlloc( long lNewBreakAlloc );
virtual int CrtSetReportMode( int nReportType, int nReportMode );
virtual int CrtIsValidHeapPointer( const void *pMem );
virtual int CrtIsValidPointer( const void *pMem, unsigned int size, int access );
virtual int CrtCheckMemory( void );
virtual int CrtSetDbgFlag( int nNewFlag );
virtual void CrtMemCheckpoint( _CrtMemState *pState );
// handles storing allocation info for coroutines
virtual uint32 GetDebugInfoSize();
virtual void SaveDebugInfo( void *pvDebugInfo );
virtual void RestoreDebugInfo( const void *pvDebugInfo );
virtual void InitDebugInfo( void *pvDebugInfo, const char *pchRootFileName, int nLine );
// FIXME: Remove when we have our own allocator
virtual void* CrtSetReportFile( int nRptType, void* hFile );
virtual void* CrtSetReportHook( void* pfnNewHook );
virtual int CrtDbgReport( int nRptType, const char * szFile,
int nLine, const char * szModule, const char * szFormat );
virtual int heapchk();
virtual bool IsDebugHeap() { return true; }
virtual int GetVersion() { return MEMALLOC_VERSION; }
virtual void CompactHeap()
{
#if defined( _X360 ) && defined( _DEBUG )
HeapCompact( GetProcessHeap(), 0 );
#endif
}
virtual MemAllocFailHandler_t SetAllocFailHandler( MemAllocFailHandler_t pfnMemAllocFailHandler ) { return NULL; } // debug heap doesn't attempt retries
#if defined( _MEMTEST )
void SetStatsExtraInfo( const char *pMapName, const char *pComment )
{
strncpy( s_szStatsMapName, pMapName, sizeof( s_szStatsMapName ) );
s_szStatsMapName[sizeof( s_szStatsMapName ) - 1] = '\0';
strncpy( s_szStatsComment, pComment, sizeof( s_szStatsComment ) );
s_szStatsComment[sizeof( s_szStatsComment ) - 1] = '\0';
}
#endif
virtual size_t MemoryAllocFailed();
void SetCRTAllocFailed( size_t nMemSize );
enum
{
BYTE_COUNT_16 = 0,
BYTE_COUNT_32,
BYTE_COUNT_128,
BYTE_COUNT_1024,
BYTE_COUNT_GREATER,
NUM_BYTE_COUNT_BUCKETS
};
void Shutdown();
private:
struct MemInfo_t
{
MemInfo_t()
{
memset( this, 0, sizeof(*this) );
}
// Size in bytes
size_t m_nCurrentSize;
size_t m_nPeakSize;
size_t m_nTotalSize;
size_t m_nOverheadSize;
size_t m_nPeakOverheadSize;
// Count in terms of # of allocations
size_t m_nCurrentCount;
size_t m_nPeakCount;
size_t m_nTotalCount;
// Count in terms of # of allocations of a particular size
size_t m_pCount[NUM_BYTE_COUNT_BUCKETS];
// Time spent allocating + deallocating (microseconds)
int64 m_nTime;
};
struct MemInfoKey_t
{
MemInfoKey_t( const char *pFileName, int line ) : m_pFileName(pFileName), m_nLine(line) {}
bool operator<( const MemInfoKey_t &key ) const
{
int iret = stricmp( m_pFileName, key.m_pFileName );
if ( iret < 0 )
return true;
if ( iret > 0 )
return false;
return m_nLine < key.m_nLine;
}
const char *m_pFileName;
int m_nLine;
};
// NOTE: Deliberately using STL here because the UTL stuff
// is a client of this library; want to avoid circular dependency
// Maps file name to info
typedef std::map< MemInfoKey_t, MemInfo_t, std::less<MemInfoKey_t>, CNoRecurseAllocator<std::pair<const MemInfoKey_t, MemInfo_t> > > StatMap_t;
typedef StatMap_t::iterator StatMapIter_t;
typedef StatMap_t::value_type StatMapEntry_t;
typedef std::set<const char *, CStringLess, CNoRecurseAllocator<const char *> > Filenames_t;
// Heap reporting method
typedef void (*HeapReportFunc_t)( char const *pFormat, ... );
private:
// Returns the actual debug info
void GetActualDbgInfo( const char *&pFileName, int &nLine );
void Initialize();
// Finds the file in our map
MemInfo_t &FindOrCreateEntry( const char *pFileName, int line );
const char *FindOrCreateFilename( const char *pFileName );
// Updates stats
void RegisterAllocation( const char *pFileName, int nLine, size_t nLogicalSize, size_t nActualSize, unsigned nTime );
void RegisterDeallocation( const char *pFileName, int nLine, size_t nLogicalSize, size_t nActualSize, unsigned nTime );
void RegisterAllocation( MemInfo_t &info, size_t nLogicalSize, size_t nActualSize, unsigned nTime );
void RegisterDeallocation( MemInfo_t &info, size_t nLogicalSize, size_t nActualSize, unsigned nTime );
// Gets the allocation file name
const char *GetAllocatonFileName( void *pMem );
int GetAllocatonLineNumber( void *pMem );
// FIXME: specify a spew output func for dumping stats
// Stat output
void DumpMemInfo( const char *pAllocationName, int line, const MemInfo_t &info );
void DumpFileStats();
void DumpStats();
void DumpStatsFileBase( char const *pchFileBase );
void DumpBlockStats( void *p );
virtual void GlobalMemoryStatus( size_t *pUsedMemory, size_t *pFreeMemory );
private:
StatMap_t *m_pStatMap;
MemInfo_t m_GlobalInfo;
CFastTimer m_Timer;
bool m_bInitialized;
Filenames_t *m_pFilenames;
HeapReportFunc_t m_OutputFunc;
static int s_pCountSizes[NUM_BYTE_COUNT_BUCKETS];
static const char *s_pCountHeader[NUM_BYTE_COUNT_BUCKETS];
size_t m_sMemoryAllocFailed;
};
static char const *g_pszUnknown = "unknown";
//-----------------------------------------------------------------------------
const int DBG_INFO_STACK_DEPTH = 32;
struct DbgInfoStack_t
{
const char *m_pFileName;
int m_nLine;
};
CThreadLocalPtr<DbgInfoStack_t> g_DbgInfoStack CONSTRUCT_EARLY;
CThreadLocalInt<> g_nDbgInfoStackDepth CONSTRUCT_EARLY;
//-----------------------------------------------------------------------------
// Singleton...
//-----------------------------------------------------------------------------
static CDbgMemAlloc s_DbgMemAlloc CONSTRUCT_EARLY;
#ifndef TIER0_VALIDATE_HEAP
IMemAlloc *g_pMemAlloc = &s_DbgMemAlloc;
#else
IMemAlloc *g_pActualAlloc = &s_DbgMemAlloc;
#endif
//-----------------------------------------------------------------------------
CThreadMutex g_DbgMemMutex CONSTRUCT_EARLY;
#define HEAP_LOCK() AUTO_LOCK( g_DbgMemMutex )
//-----------------------------------------------------------------------------
// Byte count buckets
//-----------------------------------------------------------------------------
int CDbgMemAlloc::s_pCountSizes[CDbgMemAlloc::NUM_BYTE_COUNT_BUCKETS] =
{
16, 32, 128, 1024, INT_MAX
};
const char *CDbgMemAlloc::s_pCountHeader[CDbgMemAlloc::NUM_BYTE_COUNT_BUCKETS] =
{
"<=16 byte allocations",
"17-32 byte allocations",
"33-128 byte allocations",
"129-1024 byte allocations",
">1024 byte allocations"
};
//-----------------------------------------------------------------------------
// Standard output
//-----------------------------------------------------------------------------
static FILE* s_DbgFile;
static void DefaultHeapReportFunc( char const *pFormat, ... )
{
va_list args;
va_start( args, pFormat );
vfprintf( s_DbgFile, pFormat, args );
va_end( args );
}
//-----------------------------------------------------------------------------
// Constructor
//-----------------------------------------------------------------------------
CDbgMemAlloc::CDbgMemAlloc() : m_sMemoryAllocFailed( (size_t)0 )
{
// Make sure that we return 64-bit addresses in 64-bit builds.
ReserveBottomMemory();
m_OutputFunc = DefaultHeapReportFunc;
m_bInitialized = false;
if ( !IsDebug() && !IsX360() )
{
Plat_DebugString( "USE_MEM_DEBUG is enabled in a release build. Don't check this in!\n" );
}
}
CDbgMemAlloc::~CDbgMemAlloc()
{
Shutdown();
}
void CDbgMemAlloc::Initialize()
{
if ( !m_bInitialized )
{
m_pFilenames = new Filenames_t;
m_pStatMap= new StatMap_t;
m_bInitialized = true;
}
}
//-----------------------------------------------------------------------------
// Release versions
//-----------------------------------------------------------------------------
void CDbgMemAlloc::Shutdown()
{
if ( m_bInitialized )
{
Filenames_t::const_iterator iter = m_pFilenames->begin();
while ( iter != m_pFilenames->end() )
{
char *pFileName = (char*)(*iter);
free( pFileName );
iter++;
}
m_pFilenames->clear();
m_bInitialized = false;
delete m_pFilenames;
m_pFilenames = nullptr;
delete m_pStatMap;
m_pStatMap = nullptr;
}
m_bInitialized = false;
}
#ifdef WIN32
extern "C" BOOL APIENTRY MemDbgDllMain( HMODULE hDll, DWORD dwReason, PVOID pvReserved )
{
UNREFERENCED_PARAMETER( pvReserved );
// Check if we are shutting down
if ( dwReason == DLL_PROCESS_DETACH )
{
// CDbgMemAlloc is a global object and destructs after the _Lockit object in the CRT runtime,
// so we can't actually operate on the STL object in a normal destructor here as its support libraries have been turned off already
s_DbgMemAlloc.Shutdown();
}
return TRUE;
}
#endif
//-----------------------------------------------------------------------------
// Release versions
//-----------------------------------------------------------------------------
void *CDbgMemAlloc::Alloc( size_t nSize )
{
/*
// NOTE: Uncomment this to find unknown allocations
const char *pFileName = g_pszUnknown;
int nLine;
GetActualDbgInfo( pFileName, nLine );
if (pFileName == g_pszUnknown)
{
int x = 3;
}
*/
char szModule[MAX_PATH];
if ( GetCallerModule( szModule ) )
{
return Alloc( nSize, szModule, 0 );
}
else
{
return Alloc( nSize, g_pszUnknown, 0 );
}
// return malloc( nSize );
}
void *CDbgMemAlloc::Realloc( void *pMem, size_t nSize )
{
/*
// NOTE: Uncomment this to find unknown allocations
const char *pFileName = g_pszUnknown;
int nLine;
GetActualDbgInfo( pFileName, nLine );
if (pFileName == g_pszUnknown)
{
int x = 3;
}
*/
// FIXME: Should these gather stats?
char szModule[MAX_PATH];
if ( GetCallerModule( szModule ) )
{
return Realloc( pMem, nSize, szModule, 0 );
}
else
{
return Realloc( pMem, nSize, g_pszUnknown, 0 );
}
// return realloc( pMem, nSize );
}
void CDbgMemAlloc::Free( void *pMem )
{
// FIXME: Should these gather stats?
Free( pMem, g_pszUnknown, 0 );
// free( pMem );
}
void *CDbgMemAlloc::Expand_NoLongerSupported( void *pMem, size_t nSize )
{
return NULL;
}
//-----------------------------------------------------------------------------
// Force file + line information for an allocation
//-----------------------------------------------------------------------------
void CDbgMemAlloc::PushAllocDbgInfo( const char *pFileName, int nLine )
{
if ( g_DbgInfoStack == (int)NULL )
{
g_DbgInfoStack = (DbgInfoStack_t *)DebugAlloc( sizeof(DbgInfoStack_t) * DBG_INFO_STACK_DEPTH );
g_nDbgInfoStackDepth = -1;
}
++g_nDbgInfoStackDepth;
Assert( g_nDbgInfoStackDepth < DBG_INFO_STACK_DEPTH );
g_DbgInfoStack[g_nDbgInfoStackDepth].m_pFileName = FindOrCreateFilename( pFileName );
g_DbgInfoStack[g_nDbgInfoStackDepth].m_nLine = nLine;
}
void CDbgMemAlloc::PopAllocDbgInfo()
{
if ( g_DbgInfoStack == (int)NULL )
{
g_DbgInfoStack = (DbgInfoStack_t *)DebugAlloc( sizeof(DbgInfoStack_t) * DBG_INFO_STACK_DEPTH );
g_nDbgInfoStackDepth = -1;
}
--g_nDbgInfoStackDepth;
Assert( g_nDbgInfoStackDepth >= -1 );
}
//-----------------------------------------------------------------------------
// handles storing allocation info for coroutines
//-----------------------------------------------------------------------------
uint32 CDbgMemAlloc::GetDebugInfoSize()
{
return sizeof( DbgInfoStack_t ) * DBG_INFO_STACK_DEPTH + sizeof( int32 );
}
void CDbgMemAlloc::SaveDebugInfo( void *pvDebugInfo )
{
if ( g_DbgInfoStack == (int)NULL )
{
g_DbgInfoStack = (DbgInfoStack_t *)DebugAlloc( sizeof(DbgInfoStack_t) * DBG_INFO_STACK_DEPTH );
g_nDbgInfoStackDepth = -1;
}
int32 *pnStackDepth = (int32*) pvDebugInfo;
*pnStackDepth = g_nDbgInfoStackDepth;
memcpy( pnStackDepth+1, &g_DbgInfoStack[0], sizeof( DbgInfoStack_t ) * DBG_INFO_STACK_DEPTH );
}
void CDbgMemAlloc::RestoreDebugInfo( const void *pvDebugInfo )
{
if ( g_DbgInfoStack == (int)NULL )
{
g_DbgInfoStack = (DbgInfoStack_t *)DebugAlloc( sizeof(DbgInfoStack_t) * DBG_INFO_STACK_DEPTH );
g_nDbgInfoStackDepth = -1;
}
const int32 *pnStackDepth = (const int32*) pvDebugInfo;
g_nDbgInfoStackDepth = *pnStackDepth;
memcpy( &g_DbgInfoStack[0], pnStackDepth+1, sizeof( DbgInfoStack_t ) * DBG_INFO_STACK_DEPTH );
}
void CDbgMemAlloc::InitDebugInfo( void *pvDebugInfo, const char *pchRootFileName, int nLine )
{
int32 *pnStackDepth = (int32*) pvDebugInfo;
if( pchRootFileName )
{
*pnStackDepth = 0;
DbgInfoStack_t *pStackRoot = (DbgInfoStack_t *)(pnStackDepth + 1);
pStackRoot->m_pFileName = FindOrCreateFilename( pchRootFileName );
pStackRoot->m_nLine = nLine;
}
else
{
*pnStackDepth = -1;
}
}
//-----------------------------------------------------------------------------
// Returns the actual debug info
//-----------------------------------------------------------------------------
void CDbgMemAlloc::GetActualDbgInfo( const char *&pFileName, int &nLine )
{
#if defined( USE_STACK_WALK_DETAILED )
return;
#endif
if ( g_DbgInfoStack == (int)NULL )
{
g_DbgInfoStack = (DbgInfoStack_t *)DebugAlloc( sizeof(DbgInfoStack_t) * DBG_INFO_STACK_DEPTH );
g_nDbgInfoStackDepth = -1;
}
if ( g_nDbgInfoStackDepth >= 0 && g_DbgInfoStack[0].m_pFileName)
{
pFileName = g_DbgInfoStack[0].m_pFileName;
nLine = g_DbgInfoStack[0].m_nLine;
}
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
const char *CDbgMemAlloc::FindOrCreateFilename( const char *pFileName )
{
Initialize();
// If we created it for the first time, actually *allocate* the filename memory