cMemoryManager.cpp

00001 // ---------------------------------------------------------------------------------------------------------------------------------
00002 //
00003 //
00004 //  _ __ ___  _ __ ___   __ _ _ __      ___ _ __  _ __
00005 // | '_ ` _ \| '_ ` _ \ / _` | '__|    / __| '_ \| '_ \
00006 // | | | | | | | | | | | (_| | |    _ | (__| |_) | |_) |
00007 // |_| |_| |_|_| |_| |_|\__, |_|   (_) \___| .__/| .__/
00008 //                       __/ |             | |   | |
00009 //                      |___/              |_|   |_|
00010 //
00011 // Memory manager & tracking software
00012 //
00013 // Best viewed with 8-character tabs and (at least) 132 columns
00014 //
00015 // ---------------------------------------------------------------------------------------------------------------------------------
00016 //
00017 // Restrictions & freedoms pertaining to usage and redistribution of this software:
00018 //
00019 //  * This software is 100% free
00020 //  * If you use this software (in part or in whole) you must credit the author.
00021 //  * This software may not be re-distributed (in part or in whole) in a modified
00022 //    form without clear documentation on how to obtain a copy of the original work.
00023 //  * You may not use this software to directly or indirectly cause harm to others.
00024 //  * This software is provided as-is and without warrantee. Use at your own risk.
00025 //
00026 // For more information, visit HTTP://www.FluidStudios.com
00027 //
00028 // ---------------------------------------------------------------------------------------------------------------------------------
00029 // Originally created on 12/22/2000 by Paul Nettle
00030 //
00031 // Copyright 2000, Fluid Studios, Inc., all rights reserved.
00032 // ---------------------------------------------------------------------------------------------------------------------------------
00033 //
00034 // !!IMPORTANT!!
00035 //
00036 // This software is self-documented with periodic comments. Before you start using this software, perform a search for the string
00037 // "-DOC-" to locate pertinent information about how to use this software.
00038 //
00039 // You are also encouraged to read the comment blocks throughout this source file. They will help you understand how this memory
00040 // tracking software works, so you can better utilize it within your applications.
00041 //
00042 // NOTES:
00043 //
00044 // 1. If you get compiler errors having to do with set_new_handler, then go through this source and search/replace
00045 //    "_handler" with "set_new_handler".
00046 //
00047 // 2. This code purposely uses no external routines that allocate RAM (other than the raw allocation routines, such as malloc). We
00048 //    do this because we want this to be as self-contained as possible. As an example, we don't use assert, because when running
00049 //    under WIN32, the assert brings up a dialog box, which allocates RAM. Doing this in the middle of an allocation would be bad.
00050 //
00051 // 3. When trying to override new/delete under MFC (which has its own version of global new/delete) the linker will complain. In
00052 //    order to fix this error, use the compiler option: /FORCE, which will force it to build an executable even with linker errors.
00053 //    Be sure to check those errors each time you compile, otherwise, you may miss a valid linker error.
00054 //
00055 // 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
00056 //    code was carefully thought out. If something looks odd, then just assume I've got a good reason for doing it that way (an
00057 //    example is the use of the class MemStaticTimeTracker.)
00058 //
00059 // 5. With MFC applications, you will need to comment out any occurance of "#define new DEBUG_NEW" from all source files.
00060 //
00061 // 6. Include file dependencies are _very_important_ for getting the MMGR to integrate nicely into your application. Be careful if
00062 //    you're including standard includes from within your own project inclues; that will break this very specific dependency order.
00063 //    It should look like this:
00064 //
00065 //              #include <stdio.h>   // Standard includes MUST come first
00066 //              #include <stdlib.h>  //
00067 //              #include <streamio>  //
00068 //
00069 //              #include "mmgr.h"    // mmgr.h MUST come next
00070 //
00071 //              #include "myfile1.h" // Project includes MUST come last
00072 //              #include "myfile2.h" //
00073 //              #include "myfile3.h" //
00074 //
00075 // ---------------------------------------------------------------------------------------------------------------------------------
00076 
00077 //#include "stdafx.h"
00078 #include <iostream>
00079 #include <stdio.h>
00080 #include <stdlib.h>
00081 #include <assert.h>
00082 #include <string.h>
00083 #include <time.h>
00084 #include <stdarg.h>
00085 
00086 #ifdef  CAUDIO_PLATFORM_WIN
00087 #include <new.h>
00088 #endif
00089 
00090 #ifdef CAUDIO_PLATFORM_LINUX
00091 #include <mpatrol.h>
00092 #endif
00093 
00094 #include "../Headers/cMemoryManager.h"
00095 #include "../include/cAudioDefines.h"
00096 // ---------------------------------------------------------------------------------------------------------------------------------
00097 // -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
00098 // very good reasons... like making bugs obvious as early as possible.) Some people may be inclined to remove this memory tracking
00099 // software if it causes crashes that didn't exist previously. In reality, these new crashes are the BEST reason for using this
00100 // software!
00101 //
00102 // Whether this software causes your application to crash, or if it reports errors, you need to be able to TRUST this software. To
00103 // this end, you are given some very simple debugging tools.
00104 //
00105 // The quickest way to locate problems is to enable the STRESS_TEST macro (below.) This should catch 95% of the crashes before they
00106 // occur by validating every allocation each time this memory manager performs an allocation function. If that doesn't work, keep
00107 // reading...
00108 //
00109 // If you enable the TEST_MEMORY_MANAGER #define (below), this memory manager will log an entry in the memory.log file each time it
00110 // enters and exits one of its primary allocation handling routines. Each call that succeeds should place an "ENTER" and an "EXIT"
00111 // into the log. If the program crashes within the memory manager, it will log an "ENTER", but not an "EXIT". The log will also
00112 // report the name of the routine.
00113 //
00114 // Just because this memory manager crashes does not mean that there is a bug here! First, an application could inadvertantly damage
00115 // the heap, causing malloc(), realloc() or free() to crash. Also, an application could inadvertantly damage some of the memory used
00116 // by this memory tracking software, causing it to crash in much the same way that a damaged heap would affect the standard
00117 // allocation routines.
00118 //
00119 // 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
00120 // crashing. You can do this by adding log() entries throughout the routine that crashes, repeating this process until you narrow
00121 // 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
00122 // bother contacting me, your application has damaged the heap. You can help find the culprit in your code by enabling the
00123 // STRESS_TEST macro (below.)
00124 //
00125 // If you truely suspect a bug in this memory manager (and you had better be sure about it! :) you can contact me at
00126 // midnight@FluidStudios.com. Before you do, however, check for a newer version at:
00127 //
00128 //      http://www.FluidStudios.com/publications.html
00129 //
00130 // When using this debugging aid, make sure that you are NOT setting the alwaysLogAll variable on, otherwise the log could be
00131 // cluttered and hard to read.
00132 // ---------------------------------------------------------------------------------------------------------------------------------
00133 
00134 //#define       TEST_MEMORY_MANAGER
00135 
00136 // ---------------------------------------------------------------------------------------------------------------------------------
00137 // -DOC- Enable this sucker if you really want to stress-test your app's memory usage, or to help find hard-to-find bugs
00138 // ---------------------------------------------------------------------------------------------------------------------------------
00139 
00140 //#define       STRESS_TEST
00141 
00142 // ---------------------------------------------------------------------------------------------------------------------------------
00143 // -DOC- Enable this sucker if you want to stress-test your app's error-handling. Set RANDOM_FAIL to the percentage of failures you
00144 //       want to test with (0 = none, >100 = all failures).
00145 // ---------------------------------------------------------------------------------------------------------------------------------
00146 
00147 //#define       RANDOM_FAILURE 10.0
00148 
00149 // ---------------------------------------------------------------------------------------------------------------------------------
00150 // -DOC- Locals -- modify these flags to suit your needs
00151 // ---------------------------------------------------------------------------------------------------------------------------------
00152 
00153 #ifdef  STRESS_TEST
00154 static  const   unsigned int    hashBits               = 12;
00155 static          bool            randomWipe             = true;
00156 static          bool            alwaysValidateAll      = true;
00157 static          bool            alwaysLogAll           = true;
00158 static          bool            alwaysWipeAll          = true;
00159 static          bool            cleanupLogOnFirstRun   = true;
00160 static  const   unsigned int    paddingSize            = 1024; // An extra 8K per allocation!
00161 #else
00162 static  const   unsigned int    hashBits               = 12;
00163 static          bool            randomWipe             = false;
00164 static          bool            alwaysValidateAll      = false;
00165 static          bool            alwaysLogAll           = false;
00166 static          bool            alwaysWipeAll          = true;
00167 static          bool            cleanupLogOnFirstRun   = true;
00168 static  const   unsigned int    paddingSize            = 4;
00169 #endif
00170 
00171 // ---------------------------------------------------------------------------------------------------------------------------------
00172 // We define our own assert, because we don't want to bring up an assertion dialog, since that allocates RAM. Our new assert
00173 // simply declares a forced breakpoint.
00174 //
00175 // The BEOS assert added by Arvid Norberg <arvid@iname.com>.
00176 // ---------------------------------------------------------------------------------------------------------------------------------
00177 
00178 #ifdef  WIN32
00179         #ifdef  _DEBUG
00180         #define m_assert(x) if ((x) == false) __asm { int 3 }
00181         #else
00182         #define m_assert(x) {}
00183         #endif
00184 #elif defined(__BEOS__)
00185         #ifdef DEBUG
00186                 extern void debugger(const char *message);
00187                 #define m_assert(x) if ((x) == false) debugger("mmgr: assert failed")
00188         #else
00189                 #define m_assert(x) {}
00190         #endif
00191 #else   // Linux uses assert, which we can use safely, since it doesn't bring up a dialog within the program.
00192         #define m_assert(cond) assert(cond)
00193 #endif
00194 
00195 // ---------------------------------------------------------------------------------------------------------------------------------
00196 // Here, we turn off our macros because any place in this source file where the word 'new' or the word 'delete' (etc.)
00197 // appear will be expanded by the macro. So to avoid problems using them within this source file, we'll just #undef them.
00198 // ---------------------------------------------------------------------------------------------------------------------------------
00199 
00200 #undef  new
00201 #undef  delete
00202 #undef  malloc
00203 #undef  calloc
00204 #undef  realloc
00205 #undef  free
00206 
00207 // ---------------------------------------------------------------------------------------------------------------------------------
00208 // Defaults for the constants & statics in the MemoryManager class
00209 // ---------------------------------------------------------------------------------------------------------------------------------
00210 
00211 const           unsigned int    m_alloc_unknown        = 0;
00212 const           unsigned int    m_alloc_new            = 1;
00213 const           unsigned int    m_alloc_new_array      = 2;
00214 const           unsigned int    m_alloc_malloc         = 3;
00215 const           unsigned int    m_alloc_calloc         = 4;
00216 const           unsigned int    m_alloc_realloc        = 5;
00217 const           unsigned int    m_alloc_delete         = 6;
00218 const           unsigned int    m_alloc_delete_array   = 7;
00219 const           unsigned int    m_alloc_free           = 8;
00220 
00221 // ---------------------------------------------------------------------------------------------------------------------------------
00222 // -DOC- Get to know these values. They represent the values that will be used to fill unused and deallocated RAM.
00223 // ---------------------------------------------------------------------------------------------------------------------------------
00224 
00225 static          unsigned int    prefixPattern          = 0xbaadf00d; // Fill pattern for bytes preceeding allocated blocks
00226 static          unsigned int    postfixPattern         = 0xdeadc0de; // Fill pattern for bytes following allocated blocks
00227 static          unsigned int    unusedPattern          = 0xfeedface; // Fill pattern for freshly allocated blocks
00228 static          unsigned int    releasedPattern        = 0xdeadbeef; // Fill pattern for deallocated blocks
00229 
00230 // ---------------------------------------------------------------------------------------------------------------------------------
00231 // Other locals
00232 // ---------------------------------------------------------------------------------------------------------------------------------
00233 
00234 static  const   unsigned int    hashSize               = 1 << hashBits;
00235 static  const   char            *allocationTypes[]     = {"Unknown",
00236                                                           "new",     "new[]",  "malloc",   "calloc",
00237                                                           "realloc", "delete", "delete[]", "free"};
00238 static          sAllocUnit      *hashTable[hashSize];
00239 static          sAllocUnit      *reservoir;
00240 static          unsigned int    currentAllocationCount = 0;
00241 static          unsigned int    breakOnAllocationCount = 0;
00242 static          sMStats         stats;
00243 static  const   char            *sourceFile            = "??";
00244 static  const   char            *sourceFunc            = "??";
00245 static          unsigned int    sourceLine             = 0;
00246 static          bool            staticDeinitTime       = false;
00247 static          sAllocUnit      **reservoirBuffer      = NULL;
00248 static          unsigned int    reservoirBufferSize    = 0;
00249 static const    char            *memoryLogFile         = "memory.log";
00250 static const    char            *memoryLeakLogFile     = "memleaks.log";
00251 static          void            doCleanupLogOnFirstRun();
00252 
00253 // ---------------------------------------------------------------------------------------------------------------------------------
00254 // Local functions only
00255 // ---------------------------------------------------------------------------------------------------------------------------------
00256 
00257 
00258 static  void    log(const char *format, ...)
00259 {
00260     #ifdef CAUDIO_USE_MMGR
00261         // Cleanup the log?
00262 
00263         if (cleanupLogOnFirstRun) doCleanupLogOnFirstRun();
00264 
00265         // Build the buffer
00266 
00267         static char buffer[2048];
00268         va_list ap;
00269         va_start(ap, format);
00270         vsprintf(buffer, format, ap);
00271         va_end(ap);
00272 
00273         // Open the log file
00274 
00275         FILE    *fp = fopen(memoryLogFile, "ab");
00276 
00277         // If you hit this assert, then the memory logger is unable to log information to a file (can't open the file for some
00278         // reason.) You can interrogate the variable 'buffer' to see what was supposed to be logged (but won't be.)
00279         m_assert(fp);
00280 
00281         if (!fp) return;
00282 
00283         // Spit out the data to the log
00284 
00285         fprintf(fp, "%s\r\n", buffer);
00286         fclose(fp);
00287     #endif
00288 }
00289 
00290 
00291 // ---------------------------------------------------------------------------------------------------------------------------------
00292 
00293 static  void    doCleanupLogOnFirstRun()
00294 {
00295         if (cleanupLogOnFirstRun)
00296         {
00297                 unlink(memoryLogFile);
00298                 cleanupLogOnFirstRun = false;
00299 
00300                 // Print a header for the log
00301 
00302                 time_t  t = time(NULL);
00303                 log("--------------------------------------------------------------------------------");
00304                 log("");
00305                 log("      %s - Memory logging file created on %s", memoryLogFile, asctime(localtime(&t)));
00306                 log("--------------------------------------------------------------------------------");
00307                 log("");
00308                 log("This file contains a log of all memory operations performed during the last run.");
00309                 log("");
00310                 log("Interrogate this file to track errors or to help track down memory-related");
00311                 log("issues. You can do this by tracing the allocations performed by a specific owner");
00312                 log("or by tracking a specific address through a series of allocations and");
00313                 log("reallocations.");
00314                 log("");
00315                 log("There is a lot of useful information here which, when used creatively, can be");
00316                 log("extremely helpful.");
00317                 log("");
00318                 log("Note that the following guides are used throughout this file:");
00319                 log("");
00320                 log("   [!] - Error");
00321                 log("   [+] - Allocation");
00322                 log("   [~] - Reallocation");
00323                 log("   [-] - Deallocation");
00324                 log("   [I] - Generic information");
00325                 log("   [F] - Failure induced for the purpose of stress-testing your application");
00326                 log("   [D] - Information used for debugging this memory manager");
00327                 log("");
00328                 log("...so, to find all errors in the file, search for \"[!]\"");
00329                 log("");
00330                 log("--------------------------------------------------------------------------------");
00331         }
00332 }
00333 
00334 // ---------------------------------------------------------------------------------------------------------------------------------
00335 
00336 static  const char      *sourceFileStripper(const char *sourceFile)
00337 {
00338         const char      *ptr = strrchr(sourceFile, '\\');
00339         if (ptr) return ptr + 1;
00340         ptr = strrchr(sourceFile, '/');
00341         if (ptr) return ptr + 1;
00342         return sourceFile;
00343 }
00344 
00345 // ---------------------------------------------------------------------------------------------------------------------------------
00346 
00347 static  const char      *ownerString(const char *sourceFile, const unsigned int sourceLine, const char *sourceFunc)
00348 {
00349         static  char    str[90];
00350         memset(str, 0, sizeof(str));
00351         sprintf(str, "%s(%05d)::%s", sourceFileStripper(sourceFile), sourceLine, sourceFunc);
00352         return str;
00353 }
00354 
00355 // ---------------------------------------------------------------------------------------------------------------------------------
00356 
00357 static  const char      *insertCommas(unsigned int value)
00358 {
00359         static  char    str[30];
00360         memset(str, 0, sizeof(str));
00361 
00362         sprintf(str, "%u", value);
00363         if (strlen(str) > 3)
00364         {
00365                 memmove(&str[strlen(str)-3], &str[strlen(str)-4], 4);
00366                 str[strlen(str) - 4] = ',';
00367         }
00368         if (strlen(str) > 7)
00369         {
00370                 memmove(&str[strlen(str)-7], &str[strlen(str)-8], 8);
00371                 str[strlen(str) - 8] = ',';
00372         }
00373         if (strlen(str) > 11)
00374         {
00375                 memmove(&str[strlen(str)-11], &str[strlen(str)-12], 12);
00376                 str[strlen(str) - 12] = ',';
00377         }
00378 
00379         return str;
00380 }
00381 
00382 // ---------------------------------------------------------------------------------------------------------------------------------
00383 
00384 static  const char      *memorySizeString(unsigned long size)
00385 {
00386         static  char    str[90];
00387              if (size > (1024*1024))    sprintf(str, "%10s (%7.2fM)", insertCommas(size), static_cast<float>(size) / (1024.0f * 1024.0f));
00388         else if (size > 1024)           sprintf(str, "%10s (%7.2fK)", insertCommas(size), static_cast<float>(size) / 1024.0f);
00389         else                            sprintf(str, "%10s bytes     ", insertCommas(size));
00390         return str;
00391 }
00392 
00393 // ---------------------------------------------------------------------------------------------------------------------------------
00394 
00395 static  sAllocUnit      *findAllocUnit(const void *reportedAddress)
00396 {
00397         // Just in case...
00398         m_assert(reportedAddress != NULL);
00399 
00400         // Use the address to locate the hash index. Note that we shift off the lower four bits. This is because most allocated
00401         // addresses will be on four-, eight- or even sixteen-byte boundaries. If we didn't do this, the hash index would not have
00402         // very good coverage.
00403 
00404         unsigned int    hashIndex = (reinterpret_cast<unsigned int>(const_cast<void *>(reportedAddress)) >> 4) & (hashSize - 1);
00405         sAllocUnit      *ptr = hashTable[hashIndex];
00406         while(ptr)
00407         {
00408                 if (ptr->reportedAddress == reportedAddress) return ptr;
00409                 ptr = ptr->next;
00410         }
00411 
00412         return NULL;
00413 }
00414 
00415 // ---------------------------------------------------------------------------------------------------------------------------------
00416 
00417 static  size_t  calculateActualSize(const size_t reportedSize)
00418 {
00419         // 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
00420         // 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
00421         // 8 bytes, which means an int can actually be larger than a long.)
00422 
00423         return reportedSize + paddingSize * sizeof(long) * 2;
00424 }
00425 
00426 // ---------------------------------------------------------------------------------------------------------------------------------
00427 
00428 static  size_t  calculateReportedSize(const size_t actualSize)
00429 {
00430         // 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
00431         // 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
00432         // 8 bytes, which means an int can actually be larger than a long.)
00433 
00434         return actualSize - paddingSize * sizeof(long) * 2;
00435 }
00436 
00437 // ---------------------------------------------------------------------------------------------------------------------------------
00438 
00439 static  void    *calculateReportedAddress(const void *actualAddress)
00440 {
00441         // We allow this...
00442 
00443         if (!actualAddress) return NULL;
00444 
00445         // JUst account for the padding
00446 
00447         return reinterpret_cast<void *>(const_cast<char *>(reinterpret_cast<const char *>(actualAddress) + sizeof(long) * paddingSize));
00448 }
00449 
00450 // ---------------------------------------------------------------------------------------------------------------------------------
00451 
00452 static  void    wipeWithPattern(sAllocUnit *allocUnit, unsigned long pattern, const unsigned int originalReportedSize = 0)
00453 {
00454         // 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
00455         // crash in a differnt place each time, so we specifically DO NOT call srand. If, by chance your program calls srand(),
00456         // you may wish to disable that when running with a random wipe test. This will make any crashes more consistent so they
00457         // can be tracked down easier.
00458 
00459         if (randomWipe)
00460         {
00461                 pattern = ((rand() & 0xff) << 24) | ((rand() & 0xff) << 16) | ((rand() & 0xff) << 8) | (rand() & 0xff);
00462         }
00463 
00464         // -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
00465         // product. So uncomment the following line for releases.
00466         //
00467         // Note that the "alwaysWipeAll" should be turned on for this to have effect, otherwise it won't do much good. But we'll
00468         // leave it this way (as an option) because this does slow things down.
00469 //      pattern = 0;
00470 
00471         // This part of the operation is optional
00472 
00473         if (alwaysWipeAll && allocUnit->reportedSize > originalReportedSize)
00474         {
00475                 // Fill the bulk
00476 
00477                 long    *lptr = reinterpret_cast<long *>(reinterpret_cast<char *>(allocUnit->reportedAddress) + originalReportedSize);
00478                 int     length = static_cast<int>(allocUnit->reportedSize - originalReportedSize);
00479                 int     i;
00480                 for (i = 0; i < (length >> 2); i++, lptr++)
00481                 {
00482                         *lptr = pattern;
00483                 }
00484 
00485                 // Fill the remainder
00486 
00487                 unsigned int    shiftCount = 0;
00488                 char            *cptr = reinterpret_cast<char *>(lptr);
00489                 for (i = 0; i < (length & 0x3); i++, cptr++, shiftCount += 8)
00490                 {
00491                         *cptr = static_cast<char>((pattern & (0xff << shiftCount)) >> shiftCount);
00492                 }
00493         }
00494 
00495         // Write in the prefix/postfix bytes
00496 
00497         long            *pre = reinterpret_cast<long *>(allocUnit->actualAddress);
00498         long            *post = reinterpret_cast<long *>(reinterpret_cast<char *>(allocUnit->actualAddress) + allocUnit->actualSize - paddingSize * sizeof(long));
00499         for (unsigned int i = 0; i < paddingSize; i++, pre++, post++)
00500         {
00501                 *pre = prefixPattern;
00502                 *post = postfixPattern;
00503         }
00504 }
00505 
00506 // ---------------------------------------------------------------------------------------------------------------------------------
00507 
00508 static  void    dumpAllocations(FILE *fp)
00509 {
00510         fprintf(fp, "Alloc.   Addr       Size       Addr       Size                        BreakOn BreakOn              \r\n");
00511         fprintf(fp, "Number Reported   Reported    Actual     Actual     Unused    Method  Dealloc Realloc Allocated by \r\n");
00512         fprintf(fp, "------ ---------- ---------- ---------- ---------- ---------- -------- ------- ------- --------------------------------------------------- \r\n");
00513 
00514 
00515         for (unsigned int i = 0; i < hashSize; i++)
00516         {
00517                 sAllocUnit *ptr = hashTable[i];
00518                 while(ptr)
00519                 {
00520                         fprintf(fp, "%06d 0x%08X 0x%08X 0x%08X 0x%08X 0x%08X %-8s    %c       %c    %s\r\n",
00521                                 ptr->allocationNumber,
00522                                 reinterpret_cast<unsigned int>(ptr->reportedAddress), ptr->reportedSize,
00523                                 reinterpret_cast<unsigned int>(ptr->actualAddress), ptr->actualSize,
00524                                 m_calcUnused(ptr),
00525                                 allocationTypes[ptr->allocationType],
00526                                 ptr->breakOnDealloc ? 'Y':'N',
00527                                 ptr->breakOnRealloc ? 'Y':'N',
00528                                 ownerString(ptr->sourceFile, ptr->sourceLine, ptr->sourceFunc));
00529                         ptr = ptr->next;
00530                 }
00531         }
00532 }
00533 
00534 // ---------------------------------------------------------------------------------------------------------------------------------
00535 
00536 static  void    dumpLeakReport()
00537 {
00538     #ifdef CAUDIO_USE_MMGR
00539         // Open the report file
00540 
00541         FILE    *fp = fopen(memoryLeakLogFile, "w+b");
00542 
00543         // If you hit this assert, then the memory report generator is unable to log information to a file (can't open the file for
00544         // some reason.)
00545         m_assert(fp);
00546         if (!fp) return;
00547 
00548         // Any leaks?
00549 
00550         // Header
00551 
00552         static  char    timeString[25];
00553         memset(timeString, 0, sizeof(timeString));
00554         time_t  t = time(NULL);
00555         struct  tm *tme = localtime(&t);
00556         fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
00557         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);
00558         fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
00559         fprintf(fp, "\r\n");
00560         fprintf(fp, "\r\n");
00561         if (stats.totalAllocUnitCount)
00562         {
00563                 fprintf(fp, "%d memory leak%s found:\r\n", stats.totalAllocUnitCount, stats.totalAllocUnitCount == 1 ? "":"s");
00564         }
00565         else
00566         {
00567                 fprintf(fp, "Congratulations! No memory leaks found!\r\n");
00568 
00569                 // We can finally free up our own memory allocations
00570 
00571                 if (reservoirBuffer)
00572                 {
00573                         for (unsigned int i = 0; i < reservoirBufferSize; i++)
00574                         {
00575                                 free(reservoirBuffer[i]);
00576                         }
00577                         free(reservoirBuffer);
00578                         reservoirBuffer = 0;
00579                         reservoirBufferSize = 0;
00580                         reservoir = NULL;
00581                 }
00582         }
00583         fprintf(fp, "\r\n");
00584 
00585         if (stats.totalAllocUnitCount)
00586         {
00587                 dumpAllocations(fp);
00588         }
00589 
00590         fclose(fp);
00591         #endif
00592 }
00593 
00594 // ---------------------------------------------------------------------------------------------------------------------------------
00595 // We use a static class to let us know when we're in the midst of static deinitialization
00596 // ---------------------------------------------------------------------------------------------------------------------------------
00597 
00598 class   MemStaticTimeTracker
00599 {
00600 public:
00601         MemStaticTimeTracker() {doCleanupLogOnFirstRun();}
00602         ~MemStaticTimeTracker() {staticDeinitTime = true; dumpLeakReport();}
00603 };
00604 static  MemStaticTimeTracker    mstt;
00605 
00606 // ---------------------------------------------------------------------------------------------------------------------------------
00607 // -DOC- Flags & options -- Call these routines to enable/disable the following options
00608 // ---------------------------------------------------------------------------------------------------------------------------------
00609 
00610 bool    &m_alwaysValidateAll()
00611 {
00612         // Force a validation of all allocation units each time we enter this software
00613         return alwaysValidateAll;
00614 }
00615 
00616 // ---------------------------------------------------------------------------------------------------------------------------------
00617 
00618 bool    &m_alwaysLogAll()
00619 {
00620         // Force a log of every allocation & deallocation into memory.log
00621         return alwaysLogAll;
00622 }
00623 
00624 // ---------------------------------------------------------------------------------------------------------------------------------
00625 
00626 bool    &m_alwaysWipeAll()
00627 {
00628         // Force this software to always wipe memory with a pattern when it is being allocated/dallocated
00629         return alwaysWipeAll;
00630 }
00631 
00632 // ---------------------------------------------------------------------------------------------------------------------------------
00633 
00634 bool    &m_randomeWipe()
00635 {
00636         // Force this software to use a random pattern when wiping memory -- good for stress testing
00637         return randomWipe;
00638 }
00639 
00640 // ---------------------------------------------------------------------------------------------------------------------------------
00641 // -DOC- Simply call this routine with the address of an allocated block of RAM, to cause it to force a breakpoint when it is
00642 // reallocated.
00643 // ---------------------------------------------------------------------------------------------------------------------------------
00644 
00645 bool    &m_breakOnRealloc(void *reportedAddress)
00646 {
00647         // Locate the existing allocation unit
00648 
00649         sAllocUnit      *au = findAllocUnit(reportedAddress);
00650 
00651         // If you hit this assert, you tried to set a breakpoint on reallocation for an address that doesn't exist. Interrogate the
00652         // stack frame or the variable 'au' to see which allocation this is.
00653         m_assert(au != NULL);
00654 
00655         // If you hit this assert, you tried to set a breakpoint on reallocation for an address that wasn't allocated in a way that
00656         // is compatible with reallocation.
00657         m_assert(au->allocationType == m_alloc_malloc ||
00658                  au->allocationType == m_alloc_calloc ||
00659                  au->allocationType == m_alloc_realloc);
00660 
00661         return au->breakOnRealloc;
00662 }
00663 
00664 // ---------------------------------------------------------------------------------------------------------------------------------
00665 // -DOC- Simply call this routine with the address of an allocated block of RAM, to cause it to force a breakpoint when it is
00666 // deallocated.
00667 // ---------------------------------------------------------------------------------------------------------------------------------
00668 
00669 bool    &m_breakOnDealloc(void *reportedAddress)
00670 {
00671         // Locate the existing allocation unit
00672 
00673         sAllocUnit      *au = findAllocUnit(reportedAddress);
00674 
00675         // If you hit this assert, you tried to set a breakpoint on deallocation for an address that doesn't exist. Interrogate the
00676         // stack frame or the variable 'au' to see which allocation this is.
00677         m_assert(au != NULL);
00678 
00679         return au->breakOnDealloc;
00680 }
00681 
00682 // ---------------------------------------------------------------------------------------------------------------------------------
00683 // -DOC- When tracking down a difficult bug, use this routine to force a breakpoint on a specific allocation count
00684 // ---------------------------------------------------------------------------------------------------------------------------------
00685 
00686 void    m_breakOnAllocation(unsigned int count)
00687 {
00688         breakOnAllocationCount = count;
00689 }
00690 
00691 // ---------------------------------------------------------------------------------------------------------------------------------
00692 // Used by the macros
00693 // ---------------------------------------------------------------------------------------------------------------------------------
00694 
00695 void    m_setOwner(const char *file, const unsigned int line, const char *func)
00696 {
00697         // You're probably wondering about this...
00698         //
00699         // It's important for this memory manager to primarily work with global new/delete in their original forms (i.e. with
00700         // no extra parameters.) In order to do this, we use macros that call this function prior to operators new & delete. This
00701         // is fine... usually. Here's what actually happens when you use this macro to delete an object:
00702         //
00703         // m_setOwner(__FILE__, __LINE__, __FUNCTION__) --> object::~object() --> delete
00704         //
00705         // Note that the compiler inserts a call to the object's destructor just prior to calling our overridden operator delete.
00706         // But what happens when we delete an object whose destructor deletes another object, whose desctuctor deletes another
00707         // object? Here's a diagram (indentation follows stack depth):
00708         //
00709         // m_setOwner(...) -> ~obj1()                          // original call to delete obj1
00710         //     m_setOwner(...) -> ~obj2()                      // obj1's destructor deletes obj2
00711         //         m_setOwner(...) -> ~obj3()                  // obj2's destructor deletes obj3
00712         //             ...                                     // obj3's destructor just does some stuff
00713         //         delete                                      // back in obj2's destructor, we call delete
00714         //     delete                                          // back in obj1's destructor, we call delete
00715         // delete                                              // back to our original call, we call delete
00716         //
00717         // Because m_setOwner() just sets up some static variables (below) it's important that each call to m_setOwner() and
00718         // successive calls to new/delete alternate. However, in this case, three calls to m_setOwner() happen in succession
00719         // followed by three calls to delete in succession (with a few calls to destructors mixed in for fun.) This means that
00720         // only the final call to delete (in this chain of events) will have the proper reporting, and the first two in the chain
00721         // will not have ANY owner-reporting information. The deletes will still work fine, we just won't know who called us.
00722         //
00723         // "Then build a stack, my friend!" you might think... but it's a very common thing that people will be working with third-
00724         // party libraries (including MFC under Windows) which is not compiled with this memory manager's macros. In those cases,
00725         // m_setOwner() is never called, and rightfully should not have the proper trace-back information. So if one of the
00726         // destructors in the chain ends up being a call to a delete from a non-mmgr-compiled library, the stack will get confused.
00727         //
00728         // I've been unable to find a solution to this problem, but at least we can detect it and report the data before we
00729         // lose it. That's what this is all about. It makes it somewhat confusing to read in the logs, but at least ALL the
00730         // information is present...
00731         //
00732         // There's a caveat here... The compiler is not required to call operator delete if the value being deleted is NULL.
00733         // In this case, any call to delete with a NULL will sill call m_setOwner(), which will make m_setOwner() think that
00734         // there is a destructor chain becuase we setup the variables, but nothing gets called to clear them. Because of this
00735         // we report a "Possible destructor chain".
00736         //
00737         // Thanks to J. Woznack (from Kodiak Interactive Software Studios -- www.kodiakgames.com) for pointing this out.
00738 
00739         if (sourceLine && alwaysLogAll)
00740         {
00741                 log("[I] NOTE! Possible destructor chain: previous owner is %s", ownerString(sourceFile, sourceLine, sourceFunc));
00742         }
00743 
00744         // Okay... save this stuff off so we can keep track of the caller
00745 
00746         sourceFile = file;
00747         sourceLine = line;
00748         sourceFunc = func;
00749 }
00750 
00751 // ---------------------------------------------------------------------------------------------------------------------------------
00752 
00753 static  void    resetGlobals()
00754 {
00755         sourceFile = "??";
00756         sourceLine = 0;
00757         sourceFunc = "??";
00758 }
00759 
00760 // ---------------------------------------------------------------------------------------------------------------------------------
00761 // Global new/new[]
00762 //
00763 // These are the standard new/new[] operators. They are merely interface functions that operate like normal new/new[], but use our
00764 // memory tracking routines.
00765 // ---------------------------------------------------------------------------------------------------------------------------------
00766 
00767 void    *operator new(size_t reportedSize)
00768 {
00769         #ifdef TEST_MEMORY_MANAGER
00770         log("[D] ENTER: new");
00771         #endif
00772 
00773         // Save these off...
00774 
00775         const   char            *file = sourceFile;
00776         const   unsigned int    line = sourceLine;
00777         const   char            *func = sourceFunc;
00778 
00779         // ANSI says: allocation requests of 0 bytes will still return a valid value
00780 
00781         if (reportedSize == 0) reportedSize = 1;
00782 
00783         // ANSI says: loop continuously because the error handler could possibly free up some memory
00784 
00785         for(;;)
00786         {
00787                 // Try the allocation
00788 
00789                 void    *ptr = m_allocator(file, line, func, m_alloc_new, reportedSize);
00790                 if (ptr)
00791                 {
00792                         #ifdef TEST_MEMORY_MANAGER
00793                         log("[D] EXIT : new");
00794                         #endif
00795                         return ptr;
00796                 }
00797 
00798                 // There isn't a way to determine the new handler, except through setting it. So we'll just set it to NULL, then
00799                 // set it back again.
00800 
00801                 std::new_handler        nh = std::set_new_handler(0);
00802                 std::set_new_handler(nh);
00803 
00804                 // If there is an error handler, call it
00805 
00806                 if (nh)
00807                 {
00808                         (*nh)();
00809                 }
00810 
00811                 // Otherwise, throw the exception
00812 
00813                 else
00814                 {
00815                         #ifdef TEST_MEMORY_MANAGER
00816                         log("[D] EXIT : new");
00817                         #endif
00818                         throw std::bad_alloc();
00819                 }
00820         }
00821 }
00822 
00823 // ---------------------------------------------------------------------------------------------------------------------------------
00824 
00825 void    *operator new[](size_t reportedSize)
00826 {
00827         #ifdef TEST_MEMORY_MANAGER
00828         log("[D] ENTER: new[]");
00829         #endif
00830 
00831         // Save these off...
00832 
00833         const   char            *file = sourceFile;
00834         const   unsigned int    line = sourceLine;
00835         const   char            *func = sourceFunc;
00836 
00837         // The ANSI standard says that allocation requests of 0 bytes will still return a valid value
00838 
00839         if (reportedSize == 0) reportedSize = 1;
00840 
00841         // ANSI says: loop continuously because the error handler could possibly free up some memory
00842 
00843         for(;;)
00844         {
00845                 // Try the allocation
00846 
00847                 void    *ptr = m_allocator(file, line, func, m_alloc_new_array, reportedSize);
00848                 if (ptr)
00849                 {
00850                         #ifdef TEST_MEMORY_MANAGER
00851                         log("[D] EXIT : new[]");
00852                         #endif
00853                         return ptr;
00854                 }
00855 
00856                 // There isn't a way to determine the new handler, except through setting it. So we'll just set it to NULL, then
00857                 // set it back again.
00858 
00859                 std::new_handler        nh = std::set_new_handler(0);
00860                 std::set_new_handler(nh);
00861 
00862                 // If there is an error handler, call it
00863 
00864                 if (nh)
00865                 {
00866                         (*nh)();
00867                 }
00868 
00869                 // Otherwise, throw the exception
00870 
00871                 else
00872                 {
00873                         #ifdef TEST_MEMORY_MANAGER
00874                         log("[D] EXIT : new[]");
00875                         #endif
00876                         throw std::bad_alloc();
00877                 }
00878         }
00879 }
00880 
00881 // ---------------------------------------------------------------------------------------------------------------------------------
00882 // Other global new/new[]
00883 //
00884 // These are the standard new/new[] operators as used by Microsoft's memory tracker. We don't want them interfering with our memory
00885 // tracking efforts. Like the previous versions, these are merely interface functions that operate like normal new/new[], but use
00886 // our memory tracking routines.
00887 // ---------------------------------------------------------------------------------------------------------------------------------
00888 
00889 void    *operator new(size_t reportedSize, const char *sourceFile, int sourceLine)
00890 {
00891         #ifdef TEST_MEMORY_MANAGER
00892         log("[D] ENTER: new");
00893         #endif
00894 
00895         // The ANSI standard says that allocation requests of 0 bytes will still return a valid value
00896 
00897         if (reportedSize == 0) reportedSize = 1;
00898 
00899         // ANSI says: loop continuously because the error handler could possibly free up some memory
00900 
00901         for(;;)
00902         {
00903                 // Try the allocation
00904 
00905                 void    *ptr = m_allocator(sourceFile, sourceLine, "??", m_alloc_new, reportedSize);
00906                 if (ptr)
00907                 {
00908                         #ifdef TEST_MEMORY_MANAGER
00909                         log("[D] EXIT : new");
00910                         #endif
00911                         return ptr;
00912                 }
00913 
00914                 // There isn't a way to determine the new handler, except through setting it. So we'll just set it to NULL, then
00915                 // set it back again.
00916 
00917                 std::new_handler        nh = std::set_new_handler(0);
00918                 std::set_new_handler(nh);
00919 
00920                 // If there is an error handler, call it
00921 
00922                 if (nh)
00923                 {
00924                         (*nh)();
00925                 }
00926 
00927                 // Otherwise, throw the exception
00928 
00929                 else
00930                 {
00931                         #ifdef TEST_MEMORY_MANAGER
00932                         log("[D] EXIT : new");
00933                         #endif
00934                         throw std::bad_alloc();
00935                 }
00936         }
00937 }
00938 
00939 // ---------------------------------------------------------------------------------------------------------------------------------
00940 
00941 void    *operator new[](size_t reportedSize, const char *sourceFile, int sourceLine)
00942 {
00943         #ifdef TEST_MEMORY_MANAGER
00944         log("[D] ENTER: new[]");
00945         #endif
00946 
00947         // The ANSI standard says that allocation requests of 0 bytes will still return a valid value
00948 
00949         if (reportedSize == 0) reportedSize = 1;
00950 
00951         // ANSI says: loop continuously because the error handler could possibly free up some memory
00952 
00953         for(;;)
00954         {
00955                 // Try the allocation
00956 
00957                 void    *ptr = m_allocator(sourceFile, sourceLine, "??", m_alloc_new_array, reportedSize);
00958                 if (ptr)
00959                 {
00960                         #ifdef TEST_MEMORY_MANAGER
00961                         log("[D] EXIT : new[]");
00962                         #endif
00963                         return ptr;
00964                 }
00965 
00966                 // There isn't a way to determine the new handler, except through setting it. So we'll just set it to NULL, then
00967                 // set it back again.
00968 
00969                 std::new_handler        nh = std::set_new_handler(0);
00970                 std::set_new_handler(nh);
00971 
00972                 // If there is an error handler, call it
00973 
00974                 if (nh)
00975                 {
00976                         (*nh)();
00977                 }
00978 
00979                 // Otherwise, throw the exception
00980 
00981                 else
00982                 {
00983                         #ifdef TEST_MEMORY_MANAGER
00984                         log("[D] EXIT : new[]");
00985                         #endif
00986                         throw std::bad_alloc();
00987                 }
00988         }
00989 }
00990 
00991 // ---------------------------------------------------------------------------------------------------------------------------------
00992 // Global delete/delete[]
00993 //
00994 // These are the standard delete/delete[] operators. They are merely interface functions that operate like normal delete/delete[],
00995 // but use our memory tracking routines.
00996 // ---------------------------------------------------------------------------------------------------------------------------------
00997 
00998 void    operator delete(void *reportedAddress)
00999 {
01000         #ifdef TEST_MEMORY_MANAGER
01001         log("[D] ENTER: delete");
01002         #endif
01003 
01004         // ANSI says: delete & delete[] allow NULL pointers (they do nothing)
01005 
01006         if (reportedAddress) m_deallocator(sourceFile, sourceLine, sourceFunc, m_alloc_delete, reportedAddress);
01007         else if (alwaysLogAll) log("[-] ----- %8s of NULL                      by %s", allocationTypes[m_alloc_delete], ownerString(sourceFile, sourceLine, sourceFunc));
01008 
01009         // Resetting the globals insures that if at some later time, somebody calls our memory manager from an unknown
01010         // source (i.e. they didn't include our H file) then we won't think it was the last allocation.
01011 
01012         resetGlobals();
01013 
01014         #ifdef TEST_MEMORY_MANAGER
01015         log("[D] EXIT : delete");
01016         #endif
01017 }
01018 
01019 // ---------------------------------------------------------------------------------------------------------------------------------
01020 
01021 void    operator delete[](void *reportedAddress)
01022 {
01023         #ifdef TEST_MEMORY_MANAGER
01024         log("[D] ENTER: delete[]");
01025         #endif
01026 
01027         // ANSI says: delete & delete[] allow NULL pointers (they do nothing)
01028 
01029         if (reportedAddress) m_deallocator(sourceFile, sourceLine, sourceFunc, m_alloc_delete_array, reportedAddress);
01030         else if (alwaysLogAll)
01031                 log("[-] ----- %8s of NULL                      by %s", allocationTypes[m_alloc_delete_array], ownerString(sourceFile, sourceLine, sourceFunc));
01032 
01033         // Resetting the globals insures that if at some later time, somebody calls our memory manager from an unknown
01034         // source (i.e. they didn't include our H file) then we won't think it was the last allocation.
01035 
01036         resetGlobals();
01037 
01038         #ifdef TEST_MEMORY_MANAGER
01039         log("[D] EXIT : delete[]");
01040         #endif
01041 }
01042 
01043 // ---------------------------------------------------------------------------------------------------------------------------------
01044 // Allocate memory and track it
01045 // ---------------------------------------------------------------------------------------------------------------------------------
01046 
01047 void    *m_allocator(const char *sourceFile, const unsigned int sourceLine, const char *sourceFunc, const unsigned int allocationType, const size_t reportedSize)
01048 {
01049         try
01050         {
01051                 #ifdef TEST_MEMORY_MANAGER
01052                 log("[D] ENTER: m_allocator()");
01053                 #endif
01054 
01055                 // Increase our allocation count
01056 
01057                 currentAllocationCount++;
01058 
01059                 // Log the request
01060 
01061                 if (alwaysLogAll) log("[+] %05d %8s of size 0x%08X(%08d) by %s", currentAllocationCount, allocationTypes[allocationType], reportedSize, reportedSize, ownerString(sourceFile, sourceLine, sourceFunc));
01062 
01063                 // If you hit this assert, you requested a breakpoint on a specific allocation count
01064                 m_assert(currentAllocationCount != breakOnAllocationCount);
01065 
01066                 // If necessary, grow the reservoir of unused allocation units
01067 
01068                 if (!reservoir)
01069                 {
01070                         // Allocate 256 reservoir elements
01071 
01072                         reservoir = (sAllocUnit *) malloc(sizeof(sAllocUnit) * 256);
01073 
01074                         // If you hit this assert, then the memory manager failed to allocate internal memory for tracking the
01075                         // allocations
01076                         m_assert(reservoir != NULL);
01077 
01078                         // Danger Will Robinson!
01079 
01080                         if (reservoir == NULL) throw "Unable to allocate RAM for internal memory tracking data";
01081 
01082                         // Build a linked-list of the elements in our reservoir
01083 
01084                         memset(reservoir, 0, sizeof(sAllocUnit) * 256);
01085                         for (unsigned int i = 0; i < 256 - 1; i++)
01086                         {
01087                                 reservoir[i].next = &reservoir[i+1];
01088                         }
01089 
01090                         // Add this address to our reservoirBuffer so we can free it later
01091 
01092                         sAllocUnit      **temp = (sAllocUnit **) realloc(reservoirBuffer, (reservoirBufferSize + 1) * sizeof(sAllocUnit *));
01093                         m_assert(temp);
01094                         if (temp)
01095                         {
01096                                 reservoirBuffer = temp;
01097                                 reservoirBuffer[reservoirBufferSize++] = reservoir;
01098                         }
01099                 }
01100 
01101                 // Logical flow says this should never happen...
01102                 m_assert(reservoir != NULL);
01103 
01104                 // Grab a new allocaton unit from the front of the reservoir
01105 
01106                 sAllocUnit      *au = reservoir;
01107                 reservoir = au->next;
01108 
01109                 // Populate it with some real data
01110 
01111                 memset(au, 0, sizeof(sAllocUnit));
01112                 au->actualSize        = calculateActualSize(reportedSize);
01113                 #ifdef RANDOM_FAILURE
01114                 double  a = rand();
01115                 double  b = RAND_MAX / 100.0 * RANDOM_FAILURE;
01116                 if (a > b)
01117                 {
01118                         au->actualAddress = malloc(au->actualSize);
01119                 }
01120                 else
01121                 {
01122                         log("[F] Random faiure");
01123                         au->actualAddress = NULL;
01124                 }
01125                 #else
01126                 au->actualAddress     = malloc(au->actualSize);
01127                 #endif
01128                 au->reportedSize      = reportedSize;
01129                 au->reportedAddress   = calculateReportedAddress(au->actualAddress);
01130                 au->allocationType    = allocationType;
01131                 au->sourceLine        = sourceLine;
01132                 au->allocationNumber  = currentAllocationCount;
01133                 if (sourceFile) strncpy(au->sourceFile, sourceFileStripper(sourceFile), sizeof(au->sourceFile) - 1);
01134                 else            strcpy (au->sourceFile, "??");
01135                 if (sourceFunc) strncpy(au->sourceFunc, sourceFunc, sizeof(au->sourceFunc) - 1);
01136                 else            strcpy (au->sourceFunc, "??");
01137 
01138                 // We don't want to assert with random failures, because we want the application to deal with them.
01139 
01140                 #ifndef RANDOM_FAILURE
01141                 // If you hit this assert, then the requested allocation simply failed (you're out of memory.) Interrogate the
01142                 // variable 'au' or the stack frame to see what you were trying to do.
01143                 m_assert(au->actualAddress != NULL);
01144                 #endif
01145 
01146                 if (au->actualAddress == NULL)
01147                 {
01148                         throw "Request for allocation failed. Out of memory.";
01149                 }
01150 
01151                 // If you hit this assert, then this allocation was made from a source that isn't setup to use this memory tracking
01152                 // software, use the stack frame to locate the source and include our H file.
01153                 m_assert(allocationType != m_alloc_unknown);
01154 
01155                 // Insert the new allocation into the hash table
01156 
01157                 unsigned int    hashIndex = (reinterpret_cast<unsigned int>(au->reportedAddress) >> 4) & (hashSize - 1);
01158                 if (hashTable[hashIndex]) hashTable[hashIndex]->prev = au;
01159                 au->next = hashTable[hashIndex];
01160                 au->prev = NULL;
01161                 hashTable[hashIndex] = au;
01162 
01163                 // Account for the new allocatin unit in our stats
01164 
01165                 stats.totalReportedMemory += static_cast<unsigned int>(au->reportedSize);
01166                 stats.totalActualMemory   += static_cast<unsigned int>(au->actualSize);
01167                 stats.totalAllocUnitCount++;
01168                 if (stats.totalReportedMemory > stats.peakReportedMemory) stats.peakReportedMemory = stats.totalReportedMemory;
01169                 if (stats.totalActualMemory   > stats.peakActualMemory)   stats.peakActualMemory   = stats.totalActualMemory;
01170                 if (stats.totalAllocUnitCount > stats.peakAllocUnitCount) stats.peakAllocUnitCount = stats.totalAllocUnitCount;
01171                 stats.accumulatedReportedMemory += static_cast<unsigned int>(au->reportedSize);
01172                 stats.accumulatedActualMemory += static_cast<unsigned int>(au->actualSize);
01173                 stats.accumulatedAllocUnitCount++;
01174 
01175                 // Prepare the allocation unit for use (wipe it with recognizable garbage)
01176 
01177                 wipeWithPattern(au, unusedPattern);
01178 
01179                 // calloc() expects the reported memory address range to be filled with 0's
01180 
01181                 if (allocationType == m_alloc_calloc)
01182                 {
01183                         memset(au->reportedAddress, 0, au->reportedSize);
01184                 }
01185 
01186                 // Validate every single allocated unit in memory
01187 
01188                 if (alwaysValidateAll) m_validateAllAllocUnits();
01189 
01190                 // Log the result
01191 
01192                 if (alwaysLogAll) log("[+] ---->             addr 0x%08X", reinterpret_cast<unsigned int>(au->reportedAddress));
01193 
01194                 // Resetting the globals insures that if at some later time, somebody calls our memory manager from an unknown
01195                 // source (i.e. they didn't include our H file) then we won't think it was the last allocation.
01196 
01197                 resetGlobals();
01198 
01199                 // Return the (reported) address of the new allocation unit
01200 
01201                 #ifdef TEST_MEMORY_MANAGER
01202                 log("[D] EXIT : m_allocator()");
01203                 #endif
01204 
01205                 return au->reportedAddress;
01206         }
01207         catch(const char *err)
01208         {
01209                 // Deal with the errors
01210 
01211                 log("[!] %s", err);
01212                 resetGlobals();
01213 
01214                 #ifdef TEST_MEMORY_MANAGER
01215                 log("[D] EXIT : m_allocator()");
01216                 #endif
01217 
01218                 return NULL;
01219         }
01220 }
01221 
01222 // ---------------------------------------------------------------------------------------------------------------------------------
01223 // Reallocate memory and track it
01224 // ---------------------------------------------------------------------------------------------------------------------------------
01225 
01226 void    *m_reallocator(const char *sourceFile, const unsigned int sourceLine, const char *sourceFunc, const unsigned int reallocationType, const size_t reportedSize, void *reportedAddress)
01227 {
01228         try
01229         {
01230                 #ifdef TEST_MEMORY_MANAGER
01231                 log("[D] ENTER: m_reallocator()");
01232                 #endif
01233 
01234                 // Calling realloc with a NULL should force same operations as a malloc
01235 
01236                 if (!reportedAddress)
01237                 {
01238                         return m_allocator(sourceFile, sourceLine, sourceFunc, reallocationType, reportedSize);
01239                 }
01240 
01241                 // Increase our allocation count
01242 
01243                 currentAllocationCount++;
01244 
01245                 // If you hit this assert, you requested a breakpoint on a specific allocation count
01246                 m_assert(currentAllocationCount != breakOnAllocationCount);
01247 
01248                 // Log the request
01249 
01250                 if (alwaysLogAll) log("[~] %05d %8s of size 0x%08X(%08d) by %s", currentAllocationCount, allocationTypes[reallocationType], reportedSize, reportedSize, ownerString(sourceFile, sourceLine, sourceFunc));
01251 
01252                 // Locate the existing allocation unit
01253 
01254                 sAllocUnit      *au = findAllocUnit(reportedAddress);
01255 
01256                 // If you hit this assert, you tried to reallocate RAM that wasn't allocated by this memory manager.
01257                 m_assert(au != NULL);
01258                 if (au == NULL) throw "Request to reallocate RAM that was never allocated";
01259 
01260                 // If you hit this assert, then the allocation unit that is about to be reallocated is damaged. But you probably
01261                 // already know that from a previous assert you should have seen in validateAllocUnit() :)
01262                 m_assert(m_validateAllocUnit(au));
01263 
01264                 // If you hit this assert, then this reallocation was made from a source that isn't setup to use this memory
01265                 // tracking software, use the stack frame to locate the source and include our H file.
01266                 m_assert(reallocationType != m_alloc_unknown);
01267 
01268                 // If you hit this assert, you were trying to reallocate RAM that was not allocated in a way that is compatible with
01269                 // realloc. In other words, you have a allocation/reallocation mismatch.
01270                 m_assert(au->allocationType == m_alloc_malloc ||
01271                          au->allocationType == m_alloc_calloc ||
01272                          au->allocationType == m_alloc_realloc);
01273 
01274                 // If you hit this assert, then the "break on realloc" flag for this allocation unit is set (and will continue to be
01275                 // set until you specifically shut it off. Interrogate the 'au' variable to determine information about this
01276                 // allocation unit.
01277                 m_assert(au->breakOnRealloc == false);
01278 
01279                 // Keep track of the original size
01280 
01281                 unsigned int    originalReportedSize = static_cast<unsigned int>(au->reportedSize);
01282 
01283                 if (alwaysLogAll) log("[~] ---->             from 0x%08X(%08d)", originalReportedSize, originalReportedSize);
01284 
01285                 // Do the reallocation
01286 
01287                 void    *oldReportedAddress = reportedAddress;
01288                 size_t  newActualSize = calculateActualSize(reportedSize);
01289                 void    *newActualAddress = NULL;
01290                 #ifdef RANDOM_FAILURE
01291                 double  a = rand();
01292                 double  b = RAND_MAX / 100.0 * RANDOM_FAILURE;
01293                 if (a > b)
01294                 {
01295                         newActualAddress = realloc(au->actualAddress, newActualSize);
01296                 }
01297                 else
01298                 {
01299                         log("[F] Random faiure");
01300                 }
01301                 #else
01302                 newActualAddress = realloc(au->actualAddress, newActualSize);
01303                 #endif
01304 
01305                 // We don't want to assert with random failures, because we want the application to deal with them.
01306 
01307                 #ifndef RANDOM_FAILURE
01308                 // If you hit this assert, then the requested allocation simply failed (you're out of memory) Interrogate the
01309                 // variable 'au' to see the original allocation. You can also query 'newActualSize' to see the amount of memory
01310                 // trying to be allocated. Finally, you can query 'reportedSize' to see how much memory was requested by the caller.
01311                 m_assert(newActualAddress);
01312                 #endif
01313 
01314                 if (!newActualAddress) throw "Request for reallocation failed. Out of memory.";
01315 
01316                 // Remove this allocation from our stats (we'll add the new reallocation again later)
01317 
01318                 stats.totalReportedMemory -= static_cast<unsigned int>(au->reportedSize);
01319                 stats.totalActualMemory   -= static_cast<unsigned int>(au->actualSize);
01320 
01321                 // Update the allocation with the new information
01322 
01323                 au->actualSize        = newActualSize;
01324                 au->actualAddress     = newActualAddress;
01325                 au->reportedSize      = calculateReportedSize(newActualSize);
01326                 au->reportedAddress   = calculateReportedAddress(newActualAddress);
01327                 au->allocationType    = reallocationType;
01328                 au->sourceLine        = sourceLine;
01329                 au->allocationNumber  = currentAllocationCount;
01330                 if (sourceFile) strncpy(au->sourceFile, sourceFileStripper(sourceFile), sizeof(au->sourceFile) - 1);
01331                 else            strcpy (au->sourceFile, "??");
01332                 if (sourceFunc) strncpy(au->sourceFunc, sourceFunc, sizeof(au->sourceFunc) - 1);
01333                 else            strcpy (au->sourceFunc, "??");
01334 
01335                 // The reallocation may cause the address to change, so we should relocate our allocation unit within the hash table
01336 
01337                 unsigned int    hashIndex = static_cast<unsigned int>(-1);
01338                 if (oldReportedAddress != au->reportedAddress)
01339                 {
01340                         // Remove this allocation unit from the hash table
01341 
01342                         {
01343                                 unsigned int    hashIndex = (reinterpret_cast<unsigned int>(oldReportedAddress) >> 4) & (hashSize - 1);
01344                                 if (hashTable[hashIndex] == au)
01345                                 {
01346                                         hashTable[hashIndex] = hashTable[hashIndex]->next;
01347                                 }
01348                                 else
01349                                 {
01350                                         if (au->prev)   au->prev->next = au->next;
01351                                         if (au->next)   au->next->prev = au->prev;
01352                                 }
01353                         }
01354 
01355                         // Re-insert it back into the hash table
01356 
01357                         hashIndex = (reinterpret_cast<unsigned int>(au->reportedAddress) >> 4) & (hashSize - 1);
01358                         if (hashTable[hashIndex]) hashTable[hashIndex]->prev = au;
01359                         au->next = hashTable[hashIndex];
01360                         au->prev = NULL;
01361                         hashTable[hashIndex] = au;
01362                 }
01363 
01364                 // Account for the new allocatin unit in our stats
01365 
01366                 stats.totalReportedMemory += static_cast<unsigned int>(au->reportedSize);
01367                 stats.totalActualMemory   += static_cast<unsigned int>(au->actualSize);
01368                 if (stats.totalReportedMemory > stats.peakReportedMemory) stats.peakReportedMemory = stats.totalReportedMemory;
01369                 if (stats.totalActualMemory   > stats.peakActualMemory)   stats.peakActualMemory   = stats.totalActualMemory;
01370                 int     deltaReportedSize = static_cast<int>(reportedSize - originalReportedSize);
01371                 if (deltaReportedSize > 0)
01372                 {
01373                         stats.accumulatedReportedMemory += deltaReportedSize;
01374                         stats.accumulatedActualMemory += deltaReportedSize;
01375                 }
01376 
01377                 // Prepare the allocation unit for use (wipe it with recognizable garbage)
01378 
01379                 wipeWithPattern(au, unusedPattern, originalReportedSize);
01380 
01381                 // If you hit this assert, then something went wrong, because the allocation unit was properly validated PRIOR to
01382                 // the reallocation. This should not happen.
01383                 m_assert(m_validateAllocUnit(au));
01384 
01385                 // Validate every single allocated unit in memory
01386 
01387                 if (alwaysValidateAll) m_validateAllAllocUnits();
01388 
01389                 // Log the result
01390 
01391                 if (alwaysLogAll) log("[~] ---->             addr 0x%08X", reinterpret_cast<unsigned int>(au->reportedAddress));
01392 
01393                 // Resetting the globals insures that if at some later time, somebody calls our memory manager from an unknown
01394                 // source (i.e. they didn't include our H file) then we won't think it was the last allocation.
01395 
01396                 resetGlobals();
01397 
01398                 // Return the (reported) address of the new allocation unit
01399 
01400                 #ifdef TEST_MEMORY_MANAGER
01401                 log("[D] EXIT : m_reallocator()");
01402                 #endif
01403 
01404                 return au->reportedAddress;
01405         }
01406         catch(const char *err)
01407         {
01408                 // Deal with the errors
01409 
01410                 log("[!] %s", err);
01411                 resetGlobals();
01412 
01413                 #ifdef TEST_MEMORY_MANAGER
01414                 log("[D] EXIT : m_reallocator()");
01415                 #endif
01416 
01417                 return NULL;
01418         }
01419 }
01420 
01421 // ---------------------------------------------------------------------------------------------------------------------------------
01422 // Deallocate memory and track it
01423 // ---------------------------------------------------------------------------------------------------------------------------------
01424 
01425 void    m_deallocator(const char *sourceFile, const unsigned int sourceLine, const char *sourceFunc, const unsigned int deallocationType, const void *reportedAddress)
01426 {
01427         try
01428         {
01429                 #ifdef TEST_MEMORY_MANAGER
01430                 log("[D] ENTER: m_deallocator()");
01431                 #endif
01432 
01433                 // Log the request
01434 
01435                 if (alwaysLogAll) log("[-] ----- %8s of addr 0x%08X           by %s", allocationTypes[deallocationType], reinterpret_cast<unsigned int>(const_cast<void *>(reportedAddress)), ownerString(sourceFile, sourceLine, sourceFunc));
01436 
01437                 // 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
01438                 // both bail before they get here.) So, since ANSI allows free(NULL), we'll not bother trying to actually free the allocated
01439                 // memory or track it any further.
01440 
01441                 if (reportedAddress)
01442                 {
01443                         // Go get the allocation unit
01444 
01445                         sAllocUnit      *au = findAllocUnit(reportedAddress);
01446 
01447                         // If you hit this assert, you tried to deallocate RAM that wasn't allocated by this memory manager.
01448                         m_assert(au != NULL);
01449                         if (au == NULL) throw "Request to deallocate RAM that was never allocated";
01450 
01451                         // If you hit this assert, then the allocation unit that is about to be deallocated is damaged. But you probably
01452                         // already know that from a previous assert you should have seen in validateAllocUnit() :)
01453                         m_assert(m_validateAllocUnit(au));
01454 
01455                         // If you hit this assert, then this deallocation was made from a source that isn't setup to use this memory
01456                         // tracking software, use the stack frame to locate the source and include our H file.
01457                         m_assert(deallocationType != m_alloc_unknown);
01458 
01459                         // If you hit this assert, you were trying to deallocate RAM that was not allocated in a way that is compatible with
01460                         // the deallocation method requested. In other words, you have a allocation/deallocation mismatch.
01461                         m_assert((deallocationType == m_alloc_delete       && au->allocationType == m_alloc_new      ) ||
01462                                 (deallocationType == m_alloc_delete_array && au->allocationType == m_alloc_new_array) ||
01463                                 (deallocationType == m_alloc_free         && au->allocationType == m_alloc_malloc   ) ||
01464                                 (deallocationType == m_alloc_free         && au->allocationType == m_alloc_calloc   ) ||
01465                                 (deallocationType == m_alloc_free         && au->allocationType == m_alloc_realloc  ) ||
01466                                 (deallocationType == m_alloc_unknown                                                ) );
01467 
01468                         // If you hit this assert, then the "break on dealloc" flag for this allocation unit is set. Interrogate the 'au'
01469                         // variable to determine information about this allocation unit.
01470                         m_assert(au->breakOnDealloc == false);
01471 
01472                         // Wipe the deallocated RAM with a new pattern. This doen't actually do us much good in debug mode under WIN32,
01473                         // because Microsoft's memory debugging & tracking utilities will wipe it right after we do. Oh well.
01474 
01475                         wipeWithPattern(au, releasedPattern);
01476 
01477                         // Do the deallocation
01478 
01479                         free(au->actualAddress);
01480 
01481                         // Remove this allocation unit from the hash table
01482 
01483                         unsigned int    hashIndex = (reinterpret_cast<unsigned int>(au->reportedAddress) >> 4) & (hashSize - 1);
01484                         if (hashTable[hashIndex] == au)
01485                         {
01486                                 hashTable[hashIndex] = au->next;
01487                         }
01488                         else
01489                         {
01490                                 if (au->prev)   au->prev->next = au->next;
01491                                 if (au->next)   au->next->prev = au->prev;
01492                         }
01493 
01494                         // Remove this allocation from our stats
01495 
01496                         stats.totalReportedMemory -= static_cast<unsigned int>(au->reportedSize);
01497                         stats.totalActualMemory   -= static_cast<unsigned int>(au->actualSize);
01498                         stats.totalAllocUnitCount--;
01499 
01500                         // Add this allocation unit to the front of our reservoir of unused allocation units
01501 
01502                         memset(au, 0, sizeof(sAllocUnit));
01503                         au->next = reservoir;
01504                         reservoir = au;
01505                 }
01506 
01507                 // Resetting the globals insures that if at some later time, somebody calls our memory manager from an unknown
01508                 // source (i.e. they didn't include our H file) then we won't think it was the last allocation.
01509 
01510                 resetGlobals();
01511 
01512                 // Validate every single allocated unit in memory
01513 
01514                 if (alwaysValidateAll) m_validateAllAllocUnits();
01515 
01516                 // If we're in the midst of static deinitialization time, track any pending memory leaks
01517 
01518                 if (staticDeinitTime) dumpLeakReport();
01519         }
01520         catch(const char *err)
01521         {
01522                 // Deal with errors
01523 
01524                 log("[!] %s", err);
01525                 resetGlobals();
01526         }
01527 
01528         #ifdef TEST_MEMORY_MANAGER
01529         log("[D] EXIT : m_deallocator()");
01530         #endif
01531 }
01532 
01533 // ---------------------------------------------------------------------------------------------------------------------------------
01534 // -DOC- The following utilitarian allow you to become proactive in tracking your own memory, or help you narrow in on those tough
01535 // bugs.
01536 // ---------------------------------------------------------------------------------------------------------------------------------
01537 
01538 bool    m_validateAddress(const void *reportedAddress)
01539 {
01540         // Just see if the address exists in our allocation routines
01541 
01542         return findAllocUnit(reportedAddress) != NULL;
01543 }
01544 
01545 // ---------------------------------------------------------------------------------------------------------------------------------
01546 
01547 bool    m_validateAllocUnit(const sAllocUnit *allocUnit)
01548 {
01549         // Make sure the padding is untouched
01550 
01551         long    *pre = reinterpret_cast<long *>(allocUnit->actualAddress);
01552         long    *post = reinterpret_cast<long *>((char *)allocUnit->actualAddress + allocUnit->actualSize - paddingSize * sizeof(long));
01553         bool    errorFlag = false;
01554         for (unsigned int i = 0; i < paddingSize; i++, pre++, post++)
01555         {
01556                 if (*pre != (long) prefixPattern)
01557                 {
01558                         log("[!] A memory allocation unit was corrupt because of an underrun:");
01559                         m_dumpAllocUnit(allocUnit, "  ");
01560                         errorFlag = true;
01561                 }
01562 
01563                 // If you hit this assert, then you should know that this allocation unit has been damaged. Something (possibly the
01564                 // owner?) has underrun the allocation unit (modified a few bytes prior to the start). You can interrogate the
01565                 // variable 'allocUnit' to see statistics and information about this damaged allocation unit.
01566                 m_assert(*pre == static_cast<long>(prefixPattern));
01567 
01568                 if (*post != static_cast<long>(postfixPattern))
01569                 {
01570                         log("[!] A memory allocation unit was corrupt because of an overrun:");
01571                         m_dumpAllocUnit(allocUnit, "  ");
01572                         errorFlag = true;
01573                 }
01574 
01575                 // If you hit this assert, then you should know that this allocation unit has been damaged. Something (possibly the
01576                 // owner?) has overrun the allocation unit (modified a few bytes after the end). You can interrogate the variable
01577                 // 'allocUnit' to see statistics and information about this damaged allocation unit.
01578                 m_assert(*post == static_cast<long>(postfixPattern));
01579         }
01580 
01581         // Return the error status (we invert it, because a return of 'false' means error)
01582 
01583         return !errorFlag;
01584 }
01585 
01586 // ---------------------------------------------------------------------------------------------------------------------------------
01587 
01588 bool    m_validateAllAllocUnits()
01589 {
01590         // Just go through each allocation unit in the hash table and count the ones that have errors
01591 
01592         unsigned int    errors = 0;
01593         unsigned int    allocCount = 0;
01594         for (unsigned int i = 0; i < hashSize; i++)
01595         {
01596                 sAllocUnit      *ptr = hashTable[i];
01597                 while(ptr)
01598                 {
01599                         allocCount++;
01600                         if (!m_validateAllocUnit(ptr)) errors++;
01601                         ptr = ptr->next;
01602                 }
01603         }
01604 
01605         // Test for hash-table correctness
01606 
01607         if (allocCount != stats.totalAllocUnitCount)
01608         {
01609                 log("[!] Memory tracking hash table corrupt!");
01610                 errors++;
01611         }
01612 
01613         // If you hit this assert, then the internal memory (hash table) used by this memory tracking software is damaged! The
01614         // best way to track this down is to use the alwaysLogAll flag in conjunction with STRESS_TEST macro to narrow in on the
01615         // offending code. After running the application with these settings (and hitting this assert again), interrogate the
01616         // memory.log file to find the previous successful operation. The corruption will have occurred between that point and this
01617         // assertion.
01618         m_assert(allocCount == stats.totalAllocUnitCount);
01619 
01620         // If you hit this assert, then you've probably already been notified that there was a problem with a allocation unit in a
01621         // prior call to validateAllocUnit(), but this assert is here just to make sure you know about it. :)
01622         m_assert(errors == 0);
01623 
01624         // Log any errors
01625 
01626         if (errors) log("[!] While validting all allocation units, %d allocation unit(s) were found to have problems", errors);
01627 
01628         // Return the error status
01629 
01630         return errors != 0;
01631 }
01632 
01633 // ---------------------------------------------------------------------------------------------------------------------------------
01634 // -DOC- Unused RAM calculation routines. Use these to determine how much of your RAM is unused (in bytes)
01635 // ---------------------------------------------------------------------------------------------------------------------------------
01636 
01637 unsigned int    m_calcUnused(const sAllocUnit *allocUnit)
01638 {
01639         const unsigned long     *ptr = reinterpret_cast<const unsigned long *>(allocUnit->reportedAddress);
01640         unsigned int            count = 0;
01641 
01642         for (unsigned int i = 0; i < allocUnit->reportedSize; i += sizeof(long), ptr++)
01643         {
01644                 if (*ptr == unusedPattern) count += sizeof(long);
01645         }
01646 
01647         return count;
01648 }
01649 
01650 // ---------------------------------------------------------------------------------------------------------------------------------
01651 
01652 unsigned int    m_calcAllUnused()
01653 {
01654         // Just go through each allocation unit in the hash table and count the unused RAM
01655 
01656         unsigned int    total = 0;
01657         for (unsigned int i = 0; i < hashSize; i++)
01658         {
01659                 sAllocUnit      *ptr = hashTable[i];
01660                 while(ptr)
01661                 {
01662                         total += m_calcUnused(ptr);
01663                         ptr = ptr->next;
01664                 }
01665         }
01666 
01667         return total;
01668 }
01669 
01670 // ---------------------------------------------------------------------------------------------------------------------------------
01671 // -DOC- The following functions are for logging and statistics reporting.
01672 // ---------------------------------------------------------------------------------------------------------------------------------
01673 
01674 void    m_dumpAllocUnit(const sAllocUnit *allocUnit, const char *prefix)
01675 {
01676         log("[I] %sAddress (reported): %010p",       prefix, allocUnit->reportedAddress);
01677         log("[I] %sAddress (actual)  : %010p",       prefix, allocUnit->actualAddress);
01678         log("[I] %sSize (reported)   : 0x%08X (%s)", prefix, static_cast<unsigned int>(allocUnit->reportedSize), memorySizeString(static_cast<unsigned int>(allocUnit->reportedSize)));
01679         log("[I] %sSize (actual)     : 0x%08X (%s)", prefix, static_cast<unsigned int>(allocUnit->actualSize), memorySizeString(static_cast<unsigned int>(allocUnit->actualSize)));
01680         log("[I] %sOwner             : %s(%d)::%s",  prefix, allocUnit->sourceFile, allocUnit->sourceLine, allocUnit->sourceFunc);
01681         log("[I] %sAllocation type   : %s",          prefix, allocationTypes[allocUnit->allocationType]);
01682         log("[I] %sAllocation number : %d",          prefix, allocUnit->allocationNumber);
01683 }
01684 
01685 // ---------------------------------------------------------------------------------------------------------------------------------
01686 
01687 void    m_dumpMemoryReport(const char *filename, const bool overwrite)
01688 {
01689         // Open the report file
01690 
01691         FILE    *fp = NULL;
01692 
01693         if (overwrite)  fp = fopen(filename, "w+b");
01694         else            fp = fopen(filename, "ab");
01695 
01696         // If you hit this assert, then the memory report generator is unable to log information to a file (can't open the file for
01697         // some reason.)
01698         m_assert(fp);
01699         if (!fp) return;
01700 
01701         // Header
01702 
01703         static  char    timeString[25];
01704         memset(timeString, 0, sizeof(timeString));
01705         time_t  t = time(NULL);
01706         struct  tm *tme = localtime(&t);
01707         fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
01708         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);
01709         fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
01710         fprintf(fp, "\r\n");
01711         fprintf(fp, "\r\n");
01712 
01713         // Report summary
01714 
01715         fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
01716         fprintf(fp, "|                                                           T O T A L S                                                            |\r\n");
01717         fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
01718         fprintf(fp, "              Allocation unit count: %10s\r\n", insertCommas(stats.totalAllocUnitCount));
01719         fprintf(fp, "            Reported to application: %s\r\n", memorySizeString(stats.totalReportedMemory));
01720         fprintf(fp, "         Actual total memory in use: %s\r\n", memorySizeString(stats.totalActualMemory));
01721         fprintf(fp, "           Memory tracking overhead: %s\r\n", memorySizeString(stats.totalActualMemory - stats.totalReportedMemory));
01722         fprintf(fp, "\r\n");
01723 
01724         fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
01725         fprintf(fp, "|                                                            P E A K S                                                             |\r\n");
01726         fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
01727         fprintf(fp, "              Allocation unit count: %10s\r\n", insertCommas(stats.peakAllocUnitCount));
01728         fprintf(fp, "            Reported to application: %s\r\n", memorySizeString(stats.peakReportedMemory));
01729         fprintf(fp, "                             Actual: %s\r\n", memorySizeString(stats.peakActualMemory));
01730         fprintf(fp, "           Memory tracking overhead: %s\r\n", memorySizeString(stats.peakActualMemory - stats.peakReportedMemory));
01731         fprintf(fp, "\r\n");
01732 
01733         fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
01734         fprintf(fp, "|                                                      A C C U M U L A T E D                                                       |\r\n");
01735         fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
01736         fprintf(fp, "              Allocation unit count: %s\r\n", memorySizeString(stats.accumulatedAllocUnitCount));
01737         fprintf(fp, "            Reported to application: %s\r\n", memorySizeString(stats.accumulatedReportedMemory));
01738         fprintf(fp, "                             Actual: %s\r\n", memorySizeString(stats.accumulatedActualMemory));
01739         fprintf(fp, "\r\n");
01740 
01741         fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
01742         fprintf(fp, "|                                                           U N U S E D                                                            |\r\n");
01743         fprintf(fp, " ---------------------------------------------------------------------------------------------------------------------------------- \r\n");
01744         fprintf(fp, "    Memory allocated but not in use: %s\r\n", memorySizeString(m_calcAllUnused()));
01745         fprintf(fp, "\r\n");
01746 
01747         dumpAllocations(fp);
01748 
01749         fclose(fp);
01750 }
01751 
01752 // ---------------------------------------------------------------------------------------------------------------------------------
01753 
01754 sMStats m_getMemoryStatistics()
01755 {
01756         return stats;
01757 }
01758 
01759 // ---------------------------------------------------------------------------------------------------------------------------------
01760 // mmgr.cpp - End of file
01761 // ---------------------------------------------------------------------------------------------------------------------------------
 All Classes Namespaces Functions Variables Enumerations

Generated on Sat Feb 20 22:55:09 2010 for cAudio by  doxygen 1.6.2