]> git.jsancho.org Git - lugaru.git/blob - Source/mmgr.cpp
25ac363541382a4b8b40f08bfe3b5977fc1eb0e3
[lugaru.git] / Source / mmgr.cpp
1 // ---------------------------------------------------------------------------------------------------------------------------------
2 //                                                      
3 //                                                      
4 //  _ __ ___  _ __ ___   __ _ _ __      ___ _ __  _ __  
5 // | '_ ` _ \| '_ ` _ \ / _` | '__|    / __| '_ \| '_ \ 
6 // | | | | | | | | | | | (_| | |    _ | (__| |_) | |_) |
7 // |_| |_| |_|_| |_| |_|\__, |_|   (_) \___| .__/| .__/ 
8 //                       __/ |             | |   | |    
9 //                      |___/              |_|   |_|    
10 //
11 // Memory manager & tracking software
12 //
13 // Best viewed with 8-character tabs and (at least) 132 columns
14 //
15 // ---------------------------------------------------------------------------------------------------------------------------------
16 //
17 // Restrictions & freedoms pertaining to usage and redistribution of this software:
18 //
19 //  * This software is 100% free
20 //  * If you use this software (in part or in whole) you must credit the author.
21 //  * This software may not be re-distributed (in part or in whole) in a modified
22 //    form without clear documentation on how to obtain a copy of the original work.
23 //  * You may not use this software to directly or indirectly cause harm to others.
24 //  * This software is provided as-is and without warrantee. Use at your own risk.
25 //
26 // For more information, visit HTTP://www.FluidStudios.com
27 //
28 // ---------------------------------------------------------------------------------------------------------------------------------
29 // Originally created on 12/22/2000 by Paul Nettle
30 //
31 // Copyright 2000, Fluid Studios, Inc., all rights reserved.
32 // ---------------------------------------------------------------------------------------------------------------------------------
33 //
34 // !!IMPORTANT!!
35 //
36 // This software is self-documented with periodic comments. Before you start using this software, perform a search for the string
37 // "-DOC-" to locate pertinent information about how to use this software.
38 //
39 // You are also encouraged to read the comment blocks throughout this source file. They will help you understand how this memory
40 // tracking software works, so you can better utilize it within your applications.
41 //
42 // NOTES:
43 //
44 // 1. If you get compiler errors having to do with set_new_handler, then go through this source and search/replace
45 //    "std::set_new_handler" with "set_new_handler".
46 //
47 // 2. This code purposely uses no external routines that allocate RAM (other than the raw allocation routines, such as malloc). We
48 //    do this because we want this to be as self-contained as possible. As an example, we don't use assert, because when running
49 //    under WIN32, the assert brings up a dialog box, which allocates RAM. Doing this in the middle of an allocation would be bad.
50 //
51 // 3. When trying to override new/delete under MFC (which has its own version of global new/delete) the linker will complain. In
52 //    order to fix this error, use the compiler option: /FORCE, which will force it to build an executable even with linker errors.
53 //    Be sure to check those errors each time you compile, otherwise, you may miss a valid linker error.
54 //
55 // 4. If you see something that looks odd to you or seems like a strange way of going about doing something, then consider that this
56 //    code was carefully thought out. If something looks odd, then just assume I've got a good reason for doing it that way (an
57 //    example is the use of the class MemStaticTimeTracker.)
58 //
59 // 5. With MFC applications, you will need to comment out any occurance of "#define new DEBUG_NEW" from all source files.
60 //
61 // 6. Include file dependencies are _very_important_ for getting the MMGR to integrate nicely into your application. Be careful if
62 //    you're including standard includes from within your own project inclues; that will break this very specific dependency order. 
63 //    It should look like this:
64 //
65 //              #include <stdio.h>   // Standard includes MUST come first
66 //              #include <stdlib.h>  //
67 //              #include <streamio>  //
68 //
69 //              #include "mmgr.h"    // mmgr.h MUST come next
70 //
71 //              #include "myfile1.h" // Project includes MUST come last
72 //              #include "myfile2.h" //
73 //              #include "myfile3.h" //
74 //
75 // ---------------------------------------------------------------------------------------------------------------------------------
76
77 #include <iostream>
78 #include <stdio.h>
79 #include <stdlib.h>
80 #include <assert.h>
81 #include <string.h>
82 #include <time.h>
83 #include <stdarg.h>
84 #include <new>
85
86 #ifndef WIN32
87 #include <unistd.h>
88 #endif
89
90 #include "mmgr.h"
91
92 // ---------------------------------------------------------------------------------------------------------------------------------
93 // -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
94 // very good reasons... like making bugs obvious as early as possible.) Some people may be inclined to remove this memory tracking
95 // software if it causes crashes that didn't exist previously. In reality, these new crashes are the BEST reason for using this
96 // software!
97 //
98 // Whether this software causes your application to crash, or if it reports errors, you need to be able to TRUST this software. To
99 // this end, you are given some very simple debugging tools.
100 // 
101 // The quickest way to locate problems is to enable the STRESS_TEST macro (below.) This should catch 95% of the crashes before they
102 // occur by validating every allocation each time this memory manager performs an allocation function. If that doesn't work, keep
103 // reading...
104 //
105 // If you enable the TEST_MEMORY_MANAGER #define (below), this memory manager will log an entry in the memory.log file each time it
106 // enters and exits one of its primary allocation handling routines. Each call that succeeds should place an "ENTER" and an "EXIT"
107 // into the log. If the program crashes within the memory manager, it will log an "ENTER", but not an "EXIT". The log will also
108 // report the name of the routine.
109 //
110 // Just because this memory manager crashes does not mean that there is a bug here! First, an application could inadvertantly damage
111 // the heap, causing malloc(), realloc() or free() to crash. Also, an application could inadvertantly damage some of the memory used
112 // by this memory tracking software, causing it to crash in much the same way that a damaged heap would affect the standard
113 // allocation routines.
114 //
115 // 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
116 // crashing. You can do this by adding log() entries throughout the routine that crashes, repeating this process until you narrow
117 // 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
118 // bother contacting me, your application has damaged the heap. You can help find the culprit in your code by enabling the
119 // STRESS_TEST macro (below.)
120 //
121 // If you truely suspect a bug in this memory manager (and you had better be sure about it! :) you can contact me at
122 // midnight@FluidStudios.com. Before you do, however, check for a newer version at:
123 //
124 //      http://www.FluidStudios.com/publications.html
125 //
126 // When using this debugging aid, make sure that you are NOT setting the alwaysLogAll variable on, otherwise the log could be
127 // cluttered and hard to read.
128 // ---------------------------------------------------------------------------------------------------------------------------------
129
130 //#define       TEST_MEMORY_MANAGER
131
132 // ---------------------------------------------------------------------------------------------------------------------------------
133 // -DOC- Enable this sucker if you really want to stress-test your app's memory usage, or to help find hard-to-find bugs
134 // ---------------------------------------------------------------------------------------------------------------------------------
135
136 //#define       STRESS_TEST
137
138 // ---------------------------------------------------------------------------------------------------------------------------------
139 // -DOC- Enable this sucker if you want to stress-test your app's error-handling. Set RANDOM_FAIL to the percentage of failures you
140 //       want to test with (0 = none, >100 = all failures).
141 // ---------------------------------------------------------------------------------------------------------------------------------
142
143 //#define       RANDOM_FAILURE 10.0
144
145 // ---------------------------------------------------------------------------------------------------------------------------------
146 // -DOC- Locals -- modify these flags to suit your needs
147 // ---------------------------------------------------------------------------------------------------------------------------------
148
149 #ifdef  STRESS_TEST
150 static  const   unsigned int    hashBits               = 12;
151 static          bool            randomWipe             = true;
152 static          bool            alwaysValidateAll      = true;
153 static          bool            alwaysLogAll           = true;
154 static          bool            alwaysWipeAll          = true;
155 static          bool            cleanupLogOnFirstRun   = true;
156 static  const   unsigned int    paddingSize            = 1024; // An extra 8K per allocation!
157 #else
158 static  const   unsigned int    hashBits               = 12;
159 static          bool            randomWipe             = false;
160 static          bool            alwaysValidateAll      = false;
161 static          bool            alwaysLogAll           = false;
162 static          bool            alwaysWipeAll          = true;
163 static          bool            cleanupLogOnFirstRun   = true;
164 static  const   unsigned int    paddingSize            = 4;
165 #endif
166
167 // ---------------------------------------------------------------------------------------------------------------------------------
168 // We define our own assert, because we don't want to bring up an assertion dialog, since that allocates RAM. Our new assert
169 // simply declares a forced breakpoint.
170 //
171 // The BEOS assert added by Arvid Norberg <arvid@iname.com>.
172 // ---------------------------------------------------------------------------------------------------------------------------------
173
174 #ifdef  WIN32
175         #ifdef  _DEBUG
176         #define m_assert(x) if ((x) == false) __asm { int 3 }
177         #else
178         #define m_assert(x) {}
179         #endif
180 #elif defined(__BEOS__)
181         #ifdef DEBUG
182                 extern void debugger(const char *message);
183                 #define m_assert(x) if ((x) == false) debugger("mmgr: assert failed")
184         #else
185                 #define m_assert(x) {}
186         #endif
187 #else   // Linux uses assert, which we can use safely, since it doesn't bring up a dialog within the program.
188         #define m_assert(cond) assert(cond)
189 #endif
190
191 // ---------------------------------------------------------------------------------------------------------------------------------
192 // Here, we turn off our macros because any place in this source file where the word 'new' or the word 'delete' (etc.)
193 // appear will be expanded by the macro. So to avoid problems using them within this source file, we'll just #undef them.
194 // ---------------------------------------------------------------------------------------------------------------------------------
195
196 #undef  new
197 #undef  delete
198 #undef  malloc
199 #undef  calloc
200 #undef  realloc
201 #undef  free
202
203 // ---------------------------------------------------------------------------------------------------------------------------------
204 // Defaults for the constants & statics in the MemoryManager class
205 // ---------------------------------------------------------------------------------------------------------------------------------
206
207 const           unsigned int    m_alloc_unknown        = 0;
208 const           unsigned int    m_alloc_new            = 1;
209 const           unsigned int    m_alloc_new_array      = 2;
210 const           unsigned int    m_alloc_malloc         = 3;
211 const           unsigned int    m_alloc_calloc         = 4;
212 const           unsigned int    m_alloc_realloc        = 5;
213 const           unsigned int    m_alloc_delete         = 6;
214 const           unsigned int    m_alloc_delete_array   = 7;
215 const           unsigned int    m_alloc_free           = 8;
216
217 // ---------------------------------------------------------------------------------------------------------------------------------
218 // -DOC- Get to know these values. They represent the values that will be used to fill unused and deallocated RAM.
219 // ---------------------------------------------------------------------------------------------------------------------------------
220
221 static          unsigned int    prefixPattern          = 0xbaadf00d; // Fill pattern for bytes preceeding allocated blocks
222 static          unsigned int    postfixPattern         = 0xdeadc0de; // Fill pattern for bytes following allocated blocks
223 static          unsigned int    unusedPattern          = 0xfeedface; // Fill pattern for freshly allocated blocks
224 static          unsigned int    releasedPattern        = 0xdeadbeef; // Fill pattern for deallocated blocks
225
226 // ---------------------------------------------------------------------------------------------------------------------------------
227 // Other locals
228 // ---------------------------------------------------------------------------------------------------------------------------------
229
230 static  const   unsigned int    hashSize               = 1 << hashBits;
231 static  const   char            *allocationTypes[]     = {"Unknown",
232                                                           "new",     "new[]",  "malloc",   "calloc",
233                                                           "realloc", "delete", "delete[]", "free"};
234 static          sAllocUnit      *hashTable[hashSize];
235 static          sAllocUnit      *reservoir;
236 static          unsigned int    currentAllocationCount = 0;
237 static          unsigned int    breakOnAllocationCount = 0;
238 static          sMStats         stats;
239 static  const   char            *sourceFile            = "??";
240 static  const   char            *sourceFunc            = "??";
241 static          unsigned int    sourceLine             = 0;
242 static          bool            staticDeinitTime       = false;
243 static          sAllocUnit      **reservoirBuffer      = NULL;
244 static          unsigned int    reservoirBufferSize    = 0;
245 static const    char            *memoryLogFile         = "memory.log";
246 static const    char            *memoryLeakLogFile     = "memleaks.log";
247 static          void            doCleanupLogOnFirstRun();
248
249 // ---------------------------------------------------------------------------------------------------------------------------------
250 // Local functions only
251 // ---------------------------------------------------------------------------------------------------------------------------------
252
253 static  void    log(const char *format, ...)
254 {
255         // Cleanup the log?
256
257         if (cleanupLogOnFirstRun) doCleanupLogOnFirstRun();
258
259         // Build the buffer
260
261         static char buffer[2048];
262         va_list ap;
263         va_start(ap, format);
264         vsprintf(buffer, format, ap);
265         va_end(ap);
266
267         // Open the log file
268
269         FILE    *fp = fopen(memoryLogFile, "ab");
270
271         // If you hit this assert, then the memory logger is unable to log information to a file (can't open the file for some
272         // reason.) You can interrogate the variable 'buffer' to see what was supposed to be logged (but won't be.)
273         m_assert(fp);
274
275         if (!fp) return;
276
277         // Spit out the data to the log
278
279         fprintf(fp, "%s\r\n", buffer);
280         fclose(fp);
281 }
282
283 // ---------------------------------------------------------------------------------------------------------------------------------
284
285 static  void    doCleanupLogOnFirstRun()
286 {
287         if (cleanupLogOnFirstRun)
288         {
289                 unlink(memoryLogFile);
290                 cleanupLogOnFirstRun = false;
291
292                 // Print a header for the log
293
294                 time_t  t = time(NULL);
295                 log("--------------------------------------------------------------------------------");
296                 log("");
297                 log("      %s - Memory logging file created on %s", memoryLogFile, asctime(localtime(&t)));
298                 log("--------------------------------------------------------------------------------");
299                 log("");
300                 log("This file contains a log of all memory operations performed during the last run.");
301                 log("");
302                 log("Interrogate this file to track errors or to help track down memory-related");
303                 log("issues. You can do this by tracing the allocations performed by a specific owner");
304                 log("or by tracking a specific address through a series of allocations and");
305                 log("reallocations.");
306                 log("");
307                 log("There is a lot of useful information here which, when used creatively, can be");
308                 log("extremely helpful.");
309                 log("");
310                 log("Note that the following guides are used throughout this file:");
311                 log("");
312                 log("   [!] - Error");
313                 log("   [+] - Allocation");
314                 log("   [~] - Reallocation");
315                 log("   [-] - Deallocation");
316                 log("   [I] - Generic information");
317                 log("   [F] - Failure induced for the purpose of stress-testing your application");
318                 log("   [D] - Information used for debugging this memory manager");
319                 log("");
320                 log("...so, to find all errors in the file, search for \"[!]\"");
321                 log("");
322                 log("--------------------------------------------------------------------------------");
323         }
324 }
325
326 // ---------------------------------------------------------------------------------------------------------------------------------
327
328 static  const char      *sourceFileStripper(const char *sourceFile)
329 {
330         char    *ptr = strrchr(sourceFile, '\\');
331         if (ptr) return ptr + 1;
332         ptr = strrchr(sourceFile, '/');
333         if (ptr) return ptr + 1;
334         return sourceFile;
335 }
336
337 // ---------------------------------------------------------------------------------------------------------------------------------
338
339 static  const char      *ownerString(const char *sourceFile, const unsigned int sourceLine, const char *sourceFunc)
340 {
341         static  char    str[90];
342         memset(str, 0, sizeof(str));
343         sprintf(str, "%s(%05d)::%s", sourceFileStripper(sourceFile), sourceLine, sourceFunc);
344         return str;
345 }
346
347 // ---------------------------------------------------------------------------------------------------------------------------------
348
349 static  const char      *insertCommas(unsigned int value)
350 {
351         static  char    str[30];
352         memset(str, 0, sizeof(str));
353
354         sprintf(str, "%u", value);
355         if (strlen(str) > 3)
356         {
357                 memmove(&str[strlen(str)-3], &str[strlen(str)-4], 4);
358                 str[strlen(str) - 4] = ',';
359         }
360         if (strlen(str) > 7)
361         {
362                 memmove(&str[strlen(str)-7], &str[strlen(str)-8], 8);
363                 str[strlen(str) - 8] = ',';
364         }
365         if (strlen(str) > 11)
366         {
367                 memmove(&str[strlen(str)-11], &str[strlen(str)-12], 12);
368                 str[strlen(str) - 12] = ',';
369         }
370
371         return str;
372 }
373
374 // ---------------------------------------------------------------------------------------------------------------------------------
375
376 static  const char      *memorySizeString(unsigned long size)
377 {
378         static  char    str[90];
379              if (size > (1024*1024))    sprintf(str, "%10s (%7.2fM)", insertCommas(size), static_cast<float>(size) / (1024.0f * 1024.0f));
380         else if (size > 1024)           sprintf(str, "%10s (%7.2fK)", insertCommas(size), static_cast<float>(size) / 1024.0f);
381         else                            sprintf(str, "%10s bytes     ", insertCommas(size));
382         return str;
383 }
384
385 // ---------------------------------------------------------------------------------------------------------------------------------
386
387 static  sAllocUnit      *findAllocUnit(const void *reportedAddress)
388 {
389         // Just in case...
390         m_assert(reportedAddress != NULL);
391
392         // Use the address to locate the hash index. Note that we shift off the lower four bits. This is because most allocated
393         // addresses will be on four-, eight- or even sixteen-byte boundaries. If we didn't do this, the hash index would not have
394         // very good coverage.
395
396         unsigned int    hashIndex = (reinterpret_cast<unsigned int>(const_cast<void *>(reportedAddress)) >> 4) & (hashSize - 1);
397         sAllocUnit      *ptr = hashTable[hashIndex];
398         while(ptr)
399         {
400                 if (ptr->reportedAddress == reportedAddress) return ptr;
401                 ptr = ptr->next;
402         }
403
404         return NULL;
405 }
406
407 // ---------------------------------------------------------------------------------------------------------------------------------
408
409 static  size_t  calculateActualSize(const size_t reportedSize)
410 {
411         // 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
412         // 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
413         // 8 bytes, which means an int can actually be larger than a long.)
414
415         return reportedSize + paddingSize * sizeof(long) * 2;
416 }
417
418 // ---------------------------------------------------------------------------------------------------------------------------------
419
420 static  size_t  calculateReportedSize(const size_t actualSize)
421 {
422         // 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
423         // 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
424         // 8 bytes, which means an int can actually be larger than a long.)
425
426         return actualSize - paddingSize * sizeof(long) * 2;
427 }
428
429 // ---------------------------------------------------------------------------------------------------------------------------------
430
431 static  void    *calculateReportedAddress(const void *actualAddress)
432 {
433         // We allow this...
434
435         if (!actualAddress) return NULL;
436
437         // JUst account for the padding
438
439         return reinterpret_cast<void *>(const_cast<char *>(reinterpret_cast<const char *>(actualAddress) + sizeof(long) * paddingSize));
440 }
441
442 // ---------------------------------------------------------------------------------------------------------------------------------
443
444 static  void    wipeWithPattern(sAllocUnit *allocUnit, unsigned long pattern, const unsigned int originalReportedSize = 0)
445 {
446         // 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
447         // crash in a differnt place each time, so we specifically DO NOT call srand. If, by chance your program calls srand(),
448         // you may wish to disable that when running with a random wipe test. This will make any crashes more consistent so they
449         // can be tracked down easier.
450
451         if (randomWipe)
452         {
453                 pattern = ((rand() & 0xff) << 24) | ((rand() & 0xff) << 16) | ((rand() & 0xff) << 8) | (rand() & 0xff);
454         }
455
456         // -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
457         // product. So uncomment the following line for releases.
458         //
459         // Note that the "alwaysWipeAll" should be turned on for this to have effect, otherwise it won't do much good. But we'll
460         // leave it this way (as an option) because this does slow things down.
461 //      pattern = 0;
462
463         // This part of the operation is optional
464
465         if (alwaysWipeAll && allocUnit->reportedSize > originalReportedSize)
466         {
467                 // Fill the bulk
468
469                 long    *lptr = reinterpret_cast<long *>(reinterpret_cast<char *>(allocUnit->reportedAddress) + originalReportedSize);
470                 int     length = static_cast<int>(allocUnit->reportedSize - originalReportedSize);
471                 int     i;
472                 for (i = 0; i < (length >> 2); i++, lptr++)
473                 {
474                         *lptr = pattern;
475                 }
476
477                 // Fill the remainder
478
479                 unsigned int    shiftCount = 0;
480                 char            *cptr = reinterpret_cast<char *>(lptr);
481                 for (i = 0; i < (length & 0x3); i++, cptr++, shiftCount += 8)
482                 {
483                         *cptr = static_cast<char>((pattern & (0xff << shiftCount)) >> shiftCount);
484                 }
485         }
486
487         // Write in the prefix/postfix bytes
488
489         long            *pre = reinterpret_cast<long *>(allocUnit->actualAddress);
490         long            *post = reinterpret_cast<long *>(reinterpret_cast<char *>(allocUnit->actualAddress) + allocUnit->actualSize - paddingSize * sizeof(long));
491         for (unsigned int i = 0; i < paddingSize; i++, pre++, post++)
492         {
493                 *pre = prefixPattern;
494                 *post = postfixPattern;
495         }
496 }
497
498 // ---------------------------------------------------------------------------------------------------------------------------------
499
500 static  void    dumpAllocations(FILE *fp)
501 {
502         fprintf(fp, "Alloc.   Addr       Size       Addr       Size                        BreakOn BreakOn              \r\n");
503         fprintf(fp, "Number Reported   Reported    Actual     Actual     Unused    Method  Dealloc Realloc Allocated by \r\n");
504         fprintf(fp, "------ ---------- ---------- ---------- ---------- ---------- -------- ------- ------- --------------------------------------------------- \r\n");
505
506
507         for (unsigned int i = 0; i < hashSize; i++)
508         {
509                 sAllocUnit *ptr = hashTable[i];
510                 while(ptr)
511                 {
512                         fprintf(fp, "%06d 0x%08X 0x%08X 0x%08X 0x%08X 0x%08X %-8s    %c       %c    %s\r\n",
513                                 ptr->allocationNumber,
514                                 reinterpret_cast<unsigned int>(ptr->reportedAddress), ptr->reportedSize,
515                                 reinterpret_cast<unsigned int>(ptr->actualAddress), ptr->actualSize,
516                                 m_calcUnused(ptr),
517                                 allocationTypes[ptr->allocationType],
518                                 ptr->breakOnDealloc ? 'Y':'N',
519                                 ptr->breakOnRealloc ? 'Y':'N',
520                                 ownerString(ptr->sourceFile, ptr->sourceLine, ptr->sourceFunc));
521                         ptr = ptr->next;
522                 }
523         }
524 }
525
526 // ---------------------------------------------------------------------------------------------------------------------------------
527
528 static  void    dumpLeakReport()
529 {
530         // Open the report file
531
532         FILE    *fp = fopen(memoryLeakLogFile, "w+b");
533
534         // If you hit this assert, then the memory report generator is unable to log information to a file (can't open the file for
535         // some reason.)
536         m_assert(fp);
537         if (!fp) return;
538
539         // Any leaks?
540
541         // Header
542
543         static  char    timeString[25];
544         memset(timeString, 0, sizeof(timeString));
545         time_t  t = time(NULL);
546         struct  tm *tme = localtime(&t);
547         fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
548         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);
549         fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
550         fprintf(fp, "\r\n");
551         fprintf(fp, "\r\n");
552         if (stats.totalAllocUnitCount)
553         {
554                 fprintf(fp, "%d memory leak%s found:\r\n", stats.totalAllocUnitCount, stats.totalAllocUnitCount == 1 ? "":"s");
555         }
556         else
557         {
558                 fprintf(fp, "Congratulations! No memory leaks found!\r\n");
559
560                 // We can finally free up our own memory allocations
561
562                 if (reservoirBuffer)
563                 {
564                         for (unsigned int i = 0; i < reservoirBufferSize; i++)
565                         {
566                                 free(reservoirBuffer[i]);
567                         }
568                         free(reservoirBuffer);
569                         reservoirBuffer = 0;
570                         reservoirBufferSize = 0;
571                         reservoir = NULL;
572                 }
573         }
574         fprintf(fp, "\r\n");
575
576         if (stats.totalAllocUnitCount)
577         {
578                 dumpAllocations(fp);
579         }
580
581         fclose(fp);
582 }
583
584 // ---------------------------------------------------------------------------------------------------------------------------------
585 // We use a static class to let us know when we're in the midst of static deinitialization
586 // ---------------------------------------------------------------------------------------------------------------------------------
587
588 class   MemStaticTimeTracker
589 {
590 public:
591         MemStaticTimeTracker() {doCleanupLogOnFirstRun();}
592         ~MemStaticTimeTracker() {staticDeinitTime = true; dumpLeakReport();}
593 };
594 static  MemStaticTimeTracker    mstt;
595
596 // ---------------------------------------------------------------------------------------------------------------------------------
597 // -DOC- Flags & options -- Call these routines to enable/disable the following options
598 // ---------------------------------------------------------------------------------------------------------------------------------
599
600 bool    &m_alwaysValidateAll()
601 {
602         // Force a validation of all allocation units each time we enter this software
603         return alwaysValidateAll;
604 }
605
606 // ---------------------------------------------------------------------------------------------------------------------------------
607
608 bool    &m_alwaysLogAll()
609 {
610         // Force a log of every allocation & deallocation into memory.log
611         return alwaysLogAll;
612 }
613
614 // ---------------------------------------------------------------------------------------------------------------------------------
615
616 bool    &m_alwaysWipeAll()
617 {
618         // Force this software to always wipe memory with a pattern when it is being allocated/dallocated
619         return alwaysWipeAll;
620 }
621
622 // ---------------------------------------------------------------------------------------------------------------------------------
623
624 bool    &m_randomeWipe()
625 {
626         // Force this software to use a random pattern when wiping memory -- good for stress testing
627         return randomWipe;
628 }
629
630 // ---------------------------------------------------------------------------------------------------------------------------------
631 // -DOC- Simply call this routine with the address of an allocated block of RAM, to cause it to force a breakpoint when it is
632 // reallocated.
633 // ---------------------------------------------------------------------------------------------------------------------------------
634
635 bool    &m_breakOnRealloc(void *reportedAddress)
636 {
637         // Locate the existing allocation unit
638
639         sAllocUnit      *au = findAllocUnit(reportedAddress);
640
641         // If you hit this assert, you tried to set a breakpoint on reallocation for an address that doesn't exist. Interrogate the
642         // stack frame or the variable 'au' to see which allocation this is.
643         m_assert(au != NULL);
644
645         // If you hit this assert, you tried to set a breakpoint on reallocation for an address that wasn't allocated in a way that
646         // is compatible with reallocation.
647         m_assert(au->allocationType == m_alloc_malloc ||
648                  au->allocationType == m_alloc_calloc ||
649                  au->allocationType == m_alloc_realloc);
650
651         return au->breakOnRealloc;
652 }
653
654 // ---------------------------------------------------------------------------------------------------------------------------------
655 // -DOC- Simply call this routine with the address of an allocated block of RAM, to cause it to force a breakpoint when it is
656 // deallocated.
657 // ---------------------------------------------------------------------------------------------------------------------------------
658
659 bool    &m_breakOnDealloc(void *reportedAddress)
660 {
661         // Locate the existing allocation unit
662
663         sAllocUnit      *au = findAllocUnit(reportedAddress);
664
665         // If you hit this assert, you tried to set a breakpoint on deallocation for an address that doesn't exist. Interrogate the
666         // stack frame or the variable 'au' to see which allocation this is.
667         m_assert(au != NULL);
668
669         return au->breakOnDealloc;
670 }
671
672 // ---------------------------------------------------------------------------------------------------------------------------------
673 // -DOC- When tracking down a difficult bug, use this routine to force a breakpoint on a specific allocation count
674 // ---------------------------------------------------------------------------------------------------------------------------------
675
676 void    m_breakOnAllocation(unsigned int count)
677 {
678         breakOnAllocationCount = count;
679 }
680
681 // ---------------------------------------------------------------------------------------------------------------------------------
682 // Used by the macros
683 // ---------------------------------------------------------------------------------------------------------------------------------
684
685 void    m_setOwner(const char *file, const unsigned int line, const char *func)
686 {
687         // You're probably wondering about this...
688         //
689         // It's important for this memory manager to primarily work with global new/delete in their original forms (i.e. with
690         // no extra parameters.) In order to do this, we use macros that call this function prior to operators new & delete. This
691         // is fine... usually. Here's what actually happens when you use this macro to delete an object:
692         //
693         // m_setOwner(__FILE__, __LINE__, __FUNCTION__) --> object::~object() --> delete
694         //
695         // Note that the compiler inserts a call to the object's destructor just prior to calling our overridden operator delete.
696         // But what happens when we delete an object whose destructor deletes another object, whose desctuctor deletes another
697         // object? Here's a diagram (indentation follows stack depth):
698         //
699         // m_setOwner(...) -> ~obj1()                          // original call to delete obj1
700         //     m_setOwner(...) -> ~obj2()                      // obj1's destructor deletes obj2
701         //         m_setOwner(...) -> ~obj3()                  // obj2's destructor deletes obj3
702         //             ...                                     // obj3's destructor just does some stuff
703         //         delete                                      // back in obj2's destructor, we call delete
704         //     delete                                          // back in obj1's destructor, we call delete
705         // delete                                              // back to our original call, we call delete
706         //
707         // Because m_setOwner() just sets up some static variables (below) it's important that each call to m_setOwner() and
708         // successive calls to new/delete alternate. However, in this case, three calls to m_setOwner() happen in succession
709         // followed by three calls to delete in succession (with a few calls to destructors mixed in for fun.) This means that
710         // only the final call to delete (in this chain of events) will have the proper reporting, and the first two in the chain
711         // will not have ANY owner-reporting information. The deletes will still work fine, we just won't know who called us.
712         //
713         // "Then build a stack, my friend!" you might think... but it's a very common thing that people will be working with third-
714         // party libraries (including MFC under Windows) which is not compiled with this memory manager's macros. In those cases,
715         // m_setOwner() is never called, and rightfully should not have the proper trace-back information. So if one of the
716         // destructors in the chain ends up being a call to a delete from a non-mmgr-compiled library, the stack will get confused.
717         //
718         // I've been unable to find a solution to this problem, but at least we can detect it and report the data before we
719         // lose it. That's what this is all about. It makes it somewhat confusing to read in the logs, but at least ALL the
720         // information is present...
721         //
722         // There's a caveat here... The compiler is not required to call operator delete if the value being deleted is NULL.
723         // In this case, any call to delete with a NULL will sill call m_setOwner(), which will make m_setOwner() think that
724         // there is a destructor chain becuase we setup the variables, but nothing gets called to clear them. Because of this
725         // we report a "Possible destructor chain".
726         //
727         // Thanks to J. Woznack (from Kodiak Interactive Software Studios -- www.kodiakgames.com) for pointing this out.
728
729         if (sourceLine && alwaysLogAll)
730         {
731                 log("[I] NOTE! Possible destructor chain: previous owner is %s", ownerString(sourceFile, sourceLine, sourceFunc));
732         }
733
734         // Okay... save this stuff off so we can keep track of the caller
735
736         sourceFile = file;
737         sourceLine = line;
738         sourceFunc = func;
739 }
740
741 // ---------------------------------------------------------------------------------------------------------------------------------
742
743 static  void    resetGlobals()
744 {
745         sourceFile = "??";
746         sourceLine = 0;
747         sourceFunc = "??";
748 }
749
750 // ---------------------------------------------------------------------------------------------------------------------------------
751 // Global new/new[]
752 //
753 // These are the standard new/new[] operators. They are merely interface functions that operate like normal new/new[], but use our
754 // memory tracking routines.
755 // ---------------------------------------------------------------------------------------------------------------------------------
756
757 void    *operator new(size_t reportedSize)
758 {
759         #ifdef TEST_MEMORY_MANAGER
760         log("[D] ENTER: new");
761         #endif
762
763         // Save these off...
764
765         const   char            *file = sourceFile;
766         const   unsigned int    line = sourceLine;
767         const   char            *func = sourceFunc;
768
769         // ANSI says: allocation requests of 0 bytes will still return a valid value
770
771         if (reportedSize == 0) reportedSize = 1;
772
773         // ANSI says: loop continuously because the error handler could possibly free up some memory
774
775         for(;;)
776         {
777                 // Try the allocation
778
779                 void    *ptr = m_allocator(file, line, func, m_alloc_new, reportedSize);
780                 if (ptr)
781                 {
782                         #ifdef TEST_MEMORY_MANAGER
783                         log("[D] EXIT : new");
784                         #endif
785                         return ptr;
786                 }
787
788                 // There isn't a way to determine the new handler, except through setting it. So we'll just set it to NULL, then
789                 // set it back again.
790
791                 std::new_handler        nh = std::set_new_handler(0);
792                 std::set_new_handler(nh);
793
794                 // If there is an error handler, call it
795
796                 if (nh)
797                 {
798                         (*nh)();
799                 }
800
801                 // Otherwise, throw the exception
802
803                 else
804                 {
805                         #ifdef TEST_MEMORY_MANAGER
806                         log("[D] EXIT : new");
807                         #endif
808                         throw std::bad_alloc();
809                 }
810         }
811 }
812
813 // ---------------------------------------------------------------------------------------------------------------------------------
814
815 void    *operator new[](size_t reportedSize)
816 {
817         #ifdef TEST_MEMORY_MANAGER
818         log("[D] ENTER: new[]");
819         #endif
820
821         // Save these off...
822
823         const   char            *file = sourceFile;
824         const   unsigned int    line = sourceLine;
825         const   char            *func = sourceFunc;
826
827         // The ANSI standard says that allocation requests of 0 bytes will still return a valid value
828
829         if (reportedSize == 0) reportedSize = 1;
830
831         // ANSI says: loop continuously because the error handler could possibly free up some memory
832
833         for(;;)
834         {
835                 // Try the allocation
836
837                 void    *ptr = m_allocator(file, line, func, m_alloc_new_array, reportedSize);
838                 if (ptr)
839                 {
840                         #ifdef TEST_MEMORY_MANAGER
841                         log("[D] EXIT : new[]");
842                         #endif
843                         return ptr;
844                 }
845
846                 // There isn't a way to determine the new handler, except through setting it. So we'll just set it to NULL, then
847                 // set it back again.
848
849                 std::new_handler        nh = std::set_new_handler(0);
850                 std::set_new_handler(nh);
851
852                 // If there is an error handler, call it
853
854                 if (nh)
855                 {
856                         (*nh)();
857                 }
858
859                 // Otherwise, throw the exception
860
861                 else
862                 {
863                         #ifdef TEST_MEMORY_MANAGER
864                         log("[D] EXIT : new[]");
865                         #endif
866                         throw std::bad_alloc();
867                 }
868         }
869 }
870
871 // ---------------------------------------------------------------------------------------------------------------------------------
872 // Other global new/new[]
873 //
874 // These are the standard new/new[] operators as used by Microsoft's memory tracker. We don't want them interfering with our memory
875 // tracking efforts. Like the previous versions, these are merely interface functions that operate like normal new/new[], but use
876 // our memory tracking routines.
877 // ---------------------------------------------------------------------------------------------------------------------------------
878
879 void    *operator new(size_t reportedSize, const char *sourceFile, int sourceLine)
880 {
881         #ifdef TEST_MEMORY_MANAGER
882         log("[D] ENTER: new");
883         #endif
884
885         // The ANSI standard says that allocation requests of 0 bytes will still return a valid value
886
887         if (reportedSize == 0) reportedSize = 1;
888
889         // ANSI says: loop continuously because the error handler could possibly free up some memory
890
891         for(;;)
892         {
893                 // Try the allocation
894
895                 void    *ptr = m_allocator(sourceFile, sourceLine, "??", m_alloc_new, reportedSize);
896                 if (ptr)
897                 {
898                         #ifdef TEST_MEMORY_MANAGER
899                         log("[D] EXIT : new");
900                         #endif
901                         return ptr;
902                 }
903
904                 // There isn't a way to determine the new handler, except through setting it. So we'll just set it to NULL, then
905                 // set it back again.
906
907                 std::new_handler        nh = std::set_new_handler(0);
908                 std::set_new_handler(nh);
909
910                 // If there is an error handler, call it
911
912                 if (nh)
913                 {
914                         (*nh)();
915                 }
916
917                 // Otherwise, throw the exception
918
919                 else
920                 {
921                         #ifdef TEST_MEMORY_MANAGER
922                         log("[D] EXIT : new");
923                         #endif
924                         throw std::bad_alloc();
925                 }
926         }
927 }
928
929 // ---------------------------------------------------------------------------------------------------------------------------------
930
931 void    *operator new[](size_t reportedSize, const char *sourceFile, int sourceLine)
932 {
933         #ifdef TEST_MEMORY_MANAGER
934         log("[D] ENTER: new[]");
935         #endif
936
937         // The ANSI standard says that allocation requests of 0 bytes will still return a valid value
938
939         if (reportedSize == 0) reportedSize = 1;
940
941         // ANSI says: loop continuously because the error handler could possibly free up some memory
942
943         for(;;)
944         {
945                 // Try the allocation
946
947                 void    *ptr = m_allocator(sourceFile, sourceLine, "??", m_alloc_new_array, reportedSize);
948                 if (ptr)
949                 {
950                         #ifdef TEST_MEMORY_MANAGER
951                         log("[D] EXIT : new[]");
952                         #endif
953                         return ptr;
954                 }
955
956                 // There isn't a way to determine the new handler, except through setting it. So we'll just set it to NULL, then
957                 // set it back again.
958
959                 std::new_handler        nh = std::set_new_handler(0);
960                 std::set_new_handler(nh);
961
962                 // If there is an error handler, call it
963
964                 if (nh)
965                 {
966                         (*nh)();
967                 }
968
969                 // Otherwise, throw the exception
970
971                 else
972                 {
973                         #ifdef TEST_MEMORY_MANAGER
974                         log("[D] EXIT : new[]");
975                         #endif
976                         throw std::bad_alloc();
977                 }
978         }
979 }
980
981 // ---------------------------------------------------------------------------------------------------------------------------------
982 // Global delete/delete[]
983 //
984 // These are the standard delete/delete[] operators. They are merely interface functions that operate like normal delete/delete[],
985 // but use our memory tracking routines.
986 // ---------------------------------------------------------------------------------------------------------------------------------
987
988 void    operator delete(void *reportedAddress)
989 {
990         #ifdef TEST_MEMORY_MANAGER
991         log("[D] ENTER: delete");
992         #endif
993
994         // ANSI says: delete & delete[] allow NULL pointers (they do nothing)
995
996         if (reportedAddress) m_deallocator(sourceFile, sourceLine, sourceFunc, m_alloc_delete, reportedAddress);
997         else if (alwaysLogAll) log("[-] ----- %8s of NULL                      by %s", allocationTypes[m_alloc_delete], ownerString(sourceFile, sourceLine, sourceFunc));
998
999         // Resetting the globals insures that if at some later time, somebody calls our memory manager from an unknown
1000         // source (i.e. they didn't include our H file) then we won't think it was the last allocation.
1001
1002         resetGlobals();
1003
1004         #ifdef TEST_MEMORY_MANAGER
1005         log("[D] EXIT : delete");
1006         #endif
1007 }
1008
1009 // ---------------------------------------------------------------------------------------------------------------------------------
1010
1011 void    operator delete[](void *reportedAddress)
1012 {
1013         #ifdef TEST_MEMORY_MANAGER
1014         log("[D] ENTER: delete[]");
1015         #endif
1016
1017         // ANSI says: delete & delete[] allow NULL pointers (they do nothing)
1018
1019         if (reportedAddress) m_deallocator(sourceFile, sourceLine, sourceFunc, m_alloc_delete_array, reportedAddress);
1020         else if (alwaysLogAll)
1021                 log("[-] ----- %8s of NULL                      by %s", allocationTypes[m_alloc_delete_array], ownerString(sourceFile, sourceLine, sourceFunc));
1022
1023         // Resetting the globals insures that if at some later time, somebody calls our memory manager from an unknown
1024         // source (i.e. they didn't include our H file) then we won't think it was the last allocation.
1025
1026         resetGlobals();
1027
1028         #ifdef TEST_MEMORY_MANAGER
1029         log("[D] EXIT : delete[]");
1030         #endif
1031 }
1032
1033 // ---------------------------------------------------------------------------------------------------------------------------------
1034 // Allocate memory and track it
1035 // ---------------------------------------------------------------------------------------------------------------------------------
1036
1037 void    *m_allocator(const char *sourceFile, const unsigned int sourceLine, const char *sourceFunc, const unsigned int allocationType, const size_t reportedSize)
1038 {
1039         try
1040         {
1041                 #ifdef TEST_MEMORY_MANAGER
1042                 log("[D] ENTER: m_allocator()");
1043                 #endif
1044
1045                 // Increase our allocation count
1046
1047                 currentAllocationCount++;
1048
1049                 // Log the request
1050
1051                 if (alwaysLogAll) log("[+] %05d %8s of size 0x%08X(%08d) by %s", currentAllocationCount, allocationTypes[allocationType], reportedSize, reportedSize, ownerString(sourceFile, sourceLine, sourceFunc));
1052
1053                 // If you hit this assert, you requested a breakpoint on a specific allocation count
1054                 m_assert(currentAllocationCount != breakOnAllocationCount);
1055
1056                 // If necessary, grow the reservoir of unused allocation units
1057
1058                 if (!reservoir)
1059                 {
1060                         // Allocate 256 reservoir elements
1061
1062                         reservoir = (sAllocUnit *) malloc(sizeof(sAllocUnit) * 256);
1063
1064                         // If you hit this assert, then the memory manager failed to allocate internal memory for tracking the
1065                         // allocations
1066                         m_assert(reservoir != NULL);
1067
1068                         // Danger Will Robinson!
1069
1070                         if (reservoir == NULL) throw "Unable to allocate RAM for internal memory tracking data";
1071
1072                         // Build a linked-list of the elements in our reservoir
1073
1074                         memset(reservoir, 0, sizeof(sAllocUnit) * 256);
1075                         for (unsigned int i = 0; i < 256 - 1; i++)
1076                         {
1077                                 reservoir[i].next = &reservoir[i+1];
1078                         }
1079
1080                         // Add this address to our reservoirBuffer so we can free it later
1081
1082                         sAllocUnit      **temp = (sAllocUnit **) realloc(reservoirBuffer, (reservoirBufferSize + 1) * sizeof(sAllocUnit *));
1083                         m_assert(temp);
1084                         if (temp)
1085                         {
1086                                 reservoirBuffer = temp;
1087                                 reservoirBuffer[reservoirBufferSize++] = reservoir;
1088                         }
1089                 }
1090
1091                 // Logical flow says this should never happen...
1092                 m_assert(reservoir != NULL);
1093
1094                 // Grab a new allocaton unit from the front of the reservoir
1095
1096                 sAllocUnit      *au = reservoir;
1097                 reservoir = au->next;
1098
1099                 // Populate it with some real data
1100
1101                 memset(au, 0, sizeof(sAllocUnit));
1102                 au->actualSize        = calculateActualSize(reportedSize);
1103                 #ifdef RANDOM_FAILURE
1104                 double  a = rand();
1105                 double  b = RAND_MAX / 100.0 * RANDOM_FAILURE;
1106                 if (a > b)
1107                 {
1108                         au->actualAddress = malloc(au->actualSize);
1109                 }
1110                 else
1111                 {
1112                         log("[F] Random faiure");
1113                         au->actualAddress = NULL;
1114                 }
1115                 #else
1116                 au->actualAddress     = malloc(au->actualSize);
1117                 #endif
1118                 au->reportedSize      = reportedSize;
1119                 au->reportedAddress   = calculateReportedAddress(au->actualAddress);
1120                 au->allocationType    = allocationType;
1121                 au->sourceLine        = sourceLine;
1122                 au->allocationNumber  = currentAllocationCount;
1123                 if (sourceFile) strncpy(au->sourceFile, sourceFileStripper(sourceFile), sizeof(au->sourceFile) - 1);
1124                 else            strcpy (au->sourceFile, "??");
1125                 if (sourceFunc) strncpy(au->sourceFunc, sourceFunc, sizeof(au->sourceFunc) - 1);
1126                 else            strcpy (au->sourceFunc, "??");
1127
1128                 // We don't want to assert with random failures, because we want the application to deal with them.
1129
1130                 #ifndef RANDOM_FAILURE
1131                 // If you hit this assert, then the requested allocation simply failed (you're out of memory.) Interrogate the
1132                 // variable 'au' or the stack frame to see what you were trying to do.
1133                 m_assert(au->actualAddress != NULL);
1134                 #endif
1135
1136                 if (au->actualAddress == NULL)
1137                 {
1138                         throw "Request for allocation failed. Out of memory.";
1139                 }
1140
1141                 // If you hit this assert, then this allocation was made from a source that isn't setup to use this memory tracking
1142                 // software, use the stack frame to locate the source and include our H file.
1143                 m_assert(allocationType != m_alloc_unknown);
1144
1145                 // Insert the new allocation into the hash table
1146
1147                 unsigned int    hashIndex = (reinterpret_cast<unsigned int>(au->reportedAddress) >> 4) & (hashSize - 1);
1148                 if (hashTable[hashIndex]) hashTable[hashIndex]->prev = au;
1149                 au->next = hashTable[hashIndex];
1150                 au->prev = NULL;
1151                 hashTable[hashIndex] = au;
1152
1153                 // Account for the new allocatin unit in our stats
1154
1155                 stats.totalReportedMemory += static_cast<unsigned int>(au->reportedSize);
1156                 stats.totalActualMemory   += static_cast<unsigned int>(au->actualSize);
1157                 stats.totalAllocUnitCount++;
1158                 if (stats.totalReportedMemory > stats.peakReportedMemory) stats.peakReportedMemory = stats.totalReportedMemory;
1159                 if (stats.totalActualMemory   > stats.peakActualMemory)   stats.peakActualMemory   = stats.totalActualMemory;
1160                 if (stats.totalAllocUnitCount > stats.peakAllocUnitCount) stats.peakAllocUnitCount = stats.totalAllocUnitCount;
1161                 stats.accumulatedReportedMemory += static_cast<unsigned int>(au->reportedSize);
1162                 stats.accumulatedActualMemory += static_cast<unsigned int>(au->actualSize);
1163                 stats.accumulatedAllocUnitCount++;
1164
1165                 // Prepare the allocation unit for use (wipe it with recognizable garbage)
1166
1167                 wipeWithPattern(au, unusedPattern);
1168
1169                 // calloc() expects the reported memory address range to be filled with 0's
1170
1171                 if (allocationType == m_alloc_calloc)
1172                 {
1173                         memset(au->reportedAddress, 0, au->reportedSize);
1174                 }
1175
1176                 // Validate every single allocated unit in memory
1177
1178                 if (alwaysValidateAll) m_validateAllAllocUnits();
1179
1180                 // Log the result
1181
1182                 if (alwaysLogAll) log("[+] ---->             addr 0x%08X", reinterpret_cast<unsigned int>(au->reportedAddress));
1183
1184                 // Resetting the globals insures that if at some later time, somebody calls our memory manager from an unknown
1185                 // source (i.e. they didn't include our H file) then we won't think it was the last allocation.
1186
1187                 resetGlobals();
1188
1189                 // Return the (reported) address of the new allocation unit
1190
1191                 #ifdef TEST_MEMORY_MANAGER
1192                 log("[D] EXIT : m_allocator()");
1193                 #endif
1194
1195                 return au->reportedAddress;
1196         }
1197         catch(const char *err)
1198         {
1199                 // Deal with the errors
1200
1201                 log("[!] %s", err);
1202                 resetGlobals();
1203
1204                 #ifdef TEST_MEMORY_MANAGER
1205                 log("[D] EXIT : m_allocator()");
1206                 #endif
1207
1208                 return NULL;
1209         }
1210 }
1211
1212 // ---------------------------------------------------------------------------------------------------------------------------------
1213 // Reallocate memory and track it
1214 // ---------------------------------------------------------------------------------------------------------------------------------
1215
1216 void    *m_reallocator(const char *sourceFile, const unsigned int sourceLine, const char *sourceFunc, const unsigned int reallocationType, const size_t reportedSize, void *reportedAddress)
1217 {
1218         try
1219         {
1220                 #ifdef TEST_MEMORY_MANAGER
1221                 log("[D] ENTER: m_reallocator()");
1222                 #endif
1223
1224                 // Calling realloc with a NULL should force same operations as a malloc
1225
1226                 if (!reportedAddress)
1227                 {
1228                         return m_allocator(sourceFile, sourceLine, sourceFunc, reallocationType, reportedSize);
1229                 }
1230
1231                 // Increase our allocation count
1232
1233                 currentAllocationCount++;
1234
1235                 // If you hit this assert, you requested a breakpoint on a specific allocation count
1236                 m_assert(currentAllocationCount != breakOnAllocationCount);
1237
1238                 // Log the request
1239
1240                 if (alwaysLogAll) log("[~] %05d %8s of size 0x%08X(%08d) by %s", currentAllocationCount, allocationTypes[reallocationType], reportedSize, reportedSize, ownerString(sourceFile, sourceLine, sourceFunc));
1241
1242                 // Locate the existing allocation unit
1243
1244                 sAllocUnit      *au = findAllocUnit(reportedAddress);
1245
1246                 // If you hit this assert, you tried to reallocate RAM that wasn't allocated by this memory manager.
1247                 m_assert(au != NULL);
1248                 if (au == NULL) throw "Request to reallocate RAM that was never allocated";
1249
1250                 // If you hit this assert, then the allocation unit that is about to be reallocated is damaged. But you probably
1251                 // already know that from a previous assert you should have seen in validateAllocUnit() :)
1252                 m_assert(m_validateAllocUnit(au));
1253
1254                 // If you hit this assert, then this reallocation was made from a source that isn't setup to use this memory
1255                 // tracking software, use the stack frame to locate the source and include our H file.
1256                 m_assert(reallocationType != m_alloc_unknown);
1257
1258                 // If you hit this assert, you were trying to reallocate RAM that was not allocated in a way that is compatible with
1259                 // realloc. In other words, you have a allocation/reallocation mismatch.
1260                 m_assert(au->allocationType == m_alloc_malloc ||
1261                          au->allocationType == m_alloc_calloc ||
1262                          au->allocationType == m_alloc_realloc);
1263
1264                 // If you hit this assert, then the "break on realloc" flag for this allocation unit is set (and will continue to be
1265                 // set until you specifically shut it off. Interrogate the 'au' variable to determine information about this
1266                 // allocation unit.
1267                 m_assert(au->breakOnRealloc == false);
1268
1269                 // Keep track of the original size
1270
1271                 unsigned int    originalReportedSize = static_cast<unsigned int>(au->reportedSize);
1272
1273                 if (alwaysLogAll) log("[~] ---->             from 0x%08X(%08d)", originalReportedSize, originalReportedSize);
1274
1275                 // Do the reallocation
1276
1277                 void    *oldReportedAddress = reportedAddress;
1278                 size_t  newActualSize = calculateActualSize(reportedSize);
1279                 void    *newActualAddress = NULL;
1280                 #ifdef RANDOM_FAILURE
1281                 double  a = rand();
1282                 double  b = RAND_MAX / 100.0 * RANDOM_FAILURE;
1283                 if (a > b)
1284                 {
1285                         newActualAddress = realloc(au->actualAddress, newActualSize);
1286                 }
1287                 else
1288                 {
1289                         log("[F] Random faiure");
1290                 }
1291                 #else
1292                 newActualAddress = realloc(au->actualAddress, newActualSize);
1293                 #endif
1294
1295                 // We don't want to assert with random failures, because we want the application to deal with them.
1296
1297                 #ifndef RANDOM_FAILURE
1298                 // If you hit this assert, then the requested allocation simply failed (you're out of memory) Interrogate the
1299                 // variable 'au' to see the original allocation. You can also query 'newActualSize' to see the amount of memory
1300                 // trying to be allocated. Finally, you can query 'reportedSize' to see how much memory was requested by the caller.
1301                 m_assert(newActualAddress);
1302                 #endif
1303
1304                 if (!newActualAddress) throw "Request for reallocation failed. Out of memory.";
1305
1306                 // Remove this allocation from our stats (we'll add the new reallocation again later)
1307
1308                 stats.totalReportedMemory -= static_cast<unsigned int>(au->reportedSize);
1309                 stats.totalActualMemory   -= static_cast<unsigned int>(au->actualSize);
1310
1311                 // Update the allocation with the new information
1312
1313                 au->actualSize        = newActualSize;
1314                 au->actualAddress     = newActualAddress;
1315                 au->reportedSize      = calculateReportedSize(newActualSize);
1316                 au->reportedAddress   = calculateReportedAddress(newActualAddress);
1317                 au->allocationType    = reallocationType;
1318                 au->sourceLine        = sourceLine;
1319                 au->allocationNumber  = currentAllocationCount;
1320                 if (sourceFile) strncpy(au->sourceFile, sourceFileStripper(sourceFile), sizeof(au->sourceFile) - 1);
1321                 else            strcpy (au->sourceFile, "??");
1322                 if (sourceFunc) strncpy(au->sourceFunc, sourceFunc, sizeof(au->sourceFunc) - 1);
1323                 else            strcpy (au->sourceFunc, "??");
1324
1325                 // The reallocation may cause the address to change, so we should relocate our allocation unit within the hash table
1326
1327                 unsigned int    hashIndex = static_cast<unsigned int>(-1);
1328                 if (oldReportedAddress != au->reportedAddress)
1329                 {
1330                         // Remove this allocation unit from the hash table
1331
1332                         {
1333                                 unsigned int    hashIndex = (reinterpret_cast<unsigned int>(oldReportedAddress) >> 4) & (hashSize - 1);
1334                                 if (hashTable[hashIndex] == au)
1335                                 {
1336                                         hashTable[hashIndex] = hashTable[hashIndex]->next;
1337                                 }
1338                                 else
1339                                 {
1340                                         if (au->prev)   au->prev->next = au->next;
1341                                         if (au->next)   au->next->prev = au->prev;
1342                                 }
1343                         }
1344
1345                         // Re-insert it back into the hash table
1346
1347                         hashIndex = (reinterpret_cast<unsigned int>(au->reportedAddress) >> 4) & (hashSize - 1);
1348                         if (hashTable[hashIndex]) hashTable[hashIndex]->prev = au;
1349                         au->next = hashTable[hashIndex];
1350                         au->prev = NULL;
1351                         hashTable[hashIndex] = au;
1352                 }
1353
1354                 // Account for the new allocatin unit in our stats
1355
1356                 stats.totalReportedMemory += static_cast<unsigned int>(au->reportedSize);
1357                 stats.totalActualMemory   += static_cast<unsigned int>(au->actualSize);
1358                 if (stats.totalReportedMemory > stats.peakReportedMemory) stats.peakReportedMemory = stats.totalReportedMemory;
1359                 if (stats.totalActualMemory   > stats.peakActualMemory)   stats.peakActualMemory   = stats.totalActualMemory;
1360                 int     deltaReportedSize = static_cast<int>(reportedSize - originalReportedSize);
1361                 if (deltaReportedSize > 0)
1362                 {
1363                         stats.accumulatedReportedMemory += deltaReportedSize;
1364                         stats.accumulatedActualMemory += deltaReportedSize;
1365                 }
1366
1367                 // Prepare the allocation unit for use (wipe it with recognizable garbage)
1368
1369                 wipeWithPattern(au, unusedPattern, originalReportedSize);
1370
1371                 // If you hit this assert, then something went wrong, because the allocation unit was properly validated PRIOR to
1372                 // the reallocation. This should not happen.
1373                 m_assert(m_validateAllocUnit(au));
1374
1375                 // Validate every single allocated unit in memory
1376
1377                 if (alwaysValidateAll) m_validateAllAllocUnits();
1378
1379                 // Log the result
1380
1381                 if (alwaysLogAll) log("[~] ---->             addr 0x%08X", reinterpret_cast<unsigned int>(au->reportedAddress));
1382
1383                 // Resetting the globals insures that if at some later time, somebody calls our memory manager from an unknown
1384                 // source (i.e. they didn't include our H file) then we won't think it was the last allocation.
1385
1386                 resetGlobals();
1387
1388                 // Return the (reported) address of the new allocation unit
1389
1390                 #ifdef TEST_MEMORY_MANAGER
1391                 log("[D] EXIT : m_reallocator()");
1392                 #endif
1393
1394                 return au->reportedAddress;
1395         }
1396         catch(const char *err)
1397         {
1398                 // Deal with the errors
1399
1400                 log("[!] %s", err);
1401                 resetGlobals();
1402
1403                 #ifdef TEST_MEMORY_MANAGER
1404                 log("[D] EXIT : m_reallocator()");
1405                 #endif
1406
1407                 return NULL;
1408         }
1409 }
1410
1411 // ---------------------------------------------------------------------------------------------------------------------------------
1412 // Deallocate memory and track it
1413 // ---------------------------------------------------------------------------------------------------------------------------------
1414
1415 void    m_deallocator(const char *sourceFile, const unsigned int sourceLine, const char *sourceFunc, const unsigned int deallocationType, const void *reportedAddress)
1416 {
1417         try
1418         {
1419                 #ifdef TEST_MEMORY_MANAGER
1420                 log("[D] ENTER: m_deallocator()");
1421                 #endif
1422
1423                 // Log the request
1424
1425                 if (alwaysLogAll) log("[-] ----- %8s of addr 0x%08X           by %s", allocationTypes[deallocationType], reinterpret_cast<unsigned int>(const_cast<void *>(reportedAddress)), ownerString(sourceFile, sourceLine, sourceFunc));
1426
1427                 // We should only ever get here with a null pointer if they try to do so with a call to free() (delete[] and delete will
1428                 // both bail before they get here.) So, since ANSI allows free(NULL), we'll not bother trying to actually free the allocated
1429                 // memory or track it any further.
1430
1431                 if (reportedAddress)
1432                 {
1433                         // Go get the allocation unit
1434
1435                         sAllocUnit      *au = findAllocUnit(reportedAddress);
1436
1437                         // If you hit this assert, you tried to deallocate RAM that wasn't allocated by this memory manager.
1438                         m_assert(au != NULL);
1439                         if (au == NULL) throw "Request to deallocate RAM that was never allocated";
1440
1441                         // If you hit this assert, then the allocation unit that is about to be deallocated is damaged. But you probably
1442                         // already know that from a previous assert you should have seen in validateAllocUnit() :)
1443                         m_assert(m_validateAllocUnit(au));
1444
1445                         // If you hit this assert, then this deallocation was made from a source that isn't setup to use this memory
1446                         // tracking software, use the stack frame to locate the source and include our H file.
1447                         m_assert(deallocationType != m_alloc_unknown);
1448
1449                         // If you hit this assert, you were trying to deallocate RAM that was not allocated in a way that is compatible with
1450                         // the deallocation method requested. In other words, you have a allocation/deallocation mismatch.
1451                         m_assert((deallocationType == m_alloc_delete       && au->allocationType == m_alloc_new      ) ||
1452                                 (deallocationType == m_alloc_delete_array && au->allocationType == m_alloc_new_array) ||
1453                                 (deallocationType == m_alloc_free         && au->allocationType == m_alloc_malloc   ) ||
1454                                 (deallocationType == m_alloc_free         && au->allocationType == m_alloc_calloc   ) ||
1455                                 (deallocationType == m_alloc_free         && au->allocationType == m_alloc_realloc  ) ||
1456                                 (deallocationType == m_alloc_unknown                                                ) );
1457
1458                         // If you hit this assert, then the "break on dealloc" flag for this allocation unit is set. Interrogate the 'au'
1459                         // variable to determine information about this allocation unit.
1460                         m_assert(au->breakOnDealloc == false);
1461
1462                         // Wipe the deallocated RAM with a new pattern. This doen't actually do us much good in debug mode under WIN32,
1463                         // because Microsoft's memory debugging & tracking utilities will wipe it right after we do. Oh well.
1464
1465                         wipeWithPattern(au, releasedPattern);
1466
1467                         // Do the deallocation
1468
1469                         free(au->actualAddress);
1470
1471                         // Remove this allocation unit from the hash table
1472
1473                         unsigned int    hashIndex = (reinterpret_cast<unsigned int>(au->reportedAddress) >> 4) & (hashSize - 1);
1474                         if (hashTable[hashIndex] == au)
1475                         {
1476                                 hashTable[hashIndex] = au->next;
1477                         }
1478                         else
1479                         {
1480                                 if (au->prev)   au->prev->next = au->next;
1481                                 if (au->next)   au->next->prev = au->prev;
1482                         }
1483
1484                         // Remove this allocation from our stats
1485
1486                         stats.totalReportedMemory -= static_cast<unsigned int>(au->reportedSize);
1487                         stats.totalActualMemory   -= static_cast<unsigned int>(au->actualSize);
1488                         stats.totalAllocUnitCount--;
1489
1490                         // Add this allocation unit to the front of our reservoir of unused allocation units
1491
1492                         memset(au, 0, sizeof(sAllocUnit));
1493                         au->next = reservoir;
1494                         reservoir = au;
1495                 }
1496
1497                 // Resetting the globals insures that if at some later time, somebody calls our memory manager from an unknown
1498                 // source (i.e. they didn't include our H file) then we won't think it was the last allocation.
1499
1500                 resetGlobals();
1501
1502                 // Validate every single allocated unit in memory
1503
1504                 if (alwaysValidateAll) m_validateAllAllocUnits();
1505
1506                 // If we're in the midst of static deinitialization time, track any pending memory leaks
1507
1508                 if (staticDeinitTime) dumpLeakReport();
1509         }
1510         catch(const char *err)
1511         {
1512                 // Deal with errors
1513
1514                 log("[!] %s", err);
1515                 resetGlobals();
1516         }
1517
1518         #ifdef TEST_MEMORY_MANAGER
1519         log("[D] EXIT : m_deallocator()");
1520         #endif
1521 }
1522
1523 // ---------------------------------------------------------------------------------------------------------------------------------
1524 // -DOC- The following utilitarian allow you to become proactive in tracking your own memory, or help you narrow in on those tough
1525 // bugs.
1526 // ---------------------------------------------------------------------------------------------------------------------------------
1527
1528 bool    m_validateAddress(const void *reportedAddress)
1529 {
1530         // Just see if the address exists in our allocation routines
1531
1532         return findAllocUnit(reportedAddress) != NULL;
1533 }
1534
1535 // ---------------------------------------------------------------------------------------------------------------------------------
1536
1537 bool    m_validateAllocUnit(const sAllocUnit *allocUnit)
1538 {
1539         // Make sure the padding is untouched
1540
1541         long    *pre = reinterpret_cast<long *>(allocUnit->actualAddress);
1542         long    *post = reinterpret_cast<long *>((char *)allocUnit->actualAddress + allocUnit->actualSize - paddingSize * sizeof(long));
1543         bool    errorFlag = false;
1544         for (unsigned int i = 0; i < paddingSize; i++, pre++, post++)
1545         {
1546                 if (*pre != (long) prefixPattern)
1547                 {
1548                         log("[!] A memory allocation unit was corrupt because of an underrun:");
1549                         m_dumpAllocUnit(allocUnit, "  ");
1550                         errorFlag = true;
1551                 }
1552
1553                 // If you hit this assert, then you should know that this allocation unit has been damaged. Something (possibly the
1554                 // owner?) has underrun the allocation unit (modified a few bytes prior to the start). You can interrogate the
1555                 // variable 'allocUnit' to see statistics and information about this damaged allocation unit.
1556                 m_assert(*pre == static_cast<long>(prefixPattern));
1557
1558                 if (*post != static_cast<long>(postfixPattern))
1559                 {
1560                         log("[!] A memory allocation unit was corrupt because of an overrun:");
1561                         m_dumpAllocUnit(allocUnit, "  ");
1562                         errorFlag = true;
1563                 }
1564
1565                 // If you hit this assert, then you should know that this allocation unit has been damaged. Something (possibly the
1566                 // owner?) has overrun the allocation unit (modified a few bytes after the end). You can interrogate the variable
1567                 // 'allocUnit' to see statistics and information about this damaged allocation unit.
1568                 m_assert(*post == static_cast<long>(postfixPattern));
1569         }
1570
1571         // Return the error status (we invert it, because a return of 'false' means error)
1572
1573         return !errorFlag;
1574 }
1575
1576 // ---------------------------------------------------------------------------------------------------------------------------------
1577
1578 bool    m_validateAllAllocUnits()
1579 {
1580         // Just go through each allocation unit in the hash table and count the ones that have errors
1581
1582         unsigned int    errors = 0;
1583         unsigned int    allocCount = 0;
1584         for (unsigned int i = 0; i < hashSize; i++)
1585         {
1586                 sAllocUnit      *ptr = hashTable[i];
1587                 while(ptr)
1588                 {
1589                         allocCount++;
1590                         if (!m_validateAllocUnit(ptr)) errors++;
1591                         ptr = ptr->next;
1592                 }
1593         }
1594
1595         // Test for hash-table correctness
1596
1597         if (allocCount != stats.totalAllocUnitCount)
1598         {
1599                 log("[!] Memory tracking hash table corrupt!");
1600                 errors++;
1601         }
1602
1603         // If you hit this assert, then the internal memory (hash table) used by this memory tracking software is damaged! The
1604         // best way to track this down is to use the alwaysLogAll flag in conjunction with STRESS_TEST macro to narrow in on the
1605         // offending code. After running the application with these settings (and hitting this assert again), interrogate the
1606         // memory.log file to find the previous successful operation. The corruption will have occurred between that point and this
1607         // assertion.
1608         m_assert(allocCount == stats.totalAllocUnitCount);
1609
1610         // If you hit this assert, then you've probably already been notified that there was a problem with a allocation unit in a
1611         // prior call to validateAllocUnit(), but this assert is here just to make sure you know about it. :)
1612         m_assert(errors == 0);
1613
1614         // Log any errors
1615
1616         if (errors) log("[!] While validting all allocation units, %d allocation unit(s) were found to have problems", errors);
1617
1618         // Return the error status
1619
1620         return errors != 0;
1621 }
1622
1623 // ---------------------------------------------------------------------------------------------------------------------------------
1624 // -DOC- Unused RAM calculation routines. Use these to determine how much of your RAM is unused (in bytes)
1625 // ---------------------------------------------------------------------------------------------------------------------------------
1626
1627 unsigned int    m_calcUnused(const sAllocUnit *allocUnit)
1628 {
1629         const unsigned long     *ptr = reinterpret_cast<const unsigned long *>(allocUnit->reportedAddress);
1630         unsigned int            count = 0;
1631
1632         for (unsigned int i = 0; i < allocUnit->reportedSize; i += sizeof(long), ptr++)
1633         {
1634                 if (*ptr == unusedPattern) count += sizeof(long);
1635         }
1636
1637         return count;
1638 }
1639
1640 // ---------------------------------------------------------------------------------------------------------------------------------
1641
1642 unsigned int    m_calcAllUnused()
1643 {
1644         // Just go through each allocation unit in the hash table and count the unused RAM
1645
1646         unsigned int    total = 0;
1647         for (unsigned int i = 0; i < hashSize; i++)
1648         {
1649                 sAllocUnit      *ptr = hashTable[i];
1650                 while(ptr)
1651                 {
1652                         total += m_calcUnused(ptr);
1653                         ptr = ptr->next;
1654                 }
1655         }
1656
1657         return total;
1658 }
1659
1660 // ---------------------------------------------------------------------------------------------------------------------------------
1661 // -DOC- The following functions are for logging and statistics reporting.
1662 // ---------------------------------------------------------------------------------------------------------------------------------
1663
1664 void    m_dumpAllocUnit(const sAllocUnit *allocUnit, const char *prefix)
1665 {
1666         log("[I] %sAddress (reported): %010p",       prefix, allocUnit->reportedAddress);
1667         log("[I] %sAddress (actual)  : %010p",       prefix, allocUnit->actualAddress);
1668         log("[I] %sSize (reported)   : 0x%08X (%s)", prefix, static_cast<unsigned int>(allocUnit->reportedSize), memorySizeString(static_cast<unsigned int>(allocUnit->reportedSize)));
1669         log("[I] %sSize (actual)     : 0x%08X (%s)", prefix, static_cast<unsigned int>(allocUnit->actualSize), memorySizeString(static_cast<unsigned int>(allocUnit->actualSize)));
1670         log("[I] %sOwner             : %s(%d)::%s",  prefix, allocUnit->sourceFile, allocUnit->sourceLine, allocUnit->sourceFunc);
1671         log("[I] %sAllocation type   : %s",          prefix, allocationTypes[allocUnit->allocationType]);
1672         log("[I] %sAllocation number : %d",          prefix, allocUnit->allocationNumber);
1673 }
1674
1675 // ---------------------------------------------------------------------------------------------------------------------------------
1676
1677 void    m_dumpMemoryReport(const char *filename, const bool overwrite)
1678 {
1679         // Open the report file
1680
1681         FILE    *fp = NULL;
1682         
1683         if (overwrite)  fp = fopen(filename, "w+b");
1684         else            fp = fopen(filename, "ab");
1685
1686         // If you hit this assert, then the memory report generator is unable to log information to a file (can't open the file for
1687         // some reason.)
1688         m_assert(fp);
1689         if (!fp) return;
1690
1691         // Header
1692
1693         static  char    timeString[25];
1694         memset(timeString, 0, sizeof(timeString));
1695         time_t  t = time(NULL);
1696         struct  tm *tme = localtime(&t);
1697         fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
1698         fprintf(fp, "|                                             Memory 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);
1699         fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
1700         fprintf(fp, "\r\n");
1701         fprintf(fp, "\r\n");
1702
1703         // Report summary
1704
1705         fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
1706         fprintf(fp, "|                                                           T O T A L S                                                            |\r\n");
1707         fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
1708         fprintf(fp, "              Allocation unit count: %10s\r\n", insertCommas(stats.totalAllocUnitCount));
1709         fprintf(fp, "            Reported to application: %s\r\n", memorySizeString(stats.totalReportedMemory));
1710         fprintf(fp, "         Actual total memory in use: %s\r\n", memorySizeString(stats.totalActualMemory));
1711         fprintf(fp, "           Memory tracking overhead: %s\r\n", memorySizeString(stats.totalActualMemory - stats.totalReportedMemory));
1712         fprintf(fp, "\r\n");
1713
1714         fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
1715         fprintf(fp, "|                                                            P E A K S                                                             |\r\n");
1716         fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
1717         fprintf(fp, "              Allocation unit count: %10s\r\n", insertCommas(stats.peakAllocUnitCount));
1718         fprintf(fp, "            Reported to application: %s\r\n", memorySizeString(stats.peakReportedMemory));
1719         fprintf(fp, "                             Actual: %s\r\n", memorySizeString(stats.peakActualMemory));
1720         fprintf(fp, "           Memory tracking overhead: %s\r\n", memorySizeString(stats.peakActualMemory - stats.peakReportedMemory));
1721         fprintf(fp, "\r\n");
1722
1723         fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
1724         fprintf(fp, "|                                                      A C C U M U L A T E D                                                       |\r\n");
1725         fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
1726         fprintf(fp, "              Allocation unit count: %s\r\n", memorySizeString(stats.accumulatedAllocUnitCount));
1727         fprintf(fp, "            Reported to application: %s\r\n", memorySizeString(stats.accumulatedReportedMemory));
1728         fprintf(fp, "                             Actual: %s\r\n", memorySizeString(stats.accumulatedActualMemory));
1729         fprintf(fp, "\r\n");
1730
1731         fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
1732         fprintf(fp, "|                                                           U N U S E D                                                            |\r\n");
1733         fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
1734         fprintf(fp, "    Memory allocated but not in use: %s\r\n", memorySizeString(m_calcAllUnused()));
1735         fprintf(fp, "\r\n");
1736
1737         dumpAllocations(fp);
1738
1739         fclose(fp);
1740 }
1741
1742 // ---------------------------------------------------------------------------------------------------------------------------------
1743
1744 sMStats m_getMemoryStatistics()
1745 {
1746         return stats;
1747 }
1748
1749 // ---------------------------------------------------------------------------------------------------------------------------------
1750 // mmgr.cpp - End of file
1751 // ---------------------------------------------------------------------------------------------------------------------------------
1752