-
Notifications
You must be signed in to change notification settings - Fork 270
/
Copy pathmemstd.cpp
1904 lines (1630 loc) · 48.2 KB
/
memstd.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)
#if defined( _WIN32 ) && !defined( _X360 )
#define WIN_32_LEAN_AND_MEAN
#include <windows.h>
#define VA_COMMIT_FLAGS MEM_COMMIT
#define VA_RESERVE_FLAGS MEM_RESERVE
#elif defined( _X360 )
#undef Verify
#define VA_COMMIT_FLAGS (MEM_COMMIT|MEM_NOZERO|MEM_LARGE_PAGES)
#define VA_RESERVE_FLAGS (MEM_RESERVE|MEM_LARGE_PAGES)
#endif
#ifdef OSX
#include <malloc/malloc.h>
#else
#include <malloc.h>
#endif
#include "tier0/valve_minmax_off.h" // GCC 4.2.2 headers screw up our min/max defs.
#include <algorithm>
#include "tier0/valve_minmax_on.h" // GCC 4.2.2 headers screw up our min/max defs.
#include "tier0/dbg.h"
#include "tier0/memalloc.h"
#include "tier0/threadtools.h"
#include "mem_helpers.h"
#include "memstd.h"
#ifdef _X360
#include "xbox/xbox_console.h"
#endif
// Force on redirecting all allocations to the process heap on Win64,
// which currently means the GC. This is to make AppVerifier more effective
// at catching memory stomps.
#if defined( _WIN64 )
#define FORCE_PROCESS_HEAP
#elif defined( _WIN32 )
// Define this to force using the OS Heap* functions for allocations. This is useful
// in conjunction with AppVerifier/PageHeap in order to find memory problems, and
// also allows ETW/xperf tracing to be used to record allocations.
// Normally the command-line option -processheap can be used instead.
//#define FORCE_PROCESS_HEAP
#define ALLOW_PROCESS_HEAP
#endif
// Track this to decide how to handle out-of-memory.
static bool s_bPageHeapEnabled = false;
#ifdef TIME_ALLOC
CAverageCycleCounter g_MallocCounter;
CAverageCycleCounter g_ReallocCounter;
CAverageCycleCounter g_FreeCounter;
#define PrintOne( name ) \
Msg("%-48s: %6.4f avg (%8.1f total, %7.3f peak, %5d iters)\n", \
#name, \
g_##name##Counter.GetAverageMilliseconds(), \
g_##name##Counter.GetTotalMilliseconds(), \
g_##name##Counter.GetPeakMilliseconds(), \
g_##name##Counter.GetIters() ); \
memset( &g_##name##Counter, 0, sizeof(g_##name##Counter) )
void PrintAllocTimes()
{
PrintOne( Malloc );
PrintOne( Realloc );
PrintOne( Free );
}
#define PROFILE_ALLOC(name) CAverageTimeMarker name##_ATM( &g_##name##Counter )
#else
#define PROFILE_ALLOC( name ) ((void)0)
#define PrintAllocTimes() ((void)0)
#endif
#if _MSC_VER < 1400 && defined( MSVC ) && !defined(_STATIC_LINKED) && (defined(_DEBUG) || defined(USE_MEM_DEBUG))
void *operator new( unsigned int nSize, int nBlockUse, const char *pFileName, int nLine )
{
return ::operator new( nSize );
}
void *operator new[] ( unsigned int nSize, int nBlockUse, const char *pFileName, int nLine )
{
return ::operator new[]( nSize );
}
#endif
#if (!defined(_DEBUG) && !defined(USE_MEM_DEBUG))
// Support for CHeapMemAlloc for easy switching to using the process heap.
#ifdef ALLOW_PROCESS_HEAP
// Round a size up to a multiple of 4 KB to aid in calculating how much
// memory is required if full pageheap is enabled.
static size_t RoundUpToPage( size_t nSize )
{
nSize += 0xFFF;
nSize &= ~0xFFF;
return nSize;
}
// Convenience function to deal with the necessary type-casting
static void InterlockedAddSizeT( size_t volatile *Addend, size_t Value )
{
#ifdef PLATFORM_WINDOWS_PC32
COMPILE_TIME_ASSERT( sizeof( size_t ) == sizeof( int32 ) );
InterlockedExchangeAdd( ( LONG* )Addend, LONG( Value ) );
#else
InterlockedExchangeAdd64( ( LONGLONG* )Addend, LONGLONG( Value ) );
#endif
}
class CHeapMemAlloc : public IMemAlloc
{
public:
CHeapMemAlloc()
{
// Make sure that we return 64-bit addresses in 64-bit builds.
ReserveBottomMemory();
// Do all allocations with the shared process heap so that we can still
// allocate from one DLL and free in another.
m_heap = GetProcessHeap();
}
void Init( bool bZeroMemory )
{
m_HeapFlags = bZeroMemory ? HEAP_ZERO_MEMORY : 0;
// Can't use Msg here because it isn't necessarily initialized yet.
if ( s_bPageHeapEnabled )
{
OutputDebugStringA("PageHeap is on. Memory use will be larger than normal.\n" );
}
else
{
OutputDebugStringA("PageHeap is off. Memory use will be normal.\n" );
}
if( bZeroMemory )
{
OutputDebugStringA( " HEAP_ZERO_MEMORY is specified.\n" );
}
}
// Release versions
virtual void *Alloc( size_t nSize )
{
// Ensure that the constructor has run already. Poorly defined
// order of construction can result in the allocator being used
// before it is constructed. Which could be bad.
if ( !m_heap )
__debugbreak();
void* pMem = HeapAlloc( m_heap, m_HeapFlags, nSize );
if ( pMem )
{
InterlockedAddSizeT( &m_nOutstandingBytes, nSize );
InterlockedAddSizeT( &m_nOutstandingPageHeapBytes, RoundUpToPage( nSize ) );
InterlockedIncrement( &m_nOutstandingAllocations );
InterlockedIncrement( &m_nLifetimeAllocations );
}
else if ( nSize )
{
// Having PageHeap enabled leads to lots of allocation failures. These
// then lead to crashes. In order to avoid confusion about the cause of
// these crashes, halt immediately on allocation failures.
__debugbreak();
InterlockedIncrement( &m_nAllocFailures );
}
return pMem;
}
virtual void *Realloc( void *pMem, size_t nSize )
{
// If you pass zero to HeapReAlloc then it fails (with GetLastError() saying S_OK!)
// so only call HeapReAlloc if pMem is non-zero.
if ( pMem )
{
if ( !nSize )
{
// Call the regular free function.
Free( pMem );
return 0;
}
size_t nOldSize = HeapSize( m_heap, 0, pMem );
void* pNewMem = HeapReAlloc( m_heap, m_HeapFlags, pMem, nSize );
// If we successfully allocated the requested memory (zero counts as
// success if we requested zero bytes) then update the counters for the
// change.
if ( pNewMem )
{
InterlockedAddSizeT( &m_nOutstandingBytes, nSize - nOldSize );
InterlockedAddSizeT( &m_nOutstandingPageHeapBytes, RoundUpToPage( nSize ) );
InterlockedAddSizeT( &m_nOutstandingPageHeapBytes, 0 - RoundUpToPage( nOldSize ) );
// Outstanding allocation count isn't affected by Realloc, but
// lifetime allocation count is.
InterlockedIncrement( &m_nLifetimeAllocations );
}
else
{
// Having PageHeap enabled leads to lots of allocation failures. These
// then lead to crashes. In order to avoid confusion about the cause of
// these crashes, halt immediately on allocation failures.
__debugbreak();
InterlockedIncrement( &m_nAllocFailures );
}
return pNewMem;
}
// Call the regular alloc function.
return Alloc( nSize );
}
virtual void Free( void *pMem )
{
if ( pMem )
{
size_t nOldSize = HeapSize( m_heap, 0, pMem );
InterlockedAddSizeT( &m_nOutstandingBytes, 0 - nOldSize );
InterlockedAddSizeT( &m_nOutstandingPageHeapBytes, 0 - RoundUpToPage( nOldSize ) );
InterlockedDecrement( &m_nOutstandingAllocations );
HeapFree( m_heap, 0, pMem );
}
}
virtual void *Expand_NoLongerSupported( void *pMem, size_t nSize ) { return 0; }
// Debug versions
virtual void *Alloc( size_t nSize, const char *pFileName, int nLine ) { return Alloc( nSize ); }
virtual void *Realloc( void *pMem, size_t nSize, const char *pFileName, int nLine ) { return Realloc(pMem, nSize); }
virtual void Free( void *pMem, const char *pFileName, int nLine ) { Free( pMem ); }
virtual void *Expand_NoLongerSupported( void *pMem, size_t nSize, const char *pFileName, int nLine ) { return 0; }
#ifdef MEMALLOC_SUPPORTS_ALIGNED_ALLOCATIONS
// Not currently implemented
#error
#endif
virtual void *RegionAlloc( int region, size_t nSize ) { __debugbreak(); return 0; }
virtual void *RegionAlloc( int region, size_t nSize, const char *pFileName, int nLine ) { __debugbreak(); return 0; }
// Returns size of a particular allocation
// If zero is returned then return the total size of allocated memory.
virtual size_t GetSize( void *pMem )
{
if ( !pMem )
{
return m_nOutstandingBytes;
}
return HeapSize( m_heap, 0, pMem );
}
// Force file + line information for an allocation
virtual void PushAllocDbgInfo( const char *pFileName, int nLine ) {}
virtual void PopAllocDbgInfo() {}
virtual long CrtSetBreakAlloc( long lNewBreakAlloc ) { return 0; }
virtual int CrtSetReportMode( int nReportType, int nReportMode ) { return 0; }
virtual int CrtIsValidHeapPointer( const void *pMem ) { return 0; }
virtual int CrtIsValidPointer( const void *pMem, unsigned int size, int access ) { return 0; }
virtual int CrtCheckMemory( void ) { return 0; }
virtual int CrtSetDbgFlag( int nNewFlag ) { return 0; }
virtual void CrtMemCheckpoint( _CrtMemState *pState ) {}
virtual void* CrtSetReportFile( int nRptType, void* hFile ) { return 0; }
virtual void* CrtSetReportHook( void* pfnNewHook ) { return 0; }
virtual int CrtDbgReport( int nRptType, const char * szFile,
int nLine, const char * szModule, const char * pMsg ) { return 0; }
virtual int heapchk() { return -2/*_HEAPOK*/; }
virtual void DumpStats()
{
const size_t MB = 1024 * 1024;
Msg( "Sorry -- no stats saved to file memstats.txt when the heap allocator is enabled.\n" );
// Print requested memory.
Msg( "%u MB allocated.\n", ( unsigned )( m_nOutstandingBytes / MB ) );
// Print memory after rounding up to pages.
Msg( "%u MB assuming maximum PageHeap overhead.\n", ( unsigned )( m_nOutstandingPageHeapBytes / MB ));
// Print memory after adding in reserved page after every allocation. Do 64-bit calculations
// because the pageHeap required memory can easily go over 4 GB.
__int64 pageHeapBytes = m_nOutstandingPageHeapBytes + m_nOutstandingAllocations * 4096LL;
Msg( "%u MB address space used assuming maximum PageHeap overhead.\n", ( unsigned )( pageHeapBytes / MB ));
Msg( "%u outstanding allocations (%d delta).\n", ( unsigned )m_nOutstandingAllocations, ( int )( m_nOutstandingAllocations - m_nOldOutstandingAllocations ) );
Msg( "%u lifetime allocations (%u delta).\n", ( unsigned )m_nLifetimeAllocations, ( unsigned )( m_nLifetimeAllocations - m_nOldLifetimeAllocations ) );
Msg( "%u allocation failures.\n", ( unsigned )m_nAllocFailures );
// Update the numbers on outstanding and lifetime allocation counts so
// that we can print out deltas.
m_nOldOutstandingAllocations = m_nOutstandingAllocations;
m_nOldLifetimeAllocations = m_nLifetimeAllocations;
}
virtual void DumpStatsFileBase( char const *pchFileBase ) {}
virtual size_t ComputeMemoryUsedBy( char const *pchSubStr ) { return 0; }
virtual void GlobalMemoryStatus( size_t *pUsedMemory, size_t *pFreeMemory ) {}
virtual bool IsDebugHeap() { return false; }
virtual uint32 GetDebugInfoSize() { return 0; }
virtual void SaveDebugInfo( void *pvDebugInfo ) { }
virtual void RestoreDebugInfo( const void *pvDebugInfo ) {}
virtual void InitDebugInfo( void *pvDebugInfo, const char *pchRootFileName, int nLine ) {}
virtual void GetActualDbgInfo( const char *&pFileName, int &nLine ) {}
virtual void RegisterAllocation( const char *pFileName, int nLine, size_t nLogicalSize, size_t nActualSize, unsigned nTime ) {}
virtual void RegisterDeallocation( const char *pFileName, int nLine, size_t nLogicalSize, size_t nActualSize, unsigned nTime ) {}
virtual int GetVersion() { return MEMALLOC_VERSION; }
virtual void OutOfMemory( size_t nBytesAttempted = 0 ) {}
virtual void CompactHeap() {}
virtual void CompactIncremental() {}
virtual MemAllocFailHandler_t SetAllocFailHandler( MemAllocFailHandler_t pfnMemAllocFailHandler ) { return 0; }
void DumpBlockStats( void *p ) {}
#if defined( _MEMTEST )
// Not currently implemented
#error
#endif
virtual size_t MemoryAllocFailed() { return 0; }
private:
// Handle to the process heap.
HANDLE m_heap;
uint32 m_HeapFlags;
// Total outstanding bytes allocated.
volatile size_t m_nOutstandingBytes;
// Total outstanding committed bytes assuming that all allocations are
// put on individual 4-KB pages (true when using full PageHeap from
// App Verifier).
volatile size_t m_nOutstandingPageHeapBytes;
// Total outstanding allocations. With PageHeap enabled each allocation
// requires an extra 4-KB page of address space.
volatile LONG m_nOutstandingAllocations;
LONG m_nOldOutstandingAllocations;
// Total allocations without subtracting freed memory.
volatile LONG m_nLifetimeAllocations;
LONG m_nOldLifetimeAllocations;
// Total number of allocation failures.
volatile LONG m_nAllocFailures;
};
#endif //ALLOW_PROCESS_HEAP
//-----------------------------------------------------------------------------
// Singletons...
//-----------------------------------------------------------------------------
#pragma warning( disable:4074 ) // warning C4074: initializers put in compiler reserved initialization area
#pragma init_seg( compiler )
static CStdMemAlloc s_StdMemAlloc CONSTRUCT_EARLY;
#ifndef TIER0_VALIDATE_HEAP
IMemAlloc *g_pMemAlloc = &s_StdMemAlloc;
#else
IMemAlloc *g_pActualAlloc = &s_StdMemAlloc;
#endif
#if defined(ALLOW_PROCESS_HEAP) && !defined(TIER0_VALIDATE_HEAP)
void EnableHeapMemAlloc( bool bZeroMemory )
{
// Place this here to guarantee it is constructed
// before we call Init.
static CHeapMemAlloc s_HeapMemAlloc;
static bool s_initCalled = false;
if ( !s_initCalled )
{
s_HeapMemAlloc.Init( bZeroMemory );
g_pMemAlloc = &s_HeapMemAlloc;
s_initCalled = true;
}
}
// Check whether PageHeap (part of App Verifier) has been enabled for this process.
// It specifically checks whether it was enabled by the EnableAppVerifier.bat
// batch file. This can be used to automatically enable -processheap when
// App Verifier is in use.
static bool IsPageHeapEnabled( bool& bETWHeapEnabled )
{
// Assume false.
bool result = false;
bETWHeapEnabled = false;
// First we get the application's name so we can look in the registry
// for App Verifier settings.
HMODULE exeHandle = GetModuleHandle( 0 );
if ( exeHandle )
{
char appName[ MAX_PATH ];
if ( GetModuleFileNameA( exeHandle, appName, ARRAYSIZE( appName ) ) )
{
// Guarantee null-termination -- not guaranteed on Windows XP!
appName[ ARRAYSIZE( appName ) - 1 ] = 0;
// Find the file part of the name.
const char* pFilePart = strrchr( appName, '\\' );
if ( pFilePart )
{
++pFilePart;
size_t len = strlen( pFilePart );
if ( len > 0 && pFilePart[ len - 1 ] == ' ' )
{
OutputDebugStringA( "Trailing space on executable name! This will cause Application Verifier and ETW Heap tracing to fail!\n" );
DebuggerBreakIfDebugging();
}
// Generate the key name for App Verifier settings for this process.
char regPathName[ MAX_PATH ];
_snprintf( regPathName, ARRAYSIZE( regPathName ),
"Software\\Microsoft\\Windows NT\\CurrentVersion\\Image File Execution Options\\%s",
pFilePart );
regPathName[ ARRAYSIZE( regPathName ) - 1 ] = 0;
HKEY key;
LONG regResult = RegOpenKeyA( HKEY_LOCAL_MACHINE,
regPathName,
&key );
if ( regResult == ERROR_SUCCESS )
{
// If PageHeapFlags exists then that means that App Verifier is enabled
// for this application. The StackTraceDatabaseSizeInMB is only
// set by Valve's enabling batch file so this indicates that
// a developer at Valve is using App Verifier.
if ( RegQueryValueExA( key, "StackTraceDatabaseSizeInMB", 0, NULL, NULL, NULL ) == ERROR_SUCCESS &&
RegQueryValueExA( key, "PageHeapFlags", 0, NULL, NULL, NULL) == ERROR_SUCCESS )
{
result = true;
}
if ( RegQueryValueExA( key, "TracingFlags", 0, NULL, NULL, NULL) == ERROR_SUCCESS )
bETWHeapEnabled = true;
RegCloseKey( key );
}
}
}
}
return result;
}
// Check for various allocator overrides such as -processheap and -reservelowmem.
// Returns true if -processheap is enabled, by a command line switch or other method.
bool CheckWindowsAllocSettings( const char* upperCommandLine )
{
// Are we doing ETW heap profiling?
bool bETWHeapEnabled = false;
s_bPageHeapEnabled = IsPageHeapEnabled( bETWHeapEnabled );
// Should we reserve the bottom 4 GB of RAM in order to flush out pointer
// truncation bugs? This helps ensure 64-bit compatibility.
// However this needs to be off by default to avoid causing compatibility problems,
// with Steam detours and other systems. It should also be disabled when PageHeap
// is on because for some reason the combination turns into 4 GB of working set, which
// can easily cause problems.
if ( strstr( upperCommandLine, "-RESERVELOWMEM" ) && !s_bPageHeapEnabled )
ReserveBottomMemory();
// Uninitialized data, including pointers, is often set to 0xFFEEFFEE.
// If we reserve that block of memory then we can turn these pointer
// dereferences into crashes a little bit earlier and more reliably.
// We don't really care whether this allocation succeeds, but it's
// worth trying. Note that we do this in all cases -- whether we are using
// -processheap or not.
VirtualAlloc( (void*)0xFFEEFFEE, 1, MEM_RESERVE, PAGE_NOACCESS );
// Enable application termination (breakpoint) on heap corruption. This is
// better than trying to patch it up and continue, both from a security and
// a bug-finding point of view. Do this always on Windows since the heap is
// used by video drivers and other in-proc components.
//HeapSetInformation( NULL, HeapEnableTerminationOnCorruption, NULL, 0 );
// The HeapEnableTerminationOnCorruption requires a recent platform SDK,
// so fake it up.
#if defined(PLATFORM_WINDOWS_PC)
HeapSetInformation( NULL, (HEAP_INFORMATION_CLASS)1, NULL, 0 );
#endif
bool bZeroMemory = false;
bool bProcessHeap = false;
// Should we force using the process heap? This is handy for gathering memory
// statistics with ETW/xperf. When using App Verifier -processheap is automatically
// turned on.
if ( strstr( upperCommandLine, "-PROCESSHEAP" ) )
{
bProcessHeap = true;
bZeroMemory = !!strstr( upperCommandLine, "-PROCESSHEAPZEROMEM" );
}
// Unless specifically disabled, turn on -processheap if pageheap or ETWHeap tracing
// are enabled.
if ( !strstr( upperCommandLine, "-NOPROCESSHEAP" ) && ( s_bPageHeapEnabled || bETWHeapEnabled ) )
bProcessHeap = true;
if ( bProcessHeap )
{
// Now all allocations will go through the system heap.
EnableHeapMemAlloc( bZeroMemory );
}
return bProcessHeap;
}
class CInitGlobalMemAllocPtr
{
public:
CInitGlobalMemAllocPtr()
{
char *pStr = (char*)Plat_GetCommandLineA();
if ( pStr )
{
char tempStr[512];
strncpy( tempStr, pStr, sizeof( tempStr ) - 1 );
tempStr[ sizeof( tempStr ) - 1 ] = 0;
_strupr( tempStr );
CheckWindowsAllocSettings( tempStr );
}
#if defined(FORCE_PROCESS_HEAP)
// This may cause EnableHeapMemAlloc to be called twice, but that's okay.
EnableHeapMemAlloc( false );
#endif
}
};
CInitGlobalMemAllocPtr sg_InitGlobalMemAllocPtr;
#endif
#ifdef _WIN32
//-----------------------------------------------------------------------------
// Small block heap (multi-pool)
//-----------------------------------------------------------------------------
#ifndef NO_SBH
#ifdef ALLOW_NOSBH
static bool g_UsingSBH = true;
#define UsingSBH() g_UsingSBH
#else
#define UsingSBH() true
#endif
#else
#define UsingSBH() false
#endif
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
template <typename T>
inline T MemAlign( T val, size_t alignment )
{
return (T)( ( (size_t)val + alignment - 1 ) & ~( alignment - 1 ) );
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
void CSmallBlockPool::Init( unsigned nBlockSize, byte *pBase, unsigned initialCommit )
{
if ( !( nBlockSize % MIN_SBH_ALIGN == 0 && nBlockSize >= MIN_SBH_BLOCK && nBlockSize >= sizeof(TSLNodeBase_t) ) )
DebuggerBreak();
m_nBlockSize = nBlockSize;
m_pCommitLimit = m_pNextAlloc = m_pBase = pBase;
m_pAllocLimit = m_pBase + MAX_POOL_REGION;
if ( initialCommit )
{
initialCommit = MemAlign( initialCommit, SBH_PAGE_SIZE );
if ( !VirtualAlloc( m_pCommitLimit, initialCommit, VA_COMMIT_FLAGS, PAGE_READWRITE ) )
{
Assert( 0 );
return;
}
m_pCommitLimit += initialCommit;
}
}
size_t CSmallBlockPool::GetBlockSize()
{
return m_nBlockSize;
}
bool CSmallBlockPool::IsOwner( void *p )
{
return ( p >= m_pBase && p < m_pAllocLimit );
}
void *CSmallBlockPool::Alloc()
{
void *pResult = m_FreeList.Pop();
if ( !pResult )
{
int nBlockSize = m_nBlockSize;
byte *pCommitLimit;
byte *pNextAlloc;
for (;;)
{
pCommitLimit = m_pCommitLimit;
pNextAlloc = m_pNextAlloc;
if ( pNextAlloc + nBlockSize <= pCommitLimit )
{
if ( m_pNextAlloc.AssignIf( pNextAlloc, pNextAlloc + m_nBlockSize ) )
{
pResult = pNextAlloc;
break;
}
}
else
{
AUTO_LOCK( m_CommitMutex );
if ( pCommitLimit == m_pCommitLimit )
{
if ( pCommitLimit + COMMIT_SIZE <= m_pAllocLimit )
{
if ( !VirtualAlloc( pCommitLimit, COMMIT_SIZE, VA_COMMIT_FLAGS, PAGE_READWRITE ) )
{
Assert( 0 );
return NULL;
}
m_pCommitLimit = pCommitLimit + COMMIT_SIZE;
}
else
{
return NULL;
}
}
}
}
}
return pResult;
}
void CSmallBlockPool::Free( void *p )
{
Assert( IsOwner( p ) );
m_FreeList.Push( p );
}
// Count the free blocks.
int CSmallBlockPool::CountFreeBlocks()
{
return m_FreeList.Count();
}
// Size of committed memory managed by this heap:
int CSmallBlockPool::GetCommittedSize()
{
unsigned totalSize = (uintp)m_pCommitLimit - (uintp)m_pBase;
Assert( 0 != m_nBlockSize );
return totalSize;
}
// Return the total blocks memory is committed for in the heap
int CSmallBlockPool::CountCommittedBlocks()
{
return GetCommittedSize() / GetBlockSize();
}
// Count the number of allocated blocks in the heap:
int CSmallBlockPool::CountAllocatedBlocks()
{
return CountCommittedBlocks( ) - ( CountFreeBlocks( ) + ( m_pCommitLimit - (byte *)m_pNextAlloc ) / GetBlockSize() );
}
int CSmallBlockPool::Compact()
{
int nBytesFreed = 0;
if ( m_FreeList.Count() )
{
int i;
int nFree = CountFreeBlocks();
FreeBlock_t **pSortArray = (FreeBlock_t **)malloc( nFree * sizeof(FreeBlock_t *) ); // can't use new because will reenter
if ( !pSortArray )
{
return 0;
}
i = 0;
while ( i < nFree )
{
pSortArray[i++] = m_FreeList.Pop();
}
std::sort( pSortArray, pSortArray + nFree );
byte *pOldNextAlloc = m_pNextAlloc;
for ( i = nFree - 1; i >= 0; i-- )
{
if ( (byte *)pSortArray[i] == m_pNextAlloc - m_nBlockSize )
{
pSortArray[i] = NULL;
m_pNextAlloc -= m_nBlockSize;
}
else
{
break;
}
}
if ( pOldNextAlloc != m_pNextAlloc )
{
byte *pNewCommitLimit = MemAlign( (byte *)m_pNextAlloc, SBH_PAGE_SIZE );
if ( pNewCommitLimit < m_pCommitLimit )
{
nBytesFreed = m_pCommitLimit - pNewCommitLimit;
VirtualFree( pNewCommitLimit, nBytesFreed, MEM_DECOMMIT );
m_pCommitLimit = pNewCommitLimit;
}
}
if ( pSortArray[0] )
{
for ( i = 0; i < nFree ; i++ )
{
if ( !pSortArray[i] )
{
break;
}
m_FreeList.Push( pSortArray[i] );
}
}
free( pSortArray );
}
return nBytesFreed;
}
//-----------------------------------------------------------------------------
//
//-----------------------------------------------------------------------------
#define GetInitialCommitForPool( i ) 0
CSmallBlockHeap::CSmallBlockHeap()
{
// Make sure that we return 64-bit addresses in 64-bit builds.
ReserveBottomMemory();
if ( !UsingSBH() )
{
return;
}
m_pBase = (byte *)VirtualAlloc( NULL, NUM_POOLS * MAX_POOL_REGION, VA_RESERVE_FLAGS, PAGE_NOACCESS );
m_pLimit = m_pBase + NUM_POOLS * MAX_POOL_REGION;
// Build a lookup table used to find the correct pool based on size
const int MAX_TABLE = MAX_SBH_BLOCK >> 2;
int i = 0;
int nBytesElement = 0;
byte *pCurBase = m_pBase;
CSmallBlockPool *pCurPool = NULL;
int iCurPool = 0;
#if _M_X64
// Blocks sized 0 - 256 are in pools in increments of 16
for ( ; i < 64 && i < MAX_TABLE; i++ )
{
if ( (i + 1) % 4 == 1)
{
nBytesElement += 16;
pCurPool = &m_Pools[iCurPool];
pCurPool->Init( nBytesElement, pCurBase, GetInitialCommitForPool(iCurPool) );
iCurPool++;
m_PoolLookup[i] = pCurPool;
pCurBase += MAX_POOL_REGION;
}
else
{
m_PoolLookup[i] = pCurPool;
}
}
#else
// Blocks sized 0 - 128 are in pools in increments of 8
for ( ; i < 32; i++ )
{
if ( (i + 1) % 2 == 1)
{
nBytesElement += 8;
pCurPool = &m_Pools[iCurPool];
pCurPool->Init( nBytesElement, pCurBase, GetInitialCommitForPool(iCurPool) );
iCurPool++;
m_PoolLookup[i] = pCurPool;
pCurBase += MAX_POOL_REGION;
}
else
{
m_PoolLookup[i] = pCurPool;
}
}
// Blocks sized 129 - 256 are in pools in increments of 16
for ( ; i < 64; i++ )
{
if ( (i + 1) % 4 == 1)
{
nBytesElement += 16;
pCurPool = &m_Pools[iCurPool];
pCurPool->Init( nBytesElement, pCurBase, GetInitialCommitForPool(iCurPool) );
iCurPool++;
m_PoolLookup[i] = pCurPool;
pCurBase += MAX_POOL_REGION;
}
else
{
m_PoolLookup[i] = pCurPool;
}
}
#endif
// Blocks sized 257 - 512 are in pools in increments of 32
for ( ; i < 128; i++ )
{
if ( (i + 1) % 8 == 1)
{
nBytesElement += 32;
pCurPool = &m_Pools[iCurPool];
pCurPool->Init( nBytesElement, pCurBase, GetInitialCommitForPool(iCurPool) );
iCurPool++;
m_PoolLookup[i] = pCurPool;
pCurBase += MAX_POOL_REGION;
}
else
{
m_PoolLookup[i] = pCurPool;
}
}
// Blocks sized 513 - 768 are in pools in increments of 64
for ( ; i < 192; i++ )
{
if ( (i + 1) % 16 == 1)
{
nBytesElement += 64;
pCurPool = &m_Pools[iCurPool];
pCurPool->Init( nBytesElement, pCurBase, GetInitialCommitForPool(iCurPool) );
iCurPool++;
m_PoolLookup[i] = pCurPool;
pCurBase += MAX_POOL_REGION;
}
else
{
m_PoolLookup[i] = pCurPool;
}
}
// Blocks sized 769 - 1024 are in pools in increments of 128
for ( ; i < 256; i++ )
{
if ( (i + 1) % 32 == 1)
{
nBytesElement += 128;
pCurPool = &m_Pools[iCurPool];
pCurPool->Init( nBytesElement, pCurBase, GetInitialCommitForPool(iCurPool) );
iCurPool++;
m_PoolLookup[i] = pCurPool;
pCurBase += MAX_POOL_REGION;
}
else
{
m_PoolLookup[i] = pCurPool;
}
}
// Blocks sized 1025 - 2048 are in pools in increments of 256
for ( ; i < MAX_TABLE; i++ )
{
if ( (i + 1) % 64 == 1)
{
nBytesElement += 256;
pCurPool = &m_Pools[iCurPool];
pCurPool->Init( nBytesElement, pCurBase, GetInitialCommitForPool(iCurPool) );
iCurPool++;
m_PoolLookup[i] = pCurPool;
pCurBase += MAX_POOL_REGION;
}
else
{
m_PoolLookup[i] = pCurPool;
}
}
Assert( iCurPool == NUM_POOLS );
}
bool CSmallBlockHeap::ShouldUse( size_t nBytes )
{
return ( UsingSBH() && nBytes <= MAX_SBH_BLOCK );
}
bool CSmallBlockHeap::IsOwner( void * p )
{
return ( UsingSBH() && p >= m_pBase && p < m_pLimit );
}
void *CSmallBlockHeap::Alloc( size_t nBytes )
{
if ( nBytes == 0)
{
nBytes = 1;
}
Assert( ShouldUse( nBytes ) );
CSmallBlockPool *pPool = FindPool( nBytes );
void *p = pPool->Alloc();
if ( p )
{
return p;
}
if ( s_StdMemAlloc.CallAllocFailHandler( nBytes ) >= nBytes )
{
p = pPool->Alloc();
if ( p )
{
return p;
}
}
void *pRet = malloc( nBytes );
if ( !pRet )
{
s_StdMemAlloc.SetCRTAllocFailed( nBytes );
}
return pRet;
}
void *CSmallBlockHeap::Realloc( void *p, size_t nBytes )
{
if ( nBytes == 0)
{
nBytes = 1;
}
CSmallBlockPool *pOldPool = FindPool( p );
CSmallBlockPool *pNewPool = ( ShouldUse( nBytes ) ) ? FindPool( nBytes ) : NULL;
if ( pOldPool == pNewPool )
{
return p;
}
void *pNewBlock = NULL;
if ( pNewPool )
{
pNewBlock = pNewPool->Alloc();
if ( !pNewBlock )
{
if ( s_StdMemAlloc.CallAllocFailHandler( nBytes ) >= nBytes )
{
pNewBlock = pNewPool->Alloc();
}
}
}
if ( !pNewBlock )
{
pNewBlock = malloc( nBytes );
if ( !pNewBlock )
{
s_StdMemAlloc.SetCRTAllocFailed( nBytes );
}
}
if ( pNewBlock )
{
int nBytesCopy = min( nBytes, pOldPool->GetBlockSize() );
memcpy( pNewBlock, p, nBytesCopy );
}
pOldPool->Free( p );
return pNewBlock;