00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015
00016
00017
00018
00019
00020
00021
00022
00023
00024
00025
00026
00027
00028
00029
00030
00031
00032
00033
00034
00035
00036
00037
00038
00039
00040
00041
00042
00043
00044
00045
00046
00047
00048
00049
00050
00051
00052
00053
00054
00055
00056
00057
00058
00059
00060
00061
00062
00063
00064
00065
00066
00067
00068
00069
00070
00071
00072
00073
00074
00075
00076
00077
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
00098
00099
00100
00101
00102
00103
00104
00105
00106
00107
00108
00109
00110
00111
00112
00113
00114
00115
00116
00117
00118
00119
00120
00121
00122
00123
00124
00125
00126
00127
00128
00129
00130
00131
00132
00133
00134
00135
00136
00137
00138
00139
00140
00141
00142
00143
00144
00145
00146
00147
00148
00149
00150
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;
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
00173
00174
00175
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
00197
00198
00199
00200 #undef new
00201 #undef delete
00202 #undef malloc
00203 #undef calloc
00204 #undef realloc
00205 #undef free
00206
00207
00208
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
00223
00224
00225 static unsigned int prefixPattern = 0xbaadf00d;
00226 static unsigned int postfixPattern = 0xdeadc0de;
00227 static unsigned int unusedPattern = 0xfeedface;
00228 static unsigned int releasedPattern = 0xdeadbeef;
00229
00230
00231
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
00255
00256
00257
00258 static void log(const char *format, ...)
00259 {
00260 #ifdef CAUDIO_USE_MMGR
00261
00262
00263 if (cleanupLogOnFirstRun) doCleanupLogOnFirstRun();
00264
00265
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
00274
00275 FILE *fp = fopen(memoryLogFile, "ab");
00276
00277
00278
00279 m_assert(fp);
00280
00281 if (!fp) return;
00282
00283
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
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
00398 m_assert(reportedAddress != NULL);
00399
00400
00401
00402
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
00420
00421
00422
00423 return reportedSize + paddingSize * sizeof(long) * 2;
00424 }
00425
00426
00427
00428 static size_t calculateReportedSize(const size_t actualSize)
00429 {
00430
00431
00432
00433
00434 return actualSize - paddingSize * sizeof(long) * 2;
00435 }
00436
00437
00438
00439 static void *calculateReportedAddress(const void *actualAddress)
00440 {
00441
00442
00443 if (!actualAddress) return NULL;
00444
00445
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
00455
00456
00457
00458
00459 if (randomWipe)
00460 {
00461 pattern = ((rand() & 0xff) << 24) | ((rand() & 0xff) << 16) | ((rand() & 0xff) << 8) | (rand() & 0xff);
00462 }
00463
00464
00465
00466
00467
00468
00469
00470
00471
00472
00473 if (alwaysWipeAll && allocUnit->reportedSize > originalReportedSize)
00474 {
00475
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
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
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
00540
00541 FILE *fp = fopen(memoryLeakLogFile, "w+b");
00542
00543
00544
00545 m_assert(fp);
00546 if (!fp) return;
00547
00548
00549
00550
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
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
00596
00597
00598 class MemStaticTimeTracker
00599 {
00600 public:
00601 MemStaticTimeTracker() {doCleanupLogOnFirstRun();}
00602 ~MemStaticTimeTracker() {staticDeinitTime = true; dumpLeakReport();}
00603 };
00604 static MemStaticTimeTracker mstt;
00605
00606
00607
00608
00609
00610 bool &m_alwaysValidateAll()
00611 {
00612
00613 return alwaysValidateAll;
00614 }
00615
00616
00617
00618 bool &m_alwaysLogAll()
00619 {
00620
00621 return alwaysLogAll;
00622 }
00623
00624
00625
00626 bool &m_alwaysWipeAll()
00627 {
00628
00629 return alwaysWipeAll;
00630 }
00631
00632
00633
00634 bool &m_randomeWipe()
00635 {
00636
00637 return randomWipe;
00638 }
00639
00640
00641
00642
00643
00644
00645 bool &m_breakOnRealloc(void *reportedAddress)
00646 {
00647
00648
00649 sAllocUnit *au = findAllocUnit(reportedAddress);
00650
00651
00652
00653 m_assert(au != NULL);
00654
00655
00656
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
00666
00667
00668
00669 bool &m_breakOnDealloc(void *reportedAddress)
00670 {
00671
00672
00673 sAllocUnit *au = findAllocUnit(reportedAddress);
00674
00675
00676
00677 m_assert(au != NULL);
00678
00679 return au->breakOnDealloc;
00680 }
00681
00682
00683
00684
00685
00686 void m_breakOnAllocation(unsigned int count)
00687 {
00688 breakOnAllocationCount = count;
00689 }
00690
00691
00692
00693
00694
00695 void m_setOwner(const char *file, const unsigned int line, const char *func)
00696 {
00697
00698
00699
00700
00701
00702
00703
00704
00705
00706
00707
00708
00709
00710
00711
00712
00713
00714
00715
00716
00717
00718
00719
00720
00721
00722
00723
00724
00725
00726
00727
00728
00729
00730
00731
00732
00733
00734
00735
00736
00737
00738
00739 if (sourceLine && alwaysLogAll)
00740 {
00741 log("[I] NOTE! Possible destructor chain: previous owner is %s", ownerString(sourceFile, sourceLine, sourceFunc));
00742 }
00743
00744
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
00762
00763
00764
00765
00766
00767 void *operator new(size_t reportedSize)
00768 {
00769 #ifdef TEST_MEMORY_MANAGER
00770 log("[D] ENTER: new");
00771 #endif
00772
00773
00774
00775 const char *file = sourceFile;
00776 const unsigned int line = sourceLine;
00777 const char *func = sourceFunc;
00778
00779
00780
00781 if (reportedSize == 0) reportedSize = 1;
00782
00783
00784
00785 for(;;)
00786 {
00787
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
00799
00800
00801 std::new_handler nh = std::set_new_handler(0);
00802 std::set_new_handler(nh);
00803
00804
00805
00806 if (nh)
00807 {
00808 (*nh)();
00809 }
00810
00811
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
00832
00833 const char *file = sourceFile;
00834 const unsigned int line = sourceLine;
00835 const char *func = sourceFunc;
00836
00837
00838
00839 if (reportedSize == 0) reportedSize = 1;
00840
00841
00842
00843 for(;;)
00844 {
00845
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
00857
00858
00859 std::new_handler nh = std::set_new_handler(0);
00860 std::set_new_handler(nh);
00861
00862
00863
00864 if (nh)
00865 {
00866 (*nh)();
00867 }
00868
00869
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
00883
00884
00885
00886
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
00896
00897 if (reportedSize == 0) reportedSize = 1;
00898
00899
00900
00901 for(;;)
00902 {
00903
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
00915
00916
00917 std::new_handler nh = std::set_new_handler(0);
00918 std::set_new_handler(nh);
00919
00920
00921
00922 if (nh)
00923 {
00924 (*nh)();
00925 }
00926
00927
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
00948
00949 if (reportedSize == 0) reportedSize = 1;
00950
00951
00952
00953 for(;;)
00954 {
00955
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
00967
00968
00969 std::new_handler nh = std::set_new_handler(0);
00970 std::set_new_handler(nh);
00971
00972
00973
00974 if (nh)
00975 {
00976 (*nh)();
00977 }
00978
00979
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
00993
00994
00995
00996
00997
00998 void operator delete(void *reportedAddress)
00999 {
01000 #ifdef TEST_MEMORY_MANAGER
01001 log("[D] ENTER: delete");
01002 #endif
01003
01004
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
01010
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
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
01034
01035
01036 resetGlobals();
01037
01038 #ifdef TEST_MEMORY_MANAGER
01039 log("[D] EXIT : delete[]");
01040 #endif
01041 }
01042
01043
01044
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
01056
01057 currentAllocationCount++;
01058
01059
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
01064 m_assert(currentAllocationCount != breakOnAllocationCount);
01065
01066
01067
01068 if (!reservoir)
01069 {
01070
01071
01072 reservoir = (sAllocUnit *) malloc(sizeof(sAllocUnit) * 256);
01073
01074
01075
01076 m_assert(reservoir != NULL);
01077
01078
01079
01080 if (reservoir == NULL) throw "Unable to allocate RAM for internal memory tracking data";
01081
01082
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
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
01102 m_assert(reservoir != NULL);
01103
01104
01105
01106 sAllocUnit *au = reservoir;
01107 reservoir = au->next;
01108
01109
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
01139
01140 #ifndef RANDOM_FAILURE
01141
01142
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
01152
01153 m_assert(allocationType != m_alloc_unknown);
01154
01155
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
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
01176
01177 wipeWithPattern(au, unusedPattern);
01178
01179
01180
01181 if (allocationType == m_alloc_calloc)
01182 {
01183 memset(au->reportedAddress, 0, au->reportedSize);
01184 }
01185
01186
01187
01188 if (alwaysValidateAll) m_validateAllAllocUnits();
01189
01190
01191
01192 if (alwaysLogAll) log("[+] ----> addr 0x%08X", reinterpret_cast<unsigned int>(au->reportedAddress));
01193
01194
01195
01196
01197 resetGlobals();
01198
01199
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
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
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
01235
01236 if (!reportedAddress)
01237 {
01238 return m_allocator(sourceFile, sourceLine, sourceFunc, reallocationType, reportedSize);
01239 }
01240
01241
01242
01243 currentAllocationCount++;
01244
01245
01246 m_assert(currentAllocationCount != breakOnAllocationCount);
01247
01248
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
01253
01254 sAllocUnit *au = findAllocUnit(reportedAddress);
01255
01256
01257 m_assert(au != NULL);
01258 if (au == NULL) throw "Request to reallocate RAM that was never allocated";
01259
01260
01261
01262 m_assert(m_validateAllocUnit(au));
01263
01264
01265
01266 m_assert(reallocationType != m_alloc_unknown);
01267
01268
01269
01270 m_assert(au->allocationType == m_alloc_malloc ||
01271 au->allocationType == m_alloc_calloc ||
01272 au->allocationType == m_alloc_realloc);
01273
01274
01275
01276
01277 m_assert(au->breakOnRealloc == false);
01278
01279
01280
01281 unsigned int originalReportedSize = static_cast<unsigned int>(au->reportedSize);
01282
01283 if (alwaysLogAll) log("[~] ----> from 0x%08X(%08d)", originalReportedSize, originalReportedSize);
01284
01285
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
01306
01307 #ifndef RANDOM_FAILURE
01308
01309
01310
01311 m_assert(newActualAddress);
01312 #endif
01313
01314 if (!newActualAddress) throw "Request for reallocation failed. Out of memory.";
01315
01316
01317
01318 stats.totalReportedMemory -= static_cast<unsigned int>(au->reportedSize);
01319 stats.totalActualMemory -= static_cast<unsigned int>(au->actualSize);
01320
01321
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
01336
01337 unsigned int hashIndex = static_cast<unsigned int>(-1);
01338 if (oldReportedAddress != au->reportedAddress)
01339 {
01340
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
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
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
01378
01379 wipeWithPattern(au, unusedPattern, originalReportedSize);
01380
01381
01382
01383 m_assert(m_validateAllocUnit(au));
01384
01385
01386
01387 if (alwaysValidateAll) m_validateAllAllocUnits();
01388
01389
01390
01391 if (alwaysLogAll) log("[~] ----> addr 0x%08X", reinterpret_cast<unsigned int>(au->reportedAddress));
01392
01393
01394
01395
01396 resetGlobals();
01397
01398
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
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
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
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
01438
01439
01440
01441 if (reportedAddress)
01442 {
01443
01444
01445 sAllocUnit *au = findAllocUnit(reportedAddress);
01446
01447
01448 m_assert(au != NULL);
01449 if (au == NULL) throw "Request to deallocate RAM that was never allocated";
01450
01451
01452
01453 m_assert(m_validateAllocUnit(au));
01454
01455
01456
01457 m_assert(deallocationType != m_alloc_unknown);
01458
01459
01460
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
01469
01470 m_assert(au->breakOnDealloc == false);
01471
01472
01473
01474
01475 wipeWithPattern(au, releasedPattern);
01476
01477
01478
01479 free(au->actualAddress);
01480
01481
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
01495
01496 stats.totalReportedMemory -= static_cast<unsigned int>(au->reportedSize);
01497 stats.totalActualMemory -= static_cast<unsigned int>(au->actualSize);
01498 stats.totalAllocUnitCount--;
01499
01500
01501
01502 memset(au, 0, sizeof(sAllocUnit));
01503 au->next = reservoir;
01504 reservoir = au;
01505 }
01506
01507
01508
01509
01510 resetGlobals();
01511
01512
01513
01514 if (alwaysValidateAll) m_validateAllAllocUnits();
01515
01516
01517
01518 if (staticDeinitTime) dumpLeakReport();
01519 }
01520 catch(const char *err)
01521 {
01522
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
01535
01536
01537
01538 bool m_validateAddress(const void *reportedAddress)
01539 {
01540
01541
01542 return findAllocUnit(reportedAddress) != NULL;
01543 }
01544
01545
01546
01547 bool m_validateAllocUnit(const sAllocUnit *allocUnit)
01548 {
01549
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
01564
01565
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
01576
01577
01578 m_assert(*post == static_cast<long>(postfixPattern));
01579 }
01580
01581
01582
01583 return !errorFlag;
01584 }
01585
01586
01587
01588 bool m_validateAllAllocUnits()
01589 {
01590
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
01606
01607 if (allocCount != stats.totalAllocUnitCount)
01608 {
01609 log("[!] Memory tracking hash table corrupt!");
01610 errors++;
01611 }
01612
01613
01614
01615
01616
01617
01618 m_assert(allocCount == stats.totalAllocUnitCount);
01619
01620
01621
01622 m_assert(errors == 0);
01623
01624
01625
01626 if (errors) log("[!] While validting all allocation units, %d allocation unit(s) were found to have problems", errors);
01627
01628
01629
01630 return errors != 0;
01631 }
01632
01633
01634
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
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
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
01690
01691 FILE *fp = NULL;
01692
01693 if (overwrite) fp = fopen(filename, "w+b");
01694 else fp = fopen(filename, "ab");
01695
01696
01697
01698 m_assert(fp);
01699 if (!fp) return;
01700
01701
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
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
01761