-
Notifications
You must be signed in to change notification settings - Fork 8
/
mmgr.cpp
1606 lines (1256 loc) · 61.2 KB
/
mmgr.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 2000, Paul Nettle. All rights reserved.
//
// You are free to use this source code in any commercial or non-commercial product.
//
// mmgr.cpp - Memory manager & tracking software
//
// The most recent version of this software can be found at: ftp://ftp.GraphicsPapers.com/pub/ProgrammingTools/MemoryManagers/
//
// [NOTE: Best when viewed with 8-character tabs]
//
// ---------------------------------------------------------------------------------------------------------------------------------
//
// !!IMPORTANT!!
//
// This software is self-documented with periodic comments. Before you start using this software, perform a search for the string
// "-DOC-" to locate pertinent information about how to use this software.
//
// You are also encouraged to read the comment blocks throughout this source file. They will help you understand how this memory
// tracking software works, so you can better utilize it within your applications.
//
// NOTES:
//
// 1. This code purposely uses no external routines that allocate RAM (other than the raw allocation routines, such as malloc). We
// do this because we want this to be as self-contained as possible. As an example, we don't use assert, because when running
// under WIN32, the assert brings up a dialog box, which allocates RAM. Doing this in the middle of an allocation would be bad.
//
// 2. When trying to override new/delete under MFC (which has its own version of global new/delete) the linker will complain. In
// order to fix this error, use the compiler option: /FORCE, which will force it to build an executable even with linker errors.
// Be sure to check those errors each time you compile, otherwise, you may miss a valid linker error.
//
// 3. If you see something that looks odd to you or seems like a strange way of going about doing something, then consider that this
// code was carefully thought out. If something looks odd, then just assume I've got a good reason for doing it that way (an
// example is the use of the class MemStaticTimeTracker.)
//
// 4. With MFC applications, you will need to comment out any occurance of "#define new DEBUG_NEW" from all source files.
//
// 5. Include file dependencies are _very_important_ for getting the MMGR to integrate nicely into your application. Be careful if
// you're including standard includes from within your own project inclues; that will break this very specific dependency order.
// It should look like this:
//
// #include <stdio.h> // Standard includes MUST come first
// #include <stdlib.h> //
// #include <streamio> //
//
// #include "mmgr.h" // mmgr.h MUST come next
//
// #include "myfile1.h" // Project includes MUST come last
// #include "myfile2.h" //
// #include "myfile3.h" //
//
// ---------------------------------------------------------------------------------------------------------------------------------
//#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <string.h>
#include <time.h>
#include <stdarg.h>
#include <new>
#ifndef WIN32
#include <unistd.h>
#endif
#include "mmgr.h"
// ---------------------------------------------------------------------------------------------------------------------------------
// -DOC- If you're like me, it's hard to gain trust in foreign code. This memory manager will try to INDUCE your code to crash (for
// very good reasons... like making bugs obvious as early as possible.) Some people may be inclined to remove this memory tracking
// software if it causes crashes that didn't exist previously. In reality, these new crashes are the BEST reason for using this
// software!
//
// Whether this software causes your application to crash, or if it reports errors, you need to be able to TRUST this software. To
// this end, you are given some very simple debugging tools.
//
// The quickest way to locate problems is to enable the STRESS_TEST macro (below.) This should catch 95% of the crashes before they
// occur by validating every allocation each time this memory manager performs an allocation function. If that doesn't work, keep
// reading...
//
// If you enable the TEST_MEMORY_MANAGER #define (below), this memory manager will log an entry in the memory.log file each time it
// enters and exits one of its primary allocation handling routines. Each call that succeeds should place an "ENTER" and an "EXIT"
// into the log. If the program crashes within the memory manager, it will log an "ENTER", but not an "EXIT". The log will also
// report the name of the routine.
//
// Just because this memory manager crashes does not mean that there is a bug here! First, an application could inadvertantly damage
// the heap, causing malloc(), realloc() or free() to crash. Also, an application could inadvertantly damage some of the memory used
// by this memory tracking software, causing it to crash in much the same way that a damaged heap would affect the standard
// allocation routines.
//
// In the event of a crash within this code, the first thing you'll want to do is to locate the actual line of code that is
// crashing. You can do this by adding log() entries throughout the routine that crashes, repeating this process until you narrow
// in on the offending line of code. If the crash happens in a standard C allocation routine (i.e. malloc, realloc or free) don't
// bother contacting me, your application has damaged the heap. You can help find the culprit in your code by enabling the
// STRESS_TEST macro (below.)
//
// If you truely suspect a bug in this memory manager (and you had better be sure about it! :) you can contact me at
// midnight@GraphicsPapers.com. Before you do, however, check for a newer version at:
//
// ftp://ftp.GraphicsPapers.com/pub/ProgrammingTools/MemoryManagers/
//
// When using this debugging aid, make sure that you are NOT setting the alwaysLogAll variable on, otherwise the log could be
// cluttered and hard to read.
// ---------------------------------------------------------------------------------------------------------------------------------
//#define TEST_MEMORY_MANAGER
// ---------------------------------------------------------------------------------------------------------------------------------
// -DOC- Enable this sucker if you really want to stress-test your app's memory usage, or to help find hard-to-find bugs
// ---------------------------------------------------------------------------------------------------------------------------------
//#define STRESS_TEST
// ---------------------------------------------------------------------------------------------------------------------------------
// -DOC- Enable this sucker if you want to stress-test your app's error-handling. Set RANDOM_FAIL to the percentage of failures you
// want to test with (0 = none, >100 = all failures).
// ---------------------------------------------------------------------------------------------------------------------------------
//#define RANDOM_FAILURE 100.0
// ---------------------------------------------------------------------------------------------------------------------------------
// -DOC- Locals -- modify these flags to suit your needs
// ---------------------------------------------------------------------------------------------------------------------------------
#ifdef STRESS_TEST
static const unsigned int hashBits = 12;
static bool randomWipe = true;
static bool alwaysValidateAll = true;
static bool alwaysLogAll = true;
static bool alwaysWipeAll = true;
static bool cleanupLogOnFirstRun = true;
static const unsigned int paddingSize = 1024; // An extra 8K per allocation!
#else
static const unsigned int hashBits = 12;
static bool randomWipe = false;
static bool alwaysValidateAll = false;
static bool alwaysLogAll = false;
static bool alwaysWipeAll = true;
static bool cleanupLogOnFirstRun = true;
static const unsigned int paddingSize = 4;
#endif
// ---------------------------------------------------------------------------------------------------------------------------------
// We define our own assert, because we don't want to bring up an assertion dialog, since that allocates RAM. Our new assert
// simply declares a forced breakpoint.
// ---------------------------------------------------------------------------------------------------------------------------------
#ifdef WIN32
#ifdef _DEBUG
#define m_assert(x) if ((x) == false) __asm { int 3 }
#else
#define m_assert(x) {}
#endif
#else // Linux uses assert, which we can use safely, since it doesn't bring up a dialog within the program.
#define m_assert assert
#endif
// ---------------------------------------------------------------------------------------------------------------------------------
// Here, we turn off our macros because any place in this source file where the word 'new' or the word 'delete' (etc.)
// appear will be expanded by the macro. So to avoid problems using them within this source file, we'll just #undef them.
// ---------------------------------------------------------------------------------------------------------------------------------
#undef new
#undef delete
#undef malloc
#undef calloc
#undef realloc
#undef free
// ---------------------------------------------------------------------------------------------------------------------------------
// Defaults for the constants & statics in the MemoryManager class
// ---------------------------------------------------------------------------------------------------------------------------------
const unsigned int m_alloc_unknown = 0;
const unsigned int m_alloc_new = 1;
const unsigned int m_alloc_new_array = 2;
const unsigned int m_alloc_malloc = 3;
const unsigned int m_alloc_calloc = 4;
const unsigned int m_alloc_realloc = 5;
const unsigned int m_alloc_delete = 6;
const unsigned int m_alloc_delete_array = 7;
const unsigned int m_alloc_free = 8;
// ---------------------------------------------------------------------------------------------------------------------------------
// -DOC- Get to know these values. They represent the values that will be used to fill unused and deallocated RAM.
// ---------------------------------------------------------------------------------------------------------------------------------
static unsigned int prefixPattern = 0xbaadf00d; // Fill pattern for bytes preceeding allocated blocks
static unsigned int postfixPattern = 0xdeadc0de; // Fill pattern for bytes following allocated blocks
static unsigned int unusedPattern = 0xfeedface; // Fill pattern for freshly allocated blocks
static unsigned int releasedPattern = 0xdeadbeef; // Fill pattern for deallocated blocks
// ---------------------------------------------------------------------------------------------------------------------------------
// Other locals
// ---------------------------------------------------------------------------------------------------------------------------------
static const unsigned int hashSize = 1 << hashBits;
static const char *allocationTypes[] = {"Unknown",
"new", "new[]", "malloc", "calloc",
"realloc", "delete", "delete[]", "free"};
static sAllocUnit *hashTable[hashSize];
static sAllocUnit *reservoir;
static unsigned int currentAllocationCount = 0;
static unsigned int breakOnAllocationCount = 0;
static sMStats stats;
static const char *sourceFile = "??";
static const char *sourceFunc = "??";
static unsigned int sourceLine = 0;
static bool staticDeinitTime = false;
static sAllocUnit **reservoirBuffer = NULL;
static unsigned int reservoirBufferSize = 0;
// ---------------------------------------------------------------------------------------------------------------------------------
// Local functions only
// ---------------------------------------------------------------------------------------------------------------------------------
static void doCleanupLogOnFirstRun()
{
if (cleanupLogOnFirstRun)
{
unlink("memory.log");
cleanupLogOnFirstRun = false;
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
static const char *sourceFileStripper(const char *sourceFile)
{
const char *ptr = strrchr(sourceFile, '\\');
if (ptr) return ptr + 1;
ptr = strrchr(sourceFile, '/');
if (ptr) return ptr + 1;
return sourceFile;
}
// ---------------------------------------------------------------------------------------------------------------------------------
static const char *ownerString(const char *sourceFile, const unsigned int sourceLine, const char *sourceFunc)
{
static char str[90];
memset(str, 0, sizeof(str));
sprintf(str, "%s(%05d)::%s", sourceFileStripper(sourceFile), sourceLine, sourceFunc);
return str;
}
// ---------------------------------------------------------------------------------------------------------------------------------
static const char *insertCommas(unsigned int value)
{
static char str[30];
memset(str, 0, sizeof(str));
sprintf(str, "%u", value);
if (strlen(str) > 3)
{
memmove(&str[strlen(str)-3], &str[strlen(str)-4], 4);
str[strlen(str) - 4] = ',';
}
if (strlen(str) > 7)
{
memmove(&str[strlen(str)-7], &str[strlen(str)-8], 8);
str[strlen(str) - 8] = ',';
}
if (strlen(str) > 11)
{
memmove(&str[strlen(str)-11], &str[strlen(str)-12], 12);
str[strlen(str) - 12] = ',';
}
return str;
}
// ---------------------------------------------------------------------------------------------------------------------------------
static const char *memorySizeString(unsigned long size)
{
static char str[90];
if (size > (1024*1024)) sprintf(str, "%10s (%7.2fM)", insertCommas(size), (float) size / (1024.0f * 1024.0f));
else if (size > 1024) sprintf(str, "%10s (%7.2fK)", insertCommas(size), (float) size / 1024.0f);
else sprintf(str, "%10s bytes ", insertCommas(size));
return str;
}
// ---------------------------------------------------------------------------------------------------------------------------------
static sAllocUnit *findAllocUnit(const void *reportedAddress)
{
// Just in case...
m_assert(reportedAddress != NULL);
// Use the address to locate the hash index. Note that we shift off the lower four bits. This is because most allocated
// addresses will be on four-, eight- or even sixteen-byte boundaries. If we didn't do this, the hash index would not have
// very good coverage.
unsigned int hashIndex = ((unsigned int) reportedAddress >> 4) & (hashSize - 1);
sAllocUnit *ptr = hashTable[hashIndex];
while(ptr)
{
if (ptr->reportedAddress == reportedAddress) return ptr;
ptr = ptr->next;
}
return NULL;
}
// ---------------------------------------------------------------------------------------------------------------------------------
static size_t calculateActualSize(const size_t reportedSize)
{
// We use DWORDS as our padding, and a long is guaranteed to be 4 bytes, but an int is not (ANSI defines an int as
// being the standard word size for a processor; on a 32-bit machine, that's 4 bytes, but on a 64-bit machine, it's
// 8 bytes, which means an int can actually be larger than a long.)
return reportedSize + paddingSize * sizeof(long) * 2;
}
// ---------------------------------------------------------------------------------------------------------------------------------
static size_t calculateReportedSize(const size_t actualSize)
{
// We use DWORDS as our padding, and a long is guaranteed to be 4 bytes, but an int is not (ANSI defines an int as
// being the standard word size for a processor; on a 32-bit machine, that's 4 bytes, but on a 64-bit machine, it's
// 8 bytes, which means an int can actually be larger than a long.)
return actualSize - paddingSize * sizeof(long) * 2;
}
// ---------------------------------------------------------------------------------------------------------------------------------
static void *calculateReportedAddress(const void *actualAddress)
{
// We allow this...
if (!actualAddress) return NULL;
// JUst account for the padding
return (void *) ((char *) actualAddress + sizeof(long) * paddingSize);
}
// ---------------------------------------------------------------------------------------------------------------------------------
static void wipeWithPattern(sAllocUnit *allocUnit, unsigned long pattern, const unsigned int originalReportedSize = 0)
{
// For a serious test run, we use wipes of random a random value. However, if this causes a crash, we don't want it to
// crash in a differnt place each time, so we specifically DO NOT call srand. If, by chance your program calls srand(),
// you may wish to disable that when running with a random wipe test. This will make any crashes more consistent so they
// can be tracked down easier.
if (randomWipe)
{
pattern = ((rand() & 0xff) << 24) | ((rand() & 0xff) << 16) | ((rand() & 0xff) << 8) | (rand() & 0xff);
}
// -DOC- We should wipe with 0's if we're not in debug mode, so we can help hide bugs if possible when we release the
// product. So uncomment the following line for releases.
//
// Note that the "alwaysWipeAll" should be turned on for this to have effect, otherwise it won't do much good. But we'll
// leave it this way (as an option) because this does slow things down.
// pattern = 0;
// This part of the operation is optional
if (alwaysWipeAll && allocUnit->reportedSize > originalReportedSize)
{
// Fill the bulk
long *lptr = (long *) ((char *)allocUnit->reportedAddress + originalReportedSize);
int length = allocUnit->reportedSize - originalReportedSize;
int i;
for (i = 0; i < (length >> 2); i++, lptr++)
{
*lptr = pattern;
}
// Fill the remainder
unsigned int shiftCount = 0;
char *cptr = (char *) lptr;
for (i = 0; i < (length & 0x3); i++, cptr++, shiftCount += 8)
{
*cptr = (pattern & (0xff << shiftCount)) >> shiftCount;
}
}
// Write in the prefix/postfix bytes
long *pre = (long *) allocUnit->actualAddress;
long *post = (long *) ((char *)allocUnit->actualAddress + allocUnit->actualSize - paddingSize * sizeof(long));
for (unsigned int i = 0; i < paddingSize; i++, pre++, post++)
{
*pre = prefixPattern;
*post = postfixPattern;
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
static void resetGlobals()
{
sourceFile = "??";
sourceLine = 0;
sourceFunc = "??";
}
// ---------------------------------------------------------------------------------------------------------------------------------
static void log(const char *format, ...)
{
// Build the buffer
static char buffer[2048];
va_list ap;
va_start(ap, format);
vsprintf(buffer, format, ap);
va_end(ap);
// Cleanup the log?
if (cleanupLogOnFirstRun) doCleanupLogOnFirstRun();
// Open the log file
FILE *fp = fopen("memory.log", "ab");
// If you hit this assert, then the memory logger is unable to log information to a file (can't open the file for some
// reason.) You can interrogate the variable 'buffer' to see what was supposed to be logged (but won't be.)
m_assert(fp);
if (!fp) return;
// Spit out the data to the log
fprintf(fp, "%s\r\n", buffer);
fclose(fp);
}
// ---------------------------------------------------------------------------------------------------------------------------------
static void dumpAllocations(FILE *fp)
{
fprintf(fp, "Alloc. Addr Size Addr Size BreakOn BreakOn \r\n");
fprintf(fp, "Number Reported Reported Actual Actual Unused Method Dealloc Realloc Allocated by \r\n");
fprintf(fp, "------ ---------- ---------- ---------- ---------- ---------- -------- ------- ------- --------------------------------------------------- \r\n");
for (unsigned int i = 0; i < hashSize; i++)
{
sAllocUnit *ptr = hashTable[i];
while(ptr)
{
fprintf(fp, "%06d 0x%08X 0x%08X 0x%08X 0x%08X 0x%08X %-8s %c %c %s\r\n",
ptr->allocationNumber,
(unsigned int) ptr->reportedAddress, ptr->reportedSize,
(unsigned int) ptr->actualAddress, ptr->actualSize,
m_calcUnused(ptr),
allocationTypes[ptr->allocationType],
ptr->breakOnDealloc ? 'Y':'N',
ptr->breakOnRealloc ? 'Y':'N',
ownerString(ptr->sourceFile, ptr->sourceLine, ptr->sourceFunc));
ptr = ptr->next;
}
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
static void dumpLeakReport()
{
// Open the report file
FILE *fp = fopen("memleaks.log", "w+b");
// If you hit this assert, then the memory report generator is unable to log information to a file (can't open the file for
// some reason.)
m_assert(fp);
if (!fp) return;
// Any leaks?
// Header
static char timeString[25];
memset(timeString, 0, sizeof(timeString));
time_t t = time(NULL);
struct tm *tme = localtime(&t);
fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
fprintf(fp, "| Memory leak report for: %02d/%02d/%04d %02d:%02d:%02d |\r\n", tme->tm_mon + 1, tme->tm_mday, tme->tm_year + 1900, tme->tm_hour, tme->tm_min, tme->tm_sec);
fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
fprintf(fp, "\r\n");
fprintf(fp, "\r\n");
if (stats.totalAllocUnitCount)
{
fprintf(fp, "%d memory leak%s found:\r\n", stats.totalAllocUnitCount, stats.totalAllocUnitCount == 1 ? "":"s");
}
else
{
fprintf(fp, "Congratulations! No memory leaks found!\r\n");
// We can finally free up our own memory allocations
if (reservoirBuffer)
{
for (unsigned int i = 0; i < reservoirBufferSize; i++)
{
free(reservoirBuffer[i]);
}
free(reservoirBuffer);
reservoirBuffer = 0;
reservoirBufferSize = 0;
reservoir = NULL;
}
}
fprintf(fp, "\r\n");
if (stats.totalAllocUnitCount)
{
dumpAllocations(fp);
}
fclose(fp);
}
// ---------------------------------------------------------------------------------------------------------------------------------
// We use a static class to let us know when we're in the midst of static deinitialization
// ---------------------------------------------------------------------------------------------------------------------------------
class MemStaticTimeTracker
{
public:
MemStaticTimeTracker() {doCleanupLogOnFirstRun();}
~MemStaticTimeTracker() {staticDeinitTime = true; dumpLeakReport();}
};
static MemStaticTimeTracker mstt;
// ---------------------------------------------------------------------------------------------------------------------------------
// -DOC- Flags & options -- Call these routines to enable/disable the following options
// ---------------------------------------------------------------------------------------------------------------------------------
bool &m_alwaysValidateAll()
{
// Force a validation of all allocation units each time we enter this software
return alwaysValidateAll;
}
// ---------------------------------------------------------------------------------------------------------------------------------
bool &m_alwaysLogAll()
{
// Force a log of every allocation & deallocation into memory.log
return alwaysLogAll;
}
// ---------------------------------------------------------------------------------------------------------------------------------
bool &m_alwaysWipeAll()
{
// Force this software to always wipe memory with a pattern when it is being allocated/dallocated
return alwaysWipeAll;
}
// ---------------------------------------------------------------------------------------------------------------------------------
bool &m_randomeWipe()
{
// Force this software to use a random pattern when wiping memory -- good for stress testing
return randomWipe;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// -DOC- Simply call this routine with the address of an allocated block of RAM, to cause it to force a breakpoint when it is
// reallocated.
// ---------------------------------------------------------------------------------------------------------------------------------
bool &m_breakOnRealloc(void *reportedAddress)
{
// Locate the existing allocation unit
sAllocUnit *au = findAllocUnit(reportedAddress);
// If you hit this assert, you tried to set a breakpoint on reallocation for an address that doesn't exist. Interrogate the
// stack frame or the variable 'au' to see which allocation this is.
m_assert(au != NULL);
// If you hit this assert, you tried to set a breakpoint on reallocation for an address that wasn't allocated in a way that
// is compatible with reallocation.
m_assert(au->allocationType == m_alloc_malloc ||
au->allocationType == m_alloc_calloc ||
au->allocationType == m_alloc_realloc);
return au->breakOnRealloc;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// -DOC- Simply call this routine with the address of an allocated block of RAM, to cause it to force a breakpoint when it is
// deallocated.
// ---------------------------------------------------------------------------------------------------------------------------------
bool &m_breakOnDealloc(void *reportedAddress)
{
// Locate the existing allocation unit
sAllocUnit *au = findAllocUnit(reportedAddress);
// If you hit this assert, you tried to set a breakpoint on deallocation for an address that doesn't exist. Interrogate the
// stack frame or the variable 'au' to see which allocation this is.
m_assert(au != NULL);
return au->breakOnDealloc;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// -DOC- When tracking down a difficult bug, use this routine to force a breakpoint on a specific allocation count
// ---------------------------------------------------------------------------------------------------------------------------------
void m_breakOnAllocation(unsigned int count)
{
breakOnAllocationCount = count;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// Used by the macros
// ---------------------------------------------------------------------------------------------------------------------------------
void m_setOwner(const char *file, const unsigned int line, const char *func)
{
sourceFile = file;
sourceLine = line;
sourceFunc = func;
}
// ---------------------------------------------------------------------------------------------------------------------------------
// Global new/new[]
//
// These are the standard new/new[] operators. They are merely interface functions that operate like normal new/new[], but use our
// memory tracking routines.
// ---------------------------------------------------------------------------------------------------------------------------------
void *operator new(size_t reportedSize)
{
#ifdef TEST_MEMORY_MANAGER
log("ENTER: new");
#endif
// ANSI says: allocation requests of 0 bytes will still return a valid value
if (reportedSize == 0) reportedSize = 1;
// ANSI says: loop continuously because the error handler could possibly free up some memory
for(;;)
{
// Try the allocation
void *ptr = m_allocator(sourceFile, sourceLine, sourceFunc, m_alloc_new, reportedSize);
if (ptr)
{
#ifdef TEST_MEMORY_MANAGER
log("EXIT : new");
#endif
return ptr;
}
// There isn't a way to determine the new handler, except through setting it. So we'll just set it to NULL, then
// set it back again.
std::new_handler nh = std::set_new_handler(0);
std::set_new_handler(nh);
// If there is an error handler, call it
if (nh)
{
(*nh)();
}
// Otherwise, throw the exception
else
{
#ifdef TEST_MEMORY_MANAGER
log("EXIT : new");
#endif
throw std::bad_alloc();
}
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
void *operator new[](size_t reportedSize)
{
#ifdef TEST_MEMORY_MANAGER
log("ENTER: new[]");
#endif
// The ANSI standard says that allocation requests of 0 bytes will still return a valid value
if (reportedSize == 0) reportedSize = 1;
// ANSI says: loop continuously because the error handler could possibly free up some memory
for(;;)
{
// Try the allocation
void *ptr = m_allocator(sourceFile, sourceLine, sourceFunc, m_alloc_new_array, reportedSize);
if (ptr)
{
#ifdef TEST_MEMORY_MANAGER
log("EXIT : new[]");
#endif
return ptr;
}
// There isn't a way to determine the new handler, except through setting it. So we'll just set it to NULL, then
// set it back again.
std::new_handler nh = std::set_new_handler(0);
std::set_new_handler(nh);
// If there is an error handler, call it
if (nh)
{
(*nh)();
}
// Otherwise, throw the exception
else
{
#ifdef TEST_MEMORY_MANAGER
log("EXIT : new[]");
#endif
throw std::bad_alloc();
}
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
// Other global new/new[]
//
// These are the standard new/new[] operators as used by Microsoft's memory tracker. We don't want them interfering with our memory
// tracking efforts. Like the previous versions, these are merely interface functions that operate like normal new/new[], but use
// our memory tracking routines.
// ---------------------------------------------------------------------------------------------------------------------------------
void *operator new(size_t reportedSize, const char *sourceFile, int sourceLine)
{
#ifdef TEST_MEMORY_MANAGER
log("ENTER: new");
#endif
// The ANSI standard says that allocation requests of 0 bytes will still return a valid value
if (reportedSize == 0) reportedSize = 1;
// ANSI says: loop continuously because the error handler could possibly free up some memory
for(;;)
{
// Try the allocation
void *ptr = m_allocator(sourceFile, sourceLine, "??", m_alloc_new, reportedSize);
if (ptr)
{
#ifdef TEST_MEMORY_MANAGER
log("EXIT : new");
#endif
return ptr;
}
// There isn't a way to determine the new handler, except through setting it. So we'll just set it to NULL, then
// set it back again.
std::new_handler nh = std::set_new_handler(0);
std::set_new_handler(nh);
// If there is an error handler, call it
if (nh)
{
(*nh)();
}
// Otherwise, throw the exception
else
{
#ifdef TEST_MEMORY_MANAGER
log("EXIT : new");
#endif
throw std::bad_alloc();
}
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
void *operator new[](size_t reportedSize, const char *sourceFile, int sourceLine)
{
#ifdef TEST_MEMORY_MANAGER
log("ENTER: new[]");
#endif
// The ANSI standard says that allocation requests of 0 bytes will still return a valid value
if (reportedSize == 0) reportedSize = 1;
// ANSI says: loop continuously because the error handler could possibly free up some memory
for(;;)
{
// Try the allocation
void *ptr = m_allocator(sourceFile, sourceLine, "??", m_alloc_new_array, reportedSize);
if (ptr)
{
#ifdef TEST_MEMORY_MANAGER
log("EXIT : new[]");
#endif
return ptr;
}
// There isn't a way to determine the new handler, except through setting it. So we'll just set it to NULL, then
// set it back again.
std::new_handler nh = std::set_new_handler(0);
std::set_new_handler(nh);
// If there is an error handler, call it
if (nh)
{
(*nh)();
}
// Otherwise, throw the exception
else
{
#ifdef TEST_MEMORY_MANAGER
log("EXIT : new[]");
#endif
throw std::bad_alloc();
}
}
}
// ---------------------------------------------------------------------------------------------------------------------------------
// Global delete/delete[]
//
// These are the standard delete/delete[] operators. They are merely interface functions that operate like normal delete/delete[],
// but use our memory tracking routines.
// ---------------------------------------------------------------------------------------------------------------------------------
void operator delete(void *reportedAddress)
{
#ifdef TEST_MEMORY_MANAGER
log("ENTER: delete");
#endif
// ANSI says: delete & delete[] allow NULL pointers (they do nothing)
if (!reportedAddress) return;
m_deallocator(sourceFile, sourceLine, sourceFunc, m_alloc_delete, reportedAddress);
#ifdef TEST_MEMORY_MANAGER
log("EXIT : delete");
#endif
}
// ---------------------------------------------------------------------------------------------------------------------------------
void operator delete[](void *reportedAddress)
{
#ifdef TEST_MEMORY_MANAGER
log("ENTER: delete[]");
#endif
// ANSI says: delete & delete[] allow NULL pointers (they do nothing)
if (!reportedAddress) return;
m_deallocator(sourceFile, sourceLine, sourceFunc, m_alloc_delete_array, reportedAddress);
#ifdef TEST_MEMORY_MANAGER
log("EXIT : delete[]");
#endif
}
// ---------------------------------------------------------------------------------------------------------------------------------
// Allocate memory and track it
// ---------------------------------------------------------------------------------------------------------------------------------
void *m_allocator(const char *sourceFile, const unsigned int sourceLine, const char *sourceFunc, const unsigned int allocationType, const size_t reportedSize)
{
try
{
#ifdef TEST_MEMORY_MANAGER
log("ENTER: m_allocator()");
#endif
// Increase our allocation count
currentAllocationCount++;
// Log the request
if (alwaysLogAll) log("%05d %-40s %8s : %s", currentAllocationCount, ownerString(sourceFile, sourceLine, sourceFunc), allocationTypes[allocationType], memorySizeString(reportedSize));
// If you hit this assert, you requested a breakpoint on a specific allocation count
m_assert(currentAllocationCount != breakOnAllocationCount);
// If necessary, grow the reservoir of unused allocation units
if (!reservoir)
{
// Allocate 256 reservoir elements
reservoir = (sAllocUnit *) malloc(sizeof(sAllocUnit) * 256);
// If you hit this assert, then the memory manager failed to allocate internal memory for tracking the
// allocations
m_assert(reservoir != NULL);
// Danger Will Robinson!
if (reservoir == NULL) throw "Unable to allocate RAM for internal memory tracking data";
// Build a linked-list of the elements in our reservoir
memset(reservoir, 0, sizeof(sAllocUnit) * 256);
for (unsigned int i = 0; i < 256 - 1; i++)
{
reservoir[i].next = &reservoir[i+1];
}
// Add this address to our reservoirBuffer so we can free it later
sAllocUnit **temp = (sAllocUnit **) realloc(reservoirBuffer, (reservoirBufferSize + 1) * sizeof(sAllocUnit *));
m_assert(temp);
if (temp)
{
reservoirBuffer = temp;
reservoirBuffer[reservoirBufferSize++] = reservoir;
}
}
// Logical flow says this should never happen...
m_assert(reservoir != NULL);
// Grab a new allocaton unit from the front of the reservoir
sAllocUnit *au = reservoir;
reservoir = au->next;
// Populate it with some real data
memset(au, 0, sizeof(sAllocUnit));
au->actualSize = calculateActualSize(reportedSize);
#ifdef RANDOM_FAILURE
double a = rand();
double b = RAND_MAX / 100.0 * RANDOM_FAILURE;
if (a > b)
{
au->actualAddress = malloc(au->actualSize);
}
else
{
log("!Random faiure!");
au->actualAddress = NULL;
}
#else
au->actualAddress = malloc(au->actualSize);
#endif
au->reportedSize = reportedSize;
au->reportedAddress = calculateReportedAddress(au->actualAddress);
au->allocationType = allocationType;
au->sourceLine = sourceLine;
au->allocationNumber = currentAllocationCount;
if (sourceFile) strncpy(au->sourceFile, sourceFileStripper(sourceFile), sizeof(au->sourceFile) - 1);
else strcpy (au->sourceFile, "??");
if (sourceFunc) strncpy(au->sourceFunc, sourceFunc, sizeof(au->sourceFunc) - 1);
else strcpy (au->sourceFunc, "??");
// We don't want to assert with random failures, because we want the application to deal with them.
#ifndef RANDOM_FAILURE
// If you hit this assert, then the requested allocation simply failed (you're out of memory.) Interrogate the
// variable 'au' or the stack frame to see what you were trying to do.
m_assert(au->actualAddress != NULL);
#endif
if (au->actualAddress == NULL)